diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/.github/tests_checker.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/.github/tests_checker.yml new file mode 100644 index 0000000000000000000000000000000000000000..769469b2ab26d4ee6ed08df8d5747abff384b43f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/.github/tests_checker.yml @@ -0,0 +1,8 @@ +comment: | + Hello! Thank you for contributing! + It appears that you have changed the code, but the tests that verify your change are missing. Could you please add them? +fileExtensions: + - '.ts' + - '.js' + +testDir: 'test' \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/.github/workflows/ci.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..d373acea174e183db5e10e28adc2e84026a7e6a7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/.github/workflows/ci.yml @@ -0,0 +1,26 @@ +name: CI + +on: + push: + branches: + - main + - master + - next + - 'v*' + paths-ignore: + - 'docs/**' + - '*.md' + pull_request: + paths-ignore: + - 'docs/**' + - '*.md' + +env: + TZ: 'UTC' + +jobs: + test: + uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5 + with: + lint: true + license-check: true diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/lib/default-ajv-options.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/lib/default-ajv-options.js new file mode 100644 index 0000000000000000000000000000000000000000..57c1fd8bb5fa2bfe988efdb66343fbadcad74fda --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/lib/default-ajv-options.js @@ -0,0 +1,14 @@ +'use strict' + +const fastUri = require('fast-uri') + +module.exports = Object.freeze({ + coerceTypes: 'array', + useDefaults: true, + removeAdditional: true, + uriResolver: fastUri, + addUsedSchema: false, + // Explicitly set allErrors to `false`. + // When set to `true`, a DoS attack is possible. + allErrors: false +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/lib/serializer-compiler.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/lib/serializer-compiler.js new file mode 100644 index 0000000000000000000000000000000000000000..4b54f3e758e75629a6daa38b2facb144203111f7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/lib/serializer-compiler.js @@ -0,0 +1,27 @@ +'use strict' + +const AjvJTD = require('ajv/dist/jtd') + +const defaultAjvOptions = require('./default-ajv-options') + +class SerializerCompiler { + constructor (_externalSchemas, options) { + this.ajv = new AjvJTD(Object.assign({}, defaultAjvOptions, options)) + + /** + * https://ajv.js.org/json-type-definition.html#ref-form + * Unlike JSON Schema, JTD does not allow to reference: + * - any schema fragment other than root level definitions member + * - root of the schema - there is another way to define a self-recursive schema (see Example 2) + * - another schema file (but you can still combine schemas from multiple files using JavaScript). + * + * So we ignore the externalSchemas parameter. + */ + } + + buildSerializerFunction ({ schema/*, method, url, httpStatus */ }) { + return this.ajv.compileSerializer(schema) + } +} + +module.exports = SerializerCompiler diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/lib/validator-compiler.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/lib/validator-compiler.js new file mode 100644 index 0000000000000000000000000000000000000000..890d004122513abced6b3a10a8ff551b3fbc6a03 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/lib/validator-compiler.js @@ -0,0 +1,58 @@ +'use strict' + +const Ajv = require('ajv').default +const AjvJTD = require('ajv/dist/jtd') + +const defaultAjvOptions = require('./default-ajv-options') + +class ValidatorCompiler { + constructor (externalSchemas, options) { + // This instance of Ajv is private + // it should not be customized or used + if (options.mode === 'JTD') { + this.ajv = new AjvJTD(Object.assign({}, defaultAjvOptions, options.customOptions)) + } else { + this.ajv = new Ajv(Object.assign({}, defaultAjvOptions, options.customOptions)) + } + + let addFormatPlugin = true + if (options.plugins && options.plugins.length > 0) { + for (const plugin of options.plugins) { + if (Array.isArray(plugin)) { + addFormatPlugin = addFormatPlugin && plugin[0].name !== 'formatsPlugin' + plugin[0](this.ajv, plugin[1]) + } else { + addFormatPlugin = addFormatPlugin && plugin.name !== 'formatsPlugin' + plugin(this.ajv) + } + } + } + + if (addFormatPlugin) { + require('ajv-formats')(this.ajv) + } + + options.onCreate?.(this.ajv) + + const sourceSchemas = Object.values(externalSchemas) + for (const extSchema of sourceSchemas) { + this.ajv.addSchema(extSchema) + } + } + + buildValidatorFunction ({ schema/*, method, url, httpPart */ }) { + // Ajv does not support compiling two schemas with the same + // id inside the same instance. Therefore if we have already + // compiled the schema with the given id, we just return it. + if (schema.$id) { + const stored = this.ajv.getSchema(schema.$id) + if (stored) { + return stored + } + } + + return this.ajv.compile(schema) + } +} + +module.exports = ValidatorCompiler diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/test/.gitkeep b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/test/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/test/duplicated-id-compile.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/test/duplicated-id-compile.test.js new file mode 100644 index 0000000000000000000000000000000000000000..849016c6c01cf92d8f65f0aa9501745dadbc684a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/test/duplicated-id-compile.test.js @@ -0,0 +1,59 @@ +'use strict' + +const t = require('tap') +const AjvCompiler = require('../index') + +const postSchema = Object.freeze({ + $schema: 'http://json-schema.org/draft-07/schema#', + type: 'object', + $id: 'http://mydomain.com/user', + title: 'User schema', + description: 'Contains all user fields', + properties: { + username: { type: 'string', minLength: 4 }, + firstName: { type: 'string', minLength: 1 }, + lastName: { type: 'string', minLength: 1 }, + email: { type: 'string' }, + password: { type: 'string', minLength: 6 }, + bio: { type: 'string' } + }, + required: ['username', 'firstName', 'lastName', 'email', 'bio', 'password'] +}) + +const patchSchema = Object.freeze({ + $schema: 'http://json-schema.org/draft-07/schema#', + type: 'object', + $id: 'http://mydomain.com/user', + title: 'User schema', + description: 'Contains all user fields', + properties: { + firstName: { type: 'string', minLength: 1 }, + lastName: { type: 'string', minLength: 1 }, + bio: { type: 'string' } + } +}) + +const fastifyAjvOptionsDefault = Object.freeze({ + customOptions: {} +}) + +t.test('must not store schema on compile', t => { + t.plan(4) + const factory = AjvCompiler() + const compiler = factory({}, fastifyAjvOptionsDefault) + const postFn = compiler({ schema: postSchema }) + const patchFn = compiler({ schema: patchSchema }) + + const resultForPost = postFn({}) + t.equal(resultForPost, false) + t.has(postFn.errors, [ + { + keyword: 'required', + message: "must have required property 'username'" + } + ]) + + const resultForPatch = patchFn({}) + t.ok(resultForPatch) + t.notOk(patchFn.errors) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/test/index.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/test/index.test.js new file mode 100644 index 0000000000000000000000000000000000000000..fe1427ce81877b16d7407d91ac4c5f40d2e02868 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/test/index.test.js @@ -0,0 +1,307 @@ +'use strict' + +const t = require('tap') +const fastify = require('fastify') +const AjvCompiler = require('../index') + +const sym = Symbol.for('fastify.ajv-compiler.reference') + +const sampleSchema = Object.freeze({ + $id: 'example1', + type: 'object', + properties: { + name: { type: 'string' } + } +}) + +const externalSchemas1 = Object.freeze({}) +const externalSchemas2 = Object.freeze({ + foo: { + $id: 'foo', + type: 'object', + properties: { + name: { type: 'string' } + } + } +}) + +const fastifyAjvOptionsDefault = Object.freeze({ + customOptions: {} +}) + +const fastifyJtdDefault = Object.freeze({ + customOptions: { }, + mode: 'JTD' +}) + +const fastifyAjvOptionsCustom = Object.freeze({ + customOptions: { + allErrors: true, + removeAdditional: false + }, + plugins: [ + require('ajv-formats'), + [require('ajv-errors'), { singleError: false }] + ] +}) + +t.test('basic usage', t => { + t.plan(1) + const factory = AjvCompiler() + const compiler = factory(externalSchemas1, fastifyAjvOptionsDefault) + const validatorFunc = compiler({ schema: sampleSchema }) + const result = validatorFunc({ name: 'hello' }) + t.equal(result, true) +}) + +t.test('array coercion', t => { + t.plan(2) + const factory = AjvCompiler() + const compiler = factory(externalSchemas1, fastifyAjvOptionsDefault) + + const arraySchema = { + $id: 'example1', + type: 'object', + properties: { + name: { type: 'array', items: { type: 'string' } } + } + } + + const validatorFunc = compiler({ schema: arraySchema }) + + const inputObj = { name: 'hello' } + t.equal(validatorFunc(inputObj), true) + t.same(inputObj, { name: ['hello'] }, 'the name property should be coerced to an array') +}) + +t.test('nullable default', t => { + t.plan(2) + const factory = AjvCompiler() + const compiler = factory({}, fastifyAjvOptionsDefault) + const validatorFunc = compiler({ + schema: { + type: 'object', + properties: { + nullable: { type: 'string', nullable: true }, + notNullable: { type: 'string' } + } + } + }) + const input = { nullable: null, notNullable: null } + const result = validatorFunc(input) + t.equal(result, true) + t.same(input, { nullable: null, notNullable: '' }, 'the notNullable field has been coerced') +}) + +t.test('plugin loading', t => { + t.plan(3) + const factory = AjvCompiler() + const compiler = factory(externalSchemas1, fastifyAjvOptionsCustom) + const validatorFunc = compiler({ + schema: { + type: 'object', + properties: { + q: { + type: 'string', + format: 'date', + formatMinimum: '2016-02-06', + formatExclusiveMaximum: '2016-12-27' + } + }, + required: ['q'], + errorMessage: 'hello world' + } + }) + const result = validatorFunc({ q: '2016-10-02' }) + t.equal(result, true) + + const resultFail = validatorFunc({}) + t.equal(resultFail, false) + t.equal(validatorFunc.errors[0].message, 'hello world') +}) + +t.test('optimization - cache ajv instance', t => { + t.plan(5) + const factory = AjvCompiler() + const compiler1 = factory(externalSchemas1, fastifyAjvOptionsDefault) + const compiler2 = factory(externalSchemas1, fastifyAjvOptionsDefault) + t.equal(compiler1, compiler2, 'same instance') + t.same(compiler1, compiler2, 'same instance') + + const compiler3 = factory(externalSchemas2, fastifyAjvOptionsDefault) + t.not(compiler3, compiler1, 'new ajv instance when externa schema change') + + const compiler4 = factory(externalSchemas1, fastifyAjvOptionsCustom) + t.not(compiler4, compiler1, 'new ajv instance when externa schema change') + t.not(compiler4, compiler3, 'new ajv instance when externa schema change') +}) + +t.test('the onCreate callback can enhance the ajv instance', t => { + t.plan(2) + const factory = AjvCompiler() + + const fastifyAjvCustomOptionsFormats = Object.freeze({ + onCreate (ajv) { + for (const [formatName, format] of Object.entries(this.customOptions.formats)) { + ajv.addFormat(formatName, format) + } + }, + customOptions: { + formats: { + date: /foo/ + } + } + }) + + const compiler1 = factory(externalSchemas1, fastifyAjvCustomOptionsFormats) + const validatorFunc = compiler1({ + schema: { + type: 'string', + format: 'date' + } + }) + const result = validatorFunc('foo') + t.equal(result, true) + + const resultFail = validatorFunc('2016-10-02') + t.equal(resultFail, false) +}) + +// https://github.com/fastify/fastify/pull/2969 +t.test('compile same $id when in external schema', t => { + t.plan(3) + const factory = AjvCompiler() + + const base = { + $id: 'urn:schema:base', + definitions: { + hello: { type: 'string' } + }, + type: 'object', + properties: { + hello: { $ref: '#/definitions/hello' } + } + } + + const refSchema = { + $id: 'urn:schema:ref', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:base#/definitions/hello' } + } + } + + const compiler = factory({ + [base.$id]: base, + [refSchema.$id]: refSchema + + }, fastifyAjvOptionsDefault) + + t.notOk(compiler[sym], 'the ajv reference do not exists if code is not activated') + + const validatorFunc1 = compiler({ + schema: { + $id: 'urn:schema:ref' + } + }) + + const validatorFunc2 = compiler({ + schema: { + $id: 'urn:schema:ref' + } + }) + + t.pass('the compile does not fail if the schema compiled is already in the external schemas') + t.equal(validatorFunc1, validatorFunc2, 'the returned function is the same') +}) + +t.test('JTD MODE', t => { + t.plan(2) + + t.test('compile jtd schema', t => { + t.plan(4) + const factory = AjvCompiler() + + const jtdSchema = { + discriminator: 'version', + mapping: { + 1: { + properties: { + foo: { type: 'uint8' } + } + }, + 2: { + properties: { + foo: { type: 'string' } + } + } + } + } + + const compiler = factory({}, fastifyJtdDefault) + const validatorFunc = compiler({ schema: jtdSchema }) + t.pass('generated validation function for JTD SCHEMA') + + const result = validatorFunc({ + version: '2', + foo: [] + }) + t.notOk(result, 'failed validation') + t.type(validatorFunc.errors, 'Array') + + const success = validatorFunc({ + version: '1', + foo: 42 + }) + t.ok(success) + }) + + t.test('fastify integration', async t => { + const factory = AjvCompiler() + + const app = fastify({ + jsonShorthand: false, + ajv: { + customOptions: { }, + mode: 'JTD' + }, + schemaController: { + compilersFactory: { + buildValidator: factory + } + } + }) + + app.post('/', { + schema: { + body: { + discriminator: 'version', + mapping: { + 1: { + properties: { + foo: { type: 'uint8' } + } + }, + 2: { + properties: { + foo: { type: 'string' } + } + } + } + } + } + }, () => {}) + + const res = await app.inject({ + url: '/', + method: 'POST', + payload: { + version: '1', + foo: 'this is not a number' + } + }) + + t.equal(res.statusCode, 400) + t.equal(res.json().message, 'body/foo must be uint8') + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/test/plugins.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/test/plugins.test.js new file mode 100644 index 0000000000000000000000000000000000000000..dacb0e893676ac713f48381cebfd380a3b1d3ef4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/test/plugins.test.js @@ -0,0 +1,264 @@ +'use strict' + +const t = require('tap') +const fastify = require('fastify') +const AjvCompiler = require('../index') + +const ajvFormats = require('ajv-formats') +const ajvErrors = require('ajv-errors') +const localize = require('ajv-i18n') + +t.test('Format Baseline test', async (t) => { + const app = buildApplication({ + customOptions: { + validateFormats: false + } + }) + + const res = await app.inject({ + url: '/hello', + headers: { + 'x-foo': 'hello', + 'x-date': 'not a date', + 'x-email': 'not an email' + }, + query: { + foo: 'hello', + date: 'not a date', + email: 'not an email' + } + }) + t.equal(res.statusCode, 200, 'format validation does not apply as configured') + t.equal(res.payload, 'hello') +}) + +t.test('Custom Format plugin loading test', (t) => { + t.plan(6) + const app = buildApplication({ + customOptions: { + validateFormats: true + }, + plugins: [[ajvFormats, { mode: 'fast' }]] + }) + + app.inject('/hello', (err, res) => { + t.error(err) + t.equal(res.statusCode, 400, 'format validation applies') + }) + + app.inject('/2ad0612c-7578-4b18-9a6f-579863f40e0b', (err, res) => { + t.error(err) + t.equal(res.statusCode, 400, 'format validation applies') + }) + + app.inject({ + url: '/2ad0612c-7578-4b18-9a6f-579863f40e0b', + headers: { + 'x-foo': 'hello', + 'x-date': new Date().toISOString(), + 'x-email': 'foo@bar.baz' + }, + query: { + foo: 'hello', + date: new Date().toISOString(), + email: 'foo@bar.baz' + } + }, (err, res) => { + t.error(err) + t.equal(res.statusCode, 200) + }) +}) + +t.test('Format plugin set by default test', (t) => { + t.plan(6) + const app = buildApplication({}) + + app.inject('/hello', (err, res) => { + t.error(err) + t.equal(res.statusCode, 400, 'format validation applies') + }) + + app.inject('/2ad0612c-7578-4b18-9a6f-579863f40e0b', (err, res) => { + t.error(err) + t.equal(res.statusCode, 400, 'format validation applies') + }) + + app.inject({ + url: '/2ad0612c-7578-4b18-9a6f-579863f40e0b', + headers: { + 'x-foo': 'hello', + 'x-date': new Date().toISOString(), + 'x-email': 'foo@bar.baz' + }, + query: { + foo: 'hello', + date: new Date().toISOString(), + email: 'foo@bar.baz' + } + }, (err, res) => { + t.error(err) + t.equal(res.statusCode, 200) + }) +}) + +t.test('Custom error messages', (t) => { + t.plan(9) + + const app = buildApplication({ + customOptions: { + removeAdditional: false, + allErrors: true + }, + plugins: [ajvFormats, ajvErrors] + }) + + const errorMessage = { + required: 'custom miss', + type: 'custom type', // will not replace internal "type" error for the property "foo" + _: 'custom type', // this prop will do it + additionalProperties: 'custom too many params' + } + + app.post('/', { + handler: () => { t.fail('dont call me') }, + schema: { + body: { + type: 'object', + required: ['foo'], + properties: { + foo: { type: 'integer' } + }, + additionalProperties: false, + errorMessage + } + } + }) + + app.inject({ + url: '/', + method: 'post', + payload: {} + }, (err, res) => { + t.error(err) + t.equal(res.statusCode, 400) + t.match(res.json().message, errorMessage.required) + }) + + app.inject({ + url: '/', + method: 'post', + payload: { foo: 'not a number' } + }, (err, res) => { + t.error(err) + t.equal(res.statusCode, 400) + t.match(res.json().message, errorMessage.type) + }) + + app.inject({ + url: '/', + method: 'post', + payload: { foo: 3, bar: 'ops' } + }, (err, res) => { + t.error(err) + t.equal(res.statusCode, 400) + t.match(res.json().message, errorMessage.additionalProperties) + }) +}) + +t.test('Custom i18n error messages', (t) => { + t.plan(3) + + const app = buildApplication({ + customOptions: { + allErrors: true, + messages: false + }, + plugins: [ajvFormats] + }) + + app.post('/', { + handler: () => { t.fail('dont call me') }, + schema: { + body: { + type: 'object', + required: ['foo'], + properties: { + foo: { type: 'integer' } + } + } + } + }) + + app.setErrorHandler((error, request, reply) => { + t.pass('Error handler executed') + if (error.validation) { + localize.ru(error.validation) + reply.status(400).send(error.validation) + return + } + t.fail('not other errors') + }) + + app.inject({ + method: 'POST', + url: '/', + payload: { + foo: 'string' + } + }, (err, res) => { + t.error(err) + t.equal(res.json()[0].message, 'должно быть integer') + }) +}) + +function buildApplication (ajvOptions) { + const factory = AjvCompiler() + + const app = fastify({ + ajv: ajvOptions, + schemaController: { + compilersFactory: { + buildValidator: factory + } + } + }) + + app.get('/:id', { + schema: { + headers: { + type: 'object', + required: [ + 'x-foo', + 'x-date', + 'x-email' + ], + properties: { + 'x-foo': { type: 'string' }, + 'x-date': { type: 'string', format: 'date-time' }, + 'x-email': { type: 'string', format: 'email' } + } + }, + query: { + type: 'object', + required: [ + 'foo', + 'date', + 'email' + ], + properties: { + foo: { type: 'string' }, + date: { type: 'string', format: 'date-time' }, + email: { type: 'string', format: 'email' } + } + }, + params: { + type: 'object', + properties: { + id: { type: 'string', format: 'uuid' } + } + } + } + }, async () => 'hello') + + return app +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/test/serialization.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/test/serialization.test.js new file mode 100644 index 0000000000000000000000000000000000000000..20821e0d1fc1a4849b9d0dfae98d7f38f8f81cdd --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/test/serialization.test.js @@ -0,0 +1,279 @@ +'use strict' + +const t = require('tap') +const fastify = require('fastify') +const AjvCompiler = require('../index') + +const jtdSchema = { + discriminator: 'version', + mapping: { + 1: { + properties: { + foo: { type: 'uint8' } + } + }, + 2: { + properties: { + foo: { type: 'string' } + } + } + } +} + +const externalSchemas1 = Object.freeze({}) +const externalSchemas2 = Object.freeze({ + foo: { + definitions: { + coordinates: { + properties: { + lat: { type: 'float32' }, + lng: { type: 'float32' } + } + } + } + } +}) + +const fastifyAjvOptionsDefault = Object.freeze({ + customOptions: {} +}) + +t.test('basic serializer usage', t => { + t.plan(4) + const factory = AjvCompiler({ jtdSerializer: true }) + const compiler = factory(externalSchemas1, fastifyAjvOptionsDefault) + const serializeFunc = compiler({ schema: jtdSchema }) + t.equal(serializeFunc({ version: '1', foo: 42 }), '{"version":"1","foo":42}') + t.equal(serializeFunc({ version: '2', foo: 'hello' }), '{"version":"2","foo":"hello"}') + t.equal(serializeFunc({ version: '3', foo: 'hello' }), '{"version":"3"}') + t.equal(serializeFunc({ version: '2', foo: ['not', 1, { string: 'string' }] }), '{"version":"2","foo":"not,1,[object Object]"}') +}) + +t.test('external schemas are ignored', t => { + t.plan(1) + const factory = AjvCompiler({ jtdSerializer: true }) + const compiler = factory(externalSchemas2, fastifyAjvOptionsDefault) + const serializeFunc = compiler({ + schema: { + definitions: { + coordinates: { + properties: { + lat: { type: 'float32' }, + lng: { type: 'float32' } + } + } + }, + properties: { + userLoc: { ref: 'coordinates' }, + serverLoc: { ref: 'coordinates' } + } + } + }) + t.equal(serializeFunc( + { userLoc: { lat: 50, lng: -90 }, serverLoc: { lat: -15, lng: 50 } }), + '{"userLoc":{"lat":50,"lng":-90},"serverLoc":{"lat":-15,"lng":50}}' + ) +}) + +t.test('fastify integration within JTD serializer', async t => { + const factoryValidator = AjvCompiler() + const factorySerializer = AjvCompiler({ jtdSerializer: true }) + + const app = fastify({ + jsonShorthand: false, + ajv: { + customOptions: { }, + mode: 'JTD' + }, + schemaController: { + compilersFactory: { + buildValidator: factoryValidator, + buildSerializer: factorySerializer + } + } + }) + + app.post('/', { + schema: { + body: jtdSchema, + response: { + 200: { + properties: { + id: { type: 'string' }, + createdAt: { type: 'timestamp' }, + karma: { type: 'int32' }, + isAdmin: { type: 'boolean' } + } + }, + 400: jtdSchema + } + } + }, async () => { + return { + id: '123', + createdAt: new Date('1999-01-31T23:00:00.000Z'), + karma: 42, + isAdmin: true, + remove: 'me' + } + }) + + { + const res = await app.inject({ + url: '/', + method: 'POST', + payload: { + version: '1', + foo: 'not a number' + } + }) + + t.equal(res.statusCode, 400) + t.same(res.json(), { version: 'undefined' }) + } + + { + const res = await app.inject({ + url: '/', + method: 'POST', + payload: { + version: '1', + foo: 32 + } + }) + + t.equal(res.statusCode, 200) + t.same(res.json(), { + id: '123', + createdAt: '1999-01-31T23:00:00.000Z', + karma: 42, + isAdmin: true + }) + } +}) + +t.test('fastify integration and cached serializer', async t => { + const factoryValidator = AjvCompiler() + const factorySerializer = AjvCompiler({ jtdSerializer: true }) + + const app = fastify({ + jsonShorthand: false, + ajv: { + customOptions: { }, + mode: 'JTD' + }, + schemaController: { + compilersFactory: { + buildValidator: factoryValidator, + buildSerializer: factorySerializer + } + } + }) + + app.register(async function plugin (app, opts) { + app.post('/', { + schema: { + body: jtdSchema, + response: { + 200: { + properties: { + id: { type: 'string' }, + createdAt: { type: 'timestamp' }, + karma: { type: 'int32' }, + isAdmin: { type: 'boolean' } + } + }, + 400: jtdSchema + } + } + }, async () => { + return { + id: '123', + createdAt: new Date('1999-01-31T23:00:00.000Z'), + karma: 42, + isAdmin: true, + remove: 'me' + } + }) + }) + + app.register(async function plugin (app, opts) { + app.post('/two', { + schema: { + body: jtdSchema, + response: { + 400: jtdSchema + } + } + }, () => {}) + }) + + { + const res = await app.inject({ + url: '/', + method: 'POST', + payload: { + version: '1', + foo: 'not a number' + } + }) + + t.equal(res.statusCode, 400) + t.same(res.json(), { version: 'undefined' }) + } + + { + const res = await app.inject({ + url: '/', + method: 'POST', + payload: { + version: '1', + foo: 32 + } + }) + + t.equal(res.statusCode, 200) + t.same(res.json(), { + id: '123', + createdAt: '1999-01-31T23:00:00.000Z', + karma: 42, + isAdmin: true + }) + } +}) + +t.test('fastify integration within JTD serializer and custom options', async t => { + const factorySerializer = AjvCompiler({ jtdSerializer: true }) + + const app = fastify({ + jsonShorthand: false, + serializerOpts: { + allErrors: true, + logger: 'wrong-value' + }, + schemaController: { + compilersFactory: { + buildSerializer: factorySerializer + } + } + }) + + app.post('/', { + schema: { + response: { + 200: { + properties: { + test: { type: 'boolean' } + } + } + } + } + }, async () => { }) + + try { + await app.ready() + t.fail('should throw') + } catch (error) { + t.equal(error.message, 'logger must implement log, warn and error methods', 'the wrong setting is forwarded to ajv/jtd') + } +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/test/standalone.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/test/standalone.test.js new file mode 100644 index 0000000000000000000000000000000000000000..f32fcbac727e99e073e9a4e369042b2cfde7db44 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/test/standalone.test.js @@ -0,0 +1,203 @@ +'use strict' + +const fs = require('node:fs') +const path = require('node:path') +const t = require('tap') +const fastify = require('fastify') +const sanitize = require('sanitize-filename') + +const { StandaloneValidator: AjvStandaloneValidator } = require('../') + +function generateFileName (routeOpts) { + return `/ajv-generated-${sanitize(routeOpts.schema.$id)}-${routeOpts.method}-${routeOpts.httpPart}-${sanitize(routeOpts.url)}.js` +} + +const generatedFileNames = [] + +t.test('standalone', t => { + t.plan(4) + + t.teardown(async () => { + for (const fileName of generatedFileNames) { + await fs.promises.unlink(path.join(__dirname, fileName)) + } + }) + + t.test('errors', t => { + t.plan(2) + t.throws(() => { + AjvStandaloneValidator() + }, 'missing restoreFunction') + t.throws(() => { + AjvStandaloneValidator({ readMode: false }) + }, 'missing storeFunction') + }) + + t.test('generate standalone code', t => { + t.plan(5) + + const base = { + $id: 'urn:schema:base', + definitions: { + hello: { type: 'string' } + }, + type: 'object', + properties: { + hello: { $ref: '#/definitions/hello' } + } + } + + const refSchema = { + $id: 'urn:schema:ref', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:base#/definitions/hello' } + } + } + + const endpointSchema = { + schema: { + $id: 'urn:schema:endpoint', + $ref: 'urn:schema:ref' + } + } + + const schemaMap = { + [base.$id]: base, + [refSchema.$id]: refSchema + } + + const factory = AjvStandaloneValidator({ + readMode: false, + storeFunction (routeOpts, schemaValidationCode) { + t.same(routeOpts, endpointSchema) + t.type(schemaValidationCode, 'string') + fs.writeFileSync(path.join(__dirname, '/ajv-generated.js'), schemaValidationCode) + generatedFileNames.push('/ajv-generated.js') + t.pass('stored the validation function') + } + }) + + const compiler = factory(schemaMap) + compiler(endpointSchema) + t.pass('compiled the endpoint schema') + + t.test('usage standalone code', t => { + t.plan(3) + const standaloneValidate = require('./ajv-generated') + + const valid = standaloneValidate({ hello: 'world' }) + t.ok(valid) + + const invalid = standaloneValidate({ hello: [] }) + t.notOk(invalid) + + t.ok(standaloneValidate) + }) + }) + + t.test('fastify integration - writeMode', async t => { + t.plan(6) + + const factory = AjvStandaloneValidator({ + readMode: false, + storeFunction (routeOpts, schemaValidationCode) { + const fileName = generateFileName(routeOpts) + t.ok(routeOpts) + fs.writeFileSync(path.join(__dirname, fileName), schemaValidationCode) + t.pass('stored the validation function') + generatedFileNames.push(fileName) + }, + restoreFunction () { + t.fail('write mode ON') + } + }) + + const app = buildApp(factory) + await app.ready() + }) + + t.test('fastify integration - readMode', async t => { + t.plan(6) + + const factory = AjvStandaloneValidator({ + readMode: true, + storeFunction () { + t.fail('read mode ON') + }, + restoreFunction (routeOpts) { + t.pass('restore the validation function') + const fileName = generateFileName(routeOpts) + return require(path.join(__dirname, fileName)) + } + }) + + const app = buildApp(factory) + await app.ready() + + let res = await app.inject({ + url: '/foo', + method: 'POST', + payload: { hello: [] } + }) + t.equal(res.statusCode, 400) + + res = await app.inject({ + url: '/bar?lang=invalid', + method: 'GET' + }) + t.equal(res.statusCode, 400) + + res = await app.inject({ + url: '/bar?lang=it', + method: 'GET' + }) + t.equal(res.statusCode, 200) + }) + + function buildApp (factory) { + const app = fastify({ + jsonShorthand: false, + schemaController: { + compilersFactory: { + buildValidator: factory + } + } + }) + + app.addSchema({ + $id: 'urn:schema:foo', + type: 'object', + properties: { + name: { type: 'string' }, + id: { type: 'integer' } + } + }) + + app.post('/foo', { + schema: { + body: { + $id: 'urn:schema:body', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:foo#/properties/name' } + } + } + } + }, () => { return 'ok' }) + + app.get('/bar', { + schema: { + query: { + $id: 'urn:schema:query', + type: 'object', + properties: { + lang: { type: 'string', enum: ['it', 'en'] } + } + } + } + }, () => { return 'ok' }) + + return app + } +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/types/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0749dfaac89500a81f72acf10c297a0b7cdacc09 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/types/index.d.ts @@ -0,0 +1,72 @@ +import _ajv, { AnySchema, Options as AjvOptions, ValidateFunction } from 'ajv' +import AjvJTD, { JTDOptions } from 'ajv/dist/jtd' +import type { Options, ErrorObject } from 'ajv' +import { AnyValidateFunction } from 'ajv/dist/core' + +type Ajv = _ajv +type AjvSerializerGenerator = typeof AjvCompiler + +type AjvJTDCompile = AjvJTD['compileSerializer'] +type AjvCompile = (schema: AnySchema, _meta?: boolean) => AnyValidateFunction + +declare function buildCompilerFromPool (externalSchemas: { [key: string]: AnySchema | AnySchema[] }, options?: { mode: 'JTD'; customOptions?: JTDOptions; onCreate?: (ajvInstance: Ajv) => void }): AjvCompile +declare function buildCompilerFromPool (externalSchemas: { [key: string]: AnySchema | AnySchema[] }, options?: { mode?: never; customOptions?: AjvOptions; onCreate?: (ajvInstance: Ajv) => void }): AjvCompile + +declare function buildSerializerFromPool (externalSchemas: any, serializerOpts?: { mode?: never; } & JTDOptions): AjvJTDCompile + +declare function AjvCompiler (opts: { jtdSerializer: true }): AjvCompiler.BuildSerializerFromPool +declare function AjvCompiler (opts?: { jtdSerializer?: false }): AjvCompiler.BuildCompilerFromPool + +declare function StandaloneValidator (options: AjvCompiler.StandaloneOptions): AjvCompiler.BuildCompilerFromPool + +declare namespace AjvCompiler { + export type { Options, ErrorObject } + export { Ajv } + + export type BuildSerializerFromPool = typeof buildSerializerFromPool + + export type BuildCompilerFromPool = typeof buildCompilerFromPool + + export const AjvReference: Symbol + + export enum HttpParts { + Body = 'body', + Headers = 'headers', + Params = 'params', + Query = 'querystring', + } + + export type RouteDefinition = { + method: string, + url: string, + httpPart: HttpParts, + schema?: unknown, + } + + export type StandaloneRestoreFunction = (opts: RouteDefinition) => ValidateFunction + + export type StandaloneStoreFunction = (opts: RouteDefinition, schemaValidationCode: string) => void + + export type StandaloneOptionsReadModeOn = { + readMode: true; + restoreFunction?: StandaloneRestoreFunction + } + + export type StandaloneOptionsReadModeOff = { + readMode?: false | undefined; + storeFunction?: StandaloneStoreFunction; + } + + export type StandaloneOptions = StandaloneOptionsReadModeOn | StandaloneOptionsReadModeOff + + export type ValidatorFactory = BuildCompilerFromPool | BuildSerializerFromPool + + export type ValidatorCompiler = ReturnType + + export { StandaloneValidator } + + export const AjvCompiler: AjvSerializerGenerator + export { AjvCompiler as default } +} + +export = AjvCompiler diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/types/index.test-d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/types/index.test-d.ts new file mode 100644 index 0000000000000000000000000000000000000000..391e7b7ad24d9e16f0218d599df6abb87d521d38 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/ajv-compiler/types/index.test-d.ts @@ -0,0 +1,226 @@ +import { AnySchemaObject, ValidateFunction } from 'ajv' +import { AnyValidateFunction } from 'ajv/dist/core' +import { expectAssignable, expectType } from 'tsd' +import AjvCompiler, { AjvReference, ValidatorFactory, StandaloneValidator, RouteDefinition, ErrorObject, BuildCompilerFromPool, BuildSerializerFromPool, ValidatorCompiler } from '..' + +{ + const compiler = AjvCompiler({}) + expectType(compiler) +} +{ + const compiler = AjvCompiler() + expectType(compiler) +} +{ + const compiler = AjvCompiler({ jtdSerializer: false }) + expectType(compiler) +} + +{ + const factory = AjvCompiler({ jtdSerializer: false }) + expectType(factory) + factory({}, { + onCreate (ajv) { + expectType(ajv) + } + }) +} + +{ + const compiler = AjvCompiler({ jtdSerializer: true }) + expectType(compiler) +} +const reader = StandaloneValidator({ + readMode: true, + restoreFunction: (route: RouteDefinition) => { + expectAssignable(route) + return {} as ValidateFunction + }, +}) +expectAssignable(reader) + +const writer = StandaloneValidator({ + readMode: false, + storeFunction: (route: RouteDefinition, code: string) => { + expectAssignable(route) + expectAssignable(code) + }, +}) +expectAssignable(writer) + +expectType(({} as ErrorObject).data) +expectType(({} as ErrorObject).instancePath) +expectType(({} as ErrorObject).keyword) +expectType(({} as ErrorObject).message) +expectType>(({} as ErrorObject).params) +expectType(({} as ErrorObject).parentSchema) +expectType(({} as ErrorObject).propertyName) +expectType(({} as ErrorObject).schema) +expectType(({} as ErrorObject).schemaPath) + +expectType(AjvReference) + +{ + const jtdSchema = { + discriminator: 'version', + mapping: { + 1: { + properties: { + foo: { type: 'uint8' } + } + }, + 2: { + properties: { + foo: { type: 'string' } + } + } + } + } + + const externalSchemas1 = { + foo: { + definitions: { + coordinates: { + properties: { + lat: { type: 'float32' }, + lng: { type: 'float32' } + } + } + } + } + } + + const factory = AjvCompiler({ jtdSerializer: true }) + expectType(factory) + const compiler = factory(externalSchemas1, {}) + expectAssignable(compiler) + const serializeFunc = compiler({ schema: jtdSchema }) + expectType<(data: unknown) => string>(serializeFunc) + expectType(serializeFunc({ version: '1', foo: 42 })) +} +// JTD +{ + const factory = AjvCompiler() + expectType(factory) + + const jtdSchema = { + discriminator: 'version', + mapping: { + 1: { + properties: { + foo: { type: 'uint8' } + } + }, + 2: { + properties: { + foo: { type: 'string' } + } + } + } + } + + const compiler = factory({}, { + customOptions: {}, + mode: 'JTD' + }) + expectAssignable(compiler) + const validatorFunc = compiler({ schema: jtdSchema }) + expectAssignable(validatorFunc) + + expectType>(validatorFunc({ + version: '2', + foo: [] + })) +} + +// generate standalone code +{ + const base = { + $id: 'urn:schema:base', + definitions: { + hello: { type: 'string' } + }, + type: 'object', + properties: { + hello: { $ref: '#/definitions/hello' } + } + } + + const refSchema = { + $id: 'urn:schema:ref', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:base#/definitions/hello' } + } + } + + const endpointSchema = { + schema: { + $id: 'urn:schema:endpoint', + $ref: 'urn:schema:ref' + } + } + + const schemaMap = { + [base.$id]: base, + [refSchema.$id]: refSchema + } + + const factory = StandaloneValidator({ + readMode: false, + storeFunction (routeOpts, schemaValidationCode) { + expectType(routeOpts) + expectType(schemaValidationCode) + } + }) + expectAssignable(factory) + + const compiler = factory(schemaMap) + expectAssignable(compiler) + expectAssignable(compiler(endpointSchema)) +} + +{ + const base = { + $id: 'urn:schema:base', + definitions: { + hello: { type: 'string' } + }, + type: 'object', + properties: { + hello: { $ref: '#/definitions/hello' } + } + } + + const refSchema = { + $id: 'urn:schema:ref', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:base#/definitions/hello' } + } + } + + const endpointSchema = { + schema: { + $id: 'urn:schema:endpoint', + $ref: 'urn:schema:ref' + } + } + + const schemaMap = { + [base.$id]: base, + [refSchema.$id]: refSchema + } + const factory = StandaloneValidator({ + readMode: true, + restoreFunction (routeOpts) { + expectType(routeOpts) + return {} as ValidateFunction + } + }) + expectAssignable(factory) + + const compiler = factory(schemaMap) + expectAssignable(compiler) + expectType>(compiler(endpointSchema)) +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/.github/dependabot.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..35d66ca7ac75f125b9c9c5b3dee0987fdfca4a45 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 + + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/.github/stale.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/.github/stale.yml new file mode 100644 index 0000000000000000000000000000000000000000..d51ce639022226bc44471aa18bb218b50876cd52 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/.github/stale.yml @@ -0,0 +1,21 @@ +# Number of days of inactivity before an issue becomes stale +daysUntilStale: 15 +# Number of days of inactivity before a stale issue is closed +daysUntilClose: 7 +# Issues with these labels will never be considered stale +exemptLabels: + - "discussion" + - "feature request" + - "bug" + - "help wanted" + - "plugin suggestion" + - "good first issue" +# Label to use when marking an issue as stale +staleLabel: stale +# Comment to post when marking an issue as stale. Set to `false` to disable +markComment: > + This issue has been automatically marked as stale because it has not had + recent activity. It will be closed if no further activity occurs. Thank you + for your contributions. +# Comment to post when closing a stale issue. Set to `false` to disable +closeComment: false diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/.github/workflows/ci.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..fd45202abff682784e3a60d54fbfee567d304b26 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/.github/workflows/ci.yml @@ -0,0 +1,28 @@ +name: CI + +on: + push: + branches: + - main + - next + - 'v*' + paths-ignore: + - 'docs/**' + - '*.md' + pull_request: + paths-ignore: + - 'docs/**' + - '*.md' + +permissions: + contents: read + +jobs: + test: + permissions: + contents: write + pull-requests: write + uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5 + with: + license-check: true + lint: true diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/benchmark/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/benchmark/package.json new file mode 100644 index 0000000000000000000000000000000000000000..15818d33bebbacf3a87f948d0af6227164af467e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/benchmark/package.json @@ -0,0 +1,15 @@ +{ + "name": "benchmark", + "version": "1.0.0", + "description": "", + "main": "vary.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC", + "dependencies": { + "benchmark": "^2.1.4", + "vary": "^1.1.2" + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/benchmark/vary.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/benchmark/vary.js new file mode 100644 index 0000000000000000000000000000000000000000..4aca63d803c065af6efd9464865bad42696eac1d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/benchmark/vary.js @@ -0,0 +1,34 @@ +'use strict' + +const benchmark = require('benchmark') +const vary = require('vary') +const createAddFieldnameToVary = require('../vary').createAddFieldnameToVary + +const replyMock = (header) => ({ + getHeader () { return header }, + setHeader () { }, + header () { } +}) + +const addAcceptToVary = createAddFieldnameToVary('Accept') +const addWildcardToVary = createAddFieldnameToVary('*') +const addAcceptEncodingToVary = createAddFieldnameToVary('Accept-Encoding') +const addXFooToVary = createAddFieldnameToVary('X-Foo') + +new benchmark.Suite() + .add('vary - field to undefined', function () { vary(replyMock(undefined), 'Accept-Encoding') }, { minSamples: 100 }) + .add('vary - field to *', function () { vary(replyMock('*'), 'Accept-Encoding') }, { minSamples: 100 }) + .add('vary - * to field', function () { vary(replyMock('Accept-Encoding'), '*') }, { minSamples: 100 }) + .add('vary - field to empty', function () { vary(replyMock(''), 'Accept-Encoding') }, { minSamples: 100 }) + .add('vary - fields string to empty', function () { vary(replyMock(''), 'Accept') }, { minSamples: 100 }) + .add('vary - field to fields', function () { vary(replyMock('Accept, Accept-Encoding, Accept-Language'), 'X-Foo') }, { minSamples: 100 }) + + .add('cors - field to undefined', function () { addAcceptEncodingToVary(replyMock(undefined)) }, { minSamples: 100 }) + .add('cors - field to *', function () { addAcceptEncodingToVary(replyMock('*')) }, { minSamples: 100 }) + .add('cors - * to field', function () { addWildcardToVary(replyMock('Accept-Encoding')) }, { minSamples: 100 }) + .add('cors - field to empty', function () { addAcceptEncodingToVary(replyMock('')) }, { minSamples: 100 }) + .add('cors - fields string to empty', function () { addAcceptToVary(replyMock('')) }, { minSamples: 100 }) + .add('cors - field to fields', function () { addXFooToVary(replyMock('Accept, Accept-Encoding, Accept-Language')) }, { minSamples: 100 }) + + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/test/cors.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/test/cors.test.js new file mode 100644 index 0000000000000000000000000000000000000000..d64c48acfc672acd147640e931c41a3fee7219bb --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/test/cors.test.js @@ -0,0 +1,1052 @@ +'use strict' + +const { test } = require('node:test') +const { createReadStream, statSync, readFileSync } = require('node:fs') +const Fastify = require('fastify') +const cors = require('../') +const { resolve } = require('node:path') +const { setTimeout: sleep } = require('node:timers/promises') + +test('Should add cors headers', async t => { + t.plan(4) + + const fastify = Fastify() + fastify.register(cors) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.deepStrictEqual(res.headers['access-control-allow-origin'], + '*' + ) +}) + +test('Should add cors headers when payload is a stream', async t => { + t.plan(4) + + const fastify = Fastify() + fastify.register(cors) + const filePath = resolve(__dirname, __filename) + + fastify.get('/', (_req, reply) => { + const stream = createReadStream(filePath) + reply + .type('application/json') + .header('Content-Length', statSync(filePath).size) + .send(stream) + }) + + const fileContent = readFileSync(filePath, 'utf-8') + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, fileContent) + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'content-length': res.headers['content-length'] + + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'content-length': statSync(filePath).size.toString() + }) +}) + +test('Should add cors headers (custom values)', async t => { + t.plan(10) + + const fastify = Fastify() + fastify.register(cors, { + origin: 'example.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['foo', 'bar'], + allowedHeaders: ['baz', 'woo'], + maxAge: 123, + cacheControl: 321 + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + 'access-control-allow-headers': res.headers['access-control-allow-headers'], + 'access-control-max-age': res.headers['access-control-max-age'], + 'cache-control': res.headers['cache-control'], + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'example.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'foo, bar', + 'access-control-allow-methods': 'GET', + 'access-control-allow-headers': 'baz, woo', + 'access-control-max-age': '123', + 'cache-control': 'max-age=321', + 'content-length': '0' + }) + t.assert.notDeepEqual(res.headers, { vary: 'Origin' }) + + res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders2 = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders2, { + 'access-control-allow-origin': 'example.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'foo, bar', + 'content-length': '2' + }) + t.assert.notDeepEqual(res.headers, { vary: 'Origin' }) +}) + +test('Should support dynamic config (callback)', async t => { + t.plan(16) + + const configs = [{ + origin: 'example.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['foo', 'bar'], + allowedHeaders: ['baz', 'woo'], + maxAge: 123, + cacheControl: 456 + }, { + origin: 'sample.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['zoo', 'bar'], + allowedHeaders: ['baz', 'foo'], + maxAge: 321, + cacheControl: '456' + }] + + const fastify = Fastify() + let requestId = 0 + const configDelegation = async function (req, cb) { + // request should have id + t.assert.ok(req.id) + // request should not have send + t.assert.ifError(req.send) + + const config = configs[requestId] + requestId++ + if (config) { + cb(null, config) + } else { + cb(new Error('ouch')) + } + } + await fastify.register(cors, () => configDelegation) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + // Sleep to wait for callback + sleep() + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'example.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'foo, bar', + 'content-length': '2', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const actualHeaders2 = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + 'access-control-allow-headers': res.headers['access-control-allow-headers'], + 'access-control-max-age': res.headers['access-control-max-age'], + 'cache-control': res.headers['cache-control'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + // Sleep to wait for callback + sleep() + t.assert.deepStrictEqual(actualHeaders2, { + 'access-control-allow-origin': 'sample.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'zoo, bar', + 'access-control-allow-methods': 'GET', + 'access-control-allow-headers': 'baz, foo', + 'access-control-max-age': '321', + 'cache-control': '456', + 'content-length': '0', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Should support dynamic config (Promise)', async t => { + t.plan(23) + + const configs = [{ + origin: 'example.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['foo', 'bar'], + allowedHeaders: ['baz', 'woo'], + maxAge: 123, + cacheControl: 456 + }, { + origin: 'sample.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['zoo', 'bar'], + allowedHeaders: ['baz', 'foo'], + maxAge: 321, + cacheControl: true // Invalid value should be ignored + }, { + origin: 'sample.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['zoo', 'bar'], + allowedHeaders: ['baz', 'foo'], + maxAge: 321, + cacheControl: 'public, max-age=456' + }] + + const fastify = Fastify() + let requestId = 0 + const configDelegation = async function (req) { + // request should have id + t.assert.ok(req.id) + // request should not have send + t.assert.ifError(req.send) + const config = configs[requestId] + requestId++ + if (config) { + return Promise.resolve(config) + } else { + return Promise.reject(new Error('ouch')) + } + } + await fastify.register(cors, () => configDelegation) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'example.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'foo, bar', + 'content-length': '2', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'sample.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const acutalHeaders2 = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + 'access-control-allow-headers': res.headers['access-control-allow-headers'], + 'access-control-max-age': res.headers['access-control-max-age'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(acutalHeaders2, { + 'access-control-allow-origin': 'sample.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'zoo, bar', + 'access-control-allow-methods': 'GET', + 'access-control-allow-headers': 'baz, foo', + 'access-control-max-age': '321', + 'content-length': '0', + vary: 'Origin' + }) + t.assert.strictEqual(res.headers['cache-control'], undefined, 'cache-control omitted (invalid value)') + + res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const actualHeaders3 = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + 'access-control-allow-headers': res.headers['access-control-allow-headers'], + 'access-control-max-age': res.headers['access-control-max-age'], + 'cache-control': res.headers['cache-control'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders3, { + 'access-control-allow-origin': 'sample.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'zoo, bar', + 'access-control-allow-methods': 'GET', + 'access-control-allow-headers': 'baz, foo', + 'access-control-max-age': '321', + 'cache-control': 'public, max-age=456', // cache-control included (custom string) + 'content-length': '0', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Should support dynamic config. (Invalid function)', async t => { + t.plan(2) + + const fastify = Fastify() + fastify.register(cors, () => () => {}) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Dynamic origin resolution (valid origin)', async t => { + t.plan(6) + + const fastify = Fastify() + const origin = function (header, cb) { + t.assert.strictEqual(header, 'example.com') + t.assert.equal(this, fastify) + cb(null, true) + } + fastify.register(cors, { origin }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'example.com', + vary: 'Origin' + }) +}) + +test('Dynamic origin resolution (not valid origin)', async t => { + t.plan(5) + + const fastify = Fastify() + const origin = (header, cb) => { + t.assert.strictEqual(header, 'example.com') + cb(null, false) + } + fastify.register(cors, { origin }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'content-length': res.headers['content-length'], + 'content-type': res.headers['content-type'], + connection: res.headers.connection, + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'content-length': '2', + 'content-type': 'text/plain; charset=utf-8', + connection: 'keep-alive', + vary: 'Origin' + }) +}) + +test('Dynamic origin resolution (errored)', async t => { + t.plan(3) + + const fastify = Fastify() + const origin = (header, cb) => { + t.assert.strictEqual(header, 'example.com') + cb(new Error('ouch')) + } + fastify.register(cors, { origin }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Dynamic origin resolution (invalid result)', async t => { + t.plan(3) + + const fastify = Fastify() + const origin = (header, cb) => { + t.assert.strictEqual(header, 'example.com') + cb(null, undefined) + } + fastify.register(cors, { origin }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Dynamic origin resolution (valid origin - promises)', async t => { + t.plan(5) + + const fastify = Fastify() + const origin = (header) => { + return new Promise((resolve) => { + t.assert.strictEqual(header, 'example.com') + resolve(true) + }) + } + fastify.register(cors, { origin }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'example.com', + vary: 'Origin' + }) +}) + +test('Dynamic origin resolution (not valid origin - promises)', async t => { + t.plan(5) + + const fastify = Fastify() + const origin = (header) => { + return new Promise((resolve) => { + t.assert.strictEqual(header, 'example.com') + resolve(false) + }) + } + fastify.register(cors, { origin }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'content-length': res.headers['content-length'], + 'content-type': res.headers['content-type'], + connection: res.headers.connection, + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'content-length': '2', + 'content-type': 'text/plain; charset=utf-8', + connection: 'keep-alive', + vary: 'Origin' + }) +}) + +test('Dynamic origin resolution (errored - promises)', async t => { + t.plan(3) + + const fastify = Fastify() + const origin = (header) => { + return new Promise((_resolve, reject) => { + t.assert.strictEqual(header, 'example.com') + reject(new Error('ouch')) + }) + } + fastify.register(cors, { origin }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Should reply 404 without cors headers when origin is false', async t => { + t.plan(8) + + const fastify = Fastify() + fastify.register(cors, { + origin: false, + methods: 'GET', + credentials: true, + exposedHeaders: ['foo', 'bar'], + allowedHeaders: ['baz', 'woo'], + maxAge: 123 + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 404) + t.assert.strictEqual(res.payload, '{"message":"Route OPTIONS:/ not found","error":"Not Found","statusCode":404}') + const actualHeaders = { + 'content-length': res.headers['content-length'], + 'content-type': res.headers['content-type'], + connection: res.headers.connection + } + t.assert.deepStrictEqual(actualHeaders, { + 'content-length': '76', + 'content-type': 'application/json; charset=utf-8', + connection: 'keep-alive' + }) + + res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.deepStrictEqual(res.headers, { + 'content-length': '2', + 'content-type': 'text/plain; charset=utf-8', + connection: 'keep-alive' + }) +}) + +test('Server error if origin option is falsy but not false', async t => { + t.plan(4) + + const fastify = Fastify() + fastify.register(cors, { origin: '' }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 500) + t.assert.deepStrictEqual(res.json(), { statusCode: 500, error: 'Internal Server Error', message: 'Invalid CORS origin option' }) + const actualHeaders = { + 'content-length': res.headers['content-length'], + 'content-type': res.headers['content-type'], + connection: res.headers.connection + } + t.assert.deepStrictEqual(actualHeaders, { + 'content-length': '89', + 'content-type': 'application/json; charset=utf-8', + connection: 'keep-alive' + }) +}) + +test('Allow only request from a specific origin', async t => { + t.plan(5) + + const fastify = Fastify() + fastify.register(cors, { origin: 'other.io' }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.deepStrictEqual(res.headers['access-control-allow-origin'], + 'other.io' + ) + t.assert.notDeepEqual(res.headers, { vary: 'Origin' }) +}) + +test('Allow only request from multiple specific origin', async t => { + t.plan(9) + + const fastify = Fastify() + fastify.register(cors, { origin: ['other.io', 'example.com'] }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'other.io' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'other.io', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'foo.com' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.deepStrictEqual(res.headers.vary, + 'Origin' + ) + t.assert.strictEqual(res.headers['access-control-allow-origin'], undefined) +}) + +test('Allow only request from a specific origin using regex', async t => { + t.plan(8) + + const fastify = Fastify() + fastify.register(cors, { origin: /(?:example|other)\.com\/?$/giu }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + // .test was previously used, which caused 2 consecutive requests to return + // different results with global (e.g. /g) regexes. Therefore, check this + // twice to check consistency + for (let i = 0; i < 2; i++) { + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'https://www.example.com/' } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'https://www.example.com/', + vary: 'Origin' + }) + } +}) + +test('Disable preflight', async t => { + t.plan(7) + + const fastify = Fastify() + fastify.register(cors, { preflight: false }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/hello' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 404) + t.assert.strictEqual(res.headers['access-control-allow-origin'], + '*' + ) + + res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.strictEqual(res.headers['access-control-allow-origin'], + '*' + ) +}) + +test('Should always add vary header to `Origin` for reflected origin', async t => { + t.plan(12) + + const fastify = Fastify() + fastify.register(cors, { origin: true }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + // Invalid Preflight + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 400) + t.assert.strictEqual(res.payload, 'Invalid Preflight Request') + t.assert.strictEqual(res.headers.vary, + 'Origin' + ) + + // Valid Preflight + res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + t.assert.strictEqual(res.headers.vary, + 'Origin, Access-Control-Request-Headers' + ) + + // Other Route + res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.strictEqual(res.headers.vary, + 'Origin' + ) +}) + +test('Should always add vary header to `Origin` for reflected origin (vary is array)', async t => { + t.plan(4) + + const fastify = Fastify() + + // Mock getHeader function + fastify.decorateReply('getHeader', () => ['foo', 'bar']) + + fastify.register(cors, { origin: true }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.strictEqual(res.headers.vary, + 'foo, bar, Origin' + ) +}) + +test('Allow only request from with specific headers', async t => { + t.plan(8) + + const fastify = Fastify() + fastify.register(cors, { + allowedHeaders: 'foo', + exposedHeaders: 'bar' + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.deepStrictEqual(res.headers['access-control-allow-headers'], + 'foo' + ) + t.assert.notDeepEqual(res.headers.vary, 'Origin') + + res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.strictEqual(res.headers['access-control-expose-headers'], + 'bar' + ) +}) + +test('Should support wildcard config /1', async t => { + t.plan(4) + + const fastify = Fastify() + fastify.register(cors, { origin: '*' }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.strictEqual(res.headers['access-control-allow-origin'], '*') +}) + +test('Should support wildcard config /2', async t => { + t.plan(4) + + const fastify = Fastify() + fastify.register(cors, { origin: ['*'] }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + t.assert.strictEqual(res.headers['access-control-allow-origin'], '*') +}) + +test('Should allow routes to disable CORS individually', async t => { + t.plan(6) + + const fastify = Fastify() + fastify.register(cors, { origin: '*' }) + + fastify.get('/cors-enabled', (_req, reply) => { + reply.send('ok') + }) + + fastify.get('/cors-disabled', { config: { cors: false } }, (_req, reply) => { + reply.send('ok') + }) + + // Test CORS enabled route + let res = await fastify.inject({ + method: 'GET', + url: '/cors-enabled', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.headers['access-control-allow-origin'], '*') + + // Test CORS disabled route + res = await fastify.inject({ + method: 'GET', + url: '/cors-disabled', + headers: { origin: 'example.com' } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.headers['access-control-allow-origin'], undefined) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/test/hooks.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/test/hooks.test.js new file mode 100644 index 0000000000000000000000000000000000000000..74ccf22592b1759ce552ded6861abe1366e8619e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/test/hooks.test.js @@ -0,0 +1,787 @@ +'use strict' + +const { test } = require('node:test') +const Fastify = require('fastify') +const kFastifyContext = require('fastify/lib/symbols').kRouteContext +const cors = require('..') +const { setTimeout: sleep } = require('node:timers/promises') + +test('Should error on invalid hook option', async (t) => { + t.plan(3) + + const fastify = Fastify() + await t.assert.rejects( + async () => fastify.register(cors, { hook: 'invalid' }), + (err) => { + t.assert.strictEqual(err.name, 'TypeError') + t.assert.strictEqual(err.message, '@fastify/cors: Invalid hook option provided.') + return true + } + ) +}) + +test('Should set hook onRequest if hook option is not set', async (t) => { + t.plan(10) + + const fastify = Fastify() + + fastify.register(cors) + + fastify.addHook('onResponse', (request, _reply, done) => { + t.assert.strictEqual(request[kFastifyContext].onError, null) + t.assert.strictEqual(request[kFastifyContext].onRequest.length, 1) + t.assert.strictEqual(request[kFastifyContext].onSend, null) + t.assert.strictEqual(request[kFastifyContext].preHandler, null) + t.assert.strictEqual(request[kFastifyContext].preParsing, null) + t.assert.strictEqual(request[kFastifyContext].preSerialization, null) + t.assert.strictEqual(request[kFastifyContext].preValidation, null) + done() + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + await fastify.ready() + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeader = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'] + } + t.assert.deepStrictEqual(actualHeader, { + 'access-control-allow-origin': '*' + }) +}) + +test('Should set hook onRequest if hook option is set to onRequest', async (t) => { + t.plan(10) + + const fastify = Fastify() + + fastify.register(cors, { + hook: 'onRequest' + }) + + fastify.addHook('onResponse', (request, _reply, done) => { + t.assert.strictEqual(request[kFastifyContext].onError, null) + t.assert.strictEqual(request[kFastifyContext].onRequest.length, 1) + t.assert.strictEqual(request[kFastifyContext].onSend, null) + t.assert.strictEqual(request[kFastifyContext].preHandler, null) + t.assert.strictEqual(request[kFastifyContext].preParsing, null) + t.assert.strictEqual(request[kFastifyContext].preSerialization, null) + t.assert.strictEqual(request[kFastifyContext].preValidation, null) + done() + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + await fastify.ready() + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeader = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'] + } + t.assert.deepStrictEqual(actualHeader, { + 'access-control-allow-origin': '*' + }) +}) + +test('Should set hook preParsing if hook option is set to preParsing', async (t) => { + t.plan(11) + + const fastify = Fastify() + + fastify.register(cors, { + hook: 'preParsing' + }) + + fastify.addHook('onResponse', (request, _reply, done) => { + t.assert.strictEqual(request[kFastifyContext].onError, null) + t.assert.strictEqual(request[kFastifyContext].onRequest, null) + t.assert.strictEqual(request[kFastifyContext].onSend, null) + t.assert.strictEqual(request[kFastifyContext].preHandler, null) + t.assert.strictEqual(request[kFastifyContext].preParsing.length, 1) + t.assert.strictEqual(request[kFastifyContext].preSerialization, null) + t.assert.strictEqual(request[kFastifyContext].preValidation, null) + done() + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + await fastify.ready() + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeader = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'] + } + t.assert.deepStrictEqual(actualHeader, { + 'access-control-allow-origin': '*' + }) + t.assert.notStrictEqual(res.headers.vary, 'Origin') +}) + +test('Should set hook preValidation if hook option is set to preValidation', async (t) => { + t.plan(11) + + const fastify = Fastify() + + fastify.register(cors, { + hook: 'preValidation' + }) + + fastify.addHook('onResponse', (request, _reply, done) => { + t.assert.strictEqual(request[kFastifyContext].onError, null) + t.assert.strictEqual(request[kFastifyContext].onRequest, null) + t.assert.strictEqual(request[kFastifyContext].onSend, null) + t.assert.strictEqual(request[kFastifyContext].preHandler, null) + t.assert.strictEqual(request[kFastifyContext].preParsing, null) + t.assert.strictEqual(request[kFastifyContext].preSerialization, null) + t.assert.strictEqual(request[kFastifyContext].preValidation.length, 1) + done() + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + await fastify.ready() + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeader = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'] + } + t.assert.deepStrictEqual(actualHeader, { + 'access-control-allow-origin': '*' + }) + t.assert.notStrictEqual(res.headers.vary, 'Origin') +}) + +test('Should set hook preParsing if hook option is set to preParsing', async (t) => { + t.plan(11) + + const fastify = Fastify() + + fastify.register(cors, { + hook: 'preParsing' + }) + + fastify.addHook('onResponse', (request, _reply, done) => { + t.assert.strictEqual(request[kFastifyContext].onError, null) + t.assert.strictEqual(request[kFastifyContext].onRequest, null) + t.assert.strictEqual(request[kFastifyContext].onSend, null) + t.assert.strictEqual(request[kFastifyContext].preHandler, null) + t.assert.strictEqual(request[kFastifyContext].preParsing.length, 1) + t.assert.strictEqual(request[kFastifyContext].preSerialization, null) + t.assert.strictEqual(request[kFastifyContext].preValidation, null) + done() + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + await fastify.ready() + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeader = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'] + } + t.assert.deepStrictEqual(actualHeader, { + 'access-control-allow-origin': '*' + }) + t.assert.notStrictEqual(res.headers.vary, 'Origin') +}) + +test('Should set hook preHandler if hook option is set to preHandler', async (t) => { + t.plan(11) + + const fastify = Fastify() + + fastify.register(cors, { + hook: 'preHandler' + }) + + fastify.addHook('onResponse', (request, _reply, done) => { + t.assert.strictEqual(request[kFastifyContext].onError, null) + t.assert.strictEqual(request[kFastifyContext].onRequest, null) + t.assert.strictEqual(request[kFastifyContext].onSend, null) + t.assert.strictEqual(request[kFastifyContext].preHandler.length, 1) + t.assert.strictEqual(request[kFastifyContext].preParsing, null) + t.assert.strictEqual(request[kFastifyContext].preSerialization, null) + t.assert.strictEqual(request[kFastifyContext].preValidation, null) + done() + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + await fastify.ready() + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeader = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'] + } + t.assert.deepStrictEqual(actualHeader, { + 'access-control-allow-origin': '*' + }) + t.assert.notStrictEqual(res.headers.vary, 'Origin') +}) + +test('Should set hook onSend if hook option is set to onSend', async (t) => { + t.plan(11) + + const fastify = Fastify() + + fastify.register(cors, { + hook: 'onSend' + }) + + fastify.addHook('onResponse', (request, _reply, done) => { + t.assert.strictEqual(request[kFastifyContext].onError, null) + t.assert.strictEqual(request[kFastifyContext].onRequest, null) + t.assert.strictEqual(request[kFastifyContext].onSend.length, 1) + t.assert.strictEqual(request[kFastifyContext].preHandler, null) + t.assert.strictEqual(request[kFastifyContext].preParsing, null) + t.assert.strictEqual(request[kFastifyContext].preSerialization, null) + t.assert.strictEqual(request[kFastifyContext].preValidation, null) + done() + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + await fastify.ready() + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeader = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'] + } + t.assert.deepStrictEqual(actualHeader, { + 'access-control-allow-origin': '*' + }) + t.assert.notStrictEqual(res.headers.vary, 'Origin') +}) + +test('Should set hook preSerialization if hook option is set to preSerialization', async (t) => { + t.plan(11) + + const fastify = Fastify() + + fastify.register(cors, { + hook: 'preSerialization' + }) + + fastify.addHook('onResponse', (request, _reply, done) => { + t.assert.strictEqual(request[kFastifyContext].onError, null) + t.assert.strictEqual(request[kFastifyContext].onRequest, null) + t.assert.strictEqual(request[kFastifyContext].onSend, null) + t.assert.strictEqual(request[kFastifyContext].preHandler, null) + t.assert.strictEqual(request[kFastifyContext].preParsing, null) + t.assert.strictEqual(request[kFastifyContext].preSerialization.length, 1) + t.assert.strictEqual(request[kFastifyContext].preValidation, null) + done() + }) + + fastify.get('/', (_req, reply) => { + reply.send({ nonString: true }) + }) + + await fastify.ready() + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, '{"nonString":true}') + const actualHeader = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'] + } + t.assert.deepStrictEqual(actualHeader, { + 'access-control-allow-origin': '*' + }) + t.assert.notStrictEqual(res.headers.vary, 'Origin') +}) + +test('Should support custom hook with dynamic config', async t => { + t.plan(16) + + const configs = [{ + origin: 'example.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['foo', 'bar'], + allowedHeaders: ['baz', 'woo'], + maxAge: 123 + }, { + origin: 'sample.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['zoo', 'bar'], + allowedHeaders: ['baz', 'foo'], + maxAge: 321 + }] + + const fastify = Fastify() + let requestId = 0 + const configDelegation = async function (req) { + // request should have id + t.assert.ok(req.id) + // request should not have send + t.assert.ifError(req.send) + const config = configs[requestId] + requestId++ + if (config) { + return Promise.resolve(config) + } else { + return Promise.reject(new Error('ouch')) + } + } + await fastify.register(cors, { + hook: 'preHandler', + delegator: configDelegation + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + let actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'example.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'foo, bar', + 'content-length': '2', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + 'access-control-allow-headers': res.headers['access-control-allow-headers'], + 'access-control-max-age': res.headers['access-control-max-age'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'sample.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'zoo, bar', + 'access-control-allow-methods': 'GET', + 'access-control-allow-headers': 'baz, foo', + 'access-control-max-age': '321', + 'content-length': '0', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Should support custom hook with dynamic config (callback)', async t => { + t.plan(16) + + const configs = [{ + origin: 'example.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['foo', 'bar'], + allowedHeaders: ['baz', 'woo'], + maxAge: 123 + }, { + origin: 'sample.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['zoo', 'bar'], + allowedHeaders: ['baz', 'foo'], + maxAge: 321 + }] + + const fastify = Fastify() + let requestId = 0 + const configDelegation = function (req, cb) { + // request should have id + t.assert.ok(req.id) + // request should not have send + t.assert.ifError(req.send) + const config = configs[requestId] + requestId++ + if (config) { + cb(null, config) + } else { + cb(new Error('ouch')) + } + } + fastify.register(cors, { + hook: 'preParsing', + delegator: configDelegation + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + fastify.inject({ + method: 'GET', + url: '/' + }, (err, res) => { + t.assert.ifError(err) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'example.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'foo, bar', + 'content-length': '2', + vary: 'Origin' + }) + }) + + fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }, (err, res) => { + t.assert.ifError(err) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + 'access-control-allow-headers': res.headers['access-control-allow-headers'], + 'access-control-max-age': res.headers['access-control-max-age'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'sample.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'zoo, bar', + 'access-control-allow-methods': 'GET', + 'access-control-allow-headers': 'baz, foo', + 'access-control-max-age': '321', + 'content-length': '0', + vary: 'Origin' + }) + }) + + fastify.inject({ + method: 'GET', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }, (err, res) => { + t.assert.ifError(err) + t.assert.strictEqual(res.statusCode, 500) + }) + await sleep() +}) + +test('Should support custom hook with dynamic config (Promise)', async t => { + t.plan(16) + + const configs = [{ + origin: 'example.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['foo', 'bar'], + allowedHeaders: ['baz', 'woo'], + maxAge: 123 + }, { + origin: 'sample.com', + methods: 'GET', + credentials: true, + exposedHeaders: ['zoo', 'bar'], + allowedHeaders: ['baz', 'foo'], + maxAge: 321 + }] + + const fastify = Fastify() + let requestId = 0 + const configDelegation = async function (req) { + // request should have id + t.assert.ok(req.id) + // request should not have send + t.assert.ifError(req.send) + const config = configs[requestId] + requestId++ + if (config) { + return Promise.resolve(config) + } else { + return Promise.reject(new Error('ouch')) + } + } + + await fastify.register(cors, { + hook: 'preParsing', + delegator: configDelegation + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'GET', + url: '/' + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + let actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'example.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'foo, bar', + 'content-length': '2', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-credentials': res.headers['access-control-allow-credentials'], + 'access-control-expose-headers': res.headers['access-control-expose-headers'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + 'access-control-allow-headers': res.headers['access-control-allow-headers'], + 'access-control-max-age': res.headers['access-control-max-age'], + 'content-length': res.headers['content-length'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': 'sample.com', + 'access-control-allow-credentials': 'true', + 'access-control-expose-headers': 'zoo, bar', + 'access-control-allow-methods': 'GET', + 'access-control-allow-headers': 'baz, foo', + 'access-control-max-age': '321', + 'content-length': '0', + vary: 'Origin' + }) + + res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Should support custom hook with dynamic config (Promise), but should error /1', async t => { + t.plan(6) + + const fastify = Fastify() + const configDelegation = function () { + return false + } + + await fastify.register(cors, { + hook: 'preParsing', + delegator: configDelegation + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 500) + t.assert.strictEqual(res.payload, '{"statusCode":500,"error":"Internal Server Error","message":"Invalid CORS origin option"}') + const actualHeaders = { + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'content-length': '89' + }) + + res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) + +test('Should support custom hook with dynamic config (Promise), but should error /2', async t => { + t.plan(6) + + const fastify = Fastify() + const configDelegation = function () { + return false + } + + await fastify.register(cors, { + delegator: configDelegation + }) + + fastify.get('/', (_req, reply) => { + reply.send('ok') + }) + + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 500) + t.assert.strictEqual(res.payload, '{"statusCode":500,"error":"Internal Server Error","message":"Invalid CORS origin option"}') + const actualHeaders = { + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'content-length': '89' + }) + + res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 500) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/test/preflight.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/test/preflight.test.js new file mode 100644 index 0000000000000000000000000000000000000000..7a20de20c7e7c63089da6dc9a0100187df06eb79 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/test/preflight.test.js @@ -0,0 +1,590 @@ +'use strict' + +const { test } = require('node:test') +const Fastify = require('fastify') +const cors = require('../') + +test('Should reply to preflight requests', async t => { + t.plan(4) + + const fastify = Fastify() + await fastify.register(cors) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + vary: res.headers.vary, + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + vary: 'Access-Control-Request-Headers', + 'content-length': '0' + }) +}) + +test('Should add access-control-allow-headers to response if preflight req has access-control-request-headers', async t => { + t.plan(4) + + const fastify = Fastify() + await fastify.register(cors) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-headers': 'x-requested-with', + 'access-control-request-method': 'GET', + origin: 'example.com' + } + + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + 'access-control-allow-headers': res.headers['access-control-allow-headers'], + vary: res.headers.vary, + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + 'access-control-allow-headers': 'x-requested-with', + vary: 'Access-Control-Request-Headers', + 'content-length': '0' + }) +}) + +test('Should reply to preflight requests with custom status code', async t => { + t.plan(4) + + const fastify = Fastify() + await fastify.register(cors, { optionsSuccessStatus: 200 }) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, '') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + vary: res.headers.vary, + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + vary: 'Access-Control-Request-Headers', + 'content-length': '0' + }) +}) + +test('Should be able to override preflight response with a route', async t => { + t.plan(5) + + const fastify = Fastify() + await fastify.register(cors, { preflightContinue: true }) + + fastify.options('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'] + } + t.assert.deepStrictEqual(actualHeaders, { + // Only the base cors headers and no preflight headers + 'access-control-allow-origin': '*' + }) + t.assert.notStrictEqual(res.headers.vary, 'Origin') +}) + +test('Should reply to all options requests', async t => { + t.plan(4) + + const fastify = Fastify() + await fastify.register(cors) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/hello', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + vary: res.headers.vary, + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + vary: 'Access-Control-Request-Headers', + 'content-length': '0' + }) +}) + +test('Should support a prefix for preflight requests', async t => { + t.plan(6) + + const fastify = Fastify() + await fastify.register((instance, _opts, next) => { + instance.register(cors) + next() + }, { prefix: '/subsystem' }) + + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/hello' + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 404) + + res = await fastify.inject({ + method: 'OPTIONS', + url: '/subsystem/hello', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + vary: res.headers.vary, + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + vary: 'Access-Control-Request-Headers', + 'content-length': '0' + }) +}) + +test('hide options route by default', async t => { + t.plan(2) + + const fastify = Fastify() + + fastify.addHook('onRoute', (route) => { + if (route.method === 'OPTIONS' && route.url === '*') { + t.assert.strictEqual(route.schema.hide, true) + } + }) + await fastify.register(cors) + + const ready = await fastify.ready() + t.assert.ok(ready) +}) + +test('show options route', async t => { + t.plan(2) + + const fastify = Fastify() + + fastify.addHook('onRoute', (route) => { + if (route.method === 'OPTIONS' && route.url === '*') { + t.assert.strictEqual(route.schema.hide, false) + } + }) + await fastify.register(cors, { hideOptionsRoute: false }) + + const ready = await fastify.ready() + t.assert.ok(ready) +}) + +test('Allow only request from with specific methods', async t => { + t.plan(4) + + const fastify = Fastify() + await fastify.register(cors, { methods: ['GET', 'POST'] }) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + const actualHeaders = { + 'access-control-allow-methods': res.headers['access-control-allow-methods'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-methods': 'GET, POST' + }) + t.assert.notStrictEqual(res.headers.vary, 'Origin') +}) + +test('Should reply with 400 error to OPTIONS requests missing origin header when default strictPreflight', async t => { + t.plan(3) + + const fastify = Fastify() + await fastify.register(cors) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET' + } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 400) + t.assert.strictEqual(res.payload, 'Invalid Preflight Request') +}) + +test('Should reply with 400 to OPTIONS requests when missing Access-Control-Request-Method header when default strictPreflight', async t => { + t.plan(3) + + const fastify = Fastify() + await fastify.register(cors, { + strictPreflight: true + }) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + origin: 'example.com' + } + }) + t.assert.ok(res) + t.assert.strictEqual(res.statusCode, 400) + t.assert.strictEqual(res.payload, 'Invalid Preflight Request') +}) + +test('Should reply to all preflight requests when strictPreflight is disabled', async t => { + t.plan(4) + + const fastify = Fastify() + await fastify.register(cors, { strictPreflight: false }) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/' + // No access-control-request-method or origin headers + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + vary: res.headers.vary, + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + vary: 'Access-Control-Request-Headers', + 'content-length': '0' + }) +}) + +test('Default empty 200 response with preflightContinue on OPTIONS routes', async t => { + t.plan(4) + + const fastify = Fastify() + await fastify.register(cors, { preflightContinue: true }) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/doesnotexist', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, '') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + vary: 'Access-Control-Request-Headers' + }) +}) + +test('Can override preflight response with preflightContinue', async t => { + t.plan(4) + + const fastify = Fastify() + await fastify.register(cors, { preflightContinue: true }) + + fastify.options('/', (_req, reply) => { + reply.send('ok') + }) + + const res = await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 200) + t.assert.strictEqual(res.payload, 'ok') + const actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + vary: res.headers.vary + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + vary: 'Access-Control-Request-Headers' + }) +}) + +test('Should support ongoing prefix ', async t => { + t.plan(12) + + const fastify = Fastify() + + await fastify.register(async (instance) => { + instance.register(cors) + }, { prefix: '/prefix' }) + + // support prefixed route + let res = await fastify.inject({ + method: 'OPTIONS', + url: '/prefix', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + let actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + vary: res.headers.vary, + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + vary: 'Access-Control-Request-Headers', + 'content-length': '0' + }) + + // support prefixed route without / continue + res = await fastify.inject({ + method: 'OPTIONS', + url: '/prefixfoo', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + vary: res.headers.vary, + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + vary: 'Access-Control-Request-Headers', + 'content-length': '0' + }) + + // support prefixed route with / continue + res = await fastify.inject({ + method: 'OPTIONS', + url: '/prefix/foo', + headers: { + 'access-control-request-method': 'GET', + origin: 'example.com' + } + }) + t.assert.ok(res) + delete res.headers.date + t.assert.strictEqual(res.statusCode, 204) + t.assert.strictEqual(res.payload, '') + actualHeaders = { + 'access-control-allow-origin': res.headers['access-control-allow-origin'], + 'access-control-allow-methods': res.headers['access-control-allow-methods'], + vary: res.headers.vary, + 'content-length': res.headers['content-length'] + } + t.assert.deepStrictEqual(actualHeaders, { + 'access-control-allow-origin': '*', + 'access-control-allow-methods': 'GET,HEAD,POST', + vary: 'Access-Control-Request-Headers', + 'content-length': '0' + }) +}) + +test('Silences preflight logs when logLevel is "silent"', async t => { + const logs = [] + const fastify = Fastify({ + logger: { + level: 'info', + stream: { + write (line) { + try { + logs.push(JSON.parse(line)) + } catch { + } + } + } + } + }) + + await fastify.register(cors, { logLevel: 'silent' }) + + fastify.get('/', async () => ({ ok: true })) + + await fastify.ready() + t.assert.ok(fastify) + + await fastify.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'https://example.com' + } + }) + + await fastify.inject({ method: 'GET', url: '/' }) + + const hasOptionsLog = logs.some(l => l.req && l.req.method === 'OPTIONS') + const hasGetLog = logs.some(l => l.req && l.req.method === 'GET') + + t.assert.strictEqual(hasOptionsLog, false) + t.assert.strictEqual(hasGetLog, true) + + await fastify.close() +}) +test('delegator + logLevel:"silent" → OPTIONS logs are suppressed', async t => { + t.plan(3) + + const logs = [] + const app = Fastify({ + logger: { + level: 'info', + stream: { write: l => { try { logs.push(JSON.parse(l)) } catch {} } } + } + }) + + await app.register(cors, { + delegator: () => ({ origin: '*' }), + logLevel: 'silent' + }) + + app.get('/', () => ({ ok: true })) + await app.ready() + t.assert.ok(app) + + await app.inject({ + method: 'OPTIONS', + url: '/', + headers: { + 'access-control-request-method': 'GET', + origin: 'https://example.com' + } + }) + + await app.inject({ method: 'GET', url: '/' }) + + const hasOptionsLog = logs.some(l => l.req?.method === 'OPTIONS') + const hasGetLog = logs.some(l => l.req?.method === 'GET') + + t.assert.strictEqual(hasOptionsLog, false) + t.assert.strictEqual(hasGetLog, true) + + await app.close() +}) +test('delegator + hideOptionsRoute:false → OPTIONS route is visible', async t => { + t.plan(2) + + const app = Fastify() + + app.addHook('onRoute', route => { + if (route.method === 'OPTIONS' && route.url === '*') { + t.assert.strictEqual(route.schema.hide, false) + } + }) + + await app.register(cors, { + delegator: () => ({ origin: '*' }), + hideOptionsRoute: false + }) + + await app.ready() + t.assert.ok(app) + await app.close() +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/test/vary.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/test/vary.test.js new file mode 100644 index 0000000000000000000000000000000000000000..4357add02a890853b0183e6b54bdf15cda561f86 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/test/vary.test.js @@ -0,0 +1,237 @@ +'use strict' + +const { test } = require('node:test') +const { createAddFieldnameToVary } = require('../vary') +const { parse } = require('../vary') + +test('Should set * even if we set a specific field', async t => { + t.plan(1) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return '*' + }, + header () { + t.fail('Should not be here') + } + } + + addOriginToVary(replyMock) + t.assert.ok(true) // equalivant to tap t.pass() +}) + +test('Should set * even if we set a specific field', t => { + t.plan(2) + + const addWildcardToVary = createAddFieldnameToVary('*') + const replyMock = { + getHeader () { + return 'Origin' + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, '*') + } + } + + addWildcardToVary(replyMock) +}) + +test('Should set * when field contains a *', t => { + t.plan(3) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return ['Origin', '*', 'Access-Control-Request-Headers'] + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, '*') + } + } + + addOriginToVary(replyMock) + t.assert.ok(true) // equalivant to tap t.pass() +}) + +test('Should concat vary values', t => { + t.plan(3) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return 'Access-Control-Request-Headers' + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, 'Access-Control-Request-Headers, Origin') + } + } + + addOriginToVary(replyMock) + t.assert.ok(true) // equalivant to tap t.pass() +}) + +test('Should concat vary values ignoring consecutive commas', t => { + t.plan(3) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return ' Access-Control-Request-Headers,Access-Control-Request-Method' + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, ' Access-Control-Request-Headers,Access-Control-Request-Method, Origin') + } + } + + addOriginToVary(replyMock) + t.assert.ok(true) // equalivant to tap t.pass() +}) + +test('Should concat vary values ignoring whitespace', t => { + t.plan(3) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return ' Access-Control-Request-Headers ,Access-Control-Request-Method' + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, ' Access-Control-Request-Headers ,Access-Control-Request-Method, Origin') + } + } + + addOriginToVary(replyMock) + t.assert.ok(true) // equalivant to tap t.pass() +}) + +test('Should set the field as value for vary if no vary is defined', t => { + t.plan(2) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return undefined + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, 'Origin') + } + } + + addOriginToVary(replyMock) +}) + +test('Should set * as value for vary if vary contains *', t => { + t.plan(2) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return 'Accept,*' + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, '*') + } + } + + addOriginToVary(replyMock) +}) + +test('Should set Accept-Encoding as value for vary if vary is empty string', t => { + t.plan(2) + + const addAcceptEncodingToVary = createAddFieldnameToVary('Accept-Encoding') + const replyMock = { + getHeader () { + return '' + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, 'Accept-Encoding') + } + } + + addAcceptEncodingToVary(replyMock) +}) + +test('Should have no issues with values containing dashes', t => { + t.plan(2) + + const addXFooToVary = createAddFieldnameToVary('X-Foo') + const replyMock = { + value: 'Accept-Encoding', + getHeader () { + return this.value + }, + header (name, value) { + t.assert.deepStrictEqual(name, 'Vary') + t.assert.deepStrictEqual(value, 'Accept-Encoding, X-Foo') + this.value = value + } + } + + addXFooToVary(replyMock) + addXFooToVary(replyMock) +}) + +test('Should ignore the header as value for vary if it is already in vary', t => { + t.plan(1) + + const addOriginToVary = createAddFieldnameToVary('Origin') + const replyMock = { + getHeader () { + return 'Origin' + }, + header () { + t.fail('Should not be here') + } + } + addOriginToVary(replyMock) + addOriginToVary(replyMock) + + t.assert.ok(true) // equalivant to tap t.pass() +}) + +test('parse', t => { + t.plan(18) + t.assert.deepStrictEqual(parse(''), []) + t.assert.deepStrictEqual(parse('a'), ['a']) + t.assert.deepStrictEqual(parse('a,b'), ['a', 'b']) + t.assert.deepStrictEqual(parse(' a,b'), ['a', 'b']) + t.assert.deepStrictEqual(parse('a,b '), ['a', 'b']) + t.assert.deepStrictEqual(parse('a,b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('A,b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a,b,c,'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a,b,c, '), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse(',a,b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse(' ,a,b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a,,b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a,,,b,,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a, b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a, b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a, , b,c'), ['a', 'b', 'c']) + t.assert.deepStrictEqual(parse('a, , b,c'), ['a', 'b', 'c']) + + // one for the cache + t.assert.deepStrictEqual(parse('A,b,c'), ['a', 'b', 'c']) +}) + +test('createAddFieldnameToVary', async t => { + t.plan(4) + t.assert.strictEqual(typeof createAddFieldnameToVary('valid-header'), 'function') + await t.assert.rejects( + async () => createAddFieldnameToVary('invalid:header'), + (err) => { + t.assert.strictEqual(err.name, 'TypeError') + t.assert.strictEqual(err.message, 'Fieldname contains invalid characters.') + return true + } + ) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/types/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..eab0b1ba66177929766c574ec77c2f62e6c0cfbb --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/types/index.d.ts @@ -0,0 +1,126 @@ +/// + +import { FastifyInstance, FastifyPluginCallback, FastifyRequest, LogLevel } from 'fastify' + +type OriginCallback = (err: Error | null, origin: ValueOrArray) => void +type OriginType = string | boolean | RegExp +type ValueOrArray = T | ArrayOfValueOrArray + +interface ArrayOfValueOrArray extends Array> { +} + +type FastifyCorsPlugin = FastifyPluginCallback< + NonNullable | fastifyCors.FastifyCorsOptionsDelegate +> + +type FastifyCorsHook = + | 'onRequest' + | 'preParsing' + | 'preValidation' + | 'preHandler' + | 'preSerialization' + | 'onSend' + +declare namespace fastifyCors { + export type OriginFunction = (origin: string | undefined, callback: OriginCallback) => void + export type AsyncOriginFunction = (origin: string | undefined) => Promise> + + export interface FastifyCorsOptions { + /** + * Configures the Lifecycle Hook. + */ + hook?: FastifyCorsHook; + + /** + * Configures the delegate function. + */ + delegator?: FastifyCorsOptionsDelegate; + + /** + * Configures the Access-Control-Allow-Origin CORS header. + */ + origin?: ValueOrArray | fastifyCors.AsyncOriginFunction | fastifyCors.OriginFunction; + /** + * Configures the Access-Control-Allow-Credentials CORS header. + * Set to true to pass the header, otherwise it is omitted. + */ + credentials?: boolean; + /** + * Configures the Access-Control-Expose-Headers CORS header. + * Expects a comma-delimited string (ex: 'Content-Range,X-Content-Range') + * or an array (ex: ['Content-Range', 'X-Content-Range']). + * If not specified, no custom headers are exposed. + */ + exposedHeaders?: string | string[]; + /** + * Configures the Access-Control-Allow-Headers CORS header. + * Expects a comma-delimited string (ex: 'Content-Type,Authorization') + * or an array (ex: ['Content-Type', 'Authorization']). If not + * specified, defaults to reflecting the headers specified in the + * request's Access-Control-Request-Headers header. + */ + allowedHeaders?: string | string[]; + /** + * Configures the Access-Control-Allow-Methods CORS header. + * Expects a comma-delimited string (ex: 'GET,PUT,POST') or an array (ex: ['GET', 'PUT', 'POST']). + */ + methods?: string | string[]; + /** + * Configures the Access-Control-Max-Age CORS header. + * Set to an integer to pass the header, otherwise it is omitted. + */ + maxAge?: number; + /** + * Configures the Cache-Control header for CORS preflight responses. + * Set to an integer to pass the header as `Cache-Control: max-age=${cacheControl}`, + * or set to a string to pass the header as `Cache-Control: ${cacheControl}` (fully define + * the header value), otherwise the header is omitted. + */ + cacheControl?: number | string; + /** + * Pass the CORS preflight response to the route handler (default: false). + */ + preflightContinue?: boolean; + /** + * Provides a status code to use for successful OPTIONS requests, + * since some legacy browsers (IE11, various SmartTVs) choke on 204. + */ + optionsSuccessStatus?: number; + /** + * Pass the CORS preflight response to the route handler (default: true). + */ + preflight?: boolean; + /** + * Enforces strict requirement of the CORS preflight request headers (Access-Control-Request-Method and Origin). + * Preflight requests without the required headers will result in 400 errors when set to `true` (default: `true`). + */ + strictPreflight?: boolean; + /** + * Hide options route from the documentation built using fastify-swagger (default: true). + */ + hideOptionsRoute?: boolean; + + /** + * Sets the Fastify log level specifically for the internal OPTIONS route + * used to handle CORS preflight requests. For example, setting this to `'silent'` + * will prevent these requests from being logged. + * Useful for reducing noise in application logs. + * Default: inherits Fastify's global log level. + */ + logLevel?: LogLevel; + } + + export interface FastifyCorsOptionsDelegateCallback { (req: FastifyRequest, cb: (error: Error | null, corsOptions?: FastifyCorsOptions) => void): void } + export interface FastifyCorsOptionsDelegatePromise { (req: FastifyRequest): Promise } + export type FastifyCorsOptionsDelegate = FastifyCorsOptionsDelegateCallback | FastifyCorsOptionsDelegatePromise + export type FastifyPluginOptionsDelegate = (instance: FastifyInstance) => T + + export const fastifyCors: FastifyCorsPlugin + export { fastifyCors as default } +} + +declare function fastifyCors ( + ...params: Parameters +): ReturnType + +export = fastifyCors diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/types/index.test-d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/types/index.test-d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4040e6666a0656edf01db4b08a1ddc400764f4f1 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/cors/types/index.test-d.ts @@ -0,0 +1,388 @@ +import fastify, { FastifyRequest } from 'fastify' +import { expectType } from 'tsd' +import fastifyCors, { + AsyncOriginFunction, + FastifyCorsOptions, + FastifyCorsOptionsDelegate, + FastifyCorsOptionsDelegatePromise, + FastifyPluginOptionsDelegate, + OriginFunction +} from '..' + +const app = fastify() + +app.register(fastifyCors) + +app.register(fastifyCors, { + origin: true, + allowedHeaders: 'authorization,content-type', + methods: 'GET,POST,PUT,PATCH,DELETE,OPTIONS', + credentials: true, + exposedHeaders: 'authorization', + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +app.register(fastifyCors, { + origin: true, + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 'public, max-age=3500', + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +app.register(fastifyCors, { + origin: '*', + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +app.register(fastifyCors, { + origin: /\*/, + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +app.register(fastifyCors, { + origin: ['*', 'something'], + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +app.register(fastifyCors, { + origin: [/\*/, /something/], + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +const corsDelegate: OriginFunction = (origin, cb) => { + if (origin === undefined || /localhost/.test(origin)) { + cb(null, true) + return + } + cb(new Error(), false) +} + +app.register(fastifyCors, { + origin: corsDelegate, + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +const asyncCorsDelegate: OriginFunction = async (origin) => { + if (origin === undefined || /localhost/.test(origin)) { + return true + } + return false +} + +app.register(fastifyCors, { + origin: asyncCorsDelegate, + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +app.register(fastifyCors, { + origin: (_origin, cb) => cb(null, true) +}) + +app.register(fastifyCors, { + origin: (_origin, cb) => cb(null, '*') +}) + +app.register(fastifyCors, { + origin: (_origin, cb) => cb(null, /\*/) +}) + +const appHttp2 = fastify({ http2: true }) + +appHttp2.register(fastifyCors) + +appHttp2.register(fastifyCors, { + origin: true, + allowedHeaders: 'authorization,content-type', + methods: 'GET,POST,PUT,PATCH,DELETE,OPTIONS', + credentials: true, + exposedHeaders: 'authorization', + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false, + logLevel: 'silent' +}) + +appHttp2.register(fastifyCors, { + origin: true, + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +appHttp2.register(fastifyCors, { + origin: '*', + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +appHttp2.register(fastifyCors, { + origin: /\*/, + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +appHttp2.register(fastifyCors, { + origin: ['*', 'something'], + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +appHttp2.register(fastifyCors, { + origin: [/\*/, /something/], + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +appHttp2.register(fastifyCors, { + origin: (origin: string | undefined, cb: (err: Error | null, allow: boolean) => void) => { + if (origin === undefined || /localhost/.test(origin)) { + cb(null, true) + return + } + cb(new Error(), false) + }, + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false +}) + +appHttp2.register(fastifyCors, (): FastifyCorsOptionsDelegate => (_req, cb) => { + cb(null, { + origin: [/\*/, /something/], + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false + }) +}) + +appHttp2.register(fastifyCors, (): FastifyCorsOptionsDelegatePromise => () => { + return Promise.resolve({ + origin: [/\*/, /something/], + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false + }) +}) + +const delegate: FastifyPluginOptionsDelegate = () => async () => { + return { + origin: [/\*/, /something/], + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 13000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false + } +} + +appHttp2.register(fastifyCors, { + hook: 'onRequest' +}) +appHttp2.register(fastifyCors, { + hook: 'preParsing' +}) +appHttp2.register(fastifyCors, { + hook: 'preValidation' +}) +appHttp2.register(fastifyCors, { + hook: 'preHandler' +}) +appHttp2.register(fastifyCors, { + hook: 'preSerialization' +}) +appHttp2.register(fastifyCors, { + hook: 'onSend' +}) + +appHttp2.register(fastifyCors, { + hook: 'preParsing', + delegator: (req, cb) => { + if (req.url.startsWith('/some-value')) { + cb(new Error()) + } + cb(null, { + origin: [/\*/, /something/], + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 12000, + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false + }) + } +}) + +appHttp2.register(fastifyCors, { + hook: 'preParsing', + delegator: async (_req: FastifyRequest): Promise => { + return { + origin: [/\*/, /something/], + allowedHeaders: ['authorization', 'content-type'], + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], + credentials: true, + exposedHeaders: ['authorization'], + maxAge: 13000, + cacheControl: 'public, max-age=3500', + preflightContinue: false, + optionsSuccessStatus: 200, + preflight: false, + strictPreflight: false + } + } +}) + +appHttp2.register(fastifyCors, delegate) + +appHttp2.register(fastifyCors, { + hook: 'preParsing', + origin: function (origin, cb) { + expectType(origin) + cb(null, false) + }, +}) + +const asyncOriginFn: AsyncOriginFunction = async function (origin): Promise { + expectType(origin) + return false +} + +appHttp2.register(fastifyCors, { + hook: 'preParsing', + origin: asyncOriginFn, +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/.github/dependabot.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..35d66ca7ac75f125b9c9c5b3dee0987fdfca4a45 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 + + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/.github/workflows/ci.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..fd45202abff682784e3a60d54fbfee567d304b26 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/.github/workflows/ci.yml @@ -0,0 +1,28 @@ +name: CI + +on: + push: + branches: + - main + - next + - 'v*' + paths-ignore: + - 'docs/**' + - '*.md' + pull_request: + paths-ignore: + - 'docs/**' + - '*.md' + +permissions: + contents: read + +jobs: + test: + permissions: + contents: write + pull-requests: write + uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5 + with: + license-check: true + lint: true diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/benchmarks/create.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/benchmarks/create.js new file mode 100644 index 0000000000000000000000000000000000000000..bb9abbfe1b34856cb81ea8fd7157ef8726c671fa --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/benchmarks/create.js @@ -0,0 +1,9 @@ +'use strict' + +const benchmark = require('benchmark') +const createError = require('..') + +new benchmark.Suite() + .add('create FastifyError', function () { createError('CODE', 'Not available') }, { minSamples: 100 }) + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/benchmarks/instantiate.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/benchmarks/instantiate.js new file mode 100644 index 0000000000000000000000000000000000000000..890aaf0ac18f6ba3cb75e36d58421e1ac8f84673 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/benchmarks/instantiate.js @@ -0,0 +1,18 @@ +'use strict' + +const benchmark = require('benchmark') +const createError = require('..') + +const FastifyError = createError('CODE', 'Not available') +const FastifyError1 = createError('CODE', 'Not %s available') +const FastifyError2 = createError('CODE', 'Not %s available %s') + +const cause = new Error('cause') +new benchmark.Suite() + .add('instantiate Error', function () { new Error() }, { minSamples: 100 }) // eslint-disable-line no-new + .add('instantiate FastifyError', function () { new FastifyError() }, { minSamples: 100 }) // eslint-disable-line no-new + .add('instantiate FastifyError arg 1', function () { new FastifyError1('q') }, { minSamples: 100 }) // eslint-disable-line no-new + .add('instantiate FastifyError arg 2', function () { new FastifyError2('qq', 'ss') }, { minSamples: 100 }) // eslint-disable-line no-new + .add('instantiate FastifyError cause', function () { new FastifyError2({ cause }) }, { minSamples: 100 }) // eslint-disable-line no-new + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/benchmarks/no-stack.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/benchmarks/no-stack.js new file mode 100644 index 0000000000000000000000000000000000000000..b626b5c79da786de28356722976d5ed3af0fe958 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/benchmarks/no-stack.js @@ -0,0 +1,13 @@ +'use strict' + +const benchmark = require('benchmark') +const createError = require('..') + +const FastifyError = createError('CODE', 'Not available') +Error.stackTraceLimit = 0 + +new benchmark.Suite() + .add('no-stack instantiate Error', function () { new Error() }, { minSamples: 100 }) // eslint-disable-line no-new + .add('no-stack instantiate FastifyError', function () { new FastifyError() }, { minSamples: 100 }) // eslint-disable-line no-new + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/benchmarks/toString.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/benchmarks/toString.js new file mode 100644 index 0000000000000000000000000000000000000000..119154925ed8f6072c5f670c95ced9a52ca395f7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/benchmarks/toString.js @@ -0,0 +1,11 @@ +'use strict' + +const benchmark = require('benchmark') +const createError = require('..') + +const FastifyError = createError('CODE', 'Not available') + +new benchmark.Suite() + .add('FastifyError toString', function () { new FastifyError().toString() }, { minSamples: 100 }) + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/test/index.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/test/index.test.js new file mode 100644 index 0000000000000000000000000000000000000000..3ad97f6d3941237231d553259daee284e7ca4596 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/test/index.test.js @@ -0,0 +1,232 @@ +'use strict' + +const test = require('node:test') +const { createError, FastifyError } = require('..') + +test('Create error with zero parameter', (t) => { + t.plan(6) + + const NewError = createError('CODE', 'Not available') + const err = new NewError() + t.assert.ok(err instanceof Error) + t.assert.equal(err.name, 'FastifyError') + t.assert.equal(err.message, 'Not available') + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, 500) + t.assert.ok(err.stack) +}) + +test('Create error with 1 parameter', (t) => { + t.plan(6) + + const NewError = createError('CODE', 'hey %s') + const err = new NewError('alice') + t.assert.equal(err.name, 'FastifyError') + t.assert.ok(err instanceof Error) + t.assert.equal(err.message, 'hey alice') + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, 500) + t.assert.ok(err.stack) +}) + +test('Create error with 1 parameter set to undefined', (t) => { + t.plan(1) + + const NewError = createError('CODE', 'hey %s') + const err = new NewError(undefined) + t.assert.equal(err.message, 'hey undefined') +}) + +test('Create error with 2 parameters', (t) => { + t.plan(6) + + const NewError = createError('CODE', 'hey %s, I like your %s') + const err = new NewError('alice', 'attitude') + t.assert.ok(err instanceof Error) + t.assert.equal(err.name, 'FastifyError') + t.assert.equal(err.message, 'hey alice, I like your attitude') + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, 500) + t.assert.ok(err.stack) +}) + +test('Create error with 2 parameters set to undefined', (t) => { + t.plan(1) + + const NewError = createError('CODE', 'hey %s, I like your %s') + const err = new NewError(undefined, undefined) + t.assert.equal(err.message, 'hey undefined, I like your undefined') +}) + +test('Create error with 3 parameters', (t) => { + t.plan(6) + + const NewError = createError('CODE', 'hey %s, I like your %s %s') + const err = new NewError('alice', 'attitude', 'see you') + t.assert.ok(err instanceof Error) + t.assert.equal(err.name, 'FastifyError') + t.assert.equal(err.message, 'hey alice, I like your attitude see you') + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, 500) + t.assert.ok(err.stack) +}) + +test('Create error with 3 parameters set to undefined', (t) => { + t.plan(4) + + const NewError = createError('CODE', 'hey %s, I like your %s %s') + const err = new NewError(undefined, undefined, undefined) + t.assert.equal(err.message, 'hey undefined, I like your undefined undefined') + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, 500) + t.assert.ok(err.stack) +}) + +test('Create error with 4 parameters set to undefined', (t) => { + t.plan(4) + + const NewError = createError('CODE', 'hey %s, I like your %s %s and %s') + const err = new NewError(undefined, undefined, undefined, undefined) + t.assert.equal( + err.message, + 'hey undefined, I like your undefined undefined and undefined' + ) + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, 500) + t.assert.ok(err.stack) +}) + +test('Create error with no statusCode property', (t) => { + t.plan(6) + + const NewError = createError('CODE', 'hey %s', 0) + const err = new NewError('dude') + t.assert.ok(err instanceof Error) + t.assert.equal(err.name, 'FastifyError') + t.assert.equal(err.message, 'hey dude') + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, undefined) + t.assert.ok(err.stack) +}) + +test('Should throw when error code has no fastify code', (t) => { + t.plan(1) + t.assert.throws( + () => createError(), + new Error('Fastify error code must not be empty') + ) +}) + +test('Should throw when error code has no message', (t) => { + t.assert.throws( + () => createError('code'), + new Error('Fastify error message must not be empty') + ) +}) + +test('Create error with different base', (t) => { + t.plan(7) + + const NewError = createError('CODE', 'hey %s', 500, TypeError) + const err = new NewError('dude') + t.assert.ok(err instanceof Error) + t.assert.ok(err instanceof TypeError) + t.assert.equal(err.name, 'FastifyError') + t.assert.equal(err.message, 'hey dude') + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, 500) + t.assert.ok(err.stack) +}) + +test('Create error with different base (no stack) (global)', (t) => { + t.plan(7) + + createError.captureStackTrace = false + const NewError = createError('CODE', 'hey %s', 500, TypeError) + const err = new NewError('dude') + t.assert.ok(err instanceof Error) + t.assert.ok(err instanceof TypeError) + t.assert.equal(err.name, 'FastifyError') + t.assert.equal(err.message, 'hey dude') + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, 500) + t.assert.equal(err.stack, undefined) + createError.captureStackTrace = true +}) + +test('Create error with different base (no stack) (parameter)', (t) => { + t.plan(7) + + const NewError = createError('CODE', 'hey %s', 500, TypeError, false) + const err = new NewError('dude') + t.assert.ok(err instanceof Error) + t.assert.ok(err instanceof TypeError) + t.assert.equal(err.name, 'FastifyError') + t.assert.equal(err.message, 'hey dude') + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, 500) + t.assert.equal(err.stack, undefined) +}) + +test('FastifyError.toString returns code', (t) => { + t.plan(1) + + const NewError = createError('CODE', 'foo') + const err = new NewError() + t.assert.equal(err.toString(), 'FastifyError [CODE]: foo') +}) + +test('Create the error without the new keyword', (t) => { + t.plan(6) + + const NewError = createError('CODE', 'Not available') + const err = NewError() + t.assert.ok(err instanceof Error) + t.assert.equal(err.name, 'FastifyError') + t.assert.equal(err.message, 'Not available') + t.assert.equal(err.code, 'CODE') + t.assert.equal(err.statusCode, 500) + t.assert.ok(err.stack) +}) + +test('Create an error with cause', (t) => { + t.plan(2) + + const cause = new Error('HEY') + const NewError = createError('CODE', 'Not available') + const err = NewError({ cause }) + + t.assert.ok(err instanceof Error) + t.assert.equal(err.cause, cause) +}) + +test('Create an error with cause and message', (t) => { + t.plan(2) + + const cause = new Error('HEY') + const NewError = createError('CODE', 'Not available: %s') + const err = NewError('foo', { cause }) + + t.assert.ok(err instanceof Error) + t.assert.equal(err.cause, cause) +}) + +test('Create an error with last argument null', (t) => { + t.plan(2) + + const cause = new Error('HEY') + const NewError = createError('CODE', 'Not available') + const err = NewError({ cause }, null) + + t.assert.ok(err instanceof Error) + t.assert.ifError(err.cause) +}) + +test('check if FastifyError is instantiable', (t) => { + t.plan(2) + + const err = new FastifyError() + + t.assert.ok(err instanceof FastifyError) + t.assert.ok(err instanceof Error) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/test/instanceof.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/test/instanceof.test.js new file mode 100644 index 0000000000000000000000000000000000000000..34d56fbf92cc1fcb391d8abdb2a543d4f09d0afa --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/test/instanceof.test.js @@ -0,0 +1,263 @@ +'use strict' + +const cp = require('node:child_process') +const fs = require('node:fs') +const path = require('node:path') +const os = require('node:os') +const test = require('node:test') +const { createError, FastifyError } = require('..') + +test('Readme: All errors created with `createError` will be instances of the base error constructor you provided, or `Error` if none was provided.', (t) => { + t.plan(3) + + const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError) + const customError = new CustomError('world') + + t.assert.ok(customError instanceof CustomError) + t.assert.ok(customError instanceof TypeError) + t.assert.ok(customError instanceof Error) +}) + +test('Readme: All instantiated errors will be instances of the `FastifyError` class. The `FastifyError` class can be required from the module directly.', (t) => { + t.plan(1) + + const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError) + const customError = new CustomError('world') + + t.assert.ok(customError instanceof FastifyError) +}) + +test('Readme: It is possible to create a `FastifyError` that extends another `FastifyError`, created by `createError`, while instanceof working correctly.', (t) => { + t.plan(5) + + const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError) + const ChildCustomError = createError('CHILD_ERROR_CODE', 'Hello %s', 500, CustomError) + + const customError = new ChildCustomError('world') + + t.assert.ok(customError instanceof ChildCustomError) + t.assert.ok(customError instanceof CustomError) + t.assert.ok(customError instanceof FastifyError) + t.assert.ok(customError instanceof TypeError) + t.assert.ok(customError instanceof Error) +}) + +test('Readme: Changing the code of an instantiated Error will not change the result of the `instanceof` operator.', (t) => { + t.plan(3) + + const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError) + const AnotherCustomError = createError('ANOTHER_ERROR_CODE', 'Hello %s', 500, CustomError) + + const customError = new CustomError('world') + customError.code = 'ANOTHER_ERROR_CODE' + + t.assert.ok(customError instanceof CustomError) + t.assert.ok(customError instanceof AnotherCustomError === false) + t.assert.ok(customError instanceof FastifyError) +}) + +test('check if createError creates an Error which is instanceof Error', (t) => { + t.plan(3) + + const CustomFastifyError = createError('CODE', 'Not available') + const err = CustomFastifyError() + + t.assert.ok(err instanceof Error) + t.assert.ok(err instanceof SyntaxError === false) + t.assert.ok(err instanceof TypeError === false) +}) + +test('check if createError creates an Error which is instanceof FastifyError', (t) => { + t.plan(4) + + const CustomFastifyError = createError('CODE', 'Not available') + const err = CustomFastifyError() + + t.assert.ok(err instanceof Error) + t.assert.ok(err instanceof FastifyError) + t.assert.ok(err instanceof SyntaxError === false) + t.assert.ok(err instanceof TypeError === false) +}) + +test('check if createError creates an Error with the right BaseConstructor', (t) => { + t.plan(2) + + const CustomFastifyError = createError('CODE', 'Not available', 500, TypeError) + const err = CustomFastifyError() + + t.assert.ok(err instanceof Error) + t.assert.ok(err instanceof TypeError) +}) + +test('check if createError creates an Error with the right BaseConstructor, which is a FastifyError', (t) => { + t.plan(6) + + const BaseFastifyError = createError('CODE', 'Not available', 500, TypeError) + const CustomFastifyError = createError('CODE', 'Not available', 500, BaseFastifyError) + const err = CustomFastifyError() + + t.assert.ok(err instanceof Error) + t.assert.ok(err instanceof TypeError) + t.assert.ok(err instanceof FastifyError) + t.assert.ok(err instanceof BaseFastifyError) + t.assert.ok(err instanceof CustomFastifyError) + t.assert.ok(err instanceof SyntaxError === false) +}) + +// for more information see https://github.com/fastify/fastify-error/pull/86#issuecomment-1301466407 +test('ensure that instanceof works accross different installations of the fastify-error module', async (t) => { + const assertsPlanned = 5 + t.plan(assertsPlanned) + + // We need to create a test environment where fastify-error is installed in two different locations + // and then we will check if the error created in one location is instanceof the error created in the other location + // This is done by creating a test directory with the following structure: + + // / + // ├── index.js + // └── node_modules/ + // ├── fastify-error/ + // │ └── index.js + // └── dep/ + // ├── index.js + // └── node_modules/ + // └── fastify-error/ + // └── index.js + + const testDirectoryPrefix = 'fastify-error-instanceof-test-' + + const testCwd = path.resolve(os.tmpdir(), `${testDirectoryPrefix}${Math.random().toString(36).substring(2, 15)}`) + fs.mkdirSync(testCwd, { recursive: true }) + + // Create the index.js. It will be executed as a forked process, so we need to + // use process.send to send messages back to the parent process. + fs.writeFileSync(path.resolve(testCwd, 'index.js'), ` + 'use strict' + + const path = require('node:path') + const { createError, FastifyError } = require('fastify-error') + const { foo } = require('dep') + + const actualPathOfFastifyError = require.resolve('fastify-error') + const expectedPathOfFastifyError = path.resolve('node_modules', 'fastify-error', 'index.js') + + // Ensure that fastify-error is required from the node_modules directory of the test-project + if (actualPathOfFastifyError !== expectedPathOfFastifyError) { + console.error('actualPathOfFastifyError', actualPathOfFastifyError) + console.error('expectedPathOfFastifyError', expectedPathOfFastifyError) + throw new Error('fastify-error should be required from the node_modules directory of the test-project') + } + + const Boom = createError('Boom', 'Boom', 500) + const ChildBoom = createError('ChildBoom', 'Boom', 500, Boom) + const NotChildBoom = createError('NotChildBoom', 'NotChildBoom', 500, Boom) + + try { + foo() + } catch (err) { + process.send(err instanceof Error) + process.send(err instanceof FastifyError) + process.send(err instanceof NotChildBoom) + process.send(err instanceof Boom) + process.send(err instanceof ChildBoom) + } + `) + + // Create /node_modules/fastify-error directory + // Copy the index.js file to the fastify-error directory + fs.mkdirSync(path.resolve(testCwd, 'node_modules', 'fastify-error'), { recursive: true }) + fs.copyFileSync(path.resolve(process.cwd(), 'index.js'), path.resolve(testCwd, 'node_modules', 'fastify-error', 'index.js')) + + // Create /node_modules/dep/node_modules/fastify-error directory + // Copy the index.js to the fastify-error directory + fs.mkdirSync(path.resolve(testCwd, 'node_modules', 'dep', 'node_modules', 'fastify-error'), { recursive: true }) + fs.copyFileSync(path.resolve(process.cwd(), 'index.js'), path.resolve(testCwd, 'node_modules', 'dep', 'node_modules', 'fastify-error', 'index.js')) + + // Create /node_modules/dep/index.js. It will export a function foo which will + // throw an error when called. The error will be an instance of ChildBoom, created + // by the fastify-error module in the node_modules directory of dep. + fs.writeFileSync(path.resolve(testCwd, 'node_modules', 'dep', 'index.js'), ` + 'use strict' + + const path = require('node:path') + const { createError } = require('fastify-error') + + const actualPathOfFastifyError = require.resolve('fastify-error') + const expectedPathOfFastifyError = path.resolve('node_modules', 'dep', 'node_modules', 'fastify-error', 'index.js') + + // Ensure that fastify-error is required from the node_modules directory of the test-project + if (actualPathOfFastifyError !== expectedPathOfFastifyError) { + console.error('actualPathOfFastifyError', actualPathOfFastifyError) + console.error('expectedPathOfFastifyError', expectedPathOfFastifyError) + throw new Error('fastify-error should be required from the node_modules directory of dep') + } + + const Boom = createError('Boom', 'Boom', 500) + const ChildBoom = createError('ChildBoom', 'Boom', 500, Boom) + + module.exports.foo = function foo () { + throw new ChildBoom('foo go Boom') + } + `) + + const finishedPromise = { + promise: undefined, + reject: undefined, + resolve: undefined, + } + + finishedPromise.promise = new Promise((resolve, reject) => { + finishedPromise.resolve = resolve + finishedPromise.reject = reject + }) + + const child = cp.fork(path.resolve(testCwd, 'index.js'), { + cwd: testCwd, + stdio: 'inherit', + env: { + ...process.env, + NODE_OPTIONS: '--no-warnings' + }, + }) + + let messageCount = 0 + child.on('message', message => { + try { + switch (messageCount) { + case 0: + t.assert.strictEqual(message, true, 'instanceof Error') + break + case 1: + t.assert.strictEqual(message, true, 'instanceof FastifyError') + break + case 2: + t.assert.strictEqual(message, false, 'instanceof NotChildBoom') + break + case 3: + t.assert.strictEqual(message, true, 'instanceof Boom') + break + case 4: + t.assert.strictEqual(message, true, 'instanceof ChildBoom') + break + } + if (++messageCount === assertsPlanned) { + finishedPromise.resolve() + } + } catch (err) { + finishedPromise.reject(err) + } + }) + + child.on('error', err => { + finishedPromise.reject(err) + }) + + await finishedPromise.promise + + // Cleanup + // As we are creating the test-setup on the fly in the /tmp directory, we can remove it + // safely when we are done. It is not relevant for the test if the deletion fails. + try { + fs.rmSync(testCwd, { recursive: true, force: true }) + } catch {} +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/types/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2e59d9febe28d1cad109f914d95c02551097ec59 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/types/index.d.ts @@ -0,0 +1,49 @@ +declare function createError ( + code: C, + message: string, + statusCode: SC, + Base?: ErrorConstructor, + captureStackTrace?: boolean +): createError.FastifyErrorConstructor<{ code: C, statusCode: SC }, Arg> + +declare function createError ( + code: C, + message: string, + statusCode?: number, + Base?: ErrorConstructor, + captureStackTrace?: boolean +): createError.FastifyErrorConstructor<{ code: C }, Arg> + +declare function createError ( + code: string, + message: string, + statusCode?: number, + Base?: ErrorConstructor, + captureStackTrace?: boolean +): createError.FastifyErrorConstructor<{ code: string }, Arg> + +type CreateError = typeof createError + +declare namespace createError { + export interface FastifyError extends Error { + code: string + name: string + statusCode?: number + } + + export interface FastifyErrorConstructor< + E extends { code: string, statusCode?: number } = { code: string, statusCode?: number }, + T extends unknown[] = [any?, any?, any?] + > { + new(...arg: T): FastifyError & E + (...arg: T): FastifyError & E + readonly prototype: FastifyError & E + } + + export const FastifyError: FastifyErrorConstructor + + export const createError: CreateError + export { createError as default } +} + +export = createError diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/types/index.test-d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/types/index.test-d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a4398d4a452995bea323b67f7f2b041a6332af3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/error/types/index.test-d.ts @@ -0,0 +1,92 @@ +import createError, { FastifyError, FastifyErrorConstructor } from '..' +import { expectType, expectError } from 'tsd' + +const CustomError = createError('ERROR_CODE', 'message') +expectType>(CustomError) +const err = new CustomError() +expectType(err) +expectType<'ERROR_CODE'>(err.code) +expectType(err.message) +expectType(err.statusCode) + +const CustomErrorNoStackTrace = createError('ERROR_CODE', 'message', undefined, undefined, false) +expectType>(CustomErrorNoStackTrace) +const errNoStackTrace = new CustomErrorNoStackTrace() +expectType(errNoStackTrace) +expectType<'ERROR_CODE'>(errNoStackTrace.code) +expectType(errNoStackTrace.message) +expectType(errNoStackTrace.statusCode) + +const CustomTypedError = createError('OTHER_CODE', 'message', 400) +expectType>(CustomTypedError) +const typed = new CustomTypedError() +expectType(typed) +expectType<'OTHER_CODE'>(typed.code) +expectType(typed.message) +expectType<400>(typed.statusCode) + +/* eslint-disable no-new */ +const CustomTypedArgError = createError<[string]>('OTHER_CODE', 'expect %s message', 400) +CustomTypedArgError('a') +expectError(CustomTypedArgError('a', 'b')) +expectError(new CustomTypedArgError('a', 'b')) +expectError(CustomTypedArgError(1)) +expectError(new CustomTypedArgError(1)) + +const CustomTypedArgError2 = createError('OTHER_CODE', 'expect %s message', 400) +CustomTypedArgError2('a') +expectError(CustomTypedArgError2('a', 'b')) +expectError(new CustomTypedArgError2('a', 'b')) +expectError(CustomTypedArgError2(1)) +expectError(new CustomTypedArgError2(1)) + +const CustomTypedArgError3 = createError('OTHER_CODE', 'expect %s message but got %s', 400) +expectError(CustomTypedArgError3('a')) +CustomTypedArgError3('a', 'b') +new CustomTypedArgError3('a', 'b') +expectError(CustomTypedArgError3(1)) +expectError(new CustomTypedArgError3(1)) +expectError(new CustomTypedArgError3(1, 2)) +expectError(new CustomTypedArgError3('1', 2)) +expectError(new CustomTypedArgError3(1, '2')) + +const CustomTypedArgError4 = createError('OTHER_CODE', 'expect %s message but got %s', 400) +expectError(CustomTypedArgError4('a')) +CustomTypedArgError4('a', 'b') +new CustomTypedArgError4('a', 'b') +expectError(CustomTypedArgError4(1)) +expectError(new CustomTypedArgError4(1)) +expectError(new CustomTypedArgError4(1, 2)) +expectError(new CustomTypedArgError4('1', 2)) +expectError(new CustomTypedArgError4(1, '2')) + +const CustomTypedArgError5 = createError<[string, string, string, string]>('OTHER_CODE', 'expect %s message but got %s. Please contact %s by emailing to %s', 400) +expectError(CustomTypedArgError5('a')) +expectError(new CustomTypedArgError5('a', 'b')) +expectError(new CustomTypedArgError5('a', 'b', 'c')) +CustomTypedArgError5('a', 'b', 'c', 'd') +expectError(new CustomTypedArgError5('a', 'b', 'c', 'd', 'e')) + +const CustomTypedArgError6 = createError('OTHER_CODE', 'expect %s message but got %s. Please contact %s by emailing to %s', 400) +expectError(CustomTypedArgError6('a')) +expectError(new CustomTypedArgError6('a', 'b')) +expectError(new CustomTypedArgError6('a', 'b', 'c')) +CustomTypedArgError6('a', 'b', 'c', 'd') +expectError(new CustomTypedArgError6('a', 'b', 'c', 'd', 'e')) + +const CustomErrorWithErrorConstructor = createError('ERROR_CODE', 'message', 500, TypeError) +expectType>(CustomErrorWithErrorConstructor) +CustomErrorWithErrorConstructor({ cause: new Error('Error') }) +const customErrorWithErrorConstructor = CustomErrorWithErrorConstructor() +if (customErrorWithErrorConstructor instanceof FastifyError) { + expectType<'ERROR_CODE'>(customErrorWithErrorConstructor.code) + expectType(customErrorWithErrorConstructor.message) + expectType<500>(customErrorWithErrorConstructor.statusCode) +} + +const error = new FastifyError('ERROR_CODE', 'message', 500) +if (error instanceof FastifyError) { + expectType(error.code) + expectType(error.message) + expectType(error.statusCode) +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.github/dependabot.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..35d66ca7ac75f125b9c9c5b3dee0987fdfca4a45 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 + + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.github/workflows/ci.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..fd45202abff682784e3a60d54fbfee567d304b26 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/.github/workflows/ci.yml @@ -0,0 +1,28 @@ +name: CI + +on: + push: + branches: + - main + - next + - 'v*' + paths-ignore: + - 'docs/**' + - '*.md' + pull_request: + paths-ignore: + - 'docs/**' + - '*.md' + +permissions: + contents: read + +jobs: + test: + permissions: + contents: write + pull-requests: write + uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5 + with: + license-check: true + lint: true diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/test/duplicate-schema.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/test/duplicate-schema.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2acaa24026b26ff0b7ce43c506e6fc79025e6cdd --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/test/duplicate-schema.test.js @@ -0,0 +1,26 @@ +'use strict' + +const { test } = require('node:test') +const FjsCompiler = require('../index') + +test('Use input schema duplicate in the externalSchemas', async t => { + t.plan(1) + const externalSchemas = { + schema1: { + $id: 'schema1', + type: 'number' + }, + schema2: { + $id: 'schema2', + type: 'string' + } + } + + const factory = FjsCompiler() + const compiler = factory(externalSchemas) + + compiler({ schema: externalSchemas.schema1 }) + compiler({ schema: externalSchemas.schema2 }) + + t.assert.ok(true) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/test/plugin.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/test/plugin.test.js new file mode 100644 index 0000000000000000000000000000000000000000..26ca0f5f450c7695059725aeb4acea5c5b20fc3e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/test/plugin.test.js @@ -0,0 +1,78 @@ +'use strict' + +const { test } = require('node:test') +const fastify = require('fastify') +const FjsCompiler = require('../index') + +const echo = async (req) => { return req.body } + +const sampleSchema = Object.freeze({ + $id: 'example1', + type: 'object', + properties: { + name: { type: 'string' } + } +}) + +const externalSchemas1 = Object.freeze({}) +const externalSchemas2 = Object.freeze({ + foo: { + $id: 'foo', + type: 'object', + properties: { + name: { type: 'string' } + } + } +}) + +const fastifyFjsOptionsDefault = Object.freeze({}) + +test('basic usage', t => { + t.plan(1) + const factory = FjsCompiler() + const compiler = factory(externalSchemas1, fastifyFjsOptionsDefault) + const serializeFunc = compiler({ schema: sampleSchema }) + const result = serializeFunc({ name: 'hello' }) + t.assert.equal(result, '{"name":"hello"}') +}) + +test('fastify integration', async t => { + const factory = FjsCompiler() + + const app = fastify({ + serializerOpts: { + rounding: 'ceil' + }, + schemaController: { + compilersFactory: { + buildSerializer: factory + } + } + }) + + app.addSchema(externalSchemas2.foo) + + app.post('/', { + handler: echo, + schema: { + response: { + 200: { + $ref: 'foo#' + } + } + } + }) + + const res = await app.inject({ + url: '/', + method: 'POST', + payload: { + version: '1', + foo: 'this is not a number', + name: 'serialize me' + } + }) + + t.assert.equal(res.statusCode, 200) + t.assert.deepStrictEqual(res.json(), { name: 'serialize me' }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/test/standalone.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/test/standalone.test.js new file mode 100644 index 0000000000000000000000000000000000000000..6ecdc1714e2e1809c6a6fee7ddb1d3b0feab5cc2 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/test/standalone.test.js @@ -0,0 +1,230 @@ +'use strict' + +const fs = require('node:fs') +const path = require('node:path') +const { test } = require('node:test') +const fastify = require('fastify') +const sanitize = require('sanitize-filename') + +const { StandaloneSerializer: FjsStandaloneCompiler } = require('../') + +const generatedFileNames = [] + +function generateFileName (routeOpts) { + const fileName = `/fjs-generated-${sanitize(routeOpts.schema.$id)}-${routeOpts.method}-${routeOpts.httpPart}-${sanitize(routeOpts.url)}.js` + generatedFileNames.push(fileName) + return fileName +} + +test('standalone', async t => { + t.plan(5) + + t.after(async () => { + for (const fileName of generatedFileNames) { + try { + await fs.promises.unlink(path.join(__dirname, fileName)) + } catch {} + } + }) + + t.test('errors', t => { + t.plan(2) + t.assert.throws(() => { + FjsStandaloneCompiler() + }, 'missing restoreFunction') + t.assert.throws(() => { + FjsStandaloneCompiler({ readMode: false }) + }, 'missing storeFunction') + }) + + t.test('generate standalone code', t => { + t.plan(5) + + const base = { + $id: 'urn:schema:base', + definitions: { + hello: { type: 'string' } + }, + type: 'object', + properties: { + hello: { $ref: '#/definitions/hello' } + } + } + + const refSchema = { + $id: 'urn:schema:ref', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:base#/definitions/hello' } + } + } + + const endpointSchema = { + schema: { + $id: 'urn:schema:endpoint', + $ref: 'urn:schema:ref' + } + } + + const schemaMap = { + [base.$id]: base, + [refSchema.$id]: refSchema + } + + const factory = FjsStandaloneCompiler({ + readMode: false, + storeFunction (routeOpts, schemaSerializerCode) { + t.assert.deepStrictEqual(routeOpts, endpointSchema) + t.assert.ok(typeof schemaSerializerCode === 'string') + fs.writeFileSync(path.join(__dirname, '/fjs-generated.js'), schemaSerializerCode) + generatedFileNames.push('/fjs-generated.js') + t.assert.ok('stored the serializer function') + } + }) + + const compiler = factory(schemaMap) + compiler(endpointSchema) + t.assert.ok('compiled the endpoint schema') + + t.test('usage standalone code', t => { + t.plan(3) + const standaloneSerializer = require('./fjs-generated') + t.assert.ok(standaloneSerializer) + + const valid = standaloneSerializer({ hello: 'world' }) + t.assert.deepStrictEqual(valid, JSON.stringify({ hello: 'world' })) + + const invalid = standaloneSerializer({ hello: [] }) + t.assert.deepStrictEqual(invalid, '{"hello":""}') + }) + }) + + t.test('fastify integration - writeMode', async t => { + t.plan(4) + + const factory = FjsStandaloneCompiler({ + readMode: false, + storeFunction (routeOpts, schemaSerializationCode) { + const fileName = generateFileName(routeOpts) + t.assert.ok(routeOpts) + fs.writeFileSync(path.join(__dirname, fileName), schemaSerializationCode) + t.assert.ok(`stored the serializer function ${fileName}`) + }, + restoreFunction () { + t.fail('write mode ON') + } + }) + + const app = buildApp(factory) + await app.ready() + }) + + await t.test('fastify integration - writeMode forces standalone', async t => { + t.plan(4) + + const factory = FjsStandaloneCompiler({ + readMode: false, + storeFunction (routeOpts, schemaSerializationCode) { + const fileName = generateFileName(routeOpts) + t.assert.ok(routeOpts) + fs.writeFileSync(path.join(__dirname, fileName), schemaSerializationCode) + t.assert.ok(`stored the serializer function ${fileName}`) + }, + restoreFunction () { + t.fail('write mode ON') + } + }) + + const app = buildApp(factory, { + mode: 'not-standalone', + rounding: 'ceil' + }) + + await app.ready() + }) + + await t.test('fastify integration - readMode', async t => { + t.plan(6) + + const factory = FjsStandaloneCompiler({ + readMode: true, + storeFunction () { + t.fail('read mode ON') + }, + restoreFunction (routeOpts) { + const fileName = generateFileName(routeOpts) + t.assert.ok(`restore the serializer function ${fileName}}`) + return require(path.join(__dirname, fileName)) + } + }) + + const app = buildApp(factory) + await app.ready() + + let res = await app.inject({ + url: '/foo', + method: 'POST' + }) + t.assert.equal(res.statusCode, 200) + t.assert.equal(res.payload, JSON.stringify({ hello: 'world' })) + + res = await app.inject({ + url: '/bar?lang=it', + method: 'GET' + }) + t.assert.equal(res.statusCode, 200) + t.assert.equal(res.payload, JSON.stringify({ lang: 'en' })) + }) + + function buildApp (factory, serializerOpts) { + const app = fastify({ + exposeHeadRoutes: false, + jsonShorthand: false, + schemaController: { + compilersFactory: { + buildSerializer: factory + } + }, + serializerOpts + }) + + app.addSchema({ + $id: 'urn:schema:foo', + type: 'object', + properties: { + name: { type: 'string' }, + id: { type: 'integer' } + } + }) + + app.post('/foo', { + schema: { + response: { + 200: { + $id: 'urn:schema:response', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:foo#/properties/name' } + } + } + } + } + }, () => { return { hello: 'world' } }) + + app.get('/bar', { + schema: { + response: { + 200: { + $id: 'urn:schema:response:bar', + type: 'object', + properties: { + lang: { type: 'string', enum: ['it', 'en'] } + } + } + } + } + }, () => { return { lang: 'en' } }) + + return app + } +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/types/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..05461351432d028c25868f7ab46f322548cd28ca --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/types/index.d.ts @@ -0,0 +1,41 @@ +import { Options } from 'fast-json-stringify' + +type FastJsonStringifyFactory = () => SerializerSelector.SerializerFactory + +declare namespace SerializerSelector { + export type SerializerFactory = ( + externalSchemas?: unknown, + options?: Options + ) => SerializerCompiler + + export type SerializerCompiler = (routeDef: RouteDefinition) => Serializer + export type Serializer = (doc: any) => string + + export type RouteDefinition = { + method: string; + url: string; + httpStatus: string; + schema?: unknown; + } + + export type StandaloneOptions = StandaloneOptionsReadModeOn | StandaloneOptionsReadModeOff + + export type StandaloneOptionsReadModeOn = { + readMode: true; + restoreFunction?(opts: RouteDefinition): Serializer; + } + + export type StandaloneOptionsReadModeOff = { + readMode?: false | undefined; + storeFunction?(opts: RouteDefinition, schemaSerializationCode: string): void; + } + + export type { Options } + export const SerializerSelector: FastJsonStringifyFactory + export function StandaloneSerializer (options: StandaloneOptions): SerializerFactory + + export { SerializerSelector as default } +} + +declare function SerializerSelector (...params: Parameters): ReturnType +export = SerializerSelector diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/types/index.test-d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/types/index.test-d.ts new file mode 100644 index 0000000000000000000000000000000000000000..018759aadc42c09b683479fbbfc370d0dcb4b119 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/fast-json-stringify-compiler/types/index.test-d.ts @@ -0,0 +1,142 @@ +import { expectAssignable, expectError, expectType } from 'tsd' +import SerializerSelector, { + RouteDefinition, + Serializer, + SerializerCompiler, + SerializerFactory, + SerializerSelector as SerializerSelectorNamed, + StandaloneSerializer, +} from '..' + +/** + * SerializerSelector + */ + +{ + const compiler = SerializerSelector() + expectType(compiler) +} + +{ + const compiler = SerializerSelectorNamed() + expectType(compiler) +} + +{ + const sampleSchema = { + $id: 'example1', + type: 'object', + properties: { + name: { type: 'string' } + } + } + + const externalSchemas1 = {} + + const factory = SerializerSelector() + expectType(factory) + const compiler = factory(externalSchemas1, {}) + expectType(compiler) + const serializeFunc = compiler({ schema: sampleSchema, method: '', url: '', httpStatus: '' }) + expectType(serializeFunc) + + expectType(serializeFunc({ name: 'hello' })) +} + +/** + * StandaloneSerializer + */ + +const reader = StandaloneSerializer({ + readMode: true, + restoreFunction: (route: RouteDefinition) => { + expectAssignable(route) + return {} as Serializer + }, +}) +expectType(reader) + +const writer = StandaloneSerializer({ + readMode: false, + storeFunction: (route: RouteDefinition, code: string) => { + expectAssignable(route) + expectAssignable(code) + }, +}) +expectType(writer) + +{ + const base = { + $id: 'urn:schema:base', + definitions: { + hello: { type: 'string' } + }, + type: 'object', + properties: { + hello: { $ref: '#/definitions/hello' } + } + } + + const refSchema = { + $id: 'urn:schema:ref', + type: 'object', + properties: { + hello: { $ref: 'urn:schema:base#/definitions/hello' } + } + } + + const endpointSchema = { + method: '', + url: '', + httpStatus: '', + schema: { + $id: 'urn:schema:endpoint', + $ref: 'urn:schema:ref' + } + } + + const schemaMap = { + [base.$id]: base, + [refSchema.$id]: refSchema + } + + expectError(StandaloneSerializer({ + readMode: true, + storeFunction () { } + })) + expectError(StandaloneSerializer({ + readMode: false, + restoreFunction () {} + })) + expectError(StandaloneSerializer({ + restoreFunction () {} + })) + + expectType(StandaloneSerializer({ + storeFunction (routeOpts, schemaSerializerCode) { + expectType(routeOpts) + expectType(schemaSerializerCode) + } + })) + + expectType(StandaloneSerializer({ + readMode: true, + restoreFunction (routeOpts) { + expectType(routeOpts) + return {} as Serializer + } + })) + + const factory = StandaloneSerializer({ + readMode: false, + storeFunction (routeOpts, schemaSerializerCode) { + expectType(routeOpts) + expectType(schemaSerializerCode) + } + }) + expectType(factory) + + const compiler = factory(schemaMap) + expectType(compiler) + expectType(compiler(endpointSchema)) +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/forwarded/types/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/forwarded/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ed5fb986ba0f12de70e2a4b7bb0fe161e7210bc8 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/forwarded/types/index.d.ts @@ -0,0 +1,14 @@ +import { IncomingMessage } from 'http'; + +type Forwarded = (req: IncomingMessage) => string[] + +declare namespace forwarded { + export const forwarded: Forwarded + export { forwarded as default } +} + +/** + * Get all addresses in the request used in the `X-Forwarded-For` header. + */ +declare function forwarded(...params: Parameters): ReturnType +export = forwarded diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/.github/dependabot.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..dfa7fa6cba823110c8476a4b4ebcc07cfda12535 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 + + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "weekly" + open-pull-requests-limit: 10 diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/.github/workflows/ci.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..3aa613009753c4be21cc8f212f1495d70427f133 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/.github/workflows/ci.yml @@ -0,0 +1,23 @@ +name: CI + +on: + push: + branches: + - main + - master + - next + - 'v*' + paths-ignore: + - 'docs/**' + - '*.md' + pull_request: + paths-ignore: + - 'docs/**' + - '*.md' + +jobs: + test: + uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5 + with: + license-check: true + lint: true diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/lib/errors.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/lib/errors.js new file mode 100644 index 0000000000000000000000000000000000000000..0a14792e73e87a7289de5bf5452b5751de562a80 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/lib/errors.js @@ -0,0 +1,36 @@ +'use strict' + +class MergeError extends Error { + constructor (keyword, schemas) { + super() + this.name = 'JsonSchemaMergeError' + this.code = 'JSON_SCHEMA_MERGE_ERROR' + this.message = `Failed to merge "${keyword}" keyword schemas.` + this.schemas = schemas + } +} + +class ResolverNotFoundError extends Error { + constructor (keyword, schemas) { + super() + this.name = 'JsonSchemaMergeError' + this.code = 'JSON_SCHEMA_MERGE_ERROR' + this.message = `Resolver for "${keyword}" keyword not found.` + this.schemas = schemas + } +} + +class InvalidOnConflictOptionError extends Error { + constructor (onConflict) { + super() + this.name = 'JsonSchemaMergeError' + this.code = 'JSON_SCHEMA_MERGE_ERROR' + this.message = `Invalid "onConflict" option: "${onConflict}".` + } +} + +module.exports = { + MergeError, + ResolverNotFoundError, + InvalidOnConflictOptionError +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/lib/resolvers.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/lib/resolvers.js new file mode 100644 index 0000000000000000000000000000000000000000..4458838ed7040c8e98f293937e0ddc702203b2b6 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/lib/resolvers.js @@ -0,0 +1,127 @@ +'use strict' + +const { dequal: deepEqual } = require('dequal') +const { MergeError } = require('./errors') + +function _arraysIntersection (arrays) { + let intersection = arrays[0] + for (let i = 1; i < arrays.length; i++) { + intersection = intersection.filter( + value => arrays[i].includes(value) + ) + } + return intersection +} + +function arraysIntersection (keyword, values, mergedSchema) { + const intersection = _arraysIntersection(values) + if (intersection.length === 0) { + throw new MergeError(keyword, values) + } + mergedSchema[keyword] = intersection +} + +function hybridArraysIntersection (keyword, values, mergedSchema) { + for (let i = 0; i < values.length; i++) { + if (!Array.isArray(values[i])) { + values[i] = [values[i]] + } + } + + const intersection = _arraysIntersection(values) + if (intersection.length === 0) { + throw new MergeError(keyword, values) + } + + if (intersection.length === 1) { + mergedSchema[keyword] = intersection[0] + } else { + mergedSchema[keyword] = intersection + } +} + +function arraysUnion (keyword, values, mergedSchema) { + const union = [] + + for (const array of values) { + for (const value of array) { + if (!union.includes(value)) { + union.push(value) + } + } + } + + mergedSchema[keyword] = union +} + +function minNumber (keyword, values, mergedSchema) { + mergedSchema[keyword] = Math.min(...values) +} + +function maxNumber (keyword, values, mergedSchema) { + mergedSchema[keyword] = Math.max(...values) +} + +function commonMultiple (keyword, values, mergedSchema) { + const gcd = (a, b) => (!b ? a : gcd(b, a % b)) + const lcm = (a, b) => (a * b) / gcd(a, b) + + let scale = 1 + for (const value of values) { + while (value * scale % 1 !== 0) { + scale *= 10 + } + } + + let multiple = values[0] * scale + for (const value of values) { + multiple = lcm(multiple, value * scale) + } + + mergedSchema[keyword] = multiple / scale +} + +function allEqual (keyword, values, mergedSchema) { + const firstValue = values[0] + for (let i = 1; i < values.length; i++) { + if (!deepEqual(values[i], firstValue)) { + throw new MergeError(keyword, values) + } + } + mergedSchema[keyword] = firstValue +} + +function skip () {} + +function booleanAnd (keyword, values, mergedSchema) { + for (const value of values) { + if (value === false) { + mergedSchema[keyword] = false + return + } + } + mergedSchema[keyword] = true +} + +function booleanOr (keyword, values, mergedSchema) { + for (const value of values) { + if (value === true) { + mergedSchema[keyword] = true + return + } + } + mergedSchema[keyword] = false +} + +module.exports = { + arraysIntersection, + hybridArraysIntersection, + arraysUnion, + minNumber, + maxNumber, + commonMultiple, + allEqual, + booleanAnd, + booleanOr, + skip +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/additional-items.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/additional-items.test.js new file mode 100644 index 0000000000000000000000000000000000000000..707450f607b27fb399c5bd565293deb62a069f90 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/additional-items.test.js @@ -0,0 +1,164 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and additionalItems = false keyword', () => { + const schema1 = { type: 'array' } + const schema2 = { + type: 'array', + additionalItems: false + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + additionalItems: false + }) +}) + +test('should merge two schemas with boolean additionalItems', () => { + const schema1 = { + type: 'array', + additionalItems: true + } + const schema2 = { + type: 'array', + additionalItems: false + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + additionalItems: false + }) +}) + +test('should merge additionalItems schema with false value', () => { + const schema1 = { + type: 'array', + additionalItems: { + type: 'string' + } + } + const schema2 = { + type: 'array', + additionalItems: false + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + additionalItems: false + }) +}) + +test('should merge additionalItems schema with true value', () => { + const schema1 = { + type: 'array', + additionalItems: { + type: 'string' + } + } + const schema2 = { + type: 'array', + additionalItems: true + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + additionalItems: { + type: 'string' + } + }) +}) + +test('should merge two additionalItems schemas', () => { + const schema1 = { + type: 'array', + additionalItems: { + type: 'string' + } + } + const schema2 = { + type: 'array', + additionalItems: { + type: 'string', minLength: 1 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + additionalItems: { + type: 'string', minLength: 1 + } + }) +}) + +test('should merge additionalItems with items array', () => { + const schema1 = { + type: 'array', + items: [ + { type: 'string', const: 'foo1' }, + { type: 'string', const: 'foo2' }, + { type: 'string', const: 'foo3' } + ] + } + const schema2 = { + type: 'array', + additionalItems: { + type: 'string', minLength: 42 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + items: [ + { type: 'string', const: 'foo1', minLength: 42 }, + { type: 'string', const: 'foo2', minLength: 42 }, + { type: 'string', const: 'foo3', minLength: 42 } + ], + additionalItems: { + type: 'string', minLength: 42 + } + }) +}) + +test('should merge items array and additionalItems with items array', () => { + const schema1 = { + type: 'array', + items: [ + { type: 'string', const: 'foo1' }, + { type: 'string', const: 'foo2' }, + { type: 'string', const: 'foo3' } + ] + } + const schema2 = { + type: 'array', + items: [ + { type: 'string', minLength: 1 }, + { type: 'string', minLength: 2 } + ], + additionalItems: { + type: 'string', minLength: 3 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + items: [ + { type: 'string', const: 'foo1', minLength: 1 }, + { type: 'string', const: 'foo2', minLength: 2 }, + { type: 'string', const: 'foo3', minLength: 3 } + ], + additionalItems: { + type: 'string', minLength: 3 + } + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/additional-properties.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/additional-properties.test.js new file mode 100644 index 0000000000000000000000000000000000000000..e4304ac04074ce5aa4bdceb544cba911a5f7ca94 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/additional-properties.test.js @@ -0,0 +1,129 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and additionalProperties=false keyword', () => { + const schema1 = { type: 'object' } + const schema2 = { + type: 'object', + additionalProperties: false + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + additionalProperties: false + }) +}) + +test('should merge two schemas with boolean additionalProperties', () => { + const schema1 = { + type: 'object', + additionalProperties: true + } + const schema2 = { + type: 'object', + additionalProperties: false + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + additionalProperties: false + }) +}) + +test('should merge additionalProperties schema with false value', () => { + const schema1 = { + type: 'object', + additionalProperties: { + type: 'string' + } + } + const schema2 = { + type: 'object', + additionalProperties: false + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + additionalProperties: false + }) +}) + +test('should merge additionalProperties schema with true value', () => { + const schema1 = { + type: 'object', + additionalProperties: { + type: 'string' + } + } + const schema2 = { + type: 'object', + additionalProperties: true + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + additionalProperties: { + type: 'string' + } + }) +}) + +test('should merge two additionalProperties schemas', () => { + const schema1 = { + type: 'object', + additionalProperties: { + type: 'string' + } + } + const schema2 = { + type: 'object', + additionalProperties: { + type: 'string', minLength: 1 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + additionalProperties: { + type: 'string', minLength: 1 + } + }) +}) + +test('should merge two additionalProperties and properties schemas', () => { + const schema1 = { + type: 'object', + additionalProperties: { + type: 'string' + } + } + const schema2 = { + type: 'object', + properties: { + foo: { type: ['string', 'number'] } + }, + additionalProperties: { + type: 'string', minLength: 1 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string' } + }, + additionalProperties: { + type: 'string', minLength: 1 + } + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/all-of.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/all-of.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2b2acef7eb0d040b4af2cfbcb6050cf3710c7038 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/all-of.test.js @@ -0,0 +1,43 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and allOf keyword', () => { + const schema1 = {} + const schema2 = { + allOf: [ + { type: 'string', const: 'foo' } + ] + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + allOf: [ + { type: 'string', const: 'foo' } + ] + }) +}) + +test('should merge schemas with allOfs schemas', () => { + const schema1 = { + allOf: [ + { type: 'number', minimum: 0 } + ] + } + const schema2 = { + allOf: [ + { type: 'string', const: 'foo' } + ] + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + allOf: [ + { type: 'number', minimum: 0 }, + { type: 'string', const: 'foo' } + ] + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/any-of.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/any-of.test.js new file mode 100644 index 0000000000000000000000000000000000000000..98b3a21e71db3f47847e6dc7cef143dff0504cae --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/any-of.test.js @@ -0,0 +1,81 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and anyOf keyword', () => { + const schema1 = {} + const schema2 = { + anyOf: [ + { type: 'string', const: 'foo' } + ] + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + anyOf: [ + { type: 'string', const: 'foo' } + ] + }) +}) + +test('should merge two schemas with anyOfs schemas', () => { + const schema1 = { + anyOf: [ + { type: 'string', enum: ['foo1', 'foo2', 'foo3'] }, + { type: 'string', enum: ['foo3', 'foo4', 'foo5'] } + ] + } + const schema2 = { + anyOf: [ + { type: 'string', enum: ['foo2', 'foo3', 'foo4'] }, + { type: 'string', enum: ['foo3', 'foo6', 'foo7'] } + ] + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + anyOf: [ + { type: 'string', enum: ['foo2', 'foo3'] }, + { type: 'string', enum: ['foo3'] }, + { type: 'string', enum: ['foo3', 'foo4'] }, + { type: 'string', enum: ['foo3'] } + ] + }) +}) + +test('should merge three schemas with anyOfs schemas', () => { + const schema1 = { + anyOf: [ + { type: 'string', enum: ['foo1', 'foo2', 'foo3', 'foo4'] }, + { type: 'string', enum: ['foo3', 'foo4', 'foo5', 'foo7'] } + ] + } + const schema2 = { + anyOf: [ + { type: 'string', enum: ['foo2', 'foo3', 'foo4', 'foo5'] }, + { type: 'string', enum: ['foo3', 'foo6', 'foo7', 'foo8'] } + ] + } + + const schema3 = { + anyOf: [ + { type: 'string', enum: ['foo1', 'foo3', 'foo5', 'foo7'] }, + { type: 'string', enum: ['foo2', 'foo4', 'foo6', 'foo8'] } + ] + } + + const mergedSchema = mergeSchemas([schema1, schema2, schema3], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + anyOf: [ + { type: 'string', enum: ['foo3'] }, + { type: 'string', enum: ['foo2', 'foo4'] }, + { type: 'string', enum: ['foo3'] }, + { type: 'string', enum: ['foo3', 'foo5'] }, + { type: 'string', enum: ['foo4'] }, + { type: 'string', enum: ['foo3', 'foo7'] } + ] + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/const.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/const.test.js new file mode 100644 index 0000000000000000000000000000000000000000..1b8cfe0dda01ea0380edf8cc99f9e1222e8fd885 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/const.test.js @@ -0,0 +1,58 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and string const keyword', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', const: 'foo' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', const: 'foo' }) +}) + +test('should merge equal string const keywords', () => { + const schema1 = { type: 'string', const: 'foo' } + const schema2 = { type: 'string', const: 'foo' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', const: 'foo' }) +}) + +test('should merge equal object const keywords', () => { + const schema1 = { type: 'string', const: { foo: 'bar' } } + const schema2 = { type: 'string', const: { foo: 'bar' } } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', const: { foo: 'bar' } }) +}) + +test('should throw an error if const string values are different', () => { + const schema1 = { type: 'string', const: 'foo' } + const schema2 = { type: 'string', const: 'bar' } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { defaultResolver }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Failed to merge "const" keyword schemas.', + schemas: ['foo', 'bar'] + }) +}) + +test('should throw an error if const object values are different', () => { + const schema1 = { type: 'object', const: { foo: 'bar' } } + const schema2 = { type: 'object', const: { foo: 'baz' } } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { defaultResolver }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Failed to merge "const" keyword schemas.', + schemas: [{ foo: 'bar' }, { foo: 'baz' }] + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/contains.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/contains.test.js new file mode 100644 index 0000000000000000000000000000000000000000..66efb05b28804c50d20f683c4d6dc0e929bf9fcd --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/contains.test.js @@ -0,0 +1,55 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and contains keyword', () => { + const schema1 = {} + const schema2 = { + type: 'array', + contains: { + type: 'integer', + minimum: 5 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + contains: { + type: 'integer', + minimum: 5 + } + }) +}) + +test('should merge two contains keyword schemas', () => { + const schema1 = { + type: 'array', + contains: { + type: 'integer', + minimum: 5, + maximum: 14 + } + } + const schema2 = { + type: 'array', + contains: { + type: 'integer', + minimum: 9, + maximum: 10 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + contains: { + type: 'integer', + minimum: 9, + maximum: 10 + } + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/custom-resolvers.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/custom-resolvers.test.js new file mode 100644 index 0000000000000000000000000000000000000000..20791881f681bb6d04c6b30f4c8a921035aae474 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/custom-resolvers.test.js @@ -0,0 +1,50 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should use a custom resolver instead of default one', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'number' } + + const mergedSchema = mergeSchemas( + [schema1, schema2], + { + resolvers: { + type: (keyword, values, mergedSchema, schemas) => { + assert.strictEqual(keyword, 'type') + assert.deepStrictEqual(values, ['string', 'number']) + assert.deepStrictEqual(schemas, [schema1, schema2]) + + mergedSchema[keyword] = 'custom-type' + } + }, + defaultResolver + } + ) + assert.deepStrictEqual(mergedSchema, { type: 'custom-type' }) +}) + +test('should use a custom resolver for unknown keyword', () => { + const schema1 = { customKeyword: 'string' } + const schema2 = { customKeyword: 'number' } + + const mergedSchema = mergeSchemas( + [schema1, schema2], + { + resolvers: { + customKeyword: (keyword, values, mergedSchema, schemas) => { + assert.strictEqual(keyword, 'customKeyword') + assert.deepStrictEqual(values, ['string', 'number']) + assert.deepStrictEqual(schemas, [schema1, schema2]) + + mergedSchema[keyword] = 'custom-type' + } + }, + defaultResolver + } + ) + assert.deepStrictEqual(mergedSchema, { customKeyword: 'custom-type' }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/default-resolver.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/default-resolver.test.js new file mode 100644 index 0000000000000000000000000000000000000000..186a13aa4141f18ee01e1dd1f8bd9053abc7ce33 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/default-resolver.test.js @@ -0,0 +1,111 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') + +test('should merge an unknown keyword with an empty schema', () => { + const schema1 = {} + const schema2 = { customKeyword: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2]) + assert.deepStrictEqual(mergedSchema, { customKeyword: 42 }) +}) + +test('should merge two equal unknown keywords', () => { + const schema1 = { customKeyword: 42 } + const schema2 = { customKeyword: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2]) + assert.deepStrictEqual(mergedSchema, { customKeyword: 42 }) +}) + +test('should merge two equal unknown object keywords', () => { + const schema1 = { type: 'string', customKeyword: { foo: 'bar' } } + const schema2 = { type: 'string', customKeyword: { foo: 'bar' } } + + const mergedSchema = mergeSchemas([schema1, schema2]) + assert.deepStrictEqual(mergedSchema, { + type: 'string', + customKeyword: { foo: 'bar' } + }) +}) + +test('should use custom defaultResolver if passed', () => { + const schema1 = { type: 'string', customKeyword: 42 } + const schema2 = { type: 'string', customKeyword: 43 } + + const mergedSchema = mergeSchemas( + [schema1, schema2], + { + defaultResolver: (keyword, values, mergedSchema, schemas) => { + assert.strictEqual(keyword, 'customKeyword') + assert.deepStrictEqual(values, [42, 43]) + assert.deepStrictEqual(schemas, [schema1, schema2]) + + mergedSchema.customKeyword = 'custom-value-42' + } + } + ) + assert.deepStrictEqual(mergedSchema, { + type: 'string', + customKeyword: 'custom-value-42' + }) +}) + +test('should trow an error when merging two different unknown keywords', () => { + const schema1 = { customKeyword: 42 } + const schema2 = { customKeyword: 43 } + + assert.throws(() => { + mergeSchemas([schema1, schema2]) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Resolver for "customKeyword" keyword not found.', + schemas: [42, 43] + }) +}) + +test('should trow an error when merging two different unknown keywords with onConflict = throw', () => { + const schema1 = { customKeyword: 42 } + const schema2 = { customKeyword: 43 } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { onConflict: 'throw' }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Resolver for "customKeyword" keyword not found.', + schemas: [42, 43] + }) +}) + +test('should skip the keyword schemas if onConflict = skip', () => { + const schema1 = { customKeyword: 42 } + const schema2 = { customKeyword: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { onConflict: 'skip' }) + assert.deepStrictEqual(mergedSchema, {}) +}) + +test('should pick first schema if onConflict = first', () => { + const schema1 = { customKeyword: 42 } + const schema2 = { customKeyword: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { onConflict: 'first' }) + assert.deepStrictEqual(mergedSchema, { customKeyword: 42 }) +}) + +test('should throw an error if pass wrong onConflict value', () => { + const schema1 = { customKeyword: 42 } + const schema2 = { customKeyword: 43 } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { onConflict: 'foo' }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Invalid "onConflict" option: "foo".' + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/default.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/default.test.js new file mode 100644 index 0000000000000000000000000000000000000000..a87cbcc51b87ce32e31b86b1c75410b88e9e3bf5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/default.test.js @@ -0,0 +1,50 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and string default keyword', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', default: 'foo' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', default: 'foo' }) +}) + +test('should merge equal string default keywords', () => { + const schema1 = { type: 'string', default: 'foo' } + const schema2 = { type: 'string', default: 'foo' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', default: 'foo' }) +}) + +test('should throw an error if default string values are different', () => { + const schema1 = { type: 'string', default: 'foo' } + const schema2 = { type: 'string', default: 'bar' } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { defaultResolver }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Failed to merge "default" keyword schemas.', + schemas: ['foo', 'bar'] + }) +}) + +test('should throw an error if default object values are different', () => { + const schema1 = { type: 'object', default: { foo: 'bar' } } + const schema2 = { type: 'object', default: { foo: 'baz' } } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { defaultResolver }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Failed to merge "default" keyword schemas.', + schemas: [{ foo: 'bar' }, { foo: 'baz' }] + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/definitions.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/definitions.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2f90280b75e0040e29742d8f00ede6cae51f430d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/definitions.test.js @@ -0,0 +1,46 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and definitions keyword', () => { + const schema1 = {} + const schema2 = { + definitions: { + foo: { type: 'string', const: 'foo' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + definitions: { + foo: { type: 'string', const: 'foo' } + } + }) +}) + +test('should merge two definition schemas', () => { + const schema1 = { + definitions: { + foo: { type: 'string', enum: ['foo', 'bar'] }, + bar: { type: 'string', enum: ['foo', 'bar'] } + } + } + const schema2 = { + definitions: { + foo: { type: 'string', enum: ['foo'] }, + baz: { type: 'string' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + definitions: { + foo: { type: 'string', enum: ['foo'] }, + bar: { type: 'string', enum: ['foo', 'bar'] }, + baz: { type: 'string' } + } + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/defs.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/defs.test.js new file mode 100644 index 0000000000000000000000000000000000000000..e5433abbb8b2c149b07e27715757c2a9c5c22a5b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/defs.test.js @@ -0,0 +1,46 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and $defs keyword', () => { + const schema1 = {} + const schema2 = { + $defs: { + foo: { type: 'string', const: 'foo' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + $defs: { + foo: { type: 'string', const: 'foo' } + } + }) +}) + +test('should merge two definition schemas', () => { + const schema1 = { + $defs: { + foo: { type: 'string', enum: ['foo', 'bar'] }, + bar: { type: 'string', enum: ['foo', 'bar'] } + } + } + const schema2 = { + $defs: { + foo: { type: 'string', enum: ['foo'] }, + baz: { type: 'string' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + $defs: { + foo: { type: 'string', enum: ['foo'] }, + bar: { type: 'string', enum: ['foo', 'bar'] }, + baz: { type: 'string' } + } + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/dependencies.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/dependencies.test.js new file mode 100644 index 0000000000000000000000000000000000000000..3afb0cf96ac1e78621cb61dbd1485b08722fe5b2 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/dependencies.test.js @@ -0,0 +1,75 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and dependencies keyword', () => { + const schema1 = {} + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' } + }, + dependencies: { + foo: ['bar'] + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' } + }, + dependencies: { + foo: ['bar'] + } + }) +}) + +test('should merge two dependencies keyword schemas', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' }, + que: { type: 'string' } + }, + dependencies: { + foo: ['bar', 'que'], + bar: ['que'] + } + } + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' }, + baz: { type: 'string' } + }, + dependencies: { + foo: ['baz'], + baz: ['foo'] + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' }, + que: { type: 'string' }, + baz: { type: 'string' } + }, + dependencies: { + foo: ['bar', 'que', 'baz'], + bar: ['que'], + baz: ['foo'] + } + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/dependent-required.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/dependent-required.test.js new file mode 100644 index 0000000000000000000000000000000000000000..7729b9594755ad7899bfccfdfdeff5d693a2e994 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/dependent-required.test.js @@ -0,0 +1,75 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and dependentRequired keyword', () => { + const schema1 = {} + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' } + }, + dependentRequired: { + foo: ['bar'] + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' } + }, + dependentRequired: { + foo: ['bar'] + } + }) +}) + +test('should merge two dependentRequired keyword schemas', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' }, + que: { type: 'string' } + }, + dependentRequired: { + foo: ['bar', 'que'], + bar: ['que'] + } + } + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' }, + baz: { type: 'string' } + }, + dependentRequired: { + foo: ['baz'], + baz: ['foo'] + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' }, + que: { type: 'string' }, + baz: { type: 'string' } + }, + dependentRequired: { + foo: ['bar', 'que', 'baz'], + bar: ['que'], + baz: ['foo'] + } + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/dependent-schemas.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/dependent-schemas.test.js new file mode 100644 index 0000000000000000000000000000000000000000..76e04353845512dde41479e91f2731803af63301 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/dependent-schemas.test.js @@ -0,0 +1,76 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and dependentRequired keyword', () => { + const schema1 = {} + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' } + }, + dependentSchemas: { + foo: { required: ['bar'] } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' } + }, + dependentSchemas: { + foo: { required: ['bar'] } + } + }) +}) + +test('should merge two dependentRequired keyword schemas', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' }, + que: { type: 'string' } + }, + dependentSchemas: { + foo: { required: ['bar', 'que'] }, + bar: { required: ['que'] } + } + } + + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' }, + baz: { type: 'string' } + }, + dependentSchemas: { + foo: { required: ['baz'] }, + baz: { required: ['foo'] } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'string' }, + que: { type: 'string' }, + baz: { type: 'string' } + }, + dependentSchemas: { + foo: { required: ['bar', 'que', 'baz'] }, + bar: { required: ['que'] }, + baz: { required: ['foo'] } + } + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/enum.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/enum.test.js new file mode 100644 index 0000000000000000000000000000000000000000..8a0dd133cce70242b005af352812873e98321599 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/enum.test.js @@ -0,0 +1,44 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and string enum values', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', enum: ['foo', 'bar'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', enum: ['foo', 'bar'] }) +}) + +test('should merge equal string enum values', () => { + const schema1 = { type: 'string', enum: ['foo', 'bar'] } + const schema2 = { type: 'string', enum: ['foo', 'bar'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', enum: ['foo', 'bar'] }) +}) + +test('should merge different string enum values', () => { + const schema1 = { type: 'string', enum: ['foo', 'bar'] } + const schema2 = { type: 'string', enum: ['foo', 'baz'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', enum: ['foo'] }) +}) + +test('should throw an error if can not merge enum values', () => { + const schema1 = { type: 'string', enum: ['foo', 'bar'] } + const schema2 = { type: 'string', enum: ['baz', 'qux'] } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { defaultResolver }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Failed to merge "enum" keyword schemas.', + schemas: [['foo', 'bar'], ['baz', 'qux']] + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/exclusive-maximum.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/exclusive-maximum.test.js new file mode 100644 index 0000000000000000000000000000000000000000..9481bb5f97339893248cbb7a56fc943700243d3e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/exclusive-maximum.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and exclusiveMaximum keyword', () => { + const schema1 = { type: 'number' } + const schema2 = { type: 'number', exclusiveMaximum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', exclusiveMaximum: 42 }) +}) + +test('should merge equal exclusiveMaximum values', () => { + const schema1 = { type: 'number', exclusiveMaximum: 42 } + const schema2 = { type: 'number', exclusiveMaximum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', exclusiveMaximum: 42 }) +}) + +test('should merge different exclusiveMaximum values', () => { + const schema1 = { type: 'integer', exclusiveMaximum: 42 } + const schema2 = { type: 'integer', exclusiveMaximum: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'integer', exclusiveMaximum: 42 }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/exclusive-minimum.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/exclusive-minimum.test.js new file mode 100644 index 0000000000000000000000000000000000000000..d2de258104ce59c592dd6958900e7436f15ebbd7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/exclusive-minimum.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and exclusiveMinimum keyword', () => { + const schema1 = { type: 'number' } + const schema2 = { type: 'number', exclusiveMinimum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', exclusiveMinimum: 42 }) +}) + +test('should merge equal exclusiveMinimum values', () => { + const schema1 = { type: 'number', exclusiveMinimum: 42 } + const schema2 = { type: 'number', exclusiveMinimum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', exclusiveMinimum: 42 }) +}) + +test('should merge different exclusiveMinimum values', () => { + const schema1 = { type: 'integer', exclusiveMinimum: 42 } + const schema2 = { type: 'integer', exclusiveMinimum: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'integer', exclusiveMinimum: 43 }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/format.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/format.test.js new file mode 100644 index 0000000000000000000000000000000000000000..e79e1c88addfaefd9aefccc6d11b5c97d2ded12c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/format.test.js @@ -0,0 +1,36 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and string format keyword', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', format: 'date-time' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', format: 'date-time' }) +}) + +test('should merge equal string format keywords', () => { + const schema1 = { type: 'string', format: 'date-time' } + const schema2 = { type: 'string', format: 'date-time' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', format: 'date-time' }) +}) + +test('should throw an error if format keyword values are different', () => { + const schema1 = { type: 'string', format: 'date-time' } + const schema2 = { type: 'string', format: 'date' } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { defaultResolver }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Failed to merge "format" keyword schemas.', + schemas: ['date-time', 'date'] + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/id.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/id.test.js new file mode 100644 index 0000000000000000000000000000000000000000..9221738daccfdcc0749cb0c4725bdf1e90309f78 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/id.test.js @@ -0,0 +1,22 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should skip $id keyword if they are equal', () => { + const schema1 = { $id: 'foo', type: 'string' } + const schema2 = { $id: 'foo', type: 'string' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string' }) +}) + +test('should skip $id keyword if they are different', () => { + const schema1 = { $id: 'foo', type: 'string' } + const schema2 = { $id: 'bar', type: 'string' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string' }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/if-then-else.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/if-then-else.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2135611a49b414f946c67991e8b20e7ef979ed3a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/if-then-else.test.js @@ -0,0 +1,550 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and if/then/else keywords', () => { + const schema1 = {} + const schema2 = { + if: { + type: 'string', + const: 'foo' + }, + then: { + type: 'string', + const: 'bar' + }, + else: { + type: 'string', + const: 'baz' + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + if: { + type: 'string', + const: 'foo' + }, + then: { + type: 'string', + const: 'bar' + }, + else: { + type: 'string', + const: 'baz' + } + }) +}) + +test('should merge if/then/else schema with an empty schema', () => { + const schema1 = { + if: { + type: 'string', + const: 'foo' + }, + then: { + type: 'string', + const: 'bar' + }, + else: { + type: 'string', + const: 'baz' + } + } + const schema2 = {} + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + if: { + type: 'string', + const: 'foo' + }, + then: { + type: 'string', + const: 'bar' + }, + else: { + type: 'string', + const: 'baz' + } + }) +}) + +test('should merge two if/then/else schemas', () => { + const schema1 = { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + } + }, + else: { + properties: { + baz1: { type: 'string', const: 'baz1' } + } + } + } + const schema2 = { + type: 'object', + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + }, + else: { + properties: { + baz2: { type: 'string', const: 'baz2' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + }, + else: { + properties: { + baz2: { type: 'string', const: 'baz2' } + } + } + }, + else: { + properties: { + baz1: { type: 'string', const: 'baz1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + }, + else: { + properties: { + baz2: { type: 'string', const: 'baz2' } + } + } + } + }) +}) + +test('should merge three if/then/else schemas', () => { + const schema1 = { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + } + }, + else: { + properties: { + baz1: { type: 'string', const: 'baz1' } + } + } + } + const schema2 = { + type: 'object', + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + }, + else: { + properties: { + baz2: { type: 'string', const: 'baz2' } + } + } + } + const schema3 = { + type: 'object', + if: { + properties: { + foo3: { type: 'string', const: 'foo3' } + } + }, + then: { + properties: { + bar3: { type: 'string', const: 'bar3' } + } + }, + else: { + properties: { + baz3: { type: 'string', const: 'baz3' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2, schema3], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + }, + if: { + properties: { + foo3: { type: 'string', const: 'foo3' } + } + }, + then: { + properties: { + bar3: { type: 'string', const: 'bar3' } + } + }, + else: { + properties: { + baz3: { type: 'string', const: 'baz3' } + } + } + }, + else: { + properties: { + baz2: { type: 'string', const: 'baz2' } + }, + if: { + properties: { + foo3: { type: 'string', const: 'foo3' } + } + }, + then: { + properties: { + bar3: { type: 'string', const: 'bar3' } + } + }, + else: { + properties: { + baz3: { type: 'string', const: 'baz3' } + } + } + } + }, + else: { + properties: { + baz1: { type: 'string', const: 'baz1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + }, + if: { + properties: { + foo3: { type: 'string', const: 'foo3' } + } + }, + then: { + properties: { + bar3: { type: 'string', const: 'bar3' } + } + }, + else: { + properties: { + baz3: { type: 'string', const: 'baz3' } + } + } + }, + else: { + properties: { + baz2: { type: 'string', const: 'baz2' } + }, + if: { + properties: { + foo3: { type: 'string', const: 'foo3' } + } + }, + then: { + properties: { + bar3: { type: 'string', const: 'bar3' } + } + }, + else: { + properties: { + baz3: { type: 'string', const: 'baz3' } + } + } + } + } + }) +}) + +test('should two if/then keyword schemas', () => { + const schema1 = { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + } + } + } + + const schema2 = { + type: 'object', + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + }) +}) + +test('should two if/else keyword schemas', () => { + const schema1 = { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + else: { + properties: { + bar1: { type: 'string', const: 'bar1' } + } + } + } + + const schema2 = { + type: 'object', + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + else: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + else: { + properties: { + bar1: { type: 'string', const: 'bar1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + else: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + }) +}) + +test('should two if/then and if/else keyword schemas', () => { + const schema1 = { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + } + } + } + + const schema2 = { + type: 'object', + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + else: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + then: { + properties: { + bar1: { type: 'string', const: 'bar1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + else: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + }) +}) + +test('should two if/else and if/then keyword schemas', () => { + const schema1 = { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + else: { + properties: { + bar1: { type: 'string', const: 'bar1' } + } + } + } + + const schema2 = { + type: 'object', + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + if: { + properties: { + foo1: { type: 'string', const: 'foo1' } + } + }, + else: { + properties: { + bar1: { type: 'string', const: 'bar1' } + }, + if: { + properties: { + foo2: { type: 'string', const: 'foo2' } + } + }, + then: { + properties: { + bar2: { type: 'string', const: 'bar2' } + } + } + } + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/items.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/items.test.js new file mode 100644 index 0000000000000000000000000000000000000000..b780530370e512e815024fd974a8c021d6712bc1 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/items.test.js @@ -0,0 +1,152 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and items keyword', () => { + const schema1 = { type: 'array' } + const schema2 = { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' } + } + } + }) +}) + +test('should merge two equal item schemas', () => { + const schema1 = { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' } + } + } + } + + const schema2 = { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' } + } + } + }) +}) + +test('should merge two different sets of item schemas', () => { + const schema1 = { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' } + } + } + } + + const schema2 = { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' }, + baz: { type: 'boolean' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' }, + baz: { type: 'boolean' } + } + } + }) +}) + +test('should merge two different sets of item schemas with additionalItems', () => { + const schema1 = { + type: 'array', + items: [ + { + type: 'object', + properties: { + foo: { type: 'string', const: 'foo' } + } + } + ], + additionalItems: { + type: 'object', + properties: { + baz: { type: 'string', const: 'baz' } + } + } + } + + const schema2 = { + type: 'array', + items: { + type: 'object', + properties: { + foo: { type: 'string' }, + baz: { type: 'string' } + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + items: [ + { + type: 'object', + properties: { + foo: { type: 'string', const: 'foo' }, + baz: { type: 'string' } + } + } + ], + additionalItems: { + type: 'object', + properties: { + foo: { type: 'string' }, + baz: { type: 'string', const: 'baz' } + } + } + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-items.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-items.test.js new file mode 100644 index 0000000000000000000000000000000000000000..939cf29940a53858b7e92a9f55e5a71b690a41f5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-items.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and maxItems keyword', () => { + const schema1 = { type: 'array' } + const schema2 = { type: 'array', maxItems: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', maxItems: 42 }) +}) + +test('should merge equal maxItems values', () => { + const schema1 = { type: 'array', maxItems: 42 } + const schema2 = { type: 'array', maxItems: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', maxItems: 42 }) +}) + +test('should merge different maxItems values', () => { + const schema1 = { type: 'array', maxItems: 42 } + const schema2 = { type: 'array', maxItems: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', maxItems: 42 }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-length.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-length.test.js new file mode 100644 index 0000000000000000000000000000000000000000..c97002fbf99021b043a54dfddb267ae6e4663180 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-length.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and maxLength keyword', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', maxLength: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', maxLength: 42 }) +}) + +test('should merge equal maxLength values', () => { + const schema1 = { type: 'string', maxLength: 42 } + const schema2 = { type: 'string', maxLength: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', maxLength: 42 }) +}) + +test('should merge different maxLength values', () => { + const schema1 = { type: 'string', maxLength: 42 } + const schema2 = { type: 'string', maxLength: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', maxLength: 42 }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-properties.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-properties.test.js new file mode 100644 index 0000000000000000000000000000000000000000..b5b39496bd4624a0a4b13ae8042f43955012d353 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/max-properties.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and maxProperties keyword', () => { + const schema1 = { type: 'object' } + const schema2 = { type: 'object', maxProperties: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', maxProperties: 42 }) +}) + +test('should merge equal maxProperties values', () => { + const schema1 = { type: 'object', maxProperties: 42 } + const schema2 = { type: 'object', maxProperties: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', maxProperties: 42 }) +}) + +test('should merge different maxProperties values', () => { + const schema1 = { type: 'object', maxProperties: 42 } + const schema2 = { type: 'object', maxProperties: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', maxProperties: 42 }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/maximum.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/maximum.test.js new file mode 100644 index 0000000000000000000000000000000000000000..4a0c982fa4360598338a9c3ce49ed83499a89e42 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/maximum.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and maximum keyword', () => { + const schema1 = { type: 'number' } + const schema2 = { type: 'number', maximum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', maximum: 42 }) +}) + +test('should merge equal maximum values', () => { + const schema1 = { type: 'number', maximum: 42 } + const schema2 = { type: 'number', maximum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', maximum: 42 }) +}) + +test('should merge different maximum values', () => { + const schema1 = { type: 'integer', maximum: 42 } + const schema2 = { type: 'integer', maximum: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'integer', maximum: 42 }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/merge-schema.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/merge-schema.test.js new file mode 100644 index 0000000000000000000000000000000000000000..a41c3a983fe280eb712fd74cfda21991e97cf3ea --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/merge-schema.test.js @@ -0,0 +1,29 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should return an empty schema if passing an empty array', () => { + const mergedSchema = mergeSchemas([], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, {}) +}) + +test('should return true if passing all true values', () => { + const mergedSchema = mergeSchemas([true, true, true], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, true) +}) + +test('should return true if passing all false values', () => { + const mergedSchema = mergeSchemas([false, false, false], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, false) +}) + +test('should return true if passing at least one false schema', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'number' } + + const mergedSchema = mergeSchemas([schema1, schema2, false], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, false) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/min-items.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/min-items.test.js new file mode 100644 index 0000000000000000000000000000000000000000..b5d5073556ddfb11cafd6d71c492c6a96b0f4552 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/min-items.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and minItems keyword', () => { + const schema1 = { type: 'array' } + const schema2 = { type: 'array', minItems: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', minItems: 42 }) +}) + +test('should merge equal minItems values', () => { + const schema1 = { type: 'array', minItems: 42 } + const schema2 = { type: 'array', minItems: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', minItems: 42 }) +}) + +test('should merge different minItems values', () => { + const schema1 = { type: 'array', minItems: 42 } + const schema2 = { type: 'array', minItems: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', minItems: 43 }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/min-length.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/min-length.test.js new file mode 100644 index 0000000000000000000000000000000000000000..64a2c4458ae23e7b35ed9d7e7ed0209e3d53a07d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/min-length.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and minLength keyword', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', minLength: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', minLength: 42 }) +}) + +test('should merge equal minLength values', () => { + const schema1 = { type: 'string', minLength: 42 } + const schema2 = { type: 'string', minLength: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', minLength: 42 }) +}) + +test('should merge different minLength values', () => { + const schema1 = { type: 'string', minLength: 42 } + const schema2 = { type: 'string', minLength: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', minLength: 43 }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/min-properties.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/min-properties.test.js new file mode 100644 index 0000000000000000000000000000000000000000..bfe4599b33e0c1562a09f91bb3bc3e7def57d221 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/min-properties.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and minProperties keyword', () => { + const schema1 = { type: 'object' } + const schema2 = { type: 'object', minProperties: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', minProperties: 42 }) +}) + +test('should merge equal minItems values', () => { + const schema1 = { type: 'object', minProperties: 42 } + const schema2 = { type: 'object', minProperties: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', minProperties: 42 }) +}) + +test('should merge different minItems values', () => { + const schema1 = { type: 'object', minProperties: 42 } + const schema2 = { type: 'object', minProperties: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', minProperties: 43 }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/minimum.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/minimum.test.js new file mode 100644 index 0000000000000000000000000000000000000000..f0dd105ad35bc61b134c91d391db910a587cb8e3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/minimum.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and minimum keyword', () => { + const schema1 = { type: 'number' } + const schema2 = { type: 'number', minimum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', minimum: 42 }) +}) + +test('should merge equal minimum values', () => { + const schema1 = { type: 'number', minimum: 42 } + const schema2 = { type: 'number', minimum: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', minimum: 42 }) +}) + +test('should merge different minimum values', () => { + const schema1 = { type: 'integer', minimum: 42 } + const schema2 = { type: 'integer', minimum: 43 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'integer', minimum: 43 }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/multiple-of.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/multiple-of.test.js new file mode 100644 index 0000000000000000000000000000000000000000..f07a32bcff9b10d117227919ba59fdcfb58e68e8 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/multiple-of.test.js @@ -0,0 +1,36 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and multipleOf keyword', () => { + const schema1 = { type: 'number' } + const schema2 = { type: 'number', multipleOf: 42 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', multipleOf: 42 }) +}) + +test('should merge two schemas with multipleOf keywords', () => { + const schema1 = { type: 'number', multipleOf: 2 } + const schema2 = { type: 'number', multipleOf: 3 } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'number', multipleOf: 6 }) +}) + +test('should merge multiple schemas with float multipleOf keywords', () => { + const schema1 = { type: 'number', multipleOf: 0.2 } + const schema2 = { type: 'number', multipleOf: 2 } + const schema3 = { type: 'number', multipleOf: 2 } + const schema4 = { type: 'number', multipleOf: 0.5 } + const schema5 = { type: 'number', multipleOf: 1.5 } + + const mergedSchema = mergeSchemas( + [schema1, schema2, schema3, schema4, schema5], + { defaultResolver } + ) + assert.deepStrictEqual(mergedSchema, { type: 'number', multipleOf: 6 }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/not.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/not.test.js new file mode 100644 index 0000000000000000000000000000000000000000..e73131d48b0262e74a9618a3d89fff2084a189df --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/not.test.js @@ -0,0 +1,29 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge two "not" keyword schemas', () => { + const schema1 = { + type: 'array', + not: { + type: 'string' + } + } + const schema2 = { + type: 'array', + not: { + type: 'string', minLength: 1 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'array', + not: { + type: 'string', minLength: 1 + } + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/nullable.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/nullable.test.js new file mode 100644 index 0000000000000000000000000000000000000000..ef5fcfd8618fc9e0451e5a72f15af88336c1a1bb --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/nullable.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and nullable = true keyword', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', nullable: true } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', nullable: true }) +}) + +test('should merge empty schema and nullable = false keyword', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string', nullable: false } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', nullable: false }) +}) + +test('should merge schemas with nullable true and false values', () => { + const schema1 = { type: 'string', nullable: false } + const schema2 = { type: 'string', nullable: true } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string', nullable: false }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/one-of.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/one-of.test.js new file mode 100644 index 0000000000000000000000000000000000000000..94eab45a8f053b688a3fa7797883d0e1ba38c4c9 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/one-of.test.js @@ -0,0 +1,144 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas, MergeError } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and oneOf keyword', () => { + const schema1 = {} + const schema2 = { + oneOf: [ + { type: 'string', const: 'foo' } + ] + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + oneOf: [ + { type: 'string', const: 'foo' } + ] + }) +}) + +test('should merge two schemas with oneOfs schemas', () => { + const schema1 = { + oneOf: [ + { type: 'string', enum: ['foo1', 'foo2', 'foo3'] }, + { type: 'string', enum: ['foo3', 'foo4', 'foo5'] } + ] + } + const schema2 = { + oneOf: [ + { type: 'string', enum: ['foo2', 'foo3', 'foo4'] }, + { type: 'string', enum: ['foo3', 'foo6', 'foo7'] } + ] + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + oneOf: [ + { type: 'string', enum: ['foo2', 'foo3'] }, + { type: 'string', enum: ['foo3'] }, + { type: 'string', enum: ['foo3', 'foo4'] }, + { type: 'string', enum: ['foo3'] } + ] + }) +}) + +test('should merge three schemas with oneOfs schemas', () => { + const schema1 = { + oneOf: [ + { type: 'string', enum: ['foo1', 'foo2', 'foo3', 'foo4'] }, + { type: 'string', enum: ['foo3', 'foo4', 'foo5', 'foo7'] } + ] + } + const schema2 = { + oneOf: [ + { type: 'string', enum: ['foo2', 'foo3', 'foo4', 'foo5'] }, + { type: 'string', enum: ['foo3', 'foo6', 'foo7', 'foo8'] } + ] + } + + const schema3 = { + oneOf: [ + { type: 'string', enum: ['foo1', 'foo3', 'foo5', 'foo7'] }, + { type: 'string', enum: ['foo2', 'foo4', 'foo6', 'foo8'] } + ] + } + + const mergedSchema = mergeSchemas( + [schema1, schema2, schema3], + { defaultResolver } + ) + assert.deepStrictEqual(mergedSchema, { + oneOf: [ + { type: 'string', enum: ['foo3'] }, + { type: 'string', enum: ['foo2', 'foo4'] }, + { type: 'string', enum: ['foo3'] }, + { type: 'string', enum: ['foo3', 'foo5'] }, + { type: 'string', enum: ['foo4'] }, + { type: 'string', enum: ['foo3', 'foo7'] } + ] + }) +}) + +test('should throw a non MergeError error during oneOf merge', () => { + const schema1 = { + oneOf: [ + { type: 'string', customKeyword: 42 }, + { type: 'string', customKeyword: 43 } + ] + } + const schema2 = { + oneOf: [ + { type: 'string', customKeyword: 44 }, + { type: 'string', customKeyword: 45 } + ] + } + + assert.throws(() => { + mergeSchemas( + [schema1, schema2], + { + resolvers: { + customKeyword: () => { + throw new Error('Custom error') + } + }, + defaultResolver + } + ) + }, { + name: 'Error', + message: 'Custom error' + }) +}) + +test('should not throw a MergeError error during oneOf merge', () => { + const schema1 = { + oneOf: [ + { type: 'string', customKeyword: 42 }, + { type: 'string', customKeyword: 43 } + ] + } + const schema2 = { + oneOf: [ + { type: 'string', customKeyword: 44 }, + { type: 'string', customKeyword: 45 } + ] + } + + const mergedSchema = mergeSchemas( + [schema1, schema2], + { + resolvers: { + customKeyword: (keyword, values) => { + throw new MergeError(keyword, values) + } + }, + defaultResolver + } + ) + assert.deepStrictEqual(mergedSchema, { oneOf: [] }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/properties.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/properties.test.js new file mode 100644 index 0000000000000000000000000000000000000000..6e26492d920ce42cb9151d15ed781306fd5f56f4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/properties.test.js @@ -0,0 +1,312 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and properties keyword', () => { + const schema1 = { type: 'object' } + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string' } + } + }) +}) + +test('should merge two equal property schemas', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' } + } + } + + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string' } + } + }) +}) + +test('should merge two different sets of property schemas', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' } + } + } + + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string' }, + baz: { type: 'boolean' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' }, + baz: { type: 'boolean' } + } + }) +}) + +test('should merge property with different schemas', () => { + const schema1 = { + type: 'object', + properties: { + foo: { + type: ['string', 'number'], + enum: ['42', 2, 3] + } + } + } + + const schema2 = { + type: 'object', + properties: { + foo: { + type: ['number', 'null'], + enum: [1, 2, 3, null] + } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'number', enum: [2, 3] } + } + }) +}) + +test('should merge properties if one schema has additionalProperties = false', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' } + }, + additionalProperties: false + } + + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + baz: { type: 'string' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + bar: { type: 'number' }, + baz: false + }, + additionalProperties: false + }) +}) + +test('should merge properties if both schemas have additionalProperties = false', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' } + }, + additionalProperties: false + } + + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + baz: { type: 'string' } + }, + additionalProperties: false + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + bar: false, + baz: false + }, + additionalProperties: false + }) +}) + +test('should merge properties if one schema has additionalProperties schema', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' } + }, + additionalProperties: { type: 'string', enum: ['43'] } + } + + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + baz: { type: 'string' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + bar: { type: 'number' }, + baz: { type: 'string', enum: ['43'] } + }, + additionalProperties: { type: 'string', enum: ['43'] } + }) +}) + +test('should merge properties if both schemas have additionalProperties schemas', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' } + }, + additionalProperties: { + type: ['string', 'number', 'null'], + enum: ['45', '43', 41, null] + } + } + + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + baz: { type: 'string' } + }, + additionalProperties: { + type: ['string', 'boolean', 'number'], + enum: ['44', '43', true, 41] + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + bar: { type: 'number', enum: ['44', '43', true, 41] }, + baz: { type: 'string', enum: ['45', '43', 41, null] } + }, + additionalProperties: { type: ['string', 'number'], enum: ['43', 41] } + }) +}) + +test('should merge properties if one schema has patternProperties schema', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' } + }, + patternProperties: { + '^baz$': { type: 'string', enum: ['43'] } + } + } + + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + baz: { type: 'string' }, + qux: { type: 'string' } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + bar: { type: 'number' }, + baz: { type: 'string', enum: ['43'] }, + qux: { type: 'string' } + }, + patternProperties: { + '^baz$': { type: 'string', enum: ['43'] } + } + }) +}) + +test('should merge properties if both schemas have patternProperties schemas', () => { + const schema1 = { + type: 'object', + properties: { + foo: { type: 'string' }, + bar: { type: 'number' }, + bak: { type: 'number' } + }, + patternProperties: { + '^baz$': { type: 'string', enum: ['43'] } + } + } + + const schema2 = { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + baz: { type: 'string' }, + qux: { type: 'string' } + }, + patternProperties: { + '^bar$': { type: 'number', minimum: 2 } + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + properties: { + foo: { type: 'string', enum: ['42'] }, + bar: { type: 'number', minimum: 2 }, + bak: { type: 'number' }, + baz: { type: 'string', enum: ['43'] }, + qux: { type: 'string' } + }, + patternProperties: { + '^bar$': { type: 'number', minimum: 2 }, + '^baz$': { type: 'string', enum: ['43'] } + } + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/property-names.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/property-names.test.js new file mode 100644 index 0000000000000000000000000000000000000000..9f27572a944bbebdfb52c75733555937f8ef32e7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/property-names.test.js @@ -0,0 +1,49 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and propertyNames keyword', () => { + const schema1 = {} + const schema2 = { + type: 'object', + propertyNames: { + pattern: '^[a-zA-Z]+$', + minLength: 42 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + propertyNames: { + pattern: '^[a-zA-Z]+$', + minLength: 42 + } + }) +}) + +test('should merge two propertyNames keyword schemas', () => { + const schema1 = { + type: 'object', + propertyNames: { + minLength: 42 + } + } + const schema2 = { + type: 'object', + propertyNames: { + minLength: 43 + } + } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { + type: 'object', + propertyNames: { + minLength: 43 + } + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/required.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/required.test.js new file mode 100644 index 0000000000000000000000000000000000000000..3afa392f7faf33c707ee8fecdaf71acce4ad832c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/required.test.js @@ -0,0 +1,30 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and required keyword', () => { + const schema1 = { type: 'object' } + const schema2 = { type: 'object', required: ['foo'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', required: ['foo'] }) +}) + +test('should merge two equal required keywords', () => { + const schema1 = { type: 'object', required: ['foo'] } + const schema2 = { type: 'object', required: ['foo'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', required: ['foo'] }) +}) + +test('should merge two different required keywords', () => { + const schema1 = { type: 'object', required: ['foo', 'bar'] } + const schema2 = { type: 'object', required: ['foo', 'baz'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'object', required: ['foo', 'bar', 'baz'] }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/type.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/type.test.js new file mode 100644 index 0000000000000000000000000000000000000000..69c0861ae186988da6863eb0e93601621b479bc7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/type.test.js @@ -0,0 +1,52 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge equal type values', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'string' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string' }) +}) + +test('should merge array type values', () => { + const schema1 = { type: ['string', 'number'] } + const schema2 = { type: ['null', 'string'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string' }) +}) + +test('should merge array type values', () => { + const schema1 = { type: ['string', 'number'] } + const schema2 = { type: 'string' } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'string' }) +}) + +test('should merge array type values', () => { + const schema1 = { type: ['number', 'string', 'boolean'] } + const schema2 = { type: ['string', 'number', 'null'] } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: ['number', 'string'] }) +}) + +test('should throw an error if can not merge type values', () => { + const schema1 = { type: 'string' } + const schema2 = { type: 'number' } + + assert.throws(() => { + mergeSchemas([schema1, schema2], { defaultResolver }) + }, { + name: 'JsonSchemaMergeError', + code: 'JSON_SCHEMA_MERGE_ERROR', + message: 'Failed to merge "type" keyword schemas.', + schemas: [['string'], ['number']] + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/unique-items.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/unique-items.test.js new file mode 100644 index 0000000000000000000000000000000000000000..61a55e80ca7ffb2a3211bd19aa10232391e5db9e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/unique-items.test.js @@ -0,0 +1,38 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { mergeSchemas } = require('../index') +const { defaultResolver } = require('./utils') + +test('should merge empty schema and uniqueItems keyword', () => { + const schema1 = { type: 'array' } + const schema2 = { type: 'array', uniqueItems: true } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', uniqueItems: true }) +}) + +test('should merge two equal uniqueItems keyword schemas = true', () => { + const schema1 = { type: 'array', uniqueItems: true } + const schema2 = { type: 'array', uniqueItems: true } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', uniqueItems: true }) +}) + +test('should merge two equal uniqueItems keyword schemas = false', () => { + const schema1 = { type: 'array', uniqueItems: false } + const schema2 = { type: 'array', uniqueItems: false } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', uniqueItems: false }) +}) + +test('should merge two equal uniqueItems keyword schemas', () => { + const schema1 = { type: 'array', uniqueItems: false } + const schema2 = { type: 'array', uniqueItems: true } + + const mergedSchema = mergeSchemas([schema1, schema2], { defaultResolver }) + assert.deepStrictEqual(mergedSchema, { type: 'array', uniqueItems: true }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/utils.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..956ba245ae0ba1ae643f52251ee15c76f763f08b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/test/utils.js @@ -0,0 +1,9 @@ +'use strict' + +function defaultResolver () { + throw new Error('Default resolver should not be called.') +} + +module.exports = { + defaultResolver +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/types/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ab29554884764cfbaba5be2d35549e9fa0d630d1 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/types/index.d.ts @@ -0,0 +1,61 @@ +export type KeywordResolver = ( + keyword: string, + keywordValues: any[], + mergedSchema: any, + parentSchemas: any[], + options: MergeOptions +) => any + +export type KeywordResolvers = { + $id: KeywordResolver, + type: KeywordResolver, + enum: KeywordResolver, + minLength: KeywordResolver, + maxLength: KeywordResolver, + minimum: KeywordResolver, + maximum: KeywordResolver, + multipleOf: KeywordResolver, + exclusiveMinimum: KeywordResolver, + exclusiveMaximum: KeywordResolver, + minItems: KeywordResolver, + maxItems: KeywordResolver, + maxProperties: KeywordResolver, + minProperties: KeywordResolver, + const: KeywordResolver, + default: KeywordResolver, + format: KeywordResolver, + required: KeywordResolver, + properties: KeywordResolver, + patternProperties: KeywordResolver, + additionalProperties: KeywordResolver, + items: KeywordResolver, + additionalItems: KeywordResolver, + definitions: KeywordResolver, + $defs: KeywordResolver, + nullable: KeywordResolver, + oneOf: KeywordResolver, + anyOf: KeywordResolver, + allOf: KeywordResolver, + not: KeywordResolver, + if: KeywordResolver, + then: KeywordResolver, + else: KeywordResolver, + dependencies: KeywordResolver, + dependentRequired: KeywordResolver, + dependentSchemas: KeywordResolver, + propertyNames: KeywordResolver, + uniqueItems: KeywordResolver, + contains: KeywordResolver +} + +export type MergeOptions = { + defaultResolver?: KeywordResolver, + resolvers?: Partial, + // enum of ["throw", "skip", "first"] + onConflict?: 'throw' | 'skip' | 'first' +} + +export function mergeSchemas (schemas: any[], options?: MergeOptions): any + +export const keywordsResolvers: KeywordResolvers +export const defaultResolver: KeywordResolver diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/types/index.test-d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/types/index.test-d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7d82a148ec717c6989e29bff6b4c379a7bc6a118 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/merge-json-schemas/types/index.test-d.ts @@ -0,0 +1,52 @@ +import { mergeSchemas, MergeOptions } from '..' +import { expectType } from 'tsd' + +{ + const schema1 = { type: 'string', enum: ['foo', 'bar'] } + const schema2 = { type: 'string', enum: ['foo', 'baz'] } + + mergeSchemas([schema1, schema2]) +} + +{ + const schema1 = { type: 'string', enum: ['foo', 'bar'] } + const schema2 = { type: 'string', enum: ['foo', 'baz'] } + + const mergeOptions: MergeOptions = { + resolvers: { + enum: ( + keyword: string, + keywordValues: any[], + mergedSchema: any, + parentSchemas: any[], + options: MergeOptions + ) => { + expectType(keyword) + expectType(keywordValues) + expectType(mergedSchema) + expectType(parentSchemas) + expectType(options) + + return keywordValues + } + }, + defaultResolver: ( + keyword: string, + keywordValues: any[], + mergedSchema: any, + parentSchemas: any[], + options: MergeOptions + ) => { + expectType(keyword) + expectType(keywordValues) + expectType(mergedSchema) + expectType(parentSchemas) + expectType(options) + + return keywordValues + }, + onConflict: 'throw' + } + + mergeSchemas([schema1, schema2], mergeOptions) +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/.github/dependabot.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..dfa7fa6cba823110c8476a4b4ebcc07cfda12535 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 + + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "weekly" + open-pull-requests-limit: 10 diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/.github/stale.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/.github/stale.yml new file mode 100644 index 0000000000000000000000000000000000000000..d51ce639022226bc44471aa18bb218b50876cd52 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/.github/stale.yml @@ -0,0 +1,21 @@ +# Number of days of inactivity before an issue becomes stale +daysUntilStale: 15 +# Number of days of inactivity before a stale issue is closed +daysUntilClose: 7 +# Issues with these labels will never be considered stale +exemptLabels: + - "discussion" + - "feature request" + - "bug" + - "help wanted" + - "plugin suggestion" + - "good first issue" +# Label to use when marking an issue as stale +staleLabel: stale +# Comment to post when marking an issue as stale. Set to `false` to disable +markComment: > + This issue has been automatically marked as stale because it has not had + recent activity. It will be closed if no further activity occurs. Thank you + for your contributions. +# Comment to post when closing a stale issue. Set to `false` to disable +closeComment: false diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/.github/workflows/ci.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..31223b14224a040e75704597c6808a6dc3f15851 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/.github/workflows/ci.yml @@ -0,0 +1,24 @@ +name: CI + +on: + push: + branches: + - main + - master + - next + - 'v*' + paths-ignore: + - 'docs/**' + - '*.md' + pull_request: + paths-ignore: + - 'docs/**' + - '*.md' + +jobs: + test: + uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5.0.0 + with: + license-check: true + lint: true + node-versions: '["18", "20", "22"]' diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/compiling.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/compiling.js new file mode 100644 index 0000000000000000000000000000000000000000..76387276e08986d731e42babfeff89060083efb4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/compiling.js @@ -0,0 +1,50 @@ +'use strict' + +/** + * Globals for benchmark.js + */ +global.proxyaddr = require('..') +global.createReq = createReq + +/** + * Module dependencies. + */ +const benchmark = require('benchmark') +const benchmarks = require('beautify-benchmark') + +const suite = new benchmark.Suite() + +suite.add({ + name: 're-compiling', + minSamples: 100, + fn: 'proxyaddr(req, "loopback")', + setup: 'req = createReq("127.0.0.1", "10.0.0.1")' +}) + +suite.add({ + name: 'pre-compiling', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = proxyaddr.compile("loopback")' +}) + +suite.on('cycle', function onCycle (event) { + benchmarks.add(event.target) +}) + +suite.on('complete', function onComplete () { + benchmarks.log() +}) + +suite.run({ async: false }) + +function createReq (socketAddr, forwardedFor) { + return { + socket: { + remoteAddress: socketAddr + }, + headers: { + 'x-forwarded-for': (forwardedFor || '') + } + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4b5af22e636034104db7f3146a5c80a43a53b2db --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/index.js @@ -0,0 +1,30 @@ +'use strict' + +const fs = require('node:fs') +const path = require('node:path') +const spawn = require('node:child_process').spawn + +const exe = process.argv[0] +const cwd = process.cwd() + +runScripts(fs.readdirSync(__dirname)) + +function runScripts (fileNames) { + const fileName = fileNames.shift() + + if (!fileName) return + if (!/\.js$/i.test(fileName)) return runScripts(fileNames) + if (fileName.toLowerCase() === 'index.js') return runScripts(fileNames) + + const fullPath = path.join(__dirname, fileName) + + console.log('> %s %s', exe, path.relative(cwd, fullPath)) + + const proc = spawn(exe, [fullPath], { + stdio: 'inherit' + }) + + proc.on('exit', function () { + runScripts(fileNames) + }) +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/kind.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/kind.js new file mode 100644 index 0000000000000000000000000000000000000000..239ccf947ac53d84eaa66b7381a84e7a2d91de60 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/kind.js @@ -0,0 +1,57 @@ +'use strict' + +/** + * Globals for benchmark.js + */ +global.proxyaddr = require('..') +global.createReq = createReq + +/** + * Module dependencies. + */ +const benchmark = require('benchmark') +const benchmarks = require('beautify-benchmark') + +const suite = new benchmark.Suite() + +suite.add({ + name: 'ipv4', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = proxyaddr.compile("127.0.0.1")' +}) + +suite.add({ + name: 'ipv4-mapped', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("::ffff:7f00:1", "10.0.0.1"); trust = proxyaddr.compile("127.0.0.1")' +}) + +suite.add({ + name: 'ipv6', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("::1", "10.0.0.1"); trust = proxyaddr.compile("::1")' +}) + +suite.on('cycle', function onCycle (event) { + benchmarks.add(event.target) +}) + +suite.on('complete', function onComplete () { + benchmarks.log() +}) + +suite.run({ async: false }) + +function createReq (socketAddr, forwardedFor) { + return { + socket: { + remoteAddress: socketAddr + }, + headers: { + 'x-forwarded-for': (forwardedFor || '') + } + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/matching.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/matching.js new file mode 100644 index 0000000000000000000000000000000000000000..d584c6801d93048e64cd0b4f0a8b605c29df5ece --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/benchmark/matching.js @@ -0,0 +1,78 @@ +'use strict' + +/** + * Globals for benchmark.js + */ +global.proxyaddr = require('..') +global.createReq = createReq + +/** + * Module dependencies. + */ +const benchmark = require('benchmark') +const benchmarks = require('beautify-benchmark') + +const suite = new benchmark.Suite() + +suite.add({ + name: 'trust none', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = proxyaddr.compile([])' +}) + +suite.add({ + name: 'trust all', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = function() {return true}' +}) + +suite.add({ + name: 'trust single', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = proxyaddr.compile("127.0.0.1")' +}) + +suite.add({ + name: 'trust first', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = function(a, i) {return i<1}' +}) + +suite.add({ + name: 'trust subnet', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = proxyaddr.compile("127.0.0.1/8")' +}) + +suite.add({ + name: 'trust multiple', + minSamples: 100, + fn: 'proxyaddr(req, trust)', + setup: 'req = createReq("127.0.0.1", "10.0.0.1"); trust = proxyaddr.compile(["127.0.0.1", "10.0.0.1"])' +}) + +suite.on('cycle', function onCycle (event) { + benchmarks.add(event.target) +}) + +suite.on('complete', function onComplete () { + benchmarks.log() +}) + +suite.run({ async: false }) + +function createReq (socketAddr, forwardedFor) { + return { + socket: { + remoteAddress: socketAddr + }, + headers: { + 'x-forwarded-for': (forwardedFor || '') + } + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/test/.eslintrc.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/test/.eslintrc.yml new file mode 100644 index 0000000000000000000000000000000000000000..9808c3b2b6602da61eb4afcb4caf33368e3e2bd4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/test/.eslintrc.yml @@ -0,0 +1,2 @@ +env: + mocha: true diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/test/all.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/test/all.js new file mode 100644 index 0000000000000000000000000000000000000000..44da283d71b859af84a3515076fc692681a1c430 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/test/all.js @@ -0,0 +1,62 @@ +'use strict' + +const test = require('tape') +const proxyaddr = require('..') + +test('argument req should be required', function (t) { + t.throws(proxyaddr.all, /req.*required/u) + t.end() +}) + +test('argument trustshould be optional', function (t) { + const req = createReq('127.0.0.1') + t.doesNotThrow(proxyaddr.all.bind(null, req)) + t.end() +}) + +test('with no headers should return socket address', function (t) { + const req = createReq('127.0.0.1') + t.same(proxyaddr.all(req), ['127.0.0.1']) + t.end() +}) + +test('with x-forwarded-for header should include x-forwarded-for', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': '10.0.0.1' + }) + t.same(proxyaddr.all(req), ['127.0.0.1', '10.0.0.1']) + t.end() +}) + +test('with x-forwarded-for header should include x-forwarded-for in correct order', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': '10.0.0.1, 10.0.0.2' + }) + t.same(proxyaddr.all(req), ['127.0.0.1', '10.0.0.2', '10.0.0.1']) + t.end() +}) + +test('with trust argument should stop at first untrusted', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': '10.0.0.1, 10.0.0.2' + }) + t.same(proxyaddr.all(req, '127.0.0.1'), ['127.0.0.1', '10.0.0.2']) + t.end() +}) + +test('with trust argument should be only socket address for no trust', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': '10.0.0.1, 10.0.0.2' + }) + t.same(proxyaddr.all(req, []), ['127.0.0.1']) + t.end() +}) + +function createReq (socketAddr, headers) { + return { + socket: { + remoteAddress: socketAddr + }, + headers: headers || {} + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/test/base.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/test/base.js new file mode 100644 index 0000000000000000000000000000000000000000..77675e181200ee06a2d1333412d9f8b0300cdb96 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/test/base.js @@ -0,0 +1,417 @@ +'use strict' + +const test = require('tape') +const proxyaddr = require('..') + +test('req should be required', function (t) { + t.throws(proxyaddr, /req.*required/u) + t.end() +}) + +test('trust should be required', function (t) { + const req = createReq('127.0.0.1') + t.throws(proxyaddr.bind(null, req), /trust.*required/u) + t.end() +}) + +test('trust should accept a function', function (t) { + const req = createReq('127.0.0.1') + t.doesNotThrow(proxyaddr.bind(null, req, all)) + t.end() +}) + +test('trust should accept an array', function (t) { + const req = createReq('127.0.0.1') + t.doesNotThrow(proxyaddr.bind(null, req, [])) + t.end() +}) + +test('trust should accept a string', function (t) { + const req = createReq('127.0.0.1') + t.doesNotThrow(proxyaddr.bind(null, req, '127.0.0.1')) + t.end() +}) + +test('trust should reject a number', function (t) { + const req = createReq('127.0.0.1') + t.throws(proxyaddr.bind(null, req, 42), /unsupported trust argument/u) + t.end() +}) + +test('trust should accept IPv4', function (t) { + const req = createReq('127.0.0.1') + t.doesNotThrow(proxyaddr.bind(null, req, '127.0.0.1')) + t.end() +}) + +test('trust should accept IPv6', function (t) { + const req = createReq('127.0.0.1') + t.doesNotThrow(proxyaddr.bind(null, req, '::1')) + t.end() +}) + +test('trust should accept IPv4-style IPv6', function (t) { + const req = createReq('127.0.0.1') + t.doesNotThrow(proxyaddr.bind(null, req, '::ffff:127.0.0.1')) + t.end() +}) + +test('trust should accept pre-defined names', function (t) { + const req = createReq('127.0.0.1') + t.doesNotThrow(proxyaddr.bind(null, req, 'loopback')) + t.end() +}) + +test('trust should accept pre-defined names in array', function (t) { + const req = createReq('127.0.0.1') + t.doesNotThrow(proxyaddr.bind(null, req, ['loopback', '10.0.0.1'])) + t.end() +}) + +test('trust should not alter input array', function (t) { + const arr = ['loopback', '10.0.0.1'] + const req = createReq('127.0.0.1') + t.doesNotThrow(proxyaddr.bind(null, req, arr)) + t.same(arr, ['loopback', '10.0.0.1']) + t.end() +}) + +test('trust should reject non-IP', function (t) { + const req = createReq('127.0.0.1') + t.throws(proxyaddr.bind(null, req, 'blargh'), /invalid IP address/u) + t.throws(proxyaddr.bind(null, req, '10.0.300.1'), /invalid IP address/u) + t.throws(proxyaddr.bind(null, req, '::ffff:30.168.1.9000'), /invalid IP address/u) + t.throws(proxyaddr.bind(null, req, '-1'), /invalid IP address/u) + t.end() +}) + +test('trust should reject bad CIDR', function (t) { + const req = createReq('127.0.0.1') + t.throws(proxyaddr.bind(null, req, '10.0.0.1/internet'), /invalid range on address/u) + t.throws(proxyaddr.bind(null, req, '10.0.0.1/6000'), /invalid range on address/u) + t.throws(proxyaddr.bind(null, req, '::1/6000'), /invalid range on address/u) + t.throws(proxyaddr.bind(null, req, '::ffff:a00:2/136'), /invalid range on address/u) + t.throws(proxyaddr.bind(null, req, '::ffff:a00:2/-1'), /invalid range on address/u) + t.end() +}) + +test('trust should reject bad netmask', function (t) { + const req = createReq('127.0.0.1') + t.throws(proxyaddr.bind(null, req, '10.0.0.1/255.0.255.0'), /invalid range on address/u) + t.throws(proxyaddr.bind(null, req, '10.0.0.1/ffc0::'), /invalid range on address/u) + t.throws(proxyaddr.bind(null, req, 'fe80::/ffc0::'), /invalid range on address/u) + t.throws(proxyaddr.bind(null, req, 'fe80::/255.255.255.0'), /invalid range on address/u) + t.throws(proxyaddr.bind(null, req, '::ffff:a00:2/255.255.255.0'), /invalid range on address/u) + t.end() +}) + +test('trust should be invoked as trust(addr, i)', function (t) { + const log = [] + const req = createReq('127.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.1' + }) + + proxyaddr(req, function (addr, i) { + return log.push(Array.prototype.slice.call(arguments)) + }) + + t.same(log, [ + ['127.0.0.1', 0], + ['10.0.0.1', 1] + ]) + + t.end() +}) + +test('with all trusted should return socket address wtesth no headers', function (t) { + const req = createReq('127.0.0.1') + t.equal(proxyaddr(req, all), '127.0.0.1') + t.end() +}) + +test('with all trusted should return header value', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': '10.0.0.1' + }) + t.equal(proxyaddr(req, all), '10.0.0.1') + t.end() +}) + +test('with all trusted should return furthest header value', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': '10.0.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, all), '10.0.0.1') + t.end() +}) + +test('with none trusted should return socket address wtesth no headers', function (t) { + const req = createReq('127.0.0.1') + t.equal(proxyaddr(req, none), '127.0.0.1') + t.end() +}) + +test('with none trusted should return socket address wtesth headers', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': '10.0.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, none), '127.0.0.1') + t.end() +}) + +test('with some trusted should return socket address wtesth no headers', function (t) { + const req = createReq('127.0.0.1') + t.equal(proxyaddr(req, trust10x), '127.0.0.1') + t.end() +}) + +test('with some trusted should return socket address when not trusted', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': '10.0.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, trust10x), '127.0.0.1') + t.end() +}) + +test('with some trusted should return header when socket trusted', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1' + }) + t.equal(proxyaddr(req, trust10x), '192.168.0.1') + t.end() +}) + +test('with some trusted should return first untrusted after trusted', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, trust10x), '192.168.0.1') + t.end() +}) + +test('with some trusted should not skip untrusted', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '10.0.0.3, 192.168.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, trust10x), '192.168.0.1') + t.end() +}) + +test('when given array should accept ltesteral IP addresses', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, ['10.0.0.1', '10.0.0.2']), '192.168.0.1') + t.end() +}) + +test('when given array should not trust non-IP addresses', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.2, localhost' + }) + t.equal(proxyaddr(req, ['10.0.0.1', '10.0.0.2']), 'localhost') + t.end() +}) + +test('when given array should return socket address if none match', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, ['127.0.0.1', '192.168.0.100']), '10.0.0.1') + t.end() +}) + +test('when array empty should return socket address ', function (t) { + const req = createReq('127.0.0.1') + t.equal(proxyaddr(req, []), '127.0.0.1') + t.end() +}) + +test('when array empty should return socket address wtesth headers', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': '10.0.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, []), '127.0.0.1') + t.end() +}) + +test('when given IPv4 addresses should accept ltesteral IP addresses', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, ['10.0.0.1', '10.0.0.2']), '192.168.0.1') + t.end() +}) + +test('when given IPv4 addresses should accept CIDR notation', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.200' + }) + t.equal(proxyaddr(req, '10.0.0.2/26'), '10.0.0.200') + t.end() +}) + +test('when given IPv4 addresses should accept netmask notation', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.200' + }) + t.equal(proxyaddr(req, '10.0.0.2/255.255.255.192'), '10.0.0.200') + t.end() +}) + +test('when given IPv6 addresses should accept ltesteral IP addresses', function (t) { + const req = createReq('fe80::1', { + 'x-forwarded-for': '2002:c000:203::1, fe80::2' + }) + t.equal(proxyaddr(req, ['fe80::1', 'fe80::2']), '2002:c000:203::1') + t.end() +}) + +test('when given IPv6 addresses should accept CIDR notation', function (t) { + const req = createReq('fe80::1', { + 'x-forwarded-for': '2002:c000:203::1, fe80::ff00' + }) + t.equal(proxyaddr(req, 'fe80::/125'), 'fe80::ff00') + t.end() +}) + +test('with IP version mixed should match respective versions', function (t) { + const req = createReq('::1', { + 'x-forwarded-for': '2002:c000:203::1' + }) + t.equal(proxyaddr(req, ['127.0.0.1', '::1']), '2002:c000:203::1') + t.end() +}) + +test('with IP version mixed should not match IPv4 to IPv6', function (t) { + const req = createReq('::1', { + 'x-forwarded-for': '2002:c000:203::1' + }) + t.equal(proxyaddr(req, '127.0.0.1'), '::1') + t.end() +}) + +test('when IPv4-mapped IPv6 addresses should match IPv4 trust to IPv6 request', function (t) { + const req = createReq('::ffff:a00:1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, ['10.0.0.1', '10.0.0.2']), '192.168.0.1') + t.end() +}) + +test('when IPv4-mapped IPv6 addresses should match IPv4 netmask trust to IPv6 request', function (t) { + const req = createReq('::ffff:a00:1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, ['10.0.0.1/16']), '192.168.0.1') + t.end() +}) + +test('when IPv4-mapped IPv6 addresses should match IPv6 trust to IPv4 request', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.2' + }) + t.equal(proxyaddr(req, ['::ffff:a00:1', '::ffff:a00:2']), '192.168.0.1') + t.end() +}) + +test('when IPv4-mapped IPv6 addresses should match CIDR notation for IPv4-mapped address', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.200' + }) + t.equal(proxyaddr(req, '::ffff:a00:2/122'), '10.0.0.200') + t.end() +}) + +test('when IPv4-mapped IPv6 addresses should match CIDR notation for IPv4-mapped address mixed wtesth IPv6 CIDR', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.200' + }) + t.equal(proxyaddr(req, ['::ffff:a00:2/122', 'fe80::/125']), '10.0.0.200') + t.end() +}) + +test('when IPv4-mapped IPv6 addresses should match CIDR notation for IPv4-mapped address mixed wtesth IPv4 addresses', function (t) { + const req = createReq('10.0.0.1', { + 'x-forwarded-for': '192.168.0.1, 10.0.0.200' + }) + t.equal(proxyaddr(req, ['::ffff:a00:2/122', '127.0.0.1']), '10.0.0.200') + t.end() +}) + +test('when given predefined names should accept single pre-defined name', function (t) { + const req = createReq('fe80::1', { + 'x-forwarded-for': '2002:c000:203::1, fe80::2' + }) + t.equal(proxyaddr(req, 'linklocal'), '2002:c000:203::1') + t.end() +}) + +test('when given predefined names should accept multiple pre-defined names', function (t) { + const req = createReq('::1', { + 'x-forwarded-for': '2002:c000:203::1, fe80::2' + }) + t.equal(proxyaddr(req, ['loopback', 'linklocal']), '2002:c000:203::1') + t.end() +}) + +test('when header contains non-ip addresses should stop at first non-ip after trusted', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': 'myrouter, 127.0.0.1, proxy' + }) + t.equal(proxyaddr(req, '127.0.0.1'), 'proxy') + t.end() +}) + +test('when header contains non-ip addresses should stop at first malformed ip after trusted', function (t) { + const req = createReq('127.0.0.1', { + 'x-forwarded-for': 'myrouter, 127.0.0.1, ::8:8:8:8:8:8:8:8:8' + }) + t.equal(proxyaddr(req, '127.0.0.1'), '::8:8:8:8:8:8:8:8:8') + t.end() +}) + +test('when header contains non-ip addresses should provide all values to function', function (t) { + const log = [] + const req = createReq('127.0.0.1', { + 'x-forwarded-for': 'myrouter, 127.0.0.1, proxy' + }) + + proxyaddr(req, function (addr, i) { + return log.push(Array.prototype.slice.call(arguments)) + }) + + t.same(log, [ + ['127.0.0.1', 0], + ['proxy', 1], + ['127.0.0.1', 2] + ]) + t.end() +}) + +test('when socket address undefined should return undefined as address', function (t) { + const req = createReq(undefined) + t.equal(proxyaddr(req, '127.0.0.1'), undefined) + t.end() +}) + +test('when socket address undefined should return undefined even wtesth trusted headers', function (t) { + const req = createReq(undefined, { + 'x-forwarded-for': '127.0.0.1, 10.0.0.1' + }) + t.equal(proxyaddr(req, '127.0.0.1'), undefined) + t.end() +}) + +function createReq (socketAddr, headers) { + return { + socket: { + remoteAddress: socketAddr + }, + headers: headers || {} + } +} + +function all () { return true } +function none () { return false } +function trust10x (addr) { return /^10\./u.test(addr) } diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/test/compile.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/test/compile.js new file mode 100644 index 0000000000000000000000000000000000000000..599a73dcf5a5b961dbb0200ff005e67b77866cf8 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/test/compile.js @@ -0,0 +1,70 @@ +'use strict' + +const test = require('tape') +const proxyaddr = require('..') + +test('trust arg should be required', function (t) { + t.throws(proxyaddr.compile, /argument.*required/u) + t.end() +}) + +test('trust arg should accept an array', function (t) { + t.equal(typeof proxyaddr.compile([]), 'function') + t.end() +}) + +test('trust arg should accept a string', function (t) { + t.equal(typeof proxyaddr.compile('127.0.0.1'), 'function') + t.end() +}) + +test('trust arg should reject a number', function (t) { + t.throws(proxyaddr.compile.bind(null, 42), /unsupported trust argument/u) + t.end() +}) + +test('trust arg should accept IPv4', function (t) { + t.equal(typeof proxyaddr.compile('127.0.0.1'), 'function') + t.end() +}) + +test('trust arg should accept IPv6', function (t) { + t.equal(typeof proxyaddr.compile('::1'), 'function') + t.end() +}) + +test('trust arg should accept IPv4-style IPv6', function (t) { + t.equal(typeof proxyaddr.compile('::ffff:127.0.0.1'), 'function') + t.end() +}) + +test('trust arg should accept pre-defined names', function (t) { + t.equal(typeof proxyaddr.compile('loopback'), 'function') + t.end() +}) + +test('trust arg should accept pre-defined names in array', function (t) { + t.equal(typeof proxyaddr.compile(['loopback', '10.0.0.1']), 'function') + t.end() +}) + +test('trust arg should reject non-IP', function (t) { + t.throws(proxyaddr.compile.bind(null, 'blargh'), /invalid IP address/u) + t.throws(proxyaddr.compile.bind(null, '-1'), /invalid IP address/u) + t.end() +}) + +test('trust arg should reject bad CIDR', function (t) { + t.throws(proxyaddr.compile.bind(null, '10.0.0.1/6000'), /invalid range on address/u) + t.throws(proxyaddr.compile.bind(null, '::1/6000'), /invalid range on address/u) + t.throws(proxyaddr.compile.bind(null, '::ffff:a00:2/136'), /invalid range on address/u) + t.throws(proxyaddr.compile.bind(null, '::ffff:a00:2/-46'), /invalid range on address/u) + t.end() +}) + +test('trust arg should not alter input array', function (t) { + const arr = ['loopback', '10.0.0.1'] + t.equal(typeof proxyaddr.compile(arr), 'function') + t.same(arr, ['loopback', '10.0.0.1']) + t.end() +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/types/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e554f5008d04c4be28679d2b347a2a7f086c6985 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/types/index.d.ts @@ -0,0 +1,18 @@ +/// + +import { IncomingMessage } from 'http'; + +type FastifyProxyAddr = typeof proxyaddr + +declare function proxyaddr(req: IncomingMessage, trust: proxyaddr.Address | proxyaddr.Address[] | ((addr: string, i: number) => boolean)): string; + +declare namespace proxyaddr { + export function all(req: IncomingMessage, trust?: Address | Address[] | ((addr: string, i: number) => boolean)): string[]; + export function compile(val: Address | Address[]): (addr: string, i: number) => boolean; + + export type Address = 'loopback' | 'linklocal' | 'uniquelocal' | string; + + export const proxyAddr: FastifyProxyAddr + export { proxyAddr as default } +} +export = proxyaddr; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/types/index.test-d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/types/index.test-d.ts new file mode 100644 index 0000000000000000000000000000000000000000..067e761c99eff86823eebcde2885b9eb9d46a169 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/proxy-addr/types/index.test-d.ts @@ -0,0 +1,27 @@ +import proxyaddr from '..'; +import { createServer } from 'http'; + +createServer(req => { + // $ExpectType string + proxyaddr(req, addr => addr === '127.0.0.1'); + proxyaddr(req, (addr, i) => i < 1); + + proxyaddr(req, '127.0.0.1'); + proxyaddr(req, ['127.0.0.0/8', '10.0.0.0/8']); + proxyaddr(req, ['127.0.0.0/255.0.0.0', '192.168.0.0/255.255.0.0']); + + proxyaddr(req, '::1'); + proxyaddr(req, ['::1/128', 'fe80::/10']); + + proxyaddr(req, 'loopback'); + proxyaddr(req, ['loopback', 'fc00:ac:1ab5:fff::1/64']); + + // $ExpectType string[] + proxyaddr.all(req); + proxyaddr.all(req, 'loopback'); + + const trust = proxyaddr.compile('localhost'); + proxyaddr.compile(['localhost']); + trust; // $ExpectType (addr: string, i: number) => boolean + proxyaddr(req, trust); +}); \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/.github/dependabot.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..be225b0af94422138289ed0c549ab7f08656bfab --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 + + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/.github/workflows/ci.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..fd45202abff682784e3a60d54fbfee567d304b26 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/.github/workflows/ci.yml @@ -0,0 +1,28 @@ +name: CI + +on: + push: + branches: + - main + - next + - 'v*' + paths-ignore: + - 'docs/**' + - '*.md' + pull_request: + paths-ignore: + - 'docs/**' + - '*.md' + +permissions: + contents: read + +jobs: + test: + permissions: + contents: write + pull-requests: write + uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5 + with: + license-check: true + lint: true diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/benchmarks/collapseLeadingSlashes.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/benchmarks/collapseLeadingSlashes.js new file mode 100644 index 0000000000000000000000000000000000000000..2b56dd4a58b86a920c1f1fec5e09f62d6550d77e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/benchmarks/collapseLeadingSlashes.js @@ -0,0 +1,13 @@ +'use strict' + +const benchmark = require('benchmark') +const collapseLeadingSlashes = require('../lib/collapseLeadingSlashes').collapseLeadingSlashes + +const nonLeading = 'bla.json' +const hasLeading = '///./json' + +new benchmark.Suite() + .add(nonLeading, function () { collapseLeadingSlashes(nonLeading) }, { minSamples: 100 }) + .add(hasLeading, function () { collapseLeadingSlashes(hasLeading) }, { minSamples: 100 }) + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/benchmarks/containsDotFile.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/benchmarks/containsDotFile.js new file mode 100644 index 0000000000000000000000000000000000000000..a9cbfc43022f024fa74961c07b2d1b1612d6583a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/benchmarks/containsDotFile.js @@ -0,0 +1,15 @@ +'use strict' + +const benchmark = require('benchmark') +const { containsDotFile } = require('../lib/containsDotFile') + +const hasDotFileSimple = '.github'.split('/') +const hasDotFile = './.github'.split('/') +const noDotFile = './index.html'.split('/') + +new benchmark.Suite() + .add(hasDotFileSimple.join('/'), function () { containsDotFile(hasDotFileSimple) }, { minSamples: 100 }) + .add(noDotFile.join('/'), function () { containsDotFile(noDotFile) }, { minSamples: 100 }) + .add(hasDotFile.join('/'), function () { containsDotFile(hasDotFile) }, { minSamples: 100 }) + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/benchmarks/isUtf8MimeType.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/benchmarks/isUtf8MimeType.js new file mode 100644 index 0000000000000000000000000000000000000000..a68a8bc03e343698a94795783c09919ea2d55315 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/benchmarks/isUtf8MimeType.js @@ -0,0 +1,23 @@ +'use strict' + +const benchmark = require('benchmark') +const isUtf8MimeType = require('../lib/isUtf8MimeType').isUtf8MimeType + +const applicationJson = 'application/json' +const applicationJavascript = 'application/javascript' +const textJson = 'text/json' +const textHtml = 'text/html' +const textJavascript = 'text/javascript' +const imagePng = 'image/png' + +new benchmark.Suite() + .add('isUtf8MimeType', function () { + isUtf8MimeType(applicationJson) + isUtf8MimeType(applicationJavascript) + isUtf8MimeType(imagePng) + isUtf8MimeType(textJson) + isUtf8MimeType(textHtml) + isUtf8MimeType(textJavascript) + }, { minSamples: 100 }) + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/benchmarks/normalizeList.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/benchmarks/normalizeList.js new file mode 100644 index 0000000000000000000000000000000000000000..9926ca3caa1ff0dadfe1972f5ca240ef589785ce --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/benchmarks/normalizeList.js @@ -0,0 +1,14 @@ +'use strict' + +const benchmark = require('benchmark') +const { normalizeList } = require('../lib/normalizeList') + +const validSingle = 'a' +const validArray = ['a', 'b', 'c'] + +new benchmark.Suite() + .add('false', function () { normalizeList(false) }, { minSamples: 100 }) + .add('valid single', function () { normalizeList(validSingle) }, { minSamples: 100 }) + .add('valid array', function () { normalizeList(validArray) }, { minSamples: 100 }) + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/benchmarks/parseBytesRange.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/benchmarks/parseBytesRange.js new file mode 100644 index 0000000000000000000000000000000000000000..48d59abae961fc6de0b9a2f82e9424a0c2306773 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/benchmarks/parseBytesRange.js @@ -0,0 +1,15 @@ +'use strict' + +const benchmark = require('benchmark') +const { parseBytesRange } = require('../lib/parseBytesRange') + +const size150 = 150 + +const rangeSingle = 'bytes=0-100' +const rangeMultiple = 'bytes=0-4,90-99,5-75,100-199,101-102' + +new benchmark.Suite() + .add('size: 150, bytes=0-100', function () { parseBytesRange(size150, rangeSingle) }, { minSamples: 100 }) + .add('size: 150, bytes=0-4,90-99,5-75,100-199,101-102', function () { parseBytesRange(size150, rangeMultiple) }, { minSamples: 100 }) + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/examples/index.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/examples/index.html new file mode 100644 index 0000000000000000000000000000000000000000..7f41cde5ec3164e627306898d98d9352f1ed8ddb --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/examples/index.html @@ -0,0 +1 @@ +

Hello, World

diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/examples/simple.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/examples/simple.js new file mode 100644 index 0000000000000000000000000000000000000000..5297b75b8256ad483e3526689b1184a4c06f43c4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/examples/simple.js @@ -0,0 +1,15 @@ +'use strict' + +const http = require('node:http') +const send = require('..') +const path = require('node:path') + +const indexPath = path.join(__dirname, 'index.html') + +const server = http.createServer(async function onRequest (req, res) { + const { statusCode, headers, stream } = await send(req, indexPath) + res.writeHead(statusCode, headers) + stream.pipe(res) +}) + +server.listen(3000) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/collapseLeadingSlashes.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/collapseLeadingSlashes.js new file mode 100644 index 0000000000000000000000000000000000000000..b611a9cdfd5d678f36db4ad5c5340e6e4705387b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/collapseLeadingSlashes.js @@ -0,0 +1,25 @@ +'use strict' + +/** + * Collapse all leading slashes into a single slash + * + * @param {string} str + * @private + */ + +function collapseLeadingSlashes (str) { + if ( + str[0] !== '/' || + str[1] !== '/' + ) { + return str + } + for (let i = 2, il = str.length; i < il; ++i) { + if (str[i] !== '/') { + return str.slice(i - 1) + } + } + /* c8 ignore next */ +} + +module.exports.collapseLeadingSlashes = collapseLeadingSlashes diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/containsDotFile.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/containsDotFile.js new file mode 100644 index 0000000000000000000000000000000000000000..c446aa0b3719c71564e75ddb22cbf74d59d860e2 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/containsDotFile.js @@ -0,0 +1,23 @@ +/*! + * send + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ +'use strict' +/** + * Determine if path parts contain a dotfile. + * + * @api private + */ +function containsDotFile (parts) { + for (let i = 0, il = parts.length; i < il; ++i) { + if (parts[i].length !== 1 && parts[i][0] === '.') { + return true + } + } + + return false +} + +module.exports.containsDotFile = containsDotFile diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/contentRange.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/contentRange.js new file mode 100644 index 0000000000000000000000000000000000000000..a2183edfef31adb2bb3937185ac65f65fec3c3df --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/contentRange.js @@ -0,0 +1,18 @@ +/*! + * send + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ +'use strict' +/** + * Create a Content-Range header. + * + * @param {string} type + * @param {number} size + * @param {array} [range] + */ +function contentRange (type, size, range) { + return type + ' ' + (range ? range.start + '-' + range.end : '*') + '/' + size +} +exports.contentRange = contentRange diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/createHtmlDocument.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/createHtmlDocument.js new file mode 100644 index 0000000000000000000000000000000000000000..d4d64d2b89c1f16b57750666075fee53d9218548 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/createHtmlDocument.js @@ -0,0 +1,29 @@ +/*! + * send + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2014-2022 Douglas Christopher Wilson + * MIT Licensed + */ +'use strict' +/** + * Create a minimal HTML document. + * + * @param {string} title + * @param {string} body + * @private + */ +function createHtmlDocument (title, body) { + const html = '\n' + + '\n' + + '\n' + + '\n' + + '' + title + '\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' + + return [html, Buffer.byteLength(html)] +} +exports.createHtmlDocument = createHtmlDocument diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/createHttpError.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/createHttpError.js new file mode 100644 index 0000000000000000000000000000000000000000..ba7bcca0166f68482586f0dbd9dc857602b97f59 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/createHttpError.js @@ -0,0 +1,23 @@ +'use strict' + +const createError = require('http-errors') + +/** + * Create a HttpError object from simple arguments. + * + * @param {number} status + * @param {Error|object} err + * @private + */ + +function createHttpError (status, err) { + if (!err) { + return createError(status) + } + + return err instanceof Error + ? createError(status, err, { expose: false }) + : createError(status, err) +} + +module.exports.createHttpError = createHttpError diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/isUtf8MimeType.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/isUtf8MimeType.js new file mode 100644 index 0000000000000000000000000000000000000000..d24978a8012753a012b9df2411ee96a5caac6410 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/isUtf8MimeType.js @@ -0,0 +1,12 @@ +'use strict' + +function isUtf8MimeType (value) { + const len = value.length + return ( + (len > 21 && value.indexOf('application/javascript') === 0) || + (len > 14 && value.indexOf('application/json') === 0) || + (len > 5 && value.indexOf('text/') === 0) + ) +} + +module.exports.isUtf8MimeType = isUtf8MimeType diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/normalizeList.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/normalizeList.js new file mode 100644 index 0000000000000000000000000000000000000000..b18eac974b0bc8c9232293fe986e4850627fb713 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/normalizeList.js @@ -0,0 +1,28 @@ +'use strict' + +/** + * Normalize the index option into an array. + * + * @param {boolean|string|array} val + * @param {string} name + * @private + */ + +function normalizeList (val, name) { + if (typeof val === 'string') { + return [val] + } else if (val === false) { + return [] + } else if (Array.isArray(val)) { + for (let i = 0, il = val.length; i < il; ++i) { + if (typeof val[i] !== 'string') { + throw new TypeError(name + ' must be array of strings or false') + } + } + return val + } else { + throw new TypeError(name + ' must be array of strings or false') + } +} + +module.exports.normalizeList = normalizeList diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/parseBytesRange.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/parseBytesRange.js new file mode 100644 index 0000000000000000000000000000000000000000..5235c3eda10b5ffabab0d28e80e3016298dcae66 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/parseBytesRange.js @@ -0,0 +1,133 @@ +'use strict' + +/*! + * Based on range-parser + * + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Parse "Range" header `str` relative to the given file `size`. + * + * @param {Number} size + * @param {String} str + * @return {Array} + * @public + */ + +function parseBytesRange (size, str) { + // split the range string + const values = str.slice(str.indexOf('=') + 1) + const ranges = [] + + const len = values.length + let i = 0 + let il = 0 + let j = 0 + let start + let end + let commaIdx = values.indexOf(',') + let dashIdx = values.indexOf('-') + let prevIdx = -1 + + // parse all ranges + while (true) { + commaIdx === -1 && (commaIdx = len) + start = parseInt(values.slice(prevIdx + 1, dashIdx), 10) + end = parseInt(values.slice(dashIdx + 1, commaIdx), 10) + + // -nnn + // eslint-disable-next-line no-self-compare + if (start !== start) { // fast path of isNaN(number) + start = size - end + end = size - 1 + // nnn- + // eslint-disable-next-line no-self-compare + } else if (end !== end) { // fast path of isNaN(number) + end = size - 1 + // limit last-byte-pos to current length + } else if (end > size - 1) { + end = size - 1 + } + + // add range only on valid ranges + if ( + // eslint-disable-next-line no-self-compare + start === start && // fast path of isNaN(number) + // eslint-disable-next-line no-self-compare + end === end && // fast path of isNaN(number) + start > -1 && + start <= end + ) { + // add range + ranges.push({ + start, + end, + index: j++ + }) + } + + if (commaIdx === len) { + break + } + prevIdx = commaIdx++ + dashIdx = values.indexOf('-', commaIdx) + commaIdx = values.indexOf(',', commaIdx) + } + + // unsatisfiable + if ( + j < 2 + ) { + return ranges + } + + ranges.sort(sortByRangeStart) + + il = j + j = 0 + i = 1 + while (i < il) { + const range = ranges[i++] + const current = ranges[j] + + if (range.start > current.end + 1) { + // next range + ranges[++j] = range + } else if (range.end > current.end) { + // extend range + current.end = range.end + current.index > range.index && (current.index = range.index) + } + } + + // trim ordered array + ranges.length = j + 1 + + // generate combined range + ranges.sort(sortByRangeIndex) + + return ranges +} + +/** + * Sort function to sort ranges by index. + * @private + */ + +function sortByRangeIndex (a, b) { + return a.index - b.index +} + +/** + * Sort function to sort ranges by start position. + * @private + */ + +function sortByRangeStart (a, b) { + return a.start - b.start +} + +module.exports.parseBytesRange = parseBytesRange diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/parseTokenList.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/parseTokenList.js new file mode 100644 index 0000000000000000000000000000000000000000..eb3e436bb21743cf401259630b2cab825a885fba --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/parseTokenList.js @@ -0,0 +1,46 @@ +'use strict' + +/** + * Parse a HTTP token list. + * + * @param {string} str + * @private + */ + +const slice = String.prototype.slice + +function parseTokenList (str, cb) { + let end = 0 + let start = 0 + let result + + // gather tokens + for (let i = 0, len = str.length; i < len; i++) { + switch (str.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + if (start !== end) { + result = cb(slice.call(str, start, end)) + if (result !== undefined) { + return result + } + } + start = end = i + 1 + break + default: + end = i + 1 + break + } + } + + // final token + if (start !== end) { + return cb(slice.call(str, start, end)) + } +} + +module.exports.parseTokenList = parseTokenList diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/send.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/send.js new file mode 100644 index 0000000000000000000000000000000000000000..a0f4a50c4e6ba2930ecddba0c7cf267db2fe5a4c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/lib/send.js @@ -0,0 +1,729 @@ +'use strict' + +const fs = require('node:fs') +const path = require('node:path') +const stream = require('node:stream') +const debug = require('node:util').debuglog('send') + +const decode = require('fast-decode-uri-component') +const escapeHtml = require('escape-html') +const mime = require('mime') +const ms = require('@lukeed/ms') + +const { collapseLeadingSlashes } = require('./collapseLeadingSlashes') +const { containsDotFile } = require('../lib/containsDotFile') +const { contentRange } = require('../lib/contentRange') +const { createHtmlDocument } = require('../lib/createHtmlDocument') +const { isUtf8MimeType } = require('../lib/isUtf8MimeType') +const { normalizeList } = require('../lib/normalizeList') +const { parseBytesRange } = require('../lib/parseBytesRange') +const { parseTokenList } = require('./parseTokenList') +const { createHttpError } = require('./createHttpError') + +/** + * Path function references. + * @private + */ + +const extname = path.extname +const join = path.join +const normalize = path.normalize +const resolve = path.resolve +const sep = path.sep + +/** + * Stream function references. + * @private + */ +const Readable = stream.Readable + +/** + * Regular expression for identifying a bytes Range header. + * @private + */ + +const BYTES_RANGE_REGEXP = /^ *bytes=/ + +/** + * Maximum value allowed for the max age. + * @private + */ + +const MAX_MAXAGE = 60 * 60 * 24 * 365 * 1000 // 1 year + +/** + * Regular expression to match a path with a directory up component. + * @private + */ + +const UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/ + +const ERROR_RESPONSES = { + 400: createHtmlDocument('Error', 'Bad Request'), + 403: createHtmlDocument('Error', 'Forbidden'), + 404: createHtmlDocument('Error', 'Not Found'), + 412: createHtmlDocument('Error', 'Precondition Failed'), + 416: createHtmlDocument('Error', 'Range Not Satisfiable'), + 500: createHtmlDocument('Error', 'Internal Server Error') +} + +const validDotFilesOptions = [ + 'allow', + 'ignore', + 'deny' +] + +function normalizeMaxAge (_maxage) { + let maxage + if (typeof _maxage === 'string') { + maxage = ms.parse(_maxage) + } else { + maxage = Number(_maxage) + } + + // eslint-disable-next-line no-self-compare + if (maxage !== maxage) { + // fast path of isNaN(number) + return 0 + } + + return Math.min(Math.max(0, maxage), MAX_MAXAGE) +} + +function normalizeOptions (options) { + options = options ?? {} + + const acceptRanges = options.acceptRanges !== undefined + ? Boolean(options.acceptRanges) + : true + + const cacheControl = options.cacheControl !== undefined + ? Boolean(options.cacheControl) + : true + + const contentType = options.contentType !== undefined + ? Boolean(options.contentType) + : true + + const etag = options.etag !== undefined + ? Boolean(options.etag) + : true + + const dotfiles = options.dotfiles !== undefined + ? validDotFilesOptions.indexOf(options.dotfiles) + : 1 // 'ignore' + if (dotfiles === -1) { + throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"') + } + + const extensions = options.extensions !== undefined + ? normalizeList(options.extensions, 'extensions option') + : [] + + const immutable = options.immutable !== undefined + ? Boolean(options.immutable) + : false + + const index = options.index !== undefined + ? normalizeList(options.index, 'index option') + : ['index.html'] + + const lastModified = options.lastModified !== undefined + ? Boolean(options.lastModified) + : true + + const maxage = normalizeMaxAge(options.maxAge ?? options.maxage) + + const maxContentRangeChunkSize = options.maxContentRangeChunkSize !== undefined + ? Number(options.maxContentRangeChunkSize) + : null + + const root = options.root + ? resolve(options.root) + : null + + const highWaterMark = Number.isSafeInteger(options.highWaterMark) && options.highWaterMark > 0 + ? options.highWaterMark + : null + + return { + acceptRanges, + cacheControl, + contentType, + etag, + dotfiles, + extensions, + immutable, + index, + lastModified, + maxage, + maxContentRangeChunkSize, + root, + highWaterMark, + start: options.start, + end: options.end + } +} + +function normalizePath (_path, root) { + // decode the path + let path = decode(_path) + if (path == null) { + return { statusCode: 400 } + } + + // null byte(s) + if (~path.indexOf('\0')) { + return { statusCode: 400 } + } + + let parts + if (root !== null) { + // normalize + if (path) { + path = normalize('.' + sep + path) + } + + // malicious path + if (UP_PATH_REGEXP.test(path)) { + debug('malicious path "%s"', path) + return { statusCode: 403 } + } + + // explode path parts + parts = path.split(sep) + + // join / normalize from optional root dir + path = normalize(join(root, path)) + } else { + // ".." is malicious without "root" + if (UP_PATH_REGEXP.test(path)) { + debug('malicious path "%s"', path) + return { statusCode: 403 } + } + + // explode path parts + parts = normalize(path).split(sep) + + // resolve the path + path = resolve(path) + } + + return { path, parts } +} + +/** + * Check if the pathname ends with "/". + * + * @return {boolean} + * @private + */ + +function hasTrailingSlash (path) { + return path[path.length - 1] === '/' +} + +/** + * Check if this is a conditional GET request. + * + * @return {Boolean} + * @api private + */ + +function isConditionalGET (request) { + return request.headers['if-match'] || + request.headers['if-unmodified-since'] || + request.headers['if-none-match'] || + request.headers['if-modified-since'] +} + +function isNotModifiedFailure (request, headers) { + // Always return stale when Cache-Control: no-cache + // to support end-to-end reload requests + // https://tools.ietf.org/html/rfc2616#section-14.9.4 + if ( + 'cache-control' in request.headers && + request.headers['cache-control'].indexOf('no-cache') !== -1 + ) { + return false + } + + // if-none-match + if ('if-none-match' in request.headers) { + const ifNoneMatch = request.headers['if-none-match'] + + if (ifNoneMatch === '*') { + return true + } + + const etag = headers.ETag + + if (typeof etag !== 'string') { + return false + } + + const etagL = etag.length + const isMatching = parseTokenList(ifNoneMatch, function (match) { + const mL = match.length + + if ( + (etagL === mL && match === etag) || + (etagL > mL && 'W/' + match === etag) + ) { + return true + } + }) + + if (isMatching) { + return true + } + + /** + * A recipient MUST ignore If-Modified-Since if the request contains an + * If-None-Match header field; the condition in If-None-Match is considered + * to be a more accurate replacement for the condition in If-Modified-Since, + * and the two are only combined for the sake of interoperating with older + * intermediaries that might not implement If-None-Match. + * + * @see RFC 9110 section 13.1.3 + */ + return false + } + + // if-modified-since + if ('if-modified-since' in request.headers) { + const ifModifiedSince = request.headers['if-modified-since'] + const lastModified = headers['Last-Modified'] + + if (!lastModified || (Date.parse(lastModified) <= Date.parse(ifModifiedSince))) { + return true + } + } + + return false +} + +/** + * Check if the request preconditions failed. + * + * @return {boolean} + * @private + */ + +function isPreconditionFailure (request, headers) { + // if-match + const ifMatch = request.headers['if-match'] + if (ifMatch) { + const etag = headers.ETag + + if (ifMatch !== '*') { + const isMatching = parseTokenList(ifMatch, function (match) { + if ( + match === etag || + 'W/' + match === etag + ) { + return true + } + }) || false + + if (isMatching !== true) { + return true + } + } + } + + // if-unmodified-since + if ('if-unmodified-since' in request.headers) { + const ifUnmodifiedSince = request.headers['if-unmodified-since'] + const unmodifiedSince = Date.parse(ifUnmodifiedSince) + // eslint-disable-next-line no-self-compare + if (unmodifiedSince === unmodifiedSince) { // fast path of isNaN(number) + const lastModified = Date.parse(headers['Last-Modified']) + if ( + // eslint-disable-next-line no-self-compare + lastModified !== lastModified ||// fast path of isNaN(number) + lastModified > unmodifiedSince + ) { + return true + } + } + } + + return false +} + +/** + * Check if the range is fresh. + * + * @return {Boolean} + * @api private + */ + +function isRangeFresh (request, headers) { + if (!('if-range' in request.headers)) { + return true + } + + const ifRange = request.headers['if-range'] + + // if-range as etag + if (ifRange.indexOf('"') !== -1) { + const etag = headers.ETag + return (etag && ifRange.indexOf(etag) !== -1) || false + } + + const ifRangeTimestamp = Date.parse(ifRange) + // eslint-disable-next-line no-self-compare + if (ifRangeTimestamp !== ifRangeTimestamp) { // fast path of isNaN(number) + return false + } + + // if-range as modified date + const lastModified = Date.parse(headers['Last-Modified']) + + return ( + // eslint-disable-next-line no-self-compare + lastModified !== lastModified || // fast path of isNaN(number) + lastModified <= ifRangeTimestamp + ) +} + +// we provide stat function that will always resolve +// without throwing +function tryStat (path) { + return new Promise((resolve) => { + fs.stat(path, function onstat (error, stat) { + resolve({ error, stat }) + }) + }) +} + +function sendError (statusCode, err) { + const headers = {} + + // add error headers + if (err && err.headers) { + for (const headerName in err.headers) { + headers[headerName] = err.headers[headerName] + } + } + + const doc = ERROR_RESPONSES[statusCode] + + // basic response + headers['Content-Type'] = 'text/html; charset=utf-8' + headers['Content-Length'] = doc[1] + headers['Content-Security-Policy'] = "default-src 'none'" + headers['X-Content-Type-Options'] = 'nosniff' + + return { + statusCode, + headers, + stream: Readable.from(doc[0]), + // metadata + type: 'error', + metadata: { error: createHttpError(statusCode, err) } + } +} + +function sendStatError (err) { + // POSIX throws ENAMETOOLONG and ENOTDIR, Windows only ENOENT + /* c8 ignore start */ + switch (err.code) { + case 'ENAMETOOLONG': + case 'ENOTDIR': + case 'ENOENT': + return sendError(404, err) + default: + return sendError(500, err) + } + /* c8 ignore stop */ +} + +/** + * Respond with 304 not modified. + * + * @api private + */ + +function sendNotModified (headers, path, stat) { + debug('not modified') + + delete headers['Content-Encoding'] + delete headers['Content-Language'] + delete headers['Content-Length'] + delete headers['Content-Range'] + delete headers['Content-Type'] + + return { + statusCode: 304, + headers, + stream: Readable.from(''), + // metadata + type: 'file', + metadata: { path, stat } + } +} + +function sendFileDirectly (request, path, stat, options) { + let len = stat.size + let offset = options.start ?? 0 + + let statusCode = 200 + const headers = {} + + debug('send "%s"', path) + + // set header fields + if (options.acceptRanges) { + debug('accept ranges') + headers['Accept-Ranges'] = 'bytes' + } + + if (options.cacheControl) { + let cacheControl = 'public, max-age=' + Math.floor(options.maxage / 1000) + + if (options.immutable) { + cacheControl += ', immutable' + } + + debug('cache-control %s', cacheControl) + headers['Cache-Control'] = cacheControl + } + + if (options.lastModified) { + const modified = stat.mtime.toUTCString() + debug('modified %s', modified) + headers['Last-Modified'] = modified + } + + if (options.etag) { + const etag = 'W/"' + stat.size.toString(16) + '-' + stat.mtime.getTime().toString(16) + '"' + debug('etag %s', etag) + headers.ETag = etag + } + + // set content-type + if (options.contentType) { + let type = mime.getType(path) || mime.default_type + debug('content-type %s', type) + if (type && isUtf8MimeType(type)) { + type += '; charset=utf-8' + } + if (type) { + headers['Content-Type'] = type + } + } + + // conditional GET support + if (isConditionalGET(request)) { + if (isPreconditionFailure(request, headers)) { + return sendError(412) + } + + if (isNotModifiedFailure(request, headers)) { + return sendNotModified(headers, path, stat) + } + } + + // adjust len to start/end options + len = Math.max(0, len - offset) + if (options.end !== undefined) { + const bytes = options.end - offset + 1 + if (len > bytes) len = bytes + } + + // Range support + if (options.acceptRanges) { + const rangeHeader = request.headers.range + + if ( + rangeHeader !== undefined && + BYTES_RANGE_REGEXP.test(rangeHeader) + ) { + // If-Range support + if (isRangeFresh(request, headers)) { + // parse + const ranges = parseBytesRange(len, rangeHeader) + + // unsatisfiable + if (ranges.length === 0) { + debug('range unsatisfiable') + + // Content-Range + headers['Content-Range'] = contentRange('bytes', len) + + // 416 Requested Range Not Satisfiable + return sendError(416, { + headers: { 'Content-Range': headers['Content-Range'] } + }) + // valid (syntactically invalid/multiple ranges are treated as a regular response) + } else if (ranges.length === 1) { + debug('range %j', ranges) + + // Content-Range + statusCode = 206 + if (options.maxContentRangeChunkSize) { + ranges[0].end = Math.min(ranges[0].end, ranges[0].start + options.maxContentRangeChunkSize - 1) + } + headers['Content-Range'] = contentRange('bytes', len, ranges[0]) + + // adjust for requested range + offset += ranges[0].start + len = ranges[0].end - ranges[0].start + 1 + } + } else { + debug('range stale') + } + } + } + + // content-length + headers['Content-Length'] = len + + // HEAD support + if (request.method === 'HEAD') { + return { + statusCode, + headers, + stream: Readable.from(''), + // metadata + type: 'file', + metadata: { path, stat } + } + } + + const stream = fs.createReadStream(path, { + highWaterMark: options.highWaterMark, + start: offset, + end: Math.max(offset, offset + len - 1) + }) + + return { + statusCode, + headers, + stream, + // metadata + type: 'file', + metadata: { path, stat } + } +} + +function sendRedirect (path, options) { + if (hasTrailingSlash(options.path)) { + return sendError(403) + } + + const loc = encodeURI(collapseLeadingSlashes(options.path + '/')) + const doc = createHtmlDocument('Redirecting', 'Redirecting to ' + escapeHtml(loc)) + + const headers = {} + headers['Content-Type'] = 'text/html; charset=utf-8' + headers['Content-Length'] = doc[1] + headers['Content-Security-Policy'] = "default-src 'none'" + headers['X-Content-Type-Options'] = 'nosniff' + headers.Location = loc + + return { + statusCode: 301, + headers, + stream: Readable.from(doc[0]), + // metadata + type: 'directory', + metadata: { requestPath: options.path, path } + } +} + +async function sendIndex (request, path, options) { + let err + for (let i = 0; i < options.index.length; i++) { + const index = options.index[i] + const p = join(path, index) + const { error, stat } = await tryStat(p) + if (error) { + err = error + continue + } + if (stat.isDirectory()) continue + return sendFileDirectly(request, p, stat, options) + } + + if (err) { + return sendStatError(err) + } + + return sendError(404) +} + +async function sendFile (request, path, options) { + const { error, stat } = await tryStat(path) + if (error && error.code === 'ENOENT' && !extname(path) && path[path.length - 1] !== sep) { + let err = error + // not found, check extensions + for (let i = 0; i < options.extensions.length; i++) { + const extension = options.extensions[i] + const p = path + '.' + extension + const { error, stat } = await tryStat(p) + if (error) { + err = error + continue + } + if (stat.isDirectory()) { + err = null + continue + } + return sendFileDirectly(request, p, stat, options) + } + if (err) { + return sendStatError(err) + } + return sendError(404) + } + if (error) return sendStatError(error) + if (stat.isDirectory()) return sendRedirect(path, options) + return sendFileDirectly(request, path, stat, options) +} + +async function send (request, _path, options) { + const opts = normalizeOptions(options) + opts.path = _path + + const parsed = normalizePath(_path, opts.root) + const { path, parts } = parsed + if (parsed.statusCode !== undefined) { + return sendError(parsed.statusCode) + } + + // dotfile handling + if ( + ( + debug.enabled || // if debugging is enabled, then check for all cases to log allow case + opts.dotfiles !== 0 // if debugging is not enabled, then only check if 'deny' or 'ignore' is set + ) && + containsDotFile(parts) + ) { + switch (opts.dotfiles) { + /* c8 ignore start */ /* unreachable, because NODE_DEBUG can not be set after process is running */ + case 0: // 'allow' + debug('allow dotfile "%s"', path) + break + /* c8 ignore stop */ + case 2: // 'deny' + debug('deny dotfile "%s"', path) + return sendError(403) + case 1: // 'ignore' + default: + debug('ignore dotfile "%s"', path) + return sendError(404) + } + } + + // index file support + if (opts.index.length && hasTrailingSlash(_path)) { + return sendIndex(request, path, opts) + } + + return sendFile(request, path, opts) +} + +module.exports.send = send diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/collapseLeadingSlashes.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/collapseLeadingSlashes.test.js new file mode 100644 index 0000000000000000000000000000000000000000..1410d7a09cdcfff66ac950e2b5bdb96fce75382c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/collapseLeadingSlashes.test.js @@ -0,0 +1,22 @@ +'use strict' + +const { test } = require('node:test') +const { collapseLeadingSlashes } = require('../lib/collapseLeadingSlashes') + +test('collapseLeadingSlashes', function (t) { + const testCases = [ + ['abcd', 'abcd'], + ['text/json', 'text/json'], + ['/text/json', '/text/json'], + ['//text/json', '/text/json'], + ['///text/json', '/text/json'], + ['/.//text/json', '/.//text/json'], + ['//./text/json', '/./text/json'], + ['///./text/json', '/./text/json'] + ] + t.plan(testCases.length) + + for (const testCase of testCases) { + t.assert.deepStrictEqual(collapseLeadingSlashes(testCase[0]), testCase[1]) + } +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/containsDotFile.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/containsDotFile.test.js new file mode 100644 index 0000000000000000000000000000000000000000..7e9d6647490c9e41b3ce3a58467dcead2fe68b24 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/containsDotFile.test.js @@ -0,0 +1,18 @@ +'use strict' + +const { test } = require('node:test') +const { containsDotFile } = require('../lib/containsDotFile') + +test('containsDotFile', function (t) { + const testCases = [ + ['/.github', true], + ['.github', true], + ['index.html', false], + ['./index.html', false] + ] + t.plan(testCases.length) + + for (const testCase of testCases) { + t.assert.deepStrictEqual(containsDotFile(testCase[0].split('/')), testCase[1], testCase[0]) + } +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/.hidden.txt b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/.hidden.txt new file mode 100644 index 0000000000000000000000000000000000000000..536aca34dbae6b2b8af26bebdcba83543c9546f0 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/.hidden.txt @@ -0,0 +1 @@ +secret \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/.mine/.hidden.txt b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/.mine/.hidden.txt new file mode 100644 index 0000000000000000000000000000000000000000..d97c5eada5d8c52079031eef0107a4430a9617c5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/.mine/.hidden.txt @@ -0,0 +1 @@ +secret diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/.mine/name.txt b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/.mine/name.txt new file mode 100644 index 0000000000000000000000000000000000000000..fa66f37ff2170afebb34dd2da5a1ba69d3657270 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/.mine/name.txt @@ -0,0 +1 @@ +tobi \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/do..ts.txt b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/do..ts.txt new file mode 100644 index 0000000000000000000000000000000000000000..90a1d60ab71387c42694fa4b6335c37f51255fc2 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/do..ts.txt @@ -0,0 +1 @@ +... \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/empty.txt b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/empty.txt new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/name.d/name.txt b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/name.d/name.txt new file mode 100644 index 0000000000000000000000000000000000000000..789c47ab13a523803dd653520c787a93cb98ca2c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/name.d/name.txt @@ -0,0 +1 @@ +loki \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/name.dir/name.txt b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/name.dir/name.txt new file mode 100644 index 0000000000000000000000000000000000000000..fa66f37ff2170afebb34dd2da5a1ba69d3657270 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/name.dir/name.txt @@ -0,0 +1 @@ +tobi \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/name.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/name.html new file mode 100644 index 0000000000000000000000000000000000000000..52b192303484e35a267b2df79245808ad1686aa9 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/name.html @@ -0,0 +1 @@ +

tobi

\ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/name.txt b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/name.txt new file mode 100644 index 0000000000000000000000000000000000000000..fa66f37ff2170afebb34dd2da5a1ba69d3657270 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/name.txt @@ -0,0 +1 @@ +tobi \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/no_ext b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/no_ext new file mode 100644 index 0000000000000000000000000000000000000000..f6ea0495187600e7b2288c8ac19c5886383a4632 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/no_ext @@ -0,0 +1 @@ +foobar \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/nums.txt b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/nums.txt new file mode 100644 index 0000000000000000000000000000000000000000..e2e107ac61ac259b87c544f6e7a4eb03422c6c21 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/nums.txt @@ -0,0 +1 @@ +123456789 \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/pets/.hidden.txt b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/pets/.hidden.txt new file mode 100644 index 0000000000000000000000000000000000000000..d97c5eada5d8c52079031eef0107a4430a9617c5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/pets/.hidden.txt @@ -0,0 +1 @@ +secret diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/pets/index.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/pets/index.html new file mode 100644 index 0000000000000000000000000000000000000000..5106b6f5dbc8d89a7d4b4ef9961ca4d5bbfb6746 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/pets/index.html @@ -0,0 +1,3 @@ +tobi +loki +jane \ No newline at end of file diff --git "a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/snow \342\230\203/index.html" "b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/snow \342\230\203/index.html" new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/some thing.txt b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/some thing.txt new file mode 100644 index 0000000000000000000000000000000000000000..2b31011cf9de6c82d52dc386cd7d1a9be83188c1 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/some thing.txt @@ -0,0 +1 @@ +hey \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/thing.html.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/thing.html.html new file mode 100644 index 0000000000000000000000000000000000000000..d5644325b6382287619c9c75cc0fda93cafc7e08 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/thing.html.html @@ -0,0 +1 @@ +

trap!

\ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/tobi.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/tobi.html new file mode 100644 index 0000000000000000000000000000000000000000..52b192303484e35a267b2df79245808ad1686aa9 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/fixtures/tobi.html @@ -0,0 +1 @@ +

tobi

\ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/isUtf8MimeType.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/isUtf8MimeType.test.js new file mode 100644 index 0000000000000000000000000000000000000000..daad69368c13f250b201f3f427c5742cefc21626 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/isUtf8MimeType.test.js @@ -0,0 +1,22 @@ +'use strict' + +const { test } = require('node:test') +const { isUtf8MimeType } = require('../lib/isUtf8MimeType') + +test('isUtf8MimeType', function (t) { + const testCases = [ + ['application/json', true], + ['text/json', true], + ['application/javascript', true], + ['text/javascript', true], + ['application/json+v5', true], + ['text/xml', true], + ['text/html', true], + ['image/png', false] + ] + t.plan(testCases.length) + + for (const testCase of testCases) { + t.assert.deepStrictEqual(isUtf8MimeType(testCase[0], 'test'), testCase[1]) + } +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/mime.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/mime.test.js new file mode 100644 index 0000000000000000000000000000000000000000..433a003f8d8672d0142963980b2464bc70f00168 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/mime.test.js @@ -0,0 +1,56 @@ +'use strict' + +const { test } = require('node:test') +const path = require('node:path') +const request = require('supertest') +const send = require('..') +const { shouldNotHaveHeader, createServer } = require('./utils') + +const fixtures = path.join(__dirname, 'fixtures') + +test('send.mime', async function (t) { + t.plan(2) + + await t.test('should be exposed', function (t) { + t.plan(1) + t.assert.ok(send.mime) + }) + + await t.test('.default_type', async function (t) { + t.plan(3) + + t.before(() => { + this.default_type = send.mime.default_type + }) + + t.afterEach(() => { + send.mime.default_type = this.default_type + }) + + await t.test('should change the default type', async function (t) { + send.mime.default_type = 'text/plain' + + await request(createServer({ root: fixtures })) + .get('/no_ext') + .expect('Content-Type', 'text/plain; charset=utf-8') + .expect(200) + }) + + await t.test('should not add Content-Type for undefined default', async function (t) { + t.plan(1) + send.mime.default_type = undefined + + await request(createServer({ root: fixtures })) + .get('/no_ext') + .expect(shouldNotHaveHeader('Content-Type', t)) + .expect(200) + }) + + await t.test('should return Content-Type without charset', async function (t) { + await request(createServer({ root: fixtures })) + .get('/images/node-js.png') + .expect('Content-Type', 'image/png') + .expect(200) + }) + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/normalizeList.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/normalizeList.test.js new file mode 100644 index 0000000000000000000000000000000000000000..84b821652ada2c83cfd374419dc4a710e756d860 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/normalizeList.test.js @@ -0,0 +1,28 @@ +'use strict' + +const { test } = require('node:test') +const { normalizeList } = require('../lib/normalizeList') + +test('normalizeList', function (t) { + const testCases = [ + [undefined, new TypeError('test must be array of strings or false')], + [false, []], + [[], []], + ['', ['']], + [[''], ['']], + [['a'], ['a']], + ['a', ['a']], + [true, new TypeError('test must be array of strings or false')], + [1, new TypeError('test must be array of strings or false')], + [[1], new TypeError('test must be array of strings or false')] + ] + t.plan(testCases.length) + + for (const testCase of testCases) { + if (testCase[1] instanceof Error) { + t.assert.throws(() => normalizeList(testCase[0], 'test'), testCase[1]) + } else { + t.assert.deepStrictEqual(normalizeList(testCase[0], 'test'), testCase[1]) + } + } +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/parseBytesRange.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/parseBytesRange.test.js new file mode 100644 index 0000000000000000000000000000000000000000..dcbf3250f5240df3e8364d5d8fc94ece817eedde --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/parseBytesRange.test.js @@ -0,0 +1,103 @@ +'use strict' + +const { test } = require('node:test') +const { parseBytesRange } = require('../lib/parseBytesRange') + +test('parseBytesRange', async function (t) { + t.plan(13) + + await t.test('should return empty array if all specified ranges are invalid', function (t) { + t.plan(3) + t.assert.deepStrictEqual(parseBytesRange(200, 'bytes=500-20'), []) + t.assert.deepStrictEqual(parseBytesRange(200, 'bytes=500-999'), []) + t.assert.deepStrictEqual(parseBytesRange(200, 'bytes=500-999,1000-1499'), []) + }) + + await t.test('should parse str', function (t) { + t.plan(2) + const range = parseBytesRange(1000, 'bytes=0-499') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 0, end: 499, index: 0 }) + }) + + await t.test('should cap end at size', function (t) { + t.plan(2) + const range = parseBytesRange(200, 'bytes=0-499') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 0, end: 199, index: 0 }) + }) + + await t.test('should parse str', function (t) { + t.plan(2) + const range = parseBytesRange(1000, 'bytes=40-80') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 40, end: 80, index: 0 }) + }) + + await t.test('should parse str asking for last n bytes', function (t) { + t.plan(2) + const range = parseBytesRange(1000, 'bytes=-400') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 600, end: 999, index: 0 }) + }) + + await t.test('should parse str with only start', function (t) { + t.plan(2) + const range = parseBytesRange(1000, 'bytes=400-') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 400, end: 999, index: 0 }) + }) + + await t.test('should parse "bytes=0-"', function (t) { + t.plan(2) + const range = parseBytesRange(1000, 'bytes=0-') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 0, end: 999, index: 0 }) + }) + + await t.test('should parse str with no bytes', function (t) { + t.plan(2) + const range = parseBytesRange(1000, 'bytes=0-0') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 0, end: 0, index: 0 }) + }) + + await t.test('should parse str asking for last byte', function (t) { + t.plan(2) + const range = parseBytesRange(1000, 'bytes=-1') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 999, end: 999, index: 0 }) + }) + + await t.test('should parse str with some invalid ranges', function (t) { + t.plan(2) + const range = parseBytesRange(200, 'bytes=0-499,1000-,500-999') + t.assert.deepStrictEqual(range.length, 1) + t.assert.deepStrictEqual(range[0], { start: 0, end: 199, index: 0 }) + }) + + await t.test('should combine overlapping ranges', function (t) { + t.plan(3) + const range = parseBytesRange(150, 'bytes=0-4,90-99,5-75,100-199,101-102') + t.assert.deepStrictEqual(range.length, 2) + t.assert.deepStrictEqual(range[0], { start: 0, end: 75, index: 0 }) + t.assert.deepStrictEqual(range[1], { start: 90, end: 149, index: 1 }) + }) + + await t.test('should retain original order /1', function (t) { + t.plan(3) + const range = parseBytesRange(150, 'bytes=90-99,5-75,100-199,101-102,0-4') + t.assert.deepStrictEqual(range.length, 2) + t.assert.deepStrictEqual(range[0], { start: 90, end: 149, index: 0 }) + t.assert.deepStrictEqual(range[1], { start: 0, end: 75, index: 1 }) + }) + + await t.test('should retain original order /2', function (t) { + t.plan(4) + const range = parseBytesRange(150, 'bytes=-1,20-100,0-1,101-120') + t.assert.deepStrictEqual(range.length, 3) + t.assert.deepStrictEqual(range[0], { start: 149, end: 149, index: 0 }) + t.assert.deepStrictEqual(range[1], { start: 20, end: 120, index: 1 }) + t.assert.deepStrictEqual(range[2], { start: 0, end: 1, index: 2 }) + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/send.1.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/send.1.test.js new file mode 100644 index 0000000000000000000000000000000000000000..aa0c5818c990863c190808bc49c04fe6175b7cd8 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/send.1.test.js @@ -0,0 +1,646 @@ +'use strict' + +const { test } = require('node:test') +const fs = require('node:fs') +const http = require('node:http') +const path = require('node:path') +const request = require('supertest') +const { send } = require('..') +const { shouldNotHaveHeader, createServer } = require('./utils') +const { getDefaultHighWaterMark } = require('node:stream') + +// test server + +const fixtures = path.join(__dirname, 'fixtures') + +test('send(file, options)', async function (t) { + t.plan(12) + + await t.test('acceptRanges', async function (t) { + t.plan(6) + + await t.test('should support disabling accept-ranges', async function (t) { + t.plan(1) + + await request(createServer({ acceptRanges: false, root: fixtures })) + .get('/nums.txt') + .expect(shouldNotHaveHeader('Accept-Ranges', t)) + .expect(200) + }) + + await t.test('should ignore requested range', async function (t) { + t.plan(2) + + await request(createServer({ acceptRanges: false, root: fixtures })) + .get('/nums.txt') + .set('Range', 'bytes=0-2') + .expect(shouldNotHaveHeader('Accept-Ranges', t)) + .expect(shouldNotHaveHeader('Content-Range', t)) + .expect(200, '123456789') + }) + + await t.test('should limit high return size /1', async function (t) { + t.plan(3) + + await request(createServer({ acceptRanges: true, maxContentRangeChunkSize: 1, root: fixtures })) + .get('/nums.txt') + .set('Range', 'bytes=0-2') + .expect((res) => t.assert.deepStrictEqual(res.headers['accept-ranges'], 'bytes')) + .expect((res) => t.assert.deepStrictEqual(res.headers['content-range'], 'bytes 0-0/9')) + .expect((res) => t.assert.deepStrictEqual(res.headers['content-length'], '1', 'should content-length must be as same as maxContentRangeChunkSize')) + .expect(206, '1') + }) + + await t.test('should limit high return size /2', async function (t) { + t.plan(3) + + await request(createServer({ acceptRanges: true, maxContentRangeChunkSize: 1, root: fixtures })) + .get('/nums.txt') + .set('Range', 'bytes=1-2') + .expect((res) => t.assert.deepStrictEqual(res.headers['accept-ranges'], 'bytes')) + .expect((res) => t.assert.deepStrictEqual(res.headers['content-range'], 'bytes 1-1/9')) + .expect((res) => t.assert.deepStrictEqual(res.headers['content-length'], '1', 'should content-length must be as same as maxContentRangeChunkSize')) + .expect(206, '2') + }) + + await t.test('should limit high return size /3', async function (t) { + t.plan(3) + + await request(createServer({ acceptRanges: true, maxContentRangeChunkSize: 1, root: fixtures })) + .get('/nums.txt') + .set('Range', 'bytes=1-3') + .expect((res) => t.assert.deepStrictEqual(res.headers['accept-ranges'], 'bytes')) + .expect((res) => t.assert.deepStrictEqual(res.headers['content-range'], 'bytes 1-1/9')) + .expect((res) => t.assert.deepStrictEqual(res.headers['content-length'], '1', 'should content-length must be as same as maxContentRangeChunkSize')) + .expect(206, '2') + }) + + await t.test('should limit high return size /4', async function (t) { + t.plan(3) + + await request(createServer({ acceptRanges: true, maxContentRangeChunkSize: 4, root: fixtures })) + .get('/nums.txt') + .set('Range', 'bytes=1-2,3-6') + .expect((res) => t.assert.deepStrictEqual(res.headers['accept-ranges'], 'bytes')) + .expect((res) => t.assert.deepStrictEqual(res.headers['content-range'], 'bytes 1-4/9')) + .expect((res) => t.assert.deepStrictEqual(res.headers['content-length'], '4', 'should content-length must be as same as maxContentRangeChunkSize')) + .expect(206, '2345') + }) + }) + + await t.test('cacheControl', async function (t) { + t.plan(2) + + await t.test('should support disabling cache-control', async function (t) { + t.plan(1) + await request(createServer({ cacheControl: false, root: fixtures })) + .get('/name.txt') + .expect(shouldNotHaveHeader('Cache-Control', t)) + .expect(200) + }) + + await t.test('should ignore maxAge option', async function (t) { + t.plan(1) + + await request(createServer({ cacheControl: false, maxAge: 1000, root: fixtures })) + .get('/name.txt') + .expect(shouldNotHaveHeader('Cache-Control', t)) + .expect(200) + }) + }) + + await t.test('contentType', async function (t) { + t.plan(1) + + await t.test('should support disabling content-type', async function (t) { + t.plan(1) + + await request(createServer({ contentType: false, root: fixtures })) + .get('/name.txt') + .expect(shouldNotHaveHeader('Content-Type', t)) + .expect(200) + }) + }) + + await t.test('etag', async function (t) { + t.plan(1) + + await t.test('should support disabling etags', async function (t) { + t.plan(1) + + await request(createServer({ etag: false, root: fixtures })) + .get('/name.txt') + .expect(shouldNotHaveHeader('ETag', t)) + .expect(200) + }) + }) + + await t.test('extensions', async function (t) { + t.plan(9) + + await t.test('should reject numbers', async function (t) { + await request(createServer({ extensions: 42, root: fixtures })) + .get('/pets/') + .expect(500, /TypeError: extensions option/) + }) + + await t.test('should reject true', async function (t) { + await request(createServer({ extensions: true, root: fixtures })) + .get('/pets/') + .expect(500, /TypeError: extensions option/) + }) + + await t.test('should be not be enabled by default', async function (t) { + await request(createServer({ root: fixtures })) + .get('/tobi') + .expect(404) + }) + + await t.test('should be configurable', async function (t) { + await request(createServer({ extensions: 'txt', root: fixtures })) + .get('/name') + .expect(200, 'tobi') + }) + + await t.test('should support disabling extensions', async function (t) { + await request(createServer({ extensions: false, root: fixtures })) + .get('/name') + .expect(404) + }) + + await t.test('should support fallbacks', async function (t) { + await request(createServer({ extensions: ['htm', 'html', 'txt'], root: fixtures })) + .get('/name') + .expect(200, '

tobi

') + }) + + await t.test('should 404 if nothing found', async function (t) { + await request(createServer({ extensions: ['htm', 'html', 'txt'], root: fixtures })) + .get('/bob') + .expect(404) + }) + + await t.test('should skip directories', async function (t) { + await request(createServer({ extensions: ['file', 'dir'], root: fixtures })) + .get('/name') + .expect(404) + }) + + await t.test('should not search if file has extension', async function (t) { + await request(createServer({ extensions: 'html', root: fixtures })) + .get('/thing.html') + .expect(404) + }) + }) + + await t.test('lastModified', async function (t) { + t.plan(1) + + await t.test('should support disabling last-modified', async function (t) { + t.plan(1) + + await request(createServer({ lastModified: false, root: fixtures })) + .get('/name.txt') + .expect(shouldNotHaveHeader('Last-Modified', t)) + .expect(200) + }) + }) + + await t.test('dotfiles', async function (t) { + t.plan(5) + + await t.test('should default to "ignore"', async function (t) { + await request(createServer({ root: fixtures })) + .get('/.hidden.txt') + .expect(404) + }) + + await t.test('should reject bad value', async function (t) { + await request(createServer({ dotfiles: 'bogus' })) + .get('/name.txt') + .expect(500, /dotfiles/) + }) + + await t.test('when "allow"', async function (t) { + t.plan(3) + + await t.test('should send dotfile', async function (t) { + await request(createServer({ dotfiles: 'allow', root: fixtures })) + .get('/.hidden.txt') + .expect(200, 'secret') + }) + + await t.test('should send within dotfile directory', async function (t) { + await request(createServer({ dotfiles: 'allow', root: fixtures })) + .get('/.mine/name.txt') + .expect(200, /tobi/) + }) + + await t.test('should 404 for non-existent dotfile', async function (t) { + await request(createServer({ dotfiles: 'allow', root: fixtures })) + .get('/.nothere') + .expect(404) + }) + }) + + await t.test('when "deny"', async function (t) { + t.plan(10) + + await t.test('should 403 for dotfile', async function (t) { + await request(createServer({ dotfiles: 'deny', root: fixtures })) + .get('/.hidden.txt') + .expect(403) + }) + + await t.test('should 403 for dotfile directory', async function (t) { + await request(createServer({ dotfiles: 'deny', root: fixtures })) + .get('/.mine') + .expect(403) + }) + + await t.test('should 403 for dotfile directory with trailing slash', async function (t) { + await request(createServer({ dotfiles: 'deny', root: fixtures })) + .get('/.mine/') + .expect(403) + }) + + await t.test('should 403 for file within dotfile directory', async function (t) { + await request(createServer({ dotfiles: 'deny', root: fixtures })) + .get('/.mine/name.txt') + .expect(403) + }) + + await t.test('should 403 for non-existent dotfile', async function (t) { + await request(createServer({ dotfiles: 'deny', root: fixtures })) + .get('/.nothere') + .expect(403) + }) + + await t.test('should 403 for non-existent dotfile directory', async function (t) { + await request(createServer({ dotfiles: 'deny', root: fixtures })) + .get('/.what/name.txt') + .expect(403) + }) + + await t.test('should 403 for dotfile in directory', async function (t) { + await request(createServer({ dotfiles: 'deny', root: fixtures })) + .get('/pets/.hidden.txt') + .expect(403) + }) + + await t.test('should 403 for dotfile in dotfile directory', async function (t) { + await request(createServer({ dotfiles: 'deny', root: fixtures })) + .get('/.mine/.hidden.txt') + .expect(403) + }) + + await t.test('should send files in root dotfile directory', async function (t) { + await request(createServer({ dotfiles: 'deny', root: path.join(fixtures, '.mine') })) + .get('/name.txt') + .expect(200, /tobi/) + }) + + await t.test('should 403 for dotfile without root', async function (t) { + const server = http.createServer(async function onRequest (req, res) { + const { statusCode, headers, stream } = await send(req, fixtures + '/.mine' + req.url, { dotfiles: 'deny' }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(server) + .get('/name.txt') + .expect(403) + }) + }) + + await t.test('when "ignore"', async function (t) { + t.plan(8) + + await t.test('should 404 for dotfile', async function (t) { + await request(createServer({ dotfiles: 'ignore', root: fixtures })) + .get('/.hidden.txt') + .expect(404) + }) + + await t.test('should 404 for dotfile directory', async function (t) { + await request(createServer({ dotfiles: 'ignore', root: fixtures })) + .get('/.mine') + .expect(404) + }) + + await t.test('should 404 for dotfile directory with trailing slash', async function (t) { + await request(createServer({ dotfiles: 'ignore', root: fixtures })) + .get('/.mine/') + .expect(404) + }) + + await t.test('should 404 for file within dotfile directory', async function (t) { + await request(createServer({ dotfiles: 'ignore', root: fixtures })) + .get('/.mine/name.txt') + .expect(404) + }) + + await t.test('should 404 for non-existent dotfile', async function (t) { + await request(createServer({ dotfiles: 'ignore', root: fixtures })) + .get('/.nothere') + .expect(404) + }) + + await t.test('should 404 for non-existent dotfile directory', async function (t) { + await request(createServer({ dotfiles: 'ignore', root: fixtures })) + .get('/.what/name.txt') + .expect(404) + }) + + await t.test('should send files in root dotfile directory', async function (t) { + await request(createServer({ dotfiles: 'ignore', root: path.join(fixtures, '.mine') })) + .get('/name.txt') + .expect(200, /tobi/) + }) + + await t.test('should 404 for dotfile without root', async function (t) { + const server = http.createServer(async function onRequest (req, res) { + const { statusCode, headers, stream } = await send(req, fixtures + '/.mine' + req.url, { dotfiles: 'ignore' }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(server) + .get('/name.txt') + .expect(404) + }) + }) + }) + + await t.test('immutable', async function (t) { + t.plan(2) + + await t.test('should default to false', async function (t) { + await request(createServer({ root: fixtures })) + .get('/name.txt') + .expect('Cache-Control', 'public, max-age=0') + }) + + await t.test('should set immutable directive in Cache-Control', async function (t) { + await request(createServer({ immutable: true, maxAge: '1h', root: fixtures })) + .get('/name.txt') + .expect('Cache-Control', 'public, max-age=3600, immutable') + }) + }) + + await t.test('maxAge', async function (t) { + t.plan(4) + + await t.test('should default to 0', async function (t) { + await request(createServer({ root: fixtures })) + .get('/name.txt') + .expect('Cache-Control', 'public, max-age=0') + }) + + await t.test('should floor to integer', async function (t) { + await request(createServer({ maxAge: 123956, root: fixtures })) + .get('/name.txt') + .expect('Cache-Control', 'public, max-age=123') + }) + + await t.test('should accept string', async function (t) { + await request(createServer({ maxAge: '30d', root: fixtures })) + .get('/name.txt') + .expect('Cache-Control', 'public, max-age=2592000') + }) + + await t.test('should max at 1 year', async function (t) { + await request(createServer({ maxAge: '2y', root: fixtures })) + .get('/name.txt') + .expect('Cache-Control', 'public, max-age=31536000') + }) + }) + + await t.test('index', async function (t) { + t.plan(10) + + await t.test('should reject numbers', async function (t) { + await request(createServer({ root: fixtures, index: 42 })) + .get('/pets/') + .expect(500, /TypeError: index option/) + }) + + await t.test('should reject true', async function (t) { + await request(createServer({ root: fixtures, index: true })) + .get('/pets/') + .expect(500, /TypeError: index option/) + }) + + await t.test('should default to index.html', async function (t) { + await request(createServer({ root: fixtures })) + .get('/pets/') + .expect(fs.readFileSync(path.join(fixtures, 'pets', 'index.html'), 'utf8')) + }) + + await t.test('should be configurable', async function (t) { + await request(createServer({ root: fixtures, index: 'tobi.html' })) + .get('/') + .expect(200, '

tobi

') + }) + + await t.test('should support disabling', async function (t) { + await request(createServer({ root: fixtures, index: false })) + .get('/pets/') + .expect(403) + }) + + await t.test('should support fallbacks', async function (t) { + await request(createServer({ root: fixtures, index: ['default.htm', 'index.html'] })) + .get('/pets/') + .expect(200, fs.readFileSync(path.join(fixtures, 'pets', 'index.html'), 'utf8')) + }) + + await t.test('should 404 if no index file found (file)', async function (t) { + await request(createServer({ root: fixtures, index: 'default.htm' })) + .get('/pets/') + .expect(404) + }) + + await t.test('should 404 if no index file found (dir)', async function (t) { + await request(createServer({ root: fixtures, index: 'pets' })) + .get('/') + .expect(404) + }) + + await t.test('should not follow directories', async function (t) { + await request(createServer({ root: fixtures, index: ['pets', 'name.txt'] })) + .get('/') + .expect(200, 'tobi') + }) + + await t.test('should work without root', async function (t) { + const server = http.createServer(async function (req, res) { + const p = path.join(fixtures, 'pets').replace(/\\/g, '/') + '/' + const { statusCode, headers, stream } = await send(req, p, { index: ['index.html'] }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(server) + .get('/') + .expect(200, /tobi/) + }) + }) + + await t.test('root', async function (t) { + t.plan(2) + + await t.test('when given', async function (t) { + t.plan(8) + + await t.test('should join root', async function (t) { + await request(createServer({ root: fixtures })) + .get('/pets/../name.txt') + .expect(200, 'tobi') + }) + + await t.test('should work with trailing slash', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures + '/' }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect(200, 'tobi') + }) + + await t.test('should work with empty path', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, '', { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect(301, /Redirecting to/) + }) + + // + // NOTE: This is not a real part of the API, but + // over time this has become something users + // are doing, so this will prevent unseen + // regressions around this use-case. + // + await t.test('should try as file with empty path', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, '', { root: path.join(fixtures, 'name.txt') }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/') + .expect(200, 'tobi') + }) + + await t.test('should restrict paths to within root', async function (t) { + await request(createServer({ root: fixtures })) + .get('/pets/../../send.js') + .expect(403) + }) + + await t.test('should allow .. in root', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures + '/../fixtures' }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/pets/../../send.js') + .expect(403) + }) + + await t.test('should not allow root transversal', async function (t) { + await request(createServer({ root: path.join(fixtures, 'name.d') })) + .get('/../name.dir/name.txt') + .expect(403) + }) + + await t.test('should not allow root path disclosure', async function (t) { + await request(createServer({ root: fixtures })) + .get('/pets/../../fixtures/name.txt') + .expect(403) + }) + }) + + await t.test('when missing', async function (t) { + t.plan(2) + + await t.test('should consider .. malicious', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, fixtures + req.url) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/../send.js') + .expect(403) + }) + + await t.test('should still serve files with dots in name', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, fixtures + req.url) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/do..ts.txt') + .expect(200, '...') + }) + }) + }) + + await t.test('highWaterMark', async function (t) { + t.plan(3) + + await t.test('should support highWaterMark', async function (t) { + t.plan(1) + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { highWaterMark: 512 * 1024, root: fixtures + '/' }) + res.writeHead(statusCode, headers) + t.assert.deepStrictEqual(stream.readableHighWaterMark, 524288) + stream.pipe(res) + }) + await request(app) + .get('/name.txt') + .expect(200, 'tobi') + }) + + await t.test('should use default value', async function (t) { + t.plan(1) + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures + '/' }) + res.writeHead(statusCode, headers) + t.assert.deepStrictEqual(stream.readableHighWaterMark, getDefaultHighWaterMark(false)) + stream.pipe(res) + }) + await request(app) + .get('/name.txt') + .expect(200, 'tobi') + }) + + await t.test('should ignore negative number', async function (t) { + t.plan(1) + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { highWaterMark: -54, root: fixtures + '/' }) + res.writeHead(statusCode, headers) + t.assert.deepStrictEqual(stream.readableHighWaterMark, getDefaultHighWaterMark(false)) + stream.pipe(res) + }) + await request(app) + .get('/name.txt') + .expect(200, 'tobi') + }) + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/send.2.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/send.2.test.js new file mode 100644 index 0000000000000000000000000000000000000000..957d6f5197d2bdbc7f62e612fcba40cece1b3356 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/test/send.2.test.js @@ -0,0 +1,977 @@ +'use strict' + +const { test } = require('node:test') +const http = require('node:http') +const path = require('node:path') +const request = require('supertest') +const send = require('../lib/send').send +const { shouldNotHaveBody, createServer, shouldNotHaveHeader } = require('./utils') + +const dateRegExp = /^\w{3}, \d+ \w+ \d+ \d+:\d+:\d+ \w+$/ +const fixtures = path.join(__dirname, 'fixtures') + +test('send(file)', async function (t) { + t.plan(22) + + await t.test('should stream the file contents', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect('Content-Length', '4') + .expect(200, 'tobi') + }) + + await t.test('should stream a zero-length file', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/empty.txt') + .expect('Content-Length', '0') + .expect(200, '') + }) + + await t.test('should decode the given path as a URI', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/some%20thing.txt') + .expect(200, 'hey') + }) + + await t.test('should serve files with dots in name', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/do..ts.txt') + .expect(200, '...') + }) + + await t.test('should treat a malformed URI as a bad request', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/some%99thing.txt') + .expect(400, /Bad Request/) + }) + + await t.test('should 400 on NULL bytes', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/some%00thing.txt') + .expect(400, /Bad Request/) + }) + + await t.test('should treat an ENAMETOOLONG as a 404', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + const path = Array(100).join('foobar') + await request(app) + .get('/' + path) + .expect(404) + }) + + await t.test('should support HEAD', async function (t) { + t.plan(1) + + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .head('/name.txt') + .expect(200) + .expect('Content-Length', '4') + .expect(shouldNotHaveBody(t)) + }) + + await t.test('should add an ETag header field', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect('etag', /^W\/"[^"]+"$/) + }) + + await t.test('should add a Date header field', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect('date', dateRegExp) + }) + + await t.test('should add a Last-Modified header field', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect('last-modified', dateRegExp) + }) + + await t.test('should add a Accept-Ranges header field', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect('Accept-Ranges', 'bytes') + }) + + await t.test('should 404 if the file does not exist', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/meow') + .expect(404, /Not Found/) + }) + + await t.test('should 404 if the filename is too long', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + const longFilename = new Array(512).fill('a').join('') + + await request(app) + .get('/' + longFilename) + .expect(404, /Not Found/) + }) + + await t.test('should 404 if the requested resource is not a directory', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/nums.txt/invalid') + .expect(404, /Not Found/) + }) + + await t.test('should not override content-type', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, { + ...headers, + 'Content-Type': 'application/x-custom' + }) + stream.pipe(res) + }) + await request(app) + .get('/name.txt') + .expect('Content-Type', 'application/x-custom') + }) + + await t.test('should set Content-Type via mime map', async function (t) { + const app = http.createServer(async function (req, res) { + const { statusCode, headers, stream } = await send(req, req.url, { root: fixtures }) + res.writeHead(statusCode, headers) + stream.pipe(res) + }) + + await request(app) + .get('/name.txt') + .expect('Content-Type', 'text/plain; charset=utf-8') + .expect(200) + + await request(app) + .get('/tobi.html') + .expect('Content-Type', 'text/html; charset=utf-8') + .expect(200) + }) + + await t.test('send directory', async function (t) { + t.plan(5) + + await t.test('should redirect directories to trailing slash', async function (t) { + await request(createServer({ root: fixtures })) + .get('/pets') + .expect('Location', '/pets/') + .expect(301) + }) + + await t.test('should respond with an HTML redirect', async function (t) { + await request(createServer({ root: fixtures })) + .get('/pets') + .expect('Location', '/pets/') + .expect('Content-Type', /html/) + .expect(301, />Redirecting to \/pets\/Redirecting to \/snow%20%E2%98%83\/Not Found +// Piotr Błażejewicz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Dirent } from 'node:fs' +import * as stream from 'node:stream' + +/** + * Create a new SendStream for the given path to send to a res. + * The req is the Node.js HTTP request and the path is a urlencoded path to send (urlencoded, not the actual file-system path). + */ +declare function send (req: stream.Readable, path: string, options?: send.SendOptions): Promise + +type Send = typeof send + +declare class Mime { + constructor (typeMap: TypeMap, ...mimes: TypeMap[]) + + getType (path: string): string | null + getExtension (mime: string): string | null + define (typeMap: TypeMap, force?: boolean): void +} + +interface TypeMap { + [key: string]: string[]; +} + +declare namespace send { + export const mime: Mime + export const isUtf8MimeType: (value: string) => boolean + + export interface SendOptions { + /** + * Enable or disable accepting ranged requests, defaults to true. + * Disabling this will not send Accept-Ranges and ignore the contents of the Range request header. + */ + acceptRanges?: boolean | undefined; + + /** + * Enable or disable setting Cache-Control response header, defaults to true. + * Disabling this will ignore the maxAge option. + */ + cacheControl?: boolean | undefined; + + /** + * Enable or disable setting Content-Type response header, defaults to true. + */ + contentType?: boolean | undefined; + + /** + * Set how "dotfiles" are treated when encountered. + * A dotfile is a file or directory that begins with a dot ("."). + * Note this check is done on the path itself without checking if the path actually exists on the disk. + * If root is specified, only the dotfiles above the root are checked (i.e. the root itself can be within a dotfile when when set to "deny"). + * 'allow' No special treatment for dotfiles. + * 'deny' Send a 403 for any request for a dotfile. + * 'ignore' Pretend like the dotfile does not exist and 404. + * The default value is similar to 'ignore', with the exception that this default will not ignore the files within a directory that begins with a dot, for backward-compatibility. + */ + dotfiles?: 'allow' | 'deny' | 'ignore' | undefined; + + /** + * Byte offset at which the stream ends, defaults to the length of the file minus 1. + * The end is inclusive in the stream, meaning end: 3 will include the 4th byte in the stream. + */ + end?: number | undefined; + + /** + * Enable or disable etag generation, defaults to true. + */ + etag?: boolean | undefined; + + /** + * If a given file doesn't exist, try appending one of the given extensions, in the given order. + * By default, this is disabled (set to false). + * An example value that will serve extension-less HTML files: ['html', 'htm']. + * This is skipped if the requested file already has an extension. + */ + extensions?: string[] | string | boolean | undefined; + + /** + * Enable or disable the immutable directive in the Cache-Control response header, defaults to false. + * If set to true, the maxAge option should also be specified to enable caching. + * The immutable directive will prevent supported clients from making conditional requests during the life of the maxAge option to check if the file has changed. + * @default false + */ + immutable?: boolean | undefined; + + /** + * By default send supports "index.html" files, to disable this set false or to supply a new index pass a string or an array in preferred order. + */ + index?: string[] | string | boolean | undefined; + + /** + * Enable or disable Last-Modified header, defaults to true. + * Uses the file system's last modified value. + */ + lastModified?: boolean | undefined; + + /** + * Provide a max-age in milliseconds for http caching, defaults to 0. + * This can also be a string accepted by the ms module. + */ + maxAge?: string | number | undefined; + + /** + * Limit max response content size when acceptRanges is true, defaults to the entire file size. + */ + maxContentRangeChunkSize?: number | undefined; + + /** + * Serve files relative to path. + */ + root?: string | undefined; + + /** + * Byte offset at which the stream starts, defaults to 0. + * The start is inclusive, meaning start: 2 will include the 3rd byte in the stream. + */ + start?: number | undefined; + + /** + * Maximum number of bytes that the internal buffer will hold. + * If omitted, Node.js falls back to its built-in default. + */ + highWaterMark?: number | undefined; + } + + export interface BaseSendResult { + statusCode: number + headers: Record + stream: stream.Readable + } + + export interface FileSendResult extends BaseSendResult { + type: 'file' + metadata: { + path: string + stat: Dirent + } + } + + export interface DirectorySendResult extends BaseSendResult { + type: 'directory' + metadata: { + path: string + requestPath: string + } + } + + export interface ErrorSendResult extends BaseSendResult { + type: 'error' + metadata: { + error: Error + } + } + + export type SendResult = FileSendResult | DirectorySendResult | ErrorSendResult + + export const send: Send + + export { send as default } +} + +export = send diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/types/index.test-d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/types/index.test-d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1711484d1e908d0bb78dae1e1a9994846b3bc875 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/send/types/index.test-d.ts @@ -0,0 +1,67 @@ +import { Dirent } from 'node:fs' +import { resolve } from 'node:path' +import { Readable } from 'node:stream' +import { expectType } from 'tsd' +import send, { DirectorySendResult, ErrorSendResult, FileSendResult, SendResult } from '..' + +send.mime.define({ + 'application/x-my-type': ['x-mt', 'x-mtt'] +}) + +expectType<(value: string) => boolean>(send.isUtf8MimeType) +expectType(send.isUtf8MimeType('application/json')) + +const req: any = {} + +{ + const result = await send(req, '/test.html', { + acceptRanges: true, + maxContentRangeChunkSize: 10, + immutable: true, + maxAge: 0, + root: resolve(__dirname, '/wwwroot') + }) + + expectType(result) + expectType(result.statusCode) + expectType>(result.headers) + expectType(result.stream) +} + +{ + const result = await send(req, '/test.html', { contentType: true, maxAge: 0, root: resolve(__dirname, '/wwwroot') }) + + expectType(result) + expectType(result.statusCode) + expectType>(result.headers) + expectType(result.stream) +} + +{ + const result = await send(req, '/test.html', { contentType: false, root: resolve(__dirname, '/wwwroot') }) + + expectType(result) + expectType(result.statusCode) + expectType>(result.headers) + expectType(result.stream) +} + +const result = await send(req, '/test.html') +switch (result.type) { + case 'file': { + expectType(result) + expectType(result.metadata.path) + expectType(result.metadata.stat) + break + } + case 'directory': { + expectType(result) + expectType(result.metadata.path) + expectType(result.metadata.requestPath) + break + } + case 'error': { + expectType(result) + expectType(result.metadata.error) + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/.github/dependabot.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..35d66ca7ac75f125b9c9c5b3dee0987fdfca4a45 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 + + - package-ecosystem: "npm" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 10 diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/.github/stale.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/.github/stale.yml new file mode 100644 index 0000000000000000000000000000000000000000..d51ce639022226bc44471aa18bb218b50876cd52 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/.github/stale.yml @@ -0,0 +1,21 @@ +# Number of days of inactivity before an issue becomes stale +daysUntilStale: 15 +# Number of days of inactivity before a stale issue is closed +daysUntilClose: 7 +# Issues with these labels will never be considered stale +exemptLabels: + - "discussion" + - "feature request" + - "bug" + - "help wanted" + - "plugin suggestion" + - "good first issue" +# Label to use when marking an issue as stale +staleLabel: stale +# Comment to post when marking an issue as stale. Set to `false` to disable +markComment: > + This issue has been automatically marked as stale because it has not had + recent activity. It will be closed if no further activity occurs. Thank you + for your contributions. +# Comment to post when closing a stale issue. Set to `false` to disable +closeComment: false diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/.github/workflows/ci.yml b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..fd45202abff682784e3a60d54fbfee567d304b26 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/.github/workflows/ci.yml @@ -0,0 +1,28 @@ +name: CI + +on: + push: + branches: + - main + - next + - 'v*' + paths-ignore: + - 'docs/**' + - '*.md' + pull_request: + paths-ignore: + - 'docs/**' + - '*.md' + +permissions: + contents: read + +jobs: + test: + permissions: + contents: write + pull-requests: write + uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5 + with: + license-check: true + lint: true diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/public/.hidden/sample.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/public/.hidden/sample.json new file mode 100644 index 0000000000000000000000000000000000000000..56c8e280338ea64e1ab62ef9bacdf02840a0dabb --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/public/.hidden/sample.json @@ -0,0 +1 @@ +{"hello": "world"} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/public/index.css b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/public/index.css new file mode 100644 index 0000000000000000000000000000000000000000..6d21fe430740be4a187414456706db6e526af5f7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/public/index.css @@ -0,0 +1,9 @@ +#my-button { + position: absolute; + top: 50%; + left: 50%; + width: 200px; + height: 28px; + margin-top: -14px; + margin-left: -100px; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/public/index.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/public/index.html new file mode 100644 index 0000000000000000000000000000000000000000..c8c65f9329aa116199efeb0dcc8e72fbad440b8f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/public/index.html @@ -0,0 +1,11 @@ + + + + + + + + + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/public/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/public/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a0d57a71cdbfc34d6ebc91b27148f126b45cb852 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/public/index.js @@ -0,0 +1,8 @@ +'use strict' + +window.onload = function () { + const b = document.getElementById('my-button') + b.onclick = function () { + window.alert('foo') + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/public2/test.css b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/public2/test.css new file mode 100644 index 0000000000000000000000000000000000000000..1bee9c0281bdfbc82d671407cb49326632cb427e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/public2/test.css @@ -0,0 +1,4 @@ +body { + background-color: black; + color: white; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/public2/test.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/public2/test.html new file mode 100644 index 0000000000000000000000000000000000000000..5480039682366042f6a09482a7af200e1de44036 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/public2/test.html @@ -0,0 +1,8 @@ + + + + + +

Test 2

+ + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/server-compress.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/server-compress.js new file mode 100644 index 0000000000000000000000000000000000000000..2dd5b2525a2b20b0478c09c3659fd44d4a734338 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/server-compress.js @@ -0,0 +1,15 @@ +'use strict' + +const path = require('node:path') +const fastify = require('fastify')({ logger: { level: 'trace' } }) + +fastify + // Compress everything. + .register(require('@fastify/compress'), { threshold: 0 }) + .register(require('../'), { + // An absolute path containing static files to serve. + root: path.join(__dirname, '/public') + }) + .listen({ port: 3000 }, err => { + if (err) throw err + }) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/server-dir-list.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/server-dir-list.js new file mode 100644 index 0000000000000000000000000000000000000000..39cca9823cb7a314b26686419ec8470687d3824e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/server-dir-list.js @@ -0,0 +1,38 @@ +'use strict' + +const path = require('node:path') + +const fastify = require('fastify')({ logger: { level: 'trace' } }) + +const renderer = (dirs, files) => { + return ` + + + + +` +} + +fastify + .register(require('..'), { + // An absolute path containing static files to serve. + root: path.join(__dirname, '/public'), + // Do not append a trailing slash to prefixes. + prefixAvoidTrailingSlash: true, + // Return a directory listing with a handlebar template. + list: { + // html or json response? html requires a render method. + format: 'html', + // A list of filenames that trigger a directory list response. + names: ['index', 'index.html', 'index.htm', '/'], + // You can provide your own render method as needed. + renderer + } + }) + .listen({ port: 3000 }, err => { + if (err) throw err + }) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/server-hidden-file.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/server-hidden-file.js new file mode 100644 index 0000000000000000000000000000000000000000..fe1f3afb3d6dc2adffbd150a51b2ba8f0151d752 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/server-hidden-file.js @@ -0,0 +1,15 @@ +'use strict' + +const path = require('node:path') +const fastify = require('fastify')({ logger: { level: 'trace' } }) + +fastify + .register(require('../'), { + // An absolute path containing static files to serve. + root: path.join(__dirname, '/public'), + wildcard: false, + serveDotFiles: true + }) + .listen({ port: 3000 }, err => { + if (err) throw err + }) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/server.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/server.js new file mode 100644 index 0000000000000000000000000000000000000000..f587183bce2fe82583a48c33e1a995a2599419cb --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/example/server.js @@ -0,0 +1,13 @@ +'use strict' + +const path = require('node:path') +const fastify = require('fastify')({ logger: { level: 'trace' } }) + +fastify + .register(require('../'), { + // An absolute path containing static files to serve. + root: path.join(__dirname, '/public') + }) + .listen({ port: 3000 }, err => { + if (err) throw err + }) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/lib/dirList.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/lib/dirList.js new file mode 100644 index 0000000000000000000000000000000000000000..916ace6c4e4485a09f8a8a6951b2bf1853b39ac3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/lib/dirList.js @@ -0,0 +1,211 @@ +'use strict' + +const os = require('node:os') +const path = require('node:path') +const fs = require('node:fs/promises') +const fastq = require('fastq') +const fastqConcurrency = Math.max(1, os.cpus().length - 1) + +const dirList = { + _getExtendedInfo: async function (dir, info) { + const depth = dir.split(path.sep).length + const files = await fs.readdir(dir) + + const worker = async (filename) => { + const filePath = path.join(dir, filename) + let stats + try { + stats = await fs.stat(filePath) + } catch { + return + } + + if (stats.isDirectory()) { + info.totalFolderCount++ + filePath.split(path.sep).length === depth + 1 && info.folderCount++ + await dirList._getExtendedInfo(filePath, info) + } else { + info.totalSize += stats.size + info.totalFileCount++ + filePath.split(path.sep).length === depth + 1 && info.fileCount++ + info.lastModified = Math.max(info.lastModified, stats.mtimeMs) + } + } + const queue = fastq.promise(worker, fastqConcurrency) + await Promise.all(files.map(filename => queue.push(filename))) + }, + + /** + * get extended info about a folder + * @param {string} folderPath full path fs dir + * @return {Promise} + */ + getExtendedInfo: async function (folderPath) { + const info = { + totalSize: 0, + fileCount: 0, + totalFileCount: 0, + folderCount: 0, + totalFolderCount: 0, + lastModified: 0 + } + + await dirList._getExtendedInfo(folderPath, info) + + return info + }, + + /** + * get files and dirs from dir, or error + * @param {string} dir full path fs dir + * @param {(boolean | ListOptionsJsonFormat | ListOptionsHtmlFormat)} options + * @param {string} dotfiles + * note: can't use glob because don't get error on non existing dir + */ + list: async function (dir, options, dotfiles) { + const entries = { dirs: [], files: [] } + let files = await fs.readdir(dir) + if (dotfiles === 'deny' || dotfiles === 'ignore') { + files = files.filter(file => file.charAt(0) !== '.') + } + if (files.length < 1) { + return entries + } + + const worker = async (filename) => { + let stats + try { + stats = await fs.stat(path.join(dir, filename)) + } catch { + return + } + const entry = { name: filename, stats } + if (stats.isDirectory()) { + if (options.extendedFolderInfo) { + entry.extendedInfo = await dirList.getExtendedInfo(path.join(dir, filename)) + } + entries.dirs.push(entry) + } else { + entries.files.push(entry) + } + } + const queue = fastq.promise(worker, fastqConcurrency) + await Promise.all(files.map(filename => queue.push(filename))) + + entries.dirs.sort((a, b) => a.name.localeCompare(b.name)) + entries.files.sort((a, b) => a.name.localeCompare(b.name)) + + return entries + }, + + /** + * send dir list content, or 404 on error + * @param {Fastify.Reply} reply + * @param {string} dir full path fs dir + * @param {(boolean | ListOptionsJsonFormat | ListOptionsHtmlFormat)} options + * @param {string} route request route + * @param {string} dotfiles + */ + send: async function ({ reply, dir, options, route, prefix, dotfiles }) { + if (reply.request.query.format === 'html' && typeof options.render !== 'function') { + throw new TypeError('The `list.render` option must be a function and is required with the URL parameter `format=html`') + } + + let entries + try { + entries = await dirList.list(dir, options, dotfiles) + } catch { + return reply.callNotFound() + } + + const format = reply.request.query.format || options.format + if (format !== 'html') { + if (options.jsonFormat !== 'extended') { + const nameEntries = { dirs: [], files: [] } + entries.dirs.forEach(entry => nameEntries.dirs.push(entry.name)) + entries.files.forEach(entry => nameEntries.files.push(entry.name)) + + await reply.send(nameEntries) + } else { + await reply.send(entries) + } + return + } + + const html = options.render( + entries.dirs.map(entry => dirList.htmlInfo(entry, route, prefix, options)), + entries.files.map(entry => dirList.htmlInfo(entry, route, prefix, options))) + await reply.type('text/html').send(html) + }, + + /** + * provide the html information about entry and route, to get name and full route + * @param entry file or dir name and stats + * @param {string} route request route + * @return {ListFile} + */ + htmlInfo: function (entry, route, prefix, options) { + if (options.names?.includes(path.basename(route))) { + route = path.normalize(path.join(route, '..')) + } + return { + href: encodeURI(path.join(prefix, route, entry.name).replace(/\\/gu, '/')), + name: entry.name, + stats: entry.stats, + extendedInfo: entry.extendedInfo + } + }, + + /** + * say if the route can be handled by dir list or not + * @param {string} route request route + * @param {(boolean | ListOptionsJsonFormat | ListOptionsHtmlFormat)} options + * @return {boolean} + */ + handle: function (route, options) { + return options.names?.includes(path.basename(route)) || + // match trailing slash + ((options.names?.includes('/') && route[route.length - 1] === '/') ?? false) + }, + + /** + * get path from route and fs root paths, considering trailing slash + * @param {string} root fs root path + * @param {string} route request route + */ + path: function (root, route) { + const _route = route[route.length - 1] === '/' + ? route + 'none' + : route + return path.dirname(path.join(root, _route)) + }, + + /** + * validate options + * @return {Error} + */ + validateOptions: function (options) { + if (!options.list) { + return + } + + if (Array.isArray(options.root)) { + return new TypeError('multi-root with list option is not supported') + } + + if (options.list.format && options.list.format !== 'json' && options.list.format !== 'html') { + return new TypeError('The `list.format` option must be json or html') + } + if (options.list.names && !Array.isArray(options.list.names)) { + return new TypeError('The `list.names` option must be an array') + } + if (options.list.jsonFormat != null && options.list.jsonFormat !== 'names' && options.list.jsonFormat !== 'extended') { + return new TypeError('The `list.jsonFormat` option must be name or extended') + } + if (options.list.format === 'html' && typeof options.list.render !== 'function') { + return new TypeError('The `list.render` option must be a function and is required with html format') + } + } +} + +module.exports = dirList diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type.test.js new file mode 100644 index 0000000000000000000000000000000000000000..6712eeadd8dd7f00d994d06c242cf376a7508eca --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type.test.js @@ -0,0 +1,144 @@ +'use strict' + +/* eslint n/no-deprecated-api: "off" */ + +const path = require('node:path') +const { test } = require('node:test') +const Fastify = require('fastify') + +const fastifyStatic = require('../') + +test('register /content-type', async t => { + t.plan(5) + + const pluginOptions = { + root: path.join(__dirname, '/content-type'), + prefix: '/content-type' + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/content-type/index.html', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/content-type/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/html; charset=utf-8') + }) + + await t.test('/content-type/index.css', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/content-type/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/css; charset=utf-8') + }) + + await t.test('/content-type/sample.jpg', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/content-type/sample.jpg') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'image/jpeg') + }) + + await t.test('/content-type/test.txt', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/content-type/test.txt') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/plain; charset=utf-8') + }) + + await t.test('/content-type/binary', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/content-type/binary') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'application/octet-stream') + }) +}) + +test('register /content-type preCompressed', async t => { + t.plan(5) + + const pluginOptions = { + root: path.join(__dirname, '/content-type'), + prefix: '/content-type', + preCompressed: true + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/content-type/index.html', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/content-type/index.html', { + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/html; charset=utf-8') + }) + + await t.test('/content-type/index.css', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/content-type/index.css', { + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/css; charset=utf-8') + }) + + await t.test('/content-type/sample.jpg', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/content-type/sample.jpg', { + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'image/jpeg') + }) + + await t.test('/content-type/test.txt', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/content-type/test.txt', { + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/plain; charset=utf-8') + }) + + await t.test('/content-type/binary', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/content-type/binary', { + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'application/octet-stream') + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type/binary b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type/binary new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type/binary.br b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type/binary.br new file mode 100644 index 0000000000000000000000000000000000000000..c183df6a308637ea8e1bbb578785c74bec7f8599 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type/binary.br @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type/index.css b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type/index.css new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type/index.css.br b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type/index.css.br new file mode 100644 index 0000000000000000000000000000000000000000..c183df6a308637ea8e1bbb578785c74bec7f8599 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type/index.css.br @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type/index.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type/index.html new file mode 100644 index 0000000000000000000000000000000000000000..1b0b72f02fe433adb972fde358d316866365eef5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type/index.html @@ -0,0 +1,5 @@ + + + the body + + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type/index.html.br b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type/index.html.br new file mode 100644 index 0000000000000000000000000000000000000000..bebb53895ec7fcf262a7d4e045bb24a794b0cce1 Binary files /dev/null and b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type/index.html.br differ diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type/test.txt b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type/test.txt new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type/test.txt.br b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type/test.txt.br new file mode 100644 index 0000000000000000000000000000000000000000..c183df6a308637ea8e1bbb578785c74bec7f8599 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/content-type/test.txt.br @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/dir-list.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/dir-list.test.js new file mode 100644 index 0000000000000000000000000000000000000000..a6af123f9827f57d4759f9083d8c455c3fedd788 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/dir-list.test.js @@ -0,0 +1,738 @@ +'use strict' + +/* eslint n/no-deprecated-api: "off" */ + +const fs = require('node:fs') +const path = require('node:path') +const { test } = require('node:test') +const Fastify = require('fastify') + +const fastifyStatic = require('..') +const dirList = require('../lib/dirList') + +const helper = { + arrange: async function (t, options, f) { + const fastify = Fastify() + fastify.register(fastifyStatic, options) + t.after(() => fastify.close()) + await fastify.listen({ port: 0 }) + fastify.server.unref() + await f('http://localhost:' + fastify.server.address().port) + } +} + +try { + fs.mkdirSync(path.join(__dirname, 'static/shallow/empty')) +} catch {} + +test('throws when `root` is an array', t => { + t.plan(2) + + const err = dirList.validateOptions({ root: ['hello', 'world'], list: true }) + t.assert.ok(err instanceof TypeError) + t.assert.deepStrictEqual(err.message, 'multi-root with list option is not supported') +}) + +test('throws when `list.format` option is invalid', t => { + t.plan(2) + + const err = dirList.validateOptions({ list: { format: 'hello' } }) + t.assert.ok(err instanceof TypeError) + t.assert.deepStrictEqual(err.message, 'The `list.format` option must be json or html') +}) + +test('throws when `list.names option` is not an array', t => { + t.plan(2) + + const err = dirList.validateOptions({ list: { names: 'hello' } }) + t.assert.ok(err instanceof TypeError) + t.assert.deepStrictEqual(err.message, 'The `list.names` option must be an array') +}) + +test('throws when `list.jsonFormat` option is invalid', t => { + t.plan(2) + + const err = dirList.validateOptions({ list: { jsonFormat: 'hello' } }) + t.assert.ok(err instanceof TypeError) + t.assert.deepStrictEqual(err.message, 'The `list.jsonFormat` option must be name or extended') +}) + +test('throws when `list.format` is html and `list render` is not a function', t => { + t.plan(2) + + const err = dirList.validateOptions({ list: { format: 'html', render: 'hello' } }) + t.assert.ok(err instanceof TypeError) + t.assert.deepStrictEqual(err.message, 'The `list.render` option must be a function and is required with html format') +}) + +test('dir list wrong options', async t => { + t.plan(3) + + const cases = [ + { + options: { + root: path.join(__dirname, '/static'), + prefix: '/public', + list: { + format: 'no-json,no-html' + } + }, + error: new TypeError('The `list.format` option must be json or html') + }, + { + options: { + root: path.join(__dirname, '/static'), + list: { + format: 'html' + // no render function + } + }, + error: new TypeError('The `list.render` option must be a function and is required with html format') + }, + { + options: { + root: path.join(__dirname, '/static'), + list: { + names: 'not-an-array' + } + }, + error: new TypeError('The `list.names` option must be an array') + } + ] + + for (const case_ of cases) { + const fastify = Fastify() + fastify.register(fastifyStatic, case_.options) + await t.assert.rejects(fastify.listen({ port: 0 }), new TypeError(case_.error.message)) + fastify.server.unref() + } +}) + +test('dir list default options', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + list: true + } + const route = '/public/shallow' + const content = { dirs: ['empty'], files: ['sample.jpg'] } + + await helper.arrange(t, options, async (url) => { + await t.test(route, async t => { + t.plan(3) + + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), content) + }) + }) +}) + +test('dir list, custom options', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + index: false, + list: true + } + + const route = '/public/' + const content = { dirs: ['deep', 'shallow'], files: ['.example', '100%.txt', 'a .md', 'foo.html', 'foobar.html', 'index.css', 'index.html'] } + + await helper.arrange(t, options, async (url) => { + await t.test(route, async t => { + t.plan(3) + + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), content) + }) + }) +}) + +test('dir list, custom options with empty array index', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + index: [], + list: true + } + + const route = '/public/' + const content = { dirs: ['deep', 'shallow'], files: ['.example', '100%.txt', 'a .md', 'foo.html', 'foobar.html', 'index.css', 'index.html'] } + + await helper.arrange(t, options, async (url) => { + await t.test(route, async t => { + t.plan(3) + + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), content) + }) + }) +}) + +test('dir list html format', async t => { + t.plan(2) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + index: false, + list: { + format: 'html', + names: ['index', 'index.htm'], + render: (dirs, files) => { + return ` + + + + +` + } + } + } + const routes = ['/public/index.htm', '/public/index'] + + // check all routes by names + + await helper.arrange(t, options, async (url) => { + for (const route of routes) { + await t.test(route, async t => { + t.plan(3) + + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), ` + + + + +`) + }) + } + }) +}) + +test('dir list href nested structure', async t => { + t.plan(5) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + index: false, + list: { + format: 'html', + names: ['index', 'index.htm'], + render (dirs) { + return dirs[0].href + } + } + } + + const routes = [ + { path: '/public/', response: '/public/deep' }, + { path: '/public/index', response: '/public/deep' }, + { path: '/public/deep/', response: '/public/deep/path' }, + { path: '/public/deep/index.htm', response: '/public/deep/path' }, + { path: '/public/deep/path/', response: '/public/deep/path/for' } + ] + await helper.arrange(t, options, async (url) => { + for (const route of routes) { + await t.test(route.path, async t => { + t.plan(5) + + const response = await fetch(url + route.path) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + const responseContent = await response.text() + t.assert.deepStrictEqual(responseContent, route.response) + + const response2 = await fetch(url + responseContent) + t.assert.ok(response2.ok) + t.assert.deepStrictEqual(response2.status, 200) + }) + } + }) +}) + +test('dir list html format - stats', async t => { + t.plan(6) + + const options1 = { + root: path.join(__dirname, '/static'), + prefix: '/public', + index: false, + list: { + format: 'html', + render (dirs, files) { + t.assert.ok(dirs.length > 0) + t.assert.ok(files.length > 0) + + t.assert.ok(dirs.every(every)) + t.assert.ok(files.every(every)) + + function every (value) { + return value.stats?.atime && + !value.extendedInfo + } + } + } + } + + const route = '/public/' + + await helper.arrange(t, options1, async (url) => { + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + }) +}) + +test('dir list html format - extended info', async t => { + t.plan(2) + + const route = '/public/' + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + index: false, + list: { + format: 'html', + extendedFolderInfo: true, + render (dirs) { + test('dirs', t => { + t.plan(dirs.length * 7) + + for (const value of dirs) { + t.assert.ok(value.extendedInfo) + + t.assert.deepStrictEqual(typeof value.extendedInfo.fileCount, 'number') + t.assert.deepStrictEqual(typeof value.extendedInfo.totalFileCount, 'number') + t.assert.deepStrictEqual(typeof value.extendedInfo.folderCount, 'number') + t.assert.deepStrictEqual(typeof value.extendedInfo.totalFolderCount, 'number') + t.assert.deepStrictEqual(typeof value.extendedInfo.totalSize, 'number') + t.assert.deepStrictEqual(typeof value.extendedInfo.lastModified, 'number') + } + }) + } + } + } + + await helper.arrange(t, options, async (url) => { + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + }) +}) + +test('dir list json format', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + prefixAvoidTrailingSlash: true, + list: { + format: 'json', + names: ['index', 'index.json', '/'] + } + } + const routes = ['/public/shallow/'] + const content = { dirs: ['empty'], files: ['sample.jpg'] } + + await helper.arrange(t, options, async (url) => { + for (const route of routes) { + await t.test(route, async t => { + t.plan(3) + + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), content) + }) + } + }) +}) + +test('dir list json format - extended info', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + prefixAvoidTrailingSlash: true, + list: { + format: 'json', + names: ['index', 'index.json', '/'], + extendedFolderInfo: true, + jsonFormat: 'extended' + + } + } + const routes = ['/public/shallow/'] + + await helper.arrange(t, options, async (url) => { + for (const route of routes) { + await t.test(route, async t => { + t.plan(5) + + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + const responseContent = await response.json() + t.assert.deepStrictEqual(responseContent.dirs[0].name, 'empty') + t.assert.deepStrictEqual(typeof responseContent.dirs[0].stats.atimeMs, 'number') + t.assert.deepStrictEqual(typeof responseContent.dirs[0].extendedInfo.totalSize, 'number') + }) + } + }) +}) + +test('json format with url parameter format', async t => { + t.plan(12) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + index: false, + list: { + format: 'json', + render () { + return 'html' + } + } + } + const route = '/public/' + const jsonContent = { dirs: ['deep', 'shallow'], files: ['.example', '100%.txt', 'a .md', 'foo.html', 'foobar.html', 'index.css', 'index.html'] } + + await helper.arrange(t, options, async (url) => { + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), jsonContent) + t.assert.ok(response.headers.get('content-type').includes('application/json')) + + const response2 = await fetch(url + route + '?format=html') + t.assert.ok(response2.ok) + t.assert.deepStrictEqual(response2.status, 200) + t.assert.deepStrictEqual(await response2.text(), 'html') + t.assert.ok(response2.headers.get('content-type').includes('text/html')) + + const response3 = await fetch(url + route + '?format=json') + t.assert.ok(response3.ok) + t.assert.deepStrictEqual(response3.status, 200) + t.assert.deepStrictEqual(await response3.json(), jsonContent) + t.assert.ok(response3.headers.get('content-type').includes('application/json')) + }) +}) + +test('json format with url parameter format and without render option', async t => { + t.plan(11) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + index: false, + list: { + format: 'json' + } + } + const route = '/public/' + const jsonContent = { dirs: ['deep', 'shallow'], files: ['.example', '100%.txt', 'a .md', 'foo.html', 'foobar.html', 'index.css', 'index.html'] } + + await helper.arrange(t, options, async (url) => { + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), jsonContent) + t.assert.ok(response.headers.get('content-type').includes('application/json')) + + const response2 = await fetch(url + route + '?format=html') + t.assert.ok(!response2.ok) + t.assert.deepStrictEqual(response2.status, 500) + t.assert.deepStrictEqual((await response2.json()).message, 'The `list.render` option must be a function and is required with the URL parameter `format=html`') + + const response3 = await fetch(url + route + '?format=json') + t.assert.ok(response3.ok) + t.assert.deepStrictEqual(response3.status, 200) + t.assert.deepStrictEqual(await response3.json(), jsonContent) + t.assert.ok(response3.headers.get('content-type').includes('application/json')) + }) +}) + +test('html format with url parameter format', async t => { + t.plan(12) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + index: false, + list: { + format: 'html', + render () { + return 'html' + } + } + } + const route = '/public/' + const jsonContent = { dirs: ['deep', 'shallow'], files: ['.example', '100%.txt', 'a .md', 'foo.html', 'foobar.html', 'index.css', 'index.html'] } + + await helper.arrange(t, options, async (url) => { + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), 'html') + t.assert.ok(response.headers.get('content-type').includes('text/html')) + + const response2 = await fetch(url + route + '?format=html') + t.assert.ok(response2.ok) + t.assert.deepStrictEqual(response2.status, 200) + t.assert.deepStrictEqual(await response2.text(), 'html') + t.assert.ok(response2.headers.get('content-type').includes('text/html')) + + const response3 = await fetch(url + route + '?format=json') + t.assert.ok(response3.ok) + t.assert.deepStrictEqual(response3.status, 200) + t.assert.deepStrictEqual(await response3.json(), jsonContent) + t.assert.ok(response3.headers.get('content-type').includes('application/json')) + }) +}) + +test('dir list on empty dir', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + list: true + } + const route = '/public/shallow/empty' + const content = { dirs: [], files: [] } + + await helper.arrange(t, options, async (url) => { + await t.test(route, async t => { + t.plan(3) + + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), content) + }) + }) +}) + +test('dir list serve index.html on index option', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + index: false, + list: { + format: 'html', + names: ['index', 'index.html'], + render: () => 'dir list index' + } + } + + await helper.arrange(t, options, async (url) => { + await t.test('serve index.html from fs', async t => { + t.plan(6) + + const response = await fetch(url + '/public/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '\n \n the body\n \n\n') + + const response2 = await fetch(url + '/public/index') + t.assert.ok(response2.ok) + t.assert.deepStrictEqual(response2.status, 200) + t.assert.deepStrictEqual(await response2.text(), 'dir list index') + }) + }) +}) + +test('serve a non existent dir and get error', async t => { + t.plan(1) + + const options = { + root: '/none', + prefix: '/public', + list: true + } + const route = '/public/' + + await helper.arrange(t, options, async (url) => { + await t.test(route, async t => { + t.plan(2) + + const response = await fetch(url + route) + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + }) + }) +}) + +test('serve a non existent dir and get error', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + list: { + names: ['index'] + } + } + const route = '/public/none/index' + + await helper.arrange(t, options, async (url) => { + await t.test(route, async t => { + t.plan(2) + + const response = await fetch(url + route) + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + }) + }) +}) + +test('dir list with dotfiles allow option', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static-dotfiles'), + prefix: '/public', + dotfiles: 'allow', + index: false, + list: true + } + const route = '/public/' + const content = { dirs: ['dir'], files: ['.aaa', 'test.txt'] } + + await helper.arrange(t, options, async (url) => { + await t.test(route, async t => { + t.plan(3) + + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), content) + }) + }) +}) + +test('dir list with dotfiles deny option', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static-dotfiles'), + prefix: '/public', + dotfiles: 'deny', + index: false, + list: true + } + const route = '/public/' + const content = { dirs: ['dir'], files: ['test.txt'] } + + await helper.arrange(t, options, async (url) => { + await t.test(route, async t => { + t.plan(3) + + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), content) + }) + }) +}) + +test('dir list with dotfiles ignore option', async t => { + t.plan(1) + + const options = { + root: path.join(__dirname, '/static-dotfiles'), + prefix: '/public', + dotfiles: 'ignore', + index: false, + list: true + } + const route = '/public/' + const content = { dirs: ['dir'], files: ['test.txt'] } + + await helper.arrange(t, options, async (url) => { + await t.test(route, async t => { + t.plan(3) + + const response = await fetch(url + route) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), content) + }) + }) +}) + +test('dir list error', async t => { + t.plan(6) + + const options = { + root: path.join(__dirname, '/static'), + prefix: '/public', + prefixAvoidTrailingSlash: true, + index: false, + list: { + format: 'html', + names: ['index', 'index.htm'], + render: () => '' + } + } + + const errorMessage = 'mocking send' + dirList.send = async () => { throw new Error(errorMessage) } + + t.beforeEach((ctx) => { + ctx.initialDirList = ctx['../lib/dirList.js'] + ctx['../lib/dirList.js'] = dirList + }) + + t.afterEach((ctx) => { + ctx['../lib/dirList.js'] = ctx.initialDirList + }) + + const routes = ['/public/', '/public/index.htm'] + + await helper.arrange(t, options, async (url) => { + for (const route of routes) { + const response = await fetch(url + route) + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 500) + t.assert.deepStrictEqual((await response.json()).message, errorMessage) + } + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-dotfiles/.aaa b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-dotfiles/.aaa new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-dotfiles/dir/index.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-dotfiles/dir/index.html new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-dotfiles/test.txt b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-dotfiles/test.txt new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-encode/[...]/a .md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-encode/[...]/a .md new file mode 100644 index 0000000000000000000000000000000000000000..96236f8158b12701d5e75c14fb876c4a0f31b963 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-encode/[...]/a .md @@ -0,0 +1 @@ +example \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-filtered/bar.private b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-filtered/bar.private new file mode 100644 index 0000000000000000000000000000000000000000..5716ca5987cbf97d6bb54920bea6adde242d87e6 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-filtered/bar.private @@ -0,0 +1 @@ +bar diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-filtered/deep/path/to/baz.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-filtered/deep/path/to/baz.html new file mode 100644 index 0000000000000000000000000000000000000000..bd2a31ffd3da0a6bb4165f563169b76b273a2e7b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-filtered/deep/path/to/baz.html @@ -0,0 +1,3 @@ + + baz + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-filtered/deep/path/to/baz.private b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-filtered/deep/path/to/baz.private new file mode 100644 index 0000000000000000000000000000000000000000..76018072e09c5d31c8c6e3113b8aa0fe625195ca --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-filtered/deep/path/to/baz.private @@ -0,0 +1 @@ +baz diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-filtered/index.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-filtered/index.html new file mode 100644 index 0000000000000000000000000000000000000000..e3b8da08481c7025e626016a2d0a00e9f2623e25 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-filtered/index.html @@ -0,0 +1,3 @@ + + index2 + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-hidden/.hidden/sample.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-hidden/.hidden/sample.json new file mode 100644 index 0000000000000000000000000000000000000000..56c8e280338ea64e1ab62ef9bacdf02840a0dabb --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-hidden/.hidden/sample.json @@ -0,0 +1 @@ +{"hello": "world"} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/all-three.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/all-three.html new file mode 100644 index 0000000000000000000000000000000000000000..1b0b72f02fe433adb972fde358d316866365eef5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/all-three.html @@ -0,0 +1,5 @@ + + + the body + + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/all-three.html.br b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/all-three.html.br new file mode 100644 index 0000000000000000000000000000000000000000..4d2fc468bee50c97ed0cb1421d82139afbc44d10 Binary files /dev/null and b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/all-three.html.br differ diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/baz.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/baz.json new file mode 100644 index 0000000000000000000000000000000000000000..871e874c25101ffc595d9bee4dd908261d285f90 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/baz.json @@ -0,0 +1,3 @@ +{ + "baz": "baz" +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/dir-gz/index.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/dir-gz/index.html new file mode 100644 index 0000000000000000000000000000000000000000..8551365650119cd0cd3c30867546290d39f9449a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/dir-gz/index.html @@ -0,0 +1,5 @@ + + + dir-gz index + + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/dir/index.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/dir/index.html new file mode 100644 index 0000000000000000000000000000000000000000..671d084dee34d4ded75deacf01abe21ece3b725b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/dir/index.html @@ -0,0 +1,5 @@ + + + dir index + + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/dir/index.html.br b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/dir/index.html.br new file mode 100644 index 0000000000000000000000000000000000000000..8ae99efcb35996bf1c7840895247d5b49720d19c Binary files /dev/null and b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/dir/index.html.br differ diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/empty/.gitkeep b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/empty/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/gzip-only.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/gzip-only.html new file mode 100644 index 0000000000000000000000000000000000000000..424329433de5692770306bca1817b08928b0e153 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/gzip-only.html @@ -0,0 +1,3 @@ + + foo + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/index.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/index.html new file mode 100644 index 0000000000000000000000000000000000000000..4f5bf40dbb95e7eb582009493b1c21b871e68cbc --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/index.html @@ -0,0 +1,5 @@ + + + index + + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/index.html.br b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/index.html.br new file mode 100644 index 0000000000000000000000000000000000000000..a3cdfb5848c451e39b86c615adff7ecd7b08dab3 Binary files /dev/null and b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/index.html.br differ diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/sample.jpg.br b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/sample.jpg.br new file mode 100644 index 0000000000000000000000000000000000000000..4d25b0c293ed811be2595d045ffa5a0124c72d22 Binary files /dev/null and b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/sample.jpg.br differ diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/uncompressed.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/uncompressed.html new file mode 100644 index 0000000000000000000000000000000000000000..d53979c2599ff126adc38527409dc96784dc9c5f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-pre-compressed/uncompressed.html @@ -0,0 +1,3 @@ + + foobar + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-symbolic-link/origin/subdir/subdir/index.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-symbolic-link/origin/subdir/subdir/index.html new file mode 100644 index 0000000000000000000000000000000000000000..fbd827cb75e54eeccec930bb1cceae858b1dfea5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static-symbolic-link/origin/subdir/subdir/index.html @@ -0,0 +1,3 @@ + + index + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static.test.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static.test.js new file mode 100644 index 0000000000000000000000000000000000000000..1502016c09fb60df1240627ae8fd9242722960be --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static.test.js @@ -0,0 +1,3745 @@ +'use strict' + +/* eslint n/no-deprecated-api: "off" */ + +const path = require('node:path') +const fs = require('node:fs') +const url = require('node:url') +const http = require('node:http') +const { test } = require('node:test') +const Fastify = require('fastify') +const compress = require('@fastify/compress') +const concat = require('concat-stream') +const pino = require('pino') +const proxyquire = require('proxyquire') + +const fastifyStatic = require('../') + +const indexContent = fs + .readFileSync('./test/static/index.html') + .toString('utf8') +const index2Content = fs + .readFileSync('./test/static2/index.html') + .toString('utf8') +const foobarContent = fs + .readFileSync('./test/static/foobar.html') + .toString('utf8') +const deepContent = fs + .readFileSync('./test/static/deep/path/for/test/purpose/foo.html') + .toString('utf8') +const innerIndex = fs + .readFileSync('./test/static/deep/path/for/test/index.html') + .toString('utf8') +const allThreeBr = fs.readFileSync( + './test/static-pre-compressed/all-three.html.br' +) +const allThreeGzip = fs.readFileSync( + './test/static-pre-compressed/all-three.html.gz' +) +const gzipOnly = fs.readFileSync( + './test/static-pre-compressed/gzip-only.html.gz' +) +const indexBr = fs.readFileSync( + './test/static-pre-compressed/index.html.br' +) +const dirIndexBr = fs.readFileSync( + './test/static-pre-compressed/dir/index.html.br' +) +const dirIndexGz = fs.readFileSync( + './test/static-pre-compressed/dir-gz/index.html.gz' +) +const uncompressedStatic = fs + .readFileSync('./test/static-pre-compressed/uncompressed.html') + .toString('utf8') +const fooContent = fs.readFileSync('./test/static/foo.html').toString('utf8') +const barContent = fs.readFileSync('./test/static2/bar.html').toString('utf8') +const jsonHiddenContent = fs.readFileSync('./test/static-hidden/.hidden/sample.json').toString('utf8') + +const GENERIC_RESPONSE_CHECK_COUNT = 5 +function genericResponseChecks (t, response) { + t.assert.ok(/text\/(html|css)/.test(response.headers.get?.('content-type') ?? response.headers['content-type'])) + t.assert.ok(response.headers.get?.('etag') ?? response.headers.etag) + t.assert.ok(response.headers.get?.('last-modified') ?? response.headers['last-modified']) + t.assert.ok(response.headers.get?.('date') ?? response.headers.date) + t.assert.ok(response.headers.get?.('cache-control') ?? response.headers['cache-control']) +} + +const GENERIC_ERROR_RESPONSE_CHECK_COUNT = 2 +function genericErrorResponseChecks (t, response) { + t.assert.deepStrictEqual(response.headers.get?.('content-type') ?? response.headers['content-type'], 'application/json; charset=utf-8') + t.assert.ok(response.headers.get?.('date') ?? response.headers.date) +} + +if (typeof Promise.withResolvers === 'undefined') { + Promise.withResolvers = function () { + let promiseResolve, promiseReject + const promise = new Promise((resolve, reject) => { + promiseResolve = resolve + promiseReject = reject + }) + return { promise, resolve: promiseResolve, reject: promiseReject } + } +} + +test('register /static prefixAvoidTrailingSlash', async t => { + t.plan(11) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static', + prefixAvoidTrailingSlash: true + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + + genericResponseChecks(t, response) + }) + + await t.test('/static/index.css', async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.css') + + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + genericResponseChecks(t, response) + }) + + await t.test('/static/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test/purpose/foo.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/purpose/foo.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/static/this/path/for/test', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/this/path/for/test') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/static/this/path/doesnt/exist.html', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/this/path/doesnt/exist.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/static/../index.js', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/../index.js') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('file not exposed outside of the plugin', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foobar.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + }) + + await t.test('file retrieve with HEAD method', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html', { + method: 'HEAD' + }) + + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) +}) + +test('register /static', async (t) => { + t.plan(10) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static' + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/index.css', async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + genericResponseChecks(t, response) + }) + + await t.test('/static/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + }) + + await t.test('/static/deep/path/for/test/purpose/foo.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/purpose/foo.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/static/this/path/for/test', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/this/path/for/test') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/static/this/path/doesnt/exist.html', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/this/path/doesnt/exist.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/static/../index.js', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/../index.js', { + redirect: 'error' + }) + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('file not exposed outside of the plugin', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foobar.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + }) +}) + +test('register /static/', async t => { + t.plan(11) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static/' + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/index.html', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html', { + method: 'HEAD' + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) + + await t.test('/static/index.css', async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + genericResponseChecks(t, response) + }) + + await t.test('/static/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + }) + + await t.test('/static/deep/path/for/test/purpose/foo.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/purpose/foo.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/static/this/path/for/test', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/this/path/for/test') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/static/this/path/doesnt/exist.html', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/this/path/doesnt/exist.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/static/../index.js', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/../index.js') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('304', async t => { + t.plan(5 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + + const response2 = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html', { + headers: { + 'if-none-match': response.headers.get('etag') + }, + cache: 'no-cache' + }) + t.assert.ok(!response2.ok) + t.assert.deepStrictEqual(response2.status, 304) + }) +}) + +test('register /static and /static2', async (t) => { + t.plan(4) + + const pluginOptions = { + root: [path.join(__dirname, '/static'), path.join(__dirname, '/static2')], + prefix: '/static' + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/foo', (_req, rep) => { + rep.sendFile('foo.html') + }) + + fastify.get('/bar', (_req, rep) => { + rep.sendFile('bar.html') + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(4 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + const responseText = await response.text() + t.assert.deepStrictEqual(responseText, indexContent) + t.assert.notDeepStrictEqual(responseText, index2Content) + genericResponseChecks(t, response) + }) + + await t.test('/static/bar.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/bar.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), barContent) + genericResponseChecks(t, response) + }) + + await t.test('sendFile foo.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), fooContent) + genericResponseChecks(t, response) + }) + + await t.test('sendFile bar.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/bar') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), barContent) + genericResponseChecks(t, response) + }) +}) + +test('register /static with constraints', async (t) => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static', + constraints: { + version: '1.2.0' + } + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + await t.test('example.com/static/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html', { + headers: { + 'accept-version': '1.x' + } + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('not-example.com/static/index.html', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html', { + headers: { + 'accept-version': '2.x' + } + }) + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) +}) + +test('payload.path is set', async (t) => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static/' + } + const fastify = Fastify() + let gotFilename + fastify.register(fastifyStatic, pluginOptions) + fastify.addHook('onSend', function (_req, _reply, payload, next) { + gotFilename = payload.path + next() + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(5 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + t.assert.deepStrictEqual(typeof gotFilename, 'string') + t.assert.deepStrictEqual(gotFilename, path.join(pluginOptions.root, 'index.html')) + genericResponseChecks(t, response) + }) + + await t.test('/static/this/path/doesnt/exist.html', async (t) => { + t.plan(3 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/this/path/doesnt/exist.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + t.assert.deepStrictEqual(typeof gotFilename, 'undefined') + genericErrorResponseChecks(t, response) + }) +}) + +test('error responses can be customized with fastify.setErrorHandler()', async t => { + t.plan(1) + + const pluginOptions = { + root: path.join(__dirname, '/static') + } + const fastify = Fastify() + + fastify.setErrorHandler(function errorHandler (err, _request, reply) { + reply.code(403).type('text/plain').send(`${err.statusCode} Custom error message`) + }) + + fastify.get('/index.js', (_, reply) => { + return reply.type('text/html').sendFile('foo.js') + }) + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/../index.js', async t => { + t.plan(4) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.js') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 403) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/plain') + t.assert.deepStrictEqual(await response.text(), '500 Custom error message') + }) +}) + +test('not found responses can be customized with fastify.setNotFoundHandler()', async t => { + t.plan(1) + + const pluginOptions = { + root: path.join(__dirname, '/static') + } + const fastify = Fastify() + + fastify.setNotFoundHandler(function notFoundHandler (request, reply) { + reply.code(404).type('text/plain').send(request.raw.url + ' Not Found') + }) + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/path/does/not/exist.html', async t => { + t.plan(4) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/path/does/not/exist.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/plain') + t.assert.deepStrictEqual(await response.text(), '/path/does/not/exist.html Not Found') + }) +}) + +test('fastify.setNotFoundHandler() is called for dotfiles when send is configured to ignore dotfiles', async t => { + t.plan(1) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + send: { + dotfiles: 'ignore' + } + } + const fastify = Fastify() + + fastify.setNotFoundHandler(function notFoundHandler (request, reply) { + reply.code(404).type('text/plain').send(request.raw.url + ' Not Found') + }) + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + // Requesting files with a leading dot doesn't follow the same code path as + // other 404 errors + await t.test('/path/does/not/.exist.html', async t => { + t.plan(4) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/path/does/not/.exist.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/plain') + t.assert.deepStrictEqual(await response.text(), '/path/does/not/.exist.html Not Found') + }) +}) + +test('serving disabled', async (t) => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static/', + serve: false + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + fastify.get('/foo/bar', (_request, reply) => { + reply.sendFile('index.html') + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static/index.html not found', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + }) + + await t.test('/static/index.html via sendFile found', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo/bar') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) +}) + +test('sendFile', async (t) => { + t.plan(4) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static' + } + const fastify = Fastify() + const maxAge = Math.round(Math.random() * 10) * 10000 + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + fastify.get('/foo/bar', function (_req, reply) { + reply.sendFile('/index.html') + }) + + fastify.get('/root/path/override/test', (_request, reply) => { + reply.sendFile( + '/foo.html', + path.join(__dirname, 'static', 'deep', 'path', 'for', 'test', 'purpose') + ) + }) + + fastify.get('/foo/bar/options/override/test', function (_req, reply) { + reply.sendFile('/index.html', { maxAge }) + }) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + await t.test('reply.sendFile()', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo/bar') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('reply.sendFile() with rootPath', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/root/path/override/test') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('reply.sendFile() again without root path', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo/bar') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('reply.sendFile() with options', async (t) => { + t.plan(4 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo/bar/options/override/test') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + t.assert.deepStrictEqual(response.headers.get('cache-control'), `public, max-age=${maxAge / 1000}`) + genericResponseChecks(t, response) + }) +}) + +test('sendFile disabled', async (t) => { + t.plan(1) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static', + decorateReply: false + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + fastify.get('/foo/bar', function (_req, reply) { + if (reply.sendFile === undefined) { + reply.send('pass') + } else { + reply.send('fail') + } + }) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('reply.sendFile undefined', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo/bar') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), 'pass') + }) +}) + +test('allowedPath option - pathname', async (t) => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + allowedPath: (pathName) => pathName !== '/foobar.html' + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + await t.test('/foobar.html not found', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foobar.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/index.css found', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + }) +}) + +test('allowedPath option - request', async (t) => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + allowedPath: (_pathName, _root, request) => request.query.key === 'temporaryKey' + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/foobar.html not found', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foobar.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/index.css found', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.css?key=temporaryKey') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + }) +}) + +test('download', async (t) => { + t.plan(6) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static' + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + fastify.get('/foo/bar', function (_req, reply) { + reply.download('/index.html') + }) + + fastify.get('/foo/bar/change', function (_req, reply) { + reply.download('/index.html', 'hello-world.html') + }) + + fastify.get('/foo/bar/override', function (_req, reply) { + reply.download('/index.html', 'hello-world.html', { + maxAge: '2 hours', + immutable: true + }) + }) + + fastify.get('/foo/bar/override/2', function (_req, reply) { + reply.download('/index.html', { acceptRanges: false }) + }) + + fastify.get('/root/path/override/test', (_request, reply) => { + reply.download('/foo.html', { + root: path.join( + __dirname, + 'static', + 'deep', + 'path', + 'for', + 'test', + 'purpose' + ) + }) + }) + + fastify.get('/root/path/override/test/change', (_request, reply) => { + reply.download('/foo.html', 'hello-world.html', { + root: path.join( + __dirname, + 'static', + 'deep', + 'path', + 'for', + 'test', + 'purpose' + ) + }) + }) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('reply.download()', async (t) => { + t.plan(4 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo/bar') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.headers.get('content-disposition'), 'attachment; filename="index.html"') + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('reply.download() with fileName', async t => { + t.plan(4 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo/bar/change') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-disposition'), 'attachment; filename="hello-world.html"') + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('reply.download() with fileName - override', async (t) => { + t.plan(4 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/root/path/override/test') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-disposition'), 'attachment; filename="foo.html"') + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('reply.download() with custom opts', async (t) => { + t.plan(5 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo/bar/override') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-disposition'), 'attachment; filename="hello-world.html"') + t.assert.deepStrictEqual(response.headers.get('cache-control'), 'public, max-age=7200, immutable') + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('reply.download() with custom opts (2)', async (t) => { + t.plan(5 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo/bar/override/2') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-disposition'), 'attachment; filename="index.html"') + t.assert.deepStrictEqual(response.headers.get('accept-ranges'), null) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('reply.download() with rootPath and fileName', async (t) => { + t.plan(4 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/root/path/override/test/change') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-disposition'), 'attachment; filename="hello-world.html"') + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) +}) + +test('download disabled', async (t) => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static', + decorateReply: false + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/foo/bar', function (_req, reply) { + if (reply.download === undefined) { + t.assert.deepStrictEqual(reply.download, undefined) + reply.send('pass') + } else { + reply.send('fail') + } + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('reply.sendFile undefined', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/foo/bar') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), 'pass') + }) +}) + +test('prefix default', (t) => { + t.plan(1) + const pluginOptions = { root: path.join(__dirname, 'static') } + const fastify = Fastify({ logger: false }) + t.assert.doesNotThrow(() => fastify.register(fastifyStatic, pluginOptions)) +}) + +test('root not found warning', async (t) => { + t.plan(1) + const rootPath = path.join(__dirname, 'does-not-exist') + const pluginOptions = { root: rootPath } + const destination = concat((data) => { + t.assert.deepStrictEqual(JSON.parse(data).msg, `"root" path "${rootPath}" must exist`) + }) + const loggerInstance = pino( + { + level: 'warn' + }, + destination + ) + const fastify = Fastify({ loggerInstance }) + fastify.register(fastifyStatic, pluginOptions) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + destination.end() +}) + +test('send options', (t) => { + t.plan(12) + const pluginOptions = { + root: path.join(__dirname, '/static'), + acceptRanges: 'acceptRanges', + contentType: 'contentType', + cacheControl: 'cacheControl', + dotfiles: 'dotfiles', + etag: 'etag', + extensions: 'extensions', + immutable: 'immutable', + index: 'index', + lastModified: 'lastModified', + maxAge: 'maxAge' + } + const fastify = Fastify({ logger: false }) + const { resolve, promise } = Promise.withResolvers() + const fastifyStatic = require('proxyquire')('../', { + '@fastify/send': function sendStub (_req, pathName, options) { + t.assert.deepStrictEqual(pathName, '/index.html') + t.assert.deepStrictEqual(options.root, path.join(__dirname, '/static')) + t.assert.deepStrictEqual(options.acceptRanges, 'acceptRanges') + t.assert.deepStrictEqual(options.contentType, 'contentType') + t.assert.deepStrictEqual(options.cacheControl, 'cacheControl') + t.assert.deepStrictEqual(options.dotfiles, 'dotfiles') + t.assert.deepStrictEqual(options.etag, 'etag') + t.assert.deepStrictEqual(options.extensions, 'extensions') + t.assert.deepStrictEqual(options.immutable, 'immutable') + t.assert.deepStrictEqual(options.index, 'index') + t.assert.deepStrictEqual(options.lastModified, 'lastModified') + t.assert.deepStrictEqual(options.maxAge, 'maxAge') + resolve() + return { on: () => { }, pipe: () => { } } + } + }) + fastify.register(fastifyStatic, pluginOptions) + fastify.inject({ url: '/index.html' }) + + return promise +}) + +test('setHeaders option', async (t) => { + t.plan(5 + GENERIC_RESPONSE_CHECK_COUNT) + + const pluginOptions = { + root: path.join(__dirname, 'static'), + setHeaders: function (res, pathName) { + t.assert.deepStrictEqual(pathName, path.join(__dirname, 'static/index.html')) + res.setHeader('X-Test-Header', 'test') + } + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('x-test-header'), 'test') + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) +}) + +test('maxAge option', async (t) => { + t.plan(4 + GENERIC_RESPONSE_CHECK_COUNT) + + const pluginOptions = { + root: path.join(__dirname, 'static'), + maxAge: 3600000 + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('cache-control'), 'public, max-age=3600') + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) +}) + +test('errors', async (t) => { + t.plan(11) + + await t.test('no root', async (t) => { + t.plan(1) + const pluginOptions = {} + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) + + await t.test('root is not a string', async (t) => { + t.plan(1) + const pluginOptions = { root: 42 } + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) + + await t.test('root is not an absolute path', async (t) => { + t.plan(1) + const pluginOptions = { root: './my/path' } + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) + + await t.test('root is not a directory', async (t) => { + t.plan(1) + const pluginOptions = { root: __filename } + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) + + await t.test('root is an empty array', async (t) => { + t.plan(1) + const pluginOptions = { root: [] } + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) + + await t.test('root array does not contain strings', async (t) => { + t.plan(1) + const pluginOptions = { root: [1] } + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) + + await t.test('root array does not contain an absolute path', async (t) => { + t.plan(1) + const pluginOptions = { root: ['./my/path'] } + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) + + await t.test('root array path is not a directory', async (t) => { + t.plan(1) + const pluginOptions = { root: [__filename] } + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) + + await t.test('all root array paths must be valid', async (t) => { + t.plan(1) + const pluginOptions = { root: [path.join(__dirname, '/static'), 1] } + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) + + await t.test('duplicate root paths are not allowed', async (t) => { + t.plan(1) + const pluginOptions = { + root: [path.join(__dirname, '/static'), path.join(__dirname, '/static')] + } + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) + + await t.test('setHeaders is not a function', async (t) => { + t.plan(1) + const pluginOptions = { root: __dirname, setHeaders: 'headers' } + const fastify = Fastify({ logger: false }) + await t.assert.rejects(async () => await fastify.register(fastifyStatic, pluginOptions)) + }) +}) + +test('register no prefix', async (t) => { + t.plan(7) + + const pluginOptions = { + root: path.join(__dirname, '/static') + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/', (_request, reply) => { + reply.send({ hello: 'world' }) + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/index.css', async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + genericResponseChecks(t, response) + }) + + await t.test('/', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), { hello: 'world' }) + }) + + await t.test('/deep/path/for/test/purpose/foo.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/deep/path/for/test/purpose/foo.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('/deep/path/for/test/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/deep/path/for/test/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/this/path/doesnt/exist.html', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/this/path/doesnt/exist.html') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/../index.js', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/../index.js') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) +}) + +test('with fastify-compress', async t => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static') + } + const fastify = Fastify() + fastify.register(compress, { threshold: 0 }) + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + await t.test('deflate', async function (t) { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html', { + headers: { + 'accept-encoding': ['deflate'] + } + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-encoding'), 'deflate') + genericResponseChecks(t, response) + }) + + await t.test('gzip', async function (t) { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-encoding'), 'gzip') + genericResponseChecks(t, response) + }) +}) +test('register /static/ with schemaHide true', async t => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static/', + schemaHide: true + } + + const fastify = Fastify() + + fastify.addHook('onRoute', function (routeOptions) { + t.assert.deepStrictEqual(routeOptions.schema, { hide: true }) + }) + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/html; charset=utf-8') + genericResponseChecks(t, response) + }) +}) + +test('register /static/ with schemaHide false', async t => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static/', + schemaHide: false + } + + const fastify = Fastify() + + fastify.addHook('onRoute', function (routeOptions) { + t.assert.deepStrictEqual(routeOptions.schema, { hide: false }) + }) + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/html; charset=utf-8') + genericResponseChecks(t, response) + }) +}) + +test('register /static/ without schemaHide', async t => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static/' + } + + const fastify = Fastify() + + fastify.addHook('onRoute', function (routeOptions) { + t.assert.deepStrictEqual(routeOptions.schema, { hide: true }) + }) + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/html; charset=utf-8') + genericResponseChecks(t, response) + }) +}) + +test('fastify with exposeHeadRoutes', async t => { + t.plan(1) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + wildcard: false + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/index.html', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html', { method: 'HEAD' }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) +}) + +test('register with wildcard false', async t => { + t.plan(8) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + wildcard: false + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/*', (_request, reply) => { + reply.send({ hello: 'world' }) + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/index.html', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/index.css', async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + genericResponseChecks(t, response) + }) + + await t.test('/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/not-defined', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/not-defined') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), { hello: 'world' }) + }) + + await t.test('/deep/path/for/test/purpose/foo.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/deep/path/for/test/purpose/foo.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('/deep/path/for/test/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/deep/path/for/test/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/../index.js', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/../index.js') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), { hello: 'world' }) + }) + + await t.test('/index.css', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) +}) + +test('register with wildcard false (trailing slash in the root)', async t => { + t.plan(5) + + const pluginOptions = { + root: path.join(__dirname, '/static/'), + prefix: '/assets/', + index: false, + wildcard: false + } + const fastify = Fastify({ + ignoreTrailingSlash: true + }) + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/*', (_request, reply) => { + reply.send({ hello: 'world' }) + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/index.css', async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/assets/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + genericResponseChecks(t, response) + }) + + await t.test('/not-defined', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/assets/not-defined') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), { hello: 'world' }) + }) + + await t.test('/deep/path/for/test/purpose/foo.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/assets/deep/path/for/test/purpose/foo.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('/../index.js', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/assets/../index.js') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), { hello: 'world' }) + }) + + await t.test('/index.css', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/assets/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) +}) + +test('register with wildcard string', async (t) => { + t.plan(1) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + wildcard: '**/index.html' + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/*', (_request, reply) => { + reply.send({ hello: 'world' }) + }) + + await t.assert.rejects(fastify.ready()) +}) + +test('register with wildcard string on multiple root paths', async (t) => { + t.plan(1) + + const pluginOptions = { + root: [path.join(__dirname, '/static'), path.join(__dirname, '/static2')], + wildcard: '**/*.js' + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/*', (_request, reply) => { + reply.send({ hello: 'world' }) + }) + + t.after(() => fastify.close()) + + await t.assert.rejects(fastify.listen({ port: 0 })) +}) + +test('register with wildcard false and alternative index', async t => { + t.plan(10) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + wildcard: false, + index: ['foobar.html', 'foo.html', 'index.html'] + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/*', (_request, reply) => { + reply.send({ hello: 'world' }) + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/index.html', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html', { method: 'HEAD' }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) + + await t.test('/index.css', async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + genericResponseChecks(t, response) + }) + + await t.test('/?a=b', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), foobarContent) + genericResponseChecks(t, response) + }) + + await t.test('/?a=b', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port, { + method: 'HEAD' + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) + + await t.test('/not-defined', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/not-defined') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), { hello: 'world' }) + }) + + await t.test('/deep/path/for/test/purpose/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/deep/path/for/test/purpose/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('/deep/path/for/test/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/deep/path/for/test/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/deep/path/for/test/', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/deep/path/for/test/', { + method: 'HEAD' + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) + + await t.test('/../index.js', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/../index.js') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), { hello: 'world' }) + }) +}) + +test('register /static with wildcard false and alternative index', async t => { + t.plan(10) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static', + wildcard: false, + index: ['foobar.html', 'foo.html', 'index.html'] + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/*', (_request, reply) => { + reply.send({ hello: 'world' }) + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/index.html', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html', { + method: 'HEAD' + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) + + await t.test('/static/index.css', async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + genericResponseChecks(t, response) + }) + + await t.test('/static', (t) => { + t.plan(2) + + const { promise, resolve } = Promise.withResolvers() + + // simple-get doesn't tell us about redirects so use http.request directly + // to verify we do not get a redirect when not requested + const testurl = 'http://localhost:' + fastify.server.address().port + '/static' + const req = http.request(url.parse(testurl), res => { + t.assert.deepStrictEqual(res.statusCode, 200) + let body = '' + res.on('data', (chunk) => { + body += chunk.toString() + }) + res.on('end', () => { + t.assert.deepStrictEqual(JSON.parse(body.toString()), { hello: 'world' }) + resolve() + }) + }) + req.on('error', (err) => console.error(err)) + req.end() + + return promise + }) + + await t.test('/static/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), foobarContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/', { + method: 'HEAD' + }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) + + await t.test('/static/not-defined', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/not-defined') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), { hello: 'world' }) + }) + + await t.test('/static/deep/path/for/test/purpose/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/purpose/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/static/../index.js', async (t) => { + t.plan(3) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/../index.js') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.json(), { hello: 'world' }) + }) +}) + +test('register /static with redirect true', async t => { + t.plan(6) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static', + redirect: true, + index: 'index.html' + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static?a=b', async (t) => { + t.plan(5 + GENERIC_RESPONSE_CHECK_COUNT) + + const { promise, resolve } = Promise.withResolvers() + + // simple-get doesn't tell us about redirects so use http.request directly + const testurl = 'http://localhost:' + fastify.server.address().port + '/static?a=b' + const req = http.request(url.parse(testurl), res => { + t.assert.deepStrictEqual(res.statusCode, 301) + t.assert.deepStrictEqual(res.headers.location, '/static/?a=b') + resolve() + }) + req.on('error', (err) => console.error(err)) + req.end() + + await promise + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static?a=b') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static', t => { + t.plan(2) + + const { promise, resolve } = Promise.withResolvers() + + // simple-get doesn't tell us about redirects so use http.request directly + const testurl = 'http://localhost:' + fastify.server.address().port + '/static' + const req = http.request(url.parse(testurl), res => { + t.assert.deepStrictEqual(res.statusCode, 301) + t.assert.deepStrictEqual(res.headers.location, '/static/') + + resolve() + }) + req.on('error', err => console.error(err)) + req.end() + + return promise + }) + + await t.test('/static/', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/deep', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test?a=b', async (t) => { + t.plan(5 + GENERIC_RESPONSE_CHECK_COUNT) + + const { promise, resolve } = Promise.withResolvers() + + // simple-get doesn't tell us about redirects so use http.request directly + const testurl = 'http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test?a=b' + const req = http.request(url.parse(testurl), res => { + t.assert.deepStrictEqual(res.statusCode, 301) + t.assert.deepStrictEqual(res.headers.location, '/static/deep/path/for/test/?a=b') + resolve() + }) + req.on('error', (err) => console.error(err)) + req.end() + + await promise + + // verify the redirect with query parameters works + const response = await fetch(testurl) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) +}) + +test('register /static with redirect true and wildcard false', async t => { + t.plan(7) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static', + redirect: true, + wildcard: false, + index: 'index.html' + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/static?a=b', async t => { + t.plan(5 + GENERIC_RESPONSE_CHECK_COUNT) + + const { promise, resolve } = Promise.withResolvers() + + // simple-get doesn't tell us about redirects so use http.request directly + const testurl = 'http://localhost:' + fastify.server.address().port + '/static?a=b' + const req = http.request(url.parse(testurl), res => { + t.assert.deepStrictEqual(res.statusCode, 301) + t.assert.deepStrictEqual(res.headers.location, '/static/?a=b') + resolve() + }) + req.on('error', err => console.error(err)) + req.end() + await promise + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static?a=b') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/?a=b', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/?a=b') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/?a=b - HEAD', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/?a=b', { method: 'HEAD' }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) + + await t.test('/static/deep', async t => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test?a=b', async t => { + t.plan(5 + GENERIC_RESPONSE_CHECK_COUNT) + + const { promise, resolve } = Promise.withResolvers() + + // simple-get doesn't tell us about redirects so use http.request directly + const testurl = 'http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test?a=b' + const req = http.request(url.parse(testurl), res => { + t.assert.deepStrictEqual(res.statusCode, 301) + t.assert.deepStrictEqual(res.headers.location, '/static/deep/path/for/test/?a=b') + resolve() + }) + req.on('error', err => console.error(err)) + req.end() + await promise + + const response = await fetch(testurl) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test', { method: 'HEAD' }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) +}) + +test('trailing slash behavior with redirect = false', async (t) => { + t.plan(5) + + const fastify = Fastify() + fastify.register(fastifyStatic, { + root: path.join(__dirname, '/static'), + prefix: '/static', + redirect: false + }) + fastify.server.unref() + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + const host = 'http://localhost:' + fastify.server.address().port + + await t.test('prefix with no trailing slash => 404', async (t) => { + t.plan(2) + + const response = await fetch(host + '/static') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + }) + + await t.test('prefix with trailing trailing slash => 200', async (t) => { + t.plan(2) + + const response = await fetch(host + '/static/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + }) + + await t.test('deep path with no index.html or trailing slash => 404', async (t) => { + t.plan(2) + + const response = await fetch(host + '/static/deep/path') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + }) + + await t.test('deep path with index.html but no trailing slash => 200', async (t) => { + t.plan(2) + + const response = await fetch(host + '/static/deep/path/for/test') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + }) + + await t.test('deep path with index.html and trailing slash => 200', async (t) => { + t.plan(2) + + const response = await fetch(host + '/static/deep/path/for/test/') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + }) +}) + +test('if dotfiles are properly served according to plugin options', async (t) => { + t.plan(3) + const exampleContents = fs + .readFileSync(path.join(__dirname, 'static', '.example'), { + encoding: 'utf8' + }) + .toString() + + await t.test('freely serve dotfiles', async (t) => { + t.plan(3) + const fastify = Fastify() + + const pluginOptions = { + root: path.join(__dirname, 'static'), + prefix: '/static/', + dotfiles: 'allow' + } + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/.example') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), exampleContents) + }) + + await t.test('ignore dotfiles', async (t) => { + t.plan(2) + const fastify = Fastify() + + const pluginOptions = { + root: path.join(__dirname, 'static'), + prefix: '/static/', + dotfiles: 'ignore' + } + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/.example') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + }) + + await t.test('deny requests to serve a dotfile', async (t) => { + t.plan(2) + const fastify = Fastify() + + const pluginOptions = { + root: path.join(__dirname, 'static'), + prefix: '/static/', + dotfiles: 'deny' + } + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/.example') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 403) + }) +}) + +test('register with failing glob handler', async (t) => { + const fastifyStatic = proxyquire.noCallThru()('../', { + glob: function globStub (_pattern, _options, cb) { + process.nextTick(function () { + return cb(new Error('mock glob error')) + }) + } + }) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + serve: true, + wildcard: false + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await t.assert.rejects(fastify.listen({ port: 0 })) +}) + +test( + 'register with rootpath that causes statSync to fail with non-ENOENT code', + async (t) => { + const fastifyStatic = proxyquire('../', { + 'node:fs': { + statSync: function statSyncStub () { + throw new Error({ code: 'MOCK' }) + } + } + }) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + wildcard: true + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await t.assert.rejects(fastify.listen({ port: 0 })) + } +) + +test('inject support', async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static' + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static/index.html' + }) + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.body.toString(), indexContent) +}) + +test('routes should use custom errorHandler premature stream close', async t => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static/' + } + + const fastify = Fastify() + + fastify.addHook('onRoute', function (routeOptions) { + t.assert.ok(routeOptions.errorHandler instanceof Function) + + routeOptions.onRequest = (_request, _reply, done) => { + const fakeError = new Error() + fakeError.code = 'ERR_STREAM_PREMATURE_CLOSE' + done(fakeError) + } + }) + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + await t.assert.rejects(fastify.inject({ method: 'GET', url: '/static/index.html' })) +}) + +test('routes should fallback to default errorHandler', async t => { + t.plan(3) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static/' + } + + const fastify = Fastify() + + fastify.addHook('onRoute', function (routeOptions) { + t.assert.ok(routeOptions.errorHandler instanceof Function) + + routeOptions.preHandler = (_request, _reply, done) => { + const fakeError = new Error() + fakeError.code = 'SOMETHING_ELSE' + done(fakeError) + } + }) + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ method: 'GET', url: '/static/index.html' }) + t.assert.deepStrictEqual(response.statusCode, 500) + t.assert.deepStrictEqual(await response.json(), { + statusCode: 500, + code: 'SOMETHING_ELSE', + error: 'Internal Server Error', + message: '' + }) +}) + +test('percent encoded URLs in glob mode', async (t) => { + t.plan(3) + + const fastify = Fastify({}) + + fastify.register(fastifyStatic, { + root: path.join(__dirname, 'static'), + prefix: '/static', + wildcard: true + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/a .md') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual( + fs.readFileSync(path.join(__dirname, 'static', 'a .md'), 'utf-8'), + await response.text() + ) +}) + +test('register /static and /static2 without wildcard', async t => { + t.plan(2) + + const pluginOptions = { + root: [path.join(__dirname, '/static'), path.join(__dirname, '/static2')], + wildcard: false + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + await t.test('/index.html', async t => { + t.plan(4 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + const responseContent = await response.text() + t.assert.notDeepStrictEqual(responseContent, index2Content) + t.assert.deepStrictEqual(responseContent, indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/bar.html', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/bar.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), barContent) + genericResponseChecks(t, response) + }) +}) + +test( + 'will serve pre-compressed files with .br at the highest priority', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/all-three.html', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'br') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, allThreeBr) + } +) + +test( + 'will serve pre-compressed files and fallback to .gz if .br is not on disk', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/gzip-only.html', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'gzip') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, gzipOnly) + } +) + +test( + 'will serve pre-compressed files with .gzip if * directive used', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/all-three.html', + headers: { + 'accept-encoding': '*' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'gzip') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, allThreeGzip) + } +) + +test( + 'will serve pre-compressed files with .gzip if multiple * directives used', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/all-three.html', + headers: { + 'accept-encoding': '*, *' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'gzip') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, allThreeGzip) + } +) + +test( + 'will serve uncompressed files if there are no compressed variants on disk', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/uncompressed.html', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], undefined) + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.body, uncompressedStatic) + } +) + +test( + 'will serve pre-compressed files with .br at the highest priority (with wildcard: false)', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true, + wildcard: false + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/all-three.html', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'br') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, allThreeBr) + } +) + +test( + 'will serve pre-compressed files and fallback to .gz if .br is not on disk (with wildcard: false)', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true, + wildcard: false + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/gzip-only.html', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'gzip') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, gzipOnly) + } +) + +test( + 'will serve pre-compressed files with .gzip if * directive used (with wildcard: false)', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true, + wildcard: false + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/all-three.html', + headers: { + 'accept-encoding': '*' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'gzip') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, allThreeGzip) + } +) + +test( + 'will serve pre-compressed files with .gzip if multiple * directives used (with wildcard: false)', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true, + wildcard: false + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/all-three.html', + headers: { + 'accept-encoding': '*, *' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'gzip') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, allThreeGzip) + } +) + +test( + 'will serve uncompressed files if there are no compressed variants on disk (with wildcard: false)', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true, + wildcard: false + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/uncompressed.html', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], undefined) + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.body, uncompressedStatic) + } +) + +test( + 'will serve uncompressed files the accept-encoding header is missing', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/uncompressed.html' + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], undefined) + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.body, uncompressedStatic) + } +) + +test( + 'will serve precompressed index', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'br') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, indexBr) + } +) + +test( + 'will serve preCompressed index without trailing slash', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true, + redirect: false + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/dir', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'br') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, dirIndexBr) + } +) + +test( + 'will redirect to preCompressed index without trailing slash when redirect is true', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true, + redirect: true, + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/dir', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + t.assert.deepStrictEqual(response.statusCode, 301) + t.assert.deepStrictEqual(response.headers.location, '/static-pre-compressed/dir/') + } +) + +test( + 'will serve precompressed gzip index in subdir', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/dir-gz', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'gzip') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, dirIndexGz) + } +) + +test( + 'will serve precompressed index with alternative index option', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true, + index: ['all-three.html'] + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'br') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, allThreeBr) + } +) + +test( + 'will serve precompressed file without content-type charset', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/sample.jpg', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + t.assert.deepStrictEqual(response.headers['content-type'], 'image/jpeg') + t.assert.deepStrictEqual(response.headers['content-encoding'], 'br') + t.assert.deepStrictEqual(response.statusCode, 200) + } +) + +test( + 'will not redirect but serve a file if preCompressed but no compressed file exists and redirect is true', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true, + redirect: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/baz.json', + headers: { + 'accept-encoding': '*' + } + }) + + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.headers['content-type'], 'application/json; charset=utf-8') + } +) + +test( + 'nonexistent index with precompressed option', + async (t) => { + const pluginOptions = { + root: path.join(__dirname, '/static-pre-compressed'), + prefix: '/static-pre-compressed/', + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: '/static-pre-compressed/empty/', + headers: { + 'accept-encoding': 'gzip, deflate, br' + } + }) + + t.assert.deepStrictEqual(response.statusCode, 404) + genericErrorResponseChecks(t, response) + } +) + +test('should not redirect to protocol-relative locations', async (t) => { + const urls = [ + ['//^/..', '/', 301], + ['//^/.', null, 404], // it is NOT recognized as a directory by pillarjs/send + ['//:/..', '/', 301], + ['/\\\\a//google.com/%2e%2e%2f%2e%2e', '/a//google.com/%2e%2e%2f%2e%2e/', 301], + ['//a//youtube.com/%2e%2e%2f%2e%2e', '/a//youtube.com/%2e%2e%2f%2e%2e/', 301], + ['/^', null, 404], // it is NOT recognized as a directory by pillarjs/send + ['//google.com/%2e%2e', '/', 301], + ['//users/%2e%2e', '/', 301], + ['//users', null, 404], + ['///deep/path//for//test//index.html', null, 200] + ] + + t.plan(urls.length * 2) + const fastify = Fastify() + fastify.register(fastifyStatic, { + root: path.join(__dirname, '/static'), + redirect: true + }) + t.after(() => fastify.close()) + + const address = await fastify.listen({ port: 0 }) + fastify.server.unref() + + const promises = urls.map(([testUrl, expected, status]) => { + const { promise, resolve } = Promise.withResolvers() + + const req = http.request(url.parse(address + testUrl), res => { + t.assert.deepStrictEqual(res.statusCode, status, `status ${testUrl}`) + + if (expected) { + t.assert.deepStrictEqual(res.headers.location, expected) + } else { + t.assert.ok(!res.headers.location) + } + + resolve() + }) + req.on('error', t.assert.fail) + req.end() + return promise + }) + + await Promise.all(promises) +}) + +test('should not serve index if option is `false`', async (t) => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static', + index: false + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) +}) + +test('should follow symbolic link without wildcard', async (t) => { + t.plan(4) + const fastify = Fastify() + fastify.register(fastifyStatic, { + root: path.join(__dirname, '/static-symbolic-link'), + wildcard: false + }) + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/origin/subdir/subdir/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + + const response2 = await fetch('http://localhost:' + fastify.server.address().port + '/dir/symlink/subdir/subdir/index.html') + t.assert.ok(response2.ok) + t.assert.deepStrictEqual(response2.status, 200) +}) + +test('should serve files into hidden dir with wildcard `false`', async (t) => { + t.plan(8) + + const pluginOptions = { + root: path.join(__dirname, '/static-hidden'), + wildcard: false, + serveDotFiles: true + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/.hidden/sample.json') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), jsonHiddenContent) + t.assert.ok(/application\/(json)/.test(response.headers.get('content-type'))) + t.assert.ok(response.headers.get('etag')) + t.assert.ok(response.headers.get('last-modified')) + t.assert.ok(response.headers.get('date')) + t.assert.ok(response.headers.get('cache-control')) +}) + +test('should not found hidden file with wildcard is `false`', async (t) => { + t.plan(2) + + const pluginOptions = { + root: path.join(__dirname, '/static-hidden'), + wildcard: false + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/.hidden/sample.json') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) +}) + +test('should serve files into hidden dir without wildcard option', async (t) => { + t.plan(8) + + const pluginOptions = { + root: path.join(__dirname, '/static-hidden') + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/.hidden/sample.json') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), jsonHiddenContent) + t.assert.ok(/application\/(json)/.test(response.headers.get('content-type'))) + t.assert.ok(response.headers.get('etag')) + t.assert.ok(response.headers.get('last-modified')) + t.assert.ok(response.headers.get('date')) + t.assert.ok(response.headers.get('cache-control')) +}) + +test( + 'will serve pre-compressed files with .gzip if multi-root', + async (t) => { + const pluginOptions = { + root: [path.join(__dirname, '/static-pre-compressed'), path.join(__dirname, '/static')], + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: 'all-three.html', + headers: { + 'accept-encoding': '*, *' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.headers['content-encoding'], 'gzip') + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.rawPayload, allThreeGzip) + } +) + +test( + 'will still serve un-compressed files with multi-root and preCompressed as true', + async (t) => { + const pluginOptions = { + root: [path.join(__dirname, '/static-pre-compressed'), path.join(__dirname, '/static')], + preCompressed: true + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + t.after(() => fastify.close()) + + const response = await fastify.inject({ + method: 'GET', + url: 'foobar.html', + headers: { + 'accept-encoding': '*, *' + } + }) + + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.body, foobarContent) + } +) + +test( + 'converts URL to path', + async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + const pluginOptions = { + root: url.pathToFileURL(path.join(__dirname, '/static')) + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + const response = await fastify.inject({ + method: 'GET', + url: 'foobar.html', + headers: { + 'accept-encoding': '*, *' + } + }) + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.body, foobarContent) + } +) + +test( + 'converts array of URLs to path, contains string path', + async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + const pluginOptions = { + root: [url.pathToFileURL(path.join(__dirname, '/static')), path.join(__dirname, 'static-dotfiles'), url.pathToFileURL(path.join(__dirname, '/static-pre-compressed'))] + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + const response = await fastify.inject({ + method: 'GET', + url: 'foobar.html', + headers: { + 'accept-encoding': '*, *' + } + }) + genericResponseChecks(t, response) + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.body, foobarContent) + } +) + +test( + 'serves files with paths that have characters modified by encodeUri when wildcard is false', + async (t) => { + const aContent = fs.readFileSync(path.join(__dirname, 'static-encode/[...]', 'a .md'), 'utf-8') + + t.plan(4) + const pluginOptions = { + root: url.pathToFileURL(path.join(__dirname, '/static-encode')), + wildcard: false + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + const response = await fastify.inject({ + method: 'GET', + url: '[...]/a .md', + headers: { + 'accept-encoding': '*, *' + } + }) + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.body, aContent) + + const response2 = await fastify.inject({ + method: 'GET', + url: '%5B...%5D/a%20.md', + headers: { + 'accept-encoding': '*, *' + } + }) + t.assert.deepStrictEqual(response2.statusCode, 200) + t.assert.deepStrictEqual(response2.body, aContent) + } +) + +test( + 'serves files with % in the filename', + async (t) => { + t.plan(2) + + const txtContent = fs.readFileSync(path.join(__dirname, 'static', '100%.txt'), 'utf-8') + + const pluginOptions = { + root: url.pathToFileURL(path.join(__dirname, '/static')), + wildcard: false + } + + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + const response = await fastify.inject({ + method: 'GET', + url: '100%25.txt', + headers: { + 'accept-encoding': '*, *' + } + }) + t.assert.deepStrictEqual(response.statusCode, 200) + t.assert.deepStrictEqual(response.body, txtContent) + } +) + +test('content-length in head route should not return zero when using wildcard', async t => { + t.plan(5) + + const pluginOptions = { + root: path.join(__dirname, '/static') + } + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const file = fs.readFileSync(path.join(__dirname, '/static/index.html')) + const contentLength = Buffer.byteLength(file).toString() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html', { method: 'HEAD' }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/html; charset=utf-8') + t.assert.deepStrictEqual(response.headers.get('content-length'), contentLength) + t.assert.deepStrictEqual(await response.text(), '') +}) + +test('respect the .code when using with sendFile', async t => { + t.plan(5) + + const pluginOptions = { + root: path.join(__dirname, '/static') + } + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/custom', (_, reply) => { + return reply.code(404).type('text/html').sendFile('foo.html') + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const file = fs.readFileSync(path.join(__dirname, '/static/foo.html')) + const contentLength = Buffer.byteLength(file).toString() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/custom', { method: 'HEAD' }) + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/html; charset=utf-8') + t.assert.deepStrictEqual(response.headers.get('content-length'), contentLength) + t.assert.deepStrictEqual(await response.text(), '') +}) + +test('respect the .type when using with sendFile with contentType disabled', async t => { + t.plan(5) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + contentType: false + } + const fastify = Fastify() + + fastify.register(fastifyStatic, pluginOptions) + + fastify.get('/custom', (_, reply) => { + return reply.type('text/html; charset=windows-1252').sendFile('foo.html') + }) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + const file = fs.readFileSync(path.join(__dirname, '/static/foo.html')) + const contentLength = Buffer.byteLength(file).toString() + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/custom') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(response.headers.get('content-type'), 'text/html; charset=windows-1252') + t.assert.deepStrictEqual(response.headers.get('content-length'), contentLength) + t.assert.deepStrictEqual(await response.text(), fooContent) +}) + +test('register /static/ with custom log level', async t => { + t.plan(9) + + const pluginOptions = { + root: path.join(__dirname, '/static'), + prefix: '/static/', + logLevel: 'warn' + } + const fastify = Fastify({ + logger: { + stream: { + write: (logLine) => { + if (logLine.includes('"msg":"incoming request"')) { + console.warn(logLine) + throw new Error('Should never reach this point since log level is set at WARN!! Unexpected log line: ' + logLine) + } + }, + }, + }, + }) + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + fastify.server.unref() + + await t.test('/static/index.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/index.html', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html', { method: 'HEAD' }) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), '') + genericResponseChecks(t, response) + }) + + await t.test('/static/index.css', async (t) => { + t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT) + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.css') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + genericResponseChecks(t, response) + }) + + await t.test('/static/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/') + + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/static/deep/path/for/test/purpose/foo.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/purpose/foo.html') + + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + await t.test('/static/deep/path/for/test/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/') + + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), innerIndex) + genericResponseChecks(t, response) + }) + + await t.test('/static/this/path/for/test', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/this/path/for/test') + + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('/static/this/path/doesnt/exist.html', async (t) => { + t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT) + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/this/path/doesnt/exist.html') + + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + genericErrorResponseChecks(t, response) + }) + + await t.test('304', async t => { + t.plan(5 + GENERIC_RESPONSE_CHECK_COUNT) + const response = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html') + + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + + const response2 = await fetch('http://localhost:' + fastify.server.address().port + '/static/index.html', { + headers: { + 'if-none-match': response.headers.get('etag') + }, + cache: 'no-cache' + }) + t.assert.ok(!response2.ok) + t.assert.deepStrictEqual(response2.status, 304) + }) +}) + +test('register with wildcard false and globIgnore', async t => { + t.plan(5) + + const indexContent = fs + .readFileSync('./test/static-filtered/index.html') + .toString('utf8') + + const deepContent = fs + .readFileSync('./test/static-filtered/deep/path/to/baz.html') + .toString('utf8') + + const pluginOptions = { + root: path.join(__dirname, '/static-filtered'), + wildcard: false, + globIgnore: ['**/*.private'] + } + const fastify = Fastify() + fastify.register(fastifyStatic, pluginOptions) + + t.after(() => fastify.close()) + + await fastify.listen({ port: 0 }) + + fastify.server.unref() + + await t.test('/index.html', async t => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/index.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/bar.private', async t => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/bar.private') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + await response.text() + }) + + await t.test('/', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port) + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), indexContent) + genericResponseChecks(t, response) + }) + + await t.test('/deep/path/to/baz.html', async (t) => { + t.plan(3 + GENERIC_RESPONSE_CHECK_COUNT) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/deep/path/to/baz.html') + t.assert.ok(response.ok) + t.assert.deepStrictEqual(response.status, 200) + t.assert.deepStrictEqual(await response.text(), deepContent) + genericResponseChecks(t, response) + }) + + await t.test('/deep/path/to/baz.private', async (t) => { + t.plan(2) + + const response = await fetch('http://localhost:' + fastify.server.address().port + '/deep/path/to/baz.private') + t.assert.ok(!response.ok) + t.assert.deepStrictEqual(response.status, 404) + await response.text() + }) +}) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/.example b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/.example new file mode 100644 index 0000000000000000000000000000000000000000..09de8f1d51dad3c8119cdd67cb90dcf3721eb2f3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/.example @@ -0,0 +1 @@ +contents of a dotfile \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/100%.txt b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/100%.txt new file mode 100644 index 0000000000000000000000000000000000000000..4dd6a5cb6024f4c997e5888b979953d5ca2a1f4f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/100%.txt @@ -0,0 +1 @@ +100% diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/a .md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/a .md new file mode 100644 index 0000000000000000000000000000000000000000..96236f8158b12701d5e75c14fb876c4a0f31b963 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/a .md @@ -0,0 +1 @@ +example \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/deep/path/for/test/index.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/deep/path/for/test/index.html new file mode 100644 index 0000000000000000000000000000000000000000..49700f6bdd5e5cd20d188313e60d450d9fc211d0 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/deep/path/for/test/index.html @@ -0,0 +1,5 @@ + + + inner index.html + + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/deep/path/for/test/purpose/foo.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/deep/path/for/test/purpose/foo.html new file mode 100644 index 0000000000000000000000000000000000000000..900b7166cc9d931a143e863a8a2d5f62938047c3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/deep/path/for/test/purpose/foo.html @@ -0,0 +1,5 @@ + + + the deep path for test purpose body + + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/foo.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/foo.html new file mode 100644 index 0000000000000000000000000000000000000000..424329433de5692770306bca1817b08928b0e153 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/foo.html @@ -0,0 +1,3 @@ + + foo + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/foobar.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/foobar.html new file mode 100644 index 0000000000000000000000000000000000000000..d53979c2599ff126adc38527409dc96784dc9c5f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/foobar.html @@ -0,0 +1,3 @@ + + foobar + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/index.css b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/index.css new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/index.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/index.html new file mode 100644 index 0000000000000000000000000000000000000000..1b0b72f02fe433adb972fde358d316866365eef5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static/index.html @@ -0,0 +1,5 @@ + + + the body + + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static2/bar.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static2/bar.html new file mode 100644 index 0000000000000000000000000000000000000000..00d3bc347080dd858da04acee2dc549f8643c8a7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static2/bar.html @@ -0,0 +1,3 @@ + + bar + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static2/index.html b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static2/index.html new file mode 100644 index 0000000000000000000000000000000000000000..e3b8da08481c7025e626016a2d0a00e9f2623e25 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/test/static2/index.html @@ -0,0 +1,3 @@ + + index2 + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/types/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d410bb212f69c43065618b854fe51f3329540a88 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/types/index.d.ts @@ -0,0 +1,128 @@ +// Definitions by: Jannik +// Leo +/// + +import { FastifyPluginAsync, FastifyReply, FastifyRequest, RouteOptions } from 'fastify' +import { Stats } from 'node:fs' + +declare module 'fastify' { + interface FastifyReply { + sendFile(filename: string, rootPath?: string): FastifyReply; + sendFile(filename: string, options?: fastifyStatic.SendOptions): FastifyReply; + sendFile(filename: string, rootPath?: string, options?: fastifyStatic.SendOptions): FastifyReply; + download(filepath: string, options?: fastifyStatic.SendOptions): FastifyReply; + download(filepath: string, filename?: string): FastifyReply; + download(filepath: string, filename?: string, options?: fastifyStatic.SendOptions): FastifyReply; + } +} + +type FastifyStaticPlugin = FastifyPluginAsync> + +declare namespace fastifyStatic { + export interface SetHeadersResponse { + getHeader: FastifyReply['getHeader']; + setHeader: FastifyReply['header']; + readonly filename: string; + statusCode: number; + } + + export interface ExtendedInformation { + fileCount: number; + totalFileCount: number; + folderCount: number; + totalFolderCount: number; + totalSize: number; + lastModified: number; + } + + export interface ListDir { + href: string; + name: string; + stats: Stats; + extendedInfo?: ExtendedInformation; + } + + export interface ListFile { + href: string; + name: string; + stats: Stats; + } + + export interface ListRender { + (dirs: ListDir[], files: ListFile[]): string; + } + + export interface ListOptions { + names?: string[]; + extendedFolderInfo?: boolean; + jsonFormat?: 'names' | 'extended'; + } + + export interface ListOptionsJsonFormat extends ListOptions { + format: 'json'; + // Required when the URL parameter `format=html` exists + render?: ListRender; + } + + export interface ListOptionsHtmlFormat extends ListOptions { + format: 'html'; + render: ListRender; + } + + // Passed on to `send` + export interface SendOptions { + acceptRanges?: boolean; + contentType?: boolean; + cacheControl?: boolean; + dotfiles?: 'allow' | 'deny' | 'ignore'; + etag?: boolean; + extensions?: string[]; + immutable?: boolean; + index?: string[] | string | false; + lastModified?: boolean; + maxAge?: string | number; + serveDotFiles?: boolean; + } + + export interface FastifyStaticOptions extends SendOptions { + root: string | string[] | URL | URL[]; + prefix?: string; + prefixAvoidTrailingSlash?: boolean; + serve?: boolean; + decorateReply?: boolean; + schemaHide?: boolean; + setHeaders?: (res: SetHeadersResponse, path: string, stat: Stats) => void; + redirect?: boolean; + wildcard?: boolean; + globIgnore?: string[]; + list?: boolean | ListOptionsJsonFormat | ListOptionsHtmlFormat; + allowedPath?: (pathName: string, root: string, request: FastifyRequest) => boolean; + /** + * @description + * Opt-in to looking for pre-compressed files + */ + preCompressed?: boolean; + + // Passed on to `send` + acceptRanges?: boolean; + contentType?: boolean; + cacheControl?: boolean; + dotfiles?: 'allow' | 'deny' | 'ignore'; + etag?: boolean; + extensions?: string[]; + immutable?: boolean; + index?: string[] | string | false; + lastModified?: boolean; + maxAge?: string | number; + constraints?: RouteOptions['constraints']; + logLevel?: RouteOptions['logLevel']; + } + + export const fastifyStatic: FastifyStaticPlugin + + export { fastifyStatic as default } +} + +declare function fastifyStatic (...params: Parameters): ReturnType + +export = fastifyStatic diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/types/index.test-d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/types/index.test-d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c1936310e55c5e830bbfd40180e8651e994f500f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@fastify/static/types/index.test-d.ts @@ -0,0 +1,227 @@ +import fastify, { FastifyInstance, FastifyPluginAsync, FastifyRequest, FastifyReply } from 'fastify' +import { Server } from 'node:http' +import { Stats } from 'node:fs' +import { expectAssignable, expectError, expectType } from 'tsd' +import * as fastifyStaticStar from '..' +import fastifyStatic, { + FastifyStaticOptions, + fastifyStatic as fastifyStaticNamed +} from '..' + +import fastifyStaticCjsImport = require('..') +const fastifyStaticCjs = require('..') + +const app: FastifyInstance = fastify() + +app.register(fastifyStatic, { root: __dirname }) +app.register(fastifyStaticNamed, { root: __dirname }) +app.register(fastifyStaticCjs, { root: __dirname }) +app.register(fastifyStaticCjsImport.default, { root: __dirname }) +app.register(fastifyStaticCjsImport.fastifyStatic, { root: __dirname }) +app.register(fastifyStaticStar.default, { root: __dirname }) +app.register(fastifyStaticStar.fastifyStatic, { root: __dirname }) + +expectType>(fastifyStatic) +expectType>(fastifyStaticNamed) +expectType>(fastifyStaticCjsImport.default) +expectType>(fastifyStaticCjsImport.fastifyStatic) +expectType>(fastifyStaticStar.default) +expectType>( + fastifyStaticStar.fastifyStatic +) +expectType(fastifyStaticCjs) + +const appWithImplicitHttp = fastify() +const options: FastifyStaticOptions = { + acceptRanges: true, + contentType: true, + cacheControl: true, + decorateReply: true, + dotfiles: 'allow', + etag: true, + extensions: ['.js'], + immutable: true, + index: ['1'], + lastModified: true, + maxAge: '', + prefix: '', + prefixAvoidTrailingSlash: false, + root: '', + schemaHide: true, + serve: true, + wildcard: true, + globIgnore: ['**/*.private'], + list: false, + setHeaders: (res, path, stat) => { + expectType(res.filename) + expectType(res.statusCode) + expectType>(res.getHeader('X-Test')) + res.setHeader('X-Test', 'string') + + expectType(path) + + expectType(stat) + }, + preCompressed: false, + allowedPath: (_pathName: string, _root: string, _request: FastifyRequest) => { + return true + }, + constraints: { + host: /.*\.example\.com/, + version: '1.0.2' + }, + logLevel: 'warn' +} + +expectError({ + root: '', + wildcard: '**/**' +}) + +expectAssignable({ + root: '', + list: { + format: 'json' + } +}) + +expectAssignable({ + root: '', + list: { + format: 'json', + render: () => '' + } +}) + +expectAssignable({ + root: '', + list: { + format: 'html', + render: () => '' + } +}) + +expectError({ + root: '', + list: { + format: 'html' + } +}) + +expectAssignable({ + root: [''] +}) + +expectAssignable({ + root: new URL('') +}) + +expectAssignable({ + root: [new URL('')] +}) + +appWithImplicitHttp + .register(fastifyStatic, options) + .after(() => { + appWithImplicitHttp.get('/', (_request, reply) => { + reply.sendFile('some-file-name') + }) + }) + +const appWithHttp2 = fastify({ http2: true }) + +appWithHttp2 + .register(fastifyStatic, options) + .after(() => { + appWithHttp2.get('/', (_request, reply) => { + reply.sendFile('some-file-name') + }) + + appWithHttp2.get('/download', (_request, reply) => { + reply.download('some-file-name') + }) + + appWithHttp2.get('/download/1', (_request, reply) => { + reply.download('some-file-name', { maxAge: '2 days' }) + }) + + appWithHttp2.get('/download/2', (_request, reply) => { + reply.download('some-file-name', 'some-filename', { cacheControl: false, acceptRanges: true }) + }) + + appWithHttp2.get('/download/3', (_request, reply) => { + reply.download('some-file-name', 'some-filename', { contentType: false }) + }) + }) + +const multiRootAppWithImplicitHttp = fastify() +options.root = [''] + +multiRootAppWithImplicitHttp + .register(fastifyStatic, options) + .after(() => { + multiRootAppWithImplicitHttp.get('/', (_request, reply) => { + reply.sendFile('some-file-name') + }) + + multiRootAppWithImplicitHttp.get('/', (_request, reply) => { + reply.sendFile('some-file-name', { cacheControl: false, acceptRanges: true }) + }) + + multiRootAppWithImplicitHttp.get('/', (_request, reply) => { + reply.sendFile('some-file-name', 'some-root-name', { cacheControl: false, acceptRanges: true }) + }) + + multiRootAppWithImplicitHttp.get('/', (_request, reply) => { + reply.sendFile('some-file-name', 'some-root-name-2', { contentType: false }) + }) + + multiRootAppWithImplicitHttp.get('/download', (_request, reply) => { + reply.download('some-file-name') + }) + + multiRootAppWithImplicitHttp.get('/download/1', (_request, reply) => { + reply.download('some-file-name', { maxAge: '2 days' }) + }) + + multiRootAppWithImplicitHttp.get('/download/2', (_request, reply) => { + reply.download('some-file-name', 'some-filename', { cacheControl: false, acceptRanges: true }) + }) + + multiRootAppWithImplicitHttp.get('/download/3', (_request, reply) => { + reply.download('some-file-name', 'some-filename', { contentType: false }) + }) + }) + +const noIndexApp = fastify() +options.root = '' +options.index = false + +noIndexApp + .register(fastifyStatic, options) + .after(() => { + noIndexApp.get('/', (_request, reply) => { + reply.send('

fastify-static

') + }) + }) + +options.root = new URL('') + +const URLRootApp = fastify() +URLRootApp.register(fastifyStatic, options) + .after(() => { + URLRootApp.get('/', (_request, reply) => { + reply.send('

fastify-static

') + }) + }) + +const defaultIndexApp = fastify() +options.index = 'index.html' + +defaultIndexApp + .register(fastifyStatic, options) + .after(() => { + defaultIndexApp.get('/', (_request, reply) => { + reply.send('

fastify-static

') + }) + }) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/LICENSE b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/README.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7fb7457e4d2692285cae72922b5df25b8030eb72 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/README.md @@ -0,0 +1,377 @@ +# Google Gen AI SDK for TypeScript and JavaScript + +[![NPM Downloads](https://img.shields.io/npm/dw/%40google%2Fgenai)](https://www.npmjs.com/package/@google/genai) +[![Node Current](https://img.shields.io/node/v/%40google%2Fgenai)](https://www.npmjs.com/package/@google/genai) + +---------------------- +**Documentation:** https://googleapis.github.io/js-genai/ + +---------------------- + +The Google Gen AI JavaScript SDK is designed for +TypeScript and JavaScript developers to build applications powered by Gemini. The SDK +supports both the [Gemini Developer API](https://ai.google.dev/gemini-api/docs) +and [Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/overview). + +The Google Gen AI SDK is designed to work with Gemini 2.0 features. + +> [!CAUTION] +> **API Key Security:** Avoid exposing API keys in client-side code. +> Use server-side implementations in production environments. + +## Prerequisites + +1. Node.js version 20 or later + +### The following are required for Vertex AI users (excluding Vertex AI Studio) +1. [Select](https://console.cloud.google.com/project) or [create](https://cloud.google.com/resource-manager/docs/creating-managing-projects#creating_a_project) a Google Cloud project. +1. [Enable billing for your project](https://cloud.google.com/billing/docs/how-to/modify-project). +1. [Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com). +1. [Configure authentication](https://cloud.google.com/docs/authentication) for your project. + * [Install the gcloud CLI](https://cloud.google.com/sdk/docs/install). + * [Initialize the gcloud CLI](https://cloud.google.com/sdk/docs/initializing). + * Create local authentication credentials for your user account: + + ```sh + gcloud auth application-default login + ``` +A list of accepted authentication options are listed in [GoogleAuthOptions](https://github.com/googleapis/google-auth-library-nodejs/blob/3ae120d0a45c95e36c59c9ac8286483938781f30/src/auth/googleauth.ts#L87) interface of google-auth-library-node.js GitHub repo. + +## Installation + +To install the SDK, run the following command: + +```shell +npm install @google/genai +``` + +## Quickstart + +The simplest way to get started is to use an API key from +[Google AI Studio](https://aistudio.google.com/apikey): + +```typescript +import {GoogleGenAI} from '@google/genai'; +const GEMINI_API_KEY = process.env.GEMINI_API_KEY; + +const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY}); + +async function main() { + const response = await ai.models.generateContent({ + model: 'gemini-2.0-flash-001', + contents: 'Why is the sky blue?', + }); + console.log(response.text); +} + +main(); +``` + +## Initialization + +The Google Gen AI SDK provides support for both the +[Google AI Studio](https://ai.google.dev/gemini-api/docs) and +[Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/overview) + implementations of the Gemini API. + +### Gemini Developer API + +For server-side applications, initialize using an API key, which can +be acquired from [Google AI Studio](https://aistudio.google.com/apikey): + +```typescript +import { GoogleGenAI } from '@google/genai'; +const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); +``` + +#### Browser + +> [!CAUTION] +> **API Key Security:** Avoid exposing API keys in client-side code. +> Use server-side implementations in production environments. + +In the browser the initialization code is identical: + + +```typescript +import { GoogleGenAI } from '@google/genai'; +const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); +``` + +### Vertex AI + +Sample code for VertexAI initialization: + +```typescript +import { GoogleGenAI } from '@google/genai'; + +const ai = new GoogleGenAI({ + vertexai: true, + project: 'your_project', + location: 'your_location', +}); +``` + +### (Optional) (NodeJS only) Using environment variables: + +For NodeJS environments, you can create a client by configuring the necessary +environment variables. Configuration setup instructions depends on whether +you're using the Gemini Developer API or the Gemini API in Vertex AI. + +**Gemini Developer API:** Set `GOOGLE_API_KEY` as shown below: + +```bash +export GOOGLE_API_KEY='your-api-key' +``` + +**Gemini API on Vertex AI:** Set `GOOGLE_GENAI_USE_VERTEXAI`, +`GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION`, as shown below: + +```bash +export GOOGLE_GENAI_USE_VERTEXAI=true +export GOOGLE_CLOUD_PROJECT='your-project-id' +export GOOGLE_CLOUD_LOCATION='us-central1' +``` + +```typescript +import {GoogleGenAI} from '@google/genai'; + +const ai = new GoogleGenAI(); +``` + +## API Selection + +By default, the SDK uses the beta API endpoints provided by Google to support +preview features in the APIs. The stable API endpoints can be selected by +setting the API version to `v1`. + +To set the API version use `apiVersion`. For example, to set the API version to +`v1` for Vertex AI: + +```typescript +const ai = new GoogleGenAI({ + vertexai: true, + project: 'your_project', + location: 'your_location', + apiVersion: 'v1' +}); +``` + +To set the API version to `v1alpha` for the Gemini Developer API: + +```typescript +const ai = new GoogleGenAI({ + apiKey: 'GEMINI_API_KEY', + apiVersion: 'v1alpha' +}); +``` + +## GoogleGenAI overview + +All API features are accessed through an instance of the `GoogleGenAI` classes. +The submodules bundle together related API methods: + +- [`ai.models`](https://googleapis.github.io/js-genai/release_docs/classes/models.Models.html): + Use `models` to query models (`generateContent`, `generateImages`, ...), or + examine their metadata. +- [`ai.caches`](https://googleapis.github.io/js-genai/release_docs/classes/caches.Caches.html): + Create and manage `caches` to reduce costs when repeatedly using the same + large prompt prefix. +- [`ai.chats`](https://googleapis.github.io/js-genai/release_docs/classes/chats.Chats.html): + Create local stateful `chat` objects to simplify multi turn interactions. +- [`ai.files`](https://googleapis.github.io/js-genai/release_docs/classes/files.Files.html): + Upload `files` to the API and reference them in your prompts. + This reduces bandwidth if you use a file many times, and handles files too + large to fit inline with your prompt. +- [`ai.live`](https://googleapis.github.io/js-genai/release_docs/classes/live.Live.html): + Start a `live` session for real time interaction, allows text + audio + video + input, and text or audio output. + +## Samples + +More samples can be found in the +[github samples directory](https://github.com/googleapis/js-genai/tree/main/sdk-samples). + +### Streaming + +For quicker, more responsive API interactions use the `generateContentStream` +method which yields chunks as they're generated: + +```typescript +import {GoogleGenAI} from '@google/genai'; +const GEMINI_API_KEY = process.env.GEMINI_API_KEY; + +const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY}); + +async function main() { + const response = await ai.models.generateContentStream({ + model: 'gemini-2.0-flash-001', + contents: 'Write a 100-word poem.', + }); + for await (const chunk of response) { + console.log(chunk.text); + } +} + +main(); +``` + +### Function Calling + +To let Gemini to interact with external systems, you can provide +`functionDeclaration` objects as `tools`. To use these tools it's a 4 step + +1. **Declare the function name, description, and parametersJsonSchema** +2. **Call `generateContent` with function calling enabled** +3. **Use the returned `FunctionCall` parameters to call your actual function** +3. **Send the result back to the model (with history, easier in `ai.chat`) + as a `FunctionResponse`** + +```typescript +import {GoogleGenAI, FunctionCallingConfigMode, FunctionDeclaration, Type} from '@google/genai'; +const GEMINI_API_KEY = process.env.GEMINI_API_KEY; + +async function main() { + const controlLightDeclaration: FunctionDeclaration = { + name: 'controlLight', + parametersJsonSchema: { + type: 'object', + properties:{ + brightness: { + type:'number', + }, + colorTemperature: { + type:'string', + }, + }, + required: ['brightness', 'colorTemperature'], + }, + }; + + const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY}); + const response = await ai.models.generateContent({ + model: 'gemini-2.0-flash-001', + contents: 'Dim the lights so the room feels cozy and warm.', + config: { + toolConfig: { + functionCallingConfig: { + // Force it to call any function + mode: FunctionCallingConfigMode.ANY, + allowedFunctionNames: ['controlLight'], + } + }, + tools: [{functionDeclarations: [controlLightDeclaration]}] + } + }); + + console.log(response.functionCalls); +} + +main(); +``` + +#### Model Context Protocol (MCP) support (experimental) + +Built-in [MCP](https://modelcontextprotocol.io/introduction) support is an +experimental feature. You can pass a local MCP server as a tool directly. + +```javascript +import { GoogleGenAI, FunctionCallingConfigMode , mcpToTool} from '@google/genai'; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; + +// Create server parameters for stdio connection +const serverParams = new StdioClientTransport({ + command: "npx", // Executable + args: ["-y", "@philschmid/weather-mcp"] // MCP Server +}); + +const client = new Client( + { + name: "example-client", + version: "1.0.0" + } +); + +// Configure the client +const ai = new GoogleGenAI({}); + +// Initialize the connection between client and server +await client.connect(serverParams); + +// Send request to the model with MCP tools +const response = await ai.models.generateContent({ + model: "gemini-2.5-flash", + contents: `What is the weather in London in ${new Date().toLocaleDateString()}?`, + config: { + tools: [mcpToTool(client)], // uses the session, will automatically call the tool using automatic function calling + }, +}); +console.log(response.text); + +// Close the connection +await client.close(); +``` + +### Generate Content + +#### How to structure `contents` argument for `generateContent` + +The SDK allows you to specify the following types in the `contents` parameter: + +#### Content + +- `Content`: The SDK will wrap the singular `Content` instance in an array which +contains only the given content instance +- `Content[]`: No transformation happens + +#### Part + +Parts will be aggregated on a singular Content, with role 'user'. + +- `Part | string`: The SDK will wrap the `string` or `Part` in a `Content` +instance with role 'user'. +- `Part[] | string[]`: The SDK will wrap the full provided list into a single +`Content` with role 'user'. + +**_NOTE:_** This doesn't apply to `FunctionCall` and `FunctionResponse` parts, +if you are specifying those, you need to explicitly provide the full +`Content[]` structure making it explicit which Parts are 'spoken' by the model, +or the user. The SDK will throw an exception if you try this. + +## Error Handling + +To handle errors raised by the API, the SDK provides this [ApiError](https://github.com/googleapis/js-genai/blob/main/src/errors.ts) class. + +```typescript +import {GoogleGenAI} from '@google/genai'; +const GEMINI_API_KEY = process.env.GEMINI_API_KEY; + +const ai = new GoogleGenAI({apiKey: GEMINI_API_KEY}); + +async function main() { + await ai.models.generateContent({ + model: 'non-existent-model', + contents: 'Write a 100-word poem.', + }).catch((e) => { + console.error('error name: ', e.name); + console.error('error message: ', e.message); + console.error('error status: ', e.status); + }); +} + +main(); +``` + +## How is this different from the other Google AI SDKs +This SDK (`@google/genai`) is Google Deepmind’s "vanilla" SDK for its generative +AI offerings, and is where Google Deepmind adds new AI features. + +Models hosted either on the [Vertex AI platform](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/overview) or the [Gemini Developer platform](https://ai.google.dev/gemini-api/docs) are accessible through this SDK. + +Other SDKs may be offering additional AI frameworks on top of this SDK, or may +be targeting specific project environments (like Firebase). + +The `@google/generative_language` and `@google-cloud/vertexai` SDKs are previous +iterations of this SDK and are no longer receiving new Gemini 2.0+ features. + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/genai.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/genai.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..feb9a20d8c1c334a60a54c26ccb90a4d527e7a19 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/genai.d.ts @@ -0,0 +1,7701 @@ +// @ts-ignore +import type { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { GoogleAuthOptions } from 'google-auth-library'; + +/** Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface ActivityEnd { +} + +/** The different ways of handling user activity. */ +export declare enum ActivityHandling { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ACTIVITY_HANDLING_UNSPECIFIED = "ACTIVITY_HANDLING_UNSPECIFIED", + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + START_OF_ACTIVITY_INTERRUPTS = "START_OF_ACTIVITY_INTERRUPTS", + /** + * The model's response will not be interrupted. + */ + NO_INTERRUPTION = "NO_INTERRUPTION" +} + +/** Marks the start of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface ActivityStart { +} + +/** Optional. Adapter size for tuning. */ +export declare enum AdapterSize { + /** + * Adapter size is unspecified. + */ + ADAPTER_SIZE_UNSPECIFIED = "ADAPTER_SIZE_UNSPECIFIED", + /** + * Adapter size 1. + */ + ADAPTER_SIZE_ONE = "ADAPTER_SIZE_ONE", + /** + * Adapter size 2. + */ + ADAPTER_SIZE_TWO = "ADAPTER_SIZE_TWO", + /** + * Adapter size 4. + */ + ADAPTER_SIZE_FOUR = "ADAPTER_SIZE_FOUR", + /** + * Adapter size 8. + */ + ADAPTER_SIZE_EIGHT = "ADAPTER_SIZE_EIGHT", + /** + * Adapter size 16. + */ + ADAPTER_SIZE_SIXTEEN = "ADAPTER_SIZE_SIXTEEN", + /** + * Adapter size 32. + */ + ADAPTER_SIZE_THIRTY_TWO = "ADAPTER_SIZE_THIRTY_TWO" +} + +/** The generic reusable api auth config. Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto) instead. */ +export declare interface ApiAuth { + /** The API secret. */ + apiKeyConfig?: ApiAuthApiKeyConfig; +} + +/** The API secret. */ +export declare interface ApiAuthApiKeyConfig { + /** Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version} */ + apiKeySecretVersion?: string; + /** The API key string. Either this or `api_key_secret_version` must be set. */ + apiKeyString?: string; +} + +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +declare class ApiClient { + readonly clientOptions: ApiClientInitOptions; + constructor(opts: ApiClientInitOptions); + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + private baseUrlFromProjectLocation; + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + private normalizeAuthParameters; + isVertexAI(): boolean; + getProject(): string | undefined; + getLocation(): string | undefined; + getApiVersion(): string; + getBaseUrl(): string; + getRequestUrl(): string; + getHeaders(): Record; + private getRequestUrlInternal; + getBaseResourcePath(): string; + getApiKey(): string | undefined; + getWebsocketBaseUrl(): string; + setBaseUrl(url: string): void; + private constructUrl; + private shouldPrependVertexProjectPath; + request(request: HttpRequest): Promise; + private patchHttpOptions; + requestStream(request: HttpRequest): Promise>; + private includeExtraHttpOptionsToRequestInit; + private unaryApiCall; + private streamApiCall; + processStreamResponse(response: Response): AsyncGenerator; + private apiCall; + getDefaultHeaders(): Record; + private getHeadersInternal; + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + uploadFile(file: string | Blob, config?: UploadFileConfig): Promise; + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + downloadFile(params: DownloadFileParameters): Promise; + private fetchUploadUrl; +} + +/** + * Options for initializing the ApiClient. The ApiClient uses the parameters + * for authentication purposes as well as to infer if SDK should send the + * request to Vertex AI or Gemini API. + */ +declare interface ApiClientInitOptions { + /** + * The object used for adding authentication headers to API requests. + */ + auth: Auth; + /** + * The uploader to use for uploading files. This field is required for + * creating a client, will be set through the Node_client or Web_client. + */ + uploader: Uploader; + /** + * Optional. The downloader to use for downloading files. This field is + * required for creating a client, will be set through the Node_client or + * Web_client. + */ + downloader: Downloader; + /** + * Optional. The Google Cloud project ID for Vertex AI users. + * It is not the numeric project name. + * If not provided, SDK will try to resolve it from runtime environment. + */ + project?: string; + /** + * Optional. The Google Cloud project location for Vertex AI users. + * If not provided, SDK will try to resolve it from runtime environment. + */ + location?: string; + /** + * The API Key. This is required for Gemini API users. + */ + apiKey?: string; + /** + * Optional. Set to true if you intend to call Vertex AI endpoints. + * If unset, default SDK behavior is to call Gemini API. + */ + vertexai?: boolean; + /** + * Optional. The API version for the endpoint. + * If unset, SDK will choose a default api version. + */ + apiVersion?: string; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; + /** + * Optional. An extra string to append at the end of the User-Agent header. + * + * This can be used to e.g specify the runtime and its version. + */ + userAgentExtra?: string; +} + +/** + * API errors raised by the GenAI API. + */ +export declare class ApiError extends Error { + /** HTTP status code */ + status: number; + constructor(options: ApiErrorInfo); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Details for errors from calling the API. + */ +export declare interface ApiErrorInfo { + /** The error message. */ + message: string; + /** The HTTP status code. */ + status: number; +} + +/** Config for authentication with API key. */ +export declare interface ApiKeyConfig { + /** The API key to be used in the request directly. */ + apiKeyString?: string; +} + +/** The API spec that the external API implements. */ +export declare enum ApiSpec { + /** + * Unspecified API spec. This value should not be used. + */ + API_SPEC_UNSPECIFIED = "API_SPEC_UNSPECIFIED", + /** + * Simple search API spec. + */ + SIMPLE_SEARCH = "SIMPLE_SEARCH", + /** + * Elastic search API spec. + */ + ELASTIC_SEARCH = "ELASTIC_SEARCH" +} + +/** Representation of an audio chunk. */ +export declare interface AudioChunk { + /** Raw bytes of audio data. + * @remarks Encoded as base64 string. */ + data?: string; + /** MIME type of the audio chunk. */ + mimeType?: string; + /** Prompts and config used for generating this audio chunk. */ + sourceMetadata?: LiveMusicSourceMetadata; +} + +/** The audio transcription configuration in Setup. */ +export declare interface AudioTranscriptionConfig { +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * The Auth interface is used to authenticate with the API service. + */ +declare interface Auth { + /** + * Sets the headers needed to authenticate with the API service. + * + * @param headers - The Headers object that will be updated with the authentication headers. + */ + addAuthHeaders(headers: Headers): Promise; +} + +/** Auth configuration to run the extension. */ +export declare interface AuthConfig { + /** Config for API key auth. */ + apiKeyConfig?: ApiKeyConfig; + /** Type of auth scheme. */ + authType?: AuthType; + /** Config for Google Service Account auth. */ + googleServiceAccountConfig?: AuthConfigGoogleServiceAccountConfig; + /** Config for HTTP Basic auth. */ + httpBasicAuthConfig?: AuthConfigHttpBasicAuthConfig; + /** Config for user oauth. */ + oauthConfig?: AuthConfigOauthConfig; + /** Config for user OIDC auth. */ + oidcConfig?: AuthConfigOidcConfig; +} + +/** Config for Google Service Account Authentication. */ +export declare interface AuthConfigGoogleServiceAccountConfig { + /** Optional. The service account that the extension execution service runs as. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified service account. - If not specified, the Vertex AI Extension Service Agent will be used to execute the Extension. */ + serviceAccount?: string; +} + +/** Config for HTTP Basic Authentication. */ +export declare interface AuthConfigHttpBasicAuthConfig { + /** Required. The name of the SecretManager secret version resource storing the base64 encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource. */ + credentialSecret?: string; +} + +/** Config for user oauth. */ +export declare interface AuthConfigOauthConfig { + /** Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */ + accessToken?: string; + /** The service account used to generate access tokens for executing the Extension. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the provided service account. */ + serviceAccount?: string; +} + +/** Config for user OIDC auth. */ +export declare interface AuthConfigOidcConfig { + /** OpenID Connect formatted ID token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */ + idToken?: string; + /** The service account used to generate an OpenID Connect (OIDC)-compatible JWT token signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc). - The audience for the token will be set to the URL in the server url defined in the OpenApi spec. - If the service account is provided, the service account should grant `iam.serviceAccounts.getOpenIdToken` permission to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents). */ + serviceAccount?: string; +} + +/** Config for auth_tokens.create parameters. */ +export declare interface AuthToken { + /** The name of the auth token. */ + name?: string; +} + +/** Type of auth scheme. */ +export declare enum AuthType { + AUTH_TYPE_UNSPECIFIED = "AUTH_TYPE_UNSPECIFIED", + /** + * No Auth. + */ + NO_AUTH = "NO_AUTH", + /** + * API Key Auth. + */ + API_KEY_AUTH = "API_KEY_AUTH", + /** + * HTTP Basic Auth. + */ + HTTP_BASIC_AUTH = "HTTP_BASIC_AUTH", + /** + * Google Service Account Auth. + */ + GOOGLE_SERVICE_ACCOUNT_AUTH = "GOOGLE_SERVICE_ACCOUNT_AUTH", + /** + * OAuth auth. + */ + OAUTH = "OAUTH", + /** + * OpenID Connect (OIDC) Auth. + */ + OIDC_AUTH = "OIDC_AUTH" +} + +/** Configures automatic detection of activity. */ +export declare interface AutomaticActivityDetection { + /** If enabled, detected voice and text input count as activity. If disabled, the client must send activity signals. */ + disabled?: boolean; + /** Determines how likely speech is to be detected. */ + startOfSpeechSensitivity?: StartSensitivity; + /** Determines how likely detected speech is ended. */ + endOfSpeechSensitivity?: EndSensitivity; + /** The required duration of detected speech before start-of-speech is committed. The lower this value the more sensitive the start-of-speech detection is and the shorter speech can be recognized. However, this also increases the probability of false positives. */ + prefixPaddingMs?: number; + /** The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency. */ + silenceDurationMs?: number; +} + +/** The configuration for automatic function calling. */ +export declare interface AutomaticFunctionCallingConfig { + /** Whether to disable automatic function calling. + If not set or set to False, will enable automatic function calling. + If set to True, will disable automatic function calling. + */ + disable?: boolean; + /** If automatic function calling is enabled, + maximum number of remote calls for automatic function calling. + This number should be a positive integer. + If not set, SDK will set maximum number of remote calls to 10. + */ + maximumRemoteCalls?: number; + /** If automatic function calling is enabled, + whether to ignore call history to the response. + If not set, SDK will set ignore_call_history to false, + and will append the call history to + GenerateContentResponse.automatic_function_calling_history. + */ + ignoreCallHistory?: boolean; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +declare class BaseModule { +} + +/** + * Parameters for setting the base URLs for the Gemini API and Vertex AI API. + */ +export declare interface BaseUrlParameters { + geminiUrl?: string; + vertexUrl?: string; +} + +export declare class Batches extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + create: (params: types.CreateBatchJobParameters) => Promise; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + list: (params?: types.ListBatchJobsParameters) => Promise>; + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + private createInternal; + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + get(params: types.GetBatchJobParameters): Promise; + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + cancel(params: types.CancelBatchJobParameters): Promise; + private listInternal; + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + delete(params: types.DeleteBatchJobParameters): Promise; +} + +/** Config for batches.create return value. */ +export declare interface BatchJob { + /** The resource name of the BatchJob. Output only.". + */ + name?: string; + /** The display name of the BatchJob. + */ + displayName?: string; + /** The state of the BatchJob. + */ + state?: JobState; + /** Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED. */ + error?: JobError; + /** The time when the BatchJob was created. + */ + createTime?: string; + /** Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state. */ + startTime?: string; + /** The time when the BatchJob was completed. + */ + endTime?: string; + /** The time when the BatchJob was last updated. + */ + updateTime?: string; + /** The name of the model that produces the predictions via the BatchJob. + */ + model?: string; + /** Configuration for the input data. + */ + src?: BatchJobSource; + /** Configuration for the output data. + */ + dest?: BatchJobDestination; +} + +/** Config for `des` parameter. */ +export declare interface BatchJobDestination { + /** Storage format of the output files. Must be one of: + 'jsonl', 'bigquery'. + */ + format?: string; + /** The Google Cloud Storage URI to the output file. + */ + gcsUri?: string; + /** The BigQuery URI to the output table. + */ + bigqueryUri?: string; + /** The Gemini Developer API's file resource name of the output data + (e.g. "files/12345"). The file will be a JSONL file with a single response + per line. The responses will be GenerateContentResponse messages formatted + as JSON. The responses will be written in the same order as the input + requests. + */ + fileName?: string; + /** The responses to the requests in the batch. Returned when the batch was + built using inlined requests. The responses will be in the same order as + the input requests. + */ + inlinedResponses?: InlinedResponse[]; +} + +export declare type BatchJobDestinationUnion = BatchJobDestination | string; + +/** Config for `src` parameter. */ +export declare interface BatchJobSource { + /** Storage format of the input files. Must be one of: + 'jsonl', 'bigquery'. + */ + format?: string; + /** The Google Cloud Storage URIs to input files. + */ + gcsUri?: string[]; + /** The BigQuery URI to input table. + */ + bigqueryUri?: string; + /** The Gemini Developer API's file resource name of the input data + (e.g. "files/12345"). + */ + fileName?: string; + /** The Gemini Developer API's inlined input data to run batch job. + */ + inlinedRequests?: InlinedRequest[]; +} + +export declare type BatchJobSourceUnion = BatchJobSource | InlinedRequest[] | string; + +/** Defines the function behavior. Defaults to `BLOCKING`. */ +export declare enum Behavior { + /** + * This value is unused. + */ + UNSPECIFIED = "UNSPECIFIED", + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + BLOCKING = "BLOCKING", + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + NON_BLOCKING = "NON_BLOCKING" +} + +/** Content blob. */ +declare interface Blob_2 { + /** Optional. Display name of the blob. Used to provide a label or filename to distinguish blobs. This field is not currently used in the Gemini GenerateContent calls. */ + displayName?: string; + /** Required. Raw bytes. + * @remarks Encoded as base64 string. */ + data?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} +export { Blob_2 as Blob } + +export declare type BlobImageUnion = Blob_2; + +/** Output only. Blocked reason. */ +export declare enum BlockedReason { + /** + * Unspecified blocked reason. + */ + BLOCKED_REASON_UNSPECIFIED = "BLOCKED_REASON_UNSPECIFIED", + /** + * Candidates blocked due to safety. + */ + SAFETY = "SAFETY", + /** + * Candidates blocked due to other reason. + */ + OTHER = "OTHER", + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BLOCKLIST = "BLOCKLIST", + /** + * Candidates blocked due to prohibited content. + */ + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + /** + * Candidates blocked due to unsafe image generation content. + */ + IMAGE_SAFETY = "IMAGE_SAFETY" +} + +/** A resource used in LLM queries for users to explicitly specify what to cache. */ +export declare interface CachedContent { + /** The server-generated resource name of the cached content. */ + name?: string; + /** The user-generated meaningful display name of the cached content. */ + displayName?: string; + /** The name of the publisher model to use for cached content. */ + model?: string; + /** Creation time of the cache entry. */ + createTime?: string; + /** When the cache entry was last updated in UTC time. */ + updateTime?: string; + /** Expiration time of the cached content. */ + expireTime?: string; + /** Metadata on the usage of the cached content. */ + usageMetadata?: CachedContentUsageMetadata; +} + +/** Metadata on the usage of the cached content. */ +export declare interface CachedContentUsageMetadata { + /** Duration of audio in seconds. */ + audioDurationSeconds?: number; + /** Number of images. */ + imageCount?: number; + /** Number of text characters. */ + textCount?: number; + /** Total number of tokens that the cached content consumes. */ + totalTokenCount?: number; + /** Duration of video in seconds. */ + videoDurationSeconds?: number; +} + +export declare class Caches extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + list: (params?: types.ListCachedContentsParameters) => Promise>; + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + create(params: types.CreateCachedContentParameters): Promise; + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + get(params: types.GetCachedContentParameters): Promise; + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + delete(params: types.DeleteCachedContentParameters): Promise; + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + update(params: types.UpdateCachedContentParameters): Promise; + private listInternal; +} + +/** + * CallableTool is an invokable tool that can be executed with external + * application (e.g., via Model Context Protocol) or local functions with + * function calling. + */ +export declare interface CallableTool { + /** + * Returns tool that can be called by Gemini. + */ + tool(): Promise; + /** + * Executes the callable tool with the given function call arguments and + * returns the response parts from the tool execution. + */ + callTool(functionCalls: FunctionCall[]): Promise; +} + +/** + * CallableToolConfig is the configuration for a callable tool. + */ +export declare interface CallableToolConfig { + /** + * Specifies the model's behavior after invoking this tool. + */ + behavior?: Behavior; + /** + * Timeout for remote calls in milliseconds. Note this timeout applies only to + * tool remote calls, and not making HTTP requests to the API. */ + timeout?: number; +} + +/** Optional parameters. */ +export declare interface CancelBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.cancel parameters. */ +export declare interface CancelBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: CancelBatchJobConfig; +} + +/** A response candidate generated from the model. */ +export declare interface Candidate { + /** Contains the multi-part content of the response. + */ + content?: Content; + /** Source attribution of the generated content. + */ + citationMetadata?: CitationMetadata; + /** Describes the reason the model stopped generating tokens. + */ + finishMessage?: string; + /** Number of tokens for this candidate. + */ + tokenCount?: number; + /** The reason why the model stopped generating tokens. + If empty, the model has not stopped generating the tokens. + */ + finishReason?: FinishReason; + /** Metadata related to url context retrieval tool. */ + urlContextMetadata?: UrlContextMetadata; + /** Output only. Average log probability score of the candidate. */ + avgLogprobs?: number; + /** Output only. Metadata specifies sources used to ground generated content. */ + groundingMetadata?: GroundingMetadata; + /** Output only. Index of the candidate. */ + index?: number; + /** Output only. Log-likelihood scores for the response tokens and top tokens */ + logprobsResult?: LogprobsResult; + /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */ + safetyRatings?: SafetyRating[]; +} + +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +export declare class Chat { + private readonly apiClient; + private readonly modelsModule; + private readonly model; + private readonly config; + private history; + private sendPromise; + constructor(apiClient: ApiClient, modelsModule: Models, model: string, config?: types.GenerateContentConfig, history?: types.Content[]); + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + sendMessage(params: types.SendMessageParameters): Promise; + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + sendMessageStream(params: types.SendMessageParameters): Promise>; + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated?: boolean): types.Content[]; + private processStreamResponse; + private recordHistory; +} + +/** + * A utility class to create a chat session. + */ +export declare class Chats { + private readonly modelsModule; + private readonly apiClient; + constructor(modelsModule: Models, apiClient: ApiClient); + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params: types.CreateChatParameters): Chat; +} + +/** Describes the machine learning model version checkpoint. */ +export declare interface Checkpoint { + /** The ID of the checkpoint. + */ + checkpointId?: string; + /** The epoch of the checkpoint. + */ + epoch?: string; + /** The step of the checkpoint. + */ + step?: string; +} + +/** Source attributions for content. */ +export declare interface Citation { + /** Output only. End index into the content. */ + endIndex?: number; + /** Output only. License of the attribution. */ + license?: string; + /** Output only. Publication date of the attribution. */ + publicationDate?: GoogleTypeDate; + /** Output only. Start index into the content. */ + startIndex?: number; + /** Output only. Title of the attribution. */ + title?: string; + /** Output only. Url reference of the attribution. */ + uri?: string; +} + +/** Citation information when the model quotes another source. */ +export declare interface CitationMetadata { + /** Contains citation information when the model directly quotes, at + length, from another source. Can include traditional websites and code + repositories. + */ + citations?: Citation[]; +} + +/** Result of executing the [ExecutableCode]. Only generated when using the [CodeExecution] tool, and always follows a `part` containing the [ExecutableCode]. */ +export declare interface CodeExecutionResult { + /** Required. Outcome of the code execution. */ + outcome?: Outcome; + /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */ + output?: string; +} + +/** Optional parameters for computing tokens. */ +export declare interface ComputeTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for computing tokens. */ +export declare interface ComputeTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Optional parameters for the request. + */ + config?: ComputeTokensConfig; +} + +/** Response for computing tokens. */ +export declare class ComputeTokensResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */ + tokensInfo?: TokensInfo[]; +} + +/** Contains the multi-part content of a message. */ +export declare interface Content { + /** List of parts that constitute a single message. Each part may have + a different IANA MIME type. */ + parts?: Part[]; + /** Optional. The producer of the content. Must be either 'user' or + 'model'. Useful to set for multi-turn conversations, otherwise can be + empty. If role is not specified, SDK will determine the role. */ + role?: string; +} + +/** The embedding generated from an input content. */ +export declare interface ContentEmbedding { + /** A list of floats representing an embedding. + */ + values?: number[]; + /** Vertex API only. Statistics of the input text associated with this + embedding. + */ + statistics?: ContentEmbeddingStatistics; +} + +/** Statistics of the input text associated with the result of content embedding. */ +export declare interface ContentEmbeddingStatistics { + /** Vertex API only. If the input text was truncated due to having + a length longer than the allowed maximum input. + */ + truncated?: boolean; + /** Vertex API only. Number of tokens of the input text. + */ + tokenCount?: number; +} + +export declare type ContentListUnion = Content | Content[] | PartUnion | PartUnion[]; + +export declare type ContentUnion = Content | PartUnion[] | PartUnion; + +/** Enables context window compression -- mechanism managing model context window so it does not exceed given length. */ +export declare interface ContextWindowCompressionConfig { + /** Number of tokens (before running turn) that triggers context window compression mechanism. */ + triggerTokens?: string; + /** Sliding window compression mechanism. */ + slidingWindow?: SlidingWindow; +} + +/** Configuration for a Control reference image. */ +export declare interface ControlReferenceConfig { + /** The type of control reference image to use. */ + controlType?: ControlReferenceType; + /** Defaults to False. When set to True, the control image will be + computed by the model based on the control type. When set to False, + the control image must be provided by the user. */ + enableControlImageComputation?: boolean; +} + +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +export declare class ControlReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the control reference image. */ + config?: ControlReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the control type of a control reference image. */ +export declare enum ControlReferenceType { + CONTROL_TYPE_DEFAULT = "CONTROL_TYPE_DEFAULT", + CONTROL_TYPE_CANNY = "CONTROL_TYPE_CANNY", + CONTROL_TYPE_SCRIBBLE = "CONTROL_TYPE_SCRIBBLE", + CONTROL_TYPE_FACE_MESH = "CONTROL_TYPE_FACE_MESH" +} + +/** Config for the count_tokens method. */ +export declare interface CountTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Instructions for the model to steer it toward better performance. + */ + systemInstruction?: ContentUnion; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: Tool[]; + /** Configuration that the model uses to generate the response. Not + supported by the Gemini Developer API. + */ + generationConfig?: GenerationConfig; +} + +/** Parameters for counting tokens. */ +export declare interface CountTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Configuration for counting tokens. */ + config?: CountTokensConfig; +} + +/** Response for counting tokens. */ +export declare class CountTokensResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Total number of tokens. */ + totalTokens?: number; + /** Number of tokens in the cached part of the prompt (the cached content). */ + cachedContentTokenCount?: number; +} + +/** Optional parameters. */ +export declare interface CreateAuthTokenConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** An optional time after which, when using the resulting token, + messages in Live API sessions will be rejected. (Gemini may + preemptively close the session after this time.) + + If not set then this defaults to 30 minutes in the future. If set, this + value must be less than 20 hours in the future. */ + expireTime?: string; + /** The time after which new Live API sessions using the token + resulting from this request will be rejected. + + If not set this defaults to 60 seconds in the future. If set, this value + must be less than 20 hours in the future. */ + newSessionExpireTime?: string; + /** The number of times the token can be used. If this value is zero + then no limit is applied. Default is 1. Resuming a Live API session does + not count as a use. */ + uses?: number; + /** Configuration specific to Live API connections created using this token. */ + liveConnectConstraints?: LiveConnectConstraints; + /** Additional fields to lock in the effective LiveConnectParameters. */ + lockAdditionalFields?: string[]; +} + +/** Config for auth_tokens.create parameters. */ +export declare interface CreateAuthTokenParameters { + /** Optional parameters for the request. */ + config?: CreateAuthTokenConfig; +} + +/** Config for optional parameters. */ +export declare interface CreateBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The user-defined name of this BatchJob. + */ + displayName?: string; + /** GCS or BigQuery URI prefix for the output predictions. Example: + "gs://path/to/output/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + dest?: BatchJobDestinationUnion; +} + +/** Config for batches.create parameters. */ +export declare interface CreateBatchJobParameters { + /** The name of the model to produces the predictions via the BatchJob. + */ + model?: string; + /** GCS URI(-s) or BigQuery URI to your input data to run batch job. + Example: "gs://path/to/input/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + src: BatchJobSourceUnion; + /** Optional parameters for creating a BatchJob. + */ + config?: CreateBatchJobConfig; +} + +/** Optional configuration for cached content creation. */ +export declare interface CreateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; + /** The user-generated meaningful display name of the cached content. + */ + displayName?: string; + /** The content to cache. + */ + contents?: ContentListUnion; + /** Developer set system instruction. + */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + */ + tools?: Tool[]; + /** Configuration for the tools to use. This config is shared for all tools. + */ + toolConfig?: ToolConfig; + /** The Cloud KMS resource identifier of the customer managed + encryption key used to protect a resource. + The key needs to be in the same region as where the compute resource is + created. See + https://cloud.google.com/vertex-ai/docs/general/cmek for more + details. If this is set, then all created CachedContent objects + will be encrypted with the provided encryption key. + Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key} + */ + kmsKeyName?: string; +} + +/** Parameters for caches.create method. */ +export declare interface CreateCachedContentParameters { + /** ID of the model to use. Example: gemini-2.0-flash */ + model: string; + /** Configuration that contains optional parameters. + */ + config?: CreateCachedContentConfig; +} + +/** Parameters for initializing a new chat session. + + These parameters are used when creating a chat session with the + `chats.create()` method. + */ +export declare interface CreateChatParameters { + /** The name of the model to use for the chat session. + + For example: 'gemini-2.0-flash', 'gemini-2.0-flash-lite', etc. See Gemini API + docs to find the available models. + */ + model: string; + /** Config for the entire chat session. + + This config applies to all requests within the session + unless overridden by a per-request `config` in `SendMessageParameters`. + */ + config?: GenerateContentConfig; + /** The initial conversation history for the chat session. + + This allows you to start the chat with a pre-existing history. The history + must be a list of `Content` alternating between 'user' and 'model' roles. + It should start with a 'user' message. + */ + history?: Content[]; +} + +/** Used to override the default configuration. */ +export declare interface CreateFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the private _create method. */ +export declare interface CreateFileParameters { + /** The file to be uploaded. + mime_type: (Required) The MIME type of the file. Must be provided. + name: (Optional) The name of the file in the destination (e.g. + 'files/sample-image'). + display_name: (Optional) The display name of the file. + */ + file: File_2; + /** Used to override the default configuration. */ + config?: CreateFileConfig; +} + +/** Response for the create file method. */ +export declare class CreateFileResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; +} + +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +export declare function createModelContent(partOrString: PartListUnion | string): Content; + +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +export declare function createPartFromBase64(data: string, mimeType: string): Part; + +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +export declare function createPartFromCodeExecutionResult(outcome: Outcome, output: string): Part; + +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +export declare function createPartFromExecutableCode(code: string, language: Language): Part; + +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +export declare function createPartFromFunctionCall(name: string, args: Record): Part; + +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +export declare function createPartFromFunctionResponse(id: string, name: string, response: Record): Part; + +/** + * Creates a `Part` object from a `text` string. + */ +export declare function createPartFromText(text: string): Part; + +/** + * Creates a `Part` object from a `URI` string. + */ +export declare function createPartFromUri(uri: string, mimeType: string): Part; + +/** Supervised fine-tuning job creation request - optional fields. */ +export declare interface CreateTuningJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + validationDataset?: TuningValidationDataset; + /** The display name of the tuned Model. The name can be up to 128 characters long and can consist of any UTF-8 characters. */ + tunedModelDisplayName?: string; + /** The description of the TuningJob */ + description?: string; + /** Number of complete passes the model makes over the entire training dataset during training. */ + epochCount?: number; + /** Multiplier for adjusting the default learning rate. */ + learningRateMultiplier?: number; + /** If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. */ + exportLastCheckpointOnly?: boolean; + /** The optional checkpoint id of the pre-tuned model to use for tuning, if applicable. */ + preTunedModelCheckpointId?: string; + /** Adapter size for tuning. */ + adapterSize?: AdapterSize; + /** The batch size hyperparameter for tuning. If not set, a default of 4 or 16 will be used based on the number of training examples. */ + batchSize?: number; + /** The learning rate hyperparameter for tuning. If not set, a default of 0.001 or 0.0002 will be calculated based on the number of training examples. */ + learningRate?: number; +} + +/** Supervised fine-tuning job creation parameters - optional fields. */ +export declare interface CreateTuningJobParameters { + /** The base model that is being tuned, e.g., "gemini-2.5-flash". */ + baseModel: string; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDataset: TuningDataset; + /** Configuration for the tuning job. */ + config?: CreateTuningJobConfig; +} + +/** Supervised fine-tuning job creation parameters - optional fields. */ +export declare interface CreateTuningJobParametersPrivate { + /** The base model that is being tuned, e.g., "gemini-2.5-flash". */ + baseModel?: string; + /** The PreTunedModel that is being tuned. */ + preTunedModel?: PreTunedModel; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDataset: TuningDataset; + /** Configuration for the tuning job. */ + config?: CreateTuningJobConfig; +} + +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +export declare function createUserContent(partOrString: PartListUnion | string): Content; + +/** Distribution computed over a tuning dataset. */ +export declare interface DatasetDistribution { + /** Output only. Defines the histogram bucket. */ + buckets?: DatasetDistributionDistributionBucket[]; + /** Output only. The maximum of the population values. */ + max?: number; + /** Output only. The arithmetic mean of the values in the population. */ + mean?: number; + /** Output only. The median of the values in the population. */ + median?: number; + /** Output only. The minimum of the population values. */ + min?: number; + /** Output only. The 5th percentile of the values in the population. */ + p5?: number; + /** Output only. The 95th percentile of the values in the population. */ + p95?: number; + /** Output only. Sum of a given population of values. */ + sum?: number; +} + +/** Dataset bucket used to create a histogram for the distribution given a population of values. */ +export declare interface DatasetDistributionDistributionBucket { + /** Output only. Number of values in the bucket. */ + count?: string; + /** Output only. Left bound of the bucket. */ + left?: number; + /** Output only. Right bound of the bucket. */ + right?: number; +} + +/** Statistics computed over a tuning dataset. */ +export declare interface DatasetStats { + /** Output only. Number of billable characters in the tuning dataset. */ + totalBillableCharacterCount?: string; + /** Output only. Number of tuning characters in the tuning dataset. */ + totalTuningCharacterCount?: string; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user messages in the training dataset uri. */ + userDatasetExamples?: Content[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the messages per example. */ + userMessagePerExampleDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: DatasetDistribution; +} + +/** Optional parameters for models.get method. */ +export declare interface DeleteBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.delete parameters. */ +export declare interface DeleteBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: DeleteBatchJobConfig; +} + +/** Optional parameters for caches.delete method. */ +export declare interface DeleteCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for caches.delete method. */ +export declare interface DeleteCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: DeleteCachedContentConfig; +} + +/** Empty response for caches.delete method. */ +export declare class DeleteCachedContentResponse { +} + +/** Used to override the default configuration. */ +export declare interface DeleteFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the get method. */ +export declare interface DeleteFileParameters { + /** The name identifier for the file to be deleted. */ + name: string; + /** Used to override the default configuration. */ + config?: DeleteFileConfig; +} + +/** Response for the delete file method. */ +export declare class DeleteFileResponse { +} + +/** Configuration for deleting a tuned model. */ +export declare interface DeleteModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for deleting a tuned model. */ +export declare interface DeleteModelParameters { + model: string; + /** Optional parameters for the request. */ + config?: DeleteModelConfig; +} + +export declare class DeleteModelResponse { +} + +/** The return value of delete operation. */ +export declare interface DeleteResourceJob { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + name?: string; + done?: boolean; + error?: JobError; +} + +/** Statistics computed for datasets used for distillation. */ +export declare interface DistillationDataStats { + /** Output only. Statistics computed for the training dataset. */ + trainingDatasetStats?: DatasetStats; +} + +export declare type DownloadableFileUnion = string | File_2 | GeneratedVideo | Video; + +declare interface Downloader { + /** + * Downloads a file to the given location. + * + * @param params The parameters for downloading the file. + * @param apiClient The ApiClient to use for uploading. + * @return A Promises that resolves when the download is complete. + */ + download(params: DownloadFileParameters, apiClient: ApiClient): Promise; +} + +/** Used to override the default configuration. */ +export declare interface DownloadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters used to download a file. */ +export declare interface DownloadFileParameters { + /** The file to download. It can be a file name, a file object or a generated video. */ + file: DownloadableFileUnion; + /** Location where the file should be downloaded to. */ + downloadPath: string; + /** Configuration to for the download operation. */ + config?: DownloadFileConfig; +} + +/** Describes the options to customize dynamic retrieval. */ +export declare interface DynamicRetrievalConfig { + /** The mode of the predictor to be used in dynamic retrieval. */ + mode?: DynamicRetrievalConfigMode; + /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */ + dynamicThreshold?: number; +} + +/** Config for the dynamic retrieval config mode. */ +export declare enum DynamicRetrievalConfigMode { + /** + * Always trigger retrieval. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Run retrieval only when system decides it is necessary. + */ + MODE_DYNAMIC = "MODE_DYNAMIC" +} + +/** Configuration for editing an image. */ +export declare interface EditImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage URI used to store the generated images. + */ + outputGcsUri?: string; + /** Description of what to discourage in the generated images. + */ + negativePrompt?: string; + /** Number of images to generate. + */ + numberOfImages?: number; + /** Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9". + */ + aspectRatio?: string; + /** Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality. + */ + guidanceScale?: number; + /** Random seed for image generation. This is not available when + ``add_watermark`` is set to true. + */ + seed?: number; + /** Filter level for safety filtering. + */ + safetyFilterLevel?: SafetyFilterLevel; + /** Allows generation of people by the model. + */ + personGeneration?: PersonGeneration; + /** Whether to report the safety scores of each generated image and + the positive prompt in the response. + */ + includeSafetyAttributes?: boolean; + /** Whether to include the Responsible AI filter reason if the image + is filtered out of the response. + */ + includeRaiReason?: boolean; + /** Language of the text in the prompt. + */ + language?: ImagePromptLanguage; + /** MIME type of the generated image. + */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). + */ + outputCompressionQuality?: number; + /** Whether to add a watermark to the generated images. + */ + addWatermark?: boolean; + /** Describes the editing mode for the request. */ + editMode?: EditMode; + /** The number of sampling steps. A higher value has better image + quality, while a lower value has better latency. */ + baseSteps?: number; +} + +/** Parameters for the request to edit an image. */ +export declare interface EditImageParameters { + /** The model to use. */ + model: string; + /** A text description of the edit to apply to the image. */ + prompt: string; + /** The reference images for Imagen 3 editing. */ + referenceImages: ReferenceImage[]; + /** Configuration for editing. */ + config?: EditImageConfig; +} + +/** Response for the request to edit an image. */ +export declare class EditImageResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** Enum representing the Imagen 3 Edit mode. */ +export declare enum EditMode { + EDIT_MODE_DEFAULT = "EDIT_MODE_DEFAULT", + EDIT_MODE_INPAINT_REMOVAL = "EDIT_MODE_INPAINT_REMOVAL", + EDIT_MODE_INPAINT_INSERTION = "EDIT_MODE_INPAINT_INSERTION", + EDIT_MODE_OUTPAINT = "EDIT_MODE_OUTPAINT", + EDIT_MODE_CONTROLLED_EDITING = "EDIT_MODE_CONTROLLED_EDITING", + EDIT_MODE_STYLE = "EDIT_MODE_STYLE", + EDIT_MODE_BGSWAP = "EDIT_MODE_BGSWAP", + EDIT_MODE_PRODUCT_IMAGE = "EDIT_MODE_PRODUCT_IMAGE" +} + +/** Optional parameters for the embed_content method. */ +export declare interface EmbedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Type of task for which the embedding will be used. + */ + taskType?: string; + /** Title for the text. Only applicable when TaskType is + `RETRIEVAL_DOCUMENT`. + */ + title?: string; + /** Reduced dimension for the output embedding. If set, + excessive values in the output embedding are truncated from the end. + Supported by newer models since 2024 only. You cannot set this value if + using the earlier model (`models/embedding-001`). + */ + outputDimensionality?: number; + /** Vertex API only. The MIME type of the input. + */ + mimeType?: string; + /** Vertex API only. Whether to silently truncate inputs longer than + the max sequence length. If this option is set to false, oversized inputs + will lead to an INVALID_ARGUMENT error, similar to other text APIs. + */ + autoTruncate?: boolean; +} + +/** Request-level metadata for the Vertex Embed Content API. */ +export declare interface EmbedContentMetadata { + /** Vertex API only. The total number of billable characters included + in the request. + */ + billableCharacterCount?: number; +} + +/** Parameters for the embed_content method. */ +export declare interface EmbedContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The content to embed. Only the `parts.text` fields will be counted. + */ + contents: ContentListUnion; + /** Configuration that contains optional parameters. + */ + config?: EmbedContentConfig; +} + +/** Response for the embed_content method. */ +export declare class EmbedContentResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** The embeddings for each request, in the same order as provided in + the batch request. + */ + embeddings?: ContentEmbedding[]; + /** Vertex API only. Metadata about the request. + */ + metadata?: EmbedContentMetadata; +} + +/** Represents a customer-managed encryption key spec that can be applied to a top-level resource. */ +export declare interface EncryptionSpec { + /** Required. The Cloud KMS resource identifier of the customer managed encryption key used to protect a resource. Has the form: `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`. The key needs to be in the same region as where the compute resource is created. */ + kmsKeyName?: string; +} + +/** An endpoint where you deploy models. */ +export declare interface Endpoint { + /** Resource name of the endpoint. */ + name?: string; + /** ID of the model that's deployed to the endpoint. */ + deployedModelId?: string; +} + +/** End of speech sensitivity. */ +export declare enum EndSensitivity { + /** + * The default is END_SENSITIVITY_LOW. + */ + END_SENSITIVITY_UNSPECIFIED = "END_SENSITIVITY_UNSPECIFIED", + /** + * Automatic detection ends speech more often. + */ + END_SENSITIVITY_HIGH = "END_SENSITIVITY_HIGH", + /** + * Automatic detection ends speech less often. + */ + END_SENSITIVITY_LOW = "END_SENSITIVITY_LOW" +} + +/** Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. */ +export declare interface EnterpriseWebSearch { + /** Optional. List of domains to be excluded from the search results. The default limit is 2000 domains. */ + excludeDomains?: string[]; +} + +/** An entity representing the segmented area. */ +export declare interface EntityLabel { + /** The label of the segmented entity. */ + label?: string; + /** The confidence score of the detected label. */ + score?: number; +} + +/** The environment being operated. */ +export declare enum Environment { + /** + * Defaults to browser. + */ + ENVIRONMENT_UNSPECIFIED = "ENVIRONMENT_UNSPECIFIED", + /** + * Operates in a web browser. + */ + ENVIRONMENT_BROWSER = "ENVIRONMENT_BROWSER" +} + +/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [CodeExecution] tool, in which the code will be automatically executed, and a corresponding [CodeExecutionResult] will also be generated. */ +export declare interface ExecutableCode { + /** Required. The code to be executed. */ + code?: string; + /** Required. Programming language of the `code`. */ + language?: Language; +} + +/** Retrieve from data source powered by external API for grounding. The external API is not owned by Google, but need to follow the pre-defined API spec. */ +export declare interface ExternalApi { + /** The authentication config to access the API. Deprecated. Please use auth_config instead. */ + apiAuth?: ApiAuth; + /** The API spec that the external API implements. */ + apiSpec?: ApiSpec; + /** The authentication config to access the API. */ + authConfig?: AuthConfig; + /** Parameters for the elastic search API. */ + elasticSearchParams?: ExternalApiElasticSearchParams; + /** The endpoint of the external API. The system will call the API at this endpoint to retrieve the data for grounding. Example: https://acme.com:443/search */ + endpoint?: string; + /** Parameters for the simple search API. */ + simpleSearchParams?: ExternalApiSimpleSearchParams; +} + +/** The search parameters to use for the ELASTIC_SEARCH spec. */ +export declare interface ExternalApiElasticSearchParams { + /** The ElasticSearch index to use. */ + index?: string; + /** Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as the `num_hits` param. */ + numHits?: number; + /** The ElasticSearch search template to use. */ + searchTemplate?: string; +} + +/** The search parameters to use for SIMPLE_SEARCH spec. */ +export declare interface ExternalApiSimpleSearchParams { +} + +/** Options for feature selection preference. */ +export declare enum FeatureSelectionPreference { + FEATURE_SELECTION_PREFERENCE_UNSPECIFIED = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED", + PRIORITIZE_QUALITY = "PRIORITIZE_QUALITY", + BALANCED = "BALANCED", + PRIORITIZE_COST = "PRIORITIZE_COST" +} + +export declare interface FetchPredictOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the fetchPredictOperation method. */ +export declare interface FetchPredictOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + resourceName: string; + /** Used to override the default configuration. */ + config?: FetchPredictOperationConfig; +} + +/** A file uploaded to the API. */ +declare interface File_2 { + /** The `File` resource name. The ID (name excluding the "files/" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */ + name?: string; + /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */ + displayName?: string; + /** Output only. MIME type of the file. */ + mimeType?: string; + /** Output only. Size of the file in bytes. */ + sizeBytes?: string; + /** Output only. The timestamp of when the `File` was created. */ + createTime?: string; + /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */ + expirationTime?: string; + /** Output only. The timestamp of when the `File` was last updated. */ + updateTime?: string; + /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */ + sha256Hash?: string; + /** Output only. The URI of the `File`. */ + uri?: string; + /** Output only. The URI of the `File`, only set for downloadable (generated) files. */ + downloadUri?: string; + /** Output only. Processing state of the File. */ + state?: FileState; + /** Output only. The source of the `File`. */ + source?: FileSource; + /** Output only. Metadata for a video. */ + videoMetadata?: Record; + /** Output only. Error status if File processing failed. */ + error?: FileStatus; +} +export { File_2 as File } + +/** URI based data. */ +export declare interface FileData { + /** Optional. Display name of the file data. Used to provide a label or filename to distinguish file datas. It is not currently used in the Gemini GenerateContent calls. */ + displayName?: string; + /** Required. URI. */ + fileUri?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} + +export declare class Files extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + list: (params?: types.ListFilesParameters) => Promise>; + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + upload(params: types.UploadFileParameters): Promise; + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + download(params: types.DownloadFileParameters): Promise; + private listInternal; + private createInternal; + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + get(params: types.GetFileParameters): Promise; + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + delete(params: types.DeleteFileParameters): Promise; +} + +/** Source of the File. */ +export declare enum FileSource { + SOURCE_UNSPECIFIED = "SOURCE_UNSPECIFIED", + UPLOADED = "UPLOADED", + GENERATED = "GENERATED" +} + +/** + * Represents the size and mimeType of a file. The information is used to + * request the upload URL from the https://generativelanguage.googleapis.com/upload/v1beta/files endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface FileStat { + /** + * The size of the file in bytes. + */ + size: number; + /** + * The MIME type of the file. + */ + type: string | undefined; +} + +/** State for the lifecycle of a File. */ +export declare enum FileState { + STATE_UNSPECIFIED = "STATE_UNSPECIFIED", + PROCESSING = "PROCESSING", + ACTIVE = "ACTIVE", + FAILED = "FAILED" +} + +/** Status of a File that uses a common error model. */ +export declare interface FileStatus { + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: Record[]; + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + message?: string; + /** The status code. 0 for OK, 1 for CANCELLED */ + code?: number; +} + +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +export declare enum FinishReason { + /** + * The finish reason is unspecified. + */ + FINISH_REASON_UNSPECIFIED = "FINISH_REASON_UNSPECIFIED", + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + STOP = "STOP", + /** + * Token generation reached the configured maximum output tokens. + */ + MAX_TOKENS = "MAX_TOKENS", + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + SAFETY = "SAFETY", + /** + * The token generation stopped because of potential recitation. + */ + RECITATION = "RECITATION", + /** + * The token generation stopped because of using an unsupported language. + */ + LANGUAGE = "LANGUAGE", + /** + * All other reasons that stopped the token generation. + */ + OTHER = "OTHER", + /** + * Token generation stopped because the content contains forbidden terms. + */ + BLOCKLIST = "BLOCKLIST", + /** + * Token generation stopped for potentially containing prohibited content. + */ + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + /** + * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). + */ + SPII = "SPII", + /** + * The function call generated by the model is invalid. + */ + MALFORMED_FUNCTION_CALL = "MALFORMED_FUNCTION_CALL", + /** + * Token generation stopped because generated images have safety violations. + */ + IMAGE_SAFETY = "IMAGE_SAFETY", + /** + * The tool call generated by the model is invalid. + */ + UNEXPECTED_TOOL_CALL = "UNEXPECTED_TOOL_CALL" +} + +/** A function call. */ +export declare interface FunctionCall { + /** The unique id of the function call. If populated, the client to execute the + `function_call` and return the response with the matching `id`. */ + id?: string; + /** Optional. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */ + args?: Record; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */ + name?: string; +} + +/** Function calling config. */ +export declare interface FunctionCallingConfig { + /** Optional. Function calling mode. */ + mode?: FunctionCallingConfigMode; + /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */ + allowedFunctionNames?: string[]; +} + +/** Config for the function calling config mode. */ +export declare enum FunctionCallingConfigMode { + /** + * The function calling config mode is unspecified. Should not be used. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + AUTO = "AUTO", + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + ANY = "ANY", + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + NONE = "NONE" +} + +/** Defines a function that the model can generate JSON inputs for. + + The inputs are based on `OpenAPI 3.0 specifications + `_. + */ +export declare interface FunctionDeclaration { + /** Defines the function behavior. */ + behavior?: Behavior; + /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */ + description?: string; + /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */ + name?: string; + /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */ + parameters?: Schema; + /** Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "integer" } }, "additionalProperties": false, "required": ["name", "age"], "propertyOrdering": ["name", "age"] } ``` This field is mutually exclusive with `parameters`. */ + parametersJsonSchema?: unknown; + /** Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function. */ + response?: Schema; + /** Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`. */ + responseJsonSchema?: unknown; +} + +/** A function response. */ +export declare class FunctionResponse { + /** Signals that function call continues, and more responses will be returned, turning the function call into a generator. Is only applicable to NON_BLOCKING function calls (see FunctionDeclaration.behavior for details), ignored otherwise. If false, the default, future responses will not be considered. Is only applicable to NON_BLOCKING function calls, is ignored otherwise. If set to false, future responses will not be considered. It is allowed to return empty `response` with `will_continue=False` to signal that the function call is finished. */ + willContinue?: boolean; + /** Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. */ + scheduling?: FunctionResponseScheduling; + /** Optional. The id of the function call this response is for. Populated by the client to match the corresponding function call `id`. */ + id?: string; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */ + name?: string; + /** Required. The function response in JSON object format. Use "output" key to specify function output and "error" key to specify error details (if any). If "output" and "error" keys are not specified, then whole "response" is treated as function output. */ + response?: Record; +} + +/** Specifies how the response should be scheduled in the conversation. */ +export declare enum FunctionResponseScheduling { + /** + * This value is unused. + */ + SCHEDULING_UNSPECIFIED = "SCHEDULING_UNSPECIFIED", + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + SILENT = "SILENT", + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + WHEN_IDLE = "WHEN_IDLE", + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + INTERRUPT = "INTERRUPT" +} + +/** Input example for preference optimization. */ +export declare interface GeminiPreferenceExample { + /** List of completions for a given prompt. */ + completions?: GeminiPreferenceExampleCompletion[]; + /** Multi-turn contents that represents the Prompt. */ + contents?: Content[]; +} + +/** Completion and its preference score. */ +export declare interface GeminiPreferenceExampleCompletion { + /** Single turn completion for the given prompt. */ + completion?: Content; + /** The score for the given completion. */ + score?: number; +} + +/** Optional model configuration parameters. + + For more information, see `Content generation parameters + `_. + */ +export declare interface GenerateContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Instructions for the model to steer it toward better performance. + For example, "Answer as concisely as possible" or "Don't use technical + terms in your response". + */ + systemInstruction?: ContentUnion; + /** Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + */ + temperature?: number; + /** Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + */ + topP?: number; + /** For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + */ + topK?: number; + /** Number of response variations to return. + */ + candidateCount?: number; + /** Maximum number of tokens that can be generated in the response. + */ + maxOutputTokens?: number; + /** List of strings that tells the model to stop generating text if one + of the strings is encountered in the response. + */ + stopSequences?: string[]; + /** Whether to return the log probabilities of the tokens that were + chosen by the model at each step. + */ + responseLogprobs?: boolean; + /** Number of top candidate tokens to return the log probabilities for + at each generation step. + */ + logprobs?: number; + /** Positive values penalize tokens that already appear in the + generated text, increasing the probability of generating more diverse + content. + */ + presencePenalty?: number; + /** Positive values penalize tokens that repeatedly appear in the + generated text, increasing the probability of generating more diverse + content. + */ + frequencyPenalty?: number; + /** When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + */ + seed?: number; + /** Output response mimetype of the generated candidate text. + Supported mimetype: + - `text/plain`: (default) Text output. + - `application/json`: JSON response in the candidates. + The model needs to be prompted to output the appropriate response type, + otherwise the behavior is undefined. + This is a preview feature. + */ + responseMimeType?: string; + /** The `Schema` object allows the definition of input and output data types. + These types can be objects, but also primitives and arrays. + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema). + If set, a compatible response_mime_type must also be set. + Compatible mimetypes: `application/json`: Schema for JSON response. + */ + responseSchema?: SchemaUnion; + /** Optional. Output schema of the generated response. + This is an alternative to `response_schema` that accepts [JSON + Schema](https://json-schema.org/). If set, `response_schema` must be + omitted, but `response_mime_type` is required. While the full JSON Schema + may be sent, not all features are supported. Specifically, only the + following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` + - `type` - `format` - `title` - `description` - `enum` (for strings and + numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - + `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - + `properties` - `additionalProperties` - `required` The non-standard + `propertyOrdering` property may also be set. Cyclic references are + unrolled to a limited degree and, as such, may only be used within + non-required properties. (Nullable properties are not sufficient.) If + `$ref` is set on a sub-schema, no other properties, except for than those + starting as a `$`, may be set. */ + responseJsonSchema?: unknown; + /** Configuration for model router requests. + */ + routingConfig?: GenerationConfigRoutingConfig; + /** Configuration for model selection. + */ + modelSelectionConfig?: ModelSelectionConfig; + /** Safety settings in the request to block unsafe content in the + response. + */ + safetySettings?: SafetySetting[]; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: ToolListUnion; + /** Associates model output to a specific function call. + */ + toolConfig?: ToolConfig; + /** Labels with user-defined metadata to break down billed charges. */ + labels?: Record; + /** Resource name of a context cache that can be used in subsequent + requests. + */ + cachedContent?: string; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. + */ + responseModalities?: string[]; + /** If specified, the media resolution specified will be used. + */ + mediaResolution?: MediaResolution; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfigUnion; + /** If enabled, audio timestamp will be included in the request to the + model. + */ + audioTimestamp?: boolean; + /** The configuration for automatic function calling. + */ + automaticFunctionCalling?: AutomaticFunctionCallingConfig; + /** The thinking features configuration. + */ + thinkingConfig?: ThinkingConfig; +} + +/** Config for models.generate_content parameters. */ +export declare interface GenerateContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Content of the request. + */ + contents: ContentListUnion; + /** Configuration that contains optional model parameters. + */ + config?: GenerateContentConfig; +} + +/** Response message for PredictionService.GenerateContent. */ +export declare class GenerateContentResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Response variations returned by the model. + */ + candidates?: Candidate[]; + /** Timestamp when the request is made to the server. + */ + createTime?: string; + /** The history of automatic function calling. + */ + automaticFunctionCallingHistory?: Content[]; + /** Output only. The model version used to generate the response. */ + modelVersion?: string; + /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */ + promptFeedback?: GenerateContentResponsePromptFeedback; + /** Output only. response_id is used to identify each response. It is the encoding of the event_id. */ + responseId?: string; + /** Usage metadata about the response(s). */ + usageMetadata?: GenerateContentResponseUsageMetadata; + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text(): string | undefined; + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data(): string | undefined; + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls(): FunctionCall[] | undefined; + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode(): string | undefined; + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult(): string | undefined; +} + +/** Content filter results for a prompt sent in the request. */ +export declare class GenerateContentResponsePromptFeedback { + /** Output only. Blocked reason. */ + blockReason?: BlockedReason; + /** Output only. A readable block reason message. */ + blockReasonMessage?: string; + /** Output only. Safety ratings. */ + safetyRatings?: SafetyRating[]; +} + +/** Usage metadata about response(s). */ +export declare class GenerateContentResponseUsageMetadata { + /** Output only. List of modalities of the cached content in the request input. */ + cacheTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens in the cached part in the input (the cached content). */ + cachedContentTokenCount?: number; + /** Number of tokens in the response(s). */ + candidatesTokenCount?: number; + /** Output only. List of modalities that were returned in the response. */ + candidatesTokensDetails?: ModalityTokenCount[]; + /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */ + promptTokenCount?: number; + /** Output only. List of modalities that were processed in the request input. */ + promptTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens present in thoughts output. */ + thoughtsTokenCount?: number; + /** Output only. Number of tokens present in tool-use prompt(s). */ + toolUsePromptTokenCount?: number; + /** Output only. List of modalities that were processed for tool-use request inputs. */ + toolUsePromptTokensDetails?: ModalityTokenCount[]; + /** Total token count for prompt, response candidates, and tool-use prompts (if present). */ + totalTokenCount?: number; + /** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ + trafficType?: TrafficType; +} + +/** An output image. */ +export declare interface GeneratedImage { + /** The output image data. + */ + image?: Image_2; + /** Responsible AI filter reason if the image is filtered out of the + response. + */ + raiFilteredReason?: string; + /** Safety attributes of the image. Lists of RAI categories and their + scores of each content. + */ + safetyAttributes?: SafetyAttributes; + /** The rewritten prompt used for the image generation if the prompt + enhancer is enabled. + */ + enhancedPrompt?: string; +} + +/** A generated image mask. */ +export declare interface GeneratedImageMask { + /** The generated image mask. */ + mask?: Image_2; + /** The detected entities on the segmented area. */ + labels?: EntityLabel[]; +} + +/** A generated video. */ +export declare interface GeneratedVideo { + /** The output video */ + video?: Video; +} + +/** The config for generating an images. */ +export declare interface GenerateImagesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage URI used to store the generated images. + */ + outputGcsUri?: string; + /** Description of what to discourage in the generated images. + */ + negativePrompt?: string; + /** Number of images to generate. + */ + numberOfImages?: number; + /** Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9". + */ + aspectRatio?: string; + /** Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality. + */ + guidanceScale?: number; + /** Random seed for image generation. This is not available when + ``add_watermark`` is set to true. + */ + seed?: number; + /** Filter level for safety filtering. + */ + safetyFilterLevel?: SafetyFilterLevel; + /** Allows generation of people by the model. + */ + personGeneration?: PersonGeneration; + /** Whether to report the safety scores of each generated image and + the positive prompt in the response. + */ + includeSafetyAttributes?: boolean; + /** Whether to include the Responsible AI filter reason if the image + is filtered out of the response. + */ + includeRaiReason?: boolean; + /** Language of the text in the prompt. + */ + language?: ImagePromptLanguage; + /** MIME type of the generated image. + */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). + */ + outputCompressionQuality?: number; + /** Whether to add a watermark to the generated images. + */ + addWatermark?: boolean; + /** The size of the largest dimension of the generated image. + Supported sizes are 1K and 2K (not supported for Imagen 3 models). + */ + imageSize?: string; + /** Whether to use the prompt rewriting logic. + */ + enhancePrompt?: boolean; +} + +/** The parameters for generating images. */ +export declare interface GenerateImagesParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Text prompt that typically describes the images to output. + */ + prompt: string; + /** Configuration for generating images. + */ + config?: GenerateImagesConfig; +} + +/** The output images response. */ +export declare class GenerateImagesResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** List of generated images. + */ + generatedImages?: GeneratedImage[]; + /** Safety attributes of the positive prompt. Only populated if + ``include_safety_attributes`` is set to True. + */ + positivePromptSafetyAttributes?: SafetyAttributes; +} + +/** Configuration for generating videos. */ +export declare interface GenerateVideosConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Number of output videos. */ + numberOfVideos?: number; + /** The gcs bucket where to save the generated videos. */ + outputGcsUri?: string; + /** Frames per second for video generation. */ + fps?: number; + /** Duration of the clip for video generation in seconds. */ + durationSeconds?: number; + /** The RNG seed. If RNG seed is exactly same for each request with unchanged inputs, the prediction results will be consistent. Otherwise, a random RNG seed will be used each time to produce a different result. */ + seed?: number; + /** The aspect ratio for the generated video. 16:9 (landscape) and 9:16 (portrait) are supported. */ + aspectRatio?: string; + /** The resolution for the generated video. 720p and 1080p are supported. */ + resolution?: string; + /** Whether allow to generate person videos, and restrict to specific ages. Supported values are: dont_allow, allow_adult. */ + personGeneration?: string; + /** The pubsub topic where to publish the video generation progress. */ + pubsubTopic?: string; + /** Optional field in addition to the text content. Negative prompts can be explicitly stated here to help generate the video. */ + negativePrompt?: string; + /** Whether to use the prompt rewriting logic. */ + enhancePrompt?: boolean; + /** Whether to generate audio along with the video. */ + generateAudio?: boolean; + /** Image to use as the last frame of generated videos. Only supported for image to video use cases. */ + lastFrame?: Image_2; + /** The images to use as the references to generate the videos. + If this field is provided, the text prompt field must also be provided. + The image, video, or last_frame field are not supported. Each image must + be associated with a type. Veo 2 supports up to 3 asset images *or* 1 + style image. */ + referenceImages?: VideoGenerationReferenceImage[]; + /** Compression quality of the generated videos. */ + compressionQuality?: VideoCompressionQuality; +} + +/** A video generation long-running operation. */ +export declare class GenerateVideosOperation implements Operation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The response if the operation is successful. */ + response?: GenerateVideosResponse; + /** The full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }: OperationFromAPIResponseParameters): Operation; +} + +/** Class that represents the parameters for generating videos. */ +export declare interface GenerateVideosParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The text prompt for generating the videos. Optional for image to video use cases. */ + prompt?: string; + /** The input image for generating the videos. + Optional if prompt or video is provided. */ + image?: Image_2; + /** The input video for video extension use cases. + Optional if prompt or image is provided. */ + video?: Video; + /** Configuration for generating videos. */ + config?: GenerateVideosConfig; +} + +/** Response with generated videos. */ +export declare class GenerateVideosResponse { + /** List of the generated videos */ + generatedVideos?: GeneratedVideo[]; + /** Returns if any videos were filtered due to RAI policies. */ + raiMediaFilteredCount?: number; + /** Returns rai failure reasons if any. */ + raiMediaFilteredReasons?: string[]; +} + +/** Generation config. */ +export declare interface GenerationConfig { + /** Optional. Config for model selection. */ + modelSelectionConfig?: ModelSelectionConfig; + /** Optional. If enabled, audio timestamp will be included in the request to the model. */ + audioTimestamp?: boolean; + /** Optional. Number of candidates to generate. */ + candidateCount?: number; + /** Optional. If enabled, the model will detect emotions and adapt its responses accordingly. */ + enableAffectiveDialog?: boolean; + /** Optional. Frequency penalties. */ + frequencyPenalty?: number; + /** Optional. Logit probabilities. */ + logprobs?: number; + /** Optional. The maximum number of output tokens to generate per message. */ + maxOutputTokens?: number; + /** Optional. If specified, the media resolution specified will be used. */ + mediaResolution?: MediaResolution; + /** Optional. Positive penalties. */ + presencePenalty?: number; + /** Optional. Output schema of the generated response. This is an alternative to `response_schema` that accepts [JSON Schema](https://json-schema.org/). If set, `response_schema` must be omitted, but `response_mime_type` is required. While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` - `type` - `format` - `title` - `description` - `enum` (for strings and numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - `properties` - `additionalProperties` - `required` The non-standard `propertyOrdering` property may also be set. Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If `$ref` is set on a sub-schema, no other properties, except for than those starting as a `$`, may be set. */ + responseJsonSchema?: unknown; + /** Optional. If true, export the logprobs results in response. */ + responseLogprobs?: boolean; + /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */ + responseMimeType?: string; + /** Optional. The modalities of the response. */ + responseModalities?: Modality[]; + /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */ + responseSchema?: Schema; + /** Optional. Routing configuration. */ + routingConfig?: GenerationConfigRoutingConfig; + /** Optional. Seed. */ + seed?: number; + /** Optional. The speech generation config. */ + speechConfig?: SpeechConfig; + /** Optional. Stop sequences. */ + stopSequences?: string[]; + /** Optional. Controls the randomness of predictions. */ + temperature?: number; + /** Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking. */ + thinkingConfig?: GenerationConfigThinkingConfig; + /** Optional. If specified, top-k sampling will be used. */ + topK?: number; + /** Optional. If specified, nucleus sampling will be used. */ + topP?: number; +} + +/** The configuration for routing the request to a specific model. */ +export declare interface GenerationConfigRoutingConfig { + /** Automated routing. */ + autoMode?: GenerationConfigRoutingConfigAutoRoutingMode; + /** Manual routing. */ + manualMode?: GenerationConfigRoutingConfigManualRoutingMode; +} + +/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */ +export declare interface GenerationConfigRoutingConfigAutoRoutingMode { + /** The model routing preference. */ + modelRoutingPreference?: 'UNKNOWN' | 'PRIORITIZE_QUALITY' | 'BALANCED' | 'PRIORITIZE_COST'; +} + +/** When manual routing is set, the specified model will be used directly. */ +export declare interface GenerationConfigRoutingConfigManualRoutingMode { + /** The model name to use. Only the public LLM models are accepted. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */ + modelName?: string; +} + +/** Config for thinking features. */ +export declare interface GenerationConfigThinkingConfig { + /** Optional. Indicates whether to include thoughts in the response. If true, thoughts are returned only when available. */ + includeThoughts?: boolean; + /** Optional. Indicates the thinking budget in tokens. */ + thinkingBudget?: number; +} + +/** Optional parameters. */ +export declare interface GetBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.get parameters. */ +export declare interface GetBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: GetBatchJobConfig; +} + +/** Optional parameters for caches.get method. */ +export declare interface GetCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for caches.get method. */ +export declare interface GetCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: GetCachedContentConfig; +} + +/** Used to override the default configuration. */ +export declare interface GetFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the get method. */ +export declare interface GetFileParameters { + /** The name identifier for the file to retrieve. */ + name: string; + /** Used to override the default configuration. */ + config?: GetFileConfig; +} + +/** Optional parameters for models.get method. */ +export declare interface GetModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +export declare interface GetModelParameters { + model: string; + /** Optional parameters for the request. */ + config?: GetModelConfig; +} + +export declare interface GetOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the GET method. */ +export declare interface GetOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + /** Used to override the default configuration. */ + config?: GetOperationConfig; +} + +/** Optional parameters for tunings.get method. */ +export declare interface GetTuningJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the get method. */ +export declare interface GetTuningJobParameters { + name: string; + /** Optional parameters for the request. */ + config?: GetTuningJobConfig; +} + +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} + * or the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be set, + * when using Vertex AI {@link GoogleGenAIOptions.project} and {@link GoogleGenAIOptions.location} must also be set. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +export declare class GoogleGenAI { + protected readonly apiClient: ApiClient; + private readonly apiKey?; + readonly vertexai: boolean; + private readonly apiVersion?; + readonly models: Models; + readonly live: Live; + readonly batches: Batches; + readonly chats: Chats; + readonly caches: Caches; + readonly files: Files; + readonly operations: Operations; + readonly authTokens: Tokens; + readonly tunings: Tunings; + constructor(options: GoogleGenAIOptions); +} + +/** + * Google Gen AI SDK's configuration options. + * + * See {@link GoogleGenAI} for usage samples. + */ +export declare interface GoogleGenAIOptions { + /** + * Optional. Determines whether to use the Vertex AI or the Gemini API. + * + * @remarks + * When true, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API} will used. + * When false, the {@link https://ai.google.dev/api | Gemini API} will be used. + * + * If unset, default SDK behavior is to use the Gemini API service. + */ + vertexai?: boolean; + /** + * Optional. The Google Cloud project ID for Vertex AI clients. + * + * Find your project ID: https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + */ + project?: string; + /** + * Optional. The Google Cloud project {@link https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations | location} for Vertex AI clients. + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + location?: string; + /** + * The API Key, required for Gemini API clients. + * + * @remarks + * Required on browser runtimes. + */ + apiKey?: string; + /** + * Optional. The API version to use. + * + * @remarks + * If unset, the default API version will be used. + */ + apiVersion?: string; + /** + * Optional. Authentication options defined by the by google-auth-library for Vertex AI clients. + * + * @remarks + * @see {@link https://github.com/googleapis/google-auth-library-nodejs/blob/v9.15.0/src/auth/googleauth.ts | GoogleAuthOptions interface in google-auth-library-nodejs}. + * + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + googleAuthOptions?: GoogleAuthOptions; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; +} + +/** Tool to support Google Maps in Model. */ +export declare interface GoogleMaps { + /** Optional. Auth config for the Google Maps tool. */ + authConfig?: AuthConfig; +} + +/** The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). */ +export declare interface GoogleRpcStatus { + /** The status code, which should be an enum value of google.rpc.Code. */ + code?: number; + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: Record[]; + /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */ + message?: string; +} + +/** Tool to support Google Search in Model. Powered by Google. */ +export declare interface GoogleSearch { + /** Optional. Filter search results to a specific time range. + If customers set a start time, they must set an end time (and vice versa). + */ + timeRangeFilter?: Interval; + /** Optional. List of domains to be excluded from the search results. + The default limit is 2000 domains. */ + excludeDomains?: string[]; +} + +/** Tool to retrieve public web data for grounding, powered by Google. */ +export declare interface GoogleSearchRetrieval { + /** Specifies the dynamic retrieval configuration for the given source. */ + dynamicRetrievalConfig?: DynamicRetrievalConfig; +} + +/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */ +export declare interface GoogleTypeDate { + /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */ + day?: number; + /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */ + month?: number; + /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */ + year?: number; +} + +/** Grounding chunk. */ +export declare interface GroundingChunk { + /** Grounding chunk from Google Maps. */ + maps?: GroundingChunkMaps; + /** Grounding chunk from context retrieved by the retrieval tools. */ + retrievedContext?: GroundingChunkRetrievedContext; + /** Grounding chunk from the web. */ + web?: GroundingChunkWeb; +} + +/** Chunk from Google Maps. */ +export declare interface GroundingChunkMaps { + /** Sources used to generate the place answer. This includes review snippets and photos that were used to generate the answer, as well as uris to flag content. */ + placeAnswerSources?: GroundingChunkMapsPlaceAnswerSources; + /** This Place's resource name, in `places/{place_id}` format. Can be used to look up the Place. */ + placeId?: string; + /** Text of the chunk. */ + text?: string; + /** Title of the chunk. */ + title?: string; + /** URI reference of the chunk. */ + uri?: string; +} + +/** Sources used to generate the place answer. */ +export declare interface GroundingChunkMapsPlaceAnswerSources { + /** A link where users can flag a problem with the generated answer. */ + flagContentUri?: string; + /** Snippets of reviews that are used to generate the answer. */ + reviewSnippets?: GroundingChunkMapsPlaceAnswerSourcesReviewSnippet[]; +} + +/** Author attribution for a photo or review. */ +export declare interface GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution { + /** Name of the author of the Photo or Review. */ + displayName?: string; + /** Profile photo URI of the author of the Photo or Review. */ + photoUri?: string; + /** URI of the author of the Photo or Review. */ + uri?: string; +} + +/** Encapsulates a review snippet. */ +export declare interface GroundingChunkMapsPlaceAnswerSourcesReviewSnippet { + /** This review's author. */ + authorAttribution?: GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution; + /** A link where users can flag a problem with the review. */ + flagContentUri?: string; + /** A link to show the review on Google Maps. */ + googleMapsUri?: string; + /** A string of formatted recent time, expressing the review time relative to the current time in a form appropriate for the language and country. */ + relativePublishTimeDescription?: string; + /** A reference representing this place review which may be used to look up this place review again. */ + review?: string; +} + +/** Chunk from context retrieved by the retrieval tools. */ +export declare interface GroundingChunkRetrievedContext { + /** Output only. The full document name for the referenced Vertex AI Search document. */ + documentName?: string; + /** Additional context for the RAG retrieval result. This is only populated when using the RAG retrieval tool. */ + ragChunk?: RagChunk; + /** Text of the attribution. */ + text?: string; + /** Title of the attribution. */ + title?: string; + /** URI reference of the attribution. */ + uri?: string; +} + +/** Chunk from the web. */ +export declare interface GroundingChunkWeb { + /** Domain of the (original) URI. */ + domain?: string; + /** Title of the chunk. */ + title?: string; + /** URI reference of the chunk. */ + uri?: string; +} + +/** Metadata returned to client when grounding is enabled. */ +export declare interface GroundingMetadata { + /** Optional. Output only. Resource name of the Google Maps widget context token to be used with the PlacesContextElement widget to render contextual data. This is populated only for Google Maps grounding. */ + googleMapsWidgetContextToken?: string; + /** List of supporting references retrieved from specified grounding source. */ + groundingChunks?: GroundingChunk[]; + /** Optional. List of grounding support. */ + groundingSupports?: GroundingSupport[]; + /** Optional. Output only. Retrieval metadata. */ + retrievalMetadata?: RetrievalMetadata; + /** Optional. Queries executed by the retrieval tools. */ + retrievalQueries?: string[]; + /** Optional. Google search entry for the following-up web searches. */ + searchEntryPoint?: SearchEntryPoint; + /** Optional. Web search queries for the following-up web search. */ + webSearchQueries?: string[]; +} + +/** Grounding support. */ +export declare interface GroundingSupport { + /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. For Gemini 2.0 and before, this list must have the same size as the grounding_chunk_indices. For Gemini 2.5 and after, this list will be empty and should be ignored. */ + confidenceScores?: number[]; + /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */ + groundingChunkIndices?: number[]; + /** Segment of the content this support belongs to. */ + segment?: Segment; +} + +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +export declare enum HarmBlockMethod { + /** + * The harm block method is unspecified. + */ + HARM_BLOCK_METHOD_UNSPECIFIED = "HARM_BLOCK_METHOD_UNSPECIFIED", + /** + * The harm block method uses both probability and severity scores. + */ + SEVERITY = "SEVERITY", + /** + * The harm block method uses the probability score. + */ + PROBABILITY = "PROBABILITY" +} + +/** Required. The harm block threshold. */ +export declare enum HarmBlockThreshold { + /** + * Unspecified harm block threshold. + */ + HARM_BLOCK_THRESHOLD_UNSPECIFIED = "HARM_BLOCK_THRESHOLD_UNSPECIFIED", + /** + * Block low threshold and above (i.e. block more). + */ + BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", + /** + * Block medium threshold and above. + */ + BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", + /** + * Block only high threshold (i.e. block less). + */ + BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", + /** + * Block none. + */ + BLOCK_NONE = "BLOCK_NONE", + /** + * Turn off the safety filter. + */ + OFF = "OFF" +} + +/** Required. Harm category. */ +export declare enum HarmCategory { + /** + * The harm category is unspecified. + */ + HARM_CATEGORY_UNSPECIFIED = "HARM_CATEGORY_UNSPECIFIED", + /** + * The harm category is hate speech. + */ + HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH", + /** + * The harm category is dangerous content. + */ + HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT", + /** + * The harm category is harassment. + */ + HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT", + /** + * The harm category is sexually explicit content. + */ + HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT", + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HARM_CATEGORY_CIVIC_INTEGRITY = "HARM_CATEGORY_CIVIC_INTEGRITY", + /** + * The harm category is image hate. + */ + HARM_CATEGORY_IMAGE_HATE = "HARM_CATEGORY_IMAGE_HATE", + /** + * The harm category is image dangerous content. + */ + HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT", + /** + * The harm category is image harassment. + */ + HARM_CATEGORY_IMAGE_HARASSMENT = "HARM_CATEGORY_IMAGE_HARASSMENT", + /** + * The harm category is image sexually explicit content. + */ + HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT" +} + +/** Output only. Harm probability levels in the content. */ +export declare enum HarmProbability { + /** + * Harm probability unspecified. + */ + HARM_PROBABILITY_UNSPECIFIED = "HARM_PROBABILITY_UNSPECIFIED", + /** + * Negligible level of harm. + */ + NEGLIGIBLE = "NEGLIGIBLE", + /** + * Low level of harm. + */ + LOW = "LOW", + /** + * Medium level of harm. + */ + MEDIUM = "MEDIUM", + /** + * High level of harm. + */ + HIGH = "HIGH" +} + +/** Output only. Harm severity levels in the content. */ +export declare enum HarmSeverity { + /** + * Harm severity unspecified. + */ + HARM_SEVERITY_UNSPECIFIED = "HARM_SEVERITY_UNSPECIFIED", + /** + * Negligible level of harm severity. + */ + HARM_SEVERITY_NEGLIGIBLE = "HARM_SEVERITY_NEGLIGIBLE", + /** + * Low level of harm severity. + */ + HARM_SEVERITY_LOW = "HARM_SEVERITY_LOW", + /** + * Medium level of harm severity. + */ + HARM_SEVERITY_MEDIUM = "HARM_SEVERITY_MEDIUM", + /** + * High level of harm severity. + */ + HARM_SEVERITY_HIGH = "HARM_SEVERITY_HIGH" +} + +/** HTTP options to be used in each of the requests. */ +export declare interface HttpOptions { + /** The base URL for the AI platform service endpoint. */ + baseUrl?: string; + /** Specifies the version of the API to use. */ + apiVersion?: string; + /** Additional HTTP headers to be sent with the request. */ + headers?: Record; + /** Timeout for the request in milliseconds. */ + timeout?: number; + /** Extra parameters to add to the request body. + The structure must match the backend API's request structure. + - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest + - GeminiAPI backend API docs: https://ai.google.dev/api/rest */ + extraBody?: Record; +} + +/** + * Represents the necessary information to send a request to an API endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface HttpRequest { + /** + * URL path from the modules, this path is appended to the base API URL to + * form the complete request URL. + * + * If you wish to set full URL, use httpOptions.baseUrl instead. Example to + * set full URL in the request: + * + * const request: HttpRequest = { + * path: '', + * httpOptions: { + * baseUrl: 'https://', + * apiVersion: '', + * }, + * httpMethod: 'GET', + * }; + * + * The result URL will be: https:// + * + */ + path: string; + /** + * Optional query parameters to be appended to the request URL. + */ + queryParams?: Record; + /** + * Optional request body in json string or Blob format, GET request doesn't + * need a request body. + */ + body?: string | Blob; + /** + * The HTTP method to be used for the request. + */ + httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE'; + /** + * Optional set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; + /** + * Optional abort signal which can be used to cancel the request. + */ + abortSignal?: AbortSignal; +} + +/** A wrapper class for the http response. */ +export declare class HttpResponse { + /** Used to retain the processed HTTP headers in the response. */ + headers?: Record; + /** + * The original http response. + */ + responseInternal: Response; + constructor(response: Response); + json(): Promise; +} + +/** An image. */ +declare interface Image_2 { + /** The Cloud Storage URI of the image. ``Image`` can contain a value + for this field or the ``image_bytes`` field but not both. + */ + gcsUri?: string; + /** The image bytes data. ``Image`` can contain a value for this field + or the ``gcs_uri`` field but not both. + + * @remarks Encoded as base64 string. */ + imageBytes?: string; + /** The MIME type of the image. */ + mimeType?: string; +} +export { Image_2 as Image } + +/** Enum that specifies the language of the text in the prompt. */ +export declare enum ImagePromptLanguage { + /** + * Auto-detect the language. + */ + auto = "auto", + /** + * English + */ + en = "en", + /** + * Japanese + */ + ja = "ja", + /** + * Korean + */ + ko = "ko", + /** + * Hindi + */ + hi = "hi", + /** + * Chinese + */ + zh = "zh", + /** + * Portuguese + */ + pt = "pt", + /** + * Spanish + */ + es = "es" +} + +/** Config for inlined request. */ +export declare interface InlinedRequest { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model?: string; + /** Content of the request. + */ + contents?: ContentListUnion; + /** Configuration that contains optional model parameters. + */ + config?: GenerateContentConfig; +} + +/** Config for `inlined_responses` parameter. */ +export declare class InlinedResponse { + /** The response to the request. + */ + response?: GenerateContentResponse; + /** The error encountered while processing the request. + */ + error?: JobError; +} + +/** Represents a time interval, encoded as a start time (inclusive) and an end time (exclusive). + + The start time must be less than or equal to the end time. + When the start equals the end time, the interval is an empty interval. + (matches no time) + When both start and end are unspecified, the interval matches any time. + */ +export declare interface Interval { + /** The start time of the interval. */ + startTime?: string; + /** The end time of the interval. */ + endTime?: string; +} + +/** Job error. */ +export declare interface JobError { + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: string[]; + /** The status code. */ + code?: number; + /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the `details` field. */ + message?: string; +} + +/** Job state. */ +export declare enum JobState { + /** + * The job state is unspecified. + */ + JOB_STATE_UNSPECIFIED = "JOB_STATE_UNSPECIFIED", + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JOB_STATE_QUEUED = "JOB_STATE_QUEUED", + /** + * The service is preparing to run the job. + */ + JOB_STATE_PENDING = "JOB_STATE_PENDING", + /** + * The job is in progress. + */ + JOB_STATE_RUNNING = "JOB_STATE_RUNNING", + /** + * The job completed successfully. + */ + JOB_STATE_SUCCEEDED = "JOB_STATE_SUCCEEDED", + /** + * The job failed. + */ + JOB_STATE_FAILED = "JOB_STATE_FAILED", + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JOB_STATE_CANCELLING = "JOB_STATE_CANCELLING", + /** + * The job has been cancelled. + */ + JOB_STATE_CANCELLED = "JOB_STATE_CANCELLED", + /** + * The job has been stopped, and can be resumed. + */ + JOB_STATE_PAUSED = "JOB_STATE_PAUSED", + /** + * The job has expired. + */ + JOB_STATE_EXPIRED = "JOB_STATE_EXPIRED", + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JOB_STATE_UPDATING = "JOB_STATE_UPDATING", + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JOB_STATE_PARTIALLY_SUCCEEDED = "JOB_STATE_PARTIALLY_SUCCEEDED" +} + +/** Required. Programming language of the `code`. */ +export declare enum Language { + /** + * Unspecified language. This value should not be used. + */ + LANGUAGE_UNSPECIFIED = "LANGUAGE_UNSPECIFIED", + /** + * Python >= 3.10, with numpy and simpy available. + */ + PYTHON = "PYTHON" +} + +/** An object that represents a latitude/longitude pair. + + This is expressed as a pair of doubles to represent degrees latitude and + degrees longitude. Unless specified otherwise, this object must conform to the + + WGS84 standard. Values must be within normalized ranges. + */ +export declare interface LatLng { + /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */ + latitude?: number; + /** The longitude in degrees. It must be in the range [-180.0, +180.0] */ + longitude?: number; +} + +/** Config for optional parameters. */ +export declare interface ListBatchJobsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; +} + +/** Config for batches.list parameters. */ +export declare interface ListBatchJobsParameters { + config?: ListBatchJobsConfig; +} + +/** Config for batches.list return value. */ +export declare class ListBatchJobsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + batchJobs?: BatchJob[]; +} + +/** Config for caches.list method. */ +export declare interface ListCachedContentsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; +} + +/** Parameters for caches.list method. */ +export declare interface ListCachedContentsParameters { + /** Configuration that contains optional parameters. + */ + config?: ListCachedContentsConfig; +} + +export declare class ListCachedContentsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + /** List of cached contents. + */ + cachedContents?: CachedContent[]; +} + +/** Used to override the default configuration. */ +export declare interface ListFilesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; +} + +/** Generates the parameters for the list method. */ +export declare interface ListFilesParameters { + /** Used to override the default configuration. */ + config?: ListFilesConfig; +} + +/** Response for the list files method. */ +export declare class ListFilesResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** A token to retrieve next page of results. */ + nextPageToken?: string; + /** The list of files. */ + files?: File_2[]; +} + +export declare interface ListModelsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; + /** Set true to list base models, false to list tuned models. */ + queryBase?: boolean; +} + +export declare interface ListModelsParameters { + config?: ListModelsConfig; +} + +export declare class ListModelsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + models?: Model[]; +} + +/** Configuration for the list tuning jobs method. */ +export declare interface ListTuningJobsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; +} + +/** Parameters for the list tuning jobs method. */ +export declare interface ListTuningJobsParameters { + config?: ListTuningJobsConfig; +} + +/** Response for the list tuning jobs method. */ +export declare class ListTuningJobsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** A token to retrieve the next page of results. Pass to ListTuningJobsRequest.page_token to obtain that page. */ + nextPageToken?: string; + /** List of TuningJobs in the requested page. */ + tuningJobs?: TuningJob[]; +} + +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +export declare class Live { + private readonly apiClient; + private readonly auth; + private readonly webSocketFactory; + readonly music: LiveMusic; + constructor(apiClient: ApiClient, auth: Auth, webSocketFactory: WebSocketFactory); + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + connect(params: types.LiveConnectParameters): Promise; + private isCallableTool; +} + +/** Callbacks for the live API. */ +export declare interface LiveCallbacks { + /** + * Called when the websocket connection is established. + */ + onopen?: (() => void) | null; + /** + * Called when a message is received from the server. + */ + onmessage: (e: LiveServerMessage) => void; + /** + * Called when an error occurs. + */ + onerror?: ((e: ErrorEvent) => void) | null; + /** + * Called when the websocket connection is closed. + */ + onclose?: ((e: CloseEvent) => void) | null; +} + +/** Incremental update of the current conversation delivered from the client. + + All the content here will unconditionally be appended to the conversation + history and used as part of the prompt to the model to generate content. + + A message here will interrupt any current model generation. + */ +export declare interface LiveClientContent { + /** The content appended to the current conversation with the model. + + For single-turn queries, this is a single instance. For multi-turn + queries, this is a repeated field that contains conversation history and + latest request. + */ + turns?: Content[]; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Messages sent by the client in the API call. */ +export declare interface LiveClientMessage { + /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */ + setup?: LiveClientSetup; + /** Incremental update of the current conversation delivered from the client. */ + clientContent?: LiveClientContent; + /** User input that is sent in real time. */ + realtimeInput?: LiveClientRealtimeInput; + /** Response to a `ToolCallMessage` received from the server. */ + toolResponse?: LiveClientToolResponse; +} + +/** User input that is sent in real time. + + This is different from `LiveClientContent` in a few ways: + + - Can be sent continuously without interruption to model generation. + - If there is a need to mix data interleaved across the + `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to + optimize for best response, but there are no guarantees. + - End of turn is not explicitly specified, but is rather derived from user + activity (for example, end of speech). + - Even before the end of turn, the data is processed incrementally + to optimize for a fast start of the response from the model. + - Is always assumed to be the user's input (cannot be used to populate + conversation history). + */ +export declare interface LiveClientRealtimeInput { + /** Inlined bytes data for media input. */ + mediaChunks?: Blob_2[]; + /** The realtime audio input stream. */ + audio?: Blob_2; + /** + Indicates that the audio stream has ended, e.g. because the microphone was + turned off. + + This should only be sent when automatic activity detection is enabled + (which is the default). + + The client can reopen the stream by sending an audio message. + */ + audioStreamEnd?: boolean; + /** The realtime video input stream. */ + video?: Blob_2; + /** The realtime text input stream. */ + text?: string; + /** Marks the start of user activity. */ + activityStart?: ActivityStart; + /** Marks the end of user activity. */ + activityEnd?: ActivityEnd; +} + +/** Message contains configuration that will apply for the duration of the streaming session. */ +export declare interface LiveClientSetup { + /** + The fully qualified name of the publisher model or tuned model endpoint to + use. + */ + model?: string; + /** The generation configuration for the session. + Note: only a subset of fields are supported. + */ + generationConfig?: GenerationConfig; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; + /** Configures the realtime input behavior in BidiGenerateContent. */ + realtimeInputConfig?: RealtimeInputConfig; + /** Configures session resumption mechanism. + + If included server will send SessionResumptionUpdate messages. */ + sessionResumption?: SessionResumptionConfig; + /** Configures context window compression mechanism. + + If included, server will compress context window to fit into given length. */ + contextWindowCompression?: ContextWindowCompressionConfig; + /** The transcription of the input aligns with the input audio language. + */ + inputAudioTranscription?: AudioTranscriptionConfig; + /** The transcription of the output aligns with the language code + specified for the output audio. + */ + outputAudioTranscription?: AudioTranscriptionConfig; + /** Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input. */ + proactivity?: ProactivityConfig; +} + +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +export declare class LiveClientToolResponse { + /** The response to the function calls. */ + functionResponses?: FunctionResponse[]; +} + +/** Session config for the API connection. */ +export declare interface LiveConnectConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The generation configuration for the session. */ + generationConfig?: GenerationConfig; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. Defaults to AUDIO if not specified. + */ + responseModalities?: Modality[]; + /** Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + */ + temperature?: number; + /** Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + */ + topP?: number; + /** For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + */ + topK?: number; + /** Maximum number of tokens that can be generated in the response. + */ + maxOutputTokens?: number; + /** If specified, the media resolution specified will be used. + */ + mediaResolution?: MediaResolution; + /** When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + */ + seed?: number; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfig; + /** If enabled, the model will detect emotions and adapt its responses accordingly. */ + enableAffectiveDialog?: boolean; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; + /** Configures session resumption mechanism. + + If included the server will send SessionResumptionUpdate messages. */ + sessionResumption?: SessionResumptionConfig; + /** The transcription of the input aligns with the input audio language. + */ + inputAudioTranscription?: AudioTranscriptionConfig; + /** The transcription of the output aligns with the language code + specified for the output audio. + */ + outputAudioTranscription?: AudioTranscriptionConfig; + /** Configures the realtime input behavior in BidiGenerateContent. */ + realtimeInputConfig?: RealtimeInputConfig; + /** Configures context window compression mechanism. + + If included, server will compress context window to fit into given length. */ + contextWindowCompression?: ContextWindowCompressionConfig; + /** Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input. */ + proactivity?: ProactivityConfig; +} + +/** Config for LiveConnectConstraints for Auth Token creation. */ +export declare interface LiveConnectConstraints { + /** ID of the model to configure in the ephemeral token for Live API. + For a list of models, see `Gemini models + `. */ + model?: string; + /** Configuration specific to Live API connections created using this token. */ + config?: LiveConnectConfig; +} + +/** Parameters for connecting to the live API. */ +export declare interface LiveConnectParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** callbacks */ + callbacks: LiveCallbacks; + /** Optional configuration parameters for the request. + */ + config?: LiveConnectConfig; +} + +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +declare class LiveMusic { + private readonly apiClient; + private readonly auth; + private readonly webSocketFactory; + constructor(apiClient: ApiClient, auth: Auth, webSocketFactory: WebSocketFactory); + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + connect(params: types.LiveMusicConnectParameters): Promise; +} + +/** Callbacks for the realtime music API. */ +export declare interface LiveMusicCallbacks { + /** + * Called when a message is received from the server. + */ + onmessage: (e: LiveMusicServerMessage) => void; + /** + * Called when an error occurs. + */ + onerror?: ((e: ErrorEvent) => void) | null; + /** + * Called when the websocket connection is closed. + */ + onclose?: ((e: CloseEvent) => void) | null; +} + +/** User input to start or steer the music. */ +export declare interface LiveMusicClientContent { + /** Weighted prompts as the model input. */ + weightedPrompts?: WeightedPrompt[]; +} + +/** Messages sent by the client in the LiveMusicClientMessage call. */ +export declare interface LiveMusicClientMessage { + /** Message to be sent in the first (and only in the first) `LiveMusicClientMessage`. + Clients should wait for a `LiveMusicSetupComplete` message before + sending any additional messages. */ + setup?: LiveMusicClientSetup; + /** User input to influence music generation. */ + clientContent?: LiveMusicClientContent; + /** Configuration for music generation. */ + musicGenerationConfig?: LiveMusicGenerationConfig; + /** Playback control signal for the music generation. */ + playbackControl?: LiveMusicPlaybackControl; +} + +/** Message to be sent by the system when connecting to the API. */ +export declare interface LiveMusicClientSetup { + /** The model's resource name. Format: `models/{model}`. */ + model?: string; +} + +/** Parameters for connecting to the live API. */ +export declare interface LiveMusicConnectParameters { + /** The model's resource name. */ + model: string; + /** Callbacks invoked on server events. */ + callbacks: LiveMusicCallbacks; +} + +/** A prompt that was filtered with the reason. */ +export declare interface LiveMusicFilteredPrompt { + /** The text prompt that was filtered. */ + text?: string; + /** The reason the prompt was filtered. */ + filteredReason?: string; +} + +/** Configuration for music generation. */ +export declare interface LiveMusicGenerationConfig { + /** Controls the variance in audio generation. Higher values produce + higher variance. Range is [0.0, 3.0]. */ + temperature?: number; + /** Controls how the model selects tokens for output. Samples the topK + tokens with the highest probabilities. Range is [1, 1000]. */ + topK?: number; + /** Seeds audio generation. If not set, the request uses a randomly + generated seed. */ + seed?: number; + /** Controls how closely the model follows prompts. + Higher guidance follows more closely, but will make transitions more + abrupt. Range is [0.0, 6.0]. */ + guidance?: number; + /** Beats per minute. Range is [60, 200]. */ + bpm?: number; + /** Density of sounds. Range is [0.0, 1.0]. */ + density?: number; + /** Brightness of the music. Range is [0.0, 1.0]. */ + brightness?: number; + /** Scale of the generated music. */ + scale?: Scale; + /** Whether the audio output should contain bass. */ + muteBass?: boolean; + /** Whether the audio output should contain drums. */ + muteDrums?: boolean; + /** Whether the audio output should contain only bass and drums. */ + onlyBassAndDrums?: boolean; + /** The mode of music generation. Default mode is QUALITY. */ + musicGenerationMode?: MusicGenerationMode; +} + +/** The playback control signal to apply to the music generation. */ +export declare enum LiveMusicPlaybackControl { + /** + * This value is unused. + */ + PLAYBACK_CONTROL_UNSPECIFIED = "PLAYBACK_CONTROL_UNSPECIFIED", + /** + * Start generating the music. + */ + PLAY = "PLAY", + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + PAUSE = "PAUSE", + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + STOP = "STOP", + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + RESET_CONTEXT = "RESET_CONTEXT" +} + +/** Server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. + Clients may choose to buffer and play it out in real time. + */ +export declare interface LiveMusicServerContent { + /** The audio chunks that the model has generated. */ + audioChunks?: AudioChunk[]; +} + +/** Response message for the LiveMusicClientMessage call. */ +export declare class LiveMusicServerMessage { + /** Message sent in response to a `LiveMusicClientSetup` message from the client. + Clients should wait for this message before sending any additional messages. */ + setupComplete?: LiveMusicServerSetupComplete; + /** Content generated by the model in response to client messages. */ + serverContent?: LiveMusicServerContent; + /** A prompt that was filtered with the reason. */ + filteredPrompt?: LiveMusicFilteredPrompt; + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk(): AudioChunk | undefined; +} + +/** Sent in response to a `LiveMusicClientSetup` message from the client. */ +export declare interface LiveMusicServerSetupComplete { +} + +/** + Represents a connection to the API. + + @experimental + */ +export declare class LiveMusicSession { + readonly conn: WebSocket_2; + private readonly apiClient; + constructor(conn: WebSocket_2, apiClient: ApiClient); + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + setWeightedPrompts(params: types.LiveMusicSetWeightedPromptsParameters): Promise; + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + setMusicGenerationConfig(params: types.LiveMusicSetConfigParameters): Promise; + private sendPlaybackControl; + /** + * Start the music stream. + * + * @experimental + */ + play(): void; + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause(): void; + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop(): void; + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext(): void; + /** + Terminates the WebSocket connection. + + @experimental + */ + close(): void; +} + +/** Parameters for setting config for the live music API. */ +export declare interface LiveMusicSetConfigParameters { + /** Configuration for music generation. */ + musicGenerationConfig: LiveMusicGenerationConfig; +} + +/** Parameters for setting weighted prompts for the live music API. */ +export declare interface LiveMusicSetWeightedPromptsParameters { + /** A map of text prompts to weights to use for the generation request. */ + weightedPrompts: WeightedPrompt[]; +} + +/** Prompts and config used for generating this audio chunk. */ +export declare interface LiveMusicSourceMetadata { + /** Weighted prompts for generating this audio chunk. */ + clientContent?: LiveMusicClientContent; + /** Music generation config for generating this audio chunk. */ + musicGenerationConfig?: LiveMusicGenerationConfig; +} + +/** Parameters for sending client content to the live API. */ +export declare interface LiveSendClientContentParameters { + /** Client content to send to the session. */ + turns?: ContentListUnion; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Parameters for sending realtime input to the live API. */ +export declare interface LiveSendRealtimeInputParameters { + /** Realtime input to send to the session. */ + media?: BlobImageUnion; + /** The realtime audio input stream. */ + audio?: Blob_2; + /** + Indicates that the audio stream has ended, e.g. because the microphone was + turned off. + + This should only be sent when automatic activity detection is enabled + (which is the default). + + The client can reopen the stream by sending an audio message. + */ + audioStreamEnd?: boolean; + /** The realtime video input stream. */ + video?: BlobImageUnion; + /** The realtime text input stream. */ + text?: string; + /** Marks the start of user activity. */ + activityStart?: ActivityStart; + /** Marks the end of user activity. */ + activityEnd?: ActivityEnd; +} + +/** Parameters for sending tool responses to the live API. */ +export declare class LiveSendToolResponseParameters { + /** Tool responses to send to the session. */ + functionResponses: FunctionResponse[] | FunctionResponse; +} + +/** Incremental server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. Clients + may choose to buffer and play it out in real time. + */ +export declare interface LiveServerContent { + /** The content that the model has generated as part of the current conversation with the user. */ + modelTurn?: Content; + /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */ + turnComplete?: boolean; + /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */ + interrupted?: boolean; + /** Metadata returned to client when grounding is enabled. */ + groundingMetadata?: GroundingMetadata; + /** If true, indicates that the model is done generating. When model is + interrupted while generating there will be no generation_complete message + in interrupted turn, it will go through interrupted > turn_complete. + When model assumes realtime playback there will be delay between + generation_complete and turn_complete that is caused by model + waiting for playback to finish. If true, indicates that the model + has finished generating all content. This is a signal to the client + that it can stop sending messages. */ + generationComplete?: boolean; + /** Input transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn. */ + inputTranscription?: Transcription; + /** Output transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn. + */ + outputTranscription?: Transcription; + /** Metadata related to url context retrieval tool. */ + urlContextMetadata?: UrlContextMetadata; +} + +/** Server will not be able to service client soon. */ +export declare interface LiveServerGoAway { + /** The remaining time before the connection will be terminated as ABORTED. The minimal time returned here is specified differently together with the rate limits for a given model. */ + timeLeft?: string; +} + +/** Response message for API call. */ +export declare class LiveServerMessage { + /** Sent in response to a `LiveClientSetup` message from the client. */ + setupComplete?: LiveServerSetupComplete; + /** Content generated by the model in response to client messages. */ + serverContent?: LiveServerContent; + /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ + toolCall?: LiveServerToolCall; + /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */ + toolCallCancellation?: LiveServerToolCallCancellation; + /** Usage metadata about model response(s). */ + usageMetadata?: UsageMetadata; + /** Server will disconnect soon. */ + goAway?: LiveServerGoAway; + /** Update of the session resumption state. */ + sessionResumptionUpdate?: LiveServerSessionResumptionUpdate; + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text(): string | undefined; + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data(): string | undefined; +} + +/** Update of the session resumption state. + + Only sent if `session_resumption` was set in the connection config. + */ +export declare interface LiveServerSessionResumptionUpdate { + /** New handle that represents state that can be resumed. Empty if `resumable`=false. */ + newHandle?: string; + /** True if session can be resumed at this point. It might be not possible to resume session at some points. In that case we send update empty new_handle and resumable=false. Example of such case could be model executing function calls or just generating. Resuming session (using previous session token) in such state will result in some data loss. */ + resumable?: boolean; + /** Index of last message sent by client that is included in state represented by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent` is set. + + Presence of this index allows users to transparently reconnect and avoid issue of losing some part of realtime audio input/video. If client wishes to temporarily disconnect (for example as result of receiving GoAway) they can do it without losing state by buffering messages sent since last `SessionResmumptionTokenUpdate`. This field will enable them to limit buffering (avoid keeping all requests in RAM). + + Note: This should not be used for when resuming a session at some time later -- in those cases partial audio and video frames arelikely not needed. */ + lastConsumedClientMessageIndex?: string; +} + +export declare interface LiveServerSetupComplete { + /** The session id of the live session. */ + sessionId?: string; +} + +/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ +export declare interface LiveServerToolCall { + /** The function call to be executed. */ + functionCalls?: FunctionCall[]; +} + +/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. + + If there were side-effects to those tool calls, clients may attempt to undo + the tool calls. This message occurs only in cases where the clients interrupt + server turns. + */ +export declare interface LiveServerToolCallCancellation { + /** The ids of the tool calls to be cancelled. */ + ids?: string[]; +} + +/** Logprobs Result */ +export declare interface LogprobsResult { + /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */ + chosenCandidates?: LogprobsResultCandidate[]; + /** Length = total number of decoding steps. */ + topCandidates?: LogprobsResultTopCandidates[]; +} + +/** Candidate for the logprobs token and score. */ +export declare interface LogprobsResultCandidate { + /** The candidate's log probability. */ + logProbability?: number; + /** The candidate's token string value. */ + token?: string; + /** The candidate's token id value. */ + tokenId?: number; +} + +/** Candidates with top log probabilities at each decoding step. */ +export declare interface LogprobsResultTopCandidates { + /** Sorted by log probability in descending order. */ + candidates?: LogprobsResultCandidate[]; +} + +/** Configuration for a Mask reference image. */ +export declare interface MaskReferenceConfig { + /** Prompts the model to generate a mask instead of you needing to + provide one (unless MASK_MODE_USER_PROVIDED is used). */ + maskMode?: MaskReferenceMode; + /** A list of up to 5 class ids to use for semantic segmentation. + Automatically creates an image mask based on specific objects. */ + segmentationClasses?: number[]; + /** Dilation percentage of the mask provided. + Float between 0 and 1. */ + maskDilation?: number; +} + +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +export declare class MaskReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the mask reference image. */ + config?: MaskReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the mask mode of a mask reference image. */ +export declare enum MaskReferenceMode { + MASK_MODE_DEFAULT = "MASK_MODE_DEFAULT", + MASK_MODE_USER_PROVIDED = "MASK_MODE_USER_PROVIDED", + MASK_MODE_BACKGROUND = "MASK_MODE_BACKGROUND", + MASK_MODE_FOREGROUND = "MASK_MODE_FOREGROUND", + MASK_MODE_SEMANTIC = "MASK_MODE_SEMANTIC" +} + +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +export declare function mcpToTool(...args: [...Client[], CallableToolConfig | Client]): CallableTool; + +/** Server content modalities. */ +export declare enum MediaModality { + /** + * The modality is unspecified. + */ + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + /** + * Plain text. + */ + TEXT = "TEXT", + /** + * Images. + */ + IMAGE = "IMAGE", + /** + * Video. + */ + VIDEO = "VIDEO", + /** + * Audio. + */ + AUDIO = "AUDIO", + /** + * Document, e.g. PDF. + */ + DOCUMENT = "DOCUMENT" +} + +/** The media resolution to use. */ +export declare enum MediaResolution { + /** + * Media resolution has not been set + */ + MEDIA_RESOLUTION_UNSPECIFIED = "MEDIA_RESOLUTION_UNSPECIFIED", + /** + * Media resolution set to low (64 tokens). + */ + MEDIA_RESOLUTION_LOW = "MEDIA_RESOLUTION_LOW", + /** + * Media resolution set to medium (256 tokens). + */ + MEDIA_RESOLUTION_MEDIUM = "MEDIA_RESOLUTION_MEDIUM", + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MEDIA_RESOLUTION_HIGH = "MEDIA_RESOLUTION_HIGH" +} + +/** Server content modalities. */ +export declare enum Modality { + /** + * The modality is unspecified. + */ + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + /** + * Indicates the model should return text + */ + TEXT = "TEXT", + /** + * Indicates the model should return images. + */ + IMAGE = "IMAGE", + /** + * Indicates the model should return audio. + */ + AUDIO = "AUDIO" +} + +/** Represents token counting info for a single modality. */ +export declare interface ModalityTokenCount { + /** The modality associated with this token count. */ + modality?: MediaModality; + /** Number of tokens. */ + tokenCount?: number; +} + +/** The mode of the predictor to be used in dynamic retrieval. */ +export declare enum Mode { + /** + * Always trigger retrieval. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Run retrieval only when system decides it is necessary. + */ + MODE_DYNAMIC = "MODE_DYNAMIC" +} + +/** A trained machine learning model. */ +export declare interface Model { + /** Resource name of the model. */ + name?: string; + /** Display name of the model. */ + displayName?: string; + /** Description of the model. */ + description?: string; + /** Version ID of the model. A new version is committed when a new + model version is uploaded or trained under an existing model ID. The + version ID is an auto-incrementing decimal number in string + representation. */ + version?: string; + /** List of deployed models created from this base model. Note that a + model could have been deployed to endpoints in different locations. */ + endpoints?: Endpoint[]; + /** Labels with user-defined metadata to organize your models. */ + labels?: Record; + /** Information about the tuned model from the base model. */ + tunedModelInfo?: TunedModelInfo; + /** The maximum number of input tokens that the model can handle. */ + inputTokenLimit?: number; + /** The maximum number of output tokens that the model can generate. */ + outputTokenLimit?: number; + /** List of actions that are supported by the model. */ + supportedActions?: string[]; + /** The default checkpoint id of a model version. + */ + defaultCheckpointId?: string; + /** The checkpoints of the model. */ + checkpoints?: Checkpoint[]; +} + +export declare class Models extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + generateContent: (params: types.GenerateContentParameters) => Promise; + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + private maybeMoveToResponseJsonSchem; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + generateContentStream: (params: types.GenerateContentParameters) => Promise>; + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + private processParamsMaybeAddMcpUsage; + private initAfcToolsMap; + private processAfcStream; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + generateImages: (params: types.GenerateImagesParameters) => Promise; + list: (params?: types.ListModelsParameters) => Promise>; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + editImage: (params: types.EditImageParameters) => Promise; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + upscaleImage: (params: types.UpscaleImageParameters) => Promise; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + generateVideos: (params: types.GenerateVideosParameters) => Promise; + private generateContentInternal; + private generateContentStreamInternal; + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + embedContent(params: types.EmbedContentParameters): Promise; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + private generateImagesInternal; + private editImageInternal; + private upscaleImageInternal; + /** + * Recontextualizes an image. + * + * There are two types of recontextualization currently supported: + * 1) Imagen Product Recontext - Generate images of products in new scenes + * and contexts. + * 2) Virtual Try-On: Generate images of persons modeling fashion products. + * + * @param params - The parameters for recontextualizing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response1 = await ai.models.recontextImage({ + * model: 'imagen-product-recontext-preview-06-30', + * source: { + * prompt: 'In a modern kitchen setting.', + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response1?.generatedImages?.[0]?.image?.imageBytes); + * + * const response2 = await ai.models.recontextImage({ + * model: 'virtual-try-on-preview-08-04', + * source: { + * personImage: personImage, + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response2?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + recontextImage(params: types.RecontextImageParameters): Promise; + /** + * Segments an image, creating a mask of a specified area. + * + * @param params - The parameters for segmenting an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.segmentImage({ + * model: 'image-segmentation-001', + * source: { + * image: image, + * }, + * config: { + * mode: 'foreground', + * }, + * }); + * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes); + * ``` + */ + segmentImage(params: types.SegmentImageParameters): Promise; + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + get(params: types.GetModelParameters): Promise; + private listInternal; + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + update(params: types.UpdateModelParameters): Promise; + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + delete(params: types.DeleteModelParameters): Promise; + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + countTokens(params: types.CountTokensParameters): Promise; + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + computeTokens(params: types.ComputeTokensParameters): Promise; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + private generateVideosInternal; +} + +/** Config for model selection. */ +export declare interface ModelSelectionConfig { + /** Options for feature selection preference. */ + featureSelectionPreference?: FeatureSelectionPreference; +} + +/** The configuration for the multi-speaker setup. */ +export declare interface MultiSpeakerVoiceConfig { + /** The configuration for the speaker to use. */ + speakerVoiceConfigs?: SpeakerVoiceConfig[]; +} + +/** The mode of music generation. */ +export declare enum MusicGenerationMode { + /** + * Rely on the server default generation mode. + */ + MUSIC_GENERATION_MODE_UNSPECIFIED = "MUSIC_GENERATION_MODE_UNSPECIFIED", + /** + * Steer text prompts to regions of latent space with higher quality + music. + */ + QUALITY = "QUALITY", + /** + * Steer text prompts to regions of latent space with a larger + diversity of music. + */ + DIVERSITY = "DIVERSITY", + /** + * Steer text prompts to regions of latent space more likely to + generate music with vocals. + */ + VOCALIZATION = "VOCALIZATION" +} + +/** A long-running operation. */ +export declare interface Operation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The response if the operation is successful. */ + response?: T; + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }: OperationFromAPIResponseParameters): Operation; +} + +/** Parameters of the fromAPIResponse method of the Operation class. */ +export declare interface OperationFromAPIResponseParameters { + /** The API response to be converted to an Operation. */ + apiResponse: Record; + /** Whether the API response is from Vertex AI. */ + isVertexAI: boolean; +} + +/** Parameters for the get method of the operations module. */ +export declare interface OperationGetParameters> { + /** The operation to be retrieved. */ + operation: U; + /** Used to override the default configuration. */ + config?: GetOperationConfig; +} + +export declare class Operations extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + getVideosOperation(parameters: types.OperationGetParameters): Promise; + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + get>(parameters: types.OperationGetParameters): Promise>; + private getVideosOperationInternal; + private fetchPredictVideosOperationInternal; +} + +/** Required. Outcome of the code execution. */ +export declare enum Outcome { + /** + * Unspecified status. This value should not be used. + */ + OUTCOME_UNSPECIFIED = "OUTCOME_UNSPECIFIED", + /** + * Code execution completed successfully. + */ + OUTCOME_OK = "OUTCOME_OK", + /** + * Code execution finished but with a failure. `stderr` should contain the reason. + */ + OUTCOME_FAILED = "OUTCOME_FAILED", + /** + * Code execution ran for too long, and was cancelled. There may or may not be a partial output present. + */ + OUTCOME_DEADLINE_EXCEEDED = "OUTCOME_DEADLINE_EXCEEDED" +} + +export declare enum PagedItem { + PAGED_ITEM_BATCH_JOBS = "batchJobs", + PAGED_ITEM_MODELS = "models", + PAGED_ITEM_TUNING_JOBS = "tuningJobs", + PAGED_ITEM_FILES = "files", + PAGED_ITEM_CACHED_CONTENTS = "cachedContents" +} + +declare interface PagedItemConfig { + config?: { + pageToken?: string; + pageSize?: number; + }; +} + +declare interface PagedItemResponse { + nextPageToken?: string; + sdkHttpResponse?: types.HttpResponse; + batchJobs?: T[]; + models?: T[]; + tuningJobs?: T[]; + files?: T[]; + cachedContents?: T[]; +} + +/** + * Pager class for iterating through paginated results. + */ +export declare class Pager implements AsyncIterable { + private nameInternal; + private pageInternal; + private paramsInternal; + private pageInternalSize; + private sdkHttpResponseInternal?; + protected requestInternal: (params: PagedItemConfig) => Promise>; + protected idxInternal: number; + constructor(name: PagedItem, request: (params: PagedItemConfig) => Promise>, response: PagedItemResponse, params: PagedItemConfig); + private init; + private initNextPage; + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page(): T[]; + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name(): PagedItem; + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize(): number; + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse(): types.HttpResponse | undefined; + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params(): PagedItemConfig; + /** + * Returns the total number of items in the current page. + */ + get pageLength(): number; + /** + * Returns the item at the given index. + */ + getItem(index: number): T; + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator](): AsyncIterator; + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + nextPage(): Promise; + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage(): boolean; +} + +/** A datatype containing media content. + + Exactly one field within a Part should be set, representing the specific type + of content being conveyed. Using multiple fields within the same `Part` + instance is considered invalid. + */ +export declare interface Part { + /** Metadata for a given video. */ + videoMetadata?: VideoMetadata; + /** Indicates if the part is thought from the model. */ + thought?: boolean; + /** Optional. Inlined bytes data. */ + inlineData?: Blob_2; + /** Optional. URI based data. */ + fileData?: FileData; + /** An opaque signature for the thought so it can be reused in subsequent requests. + * @remarks Encoded as base64 string. */ + thoughtSignature?: string; + /** Optional. Result of executing the [ExecutableCode]. */ + codeExecutionResult?: CodeExecutionResult; + /** Optional. Code generated by the model that is meant to be executed. */ + executableCode?: ExecutableCode; + /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */ + functionCall?: FunctionCall; + /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */ + functionResponse?: FunctionResponse; + /** Optional. Text part (can be code). */ + text?: string; +} + +export declare type PartListUnion = PartUnion[] | PartUnion; + +/** Tuning spec for Partner models. */ +export declare interface PartnerModelTuningSpec { + /** Hyperparameters for tuning. The accepted hyper_parameters and their valid range of values will differ depending on the base model. */ + hyperParameters?: Record; + /** Required. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDatasetUri?: string; + /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */ + validationDatasetUri?: string; +} + +export declare type PartUnion = Part | string; + +/** Enum that controls the generation of people. */ +export declare enum PersonGeneration { + /** + * Block generation of images of people. + */ + DONT_ALLOW = "DONT_ALLOW", + /** + * Generate images of adults, but not children. + */ + ALLOW_ADULT = "ALLOW_ADULT", + /** + * Generate images that include adults and children. + */ + ALLOW_ALL = "ALLOW_ALL" +} + +/** The configuration for the prebuilt speaker to use. */ +export declare interface PrebuiltVoiceConfig { + /** The name of the prebuilt voice to use. */ + voiceName?: string; +} + +/** Statistics computed for datasets used for preference optimization. */ +export declare interface PreferenceOptimizationDataStats { + /** Output only. Dataset distributions for scores variance per example. */ + scoreVariancePerExampleDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for scores. */ + scoresDistribution?: DatasetDistribution; + /** Output only. Number of billable tokens in the tuning dataset. */ + totalBillableTokenCount?: string; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user examples in the training dataset. */ + userDatasetExamples?: GeminiPreferenceExample[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: DatasetDistribution; +} + +/** A pre-tuned model for continuous tuning. */ +export declare interface PreTunedModel { + /** Output only. The name of the base model this PreTunedModel was tuned from. */ + baseModel?: string; + /** Optional. The source checkpoint id. If not specified, the default checkpoint will be used. */ + checkpointId?: string; + /** The resource name of the Model. E.g., a model resource name with a specified version id or alias: `projects/{project}/locations/{location}/models/{model}@{version_id}` `projects/{project}/locations/{location}/models/{model}@{alias}` Or, omit the version id to use the default version: `projects/{project}/locations/{location}/models/{model}` */ + tunedModelName?: string; +} + +/** Config for proactivity features. */ +export declare interface ProactivityConfig { + /** If enabled, the model can reject responding to the last prompt. For + example, this allows the model to ignore out of context speech or to stay + silent if the user did not make a request, yet. */ + proactiveAudio?: boolean; +} + +/** An image of the product. */ +export declare interface ProductImage { + /** An image of the product to be recontextualized. */ + productImage?: Image_2; +} + +/** A RagChunk includes the content of a chunk of a RagFile, and associated metadata. */ +export declare interface RagChunk { + /** If populated, represents where the chunk starts and ends in the document. */ + pageSpan?: RagChunkPageSpan; + /** The content of the chunk. */ + text?: string; +} + +/** Represents where the chunk starts and ends in the document. */ +export declare interface RagChunkPageSpan { + /** Page where chunk starts in the document. Inclusive. 1-indexed. */ + firstPage?: number; + /** Page where chunk ends in the document. Inclusive. 1-indexed. */ + lastPage?: number; +} + +/** Specifies the context retrieval config. */ +export declare interface RagRetrievalConfig { + /** Optional. Config for filters. */ + filter?: RagRetrievalConfigFilter; + /** Optional. Config for Hybrid Search. */ + hybridSearch?: RagRetrievalConfigHybridSearch; + /** Optional. Config for ranking and reranking. */ + ranking?: RagRetrievalConfigRanking; + /** Optional. The number of contexts to retrieve. */ + topK?: number; +} + +/** Config for filters. */ +export declare interface RagRetrievalConfigFilter { + /** Optional. String for metadata filtering. */ + metadataFilter?: string; + /** Optional. Only returns contexts with vector distance smaller than the threshold. */ + vectorDistanceThreshold?: number; + /** Optional. Only returns contexts with vector similarity larger than the threshold. */ + vectorSimilarityThreshold?: number; +} + +/** Config for Hybrid Search. */ +export declare interface RagRetrievalConfigHybridSearch { + /** Optional. Alpha value controls the weight between dense and sparse vector search results. The range is [0, 1], while 0 means sparse vector search only and 1 means dense vector search only. The default value is 0.5 which balances sparse and dense vector search equally. */ + alpha?: number; +} + +/** Config for ranking and reranking. */ +export declare interface RagRetrievalConfigRanking { + /** Optional. Config for LlmRanker. */ + llmRanker?: RagRetrievalConfigRankingLlmRanker; + /** Optional. Config for Rank Service. */ + rankService?: RagRetrievalConfigRankingRankService; +} + +/** Config for LlmRanker. */ +export declare interface RagRetrievalConfigRankingLlmRanker { + /** Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */ + modelName?: string; +} + +/** Config for Rank Service. */ +export declare interface RagRetrievalConfigRankingRankService { + /** Optional. The model name of the rank service. Format: `semantic-ranker-512@latest` */ + modelName?: string; +} + +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +export declare class RawReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface RealtimeInputConfig { + /** If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals. */ + automaticActivityDetection?: AutomaticActivityDetection; + /** Defines what effect activity has. */ + activityHandling?: ActivityHandling; + /** Defines which input is included in the user's turn. */ + turnCoverage?: TurnCoverage; +} + +/** Configuration for recontextualizing an image. */ +export declare interface RecontextImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Number of images to generate. */ + numberOfImages?: number; + /** The number of sampling steps. A higher value has better image + quality, while a lower value has better latency. */ + baseSteps?: number; + /** Cloud Storage URI used to store the generated images. */ + outputGcsUri?: string; + /** Random seed for image generation. */ + seed?: number; + /** Filter level for safety filtering. */ + safetyFilterLevel?: SafetyFilterLevel; + /** Whether allow to generate person images, and restrict to specific + ages. */ + personGeneration?: PersonGeneration; + /** MIME type of the generated image. */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). */ + outputCompressionQuality?: number; + /** Whether to use the prompt rewriting logic. */ + enhancePrompt?: boolean; +} + +/** The parameters for recontextualizing an image. */ +export declare interface RecontextImageParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** A set of source input(s) for image recontextualization. */ + source: RecontextImageSource; + /** Configuration for image recontextualization. */ + config?: RecontextImageConfig; +} + +/** The output images response. */ +export declare class RecontextImageResponse { + /** List of generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** A set of source input(s) for image recontextualization. */ +export declare interface RecontextImageSource { + /** A text prompt for guiding the model during image + recontextualization. Not supported for Virtual Try-On. */ + prompt?: string; + /** Image of the person or subject who will be wearing the + product(s). */ + personImage?: Image_2; + /** A list of product images. */ + productImages?: ProductImage[]; +} + +export declare type ReferenceImage = RawReferenceImage | MaskReferenceImage | ControlReferenceImage | StyleReferenceImage | SubjectReferenceImage; + +/** Private class that represents a Reference image that is sent to API. */ +declare interface ReferenceImageAPIInternal { + /** The reference image for the editing operation. */ + referenceImage?: types.Image; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the mask reference image. */ + maskImageConfig?: types.MaskReferenceConfig; + /** Configuration for the control reference image. */ + controlImageConfig?: types.ControlReferenceConfig; + /** Configuration for the style reference image. */ + styleImageConfig?: types.StyleReferenceConfig; + /** Configuration for the subject reference image. */ + subjectImageConfig?: types.SubjectReferenceConfig; +} + +/** Represents a recorded session. */ +export declare interface ReplayFile { + replayId?: string; + interactions?: ReplayInteraction[]; +} + +/** Represents a single interaction, request and response in a replay. */ +export declare interface ReplayInteraction { + request?: ReplayRequest; + response?: ReplayResponse; +} + +/** Represents a single request in a replay. */ +export declare interface ReplayRequest { + method?: string; + url?: string; + headers?: Record; + bodySegments?: Record[]; +} + +/** Represents a single response in a replay. */ +export declare class ReplayResponse { + statusCode?: number; + headers?: Record; + bodySegments?: Record[]; + sdkResponseSegments?: Record[]; +} + +/** Defines a retrieval tool that model can call to access external knowledge. */ +export declare interface Retrieval { + /** Optional. Deprecated. This option is no longer supported. */ + disableAttribution?: boolean; + /** Use data source powered by external API for grounding. */ + externalApi?: ExternalApi; + /** Set to use data source powered by Vertex AI Search. */ + vertexAiSearch?: VertexAISearch; + /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */ + vertexRagStore?: VertexRagStore; +} + +/** Retrieval config. + */ +export declare interface RetrievalConfig { + /** Optional. The location of the user. */ + latLng?: LatLng; + /** The language code of the user. */ + languageCode?: string; +} + +/** Metadata related to retrieval in the grounding flow. */ +export declare interface RetrievalMetadata { + /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */ + googleSearchDynamicRetrievalScore?: number; +} + +/** Safety attributes of a GeneratedImage or the user-provided prompt. */ +export declare interface SafetyAttributes { + /** List of RAI categories. + */ + categories?: string[]; + /** List of scores of each categories. + */ + scores?: number[]; + /** Internal use only. + */ + contentType?: string; +} + +/** Enum that controls the safety filter level for objectionable content. */ +export declare enum SafetyFilterLevel { + BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", + BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", + BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", + BLOCK_NONE = "BLOCK_NONE" +} + +/** Safety rating corresponding to the generated content. */ +export declare interface SafetyRating { + /** Output only. Indicates whether the content was filtered out because of this rating. */ + blocked?: boolean; + /** Output only. Harm category. */ + category?: HarmCategory; + /** Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If minors are detected in the output image, the threshold of each safety category will be overwritten if user sets a lower threshold. */ + overwrittenThreshold?: HarmBlockThreshold; + /** Output only. Harm probability levels in the content. */ + probability?: HarmProbability; + /** Output only. Harm probability score. */ + probabilityScore?: number; + /** Output only. Harm severity levels in the content. */ + severity?: HarmSeverity; + /** Output only. Harm severity score. */ + severityScore?: number; +} + +/** Safety settings. */ +export declare interface SafetySetting { + /** Determines if the harm block method uses probability or probability + and severity scores. */ + method?: HarmBlockMethod; + /** Required. Harm category. */ + category?: HarmCategory; + /** Required. The harm block threshold. */ + threshold?: HarmBlockThreshold; +} + +/** Scale of the generated music. */ +export declare enum Scale { + /** + * Default value. This value is unused. + */ + SCALE_UNSPECIFIED = "SCALE_UNSPECIFIED", + /** + * C major or A minor. + */ + C_MAJOR_A_MINOR = "C_MAJOR_A_MINOR", + /** + * Db major or Bb minor. + */ + D_FLAT_MAJOR_B_FLAT_MINOR = "D_FLAT_MAJOR_B_FLAT_MINOR", + /** + * D major or B minor. + */ + D_MAJOR_B_MINOR = "D_MAJOR_B_MINOR", + /** + * Eb major or C minor + */ + E_FLAT_MAJOR_C_MINOR = "E_FLAT_MAJOR_C_MINOR", + /** + * E major or Db minor. + */ + E_MAJOR_D_FLAT_MINOR = "E_MAJOR_D_FLAT_MINOR", + /** + * F major or D minor. + */ + F_MAJOR_D_MINOR = "F_MAJOR_D_MINOR", + /** + * Gb major or Eb minor. + */ + G_FLAT_MAJOR_E_FLAT_MINOR = "G_FLAT_MAJOR_E_FLAT_MINOR", + /** + * G major or E minor. + */ + G_MAJOR_E_MINOR = "G_MAJOR_E_MINOR", + /** + * Ab major or F minor. + */ + A_FLAT_MAJOR_F_MINOR = "A_FLAT_MAJOR_F_MINOR", + /** + * A major or Gb minor. + */ + A_MAJOR_G_FLAT_MINOR = "A_MAJOR_G_FLAT_MINOR", + /** + * Bb major or G minor. + */ + B_FLAT_MAJOR_G_MINOR = "B_FLAT_MAJOR_G_MINOR", + /** + * B major or Ab minor. + */ + B_MAJOR_A_FLAT_MINOR = "B_MAJOR_A_FLAT_MINOR" +} + +/** Schema is used to define the format of input/output data. + + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may + be added in the future as needed. + */ +export declare interface Schema { + /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */ + anyOf?: Schema[]; + /** Optional. Default value of the data. */ + default?: unknown; + /** Optional. The description of the data. */ + description?: string; + /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:["101", "201", "301"]} */ + enum?: string[]; + /** Optional. Example of the object. Will only populated when the object is the root. */ + example?: unknown; + /** Optional. The format of the data. Supported formats: for NUMBER type: "float", "double" for INTEGER type: "int32", "int64" for STRING type: "email", "byte", etc */ + format?: string; + /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */ + items?: Schema; + /** Optional. Maximum number of the elements for Type.ARRAY. */ + maxItems?: string; + /** Optional. Maximum length of the Type.STRING */ + maxLength?: string; + /** Optional. Maximum number of the properties for Type.OBJECT. */ + maxProperties?: string; + /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */ + maximum?: number; + /** Optional. Minimum number of the elements for Type.ARRAY. */ + minItems?: string; + /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */ + minLength?: string; + /** Optional. Minimum number of the properties for Type.OBJECT. */ + minProperties?: string; + /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */ + minimum?: number; + /** Optional. Indicates if the value may be null. */ + nullable?: boolean; + /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */ + pattern?: string; + /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */ + properties?: Record; + /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */ + propertyOrdering?: string[]; + /** Optional. Required properties of Type.OBJECT. */ + required?: string[]; + /** Optional. The title of the Schema. */ + title?: string; + /** Optional. The type of the data. */ + type?: Type; +} + +export declare type SchemaUnion = Schema | unknown; + +/** An image mask representing a brush scribble. */ +export declare interface ScribbleImage { + /** The brush scribble to guide segmentation. Valid for the interactive mode. */ + image?: Image_2; +} + +/** Google search entry point. */ +export declare interface SearchEntryPoint { + /** Optional. Web content snippet that can be embedded in a web page or an app webview. */ + renderedContent?: string; + /** Optional. Base64 encoded JSON representing array of tuple. + * @remarks Encoded as base64 string. */ + sdkBlob?: string; +} + +/** Segment of the content. */ +export declare interface Segment { + /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */ + endIndex?: number; + /** Output only. The index of a Part object within its parent Content object. */ + partIndex?: number; + /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */ + startIndex?: number; + /** Output only. The text corresponding to the segment from the response. */ + text?: string; +} + +/** Configuration for segmenting an image. */ +export declare interface SegmentImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The segmentation mode to use. */ + mode?: SegmentMode; + /** The maximum number of predictions to return up to, by top + confidence score. */ + maxPredictions?: number; + /** The confidence score threshold for the detections as a decimal + value. Only predictions with a confidence score higher than this + threshold will be returned. */ + confidenceThreshold?: number; + /** A decimal value representing how much dilation to apply to the + masks. 0 for no dilation. 1.0 means the masked area covers the whole + image. */ + maskDilation?: number; + /** The binary color threshold to apply to the masks. The threshold + can be set to a decimal value between 0 and 255 non-inclusive. + Set to -1 for no binary color thresholding. */ + binaryColorThreshold?: number; +} + +/** The parameters for segmenting an image. */ +export declare interface SegmentImageParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** A set of source input(s) for image segmentation. */ + source: SegmentImageSource; + /** Configuration for image segmentation. */ + config?: SegmentImageConfig; +} + +/** The output images response. */ +export declare class SegmentImageResponse { + /** List of generated image masks. + */ + generatedMasks?: GeneratedImageMask[]; +} + +/** A set of source input(s) for image segmentation. */ +export declare interface SegmentImageSource { + /** A text prompt for guiding the model during image segmentation. + Required for prompt mode and semantic mode, disallowed for other modes. */ + prompt?: string; + /** The image to be segmented. */ + image?: Image_2; + /** The brush scribble to guide segmentation. + Required for the interactive mode, disallowed for other modes. */ + scribbleImage?: ScribbleImage; +} + +/** Enum that represents the segmentation mode. */ +export declare enum SegmentMode { + FOREGROUND = "FOREGROUND", + BACKGROUND = "BACKGROUND", + PROMPT = "PROMPT", + SEMANTIC = "SEMANTIC", + INTERACTIVE = "INTERACTIVE" +} + +/** Parameters for sending a message within a chat session. + + These parameters are used with the `chat.sendMessage()` method. + */ +export declare interface SendMessageParameters { + /** The message to send to the model. + + The SDK will combine all parts into a single 'user' content to send to + the model. + */ + message: PartListUnion; + /** Config for this specific request. + + Please note that the per-request config does not change the chat level + config, nor inherit from it. If you intend to use some values from the + chat's default config, you must explicitly copy them into this per-request + config. + */ + config?: GenerateContentConfig; +} + +/** + Represents a connection to the API. + + @experimental + */ +export declare class Session { + readonly conn: WebSocket_2; + private readonly apiClient; + constructor(conn: WebSocket_2, apiClient: ApiClient); + private tLiveClientContent; + private tLiveClienttToolResponse; + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params: types.LiveSendClientContentParameters): void; + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params: types.LiveSendRealtimeInputParameters): void; + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params: types.LiveSendToolResponseParameters): void; + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close(): void; +} + +/** Configuration of session resumption mechanism. + + Included in `LiveConnectConfig.session_resumption`. If included server + will send `LiveServerSessionResumptionUpdate` messages. + */ +export declare interface SessionResumptionConfig { + /** Session resumption handle of previous session (session to restore). + + If not present new session will be started. */ + handle?: string; + /** If set the server will send `last_consumed_client_message_index` in the `session_resumption_update` messages to allow for transparent reconnections. */ + transparent?: boolean; +} + +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +export declare function setDefaultBaseUrls(baseUrlParams: BaseUrlParameters): void; + +/** Context window will be truncated by keeping only suffix of it. + + Context window will always be cut at start of USER role turn. System + instructions and `BidiGenerateContentSetup.prefix_turns` will not be + subject to the sliding window mechanism, they will always stay at the + beginning of context window. + */ +export declare interface SlidingWindow { + /** Session reduction target -- how many tokens we should keep. Window shortening operation has some latency costs, so we should avoid running it on every turn. Should be < trigger_tokens. If not set, trigger_tokens/2 is assumed. */ + targetTokens?: string; +} + +/** The configuration for the speaker to use. */ +export declare interface SpeakerVoiceConfig { + /** The name of the speaker to use. Should be the same as in the + prompt. */ + speaker?: string; + /** The configuration for the voice to use. */ + voiceConfig?: VoiceConfig; +} + +/** The speech generation configuration. */ +export declare interface SpeechConfig { + /** The configuration for the speaker to use. + */ + voiceConfig?: VoiceConfig; + /** The configuration for the multi-speaker setup. + It is mutually exclusive with the voice_config field. + */ + multiSpeakerVoiceConfig?: MultiSpeakerVoiceConfig; + /** Language code (ISO 639. e.g. en-US) for the speech synthesization. + Only available for Live API. + */ + languageCode?: string; +} + +export declare type SpeechConfigUnion = SpeechConfig | string; + +/** Start of speech sensitivity. */ +export declare enum StartSensitivity { + /** + * The default is START_SENSITIVITY_LOW. + */ + START_SENSITIVITY_UNSPECIFIED = "START_SENSITIVITY_UNSPECIFIED", + /** + * Automatic detection will detect the start of speech more often. + */ + START_SENSITIVITY_HIGH = "START_SENSITIVITY_HIGH", + /** + * Automatic detection will detect the start of speech less often. + */ + START_SENSITIVITY_LOW = "START_SENSITIVITY_LOW" +} + +/** Configuration for a Style reference image. */ +export declare interface StyleReferenceConfig { + /** A text description of the style to use for the generated image. */ + styleDescription?: string; +} + +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +export declare class StyleReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the style reference image. */ + config?: StyleReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Configuration for a Subject reference image. */ +export declare interface SubjectReferenceConfig { + /** The subject type of a subject reference image. */ + subjectType?: SubjectReferenceType; + /** Subject description for the image. */ + subjectDescription?: string; +} + +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +export declare class SubjectReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the subject reference image. */ + config?: SubjectReferenceConfig; + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the subject type of a subject reference image. */ +export declare enum SubjectReferenceType { + SUBJECT_TYPE_DEFAULT = "SUBJECT_TYPE_DEFAULT", + SUBJECT_TYPE_PERSON = "SUBJECT_TYPE_PERSON", + SUBJECT_TYPE_ANIMAL = "SUBJECT_TYPE_ANIMAL", + SUBJECT_TYPE_PRODUCT = "SUBJECT_TYPE_PRODUCT" +} + +/** Hyperparameters for SFT. */ +export declare interface SupervisedHyperParameters { + /** Optional. Adapter size for tuning. */ + adapterSize?: AdapterSize; + /** Optional. Batch size for tuning. This feature is only available for open source models. */ + batchSize?: string; + /** Optional. Number of complete passes the model makes over the entire training dataset during training. */ + epochCount?: string; + /** Optional. Learning rate for tuning. Mutually exclusive with `learning_rate_multiplier`. This feature is only available for open source models. */ + learningRate?: number; + /** Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with `learning_rate`. This feature is only available for 1P models. */ + learningRateMultiplier?: number; +} + +/** Dataset distribution for Supervised Tuning. */ +export declare interface SupervisedTuningDatasetDistribution { + /** Output only. Sum of a given population of values that are billable. */ + billableSum?: string; + /** Output only. Defines the histogram bucket. */ + buckets?: SupervisedTuningDatasetDistributionDatasetBucket[]; + /** Output only. The maximum of the population values. */ + max?: number; + /** Output only. The arithmetic mean of the values in the population. */ + mean?: number; + /** Output only. The median of the values in the population. */ + median?: number; + /** Output only. The minimum of the population values. */ + min?: number; + /** Output only. The 5th percentile of the values in the population. */ + p5?: number; + /** Output only. The 95th percentile of the values in the population. */ + p95?: number; + /** Output only. Sum of a given population of values. */ + sum?: string; +} + +/** Dataset bucket used to create a histogram for the distribution given a population of values. */ +export declare interface SupervisedTuningDatasetDistributionDatasetBucket { + /** Output only. Number of values in the bucket. */ + count?: number; + /** Output only. Left bound of the bucket. */ + left?: number; + /** Output only. Right bound of the bucket. */ + right?: number; +} + +/** Tuning data statistics for Supervised Tuning. */ +export declare interface SupervisedTuningDataStats { + /** Output only. For each index in `truncated_example_indices`, the user-facing reason why the example was dropped. */ + droppedExampleReasons?: string[]; + /** Output only. Number of billable characters in the tuning dataset. */ + totalBillableCharacterCount?: string; + /** Output only. Number of billable tokens in the tuning dataset. */ + totalBillableTokenCount?: string; + /** Output only. The number of examples in the dataset that have been dropped. An example can be dropped for reasons including: too many tokens, contains an invalid image, contains too many images, etc. */ + totalTruncatedExampleCount?: string; + /** Output only. Number of tuning characters in the tuning dataset. */ + totalTuningCharacterCount?: string; + /** Output only. A partial sample of the indices (starting from 1) of the dropped examples. */ + truncatedExampleIndices?: string[]; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user messages in the training dataset uri. */ + userDatasetExamples?: Content[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: SupervisedTuningDatasetDistribution; + /** Output only. Dataset distributions for the messages per example. */ + userMessagePerExampleDistribution?: SupervisedTuningDatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: SupervisedTuningDatasetDistribution; +} + +/** Tuning Spec for Supervised Tuning for first party models. */ +export declare interface SupervisedTuningSpec { + /** Optional. If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. Default is false. */ + exportLastCheckpointOnly?: boolean; + /** Optional. Hyperparameters for SFT. */ + hyperParameters?: SupervisedHyperParameters; + /** Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */ + trainingDatasetUri?: string; + /** Tuning mode. */ + tuningMode?: TuningMode; + /** Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */ + validationDatasetUri?: string; +} + +export declare interface TestTableFile { + comment?: string; + testMethod?: string; + parameterNames?: string[]; + testTable?: TestTableItem[]; +} + +export declare interface TestTableItem { + /** The name of the test. This is used to derive the replay id. */ + name?: string; + /** The parameters to the test. Use pydantic models. */ + parameters?: Record; + /** Expects an exception for MLDev matching the string. */ + exceptionIfMldev?: string; + /** Expects an exception for Vertex matching the string. */ + exceptionIfVertex?: string; + /** Use if you don't want to use the default replay id which is derived from the test name. */ + overrideReplayId?: string; + /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */ + hasUnion?: boolean; + /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */ + skipInApiMode?: string; + /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */ + ignoreKeys?: string[]; +} + +/** The thinking features configuration. */ +export declare interface ThinkingConfig { + /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available. + */ + includeThoughts?: boolean; + /** Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent. + */ + thinkingBudget?: number; +} + +export declare class Tokens extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + create(params: types.CreateAuthTokenParameters): Promise; +} + +/** Tokens info with a list of tokens and the corresponding list of token ids. */ +export declare interface TokensInfo { + /** Optional. Optional fields for the role from the corresponding Content. */ + role?: string; + /** A list of token ids from the input. */ + tokenIds?: string[]; + /** A list of tokens from the input. + * @remarks Encoded as base64 string. */ + tokens?: string[]; +} + +/** Tool details of a tool that the model may use to generate a response. */ +export declare interface Tool { + /** List of function declarations that the tool supports. */ + functionDeclarations?: FunctionDeclaration[]; + /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */ + retrieval?: Retrieval; + /** Optional. Google Search tool type. Specialized retrieval tool + that is powered by Google Search. */ + googleSearch?: GoogleSearch; + /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */ + googleSearchRetrieval?: GoogleSearchRetrieval; + /** Optional. Enterprise web search tool type. Specialized retrieval + tool that is powered by Vertex AI Search and Sec4 compliance. */ + enterpriseWebSearch?: EnterpriseWebSearch; + /** Optional. Google Maps tool type. Specialized retrieval tool + that is powered by Google Maps. */ + googleMaps?: GoogleMaps; + /** Optional. Tool to support URL context retrieval. */ + urlContext?: UrlContext; + /** Optional. Tool to support the model interacting directly with the + computer. If enabled, it automatically populates computer-use specific + Function Declarations. */ + computerUse?: ToolComputerUse; + /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. */ + codeExecution?: ToolCodeExecution; +} + +/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */ +export declare interface ToolCodeExecution { +} + +/** Tool to support computer use. */ +export declare interface ToolComputerUse { + /** Required. The environment being operated. */ + environment?: Environment; +} + +/** Tool config. + + This config is shared for all tools provided in the request. + */ +export declare interface ToolConfig { + /** Optional. Function calling config. */ + functionCallingConfig?: FunctionCallingConfig; + /** Optional. Retrieval config. */ + retrievalConfig?: RetrievalConfig; +} + +export declare type ToolListUnion = ToolUnion[]; + +export declare type ToolUnion = Tool | CallableTool; + +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +export declare enum TrafficType { + /** + * Unspecified request traffic type. + */ + TRAFFIC_TYPE_UNSPECIFIED = "TRAFFIC_TYPE_UNSPECIFIED", + /** + * Type for Pay-As-You-Go traffic. + */ + ON_DEMAND = "ON_DEMAND", + /** + * Type for Provisioned Throughput traffic. + */ + PROVISIONED_THROUGHPUT = "PROVISIONED_THROUGHPUT" +} + +/** Audio transcription in Server Conent. */ +export declare interface Transcription { + /** Transcription text. + */ + text?: string; + /** The bool indicates the end of the transcription. + */ + finished?: boolean; +} + +export declare interface TunedModel { + /** Output only. The resource name of the TunedModel. Format: `projects/{project}/locations/{location}/models/{model}@{version_id}` When tuning from a base model, the version_id will be 1. For continuous tuning, the version id will be incremented by 1 from the last version id in the parent model. E.g., `projects/{project}/locations/{location}/models/{model}@{last_version_id + 1}` */ + model?: string; + /** Output only. A resource name of an Endpoint. Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. */ + endpoint?: string; + /** The checkpoints associated with this TunedModel. + This field is only populated for tuning jobs that enable intermediate + checkpoints. */ + checkpoints?: TunedModelCheckpoint[]; +} + +/** TunedModelCheckpoint for the Tuned Model of a Tuning Job. */ +export declare interface TunedModelCheckpoint { + /** The ID of the checkpoint. + */ + checkpointId?: string; + /** The epoch of the checkpoint. + */ + epoch?: string; + /** The step of the checkpoint. + */ + step?: string; + /** The Endpoint resource name that the checkpoint is deployed to. + Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. + */ + endpoint?: string; +} + +/** A tuned machine learning model. */ +export declare interface TunedModelInfo { + /** ID of the base model that you want to tune. */ + baseModel?: string; + /** Date and time when the base model was created. */ + createTime?: string; + /** Date and time when the base model was last updated. */ + updateTime?: string; +} + +/** Supervised fine-tuning training dataset. */ +export declare interface TuningDataset { + /** GCS URI of the file containing training dataset in JSONL format. */ + gcsUri?: string; + /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */ + vertexDatasetResource?: string; + /** Inline examples with simple input/output text. */ + examples?: TuningExample[]; +} + +/** The tuning data statistic values for TuningJob. */ +export declare interface TuningDataStats { + /** Output only. Statistics for distillation. */ + distillationDataStats?: DistillationDataStats; + /** Output only. Statistics for preference optimization. */ + preferenceOptimizationDataStats?: PreferenceOptimizationDataStats; + /** The SFT Tuning data stats. */ + supervisedTuningDataStats?: SupervisedTuningDataStats; +} + +export declare interface TuningExample { + /** Text model input. */ + textInput?: string; + /** The expected model output. */ + output?: string; +} + +/** A tuning job. */ +export declare interface TuningJob { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}` */ + name?: string; + /** Output only. The detailed state of the job. */ + state?: JobState; + /** Output only. Time when the TuningJob was created. */ + createTime?: string; + /** Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING` state. */ + startTime?: string; + /** Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`. */ + endTime?: string; + /** Output only. Time when the TuningJob was most recently updated. */ + updateTime?: string; + /** Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. */ + error?: GoogleRpcStatus; + /** Optional. The description of the TuningJob. */ + description?: string; + /** The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */ + baseModel?: string; + /** Output only. The tuned model resources associated with this TuningJob. */ + tunedModel?: TunedModel; + /** The pre-tuned model for continuous tuning. */ + preTunedModel?: PreTunedModel; + /** Tuning Spec for Supervised Fine Tuning. */ + supervisedTuningSpec?: SupervisedTuningSpec; + /** Output only. The tuning data statistics associated with this TuningJob. */ + tuningDataStats?: TuningDataStats; + /** Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with the provided encryption key. */ + encryptionSpec?: EncryptionSpec; + /** Tuning Spec for open sourced and third party Partner models. */ + partnerModelTuningSpec?: PartnerModelTuningSpec; + /** Optional. The user-provided path to custom model weights. Set this field to tune a custom model. The path must be a Cloud Storage directory that contains the model weights in .safetensors format along with associated model metadata files. If this field is set, the base_model field must still be set to indicate which base model the custom model is derived from. This feature is only available for open source models. */ + customBaseModel?: string; + /** Output only. The Experiment associated with this TuningJob. */ + experiment?: string; + /** Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. */ + labels?: Record; + /** Optional. Cloud Storage path to the directory where tuning job outputs are written to. This field is only available and required for open source models. */ + outputUri?: string; + /** Output only. The resource name of the PipelineJob associated with the TuningJob. Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`. */ + pipelineJob?: string; + /** The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission on this service account. */ + serviceAccount?: string; + /** Optional. The display name of the TunedModel. The name can be up to 128 characters long and can consist of any UTF-8 characters. */ + tunedModelDisplayName?: string; +} + +/** Tuning mode. */ +export declare enum TuningMode { + /** + * Tuning mode is unspecified. + */ + TUNING_MODE_UNSPECIFIED = "TUNING_MODE_UNSPECIFIED", + /** + * Full fine-tuning mode. + */ + TUNING_MODE_FULL = "TUNING_MODE_FULL", + /** + * PEFT adapter tuning mode. + */ + TUNING_MODE_PEFT_ADAPTER = "TUNING_MODE_PEFT_ADAPTER" +} + +/** A long-running operation. */ +export declare interface TuningOperation { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; +} + +declare class Tunings extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + get: (params: types.GetTuningJobParameters) => Promise; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + list: (params?: types.ListTuningJobsParameters) => Promise>; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + tune: (params: types.CreateTuningJobParameters) => Promise; + private getInternal; + private listInternal; + private tuneInternal; + private tuneMldevInternal; +} + +export declare interface TuningValidationDataset { + /** GCS URI of the file containing validation dataset in JSONL format. */ + gcsUri?: string; + /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */ + vertexDatasetResource?: string; +} + +/** Options about which input is included in the user's turn. */ +export declare enum TurnCoverage { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TURN_COVERAGE_UNSPECIFIED = "TURN_COVERAGE_UNSPECIFIED", + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TURN_INCLUDES_ONLY_ACTIVITY = "TURN_INCLUDES_ONLY_ACTIVITY", + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TURN_INCLUDES_ALL_INPUT = "TURN_INCLUDES_ALL_INPUT" +} + +/** Optional. The type of the data. */ +export declare enum Type { + /** + * Not specified, should not be used. + */ + TYPE_UNSPECIFIED = "TYPE_UNSPECIFIED", + /** + * OpenAPI string type + */ + STRING = "STRING", + /** + * OpenAPI number type + */ + NUMBER = "NUMBER", + /** + * OpenAPI integer type + */ + INTEGER = "INTEGER", + /** + * OpenAPI boolean type + */ + BOOLEAN = "BOOLEAN", + /** + * OpenAPI array type + */ + ARRAY = "ARRAY", + /** + * OpenAPI object type + */ + OBJECT = "OBJECT", + /** + * Null type + */ + NULL = "NULL" +} + +declare namespace types { + export { + createPartFromUri, + createPartFromText, + createPartFromFunctionCall, + createPartFromFunctionResponse, + createPartFromBase64, + createPartFromCodeExecutionResult, + createPartFromExecutableCode, + createUserContent, + createModelContent, + Outcome, + Language, + Type, + HarmCategory, + HarmBlockMethod, + HarmBlockThreshold, + Mode, + AuthType, + ApiSpec, + UrlRetrievalStatus, + FinishReason, + HarmProbability, + HarmSeverity, + BlockedReason, + TrafficType, + Modality, + MediaResolution, + JobState, + TuningMode, + AdapterSize, + FeatureSelectionPreference, + Behavior, + DynamicRetrievalConfigMode, + Environment, + FunctionCallingConfigMode, + SafetyFilterLevel, + PersonGeneration, + ImagePromptLanguage, + MaskReferenceMode, + ControlReferenceType, + SubjectReferenceType, + EditMode, + SegmentMode, + VideoCompressionQuality, + FileState, + FileSource, + MediaModality, + StartSensitivity, + EndSensitivity, + ActivityHandling, + TurnCoverage, + FunctionResponseScheduling, + Scale, + MusicGenerationMode, + LiveMusicPlaybackControl, + VideoMetadata, + Blob_2 as Blob, + FileData, + CodeExecutionResult, + ExecutableCode, + FunctionCall, + FunctionResponse, + Part, + Content, + HttpOptions, + Schema, + ModelSelectionConfig, + SafetySetting, + FunctionDeclaration, + Interval, + GoogleSearch, + DynamicRetrievalConfig, + GoogleSearchRetrieval, + EnterpriseWebSearch, + ApiKeyConfig, + AuthConfigGoogleServiceAccountConfig, + AuthConfigHttpBasicAuthConfig, + AuthConfigOauthConfig, + AuthConfigOidcConfig, + AuthConfig, + GoogleMaps, + UrlContext, + ToolComputerUse, + ApiAuthApiKeyConfig, + ApiAuth, + ExternalApiElasticSearchParams, + ExternalApiSimpleSearchParams, + ExternalApi, + VertexAISearchDataStoreSpec, + VertexAISearch, + VertexRagStoreRagResource, + RagRetrievalConfigFilter, + RagRetrievalConfigHybridSearch, + RagRetrievalConfigRankingLlmRanker, + RagRetrievalConfigRankingRankService, + RagRetrievalConfigRanking, + RagRetrievalConfig, + VertexRagStore, + Retrieval, + ToolCodeExecution, + Tool, + FunctionCallingConfig, + LatLng, + RetrievalConfig, + ToolConfig, + PrebuiltVoiceConfig, + VoiceConfig, + SpeakerVoiceConfig, + MultiSpeakerVoiceConfig, + SpeechConfig, + AutomaticFunctionCallingConfig, + ThinkingConfig, + GenerationConfigRoutingConfigAutoRoutingMode, + GenerationConfigRoutingConfigManualRoutingMode, + GenerationConfigRoutingConfig, + GenerateContentConfig, + GenerateContentParameters, + HttpResponse, + LiveCallbacks, + GoogleTypeDate, + Citation, + CitationMetadata, + UrlMetadata, + UrlContextMetadata, + GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution, + GroundingChunkMapsPlaceAnswerSourcesReviewSnippet, + GroundingChunkMapsPlaceAnswerSources, + GroundingChunkMaps, + RagChunkPageSpan, + RagChunk, + GroundingChunkRetrievedContext, + GroundingChunkWeb, + GroundingChunk, + Segment, + GroundingSupport, + RetrievalMetadata, + SearchEntryPoint, + GroundingMetadata, + LogprobsResultCandidate, + LogprobsResultTopCandidates, + LogprobsResult, + SafetyRating, + Candidate, + GenerateContentResponsePromptFeedback, + ModalityTokenCount, + GenerateContentResponseUsageMetadata, + GenerateContentResponse, + ReferenceImage, + EditImageParameters, + EmbedContentConfig, + EmbedContentParameters, + ContentEmbeddingStatistics, + ContentEmbedding, + EmbedContentMetadata, + EmbedContentResponse, + GenerateImagesConfig, + GenerateImagesParameters, + Image_2 as Image, + SafetyAttributes, + GeneratedImage, + GenerateImagesResponse, + MaskReferenceConfig, + ControlReferenceConfig, + StyleReferenceConfig, + SubjectReferenceConfig, + EditImageConfig, + EditImageResponse, + UpscaleImageResponse, + ProductImage, + RecontextImageSource, + RecontextImageConfig, + RecontextImageParameters, + RecontextImageResponse, + ScribbleImage, + SegmentImageSource, + SegmentImageConfig, + SegmentImageParameters, + EntityLabel, + GeneratedImageMask, + SegmentImageResponse, + GetModelConfig, + GetModelParameters, + Endpoint, + TunedModelInfo, + Checkpoint, + Model, + ListModelsConfig, + ListModelsParameters, + ListModelsResponse, + UpdateModelConfig, + UpdateModelParameters, + DeleteModelConfig, + DeleteModelParameters, + DeleteModelResponse, + GenerationConfigThinkingConfig, + GenerationConfig, + CountTokensConfig, + CountTokensParameters, + CountTokensResponse, + ComputeTokensConfig, + ComputeTokensParameters, + TokensInfo, + ComputeTokensResponse, + Video, + VideoGenerationReferenceImage, + GenerateVideosConfig, + GenerateVideosParameters, + GeneratedVideo, + GenerateVideosResponse, + GetTuningJobConfig, + GetTuningJobParameters, + TunedModelCheckpoint, + TunedModel, + GoogleRpcStatus, + PreTunedModel, + SupervisedHyperParameters, + SupervisedTuningSpec, + DatasetDistributionDistributionBucket, + DatasetDistribution, + DatasetStats, + DistillationDataStats, + GeminiPreferenceExampleCompletion, + GeminiPreferenceExample, + PreferenceOptimizationDataStats, + SupervisedTuningDatasetDistributionDatasetBucket, + SupervisedTuningDatasetDistribution, + SupervisedTuningDataStats, + TuningDataStats, + EncryptionSpec, + PartnerModelTuningSpec, + TuningJob, + ListTuningJobsConfig, + ListTuningJobsParameters, + ListTuningJobsResponse, + TuningExample, + TuningDataset, + TuningValidationDataset, + CreateTuningJobConfig, + CreateTuningJobParametersPrivate, + TuningOperation, + CreateCachedContentConfig, + CreateCachedContentParameters, + CachedContentUsageMetadata, + CachedContent, + GetCachedContentConfig, + GetCachedContentParameters, + DeleteCachedContentConfig, + DeleteCachedContentParameters, + DeleteCachedContentResponse, + UpdateCachedContentConfig, + UpdateCachedContentParameters, + ListCachedContentsConfig, + ListCachedContentsParameters, + ListCachedContentsResponse, + ListFilesConfig, + ListFilesParameters, + FileStatus, + File_2 as File, + ListFilesResponse, + CreateFileConfig, + CreateFileParameters, + CreateFileResponse, + GetFileConfig, + GetFileParameters, + DeleteFileConfig, + DeleteFileParameters, + DeleteFileResponse, + InlinedRequest, + BatchJobSource, + JobError, + InlinedResponse, + BatchJobDestination, + CreateBatchJobConfig, + CreateBatchJobParameters, + BatchJob, + GetBatchJobConfig, + GetBatchJobParameters, + CancelBatchJobConfig, + CancelBatchJobParameters, + ListBatchJobsConfig, + ListBatchJobsParameters, + ListBatchJobsResponse, + DeleteBatchJobConfig, + DeleteBatchJobParameters, + DeleteResourceJob, + GetOperationConfig, + GetOperationParameters, + FetchPredictOperationConfig, + FetchPredictOperationParameters, + TestTableItem, + TestTableFile, + ReplayRequest, + ReplayResponse, + ReplayInteraction, + ReplayFile, + UploadFileConfig, + DownloadFileConfig, + DownloadFileParameters, + UpscaleImageConfig, + UpscaleImageParameters, + RawReferenceImage, + MaskReferenceImage, + ControlReferenceImage, + StyleReferenceImage, + SubjectReferenceImage, + LiveServerSetupComplete, + Transcription, + LiveServerContent, + LiveServerToolCall, + LiveServerToolCallCancellation, + UsageMetadata, + LiveServerGoAway, + LiveServerSessionResumptionUpdate, + LiveServerMessage, + OperationGetParameters, + OperationFromAPIResponseParameters, + Operation, + GenerateVideosOperation, + AutomaticActivityDetection, + RealtimeInputConfig, + SessionResumptionConfig, + SlidingWindow, + ContextWindowCompressionConfig, + AudioTranscriptionConfig, + ProactivityConfig, + LiveClientSetup, + LiveClientContent, + ActivityStart, + ActivityEnd, + LiveClientRealtimeInput, + LiveClientToolResponse, + LiveSendRealtimeInputParameters, + LiveClientMessage, + LiveConnectConfig, + LiveConnectParameters, + CreateChatParameters, + SendMessageParameters, + LiveSendClientContentParameters, + LiveSendToolResponseParameters, + LiveMusicClientSetup, + WeightedPrompt, + LiveMusicClientContent, + LiveMusicGenerationConfig, + LiveMusicClientMessage, + LiveMusicServerSetupComplete, + LiveMusicSourceMetadata, + AudioChunk, + LiveMusicServerContent, + LiveMusicFilteredPrompt, + LiveMusicServerMessage, + LiveMusicCallbacks, + UploadFileParameters, + CallableTool, + CallableToolConfig, + LiveMusicConnectParameters, + LiveMusicSetConfigParameters, + LiveMusicSetWeightedPromptsParameters, + AuthToken, + LiveConnectConstraints, + CreateAuthTokenConfig, + CreateAuthTokenParameters, + CreateTuningJobParameters, + BlobImageUnion, + PartUnion, + PartListUnion, + ContentUnion, + ContentListUnion, + SchemaUnion, + SpeechConfigUnion, + ToolUnion, + ToolListUnion, + DownloadableFileUnion, + BatchJobSourceUnion, + BatchJobDestinationUnion + } +} + +/** Optional parameters for caches.update method. */ +export declare interface UpdateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; +} + +export declare interface UpdateCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Configuration that contains optional parameters. + */ + config?: UpdateCachedContentConfig; +} + +/** Configuration for updating a tuned model. */ +export declare interface UpdateModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + displayName?: string; + description?: string; + defaultCheckpointId?: string; +} + +/** Configuration for updating a tuned model. */ +export declare interface UpdateModelParameters { + model: string; + config?: UpdateModelConfig; +} + +declare interface Uploader { + /** + * Uploads a file to the given upload url. + * + * @param file The file to upload. file is in string type or a Blob. + * @param uploadUrl The upload URL as a string is where the file will be + * uploaded to. The uploadUrl must be a url that was returned by the + * https://generativelanguage.googleapis.com/upload/v1beta/files endpoint + * @param apiClient The ApiClient to use for uploading. + * @return A Promise that resolves to types.File. + */ + upload(file: string | Blob, uploadUrl: string, apiClient: ApiClient): Promise; + /** + * Returns the file's mimeType and the size of a given file. If the file is a + * string path, the file type is determined by the file extension. If the + * file's type cannot be determined, the type will be set to undefined. + * + * @param file The file to get the stat for. Can be a string path or a Blob. + * @return A Promise that resolves to the file stat of the given file. + */ + stat(file: string | Blob): Promise; +} + +/** Used to override the default configuration. */ +export declare interface UploadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */ + name?: string; + /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */ + mimeType?: string; + /** Optional display name of the file. */ + displayName?: string; +} + +/** Parameters for the upload file method. */ +export declare interface UploadFileParameters { + /** The string path to the file to be uploaded or a Blob object. */ + file: string | globalThis.Blob; + /** Configuration that contains optional parameters. */ + config?: UploadFileConfig; +} + +/** Configuration for upscaling an image. + + For more information on this configuration, refer to + the `Imagen API reference documentation + `_. + */ +export declare interface UpscaleImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Whether to include a reason for filtered-out images in the + response. */ + includeRaiReason?: boolean; + /** The image format that the output should be saved as. */ + outputMimeType?: string; + /** The level of compression if the ``output_mime_type`` is + ``image/jpeg``. */ + outputCompressionQuality?: number; + /** Whether to add an image enhancing step before upscaling. + It is expected to suppress the noise and JPEG compression artifacts + from the input image. */ + enhanceInputImage?: boolean; + /** With a higher image preservation factor, the original image + pixels are more respected. With a lower image preservation factor, the + output image will have be more different from the input image, but + with finer details and less noise. */ + imagePreservationFactor?: number; +} + +/** User-facing config UpscaleImageParameters. */ +export declare interface UpscaleImageParameters { + /** The model to use. */ + model: string; + /** The input image to upscale. */ + image: Image_2; + /** The factor to upscale the image (x2 or x4). */ + upscaleFactor: string; + /** Configuration for upscaling. */ + config?: UpscaleImageConfig; +} + +export declare class UpscaleImageResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** Tool to support URL context retrieval. */ +export declare interface UrlContext { +} + +/** Metadata related to url context retrieval tool. */ +export declare interface UrlContextMetadata { + /** List of url context. */ + urlMetadata?: UrlMetadata[]; +} + +/** Context for a single url retrieval. */ +export declare interface UrlMetadata { + /** The URL retrieved by the tool. */ + retrievedUrl?: string; + /** Status of the url retrieval. */ + urlRetrievalStatus?: UrlRetrievalStatus; +} + +/** Status of the url retrieval. */ +export declare enum UrlRetrievalStatus { + /** + * Default value. This value is unused + */ + URL_RETRIEVAL_STATUS_UNSPECIFIED = "URL_RETRIEVAL_STATUS_UNSPECIFIED", + /** + * Url retrieval is successful. + */ + URL_RETRIEVAL_STATUS_SUCCESS = "URL_RETRIEVAL_STATUS_SUCCESS", + /** + * Url retrieval is failed due to error. + */ + URL_RETRIEVAL_STATUS_ERROR = "URL_RETRIEVAL_STATUS_ERROR", + /** + * Url retrieval is failed because the content is behind paywall. + */ + URL_RETRIEVAL_STATUS_PAYWALL = "URL_RETRIEVAL_STATUS_PAYWALL", + /** + * Url retrieval is failed because the content is unsafe. + */ + URL_RETRIEVAL_STATUS_UNSAFE = "URL_RETRIEVAL_STATUS_UNSAFE" +} + +/** Usage metadata about response(s). */ +export declare interface UsageMetadata { + /** Number of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */ + promptTokenCount?: number; + /** Number of tokens in the cached part of the prompt (the cached content). */ + cachedContentTokenCount?: number; + /** Total number of tokens across all the generated response candidates. */ + responseTokenCount?: number; + /** Number of tokens present in tool-use prompt(s). */ + toolUsePromptTokenCount?: number; + /** Number of tokens of thoughts for thinking models. */ + thoughtsTokenCount?: number; + /** Total token count for prompt, response candidates, and tool-use prompts(if present). */ + totalTokenCount?: number; + /** List of modalities that were processed in the request input. */ + promptTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were processed in the cache input. */ + cacheTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were returned in the response. */ + responseTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were processed in the tool-use prompt. */ + toolUsePromptTokensDetails?: ModalityTokenCount[]; + /** Traffic type. This shows whether a request consumes Pay-As-You-Go + or Provisioned Throughput quota. */ + trafficType?: TrafficType; +} + +/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */ +export declare interface VertexAISearch { + /** Specifications that define the specific DataStores to be searched, along with configurations for those data stores. This is only considered for Engines with multiple data stores. It should only be set if engine is used. */ + dataStoreSpecs?: VertexAISearchDataStoreSpec[]; + /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */ + datastore?: string; + /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */ + engine?: string; + /** Optional. Filter strings to be passed to the search API. */ + filter?: string; + /** Optional. Number of search results to return per query. The default value is 10. The maximumm allowed value is 10. */ + maxResults?: number; +} + +/** Define data stores within engine to filter on in a search call and configurations for those data stores. For more information, see https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec */ +export declare interface VertexAISearchDataStoreSpec { + /** Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */ + dataStore?: string; + /** Optional. Filter specification to filter documents in the data store specified by data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata) */ + filter?: string; +} + +/** Retrieve from Vertex RAG Store for grounding. */ +export declare interface VertexRagStore { + /** Optional. Deprecated. Please use rag_resources instead. */ + ragCorpora?: string[]; + /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */ + ragResources?: VertexRagStoreRagResource[]; + /** Optional. The retrieval config for the Rag query. */ + ragRetrievalConfig?: RagRetrievalConfig; + /** Optional. Number of top k results to return from the selected corpora. */ + similarityTopK?: number; + /** Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal Live API, if `store_context` bool is specified, Gemini will leverage it to automatically memorize the interactions between the client and Gemini, and retrieve context when needed to augment the response generation for users' ongoing and future interactions. */ + storeContext?: boolean; + /** Optional. Only return results with vector distance smaller than the threshold. */ + vectorDistanceThreshold?: number; +} + +/** The definition of the Rag resource. */ +export declare interface VertexRagStoreRagResource { + /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */ + ragCorpus?: string; + /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */ + ragFileIds?: string[]; +} + +/** A generated video. */ +export declare interface Video { + /** Path to another storage. */ + uri?: string; + /** Video bytes. + * @remarks Encoded as base64 string. */ + videoBytes?: string; + /** Video encoding, for example "video/mp4". */ + mimeType?: string; +} + +/** Enum that controls the compression quality of the generated videos. */ +export declare enum VideoCompressionQuality { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + OPTIMIZED = "OPTIMIZED", + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + LOSSLESS = "LOSSLESS" +} + +/** A reference image for video generation. */ +export declare interface VideoGenerationReferenceImage { + /** The reference image. + */ + image?: Image_2; + /** The type of the reference image, which defines how the reference + image will be used to generate the video. Supported values are 'asset' + or 'style'. */ + referenceType?: string; +} + +/** Describes how the video in the Part should be used by the model. */ +export declare interface VideoMetadata { + /** The frame rate of the video sent to the model. If not specified, the + default value will be 1.0. The fps range is (0.0, 24.0]. */ + fps?: number; + /** Optional. The end offset of the video. */ + endOffset?: string; + /** Optional. The start offset of the video. */ + startOffset?: string; +} + +/** The configuration for the voice to use. */ +export declare interface VoiceConfig { + /** The configuration for the speaker to use. + */ + prebuiltVoiceConfig?: PrebuiltVoiceConfig; +} + +declare interface WebSocket_2 { + /** + * Connects the socket to the server. + */ + connect(): void; + /** + * Sends a message to the server. + */ + send(message: string): void; + /** + * Closes the socket connection. + */ + close(): void; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +declare interface WebSocketCallbacks { + onopen: () => void; + onerror: (e: any) => void; + onmessage: (e: any) => void; + onclose: (e: any) => void; +} + +declare interface WebSocketFactory { + /** + * Returns a new WebSocket instance. + */ + create(url: string, headers: Record, callbacks: WebSocketCallbacks): WebSocket_2; +} + +/** Maps a prompt to a relative weight to steer music generation. */ +export declare interface WeightedPrompt { + /** Text prompt. */ + text?: string; + /** Weight of the prompt. The weight is used to control the relative + importance of the prompt. Higher weights are more important than lower + weights. + + Weight must not be 0. Weights of all weighted_prompts in this + LiveMusicClientContent message will be normalized. */ + weight?: number; +} + +export { } diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/index.cjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..5b25bfe64ce087af5ce46536015ddedeb5363d41 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/index.cjs @@ -0,0 +1,18717 @@ +'use strict'; + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +function setDefaultBaseUrls(baseUrlParams) { + baseUrlParams.geminiUrl; + baseUrlParams.vertexUrl; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BaseModule { +} +function formatMap(templateString, valueMap) { + // Use a regular expression to find all placeholders in the template string + const regex = /\{([^}]+)\}/g; + // Replace each placeholder with its corresponding value from the valueMap + return templateString.replace(regex, (match, key) => { + if (Object.prototype.hasOwnProperty.call(valueMap, key)) { + const value = valueMap[key]; + // Convert the value to a string if it's not a string already + return value !== undefined && value !== null ? String(value) : ''; + } + else { + // Handle missing keys + throw new Error(`Key '${key}' not found in valueMap.`); + } + }); +} +function setValueByPath(data, keys, value) { + for (let i = 0; i < keys.length - 1; i++) { + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (!(keyName in data)) { + if (Array.isArray(value)) { + data[keyName] = Array.from({ length: value.length }, () => ({})); + } + else { + throw new Error(`Value must be a list given an array path ${key}`); + } + } + if (Array.isArray(data[keyName])) { + const arrayData = data[keyName]; + if (Array.isArray(value)) { + for (let j = 0; j < arrayData.length; j++) { + const entry = arrayData[j]; + setValueByPath(entry, keys.slice(i + 1), value[j]); + } + } + else { + for (const d of arrayData) { + setValueByPath(d, keys.slice(i + 1), value); + } + } + } + return; + } + else if (key.endsWith('[0]')) { + const keyName = key.slice(0, -3); + if (!(keyName in data)) { + data[keyName] = [{}]; + } + const arrayData = data[keyName]; + setValueByPath(arrayData[0], keys.slice(i + 1), value); + return; + } + if (!data[key] || typeof data[key] !== 'object') { + data[key] = {}; + } + data = data[key]; + } + const keyToSet = keys[keys.length - 1]; + const existingData = data[keyToSet]; + if (existingData !== undefined) { + if (!value || + (typeof value === 'object' && Object.keys(value).length === 0)) { + return; + } + if (value === existingData) { + return; + } + if (typeof existingData === 'object' && + typeof value === 'object' && + existingData !== null && + value !== null) { + Object.assign(existingData, value); + } + else { + throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`); + } + } + else { + data[keyToSet] = value; + } +} +function getValueByPath(data, keys) { + try { + if (keys.length === 1 && keys[0] === '_self') { + return data; + } + for (let i = 0; i < keys.length; i++) { + if (typeof data !== 'object' || data === null) { + return undefined; + } + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (keyName in data) { + const arrayData = data[keyName]; + if (!Array.isArray(arrayData)) { + return undefined; + } + return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1))); + } + else { + return undefined; + } + } + else { + data = data[key]; + } + } + return data; + } + catch (error) { + if (error instanceof TypeError) { + return undefined; + } + throw error; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tBytes$1(fromBytes) { + if (typeof fromBytes !== 'string') { + throw new Error('fromImageBytes must be a string'); + } + // TODO(b/389133914): Remove dummy bytes converter. + return fromBytes; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +/** Required. Outcome of the code execution. */ +exports.Outcome = void 0; +(function (Outcome) { + /** + * Unspecified status. This value should not be used. + */ + Outcome["OUTCOME_UNSPECIFIED"] = "OUTCOME_UNSPECIFIED"; + /** + * Code execution completed successfully. + */ + Outcome["OUTCOME_OK"] = "OUTCOME_OK"; + /** + * Code execution finished but with a failure. `stderr` should contain the reason. + */ + Outcome["OUTCOME_FAILED"] = "OUTCOME_FAILED"; + /** + * Code execution ran for too long, and was cancelled. There may or may not be a partial output present. + */ + Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "OUTCOME_DEADLINE_EXCEEDED"; +})(exports.Outcome || (exports.Outcome = {})); +/** Required. Programming language of the `code`. */ +exports.Language = void 0; +(function (Language) { + /** + * Unspecified language. This value should not be used. + */ + Language["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED"; + /** + * Python >= 3.10, with numpy and simpy available. + */ + Language["PYTHON"] = "PYTHON"; +})(exports.Language || (exports.Language = {})); +/** Optional. The type of the data. */ +exports.Type = void 0; +(function (Type) { + /** + * Not specified, should not be used. + */ + Type["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + /** + * OpenAPI string type + */ + Type["STRING"] = "STRING"; + /** + * OpenAPI number type + */ + Type["NUMBER"] = "NUMBER"; + /** + * OpenAPI integer type + */ + Type["INTEGER"] = "INTEGER"; + /** + * OpenAPI boolean type + */ + Type["BOOLEAN"] = "BOOLEAN"; + /** + * OpenAPI array type + */ + Type["ARRAY"] = "ARRAY"; + /** + * OpenAPI object type + */ + Type["OBJECT"] = "OBJECT"; + /** + * Null type + */ + Type["NULL"] = "NULL"; +})(exports.Type || (exports.Type = {})); +/** Required. Harm category. */ +exports.HarmCategory = void 0; +(function (HarmCategory) { + /** + * The harm category is unspecified. + */ + HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + /** + * The harm category is hate speech. + */ + HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + /** + * The harm category is dangerous content. + */ + HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT"; + /** + * The harm category is harassment. + */ + HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + /** + * The harm category is sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY"; + /** + * The harm category is image hate. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE"; + /** + * The harm category is image dangerous content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"; + /** + * The harm category is image harassment. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HARASSMENT"] = "HARM_CATEGORY_IMAGE_HARASSMENT"; + /** + * The harm category is image sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"; +})(exports.HarmCategory || (exports.HarmCategory = {})); +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +exports.HarmBlockMethod = void 0; +(function (HarmBlockMethod) { + /** + * The harm block method is unspecified. + */ + HarmBlockMethod["HARM_BLOCK_METHOD_UNSPECIFIED"] = "HARM_BLOCK_METHOD_UNSPECIFIED"; + /** + * The harm block method uses both probability and severity scores. + */ + HarmBlockMethod["SEVERITY"] = "SEVERITY"; + /** + * The harm block method uses the probability score. + */ + HarmBlockMethod["PROBABILITY"] = "PROBABILITY"; +})(exports.HarmBlockMethod || (exports.HarmBlockMethod = {})); +/** Required. The harm block threshold. */ +exports.HarmBlockThreshold = void 0; +(function (HarmBlockThreshold) { + /** + * Unspecified harm block threshold. + */ + HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + /** + * Block low threshold and above (i.e. block more). + */ + HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + /** + * Block medium threshold and above. + */ + HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + /** + * Block only high threshold (i.e. block less). + */ + HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + /** + * Block none. + */ + HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; + /** + * Turn off the safety filter. + */ + HarmBlockThreshold["OFF"] = "OFF"; +})(exports.HarmBlockThreshold || (exports.HarmBlockThreshold = {})); +/** The mode of the predictor to be used in dynamic retrieval. */ +exports.Mode = void 0; +(function (Mode) { + /** + * Always trigger retrieval. + */ + Mode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + Mode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(exports.Mode || (exports.Mode = {})); +/** Type of auth scheme. */ +exports.AuthType = void 0; +(function (AuthType) { + AuthType["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED"; + /** + * No Auth. + */ + AuthType["NO_AUTH"] = "NO_AUTH"; + /** + * API Key Auth. + */ + AuthType["API_KEY_AUTH"] = "API_KEY_AUTH"; + /** + * HTTP Basic Auth. + */ + AuthType["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH"; + /** + * Google Service Account Auth. + */ + AuthType["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH"; + /** + * OAuth auth. + */ + AuthType["OAUTH"] = "OAUTH"; + /** + * OpenID Connect (OIDC) Auth. + */ + AuthType["OIDC_AUTH"] = "OIDC_AUTH"; +})(exports.AuthType || (exports.AuthType = {})); +/** The API spec that the external API implements. */ +exports.ApiSpec = void 0; +(function (ApiSpec) { + /** + * Unspecified API spec. This value should not be used. + */ + ApiSpec["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED"; + /** + * Simple search API spec. + */ + ApiSpec["SIMPLE_SEARCH"] = "SIMPLE_SEARCH"; + /** + * Elastic search API spec. + */ + ApiSpec["ELASTIC_SEARCH"] = "ELASTIC_SEARCH"; +})(exports.ApiSpec || (exports.ApiSpec = {})); +/** Status of the url retrieval. */ +exports.UrlRetrievalStatus = void 0; +(function (UrlRetrievalStatus) { + /** + * Default value. This value is unused + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = "URL_RETRIEVAL_STATUS_UNSPECIFIED"; + /** + * Url retrieval is successful. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_SUCCESS"] = "URL_RETRIEVAL_STATUS_SUCCESS"; + /** + * Url retrieval is failed due to error. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_ERROR"] = "URL_RETRIEVAL_STATUS_ERROR"; + /** + * Url retrieval is failed because the content is behind paywall. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_PAYWALL"] = "URL_RETRIEVAL_STATUS_PAYWALL"; + /** + * Url retrieval is failed because the content is unsafe. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSAFE"] = "URL_RETRIEVAL_STATUS_UNSAFE"; +})(exports.UrlRetrievalStatus || (exports.UrlRetrievalStatus = {})); +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +exports.FinishReason = void 0; +(function (FinishReason) { + /** + * The finish reason is unspecified. + */ + FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + FinishReason["STOP"] = "STOP"; + /** + * Token generation reached the configured maximum output tokens. + */ + FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + FinishReason["SAFETY"] = "SAFETY"; + /** + * The token generation stopped because of potential recitation. + */ + FinishReason["RECITATION"] = "RECITATION"; + /** + * The token generation stopped because of using an unsupported language. + */ + FinishReason["LANGUAGE"] = "LANGUAGE"; + /** + * All other reasons that stopped the token generation. + */ + FinishReason["OTHER"] = "OTHER"; + /** + * Token generation stopped because the content contains forbidden terms. + */ + FinishReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Token generation stopped for potentially containing prohibited content. + */ + FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). + */ + FinishReason["SPII"] = "SPII"; + /** + * The function call generated by the model is invalid. + */ + FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; + /** + * Token generation stopped because generated images have safety violations. + */ + FinishReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; + /** + * The tool call generated by the model is invalid. + */ + FinishReason["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL"; +})(exports.FinishReason || (exports.FinishReason = {})); +/** Output only. Harm probability levels in the content. */ +exports.HarmProbability = void 0; +(function (HarmProbability) { + /** + * Harm probability unspecified. + */ + HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED"; + /** + * Negligible level of harm. + */ + HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; + /** + * Low level of harm. + */ + HarmProbability["LOW"] = "LOW"; + /** + * Medium level of harm. + */ + HarmProbability["MEDIUM"] = "MEDIUM"; + /** + * High level of harm. + */ + HarmProbability["HIGH"] = "HIGH"; +})(exports.HarmProbability || (exports.HarmProbability = {})); +/** Output only. Harm severity levels in the content. */ +exports.HarmSeverity = void 0; +(function (HarmSeverity) { + /** + * Harm severity unspecified. + */ + HarmSeverity["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED"; + /** + * Negligible level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE"; + /** + * Low level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW"; + /** + * Medium level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM"; + /** + * High level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH"; +})(exports.HarmSeverity || (exports.HarmSeverity = {})); +/** Output only. Blocked reason. */ +exports.BlockedReason = void 0; +(function (BlockedReason) { + /** + * Unspecified blocked reason. + */ + BlockedReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + /** + * Candidates blocked due to safety. + */ + BlockedReason["SAFETY"] = "SAFETY"; + /** + * Candidates blocked due to other reason. + */ + BlockedReason["OTHER"] = "OTHER"; + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BlockedReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Candidates blocked due to prohibited content. + */ + BlockedReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Candidates blocked due to unsafe image generation content. + */ + BlockedReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; +})(exports.BlockedReason || (exports.BlockedReason = {})); +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +exports.TrafficType = void 0; +(function (TrafficType) { + /** + * Unspecified request traffic type. + */ + TrafficType["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED"; + /** + * Type for Pay-As-You-Go traffic. + */ + TrafficType["ON_DEMAND"] = "ON_DEMAND"; + /** + * Type for Provisioned Throughput traffic. + */ + TrafficType["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT"; +})(exports.TrafficType || (exports.TrafficType = {})); +/** Server content modalities. */ +exports.Modality = void 0; +(function (Modality) { + /** + * The modality is unspecified. + */ + Modality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Indicates the model should return text + */ + Modality["TEXT"] = "TEXT"; + /** + * Indicates the model should return images. + */ + Modality["IMAGE"] = "IMAGE"; + /** + * Indicates the model should return audio. + */ + Modality["AUDIO"] = "AUDIO"; +})(exports.Modality || (exports.Modality = {})); +/** The media resolution to use. */ +exports.MediaResolution = void 0; +(function (MediaResolution) { + /** + * Media resolution has not been set + */ + MediaResolution["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED"; + /** + * Media resolution set to low (64 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + /** + * Media resolution set to medium (256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; +})(exports.MediaResolution || (exports.MediaResolution = {})); +/** Job state. */ +exports.JobState = void 0; +(function (JobState) { + /** + * The job state is unspecified. + */ + JobState["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED"; + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JobState["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED"; + /** + * The service is preparing to run the job. + */ + JobState["JOB_STATE_PENDING"] = "JOB_STATE_PENDING"; + /** + * The job is in progress. + */ + JobState["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING"; + /** + * The job completed successfully. + */ + JobState["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED"; + /** + * The job failed. + */ + JobState["JOB_STATE_FAILED"] = "JOB_STATE_FAILED"; + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JobState["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING"; + /** + * The job has been cancelled. + */ + JobState["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED"; + /** + * The job has been stopped, and can be resumed. + */ + JobState["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED"; + /** + * The job has expired. + */ + JobState["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED"; + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JobState["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING"; + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JobState["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED"; +})(exports.JobState || (exports.JobState = {})); +/** Tuning mode. */ +exports.TuningMode = void 0; +(function (TuningMode) { + /** + * Tuning mode is unspecified. + */ + TuningMode["TUNING_MODE_UNSPECIFIED"] = "TUNING_MODE_UNSPECIFIED"; + /** + * Full fine-tuning mode. + */ + TuningMode["TUNING_MODE_FULL"] = "TUNING_MODE_FULL"; + /** + * PEFT adapter tuning mode. + */ + TuningMode["TUNING_MODE_PEFT_ADAPTER"] = "TUNING_MODE_PEFT_ADAPTER"; +})(exports.TuningMode || (exports.TuningMode = {})); +/** Optional. Adapter size for tuning. */ +exports.AdapterSize = void 0; +(function (AdapterSize) { + /** + * Adapter size is unspecified. + */ + AdapterSize["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED"; + /** + * Adapter size 1. + */ + AdapterSize["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE"; + /** + * Adapter size 2. + */ + AdapterSize["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO"; + /** + * Adapter size 4. + */ + AdapterSize["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR"; + /** + * Adapter size 8. + */ + AdapterSize["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT"; + /** + * Adapter size 16. + */ + AdapterSize["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN"; + /** + * Adapter size 32. + */ + AdapterSize["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO"; +})(exports.AdapterSize || (exports.AdapterSize = {})); +/** Options for feature selection preference. */ +exports.FeatureSelectionPreference = void 0; +(function (FeatureSelectionPreference) { + FeatureSelectionPreference["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"; + FeatureSelectionPreference["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY"; + FeatureSelectionPreference["BALANCED"] = "BALANCED"; + FeatureSelectionPreference["PRIORITIZE_COST"] = "PRIORITIZE_COST"; +})(exports.FeatureSelectionPreference || (exports.FeatureSelectionPreference = {})); +/** Defines the function behavior. Defaults to `BLOCKING`. */ +exports.Behavior = void 0; +(function (Behavior) { + /** + * This value is unused. + */ + Behavior["UNSPECIFIED"] = "UNSPECIFIED"; + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + Behavior["BLOCKING"] = "BLOCKING"; + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + Behavior["NON_BLOCKING"] = "NON_BLOCKING"; +})(exports.Behavior || (exports.Behavior = {})); +/** Config for the dynamic retrieval config mode. */ +exports.DynamicRetrievalConfigMode = void 0; +(function (DynamicRetrievalConfigMode) { + /** + * Always trigger retrieval. + */ + DynamicRetrievalConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + DynamicRetrievalConfigMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(exports.DynamicRetrievalConfigMode || (exports.DynamicRetrievalConfigMode = {})); +/** The environment being operated. */ +exports.Environment = void 0; +(function (Environment) { + /** + * Defaults to browser. + */ + Environment["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED"; + /** + * Operates in a web browser. + */ + Environment["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER"; +})(exports.Environment || (exports.Environment = {})); +/** Config for the function calling config mode. */ +exports.FunctionCallingConfigMode = void 0; +(function (FunctionCallingConfigMode) { + /** + * The function calling config mode is unspecified. Should not be used. + */ + FunctionCallingConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + FunctionCallingConfigMode["AUTO"] = "AUTO"; + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + FunctionCallingConfigMode["ANY"] = "ANY"; + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + FunctionCallingConfigMode["NONE"] = "NONE"; +})(exports.FunctionCallingConfigMode || (exports.FunctionCallingConfigMode = {})); +/** Enum that controls the safety filter level for objectionable content. */ +exports.SafetyFilterLevel = void 0; +(function (SafetyFilterLevel) { + SafetyFilterLevel["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + SafetyFilterLevel["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + SafetyFilterLevel["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + SafetyFilterLevel["BLOCK_NONE"] = "BLOCK_NONE"; +})(exports.SafetyFilterLevel || (exports.SafetyFilterLevel = {})); +/** Enum that controls the generation of people. */ +exports.PersonGeneration = void 0; +(function (PersonGeneration) { + /** + * Block generation of images of people. + */ + PersonGeneration["DONT_ALLOW"] = "DONT_ALLOW"; + /** + * Generate images of adults, but not children. + */ + PersonGeneration["ALLOW_ADULT"] = "ALLOW_ADULT"; + /** + * Generate images that include adults and children. + */ + PersonGeneration["ALLOW_ALL"] = "ALLOW_ALL"; +})(exports.PersonGeneration || (exports.PersonGeneration = {})); +/** Enum that specifies the language of the text in the prompt. */ +exports.ImagePromptLanguage = void 0; +(function (ImagePromptLanguage) { + /** + * Auto-detect the language. + */ + ImagePromptLanguage["auto"] = "auto"; + /** + * English + */ + ImagePromptLanguage["en"] = "en"; + /** + * Japanese + */ + ImagePromptLanguage["ja"] = "ja"; + /** + * Korean + */ + ImagePromptLanguage["ko"] = "ko"; + /** + * Hindi + */ + ImagePromptLanguage["hi"] = "hi"; + /** + * Chinese + */ + ImagePromptLanguage["zh"] = "zh"; + /** + * Portuguese + */ + ImagePromptLanguage["pt"] = "pt"; + /** + * Spanish + */ + ImagePromptLanguage["es"] = "es"; +})(exports.ImagePromptLanguage || (exports.ImagePromptLanguage = {})); +/** Enum representing the mask mode of a mask reference image. */ +exports.MaskReferenceMode = void 0; +(function (MaskReferenceMode) { + MaskReferenceMode["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT"; + MaskReferenceMode["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED"; + MaskReferenceMode["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND"; + MaskReferenceMode["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND"; + MaskReferenceMode["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC"; +})(exports.MaskReferenceMode || (exports.MaskReferenceMode = {})); +/** Enum representing the control type of a control reference image. */ +exports.ControlReferenceType = void 0; +(function (ControlReferenceType) { + ControlReferenceType["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT"; + ControlReferenceType["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY"; + ControlReferenceType["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE"; + ControlReferenceType["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH"; +})(exports.ControlReferenceType || (exports.ControlReferenceType = {})); +/** Enum representing the subject type of a subject reference image. */ +exports.SubjectReferenceType = void 0; +(function (SubjectReferenceType) { + SubjectReferenceType["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT"; + SubjectReferenceType["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON"; + SubjectReferenceType["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL"; + SubjectReferenceType["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT"; +})(exports.SubjectReferenceType || (exports.SubjectReferenceType = {})); +/** Enum representing the Imagen 3 Edit mode. */ +exports.EditMode = void 0; +(function (EditMode) { + EditMode["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT"; + EditMode["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL"; + EditMode["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION"; + EditMode["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT"; + EditMode["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING"; + EditMode["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE"; + EditMode["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP"; + EditMode["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE"; +})(exports.EditMode || (exports.EditMode = {})); +/** Enum that represents the segmentation mode. */ +exports.SegmentMode = void 0; +(function (SegmentMode) { + SegmentMode["FOREGROUND"] = "FOREGROUND"; + SegmentMode["BACKGROUND"] = "BACKGROUND"; + SegmentMode["PROMPT"] = "PROMPT"; + SegmentMode["SEMANTIC"] = "SEMANTIC"; + SegmentMode["INTERACTIVE"] = "INTERACTIVE"; +})(exports.SegmentMode || (exports.SegmentMode = {})); +/** Enum that controls the compression quality of the generated videos. */ +exports.VideoCompressionQuality = void 0; +(function (VideoCompressionQuality) { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + VideoCompressionQuality["OPTIMIZED"] = "OPTIMIZED"; + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + VideoCompressionQuality["LOSSLESS"] = "LOSSLESS"; +})(exports.VideoCompressionQuality || (exports.VideoCompressionQuality = {})); +/** State for the lifecycle of a File. */ +exports.FileState = void 0; +(function (FileState) { + FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + FileState["PROCESSING"] = "PROCESSING"; + FileState["ACTIVE"] = "ACTIVE"; + FileState["FAILED"] = "FAILED"; +})(exports.FileState || (exports.FileState = {})); +/** Source of the File. */ +exports.FileSource = void 0; +(function (FileSource) { + FileSource["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED"; + FileSource["UPLOADED"] = "UPLOADED"; + FileSource["GENERATED"] = "GENERATED"; +})(exports.FileSource || (exports.FileSource = {})); +/** Server content modalities. */ +exports.MediaModality = void 0; +(function (MediaModality) { + /** + * The modality is unspecified. + */ + MediaModality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Plain text. + */ + MediaModality["TEXT"] = "TEXT"; + /** + * Images. + */ + MediaModality["IMAGE"] = "IMAGE"; + /** + * Video. + */ + MediaModality["VIDEO"] = "VIDEO"; + /** + * Audio. + */ + MediaModality["AUDIO"] = "AUDIO"; + /** + * Document, e.g. PDF. + */ + MediaModality["DOCUMENT"] = "DOCUMENT"; +})(exports.MediaModality || (exports.MediaModality = {})); +/** Start of speech sensitivity. */ +exports.StartSensitivity = void 0; +(function (StartSensitivity) { + /** + * The default is START_SENSITIVITY_LOW. + */ + StartSensitivity["START_SENSITIVITY_UNSPECIFIED"] = "START_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection will detect the start of speech more often. + */ + StartSensitivity["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH"; + /** + * Automatic detection will detect the start of speech less often. + */ + StartSensitivity["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW"; +})(exports.StartSensitivity || (exports.StartSensitivity = {})); +/** End of speech sensitivity. */ +exports.EndSensitivity = void 0; +(function (EndSensitivity) { + /** + * The default is END_SENSITIVITY_LOW. + */ + EndSensitivity["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection ends speech more often. + */ + EndSensitivity["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH"; + /** + * Automatic detection ends speech less often. + */ + EndSensitivity["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW"; +})(exports.EndSensitivity || (exports.EndSensitivity = {})); +/** The different ways of handling user activity. */ +exports.ActivityHandling = void 0; +(function (ActivityHandling) { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ActivityHandling["ACTIVITY_HANDLING_UNSPECIFIED"] = "ACTIVITY_HANDLING_UNSPECIFIED"; + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + ActivityHandling["START_OF_ACTIVITY_INTERRUPTS"] = "START_OF_ACTIVITY_INTERRUPTS"; + /** + * The model's response will not be interrupted. + */ + ActivityHandling["NO_INTERRUPTION"] = "NO_INTERRUPTION"; +})(exports.ActivityHandling || (exports.ActivityHandling = {})); +/** Options about which input is included in the user's turn. */ +exports.TurnCoverage = void 0; +(function (TurnCoverage) { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TurnCoverage["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED"; + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TurnCoverage["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY"; + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TurnCoverage["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT"; +})(exports.TurnCoverage || (exports.TurnCoverage = {})); +/** Specifies how the response should be scheduled in the conversation. */ +exports.FunctionResponseScheduling = void 0; +(function (FunctionResponseScheduling) { + /** + * This value is unused. + */ + FunctionResponseScheduling["SCHEDULING_UNSPECIFIED"] = "SCHEDULING_UNSPECIFIED"; + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + FunctionResponseScheduling["SILENT"] = "SILENT"; + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + FunctionResponseScheduling["WHEN_IDLE"] = "WHEN_IDLE"; + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + FunctionResponseScheduling["INTERRUPT"] = "INTERRUPT"; +})(exports.FunctionResponseScheduling || (exports.FunctionResponseScheduling = {})); +/** Scale of the generated music. */ +exports.Scale = void 0; +(function (Scale) { + /** + * Default value. This value is unused. + */ + Scale["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED"; + /** + * C major or A minor. + */ + Scale["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR"; + /** + * Db major or Bb minor. + */ + Scale["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR"; + /** + * D major or B minor. + */ + Scale["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR"; + /** + * Eb major or C minor + */ + Scale["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR"; + /** + * E major or Db minor. + */ + Scale["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR"; + /** + * F major or D minor. + */ + Scale["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR"; + /** + * Gb major or Eb minor. + */ + Scale["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR"; + /** + * G major or E minor. + */ + Scale["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR"; + /** + * Ab major or F minor. + */ + Scale["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR"; + /** + * A major or Gb minor. + */ + Scale["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR"; + /** + * Bb major or G minor. + */ + Scale["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR"; + /** + * B major or Ab minor. + */ + Scale["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR"; +})(exports.Scale || (exports.Scale = {})); +/** The mode of music generation. */ +exports.MusicGenerationMode = void 0; +(function (MusicGenerationMode) { + /** + * Rely on the server default generation mode. + */ + MusicGenerationMode["MUSIC_GENERATION_MODE_UNSPECIFIED"] = "MUSIC_GENERATION_MODE_UNSPECIFIED"; + /** + * Steer text prompts to regions of latent space with higher quality + music. + */ + MusicGenerationMode["QUALITY"] = "QUALITY"; + /** + * Steer text prompts to regions of latent space with a larger + diversity of music. + */ + MusicGenerationMode["DIVERSITY"] = "DIVERSITY"; + /** + * Steer text prompts to regions of latent space more likely to + generate music with vocals. + */ + MusicGenerationMode["VOCALIZATION"] = "VOCALIZATION"; +})(exports.MusicGenerationMode || (exports.MusicGenerationMode = {})); +/** The playback control signal to apply to the music generation. */ +exports.LiveMusicPlaybackControl = void 0; +(function (LiveMusicPlaybackControl) { + /** + * This value is unused. + */ + LiveMusicPlaybackControl["PLAYBACK_CONTROL_UNSPECIFIED"] = "PLAYBACK_CONTROL_UNSPECIFIED"; + /** + * Start generating the music. + */ + LiveMusicPlaybackControl["PLAY"] = "PLAY"; + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + LiveMusicPlaybackControl["PAUSE"] = "PAUSE"; + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + LiveMusicPlaybackControl["STOP"] = "STOP"; + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + LiveMusicPlaybackControl["RESET_CONTEXT"] = "RESET_CONTEXT"; +})(exports.LiveMusicPlaybackControl || (exports.LiveMusicPlaybackControl = {})); +/** A function response. */ +class FunctionResponse { +} +/** + * Creates a `Part` object from a `URI` string. + */ +function createPartFromUri(uri, mimeType) { + return { + fileData: { + fileUri: uri, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from a `text` string. + */ +function createPartFromText(text) { + return { + text: text, + }; +} +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +function createPartFromFunctionCall(name, args) { + return { + functionCall: { + name: name, + args: args, + }, + }; +} +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +function createPartFromFunctionResponse(id, name, response) { + return { + functionResponse: { + id: id, + name: name, + response: response, + }, + }; +} +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +function createPartFromBase64(data, mimeType) { + return { + inlineData: { + data: data, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +function createPartFromCodeExecutionResult(outcome, output) { + return { + codeExecutionResult: { + outcome: outcome, + output: output, + }, + }; +} +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +function createPartFromExecutableCode(code, language) { + return { + executableCode: { + code: code, + language: language, + }, + }; +} +function _isPart(obj) { + if (typeof obj === 'object' && obj !== null) { + return ('fileData' in obj || + 'text' in obj || + 'functionCall' in obj || + 'functionResponse' in obj || + 'inlineData' in obj || + 'videoMetadata' in obj || + 'codeExecutionResult' in obj || + 'executableCode' in obj); + } + return false; +} +function _toParts(partOrString) { + const parts = []; + if (typeof partOrString === 'string') { + parts.push(createPartFromText(partOrString)); + } + else if (_isPart(partOrString)) { + parts.push(partOrString); + } + else if (Array.isArray(partOrString)) { + if (partOrString.length === 0) { + throw new Error('partOrString cannot be an empty array'); + } + for (const part of partOrString) { + if (typeof part === 'string') { + parts.push(createPartFromText(part)); + } + else if (_isPart(part)) { + parts.push(part); + } + else { + throw new Error('element in PartUnion must be a Part object or string'); + } + } + } + else { + throw new Error('partOrString must be a Part object, string, or array'); + } + return parts; +} +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +function createUserContent(partOrString) { + return { + role: 'user', + parts: _toParts(partOrString), + }; +} +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +function createModelContent(partOrString) { + return { + role: 'model', + parts: _toParts(partOrString), + }; +} +/** A wrapper class for the http response. */ +class HttpResponse { + constructor(response) { + // Process the headers. + const headers = {}; + for (const pair of response.headers.entries()) { + headers[pair[0]] = pair[1]; + } + this.headers = headers; + // Keep the original response. + this.responseInternal = response; + } + json() { + return this.responseInternal.json(); + } +} +/** Content filter results for a prompt sent in the request. */ +class GenerateContentResponsePromptFeedback { +} +/** Usage metadata about response(s). */ +class GenerateContentResponseUsageMetadata { +} +/** Response message for PredictionService.GenerateContent. */ +class GenerateContentResponse { + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning text from the first one.'); + } + let text = ''; + let anyTextPartText = false; + const nonTextParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + (fieldValue !== null || fieldValue !== undefined)) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartText = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartText ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning data from the first one.'); + } + let data = ''; + const nonDataParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && + (fieldValue !== null || fieldValue !== undefined)) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning function calls from the first one.'); + } + const functionCalls = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.functionCall).map((part) => part.functionCall).filter((functionCall) => functionCall !== undefined); + if ((functionCalls === null || functionCalls === void 0 ? void 0 : functionCalls.length) === 0) { + return undefined; + } + return functionCalls; + } + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning executable code from the first one.'); + } + const executableCode = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.executableCode).map((part) => part.executableCode).filter((executableCode) => executableCode !== undefined); + if ((executableCode === null || executableCode === void 0 ? void 0 : executableCode.length) === 0) { + return undefined; + } + return (_j = executableCode === null || executableCode === void 0 ? void 0 : executableCode[0]) === null || _j === void 0 ? void 0 : _j.code; + } + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning code execution result from the first one.'); + } + const codeExecutionResult = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.codeExecutionResult).map((part) => part.codeExecutionResult).filter((codeExecutionResult) => codeExecutionResult !== undefined); + if ((codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult.length) === 0) { + return undefined; + } + return (_j = codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult[0]) === null || _j === void 0 ? void 0 : _j.output; + } +} +/** Response for the embed_content method. */ +class EmbedContentResponse { +} +/** The output images response. */ +class GenerateImagesResponse { +} +/** Response for the request to edit an image. */ +class EditImageResponse { +} +class UpscaleImageResponse { +} +/** The output images response. */ +class RecontextImageResponse { +} +/** The output images response. */ +class SegmentImageResponse { +} +class ListModelsResponse { +} +class DeleteModelResponse { +} +/** Response for counting tokens. */ +class CountTokensResponse { +} +/** Response for computing tokens. */ +class ComputeTokensResponse { +} +/** Response with generated videos. */ +class GenerateVideosResponse { +} +/** Response for the list tuning jobs method. */ +class ListTuningJobsResponse { +} +/** Empty response for caches.delete method. */ +class DeleteCachedContentResponse { +} +class ListCachedContentsResponse { +} +/** Response for the list files method. */ +class ListFilesResponse { +} +/** Response for the create file method. */ +class CreateFileResponse { +} +/** Response for the delete file method. */ +class DeleteFileResponse { +} +/** Config for `inlined_responses` parameter. */ +class InlinedResponse { +} +/** Config for batches.list return value. */ +class ListBatchJobsResponse { +} +/** Represents a single response in a replay. */ +class ReplayResponse { +} +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +class RawReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_RAW', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + }; + return referenceImageAPI; + } +} +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +class MaskReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_MASK', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + maskImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +class ControlReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_CONTROL', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + controlImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +class StyleReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_STYLE', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + styleImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +class SubjectReferenceImage { + /* Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_SUBJECT', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + subjectImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** Response message for API call. */ +class LiveServerMessage { + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text() { + var _a, _b, _c; + let text = ''; + let anyTextPartFound = false; + const nonTextParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + fieldValue !== null) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartFound = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartFound ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c; + let data = ''; + const nonDataParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && fieldValue !== null) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } +} +/** A video generation long-running operation. */ +class GenerateVideosOperation { + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }) { + const operation = new GenerateVideosOperation(); + operation.name = apiResponse['name']; + operation.metadata = apiResponse['metadata']; + operation.done = apiResponse['done']; + operation.error = apiResponse['error']; + if (isVertexAI) { + const response = apiResponse['response']; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const responseVideos = response['videos']; + operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => { + return { + video: { + uri: generatedVideo['gcsUri'], + videoBytes: generatedVideo['bytesBase64Encoded'] + ? tBytes$1(generatedVideo['bytesBase64Encoded']) + : undefined, + mimeType: generatedVideo['mimeType'], + }, + }; + }); + operationResponse.raiMediaFilteredCount = response['raiMediaFilteredCount']; + operationResponse.raiMediaFilteredReasons = response['raiMediaFilteredReasons']; + operation.response = operationResponse; + } + } + else { + const response = apiResponse['response']; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const generatedVideoResponse = response['generateVideoResponse']; + const responseVideos = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['generatedSamples']; + operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => { + const video = generatedVideo['video']; + return { + video: { + uri: video === null || video === void 0 ? void 0 : video['uri'], + videoBytes: (video === null || video === void 0 ? void 0 : video['encodedVideo']) + ? tBytes$1(video === null || video === void 0 ? void 0 : video['encodedVideo']) + : undefined, + mimeType: generatedVideo['encoding'], + }, + }; + }); + operationResponse.raiMediaFilteredCount = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['raiMediaFilteredCount']; + operationResponse.raiMediaFilteredReasons = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['raiMediaFilteredReasons']; + operation.response = operationResponse; + } + } + return operation; + } +} +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +class LiveClientToolResponse { +} +/** Parameters for sending tool responses to the live API. */ +class LiveSendToolResponseParameters { + constructor() { + /** Tool responses to send to the session. */ + this.functionResponses = []; + } +} +/** Response message for the LiveMusicClientMessage call. */ +class LiveMusicServerMessage { + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk() { + if (this.serverContent && + this.serverContent.audioChunks && + this.serverContent.audioChunks.length > 0) { + return this.serverContent.audioChunks[0]; + } + return undefined; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tModel(apiClient, model) { + if (!model || typeof model !== 'string') { + throw new Error('model is required and must be a string'); + } + if (apiClient.isVertexAI()) { + if (model.startsWith('publishers/') || + model.startsWith('projects/') || + model.startsWith('models/')) { + return model; + } + else if (model.indexOf('/') >= 0) { + const parts = model.split('/', 2); + return `publishers/${parts[0]}/models/${parts[1]}`; + } + else { + return `publishers/google/models/${model}`; + } + } + else { + if (model.startsWith('models/') || model.startsWith('tunedModels/')) { + return model; + } + else { + return `models/${model}`; + } + } +} +function tCachesModel(apiClient, model) { + const transformedModel = tModel(apiClient, model); + if (!transformedModel) { + return ''; + } + if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) { + // vertex caches only support model name start with projects. + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`; + } + else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) { + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`; + } + else { + return transformedModel; + } +} +function tBlobs(blobs) { + if (Array.isArray(blobs)) { + return blobs.map((blob) => tBlob(blob)); + } + else { + return [tBlob(blobs)]; + } +} +function tBlob(blob) { + if (typeof blob === 'object' && blob !== null) { + return blob; + } + throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof blob}`); +} +function tImageBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('image/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tAudioBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('audio/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tPart(origin) { + if (origin === null || origin === undefined) { + throw new Error('PartUnion is required'); + } + if (typeof origin === 'object') { + return origin; + } + if (typeof origin === 'string') { + return { text: origin }; + } + throw new Error(`Unsupported part type: ${typeof origin}`); +} +function tParts(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('PartListUnion is required'); + } + if (Array.isArray(origin)) { + return origin.map((item) => tPart(item)); + } + return [tPart(origin)]; +} +function _isContent(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'parts' in origin && + Array.isArray(origin.parts)); +} +function _isFunctionCallPart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionCall' in origin); +} +function _isFunctionResponsePart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionResponse' in origin); +} +function tContent(origin) { + if (origin === null || origin === undefined) { + throw new Error('ContentUnion is required'); + } + if (_isContent(origin)) { + // _isContent is a utility function that checks if the + // origin is a Content. + return origin; + } + return { + role: 'user', + parts: tParts(origin), + }; +} +function tContentsForEmbed(apiClient, origin) { + if (!origin) { + return []; + } + if (apiClient.isVertexAI() && Array.isArray(origin)) { + return origin.flatMap((item) => { + const content = tContent(item); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + }); + } + else if (apiClient.isVertexAI()) { + const content = tContent(origin); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + } + if (Array.isArray(origin)) { + return origin.map((item) => tContent(item)); + } + return [tContent(origin)]; +} +function tContents(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('contents are required'); + } + if (!Array.isArray(origin)) { + // If it's not an array, it's a single content or a single PartUnion. + if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them'); + } + return [tContent(origin)]; + } + const result = []; + const accumulatedParts = []; + const isContentArray = _isContent(origin[0]); + for (const item of origin) { + const isContent = _isContent(item); + if (isContent != isContentArray) { + throw new Error('Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them'); + } + if (isContent) { + // `isContent` contains the result of _isContent, which is a utility + // function that checks if the item is a Content. + result.push(item); + } + else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them'); + } + else { + accumulatedParts.push(item); + } + } + if (!isContentArray) { + result.push({ role: 'user', parts: tParts(accumulatedParts) }); + } + return result; +} +/* +Transform the type field from an array of types to an array of anyOf fields. +Example: + {type: ['STRING', 'NUMBER']} +will be transformed to + {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]} +*/ +function flattenTypeArrayToAnyOf(typeList, resultingSchema) { + if (typeList.includes('null')) { + resultingSchema['nullable'] = true; + } + const listWithoutNull = typeList.filter((type) => type !== 'null'); + if (listWithoutNull.length === 1) { + resultingSchema['type'] = Object.values(exports.Type).includes(listWithoutNull[0].toUpperCase()) + ? listWithoutNull[0].toUpperCase() + : exports.Type.TYPE_UNSPECIFIED; + } + else { + resultingSchema['anyOf'] = []; + for (const i of listWithoutNull) { + resultingSchema['anyOf'].push({ + 'type': Object.values(exports.Type).includes(i.toUpperCase()) + ? i.toUpperCase() + : exports.Type.TYPE_UNSPECIFIED, + }); + } + } +} +function processJsonSchema(_jsonSchema) { + const genAISchema = {}; + const schemaFieldNames = ['items']; + const listSchemaFieldNames = ['anyOf']; + const dictSchemaFieldNames = ['properties']; + if (_jsonSchema['type'] && _jsonSchema['anyOf']) { + throw new Error('type and anyOf cannot be both populated.'); + } + /* + This is to handle the nullable array or object. The _jsonSchema will + be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The + logic is to check if anyOf has 2 elements and one of the element is null, + if so, the anyOf field is unnecessary, so we need to get rid of the anyOf + field and make the schema nullable. Then use the other element as the new + _jsonSchema for processing. This is because the backend doesn't have a null + type. + This has to be checked before we process any other fields. + For example: + const objectNullable = z.object({ + nullableArray: z.array(z.string()).nullable(), + }); + Will have the raw _jsonSchema as: + { + type: 'OBJECT', + properties: { + nullableArray: { + anyOf: [ + {type: 'null'}, + { + type: 'array', + items: {type: 'string'}, + }, + ], + } + }, + required: [ 'nullableArray' ], + } + Will result in following schema compatible with Gemini API: + { + type: 'OBJECT', + properties: { + nullableArray: { + nullable: true, + type: 'ARRAY', + items: {type: 'string'}, + } + }, + required: [ 'nullableArray' ], + } + */ + const incomingAnyOf = _jsonSchema['anyOf']; + if (incomingAnyOf != null && incomingAnyOf.length == 2) { + if (incomingAnyOf[0]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[1]; + } + else if (incomingAnyOf[1]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[0]; + } + } + if (_jsonSchema['type'] instanceof Array) { + flattenTypeArrayToAnyOf(_jsonSchema['type'], genAISchema); + } + for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) { + // Skip if the fieldvalue is undefined or null. + if (fieldValue == null) { + continue; + } + if (fieldName == 'type') { + if (fieldValue === 'null') { + throw new Error('type: null can not be the only possible type for the field.'); + } + if (fieldValue instanceof Array) { + // we have already handled the type field with array of types in the + // beginning of this function. + continue; + } + genAISchema['type'] = Object.values(exports.Type).includes(fieldValue.toUpperCase()) + ? fieldValue.toUpperCase() + : exports.Type.TYPE_UNSPECIFIED; + } + else if (schemaFieldNames.includes(fieldName)) { + genAISchema[fieldName] = + processJsonSchema(fieldValue); + } + else if (listSchemaFieldNames.includes(fieldName)) { + const listSchemaFieldValue = []; + for (const item of fieldValue) { + if (item['type'] == 'null') { + genAISchema['nullable'] = true; + continue; + } + listSchemaFieldValue.push(processJsonSchema(item)); + } + genAISchema[fieldName] = + listSchemaFieldValue; + } + else if (dictSchemaFieldNames.includes(fieldName)) { + const dictSchemaFieldValue = {}; + for (const [key, value] of Object.entries(fieldValue)) { + dictSchemaFieldValue[key] = processJsonSchema(value); + } + genAISchema[fieldName] = + dictSchemaFieldValue; + } + else { + // additionalProperties is not included in JSONSchema, skipping it. + if (fieldName === 'additionalProperties') { + continue; + } + genAISchema[fieldName] = fieldValue; + } + } + return genAISchema; +} +// we take the unknown in the schema field because we want enable user to pass +// the output of major schema declaration tools without casting. Tools such as +// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type +// or object, see details in +// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7 +// typebox can return unknown, see details in +// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35 +// Note: proper json schemas with the $schema field set never arrive to this +// transformer. Schemas with $schema are routed to the equivalent API json +// schema field. +function tSchema(schema) { + return processJsonSchema(schema); +} +function tSpeechConfig(speechConfig) { + if (typeof speechConfig === 'object') { + return speechConfig; + } + else if (typeof speechConfig === 'string') { + return { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: speechConfig, + }, + }, + }; + } + else { + throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`); + } +} +function tLiveSpeechConfig(speechConfig) { + if ('multiSpeakerVoiceConfig' in speechConfig) { + throw new Error('multiSpeakerVoiceConfig is not supported in the live API.'); + } + return speechConfig; +} +function tTool(tool) { + if (tool.functionDeclarations) { + for (const functionDeclaration of tool.functionDeclarations) { + if (functionDeclaration.parameters) { + if (!Object.keys(functionDeclaration.parameters).includes('$schema')) { + functionDeclaration.parameters = processJsonSchema(functionDeclaration.parameters); + } + else { + if (!functionDeclaration.parametersJsonSchema) { + functionDeclaration.parametersJsonSchema = + functionDeclaration.parameters; + delete functionDeclaration.parameters; + } + } + } + if (functionDeclaration.response) { + if (!Object.keys(functionDeclaration.response).includes('$schema')) { + functionDeclaration.response = processJsonSchema(functionDeclaration.response); + } + else { + if (!functionDeclaration.responseJsonSchema) { + functionDeclaration.responseJsonSchema = + functionDeclaration.response; + delete functionDeclaration.response; + } + } + } + } + } + return tool; +} +function tTools(tools) { + // Check if the incoming type is defined. + if (tools === undefined || tools === null) { + throw new Error('tools is required'); + } + if (!Array.isArray(tools)) { + throw new Error('tools is required and must be an array of Tools'); + } + const result = []; + for (const tool of tools) { + result.push(tool); + } + return result; +} +/** + * Prepends resource name with project, location, resource_prefix if needed. + * + * @param client The API client. + * @param resourceName The resource name. + * @param resourcePrefix The resource prefix. + * @param splitsAfterPrefix The number of splits after the prefix. + * @returns The completed resource name. + * + * Examples: + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/bar/locations/us-west1/cachedContents/123' + * ``` + * + * ``` + * resource_name = 'projects/foo/locations/us-central1/cachedContents/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/foo/locations/us-central1/cachedContents/123' + * ``` + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns 'cachedContents/123' + * ``` + * + * ``` + * resource_name = 'some/wrong/cachedContents/resource/name/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * # client.vertexai = True + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * -> 'some/wrong/resource/name/123' + * ``` + */ +function resourceName(client, resourceName, resourcePrefix, splitsAfterPrefix = 1) { + const shouldAppendPrefix = !resourceName.startsWith(`${resourcePrefix}/`) && + resourceName.split('/').length === splitsAfterPrefix; + if (client.isVertexAI()) { + if (resourceName.startsWith('projects/')) { + return resourceName; + } + else if (resourceName.startsWith('locations/')) { + return `projects/${client.getProject()}/${resourceName}`; + } + else if (resourceName.startsWith(`${resourcePrefix}/`)) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`; + } + else if (shouldAppendPrefix) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`; + } + else { + return resourceName; + } + } + if (shouldAppendPrefix) { + return `${resourcePrefix}/${resourceName}`; + } + return resourceName; +} +function tCachedContentName(apiClient, name) { + if (typeof name !== 'string') { + throw new Error('name must be a string'); + } + return resourceName(apiClient, name, 'cachedContents'); +} +function tTuningJobStatus(status) { + switch (status) { + case 'STATE_UNSPECIFIED': + return 'JOB_STATE_UNSPECIFIED'; + case 'CREATING': + return 'JOB_STATE_RUNNING'; + case 'ACTIVE': + return 'JOB_STATE_SUCCEEDED'; + case 'FAILED': + return 'JOB_STATE_FAILED'; + default: + return status; + } +} +function tBytes(fromImageBytes) { + return tBytes$1(fromImageBytes); +} +function _isFile(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'name' in origin); +} +function isGeneratedVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'video' in origin); +} +function isVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'uri' in origin); +} +function tFileName(fromName) { + var _a; + let name; + if (_isFile(fromName)) { + name = fromName.name; + } + if (isVideo(fromName)) { + name = fromName.uri; + if (name === undefined) { + return undefined; + } + } + if (isGeneratedVideo(fromName)) { + name = (_a = fromName.video) === null || _a === void 0 ? void 0 : _a.uri; + if (name === undefined) { + return undefined; + } + } + if (typeof fromName === 'string') { + name = fromName; + } + if (name === undefined) { + throw new Error('Could not extract file name from the provided input.'); + } + if (name.startsWith('https://')) { + const suffix = name.split('files/')[1]; + const match = suffix.match(/[a-z0-9]+/); + if (match === null) { + throw new Error(`Could not extract file name from URI ${name}`); + } + name = match[0]; + } + else if (name.startsWith('files/')) { + name = name.split('files/')[1]; + } + return name; +} +function tModelsUrl(apiClient, baseModels) { + let res; + if (apiClient.isVertexAI()) { + res = baseModels ? 'publishers/google/models' : 'models'; + } + else { + res = baseModels ? 'models' : 'tunedModels'; + } + return res; +} +function tExtractModels(response) { + for (const key of ['models', 'tunedModels', 'publisherModels']) { + if (hasField(response, key)) { + return response[key]; + } + } + return []; +} +function hasField(data, fieldName) { + return data !== null && typeof data === 'object' && fieldName in data; +} +function mcpToGeminiTool(mcpTool, config = {}) { + const mcpToolSchema = mcpTool; + const functionDeclaration = { + name: mcpToolSchema['name'], + description: mcpToolSchema['description'], + parametersJsonSchema: mcpToolSchema['inputSchema'], + }; + if (config.behavior) { + functionDeclaration['behavior'] = config.behavior; + } + const geminiTool = { + functionDeclarations: [ + functionDeclaration, + ], + }; + return geminiTool; +} +/** + * Converts a list of MCP tools to a single Gemini tool with a list of function + * declarations. + */ +function mcpToolsToGeminiTool(mcpTools, config = {}) { + const functionDeclarations = []; + const toolNames = new Set(); + for (const mcpTool of mcpTools) { + const mcpToolName = mcpTool.name; + if (toolNames.has(mcpToolName)) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + toolNames.add(mcpToolName); + const geminiTool = mcpToGeminiTool(mcpTool, config); + if (geminiTool.functionDeclarations) { + functionDeclarations.push(...geminiTool.functionDeclarations); + } + } + return { functionDeclarations: functionDeclarations }; +} +// Transforms a source input into a BatchJobSource object with validation. +function tBatchJobSource(apiClient, src) { + if (typeof src !== 'string' && !Array.isArray(src)) { + if (apiClient && apiClient.isVertexAI()) { + if (src.gcsUri && src.bigqueryUri) { + throw new Error('Only one of `gcsUri` or `bigqueryUri` can be set.'); + } + else if (!src.gcsUri && !src.bigqueryUri) { + throw new Error('One of `gcsUri` or `bigqueryUri` must be set.'); + } + } + else { + // Logic for non-Vertex AI client (inlined_requests, file_name) + if (src.inlinedRequests && src.fileName) { + throw new Error('Only one of `inlinedRequests` or `fileName` can be set.'); + } + else if (!src.inlinedRequests && !src.fileName) { + throw new Error('One of `inlinedRequests` or `fileName` must be set.'); + } + } + return src; + } + // If src is an array (list in Python) + else if (Array.isArray(src)) { + return { inlinedRequests: src }; + } + else if (typeof src === 'string') { + if (src.startsWith('gs://')) { + return { + format: 'jsonl', + gcsUri: [src], // GCS URI is expected as an array + }; + } + else if (src.startsWith('bq://')) { + return { + format: 'bigquery', + bigqueryUri: src, + }; + } + else if (src.startsWith('files/')) { + return { + fileName: src, + }; + } + } + throw new Error(`Unsupported source: ${src}`); +} +function tBatchJobDestination(dest) { + if (typeof dest !== 'string') { + return dest; + } + const destString = dest; + if (destString.startsWith('gs://')) { + return { + format: 'jsonl', + gcsUri: destString, + }; + } + else if (destString.startsWith('bq://')) { + return { + format: 'bigquery', + bigqueryUri: destString, + }; + } + else { + throw new Error(`Unsupported destination: ${destString}`); + } +} +function tBatchJobName(apiClient, name) { + const nameString = name; + if (!apiClient.isVertexAI()) { + const mldevPattern = /batches\/[^/]+$/; + if (mldevPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } + } + const vertexPattern = /^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/; + if (vertexPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else if (/^\d+$/.test(nameString)) { + return nameString; + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } +} +function tJobState(state) { + const stateString = state; + if (stateString === 'BATCH_STATE_UNSPECIFIED') { + return 'JOB_STATE_UNSPECIFIED'; + } + else if (stateString === 'BATCH_STATE_PENDING') { + return 'JOB_STATE_PENDING'; + } + else if (stateString === 'BATCH_STATE_SUCCEEDED') { + return 'JOB_STATE_SUCCEEDED'; + } + else if (stateString === 'BATCH_STATE_FAILED') { + return 'JOB_STATE_FAILED'; + } + else if (stateString === 'BATCH_STATE_CANCELLED') { + return 'JOB_STATE_CANCELLED'; + } + else { + return stateString; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$4(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$4(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$4(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$4(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$4(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$4(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$4(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev$1(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$4(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$4(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$4(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$4(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$4(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$4(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$4(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$4() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$4(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$4(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$4(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$4(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$4(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$4()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$4(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev$2(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev$2(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$2(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev$2(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$3(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$3(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$3(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$3(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$3(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev$1(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$4(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToMldev$1(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev$1(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$4(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$2(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToMldev$3(tSpeechConfig(fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev$1(fromThinkingConfig)); + } + return toObject; +} +function inlinedRequestToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['request', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$4(item); + }); + } + setValueByPath(toObject, ['request', 'contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['request', 'generationConfig'], generateContentConfigToMldev$1(apiClient, fromConfig, toObject)); + } + return toObject; +} +function batchJobSourceToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['format']) !== undefined) { + throw new Error('format parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['bigqueryUri']) !== undefined) { + throw new Error('bigqueryUri parameter is not supported in Gemini API.'); + } + const fromFileName = getValueByPath(fromObject, ['fileName']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedRequests = getValueByPath(fromObject, [ + 'inlinedRequests', + ]); + if (fromInlinedRequests != null) { + let transformedList = fromInlinedRequests; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedRequestToMldev(apiClient, item); + }); + } + setValueByPath(toObject, ['requests', 'requests'], transformedList); + } + return toObject; +} +function createBatchJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['batch', 'displayName'], fromDisplayName); + } + if (getValueByPath(fromObject, ['dest']) !== undefined) { + throw new Error('dest parameter is not supported in Gemini API.'); + } + return toObject; +} +function createBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['batch', 'inputConfig'], batchJobSourceToMldev(apiClient, tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createBatchJobConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + if (getValueByPath(fromObject, ['filter']) !== undefined) { + throw new Error('filter parameter is not supported in Gemini API.'); + } + return toObject; +} +function listBatchJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listBatchJobsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function deleteBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function batchJobSourceToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['instancesFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsSource', 'uris'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigquerySource', 'inputUri'], fromBigqueryUri); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['inlinedRequests']) !== undefined) { + throw new Error('inlinedRequests parameter is not supported in Vertex AI.'); + } + return toObject; +} +function batchJobDestinationToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['predictionsFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsDestination', 'outputUriPrefix'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryDestination', 'outputUri'], fromBigqueryUri); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['inlinedResponses']) !== undefined) { + throw new Error('inlinedResponses parameter is not supported in Vertex AI.'); + } + return toObject; +} +function createBatchJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDest = getValueByPath(fromObject, ['dest']); + if (parentObject !== undefined && fromDest != null) { + setValueByPath(parentObject, ['outputConfig'], batchJobDestinationToVertex(tBatchJobDestination(fromDest))); + } + return toObject; +} +function createBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['inputConfig'], batchJobSourceToVertex(tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createBatchJobConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listBatchJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listBatchJobsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function deleteBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev$2(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$2(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$2(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromMldev$1(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev$2(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev$1(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev$2(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev$1(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev$1(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function jobErrorFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + return toObject; +} +function inlinedResponseFromMldev(fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateContentResponseFromMldev$1(fromResponse)); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError)); + } + return toObject; +} +function batchJobDestinationFromMldev(fromObject) { + const toObject = {}; + const fromFileName = getValueByPath(fromObject, ['responsesFile']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedResponses = getValueByPath(fromObject, [ + 'inlinedResponses', + 'inlinedResponses', + ]); + if (fromInlinedResponses != null) { + let transformedList = fromInlinedResponses; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedResponseFromMldev(item); + }); + } + setValueByPath(toObject, ['inlinedResponses'], transformedList); + } + return toObject; +} +function batchJobFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, [ + 'metadata', + 'displayName', + ]); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['metadata', 'state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, [ + 'metadata', + 'createTime', + ]); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'metadata', + 'endTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, [ + 'metadata', + 'updateTime', + ]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['metadata', 'model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromDest = getValueByPath(fromObject, ['metadata', 'output']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromMldev(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, ['operations']); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromMldev(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function deleteResourceJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError)); + } + return toObject; +} +function jobErrorFromVertex(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + return toObject; +} +function batchJobSourceFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['instancesFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsSource', 'uris']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigquerySource', + 'inputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + return toObject; +} +function batchJobDestinationFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['predictionsFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, [ + 'gcsDestination', + 'outputUriPrefix', + ]); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigqueryDestination', + 'outputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + return toObject; +} +function batchJobFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromSrc = getValueByPath(fromObject, ['inputConfig']); + if (fromSrc != null) { + setValueByPath(toObject, ['src'], batchJobSourceFromVertex(fromSrc)); + } + const fromDest = getValueByPath(fromObject, ['outputConfig']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromVertex(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, [ + 'batchPredictionJobs', + ]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromVertex(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function deleteResourceJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +exports.PagedItem = void 0; +(function (PagedItem) { + PagedItem["PAGED_ITEM_BATCH_JOBS"] = "batchJobs"; + PagedItem["PAGED_ITEM_MODELS"] = "models"; + PagedItem["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs"; + PagedItem["PAGED_ITEM_FILES"] = "files"; + PagedItem["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents"; +})(exports.PagedItem || (exports.PagedItem = {})); +/** + * Pager class for iterating through paginated results. + */ +class Pager { + constructor(name, request, response, params) { + this.pageInternal = []; + this.paramsInternal = {}; + this.requestInternal = request; + this.init(name, response, params); + } + init(name, response, params) { + var _a, _b; + this.nameInternal = name; + this.pageInternal = response[this.nameInternal] || []; + this.sdkHttpResponseInternal = response === null || response === void 0 ? void 0 : response.sdkHttpResponse; + this.idxInternal = 0; + let requestParams = { config: {} }; + if (!params || Object.keys(params).length === 0) { + requestParams = { config: {} }; + } + else if (typeof params === 'object') { + requestParams = Object.assign({}, params); + } + else { + requestParams = params; + } + if (requestParams['config']) { + requestParams['config']['pageToken'] = response['nextPageToken']; + } + this.paramsInternal = requestParams; + this.pageInternalSize = + (_b = (_a = requestParams['config']) === null || _a === void 0 ? void 0 : _a['pageSize']) !== null && _b !== void 0 ? _b : this.pageInternal.length; + } + initNextPage(response) { + this.init(this.nameInternal, response, this.paramsInternal); + } + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page() { + return this.pageInternal; + } + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name() { + return this.nameInternal; + } + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize() { + return this.pageInternalSize; + } + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse() { + return this.sdkHttpResponseInternal; + } + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params() { + return this.paramsInternal; + } + /** + * Returns the total number of items in the current page. + */ + get pageLength() { + return this.pageInternal.length; + } + /** + * Returns the item at the given index. + */ + getItem(index) { + return this.pageInternal[index]; + } + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator]() { + return { + next: async () => { + if (this.idxInternal >= this.pageLength) { + if (this.hasNextPage()) { + await this.nextPage(); + } + else { + return { value: undefined, done: true }; + } + } + const item = this.getItem(this.idxInternal); + this.idxInternal += 1; + return { value: item, done: false }; + }, + return: async () => { + return { value: undefined, done: true }; + }, + }; + } + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + async nextPage() { + if (!this.hasNextPage()) { + throw new Error('No more pages to fetch.'); + } + const response = await this.requestInternal(this.params); + this.initNextPage(response); + return this.page; + } + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage() { + var _a; + if (((_a = this.params['config']) === null || _a === void 0 ? void 0 : _a['pageToken']) !== undefined) { + return true; + } + return false; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Batches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + this.create = async (params) => { + var _a, _b; + if (this.apiClient.isVertexAI()) { + const timestamp = Date.now(); + const timestampStr = timestamp.toString(); + if (Array.isArray(params.src)) { + throw new Error('InlinedRequest[] is not supported in Vertex AI. Please use ' + + 'Google Cloud Storage URI or BigQuery URI instead.'); + } + params.config = params.config || {}; + if (params.config.displayName === undefined) { + params.config.displayName = 'genaiBatchJob_${timestampStr}'; + } + if (params.config.dest === undefined && typeof params.src === 'string') { + if (params.src.startsWith('gs://') && params.src.endsWith('.jsonl')) { + params.config.dest = `${params.src.slice(0, -6)}/dest`; + } + else if (params.src.startsWith('bq://')) { + params.config.dest = + `${params.src}_dest_${timestampStr}`; + } + else { + throw new Error('Unsupported source:' + params.src); + } + } + } + else { + if (Array.isArray(params.src) || + (typeof params.src !== 'string' && params.src.inlinedRequests)) { + // Move system instruction to httpOptions extraBody. + let path = ''; + let queryParams = {}; + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchGenerateContent', body['_url']); + queryParams = body['_query']; + // Move system instruction to 'request': + // {'systemInstruction': system_instruction} + const batch = body['batch']; + const inputConfig = batch['inputConfig']; + const requestsWrapper = inputConfig['requests']; + const requests = requestsWrapper['requests']; + const newRequests = []; + for (const request of requests) { + const requestDict = request; + if (requestDict['systemInstruction']) { + const systemInstructionValue = requestDict['systemInstruction']; + delete requestDict['systemInstruction']; + const requestContent = requestDict['request']; + requestContent['systemInstruction'] = systemInstructionValue; + requestDict['request'] = requestContent; + } + newRequests.push(requestDict); + } + requestsWrapper['requests'] = newRequests; + delete body['config']; + delete body['_url']; + delete body['_query']; + const response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + return await this.createInternal(params); + }; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(exports.PagedItem.PAGED_ITEM_BATCH_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + async createInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchGenerateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + else { + const body = cancelBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listBatchJobsParametersToVertex(params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromVertex(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listBatchJobsParametersToMldev(params); + path = formatMap('batches', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromMldev(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = deleteBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$3(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$3(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$3(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$3(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$3(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$3(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$3(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$3(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$3(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$3(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$3(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$3(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$3(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$3(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$3() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$3(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$3(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$3(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$3(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$3(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$3()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$3(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$1(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev$1(fromRetrievalConfig)); + } + return toObject; +} +function createCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$3(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$3(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$3(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$1(fromToolConfig)); + } + if (getValueByPath(fromObject, ['kmsKeyName']) !== undefined) { + throw new Error('kmsKeyName parameter is not supported in Gemini API.'); + } + return toObject; +} +function createCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createCachedContentConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataToVertex$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex$2(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$2(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex$2(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex$2(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$2(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex$2(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex$2(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$2(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$2(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$2(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex$2(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex$2(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex$2()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex$2(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToVertex$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToVertex$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex$1(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToVertex$1(fromRetrievalConfig)); + } + return toObject; +} +function createCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex$2(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$2(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex$1(fromToolConfig)); + } + const fromKmsKeyName = getValueByPath(fromObject, ['kmsKeyName']); + if (parentObject !== undefined && fromKmsKeyName != null) { + setValueByPath(parentObject, ['encryption_spec', 'kmsKeyName'], fromKmsKeyName); + } + return toObject; +} +function createCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createCachedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function cachedContentFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromMldev() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromMldev(item); + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} +function cachedContentFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromVertex() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromVertex(item); + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Caches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(exports.PagedItem.PAGED_ITEM_CACHED_CONTENTS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + async create(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = createCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromVertex(); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromMldev(); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = updateCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listCachedContentsParametersToVertex(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromVertex(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listCachedContentsParametersToMldev(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromMldev(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns true if the response is valid, false otherwise. + */ +function isValidResponse(response) { + var _a; + if (response.candidates == undefined || response.candidates.length === 0) { + return false; + } + const content = (_a = response.candidates[0]) === null || _a === void 0 ? void 0 : _a.content; + if (content === undefined) { + return false; + } + return isValidContent(content); +} +function isValidContent(content) { + if (content.parts === undefined || content.parts.length === 0) { + return false; + } + for (const part of content.parts) { + if (part === undefined || Object.keys(part).length === 0) { + return false; + } + } + return true; +} +/** + * Validates the history contains the correct roles. + * + * @throws Error if the history does not start with a user turn. + * @throws Error if the history contains an invalid role. + */ +function validateHistory(history) { + // Empty history is valid. + if (history.length === 0) { + return; + } + for (const content of history) { + if (content.role !== 'user' && content.role !== 'model') { + throw new Error(`Role must be user or model, but got ${content.role}.`); + } + } +} +/** + * Extracts the curated (valid) history from a comprehensive history. + * + * @remarks + * The model may sometimes generate invalid or empty contents(e.g., due to safty + * filters or recitation). Extracting valid turns from the history + * ensures that subsequent requests could be accpeted by the model. + */ +function extractCuratedHistory(comprehensiveHistory) { + if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) { + return []; + } + const curatedHistory = []; + const length = comprehensiveHistory.length; + let i = 0; + while (i < length) { + if (comprehensiveHistory[i].role === 'user') { + curatedHistory.push(comprehensiveHistory[i]); + i++; + } + else { + const modelOutput = []; + let isValid = true; + while (i < length && comprehensiveHistory[i].role === 'model') { + modelOutput.push(comprehensiveHistory[i]); + if (isValid && !isValidContent(comprehensiveHistory[i])) { + isValid = false; + } + i++; + } + if (isValid) { + curatedHistory.push(...modelOutput); + } + else { + // Remove the last user input when model content is invalid. + curatedHistory.pop(); + } + } + } + return curatedHistory; +} +/** + * A utility class to create a chat session. + */ +class Chats { + constructor(modelsModule, apiClient) { + this.modelsModule = modelsModule; + this.apiClient = apiClient; + } + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params) { + return new Chat(this.apiClient, this.modelsModule, params.model, params.config, + // Deep copy the history to avoid mutating the history outside of the + // chat session. + structuredClone(params.history)); + } +} +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +class Chat { + constructor(apiClient, modelsModule, model, config = {}, history = []) { + this.apiClient = apiClient; + this.modelsModule = modelsModule; + this.model = model; + this.config = config; + this.history = history; + // A promise to represent the current state of the message being sent to the + // model. + this.sendPromise = Promise.resolve(); + validateHistory(history); + } + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + async sendMessage(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const responsePromise = this.modelsModule.generateContent({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + this.sendPromise = (async () => { + var _a, _b, _c; + const response = await responsePromise; + const outputContent = (_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content; + // Because the AFC input contains the entire curated chat history in + // addition to the new user input, we need to truncate the AFC history + // to deduplicate the existing chat history. + const fullAutomaticFunctionCallingHistory = response.automaticFunctionCallingHistory; + const index = this.getHistory(true).length; + let automaticFunctionCallingHistory = []; + if (fullAutomaticFunctionCallingHistory != null) { + automaticFunctionCallingHistory = + (_c = fullAutomaticFunctionCallingHistory.slice(index)) !== null && _c !== void 0 ? _c : []; + } + const modelOutput = outputContent ? [outputContent] : []; + this.recordHistory(inputContent, modelOutput, automaticFunctionCallingHistory); + return; + })(); + await this.sendPromise.catch(() => { + // Resets sendPromise to avoid subsequent calls failing + this.sendPromise = Promise.resolve(); + }); + return responsePromise; + } + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + async sendMessageStream(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const streamResponse = this.modelsModule.generateContentStream({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + // Resolve the internal tracking of send completion promise - `sendPromise` + // for both success and failure response. The actual failure is still + // propagated by the `await streamResponse`. + this.sendPromise = streamResponse + .then(() => undefined) + .catch(() => undefined); + const response = await streamResponse; + const result = this.processStreamResponse(response, inputContent); + return result; + } + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated = false) { + const history = curated + ? extractCuratedHistory(this.history) + : this.history; + // Deep copy the history to avoid mutating the history outside of the + // chat session. + return structuredClone(history); + } + processStreamResponse(streamResponse, inputContent) { + var _a, _b; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + var _c, e_1, _d, _e; + const outputContent = []; + try { + for (var _f = true, streamResponse_1 = __asyncValues(streamResponse), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()), _c = streamResponse_1_1.done, !_c; _f = true) { + _e = streamResponse_1_1.value; + _f = false; + const chunk = _e; + if (isValidResponse(chunk)) { + const content = (_b = (_a = chunk.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content; + if (content !== undefined) { + outputContent.push(content); + } + } + yield yield __await(chunk); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_c && (_d = streamResponse_1.return)) yield __await(_d.call(streamResponse_1)); + } + finally { if (e_1) throw e_1.error; } + } + this.recordHistory(inputContent, outputContent); + }); + } + recordHistory(userInput, modelOutput, automaticFunctionCallingHistory) { + let outputContents = []; + if (modelOutput.length > 0 && + modelOutput.every((content) => content.role !== undefined)) { + outputContents = modelOutput; + } + else { + // Appends an empty content when model returns empty response, so that the + // history is always alternating between user and model. + outputContents.push({ + role: 'model', + parts: [], + }); + } + if (automaticFunctionCallingHistory && + automaticFunctionCallingHistory.length > 0) { + this.history.push(...extractCuratedHistory(automaticFunctionCallingHistory)); + } + else { + this.history.push(userInput); + } + this.history.push(...outputContents); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * API errors raised by the GenAI API. + */ +class ApiError extends Error { + constructor(options) { + super(options.message); + this.name = 'ApiError'; + this.status = options.status; + Object.setPrototypeOf(this, ApiError.prototype); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const CONTENT_TYPE_HEADER = 'Content-Type'; +const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout'; +const USER_AGENT_HEADER = 'User-Agent'; +const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client'; +const SDK_VERSION = '1.15.0'; // x-release-please-version +const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`; +const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1'; +const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta'; +const responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/; +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +class ApiClient { + constructor(opts) { + var _a, _b; + this.clientOptions = Object.assign(Object.assign({}, opts), { project: opts.project, location: opts.location, apiKey: opts.apiKey, vertexai: opts.vertexai }); + const initHttpOptions = {}; + if (this.clientOptions.vertexai) { + initHttpOptions.apiVersion = + (_a = this.clientOptions.apiVersion) !== null && _a !== void 0 ? _a : VERTEX_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = this.baseUrlFromProjectLocation(); + this.normalizeAuthParameters(); + } + else { + // Gemini API + initHttpOptions.apiVersion = + (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 ? _b : GOOGLE_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`; + } + initHttpOptions.headers = this.getDefaultHeaders(); + this.clientOptions.httpOptions = initHttpOptions; + if (opts.httpOptions) { + this.clientOptions.httpOptions = this.patchHttpOptions(initHttpOptions, opts.httpOptions); + } + } + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + baseUrlFromProjectLocation() { + if (this.clientOptions.project && + this.clientOptions.location && + this.clientOptions.location !== 'global') { + // Regional endpoint + return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`; + } + // Global endpoint (covers 'global' location and API key usage) + return `https://aiplatform.googleapis.com/`; + } + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + normalizeAuthParameters() { + if (this.clientOptions.project && this.clientOptions.location) { + // Using project/location for auth, clear potential API key + this.clientOptions.apiKey = undefined; + return; + } + // Using API key for auth (or no auth provided yet), clear project/location + this.clientOptions.project = undefined; + this.clientOptions.location = undefined; + } + isVertexAI() { + var _a; + return (_a = this.clientOptions.vertexai) !== null && _a !== void 0 ? _a : false; + } + getProject() { + return this.clientOptions.project; + } + getLocation() { + return this.clientOptions.location; + } + getApiVersion() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.apiVersion !== undefined) { + return this.clientOptions.httpOptions.apiVersion; + } + throw new Error('API version is not set.'); + } + getBaseUrl() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.baseUrl !== undefined) { + return this.clientOptions.httpOptions.baseUrl; + } + throw new Error('Base URL is not set.'); + } + getRequestUrl() { + return this.getRequestUrlInternal(this.clientOptions.httpOptions); + } + getHeaders() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.headers !== undefined) { + return this.clientOptions.httpOptions.headers; + } + else { + throw new Error('Headers are not set.'); + } + } + getRequestUrlInternal(httpOptions) { + if (!httpOptions || + httpOptions.baseUrl === undefined || + httpOptions.apiVersion === undefined) { + throw new Error('HTTP options are not correctly set.'); + } + const baseUrl = httpOptions.baseUrl.endsWith('/') + ? httpOptions.baseUrl.slice(0, -1) + : httpOptions.baseUrl; + const urlElement = [baseUrl]; + if (httpOptions.apiVersion && httpOptions.apiVersion !== '') { + urlElement.push(httpOptions.apiVersion); + } + return urlElement.join('/'); + } + getBaseResourcePath() { + return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`; + } + getApiKey() { + return this.clientOptions.apiKey; + } + getWebsocketBaseUrl() { + const baseUrl = this.getBaseUrl(); + const urlParts = new URL(baseUrl); + urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss'; + return urlParts.toString(); + } + setBaseUrl(url) { + if (this.clientOptions.httpOptions) { + this.clientOptions.httpOptions.baseUrl = url; + } + else { + throw new Error('HTTP options are not correctly set.'); + } + } + constructUrl(path, httpOptions, prependProjectLocation) { + const urlElement = [this.getRequestUrlInternal(httpOptions)]; + if (prependProjectLocation) { + urlElement.push(this.getBaseResourcePath()); + } + if (path !== '') { + urlElement.push(path); + } + const url = new URL(`${urlElement.join('/')}`); + return url; + } + shouldPrependVertexProjectPath(request) { + if (this.clientOptions.apiKey) { + return false; + } + if (!this.clientOptions.vertexai) { + return false; + } + if (request.path.startsWith('projects/')) { + // Assume the path already starts with + // `projects//location/`. + return false; + } + if (request.httpMethod === 'GET' && + request.path.startsWith('publishers/google/models')) { + // These paths are used by Vertex's models.get and models.list + // calls. For base models Vertex does not accept a project/location + // prefix (for tuned model the prefix is required). + return false; + } + return true; + } + async request(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (request.queryParams) { + for (const [key, value] of Object.entries(request.queryParams)) { + url.searchParams.append(key, String(value)); + } + } + let requestInit = {}; + if (request.httpMethod === 'GET') { + if (request.body && request.body !== '{}') { + throw new Error('Request body should be empty for GET request, but got non empty request body'); + } + } + else { + requestInit.body = request.body; + } + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal); + return this.unaryApiCall(url, requestInit, request.httpMethod); + } + patchHttpOptions(baseHttpOptions, requestHttpOptions) { + const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions)); + for (const [key, value] of Object.entries(requestHttpOptions)) { + // Records compile to objects. + if (typeof value === 'object') { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = Object.assign(Object.assign({}, patchedHttpOptions[key]), value); + } + else if (value !== undefined) { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = value; + } + } + return patchedHttpOptions; + } + async requestStream(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') { + url.searchParams.set('alt', 'sse'); + } + let requestInit = {}; + requestInit.body = request.body; + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal); + return this.streamApiCall(url, requestInit, request.httpMethod); + } + async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions, abortSignal) { + if ((httpOptions && httpOptions.timeout) || abortSignal) { + const abortController = new AbortController(); + const signal = abortController.signal; + if (httpOptions.timeout && (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) > 0) { + const timeoutHandle = setTimeout(() => abortController.abort(), httpOptions.timeout); + if (timeoutHandle && + typeof timeoutHandle.unref === + 'function') { + // call unref to prevent nodejs process from hanging, see + // https://nodejs.org/api/timers.html#timeoutunref + timeoutHandle.unref(); + } + } + if (abortSignal) { + abortSignal.addEventListener('abort', () => { + abortController.abort(); + }); + } + requestInit.signal = signal; + } + if (httpOptions && httpOptions.extraBody !== null) { + includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody); + } + requestInit.headers = await this.getHeadersInternal(httpOptions); + return requestInit; + } + async unaryApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return new HttpResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + async streamApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return this.processStreamResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + processStreamResponse(response) { + var _a; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + const reader = (_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.getReader(); + const decoder = new TextDecoder('utf-8'); + if (!reader) { + throw new Error('Response body is empty'); + } + try { + let buffer = ''; + while (true) { + const { done, value } = yield __await(reader.read()); + if (done) { + if (buffer.trim().length > 0) { + throw new Error('Incomplete JSON segment at the end'); + } + break; + } + const chunkString = decoder.decode(value, { stream: true }); + // Parse and throw an error if the chunk contains an error. + try { + const chunkJson = JSON.parse(chunkString); + if ('error' in chunkJson) { + const errorJson = JSON.parse(JSON.stringify(chunkJson['error'])); + const status = errorJson['status']; + const code = errorJson['code']; + const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`; + if (code >= 400 && code < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: code, + }); + throw apiError; + } + } + } + catch (e) { + const error = e; + if (error.name === 'ApiError') { + throw e; + } + } + buffer += chunkString; + let match = buffer.match(responseLineRE); + while (match) { + const processedChunkString = match[1]; + try { + const partialResponse = new Response(processedChunkString, { + headers: response === null || response === void 0 ? void 0 : response.headers, + status: response === null || response === void 0 ? void 0 : response.status, + statusText: response === null || response === void 0 ? void 0 : response.statusText, + }); + yield yield __await(new HttpResponse(partialResponse)); + buffer = buffer.slice(match[0].length); + match = buffer.match(responseLineRE); + } + catch (e) { + throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`); + } + } + } + } + finally { + reader.releaseLock(); + } + }); + } + async apiCall(url, requestInit) { + return fetch(url, requestInit).catch((e) => { + throw new Error(`exception ${e} sending request`); + }); + } + getDefaultHeaders() { + const headers = {}; + const versionHeaderValue = LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra; + headers[USER_AGENT_HEADER] = versionHeaderValue; + headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue; + headers[CONTENT_TYPE_HEADER] = 'application/json'; + return headers; + } + async getHeadersInternal(httpOptions) { + const headers = new Headers(); + if (httpOptions && httpOptions.headers) { + for (const [key, value] of Object.entries(httpOptions.headers)) { + headers.append(key, value); + } + // Append a timeout header if it is set, note that the timeout option is + // in milliseconds but the header is in seconds. + if (httpOptions.timeout && httpOptions.timeout > 0) { + headers.append(SERVER_TIMEOUT_HEADER, String(Math.ceil(httpOptions.timeout / 1000))); + } + } + await this.clientOptions.auth.addAuthHeaders(headers); + return headers; + } + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + async uploadFile(file, config) { + var _a; + const fileToUpload = {}; + if (config != null) { + fileToUpload.mimeType = config.mimeType; + fileToUpload.name = config.name; + fileToUpload.displayName = config.displayName; + } + if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) { + fileToUpload.name = `files/${fileToUpload.name}`; + } + const uploader = this.clientOptions.uploader; + const fileStat = await uploader.stat(file); + fileToUpload.sizeBytes = String(fileStat.size); + const mimeType = (_a = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a !== void 0 ? _a : fileStat.type; + if (mimeType === undefined || mimeType === '') { + throw new Error('Can not determine mimeType. Please provide mimeType in the config.'); + } + fileToUpload.mimeType = mimeType; + const uploadUrl = await this.fetchUploadUrl(fileToUpload, config); + return uploader.upload(file, uploadUrl, this); + } + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + async downloadFile(params) { + const downloader = this.clientOptions.downloader; + await downloader.download(params, this); + } + async fetchUploadUrl(file, config) { + var _a; + let httpOptions = {}; + if (config === null || config === void 0 ? void 0 : config.httpOptions) { + httpOptions = config.httpOptions; + } + else { + httpOptions = { + apiVersion: '', + headers: { + 'Content-Type': 'application/json', + 'X-Goog-Upload-Protocol': 'resumable', + 'X-Goog-Upload-Command': 'start', + 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`, + 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`, + }, + }; + } + const body = { + 'file': file, + }; + const httpResponse = await this.request({ + path: formatMap('upload/v1beta/files', body['_url']), + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions, + }); + if (!httpResponse || !(httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers)) { + throw new Error('Server did not return an HttpResponse or the returned HttpResponse did not have headers.'); + } + const uploadUrl = (_a = httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers) === null || _a === void 0 ? void 0 : _a['x-goog-upload-url']; + if (uploadUrl === undefined) { + throw new Error('Failed to get upload url. Server did not return the x-google-upload-url in the headers'); + } + return uploadUrl; + } +} +async function throwErrorIfNotOK(response) { + var _a; + if (response === undefined) { + throw new Error('response is undefined'); + } + if (!response.ok) { + const status = response.status; + let errorBody; + if ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('application/json')) { + errorBody = await response.json(); + } + else { + errorBody = { + error: { + message: await response.text(), + code: response.status, + status: response.statusText, + }, + }; + } + const errorMessage = JSON.stringify(errorBody); + if (status >= 400 && status < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: status, + }); + throw apiError; + } + throw new Error(errorMessage); + } +} +/** + * Recursively updates the `requestInit.body` with values from an `extraBody` object. + * + * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed. + * The `extraBody` is then deeply merged into this parsed object. + * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged, + * as merging structured data into an opaque Blob is not supported. + * + * The function does not enforce that updated values from `extraBody` have the + * same type as existing values in `requestInit.body`. Type mismatches during + * the merge will result in a warning, but the value from `extraBody` will overwrite + * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure. + * + * @param requestInit The RequestInit object whose body will be updated. + * @param extraBody The object containing updates to be merged into `requestInit.body`. + */ +function includeExtraBodyToRequestInit(requestInit, extraBody) { + if (!extraBody || Object.keys(extraBody).length === 0) { + return; + } + if (requestInit.body instanceof Blob) { + console.warn('includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.'); + return; + } + let currentBodyObject = {}; + // If adding new type to HttpRequest.body, please check the code below to + // see if we need to update the logic. + if (typeof requestInit.body === 'string' && requestInit.body.length > 0) { + try { + const parsedBody = JSON.parse(requestInit.body); + if (typeof parsedBody === 'object' && + parsedBody !== null && + !Array.isArray(parsedBody)) { + currentBodyObject = parsedBody; + } + else { + console.warn('includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.'); + return; + } + /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ + } + catch (e) { + console.warn('includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.'); + return; + } + } + function deepMerge(target, source) { + const output = Object.assign({}, target); + for (const key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + const sourceValue = source[key]; + const targetValue = output[key]; + if (sourceValue && + typeof sourceValue === 'object' && + !Array.isArray(sourceValue) && + targetValue && + typeof targetValue === 'object' && + !Array.isArray(targetValue)) { + output[key] = deepMerge(targetValue, sourceValue); + } + else { + if (targetValue && + sourceValue && + typeof targetValue !== typeof sourceValue) { + console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`); + } + output[key] = sourceValue; + } + } + } + return output; + } + const mergedBody = deepMerge(currentBodyObject, extraBody); + requestInit.body = JSON.stringify(mergedBody); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function crossError() { + // TODO(b/399934880): this message needs a link to a help page explaining how to enable conditional exports + return new Error(`This feature requires the web or Node specific @google/genai implementation, you can fix this by either: + +*Enabling conditional exports for your project [recommended]* + +*Using a platform specific import* - Make sure your code imports either '@google/genai/web' or '@google/genai/node' instead of '@google/genai'. +`); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class CrossDownloader { + async download(_params, _apiClient) { + throw crossError(); + } +} + +const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes +const MAX_RETRY_COUNT = 3; +const INITIAL_RETRY_DELAY_MS = 1000; +const DELAY_MULTIPLIER = 2; +const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status'; +class CrossUploader { + async upload(file, uploadUrl, apiClient) { + if (typeof file === 'string') { + throw crossError(); + } + else { + return uploadBlob(file, uploadUrl, apiClient); + } + } + async stat(file) { + if (typeof file === 'string') { + throw crossError(); + } + else { + return getBlobStat(file); + } + } +} +async function uploadBlob(file, uploadUrl, apiClient) { + var _a, _b, _c; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = 'upload'; + fileSize = file.size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + const chunk = file.slice(offset, offset + chunkSize); + if (offset + chunkSize >= fileSize) { + uploadCommand += ', finalize'; + } + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: '', + body: chunk, + httpMethod: 'POST', + httpOptions: { + apiVersion: '', + baseUrl: uploadUrl, + headers: { + 'X-Goog-Upload-Command': uploadCommand, + 'X-Goog-Upload-Offset': String(offset), + 'Content-Length': String(chunkSize), + }, + }, + }); + if ((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += chunkSize; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'active') { + break; + } + // TODO(b/401391430) Investigate why the upload status is not finalized + // even though all content has been uploaded. + if (fileSize <= offset) { + throw new Error('All content has been uploaded, but the upload status is not finalized.'); + } + } + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_c = response === null || response === void 0 ? void 0 : response.headers) === null || _c === void 0 ? void 0 : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + return responseJson['file']; +} +async function getBlobStat(file) { + const fileStat = { size: file.size, type: file.type }; + return fileStat; +} +function sleep(ms) { + return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class CrossWebSocketFactory { + create(_url, _headers, _callbacks) { + throw crossError(); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function listFilesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listFilesParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listFilesConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function fileStatusToMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusToMldev(fromError)); + } + return toObject; +} +function createFileParametersToMldev(fromObject) { + const toObject = {}; + const fromFile = getValueByPath(fromObject, ['file']); + if (fromFile != null) { + setValueByPath(toObject, ['file'], fileToMldev(fromFile)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fileStatusFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusFromMldev(fromError)); + } + return toObject; +} +function listFilesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromFiles = getValueByPath(fromObject, ['files']); + if (fromFiles != null) { + let transformedList = fromFiles; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return fileFromMldev(item); + }); + } + setValueByPath(toObject, ['files'], transformedList); + } + return toObject; +} +function createFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function deleteFileResponseFromMldev() { + const toObject = {}; + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Files extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(exports.PagedItem.PAGED_ITEM_FILES, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + async upload(params) { + if (this.apiClient.isVertexAI()) { + throw new Error('Vertex AI does not support uploading files. You can share files through a GCS bucket.'); + } + return this.apiClient + .uploadFile(params.file, params.config) + .then((response) => { + const file = fileFromMldev(response); + return file; + }); + } + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + async download(params) { + await this.apiClient.downloadFile(params); + } + async listInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = listFilesParametersToMldev(params); + path = formatMap('files', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listFilesResponseFromMldev(apiResponse); + const typedResp = new ListFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async createInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createFileParametersToMldev(params); + path = formatMap('upload/v1beta/files', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = createFileResponseFromMldev(apiResponse); + const typedResp = new CreateFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + async get(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = getFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = fileFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + async delete(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = deleteFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteFileResponseFromMldev(); + const typedResp = new DeleteFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$2(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$2(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$2(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$2(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$2(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$2(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$2(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$2(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$2(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$2(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$2(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$2(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$2()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$2(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is not supported in Gemini API.'); + } + return toObject; +} +function audioTranscriptionConfigToMldev$1() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev$1(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev$1(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToMldev$1(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev$1(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToMldev$1(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToMldev$1(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev$1(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToMldev$2(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$2(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev$1(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToMldev$1()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToMldev$1()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToMldev$1(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToMldev$1(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToMldev$1(fromProactivity)); + } + return toObject; +} +function liveConnectParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev$1(fromConfig, toObject)); + } + return toObject; +} +function activityStartToMldev() { + const toObject = {}; + return toObject; +} +function activityEndToMldev() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToMldev(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + setValueByPath(toObject, ['mediaChunks'], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], activityStartToMldev()); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], activityEndToMldev()); + } + return toObject; +} +function weightedPromptToMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromWeight = getValueByPath(fromObject, ['weight']); + if (fromWeight != null) { + setValueByPath(toObject, ['weight'], fromWeight); + } + return toObject; +} +function liveMusicSetWeightedPromptsParametersToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigToMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ['guidance']); + if (fromGuidance != null) { + setValueByPath(toObject, ['guidance'], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ['bpm']); + if (fromBpm != null) { + setValueByPath(toObject, ['bpm'], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ['density']); + if (fromDensity != null) { + setValueByPath(toObject, ['density'], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ['brightness']); + if (fromBrightness != null) { + setValueByPath(toObject, ['brightness'], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ['scale']); + if (fromScale != null) { + setValueByPath(toObject, ['scale'], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ['muteBass']); + if (fromMuteBass != null) { + setValueByPath(toObject, ['muteBass'], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ['muteDrums']); + if (fromMuteDrums != null) { + setValueByPath(toObject, ['muteDrums'], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, [ + 'onlyBassAndDrums', + ]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums); + } + const fromMusicGenerationMode = getValueByPath(fromObject, [ + 'musicGenerationMode', + ]); + if (fromMusicGenerationMode != null) { + setValueByPath(toObject, ['musicGenerationMode'], fromMusicGenerationMode); + } + return toObject; +} +function liveMusicSetConfigParametersToMldev(fromObject) { + const toObject = {}; + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig)); + } + return toObject; +} +function liveMusicClientSetupToMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + return toObject; +} +function liveMusicClientContentToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicClientMessageToMldev(fromObject) { + const toObject = {}; + const fromSetup = getValueByPath(fromObject, ['setup']); + if (fromSetup != null) { + setValueByPath(toObject, ['setup'], liveMusicClientSetupToMldev(fromSetup)); + } + const fromClientContent = getValueByPath(fromObject, [ + 'clientContent', + ]); + if (fromClientContent != null) { + setValueByPath(toObject, ['clientContent'], liveMusicClientContentToMldev(fromClientContent)); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig)); + } + const fromPlaybackControl = getValueByPath(fromObject, [ + 'playbackControl', + ]); + if (fromPlaybackControl != null) { + setValueByPath(toObject, ['playbackControl'], fromPlaybackControl); + } + return toObject; +} +function prebuiltVoiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex$1(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex$1(fromVoiceConfig)); + } + if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) { + throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.'); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex$1(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$1(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex$1(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex$1(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$1(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex$1(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex$1(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$1(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$1(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$1(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex$1(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex$1(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex$1()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex$1(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToVertex(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + const fromTransparent = getValueByPath(fromObject, ['transparent']); + if (fromTransparent != null) { + setValueByPath(toObject, ['transparent'], fromTransparent); + } + return toObject; +} +function audioTranscriptionConfigToVertex() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToVertex(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToVertex(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToVertex(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToVertex(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToVertex(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToVertex(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToVertex(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToVertex$1(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToVertex(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToVertex()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToVertex()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToVertex(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToVertex(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToVertex(fromProactivity)); + } + return toObject; +} +function liveConnectParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function activityStartToVertex() { + const toObject = {}; + return toObject; +} +function activityEndToVertex() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToVertex(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + setValueByPath(toObject, ['mediaChunks'], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], activityStartToVertex()); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], activityEndToVertex()); + } + return toObject; +} +function liveServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function videoMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev$1(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$1(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function transcriptionFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFinished = getValueByPath(fromObject, ['finished']); + if (fromFinished != null) { + setValueByPath(toObject, ['finished'], fromFinished); + } + return toObject; +} +function urlMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$1(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function liveServerContentFromMldev(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn != null) { + setValueByPath(toObject, ['modelTurn'], contentFromMldev$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete != null) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted != null) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + 'generationComplete', + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ['generationComplete'], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + 'inputTranscription', + ]); + if (fromInputTranscription != null) { + setValueByPath(toObject, ['inputTranscription'], transcriptionFromMldev(fromInputTranscription)); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + 'outputTranscription', + ]); + if (fromOutputTranscription != null) { + setValueByPath(toObject, ['outputTranscription'], transcriptionFromMldev(fromOutputTranscription)); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev$1(fromUrlContextMetadata)); + } + return toObject; +} +function functionCallFromMldev(fromObject) { + const toObject = {}; + const fromId = getValueByPath(fromObject, ['id']); + if (fromId != null) { + setValueByPath(toObject, ['id'], fromId); + } + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromMldev(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromMldev(item); + }); + } + setValueByPath(toObject, ['functionCalls'], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromMldev(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds != null) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function modalityTokenCountFromMldev(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ['modality']); + if (fromModality != null) { + setValueByPath(toObject, ['modality'], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function usageMetadataFromMldev(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, [ + 'promptTokenCount', + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + 'responseTokenCount', + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ['responseTokenCount'], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + 'toolUsePromptTokenCount', + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ['toolUsePromptTokenCount'], fromToolUsePromptTokenCount); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + 'thoughtsTokenCount', + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ['thoughtsTokenCount'], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, [ + 'totalTokenCount', + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + 'promptTokensDetails', + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['promptTokensDetails'], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + 'cacheTokensDetails', + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['cacheTokensDetails'], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + 'responseTokensDetails', + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['responseTokensDetails'], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + 'toolUsePromptTokensDetails', + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['toolUsePromptTokensDetails'], transformedList); + } + return toObject; +} +function liveServerGoAwayFromMldev(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ['timeLeft']); + if (fromTimeLeft != null) { + setValueByPath(toObject, ['timeLeft'], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromMldev(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ['newHandle']); + if (fromNewHandle != null) { + setValueByPath(toObject, ['newHandle'], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ['resumable']); + if (fromResumable != null) { + setValueByPath(toObject, ['resumable'], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + 'lastConsumedClientMessageIndex', + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath(toObject, ['lastConsumedClientMessageIndex'], fromLastConsumedClientMessageIndex); + } + return toObject; +} +function liveServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveServerSetupCompleteFromMldev()); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromMldev(fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromMldev(fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromMldev(fromToolCallCancellation)); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], usageMetadataFromMldev(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject, ['goAway']); + if (fromGoAway != null) { + setValueByPath(toObject, ['goAway'], liveServerGoAwayFromMldev(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + 'sessionResumptionUpdate', + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ['sessionResumptionUpdate'], liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate)); + } + return toObject; +} +function liveMusicServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function weightedPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromWeight = getValueByPath(fromObject, ['weight']); + if (fromWeight != null) { + setValueByPath(toObject, ['weight'], fromWeight); + } + return toObject; +} +function liveMusicClientContentFromMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptFromMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigFromMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ['guidance']); + if (fromGuidance != null) { + setValueByPath(toObject, ['guidance'], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ['bpm']); + if (fromBpm != null) { + setValueByPath(toObject, ['bpm'], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ['density']); + if (fromDensity != null) { + setValueByPath(toObject, ['density'], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ['brightness']); + if (fromBrightness != null) { + setValueByPath(toObject, ['brightness'], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ['scale']); + if (fromScale != null) { + setValueByPath(toObject, ['scale'], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ['muteBass']); + if (fromMuteBass != null) { + setValueByPath(toObject, ['muteBass'], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ['muteDrums']); + if (fromMuteDrums != null) { + setValueByPath(toObject, ['muteDrums'], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, [ + 'onlyBassAndDrums', + ]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums); + } + const fromMusicGenerationMode = getValueByPath(fromObject, [ + 'musicGenerationMode', + ]); + if (fromMusicGenerationMode != null) { + setValueByPath(toObject, ['musicGenerationMode'], fromMusicGenerationMode); + } + return toObject; +} +function liveMusicSourceMetadataFromMldev(fromObject) { + const toObject = {}; + const fromClientContent = getValueByPath(fromObject, [ + 'clientContent', + ]); + if (fromClientContent != null) { + setValueByPath(toObject, ['clientContent'], liveMusicClientContentFromMldev(fromClientContent)); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig)); + } + return toObject; +} +function audioChunkFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSourceMetadata = getValueByPath(fromObject, [ + 'sourceMetadata', + ]); + if (fromSourceMetadata != null) { + setValueByPath(toObject, ['sourceMetadata'], liveMusicSourceMetadataFromMldev(fromSourceMetadata)); + } + return toObject; +} +function liveMusicServerContentFromMldev(fromObject) { + const toObject = {}; + const fromAudioChunks = getValueByPath(fromObject, ['audioChunks']); + if (fromAudioChunks != null) { + let transformedList = fromAudioChunks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return audioChunkFromMldev(item); + }); + } + setValueByPath(toObject, ['audioChunks'], transformedList); + } + return toObject; +} +function liveMusicFilteredPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFilteredReason = getValueByPath(fromObject, [ + 'filteredReason', + ]); + if (fromFilteredReason != null) { + setValueByPath(toObject, ['filteredReason'], fromFilteredReason); + } + return toObject; +} +function liveMusicServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveMusicServerSetupCompleteFromMldev()); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveMusicServerContentFromMldev(fromServerContent)); + } + const fromFilteredPrompt = getValueByPath(fromObject, [ + 'filteredPrompt', + ]); + if (fromFilteredPrompt != null) { + setValueByPath(toObject, ['filteredPrompt'], liveMusicFilteredPromptFromMldev(fromFilteredPrompt)); + } + return toObject; +} +function liveServerSetupCompleteFromVertex(fromObject) { + const toObject = {}; + const fromSessionId = getValueByPath(fromObject, ['sessionId']); + if (fromSessionId != null) { + setValueByPath(toObject, ['sessionId'], fromSessionId); + } + return toObject; +} +function videoMetadataFromVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromVertex$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function transcriptionFromVertex(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFinished = getValueByPath(fromObject, ['finished']); + if (fromFinished != null) { + setValueByPath(toObject, ['finished'], fromFinished); + } + return toObject; +} +function liveServerContentFromVertex(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn != null) { + setValueByPath(toObject, ['modelTurn'], contentFromVertex$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete != null) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted != null) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + 'generationComplete', + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ['generationComplete'], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + 'inputTranscription', + ]); + if (fromInputTranscription != null) { + setValueByPath(toObject, ['inputTranscription'], transcriptionFromVertex(fromInputTranscription)); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + 'outputTranscription', + ]); + if (fromOutputTranscription != null) { + setValueByPath(toObject, ['outputTranscription'], transcriptionFromVertex(fromOutputTranscription)); + } + return toObject; +} +function functionCallFromVertex(fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromVertex(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromVertex(item); + }); + } + setValueByPath(toObject, ['functionCalls'], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromVertex(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds != null) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function modalityTokenCountFromVertex(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ['modality']); + if (fromModality != null) { + setValueByPath(toObject, ['modality'], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function usageMetadataFromVertex(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, [ + 'promptTokenCount', + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + 'candidatesTokenCount', + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ['responseTokenCount'], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + 'toolUsePromptTokenCount', + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ['toolUsePromptTokenCount'], fromToolUsePromptTokenCount); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + 'thoughtsTokenCount', + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ['thoughtsTokenCount'], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, [ + 'totalTokenCount', + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + 'promptTokensDetails', + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['promptTokensDetails'], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + 'cacheTokensDetails', + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['cacheTokensDetails'], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + 'candidatesTokensDetails', + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['responseTokensDetails'], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + 'toolUsePromptTokensDetails', + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['toolUsePromptTokensDetails'], transformedList); + } + const fromTrafficType = getValueByPath(fromObject, ['trafficType']); + if (fromTrafficType != null) { + setValueByPath(toObject, ['trafficType'], fromTrafficType); + } + return toObject; +} +function liveServerGoAwayFromVertex(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ['timeLeft']); + if (fromTimeLeft != null) { + setValueByPath(toObject, ['timeLeft'], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromVertex(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ['newHandle']); + if (fromNewHandle != null) { + setValueByPath(toObject, ['newHandle'], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ['resumable']); + if (fromResumable != null) { + setValueByPath(toObject, ['resumable'], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + 'lastConsumedClientMessageIndex', + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath(toObject, ['lastConsumedClientMessageIndex'], fromLastConsumedClientMessageIndex); + } + return toObject; +} +function liveServerMessageFromVertex(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveServerSetupCompleteFromVertex(fromSetupComplete)); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromVertex(fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromVertex(fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromVertex(fromToolCallCancellation)); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], usageMetadataFromVertex(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject, ['goAway']); + if (fromGoAway != null) { + setValueByPath(toObject, ['goAway'], liveServerGoAwayFromVertex(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + 'sessionResumptionUpdate', + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ['sessionResumptionUpdate'], liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$1(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$1(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$1(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$1(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$1(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$1(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$1(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$1()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$1(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$1(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$1(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$1(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$1(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$1(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$1(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToMldev(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToMldev$1(tSpeechConfig(fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev(fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['requests[]', 'taskType'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['requests[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['requests[]', 'outputDimensionality'], fromOutputDimensionality); + } + if (getValueByPath(fromObject, ['mimeType']) !== undefined) { + throw new Error('mimeType parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['autoTruncate']) !== undefined) { + throw new Error('autoTruncate parameter is not supported in Gemini API.'); + } + return toObject; +} +function embedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + setValueByPath(toObject, ['requests[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToMldev(fromConfig, toObject)); + } + const fromModelForEmbedContent = getValueByPath(fromObject, ['model']); + if (fromModelForEmbedContent !== undefined) { + setValueByPath(toObject, ['requests[]', 'model'], tModel(apiClient, fromModelForEmbedContent)); + } + return toObject; +} +function generateImagesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['negativePrompt']) !== undefined) { + throw new Error('negativePrompt parameter is not supported in Gemini API.'); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + if (getValueByPath(fromObject, ['addWatermark']) !== undefined) { + throw new Error('addWatermark parameter is not supported in Gemini API.'); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath(parentObject, ['parameters', 'sampleImageSize'], fromImageSize); + } + if (getValueByPath(fromObject, ['enhancePrompt']) !== undefined) { + throw new Error('enhancePrompt parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateImagesParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateImagesConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listModelsConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listModelsConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function updateModelConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateModelConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function deleteModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function countTokensConfigToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['systemInstruction']) !== undefined) { + throw new Error('systemInstruction parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['tools']) !== undefined) { + throw new Error('tools parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['generationConfig']) !== undefined) { + throw new Error('generationConfig parameter is not supported in Gemini API.'); + } + return toObject; +} +function countTokensParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToMldev(fromConfig)); + } + return toObject; +} +function imageToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['fps']) !== undefined) { + throw new Error('fps parameter is not supported in Gemini API.'); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + if (getValueByPath(fromObject, ['resolution']) !== undefined) { + throw new Error('resolution parameter is not supported in Gemini API.'); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + if (getValueByPath(fromObject, ['pubsubTopic']) !== undefined) { + throw new Error('pubsubTopic parameter is not supported in Gemini API.'); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + if (getValueByPath(fromObject, ['generateAudio']) !== undefined) { + throw new Error('generateAudio parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['lastFrame']) !== undefined) { + throw new Error('lastFrame parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['referenceImages']) !== undefined) { + throw new Error('referenceImages parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['compressionQuality']) !== undefined) { + throw new Error('compressionQuality parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateVideosParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToMldev(fromImage)); + } + if (getValueByPath(fromObject, ['video']) !== undefined) { + throw new Error('video parameter is not supported in Gemini API.'); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataToVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToVertex(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function modelSelectionConfigToVertex(fromObject) { + const toObject = {}; + const fromFeatureSelectionPreference = getValueByPath(fromObject, [ + 'featureSelectionPreference', + ]); + if (fromFeatureSelectionPreference != null) { + setValueByPath(toObject, ['featureSelectionPreference'], fromFeatureSelectionPreference); + } + return toObject; +} +function safetySettingToVertex(fromObject) { + const toObject = {}; + const fromMethod = getValueByPath(fromObject, ['method']); + if (fromMethod != null) { + setValueByPath(toObject, ['method'], fromMethod); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToVertex(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToVertex(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToVertex(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex(fromVoiceConfig)); + } + if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) { + throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.'); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToVertex(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToVertex(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + const fromRoutingConfig = getValueByPath(fromObject, [ + 'routingConfig', + ]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ['routingConfig'], fromRoutingConfig); + } + const fromModelSelectionConfig = getValueByPath(fromObject, [ + 'modelSelectionConfig', + ]); + if (fromModelSelectionConfig != null) { + setValueByPath(toObject, ['modelConfig'], modelSelectionConfigToVertex(fromModelSelectionConfig)); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToVertex(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex(fromToolConfig)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ['labels'], fromLabels); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToVertex(tSpeechConfig(fromSpeechConfig))); + } + const fromAudioTimestamp = getValueByPath(fromObject, [ + 'audioTimestamp', + ]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToVertex(fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['instances[]', 'task_type'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['instances[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['parameters', 'outputDimensionality'], fromOutputDimensionality); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (parentObject !== undefined && fromMimeType != null) { + setValueByPath(parentObject, ['instances[]', 'mimeType'], fromMimeType); + } + const fromAutoTruncate = getValueByPath(fromObject, ['autoTruncate']); + if (parentObject !== undefined && fromAutoTruncate != null) { + setValueByPath(parentObject, ['parameters', 'autoTruncate'], fromAutoTruncate); + } + return toObject; +} +function embedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + setValueByPath(toObject, ['instances[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function generateImagesConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath(parentObject, ['parameters', 'sampleImageSize'], fromImageSize); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function generateImagesParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateImagesConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function imageToVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function maskReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromMaskMode = getValueByPath(fromObject, ['maskMode']); + if (fromMaskMode != null) { + setValueByPath(toObject, ['maskMode'], fromMaskMode); + } + const fromSegmentationClasses = getValueByPath(fromObject, [ + 'segmentationClasses', + ]); + if (fromSegmentationClasses != null) { + setValueByPath(toObject, ['maskClasses'], fromSegmentationClasses); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (fromMaskDilation != null) { + setValueByPath(toObject, ['dilation'], fromMaskDilation); + } + return toObject; +} +function controlReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromControlType = getValueByPath(fromObject, ['controlType']); + if (fromControlType != null) { + setValueByPath(toObject, ['controlType'], fromControlType); + } + const fromEnableControlImageComputation = getValueByPath(fromObject, [ + 'enableControlImageComputation', + ]); + if (fromEnableControlImageComputation != null) { + setValueByPath(toObject, ['computeControl'], fromEnableControlImageComputation); + } + return toObject; +} +function styleReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromStyleDescription = getValueByPath(fromObject, [ + 'styleDescription', + ]); + if (fromStyleDescription != null) { + setValueByPath(toObject, ['styleDescription'], fromStyleDescription); + } + return toObject; +} +function subjectReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromSubjectType = getValueByPath(fromObject, ['subjectType']); + if (fromSubjectType != null) { + setValueByPath(toObject, ['subjectType'], fromSubjectType); + } + const fromSubjectDescription = getValueByPath(fromObject, [ + 'subjectDescription', + ]); + if (fromSubjectDescription != null) { + setValueByPath(toObject, ['subjectDescription'], fromSubjectDescription); + } + return toObject; +} +function referenceImageAPIInternalToVertex(fromObject) { + const toObject = {}; + const fromReferenceImage = getValueByPath(fromObject, [ + 'referenceImage', + ]); + if (fromReferenceImage != null) { + setValueByPath(toObject, ['referenceImage'], imageToVertex(fromReferenceImage)); + } + const fromReferenceId = getValueByPath(fromObject, ['referenceId']); + if (fromReferenceId != null) { + setValueByPath(toObject, ['referenceId'], fromReferenceId); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + const fromMaskImageConfig = getValueByPath(fromObject, [ + 'maskImageConfig', + ]); + if (fromMaskImageConfig != null) { + setValueByPath(toObject, ['maskImageConfig'], maskReferenceConfigToVertex(fromMaskImageConfig)); + } + const fromControlImageConfig = getValueByPath(fromObject, [ + 'controlImageConfig', + ]); + if (fromControlImageConfig != null) { + setValueByPath(toObject, ['controlImageConfig'], controlReferenceConfigToVertex(fromControlImageConfig)); + } + const fromStyleImageConfig = getValueByPath(fromObject, [ + 'styleImageConfig', + ]); + if (fromStyleImageConfig != null) { + setValueByPath(toObject, ['styleImageConfig'], styleReferenceConfigToVertex(fromStyleImageConfig)); + } + const fromSubjectImageConfig = getValueByPath(fromObject, [ + 'subjectImageConfig', + ]); + if (fromSubjectImageConfig != null) { + setValueByPath(toObject, ['subjectImageConfig'], subjectReferenceConfigToVertex(fromSubjectImageConfig)); + } + return toObject; +} +function editImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromEditMode = getValueByPath(fromObject, ['editMode']); + if (parentObject !== undefined && fromEditMode != null) { + setValueByPath(parentObject, ['parameters', 'editMode'], fromEditMode); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'editConfig', 'baseSteps'], fromBaseSteps); + } + return toObject; +} +function editImageParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return referenceImageAPIInternalToVertex(item); + }); + } + setValueByPath(toObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], editImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function upscaleImageAPIConfigInternalToVertex(fromObject, parentObject) { + const toObject = {}; + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhanceInputImage = getValueByPath(fromObject, [ + 'enhanceInputImage', + ]); + if (parentObject !== undefined && fromEnhanceInputImage != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'enhanceInputImage'], fromEnhanceInputImage); + } + const fromImagePreservationFactor = getValueByPath(fromObject, [ + 'imagePreservationFactor', + ]); + if (parentObject !== undefined && fromImagePreservationFactor != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'imagePreservationFactor'], fromImagePreservationFactor); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + return toObject; +} +function upscaleImageAPIParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromUpscaleFactor = getValueByPath(fromObject, [ + 'upscaleFactor', + ]); + if (fromUpscaleFactor != null) { + setValueByPath(toObject, ['parameters', 'upscaleConfig', 'upscaleFactor'], fromUpscaleFactor); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], upscaleImageAPIConfigInternalToVertex(fromConfig, toObject)); + } + return toObject; +} +function productImageToVertex(fromObject) { + const toObject = {}; + const fromProductImage = getValueByPath(fromObject, ['productImage']); + if (fromProductImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromProductImage)); + } + return toObject; +} +function recontextImageSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromPersonImage = getValueByPath(fromObject, ['personImage']); + if (parentObject !== undefined && fromPersonImage != null) { + setValueByPath(parentObject, ['instances[0]', 'personImage', 'image'], imageToVertex(fromPersonImage)); + } + const fromProductImages = getValueByPath(fromObject, [ + 'productImages', + ]); + if (parentObject !== undefined && fromProductImages != null) { + let transformedList = fromProductImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return productImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'productImages'], transformedList); + } + return toObject; +} +function recontextImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'editConfig', 'baseSteps'], fromBaseSteps); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function recontextImageParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], recontextImageSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], recontextImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function scribbleImageToVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + return toObject; +} +function segmentImageSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromScribbleImage = getValueByPath(fromObject, [ + 'scribbleImage', + ]); + if (parentObject !== undefined && fromScribbleImage != null) { + setValueByPath(parentObject, ['instances[0]', 'scribble'], scribbleImageToVertex(fromScribbleImage)); + } + return toObject; +} +function segmentImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + const fromMaxPredictions = getValueByPath(fromObject, [ + 'maxPredictions', + ]); + if (parentObject !== undefined && fromMaxPredictions != null) { + setValueByPath(parentObject, ['parameters', 'maxPredictions'], fromMaxPredictions); + } + const fromConfidenceThreshold = getValueByPath(fromObject, [ + 'confidenceThreshold', + ]); + if (parentObject !== undefined && fromConfidenceThreshold != null) { + setValueByPath(parentObject, ['parameters', 'confidenceThreshold'], fromConfidenceThreshold); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (parentObject !== undefined && fromMaskDilation != null) { + setValueByPath(parentObject, ['parameters', 'maskDilation'], fromMaskDilation); + } + const fromBinaryColorThreshold = getValueByPath(fromObject, [ + 'binaryColorThreshold', + ]); + if (parentObject !== undefined && fromBinaryColorThreshold != null) { + setValueByPath(parentObject, ['parameters', 'binaryColorThreshold'], fromBinaryColorThreshold); + } + return toObject; +} +function segmentImageParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], segmentImageSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], segmentImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listModelsConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listModelsConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function updateModelConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateModelConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function deleteModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function countTokensConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['generationConfig'], fromGenerationConfig); + } + return toObject; +} +function countTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function computeTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoToVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['gcsUri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ['videoBytes']); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function videoGenerationReferenceImageToVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + return toObject; +} +function generateVideosConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromFps = getValueByPath(fromObject, ['fps']); + if (parentObject !== undefined && fromFps != null) { + setValueByPath(parentObject, ['parameters', 'fps'], fromFps); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromResolution = getValueByPath(fromObject, ['resolution']); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ['parameters', 'resolution'], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromPubsubTopic = getValueByPath(fromObject, ['pubsubTopic']); + if (parentObject !== undefined && fromPubsubTopic != null) { + setValueByPath(parentObject, ['parameters', 'pubsubTopic'], fromPubsubTopic); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + const fromGenerateAudio = getValueByPath(fromObject, [ + 'generateAudio', + ]); + if (parentObject !== undefined && fromGenerateAudio != null) { + setValueByPath(parentObject, ['parameters', 'generateAudio'], fromGenerateAudio); + } + const fromLastFrame = getValueByPath(fromObject, ['lastFrame']); + if (parentObject !== undefined && fromLastFrame != null) { + setValueByPath(parentObject, ['instances[0]', 'lastFrame'], imageToVertex(fromLastFrame)); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (parentObject !== undefined && fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return videoGenerationReferenceImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromCompressionQuality = getValueByPath(fromObject, [ + 'compressionQuality', + ]); + if (parentObject !== undefined && fromCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'compressionQuality'], fromCompressionQuality); + } + return toObject; +} +function generateVideosParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['instances[0]', 'video'], videoToVertex(fromVideo)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataFromMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromMldev(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingFromMldev(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + return toObject; +} +function embedContentMetadataFromMldev() { + const toObject = {}; + return toObject; +} +function embedContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, ['embeddings']); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromMldev(item); + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromMldev()); + } + return toObject; +} +function imageFromMldev(fromObject) { + const toObject = {}; + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromMldev(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + 'safetyAttributes', + 'categories', + ]); + if (fromCategories != null) { + setValueByPath(toObject, ['categories'], fromCategories); + } + const fromScores = getValueByPath(fromObject, [ + 'safetyAttributes', + 'scores', + ]); + if (fromScores != null) { + setValueByPath(toObject, ['scores'], fromScores); + } + const fromContentType = getValueByPath(fromObject, ['contentType']); + if (fromContentType != null) { + setValueByPath(toObject, ['contentType'], fromContentType); + } + return toObject; +} +function generatedImageFromMldev(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromMldev(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromMldev(fromSafetyAttributes)); + } + return toObject; +} +function generateImagesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromMldev(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromMldev(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function tunedModelInfoFromMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function modelFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['version']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromMldev(fromTunedModelInfo)); + } + const fromInputTokenLimit = getValueByPath(fromObject, [ + 'inputTokenLimit', + ]); + if (fromInputTokenLimit != null) { + setValueByPath(toObject, ['inputTokenLimit'], fromInputTokenLimit); + } + const fromOutputTokenLimit = getValueByPath(fromObject, [ + 'outputTokenLimit', + ]); + if (fromOutputTokenLimit != null) { + setValueByPath(toObject, ['outputTokenLimit'], fromOutputTokenLimit); + } + const fromSupportedActions = getValueByPath(fromObject, [ + 'supportedGenerationMethods', + ]); + if (fromSupportedActions != null) { + setValueByPath(toObject, ['supportedActions'], fromSupportedActions); + } + return toObject; +} +function listModelsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromMldev(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function deleteModelResponseFromMldev() { + const toObject = {}; + return toObject; +} +function countTokensResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + return toObject; +} +function videoFromMldev(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['video', 'uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'video', + 'encodedVideo', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['encoding']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromMldev(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, [ + 'generatedSamples', + ]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromMldev(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosOperationFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, [ + 'response', + 'generateVideoResponse', + ]); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromMldev(fromResponse)); + } + return toObject; +} +function videoMetadataFromVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromVertex(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromVertex(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citations']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromVertex(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromVertex(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromVertex(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromVertex(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromVertex(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromVertex(fromCitationMetadata)); + } + const fromFinishMessage = getValueByPath(fromObject, [ + 'finishMessage', + ]); + if (fromFinishMessage != null) { + setValueByPath(toObject, ['finishMessage'], fromFinishMessage); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromVertex(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromVertex(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingStatisticsFromVertex(fromObject) { + const toObject = {}; + const fromTruncated = getValueByPath(fromObject, ['truncated']); + if (fromTruncated != null) { + setValueByPath(toObject, ['truncated'], fromTruncated); + } + const fromTokenCount = getValueByPath(fromObject, ['token_count']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function contentEmbeddingFromVertex(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + const fromStatistics = getValueByPath(fromObject, ['statistics']); + if (fromStatistics != null) { + setValueByPath(toObject, ['statistics'], contentEmbeddingStatisticsFromVertex(fromStatistics)); + } + return toObject; +} +function embedContentMetadataFromVertex(fromObject) { + const toObject = {}; + const fromBillableCharacterCount = getValueByPath(fromObject, [ + 'billableCharacterCount', + ]); + if (fromBillableCharacterCount != null) { + setValueByPath(toObject, ['billableCharacterCount'], fromBillableCharacterCount); + } + return toObject; +} +function embedContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, [ + 'predictions[]', + 'embeddings', + ]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromVertex(item); + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromVertex(fromMetadata)); + } + return toObject; +} +function imageFromVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromVertex(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + 'safetyAttributes', + 'categories', + ]); + if (fromCategories != null) { + setValueByPath(toObject, ['categories'], fromCategories); + } + const fromScores = getValueByPath(fromObject, [ + 'safetyAttributes', + 'scores', + ]); + if (fromScores != null) { + setValueByPath(toObject, ['scores'], fromScores); + } + const fromContentType = getValueByPath(fromObject, ['contentType']); + if (fromContentType != null) { + setValueByPath(toObject, ['contentType'], fromContentType); + } + return toObject; +} +function generatedImageFromVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromVertex(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromVertex(fromSafetyAttributes)); + } + const fromEnhancedPrompt = getValueByPath(fromObject, ['prompt']); + if (fromEnhancedPrompt != null) { + setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt); + } + return toObject; +} +function generateImagesResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromVertex(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function editImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function upscaleImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function recontextImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function entityLabelFromVertex(fromObject) { + const toObject = {}; + const fromLabel = getValueByPath(fromObject, ['label']); + if (fromLabel != null) { + setValueByPath(toObject, ['label'], fromLabel); + } + const fromScore = getValueByPath(fromObject, ['score']); + if (fromScore != null) { + setValueByPath(toObject, ['score'], fromScore); + } + return toObject; +} +function generatedImageMaskFromVertex(fromObject) { + const toObject = {}; + const fromMask = getValueByPath(fromObject, ['_self']); + if (fromMask != null) { + setValueByPath(toObject, ['mask'], imageFromVertex(fromMask)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + let transformedList = fromLabels; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return entityLabelFromVertex(item); + }); + } + setValueByPath(toObject, ['labels'], transformedList); + } + return toObject; +} +function segmentImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedMasks = getValueByPath(fromObject, ['predictions']); + if (fromGeneratedMasks != null) { + let transformedList = fromGeneratedMasks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageMaskFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedMasks'], transformedList); + } + return toObject; +} +function endpointFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['endpoint']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDeployedModelId = getValueByPath(fromObject, [ + 'deployedModelId', + ]); + if (fromDeployedModelId != null) { + setValueByPath(toObject, ['deployedModelId'], fromDeployedModelId); + } + return toObject; +} +function tunedModelInfoFromVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, [ + 'labels', + 'google-vertex-llm-tuning-base-model-id', + ]); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function checkpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ['checkpointId']); + if (fromCheckpointId != null) { + setValueByPath(toObject, ['checkpointId'], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ['epoch']); + if (fromEpoch != null) { + setValueByPath(toObject, ['epoch'], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ['step']); + if (fromStep != null) { + setValueByPath(toObject, ['step'], fromStep); + } + return toObject; +} +function modelFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['versionId']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromEndpoints = getValueByPath(fromObject, ['deployedModels']); + if (fromEndpoints != null) { + let transformedList = fromEndpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return endpointFromVertex(item); + }); + } + setValueByPath(toObject, ['endpoints'], transformedList); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromVertex(fromTunedModelInfo)); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (fromDefaultCheckpointId != null) { + setValueByPath(toObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + const fromCheckpoints = getValueByPath(fromObject, ['checkpoints']); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return checkpointFromVertex(item); + }); + } + setValueByPath(toObject, ['checkpoints'], transformedList); + } + return toObject; +} +function listModelsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromVertex(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function deleteModelResponseFromVertex() { + const toObject = {}; + return toObject; +} +function countTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + return toObject; +} +function computeTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTokensInfo = getValueByPath(fromObject, ['tokensInfo']); + if (fromTokensInfo != null) { + setValueByPath(toObject, ['tokensInfo'], fromTokensInfo); + } + return toObject; +} +function videoFromVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['gcsUri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromVertex(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ['videos']); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosOperationFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromVertex(fromResponse)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// TODO: b/416041229 - Determine how to retrieve the MCP package version. +const MCP_LABEL = 'mcp_used/unknown'; +// Whether MCP tool usage is detected from mcpToTool. This is used for +// telemetry. +let hasMcpToolUsageFromMcpToTool = false; +// Checks whether the list of tools contains any MCP tools. +function hasMcpToolUsage(tools) { + for (const tool of tools) { + if (isMcpCallableTool(tool)) { + return true; + } + if (typeof tool === 'object' && 'inputSchema' in tool) { + return true; + } + } + return hasMcpToolUsageFromMcpToTool; +} +// Sets the MCP version label in the Google API client header. +function setMcpUsageHeader(headers) { + var _a; + const existingHeader = (_a = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a !== void 0 ? _a : ''; + headers[GOOGLE_API_CLIENT_HEADER] = (existingHeader + ` ${MCP_LABEL}`).trimStart(); +} +// Returns true if the object is a MCP CallableTool, otherwise false. +function isMcpCallableTool(object) { + return (object !== null && + typeof object === 'object' && + object instanceof McpCallableTool); +} +// List all tools from the MCP client. +function listAllTools(mcpClient, maxTools = 100) { + return __asyncGenerator(this, arguments, function* listAllTools_1() { + let cursor = undefined; + let numTools = 0; + while (numTools < maxTools) { + const t = yield __await(mcpClient.listTools({ cursor })); + for (const tool of t.tools) { + yield yield __await(tool); + numTools++; + } + if (!t.nextCursor) { + break; + } + cursor = t.nextCursor; + } + }); +} +/** + * McpCallableTool can be used for model inference and invoking MCP clients with + * given function call arguments. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +class McpCallableTool { + constructor(mcpClients = [], config) { + this.mcpTools = []; + this.functionNameToMcpClient = {}; + this.mcpClients = mcpClients; + this.config = config; + } + /** + * Creates a McpCallableTool. + */ + static create(mcpClients, config) { + return new McpCallableTool(mcpClients, config); + } + /** + * Validates the function names are not duplicate and initialize the function + * name to MCP client mapping. + * + * @throws {Error} if the MCP tools from the MCP clients have duplicate tool + * names. + */ + async initialize() { + var _a, e_1, _b, _c; + if (this.mcpTools.length > 0) { + return; + } + const functionMap = {}; + const mcpTools = []; + for (const mcpClient of this.mcpClients) { + try { + for (var _d = true, _e = (e_1 = void 0, __asyncValues(listAllTools(mcpClient))), _f; _f = await _e.next(), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const mcpTool = _c; + mcpTools.push(mcpTool); + const mcpToolName = mcpTool.name; + if (functionMap[mcpToolName]) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + functionMap[mcpToolName] = mcpClient; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_d && !_a && (_b = _e.return)) await _b.call(_e); + } + finally { if (e_1) throw e_1.error; } + } + } + this.mcpTools = mcpTools; + this.functionNameToMcpClient = functionMap; + } + async tool() { + await this.initialize(); + return mcpToolsToGeminiTool(this.mcpTools, this.config); + } + async callTool(functionCalls) { + await this.initialize(); + const functionCallResponseParts = []; + for (const functionCall of functionCalls) { + if (functionCall.name in this.functionNameToMcpClient) { + const mcpClient = this.functionNameToMcpClient[functionCall.name]; + let requestOptions = undefined; + // TODO: b/424238654 - Add support for finer grained timeout control. + if (this.config.timeout) { + requestOptions = { + timeout: this.config.timeout, + }; + } + const callToolResponse = await mcpClient.callTool({ + name: functionCall.name, + arguments: functionCall.args, + }, + // Set the result schema to undefined to allow MCP to rely on the + // default schema. + undefined, requestOptions); + functionCallResponseParts.push({ + functionResponse: { + name: functionCall.name, + response: callToolResponse.isError + ? { error: callToolResponse } + : callToolResponse, + }, + }); + } + } + return functionCallResponseParts; + } +} +function isMcpClient(client) { + return (client !== null && + typeof client === 'object' && + 'listTools' in client && + typeof client.listTools === 'function'); +} +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +function mcpToTool(...args) { + // Set MCP usage for telemetry. + hasMcpToolUsageFromMcpToTool = true; + if (args.length === 0) { + throw new Error('No MCP clients provided'); + } + const maybeConfig = args[args.length - 1]; + if (isMcpClient(maybeConfig)) { + return McpCallableTool.create(args, {}); + } + return McpCallableTool.create(args.slice(0, args.length - 1), maybeConfig); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveMusicServerMessage, and then calling the onmessage callback. + * Note that the first message which is received from the server is a + * setupComplete message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage$1(apiClient, onmessage, event) { + const serverMessage = new LiveMusicServerMessage(); + let data; + if (event.data instanceof Blob) { + data = JSON.parse(await event.data.text()); + } + else { + data = JSON.parse(event.data); + } + const response = liveMusicServerMessageFromMldev(data); + Object.assign(serverMessage, response); + onmessage(serverMessage); +} +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +class LiveMusic { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + } + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b; + if (this.apiClient.isVertexAI()) { + throw new Error('Live music is not supported for Vertex AI.'); + } + console.warn('Live music generation is experimental and may change in future versions.'); + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + const headers = mapToHeaders$1(this.apiClient.getDefaultHeaders()); + const apiKey = this.apiClient.getApiKey(); + const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`; + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage$1(apiClient, callbacks.onmessage, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap$1(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + const model = tModel(this.apiClient, params.model); + const setup = liveMusicClientSetupToMldev({ + model, + }); + const clientMessage = liveMusicClientMessageToMldev({ setup }); + conn.send(JSON.stringify(clientMessage)); + return new LiveMusicSession(conn, this.apiClient); + } +} +/** + Represents a connection to the API. + + @experimental + */ +class LiveMusicSession { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + async setWeightedPrompts(params) { + if (!params.weightedPrompts || + Object.keys(params.weightedPrompts).length === 0) { + throw new Error('Weighted prompts must be set and contain at least one entry.'); + } + const setWeightedPromptsParameters = liveMusicSetWeightedPromptsParametersToMldev(params); + const clientContent = liveMusicClientContentToMldev(setWeightedPromptsParameters); + this.conn.send(JSON.stringify({ clientContent })); + } + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + async setMusicGenerationConfig(params) { + if (!params.musicGenerationConfig) { + params.musicGenerationConfig = {}; + } + const setConfigParameters = liveMusicSetConfigParametersToMldev(params); + const clientMessage = liveMusicClientMessageToMldev(setConfigParameters); + this.conn.send(JSON.stringify(clientMessage)); + } + sendPlaybackControl(playbackControl) { + const clientMessage = liveMusicClientMessageToMldev({ + playbackControl, + }); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + * Start the music stream. + * + * @experimental + */ + play() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.PLAY); + } + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.PAUSE); + } + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.STOP); + } + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.RESET_CONTEXT); + } + /** + Terminates the WebSocket connection. + + @experimental + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap$1(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders$1(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const FUNCTION_RESPONSE_REQUIRES_ID = 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.'; +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveServerMessages, and then calling the onmessage callback. Note that + * the first message which is received from the server is a setupComplete + * message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage(apiClient, onmessage, event) { + const serverMessage = new LiveServerMessage(); + let jsonData; + if (event.data instanceof Blob) { + jsonData = await event.data.text(); + } + else if (event.data instanceof ArrayBuffer) { + jsonData = new TextDecoder().decode(event.data); + } + else { + jsonData = event.data; + } + const data = JSON.parse(jsonData); + if (apiClient.isVertexAI()) { + const resp = liveServerMessageFromVertex(data); + Object.assign(serverMessage, resp); + } + else { + const resp = liveServerMessageFromMldev(data); + Object.assign(serverMessage, resp); + } + onmessage(serverMessage); +} +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +class Live { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + this.music = new LiveMusic(this.apiClient, this.auth, this.webSocketFactory); + } + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b, _c, _d, _e, _f; + // TODO: b/404946746 - Support per request HTTP options. + if (params.config && params.config.httpOptions) { + throw new Error('The Live module does not support httpOptions at request-level in' + + ' LiveConnectConfig yet. Please use the client-level httpOptions' + + ' configuration instead.'); + } + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + let url; + const clientHeaders = this.apiClient.getHeaders(); + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + setMcpUsageHeader(clientHeaders); + } + const headers = mapToHeaders(clientHeaders); + if (this.apiClient.isVertexAI()) { + url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`; + await this.auth.addAuthHeaders(headers); + } + else { + const apiKey = this.apiClient.getApiKey(); + let method = 'BidiGenerateContent'; + let keyName = 'key'; + if (apiKey === null || apiKey === void 0 ? void 0 : apiKey.startsWith('auth_tokens/')) { + console.warn('Warning: Ephemeral token support is experimental and may change in future versions.'); + if (apiVersion !== 'v1alpha') { + console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."); + } + method = 'BidiGenerateContentConstrained'; + keyName = 'access_token'; + } + url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`; + } + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + var _a; + (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onopen) === null || _a === void 0 ? void 0 : _a.call(callbacks); + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage(apiClient, callbacks.onmessage, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + let transformedModel = tModel(this.apiClient, params.model); + if (this.apiClient.isVertexAI() && + transformedModel.startsWith('publishers/')) { + const project = this.apiClient.getProject(); + const location = this.apiClient.getLocation(); + transformedModel = + `projects/${project}/locations/${location}/` + transformedModel; + } + let clientMessage = {}; + if (this.apiClient.isVertexAI() && + ((_c = params.config) === null || _c === void 0 ? void 0 : _c.responseModalities) === undefined) { + // Set default to AUDIO to align with MLDev API. + if (params.config === undefined) { + params.config = { responseModalities: [exports.Modality.AUDIO] }; + } + else { + params.config.responseModalities = [exports.Modality.AUDIO]; + } + } + if ((_d = params.config) === null || _d === void 0 ? void 0 : _d.generationConfig) { + // Raise deprecation warning for generationConfig. + console.warn('Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).'); + } + const inputTools = (_f = (_e = params.config) === null || _e === void 0 ? void 0 : _e.tools) !== null && _f !== void 0 ? _f : []; + const convertedTools = []; + for (const tool of inputTools) { + if (this.isCallableTool(tool)) { + const callableTool = tool; + convertedTools.push(await callableTool.tool()); + } + else { + convertedTools.push(tool); + } + } + if (convertedTools.length > 0) { + params.config.tools = convertedTools; + } + const liveConnectParameters = { + model: transformedModel, + config: params.config, + callbacks: params.callbacks, + }; + if (this.apiClient.isVertexAI()) { + clientMessage = liveConnectParametersToVertex(this.apiClient, liveConnectParameters); + } + else { + clientMessage = liveConnectParametersToMldev(this.apiClient, liveConnectParameters); + } + delete clientMessage['config']; + conn.send(JSON.stringify(clientMessage)); + return new Session(conn, this.apiClient); + } + // TODO: b/416041229 - Abstract this method to a common place. + isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; + } +} +const defaultLiveSendClientContentParamerters = { + turnComplete: true, +}; +/** + Represents a connection to the API. + + @experimental + */ +class Session { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + tLiveClientContent(apiClient, params) { + if (params.turns !== null && params.turns !== undefined) { + let contents = []; + try { + contents = tContents(params.turns); + if (apiClient.isVertexAI()) { + contents = contents.map((item) => contentToVertex(item)); + } + else { + contents = contents.map((item) => contentToMldev$1(item)); + } + } + catch (_a) { + throw new Error(`Failed to parse client content "turns", type: '${typeof params.turns}'`); + } + return { + clientContent: { turns: contents, turnComplete: params.turnComplete }, + }; + } + return { + clientContent: { turnComplete: params.turnComplete }, + }; + } + tLiveClienttToolResponse(apiClient, params) { + let functionResponses = []; + if (params.functionResponses == null) { + throw new Error('functionResponses is required.'); + } + if (!Array.isArray(params.functionResponses)) { + functionResponses = [params.functionResponses]; + } + else { + functionResponses = params.functionResponses; + } + if (functionResponses.length === 0) { + throw new Error('functionResponses is required.'); + } + for (const functionResponse of functionResponses) { + if (typeof functionResponse !== 'object' || + functionResponse === null || + !('name' in functionResponse) || + !('response' in functionResponse)) { + throw new Error(`Could not parse function response, type '${typeof functionResponse}'.`); + } + if (!apiClient.isVertexAI() && !('id' in functionResponse)) { + throw new Error(FUNCTION_RESPONSE_REQUIRES_ID); + } + } + const clientMessage = { + toolResponse: { functionResponses: functionResponses }, + }; + return clientMessage; + } + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params) { + params = Object.assign(Object.assign({}, defaultLiveSendClientContentParamerters), params); + const clientMessage = this.tLiveClientContent(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params) { + let clientMessage = {}; + if (this.apiClient.isVertexAI()) { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToVertex(params), + }; + } + else { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToMldev(params), + }; + } + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params) { + if (params.functionResponses == null) { + throw new Error('Tool response parameters are required.'); + } + const clientMessage = this.tLiveClienttToolResponse(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const DEFAULT_MAX_REMOTE_CALLS = 10; +/** Returns whether automatic function calling is disabled. */ +function shouldDisableAfc(config) { + var _a, _b, _c; + if ((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.disable) { + return true; + } + let callableToolsPresent = false; + for (const tool of (_b = config === null || config === void 0 ? void 0 : config.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + callableToolsPresent = true; + break; + } + } + if (!callableToolsPresent) { + return true; + } + const maxCalls = (_c = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _c === void 0 ? void 0 : _c.maximumRemoteCalls; + if ((maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) || + maxCalls == 0) { + console.warn('Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:', maxCalls); + return true; + } + return false; +} +function isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; +} +// Checks whether the list of tools contains any CallableTools. Will return true +// if there is at least one CallableTool. +function hasCallableTools(params) { + var _a, _b, _c; + return (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +// Checks whether the list of tools contains any non-callable tools. Will return +// true if there is at least one non-Callable tool. +function hasNonCallableTools(params) { + var _a, _b, _c; + return (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => !isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +/** + * Returns whether to append automatic function calling history to the + * response. + */ +function shouldAppendAfcHistory(config) { + var _a; + return !((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.ignoreCallHistory); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Models extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + this.generateContent = async (params) => { + var _a, _b, _c, _d, _e; + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + this.maybeMoveToResponseJsonSchem(params); + if (!hasCallableTools(params) || shouldDisableAfc(params.config)) { + return await this.generateContentInternal(transformedParams); + } + if (hasNonCallableTools(params)) { + throw new Error('Automatic function calling with CallableTools and Tools is not yet supported.'); + } + let response; + let functionResponseContent; + const automaticFunctionCallingHistory = tContents(transformedParams.contents); + const maxRemoteCalls = (_c = (_b = (_a = transformedParams.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let remoteCalls = 0; + while (remoteCalls < maxRemoteCalls) { + response = await this.generateContentInternal(transformedParams); + if (!response.functionCalls || response.functionCalls.length === 0) { + break; + } + const responseContent = response.candidates[0].content; + const functionResponseParts = []; + for (const tool of (_e = (_d = params.config) === null || _d === void 0 ? void 0 : _d.tools) !== null && _e !== void 0 ? _e : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const parts = await callableTool.callTool(response.functionCalls); + functionResponseParts.push(...parts); + } + } + remoteCalls++; + functionResponseContent = { + role: 'user', + parts: functionResponseParts, + }; + transformedParams.contents = tContents(transformedParams.contents); + transformedParams.contents.push(responseContent); + transformedParams.contents.push(functionResponseContent); + if (shouldAppendAfcHistory(transformedParams.config)) { + automaticFunctionCallingHistory.push(responseContent); + automaticFunctionCallingHistory.push(functionResponseContent); + } + } + if (shouldAppendAfcHistory(transformedParams.config)) { + response.automaticFunctionCallingHistory = + automaticFunctionCallingHistory; + } + return response; + }; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + this.generateContentStream = async (params) => { + this.maybeMoveToResponseJsonSchem(params); + if (shouldDisableAfc(params.config)) { + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + return await this.generateContentStreamInternal(transformedParams); + } + else { + return await this.processAfcStream(params); + } + }; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.generateImages = async (params) => { + return await this.generateImagesInternal(params).then((apiResponse) => { + var _a; + let positivePromptSafetyAttributes; + const generatedImages = []; + if (apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.generatedImages) { + for (const generatedImage of apiResponse.generatedImages) { + if (generatedImage && + (generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) && + ((_a = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) === null || _a === void 0 ? void 0 : _a.contentType) === 'Positive Prompt') { + positivePromptSafetyAttributes = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes; + } + else { + generatedImages.push(generatedImage); + } + } + } + let response; + if (positivePromptSafetyAttributes) { + response = { + generatedImages: generatedImages, + positivePromptSafetyAttributes: positivePromptSafetyAttributes, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + else { + response = { + generatedImages: generatedImages, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + return response; + }); + }; + this.list = async (params) => { + var _a; + const defaultConfig = { + queryBase: true, + }; + const actualConfig = Object.assign(Object.assign({}, defaultConfig), params === null || params === void 0 ? void 0 : params.config); + const actualParams = { + config: actualConfig, + }; + if (this.apiClient.isVertexAI()) { + if (!actualParams.config.queryBase) { + if ((_a = actualParams.config) === null || _a === void 0 ? void 0 : _a.filter) { + throw new Error('Filtering tuned models list for Vertex AI is not currently supported'); + } + else { + actualParams.config.filter = 'labels.tune-type:*'; + } + } + } + return new Pager(exports.PagedItem.PAGED_ITEM_MODELS, (x) => this.listInternal(x), await this.listInternal(actualParams), actualParams); + }; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.editImage = async (params) => { + const paramsInternal = { + model: params.model, + prompt: params.prompt, + referenceImages: [], + config: params.config, + }; + if (params.referenceImages) { + if (params.referenceImages) { + paramsInternal.referenceImages = params.referenceImages.map((img) => img.toReferenceImageAPI()); + } + } + return await this.editImageInternal(paramsInternal); + }; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.upscaleImage = async (params) => { + let apiConfig = { + numberOfImages: 1, + mode: 'upscale', + }; + if (params.config) { + apiConfig = Object.assign(Object.assign({}, apiConfig), params.config); + } + const apiParams = { + model: params.model, + image: params.image, + upscaleFactor: params.upscaleFactor, + config: apiConfig, + }; + return await this.upscaleImageInternal(apiParams); + }; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + this.generateVideos = async (params) => { + return await this.generateVideosInternal(params); + }; + } + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + maybeMoveToResponseJsonSchem(params) { + if (params.config && params.config.responseSchema) { + if (!params.config.responseJsonSchema) { + if (Object.keys(params.config.responseSchema).includes('$schema')) { + params.config.responseJsonSchema = params.config.responseSchema; + delete params.config.responseSchema; + } + } + } + return; + } + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + async processParamsMaybeAddMcpUsage(params) { + var _a, _b, _c; + const tools = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools; + if (!tools) { + return params; + } + const transformedTools = await Promise.all(tools.map(async (tool) => { + if (isCallableTool(tool)) { + const callableTool = tool; + return await callableTool.tool(); + } + return tool; + })); + const newParams = { + model: params.model, + contents: params.contents, + config: Object.assign(Object.assign({}, params.config), { tools: transformedTools }), + }; + newParams.config.tools = transformedTools; + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + const headers = (_c = (_b = params.config.httpOptions) === null || _b === void 0 ? void 0 : _b.headers) !== null && _c !== void 0 ? _c : {}; + let newHeaders = Object.assign({}, headers); + if (Object.keys(newHeaders).length === 0) { + newHeaders = this.apiClient.getDefaultHeaders(); + } + setMcpUsageHeader(newHeaders); + newParams.config.httpOptions = Object.assign(Object.assign({}, params.config.httpOptions), { headers: newHeaders }); + } + return newParams; + } + async initAfcToolsMap(params) { + var _a, _b, _c; + const afcTools = new Map(); + for (const tool of (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const toolDeclaration = await callableTool.tool(); + for (const declaration of (_c = toolDeclaration.functionDeclarations) !== null && _c !== void 0 ? _c : []) { + if (!declaration.name) { + throw new Error('Function declaration name is required.'); + } + if (afcTools.has(declaration.name)) { + throw new Error(`Duplicate tool declaration name: ${declaration.name}`); + } + afcTools.set(declaration.name, callableTool); + } + } + } + return afcTools; + } + async processAfcStream(params) { + var _a, _b, _c; + const maxRemoteCalls = (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let wereFunctionsCalled = false; + let remoteCallCount = 0; + const afcToolsMap = await this.initAfcToolsMap(params); + return (function (models, afcTools, params) { + var _a, _b; + return __asyncGenerator(this, arguments, function* () { + var _c, e_1, _d, _e; + while (remoteCallCount < maxRemoteCalls) { + if (wereFunctionsCalled) { + remoteCallCount++; + wereFunctionsCalled = false; + } + const transformedParams = yield __await(models.processParamsMaybeAddMcpUsage(params)); + const response = yield __await(models.generateContentStreamInternal(transformedParams)); + const functionResponses = []; + const responseContents = []; + try { + for (var _f = true, response_1 = (e_1 = void 0, __asyncValues(response)), response_1_1; response_1_1 = yield __await(response_1.next()), _c = response_1_1.done, !_c; _f = true) { + _e = response_1_1.value; + _f = false; + const chunk = _e; + yield yield __await(chunk); + if (chunk.candidates && ((_a = chunk.candidates[0]) === null || _a === void 0 ? void 0 : _a.content)) { + responseContents.push(chunk.candidates[0].content); + for (const part of (_b = chunk.candidates[0].content.parts) !== null && _b !== void 0 ? _b : []) { + if (remoteCallCount < maxRemoteCalls && part.functionCall) { + if (!part.functionCall.name) { + throw new Error('Function call name was not returned by the model.'); + } + if (!afcTools.has(part.functionCall.name)) { + throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${part.functionCall.name}`); + } + else { + const responseParts = yield __await(afcTools + .get(part.functionCall.name) + .callTool([part.functionCall])); + functionResponses.push(...responseParts); + } + } + } + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_c && (_d = response_1.return)) yield __await(_d.call(response_1)); + } + finally { if (e_1) throw e_1.error; } + } + if (functionResponses.length > 0) { + wereFunctionsCalled = true; + const typedResponseChunk = new GenerateContentResponse(); + typedResponseChunk.candidates = [ + { + content: { + role: 'user', + parts: functionResponses, + }, + }, + ]; + yield yield __await(typedResponseChunk); + const newContents = []; + newContents.push(...responseContents); + newContents.push({ + role: 'user', + parts: functionResponses, + }); + const updatedContents = tContents(params.contents).concat(newContents); + params.contents = updatedContents; + } + else { + break; + } + } + }); + })(this, afcToolsMap, params); + } + async generateContentInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromVertex(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromMldev(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async generateContentStreamInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_2, _b, _c; + try { + for (var _d = true, apiResponse_1 = __asyncValues(apiResponse), apiResponse_1_1; apiResponse_1_1 = yield __await(apiResponse_1.next()), _a = apiResponse_1_1.done, !_a; _d = true) { + _c = apiResponse_1_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromVertex((yield __await(chunk.json()))); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_1.return)) yield __await(_b.call(apiResponse_1)); + } + finally { if (e_2) throw e_2.error; } + } + }); + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_3, _b, _c; + try { + for (var _d = true, apiResponse_2 = __asyncValues(apiResponse), apiResponse_2_1; apiResponse_2_1 = yield __await(apiResponse_2.next()), _a = apiResponse_2_1.done, !_a; _d = true) { + _c = apiResponse_2_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromMldev((yield __await(chunk.json()))); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_2.return)) yield __await(_b.call(apiResponse_2)); + } + finally { if (e_3) throw e_3.error; } + } + }); + }); + } + } + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + async embedContent(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = embedContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromVertex(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = embedContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchEmbedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromMldev(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async generateImagesInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateImagesParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromVertex(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateImagesParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromMldev(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async editImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = editImageParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = editImageResponseFromVertex(apiResponse); + const typedResp = new EditImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + async upscaleImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = upscaleImageAPIParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = upscaleImageResponseFromVertex(apiResponse); + const typedResp = new UpscaleImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Recontextualizes an image. + * + * There are two types of recontextualization currently supported: + * 1) Imagen Product Recontext - Generate images of products in new scenes + * and contexts. + * 2) Virtual Try-On: Generate images of persons modeling fashion products. + * + * @param params - The parameters for recontextualizing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response1 = await ai.models.recontextImage({ + * model: 'imagen-product-recontext-preview-06-30', + * source: { + * prompt: 'In a modern kitchen setting.', + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response1?.generatedImages?.[0]?.image?.imageBytes); + * + * const response2 = await ai.models.recontextImage({ + * model: 'virtual-try-on-preview-08-04', + * source: { + * personImage: personImage, + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response2?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async recontextImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = recontextImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = recontextImageResponseFromVertex(apiResponse); + const typedResp = new RecontextImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Segments an image, creating a mask of a specified area. + * + * @param params - The parameters for segmenting an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.segmentImage({ + * model: 'image-segmentation-001', + * source: { + * image: image, + * }, + * config: { + * mode: 'foreground', + * }, + * }); + * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes); + * ``` + */ + async segmentImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = segmentImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = segmentImageResponseFromVertex(apiResponse); + const typedResp = new SegmentImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listModelsParametersToVertex(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromVertex(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listModelsParametersToMldev(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromMldev(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateModelParametersToVertex(this.apiClient, params); + path = formatMap('{model}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = updateModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteModelResponseFromVertex(); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteModelResponseFromMldev(); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + async countTokens(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = countTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromVertex(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = countTokensParametersToMldev(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromMldev(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + async computeTokens(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = computeTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:computeTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = computeTokensResponseFromVertex(apiResponse); + const typedResp = new ComputeTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + async generateVideosInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateVideosParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateVideosParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getOperationParametersToMldev(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fetchPredictOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['operationName'], fromOperationName); + } + const fromResourceName = getValueByPath(fromObject, ['resourceName']); + if (fromResourceName != null) { + setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Operations extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async getVideosOperation(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async get(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + async getVideosOperationInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getOperationParametersToVertex(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + const body = getOperationParametersToMldev(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + } + async fetchPredictVideosOperationInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = fetchPredictOperationParametersToVertex(params); + path = formatMap('{resourceName}:fetchPredictOperation', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is not supported in Gemini API.'); + } + return toObject; +} +function audioTranscriptionConfigToMldev() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToMldev(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToMldev(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToMldev(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToMldev(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToMldev()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToMldev()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToMldev(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToMldev(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToMldev(fromProactivity)); + } + return toObject; +} +function liveConnectConstraintsToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function createAuthTokenConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromNewSessionExpireTime = getValueByPath(fromObject, [ + 'newSessionExpireTime', + ]); + if (parentObject !== undefined && fromNewSessionExpireTime != null) { + setValueByPath(parentObject, ['newSessionExpireTime'], fromNewSessionExpireTime); + } + const fromUses = getValueByPath(fromObject, ['uses']); + if (parentObject !== undefined && fromUses != null) { + setValueByPath(parentObject, ['uses'], fromUses); + } + const fromLiveConnectConstraints = getValueByPath(fromObject, [ + 'liveConnectConstraints', + ]); + if (parentObject !== undefined && fromLiveConnectConstraints != null) { + setValueByPath(parentObject, ['bidiGenerateContentSetup'], liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints)); + } + const fromLockAdditionalFields = getValueByPath(fromObject, [ + 'lockAdditionalFields', + ]); + if (parentObject !== undefined && fromLockAdditionalFields != null) { + setValueByPath(parentObject, ['fieldMask'], fromLockAdditionalFields); + } + return toObject; +} +function createAuthTokenParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createAuthTokenConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function authTokenFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns a comma-separated list of field masks from a given object. + * + * @param setup The object to extract field masks from. + * @return A comma-separated list of field masks. + */ +function getFieldMasks(setup) { + const fields = []; + for (const key in setup) { + if (Object.prototype.hasOwnProperty.call(setup, key)) { + const value = setup[key]; + // 2nd layer, recursively get field masks see TODO(b/418290100) + if (typeof value === 'object' && + value != null && + Object.keys(value).length > 0) { + const field = Object.keys(value).map((kk) => `${key}.${kk}`); + fields.push(...field); + } + else { + fields.push(key); // 1st layer + } + } + } + return fields.join(','); +} +/** + * Converts bidiGenerateContentSetup. + * @param requestDict - The request dictionary. + * @param config - The configuration object. + * @return - The modified request dictionary. + */ +function convertBidiSetupToTokenSetup(requestDict, config) { + // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup. + let setupForMaskGeneration = null; + const bidiGenerateContentSetupValue = requestDict['bidiGenerateContentSetup']; + if (typeof bidiGenerateContentSetupValue === 'object' && + bidiGenerateContentSetupValue !== null && + 'setup' in bidiGenerateContentSetupValue) { + // Now we know bidiGenerateContentSetupValue is an object and has a 'setup' + // property. + const innerSetup = bidiGenerateContentSetupValue + .setup; + if (typeof innerSetup === 'object' && innerSetup !== null) { + // Valid inner setup found. + requestDict['bidiGenerateContentSetup'] = innerSetup; + setupForMaskGeneration = innerSetup; + } + else { + // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as + // if bidiGenerateContentSetup is invalid. + delete requestDict['bidiGenerateContentSetup']; + } + } + else if (bidiGenerateContentSetupValue !== undefined) { + // `bidiGenerateContentSetup` exists but not in the expected + // shape {setup: {...}}; treat as invalid. + delete requestDict['bidiGenerateContentSetup']; + } + const preExistingFieldMask = requestDict['fieldMask']; + // Handle mask generation setup. + if (setupForMaskGeneration) { + const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration); + if (Array.isArray(config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + (config === null || config === void 0 ? void 0 : config.lockAdditionalFields.length) === 0) { + // Case 1: lockAdditionalFields is an empty array. Lock only fields from + // bidi setup. + if (generatedMaskFromBidi) { + // Only assign if mask is not empty + requestDict['fieldMask'] = generatedMaskFromBidi; + } + else { + delete requestDict['fieldMask']; // If mask is empty, effectively no + // specific fields locked by bidi + } + } + else if ((config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + config.lockAdditionalFields.length > 0 && + preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // Case 2: Lock fields from bidi setup + additional fields + // (preExistingFieldMask). + const generationConfigFields = [ + 'temperature', + 'topK', + 'topP', + 'maxOutputTokens', + 'responseModalities', + 'seed', + 'speechConfig', + ]; + let mappedFieldsFromPreExisting = []; + if (preExistingFieldMask.length > 0) { + mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => { + if (generationConfigFields.includes(field)) { + return `generationConfig.${field}`; + } + return field; // Keep original field name if not in + // generationConfigFields + }); + } + const finalMaskParts = []; + if (generatedMaskFromBidi) { + finalMaskParts.push(generatedMaskFromBidi); + } + if (mappedFieldsFromPreExisting.length > 0) { + finalMaskParts.push(...mappedFieldsFromPreExisting); + } + if (finalMaskParts.length > 0) { + requestDict['fieldMask'] = finalMaskParts.join(','); + } + else { + // If no fields from bidi and no valid additional fields from + // pre-existing mask. + delete requestDict['fieldMask']; + } + } + else { + // Case 3: "Lock all fields" (meaning, don't send a field_mask, let server + // defaults apply or all are mutable). This is hit if: + // - `config.lockAdditionalFields` is undefined. + // - `config.lockAdditionalFields` is non-empty, BUT + // `preExistingFieldMask` is null, not a string, or an empty string. + delete requestDict['fieldMask']; + } + } + else { + // No valid `bidiGenerateContentSetup` was found or extracted. + // "Lock additional null fields if any". + if (preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // If there's a pre-existing field mask, it's a string, and it's not + // empty, then we should lock all fields. + requestDict['fieldMask'] = preExistingFieldMask.join(','); + } + else { + delete requestDict['fieldMask']; + } + } + return requestDict; +} +class Tokens extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + async create(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('The client.tokens.create method is only supported by the Gemini Developer API.'); + } + else { + const body = createAuthTokenParametersToMldev(this.apiClient, params); + path = formatMap('auth_tokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const transformedBody = convertBidiSetupToTokenSetup(body, params.config); + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(transformedBody), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = authTokenFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listTuningJobsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function tuningExampleToMldev(fromObject) { + const toObject = {}; + const fromTextInput = getValueByPath(fromObject, ['textInput']); + if (fromTextInput != null) { + setValueByPath(toObject, ['textInput'], fromTextInput); + } + const fromOutput = getValueByPath(fromObject, ['output']); + if (fromOutput != null) { + setValueByPath(toObject, ['output'], fromOutput); + } + return toObject; +} +function tuningDatasetToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['vertexDatasetResource']) !== undefined) { + throw new Error('vertexDatasetResource parameter is not supported in Gemini API.'); + } + const fromExamples = getValueByPath(fromObject, ['examples']); + if (fromExamples != null) { + let transformedList = fromExamples; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningExampleToMldev(item); + }); + } + setValueByPath(toObject, ['examples', 'examples'], transformedList); + } + return toObject; +} +function createTuningJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['validationDataset']) !== undefined) { + throw new Error('validationDataset parameter is not supported in Gemini API.'); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromTunedModelDisplayName); + } + if (getValueByPath(fromObject, ['description']) !== undefined) { + throw new Error('description parameter is not supported in Gemini API.'); + } + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (fromLearningRateMultiplier != null) { + setValueByPath(toObject, ['tuningTask', 'hyperparameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + if (getValueByPath(fromObject, ['exportLastCheckpointOnly']) !== + undefined) { + throw new Error('exportLastCheckpointOnly parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['preTunedModelCheckpointId']) !== + undefined) { + throw new Error('preTunedModelCheckpointId parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['adapterSize']) !== undefined) { + throw new Error('adapterSize parameter is not supported in Gemini API.'); + } + const fromBatchSize = getValueByPath(fromObject, ['batchSize']); + if (parentObject !== undefined && fromBatchSize != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'batchSize'], fromBatchSize); + } + const fromLearningRate = getValueByPath(fromObject, ['learningRate']); + if (parentObject !== undefined && fromLearningRate != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'learningRate'], fromLearningRate); + } + return toObject; +} +function createTuningJobParametersPrivateToMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + setValueByPath(toObject, ['tuningTask', 'trainingData'], tuningDatasetToMldev(fromTrainingDataset)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createTuningJobConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listTuningJobsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function tuningDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (parentObject !== undefined && fromGcsUri != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + if (getValueByPath(fromObject, ['examples']) !== undefined) { + throw new Error('examples parameter is not supported in Vertex AI.'); + } + return toObject; +} +function tuningValidationDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['validationDatasetUri'], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + return toObject; +} +function createTuningJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromValidationDataset = getValueByPath(fromObject, [ + 'validationDataset', + ]); + if (parentObject !== undefined && fromValidationDataset != null) { + setValueByPath(parentObject, ['supervisedTuningSpec'], tuningValidationDatasetToVertex(fromValidationDataset, toObject)); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (parentObject !== undefined && fromLearningRateMultiplier != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + const fromExportLastCheckpointOnly = getValueByPath(fromObject, [ + 'exportLastCheckpointOnly', + ]); + if (parentObject !== undefined && fromExportLastCheckpointOnly != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'exportLastCheckpointOnly'], fromExportLastCheckpointOnly); + } + const fromPreTunedModelCheckpointId = getValueByPath(fromObject, [ + 'preTunedModelCheckpointId', + ]); + if (fromPreTunedModelCheckpointId != null) { + setValueByPath(toObject, ['preTunedModel', 'checkpointId'], fromPreTunedModelCheckpointId); + } + const fromAdapterSize = getValueByPath(fromObject, ['adapterSize']); + if (parentObject !== undefined && fromAdapterSize != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'], fromAdapterSize); + } + if (getValueByPath(fromObject, ['batchSize']) !== undefined) { + throw new Error('batchSize parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['learningRate']) !== undefined) { + throw new Error('learningRate parameter is not supported in Vertex AI.'); + } + return toObject; +} +function createTuningJobParametersPrivateToVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + setValueByPath(toObject, ['supervisedTuningSpec', 'trainingDatasetUri'], tuningDatasetToVertex(fromTrainingDataset, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createTuningJobConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function tunedModelFromMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['name']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ['name']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + return toObject; +} +function tuningJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, [ + 'tuningTask', + 'startTime', + ]); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'tuningTask', + 'completeTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['_self']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], tunedModelFromMldev(fromTunedModel)); + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel); + } + const fromExperiment = getValueByPath(fromObject, ['experiment']); + if (fromExperiment != null) { + setValueByPath(toObject, ['experiment'], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (fromOutputUri != null) { + setValueByPath(toObject, ['outputUri'], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject, ['pipelineJob']); + if (fromPipelineJob != null) { + setValueByPath(toObject, ['pipelineJob'], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject, [ + 'serviceAccount', + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ['serviceAccount'], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + return toObject; +} +function listTuningJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ['tunedModels']); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromMldev(item); + }); + } + setValueByPath(toObject, ['tuningJobs'], transformedList); + } + return toObject; +} +function tuningOperationFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + return toObject; +} +function tunedModelCheckpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ['checkpointId']); + if (fromCheckpointId != null) { + setValueByPath(toObject, ['checkpointId'], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ['epoch']); + if (fromEpoch != null) { + setValueByPath(toObject, ['epoch'], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ['step']); + if (fromStep != null) { + setValueByPath(toObject, ['step'], fromStep); + } + const fromEndpoint = getValueByPath(fromObject, ['endpoint']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + return toObject; +} +function tunedModelFromVertex(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ['endpoint']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + const fromCheckpoints = getValueByPath(fromObject, ['checkpoints']); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tunedModelCheckpointFromVertex(item); + }); + } + setValueByPath(toObject, ['checkpoints'], transformedList); + } + return toObject; +} +function tuningJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['tunedModel']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], tunedModelFromVertex(fromTunedModel)); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromSupervisedTuningSpec = getValueByPath(fromObject, [ + 'supervisedTuningSpec', + ]); + if (fromSupervisedTuningSpec != null) { + setValueByPath(toObject, ['supervisedTuningSpec'], fromSupervisedTuningSpec); + } + const fromTuningDataStats = getValueByPath(fromObject, [ + 'tuningDataStats', + ]); + if (fromTuningDataStats != null) { + setValueByPath(toObject, ['tuningDataStats'], fromTuningDataStats); + } + const fromEncryptionSpec = getValueByPath(fromObject, [ + 'encryptionSpec', + ]); + if (fromEncryptionSpec != null) { + setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec); + } + const fromPartnerModelTuningSpec = getValueByPath(fromObject, [ + 'partnerModelTuningSpec', + ]); + if (fromPartnerModelTuningSpec != null) { + setValueByPath(toObject, ['partnerModelTuningSpec'], fromPartnerModelTuningSpec); + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel); + } + const fromExperiment = getValueByPath(fromObject, ['experiment']); + if (fromExperiment != null) { + setValueByPath(toObject, ['experiment'], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (fromOutputUri != null) { + setValueByPath(toObject, ['outputUri'], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject, ['pipelineJob']); + if (fromPipelineJob != null) { + setValueByPath(toObject, ['pipelineJob'], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject, [ + 'serviceAccount', + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ['serviceAccount'], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + return toObject; +} +function listTuningJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ['tuningJobs']); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromVertex(item); + }); + } + setValueByPath(toObject, ['tuningJobs'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Tunings extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.get = async (params) => { + return await this.getInternal(params); + }; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.list = async (params = {}) => { + return new Pager(exports.PagedItem.PAGED_ITEM_TUNING_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.tune = async (params) => { + if (this.apiClient.isVertexAI()) { + if (params.baseModel.startsWith('projects/')) { + const preTunedModel = { + tunedModelName: params.baseModel, + }; + const paramsPrivate = Object.assign(Object.assign({}, params), { preTunedModel: preTunedModel }); + paramsPrivate.baseModel = undefined; + return await this.tuneInternal(paramsPrivate); + } + else { + const paramsPrivate = Object.assign({}, params); + return await this.tuneInternal(paramsPrivate); + } + } + else { + const paramsPrivate = Object.assign({}, params); + const operation = await this.tuneMldevInternal(paramsPrivate); + let tunedModelName = ''; + if (operation['metadata'] !== undefined && + operation['metadata']['tunedModel'] !== undefined) { + tunedModelName = operation['metadata']['tunedModel']; + } + else if (operation['name'] !== undefined && + operation['name'].includes('/operations/')) { + tunedModelName = operation['name'].split('/operations/')[0]; + } + const tuningJob = { + name: tunedModelName, + state: exports.JobState.JOB_STATE_QUEUED, + }; + return tuningJob; + } + }; + } + async getInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getTuningJobParametersToVertex(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getTuningJobParametersToMldev(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listTuningJobsParametersToVertex(params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromVertex(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listTuningJobsParametersToMldev(params); + path = formatMap('tunedModels', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromMldev(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async tuneInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createTuningJobParametersPrivateToVertex(params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + async tuneMldevInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createTuningJobParametersPrivateToMldev(params); + path = formatMap('tunedModels', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningOperationFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const GOOGLE_API_KEY_HEADER = 'x-goog-api-key'; +// TODO(b/395122533): We need a secure client side authentication mechanism. +class WebAuth { + constructor(apiKey) { + this.apiKey = apiKey; + } + async addAuthHeaders(headers) { + if (headers.get(GOOGLE_API_KEY_HEADER) !== null) { + return; + } + if (this.apiKey.startsWith('auth_tokens/')) { + throw new Error('Ephemeral tokens are only supported by the live API.'); + } + // Check if API key is empty or null + if (!this.apiKey) { + throw new Error('API key is missing. Please provide a valid API key.'); + } + headers.append(GOOGLE_API_KEY_HEADER, this.apiKey); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const LANGUAGE_LABEL_PREFIX = 'gl-node/'; +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} + * or the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be set, + * when using Vertex AI {@link GoogleGenAIOptions.project} and {@link GoogleGenAIOptions.location} must also be set. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +class GoogleGenAI { + constructor(options) { + var _a; + if (options.apiKey == null) { + throw new Error(`An API Key must be set when running in an unspecified environment.\n + ${crossError().message}`); + } + this.vertexai = (_a = options.vertexai) !== null && _a !== void 0 ? _a : false; + this.apiKey = options.apiKey; + this.apiVersion = options.apiVersion; + const auth = new WebAuth(this.apiKey); + this.apiClient = new ApiClient({ + auth: auth, + apiVersion: this.apiVersion, + apiKey: this.apiKey, + vertexai: this.vertexai, + httpOptions: options.httpOptions, + userAgentExtra: LANGUAGE_LABEL_PREFIX + 'cross', + uploader: new CrossUploader(), + downloader: new CrossDownloader(), + }); + this.models = new Models(this.apiClient); + this.live = new Live(this.apiClient, auth, new CrossWebSocketFactory()); + this.chats = new Chats(this.models, this.apiClient); + this.batches = new Batches(this.apiClient); + this.caches = new Caches(this.apiClient); + this.files = new Files(this.apiClient); + this.operations = new Operations(this.apiClient); + this.authTokens = new Tokens(this.apiClient); + this.tunings = new Tunings(this.apiClient); + } +} + +exports.ApiError = ApiError; +exports.Batches = Batches; +exports.Caches = Caches; +exports.Chat = Chat; +exports.Chats = Chats; +exports.ComputeTokensResponse = ComputeTokensResponse; +exports.ControlReferenceImage = ControlReferenceImage; +exports.CountTokensResponse = CountTokensResponse; +exports.CreateFileResponse = CreateFileResponse; +exports.DeleteCachedContentResponse = DeleteCachedContentResponse; +exports.DeleteFileResponse = DeleteFileResponse; +exports.DeleteModelResponse = DeleteModelResponse; +exports.EditImageResponse = EditImageResponse; +exports.EmbedContentResponse = EmbedContentResponse; +exports.Files = Files; +exports.FunctionResponse = FunctionResponse; +exports.GenerateContentResponse = GenerateContentResponse; +exports.GenerateContentResponsePromptFeedback = GenerateContentResponsePromptFeedback; +exports.GenerateContentResponseUsageMetadata = GenerateContentResponseUsageMetadata; +exports.GenerateImagesResponse = GenerateImagesResponse; +exports.GenerateVideosOperation = GenerateVideosOperation; +exports.GenerateVideosResponse = GenerateVideosResponse; +exports.GoogleGenAI = GoogleGenAI; +exports.HttpResponse = HttpResponse; +exports.InlinedResponse = InlinedResponse; +exports.ListBatchJobsResponse = ListBatchJobsResponse; +exports.ListCachedContentsResponse = ListCachedContentsResponse; +exports.ListFilesResponse = ListFilesResponse; +exports.ListModelsResponse = ListModelsResponse; +exports.ListTuningJobsResponse = ListTuningJobsResponse; +exports.Live = Live; +exports.LiveClientToolResponse = LiveClientToolResponse; +exports.LiveMusicServerMessage = LiveMusicServerMessage; +exports.LiveSendToolResponseParameters = LiveSendToolResponseParameters; +exports.LiveServerMessage = LiveServerMessage; +exports.MaskReferenceImage = MaskReferenceImage; +exports.Models = Models; +exports.Operations = Operations; +exports.Pager = Pager; +exports.RawReferenceImage = RawReferenceImage; +exports.RecontextImageResponse = RecontextImageResponse; +exports.ReplayResponse = ReplayResponse; +exports.SegmentImageResponse = SegmentImageResponse; +exports.Session = Session; +exports.StyleReferenceImage = StyleReferenceImage; +exports.SubjectReferenceImage = SubjectReferenceImage; +exports.Tokens = Tokens; +exports.UpscaleImageResponse = UpscaleImageResponse; +exports.createModelContent = createModelContent; +exports.createPartFromBase64 = createPartFromBase64; +exports.createPartFromCodeExecutionResult = createPartFromCodeExecutionResult; +exports.createPartFromExecutableCode = createPartFromExecutableCode; +exports.createPartFromFunctionCall = createPartFromFunctionCall; +exports.createPartFromFunctionResponse = createPartFromFunctionResponse; +exports.createPartFromText = createPartFromText; +exports.createPartFromUri = createPartFromUri; +exports.createUserContent = createUserContent; +exports.mcpToTool = mcpToTool; +exports.setDefaultBaseUrls = setDefaultBaseUrls; +//# sourceMappingURL=index.cjs.map diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/index.mjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..dc3d3b90baba384471dac46562ccbd20bd9c58ff --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/index.mjs @@ -0,0 +1,18657 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +function setDefaultBaseUrls(baseUrlParams) { + baseUrlParams.geminiUrl; + baseUrlParams.vertexUrl; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BaseModule { +} +function formatMap(templateString, valueMap) { + // Use a regular expression to find all placeholders in the template string + const regex = /\{([^}]+)\}/g; + // Replace each placeholder with its corresponding value from the valueMap + return templateString.replace(regex, (match, key) => { + if (Object.prototype.hasOwnProperty.call(valueMap, key)) { + const value = valueMap[key]; + // Convert the value to a string if it's not a string already + return value !== undefined && value !== null ? String(value) : ''; + } + else { + // Handle missing keys + throw new Error(`Key '${key}' not found in valueMap.`); + } + }); +} +function setValueByPath(data, keys, value) { + for (let i = 0; i < keys.length - 1; i++) { + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (!(keyName in data)) { + if (Array.isArray(value)) { + data[keyName] = Array.from({ length: value.length }, () => ({})); + } + else { + throw new Error(`Value must be a list given an array path ${key}`); + } + } + if (Array.isArray(data[keyName])) { + const arrayData = data[keyName]; + if (Array.isArray(value)) { + for (let j = 0; j < arrayData.length; j++) { + const entry = arrayData[j]; + setValueByPath(entry, keys.slice(i + 1), value[j]); + } + } + else { + for (const d of arrayData) { + setValueByPath(d, keys.slice(i + 1), value); + } + } + } + return; + } + else if (key.endsWith('[0]')) { + const keyName = key.slice(0, -3); + if (!(keyName in data)) { + data[keyName] = [{}]; + } + const arrayData = data[keyName]; + setValueByPath(arrayData[0], keys.slice(i + 1), value); + return; + } + if (!data[key] || typeof data[key] !== 'object') { + data[key] = {}; + } + data = data[key]; + } + const keyToSet = keys[keys.length - 1]; + const existingData = data[keyToSet]; + if (existingData !== undefined) { + if (!value || + (typeof value === 'object' && Object.keys(value).length === 0)) { + return; + } + if (value === existingData) { + return; + } + if (typeof existingData === 'object' && + typeof value === 'object' && + existingData !== null && + value !== null) { + Object.assign(existingData, value); + } + else { + throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`); + } + } + else { + data[keyToSet] = value; + } +} +function getValueByPath(data, keys) { + try { + if (keys.length === 1 && keys[0] === '_self') { + return data; + } + for (let i = 0; i < keys.length; i++) { + if (typeof data !== 'object' || data === null) { + return undefined; + } + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (keyName in data) { + const arrayData = data[keyName]; + if (!Array.isArray(arrayData)) { + return undefined; + } + return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1))); + } + else { + return undefined; + } + } + else { + data = data[key]; + } + } + return data; + } + catch (error) { + if (error instanceof TypeError) { + return undefined; + } + throw error; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tBytes$1(fromBytes) { + if (typeof fromBytes !== 'string') { + throw new Error('fromImageBytes must be a string'); + } + // TODO(b/389133914): Remove dummy bytes converter. + return fromBytes; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +/** Required. Outcome of the code execution. */ +var Outcome; +(function (Outcome) { + /** + * Unspecified status. This value should not be used. + */ + Outcome["OUTCOME_UNSPECIFIED"] = "OUTCOME_UNSPECIFIED"; + /** + * Code execution completed successfully. + */ + Outcome["OUTCOME_OK"] = "OUTCOME_OK"; + /** + * Code execution finished but with a failure. `stderr` should contain the reason. + */ + Outcome["OUTCOME_FAILED"] = "OUTCOME_FAILED"; + /** + * Code execution ran for too long, and was cancelled. There may or may not be a partial output present. + */ + Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "OUTCOME_DEADLINE_EXCEEDED"; +})(Outcome || (Outcome = {})); +/** Required. Programming language of the `code`. */ +var Language; +(function (Language) { + /** + * Unspecified language. This value should not be used. + */ + Language["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED"; + /** + * Python >= 3.10, with numpy and simpy available. + */ + Language["PYTHON"] = "PYTHON"; +})(Language || (Language = {})); +/** Optional. The type of the data. */ +var Type; +(function (Type) { + /** + * Not specified, should not be used. + */ + Type["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + /** + * OpenAPI string type + */ + Type["STRING"] = "STRING"; + /** + * OpenAPI number type + */ + Type["NUMBER"] = "NUMBER"; + /** + * OpenAPI integer type + */ + Type["INTEGER"] = "INTEGER"; + /** + * OpenAPI boolean type + */ + Type["BOOLEAN"] = "BOOLEAN"; + /** + * OpenAPI array type + */ + Type["ARRAY"] = "ARRAY"; + /** + * OpenAPI object type + */ + Type["OBJECT"] = "OBJECT"; + /** + * Null type + */ + Type["NULL"] = "NULL"; +})(Type || (Type = {})); +/** Required. Harm category. */ +var HarmCategory; +(function (HarmCategory) { + /** + * The harm category is unspecified. + */ + HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + /** + * The harm category is hate speech. + */ + HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + /** + * The harm category is dangerous content. + */ + HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT"; + /** + * The harm category is harassment. + */ + HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + /** + * The harm category is sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY"; + /** + * The harm category is image hate. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE"; + /** + * The harm category is image dangerous content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"; + /** + * The harm category is image harassment. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HARASSMENT"] = "HARM_CATEGORY_IMAGE_HARASSMENT"; + /** + * The harm category is image sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"; +})(HarmCategory || (HarmCategory = {})); +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +var HarmBlockMethod; +(function (HarmBlockMethod) { + /** + * The harm block method is unspecified. + */ + HarmBlockMethod["HARM_BLOCK_METHOD_UNSPECIFIED"] = "HARM_BLOCK_METHOD_UNSPECIFIED"; + /** + * The harm block method uses both probability and severity scores. + */ + HarmBlockMethod["SEVERITY"] = "SEVERITY"; + /** + * The harm block method uses the probability score. + */ + HarmBlockMethod["PROBABILITY"] = "PROBABILITY"; +})(HarmBlockMethod || (HarmBlockMethod = {})); +/** Required. The harm block threshold. */ +var HarmBlockThreshold; +(function (HarmBlockThreshold) { + /** + * Unspecified harm block threshold. + */ + HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + /** + * Block low threshold and above (i.e. block more). + */ + HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + /** + * Block medium threshold and above. + */ + HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + /** + * Block only high threshold (i.e. block less). + */ + HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + /** + * Block none. + */ + HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; + /** + * Turn off the safety filter. + */ + HarmBlockThreshold["OFF"] = "OFF"; +})(HarmBlockThreshold || (HarmBlockThreshold = {})); +/** The mode of the predictor to be used in dynamic retrieval. */ +var Mode; +(function (Mode) { + /** + * Always trigger retrieval. + */ + Mode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + Mode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(Mode || (Mode = {})); +/** Type of auth scheme. */ +var AuthType; +(function (AuthType) { + AuthType["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED"; + /** + * No Auth. + */ + AuthType["NO_AUTH"] = "NO_AUTH"; + /** + * API Key Auth. + */ + AuthType["API_KEY_AUTH"] = "API_KEY_AUTH"; + /** + * HTTP Basic Auth. + */ + AuthType["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH"; + /** + * Google Service Account Auth. + */ + AuthType["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH"; + /** + * OAuth auth. + */ + AuthType["OAUTH"] = "OAUTH"; + /** + * OpenID Connect (OIDC) Auth. + */ + AuthType["OIDC_AUTH"] = "OIDC_AUTH"; +})(AuthType || (AuthType = {})); +/** The API spec that the external API implements. */ +var ApiSpec; +(function (ApiSpec) { + /** + * Unspecified API spec. This value should not be used. + */ + ApiSpec["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED"; + /** + * Simple search API spec. + */ + ApiSpec["SIMPLE_SEARCH"] = "SIMPLE_SEARCH"; + /** + * Elastic search API spec. + */ + ApiSpec["ELASTIC_SEARCH"] = "ELASTIC_SEARCH"; +})(ApiSpec || (ApiSpec = {})); +/** Status of the url retrieval. */ +var UrlRetrievalStatus; +(function (UrlRetrievalStatus) { + /** + * Default value. This value is unused + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = "URL_RETRIEVAL_STATUS_UNSPECIFIED"; + /** + * Url retrieval is successful. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_SUCCESS"] = "URL_RETRIEVAL_STATUS_SUCCESS"; + /** + * Url retrieval is failed due to error. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_ERROR"] = "URL_RETRIEVAL_STATUS_ERROR"; + /** + * Url retrieval is failed because the content is behind paywall. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_PAYWALL"] = "URL_RETRIEVAL_STATUS_PAYWALL"; + /** + * Url retrieval is failed because the content is unsafe. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSAFE"] = "URL_RETRIEVAL_STATUS_UNSAFE"; +})(UrlRetrievalStatus || (UrlRetrievalStatus = {})); +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +var FinishReason; +(function (FinishReason) { + /** + * The finish reason is unspecified. + */ + FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + FinishReason["STOP"] = "STOP"; + /** + * Token generation reached the configured maximum output tokens. + */ + FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + FinishReason["SAFETY"] = "SAFETY"; + /** + * The token generation stopped because of potential recitation. + */ + FinishReason["RECITATION"] = "RECITATION"; + /** + * The token generation stopped because of using an unsupported language. + */ + FinishReason["LANGUAGE"] = "LANGUAGE"; + /** + * All other reasons that stopped the token generation. + */ + FinishReason["OTHER"] = "OTHER"; + /** + * Token generation stopped because the content contains forbidden terms. + */ + FinishReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Token generation stopped for potentially containing prohibited content. + */ + FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). + */ + FinishReason["SPII"] = "SPII"; + /** + * The function call generated by the model is invalid. + */ + FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; + /** + * Token generation stopped because generated images have safety violations. + */ + FinishReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; + /** + * The tool call generated by the model is invalid. + */ + FinishReason["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL"; +})(FinishReason || (FinishReason = {})); +/** Output only. Harm probability levels in the content. */ +var HarmProbability; +(function (HarmProbability) { + /** + * Harm probability unspecified. + */ + HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED"; + /** + * Negligible level of harm. + */ + HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; + /** + * Low level of harm. + */ + HarmProbability["LOW"] = "LOW"; + /** + * Medium level of harm. + */ + HarmProbability["MEDIUM"] = "MEDIUM"; + /** + * High level of harm. + */ + HarmProbability["HIGH"] = "HIGH"; +})(HarmProbability || (HarmProbability = {})); +/** Output only. Harm severity levels in the content. */ +var HarmSeverity; +(function (HarmSeverity) { + /** + * Harm severity unspecified. + */ + HarmSeverity["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED"; + /** + * Negligible level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE"; + /** + * Low level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW"; + /** + * Medium level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM"; + /** + * High level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH"; +})(HarmSeverity || (HarmSeverity = {})); +/** Output only. Blocked reason. */ +var BlockedReason; +(function (BlockedReason) { + /** + * Unspecified blocked reason. + */ + BlockedReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + /** + * Candidates blocked due to safety. + */ + BlockedReason["SAFETY"] = "SAFETY"; + /** + * Candidates blocked due to other reason. + */ + BlockedReason["OTHER"] = "OTHER"; + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BlockedReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Candidates blocked due to prohibited content. + */ + BlockedReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Candidates blocked due to unsafe image generation content. + */ + BlockedReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; +})(BlockedReason || (BlockedReason = {})); +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +var TrafficType; +(function (TrafficType) { + /** + * Unspecified request traffic type. + */ + TrafficType["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED"; + /** + * Type for Pay-As-You-Go traffic. + */ + TrafficType["ON_DEMAND"] = "ON_DEMAND"; + /** + * Type for Provisioned Throughput traffic. + */ + TrafficType["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT"; +})(TrafficType || (TrafficType = {})); +/** Server content modalities. */ +var Modality; +(function (Modality) { + /** + * The modality is unspecified. + */ + Modality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Indicates the model should return text + */ + Modality["TEXT"] = "TEXT"; + /** + * Indicates the model should return images. + */ + Modality["IMAGE"] = "IMAGE"; + /** + * Indicates the model should return audio. + */ + Modality["AUDIO"] = "AUDIO"; +})(Modality || (Modality = {})); +/** The media resolution to use. */ +var MediaResolution; +(function (MediaResolution) { + /** + * Media resolution has not been set + */ + MediaResolution["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED"; + /** + * Media resolution set to low (64 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + /** + * Media resolution set to medium (256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; +})(MediaResolution || (MediaResolution = {})); +/** Job state. */ +var JobState; +(function (JobState) { + /** + * The job state is unspecified. + */ + JobState["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED"; + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JobState["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED"; + /** + * The service is preparing to run the job. + */ + JobState["JOB_STATE_PENDING"] = "JOB_STATE_PENDING"; + /** + * The job is in progress. + */ + JobState["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING"; + /** + * The job completed successfully. + */ + JobState["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED"; + /** + * The job failed. + */ + JobState["JOB_STATE_FAILED"] = "JOB_STATE_FAILED"; + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JobState["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING"; + /** + * The job has been cancelled. + */ + JobState["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED"; + /** + * The job has been stopped, and can be resumed. + */ + JobState["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED"; + /** + * The job has expired. + */ + JobState["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED"; + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JobState["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING"; + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JobState["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED"; +})(JobState || (JobState = {})); +/** Tuning mode. */ +var TuningMode; +(function (TuningMode) { + /** + * Tuning mode is unspecified. + */ + TuningMode["TUNING_MODE_UNSPECIFIED"] = "TUNING_MODE_UNSPECIFIED"; + /** + * Full fine-tuning mode. + */ + TuningMode["TUNING_MODE_FULL"] = "TUNING_MODE_FULL"; + /** + * PEFT adapter tuning mode. + */ + TuningMode["TUNING_MODE_PEFT_ADAPTER"] = "TUNING_MODE_PEFT_ADAPTER"; +})(TuningMode || (TuningMode = {})); +/** Optional. Adapter size for tuning. */ +var AdapterSize; +(function (AdapterSize) { + /** + * Adapter size is unspecified. + */ + AdapterSize["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED"; + /** + * Adapter size 1. + */ + AdapterSize["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE"; + /** + * Adapter size 2. + */ + AdapterSize["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO"; + /** + * Adapter size 4. + */ + AdapterSize["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR"; + /** + * Adapter size 8. + */ + AdapterSize["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT"; + /** + * Adapter size 16. + */ + AdapterSize["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN"; + /** + * Adapter size 32. + */ + AdapterSize["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO"; +})(AdapterSize || (AdapterSize = {})); +/** Options for feature selection preference. */ +var FeatureSelectionPreference; +(function (FeatureSelectionPreference) { + FeatureSelectionPreference["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"; + FeatureSelectionPreference["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY"; + FeatureSelectionPreference["BALANCED"] = "BALANCED"; + FeatureSelectionPreference["PRIORITIZE_COST"] = "PRIORITIZE_COST"; +})(FeatureSelectionPreference || (FeatureSelectionPreference = {})); +/** Defines the function behavior. Defaults to `BLOCKING`. */ +var Behavior; +(function (Behavior) { + /** + * This value is unused. + */ + Behavior["UNSPECIFIED"] = "UNSPECIFIED"; + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + Behavior["BLOCKING"] = "BLOCKING"; + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + Behavior["NON_BLOCKING"] = "NON_BLOCKING"; +})(Behavior || (Behavior = {})); +/** Config for the dynamic retrieval config mode. */ +var DynamicRetrievalConfigMode; +(function (DynamicRetrievalConfigMode) { + /** + * Always trigger retrieval. + */ + DynamicRetrievalConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + DynamicRetrievalConfigMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(DynamicRetrievalConfigMode || (DynamicRetrievalConfigMode = {})); +/** The environment being operated. */ +var Environment; +(function (Environment) { + /** + * Defaults to browser. + */ + Environment["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED"; + /** + * Operates in a web browser. + */ + Environment["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER"; +})(Environment || (Environment = {})); +/** Config for the function calling config mode. */ +var FunctionCallingConfigMode; +(function (FunctionCallingConfigMode) { + /** + * The function calling config mode is unspecified. Should not be used. + */ + FunctionCallingConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + FunctionCallingConfigMode["AUTO"] = "AUTO"; + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + FunctionCallingConfigMode["ANY"] = "ANY"; + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + FunctionCallingConfigMode["NONE"] = "NONE"; +})(FunctionCallingConfigMode || (FunctionCallingConfigMode = {})); +/** Enum that controls the safety filter level for objectionable content. */ +var SafetyFilterLevel; +(function (SafetyFilterLevel) { + SafetyFilterLevel["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + SafetyFilterLevel["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + SafetyFilterLevel["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + SafetyFilterLevel["BLOCK_NONE"] = "BLOCK_NONE"; +})(SafetyFilterLevel || (SafetyFilterLevel = {})); +/** Enum that controls the generation of people. */ +var PersonGeneration; +(function (PersonGeneration) { + /** + * Block generation of images of people. + */ + PersonGeneration["DONT_ALLOW"] = "DONT_ALLOW"; + /** + * Generate images of adults, but not children. + */ + PersonGeneration["ALLOW_ADULT"] = "ALLOW_ADULT"; + /** + * Generate images that include adults and children. + */ + PersonGeneration["ALLOW_ALL"] = "ALLOW_ALL"; +})(PersonGeneration || (PersonGeneration = {})); +/** Enum that specifies the language of the text in the prompt. */ +var ImagePromptLanguage; +(function (ImagePromptLanguage) { + /** + * Auto-detect the language. + */ + ImagePromptLanguage["auto"] = "auto"; + /** + * English + */ + ImagePromptLanguage["en"] = "en"; + /** + * Japanese + */ + ImagePromptLanguage["ja"] = "ja"; + /** + * Korean + */ + ImagePromptLanguage["ko"] = "ko"; + /** + * Hindi + */ + ImagePromptLanguage["hi"] = "hi"; + /** + * Chinese + */ + ImagePromptLanguage["zh"] = "zh"; + /** + * Portuguese + */ + ImagePromptLanguage["pt"] = "pt"; + /** + * Spanish + */ + ImagePromptLanguage["es"] = "es"; +})(ImagePromptLanguage || (ImagePromptLanguage = {})); +/** Enum representing the mask mode of a mask reference image. */ +var MaskReferenceMode; +(function (MaskReferenceMode) { + MaskReferenceMode["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT"; + MaskReferenceMode["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED"; + MaskReferenceMode["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND"; + MaskReferenceMode["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND"; + MaskReferenceMode["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC"; +})(MaskReferenceMode || (MaskReferenceMode = {})); +/** Enum representing the control type of a control reference image. */ +var ControlReferenceType; +(function (ControlReferenceType) { + ControlReferenceType["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT"; + ControlReferenceType["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY"; + ControlReferenceType["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE"; + ControlReferenceType["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH"; +})(ControlReferenceType || (ControlReferenceType = {})); +/** Enum representing the subject type of a subject reference image. */ +var SubjectReferenceType; +(function (SubjectReferenceType) { + SubjectReferenceType["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT"; + SubjectReferenceType["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON"; + SubjectReferenceType["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL"; + SubjectReferenceType["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT"; +})(SubjectReferenceType || (SubjectReferenceType = {})); +/** Enum representing the Imagen 3 Edit mode. */ +var EditMode; +(function (EditMode) { + EditMode["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT"; + EditMode["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL"; + EditMode["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION"; + EditMode["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT"; + EditMode["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING"; + EditMode["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE"; + EditMode["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP"; + EditMode["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE"; +})(EditMode || (EditMode = {})); +/** Enum that represents the segmentation mode. */ +var SegmentMode; +(function (SegmentMode) { + SegmentMode["FOREGROUND"] = "FOREGROUND"; + SegmentMode["BACKGROUND"] = "BACKGROUND"; + SegmentMode["PROMPT"] = "PROMPT"; + SegmentMode["SEMANTIC"] = "SEMANTIC"; + SegmentMode["INTERACTIVE"] = "INTERACTIVE"; +})(SegmentMode || (SegmentMode = {})); +/** Enum that controls the compression quality of the generated videos. */ +var VideoCompressionQuality; +(function (VideoCompressionQuality) { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + VideoCompressionQuality["OPTIMIZED"] = "OPTIMIZED"; + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + VideoCompressionQuality["LOSSLESS"] = "LOSSLESS"; +})(VideoCompressionQuality || (VideoCompressionQuality = {})); +/** State for the lifecycle of a File. */ +var FileState; +(function (FileState) { + FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + FileState["PROCESSING"] = "PROCESSING"; + FileState["ACTIVE"] = "ACTIVE"; + FileState["FAILED"] = "FAILED"; +})(FileState || (FileState = {})); +/** Source of the File. */ +var FileSource; +(function (FileSource) { + FileSource["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED"; + FileSource["UPLOADED"] = "UPLOADED"; + FileSource["GENERATED"] = "GENERATED"; +})(FileSource || (FileSource = {})); +/** Server content modalities. */ +var MediaModality; +(function (MediaModality) { + /** + * The modality is unspecified. + */ + MediaModality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Plain text. + */ + MediaModality["TEXT"] = "TEXT"; + /** + * Images. + */ + MediaModality["IMAGE"] = "IMAGE"; + /** + * Video. + */ + MediaModality["VIDEO"] = "VIDEO"; + /** + * Audio. + */ + MediaModality["AUDIO"] = "AUDIO"; + /** + * Document, e.g. PDF. + */ + MediaModality["DOCUMENT"] = "DOCUMENT"; +})(MediaModality || (MediaModality = {})); +/** Start of speech sensitivity. */ +var StartSensitivity; +(function (StartSensitivity) { + /** + * The default is START_SENSITIVITY_LOW. + */ + StartSensitivity["START_SENSITIVITY_UNSPECIFIED"] = "START_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection will detect the start of speech more often. + */ + StartSensitivity["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH"; + /** + * Automatic detection will detect the start of speech less often. + */ + StartSensitivity["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW"; +})(StartSensitivity || (StartSensitivity = {})); +/** End of speech sensitivity. */ +var EndSensitivity; +(function (EndSensitivity) { + /** + * The default is END_SENSITIVITY_LOW. + */ + EndSensitivity["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection ends speech more often. + */ + EndSensitivity["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH"; + /** + * Automatic detection ends speech less often. + */ + EndSensitivity["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW"; +})(EndSensitivity || (EndSensitivity = {})); +/** The different ways of handling user activity. */ +var ActivityHandling; +(function (ActivityHandling) { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ActivityHandling["ACTIVITY_HANDLING_UNSPECIFIED"] = "ACTIVITY_HANDLING_UNSPECIFIED"; + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + ActivityHandling["START_OF_ACTIVITY_INTERRUPTS"] = "START_OF_ACTIVITY_INTERRUPTS"; + /** + * The model's response will not be interrupted. + */ + ActivityHandling["NO_INTERRUPTION"] = "NO_INTERRUPTION"; +})(ActivityHandling || (ActivityHandling = {})); +/** Options about which input is included in the user's turn. */ +var TurnCoverage; +(function (TurnCoverage) { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TurnCoverage["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED"; + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TurnCoverage["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY"; + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TurnCoverage["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT"; +})(TurnCoverage || (TurnCoverage = {})); +/** Specifies how the response should be scheduled in the conversation. */ +var FunctionResponseScheduling; +(function (FunctionResponseScheduling) { + /** + * This value is unused. + */ + FunctionResponseScheduling["SCHEDULING_UNSPECIFIED"] = "SCHEDULING_UNSPECIFIED"; + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + FunctionResponseScheduling["SILENT"] = "SILENT"; + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + FunctionResponseScheduling["WHEN_IDLE"] = "WHEN_IDLE"; + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + FunctionResponseScheduling["INTERRUPT"] = "INTERRUPT"; +})(FunctionResponseScheduling || (FunctionResponseScheduling = {})); +/** Scale of the generated music. */ +var Scale; +(function (Scale) { + /** + * Default value. This value is unused. + */ + Scale["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED"; + /** + * C major or A minor. + */ + Scale["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR"; + /** + * Db major or Bb minor. + */ + Scale["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR"; + /** + * D major or B minor. + */ + Scale["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR"; + /** + * Eb major or C minor + */ + Scale["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR"; + /** + * E major or Db minor. + */ + Scale["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR"; + /** + * F major or D minor. + */ + Scale["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR"; + /** + * Gb major or Eb minor. + */ + Scale["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR"; + /** + * G major or E minor. + */ + Scale["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR"; + /** + * Ab major or F minor. + */ + Scale["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR"; + /** + * A major or Gb minor. + */ + Scale["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR"; + /** + * Bb major or G minor. + */ + Scale["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR"; + /** + * B major or Ab minor. + */ + Scale["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR"; +})(Scale || (Scale = {})); +/** The mode of music generation. */ +var MusicGenerationMode; +(function (MusicGenerationMode) { + /** + * Rely on the server default generation mode. + */ + MusicGenerationMode["MUSIC_GENERATION_MODE_UNSPECIFIED"] = "MUSIC_GENERATION_MODE_UNSPECIFIED"; + /** + * Steer text prompts to regions of latent space with higher quality + music. + */ + MusicGenerationMode["QUALITY"] = "QUALITY"; + /** + * Steer text prompts to regions of latent space with a larger + diversity of music. + */ + MusicGenerationMode["DIVERSITY"] = "DIVERSITY"; + /** + * Steer text prompts to regions of latent space more likely to + generate music with vocals. + */ + MusicGenerationMode["VOCALIZATION"] = "VOCALIZATION"; +})(MusicGenerationMode || (MusicGenerationMode = {})); +/** The playback control signal to apply to the music generation. */ +var LiveMusicPlaybackControl; +(function (LiveMusicPlaybackControl) { + /** + * This value is unused. + */ + LiveMusicPlaybackControl["PLAYBACK_CONTROL_UNSPECIFIED"] = "PLAYBACK_CONTROL_UNSPECIFIED"; + /** + * Start generating the music. + */ + LiveMusicPlaybackControl["PLAY"] = "PLAY"; + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + LiveMusicPlaybackControl["PAUSE"] = "PAUSE"; + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + LiveMusicPlaybackControl["STOP"] = "STOP"; + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + LiveMusicPlaybackControl["RESET_CONTEXT"] = "RESET_CONTEXT"; +})(LiveMusicPlaybackControl || (LiveMusicPlaybackControl = {})); +/** A function response. */ +class FunctionResponse { +} +/** + * Creates a `Part` object from a `URI` string. + */ +function createPartFromUri(uri, mimeType) { + return { + fileData: { + fileUri: uri, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from a `text` string. + */ +function createPartFromText(text) { + return { + text: text, + }; +} +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +function createPartFromFunctionCall(name, args) { + return { + functionCall: { + name: name, + args: args, + }, + }; +} +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +function createPartFromFunctionResponse(id, name, response) { + return { + functionResponse: { + id: id, + name: name, + response: response, + }, + }; +} +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +function createPartFromBase64(data, mimeType) { + return { + inlineData: { + data: data, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +function createPartFromCodeExecutionResult(outcome, output) { + return { + codeExecutionResult: { + outcome: outcome, + output: output, + }, + }; +} +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +function createPartFromExecutableCode(code, language) { + return { + executableCode: { + code: code, + language: language, + }, + }; +} +function _isPart(obj) { + if (typeof obj === 'object' && obj !== null) { + return ('fileData' in obj || + 'text' in obj || + 'functionCall' in obj || + 'functionResponse' in obj || + 'inlineData' in obj || + 'videoMetadata' in obj || + 'codeExecutionResult' in obj || + 'executableCode' in obj); + } + return false; +} +function _toParts(partOrString) { + const parts = []; + if (typeof partOrString === 'string') { + parts.push(createPartFromText(partOrString)); + } + else if (_isPart(partOrString)) { + parts.push(partOrString); + } + else if (Array.isArray(partOrString)) { + if (partOrString.length === 0) { + throw new Error('partOrString cannot be an empty array'); + } + for (const part of partOrString) { + if (typeof part === 'string') { + parts.push(createPartFromText(part)); + } + else if (_isPart(part)) { + parts.push(part); + } + else { + throw new Error('element in PartUnion must be a Part object or string'); + } + } + } + else { + throw new Error('partOrString must be a Part object, string, or array'); + } + return parts; +} +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +function createUserContent(partOrString) { + return { + role: 'user', + parts: _toParts(partOrString), + }; +} +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +function createModelContent(partOrString) { + return { + role: 'model', + parts: _toParts(partOrString), + }; +} +/** A wrapper class for the http response. */ +class HttpResponse { + constructor(response) { + // Process the headers. + const headers = {}; + for (const pair of response.headers.entries()) { + headers[pair[0]] = pair[1]; + } + this.headers = headers; + // Keep the original response. + this.responseInternal = response; + } + json() { + return this.responseInternal.json(); + } +} +/** Content filter results for a prompt sent in the request. */ +class GenerateContentResponsePromptFeedback { +} +/** Usage metadata about response(s). */ +class GenerateContentResponseUsageMetadata { +} +/** Response message for PredictionService.GenerateContent. */ +class GenerateContentResponse { + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning text from the first one.'); + } + let text = ''; + let anyTextPartText = false; + const nonTextParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + (fieldValue !== null || fieldValue !== undefined)) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartText = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartText ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning data from the first one.'); + } + let data = ''; + const nonDataParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && + (fieldValue !== null || fieldValue !== undefined)) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning function calls from the first one.'); + } + const functionCalls = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.functionCall).map((part) => part.functionCall).filter((functionCall) => functionCall !== undefined); + if ((functionCalls === null || functionCalls === void 0 ? void 0 : functionCalls.length) === 0) { + return undefined; + } + return functionCalls; + } + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning executable code from the first one.'); + } + const executableCode = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.executableCode).map((part) => part.executableCode).filter((executableCode) => executableCode !== undefined); + if ((executableCode === null || executableCode === void 0 ? void 0 : executableCode.length) === 0) { + return undefined; + } + return (_j = executableCode === null || executableCode === void 0 ? void 0 : executableCode[0]) === null || _j === void 0 ? void 0 : _j.code; + } + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning code execution result from the first one.'); + } + const codeExecutionResult = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.codeExecutionResult).map((part) => part.codeExecutionResult).filter((codeExecutionResult) => codeExecutionResult !== undefined); + if ((codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult.length) === 0) { + return undefined; + } + return (_j = codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult[0]) === null || _j === void 0 ? void 0 : _j.output; + } +} +/** Response for the embed_content method. */ +class EmbedContentResponse { +} +/** The output images response. */ +class GenerateImagesResponse { +} +/** Response for the request to edit an image. */ +class EditImageResponse { +} +class UpscaleImageResponse { +} +/** The output images response. */ +class RecontextImageResponse { +} +/** The output images response. */ +class SegmentImageResponse { +} +class ListModelsResponse { +} +class DeleteModelResponse { +} +/** Response for counting tokens. */ +class CountTokensResponse { +} +/** Response for computing tokens. */ +class ComputeTokensResponse { +} +/** Response with generated videos. */ +class GenerateVideosResponse { +} +/** Response for the list tuning jobs method. */ +class ListTuningJobsResponse { +} +/** Empty response for caches.delete method. */ +class DeleteCachedContentResponse { +} +class ListCachedContentsResponse { +} +/** Response for the list files method. */ +class ListFilesResponse { +} +/** Response for the create file method. */ +class CreateFileResponse { +} +/** Response for the delete file method. */ +class DeleteFileResponse { +} +/** Config for `inlined_responses` parameter. */ +class InlinedResponse { +} +/** Config for batches.list return value. */ +class ListBatchJobsResponse { +} +/** Represents a single response in a replay. */ +class ReplayResponse { +} +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +class RawReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_RAW', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + }; + return referenceImageAPI; + } +} +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +class MaskReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_MASK', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + maskImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +class ControlReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_CONTROL', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + controlImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +class StyleReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_STYLE', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + styleImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +class SubjectReferenceImage { + /* Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_SUBJECT', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + subjectImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** Response message for API call. */ +class LiveServerMessage { + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text() { + var _a, _b, _c; + let text = ''; + let anyTextPartFound = false; + const nonTextParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + fieldValue !== null) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartFound = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartFound ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c; + let data = ''; + const nonDataParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && fieldValue !== null) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } +} +/** A video generation long-running operation. */ +class GenerateVideosOperation { + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }) { + const operation = new GenerateVideosOperation(); + operation.name = apiResponse['name']; + operation.metadata = apiResponse['metadata']; + operation.done = apiResponse['done']; + operation.error = apiResponse['error']; + if (isVertexAI) { + const response = apiResponse['response']; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const responseVideos = response['videos']; + operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => { + return { + video: { + uri: generatedVideo['gcsUri'], + videoBytes: generatedVideo['bytesBase64Encoded'] + ? tBytes$1(generatedVideo['bytesBase64Encoded']) + : undefined, + mimeType: generatedVideo['mimeType'], + }, + }; + }); + operationResponse.raiMediaFilteredCount = response['raiMediaFilteredCount']; + operationResponse.raiMediaFilteredReasons = response['raiMediaFilteredReasons']; + operation.response = operationResponse; + } + } + else { + const response = apiResponse['response']; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const generatedVideoResponse = response['generateVideoResponse']; + const responseVideos = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['generatedSamples']; + operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => { + const video = generatedVideo['video']; + return { + video: { + uri: video === null || video === void 0 ? void 0 : video['uri'], + videoBytes: (video === null || video === void 0 ? void 0 : video['encodedVideo']) + ? tBytes$1(video === null || video === void 0 ? void 0 : video['encodedVideo']) + : undefined, + mimeType: generatedVideo['encoding'], + }, + }; + }); + operationResponse.raiMediaFilteredCount = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['raiMediaFilteredCount']; + operationResponse.raiMediaFilteredReasons = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['raiMediaFilteredReasons']; + operation.response = operationResponse; + } + } + return operation; + } +} +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +class LiveClientToolResponse { +} +/** Parameters for sending tool responses to the live API. */ +class LiveSendToolResponseParameters { + constructor() { + /** Tool responses to send to the session. */ + this.functionResponses = []; + } +} +/** Response message for the LiveMusicClientMessage call. */ +class LiveMusicServerMessage { + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk() { + if (this.serverContent && + this.serverContent.audioChunks && + this.serverContent.audioChunks.length > 0) { + return this.serverContent.audioChunks[0]; + } + return undefined; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tModel(apiClient, model) { + if (!model || typeof model !== 'string') { + throw new Error('model is required and must be a string'); + } + if (apiClient.isVertexAI()) { + if (model.startsWith('publishers/') || + model.startsWith('projects/') || + model.startsWith('models/')) { + return model; + } + else if (model.indexOf('/') >= 0) { + const parts = model.split('/', 2); + return `publishers/${parts[0]}/models/${parts[1]}`; + } + else { + return `publishers/google/models/${model}`; + } + } + else { + if (model.startsWith('models/') || model.startsWith('tunedModels/')) { + return model; + } + else { + return `models/${model}`; + } + } +} +function tCachesModel(apiClient, model) { + const transformedModel = tModel(apiClient, model); + if (!transformedModel) { + return ''; + } + if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) { + // vertex caches only support model name start with projects. + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`; + } + else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) { + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`; + } + else { + return transformedModel; + } +} +function tBlobs(blobs) { + if (Array.isArray(blobs)) { + return blobs.map((blob) => tBlob(blob)); + } + else { + return [tBlob(blobs)]; + } +} +function tBlob(blob) { + if (typeof blob === 'object' && blob !== null) { + return blob; + } + throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof blob}`); +} +function tImageBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('image/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tAudioBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('audio/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tPart(origin) { + if (origin === null || origin === undefined) { + throw new Error('PartUnion is required'); + } + if (typeof origin === 'object') { + return origin; + } + if (typeof origin === 'string') { + return { text: origin }; + } + throw new Error(`Unsupported part type: ${typeof origin}`); +} +function tParts(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('PartListUnion is required'); + } + if (Array.isArray(origin)) { + return origin.map((item) => tPart(item)); + } + return [tPart(origin)]; +} +function _isContent(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'parts' in origin && + Array.isArray(origin.parts)); +} +function _isFunctionCallPart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionCall' in origin); +} +function _isFunctionResponsePart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionResponse' in origin); +} +function tContent(origin) { + if (origin === null || origin === undefined) { + throw new Error('ContentUnion is required'); + } + if (_isContent(origin)) { + // _isContent is a utility function that checks if the + // origin is a Content. + return origin; + } + return { + role: 'user', + parts: tParts(origin), + }; +} +function tContentsForEmbed(apiClient, origin) { + if (!origin) { + return []; + } + if (apiClient.isVertexAI() && Array.isArray(origin)) { + return origin.flatMap((item) => { + const content = tContent(item); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + }); + } + else if (apiClient.isVertexAI()) { + const content = tContent(origin); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + } + if (Array.isArray(origin)) { + return origin.map((item) => tContent(item)); + } + return [tContent(origin)]; +} +function tContents(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('contents are required'); + } + if (!Array.isArray(origin)) { + // If it's not an array, it's a single content or a single PartUnion. + if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them'); + } + return [tContent(origin)]; + } + const result = []; + const accumulatedParts = []; + const isContentArray = _isContent(origin[0]); + for (const item of origin) { + const isContent = _isContent(item); + if (isContent != isContentArray) { + throw new Error('Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them'); + } + if (isContent) { + // `isContent` contains the result of _isContent, which is a utility + // function that checks if the item is a Content. + result.push(item); + } + else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them'); + } + else { + accumulatedParts.push(item); + } + } + if (!isContentArray) { + result.push({ role: 'user', parts: tParts(accumulatedParts) }); + } + return result; +} +/* +Transform the type field from an array of types to an array of anyOf fields. +Example: + {type: ['STRING', 'NUMBER']} +will be transformed to + {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]} +*/ +function flattenTypeArrayToAnyOf(typeList, resultingSchema) { + if (typeList.includes('null')) { + resultingSchema['nullable'] = true; + } + const listWithoutNull = typeList.filter((type) => type !== 'null'); + if (listWithoutNull.length === 1) { + resultingSchema['type'] = Object.values(Type).includes(listWithoutNull[0].toUpperCase()) + ? listWithoutNull[0].toUpperCase() + : Type.TYPE_UNSPECIFIED; + } + else { + resultingSchema['anyOf'] = []; + for (const i of listWithoutNull) { + resultingSchema['anyOf'].push({ + 'type': Object.values(Type).includes(i.toUpperCase()) + ? i.toUpperCase() + : Type.TYPE_UNSPECIFIED, + }); + } + } +} +function processJsonSchema(_jsonSchema) { + const genAISchema = {}; + const schemaFieldNames = ['items']; + const listSchemaFieldNames = ['anyOf']; + const dictSchemaFieldNames = ['properties']; + if (_jsonSchema['type'] && _jsonSchema['anyOf']) { + throw new Error('type and anyOf cannot be both populated.'); + } + /* + This is to handle the nullable array or object. The _jsonSchema will + be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The + logic is to check if anyOf has 2 elements and one of the element is null, + if so, the anyOf field is unnecessary, so we need to get rid of the anyOf + field and make the schema nullable. Then use the other element as the new + _jsonSchema for processing. This is because the backend doesn't have a null + type. + This has to be checked before we process any other fields. + For example: + const objectNullable = z.object({ + nullableArray: z.array(z.string()).nullable(), + }); + Will have the raw _jsonSchema as: + { + type: 'OBJECT', + properties: { + nullableArray: { + anyOf: [ + {type: 'null'}, + { + type: 'array', + items: {type: 'string'}, + }, + ], + } + }, + required: [ 'nullableArray' ], + } + Will result in following schema compatible with Gemini API: + { + type: 'OBJECT', + properties: { + nullableArray: { + nullable: true, + type: 'ARRAY', + items: {type: 'string'}, + } + }, + required: [ 'nullableArray' ], + } + */ + const incomingAnyOf = _jsonSchema['anyOf']; + if (incomingAnyOf != null && incomingAnyOf.length == 2) { + if (incomingAnyOf[0]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[1]; + } + else if (incomingAnyOf[1]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[0]; + } + } + if (_jsonSchema['type'] instanceof Array) { + flattenTypeArrayToAnyOf(_jsonSchema['type'], genAISchema); + } + for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) { + // Skip if the fieldvalue is undefined or null. + if (fieldValue == null) { + continue; + } + if (fieldName == 'type') { + if (fieldValue === 'null') { + throw new Error('type: null can not be the only possible type for the field.'); + } + if (fieldValue instanceof Array) { + // we have already handled the type field with array of types in the + // beginning of this function. + continue; + } + genAISchema['type'] = Object.values(Type).includes(fieldValue.toUpperCase()) + ? fieldValue.toUpperCase() + : Type.TYPE_UNSPECIFIED; + } + else if (schemaFieldNames.includes(fieldName)) { + genAISchema[fieldName] = + processJsonSchema(fieldValue); + } + else if (listSchemaFieldNames.includes(fieldName)) { + const listSchemaFieldValue = []; + for (const item of fieldValue) { + if (item['type'] == 'null') { + genAISchema['nullable'] = true; + continue; + } + listSchemaFieldValue.push(processJsonSchema(item)); + } + genAISchema[fieldName] = + listSchemaFieldValue; + } + else if (dictSchemaFieldNames.includes(fieldName)) { + const dictSchemaFieldValue = {}; + for (const [key, value] of Object.entries(fieldValue)) { + dictSchemaFieldValue[key] = processJsonSchema(value); + } + genAISchema[fieldName] = + dictSchemaFieldValue; + } + else { + // additionalProperties is not included in JSONSchema, skipping it. + if (fieldName === 'additionalProperties') { + continue; + } + genAISchema[fieldName] = fieldValue; + } + } + return genAISchema; +} +// we take the unknown in the schema field because we want enable user to pass +// the output of major schema declaration tools without casting. Tools such as +// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type +// or object, see details in +// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7 +// typebox can return unknown, see details in +// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35 +// Note: proper json schemas with the $schema field set never arrive to this +// transformer. Schemas with $schema are routed to the equivalent API json +// schema field. +function tSchema(schema) { + return processJsonSchema(schema); +} +function tSpeechConfig(speechConfig) { + if (typeof speechConfig === 'object') { + return speechConfig; + } + else if (typeof speechConfig === 'string') { + return { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: speechConfig, + }, + }, + }; + } + else { + throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`); + } +} +function tLiveSpeechConfig(speechConfig) { + if ('multiSpeakerVoiceConfig' in speechConfig) { + throw new Error('multiSpeakerVoiceConfig is not supported in the live API.'); + } + return speechConfig; +} +function tTool(tool) { + if (tool.functionDeclarations) { + for (const functionDeclaration of tool.functionDeclarations) { + if (functionDeclaration.parameters) { + if (!Object.keys(functionDeclaration.parameters).includes('$schema')) { + functionDeclaration.parameters = processJsonSchema(functionDeclaration.parameters); + } + else { + if (!functionDeclaration.parametersJsonSchema) { + functionDeclaration.parametersJsonSchema = + functionDeclaration.parameters; + delete functionDeclaration.parameters; + } + } + } + if (functionDeclaration.response) { + if (!Object.keys(functionDeclaration.response).includes('$schema')) { + functionDeclaration.response = processJsonSchema(functionDeclaration.response); + } + else { + if (!functionDeclaration.responseJsonSchema) { + functionDeclaration.responseJsonSchema = + functionDeclaration.response; + delete functionDeclaration.response; + } + } + } + } + } + return tool; +} +function tTools(tools) { + // Check if the incoming type is defined. + if (tools === undefined || tools === null) { + throw new Error('tools is required'); + } + if (!Array.isArray(tools)) { + throw new Error('tools is required and must be an array of Tools'); + } + const result = []; + for (const tool of tools) { + result.push(tool); + } + return result; +} +/** + * Prepends resource name with project, location, resource_prefix if needed. + * + * @param client The API client. + * @param resourceName The resource name. + * @param resourcePrefix The resource prefix. + * @param splitsAfterPrefix The number of splits after the prefix. + * @returns The completed resource name. + * + * Examples: + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/bar/locations/us-west1/cachedContents/123' + * ``` + * + * ``` + * resource_name = 'projects/foo/locations/us-central1/cachedContents/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/foo/locations/us-central1/cachedContents/123' + * ``` + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns 'cachedContents/123' + * ``` + * + * ``` + * resource_name = 'some/wrong/cachedContents/resource/name/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * # client.vertexai = True + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * -> 'some/wrong/resource/name/123' + * ``` + */ +function resourceName(client, resourceName, resourcePrefix, splitsAfterPrefix = 1) { + const shouldAppendPrefix = !resourceName.startsWith(`${resourcePrefix}/`) && + resourceName.split('/').length === splitsAfterPrefix; + if (client.isVertexAI()) { + if (resourceName.startsWith('projects/')) { + return resourceName; + } + else if (resourceName.startsWith('locations/')) { + return `projects/${client.getProject()}/${resourceName}`; + } + else if (resourceName.startsWith(`${resourcePrefix}/`)) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`; + } + else if (shouldAppendPrefix) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`; + } + else { + return resourceName; + } + } + if (shouldAppendPrefix) { + return `${resourcePrefix}/${resourceName}`; + } + return resourceName; +} +function tCachedContentName(apiClient, name) { + if (typeof name !== 'string') { + throw new Error('name must be a string'); + } + return resourceName(apiClient, name, 'cachedContents'); +} +function tTuningJobStatus(status) { + switch (status) { + case 'STATE_UNSPECIFIED': + return 'JOB_STATE_UNSPECIFIED'; + case 'CREATING': + return 'JOB_STATE_RUNNING'; + case 'ACTIVE': + return 'JOB_STATE_SUCCEEDED'; + case 'FAILED': + return 'JOB_STATE_FAILED'; + default: + return status; + } +} +function tBytes(fromImageBytes) { + return tBytes$1(fromImageBytes); +} +function _isFile(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'name' in origin); +} +function isGeneratedVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'video' in origin); +} +function isVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'uri' in origin); +} +function tFileName(fromName) { + var _a; + let name; + if (_isFile(fromName)) { + name = fromName.name; + } + if (isVideo(fromName)) { + name = fromName.uri; + if (name === undefined) { + return undefined; + } + } + if (isGeneratedVideo(fromName)) { + name = (_a = fromName.video) === null || _a === void 0 ? void 0 : _a.uri; + if (name === undefined) { + return undefined; + } + } + if (typeof fromName === 'string') { + name = fromName; + } + if (name === undefined) { + throw new Error('Could not extract file name from the provided input.'); + } + if (name.startsWith('https://')) { + const suffix = name.split('files/')[1]; + const match = suffix.match(/[a-z0-9]+/); + if (match === null) { + throw new Error(`Could not extract file name from URI ${name}`); + } + name = match[0]; + } + else if (name.startsWith('files/')) { + name = name.split('files/')[1]; + } + return name; +} +function tModelsUrl(apiClient, baseModels) { + let res; + if (apiClient.isVertexAI()) { + res = baseModels ? 'publishers/google/models' : 'models'; + } + else { + res = baseModels ? 'models' : 'tunedModels'; + } + return res; +} +function tExtractModels(response) { + for (const key of ['models', 'tunedModels', 'publisherModels']) { + if (hasField(response, key)) { + return response[key]; + } + } + return []; +} +function hasField(data, fieldName) { + return data !== null && typeof data === 'object' && fieldName in data; +} +function mcpToGeminiTool(mcpTool, config = {}) { + const mcpToolSchema = mcpTool; + const functionDeclaration = { + name: mcpToolSchema['name'], + description: mcpToolSchema['description'], + parametersJsonSchema: mcpToolSchema['inputSchema'], + }; + if (config.behavior) { + functionDeclaration['behavior'] = config.behavior; + } + const geminiTool = { + functionDeclarations: [ + functionDeclaration, + ], + }; + return geminiTool; +} +/** + * Converts a list of MCP tools to a single Gemini tool with a list of function + * declarations. + */ +function mcpToolsToGeminiTool(mcpTools, config = {}) { + const functionDeclarations = []; + const toolNames = new Set(); + for (const mcpTool of mcpTools) { + const mcpToolName = mcpTool.name; + if (toolNames.has(mcpToolName)) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + toolNames.add(mcpToolName); + const geminiTool = mcpToGeminiTool(mcpTool, config); + if (geminiTool.functionDeclarations) { + functionDeclarations.push(...geminiTool.functionDeclarations); + } + } + return { functionDeclarations: functionDeclarations }; +} +// Transforms a source input into a BatchJobSource object with validation. +function tBatchJobSource(apiClient, src) { + if (typeof src !== 'string' && !Array.isArray(src)) { + if (apiClient && apiClient.isVertexAI()) { + if (src.gcsUri && src.bigqueryUri) { + throw new Error('Only one of `gcsUri` or `bigqueryUri` can be set.'); + } + else if (!src.gcsUri && !src.bigqueryUri) { + throw new Error('One of `gcsUri` or `bigqueryUri` must be set.'); + } + } + else { + // Logic for non-Vertex AI client (inlined_requests, file_name) + if (src.inlinedRequests && src.fileName) { + throw new Error('Only one of `inlinedRequests` or `fileName` can be set.'); + } + else if (!src.inlinedRequests && !src.fileName) { + throw new Error('One of `inlinedRequests` or `fileName` must be set.'); + } + } + return src; + } + // If src is an array (list in Python) + else if (Array.isArray(src)) { + return { inlinedRequests: src }; + } + else if (typeof src === 'string') { + if (src.startsWith('gs://')) { + return { + format: 'jsonl', + gcsUri: [src], // GCS URI is expected as an array + }; + } + else if (src.startsWith('bq://')) { + return { + format: 'bigquery', + bigqueryUri: src, + }; + } + else if (src.startsWith('files/')) { + return { + fileName: src, + }; + } + } + throw new Error(`Unsupported source: ${src}`); +} +function tBatchJobDestination(dest) { + if (typeof dest !== 'string') { + return dest; + } + const destString = dest; + if (destString.startsWith('gs://')) { + return { + format: 'jsonl', + gcsUri: destString, + }; + } + else if (destString.startsWith('bq://')) { + return { + format: 'bigquery', + bigqueryUri: destString, + }; + } + else { + throw new Error(`Unsupported destination: ${destString}`); + } +} +function tBatchJobName(apiClient, name) { + const nameString = name; + if (!apiClient.isVertexAI()) { + const mldevPattern = /batches\/[^/]+$/; + if (mldevPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } + } + const vertexPattern = /^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/; + if (vertexPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else if (/^\d+$/.test(nameString)) { + return nameString; + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } +} +function tJobState(state) { + const stateString = state; + if (stateString === 'BATCH_STATE_UNSPECIFIED') { + return 'JOB_STATE_UNSPECIFIED'; + } + else if (stateString === 'BATCH_STATE_PENDING') { + return 'JOB_STATE_PENDING'; + } + else if (stateString === 'BATCH_STATE_SUCCEEDED') { + return 'JOB_STATE_SUCCEEDED'; + } + else if (stateString === 'BATCH_STATE_FAILED') { + return 'JOB_STATE_FAILED'; + } + else if (stateString === 'BATCH_STATE_CANCELLED') { + return 'JOB_STATE_CANCELLED'; + } + else { + return stateString; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$4(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$4(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$4(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$4(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$4(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$4(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$4(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev$1(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$4(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$4(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$4(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$4(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$4(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$4(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$4(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$4() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$4(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$4(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$4(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$4(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$4(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$4()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$4(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev$2(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev$2(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$2(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev$2(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$3(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$3(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$3(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$3(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$3(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev$1(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$4(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToMldev$1(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev$1(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$4(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$2(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToMldev$3(tSpeechConfig(fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev$1(fromThinkingConfig)); + } + return toObject; +} +function inlinedRequestToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['request', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$4(item); + }); + } + setValueByPath(toObject, ['request', 'contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['request', 'generationConfig'], generateContentConfigToMldev$1(apiClient, fromConfig, toObject)); + } + return toObject; +} +function batchJobSourceToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['format']) !== undefined) { + throw new Error('format parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['bigqueryUri']) !== undefined) { + throw new Error('bigqueryUri parameter is not supported in Gemini API.'); + } + const fromFileName = getValueByPath(fromObject, ['fileName']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedRequests = getValueByPath(fromObject, [ + 'inlinedRequests', + ]); + if (fromInlinedRequests != null) { + let transformedList = fromInlinedRequests; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedRequestToMldev(apiClient, item); + }); + } + setValueByPath(toObject, ['requests', 'requests'], transformedList); + } + return toObject; +} +function createBatchJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['batch', 'displayName'], fromDisplayName); + } + if (getValueByPath(fromObject, ['dest']) !== undefined) { + throw new Error('dest parameter is not supported in Gemini API.'); + } + return toObject; +} +function createBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['batch', 'inputConfig'], batchJobSourceToMldev(apiClient, tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createBatchJobConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + if (getValueByPath(fromObject, ['filter']) !== undefined) { + throw new Error('filter parameter is not supported in Gemini API.'); + } + return toObject; +} +function listBatchJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listBatchJobsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function deleteBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function batchJobSourceToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['instancesFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsSource', 'uris'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigquerySource', 'inputUri'], fromBigqueryUri); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['inlinedRequests']) !== undefined) { + throw new Error('inlinedRequests parameter is not supported in Vertex AI.'); + } + return toObject; +} +function batchJobDestinationToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['predictionsFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsDestination', 'outputUriPrefix'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryDestination', 'outputUri'], fromBigqueryUri); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['inlinedResponses']) !== undefined) { + throw new Error('inlinedResponses parameter is not supported in Vertex AI.'); + } + return toObject; +} +function createBatchJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDest = getValueByPath(fromObject, ['dest']); + if (parentObject !== undefined && fromDest != null) { + setValueByPath(parentObject, ['outputConfig'], batchJobDestinationToVertex(tBatchJobDestination(fromDest))); + } + return toObject; +} +function createBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['inputConfig'], batchJobSourceToVertex(tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createBatchJobConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listBatchJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listBatchJobsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function deleteBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev$2(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$2(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$2(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromMldev$1(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev$2(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev$1(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev$2(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev$1(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev$1(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function jobErrorFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + return toObject; +} +function inlinedResponseFromMldev(fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateContentResponseFromMldev$1(fromResponse)); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError)); + } + return toObject; +} +function batchJobDestinationFromMldev(fromObject) { + const toObject = {}; + const fromFileName = getValueByPath(fromObject, ['responsesFile']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedResponses = getValueByPath(fromObject, [ + 'inlinedResponses', + 'inlinedResponses', + ]); + if (fromInlinedResponses != null) { + let transformedList = fromInlinedResponses; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedResponseFromMldev(item); + }); + } + setValueByPath(toObject, ['inlinedResponses'], transformedList); + } + return toObject; +} +function batchJobFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, [ + 'metadata', + 'displayName', + ]); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['metadata', 'state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, [ + 'metadata', + 'createTime', + ]); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'metadata', + 'endTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, [ + 'metadata', + 'updateTime', + ]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['metadata', 'model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromDest = getValueByPath(fromObject, ['metadata', 'output']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromMldev(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, ['operations']); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromMldev(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function deleteResourceJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError)); + } + return toObject; +} +function jobErrorFromVertex(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + return toObject; +} +function batchJobSourceFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['instancesFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsSource', 'uris']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigquerySource', + 'inputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + return toObject; +} +function batchJobDestinationFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['predictionsFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, [ + 'gcsDestination', + 'outputUriPrefix', + ]); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigqueryDestination', + 'outputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + return toObject; +} +function batchJobFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromSrc = getValueByPath(fromObject, ['inputConfig']); + if (fromSrc != null) { + setValueByPath(toObject, ['src'], batchJobSourceFromVertex(fromSrc)); + } + const fromDest = getValueByPath(fromObject, ['outputConfig']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromVertex(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, [ + 'batchPredictionJobs', + ]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromVertex(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function deleteResourceJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +var PagedItem; +(function (PagedItem) { + PagedItem["PAGED_ITEM_BATCH_JOBS"] = "batchJobs"; + PagedItem["PAGED_ITEM_MODELS"] = "models"; + PagedItem["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs"; + PagedItem["PAGED_ITEM_FILES"] = "files"; + PagedItem["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents"; +})(PagedItem || (PagedItem = {})); +/** + * Pager class for iterating through paginated results. + */ +class Pager { + constructor(name, request, response, params) { + this.pageInternal = []; + this.paramsInternal = {}; + this.requestInternal = request; + this.init(name, response, params); + } + init(name, response, params) { + var _a, _b; + this.nameInternal = name; + this.pageInternal = response[this.nameInternal] || []; + this.sdkHttpResponseInternal = response === null || response === void 0 ? void 0 : response.sdkHttpResponse; + this.idxInternal = 0; + let requestParams = { config: {} }; + if (!params || Object.keys(params).length === 0) { + requestParams = { config: {} }; + } + else if (typeof params === 'object') { + requestParams = Object.assign({}, params); + } + else { + requestParams = params; + } + if (requestParams['config']) { + requestParams['config']['pageToken'] = response['nextPageToken']; + } + this.paramsInternal = requestParams; + this.pageInternalSize = + (_b = (_a = requestParams['config']) === null || _a === void 0 ? void 0 : _a['pageSize']) !== null && _b !== void 0 ? _b : this.pageInternal.length; + } + initNextPage(response) { + this.init(this.nameInternal, response, this.paramsInternal); + } + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page() { + return this.pageInternal; + } + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name() { + return this.nameInternal; + } + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize() { + return this.pageInternalSize; + } + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse() { + return this.sdkHttpResponseInternal; + } + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params() { + return this.paramsInternal; + } + /** + * Returns the total number of items in the current page. + */ + get pageLength() { + return this.pageInternal.length; + } + /** + * Returns the item at the given index. + */ + getItem(index) { + return this.pageInternal[index]; + } + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator]() { + return { + next: async () => { + if (this.idxInternal >= this.pageLength) { + if (this.hasNextPage()) { + await this.nextPage(); + } + else { + return { value: undefined, done: true }; + } + } + const item = this.getItem(this.idxInternal); + this.idxInternal += 1; + return { value: item, done: false }; + }, + return: async () => { + return { value: undefined, done: true }; + }, + }; + } + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + async nextPage() { + if (!this.hasNextPage()) { + throw new Error('No more pages to fetch.'); + } + const response = await this.requestInternal(this.params); + this.initNextPage(response); + return this.page; + } + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage() { + var _a; + if (((_a = this.params['config']) === null || _a === void 0 ? void 0 : _a['pageToken']) !== undefined) { + return true; + } + return false; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Batches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + this.create = async (params) => { + var _a, _b; + if (this.apiClient.isVertexAI()) { + const timestamp = Date.now(); + const timestampStr = timestamp.toString(); + if (Array.isArray(params.src)) { + throw new Error('InlinedRequest[] is not supported in Vertex AI. Please use ' + + 'Google Cloud Storage URI or BigQuery URI instead.'); + } + params.config = params.config || {}; + if (params.config.displayName === undefined) { + params.config.displayName = 'genaiBatchJob_${timestampStr}'; + } + if (params.config.dest === undefined && typeof params.src === 'string') { + if (params.src.startsWith('gs://') && params.src.endsWith('.jsonl')) { + params.config.dest = `${params.src.slice(0, -6)}/dest`; + } + else if (params.src.startsWith('bq://')) { + params.config.dest = + `${params.src}_dest_${timestampStr}`; + } + else { + throw new Error('Unsupported source:' + params.src); + } + } + } + else { + if (Array.isArray(params.src) || + (typeof params.src !== 'string' && params.src.inlinedRequests)) { + // Move system instruction to httpOptions extraBody. + let path = ''; + let queryParams = {}; + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchGenerateContent', body['_url']); + queryParams = body['_query']; + // Move system instruction to 'request': + // {'systemInstruction': system_instruction} + const batch = body['batch']; + const inputConfig = batch['inputConfig']; + const requestsWrapper = inputConfig['requests']; + const requests = requestsWrapper['requests']; + const newRequests = []; + for (const request of requests) { + const requestDict = request; + if (requestDict['systemInstruction']) { + const systemInstructionValue = requestDict['systemInstruction']; + delete requestDict['systemInstruction']; + const requestContent = requestDict['request']; + requestContent['systemInstruction'] = systemInstructionValue; + requestDict['request'] = requestContent; + } + newRequests.push(requestDict); + } + requestsWrapper['requests'] = newRequests; + delete body['config']; + delete body['_url']; + delete body['_query']; + const response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + return await this.createInternal(params); + }; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_BATCH_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + async createInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchGenerateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + else { + const body = cancelBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listBatchJobsParametersToVertex(params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromVertex(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listBatchJobsParametersToMldev(params); + path = formatMap('batches', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromMldev(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = deleteBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$3(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$3(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$3(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$3(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$3(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$3(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$3(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$3(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$3(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$3(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$3(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$3(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$3(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$3(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$3() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$3(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$3(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$3(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$3(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$3(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$3()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$3(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$1(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev$1(fromRetrievalConfig)); + } + return toObject; +} +function createCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$3(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$3(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$3(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$1(fromToolConfig)); + } + if (getValueByPath(fromObject, ['kmsKeyName']) !== undefined) { + throw new Error('kmsKeyName parameter is not supported in Gemini API.'); + } + return toObject; +} +function createCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createCachedContentConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataToVertex$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex$2(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$2(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex$2(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex$2(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$2(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex$2(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex$2(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$2(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$2(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$2(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex$2(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex$2(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex$2()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex$2(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToVertex$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToVertex$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex$1(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToVertex$1(fromRetrievalConfig)); + } + return toObject; +} +function createCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex$2(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$2(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex$1(fromToolConfig)); + } + const fromKmsKeyName = getValueByPath(fromObject, ['kmsKeyName']); + if (parentObject !== undefined && fromKmsKeyName != null) { + setValueByPath(parentObject, ['encryption_spec', 'kmsKeyName'], fromKmsKeyName); + } + return toObject; +} +function createCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createCachedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function cachedContentFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromMldev() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromMldev(item); + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} +function cachedContentFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromVertex() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromVertex(item); + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Caches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_CACHED_CONTENTS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + async create(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = createCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromVertex(); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromMldev(); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = updateCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listCachedContentsParametersToVertex(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromVertex(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listCachedContentsParametersToMldev(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromMldev(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns true if the response is valid, false otherwise. + */ +function isValidResponse(response) { + var _a; + if (response.candidates == undefined || response.candidates.length === 0) { + return false; + } + const content = (_a = response.candidates[0]) === null || _a === void 0 ? void 0 : _a.content; + if (content === undefined) { + return false; + } + return isValidContent(content); +} +function isValidContent(content) { + if (content.parts === undefined || content.parts.length === 0) { + return false; + } + for (const part of content.parts) { + if (part === undefined || Object.keys(part).length === 0) { + return false; + } + } + return true; +} +/** + * Validates the history contains the correct roles. + * + * @throws Error if the history does not start with a user turn. + * @throws Error if the history contains an invalid role. + */ +function validateHistory(history) { + // Empty history is valid. + if (history.length === 0) { + return; + } + for (const content of history) { + if (content.role !== 'user' && content.role !== 'model') { + throw new Error(`Role must be user or model, but got ${content.role}.`); + } + } +} +/** + * Extracts the curated (valid) history from a comprehensive history. + * + * @remarks + * The model may sometimes generate invalid or empty contents(e.g., due to safty + * filters or recitation). Extracting valid turns from the history + * ensures that subsequent requests could be accpeted by the model. + */ +function extractCuratedHistory(comprehensiveHistory) { + if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) { + return []; + } + const curatedHistory = []; + const length = comprehensiveHistory.length; + let i = 0; + while (i < length) { + if (comprehensiveHistory[i].role === 'user') { + curatedHistory.push(comprehensiveHistory[i]); + i++; + } + else { + const modelOutput = []; + let isValid = true; + while (i < length && comprehensiveHistory[i].role === 'model') { + modelOutput.push(comprehensiveHistory[i]); + if (isValid && !isValidContent(comprehensiveHistory[i])) { + isValid = false; + } + i++; + } + if (isValid) { + curatedHistory.push(...modelOutput); + } + else { + // Remove the last user input when model content is invalid. + curatedHistory.pop(); + } + } + } + return curatedHistory; +} +/** + * A utility class to create a chat session. + */ +class Chats { + constructor(modelsModule, apiClient) { + this.modelsModule = modelsModule; + this.apiClient = apiClient; + } + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params) { + return new Chat(this.apiClient, this.modelsModule, params.model, params.config, + // Deep copy the history to avoid mutating the history outside of the + // chat session. + structuredClone(params.history)); + } +} +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +class Chat { + constructor(apiClient, modelsModule, model, config = {}, history = []) { + this.apiClient = apiClient; + this.modelsModule = modelsModule; + this.model = model; + this.config = config; + this.history = history; + // A promise to represent the current state of the message being sent to the + // model. + this.sendPromise = Promise.resolve(); + validateHistory(history); + } + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + async sendMessage(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const responsePromise = this.modelsModule.generateContent({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + this.sendPromise = (async () => { + var _a, _b, _c; + const response = await responsePromise; + const outputContent = (_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content; + // Because the AFC input contains the entire curated chat history in + // addition to the new user input, we need to truncate the AFC history + // to deduplicate the existing chat history. + const fullAutomaticFunctionCallingHistory = response.automaticFunctionCallingHistory; + const index = this.getHistory(true).length; + let automaticFunctionCallingHistory = []; + if (fullAutomaticFunctionCallingHistory != null) { + automaticFunctionCallingHistory = + (_c = fullAutomaticFunctionCallingHistory.slice(index)) !== null && _c !== void 0 ? _c : []; + } + const modelOutput = outputContent ? [outputContent] : []; + this.recordHistory(inputContent, modelOutput, automaticFunctionCallingHistory); + return; + })(); + await this.sendPromise.catch(() => { + // Resets sendPromise to avoid subsequent calls failing + this.sendPromise = Promise.resolve(); + }); + return responsePromise; + } + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + async sendMessageStream(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const streamResponse = this.modelsModule.generateContentStream({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + // Resolve the internal tracking of send completion promise - `sendPromise` + // for both success and failure response. The actual failure is still + // propagated by the `await streamResponse`. + this.sendPromise = streamResponse + .then(() => undefined) + .catch(() => undefined); + const response = await streamResponse; + const result = this.processStreamResponse(response, inputContent); + return result; + } + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated = false) { + const history = curated + ? extractCuratedHistory(this.history) + : this.history; + // Deep copy the history to avoid mutating the history outside of the + // chat session. + return structuredClone(history); + } + processStreamResponse(streamResponse, inputContent) { + var _a, _b; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + var _c, e_1, _d, _e; + const outputContent = []; + try { + for (var _f = true, streamResponse_1 = __asyncValues(streamResponse), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()), _c = streamResponse_1_1.done, !_c; _f = true) { + _e = streamResponse_1_1.value; + _f = false; + const chunk = _e; + if (isValidResponse(chunk)) { + const content = (_b = (_a = chunk.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content; + if (content !== undefined) { + outputContent.push(content); + } + } + yield yield __await(chunk); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_c && (_d = streamResponse_1.return)) yield __await(_d.call(streamResponse_1)); + } + finally { if (e_1) throw e_1.error; } + } + this.recordHistory(inputContent, outputContent); + }); + } + recordHistory(userInput, modelOutput, automaticFunctionCallingHistory) { + let outputContents = []; + if (modelOutput.length > 0 && + modelOutput.every((content) => content.role !== undefined)) { + outputContents = modelOutput; + } + else { + // Appends an empty content when model returns empty response, so that the + // history is always alternating between user and model. + outputContents.push({ + role: 'model', + parts: [], + }); + } + if (automaticFunctionCallingHistory && + automaticFunctionCallingHistory.length > 0) { + this.history.push(...extractCuratedHistory(automaticFunctionCallingHistory)); + } + else { + this.history.push(userInput); + } + this.history.push(...outputContents); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * API errors raised by the GenAI API. + */ +class ApiError extends Error { + constructor(options) { + super(options.message); + this.name = 'ApiError'; + this.status = options.status; + Object.setPrototypeOf(this, ApiError.prototype); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const CONTENT_TYPE_HEADER = 'Content-Type'; +const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout'; +const USER_AGENT_HEADER = 'User-Agent'; +const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client'; +const SDK_VERSION = '1.15.0'; // x-release-please-version +const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`; +const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1'; +const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta'; +const responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/; +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +class ApiClient { + constructor(opts) { + var _a, _b; + this.clientOptions = Object.assign(Object.assign({}, opts), { project: opts.project, location: opts.location, apiKey: opts.apiKey, vertexai: opts.vertexai }); + const initHttpOptions = {}; + if (this.clientOptions.vertexai) { + initHttpOptions.apiVersion = + (_a = this.clientOptions.apiVersion) !== null && _a !== void 0 ? _a : VERTEX_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = this.baseUrlFromProjectLocation(); + this.normalizeAuthParameters(); + } + else { + // Gemini API + initHttpOptions.apiVersion = + (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 ? _b : GOOGLE_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`; + } + initHttpOptions.headers = this.getDefaultHeaders(); + this.clientOptions.httpOptions = initHttpOptions; + if (opts.httpOptions) { + this.clientOptions.httpOptions = this.patchHttpOptions(initHttpOptions, opts.httpOptions); + } + } + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + baseUrlFromProjectLocation() { + if (this.clientOptions.project && + this.clientOptions.location && + this.clientOptions.location !== 'global') { + // Regional endpoint + return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`; + } + // Global endpoint (covers 'global' location and API key usage) + return `https://aiplatform.googleapis.com/`; + } + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + normalizeAuthParameters() { + if (this.clientOptions.project && this.clientOptions.location) { + // Using project/location for auth, clear potential API key + this.clientOptions.apiKey = undefined; + return; + } + // Using API key for auth (or no auth provided yet), clear project/location + this.clientOptions.project = undefined; + this.clientOptions.location = undefined; + } + isVertexAI() { + var _a; + return (_a = this.clientOptions.vertexai) !== null && _a !== void 0 ? _a : false; + } + getProject() { + return this.clientOptions.project; + } + getLocation() { + return this.clientOptions.location; + } + getApiVersion() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.apiVersion !== undefined) { + return this.clientOptions.httpOptions.apiVersion; + } + throw new Error('API version is not set.'); + } + getBaseUrl() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.baseUrl !== undefined) { + return this.clientOptions.httpOptions.baseUrl; + } + throw new Error('Base URL is not set.'); + } + getRequestUrl() { + return this.getRequestUrlInternal(this.clientOptions.httpOptions); + } + getHeaders() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.headers !== undefined) { + return this.clientOptions.httpOptions.headers; + } + else { + throw new Error('Headers are not set.'); + } + } + getRequestUrlInternal(httpOptions) { + if (!httpOptions || + httpOptions.baseUrl === undefined || + httpOptions.apiVersion === undefined) { + throw new Error('HTTP options are not correctly set.'); + } + const baseUrl = httpOptions.baseUrl.endsWith('/') + ? httpOptions.baseUrl.slice(0, -1) + : httpOptions.baseUrl; + const urlElement = [baseUrl]; + if (httpOptions.apiVersion && httpOptions.apiVersion !== '') { + urlElement.push(httpOptions.apiVersion); + } + return urlElement.join('/'); + } + getBaseResourcePath() { + return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`; + } + getApiKey() { + return this.clientOptions.apiKey; + } + getWebsocketBaseUrl() { + const baseUrl = this.getBaseUrl(); + const urlParts = new URL(baseUrl); + urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss'; + return urlParts.toString(); + } + setBaseUrl(url) { + if (this.clientOptions.httpOptions) { + this.clientOptions.httpOptions.baseUrl = url; + } + else { + throw new Error('HTTP options are not correctly set.'); + } + } + constructUrl(path, httpOptions, prependProjectLocation) { + const urlElement = [this.getRequestUrlInternal(httpOptions)]; + if (prependProjectLocation) { + urlElement.push(this.getBaseResourcePath()); + } + if (path !== '') { + urlElement.push(path); + } + const url = new URL(`${urlElement.join('/')}`); + return url; + } + shouldPrependVertexProjectPath(request) { + if (this.clientOptions.apiKey) { + return false; + } + if (!this.clientOptions.vertexai) { + return false; + } + if (request.path.startsWith('projects/')) { + // Assume the path already starts with + // `projects//location/`. + return false; + } + if (request.httpMethod === 'GET' && + request.path.startsWith('publishers/google/models')) { + // These paths are used by Vertex's models.get and models.list + // calls. For base models Vertex does not accept a project/location + // prefix (for tuned model the prefix is required). + return false; + } + return true; + } + async request(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (request.queryParams) { + for (const [key, value] of Object.entries(request.queryParams)) { + url.searchParams.append(key, String(value)); + } + } + let requestInit = {}; + if (request.httpMethod === 'GET') { + if (request.body && request.body !== '{}') { + throw new Error('Request body should be empty for GET request, but got non empty request body'); + } + } + else { + requestInit.body = request.body; + } + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal); + return this.unaryApiCall(url, requestInit, request.httpMethod); + } + patchHttpOptions(baseHttpOptions, requestHttpOptions) { + const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions)); + for (const [key, value] of Object.entries(requestHttpOptions)) { + // Records compile to objects. + if (typeof value === 'object') { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = Object.assign(Object.assign({}, patchedHttpOptions[key]), value); + } + else if (value !== undefined) { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = value; + } + } + return patchedHttpOptions; + } + async requestStream(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') { + url.searchParams.set('alt', 'sse'); + } + let requestInit = {}; + requestInit.body = request.body; + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal); + return this.streamApiCall(url, requestInit, request.httpMethod); + } + async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions, abortSignal) { + if ((httpOptions && httpOptions.timeout) || abortSignal) { + const abortController = new AbortController(); + const signal = abortController.signal; + if (httpOptions.timeout && (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) > 0) { + const timeoutHandle = setTimeout(() => abortController.abort(), httpOptions.timeout); + if (timeoutHandle && + typeof timeoutHandle.unref === + 'function') { + // call unref to prevent nodejs process from hanging, see + // https://nodejs.org/api/timers.html#timeoutunref + timeoutHandle.unref(); + } + } + if (abortSignal) { + abortSignal.addEventListener('abort', () => { + abortController.abort(); + }); + } + requestInit.signal = signal; + } + if (httpOptions && httpOptions.extraBody !== null) { + includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody); + } + requestInit.headers = await this.getHeadersInternal(httpOptions); + return requestInit; + } + async unaryApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return new HttpResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + async streamApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return this.processStreamResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + processStreamResponse(response) { + var _a; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + const reader = (_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.getReader(); + const decoder = new TextDecoder('utf-8'); + if (!reader) { + throw new Error('Response body is empty'); + } + try { + let buffer = ''; + while (true) { + const { done, value } = yield __await(reader.read()); + if (done) { + if (buffer.trim().length > 0) { + throw new Error('Incomplete JSON segment at the end'); + } + break; + } + const chunkString = decoder.decode(value, { stream: true }); + // Parse and throw an error if the chunk contains an error. + try { + const chunkJson = JSON.parse(chunkString); + if ('error' in chunkJson) { + const errorJson = JSON.parse(JSON.stringify(chunkJson['error'])); + const status = errorJson['status']; + const code = errorJson['code']; + const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`; + if (code >= 400 && code < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: code, + }); + throw apiError; + } + } + } + catch (e) { + const error = e; + if (error.name === 'ApiError') { + throw e; + } + } + buffer += chunkString; + let match = buffer.match(responseLineRE); + while (match) { + const processedChunkString = match[1]; + try { + const partialResponse = new Response(processedChunkString, { + headers: response === null || response === void 0 ? void 0 : response.headers, + status: response === null || response === void 0 ? void 0 : response.status, + statusText: response === null || response === void 0 ? void 0 : response.statusText, + }); + yield yield __await(new HttpResponse(partialResponse)); + buffer = buffer.slice(match[0].length); + match = buffer.match(responseLineRE); + } + catch (e) { + throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`); + } + } + } + } + finally { + reader.releaseLock(); + } + }); + } + async apiCall(url, requestInit) { + return fetch(url, requestInit).catch((e) => { + throw new Error(`exception ${e} sending request`); + }); + } + getDefaultHeaders() { + const headers = {}; + const versionHeaderValue = LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra; + headers[USER_AGENT_HEADER] = versionHeaderValue; + headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue; + headers[CONTENT_TYPE_HEADER] = 'application/json'; + return headers; + } + async getHeadersInternal(httpOptions) { + const headers = new Headers(); + if (httpOptions && httpOptions.headers) { + for (const [key, value] of Object.entries(httpOptions.headers)) { + headers.append(key, value); + } + // Append a timeout header if it is set, note that the timeout option is + // in milliseconds but the header is in seconds. + if (httpOptions.timeout && httpOptions.timeout > 0) { + headers.append(SERVER_TIMEOUT_HEADER, String(Math.ceil(httpOptions.timeout / 1000))); + } + } + await this.clientOptions.auth.addAuthHeaders(headers); + return headers; + } + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + async uploadFile(file, config) { + var _a; + const fileToUpload = {}; + if (config != null) { + fileToUpload.mimeType = config.mimeType; + fileToUpload.name = config.name; + fileToUpload.displayName = config.displayName; + } + if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) { + fileToUpload.name = `files/${fileToUpload.name}`; + } + const uploader = this.clientOptions.uploader; + const fileStat = await uploader.stat(file); + fileToUpload.sizeBytes = String(fileStat.size); + const mimeType = (_a = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a !== void 0 ? _a : fileStat.type; + if (mimeType === undefined || mimeType === '') { + throw new Error('Can not determine mimeType. Please provide mimeType in the config.'); + } + fileToUpload.mimeType = mimeType; + const uploadUrl = await this.fetchUploadUrl(fileToUpload, config); + return uploader.upload(file, uploadUrl, this); + } + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + async downloadFile(params) { + const downloader = this.clientOptions.downloader; + await downloader.download(params, this); + } + async fetchUploadUrl(file, config) { + var _a; + let httpOptions = {}; + if (config === null || config === void 0 ? void 0 : config.httpOptions) { + httpOptions = config.httpOptions; + } + else { + httpOptions = { + apiVersion: '', + headers: { + 'Content-Type': 'application/json', + 'X-Goog-Upload-Protocol': 'resumable', + 'X-Goog-Upload-Command': 'start', + 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`, + 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`, + }, + }; + } + const body = { + 'file': file, + }; + const httpResponse = await this.request({ + path: formatMap('upload/v1beta/files', body['_url']), + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions, + }); + if (!httpResponse || !(httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers)) { + throw new Error('Server did not return an HttpResponse or the returned HttpResponse did not have headers.'); + } + const uploadUrl = (_a = httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers) === null || _a === void 0 ? void 0 : _a['x-goog-upload-url']; + if (uploadUrl === undefined) { + throw new Error('Failed to get upload url. Server did not return the x-google-upload-url in the headers'); + } + return uploadUrl; + } +} +async function throwErrorIfNotOK(response) { + var _a; + if (response === undefined) { + throw new Error('response is undefined'); + } + if (!response.ok) { + const status = response.status; + let errorBody; + if ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('application/json')) { + errorBody = await response.json(); + } + else { + errorBody = { + error: { + message: await response.text(), + code: response.status, + status: response.statusText, + }, + }; + } + const errorMessage = JSON.stringify(errorBody); + if (status >= 400 && status < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: status, + }); + throw apiError; + } + throw new Error(errorMessage); + } +} +/** + * Recursively updates the `requestInit.body` with values from an `extraBody` object. + * + * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed. + * The `extraBody` is then deeply merged into this parsed object. + * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged, + * as merging structured data into an opaque Blob is not supported. + * + * The function does not enforce that updated values from `extraBody` have the + * same type as existing values in `requestInit.body`. Type mismatches during + * the merge will result in a warning, but the value from `extraBody` will overwrite + * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure. + * + * @param requestInit The RequestInit object whose body will be updated. + * @param extraBody The object containing updates to be merged into `requestInit.body`. + */ +function includeExtraBodyToRequestInit(requestInit, extraBody) { + if (!extraBody || Object.keys(extraBody).length === 0) { + return; + } + if (requestInit.body instanceof Blob) { + console.warn('includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.'); + return; + } + let currentBodyObject = {}; + // If adding new type to HttpRequest.body, please check the code below to + // see if we need to update the logic. + if (typeof requestInit.body === 'string' && requestInit.body.length > 0) { + try { + const parsedBody = JSON.parse(requestInit.body); + if (typeof parsedBody === 'object' && + parsedBody !== null && + !Array.isArray(parsedBody)) { + currentBodyObject = parsedBody; + } + else { + console.warn('includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.'); + return; + } + /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ + } + catch (e) { + console.warn('includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.'); + return; + } + } + function deepMerge(target, source) { + const output = Object.assign({}, target); + for (const key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + const sourceValue = source[key]; + const targetValue = output[key]; + if (sourceValue && + typeof sourceValue === 'object' && + !Array.isArray(sourceValue) && + targetValue && + typeof targetValue === 'object' && + !Array.isArray(targetValue)) { + output[key] = deepMerge(targetValue, sourceValue); + } + else { + if (targetValue && + sourceValue && + typeof targetValue !== typeof sourceValue) { + console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`); + } + output[key] = sourceValue; + } + } + } + return output; + } + const mergedBody = deepMerge(currentBodyObject, extraBody); + requestInit.body = JSON.stringify(mergedBody); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function crossError() { + // TODO(b/399934880): this message needs a link to a help page explaining how to enable conditional exports + return new Error(`This feature requires the web or Node specific @google/genai implementation, you can fix this by either: + +*Enabling conditional exports for your project [recommended]* + +*Using a platform specific import* - Make sure your code imports either '@google/genai/web' or '@google/genai/node' instead of '@google/genai'. +`); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class CrossDownloader { + async download(_params, _apiClient) { + throw crossError(); + } +} + +const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes +const MAX_RETRY_COUNT = 3; +const INITIAL_RETRY_DELAY_MS = 1000; +const DELAY_MULTIPLIER = 2; +const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status'; +class CrossUploader { + async upload(file, uploadUrl, apiClient) { + if (typeof file === 'string') { + throw crossError(); + } + else { + return uploadBlob(file, uploadUrl, apiClient); + } + } + async stat(file) { + if (typeof file === 'string') { + throw crossError(); + } + else { + return getBlobStat(file); + } + } +} +async function uploadBlob(file, uploadUrl, apiClient) { + var _a, _b, _c; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = 'upload'; + fileSize = file.size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + const chunk = file.slice(offset, offset + chunkSize); + if (offset + chunkSize >= fileSize) { + uploadCommand += ', finalize'; + } + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: '', + body: chunk, + httpMethod: 'POST', + httpOptions: { + apiVersion: '', + baseUrl: uploadUrl, + headers: { + 'X-Goog-Upload-Command': uploadCommand, + 'X-Goog-Upload-Offset': String(offset), + 'Content-Length': String(chunkSize), + }, + }, + }); + if ((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += chunkSize; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'active') { + break; + } + // TODO(b/401391430) Investigate why the upload status is not finalized + // even though all content has been uploaded. + if (fileSize <= offset) { + throw new Error('All content has been uploaded, but the upload status is not finalized.'); + } + } + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_c = response === null || response === void 0 ? void 0 : response.headers) === null || _c === void 0 ? void 0 : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + return responseJson['file']; +} +async function getBlobStat(file) { + const fileStat = { size: file.size, type: file.type }; + return fileStat; +} +function sleep(ms) { + return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class CrossWebSocketFactory { + create(_url, _headers, _callbacks) { + throw crossError(); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function listFilesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listFilesParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listFilesConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function fileStatusToMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusToMldev(fromError)); + } + return toObject; +} +function createFileParametersToMldev(fromObject) { + const toObject = {}; + const fromFile = getValueByPath(fromObject, ['file']); + if (fromFile != null) { + setValueByPath(toObject, ['file'], fileToMldev(fromFile)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fileStatusFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusFromMldev(fromError)); + } + return toObject; +} +function listFilesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromFiles = getValueByPath(fromObject, ['files']); + if (fromFiles != null) { + let transformedList = fromFiles; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return fileFromMldev(item); + }); + } + setValueByPath(toObject, ['files'], transformedList); + } + return toObject; +} +function createFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function deleteFileResponseFromMldev() { + const toObject = {}; + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Files extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_FILES, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + async upload(params) { + if (this.apiClient.isVertexAI()) { + throw new Error('Vertex AI does not support uploading files. You can share files through a GCS bucket.'); + } + return this.apiClient + .uploadFile(params.file, params.config) + .then((response) => { + const file = fileFromMldev(response); + return file; + }); + } + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + async download(params) { + await this.apiClient.downloadFile(params); + } + async listInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = listFilesParametersToMldev(params); + path = formatMap('files', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listFilesResponseFromMldev(apiResponse); + const typedResp = new ListFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async createInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createFileParametersToMldev(params); + path = formatMap('upload/v1beta/files', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = createFileResponseFromMldev(apiResponse); + const typedResp = new CreateFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + async get(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = getFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = fileFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + async delete(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = deleteFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteFileResponseFromMldev(); + const typedResp = new DeleteFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$2(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$2(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$2(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$2(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$2(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$2(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$2(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$2(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$2(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$2(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$2(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$2(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$2()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$2(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is not supported in Gemini API.'); + } + return toObject; +} +function audioTranscriptionConfigToMldev$1() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev$1(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev$1(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToMldev$1(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev$1(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToMldev$1(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToMldev$1(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev$1(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToMldev$2(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$2(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev$1(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToMldev$1()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToMldev$1()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToMldev$1(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToMldev$1(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToMldev$1(fromProactivity)); + } + return toObject; +} +function liveConnectParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev$1(fromConfig, toObject)); + } + return toObject; +} +function activityStartToMldev() { + const toObject = {}; + return toObject; +} +function activityEndToMldev() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToMldev(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + setValueByPath(toObject, ['mediaChunks'], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], activityStartToMldev()); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], activityEndToMldev()); + } + return toObject; +} +function weightedPromptToMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromWeight = getValueByPath(fromObject, ['weight']); + if (fromWeight != null) { + setValueByPath(toObject, ['weight'], fromWeight); + } + return toObject; +} +function liveMusicSetWeightedPromptsParametersToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigToMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ['guidance']); + if (fromGuidance != null) { + setValueByPath(toObject, ['guidance'], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ['bpm']); + if (fromBpm != null) { + setValueByPath(toObject, ['bpm'], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ['density']); + if (fromDensity != null) { + setValueByPath(toObject, ['density'], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ['brightness']); + if (fromBrightness != null) { + setValueByPath(toObject, ['brightness'], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ['scale']); + if (fromScale != null) { + setValueByPath(toObject, ['scale'], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ['muteBass']); + if (fromMuteBass != null) { + setValueByPath(toObject, ['muteBass'], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ['muteDrums']); + if (fromMuteDrums != null) { + setValueByPath(toObject, ['muteDrums'], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, [ + 'onlyBassAndDrums', + ]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums); + } + const fromMusicGenerationMode = getValueByPath(fromObject, [ + 'musicGenerationMode', + ]); + if (fromMusicGenerationMode != null) { + setValueByPath(toObject, ['musicGenerationMode'], fromMusicGenerationMode); + } + return toObject; +} +function liveMusicSetConfigParametersToMldev(fromObject) { + const toObject = {}; + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig)); + } + return toObject; +} +function liveMusicClientSetupToMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + return toObject; +} +function liveMusicClientContentToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicClientMessageToMldev(fromObject) { + const toObject = {}; + const fromSetup = getValueByPath(fromObject, ['setup']); + if (fromSetup != null) { + setValueByPath(toObject, ['setup'], liveMusicClientSetupToMldev(fromSetup)); + } + const fromClientContent = getValueByPath(fromObject, [ + 'clientContent', + ]); + if (fromClientContent != null) { + setValueByPath(toObject, ['clientContent'], liveMusicClientContentToMldev(fromClientContent)); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig)); + } + const fromPlaybackControl = getValueByPath(fromObject, [ + 'playbackControl', + ]); + if (fromPlaybackControl != null) { + setValueByPath(toObject, ['playbackControl'], fromPlaybackControl); + } + return toObject; +} +function prebuiltVoiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex$1(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex$1(fromVoiceConfig)); + } + if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) { + throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.'); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex$1(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$1(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex$1(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex$1(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$1(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex$1(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex$1(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$1(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$1(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$1(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex$1(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex$1(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex$1()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex$1(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToVertex(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + const fromTransparent = getValueByPath(fromObject, ['transparent']); + if (fromTransparent != null) { + setValueByPath(toObject, ['transparent'], fromTransparent); + } + return toObject; +} +function audioTranscriptionConfigToVertex() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToVertex(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToVertex(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToVertex(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToVertex(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToVertex(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToVertex(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToVertex(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToVertex$1(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToVertex(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToVertex()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToVertex()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToVertex(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToVertex(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToVertex(fromProactivity)); + } + return toObject; +} +function liveConnectParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function activityStartToVertex() { + const toObject = {}; + return toObject; +} +function activityEndToVertex() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToVertex(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + setValueByPath(toObject, ['mediaChunks'], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], activityStartToVertex()); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], activityEndToVertex()); + } + return toObject; +} +function liveServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function videoMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev$1(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$1(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function transcriptionFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFinished = getValueByPath(fromObject, ['finished']); + if (fromFinished != null) { + setValueByPath(toObject, ['finished'], fromFinished); + } + return toObject; +} +function urlMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$1(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function liveServerContentFromMldev(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn != null) { + setValueByPath(toObject, ['modelTurn'], contentFromMldev$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete != null) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted != null) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + 'generationComplete', + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ['generationComplete'], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + 'inputTranscription', + ]); + if (fromInputTranscription != null) { + setValueByPath(toObject, ['inputTranscription'], transcriptionFromMldev(fromInputTranscription)); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + 'outputTranscription', + ]); + if (fromOutputTranscription != null) { + setValueByPath(toObject, ['outputTranscription'], transcriptionFromMldev(fromOutputTranscription)); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev$1(fromUrlContextMetadata)); + } + return toObject; +} +function functionCallFromMldev(fromObject) { + const toObject = {}; + const fromId = getValueByPath(fromObject, ['id']); + if (fromId != null) { + setValueByPath(toObject, ['id'], fromId); + } + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromMldev(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromMldev(item); + }); + } + setValueByPath(toObject, ['functionCalls'], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromMldev(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds != null) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function modalityTokenCountFromMldev(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ['modality']); + if (fromModality != null) { + setValueByPath(toObject, ['modality'], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function usageMetadataFromMldev(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, [ + 'promptTokenCount', + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + 'responseTokenCount', + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ['responseTokenCount'], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + 'toolUsePromptTokenCount', + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ['toolUsePromptTokenCount'], fromToolUsePromptTokenCount); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + 'thoughtsTokenCount', + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ['thoughtsTokenCount'], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, [ + 'totalTokenCount', + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + 'promptTokensDetails', + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['promptTokensDetails'], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + 'cacheTokensDetails', + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['cacheTokensDetails'], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + 'responseTokensDetails', + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['responseTokensDetails'], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + 'toolUsePromptTokensDetails', + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['toolUsePromptTokensDetails'], transformedList); + } + return toObject; +} +function liveServerGoAwayFromMldev(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ['timeLeft']); + if (fromTimeLeft != null) { + setValueByPath(toObject, ['timeLeft'], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromMldev(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ['newHandle']); + if (fromNewHandle != null) { + setValueByPath(toObject, ['newHandle'], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ['resumable']); + if (fromResumable != null) { + setValueByPath(toObject, ['resumable'], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + 'lastConsumedClientMessageIndex', + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath(toObject, ['lastConsumedClientMessageIndex'], fromLastConsumedClientMessageIndex); + } + return toObject; +} +function liveServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveServerSetupCompleteFromMldev()); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromMldev(fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromMldev(fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromMldev(fromToolCallCancellation)); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], usageMetadataFromMldev(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject, ['goAway']); + if (fromGoAway != null) { + setValueByPath(toObject, ['goAway'], liveServerGoAwayFromMldev(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + 'sessionResumptionUpdate', + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ['sessionResumptionUpdate'], liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate)); + } + return toObject; +} +function liveMusicServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function weightedPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromWeight = getValueByPath(fromObject, ['weight']); + if (fromWeight != null) { + setValueByPath(toObject, ['weight'], fromWeight); + } + return toObject; +} +function liveMusicClientContentFromMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptFromMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigFromMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ['guidance']); + if (fromGuidance != null) { + setValueByPath(toObject, ['guidance'], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ['bpm']); + if (fromBpm != null) { + setValueByPath(toObject, ['bpm'], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ['density']); + if (fromDensity != null) { + setValueByPath(toObject, ['density'], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ['brightness']); + if (fromBrightness != null) { + setValueByPath(toObject, ['brightness'], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ['scale']); + if (fromScale != null) { + setValueByPath(toObject, ['scale'], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ['muteBass']); + if (fromMuteBass != null) { + setValueByPath(toObject, ['muteBass'], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ['muteDrums']); + if (fromMuteDrums != null) { + setValueByPath(toObject, ['muteDrums'], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, [ + 'onlyBassAndDrums', + ]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums); + } + const fromMusicGenerationMode = getValueByPath(fromObject, [ + 'musicGenerationMode', + ]); + if (fromMusicGenerationMode != null) { + setValueByPath(toObject, ['musicGenerationMode'], fromMusicGenerationMode); + } + return toObject; +} +function liveMusicSourceMetadataFromMldev(fromObject) { + const toObject = {}; + const fromClientContent = getValueByPath(fromObject, [ + 'clientContent', + ]); + if (fromClientContent != null) { + setValueByPath(toObject, ['clientContent'], liveMusicClientContentFromMldev(fromClientContent)); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig)); + } + return toObject; +} +function audioChunkFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSourceMetadata = getValueByPath(fromObject, [ + 'sourceMetadata', + ]); + if (fromSourceMetadata != null) { + setValueByPath(toObject, ['sourceMetadata'], liveMusicSourceMetadataFromMldev(fromSourceMetadata)); + } + return toObject; +} +function liveMusicServerContentFromMldev(fromObject) { + const toObject = {}; + const fromAudioChunks = getValueByPath(fromObject, ['audioChunks']); + if (fromAudioChunks != null) { + let transformedList = fromAudioChunks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return audioChunkFromMldev(item); + }); + } + setValueByPath(toObject, ['audioChunks'], transformedList); + } + return toObject; +} +function liveMusicFilteredPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFilteredReason = getValueByPath(fromObject, [ + 'filteredReason', + ]); + if (fromFilteredReason != null) { + setValueByPath(toObject, ['filteredReason'], fromFilteredReason); + } + return toObject; +} +function liveMusicServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveMusicServerSetupCompleteFromMldev()); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveMusicServerContentFromMldev(fromServerContent)); + } + const fromFilteredPrompt = getValueByPath(fromObject, [ + 'filteredPrompt', + ]); + if (fromFilteredPrompt != null) { + setValueByPath(toObject, ['filteredPrompt'], liveMusicFilteredPromptFromMldev(fromFilteredPrompt)); + } + return toObject; +} +function liveServerSetupCompleteFromVertex(fromObject) { + const toObject = {}; + const fromSessionId = getValueByPath(fromObject, ['sessionId']); + if (fromSessionId != null) { + setValueByPath(toObject, ['sessionId'], fromSessionId); + } + return toObject; +} +function videoMetadataFromVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromVertex$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function transcriptionFromVertex(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFinished = getValueByPath(fromObject, ['finished']); + if (fromFinished != null) { + setValueByPath(toObject, ['finished'], fromFinished); + } + return toObject; +} +function liveServerContentFromVertex(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn != null) { + setValueByPath(toObject, ['modelTurn'], contentFromVertex$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete != null) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted != null) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + 'generationComplete', + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ['generationComplete'], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + 'inputTranscription', + ]); + if (fromInputTranscription != null) { + setValueByPath(toObject, ['inputTranscription'], transcriptionFromVertex(fromInputTranscription)); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + 'outputTranscription', + ]); + if (fromOutputTranscription != null) { + setValueByPath(toObject, ['outputTranscription'], transcriptionFromVertex(fromOutputTranscription)); + } + return toObject; +} +function functionCallFromVertex(fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromVertex(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromVertex(item); + }); + } + setValueByPath(toObject, ['functionCalls'], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromVertex(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds != null) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function modalityTokenCountFromVertex(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ['modality']); + if (fromModality != null) { + setValueByPath(toObject, ['modality'], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function usageMetadataFromVertex(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, [ + 'promptTokenCount', + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + 'candidatesTokenCount', + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ['responseTokenCount'], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + 'toolUsePromptTokenCount', + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ['toolUsePromptTokenCount'], fromToolUsePromptTokenCount); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + 'thoughtsTokenCount', + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ['thoughtsTokenCount'], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, [ + 'totalTokenCount', + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + 'promptTokensDetails', + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['promptTokensDetails'], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + 'cacheTokensDetails', + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['cacheTokensDetails'], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + 'candidatesTokensDetails', + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['responseTokensDetails'], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + 'toolUsePromptTokensDetails', + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['toolUsePromptTokensDetails'], transformedList); + } + const fromTrafficType = getValueByPath(fromObject, ['trafficType']); + if (fromTrafficType != null) { + setValueByPath(toObject, ['trafficType'], fromTrafficType); + } + return toObject; +} +function liveServerGoAwayFromVertex(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ['timeLeft']); + if (fromTimeLeft != null) { + setValueByPath(toObject, ['timeLeft'], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromVertex(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ['newHandle']); + if (fromNewHandle != null) { + setValueByPath(toObject, ['newHandle'], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ['resumable']); + if (fromResumable != null) { + setValueByPath(toObject, ['resumable'], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + 'lastConsumedClientMessageIndex', + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath(toObject, ['lastConsumedClientMessageIndex'], fromLastConsumedClientMessageIndex); + } + return toObject; +} +function liveServerMessageFromVertex(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveServerSetupCompleteFromVertex(fromSetupComplete)); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromVertex(fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromVertex(fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromVertex(fromToolCallCancellation)); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], usageMetadataFromVertex(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject, ['goAway']); + if (fromGoAway != null) { + setValueByPath(toObject, ['goAway'], liveServerGoAwayFromVertex(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + 'sessionResumptionUpdate', + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ['sessionResumptionUpdate'], liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$1(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$1(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$1(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$1(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$1(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$1(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$1(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$1()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$1(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$1(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$1(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$1(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$1(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$1(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$1(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToMldev(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToMldev$1(tSpeechConfig(fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev(fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['requests[]', 'taskType'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['requests[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['requests[]', 'outputDimensionality'], fromOutputDimensionality); + } + if (getValueByPath(fromObject, ['mimeType']) !== undefined) { + throw new Error('mimeType parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['autoTruncate']) !== undefined) { + throw new Error('autoTruncate parameter is not supported in Gemini API.'); + } + return toObject; +} +function embedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + setValueByPath(toObject, ['requests[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToMldev(fromConfig, toObject)); + } + const fromModelForEmbedContent = getValueByPath(fromObject, ['model']); + if (fromModelForEmbedContent !== undefined) { + setValueByPath(toObject, ['requests[]', 'model'], tModel(apiClient, fromModelForEmbedContent)); + } + return toObject; +} +function generateImagesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['negativePrompt']) !== undefined) { + throw new Error('negativePrompt parameter is not supported in Gemini API.'); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + if (getValueByPath(fromObject, ['addWatermark']) !== undefined) { + throw new Error('addWatermark parameter is not supported in Gemini API.'); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath(parentObject, ['parameters', 'sampleImageSize'], fromImageSize); + } + if (getValueByPath(fromObject, ['enhancePrompt']) !== undefined) { + throw new Error('enhancePrompt parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateImagesParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateImagesConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listModelsConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listModelsConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function updateModelConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateModelConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function deleteModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function countTokensConfigToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['systemInstruction']) !== undefined) { + throw new Error('systemInstruction parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['tools']) !== undefined) { + throw new Error('tools parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['generationConfig']) !== undefined) { + throw new Error('generationConfig parameter is not supported in Gemini API.'); + } + return toObject; +} +function countTokensParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToMldev(fromConfig)); + } + return toObject; +} +function imageToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['fps']) !== undefined) { + throw new Error('fps parameter is not supported in Gemini API.'); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + if (getValueByPath(fromObject, ['resolution']) !== undefined) { + throw new Error('resolution parameter is not supported in Gemini API.'); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + if (getValueByPath(fromObject, ['pubsubTopic']) !== undefined) { + throw new Error('pubsubTopic parameter is not supported in Gemini API.'); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + if (getValueByPath(fromObject, ['generateAudio']) !== undefined) { + throw new Error('generateAudio parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['lastFrame']) !== undefined) { + throw new Error('lastFrame parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['referenceImages']) !== undefined) { + throw new Error('referenceImages parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['compressionQuality']) !== undefined) { + throw new Error('compressionQuality parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateVideosParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToMldev(fromImage)); + } + if (getValueByPath(fromObject, ['video']) !== undefined) { + throw new Error('video parameter is not supported in Gemini API.'); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataToVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToVertex(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function modelSelectionConfigToVertex(fromObject) { + const toObject = {}; + const fromFeatureSelectionPreference = getValueByPath(fromObject, [ + 'featureSelectionPreference', + ]); + if (fromFeatureSelectionPreference != null) { + setValueByPath(toObject, ['featureSelectionPreference'], fromFeatureSelectionPreference); + } + return toObject; +} +function safetySettingToVertex(fromObject) { + const toObject = {}; + const fromMethod = getValueByPath(fromObject, ['method']); + if (fromMethod != null) { + setValueByPath(toObject, ['method'], fromMethod); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToVertex(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToVertex(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToVertex(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex(fromVoiceConfig)); + } + if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) { + throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.'); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToVertex(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToVertex(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + const fromRoutingConfig = getValueByPath(fromObject, [ + 'routingConfig', + ]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ['routingConfig'], fromRoutingConfig); + } + const fromModelSelectionConfig = getValueByPath(fromObject, [ + 'modelSelectionConfig', + ]); + if (fromModelSelectionConfig != null) { + setValueByPath(toObject, ['modelConfig'], modelSelectionConfigToVertex(fromModelSelectionConfig)); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToVertex(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex(fromToolConfig)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ['labels'], fromLabels); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToVertex(tSpeechConfig(fromSpeechConfig))); + } + const fromAudioTimestamp = getValueByPath(fromObject, [ + 'audioTimestamp', + ]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToVertex(fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['instances[]', 'task_type'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['instances[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['parameters', 'outputDimensionality'], fromOutputDimensionality); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (parentObject !== undefined && fromMimeType != null) { + setValueByPath(parentObject, ['instances[]', 'mimeType'], fromMimeType); + } + const fromAutoTruncate = getValueByPath(fromObject, ['autoTruncate']); + if (parentObject !== undefined && fromAutoTruncate != null) { + setValueByPath(parentObject, ['parameters', 'autoTruncate'], fromAutoTruncate); + } + return toObject; +} +function embedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + setValueByPath(toObject, ['instances[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function generateImagesConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath(parentObject, ['parameters', 'sampleImageSize'], fromImageSize); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function generateImagesParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateImagesConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function imageToVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function maskReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromMaskMode = getValueByPath(fromObject, ['maskMode']); + if (fromMaskMode != null) { + setValueByPath(toObject, ['maskMode'], fromMaskMode); + } + const fromSegmentationClasses = getValueByPath(fromObject, [ + 'segmentationClasses', + ]); + if (fromSegmentationClasses != null) { + setValueByPath(toObject, ['maskClasses'], fromSegmentationClasses); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (fromMaskDilation != null) { + setValueByPath(toObject, ['dilation'], fromMaskDilation); + } + return toObject; +} +function controlReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromControlType = getValueByPath(fromObject, ['controlType']); + if (fromControlType != null) { + setValueByPath(toObject, ['controlType'], fromControlType); + } + const fromEnableControlImageComputation = getValueByPath(fromObject, [ + 'enableControlImageComputation', + ]); + if (fromEnableControlImageComputation != null) { + setValueByPath(toObject, ['computeControl'], fromEnableControlImageComputation); + } + return toObject; +} +function styleReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromStyleDescription = getValueByPath(fromObject, [ + 'styleDescription', + ]); + if (fromStyleDescription != null) { + setValueByPath(toObject, ['styleDescription'], fromStyleDescription); + } + return toObject; +} +function subjectReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromSubjectType = getValueByPath(fromObject, ['subjectType']); + if (fromSubjectType != null) { + setValueByPath(toObject, ['subjectType'], fromSubjectType); + } + const fromSubjectDescription = getValueByPath(fromObject, [ + 'subjectDescription', + ]); + if (fromSubjectDescription != null) { + setValueByPath(toObject, ['subjectDescription'], fromSubjectDescription); + } + return toObject; +} +function referenceImageAPIInternalToVertex(fromObject) { + const toObject = {}; + const fromReferenceImage = getValueByPath(fromObject, [ + 'referenceImage', + ]); + if (fromReferenceImage != null) { + setValueByPath(toObject, ['referenceImage'], imageToVertex(fromReferenceImage)); + } + const fromReferenceId = getValueByPath(fromObject, ['referenceId']); + if (fromReferenceId != null) { + setValueByPath(toObject, ['referenceId'], fromReferenceId); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + const fromMaskImageConfig = getValueByPath(fromObject, [ + 'maskImageConfig', + ]); + if (fromMaskImageConfig != null) { + setValueByPath(toObject, ['maskImageConfig'], maskReferenceConfigToVertex(fromMaskImageConfig)); + } + const fromControlImageConfig = getValueByPath(fromObject, [ + 'controlImageConfig', + ]); + if (fromControlImageConfig != null) { + setValueByPath(toObject, ['controlImageConfig'], controlReferenceConfigToVertex(fromControlImageConfig)); + } + const fromStyleImageConfig = getValueByPath(fromObject, [ + 'styleImageConfig', + ]); + if (fromStyleImageConfig != null) { + setValueByPath(toObject, ['styleImageConfig'], styleReferenceConfigToVertex(fromStyleImageConfig)); + } + const fromSubjectImageConfig = getValueByPath(fromObject, [ + 'subjectImageConfig', + ]); + if (fromSubjectImageConfig != null) { + setValueByPath(toObject, ['subjectImageConfig'], subjectReferenceConfigToVertex(fromSubjectImageConfig)); + } + return toObject; +} +function editImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromEditMode = getValueByPath(fromObject, ['editMode']); + if (parentObject !== undefined && fromEditMode != null) { + setValueByPath(parentObject, ['parameters', 'editMode'], fromEditMode); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'editConfig', 'baseSteps'], fromBaseSteps); + } + return toObject; +} +function editImageParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return referenceImageAPIInternalToVertex(item); + }); + } + setValueByPath(toObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], editImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function upscaleImageAPIConfigInternalToVertex(fromObject, parentObject) { + const toObject = {}; + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhanceInputImage = getValueByPath(fromObject, [ + 'enhanceInputImage', + ]); + if (parentObject !== undefined && fromEnhanceInputImage != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'enhanceInputImage'], fromEnhanceInputImage); + } + const fromImagePreservationFactor = getValueByPath(fromObject, [ + 'imagePreservationFactor', + ]); + if (parentObject !== undefined && fromImagePreservationFactor != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'imagePreservationFactor'], fromImagePreservationFactor); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + return toObject; +} +function upscaleImageAPIParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromUpscaleFactor = getValueByPath(fromObject, [ + 'upscaleFactor', + ]); + if (fromUpscaleFactor != null) { + setValueByPath(toObject, ['parameters', 'upscaleConfig', 'upscaleFactor'], fromUpscaleFactor); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], upscaleImageAPIConfigInternalToVertex(fromConfig, toObject)); + } + return toObject; +} +function productImageToVertex(fromObject) { + const toObject = {}; + const fromProductImage = getValueByPath(fromObject, ['productImage']); + if (fromProductImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromProductImage)); + } + return toObject; +} +function recontextImageSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromPersonImage = getValueByPath(fromObject, ['personImage']); + if (parentObject !== undefined && fromPersonImage != null) { + setValueByPath(parentObject, ['instances[0]', 'personImage', 'image'], imageToVertex(fromPersonImage)); + } + const fromProductImages = getValueByPath(fromObject, [ + 'productImages', + ]); + if (parentObject !== undefined && fromProductImages != null) { + let transformedList = fromProductImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return productImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'productImages'], transformedList); + } + return toObject; +} +function recontextImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'editConfig', 'baseSteps'], fromBaseSteps); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function recontextImageParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], recontextImageSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], recontextImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function scribbleImageToVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + return toObject; +} +function segmentImageSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromScribbleImage = getValueByPath(fromObject, [ + 'scribbleImage', + ]); + if (parentObject !== undefined && fromScribbleImage != null) { + setValueByPath(parentObject, ['instances[0]', 'scribble'], scribbleImageToVertex(fromScribbleImage)); + } + return toObject; +} +function segmentImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + const fromMaxPredictions = getValueByPath(fromObject, [ + 'maxPredictions', + ]); + if (parentObject !== undefined && fromMaxPredictions != null) { + setValueByPath(parentObject, ['parameters', 'maxPredictions'], fromMaxPredictions); + } + const fromConfidenceThreshold = getValueByPath(fromObject, [ + 'confidenceThreshold', + ]); + if (parentObject !== undefined && fromConfidenceThreshold != null) { + setValueByPath(parentObject, ['parameters', 'confidenceThreshold'], fromConfidenceThreshold); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (parentObject !== undefined && fromMaskDilation != null) { + setValueByPath(parentObject, ['parameters', 'maskDilation'], fromMaskDilation); + } + const fromBinaryColorThreshold = getValueByPath(fromObject, [ + 'binaryColorThreshold', + ]); + if (parentObject !== undefined && fromBinaryColorThreshold != null) { + setValueByPath(parentObject, ['parameters', 'binaryColorThreshold'], fromBinaryColorThreshold); + } + return toObject; +} +function segmentImageParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], segmentImageSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], segmentImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listModelsConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listModelsConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function updateModelConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateModelConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function deleteModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function countTokensConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['generationConfig'], fromGenerationConfig); + } + return toObject; +} +function countTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function computeTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoToVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['gcsUri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ['videoBytes']); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function videoGenerationReferenceImageToVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + return toObject; +} +function generateVideosConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromFps = getValueByPath(fromObject, ['fps']); + if (parentObject !== undefined && fromFps != null) { + setValueByPath(parentObject, ['parameters', 'fps'], fromFps); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromResolution = getValueByPath(fromObject, ['resolution']); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ['parameters', 'resolution'], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromPubsubTopic = getValueByPath(fromObject, ['pubsubTopic']); + if (parentObject !== undefined && fromPubsubTopic != null) { + setValueByPath(parentObject, ['parameters', 'pubsubTopic'], fromPubsubTopic); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + const fromGenerateAudio = getValueByPath(fromObject, [ + 'generateAudio', + ]); + if (parentObject !== undefined && fromGenerateAudio != null) { + setValueByPath(parentObject, ['parameters', 'generateAudio'], fromGenerateAudio); + } + const fromLastFrame = getValueByPath(fromObject, ['lastFrame']); + if (parentObject !== undefined && fromLastFrame != null) { + setValueByPath(parentObject, ['instances[0]', 'lastFrame'], imageToVertex(fromLastFrame)); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (parentObject !== undefined && fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return videoGenerationReferenceImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromCompressionQuality = getValueByPath(fromObject, [ + 'compressionQuality', + ]); + if (parentObject !== undefined && fromCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'compressionQuality'], fromCompressionQuality); + } + return toObject; +} +function generateVideosParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['instances[0]', 'video'], videoToVertex(fromVideo)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataFromMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromMldev(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingFromMldev(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + return toObject; +} +function embedContentMetadataFromMldev() { + const toObject = {}; + return toObject; +} +function embedContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, ['embeddings']); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromMldev(item); + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromMldev()); + } + return toObject; +} +function imageFromMldev(fromObject) { + const toObject = {}; + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromMldev(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + 'safetyAttributes', + 'categories', + ]); + if (fromCategories != null) { + setValueByPath(toObject, ['categories'], fromCategories); + } + const fromScores = getValueByPath(fromObject, [ + 'safetyAttributes', + 'scores', + ]); + if (fromScores != null) { + setValueByPath(toObject, ['scores'], fromScores); + } + const fromContentType = getValueByPath(fromObject, ['contentType']); + if (fromContentType != null) { + setValueByPath(toObject, ['contentType'], fromContentType); + } + return toObject; +} +function generatedImageFromMldev(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromMldev(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromMldev(fromSafetyAttributes)); + } + return toObject; +} +function generateImagesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromMldev(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromMldev(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function tunedModelInfoFromMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function modelFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['version']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromMldev(fromTunedModelInfo)); + } + const fromInputTokenLimit = getValueByPath(fromObject, [ + 'inputTokenLimit', + ]); + if (fromInputTokenLimit != null) { + setValueByPath(toObject, ['inputTokenLimit'], fromInputTokenLimit); + } + const fromOutputTokenLimit = getValueByPath(fromObject, [ + 'outputTokenLimit', + ]); + if (fromOutputTokenLimit != null) { + setValueByPath(toObject, ['outputTokenLimit'], fromOutputTokenLimit); + } + const fromSupportedActions = getValueByPath(fromObject, [ + 'supportedGenerationMethods', + ]); + if (fromSupportedActions != null) { + setValueByPath(toObject, ['supportedActions'], fromSupportedActions); + } + return toObject; +} +function listModelsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromMldev(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function deleteModelResponseFromMldev() { + const toObject = {}; + return toObject; +} +function countTokensResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + return toObject; +} +function videoFromMldev(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['video', 'uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'video', + 'encodedVideo', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['encoding']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromMldev(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, [ + 'generatedSamples', + ]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromMldev(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosOperationFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, [ + 'response', + 'generateVideoResponse', + ]); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromMldev(fromResponse)); + } + return toObject; +} +function videoMetadataFromVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromVertex(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromVertex(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citations']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromVertex(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromVertex(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromVertex(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromVertex(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromVertex(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromVertex(fromCitationMetadata)); + } + const fromFinishMessage = getValueByPath(fromObject, [ + 'finishMessage', + ]); + if (fromFinishMessage != null) { + setValueByPath(toObject, ['finishMessage'], fromFinishMessage); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromVertex(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromVertex(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingStatisticsFromVertex(fromObject) { + const toObject = {}; + const fromTruncated = getValueByPath(fromObject, ['truncated']); + if (fromTruncated != null) { + setValueByPath(toObject, ['truncated'], fromTruncated); + } + const fromTokenCount = getValueByPath(fromObject, ['token_count']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function contentEmbeddingFromVertex(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + const fromStatistics = getValueByPath(fromObject, ['statistics']); + if (fromStatistics != null) { + setValueByPath(toObject, ['statistics'], contentEmbeddingStatisticsFromVertex(fromStatistics)); + } + return toObject; +} +function embedContentMetadataFromVertex(fromObject) { + const toObject = {}; + const fromBillableCharacterCount = getValueByPath(fromObject, [ + 'billableCharacterCount', + ]); + if (fromBillableCharacterCount != null) { + setValueByPath(toObject, ['billableCharacterCount'], fromBillableCharacterCount); + } + return toObject; +} +function embedContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, [ + 'predictions[]', + 'embeddings', + ]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromVertex(item); + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromVertex(fromMetadata)); + } + return toObject; +} +function imageFromVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromVertex(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + 'safetyAttributes', + 'categories', + ]); + if (fromCategories != null) { + setValueByPath(toObject, ['categories'], fromCategories); + } + const fromScores = getValueByPath(fromObject, [ + 'safetyAttributes', + 'scores', + ]); + if (fromScores != null) { + setValueByPath(toObject, ['scores'], fromScores); + } + const fromContentType = getValueByPath(fromObject, ['contentType']); + if (fromContentType != null) { + setValueByPath(toObject, ['contentType'], fromContentType); + } + return toObject; +} +function generatedImageFromVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromVertex(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromVertex(fromSafetyAttributes)); + } + const fromEnhancedPrompt = getValueByPath(fromObject, ['prompt']); + if (fromEnhancedPrompt != null) { + setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt); + } + return toObject; +} +function generateImagesResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromVertex(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function editImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function upscaleImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function recontextImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function entityLabelFromVertex(fromObject) { + const toObject = {}; + const fromLabel = getValueByPath(fromObject, ['label']); + if (fromLabel != null) { + setValueByPath(toObject, ['label'], fromLabel); + } + const fromScore = getValueByPath(fromObject, ['score']); + if (fromScore != null) { + setValueByPath(toObject, ['score'], fromScore); + } + return toObject; +} +function generatedImageMaskFromVertex(fromObject) { + const toObject = {}; + const fromMask = getValueByPath(fromObject, ['_self']); + if (fromMask != null) { + setValueByPath(toObject, ['mask'], imageFromVertex(fromMask)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + let transformedList = fromLabels; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return entityLabelFromVertex(item); + }); + } + setValueByPath(toObject, ['labels'], transformedList); + } + return toObject; +} +function segmentImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedMasks = getValueByPath(fromObject, ['predictions']); + if (fromGeneratedMasks != null) { + let transformedList = fromGeneratedMasks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageMaskFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedMasks'], transformedList); + } + return toObject; +} +function endpointFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['endpoint']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDeployedModelId = getValueByPath(fromObject, [ + 'deployedModelId', + ]); + if (fromDeployedModelId != null) { + setValueByPath(toObject, ['deployedModelId'], fromDeployedModelId); + } + return toObject; +} +function tunedModelInfoFromVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, [ + 'labels', + 'google-vertex-llm-tuning-base-model-id', + ]); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function checkpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ['checkpointId']); + if (fromCheckpointId != null) { + setValueByPath(toObject, ['checkpointId'], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ['epoch']); + if (fromEpoch != null) { + setValueByPath(toObject, ['epoch'], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ['step']); + if (fromStep != null) { + setValueByPath(toObject, ['step'], fromStep); + } + return toObject; +} +function modelFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['versionId']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromEndpoints = getValueByPath(fromObject, ['deployedModels']); + if (fromEndpoints != null) { + let transformedList = fromEndpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return endpointFromVertex(item); + }); + } + setValueByPath(toObject, ['endpoints'], transformedList); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromVertex(fromTunedModelInfo)); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (fromDefaultCheckpointId != null) { + setValueByPath(toObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + const fromCheckpoints = getValueByPath(fromObject, ['checkpoints']); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return checkpointFromVertex(item); + }); + } + setValueByPath(toObject, ['checkpoints'], transformedList); + } + return toObject; +} +function listModelsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromVertex(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function deleteModelResponseFromVertex() { + const toObject = {}; + return toObject; +} +function countTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + return toObject; +} +function computeTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTokensInfo = getValueByPath(fromObject, ['tokensInfo']); + if (fromTokensInfo != null) { + setValueByPath(toObject, ['tokensInfo'], fromTokensInfo); + } + return toObject; +} +function videoFromVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['gcsUri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromVertex(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ['videos']); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosOperationFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromVertex(fromResponse)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// TODO: b/416041229 - Determine how to retrieve the MCP package version. +const MCP_LABEL = 'mcp_used/unknown'; +// Whether MCP tool usage is detected from mcpToTool. This is used for +// telemetry. +let hasMcpToolUsageFromMcpToTool = false; +// Checks whether the list of tools contains any MCP tools. +function hasMcpToolUsage(tools) { + for (const tool of tools) { + if (isMcpCallableTool(tool)) { + return true; + } + if (typeof tool === 'object' && 'inputSchema' in tool) { + return true; + } + } + return hasMcpToolUsageFromMcpToTool; +} +// Sets the MCP version label in the Google API client header. +function setMcpUsageHeader(headers) { + var _a; + const existingHeader = (_a = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a !== void 0 ? _a : ''; + headers[GOOGLE_API_CLIENT_HEADER] = (existingHeader + ` ${MCP_LABEL}`).trimStart(); +} +// Returns true if the object is a MCP CallableTool, otherwise false. +function isMcpCallableTool(object) { + return (object !== null && + typeof object === 'object' && + object instanceof McpCallableTool); +} +// List all tools from the MCP client. +function listAllTools(mcpClient, maxTools = 100) { + return __asyncGenerator(this, arguments, function* listAllTools_1() { + let cursor = undefined; + let numTools = 0; + while (numTools < maxTools) { + const t = yield __await(mcpClient.listTools({ cursor })); + for (const tool of t.tools) { + yield yield __await(tool); + numTools++; + } + if (!t.nextCursor) { + break; + } + cursor = t.nextCursor; + } + }); +} +/** + * McpCallableTool can be used for model inference and invoking MCP clients with + * given function call arguments. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +class McpCallableTool { + constructor(mcpClients = [], config) { + this.mcpTools = []; + this.functionNameToMcpClient = {}; + this.mcpClients = mcpClients; + this.config = config; + } + /** + * Creates a McpCallableTool. + */ + static create(mcpClients, config) { + return new McpCallableTool(mcpClients, config); + } + /** + * Validates the function names are not duplicate and initialize the function + * name to MCP client mapping. + * + * @throws {Error} if the MCP tools from the MCP clients have duplicate tool + * names. + */ + async initialize() { + var _a, e_1, _b, _c; + if (this.mcpTools.length > 0) { + return; + } + const functionMap = {}; + const mcpTools = []; + for (const mcpClient of this.mcpClients) { + try { + for (var _d = true, _e = (e_1 = void 0, __asyncValues(listAllTools(mcpClient))), _f; _f = await _e.next(), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const mcpTool = _c; + mcpTools.push(mcpTool); + const mcpToolName = mcpTool.name; + if (functionMap[mcpToolName]) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + functionMap[mcpToolName] = mcpClient; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_d && !_a && (_b = _e.return)) await _b.call(_e); + } + finally { if (e_1) throw e_1.error; } + } + } + this.mcpTools = mcpTools; + this.functionNameToMcpClient = functionMap; + } + async tool() { + await this.initialize(); + return mcpToolsToGeminiTool(this.mcpTools, this.config); + } + async callTool(functionCalls) { + await this.initialize(); + const functionCallResponseParts = []; + for (const functionCall of functionCalls) { + if (functionCall.name in this.functionNameToMcpClient) { + const mcpClient = this.functionNameToMcpClient[functionCall.name]; + let requestOptions = undefined; + // TODO: b/424238654 - Add support for finer grained timeout control. + if (this.config.timeout) { + requestOptions = { + timeout: this.config.timeout, + }; + } + const callToolResponse = await mcpClient.callTool({ + name: functionCall.name, + arguments: functionCall.args, + }, + // Set the result schema to undefined to allow MCP to rely on the + // default schema. + undefined, requestOptions); + functionCallResponseParts.push({ + functionResponse: { + name: functionCall.name, + response: callToolResponse.isError + ? { error: callToolResponse } + : callToolResponse, + }, + }); + } + } + return functionCallResponseParts; + } +} +function isMcpClient(client) { + return (client !== null && + typeof client === 'object' && + 'listTools' in client && + typeof client.listTools === 'function'); +} +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +function mcpToTool(...args) { + // Set MCP usage for telemetry. + hasMcpToolUsageFromMcpToTool = true; + if (args.length === 0) { + throw new Error('No MCP clients provided'); + } + const maybeConfig = args[args.length - 1]; + if (isMcpClient(maybeConfig)) { + return McpCallableTool.create(args, {}); + } + return McpCallableTool.create(args.slice(0, args.length - 1), maybeConfig); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveMusicServerMessage, and then calling the onmessage callback. + * Note that the first message which is received from the server is a + * setupComplete message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage$1(apiClient, onmessage, event) { + const serverMessage = new LiveMusicServerMessage(); + let data; + if (event.data instanceof Blob) { + data = JSON.parse(await event.data.text()); + } + else { + data = JSON.parse(event.data); + } + const response = liveMusicServerMessageFromMldev(data); + Object.assign(serverMessage, response); + onmessage(serverMessage); +} +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +class LiveMusic { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + } + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b; + if (this.apiClient.isVertexAI()) { + throw new Error('Live music is not supported for Vertex AI.'); + } + console.warn('Live music generation is experimental and may change in future versions.'); + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + const headers = mapToHeaders$1(this.apiClient.getDefaultHeaders()); + const apiKey = this.apiClient.getApiKey(); + const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`; + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage$1(apiClient, callbacks.onmessage, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap$1(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + const model = tModel(this.apiClient, params.model); + const setup = liveMusicClientSetupToMldev({ + model, + }); + const clientMessage = liveMusicClientMessageToMldev({ setup }); + conn.send(JSON.stringify(clientMessage)); + return new LiveMusicSession(conn, this.apiClient); + } +} +/** + Represents a connection to the API. + + @experimental + */ +class LiveMusicSession { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + async setWeightedPrompts(params) { + if (!params.weightedPrompts || + Object.keys(params.weightedPrompts).length === 0) { + throw new Error('Weighted prompts must be set and contain at least one entry.'); + } + const setWeightedPromptsParameters = liveMusicSetWeightedPromptsParametersToMldev(params); + const clientContent = liveMusicClientContentToMldev(setWeightedPromptsParameters); + this.conn.send(JSON.stringify({ clientContent })); + } + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + async setMusicGenerationConfig(params) { + if (!params.musicGenerationConfig) { + params.musicGenerationConfig = {}; + } + const setConfigParameters = liveMusicSetConfigParametersToMldev(params); + const clientMessage = liveMusicClientMessageToMldev(setConfigParameters); + this.conn.send(JSON.stringify(clientMessage)); + } + sendPlaybackControl(playbackControl) { + const clientMessage = liveMusicClientMessageToMldev({ + playbackControl, + }); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + * Start the music stream. + * + * @experimental + */ + play() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PLAY); + } + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PAUSE); + } + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop() { + this.sendPlaybackControl(LiveMusicPlaybackControl.STOP); + } + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext() { + this.sendPlaybackControl(LiveMusicPlaybackControl.RESET_CONTEXT); + } + /** + Terminates the WebSocket connection. + + @experimental + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap$1(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders$1(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const FUNCTION_RESPONSE_REQUIRES_ID = 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.'; +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveServerMessages, and then calling the onmessage callback. Note that + * the first message which is received from the server is a setupComplete + * message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage(apiClient, onmessage, event) { + const serverMessage = new LiveServerMessage(); + let jsonData; + if (event.data instanceof Blob) { + jsonData = await event.data.text(); + } + else if (event.data instanceof ArrayBuffer) { + jsonData = new TextDecoder().decode(event.data); + } + else { + jsonData = event.data; + } + const data = JSON.parse(jsonData); + if (apiClient.isVertexAI()) { + const resp = liveServerMessageFromVertex(data); + Object.assign(serverMessage, resp); + } + else { + const resp = liveServerMessageFromMldev(data); + Object.assign(serverMessage, resp); + } + onmessage(serverMessage); +} +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +class Live { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + this.music = new LiveMusic(this.apiClient, this.auth, this.webSocketFactory); + } + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b, _c, _d, _e, _f; + // TODO: b/404946746 - Support per request HTTP options. + if (params.config && params.config.httpOptions) { + throw new Error('The Live module does not support httpOptions at request-level in' + + ' LiveConnectConfig yet. Please use the client-level httpOptions' + + ' configuration instead.'); + } + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + let url; + const clientHeaders = this.apiClient.getHeaders(); + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + setMcpUsageHeader(clientHeaders); + } + const headers = mapToHeaders(clientHeaders); + if (this.apiClient.isVertexAI()) { + url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`; + await this.auth.addAuthHeaders(headers); + } + else { + const apiKey = this.apiClient.getApiKey(); + let method = 'BidiGenerateContent'; + let keyName = 'key'; + if (apiKey === null || apiKey === void 0 ? void 0 : apiKey.startsWith('auth_tokens/')) { + console.warn('Warning: Ephemeral token support is experimental and may change in future versions.'); + if (apiVersion !== 'v1alpha') { + console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."); + } + method = 'BidiGenerateContentConstrained'; + keyName = 'access_token'; + } + url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`; + } + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + var _a; + (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onopen) === null || _a === void 0 ? void 0 : _a.call(callbacks); + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage(apiClient, callbacks.onmessage, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + let transformedModel = tModel(this.apiClient, params.model); + if (this.apiClient.isVertexAI() && + transformedModel.startsWith('publishers/')) { + const project = this.apiClient.getProject(); + const location = this.apiClient.getLocation(); + transformedModel = + `projects/${project}/locations/${location}/` + transformedModel; + } + let clientMessage = {}; + if (this.apiClient.isVertexAI() && + ((_c = params.config) === null || _c === void 0 ? void 0 : _c.responseModalities) === undefined) { + // Set default to AUDIO to align with MLDev API. + if (params.config === undefined) { + params.config = { responseModalities: [Modality.AUDIO] }; + } + else { + params.config.responseModalities = [Modality.AUDIO]; + } + } + if ((_d = params.config) === null || _d === void 0 ? void 0 : _d.generationConfig) { + // Raise deprecation warning for generationConfig. + console.warn('Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).'); + } + const inputTools = (_f = (_e = params.config) === null || _e === void 0 ? void 0 : _e.tools) !== null && _f !== void 0 ? _f : []; + const convertedTools = []; + for (const tool of inputTools) { + if (this.isCallableTool(tool)) { + const callableTool = tool; + convertedTools.push(await callableTool.tool()); + } + else { + convertedTools.push(tool); + } + } + if (convertedTools.length > 0) { + params.config.tools = convertedTools; + } + const liveConnectParameters = { + model: transformedModel, + config: params.config, + callbacks: params.callbacks, + }; + if (this.apiClient.isVertexAI()) { + clientMessage = liveConnectParametersToVertex(this.apiClient, liveConnectParameters); + } + else { + clientMessage = liveConnectParametersToMldev(this.apiClient, liveConnectParameters); + } + delete clientMessage['config']; + conn.send(JSON.stringify(clientMessage)); + return new Session(conn, this.apiClient); + } + // TODO: b/416041229 - Abstract this method to a common place. + isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; + } +} +const defaultLiveSendClientContentParamerters = { + turnComplete: true, +}; +/** + Represents a connection to the API. + + @experimental + */ +class Session { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + tLiveClientContent(apiClient, params) { + if (params.turns !== null && params.turns !== undefined) { + let contents = []; + try { + contents = tContents(params.turns); + if (apiClient.isVertexAI()) { + contents = contents.map((item) => contentToVertex(item)); + } + else { + contents = contents.map((item) => contentToMldev$1(item)); + } + } + catch (_a) { + throw new Error(`Failed to parse client content "turns", type: '${typeof params.turns}'`); + } + return { + clientContent: { turns: contents, turnComplete: params.turnComplete }, + }; + } + return { + clientContent: { turnComplete: params.turnComplete }, + }; + } + tLiveClienttToolResponse(apiClient, params) { + let functionResponses = []; + if (params.functionResponses == null) { + throw new Error('functionResponses is required.'); + } + if (!Array.isArray(params.functionResponses)) { + functionResponses = [params.functionResponses]; + } + else { + functionResponses = params.functionResponses; + } + if (functionResponses.length === 0) { + throw new Error('functionResponses is required.'); + } + for (const functionResponse of functionResponses) { + if (typeof functionResponse !== 'object' || + functionResponse === null || + !('name' in functionResponse) || + !('response' in functionResponse)) { + throw new Error(`Could not parse function response, type '${typeof functionResponse}'.`); + } + if (!apiClient.isVertexAI() && !('id' in functionResponse)) { + throw new Error(FUNCTION_RESPONSE_REQUIRES_ID); + } + } + const clientMessage = { + toolResponse: { functionResponses: functionResponses }, + }; + return clientMessage; + } + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params) { + params = Object.assign(Object.assign({}, defaultLiveSendClientContentParamerters), params); + const clientMessage = this.tLiveClientContent(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params) { + let clientMessage = {}; + if (this.apiClient.isVertexAI()) { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToVertex(params), + }; + } + else { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToMldev(params), + }; + } + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params) { + if (params.functionResponses == null) { + throw new Error('Tool response parameters are required.'); + } + const clientMessage = this.tLiveClienttToolResponse(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const DEFAULT_MAX_REMOTE_CALLS = 10; +/** Returns whether automatic function calling is disabled. */ +function shouldDisableAfc(config) { + var _a, _b, _c; + if ((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.disable) { + return true; + } + let callableToolsPresent = false; + for (const tool of (_b = config === null || config === void 0 ? void 0 : config.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + callableToolsPresent = true; + break; + } + } + if (!callableToolsPresent) { + return true; + } + const maxCalls = (_c = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _c === void 0 ? void 0 : _c.maximumRemoteCalls; + if ((maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) || + maxCalls == 0) { + console.warn('Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:', maxCalls); + return true; + } + return false; +} +function isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; +} +// Checks whether the list of tools contains any CallableTools. Will return true +// if there is at least one CallableTool. +function hasCallableTools(params) { + var _a, _b, _c; + return (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +// Checks whether the list of tools contains any non-callable tools. Will return +// true if there is at least one non-Callable tool. +function hasNonCallableTools(params) { + var _a, _b, _c; + return (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => !isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +/** + * Returns whether to append automatic function calling history to the + * response. + */ +function shouldAppendAfcHistory(config) { + var _a; + return !((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.ignoreCallHistory); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Models extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + this.generateContent = async (params) => { + var _a, _b, _c, _d, _e; + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + this.maybeMoveToResponseJsonSchem(params); + if (!hasCallableTools(params) || shouldDisableAfc(params.config)) { + return await this.generateContentInternal(transformedParams); + } + if (hasNonCallableTools(params)) { + throw new Error('Automatic function calling with CallableTools and Tools is not yet supported.'); + } + let response; + let functionResponseContent; + const automaticFunctionCallingHistory = tContents(transformedParams.contents); + const maxRemoteCalls = (_c = (_b = (_a = transformedParams.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let remoteCalls = 0; + while (remoteCalls < maxRemoteCalls) { + response = await this.generateContentInternal(transformedParams); + if (!response.functionCalls || response.functionCalls.length === 0) { + break; + } + const responseContent = response.candidates[0].content; + const functionResponseParts = []; + for (const tool of (_e = (_d = params.config) === null || _d === void 0 ? void 0 : _d.tools) !== null && _e !== void 0 ? _e : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const parts = await callableTool.callTool(response.functionCalls); + functionResponseParts.push(...parts); + } + } + remoteCalls++; + functionResponseContent = { + role: 'user', + parts: functionResponseParts, + }; + transformedParams.contents = tContents(transformedParams.contents); + transformedParams.contents.push(responseContent); + transformedParams.contents.push(functionResponseContent); + if (shouldAppendAfcHistory(transformedParams.config)) { + automaticFunctionCallingHistory.push(responseContent); + automaticFunctionCallingHistory.push(functionResponseContent); + } + } + if (shouldAppendAfcHistory(transformedParams.config)) { + response.automaticFunctionCallingHistory = + automaticFunctionCallingHistory; + } + return response; + }; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + this.generateContentStream = async (params) => { + this.maybeMoveToResponseJsonSchem(params); + if (shouldDisableAfc(params.config)) { + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + return await this.generateContentStreamInternal(transformedParams); + } + else { + return await this.processAfcStream(params); + } + }; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.generateImages = async (params) => { + return await this.generateImagesInternal(params).then((apiResponse) => { + var _a; + let positivePromptSafetyAttributes; + const generatedImages = []; + if (apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.generatedImages) { + for (const generatedImage of apiResponse.generatedImages) { + if (generatedImage && + (generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) && + ((_a = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) === null || _a === void 0 ? void 0 : _a.contentType) === 'Positive Prompt') { + positivePromptSafetyAttributes = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes; + } + else { + generatedImages.push(generatedImage); + } + } + } + let response; + if (positivePromptSafetyAttributes) { + response = { + generatedImages: generatedImages, + positivePromptSafetyAttributes: positivePromptSafetyAttributes, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + else { + response = { + generatedImages: generatedImages, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + return response; + }); + }; + this.list = async (params) => { + var _a; + const defaultConfig = { + queryBase: true, + }; + const actualConfig = Object.assign(Object.assign({}, defaultConfig), params === null || params === void 0 ? void 0 : params.config); + const actualParams = { + config: actualConfig, + }; + if (this.apiClient.isVertexAI()) { + if (!actualParams.config.queryBase) { + if ((_a = actualParams.config) === null || _a === void 0 ? void 0 : _a.filter) { + throw new Error('Filtering tuned models list for Vertex AI is not currently supported'); + } + else { + actualParams.config.filter = 'labels.tune-type:*'; + } + } + } + return new Pager(PagedItem.PAGED_ITEM_MODELS, (x) => this.listInternal(x), await this.listInternal(actualParams), actualParams); + }; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.editImage = async (params) => { + const paramsInternal = { + model: params.model, + prompt: params.prompt, + referenceImages: [], + config: params.config, + }; + if (params.referenceImages) { + if (params.referenceImages) { + paramsInternal.referenceImages = params.referenceImages.map((img) => img.toReferenceImageAPI()); + } + } + return await this.editImageInternal(paramsInternal); + }; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.upscaleImage = async (params) => { + let apiConfig = { + numberOfImages: 1, + mode: 'upscale', + }; + if (params.config) { + apiConfig = Object.assign(Object.assign({}, apiConfig), params.config); + } + const apiParams = { + model: params.model, + image: params.image, + upscaleFactor: params.upscaleFactor, + config: apiConfig, + }; + return await this.upscaleImageInternal(apiParams); + }; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + this.generateVideos = async (params) => { + return await this.generateVideosInternal(params); + }; + } + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + maybeMoveToResponseJsonSchem(params) { + if (params.config && params.config.responseSchema) { + if (!params.config.responseJsonSchema) { + if (Object.keys(params.config.responseSchema).includes('$schema')) { + params.config.responseJsonSchema = params.config.responseSchema; + delete params.config.responseSchema; + } + } + } + return; + } + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + async processParamsMaybeAddMcpUsage(params) { + var _a, _b, _c; + const tools = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools; + if (!tools) { + return params; + } + const transformedTools = await Promise.all(tools.map(async (tool) => { + if (isCallableTool(tool)) { + const callableTool = tool; + return await callableTool.tool(); + } + return tool; + })); + const newParams = { + model: params.model, + contents: params.contents, + config: Object.assign(Object.assign({}, params.config), { tools: transformedTools }), + }; + newParams.config.tools = transformedTools; + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + const headers = (_c = (_b = params.config.httpOptions) === null || _b === void 0 ? void 0 : _b.headers) !== null && _c !== void 0 ? _c : {}; + let newHeaders = Object.assign({}, headers); + if (Object.keys(newHeaders).length === 0) { + newHeaders = this.apiClient.getDefaultHeaders(); + } + setMcpUsageHeader(newHeaders); + newParams.config.httpOptions = Object.assign(Object.assign({}, params.config.httpOptions), { headers: newHeaders }); + } + return newParams; + } + async initAfcToolsMap(params) { + var _a, _b, _c; + const afcTools = new Map(); + for (const tool of (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const toolDeclaration = await callableTool.tool(); + for (const declaration of (_c = toolDeclaration.functionDeclarations) !== null && _c !== void 0 ? _c : []) { + if (!declaration.name) { + throw new Error('Function declaration name is required.'); + } + if (afcTools.has(declaration.name)) { + throw new Error(`Duplicate tool declaration name: ${declaration.name}`); + } + afcTools.set(declaration.name, callableTool); + } + } + } + return afcTools; + } + async processAfcStream(params) { + var _a, _b, _c; + const maxRemoteCalls = (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let wereFunctionsCalled = false; + let remoteCallCount = 0; + const afcToolsMap = await this.initAfcToolsMap(params); + return (function (models, afcTools, params) { + var _a, _b; + return __asyncGenerator(this, arguments, function* () { + var _c, e_1, _d, _e; + while (remoteCallCount < maxRemoteCalls) { + if (wereFunctionsCalled) { + remoteCallCount++; + wereFunctionsCalled = false; + } + const transformedParams = yield __await(models.processParamsMaybeAddMcpUsage(params)); + const response = yield __await(models.generateContentStreamInternal(transformedParams)); + const functionResponses = []; + const responseContents = []; + try { + for (var _f = true, response_1 = (e_1 = void 0, __asyncValues(response)), response_1_1; response_1_1 = yield __await(response_1.next()), _c = response_1_1.done, !_c; _f = true) { + _e = response_1_1.value; + _f = false; + const chunk = _e; + yield yield __await(chunk); + if (chunk.candidates && ((_a = chunk.candidates[0]) === null || _a === void 0 ? void 0 : _a.content)) { + responseContents.push(chunk.candidates[0].content); + for (const part of (_b = chunk.candidates[0].content.parts) !== null && _b !== void 0 ? _b : []) { + if (remoteCallCount < maxRemoteCalls && part.functionCall) { + if (!part.functionCall.name) { + throw new Error('Function call name was not returned by the model.'); + } + if (!afcTools.has(part.functionCall.name)) { + throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${part.functionCall.name}`); + } + else { + const responseParts = yield __await(afcTools + .get(part.functionCall.name) + .callTool([part.functionCall])); + functionResponses.push(...responseParts); + } + } + } + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_c && (_d = response_1.return)) yield __await(_d.call(response_1)); + } + finally { if (e_1) throw e_1.error; } + } + if (functionResponses.length > 0) { + wereFunctionsCalled = true; + const typedResponseChunk = new GenerateContentResponse(); + typedResponseChunk.candidates = [ + { + content: { + role: 'user', + parts: functionResponses, + }, + }, + ]; + yield yield __await(typedResponseChunk); + const newContents = []; + newContents.push(...responseContents); + newContents.push({ + role: 'user', + parts: functionResponses, + }); + const updatedContents = tContents(params.contents).concat(newContents); + params.contents = updatedContents; + } + else { + break; + } + } + }); + })(this, afcToolsMap, params); + } + async generateContentInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromVertex(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromMldev(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async generateContentStreamInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_2, _b, _c; + try { + for (var _d = true, apiResponse_1 = __asyncValues(apiResponse), apiResponse_1_1; apiResponse_1_1 = yield __await(apiResponse_1.next()), _a = apiResponse_1_1.done, !_a; _d = true) { + _c = apiResponse_1_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromVertex((yield __await(chunk.json()))); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_1.return)) yield __await(_b.call(apiResponse_1)); + } + finally { if (e_2) throw e_2.error; } + } + }); + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_3, _b, _c; + try { + for (var _d = true, apiResponse_2 = __asyncValues(apiResponse), apiResponse_2_1; apiResponse_2_1 = yield __await(apiResponse_2.next()), _a = apiResponse_2_1.done, !_a; _d = true) { + _c = apiResponse_2_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromMldev((yield __await(chunk.json()))); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_2.return)) yield __await(_b.call(apiResponse_2)); + } + finally { if (e_3) throw e_3.error; } + } + }); + }); + } + } + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + async embedContent(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = embedContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromVertex(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = embedContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchEmbedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromMldev(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async generateImagesInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateImagesParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromVertex(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateImagesParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromMldev(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async editImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = editImageParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = editImageResponseFromVertex(apiResponse); + const typedResp = new EditImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + async upscaleImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = upscaleImageAPIParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = upscaleImageResponseFromVertex(apiResponse); + const typedResp = new UpscaleImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Recontextualizes an image. + * + * There are two types of recontextualization currently supported: + * 1) Imagen Product Recontext - Generate images of products in new scenes + * and contexts. + * 2) Virtual Try-On: Generate images of persons modeling fashion products. + * + * @param params - The parameters for recontextualizing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response1 = await ai.models.recontextImage({ + * model: 'imagen-product-recontext-preview-06-30', + * source: { + * prompt: 'In a modern kitchen setting.', + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response1?.generatedImages?.[0]?.image?.imageBytes); + * + * const response2 = await ai.models.recontextImage({ + * model: 'virtual-try-on-preview-08-04', + * source: { + * personImage: personImage, + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response2?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async recontextImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = recontextImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = recontextImageResponseFromVertex(apiResponse); + const typedResp = new RecontextImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Segments an image, creating a mask of a specified area. + * + * @param params - The parameters for segmenting an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.segmentImage({ + * model: 'image-segmentation-001', + * source: { + * image: image, + * }, + * config: { + * mode: 'foreground', + * }, + * }); + * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes); + * ``` + */ + async segmentImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = segmentImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = segmentImageResponseFromVertex(apiResponse); + const typedResp = new SegmentImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listModelsParametersToVertex(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromVertex(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listModelsParametersToMldev(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromMldev(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateModelParametersToVertex(this.apiClient, params); + path = formatMap('{model}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = updateModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteModelResponseFromVertex(); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteModelResponseFromMldev(); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + async countTokens(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = countTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromVertex(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = countTokensParametersToMldev(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromMldev(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + async computeTokens(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = computeTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:computeTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = computeTokensResponseFromVertex(apiResponse); + const typedResp = new ComputeTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + async generateVideosInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateVideosParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateVideosParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getOperationParametersToMldev(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fetchPredictOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['operationName'], fromOperationName); + } + const fromResourceName = getValueByPath(fromObject, ['resourceName']); + if (fromResourceName != null) { + setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Operations extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async getVideosOperation(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async get(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + async getVideosOperationInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getOperationParametersToVertex(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + const body = getOperationParametersToMldev(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + } + async fetchPredictVideosOperationInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = fetchPredictOperationParametersToVertex(params); + path = formatMap('{resourceName}:fetchPredictOperation', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is not supported in Gemini API.'); + } + return toObject; +} +function audioTranscriptionConfigToMldev() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToMldev(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToMldev(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToMldev(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToMldev(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToMldev()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToMldev()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToMldev(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToMldev(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToMldev(fromProactivity)); + } + return toObject; +} +function liveConnectConstraintsToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function createAuthTokenConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromNewSessionExpireTime = getValueByPath(fromObject, [ + 'newSessionExpireTime', + ]); + if (parentObject !== undefined && fromNewSessionExpireTime != null) { + setValueByPath(parentObject, ['newSessionExpireTime'], fromNewSessionExpireTime); + } + const fromUses = getValueByPath(fromObject, ['uses']); + if (parentObject !== undefined && fromUses != null) { + setValueByPath(parentObject, ['uses'], fromUses); + } + const fromLiveConnectConstraints = getValueByPath(fromObject, [ + 'liveConnectConstraints', + ]); + if (parentObject !== undefined && fromLiveConnectConstraints != null) { + setValueByPath(parentObject, ['bidiGenerateContentSetup'], liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints)); + } + const fromLockAdditionalFields = getValueByPath(fromObject, [ + 'lockAdditionalFields', + ]); + if (parentObject !== undefined && fromLockAdditionalFields != null) { + setValueByPath(parentObject, ['fieldMask'], fromLockAdditionalFields); + } + return toObject; +} +function createAuthTokenParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createAuthTokenConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function authTokenFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns a comma-separated list of field masks from a given object. + * + * @param setup The object to extract field masks from. + * @return A comma-separated list of field masks. + */ +function getFieldMasks(setup) { + const fields = []; + for (const key in setup) { + if (Object.prototype.hasOwnProperty.call(setup, key)) { + const value = setup[key]; + // 2nd layer, recursively get field masks see TODO(b/418290100) + if (typeof value === 'object' && + value != null && + Object.keys(value).length > 0) { + const field = Object.keys(value).map((kk) => `${key}.${kk}`); + fields.push(...field); + } + else { + fields.push(key); // 1st layer + } + } + } + return fields.join(','); +} +/** + * Converts bidiGenerateContentSetup. + * @param requestDict - The request dictionary. + * @param config - The configuration object. + * @return - The modified request dictionary. + */ +function convertBidiSetupToTokenSetup(requestDict, config) { + // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup. + let setupForMaskGeneration = null; + const bidiGenerateContentSetupValue = requestDict['bidiGenerateContentSetup']; + if (typeof bidiGenerateContentSetupValue === 'object' && + bidiGenerateContentSetupValue !== null && + 'setup' in bidiGenerateContentSetupValue) { + // Now we know bidiGenerateContentSetupValue is an object and has a 'setup' + // property. + const innerSetup = bidiGenerateContentSetupValue + .setup; + if (typeof innerSetup === 'object' && innerSetup !== null) { + // Valid inner setup found. + requestDict['bidiGenerateContentSetup'] = innerSetup; + setupForMaskGeneration = innerSetup; + } + else { + // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as + // if bidiGenerateContentSetup is invalid. + delete requestDict['bidiGenerateContentSetup']; + } + } + else if (bidiGenerateContentSetupValue !== undefined) { + // `bidiGenerateContentSetup` exists but not in the expected + // shape {setup: {...}}; treat as invalid. + delete requestDict['bidiGenerateContentSetup']; + } + const preExistingFieldMask = requestDict['fieldMask']; + // Handle mask generation setup. + if (setupForMaskGeneration) { + const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration); + if (Array.isArray(config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + (config === null || config === void 0 ? void 0 : config.lockAdditionalFields.length) === 0) { + // Case 1: lockAdditionalFields is an empty array. Lock only fields from + // bidi setup. + if (generatedMaskFromBidi) { + // Only assign if mask is not empty + requestDict['fieldMask'] = generatedMaskFromBidi; + } + else { + delete requestDict['fieldMask']; // If mask is empty, effectively no + // specific fields locked by bidi + } + } + else if ((config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + config.lockAdditionalFields.length > 0 && + preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // Case 2: Lock fields from bidi setup + additional fields + // (preExistingFieldMask). + const generationConfigFields = [ + 'temperature', + 'topK', + 'topP', + 'maxOutputTokens', + 'responseModalities', + 'seed', + 'speechConfig', + ]; + let mappedFieldsFromPreExisting = []; + if (preExistingFieldMask.length > 0) { + mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => { + if (generationConfigFields.includes(field)) { + return `generationConfig.${field}`; + } + return field; // Keep original field name if not in + // generationConfigFields + }); + } + const finalMaskParts = []; + if (generatedMaskFromBidi) { + finalMaskParts.push(generatedMaskFromBidi); + } + if (mappedFieldsFromPreExisting.length > 0) { + finalMaskParts.push(...mappedFieldsFromPreExisting); + } + if (finalMaskParts.length > 0) { + requestDict['fieldMask'] = finalMaskParts.join(','); + } + else { + // If no fields from bidi and no valid additional fields from + // pre-existing mask. + delete requestDict['fieldMask']; + } + } + else { + // Case 3: "Lock all fields" (meaning, don't send a field_mask, let server + // defaults apply or all are mutable). This is hit if: + // - `config.lockAdditionalFields` is undefined. + // - `config.lockAdditionalFields` is non-empty, BUT + // `preExistingFieldMask` is null, not a string, or an empty string. + delete requestDict['fieldMask']; + } + } + else { + // No valid `bidiGenerateContentSetup` was found or extracted. + // "Lock additional null fields if any". + if (preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // If there's a pre-existing field mask, it's a string, and it's not + // empty, then we should lock all fields. + requestDict['fieldMask'] = preExistingFieldMask.join(','); + } + else { + delete requestDict['fieldMask']; + } + } + return requestDict; +} +class Tokens extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + async create(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('The client.tokens.create method is only supported by the Gemini Developer API.'); + } + else { + const body = createAuthTokenParametersToMldev(this.apiClient, params); + path = formatMap('auth_tokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const transformedBody = convertBidiSetupToTokenSetup(body, params.config); + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(transformedBody), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = authTokenFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listTuningJobsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function tuningExampleToMldev(fromObject) { + const toObject = {}; + const fromTextInput = getValueByPath(fromObject, ['textInput']); + if (fromTextInput != null) { + setValueByPath(toObject, ['textInput'], fromTextInput); + } + const fromOutput = getValueByPath(fromObject, ['output']); + if (fromOutput != null) { + setValueByPath(toObject, ['output'], fromOutput); + } + return toObject; +} +function tuningDatasetToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['vertexDatasetResource']) !== undefined) { + throw new Error('vertexDatasetResource parameter is not supported in Gemini API.'); + } + const fromExamples = getValueByPath(fromObject, ['examples']); + if (fromExamples != null) { + let transformedList = fromExamples; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningExampleToMldev(item); + }); + } + setValueByPath(toObject, ['examples', 'examples'], transformedList); + } + return toObject; +} +function createTuningJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['validationDataset']) !== undefined) { + throw new Error('validationDataset parameter is not supported in Gemini API.'); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromTunedModelDisplayName); + } + if (getValueByPath(fromObject, ['description']) !== undefined) { + throw new Error('description parameter is not supported in Gemini API.'); + } + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (fromLearningRateMultiplier != null) { + setValueByPath(toObject, ['tuningTask', 'hyperparameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + if (getValueByPath(fromObject, ['exportLastCheckpointOnly']) !== + undefined) { + throw new Error('exportLastCheckpointOnly parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['preTunedModelCheckpointId']) !== + undefined) { + throw new Error('preTunedModelCheckpointId parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['adapterSize']) !== undefined) { + throw new Error('adapterSize parameter is not supported in Gemini API.'); + } + const fromBatchSize = getValueByPath(fromObject, ['batchSize']); + if (parentObject !== undefined && fromBatchSize != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'batchSize'], fromBatchSize); + } + const fromLearningRate = getValueByPath(fromObject, ['learningRate']); + if (parentObject !== undefined && fromLearningRate != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'learningRate'], fromLearningRate); + } + return toObject; +} +function createTuningJobParametersPrivateToMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + setValueByPath(toObject, ['tuningTask', 'trainingData'], tuningDatasetToMldev(fromTrainingDataset)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createTuningJobConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listTuningJobsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function tuningDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (parentObject !== undefined && fromGcsUri != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + if (getValueByPath(fromObject, ['examples']) !== undefined) { + throw new Error('examples parameter is not supported in Vertex AI.'); + } + return toObject; +} +function tuningValidationDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['validationDatasetUri'], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + return toObject; +} +function createTuningJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromValidationDataset = getValueByPath(fromObject, [ + 'validationDataset', + ]); + if (parentObject !== undefined && fromValidationDataset != null) { + setValueByPath(parentObject, ['supervisedTuningSpec'], tuningValidationDatasetToVertex(fromValidationDataset, toObject)); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (parentObject !== undefined && fromLearningRateMultiplier != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + const fromExportLastCheckpointOnly = getValueByPath(fromObject, [ + 'exportLastCheckpointOnly', + ]); + if (parentObject !== undefined && fromExportLastCheckpointOnly != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'exportLastCheckpointOnly'], fromExportLastCheckpointOnly); + } + const fromPreTunedModelCheckpointId = getValueByPath(fromObject, [ + 'preTunedModelCheckpointId', + ]); + if (fromPreTunedModelCheckpointId != null) { + setValueByPath(toObject, ['preTunedModel', 'checkpointId'], fromPreTunedModelCheckpointId); + } + const fromAdapterSize = getValueByPath(fromObject, ['adapterSize']); + if (parentObject !== undefined && fromAdapterSize != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'], fromAdapterSize); + } + if (getValueByPath(fromObject, ['batchSize']) !== undefined) { + throw new Error('batchSize parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['learningRate']) !== undefined) { + throw new Error('learningRate parameter is not supported in Vertex AI.'); + } + return toObject; +} +function createTuningJobParametersPrivateToVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + setValueByPath(toObject, ['supervisedTuningSpec', 'trainingDatasetUri'], tuningDatasetToVertex(fromTrainingDataset, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createTuningJobConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function tunedModelFromMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['name']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ['name']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + return toObject; +} +function tuningJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, [ + 'tuningTask', + 'startTime', + ]); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'tuningTask', + 'completeTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['_self']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], tunedModelFromMldev(fromTunedModel)); + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel); + } + const fromExperiment = getValueByPath(fromObject, ['experiment']); + if (fromExperiment != null) { + setValueByPath(toObject, ['experiment'], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (fromOutputUri != null) { + setValueByPath(toObject, ['outputUri'], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject, ['pipelineJob']); + if (fromPipelineJob != null) { + setValueByPath(toObject, ['pipelineJob'], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject, [ + 'serviceAccount', + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ['serviceAccount'], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + return toObject; +} +function listTuningJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ['tunedModels']); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromMldev(item); + }); + } + setValueByPath(toObject, ['tuningJobs'], transformedList); + } + return toObject; +} +function tuningOperationFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + return toObject; +} +function tunedModelCheckpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ['checkpointId']); + if (fromCheckpointId != null) { + setValueByPath(toObject, ['checkpointId'], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ['epoch']); + if (fromEpoch != null) { + setValueByPath(toObject, ['epoch'], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ['step']); + if (fromStep != null) { + setValueByPath(toObject, ['step'], fromStep); + } + const fromEndpoint = getValueByPath(fromObject, ['endpoint']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + return toObject; +} +function tunedModelFromVertex(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ['endpoint']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + const fromCheckpoints = getValueByPath(fromObject, ['checkpoints']); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tunedModelCheckpointFromVertex(item); + }); + } + setValueByPath(toObject, ['checkpoints'], transformedList); + } + return toObject; +} +function tuningJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['tunedModel']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], tunedModelFromVertex(fromTunedModel)); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromSupervisedTuningSpec = getValueByPath(fromObject, [ + 'supervisedTuningSpec', + ]); + if (fromSupervisedTuningSpec != null) { + setValueByPath(toObject, ['supervisedTuningSpec'], fromSupervisedTuningSpec); + } + const fromTuningDataStats = getValueByPath(fromObject, [ + 'tuningDataStats', + ]); + if (fromTuningDataStats != null) { + setValueByPath(toObject, ['tuningDataStats'], fromTuningDataStats); + } + const fromEncryptionSpec = getValueByPath(fromObject, [ + 'encryptionSpec', + ]); + if (fromEncryptionSpec != null) { + setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec); + } + const fromPartnerModelTuningSpec = getValueByPath(fromObject, [ + 'partnerModelTuningSpec', + ]); + if (fromPartnerModelTuningSpec != null) { + setValueByPath(toObject, ['partnerModelTuningSpec'], fromPartnerModelTuningSpec); + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel); + } + const fromExperiment = getValueByPath(fromObject, ['experiment']); + if (fromExperiment != null) { + setValueByPath(toObject, ['experiment'], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (fromOutputUri != null) { + setValueByPath(toObject, ['outputUri'], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject, ['pipelineJob']); + if (fromPipelineJob != null) { + setValueByPath(toObject, ['pipelineJob'], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject, [ + 'serviceAccount', + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ['serviceAccount'], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + return toObject; +} +function listTuningJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ['tuningJobs']); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromVertex(item); + }); + } + setValueByPath(toObject, ['tuningJobs'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Tunings extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.get = async (params) => { + return await this.getInternal(params); + }; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_TUNING_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.tune = async (params) => { + if (this.apiClient.isVertexAI()) { + if (params.baseModel.startsWith('projects/')) { + const preTunedModel = { + tunedModelName: params.baseModel, + }; + const paramsPrivate = Object.assign(Object.assign({}, params), { preTunedModel: preTunedModel }); + paramsPrivate.baseModel = undefined; + return await this.tuneInternal(paramsPrivate); + } + else { + const paramsPrivate = Object.assign({}, params); + return await this.tuneInternal(paramsPrivate); + } + } + else { + const paramsPrivate = Object.assign({}, params); + const operation = await this.tuneMldevInternal(paramsPrivate); + let tunedModelName = ''; + if (operation['metadata'] !== undefined && + operation['metadata']['tunedModel'] !== undefined) { + tunedModelName = operation['metadata']['tunedModel']; + } + else if (operation['name'] !== undefined && + operation['name'].includes('/operations/')) { + tunedModelName = operation['name'].split('/operations/')[0]; + } + const tuningJob = { + name: tunedModelName, + state: JobState.JOB_STATE_QUEUED, + }; + return tuningJob; + } + }; + } + async getInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getTuningJobParametersToVertex(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getTuningJobParametersToMldev(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listTuningJobsParametersToVertex(params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromVertex(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listTuningJobsParametersToMldev(params); + path = formatMap('tunedModels', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromMldev(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async tuneInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createTuningJobParametersPrivateToVertex(params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + async tuneMldevInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createTuningJobParametersPrivateToMldev(params); + path = formatMap('tunedModels', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningOperationFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const GOOGLE_API_KEY_HEADER = 'x-goog-api-key'; +// TODO(b/395122533): We need a secure client side authentication mechanism. +class WebAuth { + constructor(apiKey) { + this.apiKey = apiKey; + } + async addAuthHeaders(headers) { + if (headers.get(GOOGLE_API_KEY_HEADER) !== null) { + return; + } + if (this.apiKey.startsWith('auth_tokens/')) { + throw new Error('Ephemeral tokens are only supported by the live API.'); + } + // Check if API key is empty or null + if (!this.apiKey) { + throw new Error('API key is missing. Please provide a valid API key.'); + } + headers.append(GOOGLE_API_KEY_HEADER, this.apiKey); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const LANGUAGE_LABEL_PREFIX = 'gl-node/'; +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} + * or the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be set, + * when using Vertex AI {@link GoogleGenAIOptions.project} and {@link GoogleGenAIOptions.location} must also be set. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +class GoogleGenAI { + constructor(options) { + var _a; + if (options.apiKey == null) { + throw new Error(`An API Key must be set when running in an unspecified environment.\n + ${crossError().message}`); + } + this.vertexai = (_a = options.vertexai) !== null && _a !== void 0 ? _a : false; + this.apiKey = options.apiKey; + this.apiVersion = options.apiVersion; + const auth = new WebAuth(this.apiKey); + this.apiClient = new ApiClient({ + auth: auth, + apiVersion: this.apiVersion, + apiKey: this.apiKey, + vertexai: this.vertexai, + httpOptions: options.httpOptions, + userAgentExtra: LANGUAGE_LABEL_PREFIX + 'cross', + uploader: new CrossUploader(), + downloader: new CrossDownloader(), + }); + this.models = new Models(this.apiClient); + this.live = new Live(this.apiClient, auth, new CrossWebSocketFactory()); + this.chats = new Chats(this.models, this.apiClient); + this.batches = new Batches(this.apiClient); + this.caches = new Caches(this.apiClient); + this.files = new Files(this.apiClient); + this.operations = new Operations(this.apiClient); + this.authTokens = new Tokens(this.apiClient); + this.tunings = new Tunings(this.apiClient); + } +} + +export { ActivityHandling, AdapterSize, ApiError, ApiSpec, AuthType, Batches, Behavior, BlockedReason, Caches, Chat, Chats, ComputeTokensResponse, ControlReferenceImage, ControlReferenceType, CountTokensResponse, CreateFileResponse, DeleteCachedContentResponse, DeleteFileResponse, DeleteModelResponse, DynamicRetrievalConfigMode, EditImageResponse, EditMode, EmbedContentResponse, EndSensitivity, Environment, FeatureSelectionPreference, FileSource, FileState, Files, FinishReason, FunctionCallingConfigMode, FunctionResponse, FunctionResponseScheduling, GenerateContentResponse, GenerateContentResponsePromptFeedback, GenerateContentResponseUsageMetadata, GenerateImagesResponse, GenerateVideosOperation, GenerateVideosResponse, GoogleGenAI, HarmBlockMethod, HarmBlockThreshold, HarmCategory, HarmProbability, HarmSeverity, HttpResponse, ImagePromptLanguage, InlinedResponse, JobState, Language, ListBatchJobsResponse, ListCachedContentsResponse, ListFilesResponse, ListModelsResponse, ListTuningJobsResponse, Live, LiveClientToolResponse, LiveMusicPlaybackControl, LiveMusicServerMessage, LiveSendToolResponseParameters, LiveServerMessage, MaskReferenceImage, MaskReferenceMode, MediaModality, MediaResolution, Modality, Mode, Models, MusicGenerationMode, Operations, Outcome, PagedItem, Pager, PersonGeneration, RawReferenceImage, RecontextImageResponse, ReplayResponse, SafetyFilterLevel, Scale, SegmentImageResponse, SegmentMode, Session, StartSensitivity, StyleReferenceImage, SubjectReferenceImage, SubjectReferenceType, Tokens, TrafficType, TuningMode, TurnCoverage, Type, UpscaleImageResponse, UrlRetrievalStatus, VideoCompressionQuality, createModelContent, createPartFromBase64, createPartFromCodeExecutionResult, createPartFromExecutableCode, createPartFromFunctionCall, createPartFromFunctionResponse, createPartFromText, createPartFromUri, createUserContent, mcpToTool, setDefaultBaseUrls }; +//# sourceMappingURL=index.mjs.map diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/index.mjs.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..f07876cd79cb6ee8dc34830364fed432e01ae276 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sources":["../src/_base_url.ts","../src/_common.ts","../src/_base_transformers.ts","../src/types.ts","../src/_transformers.ts","../src/converters/_batches_converters.ts","../src/pagers.ts","../src/batches.ts","../src/converters/_caches_converters.ts","../src/caches.ts","../src/chats.ts","../src/errors.ts","../src/_api_client.ts","../src/cross/_cross_error.ts","../src/cross/_cross_downloader.ts","../src/cross/_cross_uploader.ts","../src/cross/_cross_websocket.ts","../src/converters/_files_converters.ts","../src/files.ts","../src/converters/_live_converters.ts","../src/converters/_models_converters.ts","../src/mcp/_mcp.ts","../src/music.ts","../src/live.ts","../src/_afc.ts","../src/models.ts","../src/converters/_operations_converters.ts","../src/operations.ts","../src/converters/_tokens_converters.ts","../src/tokens.ts","../src/converters/_tunings_converters.ts","../src/tunings.ts","../src/web/_web_auth.ts","../src/client.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {HttpOptions} from './types.js';\n\nlet _defaultBaseGeminiUrl: string | undefined = undefined;\nlet _defaultBaseVertexUrl: string | undefined = undefined;\n\n/**\n * Parameters for setting the base URLs for the Gemini API and Vertex AI API.\n */\nexport interface BaseUrlParameters {\n geminiUrl?: string;\n vertexUrl?: string;\n}\n\n/**\n * Overrides the base URLs for the Gemini API and Vertex AI API.\n *\n * @remarks This function should be called before initializing the SDK. If the\n * base URLs are set after initializing the SDK, the base URLs will not be\n * updated. Base URLs provided in the HttpOptions will also take precedence over\n * URLs set here.\n *\n * @example\n * ```ts\n * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai';\n * // Override the base URL for the Gemini API.\n * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'});\n *\n * // Override the base URL for the Vertex AI API.\n * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'});\n *\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n */\nexport function setDefaultBaseUrls(baseUrlParams: BaseUrlParameters) {\n _defaultBaseGeminiUrl = baseUrlParams.geminiUrl;\n _defaultBaseVertexUrl = baseUrlParams.vertexUrl;\n}\n\n/**\n * Returns the default base URLs for the Gemini API and Vertex AI API.\n */\nexport function getDefaultBaseUrls(): BaseUrlParameters {\n return {\n geminiUrl: _defaultBaseGeminiUrl,\n vertexUrl: _defaultBaseVertexUrl,\n };\n}\n\n/**\n * Returns the default base URL based on the following priority:\n * 1. Base URLs set via HttpOptions.\n * 2. Base URLs set via the latest call to setDefaultBaseUrls.\n * 3. Base URLs set via environment variables.\n */\nexport function getBaseUrl(\n httpOptions: HttpOptions | undefined,\n vertexai: boolean | undefined,\n vertexBaseUrlFromEnv: string | undefined,\n geminiBaseUrlFromEnv: string | undefined,\n): string | undefined {\n if (!httpOptions?.baseUrl) {\n const defaultBaseUrls = getDefaultBaseUrls();\n if (vertexai) {\n return defaultBaseUrls.vertexUrl ?? vertexBaseUrlFromEnv;\n } else {\n return defaultBaseUrls.geminiUrl ?? geminiBaseUrlFromEnv;\n }\n }\n\n return httpOptions.baseUrl;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport class BaseModule {}\n\nexport function formatMap(\n templateString: string,\n valueMap: Record,\n): string {\n // Use a regular expression to find all placeholders in the template string\n const regex = /\\{([^}]+)\\}/g;\n\n // Replace each placeholder with its corresponding value from the valueMap\n return templateString.replace(regex, (match, key) => {\n if (Object.prototype.hasOwnProperty.call(valueMap, key)) {\n const value = valueMap[key];\n // Convert the value to a string if it's not a string already\n return value !== undefined && value !== null ? String(value) : '';\n } else {\n // Handle missing keys\n throw new Error(`Key '${key}' not found in valueMap.`);\n }\n });\n}\n\nexport function setValueByPath(\n data: Record,\n keys: string[],\n value: unknown,\n): void {\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (!(keyName in data)) {\n if (Array.isArray(value)) {\n data[keyName] = Array.from({length: value.length}, () => ({}));\n } else {\n throw new Error(`Value must be a list given an array path ${key}`);\n }\n }\n\n if (Array.isArray(data[keyName])) {\n const arrayData = data[keyName] as Array;\n\n if (Array.isArray(value)) {\n for (let j = 0; j < arrayData.length; j++) {\n const entry = arrayData[j] as Record;\n setValueByPath(entry, keys.slice(i + 1), value[j]);\n }\n } else {\n for (const d of arrayData) {\n setValueByPath(\n d as Record,\n keys.slice(i + 1),\n value,\n );\n }\n }\n }\n return;\n } else if (key.endsWith('[0]')) {\n const keyName = key.slice(0, -3);\n if (!(keyName in data)) {\n data[keyName] = [{}];\n }\n const arrayData = (data as Record)[keyName];\n setValueByPath(\n (arrayData as Array>)[0],\n keys.slice(i + 1),\n value,\n );\n return;\n }\n\n if (!data[key] || typeof data[key] !== 'object') {\n data[key] = {};\n }\n\n data = data[key] as Record;\n }\n\n const keyToSet = keys[keys.length - 1];\n const existingData = data[keyToSet];\n\n if (existingData !== undefined) {\n if (\n !value ||\n (typeof value === 'object' && Object.keys(value).length === 0)\n ) {\n return;\n }\n\n if (value === existingData) {\n return;\n }\n\n if (\n typeof existingData === 'object' &&\n typeof value === 'object' &&\n existingData !== null &&\n value !== null\n ) {\n Object.assign(existingData, value);\n } else {\n throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`);\n }\n } else {\n data[keyToSet] = value;\n }\n}\n\nexport function getValueByPath(data: unknown, keys: string[]): unknown {\n try {\n if (keys.length === 1 && keys[0] === '_self') {\n return data;\n }\n\n for (let i = 0; i < keys.length; i++) {\n if (typeof data !== 'object' || data === null) {\n return undefined;\n }\n\n const key = keys[i];\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (keyName in data) {\n const arrayData = (data as Record)[keyName];\n if (!Array.isArray(arrayData)) {\n return undefined;\n }\n return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1)));\n } else {\n return undefined;\n }\n } else {\n data = (data as Record)[key];\n }\n }\n\n return data;\n } catch (error) {\n if (error instanceof TypeError) {\n return undefined;\n }\n throw error;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function tBytes(fromBytes: string | unknown): string {\n if (typeof fromBytes !== 'string') {\n throw new Error('fromImageBytes must be a string');\n }\n // TODO(b/389133914): Remove dummy bytes converter.\n return fromBytes;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {tBytes} from './_base_transformers.js';\nimport type {ReferenceImageAPIInternal} from './_internal_types.js';\n\n/** Required. Outcome of the code execution. */\nexport enum Outcome {\n /**\n * Unspecified status. This value should not be used.\n */\n OUTCOME_UNSPECIFIED = 'OUTCOME_UNSPECIFIED',\n /**\n * Code execution completed successfully.\n */\n OUTCOME_OK = 'OUTCOME_OK',\n /**\n * Code execution finished but with a failure. `stderr` should contain the reason.\n */\n OUTCOME_FAILED = 'OUTCOME_FAILED',\n /**\n * Code execution ran for too long, and was cancelled. There may or may not be a partial output present.\n */\n OUTCOME_DEADLINE_EXCEEDED = 'OUTCOME_DEADLINE_EXCEEDED',\n}\n\n/** Required. Programming language of the `code`. */\nexport enum Language {\n /**\n * Unspecified language. This value should not be used.\n */\n LANGUAGE_UNSPECIFIED = 'LANGUAGE_UNSPECIFIED',\n /**\n * Python >= 3.10, with numpy and simpy available.\n */\n PYTHON = 'PYTHON',\n}\n\n/** Optional. The type of the data. */\nexport enum Type {\n /**\n * Not specified, should not be used.\n */\n TYPE_UNSPECIFIED = 'TYPE_UNSPECIFIED',\n /**\n * OpenAPI string type\n */\n STRING = 'STRING',\n /**\n * OpenAPI number type\n */\n NUMBER = 'NUMBER',\n /**\n * OpenAPI integer type\n */\n INTEGER = 'INTEGER',\n /**\n * OpenAPI boolean type\n */\n BOOLEAN = 'BOOLEAN',\n /**\n * OpenAPI array type\n */\n ARRAY = 'ARRAY',\n /**\n * OpenAPI object type\n */\n OBJECT = 'OBJECT',\n /**\n * Null type\n */\n NULL = 'NULL',\n}\n\n/** Required. Harm category. */\nexport enum HarmCategory {\n /**\n * The harm category is unspecified.\n */\n HARM_CATEGORY_UNSPECIFIED = 'HARM_CATEGORY_UNSPECIFIED',\n /**\n * The harm category is hate speech.\n */\n HARM_CATEGORY_HATE_SPEECH = 'HARM_CATEGORY_HATE_SPEECH',\n /**\n * The harm category is dangerous content.\n */\n HARM_CATEGORY_DANGEROUS_CONTENT = 'HARM_CATEGORY_DANGEROUS_CONTENT',\n /**\n * The harm category is harassment.\n */\n HARM_CATEGORY_HARASSMENT = 'HARM_CATEGORY_HARASSMENT',\n /**\n * The harm category is sexually explicit content.\n */\n HARM_CATEGORY_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_SEXUALLY_EXPLICIT',\n /**\n * Deprecated: Election filter is not longer supported. The harm category is civic integrity.\n */\n HARM_CATEGORY_CIVIC_INTEGRITY = 'HARM_CATEGORY_CIVIC_INTEGRITY',\n /**\n * The harm category is image hate.\n */\n HARM_CATEGORY_IMAGE_HATE = 'HARM_CATEGORY_IMAGE_HATE',\n /**\n * The harm category is image dangerous content.\n */\n HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT = 'HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT',\n /**\n * The harm category is image harassment.\n */\n HARM_CATEGORY_IMAGE_HARASSMENT = 'HARM_CATEGORY_IMAGE_HARASSMENT',\n /**\n * The harm category is image sexually explicit content.\n */\n HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT',\n}\n\n/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */\nexport enum HarmBlockMethod {\n /**\n * The harm block method is unspecified.\n */\n HARM_BLOCK_METHOD_UNSPECIFIED = 'HARM_BLOCK_METHOD_UNSPECIFIED',\n /**\n * The harm block method uses both probability and severity scores.\n */\n SEVERITY = 'SEVERITY',\n /**\n * The harm block method uses the probability score.\n */\n PROBABILITY = 'PROBABILITY',\n}\n\n/** Required. The harm block threshold. */\nexport enum HarmBlockThreshold {\n /**\n * Unspecified harm block threshold.\n */\n HARM_BLOCK_THRESHOLD_UNSPECIFIED = 'HARM_BLOCK_THRESHOLD_UNSPECIFIED',\n /**\n * Block low threshold and above (i.e. block more).\n */\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n /**\n * Block medium threshold and above.\n */\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n /**\n * Block only high threshold (i.e. block less).\n */\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n /**\n * Block none.\n */\n BLOCK_NONE = 'BLOCK_NONE',\n /**\n * Turn off the safety filter.\n */\n OFF = 'OFF',\n}\n\n/** The mode of the predictor to be used in dynamic retrieval. */\nexport enum Mode {\n /**\n * Always trigger retrieval.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Run retrieval only when system decides it is necessary.\n */\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\n/** Type of auth scheme. */\nexport enum AuthType {\n AUTH_TYPE_UNSPECIFIED = 'AUTH_TYPE_UNSPECIFIED',\n /**\n * No Auth.\n */\n NO_AUTH = 'NO_AUTH',\n /**\n * API Key Auth.\n */\n API_KEY_AUTH = 'API_KEY_AUTH',\n /**\n * HTTP Basic Auth.\n */\n HTTP_BASIC_AUTH = 'HTTP_BASIC_AUTH',\n /**\n * Google Service Account Auth.\n */\n GOOGLE_SERVICE_ACCOUNT_AUTH = 'GOOGLE_SERVICE_ACCOUNT_AUTH',\n /**\n * OAuth auth.\n */\n OAUTH = 'OAUTH',\n /**\n * OpenID Connect (OIDC) Auth.\n */\n OIDC_AUTH = 'OIDC_AUTH',\n}\n\n/** The API spec that the external API implements. */\nexport enum ApiSpec {\n /**\n * Unspecified API spec. This value should not be used.\n */\n API_SPEC_UNSPECIFIED = 'API_SPEC_UNSPECIFIED',\n /**\n * Simple search API spec.\n */\n SIMPLE_SEARCH = 'SIMPLE_SEARCH',\n /**\n * Elastic search API spec.\n */\n ELASTIC_SEARCH = 'ELASTIC_SEARCH',\n}\n\n/** Status of the url retrieval. */\nexport enum UrlRetrievalStatus {\n /**\n * Default value. This value is unused\n */\n URL_RETRIEVAL_STATUS_UNSPECIFIED = 'URL_RETRIEVAL_STATUS_UNSPECIFIED',\n /**\n * Url retrieval is successful.\n */\n URL_RETRIEVAL_STATUS_SUCCESS = 'URL_RETRIEVAL_STATUS_SUCCESS',\n /**\n * Url retrieval is failed due to error.\n */\n URL_RETRIEVAL_STATUS_ERROR = 'URL_RETRIEVAL_STATUS_ERROR',\n /**\n * Url retrieval is failed because the content is behind paywall.\n */\n URL_RETRIEVAL_STATUS_PAYWALL = 'URL_RETRIEVAL_STATUS_PAYWALL',\n /**\n * Url retrieval is failed because the content is unsafe.\n */\n URL_RETRIEVAL_STATUS_UNSAFE = 'URL_RETRIEVAL_STATUS_UNSAFE',\n}\n\n/** Output only. The reason why the model stopped generating tokens.\n\n If empty, the model has not stopped generating the tokens.\n */\nexport enum FinishReason {\n /**\n * The finish reason is unspecified.\n */\n FINISH_REASON_UNSPECIFIED = 'FINISH_REASON_UNSPECIFIED',\n /**\n * Token generation reached a natural stopping point or a configured stop sequence.\n */\n STOP = 'STOP',\n /**\n * Token generation reached the configured maximum output tokens.\n */\n MAX_TOKENS = 'MAX_TOKENS',\n /**\n * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output.\n */\n SAFETY = 'SAFETY',\n /**\n * The token generation stopped because of potential recitation.\n */\n RECITATION = 'RECITATION',\n /**\n * The token generation stopped because of using an unsupported language.\n */\n LANGUAGE = 'LANGUAGE',\n /**\n * All other reasons that stopped the token generation.\n */\n OTHER = 'OTHER',\n /**\n * Token generation stopped because the content contains forbidden terms.\n */\n BLOCKLIST = 'BLOCKLIST',\n /**\n * Token generation stopped for potentially containing prohibited content.\n */\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n /**\n * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII).\n */\n SPII = 'SPII',\n /**\n * The function call generated by the model is invalid.\n */\n MALFORMED_FUNCTION_CALL = 'MALFORMED_FUNCTION_CALL',\n /**\n * Token generation stopped because generated images have safety violations.\n */\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n /**\n * The tool call generated by the model is invalid.\n */\n UNEXPECTED_TOOL_CALL = 'UNEXPECTED_TOOL_CALL',\n}\n\n/** Output only. Harm probability levels in the content. */\nexport enum HarmProbability {\n /**\n * Harm probability unspecified.\n */\n HARM_PROBABILITY_UNSPECIFIED = 'HARM_PROBABILITY_UNSPECIFIED',\n /**\n * Negligible level of harm.\n */\n NEGLIGIBLE = 'NEGLIGIBLE',\n /**\n * Low level of harm.\n */\n LOW = 'LOW',\n /**\n * Medium level of harm.\n */\n MEDIUM = 'MEDIUM',\n /**\n * High level of harm.\n */\n HIGH = 'HIGH',\n}\n\n/** Output only. Harm severity levels in the content. */\nexport enum HarmSeverity {\n /**\n * Harm severity unspecified.\n */\n HARM_SEVERITY_UNSPECIFIED = 'HARM_SEVERITY_UNSPECIFIED',\n /**\n * Negligible level of harm severity.\n */\n HARM_SEVERITY_NEGLIGIBLE = 'HARM_SEVERITY_NEGLIGIBLE',\n /**\n * Low level of harm severity.\n */\n HARM_SEVERITY_LOW = 'HARM_SEVERITY_LOW',\n /**\n * Medium level of harm severity.\n */\n HARM_SEVERITY_MEDIUM = 'HARM_SEVERITY_MEDIUM',\n /**\n * High level of harm severity.\n */\n HARM_SEVERITY_HIGH = 'HARM_SEVERITY_HIGH',\n}\n\n/** Output only. Blocked reason. */\nexport enum BlockedReason {\n /**\n * Unspecified blocked reason.\n */\n BLOCKED_REASON_UNSPECIFIED = 'BLOCKED_REASON_UNSPECIFIED',\n /**\n * Candidates blocked due to safety.\n */\n SAFETY = 'SAFETY',\n /**\n * Candidates blocked due to other reason.\n */\n OTHER = 'OTHER',\n /**\n * Candidates blocked due to the terms which are included from the terminology blocklist.\n */\n BLOCKLIST = 'BLOCKLIST',\n /**\n * Candidates blocked due to prohibited content.\n */\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n /**\n * Candidates blocked due to unsafe image generation content.\n */\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n}\n\n/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */\nexport enum TrafficType {\n /**\n * Unspecified request traffic type.\n */\n TRAFFIC_TYPE_UNSPECIFIED = 'TRAFFIC_TYPE_UNSPECIFIED',\n /**\n * Type for Pay-As-You-Go traffic.\n */\n ON_DEMAND = 'ON_DEMAND',\n /**\n * Type for Provisioned Throughput traffic.\n */\n PROVISIONED_THROUGHPUT = 'PROVISIONED_THROUGHPUT',\n}\n\n/** Server content modalities. */\nexport enum Modality {\n /**\n * The modality is unspecified.\n */\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n /**\n * Indicates the model should return text\n */\n TEXT = 'TEXT',\n /**\n * Indicates the model should return images.\n */\n IMAGE = 'IMAGE',\n /**\n * Indicates the model should return audio.\n */\n AUDIO = 'AUDIO',\n}\n\n/** The media resolution to use. */\nexport enum MediaResolution {\n /**\n * Media resolution has not been set\n */\n MEDIA_RESOLUTION_UNSPECIFIED = 'MEDIA_RESOLUTION_UNSPECIFIED',\n /**\n * Media resolution set to low (64 tokens).\n */\n MEDIA_RESOLUTION_LOW = 'MEDIA_RESOLUTION_LOW',\n /**\n * Media resolution set to medium (256 tokens).\n */\n MEDIA_RESOLUTION_MEDIUM = 'MEDIA_RESOLUTION_MEDIUM',\n /**\n * Media resolution set to high (zoomed reframing with 256 tokens).\n */\n MEDIA_RESOLUTION_HIGH = 'MEDIA_RESOLUTION_HIGH',\n}\n\n/** Job state. */\nexport enum JobState {\n /**\n * The job state is unspecified.\n */\n JOB_STATE_UNSPECIFIED = 'JOB_STATE_UNSPECIFIED',\n /**\n * The job has been just created or resumed and processing has not yet begun.\n */\n JOB_STATE_QUEUED = 'JOB_STATE_QUEUED',\n /**\n * The service is preparing to run the job.\n */\n JOB_STATE_PENDING = 'JOB_STATE_PENDING',\n /**\n * The job is in progress.\n */\n JOB_STATE_RUNNING = 'JOB_STATE_RUNNING',\n /**\n * The job completed successfully.\n */\n JOB_STATE_SUCCEEDED = 'JOB_STATE_SUCCEEDED',\n /**\n * The job failed.\n */\n JOB_STATE_FAILED = 'JOB_STATE_FAILED',\n /**\n * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`.\n */\n JOB_STATE_CANCELLING = 'JOB_STATE_CANCELLING',\n /**\n * The job has been cancelled.\n */\n JOB_STATE_CANCELLED = 'JOB_STATE_CANCELLED',\n /**\n * The job has been stopped, and can be resumed.\n */\n JOB_STATE_PAUSED = 'JOB_STATE_PAUSED',\n /**\n * The job has expired.\n */\n JOB_STATE_EXPIRED = 'JOB_STATE_EXPIRED',\n /**\n * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state.\n */\n JOB_STATE_UPDATING = 'JOB_STATE_UPDATING',\n /**\n * The job is partially succeeded, some results may be missing due to errors.\n */\n JOB_STATE_PARTIALLY_SUCCEEDED = 'JOB_STATE_PARTIALLY_SUCCEEDED',\n}\n\n/** Tuning mode. */\nexport enum TuningMode {\n /**\n * Tuning mode is unspecified.\n */\n TUNING_MODE_UNSPECIFIED = 'TUNING_MODE_UNSPECIFIED',\n /**\n * Full fine-tuning mode.\n */\n TUNING_MODE_FULL = 'TUNING_MODE_FULL',\n /**\n * PEFT adapter tuning mode.\n */\n TUNING_MODE_PEFT_ADAPTER = 'TUNING_MODE_PEFT_ADAPTER',\n}\n\n/** Optional. Adapter size for tuning. */\nexport enum AdapterSize {\n /**\n * Adapter size is unspecified.\n */\n ADAPTER_SIZE_UNSPECIFIED = 'ADAPTER_SIZE_UNSPECIFIED',\n /**\n * Adapter size 1.\n */\n ADAPTER_SIZE_ONE = 'ADAPTER_SIZE_ONE',\n /**\n * Adapter size 2.\n */\n ADAPTER_SIZE_TWO = 'ADAPTER_SIZE_TWO',\n /**\n * Adapter size 4.\n */\n ADAPTER_SIZE_FOUR = 'ADAPTER_SIZE_FOUR',\n /**\n * Adapter size 8.\n */\n ADAPTER_SIZE_EIGHT = 'ADAPTER_SIZE_EIGHT',\n /**\n * Adapter size 16.\n */\n ADAPTER_SIZE_SIXTEEN = 'ADAPTER_SIZE_SIXTEEN',\n /**\n * Adapter size 32.\n */\n ADAPTER_SIZE_THIRTY_TWO = 'ADAPTER_SIZE_THIRTY_TWO',\n}\n\n/** Options for feature selection preference. */\nexport enum FeatureSelectionPreference {\n FEATURE_SELECTION_PREFERENCE_UNSPECIFIED = 'FEATURE_SELECTION_PREFERENCE_UNSPECIFIED',\n PRIORITIZE_QUALITY = 'PRIORITIZE_QUALITY',\n BALANCED = 'BALANCED',\n PRIORITIZE_COST = 'PRIORITIZE_COST',\n}\n\n/** Defines the function behavior. Defaults to `BLOCKING`. */\nexport enum Behavior {\n /**\n * This value is unused.\n */\n UNSPECIFIED = 'UNSPECIFIED',\n /**\n * If set, the system will wait to receive the function response before continuing the conversation.\n */\n BLOCKING = 'BLOCKING',\n /**\n * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model.\n */\n NON_BLOCKING = 'NON_BLOCKING',\n}\n\n/** Config for the dynamic retrieval config mode. */\nexport enum DynamicRetrievalConfigMode {\n /**\n * Always trigger retrieval.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Run retrieval only when system decides it is necessary.\n */\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\n/** The environment being operated. */\nexport enum Environment {\n /**\n * Defaults to browser.\n */\n ENVIRONMENT_UNSPECIFIED = 'ENVIRONMENT_UNSPECIFIED',\n /**\n * Operates in a web browser.\n */\n ENVIRONMENT_BROWSER = 'ENVIRONMENT_BROWSER',\n}\n\n/** Config for the function calling config mode. */\nexport enum FunctionCallingConfigMode {\n /**\n * The function calling config mode is unspecified. Should not be used.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Default model behavior, model decides to predict either function calls or natural language response.\n */\n AUTO = 'AUTO',\n /**\n * Model is constrained to always predicting function calls only. If \"allowed_function_names\" are set, the predicted function calls will be limited to any one of \"allowed_function_names\", else the predicted function calls will be any one of the provided \"function_declarations\".\n */\n ANY = 'ANY',\n /**\n * Model will not predict any function calls. Model behavior is same as when not passing any function declarations.\n */\n NONE = 'NONE',\n}\n\n/** Enum that controls the safety filter level for objectionable content. */\nexport enum SafetyFilterLevel {\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n BLOCK_NONE = 'BLOCK_NONE',\n}\n\n/** Enum that controls the generation of people. */\nexport enum PersonGeneration {\n /**\n * Block generation of images of people.\n */\n DONT_ALLOW = 'DONT_ALLOW',\n /**\n * Generate images of adults, but not children.\n */\n ALLOW_ADULT = 'ALLOW_ADULT',\n /**\n * Generate images that include adults and children.\n */\n ALLOW_ALL = 'ALLOW_ALL',\n}\n\n/** Enum that specifies the language of the text in the prompt. */\nexport enum ImagePromptLanguage {\n /**\n * Auto-detect the language.\n */\n auto = 'auto',\n /**\n * English\n */\n en = 'en',\n /**\n * Japanese\n */\n ja = 'ja',\n /**\n * Korean\n */\n ko = 'ko',\n /**\n * Hindi\n */\n hi = 'hi',\n /**\n * Chinese\n */\n zh = 'zh',\n /**\n * Portuguese\n */\n pt = 'pt',\n /**\n * Spanish\n */\n es = 'es',\n}\n\n/** Enum representing the mask mode of a mask reference image. */\nexport enum MaskReferenceMode {\n MASK_MODE_DEFAULT = 'MASK_MODE_DEFAULT',\n MASK_MODE_USER_PROVIDED = 'MASK_MODE_USER_PROVIDED',\n MASK_MODE_BACKGROUND = 'MASK_MODE_BACKGROUND',\n MASK_MODE_FOREGROUND = 'MASK_MODE_FOREGROUND',\n MASK_MODE_SEMANTIC = 'MASK_MODE_SEMANTIC',\n}\n\n/** Enum representing the control type of a control reference image. */\nexport enum ControlReferenceType {\n CONTROL_TYPE_DEFAULT = 'CONTROL_TYPE_DEFAULT',\n CONTROL_TYPE_CANNY = 'CONTROL_TYPE_CANNY',\n CONTROL_TYPE_SCRIBBLE = 'CONTROL_TYPE_SCRIBBLE',\n CONTROL_TYPE_FACE_MESH = 'CONTROL_TYPE_FACE_MESH',\n}\n\n/** Enum representing the subject type of a subject reference image. */\nexport enum SubjectReferenceType {\n SUBJECT_TYPE_DEFAULT = 'SUBJECT_TYPE_DEFAULT',\n SUBJECT_TYPE_PERSON = 'SUBJECT_TYPE_PERSON',\n SUBJECT_TYPE_ANIMAL = 'SUBJECT_TYPE_ANIMAL',\n SUBJECT_TYPE_PRODUCT = 'SUBJECT_TYPE_PRODUCT',\n}\n\n/** Enum representing the Imagen 3 Edit mode. */\nexport enum EditMode {\n EDIT_MODE_DEFAULT = 'EDIT_MODE_DEFAULT',\n EDIT_MODE_INPAINT_REMOVAL = 'EDIT_MODE_INPAINT_REMOVAL',\n EDIT_MODE_INPAINT_INSERTION = 'EDIT_MODE_INPAINT_INSERTION',\n EDIT_MODE_OUTPAINT = 'EDIT_MODE_OUTPAINT',\n EDIT_MODE_CONTROLLED_EDITING = 'EDIT_MODE_CONTROLLED_EDITING',\n EDIT_MODE_STYLE = 'EDIT_MODE_STYLE',\n EDIT_MODE_BGSWAP = 'EDIT_MODE_BGSWAP',\n EDIT_MODE_PRODUCT_IMAGE = 'EDIT_MODE_PRODUCT_IMAGE',\n}\n\n/** Enum that represents the segmentation mode. */\nexport enum SegmentMode {\n FOREGROUND = 'FOREGROUND',\n BACKGROUND = 'BACKGROUND',\n PROMPT = 'PROMPT',\n SEMANTIC = 'SEMANTIC',\n INTERACTIVE = 'INTERACTIVE',\n}\n\n/** Enum that controls the compression quality of the generated videos. */\nexport enum VideoCompressionQuality {\n /**\n * Optimized video compression quality. This will produce videos\n with a compressed, smaller file size.\n */\n OPTIMIZED = 'OPTIMIZED',\n /**\n * Lossless video compression quality. This will produce videos\n with a larger file size.\n */\n LOSSLESS = 'LOSSLESS',\n}\n\n/** State for the lifecycle of a File. */\nexport enum FileState {\n STATE_UNSPECIFIED = 'STATE_UNSPECIFIED',\n PROCESSING = 'PROCESSING',\n ACTIVE = 'ACTIVE',\n FAILED = 'FAILED',\n}\n\n/** Source of the File. */\nexport enum FileSource {\n SOURCE_UNSPECIFIED = 'SOURCE_UNSPECIFIED',\n UPLOADED = 'UPLOADED',\n GENERATED = 'GENERATED',\n}\n\n/** Server content modalities. */\nexport enum MediaModality {\n /**\n * The modality is unspecified.\n */\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n /**\n * Plain text.\n */\n TEXT = 'TEXT',\n /**\n * Images.\n */\n IMAGE = 'IMAGE',\n /**\n * Video.\n */\n VIDEO = 'VIDEO',\n /**\n * Audio.\n */\n AUDIO = 'AUDIO',\n /**\n * Document, e.g. PDF.\n */\n DOCUMENT = 'DOCUMENT',\n}\n\n/** Start of speech sensitivity. */\nexport enum StartSensitivity {\n /**\n * The default is START_SENSITIVITY_LOW.\n */\n START_SENSITIVITY_UNSPECIFIED = 'START_SENSITIVITY_UNSPECIFIED',\n /**\n * Automatic detection will detect the start of speech more often.\n */\n START_SENSITIVITY_HIGH = 'START_SENSITIVITY_HIGH',\n /**\n * Automatic detection will detect the start of speech less often.\n */\n START_SENSITIVITY_LOW = 'START_SENSITIVITY_LOW',\n}\n\n/** End of speech sensitivity. */\nexport enum EndSensitivity {\n /**\n * The default is END_SENSITIVITY_LOW.\n */\n END_SENSITIVITY_UNSPECIFIED = 'END_SENSITIVITY_UNSPECIFIED',\n /**\n * Automatic detection ends speech more often.\n */\n END_SENSITIVITY_HIGH = 'END_SENSITIVITY_HIGH',\n /**\n * Automatic detection ends speech less often.\n */\n END_SENSITIVITY_LOW = 'END_SENSITIVITY_LOW',\n}\n\n/** The different ways of handling user activity. */\nexport enum ActivityHandling {\n /**\n * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`.\n */\n ACTIVITY_HANDLING_UNSPECIFIED = 'ACTIVITY_HANDLING_UNSPECIFIED',\n /**\n * If true, start of activity will interrupt the model's response (also called \"barge in\"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior.\n */\n START_OF_ACTIVITY_INTERRUPTS = 'START_OF_ACTIVITY_INTERRUPTS',\n /**\n * The model's response will not be interrupted.\n */\n NO_INTERRUPTION = 'NO_INTERRUPTION',\n}\n\n/** Options about which input is included in the user's turn. */\nexport enum TurnCoverage {\n /**\n * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`.\n */\n TURN_COVERAGE_UNSPECIFIED = 'TURN_COVERAGE_UNSPECIFIED',\n /**\n * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior.\n */\n TURN_INCLUDES_ONLY_ACTIVITY = 'TURN_INCLUDES_ONLY_ACTIVITY',\n /**\n * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream).\n */\n TURN_INCLUDES_ALL_INPUT = 'TURN_INCLUDES_ALL_INPUT',\n}\n\n/** Specifies how the response should be scheduled in the conversation. */\nexport enum FunctionResponseScheduling {\n /**\n * This value is unused.\n */\n SCHEDULING_UNSPECIFIED = 'SCHEDULING_UNSPECIFIED',\n /**\n * Only add the result to the conversation context, do not interrupt or trigger generation.\n */\n SILENT = 'SILENT',\n /**\n * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation.\n */\n WHEN_IDLE = 'WHEN_IDLE',\n /**\n * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output.\n */\n INTERRUPT = 'INTERRUPT',\n}\n\n/** Scale of the generated music. */\nexport enum Scale {\n /**\n * Default value. This value is unused.\n */\n SCALE_UNSPECIFIED = 'SCALE_UNSPECIFIED',\n /**\n * C major or A minor.\n */\n C_MAJOR_A_MINOR = 'C_MAJOR_A_MINOR',\n /**\n * Db major or Bb minor.\n */\n D_FLAT_MAJOR_B_FLAT_MINOR = 'D_FLAT_MAJOR_B_FLAT_MINOR',\n /**\n * D major or B minor.\n */\n D_MAJOR_B_MINOR = 'D_MAJOR_B_MINOR',\n /**\n * Eb major or C minor\n */\n E_FLAT_MAJOR_C_MINOR = 'E_FLAT_MAJOR_C_MINOR',\n /**\n * E major or Db minor.\n */\n E_MAJOR_D_FLAT_MINOR = 'E_MAJOR_D_FLAT_MINOR',\n /**\n * F major or D minor.\n */\n F_MAJOR_D_MINOR = 'F_MAJOR_D_MINOR',\n /**\n * Gb major or Eb minor.\n */\n G_FLAT_MAJOR_E_FLAT_MINOR = 'G_FLAT_MAJOR_E_FLAT_MINOR',\n /**\n * G major or E minor.\n */\n G_MAJOR_E_MINOR = 'G_MAJOR_E_MINOR',\n /**\n * Ab major or F minor.\n */\n A_FLAT_MAJOR_F_MINOR = 'A_FLAT_MAJOR_F_MINOR',\n /**\n * A major or Gb minor.\n */\n A_MAJOR_G_FLAT_MINOR = 'A_MAJOR_G_FLAT_MINOR',\n /**\n * Bb major or G minor.\n */\n B_FLAT_MAJOR_G_MINOR = 'B_FLAT_MAJOR_G_MINOR',\n /**\n * B major or Ab minor.\n */\n B_MAJOR_A_FLAT_MINOR = 'B_MAJOR_A_FLAT_MINOR',\n}\n\n/** The mode of music generation. */\nexport enum MusicGenerationMode {\n /**\n * Rely on the server default generation mode.\n */\n MUSIC_GENERATION_MODE_UNSPECIFIED = 'MUSIC_GENERATION_MODE_UNSPECIFIED',\n /**\n * Steer text prompts to regions of latent space with higher quality\n music.\n */\n QUALITY = 'QUALITY',\n /**\n * Steer text prompts to regions of latent space with a larger\n diversity of music.\n */\n DIVERSITY = 'DIVERSITY',\n /**\n * Steer text prompts to regions of latent space more likely to\n generate music with vocals.\n */\n VOCALIZATION = 'VOCALIZATION',\n}\n\n/** The playback control signal to apply to the music generation. */\nexport enum LiveMusicPlaybackControl {\n /**\n * This value is unused.\n */\n PLAYBACK_CONTROL_UNSPECIFIED = 'PLAYBACK_CONTROL_UNSPECIFIED',\n /**\n * Start generating the music.\n */\n PLAY = 'PLAY',\n /**\n * Hold the music generation. Use PLAY to resume from the current position.\n */\n PAUSE = 'PAUSE',\n /**\n * Stop the music generation and reset the context (prompts retained).\n Use PLAY to restart the music generation.\n */\n STOP = 'STOP',\n /**\n * Reset the context of the music generation without stopping it.\n Retains the current prompts and config.\n */\n RESET_CONTEXT = 'RESET_CONTEXT',\n}\n\n/** Describes how the video in the Part should be used by the model. */\nexport declare interface VideoMetadata {\n /** The frame rate of the video sent to the model. If not specified, the\n default value will be 1.0. The fps range is (0.0, 24.0]. */\n fps?: number;\n /** Optional. The end offset of the video. */\n endOffset?: string;\n /** Optional. The start offset of the video. */\n startOffset?: string;\n}\n\n/** Content blob. */\nexport declare interface Blob {\n /** Optional. Display name of the blob. Used to provide a label or filename to distinguish blobs. This field is not currently used in the Gemini GenerateContent calls. */\n displayName?: string;\n /** Required. Raw bytes.\n * @remarks Encoded as base64 string. */\n data?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** URI based data. */\nexport declare interface FileData {\n /** Optional. Display name of the file data. Used to provide a label or filename to distinguish file datas. It is not currently used in the Gemini GenerateContent calls. */\n displayName?: string;\n /** Required. URI. */\n fileUri?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** Result of executing the [ExecutableCode]. Only generated when using the [CodeExecution] tool, and always follows a `part` containing the [ExecutableCode]. */\nexport declare interface CodeExecutionResult {\n /** Required. Outcome of the code execution. */\n outcome?: Outcome;\n /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */\n output?: string;\n}\n\n/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [CodeExecution] tool, in which the code will be automatically executed, and a corresponding [CodeExecutionResult] will also be generated. */\nexport declare interface ExecutableCode {\n /** Required. The code to be executed. */\n code?: string;\n /** Required. Programming language of the `code`. */\n language?: Language;\n}\n\n/** A function call. */\nexport declare interface FunctionCall {\n /** The unique id of the function call. If populated, the client to execute the\n `function_call` and return the response with the matching `id`. */\n id?: string;\n /** Optional. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */\n args?: Record;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */\n name?: string;\n}\n\n/** A function response. */\nexport class FunctionResponse {\n /** Signals that function call continues, and more responses will be returned, turning the function call into a generator. Is only applicable to NON_BLOCKING function calls (see FunctionDeclaration.behavior for details), ignored otherwise. If false, the default, future responses will not be considered. Is only applicable to NON_BLOCKING function calls, is ignored otherwise. If set to false, future responses will not be considered. It is allowed to return empty `response` with `will_continue=False` to signal that the function call is finished. */\n willContinue?: boolean;\n /** Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. */\n scheduling?: FunctionResponseScheduling;\n /** Optional. The id of the function call this response is for. Populated by the client to match the corresponding function call `id`. */\n id?: string;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */\n name?: string;\n /** Required. The function response in JSON object format. Use \"output\" key to specify function output and \"error\" key to specify error details (if any). If \"output\" and \"error\" keys are not specified, then whole \"response\" is treated as function output. */\n response?: Record;\n}\n\n/** A datatype containing media content.\n\n Exactly one field within a Part should be set, representing the specific type\n of content being conveyed. Using multiple fields within the same `Part`\n instance is considered invalid.\n */\nexport declare interface Part {\n /** Metadata for a given video. */\n videoMetadata?: VideoMetadata;\n /** Indicates if the part is thought from the model. */\n thought?: boolean;\n /** Optional. Inlined bytes data. */\n inlineData?: Blob;\n /** Optional. URI based data. */\n fileData?: FileData;\n /** An opaque signature for the thought so it can be reused in subsequent requests.\n * @remarks Encoded as base64 string. */\n thoughtSignature?: string;\n /** Optional. Result of executing the [ExecutableCode]. */\n codeExecutionResult?: CodeExecutionResult;\n /** Optional. Code generated by the model that is meant to be executed. */\n executableCode?: ExecutableCode;\n /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */\n functionCall?: FunctionCall;\n /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */\n functionResponse?: FunctionResponse;\n /** Optional. Text part (can be code). */\n text?: string;\n}\n/**\n * Creates a `Part` object from a `URI` string.\n */\nexport function createPartFromUri(uri: string, mimeType: string): Part {\n return {\n fileData: {\n fileUri: uri,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from a `text` string.\n */\nexport function createPartFromText(text: string): Part {\n return {\n text: text,\n };\n}\n/**\n * Creates a `Part` object from a `FunctionCall` object.\n */\nexport function createPartFromFunctionCall(\n name: string,\n args: Record,\n): Part {\n return {\n functionCall: {\n name: name,\n args: args,\n },\n };\n}\n/**\n * Creates a `Part` object from a `FunctionResponse` object.\n */\nexport function createPartFromFunctionResponse(\n id: string,\n name: string,\n response: Record,\n): Part {\n return {\n functionResponse: {\n id: id,\n name: name,\n response: response,\n },\n };\n}\n/**\n * Creates a `Part` object from a `base64` encoded `string`.\n */\nexport function createPartFromBase64(data: string, mimeType: string): Part {\n return {\n inlineData: {\n data: data,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object.\n */\nexport function createPartFromCodeExecutionResult(\n outcome: Outcome,\n output: string,\n): Part {\n return {\n codeExecutionResult: {\n outcome: outcome,\n output: output,\n },\n };\n}\n/**\n * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object.\n */\nexport function createPartFromExecutableCode(\n code: string,\n language: Language,\n): Part {\n return {\n executableCode: {\n code: code,\n language: language,\n },\n };\n}\n\n/** Contains the multi-part content of a message. */\nexport declare interface Content {\n /** List of parts that constitute a single message. Each part may have\n a different IANA MIME type. */\n parts?: Part[];\n /** Optional. The producer of the content. Must be either 'user' or\n 'model'. Useful to set for multi-turn conversations, otherwise can be\n empty. If role is not specified, SDK will determine the role. */\n role?: string;\n}\nfunction _isPart(obj: unknown): obj is Part {\n if (typeof obj === 'object' && obj !== null) {\n return (\n 'fileData' in obj ||\n 'text' in obj ||\n 'functionCall' in obj ||\n 'functionResponse' in obj ||\n 'inlineData' in obj ||\n 'videoMetadata' in obj ||\n 'codeExecutionResult' in obj ||\n 'executableCode' in obj\n );\n }\n return false;\n}\nfunction _toParts(partOrString: PartListUnion | string): Part[] {\n const parts: Part[] = [];\n if (typeof partOrString === 'string') {\n parts.push(createPartFromText(partOrString));\n } else if (_isPart(partOrString)) {\n parts.push(partOrString);\n } else if (Array.isArray(partOrString)) {\n if (partOrString.length === 0) {\n throw new Error('partOrString cannot be an empty array');\n }\n for (const part of partOrString) {\n if (typeof part === 'string') {\n parts.push(createPartFromText(part));\n } else if (_isPart(part)) {\n parts.push(part);\n } else {\n throw new Error('element in PartUnion must be a Part object or string');\n }\n }\n } else {\n throw new Error('partOrString must be a Part object, string, or array');\n }\n return parts;\n}\n/**\n * Creates a `Content` object with a user role from a `PartListUnion` object or `string`.\n */\nexport function createUserContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'user',\n parts: _toParts(partOrString),\n };\n}\n\n/**\n * Creates a `Content` object with a model role from a `PartListUnion` object or `string`.\n */\nexport function createModelContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'model',\n parts: _toParts(partOrString),\n };\n}\n/** HTTP options to be used in each of the requests. */\nexport declare interface HttpOptions {\n /** The base URL for the AI platform service endpoint. */\n baseUrl?: string;\n /** Specifies the version of the API to use. */\n apiVersion?: string;\n /** Additional HTTP headers to be sent with the request. */\n headers?: Record;\n /** Timeout for the request in milliseconds. */\n timeout?: number;\n /** Extra parameters to add to the request body.\n The structure must match the backend API's request structure.\n - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest\n - GeminiAPI backend API docs: https://ai.google.dev/api/rest */\n extraBody?: Record;\n}\n\n/** Schema is used to define the format of input/output data.\n\n Represents a select subset of an [OpenAPI 3.0 schema\n object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may\n be added in the future as needed.\n */\nexport declare interface Schema {\n /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */\n anyOf?: Schema[];\n /** Optional. Default value of the data. */\n default?: unknown;\n /** Optional. The description of the data. */\n description?: string;\n /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:[\"EAST\", NORTH\", \"SOUTH\", \"WEST\"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:[\"101\", \"201\", \"301\"]} */\n enum?: string[];\n /** Optional. Example of the object. Will only populated when the object is the root. */\n example?: unknown;\n /** Optional. The format of the data. Supported formats: for NUMBER type: \"float\", \"double\" for INTEGER type: \"int32\", \"int64\" for STRING type: \"email\", \"byte\", etc */\n format?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */\n items?: Schema;\n /** Optional. Maximum number of the elements for Type.ARRAY. */\n maxItems?: string;\n /** Optional. Maximum length of the Type.STRING */\n maxLength?: string;\n /** Optional. Maximum number of the properties for Type.OBJECT. */\n maxProperties?: string;\n /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */\n maximum?: number;\n /** Optional. Minimum number of the elements for Type.ARRAY. */\n minItems?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */\n minLength?: string;\n /** Optional. Minimum number of the properties for Type.OBJECT. */\n minProperties?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */\n minimum?: number;\n /** Optional. Indicates if the value may be null. */\n nullable?: boolean;\n /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */\n pattern?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */\n properties?: Record;\n /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */\n propertyOrdering?: string[];\n /** Optional. Required properties of Type.OBJECT. */\n required?: string[];\n /** Optional. The title of the Schema. */\n title?: string;\n /** Optional. The type of the data. */\n type?: Type;\n}\n\n/** Config for model selection. */\nexport declare interface ModelSelectionConfig {\n /** Options for feature selection preference. */\n featureSelectionPreference?: FeatureSelectionPreference;\n}\n\n/** Safety settings. */\nexport declare interface SafetySetting {\n /** Determines if the harm block method uses probability or probability\n and severity scores. */\n method?: HarmBlockMethod;\n /** Required. Harm category. */\n category?: HarmCategory;\n /** Required. The harm block threshold. */\n threshold?: HarmBlockThreshold;\n}\n\n/** Defines a function that the model can generate JSON inputs for.\n\n The inputs are based on `OpenAPI 3.0 specifications\n `_.\n */\nexport declare interface FunctionDeclaration {\n /** Defines the function behavior. */\n behavior?: Behavior;\n /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */\n description?: string;\n /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */\n name?: string;\n /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */\n parameters?: Schema;\n /** Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" }, \"age\": { \"type\": \"integer\" } }, \"additionalProperties\": false, \"required\": [\"name\", \"age\"], \"propertyOrdering\": [\"name\", \"age\"] } ``` This field is mutually exclusive with `parameters`. */\n parametersJsonSchema?: unknown;\n /** Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function. */\n response?: Schema;\n /** Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`. */\n responseJsonSchema?: unknown;\n}\n\n/** Represents a time interval, encoded as a start time (inclusive) and an end time (exclusive).\n\n The start time must be less than or equal to the end time.\n When the start equals the end time, the interval is an empty interval.\n (matches no time)\n When both start and end are unspecified, the interval matches any time.\n */\nexport declare interface Interval {\n /** The start time of the interval. */\n startTime?: string;\n /** The end time of the interval. */\n endTime?: string;\n}\n\n/** Tool to support Google Search in Model. Powered by Google. */\nexport declare interface GoogleSearch {\n /** Optional. Filter search results to a specific time range.\n If customers set a start time, they must set an end time (and vice versa).\n */\n timeRangeFilter?: Interval;\n /** Optional. List of domains to be excluded from the search results.\n The default limit is 2000 domains. */\n excludeDomains?: string[];\n}\n\n/** Describes the options to customize dynamic retrieval. */\nexport declare interface DynamicRetrievalConfig {\n /** The mode of the predictor to be used in dynamic retrieval. */\n mode?: DynamicRetrievalConfigMode;\n /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */\n dynamicThreshold?: number;\n}\n\n/** Tool to retrieve public web data for grounding, powered by Google. */\nexport declare interface GoogleSearchRetrieval {\n /** Specifies the dynamic retrieval configuration for the given source. */\n dynamicRetrievalConfig?: DynamicRetrievalConfig;\n}\n\n/** Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. */\nexport declare interface EnterpriseWebSearch {\n /** Optional. List of domains to be excluded from the search results. The default limit is 2000 domains. */\n excludeDomains?: string[];\n}\n\n/** Config for authentication with API key. */\nexport declare interface ApiKeyConfig {\n /** The API key to be used in the request directly. */\n apiKeyString?: string;\n}\n\n/** Config for Google Service Account Authentication. */\nexport declare interface AuthConfigGoogleServiceAccountConfig {\n /** Optional. The service account that the extension execution service runs as. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified service account. - If not specified, the Vertex AI Extension Service Agent will be used to execute the Extension. */\n serviceAccount?: string;\n}\n\n/** Config for HTTP Basic Authentication. */\nexport declare interface AuthConfigHttpBasicAuthConfig {\n /** Required. The name of the SecretManager secret version resource storing the base64 encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource. */\n credentialSecret?: string;\n}\n\n/** Config for user oauth. */\nexport declare interface AuthConfigOauthConfig {\n /** Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */\n accessToken?: string;\n /** The service account used to generate access tokens for executing the Extension. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the provided service account. */\n serviceAccount?: string;\n}\n\n/** Config for user OIDC auth. */\nexport declare interface AuthConfigOidcConfig {\n /** OpenID Connect formatted ID token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */\n idToken?: string;\n /** The service account used to generate an OpenID Connect (OIDC)-compatible JWT token signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc). - The audience for the token will be set to the URL in the server url defined in the OpenApi spec. - If the service account is provided, the service account should grant `iam.serviceAccounts.getOpenIdToken` permission to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents). */\n serviceAccount?: string;\n}\n\n/** Auth configuration to run the extension. */\nexport declare interface AuthConfig {\n /** Config for API key auth. */\n apiKeyConfig?: ApiKeyConfig;\n /** Type of auth scheme. */\n authType?: AuthType;\n /** Config for Google Service Account auth. */\n googleServiceAccountConfig?: AuthConfigGoogleServiceAccountConfig;\n /** Config for HTTP Basic auth. */\n httpBasicAuthConfig?: AuthConfigHttpBasicAuthConfig;\n /** Config for user oauth. */\n oauthConfig?: AuthConfigOauthConfig;\n /** Config for user OIDC auth. */\n oidcConfig?: AuthConfigOidcConfig;\n}\n\n/** Tool to support Google Maps in Model. */\nexport declare interface GoogleMaps {\n /** Optional. Auth config for the Google Maps tool. */\n authConfig?: AuthConfig;\n}\n\n/** Tool to support URL context retrieval. */\nexport declare interface UrlContext {}\n\n/** Tool to support computer use. */\nexport declare interface ToolComputerUse {\n /** Required. The environment being operated. */\n environment?: Environment;\n}\n\n/** The API secret. */\nexport declare interface ApiAuthApiKeyConfig {\n /** Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version} */\n apiKeySecretVersion?: string;\n /** The API key string. Either this or `api_key_secret_version` must be set. */\n apiKeyString?: string;\n}\n\n/** The generic reusable api auth config. Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto) instead. */\nexport declare interface ApiAuth {\n /** The API secret. */\n apiKeyConfig?: ApiAuthApiKeyConfig;\n}\n\n/** The search parameters to use for the ELASTIC_SEARCH spec. */\nexport declare interface ExternalApiElasticSearchParams {\n /** The ElasticSearch index to use. */\n index?: string;\n /** Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as the `num_hits` param. */\n numHits?: number;\n /** The ElasticSearch search template to use. */\n searchTemplate?: string;\n}\n\n/** The search parameters to use for SIMPLE_SEARCH spec. */\nexport declare interface ExternalApiSimpleSearchParams {}\n\n/** Retrieve from data source powered by external API for grounding. The external API is not owned by Google, but need to follow the pre-defined API spec. */\nexport declare interface ExternalApi {\n /** The authentication config to access the API. Deprecated. Please use auth_config instead. */\n apiAuth?: ApiAuth;\n /** The API spec that the external API implements. */\n apiSpec?: ApiSpec;\n /** The authentication config to access the API. */\n authConfig?: AuthConfig;\n /** Parameters for the elastic search API. */\n elasticSearchParams?: ExternalApiElasticSearchParams;\n /** The endpoint of the external API. The system will call the API at this endpoint to retrieve the data for grounding. Example: https://acme.com:443/search */\n endpoint?: string;\n /** Parameters for the simple search API. */\n simpleSearchParams?: ExternalApiSimpleSearchParams;\n}\n\n/** Define data stores within engine to filter on in a search call and configurations for those data stores. For more information, see https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec */\nexport declare interface VertexAISearchDataStoreSpec {\n /** Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n dataStore?: string;\n /** Optional. Filter specification to filter documents in the data store specified by data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata) */\n filter?: string;\n}\n\n/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */\nexport declare interface VertexAISearch {\n /** Specifications that define the specific DataStores to be searched, along with configurations for those data stores. This is only considered for Engines with multiple data stores. It should only be set if engine is used. */\n dataStoreSpecs?: VertexAISearchDataStoreSpec[];\n /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n datastore?: string;\n /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */\n engine?: string;\n /** Optional. Filter strings to be passed to the search API. */\n filter?: string;\n /** Optional. Number of search results to return per query. The default value is 10. The maximumm allowed value is 10. */\n maxResults?: number;\n}\n\n/** The definition of the Rag resource. */\nexport declare interface VertexRagStoreRagResource {\n /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */\n ragCorpus?: string;\n /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */\n ragFileIds?: string[];\n}\n\n/** Config for filters. */\nexport declare interface RagRetrievalConfigFilter {\n /** Optional. String for metadata filtering. */\n metadataFilter?: string;\n /** Optional. Only returns contexts with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n /** Optional. Only returns contexts with vector similarity larger than the threshold. */\n vectorSimilarityThreshold?: number;\n}\n\n/** Config for Hybrid Search. */\nexport declare interface RagRetrievalConfigHybridSearch {\n /** Optional. Alpha value controls the weight between dense and sparse vector search results. The range is [0, 1], while 0 means sparse vector search only and 1 means dense vector search only. The default value is 0.5 which balances sparse and dense vector search equally. */\n alpha?: number;\n}\n\n/** Config for LlmRanker. */\nexport declare interface RagRetrievalConfigRankingLlmRanker {\n /** Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */\n modelName?: string;\n}\n\n/** Config for Rank Service. */\nexport declare interface RagRetrievalConfigRankingRankService {\n /** Optional. The model name of the rank service. Format: `semantic-ranker-512@latest` */\n modelName?: string;\n}\n\n/** Config for ranking and reranking. */\nexport declare interface RagRetrievalConfigRanking {\n /** Optional. Config for LlmRanker. */\n llmRanker?: RagRetrievalConfigRankingLlmRanker;\n /** Optional. Config for Rank Service. */\n rankService?: RagRetrievalConfigRankingRankService;\n}\n\n/** Specifies the context retrieval config. */\nexport declare interface RagRetrievalConfig {\n /** Optional. Config for filters. */\n filter?: RagRetrievalConfigFilter;\n /** Optional. Config for Hybrid Search. */\n hybridSearch?: RagRetrievalConfigHybridSearch;\n /** Optional. Config for ranking and reranking. */\n ranking?: RagRetrievalConfigRanking;\n /** Optional. The number of contexts to retrieve. */\n topK?: number;\n}\n\n/** Retrieve from Vertex RAG Store for grounding. */\nexport declare interface VertexRagStore {\n /** Optional. Deprecated. Please use rag_resources instead. */\n ragCorpora?: string[];\n /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */\n ragResources?: VertexRagStoreRagResource[];\n /** Optional. The retrieval config for the Rag query. */\n ragRetrievalConfig?: RagRetrievalConfig;\n /** Optional. Number of top k results to return from the selected corpora. */\n similarityTopK?: number;\n /** Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal Live API, if `store_context` bool is specified, Gemini will leverage it to automatically memorize the interactions between the client and Gemini, and retrieve context when needed to augment the response generation for users' ongoing and future interactions. */\n storeContext?: boolean;\n /** Optional. Only return results with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n}\n\n/** Defines a retrieval tool that model can call to access external knowledge. */\nexport declare interface Retrieval {\n /** Optional. Deprecated. This option is no longer supported. */\n disableAttribution?: boolean;\n /** Use data source powered by external API for grounding. */\n externalApi?: ExternalApi;\n /** Set to use data source powered by Vertex AI Search. */\n vertexAiSearch?: VertexAISearch;\n /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */\n vertexRagStore?: VertexRagStore;\n}\n\n/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */\nexport declare interface ToolCodeExecution {}\n\n/** Tool details of a tool that the model may use to generate a response. */\nexport declare interface Tool {\n /** List of function declarations that the tool supports. */\n functionDeclarations?: FunctionDeclaration[];\n /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */\n retrieval?: Retrieval;\n /** Optional. Google Search tool type. Specialized retrieval tool\n that is powered by Google Search. */\n googleSearch?: GoogleSearch;\n /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */\n googleSearchRetrieval?: GoogleSearchRetrieval;\n /** Optional. Enterprise web search tool type. Specialized retrieval\n tool that is powered by Vertex AI Search and Sec4 compliance. */\n enterpriseWebSearch?: EnterpriseWebSearch;\n /** Optional. Google Maps tool type. Specialized retrieval tool\n that is powered by Google Maps. */\n googleMaps?: GoogleMaps;\n /** Optional. Tool to support URL context retrieval. */\n urlContext?: UrlContext;\n /** Optional. Tool to support the model interacting directly with the\n computer. If enabled, it automatically populates computer-use specific\n Function Declarations. */\n computerUse?: ToolComputerUse;\n /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. */\n codeExecution?: ToolCodeExecution;\n}\n\n/** Function calling config. */\nexport declare interface FunctionCallingConfig {\n /** Optional. Function calling mode. */\n mode?: FunctionCallingConfigMode;\n /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */\n allowedFunctionNames?: string[];\n}\n\n/** An object that represents a latitude/longitude pair.\n\n This is expressed as a pair of doubles to represent degrees latitude and\n degrees longitude. Unless specified otherwise, this object must conform to the\n \n WGS84 standard. Values must be within normalized ranges.\n */\nexport declare interface LatLng {\n /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */\n latitude?: number;\n /** The longitude in degrees. It must be in the range [-180.0, +180.0] */\n longitude?: number;\n}\n\n/** Retrieval config.\n */\nexport declare interface RetrievalConfig {\n /** Optional. The location of the user. */\n latLng?: LatLng;\n /** The language code of the user. */\n languageCode?: string;\n}\n\n/** Tool config.\n\n This config is shared for all tools provided in the request.\n */\nexport declare interface ToolConfig {\n /** Optional. Function calling config. */\n functionCallingConfig?: FunctionCallingConfig;\n /** Optional. Retrieval config. */\n retrievalConfig?: RetrievalConfig;\n}\n\n/** The configuration for the prebuilt speaker to use. */\nexport declare interface PrebuiltVoiceConfig {\n /** The name of the prebuilt voice to use. */\n voiceName?: string;\n}\n\n/** The configuration for the voice to use. */\nexport declare interface VoiceConfig {\n /** The configuration for the speaker to use.\n */\n prebuiltVoiceConfig?: PrebuiltVoiceConfig;\n}\n\n/** The configuration for the speaker to use. */\nexport declare interface SpeakerVoiceConfig {\n /** The name of the speaker to use. Should be the same as in the\n prompt. */\n speaker?: string;\n /** The configuration for the voice to use. */\n voiceConfig?: VoiceConfig;\n}\n\n/** The configuration for the multi-speaker setup. */\nexport declare interface MultiSpeakerVoiceConfig {\n /** The configuration for the speaker to use. */\n speakerVoiceConfigs?: SpeakerVoiceConfig[];\n}\n\n/** The speech generation configuration. */\nexport declare interface SpeechConfig {\n /** The configuration for the speaker to use.\n */\n voiceConfig?: VoiceConfig;\n /** The configuration for the multi-speaker setup.\n It is mutually exclusive with the voice_config field.\n */\n multiSpeakerVoiceConfig?: MultiSpeakerVoiceConfig;\n /** Language code (ISO 639. e.g. en-US) for the speech synthesization.\n Only available for Live API.\n */\n languageCode?: string;\n}\n\n/** The configuration for automatic function calling. */\nexport declare interface AutomaticFunctionCallingConfig {\n /** Whether to disable automatic function calling.\n If not set or set to False, will enable automatic function calling.\n If set to True, will disable automatic function calling.\n */\n disable?: boolean;\n /** If automatic function calling is enabled,\n maximum number of remote calls for automatic function calling.\n This number should be a positive integer.\n If not set, SDK will set maximum number of remote calls to 10.\n */\n maximumRemoteCalls?: number;\n /** If automatic function calling is enabled,\n whether to ignore call history to the response.\n If not set, SDK will set ignore_call_history to false,\n and will append the call history to\n GenerateContentResponse.automatic_function_calling_history.\n */\n ignoreCallHistory?: boolean;\n}\n\n/** The thinking features configuration. */\nexport declare interface ThinkingConfig {\n /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available.\n */\n includeThoughts?: boolean;\n /** Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent.\n */\n thinkingBudget?: number;\n}\n\n/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */\nexport declare interface GenerationConfigRoutingConfigAutoRoutingMode {\n /** The model routing preference. */\n modelRoutingPreference?:\n | 'UNKNOWN'\n | 'PRIORITIZE_QUALITY'\n | 'BALANCED'\n | 'PRIORITIZE_COST';\n}\n\n/** When manual routing is set, the specified model will be used directly. */\nexport declare interface GenerationConfigRoutingConfigManualRoutingMode {\n /** The model name to use. Only the public LLM models are accepted. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */\n modelName?: string;\n}\n\n/** The configuration for routing the request to a specific model. */\nexport declare interface GenerationConfigRoutingConfig {\n /** Automated routing. */\n autoMode?: GenerationConfigRoutingConfigAutoRoutingMode;\n /** Manual routing. */\n manualMode?: GenerationConfigRoutingConfigManualRoutingMode;\n}\n\n/** Optional model configuration parameters.\n\n For more information, see `Content generation parameters\n `_.\n */\nexport declare interface GenerateContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Instructions for the model to steer it toward better performance.\n For example, \"Answer as concisely as possible\" or \"Don't use technical\n terms in your response\".\n */\n systemInstruction?: ContentUnion;\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Number of response variations to return.\n */\n candidateCount?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** List of strings that tells the model to stop generating text if one\n of the strings is encountered in the response.\n */\n stopSequences?: string[];\n /** Whether to return the log probabilities of the tokens that were\n chosen by the model at each step.\n */\n responseLogprobs?: boolean;\n /** Number of top candidate tokens to return the log probabilities for\n at each generation step.\n */\n logprobs?: number;\n /** Positive values penalize tokens that already appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n presencePenalty?: number;\n /** Positive values penalize tokens that repeatedly appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n frequencyPenalty?: number;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** Output response mimetype of the generated candidate text.\n Supported mimetype:\n - `text/plain`: (default) Text output.\n - `application/json`: JSON response in the candidates.\n The model needs to be prompted to output the appropriate response type,\n otherwise the behavior is undefined.\n This is a preview feature.\n */\n responseMimeType?: string;\n /** The `Schema` object allows the definition of input and output data types.\n These types can be objects, but also primitives and arrays.\n Represents a select subset of an [OpenAPI 3.0 schema\n object](https://spec.openapis.org/oas/v3.0.3#schema).\n If set, a compatible response_mime_type must also be set.\n Compatible mimetypes: `application/json`: Schema for JSON response.\n */\n responseSchema?: SchemaUnion;\n /** Optional. Output schema of the generated response.\n This is an alternative to `response_schema` that accepts [JSON\n Schema](https://json-schema.org/). If set, `response_schema` must be\n omitted, but `response_mime_type` is required. While the full JSON Schema\n may be sent, not all features are supported. Specifically, only the\n following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor`\n - `type` - `format` - `title` - `description` - `enum` (for strings and\n numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` -\n `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) -\n `properties` - `additionalProperties` - `required` The non-standard\n `propertyOrdering` property may also be set. Cyclic references are\n unrolled to a limited degree and, as such, may only be used within\n non-required properties. (Nullable properties are not sufficient.) If\n `$ref` is set on a sub-schema, no other properties, except for than those\n starting as a `$`, may be set. */\n responseJsonSchema?: unknown;\n /** Configuration for model router requests.\n */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Configuration for model selection.\n */\n modelSelectionConfig?: ModelSelectionConfig;\n /** Safety settings in the request to block unsafe content in the\n response.\n */\n safetySettings?: SafetySetting[];\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: ToolListUnion;\n /** Associates model output to a specific function call.\n */\n toolConfig?: ToolConfig;\n /** Labels with user-defined metadata to break down billed charges. */\n labels?: Record;\n /** Resource name of a context cache that can be used in subsequent\n requests.\n */\n cachedContent?: string;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return.\n */\n responseModalities?: string[];\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfigUnion;\n /** If enabled, audio timestamp will be included in the request to the\n model.\n */\n audioTimestamp?: boolean;\n /** The configuration for automatic function calling.\n */\n automaticFunctionCalling?: AutomaticFunctionCallingConfig;\n /** The thinking features configuration.\n */\n thinkingConfig?: ThinkingConfig;\n}\n\n/** Config for models.generate_content parameters. */\nexport declare interface GenerateContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Content of the request.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** A wrapper class for the http response. */\nexport class HttpResponse {\n /** Used to retain the processed HTTP headers in the response. */\n headers?: Record;\n /**\n * The original http response.\n */\n responseInternal: Response;\n\n constructor(response: Response) {\n // Process the headers.\n const headers: Record = {};\n for (const pair of response.headers.entries()) {\n headers[pair[0]] = pair[1];\n }\n this.headers = headers;\n\n // Keep the original response.\n this.responseInternal = response;\n }\n\n json(): Promise {\n return this.responseInternal.json();\n }\n}\n\n/** Callbacks for the live API. */\nexport interface LiveCallbacks {\n /**\n * Called when the websocket connection is established.\n */\n onopen?: (() => void) | null;\n /**\n * Called when a message is received from the server.\n */\n onmessage: (e: LiveServerMessage) => void;\n /**\n * Called when an error occurs.\n */\n onerror?: ((e: ErrorEvent) => void) | null;\n /**\n * Called when the websocket connection is closed.\n */\n onclose?: ((e: CloseEvent) => void) | null;\n}\n\n/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */\nexport declare interface GoogleTypeDate {\n /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */\n day?: number;\n /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */\n month?: number;\n /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */\n year?: number;\n}\n\n/** Source attributions for content. */\nexport declare interface Citation {\n /** Output only. End index into the content. */\n endIndex?: number;\n /** Output only. License of the attribution. */\n license?: string;\n /** Output only. Publication date of the attribution. */\n publicationDate?: GoogleTypeDate;\n /** Output only. Start index into the content. */\n startIndex?: number;\n /** Output only. Title of the attribution. */\n title?: string;\n /** Output only. Url reference of the attribution. */\n uri?: string;\n}\n\n/** Citation information when the model quotes another source. */\nexport declare interface CitationMetadata {\n /** Contains citation information when the model directly quotes, at\n length, from another source. Can include traditional websites and code\n repositories.\n */\n citations?: Citation[];\n}\n\n/** Context for a single url retrieval. */\nexport declare interface UrlMetadata {\n /** The URL retrieved by the tool. */\n retrievedUrl?: string;\n /** Status of the url retrieval. */\n urlRetrievalStatus?: UrlRetrievalStatus;\n}\n\n/** Metadata related to url context retrieval tool. */\nexport declare interface UrlContextMetadata {\n /** List of url context. */\n urlMetadata?: UrlMetadata[];\n}\n\n/** Author attribution for a photo or review. */\nexport declare interface GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution {\n /** Name of the author of the Photo or Review. */\n displayName?: string;\n /** Profile photo URI of the author of the Photo or Review. */\n photoUri?: string;\n /** URI of the author of the Photo or Review. */\n uri?: string;\n}\n\n/** Encapsulates a review snippet. */\nexport declare interface GroundingChunkMapsPlaceAnswerSourcesReviewSnippet {\n /** This review's author. */\n authorAttribution?: GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution;\n /** A link where users can flag a problem with the review. */\n flagContentUri?: string;\n /** A link to show the review on Google Maps. */\n googleMapsUri?: string;\n /** A string of formatted recent time, expressing the review time relative to the current time in a form appropriate for the language and country. */\n relativePublishTimeDescription?: string;\n /** A reference representing this place review which may be used to look up this place review again. */\n review?: string;\n}\n\n/** Sources used to generate the place answer. */\nexport declare interface GroundingChunkMapsPlaceAnswerSources {\n /** A link where users can flag a problem with the generated answer. */\n flagContentUri?: string;\n /** Snippets of reviews that are used to generate the answer. */\n reviewSnippets?: GroundingChunkMapsPlaceAnswerSourcesReviewSnippet[];\n}\n\n/** Chunk from Google Maps. */\nexport declare interface GroundingChunkMaps {\n /** Sources used to generate the place answer. This includes review snippets and photos that were used to generate the answer, as well as uris to flag content. */\n placeAnswerSources?: GroundingChunkMapsPlaceAnswerSources;\n /** This Place's resource name, in `places/{place_id}` format. Can be used to look up the Place. */\n placeId?: string;\n /** Text of the chunk. */\n text?: string;\n /** Title of the chunk. */\n title?: string;\n /** URI reference of the chunk. */\n uri?: string;\n}\n\n/** Represents where the chunk starts and ends in the document. */\nexport declare interface RagChunkPageSpan {\n /** Page where chunk starts in the document. Inclusive. 1-indexed. */\n firstPage?: number;\n /** Page where chunk ends in the document. Inclusive. 1-indexed. */\n lastPage?: number;\n}\n\n/** A RagChunk includes the content of a chunk of a RagFile, and associated metadata. */\nexport declare interface RagChunk {\n /** If populated, represents where the chunk starts and ends in the document. */\n pageSpan?: RagChunkPageSpan;\n /** The content of the chunk. */\n text?: string;\n}\n\n/** Chunk from context retrieved by the retrieval tools. */\nexport declare interface GroundingChunkRetrievedContext {\n /** Output only. The full document name for the referenced Vertex AI Search document. */\n documentName?: string;\n /** Additional context for the RAG retrieval result. This is only populated when using the RAG retrieval tool. */\n ragChunk?: RagChunk;\n /** Text of the attribution. */\n text?: string;\n /** Title of the attribution. */\n title?: string;\n /** URI reference of the attribution. */\n uri?: string;\n}\n\n/** Chunk from the web. */\nexport declare interface GroundingChunkWeb {\n /** Domain of the (original) URI. */\n domain?: string;\n /** Title of the chunk. */\n title?: string;\n /** URI reference of the chunk. */\n uri?: string;\n}\n\n/** Grounding chunk. */\nexport declare interface GroundingChunk {\n /** Grounding chunk from Google Maps. */\n maps?: GroundingChunkMaps;\n /** Grounding chunk from context retrieved by the retrieval tools. */\n retrievedContext?: GroundingChunkRetrievedContext;\n /** Grounding chunk from the web. */\n web?: GroundingChunkWeb;\n}\n\n/** Segment of the content. */\nexport declare interface Segment {\n /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */\n endIndex?: number;\n /** Output only. The index of a Part object within its parent Content object. */\n partIndex?: number;\n /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */\n startIndex?: number;\n /** Output only. The text corresponding to the segment from the response. */\n text?: string;\n}\n\n/** Grounding support. */\nexport declare interface GroundingSupport {\n /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. For Gemini 2.0 and before, this list must have the same size as the grounding_chunk_indices. For Gemini 2.5 and after, this list will be empty and should be ignored. */\n confidenceScores?: number[];\n /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */\n groundingChunkIndices?: number[];\n /** Segment of the content this support belongs to. */\n segment?: Segment;\n}\n\n/** Metadata related to retrieval in the grounding flow. */\nexport declare interface RetrievalMetadata {\n /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */\n googleSearchDynamicRetrievalScore?: number;\n}\n\n/** Google search entry point. */\nexport declare interface SearchEntryPoint {\n /** Optional. Web content snippet that can be embedded in a web page or an app webview. */\n renderedContent?: string;\n /** Optional. Base64 encoded JSON representing array of tuple.\n * @remarks Encoded as base64 string. */\n sdkBlob?: string;\n}\n\n/** Metadata returned to client when grounding is enabled. */\nexport declare interface GroundingMetadata {\n /** Optional. Output only. Resource name of the Google Maps widget context token to be used with the PlacesContextElement widget to render contextual data. This is populated only for Google Maps grounding. */\n googleMapsWidgetContextToken?: string;\n /** List of supporting references retrieved from specified grounding source. */\n groundingChunks?: GroundingChunk[];\n /** Optional. List of grounding support. */\n groundingSupports?: GroundingSupport[];\n /** Optional. Output only. Retrieval metadata. */\n retrievalMetadata?: RetrievalMetadata;\n /** Optional. Queries executed by the retrieval tools. */\n retrievalQueries?: string[];\n /** Optional. Google search entry for the following-up web searches. */\n searchEntryPoint?: SearchEntryPoint;\n /** Optional. Web search queries for the following-up web search. */\n webSearchQueries?: string[];\n}\n\n/** Candidate for the logprobs token and score. */\nexport declare interface LogprobsResultCandidate {\n /** The candidate's log probability. */\n logProbability?: number;\n /** The candidate's token string value. */\n token?: string;\n /** The candidate's token id value. */\n tokenId?: number;\n}\n\n/** Candidates with top log probabilities at each decoding step. */\nexport declare interface LogprobsResultTopCandidates {\n /** Sorted by log probability in descending order. */\n candidates?: LogprobsResultCandidate[];\n}\n\n/** Logprobs Result */\nexport declare interface LogprobsResult {\n /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */\n chosenCandidates?: LogprobsResultCandidate[];\n /** Length = total number of decoding steps. */\n topCandidates?: LogprobsResultTopCandidates[];\n}\n\n/** Safety rating corresponding to the generated content. */\nexport declare interface SafetyRating {\n /** Output only. Indicates whether the content was filtered out because of this rating. */\n blocked?: boolean;\n /** Output only. Harm category. */\n category?: HarmCategory;\n /** Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If minors are detected in the output image, the threshold of each safety category will be overwritten if user sets a lower threshold. */\n overwrittenThreshold?: HarmBlockThreshold;\n /** Output only. Harm probability levels in the content. */\n probability?: HarmProbability;\n /** Output only. Harm probability score. */\n probabilityScore?: number;\n /** Output only. Harm severity levels in the content. */\n severity?: HarmSeverity;\n /** Output only. Harm severity score. */\n severityScore?: number;\n}\n\n/** A response candidate generated from the model. */\nexport declare interface Candidate {\n /** Contains the multi-part content of the response.\n */\n content?: Content;\n /** Source attribution of the generated content.\n */\n citationMetadata?: CitationMetadata;\n /** Describes the reason the model stopped generating tokens.\n */\n finishMessage?: string;\n /** Number of tokens for this candidate.\n */\n tokenCount?: number;\n /** The reason why the model stopped generating tokens.\n If empty, the model has not stopped generating the tokens.\n */\n finishReason?: FinishReason;\n /** Metadata related to url context retrieval tool. */\n urlContextMetadata?: UrlContextMetadata;\n /** Output only. Average log probability score of the candidate. */\n avgLogprobs?: number;\n /** Output only. Metadata specifies sources used to ground generated content. */\n groundingMetadata?: GroundingMetadata;\n /** Output only. Index of the candidate. */\n index?: number;\n /** Output only. Log-likelihood scores for the response tokens and top tokens */\n logprobsResult?: LogprobsResult;\n /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Content filter results for a prompt sent in the request. */\nexport class GenerateContentResponsePromptFeedback {\n /** Output only. Blocked reason. */\n blockReason?: BlockedReason;\n /** Output only. A readable block reason message. */\n blockReasonMessage?: string;\n /** Output only. Safety ratings. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Represents token counting info for a single modality. */\nexport declare interface ModalityTokenCount {\n /** The modality associated with this token count. */\n modality?: MediaModality;\n /** Number of tokens. */\n tokenCount?: number;\n}\n\n/** Usage metadata about response(s). */\nexport class GenerateContentResponseUsageMetadata {\n /** Output only. List of modalities of the cached content in the request input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens in the cached part in the input (the cached content). */\n cachedContentTokenCount?: number;\n /** Number of tokens in the response(s). */\n candidatesTokenCount?: number;\n /** Output only. List of modalities that were returned in the response. */\n candidatesTokensDetails?: ModalityTokenCount[];\n /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Output only. List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens present in thoughts output. */\n thoughtsTokenCount?: number;\n /** Output only. Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Output only. List of modalities that were processed for tool-use request inputs. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Total token count for prompt, response candidates, and tool-use prompts (if present). */\n totalTokenCount?: number;\n /** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */\n trafficType?: TrafficType;\n}\n\n/** Response message for PredictionService.GenerateContent. */\nexport class GenerateContentResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Response variations returned by the model.\n */\n candidates?: Candidate[];\n /** Timestamp when the request is made to the server.\n */\n createTime?: string;\n /** The history of automatic function calling.\n */\n automaticFunctionCallingHistory?: Content[];\n /** Output only. The model version used to generate the response. */\n modelVersion?: string;\n /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */\n promptFeedback?: GenerateContentResponsePromptFeedback;\n /** Output only. response_id is used to identify each response. It is the encoding of the event_id. */\n responseId?: string;\n /** Usage metadata about the response(s). */\n usageMetadata?: GenerateContentResponseUsageMetadata;\n /**\n * Returns the concatenation of all text parts from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the text from the first\n * one will be returned.\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n * If there are thought parts in the response, the concatenation of all text\n * parts excluding the thought parts will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'Why is the sky blue?',\n * });\n *\n * console.debug(response.text);\n * ```\n */\n get text(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning text from the first one.',\n );\n }\n let text = '';\n let anyTextPartText = false;\n const nonTextParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartText = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartText ? text : undefined;\n }\n\n /**\n * Returns the concatenation of all inline data parts from the first candidate\n * in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the inline data from the\n * first one will be returned. If there are non-inline data parts in the\n * response, the concatenation of all inline data parts will be returned, and\n * a warning will be logged.\n */\n get data(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning data from the first one.',\n );\n }\n let data = '';\n const nonDataParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'inlineData' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonDataParts.push(fieldName);\n }\n }\n if (part.inlineData && typeof part.inlineData.data === 'string') {\n data += atob(part.inlineData.data);\n }\n }\n if (nonDataParts.length > 0) {\n console.warn(\n `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`,\n );\n }\n return data.length > 0 ? btoa(data) : undefined;\n }\n\n /**\n * Returns the function calls from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the function calls from\n * the first one will be returned.\n * If there are no function calls in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const controlLightFunctionDeclaration: FunctionDeclaration = {\n * name: 'controlLight',\n * parameters: {\n * type: Type.OBJECT,\n * description: 'Set the brightness and color temperature of a room light.',\n * properties: {\n * brightness: {\n * type: Type.NUMBER,\n * description:\n * 'Light level from 0 to 100. Zero is off and 100 is full brightness.',\n * },\n * colorTemperature: {\n * type: Type.STRING,\n * description:\n * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.',\n * },\n * },\n * required: ['brightness', 'colorTemperature'],\n * };\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'Dim the lights so the room feels cozy and warm.',\n * config: {\n * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}],\n * toolConfig: {\n * functionCallingConfig: {\n * mode: FunctionCallingConfigMode.ANY,\n * allowedFunctionNames: ['controlLight'],\n * },\n * },\n * },\n * });\n * console.debug(JSON.stringify(response.functionCalls));\n * ```\n */\n get functionCalls(): FunctionCall[] | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning function calls from the first one.',\n );\n }\n const functionCalls = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.functionCall)\n .map((part) => part.functionCall)\n .filter(\n (functionCall): functionCall is FunctionCall =>\n functionCall !== undefined,\n );\n if (functionCalls?.length === 0) {\n return undefined;\n }\n return functionCalls;\n }\n /**\n * Returns the first executable code from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the executable code from\n * the first one will be returned.\n * If there are no executable code in the response, undefined will be\n * returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.executableCode);\n * ```\n */\n get executableCode(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning executable code from the first one.',\n );\n }\n const executableCode = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.executableCode)\n .map((part) => part.executableCode)\n .filter(\n (executableCode): executableCode is ExecutableCode =>\n executableCode !== undefined,\n );\n if (executableCode?.length === 0) {\n return undefined;\n }\n\n return executableCode?.[0]?.code;\n }\n /**\n * Returns the first code execution result from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the code execution result from\n * the first one will be returned.\n * If there are no code execution result in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.codeExecutionResult);\n * ```\n */\n get codeExecutionResult(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning code execution result from the first one.',\n );\n }\n const codeExecutionResult = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.codeExecutionResult)\n .map((part) => part.codeExecutionResult)\n .filter(\n (codeExecutionResult): codeExecutionResult is CodeExecutionResult =>\n codeExecutionResult !== undefined,\n );\n if (codeExecutionResult?.length === 0) {\n return undefined;\n }\n return codeExecutionResult?.[0]?.output;\n }\n}\n\nexport type ReferenceImage =\n | RawReferenceImage\n | MaskReferenceImage\n | ControlReferenceImage\n | StyleReferenceImage\n | SubjectReferenceImage;\n\n/** Parameters for the request to edit an image. */\nexport declare interface EditImageParameters {\n /** The model to use. */\n model: string;\n /** A text description of the edit to apply to the image. */\n prompt: string;\n /** The reference images for Imagen 3 editing. */\n referenceImages: ReferenceImage[];\n /** Configuration for editing. */\n config?: EditImageConfig;\n}\n\n/** Optional parameters for the embed_content method. */\nexport declare interface EmbedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Type of task for which the embedding will be used.\n */\n taskType?: string;\n /** Title for the text. Only applicable when TaskType is\n `RETRIEVAL_DOCUMENT`.\n */\n title?: string;\n /** Reduced dimension for the output embedding. If set,\n excessive values in the output embedding are truncated from the end.\n Supported by newer models since 2024 only. You cannot set this value if\n using the earlier model (`models/embedding-001`).\n */\n outputDimensionality?: number;\n /** Vertex API only. The MIME type of the input.\n */\n mimeType?: string;\n /** Vertex API only. Whether to silently truncate inputs longer than\n the max sequence length. If this option is set to false, oversized inputs\n will lead to an INVALID_ARGUMENT error, similar to other text APIs.\n */\n autoTruncate?: boolean;\n}\n\n/** Parameters for the embed_content method. */\nexport declare interface EmbedContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The content to embed. Only the `parts.text` fields will be counted.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional parameters.\n */\n config?: EmbedContentConfig;\n}\n\n/** Statistics of the input text associated with the result of content embedding. */\nexport declare interface ContentEmbeddingStatistics {\n /** Vertex API only. If the input text was truncated due to having\n a length longer than the allowed maximum input.\n */\n truncated?: boolean;\n /** Vertex API only. Number of tokens of the input text.\n */\n tokenCount?: number;\n}\n\n/** The embedding generated from an input content. */\nexport declare interface ContentEmbedding {\n /** A list of floats representing an embedding.\n */\n values?: number[];\n /** Vertex API only. Statistics of the input text associated with this\n embedding.\n */\n statistics?: ContentEmbeddingStatistics;\n}\n\n/** Request-level metadata for the Vertex Embed Content API. */\nexport declare interface EmbedContentMetadata {\n /** Vertex API only. The total number of billable characters included\n in the request.\n */\n billableCharacterCount?: number;\n}\n\n/** Response for the embed_content method. */\nexport class EmbedContentResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** The embeddings for each request, in the same order as provided in\n the batch request.\n */\n embeddings?: ContentEmbedding[];\n /** Vertex API only. Metadata about the request.\n */\n metadata?: EmbedContentMetadata;\n}\n\n/** The config for generating an images. */\nexport declare interface GenerateImagesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage URI used to store the generated images.\n */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images.\n */\n negativePrompt?: string;\n /** Number of images to generate.\n */\n numberOfImages?: number;\n /** Aspect ratio of the generated images. Supported values are\n \"1:1\", \"3:4\", \"4:3\", \"9:16\", and \"16:9\".\n */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality.\n */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true.\n */\n seed?: number;\n /** Filter level for safety filtering.\n */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model.\n */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response.\n */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response.\n */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt.\n */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image.\n */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only).\n */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images.\n */\n addWatermark?: boolean;\n /** The size of the largest dimension of the generated image.\n Supported sizes are 1K and 2K (not supported for Imagen 3 models).\n */\n imageSize?: string;\n /** Whether to use the prompt rewriting logic.\n */\n enhancePrompt?: boolean;\n}\n\n/** The parameters for generating images. */\nexport declare interface GenerateImagesParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Text prompt that typically describes the images to output.\n */\n prompt: string;\n /** Configuration for generating images.\n */\n config?: GenerateImagesConfig;\n}\n\n/** An image. */\nexport declare interface Image {\n /** The Cloud Storage URI of the image. ``Image`` can contain a value\n for this field or the ``image_bytes`` field but not both.\n */\n gcsUri?: string;\n /** The image bytes data. ``Image`` can contain a value for this field\n or the ``gcs_uri`` field but not both.\n \n * @remarks Encoded as base64 string. */\n imageBytes?: string;\n /** The MIME type of the image. */\n mimeType?: string;\n}\n\n/** Safety attributes of a GeneratedImage or the user-provided prompt. */\nexport declare interface SafetyAttributes {\n /** List of RAI categories.\n */\n categories?: string[];\n /** List of scores of each categories.\n */\n scores?: number[];\n /** Internal use only.\n */\n contentType?: string;\n}\n\n/** An output image. */\nexport declare interface GeneratedImage {\n /** The output image data.\n */\n image?: Image;\n /** Responsible AI filter reason if the image is filtered out of the\n response.\n */\n raiFilteredReason?: string;\n /** Safety attributes of the image. Lists of RAI categories and their\n scores of each content.\n */\n safetyAttributes?: SafetyAttributes;\n /** The rewritten prompt used for the image generation if the prompt\n enhancer is enabled.\n */\n enhancedPrompt?: string;\n}\n\n/** The output images response. */\nexport class GenerateImagesResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** List of generated images.\n */\n generatedImages?: GeneratedImage[];\n /** Safety attributes of the positive prompt. Only populated if\n ``include_safety_attributes`` is set to True.\n */\n positivePromptSafetyAttributes?: SafetyAttributes;\n}\n\n/** Configuration for a Mask reference image. */\nexport declare interface MaskReferenceConfig {\n /** Prompts the model to generate a mask instead of you needing to\n provide one (unless MASK_MODE_USER_PROVIDED is used). */\n maskMode?: MaskReferenceMode;\n /** A list of up to 5 class ids to use for semantic segmentation.\n Automatically creates an image mask based on specific objects. */\n segmentationClasses?: number[];\n /** Dilation percentage of the mask provided.\n Float between 0 and 1. */\n maskDilation?: number;\n}\n\n/** Configuration for a Control reference image. */\nexport declare interface ControlReferenceConfig {\n /** The type of control reference image to use. */\n controlType?: ControlReferenceType;\n /** Defaults to False. When set to True, the control image will be\n computed by the model based on the control type. When set to False,\n the control image must be provided by the user. */\n enableControlImageComputation?: boolean;\n}\n\n/** Configuration for a Style reference image. */\nexport declare interface StyleReferenceConfig {\n /** A text description of the style to use for the generated image. */\n styleDescription?: string;\n}\n\n/** Configuration for a Subject reference image. */\nexport declare interface SubjectReferenceConfig {\n /** The subject type of a subject reference image. */\n subjectType?: SubjectReferenceType;\n /** Subject description for the image. */\n subjectDescription?: string;\n}\n\n/** Configuration for editing an image. */\nexport declare interface EditImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage URI used to store the generated images.\n */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images.\n */\n negativePrompt?: string;\n /** Number of images to generate.\n */\n numberOfImages?: number;\n /** Aspect ratio of the generated images. Supported values are\n \"1:1\", \"3:4\", \"4:3\", \"9:16\", and \"16:9\".\n */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality.\n */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true.\n */\n seed?: number;\n /** Filter level for safety filtering.\n */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model.\n */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response.\n */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response.\n */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt.\n */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image.\n */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only).\n */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images.\n */\n addWatermark?: boolean;\n /** Describes the editing mode for the request. */\n editMode?: EditMode;\n /** The number of sampling steps. A higher value has better image\n quality, while a lower value has better latency. */\n baseSteps?: number;\n}\n\n/** Response for the request to edit an image. */\nexport class EditImageResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Generated images. */\n generatedImages?: GeneratedImage[];\n}\n\nexport class UpscaleImageResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Generated images. */\n generatedImages?: GeneratedImage[];\n}\n\n/** An image of the product. */\nexport declare interface ProductImage {\n /** An image of the product to be recontextualized. */\n productImage?: Image;\n}\n\n/** A set of source input(s) for image recontextualization. */\nexport declare interface RecontextImageSource {\n /** A text prompt for guiding the model during image\n recontextualization. Not supported for Virtual Try-On. */\n prompt?: string;\n /** Image of the person or subject who will be wearing the\n product(s). */\n personImage?: Image;\n /** A list of product images. */\n productImages?: ProductImage[];\n}\n\n/** Configuration for recontextualizing an image. */\nexport declare interface RecontextImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Number of images to generate. */\n numberOfImages?: number;\n /** The number of sampling steps. A higher value has better image\n quality, while a lower value has better latency. */\n baseSteps?: number;\n /** Cloud Storage URI used to store the generated images. */\n outputGcsUri?: string;\n /** Random seed for image generation. */\n seed?: number;\n /** Filter level for safety filtering. */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Whether allow to generate person images, and restrict to specific\n ages. */\n personGeneration?: PersonGeneration;\n /** MIME type of the generated image. */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only). */\n outputCompressionQuality?: number;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n}\n\n/** The parameters for recontextualizing an image. */\nexport declare interface RecontextImageParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** A set of source input(s) for image recontextualization. */\n source: RecontextImageSource;\n /** Configuration for image recontextualization. */\n config?: RecontextImageConfig;\n}\n\n/** The output images response. */\nexport class RecontextImageResponse {\n /** List of generated images. */\n generatedImages?: GeneratedImage[];\n}\n\n/** An image mask representing a brush scribble. */\nexport declare interface ScribbleImage {\n /** The brush scribble to guide segmentation. Valid for the interactive mode. */\n image?: Image;\n}\n\n/** A set of source input(s) for image segmentation. */\nexport declare interface SegmentImageSource {\n /** A text prompt for guiding the model during image segmentation.\n Required for prompt mode and semantic mode, disallowed for other modes. */\n prompt?: string;\n /** The image to be segmented. */\n image?: Image;\n /** The brush scribble to guide segmentation.\n Required for the interactive mode, disallowed for other modes. */\n scribbleImage?: ScribbleImage;\n}\n\n/** Configuration for segmenting an image. */\nexport declare interface SegmentImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The segmentation mode to use. */\n mode?: SegmentMode;\n /** The maximum number of predictions to return up to, by top\n confidence score. */\n maxPredictions?: number;\n /** The confidence score threshold for the detections as a decimal\n value. Only predictions with a confidence score higher than this\n threshold will be returned. */\n confidenceThreshold?: number;\n /** A decimal value representing how much dilation to apply to the\n masks. 0 for no dilation. 1.0 means the masked area covers the whole\n image. */\n maskDilation?: number;\n /** The binary color threshold to apply to the masks. The threshold\n can be set to a decimal value between 0 and 255 non-inclusive.\n Set to -1 for no binary color thresholding. */\n binaryColorThreshold?: number;\n}\n\n/** The parameters for segmenting an image. */\nexport declare interface SegmentImageParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** A set of source input(s) for image segmentation. */\n source: SegmentImageSource;\n /** Configuration for image segmentation. */\n config?: SegmentImageConfig;\n}\n\n/** An entity representing the segmented area. */\nexport declare interface EntityLabel {\n /** The label of the segmented entity. */\n label?: string;\n /** The confidence score of the detected label. */\n score?: number;\n}\n\n/** A generated image mask. */\nexport declare interface GeneratedImageMask {\n /** The generated image mask. */\n mask?: Image;\n /** The detected entities on the segmented area. */\n labels?: EntityLabel[];\n}\n\n/** The output images response. */\nexport class SegmentImageResponse {\n /** List of generated image masks.\n */\n generatedMasks?: GeneratedImageMask[];\n}\n\n/** Optional parameters for models.get method. */\nexport declare interface GetModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\nexport declare interface GetModelParameters {\n model: string;\n /** Optional parameters for the request. */\n config?: GetModelConfig;\n}\n\n/** An endpoint where you deploy models. */\nexport declare interface Endpoint {\n /** Resource name of the endpoint. */\n name?: string;\n /** ID of the model that's deployed to the endpoint. */\n deployedModelId?: string;\n}\n\n/** A tuned machine learning model. */\nexport declare interface TunedModelInfo {\n /** ID of the base model that you want to tune. */\n baseModel?: string;\n /** Date and time when the base model was created. */\n createTime?: string;\n /** Date and time when the base model was last updated. */\n updateTime?: string;\n}\n\n/** Describes the machine learning model version checkpoint. */\nexport declare interface Checkpoint {\n /** The ID of the checkpoint.\n */\n checkpointId?: string;\n /** The epoch of the checkpoint.\n */\n epoch?: string;\n /** The step of the checkpoint.\n */\n step?: string;\n}\n\n/** A trained machine learning model. */\nexport declare interface Model {\n /** Resource name of the model. */\n name?: string;\n /** Display name of the model. */\n displayName?: string;\n /** Description of the model. */\n description?: string;\n /** Version ID of the model. A new version is committed when a new\n model version is uploaded or trained under an existing model ID. The\n version ID is an auto-incrementing decimal number in string\n representation. */\n version?: string;\n /** List of deployed models created from this base model. Note that a\n model could have been deployed to endpoints in different locations. */\n endpoints?: Endpoint[];\n /** Labels with user-defined metadata to organize your models. */\n labels?: Record;\n /** Information about the tuned model from the base model. */\n tunedModelInfo?: TunedModelInfo;\n /** The maximum number of input tokens that the model can handle. */\n inputTokenLimit?: number;\n /** The maximum number of output tokens that the model can generate. */\n outputTokenLimit?: number;\n /** List of actions that are supported by the model. */\n supportedActions?: string[];\n /** The default checkpoint id of a model version.\n */\n defaultCheckpointId?: string;\n /** The checkpoints of the model. */\n checkpoints?: Checkpoint[];\n}\n\nexport declare interface ListModelsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n /** Set true to list base models, false to list tuned models. */\n queryBase?: boolean;\n}\n\nexport declare interface ListModelsParameters {\n config?: ListModelsConfig;\n}\n\nexport class ListModelsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n models?: Model[];\n}\n\n/** Configuration for updating a tuned model. */\nexport declare interface UpdateModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n displayName?: string;\n description?: string;\n defaultCheckpointId?: string;\n}\n\n/** Configuration for updating a tuned model. */\nexport declare interface UpdateModelParameters {\n model: string;\n config?: UpdateModelConfig;\n}\n\n/** Configuration for deleting a tuned model. */\nexport declare interface DeleteModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for deleting a tuned model. */\nexport declare interface DeleteModelParameters {\n model: string;\n /** Optional parameters for the request. */\n config?: DeleteModelConfig;\n}\n\nexport class DeleteModelResponse {}\n\n/** Config for thinking features. */\nexport declare interface GenerationConfigThinkingConfig {\n /** Optional. Indicates whether to include thoughts in the response. If true, thoughts are returned only when available. */\n includeThoughts?: boolean;\n /** Optional. Indicates the thinking budget in tokens. */\n thinkingBudget?: number;\n}\n\n/** Generation config. */\nexport declare interface GenerationConfig {\n /** Optional. Config for model selection. */\n modelSelectionConfig?: ModelSelectionConfig;\n /** Optional. If enabled, audio timestamp will be included in the request to the model. */\n audioTimestamp?: boolean;\n /** Optional. Number of candidates to generate. */\n candidateCount?: number;\n /** Optional. If enabled, the model will detect emotions and adapt its responses accordingly. */\n enableAffectiveDialog?: boolean;\n /** Optional. Frequency penalties. */\n frequencyPenalty?: number;\n /** Optional. Logit probabilities. */\n logprobs?: number;\n /** Optional. The maximum number of output tokens to generate per message. */\n maxOutputTokens?: number;\n /** Optional. If specified, the media resolution specified will be used. */\n mediaResolution?: MediaResolution;\n /** Optional. Positive penalties. */\n presencePenalty?: number;\n /** Optional. Output schema of the generated response. This is an alternative to `response_schema` that accepts [JSON Schema](https://json-schema.org/). If set, `response_schema` must be omitted, but `response_mime_type` is required. While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` - `type` - `format` - `title` - `description` - `enum` (for strings and numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - `properties` - `additionalProperties` - `required` The non-standard `propertyOrdering` property may also be set. Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If `$ref` is set on a sub-schema, no other properties, except for than those starting as a `$`, may be set. */\n responseJsonSchema?: unknown;\n /** Optional. If true, export the logprobs results in response. */\n responseLogprobs?: boolean;\n /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */\n responseMimeType?: string;\n /** Optional. The modalities of the response. */\n responseModalities?: Modality[];\n /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */\n responseSchema?: Schema;\n /** Optional. Routing configuration. */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Optional. Seed. */\n seed?: number;\n /** Optional. The speech generation config. */\n speechConfig?: SpeechConfig;\n /** Optional. Stop sequences. */\n stopSequences?: string[];\n /** Optional. Controls the randomness of predictions. */\n temperature?: number;\n /** Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking. */\n thinkingConfig?: GenerationConfigThinkingConfig;\n /** Optional. If specified, top-k sampling will be used. */\n topK?: number;\n /** Optional. If specified, nucleus sampling will be used. */\n topP?: number;\n}\n\n/** Config for the count_tokens method. */\nexport declare interface CountTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Instructions for the model to steer it toward better performance.\n */\n systemInstruction?: ContentUnion;\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: Tool[];\n /** Configuration that the model uses to generate the response. Not\n supported by the Gemini Developer API.\n */\n generationConfig?: GenerationConfig;\n}\n\n/** Parameters for counting tokens. */\nexport declare interface CountTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Configuration for counting tokens. */\n config?: CountTokensConfig;\n}\n\n/** Response for counting tokens. */\nexport class CountTokensResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Total number of tokens. */\n totalTokens?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n}\n\n/** Optional parameters for computing tokens. */\nexport declare interface ComputeTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for computing tokens. */\nexport declare interface ComputeTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Optional parameters for the request.\n */\n config?: ComputeTokensConfig;\n}\n\n/** Tokens info with a list of tokens and the corresponding list of token ids. */\nexport declare interface TokensInfo {\n /** Optional. Optional fields for the role from the corresponding Content. */\n role?: string;\n /** A list of token ids from the input. */\n tokenIds?: string[];\n /** A list of tokens from the input.\n * @remarks Encoded as base64 string. */\n tokens?: string[];\n}\n\n/** Response for computing tokens. */\nexport class ComputeTokensResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */\n tokensInfo?: TokensInfo[];\n}\n\n/** A generated video. */\nexport declare interface Video {\n /** Path to another storage. */\n uri?: string;\n /** Video bytes.\n * @remarks Encoded as base64 string. */\n videoBytes?: string;\n /** Video encoding, for example \"video/mp4\". */\n mimeType?: string;\n}\n\n/** A reference image for video generation. */\nexport declare interface VideoGenerationReferenceImage {\n /** The reference image.\n */\n image?: Image;\n /** The type of the reference image, which defines how the reference\n image will be used to generate the video. Supported values are 'asset'\n or 'style'. */\n referenceType?: string;\n}\n\n/** Configuration for generating videos. */\nexport declare interface GenerateVideosConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Number of output videos. */\n numberOfVideos?: number;\n /** The gcs bucket where to save the generated videos. */\n outputGcsUri?: string;\n /** Frames per second for video generation. */\n fps?: number;\n /** Duration of the clip for video generation in seconds. */\n durationSeconds?: number;\n /** The RNG seed. If RNG seed is exactly same for each request with unchanged inputs, the prediction results will be consistent. Otherwise, a random RNG seed will be used each time to produce a different result. */\n seed?: number;\n /** The aspect ratio for the generated video. 16:9 (landscape) and 9:16 (portrait) are supported. */\n aspectRatio?: string;\n /** The resolution for the generated video. 720p and 1080p are supported. */\n resolution?: string;\n /** Whether allow to generate person videos, and restrict to specific ages. Supported values are: dont_allow, allow_adult. */\n personGeneration?: string;\n /** The pubsub topic where to publish the video generation progress. */\n pubsubTopic?: string;\n /** Optional field in addition to the text content. Negative prompts can be explicitly stated here to help generate the video. */\n negativePrompt?: string;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n /** Whether to generate audio along with the video. */\n generateAudio?: boolean;\n /** Image to use as the last frame of generated videos. Only supported for image to video use cases. */\n lastFrame?: Image;\n /** The images to use as the references to generate the videos.\n If this field is provided, the text prompt field must also be provided.\n The image, video, or last_frame field are not supported. Each image must\n be associated with a type. Veo 2 supports up to 3 asset images *or* 1\n style image. */\n referenceImages?: VideoGenerationReferenceImage[];\n /** Compression quality of the generated videos. */\n compressionQuality?: VideoCompressionQuality;\n}\n\n/** Class that represents the parameters for generating videos. */\nexport declare interface GenerateVideosParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The text prompt for generating the videos. Optional for image to video use cases. */\n prompt?: string;\n /** The input image for generating the videos.\n Optional if prompt or video is provided. */\n image?: Image;\n /** The input video for video extension use cases.\n Optional if prompt or image is provided. */\n video?: Video;\n /** Configuration for generating videos. */\n config?: GenerateVideosConfig;\n}\n\n/** A generated video. */\nexport declare interface GeneratedVideo {\n /** The output video */\n video?: Video;\n}\n\n/** Response with generated videos. */\nexport class GenerateVideosResponse {\n /** List of the generated videos */\n generatedVideos?: GeneratedVideo[];\n /** Returns if any videos were filtered due to RAI policies. */\n raiMediaFilteredCount?: number;\n /** Returns rai failure reasons if any. */\n raiMediaFilteredReasons?: string[];\n}\n\n/** Optional parameters for tunings.get method. */\nexport declare interface GetTuningJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the get method. */\nexport declare interface GetTuningJobParameters {\n name: string;\n /** Optional parameters for the request. */\n config?: GetTuningJobConfig;\n}\n\n/** TunedModelCheckpoint for the Tuned Model of a Tuning Job. */\nexport declare interface TunedModelCheckpoint {\n /** The ID of the checkpoint.\n */\n checkpointId?: string;\n /** The epoch of the checkpoint.\n */\n epoch?: string;\n /** The step of the checkpoint.\n */\n step?: string;\n /** The Endpoint resource name that the checkpoint is deployed to.\n Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`.\n */\n endpoint?: string;\n}\n\nexport declare interface TunedModel {\n /** Output only. The resource name of the TunedModel. Format: `projects/{project}/locations/{location}/models/{model}@{version_id}` When tuning from a base model, the version_id will be 1. For continuous tuning, the version id will be incremented by 1 from the last version id in the parent model. E.g., `projects/{project}/locations/{location}/models/{model}@{last_version_id + 1}` */\n model?: string;\n /** Output only. A resource name of an Endpoint. Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. */\n endpoint?: string;\n /** The checkpoints associated with this TunedModel.\n This field is only populated for tuning jobs that enable intermediate\n checkpoints. */\n checkpoints?: TunedModelCheckpoint[];\n}\n\n/** The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). */\nexport declare interface GoogleRpcStatus {\n /** The status code, which should be an enum value of google.rpc.Code. */\n code?: number;\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */\n message?: string;\n}\n\n/** A pre-tuned model for continuous tuning. */\nexport declare interface PreTunedModel {\n /** Output only. The name of the base model this PreTunedModel was tuned from. */\n baseModel?: string;\n /** Optional. The source checkpoint id. If not specified, the default checkpoint will be used. */\n checkpointId?: string;\n /** The resource name of the Model. E.g., a model resource name with a specified version id or alias: `projects/{project}/locations/{location}/models/{model}@{version_id}` `projects/{project}/locations/{location}/models/{model}@{alias}` Or, omit the version id to use the default version: `projects/{project}/locations/{location}/models/{model}` */\n tunedModelName?: string;\n}\n\n/** Hyperparameters for SFT. */\nexport declare interface SupervisedHyperParameters {\n /** Optional. Adapter size for tuning. */\n adapterSize?: AdapterSize;\n /** Optional. Batch size for tuning. This feature is only available for open source models. */\n batchSize?: string;\n /** Optional. Number of complete passes the model makes over the entire training dataset during training. */\n epochCount?: string;\n /** Optional. Learning rate for tuning. Mutually exclusive with `learning_rate_multiplier`. This feature is only available for open source models. */\n learningRate?: number;\n /** Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with `learning_rate`. This feature is only available for 1P models. */\n learningRateMultiplier?: number;\n}\n\n/** Tuning Spec for Supervised Tuning for first party models. */\nexport declare interface SupervisedTuningSpec {\n /** Optional. If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. Default is false. */\n exportLastCheckpointOnly?: boolean;\n /** Optional. Hyperparameters for SFT. */\n hyperParameters?: SupervisedHyperParameters;\n /** Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n trainingDatasetUri?: string;\n /** Tuning mode. */\n tuningMode?: TuningMode;\n /** Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n validationDatasetUri?: string;\n}\n\n/** Dataset bucket used to create a histogram for the distribution given a population of values. */\nexport declare interface DatasetDistributionDistributionBucket {\n /** Output only. Number of values in the bucket. */\n count?: string;\n /** Output only. Left bound of the bucket. */\n left?: number;\n /** Output only. Right bound of the bucket. */\n right?: number;\n}\n\n/** Distribution computed over a tuning dataset. */\nexport declare interface DatasetDistribution {\n /** Output only. Defines the histogram bucket. */\n buckets?: DatasetDistributionDistributionBucket[];\n /** Output only. The maximum of the population values. */\n max?: number;\n /** Output only. The arithmetic mean of the values in the population. */\n mean?: number;\n /** Output only. The median of the values in the population. */\n median?: number;\n /** Output only. The minimum of the population values. */\n min?: number;\n /** Output only. The 5th percentile of the values in the population. */\n p5?: number;\n /** Output only. The 95th percentile of the values in the population. */\n p95?: number;\n /** Output only. Sum of a given population of values. */\n sum?: number;\n}\n\n/** Statistics computed over a tuning dataset. */\nexport declare interface DatasetStats {\n /** Output only. Number of billable characters in the tuning dataset. */\n totalBillableCharacterCount?: string;\n /** Output only. Number of tuning characters in the tuning dataset. */\n totalTuningCharacterCount?: string;\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user messages in the training dataset uri. */\n userDatasetExamples?: Content[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the messages per example. */\n userMessagePerExampleDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: DatasetDistribution;\n}\n\n/** Statistics computed for datasets used for distillation. */\nexport declare interface DistillationDataStats {\n /** Output only. Statistics computed for the training dataset. */\n trainingDatasetStats?: DatasetStats;\n}\n\n/** Completion and its preference score. */\nexport declare interface GeminiPreferenceExampleCompletion {\n /** Single turn completion for the given prompt. */\n completion?: Content;\n /** The score for the given completion. */\n score?: number;\n}\n\n/** Input example for preference optimization. */\nexport declare interface GeminiPreferenceExample {\n /** List of completions for a given prompt. */\n completions?: GeminiPreferenceExampleCompletion[];\n /** Multi-turn contents that represents the Prompt. */\n contents?: Content[];\n}\n\n/** Statistics computed for datasets used for preference optimization. */\nexport declare interface PreferenceOptimizationDataStats {\n /** Output only. Dataset distributions for scores variance per example. */\n scoreVariancePerExampleDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for scores. */\n scoresDistribution?: DatasetDistribution;\n /** Output only. Number of billable tokens in the tuning dataset. */\n totalBillableTokenCount?: string;\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user examples in the training dataset. */\n userDatasetExamples?: GeminiPreferenceExample[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: DatasetDistribution;\n}\n\n/** Dataset bucket used to create a histogram for the distribution given a population of values. */\nexport declare interface SupervisedTuningDatasetDistributionDatasetBucket {\n /** Output only. Number of values in the bucket. */\n count?: number;\n /** Output only. Left bound of the bucket. */\n left?: number;\n /** Output only. Right bound of the bucket. */\n right?: number;\n}\n\n/** Dataset distribution for Supervised Tuning. */\nexport declare interface SupervisedTuningDatasetDistribution {\n /** Output only. Sum of a given population of values that are billable. */\n billableSum?: string;\n /** Output only. Defines the histogram bucket. */\n buckets?: SupervisedTuningDatasetDistributionDatasetBucket[];\n /** Output only. The maximum of the population values. */\n max?: number;\n /** Output only. The arithmetic mean of the values in the population. */\n mean?: number;\n /** Output only. The median of the values in the population. */\n median?: number;\n /** Output only. The minimum of the population values. */\n min?: number;\n /** Output only. The 5th percentile of the values in the population. */\n p5?: number;\n /** Output only. The 95th percentile of the values in the population. */\n p95?: number;\n /** Output only. Sum of a given population of values. */\n sum?: string;\n}\n\n/** Tuning data statistics for Supervised Tuning. */\nexport declare interface SupervisedTuningDataStats {\n /** Output only. For each index in `truncated_example_indices`, the user-facing reason why the example was dropped. */\n droppedExampleReasons?: string[];\n /** Output only. Number of billable characters in the tuning dataset. */\n totalBillableCharacterCount?: string;\n /** Output only. Number of billable tokens in the tuning dataset. */\n totalBillableTokenCount?: string;\n /** Output only. The number of examples in the dataset that have been dropped. An example can be dropped for reasons including: too many tokens, contains an invalid image, contains too many images, etc. */\n totalTruncatedExampleCount?: string;\n /** Output only. Number of tuning characters in the tuning dataset. */\n totalTuningCharacterCount?: string;\n /** Output only. A partial sample of the indices (starting from 1) of the dropped examples. */\n truncatedExampleIndices?: string[];\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user messages in the training dataset uri. */\n userDatasetExamples?: Content[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: SupervisedTuningDatasetDistribution;\n /** Output only. Dataset distributions for the messages per example. */\n userMessagePerExampleDistribution?: SupervisedTuningDatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: SupervisedTuningDatasetDistribution;\n}\n\n/** The tuning data statistic values for TuningJob. */\nexport declare interface TuningDataStats {\n /** Output only. Statistics for distillation. */\n distillationDataStats?: DistillationDataStats;\n /** Output only. Statistics for preference optimization. */\n preferenceOptimizationDataStats?: PreferenceOptimizationDataStats;\n /** The SFT Tuning data stats. */\n supervisedTuningDataStats?: SupervisedTuningDataStats;\n}\n\n/** Represents a customer-managed encryption key spec that can be applied to a top-level resource. */\nexport declare interface EncryptionSpec {\n /** Required. The Cloud KMS resource identifier of the customer managed encryption key used to protect a resource. Has the form: `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`. The key needs to be in the same region as where the compute resource is created. */\n kmsKeyName?: string;\n}\n\n/** Tuning spec for Partner models. */\nexport declare interface PartnerModelTuningSpec {\n /** Hyperparameters for tuning. The accepted hyper_parameters and their valid range of values will differ depending on the base model. */\n hyperParameters?: Record;\n /** Required. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDatasetUri?: string;\n /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */\n validationDatasetUri?: string;\n}\n\n/** A tuning job. */\nexport declare interface TuningJob {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}` */\n name?: string;\n /** Output only. The detailed state of the job. */\n state?: JobState;\n /** Output only. Time when the TuningJob was created. */\n createTime?: string;\n /** Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING` state. */\n startTime?: string;\n /** Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`. */\n endTime?: string;\n /** Output only. Time when the TuningJob was most recently updated. */\n updateTime?: string;\n /** Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. */\n error?: GoogleRpcStatus;\n /** Optional. The description of the TuningJob. */\n description?: string;\n /** The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */\n baseModel?: string;\n /** Output only. The tuned model resources associated with this TuningJob. */\n tunedModel?: TunedModel;\n /** The pre-tuned model for continuous tuning. */\n preTunedModel?: PreTunedModel;\n /** Tuning Spec for Supervised Fine Tuning. */\n supervisedTuningSpec?: SupervisedTuningSpec;\n /** Output only. The tuning data statistics associated with this TuningJob. */\n tuningDataStats?: TuningDataStats;\n /** Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with the provided encryption key. */\n encryptionSpec?: EncryptionSpec;\n /** Tuning Spec for open sourced and third party Partner models. */\n partnerModelTuningSpec?: PartnerModelTuningSpec;\n /** Optional. The user-provided path to custom model weights. Set this field to tune a custom model. The path must be a Cloud Storage directory that contains the model weights in .safetensors format along with associated model metadata files. If this field is set, the base_model field must still be set to indicate which base model the custom model is derived from. This feature is only available for open source models. */\n customBaseModel?: string;\n /** Output only. The Experiment associated with this TuningJob. */\n experiment?: string;\n /** Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. */\n labels?: Record;\n /** Optional. Cloud Storage path to the directory where tuning job outputs are written to. This field is only available and required for open source models. */\n outputUri?: string;\n /** Output only. The resource name of the PipelineJob associated with the TuningJob. Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`. */\n pipelineJob?: string;\n /** The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission on this service account. */\n serviceAccount?: string;\n /** Optional. The display name of the TunedModel. The name can be up to 128 characters long and can consist of any UTF-8 characters. */\n tunedModelDisplayName?: string;\n}\n\n/** Configuration for the list tuning jobs method. */\nexport declare interface ListTuningJobsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n}\n\n/** Parameters for the list tuning jobs method. */\nexport declare interface ListTuningJobsParameters {\n config?: ListTuningJobsConfig;\n}\n\n/** Response for the list tuning jobs method. */\nexport class ListTuningJobsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** A token to retrieve the next page of results. Pass to ListTuningJobsRequest.page_token to obtain that page. */\n nextPageToken?: string;\n /** List of TuningJobs in the requested page. */\n tuningJobs?: TuningJob[];\n}\n\nexport declare interface TuningExample {\n /** Text model input. */\n textInput?: string;\n /** The expected model output. */\n output?: string;\n}\n\n/** Supervised fine-tuning training dataset. */\nexport declare interface TuningDataset {\n /** GCS URI of the file containing training dataset in JSONL format. */\n gcsUri?: string;\n /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */\n vertexDatasetResource?: string;\n /** Inline examples with simple input/output text. */\n examples?: TuningExample[];\n}\n\nexport declare interface TuningValidationDataset {\n /** GCS URI of the file containing validation dataset in JSONL format. */\n gcsUri?: string;\n /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */\n vertexDatasetResource?: string;\n}\n\n/** Supervised fine-tuning job creation request - optional fields. */\nexport declare interface CreateTuningJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n validationDataset?: TuningValidationDataset;\n /** The display name of the tuned Model. The name can be up to 128 characters long and can consist of any UTF-8 characters. */\n tunedModelDisplayName?: string;\n /** The description of the TuningJob */\n description?: string;\n /** Number of complete passes the model makes over the entire training dataset during training. */\n epochCount?: number;\n /** Multiplier for adjusting the default learning rate. */\n learningRateMultiplier?: number;\n /** If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. */\n exportLastCheckpointOnly?: boolean;\n /** The optional checkpoint id of the pre-tuned model to use for tuning, if applicable. */\n preTunedModelCheckpointId?: string;\n /** Adapter size for tuning. */\n adapterSize?: AdapterSize;\n /** The batch size hyperparameter for tuning. If not set, a default of 4 or 16 will be used based on the number of training examples. */\n batchSize?: number;\n /** The learning rate hyperparameter for tuning. If not set, a default of 0.001 or 0.0002 will be calculated based on the number of training examples. */\n learningRate?: number;\n}\n\n/** Supervised fine-tuning job creation parameters - optional fields. */\nexport declare interface CreateTuningJobParametersPrivate {\n /** The base model that is being tuned, e.g., \"gemini-2.5-flash\". */\n baseModel?: string;\n /** The PreTunedModel that is being tuned. */\n preTunedModel?: PreTunedModel;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDataset: TuningDataset;\n /** Configuration for the tuning job. */\n config?: CreateTuningJobConfig;\n}\n\n/** A long-running operation. */\nexport declare interface TuningOperation {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n}\n\n/** Optional configuration for cached content creation. */\nexport declare interface CreateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n /** The user-generated meaningful display name of the cached content.\n */\n displayName?: string;\n /** The content to cache.\n */\n contents?: ContentListUnion;\n /** Developer set system instruction.\n */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n */\n tools?: Tool[];\n /** Configuration for the tools to use. This config is shared for all tools.\n */\n toolConfig?: ToolConfig;\n /** The Cloud KMS resource identifier of the customer managed\n encryption key used to protect a resource.\n The key needs to be in the same region as where the compute resource is\n created. See\n https://cloud.google.com/vertex-ai/docs/general/cmek for more\n details. If this is set, then all created CachedContent objects\n will be encrypted with the provided encryption key.\n Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}\n */\n kmsKeyName?: string;\n}\n\n/** Parameters for caches.create method. */\nexport declare interface CreateCachedContentParameters {\n /** ID of the model to use. Example: gemini-2.0-flash */\n model: string;\n /** Configuration that contains optional parameters.\n */\n config?: CreateCachedContentConfig;\n}\n\n/** Metadata on the usage of the cached content. */\nexport declare interface CachedContentUsageMetadata {\n /** Duration of audio in seconds. */\n audioDurationSeconds?: number;\n /** Number of images. */\n imageCount?: number;\n /** Number of text characters. */\n textCount?: number;\n /** Total number of tokens that the cached content consumes. */\n totalTokenCount?: number;\n /** Duration of video in seconds. */\n videoDurationSeconds?: number;\n}\n\n/** A resource used in LLM queries for users to explicitly specify what to cache. */\nexport declare interface CachedContent {\n /** The server-generated resource name of the cached content. */\n name?: string;\n /** The user-generated meaningful display name of the cached content. */\n displayName?: string;\n /** The name of the publisher model to use for cached content. */\n model?: string;\n /** Creation time of the cache entry. */\n createTime?: string;\n /** When the cache entry was last updated in UTC time. */\n updateTime?: string;\n /** Expiration time of the cached content. */\n expireTime?: string;\n /** Metadata on the usage of the cached content. */\n usageMetadata?: CachedContentUsageMetadata;\n}\n\n/** Optional parameters for caches.get method. */\nexport declare interface GetCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for caches.get method. */\nexport declare interface GetCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: GetCachedContentConfig;\n}\n\n/** Optional parameters for caches.delete method. */\nexport declare interface DeleteCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for caches.delete method. */\nexport declare interface DeleteCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: DeleteCachedContentConfig;\n}\n\n/** Empty response for caches.delete method. */\nexport class DeleteCachedContentResponse {}\n\n/** Optional parameters for caches.update method. */\nexport declare interface UpdateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n}\n\nexport declare interface UpdateCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Configuration that contains optional parameters.\n */\n config?: UpdateCachedContentConfig;\n}\n\n/** Config for caches.list method. */\nexport declare interface ListCachedContentsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Parameters for caches.list method. */\nexport declare interface ListCachedContentsParameters {\n /** Configuration that contains optional parameters.\n */\n config?: ListCachedContentsConfig;\n}\n\nexport class ListCachedContentsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n /** List of cached contents.\n */\n cachedContents?: CachedContent[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface ListFilesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Generates the parameters for the list method. */\nexport declare interface ListFilesParameters {\n /** Used to override the default configuration. */\n config?: ListFilesConfig;\n}\n\n/** Status of a File that uses a common error model. */\nexport declare interface FileStatus {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n message?: string;\n /** The status code. 0 for OK, 1 for CANCELLED */\n code?: number;\n}\n\n/** A file uploaded to the API. */\nexport declare interface File {\n /** The `File` resource name. The ID (name excluding the \"files/\" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */\n name?: string;\n /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */\n displayName?: string;\n /** Output only. MIME type of the file. */\n mimeType?: string;\n /** Output only. Size of the file in bytes. */\n sizeBytes?: string;\n /** Output only. The timestamp of when the `File` was created. */\n createTime?: string;\n /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */\n expirationTime?: string;\n /** Output only. The timestamp of when the `File` was last updated. */\n updateTime?: string;\n /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */\n sha256Hash?: string;\n /** Output only. The URI of the `File`. */\n uri?: string;\n /** Output only. The URI of the `File`, only set for downloadable (generated) files. */\n downloadUri?: string;\n /** Output only. Processing state of the File. */\n state?: FileState;\n /** Output only. The source of the `File`. */\n source?: FileSource;\n /** Output only. Metadata for a video. */\n videoMetadata?: Record;\n /** Output only. Error status if File processing failed. */\n error?: FileStatus;\n}\n\n/** Response for the list files method. */\nexport class ListFilesResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** A token to retrieve next page of results. */\n nextPageToken?: string;\n /** The list of files. */\n files?: File[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface CreateFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the private _create method. */\nexport declare interface CreateFileParameters {\n /** The file to be uploaded.\n mime_type: (Required) The MIME type of the file. Must be provided.\n name: (Optional) The name of the file in the destination (e.g.\n 'files/sample-image').\n display_name: (Optional) The display name of the file.\n */\n file: File;\n /** Used to override the default configuration. */\n config?: CreateFileConfig;\n}\n\n/** Response for the create file method. */\nexport class CreateFileResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Used to override the default configuration. */\nexport declare interface GetFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface GetFileParameters {\n /** The name identifier for the file to retrieve. */\n name: string;\n /** Used to override the default configuration. */\n config?: GetFileConfig;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DeleteFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface DeleteFileParameters {\n /** The name identifier for the file to be deleted. */\n name: string;\n /** Used to override the default configuration. */\n config?: DeleteFileConfig;\n}\n\n/** Response for the delete file method. */\nexport class DeleteFileResponse {}\n\n/** Config for inlined request. */\nexport declare interface InlinedRequest {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model?: string;\n /** Content of the request.\n */\n contents?: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** Config for `src` parameter. */\nexport declare interface BatchJobSource {\n /** Storage format of the input files. Must be one of:\n 'jsonl', 'bigquery'.\n */\n format?: string;\n /** The Google Cloud Storage URIs to input files.\n */\n gcsUri?: string[];\n /** The BigQuery URI to input table.\n */\n bigqueryUri?: string;\n /** The Gemini Developer API's file resource name of the input data\n (e.g. \"files/12345\").\n */\n fileName?: string;\n /** The Gemini Developer API's inlined input data to run batch job.\n */\n inlinedRequests?: InlinedRequest[];\n}\n\n/** Job error. */\nexport declare interface JobError {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: string[];\n /** The status code. */\n code?: number;\n /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the `details` field. */\n message?: string;\n}\n\n/** Config for `inlined_responses` parameter. */\nexport class InlinedResponse {\n /** The response to the request.\n */\n response?: GenerateContentResponse;\n /** The error encountered while processing the request.\n */\n error?: JobError;\n}\n\n/** Config for `des` parameter. */\nexport declare interface BatchJobDestination {\n /** Storage format of the output files. Must be one of:\n 'jsonl', 'bigquery'.\n */\n format?: string;\n /** The Google Cloud Storage URI to the output file.\n */\n gcsUri?: string;\n /** The BigQuery URI to the output table.\n */\n bigqueryUri?: string;\n /** The Gemini Developer API's file resource name of the output data\n (e.g. \"files/12345\"). The file will be a JSONL file with a single response\n per line. The responses will be GenerateContentResponse messages formatted\n as JSON. The responses will be written in the same order as the input\n requests.\n */\n fileName?: string;\n /** The responses to the requests in the batch. Returned when the batch was\n built using inlined requests. The responses will be in the same order as\n the input requests.\n */\n inlinedResponses?: InlinedResponse[];\n}\n\n/** Config for optional parameters. */\nexport declare interface CreateBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The user-defined name of this BatchJob.\n */\n displayName?: string;\n /** GCS or BigQuery URI prefix for the output predictions. Example:\n \"gs://path/to/output/data\" or \"bq://projectId.bqDatasetId.bqTableId\".\n */\n dest?: BatchJobDestinationUnion;\n}\n\n/** Config for batches.create parameters. */\nexport declare interface CreateBatchJobParameters {\n /** The name of the model to produces the predictions via the BatchJob.\n */\n model?: string;\n /** GCS URI(-s) or BigQuery URI to your input data to run batch job.\n Example: \"gs://path/to/input/data\" or \"bq://projectId.bqDatasetId.bqTableId\".\n */\n src: BatchJobSourceUnion;\n /** Optional parameters for creating a BatchJob.\n */\n config?: CreateBatchJobConfig;\n}\n\n/** Config for batches.create return value. */\nexport declare interface BatchJob {\n /** The resource name of the BatchJob. Output only.\".\n */\n name?: string;\n /** The display name of the BatchJob.\n */\n displayName?: string;\n /** The state of the BatchJob.\n */\n state?: JobState;\n /** Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED. */\n error?: JobError;\n /** The time when the BatchJob was created.\n */\n createTime?: string;\n /** Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state. */\n startTime?: string;\n /** The time when the BatchJob was completed.\n */\n endTime?: string;\n /** The time when the BatchJob was last updated.\n */\n updateTime?: string;\n /** The name of the model that produces the predictions via the BatchJob.\n */\n model?: string;\n /** Configuration for the input data.\n */\n src?: BatchJobSource;\n /** Configuration for the output data.\n */\n dest?: BatchJobDestination;\n}\n\n/** Optional parameters. */\nexport declare interface GetBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.get parameters. */\nexport declare interface GetBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: GetBatchJobConfig;\n}\n\n/** Optional parameters. */\nexport declare interface CancelBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.cancel parameters. */\nexport declare interface CancelBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: CancelBatchJobConfig;\n}\n\n/** Config for optional parameters. */\nexport declare interface ListBatchJobsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n}\n\n/** Config for batches.list parameters. */\nexport declare interface ListBatchJobsParameters {\n config?: ListBatchJobsConfig;\n}\n\n/** Config for batches.list return value. */\nexport class ListBatchJobsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n batchJobs?: BatchJob[];\n}\n\n/** Optional parameters for models.get method. */\nexport declare interface DeleteBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.delete parameters. */\nexport declare interface DeleteBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: DeleteBatchJobConfig;\n}\n\n/** The return value of delete operation. */\nexport declare interface DeleteResourceJob {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n name?: string;\n done?: boolean;\n error?: JobError;\n}\n\nexport declare interface GetOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the GET method. */\nexport declare interface GetOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\nexport declare interface FetchPredictOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the fetchPredictOperation method. */\nexport declare interface FetchPredictOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n resourceName: string;\n /** Used to override the default configuration. */\n config?: FetchPredictOperationConfig;\n}\n\nexport declare interface TestTableItem {\n /** The name of the test. This is used to derive the replay id. */\n name?: string;\n /** The parameters to the test. Use pydantic models. */\n parameters?: Record;\n /** Expects an exception for MLDev matching the string. */\n exceptionIfMldev?: string;\n /** Expects an exception for Vertex matching the string. */\n exceptionIfVertex?: string;\n /** Use if you don't want to use the default replay id which is derived from the test name. */\n overrideReplayId?: string;\n /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */\n hasUnion?: boolean;\n /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */\n skipInApiMode?: string;\n /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */\n ignoreKeys?: string[];\n}\n\nexport declare interface TestTableFile {\n comment?: string;\n testMethod?: string;\n parameterNames?: string[];\n testTable?: TestTableItem[];\n}\n\n/** Represents a single request in a replay. */\nexport declare interface ReplayRequest {\n method?: string;\n url?: string;\n headers?: Record;\n bodySegments?: Record[];\n}\n\n/** Represents a single response in a replay. */\nexport class ReplayResponse {\n statusCode?: number;\n headers?: Record;\n bodySegments?: Record[];\n sdkResponseSegments?: Record[];\n}\n\n/** Represents a single interaction, request and response in a replay. */\nexport declare interface ReplayInteraction {\n request?: ReplayRequest;\n response?: ReplayResponse;\n}\n\n/** Represents a recorded session. */\nexport declare interface ReplayFile {\n replayId?: string;\n interactions?: ReplayInteraction[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface UploadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */\n name?: string;\n /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */\n mimeType?: string;\n /** Optional display name of the file. */\n displayName?: string;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DownloadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters used to download a file. */\nexport declare interface DownloadFileParameters {\n /** The file to download. It can be a file name, a file object or a generated video. */\n file: DownloadableFileUnion;\n /** Location where the file should be downloaded to. */\n downloadPath: string;\n /** Configuration to for the download operation. */\n config?: DownloadFileConfig;\n}\n\n/** Configuration for upscaling an image.\n\n For more information on this configuration, refer to\n the `Imagen API reference documentation\n `_.\n */\nexport declare interface UpscaleImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Whether to include a reason for filtered-out images in the\n response. */\n includeRaiReason?: boolean;\n /** The image format that the output should be saved as. */\n outputMimeType?: string;\n /** The level of compression if the ``output_mime_type`` is\n ``image/jpeg``. */\n outputCompressionQuality?: number;\n /** Whether to add an image enhancing step before upscaling.\n It is expected to suppress the noise and JPEG compression artifacts\n from the input image. */\n enhanceInputImage?: boolean;\n /** With a higher image preservation factor, the original image\n pixels are more respected. With a lower image preservation factor, the\n output image will have be more different from the input image, but\n with finer details and less noise. */\n imagePreservationFactor?: number;\n}\n\n/** User-facing config UpscaleImageParameters. */\nexport declare interface UpscaleImageParameters {\n /** The model to use. */\n model: string;\n /** The input image to upscale. */\n image: Image;\n /** The factor to upscale the image (x2 or x4). */\n upscaleFactor: string;\n /** Configuration for upscaling. */\n config?: UpscaleImageConfig;\n}\n\n/** A raw reference image.\n\n A raw reference image represents the base image to edit, provided by the user.\n It can optionally be provided in addition to a mask reference image or\n a style reference image.\n */\nexport class RawReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_RAW',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n };\n return referenceImageAPI;\n }\n}\n\n/** A mask reference image.\n\n This encapsulates either a mask image provided by the user and configs for\n the user provided mask, or only config parameters for the model to generate\n a mask.\n\n A mask image is an image whose non-zero values indicate where to edit the base\n image. If the user provides a mask image, the mask must be in the same\n dimensions as the raw image.\n */\nexport class MaskReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the mask reference image. */\n config?: MaskReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_MASK',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n maskImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A control reference image.\n\n The image of the control reference image is either a control image provided\n by the user, or a regular image which the backend will use to generate a\n control image of. In the case of the latter, the\n enable_control_image_computation field in the config should be set to True.\n\n A control image is an image that represents a sketch image of areas for the\n model to fill in based on the prompt.\n */\nexport class ControlReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the control reference image. */\n config?: ControlReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_CONTROL',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n controlImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A style reference image.\n\n This encapsulates a style reference image provided by the user, and\n additionally optional config parameters for the style reference image.\n\n A raw reference image can also be provided as a destination for the style to\n be applied to.\n */\nexport class StyleReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the style reference image. */\n config?: StyleReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_STYLE',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n styleImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A subject reference image.\n\n This encapsulates a subject reference image provided by the user, and\n additionally optional config parameters for the subject reference image.\n\n A raw reference image can also be provided as a destination for the subject to\n be applied to.\n */\nexport class SubjectReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the subject reference image. */\n config?: SubjectReferenceConfig;\n /* Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_SUBJECT',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n subjectImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\nexport /** Sent in response to a `LiveGenerateContentSetup` message from the client. */\ndeclare interface LiveServerSetupComplete {\n /** The session id of the live session. */\n sessionId?: string;\n}\n\n/** Audio transcription in Server Conent. */\nexport declare interface Transcription {\n /** Transcription text.\n */\n text?: string;\n /** The bool indicates the end of the transcription.\n */\n finished?: boolean;\n}\n\n/** Incremental server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time. Clients\n may choose to buffer and play it out in real time.\n */\nexport declare interface LiveServerContent {\n /** The content that the model has generated as part of the current conversation with the user. */\n modelTurn?: Content;\n /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */\n turnComplete?: boolean;\n /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */\n interrupted?: boolean;\n /** Metadata returned to client when grounding is enabled. */\n groundingMetadata?: GroundingMetadata;\n /** If true, indicates that the model is done generating. When model is\n interrupted while generating there will be no generation_complete message\n in interrupted turn, it will go through interrupted > turn_complete.\n When model assumes realtime playback there will be delay between\n generation_complete and turn_complete that is caused by model\n waiting for playback to finish. If true, indicates that the model\n has finished generating all content. This is a signal to the client\n that it can stop sending messages. */\n generationComplete?: boolean;\n /** Input transcription. The transcription is independent to the model\n turn which means it doesn’t imply any ordering between transcription and\n model turn. */\n inputTranscription?: Transcription;\n /** Output transcription. The transcription is independent to the model\n turn which means it doesn’t imply any ordering between transcription and\n model turn.\n */\n outputTranscription?: Transcription;\n /** Metadata related to url context retrieval tool. */\n urlContextMetadata?: UrlContextMetadata;\n}\n\n/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\nexport declare interface LiveServerToolCall {\n /** The function call to be executed. */\n functionCalls?: FunctionCall[];\n}\n\n/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled.\n\n If there were side-effects to those tool calls, clients may attempt to undo\n the tool calls. This message occurs only in cases where the clients interrupt\n server turns.\n */\nexport declare interface LiveServerToolCallCancellation {\n /** The ids of the tool calls to be cancelled. */\n ids?: string[];\n}\n\n/** Usage metadata about response(s). */\nexport declare interface UsageMetadata {\n /** Number of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n /** Total number of tokens across all the generated response candidates. */\n responseTokenCount?: number;\n /** Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Number of tokens of thoughts for thinking models. */\n thoughtsTokenCount?: number;\n /** Total token count for prompt, response candidates, and tool-use prompts(if present). */\n totalTokenCount?: number;\n /** List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were processed in the cache input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were returned in the response. */\n responseTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were processed in the tool-use prompt. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Traffic type. This shows whether a request consumes Pay-As-You-Go\n or Provisioned Throughput quota. */\n trafficType?: TrafficType;\n}\n\n/** Server will not be able to service client soon. */\nexport declare interface LiveServerGoAway {\n /** The remaining time before the connection will be terminated as ABORTED. The minimal time returned here is specified differently together with the rate limits for a given model. */\n timeLeft?: string;\n}\n\n/** Update of the session resumption state.\n\n Only sent if `session_resumption` was set in the connection config.\n */\nexport declare interface LiveServerSessionResumptionUpdate {\n /** New handle that represents state that can be resumed. Empty if `resumable`=false. */\n newHandle?: string;\n /** True if session can be resumed at this point. It might be not possible to resume session at some points. In that case we send update empty new_handle and resumable=false. Example of such case could be model executing function calls or just generating. Resuming session (using previous session token) in such state will result in some data loss. */\n resumable?: boolean;\n /** Index of last message sent by client that is included in state represented by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent` is set.\n\nPresence of this index allows users to transparently reconnect and avoid issue of losing some part of realtime audio input/video. If client wishes to temporarily disconnect (for example as result of receiving GoAway) they can do it without losing state by buffering messages sent since last `SessionResmumptionTokenUpdate`. This field will enable them to limit buffering (avoid keeping all requests in RAM).\n\nNote: This should not be used for when resuming a session at some time later -- in those cases partial audio and video frames arelikely not needed. */\n lastConsumedClientMessageIndex?: string;\n}\n\n/** Response message for API call. */\nexport class LiveServerMessage {\n /** Sent in response to a `LiveClientSetup` message from the client. */\n setupComplete?: LiveServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveServerContent;\n /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\n toolCall?: LiveServerToolCall;\n /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */\n toolCallCancellation?: LiveServerToolCallCancellation;\n /** Usage metadata about model response(s). */\n usageMetadata?: UsageMetadata;\n /** Server will disconnect soon. */\n goAway?: LiveServerGoAway;\n /** Update of the session resumption state. */\n sessionResumptionUpdate?: LiveServerSessionResumptionUpdate;\n /**\n * Returns the concatenation of all text parts from the server content if present.\n *\n * @remarks\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n */\n get text(): string | undefined {\n let text = '';\n let anyTextPartFound = false;\n const nonTextParts = [];\n for (const part of this.serverContent?.modelTurn?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n fieldValue !== null\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartFound = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartFound ? text : undefined;\n }\n\n /**\n * Returns the concatenation of all inline data parts from the server content if present.\n *\n * @remarks\n * If there are non-inline data parts in the\n * response, the concatenation of all inline data parts will be returned, and\n * a warning will be logged.\n */\n get data(): string | undefined {\n let data = '';\n const nonDataParts = [];\n for (const part of this.serverContent?.modelTurn?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (fieldName !== 'inlineData' && fieldValue !== null) {\n nonDataParts.push(fieldName);\n }\n }\n if (part.inlineData && typeof part.inlineData.data === 'string') {\n data += atob(part.inlineData.data);\n }\n }\n if (nonDataParts.length > 0) {\n console.warn(\n `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`,\n );\n }\n return data.length > 0 ? btoa(data) : undefined;\n }\n}\n\n/** Parameters for the get method of the operations module. */\nexport declare interface OperationGetParameters> {\n /** The operation to be retrieved. */\n operation: U;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\n/** Parameters of the fromAPIResponse method of the Operation class. */\nexport declare interface OperationFromAPIResponseParameters {\n /** The API response to be converted to an Operation. */\n apiResponse: Record;\n /** Whether the API response is from Vertex AI. */\n isVertexAI: boolean;\n}\n\n/** A long-running operation. */\nexport declare interface Operation {\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The response if the operation is successful. */\n response?: T;\n /**\n * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n * @internal\n */\n _fromAPIResponse({\n apiResponse,\n isVertexAI,\n }: OperationFromAPIResponseParameters): Operation;\n}\n\n/** A video generation long-running operation. */\nexport class GenerateVideosOperation\n implements Operation\n{\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The response if the operation is successful. */\n response?: GenerateVideosResponse;\n /** The full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n\n /**\n * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n * @internal\n */\n _fromAPIResponse({\n apiResponse,\n isVertexAI,\n }: OperationFromAPIResponseParameters): Operation {\n const operation = new GenerateVideosOperation();\n operation.name = apiResponse['name'] as string | undefined;\n operation.metadata = apiResponse['metadata'] as\n | Record\n | undefined;\n operation.done = apiResponse['done'] as boolean | undefined;\n operation.error = apiResponse['error'] as\n | Record\n | undefined;\n\n if (isVertexAI) {\n const response = apiResponse['response'] as\n | Record\n | undefined;\n if (response) {\n const operationResponse = new GenerateVideosResponse();\n const responseVideos = response['videos'] as\n | Array>\n | undefined;\n operationResponse.generatedVideos = responseVideos?.map(\n (generatedVideo) => {\n return {\n video: {\n uri: generatedVideo['gcsUri'] as string | undefined,\n videoBytes: generatedVideo['bytesBase64Encoded']\n ? tBytes(generatedVideo['bytesBase64Encoded'] as string)\n : undefined,\n mimeType: generatedVideo['mimeType'] as string | undefined,\n } as Video,\n } as GeneratedVideo;\n },\n );\n operationResponse.raiMediaFilteredCount = response[\n 'raiMediaFilteredCount'\n ] as number | undefined;\n operationResponse.raiMediaFilteredReasons = response[\n 'raiMediaFilteredReasons'\n ] as string[] | undefined;\n operation.response = operationResponse;\n }\n } else {\n const response = apiResponse['response'] as\n | Record\n | undefined;\n if (response) {\n const operationResponse = new GenerateVideosResponse();\n const generatedVideoResponse = response['generateVideoResponse'] as\n | Record\n | undefined;\n const responseVideos = generatedVideoResponse?.['generatedSamples'] as\n | Array>\n | undefined;\n operationResponse.generatedVideos = responseVideos?.map(\n (generatedVideo) => {\n const video = generatedVideo['video'] as\n | Record\n | undefined;\n return {\n video: {\n uri: video?.['uri'] as string | undefined,\n videoBytes: video?.['encodedVideo']\n ? tBytes(video?.['encodedVideo'] as string)\n : undefined,\n mimeType: generatedVideo['encoding'] as string | undefined,\n } as Video,\n } as GeneratedVideo;\n },\n );\n operationResponse.raiMediaFilteredCount = generatedVideoResponse?.[\n 'raiMediaFilteredCount'\n ] as number | undefined;\n operationResponse.raiMediaFilteredReasons = generatedVideoResponse?.[\n 'raiMediaFilteredReasons'\n ] as string[] | undefined;\n operation.response = operationResponse;\n }\n }\n return operation;\n }\n}\n\n/** Configures automatic detection of activity. */\nexport declare interface AutomaticActivityDetection {\n /** If enabled, detected voice and text input count as activity. If disabled, the client must send activity signals. */\n disabled?: boolean;\n /** Determines how likely speech is to be detected. */\n startOfSpeechSensitivity?: StartSensitivity;\n /** Determines how likely detected speech is ended. */\n endOfSpeechSensitivity?: EndSensitivity;\n /** The required duration of detected speech before start-of-speech is committed. The lower this value the more sensitive the start-of-speech detection is and the shorter speech can be recognized. However, this also increases the probability of false positives. */\n prefixPaddingMs?: number;\n /** The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency. */\n silenceDurationMs?: number;\n}\n\n/** Marks the end of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface RealtimeInputConfig {\n /** If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals. */\n automaticActivityDetection?: AutomaticActivityDetection;\n /** Defines what effect activity has. */\n activityHandling?: ActivityHandling;\n /** Defines which input is included in the user's turn. */\n turnCoverage?: TurnCoverage;\n}\n\n/** Configuration of session resumption mechanism.\n\n Included in `LiveConnectConfig.session_resumption`. If included server\n will send `LiveServerSessionResumptionUpdate` messages.\n */\nexport declare interface SessionResumptionConfig {\n /** Session resumption handle of previous session (session to restore).\n\nIf not present new session will be started. */\n handle?: string;\n /** If set the server will send `last_consumed_client_message_index` in the `session_resumption_update` messages to allow for transparent reconnections. */\n transparent?: boolean;\n}\n\n/** Context window will be truncated by keeping only suffix of it.\n\n Context window will always be cut at start of USER role turn. System\n instructions and `BidiGenerateContentSetup.prefix_turns` will not be\n subject to the sliding window mechanism, they will always stay at the\n beginning of context window.\n */\nexport declare interface SlidingWindow {\n /** Session reduction target -- how many tokens we should keep. Window shortening operation has some latency costs, so we should avoid running it on every turn. Should be < trigger_tokens. If not set, trigger_tokens/2 is assumed. */\n targetTokens?: string;\n}\n\n/** Enables context window compression -- mechanism managing model context window so it does not exceed given length. */\nexport declare interface ContextWindowCompressionConfig {\n /** Number of tokens (before running turn) that triggers context window compression mechanism. */\n triggerTokens?: string;\n /** Sliding window compression mechanism. */\n slidingWindow?: SlidingWindow;\n}\n\n/** The audio transcription configuration in Setup. */\nexport declare interface AudioTranscriptionConfig {}\n\n/** Config for proactivity features. */\nexport declare interface ProactivityConfig {\n /** If enabled, the model can reject responding to the last prompt. For\n example, this allows the model to ignore out of context speech or to stay\n silent if the user did not make a request, yet. */\n proactiveAudio?: boolean;\n}\n\n/** Message contains configuration that will apply for the duration of the streaming session. */\nexport declare interface LiveClientSetup {\n /** \n The fully qualified name of the publisher model or tuned model endpoint to\n use.\n */\n model?: string;\n /** The generation configuration for the session.\n Note: only a subset of fields are supported.\n */\n generationConfig?: GenerationConfig;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n /** Configures the realtime input behavior in BidiGenerateContent. */\n realtimeInputConfig?: RealtimeInputConfig;\n /** Configures session resumption mechanism.\n\n If included server will send SessionResumptionUpdate messages. */\n sessionResumption?: SessionResumptionConfig;\n /** Configures context window compression mechanism.\n\n If included, server will compress context window to fit into given length. */\n contextWindowCompression?: ContextWindowCompressionConfig;\n /** The transcription of the input aligns with the input audio language.\n */\n inputAudioTranscription?: AudioTranscriptionConfig;\n /** The transcription of the output aligns with the language code\n specified for the output audio.\n */\n outputAudioTranscription?: AudioTranscriptionConfig;\n /** Configures the proactivity of the model. This allows the model to respond proactively to\n the input and to ignore irrelevant input. */\n proactivity?: ProactivityConfig;\n}\n\n/** Incremental update of the current conversation delivered from the client.\n\n All the content here will unconditionally be appended to the conversation\n history and used as part of the prompt to the model to generate content.\n\n A message here will interrupt any current model generation.\n */\nexport declare interface LiveClientContent {\n /** The content appended to the current conversation with the model.\n\n For single-turn queries, this is a single instance. For multi-turn\n queries, this is a repeated field that contains conversation history and\n latest request.\n */\n turns?: Content[];\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Marks the start of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface ActivityStart {}\n\n/** Marks the end of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface ActivityEnd {}\n\n/** User input that is sent in real time.\n\n This is different from `LiveClientContent` in a few ways:\n\n - Can be sent continuously without interruption to model generation.\n - If there is a need to mix data interleaved across the\n `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to\n optimize for best response, but there are no guarantees.\n - End of turn is not explicitly specified, but is rather derived from user\n activity (for example, end of speech).\n - Even before the end of turn, the data is processed incrementally\n to optimize for a fast start of the response from the model.\n - Is always assumed to be the user's input (cannot be used to populate\n conversation history).\n */\nexport declare interface LiveClientRealtimeInput {\n /** Inlined bytes data for media input. */\n mediaChunks?: Blob[];\n /** The realtime audio input stream. */\n audio?: Blob;\n /** \nIndicates that the audio stream has ended, e.g. because the microphone was\nturned off.\n\nThis should only be sent when automatic activity detection is enabled\n(which is the default).\n\nThe client can reopen the stream by sending an audio message.\n */\n audioStreamEnd?: boolean;\n /** The realtime video input stream. */\n video?: Blob;\n /** The realtime text input stream. */\n text?: string;\n /** Marks the start of user activity. */\n activityStart?: ActivityStart;\n /** Marks the end of user activity. */\n activityEnd?: ActivityEnd;\n}\n\n/** Client generated response to a `ToolCall` received from the server.\n\n Individual `FunctionResponse` objects are matched to the respective\n `FunctionCall` objects by the `id` field.\n\n Note that in the unary and server-streaming GenerateContent APIs function\n calling happens by exchanging the `Content` parts, while in the bidi\n GenerateContent APIs function calling happens over this dedicated set of\n messages.\n */\nexport class LiveClientToolResponse {\n /** The response to the function calls. */\n functionResponses?: FunctionResponse[];\n}\n\n/** Parameters for sending realtime input to the live API. */\nexport declare interface LiveSendRealtimeInputParameters {\n /** Realtime input to send to the session. */\n media?: BlobImageUnion;\n /** The realtime audio input stream. */\n audio?: Blob;\n /** \nIndicates that the audio stream has ended, e.g. because the microphone was\nturned off.\n\nThis should only be sent when automatic activity detection is enabled\n(which is the default).\n\nThe client can reopen the stream by sending an audio message.\n */\n audioStreamEnd?: boolean;\n /** The realtime video input stream. */\n video?: BlobImageUnion;\n /** The realtime text input stream. */\n text?: string;\n /** Marks the start of user activity. */\n activityStart?: ActivityStart;\n /** Marks the end of user activity. */\n activityEnd?: ActivityEnd;\n}\n\n/** Messages sent by the client in the API call. */\nexport declare interface LiveClientMessage {\n /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */\n setup?: LiveClientSetup;\n /** Incremental update of the current conversation delivered from the client. */\n clientContent?: LiveClientContent;\n /** User input that is sent in real time. */\n realtimeInput?: LiveClientRealtimeInput;\n /** Response to a `ToolCallMessage` received from the server. */\n toolResponse?: LiveClientToolResponse;\n}\n\n/** Session config for the API connection. */\nexport declare interface LiveConnectConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The generation configuration for the session. */\n generationConfig?: GenerationConfig;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return. Defaults to AUDIO if not specified.\n */\n responseModalities?: Modality[];\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfig;\n /** If enabled, the model will detect emotions and adapt its responses accordingly. */\n enableAffectiveDialog?: boolean;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n /** Configures session resumption mechanism.\n\nIf included the server will send SessionResumptionUpdate messages. */\n sessionResumption?: SessionResumptionConfig;\n /** The transcription of the input aligns with the input audio language.\n */\n inputAudioTranscription?: AudioTranscriptionConfig;\n /** The transcription of the output aligns with the language code\n specified for the output audio.\n */\n outputAudioTranscription?: AudioTranscriptionConfig;\n /** Configures the realtime input behavior in BidiGenerateContent. */\n realtimeInputConfig?: RealtimeInputConfig;\n /** Configures context window compression mechanism.\n\n If included, server will compress context window to fit into given length. */\n contextWindowCompression?: ContextWindowCompressionConfig;\n /** Configures the proactivity of the model. This allows the model to respond proactively to\n the input and to ignore irrelevant input. */\n proactivity?: ProactivityConfig;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveConnectParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** callbacks */\n callbacks: LiveCallbacks;\n /** Optional configuration parameters for the request.\n */\n config?: LiveConnectConfig;\n}\n\n/** Parameters for initializing a new chat session.\n\n These parameters are used when creating a chat session with the\n `chats.create()` method.\n */\nexport declare interface CreateChatParameters {\n /** The name of the model to use for the chat session.\n\n For example: 'gemini-2.0-flash', 'gemini-2.0-flash-lite', etc. See Gemini API\n docs to find the available models.\n */\n model: string;\n /** Config for the entire chat session.\n\n This config applies to all requests within the session\n unless overridden by a per-request `config` in `SendMessageParameters`.\n */\n config?: GenerateContentConfig;\n /** The initial conversation history for the chat session.\n\n This allows you to start the chat with a pre-existing history. The history\n must be a list of `Content` alternating between 'user' and 'model' roles.\n It should start with a 'user' message.\n */\n history?: Content[];\n}\n\n/** Parameters for sending a message within a chat session.\n\n These parameters are used with the `chat.sendMessage()` method.\n */\nexport declare interface SendMessageParameters {\n /** The message to send to the model.\n\n The SDK will combine all parts into a single 'user' content to send to\n the model.\n */\n message: PartListUnion;\n /** Config for this specific request.\n\n Please note that the per-request config does not change the chat level\n config, nor inherit from it. If you intend to use some values from the\n chat's default config, you must explicitly copy them into this per-request\n config.\n */\n config?: GenerateContentConfig;\n}\n\n/** Parameters for sending client content to the live API. */\nexport declare interface LiveSendClientContentParameters {\n /** Client content to send to the session. */\n turns?: ContentListUnion;\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Parameters for sending tool responses to the live API. */\nexport class LiveSendToolResponseParameters {\n /** Tool responses to send to the session. */\n functionResponses: FunctionResponse[] | FunctionResponse = [];\n}\n\n/** Message to be sent by the system when connecting to the API. */\nexport declare interface LiveMusicClientSetup {\n /** The model's resource name. Format: `models/{model}`. */\n model?: string;\n}\n\n/** Maps a prompt to a relative weight to steer music generation. */\nexport declare interface WeightedPrompt {\n /** Text prompt. */\n text?: string;\n /** Weight of the prompt. The weight is used to control the relative\n importance of the prompt. Higher weights are more important than lower\n weights.\n\n Weight must not be 0. Weights of all weighted_prompts in this\n LiveMusicClientContent message will be normalized. */\n weight?: number;\n}\n\n/** User input to start or steer the music. */\nexport declare interface LiveMusicClientContent {\n /** Weighted prompts as the model input. */\n weightedPrompts?: WeightedPrompt[];\n}\n\n/** Configuration for music generation. */\nexport declare interface LiveMusicGenerationConfig {\n /** Controls the variance in audio generation. Higher values produce\n higher variance. Range is [0.0, 3.0]. */\n temperature?: number;\n /** Controls how the model selects tokens for output. Samples the topK\n tokens with the highest probabilities. Range is [1, 1000]. */\n topK?: number;\n /** Seeds audio generation. If not set, the request uses a randomly\n generated seed. */\n seed?: number;\n /** Controls how closely the model follows prompts.\n Higher guidance follows more closely, but will make transitions more\n abrupt. Range is [0.0, 6.0]. */\n guidance?: number;\n /** Beats per minute. Range is [60, 200]. */\n bpm?: number;\n /** Density of sounds. Range is [0.0, 1.0]. */\n density?: number;\n /** Brightness of the music. Range is [0.0, 1.0]. */\n brightness?: number;\n /** Scale of the generated music. */\n scale?: Scale;\n /** Whether the audio output should contain bass. */\n muteBass?: boolean;\n /** Whether the audio output should contain drums. */\n muteDrums?: boolean;\n /** Whether the audio output should contain only bass and drums. */\n onlyBassAndDrums?: boolean;\n /** The mode of music generation. Default mode is QUALITY. */\n musicGenerationMode?: MusicGenerationMode;\n}\n\n/** Messages sent by the client in the LiveMusicClientMessage call. */\nexport declare interface LiveMusicClientMessage {\n /** Message to be sent in the first (and only in the first) `LiveMusicClientMessage`.\n Clients should wait for a `LiveMusicSetupComplete` message before\n sending any additional messages. */\n setup?: LiveMusicClientSetup;\n /** User input to influence music generation. */\n clientContent?: LiveMusicClientContent;\n /** Configuration for music generation. */\n musicGenerationConfig?: LiveMusicGenerationConfig;\n /** Playback control signal for the music generation. */\n playbackControl?: LiveMusicPlaybackControl;\n}\n\n/** Sent in response to a `LiveMusicClientSetup` message from the client. */\nexport declare interface LiveMusicServerSetupComplete {}\n\n/** Prompts and config used for generating this audio chunk. */\nexport declare interface LiveMusicSourceMetadata {\n /** Weighted prompts for generating this audio chunk. */\n clientContent?: LiveMusicClientContent;\n /** Music generation config for generating this audio chunk. */\n musicGenerationConfig?: LiveMusicGenerationConfig;\n}\n\n/** Representation of an audio chunk. */\nexport declare interface AudioChunk {\n /** Raw bytes of audio data.\n * @remarks Encoded as base64 string. */\n data?: string;\n /** MIME type of the audio chunk. */\n mimeType?: string;\n /** Prompts and config used for generating this audio chunk. */\n sourceMetadata?: LiveMusicSourceMetadata;\n}\n\n/** Server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time.\n Clients may choose to buffer and play it out in real time.\n */\nexport declare interface LiveMusicServerContent {\n /** The audio chunks that the model has generated. */\n audioChunks?: AudioChunk[];\n}\n\n/** A prompt that was filtered with the reason. */\nexport declare interface LiveMusicFilteredPrompt {\n /** The text prompt that was filtered. */\n text?: string;\n /** The reason the prompt was filtered. */\n filteredReason?: string;\n}\n\n/** Response message for the LiveMusicClientMessage call. */\nexport class LiveMusicServerMessage {\n /** Message sent in response to a `LiveMusicClientSetup` message from the client.\n Clients should wait for this message before sending any additional messages. */\n setupComplete?: LiveMusicServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveMusicServerContent;\n /** A prompt that was filtered with the reason. */\n filteredPrompt?: LiveMusicFilteredPrompt;\n /**\n * Returns the first audio chunk from the server content, if present.\n *\n * @remarks\n * If there are no audio chunks in the response, undefined will be returned.\n */\n get audioChunk(): AudioChunk | undefined {\n if (\n this.serverContent &&\n this.serverContent.audioChunks &&\n this.serverContent.audioChunks.length > 0\n ) {\n return this.serverContent.audioChunks[0];\n }\n return undefined;\n }\n}\n\n/** Callbacks for the realtime music API. */\nexport interface LiveMusicCallbacks {\n /**\n * Called when a message is received from the server.\n */\n onmessage: (e: LiveMusicServerMessage) => void;\n /**\n * Called when an error occurs.\n */\n onerror?: ((e: ErrorEvent) => void) | null;\n /**\n * Called when the websocket connection is closed.\n */\n onclose?: ((e: CloseEvent) => void) | null;\n}\n\n/** Parameters for the upload file method. */\nexport interface UploadFileParameters {\n /** The string path to the file to be uploaded or a Blob object. */\n file: string | globalThis.Blob;\n /** Configuration that contains optional parameters. */\n config?: UploadFileConfig;\n}\n\n/**\n * CallableTool is an invokable tool that can be executed with external\n * application (e.g., via Model Context Protocol) or local functions with\n * function calling.\n */\nexport interface CallableTool {\n /**\n * Returns tool that can be called by Gemini.\n */\n tool(): Promise;\n /**\n * Executes the callable tool with the given function call arguments and\n * returns the response parts from the tool execution.\n */\n callTool(functionCalls: FunctionCall[]): Promise;\n}\n\n/**\n * CallableToolConfig is the configuration for a callable tool.\n */\nexport interface CallableToolConfig {\n /**\n * Specifies the model's behavior after invoking this tool.\n */\n behavior?: Behavior;\n /**\n * Timeout for remote calls in milliseconds. Note this timeout applies only to\n * tool remote calls, and not making HTTP requests to the API. */\n timeout?: number;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveMusicConnectParameters {\n /** The model's resource name. */\n model: string;\n /** Callbacks invoked on server events. */\n callbacks: LiveMusicCallbacks;\n}\n\n/** Parameters for setting config for the live music API. */\nexport declare interface LiveMusicSetConfigParameters {\n /** Configuration for music generation. */\n musicGenerationConfig: LiveMusicGenerationConfig;\n}\n\n/** Parameters for setting weighted prompts for the live music API. */\nexport declare interface LiveMusicSetWeightedPromptsParameters {\n /** A map of text prompts to weights to use for the generation request. */\n weightedPrompts: WeightedPrompt[];\n}\n\n/** Config for auth_tokens.create parameters. */\nexport declare interface AuthToken {\n /** The name of the auth token. */\n name?: string;\n}\n\n/** Config for LiveConnectConstraints for Auth Token creation. */\nexport declare interface LiveConnectConstraints {\n /** ID of the model to configure in the ephemeral token for Live API.\n For a list of models, see `Gemini models\n `. */\n model?: string;\n /** Configuration specific to Live API connections created using this token. */\n config?: LiveConnectConfig;\n}\n\n/** Optional parameters. */\nexport declare interface CreateAuthTokenConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** An optional time after which, when using the resulting token,\n messages in Live API sessions will be rejected. (Gemini may\n preemptively close the session after this time.)\n\n If not set then this defaults to 30 minutes in the future. If set, this\n value must be less than 20 hours in the future. */\n expireTime?: string;\n /** The time after which new Live API sessions using the token\n resulting from this request will be rejected.\n\n If not set this defaults to 60 seconds in the future. If set, this value\n must be less than 20 hours in the future. */\n newSessionExpireTime?: string;\n /** The number of times the token can be used. If this value is zero\n then no limit is applied. Default is 1. Resuming a Live API session does\n not count as a use. */\n uses?: number;\n /** Configuration specific to Live API connections created using this token. */\n liveConnectConstraints?: LiveConnectConstraints;\n /** Additional fields to lock in the effective LiveConnectParameters. */\n lockAdditionalFields?: string[];\n}\n\n/** Config for auth_tokens.create parameters. */\nexport declare interface CreateAuthTokenParameters {\n /** Optional parameters for the request. */\n config?: CreateAuthTokenConfig;\n}\n\n/** Supervised fine-tuning job creation parameters - optional fields. */\nexport declare interface CreateTuningJobParameters {\n /** The base model that is being tuned, e.g., \"gemini-2.5-flash\". */\n baseModel: string;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDataset: TuningDataset;\n /** Configuration for the tuning job. */\n config?: CreateTuningJobConfig;\n}\n\nexport type BlobImageUnion = Blob;\n\nexport type PartUnion = Part | string;\n\nexport type PartListUnion = PartUnion[] | PartUnion;\n\nexport type ContentUnion = Content | PartUnion[] | PartUnion;\n\nexport type ContentListUnion = Content | Content[] | PartUnion | PartUnion[];\n\nexport type SchemaUnion = Schema | unknown;\n\nexport type SpeechConfigUnion = SpeechConfig | string;\n\nexport type ToolUnion = Tool | CallableTool;\n\nexport type ToolListUnion = ToolUnion[];\n\nexport type DownloadableFileUnion = string | File | GeneratedVideo | Video;\n\nexport type BatchJobSourceUnion = BatchJobSource | InlinedRequest[] | string;\n\nexport type BatchJobDestinationUnion = BatchJobDestination | string;\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {Tool as McpTool} from '@modelcontextprotocol/sdk/types.js';\n\nimport {ApiClient} from './_api_client.js';\nimport * as baseTransformers from './_base_transformers.js';\nimport * as types from './types.js';\n\nexport function tModel(apiClient: ApiClient, model: string | unknown): string {\n if (!model || typeof model !== 'string') {\n throw new Error('model is required and must be a string');\n }\n\n if (apiClient.isVertexAI()) {\n if (\n model.startsWith('publishers/') ||\n model.startsWith('projects/') ||\n model.startsWith('models/')\n ) {\n return model;\n } else if (model.indexOf('/') >= 0) {\n const parts = model.split('/', 2);\n return `publishers/${parts[0]}/models/${parts[1]}`;\n } else {\n return `publishers/google/models/${model}`;\n }\n } else {\n if (model.startsWith('models/') || model.startsWith('tunedModels/')) {\n return model;\n } else {\n return `models/${model}`;\n }\n }\n}\n\nexport function tCachesModel(\n apiClient: ApiClient,\n model: string | unknown,\n): string {\n const transformedModel = tModel(apiClient, model as string);\n if (!transformedModel) {\n return '';\n }\n\n if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) {\n // vertex caches only support model name start with projects.\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`;\n } else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) {\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`;\n } else {\n return transformedModel;\n }\n}\n\nexport function tBlobs(\n blobs: types.BlobImageUnion | types.BlobImageUnion[],\n): types.Blob[] {\n if (Array.isArray(blobs)) {\n return blobs.map((blob) => tBlob(blob));\n } else {\n return [tBlob(blobs)];\n }\n}\n\nexport function tBlob(blob: types.BlobImageUnion): types.Blob {\n if (typeof blob === 'object' && blob !== null) {\n return blob;\n }\n\n throw new Error(\n `Could not parse input as Blob. Unsupported blob type: ${typeof blob}`,\n );\n}\n\nexport function tImageBlob(blob: types.BlobImageUnion): types.Blob {\n const transformedBlob = tBlob(blob);\n if (\n transformedBlob.mimeType &&\n transformedBlob.mimeType.startsWith('image/')\n ) {\n return transformedBlob;\n }\n throw new Error(`Unsupported mime type: ${transformedBlob.mimeType!}`);\n}\n\nexport function tAudioBlob(blob: types.Blob): types.Blob {\n const transformedBlob = tBlob(blob);\n if (\n transformedBlob.mimeType &&\n transformedBlob.mimeType.startsWith('audio/')\n ) {\n return transformedBlob;\n }\n throw new Error(`Unsupported mime type: ${transformedBlob.mimeType!}`);\n}\n\nexport function tPart(origin?: types.PartUnion | null): types.Part {\n if (origin === null || origin === undefined) {\n throw new Error('PartUnion is required');\n }\n if (typeof origin === 'object') {\n return origin;\n }\n if (typeof origin === 'string') {\n return {text: origin};\n }\n throw new Error(`Unsupported part type: ${typeof origin}`);\n}\n\nexport function tParts(origin?: types.PartListUnion | null): types.Part[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('PartListUnion is required');\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tPart(item as types.PartUnion)!);\n }\n return [tPart(origin)!];\n}\n\nfunction _isContent(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'parts' in origin &&\n Array.isArray(origin.parts)\n );\n}\n\nfunction _isFunctionCallPart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionCall' in origin\n );\n}\n\nfunction _isFunctionResponsePart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionResponse' in origin\n );\n}\n\nexport function tContent(origin?: types.ContentUnion): types.Content {\n if (origin === null || origin === undefined) {\n throw new Error('ContentUnion is required');\n }\n if (_isContent(origin)) {\n // _isContent is a utility function that checks if the\n // origin is a Content.\n return origin as types.Content;\n }\n\n return {\n role: 'user',\n parts: tParts(origin as types.PartListUnion)!,\n };\n}\n\nexport function tContentsForEmbed(\n apiClient: ApiClient,\n origin: types.ContentListUnion,\n): types.ContentUnion[] {\n if (!origin) {\n return [];\n }\n if (apiClient.isVertexAI() && Array.isArray(origin)) {\n return origin.flatMap((item) => {\n const content = tContent(item as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n });\n } else if (apiClient.isVertexAI()) {\n const content = tContent(origin as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tContent(item as types.ContentUnion)!);\n }\n return [tContent(origin as types.ContentUnion)!];\n}\n\nexport function tContents(origin?: types.ContentListUnion): types.Content[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('contents are required');\n }\n if (!Array.isArray(origin)) {\n // If it's not an array, it's a single content or a single PartUnion.\n if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) {\n throw new Error(\n 'To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them',\n );\n }\n return [tContent(origin as types.ContentUnion)];\n }\n\n const result: types.Content[] = [];\n const accumulatedParts: types.PartUnion[] = [];\n const isContentArray = _isContent(origin[0]);\n\n for (const item of origin) {\n const isContent = _isContent(item);\n\n if (isContent != isContentArray) {\n throw new Error(\n 'Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them',\n );\n }\n\n if (isContent) {\n // `isContent` contains the result of _isContent, which is a utility\n // function that checks if the item is a Content.\n result.push(item as types.Content);\n } else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) {\n throw new Error(\n 'To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them',\n );\n } else {\n accumulatedParts.push(item as types.PartUnion);\n }\n }\n\n if (!isContentArray) {\n result.push({role: 'user', parts: tParts(accumulatedParts)});\n }\n return result;\n}\n\n/*\nTransform the type field from an array of types to an array of anyOf fields.\nExample:\n {type: ['STRING', 'NUMBER']}\nwill be transformed to\n {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]}\n*/\nfunction flattenTypeArrayToAnyOf(\n typeList: string[],\n resultingSchema: types.Schema,\n) {\n if (typeList.includes('null')) {\n resultingSchema['nullable'] = true;\n }\n const listWithoutNull = typeList.filter((type) => type !== 'null');\n\n if (listWithoutNull.length === 1) {\n resultingSchema['type'] = Object.values(types.Type).includes(\n listWithoutNull[0].toUpperCase() as types.Type,\n )\n ? (listWithoutNull[0].toUpperCase() as types.Type)\n : types.Type.TYPE_UNSPECIFIED;\n } else {\n resultingSchema['anyOf'] = [];\n for (const i of listWithoutNull) {\n resultingSchema['anyOf'].push({\n 'type': Object.values(types.Type).includes(\n i.toUpperCase() as types.Type,\n )\n ? (i.toUpperCase() as types.Type)\n : types.Type.TYPE_UNSPECIFIED,\n });\n }\n }\n}\n\nexport function processJsonSchema(\n _jsonSchema: types.Schema | Record,\n): types.Schema {\n const genAISchema: types.Schema = {};\n const schemaFieldNames = ['items'];\n const listSchemaFieldNames = ['anyOf'];\n const dictSchemaFieldNames = ['properties'];\n\n if (_jsonSchema['type'] && _jsonSchema['anyOf']) {\n throw new Error('type and anyOf cannot be both populated.');\n }\n\n /*\n This is to handle the nullable array or object. The _jsonSchema will\n be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The\n logic is to check if anyOf has 2 elements and one of the element is null,\n if so, the anyOf field is unnecessary, so we need to get rid of the anyOf\n field and make the schema nullable. Then use the other element as the new\n _jsonSchema for processing. This is because the backend doesn't have a null\n type.\n This has to be checked before we process any other fields.\n For example:\n const objectNullable = z.object({\n nullableArray: z.array(z.string()).nullable(),\n });\n Will have the raw _jsonSchema as:\n {\n type: 'OBJECT',\n properties: {\n nullableArray: {\n anyOf: [\n {type: 'null'},\n {\n type: 'array',\n items: {type: 'string'},\n },\n ],\n }\n },\n required: [ 'nullableArray' ],\n }\n Will result in following schema compatible with Gemini API:\n {\n type: 'OBJECT',\n properties: {\n nullableArray: {\n nullable: true,\n type: 'ARRAY',\n items: {type: 'string'},\n }\n },\n required: [ 'nullableArray' ],\n }\n */\n const incomingAnyOf = _jsonSchema['anyOf'] as Record[];\n if (incomingAnyOf != null && incomingAnyOf.length == 2) {\n if (incomingAnyOf[0]!['type'] === 'null') {\n genAISchema['nullable'] = true;\n _jsonSchema = incomingAnyOf![1];\n } else if (incomingAnyOf[1]!['type'] === 'null') {\n genAISchema['nullable'] = true;\n _jsonSchema = incomingAnyOf![0];\n }\n }\n\n if (_jsonSchema['type'] instanceof Array) {\n flattenTypeArrayToAnyOf(_jsonSchema['type'], genAISchema);\n }\n\n for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) {\n // Skip if the fieldvalue is undefined or null.\n if (fieldValue == null) {\n continue;\n }\n\n if (fieldName == 'type') {\n if (fieldValue === 'null') {\n throw new Error(\n 'type: null can not be the only possible type for the field.',\n );\n }\n if (fieldValue instanceof Array) {\n // we have already handled the type field with array of types in the\n // beginning of this function.\n continue;\n }\n genAISchema['type'] = Object.values(types.Type).includes(\n fieldValue.toUpperCase() as types.Type,\n )\n ? fieldValue.toUpperCase()\n : types.Type.TYPE_UNSPECIFIED;\n } else if (schemaFieldNames.includes(fieldName)) {\n (genAISchema as Record)[fieldName] =\n processJsonSchema(fieldValue);\n } else if (listSchemaFieldNames.includes(fieldName)) {\n const listSchemaFieldValue: Array = [];\n for (const item of fieldValue) {\n if (item['type'] == 'null') {\n genAISchema['nullable'] = true;\n continue;\n }\n listSchemaFieldValue.push(\n processJsonSchema(item as Record),\n );\n }\n (genAISchema as Record)[fieldName] =\n listSchemaFieldValue;\n } else if (dictSchemaFieldNames.includes(fieldName)) {\n const dictSchemaFieldValue: Record = {};\n for (const [key, value] of Object.entries(\n fieldValue as Record,\n )) {\n dictSchemaFieldValue[key] = processJsonSchema(\n value as Record,\n );\n }\n (genAISchema as Record)[fieldName] =\n dictSchemaFieldValue;\n } else {\n // additionalProperties is not included in JSONSchema, skipping it.\n if (fieldName === 'additionalProperties') {\n continue;\n }\n (genAISchema as Record)[fieldName] = fieldValue;\n }\n }\n return genAISchema;\n}\n\n// we take the unknown in the schema field because we want enable user to pass\n// the output of major schema declaration tools without casting. Tools such as\n// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type\n// or object, see details in\n// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7\n// typebox can return unknown, see details in\n// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35\n// Note: proper json schemas with the $schema field set never arrive to this\n// transformer. Schemas with $schema are routed to the equivalent API json\n// schema field.\nexport function tSchema(schema: types.Schema | unknown): types.Schema {\n return processJsonSchema(schema as types.Schema);\n}\n\nexport function tSpeechConfig(\n speechConfig: types.SpeechConfigUnion,\n): types.SpeechConfig {\n if (typeof speechConfig === 'object') {\n return speechConfig;\n } else if (typeof speechConfig === 'string') {\n return {\n voiceConfig: {\n prebuiltVoiceConfig: {\n voiceName: speechConfig,\n },\n },\n };\n } else {\n throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`);\n }\n}\n\nexport function tLiveSpeechConfig(\n speechConfig: types.SpeechConfig | object,\n): types.SpeechConfig {\n if ('multiSpeakerVoiceConfig' in speechConfig) {\n throw new Error(\n 'multiSpeakerVoiceConfig is not supported in the live API.',\n );\n }\n return speechConfig;\n}\n\nexport function tTool(tool: types.Tool): types.Tool {\n if (tool.functionDeclarations) {\n for (const functionDeclaration of tool.functionDeclarations) {\n if (functionDeclaration.parameters) {\n if (!Object.keys(functionDeclaration.parameters).includes('$schema')) {\n functionDeclaration.parameters = processJsonSchema(\n functionDeclaration.parameters,\n );\n } else {\n if (!functionDeclaration.parametersJsonSchema) {\n functionDeclaration.parametersJsonSchema =\n functionDeclaration.parameters;\n delete functionDeclaration.parameters;\n }\n }\n }\n if (functionDeclaration.response) {\n if (!Object.keys(functionDeclaration.response).includes('$schema')) {\n functionDeclaration.response = processJsonSchema(\n functionDeclaration.response,\n );\n } else {\n if (!functionDeclaration.responseJsonSchema) {\n functionDeclaration.responseJsonSchema =\n functionDeclaration.response;\n delete functionDeclaration.response;\n }\n }\n }\n }\n }\n return tool;\n}\n\nexport function tTools(tools: types.ToolListUnion | unknown): types.Tool[] {\n // Check if the incoming type is defined.\n if (tools === undefined || tools === null) {\n throw new Error('tools is required');\n }\n if (!Array.isArray(tools)) {\n throw new Error('tools is required and must be an array of Tools');\n }\n const result: types.Tool[] = [];\n for (const tool of tools) {\n result.push(tool as types.Tool);\n }\n return result;\n}\n\n/**\n * Prepends resource name with project, location, resource_prefix if needed.\n *\n * @param client The API client.\n * @param resourceName The resource name.\n * @param resourcePrefix The resource prefix.\n * @param splitsAfterPrefix The number of splits after the prefix.\n * @returns The completed resource name.\n *\n * Examples:\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/bar/locations/us-west1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'projects/foo/locations/us-central1/cachedContents/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/foo/locations/us-central1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns 'cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'some/wrong/cachedContents/resource/name/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * # client.vertexai = True\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * -> 'some/wrong/resource/name/123'\n * ```\n */\nfunction resourceName(\n client: ApiClient,\n resourceName: string,\n resourcePrefix: string,\n splitsAfterPrefix: number = 1,\n): string {\n const shouldAppendPrefix =\n !resourceName.startsWith(`${resourcePrefix}/`) &&\n resourceName.split('/').length === splitsAfterPrefix;\n if (client.isVertexAI()) {\n if (resourceName.startsWith('projects/')) {\n return resourceName;\n } else if (resourceName.startsWith('locations/')) {\n return `projects/${client.getProject()}/${resourceName}`;\n } else if (resourceName.startsWith(`${resourcePrefix}/`)) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`;\n } else if (shouldAppendPrefix) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`;\n } else {\n return resourceName;\n }\n }\n if (shouldAppendPrefix) {\n return `${resourcePrefix}/${resourceName}`;\n }\n return resourceName;\n}\n\nexport function tCachedContentName(\n apiClient: ApiClient,\n name: string | unknown,\n): string {\n if (typeof name !== 'string') {\n throw new Error('name must be a string');\n }\n return resourceName(apiClient, name, 'cachedContents');\n}\n\nexport function tTuningJobStatus(status: string | unknown): string {\n switch (status) {\n case 'STATE_UNSPECIFIED':\n return 'JOB_STATE_UNSPECIFIED';\n case 'CREATING':\n return 'JOB_STATE_RUNNING';\n case 'ACTIVE':\n return 'JOB_STATE_SUCCEEDED';\n case 'FAILED':\n return 'JOB_STATE_FAILED';\n default:\n return status as string;\n }\n}\n\nexport function tBytes(fromImageBytes: string | unknown): string {\n return baseTransformers.tBytes(fromImageBytes);\n}\n\nfunction _isFile(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'name' in origin\n );\n}\n\nexport function isGeneratedVideo(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'video' in origin\n );\n}\n\nexport function isVideo(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'uri' in origin\n );\n}\n\nexport function tFileName(\n fromName: string | types.File | types.GeneratedVideo | types.Video,\n): string | undefined {\n let name: string | undefined;\n\n if (_isFile(fromName)) {\n name = (fromName as types.File).name;\n }\n if (isVideo(fromName)) {\n name = (fromName as types.Video).uri;\n if (name === undefined) {\n return undefined;\n }\n }\n if (isGeneratedVideo(fromName)) {\n name = (fromName as types.GeneratedVideo).video?.uri;\n if (name === undefined) {\n return undefined;\n }\n }\n if (typeof fromName === 'string') {\n name = fromName;\n }\n\n if (name === undefined) {\n throw new Error('Could not extract file name from the provided input.');\n }\n\n if (name.startsWith('https://')) {\n const suffix = name.split('files/')[1];\n const match = suffix.match(/[a-z0-9]+/);\n if (match === null) {\n throw new Error(`Could not extract file name from URI ${name}`);\n }\n name = match[0];\n } else if (name.startsWith('files/')) {\n name = name.split('files/')[1];\n }\n return name;\n}\n\nexport function tModelsUrl(\n apiClient: ApiClient,\n baseModels: boolean | unknown,\n): string {\n let res: string;\n if (apiClient.isVertexAI()) {\n res = baseModels ? 'publishers/google/models' : 'models';\n } else {\n res = baseModels ? 'models' : 'tunedModels';\n }\n return res;\n}\n\nexport function tExtractModels(response: unknown): Record[] {\n for (const key of ['models', 'tunedModels', 'publisherModels']) {\n if (hasField(response, key)) {\n return (response as Record)[key] as Record<\n string,\n unknown\n >[];\n }\n }\n return [];\n}\n\nfunction hasField(data: unknown, fieldName: string): boolean {\n return data !== null && typeof data === 'object' && fieldName in data;\n}\n\nexport function mcpToGeminiTool(\n mcpTool: McpTool,\n config: types.CallableToolConfig = {},\n): types.Tool {\n const mcpToolSchema = mcpTool as Record;\n const functionDeclaration: Record = {\n name: mcpToolSchema['name'],\n description: mcpToolSchema['description'],\n parametersJsonSchema: mcpToolSchema['inputSchema'],\n };\n if (config.behavior) {\n functionDeclaration['behavior'] = config.behavior;\n }\n\n const geminiTool = {\n functionDeclarations: [\n functionDeclaration as unknown as types.FunctionDeclaration,\n ],\n };\n\n return geminiTool;\n}\n\n/**\n * Converts a list of MCP tools to a single Gemini tool with a list of function\n * declarations.\n */\nexport function mcpToolsToGeminiTool(\n mcpTools: McpTool[],\n config: types.CallableToolConfig = {},\n): types.Tool {\n const functionDeclarations: types.FunctionDeclaration[] = [];\n const toolNames = new Set();\n for (const mcpTool of mcpTools) {\n const mcpToolName = mcpTool.name as string;\n if (toolNames.has(mcpToolName)) {\n throw new Error(\n `Duplicate function name ${\n mcpToolName\n } found in MCP tools. Please ensure function names are unique.`,\n );\n }\n toolNames.add(mcpToolName);\n const geminiTool = mcpToGeminiTool(mcpTool, config);\n if (geminiTool.functionDeclarations) {\n functionDeclarations.push(...geminiTool.functionDeclarations);\n }\n }\n\n return {functionDeclarations: functionDeclarations};\n}\n\n// Transforms a source input into a BatchJobSource object with validation.\nexport function tBatchJobSource(\n apiClient: ApiClient,\n src: string | types.InlinedRequest[] | types.BatchJobSource,\n): types.BatchJobSource {\n if (typeof src !== 'string' && !Array.isArray(src)) {\n if (apiClient && apiClient.isVertexAI()) {\n if (src.gcsUri && src.bigqueryUri) {\n throw new Error('Only one of `gcsUri` or `bigqueryUri` can be set.');\n } else if (!src.gcsUri && !src.bigqueryUri) {\n throw new Error('One of `gcsUri` or `bigqueryUri` must be set.');\n }\n } else {\n // Logic for non-Vertex AI client (inlined_requests, file_name)\n if (src.inlinedRequests && src.fileName) {\n throw new Error(\n 'Only one of `inlinedRequests` or `fileName` can be set.',\n );\n } else if (!src.inlinedRequests && !src.fileName) {\n throw new Error('One of `inlinedRequests` or `fileName` must be set.');\n }\n }\n return src;\n }\n // If src is an array (list in Python)\n else if (Array.isArray(src)) {\n return {inlinedRequests: src};\n } else if (typeof src === 'string') {\n if (src.startsWith('gs://')) {\n return {\n format: 'jsonl',\n gcsUri: [src], // GCS URI is expected as an array\n };\n } else if (src.startsWith('bq://')) {\n return {\n format: 'bigquery',\n bigqueryUri: src,\n };\n } else if (src.startsWith('files/')) {\n return {\n fileName: src,\n };\n }\n }\n throw new Error(`Unsupported source: ${src}`);\n}\n\nexport function tBatchJobDestination(\n dest: string | types.BatchJobDestination,\n): types.BatchJobDestination {\n if (typeof dest !== 'string') {\n return dest as types.BatchJobDestination;\n }\n const destString = dest as string;\n if (destString.startsWith('gs://')) {\n return {\n format: 'jsonl',\n gcsUri: destString,\n };\n } else if (destString.startsWith('bq://')) {\n return {\n format: 'bigquery',\n bigqueryUri: destString,\n };\n } else {\n throw new Error(`Unsupported destination: ${destString}`);\n }\n}\n\nexport function tBatchJobName(apiClient: ApiClient, name: unknown): string {\n const nameString = name as string;\n if (!apiClient.isVertexAI()) {\n const mldevPattern = /batches\\/[^/]+$/;\n\n if (mldevPattern.test(nameString)) {\n return nameString.split('/').pop() as string;\n } else {\n throw new Error(`Invalid batch job name: ${nameString}.`);\n }\n }\n\n const vertexPattern =\n /^projects\\/[^/]+\\/locations\\/[^/]+\\/batchPredictionJobs\\/[^/]+$/;\n\n if (vertexPattern.test(nameString)) {\n return nameString.split('/').pop() as string;\n } else if (/^\\d+$/.test(nameString)) {\n return nameString;\n } else {\n throw new Error(`Invalid batch job name: ${nameString}.`);\n }\n}\n\nexport function tJobState(state: unknown): string {\n const stateString = state as string;\n if (stateString === 'BATCH_STATE_UNSPECIFIED') {\n return 'JOB_STATE_UNSPECIFIED';\n } else if (stateString === 'BATCH_STATE_PENDING') {\n return 'JOB_STATE_PENDING';\n } else if (stateString === 'BATCH_STATE_SUCCEEDED') {\n return 'JOB_STATE_SUCCEEDED';\n } else if (stateString === 'BATCH_STATE_FAILED') {\n return 'JOB_STATE_FAILED';\n } else if (stateString === 'BATCH_STATE_CANCELLED') {\n return 'JOB_STATE_CANCELLED';\n } else {\n return stateString;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined\n ) {\n throw new Error(\n 'modelSelectionConfig parameter is not supported in Gemini API.',\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function inlinedRequestToMldev(\n apiClient: ApiClient,\n fromObject: types.InlinedRequest,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['request', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['request', 'contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['request', 'generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function batchJobSourceToMldev(\n apiClient: ApiClient,\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['format']) !== undefined) {\n throw new Error('format parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['bigqueryUri']) !== undefined) {\n throw new Error('bigqueryUri parameter is not supported in Gemini API.');\n }\n\n const fromFileName = common.getValueByPath(fromObject, ['fileName']);\n if (fromFileName != null) {\n common.setValueByPath(toObject, ['fileName'], fromFileName);\n }\n\n const fromInlinedRequests = common.getValueByPath(fromObject, [\n 'inlinedRequests',\n ]);\n if (fromInlinedRequests != null) {\n let transformedList = fromInlinedRequests;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return inlinedRequestToMldev(apiClient, item);\n });\n }\n common.setValueByPath(toObject, ['requests', 'requests'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createBatchJobConfigToMldev(\n fromObject: types.CreateBatchJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['batch', 'displayName'],\n fromDisplayName,\n );\n }\n\n if (common.getValueByPath(fromObject, ['dest']) !== undefined) {\n throw new Error('dest parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function createBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['src']);\n if (fromSrc != null) {\n common.setValueByPath(\n toObject,\n ['batch', 'inputConfig'],\n batchJobSourceToMldev(apiClient, t.tBatchJobSource(apiClient, fromSrc)),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createBatchJobConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function cancelBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CancelBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsConfigToMldev(\n fromObject: types.ListBatchJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n if (common.getValueByPath(fromObject, ['filter']) !== undefined) {\n throw new Error('filter parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function listBatchJobsParametersToMldev(\n fromObject: types.ListBatchJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listBatchJobsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function batchJobSourceToVertex(\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['instancesFormat'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsSource', 'uris'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, ['bigqueryUri']);\n if (fromBigqueryUri != null) {\n common.setValueByPath(\n toObject,\n ['bigquerySource', 'inputUri'],\n fromBigqueryUri,\n );\n }\n\n if (common.getValueByPath(fromObject, ['fileName']) !== undefined) {\n throw new Error('fileName parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['inlinedRequests']) !== undefined) {\n throw new Error('inlinedRequests parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationToVertex(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['predictionsFormat'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(\n toObject,\n ['gcsDestination', 'outputUriPrefix'],\n fromGcsUri,\n );\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, ['bigqueryUri']);\n if (fromBigqueryUri != null) {\n common.setValueByPath(\n toObject,\n ['bigqueryDestination', 'outputUri'],\n fromBigqueryUri,\n );\n }\n\n if (common.getValueByPath(fromObject, ['fileName']) !== undefined) {\n throw new Error('fileName parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['inlinedResponses']) !== undefined) {\n throw new Error(\n 'inlinedResponses parameter is not supported in Vertex AI.',\n );\n }\n\n return toObject;\n}\n\nexport function createBatchJobConfigToVertex(\n fromObject: types.CreateBatchJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDest = common.getValueByPath(fromObject, ['dest']);\n if (parentObject !== undefined && fromDest != null) {\n common.setValueByPath(\n parentObject,\n ['outputConfig'],\n batchJobDestinationToVertex(t.tBatchJobDestination(fromDest)),\n );\n }\n\n return toObject;\n}\n\nexport function createBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], t.tModel(apiClient, fromModel));\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['src']);\n if (fromSrc != null) {\n common.setValueByPath(\n toObject,\n ['inputConfig'],\n batchJobSourceToVertex(t.tBatchJobSource(apiClient, fromSrc)),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createBatchJobConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function cancelBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CancelBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsConfigToVertex(\n fromObject: types.ListBatchJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsParametersToVertex(\n fromObject: types.ListBatchJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listBatchJobsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(toObject, ['content'], contentFromMldev(fromContent));\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function jobErrorFromMldev(\n fromObject: types.JobError,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n return toObject;\n}\n\nexport function inlinedResponseFromMldev(\n fromObject: types.InlinedResponse,\n): Record {\n const toObject: Record = {};\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateContentResponseFromMldev(\n fromResponse as types.GenerateContentResponse,\n ),\n );\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationFromMldev(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFileName = common.getValueByPath(fromObject, ['responsesFile']);\n if (fromFileName != null) {\n common.setValueByPath(toObject, ['fileName'], fromFileName);\n }\n\n const fromInlinedResponses = common.getValueByPath(fromObject, [\n 'inlinedResponses',\n 'inlinedResponses',\n ]);\n if (fromInlinedResponses != null) {\n let transformedList = fromInlinedResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return inlinedResponseFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['inlinedResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function batchJobFromMldev(\n fromObject: types.BatchJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, [\n 'metadata',\n 'displayName',\n ]);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['metadata', 'state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tJobState(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'createTime',\n ]);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'endTime',\n ]);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'updateTime',\n ]);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['metadata', 'model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromDest = common.getValueByPath(fromObject, ['metadata', 'output']);\n if (fromDest != null) {\n common.setValueByPath(\n toObject,\n ['dest'],\n batchJobDestinationFromMldev(fromDest),\n );\n }\n\n return toObject;\n}\n\nexport function listBatchJobsResponseFromMldev(\n fromObject: types.ListBatchJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromBatchJobs = common.getValueByPath(fromObject, ['operations']);\n if (fromBatchJobs != null) {\n let transformedList = fromBatchJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return batchJobFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['batchJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteResourceJobFromMldev(\n fromObject: types.DeleteResourceJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function jobErrorFromVertex(\n fromObject: types.JobError,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n return toObject;\n}\n\nexport function batchJobSourceFromVertex(\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['instancesFormat']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsSource', 'uris']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, [\n 'bigquerySource',\n 'inputUri',\n ]);\n if (fromBigqueryUri != null) {\n common.setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri);\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationFromVertex(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['predictionsFormat']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, [\n 'gcsDestination',\n 'outputUriPrefix',\n ]);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, [\n 'bigqueryDestination',\n 'outputUri',\n ]);\n if (fromBigqueryUri != null) {\n common.setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri);\n }\n\n return toObject;\n}\n\nexport function batchJobFromVertex(\n fromObject: types.BatchJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tJobState(fromState));\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['inputConfig']);\n if (fromSrc != null) {\n common.setValueByPath(toObject, ['src'], batchJobSourceFromVertex(fromSrc));\n }\n\n const fromDest = common.getValueByPath(fromObject, ['outputConfig']);\n if (fromDest != null) {\n common.setValueByPath(\n toObject,\n ['dest'],\n batchJobDestinationFromVertex(fromDest),\n );\n }\n\n return toObject;\n}\n\nexport function listBatchJobsResponseFromVertex(\n fromObject: types.ListBatchJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromBatchJobs = common.getValueByPath(fromObject, [\n 'batchPredictionJobs',\n ]);\n if (fromBatchJobs != null) {\n let transformedList = fromBatchJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return batchJobFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['batchJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteResourceJobFromVertex(\n fromObject: types.DeleteResourceJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError));\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Pagers for the GenAI List APIs.\n */\n\nimport * as types from '../src/types';\n\nexport enum PagedItem {\n PAGED_ITEM_BATCH_JOBS = 'batchJobs',\n PAGED_ITEM_MODELS = 'models',\n PAGED_ITEM_TUNING_JOBS = 'tuningJobs',\n PAGED_ITEM_FILES = 'files',\n PAGED_ITEM_CACHED_CONTENTS = 'cachedContents',\n}\n\ninterface PagedItemConfig {\n config?: {\n pageToken?: string;\n pageSize?: number;\n };\n}\n\ninterface PagedItemResponse {\n nextPageToken?: string;\n sdkHttpResponse?: types.HttpResponse;\n batchJobs?: T[];\n models?: T[];\n tuningJobs?: T[];\n files?: T[];\n cachedContents?: T[];\n}\n\n/**\n * Pager class for iterating through paginated results.\n */\nexport class Pager implements AsyncIterable {\n private nameInternal!: PagedItem;\n private pageInternal: T[] = [];\n private paramsInternal: PagedItemConfig = {};\n private pageInternalSize!: number;\n private sdkHttpResponseInternal?: types.HttpResponse;\n protected requestInternal!: (\n params: PagedItemConfig,\n ) => Promise>;\n protected idxInternal!: number;\n\n constructor(\n name: PagedItem,\n request: (params: PagedItemConfig) => Promise>,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.requestInternal = request;\n this.init(name, response, params);\n }\n\n private init(\n name: PagedItem,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.nameInternal = name;\n this.pageInternal = response[this.nameInternal] || [];\n\n this.sdkHttpResponseInternal = response?.sdkHttpResponse;\n this.idxInternal = 0;\n let requestParams: PagedItemConfig = {config: {}};\n if (!params || Object.keys(params).length === 0) {\n requestParams = {config: {}};\n } else if (typeof params === 'object') {\n requestParams = {...params};\n } else {\n requestParams = params;\n }\n if (requestParams['config']) {\n requestParams['config']['pageToken'] = response['nextPageToken'];\n }\n this.paramsInternal = requestParams;\n this.pageInternalSize =\n requestParams['config']?.['pageSize'] ?? this.pageInternal.length;\n }\n\n private initNextPage(response: PagedItemResponse): void {\n this.init(this.nameInternal, response, this.paramsInternal);\n }\n\n /**\n * Returns the current page, which is a list of items.\n *\n * @remarks\n * The first page is retrieved when the pager is created. The returned list of\n * items could be a subset of the entire list.\n */\n get page(): T[] {\n return this.pageInternal;\n }\n\n /**\n * Returns the type of paged item (for example, ``batch_jobs``).\n */\n get name(): PagedItem {\n return this.nameInternal;\n }\n\n /**\n * Returns the length of the page fetched each time by this pager.\n *\n * @remarks\n * The number of items in the page is less than or equal to the page length.\n */\n get pageSize(): number {\n return this.pageInternalSize;\n }\n\n /**\n * Returns the headers of the API response.\n */\n get sdkHttpResponse(): types.HttpResponse | undefined {\n return this.sdkHttpResponseInternal;\n }\n\n /**\n * Returns the parameters when making the API request for the next page.\n *\n * @remarks\n * Parameters contain a set of optional configs that can be\n * used to customize the API request. For example, the `pageToken` parameter\n * contains the token to request the next page.\n */\n get params(): PagedItemConfig {\n return this.paramsInternal;\n }\n\n /**\n * Returns the total number of items in the current page.\n */\n get pageLength(): number {\n return this.pageInternal.length;\n }\n\n /**\n * Returns the item at the given index.\n */\n getItem(index: number): T {\n return this.pageInternal[index];\n }\n\n /**\n * Returns an async iterator that support iterating through all items\n * retrieved from the API.\n *\n * @remarks\n * The iterator will automatically fetch the next page if there are more items\n * to fetch from the API.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * for await (const file of pager) {\n * console.log(file.name);\n * }\n * ```\n */\n [Symbol.asyncIterator](): AsyncIterator {\n return {\n next: async () => {\n if (this.idxInternal >= this.pageLength) {\n if (this.hasNextPage()) {\n await this.nextPage();\n } else {\n return {value: undefined, done: true};\n }\n }\n const item = this.getItem(this.idxInternal);\n this.idxInternal += 1;\n return {value: item, done: false};\n },\n return: async () => {\n return {value: undefined, done: true};\n },\n };\n }\n\n /**\n * Fetches the next page of items. This makes a new API request.\n *\n * @throws {Error} If there are no more pages to fetch.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * let page = pager.page;\n * while (true) {\n * for (const file of page) {\n * console.log(file.name);\n * }\n * if (!pager.hasNextPage()) {\n * break;\n * }\n * page = await pager.nextPage();\n * }\n * ```\n */\n async nextPage(): Promise {\n if (!this.hasNextPage()) {\n throw new Error('No more pages to fetch.');\n }\n const response = await this.requestInternal(this.params);\n this.initNextPage(response);\n return this.page;\n }\n\n /**\n * Returns true if there are more pages to fetch from the API.\n */\n hasNextPage(): boolean {\n if (this.params['config']?.['pageToken'] !== undefined) {\n return true;\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_batches_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Batches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Create batch job.\n *\n * @param params - The parameters for create batch job request.\n * @return The created batch job.\n *\n * @example\n * ```ts\n * const response = await ai.batches.create({\n * model: 'gemini-2.0-flash',\n * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'},\n * config: {\n * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'},\n * }\n * });\n * console.log(response);\n * ```\n */\n create = async (\n params: types.CreateBatchJobParameters,\n ): Promise => {\n if (this.apiClient.isVertexAI()) {\n const timestamp = Date.now();\n const timestampStr = timestamp.toString();\n if (Array.isArray(params.src)) {\n throw new Error(\n 'InlinedRequest[] is not supported in Vertex AI. Please use ' +\n 'Google Cloud Storage URI or BigQuery URI instead.',\n );\n }\n params.config = params.config || {};\n if (params.config.displayName === undefined) {\n params.config.displayName = 'genaiBatchJob_${timestampStr}';\n }\n if (params.config.dest === undefined && typeof params.src === 'string') {\n if (params.src.startsWith('gs://') && params.src.endsWith('.jsonl')) {\n params.config.dest = `${params.src.slice(0, -6)}/dest`;\n } else if (params.src.startsWith('bq://')) {\n params.config.dest =\n `${params.src}_dest_${timestampStr}` as unknown as string;\n } else {\n throw new Error('Unsupported source:' + params.src);\n }\n }\n } else {\n if (\n Array.isArray(params.src) ||\n (typeof params.src !== 'string' && params.src.inlinedRequests)\n ) {\n // Move system instruction to httpOptions extraBody.\n\n let path: string = '';\n let queryParams: Record = {};\n const body = converters.createBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchGenerateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n // Move system instruction to 'request':\n // {'systemInstruction': system_instruction}\n const batch = body['batch'] as {[key: string]: unknown};\n const inputConfig = batch['inputConfig'] as {[key: string]: unknown};\n const requestsWrapper = inputConfig['requests'] as {\n [key: string]: unknown;\n };\n const requests = requestsWrapper['requests'] as Array<{\n [key: string]: unknown;\n }>;\n const newRequests = [];\n for (const request of requests) {\n const requestDict = request as {[key: string]: unknown};\n if (requestDict['systemInstruction']) {\n const systemInstructionValue = requestDict['systemInstruction'];\n delete requestDict['systemInstruction'];\n const requestContent = requestDict['request'] as {\n [key: string]: unknown;\n };\n requestContent['systemInstruction'] = systemInstructionValue;\n requestDict['request'] = requestContent;\n }\n newRequests.push(requestDict);\n }\n requestsWrapper['requests'] = newRequests;\n\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n return await this.createInternal(params);\n };\n\n /**\n * Lists batch job configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of batch jobs.\n *\n * @example\n * ```ts\n * const batchJobs = await ai.batches.list({config: {'pageSize': 2}});\n * for await (const batchJob of batchJobs) {\n * console.log(batchJob);\n * }\n * ```\n */\n list = async (\n params: types.ListBatchJobsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_BATCH_JOBS,\n (x: types.ListBatchJobsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Internal method to create batch job.\n *\n * @param params - The parameters for create batch job request.\n * @return The created batch job.\n *\n */\n private async createInternal(\n params: types.CreateBatchJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromVertex(apiResponse);\n\n return resp as types.BatchJob;\n });\n } else {\n const body = converters.createBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchGenerateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n\n /**\n * Gets batch job configurations.\n *\n * @param params - The parameters for the get request.\n * @return The batch job.\n *\n * @example\n * ```ts\n * await ai.batches.get({name: '...'}); // The server-generated resource name.\n * ```\n */\n async get(params: types.GetBatchJobParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromVertex(apiResponse);\n\n return resp as types.BatchJob;\n });\n } else {\n const body = converters.getBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n\n /**\n * Cancels a batch job.\n *\n * @param params - The parameters for the cancel request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.batches.cancel({name: '...'}); // The server-generated resource name.\n * ```\n */\n async cancel(params: types.CancelBatchJobParameters): Promise {\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.cancelBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n } else {\n const body = converters.cancelBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n }\n }\n\n private async listInternal(\n params: types.ListBatchJobsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listBatchJobsParametersToVertex(params);\n path = common.formatMap(\n 'batchPredictionJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListBatchJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listBatchJobsResponseFromVertex(apiResponse);\n const typedResp = new types.ListBatchJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listBatchJobsParametersToMldev(params);\n path = common.formatMap(\n 'batches',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListBatchJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listBatchJobsResponseFromMldev(apiResponse);\n const typedResp = new types.ListBatchJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Deletes a batch job.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.batches.delete({name: '...'}); // The server-generated resource name.\n * ```\n */\n async delete(\n params: types.DeleteBatchJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteResourceJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteResourceJobFromVertex(apiResponse);\n\n return resp as types.DeleteResourceJob;\n });\n } else {\n const body = converters.deleteBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteResourceJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteResourceJobFromMldev(apiResponse);\n\n return resp as types.DeleteResourceJob;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToMldev(\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['contents'], transformedList);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['kmsKeyName']) !== undefined) {\n throw new Error('kmsKeyName parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToMldev(\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToMldev(\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToMldev(\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(\n fromObject: types.EnterpriseWebSearch,\n): Record {\n const toObject: Record = {};\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToVertex(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(fromEnterpriseWebSearch),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToVertex(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToVertex(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToVertex(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToVertex(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToVertex(\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['contents'], transformedList);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(fromToolConfig),\n );\n }\n\n const fromKmsKeyName = common.getValueByPath(fromObject, ['kmsKeyName']);\n if (parentObject !== undefined && fromKmsKeyName != null) {\n common.setValueByPath(\n parentObject,\n ['encryption_spec', 'kmsKeyName'],\n fromKmsKeyName,\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToVertex(\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToVertex(\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToVertex(\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function cachedContentFromMldev(\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromMldev(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromMldev(\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n let transformedList = fromCachedContents;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return cachedContentFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['cachedContents'], transformedList);\n }\n\n return toObject;\n}\n\nexport function cachedContentFromVertex(\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromVertex(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromVertex(\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n let transformedList = fromCachedContents;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return cachedContentFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['cachedContents'], transformedList);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_caches_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Caches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists cached content configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of cached contents.\n *\n * @example\n * ```ts\n * const cachedContents = await ai.caches.list({config: {'pageSize': 2}});\n * for await (const cachedContent of cachedContents) {\n * console.log(cachedContent);\n * }\n * ```\n */\n list = async (\n params: types.ListCachedContentsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_CACHED_CONTENTS,\n (x: types.ListCachedContentsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a cached contents resource.\n *\n * @remarks\n * Context caching is only supported for specific models. See [Gemini\n * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac)\n * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models)\n * for more information.\n *\n * @param params - The parameters for the create request.\n * @return The created cached content.\n *\n * @example\n * ```ts\n * const contents = ...; // Initialize the content to cache.\n * const response = await ai.caches.create({\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'contents': contents,\n * 'displayName': 'test cache',\n * 'systemInstruction': 'What is the sum of the two pdfs?',\n * 'ttl': '86400s',\n * }\n * });\n * ```\n */\n async create(\n params: types.CreateCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.createCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Gets cached content configurations.\n *\n * @param params - The parameters for the get request.\n * @return The cached content.\n *\n * @example\n * ```ts\n * await ai.caches.get({name: '...'}); // The server-generated resource name.\n * ```\n */\n async get(\n params: types.GetCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.getCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Deletes cached content.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.caches.delete({name: '...'}); // The server-generated resource name.\n * ```\n */\n async delete(\n params: types.DeleteCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteCachedContentResponseFromVertex();\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteCachedContentResponseFromMldev();\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates cached content configurations.\n *\n * @param params - The parameters for the update request.\n * @return The updated cached content.\n *\n * @example\n * ```ts\n * const response = await ai.caches.update({\n * name: '...', // The server-generated resource name.\n * config: {'ttl': '7600s'}\n * });\n * ```\n */\n async update(\n params: types.UpdateCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.updateCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n private async listInternal(\n params: types.ListCachedContentsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listCachedContentsParametersToVertex(params);\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListCachedContentsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.listCachedContentsResponseFromVertex(apiResponse);\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listCachedContentsParametersToMldev(params);\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListCachedContentsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.listCachedContentsResponseFromMldev(apiResponse);\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client.js';\nimport * as t from './_transformers.js';\nimport {Models} from './models.js';\nimport * as types from './types.js';\n\n/**\n * Returns true if the response is valid, false otherwise.\n */\nfunction isValidResponse(response: types.GenerateContentResponse): boolean {\n if (response.candidates == undefined || response.candidates.length === 0) {\n return false;\n }\n const content = response.candidates[0]?.content;\n if (content === undefined) {\n return false;\n }\n return isValidContent(content);\n}\n\nfunction isValidContent(content: types.Content): boolean {\n if (content.parts === undefined || content.parts.length === 0) {\n return false;\n }\n for (const part of content.parts) {\n if (part === undefined || Object.keys(part).length === 0) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Validates the history contains the correct roles.\n *\n * @throws Error if the history does not start with a user turn.\n * @throws Error if the history contains an invalid role.\n */\nfunction validateHistory(history: types.Content[]) {\n // Empty history is valid.\n if (history.length === 0) {\n return;\n }\n for (const content of history) {\n if (content.role !== 'user' && content.role !== 'model') {\n throw new Error(`Role must be user or model, but got ${content.role}.`);\n }\n }\n}\n\n/**\n * Extracts the curated (valid) history from a comprehensive history.\n *\n * @remarks\n * The model may sometimes generate invalid or empty contents(e.g., due to safty\n * filters or recitation). Extracting valid turns from the history\n * ensures that subsequent requests could be accpeted by the model.\n */\nfunction extractCuratedHistory(\n comprehensiveHistory: types.Content[],\n): types.Content[] {\n if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) {\n return [];\n }\n const curatedHistory: types.Content[] = [];\n const length = comprehensiveHistory.length;\n let i = 0;\n while (i < length) {\n if (comprehensiveHistory[i].role === 'user') {\n curatedHistory.push(comprehensiveHistory[i]);\n i++;\n } else {\n const modelOutput: types.Content[] = [];\n let isValid = true;\n while (i < length && comprehensiveHistory[i].role === 'model') {\n modelOutput.push(comprehensiveHistory[i]);\n if (isValid && !isValidContent(comprehensiveHistory[i])) {\n isValid = false;\n }\n i++;\n }\n if (isValid) {\n curatedHistory.push(...modelOutput);\n } else {\n // Remove the last user input when model content is invalid.\n curatedHistory.pop();\n }\n }\n }\n return curatedHistory;\n}\n\n/**\n * A utility class to create a chat session.\n */\nexport class Chats {\n private readonly modelsModule: Models;\n private readonly apiClient: ApiClient;\n\n constructor(modelsModule: Models, apiClient: ApiClient) {\n this.modelsModule = modelsModule;\n this.apiClient = apiClient;\n }\n\n /**\n * Creates a new chat session.\n *\n * @remarks\n * The config in the params will be used for all requests within the chat\n * session unless overridden by a per-request `config` in\n * @see {@link types.SendMessageParameters#config}.\n *\n * @param params - Parameters for creating a chat session.\n * @returns A new chat session.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({\n * model: 'gemini-2.0-flash'\n * config: {\n * temperature: 0.5,\n * maxOutputTokens: 1024,\n * }\n * });\n * ```\n */\n create(params: types.CreateChatParameters) {\n return new Chat(\n this.apiClient,\n this.modelsModule,\n params.model,\n params.config,\n // Deep copy the history to avoid mutating the history outside of the\n // chat session.\n structuredClone(params.history),\n );\n }\n}\n\n/**\n * Chat session that enables sending messages to the model with previous\n * conversation context.\n *\n * @remarks\n * The session maintains all the turns between user and model.\n */\nexport class Chat {\n // A promise to represent the current state of the message being sent to the\n // model.\n private sendPromise: Promise = Promise.resolve();\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly modelsModule: Models,\n private readonly model: string,\n private readonly config: types.GenerateContentConfig = {},\n private history: types.Content[] = [],\n ) {\n validateHistory(history);\n }\n\n /**\n * Sends a message to the model and returns the response.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessageStream} for streaming method.\n * @param params - parameters for sending messages within a chat session.\n * @returns The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessage({\n * message: 'Why is the sky blue?'\n * });\n * console.log(response.text);\n * ```\n */\n async sendMessage(\n params: types.SendMessageParameters,\n ): Promise {\n await this.sendPromise;\n const inputContent = t.tContent(params.message);\n const responsePromise = this.modelsModule.generateContent({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n this.sendPromise = (async () => {\n const response = await responsePromise;\n const outputContent = response.candidates?.[0]?.content;\n\n // Because the AFC input contains the entire curated chat history in\n // addition to the new user input, we need to truncate the AFC history\n // to deduplicate the existing chat history.\n const fullAutomaticFunctionCallingHistory =\n response.automaticFunctionCallingHistory;\n const index = this.getHistory(true).length;\n\n let automaticFunctionCallingHistory: types.Content[] = [];\n if (fullAutomaticFunctionCallingHistory != null) {\n automaticFunctionCallingHistory =\n fullAutomaticFunctionCallingHistory.slice(index) ?? [];\n }\n\n const modelOutput = outputContent ? [outputContent] : [];\n this.recordHistory(\n inputContent,\n modelOutput,\n automaticFunctionCallingHistory,\n );\n return;\n })();\n await this.sendPromise.catch(() => {\n // Resets sendPromise to avoid subsequent calls failing\n this.sendPromise = Promise.resolve();\n });\n return responsePromise;\n }\n\n /**\n * Sends a message to the model and returns the response in chunks.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessage} for non-streaming method.\n * @param params - parameters for sending the message.\n * @return The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessageStream({\n * message: 'Why is the sky blue?'\n * });\n * for await (const chunk of response) {\n * console.log(chunk.text);\n * }\n * ```\n */\n async sendMessageStream(\n params: types.SendMessageParameters,\n ): Promise> {\n await this.sendPromise;\n const inputContent = t.tContent(params.message);\n const streamResponse = this.modelsModule.generateContentStream({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n // Resolve the internal tracking of send completion promise - `sendPromise`\n // for both success and failure response. The actual failure is still\n // propagated by the `await streamResponse`.\n this.sendPromise = streamResponse\n .then(() => undefined)\n .catch(() => undefined);\n const response = await streamResponse;\n const result = this.processStreamResponse(response, inputContent);\n return result;\n }\n\n /**\n * Returns the chat history.\n *\n * @remarks\n * The history is a list of contents alternating between user and model.\n *\n * There are two types of history:\n * - The `curated history` contains only the valid turns between user and\n * model, which will be included in the subsequent requests sent to the model.\n * - The `comprehensive history` contains all turns, including invalid or\n * empty model outputs, providing a complete record of the history.\n *\n * The history is updated after receiving the response from the model,\n * for streaming response, it means receiving the last chunk of the response.\n *\n * The `comprehensive history` is returned by default. To get the `curated\n * history`, set the `curated` parameter to `true`.\n *\n * @param curated - whether to return the curated history or the comprehensive\n * history.\n * @return History contents alternating between user and model for the entire\n * chat session.\n */\n getHistory(curated: boolean = false): types.Content[] {\n const history = curated\n ? extractCuratedHistory(this.history)\n : this.history;\n // Deep copy the history to avoid mutating the history outside of the\n // chat session.\n return structuredClone(history);\n }\n\n private async *processStreamResponse(\n streamResponse: AsyncGenerator,\n inputContent: types.Content,\n ) {\n const outputContent: types.Content[] = [];\n for await (const chunk of streamResponse) {\n if (isValidResponse(chunk)) {\n const content = chunk.candidates?.[0]?.content;\n if (content !== undefined) {\n outputContent.push(content);\n }\n }\n yield chunk;\n }\n this.recordHistory(inputContent, outputContent);\n }\n\n private recordHistory(\n userInput: types.Content,\n modelOutput: types.Content[],\n automaticFunctionCallingHistory?: types.Content[],\n ) {\n let outputContents: types.Content[] = [];\n if (\n modelOutput.length > 0 &&\n modelOutput.every((content) => content.role !== undefined)\n ) {\n outputContents = modelOutput;\n } else {\n // Appends an empty content when model returns empty response, so that the\n // history is always alternating between user and model.\n outputContents.push({\n role: 'model',\n parts: [],\n } as types.Content);\n }\n if (\n automaticFunctionCallingHistory &&\n automaticFunctionCallingHistory.length > 0\n ) {\n this.history.push(\n ...extractCuratedHistory(automaticFunctionCallingHistory!),\n );\n } else {\n this.history.push(userInput);\n }\n this.history.push(...outputContents);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Details for errors from calling the API.\n */\nexport interface ApiErrorInfo {\n /** The error message. */\n message: string;\n /** The HTTP status code. */\n status: number;\n}\n\n/**\n * API errors raised by the GenAI API.\n */\nexport class ApiError extends Error {\n /** HTTP status code */\n status: number;\n\n constructor(options: ApiErrorInfo) {\n super(options.message);\n this.name = 'ApiError';\n this.status = options.status;\n Object.setPrototypeOf(this, ApiError.prototype);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from './_auth.js';\nimport * as common from './_common.js';\nimport {Downloader} from './_downloader.js';\nimport {Uploader} from './_uploader.js';\nimport {ApiError} from './errors.js';\nimport {\n DownloadFileParameters,\n File,\n HttpOptions,\n HttpResponse,\n UploadFileConfig,\n} from './types.js';\n\nconst CONTENT_TYPE_HEADER = 'Content-Type';\nconst SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';\nconst USER_AGENT_HEADER = 'User-Agent';\nexport const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';\nexport const SDK_VERSION = '1.15.0'; // x-release-please-version\nconst LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;\nconst VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';\nconst GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';\nconst responseLineRE = /^data: (.*)(?:\\n\\n|\\r\\r|\\r\\n\\r\\n)/;\n\n/**\n * Options for initializing the ApiClient. The ApiClient uses the parameters\n * for authentication purposes as well as to infer if SDK should send the\n * request to Vertex AI or Gemini API.\n */\nexport interface ApiClientInitOptions {\n /**\n * The object used for adding authentication headers to API requests.\n */\n auth: Auth;\n /**\n * The uploader to use for uploading files. This field is required for\n * creating a client, will be set through the Node_client or Web_client.\n */\n uploader: Uploader;\n /**\n * Optional. The downloader to use for downloading files. This field is\n * required for creating a client, will be set through the Node_client or\n * Web_client.\n */\n downloader: Downloader;\n /**\n * Optional. The Google Cloud project ID for Vertex AI users.\n * It is not the numeric project name.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n project?: string;\n /**\n * Optional. The Google Cloud project location for Vertex AI users.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n location?: string;\n /**\n * The API Key. This is required for Gemini API users.\n */\n apiKey?: string;\n /**\n * Optional. Set to true if you intend to call Vertex AI endpoints.\n * If unset, default SDK behavior is to call Gemini API.\n */\n vertexai?: boolean;\n /**\n * Optional. The API version for the endpoint.\n * If unset, SDK will choose a default api version.\n */\n apiVersion?: string;\n /**\n * Optional. A set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional. An extra string to append at the end of the User-Agent header.\n *\n * This can be used to e.g specify the runtime and its version.\n */\n userAgentExtra?: string;\n}\n\n/**\n * Represents the necessary information to send a request to an API endpoint.\n * This interface defines the structure for constructing and executing HTTP\n * requests.\n */\nexport interface HttpRequest {\n /**\n * URL path from the modules, this path is appended to the base API URL to\n * form the complete request URL.\n *\n * If you wish to set full URL, use httpOptions.baseUrl instead. Example to\n * set full URL in the request:\n *\n * const request: HttpRequest = {\n * path: '',\n * httpOptions: {\n * baseUrl: 'https://',\n * apiVersion: '',\n * },\n * httpMethod: 'GET',\n * };\n *\n * The result URL will be: https://\n *\n */\n path: string;\n /**\n * Optional query parameters to be appended to the request URL.\n */\n queryParams?: Record;\n /**\n * Optional request body in json string or Blob format, GET request doesn't\n * need a request body.\n */\n body?: string | Blob;\n /**\n * The HTTP method to be used for the request.\n */\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE';\n /**\n * Optional set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional abort signal which can be used to cancel the request.\n */\n abortSignal?: AbortSignal;\n}\n\n/**\n * The ApiClient class is used to send requests to the Gemini API or Vertex AI\n * endpoints.\n */\nexport class ApiClient {\n readonly clientOptions: ApiClientInitOptions;\n\n constructor(opts: ApiClientInitOptions) {\n this.clientOptions = {\n ...opts,\n project: opts.project,\n location: opts.location,\n apiKey: opts.apiKey,\n vertexai: opts.vertexai,\n };\n\n const initHttpOptions: HttpOptions = {};\n\n if (this.clientOptions.vertexai) {\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? VERTEX_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = this.baseUrlFromProjectLocation();\n this.normalizeAuthParameters();\n } else {\n // Gemini API\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? GOOGLE_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`;\n }\n\n initHttpOptions.headers = this.getDefaultHeaders();\n\n this.clientOptions.httpOptions = initHttpOptions;\n\n if (opts.httpOptions) {\n this.clientOptions.httpOptions = this.patchHttpOptions(\n initHttpOptions,\n opts.httpOptions,\n );\n }\n }\n\n /**\n * Determines the base URL for Vertex AI based on project and location.\n * Uses the global endpoint if location is 'global' or if project/location\n * are not specified (implying API key usage).\n * @private\n */\n private baseUrlFromProjectLocation(): string {\n if (\n this.clientOptions.project &&\n this.clientOptions.location &&\n this.clientOptions.location !== 'global'\n ) {\n // Regional endpoint\n return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`;\n }\n // Global endpoint (covers 'global' location and API key usage)\n return `https://aiplatform.googleapis.com/`;\n }\n\n /**\n * Normalizes authentication parameters for Vertex AI.\n * If project and location are provided, API key is cleared.\n * If project and location are not provided (implying API key usage),\n * project and location are cleared.\n * @private\n */\n private normalizeAuthParameters(): void {\n if (this.clientOptions.project && this.clientOptions.location) {\n // Using project/location for auth, clear potential API key\n this.clientOptions.apiKey = undefined;\n return;\n }\n // Using API key for auth (or no auth provided yet), clear project/location\n this.clientOptions.project = undefined;\n this.clientOptions.location = undefined;\n }\n\n isVertexAI(): boolean {\n return this.clientOptions.vertexai ?? false;\n }\n\n getProject() {\n return this.clientOptions.project;\n }\n\n getLocation() {\n return this.clientOptions.location;\n }\n\n getApiVersion() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.apiVersion !== undefined\n ) {\n return this.clientOptions.httpOptions.apiVersion;\n }\n throw new Error('API version is not set.');\n }\n\n getBaseUrl() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.baseUrl !== undefined\n ) {\n return this.clientOptions.httpOptions.baseUrl;\n }\n throw new Error('Base URL is not set.');\n }\n\n getRequestUrl() {\n return this.getRequestUrlInternal(this.clientOptions.httpOptions);\n }\n\n getHeaders() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.headers !== undefined\n ) {\n return this.clientOptions.httpOptions.headers;\n } else {\n throw new Error('Headers are not set.');\n }\n }\n\n private getRequestUrlInternal(httpOptions?: HttpOptions) {\n if (\n !httpOptions ||\n httpOptions.baseUrl === undefined ||\n httpOptions.apiVersion === undefined\n ) {\n throw new Error('HTTP options are not correctly set.');\n }\n const baseUrl = httpOptions.baseUrl.endsWith('/')\n ? httpOptions.baseUrl.slice(0, -1)\n : httpOptions.baseUrl;\n const urlElement: Array = [baseUrl];\n if (httpOptions.apiVersion && httpOptions.apiVersion !== '') {\n urlElement.push(httpOptions.apiVersion);\n }\n return urlElement.join('/');\n }\n\n getBaseResourcePath() {\n return `projects/${this.clientOptions.project}/locations/${\n this.clientOptions.location\n }`;\n }\n\n getApiKey() {\n return this.clientOptions.apiKey;\n }\n\n getWebsocketBaseUrl() {\n const baseUrl = this.getBaseUrl();\n const urlParts = new URL(baseUrl);\n urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss';\n return urlParts.toString();\n }\n\n setBaseUrl(url: string) {\n if (this.clientOptions.httpOptions) {\n this.clientOptions.httpOptions.baseUrl = url;\n } else {\n throw new Error('HTTP options are not correctly set.');\n }\n }\n\n private constructUrl(\n path: string,\n httpOptions: HttpOptions,\n prependProjectLocation: boolean,\n ): URL {\n const urlElement: Array = [this.getRequestUrlInternal(httpOptions)];\n if (prependProjectLocation) {\n urlElement.push(this.getBaseResourcePath());\n }\n if (path !== '') {\n urlElement.push(path);\n }\n const url = new URL(`${urlElement.join('/')}`);\n\n return url;\n }\n\n private shouldPrependVertexProjectPath(request: HttpRequest): boolean {\n if (this.clientOptions.apiKey) {\n return false;\n }\n if (!this.clientOptions.vertexai) {\n return false;\n }\n if (request.path.startsWith('projects/')) {\n // Assume the path already starts with\n // `projects//location/`.\n return false;\n }\n if (\n request.httpMethod === 'GET' &&\n request.path.startsWith('publishers/google/models')\n ) {\n // These paths are used by Vertex's models.get and models.list\n // calls. For base models Vertex does not accept a project/location\n // prefix (for tuned model the prefix is required).\n return false;\n }\n return true;\n }\n\n async request(request: HttpRequest): Promise {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const prependProjectLocation = this.shouldPrependVertexProjectPath(request);\n const url = this.constructUrl(\n request.path,\n patchedHttpOptions,\n prependProjectLocation,\n );\n if (request.queryParams) {\n for (const [key, value] of Object.entries(request.queryParams)) {\n url.searchParams.append(key, String(value));\n }\n }\n let requestInit: RequestInit = {};\n if (request.httpMethod === 'GET') {\n if (request.body && request.body !== '{}') {\n throw new Error(\n 'Request body should be empty for GET request, but got non empty request body',\n );\n }\n } else {\n requestInit.body = request.body;\n }\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n request.abortSignal,\n );\n return this.unaryApiCall(url, requestInit, request.httpMethod);\n }\n\n private patchHttpOptions(\n baseHttpOptions: HttpOptions,\n requestHttpOptions: HttpOptions,\n ): HttpOptions {\n const patchedHttpOptions = JSON.parse(\n JSON.stringify(baseHttpOptions),\n ) as HttpOptions;\n\n for (const [key, value] of Object.entries(requestHttpOptions)) {\n // Records compile to objects.\n if (typeof value === 'object') {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = {...patchedHttpOptions[key], ...value};\n } else if (value !== undefined) {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = value;\n }\n }\n return patchedHttpOptions;\n }\n\n async requestStream(\n request: HttpRequest,\n ): Promise> {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const prependProjectLocation = this.shouldPrependVertexProjectPath(request);\n const url = this.constructUrl(\n request.path,\n patchedHttpOptions,\n prependProjectLocation,\n );\n if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') {\n url.searchParams.set('alt', 'sse');\n }\n let requestInit: RequestInit = {};\n requestInit.body = request.body;\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n request.abortSignal,\n );\n return this.streamApiCall(url, requestInit, request.httpMethod);\n }\n\n private async includeExtraHttpOptionsToRequestInit(\n requestInit: RequestInit,\n httpOptions: HttpOptions,\n abortSignal?: AbortSignal,\n ): Promise {\n if ((httpOptions && httpOptions.timeout) || abortSignal) {\n const abortController = new AbortController();\n const signal = abortController.signal;\n if (httpOptions.timeout && httpOptions?.timeout > 0) {\n const timeoutHandle = setTimeout(\n () => abortController.abort(),\n httpOptions.timeout,\n );\n if (\n timeoutHandle &&\n typeof (timeoutHandle as unknown as NodeJS.Timeout).unref ===\n 'function'\n ) {\n // call unref to prevent nodejs process from hanging, see\n // https://nodejs.org/api/timers.html#timeoutunref\n timeoutHandle.unref();\n }\n }\n if (abortSignal) {\n abortSignal.addEventListener('abort', () => {\n abortController.abort();\n });\n }\n requestInit.signal = signal;\n }\n if (httpOptions && httpOptions.extraBody !== null) {\n includeExtraBodyToRequestInit(\n requestInit,\n httpOptions.extraBody as Record,\n );\n }\n requestInit.headers = await this.getHeadersInternal(httpOptions);\n return requestInit;\n }\n\n private async unaryApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return new HttpResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n private async streamApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise> {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return this.processStreamResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n async *processStreamResponse(\n response: Response,\n ): AsyncGenerator {\n const reader = response?.body?.getReader();\n const decoder = new TextDecoder('utf-8');\n if (!reader) {\n throw new Error('Response body is empty');\n }\n\n try {\n let buffer = '';\n while (true) {\n const {done, value} = await reader.read();\n if (done) {\n if (buffer.trim().length > 0) {\n throw new Error('Incomplete JSON segment at the end');\n }\n break;\n }\n const chunkString = decoder.decode(value, {stream: true});\n\n // Parse and throw an error if the chunk contains an error.\n try {\n const chunkJson = JSON.parse(chunkString) as Record;\n if ('error' in chunkJson) {\n const errorJson = JSON.parse(\n JSON.stringify(chunkJson['error']),\n ) as Record;\n const status = errorJson['status'] as string;\n const code = errorJson['code'] as number;\n const errorMessage = `got status: ${status}. ${JSON.stringify(\n chunkJson,\n )}`;\n if (code >= 400 && code < 600) {\n const apiError = new ApiError({\n message: errorMessage,\n status: code,\n });\n throw apiError;\n }\n }\n } catch (e: unknown) {\n const error = e as Error;\n if (error.name === 'ApiError') {\n throw e;\n }\n }\n buffer += chunkString;\n let match = buffer.match(responseLineRE);\n while (match) {\n const processedChunkString = match[1];\n try {\n const partialResponse = new Response(processedChunkString, {\n headers: response?.headers,\n status: response?.status,\n statusText: response?.statusText,\n });\n yield new HttpResponse(partialResponse);\n buffer = buffer.slice(match[0].length);\n match = buffer.match(responseLineRE);\n } catch (e) {\n throw new Error(\n `exception parsing stream chunk ${processedChunkString}. ${e}`,\n );\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n private async apiCall(\n url: string,\n requestInit: RequestInit,\n ): Promise {\n return fetch(url, requestInit).catch((e) => {\n throw new Error(`exception ${e} sending request`);\n });\n }\n\n getDefaultHeaders(): Record {\n const headers: Record = {};\n\n const versionHeaderValue =\n LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra;\n\n headers[USER_AGENT_HEADER] = versionHeaderValue;\n headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue;\n headers[CONTENT_TYPE_HEADER] = 'application/json';\n\n return headers;\n }\n\n private async getHeadersInternal(\n httpOptions: HttpOptions | undefined,\n ): Promise {\n const headers = new Headers();\n if (httpOptions && httpOptions.headers) {\n for (const [key, value] of Object.entries(httpOptions.headers)) {\n headers.append(key, value);\n }\n // Append a timeout header if it is set, note that the timeout option is\n // in milliseconds but the header is in seconds.\n if (httpOptions.timeout && httpOptions.timeout > 0) {\n headers.append(\n SERVER_TIMEOUT_HEADER,\n String(Math.ceil(httpOptions.timeout / 1000)),\n );\n }\n }\n await this.clientOptions.auth.addAuthHeaders(headers);\n return headers;\n }\n\n /**\n * Uploads a file asynchronously using Gemini API only, this is not supported\n * in Vertex AI.\n *\n * @param file The string path to the file to be uploaded or a Blob object.\n * @param config Optional parameters specified in the `UploadFileConfig`\n * interface. @see {@link UploadFileConfig}\n * @return A promise that resolves to a `File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n */\n async uploadFile(\n file: string | Blob,\n config?: UploadFileConfig,\n ): Promise {\n const fileToUpload: File = {};\n if (config != null) {\n fileToUpload.mimeType = config.mimeType;\n fileToUpload.name = config.name;\n fileToUpload.displayName = config.displayName;\n }\n\n if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) {\n fileToUpload.name = `files/${fileToUpload.name}`;\n }\n\n const uploader = this.clientOptions.uploader;\n const fileStat = await uploader.stat(file);\n fileToUpload.sizeBytes = String(fileStat.size);\n const mimeType = config?.mimeType ?? fileStat.type;\n if (mimeType === undefined || mimeType === '') {\n throw new Error(\n 'Can not determine mimeType. Please provide mimeType in the config.',\n );\n }\n fileToUpload.mimeType = mimeType;\n\n const uploadUrl = await this.fetchUploadUrl(fileToUpload, config);\n return uploader.upload(file, uploadUrl, this);\n }\n\n /**\n * Downloads a file asynchronously to the specified path.\n *\n * @params params - The parameters for the download request, see {@link\n * DownloadFileParameters}\n */\n async downloadFile(params: DownloadFileParameters): Promise {\n const downloader = this.clientOptions.downloader;\n await downloader.download(params, this);\n }\n\n private async fetchUploadUrl(\n file: File,\n config?: UploadFileConfig,\n ): Promise {\n let httpOptions: HttpOptions = {};\n if (config?.httpOptions) {\n httpOptions = config.httpOptions;\n } else {\n httpOptions = {\n apiVersion: '', // api-version is set in the path.\n headers: {\n 'Content-Type': 'application/json',\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`,\n 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`,\n },\n };\n }\n\n const body: Record = {\n 'file': file,\n };\n const httpResponse = await this.request({\n path: common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n ),\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions,\n });\n\n if (!httpResponse || !httpResponse?.headers) {\n throw new Error(\n 'Server did not return an HttpResponse or the returned HttpResponse did not have headers.',\n );\n }\n\n const uploadUrl: string | undefined =\n httpResponse?.headers?.['x-goog-upload-url'];\n if (uploadUrl === undefined) {\n throw new Error(\n 'Failed to get upload url. Server did not return the x-google-upload-url in the headers',\n );\n }\n return uploadUrl;\n }\n}\n\nasync function throwErrorIfNotOK(response: Response | undefined) {\n if (response === undefined) {\n throw new Error('response is undefined');\n }\n if (!response.ok) {\n const status: number = response.status;\n let errorBody: Record;\n if (response.headers.get('content-type')?.includes('application/json')) {\n errorBody = await response.json();\n } else {\n errorBody = {\n error: {\n message: await response.text(),\n code: response.status,\n status: response.statusText,\n },\n };\n }\n const errorMessage = JSON.stringify(errorBody);\n if (status >= 400 && status < 600) {\n const apiError = new ApiError({\n message: errorMessage,\n status: status,\n });\n throw apiError;\n }\n throw new Error(errorMessage);\n }\n}\n\n/**\n * Recursively updates the `requestInit.body` with values from an `extraBody` object.\n *\n * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed.\n * The `extraBody` is then deeply merged into this parsed object.\n * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged,\n * as merging structured data into an opaque Blob is not supported.\n *\n * The function does not enforce that updated values from `extraBody` have the\n * same type as existing values in `requestInit.body`. Type mismatches during\n * the merge will result in a warning, but the value from `extraBody` will overwrite\n * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure.\n *\n * @param requestInit The RequestInit object whose body will be updated.\n * @param extraBody The object containing updates to be merged into `requestInit.body`.\n */\nexport function includeExtraBodyToRequestInit(\n requestInit: RequestInit,\n extraBody: Record,\n) {\n if (!extraBody || Object.keys(extraBody).length === 0) {\n return;\n }\n\n if (requestInit.body instanceof Blob) {\n console.warn(\n 'includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.',\n );\n return;\n }\n\n let currentBodyObject: Record = {};\n\n // If adding new type to HttpRequest.body, please check the code below to\n // see if we need to update the logic.\n if (typeof requestInit.body === 'string' && requestInit.body.length > 0) {\n try {\n const parsedBody = JSON.parse(requestInit.body);\n if (\n typeof parsedBody === 'object' &&\n parsedBody !== null &&\n !Array.isArray(parsedBody)\n ) {\n currentBodyObject = parsedBody as Record;\n } else {\n console.warn(\n 'includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.',\n );\n return;\n }\n /* eslint-disable-next-line @typescript-eslint/no-unused-vars */\n } catch (e) {\n console.warn(\n 'includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.',\n );\n return;\n }\n }\n\n function deepMerge(\n target: Record,\n source: Record,\n ): Record {\n const output = {...target};\n for (const key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n const sourceValue = source[key];\n const targetValue = output[key];\n if (\n sourceValue &&\n typeof sourceValue === 'object' &&\n !Array.isArray(sourceValue) &&\n targetValue &&\n typeof targetValue === 'object' &&\n !Array.isArray(targetValue)\n ) {\n output[key] = deepMerge(\n targetValue as Record,\n sourceValue as Record,\n );\n } else {\n if (\n targetValue &&\n sourceValue &&\n typeof targetValue !== typeof sourceValue\n ) {\n console.warn(\n `includeExtraBodyToRequestInit:deepMerge: Type mismatch for key \"${key}\". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`,\n );\n }\n output[key] = sourceValue;\n }\n }\n }\n return output;\n }\n\n const mergedBody = deepMerge(currentBodyObject, extraBody);\n requestInit.body = JSON.stringify(mergedBody);\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function crossError(): Error {\n // TODO(b/399934880): this message needs a link to a help page explaining how to enable conditional exports\n return new Error(`This feature requires the web or Node specific @google/genai implementation, you can fix this by either:\n\n*Enabling conditional exports for your project [recommended]*\n\n*Using a platform specific import* - Make sure your code imports either '@google/genai/web' or '@google/genai/node' instead of '@google/genai'.\n`);\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from '../_api_client.js';\nimport {Downloader} from '../_downloader.js';\nimport {DownloadFileParameters} from '../types.js';\n\nimport {crossError} from './_cross_error.js';\n\nexport class CrossDownloader implements Downloader {\n async download(\n _params: DownloadFileParameters,\n _apiClient: ApiClient,\n ): Promise {\n throw crossError();\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {ApiClient} from '../_api_client.js';\nimport {FileStat, Uploader} from '../_uploader.js';\nimport {File, HttpResponse} from '../types.js';\n\nimport {crossError} from './_cross_error.js';\n\nexport const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes\nexport const MAX_RETRY_COUNT = 3;\nexport const INITIAL_RETRY_DELAY_MS = 1000;\nexport const DELAY_MULTIPLIER = 2;\nexport const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status';\n\nexport class CrossUploader implements Uploader {\n async upload(\n file: string | Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return uploadBlob(file, uploadUrl, apiClient);\n }\n }\n\n async stat(file: string | Blob): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return getBlobStat(file);\n }\n }\n}\n\nexport async function uploadBlob(\n file: Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n): Promise {\n let fileSize = 0;\n let offset = 0;\n let response: HttpResponse = new HttpResponse(new Response());\n let uploadCommand = 'upload';\n fileSize = file.size;\n while (offset < fileSize) {\n const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);\n const chunk = file.slice(offset, offset + chunkSize);\n if (offset + chunkSize >= fileSize) {\n uploadCommand += ', finalize';\n }\n let retryCount = 0;\n let currentDelayMs = INITIAL_RETRY_DELAY_MS;\n while (retryCount < MAX_RETRY_COUNT) {\n response = await apiClient.request({\n path: '',\n body: chunk,\n httpMethod: 'POST',\n httpOptions: {\n apiVersion: '',\n baseUrl: uploadUrl,\n headers: {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': String(offset),\n 'Content-Length': String(chunkSize),\n },\n },\n });\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) {\n break;\n }\n retryCount++;\n await sleep(currentDelayMs);\n currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;\n }\n offset += chunkSize;\n // The `x-goog-upload-status` header field can be `active`, `final` and\n //`cancelled` in resposne.\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'active') {\n break;\n }\n // TODO(b/401391430) Investigate why the upload status is not finalized\n // even though all content has been uploaded.\n if (fileSize <= offset) {\n throw new Error(\n 'All content has been uploaded, but the upload status is not finalized.',\n );\n }\n }\n const responseJson = (await response?.json()) as Record<\n string,\n File | unknown\n >;\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'final') {\n throw new Error('Failed to upload file: Upload status is not finalized.');\n }\n return responseJson['file'] as File;\n}\n\nexport async function getBlobStat(file: Blob): Promise {\n const fileStat: FileStat = {size: file.size, type: file.type};\n return fileStat;\n}\n\nexport function sleep(ms: number): Promise {\n return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n WebSocketCallbacks,\n WebSocketFactory,\n WebSocket as Ws,\n} from '../_websocket.js';\nimport {crossError} from './_cross_error.js';\n\nexport class CrossWebSocketFactory implements WebSocketFactory {\n create(\n _url: string,\n _headers: Record,\n _callbacks: WebSocketCallbacks,\n ): Ws {\n throw crossError();\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function listFilesConfigToMldev(\n fromObject: types.ListFilesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listFilesParametersToMldev(\n fromObject: types.ListFilesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listFilesConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function fileStatusToMldev(\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileToMldev(fromObject: types.File): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fileStatusToMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function createFileParametersToMldev(\n fromObject: types.CreateFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromFile = common.getValueByPath(fromObject, ['file']);\n if (fromFile != null) {\n common.setValueByPath(toObject, ['file'], fileToMldev(fromFile));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getFileParametersToMldev(\n fromObject: types.GetFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'file'], t.tFileName(fromName));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteFileParametersToMldev(\n fromObject: types.DeleteFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'file'], t.tFileName(fromName));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fileStatusFromMldev(\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileFromMldev(fromObject: types.File): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fileStatusFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function listFilesResponseFromMldev(\n fromObject: types.ListFilesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromFiles = common.getValueByPath(fromObject, ['files']);\n if (fromFiles != null) {\n let transformedList = fromFiles;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return fileFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['files'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createFileResponseFromMldev(\n fromObject: types.CreateFileResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n\nexport function deleteFileResponseFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_files_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Files extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists all current project files from the service.\n *\n * @param params - The parameters for the list request\n * @return The paginated results of the list of files\n *\n * @example\n * The following code prints the names of all files from the service, the\n * size of each page is 10.\n *\n * ```ts\n * const listResponse = await ai.files.list({config: {'pageSize': 10}});\n * for await (const file of listResponse) {\n * console.log(file.name);\n * }\n * ```\n */\n list = async (\n params: types.ListFilesParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_FILES,\n (x: types.ListFilesParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Uploads a file asynchronously to the Gemini API.\n * This method is not available in Vertex AI.\n * Supported upload sources:\n * - Node.js: File path (string) or Blob object.\n * - Browser: Blob object (e.g., File).\n *\n * @remarks\n * The `mimeType` can be specified in the `config` parameter. If omitted:\n * - For file path (string) inputs, the `mimeType` will be inferred from the\n * file extension.\n * - For Blob object inputs, the `mimeType` will be set to the Blob's `type`\n * property.\n * Somex eamples for file extension to mimeType mapping:\n * .txt -> text/plain\n * .json -> application/json\n * .jpg -> image/jpeg\n * .png -> image/png\n * .mp3 -> audio/mpeg\n * .mp4 -> video/mp4\n *\n * This section can contain multiple paragraphs and code examples.\n *\n * @param params - Optional parameters specified in the\n * `types.UploadFileParameters` interface.\n * @see {@link types.UploadFileParameters#config} for the optional\n * config in the parameters.\n * @return A promise that resolves to a `types.File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n * the `mimeType` can be provided in the `params.config` parameter.\n * @throws An error occurs if a suitable upload location cannot be established.\n *\n * @example\n * The following code uploads a file to Gemini API.\n *\n * ```ts\n * const file = await ai.files.upload({file: 'file.txt', config: {\n * mimeType: 'text/plain',\n * }});\n * console.log(file.name);\n * ```\n */\n async upload(params: types.UploadFileParameters): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'Vertex AI does not support uploading files. You can share files through a GCS bucket.',\n );\n }\n\n return this.apiClient\n .uploadFile(params.file, params.config)\n .then((response) => {\n const file = converters.fileFromMldev(response);\n return file as types.File;\n });\n }\n\n /**\n * Downloads a remotely stored file asynchronously to a location specified in\n * the `params` object. This method only works on Node environment, to\n * download files in the browser, use a browser compliant method like an \n * tag.\n *\n * @param params - The parameters for the download request.\n *\n * @example\n * The following code downloads an example file named \"files/mehozpxf877d\" as\n * \"file.txt\".\n *\n * ```ts\n * await ai.files.download({file: file.name, downloadPath: 'file.txt'});\n * ```\n */\n\n async download(params: types.DownloadFileParameters): Promise {\n await this.apiClient.downloadFile(params);\n }\n\n private async listInternal(\n params: types.ListFilesParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.listFilesParametersToMldev(params);\n path = common.formatMap('files', body['_url'] as Record);\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListFilesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listFilesResponseFromMldev(apiResponse);\n const typedResp = new types.ListFilesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async createInternal(\n params: types.CreateFileParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createFileParametersToMldev(params);\n path = common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.createFileResponseFromMldev(apiResponse);\n const typedResp = new types.CreateFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Retrieves the file information from the service.\n *\n * @param params - The parameters for the get request\n * @return The Promise that resolves to the types.File object requested.\n *\n * @example\n * ```ts\n * const config: GetFileParameters = {\n * name: fileName,\n * };\n * file = await ai.files.get(config);\n * console.log(file.name);\n * ```\n */\n async get(params: types.GetFileParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.getFileParametersToMldev(params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.fileFromMldev(apiResponse);\n\n return resp as types.File;\n });\n }\n }\n\n /**\n * Deletes a remotely stored file.\n *\n * @param params - The parameters for the delete request.\n * @return The DeleteFileResponse, the response for the delete method.\n *\n * @example\n * The following code deletes an example file named \"files/mehozpxf877d\".\n *\n * ```ts\n * await ai.files.delete({name: file.name});\n * ```\n */\n async delete(\n params: types.DeleteFileParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.deleteFileParametersToMldev(params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteFileResponseFromMldev();\n const typedResp = new types.DeleteFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToMldev(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n if (common.getValueByPath(fromObject, ['transparent']) !== undefined) {\n throw new Error('transparent parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToMldev(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToMldev(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToMldev(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToMldev(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToMldev(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToMldev(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToMldev(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToMldev(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToMldev(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function activityStartToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function activityEndToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function liveSendRealtimeInputParametersToMldev(\n fromObject: types.LiveSendRealtimeInputParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMedia = common.getValueByPath(fromObject, ['media']);\n if (fromMedia != null) {\n common.setValueByPath(toObject, ['mediaChunks'], t.tBlobs(fromMedia));\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], t.tAudioBlob(fromAudio));\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], t.tImageBlob(fromVideo));\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToMldev());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToMldev());\n }\n\n return toObject;\n}\n\nexport function liveClientSetupToMldev(\n fromObject: types.LiveClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig != null) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction != null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(toObject, ['tools'], transformedList);\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (fromRealtimeInputConfig != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (fromSessionResumption != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (fromContextWindowCompression != null) {\n common.setValueByPath(\n toObject,\n ['contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (fromInputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (fromOutputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (fromProactivity != null) {\n common.setValueByPath(\n toObject,\n ['proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveClientContentToMldev(\n fromObject: types.LiveClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromTurns = common.getValueByPath(fromObject, ['turns']);\n if (fromTurns != null) {\n let transformedList = fromTurns;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['turns'], transformedList);\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n return toObject;\n}\n\nexport function liveClientRealtimeInputToMldev(\n fromObject: types.LiveClientRealtimeInput,\n): Record {\n const toObject: Record = {};\n\n const fromMediaChunks = common.getValueByPath(fromObject, ['mediaChunks']);\n if (fromMediaChunks != null) {\n common.setValueByPath(toObject, ['mediaChunks'], fromMediaChunks);\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], fromAudio);\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], fromVideo);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToMldev());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToMldev());\n }\n\n return toObject;\n}\n\nexport function functionResponseToMldev(\n fromObject: types.FunctionResponse,\n): Record {\n const toObject: Record = {};\n\n const fromWillContinue = common.getValueByPath(fromObject, ['willContinue']);\n if (fromWillContinue != null) {\n common.setValueByPath(toObject, ['willContinue'], fromWillContinue);\n }\n\n const fromScheduling = common.getValueByPath(fromObject, ['scheduling']);\n if (fromScheduling != null) {\n common.setValueByPath(toObject, ['scheduling'], fromScheduling);\n }\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n return toObject;\n}\n\nexport function liveClientToolResponseToMldev(\n fromObject: types.LiveClientToolResponse,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionResponses = common.getValueByPath(fromObject, [\n 'functionResponses',\n ]);\n if (fromFunctionResponses != null) {\n let transformedList = fromFunctionResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionResponseToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveClientMessageToMldev(\n fromObject: types.LiveClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveClientSetupToMldev(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveClientContentToMldev(fromClientContent),\n );\n }\n\n const fromRealtimeInput = common.getValueByPath(fromObject, [\n 'realtimeInput',\n ]);\n if (fromRealtimeInput != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInput'],\n liveClientRealtimeInputToMldev(fromRealtimeInput),\n );\n }\n\n const fromToolResponse = common.getValueByPath(fromObject, ['toolResponse']);\n if (fromToolResponse != null) {\n common.setValueByPath(\n toObject,\n ['toolResponse'],\n liveClientToolResponseToMldev(fromToolResponse),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicConnectParametersToMldev(\n fromObject: types.LiveMusicConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['setup', 'model'], fromModel);\n }\n\n const fromCallbacks = common.getValueByPath(fromObject, ['callbacks']);\n if (fromCallbacks != null) {\n common.setValueByPath(toObject, ['callbacks'], fromCallbacks);\n }\n\n return toObject;\n}\n\nexport function weightedPromptToMldev(\n fromObject: types.WeightedPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromWeight = common.getValueByPath(fromObject, ['weight']);\n if (fromWeight != null) {\n common.setValueByPath(toObject, ['weight'], fromWeight);\n }\n\n return toObject;\n}\n\nexport function liveMusicSetWeightedPromptsParametersToMldev(\n fromObject: types.LiveMusicSetWeightedPromptsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicGenerationConfigToMldev(\n fromObject: types.LiveMusicGenerationConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromGuidance = common.getValueByPath(fromObject, ['guidance']);\n if (fromGuidance != null) {\n common.setValueByPath(toObject, ['guidance'], fromGuidance);\n }\n\n const fromBpm = common.getValueByPath(fromObject, ['bpm']);\n if (fromBpm != null) {\n common.setValueByPath(toObject, ['bpm'], fromBpm);\n }\n\n const fromDensity = common.getValueByPath(fromObject, ['density']);\n if (fromDensity != null) {\n common.setValueByPath(toObject, ['density'], fromDensity);\n }\n\n const fromBrightness = common.getValueByPath(fromObject, ['brightness']);\n if (fromBrightness != null) {\n common.setValueByPath(toObject, ['brightness'], fromBrightness);\n }\n\n const fromScale = common.getValueByPath(fromObject, ['scale']);\n if (fromScale != null) {\n common.setValueByPath(toObject, ['scale'], fromScale);\n }\n\n const fromMuteBass = common.getValueByPath(fromObject, ['muteBass']);\n if (fromMuteBass != null) {\n common.setValueByPath(toObject, ['muteBass'], fromMuteBass);\n }\n\n const fromMuteDrums = common.getValueByPath(fromObject, ['muteDrums']);\n if (fromMuteDrums != null) {\n common.setValueByPath(toObject, ['muteDrums'], fromMuteDrums);\n }\n\n const fromOnlyBassAndDrums = common.getValueByPath(fromObject, [\n 'onlyBassAndDrums',\n ]);\n if (fromOnlyBassAndDrums != null) {\n common.setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums);\n }\n\n const fromMusicGenerationMode = common.getValueByPath(fromObject, [\n 'musicGenerationMode',\n ]);\n if (fromMusicGenerationMode != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationMode'],\n fromMusicGenerationMode,\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicSetConfigParametersToMldev(\n fromObject: types.LiveMusicSetConfigParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigToMldev(fromMusicGenerationConfig),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicClientSetupToMldev(\n fromObject: types.LiveMusicClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientContentToMldev(\n fromObject: types.LiveMusicClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientMessageToMldev(\n fromObject: types.LiveMusicClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveMusicClientSetupToMldev(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveMusicClientContentToMldev(fromClientContent),\n );\n }\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigToMldev(fromMusicGenerationConfig),\n );\n }\n\n const fromPlaybackControl = common.getValueByPath(fromObject, [\n 'playbackControl',\n ]);\n if (fromPlaybackControl != null) {\n common.setValueByPath(toObject, ['playbackControl'], fromPlaybackControl);\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(fromVoiceConfig),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined\n ) {\n throw new Error(\n 'multiSpeakerVoiceConfig parameter is not supported in Vertex AI.',\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(\n fromObject: types.EnterpriseWebSearch,\n): Record {\n const toObject: Record = {};\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToVertex(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(fromEnterpriseWebSearch),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToVertex(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToVertex(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n const fromTransparent = common.getValueByPath(fromObject, ['transparent']);\n if (fromTransparent != null) {\n common.setValueByPath(toObject, ['transparent'], fromTransparent);\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToVertex(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToVertex(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToVertex(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToVertex(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToVertex(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToVertex(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToVertex(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToVertex(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToVertex(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToVertex(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToVertex(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToVertex(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToVertex(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function activityStartToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function activityEndToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function liveSendRealtimeInputParametersToVertex(\n fromObject: types.LiveSendRealtimeInputParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMedia = common.getValueByPath(fromObject, ['media']);\n if (fromMedia != null) {\n common.setValueByPath(toObject, ['mediaChunks'], t.tBlobs(fromMedia));\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], t.tAudioBlob(fromAudio));\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], t.tImageBlob(fromVideo));\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToVertex());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToVertex());\n }\n\n return toObject;\n}\n\nexport function liveClientSetupToVertex(\n fromObject: types.LiveClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig != null) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction != null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(toObject, ['tools'], transformedList);\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (fromRealtimeInputConfig != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInputConfig'],\n realtimeInputConfigToVertex(fromRealtimeInputConfig),\n );\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (fromSessionResumption != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumption'],\n sessionResumptionConfigToVertex(fromSessionResumption),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (fromContextWindowCompression != null) {\n common.setValueByPath(\n toObject,\n ['contextWindowCompression'],\n contextWindowCompressionConfigToVertex(fromContextWindowCompression),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (fromInputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (fromOutputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (fromProactivity != null) {\n common.setValueByPath(\n toObject,\n ['proactivity'],\n proactivityConfigToVertex(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveClientContentToVertex(\n fromObject: types.LiveClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromTurns = common.getValueByPath(fromObject, ['turns']);\n if (fromTurns != null) {\n let transformedList = fromTurns;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['turns'], transformedList);\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n return toObject;\n}\n\nexport function liveClientRealtimeInputToVertex(\n fromObject: types.LiveClientRealtimeInput,\n): Record {\n const toObject: Record = {};\n\n const fromMediaChunks = common.getValueByPath(fromObject, ['mediaChunks']);\n if (fromMediaChunks != null) {\n common.setValueByPath(toObject, ['mediaChunks'], fromMediaChunks);\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], fromAudio);\n }\n\n if (common.getValueByPath(fromObject, ['audioStreamEnd']) !== undefined) {\n throw new Error('audioStreamEnd parameter is not supported in Vertex AI.');\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], fromVideo);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToVertex());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToVertex());\n }\n\n return toObject;\n}\n\nexport function functionResponseToVertex(\n fromObject: types.FunctionResponse,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['willContinue']) !== undefined) {\n throw new Error('willContinue parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['scheduling']) !== undefined) {\n throw new Error('scheduling parameter is not supported in Vertex AI.');\n }\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n return toObject;\n}\n\nexport function liveClientToolResponseToVertex(\n fromObject: types.LiveClientToolResponse,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionResponses = common.getValueByPath(fromObject, [\n 'functionResponses',\n ]);\n if (fromFunctionResponses != null) {\n let transformedList = fromFunctionResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionResponseToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveClientMessageToVertex(\n fromObject: types.LiveClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveClientSetupToVertex(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveClientContentToVertex(fromClientContent),\n );\n }\n\n const fromRealtimeInput = common.getValueByPath(fromObject, [\n 'realtimeInput',\n ]);\n if (fromRealtimeInput != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInput'],\n liveClientRealtimeInputToVertex(fromRealtimeInput),\n );\n }\n\n const fromToolResponse = common.getValueByPath(fromObject, ['toolResponse']);\n if (fromToolResponse != null) {\n common.setValueByPath(\n toObject,\n ['toolResponse'],\n liveClientToolResponseToVertex(fromToolResponse),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicConnectParametersToVertex(\n fromObject: types.LiveMusicConnectParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['model']) !== undefined) {\n throw new Error('model parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['callbacks']) !== undefined) {\n throw new Error('callbacks parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveMusicSetWeightedPromptsParametersToVertex(\n fromObject: types.LiveMusicSetWeightedPromptsParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['weightedPrompts']) !== undefined) {\n throw new Error('weightedPrompts parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveMusicSetConfigParametersToVertex(\n fromObject: types.LiveMusicSetConfigParameters,\n): Record {\n const toObject: Record = {};\n\n if (\n common.getValueByPath(fromObject, ['musicGenerationConfig']) !== undefined\n ) {\n throw new Error(\n 'musicGenerationConfig parameter is not supported in Vertex AI.',\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicClientMessageToVertex(\n fromObject: types.LiveMusicClientMessage,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['setup']) !== undefined) {\n throw new Error('setup parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['clientContent']) !== undefined) {\n throw new Error('clientContent parameter is not supported in Vertex AI.');\n }\n\n if (\n common.getValueByPath(fromObject, ['musicGenerationConfig']) !== undefined\n ) {\n throw new Error(\n 'musicGenerationConfig parameter is not supported in Vertex AI.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['playbackControl']) !== undefined) {\n throw new Error('playbackControl parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveServerSetupCompleteFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function transcriptionFromMldev(\n fromObject: types.Transcription,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFinished = common.getValueByPath(fromObject, ['finished']);\n if (fromFinished != null) {\n common.setValueByPath(toObject, ['finished'], fromFinished);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerContentFromMldev(\n fromObject: types.LiveServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn != null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromMldev(fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted != null) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromGenerationComplete = common.getValueByPath(fromObject, [\n 'generationComplete',\n ]);\n if (fromGenerationComplete != null) {\n common.setValueByPath(\n toObject,\n ['generationComplete'],\n fromGenerationComplete,\n );\n }\n\n const fromInputTranscription = common.getValueByPath(fromObject, [\n 'inputTranscription',\n ]);\n if (fromInputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputTranscription'],\n transcriptionFromMldev(fromInputTranscription),\n );\n }\n\n const fromOutputTranscription = common.getValueByPath(fromObject, [\n 'outputTranscription',\n ]);\n if (fromOutputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputTranscription'],\n transcriptionFromMldev(fromOutputTranscription),\n );\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function functionCallFromMldev(\n fromObject: types.FunctionCall,\n): Record {\n const toObject: Record = {};\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs != null) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallFromMldev(\n fromObject: types.LiveServerToolCall,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (fromFunctionCalls != null) {\n let transformedList = fromFunctionCalls;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionCallFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionCalls'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallCancellationFromMldev(\n fromObject: types.LiveServerToolCallCancellation,\n): Record {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds != null) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nexport function modalityTokenCountFromMldev(\n fromObject: types.ModalityTokenCount,\n): Record {\n const toObject: Record = {};\n\n const fromModality = common.getValueByPath(fromObject, ['modality']);\n if (fromModality != null) {\n common.setValueByPath(toObject, ['modality'], fromModality);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function usageMetadataFromMldev(\n fromObject: types.UsageMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromPromptTokenCount = common.getValueByPath(fromObject, [\n 'promptTokenCount',\n ]);\n if (fromPromptTokenCount != null) {\n common.setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n const fromResponseTokenCount = common.getValueByPath(fromObject, [\n 'responseTokenCount',\n ]);\n if (fromResponseTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['responseTokenCount'],\n fromResponseTokenCount,\n );\n }\n\n const fromToolUsePromptTokenCount = common.getValueByPath(fromObject, [\n 'toolUsePromptTokenCount',\n ]);\n if (fromToolUsePromptTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokenCount'],\n fromToolUsePromptTokenCount,\n );\n }\n\n const fromThoughtsTokenCount = common.getValueByPath(fromObject, [\n 'thoughtsTokenCount',\n ]);\n if (fromThoughtsTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['thoughtsTokenCount'],\n fromThoughtsTokenCount,\n );\n }\n\n const fromTotalTokenCount = common.getValueByPath(fromObject, [\n 'totalTokenCount',\n ]);\n if (fromTotalTokenCount != null) {\n common.setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount);\n }\n\n const fromPromptTokensDetails = common.getValueByPath(fromObject, [\n 'promptTokensDetails',\n ]);\n if (fromPromptTokensDetails != null) {\n let transformedList = fromPromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['promptTokensDetails'], transformedList);\n }\n\n const fromCacheTokensDetails = common.getValueByPath(fromObject, [\n 'cacheTokensDetails',\n ]);\n if (fromCacheTokensDetails != null) {\n let transformedList = fromCacheTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['cacheTokensDetails'], transformedList);\n }\n\n const fromResponseTokensDetails = common.getValueByPath(fromObject, [\n 'responseTokensDetails',\n ]);\n if (fromResponseTokensDetails != null) {\n let transformedList = fromResponseTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['responseTokensDetails'], transformedList);\n }\n\n const fromToolUsePromptTokensDetails = common.getValueByPath(fromObject, [\n 'toolUsePromptTokensDetails',\n ]);\n if (fromToolUsePromptTokensDetails != null) {\n let transformedList = fromToolUsePromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokensDetails'],\n transformedList,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerGoAwayFromMldev(\n fromObject: types.LiveServerGoAway,\n): Record {\n const toObject: Record = {};\n\n const fromTimeLeft = common.getValueByPath(fromObject, ['timeLeft']);\n if (fromTimeLeft != null) {\n common.setValueByPath(toObject, ['timeLeft'], fromTimeLeft);\n }\n\n return toObject;\n}\n\nexport function liveServerSessionResumptionUpdateFromMldev(\n fromObject: types.LiveServerSessionResumptionUpdate,\n): Record {\n const toObject: Record = {};\n\n const fromNewHandle = common.getValueByPath(fromObject, ['newHandle']);\n if (fromNewHandle != null) {\n common.setValueByPath(toObject, ['newHandle'], fromNewHandle);\n }\n\n const fromResumable = common.getValueByPath(fromObject, ['resumable']);\n if (fromResumable != null) {\n common.setValueByPath(toObject, ['resumable'], fromResumable);\n }\n\n const fromLastConsumedClientMessageIndex = common.getValueByPath(fromObject, [\n 'lastConsumedClientMessageIndex',\n ]);\n if (fromLastConsumedClientMessageIndex != null) {\n common.setValueByPath(\n toObject,\n ['lastConsumedClientMessageIndex'],\n fromLastConsumedClientMessageIndex,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromMldev(\n fromObject: types.LiveServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveServerSetupCompleteFromMldev(),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromMldev(fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall != null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromMldev(fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (fromToolCallCancellation != null) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromMldev(fromToolCallCancellation),\n );\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(\n toObject,\n ['usageMetadata'],\n usageMetadataFromMldev(fromUsageMetadata),\n );\n }\n\n const fromGoAway = common.getValueByPath(fromObject, ['goAway']);\n if (fromGoAway != null) {\n common.setValueByPath(\n toObject,\n ['goAway'],\n liveServerGoAwayFromMldev(fromGoAway),\n );\n }\n\n const fromSessionResumptionUpdate = common.getValueByPath(fromObject, [\n 'sessionResumptionUpdate',\n ]);\n if (fromSessionResumptionUpdate != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumptionUpdate'],\n liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerSetupCompleteFromMldev(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function weightedPromptFromMldev(\n fromObject: types.WeightedPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromWeight = common.getValueByPath(fromObject, ['weight']);\n if (fromWeight != null) {\n common.setValueByPath(toObject, ['weight'], fromWeight);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientContentFromMldev(\n fromObject: types.LiveMusicClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicGenerationConfigFromMldev(\n fromObject: types.LiveMusicGenerationConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromGuidance = common.getValueByPath(fromObject, ['guidance']);\n if (fromGuidance != null) {\n common.setValueByPath(toObject, ['guidance'], fromGuidance);\n }\n\n const fromBpm = common.getValueByPath(fromObject, ['bpm']);\n if (fromBpm != null) {\n common.setValueByPath(toObject, ['bpm'], fromBpm);\n }\n\n const fromDensity = common.getValueByPath(fromObject, ['density']);\n if (fromDensity != null) {\n common.setValueByPath(toObject, ['density'], fromDensity);\n }\n\n const fromBrightness = common.getValueByPath(fromObject, ['brightness']);\n if (fromBrightness != null) {\n common.setValueByPath(toObject, ['brightness'], fromBrightness);\n }\n\n const fromScale = common.getValueByPath(fromObject, ['scale']);\n if (fromScale != null) {\n common.setValueByPath(toObject, ['scale'], fromScale);\n }\n\n const fromMuteBass = common.getValueByPath(fromObject, ['muteBass']);\n if (fromMuteBass != null) {\n common.setValueByPath(toObject, ['muteBass'], fromMuteBass);\n }\n\n const fromMuteDrums = common.getValueByPath(fromObject, ['muteDrums']);\n if (fromMuteDrums != null) {\n common.setValueByPath(toObject, ['muteDrums'], fromMuteDrums);\n }\n\n const fromOnlyBassAndDrums = common.getValueByPath(fromObject, [\n 'onlyBassAndDrums',\n ]);\n if (fromOnlyBassAndDrums != null) {\n common.setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums);\n }\n\n const fromMusicGenerationMode = common.getValueByPath(fromObject, [\n 'musicGenerationMode',\n ]);\n if (fromMusicGenerationMode != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationMode'],\n fromMusicGenerationMode,\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicSourceMetadataFromMldev(\n fromObject: types.LiveMusicSourceMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveMusicClientContentFromMldev(fromClientContent),\n );\n }\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig),\n );\n }\n\n return toObject;\n}\n\nexport function audioChunkFromMldev(\n fromObject: types.AudioChunk,\n): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSourceMetadata = common.getValueByPath(fromObject, [\n 'sourceMetadata',\n ]);\n if (fromSourceMetadata != null) {\n common.setValueByPath(\n toObject,\n ['sourceMetadata'],\n liveMusicSourceMetadataFromMldev(fromSourceMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerContentFromMldev(\n fromObject: types.LiveMusicServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromAudioChunks = common.getValueByPath(fromObject, ['audioChunks']);\n if (fromAudioChunks != null) {\n let transformedList = fromAudioChunks;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return audioChunkFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['audioChunks'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicFilteredPromptFromMldev(\n fromObject: types.LiveMusicFilteredPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFilteredReason = common.getValueByPath(fromObject, [\n 'filteredReason',\n ]);\n if (fromFilteredReason != null) {\n common.setValueByPath(toObject, ['filteredReason'], fromFilteredReason);\n }\n\n return toObject;\n}\n\nexport function liveMusicServerMessageFromMldev(\n fromObject: types.LiveMusicServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveMusicServerSetupCompleteFromMldev(),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveMusicServerContentFromMldev(fromServerContent),\n );\n }\n\n const fromFilteredPrompt = common.getValueByPath(fromObject, [\n 'filteredPrompt',\n ]);\n if (fromFilteredPrompt != null) {\n common.setValueByPath(\n toObject,\n ['filteredPrompt'],\n liveMusicFilteredPromptFromMldev(fromFilteredPrompt),\n );\n }\n\n return toObject;\n}\n\nexport function liveServerSetupCompleteFromVertex(\n fromObject: types.LiveServerSetupComplete,\n): Record {\n const toObject: Record = {};\n\n const fromSessionId = common.getValueByPath(fromObject, ['sessionId']);\n if (fromSessionId != null) {\n common.setValueByPath(toObject, ['sessionId'], fromSessionId);\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromVertex(\n fromObject: types.Blob,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function transcriptionFromVertex(\n fromObject: types.Transcription,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFinished = common.getValueByPath(fromObject, ['finished']);\n if (fromFinished != null) {\n common.setValueByPath(toObject, ['finished'], fromFinished);\n }\n\n return toObject;\n}\n\nexport function liveServerContentFromVertex(\n fromObject: types.LiveServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn != null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromVertex(fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted != null) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromGenerationComplete = common.getValueByPath(fromObject, [\n 'generationComplete',\n ]);\n if (fromGenerationComplete != null) {\n common.setValueByPath(\n toObject,\n ['generationComplete'],\n fromGenerationComplete,\n );\n }\n\n const fromInputTranscription = common.getValueByPath(fromObject, [\n 'inputTranscription',\n ]);\n if (fromInputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputTranscription'],\n transcriptionFromVertex(fromInputTranscription),\n );\n }\n\n const fromOutputTranscription = common.getValueByPath(fromObject, [\n 'outputTranscription',\n ]);\n if (fromOutputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputTranscription'],\n transcriptionFromVertex(fromOutputTranscription),\n );\n }\n\n return toObject;\n}\n\nexport function functionCallFromVertex(\n fromObject: types.FunctionCall,\n): Record {\n const toObject: Record = {};\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs != null) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallFromVertex(\n fromObject: types.LiveServerToolCall,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (fromFunctionCalls != null) {\n let transformedList = fromFunctionCalls;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionCallFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionCalls'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallCancellationFromVertex(\n fromObject: types.LiveServerToolCallCancellation,\n): Record {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds != null) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nexport function modalityTokenCountFromVertex(\n fromObject: types.ModalityTokenCount,\n): Record {\n const toObject: Record = {};\n\n const fromModality = common.getValueByPath(fromObject, ['modality']);\n if (fromModality != null) {\n common.setValueByPath(toObject, ['modality'], fromModality);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function usageMetadataFromVertex(\n fromObject: types.UsageMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromPromptTokenCount = common.getValueByPath(fromObject, [\n 'promptTokenCount',\n ]);\n if (fromPromptTokenCount != null) {\n common.setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n const fromResponseTokenCount = common.getValueByPath(fromObject, [\n 'candidatesTokenCount',\n ]);\n if (fromResponseTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['responseTokenCount'],\n fromResponseTokenCount,\n );\n }\n\n const fromToolUsePromptTokenCount = common.getValueByPath(fromObject, [\n 'toolUsePromptTokenCount',\n ]);\n if (fromToolUsePromptTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokenCount'],\n fromToolUsePromptTokenCount,\n );\n }\n\n const fromThoughtsTokenCount = common.getValueByPath(fromObject, [\n 'thoughtsTokenCount',\n ]);\n if (fromThoughtsTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['thoughtsTokenCount'],\n fromThoughtsTokenCount,\n );\n }\n\n const fromTotalTokenCount = common.getValueByPath(fromObject, [\n 'totalTokenCount',\n ]);\n if (fromTotalTokenCount != null) {\n common.setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount);\n }\n\n const fromPromptTokensDetails = common.getValueByPath(fromObject, [\n 'promptTokensDetails',\n ]);\n if (fromPromptTokensDetails != null) {\n let transformedList = fromPromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['promptTokensDetails'], transformedList);\n }\n\n const fromCacheTokensDetails = common.getValueByPath(fromObject, [\n 'cacheTokensDetails',\n ]);\n if (fromCacheTokensDetails != null) {\n let transformedList = fromCacheTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['cacheTokensDetails'], transformedList);\n }\n\n const fromResponseTokensDetails = common.getValueByPath(fromObject, [\n 'candidatesTokensDetails',\n ]);\n if (fromResponseTokensDetails != null) {\n let transformedList = fromResponseTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['responseTokensDetails'], transformedList);\n }\n\n const fromToolUsePromptTokensDetails = common.getValueByPath(fromObject, [\n 'toolUsePromptTokensDetails',\n ]);\n if (fromToolUsePromptTokensDetails != null) {\n let transformedList = fromToolUsePromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokensDetails'],\n transformedList,\n );\n }\n\n const fromTrafficType = common.getValueByPath(fromObject, ['trafficType']);\n if (fromTrafficType != null) {\n common.setValueByPath(toObject, ['trafficType'], fromTrafficType);\n }\n\n return toObject;\n}\n\nexport function liveServerGoAwayFromVertex(\n fromObject: types.LiveServerGoAway,\n): Record {\n const toObject: Record = {};\n\n const fromTimeLeft = common.getValueByPath(fromObject, ['timeLeft']);\n if (fromTimeLeft != null) {\n common.setValueByPath(toObject, ['timeLeft'], fromTimeLeft);\n }\n\n return toObject;\n}\n\nexport function liveServerSessionResumptionUpdateFromVertex(\n fromObject: types.LiveServerSessionResumptionUpdate,\n): Record {\n const toObject: Record = {};\n\n const fromNewHandle = common.getValueByPath(fromObject, ['newHandle']);\n if (fromNewHandle != null) {\n common.setValueByPath(toObject, ['newHandle'], fromNewHandle);\n }\n\n const fromResumable = common.getValueByPath(fromObject, ['resumable']);\n if (fromResumable != null) {\n common.setValueByPath(toObject, ['resumable'], fromResumable);\n }\n\n const fromLastConsumedClientMessageIndex = common.getValueByPath(fromObject, [\n 'lastConsumedClientMessageIndex',\n ]);\n if (fromLastConsumedClientMessageIndex != null) {\n common.setValueByPath(\n toObject,\n ['lastConsumedClientMessageIndex'],\n fromLastConsumedClientMessageIndex,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromVertex(\n fromObject: types.LiveServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveServerSetupCompleteFromVertex(fromSetupComplete),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromVertex(fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall != null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromVertex(fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (fromToolCallCancellation != null) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromVertex(fromToolCallCancellation),\n );\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(\n toObject,\n ['usageMetadata'],\n usageMetadataFromVertex(fromUsageMetadata),\n );\n }\n\n const fromGoAway = common.getValueByPath(fromObject, ['goAway']);\n if (fromGoAway != null) {\n common.setValueByPath(\n toObject,\n ['goAway'],\n liveServerGoAwayFromVertex(fromGoAway),\n );\n }\n\n const fromSessionResumptionUpdate = common.getValueByPath(fromObject, [\n 'sessionResumptionUpdate',\n ]);\n if (fromSessionResumptionUpdate != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumptionUpdate'],\n liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerMessageFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as _internal_types from '../_internal_types.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined\n ) {\n throw new Error(\n 'modelSelectionConfig parameter is not supported in Gemini API.',\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToMldev(\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'taskType'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['requests[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['mimeType']) !== undefined) {\n throw new Error('mimeType parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['autoTruncate']) !== undefined) {\n throw new Error('autoTruncate parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n const fromModelForEmbedContent = common.getValueByPath(fromObject, ['model']);\n if (fromModelForEmbedContent !== undefined) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'model'],\n t.tModel(apiClient, fromModelForEmbedContent),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToMldev(\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['negativePrompt']) !== undefined) {\n throw new Error('negativePrompt parameter is not supported in Gemini API.');\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['addWatermark']) !== undefined) {\n throw new Error('addWatermark parameter is not supported in Gemini API.');\n }\n\n const fromImageSize = common.getValueByPath(fromObject, ['imageSize']);\n if (parentObject !== undefined && fromImageSize != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleImageSize'],\n fromImageSize,\n );\n }\n\n if (common.getValueByPath(fromObject, ['enhancePrompt']) !== undefined) {\n throw new Error('enhancePrompt parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listModelsConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ListModelsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n const fromQueryBase = common.getValueByPath(fromObject, ['queryBase']);\n if (parentObject !== undefined && fromQueryBase != null) {\n common.setValueByPath(\n parentObject,\n ['_url', 'models_url'],\n t.tModelsUrl(apiClient, fromQueryBase),\n );\n }\n\n return toObject;\n}\n\nexport function listModelsParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.ListModelsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listModelsConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function updateModelConfigToMldev(\n fromObject: types.UpdateModelConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (parentObject !== undefined && fromDefaultCheckpointId != null) {\n common.setValueByPath(\n parentObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n return toObject;\n}\n\nexport function updateModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateModelConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToMldev(\n fromObject: types.CountTokensConfig,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['systemInstruction']) !== undefined) {\n throw new Error(\n 'systemInstruction parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['tools']) !== undefined) {\n throw new Error('tools parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['generationConfig']) !== undefined) {\n throw new Error(\n 'generationConfig parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToMldev(fromConfig),\n );\n }\n\n return toObject;\n}\n\nexport function imageToMldev(fromObject: types.Image): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosConfigToMldev(\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['fps']) !== undefined) {\n throw new Error('fps parameter is not supported in Gemini API.');\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n if (common.getValueByPath(fromObject, ['resolution']) !== undefined) {\n throw new Error('resolution parameter is not supported in Gemini API.');\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n if (common.getValueByPath(fromObject, ['pubsubTopic']) !== undefined) {\n throw new Error('pubsubTopic parameter is not supported in Gemini API.');\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n if (common.getValueByPath(fromObject, ['generateAudio']) !== undefined) {\n throw new Error('generateAudio parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['lastFrame']) !== undefined) {\n throw new Error('lastFrame parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['referenceImages']) !== undefined) {\n throw new Error(\n 'referenceImages parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['compressionQuality']) !== undefined) {\n throw new Error(\n 'compressionQuality parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToMldev(fromImage),\n );\n }\n\n if (common.getValueByPath(fromObject, ['video']) !== undefined) {\n throw new Error('video parameter is not supported in Gemini API.');\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToVertex(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function modelSelectionConfigToVertex(\n fromObject: types.ModelSelectionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFeatureSelectionPreference = common.getValueByPath(fromObject, [\n 'featureSelectionPreference',\n ]);\n if (fromFeatureSelectionPreference != null) {\n common.setValueByPath(\n toObject,\n ['featureSelectionPreference'],\n fromFeatureSelectionPreference,\n );\n }\n\n return toObject;\n}\n\nexport function safetySettingToVertex(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n const fromMethod = common.getValueByPath(fromObject, ['method']);\n if (fromMethod != null) {\n common.setValueByPath(toObject, ['method'], fromMethod);\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(\n fromObject: types.EnterpriseWebSearch,\n): Record {\n const toObject: Record = {};\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToVertex(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(fromEnterpriseWebSearch),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToVertex(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToVertex(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToVertex(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToVertex(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(fromVoiceConfig),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined\n ) {\n throw new Error(\n 'multiSpeakerVoiceConfig parameter is not supported in Vertex AI.',\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToVertex(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToVertex(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n const fromRoutingConfig = common.getValueByPath(fromObject, [\n 'routingConfig',\n ]);\n if (fromRoutingConfig != null) {\n common.setValueByPath(toObject, ['routingConfig'], fromRoutingConfig);\n }\n\n const fromModelSelectionConfig = common.getValueByPath(fromObject, [\n 'modelSelectionConfig',\n ]);\n if (fromModelSelectionConfig != null) {\n common.setValueByPath(\n toObject,\n ['modelConfig'],\n modelSelectionConfigToVertex(fromModelSelectionConfig),\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(fromToolConfig),\n );\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (parentObject !== undefined && fromLabels != null) {\n common.setValueByPath(parentObject, ['labels'], fromLabels);\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToVertex(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromAudioTimestamp = common.getValueByPath(fromObject, [\n 'audioTimestamp',\n ]);\n if (fromAudioTimestamp != null) {\n common.setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp);\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToVertex(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToVertex(\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'task_type'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['instances[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (parentObject !== undefined && fromMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'mimeType'],\n fromMimeType,\n );\n }\n\n const fromAutoTruncate = common.getValueByPath(fromObject, ['autoTruncate']);\n if (parentObject !== undefined && fromAutoTruncate != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'autoTruncate'],\n fromAutoTruncate,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['instances[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToVertex(\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromImageSize = common.getValueByPath(fromObject, ['imageSize']);\n if (parentObject !== undefined && fromImageSize != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleImageSize'],\n fromImageSize,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function imageToVertex(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function maskReferenceConfigToVertex(\n fromObject: types.MaskReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMaskMode = common.getValueByPath(fromObject, ['maskMode']);\n if (fromMaskMode != null) {\n common.setValueByPath(toObject, ['maskMode'], fromMaskMode);\n }\n\n const fromSegmentationClasses = common.getValueByPath(fromObject, [\n 'segmentationClasses',\n ]);\n if (fromSegmentationClasses != null) {\n common.setValueByPath(toObject, ['maskClasses'], fromSegmentationClasses);\n }\n\n const fromMaskDilation = common.getValueByPath(fromObject, ['maskDilation']);\n if (fromMaskDilation != null) {\n common.setValueByPath(toObject, ['dilation'], fromMaskDilation);\n }\n\n return toObject;\n}\n\nexport function controlReferenceConfigToVertex(\n fromObject: types.ControlReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromControlType = common.getValueByPath(fromObject, ['controlType']);\n if (fromControlType != null) {\n common.setValueByPath(toObject, ['controlType'], fromControlType);\n }\n\n const fromEnableControlImageComputation = common.getValueByPath(fromObject, [\n 'enableControlImageComputation',\n ]);\n if (fromEnableControlImageComputation != null) {\n common.setValueByPath(\n toObject,\n ['computeControl'],\n fromEnableControlImageComputation,\n );\n }\n\n return toObject;\n}\n\nexport function styleReferenceConfigToVertex(\n fromObject: types.StyleReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromStyleDescription = common.getValueByPath(fromObject, [\n 'styleDescription',\n ]);\n if (fromStyleDescription != null) {\n common.setValueByPath(toObject, ['styleDescription'], fromStyleDescription);\n }\n\n return toObject;\n}\n\nexport function subjectReferenceConfigToVertex(\n fromObject: types.SubjectReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSubjectType = common.getValueByPath(fromObject, ['subjectType']);\n if (fromSubjectType != null) {\n common.setValueByPath(toObject, ['subjectType'], fromSubjectType);\n }\n\n const fromSubjectDescription = common.getValueByPath(fromObject, [\n 'subjectDescription',\n ]);\n if (fromSubjectDescription != null) {\n common.setValueByPath(\n toObject,\n ['subjectDescription'],\n fromSubjectDescription,\n );\n }\n\n return toObject;\n}\n\nexport function referenceImageAPIInternalToVertex(\n fromObject: _internal_types.ReferenceImageAPIInternal,\n): Record {\n const toObject: Record = {};\n\n const fromReferenceImage = common.getValueByPath(fromObject, [\n 'referenceImage',\n ]);\n if (fromReferenceImage != null) {\n common.setValueByPath(\n toObject,\n ['referenceImage'],\n imageToVertex(fromReferenceImage),\n );\n }\n\n const fromReferenceId = common.getValueByPath(fromObject, ['referenceId']);\n if (fromReferenceId != null) {\n common.setValueByPath(toObject, ['referenceId'], fromReferenceId);\n }\n\n const fromReferenceType = common.getValueByPath(fromObject, [\n 'referenceType',\n ]);\n if (fromReferenceType != null) {\n common.setValueByPath(toObject, ['referenceType'], fromReferenceType);\n }\n\n const fromMaskImageConfig = common.getValueByPath(fromObject, [\n 'maskImageConfig',\n ]);\n if (fromMaskImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['maskImageConfig'],\n maskReferenceConfigToVertex(fromMaskImageConfig),\n );\n }\n\n const fromControlImageConfig = common.getValueByPath(fromObject, [\n 'controlImageConfig',\n ]);\n if (fromControlImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['controlImageConfig'],\n controlReferenceConfigToVertex(fromControlImageConfig),\n );\n }\n\n const fromStyleImageConfig = common.getValueByPath(fromObject, [\n 'styleImageConfig',\n ]);\n if (fromStyleImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['styleImageConfig'],\n styleReferenceConfigToVertex(fromStyleImageConfig),\n );\n }\n\n const fromSubjectImageConfig = common.getValueByPath(fromObject, [\n 'subjectImageConfig',\n ]);\n if (fromSubjectImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['subjectImageConfig'],\n subjectReferenceConfigToVertex(fromSubjectImageConfig),\n );\n }\n\n return toObject;\n}\n\nexport function editImageConfigToVertex(\n fromObject: types.EditImageConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromEditMode = common.getValueByPath(fromObject, ['editMode']);\n if (parentObject !== undefined && fromEditMode != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editMode'],\n fromEditMode,\n );\n }\n\n const fromBaseSteps = common.getValueByPath(fromObject, ['baseSteps']);\n if (parentObject !== undefined && fromBaseSteps != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editConfig', 'baseSteps'],\n fromBaseSteps,\n );\n }\n\n return toObject;\n}\n\nexport function editImageParametersInternalToVertex(\n apiClient: ApiClient,\n fromObject: _internal_types.EditImageParametersInternal,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromReferenceImages = common.getValueByPath(fromObject, [\n 'referenceImages',\n ]);\n if (fromReferenceImages != null) {\n let transformedList = fromReferenceImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return referenceImageAPIInternalToVertex(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['instances[0]', 'referenceImages'],\n transformedList,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n editImageConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function upscaleImageAPIConfigInternalToVertex(\n fromObject: _internal_types.UpscaleImageAPIConfigInternal,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromEnhanceInputImage = common.getValueByPath(fromObject, [\n 'enhanceInputImage',\n ]);\n if (parentObject !== undefined && fromEnhanceInputImage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'upscaleConfig', 'enhanceInputImage'],\n fromEnhanceInputImage,\n );\n }\n\n const fromImagePreservationFactor = common.getValueByPath(fromObject, [\n 'imagePreservationFactor',\n ]);\n if (parentObject !== undefined && fromImagePreservationFactor != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'upscaleConfig', 'imagePreservationFactor'],\n fromImagePreservationFactor,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (parentObject !== undefined && fromMode != null) {\n common.setValueByPath(parentObject, ['parameters', 'mode'], fromMode);\n }\n\n return toObject;\n}\n\nexport function upscaleImageAPIParametersInternalToVertex(\n apiClient: ApiClient,\n fromObject: _internal_types.UpscaleImageAPIParametersInternal,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromUpscaleFactor = common.getValueByPath(fromObject, [\n 'upscaleFactor',\n ]);\n if (fromUpscaleFactor != null) {\n common.setValueByPath(\n toObject,\n ['parameters', 'upscaleConfig', 'upscaleFactor'],\n fromUpscaleFactor,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n upscaleImageAPIConfigInternalToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function productImageToVertex(\n fromObject: types.ProductImage,\n): Record {\n const toObject: Record = {};\n\n const fromProductImage = common.getValueByPath(fromObject, ['productImage']);\n if (fromProductImage != null) {\n common.setValueByPath(toObject, ['image'], imageToVertex(fromProductImage));\n }\n\n return toObject;\n}\n\nexport function recontextImageSourceToVertex(\n fromObject: types.RecontextImageSource,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (parentObject !== undefined && fromPrompt != null) {\n common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromPersonImage = common.getValueByPath(fromObject, ['personImage']);\n if (parentObject !== undefined && fromPersonImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'personImage', 'image'],\n imageToVertex(fromPersonImage),\n );\n }\n\n const fromProductImages = common.getValueByPath(fromObject, [\n 'productImages',\n ]);\n if (parentObject !== undefined && fromProductImages != null) {\n let transformedList = fromProductImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return productImageToVertex(item);\n });\n }\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'productImages'],\n transformedList,\n );\n }\n\n return toObject;\n}\n\nexport function recontextImageConfigToVertex(\n fromObject: types.RecontextImageConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromBaseSteps = common.getValueByPath(fromObject, ['baseSteps']);\n if (parentObject !== undefined && fromBaseSteps != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editConfig', 'baseSteps'],\n fromBaseSteps,\n );\n }\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function recontextImageParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.RecontextImageParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n recontextImageSourceToVertex(fromSource, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n recontextImageConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function scribbleImageToVertex(\n fromObject: types.ScribbleImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageToVertex(fromImage));\n }\n\n return toObject;\n}\n\nexport function segmentImageSourceToVertex(\n fromObject: types.SegmentImageSource,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (parentObject !== undefined && fromPrompt != null) {\n common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (parentObject !== undefined && fromImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromScribbleImage = common.getValueByPath(fromObject, [\n 'scribbleImage',\n ]);\n if (parentObject !== undefined && fromScribbleImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'scribble'],\n scribbleImageToVertex(fromScribbleImage),\n );\n }\n\n return toObject;\n}\n\nexport function segmentImageConfigToVertex(\n fromObject: types.SegmentImageConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (parentObject !== undefined && fromMode != null) {\n common.setValueByPath(parentObject, ['parameters', 'mode'], fromMode);\n }\n\n const fromMaxPredictions = common.getValueByPath(fromObject, [\n 'maxPredictions',\n ]);\n if (parentObject !== undefined && fromMaxPredictions != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'maxPredictions'],\n fromMaxPredictions,\n );\n }\n\n const fromConfidenceThreshold = common.getValueByPath(fromObject, [\n 'confidenceThreshold',\n ]);\n if (parentObject !== undefined && fromConfidenceThreshold != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'confidenceThreshold'],\n fromConfidenceThreshold,\n );\n }\n\n const fromMaskDilation = common.getValueByPath(fromObject, ['maskDilation']);\n if (parentObject !== undefined && fromMaskDilation != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'maskDilation'],\n fromMaskDilation,\n );\n }\n\n const fromBinaryColorThreshold = common.getValueByPath(fromObject, [\n 'binaryColorThreshold',\n ]);\n if (parentObject !== undefined && fromBinaryColorThreshold != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'binaryColorThreshold'],\n fromBinaryColorThreshold,\n );\n }\n\n return toObject;\n}\n\nexport function segmentImageParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.SegmentImageParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n segmentImageSourceToVertex(fromSource, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n segmentImageConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listModelsConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ListModelsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n const fromQueryBase = common.getValueByPath(fromObject, ['queryBase']);\n if (parentObject !== undefined && fromQueryBase != null) {\n common.setValueByPath(\n parentObject,\n ['_url', 'models_url'],\n t.tModelsUrl(apiClient, fromQueryBase),\n );\n }\n\n return toObject;\n}\n\nexport function listModelsParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ListModelsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listModelsConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function updateModelConfigToVertex(\n fromObject: types.UpdateModelConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (parentObject !== undefined && fromDefaultCheckpointId != null) {\n common.setValueByPath(\n parentObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n return toObject;\n}\n\nexport function updateModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateModelConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToVertex(\n fromObject: types.CountTokensConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['generationConfig'],\n fromGenerationConfig,\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function computeTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ComputeTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoToVertex(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, ['videoBytes']);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function videoGenerationReferenceImageToVertex(\n fromObject: types.VideoGenerationReferenceImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageToVertex(fromImage));\n }\n\n const fromReferenceType = common.getValueByPath(fromObject, [\n 'referenceType',\n ]);\n if (fromReferenceType != null) {\n common.setValueByPath(toObject, ['referenceType'], fromReferenceType);\n }\n\n return toObject;\n}\n\nexport function generateVideosConfigToVertex(\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (parentObject !== undefined && fromFps != null) {\n common.setValueByPath(parentObject, ['parameters', 'fps'], fromFps);\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromResolution = common.getValueByPath(fromObject, ['resolution']);\n if (parentObject !== undefined && fromResolution != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'resolution'],\n fromResolution,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromPubsubTopic = common.getValueByPath(fromObject, ['pubsubTopic']);\n if (parentObject !== undefined && fromPubsubTopic != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'pubsubTopic'],\n fromPubsubTopic,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n const fromGenerateAudio = common.getValueByPath(fromObject, [\n 'generateAudio',\n ]);\n if (parentObject !== undefined && fromGenerateAudio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'generateAudio'],\n fromGenerateAudio,\n );\n }\n\n const fromLastFrame = common.getValueByPath(fromObject, ['lastFrame']);\n if (parentObject !== undefined && fromLastFrame != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'lastFrame'],\n imageToVertex(fromLastFrame),\n );\n }\n\n const fromReferenceImages = common.getValueByPath(fromObject, [\n 'referenceImages',\n ]);\n if (parentObject !== undefined && fromReferenceImages != null) {\n let transformedList = fromReferenceImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return videoGenerationReferenceImageToVertex(item);\n });\n }\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'referenceImages'],\n transformedList,\n );\n }\n\n const fromCompressionQuality = common.getValueByPath(fromObject, [\n 'compressionQuality',\n ]);\n if (parentObject !== undefined && fromCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'compressionQuality'],\n fromCompressionQuality,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'video'],\n videoToVertex(fromVideo),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(toObject, ['content'], contentFromMldev(fromContent));\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromMldev(\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function embedContentResponseFromMldev(\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromEmbeddings = common.getValueByPath(fromObject, ['embeddings']);\n if (fromEmbeddings != null) {\n let transformedList = fromEmbeddings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentEmbeddingFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['embeddings'], transformedList);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromMldev(),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromMldev(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(toObject, ['imageBytes'], t.tBytes(fromImageBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromMldev(\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromMldev(\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageFromMldev(fromImage));\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromMldev(fromSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromMldev(\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromMldev(fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function tunedModelInfoFromMldev(\n fromObject: types.TunedModelInfo,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n return toObject;\n}\n\nexport function modelFromMldev(\n fromObject: types.Model,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromVersion = common.getValueByPath(fromObject, ['version']);\n if (fromVersion != null) {\n common.setValueByPath(toObject, ['version'], fromVersion);\n }\n\n const fromTunedModelInfo = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModelInfo != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelInfo'],\n tunedModelInfoFromMldev(fromTunedModelInfo),\n );\n }\n\n const fromInputTokenLimit = common.getValueByPath(fromObject, [\n 'inputTokenLimit',\n ]);\n if (fromInputTokenLimit != null) {\n common.setValueByPath(toObject, ['inputTokenLimit'], fromInputTokenLimit);\n }\n\n const fromOutputTokenLimit = common.getValueByPath(fromObject, [\n 'outputTokenLimit',\n ]);\n if (fromOutputTokenLimit != null) {\n common.setValueByPath(toObject, ['outputTokenLimit'], fromOutputTokenLimit);\n }\n\n const fromSupportedActions = common.getValueByPath(fromObject, [\n 'supportedGenerationMethods',\n ]);\n if (fromSupportedActions != null) {\n common.setValueByPath(toObject, ['supportedActions'], fromSupportedActions);\n }\n\n return toObject;\n}\n\nexport function listModelsResponseFromMldev(\n fromObject: types.ListModelsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromModels = common.getValueByPath(fromObject, ['_self']);\n if (fromModels != null) {\n let transformedList = t.tExtractModels(fromModels);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modelFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['models'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteModelResponseFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function countTokensResponseFromMldev(\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n return toObject;\n}\n\nexport function videoFromMldev(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['video', 'uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'video',\n 'encodedVideo',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromMldev(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromMldev(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, [\n 'generatedSamples',\n ]);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, [\n 'response',\n 'generateVideoResponse',\n ]);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromMldev(fromResponse),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromVertex(\n fromObject: types.Blob,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromVertex(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citations']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromVertex(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromVertex(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromVertex(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(\n toObject,\n ['content'],\n contentFromVertex(fromContent),\n );\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromVertex(fromCitationMetadata),\n );\n }\n\n const fromFinishMessage = common.getValueByPath(fromObject, [\n 'finishMessage',\n ]);\n if (fromFinishMessage != null) {\n common.setValueByPath(toObject, ['finishMessage'], fromFinishMessage);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromVertex(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromVertex(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingStatisticsFromVertex(\n fromObject: types.ContentEmbeddingStatistics,\n): Record {\n const toObject: Record = {};\n\n const fromTruncated = common.getValueByPath(fromObject, ['truncated']);\n if (fromTruncated != null) {\n common.setValueByPath(toObject, ['truncated'], fromTruncated);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['token_count']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromVertex(\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n const fromStatistics = common.getValueByPath(fromObject, ['statistics']);\n if (fromStatistics != null) {\n common.setValueByPath(\n toObject,\n ['statistics'],\n contentEmbeddingStatisticsFromVertex(fromStatistics),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromVertex(\n fromObject: types.EmbedContentMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromBillableCharacterCount = common.getValueByPath(fromObject, [\n 'billableCharacterCount',\n ]);\n if (fromBillableCharacterCount != null) {\n common.setValueByPath(\n toObject,\n ['billableCharacterCount'],\n fromBillableCharacterCount,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentResponseFromVertex(\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromEmbeddings = common.getValueByPath(fromObject, [\n 'predictions[]',\n 'embeddings',\n ]);\n if (fromEmbeddings != null) {\n let transformedList = fromEmbeddings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentEmbeddingFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['embeddings'], transformedList);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromVertex(fromMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromVertex(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(toObject, ['imageBytes'], t.tBytes(fromImageBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromVertex(\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromVertex(\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageFromVertex(fromImage));\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromVertex(fromSafetyAttributes),\n );\n }\n\n const fromEnhancedPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromEnhancedPrompt != null) {\n common.setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt);\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromVertex(\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromVertex(fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function editImageResponseFromVertex(\n fromObject: types.EditImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function upscaleImageResponseFromVertex(\n fromObject: types.UpscaleImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function recontextImageResponseFromVertex(\n fromObject: types.RecontextImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function entityLabelFromVertex(\n fromObject: types.EntityLabel,\n): Record {\n const toObject: Record = {};\n\n const fromLabel = common.getValueByPath(fromObject, ['label']);\n if (fromLabel != null) {\n common.setValueByPath(toObject, ['label'], fromLabel);\n }\n\n const fromScore = common.getValueByPath(fromObject, ['score']);\n if (fromScore != null) {\n common.setValueByPath(toObject, ['score'], fromScore);\n }\n\n return toObject;\n}\n\nexport function generatedImageMaskFromVertex(\n fromObject: types.GeneratedImageMask,\n): Record {\n const toObject: Record = {};\n\n const fromMask = common.getValueByPath(fromObject, ['_self']);\n if (fromMask != null) {\n common.setValueByPath(toObject, ['mask'], imageFromVertex(fromMask));\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n let transformedList = fromLabels;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return entityLabelFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['labels'], transformedList);\n }\n\n return toObject;\n}\n\nexport function segmentImageResponseFromVertex(\n fromObject: types.SegmentImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedMasks = common.getValueByPath(fromObject, ['predictions']);\n if (fromGeneratedMasks != null) {\n let transformedList = fromGeneratedMasks;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageMaskFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedMasks'], transformedList);\n }\n\n return toObject;\n}\n\nexport function endpointFromVertex(\n fromObject: types.Endpoint,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['endpoint']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDeployedModelId = common.getValueByPath(fromObject, [\n 'deployedModelId',\n ]);\n if (fromDeployedModelId != null) {\n common.setValueByPath(toObject, ['deployedModelId'], fromDeployedModelId);\n }\n\n return toObject;\n}\n\nexport function tunedModelInfoFromVertex(\n fromObject: types.TunedModelInfo,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, [\n 'labels',\n 'google-vertex-llm-tuning-base-model-id',\n ]);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n return toObject;\n}\n\nexport function checkpointFromVertex(\n fromObject: types.Checkpoint,\n): Record {\n const toObject: Record = {};\n\n const fromCheckpointId = common.getValueByPath(fromObject, ['checkpointId']);\n if (fromCheckpointId != null) {\n common.setValueByPath(toObject, ['checkpointId'], fromCheckpointId);\n }\n\n const fromEpoch = common.getValueByPath(fromObject, ['epoch']);\n if (fromEpoch != null) {\n common.setValueByPath(toObject, ['epoch'], fromEpoch);\n }\n\n const fromStep = common.getValueByPath(fromObject, ['step']);\n if (fromStep != null) {\n common.setValueByPath(toObject, ['step'], fromStep);\n }\n\n return toObject;\n}\n\nexport function modelFromVertex(\n fromObject: types.Model,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromVersion = common.getValueByPath(fromObject, ['versionId']);\n if (fromVersion != null) {\n common.setValueByPath(toObject, ['version'], fromVersion);\n }\n\n const fromEndpoints = common.getValueByPath(fromObject, ['deployedModels']);\n if (fromEndpoints != null) {\n let transformedList = fromEndpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return endpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['endpoints'], transformedList);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromTunedModelInfo = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModelInfo != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelInfo'],\n tunedModelInfoFromVertex(fromTunedModelInfo),\n );\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (fromDefaultCheckpointId != null) {\n common.setValueByPath(\n toObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n const fromCheckpoints = common.getValueByPath(fromObject, ['checkpoints']);\n if (fromCheckpoints != null) {\n let transformedList = fromCheckpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return checkpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['checkpoints'], transformedList);\n }\n\n return toObject;\n}\n\nexport function listModelsResponseFromVertex(\n fromObject: types.ListModelsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromModels = common.getValueByPath(fromObject, ['_self']);\n if (fromModels != null) {\n let transformedList = t.tExtractModels(fromModels);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modelFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['models'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteModelResponseFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function countTokensResponseFromVertex(\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n return toObject;\n}\n\nexport function computeTokensResponseFromVertex(\n fromObject: types.ComputeTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTokensInfo = common.getValueByPath(fromObject, ['tokensInfo']);\n if (fromTokensInfo != null) {\n common.setValueByPath(toObject, ['tokensInfo'], fromTokensInfo);\n }\n\n return toObject;\n}\n\nexport function videoFromVertex(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromVertex(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromVertex(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromVertex(fromResponse),\n );\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {Client as McpClient} from '@modelcontextprotocol/sdk/client/index.js';\nimport type {Tool as McpTool} from '@modelcontextprotocol/sdk/types.js';\n\nimport {GOOGLE_API_CLIENT_HEADER} from '../_api_client.js';\nimport {mcpToolsToGeminiTool} from '../_transformers.js';\nimport {\n CallableTool,\n CallableToolConfig,\n FunctionCall,\n Part,\n Tool,\n ToolListUnion,\n} from '../types.js';\n\n// TODO: b/416041229 - Determine how to retrieve the MCP package version.\nexport const MCP_LABEL = 'mcp_used/unknown';\n\n// Whether MCP tool usage is detected from mcpToTool. This is used for\n// telemetry.\nlet hasMcpToolUsageFromMcpToTool = false;\n\n// Checks whether the list of tools contains any MCP tools.\nexport function hasMcpToolUsage(tools: ToolListUnion): boolean {\n for (const tool of tools) {\n if (isMcpCallableTool(tool)) {\n return true;\n }\n if (typeof tool === 'object' && 'inputSchema' in tool) {\n return true;\n }\n }\n\n return hasMcpToolUsageFromMcpToTool;\n}\n\n// Sets the MCP version label in the Google API client header.\nexport function setMcpUsageHeader(headers: Record) {\n const existingHeader = headers[GOOGLE_API_CLIENT_HEADER] ?? '';\n headers[GOOGLE_API_CLIENT_HEADER] = (\n existingHeader + ` ${MCP_LABEL}`\n ).trimStart();\n}\n\n// Returns true if the object is a MCP CallableTool, otherwise false.\nfunction isMcpCallableTool(object: unknown): boolean {\n return (\n object !== null &&\n typeof object === 'object' &&\n object instanceof McpCallableTool\n );\n}\n\n// List all tools from the MCP client.\nasync function* listAllTools(\n mcpClient: McpClient,\n maxTools: number = 100,\n): AsyncGenerator {\n let cursor: string | undefined = undefined;\n let numTools = 0;\n while (numTools < maxTools) {\n const t = await mcpClient.listTools({cursor});\n for (const tool of t.tools) {\n yield tool;\n numTools++;\n }\n if (!t.nextCursor) {\n break;\n }\n cursor = t.nextCursor;\n }\n}\n\n/**\n * McpCallableTool can be used for model inference and invoking MCP clients with\n * given function call arguments.\n *\n * @experimental Built-in MCP support is an experimental feature, may change in future\n * versions.\n */\nexport class McpCallableTool implements CallableTool {\n private readonly mcpClients;\n private mcpTools: McpTool[] = [];\n private functionNameToMcpClient: Record = {};\n private readonly config: CallableToolConfig;\n\n private constructor(\n mcpClients: McpClient[] = [],\n config: CallableToolConfig,\n ) {\n this.mcpClients = mcpClients;\n this.config = config;\n }\n\n /**\n * Creates a McpCallableTool.\n */\n public static create(\n mcpClients: McpClient[],\n config: CallableToolConfig,\n ): McpCallableTool {\n return new McpCallableTool(mcpClients, config);\n }\n\n /**\n * Validates the function names are not duplicate and initialize the function\n * name to MCP client mapping.\n *\n * @throws {Error} if the MCP tools from the MCP clients have duplicate tool\n * names.\n */\n async initialize() {\n if (this.mcpTools.length > 0) {\n return;\n }\n\n const functionMap: Record = {};\n const mcpTools: McpTool[] = [];\n for (const mcpClient of this.mcpClients) {\n for await (const mcpTool of listAllTools(mcpClient)) {\n mcpTools.push(mcpTool);\n const mcpToolName = mcpTool.name as string;\n if (functionMap[mcpToolName]) {\n throw new Error(\n `Duplicate function name ${\n mcpToolName\n } found in MCP tools. Please ensure function names are unique.`,\n );\n }\n functionMap[mcpToolName] = mcpClient;\n }\n }\n this.mcpTools = mcpTools;\n this.functionNameToMcpClient = functionMap;\n }\n\n public async tool(): Promise {\n await this.initialize();\n return mcpToolsToGeminiTool(this.mcpTools, this.config);\n }\n\n public async callTool(functionCalls: FunctionCall[]): Promise {\n await this.initialize();\n const functionCallResponseParts: Part[] = [];\n for (const functionCall of functionCalls) {\n if (functionCall.name! in this.functionNameToMcpClient) {\n const mcpClient = this.functionNameToMcpClient[functionCall.name!];\n let requestOptions = undefined;\n // TODO: b/424238654 - Add support for finer grained timeout control.\n if (this.config.timeout) {\n requestOptions = {\n timeout: this.config.timeout,\n };\n }\n const callToolResponse = await mcpClient.callTool(\n {\n name: functionCall.name!,\n arguments: functionCall.args,\n },\n // Set the result schema to undefined to allow MCP to rely on the\n // default schema.\n undefined,\n requestOptions,\n );\n functionCallResponseParts.push({\n functionResponse: {\n name: functionCall.name,\n response: callToolResponse.isError\n ? {error: callToolResponse}\n : (callToolResponse as Record),\n },\n });\n }\n }\n return functionCallResponseParts;\n }\n}\n\nfunction isMcpClient(client: unknown): client is McpClient {\n return (\n client !== null &&\n typeof client === 'object' &&\n 'listTools' in client &&\n typeof client.listTools === 'function'\n );\n}\n\n/**\n * Creates a McpCallableTool from MCP clients and an optional config.\n *\n * The callable tool can invoke the MCP clients with given function call\n * arguments. (often for automatic function calling).\n * Use the config to modify tool parameters such as behavior.\n *\n * @experimental Built-in MCP support is an experimental feature, may change in future\n * versions.\n */\nexport function mcpToTool(\n ...args: [...McpClient[], CallableToolConfig | McpClient]\n): CallableTool {\n // Set MCP usage for telemetry.\n hasMcpToolUsageFromMcpToTool = true;\n if (args.length === 0) {\n throw new Error('No MCP clients provided');\n }\n const maybeConfig = args[args.length - 1];\n if (isMcpClient(maybeConfig)) {\n return McpCallableTool.create(args as McpClient[], {});\n }\n return McpCallableTool.create(\n args.slice(0, args.length - 1) as McpClient[],\n maybeConfig,\n );\n}\n\n/**\n * Sets the MCP tool usage flag from calling mcpToTool. This is used for\n * telemetry.\n */\nexport function setMcpToolUsageFromMcpToTool(mcpToolUsage: boolean) {\n hasMcpToolUsageFromMcpToTool = mcpToolUsage;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live music client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client.js';\nimport {Auth} from './_auth.js';\nimport * as t from './_transformers.js';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket.js';\nimport * as converters from './converters/_live_converters.js';\nimport * as types from './types.js';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveMusicServerMessage, and then calling the onmessage callback.\n * Note that the first message which is received from the server is a\n * setupComplete message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveMusicServerMessage) => void,\n event: MessageEvent,\n): Promise {\n const serverMessage: types.LiveMusicServerMessage =\n new types.LiveMusicServerMessage();\n let data: types.LiveMusicServerMessage;\n if (event.data instanceof Blob) {\n data = JSON.parse(await event.data.text()) as types.LiveMusicServerMessage;\n } else {\n data = JSON.parse(event.data) as types.LiveMusicServerMessage;\n }\n const response = converters.liveMusicServerMessageFromMldev(data);\n Object.assign(serverMessage, response);\n onmessage(serverMessage);\n}\n\n/**\n LiveMusic class encapsulates the configuration for live music\n generation via Lyria Live models.\n\n @experimental\n */\nexport class LiveMusic {\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {}\n\n /**\n Establishes a connection to the specified model and returns a\n LiveMusicSession object representing that connection.\n\n @experimental\n\n @remarks\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n let model = 'models/lyria-realtime-exp';\n const session = await ai.live.music.connect({\n model: model,\n callbacks: {\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(\n params: types.LiveMusicConnectParameters,\n ): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error('Live music is not supported for Vertex AI.');\n }\n console.warn(\n 'Live music generation is experimental and may change in future versions.',\n );\n\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n const headers = mapToHeaders(this.apiClient.getDefaultHeaders());\n const apiKey = this.apiClient.getApiKey();\n const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.BidiGenerateMusic?key=${apiKey}`;\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveMusicCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n const model = t.tModel(this.apiClient, params.model);\n const setup = converters.liveMusicClientSetupToMldev({\n model,\n });\n const clientMessage = converters.liveMusicClientMessageToMldev({setup});\n conn.send(JSON.stringify(clientMessage));\n\n return new LiveMusicSession(conn, this.apiClient);\n }\n}\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class LiveMusicSession {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n /**\n Sets inputs to steer music generation. Updates the session's current\n weighted prompts.\n\n @param params - Contains one property, `weightedPrompts`.\n\n - `weightedPrompts` to send to the model; weights are normalized to\n sum to 1.0.\n\n @experimental\n */\n async setWeightedPrompts(\n params: types.LiveMusicSetWeightedPromptsParameters,\n ) {\n if (\n !params.weightedPrompts ||\n Object.keys(params.weightedPrompts).length === 0\n ) {\n throw new Error(\n 'Weighted prompts must be set and contain at least one entry.',\n );\n }\n const setWeightedPromptsParameters =\n converters.liveMusicSetWeightedPromptsParametersToMldev(params);\n const clientContent = converters.liveMusicClientContentToMldev(\n setWeightedPromptsParameters,\n );\n this.conn.send(JSON.stringify({clientContent}));\n }\n\n /**\n Sets a configuration to the model. Updates the session's current\n music generation config.\n\n @param params - Contains one property, `musicGenerationConfig`.\n\n - `musicGenerationConfig` to set in the model. Passing an empty or\n undefined config to the model will reset the config to defaults.\n\n @experimental\n */\n async setMusicGenerationConfig(params: types.LiveMusicSetConfigParameters) {\n if (!params.musicGenerationConfig) {\n params.musicGenerationConfig = {};\n }\n const setConfigParameters =\n converters.liveMusicSetConfigParametersToMldev(params);\n const clientMessage =\n converters.liveMusicClientMessageToMldev(setConfigParameters);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n private sendPlaybackControl(playbackControl: types.LiveMusicPlaybackControl) {\n const clientMessage = converters.liveMusicClientMessageToMldev({\n playbackControl,\n });\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n * Start the music stream.\n *\n * @experimental\n */\n play() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.PLAY);\n }\n\n /**\n * Temporarily halt the music stream. Use `play` to resume from the current\n * position.\n *\n * @experimental\n */\n pause() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.PAUSE);\n }\n\n /**\n * Stop the music stream and reset the state. Retains the current prompts\n * and config.\n *\n * @experimental\n */\n stop() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.STOP);\n }\n\n /**\n * Resets the context of the music generation without stopping it.\n * Retains the current prompts and config.\n *\n * @experimental\n */\n resetContext() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.RESET_CONTEXT);\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client.js';\nimport {Auth} from './_auth.js';\nimport * as t from './_transformers.js';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket.js';\nimport * as converters from './converters/_live_converters.js';\nimport {\n contentToMldev,\n contentToVertex,\n} from './converters/_models_converters.js';\nimport {hasMcpToolUsage, setMcpUsageHeader} from './mcp/_mcp.js';\nimport {LiveMusic} from './music.js';\nimport * as types from './types.js';\n\nconst FUNCTION_RESPONSE_REQUIRES_ID =\n 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveServerMessages, and then calling the onmessage callback. Note that\n * the first message which is received from the server is a setupComplete\n * message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveServerMessage) => void,\n event: MessageEvent,\n): Promise {\n const serverMessage: types.LiveServerMessage = new types.LiveServerMessage();\n let jsonData: string;\n if (event.data instanceof Blob) {\n jsonData = await event.data.text();\n } else if (event.data instanceof ArrayBuffer) {\n jsonData = new TextDecoder().decode(event.data);\n } else {\n jsonData = event.data;\n }\n\n const data = JSON.parse(jsonData) as types.LiveServerMessage;\n\n if (apiClient.isVertexAI()) {\n const resp = converters.liveServerMessageFromVertex(data);\n Object.assign(serverMessage, resp);\n } else {\n const resp = converters.liveServerMessageFromMldev(data);\n Object.assign(serverMessage, resp);\n }\n\n onmessage(serverMessage);\n}\n\n/**\n Live class encapsulates the configuration for live interaction with the\n Generative Language API. It embeds ApiClient for general API settings.\n\n @experimental\n */\nexport class Live {\n public readonly music: LiveMusic;\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {\n this.music = new LiveMusic(\n this.apiClient,\n this.auth,\n this.webSocketFactory,\n );\n }\n\n /**\n Establishes a connection to the specified model with the given\n configuration and returns a Session object representing that connection.\n\n @experimental Built-in MCP support is an experimental feature, may change in\n future versions.\n\n @remarks\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n let model: string;\n if (GOOGLE_GENAI_USE_VERTEXAI) {\n model = 'gemini-2.0-flash-live-preview-04-09';\n } else {\n model = 'gemini-live-2.5-flash-preview';\n }\n const session = await ai.live.connect({\n model: model,\n config: {\n responseModalities: [Modality.AUDIO],\n },\n callbacks: {\n onopen: () => {\n console.log('Connected to the socket.');\n },\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(params: types.LiveConnectParameters): Promise {\n // TODO: b/404946746 - Support per request HTTP options.\n if (params.config && params.config.httpOptions) {\n throw new Error(\n 'The Live module does not support httpOptions at request-level in' +\n ' LiveConnectConfig yet. Please use the client-level httpOptions' +\n ' configuration instead.',\n );\n }\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n let url: string;\n const clientHeaders = this.apiClient.getHeaders();\n if (\n params.config &&\n params.config.tools &&\n hasMcpToolUsage(params.config.tools)\n ) {\n setMcpUsageHeader(clientHeaders);\n }\n const headers = mapToHeaders(clientHeaders);\n if (this.apiClient.isVertexAI()) {\n url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${\n apiVersion\n }.LlmBidiService/BidiGenerateContent`;\n await this.auth.addAuthHeaders(headers);\n } else {\n const apiKey = this.apiClient.getApiKey();\n\n let method = 'BidiGenerateContent';\n let keyName = 'key';\n if (apiKey?.startsWith('auth_tokens/')) {\n console.warn(\n 'Warning: Ephemeral token support is experimental and may change in future versions.',\n );\n if (apiVersion !== 'v1alpha') {\n console.warn(\n \"Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection.\",\n );\n }\n method = 'BidiGenerateContentConstrained';\n keyName = 'access_token';\n }\n\n url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.${method}?${keyName}=${apiKey}`;\n }\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n callbacks?.onopen?.();\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n let transformedModel = t.tModel(this.apiClient, params.model);\n if (\n this.apiClient.isVertexAI() &&\n transformedModel.startsWith('publishers/')\n ) {\n const project = this.apiClient.getProject();\n const location = this.apiClient.getLocation();\n transformedModel =\n `projects/${project}/locations/${location}/` + transformedModel;\n }\n\n let clientMessage: Record = {};\n\n if (\n this.apiClient.isVertexAI() &&\n params.config?.responseModalities === undefined\n ) {\n // Set default to AUDIO to align with MLDev API.\n if (params.config === undefined) {\n params.config = {responseModalities: [types.Modality.AUDIO]};\n } else {\n params.config.responseModalities = [types.Modality.AUDIO];\n }\n }\n if (params.config?.generationConfig) {\n // Raise deprecation warning for generationConfig.\n console.warn(\n 'Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).',\n );\n }\n const inputTools = params.config?.tools ?? [];\n const convertedTools: types.Tool[] = [];\n for (const tool of inputTools) {\n if (this.isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n convertedTools.push(await callableTool.tool());\n } else {\n convertedTools.push(tool as types.Tool);\n }\n }\n if (convertedTools.length > 0) {\n params.config!.tools = convertedTools;\n }\n const liveConnectParameters: types.LiveConnectParameters = {\n model: transformedModel,\n config: params.config,\n callbacks: params.callbacks,\n };\n if (this.apiClient.isVertexAI()) {\n clientMessage = converters.liveConnectParametersToVertex(\n this.apiClient,\n liveConnectParameters,\n );\n } else {\n clientMessage = converters.liveConnectParametersToMldev(\n this.apiClient,\n liveConnectParameters,\n );\n }\n delete clientMessage['config'];\n conn.send(JSON.stringify(clientMessage));\n return new Session(conn, this.apiClient);\n }\n\n // TODO: b/416041229 - Abstract this method to a common place.\n private isCallableTool(tool: types.ToolUnion): boolean {\n return 'callTool' in tool && typeof tool.callTool === 'function';\n }\n}\n\nconst defaultLiveSendClientContentParamerters: types.LiveSendClientContentParameters =\n {\n turnComplete: true,\n };\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class Session {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n private tLiveClientContent(\n apiClient: ApiClient,\n params: types.LiveSendClientContentParameters,\n ): types.LiveClientMessage {\n if (params.turns !== null && params.turns !== undefined) {\n let contents: types.Content[] = [];\n try {\n contents = t.tContents(params.turns as types.ContentListUnion);\n if (apiClient.isVertexAI()) {\n contents = contents.map((item) => contentToVertex(item));\n } else {\n contents = contents.map((item) => contentToMldev(item));\n }\n } catch {\n throw new Error(\n `Failed to parse client content \"turns\", type: '${typeof params.turns}'`,\n );\n }\n return {\n clientContent: {turns: contents, turnComplete: params.turnComplete},\n };\n }\n\n return {\n clientContent: {turnComplete: params.turnComplete},\n };\n }\n\n private tLiveClienttToolResponse(\n apiClient: ApiClient,\n params: types.LiveSendToolResponseParameters,\n ): types.LiveClientMessage {\n let functionResponses: types.FunctionResponse[] = [];\n\n if (params.functionResponses == null) {\n throw new Error('functionResponses is required.');\n }\n\n if (!Array.isArray(params.functionResponses)) {\n functionResponses = [params.functionResponses];\n } else {\n functionResponses = params.functionResponses;\n }\n\n if (functionResponses.length === 0) {\n throw new Error('functionResponses is required.');\n }\n\n for (const functionResponse of functionResponses) {\n if (\n typeof functionResponse !== 'object' ||\n functionResponse === null ||\n !('name' in functionResponse) ||\n !('response' in functionResponse)\n ) {\n throw new Error(\n `Could not parse function response, type '${typeof functionResponse}'.`,\n );\n }\n if (!apiClient.isVertexAI() && !('id' in functionResponse)) {\n throw new Error(FUNCTION_RESPONSE_REQUIRES_ID);\n }\n }\n\n const clientMessage: types.LiveClientMessage = {\n toolResponse: {functionResponses: functionResponses},\n };\n return clientMessage;\n }\n\n /**\n Send a message over the established connection.\n\n @param params - Contains two **optional** properties, `turns` and\n `turnComplete`.\n\n - `turns` will be converted to a `Content[]`\n - `turnComplete: true` [default] indicates that you are done sending\n content and expect a response. If `turnComplete: false`, the server\n will wait for additional messages before starting generation.\n\n @experimental\n\n @remarks\n There are two ways to send messages to the live API:\n `sendClientContent` and `sendRealtimeInput`.\n\n `sendClientContent` messages are added to the model context **in order**.\n Having a conversation using `sendClientContent` messages is roughly\n equivalent to using the `Chat.sendMessageStream`, except that the state of\n the `chat` history is stored on the API server instead of locally.\n\n Because of `sendClientContent`'s order guarantee, the model cannot respons\n as quickly to `sendClientContent` messages as to `sendRealtimeInput`\n messages. This makes the biggest difference when sending objects that have\n significant preprocessing time (typically images).\n\n The `sendClientContent` message sends a `Content[]`\n which has more options than the `Blob` sent by `sendRealtimeInput`.\n\n So the main use-cases for `sendClientContent` over `sendRealtimeInput` are:\n\n - Sending anything that can't be represented as a `Blob` (text,\n `sendClientContent({turns=\"Hello?\"}`)).\n - Managing turns when not using audio input and voice activity detection.\n (`sendClientContent({turnComplete:true})` or the short form\n `sendClientContent()`)\n - Prefilling a conversation context\n ```\n sendClientContent({\n turns: [\n Content({role:user, parts:...}),\n Content({role:user, parts:...}),\n ...\n ]\n })\n ```\n @experimental\n */\n sendClientContent(params: types.LiveSendClientContentParameters) {\n params = {\n ...defaultLiveSendClientContentParamerters,\n ...params,\n };\n\n const clientMessage: types.LiveClientMessage = this.tLiveClientContent(\n this.apiClient,\n params,\n );\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a realtime message over the established connection.\n\n @param params - Contains one property, `media`.\n\n - `media` will be converted to a `Blob`\n\n @experimental\n\n @remarks\n Use `sendRealtimeInput` for realtime audio chunks and video frames (images).\n\n With `sendRealtimeInput` the api will respond to audio automatically\n based on voice activity detection (VAD).\n\n `sendRealtimeInput` is optimized for responsivness at the expense of\n deterministic ordering guarantees. Audio and video tokens are to the\n context when they become available.\n\n Note: The Call signature expects a `Blob` object, but only a subset\n of audio and image mimetypes are allowed.\n */\n sendRealtimeInput(params: types.LiveSendRealtimeInputParameters) {\n let clientMessage: types.LiveClientMessage = {};\n\n if (this.apiClient.isVertexAI()) {\n clientMessage = {\n 'realtimeInput':\n converters.liveSendRealtimeInputParametersToVertex(params),\n };\n } else {\n clientMessage = {\n 'realtimeInput':\n converters.liveSendRealtimeInputParametersToMldev(params),\n };\n }\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a function response message over the established connection.\n\n @param params - Contains property `functionResponses`.\n\n - `functionResponses` will be converted to a `functionResponses[]`\n\n @remarks\n Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server.\n\n Use {@link types.LiveConnectConfig#tools} to configure the callable functions.\n\n @experimental\n */\n sendToolResponse(params: types.LiveSendToolResponseParameters) {\n if (params.functionResponses == null) {\n throw new Error('Tool response parameters are required.');\n }\n\n const clientMessage: types.LiveClientMessage =\n this.tLiveClienttToolResponse(this.apiClient, params);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n\n @example\n ```ts\n let model: string;\n if (GOOGLE_GENAI_USE_VERTEXAI) {\n model = 'gemini-2.0-flash-live-preview-04-09';\n } else {\n model = 'gemini-live-2.5-flash-preview';\n }\n const session = await ai.live.connect({\n model: model,\n config: {\n responseModalities: [Modality.AUDIO],\n }\n });\n\n session.close();\n ```\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as types from './types.js';\n\nexport const DEFAULT_MAX_REMOTE_CALLS = 10;\n\n/** Returns whether automatic function calling is disabled. */\nexport function shouldDisableAfc(\n config: types.GenerateContentConfig | undefined,\n): boolean {\n if (config?.automaticFunctionCalling?.disable) {\n return true;\n }\n\n let callableToolsPresent = false;\n for (const tool of config?.tools ?? []) {\n if (isCallableTool(tool)) {\n callableToolsPresent = true;\n break;\n }\n }\n if (!callableToolsPresent) {\n return true;\n }\n\n const maxCalls = config?.automaticFunctionCalling?.maximumRemoteCalls;\n if (\n (maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) ||\n maxCalls == 0\n ) {\n console.warn(\n 'Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:',\n maxCalls,\n );\n return true;\n }\n return false;\n}\n\nexport function isCallableTool(tool: types.ToolUnion): boolean {\n return 'callTool' in tool && typeof tool.callTool === 'function';\n}\n\n// Checks whether the list of tools contains any CallableTools. Will return true\n// if there is at least one CallableTool.\nexport function hasCallableTools(\n params: types.GenerateContentParameters,\n): boolean {\n return params.config?.tools?.some((tool) => isCallableTool(tool)) ?? false;\n}\n\n// Checks whether the list of tools contains any non-callable tools. Will return\n// true if there is at least one non-Callable tool.\nexport function hasNonCallableTools(\n params: types.GenerateContentParameters,\n): boolean {\n return params.config?.tools?.some((tool) => !isCallableTool(tool)) ?? false;\n}\n\n/**\n * Returns whether to append automatic function calling history to the\n * response.\n */\nexport function shouldAppendAfcHistory(\n config: types.GenerateContentConfig | undefined,\n): boolean {\n return !config?.automaticFunctionCalling?.ignoreCallHistory;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {\n DEFAULT_MAX_REMOTE_CALLS,\n hasCallableTools,\n hasNonCallableTools,\n isCallableTool,\n shouldAppendAfcHistory,\n shouldDisableAfc,\n} from './_afc.js';\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as _internal_types from './_internal_types.js';\nimport {tContents} from './_transformers.js';\nimport * as converters from './converters/_models_converters.js';\nimport {hasMcpToolUsage, setMcpUsageHeader} from './mcp/_mcp.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Models extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Makes an API request to generate content with a given model.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * candidateCount: 2,\n * }\n * });\n * console.log(response);\n * ```\n */\n generateContent = async (\n params: types.GenerateContentParameters,\n ): Promise => {\n const transformedParams = await this.processParamsMaybeAddMcpUsage(params);\n this.maybeMoveToResponseJsonSchem(params);\n if (!hasCallableTools(params) || shouldDisableAfc(params.config)) {\n return await this.generateContentInternal(transformedParams);\n }\n\n if (hasNonCallableTools(params)) {\n throw new Error(\n 'Automatic function calling with CallableTools and Tools is not yet supported.',\n );\n }\n\n let response: types.GenerateContentResponse;\n let functionResponseContent: types.Content;\n const automaticFunctionCallingHistory: types.Content[] = tContents(\n transformedParams.contents,\n );\n const maxRemoteCalls =\n transformedParams.config?.automaticFunctionCalling?.maximumRemoteCalls ??\n DEFAULT_MAX_REMOTE_CALLS;\n let remoteCalls = 0;\n while (remoteCalls < maxRemoteCalls) {\n response = await this.generateContentInternal(transformedParams);\n if (!response.functionCalls || response.functionCalls!.length === 0) {\n break;\n }\n\n const responseContent: types.Content = response.candidates![0].content!;\n const functionResponseParts: types.Part[] = [];\n for (const tool of params.config?.tools ?? []) {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n const parts = await callableTool.callTool(response.functionCalls!);\n functionResponseParts.push(...parts);\n }\n }\n\n remoteCalls++;\n\n functionResponseContent = {\n role: 'user',\n parts: functionResponseParts,\n };\n\n transformedParams.contents = tContents(transformedParams.contents);\n (transformedParams.contents as types.Content[]).push(responseContent);\n (transformedParams.contents as types.Content[]).push(\n functionResponseContent,\n );\n\n if (shouldAppendAfcHistory(transformedParams.config)) {\n automaticFunctionCallingHistory.push(responseContent);\n automaticFunctionCallingHistory.push(functionResponseContent);\n }\n }\n if (shouldAppendAfcHistory(transformedParams.config)) {\n response!.automaticFunctionCallingHistory =\n automaticFunctionCallingHistory;\n }\n return response!;\n };\n\n /**\n * This logic is needed for GenerateContentConfig only.\n * Previously we made GenerateContentConfig.responseSchema field to accept\n * unknown. Since v1.9.0, we switch to use backend JSON schema support.\n * To maintain backward compatibility, we move the data that was treated as\n * JSON schema from the responseSchema field to the responseJsonSchema field.\n */\n private maybeMoveToResponseJsonSchem(\n params: types.GenerateContentParameters,\n ): void {\n if (params.config && params.config.responseSchema) {\n if (!params.config.responseJsonSchema) {\n if (Object.keys(params.config.responseSchema).includes('$schema')) {\n params.config.responseJsonSchema = params.config.responseSchema;\n delete params.config.responseSchema;\n }\n }\n }\n return;\n }\n\n /**\n * Makes an API request to generate content with a given model and yields the\n * response in chunks.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content with streaming response.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContentStream({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * maxOutputTokens: 200,\n * }\n * });\n * for await (const chunk of response) {\n * console.log(chunk);\n * }\n * ```\n */\n generateContentStream = async (\n params: types.GenerateContentParameters,\n ): Promise> => {\n this.maybeMoveToResponseJsonSchem(params);\n if (shouldDisableAfc(params.config)) {\n const transformedParams =\n await this.processParamsMaybeAddMcpUsage(params);\n return await this.generateContentStreamInternal(transformedParams);\n } else {\n return await this.processAfcStream(params);\n }\n };\n\n /**\n * Transforms the CallableTools in the parameters to be simply Tools, it\n * copies the params into a new object and replaces the tools, it does not\n * modify the original params. Also sets the MCP usage header if there are\n * MCP tools in the parameters.\n */\n private async processParamsMaybeAddMcpUsage(\n params: types.GenerateContentParameters,\n ): Promise {\n const tools = params.config?.tools;\n if (!tools) {\n return params;\n }\n const transformedTools = await Promise.all(\n tools.map(async (tool) => {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n return await callableTool.tool();\n }\n return tool;\n }),\n );\n const newParams: types.GenerateContentParameters = {\n model: params.model,\n contents: params.contents,\n config: {\n ...params.config,\n tools: transformedTools,\n },\n };\n newParams.config!.tools = transformedTools;\n\n if (\n params.config &&\n params.config.tools &&\n hasMcpToolUsage(params.config.tools)\n ) {\n const headers = params.config.httpOptions?.headers ?? {};\n let newHeaders = {...headers};\n if (Object.keys(newHeaders).length === 0) {\n newHeaders = this.apiClient.getDefaultHeaders();\n }\n setMcpUsageHeader(newHeaders);\n newParams.config!.httpOptions = {\n ...params.config.httpOptions,\n headers: newHeaders,\n };\n }\n return newParams;\n }\n\n private async initAfcToolsMap(\n params: types.GenerateContentParameters,\n ): Promise> {\n const afcTools: Map = new Map();\n for (const tool of params.config?.tools ?? []) {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n const toolDeclaration = await callableTool.tool();\n for (const declaration of toolDeclaration.functionDeclarations ?? []) {\n if (!declaration.name) {\n throw new Error('Function declaration name is required.');\n }\n if (afcTools.has(declaration.name)) {\n throw new Error(\n `Duplicate tool declaration name: ${declaration.name}`,\n );\n }\n afcTools.set(declaration.name, callableTool);\n }\n }\n }\n return afcTools;\n }\n\n private async processAfcStream(\n params: types.GenerateContentParameters,\n ): Promise> {\n const maxRemoteCalls =\n params.config?.automaticFunctionCalling?.maximumRemoteCalls ??\n DEFAULT_MAX_REMOTE_CALLS;\n let wereFunctionsCalled = false;\n let remoteCallCount = 0;\n const afcToolsMap = await this.initAfcToolsMap(params);\n return (async function* (\n models: Models,\n afcTools: Map,\n params: types.GenerateContentParameters,\n ) {\n while (remoteCallCount < maxRemoteCalls) {\n if (wereFunctionsCalled) {\n remoteCallCount++;\n wereFunctionsCalled = false;\n }\n const transformedParams =\n await models.processParamsMaybeAddMcpUsage(params);\n const response =\n await models.generateContentStreamInternal(transformedParams);\n\n const functionResponses: types.Part[] = [];\n const responseContents: types.Content[] = [];\n\n for await (const chunk of response) {\n yield chunk;\n if (chunk.candidates && chunk.candidates[0]?.content) {\n responseContents.push(chunk.candidates[0].content);\n for (const part of chunk.candidates[0].content.parts ?? []) {\n if (remoteCallCount < maxRemoteCalls && part.functionCall) {\n if (!part.functionCall.name) {\n throw new Error(\n 'Function call name was not returned by the model.',\n );\n }\n if (!afcTools.has(part.functionCall.name)) {\n throw new Error(\n `Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${\n part.functionCall.name\n }`,\n );\n } else {\n const responseParts = await afcTools\n .get(part.functionCall.name)!\n .callTool([part.functionCall]);\n functionResponses.push(...responseParts);\n }\n }\n }\n }\n }\n\n if (functionResponses.length > 0) {\n wereFunctionsCalled = true;\n const typedResponseChunk = new types.GenerateContentResponse();\n typedResponseChunk.candidates = [\n {\n content: {\n role: 'user',\n parts: functionResponses,\n },\n },\n ];\n\n yield typedResponseChunk;\n\n const newContents: types.Content[] = [];\n newContents.push(...responseContents);\n newContents.push({\n role: 'user',\n parts: functionResponses,\n });\n const updatedContents = tContents(params.contents).concat(\n newContents,\n );\n\n params.contents = updatedContents;\n } else {\n break;\n }\n }\n })(this, afcToolsMap, params);\n }\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param params - The parameters for generating images.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n generateImages = async (\n params: types.GenerateImagesParameters,\n ): Promise => {\n return await this.generateImagesInternal(params).then((apiResponse) => {\n let positivePromptSafetyAttributes;\n const generatedImages = [];\n\n if (apiResponse?.generatedImages) {\n for (const generatedImage of apiResponse.generatedImages) {\n if (\n generatedImage &&\n generatedImage?.safetyAttributes &&\n generatedImage?.safetyAttributes?.contentType === 'Positive Prompt'\n ) {\n positivePromptSafetyAttributes = generatedImage?.safetyAttributes;\n } else {\n generatedImages.push(generatedImage);\n }\n }\n }\n let response: types.GenerateImagesResponse;\n\n if (positivePromptSafetyAttributes) {\n response = {\n generatedImages: generatedImages,\n positivePromptSafetyAttributes: positivePromptSafetyAttributes,\n sdkHttpResponse: apiResponse.sdkHttpResponse,\n };\n } else {\n response = {\n generatedImages: generatedImages,\n sdkHttpResponse: apiResponse.sdkHttpResponse,\n };\n }\n return response;\n });\n };\n\n list = async (\n params?: types.ListModelsParameters,\n ): Promise> => {\n const defaultConfig: types.ListModelsConfig = {\n queryBase: true,\n };\n const actualConfig: types.ListModelsConfig = {\n ...defaultConfig,\n ...params?.config,\n };\n const actualParams: types.ListModelsParameters = {\n config: actualConfig,\n };\n\n if (this.apiClient.isVertexAI()) {\n if (!actualParams.config!.queryBase) {\n if (actualParams.config?.filter) {\n throw new Error(\n 'Filtering tuned models list for Vertex AI is not currently supported',\n );\n } else {\n actualParams.config!.filter = 'labels.tune-type:*';\n }\n }\n }\n\n return new Pager(\n PagedItem.PAGED_ITEM_MODELS,\n (x: types.ListModelsParameters) => this.listInternal(x),\n await this.listInternal(actualParams),\n actualParams,\n );\n };\n\n /**\n * Edits an image based on a prompt, list of reference images, and configuration.\n *\n * @param params - The parameters for editing an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.editImage({\n * model: 'imagen-3.0-capability-001',\n * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.',\n * referenceImages: [subjectReferenceImage]\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n editImage = async (\n params: types.EditImageParameters,\n ): Promise => {\n const paramsInternal: _internal_types.EditImageParametersInternal = {\n model: params.model,\n prompt: params.prompt,\n referenceImages: [],\n config: params.config,\n };\n if (params.referenceImages) {\n if (params.referenceImages) {\n paramsInternal.referenceImages = params.referenceImages.map((img) =>\n img.toReferenceImageAPI(),\n );\n }\n }\n return await this.editImageInternal(paramsInternal);\n };\n\n /**\n * Upscales an image based on an image, upscale factor, and configuration.\n * Only supported in Vertex AI currently.\n *\n * @param params - The parameters for upscaling an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.upscaleImage({\n * model: 'imagen-3.0-generate-002',\n * image: image,\n * upscaleFactor: 'x2',\n * config: {\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n upscaleImage = async (\n params: types.UpscaleImageParameters,\n ): Promise => {\n let apiConfig: _internal_types.UpscaleImageAPIConfigInternal = {\n numberOfImages: 1,\n mode: 'upscale',\n };\n\n if (params.config) {\n apiConfig = {...apiConfig, ...params.config};\n }\n\n const apiParams: _internal_types.UpscaleImageAPIParametersInternal = {\n model: params.model,\n image: params.image,\n upscaleFactor: params.upscaleFactor,\n config: apiConfig,\n };\n return await this.upscaleImageInternal(apiParams);\n };\n\n /**\n * Generates videos based on a text description and configuration.\n *\n * @param params - The parameters for generating videos.\n * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method.\n *\n * @example\n * ```ts\n * const operation = await ai.models.generateVideos({\n * model: 'veo-2.0-generate-001',\n * prompt: 'A neon hologram of a cat driving at top speed',\n * config: {\n * numberOfVideos: 1\n * });\n *\n * while (!operation.done) {\n * await new Promise(resolve => setTimeout(resolve, 10000));\n * operation = await ai.operations.getVideosOperation({operation: operation});\n * }\n *\n * console.log(operation.response?.generatedVideos?.[0]?.video?.uri);\n * ```\n */\n\n generateVideos = async (\n params: types.GenerateVideosParameters,\n ): Promise => {\n return await this.generateVideosInternal(params);\n };\n\n private async generateContentInternal(\n params: types.GenerateContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromVertex(apiResponse);\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromMldev(apiResponse);\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async generateContentStreamInternal(\n params: types.GenerateContentParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromVertex(\n (await chunk.json()) as types.GenerateContentResponse,\n );\n\n resp['sdkHttpResponse'] = {\n headers: chunk.headers,\n } as types.HttpResponse;\n\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromMldev(\n (await chunk.json()) as types.GenerateContentResponse,\n );\n\n resp['sdkHttpResponse'] = {\n headers: chunk.headers,\n } as types.HttpResponse;\n\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n }\n }\n\n /**\n * Calculates embeddings for the given contents. Only text is supported.\n *\n * @param params - The parameters for embedding contents.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.embedContent({\n * model: 'text-embedding-004',\n * contents: [\n * 'What is your name?',\n * 'What is your favorite color?',\n * ],\n * config: {\n * outputDimensionality: 64,\n * },\n * });\n * console.log(response);\n * ```\n */\n async embedContent(\n params: types.EmbedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.embedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EmbedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromVertex(apiResponse);\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.embedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchEmbedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EmbedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromMldev(apiResponse);\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param params - The parameters for generating images.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n private async generateImagesInternal(\n params: types.GenerateImagesParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateImagesParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateImagesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromVertex(apiResponse);\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateImagesParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateImagesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromMldev(apiResponse);\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async editImageInternal(\n params: _internal_types.EditImageParametersInternal,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.editImageParametersInternalToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EditImageResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.editImageResponseFromVertex(apiResponse);\n const typedResp = new types.EditImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n private async upscaleImageInternal(\n params: _internal_types.UpscaleImageAPIParametersInternal,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.upscaleImageAPIParametersInternalToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.UpscaleImageResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.upscaleImageResponseFromVertex(apiResponse);\n const typedResp = new types.UpscaleImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Recontextualizes an image.\n *\n * There are two types of recontextualization currently supported:\n * 1) Imagen Product Recontext - Generate images of products in new scenes\n * and contexts.\n * 2) Virtual Try-On: Generate images of persons modeling fashion products.\n *\n * @param params - The parameters for recontextualizing an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response1 = await ai.models.recontextImage({\n * model: 'imagen-product-recontext-preview-06-30',\n * source: {\n * prompt: 'In a modern kitchen setting.',\n * productImages: [productImage],\n * },\n * config: {\n * numberOfImages: 1,\n * },\n * });\n * console.log(response1?.generatedImages?.[0]?.image?.imageBytes);\n *\n * const response2 = await ai.models.recontextImage({\n * model: 'virtual-try-on-preview-08-04',\n * source: {\n * personImage: personImage,\n * productImages: [productImage],\n * },\n * config: {\n * numberOfImages: 1,\n * },\n * });\n * console.log(response2?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n async recontextImage(\n params: types.RecontextImageParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.recontextImageParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.recontextImageResponseFromVertex(apiResponse);\n const typedResp = new types.RecontextImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Segments an image, creating a mask of a specified area.\n *\n * @param params - The parameters for segmenting an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.segmentImage({\n * model: 'image-segmentation-001',\n * source: {\n * image: image,\n * },\n * config: {\n * mode: 'foreground',\n * },\n * });\n * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes);\n * ```\n */\n async segmentImage(\n params: types.SegmentImageParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.segmentImageParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.segmentImageResponseFromVertex(apiResponse);\n const typedResp = new types.SegmentImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Fetches information about a model by name.\n *\n * @example\n * ```ts\n * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'});\n * ```\n */\n async get(params: types.GetModelParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromVertex(apiResponse);\n\n return resp as types.Model;\n });\n } else {\n const body = converters.getModelParametersToMldev(this.apiClient, params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromMldev(apiResponse);\n\n return resp as types.Model;\n });\n }\n }\n\n private async listInternal(\n params: types.ListModelsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listModelsParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{models_url}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListModelsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listModelsResponseFromVertex(apiResponse);\n const typedResp = new types.ListModelsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listModelsParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{models_url}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListModelsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listModelsResponseFromMldev(apiResponse);\n const typedResp = new types.ListModelsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates a tuned model by its name.\n *\n * @param params - The parameters for updating the model.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.update({\n * model: 'tuned-model-name',\n * config: {\n * displayName: 'New display name',\n * description: 'New description',\n * },\n * });\n * ```\n */\n async update(params: types.UpdateModelParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromVertex(apiResponse);\n\n return resp as types.Model;\n });\n } else {\n const body = converters.updateModelParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromMldev(apiResponse);\n\n return resp as types.Model;\n });\n }\n }\n\n /**\n * Deletes a tuned model by its name.\n *\n * @param params - The parameters for deleting the model.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.delete({model: 'tuned-model-name'});\n * ```\n */\n async delete(\n params: types.DeleteModelParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteModelResponseFromVertex();\n const typedResp = new types.DeleteModelResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteModelParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteModelResponseFromMldev();\n const typedResp = new types.DeleteModelResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Counts the number of tokens in the given contents. Multimodal input is\n * supported for Gemini models.\n *\n * @param params - The parameters for counting tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.countTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'The quick brown fox jumps over the lazy dog.'\n * });\n * console.log(response);\n * ```\n */\n async countTokens(\n params: types.CountTokensParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.countTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.CountTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromVertex(apiResponse);\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.countTokensParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.CountTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromMldev(apiResponse);\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Given a list of contents, returns a corresponding TokensInfo containing\n * the list of tokens and list of token ids.\n *\n * This method is not supported by the Gemini Developer API.\n *\n * @param params - The parameters for computing tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.computeTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'What is your name?'\n * });\n * console.log(response);\n * ```\n */\n async computeTokens(\n params: types.ComputeTokensParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.computeTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:computeTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ComputeTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.computeTokensResponseFromVertex(apiResponse);\n const typedResp = new types.ComputeTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Generates videos based on a text description and configuration.\n *\n * @param params - The parameters for generating videos.\n * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method.\n *\n * @example\n * ```ts\n * const operation = await ai.models.generateVideos({\n * model: 'veo-2.0-generate-001',\n * prompt: 'A neon hologram of a cat driving at top speed',\n * config: {\n * numberOfVideos: 1\n * });\n *\n * while (!operation.done) {\n * await new Promise(resolve => setTimeout(resolve, 10000));\n * operation = await ai.operations.getVideosOperation({operation: operation});\n * }\n *\n * console.log(operation.response?.generatedVideos?.[0]?.video?.uri);\n * ```\n */\n\n private async generateVideosInternal(\n params: types.GenerateVideosParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateVideosParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromVertex(apiResponse);\n const typedResp = new types.GenerateVideosOperation();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateVideosParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromMldev(apiResponse);\n const typedResp = new types.GenerateVideosOperation();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as types from '../types.js';\n\nexport function getOperationParametersToMldev(\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getOperationParametersToVertex(\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fetchPredictOperationParametersToVertex(\n fromObject: types.FetchPredictOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(toObject, ['operationName'], fromOperationName);\n }\n\n const fromResourceName = common.getValueByPath(fromObject, ['resourceName']);\n if (fromResourceName != null) {\n common.setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_operations_converters.js';\nimport * as types from './types.js';\n\nexport class Operations extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param parameters The parameters for the get operation request.\n * @return The updated Operation object, with the latest status or result.\n */\n async getVideosOperation(\n parameters: types.OperationGetParameters<\n types.GenerateVideosResponse,\n types.GenerateVideosOperation\n >,\n ): Promise {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n let httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n const rawOperation = await this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: true,\n });\n } else {\n const rawOperation = await this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: false,\n });\n }\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param parameters The parameters for the get operation request.\n * @return The updated Operation object, with the latest status or result.\n */\n async get>(\n parameters: types.OperationGetParameters,\n ): Promise> {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n let httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n const rawOperation = await this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: true,\n });\n } else {\n const rawOperation = await this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: false,\n });\n }\n }\n\n private async getVideosOperationInternal(\n params: types.GetOperationParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getOperationParametersToVertex(params);\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n } else {\n const body = converters.getOperationParametersToMldev(params);\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n }\n }\n\n private async fetchPredictVideosOperationInternal(\n params: types.FetchPredictOperationParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.fetchPredictOperationParametersToVertex(params);\n path = common.formatMap(\n '{resourceName}:fetchPredictOperation',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToMldev(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n if (common.getValueByPath(fromObject, ['transparent']) !== undefined) {\n throw new Error('transparent parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToMldev(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToMldev(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToMldev(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToMldev(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToMldev(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToMldev(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToMldev(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToMldev(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToMldev(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectConstraintsToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectConstraints,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateAuthTokenConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromNewSessionExpireTime = common.getValueByPath(fromObject, [\n 'newSessionExpireTime',\n ]);\n if (parentObject !== undefined && fromNewSessionExpireTime != null) {\n common.setValueByPath(\n parentObject,\n ['newSessionExpireTime'],\n fromNewSessionExpireTime,\n );\n }\n\n const fromUses = common.getValueByPath(fromObject, ['uses']);\n if (parentObject !== undefined && fromUses != null) {\n common.setValueByPath(parentObject, ['uses'], fromUses);\n }\n\n const fromLiveConnectConstraints = common.getValueByPath(fromObject, [\n 'liveConnectConstraints',\n ]);\n if (parentObject !== undefined && fromLiveConnectConstraints != null) {\n common.setValueByPath(\n parentObject,\n ['bidiGenerateContentSetup'],\n liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints),\n );\n }\n\n const fromLockAdditionalFields = common.getValueByPath(fromObject, [\n 'lockAdditionalFields',\n ]);\n if (parentObject !== undefined && fromLockAdditionalFields != null) {\n common.setValueByPath(\n parentObject,\n ['fieldMask'],\n fromLockAdditionalFields,\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateAuthTokenParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createAuthTokenConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenParametersToVertex(\n fromObject: types.CreateAuthTokenParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['config']) !== undefined) {\n throw new Error('config parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function authTokenFromMldev(\n fromObject: types.AuthToken,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function authTokenFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_tokens_converters.js';\nimport * as types from './types.js';\n\n/**\n * Returns a comma-separated list of field masks from a given object.\n *\n * @param setup The object to extract field masks from.\n * @return A comma-separated list of field masks.\n */\nfunction getFieldMasks(setup: Record): string {\n const fields: string[] = [];\n\n for (const key in setup) {\n if (Object.prototype.hasOwnProperty.call(setup, key)) {\n const value = setup[key];\n // 2nd layer, recursively get field masks see TODO(b/418290100)\n if (\n typeof value === 'object' &&\n value != null &&\n Object.keys(value).length > 0\n ) {\n const field = Object.keys(value).map((kk) => `${key}.${kk}`);\n fields.push(...field);\n } else {\n fields.push(key); // 1st layer\n }\n }\n }\n\n return fields.join(',');\n}\n\n/**\n * Converts bidiGenerateContentSetup.\n * @param requestDict - The request dictionary.\n * @param config - The configuration object.\n * @return - The modified request dictionary.\n */\nfunction convertBidiSetupToTokenSetup(\n requestDict: Record,\n config?: {lockAdditionalFields?: string[]},\n): Record {\n // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup.\n let setupForMaskGeneration: Record | null = null;\n const bidiGenerateContentSetupValue = requestDict['bidiGenerateContentSetup'];\n if (\n typeof bidiGenerateContentSetupValue === 'object' &&\n bidiGenerateContentSetupValue !== null &&\n 'setup' in bidiGenerateContentSetupValue\n ) {\n // Now we know bidiGenerateContentSetupValue is an object and has a 'setup'\n // property.\n const innerSetup = (bidiGenerateContentSetupValue as {setup: unknown})\n .setup;\n\n if (typeof innerSetup === 'object' && innerSetup !== null) {\n // Valid inner setup found.\n requestDict['bidiGenerateContentSetup'] = innerSetup;\n setupForMaskGeneration = innerSetup as Record;\n } else {\n // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as\n // if bidiGenerateContentSetup is invalid.\n delete requestDict['bidiGenerateContentSetup'];\n }\n } else if (bidiGenerateContentSetupValue !== undefined) {\n // `bidiGenerateContentSetup` exists but not in the expected\n // shape {setup: {...}}; treat as invalid.\n delete requestDict['bidiGenerateContentSetup'];\n }\n\n const preExistingFieldMask = requestDict['fieldMask'];\n // Handle mask generation setup.\n if (setupForMaskGeneration) {\n const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration);\n\n if (\n Array.isArray(config?.lockAdditionalFields) &&\n config?.lockAdditionalFields.length === 0\n ) {\n // Case 1: lockAdditionalFields is an empty array. Lock only fields from\n // bidi setup.\n if (generatedMaskFromBidi) {\n // Only assign if mask is not empty\n requestDict['fieldMask'] = generatedMaskFromBidi;\n } else {\n delete requestDict['fieldMask']; // If mask is empty, effectively no\n // specific fields locked by bidi\n }\n } else if (\n config?.lockAdditionalFields &&\n config.lockAdditionalFields.length > 0 &&\n preExistingFieldMask !== null &&\n Array.isArray(preExistingFieldMask) &&\n preExistingFieldMask.length > 0\n ) {\n // Case 2: Lock fields from bidi setup + additional fields\n // (preExistingFieldMask).\n\n const generationConfigFields = [\n 'temperature',\n 'topK',\n 'topP',\n 'maxOutputTokens',\n 'responseModalities',\n 'seed',\n 'speechConfig',\n ];\n\n let mappedFieldsFromPreExisting: string[] = [];\n if (preExistingFieldMask.length > 0) {\n mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => {\n if (generationConfigFields.includes(field)) {\n return `generationConfig.${field}`;\n }\n return field; // Keep original field name if not in\n // generationConfigFields\n });\n }\n\n const finalMaskParts: string[] = [];\n if (generatedMaskFromBidi) {\n finalMaskParts.push(generatedMaskFromBidi);\n }\n if (mappedFieldsFromPreExisting.length > 0) {\n finalMaskParts.push(...mappedFieldsFromPreExisting);\n }\n\n if (finalMaskParts.length > 0) {\n requestDict['fieldMask'] = finalMaskParts.join(',');\n } else {\n // If no fields from bidi and no valid additional fields from\n // pre-existing mask.\n delete requestDict['fieldMask'];\n }\n } else {\n // Case 3: \"Lock all fields\" (meaning, don't send a field_mask, let server\n // defaults apply or all are mutable). This is hit if:\n // - `config.lockAdditionalFields` is undefined.\n // - `config.lockAdditionalFields` is non-empty, BUT\n // `preExistingFieldMask` is null, not a string, or an empty string.\n delete requestDict['fieldMask'];\n }\n } else {\n // No valid `bidiGenerateContentSetup` was found or extracted.\n // \"Lock additional null fields if any\".\n if (\n preExistingFieldMask !== null &&\n Array.isArray(preExistingFieldMask) &&\n preExistingFieldMask.length > 0\n ) {\n // If there's a pre-existing field mask, it's a string, and it's not\n // empty, then we should lock all fields.\n requestDict['fieldMask'] = preExistingFieldMask.join(',');\n } else {\n delete requestDict['fieldMask'];\n }\n }\n\n return requestDict;\n}\n\nexport class Tokens extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n /**\n * Creates an ephemeral auth token resource.\n *\n * @experimental\n *\n * @remarks\n * Ephemeral auth tokens is only supported in the Gemini Developer API.\n * It can be used for the session connection to the Live constrained API.\n * Support in v1alpha only.\n *\n * @param params - The parameters for the create request.\n * @return The created auth token.\n *\n * @example\n * ```ts\n * const ai = new GoogleGenAI({\n * apiKey: token.name,\n * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only.\n * });\n *\n * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig\n * // when using the token in Live API sessions. Each session connection can\n * // use a different configuration.\n * const config: CreateAuthTokenConfig = {\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 2: If LiveEphemeralParameters is set, lock all fields in\n * // LiveConnectConfig when using the token in Live API sessions. For\n * // example, changing `outputAudioTranscription` in the Live API\n * // connection will be ignored by the API.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * }\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is\n * // set, lock LiveConnectConfig with set and additional fields (e.g.\n * // responseModalities, systemInstruction, temperature in this example) when\n * // using the token in Live API sessions.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * },\n * lockAdditionalFields: ['temperature'],\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is\n * // empty array, lock LiveConnectConfig with set fields (e.g.\n * // responseModalities, systemInstruction in this example) when using the\n * // token in Live API sessions.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * },\n * lockAdditionalFields: [],\n * }\n * const token = await ai.tokens.create(config);\n * ```\n */\n\n async create(\n params: types.CreateAuthTokenParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'The client.tokens.create method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createAuthTokenParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'auth_tokens',\n body['_url'] as Record,\n );\n\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const transformedBody = convertBidiSetupToTokenSetup(body, params.config);\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(transformedBody),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.authTokenFromMldev(apiResponse);\n\n return resp as types.AuthToken;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function getTuningJobParametersToMldev(\n fromObject: types.GetTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsConfigToMldev(\n fromObject: types.ListTuningJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsParametersToMldev(\n fromObject: types.ListTuningJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listTuningJobsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function tuningExampleToMldev(\n fromObject: types.TuningExample,\n): Record {\n const toObject: Record = {};\n\n const fromTextInput = common.getValueByPath(fromObject, ['textInput']);\n if (fromTextInput != null) {\n common.setValueByPath(toObject, ['textInput'], fromTextInput);\n }\n\n const fromOutput = common.getValueByPath(fromObject, ['output']);\n if (fromOutput != null) {\n common.setValueByPath(toObject, ['output'], fromOutput);\n }\n\n return toObject;\n}\n\nexport function tuningDatasetToMldev(\n fromObject: types.TuningDataset,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['vertexDatasetResource']) !== undefined\n ) {\n throw new Error(\n 'vertexDatasetResource parameter is not supported in Gemini API.',\n );\n }\n\n const fromExamples = common.getValueByPath(fromObject, ['examples']);\n if (fromExamples != null) {\n let transformedList = fromExamples;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningExampleToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['examples', 'examples'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createTuningJobConfigToMldev(\n fromObject: types.CreateTuningJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['validationDataset']) !== undefined) {\n throw new Error(\n 'validationDataset parameter is not supported in Gemini API.',\n );\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (parentObject !== undefined && fromTunedModelDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['displayName'],\n fromTunedModelDisplayName,\n );\n }\n\n if (common.getValueByPath(fromObject, ['description']) !== undefined) {\n throw new Error('description parameter is not supported in Gemini API.');\n }\n\n const fromEpochCount = common.getValueByPath(fromObject, ['epochCount']);\n if (parentObject !== undefined && fromEpochCount != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'epochCount'],\n fromEpochCount,\n );\n }\n\n const fromLearningRateMultiplier = common.getValueByPath(fromObject, [\n 'learningRateMultiplier',\n ]);\n if (fromLearningRateMultiplier != null) {\n common.setValueByPath(\n toObject,\n ['tuningTask', 'hyperparameters', 'learningRateMultiplier'],\n fromLearningRateMultiplier,\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['exportLastCheckpointOnly']) !==\n undefined\n ) {\n throw new Error(\n 'exportLastCheckpointOnly parameter is not supported in Gemini API.',\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['preTunedModelCheckpointId']) !==\n undefined\n ) {\n throw new Error(\n 'preTunedModelCheckpointId parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['adapterSize']) !== undefined) {\n throw new Error('adapterSize parameter is not supported in Gemini API.');\n }\n\n const fromBatchSize = common.getValueByPath(fromObject, ['batchSize']);\n if (parentObject !== undefined && fromBatchSize != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'batchSize'],\n fromBatchSize,\n );\n }\n\n const fromLearningRate = common.getValueByPath(fromObject, ['learningRate']);\n if (parentObject !== undefined && fromLearningRate != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'learningRate'],\n fromLearningRate,\n );\n }\n\n return toObject;\n}\n\nexport function createTuningJobParametersPrivateToMldev(\n fromObject: types.CreateTuningJobParametersPrivate,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromPreTunedModel = common.getValueByPath(fromObject, [\n 'preTunedModel',\n ]);\n if (fromPreTunedModel != null) {\n common.setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel);\n }\n\n const fromTrainingDataset = common.getValueByPath(fromObject, [\n 'trainingDataset',\n ]);\n if (fromTrainingDataset != null) {\n common.setValueByPath(\n toObject,\n ['tuningTask', 'trainingData'],\n tuningDatasetToMldev(fromTrainingDataset),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createTuningJobConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getTuningJobParametersToVertex(\n fromObject: types.GetTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsConfigToVertex(\n fromObject: types.ListTuningJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsParametersToVertex(\n fromObject: types.ListTuningJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listTuningJobsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function tuningDatasetToVertex(\n fromObject: types.TuningDataset,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (parentObject !== undefined && fromGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromGcsUri,\n );\n }\n\n const fromVertexDatasetResource = common.getValueByPath(fromObject, [\n 'vertexDatasetResource',\n ]);\n if (parentObject !== undefined && fromVertexDatasetResource != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromVertexDatasetResource,\n );\n }\n\n if (common.getValueByPath(fromObject, ['examples']) !== undefined) {\n throw new Error('examples parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function tuningValidationDatasetToVertex(\n fromObject: types.TuningValidationDataset,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['validationDatasetUri'], fromGcsUri);\n }\n\n const fromVertexDatasetResource = common.getValueByPath(fromObject, [\n 'vertexDatasetResource',\n ]);\n if (parentObject !== undefined && fromVertexDatasetResource != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromVertexDatasetResource,\n );\n }\n\n return toObject;\n}\n\nexport function createTuningJobConfigToVertex(\n fromObject: types.CreateTuningJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromValidationDataset = common.getValueByPath(fromObject, [\n 'validationDataset',\n ]);\n if (parentObject !== undefined && fromValidationDataset != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec'],\n tuningValidationDatasetToVertex(fromValidationDataset, toObject),\n );\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (parentObject !== undefined && fromTunedModelDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromEpochCount = common.getValueByPath(fromObject, ['epochCount']);\n if (parentObject !== undefined && fromEpochCount != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'epochCount'],\n fromEpochCount,\n );\n }\n\n const fromLearningRateMultiplier = common.getValueByPath(fromObject, [\n 'learningRateMultiplier',\n ]);\n if (parentObject !== undefined && fromLearningRateMultiplier != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'],\n fromLearningRateMultiplier,\n );\n }\n\n const fromExportLastCheckpointOnly = common.getValueByPath(fromObject, [\n 'exportLastCheckpointOnly',\n ]);\n if (parentObject !== undefined && fromExportLastCheckpointOnly != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'exportLastCheckpointOnly'],\n fromExportLastCheckpointOnly,\n );\n }\n\n const fromPreTunedModelCheckpointId = common.getValueByPath(fromObject, [\n 'preTunedModelCheckpointId',\n ]);\n if (fromPreTunedModelCheckpointId != null) {\n common.setValueByPath(\n toObject,\n ['preTunedModel', 'checkpointId'],\n fromPreTunedModelCheckpointId,\n );\n }\n\n const fromAdapterSize = common.getValueByPath(fromObject, ['adapterSize']);\n if (parentObject !== undefined && fromAdapterSize != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'],\n fromAdapterSize,\n );\n }\n\n if (common.getValueByPath(fromObject, ['batchSize']) !== undefined) {\n throw new Error('batchSize parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['learningRate']) !== undefined) {\n throw new Error('learningRate parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function createTuningJobParametersPrivateToVertex(\n fromObject: types.CreateTuningJobParametersPrivate,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromPreTunedModel = common.getValueByPath(fromObject, [\n 'preTunedModel',\n ]);\n if (fromPreTunedModel != null) {\n common.setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel);\n }\n\n const fromTrainingDataset = common.getValueByPath(fromObject, [\n 'trainingDataset',\n ]);\n if (fromTrainingDataset != null) {\n common.setValueByPath(\n toObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n tuningDatasetToVertex(fromTrainingDataset, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createTuningJobConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function tunedModelFromMldev(\n fromObject: types.TunedModel,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['name']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['name']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n return toObject;\n}\n\nexport function tuningJobFromMldev(\n fromObject: types.TuningJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tTuningJobStatus(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, [\n 'tuningTask',\n 'startTime',\n ]);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, [\n 'tuningTask',\n 'completeTime',\n ]);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTunedModel = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModel != null) {\n common.setValueByPath(\n toObject,\n ['tunedModel'],\n tunedModelFromMldev(fromTunedModel),\n );\n }\n\n const fromCustomBaseModel = common.getValueByPath(fromObject, [\n 'customBaseModel',\n ]);\n if (fromCustomBaseModel != null) {\n common.setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel);\n }\n\n const fromExperiment = common.getValueByPath(fromObject, ['experiment']);\n if (fromExperiment != null) {\n common.setValueByPath(toObject, ['experiment'], fromExperiment);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromOutputUri = common.getValueByPath(fromObject, ['outputUri']);\n if (fromOutputUri != null) {\n common.setValueByPath(toObject, ['outputUri'], fromOutputUri);\n }\n\n const fromPipelineJob = common.getValueByPath(fromObject, ['pipelineJob']);\n if (fromPipelineJob != null) {\n common.setValueByPath(toObject, ['pipelineJob'], fromPipelineJob);\n }\n\n const fromServiceAccount = common.getValueByPath(fromObject, [\n 'serviceAccount',\n ]);\n if (fromServiceAccount != null) {\n common.setValueByPath(toObject, ['serviceAccount'], fromServiceAccount);\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (fromTunedModelDisplayName != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n return toObject;\n}\n\nexport function listTuningJobsResponseFromMldev(\n fromObject: types.ListTuningJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromTuningJobs = common.getValueByPath(fromObject, ['tunedModels']);\n if (fromTuningJobs != null) {\n let transformedList = fromTuningJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningJobFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['tuningJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function tuningOperationFromMldev(\n fromObject: types.TuningOperation,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n return toObject;\n}\n\nexport function tunedModelCheckpointFromVertex(\n fromObject: types.TunedModelCheckpoint,\n): Record {\n const toObject: Record = {};\n\n const fromCheckpointId = common.getValueByPath(fromObject, ['checkpointId']);\n if (fromCheckpointId != null) {\n common.setValueByPath(toObject, ['checkpointId'], fromCheckpointId);\n }\n\n const fromEpoch = common.getValueByPath(fromObject, ['epoch']);\n if (fromEpoch != null) {\n common.setValueByPath(toObject, ['epoch'], fromEpoch);\n }\n\n const fromStep = common.getValueByPath(fromObject, ['step']);\n if (fromStep != null) {\n common.setValueByPath(toObject, ['step'], fromStep);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['endpoint']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n return toObject;\n}\n\nexport function tunedModelFromVertex(\n fromObject: types.TunedModel,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['endpoint']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n const fromCheckpoints = common.getValueByPath(fromObject, ['checkpoints']);\n if (fromCheckpoints != null) {\n let transformedList = fromCheckpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tunedModelCheckpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['checkpoints'], transformedList);\n }\n\n return toObject;\n}\n\nexport function tuningJobFromVertex(\n fromObject: types.TuningJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tTuningJobStatus(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTunedModel = common.getValueByPath(fromObject, ['tunedModel']);\n if (fromTunedModel != null) {\n common.setValueByPath(\n toObject,\n ['tunedModel'],\n tunedModelFromVertex(fromTunedModel),\n );\n }\n\n const fromPreTunedModel = common.getValueByPath(fromObject, [\n 'preTunedModel',\n ]);\n if (fromPreTunedModel != null) {\n common.setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel);\n }\n\n const fromSupervisedTuningSpec = common.getValueByPath(fromObject, [\n 'supervisedTuningSpec',\n ]);\n if (fromSupervisedTuningSpec != null) {\n common.setValueByPath(\n toObject,\n ['supervisedTuningSpec'],\n fromSupervisedTuningSpec,\n );\n }\n\n const fromTuningDataStats = common.getValueByPath(fromObject, [\n 'tuningDataStats',\n ]);\n if (fromTuningDataStats != null) {\n common.setValueByPath(toObject, ['tuningDataStats'], fromTuningDataStats);\n }\n\n const fromEncryptionSpec = common.getValueByPath(fromObject, [\n 'encryptionSpec',\n ]);\n if (fromEncryptionSpec != null) {\n common.setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec);\n }\n\n const fromPartnerModelTuningSpec = common.getValueByPath(fromObject, [\n 'partnerModelTuningSpec',\n ]);\n if (fromPartnerModelTuningSpec != null) {\n common.setValueByPath(\n toObject,\n ['partnerModelTuningSpec'],\n fromPartnerModelTuningSpec,\n );\n }\n\n const fromCustomBaseModel = common.getValueByPath(fromObject, [\n 'customBaseModel',\n ]);\n if (fromCustomBaseModel != null) {\n common.setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel);\n }\n\n const fromExperiment = common.getValueByPath(fromObject, ['experiment']);\n if (fromExperiment != null) {\n common.setValueByPath(toObject, ['experiment'], fromExperiment);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromOutputUri = common.getValueByPath(fromObject, ['outputUri']);\n if (fromOutputUri != null) {\n common.setValueByPath(toObject, ['outputUri'], fromOutputUri);\n }\n\n const fromPipelineJob = common.getValueByPath(fromObject, ['pipelineJob']);\n if (fromPipelineJob != null) {\n common.setValueByPath(toObject, ['pipelineJob'], fromPipelineJob);\n }\n\n const fromServiceAccount = common.getValueByPath(fromObject, [\n 'serviceAccount',\n ]);\n if (fromServiceAccount != null) {\n common.setValueByPath(toObject, ['serviceAccount'], fromServiceAccount);\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (fromTunedModelDisplayName != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n return toObject;\n}\n\nexport function listTuningJobsResponseFromVertex(\n fromObject: types.ListTuningJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromTuningJobs = common.getValueByPath(fromObject, ['tuningJobs']);\n if (fromTuningJobs != null) {\n let transformedList = fromTuningJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningJobFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['tuningJobs'], transformedList);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_tunings_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Tunings extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets a TuningJob.\n *\n * @param name - The resource name of the tuning job.\n * @return - A TuningJob object.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n get = async (\n params: types.GetTuningJobParameters,\n ): Promise => {\n return await this.getInternal(params);\n };\n\n /**\n * Lists tuning jobs.\n *\n * @param config - The configuration for the list request.\n * @return - A list of tuning jobs.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n list = async (\n params: types.ListTuningJobsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_TUNING_JOBS,\n (x: types.ListTuningJobsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a supervised fine-tuning job.\n *\n * @param params - The parameters for the tuning job.\n * @return - A TuningJob operation.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n tune = async (\n params: types.CreateTuningJobParameters,\n ): Promise => {\n if (this.apiClient.isVertexAI()) {\n if (params.baseModel.startsWith('projects/')) {\n const preTunedModel: types.PreTunedModel = {\n tunedModelName: params.baseModel,\n };\n const paramsPrivate: types.CreateTuningJobParametersPrivate = {\n ...params,\n preTunedModel: preTunedModel,\n };\n paramsPrivate.baseModel = undefined;\n return await this.tuneInternal(paramsPrivate);\n } else {\n const paramsPrivate: types.CreateTuningJobParametersPrivate = {\n ...params,\n };\n return await this.tuneInternal(paramsPrivate);\n }\n } else {\n const paramsPrivate: types.CreateTuningJobParametersPrivate = {\n ...params,\n };\n const operation = await this.tuneMldevInternal(paramsPrivate);\n let tunedModelName = '';\n if (\n operation['metadata'] !== undefined &&\n operation['metadata']['tunedModel'] !== undefined\n ) {\n tunedModelName = operation['metadata']['tunedModel'] as string;\n } else if (\n operation['name'] !== undefined &&\n operation['name'].includes('/operations/')\n ) {\n tunedModelName = operation['name'].split('/operations/')[0];\n }\n const tuningJob: types.TuningJob = {\n name: tunedModelName,\n state: types.JobState.JOB_STATE_QUEUED,\n };\n\n return tuningJob;\n }\n };\n\n private async getInternal(\n params: types.GetTuningJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getTuningJobParametersToVertex(params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromVertex(apiResponse);\n\n return resp as types.TuningJob;\n });\n } else {\n const body = converters.getTuningJobParametersToMldev(params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromMldev(apiResponse);\n\n return resp as types.TuningJob;\n });\n }\n }\n\n private async listInternal(\n params: types.ListTuningJobsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listTuningJobsParametersToVertex(params);\n path = common.formatMap(\n 'tuningJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListTuningJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listTuningJobsResponseFromVertex(apiResponse);\n const typedResp = new types.ListTuningJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listTuningJobsParametersToMldev(params);\n path = common.formatMap(\n 'tunedModels',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListTuningJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listTuningJobsResponseFromMldev(apiResponse);\n const typedResp = new types.ListTuningJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async tuneInternal(\n params: types.CreateTuningJobParametersPrivate,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createTuningJobParametersPrivateToVertex(params);\n path = common.formatMap(\n 'tuningJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromVertex(apiResponse);\n\n return resp as types.TuningJob;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n private async tuneMldevInternal(\n params: types.CreateTuningJobParametersPrivate,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createTuningJobParametersPrivateToMldev(params);\n path = common.formatMap(\n 'tunedModels',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningOperation;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningOperationFromMldev(apiResponse);\n\n return resp as types.TuningOperation;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from '../_auth.js';\n\nexport const GOOGLE_API_KEY_HEADER = 'x-goog-api-key';\n// TODO(b/395122533): We need a secure client side authentication mechanism.\nexport class WebAuth implements Auth {\n constructor(private readonly apiKey: string) {}\n\n async addAuthHeaders(headers: Headers): Promise {\n if (headers.get(GOOGLE_API_KEY_HEADER) !== null) {\n return;\n }\n\n if (this.apiKey.startsWith('auth_tokens/')) {\n throw new Error('Ephemeral tokens are only supported by the live API.');\n }\n\n // Check if API key is empty or null\n if (!this.apiKey) {\n throw new Error('API key is missing. Please provide a valid API key.');\n }\n headers.append(GOOGLE_API_KEY_HEADER, this.apiKey);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {GoogleAuthOptions} from 'google-auth-library';\n\nimport {ApiClient} from './_api_client.js';\nimport {Batches} from './batches.js';\nimport {Caches} from './caches.js';\nimport {Chats} from './chats.js';\nimport {CrossDownloader} from './cross/_cross_downloader.js';\nimport {crossError} from './cross/_cross_error.js';\nimport {CrossUploader} from './cross/_cross_uploader.js';\nimport {CrossWebSocketFactory} from './cross/_cross_websocket.js';\nimport {Files} from './files.js';\nimport {Live} from './live.js';\nimport {Models} from './models.js';\nimport {Operations} from './operations.js';\nimport {Tokens} from './tokens.js';\nimport {Tunings} from './tunings.js';\nimport {HttpOptions} from './types.js';\nimport {WebAuth} from './web/_web_auth.js';\n\nconst LANGUAGE_LABEL_PREFIX = 'gl-node/';\n\n/**\n * Google Gen AI SDK's configuration options.\n *\n * See {@link GoogleGenAI} for usage samples.\n */\nexport interface GoogleGenAIOptions {\n /**\n * Optional. Determines whether to use the Vertex AI or the Gemini API.\n *\n * @remarks\n * When true, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API} will used.\n * When false, the {@link https://ai.google.dev/api | Gemini API} will be used.\n *\n * If unset, default SDK behavior is to use the Gemini API service.\n */\n vertexai?: boolean;\n /**\n * Optional. The Google Cloud project ID for Vertex AI clients.\n *\n * Find your project ID: https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects\n *\n * @remarks\n * Only supported on Node runtimes, ignored on browser runtimes.\n */\n project?: string;\n /**\n * Optional. The Google Cloud project {@link https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations | location} for Vertex AI clients.\n *\n * @remarks\n * Only supported on Node runtimes, ignored on browser runtimes.\n *\n */\n location?: string;\n /**\n * The API Key, required for Gemini API clients.\n *\n * @remarks\n * Required on browser runtimes.\n */\n apiKey?: string;\n /**\n * Optional. The API version to use.\n *\n * @remarks\n * If unset, the default API version will be used.\n */\n apiVersion?: string;\n /**\n * Optional. Authentication options defined by the by google-auth-library for Vertex AI clients.\n *\n * @remarks\n * @see {@link https://github.com/googleapis/google-auth-library-nodejs/blob/v9.15.0/src/auth/googleauth.ts | GoogleAuthOptions interface in google-auth-library-nodejs}.\n *\n * Only supported on Node runtimes, ignored on browser runtimes.\n *\n */\n googleAuthOptions?: GoogleAuthOptions;\n /**\n * Optional. A set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n}\n\n/**\n * The Google GenAI SDK.\n *\n * @remarks\n * Provides access to the GenAI features through either the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API}\n * or the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API}.\n *\n * The {@link GoogleGenAIOptions.vertexai} value determines which of the API services to use.\n *\n * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be set,\n * when using Vertex AI {@link GoogleGenAIOptions.project} and {@link GoogleGenAIOptions.location} must also be set.\n *\n * @example\n * Initializing the SDK for using the Gemini API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n *\n * @example\n * Initializing the SDK for using the Vertex AI API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({\n * vertexai: true,\n * project: 'PROJECT_ID',\n * location: 'PROJECT_LOCATION'\n * });\n * ```\n *\n */\nexport class GoogleGenAI {\n protected readonly apiClient: ApiClient;\n private readonly apiKey?: string;\n public readonly vertexai: boolean;\n private readonly apiVersion?: string;\n readonly models: Models;\n readonly live: Live;\n readonly batches: Batches;\n readonly chats: Chats;\n readonly caches: Caches;\n readonly files: Files;\n readonly operations: Operations;\n readonly authTokens: Tokens;\n readonly tunings: Tunings;\n\n constructor(options: GoogleGenAIOptions) {\n if (options.apiKey == null) {\n throw new Error(\n `An API Key must be set when running in an unspecified environment.\\n + ${crossError().message}`,\n );\n }\n this.vertexai = options.vertexai ?? false;\n this.apiKey = options.apiKey;\n this.apiVersion = options.apiVersion;\n const auth = new WebAuth(this.apiKey);\n this.apiClient = new ApiClient({\n auth: auth,\n apiVersion: this.apiVersion,\n apiKey: this.apiKey,\n vertexai: this.vertexai,\n httpOptions: options.httpOptions,\n userAgentExtra: LANGUAGE_LABEL_PREFIX + 'cross',\n uploader: new CrossUploader(),\n downloader: new CrossDownloader(),\n });\n this.models = new Models(this.apiClient);\n this.live = new Live(this.apiClient, auth, new CrossWebSocketFactory());\n this.chats = new Chats(this.models, this.apiClient);\n this.batches = new Batches(this.apiClient);\n this.caches = new Caches(this.apiClient);\n this.files = new Files(this.apiClient);\n this.operations = new Operations(this.apiClient);\n this.authTokens = new Tokens(this.apiClient);\n this.tunings = new Tunings(this.apiClient);\n }\n}\n"],"names":["tBytes","types.Type","baseTransformers.tBytes","videoMetadataToMldev","common.getValueByPath","common.setValueByPath","blobToMldev","fileDataToMldev","partToMldev","contentToMldev","schemaToMldev","safetySettingToMldev","functionDeclarationToMldev","intervalToMldev","googleSearchToMldev","dynamicRetrievalConfigToMldev","googleSearchRetrievalToMldev","urlContextToMldev","toolComputerUseToMldev","toolToMldev","functionCallingConfigToMldev","latLngToMldev","retrievalConfigToMldev","toolConfigToMldev","prebuiltVoiceConfigToMldev","voiceConfigToMldev","speakerVoiceConfigToMldev","multiSpeakerVoiceConfigToMldev","speechConfigToMldev","thinkingConfigToMldev","generateContentConfigToMldev","t.tContent","t.tSchema","t.tTools","t.tTool","t.tCachedContentName","t.tSpeechConfig","t.tModel","t.tContents","t.tBatchJobSource","t.tBatchJobName","t.tBatchJobDestination","videoMetadataFromMldev","blobFromMldev","fileDataFromMldev","partFromMldev","contentFromMldev","citationMetadataFromMldev","urlMetadataFromMldev","urlContextMetadataFromMldev","candidateFromMldev","generateContentResponseFromMldev","t.tJobState","converters.createBatchJobParametersToMldev","common.formatMap","converters.batchJobFromMldev","converters.createBatchJobParametersToVertex","converters.batchJobFromVertex","converters.getBatchJobParametersToVertex","converters.getBatchJobParametersToMldev","converters.cancelBatchJobParametersToVertex","converters.cancelBatchJobParametersToMldev","converters.listBatchJobsParametersToVertex","converters.listBatchJobsResponseFromVertex","types.ListBatchJobsResponse","converters.listBatchJobsParametersToMldev","converters.listBatchJobsResponseFromMldev","converters.deleteBatchJobParametersToVertex","converters.deleteResourceJobFromVertex","converters.deleteBatchJobParametersToMldev","converters.deleteResourceJobFromMldev","t.tCachesModel","videoMetadataToVertex","blobToVertex","fileDataToVertex","partToVertex","contentToVertex","functionDeclarationToVertex","intervalToVertex","googleSearchToVertex","dynamicRetrievalConfigToVertex","googleSearchRetrievalToVertex","enterpriseWebSearchToVertex","apiKeyConfigToVertex","authConfigToVertex","googleMapsToVertex","urlContextToVertex","toolComputerUseToVertex","toolToVertex","functionCallingConfigToVertex","latLngToVertex","retrievalConfigToVertex","toolConfigToVertex","converters.createCachedContentParametersToVertex","converters.cachedContentFromVertex","converters.createCachedContentParametersToMldev","converters.cachedContentFromMldev","converters.getCachedContentParametersToVertex","converters.getCachedContentParametersToMldev","converters.deleteCachedContentParametersToVertex","converters.deleteCachedContentResponseFromVertex","types.DeleteCachedContentResponse","converters.deleteCachedContentParametersToMldev","converters.deleteCachedContentResponseFromMldev","converters.updateCachedContentParametersToVertex","converters.updateCachedContentParametersToMldev","converters.listCachedContentsParametersToVertex","converters.listCachedContentsResponseFromVertex","types.ListCachedContentsResponse","converters.listCachedContentsParametersToMldev","converters.listCachedContentsResponseFromMldev","t.tFileName","converters.fileFromMldev","converters.listFilesParametersToMldev","converters.listFilesResponseFromMldev","types.ListFilesResponse","converters.createFileParametersToMldev","converters.createFileResponseFromMldev","types.CreateFileResponse","converters.getFileParametersToMldev","converters.deleteFileParametersToMldev","converters.deleteFileResponseFromMldev","types.DeleteFileResponse","sessionResumptionConfigToMldev","audioTranscriptionConfigToMldev","automaticActivityDetectionToMldev","realtimeInputConfigToMldev","slidingWindowToMldev","contextWindowCompressionConfigToMldev","proactivityConfigToMldev","liveConnectConfigToMldev","t.tLiveSpeechConfig","t.tBlobs","t.tAudioBlob","t.tImageBlob","prebuiltVoiceConfigToVertex","voiceConfigToVertex","speechConfigToVertex","videoMetadataFromVertex","blobFromVertex","fileDataFromVertex","partFromVertex","contentFromVertex","t.tContentsForEmbed","t.tModelsUrl","t.tBytes","t.tExtractModels","handleWebSocketMessage","types.LiveMusicServerMessage","converters.liveMusicServerMessageFromMldev","mapToHeaders","headersToMap","converters.liveMusicClientSetupToMldev","converters.liveMusicClientMessageToMldev","converters.liveMusicSetWeightedPromptsParametersToMldev","converters.liveMusicClientContentToMldev","converters.liveMusicSetConfigParametersToMldev","types.LiveMusicPlaybackControl","types.LiveServerMessage","converters.liveServerMessageFromVertex","converters.liveServerMessageFromMldev","types.Modality","converters.liveConnectParametersToVertex","converters.liveConnectParametersToMldev","converters.liveSendRealtimeInputParametersToVertex","converters.liveSendRealtimeInputParametersToMldev","types.GenerateContentResponse","converters.generateContentParametersToVertex","converters.generateContentResponseFromVertex","converters.generateContentParametersToMldev","converters.generateContentResponseFromMldev","converters.embedContentParametersToVertex","converters.embedContentResponseFromVertex","types.EmbedContentResponse","converters.embedContentParametersToMldev","converters.embedContentResponseFromMldev","converters.generateImagesParametersToVertex","converters.generateImagesResponseFromVertex","types.GenerateImagesResponse","converters.generateImagesParametersToMldev","converters.generateImagesResponseFromMldev","converters.editImageParametersInternalToVertex","converters.editImageResponseFromVertex","types.EditImageResponse","converters.upscaleImageAPIParametersInternalToVertex","converters.upscaleImageResponseFromVertex","types.UpscaleImageResponse","converters.recontextImageParametersToVertex","converters.recontextImageResponseFromVertex","types.RecontextImageResponse","converters.segmentImageParametersToVertex","converters.segmentImageResponseFromVertex","types.SegmentImageResponse","converters.getModelParametersToVertex","converters.modelFromVertex","converters.getModelParametersToMldev","converters.modelFromMldev","converters.listModelsParametersToVertex","converters.listModelsResponseFromVertex","types.ListModelsResponse","converters.listModelsParametersToMldev","converters.listModelsResponseFromMldev","converters.updateModelParametersToVertex","converters.updateModelParametersToMldev","converters.deleteModelParametersToVertex","converters.deleteModelResponseFromVertex","types.DeleteModelResponse","converters.deleteModelParametersToMldev","converters.deleteModelResponseFromMldev","converters.countTokensParametersToVertex","converters.countTokensResponseFromVertex","types.CountTokensResponse","converters.countTokensParametersToMldev","converters.countTokensResponseFromMldev","converters.computeTokensParametersToVertex","converters.computeTokensResponseFromVertex","types.ComputeTokensResponse","converters.generateVideosParametersToVertex","converters.generateVideosOperationFromVertex","types.GenerateVideosOperation","converters.generateVideosParametersToMldev","converters.generateVideosOperationFromMldev","converters.getOperationParametersToVertex","converters.getOperationParametersToMldev","converters.fetchPredictOperationParametersToVertex","converters.createAuthTokenParametersToMldev","converters.authTokenFromMldev","t.tTuningJobStatus","types.JobState","converters.getTuningJobParametersToVertex","converters.tuningJobFromVertex","converters.getTuningJobParametersToMldev","converters.tuningJobFromMldev","converters.listTuningJobsParametersToVertex","converters.listTuningJobsResponseFromVertex","types.ListTuningJobsResponse","converters.listTuningJobsParametersToMldev","converters.listTuningJobsResponseFromMldev","converters.createTuningJobParametersPrivateToVertex","converters.createTuningJobParametersPrivateToMldev","converters.tuningOperationFromMldev"],"mappings":"AAAA;;;;AAIG;AAeH;;;;;;;;;;;;;;;;;;;AAmBG;AACG,SAAU,kBAAkB,CAAC,aAAgC,EAAA;AACjE,IAAwB,aAAa,CAAC,SAAS;A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AAS,CAAC;;AAE7C;;;;"} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/node/index.cjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/node/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..9eb1972c03d78b0a2031e1a7f33e08e169ad9302 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/node/index.cjs @@ -0,0 +1,19135 @@ +'use strict'; + +var googleAuthLibrary = require('google-auth-library'); +var fs = require('fs'); +var node_stream = require('node:stream'); +var NodeWs = require('ws'); +var fs$1 = require('fs/promises'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var NodeWs__namespace = /*#__PURE__*/_interopNamespaceDefault(NodeWs); +var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs$1); + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +let _defaultBaseGeminiUrl = undefined; +let _defaultBaseVertexUrl = undefined; +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +function setDefaultBaseUrls(baseUrlParams) { + _defaultBaseGeminiUrl = baseUrlParams.geminiUrl; + _defaultBaseVertexUrl = baseUrlParams.vertexUrl; +} +/** + * Returns the default base URLs for the Gemini API and Vertex AI API. + */ +function getDefaultBaseUrls() { + return { + geminiUrl: _defaultBaseGeminiUrl, + vertexUrl: _defaultBaseVertexUrl, + }; +} +/** + * Returns the default base URL based on the following priority: + * 1. Base URLs set via HttpOptions. + * 2. Base URLs set via the latest call to setDefaultBaseUrls. + * 3. Base URLs set via environment variables. + */ +function getBaseUrl(httpOptions, vertexai, vertexBaseUrlFromEnv, geminiBaseUrlFromEnv) { + var _a, _b; + if (!(httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.baseUrl)) { + const defaultBaseUrls = getDefaultBaseUrls(); + if (vertexai) { + return (_a = defaultBaseUrls.vertexUrl) !== null && _a !== void 0 ? _a : vertexBaseUrlFromEnv; + } + else { + return (_b = defaultBaseUrls.geminiUrl) !== null && _b !== void 0 ? _b : geminiBaseUrlFromEnv; + } + } + return httpOptions.baseUrl; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BaseModule { +} +function formatMap(templateString, valueMap) { + // Use a regular expression to find all placeholders in the template string + const regex = /\{([^}]+)\}/g; + // Replace each placeholder with its corresponding value from the valueMap + return templateString.replace(regex, (match, key) => { + if (Object.prototype.hasOwnProperty.call(valueMap, key)) { + const value = valueMap[key]; + // Convert the value to a string if it's not a string already + return value !== undefined && value !== null ? String(value) : ''; + } + else { + // Handle missing keys + throw new Error(`Key '${key}' not found in valueMap.`); + } + }); +} +function setValueByPath(data, keys, value) { + for (let i = 0; i < keys.length - 1; i++) { + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (!(keyName in data)) { + if (Array.isArray(value)) { + data[keyName] = Array.from({ length: value.length }, () => ({})); + } + else { + throw new Error(`Value must be a list given an array path ${key}`); + } + } + if (Array.isArray(data[keyName])) { + const arrayData = data[keyName]; + if (Array.isArray(value)) { + for (let j = 0; j < arrayData.length; j++) { + const entry = arrayData[j]; + setValueByPath(entry, keys.slice(i + 1), value[j]); + } + } + else { + for (const d of arrayData) { + setValueByPath(d, keys.slice(i + 1), value); + } + } + } + return; + } + else if (key.endsWith('[0]')) { + const keyName = key.slice(0, -3); + if (!(keyName in data)) { + data[keyName] = [{}]; + } + const arrayData = data[keyName]; + setValueByPath(arrayData[0], keys.slice(i + 1), value); + return; + } + if (!data[key] || typeof data[key] !== 'object') { + data[key] = {}; + } + data = data[key]; + } + const keyToSet = keys[keys.length - 1]; + const existingData = data[keyToSet]; + if (existingData !== undefined) { + if (!value || + (typeof value === 'object' && Object.keys(value).length === 0)) { + return; + } + if (value === existingData) { + return; + } + if (typeof existingData === 'object' && + typeof value === 'object' && + existingData !== null && + value !== null) { + Object.assign(existingData, value); + } + else { + throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`); + } + } + else { + data[keyToSet] = value; + } +} +function getValueByPath(data, keys) { + try { + if (keys.length === 1 && keys[0] === '_self') { + return data; + } + for (let i = 0; i < keys.length; i++) { + if (typeof data !== 'object' || data === null) { + return undefined; + } + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (keyName in data) { + const arrayData = data[keyName]; + if (!Array.isArray(arrayData)) { + return undefined; + } + return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1))); + } + else { + return undefined; + } + } + else { + data = data[key]; + } + } + return data; + } + catch (error) { + if (error instanceof TypeError) { + return undefined; + } + throw error; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tBytes$1(fromBytes) { + if (typeof fromBytes !== 'string') { + throw new Error('fromImageBytes must be a string'); + } + // TODO(b/389133914): Remove dummy bytes converter. + return fromBytes; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +/** Required. Outcome of the code execution. */ +exports.Outcome = void 0; +(function (Outcome) { + /** + * Unspecified status. This value should not be used. + */ + Outcome["OUTCOME_UNSPECIFIED"] = "OUTCOME_UNSPECIFIED"; + /** + * Code execution completed successfully. + */ + Outcome["OUTCOME_OK"] = "OUTCOME_OK"; + /** + * Code execution finished but with a failure. `stderr` should contain the reason. + */ + Outcome["OUTCOME_FAILED"] = "OUTCOME_FAILED"; + /** + * Code execution ran for too long, and was cancelled. There may or may not be a partial output present. + */ + Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "OUTCOME_DEADLINE_EXCEEDED"; +})(exports.Outcome || (exports.Outcome = {})); +/** Required. Programming language of the `code`. */ +exports.Language = void 0; +(function (Language) { + /** + * Unspecified language. This value should not be used. + */ + Language["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED"; + /** + * Python >= 3.10, with numpy and simpy available. + */ + Language["PYTHON"] = "PYTHON"; +})(exports.Language || (exports.Language = {})); +/** Optional. The type of the data. */ +exports.Type = void 0; +(function (Type) { + /** + * Not specified, should not be used. + */ + Type["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + /** + * OpenAPI string type + */ + Type["STRING"] = "STRING"; + /** + * OpenAPI number type + */ + Type["NUMBER"] = "NUMBER"; + /** + * OpenAPI integer type + */ + Type["INTEGER"] = "INTEGER"; + /** + * OpenAPI boolean type + */ + Type["BOOLEAN"] = "BOOLEAN"; + /** + * OpenAPI array type + */ + Type["ARRAY"] = "ARRAY"; + /** + * OpenAPI object type + */ + Type["OBJECT"] = "OBJECT"; + /** + * Null type + */ + Type["NULL"] = "NULL"; +})(exports.Type || (exports.Type = {})); +/** Required. Harm category. */ +exports.HarmCategory = void 0; +(function (HarmCategory) { + /** + * The harm category is unspecified. + */ + HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + /** + * The harm category is hate speech. + */ + HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + /** + * The harm category is dangerous content. + */ + HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT"; + /** + * The harm category is harassment. + */ + HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + /** + * The harm category is sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY"; + /** + * The harm category is image hate. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE"; + /** + * The harm category is image dangerous content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"; + /** + * The harm category is image harassment. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HARASSMENT"] = "HARM_CATEGORY_IMAGE_HARASSMENT"; + /** + * The harm category is image sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"; +})(exports.HarmCategory || (exports.HarmCategory = {})); +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +exports.HarmBlockMethod = void 0; +(function (HarmBlockMethod) { + /** + * The harm block method is unspecified. + */ + HarmBlockMethod["HARM_BLOCK_METHOD_UNSPECIFIED"] = "HARM_BLOCK_METHOD_UNSPECIFIED"; + /** + * The harm block method uses both probability and severity scores. + */ + HarmBlockMethod["SEVERITY"] = "SEVERITY"; + /** + * The harm block method uses the probability score. + */ + HarmBlockMethod["PROBABILITY"] = "PROBABILITY"; +})(exports.HarmBlockMethod || (exports.HarmBlockMethod = {})); +/** Required. The harm block threshold. */ +exports.HarmBlockThreshold = void 0; +(function (HarmBlockThreshold) { + /** + * Unspecified harm block threshold. + */ + HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + /** + * Block low threshold and above (i.e. block more). + */ + HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + /** + * Block medium threshold and above. + */ + HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + /** + * Block only high threshold (i.e. block less). + */ + HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + /** + * Block none. + */ + HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; + /** + * Turn off the safety filter. + */ + HarmBlockThreshold["OFF"] = "OFF"; +})(exports.HarmBlockThreshold || (exports.HarmBlockThreshold = {})); +/** The mode of the predictor to be used in dynamic retrieval. */ +exports.Mode = void 0; +(function (Mode) { + /** + * Always trigger retrieval. + */ + Mode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + Mode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(exports.Mode || (exports.Mode = {})); +/** Type of auth scheme. */ +exports.AuthType = void 0; +(function (AuthType) { + AuthType["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED"; + /** + * No Auth. + */ + AuthType["NO_AUTH"] = "NO_AUTH"; + /** + * API Key Auth. + */ + AuthType["API_KEY_AUTH"] = "API_KEY_AUTH"; + /** + * HTTP Basic Auth. + */ + AuthType["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH"; + /** + * Google Service Account Auth. + */ + AuthType["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH"; + /** + * OAuth auth. + */ + AuthType["OAUTH"] = "OAUTH"; + /** + * OpenID Connect (OIDC) Auth. + */ + AuthType["OIDC_AUTH"] = "OIDC_AUTH"; +})(exports.AuthType || (exports.AuthType = {})); +/** The API spec that the external API implements. */ +exports.ApiSpec = void 0; +(function (ApiSpec) { + /** + * Unspecified API spec. This value should not be used. + */ + ApiSpec["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED"; + /** + * Simple search API spec. + */ + ApiSpec["SIMPLE_SEARCH"] = "SIMPLE_SEARCH"; + /** + * Elastic search API spec. + */ + ApiSpec["ELASTIC_SEARCH"] = "ELASTIC_SEARCH"; +})(exports.ApiSpec || (exports.ApiSpec = {})); +/** Status of the url retrieval. */ +exports.UrlRetrievalStatus = void 0; +(function (UrlRetrievalStatus) { + /** + * Default value. This value is unused + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = "URL_RETRIEVAL_STATUS_UNSPECIFIED"; + /** + * Url retrieval is successful. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_SUCCESS"] = "URL_RETRIEVAL_STATUS_SUCCESS"; + /** + * Url retrieval is failed due to error. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_ERROR"] = "URL_RETRIEVAL_STATUS_ERROR"; + /** + * Url retrieval is failed because the content is behind paywall. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_PAYWALL"] = "URL_RETRIEVAL_STATUS_PAYWALL"; + /** + * Url retrieval is failed because the content is unsafe. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSAFE"] = "URL_RETRIEVAL_STATUS_UNSAFE"; +})(exports.UrlRetrievalStatus || (exports.UrlRetrievalStatus = {})); +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +exports.FinishReason = void 0; +(function (FinishReason) { + /** + * The finish reason is unspecified. + */ + FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + FinishReason["STOP"] = "STOP"; + /** + * Token generation reached the configured maximum output tokens. + */ + FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + FinishReason["SAFETY"] = "SAFETY"; + /** + * The token generation stopped because of potential recitation. + */ + FinishReason["RECITATION"] = "RECITATION"; + /** + * The token generation stopped because of using an unsupported language. + */ + FinishReason["LANGUAGE"] = "LANGUAGE"; + /** + * All other reasons that stopped the token generation. + */ + FinishReason["OTHER"] = "OTHER"; + /** + * Token generation stopped because the content contains forbidden terms. + */ + FinishReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Token generation stopped for potentially containing prohibited content. + */ + FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). + */ + FinishReason["SPII"] = "SPII"; + /** + * The function call generated by the model is invalid. + */ + FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; + /** + * Token generation stopped because generated images have safety violations. + */ + FinishReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; + /** + * The tool call generated by the model is invalid. + */ + FinishReason["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL"; +})(exports.FinishReason || (exports.FinishReason = {})); +/** Output only. Harm probability levels in the content. */ +exports.HarmProbability = void 0; +(function (HarmProbability) { + /** + * Harm probability unspecified. + */ + HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED"; + /** + * Negligible level of harm. + */ + HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; + /** + * Low level of harm. + */ + HarmProbability["LOW"] = "LOW"; + /** + * Medium level of harm. + */ + HarmProbability["MEDIUM"] = "MEDIUM"; + /** + * High level of harm. + */ + HarmProbability["HIGH"] = "HIGH"; +})(exports.HarmProbability || (exports.HarmProbability = {})); +/** Output only. Harm severity levels in the content. */ +exports.HarmSeverity = void 0; +(function (HarmSeverity) { + /** + * Harm severity unspecified. + */ + HarmSeverity["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED"; + /** + * Negligible level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE"; + /** + * Low level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW"; + /** + * Medium level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM"; + /** + * High level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH"; +})(exports.HarmSeverity || (exports.HarmSeverity = {})); +/** Output only. Blocked reason. */ +exports.BlockedReason = void 0; +(function (BlockedReason) { + /** + * Unspecified blocked reason. + */ + BlockedReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + /** + * Candidates blocked due to safety. + */ + BlockedReason["SAFETY"] = "SAFETY"; + /** + * Candidates blocked due to other reason. + */ + BlockedReason["OTHER"] = "OTHER"; + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BlockedReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Candidates blocked due to prohibited content. + */ + BlockedReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Candidates blocked due to unsafe image generation content. + */ + BlockedReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; +})(exports.BlockedReason || (exports.BlockedReason = {})); +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +exports.TrafficType = void 0; +(function (TrafficType) { + /** + * Unspecified request traffic type. + */ + TrafficType["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED"; + /** + * Type for Pay-As-You-Go traffic. + */ + TrafficType["ON_DEMAND"] = "ON_DEMAND"; + /** + * Type for Provisioned Throughput traffic. + */ + TrafficType["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT"; +})(exports.TrafficType || (exports.TrafficType = {})); +/** Server content modalities. */ +exports.Modality = void 0; +(function (Modality) { + /** + * The modality is unspecified. + */ + Modality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Indicates the model should return text + */ + Modality["TEXT"] = "TEXT"; + /** + * Indicates the model should return images. + */ + Modality["IMAGE"] = "IMAGE"; + /** + * Indicates the model should return audio. + */ + Modality["AUDIO"] = "AUDIO"; +})(exports.Modality || (exports.Modality = {})); +/** The media resolution to use. */ +exports.MediaResolution = void 0; +(function (MediaResolution) { + /** + * Media resolution has not been set + */ + MediaResolution["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED"; + /** + * Media resolution set to low (64 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + /** + * Media resolution set to medium (256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; +})(exports.MediaResolution || (exports.MediaResolution = {})); +/** Job state. */ +exports.JobState = void 0; +(function (JobState) { + /** + * The job state is unspecified. + */ + JobState["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED"; + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JobState["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED"; + /** + * The service is preparing to run the job. + */ + JobState["JOB_STATE_PENDING"] = "JOB_STATE_PENDING"; + /** + * The job is in progress. + */ + JobState["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING"; + /** + * The job completed successfully. + */ + JobState["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED"; + /** + * The job failed. + */ + JobState["JOB_STATE_FAILED"] = "JOB_STATE_FAILED"; + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JobState["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING"; + /** + * The job has been cancelled. + */ + JobState["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED"; + /** + * The job has been stopped, and can be resumed. + */ + JobState["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED"; + /** + * The job has expired. + */ + JobState["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED"; + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JobState["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING"; + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JobState["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED"; +})(exports.JobState || (exports.JobState = {})); +/** Tuning mode. */ +exports.TuningMode = void 0; +(function (TuningMode) { + /** + * Tuning mode is unspecified. + */ + TuningMode["TUNING_MODE_UNSPECIFIED"] = "TUNING_MODE_UNSPECIFIED"; + /** + * Full fine-tuning mode. + */ + TuningMode["TUNING_MODE_FULL"] = "TUNING_MODE_FULL"; + /** + * PEFT adapter tuning mode. + */ + TuningMode["TUNING_MODE_PEFT_ADAPTER"] = "TUNING_MODE_PEFT_ADAPTER"; +})(exports.TuningMode || (exports.TuningMode = {})); +/** Optional. Adapter size for tuning. */ +exports.AdapterSize = void 0; +(function (AdapterSize) { + /** + * Adapter size is unspecified. + */ + AdapterSize["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED"; + /** + * Adapter size 1. + */ + AdapterSize["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE"; + /** + * Adapter size 2. + */ + AdapterSize["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO"; + /** + * Adapter size 4. + */ + AdapterSize["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR"; + /** + * Adapter size 8. + */ + AdapterSize["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT"; + /** + * Adapter size 16. + */ + AdapterSize["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN"; + /** + * Adapter size 32. + */ + AdapterSize["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO"; +})(exports.AdapterSize || (exports.AdapterSize = {})); +/** Options for feature selection preference. */ +exports.FeatureSelectionPreference = void 0; +(function (FeatureSelectionPreference) { + FeatureSelectionPreference["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"; + FeatureSelectionPreference["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY"; + FeatureSelectionPreference["BALANCED"] = "BALANCED"; + FeatureSelectionPreference["PRIORITIZE_COST"] = "PRIORITIZE_COST"; +})(exports.FeatureSelectionPreference || (exports.FeatureSelectionPreference = {})); +/** Defines the function behavior. Defaults to `BLOCKING`. */ +exports.Behavior = void 0; +(function (Behavior) { + /** + * This value is unused. + */ + Behavior["UNSPECIFIED"] = "UNSPECIFIED"; + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + Behavior["BLOCKING"] = "BLOCKING"; + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + Behavior["NON_BLOCKING"] = "NON_BLOCKING"; +})(exports.Behavior || (exports.Behavior = {})); +/** Config for the dynamic retrieval config mode. */ +exports.DynamicRetrievalConfigMode = void 0; +(function (DynamicRetrievalConfigMode) { + /** + * Always trigger retrieval. + */ + DynamicRetrievalConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + DynamicRetrievalConfigMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(exports.DynamicRetrievalConfigMode || (exports.DynamicRetrievalConfigMode = {})); +/** The environment being operated. */ +exports.Environment = void 0; +(function (Environment) { + /** + * Defaults to browser. + */ + Environment["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED"; + /** + * Operates in a web browser. + */ + Environment["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER"; +})(exports.Environment || (exports.Environment = {})); +/** Config for the function calling config mode. */ +exports.FunctionCallingConfigMode = void 0; +(function (FunctionCallingConfigMode) { + /** + * The function calling config mode is unspecified. Should not be used. + */ + FunctionCallingConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + FunctionCallingConfigMode["AUTO"] = "AUTO"; + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + FunctionCallingConfigMode["ANY"] = "ANY"; + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + FunctionCallingConfigMode["NONE"] = "NONE"; +})(exports.FunctionCallingConfigMode || (exports.FunctionCallingConfigMode = {})); +/** Enum that controls the safety filter level for objectionable content. */ +exports.SafetyFilterLevel = void 0; +(function (SafetyFilterLevel) { + SafetyFilterLevel["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + SafetyFilterLevel["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + SafetyFilterLevel["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + SafetyFilterLevel["BLOCK_NONE"] = "BLOCK_NONE"; +})(exports.SafetyFilterLevel || (exports.SafetyFilterLevel = {})); +/** Enum that controls the generation of people. */ +exports.PersonGeneration = void 0; +(function (PersonGeneration) { + /** + * Block generation of images of people. + */ + PersonGeneration["DONT_ALLOW"] = "DONT_ALLOW"; + /** + * Generate images of adults, but not children. + */ + PersonGeneration["ALLOW_ADULT"] = "ALLOW_ADULT"; + /** + * Generate images that include adults and children. + */ + PersonGeneration["ALLOW_ALL"] = "ALLOW_ALL"; +})(exports.PersonGeneration || (exports.PersonGeneration = {})); +/** Enum that specifies the language of the text in the prompt. */ +exports.ImagePromptLanguage = void 0; +(function (ImagePromptLanguage) { + /** + * Auto-detect the language. + */ + ImagePromptLanguage["auto"] = "auto"; + /** + * English + */ + ImagePromptLanguage["en"] = "en"; + /** + * Japanese + */ + ImagePromptLanguage["ja"] = "ja"; + /** + * Korean + */ + ImagePromptLanguage["ko"] = "ko"; + /** + * Hindi + */ + ImagePromptLanguage["hi"] = "hi"; + /** + * Chinese + */ + ImagePromptLanguage["zh"] = "zh"; + /** + * Portuguese + */ + ImagePromptLanguage["pt"] = "pt"; + /** + * Spanish + */ + ImagePromptLanguage["es"] = "es"; +})(exports.ImagePromptLanguage || (exports.ImagePromptLanguage = {})); +/** Enum representing the mask mode of a mask reference image. */ +exports.MaskReferenceMode = void 0; +(function (MaskReferenceMode) { + MaskReferenceMode["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT"; + MaskReferenceMode["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED"; + MaskReferenceMode["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND"; + MaskReferenceMode["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND"; + MaskReferenceMode["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC"; +})(exports.MaskReferenceMode || (exports.MaskReferenceMode = {})); +/** Enum representing the control type of a control reference image. */ +exports.ControlReferenceType = void 0; +(function (ControlReferenceType) { + ControlReferenceType["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT"; + ControlReferenceType["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY"; + ControlReferenceType["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE"; + ControlReferenceType["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH"; +})(exports.ControlReferenceType || (exports.ControlReferenceType = {})); +/** Enum representing the subject type of a subject reference image. */ +exports.SubjectReferenceType = void 0; +(function (SubjectReferenceType) { + SubjectReferenceType["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT"; + SubjectReferenceType["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON"; + SubjectReferenceType["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL"; + SubjectReferenceType["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT"; +})(exports.SubjectReferenceType || (exports.SubjectReferenceType = {})); +/** Enum representing the Imagen 3 Edit mode. */ +exports.EditMode = void 0; +(function (EditMode) { + EditMode["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT"; + EditMode["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL"; + EditMode["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION"; + EditMode["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT"; + EditMode["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING"; + EditMode["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE"; + EditMode["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP"; + EditMode["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE"; +})(exports.EditMode || (exports.EditMode = {})); +/** Enum that represents the segmentation mode. */ +exports.SegmentMode = void 0; +(function (SegmentMode) { + SegmentMode["FOREGROUND"] = "FOREGROUND"; + SegmentMode["BACKGROUND"] = "BACKGROUND"; + SegmentMode["PROMPT"] = "PROMPT"; + SegmentMode["SEMANTIC"] = "SEMANTIC"; + SegmentMode["INTERACTIVE"] = "INTERACTIVE"; +})(exports.SegmentMode || (exports.SegmentMode = {})); +/** Enum that controls the compression quality of the generated videos. */ +exports.VideoCompressionQuality = void 0; +(function (VideoCompressionQuality) { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + VideoCompressionQuality["OPTIMIZED"] = "OPTIMIZED"; + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + VideoCompressionQuality["LOSSLESS"] = "LOSSLESS"; +})(exports.VideoCompressionQuality || (exports.VideoCompressionQuality = {})); +/** State for the lifecycle of a File. */ +exports.FileState = void 0; +(function (FileState) { + FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + FileState["PROCESSING"] = "PROCESSING"; + FileState["ACTIVE"] = "ACTIVE"; + FileState["FAILED"] = "FAILED"; +})(exports.FileState || (exports.FileState = {})); +/** Source of the File. */ +exports.FileSource = void 0; +(function (FileSource) { + FileSource["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED"; + FileSource["UPLOADED"] = "UPLOADED"; + FileSource["GENERATED"] = "GENERATED"; +})(exports.FileSource || (exports.FileSource = {})); +/** Server content modalities. */ +exports.MediaModality = void 0; +(function (MediaModality) { + /** + * The modality is unspecified. + */ + MediaModality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Plain text. + */ + MediaModality["TEXT"] = "TEXT"; + /** + * Images. + */ + MediaModality["IMAGE"] = "IMAGE"; + /** + * Video. + */ + MediaModality["VIDEO"] = "VIDEO"; + /** + * Audio. + */ + MediaModality["AUDIO"] = "AUDIO"; + /** + * Document, e.g. PDF. + */ + MediaModality["DOCUMENT"] = "DOCUMENT"; +})(exports.MediaModality || (exports.MediaModality = {})); +/** Start of speech sensitivity. */ +exports.StartSensitivity = void 0; +(function (StartSensitivity) { + /** + * The default is START_SENSITIVITY_LOW. + */ + StartSensitivity["START_SENSITIVITY_UNSPECIFIED"] = "START_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection will detect the start of speech more often. + */ + StartSensitivity["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH"; + /** + * Automatic detection will detect the start of speech less often. + */ + StartSensitivity["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW"; +})(exports.StartSensitivity || (exports.StartSensitivity = {})); +/** End of speech sensitivity. */ +exports.EndSensitivity = void 0; +(function (EndSensitivity) { + /** + * The default is END_SENSITIVITY_LOW. + */ + EndSensitivity["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection ends speech more often. + */ + EndSensitivity["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH"; + /** + * Automatic detection ends speech less often. + */ + EndSensitivity["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW"; +})(exports.EndSensitivity || (exports.EndSensitivity = {})); +/** The different ways of handling user activity. */ +exports.ActivityHandling = void 0; +(function (ActivityHandling) { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ActivityHandling["ACTIVITY_HANDLING_UNSPECIFIED"] = "ACTIVITY_HANDLING_UNSPECIFIED"; + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + ActivityHandling["START_OF_ACTIVITY_INTERRUPTS"] = "START_OF_ACTIVITY_INTERRUPTS"; + /** + * The model's response will not be interrupted. + */ + ActivityHandling["NO_INTERRUPTION"] = "NO_INTERRUPTION"; +})(exports.ActivityHandling || (exports.ActivityHandling = {})); +/** Options about which input is included in the user's turn. */ +exports.TurnCoverage = void 0; +(function (TurnCoverage) { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TurnCoverage["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED"; + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TurnCoverage["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY"; + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TurnCoverage["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT"; +})(exports.TurnCoverage || (exports.TurnCoverage = {})); +/** Specifies how the response should be scheduled in the conversation. */ +exports.FunctionResponseScheduling = void 0; +(function (FunctionResponseScheduling) { + /** + * This value is unused. + */ + FunctionResponseScheduling["SCHEDULING_UNSPECIFIED"] = "SCHEDULING_UNSPECIFIED"; + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + FunctionResponseScheduling["SILENT"] = "SILENT"; + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + FunctionResponseScheduling["WHEN_IDLE"] = "WHEN_IDLE"; + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + FunctionResponseScheduling["INTERRUPT"] = "INTERRUPT"; +})(exports.FunctionResponseScheduling || (exports.FunctionResponseScheduling = {})); +/** Scale of the generated music. */ +exports.Scale = void 0; +(function (Scale) { + /** + * Default value. This value is unused. + */ + Scale["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED"; + /** + * C major or A minor. + */ + Scale["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR"; + /** + * Db major or Bb minor. + */ + Scale["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR"; + /** + * D major or B minor. + */ + Scale["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR"; + /** + * Eb major or C minor + */ + Scale["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR"; + /** + * E major or Db minor. + */ + Scale["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR"; + /** + * F major or D minor. + */ + Scale["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR"; + /** + * Gb major or Eb minor. + */ + Scale["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR"; + /** + * G major or E minor. + */ + Scale["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR"; + /** + * Ab major or F minor. + */ + Scale["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR"; + /** + * A major or Gb minor. + */ + Scale["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR"; + /** + * Bb major or G minor. + */ + Scale["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR"; + /** + * B major or Ab minor. + */ + Scale["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR"; +})(exports.Scale || (exports.Scale = {})); +/** The mode of music generation. */ +exports.MusicGenerationMode = void 0; +(function (MusicGenerationMode) { + /** + * Rely on the server default generation mode. + */ + MusicGenerationMode["MUSIC_GENERATION_MODE_UNSPECIFIED"] = "MUSIC_GENERATION_MODE_UNSPECIFIED"; + /** + * Steer text prompts to regions of latent space with higher quality + music. + */ + MusicGenerationMode["QUALITY"] = "QUALITY"; + /** + * Steer text prompts to regions of latent space with a larger + diversity of music. + */ + MusicGenerationMode["DIVERSITY"] = "DIVERSITY"; + /** + * Steer text prompts to regions of latent space more likely to + generate music with vocals. + */ + MusicGenerationMode["VOCALIZATION"] = "VOCALIZATION"; +})(exports.MusicGenerationMode || (exports.MusicGenerationMode = {})); +/** The playback control signal to apply to the music generation. */ +exports.LiveMusicPlaybackControl = void 0; +(function (LiveMusicPlaybackControl) { + /** + * This value is unused. + */ + LiveMusicPlaybackControl["PLAYBACK_CONTROL_UNSPECIFIED"] = "PLAYBACK_CONTROL_UNSPECIFIED"; + /** + * Start generating the music. + */ + LiveMusicPlaybackControl["PLAY"] = "PLAY"; + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + LiveMusicPlaybackControl["PAUSE"] = "PAUSE"; + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + LiveMusicPlaybackControl["STOP"] = "STOP"; + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + LiveMusicPlaybackControl["RESET_CONTEXT"] = "RESET_CONTEXT"; +})(exports.LiveMusicPlaybackControl || (exports.LiveMusicPlaybackControl = {})); +/** A function response. */ +class FunctionResponse { +} +/** + * Creates a `Part` object from a `URI` string. + */ +function createPartFromUri(uri, mimeType) { + return { + fileData: { + fileUri: uri, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from a `text` string. + */ +function createPartFromText(text) { + return { + text: text, + }; +} +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +function createPartFromFunctionCall(name, args) { + return { + functionCall: { + name: name, + args: args, + }, + }; +} +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +function createPartFromFunctionResponse(id, name, response) { + return { + functionResponse: { + id: id, + name: name, + response: response, + }, + }; +} +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +function createPartFromBase64(data, mimeType) { + return { + inlineData: { + data: data, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +function createPartFromCodeExecutionResult(outcome, output) { + return { + codeExecutionResult: { + outcome: outcome, + output: output, + }, + }; +} +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +function createPartFromExecutableCode(code, language) { + return { + executableCode: { + code: code, + language: language, + }, + }; +} +function _isPart(obj) { + if (typeof obj === 'object' && obj !== null) { + return ('fileData' in obj || + 'text' in obj || + 'functionCall' in obj || + 'functionResponse' in obj || + 'inlineData' in obj || + 'videoMetadata' in obj || + 'codeExecutionResult' in obj || + 'executableCode' in obj); + } + return false; +} +function _toParts(partOrString) { + const parts = []; + if (typeof partOrString === 'string') { + parts.push(createPartFromText(partOrString)); + } + else if (_isPart(partOrString)) { + parts.push(partOrString); + } + else if (Array.isArray(partOrString)) { + if (partOrString.length === 0) { + throw new Error('partOrString cannot be an empty array'); + } + for (const part of partOrString) { + if (typeof part === 'string') { + parts.push(createPartFromText(part)); + } + else if (_isPart(part)) { + parts.push(part); + } + else { + throw new Error('element in PartUnion must be a Part object or string'); + } + } + } + else { + throw new Error('partOrString must be a Part object, string, or array'); + } + return parts; +} +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +function createUserContent(partOrString) { + return { + role: 'user', + parts: _toParts(partOrString), + }; +} +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +function createModelContent(partOrString) { + return { + role: 'model', + parts: _toParts(partOrString), + }; +} +/** A wrapper class for the http response. */ +class HttpResponse { + constructor(response) { + // Process the headers. + const headers = {}; + for (const pair of response.headers.entries()) { + headers[pair[0]] = pair[1]; + } + this.headers = headers; + // Keep the original response. + this.responseInternal = response; + } + json() { + return this.responseInternal.json(); + } +} +/** Content filter results for a prompt sent in the request. */ +class GenerateContentResponsePromptFeedback { +} +/** Usage metadata about response(s). */ +class GenerateContentResponseUsageMetadata { +} +/** Response message for PredictionService.GenerateContent. */ +class GenerateContentResponse { + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning text from the first one.'); + } + let text = ''; + let anyTextPartText = false; + const nonTextParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + (fieldValue !== null || fieldValue !== undefined)) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartText = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartText ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning data from the first one.'); + } + let data = ''; + const nonDataParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && + (fieldValue !== null || fieldValue !== undefined)) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning function calls from the first one.'); + } + const functionCalls = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.functionCall).map((part) => part.functionCall).filter((functionCall) => functionCall !== undefined); + if ((functionCalls === null || functionCalls === void 0 ? void 0 : functionCalls.length) === 0) { + return undefined; + } + return functionCalls; + } + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning executable code from the first one.'); + } + const executableCode = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.executableCode).map((part) => part.executableCode).filter((executableCode) => executableCode !== undefined); + if ((executableCode === null || executableCode === void 0 ? void 0 : executableCode.length) === 0) { + return undefined; + } + return (_j = executableCode === null || executableCode === void 0 ? void 0 : executableCode[0]) === null || _j === void 0 ? void 0 : _j.code; + } + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning code execution result from the first one.'); + } + const codeExecutionResult = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.codeExecutionResult).map((part) => part.codeExecutionResult).filter((codeExecutionResult) => codeExecutionResult !== undefined); + if ((codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult.length) === 0) { + return undefined; + } + return (_j = codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult[0]) === null || _j === void 0 ? void 0 : _j.output; + } +} +/** Response for the embed_content method. */ +class EmbedContentResponse { +} +/** The output images response. */ +class GenerateImagesResponse { +} +/** Response for the request to edit an image. */ +class EditImageResponse { +} +class UpscaleImageResponse { +} +/** The output images response. */ +class RecontextImageResponse { +} +/** The output images response. */ +class SegmentImageResponse { +} +class ListModelsResponse { +} +class DeleteModelResponse { +} +/** Response for counting tokens. */ +class CountTokensResponse { +} +/** Response for computing tokens. */ +class ComputeTokensResponse { +} +/** Response with generated videos. */ +class GenerateVideosResponse { +} +/** Response for the list tuning jobs method. */ +class ListTuningJobsResponse { +} +/** Empty response for caches.delete method. */ +class DeleteCachedContentResponse { +} +class ListCachedContentsResponse { +} +/** Response for the list files method. */ +class ListFilesResponse { +} +/** Response for the create file method. */ +class CreateFileResponse { +} +/** Response for the delete file method. */ +class DeleteFileResponse { +} +/** Config for `inlined_responses` parameter. */ +class InlinedResponse { +} +/** Config for batches.list return value. */ +class ListBatchJobsResponse { +} +/** Represents a single response in a replay. */ +class ReplayResponse { +} +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +class RawReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_RAW', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + }; + return referenceImageAPI; + } +} +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +class MaskReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_MASK', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + maskImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +class ControlReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_CONTROL', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + controlImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +class StyleReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_STYLE', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + styleImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +class SubjectReferenceImage { + /* Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_SUBJECT', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + subjectImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** Response message for API call. */ +class LiveServerMessage { + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text() { + var _a, _b, _c; + let text = ''; + let anyTextPartFound = false; + const nonTextParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + fieldValue !== null) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartFound = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartFound ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c; + let data = ''; + const nonDataParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && fieldValue !== null) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } +} +/** A video generation long-running operation. */ +class GenerateVideosOperation { + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }) { + const operation = new GenerateVideosOperation(); + operation.name = apiResponse['name']; + operation.metadata = apiResponse['metadata']; + operation.done = apiResponse['done']; + operation.error = apiResponse['error']; + if (isVertexAI) { + const response = apiResponse['response']; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const responseVideos = response['videos']; + operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => { + return { + video: { + uri: generatedVideo['gcsUri'], + videoBytes: generatedVideo['bytesBase64Encoded'] + ? tBytes$1(generatedVideo['bytesBase64Encoded']) + : undefined, + mimeType: generatedVideo['mimeType'], + }, + }; + }); + operationResponse.raiMediaFilteredCount = response['raiMediaFilteredCount']; + operationResponse.raiMediaFilteredReasons = response['raiMediaFilteredReasons']; + operation.response = operationResponse; + } + } + else { + const response = apiResponse['response']; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const generatedVideoResponse = response['generateVideoResponse']; + const responseVideos = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['generatedSamples']; + operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => { + const video = generatedVideo['video']; + return { + video: { + uri: video === null || video === void 0 ? void 0 : video['uri'], + videoBytes: (video === null || video === void 0 ? void 0 : video['encodedVideo']) + ? tBytes$1(video === null || video === void 0 ? void 0 : video['encodedVideo']) + : undefined, + mimeType: generatedVideo['encoding'], + }, + }; + }); + operationResponse.raiMediaFilteredCount = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['raiMediaFilteredCount']; + operationResponse.raiMediaFilteredReasons = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['raiMediaFilteredReasons']; + operation.response = operationResponse; + } + } + return operation; + } +} +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +class LiveClientToolResponse { +} +/** Parameters for sending tool responses to the live API. */ +class LiveSendToolResponseParameters { + constructor() { + /** Tool responses to send to the session. */ + this.functionResponses = []; + } +} +/** Response message for the LiveMusicClientMessage call. */ +class LiveMusicServerMessage { + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk() { + if (this.serverContent && + this.serverContent.audioChunks && + this.serverContent.audioChunks.length > 0) { + return this.serverContent.audioChunks[0]; + } + return undefined; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tModel(apiClient, model) { + if (!model || typeof model !== 'string') { + throw new Error('model is required and must be a string'); + } + if (apiClient.isVertexAI()) { + if (model.startsWith('publishers/') || + model.startsWith('projects/') || + model.startsWith('models/')) { + return model; + } + else if (model.indexOf('/') >= 0) { + const parts = model.split('/', 2); + return `publishers/${parts[0]}/models/${parts[1]}`; + } + else { + return `publishers/google/models/${model}`; + } + } + else { + if (model.startsWith('models/') || model.startsWith('tunedModels/')) { + return model; + } + else { + return `models/${model}`; + } + } +} +function tCachesModel(apiClient, model) { + const transformedModel = tModel(apiClient, model); + if (!transformedModel) { + return ''; + } + if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) { + // vertex caches only support model name start with projects. + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`; + } + else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) { + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`; + } + else { + return transformedModel; + } +} +function tBlobs(blobs) { + if (Array.isArray(blobs)) { + return blobs.map((blob) => tBlob(blob)); + } + else { + return [tBlob(blobs)]; + } +} +function tBlob(blob) { + if (typeof blob === 'object' && blob !== null) { + return blob; + } + throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof blob}`); +} +function tImageBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('image/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tAudioBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('audio/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tPart(origin) { + if (origin === null || origin === undefined) { + throw new Error('PartUnion is required'); + } + if (typeof origin === 'object') { + return origin; + } + if (typeof origin === 'string') { + return { text: origin }; + } + throw new Error(`Unsupported part type: ${typeof origin}`); +} +function tParts(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('PartListUnion is required'); + } + if (Array.isArray(origin)) { + return origin.map((item) => tPart(item)); + } + return [tPart(origin)]; +} +function _isContent(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'parts' in origin && + Array.isArray(origin.parts)); +} +function _isFunctionCallPart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionCall' in origin); +} +function _isFunctionResponsePart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionResponse' in origin); +} +function tContent(origin) { + if (origin === null || origin === undefined) { + throw new Error('ContentUnion is required'); + } + if (_isContent(origin)) { + // _isContent is a utility function that checks if the + // origin is a Content. + return origin; + } + return { + role: 'user', + parts: tParts(origin), + }; +} +function tContentsForEmbed(apiClient, origin) { + if (!origin) { + return []; + } + if (apiClient.isVertexAI() && Array.isArray(origin)) { + return origin.flatMap((item) => { + const content = tContent(item); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + }); + } + else if (apiClient.isVertexAI()) { + const content = tContent(origin); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + } + if (Array.isArray(origin)) { + return origin.map((item) => tContent(item)); + } + return [tContent(origin)]; +} +function tContents(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('contents are required'); + } + if (!Array.isArray(origin)) { + // If it's not an array, it's a single content or a single PartUnion. + if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them'); + } + return [tContent(origin)]; + } + const result = []; + const accumulatedParts = []; + const isContentArray = _isContent(origin[0]); + for (const item of origin) { + const isContent = _isContent(item); + if (isContent != isContentArray) { + throw new Error('Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them'); + } + if (isContent) { + // `isContent` contains the result of _isContent, which is a utility + // function that checks if the item is a Content. + result.push(item); + } + else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them'); + } + else { + accumulatedParts.push(item); + } + } + if (!isContentArray) { + result.push({ role: 'user', parts: tParts(accumulatedParts) }); + } + return result; +} +/* +Transform the type field from an array of types to an array of anyOf fields. +Example: + {type: ['STRING', 'NUMBER']} +will be transformed to + {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]} +*/ +function flattenTypeArrayToAnyOf(typeList, resultingSchema) { + if (typeList.includes('null')) { + resultingSchema['nullable'] = true; + } + const listWithoutNull = typeList.filter((type) => type !== 'null'); + if (listWithoutNull.length === 1) { + resultingSchema['type'] = Object.values(exports.Type).includes(listWithoutNull[0].toUpperCase()) + ? listWithoutNull[0].toUpperCase() + : exports.Type.TYPE_UNSPECIFIED; + } + else { + resultingSchema['anyOf'] = []; + for (const i of listWithoutNull) { + resultingSchema['anyOf'].push({ + 'type': Object.values(exports.Type).includes(i.toUpperCase()) + ? i.toUpperCase() + : exports.Type.TYPE_UNSPECIFIED, + }); + } + } +} +function processJsonSchema(_jsonSchema) { + const genAISchema = {}; + const schemaFieldNames = ['items']; + const listSchemaFieldNames = ['anyOf']; + const dictSchemaFieldNames = ['properties']; + if (_jsonSchema['type'] && _jsonSchema['anyOf']) { + throw new Error('type and anyOf cannot be both populated.'); + } + /* + This is to handle the nullable array or object. The _jsonSchema will + be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The + logic is to check if anyOf has 2 elements and one of the element is null, + if so, the anyOf field is unnecessary, so we need to get rid of the anyOf + field and make the schema nullable. Then use the other element as the new + _jsonSchema for processing. This is because the backend doesn't have a null + type. + This has to be checked before we process any other fields. + For example: + const objectNullable = z.object({ + nullableArray: z.array(z.string()).nullable(), + }); + Will have the raw _jsonSchema as: + { + type: 'OBJECT', + properties: { + nullableArray: { + anyOf: [ + {type: 'null'}, + { + type: 'array', + items: {type: 'string'}, + }, + ], + } + }, + required: [ 'nullableArray' ], + } + Will result in following schema compatible with Gemini API: + { + type: 'OBJECT', + properties: { + nullableArray: { + nullable: true, + type: 'ARRAY', + items: {type: 'string'}, + } + }, + required: [ 'nullableArray' ], + } + */ + const incomingAnyOf = _jsonSchema['anyOf']; + if (incomingAnyOf != null && incomingAnyOf.length == 2) { + if (incomingAnyOf[0]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[1]; + } + else if (incomingAnyOf[1]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[0]; + } + } + if (_jsonSchema['type'] instanceof Array) { + flattenTypeArrayToAnyOf(_jsonSchema['type'], genAISchema); + } + for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) { + // Skip if the fieldvalue is undefined or null. + if (fieldValue == null) { + continue; + } + if (fieldName == 'type') { + if (fieldValue === 'null') { + throw new Error('type: null can not be the only possible type for the field.'); + } + if (fieldValue instanceof Array) { + // we have already handled the type field with array of types in the + // beginning of this function. + continue; + } + genAISchema['type'] = Object.values(exports.Type).includes(fieldValue.toUpperCase()) + ? fieldValue.toUpperCase() + : exports.Type.TYPE_UNSPECIFIED; + } + else if (schemaFieldNames.includes(fieldName)) { + genAISchema[fieldName] = + processJsonSchema(fieldValue); + } + else if (listSchemaFieldNames.includes(fieldName)) { + const listSchemaFieldValue = []; + for (const item of fieldValue) { + if (item['type'] == 'null') { + genAISchema['nullable'] = true; + continue; + } + listSchemaFieldValue.push(processJsonSchema(item)); + } + genAISchema[fieldName] = + listSchemaFieldValue; + } + else if (dictSchemaFieldNames.includes(fieldName)) { + const dictSchemaFieldValue = {}; + for (const [key, value] of Object.entries(fieldValue)) { + dictSchemaFieldValue[key] = processJsonSchema(value); + } + genAISchema[fieldName] = + dictSchemaFieldValue; + } + else { + // additionalProperties is not included in JSONSchema, skipping it. + if (fieldName === 'additionalProperties') { + continue; + } + genAISchema[fieldName] = fieldValue; + } + } + return genAISchema; +} +// we take the unknown in the schema field because we want enable user to pass +// the output of major schema declaration tools without casting. Tools such as +// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type +// or object, see details in +// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7 +// typebox can return unknown, see details in +// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35 +// Note: proper json schemas with the $schema field set never arrive to this +// transformer. Schemas with $schema are routed to the equivalent API json +// schema field. +function tSchema(schema) { + return processJsonSchema(schema); +} +function tSpeechConfig(speechConfig) { + if (typeof speechConfig === 'object') { + return speechConfig; + } + else if (typeof speechConfig === 'string') { + return { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: speechConfig, + }, + }, + }; + } + else { + throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`); + } +} +function tLiveSpeechConfig(speechConfig) { + if ('multiSpeakerVoiceConfig' in speechConfig) { + throw new Error('multiSpeakerVoiceConfig is not supported in the live API.'); + } + return speechConfig; +} +function tTool(tool) { + if (tool.functionDeclarations) { + for (const functionDeclaration of tool.functionDeclarations) { + if (functionDeclaration.parameters) { + if (!Object.keys(functionDeclaration.parameters).includes('$schema')) { + functionDeclaration.parameters = processJsonSchema(functionDeclaration.parameters); + } + else { + if (!functionDeclaration.parametersJsonSchema) { + functionDeclaration.parametersJsonSchema = + functionDeclaration.parameters; + delete functionDeclaration.parameters; + } + } + } + if (functionDeclaration.response) { + if (!Object.keys(functionDeclaration.response).includes('$schema')) { + functionDeclaration.response = processJsonSchema(functionDeclaration.response); + } + else { + if (!functionDeclaration.responseJsonSchema) { + functionDeclaration.responseJsonSchema = + functionDeclaration.response; + delete functionDeclaration.response; + } + } + } + } + } + return tool; +} +function tTools(tools) { + // Check if the incoming type is defined. + if (tools === undefined || tools === null) { + throw new Error('tools is required'); + } + if (!Array.isArray(tools)) { + throw new Error('tools is required and must be an array of Tools'); + } + const result = []; + for (const tool of tools) { + result.push(tool); + } + return result; +} +/** + * Prepends resource name with project, location, resource_prefix if needed. + * + * @param client The API client. + * @param resourceName The resource name. + * @param resourcePrefix The resource prefix. + * @param splitsAfterPrefix The number of splits after the prefix. + * @returns The completed resource name. + * + * Examples: + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/bar/locations/us-west1/cachedContents/123' + * ``` + * + * ``` + * resource_name = 'projects/foo/locations/us-central1/cachedContents/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/foo/locations/us-central1/cachedContents/123' + * ``` + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns 'cachedContents/123' + * ``` + * + * ``` + * resource_name = 'some/wrong/cachedContents/resource/name/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * # client.vertexai = True + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * -> 'some/wrong/resource/name/123' + * ``` + */ +function resourceName(client, resourceName, resourcePrefix, splitsAfterPrefix = 1) { + const shouldAppendPrefix = !resourceName.startsWith(`${resourcePrefix}/`) && + resourceName.split('/').length === splitsAfterPrefix; + if (client.isVertexAI()) { + if (resourceName.startsWith('projects/')) { + return resourceName; + } + else if (resourceName.startsWith('locations/')) { + return `projects/${client.getProject()}/${resourceName}`; + } + else if (resourceName.startsWith(`${resourcePrefix}/`)) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`; + } + else if (shouldAppendPrefix) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`; + } + else { + return resourceName; + } + } + if (shouldAppendPrefix) { + return `${resourcePrefix}/${resourceName}`; + } + return resourceName; +} +function tCachedContentName(apiClient, name) { + if (typeof name !== 'string') { + throw new Error('name must be a string'); + } + return resourceName(apiClient, name, 'cachedContents'); +} +function tTuningJobStatus(status) { + switch (status) { + case 'STATE_UNSPECIFIED': + return 'JOB_STATE_UNSPECIFIED'; + case 'CREATING': + return 'JOB_STATE_RUNNING'; + case 'ACTIVE': + return 'JOB_STATE_SUCCEEDED'; + case 'FAILED': + return 'JOB_STATE_FAILED'; + default: + return status; + } +} +function tBytes(fromImageBytes) { + return tBytes$1(fromImageBytes); +} +function _isFile(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'name' in origin); +} +function isGeneratedVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'video' in origin); +} +function isVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'uri' in origin); +} +function tFileName(fromName) { + var _a; + let name; + if (_isFile(fromName)) { + name = fromName.name; + } + if (isVideo(fromName)) { + name = fromName.uri; + if (name === undefined) { + return undefined; + } + } + if (isGeneratedVideo(fromName)) { + name = (_a = fromName.video) === null || _a === void 0 ? void 0 : _a.uri; + if (name === undefined) { + return undefined; + } + } + if (typeof fromName === 'string') { + name = fromName; + } + if (name === undefined) { + throw new Error('Could not extract file name from the provided input.'); + } + if (name.startsWith('https://')) { + const suffix = name.split('files/')[1]; + const match = suffix.match(/[a-z0-9]+/); + if (match === null) { + throw new Error(`Could not extract file name from URI ${name}`); + } + name = match[0]; + } + else if (name.startsWith('files/')) { + name = name.split('files/')[1]; + } + return name; +} +function tModelsUrl(apiClient, baseModels) { + let res; + if (apiClient.isVertexAI()) { + res = baseModels ? 'publishers/google/models' : 'models'; + } + else { + res = baseModels ? 'models' : 'tunedModels'; + } + return res; +} +function tExtractModels(response) { + for (const key of ['models', 'tunedModels', 'publisherModels']) { + if (hasField(response, key)) { + return response[key]; + } + } + return []; +} +function hasField(data, fieldName) { + return data !== null && typeof data === 'object' && fieldName in data; +} +function mcpToGeminiTool(mcpTool, config = {}) { + const mcpToolSchema = mcpTool; + const functionDeclaration = { + name: mcpToolSchema['name'], + description: mcpToolSchema['description'], + parametersJsonSchema: mcpToolSchema['inputSchema'], + }; + if (config.behavior) { + functionDeclaration['behavior'] = config.behavior; + } + const geminiTool = { + functionDeclarations: [ + functionDeclaration, + ], + }; + return geminiTool; +} +/** + * Converts a list of MCP tools to a single Gemini tool with a list of function + * declarations. + */ +function mcpToolsToGeminiTool(mcpTools, config = {}) { + const functionDeclarations = []; + const toolNames = new Set(); + for (const mcpTool of mcpTools) { + const mcpToolName = mcpTool.name; + if (toolNames.has(mcpToolName)) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + toolNames.add(mcpToolName); + const geminiTool = mcpToGeminiTool(mcpTool, config); + if (geminiTool.functionDeclarations) { + functionDeclarations.push(...geminiTool.functionDeclarations); + } + } + return { functionDeclarations: functionDeclarations }; +} +// Transforms a source input into a BatchJobSource object with validation. +function tBatchJobSource(apiClient, src) { + if (typeof src !== 'string' && !Array.isArray(src)) { + if (apiClient && apiClient.isVertexAI()) { + if (src.gcsUri && src.bigqueryUri) { + throw new Error('Only one of `gcsUri` or `bigqueryUri` can be set.'); + } + else if (!src.gcsUri && !src.bigqueryUri) { + throw new Error('One of `gcsUri` or `bigqueryUri` must be set.'); + } + } + else { + // Logic for non-Vertex AI client (inlined_requests, file_name) + if (src.inlinedRequests && src.fileName) { + throw new Error('Only one of `inlinedRequests` or `fileName` can be set.'); + } + else if (!src.inlinedRequests && !src.fileName) { + throw new Error('One of `inlinedRequests` or `fileName` must be set.'); + } + } + return src; + } + // If src is an array (list in Python) + else if (Array.isArray(src)) { + return { inlinedRequests: src }; + } + else if (typeof src === 'string') { + if (src.startsWith('gs://')) { + return { + format: 'jsonl', + gcsUri: [src], // GCS URI is expected as an array + }; + } + else if (src.startsWith('bq://')) { + return { + format: 'bigquery', + bigqueryUri: src, + }; + } + else if (src.startsWith('files/')) { + return { + fileName: src, + }; + } + } + throw new Error(`Unsupported source: ${src}`); +} +function tBatchJobDestination(dest) { + if (typeof dest !== 'string') { + return dest; + } + const destString = dest; + if (destString.startsWith('gs://')) { + return { + format: 'jsonl', + gcsUri: destString, + }; + } + else if (destString.startsWith('bq://')) { + return { + format: 'bigquery', + bigqueryUri: destString, + }; + } + else { + throw new Error(`Unsupported destination: ${destString}`); + } +} +function tBatchJobName(apiClient, name) { + const nameString = name; + if (!apiClient.isVertexAI()) { + const mldevPattern = /batches\/[^/]+$/; + if (mldevPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } + } + const vertexPattern = /^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/; + if (vertexPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else if (/^\d+$/.test(nameString)) { + return nameString; + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } +} +function tJobState(state) { + const stateString = state; + if (stateString === 'BATCH_STATE_UNSPECIFIED') { + return 'JOB_STATE_UNSPECIFIED'; + } + else if (stateString === 'BATCH_STATE_PENDING') { + return 'JOB_STATE_PENDING'; + } + else if (stateString === 'BATCH_STATE_SUCCEEDED') { + return 'JOB_STATE_SUCCEEDED'; + } + else if (stateString === 'BATCH_STATE_FAILED') { + return 'JOB_STATE_FAILED'; + } + else if (stateString === 'BATCH_STATE_CANCELLED') { + return 'JOB_STATE_CANCELLED'; + } + else { + return stateString; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$4(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$4(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$4(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$4(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$4(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$4(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$4(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev$1(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$4(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$4(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$4(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$4(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$4(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$4(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$4(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$4() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$4(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$4(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$4(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$4(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$4(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$4()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$4(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev$2(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev$2(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$2(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev$2(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$3(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$3(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$3(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$3(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$3(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev$1(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$4(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToMldev$1(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev$1(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$4(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$2(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToMldev$3(tSpeechConfig(fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev$1(fromThinkingConfig)); + } + return toObject; +} +function inlinedRequestToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['request', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$4(item); + }); + } + setValueByPath(toObject, ['request', 'contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['request', 'generationConfig'], generateContentConfigToMldev$1(apiClient, fromConfig, toObject)); + } + return toObject; +} +function batchJobSourceToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['format']) !== undefined) { + throw new Error('format parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['bigqueryUri']) !== undefined) { + throw new Error('bigqueryUri parameter is not supported in Gemini API.'); + } + const fromFileName = getValueByPath(fromObject, ['fileName']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedRequests = getValueByPath(fromObject, [ + 'inlinedRequests', + ]); + if (fromInlinedRequests != null) { + let transformedList = fromInlinedRequests; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedRequestToMldev(apiClient, item); + }); + } + setValueByPath(toObject, ['requests', 'requests'], transformedList); + } + return toObject; +} +function createBatchJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['batch', 'displayName'], fromDisplayName); + } + if (getValueByPath(fromObject, ['dest']) !== undefined) { + throw new Error('dest parameter is not supported in Gemini API.'); + } + return toObject; +} +function createBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['batch', 'inputConfig'], batchJobSourceToMldev(apiClient, tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createBatchJobConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + if (getValueByPath(fromObject, ['filter']) !== undefined) { + throw new Error('filter parameter is not supported in Gemini API.'); + } + return toObject; +} +function listBatchJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listBatchJobsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function deleteBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function batchJobSourceToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['instancesFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsSource', 'uris'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigquerySource', 'inputUri'], fromBigqueryUri); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['inlinedRequests']) !== undefined) { + throw new Error('inlinedRequests parameter is not supported in Vertex AI.'); + } + return toObject; +} +function batchJobDestinationToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['predictionsFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsDestination', 'outputUriPrefix'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryDestination', 'outputUri'], fromBigqueryUri); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['inlinedResponses']) !== undefined) { + throw new Error('inlinedResponses parameter is not supported in Vertex AI.'); + } + return toObject; +} +function createBatchJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDest = getValueByPath(fromObject, ['dest']); + if (parentObject !== undefined && fromDest != null) { + setValueByPath(parentObject, ['outputConfig'], batchJobDestinationToVertex(tBatchJobDestination(fromDest))); + } + return toObject; +} +function createBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['inputConfig'], batchJobSourceToVertex(tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createBatchJobConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listBatchJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listBatchJobsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function deleteBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev$2(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$2(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$2(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromMldev$1(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev$2(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev$1(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev$2(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev$1(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev$1(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function jobErrorFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + return toObject; +} +function inlinedResponseFromMldev(fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateContentResponseFromMldev$1(fromResponse)); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError)); + } + return toObject; +} +function batchJobDestinationFromMldev(fromObject) { + const toObject = {}; + const fromFileName = getValueByPath(fromObject, ['responsesFile']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedResponses = getValueByPath(fromObject, [ + 'inlinedResponses', + 'inlinedResponses', + ]); + if (fromInlinedResponses != null) { + let transformedList = fromInlinedResponses; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedResponseFromMldev(item); + }); + } + setValueByPath(toObject, ['inlinedResponses'], transformedList); + } + return toObject; +} +function batchJobFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, [ + 'metadata', + 'displayName', + ]); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['metadata', 'state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, [ + 'metadata', + 'createTime', + ]); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'metadata', + 'endTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, [ + 'metadata', + 'updateTime', + ]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['metadata', 'model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromDest = getValueByPath(fromObject, ['metadata', 'output']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromMldev(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, ['operations']); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromMldev(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function deleteResourceJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError)); + } + return toObject; +} +function jobErrorFromVertex(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + return toObject; +} +function batchJobSourceFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['instancesFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsSource', 'uris']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigquerySource', + 'inputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + return toObject; +} +function batchJobDestinationFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['predictionsFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, [ + 'gcsDestination', + 'outputUriPrefix', + ]); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigqueryDestination', + 'outputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + return toObject; +} +function batchJobFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromSrc = getValueByPath(fromObject, ['inputConfig']); + if (fromSrc != null) { + setValueByPath(toObject, ['src'], batchJobSourceFromVertex(fromSrc)); + } + const fromDest = getValueByPath(fromObject, ['outputConfig']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromVertex(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, [ + 'batchPredictionJobs', + ]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromVertex(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function deleteResourceJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +exports.PagedItem = void 0; +(function (PagedItem) { + PagedItem["PAGED_ITEM_BATCH_JOBS"] = "batchJobs"; + PagedItem["PAGED_ITEM_MODELS"] = "models"; + PagedItem["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs"; + PagedItem["PAGED_ITEM_FILES"] = "files"; + PagedItem["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents"; +})(exports.PagedItem || (exports.PagedItem = {})); +/** + * Pager class for iterating through paginated results. + */ +class Pager { + constructor(name, request, response, params) { + this.pageInternal = []; + this.paramsInternal = {}; + this.requestInternal = request; + this.init(name, response, params); + } + init(name, response, params) { + var _a, _b; + this.nameInternal = name; + this.pageInternal = response[this.nameInternal] || []; + this.sdkHttpResponseInternal = response === null || response === void 0 ? void 0 : response.sdkHttpResponse; + this.idxInternal = 0; + let requestParams = { config: {} }; + if (!params || Object.keys(params).length === 0) { + requestParams = { config: {} }; + } + else if (typeof params === 'object') { + requestParams = Object.assign({}, params); + } + else { + requestParams = params; + } + if (requestParams['config']) { + requestParams['config']['pageToken'] = response['nextPageToken']; + } + this.paramsInternal = requestParams; + this.pageInternalSize = + (_b = (_a = requestParams['config']) === null || _a === void 0 ? void 0 : _a['pageSize']) !== null && _b !== void 0 ? _b : this.pageInternal.length; + } + initNextPage(response) { + this.init(this.nameInternal, response, this.paramsInternal); + } + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page() { + return this.pageInternal; + } + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name() { + return this.nameInternal; + } + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize() { + return this.pageInternalSize; + } + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse() { + return this.sdkHttpResponseInternal; + } + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params() { + return this.paramsInternal; + } + /** + * Returns the total number of items in the current page. + */ + get pageLength() { + return this.pageInternal.length; + } + /** + * Returns the item at the given index. + */ + getItem(index) { + return this.pageInternal[index]; + } + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator]() { + return { + next: async () => { + if (this.idxInternal >= this.pageLength) { + if (this.hasNextPage()) { + await this.nextPage(); + } + else { + return { value: undefined, done: true }; + } + } + const item = this.getItem(this.idxInternal); + this.idxInternal += 1; + return { value: item, done: false }; + }, + return: async () => { + return { value: undefined, done: true }; + }, + }; + } + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + async nextPage() { + if (!this.hasNextPage()) { + throw new Error('No more pages to fetch.'); + } + const response = await this.requestInternal(this.params); + this.initNextPage(response); + return this.page; + } + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage() { + var _a; + if (((_a = this.params['config']) === null || _a === void 0 ? void 0 : _a['pageToken']) !== undefined) { + return true; + } + return false; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Batches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + this.create = async (params) => { + var _a, _b; + if (this.apiClient.isVertexAI()) { + const timestamp = Date.now(); + const timestampStr = timestamp.toString(); + if (Array.isArray(params.src)) { + throw new Error('InlinedRequest[] is not supported in Vertex AI. Please use ' + + 'Google Cloud Storage URI or BigQuery URI instead.'); + } + params.config = params.config || {}; + if (params.config.displayName === undefined) { + params.config.displayName = 'genaiBatchJob_${timestampStr}'; + } + if (params.config.dest === undefined && typeof params.src === 'string') { + if (params.src.startsWith('gs://') && params.src.endsWith('.jsonl')) { + params.config.dest = `${params.src.slice(0, -6)}/dest`; + } + else if (params.src.startsWith('bq://')) { + params.config.dest = + `${params.src}_dest_${timestampStr}`; + } + else { + throw new Error('Unsupported source:' + params.src); + } + } + } + else { + if (Array.isArray(params.src) || + (typeof params.src !== 'string' && params.src.inlinedRequests)) { + // Move system instruction to httpOptions extraBody. + let path = ''; + let queryParams = {}; + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchGenerateContent', body['_url']); + queryParams = body['_query']; + // Move system instruction to 'request': + // {'systemInstruction': system_instruction} + const batch = body['batch']; + const inputConfig = batch['inputConfig']; + const requestsWrapper = inputConfig['requests']; + const requests = requestsWrapper['requests']; + const newRequests = []; + for (const request of requests) { + const requestDict = request; + if (requestDict['systemInstruction']) { + const systemInstructionValue = requestDict['systemInstruction']; + delete requestDict['systemInstruction']; + const requestContent = requestDict['request']; + requestContent['systemInstruction'] = systemInstructionValue; + requestDict['request'] = requestContent; + } + newRequests.push(requestDict); + } + requestsWrapper['requests'] = newRequests; + delete body['config']; + delete body['_url']; + delete body['_query']; + const response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + return await this.createInternal(params); + }; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(exports.PagedItem.PAGED_ITEM_BATCH_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + async createInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchGenerateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + else { + const body = cancelBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listBatchJobsParametersToVertex(params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromVertex(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listBatchJobsParametersToMldev(params); + path = formatMap('batches', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromMldev(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = deleteBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$3(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$3(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$3(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$3(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$3(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$3(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$3(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$3(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$3(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$3(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$3(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$3(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$3(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$3(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$3() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$3(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$3(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$3(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$3(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$3(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$3()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$3(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$1(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev$1(fromRetrievalConfig)); + } + return toObject; +} +function createCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$3(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$3(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$3(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$1(fromToolConfig)); + } + if (getValueByPath(fromObject, ['kmsKeyName']) !== undefined) { + throw new Error('kmsKeyName parameter is not supported in Gemini API.'); + } + return toObject; +} +function createCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createCachedContentConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataToVertex$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex$2(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$2(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex$2(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex$2(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$2(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex$2(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex$2(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$2(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$2(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$2(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex$2(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex$2(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex$2()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex$2(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToVertex$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToVertex$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex$1(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToVertex$1(fromRetrievalConfig)); + } + return toObject; +} +function createCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex$2(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$2(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex$1(fromToolConfig)); + } + const fromKmsKeyName = getValueByPath(fromObject, ['kmsKeyName']); + if (parentObject !== undefined && fromKmsKeyName != null) { + setValueByPath(parentObject, ['encryption_spec', 'kmsKeyName'], fromKmsKeyName); + } + return toObject; +} +function createCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createCachedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function cachedContentFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromMldev() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromMldev(item); + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} +function cachedContentFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromVertex() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromVertex(item); + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Caches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(exports.PagedItem.PAGED_ITEM_CACHED_CONTENTS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + async create(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = createCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromVertex(); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromMldev(); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = updateCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listCachedContentsParametersToVertex(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromVertex(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listCachedContentsParametersToMldev(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromMldev(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns true if the response is valid, false otherwise. + */ +function isValidResponse(response) { + var _a; + if (response.candidates == undefined || response.candidates.length === 0) { + return false; + } + const content = (_a = response.candidates[0]) === null || _a === void 0 ? void 0 : _a.content; + if (content === undefined) { + return false; + } + return isValidContent(content); +} +function isValidContent(content) { + if (content.parts === undefined || content.parts.length === 0) { + return false; + } + for (const part of content.parts) { + if (part === undefined || Object.keys(part).length === 0) { + return false; + } + } + return true; +} +/** + * Validates the history contains the correct roles. + * + * @throws Error if the history does not start with a user turn. + * @throws Error if the history contains an invalid role. + */ +function validateHistory(history) { + // Empty history is valid. + if (history.length === 0) { + return; + } + for (const content of history) { + if (content.role !== 'user' && content.role !== 'model') { + throw new Error(`Role must be user or model, but got ${content.role}.`); + } + } +} +/** + * Extracts the curated (valid) history from a comprehensive history. + * + * @remarks + * The model may sometimes generate invalid or empty contents(e.g., due to safty + * filters or recitation). Extracting valid turns from the history + * ensures that subsequent requests could be accpeted by the model. + */ +function extractCuratedHistory(comprehensiveHistory) { + if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) { + return []; + } + const curatedHistory = []; + const length = comprehensiveHistory.length; + let i = 0; + while (i < length) { + if (comprehensiveHistory[i].role === 'user') { + curatedHistory.push(comprehensiveHistory[i]); + i++; + } + else { + const modelOutput = []; + let isValid = true; + while (i < length && comprehensiveHistory[i].role === 'model') { + modelOutput.push(comprehensiveHistory[i]); + if (isValid && !isValidContent(comprehensiveHistory[i])) { + isValid = false; + } + i++; + } + if (isValid) { + curatedHistory.push(...modelOutput); + } + else { + // Remove the last user input when model content is invalid. + curatedHistory.pop(); + } + } + } + return curatedHistory; +} +/** + * A utility class to create a chat session. + */ +class Chats { + constructor(modelsModule, apiClient) { + this.modelsModule = modelsModule; + this.apiClient = apiClient; + } + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params) { + return new Chat(this.apiClient, this.modelsModule, params.model, params.config, + // Deep copy the history to avoid mutating the history outside of the + // chat session. + structuredClone(params.history)); + } +} +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +class Chat { + constructor(apiClient, modelsModule, model, config = {}, history = []) { + this.apiClient = apiClient; + this.modelsModule = modelsModule; + this.model = model; + this.config = config; + this.history = history; + // A promise to represent the current state of the message being sent to the + // model. + this.sendPromise = Promise.resolve(); + validateHistory(history); + } + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + async sendMessage(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const responsePromise = this.modelsModule.generateContent({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + this.sendPromise = (async () => { + var _a, _b, _c; + const response = await responsePromise; + const outputContent = (_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content; + // Because the AFC input contains the entire curated chat history in + // addition to the new user input, we need to truncate the AFC history + // to deduplicate the existing chat history. + const fullAutomaticFunctionCallingHistory = response.automaticFunctionCallingHistory; + const index = this.getHistory(true).length; + let automaticFunctionCallingHistory = []; + if (fullAutomaticFunctionCallingHistory != null) { + automaticFunctionCallingHistory = + (_c = fullAutomaticFunctionCallingHistory.slice(index)) !== null && _c !== void 0 ? _c : []; + } + const modelOutput = outputContent ? [outputContent] : []; + this.recordHistory(inputContent, modelOutput, automaticFunctionCallingHistory); + return; + })(); + await this.sendPromise.catch(() => { + // Resets sendPromise to avoid subsequent calls failing + this.sendPromise = Promise.resolve(); + }); + return responsePromise; + } + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + async sendMessageStream(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const streamResponse = this.modelsModule.generateContentStream({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + // Resolve the internal tracking of send completion promise - `sendPromise` + // for both success and failure response. The actual failure is still + // propagated by the `await streamResponse`. + this.sendPromise = streamResponse + .then(() => undefined) + .catch(() => undefined); + const response = await streamResponse; + const result = this.processStreamResponse(response, inputContent); + return result; + } + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated = false) { + const history = curated + ? extractCuratedHistory(this.history) + : this.history; + // Deep copy the history to avoid mutating the history outside of the + // chat session. + return structuredClone(history); + } + processStreamResponse(streamResponse, inputContent) { + var _a, _b; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + var _c, e_1, _d, _e; + const outputContent = []; + try { + for (var _f = true, streamResponse_1 = __asyncValues(streamResponse), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()), _c = streamResponse_1_1.done, !_c; _f = true) { + _e = streamResponse_1_1.value; + _f = false; + const chunk = _e; + if (isValidResponse(chunk)) { + const content = (_b = (_a = chunk.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content; + if (content !== undefined) { + outputContent.push(content); + } + } + yield yield __await(chunk); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_c && (_d = streamResponse_1.return)) yield __await(_d.call(streamResponse_1)); + } + finally { if (e_1) throw e_1.error; } + } + this.recordHistory(inputContent, outputContent); + }); + } + recordHistory(userInput, modelOutput, automaticFunctionCallingHistory) { + let outputContents = []; + if (modelOutput.length > 0 && + modelOutput.every((content) => content.role !== undefined)) { + outputContents = modelOutput; + } + else { + // Appends an empty content when model returns empty response, so that the + // history is always alternating between user and model. + outputContents.push({ + role: 'model', + parts: [], + }); + } + if (automaticFunctionCallingHistory && + automaticFunctionCallingHistory.length > 0) { + this.history.push(...extractCuratedHistory(automaticFunctionCallingHistory)); + } + else { + this.history.push(userInput); + } + this.history.push(...outputContents); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * API errors raised by the GenAI API. + */ +class ApiError extends Error { + constructor(options) { + super(options.message); + this.name = 'ApiError'; + this.status = options.status; + Object.setPrototypeOf(this, ApiError.prototype); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function listFilesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listFilesParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listFilesConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function fileStatusToMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusToMldev(fromError)); + } + return toObject; +} +function createFileParametersToMldev(fromObject) { + const toObject = {}; + const fromFile = getValueByPath(fromObject, ['file']); + if (fromFile != null) { + setValueByPath(toObject, ['file'], fileToMldev(fromFile)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fileStatusFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusFromMldev(fromError)); + } + return toObject; +} +function listFilesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromFiles = getValueByPath(fromObject, ['files']); + if (fromFiles != null) { + let transformedList = fromFiles; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return fileFromMldev(item); + }); + } + setValueByPath(toObject, ['files'], transformedList); + } + return toObject; +} +function createFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function deleteFileResponseFromMldev() { + const toObject = {}; + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Files extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(exports.PagedItem.PAGED_ITEM_FILES, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + async upload(params) { + if (this.apiClient.isVertexAI()) { + throw new Error('Vertex AI does not support uploading files. You can share files through a GCS bucket.'); + } + return this.apiClient + .uploadFile(params.file, params.config) + .then((response) => { + const file = fileFromMldev(response); + return file; + }); + } + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + async download(params) { + await this.apiClient.downloadFile(params); + } + async listInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = listFilesParametersToMldev(params); + path = formatMap('files', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listFilesResponseFromMldev(apiResponse); + const typedResp = new ListFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async createInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createFileParametersToMldev(params); + path = formatMap('upload/v1beta/files', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = createFileResponseFromMldev(apiResponse); + const typedResp = new CreateFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + async get(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = getFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = fileFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + async delete(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = deleteFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteFileResponseFromMldev(); + const typedResp = new DeleteFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$2(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$2(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$2(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$2(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$2(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$2(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$2(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$2(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$2(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$2(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$2(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$2(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$2()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$2(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is not supported in Gemini API.'); + } + return toObject; +} +function audioTranscriptionConfigToMldev$1() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev$1(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev$1(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToMldev$1(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev$1(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToMldev$1(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToMldev$1(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev$1(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToMldev$2(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$2(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev$1(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToMldev$1()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToMldev$1()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToMldev$1(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToMldev$1(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToMldev$1(fromProactivity)); + } + return toObject; +} +function liveConnectParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev$1(fromConfig, toObject)); + } + return toObject; +} +function activityStartToMldev() { + const toObject = {}; + return toObject; +} +function activityEndToMldev() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToMldev(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + setValueByPath(toObject, ['mediaChunks'], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], activityStartToMldev()); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], activityEndToMldev()); + } + return toObject; +} +function weightedPromptToMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromWeight = getValueByPath(fromObject, ['weight']); + if (fromWeight != null) { + setValueByPath(toObject, ['weight'], fromWeight); + } + return toObject; +} +function liveMusicSetWeightedPromptsParametersToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigToMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ['guidance']); + if (fromGuidance != null) { + setValueByPath(toObject, ['guidance'], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ['bpm']); + if (fromBpm != null) { + setValueByPath(toObject, ['bpm'], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ['density']); + if (fromDensity != null) { + setValueByPath(toObject, ['density'], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ['brightness']); + if (fromBrightness != null) { + setValueByPath(toObject, ['brightness'], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ['scale']); + if (fromScale != null) { + setValueByPath(toObject, ['scale'], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ['muteBass']); + if (fromMuteBass != null) { + setValueByPath(toObject, ['muteBass'], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ['muteDrums']); + if (fromMuteDrums != null) { + setValueByPath(toObject, ['muteDrums'], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, [ + 'onlyBassAndDrums', + ]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums); + } + const fromMusicGenerationMode = getValueByPath(fromObject, [ + 'musicGenerationMode', + ]); + if (fromMusicGenerationMode != null) { + setValueByPath(toObject, ['musicGenerationMode'], fromMusicGenerationMode); + } + return toObject; +} +function liveMusicSetConfigParametersToMldev(fromObject) { + const toObject = {}; + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig)); + } + return toObject; +} +function liveMusicClientSetupToMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + return toObject; +} +function liveMusicClientContentToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicClientMessageToMldev(fromObject) { + const toObject = {}; + const fromSetup = getValueByPath(fromObject, ['setup']); + if (fromSetup != null) { + setValueByPath(toObject, ['setup'], liveMusicClientSetupToMldev(fromSetup)); + } + const fromClientContent = getValueByPath(fromObject, [ + 'clientContent', + ]); + if (fromClientContent != null) { + setValueByPath(toObject, ['clientContent'], liveMusicClientContentToMldev(fromClientContent)); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig)); + } + const fromPlaybackControl = getValueByPath(fromObject, [ + 'playbackControl', + ]); + if (fromPlaybackControl != null) { + setValueByPath(toObject, ['playbackControl'], fromPlaybackControl); + } + return toObject; +} +function prebuiltVoiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex$1(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex$1(fromVoiceConfig)); + } + if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) { + throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.'); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex$1(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$1(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex$1(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex$1(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$1(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex$1(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex$1(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$1(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$1(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$1(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex$1(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex$1(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex$1()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex$1(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToVertex(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + const fromTransparent = getValueByPath(fromObject, ['transparent']); + if (fromTransparent != null) { + setValueByPath(toObject, ['transparent'], fromTransparent); + } + return toObject; +} +function audioTranscriptionConfigToVertex() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToVertex(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToVertex(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToVertex(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToVertex(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToVertex(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToVertex(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToVertex(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToVertex$1(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToVertex(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToVertex()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToVertex()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToVertex(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToVertex(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToVertex(fromProactivity)); + } + return toObject; +} +function liveConnectParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function activityStartToVertex() { + const toObject = {}; + return toObject; +} +function activityEndToVertex() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToVertex(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + setValueByPath(toObject, ['mediaChunks'], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], activityStartToVertex()); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], activityEndToVertex()); + } + return toObject; +} +function liveServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function videoMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev$1(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$1(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function transcriptionFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFinished = getValueByPath(fromObject, ['finished']); + if (fromFinished != null) { + setValueByPath(toObject, ['finished'], fromFinished); + } + return toObject; +} +function urlMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$1(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function liveServerContentFromMldev(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn != null) { + setValueByPath(toObject, ['modelTurn'], contentFromMldev$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete != null) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted != null) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + 'generationComplete', + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ['generationComplete'], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + 'inputTranscription', + ]); + if (fromInputTranscription != null) { + setValueByPath(toObject, ['inputTranscription'], transcriptionFromMldev(fromInputTranscription)); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + 'outputTranscription', + ]); + if (fromOutputTranscription != null) { + setValueByPath(toObject, ['outputTranscription'], transcriptionFromMldev(fromOutputTranscription)); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev$1(fromUrlContextMetadata)); + } + return toObject; +} +function functionCallFromMldev(fromObject) { + const toObject = {}; + const fromId = getValueByPath(fromObject, ['id']); + if (fromId != null) { + setValueByPath(toObject, ['id'], fromId); + } + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromMldev(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromMldev(item); + }); + } + setValueByPath(toObject, ['functionCalls'], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromMldev(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds != null) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function modalityTokenCountFromMldev(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ['modality']); + if (fromModality != null) { + setValueByPath(toObject, ['modality'], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function usageMetadataFromMldev(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, [ + 'promptTokenCount', + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + 'responseTokenCount', + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ['responseTokenCount'], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + 'toolUsePromptTokenCount', + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ['toolUsePromptTokenCount'], fromToolUsePromptTokenCount); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + 'thoughtsTokenCount', + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ['thoughtsTokenCount'], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, [ + 'totalTokenCount', + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + 'promptTokensDetails', + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['promptTokensDetails'], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + 'cacheTokensDetails', + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['cacheTokensDetails'], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + 'responseTokensDetails', + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['responseTokensDetails'], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + 'toolUsePromptTokensDetails', + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['toolUsePromptTokensDetails'], transformedList); + } + return toObject; +} +function liveServerGoAwayFromMldev(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ['timeLeft']); + if (fromTimeLeft != null) { + setValueByPath(toObject, ['timeLeft'], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromMldev(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ['newHandle']); + if (fromNewHandle != null) { + setValueByPath(toObject, ['newHandle'], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ['resumable']); + if (fromResumable != null) { + setValueByPath(toObject, ['resumable'], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + 'lastConsumedClientMessageIndex', + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath(toObject, ['lastConsumedClientMessageIndex'], fromLastConsumedClientMessageIndex); + } + return toObject; +} +function liveServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveServerSetupCompleteFromMldev()); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromMldev(fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromMldev(fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromMldev(fromToolCallCancellation)); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], usageMetadataFromMldev(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject, ['goAway']); + if (fromGoAway != null) { + setValueByPath(toObject, ['goAway'], liveServerGoAwayFromMldev(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + 'sessionResumptionUpdate', + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ['sessionResumptionUpdate'], liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate)); + } + return toObject; +} +function liveMusicServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function weightedPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromWeight = getValueByPath(fromObject, ['weight']); + if (fromWeight != null) { + setValueByPath(toObject, ['weight'], fromWeight); + } + return toObject; +} +function liveMusicClientContentFromMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptFromMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigFromMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ['guidance']); + if (fromGuidance != null) { + setValueByPath(toObject, ['guidance'], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ['bpm']); + if (fromBpm != null) { + setValueByPath(toObject, ['bpm'], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ['density']); + if (fromDensity != null) { + setValueByPath(toObject, ['density'], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ['brightness']); + if (fromBrightness != null) { + setValueByPath(toObject, ['brightness'], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ['scale']); + if (fromScale != null) { + setValueByPath(toObject, ['scale'], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ['muteBass']); + if (fromMuteBass != null) { + setValueByPath(toObject, ['muteBass'], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ['muteDrums']); + if (fromMuteDrums != null) { + setValueByPath(toObject, ['muteDrums'], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, [ + 'onlyBassAndDrums', + ]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums); + } + const fromMusicGenerationMode = getValueByPath(fromObject, [ + 'musicGenerationMode', + ]); + if (fromMusicGenerationMode != null) { + setValueByPath(toObject, ['musicGenerationMode'], fromMusicGenerationMode); + } + return toObject; +} +function liveMusicSourceMetadataFromMldev(fromObject) { + const toObject = {}; + const fromClientContent = getValueByPath(fromObject, [ + 'clientContent', + ]); + if (fromClientContent != null) { + setValueByPath(toObject, ['clientContent'], liveMusicClientContentFromMldev(fromClientContent)); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig)); + } + return toObject; +} +function audioChunkFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSourceMetadata = getValueByPath(fromObject, [ + 'sourceMetadata', + ]); + if (fromSourceMetadata != null) { + setValueByPath(toObject, ['sourceMetadata'], liveMusicSourceMetadataFromMldev(fromSourceMetadata)); + } + return toObject; +} +function liveMusicServerContentFromMldev(fromObject) { + const toObject = {}; + const fromAudioChunks = getValueByPath(fromObject, ['audioChunks']); + if (fromAudioChunks != null) { + let transformedList = fromAudioChunks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return audioChunkFromMldev(item); + }); + } + setValueByPath(toObject, ['audioChunks'], transformedList); + } + return toObject; +} +function liveMusicFilteredPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFilteredReason = getValueByPath(fromObject, [ + 'filteredReason', + ]); + if (fromFilteredReason != null) { + setValueByPath(toObject, ['filteredReason'], fromFilteredReason); + } + return toObject; +} +function liveMusicServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveMusicServerSetupCompleteFromMldev()); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveMusicServerContentFromMldev(fromServerContent)); + } + const fromFilteredPrompt = getValueByPath(fromObject, [ + 'filteredPrompt', + ]); + if (fromFilteredPrompt != null) { + setValueByPath(toObject, ['filteredPrompt'], liveMusicFilteredPromptFromMldev(fromFilteredPrompt)); + } + return toObject; +} +function liveServerSetupCompleteFromVertex(fromObject) { + const toObject = {}; + const fromSessionId = getValueByPath(fromObject, ['sessionId']); + if (fromSessionId != null) { + setValueByPath(toObject, ['sessionId'], fromSessionId); + } + return toObject; +} +function videoMetadataFromVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromVertex$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function transcriptionFromVertex(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFinished = getValueByPath(fromObject, ['finished']); + if (fromFinished != null) { + setValueByPath(toObject, ['finished'], fromFinished); + } + return toObject; +} +function liveServerContentFromVertex(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn != null) { + setValueByPath(toObject, ['modelTurn'], contentFromVertex$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete != null) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted != null) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + 'generationComplete', + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ['generationComplete'], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + 'inputTranscription', + ]); + if (fromInputTranscription != null) { + setValueByPath(toObject, ['inputTranscription'], transcriptionFromVertex(fromInputTranscription)); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + 'outputTranscription', + ]); + if (fromOutputTranscription != null) { + setValueByPath(toObject, ['outputTranscription'], transcriptionFromVertex(fromOutputTranscription)); + } + return toObject; +} +function functionCallFromVertex(fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromVertex(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromVertex(item); + }); + } + setValueByPath(toObject, ['functionCalls'], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromVertex(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds != null) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function modalityTokenCountFromVertex(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ['modality']); + if (fromModality != null) { + setValueByPath(toObject, ['modality'], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function usageMetadataFromVertex(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, [ + 'promptTokenCount', + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + 'candidatesTokenCount', + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ['responseTokenCount'], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + 'toolUsePromptTokenCount', + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ['toolUsePromptTokenCount'], fromToolUsePromptTokenCount); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + 'thoughtsTokenCount', + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ['thoughtsTokenCount'], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, [ + 'totalTokenCount', + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + 'promptTokensDetails', + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['promptTokensDetails'], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + 'cacheTokensDetails', + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['cacheTokensDetails'], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + 'candidatesTokensDetails', + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['responseTokensDetails'], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + 'toolUsePromptTokensDetails', + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['toolUsePromptTokensDetails'], transformedList); + } + const fromTrafficType = getValueByPath(fromObject, ['trafficType']); + if (fromTrafficType != null) { + setValueByPath(toObject, ['trafficType'], fromTrafficType); + } + return toObject; +} +function liveServerGoAwayFromVertex(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ['timeLeft']); + if (fromTimeLeft != null) { + setValueByPath(toObject, ['timeLeft'], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromVertex(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ['newHandle']); + if (fromNewHandle != null) { + setValueByPath(toObject, ['newHandle'], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ['resumable']); + if (fromResumable != null) { + setValueByPath(toObject, ['resumable'], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + 'lastConsumedClientMessageIndex', + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath(toObject, ['lastConsumedClientMessageIndex'], fromLastConsumedClientMessageIndex); + } + return toObject; +} +function liveServerMessageFromVertex(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveServerSetupCompleteFromVertex(fromSetupComplete)); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromVertex(fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromVertex(fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromVertex(fromToolCallCancellation)); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], usageMetadataFromVertex(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject, ['goAway']); + if (fromGoAway != null) { + setValueByPath(toObject, ['goAway'], liveServerGoAwayFromVertex(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + 'sessionResumptionUpdate', + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ['sessionResumptionUpdate'], liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$1(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$1(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$1(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$1(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$1(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$1(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$1(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$1()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$1(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$1(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$1(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$1(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$1(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$1(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$1(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToMldev(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToMldev$1(tSpeechConfig(fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev(fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['requests[]', 'taskType'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['requests[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['requests[]', 'outputDimensionality'], fromOutputDimensionality); + } + if (getValueByPath(fromObject, ['mimeType']) !== undefined) { + throw new Error('mimeType parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['autoTruncate']) !== undefined) { + throw new Error('autoTruncate parameter is not supported in Gemini API.'); + } + return toObject; +} +function embedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + setValueByPath(toObject, ['requests[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToMldev(fromConfig, toObject)); + } + const fromModelForEmbedContent = getValueByPath(fromObject, ['model']); + if (fromModelForEmbedContent !== undefined) { + setValueByPath(toObject, ['requests[]', 'model'], tModel(apiClient, fromModelForEmbedContent)); + } + return toObject; +} +function generateImagesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['negativePrompt']) !== undefined) { + throw new Error('negativePrompt parameter is not supported in Gemini API.'); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + if (getValueByPath(fromObject, ['addWatermark']) !== undefined) { + throw new Error('addWatermark parameter is not supported in Gemini API.'); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath(parentObject, ['parameters', 'sampleImageSize'], fromImageSize); + } + if (getValueByPath(fromObject, ['enhancePrompt']) !== undefined) { + throw new Error('enhancePrompt parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateImagesParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateImagesConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listModelsConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listModelsConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function updateModelConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateModelConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function deleteModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function countTokensConfigToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['systemInstruction']) !== undefined) { + throw new Error('systemInstruction parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['tools']) !== undefined) { + throw new Error('tools parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['generationConfig']) !== undefined) { + throw new Error('generationConfig parameter is not supported in Gemini API.'); + } + return toObject; +} +function countTokensParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToMldev(fromConfig)); + } + return toObject; +} +function imageToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['fps']) !== undefined) { + throw new Error('fps parameter is not supported in Gemini API.'); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + if (getValueByPath(fromObject, ['resolution']) !== undefined) { + throw new Error('resolution parameter is not supported in Gemini API.'); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + if (getValueByPath(fromObject, ['pubsubTopic']) !== undefined) { + throw new Error('pubsubTopic parameter is not supported in Gemini API.'); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + if (getValueByPath(fromObject, ['generateAudio']) !== undefined) { + throw new Error('generateAudio parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['lastFrame']) !== undefined) { + throw new Error('lastFrame parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['referenceImages']) !== undefined) { + throw new Error('referenceImages parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['compressionQuality']) !== undefined) { + throw new Error('compressionQuality parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateVideosParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToMldev(fromImage)); + } + if (getValueByPath(fromObject, ['video']) !== undefined) { + throw new Error('video parameter is not supported in Gemini API.'); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataToVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToVertex(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function modelSelectionConfigToVertex(fromObject) { + const toObject = {}; + const fromFeatureSelectionPreference = getValueByPath(fromObject, [ + 'featureSelectionPreference', + ]); + if (fromFeatureSelectionPreference != null) { + setValueByPath(toObject, ['featureSelectionPreference'], fromFeatureSelectionPreference); + } + return toObject; +} +function safetySettingToVertex(fromObject) { + const toObject = {}; + const fromMethod = getValueByPath(fromObject, ['method']); + if (fromMethod != null) { + setValueByPath(toObject, ['method'], fromMethod); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToVertex(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToVertex(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToVertex(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex(fromVoiceConfig)); + } + if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) { + throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.'); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToVertex(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToVertex(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + const fromRoutingConfig = getValueByPath(fromObject, [ + 'routingConfig', + ]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ['routingConfig'], fromRoutingConfig); + } + const fromModelSelectionConfig = getValueByPath(fromObject, [ + 'modelSelectionConfig', + ]); + if (fromModelSelectionConfig != null) { + setValueByPath(toObject, ['modelConfig'], modelSelectionConfigToVertex(fromModelSelectionConfig)); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToVertex(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex(fromToolConfig)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ['labels'], fromLabels); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToVertex(tSpeechConfig(fromSpeechConfig))); + } + const fromAudioTimestamp = getValueByPath(fromObject, [ + 'audioTimestamp', + ]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToVertex(fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['instances[]', 'task_type'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['instances[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['parameters', 'outputDimensionality'], fromOutputDimensionality); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (parentObject !== undefined && fromMimeType != null) { + setValueByPath(parentObject, ['instances[]', 'mimeType'], fromMimeType); + } + const fromAutoTruncate = getValueByPath(fromObject, ['autoTruncate']); + if (parentObject !== undefined && fromAutoTruncate != null) { + setValueByPath(parentObject, ['parameters', 'autoTruncate'], fromAutoTruncate); + } + return toObject; +} +function embedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + setValueByPath(toObject, ['instances[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function generateImagesConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath(parentObject, ['parameters', 'sampleImageSize'], fromImageSize); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function generateImagesParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateImagesConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function imageToVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function maskReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromMaskMode = getValueByPath(fromObject, ['maskMode']); + if (fromMaskMode != null) { + setValueByPath(toObject, ['maskMode'], fromMaskMode); + } + const fromSegmentationClasses = getValueByPath(fromObject, [ + 'segmentationClasses', + ]); + if (fromSegmentationClasses != null) { + setValueByPath(toObject, ['maskClasses'], fromSegmentationClasses); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (fromMaskDilation != null) { + setValueByPath(toObject, ['dilation'], fromMaskDilation); + } + return toObject; +} +function controlReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromControlType = getValueByPath(fromObject, ['controlType']); + if (fromControlType != null) { + setValueByPath(toObject, ['controlType'], fromControlType); + } + const fromEnableControlImageComputation = getValueByPath(fromObject, [ + 'enableControlImageComputation', + ]); + if (fromEnableControlImageComputation != null) { + setValueByPath(toObject, ['computeControl'], fromEnableControlImageComputation); + } + return toObject; +} +function styleReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromStyleDescription = getValueByPath(fromObject, [ + 'styleDescription', + ]); + if (fromStyleDescription != null) { + setValueByPath(toObject, ['styleDescription'], fromStyleDescription); + } + return toObject; +} +function subjectReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromSubjectType = getValueByPath(fromObject, ['subjectType']); + if (fromSubjectType != null) { + setValueByPath(toObject, ['subjectType'], fromSubjectType); + } + const fromSubjectDescription = getValueByPath(fromObject, [ + 'subjectDescription', + ]); + if (fromSubjectDescription != null) { + setValueByPath(toObject, ['subjectDescription'], fromSubjectDescription); + } + return toObject; +} +function referenceImageAPIInternalToVertex(fromObject) { + const toObject = {}; + const fromReferenceImage = getValueByPath(fromObject, [ + 'referenceImage', + ]); + if (fromReferenceImage != null) { + setValueByPath(toObject, ['referenceImage'], imageToVertex(fromReferenceImage)); + } + const fromReferenceId = getValueByPath(fromObject, ['referenceId']); + if (fromReferenceId != null) { + setValueByPath(toObject, ['referenceId'], fromReferenceId); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + const fromMaskImageConfig = getValueByPath(fromObject, [ + 'maskImageConfig', + ]); + if (fromMaskImageConfig != null) { + setValueByPath(toObject, ['maskImageConfig'], maskReferenceConfigToVertex(fromMaskImageConfig)); + } + const fromControlImageConfig = getValueByPath(fromObject, [ + 'controlImageConfig', + ]); + if (fromControlImageConfig != null) { + setValueByPath(toObject, ['controlImageConfig'], controlReferenceConfigToVertex(fromControlImageConfig)); + } + const fromStyleImageConfig = getValueByPath(fromObject, [ + 'styleImageConfig', + ]); + if (fromStyleImageConfig != null) { + setValueByPath(toObject, ['styleImageConfig'], styleReferenceConfigToVertex(fromStyleImageConfig)); + } + const fromSubjectImageConfig = getValueByPath(fromObject, [ + 'subjectImageConfig', + ]); + if (fromSubjectImageConfig != null) { + setValueByPath(toObject, ['subjectImageConfig'], subjectReferenceConfigToVertex(fromSubjectImageConfig)); + } + return toObject; +} +function editImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromEditMode = getValueByPath(fromObject, ['editMode']); + if (parentObject !== undefined && fromEditMode != null) { + setValueByPath(parentObject, ['parameters', 'editMode'], fromEditMode); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'editConfig', 'baseSteps'], fromBaseSteps); + } + return toObject; +} +function editImageParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return referenceImageAPIInternalToVertex(item); + }); + } + setValueByPath(toObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], editImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function upscaleImageAPIConfigInternalToVertex(fromObject, parentObject) { + const toObject = {}; + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhanceInputImage = getValueByPath(fromObject, [ + 'enhanceInputImage', + ]); + if (parentObject !== undefined && fromEnhanceInputImage != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'enhanceInputImage'], fromEnhanceInputImage); + } + const fromImagePreservationFactor = getValueByPath(fromObject, [ + 'imagePreservationFactor', + ]); + if (parentObject !== undefined && fromImagePreservationFactor != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'imagePreservationFactor'], fromImagePreservationFactor); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + return toObject; +} +function upscaleImageAPIParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromUpscaleFactor = getValueByPath(fromObject, [ + 'upscaleFactor', + ]); + if (fromUpscaleFactor != null) { + setValueByPath(toObject, ['parameters', 'upscaleConfig', 'upscaleFactor'], fromUpscaleFactor); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], upscaleImageAPIConfigInternalToVertex(fromConfig, toObject)); + } + return toObject; +} +function productImageToVertex(fromObject) { + const toObject = {}; + const fromProductImage = getValueByPath(fromObject, ['productImage']); + if (fromProductImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromProductImage)); + } + return toObject; +} +function recontextImageSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromPersonImage = getValueByPath(fromObject, ['personImage']); + if (parentObject !== undefined && fromPersonImage != null) { + setValueByPath(parentObject, ['instances[0]', 'personImage', 'image'], imageToVertex(fromPersonImage)); + } + const fromProductImages = getValueByPath(fromObject, [ + 'productImages', + ]); + if (parentObject !== undefined && fromProductImages != null) { + let transformedList = fromProductImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return productImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'productImages'], transformedList); + } + return toObject; +} +function recontextImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'editConfig', 'baseSteps'], fromBaseSteps); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function recontextImageParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], recontextImageSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], recontextImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function scribbleImageToVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + return toObject; +} +function segmentImageSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromScribbleImage = getValueByPath(fromObject, [ + 'scribbleImage', + ]); + if (parentObject !== undefined && fromScribbleImage != null) { + setValueByPath(parentObject, ['instances[0]', 'scribble'], scribbleImageToVertex(fromScribbleImage)); + } + return toObject; +} +function segmentImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + const fromMaxPredictions = getValueByPath(fromObject, [ + 'maxPredictions', + ]); + if (parentObject !== undefined && fromMaxPredictions != null) { + setValueByPath(parentObject, ['parameters', 'maxPredictions'], fromMaxPredictions); + } + const fromConfidenceThreshold = getValueByPath(fromObject, [ + 'confidenceThreshold', + ]); + if (parentObject !== undefined && fromConfidenceThreshold != null) { + setValueByPath(parentObject, ['parameters', 'confidenceThreshold'], fromConfidenceThreshold); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (parentObject !== undefined && fromMaskDilation != null) { + setValueByPath(parentObject, ['parameters', 'maskDilation'], fromMaskDilation); + } + const fromBinaryColorThreshold = getValueByPath(fromObject, [ + 'binaryColorThreshold', + ]); + if (parentObject !== undefined && fromBinaryColorThreshold != null) { + setValueByPath(parentObject, ['parameters', 'binaryColorThreshold'], fromBinaryColorThreshold); + } + return toObject; +} +function segmentImageParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], segmentImageSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], segmentImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listModelsConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listModelsConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function updateModelConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateModelConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function deleteModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function countTokensConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['generationConfig'], fromGenerationConfig); + } + return toObject; +} +function countTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function computeTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoToVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['gcsUri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ['videoBytes']); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function videoGenerationReferenceImageToVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + return toObject; +} +function generateVideosConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromFps = getValueByPath(fromObject, ['fps']); + if (parentObject !== undefined && fromFps != null) { + setValueByPath(parentObject, ['parameters', 'fps'], fromFps); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromResolution = getValueByPath(fromObject, ['resolution']); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ['parameters', 'resolution'], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromPubsubTopic = getValueByPath(fromObject, ['pubsubTopic']); + if (parentObject !== undefined && fromPubsubTopic != null) { + setValueByPath(parentObject, ['parameters', 'pubsubTopic'], fromPubsubTopic); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + const fromGenerateAudio = getValueByPath(fromObject, [ + 'generateAudio', + ]); + if (parentObject !== undefined && fromGenerateAudio != null) { + setValueByPath(parentObject, ['parameters', 'generateAudio'], fromGenerateAudio); + } + const fromLastFrame = getValueByPath(fromObject, ['lastFrame']); + if (parentObject !== undefined && fromLastFrame != null) { + setValueByPath(parentObject, ['instances[0]', 'lastFrame'], imageToVertex(fromLastFrame)); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (parentObject !== undefined && fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return videoGenerationReferenceImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromCompressionQuality = getValueByPath(fromObject, [ + 'compressionQuality', + ]); + if (parentObject !== undefined && fromCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'compressionQuality'], fromCompressionQuality); + } + return toObject; +} +function generateVideosParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['instances[0]', 'video'], videoToVertex(fromVideo)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataFromMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromMldev(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingFromMldev(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + return toObject; +} +function embedContentMetadataFromMldev() { + const toObject = {}; + return toObject; +} +function embedContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, ['embeddings']); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromMldev(item); + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromMldev()); + } + return toObject; +} +function imageFromMldev(fromObject) { + const toObject = {}; + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromMldev(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + 'safetyAttributes', + 'categories', + ]); + if (fromCategories != null) { + setValueByPath(toObject, ['categories'], fromCategories); + } + const fromScores = getValueByPath(fromObject, [ + 'safetyAttributes', + 'scores', + ]); + if (fromScores != null) { + setValueByPath(toObject, ['scores'], fromScores); + } + const fromContentType = getValueByPath(fromObject, ['contentType']); + if (fromContentType != null) { + setValueByPath(toObject, ['contentType'], fromContentType); + } + return toObject; +} +function generatedImageFromMldev(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromMldev(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromMldev(fromSafetyAttributes)); + } + return toObject; +} +function generateImagesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromMldev(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromMldev(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function tunedModelInfoFromMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function modelFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['version']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromMldev(fromTunedModelInfo)); + } + const fromInputTokenLimit = getValueByPath(fromObject, [ + 'inputTokenLimit', + ]); + if (fromInputTokenLimit != null) { + setValueByPath(toObject, ['inputTokenLimit'], fromInputTokenLimit); + } + const fromOutputTokenLimit = getValueByPath(fromObject, [ + 'outputTokenLimit', + ]); + if (fromOutputTokenLimit != null) { + setValueByPath(toObject, ['outputTokenLimit'], fromOutputTokenLimit); + } + const fromSupportedActions = getValueByPath(fromObject, [ + 'supportedGenerationMethods', + ]); + if (fromSupportedActions != null) { + setValueByPath(toObject, ['supportedActions'], fromSupportedActions); + } + return toObject; +} +function listModelsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromMldev(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function deleteModelResponseFromMldev() { + const toObject = {}; + return toObject; +} +function countTokensResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + return toObject; +} +function videoFromMldev(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['video', 'uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'video', + 'encodedVideo', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['encoding']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromMldev(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, [ + 'generatedSamples', + ]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromMldev(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosOperationFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, [ + 'response', + 'generateVideoResponse', + ]); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromMldev(fromResponse)); + } + return toObject; +} +function videoMetadataFromVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromVertex(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromVertex(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citations']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromVertex(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromVertex(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromVertex(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromVertex(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromVertex(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromVertex(fromCitationMetadata)); + } + const fromFinishMessage = getValueByPath(fromObject, [ + 'finishMessage', + ]); + if (fromFinishMessage != null) { + setValueByPath(toObject, ['finishMessage'], fromFinishMessage); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromVertex(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromVertex(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingStatisticsFromVertex(fromObject) { + const toObject = {}; + const fromTruncated = getValueByPath(fromObject, ['truncated']); + if (fromTruncated != null) { + setValueByPath(toObject, ['truncated'], fromTruncated); + } + const fromTokenCount = getValueByPath(fromObject, ['token_count']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function contentEmbeddingFromVertex(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + const fromStatistics = getValueByPath(fromObject, ['statistics']); + if (fromStatistics != null) { + setValueByPath(toObject, ['statistics'], contentEmbeddingStatisticsFromVertex(fromStatistics)); + } + return toObject; +} +function embedContentMetadataFromVertex(fromObject) { + const toObject = {}; + const fromBillableCharacterCount = getValueByPath(fromObject, [ + 'billableCharacterCount', + ]); + if (fromBillableCharacterCount != null) { + setValueByPath(toObject, ['billableCharacterCount'], fromBillableCharacterCount); + } + return toObject; +} +function embedContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, [ + 'predictions[]', + 'embeddings', + ]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromVertex(item); + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromVertex(fromMetadata)); + } + return toObject; +} +function imageFromVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromVertex(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + 'safetyAttributes', + 'categories', + ]); + if (fromCategories != null) { + setValueByPath(toObject, ['categories'], fromCategories); + } + const fromScores = getValueByPath(fromObject, [ + 'safetyAttributes', + 'scores', + ]); + if (fromScores != null) { + setValueByPath(toObject, ['scores'], fromScores); + } + const fromContentType = getValueByPath(fromObject, ['contentType']); + if (fromContentType != null) { + setValueByPath(toObject, ['contentType'], fromContentType); + } + return toObject; +} +function generatedImageFromVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromVertex(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromVertex(fromSafetyAttributes)); + } + const fromEnhancedPrompt = getValueByPath(fromObject, ['prompt']); + if (fromEnhancedPrompt != null) { + setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt); + } + return toObject; +} +function generateImagesResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromVertex(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function editImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function upscaleImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function recontextImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function entityLabelFromVertex(fromObject) { + const toObject = {}; + const fromLabel = getValueByPath(fromObject, ['label']); + if (fromLabel != null) { + setValueByPath(toObject, ['label'], fromLabel); + } + const fromScore = getValueByPath(fromObject, ['score']); + if (fromScore != null) { + setValueByPath(toObject, ['score'], fromScore); + } + return toObject; +} +function generatedImageMaskFromVertex(fromObject) { + const toObject = {}; + const fromMask = getValueByPath(fromObject, ['_self']); + if (fromMask != null) { + setValueByPath(toObject, ['mask'], imageFromVertex(fromMask)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + let transformedList = fromLabels; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return entityLabelFromVertex(item); + }); + } + setValueByPath(toObject, ['labels'], transformedList); + } + return toObject; +} +function segmentImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedMasks = getValueByPath(fromObject, ['predictions']); + if (fromGeneratedMasks != null) { + let transformedList = fromGeneratedMasks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageMaskFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedMasks'], transformedList); + } + return toObject; +} +function endpointFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['endpoint']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDeployedModelId = getValueByPath(fromObject, [ + 'deployedModelId', + ]); + if (fromDeployedModelId != null) { + setValueByPath(toObject, ['deployedModelId'], fromDeployedModelId); + } + return toObject; +} +function tunedModelInfoFromVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, [ + 'labels', + 'google-vertex-llm-tuning-base-model-id', + ]); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function checkpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ['checkpointId']); + if (fromCheckpointId != null) { + setValueByPath(toObject, ['checkpointId'], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ['epoch']); + if (fromEpoch != null) { + setValueByPath(toObject, ['epoch'], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ['step']); + if (fromStep != null) { + setValueByPath(toObject, ['step'], fromStep); + } + return toObject; +} +function modelFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['versionId']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromEndpoints = getValueByPath(fromObject, ['deployedModels']); + if (fromEndpoints != null) { + let transformedList = fromEndpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return endpointFromVertex(item); + }); + } + setValueByPath(toObject, ['endpoints'], transformedList); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromVertex(fromTunedModelInfo)); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (fromDefaultCheckpointId != null) { + setValueByPath(toObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + const fromCheckpoints = getValueByPath(fromObject, ['checkpoints']); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return checkpointFromVertex(item); + }); + } + setValueByPath(toObject, ['checkpoints'], transformedList); + } + return toObject; +} +function listModelsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromVertex(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function deleteModelResponseFromVertex() { + const toObject = {}; + return toObject; +} +function countTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + return toObject; +} +function computeTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTokensInfo = getValueByPath(fromObject, ['tokensInfo']); + if (fromTokensInfo != null) { + setValueByPath(toObject, ['tokensInfo'], fromTokensInfo); + } + return toObject; +} +function videoFromVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['gcsUri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromVertex(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ['videos']); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosOperationFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromVertex(fromResponse)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const CONTENT_TYPE_HEADER = 'Content-Type'; +const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout'; +const USER_AGENT_HEADER = 'User-Agent'; +const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client'; +const SDK_VERSION = '1.15.0'; // x-release-please-version +const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`; +const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1'; +const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta'; +const responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/; +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +class ApiClient { + constructor(opts) { + var _a, _b; + this.clientOptions = Object.assign(Object.assign({}, opts), { project: opts.project, location: opts.location, apiKey: opts.apiKey, vertexai: opts.vertexai }); + const initHttpOptions = {}; + if (this.clientOptions.vertexai) { + initHttpOptions.apiVersion = + (_a = this.clientOptions.apiVersion) !== null && _a !== void 0 ? _a : VERTEX_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = this.baseUrlFromProjectLocation(); + this.normalizeAuthParameters(); + } + else { + // Gemini API + initHttpOptions.apiVersion = + (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 ? _b : GOOGLE_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`; + } + initHttpOptions.headers = this.getDefaultHeaders(); + this.clientOptions.httpOptions = initHttpOptions; + if (opts.httpOptions) { + this.clientOptions.httpOptions = this.patchHttpOptions(initHttpOptions, opts.httpOptions); + } + } + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + baseUrlFromProjectLocation() { + if (this.clientOptions.project && + this.clientOptions.location && + this.clientOptions.location !== 'global') { + // Regional endpoint + return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`; + } + // Global endpoint (covers 'global' location and API key usage) + return `https://aiplatform.googleapis.com/`; + } + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + normalizeAuthParameters() { + if (this.clientOptions.project && this.clientOptions.location) { + // Using project/location for auth, clear potential API key + this.clientOptions.apiKey = undefined; + return; + } + // Using API key for auth (or no auth provided yet), clear project/location + this.clientOptions.project = undefined; + this.clientOptions.location = undefined; + } + isVertexAI() { + var _a; + return (_a = this.clientOptions.vertexai) !== null && _a !== void 0 ? _a : false; + } + getProject() { + return this.clientOptions.project; + } + getLocation() { + return this.clientOptions.location; + } + getApiVersion() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.apiVersion !== undefined) { + return this.clientOptions.httpOptions.apiVersion; + } + throw new Error('API version is not set.'); + } + getBaseUrl() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.baseUrl !== undefined) { + return this.clientOptions.httpOptions.baseUrl; + } + throw new Error('Base URL is not set.'); + } + getRequestUrl() { + return this.getRequestUrlInternal(this.clientOptions.httpOptions); + } + getHeaders() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.headers !== undefined) { + return this.clientOptions.httpOptions.headers; + } + else { + throw new Error('Headers are not set.'); + } + } + getRequestUrlInternal(httpOptions) { + if (!httpOptions || + httpOptions.baseUrl === undefined || + httpOptions.apiVersion === undefined) { + throw new Error('HTTP options are not correctly set.'); + } + const baseUrl = httpOptions.baseUrl.endsWith('/') + ? httpOptions.baseUrl.slice(0, -1) + : httpOptions.baseUrl; + const urlElement = [baseUrl]; + if (httpOptions.apiVersion && httpOptions.apiVersion !== '') { + urlElement.push(httpOptions.apiVersion); + } + return urlElement.join('/'); + } + getBaseResourcePath() { + return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`; + } + getApiKey() { + return this.clientOptions.apiKey; + } + getWebsocketBaseUrl() { + const baseUrl = this.getBaseUrl(); + const urlParts = new URL(baseUrl); + urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss'; + return urlParts.toString(); + } + setBaseUrl(url) { + if (this.clientOptions.httpOptions) { + this.clientOptions.httpOptions.baseUrl = url; + } + else { + throw new Error('HTTP options are not correctly set.'); + } + } + constructUrl(path, httpOptions, prependProjectLocation) { + const urlElement = [this.getRequestUrlInternal(httpOptions)]; + if (prependProjectLocation) { + urlElement.push(this.getBaseResourcePath()); + } + if (path !== '') { + urlElement.push(path); + } + const url = new URL(`${urlElement.join('/')}`); + return url; + } + shouldPrependVertexProjectPath(request) { + if (this.clientOptions.apiKey) { + return false; + } + if (!this.clientOptions.vertexai) { + return false; + } + if (request.path.startsWith('projects/')) { + // Assume the path already starts with + // `projects//location/`. + return false; + } + if (request.httpMethod === 'GET' && + request.path.startsWith('publishers/google/models')) { + // These paths are used by Vertex's models.get and models.list + // calls. For base models Vertex does not accept a project/location + // prefix (for tuned model the prefix is required). + return false; + } + return true; + } + async request(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (request.queryParams) { + for (const [key, value] of Object.entries(request.queryParams)) { + url.searchParams.append(key, String(value)); + } + } + let requestInit = {}; + if (request.httpMethod === 'GET') { + if (request.body && request.body !== '{}') { + throw new Error('Request body should be empty for GET request, but got non empty request body'); + } + } + else { + requestInit.body = request.body; + } + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal); + return this.unaryApiCall(url, requestInit, request.httpMethod); + } + patchHttpOptions(baseHttpOptions, requestHttpOptions) { + const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions)); + for (const [key, value] of Object.entries(requestHttpOptions)) { + // Records compile to objects. + if (typeof value === 'object') { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = Object.assign(Object.assign({}, patchedHttpOptions[key]), value); + } + else if (value !== undefined) { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = value; + } + } + return patchedHttpOptions; + } + async requestStream(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') { + url.searchParams.set('alt', 'sse'); + } + let requestInit = {}; + requestInit.body = request.body; + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal); + return this.streamApiCall(url, requestInit, request.httpMethod); + } + async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions, abortSignal) { + if ((httpOptions && httpOptions.timeout) || abortSignal) { + const abortController = new AbortController(); + const signal = abortController.signal; + if (httpOptions.timeout && (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) > 0) { + const timeoutHandle = setTimeout(() => abortController.abort(), httpOptions.timeout); + if (timeoutHandle && + typeof timeoutHandle.unref === + 'function') { + // call unref to prevent nodejs process from hanging, see + // https://nodejs.org/api/timers.html#timeoutunref + timeoutHandle.unref(); + } + } + if (abortSignal) { + abortSignal.addEventListener('abort', () => { + abortController.abort(); + }); + } + requestInit.signal = signal; + } + if (httpOptions && httpOptions.extraBody !== null) { + includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody); + } + requestInit.headers = await this.getHeadersInternal(httpOptions); + return requestInit; + } + async unaryApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return new HttpResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + async streamApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return this.processStreamResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + processStreamResponse(response) { + var _a; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + const reader = (_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.getReader(); + const decoder = new TextDecoder('utf-8'); + if (!reader) { + throw new Error('Response body is empty'); + } + try { + let buffer = ''; + while (true) { + const { done, value } = yield __await(reader.read()); + if (done) { + if (buffer.trim().length > 0) { + throw new Error('Incomplete JSON segment at the end'); + } + break; + } + const chunkString = decoder.decode(value, { stream: true }); + // Parse and throw an error if the chunk contains an error. + try { + const chunkJson = JSON.parse(chunkString); + if ('error' in chunkJson) { + const errorJson = JSON.parse(JSON.stringify(chunkJson['error'])); + const status = errorJson['status']; + const code = errorJson['code']; + const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`; + if (code >= 400 && code < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: code, + }); + throw apiError; + } + } + } + catch (e) { + const error = e; + if (error.name === 'ApiError') { + throw e; + } + } + buffer += chunkString; + let match = buffer.match(responseLineRE); + while (match) { + const processedChunkString = match[1]; + try { + const partialResponse = new Response(processedChunkString, { + headers: response === null || response === void 0 ? void 0 : response.headers, + status: response === null || response === void 0 ? void 0 : response.status, + statusText: response === null || response === void 0 ? void 0 : response.statusText, + }); + yield yield __await(new HttpResponse(partialResponse)); + buffer = buffer.slice(match[0].length); + match = buffer.match(responseLineRE); + } + catch (e) { + throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`); + } + } + } + } + finally { + reader.releaseLock(); + } + }); + } + async apiCall(url, requestInit) { + return fetch(url, requestInit).catch((e) => { + throw new Error(`exception ${e} sending request`); + }); + } + getDefaultHeaders() { + const headers = {}; + const versionHeaderValue = LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra; + headers[USER_AGENT_HEADER] = versionHeaderValue; + headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue; + headers[CONTENT_TYPE_HEADER] = 'application/json'; + return headers; + } + async getHeadersInternal(httpOptions) { + const headers = new Headers(); + if (httpOptions && httpOptions.headers) { + for (const [key, value] of Object.entries(httpOptions.headers)) { + headers.append(key, value); + } + // Append a timeout header if it is set, note that the timeout option is + // in milliseconds but the header is in seconds. + if (httpOptions.timeout && httpOptions.timeout > 0) { + headers.append(SERVER_TIMEOUT_HEADER, String(Math.ceil(httpOptions.timeout / 1000))); + } + } + await this.clientOptions.auth.addAuthHeaders(headers); + return headers; + } + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + async uploadFile(file, config) { + var _a; + const fileToUpload = {}; + if (config != null) { + fileToUpload.mimeType = config.mimeType; + fileToUpload.name = config.name; + fileToUpload.displayName = config.displayName; + } + if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) { + fileToUpload.name = `files/${fileToUpload.name}`; + } + const uploader = this.clientOptions.uploader; + const fileStat = await uploader.stat(file); + fileToUpload.sizeBytes = String(fileStat.size); + const mimeType = (_a = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a !== void 0 ? _a : fileStat.type; + if (mimeType === undefined || mimeType === '') { + throw new Error('Can not determine mimeType. Please provide mimeType in the config.'); + } + fileToUpload.mimeType = mimeType; + const uploadUrl = await this.fetchUploadUrl(fileToUpload, config); + return uploader.upload(file, uploadUrl, this); + } + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + async downloadFile(params) { + const downloader = this.clientOptions.downloader; + await downloader.download(params, this); + } + async fetchUploadUrl(file, config) { + var _a; + let httpOptions = {}; + if (config === null || config === void 0 ? void 0 : config.httpOptions) { + httpOptions = config.httpOptions; + } + else { + httpOptions = { + apiVersion: '', + headers: { + 'Content-Type': 'application/json', + 'X-Goog-Upload-Protocol': 'resumable', + 'X-Goog-Upload-Command': 'start', + 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`, + 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`, + }, + }; + } + const body = { + 'file': file, + }; + const httpResponse = await this.request({ + path: formatMap('upload/v1beta/files', body['_url']), + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions, + }); + if (!httpResponse || !(httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers)) { + throw new Error('Server did not return an HttpResponse or the returned HttpResponse did not have headers.'); + } + const uploadUrl = (_a = httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers) === null || _a === void 0 ? void 0 : _a['x-goog-upload-url']; + if (uploadUrl === undefined) { + throw new Error('Failed to get upload url. Server did not return the x-google-upload-url in the headers'); + } + return uploadUrl; + } +} +async function throwErrorIfNotOK(response) { + var _a; + if (response === undefined) { + throw new Error('response is undefined'); + } + if (!response.ok) { + const status = response.status; + let errorBody; + if ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('application/json')) { + errorBody = await response.json(); + } + else { + errorBody = { + error: { + message: await response.text(), + code: response.status, + status: response.statusText, + }, + }; + } + const errorMessage = JSON.stringify(errorBody); + if (status >= 400 && status < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: status, + }); + throw apiError; + } + throw new Error(errorMessage); + } +} +/** + * Recursively updates the `requestInit.body` with values from an `extraBody` object. + * + * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed. + * The `extraBody` is then deeply merged into this parsed object. + * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged, + * as merging structured data into an opaque Blob is not supported. + * + * The function does not enforce that updated values from `extraBody` have the + * same type as existing values in `requestInit.body`. Type mismatches during + * the merge will result in a warning, but the value from `extraBody` will overwrite + * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure. + * + * @param requestInit The RequestInit object whose body will be updated. + * @param extraBody The object containing updates to be merged into `requestInit.body`. + */ +function includeExtraBodyToRequestInit(requestInit, extraBody) { + if (!extraBody || Object.keys(extraBody).length === 0) { + return; + } + if (requestInit.body instanceof Blob) { + console.warn('includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.'); + return; + } + let currentBodyObject = {}; + // If adding new type to HttpRequest.body, please check the code below to + // see if we need to update the logic. + if (typeof requestInit.body === 'string' && requestInit.body.length > 0) { + try { + const parsedBody = JSON.parse(requestInit.body); + if (typeof parsedBody === 'object' && + parsedBody !== null && + !Array.isArray(parsedBody)) { + currentBodyObject = parsedBody; + } + else { + console.warn('includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.'); + return; + } + /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ + } + catch (e) { + console.warn('includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.'); + return; + } + } + function deepMerge(target, source) { + const output = Object.assign({}, target); + for (const key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + const sourceValue = source[key]; + const targetValue = output[key]; + if (sourceValue && + typeof sourceValue === 'object' && + !Array.isArray(sourceValue) && + targetValue && + typeof targetValue === 'object' && + !Array.isArray(targetValue)) { + output[key] = deepMerge(targetValue, sourceValue); + } + else { + if (targetValue && + sourceValue && + typeof targetValue !== typeof sourceValue) { + console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`); + } + output[key] = sourceValue; + } + } + } + return output; + } + const mergedBody = deepMerge(currentBodyObject, extraBody); + requestInit.body = JSON.stringify(mergedBody); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// TODO: b/416041229 - Determine how to retrieve the MCP package version. +const MCP_LABEL = 'mcp_used/unknown'; +// Whether MCP tool usage is detected from mcpToTool. This is used for +// telemetry. +let hasMcpToolUsageFromMcpToTool = false; +// Checks whether the list of tools contains any MCP tools. +function hasMcpToolUsage(tools) { + for (const tool of tools) { + if (isMcpCallableTool(tool)) { + return true; + } + if (typeof tool === 'object' && 'inputSchema' in tool) { + return true; + } + } + return hasMcpToolUsageFromMcpToTool; +} +// Sets the MCP version label in the Google API client header. +function setMcpUsageHeader(headers) { + var _a; + const existingHeader = (_a = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a !== void 0 ? _a : ''; + headers[GOOGLE_API_CLIENT_HEADER] = (existingHeader + ` ${MCP_LABEL}`).trimStart(); +} +// Returns true if the object is a MCP CallableTool, otherwise false. +function isMcpCallableTool(object) { + return (object !== null && + typeof object === 'object' && + object instanceof McpCallableTool); +} +// List all tools from the MCP client. +function listAllTools(mcpClient, maxTools = 100) { + return __asyncGenerator(this, arguments, function* listAllTools_1() { + let cursor = undefined; + let numTools = 0; + while (numTools < maxTools) { + const t = yield __await(mcpClient.listTools({ cursor })); + for (const tool of t.tools) { + yield yield __await(tool); + numTools++; + } + if (!t.nextCursor) { + break; + } + cursor = t.nextCursor; + } + }); +} +/** + * McpCallableTool can be used for model inference and invoking MCP clients with + * given function call arguments. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +class McpCallableTool { + constructor(mcpClients = [], config) { + this.mcpTools = []; + this.functionNameToMcpClient = {}; + this.mcpClients = mcpClients; + this.config = config; + } + /** + * Creates a McpCallableTool. + */ + static create(mcpClients, config) { + return new McpCallableTool(mcpClients, config); + } + /** + * Validates the function names are not duplicate and initialize the function + * name to MCP client mapping. + * + * @throws {Error} if the MCP tools from the MCP clients have duplicate tool + * names. + */ + async initialize() { + var _a, e_1, _b, _c; + if (this.mcpTools.length > 0) { + return; + } + const functionMap = {}; + const mcpTools = []; + for (const mcpClient of this.mcpClients) { + try { + for (var _d = true, _e = (e_1 = void 0, __asyncValues(listAllTools(mcpClient))), _f; _f = await _e.next(), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const mcpTool = _c; + mcpTools.push(mcpTool); + const mcpToolName = mcpTool.name; + if (functionMap[mcpToolName]) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + functionMap[mcpToolName] = mcpClient; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_d && !_a && (_b = _e.return)) await _b.call(_e); + } + finally { if (e_1) throw e_1.error; } + } + } + this.mcpTools = mcpTools; + this.functionNameToMcpClient = functionMap; + } + async tool() { + await this.initialize(); + return mcpToolsToGeminiTool(this.mcpTools, this.config); + } + async callTool(functionCalls) { + await this.initialize(); + const functionCallResponseParts = []; + for (const functionCall of functionCalls) { + if (functionCall.name in this.functionNameToMcpClient) { + const mcpClient = this.functionNameToMcpClient[functionCall.name]; + let requestOptions = undefined; + // TODO: b/424238654 - Add support for finer grained timeout control. + if (this.config.timeout) { + requestOptions = { + timeout: this.config.timeout, + }; + } + const callToolResponse = await mcpClient.callTool({ + name: functionCall.name, + arguments: functionCall.args, + }, + // Set the result schema to undefined to allow MCP to rely on the + // default schema. + undefined, requestOptions); + functionCallResponseParts.push({ + functionResponse: { + name: functionCall.name, + response: callToolResponse.isError + ? { error: callToolResponse } + : callToolResponse, + }, + }); + } + } + return functionCallResponseParts; + } +} +function isMcpClient(client) { + return (client !== null && + typeof client === 'object' && + 'listTools' in client && + typeof client.listTools === 'function'); +} +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +function mcpToTool(...args) { + // Set MCP usage for telemetry. + hasMcpToolUsageFromMcpToTool = true; + if (args.length === 0) { + throw new Error('No MCP clients provided'); + } + const maybeConfig = args[args.length - 1]; + if (isMcpClient(maybeConfig)) { + return McpCallableTool.create(args, {}); + } + return McpCallableTool.create(args.slice(0, args.length - 1), maybeConfig); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveMusicServerMessage, and then calling the onmessage callback. + * Note that the first message which is received from the server is a + * setupComplete message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage$1(apiClient, onmessage, event) { + const serverMessage = new LiveMusicServerMessage(); + let data; + if (event.data instanceof Blob) { + data = JSON.parse(await event.data.text()); + } + else { + data = JSON.parse(event.data); + } + const response = liveMusicServerMessageFromMldev(data); + Object.assign(serverMessage, response); + onmessage(serverMessage); +} +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +class LiveMusic { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + } + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b; + if (this.apiClient.isVertexAI()) { + throw new Error('Live music is not supported for Vertex AI.'); + } + console.warn('Live music generation is experimental and may change in future versions.'); + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + const headers = mapToHeaders$1(this.apiClient.getDefaultHeaders()); + const apiKey = this.apiClient.getApiKey(); + const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`; + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage$1(apiClient, callbacks.onmessage, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap$1(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + const model = tModel(this.apiClient, params.model); + const setup = liveMusicClientSetupToMldev({ + model, + }); + const clientMessage = liveMusicClientMessageToMldev({ setup }); + conn.send(JSON.stringify(clientMessage)); + return new LiveMusicSession(conn, this.apiClient); + } +} +/** + Represents a connection to the API. + + @experimental + */ +class LiveMusicSession { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + async setWeightedPrompts(params) { + if (!params.weightedPrompts || + Object.keys(params.weightedPrompts).length === 0) { + throw new Error('Weighted prompts must be set and contain at least one entry.'); + } + const setWeightedPromptsParameters = liveMusicSetWeightedPromptsParametersToMldev(params); + const clientContent = liveMusicClientContentToMldev(setWeightedPromptsParameters); + this.conn.send(JSON.stringify({ clientContent })); + } + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + async setMusicGenerationConfig(params) { + if (!params.musicGenerationConfig) { + params.musicGenerationConfig = {}; + } + const setConfigParameters = liveMusicSetConfigParametersToMldev(params); + const clientMessage = liveMusicClientMessageToMldev(setConfigParameters); + this.conn.send(JSON.stringify(clientMessage)); + } + sendPlaybackControl(playbackControl) { + const clientMessage = liveMusicClientMessageToMldev({ + playbackControl, + }); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + * Start the music stream. + * + * @experimental + */ + play() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.PLAY); + } + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.PAUSE); + } + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.STOP); + } + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.RESET_CONTEXT); + } + /** + Terminates the WebSocket connection. + + @experimental + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap$1(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders$1(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const FUNCTION_RESPONSE_REQUIRES_ID = 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.'; +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveServerMessages, and then calling the onmessage callback. Note that + * the first message which is received from the server is a setupComplete + * message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage(apiClient, onmessage, event) { + const serverMessage = new LiveServerMessage(); + let jsonData; + if (event.data instanceof Blob) { + jsonData = await event.data.text(); + } + else if (event.data instanceof ArrayBuffer) { + jsonData = new TextDecoder().decode(event.data); + } + else { + jsonData = event.data; + } + const data = JSON.parse(jsonData); + if (apiClient.isVertexAI()) { + const resp = liveServerMessageFromVertex(data); + Object.assign(serverMessage, resp); + } + else { + const resp = liveServerMessageFromMldev(data); + Object.assign(serverMessage, resp); + } + onmessage(serverMessage); +} +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +class Live { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + this.music = new LiveMusic(this.apiClient, this.auth, this.webSocketFactory); + } + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b, _c, _d, _e, _f; + // TODO: b/404946746 - Support per request HTTP options. + if (params.config && params.config.httpOptions) { + throw new Error('The Live module does not support httpOptions at request-level in' + + ' LiveConnectConfig yet. Please use the client-level httpOptions' + + ' configuration instead.'); + } + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + let url; + const clientHeaders = this.apiClient.getHeaders(); + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + setMcpUsageHeader(clientHeaders); + } + const headers = mapToHeaders(clientHeaders); + if (this.apiClient.isVertexAI()) { + url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`; + await this.auth.addAuthHeaders(headers); + } + else { + const apiKey = this.apiClient.getApiKey(); + let method = 'BidiGenerateContent'; + let keyName = 'key'; + if (apiKey === null || apiKey === void 0 ? void 0 : apiKey.startsWith('auth_tokens/')) { + console.warn('Warning: Ephemeral token support is experimental and may change in future versions.'); + if (apiVersion !== 'v1alpha') { + console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."); + } + method = 'BidiGenerateContentConstrained'; + keyName = 'access_token'; + } + url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`; + } + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + var _a; + (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onopen) === null || _a === void 0 ? void 0 : _a.call(callbacks); + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage(apiClient, callbacks.onmessage, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + let transformedModel = tModel(this.apiClient, params.model); + if (this.apiClient.isVertexAI() && + transformedModel.startsWith('publishers/')) { + const project = this.apiClient.getProject(); + const location = this.apiClient.getLocation(); + transformedModel = + `projects/${project}/locations/${location}/` + transformedModel; + } + let clientMessage = {}; + if (this.apiClient.isVertexAI() && + ((_c = params.config) === null || _c === void 0 ? void 0 : _c.responseModalities) === undefined) { + // Set default to AUDIO to align with MLDev API. + if (params.config === undefined) { + params.config = { responseModalities: [exports.Modality.AUDIO] }; + } + else { + params.config.responseModalities = [exports.Modality.AUDIO]; + } + } + if ((_d = params.config) === null || _d === void 0 ? void 0 : _d.generationConfig) { + // Raise deprecation warning for generationConfig. + console.warn('Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).'); + } + const inputTools = (_f = (_e = params.config) === null || _e === void 0 ? void 0 : _e.tools) !== null && _f !== void 0 ? _f : []; + const convertedTools = []; + for (const tool of inputTools) { + if (this.isCallableTool(tool)) { + const callableTool = tool; + convertedTools.push(await callableTool.tool()); + } + else { + convertedTools.push(tool); + } + } + if (convertedTools.length > 0) { + params.config.tools = convertedTools; + } + const liveConnectParameters = { + model: transformedModel, + config: params.config, + callbacks: params.callbacks, + }; + if (this.apiClient.isVertexAI()) { + clientMessage = liveConnectParametersToVertex(this.apiClient, liveConnectParameters); + } + else { + clientMessage = liveConnectParametersToMldev(this.apiClient, liveConnectParameters); + } + delete clientMessage['config']; + conn.send(JSON.stringify(clientMessage)); + return new Session(conn, this.apiClient); + } + // TODO: b/416041229 - Abstract this method to a common place. + isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; + } +} +const defaultLiveSendClientContentParamerters = { + turnComplete: true, +}; +/** + Represents a connection to the API. + + @experimental + */ +class Session { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + tLiveClientContent(apiClient, params) { + if (params.turns !== null && params.turns !== undefined) { + let contents = []; + try { + contents = tContents(params.turns); + if (apiClient.isVertexAI()) { + contents = contents.map((item) => contentToVertex(item)); + } + else { + contents = contents.map((item) => contentToMldev$1(item)); + } + } + catch (_a) { + throw new Error(`Failed to parse client content "turns", type: '${typeof params.turns}'`); + } + return { + clientContent: { turns: contents, turnComplete: params.turnComplete }, + }; + } + return { + clientContent: { turnComplete: params.turnComplete }, + }; + } + tLiveClienttToolResponse(apiClient, params) { + let functionResponses = []; + if (params.functionResponses == null) { + throw new Error('functionResponses is required.'); + } + if (!Array.isArray(params.functionResponses)) { + functionResponses = [params.functionResponses]; + } + else { + functionResponses = params.functionResponses; + } + if (functionResponses.length === 0) { + throw new Error('functionResponses is required.'); + } + for (const functionResponse of functionResponses) { + if (typeof functionResponse !== 'object' || + functionResponse === null || + !('name' in functionResponse) || + !('response' in functionResponse)) { + throw new Error(`Could not parse function response, type '${typeof functionResponse}'.`); + } + if (!apiClient.isVertexAI() && !('id' in functionResponse)) { + throw new Error(FUNCTION_RESPONSE_REQUIRES_ID); + } + } + const clientMessage = { + toolResponse: { functionResponses: functionResponses }, + }; + return clientMessage; + } + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params) { + params = Object.assign(Object.assign({}, defaultLiveSendClientContentParamerters), params); + const clientMessage = this.tLiveClientContent(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params) { + let clientMessage = {}; + if (this.apiClient.isVertexAI()) { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToVertex(params), + }; + } + else { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToMldev(params), + }; + } + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params) { + if (params.functionResponses == null) { + throw new Error('Tool response parameters are required.'); + } + const clientMessage = this.tLiveClienttToolResponse(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const DEFAULT_MAX_REMOTE_CALLS = 10; +/** Returns whether automatic function calling is disabled. */ +function shouldDisableAfc(config) { + var _a, _b, _c; + if ((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.disable) { + return true; + } + let callableToolsPresent = false; + for (const tool of (_b = config === null || config === void 0 ? void 0 : config.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + callableToolsPresent = true; + break; + } + } + if (!callableToolsPresent) { + return true; + } + const maxCalls = (_c = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _c === void 0 ? void 0 : _c.maximumRemoteCalls; + if ((maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) || + maxCalls == 0) { + console.warn('Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:', maxCalls); + return true; + } + return false; +} +function isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; +} +// Checks whether the list of tools contains any CallableTools. Will return true +// if there is at least one CallableTool. +function hasCallableTools(params) { + var _a, _b, _c; + return (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +// Checks whether the list of tools contains any non-callable tools. Will return +// true if there is at least one non-Callable tool. +function hasNonCallableTools(params) { + var _a, _b, _c; + return (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => !isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +/** + * Returns whether to append automatic function calling history to the + * response. + */ +function shouldAppendAfcHistory(config) { + var _a; + return !((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.ignoreCallHistory); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Models extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + this.generateContent = async (params) => { + var _a, _b, _c, _d, _e; + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + this.maybeMoveToResponseJsonSchem(params); + if (!hasCallableTools(params) || shouldDisableAfc(params.config)) { + return await this.generateContentInternal(transformedParams); + } + if (hasNonCallableTools(params)) { + throw new Error('Automatic function calling with CallableTools and Tools is not yet supported.'); + } + let response; + let functionResponseContent; + const automaticFunctionCallingHistory = tContents(transformedParams.contents); + const maxRemoteCalls = (_c = (_b = (_a = transformedParams.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let remoteCalls = 0; + while (remoteCalls < maxRemoteCalls) { + response = await this.generateContentInternal(transformedParams); + if (!response.functionCalls || response.functionCalls.length === 0) { + break; + } + const responseContent = response.candidates[0].content; + const functionResponseParts = []; + for (const tool of (_e = (_d = params.config) === null || _d === void 0 ? void 0 : _d.tools) !== null && _e !== void 0 ? _e : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const parts = await callableTool.callTool(response.functionCalls); + functionResponseParts.push(...parts); + } + } + remoteCalls++; + functionResponseContent = { + role: 'user', + parts: functionResponseParts, + }; + transformedParams.contents = tContents(transformedParams.contents); + transformedParams.contents.push(responseContent); + transformedParams.contents.push(functionResponseContent); + if (shouldAppendAfcHistory(transformedParams.config)) { + automaticFunctionCallingHistory.push(responseContent); + automaticFunctionCallingHistory.push(functionResponseContent); + } + } + if (shouldAppendAfcHistory(transformedParams.config)) { + response.automaticFunctionCallingHistory = + automaticFunctionCallingHistory; + } + return response; + }; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + this.generateContentStream = async (params) => { + this.maybeMoveToResponseJsonSchem(params); + if (shouldDisableAfc(params.config)) { + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + return await this.generateContentStreamInternal(transformedParams); + } + else { + return await this.processAfcStream(params); + } + }; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.generateImages = async (params) => { + return await this.generateImagesInternal(params).then((apiResponse) => { + var _a; + let positivePromptSafetyAttributes; + const generatedImages = []; + if (apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.generatedImages) { + for (const generatedImage of apiResponse.generatedImages) { + if (generatedImage && + (generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) && + ((_a = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) === null || _a === void 0 ? void 0 : _a.contentType) === 'Positive Prompt') { + positivePromptSafetyAttributes = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes; + } + else { + generatedImages.push(generatedImage); + } + } + } + let response; + if (positivePromptSafetyAttributes) { + response = { + generatedImages: generatedImages, + positivePromptSafetyAttributes: positivePromptSafetyAttributes, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + else { + response = { + generatedImages: generatedImages, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + return response; + }); + }; + this.list = async (params) => { + var _a; + const defaultConfig = { + queryBase: true, + }; + const actualConfig = Object.assign(Object.assign({}, defaultConfig), params === null || params === void 0 ? void 0 : params.config); + const actualParams = { + config: actualConfig, + }; + if (this.apiClient.isVertexAI()) { + if (!actualParams.config.queryBase) { + if ((_a = actualParams.config) === null || _a === void 0 ? void 0 : _a.filter) { + throw new Error('Filtering tuned models list for Vertex AI is not currently supported'); + } + else { + actualParams.config.filter = 'labels.tune-type:*'; + } + } + } + return new Pager(exports.PagedItem.PAGED_ITEM_MODELS, (x) => this.listInternal(x), await this.listInternal(actualParams), actualParams); + }; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.editImage = async (params) => { + const paramsInternal = { + model: params.model, + prompt: params.prompt, + referenceImages: [], + config: params.config, + }; + if (params.referenceImages) { + if (params.referenceImages) { + paramsInternal.referenceImages = params.referenceImages.map((img) => img.toReferenceImageAPI()); + } + } + return await this.editImageInternal(paramsInternal); + }; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.upscaleImage = async (params) => { + let apiConfig = { + numberOfImages: 1, + mode: 'upscale', + }; + if (params.config) { + apiConfig = Object.assign(Object.assign({}, apiConfig), params.config); + } + const apiParams = { + model: params.model, + image: params.image, + upscaleFactor: params.upscaleFactor, + config: apiConfig, + }; + return await this.upscaleImageInternal(apiParams); + }; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + this.generateVideos = async (params) => { + return await this.generateVideosInternal(params); + }; + } + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + maybeMoveToResponseJsonSchem(params) { + if (params.config && params.config.responseSchema) { + if (!params.config.responseJsonSchema) { + if (Object.keys(params.config.responseSchema).includes('$schema')) { + params.config.responseJsonSchema = params.config.responseSchema; + delete params.config.responseSchema; + } + } + } + return; + } + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + async processParamsMaybeAddMcpUsage(params) { + var _a, _b, _c; + const tools = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools; + if (!tools) { + return params; + } + const transformedTools = await Promise.all(tools.map(async (tool) => { + if (isCallableTool(tool)) { + const callableTool = tool; + return await callableTool.tool(); + } + return tool; + })); + const newParams = { + model: params.model, + contents: params.contents, + config: Object.assign(Object.assign({}, params.config), { tools: transformedTools }), + }; + newParams.config.tools = transformedTools; + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + const headers = (_c = (_b = params.config.httpOptions) === null || _b === void 0 ? void 0 : _b.headers) !== null && _c !== void 0 ? _c : {}; + let newHeaders = Object.assign({}, headers); + if (Object.keys(newHeaders).length === 0) { + newHeaders = this.apiClient.getDefaultHeaders(); + } + setMcpUsageHeader(newHeaders); + newParams.config.httpOptions = Object.assign(Object.assign({}, params.config.httpOptions), { headers: newHeaders }); + } + return newParams; + } + async initAfcToolsMap(params) { + var _a, _b, _c; + const afcTools = new Map(); + for (const tool of (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const toolDeclaration = await callableTool.tool(); + for (const declaration of (_c = toolDeclaration.functionDeclarations) !== null && _c !== void 0 ? _c : []) { + if (!declaration.name) { + throw new Error('Function declaration name is required.'); + } + if (afcTools.has(declaration.name)) { + throw new Error(`Duplicate tool declaration name: ${declaration.name}`); + } + afcTools.set(declaration.name, callableTool); + } + } + } + return afcTools; + } + async processAfcStream(params) { + var _a, _b, _c; + const maxRemoteCalls = (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let wereFunctionsCalled = false; + let remoteCallCount = 0; + const afcToolsMap = await this.initAfcToolsMap(params); + return (function (models, afcTools, params) { + var _a, _b; + return __asyncGenerator(this, arguments, function* () { + var _c, e_1, _d, _e; + while (remoteCallCount < maxRemoteCalls) { + if (wereFunctionsCalled) { + remoteCallCount++; + wereFunctionsCalled = false; + } + const transformedParams = yield __await(models.processParamsMaybeAddMcpUsage(params)); + const response = yield __await(models.generateContentStreamInternal(transformedParams)); + const functionResponses = []; + const responseContents = []; + try { + for (var _f = true, response_1 = (e_1 = void 0, __asyncValues(response)), response_1_1; response_1_1 = yield __await(response_1.next()), _c = response_1_1.done, !_c; _f = true) { + _e = response_1_1.value; + _f = false; + const chunk = _e; + yield yield __await(chunk); + if (chunk.candidates && ((_a = chunk.candidates[0]) === null || _a === void 0 ? void 0 : _a.content)) { + responseContents.push(chunk.candidates[0].content); + for (const part of (_b = chunk.candidates[0].content.parts) !== null && _b !== void 0 ? _b : []) { + if (remoteCallCount < maxRemoteCalls && part.functionCall) { + if (!part.functionCall.name) { + throw new Error('Function call name was not returned by the model.'); + } + if (!afcTools.has(part.functionCall.name)) { + throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${part.functionCall.name}`); + } + else { + const responseParts = yield __await(afcTools + .get(part.functionCall.name) + .callTool([part.functionCall])); + functionResponses.push(...responseParts); + } + } + } + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_c && (_d = response_1.return)) yield __await(_d.call(response_1)); + } + finally { if (e_1) throw e_1.error; } + } + if (functionResponses.length > 0) { + wereFunctionsCalled = true; + const typedResponseChunk = new GenerateContentResponse(); + typedResponseChunk.candidates = [ + { + content: { + role: 'user', + parts: functionResponses, + }, + }, + ]; + yield yield __await(typedResponseChunk); + const newContents = []; + newContents.push(...responseContents); + newContents.push({ + role: 'user', + parts: functionResponses, + }); + const updatedContents = tContents(params.contents).concat(newContents); + params.contents = updatedContents; + } + else { + break; + } + } + }); + })(this, afcToolsMap, params); + } + async generateContentInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromVertex(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromMldev(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async generateContentStreamInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_2, _b, _c; + try { + for (var _d = true, apiResponse_1 = __asyncValues(apiResponse), apiResponse_1_1; apiResponse_1_1 = yield __await(apiResponse_1.next()), _a = apiResponse_1_1.done, !_a; _d = true) { + _c = apiResponse_1_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromVertex((yield __await(chunk.json()))); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_1.return)) yield __await(_b.call(apiResponse_1)); + } + finally { if (e_2) throw e_2.error; } + } + }); + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_3, _b, _c; + try { + for (var _d = true, apiResponse_2 = __asyncValues(apiResponse), apiResponse_2_1; apiResponse_2_1 = yield __await(apiResponse_2.next()), _a = apiResponse_2_1.done, !_a; _d = true) { + _c = apiResponse_2_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromMldev((yield __await(chunk.json()))); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_2.return)) yield __await(_b.call(apiResponse_2)); + } + finally { if (e_3) throw e_3.error; } + } + }); + }); + } + } + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + async embedContent(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = embedContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromVertex(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = embedContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchEmbedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromMldev(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async generateImagesInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateImagesParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromVertex(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateImagesParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromMldev(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async editImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = editImageParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = editImageResponseFromVertex(apiResponse); + const typedResp = new EditImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + async upscaleImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = upscaleImageAPIParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = upscaleImageResponseFromVertex(apiResponse); + const typedResp = new UpscaleImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Recontextualizes an image. + * + * There are two types of recontextualization currently supported: + * 1) Imagen Product Recontext - Generate images of products in new scenes + * and contexts. + * 2) Virtual Try-On: Generate images of persons modeling fashion products. + * + * @param params - The parameters for recontextualizing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response1 = await ai.models.recontextImage({ + * model: 'imagen-product-recontext-preview-06-30', + * source: { + * prompt: 'In a modern kitchen setting.', + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response1?.generatedImages?.[0]?.image?.imageBytes); + * + * const response2 = await ai.models.recontextImage({ + * model: 'virtual-try-on-preview-08-04', + * source: { + * personImage: personImage, + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response2?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async recontextImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = recontextImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = recontextImageResponseFromVertex(apiResponse); + const typedResp = new RecontextImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Segments an image, creating a mask of a specified area. + * + * @param params - The parameters for segmenting an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.segmentImage({ + * model: 'image-segmentation-001', + * source: { + * image: image, + * }, + * config: { + * mode: 'foreground', + * }, + * }); + * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes); + * ``` + */ + async segmentImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = segmentImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = segmentImageResponseFromVertex(apiResponse); + const typedResp = new SegmentImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listModelsParametersToVertex(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromVertex(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listModelsParametersToMldev(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromMldev(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateModelParametersToVertex(this.apiClient, params); + path = formatMap('{model}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = updateModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteModelResponseFromVertex(); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteModelResponseFromMldev(); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + async countTokens(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = countTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromVertex(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = countTokensParametersToMldev(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromMldev(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + async computeTokens(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = computeTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:computeTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = computeTokensResponseFromVertex(apiResponse); + const typedResp = new ComputeTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + async generateVideosInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateVideosParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateVideosParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getOperationParametersToMldev(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fetchPredictOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['operationName'], fromOperationName); + } + const fromResourceName = getValueByPath(fromObject, ['resourceName']); + if (fromResourceName != null) { + setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Operations extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async getVideosOperation(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async get(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + async getVideosOperationInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getOperationParametersToVertex(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + const body = getOperationParametersToMldev(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + } + async fetchPredictVideosOperationInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = fetchPredictOperationParametersToVertex(params); + path = formatMap('{resourceName}:fetchPredictOperation', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is not supported in Gemini API.'); + } + return toObject; +} +function audioTranscriptionConfigToMldev() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToMldev(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToMldev(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToMldev(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToMldev(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToMldev()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToMldev()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToMldev(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToMldev(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToMldev(fromProactivity)); + } + return toObject; +} +function liveConnectConstraintsToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function createAuthTokenConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromNewSessionExpireTime = getValueByPath(fromObject, [ + 'newSessionExpireTime', + ]); + if (parentObject !== undefined && fromNewSessionExpireTime != null) { + setValueByPath(parentObject, ['newSessionExpireTime'], fromNewSessionExpireTime); + } + const fromUses = getValueByPath(fromObject, ['uses']); + if (parentObject !== undefined && fromUses != null) { + setValueByPath(parentObject, ['uses'], fromUses); + } + const fromLiveConnectConstraints = getValueByPath(fromObject, [ + 'liveConnectConstraints', + ]); + if (parentObject !== undefined && fromLiveConnectConstraints != null) { + setValueByPath(parentObject, ['bidiGenerateContentSetup'], liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints)); + } + const fromLockAdditionalFields = getValueByPath(fromObject, [ + 'lockAdditionalFields', + ]); + if (parentObject !== undefined && fromLockAdditionalFields != null) { + setValueByPath(parentObject, ['fieldMask'], fromLockAdditionalFields); + } + return toObject; +} +function createAuthTokenParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createAuthTokenConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function authTokenFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns a comma-separated list of field masks from a given object. + * + * @param setup The object to extract field masks from. + * @return A comma-separated list of field masks. + */ +function getFieldMasks(setup) { + const fields = []; + for (const key in setup) { + if (Object.prototype.hasOwnProperty.call(setup, key)) { + const value = setup[key]; + // 2nd layer, recursively get field masks see TODO(b/418290100) + if (typeof value === 'object' && + value != null && + Object.keys(value).length > 0) { + const field = Object.keys(value).map((kk) => `${key}.${kk}`); + fields.push(...field); + } + else { + fields.push(key); // 1st layer + } + } + } + return fields.join(','); +} +/** + * Converts bidiGenerateContentSetup. + * @param requestDict - The request dictionary. + * @param config - The configuration object. + * @return - The modified request dictionary. + */ +function convertBidiSetupToTokenSetup(requestDict, config) { + // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup. + let setupForMaskGeneration = null; + const bidiGenerateContentSetupValue = requestDict['bidiGenerateContentSetup']; + if (typeof bidiGenerateContentSetupValue === 'object' && + bidiGenerateContentSetupValue !== null && + 'setup' in bidiGenerateContentSetupValue) { + // Now we know bidiGenerateContentSetupValue is an object and has a 'setup' + // property. + const innerSetup = bidiGenerateContentSetupValue + .setup; + if (typeof innerSetup === 'object' && innerSetup !== null) { + // Valid inner setup found. + requestDict['bidiGenerateContentSetup'] = innerSetup; + setupForMaskGeneration = innerSetup; + } + else { + // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as + // if bidiGenerateContentSetup is invalid. + delete requestDict['bidiGenerateContentSetup']; + } + } + else if (bidiGenerateContentSetupValue !== undefined) { + // `bidiGenerateContentSetup` exists but not in the expected + // shape {setup: {...}}; treat as invalid. + delete requestDict['bidiGenerateContentSetup']; + } + const preExistingFieldMask = requestDict['fieldMask']; + // Handle mask generation setup. + if (setupForMaskGeneration) { + const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration); + if (Array.isArray(config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + (config === null || config === void 0 ? void 0 : config.lockAdditionalFields.length) === 0) { + // Case 1: lockAdditionalFields is an empty array. Lock only fields from + // bidi setup. + if (generatedMaskFromBidi) { + // Only assign if mask is not empty + requestDict['fieldMask'] = generatedMaskFromBidi; + } + else { + delete requestDict['fieldMask']; // If mask is empty, effectively no + // specific fields locked by bidi + } + } + else if ((config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + config.lockAdditionalFields.length > 0 && + preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // Case 2: Lock fields from bidi setup + additional fields + // (preExistingFieldMask). + const generationConfigFields = [ + 'temperature', + 'topK', + 'topP', + 'maxOutputTokens', + 'responseModalities', + 'seed', + 'speechConfig', + ]; + let mappedFieldsFromPreExisting = []; + if (preExistingFieldMask.length > 0) { + mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => { + if (generationConfigFields.includes(field)) { + return `generationConfig.${field}`; + } + return field; // Keep original field name if not in + // generationConfigFields + }); + } + const finalMaskParts = []; + if (generatedMaskFromBidi) { + finalMaskParts.push(generatedMaskFromBidi); + } + if (mappedFieldsFromPreExisting.length > 0) { + finalMaskParts.push(...mappedFieldsFromPreExisting); + } + if (finalMaskParts.length > 0) { + requestDict['fieldMask'] = finalMaskParts.join(','); + } + else { + // If no fields from bidi and no valid additional fields from + // pre-existing mask. + delete requestDict['fieldMask']; + } + } + else { + // Case 3: "Lock all fields" (meaning, don't send a field_mask, let server + // defaults apply or all are mutable). This is hit if: + // - `config.lockAdditionalFields` is undefined. + // - `config.lockAdditionalFields` is non-empty, BUT + // `preExistingFieldMask` is null, not a string, or an empty string. + delete requestDict['fieldMask']; + } + } + else { + // No valid `bidiGenerateContentSetup` was found or extracted. + // "Lock additional null fields if any". + if (preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // If there's a pre-existing field mask, it's a string, and it's not + // empty, then we should lock all fields. + requestDict['fieldMask'] = preExistingFieldMask.join(','); + } + else { + delete requestDict['fieldMask']; + } + } + return requestDict; +} +class Tokens extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + async create(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('The client.tokens.create method is only supported by the Gemini Developer API.'); + } + else { + const body = createAuthTokenParametersToMldev(this.apiClient, params); + path = formatMap('auth_tokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const transformedBody = convertBidiSetupToTokenSetup(body, params.config); + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(transformedBody), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = authTokenFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const GOOGLE_API_KEY_HEADER = 'x-goog-api-key'; +const REQUIRED_VERTEX_AI_SCOPE = 'https://www.googleapis.com/auth/cloud-platform'; +class NodeAuth { + constructor(opts) { + if (opts.apiKey !== undefined) { + this.apiKey = opts.apiKey; + return; + } + const vertexAuthOptions = buildGoogleAuthOptions(opts.googleAuthOptions); + this.googleAuth = new googleAuthLibrary.GoogleAuth(vertexAuthOptions); + } + async addAuthHeaders(headers) { + if (this.apiKey !== undefined) { + if (this.apiKey.startsWith('auth_tokens/')) { + throw new Error('Ephemeral tokens are only supported by the live API.'); + } + this.addKeyHeader(headers); + return; + } + return this.addGoogleAuthHeaders(headers); + } + addKeyHeader(headers) { + if (headers.get(GOOGLE_API_KEY_HEADER) !== null) { + return; + } + if (this.apiKey === undefined) { + // This should never happen, this method is only called + // when apiKey is set. + throw new Error('Trying to set API key header but apiKey is not set'); + } + headers.append(GOOGLE_API_KEY_HEADER, this.apiKey); + } + async addGoogleAuthHeaders(headers) { + if (this.googleAuth === undefined) { + // This should never happen, addGoogleAuthHeaders should only be + // called when there is no apiKey set and in these cases googleAuth + // is set. + throw new Error('Trying to set google-auth headers but googleAuth is unset'); + } + const authHeaders = await this.googleAuth.getRequestHeaders(); + for (const key in authHeaders) { + if (headers.get(key) !== null) { + continue; + } + headers.append(key, authHeaders[key]); + } + } +} +function buildGoogleAuthOptions(googleAuthOptions) { + let authOptions; + if (!googleAuthOptions) { + authOptions = { + scopes: [REQUIRED_VERTEX_AI_SCOPE], + }; + return authOptions; + } + else { + authOptions = googleAuthOptions; + if (!authOptions.scopes) { + authOptions.scopes = [REQUIRED_VERTEX_AI_SCOPE]; + return authOptions; + } + else if ((typeof authOptions.scopes === 'string' && + authOptions.scopes !== REQUIRED_VERTEX_AI_SCOPE) || + (Array.isArray(authOptions.scopes) && + authOptions.scopes.indexOf(REQUIRED_VERTEX_AI_SCOPE) < 0)) { + throw new Error(`Invalid auth scopes. Scopes must include: ${REQUIRED_VERTEX_AI_SCOPE}`); + } + return authOptions; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeDownloader { + async download(params, apiClient) { + if (params.downloadPath) { + const response = await downloadFile(params, apiClient); + if (response instanceof HttpResponse) { + const writer = fs.createWriteStream(params.downloadPath); + node_stream.Readable.fromWeb(response.responseInternal.body).pipe(writer); + } + else { + fs.writeFile(params.downloadPath, response, { encoding: 'base64' }, (error) => { + if (error) { + throw new Error(`Failed to write file to ${params.downloadPath}: ${error}`); + } + }); + } + } + } +} +async function downloadFile(params, apiClient) { + var _a, _b, _c; + const name = tFileName(params.file); + if (name !== undefined) { + return await apiClient.request({ + path: `files/${name}:download`, + httpMethod: 'GET', + queryParams: { + 'alt': 'media', + }, + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + else if (isGeneratedVideo(params.file)) { + const videoBytes = (_c = params.file.video) === null || _c === void 0 ? void 0 : _c.videoBytes; + if (typeof videoBytes === 'string') { + return videoBytes; + } + else { + throw new Error('Failed to download generated video, Uri or videoBytes not found.'); + } + } + else if (isVideo(params.file)) { + const videoBytes = params.file.videoBytes; + if (typeof videoBytes === 'string') { + return videoBytes; + } + else { + throw new Error('Failed to download video, Uri or videoBytes not found.'); + } + } + else { + throw new Error('Unsupported file type'); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeWebSocketFactory { + create(url, headers, callbacks) { + return new NodeWebSocket(url, headers, callbacks); + } +} +class NodeWebSocket { + constructor(url, headers, callbacks) { + this.url = url; + this.headers = headers; + this.callbacks = callbacks; + } + connect() { + this.ws = new NodeWs__namespace.WebSocket(this.url, { headers: this.headers }); + this.ws.onopen = this.callbacks.onopen; + this.ws.onerror = this.callbacks.onerror; + this.ws.onclose = this.callbacks.onclose; + this.ws.onmessage = this.callbacks.onmessage; + } + send(message) { + if (this.ws === undefined) { + throw new Error('WebSocket is not connected'); + } + this.ws.send(message); + } + close() { + if (this.ws === undefined) { + throw new Error('WebSocket is not connected'); + } + this.ws.close(); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listTuningJobsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function tuningExampleToMldev(fromObject) { + const toObject = {}; + const fromTextInput = getValueByPath(fromObject, ['textInput']); + if (fromTextInput != null) { + setValueByPath(toObject, ['textInput'], fromTextInput); + } + const fromOutput = getValueByPath(fromObject, ['output']); + if (fromOutput != null) { + setValueByPath(toObject, ['output'], fromOutput); + } + return toObject; +} +function tuningDatasetToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['vertexDatasetResource']) !== undefined) { + throw new Error('vertexDatasetResource parameter is not supported in Gemini API.'); + } + const fromExamples = getValueByPath(fromObject, ['examples']); + if (fromExamples != null) { + let transformedList = fromExamples; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningExampleToMldev(item); + }); + } + setValueByPath(toObject, ['examples', 'examples'], transformedList); + } + return toObject; +} +function createTuningJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['validationDataset']) !== undefined) { + throw new Error('validationDataset parameter is not supported in Gemini API.'); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromTunedModelDisplayName); + } + if (getValueByPath(fromObject, ['description']) !== undefined) { + throw new Error('description parameter is not supported in Gemini API.'); + } + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (fromLearningRateMultiplier != null) { + setValueByPath(toObject, ['tuningTask', 'hyperparameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + if (getValueByPath(fromObject, ['exportLastCheckpointOnly']) !== + undefined) { + throw new Error('exportLastCheckpointOnly parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['preTunedModelCheckpointId']) !== + undefined) { + throw new Error('preTunedModelCheckpointId parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['adapterSize']) !== undefined) { + throw new Error('adapterSize parameter is not supported in Gemini API.'); + } + const fromBatchSize = getValueByPath(fromObject, ['batchSize']); + if (parentObject !== undefined && fromBatchSize != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'batchSize'], fromBatchSize); + } + const fromLearningRate = getValueByPath(fromObject, ['learningRate']); + if (parentObject !== undefined && fromLearningRate != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'learningRate'], fromLearningRate); + } + return toObject; +} +function createTuningJobParametersPrivateToMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + setValueByPath(toObject, ['tuningTask', 'trainingData'], tuningDatasetToMldev(fromTrainingDataset)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createTuningJobConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listTuningJobsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function tuningDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (parentObject !== undefined && fromGcsUri != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + if (getValueByPath(fromObject, ['examples']) !== undefined) { + throw new Error('examples parameter is not supported in Vertex AI.'); + } + return toObject; +} +function tuningValidationDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['validationDatasetUri'], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + return toObject; +} +function createTuningJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromValidationDataset = getValueByPath(fromObject, [ + 'validationDataset', + ]); + if (parentObject !== undefined && fromValidationDataset != null) { + setValueByPath(parentObject, ['supervisedTuningSpec'], tuningValidationDatasetToVertex(fromValidationDataset, toObject)); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (parentObject !== undefined && fromLearningRateMultiplier != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + const fromExportLastCheckpointOnly = getValueByPath(fromObject, [ + 'exportLastCheckpointOnly', + ]); + if (parentObject !== undefined && fromExportLastCheckpointOnly != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'exportLastCheckpointOnly'], fromExportLastCheckpointOnly); + } + const fromPreTunedModelCheckpointId = getValueByPath(fromObject, [ + 'preTunedModelCheckpointId', + ]); + if (fromPreTunedModelCheckpointId != null) { + setValueByPath(toObject, ['preTunedModel', 'checkpointId'], fromPreTunedModelCheckpointId); + } + const fromAdapterSize = getValueByPath(fromObject, ['adapterSize']); + if (parentObject !== undefined && fromAdapterSize != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'], fromAdapterSize); + } + if (getValueByPath(fromObject, ['batchSize']) !== undefined) { + throw new Error('batchSize parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['learningRate']) !== undefined) { + throw new Error('learningRate parameter is not supported in Vertex AI.'); + } + return toObject; +} +function createTuningJobParametersPrivateToVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + setValueByPath(toObject, ['supervisedTuningSpec', 'trainingDatasetUri'], tuningDatasetToVertex(fromTrainingDataset, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createTuningJobConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function tunedModelFromMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['name']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ['name']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + return toObject; +} +function tuningJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, [ + 'tuningTask', + 'startTime', + ]); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'tuningTask', + 'completeTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['_self']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], tunedModelFromMldev(fromTunedModel)); + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel); + } + const fromExperiment = getValueByPath(fromObject, ['experiment']); + if (fromExperiment != null) { + setValueByPath(toObject, ['experiment'], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (fromOutputUri != null) { + setValueByPath(toObject, ['outputUri'], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject, ['pipelineJob']); + if (fromPipelineJob != null) { + setValueByPath(toObject, ['pipelineJob'], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject, [ + 'serviceAccount', + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ['serviceAccount'], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + return toObject; +} +function listTuningJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ['tunedModels']); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromMldev(item); + }); + } + setValueByPath(toObject, ['tuningJobs'], transformedList); + } + return toObject; +} +function tuningOperationFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + return toObject; +} +function tunedModelCheckpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ['checkpointId']); + if (fromCheckpointId != null) { + setValueByPath(toObject, ['checkpointId'], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ['epoch']); + if (fromEpoch != null) { + setValueByPath(toObject, ['epoch'], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ['step']); + if (fromStep != null) { + setValueByPath(toObject, ['step'], fromStep); + } + const fromEndpoint = getValueByPath(fromObject, ['endpoint']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + return toObject; +} +function tunedModelFromVertex(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ['endpoint']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + const fromCheckpoints = getValueByPath(fromObject, ['checkpoints']); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tunedModelCheckpointFromVertex(item); + }); + } + setValueByPath(toObject, ['checkpoints'], transformedList); + } + return toObject; +} +function tuningJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['tunedModel']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], tunedModelFromVertex(fromTunedModel)); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromSupervisedTuningSpec = getValueByPath(fromObject, [ + 'supervisedTuningSpec', + ]); + if (fromSupervisedTuningSpec != null) { + setValueByPath(toObject, ['supervisedTuningSpec'], fromSupervisedTuningSpec); + } + const fromTuningDataStats = getValueByPath(fromObject, [ + 'tuningDataStats', + ]); + if (fromTuningDataStats != null) { + setValueByPath(toObject, ['tuningDataStats'], fromTuningDataStats); + } + const fromEncryptionSpec = getValueByPath(fromObject, [ + 'encryptionSpec', + ]); + if (fromEncryptionSpec != null) { + setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec); + } + const fromPartnerModelTuningSpec = getValueByPath(fromObject, [ + 'partnerModelTuningSpec', + ]); + if (fromPartnerModelTuningSpec != null) { + setValueByPath(toObject, ['partnerModelTuningSpec'], fromPartnerModelTuningSpec); + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel); + } + const fromExperiment = getValueByPath(fromObject, ['experiment']); + if (fromExperiment != null) { + setValueByPath(toObject, ['experiment'], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (fromOutputUri != null) { + setValueByPath(toObject, ['outputUri'], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject, ['pipelineJob']); + if (fromPipelineJob != null) { + setValueByPath(toObject, ['pipelineJob'], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject, [ + 'serviceAccount', + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ['serviceAccount'], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + return toObject; +} +function listTuningJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ['tuningJobs']); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromVertex(item); + }); + } + setValueByPath(toObject, ['tuningJobs'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Tunings extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.get = async (params) => { + return await this.getInternal(params); + }; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.list = async (params = {}) => { + return new Pager(exports.PagedItem.PAGED_ITEM_TUNING_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.tune = async (params) => { + if (this.apiClient.isVertexAI()) { + if (params.baseModel.startsWith('projects/')) { + const preTunedModel = { + tunedModelName: params.baseModel, + }; + const paramsPrivate = Object.assign(Object.assign({}, params), { preTunedModel: preTunedModel }); + paramsPrivate.baseModel = undefined; + return await this.tuneInternal(paramsPrivate); + } + else { + const paramsPrivate = Object.assign({}, params); + return await this.tuneInternal(paramsPrivate); + } + } + else { + const paramsPrivate = Object.assign({}, params); + const operation = await this.tuneMldevInternal(paramsPrivate); + let tunedModelName = ''; + if (operation['metadata'] !== undefined && + operation['metadata']['tunedModel'] !== undefined) { + tunedModelName = operation['metadata']['tunedModel']; + } + else if (operation['name'] !== undefined && + operation['name'].includes('/operations/')) { + tunedModelName = operation['name'].split('/operations/')[0]; + } + const tuningJob = { + name: tunedModelName, + state: exports.JobState.JOB_STATE_QUEUED, + }; + return tuningJob; + } + }; + } + async getInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getTuningJobParametersToVertex(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getTuningJobParametersToMldev(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listTuningJobsParametersToVertex(params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromVertex(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listTuningJobsParametersToMldev(params); + path = formatMap('tunedModels', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromMldev(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async tuneInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createTuningJobParametersPrivateToVertex(params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + async tuneMldevInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createTuningJobParametersPrivateToMldev(params); + path = formatMap('tunedModels', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningOperationFromMldev(apiResponse); + return resp; + }); + } + } +} + +const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes +const MAX_RETRY_COUNT = 3; +const INITIAL_RETRY_DELAY_MS = 1000; +const DELAY_MULTIPLIER = 2; +const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status'; +async function uploadBlob(file, uploadUrl, apiClient) { + var _a, _b, _c; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = 'upload'; + fileSize = file.size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + const chunk = file.slice(offset, offset + chunkSize); + if (offset + chunkSize >= fileSize) { + uploadCommand += ', finalize'; + } + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: '', + body: chunk, + httpMethod: 'POST', + httpOptions: { + apiVersion: '', + baseUrl: uploadUrl, + headers: { + 'X-Goog-Upload-Command': uploadCommand, + 'X-Goog-Upload-Offset': String(offset), + 'Content-Length': String(chunkSize), + }, + }, + }); + if ((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += chunkSize; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'active') { + break; + } + // TODO(b/401391430) Investigate why the upload status is not finalized + // even though all content has been uploaded. + if (fileSize <= offset) { + throw new Error('All content has been uploaded, but the upload status is not finalized.'); + } + } + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_c = response === null || response === void 0 ? void 0 : response.headers) === null || _c === void 0 ? void 0 : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + return responseJson['file']; +} +async function getBlobStat(file) { + const fileStat = { size: file.size, type: file.type }; + return fileStat; +} +function sleep(ms) { + return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeUploader { + async stat(file) { + const fileStat = { size: 0, type: undefined }; + if (typeof file === 'string') { + const originalStat = await fs__namespace.stat(file); + fileStat.size = originalStat.size; + fileStat.type = this.inferMimeType(file); + return fileStat; + } + else { + return await getBlobStat(file); + } + } + async upload(file, uploadUrl, apiClient) { + if (typeof file === 'string') { + return await this.uploadFileFromPath(file, uploadUrl, apiClient); + } + else { + return uploadBlob(file, uploadUrl, apiClient); + } + } + /** + * Infers the MIME type of a file based on its extension. + * + * @param filePath The path to the file. + * @returns The MIME type of the file, or undefined if it cannot be inferred. + */ + inferMimeType(filePath) { + // Get the file extension. + const fileExtension = filePath.slice(filePath.lastIndexOf('.') + 1); + // Create a map of file extensions to MIME types. + const mimeTypes = { + 'aac': 'audio/aac', + 'abw': 'application/x-abiword', + 'arc': 'application/x-freearc', + 'avi': 'video/x-msvideo', + 'azw': 'application/vnd.amazon.ebook', + 'bin': 'application/octet-stream', + 'bmp': 'image/bmp', + 'bz': 'application/x-bzip', + 'bz2': 'application/x-bzip2', + 'csh': 'application/x-csh', + 'css': 'text/css', + 'csv': 'text/csv', + 'doc': 'application/msword', + 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'eot': 'application/vnd.ms-fontobject', + 'epub': 'application/epub+zip', + 'gz': 'application/gzip', + 'gif': 'image/gif', + 'htm': 'text/html', + 'html': 'text/html', + 'ico': 'image/vnd.microsoft.icon', + 'ics': 'text/calendar', + 'jar': 'application/java-archive', + 'jpeg': 'image/jpeg', + 'jpg': 'image/jpeg', + 'js': 'text/javascript', + 'json': 'application/json', + 'jsonld': 'application/ld+json', + 'kml': 'application/vnd.google-earth.kml+xml', + 'kmz': 'application/vnd.google-earth.kmz+xml', + 'mjs': 'text/javascript', + 'mp3': 'audio/mpeg', + 'mp4': 'video/mp4', + 'mpeg': 'video/mpeg', + 'mpkg': 'application/vnd.apple.installer+xml', + 'odt': 'application/vnd.oasis.opendocument.text', + 'oga': 'audio/ogg', + 'ogv': 'video/ogg', + 'ogx': 'application/ogg', + 'opus': 'audio/opus', + 'otf': 'font/otf', + 'png': 'image/png', + 'pdf': 'application/pdf', + 'php': 'application/x-httpd-php', + 'ppt': 'application/vnd.ms-powerpoint', + 'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'rar': 'application/vnd.rar', + 'rtf': 'application/rtf', + 'sh': 'application/x-sh', + 'svg': 'image/svg+xml', + 'swf': 'application/x-shockwave-flash', + 'tar': 'application/x-tar', + 'tif': 'image/tiff', + 'tiff': 'image/tiff', + 'ts': 'video/mp2t', + 'ttf': 'font/ttf', + 'txt': 'text/plain', + 'vsd': 'application/vnd.visio', + 'wav': 'audio/wav', + 'weba': 'audio/webm', + 'webm': 'video/webm', + 'webp': 'image/webp', + 'woff': 'font/woff', + 'woff2': 'font/woff2', + 'xhtml': 'application/xhtml+xml', + 'xls': 'application/vnd.ms-excel', + 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xml': 'application/xml', + 'xul': 'application/vnd.mozilla.xul+xml', + 'zip': 'application/zip', + '3gp': 'video/3gpp', + '3g2': 'video/3gpp2', + '7z': 'application/x-7z-compressed', + }; + // Look up the MIME type based on the file extension. + const mimeType = mimeTypes[fileExtension.toLowerCase()]; + // Return the MIME type. + return mimeType; + } + async uploadFileFromPath(file, uploadUrl, apiClient) { + var _a, _b, _c; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = 'upload'; + let fileHandle; + try { + fileHandle = await fs__namespace.open(file, 'r'); + if (!fileHandle) { + throw new Error(`Failed to open file`); + } + fileSize = (await fileHandle.stat()).size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + if (offset + chunkSize >= fileSize) { + uploadCommand += ', finalize'; + } + const buffer = new Uint8Array(chunkSize); + const { bytesRead: bytesRead } = await fileHandle.read(buffer, 0, chunkSize, offset); + if (bytesRead !== chunkSize) { + throw new Error(`Failed to read ${chunkSize} bytes from file at offset ${offset}. bytes actually read: ${bytesRead}`); + } + const chunk = new Blob([buffer]); + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: '', + body: chunk, + httpMethod: 'POST', + httpOptions: { + apiVersion: '', + baseUrl: uploadUrl, + headers: { + 'X-Goog-Upload-Command': uploadCommand, + 'X-Goog-Upload-Offset': String(offset), + 'Content-Length': String(bytesRead), + }, + }, + }); + if ((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += bytesRead; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'active') { + break; + } + if (fileSize <= offset) { + throw new Error('All content has been uploaded, but the upload status is not finalized.'); + } + } + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_c = response === null || response === void 0 ? void 0 : response.headers) === null || _c === void 0 ? void 0 : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + return responseJson['file']; + } + finally { + // Ensure the file handle is always closed + if (fileHandle) { + await fileHandle.close(); + } + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const LANGUAGE_LABEL_PREFIX = 'gl-node/'; +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link + * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or + * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI + * API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API + * services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be + * set. When using Vertex AI, both {@link GoogleGenAIOptions.project} and {@link + * GoogleGenAIOptions.location} must be set, or a {@link + * GoogleGenAIOptions.apiKey} must be set when using Express Mode. + * + * Explicitly passed in values in {@link GoogleGenAIOptions} will always take + * precedence over environment variables. If both project/location and api_key + * exist in the environment variables, the project/location will be used. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +class GoogleGenAI { + constructor(options) { + var _a, _b, _c, _d, _e, _f; + // Validate explicitly set initializer values. + if ((options.project || options.location) && options.apiKey) { + throw new Error('Project/location and API key are mutually exclusive in the client initializer.'); + } + this.vertexai = + (_b = (_a = options.vertexai) !== null && _a !== void 0 ? _a : getBooleanEnv('GOOGLE_GENAI_USE_VERTEXAI')) !== null && _b !== void 0 ? _b : false; + const envApiKey = getApiKeyFromEnv(); + const envProject = getEnv('GOOGLE_CLOUD_PROJECT'); + const envLocation = getEnv('GOOGLE_CLOUD_LOCATION'); + this.apiKey = (_c = options.apiKey) !== null && _c !== void 0 ? _c : envApiKey; + this.project = (_d = options.project) !== null && _d !== void 0 ? _d : envProject; + this.location = (_e = options.location) !== null && _e !== void 0 ? _e : envLocation; + // Handle when to use Vertex AI in express mode (api key) + if (options.vertexai) { + if ((_f = options.googleAuthOptions) === null || _f === void 0 ? void 0 : _f.credentials) { + // Explicit credentials take precedence over implicit api_key. + console.debug('The user provided Google Cloud credentials will take precedence' + + ' over the API key from the environment variable.'); + this.apiKey = undefined; + } + // Explicit api_key and explicit project/location already handled above. + if ((envProject || envLocation) && options.apiKey) { + // Explicit api_key takes precedence over implicit project/location. + console.debug('The user provided Vertex AI API key will take precedence over' + + ' the project/location from the environment variables.'); + this.project = undefined; + this.location = undefined; + } + else if ((options.project || options.location) && envApiKey) { + // Explicit project/location takes precedence over implicit api_key. + console.debug('The user provided project/location will take precedence over' + + ' the API key from the environment variables.'); + this.apiKey = undefined; + } + else if ((envProject || envLocation) && envApiKey) { + // Implicit project/location takes precedence over implicit api_key. + console.debug('The project/location from the environment variables will take' + + ' precedence over the API key from the environment variables.'); + this.apiKey = undefined; + } + } + const baseUrl = getBaseUrl(options.httpOptions, options.vertexai, getEnv('GOOGLE_VERTEX_BASE_URL'), getEnv('GOOGLE_GEMINI_BASE_URL')); + if (baseUrl) { + if (options.httpOptions) { + options.httpOptions.baseUrl = baseUrl; + } + else { + options.httpOptions = { baseUrl: baseUrl }; + } + } + this.apiVersion = options.apiVersion; + const auth = new NodeAuth({ + apiKey: this.apiKey, + googleAuthOptions: options.googleAuthOptions, + }); + this.apiClient = new ApiClient({ + auth: auth, + project: this.project, + location: this.location, + apiVersion: this.apiVersion, + apiKey: this.apiKey, + vertexai: this.vertexai, + httpOptions: options.httpOptions, + userAgentExtra: LANGUAGE_LABEL_PREFIX + process.version, + uploader: new NodeUploader(), + downloader: new NodeDownloader(), + }); + this.models = new Models(this.apiClient); + this.live = new Live(this.apiClient, auth, new NodeWebSocketFactory()); + this.batches = new Batches(this.apiClient); + this.chats = new Chats(this.models, this.apiClient); + this.caches = new Caches(this.apiClient); + this.files = new Files(this.apiClient); + this.operations = new Operations(this.apiClient); + this.authTokens = new Tokens(this.apiClient); + this.tunings = new Tunings(this.apiClient); + } +} +function getEnv(env) { + var _a, _b, _c; + return (_c = (_b = (_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a[env]) === null || _b === void 0 ? void 0 : _b.trim()) !== null && _c !== void 0 ? _c : undefined; +} +function getBooleanEnv(env) { + return stringToBoolean(getEnv(env)); +} +function stringToBoolean(str) { + if (str === undefined) { + return false; + } + return str.toLowerCase() === 'true'; +} +function getApiKeyFromEnv() { + const envGoogleApiKey = getEnv('GOOGLE_API_KEY'); + const envGeminiApiKey = getEnv('GEMINI_API_KEY'); + if (envGoogleApiKey && envGeminiApiKey) { + console.warn('Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY.'); + } + return envGoogleApiKey || envGeminiApiKey; +} + +exports.ApiError = ApiError; +exports.Batches = Batches; +exports.Caches = Caches; +exports.Chat = Chat; +exports.Chats = Chats; +exports.ComputeTokensResponse = ComputeTokensResponse; +exports.ControlReferenceImage = ControlReferenceImage; +exports.CountTokensResponse = CountTokensResponse; +exports.CreateFileResponse = CreateFileResponse; +exports.DeleteCachedContentResponse = DeleteCachedContentResponse; +exports.DeleteFileResponse = DeleteFileResponse; +exports.DeleteModelResponse = DeleteModelResponse; +exports.EditImageResponse = EditImageResponse; +exports.EmbedContentResponse = EmbedContentResponse; +exports.Files = Files; +exports.FunctionResponse = FunctionResponse; +exports.GenerateContentResponse = GenerateContentResponse; +exports.GenerateContentResponsePromptFeedback = GenerateContentResponsePromptFeedback; +exports.GenerateContentResponseUsageMetadata = GenerateContentResponseUsageMetadata; +exports.GenerateImagesResponse = GenerateImagesResponse; +exports.GenerateVideosOperation = GenerateVideosOperation; +exports.GenerateVideosResponse = GenerateVideosResponse; +exports.GoogleGenAI = GoogleGenAI; +exports.HttpResponse = HttpResponse; +exports.InlinedResponse = InlinedResponse; +exports.ListBatchJobsResponse = ListBatchJobsResponse; +exports.ListCachedContentsResponse = ListCachedContentsResponse; +exports.ListFilesResponse = ListFilesResponse; +exports.ListModelsResponse = ListModelsResponse; +exports.ListTuningJobsResponse = ListTuningJobsResponse; +exports.Live = Live; +exports.LiveClientToolResponse = LiveClientToolResponse; +exports.LiveMusicServerMessage = LiveMusicServerMessage; +exports.LiveSendToolResponseParameters = LiveSendToolResponseParameters; +exports.LiveServerMessage = LiveServerMessage; +exports.MaskReferenceImage = MaskReferenceImage; +exports.Models = Models; +exports.Operations = Operations; +exports.Pager = Pager; +exports.RawReferenceImage = RawReferenceImage; +exports.RecontextImageResponse = RecontextImageResponse; +exports.ReplayResponse = ReplayResponse; +exports.SegmentImageResponse = SegmentImageResponse; +exports.Session = Session; +exports.StyleReferenceImage = StyleReferenceImage; +exports.SubjectReferenceImage = SubjectReferenceImage; +exports.Tokens = Tokens; +exports.UpscaleImageResponse = UpscaleImageResponse; +exports.createModelContent = createModelContent; +exports.createPartFromBase64 = createPartFromBase64; +exports.createPartFromCodeExecutionResult = createPartFromCodeExecutionResult; +exports.createPartFromExecutableCode = createPartFromExecutableCode; +exports.createPartFromFunctionCall = createPartFromFunctionCall; +exports.createPartFromFunctionResponse = createPartFromFunctionResponse; +exports.createPartFromText = createPartFromText; +exports.createPartFromUri = createPartFromUri; +exports.createUserContent = createUserContent; +exports.mcpToTool = mcpToTool; +exports.setDefaultBaseUrls = setDefaultBaseUrls; +//# sourceMappingURL=index.cjs.map diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/node/index.mjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/node/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c5d02a083749e45dde1fb8767df6437d9c0876fb --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/node/index.mjs @@ -0,0 +1,19055 @@ +import { GoogleAuth } from 'google-auth-library'; +import { createWriteStream, writeFile } from 'fs'; +import { Readable } from 'node:stream'; +import * as NodeWs from 'ws'; +import * as fs from 'fs/promises'; + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +let _defaultBaseGeminiUrl = undefined; +let _defaultBaseVertexUrl = undefined; +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +function setDefaultBaseUrls(baseUrlParams) { + _defaultBaseGeminiUrl = baseUrlParams.geminiUrl; + _defaultBaseVertexUrl = baseUrlParams.vertexUrl; +} +/** + * Returns the default base URLs for the Gemini API and Vertex AI API. + */ +function getDefaultBaseUrls() { + return { + geminiUrl: _defaultBaseGeminiUrl, + vertexUrl: _defaultBaseVertexUrl, + }; +} +/** + * Returns the default base URL based on the following priority: + * 1. Base URLs set via HttpOptions. + * 2. Base URLs set via the latest call to setDefaultBaseUrls. + * 3. Base URLs set via environment variables. + */ +function getBaseUrl(httpOptions, vertexai, vertexBaseUrlFromEnv, geminiBaseUrlFromEnv) { + var _a, _b; + if (!(httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.baseUrl)) { + const defaultBaseUrls = getDefaultBaseUrls(); + if (vertexai) { + return (_a = defaultBaseUrls.vertexUrl) !== null && _a !== void 0 ? _a : vertexBaseUrlFromEnv; + } + else { + return (_b = defaultBaseUrls.geminiUrl) !== null && _b !== void 0 ? _b : geminiBaseUrlFromEnv; + } + } + return httpOptions.baseUrl; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BaseModule { +} +function formatMap(templateString, valueMap) { + // Use a regular expression to find all placeholders in the template string + const regex = /\{([^}]+)\}/g; + // Replace each placeholder with its corresponding value from the valueMap + return templateString.replace(regex, (match, key) => { + if (Object.prototype.hasOwnProperty.call(valueMap, key)) { + const value = valueMap[key]; + // Convert the value to a string if it's not a string already + return value !== undefined && value !== null ? String(value) : ''; + } + else { + // Handle missing keys + throw new Error(`Key '${key}' not found in valueMap.`); + } + }); +} +function setValueByPath(data, keys, value) { + for (let i = 0; i < keys.length - 1; i++) { + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (!(keyName in data)) { + if (Array.isArray(value)) { + data[keyName] = Array.from({ length: value.length }, () => ({})); + } + else { + throw new Error(`Value must be a list given an array path ${key}`); + } + } + if (Array.isArray(data[keyName])) { + const arrayData = data[keyName]; + if (Array.isArray(value)) { + for (let j = 0; j < arrayData.length; j++) { + const entry = arrayData[j]; + setValueByPath(entry, keys.slice(i + 1), value[j]); + } + } + else { + for (const d of arrayData) { + setValueByPath(d, keys.slice(i + 1), value); + } + } + } + return; + } + else if (key.endsWith('[0]')) { + const keyName = key.slice(0, -3); + if (!(keyName in data)) { + data[keyName] = [{}]; + } + const arrayData = data[keyName]; + setValueByPath(arrayData[0], keys.slice(i + 1), value); + return; + } + if (!data[key] || typeof data[key] !== 'object') { + data[key] = {}; + } + data = data[key]; + } + const keyToSet = keys[keys.length - 1]; + const existingData = data[keyToSet]; + if (existingData !== undefined) { + if (!value || + (typeof value === 'object' && Object.keys(value).length === 0)) { + return; + } + if (value === existingData) { + return; + } + if (typeof existingData === 'object' && + typeof value === 'object' && + existingData !== null && + value !== null) { + Object.assign(existingData, value); + } + else { + throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`); + } + } + else { + data[keyToSet] = value; + } +} +function getValueByPath(data, keys) { + try { + if (keys.length === 1 && keys[0] === '_self') { + return data; + } + for (let i = 0; i < keys.length; i++) { + if (typeof data !== 'object' || data === null) { + return undefined; + } + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (keyName in data) { + const arrayData = data[keyName]; + if (!Array.isArray(arrayData)) { + return undefined; + } + return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1))); + } + else { + return undefined; + } + } + else { + data = data[key]; + } + } + return data; + } + catch (error) { + if (error instanceof TypeError) { + return undefined; + } + throw error; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tBytes$1(fromBytes) { + if (typeof fromBytes !== 'string') { + throw new Error('fromImageBytes must be a string'); + } + // TODO(b/389133914): Remove dummy bytes converter. + return fromBytes; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +/** Required. Outcome of the code execution. */ +var Outcome; +(function (Outcome) { + /** + * Unspecified status. This value should not be used. + */ + Outcome["OUTCOME_UNSPECIFIED"] = "OUTCOME_UNSPECIFIED"; + /** + * Code execution completed successfully. + */ + Outcome["OUTCOME_OK"] = "OUTCOME_OK"; + /** + * Code execution finished but with a failure. `stderr` should contain the reason. + */ + Outcome["OUTCOME_FAILED"] = "OUTCOME_FAILED"; + /** + * Code execution ran for too long, and was cancelled. There may or may not be a partial output present. + */ + Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "OUTCOME_DEADLINE_EXCEEDED"; +})(Outcome || (Outcome = {})); +/** Required. Programming language of the `code`. */ +var Language; +(function (Language) { + /** + * Unspecified language. This value should not be used. + */ + Language["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED"; + /** + * Python >= 3.10, with numpy and simpy available. + */ + Language["PYTHON"] = "PYTHON"; +})(Language || (Language = {})); +/** Optional. The type of the data. */ +var Type; +(function (Type) { + /** + * Not specified, should not be used. + */ + Type["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + /** + * OpenAPI string type + */ + Type["STRING"] = "STRING"; + /** + * OpenAPI number type + */ + Type["NUMBER"] = "NUMBER"; + /** + * OpenAPI integer type + */ + Type["INTEGER"] = "INTEGER"; + /** + * OpenAPI boolean type + */ + Type["BOOLEAN"] = "BOOLEAN"; + /** + * OpenAPI array type + */ + Type["ARRAY"] = "ARRAY"; + /** + * OpenAPI object type + */ + Type["OBJECT"] = "OBJECT"; + /** + * Null type + */ + Type["NULL"] = "NULL"; +})(Type || (Type = {})); +/** Required. Harm category. */ +var HarmCategory; +(function (HarmCategory) { + /** + * The harm category is unspecified. + */ + HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + /** + * The harm category is hate speech. + */ + HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + /** + * The harm category is dangerous content. + */ + HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT"; + /** + * The harm category is harassment. + */ + HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + /** + * The harm category is sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY"; + /** + * The harm category is image hate. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE"; + /** + * The harm category is image dangerous content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"; + /** + * The harm category is image harassment. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HARASSMENT"] = "HARM_CATEGORY_IMAGE_HARASSMENT"; + /** + * The harm category is image sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"; +})(HarmCategory || (HarmCategory = {})); +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +var HarmBlockMethod; +(function (HarmBlockMethod) { + /** + * The harm block method is unspecified. + */ + HarmBlockMethod["HARM_BLOCK_METHOD_UNSPECIFIED"] = "HARM_BLOCK_METHOD_UNSPECIFIED"; + /** + * The harm block method uses both probability and severity scores. + */ + HarmBlockMethod["SEVERITY"] = "SEVERITY"; + /** + * The harm block method uses the probability score. + */ + HarmBlockMethod["PROBABILITY"] = "PROBABILITY"; +})(HarmBlockMethod || (HarmBlockMethod = {})); +/** Required. The harm block threshold. */ +var HarmBlockThreshold; +(function (HarmBlockThreshold) { + /** + * Unspecified harm block threshold. + */ + HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + /** + * Block low threshold and above (i.e. block more). + */ + HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + /** + * Block medium threshold and above. + */ + HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + /** + * Block only high threshold (i.e. block less). + */ + HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + /** + * Block none. + */ + HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; + /** + * Turn off the safety filter. + */ + HarmBlockThreshold["OFF"] = "OFF"; +})(HarmBlockThreshold || (HarmBlockThreshold = {})); +/** The mode of the predictor to be used in dynamic retrieval. */ +var Mode; +(function (Mode) { + /** + * Always trigger retrieval. + */ + Mode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + Mode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(Mode || (Mode = {})); +/** Type of auth scheme. */ +var AuthType; +(function (AuthType) { + AuthType["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED"; + /** + * No Auth. + */ + AuthType["NO_AUTH"] = "NO_AUTH"; + /** + * API Key Auth. + */ + AuthType["API_KEY_AUTH"] = "API_KEY_AUTH"; + /** + * HTTP Basic Auth. + */ + AuthType["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH"; + /** + * Google Service Account Auth. + */ + AuthType["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH"; + /** + * OAuth auth. + */ + AuthType["OAUTH"] = "OAUTH"; + /** + * OpenID Connect (OIDC) Auth. + */ + AuthType["OIDC_AUTH"] = "OIDC_AUTH"; +})(AuthType || (AuthType = {})); +/** The API spec that the external API implements. */ +var ApiSpec; +(function (ApiSpec) { + /** + * Unspecified API spec. This value should not be used. + */ + ApiSpec["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED"; + /** + * Simple search API spec. + */ + ApiSpec["SIMPLE_SEARCH"] = "SIMPLE_SEARCH"; + /** + * Elastic search API spec. + */ + ApiSpec["ELASTIC_SEARCH"] = "ELASTIC_SEARCH"; +})(ApiSpec || (ApiSpec = {})); +/** Status of the url retrieval. */ +var UrlRetrievalStatus; +(function (UrlRetrievalStatus) { + /** + * Default value. This value is unused + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = "URL_RETRIEVAL_STATUS_UNSPECIFIED"; + /** + * Url retrieval is successful. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_SUCCESS"] = "URL_RETRIEVAL_STATUS_SUCCESS"; + /** + * Url retrieval is failed due to error. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_ERROR"] = "URL_RETRIEVAL_STATUS_ERROR"; + /** + * Url retrieval is failed because the content is behind paywall. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_PAYWALL"] = "URL_RETRIEVAL_STATUS_PAYWALL"; + /** + * Url retrieval is failed because the content is unsafe. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSAFE"] = "URL_RETRIEVAL_STATUS_UNSAFE"; +})(UrlRetrievalStatus || (UrlRetrievalStatus = {})); +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +var FinishReason; +(function (FinishReason) { + /** + * The finish reason is unspecified. + */ + FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + FinishReason["STOP"] = "STOP"; + /** + * Token generation reached the configured maximum output tokens. + */ + FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + FinishReason["SAFETY"] = "SAFETY"; + /** + * The token generation stopped because of potential recitation. + */ + FinishReason["RECITATION"] = "RECITATION"; + /** + * The token generation stopped because of using an unsupported language. + */ + FinishReason["LANGUAGE"] = "LANGUAGE"; + /** + * All other reasons that stopped the token generation. + */ + FinishReason["OTHER"] = "OTHER"; + /** + * Token generation stopped because the content contains forbidden terms. + */ + FinishReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Token generation stopped for potentially containing prohibited content. + */ + FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). + */ + FinishReason["SPII"] = "SPII"; + /** + * The function call generated by the model is invalid. + */ + FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; + /** + * Token generation stopped because generated images have safety violations. + */ + FinishReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; + /** + * The tool call generated by the model is invalid. + */ + FinishReason["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL"; +})(FinishReason || (FinishReason = {})); +/** Output only. Harm probability levels in the content. */ +var HarmProbability; +(function (HarmProbability) { + /** + * Harm probability unspecified. + */ + HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED"; + /** + * Negligible level of harm. + */ + HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; + /** + * Low level of harm. + */ + HarmProbability["LOW"] = "LOW"; + /** + * Medium level of harm. + */ + HarmProbability["MEDIUM"] = "MEDIUM"; + /** + * High level of harm. + */ + HarmProbability["HIGH"] = "HIGH"; +})(HarmProbability || (HarmProbability = {})); +/** Output only. Harm severity levels in the content. */ +var HarmSeverity; +(function (HarmSeverity) { + /** + * Harm severity unspecified. + */ + HarmSeverity["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED"; + /** + * Negligible level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE"; + /** + * Low level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW"; + /** + * Medium level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM"; + /** + * High level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH"; +})(HarmSeverity || (HarmSeverity = {})); +/** Output only. Blocked reason. */ +var BlockedReason; +(function (BlockedReason) { + /** + * Unspecified blocked reason. + */ + BlockedReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + /** + * Candidates blocked due to safety. + */ + BlockedReason["SAFETY"] = "SAFETY"; + /** + * Candidates blocked due to other reason. + */ + BlockedReason["OTHER"] = "OTHER"; + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BlockedReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Candidates blocked due to prohibited content. + */ + BlockedReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Candidates blocked due to unsafe image generation content. + */ + BlockedReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; +})(BlockedReason || (BlockedReason = {})); +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +var TrafficType; +(function (TrafficType) { + /** + * Unspecified request traffic type. + */ + TrafficType["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED"; + /** + * Type for Pay-As-You-Go traffic. + */ + TrafficType["ON_DEMAND"] = "ON_DEMAND"; + /** + * Type for Provisioned Throughput traffic. + */ + TrafficType["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT"; +})(TrafficType || (TrafficType = {})); +/** Server content modalities. */ +var Modality; +(function (Modality) { + /** + * The modality is unspecified. + */ + Modality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Indicates the model should return text + */ + Modality["TEXT"] = "TEXT"; + /** + * Indicates the model should return images. + */ + Modality["IMAGE"] = "IMAGE"; + /** + * Indicates the model should return audio. + */ + Modality["AUDIO"] = "AUDIO"; +})(Modality || (Modality = {})); +/** The media resolution to use. */ +var MediaResolution; +(function (MediaResolution) { + /** + * Media resolution has not been set + */ + MediaResolution["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED"; + /** + * Media resolution set to low (64 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + /** + * Media resolution set to medium (256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; +})(MediaResolution || (MediaResolution = {})); +/** Job state. */ +var JobState; +(function (JobState) { + /** + * The job state is unspecified. + */ + JobState["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED"; + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JobState["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED"; + /** + * The service is preparing to run the job. + */ + JobState["JOB_STATE_PENDING"] = "JOB_STATE_PENDING"; + /** + * The job is in progress. + */ + JobState["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING"; + /** + * The job completed successfully. + */ + JobState["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED"; + /** + * The job failed. + */ + JobState["JOB_STATE_FAILED"] = "JOB_STATE_FAILED"; + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JobState["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING"; + /** + * The job has been cancelled. + */ + JobState["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED"; + /** + * The job has been stopped, and can be resumed. + */ + JobState["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED"; + /** + * The job has expired. + */ + JobState["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED"; + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JobState["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING"; + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JobState["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED"; +})(JobState || (JobState = {})); +/** Tuning mode. */ +var TuningMode; +(function (TuningMode) { + /** + * Tuning mode is unspecified. + */ + TuningMode["TUNING_MODE_UNSPECIFIED"] = "TUNING_MODE_UNSPECIFIED"; + /** + * Full fine-tuning mode. + */ + TuningMode["TUNING_MODE_FULL"] = "TUNING_MODE_FULL"; + /** + * PEFT adapter tuning mode. + */ + TuningMode["TUNING_MODE_PEFT_ADAPTER"] = "TUNING_MODE_PEFT_ADAPTER"; +})(TuningMode || (TuningMode = {})); +/** Optional. Adapter size for tuning. */ +var AdapterSize; +(function (AdapterSize) { + /** + * Adapter size is unspecified. + */ + AdapterSize["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED"; + /** + * Adapter size 1. + */ + AdapterSize["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE"; + /** + * Adapter size 2. + */ + AdapterSize["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO"; + /** + * Adapter size 4. + */ + AdapterSize["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR"; + /** + * Adapter size 8. + */ + AdapterSize["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT"; + /** + * Adapter size 16. + */ + AdapterSize["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN"; + /** + * Adapter size 32. + */ + AdapterSize["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO"; +})(AdapterSize || (AdapterSize = {})); +/** Options for feature selection preference. */ +var FeatureSelectionPreference; +(function (FeatureSelectionPreference) { + FeatureSelectionPreference["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"; + FeatureSelectionPreference["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY"; + FeatureSelectionPreference["BALANCED"] = "BALANCED"; + FeatureSelectionPreference["PRIORITIZE_COST"] = "PRIORITIZE_COST"; +})(FeatureSelectionPreference || (FeatureSelectionPreference = {})); +/** Defines the function behavior. Defaults to `BLOCKING`. */ +var Behavior; +(function (Behavior) { + /** + * This value is unused. + */ + Behavior["UNSPECIFIED"] = "UNSPECIFIED"; + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + Behavior["BLOCKING"] = "BLOCKING"; + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + Behavior["NON_BLOCKING"] = "NON_BLOCKING"; +})(Behavior || (Behavior = {})); +/** Config for the dynamic retrieval config mode. */ +var DynamicRetrievalConfigMode; +(function (DynamicRetrievalConfigMode) { + /** + * Always trigger retrieval. + */ + DynamicRetrievalConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + DynamicRetrievalConfigMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(DynamicRetrievalConfigMode || (DynamicRetrievalConfigMode = {})); +/** The environment being operated. */ +var Environment; +(function (Environment) { + /** + * Defaults to browser. + */ + Environment["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED"; + /** + * Operates in a web browser. + */ + Environment["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER"; +})(Environment || (Environment = {})); +/** Config for the function calling config mode. */ +var FunctionCallingConfigMode; +(function (FunctionCallingConfigMode) { + /** + * The function calling config mode is unspecified. Should not be used. + */ + FunctionCallingConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + FunctionCallingConfigMode["AUTO"] = "AUTO"; + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + FunctionCallingConfigMode["ANY"] = "ANY"; + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + FunctionCallingConfigMode["NONE"] = "NONE"; +})(FunctionCallingConfigMode || (FunctionCallingConfigMode = {})); +/** Enum that controls the safety filter level for objectionable content. */ +var SafetyFilterLevel; +(function (SafetyFilterLevel) { + SafetyFilterLevel["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + SafetyFilterLevel["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + SafetyFilterLevel["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + SafetyFilterLevel["BLOCK_NONE"] = "BLOCK_NONE"; +})(SafetyFilterLevel || (SafetyFilterLevel = {})); +/** Enum that controls the generation of people. */ +var PersonGeneration; +(function (PersonGeneration) { + /** + * Block generation of images of people. + */ + PersonGeneration["DONT_ALLOW"] = "DONT_ALLOW"; + /** + * Generate images of adults, but not children. + */ + PersonGeneration["ALLOW_ADULT"] = "ALLOW_ADULT"; + /** + * Generate images that include adults and children. + */ + PersonGeneration["ALLOW_ALL"] = "ALLOW_ALL"; +})(PersonGeneration || (PersonGeneration = {})); +/** Enum that specifies the language of the text in the prompt. */ +var ImagePromptLanguage; +(function (ImagePromptLanguage) { + /** + * Auto-detect the language. + */ + ImagePromptLanguage["auto"] = "auto"; + /** + * English + */ + ImagePromptLanguage["en"] = "en"; + /** + * Japanese + */ + ImagePromptLanguage["ja"] = "ja"; + /** + * Korean + */ + ImagePromptLanguage["ko"] = "ko"; + /** + * Hindi + */ + ImagePromptLanguage["hi"] = "hi"; + /** + * Chinese + */ + ImagePromptLanguage["zh"] = "zh"; + /** + * Portuguese + */ + ImagePromptLanguage["pt"] = "pt"; + /** + * Spanish + */ + ImagePromptLanguage["es"] = "es"; +})(ImagePromptLanguage || (ImagePromptLanguage = {})); +/** Enum representing the mask mode of a mask reference image. */ +var MaskReferenceMode; +(function (MaskReferenceMode) { + MaskReferenceMode["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT"; + MaskReferenceMode["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED"; + MaskReferenceMode["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND"; + MaskReferenceMode["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND"; + MaskReferenceMode["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC"; +})(MaskReferenceMode || (MaskReferenceMode = {})); +/** Enum representing the control type of a control reference image. */ +var ControlReferenceType; +(function (ControlReferenceType) { + ControlReferenceType["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT"; + ControlReferenceType["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY"; + ControlReferenceType["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE"; + ControlReferenceType["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH"; +})(ControlReferenceType || (ControlReferenceType = {})); +/** Enum representing the subject type of a subject reference image. */ +var SubjectReferenceType; +(function (SubjectReferenceType) { + SubjectReferenceType["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT"; + SubjectReferenceType["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON"; + SubjectReferenceType["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL"; + SubjectReferenceType["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT"; +})(SubjectReferenceType || (SubjectReferenceType = {})); +/** Enum representing the Imagen 3 Edit mode. */ +var EditMode; +(function (EditMode) { + EditMode["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT"; + EditMode["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL"; + EditMode["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION"; + EditMode["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT"; + EditMode["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING"; + EditMode["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE"; + EditMode["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP"; + EditMode["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE"; +})(EditMode || (EditMode = {})); +/** Enum that represents the segmentation mode. */ +var SegmentMode; +(function (SegmentMode) { + SegmentMode["FOREGROUND"] = "FOREGROUND"; + SegmentMode["BACKGROUND"] = "BACKGROUND"; + SegmentMode["PROMPT"] = "PROMPT"; + SegmentMode["SEMANTIC"] = "SEMANTIC"; + SegmentMode["INTERACTIVE"] = "INTERACTIVE"; +})(SegmentMode || (SegmentMode = {})); +/** Enum that controls the compression quality of the generated videos. */ +var VideoCompressionQuality; +(function (VideoCompressionQuality) { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + VideoCompressionQuality["OPTIMIZED"] = "OPTIMIZED"; + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + VideoCompressionQuality["LOSSLESS"] = "LOSSLESS"; +})(VideoCompressionQuality || (VideoCompressionQuality = {})); +/** State for the lifecycle of a File. */ +var FileState; +(function (FileState) { + FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + FileState["PROCESSING"] = "PROCESSING"; + FileState["ACTIVE"] = "ACTIVE"; + FileState["FAILED"] = "FAILED"; +})(FileState || (FileState = {})); +/** Source of the File. */ +var FileSource; +(function (FileSource) { + FileSource["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED"; + FileSource["UPLOADED"] = "UPLOADED"; + FileSource["GENERATED"] = "GENERATED"; +})(FileSource || (FileSource = {})); +/** Server content modalities. */ +var MediaModality; +(function (MediaModality) { + /** + * The modality is unspecified. + */ + MediaModality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Plain text. + */ + MediaModality["TEXT"] = "TEXT"; + /** + * Images. + */ + MediaModality["IMAGE"] = "IMAGE"; + /** + * Video. + */ + MediaModality["VIDEO"] = "VIDEO"; + /** + * Audio. + */ + MediaModality["AUDIO"] = "AUDIO"; + /** + * Document, e.g. PDF. + */ + MediaModality["DOCUMENT"] = "DOCUMENT"; +})(MediaModality || (MediaModality = {})); +/** Start of speech sensitivity. */ +var StartSensitivity; +(function (StartSensitivity) { + /** + * The default is START_SENSITIVITY_LOW. + */ + StartSensitivity["START_SENSITIVITY_UNSPECIFIED"] = "START_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection will detect the start of speech more often. + */ + StartSensitivity["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH"; + /** + * Automatic detection will detect the start of speech less often. + */ + StartSensitivity["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW"; +})(StartSensitivity || (StartSensitivity = {})); +/** End of speech sensitivity. */ +var EndSensitivity; +(function (EndSensitivity) { + /** + * The default is END_SENSITIVITY_LOW. + */ + EndSensitivity["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection ends speech more often. + */ + EndSensitivity["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH"; + /** + * Automatic detection ends speech less often. + */ + EndSensitivity["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW"; +})(EndSensitivity || (EndSensitivity = {})); +/** The different ways of handling user activity. */ +var ActivityHandling; +(function (ActivityHandling) { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ActivityHandling["ACTIVITY_HANDLING_UNSPECIFIED"] = "ACTIVITY_HANDLING_UNSPECIFIED"; + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + ActivityHandling["START_OF_ACTIVITY_INTERRUPTS"] = "START_OF_ACTIVITY_INTERRUPTS"; + /** + * The model's response will not be interrupted. + */ + ActivityHandling["NO_INTERRUPTION"] = "NO_INTERRUPTION"; +})(ActivityHandling || (ActivityHandling = {})); +/** Options about which input is included in the user's turn. */ +var TurnCoverage; +(function (TurnCoverage) { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TurnCoverage["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED"; + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TurnCoverage["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY"; + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TurnCoverage["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT"; +})(TurnCoverage || (TurnCoverage = {})); +/** Specifies how the response should be scheduled in the conversation. */ +var FunctionResponseScheduling; +(function (FunctionResponseScheduling) { + /** + * This value is unused. + */ + FunctionResponseScheduling["SCHEDULING_UNSPECIFIED"] = "SCHEDULING_UNSPECIFIED"; + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + FunctionResponseScheduling["SILENT"] = "SILENT"; + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + FunctionResponseScheduling["WHEN_IDLE"] = "WHEN_IDLE"; + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + FunctionResponseScheduling["INTERRUPT"] = "INTERRUPT"; +})(FunctionResponseScheduling || (FunctionResponseScheduling = {})); +/** Scale of the generated music. */ +var Scale; +(function (Scale) { + /** + * Default value. This value is unused. + */ + Scale["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED"; + /** + * C major or A minor. + */ + Scale["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR"; + /** + * Db major or Bb minor. + */ + Scale["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR"; + /** + * D major or B minor. + */ + Scale["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR"; + /** + * Eb major or C minor + */ + Scale["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR"; + /** + * E major or Db minor. + */ + Scale["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR"; + /** + * F major or D minor. + */ + Scale["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR"; + /** + * Gb major or Eb minor. + */ + Scale["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR"; + /** + * G major or E minor. + */ + Scale["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR"; + /** + * Ab major or F minor. + */ + Scale["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR"; + /** + * A major or Gb minor. + */ + Scale["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR"; + /** + * Bb major or G minor. + */ + Scale["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR"; + /** + * B major or Ab minor. + */ + Scale["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR"; +})(Scale || (Scale = {})); +/** The mode of music generation. */ +var MusicGenerationMode; +(function (MusicGenerationMode) { + /** + * Rely on the server default generation mode. + */ + MusicGenerationMode["MUSIC_GENERATION_MODE_UNSPECIFIED"] = "MUSIC_GENERATION_MODE_UNSPECIFIED"; + /** + * Steer text prompts to regions of latent space with higher quality + music. + */ + MusicGenerationMode["QUALITY"] = "QUALITY"; + /** + * Steer text prompts to regions of latent space with a larger + diversity of music. + */ + MusicGenerationMode["DIVERSITY"] = "DIVERSITY"; + /** + * Steer text prompts to regions of latent space more likely to + generate music with vocals. + */ + MusicGenerationMode["VOCALIZATION"] = "VOCALIZATION"; +})(MusicGenerationMode || (MusicGenerationMode = {})); +/** The playback control signal to apply to the music generation. */ +var LiveMusicPlaybackControl; +(function (LiveMusicPlaybackControl) { + /** + * This value is unused. + */ + LiveMusicPlaybackControl["PLAYBACK_CONTROL_UNSPECIFIED"] = "PLAYBACK_CONTROL_UNSPECIFIED"; + /** + * Start generating the music. + */ + LiveMusicPlaybackControl["PLAY"] = "PLAY"; + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + LiveMusicPlaybackControl["PAUSE"] = "PAUSE"; + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + LiveMusicPlaybackControl["STOP"] = "STOP"; + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + LiveMusicPlaybackControl["RESET_CONTEXT"] = "RESET_CONTEXT"; +})(LiveMusicPlaybackControl || (LiveMusicPlaybackControl = {})); +/** A function response. */ +class FunctionResponse { +} +/** + * Creates a `Part` object from a `URI` string. + */ +function createPartFromUri(uri, mimeType) { + return { + fileData: { + fileUri: uri, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from a `text` string. + */ +function createPartFromText(text) { + return { + text: text, + }; +} +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +function createPartFromFunctionCall(name, args) { + return { + functionCall: { + name: name, + args: args, + }, + }; +} +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +function createPartFromFunctionResponse(id, name, response) { + return { + functionResponse: { + id: id, + name: name, + response: response, + }, + }; +} +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +function createPartFromBase64(data, mimeType) { + return { + inlineData: { + data: data, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +function createPartFromCodeExecutionResult(outcome, output) { + return { + codeExecutionResult: { + outcome: outcome, + output: output, + }, + }; +} +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +function createPartFromExecutableCode(code, language) { + return { + executableCode: { + code: code, + language: language, + }, + }; +} +function _isPart(obj) { + if (typeof obj === 'object' && obj !== null) { + return ('fileData' in obj || + 'text' in obj || + 'functionCall' in obj || + 'functionResponse' in obj || + 'inlineData' in obj || + 'videoMetadata' in obj || + 'codeExecutionResult' in obj || + 'executableCode' in obj); + } + return false; +} +function _toParts(partOrString) { + const parts = []; + if (typeof partOrString === 'string') { + parts.push(createPartFromText(partOrString)); + } + else if (_isPart(partOrString)) { + parts.push(partOrString); + } + else if (Array.isArray(partOrString)) { + if (partOrString.length === 0) { + throw new Error('partOrString cannot be an empty array'); + } + for (const part of partOrString) { + if (typeof part === 'string') { + parts.push(createPartFromText(part)); + } + else if (_isPart(part)) { + parts.push(part); + } + else { + throw new Error('element in PartUnion must be a Part object or string'); + } + } + } + else { + throw new Error('partOrString must be a Part object, string, or array'); + } + return parts; +} +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +function createUserContent(partOrString) { + return { + role: 'user', + parts: _toParts(partOrString), + }; +} +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +function createModelContent(partOrString) { + return { + role: 'model', + parts: _toParts(partOrString), + }; +} +/** A wrapper class for the http response. */ +class HttpResponse { + constructor(response) { + // Process the headers. + const headers = {}; + for (const pair of response.headers.entries()) { + headers[pair[0]] = pair[1]; + } + this.headers = headers; + // Keep the original response. + this.responseInternal = response; + } + json() { + return this.responseInternal.json(); + } +} +/** Content filter results for a prompt sent in the request. */ +class GenerateContentResponsePromptFeedback { +} +/** Usage metadata about response(s). */ +class GenerateContentResponseUsageMetadata { +} +/** Response message for PredictionService.GenerateContent. */ +class GenerateContentResponse { + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning text from the first one.'); + } + let text = ''; + let anyTextPartText = false; + const nonTextParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + (fieldValue !== null || fieldValue !== undefined)) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartText = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartText ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning data from the first one.'); + } + let data = ''; + const nonDataParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && + (fieldValue !== null || fieldValue !== undefined)) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning function calls from the first one.'); + } + const functionCalls = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.functionCall).map((part) => part.functionCall).filter((functionCall) => functionCall !== undefined); + if ((functionCalls === null || functionCalls === void 0 ? void 0 : functionCalls.length) === 0) { + return undefined; + } + return functionCalls; + } + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning executable code from the first one.'); + } + const executableCode = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.executableCode).map((part) => part.executableCode).filter((executableCode) => executableCode !== undefined); + if ((executableCode === null || executableCode === void 0 ? void 0 : executableCode.length) === 0) { + return undefined; + } + return (_j = executableCode === null || executableCode === void 0 ? void 0 : executableCode[0]) === null || _j === void 0 ? void 0 : _j.code; + } + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning code execution result from the first one.'); + } + const codeExecutionResult = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.codeExecutionResult).map((part) => part.codeExecutionResult).filter((codeExecutionResult) => codeExecutionResult !== undefined); + if ((codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult.length) === 0) { + return undefined; + } + return (_j = codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult[0]) === null || _j === void 0 ? void 0 : _j.output; + } +} +/** Response for the embed_content method. */ +class EmbedContentResponse { +} +/** The output images response. */ +class GenerateImagesResponse { +} +/** Response for the request to edit an image. */ +class EditImageResponse { +} +class UpscaleImageResponse { +} +/** The output images response. */ +class RecontextImageResponse { +} +/** The output images response. */ +class SegmentImageResponse { +} +class ListModelsResponse { +} +class DeleteModelResponse { +} +/** Response for counting tokens. */ +class CountTokensResponse { +} +/** Response for computing tokens. */ +class ComputeTokensResponse { +} +/** Response with generated videos. */ +class GenerateVideosResponse { +} +/** Response for the list tuning jobs method. */ +class ListTuningJobsResponse { +} +/** Empty response for caches.delete method. */ +class DeleteCachedContentResponse { +} +class ListCachedContentsResponse { +} +/** Response for the list files method. */ +class ListFilesResponse { +} +/** Response for the create file method. */ +class CreateFileResponse { +} +/** Response for the delete file method. */ +class DeleteFileResponse { +} +/** Config for `inlined_responses` parameter. */ +class InlinedResponse { +} +/** Config for batches.list return value. */ +class ListBatchJobsResponse { +} +/** Represents a single response in a replay. */ +class ReplayResponse { +} +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +class RawReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_RAW', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + }; + return referenceImageAPI; + } +} +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +class MaskReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_MASK', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + maskImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +class ControlReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_CONTROL', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + controlImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +class StyleReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_STYLE', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + styleImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +class SubjectReferenceImage { + /* Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_SUBJECT', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + subjectImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** Response message for API call. */ +class LiveServerMessage { + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text() { + var _a, _b, _c; + let text = ''; + let anyTextPartFound = false; + const nonTextParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + fieldValue !== null) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartFound = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartFound ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c; + let data = ''; + const nonDataParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && fieldValue !== null) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } +} +/** A video generation long-running operation. */ +class GenerateVideosOperation { + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }) { + const operation = new GenerateVideosOperation(); + operation.name = apiResponse['name']; + operation.metadata = apiResponse['metadata']; + operation.done = apiResponse['done']; + operation.error = apiResponse['error']; + if (isVertexAI) { + const response = apiResponse['response']; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const responseVideos = response['videos']; + operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => { + return { + video: { + uri: generatedVideo['gcsUri'], + videoBytes: generatedVideo['bytesBase64Encoded'] + ? tBytes$1(generatedVideo['bytesBase64Encoded']) + : undefined, + mimeType: generatedVideo['mimeType'], + }, + }; + }); + operationResponse.raiMediaFilteredCount = response['raiMediaFilteredCount']; + operationResponse.raiMediaFilteredReasons = response['raiMediaFilteredReasons']; + operation.response = operationResponse; + } + } + else { + const response = apiResponse['response']; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const generatedVideoResponse = response['generateVideoResponse']; + const responseVideos = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['generatedSamples']; + operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => { + const video = generatedVideo['video']; + return { + video: { + uri: video === null || video === void 0 ? void 0 : video['uri'], + videoBytes: (video === null || video === void 0 ? void 0 : video['encodedVideo']) + ? tBytes$1(video === null || video === void 0 ? void 0 : video['encodedVideo']) + : undefined, + mimeType: generatedVideo['encoding'], + }, + }; + }); + operationResponse.raiMediaFilteredCount = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['raiMediaFilteredCount']; + operationResponse.raiMediaFilteredReasons = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['raiMediaFilteredReasons']; + operation.response = operationResponse; + } + } + return operation; + } +} +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +class LiveClientToolResponse { +} +/** Parameters for sending tool responses to the live API. */ +class LiveSendToolResponseParameters { + constructor() { + /** Tool responses to send to the session. */ + this.functionResponses = []; + } +} +/** Response message for the LiveMusicClientMessage call. */ +class LiveMusicServerMessage { + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk() { + if (this.serverContent && + this.serverContent.audioChunks && + this.serverContent.audioChunks.length > 0) { + return this.serverContent.audioChunks[0]; + } + return undefined; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tModel(apiClient, model) { + if (!model || typeof model !== 'string') { + throw new Error('model is required and must be a string'); + } + if (apiClient.isVertexAI()) { + if (model.startsWith('publishers/') || + model.startsWith('projects/') || + model.startsWith('models/')) { + return model; + } + else if (model.indexOf('/') >= 0) { + const parts = model.split('/', 2); + return `publishers/${parts[0]}/models/${parts[1]}`; + } + else { + return `publishers/google/models/${model}`; + } + } + else { + if (model.startsWith('models/') || model.startsWith('tunedModels/')) { + return model; + } + else { + return `models/${model}`; + } + } +} +function tCachesModel(apiClient, model) { + const transformedModel = tModel(apiClient, model); + if (!transformedModel) { + return ''; + } + if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) { + // vertex caches only support model name start with projects. + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`; + } + else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) { + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`; + } + else { + return transformedModel; + } +} +function tBlobs(blobs) { + if (Array.isArray(blobs)) { + return blobs.map((blob) => tBlob(blob)); + } + else { + return [tBlob(blobs)]; + } +} +function tBlob(blob) { + if (typeof blob === 'object' && blob !== null) { + return blob; + } + throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof blob}`); +} +function tImageBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('image/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tAudioBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('audio/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tPart(origin) { + if (origin === null || origin === undefined) { + throw new Error('PartUnion is required'); + } + if (typeof origin === 'object') { + return origin; + } + if (typeof origin === 'string') { + return { text: origin }; + } + throw new Error(`Unsupported part type: ${typeof origin}`); +} +function tParts(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('PartListUnion is required'); + } + if (Array.isArray(origin)) { + return origin.map((item) => tPart(item)); + } + return [tPart(origin)]; +} +function _isContent(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'parts' in origin && + Array.isArray(origin.parts)); +} +function _isFunctionCallPart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionCall' in origin); +} +function _isFunctionResponsePart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionResponse' in origin); +} +function tContent(origin) { + if (origin === null || origin === undefined) { + throw new Error('ContentUnion is required'); + } + if (_isContent(origin)) { + // _isContent is a utility function that checks if the + // origin is a Content. + return origin; + } + return { + role: 'user', + parts: tParts(origin), + }; +} +function tContentsForEmbed(apiClient, origin) { + if (!origin) { + return []; + } + if (apiClient.isVertexAI() && Array.isArray(origin)) { + return origin.flatMap((item) => { + const content = tContent(item); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + }); + } + else if (apiClient.isVertexAI()) { + const content = tContent(origin); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + } + if (Array.isArray(origin)) { + return origin.map((item) => tContent(item)); + } + return [tContent(origin)]; +} +function tContents(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('contents are required'); + } + if (!Array.isArray(origin)) { + // If it's not an array, it's a single content or a single PartUnion. + if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them'); + } + return [tContent(origin)]; + } + const result = []; + const accumulatedParts = []; + const isContentArray = _isContent(origin[0]); + for (const item of origin) { + const isContent = _isContent(item); + if (isContent != isContentArray) { + throw new Error('Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them'); + } + if (isContent) { + // `isContent` contains the result of _isContent, which is a utility + // function that checks if the item is a Content. + result.push(item); + } + else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them'); + } + else { + accumulatedParts.push(item); + } + } + if (!isContentArray) { + result.push({ role: 'user', parts: tParts(accumulatedParts) }); + } + return result; +} +/* +Transform the type field from an array of types to an array of anyOf fields. +Example: + {type: ['STRING', 'NUMBER']} +will be transformed to + {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]} +*/ +function flattenTypeArrayToAnyOf(typeList, resultingSchema) { + if (typeList.includes('null')) { + resultingSchema['nullable'] = true; + } + const listWithoutNull = typeList.filter((type) => type !== 'null'); + if (listWithoutNull.length === 1) { + resultingSchema['type'] = Object.values(Type).includes(listWithoutNull[0].toUpperCase()) + ? listWithoutNull[0].toUpperCase() + : Type.TYPE_UNSPECIFIED; + } + else { + resultingSchema['anyOf'] = []; + for (const i of listWithoutNull) { + resultingSchema['anyOf'].push({ + 'type': Object.values(Type).includes(i.toUpperCase()) + ? i.toUpperCase() + : Type.TYPE_UNSPECIFIED, + }); + } + } +} +function processJsonSchema(_jsonSchema) { + const genAISchema = {}; + const schemaFieldNames = ['items']; + const listSchemaFieldNames = ['anyOf']; + const dictSchemaFieldNames = ['properties']; + if (_jsonSchema['type'] && _jsonSchema['anyOf']) { + throw new Error('type and anyOf cannot be both populated.'); + } + /* + This is to handle the nullable array or object. The _jsonSchema will + be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The + logic is to check if anyOf has 2 elements and one of the element is null, + if so, the anyOf field is unnecessary, so we need to get rid of the anyOf + field and make the schema nullable. Then use the other element as the new + _jsonSchema for processing. This is because the backend doesn't have a null + type. + This has to be checked before we process any other fields. + For example: + const objectNullable = z.object({ + nullableArray: z.array(z.string()).nullable(), + }); + Will have the raw _jsonSchema as: + { + type: 'OBJECT', + properties: { + nullableArray: { + anyOf: [ + {type: 'null'}, + { + type: 'array', + items: {type: 'string'}, + }, + ], + } + }, + required: [ 'nullableArray' ], + } + Will result in following schema compatible with Gemini API: + { + type: 'OBJECT', + properties: { + nullableArray: { + nullable: true, + type: 'ARRAY', + items: {type: 'string'}, + } + }, + required: [ 'nullableArray' ], + } + */ + const incomingAnyOf = _jsonSchema['anyOf']; + if (incomingAnyOf != null && incomingAnyOf.length == 2) { + if (incomingAnyOf[0]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[1]; + } + else if (incomingAnyOf[1]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[0]; + } + } + if (_jsonSchema['type'] instanceof Array) { + flattenTypeArrayToAnyOf(_jsonSchema['type'], genAISchema); + } + for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) { + // Skip if the fieldvalue is undefined or null. + if (fieldValue == null) { + continue; + } + if (fieldName == 'type') { + if (fieldValue === 'null') { + throw new Error('type: null can not be the only possible type for the field.'); + } + if (fieldValue instanceof Array) { + // we have already handled the type field with array of types in the + // beginning of this function. + continue; + } + genAISchema['type'] = Object.values(Type).includes(fieldValue.toUpperCase()) + ? fieldValue.toUpperCase() + : Type.TYPE_UNSPECIFIED; + } + else if (schemaFieldNames.includes(fieldName)) { + genAISchema[fieldName] = + processJsonSchema(fieldValue); + } + else if (listSchemaFieldNames.includes(fieldName)) { + const listSchemaFieldValue = []; + for (const item of fieldValue) { + if (item['type'] == 'null') { + genAISchema['nullable'] = true; + continue; + } + listSchemaFieldValue.push(processJsonSchema(item)); + } + genAISchema[fieldName] = + listSchemaFieldValue; + } + else if (dictSchemaFieldNames.includes(fieldName)) { + const dictSchemaFieldValue = {}; + for (const [key, value] of Object.entries(fieldValue)) { + dictSchemaFieldValue[key] = processJsonSchema(value); + } + genAISchema[fieldName] = + dictSchemaFieldValue; + } + else { + // additionalProperties is not included in JSONSchema, skipping it. + if (fieldName === 'additionalProperties') { + continue; + } + genAISchema[fieldName] = fieldValue; + } + } + return genAISchema; +} +// we take the unknown in the schema field because we want enable user to pass +// the output of major schema declaration tools without casting. Tools such as +// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type +// or object, see details in +// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7 +// typebox can return unknown, see details in +// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35 +// Note: proper json schemas with the $schema field set never arrive to this +// transformer. Schemas with $schema are routed to the equivalent API json +// schema field. +function tSchema(schema) { + return processJsonSchema(schema); +} +function tSpeechConfig(speechConfig) { + if (typeof speechConfig === 'object') { + return speechConfig; + } + else if (typeof speechConfig === 'string') { + return { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: speechConfig, + }, + }, + }; + } + else { + throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`); + } +} +function tLiveSpeechConfig(speechConfig) { + if ('multiSpeakerVoiceConfig' in speechConfig) { + throw new Error('multiSpeakerVoiceConfig is not supported in the live API.'); + } + return speechConfig; +} +function tTool(tool) { + if (tool.functionDeclarations) { + for (const functionDeclaration of tool.functionDeclarations) { + if (functionDeclaration.parameters) { + if (!Object.keys(functionDeclaration.parameters).includes('$schema')) { + functionDeclaration.parameters = processJsonSchema(functionDeclaration.parameters); + } + else { + if (!functionDeclaration.parametersJsonSchema) { + functionDeclaration.parametersJsonSchema = + functionDeclaration.parameters; + delete functionDeclaration.parameters; + } + } + } + if (functionDeclaration.response) { + if (!Object.keys(functionDeclaration.response).includes('$schema')) { + functionDeclaration.response = processJsonSchema(functionDeclaration.response); + } + else { + if (!functionDeclaration.responseJsonSchema) { + functionDeclaration.responseJsonSchema = + functionDeclaration.response; + delete functionDeclaration.response; + } + } + } + } + } + return tool; +} +function tTools(tools) { + // Check if the incoming type is defined. + if (tools === undefined || tools === null) { + throw new Error('tools is required'); + } + if (!Array.isArray(tools)) { + throw new Error('tools is required and must be an array of Tools'); + } + const result = []; + for (const tool of tools) { + result.push(tool); + } + return result; +} +/** + * Prepends resource name with project, location, resource_prefix if needed. + * + * @param client The API client. + * @param resourceName The resource name. + * @param resourcePrefix The resource prefix. + * @param splitsAfterPrefix The number of splits after the prefix. + * @returns The completed resource name. + * + * Examples: + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/bar/locations/us-west1/cachedContents/123' + * ``` + * + * ``` + * resource_name = 'projects/foo/locations/us-central1/cachedContents/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/foo/locations/us-central1/cachedContents/123' + * ``` + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns 'cachedContents/123' + * ``` + * + * ``` + * resource_name = 'some/wrong/cachedContents/resource/name/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * # client.vertexai = True + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * -> 'some/wrong/resource/name/123' + * ``` + */ +function resourceName(client, resourceName, resourcePrefix, splitsAfterPrefix = 1) { + const shouldAppendPrefix = !resourceName.startsWith(`${resourcePrefix}/`) && + resourceName.split('/').length === splitsAfterPrefix; + if (client.isVertexAI()) { + if (resourceName.startsWith('projects/')) { + return resourceName; + } + else if (resourceName.startsWith('locations/')) { + return `projects/${client.getProject()}/${resourceName}`; + } + else if (resourceName.startsWith(`${resourcePrefix}/`)) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`; + } + else if (shouldAppendPrefix) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`; + } + else { + return resourceName; + } + } + if (shouldAppendPrefix) { + return `${resourcePrefix}/${resourceName}`; + } + return resourceName; +} +function tCachedContentName(apiClient, name) { + if (typeof name !== 'string') { + throw new Error('name must be a string'); + } + return resourceName(apiClient, name, 'cachedContents'); +} +function tTuningJobStatus(status) { + switch (status) { + case 'STATE_UNSPECIFIED': + return 'JOB_STATE_UNSPECIFIED'; + case 'CREATING': + return 'JOB_STATE_RUNNING'; + case 'ACTIVE': + return 'JOB_STATE_SUCCEEDED'; + case 'FAILED': + return 'JOB_STATE_FAILED'; + default: + return status; + } +} +function tBytes(fromImageBytes) { + return tBytes$1(fromImageBytes); +} +function _isFile(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'name' in origin); +} +function isGeneratedVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'video' in origin); +} +function isVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'uri' in origin); +} +function tFileName(fromName) { + var _a; + let name; + if (_isFile(fromName)) { + name = fromName.name; + } + if (isVideo(fromName)) { + name = fromName.uri; + if (name === undefined) { + return undefined; + } + } + if (isGeneratedVideo(fromName)) { + name = (_a = fromName.video) === null || _a === void 0 ? void 0 : _a.uri; + if (name === undefined) { + return undefined; + } + } + if (typeof fromName === 'string') { + name = fromName; + } + if (name === undefined) { + throw new Error('Could not extract file name from the provided input.'); + } + if (name.startsWith('https://')) { + const suffix = name.split('files/')[1]; + const match = suffix.match(/[a-z0-9]+/); + if (match === null) { + throw new Error(`Could not extract file name from URI ${name}`); + } + name = match[0]; + } + else if (name.startsWith('files/')) { + name = name.split('files/')[1]; + } + return name; +} +function tModelsUrl(apiClient, baseModels) { + let res; + if (apiClient.isVertexAI()) { + res = baseModels ? 'publishers/google/models' : 'models'; + } + else { + res = baseModels ? 'models' : 'tunedModels'; + } + return res; +} +function tExtractModels(response) { + for (const key of ['models', 'tunedModels', 'publisherModels']) { + if (hasField(response, key)) { + return response[key]; + } + } + return []; +} +function hasField(data, fieldName) { + return data !== null && typeof data === 'object' && fieldName in data; +} +function mcpToGeminiTool(mcpTool, config = {}) { + const mcpToolSchema = mcpTool; + const functionDeclaration = { + name: mcpToolSchema['name'], + description: mcpToolSchema['description'], + parametersJsonSchema: mcpToolSchema['inputSchema'], + }; + if (config.behavior) { + functionDeclaration['behavior'] = config.behavior; + } + const geminiTool = { + functionDeclarations: [ + functionDeclaration, + ], + }; + return geminiTool; +} +/** + * Converts a list of MCP tools to a single Gemini tool with a list of function + * declarations. + */ +function mcpToolsToGeminiTool(mcpTools, config = {}) { + const functionDeclarations = []; + const toolNames = new Set(); + for (const mcpTool of mcpTools) { + const mcpToolName = mcpTool.name; + if (toolNames.has(mcpToolName)) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + toolNames.add(mcpToolName); + const geminiTool = mcpToGeminiTool(mcpTool, config); + if (geminiTool.functionDeclarations) { + functionDeclarations.push(...geminiTool.functionDeclarations); + } + } + return { functionDeclarations: functionDeclarations }; +} +// Transforms a source input into a BatchJobSource object with validation. +function tBatchJobSource(apiClient, src) { + if (typeof src !== 'string' && !Array.isArray(src)) { + if (apiClient && apiClient.isVertexAI()) { + if (src.gcsUri && src.bigqueryUri) { + throw new Error('Only one of `gcsUri` or `bigqueryUri` can be set.'); + } + else if (!src.gcsUri && !src.bigqueryUri) { + throw new Error('One of `gcsUri` or `bigqueryUri` must be set.'); + } + } + else { + // Logic for non-Vertex AI client (inlined_requests, file_name) + if (src.inlinedRequests && src.fileName) { + throw new Error('Only one of `inlinedRequests` or `fileName` can be set.'); + } + else if (!src.inlinedRequests && !src.fileName) { + throw new Error('One of `inlinedRequests` or `fileName` must be set.'); + } + } + return src; + } + // If src is an array (list in Python) + else if (Array.isArray(src)) { + return { inlinedRequests: src }; + } + else if (typeof src === 'string') { + if (src.startsWith('gs://')) { + return { + format: 'jsonl', + gcsUri: [src], // GCS URI is expected as an array + }; + } + else if (src.startsWith('bq://')) { + return { + format: 'bigquery', + bigqueryUri: src, + }; + } + else if (src.startsWith('files/')) { + return { + fileName: src, + }; + } + } + throw new Error(`Unsupported source: ${src}`); +} +function tBatchJobDestination(dest) { + if (typeof dest !== 'string') { + return dest; + } + const destString = dest; + if (destString.startsWith('gs://')) { + return { + format: 'jsonl', + gcsUri: destString, + }; + } + else if (destString.startsWith('bq://')) { + return { + format: 'bigquery', + bigqueryUri: destString, + }; + } + else { + throw new Error(`Unsupported destination: ${destString}`); + } +} +function tBatchJobName(apiClient, name) { + const nameString = name; + if (!apiClient.isVertexAI()) { + const mldevPattern = /batches\/[^/]+$/; + if (mldevPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } + } + const vertexPattern = /^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/; + if (vertexPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else if (/^\d+$/.test(nameString)) { + return nameString; + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } +} +function tJobState(state) { + const stateString = state; + if (stateString === 'BATCH_STATE_UNSPECIFIED') { + return 'JOB_STATE_UNSPECIFIED'; + } + else if (stateString === 'BATCH_STATE_PENDING') { + return 'JOB_STATE_PENDING'; + } + else if (stateString === 'BATCH_STATE_SUCCEEDED') { + return 'JOB_STATE_SUCCEEDED'; + } + else if (stateString === 'BATCH_STATE_FAILED') { + return 'JOB_STATE_FAILED'; + } + else if (stateString === 'BATCH_STATE_CANCELLED') { + return 'JOB_STATE_CANCELLED'; + } + else { + return stateString; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$4(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$4(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$4(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$4(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$4(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$4(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$4(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev$1(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$4(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$4(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$4(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$4(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$4(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$4(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$4(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$4() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$4(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$4(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$4(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$4(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$4(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$4()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$4(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev$2(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev$2(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$2(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev$2(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$3(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$3(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$3(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$3(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$3(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev$1(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$4(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToMldev$1(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev$1(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$4(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$2(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToMldev$3(tSpeechConfig(fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev$1(fromThinkingConfig)); + } + return toObject; +} +function inlinedRequestToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['request', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$4(item); + }); + } + setValueByPath(toObject, ['request', 'contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['request', 'generationConfig'], generateContentConfigToMldev$1(apiClient, fromConfig, toObject)); + } + return toObject; +} +function batchJobSourceToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['format']) !== undefined) { + throw new Error('format parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['bigqueryUri']) !== undefined) { + throw new Error('bigqueryUri parameter is not supported in Gemini API.'); + } + const fromFileName = getValueByPath(fromObject, ['fileName']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedRequests = getValueByPath(fromObject, [ + 'inlinedRequests', + ]); + if (fromInlinedRequests != null) { + let transformedList = fromInlinedRequests; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedRequestToMldev(apiClient, item); + }); + } + setValueByPath(toObject, ['requests', 'requests'], transformedList); + } + return toObject; +} +function createBatchJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['batch', 'displayName'], fromDisplayName); + } + if (getValueByPath(fromObject, ['dest']) !== undefined) { + throw new Error('dest parameter is not supported in Gemini API.'); + } + return toObject; +} +function createBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['batch', 'inputConfig'], batchJobSourceToMldev(apiClient, tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createBatchJobConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + if (getValueByPath(fromObject, ['filter']) !== undefined) { + throw new Error('filter parameter is not supported in Gemini API.'); + } + return toObject; +} +function listBatchJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listBatchJobsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function deleteBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function batchJobSourceToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['instancesFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsSource', 'uris'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigquerySource', 'inputUri'], fromBigqueryUri); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['inlinedRequests']) !== undefined) { + throw new Error('inlinedRequests parameter is not supported in Vertex AI.'); + } + return toObject; +} +function batchJobDestinationToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['predictionsFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsDestination', 'outputUriPrefix'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryDestination', 'outputUri'], fromBigqueryUri); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['inlinedResponses']) !== undefined) { + throw new Error('inlinedResponses parameter is not supported in Vertex AI.'); + } + return toObject; +} +function createBatchJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDest = getValueByPath(fromObject, ['dest']); + if (parentObject !== undefined && fromDest != null) { + setValueByPath(parentObject, ['outputConfig'], batchJobDestinationToVertex(tBatchJobDestination(fromDest))); + } + return toObject; +} +function createBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['inputConfig'], batchJobSourceToVertex(tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createBatchJobConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listBatchJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listBatchJobsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function deleteBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev$2(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$2(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$2(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromMldev$1(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev$2(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev$1(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev$2(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev$1(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev$1(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function jobErrorFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + return toObject; +} +function inlinedResponseFromMldev(fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateContentResponseFromMldev$1(fromResponse)); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError)); + } + return toObject; +} +function batchJobDestinationFromMldev(fromObject) { + const toObject = {}; + const fromFileName = getValueByPath(fromObject, ['responsesFile']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedResponses = getValueByPath(fromObject, [ + 'inlinedResponses', + 'inlinedResponses', + ]); + if (fromInlinedResponses != null) { + let transformedList = fromInlinedResponses; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedResponseFromMldev(item); + }); + } + setValueByPath(toObject, ['inlinedResponses'], transformedList); + } + return toObject; +} +function batchJobFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, [ + 'metadata', + 'displayName', + ]); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['metadata', 'state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, [ + 'metadata', + 'createTime', + ]); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'metadata', + 'endTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, [ + 'metadata', + 'updateTime', + ]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['metadata', 'model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromDest = getValueByPath(fromObject, ['metadata', 'output']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromMldev(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, ['operations']); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromMldev(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function deleteResourceJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError)); + } + return toObject; +} +function jobErrorFromVertex(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + return toObject; +} +function batchJobSourceFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['instancesFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsSource', 'uris']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigquerySource', + 'inputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + return toObject; +} +function batchJobDestinationFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['predictionsFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, [ + 'gcsDestination', + 'outputUriPrefix', + ]); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigqueryDestination', + 'outputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + return toObject; +} +function batchJobFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromSrc = getValueByPath(fromObject, ['inputConfig']); + if (fromSrc != null) { + setValueByPath(toObject, ['src'], batchJobSourceFromVertex(fromSrc)); + } + const fromDest = getValueByPath(fromObject, ['outputConfig']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromVertex(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, [ + 'batchPredictionJobs', + ]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromVertex(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function deleteResourceJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +var PagedItem; +(function (PagedItem) { + PagedItem["PAGED_ITEM_BATCH_JOBS"] = "batchJobs"; + PagedItem["PAGED_ITEM_MODELS"] = "models"; + PagedItem["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs"; + PagedItem["PAGED_ITEM_FILES"] = "files"; + PagedItem["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents"; +})(PagedItem || (PagedItem = {})); +/** + * Pager class for iterating through paginated results. + */ +class Pager { + constructor(name, request, response, params) { + this.pageInternal = []; + this.paramsInternal = {}; + this.requestInternal = request; + this.init(name, response, params); + } + init(name, response, params) { + var _a, _b; + this.nameInternal = name; + this.pageInternal = response[this.nameInternal] || []; + this.sdkHttpResponseInternal = response === null || response === void 0 ? void 0 : response.sdkHttpResponse; + this.idxInternal = 0; + let requestParams = { config: {} }; + if (!params || Object.keys(params).length === 0) { + requestParams = { config: {} }; + } + else if (typeof params === 'object') { + requestParams = Object.assign({}, params); + } + else { + requestParams = params; + } + if (requestParams['config']) { + requestParams['config']['pageToken'] = response['nextPageToken']; + } + this.paramsInternal = requestParams; + this.pageInternalSize = + (_b = (_a = requestParams['config']) === null || _a === void 0 ? void 0 : _a['pageSize']) !== null && _b !== void 0 ? _b : this.pageInternal.length; + } + initNextPage(response) { + this.init(this.nameInternal, response, this.paramsInternal); + } + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page() { + return this.pageInternal; + } + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name() { + return this.nameInternal; + } + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize() { + return this.pageInternalSize; + } + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse() { + return this.sdkHttpResponseInternal; + } + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params() { + return this.paramsInternal; + } + /** + * Returns the total number of items in the current page. + */ + get pageLength() { + return this.pageInternal.length; + } + /** + * Returns the item at the given index. + */ + getItem(index) { + return this.pageInternal[index]; + } + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator]() { + return { + next: async () => { + if (this.idxInternal >= this.pageLength) { + if (this.hasNextPage()) { + await this.nextPage(); + } + else { + return { value: undefined, done: true }; + } + } + const item = this.getItem(this.idxInternal); + this.idxInternal += 1; + return { value: item, done: false }; + }, + return: async () => { + return { value: undefined, done: true }; + }, + }; + } + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + async nextPage() { + if (!this.hasNextPage()) { + throw new Error('No more pages to fetch.'); + } + const response = await this.requestInternal(this.params); + this.initNextPage(response); + return this.page; + } + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage() { + var _a; + if (((_a = this.params['config']) === null || _a === void 0 ? void 0 : _a['pageToken']) !== undefined) { + return true; + } + return false; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Batches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + this.create = async (params) => { + var _a, _b; + if (this.apiClient.isVertexAI()) { + const timestamp = Date.now(); + const timestampStr = timestamp.toString(); + if (Array.isArray(params.src)) { + throw new Error('InlinedRequest[] is not supported in Vertex AI. Please use ' + + 'Google Cloud Storage URI or BigQuery URI instead.'); + } + params.config = params.config || {}; + if (params.config.displayName === undefined) { + params.config.displayName = 'genaiBatchJob_${timestampStr}'; + } + if (params.config.dest === undefined && typeof params.src === 'string') { + if (params.src.startsWith('gs://') && params.src.endsWith('.jsonl')) { + params.config.dest = `${params.src.slice(0, -6)}/dest`; + } + else if (params.src.startsWith('bq://')) { + params.config.dest = + `${params.src}_dest_${timestampStr}`; + } + else { + throw new Error('Unsupported source:' + params.src); + } + } + } + else { + if (Array.isArray(params.src) || + (typeof params.src !== 'string' && params.src.inlinedRequests)) { + // Move system instruction to httpOptions extraBody. + let path = ''; + let queryParams = {}; + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchGenerateContent', body['_url']); + queryParams = body['_query']; + // Move system instruction to 'request': + // {'systemInstruction': system_instruction} + const batch = body['batch']; + const inputConfig = batch['inputConfig']; + const requestsWrapper = inputConfig['requests']; + const requests = requestsWrapper['requests']; + const newRequests = []; + for (const request of requests) { + const requestDict = request; + if (requestDict['systemInstruction']) { + const systemInstructionValue = requestDict['systemInstruction']; + delete requestDict['systemInstruction']; + const requestContent = requestDict['request']; + requestContent['systemInstruction'] = systemInstructionValue; + requestDict['request'] = requestContent; + } + newRequests.push(requestDict); + } + requestsWrapper['requests'] = newRequests; + delete body['config']; + delete body['_url']; + delete body['_query']; + const response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + return await this.createInternal(params); + }; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_BATCH_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + async createInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchGenerateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + else { + const body = cancelBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listBatchJobsParametersToVertex(params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromVertex(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listBatchJobsParametersToMldev(params); + path = formatMap('batches', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromMldev(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = deleteBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$3(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$3(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$3(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$3(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$3(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$3(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$3(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$3(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$3(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$3(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$3(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$3(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$3(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$3(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$3() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$3(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$3(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$3(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$3(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$3(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$3()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$3(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$1(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev$1(fromRetrievalConfig)); + } + return toObject; +} +function createCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$3(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$3(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$3(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$1(fromToolConfig)); + } + if (getValueByPath(fromObject, ['kmsKeyName']) !== undefined) { + throw new Error('kmsKeyName parameter is not supported in Gemini API.'); + } + return toObject; +} +function createCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createCachedContentConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataToVertex$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex$2(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$2(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex$2(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex$2(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$2(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex$2(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex$2(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$2(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$2(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$2(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex$2(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex$2(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex$2()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex$2(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToVertex$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToVertex$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex$1(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToVertex$1(fromRetrievalConfig)); + } + return toObject; +} +function createCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex$2(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$2(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex$1(fromToolConfig)); + } + const fromKmsKeyName = getValueByPath(fromObject, ['kmsKeyName']); + if (parentObject !== undefined && fromKmsKeyName != null) { + setValueByPath(parentObject, ['encryption_spec', 'kmsKeyName'], fromKmsKeyName); + } + return toObject; +} +function createCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createCachedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function cachedContentFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromMldev() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromMldev(item); + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} +function cachedContentFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromVertex() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromVertex(item); + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Caches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_CACHED_CONTENTS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + async create(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = createCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromVertex(); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromMldev(); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = updateCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listCachedContentsParametersToVertex(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromVertex(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listCachedContentsParametersToMldev(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromMldev(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns true if the response is valid, false otherwise. + */ +function isValidResponse(response) { + var _a; + if (response.candidates == undefined || response.candidates.length === 0) { + return false; + } + const content = (_a = response.candidates[0]) === null || _a === void 0 ? void 0 : _a.content; + if (content === undefined) { + return false; + } + return isValidContent(content); +} +function isValidContent(content) { + if (content.parts === undefined || content.parts.length === 0) { + return false; + } + for (const part of content.parts) { + if (part === undefined || Object.keys(part).length === 0) { + return false; + } + } + return true; +} +/** + * Validates the history contains the correct roles. + * + * @throws Error if the history does not start with a user turn. + * @throws Error if the history contains an invalid role. + */ +function validateHistory(history) { + // Empty history is valid. + if (history.length === 0) { + return; + } + for (const content of history) { + if (content.role !== 'user' && content.role !== 'model') { + throw new Error(`Role must be user or model, but got ${content.role}.`); + } + } +} +/** + * Extracts the curated (valid) history from a comprehensive history. + * + * @remarks + * The model may sometimes generate invalid or empty contents(e.g., due to safty + * filters or recitation). Extracting valid turns from the history + * ensures that subsequent requests could be accpeted by the model. + */ +function extractCuratedHistory(comprehensiveHistory) { + if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) { + return []; + } + const curatedHistory = []; + const length = comprehensiveHistory.length; + let i = 0; + while (i < length) { + if (comprehensiveHistory[i].role === 'user') { + curatedHistory.push(comprehensiveHistory[i]); + i++; + } + else { + const modelOutput = []; + let isValid = true; + while (i < length && comprehensiveHistory[i].role === 'model') { + modelOutput.push(comprehensiveHistory[i]); + if (isValid && !isValidContent(comprehensiveHistory[i])) { + isValid = false; + } + i++; + } + if (isValid) { + curatedHistory.push(...modelOutput); + } + else { + // Remove the last user input when model content is invalid. + curatedHistory.pop(); + } + } + } + return curatedHistory; +} +/** + * A utility class to create a chat session. + */ +class Chats { + constructor(modelsModule, apiClient) { + this.modelsModule = modelsModule; + this.apiClient = apiClient; + } + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params) { + return new Chat(this.apiClient, this.modelsModule, params.model, params.config, + // Deep copy the history to avoid mutating the history outside of the + // chat session. + structuredClone(params.history)); + } +} +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +class Chat { + constructor(apiClient, modelsModule, model, config = {}, history = []) { + this.apiClient = apiClient; + this.modelsModule = modelsModule; + this.model = model; + this.config = config; + this.history = history; + // A promise to represent the current state of the message being sent to the + // model. + this.sendPromise = Promise.resolve(); + validateHistory(history); + } + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + async sendMessage(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const responsePromise = this.modelsModule.generateContent({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + this.sendPromise = (async () => { + var _a, _b, _c; + const response = await responsePromise; + const outputContent = (_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content; + // Because the AFC input contains the entire curated chat history in + // addition to the new user input, we need to truncate the AFC history + // to deduplicate the existing chat history. + const fullAutomaticFunctionCallingHistory = response.automaticFunctionCallingHistory; + const index = this.getHistory(true).length; + let automaticFunctionCallingHistory = []; + if (fullAutomaticFunctionCallingHistory != null) { + automaticFunctionCallingHistory = + (_c = fullAutomaticFunctionCallingHistory.slice(index)) !== null && _c !== void 0 ? _c : []; + } + const modelOutput = outputContent ? [outputContent] : []; + this.recordHistory(inputContent, modelOutput, automaticFunctionCallingHistory); + return; + })(); + await this.sendPromise.catch(() => { + // Resets sendPromise to avoid subsequent calls failing + this.sendPromise = Promise.resolve(); + }); + return responsePromise; + } + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + async sendMessageStream(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const streamResponse = this.modelsModule.generateContentStream({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + // Resolve the internal tracking of send completion promise - `sendPromise` + // for both success and failure response. The actual failure is still + // propagated by the `await streamResponse`. + this.sendPromise = streamResponse + .then(() => undefined) + .catch(() => undefined); + const response = await streamResponse; + const result = this.processStreamResponse(response, inputContent); + return result; + } + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated = false) { + const history = curated + ? extractCuratedHistory(this.history) + : this.history; + // Deep copy the history to avoid mutating the history outside of the + // chat session. + return structuredClone(history); + } + processStreamResponse(streamResponse, inputContent) { + var _a, _b; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + var _c, e_1, _d, _e; + const outputContent = []; + try { + for (var _f = true, streamResponse_1 = __asyncValues(streamResponse), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()), _c = streamResponse_1_1.done, !_c; _f = true) { + _e = streamResponse_1_1.value; + _f = false; + const chunk = _e; + if (isValidResponse(chunk)) { + const content = (_b = (_a = chunk.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content; + if (content !== undefined) { + outputContent.push(content); + } + } + yield yield __await(chunk); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_c && (_d = streamResponse_1.return)) yield __await(_d.call(streamResponse_1)); + } + finally { if (e_1) throw e_1.error; } + } + this.recordHistory(inputContent, outputContent); + }); + } + recordHistory(userInput, modelOutput, automaticFunctionCallingHistory) { + let outputContents = []; + if (modelOutput.length > 0 && + modelOutput.every((content) => content.role !== undefined)) { + outputContents = modelOutput; + } + else { + // Appends an empty content when model returns empty response, so that the + // history is always alternating between user and model. + outputContents.push({ + role: 'model', + parts: [], + }); + } + if (automaticFunctionCallingHistory && + automaticFunctionCallingHistory.length > 0) { + this.history.push(...extractCuratedHistory(automaticFunctionCallingHistory)); + } + else { + this.history.push(userInput); + } + this.history.push(...outputContents); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * API errors raised by the GenAI API. + */ +class ApiError extends Error { + constructor(options) { + super(options.message); + this.name = 'ApiError'; + this.status = options.status; + Object.setPrototypeOf(this, ApiError.prototype); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function listFilesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listFilesParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listFilesConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function fileStatusToMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusToMldev(fromError)); + } + return toObject; +} +function createFileParametersToMldev(fromObject) { + const toObject = {}; + const fromFile = getValueByPath(fromObject, ['file']); + if (fromFile != null) { + setValueByPath(toObject, ['file'], fileToMldev(fromFile)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fileStatusFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusFromMldev(fromError)); + } + return toObject; +} +function listFilesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromFiles = getValueByPath(fromObject, ['files']); + if (fromFiles != null) { + let transformedList = fromFiles; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return fileFromMldev(item); + }); + } + setValueByPath(toObject, ['files'], transformedList); + } + return toObject; +} +function createFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function deleteFileResponseFromMldev() { + const toObject = {}; + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Files extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_FILES, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + async upload(params) { + if (this.apiClient.isVertexAI()) { + throw new Error('Vertex AI does not support uploading files. You can share files through a GCS bucket.'); + } + return this.apiClient + .uploadFile(params.file, params.config) + .then((response) => { + const file = fileFromMldev(response); + return file; + }); + } + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + async download(params) { + await this.apiClient.downloadFile(params); + } + async listInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = listFilesParametersToMldev(params); + path = formatMap('files', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listFilesResponseFromMldev(apiResponse); + const typedResp = new ListFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async createInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createFileParametersToMldev(params); + path = formatMap('upload/v1beta/files', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = createFileResponseFromMldev(apiResponse); + const typedResp = new CreateFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + async get(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = getFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = fileFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + async delete(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = deleteFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteFileResponseFromMldev(); + const typedResp = new DeleteFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$2(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$2(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$2(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$2(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$2(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$2(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$2(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$2(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$2(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$2(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$2(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$2(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$2()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$2(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is not supported in Gemini API.'); + } + return toObject; +} +function audioTranscriptionConfigToMldev$1() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev$1(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev$1(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToMldev$1(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev$1(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToMldev$1(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToMldev$1(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev$1(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToMldev$2(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$2(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev$1(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToMldev$1()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToMldev$1()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToMldev$1(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToMldev$1(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToMldev$1(fromProactivity)); + } + return toObject; +} +function liveConnectParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev$1(fromConfig, toObject)); + } + return toObject; +} +function activityStartToMldev() { + const toObject = {}; + return toObject; +} +function activityEndToMldev() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToMldev(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + setValueByPath(toObject, ['mediaChunks'], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], activityStartToMldev()); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], activityEndToMldev()); + } + return toObject; +} +function weightedPromptToMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromWeight = getValueByPath(fromObject, ['weight']); + if (fromWeight != null) { + setValueByPath(toObject, ['weight'], fromWeight); + } + return toObject; +} +function liveMusicSetWeightedPromptsParametersToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigToMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ['guidance']); + if (fromGuidance != null) { + setValueByPath(toObject, ['guidance'], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ['bpm']); + if (fromBpm != null) { + setValueByPath(toObject, ['bpm'], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ['density']); + if (fromDensity != null) { + setValueByPath(toObject, ['density'], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ['brightness']); + if (fromBrightness != null) { + setValueByPath(toObject, ['brightness'], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ['scale']); + if (fromScale != null) { + setValueByPath(toObject, ['scale'], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ['muteBass']); + if (fromMuteBass != null) { + setValueByPath(toObject, ['muteBass'], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ['muteDrums']); + if (fromMuteDrums != null) { + setValueByPath(toObject, ['muteDrums'], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, [ + 'onlyBassAndDrums', + ]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums); + } + const fromMusicGenerationMode = getValueByPath(fromObject, [ + 'musicGenerationMode', + ]); + if (fromMusicGenerationMode != null) { + setValueByPath(toObject, ['musicGenerationMode'], fromMusicGenerationMode); + } + return toObject; +} +function liveMusicSetConfigParametersToMldev(fromObject) { + const toObject = {}; + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig)); + } + return toObject; +} +function liveMusicClientSetupToMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + return toObject; +} +function liveMusicClientContentToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicClientMessageToMldev(fromObject) { + const toObject = {}; + const fromSetup = getValueByPath(fromObject, ['setup']); + if (fromSetup != null) { + setValueByPath(toObject, ['setup'], liveMusicClientSetupToMldev(fromSetup)); + } + const fromClientContent = getValueByPath(fromObject, [ + 'clientContent', + ]); + if (fromClientContent != null) { + setValueByPath(toObject, ['clientContent'], liveMusicClientContentToMldev(fromClientContent)); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig)); + } + const fromPlaybackControl = getValueByPath(fromObject, [ + 'playbackControl', + ]); + if (fromPlaybackControl != null) { + setValueByPath(toObject, ['playbackControl'], fromPlaybackControl); + } + return toObject; +} +function prebuiltVoiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex$1(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex$1(fromVoiceConfig)); + } + if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) { + throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.'); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex$1(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$1(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex$1(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex$1(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$1(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex$1(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex$1(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$1(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$1(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$1(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex$1(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex$1(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex$1()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex$1(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToVertex(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + const fromTransparent = getValueByPath(fromObject, ['transparent']); + if (fromTransparent != null) { + setValueByPath(toObject, ['transparent'], fromTransparent); + } + return toObject; +} +function audioTranscriptionConfigToVertex() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToVertex(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToVertex(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToVertex(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToVertex(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToVertex(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToVertex(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToVertex(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToVertex$1(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToVertex(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToVertex()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToVertex()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToVertex(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToVertex(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToVertex(fromProactivity)); + } + return toObject; +} +function liveConnectParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function activityStartToVertex() { + const toObject = {}; + return toObject; +} +function activityEndToVertex() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToVertex(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + setValueByPath(toObject, ['mediaChunks'], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], activityStartToVertex()); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], activityEndToVertex()); + } + return toObject; +} +function liveServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function videoMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev$1(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$1(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function transcriptionFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFinished = getValueByPath(fromObject, ['finished']); + if (fromFinished != null) { + setValueByPath(toObject, ['finished'], fromFinished); + } + return toObject; +} +function urlMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$1(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function liveServerContentFromMldev(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn != null) { + setValueByPath(toObject, ['modelTurn'], contentFromMldev$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete != null) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted != null) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + 'generationComplete', + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ['generationComplete'], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + 'inputTranscription', + ]); + if (fromInputTranscription != null) { + setValueByPath(toObject, ['inputTranscription'], transcriptionFromMldev(fromInputTranscription)); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + 'outputTranscription', + ]); + if (fromOutputTranscription != null) { + setValueByPath(toObject, ['outputTranscription'], transcriptionFromMldev(fromOutputTranscription)); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev$1(fromUrlContextMetadata)); + } + return toObject; +} +function functionCallFromMldev(fromObject) { + const toObject = {}; + const fromId = getValueByPath(fromObject, ['id']); + if (fromId != null) { + setValueByPath(toObject, ['id'], fromId); + } + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromMldev(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromMldev(item); + }); + } + setValueByPath(toObject, ['functionCalls'], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromMldev(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds != null) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function modalityTokenCountFromMldev(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ['modality']); + if (fromModality != null) { + setValueByPath(toObject, ['modality'], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function usageMetadataFromMldev(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, [ + 'promptTokenCount', + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + 'responseTokenCount', + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ['responseTokenCount'], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + 'toolUsePromptTokenCount', + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ['toolUsePromptTokenCount'], fromToolUsePromptTokenCount); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + 'thoughtsTokenCount', + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ['thoughtsTokenCount'], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, [ + 'totalTokenCount', + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + 'promptTokensDetails', + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['promptTokensDetails'], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + 'cacheTokensDetails', + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['cacheTokensDetails'], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + 'responseTokensDetails', + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['responseTokensDetails'], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + 'toolUsePromptTokensDetails', + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['toolUsePromptTokensDetails'], transformedList); + } + return toObject; +} +function liveServerGoAwayFromMldev(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ['timeLeft']); + if (fromTimeLeft != null) { + setValueByPath(toObject, ['timeLeft'], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromMldev(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ['newHandle']); + if (fromNewHandle != null) { + setValueByPath(toObject, ['newHandle'], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ['resumable']); + if (fromResumable != null) { + setValueByPath(toObject, ['resumable'], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + 'lastConsumedClientMessageIndex', + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath(toObject, ['lastConsumedClientMessageIndex'], fromLastConsumedClientMessageIndex); + } + return toObject; +} +function liveServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveServerSetupCompleteFromMldev()); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromMldev(fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromMldev(fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromMldev(fromToolCallCancellation)); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], usageMetadataFromMldev(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject, ['goAway']); + if (fromGoAway != null) { + setValueByPath(toObject, ['goAway'], liveServerGoAwayFromMldev(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + 'sessionResumptionUpdate', + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ['sessionResumptionUpdate'], liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate)); + } + return toObject; +} +function liveMusicServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function weightedPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromWeight = getValueByPath(fromObject, ['weight']); + if (fromWeight != null) { + setValueByPath(toObject, ['weight'], fromWeight); + } + return toObject; +} +function liveMusicClientContentFromMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptFromMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigFromMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ['guidance']); + if (fromGuidance != null) { + setValueByPath(toObject, ['guidance'], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ['bpm']); + if (fromBpm != null) { + setValueByPath(toObject, ['bpm'], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ['density']); + if (fromDensity != null) { + setValueByPath(toObject, ['density'], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ['brightness']); + if (fromBrightness != null) { + setValueByPath(toObject, ['brightness'], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ['scale']); + if (fromScale != null) { + setValueByPath(toObject, ['scale'], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ['muteBass']); + if (fromMuteBass != null) { + setValueByPath(toObject, ['muteBass'], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ['muteDrums']); + if (fromMuteDrums != null) { + setValueByPath(toObject, ['muteDrums'], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, [ + 'onlyBassAndDrums', + ]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums); + } + const fromMusicGenerationMode = getValueByPath(fromObject, [ + 'musicGenerationMode', + ]); + if (fromMusicGenerationMode != null) { + setValueByPath(toObject, ['musicGenerationMode'], fromMusicGenerationMode); + } + return toObject; +} +function liveMusicSourceMetadataFromMldev(fromObject) { + const toObject = {}; + const fromClientContent = getValueByPath(fromObject, [ + 'clientContent', + ]); + if (fromClientContent != null) { + setValueByPath(toObject, ['clientContent'], liveMusicClientContentFromMldev(fromClientContent)); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig)); + } + return toObject; +} +function audioChunkFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSourceMetadata = getValueByPath(fromObject, [ + 'sourceMetadata', + ]); + if (fromSourceMetadata != null) { + setValueByPath(toObject, ['sourceMetadata'], liveMusicSourceMetadataFromMldev(fromSourceMetadata)); + } + return toObject; +} +function liveMusicServerContentFromMldev(fromObject) { + const toObject = {}; + const fromAudioChunks = getValueByPath(fromObject, ['audioChunks']); + if (fromAudioChunks != null) { + let transformedList = fromAudioChunks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return audioChunkFromMldev(item); + }); + } + setValueByPath(toObject, ['audioChunks'], transformedList); + } + return toObject; +} +function liveMusicFilteredPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFilteredReason = getValueByPath(fromObject, [ + 'filteredReason', + ]); + if (fromFilteredReason != null) { + setValueByPath(toObject, ['filteredReason'], fromFilteredReason); + } + return toObject; +} +function liveMusicServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveMusicServerSetupCompleteFromMldev()); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveMusicServerContentFromMldev(fromServerContent)); + } + const fromFilteredPrompt = getValueByPath(fromObject, [ + 'filteredPrompt', + ]); + if (fromFilteredPrompt != null) { + setValueByPath(toObject, ['filteredPrompt'], liveMusicFilteredPromptFromMldev(fromFilteredPrompt)); + } + return toObject; +} +function liveServerSetupCompleteFromVertex(fromObject) { + const toObject = {}; + const fromSessionId = getValueByPath(fromObject, ['sessionId']); + if (fromSessionId != null) { + setValueByPath(toObject, ['sessionId'], fromSessionId); + } + return toObject; +} +function videoMetadataFromVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromVertex$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function transcriptionFromVertex(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFinished = getValueByPath(fromObject, ['finished']); + if (fromFinished != null) { + setValueByPath(toObject, ['finished'], fromFinished); + } + return toObject; +} +function liveServerContentFromVertex(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn != null) { + setValueByPath(toObject, ['modelTurn'], contentFromVertex$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete != null) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted != null) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + 'generationComplete', + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ['generationComplete'], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + 'inputTranscription', + ]); + if (fromInputTranscription != null) { + setValueByPath(toObject, ['inputTranscription'], transcriptionFromVertex(fromInputTranscription)); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + 'outputTranscription', + ]); + if (fromOutputTranscription != null) { + setValueByPath(toObject, ['outputTranscription'], transcriptionFromVertex(fromOutputTranscription)); + } + return toObject; +} +function functionCallFromVertex(fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromVertex(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromVertex(item); + }); + } + setValueByPath(toObject, ['functionCalls'], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromVertex(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds != null) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function modalityTokenCountFromVertex(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ['modality']); + if (fromModality != null) { + setValueByPath(toObject, ['modality'], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function usageMetadataFromVertex(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, [ + 'promptTokenCount', + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + 'candidatesTokenCount', + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ['responseTokenCount'], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + 'toolUsePromptTokenCount', + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ['toolUsePromptTokenCount'], fromToolUsePromptTokenCount); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + 'thoughtsTokenCount', + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ['thoughtsTokenCount'], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, [ + 'totalTokenCount', + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + 'promptTokensDetails', + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['promptTokensDetails'], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + 'cacheTokensDetails', + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['cacheTokensDetails'], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + 'candidatesTokensDetails', + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['responseTokensDetails'], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + 'toolUsePromptTokensDetails', + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['toolUsePromptTokensDetails'], transformedList); + } + const fromTrafficType = getValueByPath(fromObject, ['trafficType']); + if (fromTrafficType != null) { + setValueByPath(toObject, ['trafficType'], fromTrafficType); + } + return toObject; +} +function liveServerGoAwayFromVertex(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ['timeLeft']); + if (fromTimeLeft != null) { + setValueByPath(toObject, ['timeLeft'], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromVertex(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ['newHandle']); + if (fromNewHandle != null) { + setValueByPath(toObject, ['newHandle'], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ['resumable']); + if (fromResumable != null) { + setValueByPath(toObject, ['resumable'], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + 'lastConsumedClientMessageIndex', + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath(toObject, ['lastConsumedClientMessageIndex'], fromLastConsumedClientMessageIndex); + } + return toObject; +} +function liveServerMessageFromVertex(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveServerSetupCompleteFromVertex(fromSetupComplete)); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromVertex(fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromVertex(fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromVertex(fromToolCallCancellation)); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], usageMetadataFromVertex(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject, ['goAway']); + if (fromGoAway != null) { + setValueByPath(toObject, ['goAway'], liveServerGoAwayFromVertex(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + 'sessionResumptionUpdate', + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ['sessionResumptionUpdate'], liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$1(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$1(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$1(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$1(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$1(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$1(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$1(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$1()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$1(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$1(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$1(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$1(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$1(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$1(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$1(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToMldev(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToMldev$1(tSpeechConfig(fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev(fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['requests[]', 'taskType'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['requests[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['requests[]', 'outputDimensionality'], fromOutputDimensionality); + } + if (getValueByPath(fromObject, ['mimeType']) !== undefined) { + throw new Error('mimeType parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['autoTruncate']) !== undefined) { + throw new Error('autoTruncate parameter is not supported in Gemini API.'); + } + return toObject; +} +function embedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + setValueByPath(toObject, ['requests[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToMldev(fromConfig, toObject)); + } + const fromModelForEmbedContent = getValueByPath(fromObject, ['model']); + if (fromModelForEmbedContent !== undefined) { + setValueByPath(toObject, ['requests[]', 'model'], tModel(apiClient, fromModelForEmbedContent)); + } + return toObject; +} +function generateImagesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['negativePrompt']) !== undefined) { + throw new Error('negativePrompt parameter is not supported in Gemini API.'); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + if (getValueByPath(fromObject, ['addWatermark']) !== undefined) { + throw new Error('addWatermark parameter is not supported in Gemini API.'); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath(parentObject, ['parameters', 'sampleImageSize'], fromImageSize); + } + if (getValueByPath(fromObject, ['enhancePrompt']) !== undefined) { + throw new Error('enhancePrompt parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateImagesParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateImagesConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listModelsConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listModelsConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function updateModelConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateModelConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function deleteModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function countTokensConfigToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['systemInstruction']) !== undefined) { + throw new Error('systemInstruction parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['tools']) !== undefined) { + throw new Error('tools parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['generationConfig']) !== undefined) { + throw new Error('generationConfig parameter is not supported in Gemini API.'); + } + return toObject; +} +function countTokensParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToMldev(fromConfig)); + } + return toObject; +} +function imageToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['fps']) !== undefined) { + throw new Error('fps parameter is not supported in Gemini API.'); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + if (getValueByPath(fromObject, ['resolution']) !== undefined) { + throw new Error('resolution parameter is not supported in Gemini API.'); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + if (getValueByPath(fromObject, ['pubsubTopic']) !== undefined) { + throw new Error('pubsubTopic parameter is not supported in Gemini API.'); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + if (getValueByPath(fromObject, ['generateAudio']) !== undefined) { + throw new Error('generateAudio parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['lastFrame']) !== undefined) { + throw new Error('lastFrame parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['referenceImages']) !== undefined) { + throw new Error('referenceImages parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['compressionQuality']) !== undefined) { + throw new Error('compressionQuality parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateVideosParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToMldev(fromImage)); + } + if (getValueByPath(fromObject, ['video']) !== undefined) { + throw new Error('video parameter is not supported in Gemini API.'); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataToVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToVertex(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function modelSelectionConfigToVertex(fromObject) { + const toObject = {}; + const fromFeatureSelectionPreference = getValueByPath(fromObject, [ + 'featureSelectionPreference', + ]); + if (fromFeatureSelectionPreference != null) { + setValueByPath(toObject, ['featureSelectionPreference'], fromFeatureSelectionPreference); + } + return toObject; +} +function safetySettingToVertex(fromObject) { + const toObject = {}; + const fromMethod = getValueByPath(fromObject, ['method']); + if (fromMethod != null) { + setValueByPath(toObject, ['method'], fromMethod); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToVertex(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToVertex(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToVertex(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex(fromVoiceConfig)); + } + if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) { + throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.'); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToVertex(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToVertex(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + const fromRoutingConfig = getValueByPath(fromObject, [ + 'routingConfig', + ]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ['routingConfig'], fromRoutingConfig); + } + const fromModelSelectionConfig = getValueByPath(fromObject, [ + 'modelSelectionConfig', + ]); + if (fromModelSelectionConfig != null) { + setValueByPath(toObject, ['modelConfig'], modelSelectionConfigToVertex(fromModelSelectionConfig)); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToVertex(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex(fromToolConfig)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ['labels'], fromLabels); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToVertex(tSpeechConfig(fromSpeechConfig))); + } + const fromAudioTimestamp = getValueByPath(fromObject, [ + 'audioTimestamp', + ]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToVertex(fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['instances[]', 'task_type'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['instances[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['parameters', 'outputDimensionality'], fromOutputDimensionality); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (parentObject !== undefined && fromMimeType != null) { + setValueByPath(parentObject, ['instances[]', 'mimeType'], fromMimeType); + } + const fromAutoTruncate = getValueByPath(fromObject, ['autoTruncate']); + if (parentObject !== undefined && fromAutoTruncate != null) { + setValueByPath(parentObject, ['parameters', 'autoTruncate'], fromAutoTruncate); + } + return toObject; +} +function embedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + setValueByPath(toObject, ['instances[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function generateImagesConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath(parentObject, ['parameters', 'sampleImageSize'], fromImageSize); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function generateImagesParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateImagesConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function imageToVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function maskReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromMaskMode = getValueByPath(fromObject, ['maskMode']); + if (fromMaskMode != null) { + setValueByPath(toObject, ['maskMode'], fromMaskMode); + } + const fromSegmentationClasses = getValueByPath(fromObject, [ + 'segmentationClasses', + ]); + if (fromSegmentationClasses != null) { + setValueByPath(toObject, ['maskClasses'], fromSegmentationClasses); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (fromMaskDilation != null) { + setValueByPath(toObject, ['dilation'], fromMaskDilation); + } + return toObject; +} +function controlReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromControlType = getValueByPath(fromObject, ['controlType']); + if (fromControlType != null) { + setValueByPath(toObject, ['controlType'], fromControlType); + } + const fromEnableControlImageComputation = getValueByPath(fromObject, [ + 'enableControlImageComputation', + ]); + if (fromEnableControlImageComputation != null) { + setValueByPath(toObject, ['computeControl'], fromEnableControlImageComputation); + } + return toObject; +} +function styleReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromStyleDescription = getValueByPath(fromObject, [ + 'styleDescription', + ]); + if (fromStyleDescription != null) { + setValueByPath(toObject, ['styleDescription'], fromStyleDescription); + } + return toObject; +} +function subjectReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromSubjectType = getValueByPath(fromObject, ['subjectType']); + if (fromSubjectType != null) { + setValueByPath(toObject, ['subjectType'], fromSubjectType); + } + const fromSubjectDescription = getValueByPath(fromObject, [ + 'subjectDescription', + ]); + if (fromSubjectDescription != null) { + setValueByPath(toObject, ['subjectDescription'], fromSubjectDescription); + } + return toObject; +} +function referenceImageAPIInternalToVertex(fromObject) { + const toObject = {}; + const fromReferenceImage = getValueByPath(fromObject, [ + 'referenceImage', + ]); + if (fromReferenceImage != null) { + setValueByPath(toObject, ['referenceImage'], imageToVertex(fromReferenceImage)); + } + const fromReferenceId = getValueByPath(fromObject, ['referenceId']); + if (fromReferenceId != null) { + setValueByPath(toObject, ['referenceId'], fromReferenceId); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + const fromMaskImageConfig = getValueByPath(fromObject, [ + 'maskImageConfig', + ]); + if (fromMaskImageConfig != null) { + setValueByPath(toObject, ['maskImageConfig'], maskReferenceConfigToVertex(fromMaskImageConfig)); + } + const fromControlImageConfig = getValueByPath(fromObject, [ + 'controlImageConfig', + ]); + if (fromControlImageConfig != null) { + setValueByPath(toObject, ['controlImageConfig'], controlReferenceConfigToVertex(fromControlImageConfig)); + } + const fromStyleImageConfig = getValueByPath(fromObject, [ + 'styleImageConfig', + ]); + if (fromStyleImageConfig != null) { + setValueByPath(toObject, ['styleImageConfig'], styleReferenceConfigToVertex(fromStyleImageConfig)); + } + const fromSubjectImageConfig = getValueByPath(fromObject, [ + 'subjectImageConfig', + ]); + if (fromSubjectImageConfig != null) { + setValueByPath(toObject, ['subjectImageConfig'], subjectReferenceConfigToVertex(fromSubjectImageConfig)); + } + return toObject; +} +function editImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromEditMode = getValueByPath(fromObject, ['editMode']); + if (parentObject !== undefined && fromEditMode != null) { + setValueByPath(parentObject, ['parameters', 'editMode'], fromEditMode); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'editConfig', 'baseSteps'], fromBaseSteps); + } + return toObject; +} +function editImageParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return referenceImageAPIInternalToVertex(item); + }); + } + setValueByPath(toObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], editImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function upscaleImageAPIConfigInternalToVertex(fromObject, parentObject) { + const toObject = {}; + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhanceInputImage = getValueByPath(fromObject, [ + 'enhanceInputImage', + ]); + if (parentObject !== undefined && fromEnhanceInputImage != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'enhanceInputImage'], fromEnhanceInputImage); + } + const fromImagePreservationFactor = getValueByPath(fromObject, [ + 'imagePreservationFactor', + ]); + if (parentObject !== undefined && fromImagePreservationFactor != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'imagePreservationFactor'], fromImagePreservationFactor); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + return toObject; +} +function upscaleImageAPIParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromUpscaleFactor = getValueByPath(fromObject, [ + 'upscaleFactor', + ]); + if (fromUpscaleFactor != null) { + setValueByPath(toObject, ['parameters', 'upscaleConfig', 'upscaleFactor'], fromUpscaleFactor); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], upscaleImageAPIConfigInternalToVertex(fromConfig, toObject)); + } + return toObject; +} +function productImageToVertex(fromObject) { + const toObject = {}; + const fromProductImage = getValueByPath(fromObject, ['productImage']); + if (fromProductImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromProductImage)); + } + return toObject; +} +function recontextImageSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromPersonImage = getValueByPath(fromObject, ['personImage']); + if (parentObject !== undefined && fromPersonImage != null) { + setValueByPath(parentObject, ['instances[0]', 'personImage', 'image'], imageToVertex(fromPersonImage)); + } + const fromProductImages = getValueByPath(fromObject, [ + 'productImages', + ]); + if (parentObject !== undefined && fromProductImages != null) { + let transformedList = fromProductImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return productImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'productImages'], transformedList); + } + return toObject; +} +function recontextImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'editConfig', 'baseSteps'], fromBaseSteps); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function recontextImageParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], recontextImageSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], recontextImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function scribbleImageToVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + return toObject; +} +function segmentImageSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromScribbleImage = getValueByPath(fromObject, [ + 'scribbleImage', + ]); + if (parentObject !== undefined && fromScribbleImage != null) { + setValueByPath(parentObject, ['instances[0]', 'scribble'], scribbleImageToVertex(fromScribbleImage)); + } + return toObject; +} +function segmentImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + const fromMaxPredictions = getValueByPath(fromObject, [ + 'maxPredictions', + ]); + if (parentObject !== undefined && fromMaxPredictions != null) { + setValueByPath(parentObject, ['parameters', 'maxPredictions'], fromMaxPredictions); + } + const fromConfidenceThreshold = getValueByPath(fromObject, [ + 'confidenceThreshold', + ]); + if (parentObject !== undefined && fromConfidenceThreshold != null) { + setValueByPath(parentObject, ['parameters', 'confidenceThreshold'], fromConfidenceThreshold); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (parentObject !== undefined && fromMaskDilation != null) { + setValueByPath(parentObject, ['parameters', 'maskDilation'], fromMaskDilation); + } + const fromBinaryColorThreshold = getValueByPath(fromObject, [ + 'binaryColorThreshold', + ]); + if (parentObject !== undefined && fromBinaryColorThreshold != null) { + setValueByPath(parentObject, ['parameters', 'binaryColorThreshold'], fromBinaryColorThreshold); + } + return toObject; +} +function segmentImageParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], segmentImageSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], segmentImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listModelsConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listModelsConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function updateModelConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateModelConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function deleteModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function countTokensConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['generationConfig'], fromGenerationConfig); + } + return toObject; +} +function countTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function computeTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoToVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['gcsUri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ['videoBytes']); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function videoGenerationReferenceImageToVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + return toObject; +} +function generateVideosConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromFps = getValueByPath(fromObject, ['fps']); + if (parentObject !== undefined && fromFps != null) { + setValueByPath(parentObject, ['parameters', 'fps'], fromFps); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromResolution = getValueByPath(fromObject, ['resolution']); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ['parameters', 'resolution'], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromPubsubTopic = getValueByPath(fromObject, ['pubsubTopic']); + if (parentObject !== undefined && fromPubsubTopic != null) { + setValueByPath(parentObject, ['parameters', 'pubsubTopic'], fromPubsubTopic); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + const fromGenerateAudio = getValueByPath(fromObject, [ + 'generateAudio', + ]); + if (parentObject !== undefined && fromGenerateAudio != null) { + setValueByPath(parentObject, ['parameters', 'generateAudio'], fromGenerateAudio); + } + const fromLastFrame = getValueByPath(fromObject, ['lastFrame']); + if (parentObject !== undefined && fromLastFrame != null) { + setValueByPath(parentObject, ['instances[0]', 'lastFrame'], imageToVertex(fromLastFrame)); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (parentObject !== undefined && fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return videoGenerationReferenceImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromCompressionQuality = getValueByPath(fromObject, [ + 'compressionQuality', + ]); + if (parentObject !== undefined && fromCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'compressionQuality'], fromCompressionQuality); + } + return toObject; +} +function generateVideosParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['instances[0]', 'video'], videoToVertex(fromVideo)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataFromMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromMldev(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingFromMldev(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + return toObject; +} +function embedContentMetadataFromMldev() { + const toObject = {}; + return toObject; +} +function embedContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, ['embeddings']); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromMldev(item); + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromMldev()); + } + return toObject; +} +function imageFromMldev(fromObject) { + const toObject = {}; + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromMldev(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + 'safetyAttributes', + 'categories', + ]); + if (fromCategories != null) { + setValueByPath(toObject, ['categories'], fromCategories); + } + const fromScores = getValueByPath(fromObject, [ + 'safetyAttributes', + 'scores', + ]); + if (fromScores != null) { + setValueByPath(toObject, ['scores'], fromScores); + } + const fromContentType = getValueByPath(fromObject, ['contentType']); + if (fromContentType != null) { + setValueByPath(toObject, ['contentType'], fromContentType); + } + return toObject; +} +function generatedImageFromMldev(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromMldev(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromMldev(fromSafetyAttributes)); + } + return toObject; +} +function generateImagesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromMldev(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromMldev(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function tunedModelInfoFromMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function modelFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['version']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromMldev(fromTunedModelInfo)); + } + const fromInputTokenLimit = getValueByPath(fromObject, [ + 'inputTokenLimit', + ]); + if (fromInputTokenLimit != null) { + setValueByPath(toObject, ['inputTokenLimit'], fromInputTokenLimit); + } + const fromOutputTokenLimit = getValueByPath(fromObject, [ + 'outputTokenLimit', + ]); + if (fromOutputTokenLimit != null) { + setValueByPath(toObject, ['outputTokenLimit'], fromOutputTokenLimit); + } + const fromSupportedActions = getValueByPath(fromObject, [ + 'supportedGenerationMethods', + ]); + if (fromSupportedActions != null) { + setValueByPath(toObject, ['supportedActions'], fromSupportedActions); + } + return toObject; +} +function listModelsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromMldev(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function deleteModelResponseFromMldev() { + const toObject = {}; + return toObject; +} +function countTokensResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + return toObject; +} +function videoFromMldev(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['video', 'uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'video', + 'encodedVideo', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['encoding']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromMldev(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, [ + 'generatedSamples', + ]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromMldev(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosOperationFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, [ + 'response', + 'generateVideoResponse', + ]); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromMldev(fromResponse)); + } + return toObject; +} +function videoMetadataFromVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromVertex(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromVertex(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citations']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromVertex(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromVertex(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromVertex(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromVertex(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromVertex(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromVertex(fromCitationMetadata)); + } + const fromFinishMessage = getValueByPath(fromObject, [ + 'finishMessage', + ]); + if (fromFinishMessage != null) { + setValueByPath(toObject, ['finishMessage'], fromFinishMessage); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromVertex(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromVertex(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingStatisticsFromVertex(fromObject) { + const toObject = {}; + const fromTruncated = getValueByPath(fromObject, ['truncated']); + if (fromTruncated != null) { + setValueByPath(toObject, ['truncated'], fromTruncated); + } + const fromTokenCount = getValueByPath(fromObject, ['token_count']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function contentEmbeddingFromVertex(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + const fromStatistics = getValueByPath(fromObject, ['statistics']); + if (fromStatistics != null) { + setValueByPath(toObject, ['statistics'], contentEmbeddingStatisticsFromVertex(fromStatistics)); + } + return toObject; +} +function embedContentMetadataFromVertex(fromObject) { + const toObject = {}; + const fromBillableCharacterCount = getValueByPath(fromObject, [ + 'billableCharacterCount', + ]); + if (fromBillableCharacterCount != null) { + setValueByPath(toObject, ['billableCharacterCount'], fromBillableCharacterCount); + } + return toObject; +} +function embedContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, [ + 'predictions[]', + 'embeddings', + ]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromVertex(item); + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromVertex(fromMetadata)); + } + return toObject; +} +function imageFromVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromVertex(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + 'safetyAttributes', + 'categories', + ]); + if (fromCategories != null) { + setValueByPath(toObject, ['categories'], fromCategories); + } + const fromScores = getValueByPath(fromObject, [ + 'safetyAttributes', + 'scores', + ]); + if (fromScores != null) { + setValueByPath(toObject, ['scores'], fromScores); + } + const fromContentType = getValueByPath(fromObject, ['contentType']); + if (fromContentType != null) { + setValueByPath(toObject, ['contentType'], fromContentType); + } + return toObject; +} +function generatedImageFromVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromVertex(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromVertex(fromSafetyAttributes)); + } + const fromEnhancedPrompt = getValueByPath(fromObject, ['prompt']); + if (fromEnhancedPrompt != null) { + setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt); + } + return toObject; +} +function generateImagesResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromVertex(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function editImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function upscaleImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function recontextImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function entityLabelFromVertex(fromObject) { + const toObject = {}; + const fromLabel = getValueByPath(fromObject, ['label']); + if (fromLabel != null) { + setValueByPath(toObject, ['label'], fromLabel); + } + const fromScore = getValueByPath(fromObject, ['score']); + if (fromScore != null) { + setValueByPath(toObject, ['score'], fromScore); + } + return toObject; +} +function generatedImageMaskFromVertex(fromObject) { + const toObject = {}; + const fromMask = getValueByPath(fromObject, ['_self']); + if (fromMask != null) { + setValueByPath(toObject, ['mask'], imageFromVertex(fromMask)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + let transformedList = fromLabels; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return entityLabelFromVertex(item); + }); + } + setValueByPath(toObject, ['labels'], transformedList); + } + return toObject; +} +function segmentImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedMasks = getValueByPath(fromObject, ['predictions']); + if (fromGeneratedMasks != null) { + let transformedList = fromGeneratedMasks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageMaskFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedMasks'], transformedList); + } + return toObject; +} +function endpointFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['endpoint']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDeployedModelId = getValueByPath(fromObject, [ + 'deployedModelId', + ]); + if (fromDeployedModelId != null) { + setValueByPath(toObject, ['deployedModelId'], fromDeployedModelId); + } + return toObject; +} +function tunedModelInfoFromVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, [ + 'labels', + 'google-vertex-llm-tuning-base-model-id', + ]); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function checkpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ['checkpointId']); + if (fromCheckpointId != null) { + setValueByPath(toObject, ['checkpointId'], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ['epoch']); + if (fromEpoch != null) { + setValueByPath(toObject, ['epoch'], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ['step']); + if (fromStep != null) { + setValueByPath(toObject, ['step'], fromStep); + } + return toObject; +} +function modelFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['versionId']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromEndpoints = getValueByPath(fromObject, ['deployedModels']); + if (fromEndpoints != null) { + let transformedList = fromEndpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return endpointFromVertex(item); + }); + } + setValueByPath(toObject, ['endpoints'], transformedList); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromVertex(fromTunedModelInfo)); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (fromDefaultCheckpointId != null) { + setValueByPath(toObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + const fromCheckpoints = getValueByPath(fromObject, ['checkpoints']); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return checkpointFromVertex(item); + }); + } + setValueByPath(toObject, ['checkpoints'], transformedList); + } + return toObject; +} +function listModelsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromVertex(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function deleteModelResponseFromVertex() { + const toObject = {}; + return toObject; +} +function countTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + return toObject; +} +function computeTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTokensInfo = getValueByPath(fromObject, ['tokensInfo']); + if (fromTokensInfo != null) { + setValueByPath(toObject, ['tokensInfo'], fromTokensInfo); + } + return toObject; +} +function videoFromVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['gcsUri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromVertex(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ['videos']); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosOperationFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromVertex(fromResponse)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const CONTENT_TYPE_HEADER = 'Content-Type'; +const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout'; +const USER_AGENT_HEADER = 'User-Agent'; +const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client'; +const SDK_VERSION = '1.15.0'; // x-release-please-version +const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`; +const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1'; +const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta'; +const responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/; +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +class ApiClient { + constructor(opts) { + var _a, _b; + this.clientOptions = Object.assign(Object.assign({}, opts), { project: opts.project, location: opts.location, apiKey: opts.apiKey, vertexai: opts.vertexai }); + const initHttpOptions = {}; + if (this.clientOptions.vertexai) { + initHttpOptions.apiVersion = + (_a = this.clientOptions.apiVersion) !== null && _a !== void 0 ? _a : VERTEX_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = this.baseUrlFromProjectLocation(); + this.normalizeAuthParameters(); + } + else { + // Gemini API + initHttpOptions.apiVersion = + (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 ? _b : GOOGLE_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`; + } + initHttpOptions.headers = this.getDefaultHeaders(); + this.clientOptions.httpOptions = initHttpOptions; + if (opts.httpOptions) { + this.clientOptions.httpOptions = this.patchHttpOptions(initHttpOptions, opts.httpOptions); + } + } + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + baseUrlFromProjectLocation() { + if (this.clientOptions.project && + this.clientOptions.location && + this.clientOptions.location !== 'global') { + // Regional endpoint + return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`; + } + // Global endpoint (covers 'global' location and API key usage) + return `https://aiplatform.googleapis.com/`; + } + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + normalizeAuthParameters() { + if (this.clientOptions.project && this.clientOptions.location) { + // Using project/location for auth, clear potential API key + this.clientOptions.apiKey = undefined; + return; + } + // Using API key for auth (or no auth provided yet), clear project/location + this.clientOptions.project = undefined; + this.clientOptions.location = undefined; + } + isVertexAI() { + var _a; + return (_a = this.clientOptions.vertexai) !== null && _a !== void 0 ? _a : false; + } + getProject() { + return this.clientOptions.project; + } + getLocation() { + return this.clientOptions.location; + } + getApiVersion() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.apiVersion !== undefined) { + return this.clientOptions.httpOptions.apiVersion; + } + throw new Error('API version is not set.'); + } + getBaseUrl() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.baseUrl !== undefined) { + return this.clientOptions.httpOptions.baseUrl; + } + throw new Error('Base URL is not set.'); + } + getRequestUrl() { + return this.getRequestUrlInternal(this.clientOptions.httpOptions); + } + getHeaders() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.headers !== undefined) { + return this.clientOptions.httpOptions.headers; + } + else { + throw new Error('Headers are not set.'); + } + } + getRequestUrlInternal(httpOptions) { + if (!httpOptions || + httpOptions.baseUrl === undefined || + httpOptions.apiVersion === undefined) { + throw new Error('HTTP options are not correctly set.'); + } + const baseUrl = httpOptions.baseUrl.endsWith('/') + ? httpOptions.baseUrl.slice(0, -1) + : httpOptions.baseUrl; + const urlElement = [baseUrl]; + if (httpOptions.apiVersion && httpOptions.apiVersion !== '') { + urlElement.push(httpOptions.apiVersion); + } + return urlElement.join('/'); + } + getBaseResourcePath() { + return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`; + } + getApiKey() { + return this.clientOptions.apiKey; + } + getWebsocketBaseUrl() { + const baseUrl = this.getBaseUrl(); + const urlParts = new URL(baseUrl); + urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss'; + return urlParts.toString(); + } + setBaseUrl(url) { + if (this.clientOptions.httpOptions) { + this.clientOptions.httpOptions.baseUrl = url; + } + else { + throw new Error('HTTP options are not correctly set.'); + } + } + constructUrl(path, httpOptions, prependProjectLocation) { + const urlElement = [this.getRequestUrlInternal(httpOptions)]; + if (prependProjectLocation) { + urlElement.push(this.getBaseResourcePath()); + } + if (path !== '') { + urlElement.push(path); + } + const url = new URL(`${urlElement.join('/')}`); + return url; + } + shouldPrependVertexProjectPath(request) { + if (this.clientOptions.apiKey) { + return false; + } + if (!this.clientOptions.vertexai) { + return false; + } + if (request.path.startsWith('projects/')) { + // Assume the path already starts with + // `projects//location/`. + return false; + } + if (request.httpMethod === 'GET' && + request.path.startsWith('publishers/google/models')) { + // These paths are used by Vertex's models.get and models.list + // calls. For base models Vertex does not accept a project/location + // prefix (for tuned model the prefix is required). + return false; + } + return true; + } + async request(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (request.queryParams) { + for (const [key, value] of Object.entries(request.queryParams)) { + url.searchParams.append(key, String(value)); + } + } + let requestInit = {}; + if (request.httpMethod === 'GET') { + if (request.body && request.body !== '{}') { + throw new Error('Request body should be empty for GET request, but got non empty request body'); + } + } + else { + requestInit.body = request.body; + } + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal); + return this.unaryApiCall(url, requestInit, request.httpMethod); + } + patchHttpOptions(baseHttpOptions, requestHttpOptions) { + const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions)); + for (const [key, value] of Object.entries(requestHttpOptions)) { + // Records compile to objects. + if (typeof value === 'object') { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = Object.assign(Object.assign({}, patchedHttpOptions[key]), value); + } + else if (value !== undefined) { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = value; + } + } + return patchedHttpOptions; + } + async requestStream(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') { + url.searchParams.set('alt', 'sse'); + } + let requestInit = {}; + requestInit.body = request.body; + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal); + return this.streamApiCall(url, requestInit, request.httpMethod); + } + async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions, abortSignal) { + if ((httpOptions && httpOptions.timeout) || abortSignal) { + const abortController = new AbortController(); + const signal = abortController.signal; + if (httpOptions.timeout && (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) > 0) { + const timeoutHandle = setTimeout(() => abortController.abort(), httpOptions.timeout); + if (timeoutHandle && + typeof timeoutHandle.unref === + 'function') { + // call unref to prevent nodejs process from hanging, see + // https://nodejs.org/api/timers.html#timeoutunref + timeoutHandle.unref(); + } + } + if (abortSignal) { + abortSignal.addEventListener('abort', () => { + abortController.abort(); + }); + } + requestInit.signal = signal; + } + if (httpOptions && httpOptions.extraBody !== null) { + includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody); + } + requestInit.headers = await this.getHeadersInternal(httpOptions); + return requestInit; + } + async unaryApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return new HttpResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + async streamApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return this.processStreamResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + processStreamResponse(response) { + var _a; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + const reader = (_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.getReader(); + const decoder = new TextDecoder('utf-8'); + if (!reader) { + throw new Error('Response body is empty'); + } + try { + let buffer = ''; + while (true) { + const { done, value } = yield __await(reader.read()); + if (done) { + if (buffer.trim().length > 0) { + throw new Error('Incomplete JSON segment at the end'); + } + break; + } + const chunkString = decoder.decode(value, { stream: true }); + // Parse and throw an error if the chunk contains an error. + try { + const chunkJson = JSON.parse(chunkString); + if ('error' in chunkJson) { + const errorJson = JSON.parse(JSON.stringify(chunkJson['error'])); + const status = errorJson['status']; + const code = errorJson['code']; + const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`; + if (code >= 400 && code < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: code, + }); + throw apiError; + } + } + } + catch (e) { + const error = e; + if (error.name === 'ApiError') { + throw e; + } + } + buffer += chunkString; + let match = buffer.match(responseLineRE); + while (match) { + const processedChunkString = match[1]; + try { + const partialResponse = new Response(processedChunkString, { + headers: response === null || response === void 0 ? void 0 : response.headers, + status: response === null || response === void 0 ? void 0 : response.status, + statusText: response === null || response === void 0 ? void 0 : response.statusText, + }); + yield yield __await(new HttpResponse(partialResponse)); + buffer = buffer.slice(match[0].length); + match = buffer.match(responseLineRE); + } + catch (e) { + throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`); + } + } + } + } + finally { + reader.releaseLock(); + } + }); + } + async apiCall(url, requestInit) { + return fetch(url, requestInit).catch((e) => { + throw new Error(`exception ${e} sending request`); + }); + } + getDefaultHeaders() { + const headers = {}; + const versionHeaderValue = LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra; + headers[USER_AGENT_HEADER] = versionHeaderValue; + headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue; + headers[CONTENT_TYPE_HEADER] = 'application/json'; + return headers; + } + async getHeadersInternal(httpOptions) { + const headers = new Headers(); + if (httpOptions && httpOptions.headers) { + for (const [key, value] of Object.entries(httpOptions.headers)) { + headers.append(key, value); + } + // Append a timeout header if it is set, note that the timeout option is + // in milliseconds but the header is in seconds. + if (httpOptions.timeout && httpOptions.timeout > 0) { + headers.append(SERVER_TIMEOUT_HEADER, String(Math.ceil(httpOptions.timeout / 1000))); + } + } + await this.clientOptions.auth.addAuthHeaders(headers); + return headers; + } + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + async uploadFile(file, config) { + var _a; + const fileToUpload = {}; + if (config != null) { + fileToUpload.mimeType = config.mimeType; + fileToUpload.name = config.name; + fileToUpload.displayName = config.displayName; + } + if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) { + fileToUpload.name = `files/${fileToUpload.name}`; + } + const uploader = this.clientOptions.uploader; + const fileStat = await uploader.stat(file); + fileToUpload.sizeBytes = String(fileStat.size); + const mimeType = (_a = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a !== void 0 ? _a : fileStat.type; + if (mimeType === undefined || mimeType === '') { + throw new Error('Can not determine mimeType. Please provide mimeType in the config.'); + } + fileToUpload.mimeType = mimeType; + const uploadUrl = await this.fetchUploadUrl(fileToUpload, config); + return uploader.upload(file, uploadUrl, this); + } + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + async downloadFile(params) { + const downloader = this.clientOptions.downloader; + await downloader.download(params, this); + } + async fetchUploadUrl(file, config) { + var _a; + let httpOptions = {}; + if (config === null || config === void 0 ? void 0 : config.httpOptions) { + httpOptions = config.httpOptions; + } + else { + httpOptions = { + apiVersion: '', + headers: { + 'Content-Type': 'application/json', + 'X-Goog-Upload-Protocol': 'resumable', + 'X-Goog-Upload-Command': 'start', + 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`, + 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`, + }, + }; + } + const body = { + 'file': file, + }; + const httpResponse = await this.request({ + path: formatMap('upload/v1beta/files', body['_url']), + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions, + }); + if (!httpResponse || !(httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers)) { + throw new Error('Server did not return an HttpResponse or the returned HttpResponse did not have headers.'); + } + const uploadUrl = (_a = httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers) === null || _a === void 0 ? void 0 : _a['x-goog-upload-url']; + if (uploadUrl === undefined) { + throw new Error('Failed to get upload url. Server did not return the x-google-upload-url in the headers'); + } + return uploadUrl; + } +} +async function throwErrorIfNotOK(response) { + var _a; + if (response === undefined) { + throw new Error('response is undefined'); + } + if (!response.ok) { + const status = response.status; + let errorBody; + if ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('application/json')) { + errorBody = await response.json(); + } + else { + errorBody = { + error: { + message: await response.text(), + code: response.status, + status: response.statusText, + }, + }; + } + const errorMessage = JSON.stringify(errorBody); + if (status >= 400 && status < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: status, + }); + throw apiError; + } + throw new Error(errorMessage); + } +} +/** + * Recursively updates the `requestInit.body` with values from an `extraBody` object. + * + * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed. + * The `extraBody` is then deeply merged into this parsed object. + * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged, + * as merging structured data into an opaque Blob is not supported. + * + * The function does not enforce that updated values from `extraBody` have the + * same type as existing values in `requestInit.body`. Type mismatches during + * the merge will result in a warning, but the value from `extraBody` will overwrite + * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure. + * + * @param requestInit The RequestInit object whose body will be updated. + * @param extraBody The object containing updates to be merged into `requestInit.body`. + */ +function includeExtraBodyToRequestInit(requestInit, extraBody) { + if (!extraBody || Object.keys(extraBody).length === 0) { + return; + } + if (requestInit.body instanceof Blob) { + console.warn('includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.'); + return; + } + let currentBodyObject = {}; + // If adding new type to HttpRequest.body, please check the code below to + // see if we need to update the logic. + if (typeof requestInit.body === 'string' && requestInit.body.length > 0) { + try { + const parsedBody = JSON.parse(requestInit.body); + if (typeof parsedBody === 'object' && + parsedBody !== null && + !Array.isArray(parsedBody)) { + currentBodyObject = parsedBody; + } + else { + console.warn('includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.'); + return; + } + /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ + } + catch (e) { + console.warn('includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.'); + return; + } + } + function deepMerge(target, source) { + const output = Object.assign({}, target); + for (const key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + const sourceValue = source[key]; + const targetValue = output[key]; + if (sourceValue && + typeof sourceValue === 'object' && + !Array.isArray(sourceValue) && + targetValue && + typeof targetValue === 'object' && + !Array.isArray(targetValue)) { + output[key] = deepMerge(targetValue, sourceValue); + } + else { + if (targetValue && + sourceValue && + typeof targetValue !== typeof sourceValue) { + console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`); + } + output[key] = sourceValue; + } + } + } + return output; + } + const mergedBody = deepMerge(currentBodyObject, extraBody); + requestInit.body = JSON.stringify(mergedBody); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// TODO: b/416041229 - Determine how to retrieve the MCP package version. +const MCP_LABEL = 'mcp_used/unknown'; +// Whether MCP tool usage is detected from mcpToTool. This is used for +// telemetry. +let hasMcpToolUsageFromMcpToTool = false; +// Checks whether the list of tools contains any MCP tools. +function hasMcpToolUsage(tools) { + for (const tool of tools) { + if (isMcpCallableTool(tool)) { + return true; + } + if (typeof tool === 'object' && 'inputSchema' in tool) { + return true; + } + } + return hasMcpToolUsageFromMcpToTool; +} +// Sets the MCP version label in the Google API client header. +function setMcpUsageHeader(headers) { + var _a; + const existingHeader = (_a = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a !== void 0 ? _a : ''; + headers[GOOGLE_API_CLIENT_HEADER] = (existingHeader + ` ${MCP_LABEL}`).trimStart(); +} +// Returns true if the object is a MCP CallableTool, otherwise false. +function isMcpCallableTool(object) { + return (object !== null && + typeof object === 'object' && + object instanceof McpCallableTool); +} +// List all tools from the MCP client. +function listAllTools(mcpClient, maxTools = 100) { + return __asyncGenerator(this, arguments, function* listAllTools_1() { + let cursor = undefined; + let numTools = 0; + while (numTools < maxTools) { + const t = yield __await(mcpClient.listTools({ cursor })); + for (const tool of t.tools) { + yield yield __await(tool); + numTools++; + } + if (!t.nextCursor) { + break; + } + cursor = t.nextCursor; + } + }); +} +/** + * McpCallableTool can be used for model inference and invoking MCP clients with + * given function call arguments. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +class McpCallableTool { + constructor(mcpClients = [], config) { + this.mcpTools = []; + this.functionNameToMcpClient = {}; + this.mcpClients = mcpClients; + this.config = config; + } + /** + * Creates a McpCallableTool. + */ + static create(mcpClients, config) { + return new McpCallableTool(mcpClients, config); + } + /** + * Validates the function names are not duplicate and initialize the function + * name to MCP client mapping. + * + * @throws {Error} if the MCP tools from the MCP clients have duplicate tool + * names. + */ + async initialize() { + var _a, e_1, _b, _c; + if (this.mcpTools.length > 0) { + return; + } + const functionMap = {}; + const mcpTools = []; + for (const mcpClient of this.mcpClients) { + try { + for (var _d = true, _e = (e_1 = void 0, __asyncValues(listAllTools(mcpClient))), _f; _f = await _e.next(), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const mcpTool = _c; + mcpTools.push(mcpTool); + const mcpToolName = mcpTool.name; + if (functionMap[mcpToolName]) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + functionMap[mcpToolName] = mcpClient; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_d && !_a && (_b = _e.return)) await _b.call(_e); + } + finally { if (e_1) throw e_1.error; } + } + } + this.mcpTools = mcpTools; + this.functionNameToMcpClient = functionMap; + } + async tool() { + await this.initialize(); + return mcpToolsToGeminiTool(this.mcpTools, this.config); + } + async callTool(functionCalls) { + await this.initialize(); + const functionCallResponseParts = []; + for (const functionCall of functionCalls) { + if (functionCall.name in this.functionNameToMcpClient) { + const mcpClient = this.functionNameToMcpClient[functionCall.name]; + let requestOptions = undefined; + // TODO: b/424238654 - Add support for finer grained timeout control. + if (this.config.timeout) { + requestOptions = { + timeout: this.config.timeout, + }; + } + const callToolResponse = await mcpClient.callTool({ + name: functionCall.name, + arguments: functionCall.args, + }, + // Set the result schema to undefined to allow MCP to rely on the + // default schema. + undefined, requestOptions); + functionCallResponseParts.push({ + functionResponse: { + name: functionCall.name, + response: callToolResponse.isError + ? { error: callToolResponse } + : callToolResponse, + }, + }); + } + } + return functionCallResponseParts; + } +} +function isMcpClient(client) { + return (client !== null && + typeof client === 'object' && + 'listTools' in client && + typeof client.listTools === 'function'); +} +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +function mcpToTool(...args) { + // Set MCP usage for telemetry. + hasMcpToolUsageFromMcpToTool = true; + if (args.length === 0) { + throw new Error('No MCP clients provided'); + } + const maybeConfig = args[args.length - 1]; + if (isMcpClient(maybeConfig)) { + return McpCallableTool.create(args, {}); + } + return McpCallableTool.create(args.slice(0, args.length - 1), maybeConfig); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveMusicServerMessage, and then calling the onmessage callback. + * Note that the first message which is received from the server is a + * setupComplete message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage$1(apiClient, onmessage, event) { + const serverMessage = new LiveMusicServerMessage(); + let data; + if (event.data instanceof Blob) { + data = JSON.parse(await event.data.text()); + } + else { + data = JSON.parse(event.data); + } + const response = liveMusicServerMessageFromMldev(data); + Object.assign(serverMessage, response); + onmessage(serverMessage); +} +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +class LiveMusic { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + } + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b; + if (this.apiClient.isVertexAI()) { + throw new Error('Live music is not supported for Vertex AI.'); + } + console.warn('Live music generation is experimental and may change in future versions.'); + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + const headers = mapToHeaders$1(this.apiClient.getDefaultHeaders()); + const apiKey = this.apiClient.getApiKey(); + const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`; + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage$1(apiClient, callbacks.onmessage, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap$1(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + const model = tModel(this.apiClient, params.model); + const setup = liveMusicClientSetupToMldev({ + model, + }); + const clientMessage = liveMusicClientMessageToMldev({ setup }); + conn.send(JSON.stringify(clientMessage)); + return new LiveMusicSession(conn, this.apiClient); + } +} +/** + Represents a connection to the API. + + @experimental + */ +class LiveMusicSession { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + async setWeightedPrompts(params) { + if (!params.weightedPrompts || + Object.keys(params.weightedPrompts).length === 0) { + throw new Error('Weighted prompts must be set and contain at least one entry.'); + } + const setWeightedPromptsParameters = liveMusicSetWeightedPromptsParametersToMldev(params); + const clientContent = liveMusicClientContentToMldev(setWeightedPromptsParameters); + this.conn.send(JSON.stringify({ clientContent })); + } + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + async setMusicGenerationConfig(params) { + if (!params.musicGenerationConfig) { + params.musicGenerationConfig = {}; + } + const setConfigParameters = liveMusicSetConfigParametersToMldev(params); + const clientMessage = liveMusicClientMessageToMldev(setConfigParameters); + this.conn.send(JSON.stringify(clientMessage)); + } + sendPlaybackControl(playbackControl) { + const clientMessage = liveMusicClientMessageToMldev({ + playbackControl, + }); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + * Start the music stream. + * + * @experimental + */ + play() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PLAY); + } + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PAUSE); + } + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop() { + this.sendPlaybackControl(LiveMusicPlaybackControl.STOP); + } + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext() { + this.sendPlaybackControl(LiveMusicPlaybackControl.RESET_CONTEXT); + } + /** + Terminates the WebSocket connection. + + @experimental + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap$1(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders$1(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const FUNCTION_RESPONSE_REQUIRES_ID = 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.'; +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveServerMessages, and then calling the onmessage callback. Note that + * the first message which is received from the server is a setupComplete + * message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage(apiClient, onmessage, event) { + const serverMessage = new LiveServerMessage(); + let jsonData; + if (event.data instanceof Blob) { + jsonData = await event.data.text(); + } + else if (event.data instanceof ArrayBuffer) { + jsonData = new TextDecoder().decode(event.data); + } + else { + jsonData = event.data; + } + const data = JSON.parse(jsonData); + if (apiClient.isVertexAI()) { + const resp = liveServerMessageFromVertex(data); + Object.assign(serverMessage, resp); + } + else { + const resp = liveServerMessageFromMldev(data); + Object.assign(serverMessage, resp); + } + onmessage(serverMessage); +} +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +class Live { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + this.music = new LiveMusic(this.apiClient, this.auth, this.webSocketFactory); + } + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b, _c, _d, _e, _f; + // TODO: b/404946746 - Support per request HTTP options. + if (params.config && params.config.httpOptions) { + throw new Error('The Live module does not support httpOptions at request-level in' + + ' LiveConnectConfig yet. Please use the client-level httpOptions' + + ' configuration instead.'); + } + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + let url; + const clientHeaders = this.apiClient.getHeaders(); + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + setMcpUsageHeader(clientHeaders); + } + const headers = mapToHeaders(clientHeaders); + if (this.apiClient.isVertexAI()) { + url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`; + await this.auth.addAuthHeaders(headers); + } + else { + const apiKey = this.apiClient.getApiKey(); + let method = 'BidiGenerateContent'; + let keyName = 'key'; + if (apiKey === null || apiKey === void 0 ? void 0 : apiKey.startsWith('auth_tokens/')) { + console.warn('Warning: Ephemeral token support is experimental and may change in future versions.'); + if (apiVersion !== 'v1alpha') { + console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."); + } + method = 'BidiGenerateContentConstrained'; + keyName = 'access_token'; + } + url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`; + } + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + var _a; + (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onopen) === null || _a === void 0 ? void 0 : _a.call(callbacks); + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage(apiClient, callbacks.onmessage, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + let transformedModel = tModel(this.apiClient, params.model); + if (this.apiClient.isVertexAI() && + transformedModel.startsWith('publishers/')) { + const project = this.apiClient.getProject(); + const location = this.apiClient.getLocation(); + transformedModel = + `projects/${project}/locations/${location}/` + transformedModel; + } + let clientMessage = {}; + if (this.apiClient.isVertexAI() && + ((_c = params.config) === null || _c === void 0 ? void 0 : _c.responseModalities) === undefined) { + // Set default to AUDIO to align with MLDev API. + if (params.config === undefined) { + params.config = { responseModalities: [Modality.AUDIO] }; + } + else { + params.config.responseModalities = [Modality.AUDIO]; + } + } + if ((_d = params.config) === null || _d === void 0 ? void 0 : _d.generationConfig) { + // Raise deprecation warning for generationConfig. + console.warn('Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).'); + } + const inputTools = (_f = (_e = params.config) === null || _e === void 0 ? void 0 : _e.tools) !== null && _f !== void 0 ? _f : []; + const convertedTools = []; + for (const tool of inputTools) { + if (this.isCallableTool(tool)) { + const callableTool = tool; + convertedTools.push(await callableTool.tool()); + } + else { + convertedTools.push(tool); + } + } + if (convertedTools.length > 0) { + params.config.tools = convertedTools; + } + const liveConnectParameters = { + model: transformedModel, + config: params.config, + callbacks: params.callbacks, + }; + if (this.apiClient.isVertexAI()) { + clientMessage = liveConnectParametersToVertex(this.apiClient, liveConnectParameters); + } + else { + clientMessage = liveConnectParametersToMldev(this.apiClient, liveConnectParameters); + } + delete clientMessage['config']; + conn.send(JSON.stringify(clientMessage)); + return new Session(conn, this.apiClient); + } + // TODO: b/416041229 - Abstract this method to a common place. + isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; + } +} +const defaultLiveSendClientContentParamerters = { + turnComplete: true, +}; +/** + Represents a connection to the API. + + @experimental + */ +class Session { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + tLiveClientContent(apiClient, params) { + if (params.turns !== null && params.turns !== undefined) { + let contents = []; + try { + contents = tContents(params.turns); + if (apiClient.isVertexAI()) { + contents = contents.map((item) => contentToVertex(item)); + } + else { + contents = contents.map((item) => contentToMldev$1(item)); + } + } + catch (_a) { + throw new Error(`Failed to parse client content "turns", type: '${typeof params.turns}'`); + } + return { + clientContent: { turns: contents, turnComplete: params.turnComplete }, + }; + } + return { + clientContent: { turnComplete: params.turnComplete }, + }; + } + tLiveClienttToolResponse(apiClient, params) { + let functionResponses = []; + if (params.functionResponses == null) { + throw new Error('functionResponses is required.'); + } + if (!Array.isArray(params.functionResponses)) { + functionResponses = [params.functionResponses]; + } + else { + functionResponses = params.functionResponses; + } + if (functionResponses.length === 0) { + throw new Error('functionResponses is required.'); + } + for (const functionResponse of functionResponses) { + if (typeof functionResponse !== 'object' || + functionResponse === null || + !('name' in functionResponse) || + !('response' in functionResponse)) { + throw new Error(`Could not parse function response, type '${typeof functionResponse}'.`); + } + if (!apiClient.isVertexAI() && !('id' in functionResponse)) { + throw new Error(FUNCTION_RESPONSE_REQUIRES_ID); + } + } + const clientMessage = { + toolResponse: { functionResponses: functionResponses }, + }; + return clientMessage; + } + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params) { + params = Object.assign(Object.assign({}, defaultLiveSendClientContentParamerters), params); + const clientMessage = this.tLiveClientContent(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params) { + let clientMessage = {}; + if (this.apiClient.isVertexAI()) { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToVertex(params), + }; + } + else { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToMldev(params), + }; + } + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params) { + if (params.functionResponses == null) { + throw new Error('Tool response parameters are required.'); + } + const clientMessage = this.tLiveClienttToolResponse(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const DEFAULT_MAX_REMOTE_CALLS = 10; +/** Returns whether automatic function calling is disabled. */ +function shouldDisableAfc(config) { + var _a, _b, _c; + if ((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.disable) { + return true; + } + let callableToolsPresent = false; + for (const tool of (_b = config === null || config === void 0 ? void 0 : config.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + callableToolsPresent = true; + break; + } + } + if (!callableToolsPresent) { + return true; + } + const maxCalls = (_c = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _c === void 0 ? void 0 : _c.maximumRemoteCalls; + if ((maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) || + maxCalls == 0) { + console.warn('Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:', maxCalls); + return true; + } + return false; +} +function isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; +} +// Checks whether the list of tools contains any CallableTools. Will return true +// if there is at least one CallableTool. +function hasCallableTools(params) { + var _a, _b, _c; + return (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +// Checks whether the list of tools contains any non-callable tools. Will return +// true if there is at least one non-Callable tool. +function hasNonCallableTools(params) { + var _a, _b, _c; + return (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => !isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +/** + * Returns whether to append automatic function calling history to the + * response. + */ +function shouldAppendAfcHistory(config) { + var _a; + return !((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.ignoreCallHistory); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Models extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + this.generateContent = async (params) => { + var _a, _b, _c, _d, _e; + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + this.maybeMoveToResponseJsonSchem(params); + if (!hasCallableTools(params) || shouldDisableAfc(params.config)) { + return await this.generateContentInternal(transformedParams); + } + if (hasNonCallableTools(params)) { + throw new Error('Automatic function calling with CallableTools and Tools is not yet supported.'); + } + let response; + let functionResponseContent; + const automaticFunctionCallingHistory = tContents(transformedParams.contents); + const maxRemoteCalls = (_c = (_b = (_a = transformedParams.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let remoteCalls = 0; + while (remoteCalls < maxRemoteCalls) { + response = await this.generateContentInternal(transformedParams); + if (!response.functionCalls || response.functionCalls.length === 0) { + break; + } + const responseContent = response.candidates[0].content; + const functionResponseParts = []; + for (const tool of (_e = (_d = params.config) === null || _d === void 0 ? void 0 : _d.tools) !== null && _e !== void 0 ? _e : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const parts = await callableTool.callTool(response.functionCalls); + functionResponseParts.push(...parts); + } + } + remoteCalls++; + functionResponseContent = { + role: 'user', + parts: functionResponseParts, + }; + transformedParams.contents = tContents(transformedParams.contents); + transformedParams.contents.push(responseContent); + transformedParams.contents.push(functionResponseContent); + if (shouldAppendAfcHistory(transformedParams.config)) { + automaticFunctionCallingHistory.push(responseContent); + automaticFunctionCallingHistory.push(functionResponseContent); + } + } + if (shouldAppendAfcHistory(transformedParams.config)) { + response.automaticFunctionCallingHistory = + automaticFunctionCallingHistory; + } + return response; + }; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + this.generateContentStream = async (params) => { + this.maybeMoveToResponseJsonSchem(params); + if (shouldDisableAfc(params.config)) { + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + return await this.generateContentStreamInternal(transformedParams); + } + else { + return await this.processAfcStream(params); + } + }; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.generateImages = async (params) => { + return await this.generateImagesInternal(params).then((apiResponse) => { + var _a; + let positivePromptSafetyAttributes; + const generatedImages = []; + if (apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.generatedImages) { + for (const generatedImage of apiResponse.generatedImages) { + if (generatedImage && + (generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) && + ((_a = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) === null || _a === void 0 ? void 0 : _a.contentType) === 'Positive Prompt') { + positivePromptSafetyAttributes = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes; + } + else { + generatedImages.push(generatedImage); + } + } + } + let response; + if (positivePromptSafetyAttributes) { + response = { + generatedImages: generatedImages, + positivePromptSafetyAttributes: positivePromptSafetyAttributes, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + else { + response = { + generatedImages: generatedImages, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + return response; + }); + }; + this.list = async (params) => { + var _a; + const defaultConfig = { + queryBase: true, + }; + const actualConfig = Object.assign(Object.assign({}, defaultConfig), params === null || params === void 0 ? void 0 : params.config); + const actualParams = { + config: actualConfig, + }; + if (this.apiClient.isVertexAI()) { + if (!actualParams.config.queryBase) { + if ((_a = actualParams.config) === null || _a === void 0 ? void 0 : _a.filter) { + throw new Error('Filtering tuned models list for Vertex AI is not currently supported'); + } + else { + actualParams.config.filter = 'labels.tune-type:*'; + } + } + } + return new Pager(PagedItem.PAGED_ITEM_MODELS, (x) => this.listInternal(x), await this.listInternal(actualParams), actualParams); + }; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.editImage = async (params) => { + const paramsInternal = { + model: params.model, + prompt: params.prompt, + referenceImages: [], + config: params.config, + }; + if (params.referenceImages) { + if (params.referenceImages) { + paramsInternal.referenceImages = params.referenceImages.map((img) => img.toReferenceImageAPI()); + } + } + return await this.editImageInternal(paramsInternal); + }; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.upscaleImage = async (params) => { + let apiConfig = { + numberOfImages: 1, + mode: 'upscale', + }; + if (params.config) { + apiConfig = Object.assign(Object.assign({}, apiConfig), params.config); + } + const apiParams = { + model: params.model, + image: params.image, + upscaleFactor: params.upscaleFactor, + config: apiConfig, + }; + return await this.upscaleImageInternal(apiParams); + }; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + this.generateVideos = async (params) => { + return await this.generateVideosInternal(params); + }; + } + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + maybeMoveToResponseJsonSchem(params) { + if (params.config && params.config.responseSchema) { + if (!params.config.responseJsonSchema) { + if (Object.keys(params.config.responseSchema).includes('$schema')) { + params.config.responseJsonSchema = params.config.responseSchema; + delete params.config.responseSchema; + } + } + } + return; + } + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + async processParamsMaybeAddMcpUsage(params) { + var _a, _b, _c; + const tools = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools; + if (!tools) { + return params; + } + const transformedTools = await Promise.all(tools.map(async (tool) => { + if (isCallableTool(tool)) { + const callableTool = tool; + return await callableTool.tool(); + } + return tool; + })); + const newParams = { + model: params.model, + contents: params.contents, + config: Object.assign(Object.assign({}, params.config), { tools: transformedTools }), + }; + newParams.config.tools = transformedTools; + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + const headers = (_c = (_b = params.config.httpOptions) === null || _b === void 0 ? void 0 : _b.headers) !== null && _c !== void 0 ? _c : {}; + let newHeaders = Object.assign({}, headers); + if (Object.keys(newHeaders).length === 0) { + newHeaders = this.apiClient.getDefaultHeaders(); + } + setMcpUsageHeader(newHeaders); + newParams.config.httpOptions = Object.assign(Object.assign({}, params.config.httpOptions), { headers: newHeaders }); + } + return newParams; + } + async initAfcToolsMap(params) { + var _a, _b, _c; + const afcTools = new Map(); + for (const tool of (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const toolDeclaration = await callableTool.tool(); + for (const declaration of (_c = toolDeclaration.functionDeclarations) !== null && _c !== void 0 ? _c : []) { + if (!declaration.name) { + throw new Error('Function declaration name is required.'); + } + if (afcTools.has(declaration.name)) { + throw new Error(`Duplicate tool declaration name: ${declaration.name}`); + } + afcTools.set(declaration.name, callableTool); + } + } + } + return afcTools; + } + async processAfcStream(params) { + var _a, _b, _c; + const maxRemoteCalls = (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let wereFunctionsCalled = false; + let remoteCallCount = 0; + const afcToolsMap = await this.initAfcToolsMap(params); + return (function (models, afcTools, params) { + var _a, _b; + return __asyncGenerator(this, arguments, function* () { + var _c, e_1, _d, _e; + while (remoteCallCount < maxRemoteCalls) { + if (wereFunctionsCalled) { + remoteCallCount++; + wereFunctionsCalled = false; + } + const transformedParams = yield __await(models.processParamsMaybeAddMcpUsage(params)); + const response = yield __await(models.generateContentStreamInternal(transformedParams)); + const functionResponses = []; + const responseContents = []; + try { + for (var _f = true, response_1 = (e_1 = void 0, __asyncValues(response)), response_1_1; response_1_1 = yield __await(response_1.next()), _c = response_1_1.done, !_c; _f = true) { + _e = response_1_1.value; + _f = false; + const chunk = _e; + yield yield __await(chunk); + if (chunk.candidates && ((_a = chunk.candidates[0]) === null || _a === void 0 ? void 0 : _a.content)) { + responseContents.push(chunk.candidates[0].content); + for (const part of (_b = chunk.candidates[0].content.parts) !== null && _b !== void 0 ? _b : []) { + if (remoteCallCount < maxRemoteCalls && part.functionCall) { + if (!part.functionCall.name) { + throw new Error('Function call name was not returned by the model.'); + } + if (!afcTools.has(part.functionCall.name)) { + throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${part.functionCall.name}`); + } + else { + const responseParts = yield __await(afcTools + .get(part.functionCall.name) + .callTool([part.functionCall])); + functionResponses.push(...responseParts); + } + } + } + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_c && (_d = response_1.return)) yield __await(_d.call(response_1)); + } + finally { if (e_1) throw e_1.error; } + } + if (functionResponses.length > 0) { + wereFunctionsCalled = true; + const typedResponseChunk = new GenerateContentResponse(); + typedResponseChunk.candidates = [ + { + content: { + role: 'user', + parts: functionResponses, + }, + }, + ]; + yield yield __await(typedResponseChunk); + const newContents = []; + newContents.push(...responseContents); + newContents.push({ + role: 'user', + parts: functionResponses, + }); + const updatedContents = tContents(params.contents).concat(newContents); + params.contents = updatedContents; + } + else { + break; + } + } + }); + })(this, afcToolsMap, params); + } + async generateContentInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromVertex(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromMldev(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async generateContentStreamInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_2, _b, _c; + try { + for (var _d = true, apiResponse_1 = __asyncValues(apiResponse), apiResponse_1_1; apiResponse_1_1 = yield __await(apiResponse_1.next()), _a = apiResponse_1_1.done, !_a; _d = true) { + _c = apiResponse_1_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromVertex((yield __await(chunk.json()))); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_1.return)) yield __await(_b.call(apiResponse_1)); + } + finally { if (e_2) throw e_2.error; } + } + }); + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_3, _b, _c; + try { + for (var _d = true, apiResponse_2 = __asyncValues(apiResponse), apiResponse_2_1; apiResponse_2_1 = yield __await(apiResponse_2.next()), _a = apiResponse_2_1.done, !_a; _d = true) { + _c = apiResponse_2_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromMldev((yield __await(chunk.json()))); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_2.return)) yield __await(_b.call(apiResponse_2)); + } + finally { if (e_3) throw e_3.error; } + } + }); + }); + } + } + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + async embedContent(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = embedContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromVertex(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = embedContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchEmbedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromMldev(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async generateImagesInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateImagesParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromVertex(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateImagesParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromMldev(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async editImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = editImageParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = editImageResponseFromVertex(apiResponse); + const typedResp = new EditImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + async upscaleImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = upscaleImageAPIParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = upscaleImageResponseFromVertex(apiResponse); + const typedResp = new UpscaleImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Recontextualizes an image. + * + * There are two types of recontextualization currently supported: + * 1) Imagen Product Recontext - Generate images of products in new scenes + * and contexts. + * 2) Virtual Try-On: Generate images of persons modeling fashion products. + * + * @param params - The parameters for recontextualizing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response1 = await ai.models.recontextImage({ + * model: 'imagen-product-recontext-preview-06-30', + * source: { + * prompt: 'In a modern kitchen setting.', + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response1?.generatedImages?.[0]?.image?.imageBytes); + * + * const response2 = await ai.models.recontextImage({ + * model: 'virtual-try-on-preview-08-04', + * source: { + * personImage: personImage, + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response2?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async recontextImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = recontextImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = recontextImageResponseFromVertex(apiResponse); + const typedResp = new RecontextImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Segments an image, creating a mask of a specified area. + * + * @param params - The parameters for segmenting an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.segmentImage({ + * model: 'image-segmentation-001', + * source: { + * image: image, + * }, + * config: { + * mode: 'foreground', + * }, + * }); + * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes); + * ``` + */ + async segmentImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = segmentImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = segmentImageResponseFromVertex(apiResponse); + const typedResp = new SegmentImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listModelsParametersToVertex(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromVertex(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listModelsParametersToMldev(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromMldev(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateModelParametersToVertex(this.apiClient, params); + path = formatMap('{model}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = updateModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteModelResponseFromVertex(); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteModelResponseFromMldev(); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + async countTokens(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = countTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromVertex(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = countTokensParametersToMldev(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromMldev(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + async computeTokens(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = computeTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:computeTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = computeTokensResponseFromVertex(apiResponse); + const typedResp = new ComputeTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + async generateVideosInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateVideosParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateVideosParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getOperationParametersToMldev(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fetchPredictOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['operationName'], fromOperationName); + } + const fromResourceName = getValueByPath(fromObject, ['resourceName']); + if (fromResourceName != null) { + setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Operations extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async getVideosOperation(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async get(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + async getVideosOperationInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getOperationParametersToVertex(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + const body = getOperationParametersToMldev(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + } + async fetchPredictVideosOperationInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = fetchPredictOperationParametersToVertex(params); + path = formatMap('{resourceName}:fetchPredictOperation', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is not supported in Gemini API.'); + } + return toObject; +} +function audioTranscriptionConfigToMldev() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToMldev(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToMldev(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToMldev(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToMldev(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToMldev()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToMldev()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToMldev(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToMldev(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToMldev(fromProactivity)); + } + return toObject; +} +function liveConnectConstraintsToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function createAuthTokenConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromNewSessionExpireTime = getValueByPath(fromObject, [ + 'newSessionExpireTime', + ]); + if (parentObject !== undefined && fromNewSessionExpireTime != null) { + setValueByPath(parentObject, ['newSessionExpireTime'], fromNewSessionExpireTime); + } + const fromUses = getValueByPath(fromObject, ['uses']); + if (parentObject !== undefined && fromUses != null) { + setValueByPath(parentObject, ['uses'], fromUses); + } + const fromLiveConnectConstraints = getValueByPath(fromObject, [ + 'liveConnectConstraints', + ]); + if (parentObject !== undefined && fromLiveConnectConstraints != null) { + setValueByPath(parentObject, ['bidiGenerateContentSetup'], liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints)); + } + const fromLockAdditionalFields = getValueByPath(fromObject, [ + 'lockAdditionalFields', + ]); + if (parentObject !== undefined && fromLockAdditionalFields != null) { + setValueByPath(parentObject, ['fieldMask'], fromLockAdditionalFields); + } + return toObject; +} +function createAuthTokenParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createAuthTokenConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function authTokenFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns a comma-separated list of field masks from a given object. + * + * @param setup The object to extract field masks from. + * @return A comma-separated list of field masks. + */ +function getFieldMasks(setup) { + const fields = []; + for (const key in setup) { + if (Object.prototype.hasOwnProperty.call(setup, key)) { + const value = setup[key]; + // 2nd layer, recursively get field masks see TODO(b/418290100) + if (typeof value === 'object' && + value != null && + Object.keys(value).length > 0) { + const field = Object.keys(value).map((kk) => `${key}.${kk}`); + fields.push(...field); + } + else { + fields.push(key); // 1st layer + } + } + } + return fields.join(','); +} +/** + * Converts bidiGenerateContentSetup. + * @param requestDict - The request dictionary. + * @param config - The configuration object. + * @return - The modified request dictionary. + */ +function convertBidiSetupToTokenSetup(requestDict, config) { + // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup. + let setupForMaskGeneration = null; + const bidiGenerateContentSetupValue = requestDict['bidiGenerateContentSetup']; + if (typeof bidiGenerateContentSetupValue === 'object' && + bidiGenerateContentSetupValue !== null && + 'setup' in bidiGenerateContentSetupValue) { + // Now we know bidiGenerateContentSetupValue is an object and has a 'setup' + // property. + const innerSetup = bidiGenerateContentSetupValue + .setup; + if (typeof innerSetup === 'object' && innerSetup !== null) { + // Valid inner setup found. + requestDict['bidiGenerateContentSetup'] = innerSetup; + setupForMaskGeneration = innerSetup; + } + else { + // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as + // if bidiGenerateContentSetup is invalid. + delete requestDict['bidiGenerateContentSetup']; + } + } + else if (bidiGenerateContentSetupValue !== undefined) { + // `bidiGenerateContentSetup` exists but not in the expected + // shape {setup: {...}}; treat as invalid. + delete requestDict['bidiGenerateContentSetup']; + } + const preExistingFieldMask = requestDict['fieldMask']; + // Handle mask generation setup. + if (setupForMaskGeneration) { + const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration); + if (Array.isArray(config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + (config === null || config === void 0 ? void 0 : config.lockAdditionalFields.length) === 0) { + // Case 1: lockAdditionalFields is an empty array. Lock only fields from + // bidi setup. + if (generatedMaskFromBidi) { + // Only assign if mask is not empty + requestDict['fieldMask'] = generatedMaskFromBidi; + } + else { + delete requestDict['fieldMask']; // If mask is empty, effectively no + // specific fields locked by bidi + } + } + else if ((config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + config.lockAdditionalFields.length > 0 && + preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // Case 2: Lock fields from bidi setup + additional fields + // (preExistingFieldMask). + const generationConfigFields = [ + 'temperature', + 'topK', + 'topP', + 'maxOutputTokens', + 'responseModalities', + 'seed', + 'speechConfig', + ]; + let mappedFieldsFromPreExisting = []; + if (preExistingFieldMask.length > 0) { + mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => { + if (generationConfigFields.includes(field)) { + return `generationConfig.${field}`; + } + return field; // Keep original field name if not in + // generationConfigFields + }); + } + const finalMaskParts = []; + if (generatedMaskFromBidi) { + finalMaskParts.push(generatedMaskFromBidi); + } + if (mappedFieldsFromPreExisting.length > 0) { + finalMaskParts.push(...mappedFieldsFromPreExisting); + } + if (finalMaskParts.length > 0) { + requestDict['fieldMask'] = finalMaskParts.join(','); + } + else { + // If no fields from bidi and no valid additional fields from + // pre-existing mask. + delete requestDict['fieldMask']; + } + } + else { + // Case 3: "Lock all fields" (meaning, don't send a field_mask, let server + // defaults apply or all are mutable). This is hit if: + // - `config.lockAdditionalFields` is undefined. + // - `config.lockAdditionalFields` is non-empty, BUT + // `preExistingFieldMask` is null, not a string, or an empty string. + delete requestDict['fieldMask']; + } + } + else { + // No valid `bidiGenerateContentSetup` was found or extracted. + // "Lock additional null fields if any". + if (preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // If there's a pre-existing field mask, it's a string, and it's not + // empty, then we should lock all fields. + requestDict['fieldMask'] = preExistingFieldMask.join(','); + } + else { + delete requestDict['fieldMask']; + } + } + return requestDict; +} +class Tokens extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + async create(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('The client.tokens.create method is only supported by the Gemini Developer API.'); + } + else { + const body = createAuthTokenParametersToMldev(this.apiClient, params); + path = formatMap('auth_tokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const transformedBody = convertBidiSetupToTokenSetup(body, params.config); + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(transformedBody), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = authTokenFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const GOOGLE_API_KEY_HEADER = 'x-goog-api-key'; +const REQUIRED_VERTEX_AI_SCOPE = 'https://www.googleapis.com/auth/cloud-platform'; +class NodeAuth { + constructor(opts) { + if (opts.apiKey !== undefined) { + this.apiKey = opts.apiKey; + return; + } + const vertexAuthOptions = buildGoogleAuthOptions(opts.googleAuthOptions); + this.googleAuth = new GoogleAuth(vertexAuthOptions); + } + async addAuthHeaders(headers) { + if (this.apiKey !== undefined) { + if (this.apiKey.startsWith('auth_tokens/')) { + throw new Error('Ephemeral tokens are only supported by the live API.'); + } + this.addKeyHeader(headers); + return; + } + return this.addGoogleAuthHeaders(headers); + } + addKeyHeader(headers) { + if (headers.get(GOOGLE_API_KEY_HEADER) !== null) { + return; + } + if (this.apiKey === undefined) { + // This should never happen, this method is only called + // when apiKey is set. + throw new Error('Trying to set API key header but apiKey is not set'); + } + headers.append(GOOGLE_API_KEY_HEADER, this.apiKey); + } + async addGoogleAuthHeaders(headers) { + if (this.googleAuth === undefined) { + // This should never happen, addGoogleAuthHeaders should only be + // called when there is no apiKey set and in these cases googleAuth + // is set. + throw new Error('Trying to set google-auth headers but googleAuth is unset'); + } + const authHeaders = await this.googleAuth.getRequestHeaders(); + for (const key in authHeaders) { + if (headers.get(key) !== null) { + continue; + } + headers.append(key, authHeaders[key]); + } + } +} +function buildGoogleAuthOptions(googleAuthOptions) { + let authOptions; + if (!googleAuthOptions) { + authOptions = { + scopes: [REQUIRED_VERTEX_AI_SCOPE], + }; + return authOptions; + } + else { + authOptions = googleAuthOptions; + if (!authOptions.scopes) { + authOptions.scopes = [REQUIRED_VERTEX_AI_SCOPE]; + return authOptions; + } + else if ((typeof authOptions.scopes === 'string' && + authOptions.scopes !== REQUIRED_VERTEX_AI_SCOPE) || + (Array.isArray(authOptions.scopes) && + authOptions.scopes.indexOf(REQUIRED_VERTEX_AI_SCOPE) < 0)) { + throw new Error(`Invalid auth scopes. Scopes must include: ${REQUIRED_VERTEX_AI_SCOPE}`); + } + return authOptions; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeDownloader { + async download(params, apiClient) { + if (params.downloadPath) { + const response = await downloadFile(params, apiClient); + if (response instanceof HttpResponse) { + const writer = createWriteStream(params.downloadPath); + Readable.fromWeb(response.responseInternal.body).pipe(writer); + } + else { + writeFile(params.downloadPath, response, { encoding: 'base64' }, (error) => { + if (error) { + throw new Error(`Failed to write file to ${params.downloadPath}: ${error}`); + } + }); + } + } + } +} +async function downloadFile(params, apiClient) { + var _a, _b, _c; + const name = tFileName(params.file); + if (name !== undefined) { + return await apiClient.request({ + path: `files/${name}:download`, + httpMethod: 'GET', + queryParams: { + 'alt': 'media', + }, + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + else if (isGeneratedVideo(params.file)) { + const videoBytes = (_c = params.file.video) === null || _c === void 0 ? void 0 : _c.videoBytes; + if (typeof videoBytes === 'string') { + return videoBytes; + } + else { + throw new Error('Failed to download generated video, Uri or videoBytes not found.'); + } + } + else if (isVideo(params.file)) { + const videoBytes = params.file.videoBytes; + if (typeof videoBytes === 'string') { + return videoBytes; + } + else { + throw new Error('Failed to download video, Uri or videoBytes not found.'); + } + } + else { + throw new Error('Unsupported file type'); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeWebSocketFactory { + create(url, headers, callbacks) { + return new NodeWebSocket(url, headers, callbacks); + } +} +class NodeWebSocket { + constructor(url, headers, callbacks) { + this.url = url; + this.headers = headers; + this.callbacks = callbacks; + } + connect() { + this.ws = new NodeWs.WebSocket(this.url, { headers: this.headers }); + this.ws.onopen = this.callbacks.onopen; + this.ws.onerror = this.callbacks.onerror; + this.ws.onclose = this.callbacks.onclose; + this.ws.onmessage = this.callbacks.onmessage; + } + send(message) { + if (this.ws === undefined) { + throw new Error('WebSocket is not connected'); + } + this.ws.send(message); + } + close() { + if (this.ws === undefined) { + throw new Error('WebSocket is not connected'); + } + this.ws.close(); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listTuningJobsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function tuningExampleToMldev(fromObject) { + const toObject = {}; + const fromTextInput = getValueByPath(fromObject, ['textInput']); + if (fromTextInput != null) { + setValueByPath(toObject, ['textInput'], fromTextInput); + } + const fromOutput = getValueByPath(fromObject, ['output']); + if (fromOutput != null) { + setValueByPath(toObject, ['output'], fromOutput); + } + return toObject; +} +function tuningDatasetToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['vertexDatasetResource']) !== undefined) { + throw new Error('vertexDatasetResource parameter is not supported in Gemini API.'); + } + const fromExamples = getValueByPath(fromObject, ['examples']); + if (fromExamples != null) { + let transformedList = fromExamples; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningExampleToMldev(item); + }); + } + setValueByPath(toObject, ['examples', 'examples'], transformedList); + } + return toObject; +} +function createTuningJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['validationDataset']) !== undefined) { + throw new Error('validationDataset parameter is not supported in Gemini API.'); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromTunedModelDisplayName); + } + if (getValueByPath(fromObject, ['description']) !== undefined) { + throw new Error('description parameter is not supported in Gemini API.'); + } + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (fromLearningRateMultiplier != null) { + setValueByPath(toObject, ['tuningTask', 'hyperparameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + if (getValueByPath(fromObject, ['exportLastCheckpointOnly']) !== + undefined) { + throw new Error('exportLastCheckpointOnly parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['preTunedModelCheckpointId']) !== + undefined) { + throw new Error('preTunedModelCheckpointId parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['adapterSize']) !== undefined) { + throw new Error('adapterSize parameter is not supported in Gemini API.'); + } + const fromBatchSize = getValueByPath(fromObject, ['batchSize']); + if (parentObject !== undefined && fromBatchSize != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'batchSize'], fromBatchSize); + } + const fromLearningRate = getValueByPath(fromObject, ['learningRate']); + if (parentObject !== undefined && fromLearningRate != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'learningRate'], fromLearningRate); + } + return toObject; +} +function createTuningJobParametersPrivateToMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + setValueByPath(toObject, ['tuningTask', 'trainingData'], tuningDatasetToMldev(fromTrainingDataset)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createTuningJobConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listTuningJobsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function tuningDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (parentObject !== undefined && fromGcsUri != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + if (getValueByPath(fromObject, ['examples']) !== undefined) { + throw new Error('examples parameter is not supported in Vertex AI.'); + } + return toObject; +} +function tuningValidationDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['validationDatasetUri'], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + return toObject; +} +function createTuningJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromValidationDataset = getValueByPath(fromObject, [ + 'validationDataset', + ]); + if (parentObject !== undefined && fromValidationDataset != null) { + setValueByPath(parentObject, ['supervisedTuningSpec'], tuningValidationDatasetToVertex(fromValidationDataset, toObject)); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (parentObject !== undefined && fromLearningRateMultiplier != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + const fromExportLastCheckpointOnly = getValueByPath(fromObject, [ + 'exportLastCheckpointOnly', + ]); + if (parentObject !== undefined && fromExportLastCheckpointOnly != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'exportLastCheckpointOnly'], fromExportLastCheckpointOnly); + } + const fromPreTunedModelCheckpointId = getValueByPath(fromObject, [ + 'preTunedModelCheckpointId', + ]); + if (fromPreTunedModelCheckpointId != null) { + setValueByPath(toObject, ['preTunedModel', 'checkpointId'], fromPreTunedModelCheckpointId); + } + const fromAdapterSize = getValueByPath(fromObject, ['adapterSize']); + if (parentObject !== undefined && fromAdapterSize != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'], fromAdapterSize); + } + if (getValueByPath(fromObject, ['batchSize']) !== undefined) { + throw new Error('batchSize parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['learningRate']) !== undefined) { + throw new Error('learningRate parameter is not supported in Vertex AI.'); + } + return toObject; +} +function createTuningJobParametersPrivateToVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + setValueByPath(toObject, ['supervisedTuningSpec', 'trainingDatasetUri'], tuningDatasetToVertex(fromTrainingDataset, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createTuningJobConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function tunedModelFromMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['name']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ['name']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + return toObject; +} +function tuningJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, [ + 'tuningTask', + 'startTime', + ]); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'tuningTask', + 'completeTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['_self']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], tunedModelFromMldev(fromTunedModel)); + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel); + } + const fromExperiment = getValueByPath(fromObject, ['experiment']); + if (fromExperiment != null) { + setValueByPath(toObject, ['experiment'], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (fromOutputUri != null) { + setValueByPath(toObject, ['outputUri'], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject, ['pipelineJob']); + if (fromPipelineJob != null) { + setValueByPath(toObject, ['pipelineJob'], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject, [ + 'serviceAccount', + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ['serviceAccount'], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + return toObject; +} +function listTuningJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ['tunedModels']); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromMldev(item); + }); + } + setValueByPath(toObject, ['tuningJobs'], transformedList); + } + return toObject; +} +function tuningOperationFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + return toObject; +} +function tunedModelCheckpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ['checkpointId']); + if (fromCheckpointId != null) { + setValueByPath(toObject, ['checkpointId'], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ['epoch']); + if (fromEpoch != null) { + setValueByPath(toObject, ['epoch'], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ['step']); + if (fromStep != null) { + setValueByPath(toObject, ['step'], fromStep); + } + const fromEndpoint = getValueByPath(fromObject, ['endpoint']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + return toObject; +} +function tunedModelFromVertex(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ['endpoint']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + const fromCheckpoints = getValueByPath(fromObject, ['checkpoints']); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tunedModelCheckpointFromVertex(item); + }); + } + setValueByPath(toObject, ['checkpoints'], transformedList); + } + return toObject; +} +function tuningJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['tunedModel']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], tunedModelFromVertex(fromTunedModel)); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromSupervisedTuningSpec = getValueByPath(fromObject, [ + 'supervisedTuningSpec', + ]); + if (fromSupervisedTuningSpec != null) { + setValueByPath(toObject, ['supervisedTuningSpec'], fromSupervisedTuningSpec); + } + const fromTuningDataStats = getValueByPath(fromObject, [ + 'tuningDataStats', + ]); + if (fromTuningDataStats != null) { + setValueByPath(toObject, ['tuningDataStats'], fromTuningDataStats); + } + const fromEncryptionSpec = getValueByPath(fromObject, [ + 'encryptionSpec', + ]); + if (fromEncryptionSpec != null) { + setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec); + } + const fromPartnerModelTuningSpec = getValueByPath(fromObject, [ + 'partnerModelTuningSpec', + ]); + if (fromPartnerModelTuningSpec != null) { + setValueByPath(toObject, ['partnerModelTuningSpec'], fromPartnerModelTuningSpec); + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel); + } + const fromExperiment = getValueByPath(fromObject, ['experiment']); + if (fromExperiment != null) { + setValueByPath(toObject, ['experiment'], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (fromOutputUri != null) { + setValueByPath(toObject, ['outputUri'], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject, ['pipelineJob']); + if (fromPipelineJob != null) { + setValueByPath(toObject, ['pipelineJob'], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject, [ + 'serviceAccount', + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ['serviceAccount'], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + return toObject; +} +function listTuningJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ['tuningJobs']); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromVertex(item); + }); + } + setValueByPath(toObject, ['tuningJobs'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Tunings extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.get = async (params) => { + return await this.getInternal(params); + }; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_TUNING_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.tune = async (params) => { + if (this.apiClient.isVertexAI()) { + if (params.baseModel.startsWith('projects/')) { + const preTunedModel = { + tunedModelName: params.baseModel, + }; + const paramsPrivate = Object.assign(Object.assign({}, params), { preTunedModel: preTunedModel }); + paramsPrivate.baseModel = undefined; + return await this.tuneInternal(paramsPrivate); + } + else { + const paramsPrivate = Object.assign({}, params); + return await this.tuneInternal(paramsPrivate); + } + } + else { + const paramsPrivate = Object.assign({}, params); + const operation = await this.tuneMldevInternal(paramsPrivate); + let tunedModelName = ''; + if (operation['metadata'] !== undefined && + operation['metadata']['tunedModel'] !== undefined) { + tunedModelName = operation['metadata']['tunedModel']; + } + else if (operation['name'] !== undefined && + operation['name'].includes('/operations/')) { + tunedModelName = operation['name'].split('/operations/')[0]; + } + const tuningJob = { + name: tunedModelName, + state: JobState.JOB_STATE_QUEUED, + }; + return tuningJob; + } + }; + } + async getInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getTuningJobParametersToVertex(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getTuningJobParametersToMldev(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listTuningJobsParametersToVertex(params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromVertex(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listTuningJobsParametersToMldev(params); + path = formatMap('tunedModels', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromMldev(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async tuneInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createTuningJobParametersPrivateToVertex(params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + async tuneMldevInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createTuningJobParametersPrivateToMldev(params); + path = formatMap('tunedModels', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningOperationFromMldev(apiResponse); + return resp; + }); + } + } +} + +const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes +const MAX_RETRY_COUNT = 3; +const INITIAL_RETRY_DELAY_MS = 1000; +const DELAY_MULTIPLIER = 2; +const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status'; +async function uploadBlob(file, uploadUrl, apiClient) { + var _a, _b, _c; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = 'upload'; + fileSize = file.size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + const chunk = file.slice(offset, offset + chunkSize); + if (offset + chunkSize >= fileSize) { + uploadCommand += ', finalize'; + } + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: '', + body: chunk, + httpMethod: 'POST', + httpOptions: { + apiVersion: '', + baseUrl: uploadUrl, + headers: { + 'X-Goog-Upload-Command': uploadCommand, + 'X-Goog-Upload-Offset': String(offset), + 'Content-Length': String(chunkSize), + }, + }, + }); + if ((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += chunkSize; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'active') { + break; + } + // TODO(b/401391430) Investigate why the upload status is not finalized + // even though all content has been uploaded. + if (fileSize <= offset) { + throw new Error('All content has been uploaded, but the upload status is not finalized.'); + } + } + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_c = response === null || response === void 0 ? void 0 : response.headers) === null || _c === void 0 ? void 0 : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + return responseJson['file']; +} +async function getBlobStat(file) { + const fileStat = { size: file.size, type: file.type }; + return fileStat; +} +function sleep(ms) { + return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeUploader { + async stat(file) { + const fileStat = { size: 0, type: undefined }; + if (typeof file === 'string') { + const originalStat = await fs.stat(file); + fileStat.size = originalStat.size; + fileStat.type = this.inferMimeType(file); + return fileStat; + } + else { + return await getBlobStat(file); + } + } + async upload(file, uploadUrl, apiClient) { + if (typeof file === 'string') { + return await this.uploadFileFromPath(file, uploadUrl, apiClient); + } + else { + return uploadBlob(file, uploadUrl, apiClient); + } + } + /** + * Infers the MIME type of a file based on its extension. + * + * @param filePath The path to the file. + * @returns The MIME type of the file, or undefined if it cannot be inferred. + */ + inferMimeType(filePath) { + // Get the file extension. + const fileExtension = filePath.slice(filePath.lastIndexOf('.') + 1); + // Create a map of file extensions to MIME types. + const mimeTypes = { + 'aac': 'audio/aac', + 'abw': 'application/x-abiword', + 'arc': 'application/x-freearc', + 'avi': 'video/x-msvideo', + 'azw': 'application/vnd.amazon.ebook', + 'bin': 'application/octet-stream', + 'bmp': 'image/bmp', + 'bz': 'application/x-bzip', + 'bz2': 'application/x-bzip2', + 'csh': 'application/x-csh', + 'css': 'text/css', + 'csv': 'text/csv', + 'doc': 'application/msword', + 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'eot': 'application/vnd.ms-fontobject', + 'epub': 'application/epub+zip', + 'gz': 'application/gzip', + 'gif': 'image/gif', + 'htm': 'text/html', + 'html': 'text/html', + 'ico': 'image/vnd.microsoft.icon', + 'ics': 'text/calendar', + 'jar': 'application/java-archive', + 'jpeg': 'image/jpeg', + 'jpg': 'image/jpeg', + 'js': 'text/javascript', + 'json': 'application/json', + 'jsonld': 'application/ld+json', + 'kml': 'application/vnd.google-earth.kml+xml', + 'kmz': 'application/vnd.google-earth.kmz+xml', + 'mjs': 'text/javascript', + 'mp3': 'audio/mpeg', + 'mp4': 'video/mp4', + 'mpeg': 'video/mpeg', + 'mpkg': 'application/vnd.apple.installer+xml', + 'odt': 'application/vnd.oasis.opendocument.text', + 'oga': 'audio/ogg', + 'ogv': 'video/ogg', + 'ogx': 'application/ogg', + 'opus': 'audio/opus', + 'otf': 'font/otf', + 'png': 'image/png', + 'pdf': 'application/pdf', + 'php': 'application/x-httpd-php', + 'ppt': 'application/vnd.ms-powerpoint', + 'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'rar': 'application/vnd.rar', + 'rtf': 'application/rtf', + 'sh': 'application/x-sh', + 'svg': 'image/svg+xml', + 'swf': 'application/x-shockwave-flash', + 'tar': 'application/x-tar', + 'tif': 'image/tiff', + 'tiff': 'image/tiff', + 'ts': 'video/mp2t', + 'ttf': 'font/ttf', + 'txt': 'text/plain', + 'vsd': 'application/vnd.visio', + 'wav': 'audio/wav', + 'weba': 'audio/webm', + 'webm': 'video/webm', + 'webp': 'image/webp', + 'woff': 'font/woff', + 'woff2': 'font/woff2', + 'xhtml': 'application/xhtml+xml', + 'xls': 'application/vnd.ms-excel', + 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xml': 'application/xml', + 'xul': 'application/vnd.mozilla.xul+xml', + 'zip': 'application/zip', + '3gp': 'video/3gpp', + '3g2': 'video/3gpp2', + '7z': 'application/x-7z-compressed', + }; + // Look up the MIME type based on the file extension. + const mimeType = mimeTypes[fileExtension.toLowerCase()]; + // Return the MIME type. + return mimeType; + } + async uploadFileFromPath(file, uploadUrl, apiClient) { + var _a, _b, _c; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = 'upload'; + let fileHandle; + try { + fileHandle = await fs.open(file, 'r'); + if (!fileHandle) { + throw new Error(`Failed to open file`); + } + fileSize = (await fileHandle.stat()).size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + if (offset + chunkSize >= fileSize) { + uploadCommand += ', finalize'; + } + const buffer = new Uint8Array(chunkSize); + const { bytesRead: bytesRead } = await fileHandle.read(buffer, 0, chunkSize, offset); + if (bytesRead !== chunkSize) { + throw new Error(`Failed to read ${chunkSize} bytes from file at offset ${offset}. bytes actually read: ${bytesRead}`); + } + const chunk = new Blob([buffer]); + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: '', + body: chunk, + httpMethod: 'POST', + httpOptions: { + apiVersion: '', + baseUrl: uploadUrl, + headers: { + 'X-Goog-Upload-Command': uploadCommand, + 'X-Goog-Upload-Offset': String(offset), + 'Content-Length': String(bytesRead), + }, + }, + }); + if ((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += bytesRead; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'active') { + break; + } + if (fileSize <= offset) { + throw new Error('All content has been uploaded, but the upload status is not finalized.'); + } + } + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_c = response === null || response === void 0 ? void 0 : response.headers) === null || _c === void 0 ? void 0 : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + return responseJson['file']; + } + finally { + // Ensure the file handle is always closed + if (fileHandle) { + await fileHandle.close(); + } + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const LANGUAGE_LABEL_PREFIX = 'gl-node/'; +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link + * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or + * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI + * API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API + * services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be + * set. When using Vertex AI, both {@link GoogleGenAIOptions.project} and {@link + * GoogleGenAIOptions.location} must be set, or a {@link + * GoogleGenAIOptions.apiKey} must be set when using Express Mode. + * + * Explicitly passed in values in {@link GoogleGenAIOptions} will always take + * precedence over environment variables. If both project/location and api_key + * exist in the environment variables, the project/location will be used. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +class GoogleGenAI { + constructor(options) { + var _a, _b, _c, _d, _e, _f; + // Validate explicitly set initializer values. + if ((options.project || options.location) && options.apiKey) { + throw new Error('Project/location and API key are mutually exclusive in the client initializer.'); + } + this.vertexai = + (_b = (_a = options.vertexai) !== null && _a !== void 0 ? _a : getBooleanEnv('GOOGLE_GENAI_USE_VERTEXAI')) !== null && _b !== void 0 ? _b : false; + const envApiKey = getApiKeyFromEnv(); + const envProject = getEnv('GOOGLE_CLOUD_PROJECT'); + const envLocation = getEnv('GOOGLE_CLOUD_LOCATION'); + this.apiKey = (_c = options.apiKey) !== null && _c !== void 0 ? _c : envApiKey; + this.project = (_d = options.project) !== null && _d !== void 0 ? _d : envProject; + this.location = (_e = options.location) !== null && _e !== void 0 ? _e : envLocation; + // Handle when to use Vertex AI in express mode (api key) + if (options.vertexai) { + if ((_f = options.googleAuthOptions) === null || _f === void 0 ? void 0 : _f.credentials) { + // Explicit credentials take precedence over implicit api_key. + console.debug('The user provided Google Cloud credentials will take precedence' + + ' over the API key from the environment variable.'); + this.apiKey = undefined; + } + // Explicit api_key and explicit project/location already handled above. + if ((envProject || envLocation) && options.apiKey) { + // Explicit api_key takes precedence over implicit project/location. + console.debug('The user provided Vertex AI API key will take precedence over' + + ' the project/location from the environment variables.'); + this.project = undefined; + this.location = undefined; + } + else if ((options.project || options.location) && envApiKey) { + // Explicit project/location takes precedence over implicit api_key. + console.debug('The user provided project/location will take precedence over' + + ' the API key from the environment variables.'); + this.apiKey = undefined; + } + else if ((envProject || envLocation) && envApiKey) { + // Implicit project/location takes precedence over implicit api_key. + console.debug('The project/location from the environment variables will take' + + ' precedence over the API key from the environment variables.'); + this.apiKey = undefined; + } + } + const baseUrl = getBaseUrl(options.httpOptions, options.vertexai, getEnv('GOOGLE_VERTEX_BASE_URL'), getEnv('GOOGLE_GEMINI_BASE_URL')); + if (baseUrl) { + if (options.httpOptions) { + options.httpOptions.baseUrl = baseUrl; + } + else { + options.httpOptions = { baseUrl: baseUrl }; + } + } + this.apiVersion = options.apiVersion; + const auth = new NodeAuth({ + apiKey: this.apiKey, + googleAuthOptions: options.googleAuthOptions, + }); + this.apiClient = new ApiClient({ + auth: auth, + project: this.project, + location: this.location, + apiVersion: this.apiVersion, + apiKey: this.apiKey, + vertexai: this.vertexai, + httpOptions: options.httpOptions, + userAgentExtra: LANGUAGE_LABEL_PREFIX + process.version, + uploader: new NodeUploader(), + downloader: new NodeDownloader(), + }); + this.models = new Models(this.apiClient); + this.live = new Live(this.apiClient, auth, new NodeWebSocketFactory()); + this.batches = new Batches(this.apiClient); + this.chats = new Chats(this.models, this.apiClient); + this.caches = new Caches(this.apiClient); + this.files = new Files(this.apiClient); + this.operations = new Operations(this.apiClient); + this.authTokens = new Tokens(this.apiClient); + this.tunings = new Tunings(this.apiClient); + } +} +function getEnv(env) { + var _a, _b, _c; + return (_c = (_b = (_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a[env]) === null || _b === void 0 ? void 0 : _b.trim()) !== null && _c !== void 0 ? _c : undefined; +} +function getBooleanEnv(env) { + return stringToBoolean(getEnv(env)); +} +function stringToBoolean(str) { + if (str === undefined) { + return false; + } + return str.toLowerCase() === 'true'; +} +function getApiKeyFromEnv() { + const envGoogleApiKey = getEnv('GOOGLE_API_KEY'); + const envGeminiApiKey = getEnv('GEMINI_API_KEY'); + if (envGoogleApiKey && envGeminiApiKey) { + console.warn('Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY.'); + } + return envGoogleApiKey || envGeminiApiKey; +} + +export { ActivityHandling, AdapterSize, ApiError, ApiSpec, AuthType, Batches, Behavior, BlockedReason, Caches, Chat, Chats, ComputeTokensResponse, ControlReferenceImage, ControlReferenceType, CountTokensResponse, CreateFileResponse, DeleteCachedContentResponse, DeleteFileResponse, DeleteModelResponse, DynamicRetrievalConfigMode, EditImageResponse, EditMode, EmbedContentResponse, EndSensitivity, Environment, FeatureSelectionPreference, FileSource, FileState, Files, FinishReason, FunctionCallingConfigMode, FunctionResponse, FunctionResponseScheduling, GenerateContentResponse, GenerateContentResponsePromptFeedback, GenerateContentResponseUsageMetadata, GenerateImagesResponse, GenerateVideosOperation, GenerateVideosResponse, GoogleGenAI, HarmBlockMethod, HarmBlockThreshold, HarmCategory, HarmProbability, HarmSeverity, HttpResponse, ImagePromptLanguage, InlinedResponse, JobState, Language, ListBatchJobsResponse, ListCachedContentsResponse, ListFilesResponse, ListModelsResponse, ListTuningJobsResponse, Live, LiveClientToolResponse, LiveMusicPlaybackControl, LiveMusicServerMessage, LiveSendToolResponseParameters, LiveServerMessage, MaskReferenceImage, MaskReferenceMode, MediaModality, MediaResolution, Modality, Mode, Models, MusicGenerationMode, Operations, Outcome, PagedItem, Pager, PersonGeneration, RawReferenceImage, RecontextImageResponse, ReplayResponse, SafetyFilterLevel, Scale, SegmentImageResponse, SegmentMode, Session, StartSensitivity, StyleReferenceImage, SubjectReferenceImage, SubjectReferenceType, Tokens, TrafficType, TuningMode, TurnCoverage, Type, UpscaleImageResponse, UrlRetrievalStatus, VideoCompressionQuality, createModelContent, createPartFromBase64, createPartFromCodeExecutionResult, createPartFromExecutableCode, createPartFromFunctionCall, createPartFromFunctionResponse, createPartFromText, createPartFromUri, createUserContent, mcpToTool, setDefaultBaseUrls }; +//# sourceMappingURL=index.mjs.map diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/node/index.mjs.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/node/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..a18bbb138726c0448645367958e04a4c56975e00 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/node/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sources":["../../src/_base_url.ts","../../src/_common.ts","../../src/_base_transformers.ts","../../src/types.ts","../../src/_transformers.ts","../../src/converters/_batches_converters.ts","../../src/pagers.ts","../../src/batches.ts","../../src/converters/_caches_converters.ts","../../src/caches.ts","../../src/chats.ts","../../src/errors.ts","../../src/converters/_files_converters.ts","../../src/files.ts","../../src/converters/_live_converters.ts","../../src/converters/_models_converters.ts","../../src/_api_client.ts","../../src/mcp/_mcp.ts","../../src/music.ts","../../src/live.ts","../../src/_afc.ts","../../src/models.ts","../../src/converters/_operations_converters.ts","../../src/operations.ts","../../src/converters/_tokens_converters.ts","../../src/tokens.ts","../../src/node/_node_auth.ts","../../src/node/_node_downloader.ts","../../src/node/_node_websocket.ts","../../src/converters/_tunings_converters.ts","../../src/tunings.ts","../../src/cross/_cross_uploader.ts","../../src/node/_node_uploader.ts","../../src/node/node_client.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {HttpOptions} from './types.js';\n\nlet _defaultBaseGeminiUrl: string | undefined = undefined;\nlet _defaultBaseVertexUrl: string | undefined = undefined;\n\n/**\n * Parameters for setting the base URLs for the Gemini API and Vertex AI API.\n */\nexport interface BaseUrlParameters {\n geminiUrl?: string;\n vertexUrl?: string;\n}\n\n/**\n * Overrides the base URLs for the Gemini API and Vertex AI API.\n *\n * @remarks This function should be called before initializing the SDK. If the\n * base URLs are set after initializing the SDK, the base URLs will not be\n * updated. Base URLs provided in the HttpOptions will also take precedence over\n * URLs set here.\n *\n * @example\n * ```ts\n * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai';\n * // Override the base URL for the Gemini API.\n * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'});\n *\n * // Override the base URL for the Vertex AI API.\n * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'});\n *\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n */\nexport function setDefaultBaseUrls(baseUrlParams: BaseUrlParameters) {\n _defaultBaseGeminiUrl = baseUrlParams.geminiUrl;\n _defaultBaseVertexUrl = baseUrlParams.vertexUrl;\n}\n\n/**\n * Returns the default base URLs for the Gemini API and Vertex AI API.\n */\nexport function getDefaultBaseUrls(): BaseUrlParameters {\n return {\n geminiUrl: _defaultBaseGeminiUrl,\n vertexUrl: _defaultBaseVertexUrl,\n };\n}\n\n/**\n * Returns the default base URL based on the following priority:\n * 1. Base URLs set via HttpOptions.\n * 2. Base URLs set via the latest call to setDefaultBaseUrls.\n * 3. Base URLs set via environment variables.\n */\nexport function getBaseUrl(\n httpOptions: HttpOptions | undefined,\n vertexai: boolean | undefined,\n vertexBaseUrlFromEnv: string | undefined,\n geminiBaseUrlFromEnv: string | undefined,\n): string | undefined {\n if (!httpOptions?.baseUrl) {\n const defaultBaseUrls = getDefaultBaseUrls();\n if (vertexai) {\n return defaultBaseUrls.vertexUrl ?? vertexBaseUrlFromEnv;\n } else {\n return defaultBaseUrls.geminiUrl ?? geminiBaseUrlFromEnv;\n }\n }\n\n return httpOptions.baseUrl;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport class BaseModule {}\n\nexport function formatMap(\n templateString: string,\n valueMap: Record,\n): string {\n // Use a regular expression to find all placeholders in the template string\n const regex = /\\{([^}]+)\\}/g;\n\n // Replace each placeholder with its corresponding value from the valueMap\n return templateString.replace(regex, (match, key) => {\n if (Object.prototype.hasOwnProperty.call(valueMap, key)) {\n const value = valueMap[key];\n // Convert the value to a string if it's not a string already\n return value !== undefined && value !== null ? String(value) : '';\n } else {\n // Handle missing keys\n throw new Error(`Key '${key}' not found in valueMap.`);\n }\n });\n}\n\nexport function setValueByPath(\n data: Record,\n keys: string[],\n value: unknown,\n): void {\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (!(keyName in data)) {\n if (Array.isArray(value)) {\n data[keyName] = Array.from({length: value.length}, () => ({}));\n } else {\n throw new Error(`Value must be a list given an array path ${key}`);\n }\n }\n\n if (Array.isArray(data[keyName])) {\n const arrayData = data[keyName] as Array;\n\n if (Array.isArray(value)) {\n for (let j = 0; j < arrayData.length; j++) {\n const entry = arrayData[j] as Record;\n setValueByPath(entry, keys.slice(i + 1), value[j]);\n }\n } else {\n for (const d of arrayData) {\n setValueByPath(\n d as Record,\n keys.slice(i + 1),\n value,\n );\n }\n }\n }\n return;\n } else if (key.endsWith('[0]')) {\n const keyName = key.slice(0, -3);\n if (!(keyName in data)) {\n data[keyName] = [{}];\n }\n const arrayData = (data as Record)[keyName];\n setValueByPath(\n (arrayData as Array>)[0],\n keys.slice(i + 1),\n value,\n );\n return;\n }\n\n if (!data[key] || typeof data[key] !== 'object') {\n data[key] = {};\n }\n\n data = data[key] as Record;\n }\n\n const keyToSet = keys[keys.length - 1];\n const existingData = data[keyToSet];\n\n if (existingData !== undefined) {\n if (\n !value ||\n (typeof value === 'object' && Object.keys(value).length === 0)\n ) {\n return;\n }\n\n if (value === existingData) {\n return;\n }\n\n if (\n typeof existingData === 'object' &&\n typeof value === 'object' &&\n existingData !== null &&\n value !== null\n ) {\n Object.assign(existingData, value);\n } else {\n throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`);\n }\n } else {\n data[keyToSet] = value;\n }\n}\n\nexport function getValueByPath(data: unknown, keys: string[]): unknown {\n try {\n if (keys.length === 1 && keys[0] === '_self') {\n return data;\n }\n\n for (let i = 0; i < keys.length; i++) {\n if (typeof data !== 'object' || data === null) {\n return undefined;\n }\n\n const key = keys[i];\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (keyName in data) {\n const arrayData = (data as Record)[keyName];\n if (!Array.isArray(arrayData)) {\n return undefined;\n }\n return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1)));\n } else {\n return undefined;\n }\n } else {\n data = (data as Record)[key];\n }\n }\n\n return data;\n } catch (error) {\n if (error instanceof TypeError) {\n return undefined;\n }\n throw error;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function tBytes(fromBytes: string | unknown): string {\n if (typeof fromBytes !== 'string') {\n throw new Error('fromImageBytes must be a string');\n }\n // TODO(b/389133914): Remove dummy bytes converter.\n return fromBytes;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {tBytes} from './_base_transformers.js';\nimport type {ReferenceImageAPIInternal} from './_internal_types.js';\n\n/** Required. Outcome of the code execution. */\nexport enum Outcome {\n /**\n * Unspecified status. This value should not be used.\n */\n OUTCOME_UNSPECIFIED = 'OUTCOME_UNSPECIFIED',\n /**\n * Code execution completed successfully.\n */\n OUTCOME_OK = 'OUTCOME_OK',\n /**\n * Code execution finished but with a failure. `stderr` should contain the reason.\n */\n OUTCOME_FAILED = 'OUTCOME_FAILED',\n /**\n * Code execution ran for too long, and was cancelled. There may or may not be a partial output present.\n */\n OUTCOME_DEADLINE_EXCEEDED = 'OUTCOME_DEADLINE_EXCEEDED',\n}\n\n/** Required. Programming language of the `code`. */\nexport enum Language {\n /**\n * Unspecified language. This value should not be used.\n */\n LANGUAGE_UNSPECIFIED = 'LANGUAGE_UNSPECIFIED',\n /**\n * Python >= 3.10, with numpy and simpy available.\n */\n PYTHON = 'PYTHON',\n}\n\n/** Optional. The type of the data. */\nexport enum Type {\n /**\n * Not specified, should not be used.\n */\n TYPE_UNSPECIFIED = 'TYPE_UNSPECIFIED',\n /**\n * OpenAPI string type\n */\n STRING = 'STRING',\n /**\n * OpenAPI number type\n */\n NUMBER = 'NUMBER',\n /**\n * OpenAPI integer type\n */\n INTEGER = 'INTEGER',\n /**\n * OpenAPI boolean type\n */\n BOOLEAN = 'BOOLEAN',\n /**\n * OpenAPI array type\n */\n ARRAY = 'ARRAY',\n /**\n * OpenAPI object type\n */\n OBJECT = 'OBJECT',\n /**\n * Null type\n */\n NULL = 'NULL',\n}\n\n/** Required. Harm category. */\nexport enum HarmCategory {\n /**\n * The harm category is unspecified.\n */\n HARM_CATEGORY_UNSPECIFIED = 'HARM_CATEGORY_UNSPECIFIED',\n /**\n * The harm category is hate speech.\n */\n HARM_CATEGORY_HATE_SPEECH = 'HARM_CATEGORY_HATE_SPEECH',\n /**\n * The harm category is dangerous content.\n */\n HARM_CATEGORY_DANGEROUS_CONTENT = 'HARM_CATEGORY_DANGEROUS_CONTENT',\n /**\n * The harm category is harassment.\n */\n HARM_CATEGORY_HARASSMENT = 'HARM_CATEGORY_HARASSMENT',\n /**\n * The harm category is sexually explicit content.\n */\n HARM_CATEGORY_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_SEXUALLY_EXPLICIT',\n /**\n * Deprecated: Election filter is not longer supported. The harm category is civic integrity.\n */\n HARM_CATEGORY_CIVIC_INTEGRITY = 'HARM_CATEGORY_CIVIC_INTEGRITY',\n /**\n * The harm category is image hate.\n */\n HARM_CATEGORY_IMAGE_HATE = 'HARM_CATEGORY_IMAGE_HATE',\n /**\n * The harm category is image dangerous content.\n */\n HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT = 'HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT',\n /**\n * The harm category is image harassment.\n */\n HARM_CATEGORY_IMAGE_HARASSMENT = 'HARM_CATEGORY_IMAGE_HARASSMENT',\n /**\n * The harm category is image sexually explicit content.\n */\n HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT',\n}\n\n/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */\nexport enum HarmBlockMethod {\n /**\n * The harm block method is unspecified.\n */\n HARM_BLOCK_METHOD_UNSPECIFIED = 'HARM_BLOCK_METHOD_UNSPECIFIED',\n /**\n * The harm block method uses both probability and severity scores.\n */\n SEVERITY = 'SEVERITY',\n /**\n * The harm block method uses the probability score.\n */\n PROBABILITY = 'PROBABILITY',\n}\n\n/** Required. The harm block threshold. */\nexport enum HarmBlockThreshold {\n /**\n * Unspecified harm block threshold.\n */\n HARM_BLOCK_THRESHOLD_UNSPECIFIED = 'HARM_BLOCK_THRESHOLD_UNSPECIFIED',\n /**\n * Block low threshold and above (i.e. block more).\n */\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n /**\n * Block medium threshold and above.\n */\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n /**\n * Block only high threshold (i.e. block less).\n */\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n /**\n * Block none.\n */\n BLOCK_NONE = 'BLOCK_NONE',\n /**\n * Turn off the safety filter.\n */\n OFF = 'OFF',\n}\n\n/** The mode of the predictor to be used in dynamic retrieval. */\nexport enum Mode {\n /**\n * Always trigger retrieval.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Run retrieval only when system decides it is necessary.\n */\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\n/** Type of auth scheme. */\nexport enum AuthType {\n AUTH_TYPE_UNSPECIFIED = 'AUTH_TYPE_UNSPECIFIED',\n /**\n * No Auth.\n */\n NO_AUTH = 'NO_AUTH',\n /**\n * API Key Auth.\n */\n API_KEY_AUTH = 'API_KEY_AUTH',\n /**\n * HTTP Basic Auth.\n */\n HTTP_BASIC_AUTH = 'HTTP_BASIC_AUTH',\n /**\n * Google Service Account Auth.\n */\n GOOGLE_SERVICE_ACCOUNT_AUTH = 'GOOGLE_SERVICE_ACCOUNT_AUTH',\n /**\n * OAuth auth.\n */\n OAUTH = 'OAUTH',\n /**\n * OpenID Connect (OIDC) Auth.\n */\n OIDC_AUTH = 'OIDC_AUTH',\n}\n\n/** The API spec that the external API implements. */\nexport enum ApiSpec {\n /**\n * Unspecified API spec. This value should not be used.\n */\n API_SPEC_UNSPECIFIED = 'API_SPEC_UNSPECIFIED',\n /**\n * Simple search API spec.\n */\n SIMPLE_SEARCH = 'SIMPLE_SEARCH',\n /**\n * Elastic search API spec.\n */\n ELASTIC_SEARCH = 'ELASTIC_SEARCH',\n}\n\n/** Status of the url retrieval. */\nexport enum UrlRetrievalStatus {\n /**\n * Default value. This value is unused\n */\n URL_RETRIEVAL_STATUS_UNSPECIFIED = 'URL_RETRIEVAL_STATUS_UNSPECIFIED',\n /**\n * Url retrieval is successful.\n */\n URL_RETRIEVAL_STATUS_SUCCESS = 'URL_RETRIEVAL_STATUS_SUCCESS',\n /**\n * Url retrieval is failed due to error.\n */\n URL_RETRIEVAL_STATUS_ERROR = 'URL_RETRIEVAL_STATUS_ERROR',\n /**\n * Url retrieval is failed because the content is behind paywall.\n */\n URL_RETRIEVAL_STATUS_PAYWALL = 'URL_RETRIEVAL_STATUS_PAYWALL',\n /**\n * Url retrieval is failed because the content is unsafe.\n */\n URL_RETRIEVAL_STATUS_UNSAFE = 'URL_RETRIEVAL_STATUS_UNSAFE',\n}\n\n/** Output only. The reason why the model stopped generating tokens.\n\n If empty, the model has not stopped generating the tokens.\n */\nexport enum FinishReason {\n /**\n * The finish reason is unspecified.\n */\n FINISH_REASON_UNSPECIFIED = 'FINISH_REASON_UNSPECIFIED',\n /**\n * Token generation reached a natural stopping point or a configured stop sequence.\n */\n STOP = 'STOP',\n /**\n * Token generation reached the configured maximum output tokens.\n */\n MAX_TOKENS = 'MAX_TOKENS',\n /**\n * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output.\n */\n SAFETY = 'SAFETY',\n /**\n * The token generation stopped because of potential recitation.\n */\n RECITATION = 'RECITATION',\n /**\n * The token generation stopped because of using an unsupported language.\n */\n LANGUAGE = 'LANGUAGE',\n /**\n * All other reasons that stopped the token generation.\n */\n OTHER = 'OTHER',\n /**\n * Token generation stopped because the content contains forbidden terms.\n */\n BLOCKLIST = 'BLOCKLIST',\n /**\n * Token generation stopped for potentially containing prohibited content.\n */\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n /**\n * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII).\n */\n SPII = 'SPII',\n /**\n * The function call generated by the model is invalid.\n */\n MALFORMED_FUNCTION_CALL = 'MALFORMED_FUNCTION_CALL',\n /**\n * Token generation stopped because generated images have safety violations.\n */\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n /**\n * The tool call generated by the model is invalid.\n */\n UNEXPECTED_TOOL_CALL = 'UNEXPECTED_TOOL_CALL',\n}\n\n/** Output only. Harm probability levels in the content. */\nexport enum HarmProbability {\n /**\n * Harm probability unspecified.\n */\n HARM_PROBABILITY_UNSPECIFIED = 'HARM_PROBABILITY_UNSPECIFIED',\n /**\n * Negligible level of harm.\n */\n NEGLIGIBLE = 'NEGLIGIBLE',\n /**\n * Low level of harm.\n */\n LOW = 'LOW',\n /**\n * Medium level of harm.\n */\n MEDIUM = 'MEDIUM',\n /**\n * High level of harm.\n */\n HIGH = 'HIGH',\n}\n\n/** Output only. Harm severity levels in the content. */\nexport enum HarmSeverity {\n /**\n * Harm severity unspecified.\n */\n HARM_SEVERITY_UNSPECIFIED = 'HARM_SEVERITY_UNSPECIFIED',\n /**\n * Negligible level of harm severity.\n */\n HARM_SEVERITY_NEGLIGIBLE = 'HARM_SEVERITY_NEGLIGIBLE',\n /**\n * Low level of harm severity.\n */\n HARM_SEVERITY_LOW = 'HARM_SEVERITY_LOW',\n /**\n * Medium level of harm severity.\n */\n HARM_SEVERITY_MEDIUM = 'HARM_SEVERITY_MEDIUM',\n /**\n * High level of harm severity.\n */\n HARM_SEVERITY_HIGH = 'HARM_SEVERITY_HIGH',\n}\n\n/** Output only. Blocked reason. */\nexport enum BlockedReason {\n /**\n * Unspecified blocked reason.\n */\n BLOCKED_REASON_UNSPECIFIED = 'BLOCKED_REASON_UNSPECIFIED',\n /**\n * Candidates blocked due to safety.\n */\n SAFETY = 'SAFETY',\n /**\n * Candidates blocked due to other reason.\n */\n OTHER = 'OTHER',\n /**\n * Candidates blocked due to the terms which are included from the terminology blocklist.\n */\n BLOCKLIST = 'BLOCKLIST',\n /**\n * Candidates blocked due to prohibited content.\n */\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n /**\n * Candidates blocked due to unsafe image generation content.\n */\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n}\n\n/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */\nexport enum TrafficType {\n /**\n * Unspecified request traffic type.\n */\n TRAFFIC_TYPE_UNSPECIFIED = 'TRAFFIC_TYPE_UNSPECIFIED',\n /**\n * Type for Pay-As-You-Go traffic.\n */\n ON_DEMAND = 'ON_DEMAND',\n /**\n * Type for Provisioned Throughput traffic.\n */\n PROVISIONED_THROUGHPUT = 'PROVISIONED_THROUGHPUT',\n}\n\n/** Server content modalities. */\nexport enum Modality {\n /**\n * The modality is unspecified.\n */\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n /**\n * Indicates the model should return text\n */\n TEXT = 'TEXT',\n /**\n * Indicates the model should return images.\n */\n IMAGE = 'IMAGE',\n /**\n * Indicates the model should return audio.\n */\n AUDIO = 'AUDIO',\n}\n\n/** The media resolution to use. */\nexport enum MediaResolution {\n /**\n * Media resolution has not been set\n */\n MEDIA_RESOLUTION_UNSPECIFIED = 'MEDIA_RESOLUTION_UNSPECIFIED',\n /**\n * Media resolution set to low (64 tokens).\n */\n MEDIA_RESOLUTION_LOW = 'MEDIA_RESOLUTION_LOW',\n /**\n * Media resolution set to medium (256 tokens).\n */\n MEDIA_RESOLUTION_MEDIUM = 'MEDIA_RESOLUTION_MEDIUM',\n /**\n * Media resolution set to high (zoomed reframing with 256 tokens).\n */\n MEDIA_RESOLUTION_HIGH = 'MEDIA_RESOLUTION_HIGH',\n}\n\n/** Job state. */\nexport enum JobState {\n /**\n * The job state is unspecified.\n */\n JOB_STATE_UNSPECIFIED = 'JOB_STATE_UNSPECIFIED',\n /**\n * The job has been just created or resumed and processing has not yet begun.\n */\n JOB_STATE_QUEUED = 'JOB_STATE_QUEUED',\n /**\n * The service is preparing to run the job.\n */\n JOB_STATE_PENDING = 'JOB_STATE_PENDING',\n /**\n * The job is in progress.\n */\n JOB_STATE_RUNNING = 'JOB_STATE_RUNNING',\n /**\n * The job completed successfully.\n */\n JOB_STATE_SUCCEEDED = 'JOB_STATE_SUCCEEDED',\n /**\n * The job failed.\n */\n JOB_STATE_FAILED = 'JOB_STATE_FAILED',\n /**\n * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`.\n */\n JOB_STATE_CANCELLING = 'JOB_STATE_CANCELLING',\n /**\n * The job has been cancelled.\n */\n JOB_STATE_CANCELLED = 'JOB_STATE_CANCELLED',\n /**\n * The job has been stopped, and can be resumed.\n */\n JOB_STATE_PAUSED = 'JOB_STATE_PAUSED',\n /**\n * The job has expired.\n */\n JOB_STATE_EXPIRED = 'JOB_STATE_EXPIRED',\n /**\n * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state.\n */\n JOB_STATE_UPDATING = 'JOB_STATE_UPDATING',\n /**\n * The job is partially succeeded, some results may be missing due to errors.\n */\n JOB_STATE_PARTIALLY_SUCCEEDED = 'JOB_STATE_PARTIALLY_SUCCEEDED',\n}\n\n/** Tuning mode. */\nexport enum TuningMode {\n /**\n * Tuning mode is unspecified.\n */\n TUNING_MODE_UNSPECIFIED = 'TUNING_MODE_UNSPECIFIED',\n /**\n * Full fine-tuning mode.\n */\n TUNING_MODE_FULL = 'TUNING_MODE_FULL',\n /**\n * PEFT adapter tuning mode.\n */\n TUNING_MODE_PEFT_ADAPTER = 'TUNING_MODE_PEFT_ADAPTER',\n}\n\n/** Optional. Adapter size for tuning. */\nexport enum AdapterSize {\n /**\n * Adapter size is unspecified.\n */\n ADAPTER_SIZE_UNSPECIFIED = 'ADAPTER_SIZE_UNSPECIFIED',\n /**\n * Adapter size 1.\n */\n ADAPTER_SIZE_ONE = 'ADAPTER_SIZE_ONE',\n /**\n * Adapter size 2.\n */\n ADAPTER_SIZE_TWO = 'ADAPTER_SIZE_TWO',\n /**\n * Adapter size 4.\n */\n ADAPTER_SIZE_FOUR = 'ADAPTER_SIZE_FOUR',\n /**\n * Adapter size 8.\n */\n ADAPTER_SIZE_EIGHT = 'ADAPTER_SIZE_EIGHT',\n /**\n * Adapter size 16.\n */\n ADAPTER_SIZE_SIXTEEN = 'ADAPTER_SIZE_SIXTEEN',\n /**\n * Adapter size 32.\n */\n ADAPTER_SIZE_THIRTY_TWO = 'ADAPTER_SIZE_THIRTY_TWO',\n}\n\n/** Options for feature selection preference. */\nexport enum FeatureSelectionPreference {\n FEATURE_SELECTION_PREFERENCE_UNSPECIFIED = 'FEATURE_SELECTION_PREFERENCE_UNSPECIFIED',\n PRIORITIZE_QUALITY = 'PRIORITIZE_QUALITY',\n BALANCED = 'BALANCED',\n PRIORITIZE_COST = 'PRIORITIZE_COST',\n}\n\n/** Defines the function behavior. Defaults to `BLOCKING`. */\nexport enum Behavior {\n /**\n * This value is unused.\n */\n UNSPECIFIED = 'UNSPECIFIED',\n /**\n * If set, the system will wait to receive the function response before continuing the conversation.\n */\n BLOCKING = 'BLOCKING',\n /**\n * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model.\n */\n NON_BLOCKING = 'NON_BLOCKING',\n}\n\n/** Config for the dynamic retrieval config mode. */\nexport enum DynamicRetrievalConfigMode {\n /**\n * Always trigger retrieval.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Run retrieval only when system decides it is necessary.\n */\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\n/** The environment being operated. */\nexport enum Environment {\n /**\n * Defaults to browser.\n */\n ENVIRONMENT_UNSPECIFIED = 'ENVIRONMENT_UNSPECIFIED',\n /**\n * Operates in a web browser.\n */\n ENVIRONMENT_BROWSER = 'ENVIRONMENT_BROWSER',\n}\n\n/** Config for the function calling config mode. */\nexport enum FunctionCallingConfigMode {\n /**\n * The function calling config mode is unspecified. Should not be used.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Default model behavior, model decides to predict either function calls or natural language response.\n */\n AUTO = 'AUTO',\n /**\n * Model is constrained to always predicting function calls only. If \"allowed_function_names\" are set, the predicted function calls will be limited to any one of \"allowed_function_names\", else the predicted function calls will be any one of the provided \"function_declarations\".\n */\n ANY = 'ANY',\n /**\n * Model will not predict any function calls. Model behavior is same as when not passing any function declarations.\n */\n NONE = 'NONE',\n}\n\n/** Enum that controls the safety filter level for objectionable content. */\nexport enum SafetyFilterLevel {\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n BLOCK_NONE = 'BLOCK_NONE',\n}\n\n/** Enum that controls the generation of people. */\nexport enum PersonGeneration {\n /**\n * Block generation of images of people.\n */\n DONT_ALLOW = 'DONT_ALLOW',\n /**\n * Generate images of adults, but not children.\n */\n ALLOW_ADULT = 'ALLOW_ADULT',\n /**\n * Generate images that include adults and children.\n */\n ALLOW_ALL = 'ALLOW_ALL',\n}\n\n/** Enum that specifies the language of the text in the prompt. */\nexport enum ImagePromptLanguage {\n /**\n * Auto-detect the language.\n */\n auto = 'auto',\n /**\n * English\n */\n en = 'en',\n /**\n * Japanese\n */\n ja = 'ja',\n /**\n * Korean\n */\n ko = 'ko',\n /**\n * Hindi\n */\n hi = 'hi',\n /**\n * Chinese\n */\n zh = 'zh',\n /**\n * Portuguese\n */\n pt = 'pt',\n /**\n * Spanish\n */\n es = 'es',\n}\n\n/** Enum representing the mask mode of a mask reference image. */\nexport enum MaskReferenceMode {\n MASK_MODE_DEFAULT = 'MASK_MODE_DEFAULT',\n MASK_MODE_USER_PROVIDED = 'MASK_MODE_USER_PROVIDED',\n MASK_MODE_BACKGROUND = 'MASK_MODE_BACKGROUND',\n MASK_MODE_FOREGROUND = 'MASK_MODE_FOREGROUND',\n MASK_MODE_SEMANTIC = 'MASK_MODE_SEMANTIC',\n}\n\n/** Enum representing the control type of a control reference image. */\nexport enum ControlReferenceType {\n CONTROL_TYPE_DEFAULT = 'CONTROL_TYPE_DEFAULT',\n CONTROL_TYPE_CANNY = 'CONTROL_TYPE_CANNY',\n CONTROL_TYPE_SCRIBBLE = 'CONTROL_TYPE_SCRIBBLE',\n CONTROL_TYPE_FACE_MESH = 'CONTROL_TYPE_FACE_MESH',\n}\n\n/** Enum representing the subject type of a subject reference image. */\nexport enum SubjectReferenceType {\n SUBJECT_TYPE_DEFAULT = 'SUBJECT_TYPE_DEFAULT',\n SUBJECT_TYPE_PERSON = 'SUBJECT_TYPE_PERSON',\n SUBJECT_TYPE_ANIMAL = 'SUBJECT_TYPE_ANIMAL',\n SUBJECT_TYPE_PRODUCT = 'SUBJECT_TYPE_PRODUCT',\n}\n\n/** Enum representing the Imagen 3 Edit mode. */\nexport enum EditMode {\n EDIT_MODE_DEFAULT = 'EDIT_MODE_DEFAULT',\n EDIT_MODE_INPAINT_REMOVAL = 'EDIT_MODE_INPAINT_REMOVAL',\n EDIT_MODE_INPAINT_INSERTION = 'EDIT_MODE_INPAINT_INSERTION',\n EDIT_MODE_OUTPAINT = 'EDIT_MODE_OUTPAINT',\n EDIT_MODE_CONTROLLED_EDITING = 'EDIT_MODE_CONTROLLED_EDITING',\n EDIT_MODE_STYLE = 'EDIT_MODE_STYLE',\n EDIT_MODE_BGSWAP = 'EDIT_MODE_BGSWAP',\n EDIT_MODE_PRODUCT_IMAGE = 'EDIT_MODE_PRODUCT_IMAGE',\n}\n\n/** Enum that represents the segmentation mode. */\nexport enum SegmentMode {\n FOREGROUND = 'FOREGROUND',\n BACKGROUND = 'BACKGROUND',\n PROMPT = 'PROMPT',\n SEMANTIC = 'SEMANTIC',\n INTERACTIVE = 'INTERACTIVE',\n}\n\n/** Enum that controls the compression quality of the generated videos. */\nexport enum VideoCompressionQuality {\n /**\n * Optimized video compression quality. This will produce videos\n with a compressed, smaller file size.\n */\n OPTIMIZED = 'OPTIMIZED',\n /**\n * Lossless video compression quality. This will produce videos\n with a larger file size.\n */\n LOSSLESS = 'LOSSLESS',\n}\n\n/** State for the lifecycle of a File. */\nexport enum FileState {\n STATE_UNSPECIFIED = 'STATE_UNSPECIFIED',\n PROCESSING = 'PROCESSING',\n ACTIVE = 'ACTIVE',\n FAILED = 'FAILED',\n}\n\n/** Source of the File. */\nexport enum FileSource {\n SOURCE_UNSPECIFIED = 'SOURCE_UNSPECIFIED',\n UPLOADED = 'UPLOADED',\n GENERATED = 'GENERATED',\n}\n\n/** Server content modalities. */\nexport enum MediaModality {\n /**\n * The modality is unspecified.\n */\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n /**\n * Plain text.\n */\n TEXT = 'TEXT',\n /**\n * Images.\n */\n IMAGE = 'IMAGE',\n /**\n * Video.\n */\n VIDEO = 'VIDEO',\n /**\n * Audio.\n */\n AUDIO = 'AUDIO',\n /**\n * Document, e.g. PDF.\n */\n DOCUMENT = 'DOCUMENT',\n}\n\n/** Start of speech sensitivity. */\nexport enum StartSensitivity {\n /**\n * The default is START_SENSITIVITY_LOW.\n */\n START_SENSITIVITY_UNSPECIFIED = 'START_SENSITIVITY_UNSPECIFIED',\n /**\n * Automatic detection will detect the start of speech more often.\n */\n START_SENSITIVITY_HIGH = 'START_SENSITIVITY_HIGH',\n /**\n * Automatic detection will detect the start of speech less often.\n */\n START_SENSITIVITY_LOW = 'START_SENSITIVITY_LOW',\n}\n\n/** End of speech sensitivity. */\nexport enum EndSensitivity {\n /**\n * The default is END_SENSITIVITY_LOW.\n */\n END_SENSITIVITY_UNSPECIFIED = 'END_SENSITIVITY_UNSPECIFIED',\n /**\n * Automatic detection ends speech more often.\n */\n END_SENSITIVITY_HIGH = 'END_SENSITIVITY_HIGH',\n /**\n * Automatic detection ends speech less often.\n */\n END_SENSITIVITY_LOW = 'END_SENSITIVITY_LOW',\n}\n\n/** The different ways of handling user activity. */\nexport enum ActivityHandling {\n /**\n * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`.\n */\n ACTIVITY_HANDLING_UNSPECIFIED = 'ACTIVITY_HANDLING_UNSPECIFIED',\n /**\n * If true, start of activity will interrupt the model's response (also called \"barge in\"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior.\n */\n START_OF_ACTIVITY_INTERRUPTS = 'START_OF_ACTIVITY_INTERRUPTS',\n /**\n * The model's response will not be interrupted.\n */\n NO_INTERRUPTION = 'NO_INTERRUPTION',\n}\n\n/** Options about which input is included in the user's turn. */\nexport enum TurnCoverage {\n /**\n * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`.\n */\n TURN_COVERAGE_UNSPECIFIED = 'TURN_COVERAGE_UNSPECIFIED',\n /**\n * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior.\n */\n TURN_INCLUDES_ONLY_ACTIVITY = 'TURN_INCLUDES_ONLY_ACTIVITY',\n /**\n * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream).\n */\n TURN_INCLUDES_ALL_INPUT = 'TURN_INCLUDES_ALL_INPUT',\n}\n\n/** Specifies how the response should be scheduled in the conversation. */\nexport enum FunctionResponseScheduling {\n /**\n * This value is unused.\n */\n SCHEDULING_UNSPECIFIED = 'SCHEDULING_UNSPECIFIED',\n /**\n * Only add the result to the conversation context, do not interrupt or trigger generation.\n */\n SILENT = 'SILENT',\n /**\n * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation.\n */\n WHEN_IDLE = 'WHEN_IDLE',\n /**\n * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output.\n */\n INTERRUPT = 'INTERRUPT',\n}\n\n/** Scale of the generated music. */\nexport enum Scale {\n /**\n * Default value. This value is unused.\n */\n SCALE_UNSPECIFIED = 'SCALE_UNSPECIFIED',\n /**\n * C major or A minor.\n */\n C_MAJOR_A_MINOR = 'C_MAJOR_A_MINOR',\n /**\n * Db major or Bb minor.\n */\n D_FLAT_MAJOR_B_FLAT_MINOR = 'D_FLAT_MAJOR_B_FLAT_MINOR',\n /**\n * D major or B minor.\n */\n D_MAJOR_B_MINOR = 'D_MAJOR_B_MINOR',\n /**\n * Eb major or C minor\n */\n E_FLAT_MAJOR_C_MINOR = 'E_FLAT_MAJOR_C_MINOR',\n /**\n * E major or Db minor.\n */\n E_MAJOR_D_FLAT_MINOR = 'E_MAJOR_D_FLAT_MINOR',\n /**\n * F major or D minor.\n */\n F_MAJOR_D_MINOR = 'F_MAJOR_D_MINOR',\n /**\n * Gb major or Eb minor.\n */\n G_FLAT_MAJOR_E_FLAT_MINOR = 'G_FLAT_MAJOR_E_FLAT_MINOR',\n /**\n * G major or E minor.\n */\n G_MAJOR_E_MINOR = 'G_MAJOR_E_MINOR',\n /**\n * Ab major or F minor.\n */\n A_FLAT_MAJOR_F_MINOR = 'A_FLAT_MAJOR_F_MINOR',\n /**\n * A major or Gb minor.\n */\n A_MAJOR_G_FLAT_MINOR = 'A_MAJOR_G_FLAT_MINOR',\n /**\n * Bb major or G minor.\n */\n B_FLAT_MAJOR_G_MINOR = 'B_FLAT_MAJOR_G_MINOR',\n /**\n * B major or Ab minor.\n */\n B_MAJOR_A_FLAT_MINOR = 'B_MAJOR_A_FLAT_MINOR',\n}\n\n/** The mode of music generation. */\nexport enum MusicGenerationMode {\n /**\n * Rely on the server default generation mode.\n */\n MUSIC_GENERATION_MODE_UNSPECIFIED = 'MUSIC_GENERATION_MODE_UNSPECIFIED',\n /**\n * Steer text prompts to regions of latent space with higher quality\n music.\n */\n QUALITY = 'QUALITY',\n /**\n * Steer text prompts to regions of latent space with a larger\n diversity of music.\n */\n DIVERSITY = 'DIVERSITY',\n /**\n * Steer text prompts to regions of latent space more likely to\n generate music with vocals.\n */\n VOCALIZATION = 'VOCALIZATION',\n}\n\n/** The playback control signal to apply to the music generation. */\nexport enum LiveMusicPlaybackControl {\n /**\n * This value is unused.\n */\n PLAYBACK_CONTROL_UNSPECIFIED = 'PLAYBACK_CONTROL_UNSPECIFIED',\n /**\n * Start generating the music.\n */\n PLAY = 'PLAY',\n /**\n * Hold the music generation. Use PLAY to resume from the current position.\n */\n PAUSE = 'PAUSE',\n /**\n * Stop the music generation and reset the context (prompts retained).\n Use PLAY to restart the music generation.\n */\n STOP = 'STOP',\n /**\n * Reset the context of the music generation without stopping it.\n Retains the current prompts and config.\n */\n RESET_CONTEXT = 'RESET_CONTEXT',\n}\n\n/** Describes how the video in the Part should be used by the model. */\nexport declare interface VideoMetadata {\n /** The frame rate of the video sent to the model. If not specified, the\n default value will be 1.0. The fps range is (0.0, 24.0]. */\n fps?: number;\n /** Optional. The end offset of the video. */\n endOffset?: string;\n /** Optional. The start offset of the video. */\n startOffset?: string;\n}\n\n/** Content blob. */\nexport declare interface Blob {\n /** Optional. Display name of the blob. Used to provide a label or filename to distinguish blobs. This field is not currently used in the Gemini GenerateContent calls. */\n displayName?: string;\n /** Required. Raw bytes.\n * @remarks Encoded as base64 string. */\n data?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** URI based data. */\nexport declare interface FileData {\n /** Optional. Display name of the file data. Used to provide a label or filename to distinguish file datas. It is not currently used in the Gemini GenerateContent calls. */\n displayName?: string;\n /** Required. URI. */\n fileUri?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** Result of executing the [ExecutableCode]. Only generated when using the [CodeExecution] tool, and always follows a `part` containing the [ExecutableCode]. */\nexport declare interface CodeExecutionResult {\n /** Required. Outcome of the code execution. */\n outcome?: Outcome;\n /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */\n output?: string;\n}\n\n/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [CodeExecution] tool, in which the code will be automatically executed, and a corresponding [CodeExecutionResult] will also be generated. */\nexport declare interface ExecutableCode {\n /** Required. The code to be executed. */\n code?: string;\n /** Required. Programming language of the `code`. */\n language?: Language;\n}\n\n/** A function call. */\nexport declare interface FunctionCall {\n /** The unique id of the function call. If populated, the client to execute the\n `function_call` and return the response with the matching `id`. */\n id?: string;\n /** Optional. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */\n args?: Record;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */\n name?: string;\n}\n\n/** A function response. */\nexport class FunctionResponse {\n /** Signals that function call continues, and more responses will be returned, turning the function call into a generator. Is only applicable to NON_BLOCKING function calls (see FunctionDeclaration.behavior for details), ignored otherwise. If false, the default, future responses will not be considered. Is only applicable to NON_BLOCKING function calls, is ignored otherwise. If set to false, future responses will not be considered. It is allowed to return empty `response` with `will_continue=False` to signal that the function call is finished. */\n willContinue?: boolean;\n /** Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. */\n scheduling?: FunctionResponseScheduling;\n /** Optional. The id of the function call this response is for. Populated by the client to match the corresponding function call `id`. */\n id?: string;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */\n name?: string;\n /** Required. The function response in JSON object format. Use \"output\" key to specify function output and \"error\" key to specify error details (if any). If \"output\" and \"error\" keys are not specified, then whole \"response\" is treated as function output. */\n response?: Record;\n}\n\n/** A datatype containing media content.\n\n Exactly one field within a Part should be set, representing the specific type\n of content being conveyed. Using multiple fields within the same `Part`\n instance is considered invalid.\n */\nexport declare interface Part {\n /** Metadata for a given video. */\n videoMetadata?: VideoMetadata;\n /** Indicates if the part is thought from the model. */\n thought?: boolean;\n /** Optional. Inlined bytes data. */\n inlineData?: Blob;\n /** Optional. URI based data. */\n fileData?: FileData;\n /** An opaque signature for the thought so it can be reused in subsequent requests.\n * @remarks Encoded as base64 string. */\n thoughtSignature?: string;\n /** Optional. Result of executing the [ExecutableCode]. */\n codeExecutionResult?: CodeExecutionResult;\n /** Optional. Code generated by the model that is meant to be executed. */\n executableCode?: ExecutableCode;\n /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */\n functionCall?: FunctionCall;\n /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */\n functionResponse?: FunctionResponse;\n /** Optional. Text part (can be code). */\n text?: string;\n}\n/**\n * Creates a `Part` object from a `URI` string.\n */\nexport function createPartFromUri(uri: string, mimeType: string): Part {\n return {\n fileData: {\n fileUri: uri,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from a `text` string.\n */\nexport function createPartFromText(text: string): Part {\n return {\n text: text,\n };\n}\n/**\n * Creates a `Part` object from a `FunctionCall` object.\n */\nexport function createPartFromFunctionCall(\n name: string,\n args: Record,\n): Part {\n return {\n functionCall: {\n name: name,\n args: args,\n },\n };\n}\n/**\n * Creates a `Part` object from a `FunctionResponse` object.\n */\nexport function createPartFromFunctionResponse(\n id: string,\n name: string,\n response: Record,\n): Part {\n return {\n functionResponse: {\n id: id,\n name: name,\n response: response,\n },\n };\n}\n/**\n * Creates a `Part` object from a `base64` encoded `string`.\n */\nexport function createPartFromBase64(data: string, mimeType: string): Part {\n return {\n inlineData: {\n data: data,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object.\n */\nexport function createPartFromCodeExecutionResult(\n outcome: Outcome,\n output: string,\n): Part {\n return {\n codeExecutionResult: {\n outcome: outcome,\n output: output,\n },\n };\n}\n/**\n * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object.\n */\nexport function createPartFromExecutableCode(\n code: string,\n language: Language,\n): Part {\n return {\n executableCode: {\n code: code,\n language: language,\n },\n };\n}\n\n/** Contains the multi-part content of a message. */\nexport declare interface Content {\n /** List of parts that constitute a single message. Each part may have\n a different IANA MIME type. */\n parts?: Part[];\n /** Optional. The producer of the content. Must be either 'user' or\n 'model'. Useful to set for multi-turn conversations, otherwise can be\n empty. If role is not specified, SDK will determine the role. */\n role?: string;\n}\nfunction _isPart(obj: unknown): obj is Part {\n if (typeof obj === 'object' && obj !== null) {\n return (\n 'fileData' in obj ||\n 'text' in obj ||\n 'functionCall' in obj ||\n 'functionResponse' in obj ||\n 'inlineData' in obj ||\n 'videoMetadata' in obj ||\n 'codeExecutionResult' in obj ||\n 'executableCode' in obj\n );\n }\n return false;\n}\nfunction _toParts(partOrString: PartListUnion | string): Part[] {\n const parts: Part[] = [];\n if (typeof partOrString === 'string') {\n parts.push(createPartFromText(partOrString));\n } else if (_isPart(partOrString)) {\n parts.push(partOrString);\n } else if (Array.isArray(partOrString)) {\n if (partOrString.length === 0) {\n throw new Error('partOrString cannot be an empty array');\n }\n for (const part of partOrString) {\n if (typeof part === 'string') {\n parts.push(createPartFromText(part));\n } else if (_isPart(part)) {\n parts.push(part);\n } else {\n throw new Error('element in PartUnion must be a Part object or string');\n }\n }\n } else {\n throw new Error('partOrString must be a Part object, string, or array');\n }\n return parts;\n}\n/**\n * Creates a `Content` object with a user role from a `PartListUnion` object or `string`.\n */\nexport function createUserContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'user',\n parts: _toParts(partOrString),\n };\n}\n\n/**\n * Creates a `Content` object with a model role from a `PartListUnion` object or `string`.\n */\nexport function createModelContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'model',\n parts: _toParts(partOrString),\n };\n}\n/** HTTP options to be used in each of the requests. */\nexport declare interface HttpOptions {\n /** The base URL for the AI platform service endpoint. */\n baseUrl?: string;\n /** Specifies the version of the API to use. */\n apiVersion?: string;\n /** Additional HTTP headers to be sent with the request. */\n headers?: Record;\n /** Timeout for the request in milliseconds. */\n timeout?: number;\n /** Extra parameters to add to the request body.\n The structure must match the backend API's request structure.\n - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest\n - GeminiAPI backend API docs: https://ai.google.dev/api/rest */\n extraBody?: Record;\n}\n\n/** Schema is used to define the format of input/output data.\n\n Represents a select subset of an [OpenAPI 3.0 schema\n object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may\n be added in the future as needed.\n */\nexport declare interface Schema {\n /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */\n anyOf?: Schema[];\n /** Optional. Default value of the data. */\n default?: unknown;\n /** Optional. The description of the data. */\n description?: string;\n /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:[\"EAST\", NORTH\", \"SOUTH\", \"WEST\"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:[\"101\", \"201\", \"301\"]} */\n enum?: string[];\n /** Optional. Example of the object. Will only populated when the object is the root. */\n example?: unknown;\n /** Optional. The format of the data. Supported formats: for NUMBER type: \"float\", \"double\" for INTEGER type: \"int32\", \"int64\" for STRING type: \"email\", \"byte\", etc */\n format?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */\n items?: Schema;\n /** Optional. Maximum number of the elements for Type.ARRAY. */\n maxItems?: string;\n /** Optional. Maximum length of the Type.STRING */\n maxLength?: string;\n /** Optional. Maximum number of the properties for Type.OBJECT. */\n maxProperties?: string;\n /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */\n maximum?: number;\n /** Optional. Minimum number of the elements for Type.ARRAY. */\n minItems?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */\n minLength?: string;\n /** Optional. Minimum number of the properties for Type.OBJECT. */\n minProperties?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */\n minimum?: number;\n /** Optional. Indicates if the value may be null. */\n nullable?: boolean;\n /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */\n pattern?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */\n properties?: Record;\n /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */\n propertyOrdering?: string[];\n /** Optional. Required properties of Type.OBJECT. */\n required?: string[];\n /** Optional. The title of the Schema. */\n title?: string;\n /** Optional. The type of the data. */\n type?: Type;\n}\n\n/** Config for model selection. */\nexport declare interface ModelSelectionConfig {\n /** Options for feature selection preference. */\n featureSelectionPreference?: FeatureSelectionPreference;\n}\n\n/** Safety settings. */\nexport declare interface SafetySetting {\n /** Determines if the harm block method uses probability or probability\n and severity scores. */\n method?: HarmBlockMethod;\n /** Required. Harm category. */\n category?: HarmCategory;\n /** Required. The harm block threshold. */\n threshold?: HarmBlockThreshold;\n}\n\n/** Defines a function that the model can generate JSON inputs for.\n\n The inputs are based on `OpenAPI 3.0 specifications\n `_.\n */\nexport declare interface FunctionDeclaration {\n /** Defines the function behavior. */\n behavior?: Behavior;\n /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */\n description?: string;\n /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */\n name?: string;\n /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */\n parameters?: Schema;\n /** Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" }, \"age\": { \"type\": \"integer\" } }, \"additionalProperties\": false, \"required\": [\"name\", \"age\"], \"propertyOrdering\": [\"name\", \"age\"] } ``` This field is mutually exclusive with `parameters`. */\n parametersJsonSchema?: unknown;\n /** Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function. */\n response?: Schema;\n /** Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`. */\n responseJsonSchema?: unknown;\n}\n\n/** Represents a time interval, encoded as a start time (inclusive) and an end time (exclusive).\n\n The start time must be less than or equal to the end time.\n When the start equals the end time, the interval is an empty interval.\n (matches no time)\n When both start and end are unspecified, the interval matches any time.\n */\nexport declare interface Interval {\n /** The start time of the interval. */\n startTime?: string;\n /** The end time of the interval. */\n endTime?: string;\n}\n\n/** Tool to support Google Search in Model. Powered by Google. */\nexport declare interface GoogleSearch {\n /** Optional. Filter search results to a specific time range.\n If customers set a start time, they must set an end time (and vice versa).\n */\n timeRangeFilter?: Interval;\n /** Optional. List of domains to be excluded from the search results.\n The default limit is 2000 domains. */\n excludeDomains?: string[];\n}\n\n/** Describes the options to customize dynamic retrieval. */\nexport declare interface DynamicRetrievalConfig {\n /** The mode of the predictor to be used in dynamic retrieval. */\n mode?: DynamicRetrievalConfigMode;\n /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */\n dynamicThreshold?: number;\n}\n\n/** Tool to retrieve public web data for grounding, powered by Google. */\nexport declare interface GoogleSearchRetrieval {\n /** Specifies the dynamic retrieval configuration for the given source. */\n dynamicRetrievalConfig?: DynamicRetrievalConfig;\n}\n\n/** Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. */\nexport declare interface EnterpriseWebSearch {\n /** Optional. List of domains to be excluded from the search results. The default limit is 2000 domains. */\n excludeDomains?: string[];\n}\n\n/** Config for authentication with API key. */\nexport declare interface ApiKeyConfig {\n /** The API key to be used in the request directly. */\n apiKeyString?: string;\n}\n\n/** Config for Google Service Account Authentication. */\nexport declare interface AuthConfigGoogleServiceAccountConfig {\n /** Optional. The service account that the extension execution service runs as. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified service account. - If not specified, the Vertex AI Extension Service Agent will be used to execute the Extension. */\n serviceAccount?: string;\n}\n\n/** Config for HTTP Basic Authentication. */\nexport declare interface AuthConfigHttpBasicAuthConfig {\n /** Required. The name of the SecretManager secret version resource storing the base64 encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource. */\n credentialSecret?: string;\n}\n\n/** Config for user oauth. */\nexport declare interface AuthConfigOauthConfig {\n /** Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */\n accessToken?: string;\n /** The service account used to generate access tokens for executing the Extension. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the provided service account. */\n serviceAccount?: string;\n}\n\n/** Config for user OIDC auth. */\nexport declare interface AuthConfigOidcConfig {\n /** OpenID Connect formatted ID token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */\n idToken?: string;\n /** The service account used to generate an OpenID Connect (OIDC)-compatible JWT token signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc). - The audience for the token will be set to the URL in the server url defined in the OpenApi spec. - If the service account is provided, the service account should grant `iam.serviceAccounts.getOpenIdToken` permission to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents). */\n serviceAccount?: string;\n}\n\n/** Auth configuration to run the extension. */\nexport declare interface AuthConfig {\n /** Config for API key auth. */\n apiKeyConfig?: ApiKeyConfig;\n /** Type of auth scheme. */\n authType?: AuthType;\n /** Config for Google Service Account auth. */\n googleServiceAccountConfig?: AuthConfigGoogleServiceAccountConfig;\n /** Config for HTTP Basic auth. */\n httpBasicAuthConfig?: AuthConfigHttpBasicAuthConfig;\n /** Config for user oauth. */\n oauthConfig?: AuthConfigOauthConfig;\n /** Config for user OIDC auth. */\n oidcConfig?: AuthConfigOidcConfig;\n}\n\n/** Tool to support Google Maps in Model. */\nexport declare interface GoogleMaps {\n /** Optional. Auth config for the Google Maps tool. */\n authConfig?: AuthConfig;\n}\n\n/** Tool to support URL context retrieval. */\nexport declare interface UrlContext {}\n\n/** Tool to support computer use. */\nexport declare interface ToolComputerUse {\n /** Required. The environment being operated. */\n environment?: Environment;\n}\n\n/** The API secret. */\nexport declare interface ApiAuthApiKeyConfig {\n /** Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version} */\n apiKeySecretVersion?: string;\n /** The API key string. Either this or `api_key_secret_version` must be set. */\n apiKeyString?: string;\n}\n\n/** The generic reusable api auth config. Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto) instead. */\nexport declare interface ApiAuth {\n /** The API secret. */\n apiKeyConfig?: ApiAuthApiKeyConfig;\n}\n\n/** The search parameters to use for the ELASTIC_SEARCH spec. */\nexport declare interface ExternalApiElasticSearchParams {\n /** The ElasticSearch index to use. */\n index?: string;\n /** Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as the `num_hits` param. */\n numHits?: number;\n /** The ElasticSearch search template to use. */\n searchTemplate?: string;\n}\n\n/** The search parameters to use for SIMPLE_SEARCH spec. */\nexport declare interface ExternalApiSimpleSearchParams {}\n\n/** Retrieve from data source powered by external API for grounding. The external API is not owned by Google, but need to follow the pre-defined API spec. */\nexport declare interface ExternalApi {\n /** The authentication config to access the API. Deprecated. Please use auth_config instead. */\n apiAuth?: ApiAuth;\n /** The API spec that the external API implements. */\n apiSpec?: ApiSpec;\n /** The authentication config to access the API. */\n authConfig?: AuthConfig;\n /** Parameters for the elastic search API. */\n elasticSearchParams?: ExternalApiElasticSearchParams;\n /** The endpoint of the external API. The system will call the API at this endpoint to retrieve the data for grounding. Example: https://acme.com:443/search */\n endpoint?: string;\n /** Parameters for the simple search API. */\n simpleSearchParams?: ExternalApiSimpleSearchParams;\n}\n\n/** Define data stores within engine to filter on in a search call and configurations for those data stores. For more information, see https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec */\nexport declare interface VertexAISearchDataStoreSpec {\n /** Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n dataStore?: string;\n /** Optional. Filter specification to filter documents in the data store specified by data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata) */\n filter?: string;\n}\n\n/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */\nexport declare interface VertexAISearch {\n /** Specifications that define the specific DataStores to be searched, along with configurations for those data stores. This is only considered for Engines with multiple data stores. It should only be set if engine is used. */\n dataStoreSpecs?: VertexAISearchDataStoreSpec[];\n /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n datastore?: string;\n /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */\n engine?: string;\n /** Optional. Filter strings to be passed to the search API. */\n filter?: string;\n /** Optional. Number of search results to return per query. The default value is 10. The maximumm allowed value is 10. */\n maxResults?: number;\n}\n\n/** The definition of the Rag resource. */\nexport declare interface VertexRagStoreRagResource {\n /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */\n ragCorpus?: string;\n /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */\n ragFileIds?: string[];\n}\n\n/** Config for filters. */\nexport declare interface RagRetrievalConfigFilter {\n /** Optional. String for metadata filtering. */\n metadataFilter?: string;\n /** Optional. Only returns contexts with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n /** Optional. Only returns contexts with vector similarity larger than the threshold. */\n vectorSimilarityThreshold?: number;\n}\n\n/** Config for Hybrid Search. */\nexport declare interface RagRetrievalConfigHybridSearch {\n /** Optional. Alpha value controls the weight between dense and sparse vector search results. The range is [0, 1], while 0 means sparse vector search only and 1 means dense vector search only. The default value is 0.5 which balances sparse and dense vector search equally. */\n alpha?: number;\n}\n\n/** Config for LlmRanker. */\nexport declare interface RagRetrievalConfigRankingLlmRanker {\n /** Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */\n modelName?: string;\n}\n\n/** Config for Rank Service. */\nexport declare interface RagRetrievalConfigRankingRankService {\n /** Optional. The model name of the rank service. Format: `semantic-ranker-512@latest` */\n modelName?: string;\n}\n\n/** Config for ranking and reranking. */\nexport declare interface RagRetrievalConfigRanking {\n /** Optional. Config for LlmRanker. */\n llmRanker?: RagRetrievalConfigRankingLlmRanker;\n /** Optional. Config for Rank Service. */\n rankService?: RagRetrievalConfigRankingRankService;\n}\n\n/** Specifies the context retrieval config. */\nexport declare interface RagRetrievalConfig {\n /** Optional. Config for filters. */\n filter?: RagRetrievalConfigFilter;\n /** Optional. Config for Hybrid Search. */\n hybridSearch?: RagRetrievalConfigHybridSearch;\n /** Optional. Config for ranking and reranking. */\n ranking?: RagRetrievalConfigRanking;\n /** Optional. The number of contexts to retrieve. */\n topK?: number;\n}\n\n/** Retrieve from Vertex RAG Store for grounding. */\nexport declare interface VertexRagStore {\n /** Optional. Deprecated. Please use rag_resources instead. */\n ragCorpora?: string[];\n /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */\n ragResources?: VertexRagStoreRagResource[];\n /** Optional. The retrieval config for the Rag query. */\n ragRetrievalConfig?: RagRetrievalConfig;\n /** Optional. Number of top k results to return from the selected corpora. */\n similarityTopK?: number;\n /** Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal Live API, if `store_context` bool is specified, Gemini will leverage it to automatically memorize the interactions between the client and Gemini, and retrieve context when needed to augment the response generation for users' ongoing and future interactions. */\n storeContext?: boolean;\n /** Optional. Only return results with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n}\n\n/** Defines a retrieval tool that model can call to access external knowledge. */\nexport declare interface Retrieval {\n /** Optional. Deprecated. This option is no longer supported. */\n disableAttribution?: boolean;\n /** Use data source powered by external API for grounding. */\n externalApi?: ExternalApi;\n /** Set to use data source powered by Vertex AI Search. */\n vertexAiSearch?: VertexAISearch;\n /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */\n vertexRagStore?: VertexRagStore;\n}\n\n/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */\nexport declare interface ToolCodeExecution {}\n\n/** Tool details of a tool that the model may use to generate a response. */\nexport declare interface Tool {\n /** List of function declarations that the tool supports. */\n functionDeclarations?: FunctionDeclaration[];\n /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */\n retrieval?: Retrieval;\n /** Optional. Google Search tool type. Specialized retrieval tool\n that is powered by Google Search. */\n googleSearch?: GoogleSearch;\n /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */\n googleSearchRetrieval?: GoogleSearchRetrieval;\n /** Optional. Enterprise web search tool type. Specialized retrieval\n tool that is powered by Vertex AI Search and Sec4 compliance. */\n enterpriseWebSearch?: EnterpriseWebSearch;\n /** Optional. Google Maps tool type. Specialized retrieval tool\n that is powered by Google Maps. */\n googleMaps?: GoogleMaps;\n /** Optional. Tool to support URL context retrieval. */\n urlContext?: UrlContext;\n /** Optional. Tool to support the model interacting directly with the\n computer. If enabled, it automatically populates computer-use specific\n Function Declarations. */\n computerUse?: ToolComputerUse;\n /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. */\n codeExecution?: ToolCodeExecution;\n}\n\n/** Function calling config. */\nexport declare interface FunctionCallingConfig {\n /** Optional. Function calling mode. */\n mode?: FunctionCallingConfigMode;\n /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */\n allowedFunctionNames?: string[];\n}\n\n/** An object that represents a latitude/longitude pair.\n\n This is expressed as a pair of doubles to represent degrees latitude and\n degrees longitude. Unless specified otherwise, this object must conform to the\n \n WGS84 standard. Values must be within normalized ranges.\n */\nexport declare interface LatLng {\n /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */\n latitude?: number;\n /** The longitude in degrees. It must be in the range [-180.0, +180.0] */\n longitude?: number;\n}\n\n/** Retrieval config.\n */\nexport declare interface RetrievalConfig {\n /** Optional. The location of the user. */\n latLng?: LatLng;\n /** The language code of the user. */\n languageCode?: string;\n}\n\n/** Tool config.\n\n This config is shared for all tools provided in the request.\n */\nexport declare interface ToolConfig {\n /** Optional. Function calling config. */\n functionCallingConfig?: FunctionCallingConfig;\n /** Optional. Retrieval config. */\n retrievalConfig?: RetrievalConfig;\n}\n\n/** The configuration for the prebuilt speaker to use. */\nexport declare interface PrebuiltVoiceConfig {\n /** The name of the prebuilt voice to use. */\n voiceName?: string;\n}\n\n/** The configuration for the voice to use. */\nexport declare interface VoiceConfig {\n /** The configuration for the speaker to use.\n */\n prebuiltVoiceConfig?: PrebuiltVoiceConfig;\n}\n\n/** The configuration for the speaker to use. */\nexport declare interface SpeakerVoiceConfig {\n /** The name of the speaker to use. Should be the same as in the\n prompt. */\n speaker?: string;\n /** The configuration for the voice to use. */\n voiceConfig?: VoiceConfig;\n}\n\n/** The configuration for the multi-speaker setup. */\nexport declare interface MultiSpeakerVoiceConfig {\n /** The configuration for the speaker to use. */\n speakerVoiceConfigs?: SpeakerVoiceConfig[];\n}\n\n/** The speech generation configuration. */\nexport declare interface SpeechConfig {\n /** The configuration for the speaker to use.\n */\n voiceConfig?: VoiceConfig;\n /** The configuration for the multi-speaker setup.\n It is mutually exclusive with the voice_config field.\n */\n multiSpeakerVoiceConfig?: MultiSpeakerVoiceConfig;\n /** Language code (ISO 639. e.g. en-US) for the speech synthesization.\n Only available for Live API.\n */\n languageCode?: string;\n}\n\n/** The configuration for automatic function calling. */\nexport declare interface AutomaticFunctionCallingConfig {\n /** Whether to disable automatic function calling.\n If not set or set to False, will enable automatic function calling.\n If set to True, will disable automatic function calling.\n */\n disable?: boolean;\n /** If automatic function calling is enabled,\n maximum number of remote calls for automatic function calling.\n This number should be a positive integer.\n If not set, SDK will set maximum number of remote calls to 10.\n */\n maximumRemoteCalls?: number;\n /** If automatic function calling is enabled,\n whether to ignore call history to the response.\n If not set, SDK will set ignore_call_history to false,\n and will append the call history to\n GenerateContentResponse.automatic_function_calling_history.\n */\n ignoreCallHistory?: boolean;\n}\n\n/** The thinking features configuration. */\nexport declare interface ThinkingConfig {\n /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available.\n */\n includeThoughts?: boolean;\n /** Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent.\n */\n thinkingBudget?: number;\n}\n\n/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */\nexport declare interface GenerationConfigRoutingConfigAutoRoutingMode {\n /** The model routing preference. */\n modelRoutingPreference?:\n | 'UNKNOWN'\n | 'PRIORITIZE_QUALITY'\n | 'BALANCED'\n | 'PRIORITIZE_COST';\n}\n\n/** When manual routing is set, the specified model will be used directly. */\nexport declare interface GenerationConfigRoutingConfigManualRoutingMode {\n /** The model name to use. Only the public LLM models are accepted. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */\n modelName?: string;\n}\n\n/** The configuration for routing the request to a specific model. */\nexport declare interface GenerationConfigRoutingConfig {\n /** Automated routing. */\n autoMode?: GenerationConfigRoutingConfigAutoRoutingMode;\n /** Manual routing. */\n manualMode?: GenerationConfigRoutingConfigManualRoutingMode;\n}\n\n/** Optional model configuration parameters.\n\n For more information, see `Content generation parameters\n `_.\n */\nexport declare interface GenerateContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Instructions for the model to steer it toward better performance.\n For example, \"Answer as concisely as possible\" or \"Don't use technical\n terms in your response\".\n */\n systemInstruction?: ContentUnion;\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Number of response variations to return.\n */\n candidateCount?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** List of strings that tells the model to stop generating text if one\n of the strings is encountered in the response.\n */\n stopSequences?: string[];\n /** Whether to return the log probabilities of the tokens that were\n chosen by the model at each step.\n */\n responseLogprobs?: boolean;\n /** Number of top candidate tokens to return the log probabilities for\n at each generation step.\n */\n logprobs?: number;\n /** Positive values penalize tokens that already appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n presencePenalty?: number;\n /** Positive values penalize tokens that repeatedly appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n frequencyPenalty?: number;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** Output response mimetype of the generated candidate text.\n Supported mimetype:\n - `text/plain`: (default) Text output.\n - `application/json`: JSON response in the candidates.\n The model needs to be prompted to output the appropriate response type,\n otherwise the behavior is undefined.\n This is a preview feature.\n */\n responseMimeType?: string;\n /** The `Schema` object allows the definition of input and output data types.\n These types can be objects, but also primitives and arrays.\n Represents a select subset of an [OpenAPI 3.0 schema\n object](https://spec.openapis.org/oas/v3.0.3#schema).\n If set, a compatible response_mime_type must also be set.\n Compatible mimetypes: `application/json`: Schema for JSON response.\n */\n responseSchema?: SchemaUnion;\n /** Optional. Output schema of the generated response.\n This is an alternative to `response_schema` that accepts [JSON\n Schema](https://json-schema.org/). If set, `response_schema` must be\n omitted, but `response_mime_type` is required. While the full JSON Schema\n may be sent, not all features are supported. Specifically, only the\n following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor`\n - `type` - `format` - `title` - `description` - `enum` (for strings and\n numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` -\n `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) -\n `properties` - `additionalProperties` - `required` The non-standard\n `propertyOrdering` property may also be set. Cyclic references are\n unrolled to a limited degree and, as such, may only be used within\n non-required properties. (Nullable properties are not sufficient.) If\n `$ref` is set on a sub-schema, no other properties, except for than those\n starting as a `$`, may be set. */\n responseJsonSchema?: unknown;\n /** Configuration for model router requests.\n */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Configuration for model selection.\n */\n modelSelectionConfig?: ModelSelectionConfig;\n /** Safety settings in the request to block unsafe content in the\n response.\n */\n safetySettings?: SafetySetting[];\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: ToolListUnion;\n /** Associates model output to a specific function call.\n */\n toolConfig?: ToolConfig;\n /** Labels with user-defined metadata to break down billed charges. */\n labels?: Record;\n /** Resource name of a context cache that can be used in subsequent\n requests.\n */\n cachedContent?: string;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return.\n */\n responseModalities?: string[];\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfigUnion;\n /** If enabled, audio timestamp will be included in the request to the\n model.\n */\n audioTimestamp?: boolean;\n /** The configuration for automatic function calling.\n */\n automaticFunctionCalling?: AutomaticFunctionCallingConfig;\n /** The thinking features configuration.\n */\n thinkingConfig?: ThinkingConfig;\n}\n\n/** Config for models.generate_content parameters. */\nexport declare interface GenerateContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Content of the request.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** A wrapper class for the http response. */\nexport class HttpResponse {\n /** Used to retain the processed HTTP headers in the response. */\n headers?: Record;\n /**\n * The original http response.\n */\n responseInternal: Response;\n\n constructor(response: Response) {\n // Process the headers.\n const headers: Record = {};\n for (const pair of response.headers.entries()) {\n headers[pair[0]] = pair[1];\n }\n this.headers = headers;\n\n // Keep the original response.\n this.responseInternal = response;\n }\n\n json(): Promise {\n return this.responseInternal.json();\n }\n}\n\n/** Callbacks for the live API. */\nexport interface LiveCallbacks {\n /**\n * Called when the websocket connection is established.\n */\n onopen?: (() => void) | null;\n /**\n * Called when a message is received from the server.\n */\n onmessage: (e: LiveServerMessage) => void;\n /**\n * Called when an error occurs.\n */\n onerror?: ((e: ErrorEvent) => void) | null;\n /**\n * Called when the websocket connection is closed.\n */\n onclose?: ((e: CloseEvent) => void) | null;\n}\n\n/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */\nexport declare interface GoogleTypeDate {\n /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */\n day?: number;\n /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */\n month?: number;\n /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */\n year?: number;\n}\n\n/** Source attributions for content. */\nexport declare interface Citation {\n /** Output only. End index into the content. */\n endIndex?: number;\n /** Output only. License of the attribution. */\n license?: string;\n /** Output only. Publication date of the attribution. */\n publicationDate?: GoogleTypeDate;\n /** Output only. Start index into the content. */\n startIndex?: number;\n /** Output only. Title of the attribution. */\n title?: string;\n /** Output only. Url reference of the attribution. */\n uri?: string;\n}\n\n/** Citation information when the model quotes another source. */\nexport declare interface CitationMetadata {\n /** Contains citation information when the model directly quotes, at\n length, from another source. Can include traditional websites and code\n repositories.\n */\n citations?: Citation[];\n}\n\n/** Context for a single url retrieval. */\nexport declare interface UrlMetadata {\n /** The URL retrieved by the tool. */\n retrievedUrl?: string;\n /** Status of the url retrieval. */\n urlRetrievalStatus?: UrlRetrievalStatus;\n}\n\n/** Metadata related to url context retrieval tool. */\nexport declare interface UrlContextMetadata {\n /** List of url context. */\n urlMetadata?: UrlMetadata[];\n}\n\n/** Author attribution for a photo or review. */\nexport declare interface GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution {\n /** Name of the author of the Photo or Review. */\n displayName?: string;\n /** Profile photo URI of the author of the Photo or Review. */\n photoUri?: string;\n /** URI of the author of the Photo or Review. */\n uri?: string;\n}\n\n/** Encapsulates a review snippet. */\nexport declare interface GroundingChunkMapsPlaceAnswerSourcesReviewSnippet {\n /** This review's author. */\n authorAttribution?: GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution;\n /** A link where users can flag a problem with the review. */\n flagContentUri?: string;\n /** A link to show the review on Google Maps. */\n googleMapsUri?: string;\n /** A string of formatted recent time, expressing the review time relative to the current time in a form appropriate for the language and country. */\n relativePublishTimeDescription?: string;\n /** A reference representing this place review which may be used to look up this place review again. */\n review?: string;\n}\n\n/** Sources used to generate the place answer. */\nexport declare interface GroundingChunkMapsPlaceAnswerSources {\n /** A link where users can flag a problem with the generated answer. */\n flagContentUri?: string;\n /** Snippets of reviews that are used to generate the answer. */\n reviewSnippets?: GroundingChunkMapsPlaceAnswerSourcesReviewSnippet[];\n}\n\n/** Chunk from Google Maps. */\nexport declare interface GroundingChunkMaps {\n /** Sources used to generate the place answer. This includes review snippets and photos that were used to generate the answer, as well as uris to flag content. */\n placeAnswerSources?: GroundingChunkMapsPlaceAnswerSources;\n /** This Place's resource name, in `places/{place_id}` format. Can be used to look up the Place. */\n placeId?: string;\n /** Text of the chunk. */\n text?: string;\n /** Title of the chunk. */\n title?: string;\n /** URI reference of the chunk. */\n uri?: string;\n}\n\n/** Represents where the chunk starts and ends in the document. */\nexport declare interface RagChunkPageSpan {\n /** Page where chunk starts in the document. Inclusive. 1-indexed. */\n firstPage?: number;\n /** Page where chunk ends in the document. Inclusive. 1-indexed. */\n lastPage?: number;\n}\n\n/** A RagChunk includes the content of a chunk of a RagFile, and associated metadata. */\nexport declare interface RagChunk {\n /** If populated, represents where the chunk starts and ends in the document. */\n pageSpan?: RagChunkPageSpan;\n /** The content of the chunk. */\n text?: string;\n}\n\n/** Chunk from context retrieved by the retrieval tools. */\nexport declare interface GroundingChunkRetrievedContext {\n /** Output only. The full document name for the referenced Vertex AI Search document. */\n documentName?: string;\n /** Additional context for the RAG retrieval result. This is only populated when using the RAG retrieval tool. */\n ragChunk?: RagChunk;\n /** Text of the attribution. */\n text?: string;\n /** Title of the attribution. */\n title?: string;\n /** URI reference of the attribution. */\n uri?: string;\n}\n\n/** Chunk from the web. */\nexport declare interface GroundingChunkWeb {\n /** Domain of the (original) URI. */\n domain?: string;\n /** Title of the chunk. */\n title?: string;\n /** URI reference of the chunk. */\n uri?: string;\n}\n\n/** Grounding chunk. */\nexport declare interface GroundingChunk {\n /** Grounding chunk from Google Maps. */\n maps?: GroundingChunkMaps;\n /** Grounding chunk from context retrieved by the retrieval tools. */\n retrievedContext?: GroundingChunkRetrievedContext;\n /** Grounding chunk from the web. */\n web?: GroundingChunkWeb;\n}\n\n/** Segment of the content. */\nexport declare interface Segment {\n /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */\n endIndex?: number;\n /** Output only. The index of a Part object within its parent Content object. */\n partIndex?: number;\n /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */\n startIndex?: number;\n /** Output only. The text corresponding to the segment from the response. */\n text?: string;\n}\n\n/** Grounding support. */\nexport declare interface GroundingSupport {\n /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. For Gemini 2.0 and before, this list must have the same size as the grounding_chunk_indices. For Gemini 2.5 and after, this list will be empty and should be ignored. */\n confidenceScores?: number[];\n /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */\n groundingChunkIndices?: number[];\n /** Segment of the content this support belongs to. */\n segment?: Segment;\n}\n\n/** Metadata related to retrieval in the grounding flow. */\nexport declare interface RetrievalMetadata {\n /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */\n googleSearchDynamicRetrievalScore?: number;\n}\n\n/** Google search entry point. */\nexport declare interface SearchEntryPoint {\n /** Optional. Web content snippet that can be embedded in a web page or an app webview. */\n renderedContent?: string;\n /** Optional. Base64 encoded JSON representing array of tuple.\n * @remarks Encoded as base64 string. */\n sdkBlob?: string;\n}\n\n/** Metadata returned to client when grounding is enabled. */\nexport declare interface GroundingMetadata {\n /** Optional. Output only. Resource name of the Google Maps widget context token to be used with the PlacesContextElement widget to render contextual data. This is populated only for Google Maps grounding. */\n googleMapsWidgetContextToken?: string;\n /** List of supporting references retrieved from specified grounding source. */\n groundingChunks?: GroundingChunk[];\n /** Optional. List of grounding support. */\n groundingSupports?: GroundingSupport[];\n /** Optional. Output only. Retrieval metadata. */\n retrievalMetadata?: RetrievalMetadata;\n /** Optional. Queries executed by the retrieval tools. */\n retrievalQueries?: string[];\n /** Optional. Google search entry for the following-up web searches. */\n searchEntryPoint?: SearchEntryPoint;\n /** Optional. Web search queries for the following-up web search. */\n webSearchQueries?: string[];\n}\n\n/** Candidate for the logprobs token and score. */\nexport declare interface LogprobsResultCandidate {\n /** The candidate's log probability. */\n logProbability?: number;\n /** The candidate's token string value. */\n token?: string;\n /** The candidate's token id value. */\n tokenId?: number;\n}\n\n/** Candidates with top log probabilities at each decoding step. */\nexport declare interface LogprobsResultTopCandidates {\n /** Sorted by log probability in descending order. */\n candidates?: LogprobsResultCandidate[];\n}\n\n/** Logprobs Result */\nexport declare interface LogprobsResult {\n /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */\n chosenCandidates?: LogprobsResultCandidate[];\n /** Length = total number of decoding steps. */\n topCandidates?: LogprobsResultTopCandidates[];\n}\n\n/** Safety rating corresponding to the generated content. */\nexport declare interface SafetyRating {\n /** Output only. Indicates whether the content was filtered out because of this rating. */\n blocked?: boolean;\n /** Output only. Harm category. */\n category?: HarmCategory;\n /** Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If minors are detected in the output image, the threshold of each safety category will be overwritten if user sets a lower threshold. */\n overwrittenThreshold?: HarmBlockThreshold;\n /** Output only. Harm probability levels in the content. */\n probability?: HarmProbability;\n /** Output only. Harm probability score. */\n probabilityScore?: number;\n /** Output only. Harm severity levels in the content. */\n severity?: HarmSeverity;\n /** Output only. Harm severity score. */\n severityScore?: number;\n}\n\n/** A response candidate generated from the model. */\nexport declare interface Candidate {\n /** Contains the multi-part content of the response.\n */\n content?: Content;\n /** Source attribution of the generated content.\n */\n citationMetadata?: CitationMetadata;\n /** Describes the reason the model stopped generating tokens.\n */\n finishMessage?: string;\n /** Number of tokens for this candidate.\n */\n tokenCount?: number;\n /** The reason why the model stopped generating tokens.\n If empty, the model has not stopped generating the tokens.\n */\n finishReason?: FinishReason;\n /** Metadata related to url context retrieval tool. */\n urlContextMetadata?: UrlContextMetadata;\n /** Output only. Average log probability score of the candidate. */\n avgLogprobs?: number;\n /** Output only. Metadata specifies sources used to ground generated content. */\n groundingMetadata?: GroundingMetadata;\n /** Output only. Index of the candidate. */\n index?: number;\n /** Output only. Log-likelihood scores for the response tokens and top tokens */\n logprobsResult?: LogprobsResult;\n /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Content filter results for a prompt sent in the request. */\nexport class GenerateContentResponsePromptFeedback {\n /** Output only. Blocked reason. */\n blockReason?: BlockedReason;\n /** Output only. A readable block reason message. */\n blockReasonMessage?: string;\n /** Output only. Safety ratings. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Represents token counting info for a single modality. */\nexport declare interface ModalityTokenCount {\n /** The modality associated with this token count. */\n modality?: MediaModality;\n /** Number of tokens. */\n tokenCount?: number;\n}\n\n/** Usage metadata about response(s). */\nexport class GenerateContentResponseUsageMetadata {\n /** Output only. List of modalities of the cached content in the request input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens in the cached part in the input (the cached content). */\n cachedContentTokenCount?: number;\n /** Number of tokens in the response(s). */\n candidatesTokenCount?: number;\n /** Output only. List of modalities that were returned in the response. */\n candidatesTokensDetails?: ModalityTokenCount[];\n /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Output only. List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens present in thoughts output. */\n thoughtsTokenCount?: number;\n /** Output only. Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Output only. List of modalities that were processed for tool-use request inputs. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Total token count for prompt, response candidates, and tool-use prompts (if present). */\n totalTokenCount?: number;\n /** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */\n trafficType?: TrafficType;\n}\n\n/** Response message for PredictionService.GenerateContent. */\nexport class GenerateContentResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Response variations returned by the model.\n */\n candidates?: Candidate[];\n /** Timestamp when the request is made to the server.\n */\n createTime?: string;\n /** The history of automatic function calling.\n */\n automaticFunctionCallingHistory?: Content[];\n /** Output only. The model version used to generate the response. */\n modelVersion?: string;\n /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */\n promptFeedback?: GenerateContentResponsePromptFeedback;\n /** Output only. response_id is used to identify each response. It is the encoding of the event_id. */\n responseId?: string;\n /** Usage metadata about the response(s). */\n usageMetadata?: GenerateContentResponseUsageMetadata;\n /**\n * Returns the concatenation of all text parts from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the text from the first\n * one will be returned.\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n * If there are thought parts in the response, the concatenation of all text\n * parts excluding the thought parts will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'Why is the sky blue?',\n * });\n *\n * console.debug(response.text);\n * ```\n */\n get text(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning text from the first one.',\n );\n }\n let text = '';\n let anyTextPartText = false;\n const nonTextParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartText = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartText ? text : undefined;\n }\n\n /**\n * Returns the concatenation of all inline data parts from the first candidate\n * in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the inline data from the\n * first one will be returned. If there are non-inline data parts in the\n * response, the concatenation of all inline data parts will be returned, and\n * a warning will be logged.\n */\n get data(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning data from the first one.',\n );\n }\n let data = '';\n const nonDataParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'inlineData' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonDataParts.push(fieldName);\n }\n }\n if (part.inlineData && typeof part.inlineData.data === 'string') {\n data += atob(part.inlineData.data);\n }\n }\n if (nonDataParts.length > 0) {\n console.warn(\n `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`,\n );\n }\n return data.length > 0 ? btoa(data) : undefined;\n }\n\n /**\n * Returns the function calls from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the function calls from\n * the first one will be returned.\n * If there are no function calls in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const controlLightFunctionDeclaration: FunctionDeclaration = {\n * name: 'controlLight',\n * parameters: {\n * type: Type.OBJECT,\n * description: 'Set the brightness and color temperature of a room light.',\n * properties: {\n * brightness: {\n * type: Type.NUMBER,\n * description:\n * 'Light level from 0 to 100. Zero is off and 100 is full brightness.',\n * },\n * colorTemperature: {\n * type: Type.STRING,\n * description:\n * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.',\n * },\n * },\n * required: ['brightness', 'colorTemperature'],\n * };\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'Dim the lights so the room feels cozy and warm.',\n * config: {\n * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}],\n * toolConfig: {\n * functionCallingConfig: {\n * mode: FunctionCallingConfigMode.ANY,\n * allowedFunctionNames: ['controlLight'],\n * },\n * },\n * },\n * });\n * console.debug(JSON.stringify(response.functionCalls));\n * ```\n */\n get functionCalls(): FunctionCall[] | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning function calls from the first one.',\n );\n }\n const functionCalls = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.functionCall)\n .map((part) => part.functionCall)\n .filter(\n (functionCall): functionCall is FunctionCall =>\n functionCall !== undefined,\n );\n if (functionCalls?.length === 0) {\n return undefined;\n }\n return functionCalls;\n }\n /**\n * Returns the first executable code from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the executable code from\n * the first one will be returned.\n * If there are no executable code in the response, undefined will be\n * returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.executableCode);\n * ```\n */\n get executableCode(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning executable code from the first one.',\n );\n }\n const executableCode = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.executableCode)\n .map((part) => part.executableCode)\n .filter(\n (executableCode): executableCode is ExecutableCode =>\n executableCode !== undefined,\n );\n if (executableCode?.length === 0) {\n return undefined;\n }\n\n return executableCode?.[0]?.code;\n }\n /**\n * Returns the first code execution result from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the code execution result from\n * the first one will be returned.\n * If there are no code execution result in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.codeExecutionResult);\n * ```\n */\n get codeExecutionResult(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning code execution result from the first one.',\n );\n }\n const codeExecutionResult = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.codeExecutionResult)\n .map((part) => part.codeExecutionResult)\n .filter(\n (codeExecutionResult): codeExecutionResult is CodeExecutionResult =>\n codeExecutionResult !== undefined,\n );\n if (codeExecutionResult?.length === 0) {\n return undefined;\n }\n return codeExecutionResult?.[0]?.output;\n }\n}\n\nexport type ReferenceImage =\n | RawReferenceImage\n | MaskReferenceImage\n | ControlReferenceImage\n | StyleReferenceImage\n | SubjectReferenceImage;\n\n/** Parameters for the request to edit an image. */\nexport declare interface EditImageParameters {\n /** The model to use. */\n model: string;\n /** A text description of the edit to apply to the image. */\n prompt: string;\n /** The reference images for Imagen 3 editing. */\n referenceImages: ReferenceImage[];\n /** Configuration for editing. */\n config?: EditImageConfig;\n}\n\n/** Optional parameters for the embed_content method. */\nexport declare interface EmbedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Type of task for which the embedding will be used.\n */\n taskType?: string;\n /** Title for the text. Only applicable when TaskType is\n `RETRIEVAL_DOCUMENT`.\n */\n title?: string;\n /** Reduced dimension for the output embedding. If set,\n excessive values in the output embedding are truncated from the end.\n Supported by newer models since 2024 only. You cannot set this value if\n using the earlier model (`models/embedding-001`).\n */\n outputDimensionality?: number;\n /** Vertex API only. The MIME type of the input.\n */\n mimeType?: string;\n /** Vertex API only. Whether to silently truncate inputs longer than\n the max sequence length. If this option is set to false, oversized inputs\n will lead to an INVALID_ARGUMENT error, similar to other text APIs.\n */\n autoTruncate?: boolean;\n}\n\n/** Parameters for the embed_content method. */\nexport declare interface EmbedContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The content to embed. Only the `parts.text` fields will be counted.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional parameters.\n */\n config?: EmbedContentConfig;\n}\n\n/** Statistics of the input text associated with the result of content embedding. */\nexport declare interface ContentEmbeddingStatistics {\n /** Vertex API only. If the input text was truncated due to having\n a length longer than the allowed maximum input.\n */\n truncated?: boolean;\n /** Vertex API only. Number of tokens of the input text.\n */\n tokenCount?: number;\n}\n\n/** The embedding generated from an input content. */\nexport declare interface ContentEmbedding {\n /** A list of floats representing an embedding.\n */\n values?: number[];\n /** Vertex API only. Statistics of the input text associated with this\n embedding.\n */\n statistics?: ContentEmbeddingStatistics;\n}\n\n/** Request-level metadata for the Vertex Embed Content API. */\nexport declare interface EmbedContentMetadata {\n /** Vertex API only. The total number of billable characters included\n in the request.\n */\n billableCharacterCount?: number;\n}\n\n/** Response for the embed_content method. */\nexport class EmbedContentResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** The embeddings for each request, in the same order as provided in\n the batch request.\n */\n embeddings?: ContentEmbedding[];\n /** Vertex API only. Metadata about the request.\n */\n metadata?: EmbedContentMetadata;\n}\n\n/** The config for generating an images. */\nexport declare interface GenerateImagesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage URI used to store the generated images.\n */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images.\n */\n negativePrompt?: string;\n /** Number of images to generate.\n */\n numberOfImages?: number;\n /** Aspect ratio of the generated images. Supported values are\n \"1:1\", \"3:4\", \"4:3\", \"9:16\", and \"16:9\".\n */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality.\n */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true.\n */\n seed?: number;\n /** Filter level for safety filtering.\n */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model.\n */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response.\n */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response.\n */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt.\n */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image.\n */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only).\n */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images.\n */\n addWatermark?: boolean;\n /** The size of the largest dimension of the generated image.\n Supported sizes are 1K and 2K (not supported for Imagen 3 models).\n */\n imageSize?: string;\n /** Whether to use the prompt rewriting logic.\n */\n enhancePrompt?: boolean;\n}\n\n/** The parameters for generating images. */\nexport declare interface GenerateImagesParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Text prompt that typically describes the images to output.\n */\n prompt: string;\n /** Configuration for generating images.\n */\n config?: GenerateImagesConfig;\n}\n\n/** An image. */\nexport declare interface Image {\n /** The Cloud Storage URI of the image. ``Image`` can contain a value\n for this field or the ``image_bytes`` field but not both.\n */\n gcsUri?: string;\n /** The image bytes data. ``Image`` can contain a value for this field\n or the ``gcs_uri`` field but not both.\n \n * @remarks Encoded as base64 string. */\n imageBytes?: string;\n /** The MIME type of the image. */\n mimeType?: string;\n}\n\n/** Safety attributes of a GeneratedImage or the user-provided prompt. */\nexport declare interface SafetyAttributes {\n /** List of RAI categories.\n */\n categories?: string[];\n /** List of scores of each categories.\n */\n scores?: number[];\n /** Internal use only.\n */\n contentType?: string;\n}\n\n/** An output image. */\nexport declare interface GeneratedImage {\n /** The output image data.\n */\n image?: Image;\n /** Responsible AI filter reason if the image is filtered out of the\n response.\n */\n raiFilteredReason?: string;\n /** Safety attributes of the image. Lists of RAI categories and their\n scores of each content.\n */\n safetyAttributes?: SafetyAttributes;\n /** The rewritten prompt used for the image generation if the prompt\n enhancer is enabled.\n */\n enhancedPrompt?: string;\n}\n\n/** The output images response. */\nexport class GenerateImagesResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** List of generated images.\n */\n generatedImages?: GeneratedImage[];\n /** Safety attributes of the positive prompt. Only populated if\n ``include_safety_attributes`` is set to True.\n */\n positivePromptSafetyAttributes?: SafetyAttributes;\n}\n\n/** Configuration for a Mask reference image. */\nexport declare interface MaskReferenceConfig {\n /** Prompts the model to generate a mask instead of you needing to\n provide one (unless MASK_MODE_USER_PROVIDED is used). */\n maskMode?: MaskReferenceMode;\n /** A list of up to 5 class ids to use for semantic segmentation.\n Automatically creates an image mask based on specific objects. */\n segmentationClasses?: number[];\n /** Dilation percentage of the mask provided.\n Float between 0 and 1. */\n maskDilation?: number;\n}\n\n/** Configuration for a Control reference image. */\nexport declare interface ControlReferenceConfig {\n /** The type of control reference image to use. */\n controlType?: ControlReferenceType;\n /** Defaults to False. When set to True, the control image will be\n computed by the model based on the control type. When set to False,\n the control image must be provided by the user. */\n enableControlImageComputation?: boolean;\n}\n\n/** Configuration for a Style reference image. */\nexport declare interface StyleReferenceConfig {\n /** A text description of the style to use for the generated image. */\n styleDescription?: string;\n}\n\n/** Configuration for a Subject reference image. */\nexport declare interface SubjectReferenceConfig {\n /** The subject type of a subject reference image. */\n subjectType?: SubjectReferenceType;\n /** Subject description for the image. */\n subjectDescription?: string;\n}\n\n/** Configuration for editing an image. */\nexport declare interface EditImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage URI used to store the generated images.\n */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images.\n */\n negativePrompt?: string;\n /** Number of images to generate.\n */\n numberOfImages?: number;\n /** Aspect ratio of the generated images. Supported values are\n \"1:1\", \"3:4\", \"4:3\", \"9:16\", and \"16:9\".\n */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality.\n */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true.\n */\n seed?: number;\n /** Filter level for safety filtering.\n */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model.\n */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response.\n */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response.\n */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt.\n */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image.\n */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only).\n */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images.\n */\n addWatermark?: boolean;\n /** Describes the editing mode for the request. */\n editMode?: EditMode;\n /** The number of sampling steps. A higher value has better image\n quality, while a lower value has better latency. */\n baseSteps?: number;\n}\n\n/** Response for the request to edit an image. */\nexport class EditImageResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Generated images. */\n generatedImages?: GeneratedImage[];\n}\n\nexport class UpscaleImageResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Generated images. */\n generatedImages?: GeneratedImage[];\n}\n\n/** An image of the product. */\nexport declare interface ProductImage {\n /** An image of the product to be recontextualized. */\n productImage?: Image;\n}\n\n/** A set of source input(s) for image recontextualization. */\nexport declare interface RecontextImageSource {\n /** A text prompt for guiding the model during image\n recontextualization. Not supported for Virtual Try-On. */\n prompt?: string;\n /** Image of the person or subject who will be wearing the\n product(s). */\n personImage?: Image;\n /** A list of product images. */\n productImages?: ProductImage[];\n}\n\n/** Configuration for recontextualizing an image. */\nexport declare interface RecontextImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Number of images to generate. */\n numberOfImages?: number;\n /** The number of sampling steps. A higher value has better image\n quality, while a lower value has better latency. */\n baseSteps?: number;\n /** Cloud Storage URI used to store the generated images. */\n outputGcsUri?: string;\n /** Random seed for image generation. */\n seed?: number;\n /** Filter level for safety filtering. */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Whether allow to generate person images, and restrict to specific\n ages. */\n personGeneration?: PersonGeneration;\n /** MIME type of the generated image. */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only). */\n outputCompressionQuality?: number;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n}\n\n/** The parameters for recontextualizing an image. */\nexport declare interface RecontextImageParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** A set of source input(s) for image recontextualization. */\n source: RecontextImageSource;\n /** Configuration for image recontextualization. */\n config?: RecontextImageConfig;\n}\n\n/** The output images response. */\nexport class RecontextImageResponse {\n /** List of generated images. */\n generatedImages?: GeneratedImage[];\n}\n\n/** An image mask representing a brush scribble. */\nexport declare interface ScribbleImage {\n /** The brush scribble to guide segmentation. Valid for the interactive mode. */\n image?: Image;\n}\n\n/** A set of source input(s) for image segmentation. */\nexport declare interface SegmentImageSource {\n /** A text prompt for guiding the model during image segmentation.\n Required for prompt mode and semantic mode, disallowed for other modes. */\n prompt?: string;\n /** The image to be segmented. */\n image?: Image;\n /** The brush scribble to guide segmentation.\n Required for the interactive mode, disallowed for other modes. */\n scribbleImage?: ScribbleImage;\n}\n\n/** Configuration for segmenting an image. */\nexport declare interface SegmentImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The segmentation mode to use. */\n mode?: SegmentMode;\n /** The maximum number of predictions to return up to, by top\n confidence score. */\n maxPredictions?: number;\n /** The confidence score threshold for the detections as a decimal\n value. Only predictions with a confidence score higher than this\n threshold will be returned. */\n confidenceThreshold?: number;\n /** A decimal value representing how much dilation to apply to the\n masks. 0 for no dilation. 1.0 means the masked area covers the whole\n image. */\n maskDilation?: number;\n /** The binary color threshold to apply to the masks. The threshold\n can be set to a decimal value between 0 and 255 non-inclusive.\n Set to -1 for no binary color thresholding. */\n binaryColorThreshold?: number;\n}\n\n/** The parameters for segmenting an image. */\nexport declare interface SegmentImageParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** A set of source input(s) for image segmentation. */\n source: SegmentImageSource;\n /** Configuration for image segmentation. */\n config?: SegmentImageConfig;\n}\n\n/** An entity representing the segmented area. */\nexport declare interface EntityLabel {\n /** The label of the segmented entity. */\n label?: string;\n /** The confidence score of the detected label. */\n score?: number;\n}\n\n/** A generated image mask. */\nexport declare interface GeneratedImageMask {\n /** The generated image mask. */\n mask?: Image;\n /** The detected entities on the segmented area. */\n labels?: EntityLabel[];\n}\n\n/** The output images response. */\nexport class SegmentImageResponse {\n /** List of generated image masks.\n */\n generatedMasks?: GeneratedImageMask[];\n}\n\n/** Optional parameters for models.get method. */\nexport declare interface GetModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\nexport declare interface GetModelParameters {\n model: string;\n /** Optional parameters for the request. */\n config?: GetModelConfig;\n}\n\n/** An endpoint where you deploy models. */\nexport declare interface Endpoint {\n /** Resource name of the endpoint. */\n name?: string;\n /** ID of the model that's deployed to the endpoint. */\n deployedModelId?: string;\n}\n\n/** A tuned machine learning model. */\nexport declare interface TunedModelInfo {\n /** ID of the base model that you want to tune. */\n baseModel?: string;\n /** Date and time when the base model was created. */\n createTime?: string;\n /** Date and time when the base model was last updated. */\n updateTime?: string;\n}\n\n/** Describes the machine learning model version checkpoint. */\nexport declare interface Checkpoint {\n /** The ID of the checkpoint.\n */\n checkpointId?: string;\n /** The epoch of the checkpoint.\n */\n epoch?: string;\n /** The step of the checkpoint.\n */\n step?: string;\n}\n\n/** A trained machine learning model. */\nexport declare interface Model {\n /** Resource name of the model. */\n name?: string;\n /** Display name of the model. */\n displayName?: string;\n /** Description of the model. */\n description?: string;\n /** Version ID of the model. A new version is committed when a new\n model version is uploaded or trained under an existing model ID. The\n version ID is an auto-incrementing decimal number in string\n representation. */\n version?: string;\n /** List of deployed models created from this base model. Note that a\n model could have been deployed to endpoints in different locations. */\n endpoints?: Endpoint[];\n /** Labels with user-defined metadata to organize your models. */\n labels?: Record;\n /** Information about the tuned model from the base model. */\n tunedModelInfo?: TunedModelInfo;\n /** The maximum number of input tokens that the model can handle. */\n inputTokenLimit?: number;\n /** The maximum number of output tokens that the model can generate. */\n outputTokenLimit?: number;\n /** List of actions that are supported by the model. */\n supportedActions?: string[];\n /** The default checkpoint id of a model version.\n */\n defaultCheckpointId?: string;\n /** The checkpoints of the model. */\n checkpoints?: Checkpoint[];\n}\n\nexport declare interface ListModelsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n /** Set true to list base models, false to list tuned models. */\n queryBase?: boolean;\n}\n\nexport declare interface ListModelsParameters {\n config?: ListModelsConfig;\n}\n\nexport class ListModelsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n models?: Model[];\n}\n\n/** Configuration for updating a tuned model. */\nexport declare interface UpdateModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n displayName?: string;\n description?: string;\n defaultCheckpointId?: string;\n}\n\n/** Configuration for updating a tuned model. */\nexport declare interface UpdateModelParameters {\n model: string;\n config?: UpdateModelConfig;\n}\n\n/** Configuration for deleting a tuned model. */\nexport declare interface DeleteModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for deleting a tuned model. */\nexport declare interface DeleteModelParameters {\n model: string;\n /** Optional parameters for the request. */\n config?: DeleteModelConfig;\n}\n\nexport class DeleteModelResponse {}\n\n/** Config for thinking features. */\nexport declare interface GenerationConfigThinkingConfig {\n /** Optional. Indicates whether to include thoughts in the response. If true, thoughts are returned only when available. */\n includeThoughts?: boolean;\n /** Optional. Indicates the thinking budget in tokens. */\n thinkingBudget?: number;\n}\n\n/** Generation config. */\nexport declare interface GenerationConfig {\n /** Optional. Config for model selection. */\n modelSelectionConfig?: ModelSelectionConfig;\n /** Optional. If enabled, audio timestamp will be included in the request to the model. */\n audioTimestamp?: boolean;\n /** Optional. Number of candidates to generate. */\n candidateCount?: number;\n /** Optional. If enabled, the model will detect emotions and adapt its responses accordingly. */\n enableAffectiveDialog?: boolean;\n /** Optional. Frequency penalties. */\n frequencyPenalty?: number;\n /** Optional. Logit probabilities. */\n logprobs?: number;\n /** Optional. The maximum number of output tokens to generate per message. */\n maxOutputTokens?: number;\n /** Optional. If specified, the media resolution specified will be used. */\n mediaResolution?: MediaResolution;\n /** Optional. Positive penalties. */\n presencePenalty?: number;\n /** Optional. Output schema of the generated response. This is an alternative to `response_schema` that accepts [JSON Schema](https://json-schema.org/). If set, `response_schema` must be omitted, but `response_mime_type` is required. While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` - `type` - `format` - `title` - `description` - `enum` (for strings and numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - `properties` - `additionalProperties` - `required` The non-standard `propertyOrdering` property may also be set. Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If `$ref` is set on a sub-schema, no other properties, except for than those starting as a `$`, may be set. */\n responseJsonSchema?: unknown;\n /** Optional. If true, export the logprobs results in response. */\n responseLogprobs?: boolean;\n /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */\n responseMimeType?: string;\n /** Optional. The modalities of the response. */\n responseModalities?: Modality[];\n /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */\n responseSchema?: Schema;\n /** Optional. Routing configuration. */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Optional. Seed. */\n seed?: number;\n /** Optional. The speech generation config. */\n speechConfig?: SpeechConfig;\n /** Optional. Stop sequences. */\n stopSequences?: string[];\n /** Optional. Controls the randomness of predictions. */\n temperature?: number;\n /** Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking. */\n thinkingConfig?: GenerationConfigThinkingConfig;\n /** Optional. If specified, top-k sampling will be used. */\n topK?: number;\n /** Optional. If specified, nucleus sampling will be used. */\n topP?: number;\n}\n\n/** Config for the count_tokens method. */\nexport declare interface CountTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Instructions for the model to steer it toward better performance.\n */\n systemInstruction?: ContentUnion;\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: Tool[];\n /** Configuration that the model uses to generate the response. Not\n supported by the Gemini Developer API.\n */\n generationConfig?: GenerationConfig;\n}\n\n/** Parameters for counting tokens. */\nexport declare interface CountTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Configuration for counting tokens. */\n config?: CountTokensConfig;\n}\n\n/** Response for counting tokens. */\nexport class CountTokensResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Total number of tokens. */\n totalTokens?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n}\n\n/** Optional parameters for computing tokens. */\nexport declare interface ComputeTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for computing tokens. */\nexport declare interface ComputeTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Optional parameters for the request.\n */\n config?: ComputeTokensConfig;\n}\n\n/** Tokens info with a list of tokens and the corresponding list of token ids. */\nexport declare interface TokensInfo {\n /** Optional. Optional fields for the role from the corresponding Content. */\n role?: string;\n /** A list of token ids from the input. */\n tokenIds?: string[];\n /** A list of tokens from the input.\n * @remarks Encoded as base64 string. */\n tokens?: string[];\n}\n\n/** Response for computing tokens. */\nexport class ComputeTokensResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */\n tokensInfo?: TokensInfo[];\n}\n\n/** A generated video. */\nexport declare interface Video {\n /** Path to another storage. */\n uri?: string;\n /** Video bytes.\n * @remarks Encoded as base64 string. */\n videoBytes?: string;\n /** Video encoding, for example \"video/mp4\". */\n mimeType?: string;\n}\n\n/** A reference image for video generation. */\nexport declare interface VideoGenerationReferenceImage {\n /** The reference image.\n */\n image?: Image;\n /** The type of the reference image, which defines how the reference\n image will be used to generate the video. Supported values are 'asset'\n or 'style'. */\n referenceType?: string;\n}\n\n/** Configuration for generating videos. */\nexport declare interface GenerateVideosConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Number of output videos. */\n numberOfVideos?: number;\n /** The gcs bucket where to save the generated videos. */\n outputGcsUri?: string;\n /** Frames per second for video generation. */\n fps?: number;\n /** Duration of the clip for video generation in seconds. */\n durationSeconds?: number;\n /** The RNG seed. If RNG seed is exactly same for each request with unchanged inputs, the prediction results will be consistent. Otherwise, a random RNG seed will be used each time to produce a different result. */\n seed?: number;\n /** The aspect ratio for the generated video. 16:9 (landscape) and 9:16 (portrait) are supported. */\n aspectRatio?: string;\n /** The resolution for the generated video. 720p and 1080p are supported. */\n resolution?: string;\n /** Whether allow to generate person videos, and restrict to specific ages. Supported values are: dont_allow, allow_adult. */\n personGeneration?: string;\n /** The pubsub topic where to publish the video generation progress. */\n pubsubTopic?: string;\n /** Optional field in addition to the text content. Negative prompts can be explicitly stated here to help generate the video. */\n negativePrompt?: string;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n /** Whether to generate audio along with the video. */\n generateAudio?: boolean;\n /** Image to use as the last frame of generated videos. Only supported for image to video use cases. */\n lastFrame?: Image;\n /** The images to use as the references to generate the videos.\n If this field is provided, the text prompt field must also be provided.\n The image, video, or last_frame field are not supported. Each image must\n be associated with a type. Veo 2 supports up to 3 asset images *or* 1\n style image. */\n referenceImages?: VideoGenerationReferenceImage[];\n /** Compression quality of the generated videos. */\n compressionQuality?: VideoCompressionQuality;\n}\n\n/** Class that represents the parameters for generating videos. */\nexport declare interface GenerateVideosParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The text prompt for generating the videos. Optional for image to video use cases. */\n prompt?: string;\n /** The input image for generating the videos.\n Optional if prompt or video is provided. */\n image?: Image;\n /** The input video for video extension use cases.\n Optional if prompt or image is provided. */\n video?: Video;\n /** Configuration for generating videos. */\n config?: GenerateVideosConfig;\n}\n\n/** A generated video. */\nexport declare interface GeneratedVideo {\n /** The output video */\n video?: Video;\n}\n\n/** Response with generated videos. */\nexport class GenerateVideosResponse {\n /** List of the generated videos */\n generatedVideos?: GeneratedVideo[];\n /** Returns if any videos were filtered due to RAI policies. */\n raiMediaFilteredCount?: number;\n /** Returns rai failure reasons if any. */\n raiMediaFilteredReasons?: string[];\n}\n\n/** Optional parameters for tunings.get method. */\nexport declare interface GetTuningJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the get method. */\nexport declare interface GetTuningJobParameters {\n name: string;\n /** Optional parameters for the request. */\n config?: GetTuningJobConfig;\n}\n\n/** TunedModelCheckpoint for the Tuned Model of a Tuning Job. */\nexport declare interface TunedModelCheckpoint {\n /** The ID of the checkpoint.\n */\n checkpointId?: string;\n /** The epoch of the checkpoint.\n */\n epoch?: string;\n /** The step of the checkpoint.\n */\n step?: string;\n /** The Endpoint resource name that the checkpoint is deployed to.\n Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`.\n */\n endpoint?: string;\n}\n\nexport declare interface TunedModel {\n /** Output only. The resource name of the TunedModel. Format: `projects/{project}/locations/{location}/models/{model}@{version_id}` When tuning from a base model, the version_id will be 1. For continuous tuning, the version id will be incremented by 1 from the last version id in the parent model. E.g., `projects/{project}/locations/{location}/models/{model}@{last_version_id + 1}` */\n model?: string;\n /** Output only. A resource name of an Endpoint. Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. */\n endpoint?: string;\n /** The checkpoints associated with this TunedModel.\n This field is only populated for tuning jobs that enable intermediate\n checkpoints. */\n checkpoints?: TunedModelCheckpoint[];\n}\n\n/** The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). */\nexport declare interface GoogleRpcStatus {\n /** The status code, which should be an enum value of google.rpc.Code. */\n code?: number;\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */\n message?: string;\n}\n\n/** A pre-tuned model for continuous tuning. */\nexport declare interface PreTunedModel {\n /** Output only. The name of the base model this PreTunedModel was tuned from. */\n baseModel?: string;\n /** Optional. The source checkpoint id. If not specified, the default checkpoint will be used. */\n checkpointId?: string;\n /** The resource name of the Model. E.g., a model resource name with a specified version id or alias: `projects/{project}/locations/{location}/models/{model}@{version_id}` `projects/{project}/locations/{location}/models/{model}@{alias}` Or, omit the version id to use the default version: `projects/{project}/locations/{location}/models/{model}` */\n tunedModelName?: string;\n}\n\n/** Hyperparameters for SFT. */\nexport declare interface SupervisedHyperParameters {\n /** Optional. Adapter size for tuning. */\n adapterSize?: AdapterSize;\n /** Optional. Batch size for tuning. This feature is only available for open source models. */\n batchSize?: string;\n /** Optional. Number of complete passes the model makes over the entire training dataset during training. */\n epochCount?: string;\n /** Optional. Learning rate for tuning. Mutually exclusive with `learning_rate_multiplier`. This feature is only available for open source models. */\n learningRate?: number;\n /** Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with `learning_rate`. This feature is only available for 1P models. */\n learningRateMultiplier?: number;\n}\n\n/** Tuning Spec for Supervised Tuning for first party models. */\nexport declare interface SupervisedTuningSpec {\n /** Optional. If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. Default is false. */\n exportLastCheckpointOnly?: boolean;\n /** Optional. Hyperparameters for SFT. */\n hyperParameters?: SupervisedHyperParameters;\n /** Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n trainingDatasetUri?: string;\n /** Tuning mode. */\n tuningMode?: TuningMode;\n /** Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n validationDatasetUri?: string;\n}\n\n/** Dataset bucket used to create a histogram for the distribution given a population of values. */\nexport declare interface DatasetDistributionDistributionBucket {\n /** Output only. Number of values in the bucket. */\n count?: string;\n /** Output only. Left bound of the bucket. */\n left?: number;\n /** Output only. Right bound of the bucket. */\n right?: number;\n}\n\n/** Distribution computed over a tuning dataset. */\nexport declare interface DatasetDistribution {\n /** Output only. Defines the histogram bucket. */\n buckets?: DatasetDistributionDistributionBucket[];\n /** Output only. The maximum of the population values. */\n max?: number;\n /** Output only. The arithmetic mean of the values in the population. */\n mean?: number;\n /** Output only. The median of the values in the population. */\n median?: number;\n /** Output only. The minimum of the population values. */\n min?: number;\n /** Output only. The 5th percentile of the values in the population. */\n p5?: number;\n /** Output only. The 95th percentile of the values in the population. */\n p95?: number;\n /** Output only. Sum of a given population of values. */\n sum?: number;\n}\n\n/** Statistics computed over a tuning dataset. */\nexport declare interface DatasetStats {\n /** Output only. Number of billable characters in the tuning dataset. */\n totalBillableCharacterCount?: string;\n /** Output only. Number of tuning characters in the tuning dataset. */\n totalTuningCharacterCount?: string;\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user messages in the training dataset uri. */\n userDatasetExamples?: Content[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the messages per example. */\n userMessagePerExampleDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: DatasetDistribution;\n}\n\n/** Statistics computed for datasets used for distillation. */\nexport declare interface DistillationDataStats {\n /** Output only. Statistics computed for the training dataset. */\n trainingDatasetStats?: DatasetStats;\n}\n\n/** Completion and its preference score. */\nexport declare interface GeminiPreferenceExampleCompletion {\n /** Single turn completion for the given prompt. */\n completion?: Content;\n /** The score for the given completion. */\n score?: number;\n}\n\n/** Input example for preference optimization. */\nexport declare interface GeminiPreferenceExample {\n /** List of completions for a given prompt. */\n completions?: GeminiPreferenceExampleCompletion[];\n /** Multi-turn contents that represents the Prompt. */\n contents?: Content[];\n}\n\n/** Statistics computed for datasets used for preference optimization. */\nexport declare interface PreferenceOptimizationDataStats {\n /** Output only. Dataset distributions for scores variance per example. */\n scoreVariancePerExampleDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for scores. */\n scoresDistribution?: DatasetDistribution;\n /** Output only. Number of billable tokens in the tuning dataset. */\n totalBillableTokenCount?: string;\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user examples in the training dataset. */\n userDatasetExamples?: GeminiPreferenceExample[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: DatasetDistribution;\n}\n\n/** Dataset bucket used to create a histogram for the distribution given a population of values. */\nexport declare interface SupervisedTuningDatasetDistributionDatasetBucket {\n /** Output only. Number of values in the bucket. */\n count?: number;\n /** Output only. Left bound of the bucket. */\n left?: number;\n /** Output only. Right bound of the bucket. */\n right?: number;\n}\n\n/** Dataset distribution for Supervised Tuning. */\nexport declare interface SupervisedTuningDatasetDistribution {\n /** Output only. Sum of a given population of values that are billable. */\n billableSum?: string;\n /** Output only. Defines the histogram bucket. */\n buckets?: SupervisedTuningDatasetDistributionDatasetBucket[];\n /** Output only. The maximum of the population values. */\n max?: number;\n /** Output only. The arithmetic mean of the values in the population. */\n mean?: number;\n /** Output only. The median of the values in the population. */\n median?: number;\n /** Output only. The minimum of the population values. */\n min?: number;\n /** Output only. The 5th percentile of the values in the population. */\n p5?: number;\n /** Output only. The 95th percentile of the values in the population. */\n p95?: number;\n /** Output only. Sum of a given population of values. */\n sum?: string;\n}\n\n/** Tuning data statistics for Supervised Tuning. */\nexport declare interface SupervisedTuningDataStats {\n /** Output only. For each index in `truncated_example_indices`, the user-facing reason why the example was dropped. */\n droppedExampleReasons?: string[];\n /** Output only. Number of billable characters in the tuning dataset. */\n totalBillableCharacterCount?: string;\n /** Output only. Number of billable tokens in the tuning dataset. */\n totalBillableTokenCount?: string;\n /** Output only. The number of examples in the dataset that have been dropped. An example can be dropped for reasons including: too many tokens, contains an invalid image, contains too many images, etc. */\n totalTruncatedExampleCount?: string;\n /** Output only. Number of tuning characters in the tuning dataset. */\n totalTuningCharacterCount?: string;\n /** Output only. A partial sample of the indices (starting from 1) of the dropped examples. */\n truncatedExampleIndices?: string[];\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user messages in the training dataset uri. */\n userDatasetExamples?: Content[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: SupervisedTuningDatasetDistribution;\n /** Output only. Dataset distributions for the messages per example. */\n userMessagePerExampleDistribution?: SupervisedTuningDatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: SupervisedTuningDatasetDistribution;\n}\n\n/** The tuning data statistic values for TuningJob. */\nexport declare interface TuningDataStats {\n /** Output only. Statistics for distillation. */\n distillationDataStats?: DistillationDataStats;\n /** Output only. Statistics for preference optimization. */\n preferenceOptimizationDataStats?: PreferenceOptimizationDataStats;\n /** The SFT Tuning data stats. */\n supervisedTuningDataStats?: SupervisedTuningDataStats;\n}\n\n/** Represents a customer-managed encryption key spec that can be applied to a top-level resource. */\nexport declare interface EncryptionSpec {\n /** Required. The Cloud KMS resource identifier of the customer managed encryption key used to protect a resource. Has the form: `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`. The key needs to be in the same region as where the compute resource is created. */\n kmsKeyName?: string;\n}\n\n/** Tuning spec for Partner models. */\nexport declare interface PartnerModelTuningSpec {\n /** Hyperparameters for tuning. The accepted hyper_parameters and their valid range of values will differ depending on the base model. */\n hyperParameters?: Record;\n /** Required. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDatasetUri?: string;\n /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */\n validationDatasetUri?: string;\n}\n\n/** A tuning job. */\nexport declare interface TuningJob {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}` */\n name?: string;\n /** Output only. The detailed state of the job. */\n state?: JobState;\n /** Output only. Time when the TuningJob was created. */\n createTime?: string;\n /** Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING` state. */\n startTime?: string;\n /** Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`. */\n endTime?: string;\n /** Output only. Time when the TuningJob was most recently updated. */\n updateTime?: string;\n /** Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. */\n error?: GoogleRpcStatus;\n /** Optional. The description of the TuningJob. */\n description?: string;\n /** The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */\n baseModel?: string;\n /** Output only. The tuned model resources associated with this TuningJob. */\n tunedModel?: TunedModel;\n /** The pre-tuned model for continuous tuning. */\n preTunedModel?: PreTunedModel;\n /** Tuning Spec for Supervised Fine Tuning. */\n supervisedTuningSpec?: SupervisedTuningSpec;\n /** Output only. The tuning data statistics associated with this TuningJob. */\n tuningDataStats?: TuningDataStats;\n /** Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with the provided encryption key. */\n encryptionSpec?: EncryptionSpec;\n /** Tuning Spec for open sourced and third party Partner models. */\n partnerModelTuningSpec?: PartnerModelTuningSpec;\n /** Optional. The user-provided path to custom model weights. Set this field to tune a custom model. The path must be a Cloud Storage directory that contains the model weights in .safetensors format along with associated model metadata files. If this field is set, the base_model field must still be set to indicate which base model the custom model is derived from. This feature is only available for open source models. */\n customBaseModel?: string;\n /** Output only. The Experiment associated with this TuningJob. */\n experiment?: string;\n /** Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. */\n labels?: Record;\n /** Optional. Cloud Storage path to the directory where tuning job outputs are written to. This field is only available and required for open source models. */\n outputUri?: string;\n /** Output only. The resource name of the PipelineJob associated with the TuningJob. Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`. */\n pipelineJob?: string;\n /** The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission on this service account. */\n serviceAccount?: string;\n /** Optional. The display name of the TunedModel. The name can be up to 128 characters long and can consist of any UTF-8 characters. */\n tunedModelDisplayName?: string;\n}\n\n/** Configuration for the list tuning jobs method. */\nexport declare interface ListTuningJobsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n}\n\n/** Parameters for the list tuning jobs method. */\nexport declare interface ListTuningJobsParameters {\n config?: ListTuningJobsConfig;\n}\n\n/** Response for the list tuning jobs method. */\nexport class ListTuningJobsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** A token to retrieve the next page of results. Pass to ListTuningJobsRequest.page_token to obtain that page. */\n nextPageToken?: string;\n /** List of TuningJobs in the requested page. */\n tuningJobs?: TuningJob[];\n}\n\nexport declare interface TuningExample {\n /** Text model input. */\n textInput?: string;\n /** The expected model output. */\n output?: string;\n}\n\n/** Supervised fine-tuning training dataset. */\nexport declare interface TuningDataset {\n /** GCS URI of the file containing training dataset in JSONL format. */\n gcsUri?: string;\n /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */\n vertexDatasetResource?: string;\n /** Inline examples with simple input/output text. */\n examples?: TuningExample[];\n}\n\nexport declare interface TuningValidationDataset {\n /** GCS URI of the file containing validation dataset in JSONL format. */\n gcsUri?: string;\n /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */\n vertexDatasetResource?: string;\n}\n\n/** Supervised fine-tuning job creation request - optional fields. */\nexport declare interface CreateTuningJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n validationDataset?: TuningValidationDataset;\n /** The display name of the tuned Model. The name can be up to 128 characters long and can consist of any UTF-8 characters. */\n tunedModelDisplayName?: string;\n /** The description of the TuningJob */\n description?: string;\n /** Number of complete passes the model makes over the entire training dataset during training. */\n epochCount?: number;\n /** Multiplier for adjusting the default learning rate. */\n learningRateMultiplier?: number;\n /** If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. */\n exportLastCheckpointOnly?: boolean;\n /** The optional checkpoint id of the pre-tuned model to use for tuning, if applicable. */\n preTunedModelCheckpointId?: string;\n /** Adapter size for tuning. */\n adapterSize?: AdapterSize;\n /** The batch size hyperparameter for tuning. If not set, a default of 4 or 16 will be used based on the number of training examples. */\n batchSize?: number;\n /** The learning rate hyperparameter for tuning. If not set, a default of 0.001 or 0.0002 will be calculated based on the number of training examples. */\n learningRate?: number;\n}\n\n/** Supervised fine-tuning job creation parameters - optional fields. */\nexport declare interface CreateTuningJobParametersPrivate {\n /** The base model that is being tuned, e.g., \"gemini-2.5-flash\". */\n baseModel?: string;\n /** The PreTunedModel that is being tuned. */\n preTunedModel?: PreTunedModel;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDataset: TuningDataset;\n /** Configuration for the tuning job. */\n config?: CreateTuningJobConfig;\n}\n\n/** A long-running operation. */\nexport declare interface TuningOperation {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n}\n\n/** Optional configuration for cached content creation. */\nexport declare interface CreateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n /** The user-generated meaningful display name of the cached content.\n */\n displayName?: string;\n /** The content to cache.\n */\n contents?: ContentListUnion;\n /** Developer set system instruction.\n */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n */\n tools?: Tool[];\n /** Configuration for the tools to use. This config is shared for all tools.\n */\n toolConfig?: ToolConfig;\n /** The Cloud KMS resource identifier of the customer managed\n encryption key used to protect a resource.\n The key needs to be in the same region as where the compute resource is\n created. See\n https://cloud.google.com/vertex-ai/docs/general/cmek for more\n details. If this is set, then all created CachedContent objects\n will be encrypted with the provided encryption key.\n Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}\n */\n kmsKeyName?: string;\n}\n\n/** Parameters for caches.create method. */\nexport declare interface CreateCachedContentParameters {\n /** ID of the model to use. Example: gemini-2.0-flash */\n model: string;\n /** Configuration that contains optional parameters.\n */\n config?: CreateCachedContentConfig;\n}\n\n/** Metadata on the usage of the cached content. */\nexport declare interface CachedContentUsageMetadata {\n /** Duration of audio in seconds. */\n audioDurationSeconds?: number;\n /** Number of images. */\n imageCount?: number;\n /** Number of text characters. */\n textCount?: number;\n /** Total number of tokens that the cached content consumes. */\n totalTokenCount?: number;\n /** Duration of video in seconds. */\n videoDurationSeconds?: number;\n}\n\n/** A resource used in LLM queries for users to explicitly specify what to cache. */\nexport declare interface CachedContent {\n /** The server-generated resource name of the cached content. */\n name?: string;\n /** The user-generated meaningful display name of the cached content. */\n displayName?: string;\n /** The name of the publisher model to use for cached content. */\n model?: string;\n /** Creation time of the cache entry. */\n createTime?: string;\n /** When the cache entry was last updated in UTC time. */\n updateTime?: string;\n /** Expiration time of the cached content. */\n expireTime?: string;\n /** Metadata on the usage of the cached content. */\n usageMetadata?: CachedContentUsageMetadata;\n}\n\n/** Optional parameters for caches.get method. */\nexport declare interface GetCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for caches.get method. */\nexport declare interface GetCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: GetCachedContentConfig;\n}\n\n/** Optional parameters for caches.delete method. */\nexport declare interface DeleteCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for caches.delete method. */\nexport declare interface DeleteCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: DeleteCachedContentConfig;\n}\n\n/** Empty response for caches.delete method. */\nexport class DeleteCachedContentResponse {}\n\n/** Optional parameters for caches.update method. */\nexport declare interface UpdateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n}\n\nexport declare interface UpdateCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Configuration that contains optional parameters.\n */\n config?: UpdateCachedContentConfig;\n}\n\n/** Config for caches.list method. */\nexport declare interface ListCachedContentsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Parameters for caches.list method. */\nexport declare interface ListCachedContentsParameters {\n /** Configuration that contains optional parameters.\n */\n config?: ListCachedContentsConfig;\n}\n\nexport class ListCachedContentsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n /** List of cached contents.\n */\n cachedContents?: CachedContent[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface ListFilesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Generates the parameters for the list method. */\nexport declare interface ListFilesParameters {\n /** Used to override the default configuration. */\n config?: ListFilesConfig;\n}\n\n/** Status of a File that uses a common error model. */\nexport declare interface FileStatus {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n message?: string;\n /** The status code. 0 for OK, 1 for CANCELLED */\n code?: number;\n}\n\n/** A file uploaded to the API. */\nexport declare interface File {\n /** The `File` resource name. The ID (name excluding the \"files/\" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */\n name?: string;\n /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */\n displayName?: string;\n /** Output only. MIME type of the file. */\n mimeType?: string;\n /** Output only. Size of the file in bytes. */\n sizeBytes?: string;\n /** Output only. The timestamp of when the `File` was created. */\n createTime?: string;\n /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */\n expirationTime?: string;\n /** Output only. The timestamp of when the `File` was last updated. */\n updateTime?: string;\n /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */\n sha256Hash?: string;\n /** Output only. The URI of the `File`. */\n uri?: string;\n /** Output only. The URI of the `File`, only set for downloadable (generated) files. */\n downloadUri?: string;\n /** Output only. Processing state of the File. */\n state?: FileState;\n /** Output only. The source of the `File`. */\n source?: FileSource;\n /** Output only. Metadata for a video. */\n videoMetadata?: Record;\n /** Output only. Error status if File processing failed. */\n error?: FileStatus;\n}\n\n/** Response for the list files method. */\nexport class ListFilesResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** A token to retrieve next page of results. */\n nextPageToken?: string;\n /** The list of files. */\n files?: File[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface CreateFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the private _create method. */\nexport declare interface CreateFileParameters {\n /** The file to be uploaded.\n mime_type: (Required) The MIME type of the file. Must be provided.\n name: (Optional) The name of the file in the destination (e.g.\n 'files/sample-image').\n display_name: (Optional) The display name of the file.\n */\n file: File;\n /** Used to override the default configuration. */\n config?: CreateFileConfig;\n}\n\n/** Response for the create file method. */\nexport class CreateFileResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Used to override the default configuration. */\nexport declare interface GetFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface GetFileParameters {\n /** The name identifier for the file to retrieve. */\n name: string;\n /** Used to override the default configuration. */\n config?: GetFileConfig;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DeleteFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface DeleteFileParameters {\n /** The name identifier for the file to be deleted. */\n name: string;\n /** Used to override the default configuration. */\n config?: DeleteFileConfig;\n}\n\n/** Response for the delete file method. */\nexport class DeleteFileResponse {}\n\n/** Config for inlined request. */\nexport declare interface InlinedRequest {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model?: string;\n /** Content of the request.\n */\n contents?: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** Config for `src` parameter. */\nexport declare interface BatchJobSource {\n /** Storage format of the input files. Must be one of:\n 'jsonl', 'bigquery'.\n */\n format?: string;\n /** The Google Cloud Storage URIs to input files.\n */\n gcsUri?: string[];\n /** The BigQuery URI to input table.\n */\n bigqueryUri?: string;\n /** The Gemini Developer API's file resource name of the input data\n (e.g. \"files/12345\").\n */\n fileName?: string;\n /** The Gemini Developer API's inlined input data to run batch job.\n */\n inlinedRequests?: InlinedRequest[];\n}\n\n/** Job error. */\nexport declare interface JobError {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: string[];\n /** The status code. */\n code?: number;\n /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the `details` field. */\n message?: string;\n}\n\n/** Config for `inlined_responses` parameter. */\nexport class InlinedResponse {\n /** The response to the request.\n */\n response?: GenerateContentResponse;\n /** The error encountered while processing the request.\n */\n error?: JobError;\n}\n\n/** Config for `des` parameter. */\nexport declare interface BatchJobDestination {\n /** Storage format of the output files. Must be one of:\n 'jsonl', 'bigquery'.\n */\n format?: string;\n /** The Google Cloud Storage URI to the output file.\n */\n gcsUri?: string;\n /** The BigQuery URI to the output table.\n */\n bigqueryUri?: string;\n /** The Gemini Developer API's file resource name of the output data\n (e.g. \"files/12345\"). The file will be a JSONL file with a single response\n per line. The responses will be GenerateContentResponse messages formatted\n as JSON. The responses will be written in the same order as the input\n requests.\n */\n fileName?: string;\n /** The responses to the requests in the batch. Returned when the batch was\n built using inlined requests. The responses will be in the same order as\n the input requests.\n */\n inlinedResponses?: InlinedResponse[];\n}\n\n/** Config for optional parameters. */\nexport declare interface CreateBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The user-defined name of this BatchJob.\n */\n displayName?: string;\n /** GCS or BigQuery URI prefix for the output predictions. Example:\n \"gs://path/to/output/data\" or \"bq://projectId.bqDatasetId.bqTableId\".\n */\n dest?: BatchJobDestinationUnion;\n}\n\n/** Config for batches.create parameters. */\nexport declare interface CreateBatchJobParameters {\n /** The name of the model to produces the predictions via the BatchJob.\n */\n model?: string;\n /** GCS URI(-s) or BigQuery URI to your input data to run batch job.\n Example: \"gs://path/to/input/data\" or \"bq://projectId.bqDatasetId.bqTableId\".\n */\n src: BatchJobSourceUnion;\n /** Optional parameters for creating a BatchJob.\n */\n config?: CreateBatchJobConfig;\n}\n\n/** Config for batches.create return value. */\nexport declare interface BatchJob {\n /** The resource name of the BatchJob. Output only.\".\n */\n name?: string;\n /** The display name of the BatchJob.\n */\n displayName?: string;\n /** The state of the BatchJob.\n */\n state?: JobState;\n /** Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED. */\n error?: JobError;\n /** The time when the BatchJob was created.\n */\n createTime?: string;\n /** Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state. */\n startTime?: string;\n /** The time when the BatchJob was completed.\n */\n endTime?: string;\n /** The time when the BatchJob was last updated.\n */\n updateTime?: string;\n /** The name of the model that produces the predictions via the BatchJob.\n */\n model?: string;\n /** Configuration for the input data.\n */\n src?: BatchJobSource;\n /** Configuration for the output data.\n */\n dest?: BatchJobDestination;\n}\n\n/** Optional parameters. */\nexport declare interface GetBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.get parameters. */\nexport declare interface GetBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: GetBatchJobConfig;\n}\n\n/** Optional parameters. */\nexport declare interface CancelBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.cancel parameters. */\nexport declare interface CancelBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: CancelBatchJobConfig;\n}\n\n/** Config for optional parameters. */\nexport declare interface ListBatchJobsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n}\n\n/** Config for batches.list parameters. */\nexport declare interface ListBatchJobsParameters {\n config?: ListBatchJobsConfig;\n}\n\n/** Config for batches.list return value. */\nexport class ListBatchJobsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n batchJobs?: BatchJob[];\n}\n\n/** Optional parameters for models.get method. */\nexport declare interface DeleteBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.delete parameters. */\nexport declare interface DeleteBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: DeleteBatchJobConfig;\n}\n\n/** The return value of delete operation. */\nexport declare interface DeleteResourceJob {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n name?: string;\n done?: boolean;\n error?: JobError;\n}\n\nexport declare interface GetOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the GET method. */\nexport declare interface GetOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\nexport declare interface FetchPredictOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the fetchPredictOperation method. */\nexport declare interface FetchPredictOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n resourceName: string;\n /** Used to override the default configuration. */\n config?: FetchPredictOperationConfig;\n}\n\nexport declare interface TestTableItem {\n /** The name of the test. This is used to derive the replay id. */\n name?: string;\n /** The parameters to the test. Use pydantic models. */\n parameters?: Record;\n /** Expects an exception for MLDev matching the string. */\n exceptionIfMldev?: string;\n /** Expects an exception for Vertex matching the string. */\n exceptionIfVertex?: string;\n /** Use if you don't want to use the default replay id which is derived from the test name. */\n overrideReplayId?: string;\n /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */\n hasUnion?: boolean;\n /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */\n skipInApiMode?: string;\n /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */\n ignoreKeys?: string[];\n}\n\nexport declare interface TestTableFile {\n comment?: string;\n testMethod?: string;\n parameterNames?: string[];\n testTable?: TestTableItem[];\n}\n\n/** Represents a single request in a replay. */\nexport declare interface ReplayRequest {\n method?: string;\n url?: string;\n headers?: Record;\n bodySegments?: Record[];\n}\n\n/** Represents a single response in a replay. */\nexport class ReplayResponse {\n statusCode?: number;\n headers?: Record;\n bodySegments?: Record[];\n sdkResponseSegments?: Record[];\n}\n\n/** Represents a single interaction, request and response in a replay. */\nexport declare interface ReplayInteraction {\n request?: ReplayRequest;\n response?: ReplayResponse;\n}\n\n/** Represents a recorded session. */\nexport declare interface ReplayFile {\n replayId?: string;\n interactions?: ReplayInteraction[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface UploadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */\n name?: string;\n /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */\n mimeType?: string;\n /** Optional display name of the file. */\n displayName?: string;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DownloadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters used to download a file. */\nexport declare interface DownloadFileParameters {\n /** The file to download. It can be a file name, a file object or a generated video. */\n file: DownloadableFileUnion;\n /** Location where the file should be downloaded to. */\n downloadPath: string;\n /** Configuration to for the download operation. */\n config?: DownloadFileConfig;\n}\n\n/** Configuration for upscaling an image.\n\n For more information on this configuration, refer to\n the `Imagen API reference documentation\n `_.\n */\nexport declare interface UpscaleImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Whether to include a reason for filtered-out images in the\n response. */\n includeRaiReason?: boolean;\n /** The image format that the output should be saved as. */\n outputMimeType?: string;\n /** The level of compression if the ``output_mime_type`` is\n ``image/jpeg``. */\n outputCompressionQuality?: number;\n /** Whether to add an image enhancing step before upscaling.\n It is expected to suppress the noise and JPEG compression artifacts\n from the input image. */\n enhanceInputImage?: boolean;\n /** With a higher image preservation factor, the original image\n pixels are more respected. With a lower image preservation factor, the\n output image will have be more different from the input image, but\n with finer details and less noise. */\n imagePreservationFactor?: number;\n}\n\n/** User-facing config UpscaleImageParameters. */\nexport declare interface UpscaleImageParameters {\n /** The model to use. */\n model: string;\n /** The input image to upscale. */\n image: Image;\n /** The factor to upscale the image (x2 or x4). */\n upscaleFactor: string;\n /** Configuration for upscaling. */\n config?: UpscaleImageConfig;\n}\n\n/** A raw reference image.\n\n A raw reference image represents the base image to edit, provided by the user.\n It can optionally be provided in addition to a mask reference image or\n a style reference image.\n */\nexport class RawReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_RAW',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n };\n return referenceImageAPI;\n }\n}\n\n/** A mask reference image.\n\n This encapsulates either a mask image provided by the user and configs for\n the user provided mask, or only config parameters for the model to generate\n a mask.\n\n A mask image is an image whose non-zero values indicate where to edit the base\n image. If the user provides a mask image, the mask must be in the same\n dimensions as the raw image.\n */\nexport class MaskReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the mask reference image. */\n config?: MaskReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_MASK',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n maskImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A control reference image.\n\n The image of the control reference image is either a control image provided\n by the user, or a regular image which the backend will use to generate a\n control image of. In the case of the latter, the\n enable_control_image_computation field in the config should be set to True.\n\n A control image is an image that represents a sketch image of areas for the\n model to fill in based on the prompt.\n */\nexport class ControlReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the control reference image. */\n config?: ControlReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_CONTROL',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n controlImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A style reference image.\n\n This encapsulates a style reference image provided by the user, and\n additionally optional config parameters for the style reference image.\n\n A raw reference image can also be provided as a destination for the style to\n be applied to.\n */\nexport class StyleReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the style reference image. */\n config?: StyleReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_STYLE',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n styleImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A subject reference image.\n\n This encapsulates a subject reference image provided by the user, and\n additionally optional config parameters for the subject reference image.\n\n A raw reference image can also be provided as a destination for the subject to\n be applied to.\n */\nexport class SubjectReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the subject reference image. */\n config?: SubjectReferenceConfig;\n /* Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_SUBJECT',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n subjectImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\nexport /** Sent in response to a `LiveGenerateContentSetup` message from the client. */\ndeclare interface LiveServerSetupComplete {\n /** The session id of the live session. */\n sessionId?: string;\n}\n\n/** Audio transcription in Server Conent. */\nexport declare interface Transcription {\n /** Transcription text.\n */\n text?: string;\n /** The bool indicates the end of the transcription.\n */\n finished?: boolean;\n}\n\n/** Incremental server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time. Clients\n may choose to buffer and play it out in real time.\n */\nexport declare interface LiveServerContent {\n /** The content that the model has generated as part of the current conversation with the user. */\n modelTurn?: Content;\n /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */\n turnComplete?: boolean;\n /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */\n interrupted?: boolean;\n /** Metadata returned to client when grounding is enabled. */\n groundingMetadata?: GroundingMetadata;\n /** If true, indicates that the model is done generating. When model is\n interrupted while generating there will be no generation_complete message\n in interrupted turn, it will go through interrupted > turn_complete.\n When model assumes realtime playback there will be delay between\n generation_complete and turn_complete that is caused by model\n waiting for playback to finish. If true, indicates that the model\n has finished generating all content. This is a signal to the client\n that it can stop sending messages. */\n generationComplete?: boolean;\n /** Input transcription. The transcription is independent to the model\n turn which means it doesn’t imply any ordering between transcription and\n model turn. */\n inputTranscription?: Transcription;\n /** Output transcription. The transcription is independent to the model\n turn which means it doesn’t imply any ordering between transcription and\n model turn.\n */\n outputTranscription?: Transcription;\n /** Metadata related to url context retrieval tool. */\n urlContextMetadata?: UrlContextMetadata;\n}\n\n/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\nexport declare interface LiveServerToolCall {\n /** The function call to be executed. */\n functionCalls?: FunctionCall[];\n}\n\n/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled.\n\n If there were side-effects to those tool calls, clients may attempt to undo\n the tool calls. This message occurs only in cases where the clients interrupt\n server turns.\n */\nexport declare interface LiveServerToolCallCancellation {\n /** The ids of the tool calls to be cancelled. */\n ids?: string[];\n}\n\n/** Usage metadata about response(s). */\nexport declare interface UsageMetadata {\n /** Number of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n /** Total number of tokens across all the generated response candidates. */\n responseTokenCount?: number;\n /** Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Number of tokens of thoughts for thinking models. */\n thoughtsTokenCount?: number;\n /** Total token count for prompt, response candidates, and tool-use prompts(if present). */\n totalTokenCount?: number;\n /** List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were processed in the cache input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were returned in the response. */\n responseTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were processed in the tool-use prompt. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Traffic type. This shows whether a request consumes Pay-As-You-Go\n or Provisioned Throughput quota. */\n trafficType?: TrafficType;\n}\n\n/** Server will not be able to service client soon. */\nexport declare interface LiveServerGoAway {\n /** The remaining time before the connection will be terminated as ABORTED. The minimal time returned here is specified differently together with the rate limits for a given model. */\n timeLeft?: string;\n}\n\n/** Update of the session resumption state.\n\n Only sent if `session_resumption` was set in the connection config.\n */\nexport declare interface LiveServerSessionResumptionUpdate {\n /** New handle that represents state that can be resumed. Empty if `resumable`=false. */\n newHandle?: string;\n /** True if session can be resumed at this point. It might be not possible to resume session at some points. In that case we send update empty new_handle and resumable=false. Example of such case could be model executing function calls or just generating. Resuming session (using previous session token) in such state will result in some data loss. */\n resumable?: boolean;\n /** Index of last message sent by client that is included in state represented by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent` is set.\n\nPresence of this index allows users to transparently reconnect and avoid issue of losing some part of realtime audio input/video. If client wishes to temporarily disconnect (for example as result of receiving GoAway) they can do it without losing state by buffering messages sent since last `SessionResmumptionTokenUpdate`. This field will enable them to limit buffering (avoid keeping all requests in RAM).\n\nNote: This should not be used for when resuming a session at some time later -- in those cases partial audio and video frames arelikely not needed. */\n lastConsumedClientMessageIndex?: string;\n}\n\n/** Response message for API call. */\nexport class LiveServerMessage {\n /** Sent in response to a `LiveClientSetup` message from the client. */\n setupComplete?: LiveServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveServerContent;\n /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\n toolCall?: LiveServerToolCall;\n /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */\n toolCallCancellation?: LiveServerToolCallCancellation;\n /** Usage metadata about model response(s). */\n usageMetadata?: UsageMetadata;\n /** Server will disconnect soon. */\n goAway?: LiveServerGoAway;\n /** Update of the session resumption state. */\n sessionResumptionUpdate?: LiveServerSessionResumptionUpdate;\n /**\n * Returns the concatenation of all text parts from the server content if present.\n *\n * @remarks\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n */\n get text(): string | undefined {\n let text = '';\n let anyTextPartFound = false;\n const nonTextParts = [];\n for (const part of this.serverContent?.modelTurn?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n fieldValue !== null\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartFound = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartFound ? text : undefined;\n }\n\n /**\n * Returns the concatenation of all inline data parts from the server content if present.\n *\n * @remarks\n * If there are non-inline data parts in the\n * response, the concatenation of all inline data parts will be returned, and\n * a warning will be logged.\n */\n get data(): string | undefined {\n let data = '';\n const nonDataParts = [];\n for (const part of this.serverContent?.modelTurn?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (fieldName !== 'inlineData' && fieldValue !== null) {\n nonDataParts.push(fieldName);\n }\n }\n if (part.inlineData && typeof part.inlineData.data === 'string') {\n data += atob(part.inlineData.data);\n }\n }\n if (nonDataParts.length > 0) {\n console.warn(\n `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`,\n );\n }\n return data.length > 0 ? btoa(data) : undefined;\n }\n}\n\n/** Parameters for the get method of the operations module. */\nexport declare interface OperationGetParameters> {\n /** The operation to be retrieved. */\n operation: U;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\n/** Parameters of the fromAPIResponse method of the Operation class. */\nexport declare interface OperationFromAPIResponseParameters {\n /** The API response to be converted to an Operation. */\n apiResponse: Record;\n /** Whether the API response is from Vertex AI. */\n isVertexAI: boolean;\n}\n\n/** A long-running operation. */\nexport declare interface Operation {\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The response if the operation is successful. */\n response?: T;\n /**\n * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n * @internal\n */\n _fromAPIResponse({\n apiResponse,\n isVertexAI,\n }: OperationFromAPIResponseParameters): Operation;\n}\n\n/** A video generation long-running operation. */\nexport class GenerateVideosOperation\n implements Operation\n{\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The response if the operation is successful. */\n response?: GenerateVideosResponse;\n /** The full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n\n /**\n * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n * @internal\n */\n _fromAPIResponse({\n apiResponse,\n isVertexAI,\n }: OperationFromAPIResponseParameters): Operation {\n const operation = new GenerateVideosOperation();\n operation.name = apiResponse['name'] as string | undefined;\n operation.metadata = apiResponse['metadata'] as\n | Record\n | undefined;\n operation.done = apiResponse['done'] as boolean | undefined;\n operation.error = apiResponse['error'] as\n | Record\n | undefined;\n\n if (isVertexAI) {\n const response = apiResponse['response'] as\n | Record\n | undefined;\n if (response) {\n const operationResponse = new GenerateVideosResponse();\n const responseVideos = response['videos'] as\n | Array>\n | undefined;\n operationResponse.generatedVideos = responseVideos?.map(\n (generatedVideo) => {\n return {\n video: {\n uri: generatedVideo['gcsUri'] as string | undefined,\n videoBytes: generatedVideo['bytesBase64Encoded']\n ? tBytes(generatedVideo['bytesBase64Encoded'] as string)\n : undefined,\n mimeType: generatedVideo['mimeType'] as string | undefined,\n } as Video,\n } as GeneratedVideo;\n },\n );\n operationResponse.raiMediaFilteredCount = response[\n 'raiMediaFilteredCount'\n ] as number | undefined;\n operationResponse.raiMediaFilteredReasons = response[\n 'raiMediaFilteredReasons'\n ] as string[] | undefined;\n operation.response = operationResponse;\n }\n } else {\n const response = apiResponse['response'] as\n | Record\n | undefined;\n if (response) {\n const operationResponse = new GenerateVideosResponse();\n const generatedVideoResponse = response['generateVideoResponse'] as\n | Record\n | undefined;\n const responseVideos = generatedVideoResponse?.['generatedSamples'] as\n | Array>\n | undefined;\n operationResponse.generatedVideos = responseVideos?.map(\n (generatedVideo) => {\n const video = generatedVideo['video'] as\n | Record\n | undefined;\n return {\n video: {\n uri: video?.['uri'] as string | undefined,\n videoBytes: video?.['encodedVideo']\n ? tBytes(video?.['encodedVideo'] as string)\n : undefined,\n mimeType: generatedVideo['encoding'] as string | undefined,\n } as Video,\n } as GeneratedVideo;\n },\n );\n operationResponse.raiMediaFilteredCount = generatedVideoResponse?.[\n 'raiMediaFilteredCount'\n ] as number | undefined;\n operationResponse.raiMediaFilteredReasons = generatedVideoResponse?.[\n 'raiMediaFilteredReasons'\n ] as string[] | undefined;\n operation.response = operationResponse;\n }\n }\n return operation;\n }\n}\n\n/** Configures automatic detection of activity. */\nexport declare interface AutomaticActivityDetection {\n /** If enabled, detected voice and text input count as activity. If disabled, the client must send activity signals. */\n disabled?: boolean;\n /** Determines how likely speech is to be detected. */\n startOfSpeechSensitivity?: StartSensitivity;\n /** Determines how likely detected speech is ended. */\n endOfSpeechSensitivity?: EndSensitivity;\n /** The required duration of detected speech before start-of-speech is committed. The lower this value the more sensitive the start-of-speech detection is and the shorter speech can be recognized. However, this also increases the probability of false positives. */\n prefixPaddingMs?: number;\n /** The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency. */\n silenceDurationMs?: number;\n}\n\n/** Marks the end of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface RealtimeInputConfig {\n /** If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals. */\n automaticActivityDetection?: AutomaticActivityDetection;\n /** Defines what effect activity has. */\n activityHandling?: ActivityHandling;\n /** Defines which input is included in the user's turn. */\n turnCoverage?: TurnCoverage;\n}\n\n/** Configuration of session resumption mechanism.\n\n Included in `LiveConnectConfig.session_resumption`. If included server\n will send `LiveServerSessionResumptionUpdate` messages.\n */\nexport declare interface SessionResumptionConfig {\n /** Session resumption handle of previous session (session to restore).\n\nIf not present new session will be started. */\n handle?: string;\n /** If set the server will send `last_consumed_client_message_index` in the `session_resumption_update` messages to allow for transparent reconnections. */\n transparent?: boolean;\n}\n\n/** Context window will be truncated by keeping only suffix of it.\n\n Context window will always be cut at start of USER role turn. System\n instructions and `BidiGenerateContentSetup.prefix_turns` will not be\n subject to the sliding window mechanism, they will always stay at the\n beginning of context window.\n */\nexport declare interface SlidingWindow {\n /** Session reduction target -- how many tokens we should keep. Window shortening operation has some latency costs, so we should avoid running it on every turn. Should be < trigger_tokens. If not set, trigger_tokens/2 is assumed. */\n targetTokens?: string;\n}\n\n/** Enables context window compression -- mechanism managing model context window so it does not exceed given length. */\nexport declare interface ContextWindowCompressionConfig {\n /** Number of tokens (before running turn) that triggers context window compression mechanism. */\n triggerTokens?: string;\n /** Sliding window compression mechanism. */\n slidingWindow?: SlidingWindow;\n}\n\n/** The audio transcription configuration in Setup. */\nexport declare interface AudioTranscriptionConfig {}\n\n/** Config for proactivity features. */\nexport declare interface ProactivityConfig {\n /** If enabled, the model can reject responding to the last prompt. For\n example, this allows the model to ignore out of context speech or to stay\n silent if the user did not make a request, yet. */\n proactiveAudio?: boolean;\n}\n\n/** Message contains configuration that will apply for the duration of the streaming session. */\nexport declare interface LiveClientSetup {\n /** \n The fully qualified name of the publisher model or tuned model endpoint to\n use.\n */\n model?: string;\n /** The generation configuration for the session.\n Note: only a subset of fields are supported.\n */\n generationConfig?: GenerationConfig;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n /** Configures the realtime input behavior in BidiGenerateContent. */\n realtimeInputConfig?: RealtimeInputConfig;\n /** Configures session resumption mechanism.\n\n If included server will send SessionResumptionUpdate messages. */\n sessionResumption?: SessionResumptionConfig;\n /** Configures context window compression mechanism.\n\n If included, server will compress context window to fit into given length. */\n contextWindowCompression?: ContextWindowCompressionConfig;\n /** The transcription of the input aligns with the input audio language.\n */\n inputAudioTranscription?: AudioTranscriptionConfig;\n /** The transcription of the output aligns with the language code\n specified for the output audio.\n */\n outputAudioTranscription?: AudioTranscriptionConfig;\n /** Configures the proactivity of the model. This allows the model to respond proactively to\n the input and to ignore irrelevant input. */\n proactivity?: ProactivityConfig;\n}\n\n/** Incremental update of the current conversation delivered from the client.\n\n All the content here will unconditionally be appended to the conversation\n history and used as part of the prompt to the model to generate content.\n\n A message here will interrupt any current model generation.\n */\nexport declare interface LiveClientContent {\n /** The content appended to the current conversation with the model.\n\n For single-turn queries, this is a single instance. For multi-turn\n queries, this is a repeated field that contains conversation history and\n latest request.\n */\n turns?: Content[];\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Marks the start of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface ActivityStart {}\n\n/** Marks the end of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface ActivityEnd {}\n\n/** User input that is sent in real time.\n\n This is different from `LiveClientContent` in a few ways:\n\n - Can be sent continuously without interruption to model generation.\n - If there is a need to mix data interleaved across the\n `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to\n optimize for best response, but there are no guarantees.\n - End of turn is not explicitly specified, but is rather derived from user\n activity (for example, end of speech).\n - Even before the end of turn, the data is processed incrementally\n to optimize for a fast start of the response from the model.\n - Is always assumed to be the user's input (cannot be used to populate\n conversation history).\n */\nexport declare interface LiveClientRealtimeInput {\n /** Inlined bytes data for media input. */\n mediaChunks?: Blob[];\n /** The realtime audio input stream. */\n audio?: Blob;\n /** \nIndicates that the audio stream has ended, e.g. because the microphone was\nturned off.\n\nThis should only be sent when automatic activity detection is enabled\n(which is the default).\n\nThe client can reopen the stream by sending an audio message.\n */\n audioStreamEnd?: boolean;\n /** The realtime video input stream. */\n video?: Blob;\n /** The realtime text input stream. */\n text?: string;\n /** Marks the start of user activity. */\n activityStart?: ActivityStart;\n /** Marks the end of user activity. */\n activityEnd?: ActivityEnd;\n}\n\n/** Client generated response to a `ToolCall` received from the server.\n\n Individual `FunctionResponse` objects are matched to the respective\n `FunctionCall` objects by the `id` field.\n\n Note that in the unary and server-streaming GenerateContent APIs function\n calling happens by exchanging the `Content` parts, while in the bidi\n GenerateContent APIs function calling happens over this dedicated set of\n messages.\n */\nexport class LiveClientToolResponse {\n /** The response to the function calls. */\n functionResponses?: FunctionResponse[];\n}\n\n/** Parameters for sending realtime input to the live API. */\nexport declare interface LiveSendRealtimeInputParameters {\n /** Realtime input to send to the session. */\n media?: BlobImageUnion;\n /** The realtime audio input stream. */\n audio?: Blob;\n /** \nIndicates that the audio stream has ended, e.g. because the microphone was\nturned off.\n\nThis should only be sent when automatic activity detection is enabled\n(which is the default).\n\nThe client can reopen the stream by sending an audio message.\n */\n audioStreamEnd?: boolean;\n /** The realtime video input stream. */\n video?: BlobImageUnion;\n /** The realtime text input stream. */\n text?: string;\n /** Marks the start of user activity. */\n activityStart?: ActivityStart;\n /** Marks the end of user activity. */\n activityEnd?: ActivityEnd;\n}\n\n/** Messages sent by the client in the API call. */\nexport declare interface LiveClientMessage {\n /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */\n setup?: LiveClientSetup;\n /** Incremental update of the current conversation delivered from the client. */\n clientContent?: LiveClientContent;\n /** User input that is sent in real time. */\n realtimeInput?: LiveClientRealtimeInput;\n /** Response to a `ToolCallMessage` received from the server. */\n toolResponse?: LiveClientToolResponse;\n}\n\n/** Session config for the API connection. */\nexport declare interface LiveConnectConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The generation configuration for the session. */\n generationConfig?: GenerationConfig;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return. Defaults to AUDIO if not specified.\n */\n responseModalities?: Modality[];\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfig;\n /** If enabled, the model will detect emotions and adapt its responses accordingly. */\n enableAffectiveDialog?: boolean;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n /** Configures session resumption mechanism.\n\nIf included the server will send SessionResumptionUpdate messages. */\n sessionResumption?: SessionResumptionConfig;\n /** The transcription of the input aligns with the input audio language.\n */\n inputAudioTranscription?: AudioTranscriptionConfig;\n /** The transcription of the output aligns with the language code\n specified for the output audio.\n */\n outputAudioTranscription?: AudioTranscriptionConfig;\n /** Configures the realtime input behavior in BidiGenerateContent. */\n realtimeInputConfig?: RealtimeInputConfig;\n /** Configures context window compression mechanism.\n\n If included, server will compress context window to fit into given length. */\n contextWindowCompression?: ContextWindowCompressionConfig;\n /** Configures the proactivity of the model. This allows the model to respond proactively to\n the input and to ignore irrelevant input. */\n proactivity?: ProactivityConfig;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveConnectParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** callbacks */\n callbacks: LiveCallbacks;\n /** Optional configuration parameters for the request.\n */\n config?: LiveConnectConfig;\n}\n\n/** Parameters for initializing a new chat session.\n\n These parameters are used when creating a chat session with the\n `chats.create()` method.\n */\nexport declare interface CreateChatParameters {\n /** The name of the model to use for the chat session.\n\n For example: 'gemini-2.0-flash', 'gemini-2.0-flash-lite', etc. See Gemini API\n docs to find the available models.\n */\n model: string;\n /** Config for the entire chat session.\n\n This config applies to all requests within the session\n unless overridden by a per-request `config` in `SendMessageParameters`.\n */\n config?: GenerateContentConfig;\n /** The initial conversation history for the chat session.\n\n This allows you to start the chat with a pre-existing history. The history\n must be a list of `Content` alternating between 'user' and 'model' roles.\n It should start with a 'user' message.\n */\n history?: Content[];\n}\n\n/** Parameters for sending a message within a chat session.\n\n These parameters are used with the `chat.sendMessage()` method.\n */\nexport declare interface SendMessageParameters {\n /** The message to send to the model.\n\n The SDK will combine all parts into a single 'user' content to send to\n the model.\n */\n message: PartListUnion;\n /** Config for this specific request.\n\n Please note that the per-request config does not change the chat level\n config, nor inherit from it. If you intend to use some values from the\n chat's default config, you must explicitly copy them into this per-request\n config.\n */\n config?: GenerateContentConfig;\n}\n\n/** Parameters for sending client content to the live API. */\nexport declare interface LiveSendClientContentParameters {\n /** Client content to send to the session. */\n turns?: ContentListUnion;\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Parameters for sending tool responses to the live API. */\nexport class LiveSendToolResponseParameters {\n /** Tool responses to send to the session. */\n functionResponses: FunctionResponse[] | FunctionResponse = [];\n}\n\n/** Message to be sent by the system when connecting to the API. */\nexport declare interface LiveMusicClientSetup {\n /** The model's resource name. Format: `models/{model}`. */\n model?: string;\n}\n\n/** Maps a prompt to a relative weight to steer music generation. */\nexport declare interface WeightedPrompt {\n /** Text prompt. */\n text?: string;\n /** Weight of the prompt. The weight is used to control the relative\n importance of the prompt. Higher weights are more important than lower\n weights.\n\n Weight must not be 0. Weights of all weighted_prompts in this\n LiveMusicClientContent message will be normalized. */\n weight?: number;\n}\n\n/** User input to start or steer the music. */\nexport declare interface LiveMusicClientContent {\n /** Weighted prompts as the model input. */\n weightedPrompts?: WeightedPrompt[];\n}\n\n/** Configuration for music generation. */\nexport declare interface LiveMusicGenerationConfig {\n /** Controls the variance in audio generation. Higher values produce\n higher variance. Range is [0.0, 3.0]. */\n temperature?: number;\n /** Controls how the model selects tokens for output. Samples the topK\n tokens with the highest probabilities. Range is [1, 1000]. */\n topK?: number;\n /** Seeds audio generation. If not set, the request uses a randomly\n generated seed. */\n seed?: number;\n /** Controls how closely the model follows prompts.\n Higher guidance follows more closely, but will make transitions more\n abrupt. Range is [0.0, 6.0]. */\n guidance?: number;\n /** Beats per minute. Range is [60, 200]. */\n bpm?: number;\n /** Density of sounds. Range is [0.0, 1.0]. */\n density?: number;\n /** Brightness of the music. Range is [0.0, 1.0]. */\n brightness?: number;\n /** Scale of the generated music. */\n scale?: Scale;\n /** Whether the audio output should contain bass. */\n muteBass?: boolean;\n /** Whether the audio output should contain drums. */\n muteDrums?: boolean;\n /** Whether the audio output should contain only bass and drums. */\n onlyBassAndDrums?: boolean;\n /** The mode of music generation. Default mode is QUALITY. */\n musicGenerationMode?: MusicGenerationMode;\n}\n\n/** Messages sent by the client in the LiveMusicClientMessage call. */\nexport declare interface LiveMusicClientMessage {\n /** Message to be sent in the first (and only in the first) `LiveMusicClientMessage`.\n Clients should wait for a `LiveMusicSetupComplete` message before\n sending any additional messages. */\n setup?: LiveMusicClientSetup;\n /** User input to influence music generation. */\n clientContent?: LiveMusicClientContent;\n /** Configuration for music generation. */\n musicGenerationConfig?: LiveMusicGenerationConfig;\n /** Playback control signal for the music generation. */\n playbackControl?: LiveMusicPlaybackControl;\n}\n\n/** Sent in response to a `LiveMusicClientSetup` message from the client. */\nexport declare interface LiveMusicServerSetupComplete {}\n\n/** Prompts and config used for generating this audio chunk. */\nexport declare interface LiveMusicSourceMetadata {\n /** Weighted prompts for generating this audio chunk. */\n clientContent?: LiveMusicClientContent;\n /** Music generation config for generating this audio chunk. */\n musicGenerationConfig?: LiveMusicGenerationConfig;\n}\n\n/** Representation of an audio chunk. */\nexport declare interface AudioChunk {\n /** Raw bytes of audio data.\n * @remarks Encoded as base64 string. */\n data?: string;\n /** MIME type of the audio chunk. */\n mimeType?: string;\n /** Prompts and config used for generating this audio chunk. */\n sourceMetadata?: LiveMusicSourceMetadata;\n}\n\n/** Server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time.\n Clients may choose to buffer and play it out in real time.\n */\nexport declare interface LiveMusicServerContent {\n /** The audio chunks that the model has generated. */\n audioChunks?: AudioChunk[];\n}\n\n/** A prompt that was filtered with the reason. */\nexport declare interface LiveMusicFilteredPrompt {\n /** The text prompt that was filtered. */\n text?: string;\n /** The reason the prompt was filtered. */\n filteredReason?: string;\n}\n\n/** Response message for the LiveMusicClientMessage call. */\nexport class LiveMusicServerMessage {\n /** Message sent in response to a `LiveMusicClientSetup` message from the client.\n Clients should wait for this message before sending any additional messages. */\n setupComplete?: LiveMusicServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveMusicServerContent;\n /** A prompt that was filtered with the reason. */\n filteredPrompt?: LiveMusicFilteredPrompt;\n /**\n * Returns the first audio chunk from the server content, if present.\n *\n * @remarks\n * If there are no audio chunks in the response, undefined will be returned.\n */\n get audioChunk(): AudioChunk | undefined {\n if (\n this.serverContent &&\n this.serverContent.audioChunks &&\n this.serverContent.audioChunks.length > 0\n ) {\n return this.serverContent.audioChunks[0];\n }\n return undefined;\n }\n}\n\n/** Callbacks for the realtime music API. */\nexport interface LiveMusicCallbacks {\n /**\n * Called when a message is received from the server.\n */\n onmessage: (e: LiveMusicServerMessage) => void;\n /**\n * Called when an error occurs.\n */\n onerror?: ((e: ErrorEvent) => void) | null;\n /**\n * Called when the websocket connection is closed.\n */\n onclose?: ((e: CloseEvent) => void) | null;\n}\n\n/** Parameters for the upload file method. */\nexport interface UploadFileParameters {\n /** The string path to the file to be uploaded or a Blob object. */\n file: string | globalThis.Blob;\n /** Configuration that contains optional parameters. */\n config?: UploadFileConfig;\n}\n\n/**\n * CallableTool is an invokable tool that can be executed with external\n * application (e.g., via Model Context Protocol) or local functions with\n * function calling.\n */\nexport interface CallableTool {\n /**\n * Returns tool that can be called by Gemini.\n */\n tool(): Promise;\n /**\n * Executes the callable tool with the given function call arguments and\n * returns the response parts from the tool execution.\n */\n callTool(functionCalls: FunctionCall[]): Promise;\n}\n\n/**\n * CallableToolConfig is the configuration for a callable tool.\n */\nexport interface CallableToolConfig {\n /**\n * Specifies the model's behavior after invoking this tool.\n */\n behavior?: Behavior;\n /**\n * Timeout for remote calls in milliseconds. Note this timeout applies only to\n * tool remote calls, and not making HTTP requests to the API. */\n timeout?: number;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveMusicConnectParameters {\n /** The model's resource name. */\n model: string;\n /** Callbacks invoked on server events. */\n callbacks: LiveMusicCallbacks;\n}\n\n/** Parameters for setting config for the live music API. */\nexport declare interface LiveMusicSetConfigParameters {\n /** Configuration for music generation. */\n musicGenerationConfig: LiveMusicGenerationConfig;\n}\n\n/** Parameters for setting weighted prompts for the live music API. */\nexport declare interface LiveMusicSetWeightedPromptsParameters {\n /** A map of text prompts to weights to use for the generation request. */\n weightedPrompts: WeightedPrompt[];\n}\n\n/** Config for auth_tokens.create parameters. */\nexport declare interface AuthToken {\n /** The name of the auth token. */\n name?: string;\n}\n\n/** Config for LiveConnectConstraints for Auth Token creation. */\nexport declare interface LiveConnectConstraints {\n /** ID of the model to configure in the ephemeral token for Live API.\n For a list of models, see `Gemini models\n `. */\n model?: string;\n /** Configuration specific to Live API connections created using this token. */\n config?: LiveConnectConfig;\n}\n\n/** Optional parameters. */\nexport declare interface CreateAuthTokenConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** An optional time after which, when using the resulting token,\n messages in Live API sessions will be rejected. (Gemini may\n preemptively close the session after this time.)\n\n If not set then this defaults to 30 minutes in the future. If set, this\n value must be less than 20 hours in the future. */\n expireTime?: string;\n /** The time after which new Live API sessions using the token\n resulting from this request will be rejected.\n\n If not set this defaults to 60 seconds in the future. If set, this value\n must be less than 20 hours in the future. */\n newSessionExpireTime?: string;\n /** The number of times the token can be used. If this value is zero\n then no limit is applied. Default is 1. Resuming a Live API session does\n not count as a use. */\n uses?: number;\n /** Configuration specific to Live API connections created using this token. */\n liveConnectConstraints?: LiveConnectConstraints;\n /** Additional fields to lock in the effective LiveConnectParameters. */\n lockAdditionalFields?: string[];\n}\n\n/** Config for auth_tokens.create parameters. */\nexport declare interface CreateAuthTokenParameters {\n /** Optional parameters for the request. */\n config?: CreateAuthTokenConfig;\n}\n\n/** Supervised fine-tuning job creation parameters - optional fields. */\nexport declare interface CreateTuningJobParameters {\n /** The base model that is being tuned, e.g., \"gemini-2.5-flash\". */\n baseModel: string;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDataset: TuningDataset;\n /** Configuration for the tuning job. */\n config?: CreateTuningJobConfig;\n}\n\nexport type BlobImageUnion = Blob;\n\nexport type PartUnion = Part | string;\n\nexport type PartListUnion = PartUnion[] | PartUnion;\n\nexport type ContentUnion = Content | PartUnion[] | PartUnion;\n\nexport type ContentListUnion = Content | Content[] | PartUnion | PartUnion[];\n\nexport type SchemaUnion = Schema | unknown;\n\nexport type SpeechConfigUnion = SpeechConfig | string;\n\nexport type ToolUnion = Tool | CallableTool;\n\nexport type ToolListUnion = ToolUnion[];\n\nexport type DownloadableFileUnion = string | File | GeneratedVideo | Video;\n\nexport type BatchJobSourceUnion = BatchJobSource | InlinedRequest[] | string;\n\nexport type BatchJobDestinationUnion = BatchJobDestination | string;\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {Tool as McpTool} from '@modelcontextprotocol/sdk/types.js';\n\nimport {ApiClient} from './_api_client.js';\nimport * as baseTransformers from './_base_transformers.js';\nimport * as types from './types.js';\n\nexport function tModel(apiClient: ApiClient, model: string | unknown): string {\n if (!model || typeof model !== 'string') {\n throw new Error('model is required and must be a string');\n }\n\n if (apiClient.isVertexAI()) {\n if (\n model.startsWith('publishers/') ||\n model.startsWith('projects/') ||\n model.startsWith('models/')\n ) {\n return model;\n } else if (model.indexOf('/') >= 0) {\n const parts = model.split('/', 2);\n return `publishers/${parts[0]}/models/${parts[1]}`;\n } else {\n return `publishers/google/models/${model}`;\n }\n } else {\n if (model.startsWith('models/') || model.startsWith('tunedModels/')) {\n return model;\n } else {\n return `models/${model}`;\n }\n }\n}\n\nexport function tCachesModel(\n apiClient: ApiClient,\n model: string | unknown,\n): string {\n const transformedModel = tModel(apiClient, model as string);\n if (!transformedModel) {\n return '';\n }\n\n if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) {\n // vertex caches only support model name start with projects.\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`;\n } else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) {\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`;\n } else {\n return transformedModel;\n }\n}\n\nexport function tBlobs(\n blobs: types.BlobImageUnion | types.BlobImageUnion[],\n): types.Blob[] {\n if (Array.isArray(blobs)) {\n return blobs.map((blob) => tBlob(blob));\n } else {\n return [tBlob(blobs)];\n }\n}\n\nexport function tBlob(blob: types.BlobImageUnion): types.Blob {\n if (typeof blob === 'object' && blob !== null) {\n return blob;\n }\n\n throw new Error(\n `Could not parse input as Blob. Unsupported blob type: ${typeof blob}`,\n );\n}\n\nexport function tImageBlob(blob: types.BlobImageUnion): types.Blob {\n const transformedBlob = tBlob(blob);\n if (\n transformedBlob.mimeType &&\n transformedBlob.mimeType.startsWith('image/')\n ) {\n return transformedBlob;\n }\n throw new Error(`Unsupported mime type: ${transformedBlob.mimeType!}`);\n}\n\nexport function tAudioBlob(blob: types.Blob): types.Blob {\n const transformedBlob = tBlob(blob);\n if (\n transformedBlob.mimeType &&\n transformedBlob.mimeType.startsWith('audio/')\n ) {\n return transformedBlob;\n }\n throw new Error(`Unsupported mime type: ${transformedBlob.mimeType!}`);\n}\n\nexport function tPart(origin?: types.PartUnion | null): types.Part {\n if (origin === null || origin === undefined) {\n throw new Error('PartUnion is required');\n }\n if (typeof origin === 'object') {\n return origin;\n }\n if (typeof origin === 'string') {\n return {text: origin};\n }\n throw new Error(`Unsupported part type: ${typeof origin}`);\n}\n\nexport function tParts(origin?: types.PartListUnion | null): types.Part[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('PartListUnion is required');\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tPart(item as types.PartUnion)!);\n }\n return [tPart(origin)!];\n}\n\nfunction _isContent(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'parts' in origin &&\n Array.isArray(origin.parts)\n );\n}\n\nfunction _isFunctionCallPart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionCall' in origin\n );\n}\n\nfunction _isFunctionResponsePart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionResponse' in origin\n );\n}\n\nexport function tContent(origin?: types.ContentUnion): types.Content {\n if (origin === null || origin === undefined) {\n throw new Error('ContentUnion is required');\n }\n if (_isContent(origin)) {\n // _isContent is a utility function that checks if the\n // origin is a Content.\n return origin as types.Content;\n }\n\n return {\n role: 'user',\n parts: tParts(origin as types.PartListUnion)!,\n };\n}\n\nexport function tContentsForEmbed(\n apiClient: ApiClient,\n origin: types.ContentListUnion,\n): types.ContentUnion[] {\n if (!origin) {\n return [];\n }\n if (apiClient.isVertexAI() && Array.isArray(origin)) {\n return origin.flatMap((item) => {\n const content = tContent(item as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n });\n } else if (apiClient.isVertexAI()) {\n const content = tContent(origin as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tContent(item as types.ContentUnion)!);\n }\n return [tContent(origin as types.ContentUnion)!];\n}\n\nexport function tContents(origin?: types.ContentListUnion): types.Content[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('contents are required');\n }\n if (!Array.isArray(origin)) {\n // If it's not an array, it's a single content or a single PartUnion.\n if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) {\n throw new Error(\n 'To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them',\n );\n }\n return [tContent(origin as types.ContentUnion)];\n }\n\n const result: types.Content[] = [];\n const accumulatedParts: types.PartUnion[] = [];\n const isContentArray = _isContent(origin[0]);\n\n for (const item of origin) {\n const isContent = _isContent(item);\n\n if (isContent != isContentArray) {\n throw new Error(\n 'Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them',\n );\n }\n\n if (isContent) {\n // `isContent` contains the result of _isContent, which is a utility\n // function that checks if the item is a Content.\n result.push(item as types.Content);\n } else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) {\n throw new Error(\n 'To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them',\n );\n } else {\n accumulatedParts.push(item as types.PartUnion);\n }\n }\n\n if (!isContentArray) {\n result.push({role: 'user', parts: tParts(accumulatedParts)});\n }\n return result;\n}\n\n/*\nTransform the type field from an array of types to an array of anyOf fields.\nExample:\n {type: ['STRING', 'NUMBER']}\nwill be transformed to\n {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]}\n*/\nfunction flattenTypeArrayToAnyOf(\n typeList: string[],\n resultingSchema: types.Schema,\n) {\n if (typeList.includes('null')) {\n resultingSchema['nullable'] = true;\n }\n const listWithoutNull = typeList.filter((type) => type !== 'null');\n\n if (listWithoutNull.length === 1) {\n resultingSchema['type'] = Object.values(types.Type).includes(\n listWithoutNull[0].toUpperCase() as types.Type,\n )\n ? (listWithoutNull[0].toUpperCase() as types.Type)\n : types.Type.TYPE_UNSPECIFIED;\n } else {\n resultingSchema['anyOf'] = [];\n for (const i of listWithoutNull) {\n resultingSchema['anyOf'].push({\n 'type': Object.values(types.Type).includes(\n i.toUpperCase() as types.Type,\n )\n ? (i.toUpperCase() as types.Type)\n : types.Type.TYPE_UNSPECIFIED,\n });\n }\n }\n}\n\nexport function processJsonSchema(\n _jsonSchema: types.Schema | Record,\n): types.Schema {\n const genAISchema: types.Schema = {};\n const schemaFieldNames = ['items'];\n const listSchemaFieldNames = ['anyOf'];\n const dictSchemaFieldNames = ['properties'];\n\n if (_jsonSchema['type'] && _jsonSchema['anyOf']) {\n throw new Error('type and anyOf cannot be both populated.');\n }\n\n /*\n This is to handle the nullable array or object. The _jsonSchema will\n be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The\n logic is to check if anyOf has 2 elements and one of the element is null,\n if so, the anyOf field is unnecessary, so we need to get rid of the anyOf\n field and make the schema nullable. Then use the other element as the new\n _jsonSchema for processing. This is because the backend doesn't have a null\n type.\n This has to be checked before we process any other fields.\n For example:\n const objectNullable = z.object({\n nullableArray: z.array(z.string()).nullable(),\n });\n Will have the raw _jsonSchema as:\n {\n type: 'OBJECT',\n properties: {\n nullableArray: {\n anyOf: [\n {type: 'null'},\n {\n type: 'array',\n items: {type: 'string'},\n },\n ],\n }\n },\n required: [ 'nullableArray' ],\n }\n Will result in following schema compatible with Gemini API:\n {\n type: 'OBJECT',\n properties: {\n nullableArray: {\n nullable: true,\n type: 'ARRAY',\n items: {type: 'string'},\n }\n },\n required: [ 'nullableArray' ],\n }\n */\n const incomingAnyOf = _jsonSchema['anyOf'] as Record[];\n if (incomingAnyOf != null && incomingAnyOf.length == 2) {\n if (incomingAnyOf[0]!['type'] === 'null') {\n genAISchema['nullable'] = true;\n _jsonSchema = incomingAnyOf![1];\n } else if (incomingAnyOf[1]!['type'] === 'null') {\n genAISchema['nullable'] = true;\n _jsonSchema = incomingAnyOf![0];\n }\n }\n\n if (_jsonSchema['type'] instanceof Array) {\n flattenTypeArrayToAnyOf(_jsonSchema['type'], genAISchema);\n }\n\n for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) {\n // Skip if the fieldvalue is undefined or null.\n if (fieldValue == null) {\n continue;\n }\n\n if (fieldName == 'type') {\n if (fieldValue === 'null') {\n throw new Error(\n 'type: null can not be the only possible type for the field.',\n );\n }\n if (fieldValue instanceof Array) {\n // we have already handled the type field with array of types in the\n // beginning of this function.\n continue;\n }\n genAISchema['type'] = Object.values(types.Type).includes(\n fieldValue.toUpperCase() as types.Type,\n )\n ? fieldValue.toUpperCase()\n : types.Type.TYPE_UNSPECIFIED;\n } else if (schemaFieldNames.includes(fieldName)) {\n (genAISchema as Record)[fieldName] =\n processJsonSchema(fieldValue);\n } else if (listSchemaFieldNames.includes(fieldName)) {\n const listSchemaFieldValue: Array = [];\n for (const item of fieldValue) {\n if (item['type'] == 'null') {\n genAISchema['nullable'] = true;\n continue;\n }\n listSchemaFieldValue.push(\n processJsonSchema(item as Record),\n );\n }\n (genAISchema as Record)[fieldName] =\n listSchemaFieldValue;\n } else if (dictSchemaFieldNames.includes(fieldName)) {\n const dictSchemaFieldValue: Record = {};\n for (const [key, value] of Object.entries(\n fieldValue as Record,\n )) {\n dictSchemaFieldValue[key] = processJsonSchema(\n value as Record,\n );\n }\n (genAISchema as Record)[fieldName] =\n dictSchemaFieldValue;\n } else {\n // additionalProperties is not included in JSONSchema, skipping it.\n if (fieldName === 'additionalProperties') {\n continue;\n }\n (genAISchema as Record)[fieldName] = fieldValue;\n }\n }\n return genAISchema;\n}\n\n// we take the unknown in the schema field because we want enable user to pass\n// the output of major schema declaration tools without casting. Tools such as\n// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type\n// or object, see details in\n// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7\n// typebox can return unknown, see details in\n// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35\n// Note: proper json schemas with the $schema field set never arrive to this\n// transformer. Schemas with $schema are routed to the equivalent API json\n// schema field.\nexport function tSchema(schema: types.Schema | unknown): types.Schema {\n return processJsonSchema(schema as types.Schema);\n}\n\nexport function tSpeechConfig(\n speechConfig: types.SpeechConfigUnion,\n): types.SpeechConfig {\n if (typeof speechConfig === 'object') {\n return speechConfig;\n } else if (typeof speechConfig === 'string') {\n return {\n voiceConfig: {\n prebuiltVoiceConfig: {\n voiceName: speechConfig,\n },\n },\n };\n } else {\n throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`);\n }\n}\n\nexport function tLiveSpeechConfig(\n speechConfig: types.SpeechConfig | object,\n): types.SpeechConfig {\n if ('multiSpeakerVoiceConfig' in speechConfig) {\n throw new Error(\n 'multiSpeakerVoiceConfig is not supported in the live API.',\n );\n }\n return speechConfig;\n}\n\nexport function tTool(tool: types.Tool): types.Tool {\n if (tool.functionDeclarations) {\n for (const functionDeclaration of tool.functionDeclarations) {\n if (functionDeclaration.parameters) {\n if (!Object.keys(functionDeclaration.parameters).includes('$schema')) {\n functionDeclaration.parameters = processJsonSchema(\n functionDeclaration.parameters,\n );\n } else {\n if (!functionDeclaration.parametersJsonSchema) {\n functionDeclaration.parametersJsonSchema =\n functionDeclaration.parameters;\n delete functionDeclaration.parameters;\n }\n }\n }\n if (functionDeclaration.response) {\n if (!Object.keys(functionDeclaration.response).includes('$schema')) {\n functionDeclaration.response = processJsonSchema(\n functionDeclaration.response,\n );\n } else {\n if (!functionDeclaration.responseJsonSchema) {\n functionDeclaration.responseJsonSchema =\n functionDeclaration.response;\n delete functionDeclaration.response;\n }\n }\n }\n }\n }\n return tool;\n}\n\nexport function tTools(tools: types.ToolListUnion | unknown): types.Tool[] {\n // Check if the incoming type is defined.\n if (tools === undefined || tools === null) {\n throw new Error('tools is required');\n }\n if (!Array.isArray(tools)) {\n throw new Error('tools is required and must be an array of Tools');\n }\n const result: types.Tool[] = [];\n for (const tool of tools) {\n result.push(tool as types.Tool);\n }\n return result;\n}\n\n/**\n * Prepends resource name with project, location, resource_prefix if needed.\n *\n * @param client The API client.\n * @param resourceName The resource name.\n * @param resourcePrefix The resource prefix.\n * @param splitsAfterPrefix The number of splits after the prefix.\n * @returns The completed resource name.\n *\n * Examples:\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/bar/locations/us-west1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'projects/foo/locations/us-central1/cachedContents/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/foo/locations/us-central1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns 'cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'some/wrong/cachedContents/resource/name/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * # client.vertexai = True\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * -> 'some/wrong/resource/name/123'\n * ```\n */\nfunction resourceName(\n client: ApiClient,\n resourceName: string,\n resourcePrefix: string,\n splitsAfterPrefix: number = 1,\n): string {\n const shouldAppendPrefix =\n !resourceName.startsWith(`${resourcePrefix}/`) &&\n resourceName.split('/').length === splitsAfterPrefix;\n if (client.isVertexAI()) {\n if (resourceName.startsWith('projects/')) {\n return resourceName;\n } else if (resourceName.startsWith('locations/')) {\n return `projects/${client.getProject()}/${resourceName}`;\n } else if (resourceName.startsWith(`${resourcePrefix}/`)) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`;\n } else if (shouldAppendPrefix) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`;\n } else {\n return resourceName;\n }\n }\n if (shouldAppendPrefix) {\n return `${resourcePrefix}/${resourceName}`;\n }\n return resourceName;\n}\n\nexport function tCachedContentName(\n apiClient: ApiClient,\n name: string | unknown,\n): string {\n if (typeof name !== 'string') {\n throw new Error('name must be a string');\n }\n return resourceName(apiClient, name, 'cachedContents');\n}\n\nexport function tTuningJobStatus(status: string | unknown): string {\n switch (status) {\n case 'STATE_UNSPECIFIED':\n return 'JOB_STATE_UNSPECIFIED';\n case 'CREATING':\n return 'JOB_STATE_RUNNING';\n case 'ACTIVE':\n return 'JOB_STATE_SUCCEEDED';\n case 'FAILED':\n return 'JOB_STATE_FAILED';\n default:\n return status as string;\n }\n}\n\nexport function tBytes(fromImageBytes: string | unknown): string {\n return baseTransformers.tBytes(fromImageBytes);\n}\n\nfunction _isFile(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'name' in origin\n );\n}\n\nexport function isGeneratedVideo(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'video' in origin\n );\n}\n\nexport function isVideo(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'uri' in origin\n );\n}\n\nexport function tFileName(\n fromName: string | types.File | types.GeneratedVideo | types.Video,\n): string | undefined {\n let name: string | undefined;\n\n if (_isFile(fromName)) {\n name = (fromName as types.File).name;\n }\n if (isVideo(fromName)) {\n name = (fromName as types.Video).uri;\n if (name === undefined) {\n return undefined;\n }\n }\n if (isGeneratedVideo(fromName)) {\n name = (fromName as types.GeneratedVideo).video?.uri;\n if (name === undefined) {\n return undefined;\n }\n }\n if (typeof fromName === 'string') {\n name = fromName;\n }\n\n if (name === undefined) {\n throw new Error('Could not extract file name from the provided input.');\n }\n\n if (name.startsWith('https://')) {\n const suffix = name.split('files/')[1];\n const match = suffix.match(/[a-z0-9]+/);\n if (match === null) {\n throw new Error(`Could not extract file name from URI ${name}`);\n }\n name = match[0];\n } else if (name.startsWith('files/')) {\n name = name.split('files/')[1];\n }\n return name;\n}\n\nexport function tModelsUrl(\n apiClient: ApiClient,\n baseModels: boolean | unknown,\n): string {\n let res: string;\n if (apiClient.isVertexAI()) {\n res = baseModels ? 'publishers/google/models' : 'models';\n } else {\n res = baseModels ? 'models' : 'tunedModels';\n }\n return res;\n}\n\nexport function tExtractModels(response: unknown): Record[] {\n for (const key of ['models', 'tunedModels', 'publisherModels']) {\n if (hasField(response, key)) {\n return (response as Record)[key] as Record<\n string,\n unknown\n >[];\n }\n }\n return [];\n}\n\nfunction hasField(data: unknown, fieldName: string): boolean {\n return data !== null && typeof data === 'object' && fieldName in data;\n}\n\nexport function mcpToGeminiTool(\n mcpTool: McpTool,\n config: types.CallableToolConfig = {},\n): types.Tool {\n const mcpToolSchema = mcpTool as Record;\n const functionDeclaration: Record = {\n name: mcpToolSchema['name'],\n description: mcpToolSchema['description'],\n parametersJsonSchema: mcpToolSchema['inputSchema'],\n };\n if (config.behavior) {\n functionDeclaration['behavior'] = config.behavior;\n }\n\n const geminiTool = {\n functionDeclarations: [\n functionDeclaration as unknown as types.FunctionDeclaration,\n ],\n };\n\n return geminiTool;\n}\n\n/**\n * Converts a list of MCP tools to a single Gemini tool with a list of function\n * declarations.\n */\nexport function mcpToolsToGeminiTool(\n mcpTools: McpTool[],\n config: types.CallableToolConfig = {},\n): types.Tool {\n const functionDeclarations: types.FunctionDeclaration[] = [];\n const toolNames = new Set();\n for (const mcpTool of mcpTools) {\n const mcpToolName = mcpTool.name as string;\n if (toolNames.has(mcpToolName)) {\n throw new Error(\n `Duplicate function name ${\n mcpToolName\n } found in MCP tools. Please ensure function names are unique.`,\n );\n }\n toolNames.add(mcpToolName);\n const geminiTool = mcpToGeminiTool(mcpTool, config);\n if (geminiTool.functionDeclarations) {\n functionDeclarations.push(...geminiTool.functionDeclarations);\n }\n }\n\n return {functionDeclarations: functionDeclarations};\n}\n\n// Transforms a source input into a BatchJobSource object with validation.\nexport function tBatchJobSource(\n apiClient: ApiClient,\n src: string | types.InlinedRequest[] | types.BatchJobSource,\n): types.BatchJobSource {\n if (typeof src !== 'string' && !Array.isArray(src)) {\n if (apiClient && apiClient.isVertexAI()) {\n if (src.gcsUri && src.bigqueryUri) {\n throw new Error('Only one of `gcsUri` or `bigqueryUri` can be set.');\n } else if (!src.gcsUri && !src.bigqueryUri) {\n throw new Error('One of `gcsUri` or `bigqueryUri` must be set.');\n }\n } else {\n // Logic for non-Vertex AI client (inlined_requests, file_name)\n if (src.inlinedRequests && src.fileName) {\n throw new Error(\n 'Only one of `inlinedRequests` or `fileName` can be set.',\n );\n } else if (!src.inlinedRequests && !src.fileName) {\n throw new Error('One of `inlinedRequests` or `fileName` must be set.');\n }\n }\n return src;\n }\n // If src is an array (list in Python)\n else if (Array.isArray(src)) {\n return {inlinedRequests: src};\n } else if (typeof src === 'string') {\n if (src.startsWith('gs://')) {\n return {\n format: 'jsonl',\n gcsUri: [src], // GCS URI is expected as an array\n };\n } else if (src.startsWith('bq://')) {\n return {\n format: 'bigquery',\n bigqueryUri: src,\n };\n } else if (src.startsWith('files/')) {\n return {\n fileName: src,\n };\n }\n }\n throw new Error(`Unsupported source: ${src}`);\n}\n\nexport function tBatchJobDestination(\n dest: string | types.BatchJobDestination,\n): types.BatchJobDestination {\n if (typeof dest !== 'string') {\n return dest as types.BatchJobDestination;\n }\n const destString = dest as string;\n if (destString.startsWith('gs://')) {\n return {\n format: 'jsonl',\n gcsUri: destString,\n };\n } else if (destString.startsWith('bq://')) {\n return {\n format: 'bigquery',\n bigqueryUri: destString,\n };\n } else {\n throw new Error(`Unsupported destination: ${destString}`);\n }\n}\n\nexport function tBatchJobName(apiClient: ApiClient, name: unknown): string {\n const nameString = name as string;\n if (!apiClient.isVertexAI()) {\n const mldevPattern = /batches\\/[^/]+$/;\n\n if (mldevPattern.test(nameString)) {\n return nameString.split('/').pop() as string;\n } else {\n throw new Error(`Invalid batch job name: ${nameString}.`);\n }\n }\n\n const vertexPattern =\n /^projects\\/[^/]+\\/locations\\/[^/]+\\/batchPredictionJobs\\/[^/]+$/;\n\n if (vertexPattern.test(nameString)) {\n return nameString.split('/').pop() as string;\n } else if (/^\\d+$/.test(nameString)) {\n return nameString;\n } else {\n throw new Error(`Invalid batch job name: ${nameString}.`);\n }\n}\n\nexport function tJobState(state: unknown): string {\n const stateString = state as string;\n if (stateString === 'BATCH_STATE_UNSPECIFIED') {\n return 'JOB_STATE_UNSPECIFIED';\n } else if (stateString === 'BATCH_STATE_PENDING') {\n return 'JOB_STATE_PENDING';\n } else if (stateString === 'BATCH_STATE_SUCCEEDED') {\n return 'JOB_STATE_SUCCEEDED';\n } else if (stateString === 'BATCH_STATE_FAILED') {\n return 'JOB_STATE_FAILED';\n } else if (stateString === 'BATCH_STATE_CANCELLED') {\n return 'JOB_STATE_CANCELLED';\n } else {\n return stateString;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined\n ) {\n throw new Error(\n 'modelSelectionConfig parameter is not supported in Gemini API.',\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function inlinedRequestToMldev(\n apiClient: ApiClient,\n fromObject: types.InlinedRequest,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['request', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['request', 'contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['request', 'generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function batchJobSourceToMldev(\n apiClient: ApiClient,\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['format']) !== undefined) {\n throw new Error('format parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['bigqueryUri']) !== undefined) {\n throw new Error('bigqueryUri parameter is not supported in Gemini API.');\n }\n\n const fromFileName = common.getValueByPath(fromObject, ['fileName']);\n if (fromFileName != null) {\n common.setValueByPath(toObject, ['fileName'], fromFileName);\n }\n\n const fromInlinedRequests = common.getValueByPath(fromObject, [\n 'inlinedRequests',\n ]);\n if (fromInlinedRequests != null) {\n let transformedList = fromInlinedRequests;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return inlinedRequestToMldev(apiClient, item);\n });\n }\n common.setValueByPath(toObject, ['requests', 'requests'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createBatchJobConfigToMldev(\n fromObject: types.CreateBatchJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['batch', 'displayName'],\n fromDisplayName,\n );\n }\n\n if (common.getValueByPath(fromObject, ['dest']) !== undefined) {\n throw new Error('dest parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function createBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['src']);\n if (fromSrc != null) {\n common.setValueByPath(\n toObject,\n ['batch', 'inputConfig'],\n batchJobSourceToMldev(apiClient, t.tBatchJobSource(apiClient, fromSrc)),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createBatchJobConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function cancelBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CancelBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsConfigToMldev(\n fromObject: types.ListBatchJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n if (common.getValueByPath(fromObject, ['filter']) !== undefined) {\n throw new Error('filter parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function listBatchJobsParametersToMldev(\n fromObject: types.ListBatchJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listBatchJobsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function batchJobSourceToVertex(\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['instancesFormat'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsSource', 'uris'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, ['bigqueryUri']);\n if (fromBigqueryUri != null) {\n common.setValueByPath(\n toObject,\n ['bigquerySource', 'inputUri'],\n fromBigqueryUri,\n );\n }\n\n if (common.getValueByPath(fromObject, ['fileName']) !== undefined) {\n throw new Error('fileName parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['inlinedRequests']) !== undefined) {\n throw new Error('inlinedRequests parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationToVertex(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['predictionsFormat'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(\n toObject,\n ['gcsDestination', 'outputUriPrefix'],\n fromGcsUri,\n );\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, ['bigqueryUri']);\n if (fromBigqueryUri != null) {\n common.setValueByPath(\n toObject,\n ['bigqueryDestination', 'outputUri'],\n fromBigqueryUri,\n );\n }\n\n if (common.getValueByPath(fromObject, ['fileName']) !== undefined) {\n throw new Error('fileName parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['inlinedResponses']) !== undefined) {\n throw new Error(\n 'inlinedResponses parameter is not supported in Vertex AI.',\n );\n }\n\n return toObject;\n}\n\nexport function createBatchJobConfigToVertex(\n fromObject: types.CreateBatchJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDest = common.getValueByPath(fromObject, ['dest']);\n if (parentObject !== undefined && fromDest != null) {\n common.setValueByPath(\n parentObject,\n ['outputConfig'],\n batchJobDestinationToVertex(t.tBatchJobDestination(fromDest)),\n );\n }\n\n return toObject;\n}\n\nexport function createBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], t.tModel(apiClient, fromModel));\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['src']);\n if (fromSrc != null) {\n common.setValueByPath(\n toObject,\n ['inputConfig'],\n batchJobSourceToVertex(t.tBatchJobSource(apiClient, fromSrc)),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createBatchJobConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function cancelBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CancelBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsConfigToVertex(\n fromObject: types.ListBatchJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsParametersToVertex(\n fromObject: types.ListBatchJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listBatchJobsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(toObject, ['content'], contentFromMldev(fromContent));\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function jobErrorFromMldev(\n fromObject: types.JobError,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n return toObject;\n}\n\nexport function inlinedResponseFromMldev(\n fromObject: types.InlinedResponse,\n): Record {\n const toObject: Record = {};\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateContentResponseFromMldev(\n fromResponse as types.GenerateContentResponse,\n ),\n );\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationFromMldev(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFileName = common.getValueByPath(fromObject, ['responsesFile']);\n if (fromFileName != null) {\n common.setValueByPath(toObject, ['fileName'], fromFileName);\n }\n\n const fromInlinedResponses = common.getValueByPath(fromObject, [\n 'inlinedResponses',\n 'inlinedResponses',\n ]);\n if (fromInlinedResponses != null) {\n let transformedList = fromInlinedResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return inlinedResponseFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['inlinedResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function batchJobFromMldev(\n fromObject: types.BatchJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, [\n 'metadata',\n 'displayName',\n ]);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['metadata', 'state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tJobState(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'createTime',\n ]);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'endTime',\n ]);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'updateTime',\n ]);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['metadata', 'model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromDest = common.getValueByPath(fromObject, ['metadata', 'output']);\n if (fromDest != null) {\n common.setValueByPath(\n toObject,\n ['dest'],\n batchJobDestinationFromMldev(fromDest),\n );\n }\n\n return toObject;\n}\n\nexport function listBatchJobsResponseFromMldev(\n fromObject: types.ListBatchJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromBatchJobs = common.getValueByPath(fromObject, ['operations']);\n if (fromBatchJobs != null) {\n let transformedList = fromBatchJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return batchJobFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['batchJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteResourceJobFromMldev(\n fromObject: types.DeleteResourceJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function jobErrorFromVertex(\n fromObject: types.JobError,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n return toObject;\n}\n\nexport function batchJobSourceFromVertex(\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['instancesFormat']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsSource', 'uris']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, [\n 'bigquerySource',\n 'inputUri',\n ]);\n if (fromBigqueryUri != null) {\n common.setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri);\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationFromVertex(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['predictionsFormat']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, [\n 'gcsDestination',\n 'outputUriPrefix',\n ]);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, [\n 'bigqueryDestination',\n 'outputUri',\n ]);\n if (fromBigqueryUri != null) {\n common.setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri);\n }\n\n return toObject;\n}\n\nexport function batchJobFromVertex(\n fromObject: types.BatchJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tJobState(fromState));\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['inputConfig']);\n if (fromSrc != null) {\n common.setValueByPath(toObject, ['src'], batchJobSourceFromVertex(fromSrc));\n }\n\n const fromDest = common.getValueByPath(fromObject, ['outputConfig']);\n if (fromDest != null) {\n common.setValueByPath(\n toObject,\n ['dest'],\n batchJobDestinationFromVertex(fromDest),\n );\n }\n\n return toObject;\n}\n\nexport function listBatchJobsResponseFromVertex(\n fromObject: types.ListBatchJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromBatchJobs = common.getValueByPath(fromObject, [\n 'batchPredictionJobs',\n ]);\n if (fromBatchJobs != null) {\n let transformedList = fromBatchJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return batchJobFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['batchJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteResourceJobFromVertex(\n fromObject: types.DeleteResourceJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError));\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Pagers for the GenAI List APIs.\n */\n\nimport * as types from '../src/types';\n\nexport enum PagedItem {\n PAGED_ITEM_BATCH_JOBS = 'batchJobs',\n PAGED_ITEM_MODELS = 'models',\n PAGED_ITEM_TUNING_JOBS = 'tuningJobs',\n PAGED_ITEM_FILES = 'files',\n PAGED_ITEM_CACHED_CONTENTS = 'cachedContents',\n}\n\ninterface PagedItemConfig {\n config?: {\n pageToken?: string;\n pageSize?: number;\n };\n}\n\ninterface PagedItemResponse {\n nextPageToken?: string;\n sdkHttpResponse?: types.HttpResponse;\n batchJobs?: T[];\n models?: T[];\n tuningJobs?: T[];\n files?: T[];\n cachedContents?: T[];\n}\n\n/**\n * Pager class for iterating through paginated results.\n */\nexport class Pager implements AsyncIterable {\n private nameInternal!: PagedItem;\n private pageInternal: T[] = [];\n private paramsInternal: PagedItemConfig = {};\n private pageInternalSize!: number;\n private sdkHttpResponseInternal?: types.HttpResponse;\n protected requestInternal!: (\n params: PagedItemConfig,\n ) => Promise>;\n protected idxInternal!: number;\n\n constructor(\n name: PagedItem,\n request: (params: PagedItemConfig) => Promise>,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.requestInternal = request;\n this.init(name, response, params);\n }\n\n private init(\n name: PagedItem,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.nameInternal = name;\n this.pageInternal = response[this.nameInternal] || [];\n\n this.sdkHttpResponseInternal = response?.sdkHttpResponse;\n this.idxInternal = 0;\n let requestParams: PagedItemConfig = {config: {}};\n if (!params || Object.keys(params).length === 0) {\n requestParams = {config: {}};\n } else if (typeof params === 'object') {\n requestParams = {...params};\n } else {\n requestParams = params;\n }\n if (requestParams['config']) {\n requestParams['config']['pageToken'] = response['nextPageToken'];\n }\n this.paramsInternal = requestParams;\n this.pageInternalSize =\n requestParams['config']?.['pageSize'] ?? this.pageInternal.length;\n }\n\n private initNextPage(response: PagedItemResponse): void {\n this.init(this.nameInternal, response, this.paramsInternal);\n }\n\n /**\n * Returns the current page, which is a list of items.\n *\n * @remarks\n * The first page is retrieved when the pager is created. The returned list of\n * items could be a subset of the entire list.\n */\n get page(): T[] {\n return this.pageInternal;\n }\n\n /**\n * Returns the type of paged item (for example, ``batch_jobs``).\n */\n get name(): PagedItem {\n return this.nameInternal;\n }\n\n /**\n * Returns the length of the page fetched each time by this pager.\n *\n * @remarks\n * The number of items in the page is less than or equal to the page length.\n */\n get pageSize(): number {\n return this.pageInternalSize;\n }\n\n /**\n * Returns the headers of the API response.\n */\n get sdkHttpResponse(): types.HttpResponse | undefined {\n return this.sdkHttpResponseInternal;\n }\n\n /**\n * Returns the parameters when making the API request for the next page.\n *\n * @remarks\n * Parameters contain a set of optional configs that can be\n * used to customize the API request. For example, the `pageToken` parameter\n * contains the token to request the next page.\n */\n get params(): PagedItemConfig {\n return this.paramsInternal;\n }\n\n /**\n * Returns the total number of items in the current page.\n */\n get pageLength(): number {\n return this.pageInternal.length;\n }\n\n /**\n * Returns the item at the given index.\n */\n getItem(index: number): T {\n return this.pageInternal[index];\n }\n\n /**\n * Returns an async iterator that support iterating through all items\n * retrieved from the API.\n *\n * @remarks\n * The iterator will automatically fetch the next page if there are more items\n * to fetch from the API.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * for await (const file of pager) {\n * console.log(file.name);\n * }\n * ```\n */\n [Symbol.asyncIterator](): AsyncIterator {\n return {\n next: async () => {\n if (this.idxInternal >= this.pageLength) {\n if (this.hasNextPage()) {\n await this.nextPage();\n } else {\n return {value: undefined, done: true};\n }\n }\n const item = this.getItem(this.idxInternal);\n this.idxInternal += 1;\n return {value: item, done: false};\n },\n return: async () => {\n return {value: undefined, done: true};\n },\n };\n }\n\n /**\n * Fetches the next page of items. This makes a new API request.\n *\n * @throws {Error} If there are no more pages to fetch.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * let page = pager.page;\n * while (true) {\n * for (const file of page) {\n * console.log(file.name);\n * }\n * if (!pager.hasNextPage()) {\n * break;\n * }\n * page = await pager.nextPage();\n * }\n * ```\n */\n async nextPage(): Promise {\n if (!this.hasNextPage()) {\n throw new Error('No more pages to fetch.');\n }\n const response = await this.requestInternal(this.params);\n this.initNextPage(response);\n return this.page;\n }\n\n /**\n * Returns true if there are more pages to fetch from the API.\n */\n hasNextPage(): boolean {\n if (this.params['config']?.['pageToken'] !== undefined) {\n return true;\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_batches_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Batches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Create batch job.\n *\n * @param params - The parameters for create batch job request.\n * @return The created batch job.\n *\n * @example\n * ```ts\n * const response = await ai.batches.create({\n * model: 'gemini-2.0-flash',\n * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'},\n * config: {\n * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'},\n * }\n * });\n * console.log(response);\n * ```\n */\n create = async (\n params: types.CreateBatchJobParameters,\n ): Promise => {\n if (this.apiClient.isVertexAI()) {\n const timestamp = Date.now();\n const timestampStr = timestamp.toString();\n if (Array.isArray(params.src)) {\n throw new Error(\n 'InlinedRequest[] is not supported in Vertex AI. Please use ' +\n 'Google Cloud Storage URI or BigQuery URI instead.',\n );\n }\n params.config = params.config || {};\n if (params.config.displayName === undefined) {\n params.config.displayName = 'genaiBatchJob_${timestampStr}';\n }\n if (params.config.dest === undefined && typeof params.src === 'string') {\n if (params.src.startsWith('gs://') && params.src.endsWith('.jsonl')) {\n params.config.dest = `${params.src.slice(0, -6)}/dest`;\n } else if (params.src.startsWith('bq://')) {\n params.config.dest =\n `${params.src}_dest_${timestampStr}` as unknown as string;\n } else {\n throw new Error('Unsupported source:' + params.src);\n }\n }\n } else {\n if (\n Array.isArray(params.src) ||\n (typeof params.src !== 'string' && params.src.inlinedRequests)\n ) {\n // Move system instruction to httpOptions extraBody.\n\n let path: string = '';\n let queryParams: Record = {};\n const body = converters.createBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchGenerateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n // Move system instruction to 'request':\n // {'systemInstruction': system_instruction}\n const batch = body['batch'] as {[key: string]: unknown};\n const inputConfig = batch['inputConfig'] as {[key: string]: unknown};\n const requestsWrapper = inputConfig['requests'] as {\n [key: string]: unknown;\n };\n const requests = requestsWrapper['requests'] as Array<{\n [key: string]: unknown;\n }>;\n const newRequests = [];\n for (const request of requests) {\n const requestDict = request as {[key: string]: unknown};\n if (requestDict['systemInstruction']) {\n const systemInstructionValue = requestDict['systemInstruction'];\n delete requestDict['systemInstruction'];\n const requestContent = requestDict['request'] as {\n [key: string]: unknown;\n };\n requestContent['systemInstruction'] = systemInstructionValue;\n requestDict['request'] = requestContent;\n }\n newRequests.push(requestDict);\n }\n requestsWrapper['requests'] = newRequests;\n\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n return await this.createInternal(params);\n };\n\n /**\n * Lists batch job configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of batch jobs.\n *\n * @example\n * ```ts\n * const batchJobs = await ai.batches.list({config: {'pageSize': 2}});\n * for await (const batchJob of batchJobs) {\n * console.log(batchJob);\n * }\n * ```\n */\n list = async (\n params: types.ListBatchJobsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_BATCH_JOBS,\n (x: types.ListBatchJobsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Internal method to create batch job.\n *\n * @param params - The parameters for create batch job request.\n * @return The created batch job.\n *\n */\n private async createInternal(\n params: types.CreateBatchJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromVertex(apiResponse);\n\n return resp as types.BatchJob;\n });\n } else {\n const body = converters.createBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchGenerateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n\n /**\n * Gets batch job configurations.\n *\n * @param params - The parameters for the get request.\n * @return The batch job.\n *\n * @example\n * ```ts\n * await ai.batches.get({name: '...'}); // The server-generated resource name.\n * ```\n */\n async get(params: types.GetBatchJobParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromVertex(apiResponse);\n\n return resp as types.BatchJob;\n });\n } else {\n const body = converters.getBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n\n /**\n * Cancels a batch job.\n *\n * @param params - The parameters for the cancel request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.batches.cancel({name: '...'}); // The server-generated resource name.\n * ```\n */\n async cancel(params: types.CancelBatchJobParameters): Promise {\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.cancelBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n } else {\n const body = converters.cancelBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n }\n }\n\n private async listInternal(\n params: types.ListBatchJobsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listBatchJobsParametersToVertex(params);\n path = common.formatMap(\n 'batchPredictionJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListBatchJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listBatchJobsResponseFromVertex(apiResponse);\n const typedResp = new types.ListBatchJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listBatchJobsParametersToMldev(params);\n path = common.formatMap(\n 'batches',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListBatchJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listBatchJobsResponseFromMldev(apiResponse);\n const typedResp = new types.ListBatchJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Deletes a batch job.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.batches.delete({name: '...'}); // The server-generated resource name.\n * ```\n */\n async delete(\n params: types.DeleteBatchJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteResourceJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteResourceJobFromVertex(apiResponse);\n\n return resp as types.DeleteResourceJob;\n });\n } else {\n const body = converters.deleteBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteResourceJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteResourceJobFromMldev(apiResponse);\n\n return resp as types.DeleteResourceJob;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToMldev(\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['contents'], transformedList);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['kmsKeyName']) !== undefined) {\n throw new Error('kmsKeyName parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToMldev(\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToMldev(\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToMldev(\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(\n fromObject: types.EnterpriseWebSearch,\n): Record {\n const toObject: Record = {};\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToVertex(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(fromEnterpriseWebSearch),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToVertex(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToVertex(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToVertex(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToVertex(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToVertex(\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['contents'], transformedList);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(fromToolConfig),\n );\n }\n\n const fromKmsKeyName = common.getValueByPath(fromObject, ['kmsKeyName']);\n if (parentObject !== undefined && fromKmsKeyName != null) {\n common.setValueByPath(\n parentObject,\n ['encryption_spec', 'kmsKeyName'],\n fromKmsKeyName,\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToVertex(\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToVertex(\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToVertex(\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function cachedContentFromMldev(\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromMldev(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromMldev(\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n let transformedList = fromCachedContents;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return cachedContentFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['cachedContents'], transformedList);\n }\n\n return toObject;\n}\n\nexport function cachedContentFromVertex(\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromVertex(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromVertex(\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n let transformedList = fromCachedContents;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return cachedContentFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['cachedContents'], transformedList);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_caches_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Caches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists cached content configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of cached contents.\n *\n * @example\n * ```ts\n * const cachedContents = await ai.caches.list({config: {'pageSize': 2}});\n * for await (const cachedContent of cachedContents) {\n * console.log(cachedContent);\n * }\n * ```\n */\n list = async (\n params: types.ListCachedContentsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_CACHED_CONTENTS,\n (x: types.ListCachedContentsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a cached contents resource.\n *\n * @remarks\n * Context caching is only supported for specific models. See [Gemini\n * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac)\n * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models)\n * for more information.\n *\n * @param params - The parameters for the create request.\n * @return The created cached content.\n *\n * @example\n * ```ts\n * const contents = ...; // Initialize the content to cache.\n * const response = await ai.caches.create({\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'contents': contents,\n * 'displayName': 'test cache',\n * 'systemInstruction': 'What is the sum of the two pdfs?',\n * 'ttl': '86400s',\n * }\n * });\n * ```\n */\n async create(\n params: types.CreateCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.createCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Gets cached content configurations.\n *\n * @param params - The parameters for the get request.\n * @return The cached content.\n *\n * @example\n * ```ts\n * await ai.caches.get({name: '...'}); // The server-generated resource name.\n * ```\n */\n async get(\n params: types.GetCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.getCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Deletes cached content.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.caches.delete({name: '...'}); // The server-generated resource name.\n * ```\n */\n async delete(\n params: types.DeleteCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteCachedContentResponseFromVertex();\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteCachedContentResponseFromMldev();\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates cached content configurations.\n *\n * @param params - The parameters for the update request.\n * @return The updated cached content.\n *\n * @example\n * ```ts\n * const response = await ai.caches.update({\n * name: '...', // The server-generated resource name.\n * config: {'ttl': '7600s'}\n * });\n * ```\n */\n async update(\n params: types.UpdateCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.updateCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n private async listInternal(\n params: types.ListCachedContentsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listCachedContentsParametersToVertex(params);\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListCachedContentsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.listCachedContentsResponseFromVertex(apiResponse);\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listCachedContentsParametersToMldev(params);\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListCachedContentsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.listCachedContentsResponseFromMldev(apiResponse);\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client.js';\nimport * as t from './_transformers.js';\nimport {Models} from './models.js';\nimport * as types from './types.js';\n\n/**\n * Returns true if the response is valid, false otherwise.\n */\nfunction isValidResponse(response: types.GenerateContentResponse): boolean {\n if (response.candidates == undefined || response.candidates.length === 0) {\n return false;\n }\n const content = response.candidates[0]?.content;\n if (content === undefined) {\n return false;\n }\n return isValidContent(content);\n}\n\nfunction isValidContent(content: types.Content): boolean {\n if (content.parts === undefined || content.parts.length === 0) {\n return false;\n }\n for (const part of content.parts) {\n if (part === undefined || Object.keys(part).length === 0) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Validates the history contains the correct roles.\n *\n * @throws Error if the history does not start with a user turn.\n * @throws Error if the history contains an invalid role.\n */\nfunction validateHistory(history: types.Content[]) {\n // Empty history is valid.\n if (history.length === 0) {\n return;\n }\n for (const content of history) {\n if (content.role !== 'user' && content.role !== 'model') {\n throw new Error(`Role must be user or model, but got ${content.role}.`);\n }\n }\n}\n\n/**\n * Extracts the curated (valid) history from a comprehensive history.\n *\n * @remarks\n * The model may sometimes generate invalid or empty contents(e.g., due to safty\n * filters or recitation). Extracting valid turns from the history\n * ensures that subsequent requests could be accpeted by the model.\n */\nfunction extractCuratedHistory(\n comprehensiveHistory: types.Content[],\n): types.Content[] {\n if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) {\n return [];\n }\n const curatedHistory: types.Content[] = [];\n const length = comprehensiveHistory.length;\n let i = 0;\n while (i < length) {\n if (comprehensiveHistory[i].role === 'user') {\n curatedHistory.push(comprehensiveHistory[i]);\n i++;\n } else {\n const modelOutput: types.Content[] = [];\n let isValid = true;\n while (i < length && comprehensiveHistory[i].role === 'model') {\n modelOutput.push(comprehensiveHistory[i]);\n if (isValid && !isValidContent(comprehensiveHistory[i])) {\n isValid = false;\n }\n i++;\n }\n if (isValid) {\n curatedHistory.push(...modelOutput);\n } else {\n // Remove the last user input when model content is invalid.\n curatedHistory.pop();\n }\n }\n }\n return curatedHistory;\n}\n\n/**\n * A utility class to create a chat session.\n */\nexport class Chats {\n private readonly modelsModule: Models;\n private readonly apiClient: ApiClient;\n\n constructor(modelsModule: Models, apiClient: ApiClient) {\n this.modelsModule = modelsModule;\n this.apiClient = apiClient;\n }\n\n /**\n * Creates a new chat session.\n *\n * @remarks\n * The config in the params will be used for all requests within the chat\n * session unless overridden by a per-request `config` in\n * @see {@link types.SendMessageParameters#config}.\n *\n * @param params - Parameters for creating a chat session.\n * @returns A new chat session.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({\n * model: 'gemini-2.0-flash'\n * config: {\n * temperature: 0.5,\n * maxOutputTokens: 1024,\n * }\n * });\n * ```\n */\n create(params: types.CreateChatParameters) {\n return new Chat(\n this.apiClient,\n this.modelsModule,\n params.model,\n params.config,\n // Deep copy the history to avoid mutating the history outside of the\n // chat session.\n structuredClone(params.history),\n );\n }\n}\n\n/**\n * Chat session that enables sending messages to the model with previous\n * conversation context.\n *\n * @remarks\n * The session maintains all the turns between user and model.\n */\nexport class Chat {\n // A promise to represent the current state of the message being sent to the\n // model.\n private sendPromise: Promise = Promise.resolve();\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly modelsModule: Models,\n private readonly model: string,\n private readonly config: types.GenerateContentConfig = {},\n private history: types.Content[] = [],\n ) {\n validateHistory(history);\n }\n\n /**\n * Sends a message to the model and returns the response.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessageStream} for streaming method.\n * @param params - parameters for sending messages within a chat session.\n * @returns The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessage({\n * message: 'Why is the sky blue?'\n * });\n * console.log(response.text);\n * ```\n */\n async sendMessage(\n params: types.SendMessageParameters,\n ): Promise {\n await this.sendPromise;\n const inputContent = t.tContent(params.message);\n const responsePromise = this.modelsModule.generateContent({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n this.sendPromise = (async () => {\n const response = await responsePromise;\n const outputContent = response.candidates?.[0]?.content;\n\n // Because the AFC input contains the entire curated chat history in\n // addition to the new user input, we need to truncate the AFC history\n // to deduplicate the existing chat history.\n const fullAutomaticFunctionCallingHistory =\n response.automaticFunctionCallingHistory;\n const index = this.getHistory(true).length;\n\n let automaticFunctionCallingHistory: types.Content[] = [];\n if (fullAutomaticFunctionCallingHistory != null) {\n automaticFunctionCallingHistory =\n fullAutomaticFunctionCallingHistory.slice(index) ?? [];\n }\n\n const modelOutput = outputContent ? [outputContent] : [];\n this.recordHistory(\n inputContent,\n modelOutput,\n automaticFunctionCallingHistory,\n );\n return;\n })();\n await this.sendPromise.catch(() => {\n // Resets sendPromise to avoid subsequent calls failing\n this.sendPromise = Promise.resolve();\n });\n return responsePromise;\n }\n\n /**\n * Sends a message to the model and returns the response in chunks.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessage} for non-streaming method.\n * @param params - parameters for sending the message.\n * @return The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessageStream({\n * message: 'Why is the sky blue?'\n * });\n * for await (const chunk of response) {\n * console.log(chunk.text);\n * }\n * ```\n */\n async sendMessageStream(\n params: types.SendMessageParameters,\n ): Promise> {\n await this.sendPromise;\n const inputContent = t.tContent(params.message);\n const streamResponse = this.modelsModule.generateContentStream({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n // Resolve the internal tracking of send completion promise - `sendPromise`\n // for both success and failure response. The actual failure is still\n // propagated by the `await streamResponse`.\n this.sendPromise = streamResponse\n .then(() => undefined)\n .catch(() => undefined);\n const response = await streamResponse;\n const result = this.processStreamResponse(response, inputContent);\n return result;\n }\n\n /**\n * Returns the chat history.\n *\n * @remarks\n * The history is a list of contents alternating between user and model.\n *\n * There are two types of history:\n * - The `curated history` contains only the valid turns between user and\n * model, which will be included in the subsequent requests sent to the model.\n * - The `comprehensive history` contains all turns, including invalid or\n * empty model outputs, providing a complete record of the history.\n *\n * The history is updated after receiving the response from the model,\n * for streaming response, it means receiving the last chunk of the response.\n *\n * The `comprehensive history` is returned by default. To get the `curated\n * history`, set the `curated` parameter to `true`.\n *\n * @param curated - whether to return the curated history or the comprehensive\n * history.\n * @return History contents alternating between user and model for the entire\n * chat session.\n */\n getHistory(curated: boolean = false): types.Content[] {\n const history = curated\n ? extractCuratedHistory(this.history)\n : this.history;\n // Deep copy the history to avoid mutating the history outside of the\n // chat session.\n return structuredClone(history);\n }\n\n private async *processStreamResponse(\n streamResponse: AsyncGenerator,\n inputContent: types.Content,\n ) {\n const outputContent: types.Content[] = [];\n for await (const chunk of streamResponse) {\n if (isValidResponse(chunk)) {\n const content = chunk.candidates?.[0]?.content;\n if (content !== undefined) {\n outputContent.push(content);\n }\n }\n yield chunk;\n }\n this.recordHistory(inputContent, outputContent);\n }\n\n private recordHistory(\n userInput: types.Content,\n modelOutput: types.Content[],\n automaticFunctionCallingHistory?: types.Content[],\n ) {\n let outputContents: types.Content[] = [];\n if (\n modelOutput.length > 0 &&\n modelOutput.every((content) => content.role !== undefined)\n ) {\n outputContents = modelOutput;\n } else {\n // Appends an empty content when model returns empty response, so that the\n // history is always alternating between user and model.\n outputContents.push({\n role: 'model',\n parts: [],\n } as types.Content);\n }\n if (\n automaticFunctionCallingHistory &&\n automaticFunctionCallingHistory.length > 0\n ) {\n this.history.push(\n ...extractCuratedHistory(automaticFunctionCallingHistory!),\n );\n } else {\n this.history.push(userInput);\n }\n this.history.push(...outputContents);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Details for errors from calling the API.\n */\nexport interface ApiErrorInfo {\n /** The error message. */\n message: string;\n /** The HTTP status code. */\n status: number;\n}\n\n/**\n * API errors raised by the GenAI API.\n */\nexport class ApiError extends Error {\n /** HTTP status code */\n status: number;\n\n constructor(options: ApiErrorInfo) {\n super(options.message);\n this.name = 'ApiError';\n this.status = options.status;\n Object.setPrototypeOf(this, ApiError.prototype);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function listFilesConfigToMldev(\n fromObject: types.ListFilesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listFilesParametersToMldev(\n fromObject: types.ListFilesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listFilesConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function fileStatusToMldev(\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileToMldev(fromObject: types.File): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fileStatusToMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function createFileParametersToMldev(\n fromObject: types.CreateFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromFile = common.getValueByPath(fromObject, ['file']);\n if (fromFile != null) {\n common.setValueByPath(toObject, ['file'], fileToMldev(fromFile));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getFileParametersToMldev(\n fromObject: types.GetFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'file'], t.tFileName(fromName));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteFileParametersToMldev(\n fromObject: types.DeleteFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'file'], t.tFileName(fromName));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fileStatusFromMldev(\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileFromMldev(fromObject: types.File): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fileStatusFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function listFilesResponseFromMldev(\n fromObject: types.ListFilesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromFiles = common.getValueByPath(fromObject, ['files']);\n if (fromFiles != null) {\n let transformedList = fromFiles;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return fileFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['files'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createFileResponseFromMldev(\n fromObject: types.CreateFileResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n\nexport function deleteFileResponseFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_files_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Files extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists all current project files from the service.\n *\n * @param params - The parameters for the list request\n * @return The paginated results of the list of files\n *\n * @example\n * The following code prints the names of all files from the service, the\n * size of each page is 10.\n *\n * ```ts\n * const listResponse = await ai.files.list({config: {'pageSize': 10}});\n * for await (const file of listResponse) {\n * console.log(file.name);\n * }\n * ```\n */\n list = async (\n params: types.ListFilesParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_FILES,\n (x: types.ListFilesParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Uploads a file asynchronously to the Gemini API.\n * This method is not available in Vertex AI.\n * Supported upload sources:\n * - Node.js: File path (string) or Blob object.\n * - Browser: Blob object (e.g., File).\n *\n * @remarks\n * The `mimeType` can be specified in the `config` parameter. If omitted:\n * - For file path (string) inputs, the `mimeType` will be inferred from the\n * file extension.\n * - For Blob object inputs, the `mimeType` will be set to the Blob's `type`\n * property.\n * Somex eamples for file extension to mimeType mapping:\n * .txt -> text/plain\n * .json -> application/json\n * .jpg -> image/jpeg\n * .png -> image/png\n * .mp3 -> audio/mpeg\n * .mp4 -> video/mp4\n *\n * This section can contain multiple paragraphs and code examples.\n *\n * @param params - Optional parameters specified in the\n * `types.UploadFileParameters` interface.\n * @see {@link types.UploadFileParameters#config} for the optional\n * config in the parameters.\n * @return A promise that resolves to a `types.File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n * the `mimeType` can be provided in the `params.config` parameter.\n * @throws An error occurs if a suitable upload location cannot be established.\n *\n * @example\n * The following code uploads a file to Gemini API.\n *\n * ```ts\n * const file = await ai.files.upload({file: 'file.txt', config: {\n * mimeType: 'text/plain',\n * }});\n * console.log(file.name);\n * ```\n */\n async upload(params: types.UploadFileParameters): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'Vertex AI does not support uploading files. You can share files through a GCS bucket.',\n );\n }\n\n return this.apiClient\n .uploadFile(params.file, params.config)\n .then((response) => {\n const file = converters.fileFromMldev(response);\n return file as types.File;\n });\n }\n\n /**\n * Downloads a remotely stored file asynchronously to a location specified in\n * the `params` object. This method only works on Node environment, to\n * download files in the browser, use a browser compliant method like an \n * tag.\n *\n * @param params - The parameters for the download request.\n *\n * @example\n * The following code downloads an example file named \"files/mehozpxf877d\" as\n * \"file.txt\".\n *\n * ```ts\n * await ai.files.download({file: file.name, downloadPath: 'file.txt'});\n * ```\n */\n\n async download(params: types.DownloadFileParameters): Promise {\n await this.apiClient.downloadFile(params);\n }\n\n private async listInternal(\n params: types.ListFilesParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.listFilesParametersToMldev(params);\n path = common.formatMap('files', body['_url'] as Record);\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListFilesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listFilesResponseFromMldev(apiResponse);\n const typedResp = new types.ListFilesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async createInternal(\n params: types.CreateFileParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createFileParametersToMldev(params);\n path = common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.createFileResponseFromMldev(apiResponse);\n const typedResp = new types.CreateFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Retrieves the file information from the service.\n *\n * @param params - The parameters for the get request\n * @return The Promise that resolves to the types.File object requested.\n *\n * @example\n * ```ts\n * const config: GetFileParameters = {\n * name: fileName,\n * };\n * file = await ai.files.get(config);\n * console.log(file.name);\n * ```\n */\n async get(params: types.GetFileParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.getFileParametersToMldev(params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.fileFromMldev(apiResponse);\n\n return resp as types.File;\n });\n }\n }\n\n /**\n * Deletes a remotely stored file.\n *\n * @param params - The parameters for the delete request.\n * @return The DeleteFileResponse, the response for the delete method.\n *\n * @example\n * The following code deletes an example file named \"files/mehozpxf877d\".\n *\n * ```ts\n * await ai.files.delete({name: file.name});\n * ```\n */\n async delete(\n params: types.DeleteFileParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.deleteFileParametersToMldev(params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteFileResponseFromMldev();\n const typedResp = new types.DeleteFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToMldev(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n if (common.getValueByPath(fromObject, ['transparent']) !== undefined) {\n throw new Error('transparent parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToMldev(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToMldev(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToMldev(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToMldev(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToMldev(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToMldev(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToMldev(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToMldev(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToMldev(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function activityStartToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function activityEndToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function liveSendRealtimeInputParametersToMldev(\n fromObject: types.LiveSendRealtimeInputParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMedia = common.getValueByPath(fromObject, ['media']);\n if (fromMedia != null) {\n common.setValueByPath(toObject, ['mediaChunks'], t.tBlobs(fromMedia));\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], t.tAudioBlob(fromAudio));\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], t.tImageBlob(fromVideo));\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToMldev());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToMldev());\n }\n\n return toObject;\n}\n\nexport function liveClientSetupToMldev(\n fromObject: types.LiveClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig != null) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction != null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(toObject, ['tools'], transformedList);\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (fromRealtimeInputConfig != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (fromSessionResumption != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (fromContextWindowCompression != null) {\n common.setValueByPath(\n toObject,\n ['contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (fromInputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (fromOutputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (fromProactivity != null) {\n common.setValueByPath(\n toObject,\n ['proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveClientContentToMldev(\n fromObject: types.LiveClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromTurns = common.getValueByPath(fromObject, ['turns']);\n if (fromTurns != null) {\n let transformedList = fromTurns;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['turns'], transformedList);\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n return toObject;\n}\n\nexport function liveClientRealtimeInputToMldev(\n fromObject: types.LiveClientRealtimeInput,\n): Record {\n const toObject: Record = {};\n\n const fromMediaChunks = common.getValueByPath(fromObject, ['mediaChunks']);\n if (fromMediaChunks != null) {\n common.setValueByPath(toObject, ['mediaChunks'], fromMediaChunks);\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], fromAudio);\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], fromVideo);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToMldev());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToMldev());\n }\n\n return toObject;\n}\n\nexport function functionResponseToMldev(\n fromObject: types.FunctionResponse,\n): Record {\n const toObject: Record = {};\n\n const fromWillContinue = common.getValueByPath(fromObject, ['willContinue']);\n if (fromWillContinue != null) {\n common.setValueByPath(toObject, ['willContinue'], fromWillContinue);\n }\n\n const fromScheduling = common.getValueByPath(fromObject, ['scheduling']);\n if (fromScheduling != null) {\n common.setValueByPath(toObject, ['scheduling'], fromScheduling);\n }\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n return toObject;\n}\n\nexport function liveClientToolResponseToMldev(\n fromObject: types.LiveClientToolResponse,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionResponses = common.getValueByPath(fromObject, [\n 'functionResponses',\n ]);\n if (fromFunctionResponses != null) {\n let transformedList = fromFunctionResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionResponseToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveClientMessageToMldev(\n fromObject: types.LiveClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveClientSetupToMldev(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveClientContentToMldev(fromClientContent),\n );\n }\n\n const fromRealtimeInput = common.getValueByPath(fromObject, [\n 'realtimeInput',\n ]);\n if (fromRealtimeInput != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInput'],\n liveClientRealtimeInputToMldev(fromRealtimeInput),\n );\n }\n\n const fromToolResponse = common.getValueByPath(fromObject, ['toolResponse']);\n if (fromToolResponse != null) {\n common.setValueByPath(\n toObject,\n ['toolResponse'],\n liveClientToolResponseToMldev(fromToolResponse),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicConnectParametersToMldev(\n fromObject: types.LiveMusicConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['setup', 'model'], fromModel);\n }\n\n const fromCallbacks = common.getValueByPath(fromObject, ['callbacks']);\n if (fromCallbacks != null) {\n common.setValueByPath(toObject, ['callbacks'], fromCallbacks);\n }\n\n return toObject;\n}\n\nexport function weightedPromptToMldev(\n fromObject: types.WeightedPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromWeight = common.getValueByPath(fromObject, ['weight']);\n if (fromWeight != null) {\n common.setValueByPath(toObject, ['weight'], fromWeight);\n }\n\n return toObject;\n}\n\nexport function liveMusicSetWeightedPromptsParametersToMldev(\n fromObject: types.LiveMusicSetWeightedPromptsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicGenerationConfigToMldev(\n fromObject: types.LiveMusicGenerationConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromGuidance = common.getValueByPath(fromObject, ['guidance']);\n if (fromGuidance != null) {\n common.setValueByPath(toObject, ['guidance'], fromGuidance);\n }\n\n const fromBpm = common.getValueByPath(fromObject, ['bpm']);\n if (fromBpm != null) {\n common.setValueByPath(toObject, ['bpm'], fromBpm);\n }\n\n const fromDensity = common.getValueByPath(fromObject, ['density']);\n if (fromDensity != null) {\n common.setValueByPath(toObject, ['density'], fromDensity);\n }\n\n const fromBrightness = common.getValueByPath(fromObject, ['brightness']);\n if (fromBrightness != null) {\n common.setValueByPath(toObject, ['brightness'], fromBrightness);\n }\n\n const fromScale = common.getValueByPath(fromObject, ['scale']);\n if (fromScale != null) {\n common.setValueByPath(toObject, ['scale'], fromScale);\n }\n\n const fromMuteBass = common.getValueByPath(fromObject, ['muteBass']);\n if (fromMuteBass != null) {\n common.setValueByPath(toObject, ['muteBass'], fromMuteBass);\n }\n\n const fromMuteDrums = common.getValueByPath(fromObject, ['muteDrums']);\n if (fromMuteDrums != null) {\n common.setValueByPath(toObject, ['muteDrums'], fromMuteDrums);\n }\n\n const fromOnlyBassAndDrums = common.getValueByPath(fromObject, [\n 'onlyBassAndDrums',\n ]);\n if (fromOnlyBassAndDrums != null) {\n common.setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums);\n }\n\n const fromMusicGenerationMode = common.getValueByPath(fromObject, [\n 'musicGenerationMode',\n ]);\n if (fromMusicGenerationMode != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationMode'],\n fromMusicGenerationMode,\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicSetConfigParametersToMldev(\n fromObject: types.LiveMusicSetConfigParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigToMldev(fromMusicGenerationConfig),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicClientSetupToMldev(\n fromObject: types.LiveMusicClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientContentToMldev(\n fromObject: types.LiveMusicClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientMessageToMldev(\n fromObject: types.LiveMusicClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveMusicClientSetupToMldev(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveMusicClientContentToMldev(fromClientContent),\n );\n }\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigToMldev(fromMusicGenerationConfig),\n );\n }\n\n const fromPlaybackControl = common.getValueByPath(fromObject, [\n 'playbackControl',\n ]);\n if (fromPlaybackControl != null) {\n common.setValueByPath(toObject, ['playbackControl'], fromPlaybackControl);\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(fromVoiceConfig),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined\n ) {\n throw new Error(\n 'multiSpeakerVoiceConfig parameter is not supported in Vertex AI.',\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(\n fromObject: types.EnterpriseWebSearch,\n): Record {\n const toObject: Record = {};\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToVertex(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(fromEnterpriseWebSearch),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToVertex(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToVertex(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n const fromTransparent = common.getValueByPath(fromObject, ['transparent']);\n if (fromTransparent != null) {\n common.setValueByPath(toObject, ['transparent'], fromTransparent);\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToVertex(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToVertex(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToVertex(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToVertex(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToVertex(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToVertex(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToVertex(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToVertex(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToVertex(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToVertex(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToVertex(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToVertex(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToVertex(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function activityStartToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function activityEndToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function liveSendRealtimeInputParametersToVertex(\n fromObject: types.LiveSendRealtimeInputParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMedia = common.getValueByPath(fromObject, ['media']);\n if (fromMedia != null) {\n common.setValueByPath(toObject, ['mediaChunks'], t.tBlobs(fromMedia));\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], t.tAudioBlob(fromAudio));\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], t.tImageBlob(fromVideo));\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToVertex());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToVertex());\n }\n\n return toObject;\n}\n\nexport function liveClientSetupToVertex(\n fromObject: types.LiveClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig != null) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction != null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(toObject, ['tools'], transformedList);\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (fromRealtimeInputConfig != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInputConfig'],\n realtimeInputConfigToVertex(fromRealtimeInputConfig),\n );\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (fromSessionResumption != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumption'],\n sessionResumptionConfigToVertex(fromSessionResumption),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (fromContextWindowCompression != null) {\n common.setValueByPath(\n toObject,\n ['contextWindowCompression'],\n contextWindowCompressionConfigToVertex(fromContextWindowCompression),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (fromInputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (fromOutputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (fromProactivity != null) {\n common.setValueByPath(\n toObject,\n ['proactivity'],\n proactivityConfigToVertex(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveClientContentToVertex(\n fromObject: types.LiveClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromTurns = common.getValueByPath(fromObject, ['turns']);\n if (fromTurns != null) {\n let transformedList = fromTurns;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['turns'], transformedList);\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n return toObject;\n}\n\nexport function liveClientRealtimeInputToVertex(\n fromObject: types.LiveClientRealtimeInput,\n): Record {\n const toObject: Record = {};\n\n const fromMediaChunks = common.getValueByPath(fromObject, ['mediaChunks']);\n if (fromMediaChunks != null) {\n common.setValueByPath(toObject, ['mediaChunks'], fromMediaChunks);\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], fromAudio);\n }\n\n if (common.getValueByPath(fromObject, ['audioStreamEnd']) !== undefined) {\n throw new Error('audioStreamEnd parameter is not supported in Vertex AI.');\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], fromVideo);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToVertex());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToVertex());\n }\n\n return toObject;\n}\n\nexport function functionResponseToVertex(\n fromObject: types.FunctionResponse,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['willContinue']) !== undefined) {\n throw new Error('willContinue parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['scheduling']) !== undefined) {\n throw new Error('scheduling parameter is not supported in Vertex AI.');\n }\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n return toObject;\n}\n\nexport function liveClientToolResponseToVertex(\n fromObject: types.LiveClientToolResponse,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionResponses = common.getValueByPath(fromObject, [\n 'functionResponses',\n ]);\n if (fromFunctionResponses != null) {\n let transformedList = fromFunctionResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionResponseToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveClientMessageToVertex(\n fromObject: types.LiveClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveClientSetupToVertex(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveClientContentToVertex(fromClientContent),\n );\n }\n\n const fromRealtimeInput = common.getValueByPath(fromObject, [\n 'realtimeInput',\n ]);\n if (fromRealtimeInput != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInput'],\n liveClientRealtimeInputToVertex(fromRealtimeInput),\n );\n }\n\n const fromToolResponse = common.getValueByPath(fromObject, ['toolResponse']);\n if (fromToolResponse != null) {\n common.setValueByPath(\n toObject,\n ['toolResponse'],\n liveClientToolResponseToVertex(fromToolResponse),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicConnectParametersToVertex(\n fromObject: types.LiveMusicConnectParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['model']) !== undefined) {\n throw new Error('model parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['callbacks']) !== undefined) {\n throw new Error('callbacks parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveMusicSetWeightedPromptsParametersToVertex(\n fromObject: types.LiveMusicSetWeightedPromptsParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['weightedPrompts']) !== undefined) {\n throw new Error('weightedPrompts parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveMusicSetConfigParametersToVertex(\n fromObject: types.LiveMusicSetConfigParameters,\n): Record {\n const toObject: Record = {};\n\n if (\n common.getValueByPath(fromObject, ['musicGenerationConfig']) !== undefined\n ) {\n throw new Error(\n 'musicGenerationConfig parameter is not supported in Vertex AI.',\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicClientMessageToVertex(\n fromObject: types.LiveMusicClientMessage,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['setup']) !== undefined) {\n throw new Error('setup parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['clientContent']) !== undefined) {\n throw new Error('clientContent parameter is not supported in Vertex AI.');\n }\n\n if (\n common.getValueByPath(fromObject, ['musicGenerationConfig']) !== undefined\n ) {\n throw new Error(\n 'musicGenerationConfig parameter is not supported in Vertex AI.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['playbackControl']) !== undefined) {\n throw new Error('playbackControl parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveServerSetupCompleteFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function transcriptionFromMldev(\n fromObject: types.Transcription,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFinished = common.getValueByPath(fromObject, ['finished']);\n if (fromFinished != null) {\n common.setValueByPath(toObject, ['finished'], fromFinished);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerContentFromMldev(\n fromObject: types.LiveServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn != null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromMldev(fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted != null) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromGenerationComplete = common.getValueByPath(fromObject, [\n 'generationComplete',\n ]);\n if (fromGenerationComplete != null) {\n common.setValueByPath(\n toObject,\n ['generationComplete'],\n fromGenerationComplete,\n );\n }\n\n const fromInputTranscription = common.getValueByPath(fromObject, [\n 'inputTranscription',\n ]);\n if (fromInputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputTranscription'],\n transcriptionFromMldev(fromInputTranscription),\n );\n }\n\n const fromOutputTranscription = common.getValueByPath(fromObject, [\n 'outputTranscription',\n ]);\n if (fromOutputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputTranscription'],\n transcriptionFromMldev(fromOutputTranscription),\n );\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function functionCallFromMldev(\n fromObject: types.FunctionCall,\n): Record {\n const toObject: Record = {};\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs != null) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallFromMldev(\n fromObject: types.LiveServerToolCall,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (fromFunctionCalls != null) {\n let transformedList = fromFunctionCalls;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionCallFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionCalls'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallCancellationFromMldev(\n fromObject: types.LiveServerToolCallCancellation,\n): Record {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds != null) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nexport function modalityTokenCountFromMldev(\n fromObject: types.ModalityTokenCount,\n): Record {\n const toObject: Record = {};\n\n const fromModality = common.getValueByPath(fromObject, ['modality']);\n if (fromModality != null) {\n common.setValueByPath(toObject, ['modality'], fromModality);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function usageMetadataFromMldev(\n fromObject: types.UsageMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromPromptTokenCount = common.getValueByPath(fromObject, [\n 'promptTokenCount',\n ]);\n if (fromPromptTokenCount != null) {\n common.setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n const fromResponseTokenCount = common.getValueByPath(fromObject, [\n 'responseTokenCount',\n ]);\n if (fromResponseTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['responseTokenCount'],\n fromResponseTokenCount,\n );\n }\n\n const fromToolUsePromptTokenCount = common.getValueByPath(fromObject, [\n 'toolUsePromptTokenCount',\n ]);\n if (fromToolUsePromptTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokenCount'],\n fromToolUsePromptTokenCount,\n );\n }\n\n const fromThoughtsTokenCount = common.getValueByPath(fromObject, [\n 'thoughtsTokenCount',\n ]);\n if (fromThoughtsTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['thoughtsTokenCount'],\n fromThoughtsTokenCount,\n );\n }\n\n const fromTotalTokenCount = common.getValueByPath(fromObject, [\n 'totalTokenCount',\n ]);\n if (fromTotalTokenCount != null) {\n common.setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount);\n }\n\n const fromPromptTokensDetails = common.getValueByPath(fromObject, [\n 'promptTokensDetails',\n ]);\n if (fromPromptTokensDetails != null) {\n let transformedList = fromPromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['promptTokensDetails'], transformedList);\n }\n\n const fromCacheTokensDetails = common.getValueByPath(fromObject, [\n 'cacheTokensDetails',\n ]);\n if (fromCacheTokensDetails != null) {\n let transformedList = fromCacheTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['cacheTokensDetails'], transformedList);\n }\n\n const fromResponseTokensDetails = common.getValueByPath(fromObject, [\n 'responseTokensDetails',\n ]);\n if (fromResponseTokensDetails != null) {\n let transformedList = fromResponseTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['responseTokensDetails'], transformedList);\n }\n\n const fromToolUsePromptTokensDetails = common.getValueByPath(fromObject, [\n 'toolUsePromptTokensDetails',\n ]);\n if (fromToolUsePromptTokensDetails != null) {\n let transformedList = fromToolUsePromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokensDetails'],\n transformedList,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerGoAwayFromMldev(\n fromObject: types.LiveServerGoAway,\n): Record {\n const toObject: Record = {};\n\n const fromTimeLeft = common.getValueByPath(fromObject, ['timeLeft']);\n if (fromTimeLeft != null) {\n common.setValueByPath(toObject, ['timeLeft'], fromTimeLeft);\n }\n\n return toObject;\n}\n\nexport function liveServerSessionResumptionUpdateFromMldev(\n fromObject: types.LiveServerSessionResumptionUpdate,\n): Record {\n const toObject: Record = {};\n\n const fromNewHandle = common.getValueByPath(fromObject, ['newHandle']);\n if (fromNewHandle != null) {\n common.setValueByPath(toObject, ['newHandle'], fromNewHandle);\n }\n\n const fromResumable = common.getValueByPath(fromObject, ['resumable']);\n if (fromResumable != null) {\n common.setValueByPath(toObject, ['resumable'], fromResumable);\n }\n\n const fromLastConsumedClientMessageIndex = common.getValueByPath(fromObject, [\n 'lastConsumedClientMessageIndex',\n ]);\n if (fromLastConsumedClientMessageIndex != null) {\n common.setValueByPath(\n toObject,\n ['lastConsumedClientMessageIndex'],\n fromLastConsumedClientMessageIndex,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromMldev(\n fromObject: types.LiveServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveServerSetupCompleteFromMldev(),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromMldev(fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall != null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromMldev(fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (fromToolCallCancellation != null) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromMldev(fromToolCallCancellation),\n );\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(\n toObject,\n ['usageMetadata'],\n usageMetadataFromMldev(fromUsageMetadata),\n );\n }\n\n const fromGoAway = common.getValueByPath(fromObject, ['goAway']);\n if (fromGoAway != null) {\n common.setValueByPath(\n toObject,\n ['goAway'],\n liveServerGoAwayFromMldev(fromGoAway),\n );\n }\n\n const fromSessionResumptionUpdate = common.getValueByPath(fromObject, [\n 'sessionResumptionUpdate',\n ]);\n if (fromSessionResumptionUpdate != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumptionUpdate'],\n liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerSetupCompleteFromMldev(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function weightedPromptFromMldev(\n fromObject: types.WeightedPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromWeight = common.getValueByPath(fromObject, ['weight']);\n if (fromWeight != null) {\n common.setValueByPath(toObject, ['weight'], fromWeight);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientContentFromMldev(\n fromObject: types.LiveMusicClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicGenerationConfigFromMldev(\n fromObject: types.LiveMusicGenerationConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromGuidance = common.getValueByPath(fromObject, ['guidance']);\n if (fromGuidance != null) {\n common.setValueByPath(toObject, ['guidance'], fromGuidance);\n }\n\n const fromBpm = common.getValueByPath(fromObject, ['bpm']);\n if (fromBpm != null) {\n common.setValueByPath(toObject, ['bpm'], fromBpm);\n }\n\n const fromDensity = common.getValueByPath(fromObject, ['density']);\n if (fromDensity != null) {\n common.setValueByPath(toObject, ['density'], fromDensity);\n }\n\n const fromBrightness = common.getValueByPath(fromObject, ['brightness']);\n if (fromBrightness != null) {\n common.setValueByPath(toObject, ['brightness'], fromBrightness);\n }\n\n const fromScale = common.getValueByPath(fromObject, ['scale']);\n if (fromScale != null) {\n common.setValueByPath(toObject, ['scale'], fromScale);\n }\n\n const fromMuteBass = common.getValueByPath(fromObject, ['muteBass']);\n if (fromMuteBass != null) {\n common.setValueByPath(toObject, ['muteBass'], fromMuteBass);\n }\n\n const fromMuteDrums = common.getValueByPath(fromObject, ['muteDrums']);\n if (fromMuteDrums != null) {\n common.setValueByPath(toObject, ['muteDrums'], fromMuteDrums);\n }\n\n const fromOnlyBassAndDrums = common.getValueByPath(fromObject, [\n 'onlyBassAndDrums',\n ]);\n if (fromOnlyBassAndDrums != null) {\n common.setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums);\n }\n\n const fromMusicGenerationMode = common.getValueByPath(fromObject, [\n 'musicGenerationMode',\n ]);\n if (fromMusicGenerationMode != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationMode'],\n fromMusicGenerationMode,\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicSourceMetadataFromMldev(\n fromObject: types.LiveMusicSourceMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveMusicClientContentFromMldev(fromClientContent),\n );\n }\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig),\n );\n }\n\n return toObject;\n}\n\nexport function audioChunkFromMldev(\n fromObject: types.AudioChunk,\n): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSourceMetadata = common.getValueByPath(fromObject, [\n 'sourceMetadata',\n ]);\n if (fromSourceMetadata != null) {\n common.setValueByPath(\n toObject,\n ['sourceMetadata'],\n liveMusicSourceMetadataFromMldev(fromSourceMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerContentFromMldev(\n fromObject: types.LiveMusicServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromAudioChunks = common.getValueByPath(fromObject, ['audioChunks']);\n if (fromAudioChunks != null) {\n let transformedList = fromAudioChunks;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return audioChunkFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['audioChunks'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicFilteredPromptFromMldev(\n fromObject: types.LiveMusicFilteredPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFilteredReason = common.getValueByPath(fromObject, [\n 'filteredReason',\n ]);\n if (fromFilteredReason != null) {\n common.setValueByPath(toObject, ['filteredReason'], fromFilteredReason);\n }\n\n return toObject;\n}\n\nexport function liveMusicServerMessageFromMldev(\n fromObject: types.LiveMusicServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveMusicServerSetupCompleteFromMldev(),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveMusicServerContentFromMldev(fromServerContent),\n );\n }\n\n const fromFilteredPrompt = common.getValueByPath(fromObject, [\n 'filteredPrompt',\n ]);\n if (fromFilteredPrompt != null) {\n common.setValueByPath(\n toObject,\n ['filteredPrompt'],\n liveMusicFilteredPromptFromMldev(fromFilteredPrompt),\n );\n }\n\n return toObject;\n}\n\nexport function liveServerSetupCompleteFromVertex(\n fromObject: types.LiveServerSetupComplete,\n): Record {\n const toObject: Record = {};\n\n const fromSessionId = common.getValueByPath(fromObject, ['sessionId']);\n if (fromSessionId != null) {\n common.setValueByPath(toObject, ['sessionId'], fromSessionId);\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromVertex(\n fromObject: types.Blob,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function transcriptionFromVertex(\n fromObject: types.Transcription,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFinished = common.getValueByPath(fromObject, ['finished']);\n if (fromFinished != null) {\n common.setValueByPath(toObject, ['finished'], fromFinished);\n }\n\n return toObject;\n}\n\nexport function liveServerContentFromVertex(\n fromObject: types.LiveServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn != null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromVertex(fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted != null) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromGenerationComplete = common.getValueByPath(fromObject, [\n 'generationComplete',\n ]);\n if (fromGenerationComplete != null) {\n common.setValueByPath(\n toObject,\n ['generationComplete'],\n fromGenerationComplete,\n );\n }\n\n const fromInputTranscription = common.getValueByPath(fromObject, [\n 'inputTranscription',\n ]);\n if (fromInputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputTranscription'],\n transcriptionFromVertex(fromInputTranscription),\n );\n }\n\n const fromOutputTranscription = common.getValueByPath(fromObject, [\n 'outputTranscription',\n ]);\n if (fromOutputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputTranscription'],\n transcriptionFromVertex(fromOutputTranscription),\n );\n }\n\n return toObject;\n}\n\nexport function functionCallFromVertex(\n fromObject: types.FunctionCall,\n): Record {\n const toObject: Record = {};\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs != null) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallFromVertex(\n fromObject: types.LiveServerToolCall,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (fromFunctionCalls != null) {\n let transformedList = fromFunctionCalls;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionCallFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionCalls'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallCancellationFromVertex(\n fromObject: types.LiveServerToolCallCancellation,\n): Record {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds != null) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nexport function modalityTokenCountFromVertex(\n fromObject: types.ModalityTokenCount,\n): Record {\n const toObject: Record = {};\n\n const fromModality = common.getValueByPath(fromObject, ['modality']);\n if (fromModality != null) {\n common.setValueByPath(toObject, ['modality'], fromModality);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function usageMetadataFromVertex(\n fromObject: types.UsageMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromPromptTokenCount = common.getValueByPath(fromObject, [\n 'promptTokenCount',\n ]);\n if (fromPromptTokenCount != null) {\n common.setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n const fromResponseTokenCount = common.getValueByPath(fromObject, [\n 'candidatesTokenCount',\n ]);\n if (fromResponseTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['responseTokenCount'],\n fromResponseTokenCount,\n );\n }\n\n const fromToolUsePromptTokenCount = common.getValueByPath(fromObject, [\n 'toolUsePromptTokenCount',\n ]);\n if (fromToolUsePromptTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokenCount'],\n fromToolUsePromptTokenCount,\n );\n }\n\n const fromThoughtsTokenCount = common.getValueByPath(fromObject, [\n 'thoughtsTokenCount',\n ]);\n if (fromThoughtsTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['thoughtsTokenCount'],\n fromThoughtsTokenCount,\n );\n }\n\n const fromTotalTokenCount = common.getValueByPath(fromObject, [\n 'totalTokenCount',\n ]);\n if (fromTotalTokenCount != null) {\n common.setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount);\n }\n\n const fromPromptTokensDetails = common.getValueByPath(fromObject, [\n 'promptTokensDetails',\n ]);\n if (fromPromptTokensDetails != null) {\n let transformedList = fromPromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['promptTokensDetails'], transformedList);\n }\n\n const fromCacheTokensDetails = common.getValueByPath(fromObject, [\n 'cacheTokensDetails',\n ]);\n if (fromCacheTokensDetails != null) {\n let transformedList = fromCacheTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['cacheTokensDetails'], transformedList);\n }\n\n const fromResponseTokensDetails = common.getValueByPath(fromObject, [\n 'candidatesTokensDetails',\n ]);\n if (fromResponseTokensDetails != null) {\n let transformedList = fromResponseTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['responseTokensDetails'], transformedList);\n }\n\n const fromToolUsePromptTokensDetails = common.getValueByPath(fromObject, [\n 'toolUsePromptTokensDetails',\n ]);\n if (fromToolUsePromptTokensDetails != null) {\n let transformedList = fromToolUsePromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokensDetails'],\n transformedList,\n );\n }\n\n const fromTrafficType = common.getValueByPath(fromObject, ['trafficType']);\n if (fromTrafficType != null) {\n common.setValueByPath(toObject, ['trafficType'], fromTrafficType);\n }\n\n return toObject;\n}\n\nexport function liveServerGoAwayFromVertex(\n fromObject: types.LiveServerGoAway,\n): Record {\n const toObject: Record = {};\n\n const fromTimeLeft = common.getValueByPath(fromObject, ['timeLeft']);\n if (fromTimeLeft != null) {\n common.setValueByPath(toObject, ['timeLeft'], fromTimeLeft);\n }\n\n return toObject;\n}\n\nexport function liveServerSessionResumptionUpdateFromVertex(\n fromObject: types.LiveServerSessionResumptionUpdate,\n): Record {\n const toObject: Record = {};\n\n const fromNewHandle = common.getValueByPath(fromObject, ['newHandle']);\n if (fromNewHandle != null) {\n common.setValueByPath(toObject, ['newHandle'], fromNewHandle);\n }\n\n const fromResumable = common.getValueByPath(fromObject, ['resumable']);\n if (fromResumable != null) {\n common.setValueByPath(toObject, ['resumable'], fromResumable);\n }\n\n const fromLastConsumedClientMessageIndex = common.getValueByPath(fromObject, [\n 'lastConsumedClientMessageIndex',\n ]);\n if (fromLastConsumedClientMessageIndex != null) {\n common.setValueByPath(\n toObject,\n ['lastConsumedClientMessageIndex'],\n fromLastConsumedClientMessageIndex,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromVertex(\n fromObject: types.LiveServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveServerSetupCompleteFromVertex(fromSetupComplete),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromVertex(fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall != null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromVertex(fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (fromToolCallCancellation != null) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromVertex(fromToolCallCancellation),\n );\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(\n toObject,\n ['usageMetadata'],\n usageMetadataFromVertex(fromUsageMetadata),\n );\n }\n\n const fromGoAway = common.getValueByPath(fromObject, ['goAway']);\n if (fromGoAway != null) {\n common.setValueByPath(\n toObject,\n ['goAway'],\n liveServerGoAwayFromVertex(fromGoAway),\n );\n }\n\n const fromSessionResumptionUpdate = common.getValueByPath(fromObject, [\n 'sessionResumptionUpdate',\n ]);\n if (fromSessionResumptionUpdate != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumptionUpdate'],\n liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerMessageFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as _internal_types from '../_internal_types.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined\n ) {\n throw new Error(\n 'modelSelectionConfig parameter is not supported in Gemini API.',\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToMldev(\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'taskType'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['requests[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['mimeType']) !== undefined) {\n throw new Error('mimeType parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['autoTruncate']) !== undefined) {\n throw new Error('autoTruncate parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n const fromModelForEmbedContent = common.getValueByPath(fromObject, ['model']);\n if (fromModelForEmbedContent !== undefined) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'model'],\n t.tModel(apiClient, fromModelForEmbedContent),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToMldev(\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['negativePrompt']) !== undefined) {\n throw new Error('negativePrompt parameter is not supported in Gemini API.');\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['addWatermark']) !== undefined) {\n throw new Error('addWatermark parameter is not supported in Gemini API.');\n }\n\n const fromImageSize = common.getValueByPath(fromObject, ['imageSize']);\n if (parentObject !== undefined && fromImageSize != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleImageSize'],\n fromImageSize,\n );\n }\n\n if (common.getValueByPath(fromObject, ['enhancePrompt']) !== undefined) {\n throw new Error('enhancePrompt parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listModelsConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ListModelsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n const fromQueryBase = common.getValueByPath(fromObject, ['queryBase']);\n if (parentObject !== undefined && fromQueryBase != null) {\n common.setValueByPath(\n parentObject,\n ['_url', 'models_url'],\n t.tModelsUrl(apiClient, fromQueryBase),\n );\n }\n\n return toObject;\n}\n\nexport function listModelsParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.ListModelsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listModelsConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function updateModelConfigToMldev(\n fromObject: types.UpdateModelConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (parentObject !== undefined && fromDefaultCheckpointId != null) {\n common.setValueByPath(\n parentObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n return toObject;\n}\n\nexport function updateModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateModelConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToMldev(\n fromObject: types.CountTokensConfig,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['systemInstruction']) !== undefined) {\n throw new Error(\n 'systemInstruction parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['tools']) !== undefined) {\n throw new Error('tools parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['generationConfig']) !== undefined) {\n throw new Error(\n 'generationConfig parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToMldev(fromConfig),\n );\n }\n\n return toObject;\n}\n\nexport function imageToMldev(fromObject: types.Image): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosConfigToMldev(\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['fps']) !== undefined) {\n throw new Error('fps parameter is not supported in Gemini API.');\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n if (common.getValueByPath(fromObject, ['resolution']) !== undefined) {\n throw new Error('resolution parameter is not supported in Gemini API.');\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n if (common.getValueByPath(fromObject, ['pubsubTopic']) !== undefined) {\n throw new Error('pubsubTopic parameter is not supported in Gemini API.');\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n if (common.getValueByPath(fromObject, ['generateAudio']) !== undefined) {\n throw new Error('generateAudio parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['lastFrame']) !== undefined) {\n throw new Error('lastFrame parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['referenceImages']) !== undefined) {\n throw new Error(\n 'referenceImages parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['compressionQuality']) !== undefined) {\n throw new Error(\n 'compressionQuality parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToMldev(fromImage),\n );\n }\n\n if (common.getValueByPath(fromObject, ['video']) !== undefined) {\n throw new Error('video parameter is not supported in Gemini API.');\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToVertex(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function modelSelectionConfigToVertex(\n fromObject: types.ModelSelectionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFeatureSelectionPreference = common.getValueByPath(fromObject, [\n 'featureSelectionPreference',\n ]);\n if (fromFeatureSelectionPreference != null) {\n common.setValueByPath(\n toObject,\n ['featureSelectionPreference'],\n fromFeatureSelectionPreference,\n );\n }\n\n return toObject;\n}\n\nexport function safetySettingToVertex(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n const fromMethod = common.getValueByPath(fromObject, ['method']);\n if (fromMethod != null) {\n common.setValueByPath(toObject, ['method'], fromMethod);\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(\n fromObject: types.EnterpriseWebSearch,\n): Record {\n const toObject: Record = {};\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToVertex(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(fromEnterpriseWebSearch),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToVertex(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToVertex(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToVertex(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToVertex(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(fromVoiceConfig),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined\n ) {\n throw new Error(\n 'multiSpeakerVoiceConfig parameter is not supported in Vertex AI.',\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToVertex(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToVertex(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n const fromRoutingConfig = common.getValueByPath(fromObject, [\n 'routingConfig',\n ]);\n if (fromRoutingConfig != null) {\n common.setValueByPath(toObject, ['routingConfig'], fromRoutingConfig);\n }\n\n const fromModelSelectionConfig = common.getValueByPath(fromObject, [\n 'modelSelectionConfig',\n ]);\n if (fromModelSelectionConfig != null) {\n common.setValueByPath(\n toObject,\n ['modelConfig'],\n modelSelectionConfigToVertex(fromModelSelectionConfig),\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(fromToolConfig),\n );\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (parentObject !== undefined && fromLabels != null) {\n common.setValueByPath(parentObject, ['labels'], fromLabels);\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToVertex(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromAudioTimestamp = common.getValueByPath(fromObject, [\n 'audioTimestamp',\n ]);\n if (fromAudioTimestamp != null) {\n common.setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp);\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToVertex(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToVertex(\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'task_type'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['instances[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (parentObject !== undefined && fromMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'mimeType'],\n fromMimeType,\n );\n }\n\n const fromAutoTruncate = common.getValueByPath(fromObject, ['autoTruncate']);\n if (parentObject !== undefined && fromAutoTruncate != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'autoTruncate'],\n fromAutoTruncate,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['instances[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToVertex(\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromImageSize = common.getValueByPath(fromObject, ['imageSize']);\n if (parentObject !== undefined && fromImageSize != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleImageSize'],\n fromImageSize,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function imageToVertex(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function maskReferenceConfigToVertex(\n fromObject: types.MaskReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMaskMode = common.getValueByPath(fromObject, ['maskMode']);\n if (fromMaskMode != null) {\n common.setValueByPath(toObject, ['maskMode'], fromMaskMode);\n }\n\n const fromSegmentationClasses = common.getValueByPath(fromObject, [\n 'segmentationClasses',\n ]);\n if (fromSegmentationClasses != null) {\n common.setValueByPath(toObject, ['maskClasses'], fromSegmentationClasses);\n }\n\n const fromMaskDilation = common.getValueByPath(fromObject, ['maskDilation']);\n if (fromMaskDilation != null) {\n common.setValueByPath(toObject, ['dilation'], fromMaskDilation);\n }\n\n return toObject;\n}\n\nexport function controlReferenceConfigToVertex(\n fromObject: types.ControlReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromControlType = common.getValueByPath(fromObject, ['controlType']);\n if (fromControlType != null) {\n common.setValueByPath(toObject, ['controlType'], fromControlType);\n }\n\n const fromEnableControlImageComputation = common.getValueByPath(fromObject, [\n 'enableControlImageComputation',\n ]);\n if (fromEnableControlImageComputation != null) {\n common.setValueByPath(\n toObject,\n ['computeControl'],\n fromEnableControlImageComputation,\n );\n }\n\n return toObject;\n}\n\nexport function styleReferenceConfigToVertex(\n fromObject: types.StyleReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromStyleDescription = common.getValueByPath(fromObject, [\n 'styleDescription',\n ]);\n if (fromStyleDescription != null) {\n common.setValueByPath(toObject, ['styleDescription'], fromStyleDescription);\n }\n\n return toObject;\n}\n\nexport function subjectReferenceConfigToVertex(\n fromObject: types.SubjectReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSubjectType = common.getValueByPath(fromObject, ['subjectType']);\n if (fromSubjectType != null) {\n common.setValueByPath(toObject, ['subjectType'], fromSubjectType);\n }\n\n const fromSubjectDescription = common.getValueByPath(fromObject, [\n 'subjectDescription',\n ]);\n if (fromSubjectDescription != null) {\n common.setValueByPath(\n toObject,\n ['subjectDescription'],\n fromSubjectDescription,\n );\n }\n\n return toObject;\n}\n\nexport function referenceImageAPIInternalToVertex(\n fromObject: _internal_types.ReferenceImageAPIInternal,\n): Record {\n const toObject: Record = {};\n\n const fromReferenceImage = common.getValueByPath(fromObject, [\n 'referenceImage',\n ]);\n if (fromReferenceImage != null) {\n common.setValueByPath(\n toObject,\n ['referenceImage'],\n imageToVertex(fromReferenceImage),\n );\n }\n\n const fromReferenceId = common.getValueByPath(fromObject, ['referenceId']);\n if (fromReferenceId != null) {\n common.setValueByPath(toObject, ['referenceId'], fromReferenceId);\n }\n\n const fromReferenceType = common.getValueByPath(fromObject, [\n 'referenceType',\n ]);\n if (fromReferenceType != null) {\n common.setValueByPath(toObject, ['referenceType'], fromReferenceType);\n }\n\n const fromMaskImageConfig = common.getValueByPath(fromObject, [\n 'maskImageConfig',\n ]);\n if (fromMaskImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['maskImageConfig'],\n maskReferenceConfigToVertex(fromMaskImageConfig),\n );\n }\n\n const fromControlImageConfig = common.getValueByPath(fromObject, [\n 'controlImageConfig',\n ]);\n if (fromControlImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['controlImageConfig'],\n controlReferenceConfigToVertex(fromControlImageConfig),\n );\n }\n\n const fromStyleImageConfig = common.getValueByPath(fromObject, [\n 'styleImageConfig',\n ]);\n if (fromStyleImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['styleImageConfig'],\n styleReferenceConfigToVertex(fromStyleImageConfig),\n );\n }\n\n const fromSubjectImageConfig = common.getValueByPath(fromObject, [\n 'subjectImageConfig',\n ]);\n if (fromSubjectImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['subjectImageConfig'],\n subjectReferenceConfigToVertex(fromSubjectImageConfig),\n );\n }\n\n return toObject;\n}\n\nexport function editImageConfigToVertex(\n fromObject: types.EditImageConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromEditMode = common.getValueByPath(fromObject, ['editMode']);\n if (parentObject !== undefined && fromEditMode != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editMode'],\n fromEditMode,\n );\n }\n\n const fromBaseSteps = common.getValueByPath(fromObject, ['baseSteps']);\n if (parentObject !== undefined && fromBaseSteps != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editConfig', 'baseSteps'],\n fromBaseSteps,\n );\n }\n\n return toObject;\n}\n\nexport function editImageParametersInternalToVertex(\n apiClient: ApiClient,\n fromObject: _internal_types.EditImageParametersInternal,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromReferenceImages = common.getValueByPath(fromObject, [\n 'referenceImages',\n ]);\n if (fromReferenceImages != null) {\n let transformedList = fromReferenceImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return referenceImageAPIInternalToVertex(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['instances[0]', 'referenceImages'],\n transformedList,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n editImageConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function upscaleImageAPIConfigInternalToVertex(\n fromObject: _internal_types.UpscaleImageAPIConfigInternal,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromEnhanceInputImage = common.getValueByPath(fromObject, [\n 'enhanceInputImage',\n ]);\n if (parentObject !== undefined && fromEnhanceInputImage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'upscaleConfig', 'enhanceInputImage'],\n fromEnhanceInputImage,\n );\n }\n\n const fromImagePreservationFactor = common.getValueByPath(fromObject, [\n 'imagePreservationFactor',\n ]);\n if (parentObject !== undefined && fromImagePreservationFactor != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'upscaleConfig', 'imagePreservationFactor'],\n fromImagePreservationFactor,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (parentObject !== undefined && fromMode != null) {\n common.setValueByPath(parentObject, ['parameters', 'mode'], fromMode);\n }\n\n return toObject;\n}\n\nexport function upscaleImageAPIParametersInternalToVertex(\n apiClient: ApiClient,\n fromObject: _internal_types.UpscaleImageAPIParametersInternal,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromUpscaleFactor = common.getValueByPath(fromObject, [\n 'upscaleFactor',\n ]);\n if (fromUpscaleFactor != null) {\n common.setValueByPath(\n toObject,\n ['parameters', 'upscaleConfig', 'upscaleFactor'],\n fromUpscaleFactor,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n upscaleImageAPIConfigInternalToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function productImageToVertex(\n fromObject: types.ProductImage,\n): Record {\n const toObject: Record = {};\n\n const fromProductImage = common.getValueByPath(fromObject, ['productImage']);\n if (fromProductImage != null) {\n common.setValueByPath(toObject, ['image'], imageToVertex(fromProductImage));\n }\n\n return toObject;\n}\n\nexport function recontextImageSourceToVertex(\n fromObject: types.RecontextImageSource,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (parentObject !== undefined && fromPrompt != null) {\n common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromPersonImage = common.getValueByPath(fromObject, ['personImage']);\n if (parentObject !== undefined && fromPersonImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'personImage', 'image'],\n imageToVertex(fromPersonImage),\n );\n }\n\n const fromProductImages = common.getValueByPath(fromObject, [\n 'productImages',\n ]);\n if (parentObject !== undefined && fromProductImages != null) {\n let transformedList = fromProductImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return productImageToVertex(item);\n });\n }\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'productImages'],\n transformedList,\n );\n }\n\n return toObject;\n}\n\nexport function recontextImageConfigToVertex(\n fromObject: types.RecontextImageConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromBaseSteps = common.getValueByPath(fromObject, ['baseSteps']);\n if (parentObject !== undefined && fromBaseSteps != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editConfig', 'baseSteps'],\n fromBaseSteps,\n );\n }\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function recontextImageParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.RecontextImageParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n recontextImageSourceToVertex(fromSource, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n recontextImageConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function scribbleImageToVertex(\n fromObject: types.ScribbleImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageToVertex(fromImage));\n }\n\n return toObject;\n}\n\nexport function segmentImageSourceToVertex(\n fromObject: types.SegmentImageSource,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (parentObject !== undefined && fromPrompt != null) {\n common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (parentObject !== undefined && fromImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromScribbleImage = common.getValueByPath(fromObject, [\n 'scribbleImage',\n ]);\n if (parentObject !== undefined && fromScribbleImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'scribble'],\n scribbleImageToVertex(fromScribbleImage),\n );\n }\n\n return toObject;\n}\n\nexport function segmentImageConfigToVertex(\n fromObject: types.SegmentImageConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (parentObject !== undefined && fromMode != null) {\n common.setValueByPath(parentObject, ['parameters', 'mode'], fromMode);\n }\n\n const fromMaxPredictions = common.getValueByPath(fromObject, [\n 'maxPredictions',\n ]);\n if (parentObject !== undefined && fromMaxPredictions != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'maxPredictions'],\n fromMaxPredictions,\n );\n }\n\n const fromConfidenceThreshold = common.getValueByPath(fromObject, [\n 'confidenceThreshold',\n ]);\n if (parentObject !== undefined && fromConfidenceThreshold != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'confidenceThreshold'],\n fromConfidenceThreshold,\n );\n }\n\n const fromMaskDilation = common.getValueByPath(fromObject, ['maskDilation']);\n if (parentObject !== undefined && fromMaskDilation != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'maskDilation'],\n fromMaskDilation,\n );\n }\n\n const fromBinaryColorThreshold = common.getValueByPath(fromObject, [\n 'binaryColorThreshold',\n ]);\n if (parentObject !== undefined && fromBinaryColorThreshold != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'binaryColorThreshold'],\n fromBinaryColorThreshold,\n );\n }\n\n return toObject;\n}\n\nexport function segmentImageParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.SegmentImageParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n segmentImageSourceToVertex(fromSource, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n segmentImageConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listModelsConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ListModelsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n const fromQueryBase = common.getValueByPath(fromObject, ['queryBase']);\n if (parentObject !== undefined && fromQueryBase != null) {\n common.setValueByPath(\n parentObject,\n ['_url', 'models_url'],\n t.tModelsUrl(apiClient, fromQueryBase),\n );\n }\n\n return toObject;\n}\n\nexport function listModelsParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ListModelsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listModelsConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function updateModelConfigToVertex(\n fromObject: types.UpdateModelConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (parentObject !== undefined && fromDefaultCheckpointId != null) {\n common.setValueByPath(\n parentObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n return toObject;\n}\n\nexport function updateModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateModelConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToVertex(\n fromObject: types.CountTokensConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['generationConfig'],\n fromGenerationConfig,\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function computeTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ComputeTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoToVertex(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, ['videoBytes']);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function videoGenerationReferenceImageToVertex(\n fromObject: types.VideoGenerationReferenceImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageToVertex(fromImage));\n }\n\n const fromReferenceType = common.getValueByPath(fromObject, [\n 'referenceType',\n ]);\n if (fromReferenceType != null) {\n common.setValueByPath(toObject, ['referenceType'], fromReferenceType);\n }\n\n return toObject;\n}\n\nexport function generateVideosConfigToVertex(\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (parentObject !== undefined && fromFps != null) {\n common.setValueByPath(parentObject, ['parameters', 'fps'], fromFps);\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromResolution = common.getValueByPath(fromObject, ['resolution']);\n if (parentObject !== undefined && fromResolution != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'resolution'],\n fromResolution,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromPubsubTopic = common.getValueByPath(fromObject, ['pubsubTopic']);\n if (parentObject !== undefined && fromPubsubTopic != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'pubsubTopic'],\n fromPubsubTopic,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n const fromGenerateAudio = common.getValueByPath(fromObject, [\n 'generateAudio',\n ]);\n if (parentObject !== undefined && fromGenerateAudio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'generateAudio'],\n fromGenerateAudio,\n );\n }\n\n const fromLastFrame = common.getValueByPath(fromObject, ['lastFrame']);\n if (parentObject !== undefined && fromLastFrame != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'lastFrame'],\n imageToVertex(fromLastFrame),\n );\n }\n\n const fromReferenceImages = common.getValueByPath(fromObject, [\n 'referenceImages',\n ]);\n if (parentObject !== undefined && fromReferenceImages != null) {\n let transformedList = fromReferenceImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return videoGenerationReferenceImageToVertex(item);\n });\n }\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'referenceImages'],\n transformedList,\n );\n }\n\n const fromCompressionQuality = common.getValueByPath(fromObject, [\n 'compressionQuality',\n ]);\n if (parentObject !== undefined && fromCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'compressionQuality'],\n fromCompressionQuality,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'video'],\n videoToVertex(fromVideo),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(toObject, ['content'], contentFromMldev(fromContent));\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromMldev(\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function embedContentResponseFromMldev(\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromEmbeddings = common.getValueByPath(fromObject, ['embeddings']);\n if (fromEmbeddings != null) {\n let transformedList = fromEmbeddings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentEmbeddingFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['embeddings'], transformedList);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromMldev(),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromMldev(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(toObject, ['imageBytes'], t.tBytes(fromImageBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromMldev(\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromMldev(\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageFromMldev(fromImage));\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromMldev(fromSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromMldev(\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromMldev(fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function tunedModelInfoFromMldev(\n fromObject: types.TunedModelInfo,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n return toObject;\n}\n\nexport function modelFromMldev(\n fromObject: types.Model,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromVersion = common.getValueByPath(fromObject, ['version']);\n if (fromVersion != null) {\n common.setValueByPath(toObject, ['version'], fromVersion);\n }\n\n const fromTunedModelInfo = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModelInfo != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelInfo'],\n tunedModelInfoFromMldev(fromTunedModelInfo),\n );\n }\n\n const fromInputTokenLimit = common.getValueByPath(fromObject, [\n 'inputTokenLimit',\n ]);\n if (fromInputTokenLimit != null) {\n common.setValueByPath(toObject, ['inputTokenLimit'], fromInputTokenLimit);\n }\n\n const fromOutputTokenLimit = common.getValueByPath(fromObject, [\n 'outputTokenLimit',\n ]);\n if (fromOutputTokenLimit != null) {\n common.setValueByPath(toObject, ['outputTokenLimit'], fromOutputTokenLimit);\n }\n\n const fromSupportedActions = common.getValueByPath(fromObject, [\n 'supportedGenerationMethods',\n ]);\n if (fromSupportedActions != null) {\n common.setValueByPath(toObject, ['supportedActions'], fromSupportedActions);\n }\n\n return toObject;\n}\n\nexport function listModelsResponseFromMldev(\n fromObject: types.ListModelsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromModels = common.getValueByPath(fromObject, ['_self']);\n if (fromModels != null) {\n let transformedList = t.tExtractModels(fromModels);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modelFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['models'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteModelResponseFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function countTokensResponseFromMldev(\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n return toObject;\n}\n\nexport function videoFromMldev(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['video', 'uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'video',\n 'encodedVideo',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromMldev(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromMldev(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, [\n 'generatedSamples',\n ]);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, [\n 'response',\n 'generateVideoResponse',\n ]);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromMldev(fromResponse),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromVertex(\n fromObject: types.Blob,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromVertex(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citations']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromVertex(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromVertex(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromVertex(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(\n toObject,\n ['content'],\n contentFromVertex(fromContent),\n );\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromVertex(fromCitationMetadata),\n );\n }\n\n const fromFinishMessage = common.getValueByPath(fromObject, [\n 'finishMessage',\n ]);\n if (fromFinishMessage != null) {\n common.setValueByPath(toObject, ['finishMessage'], fromFinishMessage);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromVertex(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromVertex(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingStatisticsFromVertex(\n fromObject: types.ContentEmbeddingStatistics,\n): Record {\n const toObject: Record = {};\n\n const fromTruncated = common.getValueByPath(fromObject, ['truncated']);\n if (fromTruncated != null) {\n common.setValueByPath(toObject, ['truncated'], fromTruncated);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['token_count']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromVertex(\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n const fromStatistics = common.getValueByPath(fromObject, ['statistics']);\n if (fromStatistics != null) {\n common.setValueByPath(\n toObject,\n ['statistics'],\n contentEmbeddingStatisticsFromVertex(fromStatistics),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromVertex(\n fromObject: types.EmbedContentMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromBillableCharacterCount = common.getValueByPath(fromObject, [\n 'billableCharacterCount',\n ]);\n if (fromBillableCharacterCount != null) {\n common.setValueByPath(\n toObject,\n ['billableCharacterCount'],\n fromBillableCharacterCount,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentResponseFromVertex(\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromEmbeddings = common.getValueByPath(fromObject, [\n 'predictions[]',\n 'embeddings',\n ]);\n if (fromEmbeddings != null) {\n let transformedList = fromEmbeddings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentEmbeddingFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['embeddings'], transformedList);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromVertex(fromMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromVertex(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(toObject, ['imageBytes'], t.tBytes(fromImageBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromVertex(\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromVertex(\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageFromVertex(fromImage));\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromVertex(fromSafetyAttributes),\n );\n }\n\n const fromEnhancedPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromEnhancedPrompt != null) {\n common.setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt);\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromVertex(\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromVertex(fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function editImageResponseFromVertex(\n fromObject: types.EditImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function upscaleImageResponseFromVertex(\n fromObject: types.UpscaleImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function recontextImageResponseFromVertex(\n fromObject: types.RecontextImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function entityLabelFromVertex(\n fromObject: types.EntityLabel,\n): Record {\n const toObject: Record = {};\n\n const fromLabel = common.getValueByPath(fromObject, ['label']);\n if (fromLabel != null) {\n common.setValueByPath(toObject, ['label'], fromLabel);\n }\n\n const fromScore = common.getValueByPath(fromObject, ['score']);\n if (fromScore != null) {\n common.setValueByPath(toObject, ['score'], fromScore);\n }\n\n return toObject;\n}\n\nexport function generatedImageMaskFromVertex(\n fromObject: types.GeneratedImageMask,\n): Record {\n const toObject: Record = {};\n\n const fromMask = common.getValueByPath(fromObject, ['_self']);\n if (fromMask != null) {\n common.setValueByPath(toObject, ['mask'], imageFromVertex(fromMask));\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n let transformedList = fromLabels;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return entityLabelFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['labels'], transformedList);\n }\n\n return toObject;\n}\n\nexport function segmentImageResponseFromVertex(\n fromObject: types.SegmentImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedMasks = common.getValueByPath(fromObject, ['predictions']);\n if (fromGeneratedMasks != null) {\n let transformedList = fromGeneratedMasks;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageMaskFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedMasks'], transformedList);\n }\n\n return toObject;\n}\n\nexport function endpointFromVertex(\n fromObject: types.Endpoint,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['endpoint']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDeployedModelId = common.getValueByPath(fromObject, [\n 'deployedModelId',\n ]);\n if (fromDeployedModelId != null) {\n common.setValueByPath(toObject, ['deployedModelId'], fromDeployedModelId);\n }\n\n return toObject;\n}\n\nexport function tunedModelInfoFromVertex(\n fromObject: types.TunedModelInfo,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, [\n 'labels',\n 'google-vertex-llm-tuning-base-model-id',\n ]);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n return toObject;\n}\n\nexport function checkpointFromVertex(\n fromObject: types.Checkpoint,\n): Record {\n const toObject: Record = {};\n\n const fromCheckpointId = common.getValueByPath(fromObject, ['checkpointId']);\n if (fromCheckpointId != null) {\n common.setValueByPath(toObject, ['checkpointId'], fromCheckpointId);\n }\n\n const fromEpoch = common.getValueByPath(fromObject, ['epoch']);\n if (fromEpoch != null) {\n common.setValueByPath(toObject, ['epoch'], fromEpoch);\n }\n\n const fromStep = common.getValueByPath(fromObject, ['step']);\n if (fromStep != null) {\n common.setValueByPath(toObject, ['step'], fromStep);\n }\n\n return toObject;\n}\n\nexport function modelFromVertex(\n fromObject: types.Model,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromVersion = common.getValueByPath(fromObject, ['versionId']);\n if (fromVersion != null) {\n common.setValueByPath(toObject, ['version'], fromVersion);\n }\n\n const fromEndpoints = common.getValueByPath(fromObject, ['deployedModels']);\n if (fromEndpoints != null) {\n let transformedList = fromEndpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return endpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['endpoints'], transformedList);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromTunedModelInfo = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModelInfo != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelInfo'],\n tunedModelInfoFromVertex(fromTunedModelInfo),\n );\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (fromDefaultCheckpointId != null) {\n common.setValueByPath(\n toObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n const fromCheckpoints = common.getValueByPath(fromObject, ['checkpoints']);\n if (fromCheckpoints != null) {\n let transformedList = fromCheckpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return checkpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['checkpoints'], transformedList);\n }\n\n return toObject;\n}\n\nexport function listModelsResponseFromVertex(\n fromObject: types.ListModelsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromModels = common.getValueByPath(fromObject, ['_self']);\n if (fromModels != null) {\n let transformedList = t.tExtractModels(fromModels);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modelFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['models'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteModelResponseFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function countTokensResponseFromVertex(\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n return toObject;\n}\n\nexport function computeTokensResponseFromVertex(\n fromObject: types.ComputeTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTokensInfo = common.getValueByPath(fromObject, ['tokensInfo']);\n if (fromTokensInfo != null) {\n common.setValueByPath(toObject, ['tokensInfo'], fromTokensInfo);\n }\n\n return toObject;\n}\n\nexport function videoFromVertex(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromVertex(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromVertex(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromVertex(fromResponse),\n );\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from './_auth.js';\nimport * as common from './_common.js';\nimport {Downloader} from './_downloader.js';\nimport {Uploader} from './_uploader.js';\nimport {ApiError} from './errors.js';\nimport {\n DownloadFileParameters,\n File,\n HttpOptions,\n HttpResponse,\n UploadFileConfig,\n} from './types.js';\n\nconst CONTENT_TYPE_HEADER = 'Content-Type';\nconst SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';\nconst USER_AGENT_HEADER = 'User-Agent';\nexport const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';\nexport const SDK_VERSION = '1.15.0'; // x-release-please-version\nconst LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;\nconst VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';\nconst GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';\nconst responseLineRE = /^data: (.*)(?:\\n\\n|\\r\\r|\\r\\n\\r\\n)/;\n\n/**\n * Options for initializing the ApiClient. The ApiClient uses the parameters\n * for authentication purposes as well as to infer if SDK should send the\n * request to Vertex AI or Gemini API.\n */\nexport interface ApiClientInitOptions {\n /**\n * The object used for adding authentication headers to API requests.\n */\n auth: Auth;\n /**\n * The uploader to use for uploading files. This field is required for\n * creating a client, will be set through the Node_client or Web_client.\n */\n uploader: Uploader;\n /**\n * Optional. The downloader to use for downloading files. This field is\n * required for creating a client, will be set through the Node_client or\n * Web_client.\n */\n downloader: Downloader;\n /**\n * Optional. The Google Cloud project ID for Vertex AI users.\n * It is not the numeric project name.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n project?: string;\n /**\n * Optional. The Google Cloud project location for Vertex AI users.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n location?: string;\n /**\n * The API Key. This is required for Gemini API users.\n */\n apiKey?: string;\n /**\n * Optional. Set to true if you intend to call Vertex AI endpoints.\n * If unset, default SDK behavior is to call Gemini API.\n */\n vertexai?: boolean;\n /**\n * Optional. The API version for the endpoint.\n * If unset, SDK will choose a default api version.\n */\n apiVersion?: string;\n /**\n * Optional. A set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional. An extra string to append at the end of the User-Agent header.\n *\n * This can be used to e.g specify the runtime and its version.\n */\n userAgentExtra?: string;\n}\n\n/**\n * Represents the necessary information to send a request to an API endpoint.\n * This interface defines the structure for constructing and executing HTTP\n * requests.\n */\nexport interface HttpRequest {\n /**\n * URL path from the modules, this path is appended to the base API URL to\n * form the complete request URL.\n *\n * If you wish to set full URL, use httpOptions.baseUrl instead. Example to\n * set full URL in the request:\n *\n * const request: HttpRequest = {\n * path: '',\n * httpOptions: {\n * baseUrl: 'https://',\n * apiVersion: '',\n * },\n * httpMethod: 'GET',\n * };\n *\n * The result URL will be: https://\n *\n */\n path: string;\n /**\n * Optional query parameters to be appended to the request URL.\n */\n queryParams?: Record;\n /**\n * Optional request body in json string or Blob format, GET request doesn't\n * need a request body.\n */\n body?: string | Blob;\n /**\n * The HTTP method to be used for the request.\n */\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE';\n /**\n * Optional set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional abort signal which can be used to cancel the request.\n */\n abortSignal?: AbortSignal;\n}\n\n/**\n * The ApiClient class is used to send requests to the Gemini API or Vertex AI\n * endpoints.\n */\nexport class ApiClient {\n readonly clientOptions: ApiClientInitOptions;\n\n constructor(opts: ApiClientInitOptions) {\n this.clientOptions = {\n ...opts,\n project: opts.project,\n location: opts.location,\n apiKey: opts.apiKey,\n vertexai: opts.vertexai,\n };\n\n const initHttpOptions: HttpOptions = {};\n\n if (this.clientOptions.vertexai) {\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? VERTEX_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = this.baseUrlFromProjectLocation();\n this.normalizeAuthParameters();\n } else {\n // Gemini API\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? GOOGLE_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`;\n }\n\n initHttpOptions.headers = this.getDefaultHeaders();\n\n this.clientOptions.httpOptions = initHttpOptions;\n\n if (opts.httpOptions) {\n this.clientOptions.httpOptions = this.patchHttpOptions(\n initHttpOptions,\n opts.httpOptions,\n );\n }\n }\n\n /**\n * Determines the base URL for Vertex AI based on project and location.\n * Uses the global endpoint if location is 'global' or if project/location\n * are not specified (implying API key usage).\n * @private\n */\n private baseUrlFromProjectLocation(): string {\n if (\n this.clientOptions.project &&\n this.clientOptions.location &&\n this.clientOptions.location !== 'global'\n ) {\n // Regional endpoint\n return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`;\n }\n // Global endpoint (covers 'global' location and API key usage)\n return `https://aiplatform.googleapis.com/`;\n }\n\n /**\n * Normalizes authentication parameters for Vertex AI.\n * If project and location are provided, API key is cleared.\n * If project and location are not provided (implying API key usage),\n * project and location are cleared.\n * @private\n */\n private normalizeAuthParameters(): void {\n if (this.clientOptions.project && this.clientOptions.location) {\n // Using project/location for auth, clear potential API key\n this.clientOptions.apiKey = undefined;\n return;\n }\n // Using API key for auth (or no auth provided yet), clear project/location\n this.clientOptions.project = undefined;\n this.clientOptions.location = undefined;\n }\n\n isVertexAI(): boolean {\n return this.clientOptions.vertexai ?? false;\n }\n\n getProject() {\n return this.clientOptions.project;\n }\n\n getLocation() {\n return this.clientOptions.location;\n }\n\n getApiVersion() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.apiVersion !== undefined\n ) {\n return this.clientOptions.httpOptions.apiVersion;\n }\n throw new Error('API version is not set.');\n }\n\n getBaseUrl() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.baseUrl !== undefined\n ) {\n return this.clientOptions.httpOptions.baseUrl;\n }\n throw new Error('Base URL is not set.');\n }\n\n getRequestUrl() {\n return this.getRequestUrlInternal(this.clientOptions.httpOptions);\n }\n\n getHeaders() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.headers !== undefined\n ) {\n return this.clientOptions.httpOptions.headers;\n } else {\n throw new Error('Headers are not set.');\n }\n }\n\n private getRequestUrlInternal(httpOptions?: HttpOptions) {\n if (\n !httpOptions ||\n httpOptions.baseUrl === undefined ||\n httpOptions.apiVersion === undefined\n ) {\n throw new Error('HTTP options are not correctly set.');\n }\n const baseUrl = httpOptions.baseUrl.endsWith('/')\n ? httpOptions.baseUrl.slice(0, -1)\n : httpOptions.baseUrl;\n const urlElement: Array = [baseUrl];\n if (httpOptions.apiVersion && httpOptions.apiVersion !== '') {\n urlElement.push(httpOptions.apiVersion);\n }\n return urlElement.join('/');\n }\n\n getBaseResourcePath() {\n return `projects/${this.clientOptions.project}/locations/${\n this.clientOptions.location\n }`;\n }\n\n getApiKey() {\n return this.clientOptions.apiKey;\n }\n\n getWebsocketBaseUrl() {\n const baseUrl = this.getBaseUrl();\n const urlParts = new URL(baseUrl);\n urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss';\n return urlParts.toString();\n }\n\n setBaseUrl(url: string) {\n if (this.clientOptions.httpOptions) {\n this.clientOptions.httpOptions.baseUrl = url;\n } else {\n throw new Error('HTTP options are not correctly set.');\n }\n }\n\n private constructUrl(\n path: string,\n httpOptions: HttpOptions,\n prependProjectLocation: boolean,\n ): URL {\n const urlElement: Array = [this.getRequestUrlInternal(httpOptions)];\n if (prependProjectLocation) {\n urlElement.push(this.getBaseResourcePath());\n }\n if (path !== '') {\n urlElement.push(path);\n }\n const url = new URL(`${urlElement.join('/')}`);\n\n return url;\n }\n\n private shouldPrependVertexProjectPath(request: HttpRequest): boolean {\n if (this.clientOptions.apiKey) {\n return false;\n }\n if (!this.clientOptions.vertexai) {\n return false;\n }\n if (request.path.startsWith('projects/')) {\n // Assume the path already starts with\n // `projects//location/`.\n return false;\n }\n if (\n request.httpMethod === 'GET' &&\n request.path.startsWith('publishers/google/models')\n ) {\n // These paths are used by Vertex's models.get and models.list\n // calls. For base models Vertex does not accept a project/location\n // prefix (for tuned model the prefix is required).\n return false;\n }\n return true;\n }\n\n async request(request: HttpRequest): Promise {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const prependProjectLocation = this.shouldPrependVertexProjectPath(request);\n const url = this.constructUrl(\n request.path,\n patchedHttpOptions,\n prependProjectLocation,\n );\n if (request.queryParams) {\n for (const [key, value] of Object.entries(request.queryParams)) {\n url.searchParams.append(key, String(value));\n }\n }\n let requestInit: RequestInit = {};\n if (request.httpMethod === 'GET') {\n if (request.body && request.body !== '{}') {\n throw new Error(\n 'Request body should be empty for GET request, but got non empty request body',\n );\n }\n } else {\n requestInit.body = request.body;\n }\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n request.abortSignal,\n );\n return this.unaryApiCall(url, requestInit, request.httpMethod);\n }\n\n private patchHttpOptions(\n baseHttpOptions: HttpOptions,\n requestHttpOptions: HttpOptions,\n ): HttpOptions {\n const patchedHttpOptions = JSON.parse(\n JSON.stringify(baseHttpOptions),\n ) as HttpOptions;\n\n for (const [key, value] of Object.entries(requestHttpOptions)) {\n // Records compile to objects.\n if (typeof value === 'object') {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = {...patchedHttpOptions[key], ...value};\n } else if (value !== undefined) {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = value;\n }\n }\n return patchedHttpOptions;\n }\n\n async requestStream(\n request: HttpRequest,\n ): Promise> {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const prependProjectLocation = this.shouldPrependVertexProjectPath(request);\n const url = this.constructUrl(\n request.path,\n patchedHttpOptions,\n prependProjectLocation,\n );\n if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') {\n url.searchParams.set('alt', 'sse');\n }\n let requestInit: RequestInit = {};\n requestInit.body = request.body;\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n request.abortSignal,\n );\n return this.streamApiCall(url, requestInit, request.httpMethod);\n }\n\n private async includeExtraHttpOptionsToRequestInit(\n requestInit: RequestInit,\n httpOptions: HttpOptions,\n abortSignal?: AbortSignal,\n ): Promise {\n if ((httpOptions && httpOptions.timeout) || abortSignal) {\n const abortController = new AbortController();\n const signal = abortController.signal;\n if (httpOptions.timeout && httpOptions?.timeout > 0) {\n const timeoutHandle = setTimeout(\n () => abortController.abort(),\n httpOptions.timeout,\n );\n if (\n timeoutHandle &&\n typeof (timeoutHandle as unknown as NodeJS.Timeout).unref ===\n 'function'\n ) {\n // call unref to prevent nodejs process from hanging, see\n // https://nodejs.org/api/timers.html#timeoutunref\n timeoutHandle.unref();\n }\n }\n if (abortSignal) {\n abortSignal.addEventListener('abort', () => {\n abortController.abort();\n });\n }\n requestInit.signal = signal;\n }\n if (httpOptions && httpOptions.extraBody !== null) {\n includeExtraBodyToRequestInit(\n requestInit,\n httpOptions.extraBody as Record,\n );\n }\n requestInit.headers = await this.getHeadersInternal(httpOptions);\n return requestInit;\n }\n\n private async unaryApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return new HttpResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n private async streamApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise> {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return this.processStreamResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n async *processStreamResponse(\n response: Response,\n ): AsyncGenerator {\n const reader = response?.body?.getReader();\n const decoder = new TextDecoder('utf-8');\n if (!reader) {\n throw new Error('Response body is empty');\n }\n\n try {\n let buffer = '';\n while (true) {\n const {done, value} = await reader.read();\n if (done) {\n if (buffer.trim().length > 0) {\n throw new Error('Incomplete JSON segment at the end');\n }\n break;\n }\n const chunkString = decoder.decode(value, {stream: true});\n\n // Parse and throw an error if the chunk contains an error.\n try {\n const chunkJson = JSON.parse(chunkString) as Record;\n if ('error' in chunkJson) {\n const errorJson = JSON.parse(\n JSON.stringify(chunkJson['error']),\n ) as Record;\n const status = errorJson['status'] as string;\n const code = errorJson['code'] as number;\n const errorMessage = `got status: ${status}. ${JSON.stringify(\n chunkJson,\n )}`;\n if (code >= 400 && code < 600) {\n const apiError = new ApiError({\n message: errorMessage,\n status: code,\n });\n throw apiError;\n }\n }\n } catch (e: unknown) {\n const error = e as Error;\n if (error.name === 'ApiError') {\n throw e;\n }\n }\n buffer += chunkString;\n let match = buffer.match(responseLineRE);\n while (match) {\n const processedChunkString = match[1];\n try {\n const partialResponse = new Response(processedChunkString, {\n headers: response?.headers,\n status: response?.status,\n statusText: response?.statusText,\n });\n yield new HttpResponse(partialResponse);\n buffer = buffer.slice(match[0].length);\n match = buffer.match(responseLineRE);\n } catch (e) {\n throw new Error(\n `exception parsing stream chunk ${processedChunkString}. ${e}`,\n );\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n private async apiCall(\n url: string,\n requestInit: RequestInit,\n ): Promise {\n return fetch(url, requestInit).catch((e) => {\n throw new Error(`exception ${e} sending request`);\n });\n }\n\n getDefaultHeaders(): Record {\n const headers: Record = {};\n\n const versionHeaderValue =\n LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra;\n\n headers[USER_AGENT_HEADER] = versionHeaderValue;\n headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue;\n headers[CONTENT_TYPE_HEADER] = 'application/json';\n\n return headers;\n }\n\n private async getHeadersInternal(\n httpOptions: HttpOptions | undefined,\n ): Promise {\n const headers = new Headers();\n if (httpOptions && httpOptions.headers) {\n for (const [key, value] of Object.entries(httpOptions.headers)) {\n headers.append(key, value);\n }\n // Append a timeout header if it is set, note that the timeout option is\n // in milliseconds but the header is in seconds.\n if (httpOptions.timeout && httpOptions.timeout > 0) {\n headers.append(\n SERVER_TIMEOUT_HEADER,\n String(Math.ceil(httpOptions.timeout / 1000)),\n );\n }\n }\n await this.clientOptions.auth.addAuthHeaders(headers);\n return headers;\n }\n\n /**\n * Uploads a file asynchronously using Gemini API only, this is not supported\n * in Vertex AI.\n *\n * @param file The string path to the file to be uploaded or a Blob object.\n * @param config Optional parameters specified in the `UploadFileConfig`\n * interface. @see {@link UploadFileConfig}\n * @return A promise that resolves to a `File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n */\n async uploadFile(\n file: string | Blob,\n config?: UploadFileConfig,\n ): Promise {\n const fileToUpload: File = {};\n if (config != null) {\n fileToUpload.mimeType = config.mimeType;\n fileToUpload.name = config.name;\n fileToUpload.displayName = config.displayName;\n }\n\n if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) {\n fileToUpload.name = `files/${fileToUpload.name}`;\n }\n\n const uploader = this.clientOptions.uploader;\n const fileStat = await uploader.stat(file);\n fileToUpload.sizeBytes = String(fileStat.size);\n const mimeType = config?.mimeType ?? fileStat.type;\n if (mimeType === undefined || mimeType === '') {\n throw new Error(\n 'Can not determine mimeType. Please provide mimeType in the config.',\n );\n }\n fileToUpload.mimeType = mimeType;\n\n const uploadUrl = await this.fetchUploadUrl(fileToUpload, config);\n return uploader.upload(file, uploadUrl, this);\n }\n\n /**\n * Downloads a file asynchronously to the specified path.\n *\n * @params params - The parameters for the download request, see {@link\n * DownloadFileParameters}\n */\n async downloadFile(params: DownloadFileParameters): Promise {\n const downloader = this.clientOptions.downloader;\n await downloader.download(params, this);\n }\n\n private async fetchUploadUrl(\n file: File,\n config?: UploadFileConfig,\n ): Promise {\n let httpOptions: HttpOptions = {};\n if (config?.httpOptions) {\n httpOptions = config.httpOptions;\n } else {\n httpOptions = {\n apiVersion: '', // api-version is set in the path.\n headers: {\n 'Content-Type': 'application/json',\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`,\n 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`,\n },\n };\n }\n\n const body: Record = {\n 'file': file,\n };\n const httpResponse = await this.request({\n path: common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n ),\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions,\n });\n\n if (!httpResponse || !httpResponse?.headers) {\n throw new Error(\n 'Server did not return an HttpResponse or the returned HttpResponse did not have headers.',\n );\n }\n\n const uploadUrl: string | undefined =\n httpResponse?.headers?.['x-goog-upload-url'];\n if (uploadUrl === undefined) {\n throw new Error(\n 'Failed to get upload url. Server did not return the x-google-upload-url in the headers',\n );\n }\n return uploadUrl;\n }\n}\n\nasync function throwErrorIfNotOK(response: Response | undefined) {\n if (response === undefined) {\n throw new Error('response is undefined');\n }\n if (!response.ok) {\n const status: number = response.status;\n let errorBody: Record;\n if (response.headers.get('content-type')?.includes('application/json')) {\n errorBody = await response.json();\n } else {\n errorBody = {\n error: {\n message: await response.text(),\n code: response.status,\n status: response.statusText,\n },\n };\n }\n const errorMessage = JSON.stringify(errorBody);\n if (status >= 400 && status < 600) {\n const apiError = new ApiError({\n message: errorMessage,\n status: status,\n });\n throw apiError;\n }\n throw new Error(errorMessage);\n }\n}\n\n/**\n * Recursively updates the `requestInit.body` with values from an `extraBody` object.\n *\n * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed.\n * The `extraBody` is then deeply merged into this parsed object.\n * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged,\n * as merging structured data into an opaque Blob is not supported.\n *\n * The function does not enforce that updated values from `extraBody` have the\n * same type as existing values in `requestInit.body`. Type mismatches during\n * the merge will result in a warning, but the value from `extraBody` will overwrite\n * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure.\n *\n * @param requestInit The RequestInit object whose body will be updated.\n * @param extraBody The object containing updates to be merged into `requestInit.body`.\n */\nexport function includeExtraBodyToRequestInit(\n requestInit: RequestInit,\n extraBody: Record,\n) {\n if (!extraBody || Object.keys(extraBody).length === 0) {\n return;\n }\n\n if (requestInit.body instanceof Blob) {\n console.warn(\n 'includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.',\n );\n return;\n }\n\n let currentBodyObject: Record = {};\n\n // If adding new type to HttpRequest.body, please check the code below to\n // see if we need to update the logic.\n if (typeof requestInit.body === 'string' && requestInit.body.length > 0) {\n try {\n const parsedBody = JSON.parse(requestInit.body);\n if (\n typeof parsedBody === 'object' &&\n parsedBody !== null &&\n !Array.isArray(parsedBody)\n ) {\n currentBodyObject = parsedBody as Record;\n } else {\n console.warn(\n 'includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.',\n );\n return;\n }\n /* eslint-disable-next-line @typescript-eslint/no-unused-vars */\n } catch (e) {\n console.warn(\n 'includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.',\n );\n return;\n }\n }\n\n function deepMerge(\n target: Record,\n source: Record,\n ): Record {\n const output = {...target};\n for (const key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n const sourceValue = source[key];\n const targetValue = output[key];\n if (\n sourceValue &&\n typeof sourceValue === 'object' &&\n !Array.isArray(sourceValue) &&\n targetValue &&\n typeof targetValue === 'object' &&\n !Array.isArray(targetValue)\n ) {\n output[key] = deepMerge(\n targetValue as Record,\n sourceValue as Record,\n );\n } else {\n if (\n targetValue &&\n sourceValue &&\n typeof targetValue !== typeof sourceValue\n ) {\n console.warn(\n `includeExtraBodyToRequestInit:deepMerge: Type mismatch for key \"${key}\". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`,\n );\n }\n output[key] = sourceValue;\n }\n }\n }\n return output;\n }\n\n const mergedBody = deepMerge(currentBodyObject, extraBody);\n requestInit.body = JSON.stringify(mergedBody);\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {Client as McpClient} from '@modelcontextprotocol/sdk/client/index.js';\nimport type {Tool as McpTool} from '@modelcontextprotocol/sdk/types.js';\n\nimport {GOOGLE_API_CLIENT_HEADER} from '../_api_client.js';\nimport {mcpToolsToGeminiTool} from '../_transformers.js';\nimport {\n CallableTool,\n CallableToolConfig,\n FunctionCall,\n Part,\n Tool,\n ToolListUnion,\n} from '../types.js';\n\n// TODO: b/416041229 - Determine how to retrieve the MCP package version.\nexport const MCP_LABEL = 'mcp_used/unknown';\n\n// Whether MCP tool usage is detected from mcpToTool. This is used for\n// telemetry.\nlet hasMcpToolUsageFromMcpToTool = false;\n\n// Checks whether the list of tools contains any MCP tools.\nexport function hasMcpToolUsage(tools: ToolListUnion): boolean {\n for (const tool of tools) {\n if (isMcpCallableTool(tool)) {\n return true;\n }\n if (typeof tool === 'object' && 'inputSchema' in tool) {\n return true;\n }\n }\n\n return hasMcpToolUsageFromMcpToTool;\n}\n\n// Sets the MCP version label in the Google API client header.\nexport function setMcpUsageHeader(headers: Record) {\n const existingHeader = headers[GOOGLE_API_CLIENT_HEADER] ?? '';\n headers[GOOGLE_API_CLIENT_HEADER] = (\n existingHeader + ` ${MCP_LABEL}`\n ).trimStart();\n}\n\n// Returns true if the object is a MCP CallableTool, otherwise false.\nfunction isMcpCallableTool(object: unknown): boolean {\n return (\n object !== null &&\n typeof object === 'object' &&\n object instanceof McpCallableTool\n );\n}\n\n// List all tools from the MCP client.\nasync function* listAllTools(\n mcpClient: McpClient,\n maxTools: number = 100,\n): AsyncGenerator {\n let cursor: string | undefined = undefined;\n let numTools = 0;\n while (numTools < maxTools) {\n const t = await mcpClient.listTools({cursor});\n for (const tool of t.tools) {\n yield tool;\n numTools++;\n }\n if (!t.nextCursor) {\n break;\n }\n cursor = t.nextCursor;\n }\n}\n\n/**\n * McpCallableTool can be used for model inference and invoking MCP clients with\n * given function call arguments.\n *\n * @experimental Built-in MCP support is an experimental feature, may change in future\n * versions.\n */\nexport class McpCallableTool implements CallableTool {\n private readonly mcpClients;\n private mcpTools: McpTool[] = [];\n private functionNameToMcpClient: Record = {};\n private readonly config: CallableToolConfig;\n\n private constructor(\n mcpClients: McpClient[] = [],\n config: CallableToolConfig,\n ) {\n this.mcpClients = mcpClients;\n this.config = config;\n }\n\n /**\n * Creates a McpCallableTool.\n */\n public static create(\n mcpClients: McpClient[],\n config: CallableToolConfig,\n ): McpCallableTool {\n return new McpCallableTool(mcpClients, config);\n }\n\n /**\n * Validates the function names are not duplicate and initialize the function\n * name to MCP client mapping.\n *\n * @throws {Error} if the MCP tools from the MCP clients have duplicate tool\n * names.\n */\n async initialize() {\n if (this.mcpTools.length > 0) {\n return;\n }\n\n const functionMap: Record = {};\n const mcpTools: McpTool[] = [];\n for (const mcpClient of this.mcpClients) {\n for await (const mcpTool of listAllTools(mcpClient)) {\n mcpTools.push(mcpTool);\n const mcpToolName = mcpTool.name as string;\n if (functionMap[mcpToolName]) {\n throw new Error(\n `Duplicate function name ${\n mcpToolName\n } found in MCP tools. Please ensure function names are unique.`,\n );\n }\n functionMap[mcpToolName] = mcpClient;\n }\n }\n this.mcpTools = mcpTools;\n this.functionNameToMcpClient = functionMap;\n }\n\n public async tool(): Promise {\n await this.initialize();\n return mcpToolsToGeminiTool(this.mcpTools, this.config);\n }\n\n public async callTool(functionCalls: FunctionCall[]): Promise {\n await this.initialize();\n const functionCallResponseParts: Part[] = [];\n for (const functionCall of functionCalls) {\n if (functionCall.name! in this.functionNameToMcpClient) {\n const mcpClient = this.functionNameToMcpClient[functionCall.name!];\n let requestOptions = undefined;\n // TODO: b/424238654 - Add support for finer grained timeout control.\n if (this.config.timeout) {\n requestOptions = {\n timeout: this.config.timeout,\n };\n }\n const callToolResponse = await mcpClient.callTool(\n {\n name: functionCall.name!,\n arguments: functionCall.args,\n },\n // Set the result schema to undefined to allow MCP to rely on the\n // default schema.\n undefined,\n requestOptions,\n );\n functionCallResponseParts.push({\n functionResponse: {\n name: functionCall.name,\n response: callToolResponse.isError\n ? {error: callToolResponse}\n : (callToolResponse as Record),\n },\n });\n }\n }\n return functionCallResponseParts;\n }\n}\n\nfunction isMcpClient(client: unknown): client is McpClient {\n return (\n client !== null &&\n typeof client === 'object' &&\n 'listTools' in client &&\n typeof client.listTools === 'function'\n );\n}\n\n/**\n * Creates a McpCallableTool from MCP clients and an optional config.\n *\n * The callable tool can invoke the MCP clients with given function call\n * arguments. (often for automatic function calling).\n * Use the config to modify tool parameters such as behavior.\n *\n * @experimental Built-in MCP support is an experimental feature, may change in future\n * versions.\n */\nexport function mcpToTool(\n ...args: [...McpClient[], CallableToolConfig | McpClient]\n): CallableTool {\n // Set MCP usage for telemetry.\n hasMcpToolUsageFromMcpToTool = true;\n if (args.length === 0) {\n throw new Error('No MCP clients provided');\n }\n const maybeConfig = args[args.length - 1];\n if (isMcpClient(maybeConfig)) {\n return McpCallableTool.create(args as McpClient[], {});\n }\n return McpCallableTool.create(\n args.slice(0, args.length - 1) as McpClient[],\n maybeConfig,\n );\n}\n\n/**\n * Sets the MCP tool usage flag from calling mcpToTool. This is used for\n * telemetry.\n */\nexport function setMcpToolUsageFromMcpToTool(mcpToolUsage: boolean) {\n hasMcpToolUsageFromMcpToTool = mcpToolUsage;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live music client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client.js';\nimport {Auth} from './_auth.js';\nimport * as t from './_transformers.js';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket.js';\nimport * as converters from './converters/_live_converters.js';\nimport * as types from './types.js';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveMusicServerMessage, and then calling the onmessage callback.\n * Note that the first message which is received from the server is a\n * setupComplete message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveMusicServerMessage) => void,\n event: MessageEvent,\n): Promise {\n const serverMessage: types.LiveMusicServerMessage =\n new types.LiveMusicServerMessage();\n let data: types.LiveMusicServerMessage;\n if (event.data instanceof Blob) {\n data = JSON.parse(await event.data.text()) as types.LiveMusicServerMessage;\n } else {\n data = JSON.parse(event.data) as types.LiveMusicServerMessage;\n }\n const response = converters.liveMusicServerMessageFromMldev(data);\n Object.assign(serverMessage, response);\n onmessage(serverMessage);\n}\n\n/**\n LiveMusic class encapsulates the configuration for live music\n generation via Lyria Live models.\n\n @experimental\n */\nexport class LiveMusic {\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {}\n\n /**\n Establishes a connection to the specified model and returns a\n LiveMusicSession object representing that connection.\n\n @experimental\n\n @remarks\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n let model = 'models/lyria-realtime-exp';\n const session = await ai.live.music.connect({\n model: model,\n callbacks: {\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(\n params: types.LiveMusicConnectParameters,\n ): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error('Live music is not supported for Vertex AI.');\n }\n console.warn(\n 'Live music generation is experimental and may change in future versions.',\n );\n\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n const headers = mapToHeaders(this.apiClient.getDefaultHeaders());\n const apiKey = this.apiClient.getApiKey();\n const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.BidiGenerateMusic?key=${apiKey}`;\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveMusicCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n const model = t.tModel(this.apiClient, params.model);\n const setup = converters.liveMusicClientSetupToMldev({\n model,\n });\n const clientMessage = converters.liveMusicClientMessageToMldev({setup});\n conn.send(JSON.stringify(clientMessage));\n\n return new LiveMusicSession(conn, this.apiClient);\n }\n}\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class LiveMusicSession {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n /**\n Sets inputs to steer music generation. Updates the session's current\n weighted prompts.\n\n @param params - Contains one property, `weightedPrompts`.\n\n - `weightedPrompts` to send to the model; weights are normalized to\n sum to 1.0.\n\n @experimental\n */\n async setWeightedPrompts(\n params: types.LiveMusicSetWeightedPromptsParameters,\n ) {\n if (\n !params.weightedPrompts ||\n Object.keys(params.weightedPrompts).length === 0\n ) {\n throw new Error(\n 'Weighted prompts must be set and contain at least one entry.',\n );\n }\n const setWeightedPromptsParameters =\n converters.liveMusicSetWeightedPromptsParametersToMldev(params);\n const clientContent = converters.liveMusicClientContentToMldev(\n setWeightedPromptsParameters,\n );\n this.conn.send(JSON.stringify({clientContent}));\n }\n\n /**\n Sets a configuration to the model. Updates the session's current\n music generation config.\n\n @param params - Contains one property, `musicGenerationConfig`.\n\n - `musicGenerationConfig` to set in the model. Passing an empty or\n undefined config to the model will reset the config to defaults.\n\n @experimental\n */\n async setMusicGenerationConfig(params: types.LiveMusicSetConfigParameters) {\n if (!params.musicGenerationConfig) {\n params.musicGenerationConfig = {};\n }\n const setConfigParameters =\n converters.liveMusicSetConfigParametersToMldev(params);\n const clientMessage =\n converters.liveMusicClientMessageToMldev(setConfigParameters);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n private sendPlaybackControl(playbackControl: types.LiveMusicPlaybackControl) {\n const clientMessage = converters.liveMusicClientMessageToMldev({\n playbackControl,\n });\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n * Start the music stream.\n *\n * @experimental\n */\n play() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.PLAY);\n }\n\n /**\n * Temporarily halt the music stream. Use `play` to resume from the current\n * position.\n *\n * @experimental\n */\n pause() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.PAUSE);\n }\n\n /**\n * Stop the music stream and reset the state. Retains the current prompts\n * and config.\n *\n * @experimental\n */\n stop() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.STOP);\n }\n\n /**\n * Resets the context of the music generation without stopping it.\n * Retains the current prompts and config.\n *\n * @experimental\n */\n resetContext() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.RESET_CONTEXT);\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client.js';\nimport {Auth} from './_auth.js';\nimport * as t from './_transformers.js';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket.js';\nimport * as converters from './converters/_live_converters.js';\nimport {\n contentToMldev,\n contentToVertex,\n} from './converters/_models_converters.js';\nimport {hasMcpToolUsage, setMcpUsageHeader} from './mcp/_mcp.js';\nimport {LiveMusic} from './music.js';\nimport * as types from './types.js';\n\nconst FUNCTION_RESPONSE_REQUIRES_ID =\n 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveServerMessages, and then calling the onmessage callback. Note that\n * the first message which is received from the server is a setupComplete\n * message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveServerMessage) => void,\n event: MessageEvent,\n): Promise {\n const serverMessage: types.LiveServerMessage = new types.LiveServerMessage();\n let jsonData: string;\n if (event.data instanceof Blob) {\n jsonData = await event.data.text();\n } else if (event.data instanceof ArrayBuffer) {\n jsonData = new TextDecoder().decode(event.data);\n } else {\n jsonData = event.data;\n }\n\n const data = JSON.parse(jsonData) as types.LiveServerMessage;\n\n if (apiClient.isVertexAI()) {\n const resp = converters.liveServerMessageFromVertex(data);\n Object.assign(serverMessage, resp);\n } else {\n const resp = converters.liveServerMessageFromMldev(data);\n Object.assign(serverMessage, resp);\n }\n\n onmessage(serverMessage);\n}\n\n/**\n Live class encapsulates the configuration for live interaction with the\n Generative Language API. It embeds ApiClient for general API settings.\n\n @experimental\n */\nexport class Live {\n public readonly music: LiveMusic;\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {\n this.music = new LiveMusic(\n this.apiClient,\n this.auth,\n this.webSocketFactory,\n );\n }\n\n /**\n Establishes a connection to the specified model with the given\n configuration and returns a Session object representing that connection.\n\n @experimental Built-in MCP support is an experimental feature, may change in\n future versions.\n\n @remarks\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n let model: string;\n if (GOOGLE_GENAI_USE_VERTEXAI) {\n model = 'gemini-2.0-flash-live-preview-04-09';\n } else {\n model = 'gemini-live-2.5-flash-preview';\n }\n const session = await ai.live.connect({\n model: model,\n config: {\n responseModalities: [Modality.AUDIO],\n },\n callbacks: {\n onopen: () => {\n console.log('Connected to the socket.');\n },\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(params: types.LiveConnectParameters): Promise {\n // TODO: b/404946746 - Support per request HTTP options.\n if (params.config && params.config.httpOptions) {\n throw new Error(\n 'The Live module does not support httpOptions at request-level in' +\n ' LiveConnectConfig yet. Please use the client-level httpOptions' +\n ' configuration instead.',\n );\n }\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n let url: string;\n const clientHeaders = this.apiClient.getHeaders();\n if (\n params.config &&\n params.config.tools &&\n hasMcpToolUsage(params.config.tools)\n ) {\n setMcpUsageHeader(clientHeaders);\n }\n const headers = mapToHeaders(clientHeaders);\n if (this.apiClient.isVertexAI()) {\n url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${\n apiVersion\n }.LlmBidiService/BidiGenerateContent`;\n await this.auth.addAuthHeaders(headers);\n } else {\n const apiKey = this.apiClient.getApiKey();\n\n let method = 'BidiGenerateContent';\n let keyName = 'key';\n if (apiKey?.startsWith('auth_tokens/')) {\n console.warn(\n 'Warning: Ephemeral token support is experimental and may change in future versions.',\n );\n if (apiVersion !== 'v1alpha') {\n console.warn(\n \"Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection.\",\n );\n }\n method = 'BidiGenerateContentConstrained';\n keyName = 'access_token';\n }\n\n url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.${method}?${keyName}=${apiKey}`;\n }\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n callbacks?.onopen?.();\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n let transformedModel = t.tModel(this.apiClient, params.model);\n if (\n this.apiClient.isVertexAI() &&\n transformedModel.startsWith('publishers/')\n ) {\n const project = this.apiClient.getProject();\n const location = this.apiClient.getLocation();\n transformedModel =\n `projects/${project}/locations/${location}/` + transformedModel;\n }\n\n let clientMessage: Record = {};\n\n if (\n this.apiClient.isVertexAI() &&\n params.config?.responseModalities === undefined\n ) {\n // Set default to AUDIO to align with MLDev API.\n if (params.config === undefined) {\n params.config = {responseModalities: [types.Modality.AUDIO]};\n } else {\n params.config.responseModalities = [types.Modality.AUDIO];\n }\n }\n if (params.config?.generationConfig) {\n // Raise deprecation warning for generationConfig.\n console.warn(\n 'Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).',\n );\n }\n const inputTools = params.config?.tools ?? [];\n const convertedTools: types.Tool[] = [];\n for (const tool of inputTools) {\n if (this.isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n convertedTools.push(await callableTool.tool());\n } else {\n convertedTools.push(tool as types.Tool);\n }\n }\n if (convertedTools.length > 0) {\n params.config!.tools = convertedTools;\n }\n const liveConnectParameters: types.LiveConnectParameters = {\n model: transformedModel,\n config: params.config,\n callbacks: params.callbacks,\n };\n if (this.apiClient.isVertexAI()) {\n clientMessage = converters.liveConnectParametersToVertex(\n this.apiClient,\n liveConnectParameters,\n );\n } else {\n clientMessage = converters.liveConnectParametersToMldev(\n this.apiClient,\n liveConnectParameters,\n );\n }\n delete clientMessage['config'];\n conn.send(JSON.stringify(clientMessage));\n return new Session(conn, this.apiClient);\n }\n\n // TODO: b/416041229 - Abstract this method to a common place.\n private isCallableTool(tool: types.ToolUnion): boolean {\n return 'callTool' in tool && typeof tool.callTool === 'function';\n }\n}\n\nconst defaultLiveSendClientContentParamerters: types.LiveSendClientContentParameters =\n {\n turnComplete: true,\n };\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class Session {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n private tLiveClientContent(\n apiClient: ApiClient,\n params: types.LiveSendClientContentParameters,\n ): types.LiveClientMessage {\n if (params.turns !== null && params.turns !== undefined) {\n let contents: types.Content[] = [];\n try {\n contents = t.tContents(params.turns as types.ContentListUnion);\n if (apiClient.isVertexAI()) {\n contents = contents.map((item) => contentToVertex(item));\n } else {\n contents = contents.map((item) => contentToMldev(item));\n }\n } catch {\n throw new Error(\n `Failed to parse client content \"turns\", type: '${typeof params.turns}'`,\n );\n }\n return {\n clientContent: {turns: contents, turnComplete: params.turnComplete},\n };\n }\n\n return {\n clientContent: {turnComplete: params.turnComplete},\n };\n }\n\n private tLiveClienttToolResponse(\n apiClient: ApiClient,\n params: types.LiveSendToolResponseParameters,\n ): types.LiveClientMessage {\n let functionResponses: types.FunctionResponse[] = [];\n\n if (params.functionResponses == null) {\n throw new Error('functionResponses is required.');\n }\n\n if (!Array.isArray(params.functionResponses)) {\n functionResponses = [params.functionResponses];\n } else {\n functionResponses = params.functionResponses;\n }\n\n if (functionResponses.length === 0) {\n throw new Error('functionResponses is required.');\n }\n\n for (const functionResponse of functionResponses) {\n if (\n typeof functionResponse !== 'object' ||\n functionResponse === null ||\n !('name' in functionResponse) ||\n !('response' in functionResponse)\n ) {\n throw new Error(\n `Could not parse function response, type '${typeof functionResponse}'.`,\n );\n }\n if (!apiClient.isVertexAI() && !('id' in functionResponse)) {\n throw new Error(FUNCTION_RESPONSE_REQUIRES_ID);\n }\n }\n\n const clientMessage: types.LiveClientMessage = {\n toolResponse: {functionResponses: functionResponses},\n };\n return clientMessage;\n }\n\n /**\n Send a message over the established connection.\n\n @param params - Contains two **optional** properties, `turns` and\n `turnComplete`.\n\n - `turns` will be converted to a `Content[]`\n - `turnComplete: true` [default] indicates that you are done sending\n content and expect a response. If `turnComplete: false`, the server\n will wait for additional messages before starting generation.\n\n @experimental\n\n @remarks\n There are two ways to send messages to the live API:\n `sendClientContent` and `sendRealtimeInput`.\n\n `sendClientContent` messages are added to the model context **in order**.\n Having a conversation using `sendClientContent` messages is roughly\n equivalent to using the `Chat.sendMessageStream`, except that the state of\n the `chat` history is stored on the API server instead of locally.\n\n Because of `sendClientContent`'s order guarantee, the model cannot respons\n as quickly to `sendClientContent` messages as to `sendRealtimeInput`\n messages. This makes the biggest difference when sending objects that have\n significant preprocessing time (typically images).\n\n The `sendClientContent` message sends a `Content[]`\n which has more options than the `Blob` sent by `sendRealtimeInput`.\n\n So the main use-cases for `sendClientContent` over `sendRealtimeInput` are:\n\n - Sending anything that can't be represented as a `Blob` (text,\n `sendClientContent({turns=\"Hello?\"}`)).\n - Managing turns when not using audio input and voice activity detection.\n (`sendClientContent({turnComplete:true})` or the short form\n `sendClientContent()`)\n - Prefilling a conversation context\n ```\n sendClientContent({\n turns: [\n Content({role:user, parts:...}),\n Content({role:user, parts:...}),\n ...\n ]\n })\n ```\n @experimental\n */\n sendClientContent(params: types.LiveSendClientContentParameters) {\n params = {\n ...defaultLiveSendClientContentParamerters,\n ...params,\n };\n\n const clientMessage: types.LiveClientMessage = this.tLiveClientContent(\n this.apiClient,\n params,\n );\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a realtime message over the established connection.\n\n @param params - Contains one property, `media`.\n\n - `media` will be converted to a `Blob`\n\n @experimental\n\n @remarks\n Use `sendRealtimeInput` for realtime audio chunks and video frames (images).\n\n With `sendRealtimeInput` the api will respond to audio automatically\n based on voice activity detection (VAD).\n\n `sendRealtimeInput` is optimized for responsivness at the expense of\n deterministic ordering guarantees. Audio and video tokens are to the\n context when they become available.\n\n Note: The Call signature expects a `Blob` object, but only a subset\n of audio and image mimetypes are allowed.\n */\n sendRealtimeInput(params: types.LiveSendRealtimeInputParameters) {\n let clientMessage: types.LiveClientMessage = {};\n\n if (this.apiClient.isVertexAI()) {\n clientMessage = {\n 'realtimeInput':\n converters.liveSendRealtimeInputParametersToVertex(params),\n };\n } else {\n clientMessage = {\n 'realtimeInput':\n converters.liveSendRealtimeInputParametersToMldev(params),\n };\n }\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a function response message over the established connection.\n\n @param params - Contains property `functionResponses`.\n\n - `functionResponses` will be converted to a `functionResponses[]`\n\n @remarks\n Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server.\n\n Use {@link types.LiveConnectConfig#tools} to configure the callable functions.\n\n @experimental\n */\n sendToolResponse(params: types.LiveSendToolResponseParameters) {\n if (params.functionResponses == null) {\n throw new Error('Tool response parameters are required.');\n }\n\n const clientMessage: types.LiveClientMessage =\n this.tLiveClienttToolResponse(this.apiClient, params);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n\n @example\n ```ts\n let model: string;\n if (GOOGLE_GENAI_USE_VERTEXAI) {\n model = 'gemini-2.0-flash-live-preview-04-09';\n } else {\n model = 'gemini-live-2.5-flash-preview';\n }\n const session = await ai.live.connect({\n model: model,\n config: {\n responseModalities: [Modality.AUDIO],\n }\n });\n\n session.close();\n ```\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as types from './types.js';\n\nexport const DEFAULT_MAX_REMOTE_CALLS = 10;\n\n/** Returns whether automatic function calling is disabled. */\nexport function shouldDisableAfc(\n config: types.GenerateContentConfig | undefined,\n): boolean {\n if (config?.automaticFunctionCalling?.disable) {\n return true;\n }\n\n let callableToolsPresent = false;\n for (const tool of config?.tools ?? []) {\n if (isCallableTool(tool)) {\n callableToolsPresent = true;\n break;\n }\n }\n if (!callableToolsPresent) {\n return true;\n }\n\n const maxCalls = config?.automaticFunctionCalling?.maximumRemoteCalls;\n if (\n (maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) ||\n maxCalls == 0\n ) {\n console.warn(\n 'Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:',\n maxCalls,\n );\n return true;\n }\n return false;\n}\n\nexport function isCallableTool(tool: types.ToolUnion): boolean {\n return 'callTool' in tool && typeof tool.callTool === 'function';\n}\n\n// Checks whether the list of tools contains any CallableTools. Will return true\n// if there is at least one CallableTool.\nexport function hasCallableTools(\n params: types.GenerateContentParameters,\n): boolean {\n return params.config?.tools?.some((tool) => isCallableTool(tool)) ?? false;\n}\n\n// Checks whether the list of tools contains any non-callable tools. Will return\n// true if there is at least one non-Callable tool.\nexport function hasNonCallableTools(\n params: types.GenerateContentParameters,\n): boolean {\n return params.config?.tools?.some((tool) => !isCallableTool(tool)) ?? false;\n}\n\n/**\n * Returns whether to append automatic function calling history to the\n * response.\n */\nexport function shouldAppendAfcHistory(\n config: types.GenerateContentConfig | undefined,\n): boolean {\n return !config?.automaticFunctionCalling?.ignoreCallHistory;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {\n DEFAULT_MAX_REMOTE_CALLS,\n hasCallableTools,\n hasNonCallableTools,\n isCallableTool,\n shouldAppendAfcHistory,\n shouldDisableAfc,\n} from './_afc.js';\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as _internal_types from './_internal_types.js';\nimport {tContents} from './_transformers.js';\nimport * as converters from './converters/_models_converters.js';\nimport {hasMcpToolUsage, setMcpUsageHeader} from './mcp/_mcp.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Models extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Makes an API request to generate content with a given model.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * candidateCount: 2,\n * }\n * });\n * console.log(response);\n * ```\n */\n generateContent = async (\n params: types.GenerateContentParameters,\n ): Promise => {\n const transformedParams = await this.processParamsMaybeAddMcpUsage(params);\n this.maybeMoveToResponseJsonSchem(params);\n if (!hasCallableTools(params) || shouldDisableAfc(params.config)) {\n return await this.generateContentInternal(transformedParams);\n }\n\n if (hasNonCallableTools(params)) {\n throw new Error(\n 'Automatic function calling with CallableTools and Tools is not yet supported.',\n );\n }\n\n let response: types.GenerateContentResponse;\n let functionResponseContent: types.Content;\n const automaticFunctionCallingHistory: types.Content[] = tContents(\n transformedParams.contents,\n );\n const maxRemoteCalls =\n transformedParams.config?.automaticFunctionCalling?.maximumRemoteCalls ??\n DEFAULT_MAX_REMOTE_CALLS;\n let remoteCalls = 0;\n while (remoteCalls < maxRemoteCalls) {\n response = await this.generateContentInternal(transformedParams);\n if (!response.functionCalls || response.functionCalls!.length === 0) {\n break;\n }\n\n const responseContent: types.Content = response.candidates![0].content!;\n const functionResponseParts: types.Part[] = [];\n for (const tool of params.config?.tools ?? []) {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n const parts = await callableTool.callTool(response.functionCalls!);\n functionResponseParts.push(...parts);\n }\n }\n\n remoteCalls++;\n\n functionResponseContent = {\n role: 'user',\n parts: functionResponseParts,\n };\n\n transformedParams.contents = tContents(transformedParams.contents);\n (transformedParams.contents as types.Content[]).push(responseContent);\n (transformedParams.contents as types.Content[]).push(\n functionResponseContent,\n );\n\n if (shouldAppendAfcHistory(transformedParams.config)) {\n automaticFunctionCallingHistory.push(responseContent);\n automaticFunctionCallingHistory.push(functionResponseContent);\n }\n }\n if (shouldAppendAfcHistory(transformedParams.config)) {\n response!.automaticFunctionCallingHistory =\n automaticFunctionCallingHistory;\n }\n return response!;\n };\n\n /**\n * This logic is needed for GenerateContentConfig only.\n * Previously we made GenerateContentConfig.responseSchema field to accept\n * unknown. Since v1.9.0, we switch to use backend JSON schema support.\n * To maintain backward compatibility, we move the data that was treated as\n * JSON schema from the responseSchema field to the responseJsonSchema field.\n */\n private maybeMoveToResponseJsonSchem(\n params: types.GenerateContentParameters,\n ): void {\n if (params.config && params.config.responseSchema) {\n if (!params.config.responseJsonSchema) {\n if (Object.keys(params.config.responseSchema).includes('$schema')) {\n params.config.responseJsonSchema = params.config.responseSchema;\n delete params.config.responseSchema;\n }\n }\n }\n return;\n }\n\n /**\n * Makes an API request to generate content with a given model and yields the\n * response in chunks.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content with streaming response.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContentStream({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * maxOutputTokens: 200,\n * }\n * });\n * for await (const chunk of response) {\n * console.log(chunk);\n * }\n * ```\n */\n generateContentStream = async (\n params: types.GenerateContentParameters,\n ): Promise> => {\n this.maybeMoveToResponseJsonSchem(params);\n if (shouldDisableAfc(params.config)) {\n const transformedParams =\n await this.processParamsMaybeAddMcpUsage(params);\n return await this.generateContentStreamInternal(transformedParams);\n } else {\n return await this.processAfcStream(params);\n }\n };\n\n /**\n * Transforms the CallableTools in the parameters to be simply Tools, it\n * copies the params into a new object and replaces the tools, it does not\n * modify the original params. Also sets the MCP usage header if there are\n * MCP tools in the parameters.\n */\n private async processParamsMaybeAddMcpUsage(\n params: types.GenerateContentParameters,\n ): Promise {\n const tools = params.config?.tools;\n if (!tools) {\n return params;\n }\n const transformedTools = await Promise.all(\n tools.map(async (tool) => {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n return await callableTool.tool();\n }\n return tool;\n }),\n );\n const newParams: types.GenerateContentParameters = {\n model: params.model,\n contents: params.contents,\n config: {\n ...params.config,\n tools: transformedTools,\n },\n };\n newParams.config!.tools = transformedTools;\n\n if (\n params.config &&\n params.config.tools &&\n hasMcpToolUsage(params.config.tools)\n ) {\n const headers = params.config.httpOptions?.headers ?? {};\n let newHeaders = {...headers};\n if (Object.keys(newHeaders).length === 0) {\n newHeaders = this.apiClient.getDefaultHeaders();\n }\n setMcpUsageHeader(newHeaders);\n newParams.config!.httpOptions = {\n ...params.config.httpOptions,\n headers: newHeaders,\n };\n }\n return newParams;\n }\n\n private async initAfcToolsMap(\n params: types.GenerateContentParameters,\n ): Promise> {\n const afcTools: Map = new Map();\n for (const tool of params.config?.tools ?? []) {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n const toolDeclaration = await callableTool.tool();\n for (const declaration of toolDeclaration.functionDeclarations ?? []) {\n if (!declaration.name) {\n throw new Error('Function declaration name is required.');\n }\n if (afcTools.has(declaration.name)) {\n throw new Error(\n `Duplicate tool declaration name: ${declaration.name}`,\n );\n }\n afcTools.set(declaration.name, callableTool);\n }\n }\n }\n return afcTools;\n }\n\n private async processAfcStream(\n params: types.GenerateContentParameters,\n ): Promise> {\n const maxRemoteCalls =\n params.config?.automaticFunctionCalling?.maximumRemoteCalls ??\n DEFAULT_MAX_REMOTE_CALLS;\n let wereFunctionsCalled = false;\n let remoteCallCount = 0;\n const afcToolsMap = await this.initAfcToolsMap(params);\n return (async function* (\n models: Models,\n afcTools: Map,\n params: types.GenerateContentParameters,\n ) {\n while (remoteCallCount < maxRemoteCalls) {\n if (wereFunctionsCalled) {\n remoteCallCount++;\n wereFunctionsCalled = false;\n }\n const transformedParams =\n await models.processParamsMaybeAddMcpUsage(params);\n const response =\n await models.generateContentStreamInternal(transformedParams);\n\n const functionResponses: types.Part[] = [];\n const responseContents: types.Content[] = [];\n\n for await (const chunk of response) {\n yield chunk;\n if (chunk.candidates && chunk.candidates[0]?.content) {\n responseContents.push(chunk.candidates[0].content);\n for (const part of chunk.candidates[0].content.parts ?? []) {\n if (remoteCallCount < maxRemoteCalls && part.functionCall) {\n if (!part.functionCall.name) {\n throw new Error(\n 'Function call name was not returned by the model.',\n );\n }\n if (!afcTools.has(part.functionCall.name)) {\n throw new Error(\n `Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${\n part.functionCall.name\n }`,\n );\n } else {\n const responseParts = await afcTools\n .get(part.functionCall.name)!\n .callTool([part.functionCall]);\n functionResponses.push(...responseParts);\n }\n }\n }\n }\n }\n\n if (functionResponses.length > 0) {\n wereFunctionsCalled = true;\n const typedResponseChunk = new types.GenerateContentResponse();\n typedResponseChunk.candidates = [\n {\n content: {\n role: 'user',\n parts: functionResponses,\n },\n },\n ];\n\n yield typedResponseChunk;\n\n const newContents: types.Content[] = [];\n newContents.push(...responseContents);\n newContents.push({\n role: 'user',\n parts: functionResponses,\n });\n const updatedContents = tContents(params.contents).concat(\n newContents,\n );\n\n params.contents = updatedContents;\n } else {\n break;\n }\n }\n })(this, afcToolsMap, params);\n }\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param params - The parameters for generating images.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n generateImages = async (\n params: types.GenerateImagesParameters,\n ): Promise => {\n return await this.generateImagesInternal(params).then((apiResponse) => {\n let positivePromptSafetyAttributes;\n const generatedImages = [];\n\n if (apiResponse?.generatedImages) {\n for (const generatedImage of apiResponse.generatedImages) {\n if (\n generatedImage &&\n generatedImage?.safetyAttributes &&\n generatedImage?.safetyAttributes?.contentType === 'Positive Prompt'\n ) {\n positivePromptSafetyAttributes = generatedImage?.safetyAttributes;\n } else {\n generatedImages.push(generatedImage);\n }\n }\n }\n let response: types.GenerateImagesResponse;\n\n if (positivePromptSafetyAttributes) {\n response = {\n generatedImages: generatedImages,\n positivePromptSafetyAttributes: positivePromptSafetyAttributes,\n sdkHttpResponse: apiResponse.sdkHttpResponse,\n };\n } else {\n response = {\n generatedImages: generatedImages,\n sdkHttpResponse: apiResponse.sdkHttpResponse,\n };\n }\n return response;\n });\n };\n\n list = async (\n params?: types.ListModelsParameters,\n ): Promise> => {\n const defaultConfig: types.ListModelsConfig = {\n queryBase: true,\n };\n const actualConfig: types.ListModelsConfig = {\n ...defaultConfig,\n ...params?.config,\n };\n const actualParams: types.ListModelsParameters = {\n config: actualConfig,\n };\n\n if (this.apiClient.isVertexAI()) {\n if (!actualParams.config!.queryBase) {\n if (actualParams.config?.filter) {\n throw new Error(\n 'Filtering tuned models list for Vertex AI is not currently supported',\n );\n } else {\n actualParams.config!.filter = 'labels.tune-type:*';\n }\n }\n }\n\n return new Pager(\n PagedItem.PAGED_ITEM_MODELS,\n (x: types.ListModelsParameters) => this.listInternal(x),\n await this.listInternal(actualParams),\n actualParams,\n );\n };\n\n /**\n * Edits an image based on a prompt, list of reference images, and configuration.\n *\n * @param params - The parameters for editing an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.editImage({\n * model: 'imagen-3.0-capability-001',\n * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.',\n * referenceImages: [subjectReferenceImage]\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n editImage = async (\n params: types.EditImageParameters,\n ): Promise => {\n const paramsInternal: _internal_types.EditImageParametersInternal = {\n model: params.model,\n prompt: params.prompt,\n referenceImages: [],\n config: params.config,\n };\n if (params.referenceImages) {\n if (params.referenceImages) {\n paramsInternal.referenceImages = params.referenceImages.map((img) =>\n img.toReferenceImageAPI(),\n );\n }\n }\n return await this.editImageInternal(paramsInternal);\n };\n\n /**\n * Upscales an image based on an image, upscale factor, and configuration.\n * Only supported in Vertex AI currently.\n *\n * @param params - The parameters for upscaling an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.upscaleImage({\n * model: 'imagen-3.0-generate-002',\n * image: image,\n * upscaleFactor: 'x2',\n * config: {\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n upscaleImage = async (\n params: types.UpscaleImageParameters,\n ): Promise => {\n let apiConfig: _internal_types.UpscaleImageAPIConfigInternal = {\n numberOfImages: 1,\n mode: 'upscale',\n };\n\n if (params.config) {\n apiConfig = {...apiConfig, ...params.config};\n }\n\n const apiParams: _internal_types.UpscaleImageAPIParametersInternal = {\n model: params.model,\n image: params.image,\n upscaleFactor: params.upscaleFactor,\n config: apiConfig,\n };\n return await this.upscaleImageInternal(apiParams);\n };\n\n /**\n * Generates videos based on a text description and configuration.\n *\n * @param params - The parameters for generating videos.\n * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method.\n *\n * @example\n * ```ts\n * const operation = await ai.models.generateVideos({\n * model: 'veo-2.0-generate-001',\n * prompt: 'A neon hologram of a cat driving at top speed',\n * config: {\n * numberOfVideos: 1\n * });\n *\n * while (!operation.done) {\n * await new Promise(resolve => setTimeout(resolve, 10000));\n * operation = await ai.operations.getVideosOperation({operation: operation});\n * }\n *\n * console.log(operation.response?.generatedVideos?.[0]?.video?.uri);\n * ```\n */\n\n generateVideos = async (\n params: types.GenerateVideosParameters,\n ): Promise => {\n return await this.generateVideosInternal(params);\n };\n\n private async generateContentInternal(\n params: types.GenerateContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromVertex(apiResponse);\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromMldev(apiResponse);\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async generateContentStreamInternal(\n params: types.GenerateContentParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromVertex(\n (await chunk.json()) as types.GenerateContentResponse,\n );\n\n resp['sdkHttpResponse'] = {\n headers: chunk.headers,\n } as types.HttpResponse;\n\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromMldev(\n (await chunk.json()) as types.GenerateContentResponse,\n );\n\n resp['sdkHttpResponse'] = {\n headers: chunk.headers,\n } as types.HttpResponse;\n\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n }\n }\n\n /**\n * Calculates embeddings for the given contents. Only text is supported.\n *\n * @param params - The parameters for embedding contents.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.embedContent({\n * model: 'text-embedding-004',\n * contents: [\n * 'What is your name?',\n * 'What is your favorite color?',\n * ],\n * config: {\n * outputDimensionality: 64,\n * },\n * });\n * console.log(response);\n * ```\n */\n async embedContent(\n params: types.EmbedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.embedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EmbedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromVertex(apiResponse);\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.embedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchEmbedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EmbedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromMldev(apiResponse);\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param params - The parameters for generating images.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n private async generateImagesInternal(\n params: types.GenerateImagesParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateImagesParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateImagesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromVertex(apiResponse);\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateImagesParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateImagesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromMldev(apiResponse);\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async editImageInternal(\n params: _internal_types.EditImageParametersInternal,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.editImageParametersInternalToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EditImageResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.editImageResponseFromVertex(apiResponse);\n const typedResp = new types.EditImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n private async upscaleImageInternal(\n params: _internal_types.UpscaleImageAPIParametersInternal,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.upscaleImageAPIParametersInternalToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.UpscaleImageResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.upscaleImageResponseFromVertex(apiResponse);\n const typedResp = new types.UpscaleImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Recontextualizes an image.\n *\n * There are two types of recontextualization currently supported:\n * 1) Imagen Product Recontext - Generate images of products in new scenes\n * and contexts.\n * 2) Virtual Try-On: Generate images of persons modeling fashion products.\n *\n * @param params - The parameters for recontextualizing an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response1 = await ai.models.recontextImage({\n * model: 'imagen-product-recontext-preview-06-30',\n * source: {\n * prompt: 'In a modern kitchen setting.',\n * productImages: [productImage],\n * },\n * config: {\n * numberOfImages: 1,\n * },\n * });\n * console.log(response1?.generatedImages?.[0]?.image?.imageBytes);\n *\n * const response2 = await ai.models.recontextImage({\n * model: 'virtual-try-on-preview-08-04',\n * source: {\n * personImage: personImage,\n * productImages: [productImage],\n * },\n * config: {\n * numberOfImages: 1,\n * },\n * });\n * console.log(response2?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n async recontextImage(\n params: types.RecontextImageParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.recontextImageParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.recontextImageResponseFromVertex(apiResponse);\n const typedResp = new types.RecontextImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Segments an image, creating a mask of a specified area.\n *\n * @param params - The parameters for segmenting an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.segmentImage({\n * model: 'image-segmentation-001',\n * source: {\n * image: image,\n * },\n * config: {\n * mode: 'foreground',\n * },\n * });\n * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes);\n * ```\n */\n async segmentImage(\n params: types.SegmentImageParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.segmentImageParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.segmentImageResponseFromVertex(apiResponse);\n const typedResp = new types.SegmentImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Fetches information about a model by name.\n *\n * @example\n * ```ts\n * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'});\n * ```\n */\n async get(params: types.GetModelParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromVertex(apiResponse);\n\n return resp as types.Model;\n });\n } else {\n const body = converters.getModelParametersToMldev(this.apiClient, params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromMldev(apiResponse);\n\n return resp as types.Model;\n });\n }\n }\n\n private async listInternal(\n params: types.ListModelsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listModelsParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{models_url}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListModelsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listModelsResponseFromVertex(apiResponse);\n const typedResp = new types.ListModelsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listModelsParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{models_url}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListModelsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listModelsResponseFromMldev(apiResponse);\n const typedResp = new types.ListModelsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates a tuned model by its name.\n *\n * @param params - The parameters for updating the model.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.update({\n * model: 'tuned-model-name',\n * config: {\n * displayName: 'New display name',\n * description: 'New description',\n * },\n * });\n * ```\n */\n async update(params: types.UpdateModelParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromVertex(apiResponse);\n\n return resp as types.Model;\n });\n } else {\n const body = converters.updateModelParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromMldev(apiResponse);\n\n return resp as types.Model;\n });\n }\n }\n\n /**\n * Deletes a tuned model by its name.\n *\n * @param params - The parameters for deleting the model.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.delete({model: 'tuned-model-name'});\n * ```\n */\n async delete(\n params: types.DeleteModelParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteModelResponseFromVertex();\n const typedResp = new types.DeleteModelResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteModelParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteModelResponseFromMldev();\n const typedResp = new types.DeleteModelResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Counts the number of tokens in the given contents. Multimodal input is\n * supported for Gemini models.\n *\n * @param params - The parameters for counting tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.countTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'The quick brown fox jumps over the lazy dog.'\n * });\n * console.log(response);\n * ```\n */\n async countTokens(\n params: types.CountTokensParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.countTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.CountTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromVertex(apiResponse);\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.countTokensParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.CountTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromMldev(apiResponse);\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Given a list of contents, returns a corresponding TokensInfo containing\n * the list of tokens and list of token ids.\n *\n * This method is not supported by the Gemini Developer API.\n *\n * @param params - The parameters for computing tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.computeTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'What is your name?'\n * });\n * console.log(response);\n * ```\n */\n async computeTokens(\n params: types.ComputeTokensParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.computeTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:computeTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ComputeTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.computeTokensResponseFromVertex(apiResponse);\n const typedResp = new types.ComputeTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Generates videos based on a text description and configuration.\n *\n * @param params - The parameters for generating videos.\n * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method.\n *\n * @example\n * ```ts\n * const operation = await ai.models.generateVideos({\n * model: 'veo-2.0-generate-001',\n * prompt: 'A neon hologram of a cat driving at top speed',\n * config: {\n * numberOfVideos: 1\n * });\n *\n * while (!operation.done) {\n * await new Promise(resolve => setTimeout(resolve, 10000));\n * operation = await ai.operations.getVideosOperation({operation: operation});\n * }\n *\n * console.log(operation.response?.generatedVideos?.[0]?.video?.uri);\n * ```\n */\n\n private async generateVideosInternal(\n params: types.GenerateVideosParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateVideosParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromVertex(apiResponse);\n const typedResp = new types.GenerateVideosOperation();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateVideosParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromMldev(apiResponse);\n const typedResp = new types.GenerateVideosOperation();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as types from '../types.js';\n\nexport function getOperationParametersToMldev(\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getOperationParametersToVertex(\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fetchPredictOperationParametersToVertex(\n fromObject: types.FetchPredictOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(toObject, ['operationName'], fromOperationName);\n }\n\n const fromResourceName = common.getValueByPath(fromObject, ['resourceName']);\n if (fromResourceName != null) {\n common.setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_operations_converters.js';\nimport * as types from './types.js';\n\nexport class Operations extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param parameters The parameters for the get operation request.\n * @return The updated Operation object, with the latest status or result.\n */\n async getVideosOperation(\n parameters: types.OperationGetParameters<\n types.GenerateVideosResponse,\n types.GenerateVideosOperation\n >,\n ): Promise {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n let httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n const rawOperation = await this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: true,\n });\n } else {\n const rawOperation = await this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: false,\n });\n }\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param parameters The parameters for the get operation request.\n * @return The updated Operation object, with the latest status or result.\n */\n async get>(\n parameters: types.OperationGetParameters,\n ): Promise> {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n let httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n const rawOperation = await this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: true,\n });\n } else {\n const rawOperation = await this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: false,\n });\n }\n }\n\n private async getVideosOperationInternal(\n params: types.GetOperationParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getOperationParametersToVertex(params);\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n } else {\n const body = converters.getOperationParametersToMldev(params);\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n }\n }\n\n private async fetchPredictVideosOperationInternal(\n params: types.FetchPredictOperationParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.fetchPredictOperationParametersToVertex(params);\n path = common.formatMap(\n '{resourceName}:fetchPredictOperation',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToMldev(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n if (common.getValueByPath(fromObject, ['transparent']) !== undefined) {\n throw new Error('transparent parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToMldev(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToMldev(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToMldev(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToMldev(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToMldev(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToMldev(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToMldev(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToMldev(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToMldev(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectConstraintsToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectConstraints,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateAuthTokenConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromNewSessionExpireTime = common.getValueByPath(fromObject, [\n 'newSessionExpireTime',\n ]);\n if (parentObject !== undefined && fromNewSessionExpireTime != null) {\n common.setValueByPath(\n parentObject,\n ['newSessionExpireTime'],\n fromNewSessionExpireTime,\n );\n }\n\n const fromUses = common.getValueByPath(fromObject, ['uses']);\n if (parentObject !== undefined && fromUses != null) {\n common.setValueByPath(parentObject, ['uses'], fromUses);\n }\n\n const fromLiveConnectConstraints = common.getValueByPath(fromObject, [\n 'liveConnectConstraints',\n ]);\n if (parentObject !== undefined && fromLiveConnectConstraints != null) {\n common.setValueByPath(\n parentObject,\n ['bidiGenerateContentSetup'],\n liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints),\n );\n }\n\n const fromLockAdditionalFields = common.getValueByPath(fromObject, [\n 'lockAdditionalFields',\n ]);\n if (parentObject !== undefined && fromLockAdditionalFields != null) {\n common.setValueByPath(\n parentObject,\n ['fieldMask'],\n fromLockAdditionalFields,\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateAuthTokenParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createAuthTokenConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenParametersToVertex(\n fromObject: types.CreateAuthTokenParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['config']) !== undefined) {\n throw new Error('config parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function authTokenFromMldev(\n fromObject: types.AuthToken,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function authTokenFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_tokens_converters.js';\nimport * as types from './types.js';\n\n/**\n * Returns a comma-separated list of field masks from a given object.\n *\n * @param setup The object to extract field masks from.\n * @return A comma-separated list of field masks.\n */\nfunction getFieldMasks(setup: Record): string {\n const fields: string[] = [];\n\n for (const key in setup) {\n if (Object.prototype.hasOwnProperty.call(setup, key)) {\n const value = setup[key];\n // 2nd layer, recursively get field masks see TODO(b/418290100)\n if (\n typeof value === 'object' &&\n value != null &&\n Object.keys(value).length > 0\n ) {\n const field = Object.keys(value).map((kk) => `${key}.${kk}`);\n fields.push(...field);\n } else {\n fields.push(key); // 1st layer\n }\n }\n }\n\n return fields.join(',');\n}\n\n/**\n * Converts bidiGenerateContentSetup.\n * @param requestDict - The request dictionary.\n * @param config - The configuration object.\n * @return - The modified request dictionary.\n */\nfunction convertBidiSetupToTokenSetup(\n requestDict: Record,\n config?: {lockAdditionalFields?: string[]},\n): Record {\n // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup.\n let setupForMaskGeneration: Record | null = null;\n const bidiGenerateContentSetupValue = requestDict['bidiGenerateContentSetup'];\n if (\n typeof bidiGenerateContentSetupValue === 'object' &&\n bidiGenerateContentSetupValue !== null &&\n 'setup' in bidiGenerateContentSetupValue\n ) {\n // Now we know bidiGenerateContentSetupValue is an object and has a 'setup'\n // property.\n const innerSetup = (bidiGenerateContentSetupValue as {setup: unknown})\n .setup;\n\n if (typeof innerSetup === 'object' && innerSetup !== null) {\n // Valid inner setup found.\n requestDict['bidiGenerateContentSetup'] = innerSetup;\n setupForMaskGeneration = innerSetup as Record;\n } else {\n // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as\n // if bidiGenerateContentSetup is invalid.\n delete requestDict['bidiGenerateContentSetup'];\n }\n } else if (bidiGenerateContentSetupValue !== undefined) {\n // `bidiGenerateContentSetup` exists but not in the expected\n // shape {setup: {...}}; treat as invalid.\n delete requestDict['bidiGenerateContentSetup'];\n }\n\n const preExistingFieldMask = requestDict['fieldMask'];\n // Handle mask generation setup.\n if (setupForMaskGeneration) {\n const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration);\n\n if (\n Array.isArray(config?.lockAdditionalFields) &&\n config?.lockAdditionalFields.length === 0\n ) {\n // Case 1: lockAdditionalFields is an empty array. Lock only fields from\n // bidi setup.\n if (generatedMaskFromBidi) {\n // Only assign if mask is not empty\n requestDict['fieldMask'] = generatedMaskFromBidi;\n } else {\n delete requestDict['fieldMask']; // If mask is empty, effectively no\n // specific fields locked by bidi\n }\n } else if (\n config?.lockAdditionalFields &&\n config.lockAdditionalFields.length > 0 &&\n preExistingFieldMask !== null &&\n Array.isArray(preExistingFieldMask) &&\n preExistingFieldMask.length > 0\n ) {\n // Case 2: Lock fields from bidi setup + additional fields\n // (preExistingFieldMask).\n\n const generationConfigFields = [\n 'temperature',\n 'topK',\n 'topP',\n 'maxOutputTokens',\n 'responseModalities',\n 'seed',\n 'speechConfig',\n ];\n\n let mappedFieldsFromPreExisting: string[] = [];\n if (preExistingFieldMask.length > 0) {\n mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => {\n if (generationConfigFields.includes(field)) {\n return `generationConfig.${field}`;\n }\n return field; // Keep original field name if not in\n // generationConfigFields\n });\n }\n\n const finalMaskParts: string[] = [];\n if (generatedMaskFromBidi) {\n finalMaskParts.push(generatedMaskFromBidi);\n }\n if (mappedFieldsFromPreExisting.length > 0) {\n finalMaskParts.push(...mappedFieldsFromPreExisting);\n }\n\n if (finalMaskParts.length > 0) {\n requestDict['fieldMask'] = finalMaskParts.join(',');\n } else {\n // If no fields from bidi and no valid additional fields from\n // pre-existing mask.\n delete requestDict['fieldMask'];\n }\n } else {\n // Case 3: \"Lock all fields\" (meaning, don't send a field_mask, let server\n // defaults apply or all are mutable). This is hit if:\n // - `config.lockAdditionalFields` is undefined.\n // - `config.lockAdditionalFields` is non-empty, BUT\n // `preExistingFieldMask` is null, not a string, or an empty string.\n delete requestDict['fieldMask'];\n }\n } else {\n // No valid `bidiGenerateContentSetup` was found or extracted.\n // \"Lock additional null fields if any\".\n if (\n preExistingFieldMask !== null &&\n Array.isArray(preExistingFieldMask) &&\n preExistingFieldMask.length > 0\n ) {\n // If there's a pre-existing field mask, it's a string, and it's not\n // empty, then we should lock all fields.\n requestDict['fieldMask'] = preExistingFieldMask.join(',');\n } else {\n delete requestDict['fieldMask'];\n }\n }\n\n return requestDict;\n}\n\nexport class Tokens extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n /**\n * Creates an ephemeral auth token resource.\n *\n * @experimental\n *\n * @remarks\n * Ephemeral auth tokens is only supported in the Gemini Developer API.\n * It can be used for the session connection to the Live constrained API.\n * Support in v1alpha only.\n *\n * @param params - The parameters for the create request.\n * @return The created auth token.\n *\n * @example\n * ```ts\n * const ai = new GoogleGenAI({\n * apiKey: token.name,\n * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only.\n * });\n *\n * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig\n * // when using the token in Live API sessions. Each session connection can\n * // use a different configuration.\n * const config: CreateAuthTokenConfig = {\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 2: If LiveEphemeralParameters is set, lock all fields in\n * // LiveConnectConfig when using the token in Live API sessions. For\n * // example, changing `outputAudioTranscription` in the Live API\n * // connection will be ignored by the API.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * }\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is\n * // set, lock LiveConnectConfig with set and additional fields (e.g.\n * // responseModalities, systemInstruction, temperature in this example) when\n * // using the token in Live API sessions.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * },\n * lockAdditionalFields: ['temperature'],\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is\n * // empty array, lock LiveConnectConfig with set fields (e.g.\n * // responseModalities, systemInstruction in this example) when using the\n * // token in Live API sessions.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * },\n * lockAdditionalFields: [],\n * }\n * const token = await ai.tokens.create(config);\n * ```\n */\n\n async create(\n params: types.CreateAuthTokenParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'The client.tokens.create method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createAuthTokenParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'auth_tokens',\n body['_url'] as Record,\n );\n\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const transformedBody = convertBidiSetupToTokenSetup(body, params.config);\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(transformedBody),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.authTokenFromMldev(apiResponse);\n\n return resp as types.AuthToken;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {GoogleAuth, GoogleAuthOptions} from 'google-auth-library';\n\nimport {Auth} from '../_auth.js';\n\nexport const GOOGLE_API_KEY_HEADER = 'x-goog-api-key';\nconst REQUIRED_VERTEX_AI_SCOPE =\n 'https://www.googleapis.com/auth/cloud-platform';\n\nexport interface NodeAuthOptions {\n /**\n * The API Key. This is required for Gemini API users.\n */\n apiKey?: string;\n /**\n * Optional. These are the authentication options provided by google-auth-library for Vertex AI users.\n * Complete list of authentication options are documented in the\n * GoogleAuthOptions interface:\n * https://github.com/googleapis/google-auth-library-nodejs/blob/main/src/auth/googleauth.ts.\n */\n googleAuthOptions?: GoogleAuthOptions;\n}\n\nexport class NodeAuth implements Auth {\n private readonly googleAuth?: GoogleAuth;\n private readonly apiKey?: string;\n\n constructor(opts: NodeAuthOptions) {\n if (opts.apiKey !== undefined) {\n this.apiKey = opts.apiKey;\n return;\n }\n const vertexAuthOptions = buildGoogleAuthOptions(opts.googleAuthOptions);\n this.googleAuth = new GoogleAuth(vertexAuthOptions);\n }\n\n async addAuthHeaders(headers: Headers): Promise {\n if (this.apiKey !== undefined) {\n if (this.apiKey.startsWith('auth_tokens/')) {\n throw new Error('Ephemeral tokens are only supported by the live API.');\n }\n this.addKeyHeader(headers);\n return;\n }\n\n return this.addGoogleAuthHeaders(headers);\n }\n\n private addKeyHeader(headers: Headers) {\n if (headers.get(GOOGLE_API_KEY_HEADER) !== null) {\n return;\n }\n if (this.apiKey === undefined) {\n // This should never happen, this method is only called\n // when apiKey is set.\n throw new Error('Trying to set API key header but apiKey is not set');\n }\n headers.append(GOOGLE_API_KEY_HEADER, this.apiKey);\n }\n\n private async addGoogleAuthHeaders(headers: Headers): Promise {\n if (this.googleAuth === undefined) {\n // This should never happen, addGoogleAuthHeaders should only be\n // called when there is no apiKey set and in these cases googleAuth\n // is set.\n throw new Error(\n 'Trying to set google-auth headers but googleAuth is unset',\n );\n }\n const authHeaders = await this.googleAuth.getRequestHeaders();\n for (const key in authHeaders) {\n if (headers.get(key) !== null) {\n continue;\n }\n headers.append(key, authHeaders[key]);\n }\n }\n}\n\nfunction buildGoogleAuthOptions(\n googleAuthOptions?: GoogleAuthOptions,\n): GoogleAuthOptions {\n let authOptions: GoogleAuthOptions;\n if (!googleAuthOptions) {\n authOptions = {\n scopes: [REQUIRED_VERTEX_AI_SCOPE],\n };\n return authOptions;\n } else {\n authOptions = googleAuthOptions;\n if (!authOptions.scopes) {\n authOptions.scopes = [REQUIRED_VERTEX_AI_SCOPE];\n return authOptions;\n } else if (\n (typeof authOptions.scopes === 'string' &&\n authOptions.scopes !== REQUIRED_VERTEX_AI_SCOPE) ||\n (Array.isArray(authOptions.scopes) &&\n authOptions.scopes.indexOf(REQUIRED_VERTEX_AI_SCOPE) < 0)\n ) {\n throw new Error(\n `Invalid auth scopes. Scopes must include: ${REQUIRED_VERTEX_AI_SCOPE}`,\n );\n }\n return authOptions;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {createWriteStream, writeFile} from 'fs';\nimport {Readable} from 'node:stream';\nimport type {ReadableStream} from 'node:stream/web';\n\nimport {ApiClient} from '../_api_client.js';\nimport {Downloader} from '../_downloader.js';\nimport {isGeneratedVideo, isVideo, tFileName} from '../_transformers.js';\nimport {\n DownloadFileParameters,\n GeneratedVideo,\n HttpResponse,\n Video,\n} from '../types.js';\n\nexport class NodeDownloader implements Downloader {\n async download(\n params: DownloadFileParameters,\n apiClient: ApiClient,\n ): Promise {\n if (params.downloadPath) {\n const response = await downloadFile(params, apiClient);\n if (response instanceof HttpResponse) {\n const writer = createWriteStream(params.downloadPath);\n Readable.fromWeb(\n response.responseInternal.body as ReadableStream,\n ).pipe(writer);\n } else {\n writeFile(\n params.downloadPath,\n response as string,\n {encoding: 'base64'},\n (error) => {\n if (error) {\n throw new Error(\n `Failed to write file to ${params.downloadPath}: ${error}`,\n );\n }\n },\n );\n }\n }\n }\n}\n\nasync function downloadFile(\n params: DownloadFileParameters,\n apiClient: ApiClient,\n): Promise {\n const name = tFileName(params.file);\n if (name !== undefined) {\n return await apiClient.request({\n path: `files/${name}:download`,\n httpMethod: 'GET',\n queryParams: {\n 'alt': 'media',\n },\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n } else if (isGeneratedVideo(params.file)) {\n const videoBytes = (params.file as GeneratedVideo).video?.videoBytes;\n if (typeof videoBytes === 'string') {\n return videoBytes;\n } else {\n throw new Error(\n 'Failed to download generated video, Uri or videoBytes not found.',\n );\n }\n } else if (isVideo(params.file)) {\n const videoBytes = (params.file as Video).videoBytes;\n if (typeof videoBytes === 'string') {\n return videoBytes;\n } else {\n throw new Error('Failed to download video, Uri or videoBytes not found.');\n }\n } else {\n throw new Error('Unsupported file type');\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as NodeWs from 'ws';\n\nimport {\n WebSocket,\n WebSocketCallbacks,\n WebSocketFactory,\n} from '../_websocket.js';\n\nexport class NodeWebSocketFactory implements WebSocketFactory {\n create(\n url: string,\n headers: Record,\n callbacks: WebSocketCallbacks,\n ): WebSocket {\n return new NodeWebSocket(url, headers, callbacks);\n }\n}\n\nexport class NodeWebSocket implements WebSocket {\n private ws?: NodeWs.WebSocket;\n\n constructor(\n private readonly url: string,\n private readonly headers: Record,\n private readonly callbacks: WebSocketCallbacks,\n ) {}\n\n connect(): void {\n this.ws = new NodeWs.WebSocket(this.url, {headers: this.headers});\n\n this.ws.onopen = this.callbacks.onopen;\n this.ws.onerror = this.callbacks.onerror;\n this.ws.onclose = this.callbacks.onclose;\n this.ws.onmessage = this.callbacks.onmessage;\n }\n\n send(message: string) {\n if (this.ws === undefined) {\n throw new Error('WebSocket is not connected');\n }\n\n this.ws.send(message);\n }\n\n close() {\n if (this.ws === undefined) {\n throw new Error('WebSocket is not connected');\n }\n\n this.ws.close();\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function getTuningJobParametersToMldev(\n fromObject: types.GetTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsConfigToMldev(\n fromObject: types.ListTuningJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsParametersToMldev(\n fromObject: types.ListTuningJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listTuningJobsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function tuningExampleToMldev(\n fromObject: types.TuningExample,\n): Record {\n const toObject: Record = {};\n\n const fromTextInput = common.getValueByPath(fromObject, ['textInput']);\n if (fromTextInput != null) {\n common.setValueByPath(toObject, ['textInput'], fromTextInput);\n }\n\n const fromOutput = common.getValueByPath(fromObject, ['output']);\n if (fromOutput != null) {\n common.setValueByPath(toObject, ['output'], fromOutput);\n }\n\n return toObject;\n}\n\nexport function tuningDatasetToMldev(\n fromObject: types.TuningDataset,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['vertexDatasetResource']) !== undefined\n ) {\n throw new Error(\n 'vertexDatasetResource parameter is not supported in Gemini API.',\n );\n }\n\n const fromExamples = common.getValueByPath(fromObject, ['examples']);\n if (fromExamples != null) {\n let transformedList = fromExamples;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningExampleToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['examples', 'examples'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createTuningJobConfigToMldev(\n fromObject: types.CreateTuningJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['validationDataset']) !== undefined) {\n throw new Error(\n 'validationDataset parameter is not supported in Gemini API.',\n );\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (parentObject !== undefined && fromTunedModelDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['displayName'],\n fromTunedModelDisplayName,\n );\n }\n\n if (common.getValueByPath(fromObject, ['description']) !== undefined) {\n throw new Error('description parameter is not supported in Gemini API.');\n }\n\n const fromEpochCount = common.getValueByPath(fromObject, ['epochCount']);\n if (parentObject !== undefined && fromEpochCount != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'epochCount'],\n fromEpochCount,\n );\n }\n\n const fromLearningRateMultiplier = common.getValueByPath(fromObject, [\n 'learningRateMultiplier',\n ]);\n if (fromLearningRateMultiplier != null) {\n common.setValueByPath(\n toObject,\n ['tuningTask', 'hyperparameters', 'learningRateMultiplier'],\n fromLearningRateMultiplier,\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['exportLastCheckpointOnly']) !==\n undefined\n ) {\n throw new Error(\n 'exportLastCheckpointOnly parameter is not supported in Gemini API.',\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['preTunedModelCheckpointId']) !==\n undefined\n ) {\n throw new Error(\n 'preTunedModelCheckpointId parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['adapterSize']) !== undefined) {\n throw new Error('adapterSize parameter is not supported in Gemini API.');\n }\n\n const fromBatchSize = common.getValueByPath(fromObject, ['batchSize']);\n if (parentObject !== undefined && fromBatchSize != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'batchSize'],\n fromBatchSize,\n );\n }\n\n const fromLearningRate = common.getValueByPath(fromObject, ['learningRate']);\n if (parentObject !== undefined && fromLearningRate != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'learningRate'],\n fromLearningRate,\n );\n }\n\n return toObject;\n}\n\nexport function createTuningJobParametersPrivateToMldev(\n fromObject: types.CreateTuningJobParametersPrivate,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromPreTunedModel = common.getValueByPath(fromObject, [\n 'preTunedModel',\n ]);\n if (fromPreTunedModel != null) {\n common.setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel);\n }\n\n const fromTrainingDataset = common.getValueByPath(fromObject, [\n 'trainingDataset',\n ]);\n if (fromTrainingDataset != null) {\n common.setValueByPath(\n toObject,\n ['tuningTask', 'trainingData'],\n tuningDatasetToMldev(fromTrainingDataset),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createTuningJobConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getTuningJobParametersToVertex(\n fromObject: types.GetTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsConfigToVertex(\n fromObject: types.ListTuningJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsParametersToVertex(\n fromObject: types.ListTuningJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listTuningJobsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function tuningDatasetToVertex(\n fromObject: types.TuningDataset,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (parentObject !== undefined && fromGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromGcsUri,\n );\n }\n\n const fromVertexDatasetResource = common.getValueByPath(fromObject, [\n 'vertexDatasetResource',\n ]);\n if (parentObject !== undefined && fromVertexDatasetResource != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromVertexDatasetResource,\n );\n }\n\n if (common.getValueByPath(fromObject, ['examples']) !== undefined) {\n throw new Error('examples parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function tuningValidationDatasetToVertex(\n fromObject: types.TuningValidationDataset,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['validationDatasetUri'], fromGcsUri);\n }\n\n const fromVertexDatasetResource = common.getValueByPath(fromObject, [\n 'vertexDatasetResource',\n ]);\n if (parentObject !== undefined && fromVertexDatasetResource != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromVertexDatasetResource,\n );\n }\n\n return toObject;\n}\n\nexport function createTuningJobConfigToVertex(\n fromObject: types.CreateTuningJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromValidationDataset = common.getValueByPath(fromObject, [\n 'validationDataset',\n ]);\n if (parentObject !== undefined && fromValidationDataset != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec'],\n tuningValidationDatasetToVertex(fromValidationDataset, toObject),\n );\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (parentObject !== undefined && fromTunedModelDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromEpochCount = common.getValueByPath(fromObject, ['epochCount']);\n if (parentObject !== undefined && fromEpochCount != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'epochCount'],\n fromEpochCount,\n );\n }\n\n const fromLearningRateMultiplier = common.getValueByPath(fromObject, [\n 'learningRateMultiplier',\n ]);\n if (parentObject !== undefined && fromLearningRateMultiplier != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'],\n fromLearningRateMultiplier,\n );\n }\n\n const fromExportLastCheckpointOnly = common.getValueByPath(fromObject, [\n 'exportLastCheckpointOnly',\n ]);\n if (parentObject !== undefined && fromExportLastCheckpointOnly != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'exportLastCheckpointOnly'],\n fromExportLastCheckpointOnly,\n );\n }\n\n const fromPreTunedModelCheckpointId = common.getValueByPath(fromObject, [\n 'preTunedModelCheckpointId',\n ]);\n if (fromPreTunedModelCheckpointId != null) {\n common.setValueByPath(\n toObject,\n ['preTunedModel', 'checkpointId'],\n fromPreTunedModelCheckpointId,\n );\n }\n\n const fromAdapterSize = common.getValueByPath(fromObject, ['adapterSize']);\n if (parentObject !== undefined && fromAdapterSize != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'],\n fromAdapterSize,\n );\n }\n\n if (common.getValueByPath(fromObject, ['batchSize']) !== undefined) {\n throw new Error('batchSize parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['learningRate']) !== undefined) {\n throw new Error('learningRate parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function createTuningJobParametersPrivateToVertex(\n fromObject: types.CreateTuningJobParametersPrivate,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromPreTunedModel = common.getValueByPath(fromObject, [\n 'preTunedModel',\n ]);\n if (fromPreTunedModel != null) {\n common.setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel);\n }\n\n const fromTrainingDataset = common.getValueByPath(fromObject, [\n 'trainingDataset',\n ]);\n if (fromTrainingDataset != null) {\n common.setValueByPath(\n toObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n tuningDatasetToVertex(fromTrainingDataset, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createTuningJobConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function tunedModelFromMldev(\n fromObject: types.TunedModel,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['name']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['name']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n return toObject;\n}\n\nexport function tuningJobFromMldev(\n fromObject: types.TuningJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tTuningJobStatus(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, [\n 'tuningTask',\n 'startTime',\n ]);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, [\n 'tuningTask',\n 'completeTime',\n ]);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTunedModel = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModel != null) {\n common.setValueByPath(\n toObject,\n ['tunedModel'],\n tunedModelFromMldev(fromTunedModel),\n );\n }\n\n const fromCustomBaseModel = common.getValueByPath(fromObject, [\n 'customBaseModel',\n ]);\n if (fromCustomBaseModel != null) {\n common.setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel);\n }\n\n const fromExperiment = common.getValueByPath(fromObject, ['experiment']);\n if (fromExperiment != null) {\n common.setValueByPath(toObject, ['experiment'], fromExperiment);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromOutputUri = common.getValueByPath(fromObject, ['outputUri']);\n if (fromOutputUri != null) {\n common.setValueByPath(toObject, ['outputUri'], fromOutputUri);\n }\n\n const fromPipelineJob = common.getValueByPath(fromObject, ['pipelineJob']);\n if (fromPipelineJob != null) {\n common.setValueByPath(toObject, ['pipelineJob'], fromPipelineJob);\n }\n\n const fromServiceAccount = common.getValueByPath(fromObject, [\n 'serviceAccount',\n ]);\n if (fromServiceAccount != null) {\n common.setValueByPath(toObject, ['serviceAccount'], fromServiceAccount);\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (fromTunedModelDisplayName != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n return toObject;\n}\n\nexport function listTuningJobsResponseFromMldev(\n fromObject: types.ListTuningJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromTuningJobs = common.getValueByPath(fromObject, ['tunedModels']);\n if (fromTuningJobs != null) {\n let transformedList = fromTuningJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningJobFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['tuningJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function tuningOperationFromMldev(\n fromObject: types.TuningOperation,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n return toObject;\n}\n\nexport function tunedModelCheckpointFromVertex(\n fromObject: types.TunedModelCheckpoint,\n): Record {\n const toObject: Record = {};\n\n const fromCheckpointId = common.getValueByPath(fromObject, ['checkpointId']);\n if (fromCheckpointId != null) {\n common.setValueByPath(toObject, ['checkpointId'], fromCheckpointId);\n }\n\n const fromEpoch = common.getValueByPath(fromObject, ['epoch']);\n if (fromEpoch != null) {\n common.setValueByPath(toObject, ['epoch'], fromEpoch);\n }\n\n const fromStep = common.getValueByPath(fromObject, ['step']);\n if (fromStep != null) {\n common.setValueByPath(toObject, ['step'], fromStep);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['endpoint']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n return toObject;\n}\n\nexport function tunedModelFromVertex(\n fromObject: types.TunedModel,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['endpoint']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n const fromCheckpoints = common.getValueByPath(fromObject, ['checkpoints']);\n if (fromCheckpoints != null) {\n let transformedList = fromCheckpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tunedModelCheckpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['checkpoints'], transformedList);\n }\n\n return toObject;\n}\n\nexport function tuningJobFromVertex(\n fromObject: types.TuningJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tTuningJobStatus(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTunedModel = common.getValueByPath(fromObject, ['tunedModel']);\n if (fromTunedModel != null) {\n common.setValueByPath(\n toObject,\n ['tunedModel'],\n tunedModelFromVertex(fromTunedModel),\n );\n }\n\n const fromPreTunedModel = common.getValueByPath(fromObject, [\n 'preTunedModel',\n ]);\n if (fromPreTunedModel != null) {\n common.setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel);\n }\n\n const fromSupervisedTuningSpec = common.getValueByPath(fromObject, [\n 'supervisedTuningSpec',\n ]);\n if (fromSupervisedTuningSpec != null) {\n common.setValueByPath(\n toObject,\n ['supervisedTuningSpec'],\n fromSupervisedTuningSpec,\n );\n }\n\n const fromTuningDataStats = common.getValueByPath(fromObject, [\n 'tuningDataStats',\n ]);\n if (fromTuningDataStats != null) {\n common.setValueByPath(toObject, ['tuningDataStats'], fromTuningDataStats);\n }\n\n const fromEncryptionSpec = common.getValueByPath(fromObject, [\n 'encryptionSpec',\n ]);\n if (fromEncryptionSpec != null) {\n common.setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec);\n }\n\n const fromPartnerModelTuningSpec = common.getValueByPath(fromObject, [\n 'partnerModelTuningSpec',\n ]);\n if (fromPartnerModelTuningSpec != null) {\n common.setValueByPath(\n toObject,\n ['partnerModelTuningSpec'],\n fromPartnerModelTuningSpec,\n );\n }\n\n const fromCustomBaseModel = common.getValueByPath(fromObject, [\n 'customBaseModel',\n ]);\n if (fromCustomBaseModel != null) {\n common.setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel);\n }\n\n const fromExperiment = common.getValueByPath(fromObject, ['experiment']);\n if (fromExperiment != null) {\n common.setValueByPath(toObject, ['experiment'], fromExperiment);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromOutputUri = common.getValueByPath(fromObject, ['outputUri']);\n if (fromOutputUri != null) {\n common.setValueByPath(toObject, ['outputUri'], fromOutputUri);\n }\n\n const fromPipelineJob = common.getValueByPath(fromObject, ['pipelineJob']);\n if (fromPipelineJob != null) {\n common.setValueByPath(toObject, ['pipelineJob'], fromPipelineJob);\n }\n\n const fromServiceAccount = common.getValueByPath(fromObject, [\n 'serviceAccount',\n ]);\n if (fromServiceAccount != null) {\n common.setValueByPath(toObject, ['serviceAccount'], fromServiceAccount);\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (fromTunedModelDisplayName != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n return toObject;\n}\n\nexport function listTuningJobsResponseFromVertex(\n fromObject: types.ListTuningJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromTuningJobs = common.getValueByPath(fromObject, ['tuningJobs']);\n if (fromTuningJobs != null) {\n let transformedList = fromTuningJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningJobFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['tuningJobs'], transformedList);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_tunings_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Tunings extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets a TuningJob.\n *\n * @param name - The resource name of the tuning job.\n * @return - A TuningJob object.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n get = async (\n params: types.GetTuningJobParameters,\n ): Promise => {\n return await this.getInternal(params);\n };\n\n /**\n * Lists tuning jobs.\n *\n * @param config - The configuration for the list request.\n * @return - A list of tuning jobs.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n list = async (\n params: types.ListTuningJobsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_TUNING_JOBS,\n (x: types.ListTuningJobsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a supervised fine-tuning job.\n *\n * @param params - The parameters for the tuning job.\n * @return - A TuningJob operation.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n tune = async (\n params: types.CreateTuningJobParameters,\n ): Promise => {\n if (this.apiClient.isVertexAI()) {\n if (params.baseModel.startsWith('projects/')) {\n const preTunedModel: types.PreTunedModel = {\n tunedModelName: params.baseModel,\n };\n const paramsPrivate: types.CreateTuningJobParametersPrivate = {\n ...params,\n preTunedModel: preTunedModel,\n };\n paramsPrivate.baseModel = undefined;\n return await this.tuneInternal(paramsPrivate);\n } else {\n const paramsPrivate: types.CreateTuningJobParametersPrivate = {\n ...params,\n };\n return await this.tuneInternal(paramsPrivate);\n }\n } else {\n const paramsPrivate: types.CreateTuningJobParametersPrivate = {\n ...params,\n };\n const operation = await this.tuneMldevInternal(paramsPrivate);\n let tunedModelName = '';\n if (\n operation['metadata'] !== undefined &&\n operation['metadata']['tunedModel'] !== undefined\n ) {\n tunedModelName = operation['metadata']['tunedModel'] as string;\n } else if (\n operation['name'] !== undefined &&\n operation['name'].includes('/operations/')\n ) {\n tunedModelName = operation['name'].split('/operations/')[0];\n }\n const tuningJob: types.TuningJob = {\n name: tunedModelName,\n state: types.JobState.JOB_STATE_QUEUED,\n };\n\n return tuningJob;\n }\n };\n\n private async getInternal(\n params: types.GetTuningJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getTuningJobParametersToVertex(params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromVertex(apiResponse);\n\n return resp as types.TuningJob;\n });\n } else {\n const body = converters.getTuningJobParametersToMldev(params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromMldev(apiResponse);\n\n return resp as types.TuningJob;\n });\n }\n }\n\n private async listInternal(\n params: types.ListTuningJobsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listTuningJobsParametersToVertex(params);\n path = common.formatMap(\n 'tuningJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListTuningJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listTuningJobsResponseFromVertex(apiResponse);\n const typedResp = new types.ListTuningJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listTuningJobsParametersToMldev(params);\n path = common.formatMap(\n 'tunedModels',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListTuningJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listTuningJobsResponseFromMldev(apiResponse);\n const typedResp = new types.ListTuningJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async tuneInternal(\n params: types.CreateTuningJobParametersPrivate,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createTuningJobParametersPrivateToVertex(params);\n path = common.formatMap(\n 'tuningJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromVertex(apiResponse);\n\n return resp as types.TuningJob;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n private async tuneMldevInternal(\n params: types.CreateTuningJobParametersPrivate,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createTuningJobParametersPrivateToMldev(params);\n path = common.formatMap(\n 'tunedModels',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningOperation;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningOperationFromMldev(apiResponse);\n\n return resp as types.TuningOperation;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {ApiClient} from '../_api_client.js';\nimport {FileStat, Uploader} from '../_uploader.js';\nimport {File, HttpResponse} from '../types.js';\n\nimport {crossError} from './_cross_error.js';\n\nexport const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes\nexport const MAX_RETRY_COUNT = 3;\nexport const INITIAL_RETRY_DELAY_MS = 1000;\nexport const DELAY_MULTIPLIER = 2;\nexport const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status';\n\nexport class CrossUploader implements Uploader {\n async upload(\n file: string | Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return uploadBlob(file, uploadUrl, apiClient);\n }\n }\n\n async stat(file: string | Blob): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return getBlobStat(file);\n }\n }\n}\n\nexport async function uploadBlob(\n file: Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n): Promise {\n let fileSize = 0;\n let offset = 0;\n let response: HttpResponse = new HttpResponse(new Response());\n let uploadCommand = 'upload';\n fileSize = file.size;\n while (offset < fileSize) {\n const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);\n const chunk = file.slice(offset, offset + chunkSize);\n if (offset + chunkSize >= fileSize) {\n uploadCommand += ', finalize';\n }\n let retryCount = 0;\n let currentDelayMs = INITIAL_RETRY_DELAY_MS;\n while (retryCount < MAX_RETRY_COUNT) {\n response = await apiClient.request({\n path: '',\n body: chunk,\n httpMethod: 'POST',\n httpOptions: {\n apiVersion: '',\n baseUrl: uploadUrl,\n headers: {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': String(offset),\n 'Content-Length': String(chunkSize),\n },\n },\n });\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) {\n break;\n }\n retryCount++;\n await sleep(currentDelayMs);\n currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;\n }\n offset += chunkSize;\n // The `x-goog-upload-status` header field can be `active`, `final` and\n //`cancelled` in resposne.\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'active') {\n break;\n }\n // TODO(b/401391430) Investigate why the upload status is not finalized\n // even though all content has been uploaded.\n if (fileSize <= offset) {\n throw new Error(\n 'All content has been uploaded, but the upload status is not finalized.',\n );\n }\n }\n const responseJson = (await response?.json()) as Record<\n string,\n File | unknown\n >;\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'final') {\n throw new Error('Failed to upload file: Upload status is not finalized.');\n }\n return responseJson['file'] as File;\n}\n\nexport async function getBlobStat(file: Blob): Promise {\n const fileStat: FileStat = {size: file.size, type: file.type};\n return fileStat;\n}\n\nexport function sleep(ms: number): Promise {\n return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport * as fs from 'fs/promises';\n\nimport {ApiClient} from '../_api_client.js';\nimport {FileStat, Uploader} from '../_uploader.js';\nimport {\n DELAY_MULTIPLIER,\n INITIAL_RETRY_DELAY_MS,\n MAX_CHUNK_SIZE,\n MAX_RETRY_COUNT,\n X_GOOG_UPLOAD_STATUS_HEADER_FIELD,\n getBlobStat,\n sleep,\n uploadBlob,\n} from '../cross/_cross_uploader.js';\nimport {File, HttpResponse} from '../types.js';\n\nexport class NodeUploader implements Uploader {\n async stat(file: string | Blob): Promise {\n const fileStat: FileStat = {size: 0, type: undefined};\n if (typeof file === 'string') {\n const originalStat = await fs.stat(file);\n fileStat.size = originalStat.size;\n fileStat.type = this.inferMimeType(file);\n return fileStat;\n } else {\n return await getBlobStat(file);\n }\n }\n\n async upload(\n file: string | Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n if (typeof file === 'string') {\n return await this.uploadFileFromPath(file, uploadUrl, apiClient);\n } else {\n return uploadBlob(file, uploadUrl, apiClient);\n }\n }\n\n /**\n * Infers the MIME type of a file based on its extension.\n *\n * @param filePath The path to the file.\n * @returns The MIME type of the file, or undefined if it cannot be inferred.\n */\n private inferMimeType(filePath: string): string | undefined {\n // Get the file extension.\n const fileExtension = filePath.slice(filePath.lastIndexOf('.') + 1);\n\n // Create a map of file extensions to MIME types.\n const mimeTypes: {[key: string]: string} = {\n 'aac': 'audio/aac',\n 'abw': 'application/x-abiword',\n 'arc': 'application/x-freearc',\n 'avi': 'video/x-msvideo',\n 'azw': 'application/vnd.amazon.ebook',\n 'bin': 'application/octet-stream',\n 'bmp': 'image/bmp',\n 'bz': 'application/x-bzip',\n 'bz2': 'application/x-bzip2',\n 'csh': 'application/x-csh',\n 'css': 'text/css',\n 'csv': 'text/csv',\n 'doc': 'application/msword',\n 'docx':\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'eot': 'application/vnd.ms-fontobject',\n 'epub': 'application/epub+zip',\n 'gz': 'application/gzip',\n 'gif': 'image/gif',\n 'htm': 'text/html',\n 'html': 'text/html',\n 'ico': 'image/vnd.microsoft.icon',\n 'ics': 'text/calendar',\n 'jar': 'application/java-archive',\n 'jpeg': 'image/jpeg',\n 'jpg': 'image/jpeg',\n 'js': 'text/javascript',\n 'json': 'application/json',\n 'jsonld': 'application/ld+json',\n 'kml': 'application/vnd.google-earth.kml+xml',\n 'kmz': 'application/vnd.google-earth.kmz+xml',\n 'mjs': 'text/javascript',\n 'mp3': 'audio/mpeg',\n 'mp4': 'video/mp4',\n 'mpeg': 'video/mpeg',\n 'mpkg': 'application/vnd.apple.installer+xml',\n 'odt': 'application/vnd.oasis.opendocument.text',\n 'oga': 'audio/ogg',\n 'ogv': 'video/ogg',\n 'ogx': 'application/ogg',\n 'opus': 'audio/opus',\n 'otf': 'font/otf',\n 'png': 'image/png',\n 'pdf': 'application/pdf',\n 'php': 'application/x-httpd-php',\n 'ppt': 'application/vnd.ms-powerpoint',\n 'pptx':\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'rar': 'application/vnd.rar',\n 'rtf': 'application/rtf',\n 'sh': 'application/x-sh',\n 'svg': 'image/svg+xml',\n 'swf': 'application/x-shockwave-flash',\n 'tar': 'application/x-tar',\n 'tif': 'image/tiff',\n 'tiff': 'image/tiff',\n 'ts': 'video/mp2t',\n 'ttf': 'font/ttf',\n 'txt': 'text/plain',\n 'vsd': 'application/vnd.visio',\n 'wav': 'audio/wav',\n 'weba': 'audio/webm',\n 'webm': 'video/webm',\n 'webp': 'image/webp',\n 'woff': 'font/woff',\n 'woff2': 'font/woff2',\n 'xhtml': 'application/xhtml+xml',\n 'xls': 'application/vnd.ms-excel',\n 'xlsx':\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n 'xml': 'application/xml',\n 'xul': 'application/vnd.mozilla.xul+xml',\n 'zip': 'application/zip',\n '3gp': 'video/3gpp',\n '3g2': 'video/3gpp2',\n '7z': 'application/x-7z-compressed',\n };\n\n // Look up the MIME type based on the file extension.\n const mimeType = mimeTypes[fileExtension.toLowerCase()];\n\n // Return the MIME type.\n return mimeType;\n }\n\n private async uploadFileFromPath(\n file: string,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n let fileSize = 0;\n let offset = 0;\n let response: HttpResponse = new HttpResponse(new Response());\n let uploadCommand = 'upload';\n let fileHandle: fs.FileHandle | undefined;\n try {\n fileHandle = await fs.open(file, 'r');\n if (!fileHandle) {\n throw new Error(`Failed to open file`);\n }\n fileSize = (await fileHandle.stat()).size;\n while (offset < fileSize) {\n const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);\n if (offset + chunkSize >= fileSize) {\n uploadCommand += ', finalize';\n }\n const buffer = new Uint8Array(chunkSize);\n const {bytesRead: bytesRead} = await fileHandle.read(\n buffer,\n 0,\n chunkSize,\n offset,\n );\n\n if (bytesRead !== chunkSize) {\n throw new Error(\n `Failed to read ${chunkSize} bytes from file at offset ${\n offset\n }. bytes actually read: ${bytesRead}`,\n );\n }\n\n const chunk = new Blob([buffer]);\n let retryCount = 0;\n let currentDelayMs = INITIAL_RETRY_DELAY_MS;\n while (retryCount < MAX_RETRY_COUNT) {\n response = await apiClient.request({\n path: '',\n body: chunk,\n httpMethod: 'POST',\n httpOptions: {\n apiVersion: '',\n baseUrl: uploadUrl,\n headers: {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': String(offset),\n 'Content-Length': String(bytesRead),\n },\n },\n });\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) {\n break;\n }\n retryCount++;\n await sleep(currentDelayMs);\n currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;\n }\n offset += bytesRead;\n // The `x-goog-upload-status` header field can be `active`, `final` and\n //`cancelled` in resposne.\n if (\n response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'active'\n ) {\n break;\n }\n if (fileSize <= offset) {\n throw new Error(\n 'All content has been uploaded, but the upload status is not finalized.',\n );\n }\n }\n const responseJson = (await response?.json()) as Record<\n string,\n File | unknown\n >;\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'final') {\n throw new Error(\n 'Failed to upload file: Upload status is not finalized.',\n );\n }\n return responseJson['file'] as File;\n } finally {\n // Ensure the file handle is always closed\n if (fileHandle) {\n await fileHandle.close();\n }\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {GoogleAuthOptions} from 'google-auth-library';\n\nimport {ApiClient} from '../_api_client.js';\nimport {getBaseUrl} from '../_base_url.js';\nimport {Batches} from '../batches.js';\nimport {Caches} from '../caches.js';\nimport {Chats} from '../chats.js';\nimport {GoogleGenAIOptions} from '../client.js';\nimport {Files} from '../files.js';\nimport {Live} from '../live.js';\nimport {Models} from '../models.js';\nimport {NodeAuth} from '../node/_node_auth.js';\nimport {NodeDownloader} from '../node/_node_downloader.js';\nimport {NodeWebSocketFactory} from '../node/_node_websocket.js';\nimport {Operations} from '../operations.js';\nimport {Tokens} from '../tokens.js';\nimport {Tunings} from '../tunings.js';\n\nimport {NodeUploader} from './_node_uploader.js';\n\nconst LANGUAGE_LABEL_PREFIX = 'gl-node/';\n\n/**\n * The Google GenAI SDK.\n *\n * @remarks\n * Provides access to the GenAI features through either the {@link\n * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or\n * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI\n * API}.\n *\n * The {@link GoogleGenAIOptions.vertexai} value determines which of the API\n * services to use.\n *\n * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be\n * set. When using Vertex AI, both {@link GoogleGenAIOptions.project} and {@link\n * GoogleGenAIOptions.location} must be set, or a {@link\n * GoogleGenAIOptions.apiKey} must be set when using Express Mode.\n *\n * Explicitly passed in values in {@link GoogleGenAIOptions} will always take\n * precedence over environment variables. If both project/location and api_key\n * exist in the environment variables, the project/location will be used.\n *\n * @example\n * Initializing the SDK for using the Gemini API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n *\n * @example\n * Initializing the SDK for using the Vertex AI API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({\n * vertexai: true,\n * project: 'PROJECT_ID',\n * location: 'PROJECT_LOCATION'\n * });\n * ```\n *\n */\nexport class GoogleGenAI {\n protected readonly apiClient: ApiClient;\n private readonly apiKey?: string;\n public readonly vertexai: boolean;\n private readonly googleAuthOptions?: GoogleAuthOptions;\n private readonly project?: string;\n private readonly location?: string;\n private readonly apiVersion?: string;\n readonly models: Models;\n readonly live: Live;\n readonly batches: Batches;\n readonly chats: Chats;\n readonly caches: Caches;\n readonly files: Files;\n readonly operations: Operations;\n readonly authTokens: Tokens;\n readonly tunings: Tunings;\n\n constructor(options: GoogleGenAIOptions) {\n // Validate explicitly set initializer values.\n if ((options.project || options.location) && options.apiKey) {\n throw new Error(\n 'Project/location and API key are mutually exclusive in the client initializer.',\n );\n }\n\n this.vertexai =\n options.vertexai ?? getBooleanEnv('GOOGLE_GENAI_USE_VERTEXAI') ?? false;\n const envApiKey = getApiKeyFromEnv();\n const envProject = getEnv('GOOGLE_CLOUD_PROJECT');\n const envLocation = getEnv('GOOGLE_CLOUD_LOCATION');\n\n this.apiKey = options.apiKey ?? envApiKey;\n this.project = options.project ?? envProject;\n this.location = options.location ?? envLocation;\n\n // Handle when to use Vertex AI in express mode (api key)\n if (options.vertexai) {\n if (options.googleAuthOptions?.credentials) {\n // Explicit credentials take precedence over implicit api_key.\n console.debug(\n 'The user provided Google Cloud credentials will take precedence' +\n ' over the API key from the environment variable.',\n );\n this.apiKey = undefined;\n }\n // Explicit api_key and explicit project/location already handled above.\n if ((envProject || envLocation) && options.apiKey) {\n // Explicit api_key takes precedence over implicit project/location.\n console.debug(\n 'The user provided Vertex AI API key will take precedence over' +\n ' the project/location from the environment variables.',\n );\n this.project = undefined;\n this.location = undefined;\n } else if ((options.project || options.location) && envApiKey) {\n // Explicit project/location takes precedence over implicit api_key.\n console.debug(\n 'The user provided project/location will take precedence over' +\n ' the API key from the environment variables.',\n );\n this.apiKey = undefined;\n } else if ((envProject || envLocation) && envApiKey) {\n // Implicit project/location takes precedence over implicit api_key.\n console.debug(\n 'The project/location from the environment variables will take' +\n ' precedence over the API key from the environment variables.',\n );\n this.apiKey = undefined;\n }\n }\n\n const baseUrl = getBaseUrl(\n options.httpOptions,\n options.vertexai,\n getEnv('GOOGLE_VERTEX_BASE_URL'),\n getEnv('GOOGLE_GEMINI_BASE_URL'),\n );\n if (baseUrl) {\n if (options.httpOptions) {\n options.httpOptions.baseUrl = baseUrl;\n } else {\n options.httpOptions = {baseUrl: baseUrl};\n }\n }\n\n this.apiVersion = options.apiVersion;\n const auth = new NodeAuth({\n apiKey: this.apiKey,\n googleAuthOptions: options.googleAuthOptions,\n });\n this.apiClient = new ApiClient({\n auth: auth,\n project: this.project,\n location: this.location,\n apiVersion: this.apiVersion,\n apiKey: this.apiKey,\n vertexai: this.vertexai,\n httpOptions: options.httpOptions,\n userAgentExtra: LANGUAGE_LABEL_PREFIX + process.version,\n uploader: new NodeUploader(),\n downloader: new NodeDownloader(),\n });\n this.models = new Models(this.apiClient);\n this.live = new Live(this.apiClient, auth, new NodeWebSocketFactory());\n this.batches = new Batches(this.apiClient);\n this.chats = new Chats(this.models, this.apiClient);\n this.caches = new Caches(this.apiClient);\n this.files = new Files(this.apiClient);\n this.operations = new Operations(this.apiClient);\n this.authTokens = new Tokens(this.apiClient);\n this.tunings = new Tunings(this.apiClient);\n }\n}\n\nfunction getEnv(env: string): string | undefined {\n return process?.env?.[env]?.trim() ?? undefined;\n}\n\nfunction getBooleanEnv(env: string): boolean {\n return stringToBoolean(getEnv(env));\n}\n\nfunction stringToBoolean(str?: string): boolean {\n if (str === undefined) {\n return false;\n }\n return str.toLowerCase() === 'true';\n}\n\nfunction getApiKeyFromEnv(): string | undefined {\n const envGoogleApiKey = getEnv('GOOGLE_API_KEY');\n const envGeminiApiKey = getEnv('GEMINI_API_KEY');\n if (envGoogleApiKey && envGeminiApiKey) {\n console.warn(\n 'Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY.',\n );\n }\n return envGoogleApiKey || envGeminiApiKey;\n}\n"],"names":["tBytes","types.Type","baseTransformers.tBytes","videoMetadataToMldev","common.getValueByPath","common.setValueByPath","blobToMldev","fileDataToMldev","partToMldev","contentToMldev","schemaToMldev","safetySettingToMldev","functionDeclarationToMldev","intervalToMldev","googleSearchToMldev","dynamicRetrievalConfigToMldev","googleSearchRetrievalToMldev","urlContextToMldev","toolComputerUseToMldev","toolToMldev","functionCallingConfigToMldev","latLngToMldev","retrievalConfigToMldev","toolConfigToMldev","prebuiltVoiceConfigToMldev","voiceConfigToMldev","speakerVoiceConfigToMldev","multiSpeakerVoiceConfigToMldev","speechConfigToMldev","thinkingConfigToMldev","generateContentConfigToMldev","t.tContent","t.tSchema","t.tTools","t.tTool","t.tCachedContentName","t.tSpeechConfig","t.tModel","t.tContents","t.tBatchJobSource","t.tBatchJobName","t.tBatchJobDestination","videoMetadataFromMldev","blobFromMldev","fileDataFromMldev","partFromMldev","contentFromMldev","citationMetadataFromMldev","urlMetadataFromMldev","urlContextMetadataFromMldev","candidateFromMldev","generateContentResponseFromMldev","t.tJobState","converters.createBatchJobParametersToMldev","common.formatMap","converters.batchJobFromMldev","converters.createBatchJobParametersToVertex","converters.batchJobFromVertex","converters.getBatchJobParametersToVertex","converters.getBatchJobParametersToMldev","converters.cancelBatchJobParametersToVertex","converters.cancelBatchJobParametersToMldev","converters.listBatchJobsParametersToVertex","converters.listBatchJobsResponseFromVertex","types.ListBatchJobsResponse","converters.listBatchJobsParametersToMldev","converters.listBatchJobsResponseFromMldev","converters.deleteBatchJobParametersToVertex","converters.deleteResourceJobFromVertex","converters.deleteBatchJobParametersToMldev","converters.deleteResourceJobFromMldev","t.tCachesModel","videoMetadataToVertex","blobToVertex","fileDataToVertex","partToVertex","contentToVertex","functionDeclarationToVertex","intervalToVertex","googleSearchToVertex","dynamicRetrievalConfigToVertex","googleSearchRetrievalToVertex","enterpriseWebSearchToVertex","apiKeyConfigToVertex","authConfigToVertex","googleMapsToVertex","urlContextToVertex","toolComputerUseToVertex","toolToVertex","functionCallingConfigToVertex","latLngToVertex","retrievalConfigToVertex","toolConfigToVertex","converters.createCachedContentParametersToVertex","converters.cachedContentFromVertex","converters.createCachedContentParametersToMldev","converters.cachedContentFromMldev","converters.getCachedContentParametersToVertex","converters.getCachedContentParametersToMldev","converters.deleteCachedContentParametersToVertex","converters.deleteCachedContentResponseFromVertex","types.DeleteCachedContentResponse","converters.deleteCachedContentParametersToMldev","converters.deleteCachedContentResponseFromMldev","converters.updateCachedContentParametersToVertex","converters.updateCachedContentParametersToMldev","converters.listCachedContentsParametersToVertex","converters.listCachedContentsResponseFromVertex","types.ListCachedContentsResponse","converters.listCachedContentsParametersToMldev","converters.listCachedContentsResponseFromMldev","t.tFileName","converters.fileFromMldev","converters.listFilesParametersToMldev","converters.listFilesResponseFromMldev","types.ListFilesResponse","converters.createFileParametersToMldev","converters.createFileResponseFromMldev","types.CreateFileResponse","converters.getFileParametersToMldev","converters.deleteFileParametersToMldev","converters.deleteFileResponseFromMldev","types.DeleteFileResponse","sessionResumptionConfigToMldev","audioTranscriptionConfigToMldev","automaticActivityDetectionToMldev","realtimeInputConfigToMldev","slidingWindowToMldev","contextWindowCompressionConfigToMldev","proactivityConfigToMldev","liveConnectConfigToMldev","t.tLiveSpeechConfig","t.tBlobs","t.tAudioBlob","t.tImageBlob","prebuiltVoiceConfigToVertex","voiceConfigToVertex","speechConfigToVertex","videoMetadataFromVertex","blobFromVertex","fileDataFromVertex","partFromVertex","contentFromVertex","t.tContentsForEmbed","t.tModelsUrl","t.tBytes","t.tExtractModels","handleWebSocketMessage","types.LiveMusicServerMessage","converters.liveMusicServerMessageFromMldev","mapToHeaders","headersToMap","converters.liveMusicClientSetupToMldev","converters.liveMusicClientMessageToMldev","converters.liveMusicSetWeightedPromptsParametersToMldev","converters.liveMusicClientContentToMldev","converters.liveMusicSetConfigParametersToMldev","types.LiveMusicPlaybackControl","types.LiveServerMessage","converters.liveServerMessageFromVertex","converters.liveServerMessageFromMldev","types.Modality","converters.liveConnectParametersToVertex","converters.liveConnectParametersToMldev","converters.liveSendRealtimeInputParametersToVertex","converters.liveSendRealtimeInputParametersToMldev","types.GenerateContentResponse","converters.generateContentParametersToVertex","converters.generateContentResponseFromVertex","converters.generateContentParametersToMldev","converters.generateContentResponseFromMldev","converters.embedContentParametersToVertex","converters.embedContentResponseFromVertex","types.EmbedContentResponse","converters.embedContentParametersToMldev","converters.embedContentResponseFromMldev","converters.generateImagesParametersToVertex","converters.generateImagesResponseFromVertex","types.GenerateImagesResponse","converters.generateImagesParametersToMldev","converters.generateImagesResponseFromMldev","converters.editImageParametersInternalToVertex","converters.editImageResponseFromVertex","types.EditImageResponse","converters.upscaleImageAPIParametersInternalToVertex","converters.upscaleImageResponseFromVertex","types.UpscaleImageResponse","converters.recontextImageParametersToVertex","converters.recontextImageResponseFromVertex","types.RecontextImageResponse","converters.segmentImageParametersToVertex","converters.segmentImageResponseFromVertex","types.SegmentImageResponse","converters.getModelParametersToVertex","converters.modelFromVertex","converters.getModelParametersToMldev","converters.modelFromMldev","converters.listModelsParametersToVertex","converters.listModelsResponseFromVertex","types.ListModelsResponse","converters.listModelsParametersToMldev","converters.listModelsResponseFromMldev","converters.updateModelParametersToVertex","converters.updateModelParametersToMldev","converters.deleteModelParametersToVertex","converters.deleteModelResponseFromVertex","types.DeleteModelResponse","converters.deleteModelParametersToMldev","converters.deleteModelResponseFromMldev","converters.countTokensParametersToVertex","converters.countTokensResponseFromVertex","types.CountTokensResponse","converters.countTokensParametersToMldev","converters.countTokensResponseFromMldev","converters.computeTokensParametersToVertex","converters.computeTokensResponseFromVertex","types.ComputeTokensResponse","converters.generateVideosParametersToVertex","converters.generateVideosOperationFromVertex","types.GenerateVideosOperation","converters.generateVideosParametersToMldev","converters.generateVideosOperationFromMldev","converters.getOperationParametersToVertex","converters.getOperationParametersToMldev","converters.fetchPredictOperationParametersToVertex","converters.createAuthTokenParametersToMldev","converters.authTokenFromMldev","t.tTuningJobStatus","types.JobState","converters.getTuningJobParametersToVertex","converters.tuningJobFromVertex","converters.getTuningJobParametersToMldev","converters.tuningJobFromMldev","converters.listTuningJobsParametersToVertex","converters.listTuningJobsResponseFromVertex","types.ListTuningJobsResponse","converters.listTuningJobsParametersToMldev","converters.listTuningJobsResponseFromMldev","converters.createTuningJobParametersPrivateToVertex","converters.createTuningJobParametersPrivateToMldev","converters.tuningOperationFromMldev"],"mappings":";;;;;;AAAA;;;;AAIG;AAIH,IAAI,qBAAqB,GAAuB,SAAS;AACzD,IAAI,qBAAqB,GAAuB,SAAS;AAUzD;;;;;;;;;;;;;;;;;;;AAmBG;AACG,SAAU,kBAAkB,CAAC,aAAgC,EAAA;AACjE,IAAA,qBAAqB,GAAG,aAAa,CAAC,SAAS;AAC/C,IAAA,qBAAqB,GAAG,aAAa,CAAC,SAAS;AACjD;AAEA;;AAEG;SACa,kBAAkB,GAAA;IAChC,OAAO;AACL,QAAA,SAAS,EAAE,qBAAqB;AAChC,QAAA,SAAS,EAAE,qBAAqB;KACjC;AACH;AAEA;;;;;AAKG;AACG,SAAU,UAAU,CACxB,WAAoC,EACpC,QAA6B,EAC7B,oBAAwC,EACxC,oBAAwC,EAAA;;IAExC,IAAI,EAAC,WAAW,KAAX,IAAA,IAAA,WAAW,uBAAX,WAAW,CAAE,OAAO,CAAA,EAAE;AACzB,QAAA,MAAM,eAAe,GAAG,kBAAkB,EAAE;AAC5C,QAAA,IAAI,QAAQ,EAAE;AACZ,YAAA,OAAO,MAAA,eAAe,CAAC,SAAS,MAAA,IAAA,IAAA,EAAA,KAAA,MAAA,GAAA,EAAA,GAAI,oBAAoB;AACzD;AAAM,aAAA;AACL,YAAA,OAAO,MAAA,eAAe,CAAC,SAAS,MAAA,IAAA,IAAA,EAAA,KAAA,MAAA,GAAA,EAAA,GAAI,oBAAoB;AACzD;AACF;IAED,OAAO,WAAW,CAAC,OAAO;AAC5B;;AC5EA;;;;AAIG;MAEU,UAAU,CAAA;AAAG;AAEV,SAAA,SAAS,CACvB,cAAsB,EACtB,QAAiC,EAAA;;IAGjC,MAAM,KAAK,GAAG,cAAc;;IAG5B,OAAO,cAAc,CAAC,OAAO,CA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AAO,MAAA,CAAA,EAAA,GAAA,CAAA,EAAA,GAAA,OAAO,KAAP,IAAA,IAAA,OAAO,uBAAP,OAAO,CAAE,GAAG,MAAA,IAAA,IAAA,EAAA,KAAA,MAAA,GAAA,MAAA,GAAA,EAAA,CAAG,GAAG,CAAC,MAAA,IAAA,IAAA,EAAA,KAAA,MAAA,GAAA,MAAA,GAAA,EAAA,CAAE,IAAI,EAAE,MAAA,IAAA,IAAA,EAAA,KAAA,MAAA,GAAA,EAAA,GAAI,SAAS;AACjD;AAEA,SAAS,aAAa,CAAC,GAAW,EAAA;AAChC,IAAA,OAAO,eAAe,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACrC;AAEA,SAAS,eAAe,CAAC,GAAY,EAAA;IACnC,IAAI,GAAG,KAAK,SAAS,EAAE;AACrB,QAAA,OAAO,KAAK;AACb;AACD,IAAA,OAAO,GAAG,CAAC,WAAW,EAAE,KAAK,MAAM;AACrC;AAEA,SAAS,gBAAgB,GAAA;AACvB,IAAA,MAAM,eAAe,GAAG,MAAM,CAAC,gBAAgB,CAAC;AAChD,IAAA,MAAM,eAAe,GAAG,MAAM,CAAC,gBAAgB,CAAC;IAChD,IAAI,eAAe,IAAI,eAAe,EAAE;AACtC,QAAA,OAAO,CAAC,IAAI,CACV,uEAAuE,CACxE;AACF;IACD,OAAO,eAAe,IAAI,eAAe;AAC3C;;;;"} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/node/node.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/node/node.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..287e12963bf2d7566d2b789b1429eb2cea813e36 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/node/node.d.ts @@ -0,0 +1,7713 @@ +// @ts-ignore +import type { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { GoogleAuthOptions } from 'google-auth-library'; + +/** Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface ActivityEnd { +} + +/** The different ways of handling user activity. */ +export declare enum ActivityHandling { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ACTIVITY_HANDLING_UNSPECIFIED = "ACTIVITY_HANDLING_UNSPECIFIED", + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + START_OF_ACTIVITY_INTERRUPTS = "START_OF_ACTIVITY_INTERRUPTS", + /** + * The model's response will not be interrupted. + */ + NO_INTERRUPTION = "NO_INTERRUPTION" +} + +/** Marks the start of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface ActivityStart { +} + +/** Optional. Adapter size for tuning. */ +export declare enum AdapterSize { + /** + * Adapter size is unspecified. + */ + ADAPTER_SIZE_UNSPECIFIED = "ADAPTER_SIZE_UNSPECIFIED", + /** + * Adapter size 1. + */ + ADAPTER_SIZE_ONE = "ADAPTER_SIZE_ONE", + /** + * Adapter size 2. + */ + ADAPTER_SIZE_TWO = "ADAPTER_SIZE_TWO", + /** + * Adapter size 4. + */ + ADAPTER_SIZE_FOUR = "ADAPTER_SIZE_FOUR", + /** + * Adapter size 8. + */ + ADAPTER_SIZE_EIGHT = "ADAPTER_SIZE_EIGHT", + /** + * Adapter size 16. + */ + ADAPTER_SIZE_SIXTEEN = "ADAPTER_SIZE_SIXTEEN", + /** + * Adapter size 32. + */ + ADAPTER_SIZE_THIRTY_TWO = "ADAPTER_SIZE_THIRTY_TWO" +} + +/** The generic reusable api auth config. Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto) instead. */ +export declare interface ApiAuth { + /** The API secret. */ + apiKeyConfig?: ApiAuthApiKeyConfig; +} + +/** The API secret. */ +export declare interface ApiAuthApiKeyConfig { + /** Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version} */ + apiKeySecretVersion?: string; + /** The API key string. Either this or `api_key_secret_version` must be set. */ + apiKeyString?: string; +} + +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +declare class ApiClient { + readonly clientOptions: ApiClientInitOptions; + constructor(opts: ApiClientInitOptions); + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + private baseUrlFromProjectLocation; + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + private normalizeAuthParameters; + isVertexAI(): boolean; + getProject(): string | undefined; + getLocation(): string | undefined; + getApiVersion(): string; + getBaseUrl(): string; + getRequestUrl(): string; + getHeaders(): Record; + private getRequestUrlInternal; + getBaseResourcePath(): string; + getApiKey(): string | undefined; + getWebsocketBaseUrl(): string; + setBaseUrl(url: string): void; + private constructUrl; + private shouldPrependVertexProjectPath; + request(request: HttpRequest): Promise; + private patchHttpOptions; + requestStream(request: HttpRequest): Promise>; + private includeExtraHttpOptionsToRequestInit; + private unaryApiCall; + private streamApiCall; + processStreamResponse(response: Response): AsyncGenerator; + private apiCall; + getDefaultHeaders(): Record; + private getHeadersInternal; + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + uploadFile(file: string | Blob, config?: UploadFileConfig): Promise; + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + downloadFile(params: DownloadFileParameters): Promise; + private fetchUploadUrl; +} + +/** + * Options for initializing the ApiClient. The ApiClient uses the parameters + * for authentication purposes as well as to infer if SDK should send the + * request to Vertex AI or Gemini API. + */ +declare interface ApiClientInitOptions { + /** + * The object used for adding authentication headers to API requests. + */ + auth: Auth; + /** + * The uploader to use for uploading files. This field is required for + * creating a client, will be set through the Node_client or Web_client. + */ + uploader: Uploader; + /** + * Optional. The downloader to use for downloading files. This field is + * required for creating a client, will be set through the Node_client or + * Web_client. + */ + downloader: Downloader; + /** + * Optional. The Google Cloud project ID for Vertex AI users. + * It is not the numeric project name. + * If not provided, SDK will try to resolve it from runtime environment. + */ + project?: string; + /** + * Optional. The Google Cloud project location for Vertex AI users. + * If not provided, SDK will try to resolve it from runtime environment. + */ + location?: string; + /** + * The API Key. This is required for Gemini API users. + */ + apiKey?: string; + /** + * Optional. Set to true if you intend to call Vertex AI endpoints. + * If unset, default SDK behavior is to call Gemini API. + */ + vertexai?: boolean; + /** + * Optional. The API version for the endpoint. + * If unset, SDK will choose a default api version. + */ + apiVersion?: string; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; + /** + * Optional. An extra string to append at the end of the User-Agent header. + * + * This can be used to e.g specify the runtime and its version. + */ + userAgentExtra?: string; +} + +/** + * API errors raised by the GenAI API. + */ +export declare class ApiError extends Error { + /** HTTP status code */ + status: number; + constructor(options: ApiErrorInfo); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Details for errors from calling the API. + */ +export declare interface ApiErrorInfo { + /** The error message. */ + message: string; + /** The HTTP status code. */ + status: number; +} + +/** Config for authentication with API key. */ +export declare interface ApiKeyConfig { + /** The API key to be used in the request directly. */ + apiKeyString?: string; +} + +/** The API spec that the external API implements. */ +export declare enum ApiSpec { + /** + * Unspecified API spec. This value should not be used. + */ + API_SPEC_UNSPECIFIED = "API_SPEC_UNSPECIFIED", + /** + * Simple search API spec. + */ + SIMPLE_SEARCH = "SIMPLE_SEARCH", + /** + * Elastic search API spec. + */ + ELASTIC_SEARCH = "ELASTIC_SEARCH" +} + +/** Representation of an audio chunk. */ +export declare interface AudioChunk { + /** Raw bytes of audio data. + * @remarks Encoded as base64 string. */ + data?: string; + /** MIME type of the audio chunk. */ + mimeType?: string; + /** Prompts and config used for generating this audio chunk. */ + sourceMetadata?: LiveMusicSourceMetadata; +} + +/** The audio transcription configuration in Setup. */ +export declare interface AudioTranscriptionConfig { +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * The Auth interface is used to authenticate with the API service. + */ +declare interface Auth { + /** + * Sets the headers needed to authenticate with the API service. + * + * @param headers - The Headers object that will be updated with the authentication headers. + */ + addAuthHeaders(headers: Headers): Promise; +} + +/** Auth configuration to run the extension. */ +export declare interface AuthConfig { + /** Config for API key auth. */ + apiKeyConfig?: ApiKeyConfig; + /** Type of auth scheme. */ + authType?: AuthType; + /** Config for Google Service Account auth. */ + googleServiceAccountConfig?: AuthConfigGoogleServiceAccountConfig; + /** Config for HTTP Basic auth. */ + httpBasicAuthConfig?: AuthConfigHttpBasicAuthConfig; + /** Config for user oauth. */ + oauthConfig?: AuthConfigOauthConfig; + /** Config for user OIDC auth. */ + oidcConfig?: AuthConfigOidcConfig; +} + +/** Config for Google Service Account Authentication. */ +export declare interface AuthConfigGoogleServiceAccountConfig { + /** Optional. The service account that the extension execution service runs as. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified service account. - If not specified, the Vertex AI Extension Service Agent will be used to execute the Extension. */ + serviceAccount?: string; +} + +/** Config for HTTP Basic Authentication. */ +export declare interface AuthConfigHttpBasicAuthConfig { + /** Required. The name of the SecretManager secret version resource storing the base64 encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource. */ + credentialSecret?: string; +} + +/** Config for user oauth. */ +export declare interface AuthConfigOauthConfig { + /** Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */ + accessToken?: string; + /** The service account used to generate access tokens for executing the Extension. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the provided service account. */ + serviceAccount?: string; +} + +/** Config for user OIDC auth. */ +export declare interface AuthConfigOidcConfig { + /** OpenID Connect formatted ID token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */ + idToken?: string; + /** The service account used to generate an OpenID Connect (OIDC)-compatible JWT token signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc). - The audience for the token will be set to the URL in the server url defined in the OpenApi spec. - If the service account is provided, the service account should grant `iam.serviceAccounts.getOpenIdToken` permission to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents). */ + serviceAccount?: string; +} + +/** Config for auth_tokens.create parameters. */ +export declare interface AuthToken { + /** The name of the auth token. */ + name?: string; +} + +/** Type of auth scheme. */ +export declare enum AuthType { + AUTH_TYPE_UNSPECIFIED = "AUTH_TYPE_UNSPECIFIED", + /** + * No Auth. + */ + NO_AUTH = "NO_AUTH", + /** + * API Key Auth. + */ + API_KEY_AUTH = "API_KEY_AUTH", + /** + * HTTP Basic Auth. + */ + HTTP_BASIC_AUTH = "HTTP_BASIC_AUTH", + /** + * Google Service Account Auth. + */ + GOOGLE_SERVICE_ACCOUNT_AUTH = "GOOGLE_SERVICE_ACCOUNT_AUTH", + /** + * OAuth auth. + */ + OAUTH = "OAUTH", + /** + * OpenID Connect (OIDC) Auth. + */ + OIDC_AUTH = "OIDC_AUTH" +} + +/** Configures automatic detection of activity. */ +export declare interface AutomaticActivityDetection { + /** If enabled, detected voice and text input count as activity. If disabled, the client must send activity signals. */ + disabled?: boolean; + /** Determines how likely speech is to be detected. */ + startOfSpeechSensitivity?: StartSensitivity; + /** Determines how likely detected speech is ended. */ + endOfSpeechSensitivity?: EndSensitivity; + /** The required duration of detected speech before start-of-speech is committed. The lower this value the more sensitive the start-of-speech detection is and the shorter speech can be recognized. However, this also increases the probability of false positives. */ + prefixPaddingMs?: number; + /** The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency. */ + silenceDurationMs?: number; +} + +/** The configuration for automatic function calling. */ +export declare interface AutomaticFunctionCallingConfig { + /** Whether to disable automatic function calling. + If not set or set to False, will enable automatic function calling. + If set to True, will disable automatic function calling. + */ + disable?: boolean; + /** If automatic function calling is enabled, + maximum number of remote calls for automatic function calling. + This number should be a positive integer. + If not set, SDK will set maximum number of remote calls to 10. + */ + maximumRemoteCalls?: number; + /** If automatic function calling is enabled, + whether to ignore call history to the response. + If not set, SDK will set ignore_call_history to false, + and will append the call history to + GenerateContentResponse.automatic_function_calling_history. + */ + ignoreCallHistory?: boolean; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +declare class BaseModule { +} + +/** + * Parameters for setting the base URLs for the Gemini API and Vertex AI API. + */ +export declare interface BaseUrlParameters { + geminiUrl?: string; + vertexUrl?: string; +} + +export declare class Batches extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + create: (params: types.CreateBatchJobParameters) => Promise; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + list: (params?: types.ListBatchJobsParameters) => Promise>; + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + private createInternal; + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + get(params: types.GetBatchJobParameters): Promise; + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + cancel(params: types.CancelBatchJobParameters): Promise; + private listInternal; + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + delete(params: types.DeleteBatchJobParameters): Promise; +} + +/** Config for batches.create return value. */ +export declare interface BatchJob { + /** The resource name of the BatchJob. Output only.". + */ + name?: string; + /** The display name of the BatchJob. + */ + displayName?: string; + /** The state of the BatchJob. + */ + state?: JobState; + /** Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED. */ + error?: JobError; + /** The time when the BatchJob was created. + */ + createTime?: string; + /** Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state. */ + startTime?: string; + /** The time when the BatchJob was completed. + */ + endTime?: string; + /** The time when the BatchJob was last updated. + */ + updateTime?: string; + /** The name of the model that produces the predictions via the BatchJob. + */ + model?: string; + /** Configuration for the input data. + */ + src?: BatchJobSource; + /** Configuration for the output data. + */ + dest?: BatchJobDestination; +} + +/** Config for `des` parameter. */ +export declare interface BatchJobDestination { + /** Storage format of the output files. Must be one of: + 'jsonl', 'bigquery'. + */ + format?: string; + /** The Google Cloud Storage URI to the output file. + */ + gcsUri?: string; + /** The BigQuery URI to the output table. + */ + bigqueryUri?: string; + /** The Gemini Developer API's file resource name of the output data + (e.g. "files/12345"). The file will be a JSONL file with a single response + per line. The responses will be GenerateContentResponse messages formatted + as JSON. The responses will be written in the same order as the input + requests. + */ + fileName?: string; + /** The responses to the requests in the batch. Returned when the batch was + built using inlined requests. The responses will be in the same order as + the input requests. + */ + inlinedResponses?: InlinedResponse[]; +} + +export declare type BatchJobDestinationUnion = BatchJobDestination | string; + +/** Config for `src` parameter. */ +export declare interface BatchJobSource { + /** Storage format of the input files. Must be one of: + 'jsonl', 'bigquery'. + */ + format?: string; + /** The Google Cloud Storage URIs to input files. + */ + gcsUri?: string[]; + /** The BigQuery URI to input table. + */ + bigqueryUri?: string; + /** The Gemini Developer API's file resource name of the input data + (e.g. "files/12345"). + */ + fileName?: string; + /** The Gemini Developer API's inlined input data to run batch job. + */ + inlinedRequests?: InlinedRequest[]; +} + +export declare type BatchJobSourceUnion = BatchJobSource | InlinedRequest[] | string; + +/** Defines the function behavior. Defaults to `BLOCKING`. */ +export declare enum Behavior { + /** + * This value is unused. + */ + UNSPECIFIED = "UNSPECIFIED", + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + BLOCKING = "BLOCKING", + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + NON_BLOCKING = "NON_BLOCKING" +} + +/** Content blob. */ +declare interface Blob_2 { + /** Optional. Display name of the blob. Used to provide a label or filename to distinguish blobs. This field is not currently used in the Gemini GenerateContent calls. */ + displayName?: string; + /** Required. Raw bytes. + * @remarks Encoded as base64 string. */ + data?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} +export { Blob_2 as Blob } + +export declare type BlobImageUnion = Blob_2; + +/** Output only. Blocked reason. */ +export declare enum BlockedReason { + /** + * Unspecified blocked reason. + */ + BLOCKED_REASON_UNSPECIFIED = "BLOCKED_REASON_UNSPECIFIED", + /** + * Candidates blocked due to safety. + */ + SAFETY = "SAFETY", + /** + * Candidates blocked due to other reason. + */ + OTHER = "OTHER", + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BLOCKLIST = "BLOCKLIST", + /** + * Candidates blocked due to prohibited content. + */ + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + /** + * Candidates blocked due to unsafe image generation content. + */ + IMAGE_SAFETY = "IMAGE_SAFETY" +} + +/** A resource used in LLM queries for users to explicitly specify what to cache. */ +export declare interface CachedContent { + /** The server-generated resource name of the cached content. */ + name?: string; + /** The user-generated meaningful display name of the cached content. */ + displayName?: string; + /** The name of the publisher model to use for cached content. */ + model?: string; + /** Creation time of the cache entry. */ + createTime?: string; + /** When the cache entry was last updated in UTC time. */ + updateTime?: string; + /** Expiration time of the cached content. */ + expireTime?: string; + /** Metadata on the usage of the cached content. */ + usageMetadata?: CachedContentUsageMetadata; +} + +/** Metadata on the usage of the cached content. */ +export declare interface CachedContentUsageMetadata { + /** Duration of audio in seconds. */ + audioDurationSeconds?: number; + /** Number of images. */ + imageCount?: number; + /** Number of text characters. */ + textCount?: number; + /** Total number of tokens that the cached content consumes. */ + totalTokenCount?: number; + /** Duration of video in seconds. */ + videoDurationSeconds?: number; +} + +export declare class Caches extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + list: (params?: types.ListCachedContentsParameters) => Promise>; + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + create(params: types.CreateCachedContentParameters): Promise; + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + get(params: types.GetCachedContentParameters): Promise; + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + delete(params: types.DeleteCachedContentParameters): Promise; + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + update(params: types.UpdateCachedContentParameters): Promise; + private listInternal; +} + +/** + * CallableTool is an invokable tool that can be executed with external + * application (e.g., via Model Context Protocol) or local functions with + * function calling. + */ +export declare interface CallableTool { + /** + * Returns tool that can be called by Gemini. + */ + tool(): Promise; + /** + * Executes the callable tool with the given function call arguments and + * returns the response parts from the tool execution. + */ + callTool(functionCalls: FunctionCall[]): Promise; +} + +/** + * CallableToolConfig is the configuration for a callable tool. + */ +export declare interface CallableToolConfig { + /** + * Specifies the model's behavior after invoking this tool. + */ + behavior?: Behavior; + /** + * Timeout for remote calls in milliseconds. Note this timeout applies only to + * tool remote calls, and not making HTTP requests to the API. */ + timeout?: number; +} + +/** Optional parameters. */ +export declare interface CancelBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.cancel parameters. */ +export declare interface CancelBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: CancelBatchJobConfig; +} + +/** A response candidate generated from the model. */ +export declare interface Candidate { + /** Contains the multi-part content of the response. + */ + content?: Content; + /** Source attribution of the generated content. + */ + citationMetadata?: CitationMetadata; + /** Describes the reason the model stopped generating tokens. + */ + finishMessage?: string; + /** Number of tokens for this candidate. + */ + tokenCount?: number; + /** The reason why the model stopped generating tokens. + If empty, the model has not stopped generating the tokens. + */ + finishReason?: FinishReason; + /** Metadata related to url context retrieval tool. */ + urlContextMetadata?: UrlContextMetadata; + /** Output only. Average log probability score of the candidate. */ + avgLogprobs?: number; + /** Output only. Metadata specifies sources used to ground generated content. */ + groundingMetadata?: GroundingMetadata; + /** Output only. Index of the candidate. */ + index?: number; + /** Output only. Log-likelihood scores for the response tokens and top tokens */ + logprobsResult?: LogprobsResult; + /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */ + safetyRatings?: SafetyRating[]; +} + +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +export declare class Chat { + private readonly apiClient; + private readonly modelsModule; + private readonly model; + private readonly config; + private history; + private sendPromise; + constructor(apiClient: ApiClient, modelsModule: Models, model: string, config?: types.GenerateContentConfig, history?: types.Content[]); + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + sendMessage(params: types.SendMessageParameters): Promise; + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + sendMessageStream(params: types.SendMessageParameters): Promise>; + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated?: boolean): types.Content[]; + private processStreamResponse; + private recordHistory; +} + +/** + * A utility class to create a chat session. + */ +export declare class Chats { + private readonly modelsModule; + private readonly apiClient; + constructor(modelsModule: Models, apiClient: ApiClient); + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params: types.CreateChatParameters): Chat; +} + +/** Describes the machine learning model version checkpoint. */ +export declare interface Checkpoint { + /** The ID of the checkpoint. + */ + checkpointId?: string; + /** The epoch of the checkpoint. + */ + epoch?: string; + /** The step of the checkpoint. + */ + step?: string; +} + +/** Source attributions for content. */ +export declare interface Citation { + /** Output only. End index into the content. */ + endIndex?: number; + /** Output only. License of the attribution. */ + license?: string; + /** Output only. Publication date of the attribution. */ + publicationDate?: GoogleTypeDate; + /** Output only. Start index into the content. */ + startIndex?: number; + /** Output only. Title of the attribution. */ + title?: string; + /** Output only. Url reference of the attribution. */ + uri?: string; +} + +/** Citation information when the model quotes another source. */ +export declare interface CitationMetadata { + /** Contains citation information when the model directly quotes, at + length, from another source. Can include traditional websites and code + repositories. + */ + citations?: Citation[]; +} + +/** Result of executing the [ExecutableCode]. Only generated when using the [CodeExecution] tool, and always follows a `part` containing the [ExecutableCode]. */ +export declare interface CodeExecutionResult { + /** Required. Outcome of the code execution. */ + outcome?: Outcome; + /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */ + output?: string; +} + +/** Optional parameters for computing tokens. */ +export declare interface ComputeTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for computing tokens. */ +export declare interface ComputeTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Optional parameters for the request. + */ + config?: ComputeTokensConfig; +} + +/** Response for computing tokens. */ +export declare class ComputeTokensResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */ + tokensInfo?: TokensInfo[]; +} + +/** Contains the multi-part content of a message. */ +export declare interface Content { + /** List of parts that constitute a single message. Each part may have + a different IANA MIME type. */ + parts?: Part[]; + /** Optional. The producer of the content. Must be either 'user' or + 'model'. Useful to set for multi-turn conversations, otherwise can be + empty. If role is not specified, SDK will determine the role. */ + role?: string; +} + +/** The embedding generated from an input content. */ +export declare interface ContentEmbedding { + /** A list of floats representing an embedding. + */ + values?: number[]; + /** Vertex API only. Statistics of the input text associated with this + embedding. + */ + statistics?: ContentEmbeddingStatistics; +} + +/** Statistics of the input text associated with the result of content embedding. */ +export declare interface ContentEmbeddingStatistics { + /** Vertex API only. If the input text was truncated due to having + a length longer than the allowed maximum input. + */ + truncated?: boolean; + /** Vertex API only. Number of tokens of the input text. + */ + tokenCount?: number; +} + +export declare type ContentListUnion = Content | Content[] | PartUnion | PartUnion[]; + +export declare type ContentUnion = Content | PartUnion[] | PartUnion; + +/** Enables context window compression -- mechanism managing model context window so it does not exceed given length. */ +export declare interface ContextWindowCompressionConfig { + /** Number of tokens (before running turn) that triggers context window compression mechanism. */ + triggerTokens?: string; + /** Sliding window compression mechanism. */ + slidingWindow?: SlidingWindow; +} + +/** Configuration for a Control reference image. */ +export declare interface ControlReferenceConfig { + /** The type of control reference image to use. */ + controlType?: ControlReferenceType; + /** Defaults to False. When set to True, the control image will be + computed by the model based on the control type. When set to False, + the control image must be provided by the user. */ + enableControlImageComputation?: boolean; +} + +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +export declare class ControlReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the control reference image. */ + config?: ControlReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the control type of a control reference image. */ +export declare enum ControlReferenceType { + CONTROL_TYPE_DEFAULT = "CONTROL_TYPE_DEFAULT", + CONTROL_TYPE_CANNY = "CONTROL_TYPE_CANNY", + CONTROL_TYPE_SCRIBBLE = "CONTROL_TYPE_SCRIBBLE", + CONTROL_TYPE_FACE_MESH = "CONTROL_TYPE_FACE_MESH" +} + +/** Config for the count_tokens method. */ +export declare interface CountTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Instructions for the model to steer it toward better performance. + */ + systemInstruction?: ContentUnion; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: Tool[]; + /** Configuration that the model uses to generate the response. Not + supported by the Gemini Developer API. + */ + generationConfig?: GenerationConfig; +} + +/** Parameters for counting tokens. */ +export declare interface CountTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Configuration for counting tokens. */ + config?: CountTokensConfig; +} + +/** Response for counting tokens. */ +export declare class CountTokensResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Total number of tokens. */ + totalTokens?: number; + /** Number of tokens in the cached part of the prompt (the cached content). */ + cachedContentTokenCount?: number; +} + +/** Optional parameters. */ +export declare interface CreateAuthTokenConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** An optional time after which, when using the resulting token, + messages in Live API sessions will be rejected. (Gemini may + preemptively close the session after this time.) + + If not set then this defaults to 30 minutes in the future. If set, this + value must be less than 20 hours in the future. */ + expireTime?: string; + /** The time after which new Live API sessions using the token + resulting from this request will be rejected. + + If not set this defaults to 60 seconds in the future. If set, this value + must be less than 20 hours in the future. */ + newSessionExpireTime?: string; + /** The number of times the token can be used. If this value is zero + then no limit is applied. Default is 1. Resuming a Live API session does + not count as a use. */ + uses?: number; + /** Configuration specific to Live API connections created using this token. */ + liveConnectConstraints?: LiveConnectConstraints; + /** Additional fields to lock in the effective LiveConnectParameters. */ + lockAdditionalFields?: string[]; +} + +/** Config for auth_tokens.create parameters. */ +export declare interface CreateAuthTokenParameters { + /** Optional parameters for the request. */ + config?: CreateAuthTokenConfig; +} + +/** Config for optional parameters. */ +export declare interface CreateBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The user-defined name of this BatchJob. + */ + displayName?: string; + /** GCS or BigQuery URI prefix for the output predictions. Example: + "gs://path/to/output/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + dest?: BatchJobDestinationUnion; +} + +/** Config for batches.create parameters. */ +export declare interface CreateBatchJobParameters { + /** The name of the model to produces the predictions via the BatchJob. + */ + model?: string; + /** GCS URI(-s) or BigQuery URI to your input data to run batch job. + Example: "gs://path/to/input/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + src: BatchJobSourceUnion; + /** Optional parameters for creating a BatchJob. + */ + config?: CreateBatchJobConfig; +} + +/** Optional configuration for cached content creation. */ +export declare interface CreateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; + /** The user-generated meaningful display name of the cached content. + */ + displayName?: string; + /** The content to cache. + */ + contents?: ContentListUnion; + /** Developer set system instruction. + */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + */ + tools?: Tool[]; + /** Configuration for the tools to use. This config is shared for all tools. + */ + toolConfig?: ToolConfig; + /** The Cloud KMS resource identifier of the customer managed + encryption key used to protect a resource. + The key needs to be in the same region as where the compute resource is + created. See + https://cloud.google.com/vertex-ai/docs/general/cmek for more + details. If this is set, then all created CachedContent objects + will be encrypted with the provided encryption key. + Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key} + */ + kmsKeyName?: string; +} + +/** Parameters for caches.create method. */ +export declare interface CreateCachedContentParameters { + /** ID of the model to use. Example: gemini-2.0-flash */ + model: string; + /** Configuration that contains optional parameters. + */ + config?: CreateCachedContentConfig; +} + +/** Parameters for initializing a new chat session. + + These parameters are used when creating a chat session with the + `chats.create()` method. + */ +export declare interface CreateChatParameters { + /** The name of the model to use for the chat session. + + For example: 'gemini-2.0-flash', 'gemini-2.0-flash-lite', etc. See Gemini API + docs to find the available models. + */ + model: string; + /** Config for the entire chat session. + + This config applies to all requests within the session + unless overridden by a per-request `config` in `SendMessageParameters`. + */ + config?: GenerateContentConfig; + /** The initial conversation history for the chat session. + + This allows you to start the chat with a pre-existing history. The history + must be a list of `Content` alternating between 'user' and 'model' roles. + It should start with a 'user' message. + */ + history?: Content[]; +} + +/** Used to override the default configuration. */ +export declare interface CreateFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the private _create method. */ +export declare interface CreateFileParameters { + /** The file to be uploaded. + mime_type: (Required) The MIME type of the file. Must be provided. + name: (Optional) The name of the file in the destination (e.g. + 'files/sample-image'). + display_name: (Optional) The display name of the file. + */ + file: File_2; + /** Used to override the default configuration. */ + config?: CreateFileConfig; +} + +/** Response for the create file method. */ +export declare class CreateFileResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; +} + +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +export declare function createModelContent(partOrString: PartListUnion | string): Content; + +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +export declare function createPartFromBase64(data: string, mimeType: string): Part; + +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +export declare function createPartFromCodeExecutionResult(outcome: Outcome, output: string): Part; + +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +export declare function createPartFromExecutableCode(code: string, language: Language): Part; + +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +export declare function createPartFromFunctionCall(name: string, args: Record): Part; + +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +export declare function createPartFromFunctionResponse(id: string, name: string, response: Record): Part; + +/** + * Creates a `Part` object from a `text` string. + */ +export declare function createPartFromText(text: string): Part; + +/** + * Creates a `Part` object from a `URI` string. + */ +export declare function createPartFromUri(uri: string, mimeType: string): Part; + +/** Supervised fine-tuning job creation request - optional fields. */ +export declare interface CreateTuningJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + validationDataset?: TuningValidationDataset; + /** The display name of the tuned Model. The name can be up to 128 characters long and can consist of any UTF-8 characters. */ + tunedModelDisplayName?: string; + /** The description of the TuningJob */ + description?: string; + /** Number of complete passes the model makes over the entire training dataset during training. */ + epochCount?: number; + /** Multiplier for adjusting the default learning rate. */ + learningRateMultiplier?: number; + /** If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. */ + exportLastCheckpointOnly?: boolean; + /** The optional checkpoint id of the pre-tuned model to use for tuning, if applicable. */ + preTunedModelCheckpointId?: string; + /** Adapter size for tuning. */ + adapterSize?: AdapterSize; + /** The batch size hyperparameter for tuning. If not set, a default of 4 or 16 will be used based on the number of training examples. */ + batchSize?: number; + /** The learning rate hyperparameter for tuning. If not set, a default of 0.001 or 0.0002 will be calculated based on the number of training examples. */ + learningRate?: number; +} + +/** Supervised fine-tuning job creation parameters - optional fields. */ +export declare interface CreateTuningJobParameters { + /** The base model that is being tuned, e.g., "gemini-2.5-flash". */ + baseModel: string; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDataset: TuningDataset; + /** Configuration for the tuning job. */ + config?: CreateTuningJobConfig; +} + +/** Supervised fine-tuning job creation parameters - optional fields. */ +export declare interface CreateTuningJobParametersPrivate { + /** The base model that is being tuned, e.g., "gemini-2.5-flash". */ + baseModel?: string; + /** The PreTunedModel that is being tuned. */ + preTunedModel?: PreTunedModel; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDataset: TuningDataset; + /** Configuration for the tuning job. */ + config?: CreateTuningJobConfig; +} + +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +export declare function createUserContent(partOrString: PartListUnion | string): Content; + +/** Distribution computed over a tuning dataset. */ +export declare interface DatasetDistribution { + /** Output only. Defines the histogram bucket. */ + buckets?: DatasetDistributionDistributionBucket[]; + /** Output only. The maximum of the population values. */ + max?: number; + /** Output only. The arithmetic mean of the values in the population. */ + mean?: number; + /** Output only. The median of the values in the population. */ + median?: number; + /** Output only. The minimum of the population values. */ + min?: number; + /** Output only. The 5th percentile of the values in the population. */ + p5?: number; + /** Output only. The 95th percentile of the values in the population. */ + p95?: number; + /** Output only. Sum of a given population of values. */ + sum?: number; +} + +/** Dataset bucket used to create a histogram for the distribution given a population of values. */ +export declare interface DatasetDistributionDistributionBucket { + /** Output only. Number of values in the bucket. */ + count?: string; + /** Output only. Left bound of the bucket. */ + left?: number; + /** Output only. Right bound of the bucket. */ + right?: number; +} + +/** Statistics computed over a tuning dataset. */ +export declare interface DatasetStats { + /** Output only. Number of billable characters in the tuning dataset. */ + totalBillableCharacterCount?: string; + /** Output only. Number of tuning characters in the tuning dataset. */ + totalTuningCharacterCount?: string; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user messages in the training dataset uri. */ + userDatasetExamples?: Content[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the messages per example. */ + userMessagePerExampleDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: DatasetDistribution; +} + +/** Optional parameters for models.get method. */ +export declare interface DeleteBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.delete parameters. */ +export declare interface DeleteBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: DeleteBatchJobConfig; +} + +/** Optional parameters for caches.delete method. */ +export declare interface DeleteCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for caches.delete method. */ +export declare interface DeleteCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: DeleteCachedContentConfig; +} + +/** Empty response for caches.delete method. */ +export declare class DeleteCachedContentResponse { +} + +/** Used to override the default configuration. */ +export declare interface DeleteFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the get method. */ +export declare interface DeleteFileParameters { + /** The name identifier for the file to be deleted. */ + name: string; + /** Used to override the default configuration. */ + config?: DeleteFileConfig; +} + +/** Response for the delete file method. */ +export declare class DeleteFileResponse { +} + +/** Configuration for deleting a tuned model. */ +export declare interface DeleteModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for deleting a tuned model. */ +export declare interface DeleteModelParameters { + model: string; + /** Optional parameters for the request. */ + config?: DeleteModelConfig; +} + +export declare class DeleteModelResponse { +} + +/** The return value of delete operation. */ +export declare interface DeleteResourceJob { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + name?: string; + done?: boolean; + error?: JobError; +} + +/** Statistics computed for datasets used for distillation. */ +export declare interface DistillationDataStats { + /** Output only. Statistics computed for the training dataset. */ + trainingDatasetStats?: DatasetStats; +} + +export declare type DownloadableFileUnion = string | File_2 | GeneratedVideo | Video; + +declare interface Downloader { + /** + * Downloads a file to the given location. + * + * @param params The parameters for downloading the file. + * @param apiClient The ApiClient to use for uploading. + * @return A Promises that resolves when the download is complete. + */ + download(params: DownloadFileParameters, apiClient: ApiClient): Promise; +} + +/** Used to override the default configuration. */ +export declare interface DownloadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters used to download a file. */ +export declare interface DownloadFileParameters { + /** The file to download. It can be a file name, a file object or a generated video. */ + file: DownloadableFileUnion; + /** Location where the file should be downloaded to. */ + downloadPath: string; + /** Configuration to for the download operation. */ + config?: DownloadFileConfig; +} + +/** Describes the options to customize dynamic retrieval. */ +export declare interface DynamicRetrievalConfig { + /** The mode of the predictor to be used in dynamic retrieval. */ + mode?: DynamicRetrievalConfigMode; + /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */ + dynamicThreshold?: number; +} + +/** Config for the dynamic retrieval config mode. */ +export declare enum DynamicRetrievalConfigMode { + /** + * Always trigger retrieval. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Run retrieval only when system decides it is necessary. + */ + MODE_DYNAMIC = "MODE_DYNAMIC" +} + +/** Configuration for editing an image. */ +export declare interface EditImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage URI used to store the generated images. + */ + outputGcsUri?: string; + /** Description of what to discourage in the generated images. + */ + negativePrompt?: string; + /** Number of images to generate. + */ + numberOfImages?: number; + /** Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9". + */ + aspectRatio?: string; + /** Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality. + */ + guidanceScale?: number; + /** Random seed for image generation. This is not available when + ``add_watermark`` is set to true. + */ + seed?: number; + /** Filter level for safety filtering. + */ + safetyFilterLevel?: SafetyFilterLevel; + /** Allows generation of people by the model. + */ + personGeneration?: PersonGeneration; + /** Whether to report the safety scores of each generated image and + the positive prompt in the response. + */ + includeSafetyAttributes?: boolean; + /** Whether to include the Responsible AI filter reason if the image + is filtered out of the response. + */ + includeRaiReason?: boolean; + /** Language of the text in the prompt. + */ + language?: ImagePromptLanguage; + /** MIME type of the generated image. + */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). + */ + outputCompressionQuality?: number; + /** Whether to add a watermark to the generated images. + */ + addWatermark?: boolean; + /** Describes the editing mode for the request. */ + editMode?: EditMode; + /** The number of sampling steps. A higher value has better image + quality, while a lower value has better latency. */ + baseSteps?: number; +} + +/** Parameters for the request to edit an image. */ +export declare interface EditImageParameters { + /** The model to use. */ + model: string; + /** A text description of the edit to apply to the image. */ + prompt: string; + /** The reference images for Imagen 3 editing. */ + referenceImages: ReferenceImage[]; + /** Configuration for editing. */ + config?: EditImageConfig; +} + +/** Response for the request to edit an image. */ +export declare class EditImageResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** Enum representing the Imagen 3 Edit mode. */ +export declare enum EditMode { + EDIT_MODE_DEFAULT = "EDIT_MODE_DEFAULT", + EDIT_MODE_INPAINT_REMOVAL = "EDIT_MODE_INPAINT_REMOVAL", + EDIT_MODE_INPAINT_INSERTION = "EDIT_MODE_INPAINT_INSERTION", + EDIT_MODE_OUTPAINT = "EDIT_MODE_OUTPAINT", + EDIT_MODE_CONTROLLED_EDITING = "EDIT_MODE_CONTROLLED_EDITING", + EDIT_MODE_STYLE = "EDIT_MODE_STYLE", + EDIT_MODE_BGSWAP = "EDIT_MODE_BGSWAP", + EDIT_MODE_PRODUCT_IMAGE = "EDIT_MODE_PRODUCT_IMAGE" +} + +/** Optional parameters for the embed_content method. */ +export declare interface EmbedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Type of task for which the embedding will be used. + */ + taskType?: string; + /** Title for the text. Only applicable when TaskType is + `RETRIEVAL_DOCUMENT`. + */ + title?: string; + /** Reduced dimension for the output embedding. If set, + excessive values in the output embedding are truncated from the end. + Supported by newer models since 2024 only. You cannot set this value if + using the earlier model (`models/embedding-001`). + */ + outputDimensionality?: number; + /** Vertex API only. The MIME type of the input. + */ + mimeType?: string; + /** Vertex API only. Whether to silently truncate inputs longer than + the max sequence length. If this option is set to false, oversized inputs + will lead to an INVALID_ARGUMENT error, similar to other text APIs. + */ + autoTruncate?: boolean; +} + +/** Request-level metadata for the Vertex Embed Content API. */ +export declare interface EmbedContentMetadata { + /** Vertex API only. The total number of billable characters included + in the request. + */ + billableCharacterCount?: number; +} + +/** Parameters for the embed_content method. */ +export declare interface EmbedContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The content to embed. Only the `parts.text` fields will be counted. + */ + contents: ContentListUnion; + /** Configuration that contains optional parameters. + */ + config?: EmbedContentConfig; +} + +/** Response for the embed_content method. */ +export declare class EmbedContentResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** The embeddings for each request, in the same order as provided in + the batch request. + */ + embeddings?: ContentEmbedding[]; + /** Vertex API only. Metadata about the request. + */ + metadata?: EmbedContentMetadata; +} + +/** Represents a customer-managed encryption key spec that can be applied to a top-level resource. */ +export declare interface EncryptionSpec { + /** Required. The Cloud KMS resource identifier of the customer managed encryption key used to protect a resource. Has the form: `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`. The key needs to be in the same region as where the compute resource is created. */ + kmsKeyName?: string; +} + +/** An endpoint where you deploy models. */ +export declare interface Endpoint { + /** Resource name of the endpoint. */ + name?: string; + /** ID of the model that's deployed to the endpoint. */ + deployedModelId?: string; +} + +/** End of speech sensitivity. */ +export declare enum EndSensitivity { + /** + * The default is END_SENSITIVITY_LOW. + */ + END_SENSITIVITY_UNSPECIFIED = "END_SENSITIVITY_UNSPECIFIED", + /** + * Automatic detection ends speech more often. + */ + END_SENSITIVITY_HIGH = "END_SENSITIVITY_HIGH", + /** + * Automatic detection ends speech less often. + */ + END_SENSITIVITY_LOW = "END_SENSITIVITY_LOW" +} + +/** Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. */ +export declare interface EnterpriseWebSearch { + /** Optional. List of domains to be excluded from the search results. The default limit is 2000 domains. */ + excludeDomains?: string[]; +} + +/** An entity representing the segmented area. */ +export declare interface EntityLabel { + /** The label of the segmented entity. */ + label?: string; + /** The confidence score of the detected label. */ + score?: number; +} + +/** The environment being operated. */ +export declare enum Environment { + /** + * Defaults to browser. + */ + ENVIRONMENT_UNSPECIFIED = "ENVIRONMENT_UNSPECIFIED", + /** + * Operates in a web browser. + */ + ENVIRONMENT_BROWSER = "ENVIRONMENT_BROWSER" +} + +/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [CodeExecution] tool, in which the code will be automatically executed, and a corresponding [CodeExecutionResult] will also be generated. */ +export declare interface ExecutableCode { + /** Required. The code to be executed. */ + code?: string; + /** Required. Programming language of the `code`. */ + language?: Language; +} + +/** Retrieve from data source powered by external API for grounding. The external API is not owned by Google, but need to follow the pre-defined API spec. */ +export declare interface ExternalApi { + /** The authentication config to access the API. Deprecated. Please use auth_config instead. */ + apiAuth?: ApiAuth; + /** The API spec that the external API implements. */ + apiSpec?: ApiSpec; + /** The authentication config to access the API. */ + authConfig?: AuthConfig; + /** Parameters for the elastic search API. */ + elasticSearchParams?: ExternalApiElasticSearchParams; + /** The endpoint of the external API. The system will call the API at this endpoint to retrieve the data for grounding. Example: https://acme.com:443/search */ + endpoint?: string; + /** Parameters for the simple search API. */ + simpleSearchParams?: ExternalApiSimpleSearchParams; +} + +/** The search parameters to use for the ELASTIC_SEARCH spec. */ +export declare interface ExternalApiElasticSearchParams { + /** The ElasticSearch index to use. */ + index?: string; + /** Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as the `num_hits` param. */ + numHits?: number; + /** The ElasticSearch search template to use. */ + searchTemplate?: string; +} + +/** The search parameters to use for SIMPLE_SEARCH spec. */ +export declare interface ExternalApiSimpleSearchParams { +} + +/** Options for feature selection preference. */ +export declare enum FeatureSelectionPreference { + FEATURE_SELECTION_PREFERENCE_UNSPECIFIED = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED", + PRIORITIZE_QUALITY = "PRIORITIZE_QUALITY", + BALANCED = "BALANCED", + PRIORITIZE_COST = "PRIORITIZE_COST" +} + +export declare interface FetchPredictOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the fetchPredictOperation method. */ +export declare interface FetchPredictOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + resourceName: string; + /** Used to override the default configuration. */ + config?: FetchPredictOperationConfig; +} + +/** A file uploaded to the API. */ +declare interface File_2 { + /** The `File` resource name. The ID (name excluding the "files/" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */ + name?: string; + /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */ + displayName?: string; + /** Output only. MIME type of the file. */ + mimeType?: string; + /** Output only. Size of the file in bytes. */ + sizeBytes?: string; + /** Output only. The timestamp of when the `File` was created. */ + createTime?: string; + /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */ + expirationTime?: string; + /** Output only. The timestamp of when the `File` was last updated. */ + updateTime?: string; + /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */ + sha256Hash?: string; + /** Output only. The URI of the `File`. */ + uri?: string; + /** Output only. The URI of the `File`, only set for downloadable (generated) files. */ + downloadUri?: string; + /** Output only. Processing state of the File. */ + state?: FileState; + /** Output only. The source of the `File`. */ + source?: FileSource; + /** Output only. Metadata for a video. */ + videoMetadata?: Record; + /** Output only. Error status if File processing failed. */ + error?: FileStatus; +} +export { File_2 as File } + +/** URI based data. */ +export declare interface FileData { + /** Optional. Display name of the file data. Used to provide a label or filename to distinguish file datas. It is not currently used in the Gemini GenerateContent calls. */ + displayName?: string; + /** Required. URI. */ + fileUri?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} + +export declare class Files extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + list: (params?: types.ListFilesParameters) => Promise>; + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + upload(params: types.UploadFileParameters): Promise; + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + download(params: types.DownloadFileParameters): Promise; + private listInternal; + private createInternal; + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + get(params: types.GetFileParameters): Promise; + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + delete(params: types.DeleteFileParameters): Promise; +} + +/** Source of the File. */ +export declare enum FileSource { + SOURCE_UNSPECIFIED = "SOURCE_UNSPECIFIED", + UPLOADED = "UPLOADED", + GENERATED = "GENERATED" +} + +/** + * Represents the size and mimeType of a file. The information is used to + * request the upload URL from the https://generativelanguage.googleapis.com/upload/v1beta/files endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface FileStat { + /** + * The size of the file in bytes. + */ + size: number; + /** + * The MIME type of the file. + */ + type: string | undefined; +} + +/** State for the lifecycle of a File. */ +export declare enum FileState { + STATE_UNSPECIFIED = "STATE_UNSPECIFIED", + PROCESSING = "PROCESSING", + ACTIVE = "ACTIVE", + FAILED = "FAILED" +} + +/** Status of a File that uses a common error model. */ +export declare interface FileStatus { + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: Record[]; + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + message?: string; + /** The status code. 0 for OK, 1 for CANCELLED */ + code?: number; +} + +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +export declare enum FinishReason { + /** + * The finish reason is unspecified. + */ + FINISH_REASON_UNSPECIFIED = "FINISH_REASON_UNSPECIFIED", + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + STOP = "STOP", + /** + * Token generation reached the configured maximum output tokens. + */ + MAX_TOKENS = "MAX_TOKENS", + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + SAFETY = "SAFETY", + /** + * The token generation stopped because of potential recitation. + */ + RECITATION = "RECITATION", + /** + * The token generation stopped because of using an unsupported language. + */ + LANGUAGE = "LANGUAGE", + /** + * All other reasons that stopped the token generation. + */ + OTHER = "OTHER", + /** + * Token generation stopped because the content contains forbidden terms. + */ + BLOCKLIST = "BLOCKLIST", + /** + * Token generation stopped for potentially containing prohibited content. + */ + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + /** + * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). + */ + SPII = "SPII", + /** + * The function call generated by the model is invalid. + */ + MALFORMED_FUNCTION_CALL = "MALFORMED_FUNCTION_CALL", + /** + * Token generation stopped because generated images have safety violations. + */ + IMAGE_SAFETY = "IMAGE_SAFETY", + /** + * The tool call generated by the model is invalid. + */ + UNEXPECTED_TOOL_CALL = "UNEXPECTED_TOOL_CALL" +} + +/** A function call. */ +export declare interface FunctionCall { + /** The unique id of the function call. If populated, the client to execute the + `function_call` and return the response with the matching `id`. */ + id?: string; + /** Optional. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */ + args?: Record; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */ + name?: string; +} + +/** Function calling config. */ +export declare interface FunctionCallingConfig { + /** Optional. Function calling mode. */ + mode?: FunctionCallingConfigMode; + /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */ + allowedFunctionNames?: string[]; +} + +/** Config for the function calling config mode. */ +export declare enum FunctionCallingConfigMode { + /** + * The function calling config mode is unspecified. Should not be used. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + AUTO = "AUTO", + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + ANY = "ANY", + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + NONE = "NONE" +} + +/** Defines a function that the model can generate JSON inputs for. + + The inputs are based on `OpenAPI 3.0 specifications + `_. + */ +export declare interface FunctionDeclaration { + /** Defines the function behavior. */ + behavior?: Behavior; + /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */ + description?: string; + /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */ + name?: string; + /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */ + parameters?: Schema; + /** Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "integer" } }, "additionalProperties": false, "required": ["name", "age"], "propertyOrdering": ["name", "age"] } ``` This field is mutually exclusive with `parameters`. */ + parametersJsonSchema?: unknown; + /** Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function. */ + response?: Schema; + /** Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`. */ + responseJsonSchema?: unknown; +} + +/** A function response. */ +export declare class FunctionResponse { + /** Signals that function call continues, and more responses will be returned, turning the function call into a generator. Is only applicable to NON_BLOCKING function calls (see FunctionDeclaration.behavior for details), ignored otherwise. If false, the default, future responses will not be considered. Is only applicable to NON_BLOCKING function calls, is ignored otherwise. If set to false, future responses will not be considered. It is allowed to return empty `response` with `will_continue=False` to signal that the function call is finished. */ + willContinue?: boolean; + /** Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. */ + scheduling?: FunctionResponseScheduling; + /** Optional. The id of the function call this response is for. Populated by the client to match the corresponding function call `id`. */ + id?: string; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */ + name?: string; + /** Required. The function response in JSON object format. Use "output" key to specify function output and "error" key to specify error details (if any). If "output" and "error" keys are not specified, then whole "response" is treated as function output. */ + response?: Record; +} + +/** Specifies how the response should be scheduled in the conversation. */ +export declare enum FunctionResponseScheduling { + /** + * This value is unused. + */ + SCHEDULING_UNSPECIFIED = "SCHEDULING_UNSPECIFIED", + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + SILENT = "SILENT", + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + WHEN_IDLE = "WHEN_IDLE", + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + INTERRUPT = "INTERRUPT" +} + +/** Input example for preference optimization. */ +export declare interface GeminiPreferenceExample { + /** List of completions for a given prompt. */ + completions?: GeminiPreferenceExampleCompletion[]; + /** Multi-turn contents that represents the Prompt. */ + contents?: Content[]; +} + +/** Completion and its preference score. */ +export declare interface GeminiPreferenceExampleCompletion { + /** Single turn completion for the given prompt. */ + completion?: Content; + /** The score for the given completion. */ + score?: number; +} + +/** Optional model configuration parameters. + + For more information, see `Content generation parameters + `_. + */ +export declare interface GenerateContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Instructions for the model to steer it toward better performance. + For example, "Answer as concisely as possible" or "Don't use technical + terms in your response". + */ + systemInstruction?: ContentUnion; + /** Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + */ + temperature?: number; + /** Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + */ + topP?: number; + /** For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + */ + topK?: number; + /** Number of response variations to return. + */ + candidateCount?: number; + /** Maximum number of tokens that can be generated in the response. + */ + maxOutputTokens?: number; + /** List of strings that tells the model to stop generating text if one + of the strings is encountered in the response. + */ + stopSequences?: string[]; + /** Whether to return the log probabilities of the tokens that were + chosen by the model at each step. + */ + responseLogprobs?: boolean; + /** Number of top candidate tokens to return the log probabilities for + at each generation step. + */ + logprobs?: number; + /** Positive values penalize tokens that already appear in the + generated text, increasing the probability of generating more diverse + content. + */ + presencePenalty?: number; + /** Positive values penalize tokens that repeatedly appear in the + generated text, increasing the probability of generating more diverse + content. + */ + frequencyPenalty?: number; + /** When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + */ + seed?: number; + /** Output response mimetype of the generated candidate text. + Supported mimetype: + - `text/plain`: (default) Text output. + - `application/json`: JSON response in the candidates. + The model needs to be prompted to output the appropriate response type, + otherwise the behavior is undefined. + This is a preview feature. + */ + responseMimeType?: string; + /** The `Schema` object allows the definition of input and output data types. + These types can be objects, but also primitives and arrays. + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema). + If set, a compatible response_mime_type must also be set. + Compatible mimetypes: `application/json`: Schema for JSON response. + */ + responseSchema?: SchemaUnion; + /** Optional. Output schema of the generated response. + This is an alternative to `response_schema` that accepts [JSON + Schema](https://json-schema.org/). If set, `response_schema` must be + omitted, but `response_mime_type` is required. While the full JSON Schema + may be sent, not all features are supported. Specifically, only the + following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` + - `type` - `format` - `title` - `description` - `enum` (for strings and + numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - + `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - + `properties` - `additionalProperties` - `required` The non-standard + `propertyOrdering` property may also be set. Cyclic references are + unrolled to a limited degree and, as such, may only be used within + non-required properties. (Nullable properties are not sufficient.) If + `$ref` is set on a sub-schema, no other properties, except for than those + starting as a `$`, may be set. */ + responseJsonSchema?: unknown; + /** Configuration for model router requests. + */ + routingConfig?: GenerationConfigRoutingConfig; + /** Configuration for model selection. + */ + modelSelectionConfig?: ModelSelectionConfig; + /** Safety settings in the request to block unsafe content in the + response. + */ + safetySettings?: SafetySetting[]; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: ToolListUnion; + /** Associates model output to a specific function call. + */ + toolConfig?: ToolConfig; + /** Labels with user-defined metadata to break down billed charges. */ + labels?: Record; + /** Resource name of a context cache that can be used in subsequent + requests. + */ + cachedContent?: string; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. + */ + responseModalities?: string[]; + /** If specified, the media resolution specified will be used. + */ + mediaResolution?: MediaResolution; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfigUnion; + /** If enabled, audio timestamp will be included in the request to the + model. + */ + audioTimestamp?: boolean; + /** The configuration for automatic function calling. + */ + automaticFunctionCalling?: AutomaticFunctionCallingConfig; + /** The thinking features configuration. + */ + thinkingConfig?: ThinkingConfig; +} + +/** Config for models.generate_content parameters. */ +export declare interface GenerateContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Content of the request. + */ + contents: ContentListUnion; + /** Configuration that contains optional model parameters. + */ + config?: GenerateContentConfig; +} + +/** Response message for PredictionService.GenerateContent. */ +export declare class GenerateContentResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Response variations returned by the model. + */ + candidates?: Candidate[]; + /** Timestamp when the request is made to the server. + */ + createTime?: string; + /** The history of automatic function calling. + */ + automaticFunctionCallingHistory?: Content[]; + /** Output only. The model version used to generate the response. */ + modelVersion?: string; + /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */ + promptFeedback?: GenerateContentResponsePromptFeedback; + /** Output only. response_id is used to identify each response. It is the encoding of the event_id. */ + responseId?: string; + /** Usage metadata about the response(s). */ + usageMetadata?: GenerateContentResponseUsageMetadata; + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text(): string | undefined; + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data(): string | undefined; + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls(): FunctionCall[] | undefined; + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode(): string | undefined; + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult(): string | undefined; +} + +/** Content filter results for a prompt sent in the request. */ +export declare class GenerateContentResponsePromptFeedback { + /** Output only. Blocked reason. */ + blockReason?: BlockedReason; + /** Output only. A readable block reason message. */ + blockReasonMessage?: string; + /** Output only. Safety ratings. */ + safetyRatings?: SafetyRating[]; +} + +/** Usage metadata about response(s). */ +export declare class GenerateContentResponseUsageMetadata { + /** Output only. List of modalities of the cached content in the request input. */ + cacheTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens in the cached part in the input (the cached content). */ + cachedContentTokenCount?: number; + /** Number of tokens in the response(s). */ + candidatesTokenCount?: number; + /** Output only. List of modalities that were returned in the response. */ + candidatesTokensDetails?: ModalityTokenCount[]; + /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */ + promptTokenCount?: number; + /** Output only. List of modalities that were processed in the request input. */ + promptTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens present in thoughts output. */ + thoughtsTokenCount?: number; + /** Output only. Number of tokens present in tool-use prompt(s). */ + toolUsePromptTokenCount?: number; + /** Output only. List of modalities that were processed for tool-use request inputs. */ + toolUsePromptTokensDetails?: ModalityTokenCount[]; + /** Total token count for prompt, response candidates, and tool-use prompts (if present). */ + totalTokenCount?: number; + /** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ + trafficType?: TrafficType; +} + +/** An output image. */ +export declare interface GeneratedImage { + /** The output image data. + */ + image?: Image_2; + /** Responsible AI filter reason if the image is filtered out of the + response. + */ + raiFilteredReason?: string; + /** Safety attributes of the image. Lists of RAI categories and their + scores of each content. + */ + safetyAttributes?: SafetyAttributes; + /** The rewritten prompt used for the image generation if the prompt + enhancer is enabled. + */ + enhancedPrompt?: string; +} + +/** A generated image mask. */ +export declare interface GeneratedImageMask { + /** The generated image mask. */ + mask?: Image_2; + /** The detected entities on the segmented area. */ + labels?: EntityLabel[]; +} + +/** A generated video. */ +export declare interface GeneratedVideo { + /** The output video */ + video?: Video; +} + +/** The config for generating an images. */ +export declare interface GenerateImagesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage URI used to store the generated images. + */ + outputGcsUri?: string; + /** Description of what to discourage in the generated images. + */ + negativePrompt?: string; + /** Number of images to generate. + */ + numberOfImages?: number; + /** Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9". + */ + aspectRatio?: string; + /** Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality. + */ + guidanceScale?: number; + /** Random seed for image generation. This is not available when + ``add_watermark`` is set to true. + */ + seed?: number; + /** Filter level for safety filtering. + */ + safetyFilterLevel?: SafetyFilterLevel; + /** Allows generation of people by the model. + */ + personGeneration?: PersonGeneration; + /** Whether to report the safety scores of each generated image and + the positive prompt in the response. + */ + includeSafetyAttributes?: boolean; + /** Whether to include the Responsible AI filter reason if the image + is filtered out of the response. + */ + includeRaiReason?: boolean; + /** Language of the text in the prompt. + */ + language?: ImagePromptLanguage; + /** MIME type of the generated image. + */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). + */ + outputCompressionQuality?: number; + /** Whether to add a watermark to the generated images. + */ + addWatermark?: boolean; + /** The size of the largest dimension of the generated image. + Supported sizes are 1K and 2K (not supported for Imagen 3 models). + */ + imageSize?: string; + /** Whether to use the prompt rewriting logic. + */ + enhancePrompt?: boolean; +} + +/** The parameters for generating images. */ +export declare interface GenerateImagesParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Text prompt that typically describes the images to output. + */ + prompt: string; + /** Configuration for generating images. + */ + config?: GenerateImagesConfig; +} + +/** The output images response. */ +export declare class GenerateImagesResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** List of generated images. + */ + generatedImages?: GeneratedImage[]; + /** Safety attributes of the positive prompt. Only populated if + ``include_safety_attributes`` is set to True. + */ + positivePromptSafetyAttributes?: SafetyAttributes; +} + +/** Configuration for generating videos. */ +export declare interface GenerateVideosConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Number of output videos. */ + numberOfVideos?: number; + /** The gcs bucket where to save the generated videos. */ + outputGcsUri?: string; + /** Frames per second for video generation. */ + fps?: number; + /** Duration of the clip for video generation in seconds. */ + durationSeconds?: number; + /** The RNG seed. If RNG seed is exactly same for each request with unchanged inputs, the prediction results will be consistent. Otherwise, a random RNG seed will be used each time to produce a different result. */ + seed?: number; + /** The aspect ratio for the generated video. 16:9 (landscape) and 9:16 (portrait) are supported. */ + aspectRatio?: string; + /** The resolution for the generated video. 720p and 1080p are supported. */ + resolution?: string; + /** Whether allow to generate person videos, and restrict to specific ages. Supported values are: dont_allow, allow_adult. */ + personGeneration?: string; + /** The pubsub topic where to publish the video generation progress. */ + pubsubTopic?: string; + /** Optional field in addition to the text content. Negative prompts can be explicitly stated here to help generate the video. */ + negativePrompt?: string; + /** Whether to use the prompt rewriting logic. */ + enhancePrompt?: boolean; + /** Whether to generate audio along with the video. */ + generateAudio?: boolean; + /** Image to use as the last frame of generated videos. Only supported for image to video use cases. */ + lastFrame?: Image_2; + /** The images to use as the references to generate the videos. + If this field is provided, the text prompt field must also be provided. + The image, video, or last_frame field are not supported. Each image must + be associated with a type. Veo 2 supports up to 3 asset images *or* 1 + style image. */ + referenceImages?: VideoGenerationReferenceImage[]; + /** Compression quality of the generated videos. */ + compressionQuality?: VideoCompressionQuality; +} + +/** A video generation long-running operation. */ +export declare class GenerateVideosOperation implements Operation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The response if the operation is successful. */ + response?: GenerateVideosResponse; + /** The full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }: OperationFromAPIResponseParameters): Operation; +} + +/** Class that represents the parameters for generating videos. */ +export declare interface GenerateVideosParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The text prompt for generating the videos. Optional for image to video use cases. */ + prompt?: string; + /** The input image for generating the videos. + Optional if prompt or video is provided. */ + image?: Image_2; + /** The input video for video extension use cases. + Optional if prompt or image is provided. */ + video?: Video; + /** Configuration for generating videos. */ + config?: GenerateVideosConfig; +} + +/** Response with generated videos. */ +export declare class GenerateVideosResponse { + /** List of the generated videos */ + generatedVideos?: GeneratedVideo[]; + /** Returns if any videos were filtered due to RAI policies. */ + raiMediaFilteredCount?: number; + /** Returns rai failure reasons if any. */ + raiMediaFilteredReasons?: string[]; +} + +/** Generation config. */ +export declare interface GenerationConfig { + /** Optional. Config for model selection. */ + modelSelectionConfig?: ModelSelectionConfig; + /** Optional. If enabled, audio timestamp will be included in the request to the model. */ + audioTimestamp?: boolean; + /** Optional. Number of candidates to generate. */ + candidateCount?: number; + /** Optional. If enabled, the model will detect emotions and adapt its responses accordingly. */ + enableAffectiveDialog?: boolean; + /** Optional. Frequency penalties. */ + frequencyPenalty?: number; + /** Optional. Logit probabilities. */ + logprobs?: number; + /** Optional. The maximum number of output tokens to generate per message. */ + maxOutputTokens?: number; + /** Optional. If specified, the media resolution specified will be used. */ + mediaResolution?: MediaResolution; + /** Optional. Positive penalties. */ + presencePenalty?: number; + /** Optional. Output schema of the generated response. This is an alternative to `response_schema` that accepts [JSON Schema](https://json-schema.org/). If set, `response_schema` must be omitted, but `response_mime_type` is required. While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` - `type` - `format` - `title` - `description` - `enum` (for strings and numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - `properties` - `additionalProperties` - `required` The non-standard `propertyOrdering` property may also be set. Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If `$ref` is set on a sub-schema, no other properties, except for than those starting as a `$`, may be set. */ + responseJsonSchema?: unknown; + /** Optional. If true, export the logprobs results in response. */ + responseLogprobs?: boolean; + /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */ + responseMimeType?: string; + /** Optional. The modalities of the response. */ + responseModalities?: Modality[]; + /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */ + responseSchema?: Schema; + /** Optional. Routing configuration. */ + routingConfig?: GenerationConfigRoutingConfig; + /** Optional. Seed. */ + seed?: number; + /** Optional. The speech generation config. */ + speechConfig?: SpeechConfig; + /** Optional. Stop sequences. */ + stopSequences?: string[]; + /** Optional. Controls the randomness of predictions. */ + temperature?: number; + /** Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking. */ + thinkingConfig?: GenerationConfigThinkingConfig; + /** Optional. If specified, top-k sampling will be used. */ + topK?: number; + /** Optional. If specified, nucleus sampling will be used. */ + topP?: number; +} + +/** The configuration for routing the request to a specific model. */ +export declare interface GenerationConfigRoutingConfig { + /** Automated routing. */ + autoMode?: GenerationConfigRoutingConfigAutoRoutingMode; + /** Manual routing. */ + manualMode?: GenerationConfigRoutingConfigManualRoutingMode; +} + +/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */ +export declare interface GenerationConfigRoutingConfigAutoRoutingMode { + /** The model routing preference. */ + modelRoutingPreference?: 'UNKNOWN' | 'PRIORITIZE_QUALITY' | 'BALANCED' | 'PRIORITIZE_COST'; +} + +/** When manual routing is set, the specified model will be used directly. */ +export declare interface GenerationConfigRoutingConfigManualRoutingMode { + /** The model name to use. Only the public LLM models are accepted. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */ + modelName?: string; +} + +/** Config for thinking features. */ +export declare interface GenerationConfigThinkingConfig { + /** Optional. Indicates whether to include thoughts in the response. If true, thoughts are returned only when available. */ + includeThoughts?: boolean; + /** Optional. Indicates the thinking budget in tokens. */ + thinkingBudget?: number; +} + +/** Optional parameters. */ +export declare interface GetBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.get parameters. */ +export declare interface GetBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: GetBatchJobConfig; +} + +/** Optional parameters for caches.get method. */ +export declare interface GetCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for caches.get method. */ +export declare interface GetCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: GetCachedContentConfig; +} + +/** Used to override the default configuration. */ +export declare interface GetFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the get method. */ +export declare interface GetFileParameters { + /** The name identifier for the file to retrieve. */ + name: string; + /** Used to override the default configuration. */ + config?: GetFileConfig; +} + +/** Optional parameters for models.get method. */ +export declare interface GetModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +export declare interface GetModelParameters { + model: string; + /** Optional parameters for the request. */ + config?: GetModelConfig; +} + +export declare interface GetOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the GET method. */ +export declare interface GetOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + /** Used to override the default configuration. */ + config?: GetOperationConfig; +} + +/** Optional parameters for tunings.get method. */ +export declare interface GetTuningJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the get method. */ +export declare interface GetTuningJobParameters { + name: string; + /** Optional parameters for the request. */ + config?: GetTuningJobConfig; +} + +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link + * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or + * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI + * API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API + * services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be + * set. When using Vertex AI, both {@link GoogleGenAIOptions.project} and {@link + * GoogleGenAIOptions.location} must be set, or a {@link + * GoogleGenAIOptions.apiKey} must be set when using Express Mode. + * + * Explicitly passed in values in {@link GoogleGenAIOptions} will always take + * precedence over environment variables. If both project/location and api_key + * exist in the environment variables, the project/location will be used. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +export declare class GoogleGenAI { + protected readonly apiClient: ApiClient; + private readonly apiKey?; + readonly vertexai: boolean; + private readonly googleAuthOptions?; + private readonly project?; + private readonly location?; + private readonly apiVersion?; + readonly models: Models; + readonly live: Live; + readonly batches: Batches; + readonly chats: Chats; + readonly caches: Caches; + readonly files: Files; + readonly operations: Operations; + readonly authTokens: Tokens; + readonly tunings: Tunings; + constructor(options: GoogleGenAIOptions); +} + +/** + * Google Gen AI SDK's configuration options. + * + * See {@link GoogleGenAI} for usage samples. + */ +export declare interface GoogleGenAIOptions { + /** + * Optional. Determines whether to use the Vertex AI or the Gemini API. + * + * @remarks + * When true, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API} will used. + * When false, the {@link https://ai.google.dev/api | Gemini API} will be used. + * + * If unset, default SDK behavior is to use the Gemini API service. + */ + vertexai?: boolean; + /** + * Optional. The Google Cloud project ID for Vertex AI clients. + * + * Find your project ID: https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + */ + project?: string; + /** + * Optional. The Google Cloud project {@link https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations | location} for Vertex AI clients. + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + location?: string; + /** + * The API Key, required for Gemini API clients. + * + * @remarks + * Required on browser runtimes. + */ + apiKey?: string; + /** + * Optional. The API version to use. + * + * @remarks + * If unset, the default API version will be used. + */ + apiVersion?: string; + /** + * Optional. Authentication options defined by the by google-auth-library for Vertex AI clients. + * + * @remarks + * @see {@link https://github.com/googleapis/google-auth-library-nodejs/blob/v9.15.0/src/auth/googleauth.ts | GoogleAuthOptions interface in google-auth-library-nodejs}. + * + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + googleAuthOptions?: GoogleAuthOptions; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; +} + +/** Tool to support Google Maps in Model. */ +export declare interface GoogleMaps { + /** Optional. Auth config for the Google Maps tool. */ + authConfig?: AuthConfig; +} + +/** The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). */ +export declare interface GoogleRpcStatus { + /** The status code, which should be an enum value of google.rpc.Code. */ + code?: number; + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: Record[]; + /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */ + message?: string; +} + +/** Tool to support Google Search in Model. Powered by Google. */ +export declare interface GoogleSearch { + /** Optional. Filter search results to a specific time range. + If customers set a start time, they must set an end time (and vice versa). + */ + timeRangeFilter?: Interval; + /** Optional. List of domains to be excluded from the search results. + The default limit is 2000 domains. */ + excludeDomains?: string[]; +} + +/** Tool to retrieve public web data for grounding, powered by Google. */ +export declare interface GoogleSearchRetrieval { + /** Specifies the dynamic retrieval configuration for the given source. */ + dynamicRetrievalConfig?: DynamicRetrievalConfig; +} + +/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */ +export declare interface GoogleTypeDate { + /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */ + day?: number; + /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */ + month?: number; + /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */ + year?: number; +} + +/** Grounding chunk. */ +export declare interface GroundingChunk { + /** Grounding chunk from Google Maps. */ + maps?: GroundingChunkMaps; + /** Grounding chunk from context retrieved by the retrieval tools. */ + retrievedContext?: GroundingChunkRetrievedContext; + /** Grounding chunk from the web. */ + web?: GroundingChunkWeb; +} + +/** Chunk from Google Maps. */ +export declare interface GroundingChunkMaps { + /** Sources used to generate the place answer. This includes review snippets and photos that were used to generate the answer, as well as uris to flag content. */ + placeAnswerSources?: GroundingChunkMapsPlaceAnswerSources; + /** This Place's resource name, in `places/{place_id}` format. Can be used to look up the Place. */ + placeId?: string; + /** Text of the chunk. */ + text?: string; + /** Title of the chunk. */ + title?: string; + /** URI reference of the chunk. */ + uri?: string; +} + +/** Sources used to generate the place answer. */ +export declare interface GroundingChunkMapsPlaceAnswerSources { + /** A link where users can flag a problem with the generated answer. */ + flagContentUri?: string; + /** Snippets of reviews that are used to generate the answer. */ + reviewSnippets?: GroundingChunkMapsPlaceAnswerSourcesReviewSnippet[]; +} + +/** Author attribution for a photo or review. */ +export declare interface GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution { + /** Name of the author of the Photo or Review. */ + displayName?: string; + /** Profile photo URI of the author of the Photo or Review. */ + photoUri?: string; + /** URI of the author of the Photo or Review. */ + uri?: string; +} + +/** Encapsulates a review snippet. */ +export declare interface GroundingChunkMapsPlaceAnswerSourcesReviewSnippet { + /** This review's author. */ + authorAttribution?: GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution; + /** A link where users can flag a problem with the review. */ + flagContentUri?: string; + /** A link to show the review on Google Maps. */ + googleMapsUri?: string; + /** A string of formatted recent time, expressing the review time relative to the current time in a form appropriate for the language and country. */ + relativePublishTimeDescription?: string; + /** A reference representing this place review which may be used to look up this place review again. */ + review?: string; +} + +/** Chunk from context retrieved by the retrieval tools. */ +export declare interface GroundingChunkRetrievedContext { + /** Output only. The full document name for the referenced Vertex AI Search document. */ + documentName?: string; + /** Additional context for the RAG retrieval result. This is only populated when using the RAG retrieval tool. */ + ragChunk?: RagChunk; + /** Text of the attribution. */ + text?: string; + /** Title of the attribution. */ + title?: string; + /** URI reference of the attribution. */ + uri?: string; +} + +/** Chunk from the web. */ +export declare interface GroundingChunkWeb { + /** Domain of the (original) URI. */ + domain?: string; + /** Title of the chunk. */ + title?: string; + /** URI reference of the chunk. */ + uri?: string; +} + +/** Metadata returned to client when grounding is enabled. */ +export declare interface GroundingMetadata { + /** Optional. Output only. Resource name of the Google Maps widget context token to be used with the PlacesContextElement widget to render contextual data. This is populated only for Google Maps grounding. */ + googleMapsWidgetContextToken?: string; + /** List of supporting references retrieved from specified grounding source. */ + groundingChunks?: GroundingChunk[]; + /** Optional. List of grounding support. */ + groundingSupports?: GroundingSupport[]; + /** Optional. Output only. Retrieval metadata. */ + retrievalMetadata?: RetrievalMetadata; + /** Optional. Queries executed by the retrieval tools. */ + retrievalQueries?: string[]; + /** Optional. Google search entry for the following-up web searches. */ + searchEntryPoint?: SearchEntryPoint; + /** Optional. Web search queries for the following-up web search. */ + webSearchQueries?: string[]; +} + +/** Grounding support. */ +export declare interface GroundingSupport { + /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. For Gemini 2.0 and before, this list must have the same size as the grounding_chunk_indices. For Gemini 2.5 and after, this list will be empty and should be ignored. */ + confidenceScores?: number[]; + /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */ + groundingChunkIndices?: number[]; + /** Segment of the content this support belongs to. */ + segment?: Segment; +} + +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +export declare enum HarmBlockMethod { + /** + * The harm block method is unspecified. + */ + HARM_BLOCK_METHOD_UNSPECIFIED = "HARM_BLOCK_METHOD_UNSPECIFIED", + /** + * The harm block method uses both probability and severity scores. + */ + SEVERITY = "SEVERITY", + /** + * The harm block method uses the probability score. + */ + PROBABILITY = "PROBABILITY" +} + +/** Required. The harm block threshold. */ +export declare enum HarmBlockThreshold { + /** + * Unspecified harm block threshold. + */ + HARM_BLOCK_THRESHOLD_UNSPECIFIED = "HARM_BLOCK_THRESHOLD_UNSPECIFIED", + /** + * Block low threshold and above (i.e. block more). + */ + BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", + /** + * Block medium threshold and above. + */ + BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", + /** + * Block only high threshold (i.e. block less). + */ + BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", + /** + * Block none. + */ + BLOCK_NONE = "BLOCK_NONE", + /** + * Turn off the safety filter. + */ + OFF = "OFF" +} + +/** Required. Harm category. */ +export declare enum HarmCategory { + /** + * The harm category is unspecified. + */ + HARM_CATEGORY_UNSPECIFIED = "HARM_CATEGORY_UNSPECIFIED", + /** + * The harm category is hate speech. + */ + HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH", + /** + * The harm category is dangerous content. + */ + HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT", + /** + * The harm category is harassment. + */ + HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT", + /** + * The harm category is sexually explicit content. + */ + HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT", + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HARM_CATEGORY_CIVIC_INTEGRITY = "HARM_CATEGORY_CIVIC_INTEGRITY", + /** + * The harm category is image hate. + */ + HARM_CATEGORY_IMAGE_HATE = "HARM_CATEGORY_IMAGE_HATE", + /** + * The harm category is image dangerous content. + */ + HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT", + /** + * The harm category is image harassment. + */ + HARM_CATEGORY_IMAGE_HARASSMENT = "HARM_CATEGORY_IMAGE_HARASSMENT", + /** + * The harm category is image sexually explicit content. + */ + HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT" +} + +/** Output only. Harm probability levels in the content. */ +export declare enum HarmProbability { + /** + * Harm probability unspecified. + */ + HARM_PROBABILITY_UNSPECIFIED = "HARM_PROBABILITY_UNSPECIFIED", + /** + * Negligible level of harm. + */ + NEGLIGIBLE = "NEGLIGIBLE", + /** + * Low level of harm. + */ + LOW = "LOW", + /** + * Medium level of harm. + */ + MEDIUM = "MEDIUM", + /** + * High level of harm. + */ + HIGH = "HIGH" +} + +/** Output only. Harm severity levels in the content. */ +export declare enum HarmSeverity { + /** + * Harm severity unspecified. + */ + HARM_SEVERITY_UNSPECIFIED = "HARM_SEVERITY_UNSPECIFIED", + /** + * Negligible level of harm severity. + */ + HARM_SEVERITY_NEGLIGIBLE = "HARM_SEVERITY_NEGLIGIBLE", + /** + * Low level of harm severity. + */ + HARM_SEVERITY_LOW = "HARM_SEVERITY_LOW", + /** + * Medium level of harm severity. + */ + HARM_SEVERITY_MEDIUM = "HARM_SEVERITY_MEDIUM", + /** + * High level of harm severity. + */ + HARM_SEVERITY_HIGH = "HARM_SEVERITY_HIGH" +} + +/** HTTP options to be used in each of the requests. */ +export declare interface HttpOptions { + /** The base URL for the AI platform service endpoint. */ + baseUrl?: string; + /** Specifies the version of the API to use. */ + apiVersion?: string; + /** Additional HTTP headers to be sent with the request. */ + headers?: Record; + /** Timeout for the request in milliseconds. */ + timeout?: number; + /** Extra parameters to add to the request body. + The structure must match the backend API's request structure. + - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest + - GeminiAPI backend API docs: https://ai.google.dev/api/rest */ + extraBody?: Record; +} + +/** + * Represents the necessary information to send a request to an API endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface HttpRequest { + /** + * URL path from the modules, this path is appended to the base API URL to + * form the complete request URL. + * + * If you wish to set full URL, use httpOptions.baseUrl instead. Example to + * set full URL in the request: + * + * const request: HttpRequest = { + * path: '', + * httpOptions: { + * baseUrl: 'https://', + * apiVersion: '', + * }, + * httpMethod: 'GET', + * }; + * + * The result URL will be: https:// + * + */ + path: string; + /** + * Optional query parameters to be appended to the request URL. + */ + queryParams?: Record; + /** + * Optional request body in json string or Blob format, GET request doesn't + * need a request body. + */ + body?: string | Blob; + /** + * The HTTP method to be used for the request. + */ + httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE'; + /** + * Optional set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; + /** + * Optional abort signal which can be used to cancel the request. + */ + abortSignal?: AbortSignal; +} + +/** A wrapper class for the http response. */ +export declare class HttpResponse { + /** Used to retain the processed HTTP headers in the response. */ + headers?: Record; + /** + * The original http response. + */ + responseInternal: Response; + constructor(response: Response); + json(): Promise; +} + +/** An image. */ +declare interface Image_2 { + /** The Cloud Storage URI of the image. ``Image`` can contain a value + for this field or the ``image_bytes`` field but not both. + */ + gcsUri?: string; + /** The image bytes data. ``Image`` can contain a value for this field + or the ``gcs_uri`` field but not both. + + * @remarks Encoded as base64 string. */ + imageBytes?: string; + /** The MIME type of the image. */ + mimeType?: string; +} +export { Image_2 as Image } + +/** Enum that specifies the language of the text in the prompt. */ +export declare enum ImagePromptLanguage { + /** + * Auto-detect the language. + */ + auto = "auto", + /** + * English + */ + en = "en", + /** + * Japanese + */ + ja = "ja", + /** + * Korean + */ + ko = "ko", + /** + * Hindi + */ + hi = "hi", + /** + * Chinese + */ + zh = "zh", + /** + * Portuguese + */ + pt = "pt", + /** + * Spanish + */ + es = "es" +} + +/** Config for inlined request. */ +export declare interface InlinedRequest { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model?: string; + /** Content of the request. + */ + contents?: ContentListUnion; + /** Configuration that contains optional model parameters. + */ + config?: GenerateContentConfig; +} + +/** Config for `inlined_responses` parameter. */ +export declare class InlinedResponse { + /** The response to the request. + */ + response?: GenerateContentResponse; + /** The error encountered while processing the request. + */ + error?: JobError; +} + +/** Represents a time interval, encoded as a start time (inclusive) and an end time (exclusive). + + The start time must be less than or equal to the end time. + When the start equals the end time, the interval is an empty interval. + (matches no time) + When both start and end are unspecified, the interval matches any time. + */ +export declare interface Interval { + /** The start time of the interval. */ + startTime?: string; + /** The end time of the interval. */ + endTime?: string; +} + +/** Job error. */ +export declare interface JobError { + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: string[]; + /** The status code. */ + code?: number; + /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the `details` field. */ + message?: string; +} + +/** Job state. */ +export declare enum JobState { + /** + * The job state is unspecified. + */ + JOB_STATE_UNSPECIFIED = "JOB_STATE_UNSPECIFIED", + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JOB_STATE_QUEUED = "JOB_STATE_QUEUED", + /** + * The service is preparing to run the job. + */ + JOB_STATE_PENDING = "JOB_STATE_PENDING", + /** + * The job is in progress. + */ + JOB_STATE_RUNNING = "JOB_STATE_RUNNING", + /** + * The job completed successfully. + */ + JOB_STATE_SUCCEEDED = "JOB_STATE_SUCCEEDED", + /** + * The job failed. + */ + JOB_STATE_FAILED = "JOB_STATE_FAILED", + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JOB_STATE_CANCELLING = "JOB_STATE_CANCELLING", + /** + * The job has been cancelled. + */ + JOB_STATE_CANCELLED = "JOB_STATE_CANCELLED", + /** + * The job has been stopped, and can be resumed. + */ + JOB_STATE_PAUSED = "JOB_STATE_PAUSED", + /** + * The job has expired. + */ + JOB_STATE_EXPIRED = "JOB_STATE_EXPIRED", + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JOB_STATE_UPDATING = "JOB_STATE_UPDATING", + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JOB_STATE_PARTIALLY_SUCCEEDED = "JOB_STATE_PARTIALLY_SUCCEEDED" +} + +/** Required. Programming language of the `code`. */ +export declare enum Language { + /** + * Unspecified language. This value should not be used. + */ + LANGUAGE_UNSPECIFIED = "LANGUAGE_UNSPECIFIED", + /** + * Python >= 3.10, with numpy and simpy available. + */ + PYTHON = "PYTHON" +} + +/** An object that represents a latitude/longitude pair. + + This is expressed as a pair of doubles to represent degrees latitude and + degrees longitude. Unless specified otherwise, this object must conform to the + + WGS84 standard. Values must be within normalized ranges. + */ +export declare interface LatLng { + /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */ + latitude?: number; + /** The longitude in degrees. It must be in the range [-180.0, +180.0] */ + longitude?: number; +} + +/** Config for optional parameters. */ +export declare interface ListBatchJobsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; +} + +/** Config for batches.list parameters. */ +export declare interface ListBatchJobsParameters { + config?: ListBatchJobsConfig; +} + +/** Config for batches.list return value. */ +export declare class ListBatchJobsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + batchJobs?: BatchJob[]; +} + +/** Config for caches.list method. */ +export declare interface ListCachedContentsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; +} + +/** Parameters for caches.list method. */ +export declare interface ListCachedContentsParameters { + /** Configuration that contains optional parameters. + */ + config?: ListCachedContentsConfig; +} + +export declare class ListCachedContentsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + /** List of cached contents. + */ + cachedContents?: CachedContent[]; +} + +/** Used to override the default configuration. */ +export declare interface ListFilesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; +} + +/** Generates the parameters for the list method. */ +export declare interface ListFilesParameters { + /** Used to override the default configuration. */ + config?: ListFilesConfig; +} + +/** Response for the list files method. */ +export declare class ListFilesResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** A token to retrieve next page of results. */ + nextPageToken?: string; + /** The list of files. */ + files?: File_2[]; +} + +export declare interface ListModelsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; + /** Set true to list base models, false to list tuned models. */ + queryBase?: boolean; +} + +export declare interface ListModelsParameters { + config?: ListModelsConfig; +} + +export declare class ListModelsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + models?: Model[]; +} + +/** Configuration for the list tuning jobs method. */ +export declare interface ListTuningJobsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; +} + +/** Parameters for the list tuning jobs method. */ +export declare interface ListTuningJobsParameters { + config?: ListTuningJobsConfig; +} + +/** Response for the list tuning jobs method. */ +export declare class ListTuningJobsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** A token to retrieve the next page of results. Pass to ListTuningJobsRequest.page_token to obtain that page. */ + nextPageToken?: string; + /** List of TuningJobs in the requested page. */ + tuningJobs?: TuningJob[]; +} + +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +export declare class Live { + private readonly apiClient; + private readonly auth; + private readonly webSocketFactory; + readonly music: LiveMusic; + constructor(apiClient: ApiClient, auth: Auth, webSocketFactory: WebSocketFactory); + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + connect(params: types.LiveConnectParameters): Promise; + private isCallableTool; +} + +/** Callbacks for the live API. */ +export declare interface LiveCallbacks { + /** + * Called when the websocket connection is established. + */ + onopen?: (() => void) | null; + /** + * Called when a message is received from the server. + */ + onmessage: (e: LiveServerMessage) => void; + /** + * Called when an error occurs. + */ + onerror?: ((e: ErrorEvent) => void) | null; + /** + * Called when the websocket connection is closed. + */ + onclose?: ((e: CloseEvent) => void) | null; +} + +/** Incremental update of the current conversation delivered from the client. + + All the content here will unconditionally be appended to the conversation + history and used as part of the prompt to the model to generate content. + + A message here will interrupt any current model generation. + */ +export declare interface LiveClientContent { + /** The content appended to the current conversation with the model. + + For single-turn queries, this is a single instance. For multi-turn + queries, this is a repeated field that contains conversation history and + latest request. + */ + turns?: Content[]; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Messages sent by the client in the API call. */ +export declare interface LiveClientMessage { + /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */ + setup?: LiveClientSetup; + /** Incremental update of the current conversation delivered from the client. */ + clientContent?: LiveClientContent; + /** User input that is sent in real time. */ + realtimeInput?: LiveClientRealtimeInput; + /** Response to a `ToolCallMessage` received from the server. */ + toolResponse?: LiveClientToolResponse; +} + +/** User input that is sent in real time. + + This is different from `LiveClientContent` in a few ways: + + - Can be sent continuously without interruption to model generation. + - If there is a need to mix data interleaved across the + `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to + optimize for best response, but there are no guarantees. + - End of turn is not explicitly specified, but is rather derived from user + activity (for example, end of speech). + - Even before the end of turn, the data is processed incrementally + to optimize for a fast start of the response from the model. + - Is always assumed to be the user's input (cannot be used to populate + conversation history). + */ +export declare interface LiveClientRealtimeInput { + /** Inlined bytes data for media input. */ + mediaChunks?: Blob_2[]; + /** The realtime audio input stream. */ + audio?: Blob_2; + /** + Indicates that the audio stream has ended, e.g. because the microphone was + turned off. + + This should only be sent when automatic activity detection is enabled + (which is the default). + + The client can reopen the stream by sending an audio message. + */ + audioStreamEnd?: boolean; + /** The realtime video input stream. */ + video?: Blob_2; + /** The realtime text input stream. */ + text?: string; + /** Marks the start of user activity. */ + activityStart?: ActivityStart; + /** Marks the end of user activity. */ + activityEnd?: ActivityEnd; +} + +/** Message contains configuration that will apply for the duration of the streaming session. */ +export declare interface LiveClientSetup { + /** + The fully qualified name of the publisher model or tuned model endpoint to + use. + */ + model?: string; + /** The generation configuration for the session. + Note: only a subset of fields are supported. + */ + generationConfig?: GenerationConfig; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; + /** Configures the realtime input behavior in BidiGenerateContent. */ + realtimeInputConfig?: RealtimeInputConfig; + /** Configures session resumption mechanism. + + If included server will send SessionResumptionUpdate messages. */ + sessionResumption?: SessionResumptionConfig; + /** Configures context window compression mechanism. + + If included, server will compress context window to fit into given length. */ + contextWindowCompression?: ContextWindowCompressionConfig; + /** The transcription of the input aligns with the input audio language. + */ + inputAudioTranscription?: AudioTranscriptionConfig; + /** The transcription of the output aligns with the language code + specified for the output audio. + */ + outputAudioTranscription?: AudioTranscriptionConfig; + /** Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input. */ + proactivity?: ProactivityConfig; +} + +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +export declare class LiveClientToolResponse { + /** The response to the function calls. */ + functionResponses?: FunctionResponse[]; +} + +/** Session config for the API connection. */ +export declare interface LiveConnectConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The generation configuration for the session. */ + generationConfig?: GenerationConfig; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. Defaults to AUDIO if not specified. + */ + responseModalities?: Modality[]; + /** Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + */ + temperature?: number; + /** Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + */ + topP?: number; + /** For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + */ + topK?: number; + /** Maximum number of tokens that can be generated in the response. + */ + maxOutputTokens?: number; + /** If specified, the media resolution specified will be used. + */ + mediaResolution?: MediaResolution; + /** When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + */ + seed?: number; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfig; + /** If enabled, the model will detect emotions and adapt its responses accordingly. */ + enableAffectiveDialog?: boolean; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; + /** Configures session resumption mechanism. + + If included the server will send SessionResumptionUpdate messages. */ + sessionResumption?: SessionResumptionConfig; + /** The transcription of the input aligns with the input audio language. + */ + inputAudioTranscription?: AudioTranscriptionConfig; + /** The transcription of the output aligns with the language code + specified for the output audio. + */ + outputAudioTranscription?: AudioTranscriptionConfig; + /** Configures the realtime input behavior in BidiGenerateContent. */ + realtimeInputConfig?: RealtimeInputConfig; + /** Configures context window compression mechanism. + + If included, server will compress context window to fit into given length. */ + contextWindowCompression?: ContextWindowCompressionConfig; + /** Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input. */ + proactivity?: ProactivityConfig; +} + +/** Config for LiveConnectConstraints for Auth Token creation. */ +export declare interface LiveConnectConstraints { + /** ID of the model to configure in the ephemeral token for Live API. + For a list of models, see `Gemini models + `. */ + model?: string; + /** Configuration specific to Live API connections created using this token. */ + config?: LiveConnectConfig; +} + +/** Parameters for connecting to the live API. */ +export declare interface LiveConnectParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** callbacks */ + callbacks: LiveCallbacks; + /** Optional configuration parameters for the request. + */ + config?: LiveConnectConfig; +} + +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +declare class LiveMusic { + private readonly apiClient; + private readonly auth; + private readonly webSocketFactory; + constructor(apiClient: ApiClient, auth: Auth, webSocketFactory: WebSocketFactory); + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + connect(params: types.LiveMusicConnectParameters): Promise; +} + +/** Callbacks for the realtime music API. */ +export declare interface LiveMusicCallbacks { + /** + * Called when a message is received from the server. + */ + onmessage: (e: LiveMusicServerMessage) => void; + /** + * Called when an error occurs. + */ + onerror?: ((e: ErrorEvent) => void) | null; + /** + * Called when the websocket connection is closed. + */ + onclose?: ((e: CloseEvent) => void) | null; +} + +/** User input to start or steer the music. */ +export declare interface LiveMusicClientContent { + /** Weighted prompts as the model input. */ + weightedPrompts?: WeightedPrompt[]; +} + +/** Messages sent by the client in the LiveMusicClientMessage call. */ +export declare interface LiveMusicClientMessage { + /** Message to be sent in the first (and only in the first) `LiveMusicClientMessage`. + Clients should wait for a `LiveMusicSetupComplete` message before + sending any additional messages. */ + setup?: LiveMusicClientSetup; + /** User input to influence music generation. */ + clientContent?: LiveMusicClientContent; + /** Configuration for music generation. */ + musicGenerationConfig?: LiveMusicGenerationConfig; + /** Playback control signal for the music generation. */ + playbackControl?: LiveMusicPlaybackControl; +} + +/** Message to be sent by the system when connecting to the API. */ +export declare interface LiveMusicClientSetup { + /** The model's resource name. Format: `models/{model}`. */ + model?: string; +} + +/** Parameters for connecting to the live API. */ +export declare interface LiveMusicConnectParameters { + /** The model's resource name. */ + model: string; + /** Callbacks invoked on server events. */ + callbacks: LiveMusicCallbacks; +} + +/** A prompt that was filtered with the reason. */ +export declare interface LiveMusicFilteredPrompt { + /** The text prompt that was filtered. */ + text?: string; + /** The reason the prompt was filtered. */ + filteredReason?: string; +} + +/** Configuration for music generation. */ +export declare interface LiveMusicGenerationConfig { + /** Controls the variance in audio generation. Higher values produce + higher variance. Range is [0.0, 3.0]. */ + temperature?: number; + /** Controls how the model selects tokens for output. Samples the topK + tokens with the highest probabilities. Range is [1, 1000]. */ + topK?: number; + /** Seeds audio generation. If not set, the request uses a randomly + generated seed. */ + seed?: number; + /** Controls how closely the model follows prompts. + Higher guidance follows more closely, but will make transitions more + abrupt. Range is [0.0, 6.0]. */ + guidance?: number; + /** Beats per minute. Range is [60, 200]. */ + bpm?: number; + /** Density of sounds. Range is [0.0, 1.0]. */ + density?: number; + /** Brightness of the music. Range is [0.0, 1.0]. */ + brightness?: number; + /** Scale of the generated music. */ + scale?: Scale; + /** Whether the audio output should contain bass. */ + muteBass?: boolean; + /** Whether the audio output should contain drums. */ + muteDrums?: boolean; + /** Whether the audio output should contain only bass and drums. */ + onlyBassAndDrums?: boolean; + /** The mode of music generation. Default mode is QUALITY. */ + musicGenerationMode?: MusicGenerationMode; +} + +/** The playback control signal to apply to the music generation. */ +export declare enum LiveMusicPlaybackControl { + /** + * This value is unused. + */ + PLAYBACK_CONTROL_UNSPECIFIED = "PLAYBACK_CONTROL_UNSPECIFIED", + /** + * Start generating the music. + */ + PLAY = "PLAY", + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + PAUSE = "PAUSE", + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + STOP = "STOP", + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + RESET_CONTEXT = "RESET_CONTEXT" +} + +/** Server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. + Clients may choose to buffer and play it out in real time. + */ +export declare interface LiveMusicServerContent { + /** The audio chunks that the model has generated. */ + audioChunks?: AudioChunk[]; +} + +/** Response message for the LiveMusicClientMessage call. */ +export declare class LiveMusicServerMessage { + /** Message sent in response to a `LiveMusicClientSetup` message from the client. + Clients should wait for this message before sending any additional messages. */ + setupComplete?: LiveMusicServerSetupComplete; + /** Content generated by the model in response to client messages. */ + serverContent?: LiveMusicServerContent; + /** A prompt that was filtered with the reason. */ + filteredPrompt?: LiveMusicFilteredPrompt; + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk(): AudioChunk | undefined; +} + +/** Sent in response to a `LiveMusicClientSetup` message from the client. */ +export declare interface LiveMusicServerSetupComplete { +} + +/** + Represents a connection to the API. + + @experimental + */ +export declare class LiveMusicSession { + readonly conn: WebSocket_2; + private readonly apiClient; + constructor(conn: WebSocket_2, apiClient: ApiClient); + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + setWeightedPrompts(params: types.LiveMusicSetWeightedPromptsParameters): Promise; + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + setMusicGenerationConfig(params: types.LiveMusicSetConfigParameters): Promise; + private sendPlaybackControl; + /** + * Start the music stream. + * + * @experimental + */ + play(): void; + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause(): void; + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop(): void; + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext(): void; + /** + Terminates the WebSocket connection. + + @experimental + */ + close(): void; +} + +/** Parameters for setting config for the live music API. */ +export declare interface LiveMusicSetConfigParameters { + /** Configuration for music generation. */ + musicGenerationConfig: LiveMusicGenerationConfig; +} + +/** Parameters for setting weighted prompts for the live music API. */ +export declare interface LiveMusicSetWeightedPromptsParameters { + /** A map of text prompts to weights to use for the generation request. */ + weightedPrompts: WeightedPrompt[]; +} + +/** Prompts and config used for generating this audio chunk. */ +export declare interface LiveMusicSourceMetadata { + /** Weighted prompts for generating this audio chunk. */ + clientContent?: LiveMusicClientContent; + /** Music generation config for generating this audio chunk. */ + musicGenerationConfig?: LiveMusicGenerationConfig; +} + +/** Parameters for sending client content to the live API. */ +export declare interface LiveSendClientContentParameters { + /** Client content to send to the session. */ + turns?: ContentListUnion; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Parameters for sending realtime input to the live API. */ +export declare interface LiveSendRealtimeInputParameters { + /** Realtime input to send to the session. */ + media?: BlobImageUnion; + /** The realtime audio input stream. */ + audio?: Blob_2; + /** + Indicates that the audio stream has ended, e.g. because the microphone was + turned off. + + This should only be sent when automatic activity detection is enabled + (which is the default). + + The client can reopen the stream by sending an audio message. + */ + audioStreamEnd?: boolean; + /** The realtime video input stream. */ + video?: BlobImageUnion; + /** The realtime text input stream. */ + text?: string; + /** Marks the start of user activity. */ + activityStart?: ActivityStart; + /** Marks the end of user activity. */ + activityEnd?: ActivityEnd; +} + +/** Parameters for sending tool responses to the live API. */ +export declare class LiveSendToolResponseParameters { + /** Tool responses to send to the session. */ + functionResponses: FunctionResponse[] | FunctionResponse; +} + +/** Incremental server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. Clients + may choose to buffer and play it out in real time. + */ +export declare interface LiveServerContent { + /** The content that the model has generated as part of the current conversation with the user. */ + modelTurn?: Content; + /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */ + turnComplete?: boolean; + /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */ + interrupted?: boolean; + /** Metadata returned to client when grounding is enabled. */ + groundingMetadata?: GroundingMetadata; + /** If true, indicates that the model is done generating. When model is + interrupted while generating there will be no generation_complete message + in interrupted turn, it will go through interrupted > turn_complete. + When model assumes realtime playback there will be delay between + generation_complete and turn_complete that is caused by model + waiting for playback to finish. If true, indicates that the model + has finished generating all content. This is a signal to the client + that it can stop sending messages. */ + generationComplete?: boolean; + /** Input transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn. */ + inputTranscription?: Transcription; + /** Output transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn. + */ + outputTranscription?: Transcription; + /** Metadata related to url context retrieval tool. */ + urlContextMetadata?: UrlContextMetadata; +} + +/** Server will not be able to service client soon. */ +export declare interface LiveServerGoAway { + /** The remaining time before the connection will be terminated as ABORTED. The minimal time returned here is specified differently together with the rate limits for a given model. */ + timeLeft?: string; +} + +/** Response message for API call. */ +export declare class LiveServerMessage { + /** Sent in response to a `LiveClientSetup` message from the client. */ + setupComplete?: LiveServerSetupComplete; + /** Content generated by the model in response to client messages. */ + serverContent?: LiveServerContent; + /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ + toolCall?: LiveServerToolCall; + /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */ + toolCallCancellation?: LiveServerToolCallCancellation; + /** Usage metadata about model response(s). */ + usageMetadata?: UsageMetadata; + /** Server will disconnect soon. */ + goAway?: LiveServerGoAway; + /** Update of the session resumption state. */ + sessionResumptionUpdate?: LiveServerSessionResumptionUpdate; + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text(): string | undefined; + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data(): string | undefined; +} + +/** Update of the session resumption state. + + Only sent if `session_resumption` was set in the connection config. + */ +export declare interface LiveServerSessionResumptionUpdate { + /** New handle that represents state that can be resumed. Empty if `resumable`=false. */ + newHandle?: string; + /** True if session can be resumed at this point. It might be not possible to resume session at some points. In that case we send update empty new_handle and resumable=false. Example of such case could be model executing function calls or just generating. Resuming session (using previous session token) in such state will result in some data loss. */ + resumable?: boolean; + /** Index of last message sent by client that is included in state represented by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent` is set. + + Presence of this index allows users to transparently reconnect and avoid issue of losing some part of realtime audio input/video. If client wishes to temporarily disconnect (for example as result of receiving GoAway) they can do it without losing state by buffering messages sent since last `SessionResmumptionTokenUpdate`. This field will enable them to limit buffering (avoid keeping all requests in RAM). + + Note: This should not be used for when resuming a session at some time later -- in those cases partial audio and video frames arelikely not needed. */ + lastConsumedClientMessageIndex?: string; +} + +export declare interface LiveServerSetupComplete { + /** The session id of the live session. */ + sessionId?: string; +} + +/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ +export declare interface LiveServerToolCall { + /** The function call to be executed. */ + functionCalls?: FunctionCall[]; +} + +/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. + + If there were side-effects to those tool calls, clients may attempt to undo + the tool calls. This message occurs only in cases where the clients interrupt + server turns. + */ +export declare interface LiveServerToolCallCancellation { + /** The ids of the tool calls to be cancelled. */ + ids?: string[]; +} + +/** Logprobs Result */ +export declare interface LogprobsResult { + /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */ + chosenCandidates?: LogprobsResultCandidate[]; + /** Length = total number of decoding steps. */ + topCandidates?: LogprobsResultTopCandidates[]; +} + +/** Candidate for the logprobs token and score. */ +export declare interface LogprobsResultCandidate { + /** The candidate's log probability. */ + logProbability?: number; + /** The candidate's token string value. */ + token?: string; + /** The candidate's token id value. */ + tokenId?: number; +} + +/** Candidates with top log probabilities at each decoding step. */ +export declare interface LogprobsResultTopCandidates { + /** Sorted by log probability in descending order. */ + candidates?: LogprobsResultCandidate[]; +} + +/** Configuration for a Mask reference image. */ +export declare interface MaskReferenceConfig { + /** Prompts the model to generate a mask instead of you needing to + provide one (unless MASK_MODE_USER_PROVIDED is used). */ + maskMode?: MaskReferenceMode; + /** A list of up to 5 class ids to use for semantic segmentation. + Automatically creates an image mask based on specific objects. */ + segmentationClasses?: number[]; + /** Dilation percentage of the mask provided. + Float between 0 and 1. */ + maskDilation?: number; +} + +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +export declare class MaskReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the mask reference image. */ + config?: MaskReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the mask mode of a mask reference image. */ +export declare enum MaskReferenceMode { + MASK_MODE_DEFAULT = "MASK_MODE_DEFAULT", + MASK_MODE_USER_PROVIDED = "MASK_MODE_USER_PROVIDED", + MASK_MODE_BACKGROUND = "MASK_MODE_BACKGROUND", + MASK_MODE_FOREGROUND = "MASK_MODE_FOREGROUND", + MASK_MODE_SEMANTIC = "MASK_MODE_SEMANTIC" +} + +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +export declare function mcpToTool(...args: [...Client[], CallableToolConfig | Client]): CallableTool; + +/** Server content modalities. */ +export declare enum MediaModality { + /** + * The modality is unspecified. + */ + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + /** + * Plain text. + */ + TEXT = "TEXT", + /** + * Images. + */ + IMAGE = "IMAGE", + /** + * Video. + */ + VIDEO = "VIDEO", + /** + * Audio. + */ + AUDIO = "AUDIO", + /** + * Document, e.g. PDF. + */ + DOCUMENT = "DOCUMENT" +} + +/** The media resolution to use. */ +export declare enum MediaResolution { + /** + * Media resolution has not been set + */ + MEDIA_RESOLUTION_UNSPECIFIED = "MEDIA_RESOLUTION_UNSPECIFIED", + /** + * Media resolution set to low (64 tokens). + */ + MEDIA_RESOLUTION_LOW = "MEDIA_RESOLUTION_LOW", + /** + * Media resolution set to medium (256 tokens). + */ + MEDIA_RESOLUTION_MEDIUM = "MEDIA_RESOLUTION_MEDIUM", + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MEDIA_RESOLUTION_HIGH = "MEDIA_RESOLUTION_HIGH" +} + +/** Server content modalities. */ +export declare enum Modality { + /** + * The modality is unspecified. + */ + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + /** + * Indicates the model should return text + */ + TEXT = "TEXT", + /** + * Indicates the model should return images. + */ + IMAGE = "IMAGE", + /** + * Indicates the model should return audio. + */ + AUDIO = "AUDIO" +} + +/** Represents token counting info for a single modality. */ +export declare interface ModalityTokenCount { + /** The modality associated with this token count. */ + modality?: MediaModality; + /** Number of tokens. */ + tokenCount?: number; +} + +/** The mode of the predictor to be used in dynamic retrieval. */ +export declare enum Mode { + /** + * Always trigger retrieval. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Run retrieval only when system decides it is necessary. + */ + MODE_DYNAMIC = "MODE_DYNAMIC" +} + +/** A trained machine learning model. */ +export declare interface Model { + /** Resource name of the model. */ + name?: string; + /** Display name of the model. */ + displayName?: string; + /** Description of the model. */ + description?: string; + /** Version ID of the model. A new version is committed when a new + model version is uploaded or trained under an existing model ID. The + version ID is an auto-incrementing decimal number in string + representation. */ + version?: string; + /** List of deployed models created from this base model. Note that a + model could have been deployed to endpoints in different locations. */ + endpoints?: Endpoint[]; + /** Labels with user-defined metadata to organize your models. */ + labels?: Record; + /** Information about the tuned model from the base model. */ + tunedModelInfo?: TunedModelInfo; + /** The maximum number of input tokens that the model can handle. */ + inputTokenLimit?: number; + /** The maximum number of output tokens that the model can generate. */ + outputTokenLimit?: number; + /** List of actions that are supported by the model. */ + supportedActions?: string[]; + /** The default checkpoint id of a model version. + */ + defaultCheckpointId?: string; + /** The checkpoints of the model. */ + checkpoints?: Checkpoint[]; +} + +export declare class Models extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + generateContent: (params: types.GenerateContentParameters) => Promise; + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + private maybeMoveToResponseJsonSchem; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + generateContentStream: (params: types.GenerateContentParameters) => Promise>; + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + private processParamsMaybeAddMcpUsage; + private initAfcToolsMap; + private processAfcStream; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + generateImages: (params: types.GenerateImagesParameters) => Promise; + list: (params?: types.ListModelsParameters) => Promise>; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + editImage: (params: types.EditImageParameters) => Promise; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + upscaleImage: (params: types.UpscaleImageParameters) => Promise; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + generateVideos: (params: types.GenerateVideosParameters) => Promise; + private generateContentInternal; + private generateContentStreamInternal; + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + embedContent(params: types.EmbedContentParameters): Promise; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + private generateImagesInternal; + private editImageInternal; + private upscaleImageInternal; + /** + * Recontextualizes an image. + * + * There are two types of recontextualization currently supported: + * 1) Imagen Product Recontext - Generate images of products in new scenes + * and contexts. + * 2) Virtual Try-On: Generate images of persons modeling fashion products. + * + * @param params - The parameters for recontextualizing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response1 = await ai.models.recontextImage({ + * model: 'imagen-product-recontext-preview-06-30', + * source: { + * prompt: 'In a modern kitchen setting.', + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response1?.generatedImages?.[0]?.image?.imageBytes); + * + * const response2 = await ai.models.recontextImage({ + * model: 'virtual-try-on-preview-08-04', + * source: { + * personImage: personImage, + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response2?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + recontextImage(params: types.RecontextImageParameters): Promise; + /** + * Segments an image, creating a mask of a specified area. + * + * @param params - The parameters for segmenting an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.segmentImage({ + * model: 'image-segmentation-001', + * source: { + * image: image, + * }, + * config: { + * mode: 'foreground', + * }, + * }); + * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes); + * ``` + */ + segmentImage(params: types.SegmentImageParameters): Promise; + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + get(params: types.GetModelParameters): Promise; + private listInternal; + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + update(params: types.UpdateModelParameters): Promise; + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + delete(params: types.DeleteModelParameters): Promise; + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + countTokens(params: types.CountTokensParameters): Promise; + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + computeTokens(params: types.ComputeTokensParameters): Promise; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + private generateVideosInternal; +} + +/** Config for model selection. */ +export declare interface ModelSelectionConfig { + /** Options for feature selection preference. */ + featureSelectionPreference?: FeatureSelectionPreference; +} + +/** The configuration for the multi-speaker setup. */ +export declare interface MultiSpeakerVoiceConfig { + /** The configuration for the speaker to use. */ + speakerVoiceConfigs?: SpeakerVoiceConfig[]; +} + +/** The mode of music generation. */ +export declare enum MusicGenerationMode { + /** + * Rely on the server default generation mode. + */ + MUSIC_GENERATION_MODE_UNSPECIFIED = "MUSIC_GENERATION_MODE_UNSPECIFIED", + /** + * Steer text prompts to regions of latent space with higher quality + music. + */ + QUALITY = "QUALITY", + /** + * Steer text prompts to regions of latent space with a larger + diversity of music. + */ + DIVERSITY = "DIVERSITY", + /** + * Steer text prompts to regions of latent space more likely to + generate music with vocals. + */ + VOCALIZATION = "VOCALIZATION" +} + +/** A long-running operation. */ +export declare interface Operation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The response if the operation is successful. */ + response?: T; + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }: OperationFromAPIResponseParameters): Operation; +} + +/** Parameters of the fromAPIResponse method of the Operation class. */ +export declare interface OperationFromAPIResponseParameters { + /** The API response to be converted to an Operation. */ + apiResponse: Record; + /** Whether the API response is from Vertex AI. */ + isVertexAI: boolean; +} + +/** Parameters for the get method of the operations module. */ +export declare interface OperationGetParameters> { + /** The operation to be retrieved. */ + operation: U; + /** Used to override the default configuration. */ + config?: GetOperationConfig; +} + +export declare class Operations extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + getVideosOperation(parameters: types.OperationGetParameters): Promise; + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + get>(parameters: types.OperationGetParameters): Promise>; + private getVideosOperationInternal; + private fetchPredictVideosOperationInternal; +} + +/** Required. Outcome of the code execution. */ +export declare enum Outcome { + /** + * Unspecified status. This value should not be used. + */ + OUTCOME_UNSPECIFIED = "OUTCOME_UNSPECIFIED", + /** + * Code execution completed successfully. + */ + OUTCOME_OK = "OUTCOME_OK", + /** + * Code execution finished but with a failure. `stderr` should contain the reason. + */ + OUTCOME_FAILED = "OUTCOME_FAILED", + /** + * Code execution ran for too long, and was cancelled. There may or may not be a partial output present. + */ + OUTCOME_DEADLINE_EXCEEDED = "OUTCOME_DEADLINE_EXCEEDED" +} + +export declare enum PagedItem { + PAGED_ITEM_BATCH_JOBS = "batchJobs", + PAGED_ITEM_MODELS = "models", + PAGED_ITEM_TUNING_JOBS = "tuningJobs", + PAGED_ITEM_FILES = "files", + PAGED_ITEM_CACHED_CONTENTS = "cachedContents" +} + +declare interface PagedItemConfig { + config?: { + pageToken?: string; + pageSize?: number; + }; +} + +declare interface PagedItemResponse { + nextPageToken?: string; + sdkHttpResponse?: types.HttpResponse; + batchJobs?: T[]; + models?: T[]; + tuningJobs?: T[]; + files?: T[]; + cachedContents?: T[]; +} + +/** + * Pager class for iterating through paginated results. + */ +export declare class Pager implements AsyncIterable { + private nameInternal; + private pageInternal; + private paramsInternal; + private pageInternalSize; + private sdkHttpResponseInternal?; + protected requestInternal: (params: PagedItemConfig) => Promise>; + protected idxInternal: number; + constructor(name: PagedItem, request: (params: PagedItemConfig) => Promise>, response: PagedItemResponse, params: PagedItemConfig); + private init; + private initNextPage; + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page(): T[]; + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name(): PagedItem; + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize(): number; + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse(): types.HttpResponse | undefined; + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params(): PagedItemConfig; + /** + * Returns the total number of items in the current page. + */ + get pageLength(): number; + /** + * Returns the item at the given index. + */ + getItem(index: number): T; + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator](): AsyncIterator; + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + nextPage(): Promise; + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage(): boolean; +} + +/** A datatype containing media content. + + Exactly one field within a Part should be set, representing the specific type + of content being conveyed. Using multiple fields within the same `Part` + instance is considered invalid. + */ +export declare interface Part { + /** Metadata for a given video. */ + videoMetadata?: VideoMetadata; + /** Indicates if the part is thought from the model. */ + thought?: boolean; + /** Optional. Inlined bytes data. */ + inlineData?: Blob_2; + /** Optional. URI based data. */ + fileData?: FileData; + /** An opaque signature for the thought so it can be reused in subsequent requests. + * @remarks Encoded as base64 string. */ + thoughtSignature?: string; + /** Optional. Result of executing the [ExecutableCode]. */ + codeExecutionResult?: CodeExecutionResult; + /** Optional. Code generated by the model that is meant to be executed. */ + executableCode?: ExecutableCode; + /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */ + functionCall?: FunctionCall; + /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */ + functionResponse?: FunctionResponse; + /** Optional. Text part (can be code). */ + text?: string; +} + +export declare type PartListUnion = PartUnion[] | PartUnion; + +/** Tuning spec for Partner models. */ +export declare interface PartnerModelTuningSpec { + /** Hyperparameters for tuning. The accepted hyper_parameters and their valid range of values will differ depending on the base model. */ + hyperParameters?: Record; + /** Required. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDatasetUri?: string; + /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */ + validationDatasetUri?: string; +} + +export declare type PartUnion = Part | string; + +/** Enum that controls the generation of people. */ +export declare enum PersonGeneration { + /** + * Block generation of images of people. + */ + DONT_ALLOW = "DONT_ALLOW", + /** + * Generate images of adults, but not children. + */ + ALLOW_ADULT = "ALLOW_ADULT", + /** + * Generate images that include adults and children. + */ + ALLOW_ALL = "ALLOW_ALL" +} + +/** The configuration for the prebuilt speaker to use. */ +export declare interface PrebuiltVoiceConfig { + /** The name of the prebuilt voice to use. */ + voiceName?: string; +} + +/** Statistics computed for datasets used for preference optimization. */ +export declare interface PreferenceOptimizationDataStats { + /** Output only. Dataset distributions for scores variance per example. */ + scoreVariancePerExampleDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for scores. */ + scoresDistribution?: DatasetDistribution; + /** Output only. Number of billable tokens in the tuning dataset. */ + totalBillableTokenCount?: string; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user examples in the training dataset. */ + userDatasetExamples?: GeminiPreferenceExample[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: DatasetDistribution; +} + +/** A pre-tuned model for continuous tuning. */ +export declare interface PreTunedModel { + /** Output only. The name of the base model this PreTunedModel was tuned from. */ + baseModel?: string; + /** Optional. The source checkpoint id. If not specified, the default checkpoint will be used. */ + checkpointId?: string; + /** The resource name of the Model. E.g., a model resource name with a specified version id or alias: `projects/{project}/locations/{location}/models/{model}@{version_id}` `projects/{project}/locations/{location}/models/{model}@{alias}` Or, omit the version id to use the default version: `projects/{project}/locations/{location}/models/{model}` */ + tunedModelName?: string; +} + +/** Config for proactivity features. */ +export declare interface ProactivityConfig { + /** If enabled, the model can reject responding to the last prompt. For + example, this allows the model to ignore out of context speech or to stay + silent if the user did not make a request, yet. */ + proactiveAudio?: boolean; +} + +/** An image of the product. */ +export declare interface ProductImage { + /** An image of the product to be recontextualized. */ + productImage?: Image_2; +} + +/** A RagChunk includes the content of a chunk of a RagFile, and associated metadata. */ +export declare interface RagChunk { + /** If populated, represents where the chunk starts and ends in the document. */ + pageSpan?: RagChunkPageSpan; + /** The content of the chunk. */ + text?: string; +} + +/** Represents where the chunk starts and ends in the document. */ +export declare interface RagChunkPageSpan { + /** Page where chunk starts in the document. Inclusive. 1-indexed. */ + firstPage?: number; + /** Page where chunk ends in the document. Inclusive. 1-indexed. */ + lastPage?: number; +} + +/** Specifies the context retrieval config. */ +export declare interface RagRetrievalConfig { + /** Optional. Config for filters. */ + filter?: RagRetrievalConfigFilter; + /** Optional. Config for Hybrid Search. */ + hybridSearch?: RagRetrievalConfigHybridSearch; + /** Optional. Config for ranking and reranking. */ + ranking?: RagRetrievalConfigRanking; + /** Optional. The number of contexts to retrieve. */ + topK?: number; +} + +/** Config for filters. */ +export declare interface RagRetrievalConfigFilter { + /** Optional. String for metadata filtering. */ + metadataFilter?: string; + /** Optional. Only returns contexts with vector distance smaller than the threshold. */ + vectorDistanceThreshold?: number; + /** Optional. Only returns contexts with vector similarity larger than the threshold. */ + vectorSimilarityThreshold?: number; +} + +/** Config for Hybrid Search. */ +export declare interface RagRetrievalConfigHybridSearch { + /** Optional. Alpha value controls the weight between dense and sparse vector search results. The range is [0, 1], while 0 means sparse vector search only and 1 means dense vector search only. The default value is 0.5 which balances sparse and dense vector search equally. */ + alpha?: number; +} + +/** Config for ranking and reranking. */ +export declare interface RagRetrievalConfigRanking { + /** Optional. Config for LlmRanker. */ + llmRanker?: RagRetrievalConfigRankingLlmRanker; + /** Optional. Config for Rank Service. */ + rankService?: RagRetrievalConfigRankingRankService; +} + +/** Config for LlmRanker. */ +export declare interface RagRetrievalConfigRankingLlmRanker { + /** Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */ + modelName?: string; +} + +/** Config for Rank Service. */ +export declare interface RagRetrievalConfigRankingRankService { + /** Optional. The model name of the rank service. Format: `semantic-ranker-512@latest` */ + modelName?: string; +} + +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +export declare class RawReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface RealtimeInputConfig { + /** If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals. */ + automaticActivityDetection?: AutomaticActivityDetection; + /** Defines what effect activity has. */ + activityHandling?: ActivityHandling; + /** Defines which input is included in the user's turn. */ + turnCoverage?: TurnCoverage; +} + +/** Configuration for recontextualizing an image. */ +export declare interface RecontextImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Number of images to generate. */ + numberOfImages?: number; + /** The number of sampling steps. A higher value has better image + quality, while a lower value has better latency. */ + baseSteps?: number; + /** Cloud Storage URI used to store the generated images. */ + outputGcsUri?: string; + /** Random seed for image generation. */ + seed?: number; + /** Filter level for safety filtering. */ + safetyFilterLevel?: SafetyFilterLevel; + /** Whether allow to generate person images, and restrict to specific + ages. */ + personGeneration?: PersonGeneration; + /** MIME type of the generated image. */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). */ + outputCompressionQuality?: number; + /** Whether to use the prompt rewriting logic. */ + enhancePrompt?: boolean; +} + +/** The parameters for recontextualizing an image. */ +export declare interface RecontextImageParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** A set of source input(s) for image recontextualization. */ + source: RecontextImageSource; + /** Configuration for image recontextualization. */ + config?: RecontextImageConfig; +} + +/** The output images response. */ +export declare class RecontextImageResponse { + /** List of generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** A set of source input(s) for image recontextualization. */ +export declare interface RecontextImageSource { + /** A text prompt for guiding the model during image + recontextualization. Not supported for Virtual Try-On. */ + prompt?: string; + /** Image of the person or subject who will be wearing the + product(s). */ + personImage?: Image_2; + /** A list of product images. */ + productImages?: ProductImage[]; +} + +export declare type ReferenceImage = RawReferenceImage | MaskReferenceImage | ControlReferenceImage | StyleReferenceImage | SubjectReferenceImage; + +/** Private class that represents a Reference image that is sent to API. */ +declare interface ReferenceImageAPIInternal { + /** The reference image for the editing operation. */ + referenceImage?: types.Image; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the mask reference image. */ + maskImageConfig?: types.MaskReferenceConfig; + /** Configuration for the control reference image. */ + controlImageConfig?: types.ControlReferenceConfig; + /** Configuration for the style reference image. */ + styleImageConfig?: types.StyleReferenceConfig; + /** Configuration for the subject reference image. */ + subjectImageConfig?: types.SubjectReferenceConfig; +} + +/** Represents a recorded session. */ +export declare interface ReplayFile { + replayId?: string; + interactions?: ReplayInteraction[]; +} + +/** Represents a single interaction, request and response in a replay. */ +export declare interface ReplayInteraction { + request?: ReplayRequest; + response?: ReplayResponse; +} + +/** Represents a single request in a replay. */ +export declare interface ReplayRequest { + method?: string; + url?: string; + headers?: Record; + bodySegments?: Record[]; +} + +/** Represents a single response in a replay. */ +export declare class ReplayResponse { + statusCode?: number; + headers?: Record; + bodySegments?: Record[]; + sdkResponseSegments?: Record[]; +} + +/** Defines a retrieval tool that model can call to access external knowledge. */ +export declare interface Retrieval { + /** Optional. Deprecated. This option is no longer supported. */ + disableAttribution?: boolean; + /** Use data source powered by external API for grounding. */ + externalApi?: ExternalApi; + /** Set to use data source powered by Vertex AI Search. */ + vertexAiSearch?: VertexAISearch; + /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */ + vertexRagStore?: VertexRagStore; +} + +/** Retrieval config. + */ +export declare interface RetrievalConfig { + /** Optional. The location of the user. */ + latLng?: LatLng; + /** The language code of the user. */ + languageCode?: string; +} + +/** Metadata related to retrieval in the grounding flow. */ +export declare interface RetrievalMetadata { + /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */ + googleSearchDynamicRetrievalScore?: number; +} + +/** Safety attributes of a GeneratedImage or the user-provided prompt. */ +export declare interface SafetyAttributes { + /** List of RAI categories. + */ + categories?: string[]; + /** List of scores of each categories. + */ + scores?: number[]; + /** Internal use only. + */ + contentType?: string; +} + +/** Enum that controls the safety filter level for objectionable content. */ +export declare enum SafetyFilterLevel { + BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", + BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", + BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", + BLOCK_NONE = "BLOCK_NONE" +} + +/** Safety rating corresponding to the generated content. */ +export declare interface SafetyRating { + /** Output only. Indicates whether the content was filtered out because of this rating. */ + blocked?: boolean; + /** Output only. Harm category. */ + category?: HarmCategory; + /** Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If minors are detected in the output image, the threshold of each safety category will be overwritten if user sets a lower threshold. */ + overwrittenThreshold?: HarmBlockThreshold; + /** Output only. Harm probability levels in the content. */ + probability?: HarmProbability; + /** Output only. Harm probability score. */ + probabilityScore?: number; + /** Output only. Harm severity levels in the content. */ + severity?: HarmSeverity; + /** Output only. Harm severity score. */ + severityScore?: number; +} + +/** Safety settings. */ +export declare interface SafetySetting { + /** Determines if the harm block method uses probability or probability + and severity scores. */ + method?: HarmBlockMethod; + /** Required. Harm category. */ + category?: HarmCategory; + /** Required. The harm block threshold. */ + threshold?: HarmBlockThreshold; +} + +/** Scale of the generated music. */ +export declare enum Scale { + /** + * Default value. This value is unused. + */ + SCALE_UNSPECIFIED = "SCALE_UNSPECIFIED", + /** + * C major or A minor. + */ + C_MAJOR_A_MINOR = "C_MAJOR_A_MINOR", + /** + * Db major or Bb minor. + */ + D_FLAT_MAJOR_B_FLAT_MINOR = "D_FLAT_MAJOR_B_FLAT_MINOR", + /** + * D major or B minor. + */ + D_MAJOR_B_MINOR = "D_MAJOR_B_MINOR", + /** + * Eb major or C minor + */ + E_FLAT_MAJOR_C_MINOR = "E_FLAT_MAJOR_C_MINOR", + /** + * E major or Db minor. + */ + E_MAJOR_D_FLAT_MINOR = "E_MAJOR_D_FLAT_MINOR", + /** + * F major or D minor. + */ + F_MAJOR_D_MINOR = "F_MAJOR_D_MINOR", + /** + * Gb major or Eb minor. + */ + G_FLAT_MAJOR_E_FLAT_MINOR = "G_FLAT_MAJOR_E_FLAT_MINOR", + /** + * G major or E minor. + */ + G_MAJOR_E_MINOR = "G_MAJOR_E_MINOR", + /** + * Ab major or F minor. + */ + A_FLAT_MAJOR_F_MINOR = "A_FLAT_MAJOR_F_MINOR", + /** + * A major or Gb minor. + */ + A_MAJOR_G_FLAT_MINOR = "A_MAJOR_G_FLAT_MINOR", + /** + * Bb major or G minor. + */ + B_FLAT_MAJOR_G_MINOR = "B_FLAT_MAJOR_G_MINOR", + /** + * B major or Ab minor. + */ + B_MAJOR_A_FLAT_MINOR = "B_MAJOR_A_FLAT_MINOR" +} + +/** Schema is used to define the format of input/output data. + + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may + be added in the future as needed. + */ +export declare interface Schema { + /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */ + anyOf?: Schema[]; + /** Optional. Default value of the data. */ + default?: unknown; + /** Optional. The description of the data. */ + description?: string; + /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:["101", "201", "301"]} */ + enum?: string[]; + /** Optional. Example of the object. Will only populated when the object is the root. */ + example?: unknown; + /** Optional. The format of the data. Supported formats: for NUMBER type: "float", "double" for INTEGER type: "int32", "int64" for STRING type: "email", "byte", etc */ + format?: string; + /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */ + items?: Schema; + /** Optional. Maximum number of the elements for Type.ARRAY. */ + maxItems?: string; + /** Optional. Maximum length of the Type.STRING */ + maxLength?: string; + /** Optional. Maximum number of the properties for Type.OBJECT. */ + maxProperties?: string; + /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */ + maximum?: number; + /** Optional. Minimum number of the elements for Type.ARRAY. */ + minItems?: string; + /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */ + minLength?: string; + /** Optional. Minimum number of the properties for Type.OBJECT. */ + minProperties?: string; + /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */ + minimum?: number; + /** Optional. Indicates if the value may be null. */ + nullable?: boolean; + /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */ + pattern?: string; + /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */ + properties?: Record; + /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */ + propertyOrdering?: string[]; + /** Optional. Required properties of Type.OBJECT. */ + required?: string[]; + /** Optional. The title of the Schema. */ + title?: string; + /** Optional. The type of the data. */ + type?: Type; +} + +export declare type SchemaUnion = Schema | unknown; + +/** An image mask representing a brush scribble. */ +export declare interface ScribbleImage { + /** The brush scribble to guide segmentation. Valid for the interactive mode. */ + image?: Image_2; +} + +/** Google search entry point. */ +export declare interface SearchEntryPoint { + /** Optional. Web content snippet that can be embedded in a web page or an app webview. */ + renderedContent?: string; + /** Optional. Base64 encoded JSON representing array of tuple. + * @remarks Encoded as base64 string. */ + sdkBlob?: string; +} + +/** Segment of the content. */ +export declare interface Segment { + /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */ + endIndex?: number; + /** Output only. The index of a Part object within its parent Content object. */ + partIndex?: number; + /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */ + startIndex?: number; + /** Output only. The text corresponding to the segment from the response. */ + text?: string; +} + +/** Configuration for segmenting an image. */ +export declare interface SegmentImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The segmentation mode to use. */ + mode?: SegmentMode; + /** The maximum number of predictions to return up to, by top + confidence score. */ + maxPredictions?: number; + /** The confidence score threshold for the detections as a decimal + value. Only predictions with a confidence score higher than this + threshold will be returned. */ + confidenceThreshold?: number; + /** A decimal value representing how much dilation to apply to the + masks. 0 for no dilation. 1.0 means the masked area covers the whole + image. */ + maskDilation?: number; + /** The binary color threshold to apply to the masks. The threshold + can be set to a decimal value between 0 and 255 non-inclusive. + Set to -1 for no binary color thresholding. */ + binaryColorThreshold?: number; +} + +/** The parameters for segmenting an image. */ +export declare interface SegmentImageParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** A set of source input(s) for image segmentation. */ + source: SegmentImageSource; + /** Configuration for image segmentation. */ + config?: SegmentImageConfig; +} + +/** The output images response. */ +export declare class SegmentImageResponse { + /** List of generated image masks. + */ + generatedMasks?: GeneratedImageMask[]; +} + +/** A set of source input(s) for image segmentation. */ +export declare interface SegmentImageSource { + /** A text prompt for guiding the model during image segmentation. + Required for prompt mode and semantic mode, disallowed for other modes. */ + prompt?: string; + /** The image to be segmented. */ + image?: Image_2; + /** The brush scribble to guide segmentation. + Required for the interactive mode, disallowed for other modes. */ + scribbleImage?: ScribbleImage; +} + +/** Enum that represents the segmentation mode. */ +export declare enum SegmentMode { + FOREGROUND = "FOREGROUND", + BACKGROUND = "BACKGROUND", + PROMPT = "PROMPT", + SEMANTIC = "SEMANTIC", + INTERACTIVE = "INTERACTIVE" +} + +/** Parameters for sending a message within a chat session. + + These parameters are used with the `chat.sendMessage()` method. + */ +export declare interface SendMessageParameters { + /** The message to send to the model. + + The SDK will combine all parts into a single 'user' content to send to + the model. + */ + message: PartListUnion; + /** Config for this specific request. + + Please note that the per-request config does not change the chat level + config, nor inherit from it. If you intend to use some values from the + chat's default config, you must explicitly copy them into this per-request + config. + */ + config?: GenerateContentConfig; +} + +/** + Represents a connection to the API. + + @experimental + */ +export declare class Session { + readonly conn: WebSocket_2; + private readonly apiClient; + constructor(conn: WebSocket_2, apiClient: ApiClient); + private tLiveClientContent; + private tLiveClienttToolResponse; + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params: types.LiveSendClientContentParameters): void; + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params: types.LiveSendRealtimeInputParameters): void; + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params: types.LiveSendToolResponseParameters): void; + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close(): void; +} + +/** Configuration of session resumption mechanism. + + Included in `LiveConnectConfig.session_resumption`. If included server + will send `LiveServerSessionResumptionUpdate` messages. + */ +export declare interface SessionResumptionConfig { + /** Session resumption handle of previous session (session to restore). + + If not present new session will be started. */ + handle?: string; + /** If set the server will send `last_consumed_client_message_index` in the `session_resumption_update` messages to allow for transparent reconnections. */ + transparent?: boolean; +} + +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +export declare function setDefaultBaseUrls(baseUrlParams: BaseUrlParameters): void; + +/** Context window will be truncated by keeping only suffix of it. + + Context window will always be cut at start of USER role turn. System + instructions and `BidiGenerateContentSetup.prefix_turns` will not be + subject to the sliding window mechanism, they will always stay at the + beginning of context window. + */ +export declare interface SlidingWindow { + /** Session reduction target -- how many tokens we should keep. Window shortening operation has some latency costs, so we should avoid running it on every turn. Should be < trigger_tokens. If not set, trigger_tokens/2 is assumed. */ + targetTokens?: string; +} + +/** The configuration for the speaker to use. */ +export declare interface SpeakerVoiceConfig { + /** The name of the speaker to use. Should be the same as in the + prompt. */ + speaker?: string; + /** The configuration for the voice to use. */ + voiceConfig?: VoiceConfig; +} + +/** The speech generation configuration. */ +export declare interface SpeechConfig { + /** The configuration for the speaker to use. + */ + voiceConfig?: VoiceConfig; + /** The configuration for the multi-speaker setup. + It is mutually exclusive with the voice_config field. + */ + multiSpeakerVoiceConfig?: MultiSpeakerVoiceConfig; + /** Language code (ISO 639. e.g. en-US) for the speech synthesization. + Only available for Live API. + */ + languageCode?: string; +} + +export declare type SpeechConfigUnion = SpeechConfig | string; + +/** Start of speech sensitivity. */ +export declare enum StartSensitivity { + /** + * The default is START_SENSITIVITY_LOW. + */ + START_SENSITIVITY_UNSPECIFIED = "START_SENSITIVITY_UNSPECIFIED", + /** + * Automatic detection will detect the start of speech more often. + */ + START_SENSITIVITY_HIGH = "START_SENSITIVITY_HIGH", + /** + * Automatic detection will detect the start of speech less often. + */ + START_SENSITIVITY_LOW = "START_SENSITIVITY_LOW" +} + +/** Configuration for a Style reference image. */ +export declare interface StyleReferenceConfig { + /** A text description of the style to use for the generated image. */ + styleDescription?: string; +} + +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +export declare class StyleReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the style reference image. */ + config?: StyleReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Configuration for a Subject reference image. */ +export declare interface SubjectReferenceConfig { + /** The subject type of a subject reference image. */ + subjectType?: SubjectReferenceType; + /** Subject description for the image. */ + subjectDescription?: string; +} + +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +export declare class SubjectReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the subject reference image. */ + config?: SubjectReferenceConfig; + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the subject type of a subject reference image. */ +export declare enum SubjectReferenceType { + SUBJECT_TYPE_DEFAULT = "SUBJECT_TYPE_DEFAULT", + SUBJECT_TYPE_PERSON = "SUBJECT_TYPE_PERSON", + SUBJECT_TYPE_ANIMAL = "SUBJECT_TYPE_ANIMAL", + SUBJECT_TYPE_PRODUCT = "SUBJECT_TYPE_PRODUCT" +} + +/** Hyperparameters for SFT. */ +export declare interface SupervisedHyperParameters { + /** Optional. Adapter size for tuning. */ + adapterSize?: AdapterSize; + /** Optional. Batch size for tuning. This feature is only available for open source models. */ + batchSize?: string; + /** Optional. Number of complete passes the model makes over the entire training dataset during training. */ + epochCount?: string; + /** Optional. Learning rate for tuning. Mutually exclusive with `learning_rate_multiplier`. This feature is only available for open source models. */ + learningRate?: number; + /** Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with `learning_rate`. This feature is only available for 1P models. */ + learningRateMultiplier?: number; +} + +/** Dataset distribution for Supervised Tuning. */ +export declare interface SupervisedTuningDatasetDistribution { + /** Output only. Sum of a given population of values that are billable. */ + billableSum?: string; + /** Output only. Defines the histogram bucket. */ + buckets?: SupervisedTuningDatasetDistributionDatasetBucket[]; + /** Output only. The maximum of the population values. */ + max?: number; + /** Output only. The arithmetic mean of the values in the population. */ + mean?: number; + /** Output only. The median of the values in the population. */ + median?: number; + /** Output only. The minimum of the population values. */ + min?: number; + /** Output only. The 5th percentile of the values in the population. */ + p5?: number; + /** Output only. The 95th percentile of the values in the population. */ + p95?: number; + /** Output only. Sum of a given population of values. */ + sum?: string; +} + +/** Dataset bucket used to create a histogram for the distribution given a population of values. */ +export declare interface SupervisedTuningDatasetDistributionDatasetBucket { + /** Output only. Number of values in the bucket. */ + count?: number; + /** Output only. Left bound of the bucket. */ + left?: number; + /** Output only. Right bound of the bucket. */ + right?: number; +} + +/** Tuning data statistics for Supervised Tuning. */ +export declare interface SupervisedTuningDataStats { + /** Output only. For each index in `truncated_example_indices`, the user-facing reason why the example was dropped. */ + droppedExampleReasons?: string[]; + /** Output only. Number of billable characters in the tuning dataset. */ + totalBillableCharacterCount?: string; + /** Output only. Number of billable tokens in the tuning dataset. */ + totalBillableTokenCount?: string; + /** Output only. The number of examples in the dataset that have been dropped. An example can be dropped for reasons including: too many tokens, contains an invalid image, contains too many images, etc. */ + totalTruncatedExampleCount?: string; + /** Output only. Number of tuning characters in the tuning dataset. */ + totalTuningCharacterCount?: string; + /** Output only. A partial sample of the indices (starting from 1) of the dropped examples. */ + truncatedExampleIndices?: string[]; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user messages in the training dataset uri. */ + userDatasetExamples?: Content[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: SupervisedTuningDatasetDistribution; + /** Output only. Dataset distributions for the messages per example. */ + userMessagePerExampleDistribution?: SupervisedTuningDatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: SupervisedTuningDatasetDistribution; +} + +/** Tuning Spec for Supervised Tuning for first party models. */ +export declare interface SupervisedTuningSpec { + /** Optional. If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. Default is false. */ + exportLastCheckpointOnly?: boolean; + /** Optional. Hyperparameters for SFT. */ + hyperParameters?: SupervisedHyperParameters; + /** Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */ + trainingDatasetUri?: string; + /** Tuning mode. */ + tuningMode?: TuningMode; + /** Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */ + validationDatasetUri?: string; +} + +export declare interface TestTableFile { + comment?: string; + testMethod?: string; + parameterNames?: string[]; + testTable?: TestTableItem[]; +} + +export declare interface TestTableItem { + /** The name of the test. This is used to derive the replay id. */ + name?: string; + /** The parameters to the test. Use pydantic models. */ + parameters?: Record; + /** Expects an exception for MLDev matching the string. */ + exceptionIfMldev?: string; + /** Expects an exception for Vertex matching the string. */ + exceptionIfVertex?: string; + /** Use if you don't want to use the default replay id which is derived from the test name. */ + overrideReplayId?: string; + /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */ + hasUnion?: boolean; + /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */ + skipInApiMode?: string; + /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */ + ignoreKeys?: string[]; +} + +/** The thinking features configuration. */ +export declare interface ThinkingConfig { + /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available. + */ + includeThoughts?: boolean; + /** Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent. + */ + thinkingBudget?: number; +} + +export declare class Tokens extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + create(params: types.CreateAuthTokenParameters): Promise; +} + +/** Tokens info with a list of tokens and the corresponding list of token ids. */ +export declare interface TokensInfo { + /** Optional. Optional fields for the role from the corresponding Content. */ + role?: string; + /** A list of token ids from the input. */ + tokenIds?: string[]; + /** A list of tokens from the input. + * @remarks Encoded as base64 string. */ + tokens?: string[]; +} + +/** Tool details of a tool that the model may use to generate a response. */ +export declare interface Tool { + /** List of function declarations that the tool supports. */ + functionDeclarations?: FunctionDeclaration[]; + /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */ + retrieval?: Retrieval; + /** Optional. Google Search tool type. Specialized retrieval tool + that is powered by Google Search. */ + googleSearch?: GoogleSearch; + /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */ + googleSearchRetrieval?: GoogleSearchRetrieval; + /** Optional. Enterprise web search tool type. Specialized retrieval + tool that is powered by Vertex AI Search and Sec4 compliance. */ + enterpriseWebSearch?: EnterpriseWebSearch; + /** Optional. Google Maps tool type. Specialized retrieval tool + that is powered by Google Maps. */ + googleMaps?: GoogleMaps; + /** Optional. Tool to support URL context retrieval. */ + urlContext?: UrlContext; + /** Optional. Tool to support the model interacting directly with the + computer. If enabled, it automatically populates computer-use specific + Function Declarations. */ + computerUse?: ToolComputerUse; + /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. */ + codeExecution?: ToolCodeExecution; +} + +/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */ +export declare interface ToolCodeExecution { +} + +/** Tool to support computer use. */ +export declare interface ToolComputerUse { + /** Required. The environment being operated. */ + environment?: Environment; +} + +/** Tool config. + + This config is shared for all tools provided in the request. + */ +export declare interface ToolConfig { + /** Optional. Function calling config. */ + functionCallingConfig?: FunctionCallingConfig; + /** Optional. Retrieval config. */ + retrievalConfig?: RetrievalConfig; +} + +export declare type ToolListUnion = ToolUnion[]; + +export declare type ToolUnion = Tool | CallableTool; + +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +export declare enum TrafficType { + /** + * Unspecified request traffic type. + */ + TRAFFIC_TYPE_UNSPECIFIED = "TRAFFIC_TYPE_UNSPECIFIED", + /** + * Type for Pay-As-You-Go traffic. + */ + ON_DEMAND = "ON_DEMAND", + /** + * Type for Provisioned Throughput traffic. + */ + PROVISIONED_THROUGHPUT = "PROVISIONED_THROUGHPUT" +} + +/** Audio transcription in Server Conent. */ +export declare interface Transcription { + /** Transcription text. + */ + text?: string; + /** The bool indicates the end of the transcription. + */ + finished?: boolean; +} + +export declare interface TunedModel { + /** Output only. The resource name of the TunedModel. Format: `projects/{project}/locations/{location}/models/{model}@{version_id}` When tuning from a base model, the version_id will be 1. For continuous tuning, the version id will be incremented by 1 from the last version id in the parent model. E.g., `projects/{project}/locations/{location}/models/{model}@{last_version_id + 1}` */ + model?: string; + /** Output only. A resource name of an Endpoint. Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. */ + endpoint?: string; + /** The checkpoints associated with this TunedModel. + This field is only populated for tuning jobs that enable intermediate + checkpoints. */ + checkpoints?: TunedModelCheckpoint[]; +} + +/** TunedModelCheckpoint for the Tuned Model of a Tuning Job. */ +export declare interface TunedModelCheckpoint { + /** The ID of the checkpoint. + */ + checkpointId?: string; + /** The epoch of the checkpoint. + */ + epoch?: string; + /** The step of the checkpoint. + */ + step?: string; + /** The Endpoint resource name that the checkpoint is deployed to. + Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. + */ + endpoint?: string; +} + +/** A tuned machine learning model. */ +export declare interface TunedModelInfo { + /** ID of the base model that you want to tune. */ + baseModel?: string; + /** Date and time when the base model was created. */ + createTime?: string; + /** Date and time when the base model was last updated. */ + updateTime?: string; +} + +/** Supervised fine-tuning training dataset. */ +export declare interface TuningDataset { + /** GCS URI of the file containing training dataset in JSONL format. */ + gcsUri?: string; + /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */ + vertexDatasetResource?: string; + /** Inline examples with simple input/output text. */ + examples?: TuningExample[]; +} + +/** The tuning data statistic values for TuningJob. */ +export declare interface TuningDataStats { + /** Output only. Statistics for distillation. */ + distillationDataStats?: DistillationDataStats; + /** Output only. Statistics for preference optimization. */ + preferenceOptimizationDataStats?: PreferenceOptimizationDataStats; + /** The SFT Tuning data stats. */ + supervisedTuningDataStats?: SupervisedTuningDataStats; +} + +export declare interface TuningExample { + /** Text model input. */ + textInput?: string; + /** The expected model output. */ + output?: string; +} + +/** A tuning job. */ +export declare interface TuningJob { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}` */ + name?: string; + /** Output only. The detailed state of the job. */ + state?: JobState; + /** Output only. Time when the TuningJob was created. */ + createTime?: string; + /** Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING` state. */ + startTime?: string; + /** Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`. */ + endTime?: string; + /** Output only. Time when the TuningJob was most recently updated. */ + updateTime?: string; + /** Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. */ + error?: GoogleRpcStatus; + /** Optional. The description of the TuningJob. */ + description?: string; + /** The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */ + baseModel?: string; + /** Output only. The tuned model resources associated with this TuningJob. */ + tunedModel?: TunedModel; + /** The pre-tuned model for continuous tuning. */ + preTunedModel?: PreTunedModel; + /** Tuning Spec for Supervised Fine Tuning. */ + supervisedTuningSpec?: SupervisedTuningSpec; + /** Output only. The tuning data statistics associated with this TuningJob. */ + tuningDataStats?: TuningDataStats; + /** Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with the provided encryption key. */ + encryptionSpec?: EncryptionSpec; + /** Tuning Spec for open sourced and third party Partner models. */ + partnerModelTuningSpec?: PartnerModelTuningSpec; + /** Optional. The user-provided path to custom model weights. Set this field to tune a custom model. The path must be a Cloud Storage directory that contains the model weights in .safetensors format along with associated model metadata files. If this field is set, the base_model field must still be set to indicate which base model the custom model is derived from. This feature is only available for open source models. */ + customBaseModel?: string; + /** Output only. The Experiment associated with this TuningJob. */ + experiment?: string; + /** Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. */ + labels?: Record; + /** Optional. Cloud Storage path to the directory where tuning job outputs are written to. This field is only available and required for open source models. */ + outputUri?: string; + /** Output only. The resource name of the PipelineJob associated with the TuningJob. Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`. */ + pipelineJob?: string; + /** The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission on this service account. */ + serviceAccount?: string; + /** Optional. The display name of the TunedModel. The name can be up to 128 characters long and can consist of any UTF-8 characters. */ + tunedModelDisplayName?: string; +} + +/** Tuning mode. */ +export declare enum TuningMode { + /** + * Tuning mode is unspecified. + */ + TUNING_MODE_UNSPECIFIED = "TUNING_MODE_UNSPECIFIED", + /** + * Full fine-tuning mode. + */ + TUNING_MODE_FULL = "TUNING_MODE_FULL", + /** + * PEFT adapter tuning mode. + */ + TUNING_MODE_PEFT_ADAPTER = "TUNING_MODE_PEFT_ADAPTER" +} + +/** A long-running operation. */ +export declare interface TuningOperation { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; +} + +declare class Tunings extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + get: (params: types.GetTuningJobParameters) => Promise; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + list: (params?: types.ListTuningJobsParameters) => Promise>; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + tune: (params: types.CreateTuningJobParameters) => Promise; + private getInternal; + private listInternal; + private tuneInternal; + private tuneMldevInternal; +} + +export declare interface TuningValidationDataset { + /** GCS URI of the file containing validation dataset in JSONL format. */ + gcsUri?: string; + /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */ + vertexDatasetResource?: string; +} + +/** Options about which input is included in the user's turn. */ +export declare enum TurnCoverage { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TURN_COVERAGE_UNSPECIFIED = "TURN_COVERAGE_UNSPECIFIED", + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TURN_INCLUDES_ONLY_ACTIVITY = "TURN_INCLUDES_ONLY_ACTIVITY", + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TURN_INCLUDES_ALL_INPUT = "TURN_INCLUDES_ALL_INPUT" +} + +/** Optional. The type of the data. */ +export declare enum Type { + /** + * Not specified, should not be used. + */ + TYPE_UNSPECIFIED = "TYPE_UNSPECIFIED", + /** + * OpenAPI string type + */ + STRING = "STRING", + /** + * OpenAPI number type + */ + NUMBER = "NUMBER", + /** + * OpenAPI integer type + */ + INTEGER = "INTEGER", + /** + * OpenAPI boolean type + */ + BOOLEAN = "BOOLEAN", + /** + * OpenAPI array type + */ + ARRAY = "ARRAY", + /** + * OpenAPI object type + */ + OBJECT = "OBJECT", + /** + * Null type + */ + NULL = "NULL" +} + +declare namespace types { + export { + createPartFromUri, + createPartFromText, + createPartFromFunctionCall, + createPartFromFunctionResponse, + createPartFromBase64, + createPartFromCodeExecutionResult, + createPartFromExecutableCode, + createUserContent, + createModelContent, + Outcome, + Language, + Type, + HarmCategory, + HarmBlockMethod, + HarmBlockThreshold, + Mode, + AuthType, + ApiSpec, + UrlRetrievalStatus, + FinishReason, + HarmProbability, + HarmSeverity, + BlockedReason, + TrafficType, + Modality, + MediaResolution, + JobState, + TuningMode, + AdapterSize, + FeatureSelectionPreference, + Behavior, + DynamicRetrievalConfigMode, + Environment, + FunctionCallingConfigMode, + SafetyFilterLevel, + PersonGeneration, + ImagePromptLanguage, + MaskReferenceMode, + ControlReferenceType, + SubjectReferenceType, + EditMode, + SegmentMode, + VideoCompressionQuality, + FileState, + FileSource, + MediaModality, + StartSensitivity, + EndSensitivity, + ActivityHandling, + TurnCoverage, + FunctionResponseScheduling, + Scale, + MusicGenerationMode, + LiveMusicPlaybackControl, + VideoMetadata, + Blob_2 as Blob, + FileData, + CodeExecutionResult, + ExecutableCode, + FunctionCall, + FunctionResponse, + Part, + Content, + HttpOptions, + Schema, + ModelSelectionConfig, + SafetySetting, + FunctionDeclaration, + Interval, + GoogleSearch, + DynamicRetrievalConfig, + GoogleSearchRetrieval, + EnterpriseWebSearch, + ApiKeyConfig, + AuthConfigGoogleServiceAccountConfig, + AuthConfigHttpBasicAuthConfig, + AuthConfigOauthConfig, + AuthConfigOidcConfig, + AuthConfig, + GoogleMaps, + UrlContext, + ToolComputerUse, + ApiAuthApiKeyConfig, + ApiAuth, + ExternalApiElasticSearchParams, + ExternalApiSimpleSearchParams, + ExternalApi, + VertexAISearchDataStoreSpec, + VertexAISearch, + VertexRagStoreRagResource, + RagRetrievalConfigFilter, + RagRetrievalConfigHybridSearch, + RagRetrievalConfigRankingLlmRanker, + RagRetrievalConfigRankingRankService, + RagRetrievalConfigRanking, + RagRetrievalConfig, + VertexRagStore, + Retrieval, + ToolCodeExecution, + Tool, + FunctionCallingConfig, + LatLng, + RetrievalConfig, + ToolConfig, + PrebuiltVoiceConfig, + VoiceConfig, + SpeakerVoiceConfig, + MultiSpeakerVoiceConfig, + SpeechConfig, + AutomaticFunctionCallingConfig, + ThinkingConfig, + GenerationConfigRoutingConfigAutoRoutingMode, + GenerationConfigRoutingConfigManualRoutingMode, + GenerationConfigRoutingConfig, + GenerateContentConfig, + GenerateContentParameters, + HttpResponse, + LiveCallbacks, + GoogleTypeDate, + Citation, + CitationMetadata, + UrlMetadata, + UrlContextMetadata, + GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution, + GroundingChunkMapsPlaceAnswerSourcesReviewSnippet, + GroundingChunkMapsPlaceAnswerSources, + GroundingChunkMaps, + RagChunkPageSpan, + RagChunk, + GroundingChunkRetrievedContext, + GroundingChunkWeb, + GroundingChunk, + Segment, + GroundingSupport, + RetrievalMetadata, + SearchEntryPoint, + GroundingMetadata, + LogprobsResultCandidate, + LogprobsResultTopCandidates, + LogprobsResult, + SafetyRating, + Candidate, + GenerateContentResponsePromptFeedback, + ModalityTokenCount, + GenerateContentResponseUsageMetadata, + GenerateContentResponse, + ReferenceImage, + EditImageParameters, + EmbedContentConfig, + EmbedContentParameters, + ContentEmbeddingStatistics, + ContentEmbedding, + EmbedContentMetadata, + EmbedContentResponse, + GenerateImagesConfig, + GenerateImagesParameters, + Image_2 as Image, + SafetyAttributes, + GeneratedImage, + GenerateImagesResponse, + MaskReferenceConfig, + ControlReferenceConfig, + StyleReferenceConfig, + SubjectReferenceConfig, + EditImageConfig, + EditImageResponse, + UpscaleImageResponse, + ProductImage, + RecontextImageSource, + RecontextImageConfig, + RecontextImageParameters, + RecontextImageResponse, + ScribbleImage, + SegmentImageSource, + SegmentImageConfig, + SegmentImageParameters, + EntityLabel, + GeneratedImageMask, + SegmentImageResponse, + GetModelConfig, + GetModelParameters, + Endpoint, + TunedModelInfo, + Checkpoint, + Model, + ListModelsConfig, + ListModelsParameters, + ListModelsResponse, + UpdateModelConfig, + UpdateModelParameters, + DeleteModelConfig, + DeleteModelParameters, + DeleteModelResponse, + GenerationConfigThinkingConfig, + GenerationConfig, + CountTokensConfig, + CountTokensParameters, + CountTokensResponse, + ComputeTokensConfig, + ComputeTokensParameters, + TokensInfo, + ComputeTokensResponse, + Video, + VideoGenerationReferenceImage, + GenerateVideosConfig, + GenerateVideosParameters, + GeneratedVideo, + GenerateVideosResponse, + GetTuningJobConfig, + GetTuningJobParameters, + TunedModelCheckpoint, + TunedModel, + GoogleRpcStatus, + PreTunedModel, + SupervisedHyperParameters, + SupervisedTuningSpec, + DatasetDistributionDistributionBucket, + DatasetDistribution, + DatasetStats, + DistillationDataStats, + GeminiPreferenceExampleCompletion, + GeminiPreferenceExample, + PreferenceOptimizationDataStats, + SupervisedTuningDatasetDistributionDatasetBucket, + SupervisedTuningDatasetDistribution, + SupervisedTuningDataStats, + TuningDataStats, + EncryptionSpec, + PartnerModelTuningSpec, + TuningJob, + ListTuningJobsConfig, + ListTuningJobsParameters, + ListTuningJobsResponse, + TuningExample, + TuningDataset, + TuningValidationDataset, + CreateTuningJobConfig, + CreateTuningJobParametersPrivate, + TuningOperation, + CreateCachedContentConfig, + CreateCachedContentParameters, + CachedContentUsageMetadata, + CachedContent, + GetCachedContentConfig, + GetCachedContentParameters, + DeleteCachedContentConfig, + DeleteCachedContentParameters, + DeleteCachedContentResponse, + UpdateCachedContentConfig, + UpdateCachedContentParameters, + ListCachedContentsConfig, + ListCachedContentsParameters, + ListCachedContentsResponse, + ListFilesConfig, + ListFilesParameters, + FileStatus, + File_2 as File, + ListFilesResponse, + CreateFileConfig, + CreateFileParameters, + CreateFileResponse, + GetFileConfig, + GetFileParameters, + DeleteFileConfig, + DeleteFileParameters, + DeleteFileResponse, + InlinedRequest, + BatchJobSource, + JobError, + InlinedResponse, + BatchJobDestination, + CreateBatchJobConfig, + CreateBatchJobParameters, + BatchJob, + GetBatchJobConfig, + GetBatchJobParameters, + CancelBatchJobConfig, + CancelBatchJobParameters, + ListBatchJobsConfig, + ListBatchJobsParameters, + ListBatchJobsResponse, + DeleteBatchJobConfig, + DeleteBatchJobParameters, + DeleteResourceJob, + GetOperationConfig, + GetOperationParameters, + FetchPredictOperationConfig, + FetchPredictOperationParameters, + TestTableItem, + TestTableFile, + ReplayRequest, + ReplayResponse, + ReplayInteraction, + ReplayFile, + UploadFileConfig, + DownloadFileConfig, + DownloadFileParameters, + UpscaleImageConfig, + UpscaleImageParameters, + RawReferenceImage, + MaskReferenceImage, + ControlReferenceImage, + StyleReferenceImage, + SubjectReferenceImage, + LiveServerSetupComplete, + Transcription, + LiveServerContent, + LiveServerToolCall, + LiveServerToolCallCancellation, + UsageMetadata, + LiveServerGoAway, + LiveServerSessionResumptionUpdate, + LiveServerMessage, + OperationGetParameters, + OperationFromAPIResponseParameters, + Operation, + GenerateVideosOperation, + AutomaticActivityDetection, + RealtimeInputConfig, + SessionResumptionConfig, + SlidingWindow, + ContextWindowCompressionConfig, + AudioTranscriptionConfig, + ProactivityConfig, + LiveClientSetup, + LiveClientContent, + ActivityStart, + ActivityEnd, + LiveClientRealtimeInput, + LiveClientToolResponse, + LiveSendRealtimeInputParameters, + LiveClientMessage, + LiveConnectConfig, + LiveConnectParameters, + CreateChatParameters, + SendMessageParameters, + LiveSendClientContentParameters, + LiveSendToolResponseParameters, + LiveMusicClientSetup, + WeightedPrompt, + LiveMusicClientContent, + LiveMusicGenerationConfig, + LiveMusicClientMessage, + LiveMusicServerSetupComplete, + LiveMusicSourceMetadata, + AudioChunk, + LiveMusicServerContent, + LiveMusicFilteredPrompt, + LiveMusicServerMessage, + LiveMusicCallbacks, + UploadFileParameters, + CallableTool, + CallableToolConfig, + LiveMusicConnectParameters, + LiveMusicSetConfigParameters, + LiveMusicSetWeightedPromptsParameters, + AuthToken, + LiveConnectConstraints, + CreateAuthTokenConfig, + CreateAuthTokenParameters, + CreateTuningJobParameters, + BlobImageUnion, + PartUnion, + PartListUnion, + ContentUnion, + ContentListUnion, + SchemaUnion, + SpeechConfigUnion, + ToolUnion, + ToolListUnion, + DownloadableFileUnion, + BatchJobSourceUnion, + BatchJobDestinationUnion + } +} + +/** Optional parameters for caches.update method. */ +export declare interface UpdateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; +} + +export declare interface UpdateCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Configuration that contains optional parameters. + */ + config?: UpdateCachedContentConfig; +} + +/** Configuration for updating a tuned model. */ +export declare interface UpdateModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + displayName?: string; + description?: string; + defaultCheckpointId?: string; +} + +/** Configuration for updating a tuned model. */ +export declare interface UpdateModelParameters { + model: string; + config?: UpdateModelConfig; +} + +declare interface Uploader { + /** + * Uploads a file to the given upload url. + * + * @param file The file to upload. file is in string type or a Blob. + * @param uploadUrl The upload URL as a string is where the file will be + * uploaded to. The uploadUrl must be a url that was returned by the + * https://generativelanguage.googleapis.com/upload/v1beta/files endpoint + * @param apiClient The ApiClient to use for uploading. + * @return A Promise that resolves to types.File. + */ + upload(file: string | Blob, uploadUrl: string, apiClient: ApiClient): Promise; + /** + * Returns the file's mimeType and the size of a given file. If the file is a + * string path, the file type is determined by the file extension. If the + * file's type cannot be determined, the type will be set to undefined. + * + * @param file The file to get the stat for. Can be a string path or a Blob. + * @return A Promise that resolves to the file stat of the given file. + */ + stat(file: string | Blob): Promise; +} + +/** Used to override the default configuration. */ +export declare interface UploadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */ + name?: string; + /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */ + mimeType?: string; + /** Optional display name of the file. */ + displayName?: string; +} + +/** Parameters for the upload file method. */ +export declare interface UploadFileParameters { + /** The string path to the file to be uploaded or a Blob object. */ + file: string | globalThis.Blob; + /** Configuration that contains optional parameters. */ + config?: UploadFileConfig; +} + +/** Configuration for upscaling an image. + + For more information on this configuration, refer to + the `Imagen API reference documentation + `_. + */ +export declare interface UpscaleImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Whether to include a reason for filtered-out images in the + response. */ + includeRaiReason?: boolean; + /** The image format that the output should be saved as. */ + outputMimeType?: string; + /** The level of compression if the ``output_mime_type`` is + ``image/jpeg``. */ + outputCompressionQuality?: number; + /** Whether to add an image enhancing step before upscaling. + It is expected to suppress the noise and JPEG compression artifacts + from the input image. */ + enhanceInputImage?: boolean; + /** With a higher image preservation factor, the original image + pixels are more respected. With a lower image preservation factor, the + output image will have be more different from the input image, but + with finer details and less noise. */ + imagePreservationFactor?: number; +} + +/** User-facing config UpscaleImageParameters. */ +export declare interface UpscaleImageParameters { + /** The model to use. */ + model: string; + /** The input image to upscale. */ + image: Image_2; + /** The factor to upscale the image (x2 or x4). */ + upscaleFactor: string; + /** Configuration for upscaling. */ + config?: UpscaleImageConfig; +} + +export declare class UpscaleImageResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** Tool to support URL context retrieval. */ +export declare interface UrlContext { +} + +/** Metadata related to url context retrieval tool. */ +export declare interface UrlContextMetadata { + /** List of url context. */ + urlMetadata?: UrlMetadata[]; +} + +/** Context for a single url retrieval. */ +export declare interface UrlMetadata { + /** The URL retrieved by the tool. */ + retrievedUrl?: string; + /** Status of the url retrieval. */ + urlRetrievalStatus?: UrlRetrievalStatus; +} + +/** Status of the url retrieval. */ +export declare enum UrlRetrievalStatus { + /** + * Default value. This value is unused + */ + URL_RETRIEVAL_STATUS_UNSPECIFIED = "URL_RETRIEVAL_STATUS_UNSPECIFIED", + /** + * Url retrieval is successful. + */ + URL_RETRIEVAL_STATUS_SUCCESS = "URL_RETRIEVAL_STATUS_SUCCESS", + /** + * Url retrieval is failed due to error. + */ + URL_RETRIEVAL_STATUS_ERROR = "URL_RETRIEVAL_STATUS_ERROR", + /** + * Url retrieval is failed because the content is behind paywall. + */ + URL_RETRIEVAL_STATUS_PAYWALL = "URL_RETRIEVAL_STATUS_PAYWALL", + /** + * Url retrieval is failed because the content is unsafe. + */ + URL_RETRIEVAL_STATUS_UNSAFE = "URL_RETRIEVAL_STATUS_UNSAFE" +} + +/** Usage metadata about response(s). */ +export declare interface UsageMetadata { + /** Number of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */ + promptTokenCount?: number; + /** Number of tokens in the cached part of the prompt (the cached content). */ + cachedContentTokenCount?: number; + /** Total number of tokens across all the generated response candidates. */ + responseTokenCount?: number; + /** Number of tokens present in tool-use prompt(s). */ + toolUsePromptTokenCount?: number; + /** Number of tokens of thoughts for thinking models. */ + thoughtsTokenCount?: number; + /** Total token count for prompt, response candidates, and tool-use prompts(if present). */ + totalTokenCount?: number; + /** List of modalities that were processed in the request input. */ + promptTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were processed in the cache input. */ + cacheTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were returned in the response. */ + responseTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were processed in the tool-use prompt. */ + toolUsePromptTokensDetails?: ModalityTokenCount[]; + /** Traffic type. This shows whether a request consumes Pay-As-You-Go + or Provisioned Throughput quota. */ + trafficType?: TrafficType; +} + +/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */ +export declare interface VertexAISearch { + /** Specifications that define the specific DataStores to be searched, along with configurations for those data stores. This is only considered for Engines with multiple data stores. It should only be set if engine is used. */ + dataStoreSpecs?: VertexAISearchDataStoreSpec[]; + /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */ + datastore?: string; + /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */ + engine?: string; + /** Optional. Filter strings to be passed to the search API. */ + filter?: string; + /** Optional. Number of search results to return per query. The default value is 10. The maximumm allowed value is 10. */ + maxResults?: number; +} + +/** Define data stores within engine to filter on in a search call and configurations for those data stores. For more information, see https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec */ +export declare interface VertexAISearchDataStoreSpec { + /** Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */ + dataStore?: string; + /** Optional. Filter specification to filter documents in the data store specified by data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata) */ + filter?: string; +} + +/** Retrieve from Vertex RAG Store for grounding. */ +export declare interface VertexRagStore { + /** Optional. Deprecated. Please use rag_resources instead. */ + ragCorpora?: string[]; + /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */ + ragResources?: VertexRagStoreRagResource[]; + /** Optional. The retrieval config for the Rag query. */ + ragRetrievalConfig?: RagRetrievalConfig; + /** Optional. Number of top k results to return from the selected corpora. */ + similarityTopK?: number; + /** Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal Live API, if `store_context` bool is specified, Gemini will leverage it to automatically memorize the interactions between the client and Gemini, and retrieve context when needed to augment the response generation for users' ongoing and future interactions. */ + storeContext?: boolean; + /** Optional. Only return results with vector distance smaller than the threshold. */ + vectorDistanceThreshold?: number; +} + +/** The definition of the Rag resource. */ +export declare interface VertexRagStoreRagResource { + /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */ + ragCorpus?: string; + /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */ + ragFileIds?: string[]; +} + +/** A generated video. */ +export declare interface Video { + /** Path to another storage. */ + uri?: string; + /** Video bytes. + * @remarks Encoded as base64 string. */ + videoBytes?: string; + /** Video encoding, for example "video/mp4". */ + mimeType?: string; +} + +/** Enum that controls the compression quality of the generated videos. */ +export declare enum VideoCompressionQuality { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + OPTIMIZED = "OPTIMIZED", + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + LOSSLESS = "LOSSLESS" +} + +/** A reference image for video generation. */ +export declare interface VideoGenerationReferenceImage { + /** The reference image. + */ + image?: Image_2; + /** The type of the reference image, which defines how the reference + image will be used to generate the video. Supported values are 'asset' + or 'style'. */ + referenceType?: string; +} + +/** Describes how the video in the Part should be used by the model. */ +export declare interface VideoMetadata { + /** The frame rate of the video sent to the model. If not specified, the + default value will be 1.0. The fps range is (0.0, 24.0]. */ + fps?: number; + /** Optional. The end offset of the video. */ + endOffset?: string; + /** Optional. The start offset of the video. */ + startOffset?: string; +} + +/** The configuration for the voice to use. */ +export declare interface VoiceConfig { + /** The configuration for the speaker to use. + */ + prebuiltVoiceConfig?: PrebuiltVoiceConfig; +} + +declare interface WebSocket_2 { + /** + * Connects the socket to the server. + */ + connect(): void; + /** + * Sends a message to the server. + */ + send(message: string): void; + /** + * Closes the socket connection. + */ + close(): void; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +declare interface WebSocketCallbacks { + onopen: () => void; + onerror: (e: any) => void; + onmessage: (e: any) => void; + onclose: (e: any) => void; +} + +declare interface WebSocketFactory { + /** + * Returns a new WebSocket instance. + */ + create(url: string, headers: Record, callbacks: WebSocketCallbacks): WebSocket_2; +} + +/** Maps a prompt to a relative weight to steer music generation. */ +export declare interface WeightedPrompt { + /** Text prompt. */ + text?: string; + /** Weight of the prompt. The weight is used to control the relative + importance of the prompt. Higher weights are more important than lower + weights. + + Weight must not be 0. Weights of all weighted_prompts in this + LiveMusicClientContent message will be normalized. */ + weight?: number; +} + +export { } diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/web/index.mjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/web/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2733cc4ab4c6766999c938b6ba02c573c46579b6 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/web/index.mjs @@ -0,0 +1,18717 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +let _defaultBaseGeminiUrl = undefined; +let _defaultBaseVertexUrl = undefined; +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +function setDefaultBaseUrls(baseUrlParams) { + _defaultBaseGeminiUrl = baseUrlParams.geminiUrl; + _defaultBaseVertexUrl = baseUrlParams.vertexUrl; +} +/** + * Returns the default base URLs for the Gemini API and Vertex AI API. + */ +function getDefaultBaseUrls() { + return { + geminiUrl: _defaultBaseGeminiUrl, + vertexUrl: _defaultBaseVertexUrl, + }; +} +/** + * Returns the default base URL based on the following priority: + * 1. Base URLs set via HttpOptions. + * 2. Base URLs set via the latest call to setDefaultBaseUrls. + * 3. Base URLs set via environment variables. + */ +function getBaseUrl(httpOptions, vertexai, vertexBaseUrlFromEnv, geminiBaseUrlFromEnv) { + var _a, _b; + if (!(httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.baseUrl)) { + const defaultBaseUrls = getDefaultBaseUrls(); + if (vertexai) { + return (_a = defaultBaseUrls.vertexUrl) !== null && _a !== void 0 ? _a : vertexBaseUrlFromEnv; + } + else { + return (_b = defaultBaseUrls.geminiUrl) !== null && _b !== void 0 ? _b : geminiBaseUrlFromEnv; + } + } + return httpOptions.baseUrl; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BaseModule { +} +function formatMap(templateString, valueMap) { + // Use a regular expression to find all placeholders in the template string + const regex = /\{([^}]+)\}/g; + // Replace each placeholder with its corresponding value from the valueMap + return templateString.replace(regex, (match, key) => { + if (Object.prototype.hasOwnProperty.call(valueMap, key)) { + const value = valueMap[key]; + // Convert the value to a string if it's not a string already + return value !== undefined && value !== null ? String(value) : ''; + } + else { + // Handle missing keys + throw new Error(`Key '${key}' not found in valueMap.`); + } + }); +} +function setValueByPath(data, keys, value) { + for (let i = 0; i < keys.length - 1; i++) { + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (!(keyName in data)) { + if (Array.isArray(value)) { + data[keyName] = Array.from({ length: value.length }, () => ({})); + } + else { + throw new Error(`Value must be a list given an array path ${key}`); + } + } + if (Array.isArray(data[keyName])) { + const arrayData = data[keyName]; + if (Array.isArray(value)) { + for (let j = 0; j < arrayData.length; j++) { + const entry = arrayData[j]; + setValueByPath(entry, keys.slice(i + 1), value[j]); + } + } + else { + for (const d of arrayData) { + setValueByPath(d, keys.slice(i + 1), value); + } + } + } + return; + } + else if (key.endsWith('[0]')) { + const keyName = key.slice(0, -3); + if (!(keyName in data)) { + data[keyName] = [{}]; + } + const arrayData = data[keyName]; + setValueByPath(arrayData[0], keys.slice(i + 1), value); + return; + } + if (!data[key] || typeof data[key] !== 'object') { + data[key] = {}; + } + data = data[key]; + } + const keyToSet = keys[keys.length - 1]; + const existingData = data[keyToSet]; + if (existingData !== undefined) { + if (!value || + (typeof value === 'object' && Object.keys(value).length === 0)) { + return; + } + if (value === existingData) { + return; + } + if (typeof existingData === 'object' && + typeof value === 'object' && + existingData !== null && + value !== null) { + Object.assign(existingData, value); + } + else { + throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`); + } + } + else { + data[keyToSet] = value; + } +} +function getValueByPath(data, keys) { + try { + if (keys.length === 1 && keys[0] === '_self') { + return data; + } + for (let i = 0; i < keys.length; i++) { + if (typeof data !== 'object' || data === null) { + return undefined; + } + const key = keys[i]; + if (key.endsWith('[]')) { + const keyName = key.slice(0, -2); + if (keyName in data) { + const arrayData = data[keyName]; + if (!Array.isArray(arrayData)) { + return undefined; + } + return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1))); + } + else { + return undefined; + } + } + else { + data = data[key]; + } + } + return data; + } + catch (error) { + if (error instanceof TypeError) { + return undefined; + } + throw error; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tBytes$1(fromBytes) { + if (typeof fromBytes !== 'string') { + throw new Error('fromImageBytes must be a string'); + } + // TODO(b/389133914): Remove dummy bytes converter. + return fromBytes; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +/** Required. Outcome of the code execution. */ +var Outcome; +(function (Outcome) { + /** + * Unspecified status. This value should not be used. + */ + Outcome["OUTCOME_UNSPECIFIED"] = "OUTCOME_UNSPECIFIED"; + /** + * Code execution completed successfully. + */ + Outcome["OUTCOME_OK"] = "OUTCOME_OK"; + /** + * Code execution finished but with a failure. `stderr` should contain the reason. + */ + Outcome["OUTCOME_FAILED"] = "OUTCOME_FAILED"; + /** + * Code execution ran for too long, and was cancelled. There may or may not be a partial output present. + */ + Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "OUTCOME_DEADLINE_EXCEEDED"; +})(Outcome || (Outcome = {})); +/** Required. Programming language of the `code`. */ +var Language; +(function (Language) { + /** + * Unspecified language. This value should not be used. + */ + Language["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED"; + /** + * Python >= 3.10, with numpy and simpy available. + */ + Language["PYTHON"] = "PYTHON"; +})(Language || (Language = {})); +/** Optional. The type of the data. */ +var Type; +(function (Type) { + /** + * Not specified, should not be used. + */ + Type["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + /** + * OpenAPI string type + */ + Type["STRING"] = "STRING"; + /** + * OpenAPI number type + */ + Type["NUMBER"] = "NUMBER"; + /** + * OpenAPI integer type + */ + Type["INTEGER"] = "INTEGER"; + /** + * OpenAPI boolean type + */ + Type["BOOLEAN"] = "BOOLEAN"; + /** + * OpenAPI array type + */ + Type["ARRAY"] = "ARRAY"; + /** + * OpenAPI object type + */ + Type["OBJECT"] = "OBJECT"; + /** + * Null type + */ + Type["NULL"] = "NULL"; +})(Type || (Type = {})); +/** Required. Harm category. */ +var HarmCategory; +(function (HarmCategory) { + /** + * The harm category is unspecified. + */ + HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + /** + * The harm category is hate speech. + */ + HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + /** + * The harm category is dangerous content. + */ + HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT"; + /** + * The harm category is harassment. + */ + HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + /** + * The harm category is sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY"; + /** + * The harm category is image hate. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE"; + /** + * The harm category is image dangerous content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"; + /** + * The harm category is image harassment. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HARASSMENT"] = "HARM_CATEGORY_IMAGE_HARASSMENT"; + /** + * The harm category is image sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"; +})(HarmCategory || (HarmCategory = {})); +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +var HarmBlockMethod; +(function (HarmBlockMethod) { + /** + * The harm block method is unspecified. + */ + HarmBlockMethod["HARM_BLOCK_METHOD_UNSPECIFIED"] = "HARM_BLOCK_METHOD_UNSPECIFIED"; + /** + * The harm block method uses both probability and severity scores. + */ + HarmBlockMethod["SEVERITY"] = "SEVERITY"; + /** + * The harm block method uses the probability score. + */ + HarmBlockMethod["PROBABILITY"] = "PROBABILITY"; +})(HarmBlockMethod || (HarmBlockMethod = {})); +/** Required. The harm block threshold. */ +var HarmBlockThreshold; +(function (HarmBlockThreshold) { + /** + * Unspecified harm block threshold. + */ + HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + /** + * Block low threshold and above (i.e. block more). + */ + HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + /** + * Block medium threshold and above. + */ + HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + /** + * Block only high threshold (i.e. block less). + */ + HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + /** + * Block none. + */ + HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; + /** + * Turn off the safety filter. + */ + HarmBlockThreshold["OFF"] = "OFF"; +})(HarmBlockThreshold || (HarmBlockThreshold = {})); +/** The mode of the predictor to be used in dynamic retrieval. */ +var Mode; +(function (Mode) { + /** + * Always trigger retrieval. + */ + Mode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + Mode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(Mode || (Mode = {})); +/** Type of auth scheme. */ +var AuthType; +(function (AuthType) { + AuthType["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED"; + /** + * No Auth. + */ + AuthType["NO_AUTH"] = "NO_AUTH"; + /** + * API Key Auth. + */ + AuthType["API_KEY_AUTH"] = "API_KEY_AUTH"; + /** + * HTTP Basic Auth. + */ + AuthType["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH"; + /** + * Google Service Account Auth. + */ + AuthType["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH"; + /** + * OAuth auth. + */ + AuthType["OAUTH"] = "OAUTH"; + /** + * OpenID Connect (OIDC) Auth. + */ + AuthType["OIDC_AUTH"] = "OIDC_AUTH"; +})(AuthType || (AuthType = {})); +/** The API spec that the external API implements. */ +var ApiSpec; +(function (ApiSpec) { + /** + * Unspecified API spec. This value should not be used. + */ + ApiSpec["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED"; + /** + * Simple search API spec. + */ + ApiSpec["SIMPLE_SEARCH"] = "SIMPLE_SEARCH"; + /** + * Elastic search API spec. + */ + ApiSpec["ELASTIC_SEARCH"] = "ELASTIC_SEARCH"; +})(ApiSpec || (ApiSpec = {})); +/** Status of the url retrieval. */ +var UrlRetrievalStatus; +(function (UrlRetrievalStatus) { + /** + * Default value. This value is unused + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = "URL_RETRIEVAL_STATUS_UNSPECIFIED"; + /** + * Url retrieval is successful. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_SUCCESS"] = "URL_RETRIEVAL_STATUS_SUCCESS"; + /** + * Url retrieval is failed due to error. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_ERROR"] = "URL_RETRIEVAL_STATUS_ERROR"; + /** + * Url retrieval is failed because the content is behind paywall. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_PAYWALL"] = "URL_RETRIEVAL_STATUS_PAYWALL"; + /** + * Url retrieval is failed because the content is unsafe. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSAFE"] = "URL_RETRIEVAL_STATUS_UNSAFE"; +})(UrlRetrievalStatus || (UrlRetrievalStatus = {})); +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +var FinishReason; +(function (FinishReason) { + /** + * The finish reason is unspecified. + */ + FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + FinishReason["STOP"] = "STOP"; + /** + * Token generation reached the configured maximum output tokens. + */ + FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + FinishReason["SAFETY"] = "SAFETY"; + /** + * The token generation stopped because of potential recitation. + */ + FinishReason["RECITATION"] = "RECITATION"; + /** + * The token generation stopped because of using an unsupported language. + */ + FinishReason["LANGUAGE"] = "LANGUAGE"; + /** + * All other reasons that stopped the token generation. + */ + FinishReason["OTHER"] = "OTHER"; + /** + * Token generation stopped because the content contains forbidden terms. + */ + FinishReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Token generation stopped for potentially containing prohibited content. + */ + FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). + */ + FinishReason["SPII"] = "SPII"; + /** + * The function call generated by the model is invalid. + */ + FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; + /** + * Token generation stopped because generated images have safety violations. + */ + FinishReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; + /** + * The tool call generated by the model is invalid. + */ + FinishReason["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL"; +})(FinishReason || (FinishReason = {})); +/** Output only. Harm probability levels in the content. */ +var HarmProbability; +(function (HarmProbability) { + /** + * Harm probability unspecified. + */ + HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED"; + /** + * Negligible level of harm. + */ + HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; + /** + * Low level of harm. + */ + HarmProbability["LOW"] = "LOW"; + /** + * Medium level of harm. + */ + HarmProbability["MEDIUM"] = "MEDIUM"; + /** + * High level of harm. + */ + HarmProbability["HIGH"] = "HIGH"; +})(HarmProbability || (HarmProbability = {})); +/** Output only. Harm severity levels in the content. */ +var HarmSeverity; +(function (HarmSeverity) { + /** + * Harm severity unspecified. + */ + HarmSeverity["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED"; + /** + * Negligible level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE"; + /** + * Low level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW"; + /** + * Medium level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM"; + /** + * High level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH"; +})(HarmSeverity || (HarmSeverity = {})); +/** Output only. Blocked reason. */ +var BlockedReason; +(function (BlockedReason) { + /** + * Unspecified blocked reason. + */ + BlockedReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + /** + * Candidates blocked due to safety. + */ + BlockedReason["SAFETY"] = "SAFETY"; + /** + * Candidates blocked due to other reason. + */ + BlockedReason["OTHER"] = "OTHER"; + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BlockedReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Candidates blocked due to prohibited content. + */ + BlockedReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Candidates blocked due to unsafe image generation content. + */ + BlockedReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; +})(BlockedReason || (BlockedReason = {})); +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +var TrafficType; +(function (TrafficType) { + /** + * Unspecified request traffic type. + */ + TrafficType["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED"; + /** + * Type for Pay-As-You-Go traffic. + */ + TrafficType["ON_DEMAND"] = "ON_DEMAND"; + /** + * Type for Provisioned Throughput traffic. + */ + TrafficType["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT"; +})(TrafficType || (TrafficType = {})); +/** Server content modalities. */ +var Modality; +(function (Modality) { + /** + * The modality is unspecified. + */ + Modality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Indicates the model should return text + */ + Modality["TEXT"] = "TEXT"; + /** + * Indicates the model should return images. + */ + Modality["IMAGE"] = "IMAGE"; + /** + * Indicates the model should return audio. + */ + Modality["AUDIO"] = "AUDIO"; +})(Modality || (Modality = {})); +/** The media resolution to use. */ +var MediaResolution; +(function (MediaResolution) { + /** + * Media resolution has not been set + */ + MediaResolution["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED"; + /** + * Media resolution set to low (64 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + /** + * Media resolution set to medium (256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; +})(MediaResolution || (MediaResolution = {})); +/** Job state. */ +var JobState; +(function (JobState) { + /** + * The job state is unspecified. + */ + JobState["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED"; + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JobState["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED"; + /** + * The service is preparing to run the job. + */ + JobState["JOB_STATE_PENDING"] = "JOB_STATE_PENDING"; + /** + * The job is in progress. + */ + JobState["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING"; + /** + * The job completed successfully. + */ + JobState["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED"; + /** + * The job failed. + */ + JobState["JOB_STATE_FAILED"] = "JOB_STATE_FAILED"; + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JobState["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING"; + /** + * The job has been cancelled. + */ + JobState["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED"; + /** + * The job has been stopped, and can be resumed. + */ + JobState["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED"; + /** + * The job has expired. + */ + JobState["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED"; + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JobState["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING"; + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JobState["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED"; +})(JobState || (JobState = {})); +/** Tuning mode. */ +var TuningMode; +(function (TuningMode) { + /** + * Tuning mode is unspecified. + */ + TuningMode["TUNING_MODE_UNSPECIFIED"] = "TUNING_MODE_UNSPECIFIED"; + /** + * Full fine-tuning mode. + */ + TuningMode["TUNING_MODE_FULL"] = "TUNING_MODE_FULL"; + /** + * PEFT adapter tuning mode. + */ + TuningMode["TUNING_MODE_PEFT_ADAPTER"] = "TUNING_MODE_PEFT_ADAPTER"; +})(TuningMode || (TuningMode = {})); +/** Optional. Adapter size for tuning. */ +var AdapterSize; +(function (AdapterSize) { + /** + * Adapter size is unspecified. + */ + AdapterSize["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED"; + /** + * Adapter size 1. + */ + AdapterSize["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE"; + /** + * Adapter size 2. + */ + AdapterSize["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO"; + /** + * Adapter size 4. + */ + AdapterSize["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR"; + /** + * Adapter size 8. + */ + AdapterSize["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT"; + /** + * Adapter size 16. + */ + AdapterSize["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN"; + /** + * Adapter size 32. + */ + AdapterSize["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO"; +})(AdapterSize || (AdapterSize = {})); +/** Options for feature selection preference. */ +var FeatureSelectionPreference; +(function (FeatureSelectionPreference) { + FeatureSelectionPreference["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"; + FeatureSelectionPreference["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY"; + FeatureSelectionPreference["BALANCED"] = "BALANCED"; + FeatureSelectionPreference["PRIORITIZE_COST"] = "PRIORITIZE_COST"; +})(FeatureSelectionPreference || (FeatureSelectionPreference = {})); +/** Defines the function behavior. Defaults to `BLOCKING`. */ +var Behavior; +(function (Behavior) { + /** + * This value is unused. + */ + Behavior["UNSPECIFIED"] = "UNSPECIFIED"; + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + Behavior["BLOCKING"] = "BLOCKING"; + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + Behavior["NON_BLOCKING"] = "NON_BLOCKING"; +})(Behavior || (Behavior = {})); +/** Config for the dynamic retrieval config mode. */ +var DynamicRetrievalConfigMode; +(function (DynamicRetrievalConfigMode) { + /** + * Always trigger retrieval. + */ + DynamicRetrievalConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + DynamicRetrievalConfigMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(DynamicRetrievalConfigMode || (DynamicRetrievalConfigMode = {})); +/** The environment being operated. */ +var Environment; +(function (Environment) { + /** + * Defaults to browser. + */ + Environment["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED"; + /** + * Operates in a web browser. + */ + Environment["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER"; +})(Environment || (Environment = {})); +/** Config for the function calling config mode. */ +var FunctionCallingConfigMode; +(function (FunctionCallingConfigMode) { + /** + * The function calling config mode is unspecified. Should not be used. + */ + FunctionCallingConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + FunctionCallingConfigMode["AUTO"] = "AUTO"; + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + FunctionCallingConfigMode["ANY"] = "ANY"; + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + FunctionCallingConfigMode["NONE"] = "NONE"; +})(FunctionCallingConfigMode || (FunctionCallingConfigMode = {})); +/** Enum that controls the safety filter level for objectionable content. */ +var SafetyFilterLevel; +(function (SafetyFilterLevel) { + SafetyFilterLevel["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + SafetyFilterLevel["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + SafetyFilterLevel["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + SafetyFilterLevel["BLOCK_NONE"] = "BLOCK_NONE"; +})(SafetyFilterLevel || (SafetyFilterLevel = {})); +/** Enum that controls the generation of people. */ +var PersonGeneration; +(function (PersonGeneration) { + /** + * Block generation of images of people. + */ + PersonGeneration["DONT_ALLOW"] = "DONT_ALLOW"; + /** + * Generate images of adults, but not children. + */ + PersonGeneration["ALLOW_ADULT"] = "ALLOW_ADULT"; + /** + * Generate images that include adults and children. + */ + PersonGeneration["ALLOW_ALL"] = "ALLOW_ALL"; +})(PersonGeneration || (PersonGeneration = {})); +/** Enum that specifies the language of the text in the prompt. */ +var ImagePromptLanguage; +(function (ImagePromptLanguage) { + /** + * Auto-detect the language. + */ + ImagePromptLanguage["auto"] = "auto"; + /** + * English + */ + ImagePromptLanguage["en"] = "en"; + /** + * Japanese + */ + ImagePromptLanguage["ja"] = "ja"; + /** + * Korean + */ + ImagePromptLanguage["ko"] = "ko"; + /** + * Hindi + */ + ImagePromptLanguage["hi"] = "hi"; + /** + * Chinese + */ + ImagePromptLanguage["zh"] = "zh"; + /** + * Portuguese + */ + ImagePromptLanguage["pt"] = "pt"; + /** + * Spanish + */ + ImagePromptLanguage["es"] = "es"; +})(ImagePromptLanguage || (ImagePromptLanguage = {})); +/** Enum representing the mask mode of a mask reference image. */ +var MaskReferenceMode; +(function (MaskReferenceMode) { + MaskReferenceMode["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT"; + MaskReferenceMode["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED"; + MaskReferenceMode["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND"; + MaskReferenceMode["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND"; + MaskReferenceMode["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC"; +})(MaskReferenceMode || (MaskReferenceMode = {})); +/** Enum representing the control type of a control reference image. */ +var ControlReferenceType; +(function (ControlReferenceType) { + ControlReferenceType["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT"; + ControlReferenceType["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY"; + ControlReferenceType["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE"; + ControlReferenceType["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH"; +})(ControlReferenceType || (ControlReferenceType = {})); +/** Enum representing the subject type of a subject reference image. */ +var SubjectReferenceType; +(function (SubjectReferenceType) { + SubjectReferenceType["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT"; + SubjectReferenceType["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON"; + SubjectReferenceType["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL"; + SubjectReferenceType["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT"; +})(SubjectReferenceType || (SubjectReferenceType = {})); +/** Enum representing the Imagen 3 Edit mode. */ +var EditMode; +(function (EditMode) { + EditMode["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT"; + EditMode["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL"; + EditMode["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION"; + EditMode["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT"; + EditMode["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING"; + EditMode["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE"; + EditMode["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP"; + EditMode["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE"; +})(EditMode || (EditMode = {})); +/** Enum that represents the segmentation mode. */ +var SegmentMode; +(function (SegmentMode) { + SegmentMode["FOREGROUND"] = "FOREGROUND"; + SegmentMode["BACKGROUND"] = "BACKGROUND"; + SegmentMode["PROMPT"] = "PROMPT"; + SegmentMode["SEMANTIC"] = "SEMANTIC"; + SegmentMode["INTERACTIVE"] = "INTERACTIVE"; +})(SegmentMode || (SegmentMode = {})); +/** Enum that controls the compression quality of the generated videos. */ +var VideoCompressionQuality; +(function (VideoCompressionQuality) { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + VideoCompressionQuality["OPTIMIZED"] = "OPTIMIZED"; + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + VideoCompressionQuality["LOSSLESS"] = "LOSSLESS"; +})(VideoCompressionQuality || (VideoCompressionQuality = {})); +/** State for the lifecycle of a File. */ +var FileState; +(function (FileState) { + FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + FileState["PROCESSING"] = "PROCESSING"; + FileState["ACTIVE"] = "ACTIVE"; + FileState["FAILED"] = "FAILED"; +})(FileState || (FileState = {})); +/** Source of the File. */ +var FileSource; +(function (FileSource) { + FileSource["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED"; + FileSource["UPLOADED"] = "UPLOADED"; + FileSource["GENERATED"] = "GENERATED"; +})(FileSource || (FileSource = {})); +/** Server content modalities. */ +var MediaModality; +(function (MediaModality) { + /** + * The modality is unspecified. + */ + MediaModality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Plain text. + */ + MediaModality["TEXT"] = "TEXT"; + /** + * Images. + */ + MediaModality["IMAGE"] = "IMAGE"; + /** + * Video. + */ + MediaModality["VIDEO"] = "VIDEO"; + /** + * Audio. + */ + MediaModality["AUDIO"] = "AUDIO"; + /** + * Document, e.g. PDF. + */ + MediaModality["DOCUMENT"] = "DOCUMENT"; +})(MediaModality || (MediaModality = {})); +/** Start of speech sensitivity. */ +var StartSensitivity; +(function (StartSensitivity) { + /** + * The default is START_SENSITIVITY_LOW. + */ + StartSensitivity["START_SENSITIVITY_UNSPECIFIED"] = "START_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection will detect the start of speech more often. + */ + StartSensitivity["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH"; + /** + * Automatic detection will detect the start of speech less often. + */ + StartSensitivity["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW"; +})(StartSensitivity || (StartSensitivity = {})); +/** End of speech sensitivity. */ +var EndSensitivity; +(function (EndSensitivity) { + /** + * The default is END_SENSITIVITY_LOW. + */ + EndSensitivity["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection ends speech more often. + */ + EndSensitivity["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH"; + /** + * Automatic detection ends speech less often. + */ + EndSensitivity["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW"; +})(EndSensitivity || (EndSensitivity = {})); +/** The different ways of handling user activity. */ +var ActivityHandling; +(function (ActivityHandling) { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ActivityHandling["ACTIVITY_HANDLING_UNSPECIFIED"] = "ACTIVITY_HANDLING_UNSPECIFIED"; + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + ActivityHandling["START_OF_ACTIVITY_INTERRUPTS"] = "START_OF_ACTIVITY_INTERRUPTS"; + /** + * The model's response will not be interrupted. + */ + ActivityHandling["NO_INTERRUPTION"] = "NO_INTERRUPTION"; +})(ActivityHandling || (ActivityHandling = {})); +/** Options about which input is included in the user's turn. */ +var TurnCoverage; +(function (TurnCoverage) { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TurnCoverage["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED"; + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TurnCoverage["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY"; + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TurnCoverage["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT"; +})(TurnCoverage || (TurnCoverage = {})); +/** Specifies how the response should be scheduled in the conversation. */ +var FunctionResponseScheduling; +(function (FunctionResponseScheduling) { + /** + * This value is unused. + */ + FunctionResponseScheduling["SCHEDULING_UNSPECIFIED"] = "SCHEDULING_UNSPECIFIED"; + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + FunctionResponseScheduling["SILENT"] = "SILENT"; + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + FunctionResponseScheduling["WHEN_IDLE"] = "WHEN_IDLE"; + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + FunctionResponseScheduling["INTERRUPT"] = "INTERRUPT"; +})(FunctionResponseScheduling || (FunctionResponseScheduling = {})); +/** Scale of the generated music. */ +var Scale; +(function (Scale) { + /** + * Default value. This value is unused. + */ + Scale["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED"; + /** + * C major or A minor. + */ + Scale["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR"; + /** + * Db major or Bb minor. + */ + Scale["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR"; + /** + * D major or B minor. + */ + Scale["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR"; + /** + * Eb major or C minor + */ + Scale["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR"; + /** + * E major or Db minor. + */ + Scale["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR"; + /** + * F major or D minor. + */ + Scale["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR"; + /** + * Gb major or Eb minor. + */ + Scale["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR"; + /** + * G major or E minor. + */ + Scale["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR"; + /** + * Ab major or F minor. + */ + Scale["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR"; + /** + * A major or Gb minor. + */ + Scale["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR"; + /** + * Bb major or G minor. + */ + Scale["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR"; + /** + * B major or Ab minor. + */ + Scale["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR"; +})(Scale || (Scale = {})); +/** The mode of music generation. */ +var MusicGenerationMode; +(function (MusicGenerationMode) { + /** + * Rely on the server default generation mode. + */ + MusicGenerationMode["MUSIC_GENERATION_MODE_UNSPECIFIED"] = "MUSIC_GENERATION_MODE_UNSPECIFIED"; + /** + * Steer text prompts to regions of latent space with higher quality + music. + */ + MusicGenerationMode["QUALITY"] = "QUALITY"; + /** + * Steer text prompts to regions of latent space with a larger + diversity of music. + */ + MusicGenerationMode["DIVERSITY"] = "DIVERSITY"; + /** + * Steer text prompts to regions of latent space more likely to + generate music with vocals. + */ + MusicGenerationMode["VOCALIZATION"] = "VOCALIZATION"; +})(MusicGenerationMode || (MusicGenerationMode = {})); +/** The playback control signal to apply to the music generation. */ +var LiveMusicPlaybackControl; +(function (LiveMusicPlaybackControl) { + /** + * This value is unused. + */ + LiveMusicPlaybackControl["PLAYBACK_CONTROL_UNSPECIFIED"] = "PLAYBACK_CONTROL_UNSPECIFIED"; + /** + * Start generating the music. + */ + LiveMusicPlaybackControl["PLAY"] = "PLAY"; + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + LiveMusicPlaybackControl["PAUSE"] = "PAUSE"; + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + LiveMusicPlaybackControl["STOP"] = "STOP"; + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + LiveMusicPlaybackControl["RESET_CONTEXT"] = "RESET_CONTEXT"; +})(LiveMusicPlaybackControl || (LiveMusicPlaybackControl = {})); +/** A function response. */ +class FunctionResponse { +} +/** + * Creates a `Part` object from a `URI` string. + */ +function createPartFromUri(uri, mimeType) { + return { + fileData: { + fileUri: uri, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from a `text` string. + */ +function createPartFromText(text) { + return { + text: text, + }; +} +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +function createPartFromFunctionCall(name, args) { + return { + functionCall: { + name: name, + args: args, + }, + }; +} +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +function createPartFromFunctionResponse(id, name, response) { + return { + functionResponse: { + id: id, + name: name, + response: response, + }, + }; +} +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +function createPartFromBase64(data, mimeType) { + return { + inlineData: { + data: data, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +function createPartFromCodeExecutionResult(outcome, output) { + return { + codeExecutionResult: { + outcome: outcome, + output: output, + }, + }; +} +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +function createPartFromExecutableCode(code, language) { + return { + executableCode: { + code: code, + language: language, + }, + }; +} +function _isPart(obj) { + if (typeof obj === 'object' && obj !== null) { + return ('fileData' in obj || + 'text' in obj || + 'functionCall' in obj || + 'functionResponse' in obj || + 'inlineData' in obj || + 'videoMetadata' in obj || + 'codeExecutionResult' in obj || + 'executableCode' in obj); + } + return false; +} +function _toParts(partOrString) { + const parts = []; + if (typeof partOrString === 'string') { + parts.push(createPartFromText(partOrString)); + } + else if (_isPart(partOrString)) { + parts.push(partOrString); + } + else if (Array.isArray(partOrString)) { + if (partOrString.length === 0) { + throw new Error('partOrString cannot be an empty array'); + } + for (const part of partOrString) { + if (typeof part === 'string') { + parts.push(createPartFromText(part)); + } + else if (_isPart(part)) { + parts.push(part); + } + else { + throw new Error('element in PartUnion must be a Part object or string'); + } + } + } + else { + throw new Error('partOrString must be a Part object, string, or array'); + } + return parts; +} +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +function createUserContent(partOrString) { + return { + role: 'user', + parts: _toParts(partOrString), + }; +} +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +function createModelContent(partOrString) { + return { + role: 'model', + parts: _toParts(partOrString), + }; +} +/** A wrapper class for the http response. */ +class HttpResponse { + constructor(response) { + // Process the headers. + const headers = {}; + for (const pair of response.headers.entries()) { + headers[pair[0]] = pair[1]; + } + this.headers = headers; + // Keep the original response. + this.responseInternal = response; + } + json() { + return this.responseInternal.json(); + } +} +/** Content filter results for a prompt sent in the request. */ +class GenerateContentResponsePromptFeedback { +} +/** Usage metadata about response(s). */ +class GenerateContentResponseUsageMetadata { +} +/** Response message for PredictionService.GenerateContent. */ +class GenerateContentResponse { + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning text from the first one.'); + } + let text = ''; + let anyTextPartText = false; + const nonTextParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + (fieldValue !== null || fieldValue !== undefined)) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartText = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartText ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning data from the first one.'); + } + let data = ''; + const nonDataParts = []; + for (const part of (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && + (fieldValue !== null || fieldValue !== undefined)) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning function calls from the first one.'); + } + const functionCalls = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.functionCall).map((part) => part.functionCall).filter((functionCall) => functionCall !== undefined); + if ((functionCalls === null || functionCalls === void 0 ? void 0 : functionCalls.length) === 0) { + return undefined; + } + return functionCalls; + } + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning executable code from the first one.'); + } + const executableCode = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.executableCode).map((part) => part.executableCode).filter((executableCode) => executableCode !== undefined); + if ((executableCode === null || executableCode === void 0 ? void 0 : executableCode.length) === 0) { + return undefined; + } + return (_j = executableCode === null || executableCode === void 0 ? void 0 : executableCode[0]) === null || _j === void 0 ? void 0 : _j.code; + } + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a = this.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.length) === 0) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn('there are multiple candidates in the response, returning code execution result from the first one.'); + } + const codeExecutionResult = (_h = (_g = (_f = (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.codeExecutionResult).map((part) => part.codeExecutionResult).filter((codeExecutionResult) => codeExecutionResult !== undefined); + if ((codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult.length) === 0) { + return undefined; + } + return (_j = codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult[0]) === null || _j === void 0 ? void 0 : _j.output; + } +} +/** Response for the embed_content method. */ +class EmbedContentResponse { +} +/** The output images response. */ +class GenerateImagesResponse { +} +/** Response for the request to edit an image. */ +class EditImageResponse { +} +class UpscaleImageResponse { +} +/** The output images response. */ +class RecontextImageResponse { +} +/** The output images response. */ +class SegmentImageResponse { +} +class ListModelsResponse { +} +class DeleteModelResponse { +} +/** Response for counting tokens. */ +class CountTokensResponse { +} +/** Response for computing tokens. */ +class ComputeTokensResponse { +} +/** Response with generated videos. */ +class GenerateVideosResponse { +} +/** Response for the list tuning jobs method. */ +class ListTuningJobsResponse { +} +/** Empty response for caches.delete method. */ +class DeleteCachedContentResponse { +} +class ListCachedContentsResponse { +} +/** Response for the list files method. */ +class ListFilesResponse { +} +/** Response for the create file method. */ +class CreateFileResponse { +} +/** Response for the delete file method. */ +class DeleteFileResponse { +} +/** Config for `inlined_responses` parameter. */ +class InlinedResponse { +} +/** Config for batches.list return value. */ +class ListBatchJobsResponse { +} +/** Represents a single response in a replay. */ +class ReplayResponse { +} +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +class RawReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_RAW', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + }; + return referenceImageAPI; + } +} +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +class MaskReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_MASK', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + maskImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +class ControlReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_CONTROL', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + controlImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +class StyleReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_STYLE', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + styleImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +class SubjectReferenceImage { + /* Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: 'REFERENCE_TYPE_SUBJECT', + referenceImage: this.referenceImage, + referenceId: this.referenceId, + subjectImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** Response message for API call. */ +class LiveServerMessage { + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text() { + var _a, _b, _c; + let text = ''; + let anyTextPartFound = false; + const nonTextParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'text' && + fieldName !== 'thought' && + fieldValue !== null) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === 'string') { + if (typeof part.thought === 'boolean' && part.thought) { + continue; + } + anyTextPartFound = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + // part.text === '' is different from part.text is null + return anyTextPartFound ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c; + let data = ''; + const nonDataParts = []; + for (const part of (_c = (_b = (_a = this.serverContent) === null || _a === void 0 ? void 0 : _a.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== 'inlineData' && fieldValue !== null) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === 'string') { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : undefined; + } +} +/** A video generation long-running operation. */ +class GenerateVideosOperation { + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }) { + const operation = new GenerateVideosOperation(); + operation.name = apiResponse['name']; + operation.metadata = apiResponse['metadata']; + operation.done = apiResponse['done']; + operation.error = apiResponse['error']; + if (isVertexAI) { + const response = apiResponse['response']; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const responseVideos = response['videos']; + operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => { + return { + video: { + uri: generatedVideo['gcsUri'], + videoBytes: generatedVideo['bytesBase64Encoded'] + ? tBytes$1(generatedVideo['bytesBase64Encoded']) + : undefined, + mimeType: generatedVideo['mimeType'], + }, + }; + }); + operationResponse.raiMediaFilteredCount = response['raiMediaFilteredCount']; + operationResponse.raiMediaFilteredReasons = response['raiMediaFilteredReasons']; + operation.response = operationResponse; + } + } + else { + const response = apiResponse['response']; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const generatedVideoResponse = response['generateVideoResponse']; + const responseVideos = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['generatedSamples']; + operationResponse.generatedVideos = responseVideos === null || responseVideos === void 0 ? void 0 : responseVideos.map((generatedVideo) => { + const video = generatedVideo['video']; + return { + video: { + uri: video === null || video === void 0 ? void 0 : video['uri'], + videoBytes: (video === null || video === void 0 ? void 0 : video['encodedVideo']) + ? tBytes$1(video === null || video === void 0 ? void 0 : video['encodedVideo']) + : undefined, + mimeType: generatedVideo['encoding'], + }, + }; + }); + operationResponse.raiMediaFilteredCount = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['raiMediaFilteredCount']; + operationResponse.raiMediaFilteredReasons = generatedVideoResponse === null || generatedVideoResponse === void 0 ? void 0 : generatedVideoResponse['raiMediaFilteredReasons']; + operation.response = operationResponse; + } + } + return operation; + } +} +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +class LiveClientToolResponse { +} +/** Parameters for sending tool responses to the live API. */ +class LiveSendToolResponseParameters { + constructor() { + /** Tool responses to send to the session. */ + this.functionResponses = []; + } +} +/** Response message for the LiveMusicClientMessage call. */ +class LiveMusicServerMessage { + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk() { + if (this.serverContent && + this.serverContent.audioChunks && + this.serverContent.audioChunks.length > 0) { + return this.serverContent.audioChunks[0]; + } + return undefined; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tModel(apiClient, model) { + if (!model || typeof model !== 'string') { + throw new Error('model is required and must be a string'); + } + if (apiClient.isVertexAI()) { + if (model.startsWith('publishers/') || + model.startsWith('projects/') || + model.startsWith('models/')) { + return model; + } + else if (model.indexOf('/') >= 0) { + const parts = model.split('/', 2); + return `publishers/${parts[0]}/models/${parts[1]}`; + } + else { + return `publishers/google/models/${model}`; + } + } + else { + if (model.startsWith('models/') || model.startsWith('tunedModels/')) { + return model; + } + else { + return `models/${model}`; + } + } +} +function tCachesModel(apiClient, model) { + const transformedModel = tModel(apiClient, model); + if (!transformedModel) { + return ''; + } + if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) { + // vertex caches only support model name start with projects. + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`; + } + else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) { + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`; + } + else { + return transformedModel; + } +} +function tBlobs(blobs) { + if (Array.isArray(blobs)) { + return blobs.map((blob) => tBlob(blob)); + } + else { + return [tBlob(blobs)]; + } +} +function tBlob(blob) { + if (typeof blob === 'object' && blob !== null) { + return blob; + } + throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof blob}`); +} +function tImageBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('image/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tAudioBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && + transformedBlob.mimeType.startsWith('audio/')) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tPart(origin) { + if (origin === null || origin === undefined) { + throw new Error('PartUnion is required'); + } + if (typeof origin === 'object') { + return origin; + } + if (typeof origin === 'string') { + return { text: origin }; + } + throw new Error(`Unsupported part type: ${typeof origin}`); +} +function tParts(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('PartListUnion is required'); + } + if (Array.isArray(origin)) { + return origin.map((item) => tPart(item)); + } + return [tPart(origin)]; +} +function _isContent(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'parts' in origin && + Array.isArray(origin.parts)); +} +function _isFunctionCallPart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionCall' in origin); +} +function _isFunctionResponsePart(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'functionResponse' in origin); +} +function tContent(origin) { + if (origin === null || origin === undefined) { + throw new Error('ContentUnion is required'); + } + if (_isContent(origin)) { + // _isContent is a utility function that checks if the + // origin is a Content. + return origin; + } + return { + role: 'user', + parts: tParts(origin), + }; +} +function tContentsForEmbed(apiClient, origin) { + if (!origin) { + return []; + } + if (apiClient.isVertexAI() && Array.isArray(origin)) { + return origin.flatMap((item) => { + const content = tContent(item); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + }); + } + else if (apiClient.isVertexAI()) { + const content = tContent(origin); + if (content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined) { + return [content.parts[0].text]; + } + return []; + } + if (Array.isArray(origin)) { + return origin.map((item) => tContent(item)); + } + return [tContent(origin)]; +} +function tContents(origin) { + if (origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0)) { + throw new Error('contents are required'); + } + if (!Array.isArray(origin)) { + // If it's not an array, it's a single content or a single PartUnion. + if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them'); + } + return [tContent(origin)]; + } + const result = []; + const accumulatedParts = []; + const isContentArray = _isContent(origin[0]); + for (const item of origin) { + const isContent = _isContent(item); + if (isContent != isContentArray) { + throw new Error('Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them'); + } + if (isContent) { + // `isContent` contains the result of _isContent, which is a utility + // function that checks if the item is a Content. + result.push(item); + } + else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) { + throw new Error('To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them'); + } + else { + accumulatedParts.push(item); + } + } + if (!isContentArray) { + result.push({ role: 'user', parts: tParts(accumulatedParts) }); + } + return result; +} +/* +Transform the type field from an array of types to an array of anyOf fields. +Example: + {type: ['STRING', 'NUMBER']} +will be transformed to + {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]} +*/ +function flattenTypeArrayToAnyOf(typeList, resultingSchema) { + if (typeList.includes('null')) { + resultingSchema['nullable'] = true; + } + const listWithoutNull = typeList.filter((type) => type !== 'null'); + if (listWithoutNull.length === 1) { + resultingSchema['type'] = Object.values(Type).includes(listWithoutNull[0].toUpperCase()) + ? listWithoutNull[0].toUpperCase() + : Type.TYPE_UNSPECIFIED; + } + else { + resultingSchema['anyOf'] = []; + for (const i of listWithoutNull) { + resultingSchema['anyOf'].push({ + 'type': Object.values(Type).includes(i.toUpperCase()) + ? i.toUpperCase() + : Type.TYPE_UNSPECIFIED, + }); + } + } +} +function processJsonSchema(_jsonSchema) { + const genAISchema = {}; + const schemaFieldNames = ['items']; + const listSchemaFieldNames = ['anyOf']; + const dictSchemaFieldNames = ['properties']; + if (_jsonSchema['type'] && _jsonSchema['anyOf']) { + throw new Error('type and anyOf cannot be both populated.'); + } + /* + This is to handle the nullable array or object. The _jsonSchema will + be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The + logic is to check if anyOf has 2 elements and one of the element is null, + if so, the anyOf field is unnecessary, so we need to get rid of the anyOf + field and make the schema nullable. Then use the other element as the new + _jsonSchema for processing. This is because the backend doesn't have a null + type. + This has to be checked before we process any other fields. + For example: + const objectNullable = z.object({ + nullableArray: z.array(z.string()).nullable(), + }); + Will have the raw _jsonSchema as: + { + type: 'OBJECT', + properties: { + nullableArray: { + anyOf: [ + {type: 'null'}, + { + type: 'array', + items: {type: 'string'}, + }, + ], + } + }, + required: [ 'nullableArray' ], + } + Will result in following schema compatible with Gemini API: + { + type: 'OBJECT', + properties: { + nullableArray: { + nullable: true, + type: 'ARRAY', + items: {type: 'string'}, + } + }, + required: [ 'nullableArray' ], + } + */ + const incomingAnyOf = _jsonSchema['anyOf']; + if (incomingAnyOf != null && incomingAnyOf.length == 2) { + if (incomingAnyOf[0]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[1]; + } + else if (incomingAnyOf[1]['type'] === 'null') { + genAISchema['nullable'] = true; + _jsonSchema = incomingAnyOf[0]; + } + } + if (_jsonSchema['type'] instanceof Array) { + flattenTypeArrayToAnyOf(_jsonSchema['type'], genAISchema); + } + for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) { + // Skip if the fieldvalue is undefined or null. + if (fieldValue == null) { + continue; + } + if (fieldName == 'type') { + if (fieldValue === 'null') { + throw new Error('type: null can not be the only possible type for the field.'); + } + if (fieldValue instanceof Array) { + // we have already handled the type field with array of types in the + // beginning of this function. + continue; + } + genAISchema['type'] = Object.values(Type).includes(fieldValue.toUpperCase()) + ? fieldValue.toUpperCase() + : Type.TYPE_UNSPECIFIED; + } + else if (schemaFieldNames.includes(fieldName)) { + genAISchema[fieldName] = + processJsonSchema(fieldValue); + } + else if (listSchemaFieldNames.includes(fieldName)) { + const listSchemaFieldValue = []; + for (const item of fieldValue) { + if (item['type'] == 'null') { + genAISchema['nullable'] = true; + continue; + } + listSchemaFieldValue.push(processJsonSchema(item)); + } + genAISchema[fieldName] = + listSchemaFieldValue; + } + else if (dictSchemaFieldNames.includes(fieldName)) { + const dictSchemaFieldValue = {}; + for (const [key, value] of Object.entries(fieldValue)) { + dictSchemaFieldValue[key] = processJsonSchema(value); + } + genAISchema[fieldName] = + dictSchemaFieldValue; + } + else { + // additionalProperties is not included in JSONSchema, skipping it. + if (fieldName === 'additionalProperties') { + continue; + } + genAISchema[fieldName] = fieldValue; + } + } + return genAISchema; +} +// we take the unknown in the schema field because we want enable user to pass +// the output of major schema declaration tools without casting. Tools such as +// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type +// or object, see details in +// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7 +// typebox can return unknown, see details in +// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35 +// Note: proper json schemas with the $schema field set never arrive to this +// transformer. Schemas with $schema are routed to the equivalent API json +// schema field. +function tSchema(schema) { + return processJsonSchema(schema); +} +function tSpeechConfig(speechConfig) { + if (typeof speechConfig === 'object') { + return speechConfig; + } + else if (typeof speechConfig === 'string') { + return { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: speechConfig, + }, + }, + }; + } + else { + throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`); + } +} +function tLiveSpeechConfig(speechConfig) { + if ('multiSpeakerVoiceConfig' in speechConfig) { + throw new Error('multiSpeakerVoiceConfig is not supported in the live API.'); + } + return speechConfig; +} +function tTool(tool) { + if (tool.functionDeclarations) { + for (const functionDeclaration of tool.functionDeclarations) { + if (functionDeclaration.parameters) { + if (!Object.keys(functionDeclaration.parameters).includes('$schema')) { + functionDeclaration.parameters = processJsonSchema(functionDeclaration.parameters); + } + else { + if (!functionDeclaration.parametersJsonSchema) { + functionDeclaration.parametersJsonSchema = + functionDeclaration.parameters; + delete functionDeclaration.parameters; + } + } + } + if (functionDeclaration.response) { + if (!Object.keys(functionDeclaration.response).includes('$schema')) { + functionDeclaration.response = processJsonSchema(functionDeclaration.response); + } + else { + if (!functionDeclaration.responseJsonSchema) { + functionDeclaration.responseJsonSchema = + functionDeclaration.response; + delete functionDeclaration.response; + } + } + } + } + } + return tool; +} +function tTools(tools) { + // Check if the incoming type is defined. + if (tools === undefined || tools === null) { + throw new Error('tools is required'); + } + if (!Array.isArray(tools)) { + throw new Error('tools is required and must be an array of Tools'); + } + const result = []; + for (const tool of tools) { + result.push(tool); + } + return result; +} +/** + * Prepends resource name with project, location, resource_prefix if needed. + * + * @param client The API client. + * @param resourceName The resource name. + * @param resourcePrefix The resource prefix. + * @param splitsAfterPrefix The number of splits after the prefix. + * @returns The completed resource name. + * + * Examples: + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/bar/locations/us-west1/cachedContents/123' + * ``` + * + * ``` + * resource_name = 'projects/foo/locations/us-central1/cachedContents/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/foo/locations/us-central1/cachedContents/123' + * ``` + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns 'cachedContents/123' + * ``` + * + * ``` + * resource_name = 'some/wrong/cachedContents/resource/name/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * # client.vertexai = True + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * -> 'some/wrong/resource/name/123' + * ``` + */ +function resourceName(client, resourceName, resourcePrefix, splitsAfterPrefix = 1) { + const shouldAppendPrefix = !resourceName.startsWith(`${resourcePrefix}/`) && + resourceName.split('/').length === splitsAfterPrefix; + if (client.isVertexAI()) { + if (resourceName.startsWith('projects/')) { + return resourceName; + } + else if (resourceName.startsWith('locations/')) { + return `projects/${client.getProject()}/${resourceName}`; + } + else if (resourceName.startsWith(`${resourcePrefix}/`)) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`; + } + else if (shouldAppendPrefix) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`; + } + else { + return resourceName; + } + } + if (shouldAppendPrefix) { + return `${resourcePrefix}/${resourceName}`; + } + return resourceName; +} +function tCachedContentName(apiClient, name) { + if (typeof name !== 'string') { + throw new Error('name must be a string'); + } + return resourceName(apiClient, name, 'cachedContents'); +} +function tTuningJobStatus(status) { + switch (status) { + case 'STATE_UNSPECIFIED': + return 'JOB_STATE_UNSPECIFIED'; + case 'CREATING': + return 'JOB_STATE_RUNNING'; + case 'ACTIVE': + return 'JOB_STATE_SUCCEEDED'; + case 'FAILED': + return 'JOB_STATE_FAILED'; + default: + return status; + } +} +function tBytes(fromImageBytes) { + return tBytes$1(fromImageBytes); +} +function _isFile(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'name' in origin); +} +function isGeneratedVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'video' in origin); +} +function isVideo(origin) { + return (origin !== null && + origin !== undefined && + typeof origin === 'object' && + 'uri' in origin); +} +function tFileName(fromName) { + var _a; + let name; + if (_isFile(fromName)) { + name = fromName.name; + } + if (isVideo(fromName)) { + name = fromName.uri; + if (name === undefined) { + return undefined; + } + } + if (isGeneratedVideo(fromName)) { + name = (_a = fromName.video) === null || _a === void 0 ? void 0 : _a.uri; + if (name === undefined) { + return undefined; + } + } + if (typeof fromName === 'string') { + name = fromName; + } + if (name === undefined) { + throw new Error('Could not extract file name from the provided input.'); + } + if (name.startsWith('https://')) { + const suffix = name.split('files/')[1]; + const match = suffix.match(/[a-z0-9]+/); + if (match === null) { + throw new Error(`Could not extract file name from URI ${name}`); + } + name = match[0]; + } + else if (name.startsWith('files/')) { + name = name.split('files/')[1]; + } + return name; +} +function tModelsUrl(apiClient, baseModels) { + let res; + if (apiClient.isVertexAI()) { + res = baseModels ? 'publishers/google/models' : 'models'; + } + else { + res = baseModels ? 'models' : 'tunedModels'; + } + return res; +} +function tExtractModels(response) { + for (const key of ['models', 'tunedModels', 'publisherModels']) { + if (hasField(response, key)) { + return response[key]; + } + } + return []; +} +function hasField(data, fieldName) { + return data !== null && typeof data === 'object' && fieldName in data; +} +function mcpToGeminiTool(mcpTool, config = {}) { + const mcpToolSchema = mcpTool; + const functionDeclaration = { + name: mcpToolSchema['name'], + description: mcpToolSchema['description'], + parametersJsonSchema: mcpToolSchema['inputSchema'], + }; + if (config.behavior) { + functionDeclaration['behavior'] = config.behavior; + } + const geminiTool = { + functionDeclarations: [ + functionDeclaration, + ], + }; + return geminiTool; +} +/** + * Converts a list of MCP tools to a single Gemini tool with a list of function + * declarations. + */ +function mcpToolsToGeminiTool(mcpTools, config = {}) { + const functionDeclarations = []; + const toolNames = new Set(); + for (const mcpTool of mcpTools) { + const mcpToolName = mcpTool.name; + if (toolNames.has(mcpToolName)) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + toolNames.add(mcpToolName); + const geminiTool = mcpToGeminiTool(mcpTool, config); + if (geminiTool.functionDeclarations) { + functionDeclarations.push(...geminiTool.functionDeclarations); + } + } + return { functionDeclarations: functionDeclarations }; +} +// Transforms a source input into a BatchJobSource object with validation. +function tBatchJobSource(apiClient, src) { + if (typeof src !== 'string' && !Array.isArray(src)) { + if (apiClient && apiClient.isVertexAI()) { + if (src.gcsUri && src.bigqueryUri) { + throw new Error('Only one of `gcsUri` or `bigqueryUri` can be set.'); + } + else if (!src.gcsUri && !src.bigqueryUri) { + throw new Error('One of `gcsUri` or `bigqueryUri` must be set.'); + } + } + else { + // Logic for non-Vertex AI client (inlined_requests, file_name) + if (src.inlinedRequests && src.fileName) { + throw new Error('Only one of `inlinedRequests` or `fileName` can be set.'); + } + else if (!src.inlinedRequests && !src.fileName) { + throw new Error('One of `inlinedRequests` or `fileName` must be set.'); + } + } + return src; + } + // If src is an array (list in Python) + else if (Array.isArray(src)) { + return { inlinedRequests: src }; + } + else if (typeof src === 'string') { + if (src.startsWith('gs://')) { + return { + format: 'jsonl', + gcsUri: [src], // GCS URI is expected as an array + }; + } + else if (src.startsWith('bq://')) { + return { + format: 'bigquery', + bigqueryUri: src, + }; + } + else if (src.startsWith('files/')) { + return { + fileName: src, + }; + } + } + throw new Error(`Unsupported source: ${src}`); +} +function tBatchJobDestination(dest) { + if (typeof dest !== 'string') { + return dest; + } + const destString = dest; + if (destString.startsWith('gs://')) { + return { + format: 'jsonl', + gcsUri: destString, + }; + } + else if (destString.startsWith('bq://')) { + return { + format: 'bigquery', + bigqueryUri: destString, + }; + } + else { + throw new Error(`Unsupported destination: ${destString}`); + } +} +function tBatchJobName(apiClient, name) { + const nameString = name; + if (!apiClient.isVertexAI()) { + const mldevPattern = /batches\/[^/]+$/; + if (mldevPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } + } + const vertexPattern = /^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/; + if (vertexPattern.test(nameString)) { + return nameString.split('/').pop(); + } + else if (/^\d+$/.test(nameString)) { + return nameString; + } + else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } +} +function tJobState(state) { + const stateString = state; + if (stateString === 'BATCH_STATE_UNSPECIFIED') { + return 'JOB_STATE_UNSPECIFIED'; + } + else if (stateString === 'BATCH_STATE_PENDING') { + return 'JOB_STATE_PENDING'; + } + else if (stateString === 'BATCH_STATE_SUCCEEDED') { + return 'JOB_STATE_SUCCEEDED'; + } + else if (stateString === 'BATCH_STATE_FAILED') { + return 'JOB_STATE_FAILED'; + } + else if (stateString === 'BATCH_STATE_CANCELLED') { + return 'JOB_STATE_CANCELLED'; + } + else { + return stateString; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$4(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$4(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$4(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$4(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$4(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$4(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$4(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev$1(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$4(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$4(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$4(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$4(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$4(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$4(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$4(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$4() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$4(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$4(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$4(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$4(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$4(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$4()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$4(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev$2(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev$2(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$2(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev$2(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$3(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$3(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$3(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$3(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$3(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev$1(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$4(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToMldev$1(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev$1(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$4(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$2(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToMldev$3(tSpeechConfig(fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev$1(fromThinkingConfig)); + } + return toObject; +} +function inlinedRequestToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['request', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$4(item); + }); + } + setValueByPath(toObject, ['request', 'contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['request', 'generationConfig'], generateContentConfigToMldev$1(apiClient, fromConfig, toObject)); + } + return toObject; +} +function batchJobSourceToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['format']) !== undefined) { + throw new Error('format parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['bigqueryUri']) !== undefined) { + throw new Error('bigqueryUri parameter is not supported in Gemini API.'); + } + const fromFileName = getValueByPath(fromObject, ['fileName']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedRequests = getValueByPath(fromObject, [ + 'inlinedRequests', + ]); + if (fromInlinedRequests != null) { + let transformedList = fromInlinedRequests; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedRequestToMldev(apiClient, item); + }); + } + setValueByPath(toObject, ['requests', 'requests'], transformedList); + } + return toObject; +} +function createBatchJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['batch', 'displayName'], fromDisplayName); + } + if (getValueByPath(fromObject, ['dest']) !== undefined) { + throw new Error('dest parameter is not supported in Gemini API.'); + } + return toObject; +} +function createBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['batch', 'inputConfig'], batchJobSourceToMldev(apiClient, tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createBatchJobConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + if (getValueByPath(fromObject, ['filter']) !== undefined) { + throw new Error('filter parameter is not supported in Gemini API.'); + } + return toObject; +} +function listBatchJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listBatchJobsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function deleteBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function batchJobSourceToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['instancesFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsSource', 'uris'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigquerySource', 'inputUri'], fromBigqueryUri); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['inlinedRequests']) !== undefined) { + throw new Error('inlinedRequests parameter is not supported in Vertex AI.'); + } + return toObject; +} +function batchJobDestinationToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['predictionsFormat'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsDestination', 'outputUriPrefix'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ['bigqueryUri']); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryDestination', 'outputUri'], fromBigqueryUri); + } + if (getValueByPath(fromObject, ['fileName']) !== undefined) { + throw new Error('fileName parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['inlinedResponses']) !== undefined) { + throw new Error('inlinedResponses parameter is not supported in Vertex AI.'); + } + return toObject; +} +function createBatchJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDest = getValueByPath(fromObject, ['dest']); + if (parentObject !== undefined && fromDest != null) { + setValueByPath(parentObject, ['outputConfig'], batchJobDestinationToVertex(tBatchJobDestination(fromDest))); + } + return toObject; +} +function createBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ['src']); + if (fromSrc != null) { + setValueByPath(toObject, ['inputConfig'], batchJobSourceToVertex(tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createBatchJobConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listBatchJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listBatchJobsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function deleteBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tBatchJobName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev$2(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$2(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$2(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromMldev$1(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev$2(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev$1(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev$2(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev$1(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev$1(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function jobErrorFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + return toObject; +} +function inlinedResponseFromMldev(fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateContentResponseFromMldev$1(fromResponse)); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError)); + } + return toObject; +} +function batchJobDestinationFromMldev(fromObject) { + const toObject = {}; + const fromFileName = getValueByPath(fromObject, ['responsesFile']); + if (fromFileName != null) { + setValueByPath(toObject, ['fileName'], fromFileName); + } + const fromInlinedResponses = getValueByPath(fromObject, [ + 'inlinedResponses', + 'inlinedResponses', + ]); + if (fromInlinedResponses != null) { + let transformedList = fromInlinedResponses; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedResponseFromMldev(item); + }); + } + setValueByPath(toObject, ['inlinedResponses'], transformedList); + } + return toObject; +} +function batchJobFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, [ + 'metadata', + 'displayName', + ]); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['metadata', 'state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, [ + 'metadata', + 'createTime', + ]); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'metadata', + 'endTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, [ + 'metadata', + 'updateTime', + ]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['metadata', 'model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromDest = getValueByPath(fromObject, ['metadata', 'output']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromMldev(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, ['operations']); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromMldev(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function deleteResourceJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError)); + } + return toObject; +} +function jobErrorFromVertex(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + return toObject; +} +function batchJobSourceFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['instancesFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ['gcsSource', 'uris']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigquerySource', + 'inputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + return toObject; +} +function batchJobDestinationFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ['predictionsFormat']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, [ + 'gcsDestination', + 'outputUriPrefix', + ]); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + 'bigqueryDestination', + 'outputUri', + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri); + } + return toObject; +} +function batchJobFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tJobState(fromState)); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromSrc = getValueByPath(fromObject, ['inputConfig']); + if (fromSrc != null) { + setValueByPath(toObject, ['src'], batchJobSourceFromVertex(fromSrc)); + } + const fromDest = getValueByPath(fromObject, ['outputConfig']); + if (fromDest != null) { + setValueByPath(toObject, ['dest'], batchJobDestinationFromVertex(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, [ + 'batchPredictionJobs', + ]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromVertex(item); + }); + } + setValueByPath(toObject, ['batchJobs'], transformedList); + } + return toObject; +} +function deleteResourceJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +var PagedItem; +(function (PagedItem) { + PagedItem["PAGED_ITEM_BATCH_JOBS"] = "batchJobs"; + PagedItem["PAGED_ITEM_MODELS"] = "models"; + PagedItem["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs"; + PagedItem["PAGED_ITEM_FILES"] = "files"; + PagedItem["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents"; +})(PagedItem || (PagedItem = {})); +/** + * Pager class for iterating through paginated results. + */ +class Pager { + constructor(name, request, response, params) { + this.pageInternal = []; + this.paramsInternal = {}; + this.requestInternal = request; + this.init(name, response, params); + } + init(name, response, params) { + var _a, _b; + this.nameInternal = name; + this.pageInternal = response[this.nameInternal] || []; + this.sdkHttpResponseInternal = response === null || response === void 0 ? void 0 : response.sdkHttpResponse; + this.idxInternal = 0; + let requestParams = { config: {} }; + if (!params || Object.keys(params).length === 0) { + requestParams = { config: {} }; + } + else if (typeof params === 'object') { + requestParams = Object.assign({}, params); + } + else { + requestParams = params; + } + if (requestParams['config']) { + requestParams['config']['pageToken'] = response['nextPageToken']; + } + this.paramsInternal = requestParams; + this.pageInternalSize = + (_b = (_a = requestParams['config']) === null || _a === void 0 ? void 0 : _a['pageSize']) !== null && _b !== void 0 ? _b : this.pageInternal.length; + } + initNextPage(response) { + this.init(this.nameInternal, response, this.paramsInternal); + } + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page() { + return this.pageInternal; + } + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name() { + return this.nameInternal; + } + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize() { + return this.pageInternalSize; + } + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse() { + return this.sdkHttpResponseInternal; + } + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params() { + return this.paramsInternal; + } + /** + * Returns the total number of items in the current page. + */ + get pageLength() { + return this.pageInternal.length; + } + /** + * Returns the item at the given index. + */ + getItem(index) { + return this.pageInternal[index]; + } + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator]() { + return { + next: async () => { + if (this.idxInternal >= this.pageLength) { + if (this.hasNextPage()) { + await this.nextPage(); + } + else { + return { value: undefined, done: true }; + } + } + const item = this.getItem(this.idxInternal); + this.idxInternal += 1; + return { value: item, done: false }; + }, + return: async () => { + return { value: undefined, done: true }; + }, + }; + } + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + async nextPage() { + if (!this.hasNextPage()) { + throw new Error('No more pages to fetch.'); + } + const response = await this.requestInternal(this.params); + this.initNextPage(response); + return this.page; + } + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage() { + var _a; + if (((_a = this.params['config']) === null || _a === void 0 ? void 0 : _a['pageToken']) !== undefined) { + return true; + } + return false; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Batches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + this.create = async (params) => { + var _a, _b; + if (this.apiClient.isVertexAI()) { + const timestamp = Date.now(); + const timestampStr = timestamp.toString(); + if (Array.isArray(params.src)) { + throw new Error('InlinedRequest[] is not supported in Vertex AI. Please use ' + + 'Google Cloud Storage URI or BigQuery URI instead.'); + } + params.config = params.config || {}; + if (params.config.displayName === undefined) { + params.config.displayName = 'genaiBatchJob_${timestampStr}'; + } + if (params.config.dest === undefined && typeof params.src === 'string') { + if (params.src.startsWith('gs://') && params.src.endsWith('.jsonl')) { + params.config.dest = `${params.src.slice(0, -6)}/dest`; + } + else if (params.src.startsWith('bq://')) { + params.config.dest = + `${params.src}_dest_${timestampStr}`; + } + else { + throw new Error('Unsupported source:' + params.src); + } + } + } + else { + if (Array.isArray(params.src) || + (typeof params.src !== 'string' && params.src.inlinedRequests)) { + // Move system instruction to httpOptions extraBody. + let path = ''; + let queryParams = {}; + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchGenerateContent', body['_url']); + queryParams = body['_query']; + // Move system instruction to 'request': + // {'systemInstruction': system_instruction} + const batch = body['batch']; + const inputConfig = batch['inputConfig']; + const requestsWrapper = inputConfig['requests']; + const requests = requestsWrapper['requests']; + const newRequests = []; + for (const request of requests) { + const requestDict = request; + if (requestDict['systemInstruction']) { + const systemInstructionValue = requestDict['systemInstruction']; + delete requestDict['systemInstruction']; + const requestContent = requestDict['request']; + requestContent['systemInstruction'] = systemInstructionValue; + requestDict['request'] = requestContent; + } + newRequests.push(requestDict); + } + requestsWrapper['requests'] = newRequests; + delete body['config']; + delete body['_url']; + delete body['_query']; + const response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + return await this.createInternal(params); + }; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_BATCH_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + async createInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchGenerateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + } + else { + const body = cancelBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}:cancel', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listBatchJobsParametersToVertex(params); + path = formatMap('batchPredictionJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromVertex(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listBatchJobsParametersToMldev(params); + path = formatMap('batches', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromMldev(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteBatchJobParametersToVertex(this.apiClient, params); + path = formatMap('batchPredictionJobs/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = deleteBatchJobParametersToMldev(this.apiClient, params); + path = formatMap('batches/{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$3(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$3(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$3(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$3(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$3(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$3(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$3(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$3(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$3(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$3(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$3(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$3(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$3(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$3(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$3() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$3(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$3(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$3(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$3(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$3(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$3()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$3(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev$1(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev$1(fromRetrievalConfig)); + } + return toObject; +} +function createCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$3(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$3(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$3(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev$1(fromToolConfig)); + } + if (getValueByPath(fromObject, ['kmsKeyName']) !== undefined) { + throw new Error('kmsKeyName parameter is not supported in Gemini API.'); + } + return toObject; +} +function createCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createCachedContentConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataToVertex$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex$2(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$2(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex$2(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex$2(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$2(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex$2(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex$2(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$2(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$2(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$2(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex$2(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex$2(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex$2()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex$2(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToVertex$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToVertex$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex$1(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToVertex$1(fromRetrievalConfig)); + } + return toObject; +} +function createCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex$2(item); + }); + } + setValueByPath(parentObject, ['contents'], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$2(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex$1(fromToolConfig)); + } + const fromKmsKeyName = getValueByPath(fromObject, ['kmsKeyName']); + if (parentObject !== undefined && fromKmsKeyName != null) { + setValueByPath(parentObject, ['encryption_spec', 'kmsKeyName'], fromKmsKeyName); + } + return toObject; +} +function createCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createCachedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ['ttl']); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ['ttl'], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateCachedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function listCachedContentsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listCachedContentsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function cachedContentFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromMldev() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromMldev(item); + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} +function cachedContentFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (fromExpireTime != null) { + setValueByPath(toObject, ['expireTime'], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromVertex() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, [ + 'cachedContents', + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromVertex(item); + }); + } + setValueByPath(toObject, ['cachedContents'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Caches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_CACHED_CONTENTS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + async create(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = createCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromVertex(); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromMldev(); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateCachedContentParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } + else { + const body = updateCachedContentParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listCachedContentsParametersToVertex(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromVertex(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listCachedContentsParametersToMldev(params); + path = formatMap('cachedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromMldev(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns true if the response is valid, false otherwise. + */ +function isValidResponse(response) { + var _a; + if (response.candidates == undefined || response.candidates.length === 0) { + return false; + } + const content = (_a = response.candidates[0]) === null || _a === void 0 ? void 0 : _a.content; + if (content === undefined) { + return false; + } + return isValidContent(content); +} +function isValidContent(content) { + if (content.parts === undefined || content.parts.length === 0) { + return false; + } + for (const part of content.parts) { + if (part === undefined || Object.keys(part).length === 0) { + return false; + } + } + return true; +} +/** + * Validates the history contains the correct roles. + * + * @throws Error if the history does not start with a user turn. + * @throws Error if the history contains an invalid role. + */ +function validateHistory(history) { + // Empty history is valid. + if (history.length === 0) { + return; + } + for (const content of history) { + if (content.role !== 'user' && content.role !== 'model') { + throw new Error(`Role must be user or model, but got ${content.role}.`); + } + } +} +/** + * Extracts the curated (valid) history from a comprehensive history. + * + * @remarks + * The model may sometimes generate invalid or empty contents(e.g., due to safty + * filters or recitation). Extracting valid turns from the history + * ensures that subsequent requests could be accpeted by the model. + */ +function extractCuratedHistory(comprehensiveHistory) { + if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) { + return []; + } + const curatedHistory = []; + const length = comprehensiveHistory.length; + let i = 0; + while (i < length) { + if (comprehensiveHistory[i].role === 'user') { + curatedHistory.push(comprehensiveHistory[i]); + i++; + } + else { + const modelOutput = []; + let isValid = true; + while (i < length && comprehensiveHistory[i].role === 'model') { + modelOutput.push(comprehensiveHistory[i]); + if (isValid && !isValidContent(comprehensiveHistory[i])) { + isValid = false; + } + i++; + } + if (isValid) { + curatedHistory.push(...modelOutput); + } + else { + // Remove the last user input when model content is invalid. + curatedHistory.pop(); + } + } + } + return curatedHistory; +} +/** + * A utility class to create a chat session. + */ +class Chats { + constructor(modelsModule, apiClient) { + this.modelsModule = modelsModule; + this.apiClient = apiClient; + } + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params) { + return new Chat(this.apiClient, this.modelsModule, params.model, params.config, + // Deep copy the history to avoid mutating the history outside of the + // chat session. + structuredClone(params.history)); + } +} +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +class Chat { + constructor(apiClient, modelsModule, model, config = {}, history = []) { + this.apiClient = apiClient; + this.modelsModule = modelsModule; + this.model = model; + this.config = config; + this.history = history; + // A promise to represent the current state of the message being sent to the + // model. + this.sendPromise = Promise.resolve(); + validateHistory(history); + } + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + async sendMessage(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const responsePromise = this.modelsModule.generateContent({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + this.sendPromise = (async () => { + var _a, _b, _c; + const response = await responsePromise; + const outputContent = (_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content; + // Because the AFC input contains the entire curated chat history in + // addition to the new user input, we need to truncate the AFC history + // to deduplicate the existing chat history. + const fullAutomaticFunctionCallingHistory = response.automaticFunctionCallingHistory; + const index = this.getHistory(true).length; + let automaticFunctionCallingHistory = []; + if (fullAutomaticFunctionCallingHistory != null) { + automaticFunctionCallingHistory = + (_c = fullAutomaticFunctionCallingHistory.slice(index)) !== null && _c !== void 0 ? _c : []; + } + const modelOutput = outputContent ? [outputContent] : []; + this.recordHistory(inputContent, modelOutput, automaticFunctionCallingHistory); + return; + })(); + await this.sendPromise.catch(() => { + // Resets sendPromise to avoid subsequent calls failing + this.sendPromise = Promise.resolve(); + }); + return responsePromise; + } + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + async sendMessageStream(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const streamResponse = this.modelsModule.generateContentStream({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + // Resolve the internal tracking of send completion promise - `sendPromise` + // for both success and failure response. The actual failure is still + // propagated by the `await streamResponse`. + this.sendPromise = streamResponse + .then(() => undefined) + .catch(() => undefined); + const response = await streamResponse; + const result = this.processStreamResponse(response, inputContent); + return result; + } + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated = false) { + const history = curated + ? extractCuratedHistory(this.history) + : this.history; + // Deep copy the history to avoid mutating the history outside of the + // chat session. + return structuredClone(history); + } + processStreamResponse(streamResponse, inputContent) { + var _a, _b; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + var _c, e_1, _d, _e; + const outputContent = []; + try { + for (var _f = true, streamResponse_1 = __asyncValues(streamResponse), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()), _c = streamResponse_1_1.done, !_c; _f = true) { + _e = streamResponse_1_1.value; + _f = false; + const chunk = _e; + if (isValidResponse(chunk)) { + const content = (_b = (_a = chunk.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content; + if (content !== undefined) { + outputContent.push(content); + } + } + yield yield __await(chunk); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_c && (_d = streamResponse_1.return)) yield __await(_d.call(streamResponse_1)); + } + finally { if (e_1) throw e_1.error; } + } + this.recordHistory(inputContent, outputContent); + }); + } + recordHistory(userInput, modelOutput, automaticFunctionCallingHistory) { + let outputContents = []; + if (modelOutput.length > 0 && + modelOutput.every((content) => content.role !== undefined)) { + outputContents = modelOutput; + } + else { + // Appends an empty content when model returns empty response, so that the + // history is always alternating between user and model. + outputContents.push({ + role: 'model', + parts: [], + }); + } + if (automaticFunctionCallingHistory && + automaticFunctionCallingHistory.length > 0) { + this.history.push(...extractCuratedHistory(automaticFunctionCallingHistory)); + } + else { + this.history.push(userInput); + } + this.history.push(...outputContents); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * API errors raised by the GenAI API. + */ +class ApiError extends Error { + constructor(options) { + super(options.message); + this.name = 'ApiError'; + this.status = options.status; + Object.setPrototypeOf(this, ApiError.prototype); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function listFilesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + return toObject; +} +function listFilesParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listFilesConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function fileStatusToMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusToMldev(fromError)); + } + return toObject; +} +function createFileParametersToMldev(fromObject) { + const toObject = {}; + const fromFile = getValueByPath(fromObject, ['file']); + if (fromFile != null) { + setValueByPath(toObject, ['file'], fileToMldev(fromFile)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function deleteFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'file'], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fileStatusFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ['details']); + if (fromDetails != null) { + setValueByPath(toObject, ['details'], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ['message']); + if (fromMessage != null) { + setValueByPath(toObject, ['message'], fromMessage); + } + const fromCode = getValueByPath(fromObject, ['code']); + if (fromCode != null) { + setValueByPath(toObject, ['code'], fromCode); + } + return toObject; +} +function fileFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ['sizeBytes']); + if (fromSizeBytes != null) { + setValueByPath(toObject, ['sizeBytes'], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, [ + 'expirationTime', + ]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ['expirationTime'], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ['sha256Hash']); + if (fromSha256Hash != null) { + setValueByPath(toObject, ['sha256Hash'], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ['downloadUri']); + if (fromDownloadUri != null) { + setValueByPath(toObject, ['downloadUri'], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], fromState); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['source'], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fileStatusFromMldev(fromError)); + } + return toObject; +} +function listFilesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromFiles = getValueByPath(fromObject, ['files']); + if (fromFiles != null) { + let transformedList = fromFiles; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return fileFromMldev(item); + }); + } + setValueByPath(toObject, ['files'], transformedList); + } + return toObject; +} +function createFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + return toObject; +} +function deleteFileResponseFromMldev() { + const toObject = {}; + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Files extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_FILES, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + } + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + async upload(params) { + if (this.apiClient.isVertexAI()) { + throw new Error('Vertex AI does not support uploading files. You can share files through a GCS bucket.'); + } + return this.apiClient + .uploadFile(params.file, params.config) + .then((response) => { + const file = fileFromMldev(response); + return file; + }); + } + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + async download(params) { + await this.apiClient.downloadFile(params); + } + async listInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = listFilesParametersToMldev(params); + path = formatMap('files', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listFilesResponseFromMldev(apiResponse); + const typedResp = new ListFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async createInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createFileParametersToMldev(params); + path = formatMap('upload/v1beta/files', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = createFileResponseFromMldev(apiResponse); + const typedResp = new CreateFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + async get(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = getFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = fileFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + async delete(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = deleteFileParametersToMldev(params); + path = formatMap('files/{file}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteFileResponseFromMldev(); + const typedResp = new DeleteFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$2(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$2(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$2(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$2(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$2(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$2(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$2(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$2(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$2(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$2(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$2(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$2(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$2(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$2(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$2()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$2(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is not supported in Gemini API.'); + } + return toObject; +} +function audioTranscriptionConfigToMldev$1() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev$1(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev$1(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToMldev$1(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev$1(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToMldev$1(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToMldev$1(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev$1(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToMldev$2(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$2(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev$1(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToMldev$1()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToMldev$1()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToMldev$1(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToMldev$1(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToMldev$1(fromProactivity)); + } + return toObject; +} +function liveConnectParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev$1(fromConfig, toObject)); + } + return toObject; +} +function activityStartToMldev() { + const toObject = {}; + return toObject; +} +function activityEndToMldev() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToMldev(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + setValueByPath(toObject, ['mediaChunks'], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], activityStartToMldev()); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], activityEndToMldev()); + } + return toObject; +} +function weightedPromptToMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromWeight = getValueByPath(fromObject, ['weight']); + if (fromWeight != null) { + setValueByPath(toObject, ['weight'], fromWeight); + } + return toObject; +} +function liveMusicSetWeightedPromptsParametersToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigToMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ['guidance']); + if (fromGuidance != null) { + setValueByPath(toObject, ['guidance'], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ['bpm']); + if (fromBpm != null) { + setValueByPath(toObject, ['bpm'], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ['density']); + if (fromDensity != null) { + setValueByPath(toObject, ['density'], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ['brightness']); + if (fromBrightness != null) { + setValueByPath(toObject, ['brightness'], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ['scale']); + if (fromScale != null) { + setValueByPath(toObject, ['scale'], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ['muteBass']); + if (fromMuteBass != null) { + setValueByPath(toObject, ['muteBass'], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ['muteDrums']); + if (fromMuteDrums != null) { + setValueByPath(toObject, ['muteDrums'], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, [ + 'onlyBassAndDrums', + ]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums); + } + const fromMusicGenerationMode = getValueByPath(fromObject, [ + 'musicGenerationMode', + ]); + if (fromMusicGenerationMode != null) { + setValueByPath(toObject, ['musicGenerationMode'], fromMusicGenerationMode); + } + return toObject; +} +function liveMusicSetConfigParametersToMldev(fromObject) { + const toObject = {}; + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig)); + } + return toObject; +} +function liveMusicClientSetupToMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + return toObject; +} +function liveMusicClientContentToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicClientMessageToMldev(fromObject) { + const toObject = {}; + const fromSetup = getValueByPath(fromObject, ['setup']); + if (fromSetup != null) { + setValueByPath(toObject, ['setup'], liveMusicClientSetupToMldev(fromSetup)); + } + const fromClientContent = getValueByPath(fromObject, [ + 'clientContent', + ]); + if (fromClientContent != null) { + setValueByPath(toObject, ['clientContent'], liveMusicClientContentToMldev(fromClientContent)); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig)); + } + const fromPlaybackControl = getValueByPath(fromObject, [ + 'playbackControl', + ]); + if (fromPlaybackControl != null) { + setValueByPath(toObject, ['playbackControl'], fromPlaybackControl); + } + return toObject; +} +function prebuiltVoiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex$1(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex$1(fromVoiceConfig)); + } + if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) { + throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.'); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex$1(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex$1(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex$1(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex$1(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$1(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex$1(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex$1(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$1(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex$1(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex$1(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex$1(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex$1(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex$1()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex$1(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToVertex(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + const fromTransparent = getValueByPath(fromObject, ['transparent']); + if (fromTransparent != null) { + setValueByPath(toObject, ['transparent'], fromTransparent); + } + return toObject; +} +function audioTranscriptionConfigToVertex() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToVertex(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToVertex(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToVertex(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToVertex(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToVertex(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToVertex(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToVertex(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToVertex$1(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToVertex(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToVertex()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToVertex()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToVertex(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToVertex(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToVertex(fromProactivity)); + } + return toObject; +} +function liveConnectParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function activityStartToVertex() { + const toObject = {}; + return toObject; +} +function activityEndToVertex() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToVertex(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ['media']); + if (fromMedia != null) { + setValueByPath(toObject, ['mediaChunks'], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ['audio']); + if (fromAudio != null) { + setValueByPath(toObject, ['audio'], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, [ + 'audioStreamEnd', + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromActivityStart = getValueByPath(fromObject, [ + 'activityStart', + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ['activityStart'], activityStartToVertex()); + } + const fromActivityEnd = getValueByPath(fromObject, ['activityEnd']); + if (fromActivityEnd != null) { + setValueByPath(toObject, ['activityEnd'], activityEndToVertex()); + } + return toObject; +} +function liveServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function videoMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev$1(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$1(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function transcriptionFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFinished = getValueByPath(fromObject, ['finished']); + if (fromFinished != null) { + setValueByPath(toObject, ['finished'], fromFinished); + } + return toObject; +} +function urlMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$1(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function liveServerContentFromMldev(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn != null) { + setValueByPath(toObject, ['modelTurn'], contentFromMldev$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete != null) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted != null) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + 'generationComplete', + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ['generationComplete'], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + 'inputTranscription', + ]); + if (fromInputTranscription != null) { + setValueByPath(toObject, ['inputTranscription'], transcriptionFromMldev(fromInputTranscription)); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + 'outputTranscription', + ]); + if (fromOutputTranscription != null) { + setValueByPath(toObject, ['outputTranscription'], transcriptionFromMldev(fromOutputTranscription)); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev$1(fromUrlContextMetadata)); + } + return toObject; +} +function functionCallFromMldev(fromObject) { + const toObject = {}; + const fromId = getValueByPath(fromObject, ['id']); + if (fromId != null) { + setValueByPath(toObject, ['id'], fromId); + } + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromMldev(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromMldev(item); + }); + } + setValueByPath(toObject, ['functionCalls'], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromMldev(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds != null) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function modalityTokenCountFromMldev(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ['modality']); + if (fromModality != null) { + setValueByPath(toObject, ['modality'], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function usageMetadataFromMldev(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, [ + 'promptTokenCount', + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + 'responseTokenCount', + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ['responseTokenCount'], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + 'toolUsePromptTokenCount', + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ['toolUsePromptTokenCount'], fromToolUsePromptTokenCount); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + 'thoughtsTokenCount', + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ['thoughtsTokenCount'], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, [ + 'totalTokenCount', + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + 'promptTokensDetails', + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['promptTokensDetails'], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + 'cacheTokensDetails', + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['cacheTokensDetails'], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + 'responseTokensDetails', + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['responseTokensDetails'], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + 'toolUsePromptTokensDetails', + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ['toolUsePromptTokensDetails'], transformedList); + } + return toObject; +} +function liveServerGoAwayFromMldev(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ['timeLeft']); + if (fromTimeLeft != null) { + setValueByPath(toObject, ['timeLeft'], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromMldev(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ['newHandle']); + if (fromNewHandle != null) { + setValueByPath(toObject, ['newHandle'], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ['resumable']); + if (fromResumable != null) { + setValueByPath(toObject, ['resumable'], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + 'lastConsumedClientMessageIndex', + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath(toObject, ['lastConsumedClientMessageIndex'], fromLastConsumedClientMessageIndex); + } + return toObject; +} +function liveServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveServerSetupCompleteFromMldev()); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromMldev(fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromMldev(fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromMldev(fromToolCallCancellation)); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], usageMetadataFromMldev(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject, ['goAway']); + if (fromGoAway != null) { + setValueByPath(toObject, ['goAway'], liveServerGoAwayFromMldev(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + 'sessionResumptionUpdate', + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ['sessionResumptionUpdate'], liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate)); + } + return toObject; +} +function liveMusicServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function weightedPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromWeight = getValueByPath(fromObject, ['weight']); + if (fromWeight != null) { + setValueByPath(toObject, ['weight'], fromWeight); + } + return toObject; +} +function liveMusicClientContentFromMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, [ + 'weightedPrompts', + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptFromMldev(item); + }); + } + setValueByPath(toObject, ['weightedPrompts'], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigFromMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ['guidance']); + if (fromGuidance != null) { + setValueByPath(toObject, ['guidance'], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ['bpm']); + if (fromBpm != null) { + setValueByPath(toObject, ['bpm'], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ['density']); + if (fromDensity != null) { + setValueByPath(toObject, ['density'], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ['brightness']); + if (fromBrightness != null) { + setValueByPath(toObject, ['brightness'], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ['scale']); + if (fromScale != null) { + setValueByPath(toObject, ['scale'], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ['muteBass']); + if (fromMuteBass != null) { + setValueByPath(toObject, ['muteBass'], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ['muteDrums']); + if (fromMuteDrums != null) { + setValueByPath(toObject, ['muteDrums'], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, [ + 'onlyBassAndDrums', + ]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums); + } + const fromMusicGenerationMode = getValueByPath(fromObject, [ + 'musicGenerationMode', + ]); + if (fromMusicGenerationMode != null) { + setValueByPath(toObject, ['musicGenerationMode'], fromMusicGenerationMode); + } + return toObject; +} +function liveMusicSourceMetadataFromMldev(fromObject) { + const toObject = {}; + const fromClientContent = getValueByPath(fromObject, [ + 'clientContent', + ]); + if (fromClientContent != null) { + setValueByPath(toObject, ['clientContent'], liveMusicClientContentFromMldev(fromClientContent)); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + 'musicGenerationConfig', + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ['musicGenerationConfig'], liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig)); + } + return toObject; +} +function audioChunkFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + const fromSourceMetadata = getValueByPath(fromObject, [ + 'sourceMetadata', + ]); + if (fromSourceMetadata != null) { + setValueByPath(toObject, ['sourceMetadata'], liveMusicSourceMetadataFromMldev(fromSourceMetadata)); + } + return toObject; +} +function liveMusicServerContentFromMldev(fromObject) { + const toObject = {}; + const fromAudioChunks = getValueByPath(fromObject, ['audioChunks']); + if (fromAudioChunks != null) { + let transformedList = fromAudioChunks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return audioChunkFromMldev(item); + }); + } + setValueByPath(toObject, ['audioChunks'], transformedList); + } + return toObject; +} +function liveMusicFilteredPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFilteredReason = getValueByPath(fromObject, [ + 'filteredReason', + ]); + if (fromFilteredReason != null) { + setValueByPath(toObject, ['filteredReason'], fromFilteredReason); + } + return toObject; +} +function liveMusicServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveMusicServerSetupCompleteFromMldev()); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveMusicServerContentFromMldev(fromServerContent)); + } + const fromFilteredPrompt = getValueByPath(fromObject, [ + 'filteredPrompt', + ]); + if (fromFilteredPrompt != null) { + setValueByPath(toObject, ['filteredPrompt'], liveMusicFilteredPromptFromMldev(fromFilteredPrompt)); + } + return toObject; +} +function liveServerSetupCompleteFromVertex(fromObject) { + const toObject = {}; + const fromSessionId = getValueByPath(fromObject, ['sessionId']); + if (fromSessionId != null) { + setValueByPath(toObject, ['sessionId'], fromSessionId); + } + return toObject; +} +function videoMetadataFromVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromVertex$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function transcriptionFromVertex(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + const fromFinished = getValueByPath(fromObject, ['finished']); + if (fromFinished != null) { + setValueByPath(toObject, ['finished'], fromFinished); + } + return toObject; +} +function liveServerContentFromVertex(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ['modelTurn']); + if (fromModelTurn != null) { + setValueByPath(toObject, ['modelTurn'], contentFromVertex$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ['turnComplete']); + if (fromTurnComplete != null) { + setValueByPath(toObject, ['turnComplete'], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ['interrupted']); + if (fromInterrupted != null) { + setValueByPath(toObject, ['interrupted'], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + 'generationComplete', + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ['generationComplete'], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + 'inputTranscription', + ]); + if (fromInputTranscription != null) { + setValueByPath(toObject, ['inputTranscription'], transcriptionFromVertex(fromInputTranscription)); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + 'outputTranscription', + ]); + if (fromOutputTranscription != null) { + setValueByPath(toObject, ['outputTranscription'], transcriptionFromVertex(fromOutputTranscription)); + } + return toObject; +} +function functionCallFromVertex(fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ['args']); + if (fromArgs != null) { + setValueByPath(toObject, ['args'], fromArgs); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} +function liveServerToolCallFromVertex(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, [ + 'functionCalls', + ]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromVertex(item); + }); + } + setValueByPath(toObject, ['functionCalls'], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromVertex(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ['ids']); + if (fromIds != null) { + setValueByPath(toObject, ['ids'], fromIds); + } + return toObject; +} +function modalityTokenCountFromVertex(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ['modality']); + if (fromModality != null) { + setValueByPath(toObject, ['modality'], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function usageMetadataFromVertex(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, [ + 'promptTokenCount', + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + 'candidatesTokenCount', + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ['responseTokenCount'], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + 'toolUsePromptTokenCount', + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ['toolUsePromptTokenCount'], fromToolUsePromptTokenCount); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + 'thoughtsTokenCount', + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ['thoughtsTokenCount'], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, [ + 'totalTokenCount', + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + 'promptTokensDetails', + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['promptTokensDetails'], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + 'cacheTokensDetails', + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['cacheTokensDetails'], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + 'candidatesTokensDetails', + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['responseTokensDetails'], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + 'toolUsePromptTokensDetails', + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ['toolUsePromptTokensDetails'], transformedList); + } + const fromTrafficType = getValueByPath(fromObject, ['trafficType']); + if (fromTrafficType != null) { + setValueByPath(toObject, ['trafficType'], fromTrafficType); + } + return toObject; +} +function liveServerGoAwayFromVertex(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ['timeLeft']); + if (fromTimeLeft != null) { + setValueByPath(toObject, ['timeLeft'], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromVertex(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ['newHandle']); + if (fromNewHandle != null) { + setValueByPath(toObject, ['newHandle'], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ['resumable']); + if (fromResumable != null) { + setValueByPath(toObject, ['resumable'], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + 'lastConsumedClientMessageIndex', + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath(toObject, ['lastConsumedClientMessageIndex'], fromLastConsumedClientMessageIndex); + } + return toObject; +} +function liveServerMessageFromVertex(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, [ + 'setupComplete', + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ['setupComplete'], liveServerSetupCompleteFromVertex(fromSetupComplete)); + } + const fromServerContent = getValueByPath(fromObject, [ + 'serverContent', + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ['serverContent'], liveServerContentFromVertex(fromServerContent)); + } + const fromToolCall = getValueByPath(fromObject, ['toolCall']); + if (fromToolCall != null) { + setValueByPath(toObject, ['toolCall'], liveServerToolCallFromVertex(fromToolCall)); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + 'toolCallCancellation', + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ['toolCallCancellation'], liveServerToolCallCancellationFromVertex(fromToolCallCancellation)); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], usageMetadataFromVertex(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject, ['goAway']); + if (fromGoAway != null) { + setValueByPath(toObject, ['goAway'], liveServerGoAwayFromVertex(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + 'sessionResumptionUpdate', + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ['sessionResumptionUpdate'], liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev$1(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$1(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToMldev(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function safetySettingToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['method']) !== undefined) { + throw new Error('method parameter is not supported in Gemini API.'); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$1(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev$1(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev$1(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$1(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$1(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev$1(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev$1(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev$1()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev$1(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToMldev(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToMldev(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToMldev(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev$1(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$1(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$1(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev$1(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev$1(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToMldev$1(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToMldev(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ['routingConfig']) !== undefined) { + throw new Error('routingConfig parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined) { + throw new Error('modelSelectionConfig parameter is not supported in Gemini API.'); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$1(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToMldev(fromToolConfig)); + } + if (getValueByPath(fromObject, ['labels']) !== undefined) { + throw new Error('labels parameter is not supported in Gemini API.'); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToMldev$1(tSpeechConfig(fromSpeechConfig))); + } + if (getValueByPath(fromObject, ['audioTimestamp']) !== undefined) { + throw new Error('audioTimestamp parameter is not supported in Gemini API.'); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToMldev(fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['requests[]', 'taskType'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['requests[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['requests[]', 'outputDimensionality'], fromOutputDimensionality); + } + if (getValueByPath(fromObject, ['mimeType']) !== undefined) { + throw new Error('mimeType parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['autoTruncate']) !== undefined) { + throw new Error('autoTruncate parameter is not supported in Gemini API.'); + } + return toObject; +} +function embedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + setValueByPath(toObject, ['requests[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToMldev(fromConfig, toObject)); + } + const fromModelForEmbedContent = getValueByPath(fromObject, ['model']); + if (fromModelForEmbedContent !== undefined) { + setValueByPath(toObject, ['requests[]', 'model'], tModel(apiClient, fromModelForEmbedContent)); + } + return toObject; +} +function generateImagesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['negativePrompt']) !== undefined) { + throw new Error('negativePrompt parameter is not supported in Gemini API.'); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + if (getValueByPath(fromObject, ['addWatermark']) !== undefined) { + throw new Error('addWatermark parameter is not supported in Gemini API.'); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath(parentObject, ['parameters', 'sampleImageSize'], fromImageSize); + } + if (getValueByPath(fromObject, ['enhancePrompt']) !== undefined) { + throw new Error('enhancePrompt parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateImagesParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateImagesConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listModelsConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listModelsConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function updateModelConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateModelConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function deleteModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function countTokensConfigToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['systemInstruction']) !== undefined) { + throw new Error('systemInstruction parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['tools']) !== undefined) { + throw new Error('tools parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['generationConfig']) !== undefined) { + throw new Error('generationConfig parameter is not supported in Gemini API.'); + } + return toObject; +} +function countTokensParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToMldev(fromConfig)); + } + return toObject; +} +function imageToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generateVideosConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + if (getValueByPath(fromObject, ['outputGcsUri']) !== undefined) { + throw new Error('outputGcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['fps']) !== undefined) { + throw new Error('fps parameter is not supported in Gemini API.'); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + if (getValueByPath(fromObject, ['seed']) !== undefined) { + throw new Error('seed parameter is not supported in Gemini API.'); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + if (getValueByPath(fromObject, ['resolution']) !== undefined) { + throw new Error('resolution parameter is not supported in Gemini API.'); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + if (getValueByPath(fromObject, ['pubsubTopic']) !== undefined) { + throw new Error('pubsubTopic parameter is not supported in Gemini API.'); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + if (getValueByPath(fromObject, ['generateAudio']) !== undefined) { + throw new Error('generateAudio parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['lastFrame']) !== undefined) { + throw new Error('lastFrame parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['referenceImages']) !== undefined) { + throw new Error('referenceImages parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['compressionQuality']) !== undefined) { + throw new Error('compressionQuality parameter is not supported in Gemini API.'); + } + return toObject; +} +function generateVideosParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToMldev(fromImage)); + } + if (getValueByPath(fromObject, ['video']) !== undefined) { + throw new Error('video parameter is not supported in Gemini API.'); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataToVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToVertex(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function schemaToVertex(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ['anyOf']); + if (fromAnyOf != null) { + setValueByPath(toObject, ['anyOf'], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ['default']); + if (fromDefault != null) { + setValueByPath(toObject, ['default'], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ['enum']); + if (fromEnum != null) { + setValueByPath(toObject, ['enum'], fromEnum); + } + const fromExample = getValueByPath(fromObject, ['example']); + if (fromExample != null) { + setValueByPath(toObject, ['example'], fromExample); + } + const fromFormat = getValueByPath(fromObject, ['format']); + if (fromFormat != null) { + setValueByPath(toObject, ['format'], fromFormat); + } + const fromItems = getValueByPath(fromObject, ['items']); + if (fromItems != null) { + setValueByPath(toObject, ['items'], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ['maxItems']); + if (fromMaxItems != null) { + setValueByPath(toObject, ['maxItems'], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ['maxLength']); + if (fromMaxLength != null) { + setValueByPath(toObject, ['maxLength'], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, [ + 'maxProperties', + ]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ['maxProperties'], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ['maximum']); + if (fromMaximum != null) { + setValueByPath(toObject, ['maximum'], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ['minItems']); + if (fromMinItems != null) { + setValueByPath(toObject, ['minItems'], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ['minLength']); + if (fromMinLength != null) { + setValueByPath(toObject, ['minLength'], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, [ + 'minProperties', + ]); + if (fromMinProperties != null) { + setValueByPath(toObject, ['minProperties'], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ['minimum']); + if (fromMinimum != null) { + setValueByPath(toObject, ['minimum'], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ['nullable']); + if (fromNullable != null) { + setValueByPath(toObject, ['nullable'], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ['pattern']); + if (fromPattern != null) { + setValueByPath(toObject, ['pattern'], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ['properties']); + if (fromProperties != null) { + setValueByPath(toObject, ['properties'], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, [ + 'propertyOrdering', + ]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ['required']); + if (fromRequired != null) { + setValueByPath(toObject, ['required'], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (fromTitle != null) { + setValueByPath(toObject, ['title'], fromTitle); + } + const fromType = getValueByPath(fromObject, ['type']); + if (fromType != null) { + setValueByPath(toObject, ['type'], fromType); + } + return toObject; +} +function modelSelectionConfigToVertex(fromObject) { + const toObject = {}; + const fromFeatureSelectionPreference = getValueByPath(fromObject, [ + 'featureSelectionPreference', + ]); + if (fromFeatureSelectionPreference != null) { + setValueByPath(toObject, ['featureSelectionPreference'], fromFeatureSelectionPreference); + } + return toObject; +} +function safetySettingToVertex(fromObject) { + const toObject = {}; + const fromMethod = getValueByPath(fromObject, ['method']); + if (fromMethod != null) { + setValueByPath(toObject, ['method'], fromMethod); + } + const fromCategory = getValueByPath(fromObject, ['category']); + if (fromCategory != null) { + setValueByPath(toObject, ['category'], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ['threshold']); + if (fromThreshold != null) { + setValueByPath(toObject, ['threshold'], fromThreshold); + } + return toObject; +} +function functionDeclarationToVertex(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['behavior']) !== undefined) { + throw new Error('behavior parameter is not supported in Vertex AI.'); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToVertex(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToVertex(fromTimeRangeFilter)); + } + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function dynamicRetrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig)); + } + return toObject; +} +function enterpriseWebSearchToVertex(fromObject) { + const toObject = {}; + const fromExcludeDomains = getValueByPath(fromObject, [ + 'excludeDomains', + ]); + if (fromExcludeDomains != null) { + setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains); + } + return toObject; +} +function apiKeyConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ['apiKeyString']); + if (fromApiKeyString != null) { + setValueByPath(toObject, ['apiKeyString'], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ['apiKeyConfig']); + if (fromApiKeyConfig != null) { + setValueByPath(toObject, ['apiKeyConfig'], apiKeyConfigToVertex(fromApiKeyConfig)); + } + const fromAuthType = getValueByPath(fromObject, ['authType']); + if (fromAuthType != null) { + setValueByPath(toObject, ['authType'], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + 'googleServiceAccountConfig', + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath(toObject, ['googleServiceAccountConfig'], fromGoogleServiceAccountConfig); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + 'httpBasicAuthConfig', + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ['httpBasicAuthConfig'], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ['oauthConfig']); + if (fromOauthConfig != null) { + setValueByPath(toObject, ['oauthConfig'], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ['oidcConfig']); + if (fromOidcConfig != null) { + setValueByPath(toObject, ['oidcConfig'], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ['authConfig']); + if (fromAuthConfig != null) { + setValueByPath(toObject, ['authConfig'], authConfigToVertex(fromAuthConfig)); + } + return toObject; +} +function urlContextToVertex() { + const toObject = {}; + return toObject; +} +function toolComputerUseToVertex(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToVertex(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ['retrieval']); + if (fromRetrieval != null) { + setValueByPath(toObject, ['retrieval'], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToVertex(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToVertex(fromGoogleSearchRetrieval)); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + 'enterpriseWebSearch', + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ['enterpriseWebSearch'], enterpriseWebSearchToVertex(fromEnterpriseWebSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject, ['googleMaps']); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ['googleMaps'], googleMapsToVertex(fromGoogleMaps)); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToVertex()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToVertex(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + 'allowedFunctionNames', + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ['allowedFunctionNames'], fromAllowedFunctionNames); + } + return toObject; +} +function latLngToVertex(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ['latitude']); + if (fromLatitude != null) { + setValueByPath(toObject, ['latitude'], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ['longitude']); + if (fromLongitude != null) { + setValueByPath(toObject, ['longitude'], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ['latLng']); + if (fromLatLng != null) { + setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + 'functionCallingConfig', + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ['functionCallingConfig'], functionCallingConfigToVertex(fromFunctionCallingConfig)); + } + const fromRetrievalConfig = getValueByPath(fromObject, [ + 'retrievalConfig', + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ['retrievalConfig'], retrievalConfigToVertex(fromRetrievalConfig)); + } + return toObject; +} +function prebuiltVoiceConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speechConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToVertex(fromVoiceConfig)); + } + if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) { + throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.'); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToVertex(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, [ + 'includeThoughts', + ]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, [ + 'thinkingBudget', + ]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (fromTemperature != null) { + setValueByPath(toObject, ['temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (fromTopP != null) { + setValueByPath(toObject, ['topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (fromTopK != null) { + setValueByPath(toObject, ['topK'], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, [ + 'candidateCount', + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ['candidateCount'], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, [ + 'stopSequences', + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ['stopSequences'], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, [ + 'responseLogprobs', + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ['logprobs']); + if (fromLogprobs != null) { + setValueByPath(toObject, ['logprobs'], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, [ + 'presencePenalty', + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, [ + 'frequencyPenalty', + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (fromSeed != null) { + setValueByPath(toObject, ['seed'], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, [ + 'responseMimeType', + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, [ + 'responseSchema', + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ['responseSchema'], schemaToVertex(tSchema(fromResponseSchema))); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + const fromRoutingConfig = getValueByPath(fromObject, [ + 'routingConfig', + ]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ['routingConfig'], fromRoutingConfig); + } + const fromModelSelectionConfig = getValueByPath(fromObject, [ + 'modelSelectionConfig', + ]); + if (fromModelSelectionConfig != null) { + setValueByPath(toObject, ['modelConfig'], modelSelectionConfigToVertex(fromModelSelectionConfig)); + } + const fromSafetySettings = getValueByPath(fromObject, [ + 'safetySettings', + ]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToVertex(item); + }); + } + setValueByPath(parentObject, ['safetySettings'], transformedList); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(tTool(item)); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ['toolConfig']); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath(parentObject, ['toolConfig'], toolConfigToVertex(fromToolConfig)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ['labels'], fromLabels); + } + const fromCachedContent = getValueByPath(fromObject, [ + 'cachedContent', + ]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath(parentObject, ['cachedContent'], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ['responseModalities'], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ['mediaResolution'], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ['speechConfig'], speechConfigToVertex(tSpeechConfig(fromSpeechConfig))); + } + const fromAudioTimestamp = getValueByPath(fromObject, [ + 'audioTimestamp', + ]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp); + } + const fromThinkingConfig = getValueByPath(fromObject, [ + 'thinkingConfig', + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ['thinkingConfig'], thinkingConfigToVertex(fromThinkingConfig)); + } + return toObject; +} +function generateContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['generationConfig'], generateContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function embedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ['taskType']); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ['instances[]', 'task_type'], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ['title']); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ['instances[]', 'title'], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + 'outputDimensionality', + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath(parentObject, ['parameters', 'outputDimensionality'], fromOutputDimensionality); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (parentObject !== undefined && fromMimeType != null) { + setValueByPath(parentObject, ['instances[]', 'mimeType'], fromMimeType); + } + const fromAutoTruncate = getValueByPath(fromObject, ['autoTruncate']); + if (parentObject !== undefined && fromAutoTruncate != null) { + setValueByPath(parentObject, ['parameters', 'autoTruncate'], fromAutoTruncate); + } + return toObject; +} +function embedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + setValueByPath(toObject, ['instances[]', 'content'], tContentsForEmbed(apiClient, fromContents)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], embedContentConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function generateImagesConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromImageSize = getValueByPath(fromObject, ['imageSize']); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath(parentObject, ['parameters', 'sampleImageSize'], fromImageSize); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function generateImagesParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateImagesConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function imageToVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, ['imageBytes']); + if (fromImageBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function maskReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromMaskMode = getValueByPath(fromObject, ['maskMode']); + if (fromMaskMode != null) { + setValueByPath(toObject, ['maskMode'], fromMaskMode); + } + const fromSegmentationClasses = getValueByPath(fromObject, [ + 'segmentationClasses', + ]); + if (fromSegmentationClasses != null) { + setValueByPath(toObject, ['maskClasses'], fromSegmentationClasses); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (fromMaskDilation != null) { + setValueByPath(toObject, ['dilation'], fromMaskDilation); + } + return toObject; +} +function controlReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromControlType = getValueByPath(fromObject, ['controlType']); + if (fromControlType != null) { + setValueByPath(toObject, ['controlType'], fromControlType); + } + const fromEnableControlImageComputation = getValueByPath(fromObject, [ + 'enableControlImageComputation', + ]); + if (fromEnableControlImageComputation != null) { + setValueByPath(toObject, ['computeControl'], fromEnableControlImageComputation); + } + return toObject; +} +function styleReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromStyleDescription = getValueByPath(fromObject, [ + 'styleDescription', + ]); + if (fromStyleDescription != null) { + setValueByPath(toObject, ['styleDescription'], fromStyleDescription); + } + return toObject; +} +function subjectReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromSubjectType = getValueByPath(fromObject, ['subjectType']); + if (fromSubjectType != null) { + setValueByPath(toObject, ['subjectType'], fromSubjectType); + } + const fromSubjectDescription = getValueByPath(fromObject, [ + 'subjectDescription', + ]); + if (fromSubjectDescription != null) { + setValueByPath(toObject, ['subjectDescription'], fromSubjectDescription); + } + return toObject; +} +function referenceImageAPIInternalToVertex(fromObject) { + const toObject = {}; + const fromReferenceImage = getValueByPath(fromObject, [ + 'referenceImage', + ]); + if (fromReferenceImage != null) { + setValueByPath(toObject, ['referenceImage'], imageToVertex(fromReferenceImage)); + } + const fromReferenceId = getValueByPath(fromObject, ['referenceId']); + if (fromReferenceId != null) { + setValueByPath(toObject, ['referenceId'], fromReferenceId); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + const fromMaskImageConfig = getValueByPath(fromObject, [ + 'maskImageConfig', + ]); + if (fromMaskImageConfig != null) { + setValueByPath(toObject, ['maskImageConfig'], maskReferenceConfigToVertex(fromMaskImageConfig)); + } + const fromControlImageConfig = getValueByPath(fromObject, [ + 'controlImageConfig', + ]); + if (fromControlImageConfig != null) { + setValueByPath(toObject, ['controlImageConfig'], controlReferenceConfigToVertex(fromControlImageConfig)); + } + const fromStyleImageConfig = getValueByPath(fromObject, [ + 'styleImageConfig', + ]); + if (fromStyleImageConfig != null) { + setValueByPath(toObject, ['styleImageConfig'], styleReferenceConfigToVertex(fromStyleImageConfig)); + } + const fromSubjectImageConfig = getValueByPath(fromObject, [ + 'subjectImageConfig', + ]); + if (fromSubjectImageConfig != null) { + setValueByPath(toObject, ['subjectImageConfig'], subjectReferenceConfigToVertex(fromSubjectImageConfig)); + } + return toObject; +} +function editImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject, [ + 'guidanceScale', + ]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath(parentObject, ['parameters', 'guidanceScale'], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + 'includeSafetyAttributes', + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ['parameters', 'includeSafetyAttributes'], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject, ['language']); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ['parameters', 'language'], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject, ['addWatermark']); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath(parentObject, ['parameters', 'addWatermark'], fromAddWatermark); + } + const fromEditMode = getValueByPath(fromObject, ['editMode']); + if (parentObject !== undefined && fromEditMode != null) { + setValueByPath(parentObject, ['parameters', 'editMode'], fromEditMode); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'editConfig', 'baseSteps'], fromBaseSteps); + } + return toObject; +} +function editImageParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return referenceImageAPIInternalToVertex(item); + }); + } + setValueByPath(toObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], editImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function upscaleImageAPIConfigInternalToVertex(fromObject, parentObject) { + const toObject = {}; + const fromIncludeRaiReason = getValueByPath(fromObject, [ + 'includeRaiReason', + ]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ['parameters', 'includeRaiReason'], fromIncludeRaiReason); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhanceInputImage = getValueByPath(fromObject, [ + 'enhanceInputImage', + ]); + if (parentObject !== undefined && fromEnhanceInputImage != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'enhanceInputImage'], fromEnhanceInputImage); + } + const fromImagePreservationFactor = getValueByPath(fromObject, [ + 'imagePreservationFactor', + ]); + if (parentObject !== undefined && fromImagePreservationFactor != null) { + setValueByPath(parentObject, ['parameters', 'upscaleConfig', 'imagePreservationFactor'], fromImagePreservationFactor); + } + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + return toObject; +} +function upscaleImageAPIParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromUpscaleFactor = getValueByPath(fromObject, [ + 'upscaleFactor', + ]); + if (fromUpscaleFactor != null) { + setValueByPath(toObject, ['parameters', 'upscaleConfig', 'upscaleFactor'], fromUpscaleFactor); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], upscaleImageAPIConfigInternalToVertex(fromConfig, toObject)); + } + return toObject; +} +function productImageToVertex(fromObject) { + const toObject = {}; + const fromProductImage = getValueByPath(fromObject, ['productImage']); + if (fromProductImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromProductImage)); + } + return toObject; +} +function recontextImageSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromPersonImage = getValueByPath(fromObject, ['personImage']); + if (parentObject !== undefined && fromPersonImage != null) { + setValueByPath(parentObject, ['instances[0]', 'personImage', 'image'], imageToVertex(fromPersonImage)); + } + const fromProductImages = getValueByPath(fromObject, [ + 'productImages', + ]); + if (parentObject !== undefined && fromProductImages != null) { + let transformedList = fromProductImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return productImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'productImages'], transformedList); + } + return toObject; +} +function recontextImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfImages = getValueByPath(fromObject, [ + 'numberOfImages', + ]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfImages); + } + const fromBaseSteps = getValueByPath(fromObject, ['baseSteps']); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath(parentObject, ['parameters', 'editConfig', 'baseSteps'], fromBaseSteps); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + 'safetyFilterLevel', + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ['parameters', 'safetySetting'], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromOutputMimeType = getValueByPath(fromObject, [ + 'outputMimeType', + ]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'mimeType'], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + 'outputCompressionQuality', + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'outputOptions', 'compressionQuality'], fromOutputCompressionQuality); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + return toObject; +} +function recontextImageParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], recontextImageSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], recontextImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function scribbleImageToVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + return toObject; +} +function segmentImageSourceToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (parentObject !== undefined && fromPrompt != null) { + setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (parentObject !== undefined && fromImage != null) { + setValueByPath(parentObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromScribbleImage = getValueByPath(fromObject, [ + 'scribbleImage', + ]); + if (parentObject !== undefined && fromScribbleImage != null) { + setValueByPath(parentObject, ['instances[0]', 'scribble'], scribbleImageToVertex(fromScribbleImage)); + } + return toObject; +} +function segmentImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ['parameters', 'mode'], fromMode); + } + const fromMaxPredictions = getValueByPath(fromObject, [ + 'maxPredictions', + ]); + if (parentObject !== undefined && fromMaxPredictions != null) { + setValueByPath(parentObject, ['parameters', 'maxPredictions'], fromMaxPredictions); + } + const fromConfidenceThreshold = getValueByPath(fromObject, [ + 'confidenceThreshold', + ]); + if (parentObject !== undefined && fromConfidenceThreshold != null) { + setValueByPath(parentObject, ['parameters', 'confidenceThreshold'], fromConfidenceThreshold); + } + const fromMaskDilation = getValueByPath(fromObject, ['maskDilation']); + if (parentObject !== undefined && fromMaskDilation != null) { + setValueByPath(parentObject, ['parameters', 'maskDilation'], fromMaskDilation); + } + const fromBinaryColorThreshold = getValueByPath(fromObject, [ + 'binaryColorThreshold', + ]); + if (parentObject !== undefined && fromBinaryColorThreshold != null) { + setValueByPath(parentObject, ['parameters', 'binaryColorThreshold'], fromBinaryColorThreshold); + } + return toObject; +} +function segmentImageParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject, ['source']); + if (fromSource != null) { + setValueByPath(toObject, ['config'], segmentImageSourceToVertex(fromSource, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], segmentImageConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function getModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listModelsConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ['queryBase']); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath(parentObject, ['_url', 'models_url'], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listModelsConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function updateModelConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], updateModelConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function deleteModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'name'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function countTokensConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['systemInstruction'], contentToVertex(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(item); + }); + } + setValueByPath(parentObject, ['tools'], transformedList); + } + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['generationConfig'], fromGenerationConfig); + } + return toObject; +} +function countTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], countTokensConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function computeTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ['contents']); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ['contents'], transformedList); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function videoToVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['uri']); + if (fromUri != null) { + setValueByPath(toObject, ['gcsUri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ['videoBytes']); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['bytesBase64Encoded'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function videoGenerationReferenceImageToVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageToVertex(fromImage)); + } + const fromReferenceType = getValueByPath(fromObject, [ + 'referenceType', + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ['referenceType'], fromReferenceType); + } + return toObject; +} +function generateVideosConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, [ + 'numberOfVideos', + ]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath(parentObject, ['parameters', 'sampleCount'], fromNumberOfVideos); + } + const fromOutputGcsUri = getValueByPath(fromObject, ['outputGcsUri']); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath(parentObject, ['parameters', 'storageUri'], fromOutputGcsUri); + } + const fromFps = getValueByPath(fromObject, ['fps']); + if (parentObject !== undefined && fromFps != null) { + setValueByPath(parentObject, ['parameters', 'fps'], fromFps); + } + const fromDurationSeconds = getValueByPath(fromObject, [ + 'durationSeconds', + ]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath(parentObject, ['parameters', 'durationSeconds'], fromDurationSeconds); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['parameters', 'seed'], fromSeed); + } + const fromAspectRatio = getValueByPath(fromObject, ['aspectRatio']); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath(parentObject, ['parameters', 'aspectRatio'], fromAspectRatio); + } + const fromResolution = getValueByPath(fromObject, ['resolution']); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ['parameters', 'resolution'], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, [ + 'personGeneration', + ]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath(parentObject, ['parameters', 'personGeneration'], fromPersonGeneration); + } + const fromPubsubTopic = getValueByPath(fromObject, ['pubsubTopic']); + if (parentObject !== undefined && fromPubsubTopic != null) { + setValueByPath(parentObject, ['parameters', 'pubsubTopic'], fromPubsubTopic); + } + const fromNegativePrompt = getValueByPath(fromObject, [ + 'negativePrompt', + ]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath(parentObject, ['parameters', 'negativePrompt'], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject, [ + 'enhancePrompt', + ]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath(parentObject, ['parameters', 'enhancePrompt'], fromEnhancePrompt); + } + const fromGenerateAudio = getValueByPath(fromObject, [ + 'generateAudio', + ]); + if (parentObject !== undefined && fromGenerateAudio != null) { + setValueByPath(parentObject, ['parameters', 'generateAudio'], fromGenerateAudio); + } + const fromLastFrame = getValueByPath(fromObject, ['lastFrame']); + if (parentObject !== undefined && fromLastFrame != null) { + setValueByPath(parentObject, ['instances[0]', 'lastFrame'], imageToVertex(fromLastFrame)); + } + const fromReferenceImages = getValueByPath(fromObject, [ + 'referenceImages', + ]); + if (parentObject !== undefined && fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return videoGenerationReferenceImageToVertex(item); + }); + } + setValueByPath(parentObject, ['instances[0]', 'referenceImages'], transformedList); + } + const fromCompressionQuality = getValueByPath(fromObject, [ + 'compressionQuality', + ]); + if (parentObject !== undefined && fromCompressionQuality != null) { + setValueByPath(parentObject, ['parameters', 'compressionQuality'], fromCompressionQuality); + } + return toObject; +} +function generateVideosParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ['prompt']); + if (fromPrompt != null) { + setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ['image']); + if (fromImage != null) { + setValueByPath(toObject, ['instances[0]', 'image'], imageToVertex(fromImage)); + } + const fromVideo = getValueByPath(fromObject, ['video']); + if (fromVideo != null) { + setValueByPath(toObject, ['instances[0]', 'video'], videoToVertex(fromVideo)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], generateVideosConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function videoMetadataFromMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromMldev(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromMldev(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromMldev(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citationSources']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromMldev(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromMldev(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromMldev(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject, ['tokenCount']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromMldev(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingFromMldev(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + return toObject; +} +function embedContentMetadataFromMldev() { + const toObject = {}; + return toObject; +} +function embedContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, ['embeddings']); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromMldev(item); + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromMldev()); + } + return toObject; +} +function imageFromMldev(fromObject) { + const toObject = {}; + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromMldev(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + 'safetyAttributes', + 'categories', + ]); + if (fromCategories != null) { + setValueByPath(toObject, ['categories'], fromCategories); + } + const fromScores = getValueByPath(fromObject, [ + 'safetyAttributes', + 'scores', + ]); + if (fromScores != null) { + setValueByPath(toObject, ['scores'], fromScores); + } + const fromContentType = getValueByPath(fromObject, ['contentType']); + if (fromContentType != null) { + setValueByPath(toObject, ['contentType'], fromContentType); + } + return toObject; +} +function generatedImageFromMldev(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromMldev(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromMldev(fromSafetyAttributes)); + } + return toObject; +} +function generateImagesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromMldev(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromMldev(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function tunedModelInfoFromMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function modelFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['version']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromMldev(fromTunedModelInfo)); + } + const fromInputTokenLimit = getValueByPath(fromObject, [ + 'inputTokenLimit', + ]); + if (fromInputTokenLimit != null) { + setValueByPath(toObject, ['inputTokenLimit'], fromInputTokenLimit); + } + const fromOutputTokenLimit = getValueByPath(fromObject, [ + 'outputTokenLimit', + ]); + if (fromOutputTokenLimit != null) { + setValueByPath(toObject, ['outputTokenLimit'], fromOutputTokenLimit); + } + const fromSupportedActions = getValueByPath(fromObject, [ + 'supportedGenerationMethods', + ]); + if (fromSupportedActions != null) { + setValueByPath(toObject, ['supportedActions'], fromSupportedActions); + } + return toObject; +} +function listModelsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromMldev(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function deleteModelResponseFromMldev() { + const toObject = {}; + return toObject; +} +function countTokensResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + 'cachedContentTokenCount', + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ['cachedContentTokenCount'], fromCachedContentTokenCount); + } + return toObject; +} +function videoFromMldev(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['video', 'uri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'video', + 'encodedVideo', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['encoding']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromMldev(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, [ + 'generatedSamples', + ]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromMldev(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosOperationFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, [ + 'response', + 'generateVideoResponse', + ]); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromMldev(fromResponse)); + } + return toObject; +} +function videoMetadataFromVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partFromVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataFromVertex(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobFromVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataFromVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentFromVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function citationMetadataFromVertex(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ['citations']); + if (fromCitations != null) { + setValueByPath(toObject, ['citations'], fromCitations); + } + return toObject; +} +function urlMetadataFromVertex(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ['retrievedUrl']); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + 'urlRetrievalStatus', + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ['urlRetrievalStatus'], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromVertex(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ['urlMetadata']); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromVertex(item); + }); + } + setValueByPath(toObject, ['urlMetadata'], transformedList); + } + return toObject; +} +function candidateFromVertex(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ['content']); + if (fromContent != null) { + setValueByPath(toObject, ['content'], contentFromVertex(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, [ + 'citationMetadata', + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ['citationMetadata'], citationMetadataFromVertex(fromCitationMetadata)); + } + const fromFinishMessage = getValueByPath(fromObject, [ + 'finishMessage', + ]); + if (fromFinishMessage != null) { + setValueByPath(toObject, ['finishMessage'], fromFinishMessage); + } + const fromFinishReason = getValueByPath(fromObject, ['finishReason']); + if (fromFinishReason != null) { + setValueByPath(toObject, ['finishReason'], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + 'urlContextMetadata', + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ['urlContextMetadata'], urlContextMetadataFromVertex(fromUrlContextMetadata)); + } + const fromAvgLogprobs = getValueByPath(fromObject, ['avgLogprobs']); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + 'groundingMetadata', + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ['groundingMetadata'], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ['index']); + if (fromIndex != null) { + setValueByPath(toObject, ['index'], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, [ + 'logprobsResult', + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, [ + 'safetyRatings', + ]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ['candidates']); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromVertex(item); + }); + } + setValueByPath(toObject, ['candidates'], transformedList); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromModelVersion = getValueByPath(fromObject, ['modelVersion']); + if (fromModelVersion != null) { + setValueByPath(toObject, ['modelVersion'], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, [ + 'promptFeedback', + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject, ['responseId']); + if (fromResponseId != null) { + setValueByPath(toObject, ['responseId'], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject, [ + 'usageMetadata', + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingStatisticsFromVertex(fromObject) { + const toObject = {}; + const fromTruncated = getValueByPath(fromObject, ['truncated']); + if (fromTruncated != null) { + setValueByPath(toObject, ['truncated'], fromTruncated); + } + const fromTokenCount = getValueByPath(fromObject, ['token_count']); + if (fromTokenCount != null) { + setValueByPath(toObject, ['tokenCount'], fromTokenCount); + } + return toObject; +} +function contentEmbeddingFromVertex(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ['values']); + if (fromValues != null) { + setValueByPath(toObject, ['values'], fromValues); + } + const fromStatistics = getValueByPath(fromObject, ['statistics']); + if (fromStatistics != null) { + setValueByPath(toObject, ['statistics'], contentEmbeddingStatisticsFromVertex(fromStatistics)); + } + return toObject; +} +function embedContentMetadataFromVertex(fromObject) { + const toObject = {}; + const fromBillableCharacterCount = getValueByPath(fromObject, [ + 'billableCharacterCount', + ]); + if (fromBillableCharacterCount != null) { + setValueByPath(toObject, ['billableCharacterCount'], fromBillableCharacterCount); + } + return toObject; +} +function embedContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, [ + 'predictions[]', + 'embeddings', + ]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromVertex(item); + }); + } + setValueByPath(toObject, ['embeddings'], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], embedContentMetadataFromVertex(fromMetadata)); + } + return toObject; +} +function imageFromVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['gcsUri'], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ['imageBytes'], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function safetyAttributesFromVertex(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + 'safetyAttributes', + 'categories', + ]); + if (fromCategories != null) { + setValueByPath(toObject, ['categories'], fromCategories); + } + const fromScores = getValueByPath(fromObject, [ + 'safetyAttributes', + 'scores', + ]); + if (fromScores != null) { + setValueByPath(toObject, ['scores'], fromScores); + } + const fromContentType = getValueByPath(fromObject, ['contentType']); + if (fromContentType != null) { + setValueByPath(toObject, ['contentType'], fromContentType); + } + return toObject; +} +function generatedImageFromVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ['_self']); + if (fromImage != null) { + setValueByPath(toObject, ['image'], imageFromVertex(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + 'raiFilteredReason', + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ['raiFilteredReason'], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ['_self']); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ['safetyAttributes'], safetyAttributesFromVertex(fromSafetyAttributes)); + } + const fromEnhancedPrompt = getValueByPath(fromObject, ['prompt']); + if (fromEnhancedPrompt != null) { + setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt); + } + return toObject; +} +function generateImagesResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + 'positivePromptSafetyAttributes', + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ['positivePromptSafetyAttributes'], safetyAttributesFromVertex(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function editImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function upscaleImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function recontextImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedImages = getValueByPath(fromObject, [ + 'predictions', + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedImages'], transformedList); + } + return toObject; +} +function entityLabelFromVertex(fromObject) { + const toObject = {}; + const fromLabel = getValueByPath(fromObject, ['label']); + if (fromLabel != null) { + setValueByPath(toObject, ['label'], fromLabel); + } + const fromScore = getValueByPath(fromObject, ['score']); + if (fromScore != null) { + setValueByPath(toObject, ['score'], fromScore); + } + return toObject; +} +function generatedImageMaskFromVertex(fromObject) { + const toObject = {}; + const fromMask = getValueByPath(fromObject, ['_self']); + if (fromMask != null) { + setValueByPath(toObject, ['mask'], imageFromVertex(fromMask)); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + let transformedList = fromLabels; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return entityLabelFromVertex(item); + }); + } + setValueByPath(toObject, ['labels'], transformedList); + } + return toObject; +} +function segmentImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedMasks = getValueByPath(fromObject, ['predictions']); + if (fromGeneratedMasks != null) { + let transformedList = fromGeneratedMasks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageMaskFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedMasks'], transformedList); + } + return toObject; +} +function endpointFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['endpoint']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDeployedModelId = getValueByPath(fromObject, [ + 'deployedModelId', + ]); + if (fromDeployedModelId != null) { + setValueByPath(toObject, ['deployedModelId'], fromDeployedModelId); + } + return toObject; +} +function tunedModelInfoFromVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, [ + 'labels', + 'google-vertex-llm-tuning-base-model-id', + ]); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + return toObject; +} +function checkpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ['checkpointId']); + if (fromCheckpointId != null) { + setValueByPath(toObject, ['checkpointId'], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ['epoch']); + if (fromEpoch != null) { + setValueByPath(toObject, ['epoch'], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ['step']); + if (fromStep != null) { + setValueByPath(toObject, ['step'], fromStep); + } + return toObject; +} +function modelFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + setValueByPath(toObject, ['displayName'], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ['versionId']); + if (fromVersion != null) { + setValueByPath(toObject, ['version'], fromVersion); + } + const fromEndpoints = getValueByPath(fromObject, ['deployedModels']); + if (fromEndpoints != null) { + let transformedList = fromEndpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return endpointFromVertex(item); + }); + } + setValueByPath(toObject, ['endpoints'], transformedList); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromTunedModelInfo = getValueByPath(fromObject, ['_self']); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ['tunedModelInfo'], tunedModelInfoFromVertex(fromTunedModelInfo)); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + 'defaultCheckpointId', + ]); + if (fromDefaultCheckpointId != null) { + setValueByPath(toObject, ['defaultCheckpointId'], fromDefaultCheckpointId); + } + const fromCheckpoints = getValueByPath(fromObject, ['checkpoints']); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return checkpointFromVertex(item); + }); + } + setValueByPath(toObject, ['checkpoints'], transformedList); + } + return toObject; +} +function listModelsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ['_self']); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromVertex(item); + }); + } + setValueByPath(toObject, ['models'], transformedList); + } + return toObject; +} +function deleteModelResponseFromVertex() { + const toObject = {}; + return toObject; +} +function countTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ['totalTokens']); + if (fromTotalTokens != null) { + setValueByPath(toObject, ['totalTokens'], fromTotalTokens); + } + return toObject; +} +function computeTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromTokensInfo = getValueByPath(fromObject, ['tokensInfo']); + if (fromTokensInfo != null) { + setValueByPath(toObject, ['tokensInfo'], fromTokensInfo); + } + return toObject; +} +function videoFromVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ['gcsUri']); + if (fromUri != null) { + setValueByPath(toObject, ['uri'], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, [ + 'bytesBase64Encoded', + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ['videoBytes'], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ['_self']); + if (fromVideo != null) { + setValueByPath(toObject, ['video'], videoFromVertex(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ['videos']); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromVertex(item); + }); + } + setValueByPath(toObject, ['generatedVideos'], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + 'raiMediaFilteredCount', + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ['raiMediaFilteredCount'], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + 'raiMediaFilteredReasons', + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ['raiMediaFilteredReasons'], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosOperationFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], generateVideosResponseFromVertex(fromResponse)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const CONTENT_TYPE_HEADER = 'Content-Type'; +const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout'; +const USER_AGENT_HEADER = 'User-Agent'; +const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client'; +const SDK_VERSION = '1.15.0'; // x-release-please-version +const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`; +const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1'; +const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta'; +const responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/; +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +class ApiClient { + constructor(opts) { + var _a, _b; + this.clientOptions = Object.assign(Object.assign({}, opts), { project: opts.project, location: opts.location, apiKey: opts.apiKey, vertexai: opts.vertexai }); + const initHttpOptions = {}; + if (this.clientOptions.vertexai) { + initHttpOptions.apiVersion = + (_a = this.clientOptions.apiVersion) !== null && _a !== void 0 ? _a : VERTEX_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = this.baseUrlFromProjectLocation(); + this.normalizeAuthParameters(); + } + else { + // Gemini API + initHttpOptions.apiVersion = + (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 ? _b : GOOGLE_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`; + } + initHttpOptions.headers = this.getDefaultHeaders(); + this.clientOptions.httpOptions = initHttpOptions; + if (opts.httpOptions) { + this.clientOptions.httpOptions = this.patchHttpOptions(initHttpOptions, opts.httpOptions); + } + } + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + baseUrlFromProjectLocation() { + if (this.clientOptions.project && + this.clientOptions.location && + this.clientOptions.location !== 'global') { + // Regional endpoint + return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`; + } + // Global endpoint (covers 'global' location and API key usage) + return `https://aiplatform.googleapis.com/`; + } + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + normalizeAuthParameters() { + if (this.clientOptions.project && this.clientOptions.location) { + // Using project/location for auth, clear potential API key + this.clientOptions.apiKey = undefined; + return; + } + // Using API key for auth (or no auth provided yet), clear project/location + this.clientOptions.project = undefined; + this.clientOptions.location = undefined; + } + isVertexAI() { + var _a; + return (_a = this.clientOptions.vertexai) !== null && _a !== void 0 ? _a : false; + } + getProject() { + return this.clientOptions.project; + } + getLocation() { + return this.clientOptions.location; + } + getApiVersion() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.apiVersion !== undefined) { + return this.clientOptions.httpOptions.apiVersion; + } + throw new Error('API version is not set.'); + } + getBaseUrl() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.baseUrl !== undefined) { + return this.clientOptions.httpOptions.baseUrl; + } + throw new Error('Base URL is not set.'); + } + getRequestUrl() { + return this.getRequestUrlInternal(this.clientOptions.httpOptions); + } + getHeaders() { + if (this.clientOptions.httpOptions && + this.clientOptions.httpOptions.headers !== undefined) { + return this.clientOptions.httpOptions.headers; + } + else { + throw new Error('Headers are not set.'); + } + } + getRequestUrlInternal(httpOptions) { + if (!httpOptions || + httpOptions.baseUrl === undefined || + httpOptions.apiVersion === undefined) { + throw new Error('HTTP options are not correctly set.'); + } + const baseUrl = httpOptions.baseUrl.endsWith('/') + ? httpOptions.baseUrl.slice(0, -1) + : httpOptions.baseUrl; + const urlElement = [baseUrl]; + if (httpOptions.apiVersion && httpOptions.apiVersion !== '') { + urlElement.push(httpOptions.apiVersion); + } + return urlElement.join('/'); + } + getBaseResourcePath() { + return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`; + } + getApiKey() { + return this.clientOptions.apiKey; + } + getWebsocketBaseUrl() { + const baseUrl = this.getBaseUrl(); + const urlParts = new URL(baseUrl); + urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss'; + return urlParts.toString(); + } + setBaseUrl(url) { + if (this.clientOptions.httpOptions) { + this.clientOptions.httpOptions.baseUrl = url; + } + else { + throw new Error('HTTP options are not correctly set.'); + } + } + constructUrl(path, httpOptions, prependProjectLocation) { + const urlElement = [this.getRequestUrlInternal(httpOptions)]; + if (prependProjectLocation) { + urlElement.push(this.getBaseResourcePath()); + } + if (path !== '') { + urlElement.push(path); + } + const url = new URL(`${urlElement.join('/')}`); + return url; + } + shouldPrependVertexProjectPath(request) { + if (this.clientOptions.apiKey) { + return false; + } + if (!this.clientOptions.vertexai) { + return false; + } + if (request.path.startsWith('projects/')) { + // Assume the path already starts with + // `projects//location/`. + return false; + } + if (request.httpMethod === 'GET' && + request.path.startsWith('publishers/google/models')) { + // These paths are used by Vertex's models.get and models.list + // calls. For base models Vertex does not accept a project/location + // prefix (for tuned model the prefix is required). + return false; + } + return true; + } + async request(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (request.queryParams) { + for (const [key, value] of Object.entries(request.queryParams)) { + url.searchParams.append(key, String(value)); + } + } + let requestInit = {}; + if (request.httpMethod === 'GET') { + if (request.body && request.body !== '{}') { + throw new Error('Request body should be empty for GET request, but got non empty request body'); + } + } + else { + requestInit.body = request.body; + } + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal); + return this.unaryApiCall(url, requestInit, request.httpMethod); + } + patchHttpOptions(baseHttpOptions, requestHttpOptions) { + const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions)); + for (const [key, value] of Object.entries(requestHttpOptions)) { + // Records compile to objects. + if (typeof value === 'object') { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = Object.assign(Object.assign({}, patchedHttpOptions[key]), value); + } + else if (value !== undefined) { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = value; + } + } + return patchedHttpOptions; + } + async requestStream(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') { + url.searchParams.set('alt', 'sse'); + } + let requestInit = {}; + requestInit.body = request.body; + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal); + return this.streamApiCall(url, requestInit, request.httpMethod); + } + async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions, abortSignal) { + if ((httpOptions && httpOptions.timeout) || abortSignal) { + const abortController = new AbortController(); + const signal = abortController.signal; + if (httpOptions.timeout && (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) > 0) { + const timeoutHandle = setTimeout(() => abortController.abort(), httpOptions.timeout); + if (timeoutHandle && + typeof timeoutHandle.unref === + 'function') { + // call unref to prevent nodejs process from hanging, see + // https://nodejs.org/api/timers.html#timeoutunref + timeoutHandle.unref(); + } + } + if (abortSignal) { + abortSignal.addEventListener('abort', () => { + abortController.abort(); + }); + } + requestInit.signal = signal; + } + if (httpOptions && httpOptions.extraBody !== null) { + includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody); + } + requestInit.headers = await this.getHeadersInternal(httpOptions); + return requestInit; + } + async unaryApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return new HttpResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + async streamApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })) + .then(async (response) => { + await throwErrorIfNotOK(response); + return this.processStreamResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } + else { + throw new Error(JSON.stringify(e)); + } + }); + } + processStreamResponse(response) { + var _a; + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + const reader = (_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.getReader(); + const decoder = new TextDecoder('utf-8'); + if (!reader) { + throw new Error('Response body is empty'); + } + try { + let buffer = ''; + while (true) { + const { done, value } = yield __await(reader.read()); + if (done) { + if (buffer.trim().length > 0) { + throw new Error('Incomplete JSON segment at the end'); + } + break; + } + const chunkString = decoder.decode(value, { stream: true }); + // Parse and throw an error if the chunk contains an error. + try { + const chunkJson = JSON.parse(chunkString); + if ('error' in chunkJson) { + const errorJson = JSON.parse(JSON.stringify(chunkJson['error'])); + const status = errorJson['status']; + const code = errorJson['code']; + const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`; + if (code >= 400 && code < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: code, + }); + throw apiError; + } + } + } + catch (e) { + const error = e; + if (error.name === 'ApiError') { + throw e; + } + } + buffer += chunkString; + let match = buffer.match(responseLineRE); + while (match) { + const processedChunkString = match[1]; + try { + const partialResponse = new Response(processedChunkString, { + headers: response === null || response === void 0 ? void 0 : response.headers, + status: response === null || response === void 0 ? void 0 : response.status, + statusText: response === null || response === void 0 ? void 0 : response.statusText, + }); + yield yield __await(new HttpResponse(partialResponse)); + buffer = buffer.slice(match[0].length); + match = buffer.match(responseLineRE); + } + catch (e) { + throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`); + } + } + } + } + finally { + reader.releaseLock(); + } + }); + } + async apiCall(url, requestInit) { + return fetch(url, requestInit).catch((e) => { + throw new Error(`exception ${e} sending request`); + }); + } + getDefaultHeaders() { + const headers = {}; + const versionHeaderValue = LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra; + headers[USER_AGENT_HEADER] = versionHeaderValue; + headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue; + headers[CONTENT_TYPE_HEADER] = 'application/json'; + return headers; + } + async getHeadersInternal(httpOptions) { + const headers = new Headers(); + if (httpOptions && httpOptions.headers) { + for (const [key, value] of Object.entries(httpOptions.headers)) { + headers.append(key, value); + } + // Append a timeout header if it is set, note that the timeout option is + // in milliseconds but the header is in seconds. + if (httpOptions.timeout && httpOptions.timeout > 0) { + headers.append(SERVER_TIMEOUT_HEADER, String(Math.ceil(httpOptions.timeout / 1000))); + } + } + await this.clientOptions.auth.addAuthHeaders(headers); + return headers; + } + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + async uploadFile(file, config) { + var _a; + const fileToUpload = {}; + if (config != null) { + fileToUpload.mimeType = config.mimeType; + fileToUpload.name = config.name; + fileToUpload.displayName = config.displayName; + } + if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) { + fileToUpload.name = `files/${fileToUpload.name}`; + } + const uploader = this.clientOptions.uploader; + const fileStat = await uploader.stat(file); + fileToUpload.sizeBytes = String(fileStat.size); + const mimeType = (_a = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a !== void 0 ? _a : fileStat.type; + if (mimeType === undefined || mimeType === '') { + throw new Error('Can not determine mimeType. Please provide mimeType in the config.'); + } + fileToUpload.mimeType = mimeType; + const uploadUrl = await this.fetchUploadUrl(fileToUpload, config); + return uploader.upload(file, uploadUrl, this); + } + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + async downloadFile(params) { + const downloader = this.clientOptions.downloader; + await downloader.download(params, this); + } + async fetchUploadUrl(file, config) { + var _a; + let httpOptions = {}; + if (config === null || config === void 0 ? void 0 : config.httpOptions) { + httpOptions = config.httpOptions; + } + else { + httpOptions = { + apiVersion: '', + headers: { + 'Content-Type': 'application/json', + 'X-Goog-Upload-Protocol': 'resumable', + 'X-Goog-Upload-Command': 'start', + 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`, + 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`, + }, + }; + } + const body = { + 'file': file, + }; + const httpResponse = await this.request({ + path: formatMap('upload/v1beta/files', body['_url']), + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions, + }); + if (!httpResponse || !(httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers)) { + throw new Error('Server did not return an HttpResponse or the returned HttpResponse did not have headers.'); + } + const uploadUrl = (_a = httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers) === null || _a === void 0 ? void 0 : _a['x-goog-upload-url']; + if (uploadUrl === undefined) { + throw new Error('Failed to get upload url. Server did not return the x-google-upload-url in the headers'); + } + return uploadUrl; + } +} +async function throwErrorIfNotOK(response) { + var _a; + if (response === undefined) { + throw new Error('response is undefined'); + } + if (!response.ok) { + const status = response.status; + let errorBody; + if ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('application/json')) { + errorBody = await response.json(); + } + else { + errorBody = { + error: { + message: await response.text(), + code: response.status, + status: response.statusText, + }, + }; + } + const errorMessage = JSON.stringify(errorBody); + if (status >= 400 && status < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: status, + }); + throw apiError; + } + throw new Error(errorMessage); + } +} +/** + * Recursively updates the `requestInit.body` with values from an `extraBody` object. + * + * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed. + * The `extraBody` is then deeply merged into this parsed object. + * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged, + * as merging structured data into an opaque Blob is not supported. + * + * The function does not enforce that updated values from `extraBody` have the + * same type as existing values in `requestInit.body`. Type mismatches during + * the merge will result in a warning, but the value from `extraBody` will overwrite + * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure. + * + * @param requestInit The RequestInit object whose body will be updated. + * @param extraBody The object containing updates to be merged into `requestInit.body`. + */ +function includeExtraBodyToRequestInit(requestInit, extraBody) { + if (!extraBody || Object.keys(extraBody).length === 0) { + return; + } + if (requestInit.body instanceof Blob) { + console.warn('includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.'); + return; + } + let currentBodyObject = {}; + // If adding new type to HttpRequest.body, please check the code below to + // see if we need to update the logic. + if (typeof requestInit.body === 'string' && requestInit.body.length > 0) { + try { + const parsedBody = JSON.parse(requestInit.body); + if (typeof parsedBody === 'object' && + parsedBody !== null && + !Array.isArray(parsedBody)) { + currentBodyObject = parsedBody; + } + else { + console.warn('includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.'); + return; + } + /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ + } + catch (e) { + console.warn('includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.'); + return; + } + } + function deepMerge(target, source) { + const output = Object.assign({}, target); + for (const key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + const sourceValue = source[key]; + const targetValue = output[key]; + if (sourceValue && + typeof sourceValue === 'object' && + !Array.isArray(sourceValue) && + targetValue && + typeof targetValue === 'object' && + !Array.isArray(targetValue)) { + output[key] = deepMerge(targetValue, sourceValue); + } + else { + if (targetValue && + sourceValue && + typeof targetValue !== typeof sourceValue) { + console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`); + } + output[key] = sourceValue; + } + } + } + return output; + } + const mergedBody = deepMerge(currentBodyObject, extraBody); + requestInit.body = JSON.stringify(mergedBody); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// TODO: b/416041229 - Determine how to retrieve the MCP package version. +const MCP_LABEL = 'mcp_used/unknown'; +// Whether MCP tool usage is detected from mcpToTool. This is used for +// telemetry. +let hasMcpToolUsageFromMcpToTool = false; +// Checks whether the list of tools contains any MCP tools. +function hasMcpToolUsage(tools) { + for (const tool of tools) { + if (isMcpCallableTool(tool)) { + return true; + } + if (typeof tool === 'object' && 'inputSchema' in tool) { + return true; + } + } + return hasMcpToolUsageFromMcpToTool; +} +// Sets the MCP version label in the Google API client header. +function setMcpUsageHeader(headers) { + var _a; + const existingHeader = (_a = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a !== void 0 ? _a : ''; + headers[GOOGLE_API_CLIENT_HEADER] = (existingHeader + ` ${MCP_LABEL}`).trimStart(); +} +// Returns true if the object is a MCP CallableTool, otherwise false. +function isMcpCallableTool(object) { + return (object !== null && + typeof object === 'object' && + object instanceof McpCallableTool); +} +// List all tools from the MCP client. +function listAllTools(mcpClient, maxTools = 100) { + return __asyncGenerator(this, arguments, function* listAllTools_1() { + let cursor = undefined; + let numTools = 0; + while (numTools < maxTools) { + const t = yield __await(mcpClient.listTools({ cursor })); + for (const tool of t.tools) { + yield yield __await(tool); + numTools++; + } + if (!t.nextCursor) { + break; + } + cursor = t.nextCursor; + } + }); +} +/** + * McpCallableTool can be used for model inference and invoking MCP clients with + * given function call arguments. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +class McpCallableTool { + constructor(mcpClients = [], config) { + this.mcpTools = []; + this.functionNameToMcpClient = {}; + this.mcpClients = mcpClients; + this.config = config; + } + /** + * Creates a McpCallableTool. + */ + static create(mcpClients, config) { + return new McpCallableTool(mcpClients, config); + } + /** + * Validates the function names are not duplicate and initialize the function + * name to MCP client mapping. + * + * @throws {Error} if the MCP tools from the MCP clients have duplicate tool + * names. + */ + async initialize() { + var _a, e_1, _b, _c; + if (this.mcpTools.length > 0) { + return; + } + const functionMap = {}; + const mcpTools = []; + for (const mcpClient of this.mcpClients) { + try { + for (var _d = true, _e = (e_1 = void 0, __asyncValues(listAllTools(mcpClient))), _f; _f = await _e.next(), _a = _f.done, !_a; _d = true) { + _c = _f.value; + _d = false; + const mcpTool = _c; + mcpTools.push(mcpTool); + const mcpToolName = mcpTool.name; + if (functionMap[mcpToolName]) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + functionMap[mcpToolName] = mcpClient; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_d && !_a && (_b = _e.return)) await _b.call(_e); + } + finally { if (e_1) throw e_1.error; } + } + } + this.mcpTools = mcpTools; + this.functionNameToMcpClient = functionMap; + } + async tool() { + await this.initialize(); + return mcpToolsToGeminiTool(this.mcpTools, this.config); + } + async callTool(functionCalls) { + await this.initialize(); + const functionCallResponseParts = []; + for (const functionCall of functionCalls) { + if (functionCall.name in this.functionNameToMcpClient) { + const mcpClient = this.functionNameToMcpClient[functionCall.name]; + let requestOptions = undefined; + // TODO: b/424238654 - Add support for finer grained timeout control. + if (this.config.timeout) { + requestOptions = { + timeout: this.config.timeout, + }; + } + const callToolResponse = await mcpClient.callTool({ + name: functionCall.name, + arguments: functionCall.args, + }, + // Set the result schema to undefined to allow MCP to rely on the + // default schema. + undefined, requestOptions); + functionCallResponseParts.push({ + functionResponse: { + name: functionCall.name, + response: callToolResponse.isError + ? { error: callToolResponse } + : callToolResponse, + }, + }); + } + } + return functionCallResponseParts; + } +} +function isMcpClient(client) { + return (client !== null && + typeof client === 'object' && + 'listTools' in client && + typeof client.listTools === 'function'); +} +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +function mcpToTool(...args) { + // Set MCP usage for telemetry. + hasMcpToolUsageFromMcpToTool = true; + if (args.length === 0) { + throw new Error('No MCP clients provided'); + } + const maybeConfig = args[args.length - 1]; + if (isMcpClient(maybeConfig)) { + return McpCallableTool.create(args, {}); + } + return McpCallableTool.create(args.slice(0, args.length - 1), maybeConfig); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveMusicServerMessage, and then calling the onmessage callback. + * Note that the first message which is received from the server is a + * setupComplete message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage$1(apiClient, onmessage, event) { + const serverMessage = new LiveMusicServerMessage(); + let data; + if (event.data instanceof Blob) { + data = JSON.parse(await event.data.text()); + } + else { + data = JSON.parse(event.data); + } + const response = liveMusicServerMessageFromMldev(data); + Object.assign(serverMessage, response); + onmessage(serverMessage); +} +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +class LiveMusic { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + } + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b; + if (this.apiClient.isVertexAI()) { + throw new Error('Live music is not supported for Vertex AI.'); + } + console.warn('Live music generation is experimental and may change in future versions.'); + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + const headers = mapToHeaders$1(this.apiClient.getDefaultHeaders()); + const apiKey = this.apiClient.getApiKey(); + const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`; + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage$1(apiClient, callbacks.onmessage, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap$1(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + const model = tModel(this.apiClient, params.model); + const setup = liveMusicClientSetupToMldev({ + model, + }); + const clientMessage = liveMusicClientMessageToMldev({ setup }); + conn.send(JSON.stringify(clientMessage)); + return new LiveMusicSession(conn, this.apiClient); + } +} +/** + Represents a connection to the API. + + @experimental + */ +class LiveMusicSession { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + async setWeightedPrompts(params) { + if (!params.weightedPrompts || + Object.keys(params.weightedPrompts).length === 0) { + throw new Error('Weighted prompts must be set and contain at least one entry.'); + } + const setWeightedPromptsParameters = liveMusicSetWeightedPromptsParametersToMldev(params); + const clientContent = liveMusicClientContentToMldev(setWeightedPromptsParameters); + this.conn.send(JSON.stringify({ clientContent })); + } + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + async setMusicGenerationConfig(params) { + if (!params.musicGenerationConfig) { + params.musicGenerationConfig = {}; + } + const setConfigParameters = liveMusicSetConfigParametersToMldev(params); + const clientMessage = liveMusicClientMessageToMldev(setConfigParameters); + this.conn.send(JSON.stringify(clientMessage)); + } + sendPlaybackControl(playbackControl) { + const clientMessage = liveMusicClientMessageToMldev({ + playbackControl, + }); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + * Start the music stream. + * + * @experimental + */ + play() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PLAY); + } + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PAUSE); + } + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop() { + this.sendPlaybackControl(LiveMusicPlaybackControl.STOP); + } + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext() { + this.sendPlaybackControl(LiveMusicPlaybackControl.RESET_CONTEXT); + } + /** + Terminates the WebSocket connection. + + @experimental + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap$1(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders$1(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const FUNCTION_RESPONSE_REQUIRES_ID = 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.'; +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveServerMessages, and then calling the onmessage callback. Note that + * the first message which is received from the server is a setupComplete + * message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage(apiClient, onmessage, event) { + const serverMessage = new LiveServerMessage(); + let jsonData; + if (event.data instanceof Blob) { + jsonData = await event.data.text(); + } + else if (event.data instanceof ArrayBuffer) { + jsonData = new TextDecoder().decode(event.data); + } + else { + jsonData = event.data; + } + const data = JSON.parse(jsonData); + if (apiClient.isVertexAI()) { + const resp = liveServerMessageFromVertex(data); + Object.assign(serverMessage, resp); + } + else { + const resp = liveServerMessageFromMldev(data); + Object.assign(serverMessage, resp); + } + onmessage(serverMessage); +} +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +class Live { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + this.music = new LiveMusic(this.apiClient, this.auth, this.webSocketFactory); + } + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b, _c, _d, _e, _f; + // TODO: b/404946746 - Support per request HTTP options. + if (params.config && params.config.httpOptions) { + throw new Error('The Live module does not support httpOptions at request-level in' + + ' LiveConnectConfig yet. Please use the client-level httpOptions' + + ' configuration instead.'); + } + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + let url; + const clientHeaders = this.apiClient.getHeaders(); + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + setMcpUsageHeader(clientHeaders); + } + const headers = mapToHeaders(clientHeaders); + if (this.apiClient.isVertexAI()) { + url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`; + await this.auth.addAuthHeaders(headers); + } + else { + const apiKey = this.apiClient.getApiKey(); + let method = 'BidiGenerateContent'; + let keyName = 'key'; + if (apiKey === null || apiKey === void 0 ? void 0 : apiKey.startsWith('auth_tokens/')) { + console.warn('Warning: Ephemeral token support is experimental and may change in future versions.'); + if (apiVersion !== 'v1alpha') { + console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."); + } + method = 'BidiGenerateContentConstrained'; + keyName = 'access_token'; + } + url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`; + } + let onopenResolve = () => { }; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + var _a; + (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onopen) === null || _a === void 0 ? void 0 : _a.call(callbacks); + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage(apiClient, callbacks.onmessage, event); + }, + onerror: (_a = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a !== void 0 ? _a : function (e) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function (e) { + }, + }; + const conn = this.webSocketFactory.create(url, headersToMap(headers), websocketCallbacks); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + let transformedModel = tModel(this.apiClient, params.model); + if (this.apiClient.isVertexAI() && + transformedModel.startsWith('publishers/')) { + const project = this.apiClient.getProject(); + const location = this.apiClient.getLocation(); + transformedModel = + `projects/${project}/locations/${location}/` + transformedModel; + } + let clientMessage = {}; + if (this.apiClient.isVertexAI() && + ((_c = params.config) === null || _c === void 0 ? void 0 : _c.responseModalities) === undefined) { + // Set default to AUDIO to align with MLDev API. + if (params.config === undefined) { + params.config = { responseModalities: [Modality.AUDIO] }; + } + else { + params.config.responseModalities = [Modality.AUDIO]; + } + } + if ((_d = params.config) === null || _d === void 0 ? void 0 : _d.generationConfig) { + // Raise deprecation warning for generationConfig. + console.warn('Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).'); + } + const inputTools = (_f = (_e = params.config) === null || _e === void 0 ? void 0 : _e.tools) !== null && _f !== void 0 ? _f : []; + const convertedTools = []; + for (const tool of inputTools) { + if (this.isCallableTool(tool)) { + const callableTool = tool; + convertedTools.push(await callableTool.tool()); + } + else { + convertedTools.push(tool); + } + } + if (convertedTools.length > 0) { + params.config.tools = convertedTools; + } + const liveConnectParameters = { + model: transformedModel, + config: params.config, + callbacks: params.callbacks, + }; + if (this.apiClient.isVertexAI()) { + clientMessage = liveConnectParametersToVertex(this.apiClient, liveConnectParameters); + } + else { + clientMessage = liveConnectParametersToMldev(this.apiClient, liveConnectParameters); + } + delete clientMessage['config']; + conn.send(JSON.stringify(clientMessage)); + return new Session(conn, this.apiClient); + } + // TODO: b/416041229 - Abstract this method to a common place. + isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; + } +} +const defaultLiveSendClientContentParamerters = { + turnComplete: true, +}; +/** + Represents a connection to the API. + + @experimental + */ +class Session { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + tLiveClientContent(apiClient, params) { + if (params.turns !== null && params.turns !== undefined) { + let contents = []; + try { + contents = tContents(params.turns); + if (apiClient.isVertexAI()) { + contents = contents.map((item) => contentToVertex(item)); + } + else { + contents = contents.map((item) => contentToMldev$1(item)); + } + } + catch (_a) { + throw new Error(`Failed to parse client content "turns", type: '${typeof params.turns}'`); + } + return { + clientContent: { turns: contents, turnComplete: params.turnComplete }, + }; + } + return { + clientContent: { turnComplete: params.turnComplete }, + }; + } + tLiveClienttToolResponse(apiClient, params) { + let functionResponses = []; + if (params.functionResponses == null) { + throw new Error('functionResponses is required.'); + } + if (!Array.isArray(params.functionResponses)) { + functionResponses = [params.functionResponses]; + } + else { + functionResponses = params.functionResponses; + } + if (functionResponses.length === 0) { + throw new Error('functionResponses is required.'); + } + for (const functionResponse of functionResponses) { + if (typeof functionResponse !== 'object' || + functionResponse === null || + !('name' in functionResponse) || + !('response' in functionResponse)) { + throw new Error(`Could not parse function response, type '${typeof functionResponse}'.`); + } + if (!apiClient.isVertexAI() && !('id' in functionResponse)) { + throw new Error(FUNCTION_RESPONSE_REQUIRES_ID); + } + } + const clientMessage = { + toolResponse: { functionResponses: functionResponses }, + }; + return clientMessage; + } + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params) { + params = Object.assign(Object.assign({}, defaultLiveSendClientContentParamerters), params); + const clientMessage = this.tLiveClientContent(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params) { + let clientMessage = {}; + if (this.apiClient.isVertexAI()) { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToVertex(params), + }; + } + else { + clientMessage = { + 'realtimeInput': liveSendRealtimeInputParametersToMldev(params), + }; + } + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params) { + if (params.functionResponses == null) { + throw new Error('Tool response parameters are required.'); + } + const clientMessage = this.tLiveClienttToolResponse(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const DEFAULT_MAX_REMOTE_CALLS = 10; +/** Returns whether automatic function calling is disabled. */ +function shouldDisableAfc(config) { + var _a, _b, _c; + if ((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.disable) { + return true; + } + let callableToolsPresent = false; + for (const tool of (_b = config === null || config === void 0 ? void 0 : config.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + callableToolsPresent = true; + break; + } + } + if (!callableToolsPresent) { + return true; + } + const maxCalls = (_c = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _c === void 0 ? void 0 : _c.maximumRemoteCalls; + if ((maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) || + maxCalls == 0) { + console.warn('Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:', maxCalls); + return true; + } + return false; +} +function isCallableTool(tool) { + return 'callTool' in tool && typeof tool.callTool === 'function'; +} +// Checks whether the list of tools contains any CallableTools. Will return true +// if there is at least one CallableTool. +function hasCallableTools(params) { + var _a, _b, _c; + return (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +// Checks whether the list of tools contains any non-callable tools. Will return +// true if there is at least one non-Callable tool. +function hasNonCallableTools(params) { + var _a, _b, _c; + return (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => !isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +/** + * Returns whether to append automatic function calling history to the + * response. + */ +function shouldAppendAfcHistory(config) { + var _a; + return !((_a = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a === void 0 ? void 0 : _a.ignoreCallHistory); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Models extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + this.generateContent = async (params) => { + var _a, _b, _c, _d, _e; + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + this.maybeMoveToResponseJsonSchem(params); + if (!hasCallableTools(params) || shouldDisableAfc(params.config)) { + return await this.generateContentInternal(transformedParams); + } + if (hasNonCallableTools(params)) { + throw new Error('Automatic function calling with CallableTools and Tools is not yet supported.'); + } + let response; + let functionResponseContent; + const automaticFunctionCallingHistory = tContents(transformedParams.contents); + const maxRemoteCalls = (_c = (_b = (_a = transformedParams.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let remoteCalls = 0; + while (remoteCalls < maxRemoteCalls) { + response = await this.generateContentInternal(transformedParams); + if (!response.functionCalls || response.functionCalls.length === 0) { + break; + } + const responseContent = response.candidates[0].content; + const functionResponseParts = []; + for (const tool of (_e = (_d = params.config) === null || _d === void 0 ? void 0 : _d.tools) !== null && _e !== void 0 ? _e : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const parts = await callableTool.callTool(response.functionCalls); + functionResponseParts.push(...parts); + } + } + remoteCalls++; + functionResponseContent = { + role: 'user', + parts: functionResponseParts, + }; + transformedParams.contents = tContents(transformedParams.contents); + transformedParams.contents.push(responseContent); + transformedParams.contents.push(functionResponseContent); + if (shouldAppendAfcHistory(transformedParams.config)) { + automaticFunctionCallingHistory.push(responseContent); + automaticFunctionCallingHistory.push(functionResponseContent); + } + } + if (shouldAppendAfcHistory(transformedParams.config)) { + response.automaticFunctionCallingHistory = + automaticFunctionCallingHistory; + } + return response; + }; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + this.generateContentStream = async (params) => { + this.maybeMoveToResponseJsonSchem(params); + if (shouldDisableAfc(params.config)) { + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + return await this.generateContentStreamInternal(transformedParams); + } + else { + return await this.processAfcStream(params); + } + }; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.generateImages = async (params) => { + return await this.generateImagesInternal(params).then((apiResponse) => { + var _a; + let positivePromptSafetyAttributes; + const generatedImages = []; + if (apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.generatedImages) { + for (const generatedImage of apiResponse.generatedImages) { + if (generatedImage && + (generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) && + ((_a = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) === null || _a === void 0 ? void 0 : _a.contentType) === 'Positive Prompt') { + positivePromptSafetyAttributes = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes; + } + else { + generatedImages.push(generatedImage); + } + } + } + let response; + if (positivePromptSafetyAttributes) { + response = { + generatedImages: generatedImages, + positivePromptSafetyAttributes: positivePromptSafetyAttributes, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + else { + response = { + generatedImages: generatedImages, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + return response; + }); + }; + this.list = async (params) => { + var _a; + const defaultConfig = { + queryBase: true, + }; + const actualConfig = Object.assign(Object.assign({}, defaultConfig), params === null || params === void 0 ? void 0 : params.config); + const actualParams = { + config: actualConfig, + }; + if (this.apiClient.isVertexAI()) { + if (!actualParams.config.queryBase) { + if ((_a = actualParams.config) === null || _a === void 0 ? void 0 : _a.filter) { + throw new Error('Filtering tuned models list for Vertex AI is not currently supported'); + } + else { + actualParams.config.filter = 'labels.tune-type:*'; + } + } + } + return new Pager(PagedItem.PAGED_ITEM_MODELS, (x) => this.listInternal(x), await this.listInternal(actualParams), actualParams); + }; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.editImage = async (params) => { + const paramsInternal = { + model: params.model, + prompt: params.prompt, + referenceImages: [], + config: params.config, + }; + if (params.referenceImages) { + if (params.referenceImages) { + paramsInternal.referenceImages = params.referenceImages.map((img) => img.toReferenceImageAPI()); + } + } + return await this.editImageInternal(paramsInternal); + }; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.upscaleImage = async (params) => { + let apiConfig = { + numberOfImages: 1, + mode: 'upscale', + }; + if (params.config) { + apiConfig = Object.assign(Object.assign({}, apiConfig), params.config); + } + const apiParams = { + model: params.model, + image: params.image, + upscaleFactor: params.upscaleFactor, + config: apiConfig, + }; + return await this.upscaleImageInternal(apiParams); + }; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + this.generateVideos = async (params) => { + return await this.generateVideosInternal(params); + }; + } + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + maybeMoveToResponseJsonSchem(params) { + if (params.config && params.config.responseSchema) { + if (!params.config.responseJsonSchema) { + if (Object.keys(params.config.responseSchema).includes('$schema')) { + params.config.responseJsonSchema = params.config.responseSchema; + delete params.config.responseSchema; + } + } + } + return; + } + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + async processParamsMaybeAddMcpUsage(params) { + var _a, _b, _c; + const tools = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools; + if (!tools) { + return params; + } + const transformedTools = await Promise.all(tools.map(async (tool) => { + if (isCallableTool(tool)) { + const callableTool = tool; + return await callableTool.tool(); + } + return tool; + })); + const newParams = { + model: params.model, + contents: params.contents, + config: Object.assign(Object.assign({}, params.config), { tools: transformedTools }), + }; + newParams.config.tools = transformedTools; + if (params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools)) { + const headers = (_c = (_b = params.config.httpOptions) === null || _b === void 0 ? void 0 : _b.headers) !== null && _c !== void 0 ? _c : {}; + let newHeaders = Object.assign({}, headers); + if (Object.keys(newHeaders).length === 0) { + newHeaders = this.apiClient.getDefaultHeaders(); + } + setMcpUsageHeader(newHeaders); + newParams.config.httpOptions = Object.assign(Object.assign({}, params.config.httpOptions), { headers: newHeaders }); + } + return newParams; + } + async initAfcToolsMap(params) { + var _a, _b, _c; + const afcTools = new Map(); + for (const tool of (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const toolDeclaration = await callableTool.tool(); + for (const declaration of (_c = toolDeclaration.functionDeclarations) !== null && _c !== void 0 ? _c : []) { + if (!declaration.name) { + throw new Error('Function declaration name is required.'); + } + if (afcTools.has(declaration.name)) { + throw new Error(`Duplicate tool declaration name: ${declaration.name}`); + } + afcTools.set(declaration.name, callableTool); + } + } + } + return afcTools; + } + async processAfcStream(params) { + var _a, _b, _c; + const maxRemoteCalls = (_c = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let wereFunctionsCalled = false; + let remoteCallCount = 0; + const afcToolsMap = await this.initAfcToolsMap(params); + return (function (models, afcTools, params) { + var _a, _b; + return __asyncGenerator(this, arguments, function* () { + var _c, e_1, _d, _e; + while (remoteCallCount < maxRemoteCalls) { + if (wereFunctionsCalled) { + remoteCallCount++; + wereFunctionsCalled = false; + } + const transformedParams = yield __await(models.processParamsMaybeAddMcpUsage(params)); + const response = yield __await(models.generateContentStreamInternal(transformedParams)); + const functionResponses = []; + const responseContents = []; + try { + for (var _f = true, response_1 = (e_1 = void 0, __asyncValues(response)), response_1_1; response_1_1 = yield __await(response_1.next()), _c = response_1_1.done, !_c; _f = true) { + _e = response_1_1.value; + _f = false; + const chunk = _e; + yield yield __await(chunk); + if (chunk.candidates && ((_a = chunk.candidates[0]) === null || _a === void 0 ? void 0 : _a.content)) { + responseContents.push(chunk.candidates[0].content); + for (const part of (_b = chunk.candidates[0].content.parts) !== null && _b !== void 0 ? _b : []) { + if (remoteCallCount < maxRemoteCalls && part.functionCall) { + if (!part.functionCall.name) { + throw new Error('Function call name was not returned by the model.'); + } + if (!afcTools.has(part.functionCall.name)) { + throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${part.functionCall.name}`); + } + else { + const responseParts = yield __await(afcTools + .get(part.functionCall.name) + .callTool([part.functionCall])); + functionResponses.push(...responseParts); + } + } + } + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (!_f && !_c && (_d = response_1.return)) yield __await(_d.call(response_1)); + } + finally { if (e_1) throw e_1.error; } + } + if (functionResponses.length > 0) { + wereFunctionsCalled = true; + const typedResponseChunk = new GenerateContentResponse(); + typedResponseChunk.candidates = [ + { + content: { + role: 'user', + parts: functionResponses, + }, + }, + ]; + yield yield __await(typedResponseChunk); + const newContents = []; + newContents.push(...responseContents); + newContents.push({ + role: 'user', + parts: functionResponses, + }); + const updatedContents = tContents(params.contents).concat(newContents); + params.contents = updatedContents; + } + else { + break; + } + } + }); + })(this, afcToolsMap, params); + } + async generateContentInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromVertex(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:generateContent', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromMldev(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async generateContentStreamInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_2, _b, _c; + try { + for (var _d = true, apiResponse_1 = __asyncValues(apiResponse), apiResponse_1_1; apiResponse_1_1 = yield __await(apiResponse_1.next()), _a = apiResponse_1_1.done, !_a; _d = true) { + _c = apiResponse_1_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromVertex((yield __await(chunk.json()))); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_1.return)) yield __await(_b.call(apiResponse_1)); + } + finally { if (e_2) throw e_2.error; } + } + }); + }); + } + else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:streamGenerateContent?alt=sse', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_3, _b, _c; + try { + for (var _d = true, apiResponse_2 = __asyncValues(apiResponse), apiResponse_2_1; apiResponse_2_1 = yield __await(apiResponse_2.next()), _a = apiResponse_2_1.done, !_a; _d = true) { + _c = apiResponse_2_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromMldev((yield __await(chunk.json()))); + resp['sdkHttpResponse'] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (!_d && !_a && (_b = apiResponse_2.return)) yield __await(_b.call(apiResponse_2)); + } + finally { if (e_3) throw e_3.error; } + } + }); + }); + } + } + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + async embedContent(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = embedContentParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromVertex(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = embedContentParametersToMldev(this.apiClient, params); + path = formatMap('{model}:batchEmbedContents', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromMldev(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async generateImagesInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateImagesParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromVertex(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateImagesParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromMldev(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async editImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = editImageParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = editImageResponseFromVertex(apiResponse); + const typedResp = new EditImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + async upscaleImageInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = upscaleImageAPIParametersInternalToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = upscaleImageResponseFromVertex(apiResponse); + const typedResp = new UpscaleImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Recontextualizes an image. + * + * There are two types of recontextualization currently supported: + * 1) Imagen Product Recontext - Generate images of products in new scenes + * and contexts. + * 2) Virtual Try-On: Generate images of persons modeling fashion products. + * + * @param params - The parameters for recontextualizing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response1 = await ai.models.recontextImage({ + * model: 'imagen-product-recontext-preview-06-30', + * source: { + * prompt: 'In a modern kitchen setting.', + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response1?.generatedImages?.[0]?.image?.imageBytes); + * + * const response2 = await ai.models.recontextImage({ + * model: 'virtual-try-on-preview-08-04', + * source: { + * personImage: personImage, + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response2?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async recontextImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = recontextImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = recontextImageResponseFromVertex(apiResponse); + const typedResp = new RecontextImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Segments an image, creating a mask of a specified area. + * + * @param params - The parameters for segmenting an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.segmentImage({ + * model: 'image-segmentation-001', + * source: { + * image: image, + * }, + * config: { + * mode: 'foreground', + * }, + * }); + * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes); + * ``` + */ + async segmentImage(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = segmentImageParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predict', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = segmentImageResponseFromVertex(apiResponse); + const typedResp = new SegmentImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listModelsParametersToVertex(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromVertex(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listModelsParametersToMldev(this.apiClient, params); + path = formatMap('{models_url}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromMldev(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateModelParametersToVertex(this.apiClient, params); + path = formatMap('{model}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } + else { + const body = updateModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteModelParametersToVertex(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteModelResponseFromVertex(); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = deleteModelParametersToMldev(this.apiClient, params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteModelResponseFromMldev(); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + async countTokens(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = countTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromVertex(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = countTokensParametersToMldev(this.apiClient, params); + path = formatMap('{model}:countTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromMldev(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + async computeTokens(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = computeTokensParametersToVertex(this.apiClient, params); + path = formatMap('{model}:computeTokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = computeTokensResponseFromVertex(apiResponse); + const typedResp = new ComputeTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + async generateVideosInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateVideosParametersToVertex(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = generateVideosParametersToMldev(this.apiClient, params); + path = formatMap('{model}:predictLongRunning', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getOperationParametersToMldev(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function getOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['_url', 'operationName'], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function fetchPredictOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, [ + 'operationName', + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ['operationName'], fromOperationName); + } + const fromResourceName = getValueByPath(fromObject, ['resourceName']); + if (fromResourceName != null) { + setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Operations extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async getVideosOperation(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async get(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === '') { + throw new Error('Operation name is required.'); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split('/operations/')[0]; + let httpOptions = undefined; + if (config && 'httpOptions' in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } + else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + async getVideosOperationInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getOperationParametersToVertex(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + const body = getOperationParametersToMldev(params); + path = formatMap('{operationName}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + } + async fetchPredictVideosOperationInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = fetchPredictOperationParametersToVertex(params); + path = formatMap('{resourceName}:fetchPredictOperation', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ['voiceName']); + if (fromVoiceName != null) { + setValueByPath(toObject, ['voiceName'], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + 'prebuiltVoiceConfig', + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath(toObject, ['prebuiltVoiceConfig'], prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig)); + } + return toObject; +} +function speakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ['speaker']); + if (fromSpeaker != null) { + setValueByPath(toObject, ['speaker'], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(fromVoiceConfig)); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + 'speakerVoiceConfigs', + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev(item); + }); + } + setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList); + } + return toObject; +} +function speechConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']); + if (fromVoiceConfig != null) { + setValueByPath(toObject, ['voiceConfig'], voiceConfigToMldev(fromVoiceConfig)); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + 'multiSpeakerVoiceConfig', + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath(toObject, ['multiSpeakerVoiceConfig'], multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig)); + } + const fromLanguageCode = getValueByPath(fromObject, ['languageCode']); + if (fromLanguageCode != null) { + setValueByPath(toObject, ['languageCode'], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ['fps']); + if (fromFps != null) { + setValueByPath(toObject, ['fps'], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ['endOffset']); + if (fromEndOffset != null) { + setValueByPath(toObject, ['endOffset'], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ['startOffset']); + if (fromStartOffset != null) { + setValueByPath(toObject, ['startOffset'], fromStartOffset); + } + return toObject; +} +function blobToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromData = getValueByPath(fromObject, ['data']); + if (fromData != null) { + setValueByPath(toObject, ['data'], fromData); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function fileDataToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['displayName']) !== undefined) { + throw new Error('displayName parameter is not supported in Gemini API.'); + } + const fromFileUri = getValueByPath(fromObject, ['fileUri']); + if (fromFileUri != null) { + setValueByPath(toObject, ['fileUri'], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ['mimeType']); + if (fromMimeType != null) { + setValueByPath(toObject, ['mimeType'], fromMimeType); + } + return toObject; +} +function partToMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, [ + 'videoMetadata', + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ['videoMetadata'], videoMetadataToMldev(fromVideoMetadata)); + } + const fromThought = getValueByPath(fromObject, ['thought']); + if (fromThought != null) { + setValueByPath(toObject, ['thought'], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ['inlineData']); + if (fromInlineData != null) { + setValueByPath(toObject, ['inlineData'], blobToMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ['fileData']); + if (fromFileData != null) { + setValueByPath(toObject, ['fileData'], fileDataToMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, [ + 'thoughtSignature', + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + 'codeExecutionResult', + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ['codeExecutionResult'], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, [ + 'executableCode', + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ['executableCode'], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ['functionCall']); + if (fromFunctionCall != null) { + setValueByPath(toObject, ['functionCall'], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, [ + 'functionResponse', + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ['functionResponse'], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ['text']); + if (fromText != null) { + setValueByPath(toObject, ['text'], fromText); + } + return toObject; +} +function contentToMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ['parts']); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev(item); + }); + } + setValueByPath(toObject, ['parts'], transformedList); + } + const fromRole = getValueByPath(fromObject, ['role']); + if (fromRole != null) { + setValueByPath(toObject, ['role'], fromRole); + } + return toObject; +} +function functionDeclarationToMldev(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ['behavior']); + if (fromBehavior != null) { + setValueByPath(toObject, ['behavior'], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromParameters = getValueByPath(fromObject, ['parameters']); + if (fromParameters != null) { + setValueByPath(toObject, ['parameters'], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + 'parametersJsonSchema', + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ['parametersJsonSchema'], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject, ['response']); + if (fromResponse != null) { + setValueByPath(toObject, ['response'], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + 'responseJsonSchema', + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ['responseJsonSchema'], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + return toObject; +} +function googleSearchToMldev(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, [ + 'timeRangeFilter', + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ['timeRangeFilter'], intervalToMldev(fromTimeRangeFilter)); + } + if (getValueByPath(fromObject, ['excludeDomains']) !== undefined) { + throw new Error('excludeDomains parameter is not supported in Gemini API.'); + } + return toObject; +} +function dynamicRetrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ['mode']); + if (fromMode != null) { + setValueByPath(toObject, ['mode'], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, [ + 'dynamicThreshold', + ]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + 'dynamicRetrievalConfig', + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath(toObject, ['dynamicRetrievalConfig'], dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig)); + } + return toObject; +} +function urlContextToMldev() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev(fromObject) { + const toObject = {}; + const fromEnvironment = getValueByPath(fromObject, ['environment']); + if (fromEnvironment != null) { + setValueByPath(toObject, ['environment'], fromEnvironment); + } + return toObject; +} +function toolToMldev(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + 'functionDeclarations', + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev(item); + }); + } + setValueByPath(toObject, ['functionDeclarations'], transformedList); + } + if (getValueByPath(fromObject, ['retrieval']) !== undefined) { + throw new Error('retrieval parameter is not supported in Gemini API.'); + } + const fromGoogleSearch = getValueByPath(fromObject, ['googleSearch']); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ['googleSearch'], googleSearchToMldev(fromGoogleSearch)); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + 'googleSearchRetrieval', + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ['googleSearchRetrieval'], googleSearchRetrievalToMldev(fromGoogleSearchRetrieval)); + } + if (getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined) { + throw new Error('enterpriseWebSearch parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['googleMaps']) !== undefined) { + throw new Error('googleMaps parameter is not supported in Gemini API.'); + } + const fromUrlContext = getValueByPath(fromObject, ['urlContext']); + if (fromUrlContext != null) { + setValueByPath(toObject, ['urlContext'], urlContextToMldev()); + } + const fromComputerUse = getValueByPath(fromObject, ['computerUse']); + if (fromComputerUse != null) { + setValueByPath(toObject, ['computerUse'], toolComputerUseToMldev(fromComputerUse)); + } + const fromCodeExecution = getValueByPath(fromObject, [ + 'codeExecution', + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ['codeExecution'], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ['handle']); + if (fromHandle != null) { + setValueByPath(toObject, ['handle'], fromHandle); + } + if (getValueByPath(fromObject, ['transparent']) !== undefined) { + throw new Error('transparent parameter is not supported in Gemini API.'); + } + return toObject; +} +function audioTranscriptionConfigToMldev() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ['disabled']); + if (fromDisabled != null) { + setValueByPath(toObject, ['disabled'], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + 'startOfSpeechSensitivity', + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath(toObject, ['startOfSpeechSensitivity'], fromStartOfSpeechSensitivity); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + 'endOfSpeechSensitivity', + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath(toObject, ['endOfSpeechSensitivity'], fromEndOfSpeechSensitivity); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, [ + 'prefixPaddingMs', + ]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + 'silenceDurationMs', + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ['silenceDurationMs'], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + 'automaticActivityDetection', + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath(toObject, ['automaticActivityDetection'], automaticActivityDetectionToMldev(fromAutomaticActivityDetection)); + } + const fromActivityHandling = getValueByPath(fromObject, [ + 'activityHandling', + ]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ['activityHandling'], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ['turnCoverage']); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ['targetTokens']); + if (fromTargetTokens != null) { + setValueByPath(toObject, ['targetTokens'], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, [ + 'triggerTokens', + ]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, [ + 'slidingWindow', + ]); + if (fromSlidingWindow != null) { + setValueByPath(toObject, ['slidingWindow'], slidingWindowToMldev(fromSlidingWindow)); + } + return toObject; +} +function proactivityConfigToMldev(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, [ + 'proactiveAudio', + ]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, [ + 'generationConfig', + ]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig'], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject, [ + 'responseModalities', + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'responseModalities'], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject, ['temperature']); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'temperature'], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ['topP']); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topP'], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ['topK']); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'topK'], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject, [ + 'maxOutputTokens', + ]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'maxOutputTokens'], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject, [ + 'mediaResolution', + ]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'mediaResolution'], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject, ['seed']); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'seed'], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToMldev(tLiveSpeechConfig(fromSpeechConfig))); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + 'enableAffectiveDialog', + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ['setup', 'generationConfig', 'enableAffectiveDialog'], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + 'systemInstruction', + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath(parentObject, ['setup', 'systemInstruction'], contentToMldev(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject, ['tools']); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev(tTool(item)); + }); + } + setValueByPath(parentObject, ['setup', 'tools'], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + 'sessionResumption', + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath(parentObject, ['setup', 'sessionResumption'], sessionResumptionConfigToMldev(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + 'inputAudioTranscription', + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'inputAudioTranscription'], audioTranscriptionConfigToMldev()); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + 'outputAudioTranscription', + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ['setup', 'outputAudioTranscription'], audioTranscriptionConfigToMldev()); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + 'realtimeInputConfig', + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ['setup', 'realtimeInputConfig'], realtimeInputConfigToMldev(fromRealtimeInputConfig)); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + 'contextWindowCompression', + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath(parentObject, ['setup', 'contextWindowCompression'], contextWindowCompressionConfigToMldev(fromContextWindowCompression)); + } + const fromProactivity = getValueByPath(fromObject, ['proactivity']); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath(parentObject, ['setup', 'proactivity'], proactivityConfigToMldev(fromProactivity)); + } + return toObject; +} +function liveConnectConstraintsToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['setup', 'model'], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], liveConnectConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function createAuthTokenConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromExpireTime = getValueByPath(fromObject, ['expireTime']); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ['expireTime'], fromExpireTime); + } + const fromNewSessionExpireTime = getValueByPath(fromObject, [ + 'newSessionExpireTime', + ]); + if (parentObject !== undefined && fromNewSessionExpireTime != null) { + setValueByPath(parentObject, ['newSessionExpireTime'], fromNewSessionExpireTime); + } + const fromUses = getValueByPath(fromObject, ['uses']); + if (parentObject !== undefined && fromUses != null) { + setValueByPath(parentObject, ['uses'], fromUses); + } + const fromLiveConnectConstraints = getValueByPath(fromObject, [ + 'liveConnectConstraints', + ]); + if (parentObject !== undefined && fromLiveConnectConstraints != null) { + setValueByPath(parentObject, ['bidiGenerateContentSetup'], liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints)); + } + const fromLockAdditionalFields = getValueByPath(fromObject, [ + 'lockAdditionalFields', + ]); + if (parentObject !== undefined && fromLockAdditionalFields != null) { + setValueByPath(parentObject, ['fieldMask'], fromLockAdditionalFields); + } + return toObject; +} +function createAuthTokenParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createAuthTokenConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function authTokenFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns a comma-separated list of field masks from a given object. + * + * @param setup The object to extract field masks from. + * @return A comma-separated list of field masks. + */ +function getFieldMasks(setup) { + const fields = []; + for (const key in setup) { + if (Object.prototype.hasOwnProperty.call(setup, key)) { + const value = setup[key]; + // 2nd layer, recursively get field masks see TODO(b/418290100) + if (typeof value === 'object' && + value != null && + Object.keys(value).length > 0) { + const field = Object.keys(value).map((kk) => `${key}.${kk}`); + fields.push(...field); + } + else { + fields.push(key); // 1st layer + } + } + } + return fields.join(','); +} +/** + * Converts bidiGenerateContentSetup. + * @param requestDict - The request dictionary. + * @param config - The configuration object. + * @return - The modified request dictionary. + */ +function convertBidiSetupToTokenSetup(requestDict, config) { + // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup. + let setupForMaskGeneration = null; + const bidiGenerateContentSetupValue = requestDict['bidiGenerateContentSetup']; + if (typeof bidiGenerateContentSetupValue === 'object' && + bidiGenerateContentSetupValue !== null && + 'setup' in bidiGenerateContentSetupValue) { + // Now we know bidiGenerateContentSetupValue is an object and has a 'setup' + // property. + const innerSetup = bidiGenerateContentSetupValue + .setup; + if (typeof innerSetup === 'object' && innerSetup !== null) { + // Valid inner setup found. + requestDict['bidiGenerateContentSetup'] = innerSetup; + setupForMaskGeneration = innerSetup; + } + else { + // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as + // if bidiGenerateContentSetup is invalid. + delete requestDict['bidiGenerateContentSetup']; + } + } + else if (bidiGenerateContentSetupValue !== undefined) { + // `bidiGenerateContentSetup` exists but not in the expected + // shape {setup: {...}}; treat as invalid. + delete requestDict['bidiGenerateContentSetup']; + } + const preExistingFieldMask = requestDict['fieldMask']; + // Handle mask generation setup. + if (setupForMaskGeneration) { + const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration); + if (Array.isArray(config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + (config === null || config === void 0 ? void 0 : config.lockAdditionalFields.length) === 0) { + // Case 1: lockAdditionalFields is an empty array. Lock only fields from + // bidi setup. + if (generatedMaskFromBidi) { + // Only assign if mask is not empty + requestDict['fieldMask'] = generatedMaskFromBidi; + } + else { + delete requestDict['fieldMask']; // If mask is empty, effectively no + // specific fields locked by bidi + } + } + else if ((config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && + config.lockAdditionalFields.length > 0 && + preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // Case 2: Lock fields from bidi setup + additional fields + // (preExistingFieldMask). + const generationConfigFields = [ + 'temperature', + 'topK', + 'topP', + 'maxOutputTokens', + 'responseModalities', + 'seed', + 'speechConfig', + ]; + let mappedFieldsFromPreExisting = []; + if (preExistingFieldMask.length > 0) { + mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => { + if (generationConfigFields.includes(field)) { + return `generationConfig.${field}`; + } + return field; // Keep original field name if not in + // generationConfigFields + }); + } + const finalMaskParts = []; + if (generatedMaskFromBidi) { + finalMaskParts.push(generatedMaskFromBidi); + } + if (mappedFieldsFromPreExisting.length > 0) { + finalMaskParts.push(...mappedFieldsFromPreExisting); + } + if (finalMaskParts.length > 0) { + requestDict['fieldMask'] = finalMaskParts.join(','); + } + else { + // If no fields from bidi and no valid additional fields from + // pre-existing mask. + delete requestDict['fieldMask']; + } + } + else { + // Case 3: "Lock all fields" (meaning, don't send a field_mask, let server + // defaults apply or all are mutable). This is hit if: + // - `config.lockAdditionalFields` is undefined. + // - `config.lockAdditionalFields` is non-empty, BUT + // `preExistingFieldMask` is null, not a string, or an empty string. + delete requestDict['fieldMask']; + } + } + else { + // No valid `bidiGenerateContentSetup` was found or extracted. + // "Lock additional null fields if any". + if (preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0) { + // If there's a pre-existing field mask, it's a string, and it's not + // empty, then we should lock all fields. + requestDict['fieldMask'] = preExistingFieldMask.join(','); + } + else { + delete requestDict['fieldMask']; + } + } + return requestDict; +} +class Tokens extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + async create(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('The client.tokens.create method is only supported by the Gemini Developer API.'); + } + else { + const body = createAuthTokenParametersToMldev(this.apiClient, params); + path = formatMap('auth_tokens', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + const transformedBody = convertBidiSetupToTokenSetup(body, params.config); + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(transformedBody), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = authTokenFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listTuningJobsConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function tuningExampleToMldev(fromObject) { + const toObject = {}; + const fromTextInput = getValueByPath(fromObject, ['textInput']); + if (fromTextInput != null) { + setValueByPath(toObject, ['textInput'], fromTextInput); + } + const fromOutput = getValueByPath(fromObject, ['output']); + if (fromOutput != null) { + setValueByPath(toObject, ['output'], fromOutput); + } + return toObject; +} +function tuningDatasetToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['gcsUri']) !== undefined) { + throw new Error('gcsUri parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['vertexDatasetResource']) !== undefined) { + throw new Error('vertexDatasetResource parameter is not supported in Gemini API.'); + } + const fromExamples = getValueByPath(fromObject, ['examples']); + if (fromExamples != null) { + let transformedList = fromExamples; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningExampleToMldev(item); + }); + } + setValueByPath(toObject, ['examples', 'examples'], transformedList); + } + return toObject; +} +function createTuningJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ['validationDataset']) !== undefined) { + throw new Error('validationDataset parameter is not supported in Gemini API.'); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['displayName'], fromTunedModelDisplayName); + } + if (getValueByPath(fromObject, ['description']) !== undefined) { + throw new Error('description parameter is not supported in Gemini API.'); + } + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (fromLearningRateMultiplier != null) { + setValueByPath(toObject, ['tuningTask', 'hyperparameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + if (getValueByPath(fromObject, ['exportLastCheckpointOnly']) !== + undefined) { + throw new Error('exportLastCheckpointOnly parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['preTunedModelCheckpointId']) !== + undefined) { + throw new Error('preTunedModelCheckpointId parameter is not supported in Gemini API.'); + } + if (getValueByPath(fromObject, ['adapterSize']) !== undefined) { + throw new Error('adapterSize parameter is not supported in Gemini API.'); + } + const fromBatchSize = getValueByPath(fromObject, ['batchSize']); + if (parentObject !== undefined && fromBatchSize != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'batchSize'], fromBatchSize); + } + const fromLearningRate = getValueByPath(fromObject, ['learningRate']); + if (parentObject !== undefined && fromLearningRate != null) { + setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'learningRate'], fromLearningRate); + } + return toObject; +} +function createTuningJobParametersPrivateToMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + setValueByPath(toObject, ['tuningTask', 'trainingData'], tuningDatasetToMldev(fromTrainingDataset)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createTuningJobConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function getTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['_url', 'name'], fromName); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], listTuningJobsConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function tuningDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (parentObject !== undefined && fromGcsUri != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + if (getValueByPath(fromObject, ['examples']) !== undefined) { + throw new Error('examples parameter is not supported in Vertex AI.'); + } + return toObject; +} +function tuningValidationDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ['gcsUri']); + if (fromGcsUri != null) { + setValueByPath(toObject, ['validationDatasetUri'], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + 'vertexDatasetResource', + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'trainingDatasetUri'], fromVertexDatasetResource); + } + return toObject; +} +function createTuningJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromValidationDataset = getValueByPath(fromObject, [ + 'validationDataset', + ]); + if (parentObject !== undefined && fromValidationDataset != null) { + setValueByPath(parentObject, ['supervisedTuningSpec'], tuningValidationDatasetToVertex(fromValidationDataset, toObject)); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ['description'], fromDescription); + } + const fromEpochCount = getValueByPath(fromObject, ['epochCount']); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'epochCount'], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + 'learningRateMultiplier', + ]); + if (parentObject !== undefined && fromLearningRateMultiplier != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'], fromLearningRateMultiplier); + } + const fromExportLastCheckpointOnly = getValueByPath(fromObject, [ + 'exportLastCheckpointOnly', + ]); + if (parentObject !== undefined && fromExportLastCheckpointOnly != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'exportLastCheckpointOnly'], fromExportLastCheckpointOnly); + } + const fromPreTunedModelCheckpointId = getValueByPath(fromObject, [ + 'preTunedModelCheckpointId', + ]); + if (fromPreTunedModelCheckpointId != null) { + setValueByPath(toObject, ['preTunedModel', 'checkpointId'], fromPreTunedModelCheckpointId); + } + const fromAdapterSize = getValueByPath(fromObject, ['adapterSize']); + if (parentObject !== undefined && fromAdapterSize != null) { + setValueByPath(parentObject, ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'], fromAdapterSize); + } + if (getValueByPath(fromObject, ['batchSize']) !== undefined) { + throw new Error('batchSize parameter is not supported in Vertex AI.'); + } + if (getValueByPath(fromObject, ['learningRate']) !== undefined) { + throw new Error('learningRate parameter is not supported in Vertex AI.'); + } + return toObject; +} +function createTuningJobParametersPrivateToVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject, [ + 'trainingDataset', + ]); + if (fromTrainingDataset != null) { + setValueByPath(toObject, ['supervisedTuningSpec', 'trainingDatasetUri'], tuningDatasetToVertex(fromTrainingDataset, toObject)); + } + const fromConfig = getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + setValueByPath(toObject, ['config'], createTuningJobConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function tunedModelFromMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['name']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ['name']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + return toObject; +} +function tuningJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, [ + 'tuningTask', + 'startTime', + ]); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, [ + 'tuningTask', + 'completeTime', + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['_self']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], tunedModelFromMldev(fromTunedModel)); + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel); + } + const fromExperiment = getValueByPath(fromObject, ['experiment']); + if (fromExperiment != null) { + setValueByPath(toObject, ['experiment'], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (fromOutputUri != null) { + setValueByPath(toObject, ['outputUri'], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject, ['pipelineJob']); + if (fromPipelineJob != null) { + setValueByPath(toObject, ['pipelineJob'], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject, [ + 'serviceAccount', + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ['serviceAccount'], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + return toObject; +} +function listTuningJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ['tunedModels']); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromMldev(item); + }); + } + setValueByPath(toObject, ['tuningJobs'], transformedList); + } + return toObject; +} +function tuningOperationFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromMetadata = getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + setValueByPath(toObject, ['metadata'], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ['done']); + if (fromDone != null) { + setValueByPath(toObject, ['done'], fromDone); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + return toObject; +} +function tunedModelCheckpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ['checkpointId']); + if (fromCheckpointId != null) { + setValueByPath(toObject, ['checkpointId'], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ['epoch']); + if (fromEpoch != null) { + setValueByPath(toObject, ['epoch'], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ['step']); + if (fromStep != null) { + setValueByPath(toObject, ['step'], fromStep); + } + const fromEndpoint = getValueByPath(fromObject, ['endpoint']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + return toObject; +} +function tunedModelFromVertex(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ['model']); + if (fromModel != null) { + setValueByPath(toObject, ['model'], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ['endpoint']); + if (fromEndpoint != null) { + setValueByPath(toObject, ['endpoint'], fromEndpoint); + } + const fromCheckpoints = getValueByPath(fromObject, ['checkpoints']); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tunedModelCheckpointFromVertex(item); + }); + } + setValueByPath(toObject, ['checkpoints'], transformedList); + } + return toObject; +} +function tuningJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ['name']); + if (fromName != null) { + setValueByPath(toObject, ['name'], fromName); + } + const fromState = getValueByPath(fromObject, ['state']); + if (fromState != null) { + setValueByPath(toObject, ['state'], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ['createTime']); + if (fromCreateTime != null) { + setValueByPath(toObject, ['createTime'], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ['startTime']); + if (fromStartTime != null) { + setValueByPath(toObject, ['startTime'], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ['endTime']); + if (fromEndTime != null) { + setValueByPath(toObject, ['endTime'], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ['updateTime']); + if (fromUpdateTime != null) { + setValueByPath(toObject, ['updateTime'], fromUpdateTime); + } + const fromError = getValueByPath(fromObject, ['error']); + if (fromError != null) { + setValueByPath(toObject, ['error'], fromError); + } + const fromDescription = getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + setValueByPath(toObject, ['description'], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ['baseModel']); + if (fromBaseModel != null) { + setValueByPath(toObject, ['baseModel'], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ['tunedModel']); + if (fromTunedModel != null) { + setValueByPath(toObject, ['tunedModel'], tunedModelFromVertex(fromTunedModel)); + } + const fromPreTunedModel = getValueByPath(fromObject, [ + 'preTunedModel', + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel); + } + const fromSupervisedTuningSpec = getValueByPath(fromObject, [ + 'supervisedTuningSpec', + ]); + if (fromSupervisedTuningSpec != null) { + setValueByPath(toObject, ['supervisedTuningSpec'], fromSupervisedTuningSpec); + } + const fromTuningDataStats = getValueByPath(fromObject, [ + 'tuningDataStats', + ]); + if (fromTuningDataStats != null) { + setValueByPath(toObject, ['tuningDataStats'], fromTuningDataStats); + } + const fromEncryptionSpec = getValueByPath(fromObject, [ + 'encryptionSpec', + ]); + if (fromEncryptionSpec != null) { + setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec); + } + const fromPartnerModelTuningSpec = getValueByPath(fromObject, [ + 'partnerModelTuningSpec', + ]); + if (fromPartnerModelTuningSpec != null) { + setValueByPath(toObject, ['partnerModelTuningSpec'], fromPartnerModelTuningSpec); + } + const fromCustomBaseModel = getValueByPath(fromObject, [ + 'customBaseModel', + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel); + } + const fromExperiment = getValueByPath(fromObject, ['experiment']); + if (fromExperiment != null) { + setValueByPath(toObject, ['experiment'], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ['labels']); + if (fromLabels != null) { + setValueByPath(toObject, ['labels'], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject, ['outputUri']); + if (fromOutputUri != null) { + setValueByPath(toObject, ['outputUri'], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject, ['pipelineJob']); + if (fromPipelineJob != null) { + setValueByPath(toObject, ['pipelineJob'], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject, [ + 'serviceAccount', + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ['serviceAccount'], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + 'tunedModelDisplayName', + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ['tunedModelDisplayName'], fromTunedModelDisplayName); + } + return toObject; +} +function listTuningJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, [ + 'sdkHttpResponse', + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, [ + 'nextPageToken', + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ['nextPageToken'], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ['tuningJobs']); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromVertex(item); + }); + } + setValueByPath(toObject, ['tuningJobs'], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Tunings extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.get = async (params) => { + return await this.getInternal(params); + }; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_TUNING_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params); + }; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.tune = async (params) => { + if (this.apiClient.isVertexAI()) { + if (params.baseModel.startsWith('projects/')) { + const preTunedModel = { + tunedModelName: params.baseModel, + }; + const paramsPrivate = Object.assign(Object.assign({}, params), { preTunedModel: preTunedModel }); + paramsPrivate.baseModel = undefined; + return await this.tuneInternal(paramsPrivate); + } + else { + const paramsPrivate = Object.assign({}, params); + return await this.tuneInternal(paramsPrivate); + } + } + else { + const paramsPrivate = Object.assign({}, params); + const operation = await this.tuneMldevInternal(paramsPrivate); + let tunedModelName = ''; + if (operation['metadata'] !== undefined && + operation['metadata']['tunedModel'] !== undefined) { + tunedModelName = operation['metadata']['tunedModel']; + } + else if (operation['name'] !== undefined && + operation['name'].includes('/operations/')) { + tunedModelName = operation['name'].split('/operations/')[0]; + } + const tuningJob = { + name: tunedModelName, + state: JobState.JOB_STATE_QUEUED, + }; + return tuningJob; + } + }; + } + async getInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getTuningJobParametersToVertex(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + const body = getTuningJobParametersToMldev(params); + path = formatMap('{name}', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listTuningJobsParametersToVertex(params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromVertex(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + else { + const body = listTuningJobsParametersToMldev(params); + path = formatMap('tunedModels', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromMldev(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async tuneInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createTuningJobParametersPrivateToVertex(params); + path = formatMap('tuningJobs', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } + else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + async tuneMldevInternal(params) { + var _a, _b; + let response; + let path = ''; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error('This method is only supported by the Gemini Developer API.'); + } + else { + const body = createTuningJobParametersPrivateToMldev(params); + path = formatMap('tunedModels', body['_url']); + queryParams = body['_query']; + delete body['config']; + delete body['_url']; + delete body['_query']; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningOperationFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BrowserDownloader { + async download(_params, _apiClient) { + throw new Error('Download to file is not supported in the browser, please use a browser compliant download like an tag.'); + } +} + +const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes +const MAX_RETRY_COUNT = 3; +const INITIAL_RETRY_DELAY_MS = 1000; +const DELAY_MULTIPLIER = 2; +const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status'; +async function uploadBlob(file, uploadUrl, apiClient) { + var _a, _b, _c; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = 'upload'; + fileSize = file.size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + const chunk = file.slice(offset, offset + chunkSize); + if (offset + chunkSize >= fileSize) { + uploadCommand += ', finalize'; + } + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: '', + body: chunk, + httpMethod: 'POST', + httpOptions: { + apiVersion: '', + baseUrl: uploadUrl, + headers: { + 'X-Goog-Upload-Command': uploadCommand, + 'X-Goog-Upload-Offset': String(offset), + 'Content-Length': String(chunkSize), + }, + }, + }); + if ((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += chunkSize; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'active') { + break; + } + // TODO(b/401391430) Investigate why the upload status is not finalized + // even though all content has been uploaded. + if (fileSize <= offset) { + throw new Error('All content has been uploaded, but the upload status is not finalized.'); + } + } + const responseJson = (await (response === null || response === void 0 ? void 0 : response.json())); + if (((_c = response === null || response === void 0 ? void 0 : response.headers) === null || _c === void 0 ? void 0 : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') { + throw new Error('Failed to upload file: Upload status is not finalized.'); + } + return responseJson['file']; +} +async function getBlobStat(file) { + const fileStat = { size: file.size, type: file.type }; + return fileStat; +} +function sleep(ms) { + return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); +} + +class BrowserUploader { + async upload(file, uploadUrl, apiClient) { + if (typeof file === 'string') { + throw new Error('File path is not supported in browser uploader.'); + } + return await uploadBlob(file, uploadUrl, apiClient); + } + async stat(file) { + if (typeof file === 'string') { + throw new Error('File path is not supported in browser uploader.'); + } + else { + return await getBlobStat(file); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BrowserWebSocketFactory { + create(url, headers, callbacks) { + return new BrowserWebSocket(url, headers, callbacks); + } +} +class BrowserWebSocket { + constructor(url, headers, callbacks) { + this.url = url; + this.headers = headers; + this.callbacks = callbacks; + } + connect() { + this.ws = new WebSocket(this.url); + this.ws.onopen = this.callbacks.onopen; + this.ws.onerror = this.callbacks.onerror; + this.ws.onclose = this.callbacks.onclose; + this.ws.onmessage = this.callbacks.onmessage; + } + send(message) { + if (this.ws === undefined) { + throw new Error('WebSocket is not connected'); + } + this.ws.send(message); + } + close() { + if (this.ws === undefined) { + throw new Error('WebSocket is not connected'); + } + this.ws.close(); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const GOOGLE_API_KEY_HEADER = 'x-goog-api-key'; +// TODO(b/395122533): We need a secure client side authentication mechanism. +class WebAuth { + constructor(apiKey) { + this.apiKey = apiKey; + } + async addAuthHeaders(headers) { + if (headers.get(GOOGLE_API_KEY_HEADER) !== null) { + return; + } + if (this.apiKey.startsWith('auth_tokens/')) { + throw new Error('Ephemeral tokens are only supported by the live API.'); + } + // Check if API key is empty or null + if (!this.apiKey) { + throw new Error('API key is missing. Please provide a valid API key.'); + } + headers.append(GOOGLE_API_KEY_HEADER, this.apiKey); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const LANGUAGE_LABEL_PREFIX = 'gl-node/'; +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link + * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or + * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI + * API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API + * services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be + * set. When using Vertex AI, currently only {@link GoogleGenAIOptions.apiKey} + * is supported via Express mode. {@link GoogleGenAIOptions.project} and {@link + * GoogleGenAIOptions.location} should not be set. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +class GoogleGenAI { + constructor(options) { + var _a; + if (options.apiKey == null) { + throw new Error('An API Key must be set when running in a browser'); + } + // Web client only supports API key mode for Vertex AI. + if (options.project || options.location) { + throw new Error('Vertex AI project based authentication is not supported on browser runtimes. Please do not provide a project or location.'); + } + this.vertexai = (_a = options.vertexai) !== null && _a !== void 0 ? _a : false; + this.apiKey = options.apiKey; + const baseUrl = getBaseUrl(options.httpOptions, options.vertexai, + /*vertexBaseUrlFromEnv*/ undefined, + /*geminiBaseUrlFromEnv*/ undefined); + if (baseUrl) { + if (options.httpOptions) { + options.httpOptions.baseUrl = baseUrl; + } + else { + options.httpOptions = { baseUrl: baseUrl }; + } + } + this.apiVersion = options.apiVersion; + const auth = new WebAuth(this.apiKey); + this.apiClient = new ApiClient({ + auth: auth, + apiVersion: this.apiVersion, + apiKey: this.apiKey, + vertexai: this.vertexai, + httpOptions: options.httpOptions, + userAgentExtra: LANGUAGE_LABEL_PREFIX + 'web', + uploader: new BrowserUploader(), + downloader: new BrowserDownloader(), + }); + this.models = new Models(this.apiClient); + this.live = new Live(this.apiClient, auth, new BrowserWebSocketFactory()); + this.batches = new Batches(this.apiClient); + this.chats = new Chats(this.models, this.apiClient); + this.caches = new Caches(this.apiClient); + this.files = new Files(this.apiClient); + this.operations = new Operations(this.apiClient); + this.authTokens = new Tokens(this.apiClient); + this.tunings = new Tunings(this.apiClient); + } +} + +export { ActivityHandling, AdapterSize, ApiError, ApiSpec, AuthType, Batches, Behavior, BlockedReason, Caches, Chat, Chats, ComputeTokensResponse, ControlReferenceImage, ControlReferenceType, CountTokensResponse, CreateFileResponse, DeleteCachedContentResponse, DeleteFileResponse, DeleteModelResponse, DynamicRetrievalConfigMode, EditImageResponse, EditMode, EmbedContentResponse, EndSensitivity, Environment, FeatureSelectionPreference, FileSource, FileState, Files, FinishReason, FunctionCallingConfigMode, FunctionResponse, FunctionResponseScheduling, GenerateContentResponse, GenerateContentResponsePromptFeedback, GenerateContentResponseUsageMetadata, GenerateImagesResponse, GenerateVideosOperation, GenerateVideosResponse, GoogleGenAI, HarmBlockMethod, HarmBlockThreshold, HarmCategory, HarmProbability, HarmSeverity, HttpResponse, ImagePromptLanguage, InlinedResponse, JobState, Language, ListBatchJobsResponse, ListCachedContentsResponse, ListFilesResponse, ListModelsResponse, ListTuningJobsResponse, Live, LiveClientToolResponse, LiveMusicPlaybackControl, LiveMusicServerMessage, LiveSendToolResponseParameters, LiveServerMessage, MaskReferenceImage, MaskReferenceMode, MediaModality, MediaResolution, Modality, Mode, Models, MusicGenerationMode, Operations, Outcome, PagedItem, Pager, PersonGeneration, RawReferenceImage, RecontextImageResponse, ReplayResponse, SafetyFilterLevel, Scale, SegmentImageResponse, SegmentMode, Session, StartSensitivity, StyleReferenceImage, SubjectReferenceImage, SubjectReferenceType, Tokens, TrafficType, TuningMode, TurnCoverage, Type, UpscaleImageResponse, UrlRetrievalStatus, VideoCompressionQuality, createModelContent, createPartFromBase64, createPartFromCodeExecutionResult, createPartFromExecutableCode, createPartFromFunctionCall, createPartFromFunctionResponse, createPartFromText, createPartFromUri, createUserContent, mcpToTool, setDefaultBaseUrls }; +//# sourceMappingURL=index.mjs.map diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/web/index.mjs.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/web/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..1f6d0d69fb87de5cadc18bd2641567d7f7e03c9f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/web/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sources":["../../src/_base_url.ts","../../src/_common.ts","../../src/_base_transformers.ts","../../src/types.ts","../../src/_transformers.ts","../../src/converters/_batches_converters.ts","../../src/pagers.ts","../../src/batches.ts","../../src/converters/_caches_converters.ts","../../src/caches.ts","../../src/chats.ts","../../src/errors.ts","../../src/converters/_files_converters.ts","../../src/files.ts","../../src/converters/_live_converters.ts","../../src/converters/_models_converters.ts","../../src/_api_client.ts","../../src/mcp/_mcp.ts","../../src/music.ts","../../src/live.ts","../../src/_afc.ts","../../src/models.ts","../../src/converters/_operations_converters.ts","../../src/operations.ts","../../src/converters/_tokens_converters.ts","../../src/tokens.ts","../../src/converters/_tunings_converters.ts","../../src/tunings.ts","../../src/web/_browser_downloader.ts","../../src/cross/_cross_uploader.ts","../../src/web/_browser_uploader.ts","../../src/web/_browser_websocket.ts","../../src/web/_web_auth.ts","../../src/web/web_client.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {HttpOptions} from './types.js';\n\nlet _defaultBaseGeminiUrl: string | undefined = undefined;\nlet _defaultBaseVertexUrl: string | undefined = undefined;\n\n/**\n * Parameters for setting the base URLs for the Gemini API and Vertex AI API.\n */\nexport interface BaseUrlParameters {\n geminiUrl?: string;\n vertexUrl?: string;\n}\n\n/**\n * Overrides the base URLs for the Gemini API and Vertex AI API.\n *\n * @remarks This function should be called before initializing the SDK. If the\n * base URLs are set after initializing the SDK, the base URLs will not be\n * updated. Base URLs provided in the HttpOptions will also take precedence over\n * URLs set here.\n *\n * @example\n * ```ts\n * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai';\n * // Override the base URL for the Gemini API.\n * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'});\n *\n * // Override the base URL for the Vertex AI API.\n * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'});\n *\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n */\nexport function setDefaultBaseUrls(baseUrlParams: BaseUrlParameters) {\n _defaultBaseGeminiUrl = baseUrlParams.geminiUrl;\n _defaultBaseVertexUrl = baseUrlParams.vertexUrl;\n}\n\n/**\n * Returns the default base URLs for the Gemini API and Vertex AI API.\n */\nexport function getDefaultBaseUrls(): BaseUrlParameters {\n return {\n geminiUrl: _defaultBaseGeminiUrl,\n vertexUrl: _defaultBaseVertexUrl,\n };\n}\n\n/**\n * Returns the default base URL based on the following priority:\n * 1. Base URLs set via HttpOptions.\n * 2. Base URLs set via the latest call to setDefaultBaseUrls.\n * 3. Base URLs set via environment variables.\n */\nexport function getBaseUrl(\n httpOptions: HttpOptions | undefined,\n vertexai: boolean | undefined,\n vertexBaseUrlFromEnv: string | undefined,\n geminiBaseUrlFromEnv: string | undefined,\n): string | undefined {\n if (!httpOptions?.baseUrl) {\n const defaultBaseUrls = getDefaultBaseUrls();\n if (vertexai) {\n return defaultBaseUrls.vertexUrl ?? vertexBaseUrlFromEnv;\n } else {\n return defaultBaseUrls.geminiUrl ?? geminiBaseUrlFromEnv;\n }\n }\n\n return httpOptions.baseUrl;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport class BaseModule {}\n\nexport function formatMap(\n templateString: string,\n valueMap: Record,\n): string {\n // Use a regular expression to find all placeholders in the template string\n const regex = /\\{([^}]+)\\}/g;\n\n // Replace each placeholder with its corresponding value from the valueMap\n return templateString.replace(regex, (match, key) => {\n if (Object.prototype.hasOwnProperty.call(valueMap, key)) {\n const value = valueMap[key];\n // Convert the value to a string if it's not a string already\n return value !== undefined && value !== null ? String(value) : '';\n } else {\n // Handle missing keys\n throw new Error(`Key '${key}' not found in valueMap.`);\n }\n });\n}\n\nexport function setValueByPath(\n data: Record,\n keys: string[],\n value: unknown,\n): void {\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (!(keyName in data)) {\n if (Array.isArray(value)) {\n data[keyName] = Array.from({length: value.length}, () => ({}));\n } else {\n throw new Error(`Value must be a list given an array path ${key}`);\n }\n }\n\n if (Array.isArray(data[keyName])) {\n const arrayData = data[keyName] as Array;\n\n if (Array.isArray(value)) {\n for (let j = 0; j < arrayData.length; j++) {\n const entry = arrayData[j] as Record;\n setValueByPath(entry, keys.slice(i + 1), value[j]);\n }\n } else {\n for (const d of arrayData) {\n setValueByPath(\n d as Record,\n keys.slice(i + 1),\n value,\n );\n }\n }\n }\n return;\n } else if (key.endsWith('[0]')) {\n const keyName = key.slice(0, -3);\n if (!(keyName in data)) {\n data[keyName] = [{}];\n }\n const arrayData = (data as Record)[keyName];\n setValueByPath(\n (arrayData as Array>)[0],\n keys.slice(i + 1),\n value,\n );\n return;\n }\n\n if (!data[key] || typeof data[key] !== 'object') {\n data[key] = {};\n }\n\n data = data[key] as Record;\n }\n\n const keyToSet = keys[keys.length - 1];\n const existingData = data[keyToSet];\n\n if (existingData !== undefined) {\n if (\n !value ||\n (typeof value === 'object' && Object.keys(value).length === 0)\n ) {\n return;\n }\n\n if (value === existingData) {\n return;\n }\n\n if (\n typeof existingData === 'object' &&\n typeof value === 'object' &&\n existingData !== null &&\n value !== null\n ) {\n Object.assign(existingData, value);\n } else {\n throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`);\n }\n } else {\n data[keyToSet] = value;\n }\n}\n\nexport function getValueByPath(data: unknown, keys: string[]): unknown {\n try {\n if (keys.length === 1 && keys[0] === '_self') {\n return data;\n }\n\n for (let i = 0; i < keys.length; i++) {\n if (typeof data !== 'object' || data === null) {\n return undefined;\n }\n\n const key = keys[i];\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (keyName in data) {\n const arrayData = (data as Record)[keyName];\n if (!Array.isArray(arrayData)) {\n return undefined;\n }\n return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1)));\n } else {\n return undefined;\n }\n } else {\n data = (data as Record)[key];\n }\n }\n\n return data;\n } catch (error) {\n if (error instanceof TypeError) {\n return undefined;\n }\n throw error;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function tBytes(fromBytes: string | unknown): string {\n if (typeof fromBytes !== 'string') {\n throw new Error('fromImageBytes must be a string');\n }\n // TODO(b/389133914): Remove dummy bytes converter.\n return fromBytes;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {tBytes} from './_base_transformers.js';\nimport type {ReferenceImageAPIInternal} from './_internal_types.js';\n\n/** Required. Outcome of the code execution. */\nexport enum Outcome {\n /**\n * Unspecified status. This value should not be used.\n */\n OUTCOME_UNSPECIFIED = 'OUTCOME_UNSPECIFIED',\n /**\n * Code execution completed successfully.\n */\n OUTCOME_OK = 'OUTCOME_OK',\n /**\n * Code execution finished but with a failure. `stderr` should contain the reason.\n */\n OUTCOME_FAILED = 'OUTCOME_FAILED',\n /**\n * Code execution ran for too long, and was cancelled. There may or may not be a partial output present.\n */\n OUTCOME_DEADLINE_EXCEEDED = 'OUTCOME_DEADLINE_EXCEEDED',\n}\n\n/** Required. Programming language of the `code`. */\nexport enum Language {\n /**\n * Unspecified language. This value should not be used.\n */\n LANGUAGE_UNSPECIFIED = 'LANGUAGE_UNSPECIFIED',\n /**\n * Python >= 3.10, with numpy and simpy available.\n */\n PYTHON = 'PYTHON',\n}\n\n/** Optional. The type of the data. */\nexport enum Type {\n /**\n * Not specified, should not be used.\n */\n TYPE_UNSPECIFIED = 'TYPE_UNSPECIFIED',\n /**\n * OpenAPI string type\n */\n STRING = 'STRING',\n /**\n * OpenAPI number type\n */\n NUMBER = 'NUMBER',\n /**\n * OpenAPI integer type\n */\n INTEGER = 'INTEGER',\n /**\n * OpenAPI boolean type\n */\n BOOLEAN = 'BOOLEAN',\n /**\n * OpenAPI array type\n */\n ARRAY = 'ARRAY',\n /**\n * OpenAPI object type\n */\n OBJECT = 'OBJECT',\n /**\n * Null type\n */\n NULL = 'NULL',\n}\n\n/** Required. Harm category. */\nexport enum HarmCategory {\n /**\n * The harm category is unspecified.\n */\n HARM_CATEGORY_UNSPECIFIED = 'HARM_CATEGORY_UNSPECIFIED',\n /**\n * The harm category is hate speech.\n */\n HARM_CATEGORY_HATE_SPEECH = 'HARM_CATEGORY_HATE_SPEECH',\n /**\n * The harm category is dangerous content.\n */\n HARM_CATEGORY_DANGEROUS_CONTENT = 'HARM_CATEGORY_DANGEROUS_CONTENT',\n /**\n * The harm category is harassment.\n */\n HARM_CATEGORY_HARASSMENT = 'HARM_CATEGORY_HARASSMENT',\n /**\n * The harm category is sexually explicit content.\n */\n HARM_CATEGORY_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_SEXUALLY_EXPLICIT',\n /**\n * Deprecated: Election filter is not longer supported. The harm category is civic integrity.\n */\n HARM_CATEGORY_CIVIC_INTEGRITY = 'HARM_CATEGORY_CIVIC_INTEGRITY',\n /**\n * The harm category is image hate.\n */\n HARM_CATEGORY_IMAGE_HATE = 'HARM_CATEGORY_IMAGE_HATE',\n /**\n * The harm category is image dangerous content.\n */\n HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT = 'HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT',\n /**\n * The harm category is image harassment.\n */\n HARM_CATEGORY_IMAGE_HARASSMENT = 'HARM_CATEGORY_IMAGE_HARASSMENT',\n /**\n * The harm category is image sexually explicit content.\n */\n HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT',\n}\n\n/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */\nexport enum HarmBlockMethod {\n /**\n * The harm block method is unspecified.\n */\n HARM_BLOCK_METHOD_UNSPECIFIED = 'HARM_BLOCK_METHOD_UNSPECIFIED',\n /**\n * The harm block method uses both probability and severity scores.\n */\n SEVERITY = 'SEVERITY',\n /**\n * The harm block method uses the probability score.\n */\n PROBABILITY = 'PROBABILITY',\n}\n\n/** Required. The harm block threshold. */\nexport enum HarmBlockThreshold {\n /**\n * Unspecified harm block threshold.\n */\n HARM_BLOCK_THRESHOLD_UNSPECIFIED = 'HARM_BLOCK_THRESHOLD_UNSPECIFIED',\n /**\n * Block low threshold and above (i.e. block more).\n */\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n /**\n * Block medium threshold and above.\n */\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n /**\n * Block only high threshold (i.e. block less).\n */\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n /**\n * Block none.\n */\n BLOCK_NONE = 'BLOCK_NONE',\n /**\n * Turn off the safety filter.\n */\n OFF = 'OFF',\n}\n\n/** The mode of the predictor to be used in dynamic retrieval. */\nexport enum Mode {\n /**\n * Always trigger retrieval.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Run retrieval only when system decides it is necessary.\n */\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\n/** Type of auth scheme. */\nexport enum AuthType {\n AUTH_TYPE_UNSPECIFIED = 'AUTH_TYPE_UNSPECIFIED',\n /**\n * No Auth.\n */\n NO_AUTH = 'NO_AUTH',\n /**\n * API Key Auth.\n */\n API_KEY_AUTH = 'API_KEY_AUTH',\n /**\n * HTTP Basic Auth.\n */\n HTTP_BASIC_AUTH = 'HTTP_BASIC_AUTH',\n /**\n * Google Service Account Auth.\n */\n GOOGLE_SERVICE_ACCOUNT_AUTH = 'GOOGLE_SERVICE_ACCOUNT_AUTH',\n /**\n * OAuth auth.\n */\n OAUTH = 'OAUTH',\n /**\n * OpenID Connect (OIDC) Auth.\n */\n OIDC_AUTH = 'OIDC_AUTH',\n}\n\n/** The API spec that the external API implements. */\nexport enum ApiSpec {\n /**\n * Unspecified API spec. This value should not be used.\n */\n API_SPEC_UNSPECIFIED = 'API_SPEC_UNSPECIFIED',\n /**\n * Simple search API spec.\n */\n SIMPLE_SEARCH = 'SIMPLE_SEARCH',\n /**\n * Elastic search API spec.\n */\n ELASTIC_SEARCH = 'ELASTIC_SEARCH',\n}\n\n/** Status of the url retrieval. */\nexport enum UrlRetrievalStatus {\n /**\n * Default value. This value is unused\n */\n URL_RETRIEVAL_STATUS_UNSPECIFIED = 'URL_RETRIEVAL_STATUS_UNSPECIFIED',\n /**\n * Url retrieval is successful.\n */\n URL_RETRIEVAL_STATUS_SUCCESS = 'URL_RETRIEVAL_STATUS_SUCCESS',\n /**\n * Url retrieval is failed due to error.\n */\n URL_RETRIEVAL_STATUS_ERROR = 'URL_RETRIEVAL_STATUS_ERROR',\n /**\n * Url retrieval is failed because the content is behind paywall.\n */\n URL_RETRIEVAL_STATUS_PAYWALL = 'URL_RETRIEVAL_STATUS_PAYWALL',\n /**\n * Url retrieval is failed because the content is unsafe.\n */\n URL_RETRIEVAL_STATUS_UNSAFE = 'URL_RETRIEVAL_STATUS_UNSAFE',\n}\n\n/** Output only. The reason why the model stopped generating tokens.\n\n If empty, the model has not stopped generating the tokens.\n */\nexport enum FinishReason {\n /**\n * The finish reason is unspecified.\n */\n FINISH_REASON_UNSPECIFIED = 'FINISH_REASON_UNSPECIFIED',\n /**\n * Token generation reached a natural stopping point or a configured stop sequence.\n */\n STOP = 'STOP',\n /**\n * Token generation reached the configured maximum output tokens.\n */\n MAX_TOKENS = 'MAX_TOKENS',\n /**\n * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output.\n */\n SAFETY = 'SAFETY',\n /**\n * The token generation stopped because of potential recitation.\n */\n RECITATION = 'RECITATION',\n /**\n * The token generation stopped because of using an unsupported language.\n */\n LANGUAGE = 'LANGUAGE',\n /**\n * All other reasons that stopped the token generation.\n */\n OTHER = 'OTHER',\n /**\n * Token generation stopped because the content contains forbidden terms.\n */\n BLOCKLIST = 'BLOCKLIST',\n /**\n * Token generation stopped for potentially containing prohibited content.\n */\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n /**\n * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII).\n */\n SPII = 'SPII',\n /**\n * The function call generated by the model is invalid.\n */\n MALFORMED_FUNCTION_CALL = 'MALFORMED_FUNCTION_CALL',\n /**\n * Token generation stopped because generated images have safety violations.\n */\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n /**\n * The tool call generated by the model is invalid.\n */\n UNEXPECTED_TOOL_CALL = 'UNEXPECTED_TOOL_CALL',\n}\n\n/** Output only. Harm probability levels in the content. */\nexport enum HarmProbability {\n /**\n * Harm probability unspecified.\n */\n HARM_PROBABILITY_UNSPECIFIED = 'HARM_PROBABILITY_UNSPECIFIED',\n /**\n * Negligible level of harm.\n */\n NEGLIGIBLE = 'NEGLIGIBLE',\n /**\n * Low level of harm.\n */\n LOW = 'LOW',\n /**\n * Medium level of harm.\n */\n MEDIUM = 'MEDIUM',\n /**\n * High level of harm.\n */\n HIGH = 'HIGH',\n}\n\n/** Output only. Harm severity levels in the content. */\nexport enum HarmSeverity {\n /**\n * Harm severity unspecified.\n */\n HARM_SEVERITY_UNSPECIFIED = 'HARM_SEVERITY_UNSPECIFIED',\n /**\n * Negligible level of harm severity.\n */\n HARM_SEVERITY_NEGLIGIBLE = 'HARM_SEVERITY_NEGLIGIBLE',\n /**\n * Low level of harm severity.\n */\n HARM_SEVERITY_LOW = 'HARM_SEVERITY_LOW',\n /**\n * Medium level of harm severity.\n */\n HARM_SEVERITY_MEDIUM = 'HARM_SEVERITY_MEDIUM',\n /**\n * High level of harm severity.\n */\n HARM_SEVERITY_HIGH = 'HARM_SEVERITY_HIGH',\n}\n\n/** Output only. Blocked reason. */\nexport enum BlockedReason {\n /**\n * Unspecified blocked reason.\n */\n BLOCKED_REASON_UNSPECIFIED = 'BLOCKED_REASON_UNSPECIFIED',\n /**\n * Candidates blocked due to safety.\n */\n SAFETY = 'SAFETY',\n /**\n * Candidates blocked due to other reason.\n */\n OTHER = 'OTHER',\n /**\n * Candidates blocked due to the terms which are included from the terminology blocklist.\n */\n BLOCKLIST = 'BLOCKLIST',\n /**\n * Candidates blocked due to prohibited content.\n */\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n /**\n * Candidates blocked due to unsafe image generation content.\n */\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n}\n\n/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */\nexport enum TrafficType {\n /**\n * Unspecified request traffic type.\n */\n TRAFFIC_TYPE_UNSPECIFIED = 'TRAFFIC_TYPE_UNSPECIFIED',\n /**\n * Type for Pay-As-You-Go traffic.\n */\n ON_DEMAND = 'ON_DEMAND',\n /**\n * Type for Provisioned Throughput traffic.\n */\n PROVISIONED_THROUGHPUT = 'PROVISIONED_THROUGHPUT',\n}\n\n/** Server content modalities. */\nexport enum Modality {\n /**\n * The modality is unspecified.\n */\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n /**\n * Indicates the model should return text\n */\n TEXT = 'TEXT',\n /**\n * Indicates the model should return images.\n */\n IMAGE = 'IMAGE',\n /**\n * Indicates the model should return audio.\n */\n AUDIO = 'AUDIO',\n}\n\n/** The media resolution to use. */\nexport enum MediaResolution {\n /**\n * Media resolution has not been set\n */\n MEDIA_RESOLUTION_UNSPECIFIED = 'MEDIA_RESOLUTION_UNSPECIFIED',\n /**\n * Media resolution set to low (64 tokens).\n */\n MEDIA_RESOLUTION_LOW = 'MEDIA_RESOLUTION_LOW',\n /**\n * Media resolution set to medium (256 tokens).\n */\n MEDIA_RESOLUTION_MEDIUM = 'MEDIA_RESOLUTION_MEDIUM',\n /**\n * Media resolution set to high (zoomed reframing with 256 tokens).\n */\n MEDIA_RESOLUTION_HIGH = 'MEDIA_RESOLUTION_HIGH',\n}\n\n/** Job state. */\nexport enum JobState {\n /**\n * The job state is unspecified.\n */\n JOB_STATE_UNSPECIFIED = 'JOB_STATE_UNSPECIFIED',\n /**\n * The job has been just created or resumed and processing has not yet begun.\n */\n JOB_STATE_QUEUED = 'JOB_STATE_QUEUED',\n /**\n * The service is preparing to run the job.\n */\n JOB_STATE_PENDING = 'JOB_STATE_PENDING',\n /**\n * The job is in progress.\n */\n JOB_STATE_RUNNING = 'JOB_STATE_RUNNING',\n /**\n * The job completed successfully.\n */\n JOB_STATE_SUCCEEDED = 'JOB_STATE_SUCCEEDED',\n /**\n * The job failed.\n */\n JOB_STATE_FAILED = 'JOB_STATE_FAILED',\n /**\n * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`.\n */\n JOB_STATE_CANCELLING = 'JOB_STATE_CANCELLING',\n /**\n * The job has been cancelled.\n */\n JOB_STATE_CANCELLED = 'JOB_STATE_CANCELLED',\n /**\n * The job has been stopped, and can be resumed.\n */\n JOB_STATE_PAUSED = 'JOB_STATE_PAUSED',\n /**\n * The job has expired.\n */\n JOB_STATE_EXPIRED = 'JOB_STATE_EXPIRED',\n /**\n * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state.\n */\n JOB_STATE_UPDATING = 'JOB_STATE_UPDATING',\n /**\n * The job is partially succeeded, some results may be missing due to errors.\n */\n JOB_STATE_PARTIALLY_SUCCEEDED = 'JOB_STATE_PARTIALLY_SUCCEEDED',\n}\n\n/** Tuning mode. */\nexport enum TuningMode {\n /**\n * Tuning mode is unspecified.\n */\n TUNING_MODE_UNSPECIFIED = 'TUNING_MODE_UNSPECIFIED',\n /**\n * Full fine-tuning mode.\n */\n TUNING_MODE_FULL = 'TUNING_MODE_FULL',\n /**\n * PEFT adapter tuning mode.\n */\n TUNING_MODE_PEFT_ADAPTER = 'TUNING_MODE_PEFT_ADAPTER',\n}\n\n/** Optional. Adapter size for tuning. */\nexport enum AdapterSize {\n /**\n * Adapter size is unspecified.\n */\n ADAPTER_SIZE_UNSPECIFIED = 'ADAPTER_SIZE_UNSPECIFIED',\n /**\n * Adapter size 1.\n */\n ADAPTER_SIZE_ONE = 'ADAPTER_SIZE_ONE',\n /**\n * Adapter size 2.\n */\n ADAPTER_SIZE_TWO = 'ADAPTER_SIZE_TWO',\n /**\n * Adapter size 4.\n */\n ADAPTER_SIZE_FOUR = 'ADAPTER_SIZE_FOUR',\n /**\n * Adapter size 8.\n */\n ADAPTER_SIZE_EIGHT = 'ADAPTER_SIZE_EIGHT',\n /**\n * Adapter size 16.\n */\n ADAPTER_SIZE_SIXTEEN = 'ADAPTER_SIZE_SIXTEEN',\n /**\n * Adapter size 32.\n */\n ADAPTER_SIZE_THIRTY_TWO = 'ADAPTER_SIZE_THIRTY_TWO',\n}\n\n/** Options for feature selection preference. */\nexport enum FeatureSelectionPreference {\n FEATURE_SELECTION_PREFERENCE_UNSPECIFIED = 'FEATURE_SELECTION_PREFERENCE_UNSPECIFIED',\n PRIORITIZE_QUALITY = 'PRIORITIZE_QUALITY',\n BALANCED = 'BALANCED',\n PRIORITIZE_COST = 'PRIORITIZE_COST',\n}\n\n/** Defines the function behavior. Defaults to `BLOCKING`. */\nexport enum Behavior {\n /**\n * This value is unused.\n */\n UNSPECIFIED = 'UNSPECIFIED',\n /**\n * If set, the system will wait to receive the function response before continuing the conversation.\n */\n BLOCKING = 'BLOCKING',\n /**\n * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model.\n */\n NON_BLOCKING = 'NON_BLOCKING',\n}\n\n/** Config for the dynamic retrieval config mode. */\nexport enum DynamicRetrievalConfigMode {\n /**\n * Always trigger retrieval.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Run retrieval only when system decides it is necessary.\n */\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\n/** The environment being operated. */\nexport enum Environment {\n /**\n * Defaults to browser.\n */\n ENVIRONMENT_UNSPECIFIED = 'ENVIRONMENT_UNSPECIFIED',\n /**\n * Operates in a web browser.\n */\n ENVIRONMENT_BROWSER = 'ENVIRONMENT_BROWSER',\n}\n\n/** Config for the function calling config mode. */\nexport enum FunctionCallingConfigMode {\n /**\n * The function calling config mode is unspecified. Should not be used.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Default model behavior, model decides to predict either function calls or natural language response.\n */\n AUTO = 'AUTO',\n /**\n * Model is constrained to always predicting function calls only. If \"allowed_function_names\" are set, the predicted function calls will be limited to any one of \"allowed_function_names\", else the predicted function calls will be any one of the provided \"function_declarations\".\n */\n ANY = 'ANY',\n /**\n * Model will not predict any function calls. Model behavior is same as when not passing any function declarations.\n */\n NONE = 'NONE',\n}\n\n/** Enum that controls the safety filter level for objectionable content. */\nexport enum SafetyFilterLevel {\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n BLOCK_NONE = 'BLOCK_NONE',\n}\n\n/** Enum that controls the generation of people. */\nexport enum PersonGeneration {\n /**\n * Block generation of images of people.\n */\n DONT_ALLOW = 'DONT_ALLOW',\n /**\n * Generate images of adults, but not children.\n */\n ALLOW_ADULT = 'ALLOW_ADULT',\n /**\n * Generate images that include adults and children.\n */\n ALLOW_ALL = 'ALLOW_ALL',\n}\n\n/** Enum that specifies the language of the text in the prompt. */\nexport enum ImagePromptLanguage {\n /**\n * Auto-detect the language.\n */\n auto = 'auto',\n /**\n * English\n */\n en = 'en',\n /**\n * Japanese\n */\n ja = 'ja',\n /**\n * Korean\n */\n ko = 'ko',\n /**\n * Hindi\n */\n hi = 'hi',\n /**\n * Chinese\n */\n zh = 'zh',\n /**\n * Portuguese\n */\n pt = 'pt',\n /**\n * Spanish\n */\n es = 'es',\n}\n\n/** Enum representing the mask mode of a mask reference image. */\nexport enum MaskReferenceMode {\n MASK_MODE_DEFAULT = 'MASK_MODE_DEFAULT',\n MASK_MODE_USER_PROVIDED = 'MASK_MODE_USER_PROVIDED',\n MASK_MODE_BACKGROUND = 'MASK_MODE_BACKGROUND',\n MASK_MODE_FOREGROUND = 'MASK_MODE_FOREGROUND',\n MASK_MODE_SEMANTIC = 'MASK_MODE_SEMANTIC',\n}\n\n/** Enum representing the control type of a control reference image. */\nexport enum ControlReferenceType {\n CONTROL_TYPE_DEFAULT = 'CONTROL_TYPE_DEFAULT',\n CONTROL_TYPE_CANNY = 'CONTROL_TYPE_CANNY',\n CONTROL_TYPE_SCRIBBLE = 'CONTROL_TYPE_SCRIBBLE',\n CONTROL_TYPE_FACE_MESH = 'CONTROL_TYPE_FACE_MESH',\n}\n\n/** Enum representing the subject type of a subject reference image. */\nexport enum SubjectReferenceType {\n SUBJECT_TYPE_DEFAULT = 'SUBJECT_TYPE_DEFAULT',\n SUBJECT_TYPE_PERSON = 'SUBJECT_TYPE_PERSON',\n SUBJECT_TYPE_ANIMAL = 'SUBJECT_TYPE_ANIMAL',\n SUBJECT_TYPE_PRODUCT = 'SUBJECT_TYPE_PRODUCT',\n}\n\n/** Enum representing the Imagen 3 Edit mode. */\nexport enum EditMode {\n EDIT_MODE_DEFAULT = 'EDIT_MODE_DEFAULT',\n EDIT_MODE_INPAINT_REMOVAL = 'EDIT_MODE_INPAINT_REMOVAL',\n EDIT_MODE_INPAINT_INSERTION = 'EDIT_MODE_INPAINT_INSERTION',\n EDIT_MODE_OUTPAINT = 'EDIT_MODE_OUTPAINT',\n EDIT_MODE_CONTROLLED_EDITING = 'EDIT_MODE_CONTROLLED_EDITING',\n EDIT_MODE_STYLE = 'EDIT_MODE_STYLE',\n EDIT_MODE_BGSWAP = 'EDIT_MODE_BGSWAP',\n EDIT_MODE_PRODUCT_IMAGE = 'EDIT_MODE_PRODUCT_IMAGE',\n}\n\n/** Enum that represents the segmentation mode. */\nexport enum SegmentMode {\n FOREGROUND = 'FOREGROUND',\n BACKGROUND = 'BACKGROUND',\n PROMPT = 'PROMPT',\n SEMANTIC = 'SEMANTIC',\n INTERACTIVE = 'INTERACTIVE',\n}\n\n/** Enum that controls the compression quality of the generated videos. */\nexport enum VideoCompressionQuality {\n /**\n * Optimized video compression quality. This will produce videos\n with a compressed, smaller file size.\n */\n OPTIMIZED = 'OPTIMIZED',\n /**\n * Lossless video compression quality. This will produce videos\n with a larger file size.\n */\n LOSSLESS = 'LOSSLESS',\n}\n\n/** State for the lifecycle of a File. */\nexport enum FileState {\n STATE_UNSPECIFIED = 'STATE_UNSPECIFIED',\n PROCESSING = 'PROCESSING',\n ACTIVE = 'ACTIVE',\n FAILED = 'FAILED',\n}\n\n/** Source of the File. */\nexport enum FileSource {\n SOURCE_UNSPECIFIED = 'SOURCE_UNSPECIFIED',\n UPLOADED = 'UPLOADED',\n GENERATED = 'GENERATED',\n}\n\n/** Server content modalities. */\nexport enum MediaModality {\n /**\n * The modality is unspecified.\n */\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n /**\n * Plain text.\n */\n TEXT = 'TEXT',\n /**\n * Images.\n */\n IMAGE = 'IMAGE',\n /**\n * Video.\n */\n VIDEO = 'VIDEO',\n /**\n * Audio.\n */\n AUDIO = 'AUDIO',\n /**\n * Document, e.g. PDF.\n */\n DOCUMENT = 'DOCUMENT',\n}\n\n/** Start of speech sensitivity. */\nexport enum StartSensitivity {\n /**\n * The default is START_SENSITIVITY_LOW.\n */\n START_SENSITIVITY_UNSPECIFIED = 'START_SENSITIVITY_UNSPECIFIED',\n /**\n * Automatic detection will detect the start of speech more often.\n */\n START_SENSITIVITY_HIGH = 'START_SENSITIVITY_HIGH',\n /**\n * Automatic detection will detect the start of speech less often.\n */\n START_SENSITIVITY_LOW = 'START_SENSITIVITY_LOW',\n}\n\n/** End of speech sensitivity. */\nexport enum EndSensitivity {\n /**\n * The default is END_SENSITIVITY_LOW.\n */\n END_SENSITIVITY_UNSPECIFIED = 'END_SENSITIVITY_UNSPECIFIED',\n /**\n * Automatic detection ends speech more often.\n */\n END_SENSITIVITY_HIGH = 'END_SENSITIVITY_HIGH',\n /**\n * Automatic detection ends speech less often.\n */\n END_SENSITIVITY_LOW = 'END_SENSITIVITY_LOW',\n}\n\n/** The different ways of handling user activity. */\nexport enum ActivityHandling {\n /**\n * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`.\n */\n ACTIVITY_HANDLING_UNSPECIFIED = 'ACTIVITY_HANDLING_UNSPECIFIED',\n /**\n * If true, start of activity will interrupt the model's response (also called \"barge in\"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior.\n */\n START_OF_ACTIVITY_INTERRUPTS = 'START_OF_ACTIVITY_INTERRUPTS',\n /**\n * The model's response will not be interrupted.\n */\n NO_INTERRUPTION = 'NO_INTERRUPTION',\n}\n\n/** Options about which input is included in the user's turn. */\nexport enum TurnCoverage {\n /**\n * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`.\n */\n TURN_COVERAGE_UNSPECIFIED = 'TURN_COVERAGE_UNSPECIFIED',\n /**\n * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior.\n */\n TURN_INCLUDES_ONLY_ACTIVITY = 'TURN_INCLUDES_ONLY_ACTIVITY',\n /**\n * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream).\n */\n TURN_INCLUDES_ALL_INPUT = 'TURN_INCLUDES_ALL_INPUT',\n}\n\n/** Specifies how the response should be scheduled in the conversation. */\nexport enum FunctionResponseScheduling {\n /**\n * This value is unused.\n */\n SCHEDULING_UNSPECIFIED = 'SCHEDULING_UNSPECIFIED',\n /**\n * Only add the result to the conversation context, do not interrupt or trigger generation.\n */\n SILENT = 'SILENT',\n /**\n * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation.\n */\n WHEN_IDLE = 'WHEN_IDLE',\n /**\n * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output.\n */\n INTERRUPT = 'INTERRUPT',\n}\n\n/** Scale of the generated music. */\nexport enum Scale {\n /**\n * Default value. This value is unused.\n */\n SCALE_UNSPECIFIED = 'SCALE_UNSPECIFIED',\n /**\n * C major or A minor.\n */\n C_MAJOR_A_MINOR = 'C_MAJOR_A_MINOR',\n /**\n * Db major or Bb minor.\n */\n D_FLAT_MAJOR_B_FLAT_MINOR = 'D_FLAT_MAJOR_B_FLAT_MINOR',\n /**\n * D major or B minor.\n */\n D_MAJOR_B_MINOR = 'D_MAJOR_B_MINOR',\n /**\n * Eb major or C minor\n */\n E_FLAT_MAJOR_C_MINOR = 'E_FLAT_MAJOR_C_MINOR',\n /**\n * E major or Db minor.\n */\n E_MAJOR_D_FLAT_MINOR = 'E_MAJOR_D_FLAT_MINOR',\n /**\n * F major or D minor.\n */\n F_MAJOR_D_MINOR = 'F_MAJOR_D_MINOR',\n /**\n * Gb major or Eb minor.\n */\n G_FLAT_MAJOR_E_FLAT_MINOR = 'G_FLAT_MAJOR_E_FLAT_MINOR',\n /**\n * G major or E minor.\n */\n G_MAJOR_E_MINOR = 'G_MAJOR_E_MINOR',\n /**\n * Ab major or F minor.\n */\n A_FLAT_MAJOR_F_MINOR = 'A_FLAT_MAJOR_F_MINOR',\n /**\n * A major or Gb minor.\n */\n A_MAJOR_G_FLAT_MINOR = 'A_MAJOR_G_FLAT_MINOR',\n /**\n * Bb major or G minor.\n */\n B_FLAT_MAJOR_G_MINOR = 'B_FLAT_MAJOR_G_MINOR',\n /**\n * B major or Ab minor.\n */\n B_MAJOR_A_FLAT_MINOR = 'B_MAJOR_A_FLAT_MINOR',\n}\n\n/** The mode of music generation. */\nexport enum MusicGenerationMode {\n /**\n * Rely on the server default generation mode.\n */\n MUSIC_GENERATION_MODE_UNSPECIFIED = 'MUSIC_GENERATION_MODE_UNSPECIFIED',\n /**\n * Steer text prompts to regions of latent space with higher quality\n music.\n */\n QUALITY = 'QUALITY',\n /**\n * Steer text prompts to regions of latent space with a larger\n diversity of music.\n */\n DIVERSITY = 'DIVERSITY',\n /**\n * Steer text prompts to regions of latent space more likely to\n generate music with vocals.\n */\n VOCALIZATION = 'VOCALIZATION',\n}\n\n/** The playback control signal to apply to the music generation. */\nexport enum LiveMusicPlaybackControl {\n /**\n * This value is unused.\n */\n PLAYBACK_CONTROL_UNSPECIFIED = 'PLAYBACK_CONTROL_UNSPECIFIED',\n /**\n * Start generating the music.\n */\n PLAY = 'PLAY',\n /**\n * Hold the music generation. Use PLAY to resume from the current position.\n */\n PAUSE = 'PAUSE',\n /**\n * Stop the music generation and reset the context (prompts retained).\n Use PLAY to restart the music generation.\n */\n STOP = 'STOP',\n /**\n * Reset the context of the music generation without stopping it.\n Retains the current prompts and config.\n */\n RESET_CONTEXT = 'RESET_CONTEXT',\n}\n\n/** Describes how the video in the Part should be used by the model. */\nexport declare interface VideoMetadata {\n /** The frame rate of the video sent to the model. If not specified, the\n default value will be 1.0. The fps range is (0.0, 24.0]. */\n fps?: number;\n /** Optional. The end offset of the video. */\n endOffset?: string;\n /** Optional. The start offset of the video. */\n startOffset?: string;\n}\n\n/** Content blob. */\nexport declare interface Blob {\n /** Optional. Display name of the blob. Used to provide a label or filename to distinguish blobs. This field is not currently used in the Gemini GenerateContent calls. */\n displayName?: string;\n /** Required. Raw bytes.\n * @remarks Encoded as base64 string. */\n data?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** URI based data. */\nexport declare interface FileData {\n /** Optional. Display name of the file data. Used to provide a label or filename to distinguish file datas. It is not currently used in the Gemini GenerateContent calls. */\n displayName?: string;\n /** Required. URI. */\n fileUri?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** Result of executing the [ExecutableCode]. Only generated when using the [CodeExecution] tool, and always follows a `part` containing the [ExecutableCode]. */\nexport declare interface CodeExecutionResult {\n /** Required. Outcome of the code execution. */\n outcome?: Outcome;\n /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */\n output?: string;\n}\n\n/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [CodeExecution] tool, in which the code will be automatically executed, and a corresponding [CodeExecutionResult] will also be generated. */\nexport declare interface ExecutableCode {\n /** Required. The code to be executed. */\n code?: string;\n /** Required. Programming language of the `code`. */\n language?: Language;\n}\n\n/** A function call. */\nexport declare interface FunctionCall {\n /** The unique id of the function call. If populated, the client to execute the\n `function_call` and return the response with the matching `id`. */\n id?: string;\n /** Optional. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */\n args?: Record;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */\n name?: string;\n}\n\n/** A function response. */\nexport class FunctionResponse {\n /** Signals that function call continues, and more responses will be returned, turning the function call into a generator. Is only applicable to NON_BLOCKING function calls (see FunctionDeclaration.behavior for details), ignored otherwise. If false, the default, future responses will not be considered. Is only applicable to NON_BLOCKING function calls, is ignored otherwise. If set to false, future responses will not be considered. It is allowed to return empty `response` with `will_continue=False` to signal that the function call is finished. */\n willContinue?: boolean;\n /** Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. */\n scheduling?: FunctionResponseScheduling;\n /** Optional. The id of the function call this response is for. Populated by the client to match the corresponding function call `id`. */\n id?: string;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */\n name?: string;\n /** Required. The function response in JSON object format. Use \"output\" key to specify function output and \"error\" key to specify error details (if any). If \"output\" and \"error\" keys are not specified, then whole \"response\" is treated as function output. */\n response?: Record;\n}\n\n/** A datatype containing media content.\n\n Exactly one field within a Part should be set, representing the specific type\n of content being conveyed. Using multiple fields within the same `Part`\n instance is considered invalid.\n */\nexport declare interface Part {\n /** Metadata for a given video. */\n videoMetadata?: VideoMetadata;\n /** Indicates if the part is thought from the model. */\n thought?: boolean;\n /** Optional. Inlined bytes data. */\n inlineData?: Blob;\n /** Optional. URI based data. */\n fileData?: FileData;\n /** An opaque signature for the thought so it can be reused in subsequent requests.\n * @remarks Encoded as base64 string. */\n thoughtSignature?: string;\n /** Optional. Result of executing the [ExecutableCode]. */\n codeExecutionResult?: CodeExecutionResult;\n /** Optional. Code generated by the model that is meant to be executed. */\n executableCode?: ExecutableCode;\n /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */\n functionCall?: FunctionCall;\n /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */\n functionResponse?: FunctionResponse;\n /** Optional. Text part (can be code). */\n text?: string;\n}\n/**\n * Creates a `Part` object from a `URI` string.\n */\nexport function createPartFromUri(uri: string, mimeType: string): Part {\n return {\n fileData: {\n fileUri: uri,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from a `text` string.\n */\nexport function createPartFromText(text: string): Part {\n return {\n text: text,\n };\n}\n/**\n * Creates a `Part` object from a `FunctionCall` object.\n */\nexport function createPartFromFunctionCall(\n name: string,\n args: Record,\n): Part {\n return {\n functionCall: {\n name: name,\n args: args,\n },\n };\n}\n/**\n * Creates a `Part` object from a `FunctionResponse` object.\n */\nexport function createPartFromFunctionResponse(\n id: string,\n name: string,\n response: Record,\n): Part {\n return {\n functionResponse: {\n id: id,\n name: name,\n response: response,\n },\n };\n}\n/**\n * Creates a `Part` object from a `base64` encoded `string`.\n */\nexport function createPartFromBase64(data: string, mimeType: string): Part {\n return {\n inlineData: {\n data: data,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object.\n */\nexport function createPartFromCodeExecutionResult(\n outcome: Outcome,\n output: string,\n): Part {\n return {\n codeExecutionResult: {\n outcome: outcome,\n output: output,\n },\n };\n}\n/**\n * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object.\n */\nexport function createPartFromExecutableCode(\n code: string,\n language: Language,\n): Part {\n return {\n executableCode: {\n code: code,\n language: language,\n },\n };\n}\n\n/** Contains the multi-part content of a message. */\nexport declare interface Content {\n /** List of parts that constitute a single message. Each part may have\n a different IANA MIME type. */\n parts?: Part[];\n /** Optional. The producer of the content. Must be either 'user' or\n 'model'. Useful to set for multi-turn conversations, otherwise can be\n empty. If role is not specified, SDK will determine the role. */\n role?: string;\n}\nfunction _isPart(obj: unknown): obj is Part {\n if (typeof obj === 'object' && obj !== null) {\n return (\n 'fileData' in obj ||\n 'text' in obj ||\n 'functionCall' in obj ||\n 'functionResponse' in obj ||\n 'inlineData' in obj ||\n 'videoMetadata' in obj ||\n 'codeExecutionResult' in obj ||\n 'executableCode' in obj\n );\n }\n return false;\n}\nfunction _toParts(partOrString: PartListUnion | string): Part[] {\n const parts: Part[] = [];\n if (typeof partOrString === 'string') {\n parts.push(createPartFromText(partOrString));\n } else if (_isPart(partOrString)) {\n parts.push(partOrString);\n } else if (Array.isArray(partOrString)) {\n if (partOrString.length === 0) {\n throw new Error('partOrString cannot be an empty array');\n }\n for (const part of partOrString) {\n if (typeof part === 'string') {\n parts.push(createPartFromText(part));\n } else if (_isPart(part)) {\n parts.push(part);\n } else {\n throw new Error('element in PartUnion must be a Part object or string');\n }\n }\n } else {\n throw new Error('partOrString must be a Part object, string, or array');\n }\n return parts;\n}\n/**\n * Creates a `Content` object with a user role from a `PartListUnion` object or `string`.\n */\nexport function createUserContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'user',\n parts: _toParts(partOrString),\n };\n}\n\n/**\n * Creates a `Content` object with a model role from a `PartListUnion` object or `string`.\n */\nexport function createModelContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'model',\n parts: _toParts(partOrString),\n };\n}\n/** HTTP options to be used in each of the requests. */\nexport declare interface HttpOptions {\n /** The base URL for the AI platform service endpoint. */\n baseUrl?: string;\n /** Specifies the version of the API to use. */\n apiVersion?: string;\n /** Additional HTTP headers to be sent with the request. */\n headers?: Record;\n /** Timeout for the request in milliseconds. */\n timeout?: number;\n /** Extra parameters to add to the request body.\n The structure must match the backend API's request structure.\n - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest\n - GeminiAPI backend API docs: https://ai.google.dev/api/rest */\n extraBody?: Record;\n}\n\n/** Schema is used to define the format of input/output data.\n\n Represents a select subset of an [OpenAPI 3.0 schema\n object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may\n be added in the future as needed.\n */\nexport declare interface Schema {\n /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */\n anyOf?: Schema[];\n /** Optional. Default value of the data. */\n default?: unknown;\n /** Optional. The description of the data. */\n description?: string;\n /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:[\"EAST\", NORTH\", \"SOUTH\", \"WEST\"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:[\"101\", \"201\", \"301\"]} */\n enum?: string[];\n /** Optional. Example of the object. Will only populated when the object is the root. */\n example?: unknown;\n /** Optional. The format of the data. Supported formats: for NUMBER type: \"float\", \"double\" for INTEGER type: \"int32\", \"int64\" for STRING type: \"email\", \"byte\", etc */\n format?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */\n items?: Schema;\n /** Optional. Maximum number of the elements for Type.ARRAY. */\n maxItems?: string;\n /** Optional. Maximum length of the Type.STRING */\n maxLength?: string;\n /** Optional. Maximum number of the properties for Type.OBJECT. */\n maxProperties?: string;\n /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */\n maximum?: number;\n /** Optional. Minimum number of the elements for Type.ARRAY. */\n minItems?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */\n minLength?: string;\n /** Optional. Minimum number of the properties for Type.OBJECT. */\n minProperties?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */\n minimum?: number;\n /** Optional. Indicates if the value may be null. */\n nullable?: boolean;\n /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */\n pattern?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */\n properties?: Record;\n /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */\n propertyOrdering?: string[];\n /** Optional. Required properties of Type.OBJECT. */\n required?: string[];\n /** Optional. The title of the Schema. */\n title?: string;\n /** Optional. The type of the data. */\n type?: Type;\n}\n\n/** Config for model selection. */\nexport declare interface ModelSelectionConfig {\n /** Options for feature selection preference. */\n featureSelectionPreference?: FeatureSelectionPreference;\n}\n\n/** Safety settings. */\nexport declare interface SafetySetting {\n /** Determines if the harm block method uses probability or probability\n and severity scores. */\n method?: HarmBlockMethod;\n /** Required. Harm category. */\n category?: HarmCategory;\n /** Required. The harm block threshold. */\n threshold?: HarmBlockThreshold;\n}\n\n/** Defines a function that the model can generate JSON inputs for.\n\n The inputs are based on `OpenAPI 3.0 specifications\n `_.\n */\nexport declare interface FunctionDeclaration {\n /** Defines the function behavior. */\n behavior?: Behavior;\n /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */\n description?: string;\n /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */\n name?: string;\n /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */\n parameters?: Schema;\n /** Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" }, \"age\": { \"type\": \"integer\" } }, \"additionalProperties\": false, \"required\": [\"name\", \"age\"], \"propertyOrdering\": [\"name\", \"age\"] } ``` This field is mutually exclusive with `parameters`. */\n parametersJsonSchema?: unknown;\n /** Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function. */\n response?: Schema;\n /** Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`. */\n responseJsonSchema?: unknown;\n}\n\n/** Represents a time interval, encoded as a start time (inclusive) and an end time (exclusive).\n\n The start time must be less than or equal to the end time.\n When the start equals the end time, the interval is an empty interval.\n (matches no time)\n When both start and end are unspecified, the interval matches any time.\n */\nexport declare interface Interval {\n /** The start time of the interval. */\n startTime?: string;\n /** The end time of the interval. */\n endTime?: string;\n}\n\n/** Tool to support Google Search in Model. Powered by Google. */\nexport declare interface GoogleSearch {\n /** Optional. Filter search results to a specific time range.\n If customers set a start time, they must set an end time (and vice versa).\n */\n timeRangeFilter?: Interval;\n /** Optional. List of domains to be excluded from the search results.\n The default limit is 2000 domains. */\n excludeDomains?: string[];\n}\n\n/** Describes the options to customize dynamic retrieval. */\nexport declare interface DynamicRetrievalConfig {\n /** The mode of the predictor to be used in dynamic retrieval. */\n mode?: DynamicRetrievalConfigMode;\n /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */\n dynamicThreshold?: number;\n}\n\n/** Tool to retrieve public web data for grounding, powered by Google. */\nexport declare interface GoogleSearchRetrieval {\n /** Specifies the dynamic retrieval configuration for the given source. */\n dynamicRetrievalConfig?: DynamicRetrievalConfig;\n}\n\n/** Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. */\nexport declare interface EnterpriseWebSearch {\n /** Optional. List of domains to be excluded from the search results. The default limit is 2000 domains. */\n excludeDomains?: string[];\n}\n\n/** Config for authentication with API key. */\nexport declare interface ApiKeyConfig {\n /** The API key to be used in the request directly. */\n apiKeyString?: string;\n}\n\n/** Config for Google Service Account Authentication. */\nexport declare interface AuthConfigGoogleServiceAccountConfig {\n /** Optional. The service account that the extension execution service runs as. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified service account. - If not specified, the Vertex AI Extension Service Agent will be used to execute the Extension. */\n serviceAccount?: string;\n}\n\n/** Config for HTTP Basic Authentication. */\nexport declare interface AuthConfigHttpBasicAuthConfig {\n /** Required. The name of the SecretManager secret version resource storing the base64 encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource. */\n credentialSecret?: string;\n}\n\n/** Config for user oauth. */\nexport declare interface AuthConfigOauthConfig {\n /** Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */\n accessToken?: string;\n /** The service account used to generate access tokens for executing the Extension. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the provided service account. */\n serviceAccount?: string;\n}\n\n/** Config for user OIDC auth. */\nexport declare interface AuthConfigOidcConfig {\n /** OpenID Connect formatted ID token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */\n idToken?: string;\n /** The service account used to generate an OpenID Connect (OIDC)-compatible JWT token signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc). - The audience for the token will be set to the URL in the server url defined in the OpenApi spec. - If the service account is provided, the service account should grant `iam.serviceAccounts.getOpenIdToken` permission to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents). */\n serviceAccount?: string;\n}\n\n/** Auth configuration to run the extension. */\nexport declare interface AuthConfig {\n /** Config for API key auth. */\n apiKeyConfig?: ApiKeyConfig;\n /** Type of auth scheme. */\n authType?: AuthType;\n /** Config for Google Service Account auth. */\n googleServiceAccountConfig?: AuthConfigGoogleServiceAccountConfig;\n /** Config for HTTP Basic auth. */\n httpBasicAuthConfig?: AuthConfigHttpBasicAuthConfig;\n /** Config for user oauth. */\n oauthConfig?: AuthConfigOauthConfig;\n /** Config for user OIDC auth. */\n oidcConfig?: AuthConfigOidcConfig;\n}\n\n/** Tool to support Google Maps in Model. */\nexport declare interface GoogleMaps {\n /** Optional. Auth config for the Google Maps tool. */\n authConfig?: AuthConfig;\n}\n\n/** Tool to support URL context retrieval. */\nexport declare interface UrlContext {}\n\n/** Tool to support computer use. */\nexport declare interface ToolComputerUse {\n /** Required. The environment being operated. */\n environment?: Environment;\n}\n\n/** The API secret. */\nexport declare interface ApiAuthApiKeyConfig {\n /** Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version} */\n apiKeySecretVersion?: string;\n /** The API key string. Either this or `api_key_secret_version` must be set. */\n apiKeyString?: string;\n}\n\n/** The generic reusable api auth config. Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto) instead. */\nexport declare interface ApiAuth {\n /** The API secret. */\n apiKeyConfig?: ApiAuthApiKeyConfig;\n}\n\n/** The search parameters to use for the ELASTIC_SEARCH spec. */\nexport declare interface ExternalApiElasticSearchParams {\n /** The ElasticSearch index to use. */\n index?: string;\n /** Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as the `num_hits` param. */\n numHits?: number;\n /** The ElasticSearch search template to use. */\n searchTemplate?: string;\n}\n\n/** The search parameters to use for SIMPLE_SEARCH spec. */\nexport declare interface ExternalApiSimpleSearchParams {}\n\n/** Retrieve from data source powered by external API for grounding. The external API is not owned by Google, but need to follow the pre-defined API spec. */\nexport declare interface ExternalApi {\n /** The authentication config to access the API. Deprecated. Please use auth_config instead. */\n apiAuth?: ApiAuth;\n /** The API spec that the external API implements. */\n apiSpec?: ApiSpec;\n /** The authentication config to access the API. */\n authConfig?: AuthConfig;\n /** Parameters for the elastic search API. */\n elasticSearchParams?: ExternalApiElasticSearchParams;\n /** The endpoint of the external API. The system will call the API at this endpoint to retrieve the data for grounding. Example: https://acme.com:443/search */\n endpoint?: string;\n /** Parameters for the simple search API. */\n simpleSearchParams?: ExternalApiSimpleSearchParams;\n}\n\n/** Define data stores within engine to filter on in a search call and configurations for those data stores. For more information, see https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec */\nexport declare interface VertexAISearchDataStoreSpec {\n /** Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n dataStore?: string;\n /** Optional. Filter specification to filter documents in the data store specified by data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata) */\n filter?: string;\n}\n\n/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */\nexport declare interface VertexAISearch {\n /** Specifications that define the specific DataStores to be searched, along with configurations for those data stores. This is only considered for Engines with multiple data stores. It should only be set if engine is used. */\n dataStoreSpecs?: VertexAISearchDataStoreSpec[];\n /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n datastore?: string;\n /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */\n engine?: string;\n /** Optional. Filter strings to be passed to the search API. */\n filter?: string;\n /** Optional. Number of search results to return per query. The default value is 10. The maximumm allowed value is 10. */\n maxResults?: number;\n}\n\n/** The definition of the Rag resource. */\nexport declare interface VertexRagStoreRagResource {\n /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */\n ragCorpus?: string;\n /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */\n ragFileIds?: string[];\n}\n\n/** Config for filters. */\nexport declare interface RagRetrievalConfigFilter {\n /** Optional. String for metadata filtering. */\n metadataFilter?: string;\n /** Optional. Only returns contexts with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n /** Optional. Only returns contexts with vector similarity larger than the threshold. */\n vectorSimilarityThreshold?: number;\n}\n\n/** Config for Hybrid Search. */\nexport declare interface RagRetrievalConfigHybridSearch {\n /** Optional. Alpha value controls the weight between dense and sparse vector search results. The range is [0, 1], while 0 means sparse vector search only and 1 means dense vector search only. The default value is 0.5 which balances sparse and dense vector search equally. */\n alpha?: number;\n}\n\n/** Config for LlmRanker. */\nexport declare interface RagRetrievalConfigRankingLlmRanker {\n /** Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */\n modelName?: string;\n}\n\n/** Config for Rank Service. */\nexport declare interface RagRetrievalConfigRankingRankService {\n /** Optional. The model name of the rank service. Format: `semantic-ranker-512@latest` */\n modelName?: string;\n}\n\n/** Config for ranking and reranking. */\nexport declare interface RagRetrievalConfigRanking {\n /** Optional. Config for LlmRanker. */\n llmRanker?: RagRetrievalConfigRankingLlmRanker;\n /** Optional. Config for Rank Service. */\n rankService?: RagRetrievalConfigRankingRankService;\n}\n\n/** Specifies the context retrieval config. */\nexport declare interface RagRetrievalConfig {\n /** Optional. Config for filters. */\n filter?: RagRetrievalConfigFilter;\n /** Optional. Config for Hybrid Search. */\n hybridSearch?: RagRetrievalConfigHybridSearch;\n /** Optional. Config for ranking and reranking. */\n ranking?: RagRetrievalConfigRanking;\n /** Optional. The number of contexts to retrieve. */\n topK?: number;\n}\n\n/** Retrieve from Vertex RAG Store for grounding. */\nexport declare interface VertexRagStore {\n /** Optional. Deprecated. Please use rag_resources instead. */\n ragCorpora?: string[];\n /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */\n ragResources?: VertexRagStoreRagResource[];\n /** Optional. The retrieval config for the Rag query. */\n ragRetrievalConfig?: RagRetrievalConfig;\n /** Optional. Number of top k results to return from the selected corpora. */\n similarityTopK?: number;\n /** Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal Live API, if `store_context` bool is specified, Gemini will leverage it to automatically memorize the interactions between the client and Gemini, and retrieve context when needed to augment the response generation for users' ongoing and future interactions. */\n storeContext?: boolean;\n /** Optional. Only return results with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n}\n\n/** Defines a retrieval tool that model can call to access external knowledge. */\nexport declare interface Retrieval {\n /** Optional. Deprecated. This option is no longer supported. */\n disableAttribution?: boolean;\n /** Use data source powered by external API for grounding. */\n externalApi?: ExternalApi;\n /** Set to use data source powered by Vertex AI Search. */\n vertexAiSearch?: VertexAISearch;\n /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */\n vertexRagStore?: VertexRagStore;\n}\n\n/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */\nexport declare interface ToolCodeExecution {}\n\n/** Tool details of a tool that the model may use to generate a response. */\nexport declare interface Tool {\n /** List of function declarations that the tool supports. */\n functionDeclarations?: FunctionDeclaration[];\n /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */\n retrieval?: Retrieval;\n /** Optional. Google Search tool type. Specialized retrieval tool\n that is powered by Google Search. */\n googleSearch?: GoogleSearch;\n /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */\n googleSearchRetrieval?: GoogleSearchRetrieval;\n /** Optional. Enterprise web search tool type. Specialized retrieval\n tool that is powered by Vertex AI Search and Sec4 compliance. */\n enterpriseWebSearch?: EnterpriseWebSearch;\n /** Optional. Google Maps tool type. Specialized retrieval tool\n that is powered by Google Maps. */\n googleMaps?: GoogleMaps;\n /** Optional. Tool to support URL context retrieval. */\n urlContext?: UrlContext;\n /** Optional. Tool to support the model interacting directly with the\n computer. If enabled, it automatically populates computer-use specific\n Function Declarations. */\n computerUse?: ToolComputerUse;\n /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. */\n codeExecution?: ToolCodeExecution;\n}\n\n/** Function calling config. */\nexport declare interface FunctionCallingConfig {\n /** Optional. Function calling mode. */\n mode?: FunctionCallingConfigMode;\n /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */\n allowedFunctionNames?: string[];\n}\n\n/** An object that represents a latitude/longitude pair.\n\n This is expressed as a pair of doubles to represent degrees latitude and\n degrees longitude. Unless specified otherwise, this object must conform to the\n \n WGS84 standard. Values must be within normalized ranges.\n */\nexport declare interface LatLng {\n /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */\n latitude?: number;\n /** The longitude in degrees. It must be in the range [-180.0, +180.0] */\n longitude?: number;\n}\n\n/** Retrieval config.\n */\nexport declare interface RetrievalConfig {\n /** Optional. The location of the user. */\n latLng?: LatLng;\n /** The language code of the user. */\n languageCode?: string;\n}\n\n/** Tool config.\n\n This config is shared for all tools provided in the request.\n */\nexport declare interface ToolConfig {\n /** Optional. Function calling config. */\n functionCallingConfig?: FunctionCallingConfig;\n /** Optional. Retrieval config. */\n retrievalConfig?: RetrievalConfig;\n}\n\n/** The configuration for the prebuilt speaker to use. */\nexport declare interface PrebuiltVoiceConfig {\n /** The name of the prebuilt voice to use. */\n voiceName?: string;\n}\n\n/** The configuration for the voice to use. */\nexport declare interface VoiceConfig {\n /** The configuration for the speaker to use.\n */\n prebuiltVoiceConfig?: PrebuiltVoiceConfig;\n}\n\n/** The configuration for the speaker to use. */\nexport declare interface SpeakerVoiceConfig {\n /** The name of the speaker to use. Should be the same as in the\n prompt. */\n speaker?: string;\n /** The configuration for the voice to use. */\n voiceConfig?: VoiceConfig;\n}\n\n/** The configuration for the multi-speaker setup. */\nexport declare interface MultiSpeakerVoiceConfig {\n /** The configuration for the speaker to use. */\n speakerVoiceConfigs?: SpeakerVoiceConfig[];\n}\n\n/** The speech generation configuration. */\nexport declare interface SpeechConfig {\n /** The configuration for the speaker to use.\n */\n voiceConfig?: VoiceConfig;\n /** The configuration for the multi-speaker setup.\n It is mutually exclusive with the voice_config field.\n */\n multiSpeakerVoiceConfig?: MultiSpeakerVoiceConfig;\n /** Language code (ISO 639. e.g. en-US) for the speech synthesization.\n Only available for Live API.\n */\n languageCode?: string;\n}\n\n/** The configuration for automatic function calling. */\nexport declare interface AutomaticFunctionCallingConfig {\n /** Whether to disable automatic function calling.\n If not set or set to False, will enable automatic function calling.\n If set to True, will disable automatic function calling.\n */\n disable?: boolean;\n /** If automatic function calling is enabled,\n maximum number of remote calls for automatic function calling.\n This number should be a positive integer.\n If not set, SDK will set maximum number of remote calls to 10.\n */\n maximumRemoteCalls?: number;\n /** If automatic function calling is enabled,\n whether to ignore call history to the response.\n If not set, SDK will set ignore_call_history to false,\n and will append the call history to\n GenerateContentResponse.automatic_function_calling_history.\n */\n ignoreCallHistory?: boolean;\n}\n\n/** The thinking features configuration. */\nexport declare interface ThinkingConfig {\n /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available.\n */\n includeThoughts?: boolean;\n /** Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent.\n */\n thinkingBudget?: number;\n}\n\n/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */\nexport declare interface GenerationConfigRoutingConfigAutoRoutingMode {\n /** The model routing preference. */\n modelRoutingPreference?:\n | 'UNKNOWN'\n | 'PRIORITIZE_QUALITY'\n | 'BALANCED'\n | 'PRIORITIZE_COST';\n}\n\n/** When manual routing is set, the specified model will be used directly. */\nexport declare interface GenerationConfigRoutingConfigManualRoutingMode {\n /** The model name to use. Only the public LLM models are accepted. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */\n modelName?: string;\n}\n\n/** The configuration for routing the request to a specific model. */\nexport declare interface GenerationConfigRoutingConfig {\n /** Automated routing. */\n autoMode?: GenerationConfigRoutingConfigAutoRoutingMode;\n /** Manual routing. */\n manualMode?: GenerationConfigRoutingConfigManualRoutingMode;\n}\n\n/** Optional model configuration parameters.\n\n For more information, see `Content generation parameters\n `_.\n */\nexport declare interface GenerateContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Instructions for the model to steer it toward better performance.\n For example, \"Answer as concisely as possible\" or \"Don't use technical\n terms in your response\".\n */\n systemInstruction?: ContentUnion;\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Number of response variations to return.\n */\n candidateCount?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** List of strings that tells the model to stop generating text if one\n of the strings is encountered in the response.\n */\n stopSequences?: string[];\n /** Whether to return the log probabilities of the tokens that were\n chosen by the model at each step.\n */\n responseLogprobs?: boolean;\n /** Number of top candidate tokens to return the log probabilities for\n at each generation step.\n */\n logprobs?: number;\n /** Positive values penalize tokens that already appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n presencePenalty?: number;\n /** Positive values penalize tokens that repeatedly appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n frequencyPenalty?: number;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** Output response mimetype of the generated candidate text.\n Supported mimetype:\n - `text/plain`: (default) Text output.\n - `application/json`: JSON response in the candidates.\n The model needs to be prompted to output the appropriate response type,\n otherwise the behavior is undefined.\n This is a preview feature.\n */\n responseMimeType?: string;\n /** The `Schema` object allows the definition of input and output data types.\n These types can be objects, but also primitives and arrays.\n Represents a select subset of an [OpenAPI 3.0 schema\n object](https://spec.openapis.org/oas/v3.0.3#schema).\n If set, a compatible response_mime_type must also be set.\n Compatible mimetypes: `application/json`: Schema for JSON response.\n */\n responseSchema?: SchemaUnion;\n /** Optional. Output schema of the generated response.\n This is an alternative to `response_schema` that accepts [JSON\n Schema](https://json-schema.org/). If set, `response_schema` must be\n omitted, but `response_mime_type` is required. While the full JSON Schema\n may be sent, not all features are supported. Specifically, only the\n following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor`\n - `type` - `format` - `title` - `description` - `enum` (for strings and\n numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` -\n `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) -\n `properties` - `additionalProperties` - `required` The non-standard\n `propertyOrdering` property may also be set. Cyclic references are\n unrolled to a limited degree and, as such, may only be used within\n non-required properties. (Nullable properties are not sufficient.) If\n `$ref` is set on a sub-schema, no other properties, except for than those\n starting as a `$`, may be set. */\n responseJsonSchema?: unknown;\n /** Configuration for model router requests.\n */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Configuration for model selection.\n */\n modelSelectionConfig?: ModelSelectionConfig;\n /** Safety settings in the request to block unsafe content in the\n response.\n */\n safetySettings?: SafetySetting[];\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: ToolListUnion;\n /** Associates model output to a specific function call.\n */\n toolConfig?: ToolConfig;\n /** Labels with user-defined metadata to break down billed charges. */\n labels?: Record;\n /** Resource name of a context cache that can be used in subsequent\n requests.\n */\n cachedContent?: string;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return.\n */\n responseModalities?: string[];\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfigUnion;\n /** If enabled, audio timestamp will be included in the request to the\n model.\n */\n audioTimestamp?: boolean;\n /** The configuration for automatic function calling.\n */\n automaticFunctionCalling?: AutomaticFunctionCallingConfig;\n /** The thinking features configuration.\n */\n thinkingConfig?: ThinkingConfig;\n}\n\n/** Config for models.generate_content parameters. */\nexport declare interface GenerateContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Content of the request.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** A wrapper class for the http response. */\nexport class HttpResponse {\n /** Used to retain the processed HTTP headers in the response. */\n headers?: Record;\n /**\n * The original http response.\n */\n responseInternal: Response;\n\n constructor(response: Response) {\n // Process the headers.\n const headers: Record = {};\n for (const pair of response.headers.entries()) {\n headers[pair[0]] = pair[1];\n }\n this.headers = headers;\n\n // Keep the original response.\n this.responseInternal = response;\n }\n\n json(): Promise {\n return this.responseInternal.json();\n }\n}\n\n/** Callbacks for the live API. */\nexport interface LiveCallbacks {\n /**\n * Called when the websocket connection is established.\n */\n onopen?: (() => void) | null;\n /**\n * Called when a message is received from the server.\n */\n onmessage: (e: LiveServerMessage) => void;\n /**\n * Called when an error occurs.\n */\n onerror?: ((e: ErrorEvent) => void) | null;\n /**\n * Called when the websocket connection is closed.\n */\n onclose?: ((e: CloseEvent) => void) | null;\n}\n\n/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */\nexport declare interface GoogleTypeDate {\n /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */\n day?: number;\n /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */\n month?: number;\n /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */\n year?: number;\n}\n\n/** Source attributions for content. */\nexport declare interface Citation {\n /** Output only. End index into the content. */\n endIndex?: number;\n /** Output only. License of the attribution. */\n license?: string;\n /** Output only. Publication date of the attribution. */\n publicationDate?: GoogleTypeDate;\n /** Output only. Start index into the content. */\n startIndex?: number;\n /** Output only. Title of the attribution. */\n title?: string;\n /** Output only. Url reference of the attribution. */\n uri?: string;\n}\n\n/** Citation information when the model quotes another source. */\nexport declare interface CitationMetadata {\n /** Contains citation information when the model directly quotes, at\n length, from another source. Can include traditional websites and code\n repositories.\n */\n citations?: Citation[];\n}\n\n/** Context for a single url retrieval. */\nexport declare interface UrlMetadata {\n /** The URL retrieved by the tool. */\n retrievedUrl?: string;\n /** Status of the url retrieval. */\n urlRetrievalStatus?: UrlRetrievalStatus;\n}\n\n/** Metadata related to url context retrieval tool. */\nexport declare interface UrlContextMetadata {\n /** List of url context. */\n urlMetadata?: UrlMetadata[];\n}\n\n/** Author attribution for a photo or review. */\nexport declare interface GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution {\n /** Name of the author of the Photo or Review. */\n displayName?: string;\n /** Profile photo URI of the author of the Photo or Review. */\n photoUri?: string;\n /** URI of the author of the Photo or Review. */\n uri?: string;\n}\n\n/** Encapsulates a review snippet. */\nexport declare interface GroundingChunkMapsPlaceAnswerSourcesReviewSnippet {\n /** This review's author. */\n authorAttribution?: GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution;\n /** A link where users can flag a problem with the review. */\n flagContentUri?: string;\n /** A link to show the review on Google Maps. */\n googleMapsUri?: string;\n /** A string of formatted recent time, expressing the review time relative to the current time in a form appropriate for the language and country. */\n relativePublishTimeDescription?: string;\n /** A reference representing this place review which may be used to look up this place review again. */\n review?: string;\n}\n\n/** Sources used to generate the place answer. */\nexport declare interface GroundingChunkMapsPlaceAnswerSources {\n /** A link where users can flag a problem with the generated answer. */\n flagContentUri?: string;\n /** Snippets of reviews that are used to generate the answer. */\n reviewSnippets?: GroundingChunkMapsPlaceAnswerSourcesReviewSnippet[];\n}\n\n/** Chunk from Google Maps. */\nexport declare interface GroundingChunkMaps {\n /** Sources used to generate the place answer. This includes review snippets and photos that were used to generate the answer, as well as uris to flag content. */\n placeAnswerSources?: GroundingChunkMapsPlaceAnswerSources;\n /** This Place's resource name, in `places/{place_id}` format. Can be used to look up the Place. */\n placeId?: string;\n /** Text of the chunk. */\n text?: string;\n /** Title of the chunk. */\n title?: string;\n /** URI reference of the chunk. */\n uri?: string;\n}\n\n/** Represents where the chunk starts and ends in the document. */\nexport declare interface RagChunkPageSpan {\n /** Page where chunk starts in the document. Inclusive. 1-indexed. */\n firstPage?: number;\n /** Page where chunk ends in the document. Inclusive. 1-indexed. */\n lastPage?: number;\n}\n\n/** A RagChunk includes the content of a chunk of a RagFile, and associated metadata. */\nexport declare interface RagChunk {\n /** If populated, represents where the chunk starts and ends in the document. */\n pageSpan?: RagChunkPageSpan;\n /** The content of the chunk. */\n text?: string;\n}\n\n/** Chunk from context retrieved by the retrieval tools. */\nexport declare interface GroundingChunkRetrievedContext {\n /** Output only. The full document name for the referenced Vertex AI Search document. */\n documentName?: string;\n /** Additional context for the RAG retrieval result. This is only populated when using the RAG retrieval tool. */\n ragChunk?: RagChunk;\n /** Text of the attribution. */\n text?: string;\n /** Title of the attribution. */\n title?: string;\n /** URI reference of the attribution. */\n uri?: string;\n}\n\n/** Chunk from the web. */\nexport declare interface GroundingChunkWeb {\n /** Domain of the (original) URI. */\n domain?: string;\n /** Title of the chunk. */\n title?: string;\n /** URI reference of the chunk. */\n uri?: string;\n}\n\n/** Grounding chunk. */\nexport declare interface GroundingChunk {\n /** Grounding chunk from Google Maps. */\n maps?: GroundingChunkMaps;\n /** Grounding chunk from context retrieved by the retrieval tools. */\n retrievedContext?: GroundingChunkRetrievedContext;\n /** Grounding chunk from the web. */\n web?: GroundingChunkWeb;\n}\n\n/** Segment of the content. */\nexport declare interface Segment {\n /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */\n endIndex?: number;\n /** Output only. The index of a Part object within its parent Content object. */\n partIndex?: number;\n /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */\n startIndex?: number;\n /** Output only. The text corresponding to the segment from the response. */\n text?: string;\n}\n\n/** Grounding support. */\nexport declare interface GroundingSupport {\n /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. For Gemini 2.0 and before, this list must have the same size as the grounding_chunk_indices. For Gemini 2.5 and after, this list will be empty and should be ignored. */\n confidenceScores?: number[];\n /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */\n groundingChunkIndices?: number[];\n /** Segment of the content this support belongs to. */\n segment?: Segment;\n}\n\n/** Metadata related to retrieval in the grounding flow. */\nexport declare interface RetrievalMetadata {\n /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */\n googleSearchDynamicRetrievalScore?: number;\n}\n\n/** Google search entry point. */\nexport declare interface SearchEntryPoint {\n /** Optional. Web content snippet that can be embedded in a web page or an app webview. */\n renderedContent?: string;\n /** Optional. Base64 encoded JSON representing array of tuple.\n * @remarks Encoded as base64 string. */\n sdkBlob?: string;\n}\n\n/** Metadata returned to client when grounding is enabled. */\nexport declare interface GroundingMetadata {\n /** Optional. Output only. Resource name of the Google Maps widget context token to be used with the PlacesContextElement widget to render contextual data. This is populated only for Google Maps grounding. */\n googleMapsWidgetContextToken?: string;\n /** List of supporting references retrieved from specified grounding source. */\n groundingChunks?: GroundingChunk[];\n /** Optional. List of grounding support. */\n groundingSupports?: GroundingSupport[];\n /** Optional. Output only. Retrieval metadata. */\n retrievalMetadata?: RetrievalMetadata;\n /** Optional. Queries executed by the retrieval tools. */\n retrievalQueries?: string[];\n /** Optional. Google search entry for the following-up web searches. */\n searchEntryPoint?: SearchEntryPoint;\n /** Optional. Web search queries for the following-up web search. */\n webSearchQueries?: string[];\n}\n\n/** Candidate for the logprobs token and score. */\nexport declare interface LogprobsResultCandidate {\n /** The candidate's log probability. */\n logProbability?: number;\n /** The candidate's token string value. */\n token?: string;\n /** The candidate's token id value. */\n tokenId?: number;\n}\n\n/** Candidates with top log probabilities at each decoding step. */\nexport declare interface LogprobsResultTopCandidates {\n /** Sorted by log probability in descending order. */\n candidates?: LogprobsResultCandidate[];\n}\n\n/** Logprobs Result */\nexport declare interface LogprobsResult {\n /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */\n chosenCandidates?: LogprobsResultCandidate[];\n /** Length = total number of decoding steps. */\n topCandidates?: LogprobsResultTopCandidates[];\n}\n\n/** Safety rating corresponding to the generated content. */\nexport declare interface SafetyRating {\n /** Output only. Indicates whether the content was filtered out because of this rating. */\n blocked?: boolean;\n /** Output only. Harm category. */\n category?: HarmCategory;\n /** Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If minors are detected in the output image, the threshold of each safety category will be overwritten if user sets a lower threshold. */\n overwrittenThreshold?: HarmBlockThreshold;\n /** Output only. Harm probability levels in the content. */\n probability?: HarmProbability;\n /** Output only. Harm probability score. */\n probabilityScore?: number;\n /** Output only. Harm severity levels in the content. */\n severity?: HarmSeverity;\n /** Output only. Harm severity score. */\n severityScore?: number;\n}\n\n/** A response candidate generated from the model. */\nexport declare interface Candidate {\n /** Contains the multi-part content of the response.\n */\n content?: Content;\n /** Source attribution of the generated content.\n */\n citationMetadata?: CitationMetadata;\n /** Describes the reason the model stopped generating tokens.\n */\n finishMessage?: string;\n /** Number of tokens for this candidate.\n */\n tokenCount?: number;\n /** The reason why the model stopped generating tokens.\n If empty, the model has not stopped generating the tokens.\n */\n finishReason?: FinishReason;\n /** Metadata related to url context retrieval tool. */\n urlContextMetadata?: UrlContextMetadata;\n /** Output only. Average log probability score of the candidate. */\n avgLogprobs?: number;\n /** Output only. Metadata specifies sources used to ground generated content. */\n groundingMetadata?: GroundingMetadata;\n /** Output only. Index of the candidate. */\n index?: number;\n /** Output only. Log-likelihood scores for the response tokens and top tokens */\n logprobsResult?: LogprobsResult;\n /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Content filter results for a prompt sent in the request. */\nexport class GenerateContentResponsePromptFeedback {\n /** Output only. Blocked reason. */\n blockReason?: BlockedReason;\n /** Output only. A readable block reason message. */\n blockReasonMessage?: string;\n /** Output only. Safety ratings. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Represents token counting info for a single modality. */\nexport declare interface ModalityTokenCount {\n /** The modality associated with this token count. */\n modality?: MediaModality;\n /** Number of tokens. */\n tokenCount?: number;\n}\n\n/** Usage metadata about response(s). */\nexport class GenerateContentResponseUsageMetadata {\n /** Output only. List of modalities of the cached content in the request input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens in the cached part in the input (the cached content). */\n cachedContentTokenCount?: number;\n /** Number of tokens in the response(s). */\n candidatesTokenCount?: number;\n /** Output only. List of modalities that were returned in the response. */\n candidatesTokensDetails?: ModalityTokenCount[];\n /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Output only. List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens present in thoughts output. */\n thoughtsTokenCount?: number;\n /** Output only. Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Output only. List of modalities that were processed for tool-use request inputs. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Total token count for prompt, response candidates, and tool-use prompts (if present). */\n totalTokenCount?: number;\n /** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */\n trafficType?: TrafficType;\n}\n\n/** Response message for PredictionService.GenerateContent. */\nexport class GenerateContentResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Response variations returned by the model.\n */\n candidates?: Candidate[];\n /** Timestamp when the request is made to the server.\n */\n createTime?: string;\n /** The history of automatic function calling.\n */\n automaticFunctionCallingHistory?: Content[];\n /** Output only. The model version used to generate the response. */\n modelVersion?: string;\n /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */\n promptFeedback?: GenerateContentResponsePromptFeedback;\n /** Output only. response_id is used to identify each response. It is the encoding of the event_id. */\n responseId?: string;\n /** Usage metadata about the response(s). */\n usageMetadata?: GenerateContentResponseUsageMetadata;\n /**\n * Returns the concatenation of all text parts from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the text from the first\n * one will be returned.\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n * If there are thought parts in the response, the concatenation of all text\n * parts excluding the thought parts will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'Why is the sky blue?',\n * });\n *\n * console.debug(response.text);\n * ```\n */\n get text(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning text from the first one.',\n );\n }\n let text = '';\n let anyTextPartText = false;\n const nonTextParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartText = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartText ? text : undefined;\n }\n\n /**\n * Returns the concatenation of all inline data parts from the first candidate\n * in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the inline data from the\n * first one will be returned. If there are non-inline data parts in the\n * response, the concatenation of all inline data parts will be returned, and\n * a warning will be logged.\n */\n get data(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning data from the first one.',\n );\n }\n let data = '';\n const nonDataParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'inlineData' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonDataParts.push(fieldName);\n }\n }\n if (part.inlineData && typeof part.inlineData.data === 'string') {\n data += atob(part.inlineData.data);\n }\n }\n if (nonDataParts.length > 0) {\n console.warn(\n `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`,\n );\n }\n return data.length > 0 ? btoa(data) : undefined;\n }\n\n /**\n * Returns the function calls from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the function calls from\n * the first one will be returned.\n * If there are no function calls in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const controlLightFunctionDeclaration: FunctionDeclaration = {\n * name: 'controlLight',\n * parameters: {\n * type: Type.OBJECT,\n * description: 'Set the brightness and color temperature of a room light.',\n * properties: {\n * brightness: {\n * type: Type.NUMBER,\n * description:\n * 'Light level from 0 to 100. Zero is off and 100 is full brightness.',\n * },\n * colorTemperature: {\n * type: Type.STRING,\n * description:\n * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.',\n * },\n * },\n * required: ['brightness', 'colorTemperature'],\n * };\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'Dim the lights so the room feels cozy and warm.',\n * config: {\n * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}],\n * toolConfig: {\n * functionCallingConfig: {\n * mode: FunctionCallingConfigMode.ANY,\n * allowedFunctionNames: ['controlLight'],\n * },\n * },\n * },\n * });\n * console.debug(JSON.stringify(response.functionCalls));\n * ```\n */\n get functionCalls(): FunctionCall[] | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning function calls from the first one.',\n );\n }\n const functionCalls = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.functionCall)\n .map((part) => part.functionCall)\n .filter(\n (functionCall): functionCall is FunctionCall =>\n functionCall !== undefined,\n );\n if (functionCalls?.length === 0) {\n return undefined;\n }\n return functionCalls;\n }\n /**\n * Returns the first executable code from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the executable code from\n * the first one will be returned.\n * If there are no executable code in the response, undefined will be\n * returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.executableCode);\n * ```\n */\n get executableCode(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning executable code from the first one.',\n );\n }\n const executableCode = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.executableCode)\n .map((part) => part.executableCode)\n .filter(\n (executableCode): executableCode is ExecutableCode =>\n executableCode !== undefined,\n );\n if (executableCode?.length === 0) {\n return undefined;\n }\n\n return executableCode?.[0]?.code;\n }\n /**\n * Returns the first code execution result from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the code execution result from\n * the first one will be returned.\n * If there are no code execution result in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.codeExecutionResult);\n * ```\n */\n get codeExecutionResult(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning code execution result from the first one.',\n );\n }\n const codeExecutionResult = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.codeExecutionResult)\n .map((part) => part.codeExecutionResult)\n .filter(\n (codeExecutionResult): codeExecutionResult is CodeExecutionResult =>\n codeExecutionResult !== undefined,\n );\n if (codeExecutionResult?.length === 0) {\n return undefined;\n }\n return codeExecutionResult?.[0]?.output;\n }\n}\n\nexport type ReferenceImage =\n | RawReferenceImage\n | MaskReferenceImage\n | ControlReferenceImage\n | StyleReferenceImage\n | SubjectReferenceImage;\n\n/** Parameters for the request to edit an image. */\nexport declare interface EditImageParameters {\n /** The model to use. */\n model: string;\n /** A text description of the edit to apply to the image. */\n prompt: string;\n /** The reference images for Imagen 3 editing. */\n referenceImages: ReferenceImage[];\n /** Configuration for editing. */\n config?: EditImageConfig;\n}\n\n/** Optional parameters for the embed_content method. */\nexport declare interface EmbedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Type of task for which the embedding will be used.\n */\n taskType?: string;\n /** Title for the text. Only applicable when TaskType is\n `RETRIEVAL_DOCUMENT`.\n */\n title?: string;\n /** Reduced dimension for the output embedding. If set,\n excessive values in the output embedding are truncated from the end.\n Supported by newer models since 2024 only. You cannot set this value if\n using the earlier model (`models/embedding-001`).\n */\n outputDimensionality?: number;\n /** Vertex API only. The MIME type of the input.\n */\n mimeType?: string;\n /** Vertex API only. Whether to silently truncate inputs longer than\n the max sequence length. If this option is set to false, oversized inputs\n will lead to an INVALID_ARGUMENT error, similar to other text APIs.\n */\n autoTruncate?: boolean;\n}\n\n/** Parameters for the embed_content method. */\nexport declare interface EmbedContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The content to embed. Only the `parts.text` fields will be counted.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional parameters.\n */\n config?: EmbedContentConfig;\n}\n\n/** Statistics of the input text associated with the result of content embedding. */\nexport declare interface ContentEmbeddingStatistics {\n /** Vertex API only. If the input text was truncated due to having\n a length longer than the allowed maximum input.\n */\n truncated?: boolean;\n /** Vertex API only. Number of tokens of the input text.\n */\n tokenCount?: number;\n}\n\n/** The embedding generated from an input content. */\nexport declare interface ContentEmbedding {\n /** A list of floats representing an embedding.\n */\n values?: number[];\n /** Vertex API only. Statistics of the input text associated with this\n embedding.\n */\n statistics?: ContentEmbeddingStatistics;\n}\n\n/** Request-level metadata for the Vertex Embed Content API. */\nexport declare interface EmbedContentMetadata {\n /** Vertex API only. The total number of billable characters included\n in the request.\n */\n billableCharacterCount?: number;\n}\n\n/** Response for the embed_content method. */\nexport class EmbedContentResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** The embeddings for each request, in the same order as provided in\n the batch request.\n */\n embeddings?: ContentEmbedding[];\n /** Vertex API only. Metadata about the request.\n */\n metadata?: EmbedContentMetadata;\n}\n\n/** The config for generating an images. */\nexport declare interface GenerateImagesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage URI used to store the generated images.\n */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images.\n */\n negativePrompt?: string;\n /** Number of images to generate.\n */\n numberOfImages?: number;\n /** Aspect ratio of the generated images. Supported values are\n \"1:1\", \"3:4\", \"4:3\", \"9:16\", and \"16:9\".\n */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality.\n */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true.\n */\n seed?: number;\n /** Filter level for safety filtering.\n */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model.\n */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response.\n */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response.\n */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt.\n */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image.\n */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only).\n */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images.\n */\n addWatermark?: boolean;\n /** The size of the largest dimension of the generated image.\n Supported sizes are 1K and 2K (not supported for Imagen 3 models).\n */\n imageSize?: string;\n /** Whether to use the prompt rewriting logic.\n */\n enhancePrompt?: boolean;\n}\n\n/** The parameters for generating images. */\nexport declare interface GenerateImagesParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Text prompt that typically describes the images to output.\n */\n prompt: string;\n /** Configuration for generating images.\n */\n config?: GenerateImagesConfig;\n}\n\n/** An image. */\nexport declare interface Image {\n /** The Cloud Storage URI of the image. ``Image`` can contain a value\n for this field or the ``image_bytes`` field but not both.\n */\n gcsUri?: string;\n /** The image bytes data. ``Image`` can contain a value for this field\n or the ``gcs_uri`` field but not both.\n \n * @remarks Encoded as base64 string. */\n imageBytes?: string;\n /** The MIME type of the image. */\n mimeType?: string;\n}\n\n/** Safety attributes of a GeneratedImage or the user-provided prompt. */\nexport declare interface SafetyAttributes {\n /** List of RAI categories.\n */\n categories?: string[];\n /** List of scores of each categories.\n */\n scores?: number[];\n /** Internal use only.\n */\n contentType?: string;\n}\n\n/** An output image. */\nexport declare interface GeneratedImage {\n /** The output image data.\n */\n image?: Image;\n /** Responsible AI filter reason if the image is filtered out of the\n response.\n */\n raiFilteredReason?: string;\n /** Safety attributes of the image. Lists of RAI categories and their\n scores of each content.\n */\n safetyAttributes?: SafetyAttributes;\n /** The rewritten prompt used for the image generation if the prompt\n enhancer is enabled.\n */\n enhancedPrompt?: string;\n}\n\n/** The output images response. */\nexport class GenerateImagesResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** List of generated images.\n */\n generatedImages?: GeneratedImage[];\n /** Safety attributes of the positive prompt. Only populated if\n ``include_safety_attributes`` is set to True.\n */\n positivePromptSafetyAttributes?: SafetyAttributes;\n}\n\n/** Configuration for a Mask reference image. */\nexport declare interface MaskReferenceConfig {\n /** Prompts the model to generate a mask instead of you needing to\n provide one (unless MASK_MODE_USER_PROVIDED is used). */\n maskMode?: MaskReferenceMode;\n /** A list of up to 5 class ids to use for semantic segmentation.\n Automatically creates an image mask based on specific objects. */\n segmentationClasses?: number[];\n /** Dilation percentage of the mask provided.\n Float between 0 and 1. */\n maskDilation?: number;\n}\n\n/** Configuration for a Control reference image. */\nexport declare interface ControlReferenceConfig {\n /** The type of control reference image to use. */\n controlType?: ControlReferenceType;\n /** Defaults to False. When set to True, the control image will be\n computed by the model based on the control type. When set to False,\n the control image must be provided by the user. */\n enableControlImageComputation?: boolean;\n}\n\n/** Configuration for a Style reference image. */\nexport declare interface StyleReferenceConfig {\n /** A text description of the style to use for the generated image. */\n styleDescription?: string;\n}\n\n/** Configuration for a Subject reference image. */\nexport declare interface SubjectReferenceConfig {\n /** The subject type of a subject reference image. */\n subjectType?: SubjectReferenceType;\n /** Subject description for the image. */\n subjectDescription?: string;\n}\n\n/** Configuration for editing an image. */\nexport declare interface EditImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage URI used to store the generated images.\n */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images.\n */\n negativePrompt?: string;\n /** Number of images to generate.\n */\n numberOfImages?: number;\n /** Aspect ratio of the generated images. Supported values are\n \"1:1\", \"3:4\", \"4:3\", \"9:16\", and \"16:9\".\n */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality.\n */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true.\n */\n seed?: number;\n /** Filter level for safety filtering.\n */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model.\n */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response.\n */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response.\n */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt.\n */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image.\n */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only).\n */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images.\n */\n addWatermark?: boolean;\n /** Describes the editing mode for the request. */\n editMode?: EditMode;\n /** The number of sampling steps. A higher value has better image\n quality, while a lower value has better latency. */\n baseSteps?: number;\n}\n\n/** Response for the request to edit an image. */\nexport class EditImageResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Generated images. */\n generatedImages?: GeneratedImage[];\n}\n\nexport class UpscaleImageResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Generated images. */\n generatedImages?: GeneratedImage[];\n}\n\n/** An image of the product. */\nexport declare interface ProductImage {\n /** An image of the product to be recontextualized. */\n productImage?: Image;\n}\n\n/** A set of source input(s) for image recontextualization. */\nexport declare interface RecontextImageSource {\n /** A text prompt for guiding the model during image\n recontextualization. Not supported for Virtual Try-On. */\n prompt?: string;\n /** Image of the person or subject who will be wearing the\n product(s). */\n personImage?: Image;\n /** A list of product images. */\n productImages?: ProductImage[];\n}\n\n/** Configuration for recontextualizing an image. */\nexport declare interface RecontextImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Number of images to generate. */\n numberOfImages?: number;\n /** The number of sampling steps. A higher value has better image\n quality, while a lower value has better latency. */\n baseSteps?: number;\n /** Cloud Storage URI used to store the generated images. */\n outputGcsUri?: string;\n /** Random seed for image generation. */\n seed?: number;\n /** Filter level for safety filtering. */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Whether allow to generate person images, and restrict to specific\n ages. */\n personGeneration?: PersonGeneration;\n /** MIME type of the generated image. */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only). */\n outputCompressionQuality?: number;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n}\n\n/** The parameters for recontextualizing an image. */\nexport declare interface RecontextImageParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** A set of source input(s) for image recontextualization. */\n source: RecontextImageSource;\n /** Configuration for image recontextualization. */\n config?: RecontextImageConfig;\n}\n\n/** The output images response. */\nexport class RecontextImageResponse {\n /** List of generated images. */\n generatedImages?: GeneratedImage[];\n}\n\n/** An image mask representing a brush scribble. */\nexport declare interface ScribbleImage {\n /** The brush scribble to guide segmentation. Valid for the interactive mode. */\n image?: Image;\n}\n\n/** A set of source input(s) for image segmentation. */\nexport declare interface SegmentImageSource {\n /** A text prompt for guiding the model during image segmentation.\n Required for prompt mode and semantic mode, disallowed for other modes. */\n prompt?: string;\n /** The image to be segmented. */\n image?: Image;\n /** The brush scribble to guide segmentation.\n Required for the interactive mode, disallowed for other modes. */\n scribbleImage?: ScribbleImage;\n}\n\n/** Configuration for segmenting an image. */\nexport declare interface SegmentImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The segmentation mode to use. */\n mode?: SegmentMode;\n /** The maximum number of predictions to return up to, by top\n confidence score. */\n maxPredictions?: number;\n /** The confidence score threshold for the detections as a decimal\n value. Only predictions with a confidence score higher than this\n threshold will be returned. */\n confidenceThreshold?: number;\n /** A decimal value representing how much dilation to apply to the\n masks. 0 for no dilation. 1.0 means the masked area covers the whole\n image. */\n maskDilation?: number;\n /** The binary color threshold to apply to the masks. The threshold\n can be set to a decimal value between 0 and 255 non-inclusive.\n Set to -1 for no binary color thresholding. */\n binaryColorThreshold?: number;\n}\n\n/** The parameters for segmenting an image. */\nexport declare interface SegmentImageParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** A set of source input(s) for image segmentation. */\n source: SegmentImageSource;\n /** Configuration for image segmentation. */\n config?: SegmentImageConfig;\n}\n\n/** An entity representing the segmented area. */\nexport declare interface EntityLabel {\n /** The label of the segmented entity. */\n label?: string;\n /** The confidence score of the detected label. */\n score?: number;\n}\n\n/** A generated image mask. */\nexport declare interface GeneratedImageMask {\n /** The generated image mask. */\n mask?: Image;\n /** The detected entities on the segmented area. */\n labels?: EntityLabel[];\n}\n\n/** The output images response. */\nexport class SegmentImageResponse {\n /** List of generated image masks.\n */\n generatedMasks?: GeneratedImageMask[];\n}\n\n/** Optional parameters for models.get method. */\nexport declare interface GetModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\nexport declare interface GetModelParameters {\n model: string;\n /** Optional parameters for the request. */\n config?: GetModelConfig;\n}\n\n/** An endpoint where you deploy models. */\nexport declare interface Endpoint {\n /** Resource name of the endpoint. */\n name?: string;\n /** ID of the model that's deployed to the endpoint. */\n deployedModelId?: string;\n}\n\n/** A tuned machine learning model. */\nexport declare interface TunedModelInfo {\n /** ID of the base model that you want to tune. */\n baseModel?: string;\n /** Date and time when the base model was created. */\n createTime?: string;\n /** Date and time when the base model was last updated. */\n updateTime?: string;\n}\n\n/** Describes the machine learning model version checkpoint. */\nexport declare interface Checkpoint {\n /** The ID of the checkpoint.\n */\n checkpointId?: string;\n /** The epoch of the checkpoint.\n */\n epoch?: string;\n /** The step of the checkpoint.\n */\n step?: string;\n}\n\n/** A trained machine learning model. */\nexport declare interface Model {\n /** Resource name of the model. */\n name?: string;\n /** Display name of the model. */\n displayName?: string;\n /** Description of the model. */\n description?: string;\n /** Version ID of the model. A new version is committed when a new\n model version is uploaded or trained under an existing model ID. The\n version ID is an auto-incrementing decimal number in string\n representation. */\n version?: string;\n /** List of deployed models created from this base model. Note that a\n model could have been deployed to endpoints in different locations. */\n endpoints?: Endpoint[];\n /** Labels with user-defined metadata to organize your models. */\n labels?: Record;\n /** Information about the tuned model from the base model. */\n tunedModelInfo?: TunedModelInfo;\n /** The maximum number of input tokens that the model can handle. */\n inputTokenLimit?: number;\n /** The maximum number of output tokens that the model can generate. */\n outputTokenLimit?: number;\n /** List of actions that are supported by the model. */\n supportedActions?: string[];\n /** The default checkpoint id of a model version.\n */\n defaultCheckpointId?: string;\n /** The checkpoints of the model. */\n checkpoints?: Checkpoint[];\n}\n\nexport declare interface ListModelsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n /** Set true to list base models, false to list tuned models. */\n queryBase?: boolean;\n}\n\nexport declare interface ListModelsParameters {\n config?: ListModelsConfig;\n}\n\nexport class ListModelsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n models?: Model[];\n}\n\n/** Configuration for updating a tuned model. */\nexport declare interface UpdateModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n displayName?: string;\n description?: string;\n defaultCheckpointId?: string;\n}\n\n/** Configuration for updating a tuned model. */\nexport declare interface UpdateModelParameters {\n model: string;\n config?: UpdateModelConfig;\n}\n\n/** Configuration for deleting a tuned model. */\nexport declare interface DeleteModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for deleting a tuned model. */\nexport declare interface DeleteModelParameters {\n model: string;\n /** Optional parameters for the request. */\n config?: DeleteModelConfig;\n}\n\nexport class DeleteModelResponse {}\n\n/** Config for thinking features. */\nexport declare interface GenerationConfigThinkingConfig {\n /** Optional. Indicates whether to include thoughts in the response. If true, thoughts are returned only when available. */\n includeThoughts?: boolean;\n /** Optional. Indicates the thinking budget in tokens. */\n thinkingBudget?: number;\n}\n\n/** Generation config. */\nexport declare interface GenerationConfig {\n /** Optional. Config for model selection. */\n modelSelectionConfig?: ModelSelectionConfig;\n /** Optional. If enabled, audio timestamp will be included in the request to the model. */\n audioTimestamp?: boolean;\n /** Optional. Number of candidates to generate. */\n candidateCount?: number;\n /** Optional. If enabled, the model will detect emotions and adapt its responses accordingly. */\n enableAffectiveDialog?: boolean;\n /** Optional. Frequency penalties. */\n frequencyPenalty?: number;\n /** Optional. Logit probabilities. */\n logprobs?: number;\n /** Optional. The maximum number of output tokens to generate per message. */\n maxOutputTokens?: number;\n /** Optional. If specified, the media resolution specified will be used. */\n mediaResolution?: MediaResolution;\n /** Optional. Positive penalties. */\n presencePenalty?: number;\n /** Optional. Output schema of the generated response. This is an alternative to `response_schema` that accepts [JSON Schema](https://json-schema.org/). If set, `response_schema` must be omitted, but `response_mime_type` is required. While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` - `type` - `format` - `title` - `description` - `enum` (for strings and numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - `properties` - `additionalProperties` - `required` The non-standard `propertyOrdering` property may also be set. Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If `$ref` is set on a sub-schema, no other properties, except for than those starting as a `$`, may be set. */\n responseJsonSchema?: unknown;\n /** Optional. If true, export the logprobs results in response. */\n responseLogprobs?: boolean;\n /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */\n responseMimeType?: string;\n /** Optional. The modalities of the response. */\n responseModalities?: Modality[];\n /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */\n responseSchema?: Schema;\n /** Optional. Routing configuration. */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Optional. Seed. */\n seed?: number;\n /** Optional. The speech generation config. */\n speechConfig?: SpeechConfig;\n /** Optional. Stop sequences. */\n stopSequences?: string[];\n /** Optional. Controls the randomness of predictions. */\n temperature?: number;\n /** Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking. */\n thinkingConfig?: GenerationConfigThinkingConfig;\n /** Optional. If specified, top-k sampling will be used. */\n topK?: number;\n /** Optional. If specified, nucleus sampling will be used. */\n topP?: number;\n}\n\n/** Config for the count_tokens method. */\nexport declare interface CountTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Instructions for the model to steer it toward better performance.\n */\n systemInstruction?: ContentUnion;\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: Tool[];\n /** Configuration that the model uses to generate the response. Not\n supported by the Gemini Developer API.\n */\n generationConfig?: GenerationConfig;\n}\n\n/** Parameters for counting tokens. */\nexport declare interface CountTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Configuration for counting tokens. */\n config?: CountTokensConfig;\n}\n\n/** Response for counting tokens. */\nexport class CountTokensResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Total number of tokens. */\n totalTokens?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n}\n\n/** Optional parameters for computing tokens. */\nexport declare interface ComputeTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for computing tokens. */\nexport declare interface ComputeTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Optional parameters for the request.\n */\n config?: ComputeTokensConfig;\n}\n\n/** Tokens info with a list of tokens and the corresponding list of token ids. */\nexport declare interface TokensInfo {\n /** Optional. Optional fields for the role from the corresponding Content. */\n role?: string;\n /** A list of token ids from the input. */\n tokenIds?: string[];\n /** A list of tokens from the input.\n * @remarks Encoded as base64 string. */\n tokens?: string[];\n}\n\n/** Response for computing tokens. */\nexport class ComputeTokensResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */\n tokensInfo?: TokensInfo[];\n}\n\n/** A generated video. */\nexport declare interface Video {\n /** Path to another storage. */\n uri?: string;\n /** Video bytes.\n * @remarks Encoded as base64 string. */\n videoBytes?: string;\n /** Video encoding, for example \"video/mp4\". */\n mimeType?: string;\n}\n\n/** A reference image for video generation. */\nexport declare interface VideoGenerationReferenceImage {\n /** The reference image.\n */\n image?: Image;\n /** The type of the reference image, which defines how the reference\n image will be used to generate the video. Supported values are 'asset'\n or 'style'. */\n referenceType?: string;\n}\n\n/** Configuration for generating videos. */\nexport declare interface GenerateVideosConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Number of output videos. */\n numberOfVideos?: number;\n /** The gcs bucket where to save the generated videos. */\n outputGcsUri?: string;\n /** Frames per second for video generation. */\n fps?: number;\n /** Duration of the clip for video generation in seconds. */\n durationSeconds?: number;\n /** The RNG seed. If RNG seed is exactly same for each request with unchanged inputs, the prediction results will be consistent. Otherwise, a random RNG seed will be used each time to produce a different result. */\n seed?: number;\n /** The aspect ratio for the generated video. 16:9 (landscape) and 9:16 (portrait) are supported. */\n aspectRatio?: string;\n /** The resolution for the generated video. 720p and 1080p are supported. */\n resolution?: string;\n /** Whether allow to generate person videos, and restrict to specific ages. Supported values are: dont_allow, allow_adult. */\n personGeneration?: string;\n /** The pubsub topic where to publish the video generation progress. */\n pubsubTopic?: string;\n /** Optional field in addition to the text content. Negative prompts can be explicitly stated here to help generate the video. */\n negativePrompt?: string;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n /** Whether to generate audio along with the video. */\n generateAudio?: boolean;\n /** Image to use as the last frame of generated videos. Only supported for image to video use cases. */\n lastFrame?: Image;\n /** The images to use as the references to generate the videos.\n If this field is provided, the text prompt field must also be provided.\n The image, video, or last_frame field are not supported. Each image must\n be associated with a type. Veo 2 supports up to 3 asset images *or* 1\n style image. */\n referenceImages?: VideoGenerationReferenceImage[];\n /** Compression quality of the generated videos. */\n compressionQuality?: VideoCompressionQuality;\n}\n\n/** Class that represents the parameters for generating videos. */\nexport declare interface GenerateVideosParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The text prompt for generating the videos. Optional for image to video use cases. */\n prompt?: string;\n /** The input image for generating the videos.\n Optional if prompt or video is provided. */\n image?: Image;\n /** The input video for video extension use cases.\n Optional if prompt or image is provided. */\n video?: Video;\n /** Configuration for generating videos. */\n config?: GenerateVideosConfig;\n}\n\n/** A generated video. */\nexport declare interface GeneratedVideo {\n /** The output video */\n video?: Video;\n}\n\n/** Response with generated videos. */\nexport class GenerateVideosResponse {\n /** List of the generated videos */\n generatedVideos?: GeneratedVideo[];\n /** Returns if any videos were filtered due to RAI policies. */\n raiMediaFilteredCount?: number;\n /** Returns rai failure reasons if any. */\n raiMediaFilteredReasons?: string[];\n}\n\n/** Optional parameters for tunings.get method. */\nexport declare interface GetTuningJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the get method. */\nexport declare interface GetTuningJobParameters {\n name: string;\n /** Optional parameters for the request. */\n config?: GetTuningJobConfig;\n}\n\n/** TunedModelCheckpoint for the Tuned Model of a Tuning Job. */\nexport declare interface TunedModelCheckpoint {\n /** The ID of the checkpoint.\n */\n checkpointId?: string;\n /** The epoch of the checkpoint.\n */\n epoch?: string;\n /** The step of the checkpoint.\n */\n step?: string;\n /** The Endpoint resource name that the checkpoint is deployed to.\n Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`.\n */\n endpoint?: string;\n}\n\nexport declare interface TunedModel {\n /** Output only. The resource name of the TunedModel. Format: `projects/{project}/locations/{location}/models/{model}@{version_id}` When tuning from a base model, the version_id will be 1. For continuous tuning, the version id will be incremented by 1 from the last version id in the parent model. E.g., `projects/{project}/locations/{location}/models/{model}@{last_version_id + 1}` */\n model?: string;\n /** Output only. A resource name of an Endpoint. Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. */\n endpoint?: string;\n /** The checkpoints associated with this TunedModel.\n This field is only populated for tuning jobs that enable intermediate\n checkpoints. */\n checkpoints?: TunedModelCheckpoint[];\n}\n\n/** The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). */\nexport declare interface GoogleRpcStatus {\n /** The status code, which should be an enum value of google.rpc.Code. */\n code?: number;\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */\n message?: string;\n}\n\n/** A pre-tuned model for continuous tuning. */\nexport declare interface PreTunedModel {\n /** Output only. The name of the base model this PreTunedModel was tuned from. */\n baseModel?: string;\n /** Optional. The source checkpoint id. If not specified, the default checkpoint will be used. */\n checkpointId?: string;\n /** The resource name of the Model. E.g., a model resource name with a specified version id or alias: `projects/{project}/locations/{location}/models/{model}@{version_id}` `projects/{project}/locations/{location}/models/{model}@{alias}` Or, omit the version id to use the default version: `projects/{project}/locations/{location}/models/{model}` */\n tunedModelName?: string;\n}\n\n/** Hyperparameters for SFT. */\nexport declare interface SupervisedHyperParameters {\n /** Optional. Adapter size for tuning. */\n adapterSize?: AdapterSize;\n /** Optional. Batch size for tuning. This feature is only available for open source models. */\n batchSize?: string;\n /** Optional. Number of complete passes the model makes over the entire training dataset during training. */\n epochCount?: string;\n /** Optional. Learning rate for tuning. Mutually exclusive with `learning_rate_multiplier`. This feature is only available for open source models. */\n learningRate?: number;\n /** Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with `learning_rate`. This feature is only available for 1P models. */\n learningRateMultiplier?: number;\n}\n\n/** Tuning Spec for Supervised Tuning for first party models. */\nexport declare interface SupervisedTuningSpec {\n /** Optional. If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. Default is false. */\n exportLastCheckpointOnly?: boolean;\n /** Optional. Hyperparameters for SFT. */\n hyperParameters?: SupervisedHyperParameters;\n /** Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n trainingDatasetUri?: string;\n /** Tuning mode. */\n tuningMode?: TuningMode;\n /** Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n validationDatasetUri?: string;\n}\n\n/** Dataset bucket used to create a histogram for the distribution given a population of values. */\nexport declare interface DatasetDistributionDistributionBucket {\n /** Output only. Number of values in the bucket. */\n count?: string;\n /** Output only. Left bound of the bucket. */\n left?: number;\n /** Output only. Right bound of the bucket. */\n right?: number;\n}\n\n/** Distribution computed over a tuning dataset. */\nexport declare interface DatasetDistribution {\n /** Output only. Defines the histogram bucket. */\n buckets?: DatasetDistributionDistributionBucket[];\n /** Output only. The maximum of the population values. */\n max?: number;\n /** Output only. The arithmetic mean of the values in the population. */\n mean?: number;\n /** Output only. The median of the values in the population. */\n median?: number;\n /** Output only. The minimum of the population values. */\n min?: number;\n /** Output only. The 5th percentile of the values in the population. */\n p5?: number;\n /** Output only. The 95th percentile of the values in the population. */\n p95?: number;\n /** Output only. Sum of a given population of values. */\n sum?: number;\n}\n\n/** Statistics computed over a tuning dataset. */\nexport declare interface DatasetStats {\n /** Output only. Number of billable characters in the tuning dataset. */\n totalBillableCharacterCount?: string;\n /** Output only. Number of tuning characters in the tuning dataset. */\n totalTuningCharacterCount?: string;\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user messages in the training dataset uri. */\n userDatasetExamples?: Content[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the messages per example. */\n userMessagePerExampleDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: DatasetDistribution;\n}\n\n/** Statistics computed for datasets used for distillation. */\nexport declare interface DistillationDataStats {\n /** Output only. Statistics computed for the training dataset. */\n trainingDatasetStats?: DatasetStats;\n}\n\n/** Completion and its preference score. */\nexport declare interface GeminiPreferenceExampleCompletion {\n /** Single turn completion for the given prompt. */\n completion?: Content;\n /** The score for the given completion. */\n score?: number;\n}\n\n/** Input example for preference optimization. */\nexport declare interface GeminiPreferenceExample {\n /** List of completions for a given prompt. */\n completions?: GeminiPreferenceExampleCompletion[];\n /** Multi-turn contents that represents the Prompt. */\n contents?: Content[];\n}\n\n/** Statistics computed for datasets used for preference optimization. */\nexport declare interface PreferenceOptimizationDataStats {\n /** Output only. Dataset distributions for scores variance per example. */\n scoreVariancePerExampleDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for scores. */\n scoresDistribution?: DatasetDistribution;\n /** Output only. Number of billable tokens in the tuning dataset. */\n totalBillableTokenCount?: string;\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user examples in the training dataset. */\n userDatasetExamples?: GeminiPreferenceExample[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: DatasetDistribution;\n}\n\n/** Dataset bucket used to create a histogram for the distribution given a population of values. */\nexport declare interface SupervisedTuningDatasetDistributionDatasetBucket {\n /** Output only. Number of values in the bucket. */\n count?: number;\n /** Output only. Left bound of the bucket. */\n left?: number;\n /** Output only. Right bound of the bucket. */\n right?: number;\n}\n\n/** Dataset distribution for Supervised Tuning. */\nexport declare interface SupervisedTuningDatasetDistribution {\n /** Output only. Sum of a given population of values that are billable. */\n billableSum?: string;\n /** Output only. Defines the histogram bucket. */\n buckets?: SupervisedTuningDatasetDistributionDatasetBucket[];\n /** Output only. The maximum of the population values. */\n max?: number;\n /** Output only. The arithmetic mean of the values in the population. */\n mean?: number;\n /** Output only. The median of the values in the population. */\n median?: number;\n /** Output only. The minimum of the population values. */\n min?: number;\n /** Output only. The 5th percentile of the values in the population. */\n p5?: number;\n /** Output only. The 95th percentile of the values in the population. */\n p95?: number;\n /** Output only. Sum of a given population of values. */\n sum?: string;\n}\n\n/** Tuning data statistics for Supervised Tuning. */\nexport declare interface SupervisedTuningDataStats {\n /** Output only. For each index in `truncated_example_indices`, the user-facing reason why the example was dropped. */\n droppedExampleReasons?: string[];\n /** Output only. Number of billable characters in the tuning dataset. */\n totalBillableCharacterCount?: string;\n /** Output only. Number of billable tokens in the tuning dataset. */\n totalBillableTokenCount?: string;\n /** Output only. The number of examples in the dataset that have been dropped. An example can be dropped for reasons including: too many tokens, contains an invalid image, contains too many images, etc. */\n totalTruncatedExampleCount?: string;\n /** Output only. Number of tuning characters in the tuning dataset. */\n totalTuningCharacterCount?: string;\n /** Output only. A partial sample of the indices (starting from 1) of the dropped examples. */\n truncatedExampleIndices?: string[];\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user messages in the training dataset uri. */\n userDatasetExamples?: Content[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: SupervisedTuningDatasetDistribution;\n /** Output only. Dataset distributions for the messages per example. */\n userMessagePerExampleDistribution?: SupervisedTuningDatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: SupervisedTuningDatasetDistribution;\n}\n\n/** The tuning data statistic values for TuningJob. */\nexport declare interface TuningDataStats {\n /** Output only. Statistics for distillation. */\n distillationDataStats?: DistillationDataStats;\n /** Output only. Statistics for preference optimization. */\n preferenceOptimizationDataStats?: PreferenceOptimizationDataStats;\n /** The SFT Tuning data stats. */\n supervisedTuningDataStats?: SupervisedTuningDataStats;\n}\n\n/** Represents a customer-managed encryption key spec that can be applied to a top-level resource. */\nexport declare interface EncryptionSpec {\n /** Required. The Cloud KMS resource identifier of the customer managed encryption key used to protect a resource. Has the form: `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`. The key needs to be in the same region as where the compute resource is created. */\n kmsKeyName?: string;\n}\n\n/** Tuning spec for Partner models. */\nexport declare interface PartnerModelTuningSpec {\n /** Hyperparameters for tuning. The accepted hyper_parameters and their valid range of values will differ depending on the base model. */\n hyperParameters?: Record;\n /** Required. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDatasetUri?: string;\n /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */\n validationDatasetUri?: string;\n}\n\n/** A tuning job. */\nexport declare interface TuningJob {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}` */\n name?: string;\n /** Output only. The detailed state of the job. */\n state?: JobState;\n /** Output only. Time when the TuningJob was created. */\n createTime?: string;\n /** Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING` state. */\n startTime?: string;\n /** Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`. */\n endTime?: string;\n /** Output only. Time when the TuningJob was most recently updated. */\n updateTime?: string;\n /** Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. */\n error?: GoogleRpcStatus;\n /** Optional. The description of the TuningJob. */\n description?: string;\n /** The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */\n baseModel?: string;\n /** Output only. The tuned model resources associated with this TuningJob. */\n tunedModel?: TunedModel;\n /** The pre-tuned model for continuous tuning. */\n preTunedModel?: PreTunedModel;\n /** Tuning Spec for Supervised Fine Tuning. */\n supervisedTuningSpec?: SupervisedTuningSpec;\n /** Output only. The tuning data statistics associated with this TuningJob. */\n tuningDataStats?: TuningDataStats;\n /** Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with the provided encryption key. */\n encryptionSpec?: EncryptionSpec;\n /** Tuning Spec for open sourced and third party Partner models. */\n partnerModelTuningSpec?: PartnerModelTuningSpec;\n /** Optional. The user-provided path to custom model weights. Set this field to tune a custom model. The path must be a Cloud Storage directory that contains the model weights in .safetensors format along with associated model metadata files. If this field is set, the base_model field must still be set to indicate which base model the custom model is derived from. This feature is only available for open source models. */\n customBaseModel?: string;\n /** Output only. The Experiment associated with this TuningJob. */\n experiment?: string;\n /** Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. */\n labels?: Record;\n /** Optional. Cloud Storage path to the directory where tuning job outputs are written to. This field is only available and required for open source models. */\n outputUri?: string;\n /** Output only. The resource name of the PipelineJob associated with the TuningJob. Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`. */\n pipelineJob?: string;\n /** The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission on this service account. */\n serviceAccount?: string;\n /** Optional. The display name of the TunedModel. The name can be up to 128 characters long and can consist of any UTF-8 characters. */\n tunedModelDisplayName?: string;\n}\n\n/** Configuration for the list tuning jobs method. */\nexport declare interface ListTuningJobsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n}\n\n/** Parameters for the list tuning jobs method. */\nexport declare interface ListTuningJobsParameters {\n config?: ListTuningJobsConfig;\n}\n\n/** Response for the list tuning jobs method. */\nexport class ListTuningJobsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** A token to retrieve the next page of results. Pass to ListTuningJobsRequest.page_token to obtain that page. */\n nextPageToken?: string;\n /** List of TuningJobs in the requested page. */\n tuningJobs?: TuningJob[];\n}\n\nexport declare interface TuningExample {\n /** Text model input. */\n textInput?: string;\n /** The expected model output. */\n output?: string;\n}\n\n/** Supervised fine-tuning training dataset. */\nexport declare interface TuningDataset {\n /** GCS URI of the file containing training dataset in JSONL format. */\n gcsUri?: string;\n /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */\n vertexDatasetResource?: string;\n /** Inline examples with simple input/output text. */\n examples?: TuningExample[];\n}\n\nexport declare interface TuningValidationDataset {\n /** GCS URI of the file containing validation dataset in JSONL format. */\n gcsUri?: string;\n /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */\n vertexDatasetResource?: string;\n}\n\n/** Supervised fine-tuning job creation request - optional fields. */\nexport declare interface CreateTuningJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n validationDataset?: TuningValidationDataset;\n /** The display name of the tuned Model. The name can be up to 128 characters long and can consist of any UTF-8 characters. */\n tunedModelDisplayName?: string;\n /** The description of the TuningJob */\n description?: string;\n /** Number of complete passes the model makes over the entire training dataset during training. */\n epochCount?: number;\n /** Multiplier for adjusting the default learning rate. */\n learningRateMultiplier?: number;\n /** If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. */\n exportLastCheckpointOnly?: boolean;\n /** The optional checkpoint id of the pre-tuned model to use for tuning, if applicable. */\n preTunedModelCheckpointId?: string;\n /** Adapter size for tuning. */\n adapterSize?: AdapterSize;\n /** The batch size hyperparameter for tuning. If not set, a default of 4 or 16 will be used based on the number of training examples. */\n batchSize?: number;\n /** The learning rate hyperparameter for tuning. If not set, a default of 0.001 or 0.0002 will be calculated based on the number of training examples. */\n learningRate?: number;\n}\n\n/** Supervised fine-tuning job creation parameters - optional fields. */\nexport declare interface CreateTuningJobParametersPrivate {\n /** The base model that is being tuned, e.g., \"gemini-2.5-flash\". */\n baseModel?: string;\n /** The PreTunedModel that is being tuned. */\n preTunedModel?: PreTunedModel;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDataset: TuningDataset;\n /** Configuration for the tuning job. */\n config?: CreateTuningJobConfig;\n}\n\n/** A long-running operation. */\nexport declare interface TuningOperation {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n}\n\n/** Optional configuration for cached content creation. */\nexport declare interface CreateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n /** The user-generated meaningful display name of the cached content.\n */\n displayName?: string;\n /** The content to cache.\n */\n contents?: ContentListUnion;\n /** Developer set system instruction.\n */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n */\n tools?: Tool[];\n /** Configuration for the tools to use. This config is shared for all tools.\n */\n toolConfig?: ToolConfig;\n /** The Cloud KMS resource identifier of the customer managed\n encryption key used to protect a resource.\n The key needs to be in the same region as where the compute resource is\n created. See\n https://cloud.google.com/vertex-ai/docs/general/cmek for more\n details. If this is set, then all created CachedContent objects\n will be encrypted with the provided encryption key.\n Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}\n */\n kmsKeyName?: string;\n}\n\n/** Parameters for caches.create method. */\nexport declare interface CreateCachedContentParameters {\n /** ID of the model to use. Example: gemini-2.0-flash */\n model: string;\n /** Configuration that contains optional parameters.\n */\n config?: CreateCachedContentConfig;\n}\n\n/** Metadata on the usage of the cached content. */\nexport declare interface CachedContentUsageMetadata {\n /** Duration of audio in seconds. */\n audioDurationSeconds?: number;\n /** Number of images. */\n imageCount?: number;\n /** Number of text characters. */\n textCount?: number;\n /** Total number of tokens that the cached content consumes. */\n totalTokenCount?: number;\n /** Duration of video in seconds. */\n videoDurationSeconds?: number;\n}\n\n/** A resource used in LLM queries for users to explicitly specify what to cache. */\nexport declare interface CachedContent {\n /** The server-generated resource name of the cached content. */\n name?: string;\n /** The user-generated meaningful display name of the cached content. */\n displayName?: string;\n /** The name of the publisher model to use for cached content. */\n model?: string;\n /** Creation time of the cache entry. */\n createTime?: string;\n /** When the cache entry was last updated in UTC time. */\n updateTime?: string;\n /** Expiration time of the cached content. */\n expireTime?: string;\n /** Metadata on the usage of the cached content. */\n usageMetadata?: CachedContentUsageMetadata;\n}\n\n/** Optional parameters for caches.get method. */\nexport declare interface GetCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for caches.get method. */\nexport declare interface GetCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: GetCachedContentConfig;\n}\n\n/** Optional parameters for caches.delete method. */\nexport declare interface DeleteCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for caches.delete method. */\nexport declare interface DeleteCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: DeleteCachedContentConfig;\n}\n\n/** Empty response for caches.delete method. */\nexport class DeleteCachedContentResponse {}\n\n/** Optional parameters for caches.update method. */\nexport declare interface UpdateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n}\n\nexport declare interface UpdateCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Configuration that contains optional parameters.\n */\n config?: UpdateCachedContentConfig;\n}\n\n/** Config for caches.list method. */\nexport declare interface ListCachedContentsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Parameters for caches.list method. */\nexport declare interface ListCachedContentsParameters {\n /** Configuration that contains optional parameters.\n */\n config?: ListCachedContentsConfig;\n}\n\nexport class ListCachedContentsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n /** List of cached contents.\n */\n cachedContents?: CachedContent[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface ListFilesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Generates the parameters for the list method. */\nexport declare interface ListFilesParameters {\n /** Used to override the default configuration. */\n config?: ListFilesConfig;\n}\n\n/** Status of a File that uses a common error model. */\nexport declare interface FileStatus {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n message?: string;\n /** The status code. 0 for OK, 1 for CANCELLED */\n code?: number;\n}\n\n/** A file uploaded to the API. */\nexport declare interface File {\n /** The `File` resource name. The ID (name excluding the \"files/\" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */\n name?: string;\n /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */\n displayName?: string;\n /** Output only. MIME type of the file. */\n mimeType?: string;\n /** Output only. Size of the file in bytes. */\n sizeBytes?: string;\n /** Output only. The timestamp of when the `File` was created. */\n createTime?: string;\n /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */\n expirationTime?: string;\n /** Output only. The timestamp of when the `File` was last updated. */\n updateTime?: string;\n /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */\n sha256Hash?: string;\n /** Output only. The URI of the `File`. */\n uri?: string;\n /** Output only. The URI of the `File`, only set for downloadable (generated) files. */\n downloadUri?: string;\n /** Output only. Processing state of the File. */\n state?: FileState;\n /** Output only. The source of the `File`. */\n source?: FileSource;\n /** Output only. Metadata for a video. */\n videoMetadata?: Record;\n /** Output only. Error status if File processing failed. */\n error?: FileStatus;\n}\n\n/** Response for the list files method. */\nexport class ListFilesResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** A token to retrieve next page of results. */\n nextPageToken?: string;\n /** The list of files. */\n files?: File[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface CreateFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the private _create method. */\nexport declare interface CreateFileParameters {\n /** The file to be uploaded.\n mime_type: (Required) The MIME type of the file. Must be provided.\n name: (Optional) The name of the file in the destination (e.g.\n 'files/sample-image').\n display_name: (Optional) The display name of the file.\n */\n file: File;\n /** Used to override the default configuration. */\n config?: CreateFileConfig;\n}\n\n/** Response for the create file method. */\nexport class CreateFileResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Used to override the default configuration. */\nexport declare interface GetFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface GetFileParameters {\n /** The name identifier for the file to retrieve. */\n name: string;\n /** Used to override the default configuration. */\n config?: GetFileConfig;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DeleteFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface DeleteFileParameters {\n /** The name identifier for the file to be deleted. */\n name: string;\n /** Used to override the default configuration. */\n config?: DeleteFileConfig;\n}\n\n/** Response for the delete file method. */\nexport class DeleteFileResponse {}\n\n/** Config for inlined request. */\nexport declare interface InlinedRequest {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model?: string;\n /** Content of the request.\n */\n contents?: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** Config for `src` parameter. */\nexport declare interface BatchJobSource {\n /** Storage format of the input files. Must be one of:\n 'jsonl', 'bigquery'.\n */\n format?: string;\n /** The Google Cloud Storage URIs to input files.\n */\n gcsUri?: string[];\n /** The BigQuery URI to input table.\n */\n bigqueryUri?: string;\n /** The Gemini Developer API's file resource name of the input data\n (e.g. \"files/12345\").\n */\n fileName?: string;\n /** The Gemini Developer API's inlined input data to run batch job.\n */\n inlinedRequests?: InlinedRequest[];\n}\n\n/** Job error. */\nexport declare interface JobError {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: string[];\n /** The status code. */\n code?: number;\n /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the `details` field. */\n message?: string;\n}\n\n/** Config for `inlined_responses` parameter. */\nexport class InlinedResponse {\n /** The response to the request.\n */\n response?: GenerateContentResponse;\n /** The error encountered while processing the request.\n */\n error?: JobError;\n}\n\n/** Config for `des` parameter. */\nexport declare interface BatchJobDestination {\n /** Storage format of the output files. Must be one of:\n 'jsonl', 'bigquery'.\n */\n format?: string;\n /** The Google Cloud Storage URI to the output file.\n */\n gcsUri?: string;\n /** The BigQuery URI to the output table.\n */\n bigqueryUri?: string;\n /** The Gemini Developer API's file resource name of the output data\n (e.g. \"files/12345\"). The file will be a JSONL file with a single response\n per line. The responses will be GenerateContentResponse messages formatted\n as JSON. The responses will be written in the same order as the input\n requests.\n */\n fileName?: string;\n /** The responses to the requests in the batch. Returned when the batch was\n built using inlined requests. The responses will be in the same order as\n the input requests.\n */\n inlinedResponses?: InlinedResponse[];\n}\n\n/** Config for optional parameters. */\nexport declare interface CreateBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The user-defined name of this BatchJob.\n */\n displayName?: string;\n /** GCS or BigQuery URI prefix for the output predictions. Example:\n \"gs://path/to/output/data\" or \"bq://projectId.bqDatasetId.bqTableId\".\n */\n dest?: BatchJobDestinationUnion;\n}\n\n/** Config for batches.create parameters. */\nexport declare interface CreateBatchJobParameters {\n /** The name of the model to produces the predictions via the BatchJob.\n */\n model?: string;\n /** GCS URI(-s) or BigQuery URI to your input data to run batch job.\n Example: \"gs://path/to/input/data\" or \"bq://projectId.bqDatasetId.bqTableId\".\n */\n src: BatchJobSourceUnion;\n /** Optional parameters for creating a BatchJob.\n */\n config?: CreateBatchJobConfig;\n}\n\n/** Config for batches.create return value. */\nexport declare interface BatchJob {\n /** The resource name of the BatchJob. Output only.\".\n */\n name?: string;\n /** The display name of the BatchJob.\n */\n displayName?: string;\n /** The state of the BatchJob.\n */\n state?: JobState;\n /** Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED. */\n error?: JobError;\n /** The time when the BatchJob was created.\n */\n createTime?: string;\n /** Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state. */\n startTime?: string;\n /** The time when the BatchJob was completed.\n */\n endTime?: string;\n /** The time when the BatchJob was last updated.\n */\n updateTime?: string;\n /** The name of the model that produces the predictions via the BatchJob.\n */\n model?: string;\n /** Configuration for the input data.\n */\n src?: BatchJobSource;\n /** Configuration for the output data.\n */\n dest?: BatchJobDestination;\n}\n\n/** Optional parameters. */\nexport declare interface GetBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.get parameters. */\nexport declare interface GetBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: GetBatchJobConfig;\n}\n\n/** Optional parameters. */\nexport declare interface CancelBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.cancel parameters. */\nexport declare interface CancelBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: CancelBatchJobConfig;\n}\n\n/** Config for optional parameters. */\nexport declare interface ListBatchJobsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n}\n\n/** Config for batches.list parameters. */\nexport declare interface ListBatchJobsParameters {\n config?: ListBatchJobsConfig;\n}\n\n/** Config for batches.list return value. */\nexport class ListBatchJobsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n batchJobs?: BatchJob[];\n}\n\n/** Optional parameters for models.get method. */\nexport declare interface DeleteBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.delete parameters. */\nexport declare interface DeleteBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: DeleteBatchJobConfig;\n}\n\n/** The return value of delete operation. */\nexport declare interface DeleteResourceJob {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n name?: string;\n done?: boolean;\n error?: JobError;\n}\n\nexport declare interface GetOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the GET method. */\nexport declare interface GetOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\nexport declare interface FetchPredictOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the fetchPredictOperation method. */\nexport declare interface FetchPredictOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n resourceName: string;\n /** Used to override the default configuration. */\n config?: FetchPredictOperationConfig;\n}\n\nexport declare interface TestTableItem {\n /** The name of the test. This is used to derive the replay id. */\n name?: string;\n /** The parameters to the test. Use pydantic models. */\n parameters?: Record;\n /** Expects an exception for MLDev matching the string. */\n exceptionIfMldev?: string;\n /** Expects an exception for Vertex matching the string. */\n exceptionIfVertex?: string;\n /** Use if you don't want to use the default replay id which is derived from the test name. */\n overrideReplayId?: string;\n /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */\n hasUnion?: boolean;\n /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */\n skipInApiMode?: string;\n /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */\n ignoreKeys?: string[];\n}\n\nexport declare interface TestTableFile {\n comment?: string;\n testMethod?: string;\n parameterNames?: string[];\n testTable?: TestTableItem[];\n}\n\n/** Represents a single request in a replay. */\nexport declare interface ReplayRequest {\n method?: string;\n url?: string;\n headers?: Record;\n bodySegments?: Record[];\n}\n\n/** Represents a single response in a replay. */\nexport class ReplayResponse {\n statusCode?: number;\n headers?: Record;\n bodySegments?: Record[];\n sdkResponseSegments?: Record[];\n}\n\n/** Represents a single interaction, request and response in a replay. */\nexport declare interface ReplayInteraction {\n request?: ReplayRequest;\n response?: ReplayResponse;\n}\n\n/** Represents a recorded session. */\nexport declare interface ReplayFile {\n replayId?: string;\n interactions?: ReplayInteraction[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface UploadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */\n name?: string;\n /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */\n mimeType?: string;\n /** Optional display name of the file. */\n displayName?: string;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DownloadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters used to download a file. */\nexport declare interface DownloadFileParameters {\n /** The file to download. It can be a file name, a file object or a generated video. */\n file: DownloadableFileUnion;\n /** Location where the file should be downloaded to. */\n downloadPath: string;\n /** Configuration to for the download operation. */\n config?: DownloadFileConfig;\n}\n\n/** Configuration for upscaling an image.\n\n For more information on this configuration, refer to\n the `Imagen API reference documentation\n `_.\n */\nexport declare interface UpscaleImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Whether to include a reason for filtered-out images in the\n response. */\n includeRaiReason?: boolean;\n /** The image format that the output should be saved as. */\n outputMimeType?: string;\n /** The level of compression if the ``output_mime_type`` is\n ``image/jpeg``. */\n outputCompressionQuality?: number;\n /** Whether to add an image enhancing step before upscaling.\n It is expected to suppress the noise and JPEG compression artifacts\n from the input image. */\n enhanceInputImage?: boolean;\n /** With a higher image preservation factor, the original image\n pixels are more respected. With a lower image preservation factor, the\n output image will have be more different from the input image, but\n with finer details and less noise. */\n imagePreservationFactor?: number;\n}\n\n/** User-facing config UpscaleImageParameters. */\nexport declare interface UpscaleImageParameters {\n /** The model to use. */\n model: string;\n /** The input image to upscale. */\n image: Image;\n /** The factor to upscale the image (x2 or x4). */\n upscaleFactor: string;\n /** Configuration for upscaling. */\n config?: UpscaleImageConfig;\n}\n\n/** A raw reference image.\n\n A raw reference image represents the base image to edit, provided by the user.\n It can optionally be provided in addition to a mask reference image or\n a style reference image.\n */\nexport class RawReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_RAW',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n };\n return referenceImageAPI;\n }\n}\n\n/** A mask reference image.\n\n This encapsulates either a mask image provided by the user and configs for\n the user provided mask, or only config parameters for the model to generate\n a mask.\n\n A mask image is an image whose non-zero values indicate where to edit the base\n image. If the user provides a mask image, the mask must be in the same\n dimensions as the raw image.\n */\nexport class MaskReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the mask reference image. */\n config?: MaskReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_MASK',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n maskImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A control reference image.\n\n The image of the control reference image is either a control image provided\n by the user, or a regular image which the backend will use to generate a\n control image of. In the case of the latter, the\n enable_control_image_computation field in the config should be set to True.\n\n A control image is an image that represents a sketch image of areas for the\n model to fill in based on the prompt.\n */\nexport class ControlReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the control reference image. */\n config?: ControlReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_CONTROL',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n controlImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A style reference image.\n\n This encapsulates a style reference image provided by the user, and\n additionally optional config parameters for the style reference image.\n\n A raw reference image can also be provided as a destination for the style to\n be applied to.\n */\nexport class StyleReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the style reference image. */\n config?: StyleReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_STYLE',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n styleImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A subject reference image.\n\n This encapsulates a subject reference image provided by the user, and\n additionally optional config parameters for the subject reference image.\n\n A raw reference image can also be provided as a destination for the subject to\n be applied to.\n */\nexport class SubjectReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the subject reference image. */\n config?: SubjectReferenceConfig;\n /* Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_SUBJECT',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n subjectImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\nexport /** Sent in response to a `LiveGenerateContentSetup` message from the client. */\ndeclare interface LiveServerSetupComplete {\n /** The session id of the live session. */\n sessionId?: string;\n}\n\n/** Audio transcription in Server Conent. */\nexport declare interface Transcription {\n /** Transcription text.\n */\n text?: string;\n /** The bool indicates the end of the transcription.\n */\n finished?: boolean;\n}\n\n/** Incremental server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time. Clients\n may choose to buffer and play it out in real time.\n */\nexport declare interface LiveServerContent {\n /** The content that the model has generated as part of the current conversation with the user. */\n modelTurn?: Content;\n /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */\n turnComplete?: boolean;\n /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */\n interrupted?: boolean;\n /** Metadata returned to client when grounding is enabled. */\n groundingMetadata?: GroundingMetadata;\n /** If true, indicates that the model is done generating. When model is\n interrupted while generating there will be no generation_complete message\n in interrupted turn, it will go through interrupted > turn_complete.\n When model assumes realtime playback there will be delay between\n generation_complete and turn_complete that is caused by model\n waiting for playback to finish. If true, indicates that the model\n has finished generating all content. This is a signal to the client\n that it can stop sending messages. */\n generationComplete?: boolean;\n /** Input transcription. The transcription is independent to the model\n turn which means it doesn’t imply any ordering between transcription and\n model turn. */\n inputTranscription?: Transcription;\n /** Output transcription. The transcription is independent to the model\n turn which means it doesn’t imply any ordering between transcription and\n model turn.\n */\n outputTranscription?: Transcription;\n /** Metadata related to url context retrieval tool. */\n urlContextMetadata?: UrlContextMetadata;\n}\n\n/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\nexport declare interface LiveServerToolCall {\n /** The function call to be executed. */\n functionCalls?: FunctionCall[];\n}\n\n/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled.\n\n If there were side-effects to those tool calls, clients may attempt to undo\n the tool calls. This message occurs only in cases where the clients interrupt\n server turns.\n */\nexport declare interface LiveServerToolCallCancellation {\n /** The ids of the tool calls to be cancelled. */\n ids?: string[];\n}\n\n/** Usage metadata about response(s). */\nexport declare interface UsageMetadata {\n /** Number of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n /** Total number of tokens across all the generated response candidates. */\n responseTokenCount?: number;\n /** Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Number of tokens of thoughts for thinking models. */\n thoughtsTokenCount?: number;\n /** Total token count for prompt, response candidates, and tool-use prompts(if present). */\n totalTokenCount?: number;\n /** List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were processed in the cache input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were returned in the response. */\n responseTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were processed in the tool-use prompt. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Traffic type. This shows whether a request consumes Pay-As-You-Go\n or Provisioned Throughput quota. */\n trafficType?: TrafficType;\n}\n\n/** Server will not be able to service client soon. */\nexport declare interface LiveServerGoAway {\n /** The remaining time before the connection will be terminated as ABORTED. The minimal time returned here is specified differently together with the rate limits for a given model. */\n timeLeft?: string;\n}\n\n/** Update of the session resumption state.\n\n Only sent if `session_resumption` was set in the connection config.\n */\nexport declare interface LiveServerSessionResumptionUpdate {\n /** New handle that represents state that can be resumed. Empty if `resumable`=false. */\n newHandle?: string;\n /** True if session can be resumed at this point. It might be not possible to resume session at some points. In that case we send update empty new_handle and resumable=false. Example of such case could be model executing function calls or just generating. Resuming session (using previous session token) in such state will result in some data loss. */\n resumable?: boolean;\n /** Index of last message sent by client that is included in state represented by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent` is set.\n\nPresence of this index allows users to transparently reconnect and avoid issue of losing some part of realtime audio input/video. If client wishes to temporarily disconnect (for example as result of receiving GoAway) they can do it without losing state by buffering messages sent since last `SessionResmumptionTokenUpdate`. This field will enable them to limit buffering (avoid keeping all requests in RAM).\n\nNote: This should not be used for when resuming a session at some time later -- in those cases partial audio and video frames arelikely not needed. */\n lastConsumedClientMessageIndex?: string;\n}\n\n/** Response message for API call. */\nexport class LiveServerMessage {\n /** Sent in response to a `LiveClientSetup` message from the client. */\n setupComplete?: LiveServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveServerContent;\n /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\n toolCall?: LiveServerToolCall;\n /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */\n toolCallCancellation?: LiveServerToolCallCancellation;\n /** Usage metadata about model response(s). */\n usageMetadata?: UsageMetadata;\n /** Server will disconnect soon. */\n goAway?: LiveServerGoAway;\n /** Update of the session resumption state. */\n sessionResumptionUpdate?: LiveServerSessionResumptionUpdate;\n /**\n * Returns the concatenation of all text parts from the server content if present.\n *\n * @remarks\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n */\n get text(): string | undefined {\n let text = '';\n let anyTextPartFound = false;\n const nonTextParts = [];\n for (const part of this.serverContent?.modelTurn?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n fieldValue !== null\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartFound = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartFound ? text : undefined;\n }\n\n /**\n * Returns the concatenation of all inline data parts from the server content if present.\n *\n * @remarks\n * If there are non-inline data parts in the\n * response, the concatenation of all inline data parts will be returned, and\n * a warning will be logged.\n */\n get data(): string | undefined {\n let data = '';\n const nonDataParts = [];\n for (const part of this.serverContent?.modelTurn?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (fieldName !== 'inlineData' && fieldValue !== null) {\n nonDataParts.push(fieldName);\n }\n }\n if (part.inlineData && typeof part.inlineData.data === 'string') {\n data += atob(part.inlineData.data);\n }\n }\n if (nonDataParts.length > 0) {\n console.warn(\n `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`,\n );\n }\n return data.length > 0 ? btoa(data) : undefined;\n }\n}\n\n/** Parameters for the get method of the operations module. */\nexport declare interface OperationGetParameters> {\n /** The operation to be retrieved. */\n operation: U;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\n/** Parameters of the fromAPIResponse method of the Operation class. */\nexport declare interface OperationFromAPIResponseParameters {\n /** The API response to be converted to an Operation. */\n apiResponse: Record;\n /** Whether the API response is from Vertex AI. */\n isVertexAI: boolean;\n}\n\n/** A long-running operation. */\nexport declare interface Operation {\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The response if the operation is successful. */\n response?: T;\n /**\n * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n * @internal\n */\n _fromAPIResponse({\n apiResponse,\n isVertexAI,\n }: OperationFromAPIResponseParameters): Operation;\n}\n\n/** A video generation long-running operation. */\nexport class GenerateVideosOperation\n implements Operation\n{\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The response if the operation is successful. */\n response?: GenerateVideosResponse;\n /** The full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n\n /**\n * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n * @internal\n */\n _fromAPIResponse({\n apiResponse,\n isVertexAI,\n }: OperationFromAPIResponseParameters): Operation {\n const operation = new GenerateVideosOperation();\n operation.name = apiResponse['name'] as string | undefined;\n operation.metadata = apiResponse['metadata'] as\n | Record\n | undefined;\n operation.done = apiResponse['done'] as boolean | undefined;\n operation.error = apiResponse['error'] as\n | Record\n | undefined;\n\n if (isVertexAI) {\n const response = apiResponse['response'] as\n | Record\n | undefined;\n if (response) {\n const operationResponse = new GenerateVideosResponse();\n const responseVideos = response['videos'] as\n | Array>\n | undefined;\n operationResponse.generatedVideos = responseVideos?.map(\n (generatedVideo) => {\n return {\n video: {\n uri: generatedVideo['gcsUri'] as string | undefined,\n videoBytes: generatedVideo['bytesBase64Encoded']\n ? tBytes(generatedVideo['bytesBase64Encoded'] as string)\n : undefined,\n mimeType: generatedVideo['mimeType'] as string | undefined,\n } as Video,\n } as GeneratedVideo;\n },\n );\n operationResponse.raiMediaFilteredCount = response[\n 'raiMediaFilteredCount'\n ] as number | undefined;\n operationResponse.raiMediaFilteredReasons = response[\n 'raiMediaFilteredReasons'\n ] as string[] | undefined;\n operation.response = operationResponse;\n }\n } else {\n const response = apiResponse['response'] as\n | Record\n | undefined;\n if (response) {\n const operationResponse = new GenerateVideosResponse();\n const generatedVideoResponse = response['generateVideoResponse'] as\n | Record\n | undefined;\n const responseVideos = generatedVideoResponse?.['generatedSamples'] as\n | Array>\n | undefined;\n operationResponse.generatedVideos = responseVideos?.map(\n (generatedVideo) => {\n const video = generatedVideo['video'] as\n | Record\n | undefined;\n return {\n video: {\n uri: video?.['uri'] as string | undefined,\n videoBytes: video?.['encodedVideo']\n ? tBytes(video?.['encodedVideo'] as string)\n : undefined,\n mimeType: generatedVideo['encoding'] as string | undefined,\n } as Video,\n } as GeneratedVideo;\n },\n );\n operationResponse.raiMediaFilteredCount = generatedVideoResponse?.[\n 'raiMediaFilteredCount'\n ] as number | undefined;\n operationResponse.raiMediaFilteredReasons = generatedVideoResponse?.[\n 'raiMediaFilteredReasons'\n ] as string[] | undefined;\n operation.response = operationResponse;\n }\n }\n return operation;\n }\n}\n\n/** Configures automatic detection of activity. */\nexport declare interface AutomaticActivityDetection {\n /** If enabled, detected voice and text input count as activity. If disabled, the client must send activity signals. */\n disabled?: boolean;\n /** Determines how likely speech is to be detected. */\n startOfSpeechSensitivity?: StartSensitivity;\n /** Determines how likely detected speech is ended. */\n endOfSpeechSensitivity?: EndSensitivity;\n /** The required duration of detected speech before start-of-speech is committed. The lower this value the more sensitive the start-of-speech detection is and the shorter speech can be recognized. However, this also increases the probability of false positives. */\n prefixPaddingMs?: number;\n /** The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency. */\n silenceDurationMs?: number;\n}\n\n/** Marks the end of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface RealtimeInputConfig {\n /** If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals. */\n automaticActivityDetection?: AutomaticActivityDetection;\n /** Defines what effect activity has. */\n activityHandling?: ActivityHandling;\n /** Defines which input is included in the user's turn. */\n turnCoverage?: TurnCoverage;\n}\n\n/** Configuration of session resumption mechanism.\n\n Included in `LiveConnectConfig.session_resumption`. If included server\n will send `LiveServerSessionResumptionUpdate` messages.\n */\nexport declare interface SessionResumptionConfig {\n /** Session resumption handle of previous session (session to restore).\n\nIf not present new session will be started. */\n handle?: string;\n /** If set the server will send `last_consumed_client_message_index` in the `session_resumption_update` messages to allow for transparent reconnections. */\n transparent?: boolean;\n}\n\n/** Context window will be truncated by keeping only suffix of it.\n\n Context window will always be cut at start of USER role turn. System\n instructions and `BidiGenerateContentSetup.prefix_turns` will not be\n subject to the sliding window mechanism, they will always stay at the\n beginning of context window.\n */\nexport declare interface SlidingWindow {\n /** Session reduction target -- how many tokens we should keep. Window shortening operation has some latency costs, so we should avoid running it on every turn. Should be < trigger_tokens. If not set, trigger_tokens/2 is assumed. */\n targetTokens?: string;\n}\n\n/** Enables context window compression -- mechanism managing model context window so it does not exceed given length. */\nexport declare interface ContextWindowCompressionConfig {\n /** Number of tokens (before running turn) that triggers context window compression mechanism. */\n triggerTokens?: string;\n /** Sliding window compression mechanism. */\n slidingWindow?: SlidingWindow;\n}\n\n/** The audio transcription configuration in Setup. */\nexport declare interface AudioTranscriptionConfig {}\n\n/** Config for proactivity features. */\nexport declare interface ProactivityConfig {\n /** If enabled, the model can reject responding to the last prompt. For\n example, this allows the model to ignore out of context speech or to stay\n silent if the user did not make a request, yet. */\n proactiveAudio?: boolean;\n}\n\n/** Message contains configuration that will apply for the duration of the streaming session. */\nexport declare interface LiveClientSetup {\n /** \n The fully qualified name of the publisher model or tuned model endpoint to\n use.\n */\n model?: string;\n /** The generation configuration for the session.\n Note: only a subset of fields are supported.\n */\n generationConfig?: GenerationConfig;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n /** Configures the realtime input behavior in BidiGenerateContent. */\n realtimeInputConfig?: RealtimeInputConfig;\n /** Configures session resumption mechanism.\n\n If included server will send SessionResumptionUpdate messages. */\n sessionResumption?: SessionResumptionConfig;\n /** Configures context window compression mechanism.\n\n If included, server will compress context window to fit into given length. */\n contextWindowCompression?: ContextWindowCompressionConfig;\n /** The transcription of the input aligns with the input audio language.\n */\n inputAudioTranscription?: AudioTranscriptionConfig;\n /** The transcription of the output aligns with the language code\n specified for the output audio.\n */\n outputAudioTranscription?: AudioTranscriptionConfig;\n /** Configures the proactivity of the model. This allows the model to respond proactively to\n the input and to ignore irrelevant input. */\n proactivity?: ProactivityConfig;\n}\n\n/** Incremental update of the current conversation delivered from the client.\n\n All the content here will unconditionally be appended to the conversation\n history and used as part of the prompt to the model to generate content.\n\n A message here will interrupt any current model generation.\n */\nexport declare interface LiveClientContent {\n /** The content appended to the current conversation with the model.\n\n For single-turn queries, this is a single instance. For multi-turn\n queries, this is a repeated field that contains conversation history and\n latest request.\n */\n turns?: Content[];\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Marks the start of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface ActivityStart {}\n\n/** Marks the end of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface ActivityEnd {}\n\n/** User input that is sent in real time.\n\n This is different from `LiveClientContent` in a few ways:\n\n - Can be sent continuously without interruption to model generation.\n - If there is a need to mix data interleaved across the\n `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to\n optimize for best response, but there are no guarantees.\n - End of turn is not explicitly specified, but is rather derived from user\n activity (for example, end of speech).\n - Even before the end of turn, the data is processed incrementally\n to optimize for a fast start of the response from the model.\n - Is always assumed to be the user's input (cannot be used to populate\n conversation history).\n */\nexport declare interface LiveClientRealtimeInput {\n /** Inlined bytes data for media input. */\n mediaChunks?: Blob[];\n /** The realtime audio input stream. */\n audio?: Blob;\n /** \nIndicates that the audio stream has ended, e.g. because the microphone was\nturned off.\n\nThis should only be sent when automatic activity detection is enabled\n(which is the default).\n\nThe client can reopen the stream by sending an audio message.\n */\n audioStreamEnd?: boolean;\n /** The realtime video input stream. */\n video?: Blob;\n /** The realtime text input stream. */\n text?: string;\n /** Marks the start of user activity. */\n activityStart?: ActivityStart;\n /** Marks the end of user activity. */\n activityEnd?: ActivityEnd;\n}\n\n/** Client generated response to a `ToolCall` received from the server.\n\n Individual `FunctionResponse` objects are matched to the respective\n `FunctionCall` objects by the `id` field.\n\n Note that in the unary and server-streaming GenerateContent APIs function\n calling happens by exchanging the `Content` parts, while in the bidi\n GenerateContent APIs function calling happens over this dedicated set of\n messages.\n */\nexport class LiveClientToolResponse {\n /** The response to the function calls. */\n functionResponses?: FunctionResponse[];\n}\n\n/** Parameters for sending realtime input to the live API. */\nexport declare interface LiveSendRealtimeInputParameters {\n /** Realtime input to send to the session. */\n media?: BlobImageUnion;\n /** The realtime audio input stream. */\n audio?: Blob;\n /** \nIndicates that the audio stream has ended, e.g. because the microphone was\nturned off.\n\nThis should only be sent when automatic activity detection is enabled\n(which is the default).\n\nThe client can reopen the stream by sending an audio message.\n */\n audioStreamEnd?: boolean;\n /** The realtime video input stream. */\n video?: BlobImageUnion;\n /** The realtime text input stream. */\n text?: string;\n /** Marks the start of user activity. */\n activityStart?: ActivityStart;\n /** Marks the end of user activity. */\n activityEnd?: ActivityEnd;\n}\n\n/** Messages sent by the client in the API call. */\nexport declare interface LiveClientMessage {\n /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */\n setup?: LiveClientSetup;\n /** Incremental update of the current conversation delivered from the client. */\n clientContent?: LiveClientContent;\n /** User input that is sent in real time. */\n realtimeInput?: LiveClientRealtimeInput;\n /** Response to a `ToolCallMessage` received from the server. */\n toolResponse?: LiveClientToolResponse;\n}\n\n/** Session config for the API connection. */\nexport declare interface LiveConnectConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The generation configuration for the session. */\n generationConfig?: GenerationConfig;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return. Defaults to AUDIO if not specified.\n */\n responseModalities?: Modality[];\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfig;\n /** If enabled, the model will detect emotions and adapt its responses accordingly. */\n enableAffectiveDialog?: boolean;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n /** Configures session resumption mechanism.\n\nIf included the server will send SessionResumptionUpdate messages. */\n sessionResumption?: SessionResumptionConfig;\n /** The transcription of the input aligns with the input audio language.\n */\n inputAudioTranscription?: AudioTranscriptionConfig;\n /** The transcription of the output aligns with the language code\n specified for the output audio.\n */\n outputAudioTranscription?: AudioTranscriptionConfig;\n /** Configures the realtime input behavior in BidiGenerateContent. */\n realtimeInputConfig?: RealtimeInputConfig;\n /** Configures context window compression mechanism.\n\n If included, server will compress context window to fit into given length. */\n contextWindowCompression?: ContextWindowCompressionConfig;\n /** Configures the proactivity of the model. This allows the model to respond proactively to\n the input and to ignore irrelevant input. */\n proactivity?: ProactivityConfig;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveConnectParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** callbacks */\n callbacks: LiveCallbacks;\n /** Optional configuration parameters for the request.\n */\n config?: LiveConnectConfig;\n}\n\n/** Parameters for initializing a new chat session.\n\n These parameters are used when creating a chat session with the\n `chats.create()` method.\n */\nexport declare interface CreateChatParameters {\n /** The name of the model to use for the chat session.\n\n For example: 'gemini-2.0-flash', 'gemini-2.0-flash-lite', etc. See Gemini API\n docs to find the available models.\n */\n model: string;\n /** Config for the entire chat session.\n\n This config applies to all requests within the session\n unless overridden by a per-request `config` in `SendMessageParameters`.\n */\n config?: GenerateContentConfig;\n /** The initial conversation history for the chat session.\n\n This allows you to start the chat with a pre-existing history. The history\n must be a list of `Content` alternating between 'user' and 'model' roles.\n It should start with a 'user' message.\n */\n history?: Content[];\n}\n\n/** Parameters for sending a message within a chat session.\n\n These parameters are used with the `chat.sendMessage()` method.\n */\nexport declare interface SendMessageParameters {\n /** The message to send to the model.\n\n The SDK will combine all parts into a single 'user' content to send to\n the model.\n */\n message: PartListUnion;\n /** Config for this specific request.\n\n Please note that the per-request config does not change the chat level\n config, nor inherit from it. If you intend to use some values from the\n chat's default config, you must explicitly copy them into this per-request\n config.\n */\n config?: GenerateContentConfig;\n}\n\n/** Parameters for sending client content to the live API. */\nexport declare interface LiveSendClientContentParameters {\n /** Client content to send to the session. */\n turns?: ContentListUnion;\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Parameters for sending tool responses to the live API. */\nexport class LiveSendToolResponseParameters {\n /** Tool responses to send to the session. */\n functionResponses: FunctionResponse[] | FunctionResponse = [];\n}\n\n/** Message to be sent by the system when connecting to the API. */\nexport declare interface LiveMusicClientSetup {\n /** The model's resource name. Format: `models/{model}`. */\n model?: string;\n}\n\n/** Maps a prompt to a relative weight to steer music generation. */\nexport declare interface WeightedPrompt {\n /** Text prompt. */\n text?: string;\n /** Weight of the prompt. The weight is used to control the relative\n importance of the prompt. Higher weights are more important than lower\n weights.\n\n Weight must not be 0. Weights of all weighted_prompts in this\n LiveMusicClientContent message will be normalized. */\n weight?: number;\n}\n\n/** User input to start or steer the music. */\nexport declare interface LiveMusicClientContent {\n /** Weighted prompts as the model input. */\n weightedPrompts?: WeightedPrompt[];\n}\n\n/** Configuration for music generation. */\nexport declare interface LiveMusicGenerationConfig {\n /** Controls the variance in audio generation. Higher values produce\n higher variance. Range is [0.0, 3.0]. */\n temperature?: number;\n /** Controls how the model selects tokens for output. Samples the topK\n tokens with the highest probabilities. Range is [1, 1000]. */\n topK?: number;\n /** Seeds audio generation. If not set, the request uses a randomly\n generated seed. */\n seed?: number;\n /** Controls how closely the model follows prompts.\n Higher guidance follows more closely, but will make transitions more\n abrupt. Range is [0.0, 6.0]. */\n guidance?: number;\n /** Beats per minute. Range is [60, 200]. */\n bpm?: number;\n /** Density of sounds. Range is [0.0, 1.0]. */\n density?: number;\n /** Brightness of the music. Range is [0.0, 1.0]. */\n brightness?: number;\n /** Scale of the generated music. */\n scale?: Scale;\n /** Whether the audio output should contain bass. */\n muteBass?: boolean;\n /** Whether the audio output should contain drums. */\n muteDrums?: boolean;\n /** Whether the audio output should contain only bass and drums. */\n onlyBassAndDrums?: boolean;\n /** The mode of music generation. Default mode is QUALITY. */\n musicGenerationMode?: MusicGenerationMode;\n}\n\n/** Messages sent by the client in the LiveMusicClientMessage call. */\nexport declare interface LiveMusicClientMessage {\n /** Message to be sent in the first (and only in the first) `LiveMusicClientMessage`.\n Clients should wait for a `LiveMusicSetupComplete` message before\n sending any additional messages. */\n setup?: LiveMusicClientSetup;\n /** User input to influence music generation. */\n clientContent?: LiveMusicClientContent;\n /** Configuration for music generation. */\n musicGenerationConfig?: LiveMusicGenerationConfig;\n /** Playback control signal for the music generation. */\n playbackControl?: LiveMusicPlaybackControl;\n}\n\n/** Sent in response to a `LiveMusicClientSetup` message from the client. */\nexport declare interface LiveMusicServerSetupComplete {}\n\n/** Prompts and config used for generating this audio chunk. */\nexport declare interface LiveMusicSourceMetadata {\n /** Weighted prompts for generating this audio chunk. */\n clientContent?: LiveMusicClientContent;\n /** Music generation config for generating this audio chunk. */\n musicGenerationConfig?: LiveMusicGenerationConfig;\n}\n\n/** Representation of an audio chunk. */\nexport declare interface AudioChunk {\n /** Raw bytes of audio data.\n * @remarks Encoded as base64 string. */\n data?: string;\n /** MIME type of the audio chunk. */\n mimeType?: string;\n /** Prompts and config used for generating this audio chunk. */\n sourceMetadata?: LiveMusicSourceMetadata;\n}\n\n/** Server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time.\n Clients may choose to buffer and play it out in real time.\n */\nexport declare interface LiveMusicServerContent {\n /** The audio chunks that the model has generated. */\n audioChunks?: AudioChunk[];\n}\n\n/** A prompt that was filtered with the reason. */\nexport declare interface LiveMusicFilteredPrompt {\n /** The text prompt that was filtered. */\n text?: string;\n /** The reason the prompt was filtered. */\n filteredReason?: string;\n}\n\n/** Response message for the LiveMusicClientMessage call. */\nexport class LiveMusicServerMessage {\n /** Message sent in response to a `LiveMusicClientSetup` message from the client.\n Clients should wait for this message before sending any additional messages. */\n setupComplete?: LiveMusicServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveMusicServerContent;\n /** A prompt that was filtered with the reason. */\n filteredPrompt?: LiveMusicFilteredPrompt;\n /**\n * Returns the first audio chunk from the server content, if present.\n *\n * @remarks\n * If there are no audio chunks in the response, undefined will be returned.\n */\n get audioChunk(): AudioChunk | undefined {\n if (\n this.serverContent &&\n this.serverContent.audioChunks &&\n this.serverContent.audioChunks.length > 0\n ) {\n return this.serverContent.audioChunks[0];\n }\n return undefined;\n }\n}\n\n/** Callbacks for the realtime music API. */\nexport interface LiveMusicCallbacks {\n /**\n * Called when a message is received from the server.\n */\n onmessage: (e: LiveMusicServerMessage) => void;\n /**\n * Called when an error occurs.\n */\n onerror?: ((e: ErrorEvent) => void) | null;\n /**\n * Called when the websocket connection is closed.\n */\n onclose?: ((e: CloseEvent) => void) | null;\n}\n\n/** Parameters for the upload file method. */\nexport interface UploadFileParameters {\n /** The string path to the file to be uploaded or a Blob object. */\n file: string | globalThis.Blob;\n /** Configuration that contains optional parameters. */\n config?: UploadFileConfig;\n}\n\n/**\n * CallableTool is an invokable tool that can be executed with external\n * application (e.g., via Model Context Protocol) or local functions with\n * function calling.\n */\nexport interface CallableTool {\n /**\n * Returns tool that can be called by Gemini.\n */\n tool(): Promise;\n /**\n * Executes the callable tool with the given function call arguments and\n * returns the response parts from the tool execution.\n */\n callTool(functionCalls: FunctionCall[]): Promise;\n}\n\n/**\n * CallableToolConfig is the configuration for a callable tool.\n */\nexport interface CallableToolConfig {\n /**\n * Specifies the model's behavior after invoking this tool.\n */\n behavior?: Behavior;\n /**\n * Timeout for remote calls in milliseconds. Note this timeout applies only to\n * tool remote calls, and not making HTTP requests to the API. */\n timeout?: number;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveMusicConnectParameters {\n /** The model's resource name. */\n model: string;\n /** Callbacks invoked on server events. */\n callbacks: LiveMusicCallbacks;\n}\n\n/** Parameters for setting config for the live music API. */\nexport declare interface LiveMusicSetConfigParameters {\n /** Configuration for music generation. */\n musicGenerationConfig: LiveMusicGenerationConfig;\n}\n\n/** Parameters for setting weighted prompts for the live music API. */\nexport declare interface LiveMusicSetWeightedPromptsParameters {\n /** A map of text prompts to weights to use for the generation request. */\n weightedPrompts: WeightedPrompt[];\n}\n\n/** Config for auth_tokens.create parameters. */\nexport declare interface AuthToken {\n /** The name of the auth token. */\n name?: string;\n}\n\n/** Config for LiveConnectConstraints for Auth Token creation. */\nexport declare interface LiveConnectConstraints {\n /** ID of the model to configure in the ephemeral token for Live API.\n For a list of models, see `Gemini models\n `. */\n model?: string;\n /** Configuration specific to Live API connections created using this token. */\n config?: LiveConnectConfig;\n}\n\n/** Optional parameters. */\nexport declare interface CreateAuthTokenConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** An optional time after which, when using the resulting token,\n messages in Live API sessions will be rejected. (Gemini may\n preemptively close the session after this time.)\n\n If not set then this defaults to 30 minutes in the future. If set, this\n value must be less than 20 hours in the future. */\n expireTime?: string;\n /** The time after which new Live API sessions using the token\n resulting from this request will be rejected.\n\n If not set this defaults to 60 seconds in the future. If set, this value\n must be less than 20 hours in the future. */\n newSessionExpireTime?: string;\n /** The number of times the token can be used. If this value is zero\n then no limit is applied. Default is 1. Resuming a Live API session does\n not count as a use. */\n uses?: number;\n /** Configuration specific to Live API connections created using this token. */\n liveConnectConstraints?: LiveConnectConstraints;\n /** Additional fields to lock in the effective LiveConnectParameters. */\n lockAdditionalFields?: string[];\n}\n\n/** Config for auth_tokens.create parameters. */\nexport declare interface CreateAuthTokenParameters {\n /** Optional parameters for the request. */\n config?: CreateAuthTokenConfig;\n}\n\n/** Supervised fine-tuning job creation parameters - optional fields. */\nexport declare interface CreateTuningJobParameters {\n /** The base model that is being tuned, e.g., \"gemini-2.5-flash\". */\n baseModel: string;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDataset: TuningDataset;\n /** Configuration for the tuning job. */\n config?: CreateTuningJobConfig;\n}\n\nexport type BlobImageUnion = Blob;\n\nexport type PartUnion = Part | string;\n\nexport type PartListUnion = PartUnion[] | PartUnion;\n\nexport type ContentUnion = Content | PartUnion[] | PartUnion;\n\nexport type ContentListUnion = Content | Content[] | PartUnion | PartUnion[];\n\nexport type SchemaUnion = Schema | unknown;\n\nexport type SpeechConfigUnion = SpeechConfig | string;\n\nexport type ToolUnion = Tool | CallableTool;\n\nexport type ToolListUnion = ToolUnion[];\n\nexport type DownloadableFileUnion = string | File | GeneratedVideo | Video;\n\nexport type BatchJobSourceUnion = BatchJobSource | InlinedRequest[] | string;\n\nexport type BatchJobDestinationUnion = BatchJobDestination | string;\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {Tool as McpTool} from '@modelcontextprotocol/sdk/types.js';\n\nimport {ApiClient} from './_api_client.js';\nimport * as baseTransformers from './_base_transformers.js';\nimport * as types from './types.js';\n\nexport function tModel(apiClient: ApiClient, model: string | unknown): string {\n if (!model || typeof model !== 'string') {\n throw new Error('model is required and must be a string');\n }\n\n if (apiClient.isVertexAI()) {\n if (\n model.startsWith('publishers/') ||\n model.startsWith('projects/') ||\n model.startsWith('models/')\n ) {\n return model;\n } else if (model.indexOf('/') >= 0) {\n const parts = model.split('/', 2);\n return `publishers/${parts[0]}/models/${parts[1]}`;\n } else {\n return `publishers/google/models/${model}`;\n }\n } else {\n if (model.startsWith('models/') || model.startsWith('tunedModels/')) {\n return model;\n } else {\n return `models/${model}`;\n }\n }\n}\n\nexport function tCachesModel(\n apiClient: ApiClient,\n model: string | unknown,\n): string {\n const transformedModel = tModel(apiClient, model as string);\n if (!transformedModel) {\n return '';\n }\n\n if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) {\n // vertex caches only support model name start with projects.\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`;\n } else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) {\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`;\n } else {\n return transformedModel;\n }\n}\n\nexport function tBlobs(\n blobs: types.BlobImageUnion | types.BlobImageUnion[],\n): types.Blob[] {\n if (Array.isArray(blobs)) {\n return blobs.map((blob) => tBlob(blob));\n } else {\n return [tBlob(blobs)];\n }\n}\n\nexport function tBlob(blob: types.BlobImageUnion): types.Blob {\n if (typeof blob === 'object' && blob !== null) {\n return blob;\n }\n\n throw new Error(\n `Could not parse input as Blob. Unsupported blob type: ${typeof blob}`,\n );\n}\n\nexport function tImageBlob(blob: types.BlobImageUnion): types.Blob {\n const transformedBlob = tBlob(blob);\n if (\n transformedBlob.mimeType &&\n transformedBlob.mimeType.startsWith('image/')\n ) {\n return transformedBlob;\n }\n throw new Error(`Unsupported mime type: ${transformedBlob.mimeType!}`);\n}\n\nexport function tAudioBlob(blob: types.Blob): types.Blob {\n const transformedBlob = tBlob(blob);\n if (\n transformedBlob.mimeType &&\n transformedBlob.mimeType.startsWith('audio/')\n ) {\n return transformedBlob;\n }\n throw new Error(`Unsupported mime type: ${transformedBlob.mimeType!}`);\n}\n\nexport function tPart(origin?: types.PartUnion | null): types.Part {\n if (origin === null || origin === undefined) {\n throw new Error('PartUnion is required');\n }\n if (typeof origin === 'object') {\n return origin;\n }\n if (typeof origin === 'string') {\n return {text: origin};\n }\n throw new Error(`Unsupported part type: ${typeof origin}`);\n}\n\nexport function tParts(origin?: types.PartListUnion | null): types.Part[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('PartListUnion is required');\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tPart(item as types.PartUnion)!);\n }\n return [tPart(origin)!];\n}\n\nfunction _isContent(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'parts' in origin &&\n Array.isArray(origin.parts)\n );\n}\n\nfunction _isFunctionCallPart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionCall' in origin\n );\n}\n\nfunction _isFunctionResponsePart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionResponse' in origin\n );\n}\n\nexport function tContent(origin?: types.ContentUnion): types.Content {\n if (origin === null || origin === undefined) {\n throw new Error('ContentUnion is required');\n }\n if (_isContent(origin)) {\n // _isContent is a utility function that checks if the\n // origin is a Content.\n return origin as types.Content;\n }\n\n return {\n role: 'user',\n parts: tParts(origin as types.PartListUnion)!,\n };\n}\n\nexport function tContentsForEmbed(\n apiClient: ApiClient,\n origin: types.ContentListUnion,\n): types.ContentUnion[] {\n if (!origin) {\n return [];\n }\n if (apiClient.isVertexAI() && Array.isArray(origin)) {\n return origin.flatMap((item) => {\n const content = tContent(item as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n });\n } else if (apiClient.isVertexAI()) {\n const content = tContent(origin as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tContent(item as types.ContentUnion)!);\n }\n return [tContent(origin as types.ContentUnion)!];\n}\n\nexport function tContents(origin?: types.ContentListUnion): types.Content[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('contents are required');\n }\n if (!Array.isArray(origin)) {\n // If it's not an array, it's a single content or a single PartUnion.\n if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) {\n throw new Error(\n 'To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them',\n );\n }\n return [tContent(origin as types.ContentUnion)];\n }\n\n const result: types.Content[] = [];\n const accumulatedParts: types.PartUnion[] = [];\n const isContentArray = _isContent(origin[0]);\n\n for (const item of origin) {\n const isContent = _isContent(item);\n\n if (isContent != isContentArray) {\n throw new Error(\n 'Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them',\n );\n }\n\n if (isContent) {\n // `isContent` contains the result of _isContent, which is a utility\n // function that checks if the item is a Content.\n result.push(item as types.Content);\n } else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) {\n throw new Error(\n 'To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them',\n );\n } else {\n accumulatedParts.push(item as types.PartUnion);\n }\n }\n\n if (!isContentArray) {\n result.push({role: 'user', parts: tParts(accumulatedParts)});\n }\n return result;\n}\n\n/*\nTransform the type field from an array of types to an array of anyOf fields.\nExample:\n {type: ['STRING', 'NUMBER']}\nwill be transformed to\n {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]}\n*/\nfunction flattenTypeArrayToAnyOf(\n typeList: string[],\n resultingSchema: types.Schema,\n) {\n if (typeList.includes('null')) {\n resultingSchema['nullable'] = true;\n }\n const listWithoutNull = typeList.filter((type) => type !== 'null');\n\n if (listWithoutNull.length === 1) {\n resultingSchema['type'] = Object.values(types.Type).includes(\n listWithoutNull[0].toUpperCase() as types.Type,\n )\n ? (listWithoutNull[0].toUpperCase() as types.Type)\n : types.Type.TYPE_UNSPECIFIED;\n } else {\n resultingSchema['anyOf'] = [];\n for (const i of listWithoutNull) {\n resultingSchema['anyOf'].push({\n 'type': Object.values(types.Type).includes(\n i.toUpperCase() as types.Type,\n )\n ? (i.toUpperCase() as types.Type)\n : types.Type.TYPE_UNSPECIFIED,\n });\n }\n }\n}\n\nexport function processJsonSchema(\n _jsonSchema: types.Schema | Record,\n): types.Schema {\n const genAISchema: types.Schema = {};\n const schemaFieldNames = ['items'];\n const listSchemaFieldNames = ['anyOf'];\n const dictSchemaFieldNames = ['properties'];\n\n if (_jsonSchema['type'] && _jsonSchema['anyOf']) {\n throw new Error('type and anyOf cannot be both populated.');\n }\n\n /*\n This is to handle the nullable array or object. The _jsonSchema will\n be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The\n logic is to check if anyOf has 2 elements and one of the element is null,\n if so, the anyOf field is unnecessary, so we need to get rid of the anyOf\n field and make the schema nullable. Then use the other element as the new\n _jsonSchema for processing. This is because the backend doesn't have a null\n type.\n This has to be checked before we process any other fields.\n For example:\n const objectNullable = z.object({\n nullableArray: z.array(z.string()).nullable(),\n });\n Will have the raw _jsonSchema as:\n {\n type: 'OBJECT',\n properties: {\n nullableArray: {\n anyOf: [\n {type: 'null'},\n {\n type: 'array',\n items: {type: 'string'},\n },\n ],\n }\n },\n required: [ 'nullableArray' ],\n }\n Will result in following schema compatible with Gemini API:\n {\n type: 'OBJECT',\n properties: {\n nullableArray: {\n nullable: true,\n type: 'ARRAY',\n items: {type: 'string'},\n }\n },\n required: [ 'nullableArray' ],\n }\n */\n const incomingAnyOf = _jsonSchema['anyOf'] as Record[];\n if (incomingAnyOf != null && incomingAnyOf.length == 2) {\n if (incomingAnyOf[0]!['type'] === 'null') {\n genAISchema['nullable'] = true;\n _jsonSchema = incomingAnyOf![1];\n } else if (incomingAnyOf[1]!['type'] === 'null') {\n genAISchema['nullable'] = true;\n _jsonSchema = incomingAnyOf![0];\n }\n }\n\n if (_jsonSchema['type'] instanceof Array) {\n flattenTypeArrayToAnyOf(_jsonSchema['type'], genAISchema);\n }\n\n for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) {\n // Skip if the fieldvalue is undefined or null.\n if (fieldValue == null) {\n continue;\n }\n\n if (fieldName == 'type') {\n if (fieldValue === 'null') {\n throw new Error(\n 'type: null can not be the only possible type for the field.',\n );\n }\n if (fieldValue instanceof Array) {\n // we have already handled the type field with array of types in the\n // beginning of this function.\n continue;\n }\n genAISchema['type'] = Object.values(types.Type).includes(\n fieldValue.toUpperCase() as types.Type,\n )\n ? fieldValue.toUpperCase()\n : types.Type.TYPE_UNSPECIFIED;\n } else if (schemaFieldNames.includes(fieldName)) {\n (genAISchema as Record)[fieldName] =\n processJsonSchema(fieldValue);\n } else if (listSchemaFieldNames.includes(fieldName)) {\n const listSchemaFieldValue: Array = [];\n for (const item of fieldValue) {\n if (item['type'] == 'null') {\n genAISchema['nullable'] = true;\n continue;\n }\n listSchemaFieldValue.push(\n processJsonSchema(item as Record),\n );\n }\n (genAISchema as Record)[fieldName] =\n listSchemaFieldValue;\n } else if (dictSchemaFieldNames.includes(fieldName)) {\n const dictSchemaFieldValue: Record = {};\n for (const [key, value] of Object.entries(\n fieldValue as Record,\n )) {\n dictSchemaFieldValue[key] = processJsonSchema(\n value as Record,\n );\n }\n (genAISchema as Record)[fieldName] =\n dictSchemaFieldValue;\n } else {\n // additionalProperties is not included in JSONSchema, skipping it.\n if (fieldName === 'additionalProperties') {\n continue;\n }\n (genAISchema as Record)[fieldName] = fieldValue;\n }\n }\n return genAISchema;\n}\n\n// we take the unknown in the schema field because we want enable user to pass\n// the output of major schema declaration tools without casting. Tools such as\n// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type\n// or object, see details in\n// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7\n// typebox can return unknown, see details in\n// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35\n// Note: proper json schemas with the $schema field set never arrive to this\n// transformer. Schemas with $schema are routed to the equivalent API json\n// schema field.\nexport function tSchema(schema: types.Schema | unknown): types.Schema {\n return processJsonSchema(schema as types.Schema);\n}\n\nexport function tSpeechConfig(\n speechConfig: types.SpeechConfigUnion,\n): types.SpeechConfig {\n if (typeof speechConfig === 'object') {\n return speechConfig;\n } else if (typeof speechConfig === 'string') {\n return {\n voiceConfig: {\n prebuiltVoiceConfig: {\n voiceName: speechConfig,\n },\n },\n };\n } else {\n throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`);\n }\n}\n\nexport function tLiveSpeechConfig(\n speechConfig: types.SpeechConfig | object,\n): types.SpeechConfig {\n if ('multiSpeakerVoiceConfig' in speechConfig) {\n throw new Error(\n 'multiSpeakerVoiceConfig is not supported in the live API.',\n );\n }\n return speechConfig;\n}\n\nexport function tTool(tool: types.Tool): types.Tool {\n if (tool.functionDeclarations) {\n for (const functionDeclaration of tool.functionDeclarations) {\n if (functionDeclaration.parameters) {\n if (!Object.keys(functionDeclaration.parameters).includes('$schema')) {\n functionDeclaration.parameters = processJsonSchema(\n functionDeclaration.parameters,\n );\n } else {\n if (!functionDeclaration.parametersJsonSchema) {\n functionDeclaration.parametersJsonSchema =\n functionDeclaration.parameters;\n delete functionDeclaration.parameters;\n }\n }\n }\n if (functionDeclaration.response) {\n if (!Object.keys(functionDeclaration.response).includes('$schema')) {\n functionDeclaration.response = processJsonSchema(\n functionDeclaration.response,\n );\n } else {\n if (!functionDeclaration.responseJsonSchema) {\n functionDeclaration.responseJsonSchema =\n functionDeclaration.response;\n delete functionDeclaration.response;\n }\n }\n }\n }\n }\n return tool;\n}\n\nexport function tTools(tools: types.ToolListUnion | unknown): types.Tool[] {\n // Check if the incoming type is defined.\n if (tools === undefined || tools === null) {\n throw new Error('tools is required');\n }\n if (!Array.isArray(tools)) {\n throw new Error('tools is required and must be an array of Tools');\n }\n const result: types.Tool[] = [];\n for (const tool of tools) {\n result.push(tool as types.Tool);\n }\n return result;\n}\n\n/**\n * Prepends resource name with project, location, resource_prefix if needed.\n *\n * @param client The API client.\n * @param resourceName The resource name.\n * @param resourcePrefix The resource prefix.\n * @param splitsAfterPrefix The number of splits after the prefix.\n * @returns The completed resource name.\n *\n * Examples:\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/bar/locations/us-west1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'projects/foo/locations/us-central1/cachedContents/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/foo/locations/us-central1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns 'cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'some/wrong/cachedContents/resource/name/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * # client.vertexai = True\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * -> 'some/wrong/resource/name/123'\n * ```\n */\nfunction resourceName(\n client: ApiClient,\n resourceName: string,\n resourcePrefix: string,\n splitsAfterPrefix: number = 1,\n): string {\n const shouldAppendPrefix =\n !resourceName.startsWith(`${resourcePrefix}/`) &&\n resourceName.split('/').length === splitsAfterPrefix;\n if (client.isVertexAI()) {\n if (resourceName.startsWith('projects/')) {\n return resourceName;\n } else if (resourceName.startsWith('locations/')) {\n return `projects/${client.getProject()}/${resourceName}`;\n } else if (resourceName.startsWith(`${resourcePrefix}/`)) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`;\n } else if (shouldAppendPrefix) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`;\n } else {\n return resourceName;\n }\n }\n if (shouldAppendPrefix) {\n return `${resourcePrefix}/${resourceName}`;\n }\n return resourceName;\n}\n\nexport function tCachedContentName(\n apiClient: ApiClient,\n name: string | unknown,\n): string {\n if (typeof name !== 'string') {\n throw new Error('name must be a string');\n }\n return resourceName(apiClient, name, 'cachedContents');\n}\n\nexport function tTuningJobStatus(status: string | unknown): string {\n switch (status) {\n case 'STATE_UNSPECIFIED':\n return 'JOB_STATE_UNSPECIFIED';\n case 'CREATING':\n return 'JOB_STATE_RUNNING';\n case 'ACTIVE':\n return 'JOB_STATE_SUCCEEDED';\n case 'FAILED':\n return 'JOB_STATE_FAILED';\n default:\n return status as string;\n }\n}\n\nexport function tBytes(fromImageBytes: string | unknown): string {\n return baseTransformers.tBytes(fromImageBytes);\n}\n\nfunction _isFile(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'name' in origin\n );\n}\n\nexport function isGeneratedVideo(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'video' in origin\n );\n}\n\nexport function isVideo(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'uri' in origin\n );\n}\n\nexport function tFileName(\n fromName: string | types.File | types.GeneratedVideo | types.Video,\n): string | undefined {\n let name: string | undefined;\n\n if (_isFile(fromName)) {\n name = (fromName as types.File).name;\n }\n if (isVideo(fromName)) {\n name = (fromName as types.Video).uri;\n if (name === undefined) {\n return undefined;\n }\n }\n if (isGeneratedVideo(fromName)) {\n name = (fromName as types.GeneratedVideo).video?.uri;\n if (name === undefined) {\n return undefined;\n }\n }\n if (typeof fromName === 'string') {\n name = fromName;\n }\n\n if (name === undefined) {\n throw new Error('Could not extract file name from the provided input.');\n }\n\n if (name.startsWith('https://')) {\n const suffix = name.split('files/')[1];\n const match = suffix.match(/[a-z0-9]+/);\n if (match === null) {\n throw new Error(`Could not extract file name from URI ${name}`);\n }\n name = match[0];\n } else if (name.startsWith('files/')) {\n name = name.split('files/')[1];\n }\n return name;\n}\n\nexport function tModelsUrl(\n apiClient: ApiClient,\n baseModels: boolean | unknown,\n): string {\n let res: string;\n if (apiClient.isVertexAI()) {\n res = baseModels ? 'publishers/google/models' : 'models';\n } else {\n res = baseModels ? 'models' : 'tunedModels';\n }\n return res;\n}\n\nexport function tExtractModels(response: unknown): Record[] {\n for (const key of ['models', 'tunedModels', 'publisherModels']) {\n if (hasField(response, key)) {\n return (response as Record)[key] as Record<\n string,\n unknown\n >[];\n }\n }\n return [];\n}\n\nfunction hasField(data: unknown, fieldName: string): boolean {\n return data !== null && typeof data === 'object' && fieldName in data;\n}\n\nexport function mcpToGeminiTool(\n mcpTool: McpTool,\n config: types.CallableToolConfig = {},\n): types.Tool {\n const mcpToolSchema = mcpTool as Record;\n const functionDeclaration: Record = {\n name: mcpToolSchema['name'],\n description: mcpToolSchema['description'],\n parametersJsonSchema: mcpToolSchema['inputSchema'],\n };\n if (config.behavior) {\n functionDeclaration['behavior'] = config.behavior;\n }\n\n const geminiTool = {\n functionDeclarations: [\n functionDeclaration as unknown as types.FunctionDeclaration,\n ],\n };\n\n return geminiTool;\n}\n\n/**\n * Converts a list of MCP tools to a single Gemini tool with a list of function\n * declarations.\n */\nexport function mcpToolsToGeminiTool(\n mcpTools: McpTool[],\n config: types.CallableToolConfig = {},\n): types.Tool {\n const functionDeclarations: types.FunctionDeclaration[] = [];\n const toolNames = new Set();\n for (const mcpTool of mcpTools) {\n const mcpToolName = mcpTool.name as string;\n if (toolNames.has(mcpToolName)) {\n throw new Error(\n `Duplicate function name ${\n mcpToolName\n } found in MCP tools. Please ensure function names are unique.`,\n );\n }\n toolNames.add(mcpToolName);\n const geminiTool = mcpToGeminiTool(mcpTool, config);\n if (geminiTool.functionDeclarations) {\n functionDeclarations.push(...geminiTool.functionDeclarations);\n }\n }\n\n return {functionDeclarations: functionDeclarations};\n}\n\n// Transforms a source input into a BatchJobSource object with validation.\nexport function tBatchJobSource(\n apiClient: ApiClient,\n src: string | types.InlinedRequest[] | types.BatchJobSource,\n): types.BatchJobSource {\n if (typeof src !== 'string' && !Array.isArray(src)) {\n if (apiClient && apiClient.isVertexAI()) {\n if (src.gcsUri && src.bigqueryUri) {\n throw new Error('Only one of `gcsUri` or `bigqueryUri` can be set.');\n } else if (!src.gcsUri && !src.bigqueryUri) {\n throw new Error('One of `gcsUri` or `bigqueryUri` must be set.');\n }\n } else {\n // Logic for non-Vertex AI client (inlined_requests, file_name)\n if (src.inlinedRequests && src.fileName) {\n throw new Error(\n 'Only one of `inlinedRequests` or `fileName` can be set.',\n );\n } else if (!src.inlinedRequests && !src.fileName) {\n throw new Error('One of `inlinedRequests` or `fileName` must be set.');\n }\n }\n return src;\n }\n // If src is an array (list in Python)\n else if (Array.isArray(src)) {\n return {inlinedRequests: src};\n } else if (typeof src === 'string') {\n if (src.startsWith('gs://')) {\n return {\n format: 'jsonl',\n gcsUri: [src], // GCS URI is expected as an array\n };\n } else if (src.startsWith('bq://')) {\n return {\n format: 'bigquery',\n bigqueryUri: src,\n };\n } else if (src.startsWith('files/')) {\n return {\n fileName: src,\n };\n }\n }\n throw new Error(`Unsupported source: ${src}`);\n}\n\nexport function tBatchJobDestination(\n dest: string | types.BatchJobDestination,\n): types.BatchJobDestination {\n if (typeof dest !== 'string') {\n return dest as types.BatchJobDestination;\n }\n const destString = dest as string;\n if (destString.startsWith('gs://')) {\n return {\n format: 'jsonl',\n gcsUri: destString,\n };\n } else if (destString.startsWith('bq://')) {\n return {\n format: 'bigquery',\n bigqueryUri: destString,\n };\n } else {\n throw new Error(`Unsupported destination: ${destString}`);\n }\n}\n\nexport function tBatchJobName(apiClient: ApiClient, name: unknown): string {\n const nameString = name as string;\n if (!apiClient.isVertexAI()) {\n const mldevPattern = /batches\\/[^/]+$/;\n\n if (mldevPattern.test(nameString)) {\n return nameString.split('/').pop() as string;\n } else {\n throw new Error(`Invalid batch job name: ${nameString}.`);\n }\n }\n\n const vertexPattern =\n /^projects\\/[^/]+\\/locations\\/[^/]+\\/batchPredictionJobs\\/[^/]+$/;\n\n if (vertexPattern.test(nameString)) {\n return nameString.split('/').pop() as string;\n } else if (/^\\d+$/.test(nameString)) {\n return nameString;\n } else {\n throw new Error(`Invalid batch job name: ${nameString}.`);\n }\n}\n\nexport function tJobState(state: unknown): string {\n const stateString = state as string;\n if (stateString === 'BATCH_STATE_UNSPECIFIED') {\n return 'JOB_STATE_UNSPECIFIED';\n } else if (stateString === 'BATCH_STATE_PENDING') {\n return 'JOB_STATE_PENDING';\n } else if (stateString === 'BATCH_STATE_SUCCEEDED') {\n return 'JOB_STATE_SUCCEEDED';\n } else if (stateString === 'BATCH_STATE_FAILED') {\n return 'JOB_STATE_FAILED';\n } else if (stateString === 'BATCH_STATE_CANCELLED') {\n return 'JOB_STATE_CANCELLED';\n } else {\n return stateString;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined\n ) {\n throw new Error(\n 'modelSelectionConfig parameter is not supported in Gemini API.',\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function inlinedRequestToMldev(\n apiClient: ApiClient,\n fromObject: types.InlinedRequest,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['request', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['request', 'contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['request', 'generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function batchJobSourceToMldev(\n apiClient: ApiClient,\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['format']) !== undefined) {\n throw new Error('format parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['bigqueryUri']) !== undefined) {\n throw new Error('bigqueryUri parameter is not supported in Gemini API.');\n }\n\n const fromFileName = common.getValueByPath(fromObject, ['fileName']);\n if (fromFileName != null) {\n common.setValueByPath(toObject, ['fileName'], fromFileName);\n }\n\n const fromInlinedRequests = common.getValueByPath(fromObject, [\n 'inlinedRequests',\n ]);\n if (fromInlinedRequests != null) {\n let transformedList = fromInlinedRequests;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return inlinedRequestToMldev(apiClient, item);\n });\n }\n common.setValueByPath(toObject, ['requests', 'requests'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createBatchJobConfigToMldev(\n fromObject: types.CreateBatchJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['batch', 'displayName'],\n fromDisplayName,\n );\n }\n\n if (common.getValueByPath(fromObject, ['dest']) !== undefined) {\n throw new Error('dest parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function createBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['src']);\n if (fromSrc != null) {\n common.setValueByPath(\n toObject,\n ['batch', 'inputConfig'],\n batchJobSourceToMldev(apiClient, t.tBatchJobSource(apiClient, fromSrc)),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createBatchJobConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function cancelBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CancelBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsConfigToMldev(\n fromObject: types.ListBatchJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n if (common.getValueByPath(fromObject, ['filter']) !== undefined) {\n throw new Error('filter parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function listBatchJobsParametersToMldev(\n fromObject: types.ListBatchJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listBatchJobsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function batchJobSourceToVertex(\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['instancesFormat'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsSource', 'uris'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, ['bigqueryUri']);\n if (fromBigqueryUri != null) {\n common.setValueByPath(\n toObject,\n ['bigquerySource', 'inputUri'],\n fromBigqueryUri,\n );\n }\n\n if (common.getValueByPath(fromObject, ['fileName']) !== undefined) {\n throw new Error('fileName parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['inlinedRequests']) !== undefined) {\n throw new Error('inlinedRequests parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationToVertex(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['predictionsFormat'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(\n toObject,\n ['gcsDestination', 'outputUriPrefix'],\n fromGcsUri,\n );\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, ['bigqueryUri']);\n if (fromBigqueryUri != null) {\n common.setValueByPath(\n toObject,\n ['bigqueryDestination', 'outputUri'],\n fromBigqueryUri,\n );\n }\n\n if (common.getValueByPath(fromObject, ['fileName']) !== undefined) {\n throw new Error('fileName parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['inlinedResponses']) !== undefined) {\n throw new Error(\n 'inlinedResponses parameter is not supported in Vertex AI.',\n );\n }\n\n return toObject;\n}\n\nexport function createBatchJobConfigToVertex(\n fromObject: types.CreateBatchJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDest = common.getValueByPath(fromObject, ['dest']);\n if (parentObject !== undefined && fromDest != null) {\n common.setValueByPath(\n parentObject,\n ['outputConfig'],\n batchJobDestinationToVertex(t.tBatchJobDestination(fromDest)),\n );\n }\n\n return toObject;\n}\n\nexport function createBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], t.tModel(apiClient, fromModel));\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['src']);\n if (fromSrc != null) {\n common.setValueByPath(\n toObject,\n ['inputConfig'],\n batchJobSourceToVertex(t.tBatchJobSource(apiClient, fromSrc)),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createBatchJobConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function cancelBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CancelBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsConfigToVertex(\n fromObject: types.ListBatchJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsParametersToVertex(\n fromObject: types.ListBatchJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listBatchJobsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(toObject, ['content'], contentFromMldev(fromContent));\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function jobErrorFromMldev(\n fromObject: types.JobError,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n return toObject;\n}\n\nexport function inlinedResponseFromMldev(\n fromObject: types.InlinedResponse,\n): Record {\n const toObject: Record = {};\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateContentResponseFromMldev(\n fromResponse as types.GenerateContentResponse,\n ),\n );\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationFromMldev(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFileName = common.getValueByPath(fromObject, ['responsesFile']);\n if (fromFileName != null) {\n common.setValueByPath(toObject, ['fileName'], fromFileName);\n }\n\n const fromInlinedResponses = common.getValueByPath(fromObject, [\n 'inlinedResponses',\n 'inlinedResponses',\n ]);\n if (fromInlinedResponses != null) {\n let transformedList = fromInlinedResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return inlinedResponseFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['inlinedResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function batchJobFromMldev(\n fromObject: types.BatchJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, [\n 'metadata',\n 'displayName',\n ]);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['metadata', 'state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tJobState(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'createTime',\n ]);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'endTime',\n ]);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'updateTime',\n ]);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['metadata', 'model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromDest = common.getValueByPath(fromObject, ['metadata', 'output']);\n if (fromDest != null) {\n common.setValueByPath(\n toObject,\n ['dest'],\n batchJobDestinationFromMldev(fromDest),\n );\n }\n\n return toObject;\n}\n\nexport function listBatchJobsResponseFromMldev(\n fromObject: types.ListBatchJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromBatchJobs = common.getValueByPath(fromObject, ['operations']);\n if (fromBatchJobs != null) {\n let transformedList = fromBatchJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return batchJobFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['batchJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteResourceJobFromMldev(\n fromObject: types.DeleteResourceJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function jobErrorFromVertex(\n fromObject: types.JobError,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n return toObject;\n}\n\nexport function batchJobSourceFromVertex(\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['instancesFormat']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsSource', 'uris']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, [\n 'bigquerySource',\n 'inputUri',\n ]);\n if (fromBigqueryUri != null) {\n common.setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri);\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationFromVertex(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['predictionsFormat']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, [\n 'gcsDestination',\n 'outputUriPrefix',\n ]);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, [\n 'bigqueryDestination',\n 'outputUri',\n ]);\n if (fromBigqueryUri != null) {\n common.setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri);\n }\n\n return toObject;\n}\n\nexport function batchJobFromVertex(\n fromObject: types.BatchJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tJobState(fromState));\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['inputConfig']);\n if (fromSrc != null) {\n common.setValueByPath(toObject, ['src'], batchJobSourceFromVertex(fromSrc));\n }\n\n const fromDest = common.getValueByPath(fromObject, ['outputConfig']);\n if (fromDest != null) {\n common.setValueByPath(\n toObject,\n ['dest'],\n batchJobDestinationFromVertex(fromDest),\n );\n }\n\n return toObject;\n}\n\nexport function listBatchJobsResponseFromVertex(\n fromObject: types.ListBatchJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromBatchJobs = common.getValueByPath(fromObject, [\n 'batchPredictionJobs',\n ]);\n if (fromBatchJobs != null) {\n let transformedList = fromBatchJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return batchJobFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['batchJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteResourceJobFromVertex(\n fromObject: types.DeleteResourceJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError));\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Pagers for the GenAI List APIs.\n */\n\nimport * as types from '../src/types';\n\nexport enum PagedItem {\n PAGED_ITEM_BATCH_JOBS = 'batchJobs',\n PAGED_ITEM_MODELS = 'models',\n PAGED_ITEM_TUNING_JOBS = 'tuningJobs',\n PAGED_ITEM_FILES = 'files',\n PAGED_ITEM_CACHED_CONTENTS = 'cachedContents',\n}\n\ninterface PagedItemConfig {\n config?: {\n pageToken?: string;\n pageSize?: number;\n };\n}\n\ninterface PagedItemResponse {\n nextPageToken?: string;\n sdkHttpResponse?: types.HttpResponse;\n batchJobs?: T[];\n models?: T[];\n tuningJobs?: T[];\n files?: T[];\n cachedContents?: T[];\n}\n\n/**\n * Pager class for iterating through paginated results.\n */\nexport class Pager implements AsyncIterable {\n private nameInternal!: PagedItem;\n private pageInternal: T[] = [];\n private paramsInternal: PagedItemConfig = {};\n private pageInternalSize!: number;\n private sdkHttpResponseInternal?: types.HttpResponse;\n protected requestInternal!: (\n params: PagedItemConfig,\n ) => Promise>;\n protected idxInternal!: number;\n\n constructor(\n name: PagedItem,\n request: (params: PagedItemConfig) => Promise>,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.requestInternal = request;\n this.init(name, response, params);\n }\n\n private init(\n name: PagedItem,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.nameInternal = name;\n this.pageInternal = response[this.nameInternal] || [];\n\n this.sdkHttpResponseInternal = response?.sdkHttpResponse;\n this.idxInternal = 0;\n let requestParams: PagedItemConfig = {config: {}};\n if (!params || Object.keys(params).length === 0) {\n requestParams = {config: {}};\n } else if (typeof params === 'object') {\n requestParams = {...params};\n } else {\n requestParams = params;\n }\n if (requestParams['config']) {\n requestParams['config']['pageToken'] = response['nextPageToken'];\n }\n this.paramsInternal = requestParams;\n this.pageInternalSize =\n requestParams['config']?.['pageSize'] ?? this.pageInternal.length;\n }\n\n private initNextPage(response: PagedItemResponse): void {\n this.init(this.nameInternal, response, this.paramsInternal);\n }\n\n /**\n * Returns the current page, which is a list of items.\n *\n * @remarks\n * The first page is retrieved when the pager is created. The returned list of\n * items could be a subset of the entire list.\n */\n get page(): T[] {\n return this.pageInternal;\n }\n\n /**\n * Returns the type of paged item (for example, ``batch_jobs``).\n */\n get name(): PagedItem {\n return this.nameInternal;\n }\n\n /**\n * Returns the length of the page fetched each time by this pager.\n *\n * @remarks\n * The number of items in the page is less than or equal to the page length.\n */\n get pageSize(): number {\n return this.pageInternalSize;\n }\n\n /**\n * Returns the headers of the API response.\n */\n get sdkHttpResponse(): types.HttpResponse | undefined {\n return this.sdkHttpResponseInternal;\n }\n\n /**\n * Returns the parameters when making the API request for the next page.\n *\n * @remarks\n * Parameters contain a set of optional configs that can be\n * used to customize the API request. For example, the `pageToken` parameter\n * contains the token to request the next page.\n */\n get params(): PagedItemConfig {\n return this.paramsInternal;\n }\n\n /**\n * Returns the total number of items in the current page.\n */\n get pageLength(): number {\n return this.pageInternal.length;\n }\n\n /**\n * Returns the item at the given index.\n */\n getItem(index: number): T {\n return this.pageInternal[index];\n }\n\n /**\n * Returns an async iterator that support iterating through all items\n * retrieved from the API.\n *\n * @remarks\n * The iterator will automatically fetch the next page if there are more items\n * to fetch from the API.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * for await (const file of pager) {\n * console.log(file.name);\n * }\n * ```\n */\n [Symbol.asyncIterator](): AsyncIterator {\n return {\n next: async () => {\n if (this.idxInternal >= this.pageLength) {\n if (this.hasNextPage()) {\n await this.nextPage();\n } else {\n return {value: undefined, done: true};\n }\n }\n const item = this.getItem(this.idxInternal);\n this.idxInternal += 1;\n return {value: item, done: false};\n },\n return: async () => {\n return {value: undefined, done: true};\n },\n };\n }\n\n /**\n * Fetches the next page of items. This makes a new API request.\n *\n * @throws {Error} If there are no more pages to fetch.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * let page = pager.page;\n * while (true) {\n * for (const file of page) {\n * console.log(file.name);\n * }\n * if (!pager.hasNextPage()) {\n * break;\n * }\n * page = await pager.nextPage();\n * }\n * ```\n */\n async nextPage(): Promise {\n if (!this.hasNextPage()) {\n throw new Error('No more pages to fetch.');\n }\n const response = await this.requestInternal(this.params);\n this.initNextPage(response);\n return this.page;\n }\n\n /**\n * Returns true if there are more pages to fetch from the API.\n */\n hasNextPage(): boolean {\n if (this.params['config']?.['pageToken'] !== undefined) {\n return true;\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_batches_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Batches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Create batch job.\n *\n * @param params - The parameters for create batch job request.\n * @return The created batch job.\n *\n * @example\n * ```ts\n * const response = await ai.batches.create({\n * model: 'gemini-2.0-flash',\n * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'},\n * config: {\n * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'},\n * }\n * });\n * console.log(response);\n * ```\n */\n create = async (\n params: types.CreateBatchJobParameters,\n ): Promise => {\n if (this.apiClient.isVertexAI()) {\n const timestamp = Date.now();\n const timestampStr = timestamp.toString();\n if (Array.isArray(params.src)) {\n throw new Error(\n 'InlinedRequest[] is not supported in Vertex AI. Please use ' +\n 'Google Cloud Storage URI or BigQuery URI instead.',\n );\n }\n params.config = params.config || {};\n if (params.config.displayName === undefined) {\n params.config.displayName = 'genaiBatchJob_${timestampStr}';\n }\n if (params.config.dest === undefined && typeof params.src === 'string') {\n if (params.src.startsWith('gs://') && params.src.endsWith('.jsonl')) {\n params.config.dest = `${params.src.slice(0, -6)}/dest`;\n } else if (params.src.startsWith('bq://')) {\n params.config.dest =\n `${params.src}_dest_${timestampStr}` as unknown as string;\n } else {\n throw new Error('Unsupported source:' + params.src);\n }\n }\n } else {\n if (\n Array.isArray(params.src) ||\n (typeof params.src !== 'string' && params.src.inlinedRequests)\n ) {\n // Move system instruction to httpOptions extraBody.\n\n let path: string = '';\n let queryParams: Record = {};\n const body = converters.createBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchGenerateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n // Move system instruction to 'request':\n // {'systemInstruction': system_instruction}\n const batch = body['batch'] as {[key: string]: unknown};\n const inputConfig = batch['inputConfig'] as {[key: string]: unknown};\n const requestsWrapper = inputConfig['requests'] as {\n [key: string]: unknown;\n };\n const requests = requestsWrapper['requests'] as Array<{\n [key: string]: unknown;\n }>;\n const newRequests = [];\n for (const request of requests) {\n const requestDict = request as {[key: string]: unknown};\n if (requestDict['systemInstruction']) {\n const systemInstructionValue = requestDict['systemInstruction'];\n delete requestDict['systemInstruction'];\n const requestContent = requestDict['request'] as {\n [key: string]: unknown;\n };\n requestContent['systemInstruction'] = systemInstructionValue;\n requestDict['request'] = requestContent;\n }\n newRequests.push(requestDict);\n }\n requestsWrapper['requests'] = newRequests;\n\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n return await this.createInternal(params);\n };\n\n /**\n * Lists batch job configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of batch jobs.\n *\n * @example\n * ```ts\n * const batchJobs = await ai.batches.list({config: {'pageSize': 2}});\n * for await (const batchJob of batchJobs) {\n * console.log(batchJob);\n * }\n * ```\n */\n list = async (\n params: types.ListBatchJobsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_BATCH_JOBS,\n (x: types.ListBatchJobsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Internal method to create batch job.\n *\n * @param params - The parameters for create batch job request.\n * @return The created batch job.\n *\n */\n private async createInternal(\n params: types.CreateBatchJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromVertex(apiResponse);\n\n return resp as types.BatchJob;\n });\n } else {\n const body = converters.createBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchGenerateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n\n /**\n * Gets batch job configurations.\n *\n * @param params - The parameters for the get request.\n * @return The batch job.\n *\n * @example\n * ```ts\n * await ai.batches.get({name: '...'}); // The server-generated resource name.\n * ```\n */\n async get(params: types.GetBatchJobParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromVertex(apiResponse);\n\n return resp as types.BatchJob;\n });\n } else {\n const body = converters.getBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n\n /**\n * Cancels a batch job.\n *\n * @param params - The parameters for the cancel request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.batches.cancel({name: '...'}); // The server-generated resource name.\n * ```\n */\n async cancel(params: types.CancelBatchJobParameters): Promise {\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.cancelBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n } else {\n const body = converters.cancelBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n }\n }\n\n private async listInternal(\n params: types.ListBatchJobsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listBatchJobsParametersToVertex(params);\n path = common.formatMap(\n 'batchPredictionJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListBatchJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listBatchJobsResponseFromVertex(apiResponse);\n const typedResp = new types.ListBatchJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listBatchJobsParametersToMldev(params);\n path = common.formatMap(\n 'batches',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListBatchJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listBatchJobsResponseFromMldev(apiResponse);\n const typedResp = new types.ListBatchJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Deletes a batch job.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.batches.delete({name: '...'}); // The server-generated resource name.\n * ```\n */\n async delete(\n params: types.DeleteBatchJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteResourceJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteResourceJobFromVertex(apiResponse);\n\n return resp as types.DeleteResourceJob;\n });\n } else {\n const body = converters.deleteBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.DeleteResourceJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteResourceJobFromMldev(apiResponse);\n\n return resp as types.DeleteResourceJob;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToMldev(\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['contents'], transformedList);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['kmsKeyName']) !== undefined) {\n throw new Error('kmsKeyName parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToMldev(\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToMldev(\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToMldev(\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(\n fromObject: types.EnterpriseWebSearch,\n): Record {\n const toObject: Record = {};\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToVertex(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(fromEnterpriseWebSearch),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToVertex(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToVertex(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToVertex(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToVertex(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToVertex(\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['contents'], transformedList);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(fromToolConfig),\n );\n }\n\n const fromKmsKeyName = common.getValueByPath(fromObject, ['kmsKeyName']);\n if (parentObject !== undefined && fromKmsKeyName != null) {\n common.setValueByPath(\n parentObject,\n ['encryption_spec', 'kmsKeyName'],\n fromKmsKeyName,\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToVertex(\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToVertex(\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToVertex(\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function cachedContentFromMldev(\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromMldev(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromMldev(\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n let transformedList = fromCachedContents;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return cachedContentFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['cachedContents'], transformedList);\n }\n\n return toObject;\n}\n\nexport function cachedContentFromVertex(\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromVertex(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromVertex(\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n let transformedList = fromCachedContents;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return cachedContentFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['cachedContents'], transformedList);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_caches_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Caches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists cached content configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of cached contents.\n *\n * @example\n * ```ts\n * const cachedContents = await ai.caches.list({config: {'pageSize': 2}});\n * for await (const cachedContent of cachedContents) {\n * console.log(cachedContent);\n * }\n * ```\n */\n list = async (\n params: types.ListCachedContentsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_CACHED_CONTENTS,\n (x: types.ListCachedContentsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a cached contents resource.\n *\n * @remarks\n * Context caching is only supported for specific models. See [Gemini\n * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac)\n * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models)\n * for more information.\n *\n * @param params - The parameters for the create request.\n * @return The created cached content.\n *\n * @example\n * ```ts\n * const contents = ...; // Initialize the content to cache.\n * const response = await ai.caches.create({\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'contents': contents,\n * 'displayName': 'test cache',\n * 'systemInstruction': 'What is the sum of the two pdfs?',\n * 'ttl': '86400s',\n * }\n * });\n * ```\n */\n async create(\n params: types.CreateCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.createCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Gets cached content configurations.\n *\n * @param params - The parameters for the get request.\n * @return The cached content.\n *\n * @example\n * ```ts\n * await ai.caches.get({name: '...'}); // The server-generated resource name.\n * ```\n */\n async get(\n params: types.GetCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.getCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Deletes cached content.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.caches.delete({name: '...'}); // The server-generated resource name.\n * ```\n */\n async delete(\n params: types.DeleteCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteCachedContentResponseFromVertex();\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteCachedContentResponseFromMldev();\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates cached content configurations.\n *\n * @param params - The parameters for the update request.\n * @return The updated cached content.\n *\n * @example\n * ```ts\n * const response = await ai.caches.update({\n * name: '...', // The server-generated resource name.\n * config: {'ttl': '7600s'}\n * });\n * ```\n */\n async update(\n params: types.UpdateCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.updateCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n private async listInternal(\n params: types.ListCachedContentsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listCachedContentsParametersToVertex(params);\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListCachedContentsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.listCachedContentsResponseFromVertex(apiResponse);\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listCachedContentsParametersToMldev(params);\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListCachedContentsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.listCachedContentsResponseFromMldev(apiResponse);\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client.js';\nimport * as t from './_transformers.js';\nimport {Models} from './models.js';\nimport * as types from './types.js';\n\n/**\n * Returns true if the response is valid, false otherwise.\n */\nfunction isValidResponse(response: types.GenerateContentResponse): boolean {\n if (response.candidates == undefined || response.candidates.length === 0) {\n return false;\n }\n const content = response.candidates[0]?.content;\n if (content === undefined) {\n return false;\n }\n return isValidContent(content);\n}\n\nfunction isValidContent(content: types.Content): boolean {\n if (content.parts === undefined || content.parts.length === 0) {\n return false;\n }\n for (const part of content.parts) {\n if (part === undefined || Object.keys(part).length === 0) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Validates the history contains the correct roles.\n *\n * @throws Error if the history does not start with a user turn.\n * @throws Error if the history contains an invalid role.\n */\nfunction validateHistory(history: types.Content[]) {\n // Empty history is valid.\n if (history.length === 0) {\n return;\n }\n for (const content of history) {\n if (content.role !== 'user' && content.role !== 'model') {\n throw new Error(`Role must be user or model, but got ${content.role}.`);\n }\n }\n}\n\n/**\n * Extracts the curated (valid) history from a comprehensive history.\n *\n * @remarks\n * The model may sometimes generate invalid or empty contents(e.g., due to safty\n * filters or recitation). Extracting valid turns from the history\n * ensures that subsequent requests could be accpeted by the model.\n */\nfunction extractCuratedHistory(\n comprehensiveHistory: types.Content[],\n): types.Content[] {\n if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) {\n return [];\n }\n const curatedHistory: types.Content[] = [];\n const length = comprehensiveHistory.length;\n let i = 0;\n while (i < length) {\n if (comprehensiveHistory[i].role === 'user') {\n curatedHistory.push(comprehensiveHistory[i]);\n i++;\n } else {\n const modelOutput: types.Content[] = [];\n let isValid = true;\n while (i < length && comprehensiveHistory[i].role === 'model') {\n modelOutput.push(comprehensiveHistory[i]);\n if (isValid && !isValidContent(comprehensiveHistory[i])) {\n isValid = false;\n }\n i++;\n }\n if (isValid) {\n curatedHistory.push(...modelOutput);\n } else {\n // Remove the last user input when model content is invalid.\n curatedHistory.pop();\n }\n }\n }\n return curatedHistory;\n}\n\n/**\n * A utility class to create a chat session.\n */\nexport class Chats {\n private readonly modelsModule: Models;\n private readonly apiClient: ApiClient;\n\n constructor(modelsModule: Models, apiClient: ApiClient) {\n this.modelsModule = modelsModule;\n this.apiClient = apiClient;\n }\n\n /**\n * Creates a new chat session.\n *\n * @remarks\n * The config in the params will be used for all requests within the chat\n * session unless overridden by a per-request `config` in\n * @see {@link types.SendMessageParameters#config}.\n *\n * @param params - Parameters for creating a chat session.\n * @returns A new chat session.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({\n * model: 'gemini-2.0-flash'\n * config: {\n * temperature: 0.5,\n * maxOutputTokens: 1024,\n * }\n * });\n * ```\n */\n create(params: types.CreateChatParameters) {\n return new Chat(\n this.apiClient,\n this.modelsModule,\n params.model,\n params.config,\n // Deep copy the history to avoid mutating the history outside of the\n // chat session.\n structuredClone(params.history),\n );\n }\n}\n\n/**\n * Chat session that enables sending messages to the model with previous\n * conversation context.\n *\n * @remarks\n * The session maintains all the turns between user and model.\n */\nexport class Chat {\n // A promise to represent the current state of the message being sent to the\n // model.\n private sendPromise: Promise = Promise.resolve();\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly modelsModule: Models,\n private readonly model: string,\n private readonly config: types.GenerateContentConfig = {},\n private history: types.Content[] = [],\n ) {\n validateHistory(history);\n }\n\n /**\n * Sends a message to the model and returns the response.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessageStream} for streaming method.\n * @param params - parameters for sending messages within a chat session.\n * @returns The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessage({\n * message: 'Why is the sky blue?'\n * });\n * console.log(response.text);\n * ```\n */\n async sendMessage(\n params: types.SendMessageParameters,\n ): Promise {\n await this.sendPromise;\n const inputContent = t.tContent(params.message);\n const responsePromise = this.modelsModule.generateContent({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n this.sendPromise = (async () => {\n const response = await responsePromise;\n const outputContent = response.candidates?.[0]?.content;\n\n // Because the AFC input contains the entire curated chat history in\n // addition to the new user input, we need to truncate the AFC history\n // to deduplicate the existing chat history.\n const fullAutomaticFunctionCallingHistory =\n response.automaticFunctionCallingHistory;\n const index = this.getHistory(true).length;\n\n let automaticFunctionCallingHistory: types.Content[] = [];\n if (fullAutomaticFunctionCallingHistory != null) {\n automaticFunctionCallingHistory =\n fullAutomaticFunctionCallingHistory.slice(index) ?? [];\n }\n\n const modelOutput = outputContent ? [outputContent] : [];\n this.recordHistory(\n inputContent,\n modelOutput,\n automaticFunctionCallingHistory,\n );\n return;\n })();\n await this.sendPromise.catch(() => {\n // Resets sendPromise to avoid subsequent calls failing\n this.sendPromise = Promise.resolve();\n });\n return responsePromise;\n }\n\n /**\n * Sends a message to the model and returns the response in chunks.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessage} for non-streaming method.\n * @param params - parameters for sending the message.\n * @return The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessageStream({\n * message: 'Why is the sky blue?'\n * });\n * for await (const chunk of response) {\n * console.log(chunk.text);\n * }\n * ```\n */\n async sendMessageStream(\n params: types.SendMessageParameters,\n ): Promise> {\n await this.sendPromise;\n const inputContent = t.tContent(params.message);\n const streamResponse = this.modelsModule.generateContentStream({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n // Resolve the internal tracking of send completion promise - `sendPromise`\n // for both success and failure response. The actual failure is still\n // propagated by the `await streamResponse`.\n this.sendPromise = streamResponse\n .then(() => undefined)\n .catch(() => undefined);\n const response = await streamResponse;\n const result = this.processStreamResponse(response, inputContent);\n return result;\n }\n\n /**\n * Returns the chat history.\n *\n * @remarks\n * The history is a list of contents alternating between user and model.\n *\n * There are two types of history:\n * - The `curated history` contains only the valid turns between user and\n * model, which will be included in the subsequent requests sent to the model.\n * - The `comprehensive history` contains all turns, including invalid or\n * empty model outputs, providing a complete record of the history.\n *\n * The history is updated after receiving the response from the model,\n * for streaming response, it means receiving the last chunk of the response.\n *\n * The `comprehensive history` is returned by default. To get the `curated\n * history`, set the `curated` parameter to `true`.\n *\n * @param curated - whether to return the curated history or the comprehensive\n * history.\n * @return History contents alternating between user and model for the entire\n * chat session.\n */\n getHistory(curated: boolean = false): types.Content[] {\n const history = curated\n ? extractCuratedHistory(this.history)\n : this.history;\n // Deep copy the history to avoid mutating the history outside of the\n // chat session.\n return structuredClone(history);\n }\n\n private async *processStreamResponse(\n streamResponse: AsyncGenerator,\n inputContent: types.Content,\n ) {\n const outputContent: types.Content[] = [];\n for await (const chunk of streamResponse) {\n if (isValidResponse(chunk)) {\n const content = chunk.candidates?.[0]?.content;\n if (content !== undefined) {\n outputContent.push(content);\n }\n }\n yield chunk;\n }\n this.recordHistory(inputContent, outputContent);\n }\n\n private recordHistory(\n userInput: types.Content,\n modelOutput: types.Content[],\n automaticFunctionCallingHistory?: types.Content[],\n ) {\n let outputContents: types.Content[] = [];\n if (\n modelOutput.length > 0 &&\n modelOutput.every((content) => content.role !== undefined)\n ) {\n outputContents = modelOutput;\n } else {\n // Appends an empty content when model returns empty response, so that the\n // history is always alternating between user and model.\n outputContents.push({\n role: 'model',\n parts: [],\n } as types.Content);\n }\n if (\n automaticFunctionCallingHistory &&\n automaticFunctionCallingHistory.length > 0\n ) {\n this.history.push(\n ...extractCuratedHistory(automaticFunctionCallingHistory!),\n );\n } else {\n this.history.push(userInput);\n }\n this.history.push(...outputContents);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Details for errors from calling the API.\n */\nexport interface ApiErrorInfo {\n /** The error message. */\n message: string;\n /** The HTTP status code. */\n status: number;\n}\n\n/**\n * API errors raised by the GenAI API.\n */\nexport class ApiError extends Error {\n /** HTTP status code */\n status: number;\n\n constructor(options: ApiErrorInfo) {\n super(options.message);\n this.name = 'ApiError';\n this.status = options.status;\n Object.setPrototypeOf(this, ApiError.prototype);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function listFilesConfigToMldev(\n fromObject: types.ListFilesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listFilesParametersToMldev(\n fromObject: types.ListFilesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listFilesConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function fileStatusToMldev(\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileToMldev(fromObject: types.File): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fileStatusToMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function createFileParametersToMldev(\n fromObject: types.CreateFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromFile = common.getValueByPath(fromObject, ['file']);\n if (fromFile != null) {\n common.setValueByPath(toObject, ['file'], fileToMldev(fromFile));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getFileParametersToMldev(\n fromObject: types.GetFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'file'], t.tFileName(fromName));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteFileParametersToMldev(\n fromObject: types.DeleteFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'file'], t.tFileName(fromName));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fileStatusFromMldev(\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileFromMldev(fromObject: types.File): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fileStatusFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function listFilesResponseFromMldev(\n fromObject: types.ListFilesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromFiles = common.getValueByPath(fromObject, ['files']);\n if (fromFiles != null) {\n let transformedList = fromFiles;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return fileFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['files'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createFileResponseFromMldev(\n fromObject: types.CreateFileResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n\nexport function deleteFileResponseFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_files_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Files extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists all current project files from the service.\n *\n * @param params - The parameters for the list request\n * @return The paginated results of the list of files\n *\n * @example\n * The following code prints the names of all files from the service, the\n * size of each page is 10.\n *\n * ```ts\n * const listResponse = await ai.files.list({config: {'pageSize': 10}});\n * for await (const file of listResponse) {\n * console.log(file.name);\n * }\n * ```\n */\n list = async (\n params: types.ListFilesParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_FILES,\n (x: types.ListFilesParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Uploads a file asynchronously to the Gemini API.\n * This method is not available in Vertex AI.\n * Supported upload sources:\n * - Node.js: File path (string) or Blob object.\n * - Browser: Blob object (e.g., File).\n *\n * @remarks\n * The `mimeType` can be specified in the `config` parameter. If omitted:\n * - For file path (string) inputs, the `mimeType` will be inferred from the\n * file extension.\n * - For Blob object inputs, the `mimeType` will be set to the Blob's `type`\n * property.\n * Somex eamples for file extension to mimeType mapping:\n * .txt -> text/plain\n * .json -> application/json\n * .jpg -> image/jpeg\n * .png -> image/png\n * .mp3 -> audio/mpeg\n * .mp4 -> video/mp4\n *\n * This section can contain multiple paragraphs and code examples.\n *\n * @param params - Optional parameters specified in the\n * `types.UploadFileParameters` interface.\n * @see {@link types.UploadFileParameters#config} for the optional\n * config in the parameters.\n * @return A promise that resolves to a `types.File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n * the `mimeType` can be provided in the `params.config` parameter.\n * @throws An error occurs if a suitable upload location cannot be established.\n *\n * @example\n * The following code uploads a file to Gemini API.\n *\n * ```ts\n * const file = await ai.files.upload({file: 'file.txt', config: {\n * mimeType: 'text/plain',\n * }});\n * console.log(file.name);\n * ```\n */\n async upload(params: types.UploadFileParameters): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'Vertex AI does not support uploading files. You can share files through a GCS bucket.',\n );\n }\n\n return this.apiClient\n .uploadFile(params.file, params.config)\n .then((response) => {\n const file = converters.fileFromMldev(response);\n return file as types.File;\n });\n }\n\n /**\n * Downloads a remotely stored file asynchronously to a location specified in\n * the `params` object. This method only works on Node environment, to\n * download files in the browser, use a browser compliant method like an \n * tag.\n *\n * @param params - The parameters for the download request.\n *\n * @example\n * The following code downloads an example file named \"files/mehozpxf877d\" as\n * \"file.txt\".\n *\n * ```ts\n * await ai.files.download({file: file.name, downloadPath: 'file.txt'});\n * ```\n */\n\n async download(params: types.DownloadFileParameters): Promise {\n await this.apiClient.downloadFile(params);\n }\n\n private async listInternal(\n params: types.ListFilesParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.listFilesParametersToMldev(params);\n path = common.formatMap('files', body['_url'] as Record);\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListFilesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listFilesResponseFromMldev(apiResponse);\n const typedResp = new types.ListFilesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async createInternal(\n params: types.CreateFileParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createFileParametersToMldev(params);\n path = common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.createFileResponseFromMldev(apiResponse);\n const typedResp = new types.CreateFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Retrieves the file information from the service.\n *\n * @param params - The parameters for the get request\n * @return The Promise that resolves to the types.File object requested.\n *\n * @example\n * ```ts\n * const config: GetFileParameters = {\n * name: fileName,\n * };\n * file = await ai.files.get(config);\n * console.log(file.name);\n * ```\n */\n async get(params: types.GetFileParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.getFileParametersToMldev(params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.fileFromMldev(apiResponse);\n\n return resp as types.File;\n });\n }\n }\n\n /**\n * Deletes a remotely stored file.\n *\n * @param params - The parameters for the delete request.\n * @return The DeleteFileResponse, the response for the delete method.\n *\n * @example\n * The following code deletes an example file named \"files/mehozpxf877d\".\n *\n * ```ts\n * await ai.files.delete({name: file.name});\n * ```\n */\n async delete(\n params: types.DeleteFileParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.deleteFileParametersToMldev(params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteFileResponseFromMldev();\n const typedResp = new types.DeleteFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToMldev(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n if (common.getValueByPath(fromObject, ['transparent']) !== undefined) {\n throw new Error('transparent parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToMldev(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToMldev(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToMldev(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToMldev(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToMldev(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToMldev(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToMldev(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToMldev(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToMldev(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function activityStartToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function activityEndToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function liveSendRealtimeInputParametersToMldev(\n fromObject: types.LiveSendRealtimeInputParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMedia = common.getValueByPath(fromObject, ['media']);\n if (fromMedia != null) {\n common.setValueByPath(toObject, ['mediaChunks'], t.tBlobs(fromMedia));\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], t.tAudioBlob(fromAudio));\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], t.tImageBlob(fromVideo));\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToMldev());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToMldev());\n }\n\n return toObject;\n}\n\nexport function liveClientSetupToMldev(\n fromObject: types.LiveClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig != null) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction != null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(toObject, ['tools'], transformedList);\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (fromRealtimeInputConfig != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (fromSessionResumption != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (fromContextWindowCompression != null) {\n common.setValueByPath(\n toObject,\n ['contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (fromInputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (fromOutputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (fromProactivity != null) {\n common.setValueByPath(\n toObject,\n ['proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveClientContentToMldev(\n fromObject: types.LiveClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromTurns = common.getValueByPath(fromObject, ['turns']);\n if (fromTurns != null) {\n let transformedList = fromTurns;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['turns'], transformedList);\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n return toObject;\n}\n\nexport function liveClientRealtimeInputToMldev(\n fromObject: types.LiveClientRealtimeInput,\n): Record {\n const toObject: Record = {};\n\n const fromMediaChunks = common.getValueByPath(fromObject, ['mediaChunks']);\n if (fromMediaChunks != null) {\n common.setValueByPath(toObject, ['mediaChunks'], fromMediaChunks);\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], fromAudio);\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], fromVideo);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToMldev());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToMldev());\n }\n\n return toObject;\n}\n\nexport function functionResponseToMldev(\n fromObject: types.FunctionResponse,\n): Record {\n const toObject: Record = {};\n\n const fromWillContinue = common.getValueByPath(fromObject, ['willContinue']);\n if (fromWillContinue != null) {\n common.setValueByPath(toObject, ['willContinue'], fromWillContinue);\n }\n\n const fromScheduling = common.getValueByPath(fromObject, ['scheduling']);\n if (fromScheduling != null) {\n common.setValueByPath(toObject, ['scheduling'], fromScheduling);\n }\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n return toObject;\n}\n\nexport function liveClientToolResponseToMldev(\n fromObject: types.LiveClientToolResponse,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionResponses = common.getValueByPath(fromObject, [\n 'functionResponses',\n ]);\n if (fromFunctionResponses != null) {\n let transformedList = fromFunctionResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionResponseToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveClientMessageToMldev(\n fromObject: types.LiveClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveClientSetupToMldev(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveClientContentToMldev(fromClientContent),\n );\n }\n\n const fromRealtimeInput = common.getValueByPath(fromObject, [\n 'realtimeInput',\n ]);\n if (fromRealtimeInput != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInput'],\n liveClientRealtimeInputToMldev(fromRealtimeInput),\n );\n }\n\n const fromToolResponse = common.getValueByPath(fromObject, ['toolResponse']);\n if (fromToolResponse != null) {\n common.setValueByPath(\n toObject,\n ['toolResponse'],\n liveClientToolResponseToMldev(fromToolResponse),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicConnectParametersToMldev(\n fromObject: types.LiveMusicConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['setup', 'model'], fromModel);\n }\n\n const fromCallbacks = common.getValueByPath(fromObject, ['callbacks']);\n if (fromCallbacks != null) {\n common.setValueByPath(toObject, ['callbacks'], fromCallbacks);\n }\n\n return toObject;\n}\n\nexport function weightedPromptToMldev(\n fromObject: types.WeightedPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromWeight = common.getValueByPath(fromObject, ['weight']);\n if (fromWeight != null) {\n common.setValueByPath(toObject, ['weight'], fromWeight);\n }\n\n return toObject;\n}\n\nexport function liveMusicSetWeightedPromptsParametersToMldev(\n fromObject: types.LiveMusicSetWeightedPromptsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicGenerationConfigToMldev(\n fromObject: types.LiveMusicGenerationConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromGuidance = common.getValueByPath(fromObject, ['guidance']);\n if (fromGuidance != null) {\n common.setValueByPath(toObject, ['guidance'], fromGuidance);\n }\n\n const fromBpm = common.getValueByPath(fromObject, ['bpm']);\n if (fromBpm != null) {\n common.setValueByPath(toObject, ['bpm'], fromBpm);\n }\n\n const fromDensity = common.getValueByPath(fromObject, ['density']);\n if (fromDensity != null) {\n common.setValueByPath(toObject, ['density'], fromDensity);\n }\n\n const fromBrightness = common.getValueByPath(fromObject, ['brightness']);\n if (fromBrightness != null) {\n common.setValueByPath(toObject, ['brightness'], fromBrightness);\n }\n\n const fromScale = common.getValueByPath(fromObject, ['scale']);\n if (fromScale != null) {\n common.setValueByPath(toObject, ['scale'], fromScale);\n }\n\n const fromMuteBass = common.getValueByPath(fromObject, ['muteBass']);\n if (fromMuteBass != null) {\n common.setValueByPath(toObject, ['muteBass'], fromMuteBass);\n }\n\n const fromMuteDrums = common.getValueByPath(fromObject, ['muteDrums']);\n if (fromMuteDrums != null) {\n common.setValueByPath(toObject, ['muteDrums'], fromMuteDrums);\n }\n\n const fromOnlyBassAndDrums = common.getValueByPath(fromObject, [\n 'onlyBassAndDrums',\n ]);\n if (fromOnlyBassAndDrums != null) {\n common.setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums);\n }\n\n const fromMusicGenerationMode = common.getValueByPath(fromObject, [\n 'musicGenerationMode',\n ]);\n if (fromMusicGenerationMode != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationMode'],\n fromMusicGenerationMode,\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicSetConfigParametersToMldev(\n fromObject: types.LiveMusicSetConfigParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigToMldev(fromMusicGenerationConfig),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicClientSetupToMldev(\n fromObject: types.LiveMusicClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientContentToMldev(\n fromObject: types.LiveMusicClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientMessageToMldev(\n fromObject: types.LiveMusicClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveMusicClientSetupToMldev(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveMusicClientContentToMldev(fromClientContent),\n );\n }\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigToMldev(fromMusicGenerationConfig),\n );\n }\n\n const fromPlaybackControl = common.getValueByPath(fromObject, [\n 'playbackControl',\n ]);\n if (fromPlaybackControl != null) {\n common.setValueByPath(toObject, ['playbackControl'], fromPlaybackControl);\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(fromVoiceConfig),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined\n ) {\n throw new Error(\n 'multiSpeakerVoiceConfig parameter is not supported in Vertex AI.',\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(\n fromObject: types.EnterpriseWebSearch,\n): Record {\n const toObject: Record = {};\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToVertex(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(fromEnterpriseWebSearch),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToVertex(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToVertex(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n const fromTransparent = common.getValueByPath(fromObject, ['transparent']);\n if (fromTransparent != null) {\n common.setValueByPath(toObject, ['transparent'], fromTransparent);\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToVertex(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToVertex(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToVertex(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToVertex(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToVertex(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToVertex(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToVertex(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToVertex(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToVertex(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToVertex(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToVertex(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToVertex(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToVertex(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function activityStartToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function activityEndToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function liveSendRealtimeInputParametersToVertex(\n fromObject: types.LiveSendRealtimeInputParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMedia = common.getValueByPath(fromObject, ['media']);\n if (fromMedia != null) {\n common.setValueByPath(toObject, ['mediaChunks'], t.tBlobs(fromMedia));\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], t.tAudioBlob(fromAudio));\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], t.tImageBlob(fromVideo));\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToVertex());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToVertex());\n }\n\n return toObject;\n}\n\nexport function liveClientSetupToVertex(\n fromObject: types.LiveClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig != null) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction != null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(toObject, ['tools'], transformedList);\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (fromRealtimeInputConfig != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInputConfig'],\n realtimeInputConfigToVertex(fromRealtimeInputConfig),\n );\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (fromSessionResumption != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumption'],\n sessionResumptionConfigToVertex(fromSessionResumption),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (fromContextWindowCompression != null) {\n common.setValueByPath(\n toObject,\n ['contextWindowCompression'],\n contextWindowCompressionConfigToVertex(fromContextWindowCompression),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (fromInputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (fromOutputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (fromProactivity != null) {\n common.setValueByPath(\n toObject,\n ['proactivity'],\n proactivityConfigToVertex(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveClientContentToVertex(\n fromObject: types.LiveClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromTurns = common.getValueByPath(fromObject, ['turns']);\n if (fromTurns != null) {\n let transformedList = fromTurns;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['turns'], transformedList);\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n return toObject;\n}\n\nexport function liveClientRealtimeInputToVertex(\n fromObject: types.LiveClientRealtimeInput,\n): Record {\n const toObject: Record = {};\n\n const fromMediaChunks = common.getValueByPath(fromObject, ['mediaChunks']);\n if (fromMediaChunks != null) {\n common.setValueByPath(toObject, ['mediaChunks'], fromMediaChunks);\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], fromAudio);\n }\n\n if (common.getValueByPath(fromObject, ['audioStreamEnd']) !== undefined) {\n throw new Error('audioStreamEnd parameter is not supported in Vertex AI.');\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], fromVideo);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToVertex());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToVertex());\n }\n\n return toObject;\n}\n\nexport function functionResponseToVertex(\n fromObject: types.FunctionResponse,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['willContinue']) !== undefined) {\n throw new Error('willContinue parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['scheduling']) !== undefined) {\n throw new Error('scheduling parameter is not supported in Vertex AI.');\n }\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n return toObject;\n}\n\nexport function liveClientToolResponseToVertex(\n fromObject: types.LiveClientToolResponse,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionResponses = common.getValueByPath(fromObject, [\n 'functionResponses',\n ]);\n if (fromFunctionResponses != null) {\n let transformedList = fromFunctionResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionResponseToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveClientMessageToVertex(\n fromObject: types.LiveClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveClientSetupToVertex(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveClientContentToVertex(fromClientContent),\n );\n }\n\n const fromRealtimeInput = common.getValueByPath(fromObject, [\n 'realtimeInput',\n ]);\n if (fromRealtimeInput != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInput'],\n liveClientRealtimeInputToVertex(fromRealtimeInput),\n );\n }\n\n const fromToolResponse = common.getValueByPath(fromObject, ['toolResponse']);\n if (fromToolResponse != null) {\n common.setValueByPath(\n toObject,\n ['toolResponse'],\n liveClientToolResponseToVertex(fromToolResponse),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicConnectParametersToVertex(\n fromObject: types.LiveMusicConnectParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['model']) !== undefined) {\n throw new Error('model parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['callbacks']) !== undefined) {\n throw new Error('callbacks parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveMusicSetWeightedPromptsParametersToVertex(\n fromObject: types.LiveMusicSetWeightedPromptsParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['weightedPrompts']) !== undefined) {\n throw new Error('weightedPrompts parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveMusicSetConfigParametersToVertex(\n fromObject: types.LiveMusicSetConfigParameters,\n): Record {\n const toObject: Record = {};\n\n if (\n common.getValueByPath(fromObject, ['musicGenerationConfig']) !== undefined\n ) {\n throw new Error(\n 'musicGenerationConfig parameter is not supported in Vertex AI.',\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicClientMessageToVertex(\n fromObject: types.LiveMusicClientMessage,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['setup']) !== undefined) {\n throw new Error('setup parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['clientContent']) !== undefined) {\n throw new Error('clientContent parameter is not supported in Vertex AI.');\n }\n\n if (\n common.getValueByPath(fromObject, ['musicGenerationConfig']) !== undefined\n ) {\n throw new Error(\n 'musicGenerationConfig parameter is not supported in Vertex AI.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['playbackControl']) !== undefined) {\n throw new Error('playbackControl parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveServerSetupCompleteFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function transcriptionFromMldev(\n fromObject: types.Transcription,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFinished = common.getValueByPath(fromObject, ['finished']);\n if (fromFinished != null) {\n common.setValueByPath(toObject, ['finished'], fromFinished);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerContentFromMldev(\n fromObject: types.LiveServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn != null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromMldev(fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted != null) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromGenerationComplete = common.getValueByPath(fromObject, [\n 'generationComplete',\n ]);\n if (fromGenerationComplete != null) {\n common.setValueByPath(\n toObject,\n ['generationComplete'],\n fromGenerationComplete,\n );\n }\n\n const fromInputTranscription = common.getValueByPath(fromObject, [\n 'inputTranscription',\n ]);\n if (fromInputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputTranscription'],\n transcriptionFromMldev(fromInputTranscription),\n );\n }\n\n const fromOutputTranscription = common.getValueByPath(fromObject, [\n 'outputTranscription',\n ]);\n if (fromOutputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputTranscription'],\n transcriptionFromMldev(fromOutputTranscription),\n );\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function functionCallFromMldev(\n fromObject: types.FunctionCall,\n): Record {\n const toObject: Record = {};\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs != null) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallFromMldev(\n fromObject: types.LiveServerToolCall,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (fromFunctionCalls != null) {\n let transformedList = fromFunctionCalls;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionCallFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionCalls'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallCancellationFromMldev(\n fromObject: types.LiveServerToolCallCancellation,\n): Record {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds != null) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nexport function modalityTokenCountFromMldev(\n fromObject: types.ModalityTokenCount,\n): Record {\n const toObject: Record = {};\n\n const fromModality = common.getValueByPath(fromObject, ['modality']);\n if (fromModality != null) {\n common.setValueByPath(toObject, ['modality'], fromModality);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function usageMetadataFromMldev(\n fromObject: types.UsageMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromPromptTokenCount = common.getValueByPath(fromObject, [\n 'promptTokenCount',\n ]);\n if (fromPromptTokenCount != null) {\n common.setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n const fromResponseTokenCount = common.getValueByPath(fromObject, [\n 'responseTokenCount',\n ]);\n if (fromResponseTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['responseTokenCount'],\n fromResponseTokenCount,\n );\n }\n\n const fromToolUsePromptTokenCount = common.getValueByPath(fromObject, [\n 'toolUsePromptTokenCount',\n ]);\n if (fromToolUsePromptTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokenCount'],\n fromToolUsePromptTokenCount,\n );\n }\n\n const fromThoughtsTokenCount = common.getValueByPath(fromObject, [\n 'thoughtsTokenCount',\n ]);\n if (fromThoughtsTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['thoughtsTokenCount'],\n fromThoughtsTokenCount,\n );\n }\n\n const fromTotalTokenCount = common.getValueByPath(fromObject, [\n 'totalTokenCount',\n ]);\n if (fromTotalTokenCount != null) {\n common.setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount);\n }\n\n const fromPromptTokensDetails = common.getValueByPath(fromObject, [\n 'promptTokensDetails',\n ]);\n if (fromPromptTokensDetails != null) {\n let transformedList = fromPromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['promptTokensDetails'], transformedList);\n }\n\n const fromCacheTokensDetails = common.getValueByPath(fromObject, [\n 'cacheTokensDetails',\n ]);\n if (fromCacheTokensDetails != null) {\n let transformedList = fromCacheTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['cacheTokensDetails'], transformedList);\n }\n\n const fromResponseTokensDetails = common.getValueByPath(fromObject, [\n 'responseTokensDetails',\n ]);\n if (fromResponseTokensDetails != null) {\n let transformedList = fromResponseTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['responseTokensDetails'], transformedList);\n }\n\n const fromToolUsePromptTokensDetails = common.getValueByPath(fromObject, [\n 'toolUsePromptTokensDetails',\n ]);\n if (fromToolUsePromptTokensDetails != null) {\n let transformedList = fromToolUsePromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokensDetails'],\n transformedList,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerGoAwayFromMldev(\n fromObject: types.LiveServerGoAway,\n): Record {\n const toObject: Record = {};\n\n const fromTimeLeft = common.getValueByPath(fromObject, ['timeLeft']);\n if (fromTimeLeft != null) {\n common.setValueByPath(toObject, ['timeLeft'], fromTimeLeft);\n }\n\n return toObject;\n}\n\nexport function liveServerSessionResumptionUpdateFromMldev(\n fromObject: types.LiveServerSessionResumptionUpdate,\n): Record {\n const toObject: Record = {};\n\n const fromNewHandle = common.getValueByPath(fromObject, ['newHandle']);\n if (fromNewHandle != null) {\n common.setValueByPath(toObject, ['newHandle'], fromNewHandle);\n }\n\n const fromResumable = common.getValueByPath(fromObject, ['resumable']);\n if (fromResumable != null) {\n common.setValueByPath(toObject, ['resumable'], fromResumable);\n }\n\n const fromLastConsumedClientMessageIndex = common.getValueByPath(fromObject, [\n 'lastConsumedClientMessageIndex',\n ]);\n if (fromLastConsumedClientMessageIndex != null) {\n common.setValueByPath(\n toObject,\n ['lastConsumedClientMessageIndex'],\n fromLastConsumedClientMessageIndex,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromMldev(\n fromObject: types.LiveServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveServerSetupCompleteFromMldev(),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromMldev(fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall != null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromMldev(fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (fromToolCallCancellation != null) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromMldev(fromToolCallCancellation),\n );\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(\n toObject,\n ['usageMetadata'],\n usageMetadataFromMldev(fromUsageMetadata),\n );\n }\n\n const fromGoAway = common.getValueByPath(fromObject, ['goAway']);\n if (fromGoAway != null) {\n common.setValueByPath(\n toObject,\n ['goAway'],\n liveServerGoAwayFromMldev(fromGoAway),\n );\n }\n\n const fromSessionResumptionUpdate = common.getValueByPath(fromObject, [\n 'sessionResumptionUpdate',\n ]);\n if (fromSessionResumptionUpdate != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumptionUpdate'],\n liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerSetupCompleteFromMldev(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function weightedPromptFromMldev(\n fromObject: types.WeightedPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromWeight = common.getValueByPath(fromObject, ['weight']);\n if (fromWeight != null) {\n common.setValueByPath(toObject, ['weight'], fromWeight);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientContentFromMldev(\n fromObject: types.LiveMusicClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicGenerationConfigFromMldev(\n fromObject: types.LiveMusicGenerationConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromGuidance = common.getValueByPath(fromObject, ['guidance']);\n if (fromGuidance != null) {\n common.setValueByPath(toObject, ['guidance'], fromGuidance);\n }\n\n const fromBpm = common.getValueByPath(fromObject, ['bpm']);\n if (fromBpm != null) {\n common.setValueByPath(toObject, ['bpm'], fromBpm);\n }\n\n const fromDensity = common.getValueByPath(fromObject, ['density']);\n if (fromDensity != null) {\n common.setValueByPath(toObject, ['density'], fromDensity);\n }\n\n const fromBrightness = common.getValueByPath(fromObject, ['brightness']);\n if (fromBrightness != null) {\n common.setValueByPath(toObject, ['brightness'], fromBrightness);\n }\n\n const fromScale = common.getValueByPath(fromObject, ['scale']);\n if (fromScale != null) {\n common.setValueByPath(toObject, ['scale'], fromScale);\n }\n\n const fromMuteBass = common.getValueByPath(fromObject, ['muteBass']);\n if (fromMuteBass != null) {\n common.setValueByPath(toObject, ['muteBass'], fromMuteBass);\n }\n\n const fromMuteDrums = common.getValueByPath(fromObject, ['muteDrums']);\n if (fromMuteDrums != null) {\n common.setValueByPath(toObject, ['muteDrums'], fromMuteDrums);\n }\n\n const fromOnlyBassAndDrums = common.getValueByPath(fromObject, [\n 'onlyBassAndDrums',\n ]);\n if (fromOnlyBassAndDrums != null) {\n common.setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums);\n }\n\n const fromMusicGenerationMode = common.getValueByPath(fromObject, [\n 'musicGenerationMode',\n ]);\n if (fromMusicGenerationMode != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationMode'],\n fromMusicGenerationMode,\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicSourceMetadataFromMldev(\n fromObject: types.LiveMusicSourceMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveMusicClientContentFromMldev(fromClientContent),\n );\n }\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig),\n );\n }\n\n return toObject;\n}\n\nexport function audioChunkFromMldev(\n fromObject: types.AudioChunk,\n): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSourceMetadata = common.getValueByPath(fromObject, [\n 'sourceMetadata',\n ]);\n if (fromSourceMetadata != null) {\n common.setValueByPath(\n toObject,\n ['sourceMetadata'],\n liveMusicSourceMetadataFromMldev(fromSourceMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerContentFromMldev(\n fromObject: types.LiveMusicServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromAudioChunks = common.getValueByPath(fromObject, ['audioChunks']);\n if (fromAudioChunks != null) {\n let transformedList = fromAudioChunks;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return audioChunkFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['audioChunks'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicFilteredPromptFromMldev(\n fromObject: types.LiveMusicFilteredPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFilteredReason = common.getValueByPath(fromObject, [\n 'filteredReason',\n ]);\n if (fromFilteredReason != null) {\n common.setValueByPath(toObject, ['filteredReason'], fromFilteredReason);\n }\n\n return toObject;\n}\n\nexport function liveMusicServerMessageFromMldev(\n fromObject: types.LiveMusicServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveMusicServerSetupCompleteFromMldev(),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveMusicServerContentFromMldev(fromServerContent),\n );\n }\n\n const fromFilteredPrompt = common.getValueByPath(fromObject, [\n 'filteredPrompt',\n ]);\n if (fromFilteredPrompt != null) {\n common.setValueByPath(\n toObject,\n ['filteredPrompt'],\n liveMusicFilteredPromptFromMldev(fromFilteredPrompt),\n );\n }\n\n return toObject;\n}\n\nexport function liveServerSetupCompleteFromVertex(\n fromObject: types.LiveServerSetupComplete,\n): Record {\n const toObject: Record = {};\n\n const fromSessionId = common.getValueByPath(fromObject, ['sessionId']);\n if (fromSessionId != null) {\n common.setValueByPath(toObject, ['sessionId'], fromSessionId);\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromVertex(\n fromObject: types.Blob,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function transcriptionFromVertex(\n fromObject: types.Transcription,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFinished = common.getValueByPath(fromObject, ['finished']);\n if (fromFinished != null) {\n common.setValueByPath(toObject, ['finished'], fromFinished);\n }\n\n return toObject;\n}\n\nexport function liveServerContentFromVertex(\n fromObject: types.LiveServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn != null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromVertex(fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted != null) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromGenerationComplete = common.getValueByPath(fromObject, [\n 'generationComplete',\n ]);\n if (fromGenerationComplete != null) {\n common.setValueByPath(\n toObject,\n ['generationComplete'],\n fromGenerationComplete,\n );\n }\n\n const fromInputTranscription = common.getValueByPath(fromObject, [\n 'inputTranscription',\n ]);\n if (fromInputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputTranscription'],\n transcriptionFromVertex(fromInputTranscription),\n );\n }\n\n const fromOutputTranscription = common.getValueByPath(fromObject, [\n 'outputTranscription',\n ]);\n if (fromOutputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputTranscription'],\n transcriptionFromVertex(fromOutputTranscription),\n );\n }\n\n return toObject;\n}\n\nexport function functionCallFromVertex(\n fromObject: types.FunctionCall,\n): Record {\n const toObject: Record = {};\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs != null) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallFromVertex(\n fromObject: types.LiveServerToolCall,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (fromFunctionCalls != null) {\n let transformedList = fromFunctionCalls;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionCallFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionCalls'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallCancellationFromVertex(\n fromObject: types.LiveServerToolCallCancellation,\n): Record {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds != null) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nexport function modalityTokenCountFromVertex(\n fromObject: types.ModalityTokenCount,\n): Record {\n const toObject: Record = {};\n\n const fromModality = common.getValueByPath(fromObject, ['modality']);\n if (fromModality != null) {\n common.setValueByPath(toObject, ['modality'], fromModality);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function usageMetadataFromVertex(\n fromObject: types.UsageMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromPromptTokenCount = common.getValueByPath(fromObject, [\n 'promptTokenCount',\n ]);\n if (fromPromptTokenCount != null) {\n common.setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n const fromResponseTokenCount = common.getValueByPath(fromObject, [\n 'candidatesTokenCount',\n ]);\n if (fromResponseTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['responseTokenCount'],\n fromResponseTokenCount,\n );\n }\n\n const fromToolUsePromptTokenCount = common.getValueByPath(fromObject, [\n 'toolUsePromptTokenCount',\n ]);\n if (fromToolUsePromptTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokenCount'],\n fromToolUsePromptTokenCount,\n );\n }\n\n const fromThoughtsTokenCount = common.getValueByPath(fromObject, [\n 'thoughtsTokenCount',\n ]);\n if (fromThoughtsTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['thoughtsTokenCount'],\n fromThoughtsTokenCount,\n );\n }\n\n const fromTotalTokenCount = common.getValueByPath(fromObject, [\n 'totalTokenCount',\n ]);\n if (fromTotalTokenCount != null) {\n common.setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount);\n }\n\n const fromPromptTokensDetails = common.getValueByPath(fromObject, [\n 'promptTokensDetails',\n ]);\n if (fromPromptTokensDetails != null) {\n let transformedList = fromPromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['promptTokensDetails'], transformedList);\n }\n\n const fromCacheTokensDetails = common.getValueByPath(fromObject, [\n 'cacheTokensDetails',\n ]);\n if (fromCacheTokensDetails != null) {\n let transformedList = fromCacheTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['cacheTokensDetails'], transformedList);\n }\n\n const fromResponseTokensDetails = common.getValueByPath(fromObject, [\n 'candidatesTokensDetails',\n ]);\n if (fromResponseTokensDetails != null) {\n let transformedList = fromResponseTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['responseTokensDetails'], transformedList);\n }\n\n const fromToolUsePromptTokensDetails = common.getValueByPath(fromObject, [\n 'toolUsePromptTokensDetails',\n ]);\n if (fromToolUsePromptTokensDetails != null) {\n let transformedList = fromToolUsePromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokensDetails'],\n transformedList,\n );\n }\n\n const fromTrafficType = common.getValueByPath(fromObject, ['trafficType']);\n if (fromTrafficType != null) {\n common.setValueByPath(toObject, ['trafficType'], fromTrafficType);\n }\n\n return toObject;\n}\n\nexport function liveServerGoAwayFromVertex(\n fromObject: types.LiveServerGoAway,\n): Record {\n const toObject: Record = {};\n\n const fromTimeLeft = common.getValueByPath(fromObject, ['timeLeft']);\n if (fromTimeLeft != null) {\n common.setValueByPath(toObject, ['timeLeft'], fromTimeLeft);\n }\n\n return toObject;\n}\n\nexport function liveServerSessionResumptionUpdateFromVertex(\n fromObject: types.LiveServerSessionResumptionUpdate,\n): Record {\n const toObject: Record = {};\n\n const fromNewHandle = common.getValueByPath(fromObject, ['newHandle']);\n if (fromNewHandle != null) {\n common.setValueByPath(toObject, ['newHandle'], fromNewHandle);\n }\n\n const fromResumable = common.getValueByPath(fromObject, ['resumable']);\n if (fromResumable != null) {\n common.setValueByPath(toObject, ['resumable'], fromResumable);\n }\n\n const fromLastConsumedClientMessageIndex = common.getValueByPath(fromObject, [\n 'lastConsumedClientMessageIndex',\n ]);\n if (fromLastConsumedClientMessageIndex != null) {\n common.setValueByPath(\n toObject,\n ['lastConsumedClientMessageIndex'],\n fromLastConsumedClientMessageIndex,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromVertex(\n fromObject: types.LiveServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveServerSetupCompleteFromVertex(fromSetupComplete),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromVertex(fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall != null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromVertex(fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (fromToolCallCancellation != null) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromVertex(fromToolCallCancellation),\n );\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(\n toObject,\n ['usageMetadata'],\n usageMetadataFromVertex(fromUsageMetadata),\n );\n }\n\n const fromGoAway = common.getValueByPath(fromObject, ['goAway']);\n if (fromGoAway != null) {\n common.setValueByPath(\n toObject,\n ['goAway'],\n liveServerGoAwayFromVertex(fromGoAway),\n );\n }\n\n const fromSessionResumptionUpdate = common.getValueByPath(fromObject, [\n 'sessionResumptionUpdate',\n ]);\n if (fromSessionResumptionUpdate != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumptionUpdate'],\n liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerMessageFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as _internal_types from '../_internal_types.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined\n ) {\n throw new Error(\n 'modelSelectionConfig parameter is not supported in Gemini API.',\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToMldev(\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'taskType'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['requests[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['mimeType']) !== undefined) {\n throw new Error('mimeType parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['autoTruncate']) !== undefined) {\n throw new Error('autoTruncate parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n const fromModelForEmbedContent = common.getValueByPath(fromObject, ['model']);\n if (fromModelForEmbedContent !== undefined) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'model'],\n t.tModel(apiClient, fromModelForEmbedContent),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToMldev(\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['negativePrompt']) !== undefined) {\n throw new Error('negativePrompt parameter is not supported in Gemini API.');\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['addWatermark']) !== undefined) {\n throw new Error('addWatermark parameter is not supported in Gemini API.');\n }\n\n const fromImageSize = common.getValueByPath(fromObject, ['imageSize']);\n if (parentObject !== undefined && fromImageSize != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleImageSize'],\n fromImageSize,\n );\n }\n\n if (common.getValueByPath(fromObject, ['enhancePrompt']) !== undefined) {\n throw new Error('enhancePrompt parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listModelsConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ListModelsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n const fromQueryBase = common.getValueByPath(fromObject, ['queryBase']);\n if (parentObject !== undefined && fromQueryBase != null) {\n common.setValueByPath(\n parentObject,\n ['_url', 'models_url'],\n t.tModelsUrl(apiClient, fromQueryBase),\n );\n }\n\n return toObject;\n}\n\nexport function listModelsParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.ListModelsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listModelsConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function updateModelConfigToMldev(\n fromObject: types.UpdateModelConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (parentObject !== undefined && fromDefaultCheckpointId != null) {\n common.setValueByPath(\n parentObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n return toObject;\n}\n\nexport function updateModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateModelConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToMldev(\n fromObject: types.CountTokensConfig,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['systemInstruction']) !== undefined) {\n throw new Error(\n 'systemInstruction parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['tools']) !== undefined) {\n throw new Error('tools parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['generationConfig']) !== undefined) {\n throw new Error(\n 'generationConfig parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToMldev(fromConfig),\n );\n }\n\n return toObject;\n}\n\nexport function imageToMldev(fromObject: types.Image): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosConfigToMldev(\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['fps']) !== undefined) {\n throw new Error('fps parameter is not supported in Gemini API.');\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n if (common.getValueByPath(fromObject, ['resolution']) !== undefined) {\n throw new Error('resolution parameter is not supported in Gemini API.');\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n if (common.getValueByPath(fromObject, ['pubsubTopic']) !== undefined) {\n throw new Error('pubsubTopic parameter is not supported in Gemini API.');\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n if (common.getValueByPath(fromObject, ['generateAudio']) !== undefined) {\n throw new Error('generateAudio parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['lastFrame']) !== undefined) {\n throw new Error('lastFrame parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['referenceImages']) !== undefined) {\n throw new Error(\n 'referenceImages parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['compressionQuality']) !== undefined) {\n throw new Error(\n 'compressionQuality parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToMldev(fromImage),\n );\n }\n\n if (common.getValueByPath(fromObject, ['video']) !== undefined) {\n throw new Error('video parameter is not supported in Gemini API.');\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToVertex(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function modelSelectionConfigToVertex(\n fromObject: types.ModelSelectionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFeatureSelectionPreference = common.getValueByPath(fromObject, [\n 'featureSelectionPreference',\n ]);\n if (fromFeatureSelectionPreference != null) {\n common.setValueByPath(\n toObject,\n ['featureSelectionPreference'],\n fromFeatureSelectionPreference,\n );\n }\n\n return toObject;\n}\n\nexport function safetySettingToVertex(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n const fromMethod = common.getValueByPath(fromObject, ['method']);\n if (fromMethod != null) {\n common.setValueByPath(toObject, ['method'], fromMethod);\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(\n fromObject: types.EnterpriseWebSearch,\n): Record {\n const toObject: Record = {};\n\n const fromExcludeDomains = common.getValueByPath(fromObject, [\n 'excludeDomains',\n ]);\n if (fromExcludeDomains != null) {\n common.setValueByPath(toObject, ['excludeDomains'], fromExcludeDomains);\n }\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToVertex(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(fromEnterpriseWebSearch),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToVertex(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToVertex(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToVertex(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToVertex(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(fromVoiceConfig),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined\n ) {\n throw new Error(\n 'multiSpeakerVoiceConfig parameter is not supported in Vertex AI.',\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToVertex(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToVertex(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n const fromRoutingConfig = common.getValueByPath(fromObject, [\n 'routingConfig',\n ]);\n if (fromRoutingConfig != null) {\n common.setValueByPath(toObject, ['routingConfig'], fromRoutingConfig);\n }\n\n const fromModelSelectionConfig = common.getValueByPath(fromObject, [\n 'modelSelectionConfig',\n ]);\n if (fromModelSelectionConfig != null) {\n common.setValueByPath(\n toObject,\n ['modelConfig'],\n modelSelectionConfigToVertex(fromModelSelectionConfig),\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(fromToolConfig),\n );\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (parentObject !== undefined && fromLabels != null) {\n common.setValueByPath(parentObject, ['labels'], fromLabels);\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToVertex(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromAudioTimestamp = common.getValueByPath(fromObject, [\n 'audioTimestamp',\n ]);\n if (fromAudioTimestamp != null) {\n common.setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp);\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToVertex(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToVertex(\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'task_type'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['instances[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (parentObject !== undefined && fromMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'mimeType'],\n fromMimeType,\n );\n }\n\n const fromAutoTruncate = common.getValueByPath(fromObject, ['autoTruncate']);\n if (parentObject !== undefined && fromAutoTruncate != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'autoTruncate'],\n fromAutoTruncate,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['instances[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToVertex(\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromImageSize = common.getValueByPath(fromObject, ['imageSize']);\n if (parentObject !== undefined && fromImageSize != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleImageSize'],\n fromImageSize,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function imageToVertex(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function maskReferenceConfigToVertex(\n fromObject: types.MaskReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMaskMode = common.getValueByPath(fromObject, ['maskMode']);\n if (fromMaskMode != null) {\n common.setValueByPath(toObject, ['maskMode'], fromMaskMode);\n }\n\n const fromSegmentationClasses = common.getValueByPath(fromObject, [\n 'segmentationClasses',\n ]);\n if (fromSegmentationClasses != null) {\n common.setValueByPath(toObject, ['maskClasses'], fromSegmentationClasses);\n }\n\n const fromMaskDilation = common.getValueByPath(fromObject, ['maskDilation']);\n if (fromMaskDilation != null) {\n common.setValueByPath(toObject, ['dilation'], fromMaskDilation);\n }\n\n return toObject;\n}\n\nexport function controlReferenceConfigToVertex(\n fromObject: types.ControlReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromControlType = common.getValueByPath(fromObject, ['controlType']);\n if (fromControlType != null) {\n common.setValueByPath(toObject, ['controlType'], fromControlType);\n }\n\n const fromEnableControlImageComputation = common.getValueByPath(fromObject, [\n 'enableControlImageComputation',\n ]);\n if (fromEnableControlImageComputation != null) {\n common.setValueByPath(\n toObject,\n ['computeControl'],\n fromEnableControlImageComputation,\n );\n }\n\n return toObject;\n}\n\nexport function styleReferenceConfigToVertex(\n fromObject: types.StyleReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromStyleDescription = common.getValueByPath(fromObject, [\n 'styleDescription',\n ]);\n if (fromStyleDescription != null) {\n common.setValueByPath(toObject, ['styleDescription'], fromStyleDescription);\n }\n\n return toObject;\n}\n\nexport function subjectReferenceConfigToVertex(\n fromObject: types.SubjectReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSubjectType = common.getValueByPath(fromObject, ['subjectType']);\n if (fromSubjectType != null) {\n common.setValueByPath(toObject, ['subjectType'], fromSubjectType);\n }\n\n const fromSubjectDescription = common.getValueByPath(fromObject, [\n 'subjectDescription',\n ]);\n if (fromSubjectDescription != null) {\n common.setValueByPath(\n toObject,\n ['subjectDescription'],\n fromSubjectDescription,\n );\n }\n\n return toObject;\n}\n\nexport function referenceImageAPIInternalToVertex(\n fromObject: _internal_types.ReferenceImageAPIInternal,\n): Record {\n const toObject: Record = {};\n\n const fromReferenceImage = common.getValueByPath(fromObject, [\n 'referenceImage',\n ]);\n if (fromReferenceImage != null) {\n common.setValueByPath(\n toObject,\n ['referenceImage'],\n imageToVertex(fromReferenceImage),\n );\n }\n\n const fromReferenceId = common.getValueByPath(fromObject, ['referenceId']);\n if (fromReferenceId != null) {\n common.setValueByPath(toObject, ['referenceId'], fromReferenceId);\n }\n\n const fromReferenceType = common.getValueByPath(fromObject, [\n 'referenceType',\n ]);\n if (fromReferenceType != null) {\n common.setValueByPath(toObject, ['referenceType'], fromReferenceType);\n }\n\n const fromMaskImageConfig = common.getValueByPath(fromObject, [\n 'maskImageConfig',\n ]);\n if (fromMaskImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['maskImageConfig'],\n maskReferenceConfigToVertex(fromMaskImageConfig),\n );\n }\n\n const fromControlImageConfig = common.getValueByPath(fromObject, [\n 'controlImageConfig',\n ]);\n if (fromControlImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['controlImageConfig'],\n controlReferenceConfigToVertex(fromControlImageConfig),\n );\n }\n\n const fromStyleImageConfig = common.getValueByPath(fromObject, [\n 'styleImageConfig',\n ]);\n if (fromStyleImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['styleImageConfig'],\n styleReferenceConfigToVertex(fromStyleImageConfig),\n );\n }\n\n const fromSubjectImageConfig = common.getValueByPath(fromObject, [\n 'subjectImageConfig',\n ]);\n if (fromSubjectImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['subjectImageConfig'],\n subjectReferenceConfigToVertex(fromSubjectImageConfig),\n );\n }\n\n return toObject;\n}\n\nexport function editImageConfigToVertex(\n fromObject: types.EditImageConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromEditMode = common.getValueByPath(fromObject, ['editMode']);\n if (parentObject !== undefined && fromEditMode != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editMode'],\n fromEditMode,\n );\n }\n\n const fromBaseSteps = common.getValueByPath(fromObject, ['baseSteps']);\n if (parentObject !== undefined && fromBaseSteps != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editConfig', 'baseSteps'],\n fromBaseSteps,\n );\n }\n\n return toObject;\n}\n\nexport function editImageParametersInternalToVertex(\n apiClient: ApiClient,\n fromObject: _internal_types.EditImageParametersInternal,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromReferenceImages = common.getValueByPath(fromObject, [\n 'referenceImages',\n ]);\n if (fromReferenceImages != null) {\n let transformedList = fromReferenceImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return referenceImageAPIInternalToVertex(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['instances[0]', 'referenceImages'],\n transformedList,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n editImageConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function upscaleImageAPIConfigInternalToVertex(\n fromObject: _internal_types.UpscaleImageAPIConfigInternal,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromEnhanceInputImage = common.getValueByPath(fromObject, [\n 'enhanceInputImage',\n ]);\n if (parentObject !== undefined && fromEnhanceInputImage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'upscaleConfig', 'enhanceInputImage'],\n fromEnhanceInputImage,\n );\n }\n\n const fromImagePreservationFactor = common.getValueByPath(fromObject, [\n 'imagePreservationFactor',\n ]);\n if (parentObject !== undefined && fromImagePreservationFactor != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'upscaleConfig', 'imagePreservationFactor'],\n fromImagePreservationFactor,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (parentObject !== undefined && fromMode != null) {\n common.setValueByPath(parentObject, ['parameters', 'mode'], fromMode);\n }\n\n return toObject;\n}\n\nexport function upscaleImageAPIParametersInternalToVertex(\n apiClient: ApiClient,\n fromObject: _internal_types.UpscaleImageAPIParametersInternal,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromUpscaleFactor = common.getValueByPath(fromObject, [\n 'upscaleFactor',\n ]);\n if (fromUpscaleFactor != null) {\n common.setValueByPath(\n toObject,\n ['parameters', 'upscaleConfig', 'upscaleFactor'],\n fromUpscaleFactor,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n upscaleImageAPIConfigInternalToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function productImageToVertex(\n fromObject: types.ProductImage,\n): Record {\n const toObject: Record = {};\n\n const fromProductImage = common.getValueByPath(fromObject, ['productImage']);\n if (fromProductImage != null) {\n common.setValueByPath(toObject, ['image'], imageToVertex(fromProductImage));\n }\n\n return toObject;\n}\n\nexport function recontextImageSourceToVertex(\n fromObject: types.RecontextImageSource,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (parentObject !== undefined && fromPrompt != null) {\n common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromPersonImage = common.getValueByPath(fromObject, ['personImage']);\n if (parentObject !== undefined && fromPersonImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'personImage', 'image'],\n imageToVertex(fromPersonImage),\n );\n }\n\n const fromProductImages = common.getValueByPath(fromObject, [\n 'productImages',\n ]);\n if (parentObject !== undefined && fromProductImages != null) {\n let transformedList = fromProductImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return productImageToVertex(item);\n });\n }\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'productImages'],\n transformedList,\n );\n }\n\n return toObject;\n}\n\nexport function recontextImageConfigToVertex(\n fromObject: types.RecontextImageConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromBaseSteps = common.getValueByPath(fromObject, ['baseSteps']);\n if (parentObject !== undefined && fromBaseSteps != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editConfig', 'baseSteps'],\n fromBaseSteps,\n );\n }\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function recontextImageParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.RecontextImageParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n recontextImageSourceToVertex(fromSource, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n recontextImageConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function scribbleImageToVertex(\n fromObject: types.ScribbleImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageToVertex(fromImage));\n }\n\n return toObject;\n}\n\nexport function segmentImageSourceToVertex(\n fromObject: types.SegmentImageSource,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (parentObject !== undefined && fromPrompt != null) {\n common.setValueByPath(parentObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (parentObject !== undefined && fromImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromScribbleImage = common.getValueByPath(fromObject, [\n 'scribbleImage',\n ]);\n if (parentObject !== undefined && fromScribbleImage != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'scribble'],\n scribbleImageToVertex(fromScribbleImage),\n );\n }\n\n return toObject;\n}\n\nexport function segmentImageConfigToVertex(\n fromObject: types.SegmentImageConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (parentObject !== undefined && fromMode != null) {\n common.setValueByPath(parentObject, ['parameters', 'mode'], fromMode);\n }\n\n const fromMaxPredictions = common.getValueByPath(fromObject, [\n 'maxPredictions',\n ]);\n if (parentObject !== undefined && fromMaxPredictions != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'maxPredictions'],\n fromMaxPredictions,\n );\n }\n\n const fromConfidenceThreshold = common.getValueByPath(fromObject, [\n 'confidenceThreshold',\n ]);\n if (parentObject !== undefined && fromConfidenceThreshold != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'confidenceThreshold'],\n fromConfidenceThreshold,\n );\n }\n\n const fromMaskDilation = common.getValueByPath(fromObject, ['maskDilation']);\n if (parentObject !== undefined && fromMaskDilation != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'maskDilation'],\n fromMaskDilation,\n );\n }\n\n const fromBinaryColorThreshold = common.getValueByPath(fromObject, [\n 'binaryColorThreshold',\n ]);\n if (parentObject !== undefined && fromBinaryColorThreshold != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'binaryColorThreshold'],\n fromBinaryColorThreshold,\n );\n }\n\n return toObject;\n}\n\nexport function segmentImageParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.SegmentImageParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n segmentImageSourceToVertex(fromSource, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n segmentImageConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listModelsConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ListModelsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n const fromQueryBase = common.getValueByPath(fromObject, ['queryBase']);\n if (parentObject !== undefined && fromQueryBase != null) {\n common.setValueByPath(\n parentObject,\n ['_url', 'models_url'],\n t.tModelsUrl(apiClient, fromQueryBase),\n );\n }\n\n return toObject;\n}\n\nexport function listModelsParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ListModelsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listModelsConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function updateModelConfigToVertex(\n fromObject: types.UpdateModelConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (parentObject !== undefined && fromDefaultCheckpointId != null) {\n common.setValueByPath(\n parentObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n return toObject;\n}\n\nexport function updateModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateModelConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToVertex(\n fromObject: types.CountTokensConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['generationConfig'],\n fromGenerationConfig,\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function computeTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ComputeTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoToVertex(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, ['videoBytes']);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function videoGenerationReferenceImageToVertex(\n fromObject: types.VideoGenerationReferenceImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageToVertex(fromImage));\n }\n\n const fromReferenceType = common.getValueByPath(fromObject, [\n 'referenceType',\n ]);\n if (fromReferenceType != null) {\n common.setValueByPath(toObject, ['referenceType'], fromReferenceType);\n }\n\n return toObject;\n}\n\nexport function generateVideosConfigToVertex(\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (parentObject !== undefined && fromFps != null) {\n common.setValueByPath(parentObject, ['parameters', 'fps'], fromFps);\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromResolution = common.getValueByPath(fromObject, ['resolution']);\n if (parentObject !== undefined && fromResolution != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'resolution'],\n fromResolution,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromPubsubTopic = common.getValueByPath(fromObject, ['pubsubTopic']);\n if (parentObject !== undefined && fromPubsubTopic != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'pubsubTopic'],\n fromPubsubTopic,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n const fromGenerateAudio = common.getValueByPath(fromObject, [\n 'generateAudio',\n ]);\n if (parentObject !== undefined && fromGenerateAudio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'generateAudio'],\n fromGenerateAudio,\n );\n }\n\n const fromLastFrame = common.getValueByPath(fromObject, ['lastFrame']);\n if (parentObject !== undefined && fromLastFrame != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'lastFrame'],\n imageToVertex(fromLastFrame),\n );\n }\n\n const fromReferenceImages = common.getValueByPath(fromObject, [\n 'referenceImages',\n ]);\n if (parentObject !== undefined && fromReferenceImages != null) {\n let transformedList = fromReferenceImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return videoGenerationReferenceImageToVertex(item);\n });\n }\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'referenceImages'],\n transformedList,\n );\n }\n\n const fromCompressionQuality = common.getValueByPath(fromObject, [\n 'compressionQuality',\n ]);\n if (parentObject !== undefined && fromCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'compressionQuality'],\n fromCompressionQuality,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'video'],\n videoToVertex(fromVideo),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(toObject, ['content'], contentFromMldev(fromContent));\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromMldev(\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function embedContentResponseFromMldev(\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromEmbeddings = common.getValueByPath(fromObject, ['embeddings']);\n if (fromEmbeddings != null) {\n let transformedList = fromEmbeddings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentEmbeddingFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['embeddings'], transformedList);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromMldev(),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromMldev(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(toObject, ['imageBytes'], t.tBytes(fromImageBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromMldev(\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromMldev(\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageFromMldev(fromImage));\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromMldev(fromSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromMldev(\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromMldev(fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function tunedModelInfoFromMldev(\n fromObject: types.TunedModelInfo,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n return toObject;\n}\n\nexport function modelFromMldev(\n fromObject: types.Model,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromVersion = common.getValueByPath(fromObject, ['version']);\n if (fromVersion != null) {\n common.setValueByPath(toObject, ['version'], fromVersion);\n }\n\n const fromTunedModelInfo = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModelInfo != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelInfo'],\n tunedModelInfoFromMldev(fromTunedModelInfo),\n );\n }\n\n const fromInputTokenLimit = common.getValueByPath(fromObject, [\n 'inputTokenLimit',\n ]);\n if (fromInputTokenLimit != null) {\n common.setValueByPath(toObject, ['inputTokenLimit'], fromInputTokenLimit);\n }\n\n const fromOutputTokenLimit = common.getValueByPath(fromObject, [\n 'outputTokenLimit',\n ]);\n if (fromOutputTokenLimit != null) {\n common.setValueByPath(toObject, ['outputTokenLimit'], fromOutputTokenLimit);\n }\n\n const fromSupportedActions = common.getValueByPath(fromObject, [\n 'supportedGenerationMethods',\n ]);\n if (fromSupportedActions != null) {\n common.setValueByPath(toObject, ['supportedActions'], fromSupportedActions);\n }\n\n return toObject;\n}\n\nexport function listModelsResponseFromMldev(\n fromObject: types.ListModelsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromModels = common.getValueByPath(fromObject, ['_self']);\n if (fromModels != null) {\n let transformedList = t.tExtractModels(fromModels);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modelFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['models'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteModelResponseFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function countTokensResponseFromMldev(\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n return toObject;\n}\n\nexport function videoFromMldev(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['video', 'uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'video',\n 'encodedVideo',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromMldev(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromMldev(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, [\n 'generatedSamples',\n ]);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, [\n 'response',\n 'generateVideoResponse',\n ]);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromMldev(fromResponse),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromVertex(\n fromObject: types.Blob,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromVertex(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citations']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromVertex(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromVertex(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromVertex(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(\n toObject,\n ['content'],\n contentFromVertex(fromContent),\n );\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromVertex(fromCitationMetadata),\n );\n }\n\n const fromFinishMessage = common.getValueByPath(fromObject, [\n 'finishMessage',\n ]);\n if (fromFinishMessage != null) {\n common.setValueByPath(toObject, ['finishMessage'], fromFinishMessage);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromVertex(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromVertex(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingStatisticsFromVertex(\n fromObject: types.ContentEmbeddingStatistics,\n): Record {\n const toObject: Record = {};\n\n const fromTruncated = common.getValueByPath(fromObject, ['truncated']);\n if (fromTruncated != null) {\n common.setValueByPath(toObject, ['truncated'], fromTruncated);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['token_count']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromVertex(\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n const fromStatistics = common.getValueByPath(fromObject, ['statistics']);\n if (fromStatistics != null) {\n common.setValueByPath(\n toObject,\n ['statistics'],\n contentEmbeddingStatisticsFromVertex(fromStatistics),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromVertex(\n fromObject: types.EmbedContentMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromBillableCharacterCount = common.getValueByPath(fromObject, [\n 'billableCharacterCount',\n ]);\n if (fromBillableCharacterCount != null) {\n common.setValueByPath(\n toObject,\n ['billableCharacterCount'],\n fromBillableCharacterCount,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentResponseFromVertex(\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromEmbeddings = common.getValueByPath(fromObject, [\n 'predictions[]',\n 'embeddings',\n ]);\n if (fromEmbeddings != null) {\n let transformedList = fromEmbeddings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentEmbeddingFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['embeddings'], transformedList);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromVertex(fromMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromVertex(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(toObject, ['imageBytes'], t.tBytes(fromImageBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromVertex(\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromVertex(\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageFromVertex(fromImage));\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromVertex(fromSafetyAttributes),\n );\n }\n\n const fromEnhancedPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromEnhancedPrompt != null) {\n common.setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt);\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromVertex(\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromVertex(fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function editImageResponseFromVertex(\n fromObject: types.EditImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function upscaleImageResponseFromVertex(\n fromObject: types.UpscaleImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function recontextImageResponseFromVertex(\n fromObject: types.RecontextImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function entityLabelFromVertex(\n fromObject: types.EntityLabel,\n): Record {\n const toObject: Record = {};\n\n const fromLabel = common.getValueByPath(fromObject, ['label']);\n if (fromLabel != null) {\n common.setValueByPath(toObject, ['label'], fromLabel);\n }\n\n const fromScore = common.getValueByPath(fromObject, ['score']);\n if (fromScore != null) {\n common.setValueByPath(toObject, ['score'], fromScore);\n }\n\n return toObject;\n}\n\nexport function generatedImageMaskFromVertex(\n fromObject: types.GeneratedImageMask,\n): Record {\n const toObject: Record = {};\n\n const fromMask = common.getValueByPath(fromObject, ['_self']);\n if (fromMask != null) {\n common.setValueByPath(toObject, ['mask'], imageFromVertex(fromMask));\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n let transformedList = fromLabels;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return entityLabelFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['labels'], transformedList);\n }\n\n return toObject;\n}\n\nexport function segmentImageResponseFromVertex(\n fromObject: types.SegmentImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedMasks = common.getValueByPath(fromObject, ['predictions']);\n if (fromGeneratedMasks != null) {\n let transformedList = fromGeneratedMasks;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageMaskFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedMasks'], transformedList);\n }\n\n return toObject;\n}\n\nexport function endpointFromVertex(\n fromObject: types.Endpoint,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['endpoint']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDeployedModelId = common.getValueByPath(fromObject, [\n 'deployedModelId',\n ]);\n if (fromDeployedModelId != null) {\n common.setValueByPath(toObject, ['deployedModelId'], fromDeployedModelId);\n }\n\n return toObject;\n}\n\nexport function tunedModelInfoFromVertex(\n fromObject: types.TunedModelInfo,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, [\n 'labels',\n 'google-vertex-llm-tuning-base-model-id',\n ]);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n return toObject;\n}\n\nexport function checkpointFromVertex(\n fromObject: types.Checkpoint,\n): Record {\n const toObject: Record = {};\n\n const fromCheckpointId = common.getValueByPath(fromObject, ['checkpointId']);\n if (fromCheckpointId != null) {\n common.setValueByPath(toObject, ['checkpointId'], fromCheckpointId);\n }\n\n const fromEpoch = common.getValueByPath(fromObject, ['epoch']);\n if (fromEpoch != null) {\n common.setValueByPath(toObject, ['epoch'], fromEpoch);\n }\n\n const fromStep = common.getValueByPath(fromObject, ['step']);\n if (fromStep != null) {\n common.setValueByPath(toObject, ['step'], fromStep);\n }\n\n return toObject;\n}\n\nexport function modelFromVertex(\n fromObject: types.Model,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromVersion = common.getValueByPath(fromObject, ['versionId']);\n if (fromVersion != null) {\n common.setValueByPath(toObject, ['version'], fromVersion);\n }\n\n const fromEndpoints = common.getValueByPath(fromObject, ['deployedModels']);\n if (fromEndpoints != null) {\n let transformedList = fromEndpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return endpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['endpoints'], transformedList);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromTunedModelInfo = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModelInfo != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelInfo'],\n tunedModelInfoFromVertex(fromTunedModelInfo),\n );\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (fromDefaultCheckpointId != null) {\n common.setValueByPath(\n toObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n const fromCheckpoints = common.getValueByPath(fromObject, ['checkpoints']);\n if (fromCheckpoints != null) {\n let transformedList = fromCheckpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return checkpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['checkpoints'], transformedList);\n }\n\n return toObject;\n}\n\nexport function listModelsResponseFromVertex(\n fromObject: types.ListModelsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromModels = common.getValueByPath(fromObject, ['_self']);\n if (fromModels != null) {\n let transformedList = t.tExtractModels(fromModels);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modelFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['models'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteModelResponseFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function countTokensResponseFromVertex(\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n return toObject;\n}\n\nexport function computeTokensResponseFromVertex(\n fromObject: types.ComputeTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTokensInfo = common.getValueByPath(fromObject, ['tokensInfo']);\n if (fromTokensInfo != null) {\n common.setValueByPath(toObject, ['tokensInfo'], fromTokensInfo);\n }\n\n return toObject;\n}\n\nexport function videoFromVertex(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromVertex(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromVertex(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromVertex(fromResponse),\n );\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from './_auth.js';\nimport * as common from './_common.js';\nimport {Downloader} from './_downloader.js';\nimport {Uploader} from './_uploader.js';\nimport {ApiError} from './errors.js';\nimport {\n DownloadFileParameters,\n File,\n HttpOptions,\n HttpResponse,\n UploadFileConfig,\n} from './types.js';\n\nconst CONTENT_TYPE_HEADER = 'Content-Type';\nconst SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';\nconst USER_AGENT_HEADER = 'User-Agent';\nexport const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';\nexport const SDK_VERSION = '1.15.0'; // x-release-please-version\nconst LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;\nconst VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';\nconst GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';\nconst responseLineRE = /^data: (.*)(?:\\n\\n|\\r\\r|\\r\\n\\r\\n)/;\n\n/**\n * Options for initializing the ApiClient. The ApiClient uses the parameters\n * for authentication purposes as well as to infer if SDK should send the\n * request to Vertex AI or Gemini API.\n */\nexport interface ApiClientInitOptions {\n /**\n * The object used for adding authentication headers to API requests.\n */\n auth: Auth;\n /**\n * The uploader to use for uploading files. This field is required for\n * creating a client, will be set through the Node_client or Web_client.\n */\n uploader: Uploader;\n /**\n * Optional. The downloader to use for downloading files. This field is\n * required for creating a client, will be set through the Node_client or\n * Web_client.\n */\n downloader: Downloader;\n /**\n * Optional. The Google Cloud project ID for Vertex AI users.\n * It is not the numeric project name.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n project?: string;\n /**\n * Optional. The Google Cloud project location for Vertex AI users.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n location?: string;\n /**\n * The API Key. This is required for Gemini API users.\n */\n apiKey?: string;\n /**\n * Optional. Set to true if you intend to call Vertex AI endpoints.\n * If unset, default SDK behavior is to call Gemini API.\n */\n vertexai?: boolean;\n /**\n * Optional. The API version for the endpoint.\n * If unset, SDK will choose a default api version.\n */\n apiVersion?: string;\n /**\n * Optional. A set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional. An extra string to append at the end of the User-Agent header.\n *\n * This can be used to e.g specify the runtime and its version.\n */\n userAgentExtra?: string;\n}\n\n/**\n * Represents the necessary information to send a request to an API endpoint.\n * This interface defines the structure for constructing and executing HTTP\n * requests.\n */\nexport interface HttpRequest {\n /**\n * URL path from the modules, this path is appended to the base API URL to\n * form the complete request URL.\n *\n * If you wish to set full URL, use httpOptions.baseUrl instead. Example to\n * set full URL in the request:\n *\n * const request: HttpRequest = {\n * path: '',\n * httpOptions: {\n * baseUrl: 'https://',\n * apiVersion: '',\n * },\n * httpMethod: 'GET',\n * };\n *\n * The result URL will be: https://\n *\n */\n path: string;\n /**\n * Optional query parameters to be appended to the request URL.\n */\n queryParams?: Record;\n /**\n * Optional request body in json string or Blob format, GET request doesn't\n * need a request body.\n */\n body?: string | Blob;\n /**\n * The HTTP method to be used for the request.\n */\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE';\n /**\n * Optional set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional abort signal which can be used to cancel the request.\n */\n abortSignal?: AbortSignal;\n}\n\n/**\n * The ApiClient class is used to send requests to the Gemini API or Vertex AI\n * endpoints.\n */\nexport class ApiClient {\n readonly clientOptions: ApiClientInitOptions;\n\n constructor(opts: ApiClientInitOptions) {\n this.clientOptions = {\n ...opts,\n project: opts.project,\n location: opts.location,\n apiKey: opts.apiKey,\n vertexai: opts.vertexai,\n };\n\n const initHttpOptions: HttpOptions = {};\n\n if (this.clientOptions.vertexai) {\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? VERTEX_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = this.baseUrlFromProjectLocation();\n this.normalizeAuthParameters();\n } else {\n // Gemini API\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? GOOGLE_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`;\n }\n\n initHttpOptions.headers = this.getDefaultHeaders();\n\n this.clientOptions.httpOptions = initHttpOptions;\n\n if (opts.httpOptions) {\n this.clientOptions.httpOptions = this.patchHttpOptions(\n initHttpOptions,\n opts.httpOptions,\n );\n }\n }\n\n /**\n * Determines the base URL for Vertex AI based on project and location.\n * Uses the global endpoint if location is 'global' or if project/location\n * are not specified (implying API key usage).\n * @private\n */\n private baseUrlFromProjectLocation(): string {\n if (\n this.clientOptions.project &&\n this.clientOptions.location &&\n this.clientOptions.location !== 'global'\n ) {\n // Regional endpoint\n return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`;\n }\n // Global endpoint (covers 'global' location and API key usage)\n return `https://aiplatform.googleapis.com/`;\n }\n\n /**\n * Normalizes authentication parameters for Vertex AI.\n * If project and location are provided, API key is cleared.\n * If project and location are not provided (implying API key usage),\n * project and location are cleared.\n * @private\n */\n private normalizeAuthParameters(): void {\n if (this.clientOptions.project && this.clientOptions.location) {\n // Using project/location for auth, clear potential API key\n this.clientOptions.apiKey = undefined;\n return;\n }\n // Using API key for auth (or no auth provided yet), clear project/location\n this.clientOptions.project = undefined;\n this.clientOptions.location = undefined;\n }\n\n isVertexAI(): boolean {\n return this.clientOptions.vertexai ?? false;\n }\n\n getProject() {\n return this.clientOptions.project;\n }\n\n getLocation() {\n return this.clientOptions.location;\n }\n\n getApiVersion() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.apiVersion !== undefined\n ) {\n return this.clientOptions.httpOptions.apiVersion;\n }\n throw new Error('API version is not set.');\n }\n\n getBaseUrl() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.baseUrl !== undefined\n ) {\n return this.clientOptions.httpOptions.baseUrl;\n }\n throw new Error('Base URL is not set.');\n }\n\n getRequestUrl() {\n return this.getRequestUrlInternal(this.clientOptions.httpOptions);\n }\n\n getHeaders() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.headers !== undefined\n ) {\n return this.clientOptions.httpOptions.headers;\n } else {\n throw new Error('Headers are not set.');\n }\n }\n\n private getRequestUrlInternal(httpOptions?: HttpOptions) {\n if (\n !httpOptions ||\n httpOptions.baseUrl === undefined ||\n httpOptions.apiVersion === undefined\n ) {\n throw new Error('HTTP options are not correctly set.');\n }\n const baseUrl = httpOptions.baseUrl.endsWith('/')\n ? httpOptions.baseUrl.slice(0, -1)\n : httpOptions.baseUrl;\n const urlElement: Array = [baseUrl];\n if (httpOptions.apiVersion && httpOptions.apiVersion !== '') {\n urlElement.push(httpOptions.apiVersion);\n }\n return urlElement.join('/');\n }\n\n getBaseResourcePath() {\n return `projects/${this.clientOptions.project}/locations/${\n this.clientOptions.location\n }`;\n }\n\n getApiKey() {\n return this.clientOptions.apiKey;\n }\n\n getWebsocketBaseUrl() {\n const baseUrl = this.getBaseUrl();\n const urlParts = new URL(baseUrl);\n urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss';\n return urlParts.toString();\n }\n\n setBaseUrl(url: string) {\n if (this.clientOptions.httpOptions) {\n this.clientOptions.httpOptions.baseUrl = url;\n } else {\n throw new Error('HTTP options are not correctly set.');\n }\n }\n\n private constructUrl(\n path: string,\n httpOptions: HttpOptions,\n prependProjectLocation: boolean,\n ): URL {\n const urlElement: Array = [this.getRequestUrlInternal(httpOptions)];\n if (prependProjectLocation) {\n urlElement.push(this.getBaseResourcePath());\n }\n if (path !== '') {\n urlElement.push(path);\n }\n const url = new URL(`${urlElement.join('/')}`);\n\n return url;\n }\n\n private shouldPrependVertexProjectPath(request: HttpRequest): boolean {\n if (this.clientOptions.apiKey) {\n return false;\n }\n if (!this.clientOptions.vertexai) {\n return false;\n }\n if (request.path.startsWith('projects/')) {\n // Assume the path already starts with\n // `projects//location/`.\n return false;\n }\n if (\n request.httpMethod === 'GET' &&\n request.path.startsWith('publishers/google/models')\n ) {\n // These paths are used by Vertex's models.get and models.list\n // calls. For base models Vertex does not accept a project/location\n // prefix (for tuned model the prefix is required).\n return false;\n }\n return true;\n }\n\n async request(request: HttpRequest): Promise {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const prependProjectLocation = this.shouldPrependVertexProjectPath(request);\n const url = this.constructUrl(\n request.path,\n patchedHttpOptions,\n prependProjectLocation,\n );\n if (request.queryParams) {\n for (const [key, value] of Object.entries(request.queryParams)) {\n url.searchParams.append(key, String(value));\n }\n }\n let requestInit: RequestInit = {};\n if (request.httpMethod === 'GET') {\n if (request.body && request.body !== '{}') {\n throw new Error(\n 'Request body should be empty for GET request, but got non empty request body',\n );\n }\n } else {\n requestInit.body = request.body;\n }\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n request.abortSignal,\n );\n return this.unaryApiCall(url, requestInit, request.httpMethod);\n }\n\n private patchHttpOptions(\n baseHttpOptions: HttpOptions,\n requestHttpOptions: HttpOptions,\n ): HttpOptions {\n const patchedHttpOptions = JSON.parse(\n JSON.stringify(baseHttpOptions),\n ) as HttpOptions;\n\n for (const [key, value] of Object.entries(requestHttpOptions)) {\n // Records compile to objects.\n if (typeof value === 'object') {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = {...patchedHttpOptions[key], ...value};\n } else if (value !== undefined) {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = value;\n }\n }\n return patchedHttpOptions;\n }\n\n async requestStream(\n request: HttpRequest,\n ): Promise> {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const prependProjectLocation = this.shouldPrependVertexProjectPath(request);\n const url = this.constructUrl(\n request.path,\n patchedHttpOptions,\n prependProjectLocation,\n );\n if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') {\n url.searchParams.set('alt', 'sse');\n }\n let requestInit: RequestInit = {};\n requestInit.body = request.body;\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n request.abortSignal,\n );\n return this.streamApiCall(url, requestInit, request.httpMethod);\n }\n\n private async includeExtraHttpOptionsToRequestInit(\n requestInit: RequestInit,\n httpOptions: HttpOptions,\n abortSignal?: AbortSignal,\n ): Promise {\n if ((httpOptions && httpOptions.timeout) || abortSignal) {\n const abortController = new AbortController();\n const signal = abortController.signal;\n if (httpOptions.timeout && httpOptions?.timeout > 0) {\n const timeoutHandle = setTimeout(\n () => abortController.abort(),\n httpOptions.timeout,\n );\n if (\n timeoutHandle &&\n typeof (timeoutHandle as unknown as NodeJS.Timeout).unref ===\n 'function'\n ) {\n // call unref to prevent nodejs process from hanging, see\n // https://nodejs.org/api/timers.html#timeoutunref\n timeoutHandle.unref();\n }\n }\n if (abortSignal) {\n abortSignal.addEventListener('abort', () => {\n abortController.abort();\n });\n }\n requestInit.signal = signal;\n }\n if (httpOptions && httpOptions.extraBody !== null) {\n includeExtraBodyToRequestInit(\n requestInit,\n httpOptions.extraBody as Record,\n );\n }\n requestInit.headers = await this.getHeadersInternal(httpOptions);\n return requestInit;\n }\n\n private async unaryApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return new HttpResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n private async streamApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise> {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return this.processStreamResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n async *processStreamResponse(\n response: Response,\n ): AsyncGenerator {\n const reader = response?.body?.getReader();\n const decoder = new TextDecoder('utf-8');\n if (!reader) {\n throw new Error('Response body is empty');\n }\n\n try {\n let buffer = '';\n while (true) {\n const {done, value} = await reader.read();\n if (done) {\n if (buffer.trim().length > 0) {\n throw new Error('Incomplete JSON segment at the end');\n }\n break;\n }\n const chunkString = decoder.decode(value, {stream: true});\n\n // Parse and throw an error if the chunk contains an error.\n try {\n const chunkJson = JSON.parse(chunkString) as Record;\n if ('error' in chunkJson) {\n const errorJson = JSON.parse(\n JSON.stringify(chunkJson['error']),\n ) as Record;\n const status = errorJson['status'] as string;\n const code = errorJson['code'] as number;\n const errorMessage = `got status: ${status}. ${JSON.stringify(\n chunkJson,\n )}`;\n if (code >= 400 && code < 600) {\n const apiError = new ApiError({\n message: errorMessage,\n status: code,\n });\n throw apiError;\n }\n }\n } catch (e: unknown) {\n const error = e as Error;\n if (error.name === 'ApiError') {\n throw e;\n }\n }\n buffer += chunkString;\n let match = buffer.match(responseLineRE);\n while (match) {\n const processedChunkString = match[1];\n try {\n const partialResponse = new Response(processedChunkString, {\n headers: response?.headers,\n status: response?.status,\n statusText: response?.statusText,\n });\n yield new HttpResponse(partialResponse);\n buffer = buffer.slice(match[0].length);\n match = buffer.match(responseLineRE);\n } catch (e) {\n throw new Error(\n `exception parsing stream chunk ${processedChunkString}. ${e}`,\n );\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n private async apiCall(\n url: string,\n requestInit: RequestInit,\n ): Promise {\n return fetch(url, requestInit).catch((e) => {\n throw new Error(`exception ${e} sending request`);\n });\n }\n\n getDefaultHeaders(): Record {\n const headers: Record = {};\n\n const versionHeaderValue =\n LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra;\n\n headers[USER_AGENT_HEADER] = versionHeaderValue;\n headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue;\n headers[CONTENT_TYPE_HEADER] = 'application/json';\n\n return headers;\n }\n\n private async getHeadersInternal(\n httpOptions: HttpOptions | undefined,\n ): Promise {\n const headers = new Headers();\n if (httpOptions && httpOptions.headers) {\n for (const [key, value] of Object.entries(httpOptions.headers)) {\n headers.append(key, value);\n }\n // Append a timeout header if it is set, note that the timeout option is\n // in milliseconds but the header is in seconds.\n if (httpOptions.timeout && httpOptions.timeout > 0) {\n headers.append(\n SERVER_TIMEOUT_HEADER,\n String(Math.ceil(httpOptions.timeout / 1000)),\n );\n }\n }\n await this.clientOptions.auth.addAuthHeaders(headers);\n return headers;\n }\n\n /**\n * Uploads a file asynchronously using Gemini API only, this is not supported\n * in Vertex AI.\n *\n * @param file The string path to the file to be uploaded or a Blob object.\n * @param config Optional parameters specified in the `UploadFileConfig`\n * interface. @see {@link UploadFileConfig}\n * @return A promise that resolves to a `File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n */\n async uploadFile(\n file: string | Blob,\n config?: UploadFileConfig,\n ): Promise {\n const fileToUpload: File = {};\n if (config != null) {\n fileToUpload.mimeType = config.mimeType;\n fileToUpload.name = config.name;\n fileToUpload.displayName = config.displayName;\n }\n\n if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) {\n fileToUpload.name = `files/${fileToUpload.name}`;\n }\n\n const uploader = this.clientOptions.uploader;\n const fileStat = await uploader.stat(file);\n fileToUpload.sizeBytes = String(fileStat.size);\n const mimeType = config?.mimeType ?? fileStat.type;\n if (mimeType === undefined || mimeType === '') {\n throw new Error(\n 'Can not determine mimeType. Please provide mimeType in the config.',\n );\n }\n fileToUpload.mimeType = mimeType;\n\n const uploadUrl = await this.fetchUploadUrl(fileToUpload, config);\n return uploader.upload(file, uploadUrl, this);\n }\n\n /**\n * Downloads a file asynchronously to the specified path.\n *\n * @params params - The parameters for the download request, see {@link\n * DownloadFileParameters}\n */\n async downloadFile(params: DownloadFileParameters): Promise {\n const downloader = this.clientOptions.downloader;\n await downloader.download(params, this);\n }\n\n private async fetchUploadUrl(\n file: File,\n config?: UploadFileConfig,\n ): Promise {\n let httpOptions: HttpOptions = {};\n if (config?.httpOptions) {\n httpOptions = config.httpOptions;\n } else {\n httpOptions = {\n apiVersion: '', // api-version is set in the path.\n headers: {\n 'Content-Type': 'application/json',\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`,\n 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`,\n },\n };\n }\n\n const body: Record = {\n 'file': file,\n };\n const httpResponse = await this.request({\n path: common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n ),\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions,\n });\n\n if (!httpResponse || !httpResponse?.headers) {\n throw new Error(\n 'Server did not return an HttpResponse or the returned HttpResponse did not have headers.',\n );\n }\n\n const uploadUrl: string | undefined =\n httpResponse?.headers?.['x-goog-upload-url'];\n if (uploadUrl === undefined) {\n throw new Error(\n 'Failed to get upload url. Server did not return the x-google-upload-url in the headers',\n );\n }\n return uploadUrl;\n }\n}\n\nasync function throwErrorIfNotOK(response: Response | undefined) {\n if (response === undefined) {\n throw new Error('response is undefined');\n }\n if (!response.ok) {\n const status: number = response.status;\n let errorBody: Record;\n if (response.headers.get('content-type')?.includes('application/json')) {\n errorBody = await response.json();\n } else {\n errorBody = {\n error: {\n message: await response.text(),\n code: response.status,\n status: response.statusText,\n },\n };\n }\n const errorMessage = JSON.stringify(errorBody);\n if (status >= 400 && status < 600) {\n const apiError = new ApiError({\n message: errorMessage,\n status: status,\n });\n throw apiError;\n }\n throw new Error(errorMessage);\n }\n}\n\n/**\n * Recursively updates the `requestInit.body` with values from an `extraBody` object.\n *\n * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed.\n * The `extraBody` is then deeply merged into this parsed object.\n * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged,\n * as merging structured data into an opaque Blob is not supported.\n *\n * The function does not enforce that updated values from `extraBody` have the\n * same type as existing values in `requestInit.body`. Type mismatches during\n * the merge will result in a warning, but the value from `extraBody` will overwrite\n * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure.\n *\n * @param requestInit The RequestInit object whose body will be updated.\n * @param extraBody The object containing updates to be merged into `requestInit.body`.\n */\nexport function includeExtraBodyToRequestInit(\n requestInit: RequestInit,\n extraBody: Record,\n) {\n if (!extraBody || Object.keys(extraBody).length === 0) {\n return;\n }\n\n if (requestInit.body instanceof Blob) {\n console.warn(\n 'includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.',\n );\n return;\n }\n\n let currentBodyObject: Record = {};\n\n // If adding new type to HttpRequest.body, please check the code below to\n // see if we need to update the logic.\n if (typeof requestInit.body === 'string' && requestInit.body.length > 0) {\n try {\n const parsedBody = JSON.parse(requestInit.body);\n if (\n typeof parsedBody === 'object' &&\n parsedBody !== null &&\n !Array.isArray(parsedBody)\n ) {\n currentBodyObject = parsedBody as Record;\n } else {\n console.warn(\n 'includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.',\n );\n return;\n }\n /* eslint-disable-next-line @typescript-eslint/no-unused-vars */\n } catch (e) {\n console.warn(\n 'includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.',\n );\n return;\n }\n }\n\n function deepMerge(\n target: Record,\n source: Record,\n ): Record {\n const output = {...target};\n for (const key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n const sourceValue = source[key];\n const targetValue = output[key];\n if (\n sourceValue &&\n typeof sourceValue === 'object' &&\n !Array.isArray(sourceValue) &&\n targetValue &&\n typeof targetValue === 'object' &&\n !Array.isArray(targetValue)\n ) {\n output[key] = deepMerge(\n targetValue as Record,\n sourceValue as Record,\n );\n } else {\n if (\n targetValue &&\n sourceValue &&\n typeof targetValue !== typeof sourceValue\n ) {\n console.warn(\n `includeExtraBodyToRequestInit:deepMerge: Type mismatch for key \"${key}\". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`,\n );\n }\n output[key] = sourceValue;\n }\n }\n }\n return output;\n }\n\n const mergedBody = deepMerge(currentBodyObject, extraBody);\n requestInit.body = JSON.stringify(mergedBody);\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {Client as McpClient} from '@modelcontextprotocol/sdk/client/index.js';\nimport type {Tool as McpTool} from '@modelcontextprotocol/sdk/types.js';\n\nimport {GOOGLE_API_CLIENT_HEADER} from '../_api_client.js';\nimport {mcpToolsToGeminiTool} from '../_transformers.js';\nimport {\n CallableTool,\n CallableToolConfig,\n FunctionCall,\n Part,\n Tool,\n ToolListUnion,\n} from '../types.js';\n\n// TODO: b/416041229 - Determine how to retrieve the MCP package version.\nexport const MCP_LABEL = 'mcp_used/unknown';\n\n// Whether MCP tool usage is detected from mcpToTool. This is used for\n// telemetry.\nlet hasMcpToolUsageFromMcpToTool = false;\n\n// Checks whether the list of tools contains any MCP tools.\nexport function hasMcpToolUsage(tools: ToolListUnion): boolean {\n for (const tool of tools) {\n if (isMcpCallableTool(tool)) {\n return true;\n }\n if (typeof tool === 'object' && 'inputSchema' in tool) {\n return true;\n }\n }\n\n return hasMcpToolUsageFromMcpToTool;\n}\n\n// Sets the MCP version label in the Google API client header.\nexport function setMcpUsageHeader(headers: Record) {\n const existingHeader = headers[GOOGLE_API_CLIENT_HEADER] ?? '';\n headers[GOOGLE_API_CLIENT_HEADER] = (\n existingHeader + ` ${MCP_LABEL}`\n ).trimStart();\n}\n\n// Returns true if the object is a MCP CallableTool, otherwise false.\nfunction isMcpCallableTool(object: unknown): boolean {\n return (\n object !== null &&\n typeof object === 'object' &&\n object instanceof McpCallableTool\n );\n}\n\n// List all tools from the MCP client.\nasync function* listAllTools(\n mcpClient: McpClient,\n maxTools: number = 100,\n): AsyncGenerator {\n let cursor: string | undefined = undefined;\n let numTools = 0;\n while (numTools < maxTools) {\n const t = await mcpClient.listTools({cursor});\n for (const tool of t.tools) {\n yield tool;\n numTools++;\n }\n if (!t.nextCursor) {\n break;\n }\n cursor = t.nextCursor;\n }\n}\n\n/**\n * McpCallableTool can be used for model inference and invoking MCP clients with\n * given function call arguments.\n *\n * @experimental Built-in MCP support is an experimental feature, may change in future\n * versions.\n */\nexport class McpCallableTool implements CallableTool {\n private readonly mcpClients;\n private mcpTools: McpTool[] = [];\n private functionNameToMcpClient: Record = {};\n private readonly config: CallableToolConfig;\n\n private constructor(\n mcpClients: McpClient[] = [],\n config: CallableToolConfig,\n ) {\n this.mcpClients = mcpClients;\n this.config = config;\n }\n\n /**\n * Creates a McpCallableTool.\n */\n public static create(\n mcpClients: McpClient[],\n config: CallableToolConfig,\n ): McpCallableTool {\n return new McpCallableTool(mcpClients, config);\n }\n\n /**\n * Validates the function names are not duplicate and initialize the function\n * name to MCP client mapping.\n *\n * @throws {Error} if the MCP tools from the MCP clients have duplicate tool\n * names.\n */\n async initialize() {\n if (this.mcpTools.length > 0) {\n return;\n }\n\n const functionMap: Record = {};\n const mcpTools: McpTool[] = [];\n for (const mcpClient of this.mcpClients) {\n for await (const mcpTool of listAllTools(mcpClient)) {\n mcpTools.push(mcpTool);\n const mcpToolName = mcpTool.name as string;\n if (functionMap[mcpToolName]) {\n throw new Error(\n `Duplicate function name ${\n mcpToolName\n } found in MCP tools. Please ensure function names are unique.`,\n );\n }\n functionMap[mcpToolName] = mcpClient;\n }\n }\n this.mcpTools = mcpTools;\n this.functionNameToMcpClient = functionMap;\n }\n\n public async tool(): Promise {\n await this.initialize();\n return mcpToolsToGeminiTool(this.mcpTools, this.config);\n }\n\n public async callTool(functionCalls: FunctionCall[]): Promise {\n await this.initialize();\n const functionCallResponseParts: Part[] = [];\n for (const functionCall of functionCalls) {\n if (functionCall.name! in this.functionNameToMcpClient) {\n const mcpClient = this.functionNameToMcpClient[functionCall.name!];\n let requestOptions = undefined;\n // TODO: b/424238654 - Add support for finer grained timeout control.\n if (this.config.timeout) {\n requestOptions = {\n timeout: this.config.timeout,\n };\n }\n const callToolResponse = await mcpClient.callTool(\n {\n name: functionCall.name!,\n arguments: functionCall.args,\n },\n // Set the result schema to undefined to allow MCP to rely on the\n // default schema.\n undefined,\n requestOptions,\n );\n functionCallResponseParts.push({\n functionResponse: {\n name: functionCall.name,\n response: callToolResponse.isError\n ? {error: callToolResponse}\n : (callToolResponse as Record),\n },\n });\n }\n }\n return functionCallResponseParts;\n }\n}\n\nfunction isMcpClient(client: unknown): client is McpClient {\n return (\n client !== null &&\n typeof client === 'object' &&\n 'listTools' in client &&\n typeof client.listTools === 'function'\n );\n}\n\n/**\n * Creates a McpCallableTool from MCP clients and an optional config.\n *\n * The callable tool can invoke the MCP clients with given function call\n * arguments. (often for automatic function calling).\n * Use the config to modify tool parameters such as behavior.\n *\n * @experimental Built-in MCP support is an experimental feature, may change in future\n * versions.\n */\nexport function mcpToTool(\n ...args: [...McpClient[], CallableToolConfig | McpClient]\n): CallableTool {\n // Set MCP usage for telemetry.\n hasMcpToolUsageFromMcpToTool = true;\n if (args.length === 0) {\n throw new Error('No MCP clients provided');\n }\n const maybeConfig = args[args.length - 1];\n if (isMcpClient(maybeConfig)) {\n return McpCallableTool.create(args as McpClient[], {});\n }\n return McpCallableTool.create(\n args.slice(0, args.length - 1) as McpClient[],\n maybeConfig,\n );\n}\n\n/**\n * Sets the MCP tool usage flag from calling mcpToTool. This is used for\n * telemetry.\n */\nexport function setMcpToolUsageFromMcpToTool(mcpToolUsage: boolean) {\n hasMcpToolUsageFromMcpToTool = mcpToolUsage;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live music client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client.js';\nimport {Auth} from './_auth.js';\nimport * as t from './_transformers.js';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket.js';\nimport * as converters from './converters/_live_converters.js';\nimport * as types from './types.js';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveMusicServerMessage, and then calling the onmessage callback.\n * Note that the first message which is received from the server is a\n * setupComplete message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveMusicServerMessage) => void,\n event: MessageEvent,\n): Promise {\n const serverMessage: types.LiveMusicServerMessage =\n new types.LiveMusicServerMessage();\n let data: types.LiveMusicServerMessage;\n if (event.data instanceof Blob) {\n data = JSON.parse(await event.data.text()) as types.LiveMusicServerMessage;\n } else {\n data = JSON.parse(event.data) as types.LiveMusicServerMessage;\n }\n const response = converters.liveMusicServerMessageFromMldev(data);\n Object.assign(serverMessage, response);\n onmessage(serverMessage);\n}\n\n/**\n LiveMusic class encapsulates the configuration for live music\n generation via Lyria Live models.\n\n @experimental\n */\nexport class LiveMusic {\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {}\n\n /**\n Establishes a connection to the specified model and returns a\n LiveMusicSession object representing that connection.\n\n @experimental\n\n @remarks\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n let model = 'models/lyria-realtime-exp';\n const session = await ai.live.music.connect({\n model: model,\n callbacks: {\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(\n params: types.LiveMusicConnectParameters,\n ): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error('Live music is not supported for Vertex AI.');\n }\n console.warn(\n 'Live music generation is experimental and may change in future versions.',\n );\n\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n const headers = mapToHeaders(this.apiClient.getDefaultHeaders());\n const apiKey = this.apiClient.getApiKey();\n const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.BidiGenerateMusic?key=${apiKey}`;\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveMusicCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n const model = t.tModel(this.apiClient, params.model);\n const setup = converters.liveMusicClientSetupToMldev({\n model,\n });\n const clientMessage = converters.liveMusicClientMessageToMldev({setup});\n conn.send(JSON.stringify(clientMessage));\n\n return new LiveMusicSession(conn, this.apiClient);\n }\n}\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class LiveMusicSession {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n /**\n Sets inputs to steer music generation. Updates the session's current\n weighted prompts.\n\n @param params - Contains one property, `weightedPrompts`.\n\n - `weightedPrompts` to send to the model; weights are normalized to\n sum to 1.0.\n\n @experimental\n */\n async setWeightedPrompts(\n params: types.LiveMusicSetWeightedPromptsParameters,\n ) {\n if (\n !params.weightedPrompts ||\n Object.keys(params.weightedPrompts).length === 0\n ) {\n throw new Error(\n 'Weighted prompts must be set and contain at least one entry.',\n );\n }\n const setWeightedPromptsParameters =\n converters.liveMusicSetWeightedPromptsParametersToMldev(params);\n const clientContent = converters.liveMusicClientContentToMldev(\n setWeightedPromptsParameters,\n );\n this.conn.send(JSON.stringify({clientContent}));\n }\n\n /**\n Sets a configuration to the model. Updates the session's current\n music generation config.\n\n @param params - Contains one property, `musicGenerationConfig`.\n\n - `musicGenerationConfig` to set in the model. Passing an empty or\n undefined config to the model will reset the config to defaults.\n\n @experimental\n */\n async setMusicGenerationConfig(params: types.LiveMusicSetConfigParameters) {\n if (!params.musicGenerationConfig) {\n params.musicGenerationConfig = {};\n }\n const setConfigParameters =\n converters.liveMusicSetConfigParametersToMldev(params);\n const clientMessage =\n converters.liveMusicClientMessageToMldev(setConfigParameters);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n private sendPlaybackControl(playbackControl: types.LiveMusicPlaybackControl) {\n const clientMessage = converters.liveMusicClientMessageToMldev({\n playbackControl,\n });\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n * Start the music stream.\n *\n * @experimental\n */\n play() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.PLAY);\n }\n\n /**\n * Temporarily halt the music stream. Use `play` to resume from the current\n * position.\n *\n * @experimental\n */\n pause() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.PAUSE);\n }\n\n /**\n * Stop the music stream and reset the state. Retains the current prompts\n * and config.\n *\n * @experimental\n */\n stop() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.STOP);\n }\n\n /**\n * Resets the context of the music generation without stopping it.\n * Retains the current prompts and config.\n *\n * @experimental\n */\n resetContext() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.RESET_CONTEXT);\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client.js';\nimport {Auth} from './_auth.js';\nimport * as t from './_transformers.js';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket.js';\nimport * as converters from './converters/_live_converters.js';\nimport {\n contentToMldev,\n contentToVertex,\n} from './converters/_models_converters.js';\nimport {hasMcpToolUsage, setMcpUsageHeader} from './mcp/_mcp.js';\nimport {LiveMusic} from './music.js';\nimport * as types from './types.js';\n\nconst FUNCTION_RESPONSE_REQUIRES_ID =\n 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveServerMessages, and then calling the onmessage callback. Note that\n * the first message which is received from the server is a setupComplete\n * message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveServerMessage) => void,\n event: MessageEvent,\n): Promise {\n const serverMessage: types.LiveServerMessage = new types.LiveServerMessage();\n let jsonData: string;\n if (event.data instanceof Blob) {\n jsonData = await event.data.text();\n } else if (event.data instanceof ArrayBuffer) {\n jsonData = new TextDecoder().decode(event.data);\n } else {\n jsonData = event.data;\n }\n\n const data = JSON.parse(jsonData) as types.LiveServerMessage;\n\n if (apiClient.isVertexAI()) {\n const resp = converters.liveServerMessageFromVertex(data);\n Object.assign(serverMessage, resp);\n } else {\n const resp = converters.liveServerMessageFromMldev(data);\n Object.assign(serverMessage, resp);\n }\n\n onmessage(serverMessage);\n}\n\n/**\n Live class encapsulates the configuration for live interaction with the\n Generative Language API. It embeds ApiClient for general API settings.\n\n @experimental\n */\nexport class Live {\n public readonly music: LiveMusic;\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {\n this.music = new LiveMusic(\n this.apiClient,\n this.auth,\n this.webSocketFactory,\n );\n }\n\n /**\n Establishes a connection to the specified model with the given\n configuration and returns a Session object representing that connection.\n\n @experimental Built-in MCP support is an experimental feature, may change in\n future versions.\n\n @remarks\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n let model: string;\n if (GOOGLE_GENAI_USE_VERTEXAI) {\n model = 'gemini-2.0-flash-live-preview-04-09';\n } else {\n model = 'gemini-live-2.5-flash-preview';\n }\n const session = await ai.live.connect({\n model: model,\n config: {\n responseModalities: [Modality.AUDIO],\n },\n callbacks: {\n onopen: () => {\n console.log('Connected to the socket.');\n },\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(params: types.LiveConnectParameters): Promise {\n // TODO: b/404946746 - Support per request HTTP options.\n if (params.config && params.config.httpOptions) {\n throw new Error(\n 'The Live module does not support httpOptions at request-level in' +\n ' LiveConnectConfig yet. Please use the client-level httpOptions' +\n ' configuration instead.',\n );\n }\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n let url: string;\n const clientHeaders = this.apiClient.getHeaders();\n if (\n params.config &&\n params.config.tools &&\n hasMcpToolUsage(params.config.tools)\n ) {\n setMcpUsageHeader(clientHeaders);\n }\n const headers = mapToHeaders(clientHeaders);\n if (this.apiClient.isVertexAI()) {\n url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${\n apiVersion\n }.LlmBidiService/BidiGenerateContent`;\n await this.auth.addAuthHeaders(headers);\n } else {\n const apiKey = this.apiClient.getApiKey();\n\n let method = 'BidiGenerateContent';\n let keyName = 'key';\n if (apiKey?.startsWith('auth_tokens/')) {\n console.warn(\n 'Warning: Ephemeral token support is experimental and may change in future versions.',\n );\n if (apiVersion !== 'v1alpha') {\n console.warn(\n \"Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection.\",\n );\n }\n method = 'BidiGenerateContentConstrained';\n keyName = 'access_token';\n }\n\n url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.${method}?${keyName}=${apiKey}`;\n }\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n callbacks?.onopen?.();\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n let transformedModel = t.tModel(this.apiClient, params.model);\n if (\n this.apiClient.isVertexAI() &&\n transformedModel.startsWith('publishers/')\n ) {\n const project = this.apiClient.getProject();\n const location = this.apiClient.getLocation();\n transformedModel =\n `projects/${project}/locations/${location}/` + transformedModel;\n }\n\n let clientMessage: Record = {};\n\n if (\n this.apiClient.isVertexAI() &&\n params.config?.responseModalities === undefined\n ) {\n // Set default to AUDIO to align with MLDev API.\n if (params.config === undefined) {\n params.config = {responseModalities: [types.Modality.AUDIO]};\n } else {\n params.config.responseModalities = [types.Modality.AUDIO];\n }\n }\n if (params.config?.generationConfig) {\n // Raise deprecation warning for generationConfig.\n console.warn(\n 'Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).',\n );\n }\n const inputTools = params.config?.tools ?? [];\n const convertedTools: types.Tool[] = [];\n for (const tool of inputTools) {\n if (this.isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n convertedTools.push(await callableTool.tool());\n } else {\n convertedTools.push(tool as types.Tool);\n }\n }\n if (convertedTools.length > 0) {\n params.config!.tools = convertedTools;\n }\n const liveConnectParameters: types.LiveConnectParameters = {\n model: transformedModel,\n config: params.config,\n callbacks: params.callbacks,\n };\n if (this.apiClient.isVertexAI()) {\n clientMessage = converters.liveConnectParametersToVertex(\n this.apiClient,\n liveConnectParameters,\n );\n } else {\n clientMessage = converters.liveConnectParametersToMldev(\n this.apiClient,\n liveConnectParameters,\n );\n }\n delete clientMessage['config'];\n conn.send(JSON.stringify(clientMessage));\n return new Session(conn, this.apiClient);\n }\n\n // TODO: b/416041229 - Abstract this method to a common place.\n private isCallableTool(tool: types.ToolUnion): boolean {\n return 'callTool' in tool && typeof tool.callTool === 'function';\n }\n}\n\nconst defaultLiveSendClientContentParamerters: types.LiveSendClientContentParameters =\n {\n turnComplete: true,\n };\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class Session {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n private tLiveClientContent(\n apiClient: ApiClient,\n params: types.LiveSendClientContentParameters,\n ): types.LiveClientMessage {\n if (params.turns !== null && params.turns !== undefined) {\n let contents: types.Content[] = [];\n try {\n contents = t.tContents(params.turns as types.ContentListUnion);\n if (apiClient.isVertexAI()) {\n contents = contents.map((item) => contentToVertex(item));\n } else {\n contents = contents.map((item) => contentToMldev(item));\n }\n } catch {\n throw new Error(\n `Failed to parse client content \"turns\", type: '${typeof params.turns}'`,\n );\n }\n return {\n clientContent: {turns: contents, turnComplete: params.turnComplete},\n };\n }\n\n return {\n clientContent: {turnComplete: params.turnComplete},\n };\n }\n\n private tLiveClienttToolResponse(\n apiClient: ApiClient,\n params: types.LiveSendToolResponseParameters,\n ): types.LiveClientMessage {\n let functionResponses: types.FunctionResponse[] = [];\n\n if (params.functionResponses == null) {\n throw new Error('functionResponses is required.');\n }\n\n if (!Array.isArray(params.functionResponses)) {\n functionResponses = [params.functionResponses];\n } else {\n functionResponses = params.functionResponses;\n }\n\n if (functionResponses.length === 0) {\n throw new Error('functionResponses is required.');\n }\n\n for (const functionResponse of functionResponses) {\n if (\n typeof functionResponse !== 'object' ||\n functionResponse === null ||\n !('name' in functionResponse) ||\n !('response' in functionResponse)\n ) {\n throw new Error(\n `Could not parse function response, type '${typeof functionResponse}'.`,\n );\n }\n if (!apiClient.isVertexAI() && !('id' in functionResponse)) {\n throw new Error(FUNCTION_RESPONSE_REQUIRES_ID);\n }\n }\n\n const clientMessage: types.LiveClientMessage = {\n toolResponse: {functionResponses: functionResponses},\n };\n return clientMessage;\n }\n\n /**\n Send a message over the established connection.\n\n @param params - Contains two **optional** properties, `turns` and\n `turnComplete`.\n\n - `turns` will be converted to a `Content[]`\n - `turnComplete: true` [default] indicates that you are done sending\n content and expect a response. If `turnComplete: false`, the server\n will wait for additional messages before starting generation.\n\n @experimental\n\n @remarks\n There are two ways to send messages to the live API:\n `sendClientContent` and `sendRealtimeInput`.\n\n `sendClientContent` messages are added to the model context **in order**.\n Having a conversation using `sendClientContent` messages is roughly\n equivalent to using the `Chat.sendMessageStream`, except that the state of\n the `chat` history is stored on the API server instead of locally.\n\n Because of `sendClientContent`'s order guarantee, the model cannot respons\n as quickly to `sendClientContent` messages as to `sendRealtimeInput`\n messages. This makes the biggest difference when sending objects that have\n significant preprocessing time (typically images).\n\n The `sendClientContent` message sends a `Content[]`\n which has more options than the `Blob` sent by `sendRealtimeInput`.\n\n So the main use-cases for `sendClientContent` over `sendRealtimeInput` are:\n\n - Sending anything that can't be represented as a `Blob` (text,\n `sendClientContent({turns=\"Hello?\"}`)).\n - Managing turns when not using audio input and voice activity detection.\n (`sendClientContent({turnComplete:true})` or the short form\n `sendClientContent()`)\n - Prefilling a conversation context\n ```\n sendClientContent({\n turns: [\n Content({role:user, parts:...}),\n Content({role:user, parts:...}),\n ...\n ]\n })\n ```\n @experimental\n */\n sendClientContent(params: types.LiveSendClientContentParameters) {\n params = {\n ...defaultLiveSendClientContentParamerters,\n ...params,\n };\n\n const clientMessage: types.LiveClientMessage = this.tLiveClientContent(\n this.apiClient,\n params,\n );\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a realtime message over the established connection.\n\n @param params - Contains one property, `media`.\n\n - `media` will be converted to a `Blob`\n\n @experimental\n\n @remarks\n Use `sendRealtimeInput` for realtime audio chunks and video frames (images).\n\n With `sendRealtimeInput` the api will respond to audio automatically\n based on voice activity detection (VAD).\n\n `sendRealtimeInput` is optimized for responsivness at the expense of\n deterministic ordering guarantees. Audio and video tokens are to the\n context when they become available.\n\n Note: The Call signature expects a `Blob` object, but only a subset\n of audio and image mimetypes are allowed.\n */\n sendRealtimeInput(params: types.LiveSendRealtimeInputParameters) {\n let clientMessage: types.LiveClientMessage = {};\n\n if (this.apiClient.isVertexAI()) {\n clientMessage = {\n 'realtimeInput':\n converters.liveSendRealtimeInputParametersToVertex(params),\n };\n } else {\n clientMessage = {\n 'realtimeInput':\n converters.liveSendRealtimeInputParametersToMldev(params),\n };\n }\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a function response message over the established connection.\n\n @param params - Contains property `functionResponses`.\n\n - `functionResponses` will be converted to a `functionResponses[]`\n\n @remarks\n Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server.\n\n Use {@link types.LiveConnectConfig#tools} to configure the callable functions.\n\n @experimental\n */\n sendToolResponse(params: types.LiveSendToolResponseParameters) {\n if (params.functionResponses == null) {\n throw new Error('Tool response parameters are required.');\n }\n\n const clientMessage: types.LiveClientMessage =\n this.tLiveClienttToolResponse(this.apiClient, params);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n\n @example\n ```ts\n let model: string;\n if (GOOGLE_GENAI_USE_VERTEXAI) {\n model = 'gemini-2.0-flash-live-preview-04-09';\n } else {\n model = 'gemini-live-2.5-flash-preview';\n }\n const session = await ai.live.connect({\n model: model,\n config: {\n responseModalities: [Modality.AUDIO],\n }\n });\n\n session.close();\n ```\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as types from './types.js';\n\nexport const DEFAULT_MAX_REMOTE_CALLS = 10;\n\n/** Returns whether automatic function calling is disabled. */\nexport function shouldDisableAfc(\n config: types.GenerateContentConfig | undefined,\n): boolean {\n if (config?.automaticFunctionCalling?.disable) {\n return true;\n }\n\n let callableToolsPresent = false;\n for (const tool of config?.tools ?? []) {\n if (isCallableTool(tool)) {\n callableToolsPresent = true;\n break;\n }\n }\n if (!callableToolsPresent) {\n return true;\n }\n\n const maxCalls = config?.automaticFunctionCalling?.maximumRemoteCalls;\n if (\n (maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) ||\n maxCalls == 0\n ) {\n console.warn(\n 'Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:',\n maxCalls,\n );\n return true;\n }\n return false;\n}\n\nexport function isCallableTool(tool: types.ToolUnion): boolean {\n return 'callTool' in tool && typeof tool.callTool === 'function';\n}\n\n// Checks whether the list of tools contains any CallableTools. Will return true\n// if there is at least one CallableTool.\nexport function hasCallableTools(\n params: types.GenerateContentParameters,\n): boolean {\n return params.config?.tools?.some((tool) => isCallableTool(tool)) ?? false;\n}\n\n// Checks whether the list of tools contains any non-callable tools. Will return\n// true if there is at least one non-Callable tool.\nexport function hasNonCallableTools(\n params: types.GenerateContentParameters,\n): boolean {\n return params.config?.tools?.some((tool) => !isCallableTool(tool)) ?? false;\n}\n\n/**\n * Returns whether to append automatic function calling history to the\n * response.\n */\nexport function shouldAppendAfcHistory(\n config: types.GenerateContentConfig | undefined,\n): boolean {\n return !config?.automaticFunctionCalling?.ignoreCallHistory;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {\n DEFAULT_MAX_REMOTE_CALLS,\n hasCallableTools,\n hasNonCallableTools,\n isCallableTool,\n shouldAppendAfcHistory,\n shouldDisableAfc,\n} from './_afc.js';\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as _internal_types from './_internal_types.js';\nimport {tContents} from './_transformers.js';\nimport * as converters from './converters/_models_converters.js';\nimport {hasMcpToolUsage, setMcpUsageHeader} from './mcp/_mcp.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Models extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Makes an API request to generate content with a given model.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * candidateCount: 2,\n * }\n * });\n * console.log(response);\n * ```\n */\n generateContent = async (\n params: types.GenerateContentParameters,\n ): Promise => {\n const transformedParams = await this.processParamsMaybeAddMcpUsage(params);\n this.maybeMoveToResponseJsonSchem(params);\n if (!hasCallableTools(params) || shouldDisableAfc(params.config)) {\n return await this.generateContentInternal(transformedParams);\n }\n\n if (hasNonCallableTools(params)) {\n throw new Error(\n 'Automatic function calling with CallableTools and Tools is not yet supported.',\n );\n }\n\n let response: types.GenerateContentResponse;\n let functionResponseContent: types.Content;\n const automaticFunctionCallingHistory: types.Content[] = tContents(\n transformedParams.contents,\n );\n const maxRemoteCalls =\n transformedParams.config?.automaticFunctionCalling?.maximumRemoteCalls ??\n DEFAULT_MAX_REMOTE_CALLS;\n let remoteCalls = 0;\n while (remoteCalls < maxRemoteCalls) {\n response = await this.generateContentInternal(transformedParams);\n if (!response.functionCalls || response.functionCalls!.length === 0) {\n break;\n }\n\n const responseContent: types.Content = response.candidates![0].content!;\n const functionResponseParts: types.Part[] = [];\n for (const tool of params.config?.tools ?? []) {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n const parts = await callableTool.callTool(response.functionCalls!);\n functionResponseParts.push(...parts);\n }\n }\n\n remoteCalls++;\n\n functionResponseContent = {\n role: 'user',\n parts: functionResponseParts,\n };\n\n transformedParams.contents = tContents(transformedParams.contents);\n (transformedParams.contents as types.Content[]).push(responseContent);\n (transformedParams.contents as types.Content[]).push(\n functionResponseContent,\n );\n\n if (shouldAppendAfcHistory(transformedParams.config)) {\n automaticFunctionCallingHistory.push(responseContent);\n automaticFunctionCallingHistory.push(functionResponseContent);\n }\n }\n if (shouldAppendAfcHistory(transformedParams.config)) {\n response!.automaticFunctionCallingHistory =\n automaticFunctionCallingHistory;\n }\n return response!;\n };\n\n /**\n * This logic is needed for GenerateContentConfig only.\n * Previously we made GenerateContentConfig.responseSchema field to accept\n * unknown. Since v1.9.0, we switch to use backend JSON schema support.\n * To maintain backward compatibility, we move the data that was treated as\n * JSON schema from the responseSchema field to the responseJsonSchema field.\n */\n private maybeMoveToResponseJsonSchem(\n params: types.GenerateContentParameters,\n ): void {\n if (params.config && params.config.responseSchema) {\n if (!params.config.responseJsonSchema) {\n if (Object.keys(params.config.responseSchema).includes('$schema')) {\n params.config.responseJsonSchema = params.config.responseSchema;\n delete params.config.responseSchema;\n }\n }\n }\n return;\n }\n\n /**\n * Makes an API request to generate content with a given model and yields the\n * response in chunks.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content with streaming response.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContentStream({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * maxOutputTokens: 200,\n * }\n * });\n * for await (const chunk of response) {\n * console.log(chunk);\n * }\n * ```\n */\n generateContentStream = async (\n params: types.GenerateContentParameters,\n ): Promise> => {\n this.maybeMoveToResponseJsonSchem(params);\n if (shouldDisableAfc(params.config)) {\n const transformedParams =\n await this.processParamsMaybeAddMcpUsage(params);\n return await this.generateContentStreamInternal(transformedParams);\n } else {\n return await this.processAfcStream(params);\n }\n };\n\n /**\n * Transforms the CallableTools in the parameters to be simply Tools, it\n * copies the params into a new object and replaces the tools, it does not\n * modify the original params. Also sets the MCP usage header if there are\n * MCP tools in the parameters.\n */\n private async processParamsMaybeAddMcpUsage(\n params: types.GenerateContentParameters,\n ): Promise {\n const tools = params.config?.tools;\n if (!tools) {\n return params;\n }\n const transformedTools = await Promise.all(\n tools.map(async (tool) => {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n return await callableTool.tool();\n }\n return tool;\n }),\n );\n const newParams: types.GenerateContentParameters = {\n model: params.model,\n contents: params.contents,\n config: {\n ...params.config,\n tools: transformedTools,\n },\n };\n newParams.config!.tools = transformedTools;\n\n if (\n params.config &&\n params.config.tools &&\n hasMcpToolUsage(params.config.tools)\n ) {\n const headers = params.config.httpOptions?.headers ?? {};\n let newHeaders = {...headers};\n if (Object.keys(newHeaders).length === 0) {\n newHeaders = this.apiClient.getDefaultHeaders();\n }\n setMcpUsageHeader(newHeaders);\n newParams.config!.httpOptions = {\n ...params.config.httpOptions,\n headers: newHeaders,\n };\n }\n return newParams;\n }\n\n private async initAfcToolsMap(\n params: types.GenerateContentParameters,\n ): Promise> {\n const afcTools: Map = new Map();\n for (const tool of params.config?.tools ?? []) {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n const toolDeclaration = await callableTool.tool();\n for (const declaration of toolDeclaration.functionDeclarations ?? []) {\n if (!declaration.name) {\n throw new Error('Function declaration name is required.');\n }\n if (afcTools.has(declaration.name)) {\n throw new Error(\n `Duplicate tool declaration name: ${declaration.name}`,\n );\n }\n afcTools.set(declaration.name, callableTool);\n }\n }\n }\n return afcTools;\n }\n\n private async processAfcStream(\n params: types.GenerateContentParameters,\n ): Promise> {\n const maxRemoteCalls =\n params.config?.automaticFunctionCalling?.maximumRemoteCalls ??\n DEFAULT_MAX_REMOTE_CALLS;\n let wereFunctionsCalled = false;\n let remoteCallCount = 0;\n const afcToolsMap = await this.initAfcToolsMap(params);\n return (async function* (\n models: Models,\n afcTools: Map,\n params: types.GenerateContentParameters,\n ) {\n while (remoteCallCount < maxRemoteCalls) {\n if (wereFunctionsCalled) {\n remoteCallCount++;\n wereFunctionsCalled = false;\n }\n const transformedParams =\n await models.processParamsMaybeAddMcpUsage(params);\n const response =\n await models.generateContentStreamInternal(transformedParams);\n\n const functionResponses: types.Part[] = [];\n const responseContents: types.Content[] = [];\n\n for await (const chunk of response) {\n yield chunk;\n if (chunk.candidates && chunk.candidates[0]?.content) {\n responseContents.push(chunk.candidates[0].content);\n for (const part of chunk.candidates[0].content.parts ?? []) {\n if (remoteCallCount < maxRemoteCalls && part.functionCall) {\n if (!part.functionCall.name) {\n throw new Error(\n 'Function call name was not returned by the model.',\n );\n }\n if (!afcTools.has(part.functionCall.name)) {\n throw new Error(\n `Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${\n part.functionCall.name\n }`,\n );\n } else {\n const responseParts = await afcTools\n .get(part.functionCall.name)!\n .callTool([part.functionCall]);\n functionResponses.push(...responseParts);\n }\n }\n }\n }\n }\n\n if (functionResponses.length > 0) {\n wereFunctionsCalled = true;\n const typedResponseChunk = new types.GenerateContentResponse();\n typedResponseChunk.candidates = [\n {\n content: {\n role: 'user',\n parts: functionResponses,\n },\n },\n ];\n\n yield typedResponseChunk;\n\n const newContents: types.Content[] = [];\n newContents.push(...responseContents);\n newContents.push({\n role: 'user',\n parts: functionResponses,\n });\n const updatedContents = tContents(params.contents).concat(\n newContents,\n );\n\n params.contents = updatedContents;\n } else {\n break;\n }\n }\n })(this, afcToolsMap, params);\n }\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param params - The parameters for generating images.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n generateImages = async (\n params: types.GenerateImagesParameters,\n ): Promise => {\n return await this.generateImagesInternal(params).then((apiResponse) => {\n let positivePromptSafetyAttributes;\n const generatedImages = [];\n\n if (apiResponse?.generatedImages) {\n for (const generatedImage of apiResponse.generatedImages) {\n if (\n generatedImage &&\n generatedImage?.safetyAttributes &&\n generatedImage?.safetyAttributes?.contentType === 'Positive Prompt'\n ) {\n positivePromptSafetyAttributes = generatedImage?.safetyAttributes;\n } else {\n generatedImages.push(generatedImage);\n }\n }\n }\n let response: types.GenerateImagesResponse;\n\n if (positivePromptSafetyAttributes) {\n response = {\n generatedImages: generatedImages,\n positivePromptSafetyAttributes: positivePromptSafetyAttributes,\n sdkHttpResponse: apiResponse.sdkHttpResponse,\n };\n } else {\n response = {\n generatedImages: generatedImages,\n sdkHttpResponse: apiResponse.sdkHttpResponse,\n };\n }\n return response;\n });\n };\n\n list = async (\n params?: types.ListModelsParameters,\n ): Promise> => {\n const defaultConfig: types.ListModelsConfig = {\n queryBase: true,\n };\n const actualConfig: types.ListModelsConfig = {\n ...defaultConfig,\n ...params?.config,\n };\n const actualParams: types.ListModelsParameters = {\n config: actualConfig,\n };\n\n if (this.apiClient.isVertexAI()) {\n if (!actualParams.config!.queryBase) {\n if (actualParams.config?.filter) {\n throw new Error(\n 'Filtering tuned models list for Vertex AI is not currently supported',\n );\n } else {\n actualParams.config!.filter = 'labels.tune-type:*';\n }\n }\n }\n\n return new Pager(\n PagedItem.PAGED_ITEM_MODELS,\n (x: types.ListModelsParameters) => this.listInternal(x),\n await this.listInternal(actualParams),\n actualParams,\n );\n };\n\n /**\n * Edits an image based on a prompt, list of reference images, and configuration.\n *\n * @param params - The parameters for editing an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.editImage({\n * model: 'imagen-3.0-capability-001',\n * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.',\n * referenceImages: [subjectReferenceImage]\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n editImage = async (\n params: types.EditImageParameters,\n ): Promise => {\n const paramsInternal: _internal_types.EditImageParametersInternal = {\n model: params.model,\n prompt: params.prompt,\n referenceImages: [],\n config: params.config,\n };\n if (params.referenceImages) {\n if (params.referenceImages) {\n paramsInternal.referenceImages = params.referenceImages.map((img) =>\n img.toReferenceImageAPI(),\n );\n }\n }\n return await this.editImageInternal(paramsInternal);\n };\n\n /**\n * Upscales an image based on an image, upscale factor, and configuration.\n * Only supported in Vertex AI currently.\n *\n * @param params - The parameters for upscaling an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.upscaleImage({\n * model: 'imagen-3.0-generate-002',\n * image: image,\n * upscaleFactor: 'x2',\n * config: {\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n upscaleImage = async (\n params: types.UpscaleImageParameters,\n ): Promise => {\n let apiConfig: _internal_types.UpscaleImageAPIConfigInternal = {\n numberOfImages: 1,\n mode: 'upscale',\n };\n\n if (params.config) {\n apiConfig = {...apiConfig, ...params.config};\n }\n\n const apiParams: _internal_types.UpscaleImageAPIParametersInternal = {\n model: params.model,\n image: params.image,\n upscaleFactor: params.upscaleFactor,\n config: apiConfig,\n };\n return await this.upscaleImageInternal(apiParams);\n };\n\n /**\n * Generates videos based on a text description and configuration.\n *\n * @param params - The parameters for generating videos.\n * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method.\n *\n * @example\n * ```ts\n * const operation = await ai.models.generateVideos({\n * model: 'veo-2.0-generate-001',\n * prompt: 'A neon hologram of a cat driving at top speed',\n * config: {\n * numberOfVideos: 1\n * });\n *\n * while (!operation.done) {\n * await new Promise(resolve => setTimeout(resolve, 10000));\n * operation = await ai.operations.getVideosOperation({operation: operation});\n * }\n *\n * console.log(operation.response?.generatedVideos?.[0]?.video?.uri);\n * ```\n */\n\n generateVideos = async (\n params: types.GenerateVideosParameters,\n ): Promise => {\n return await this.generateVideosInternal(params);\n };\n\n private async generateContentInternal(\n params: types.GenerateContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromVertex(apiResponse);\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromMldev(apiResponse);\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async generateContentStreamInternal(\n params: types.GenerateContentParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromVertex(\n (await chunk.json()) as types.GenerateContentResponse,\n );\n\n resp['sdkHttpResponse'] = {\n headers: chunk.headers,\n } as types.HttpResponse;\n\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromMldev(\n (await chunk.json()) as types.GenerateContentResponse,\n );\n\n resp['sdkHttpResponse'] = {\n headers: chunk.headers,\n } as types.HttpResponse;\n\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n }\n }\n\n /**\n * Calculates embeddings for the given contents. Only text is supported.\n *\n * @param params - The parameters for embedding contents.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.embedContent({\n * model: 'text-embedding-004',\n * contents: [\n * 'What is your name?',\n * 'What is your favorite color?',\n * ],\n * config: {\n * outputDimensionality: 64,\n * },\n * });\n * console.log(response);\n * ```\n */\n async embedContent(\n params: types.EmbedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.embedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EmbedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromVertex(apiResponse);\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.embedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchEmbedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EmbedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromMldev(apiResponse);\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param params - The parameters for generating images.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n private async generateImagesInternal(\n params: types.GenerateImagesParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateImagesParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateImagesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromVertex(apiResponse);\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateImagesParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateImagesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromMldev(apiResponse);\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async editImageInternal(\n params: _internal_types.EditImageParametersInternal,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.editImageParametersInternalToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EditImageResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.editImageResponseFromVertex(apiResponse);\n const typedResp = new types.EditImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n private async upscaleImageInternal(\n params: _internal_types.UpscaleImageAPIParametersInternal,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.upscaleImageAPIParametersInternalToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.UpscaleImageResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.upscaleImageResponseFromVertex(apiResponse);\n const typedResp = new types.UpscaleImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Recontextualizes an image.\n *\n * There are two types of recontextualization currently supported:\n * 1) Imagen Product Recontext - Generate images of products in new scenes\n * and contexts.\n * 2) Virtual Try-On: Generate images of persons modeling fashion products.\n *\n * @param params - The parameters for recontextualizing an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response1 = await ai.models.recontextImage({\n * model: 'imagen-product-recontext-preview-06-30',\n * source: {\n * prompt: 'In a modern kitchen setting.',\n * productImages: [productImage],\n * },\n * config: {\n * numberOfImages: 1,\n * },\n * });\n * console.log(response1?.generatedImages?.[0]?.image?.imageBytes);\n *\n * const response2 = await ai.models.recontextImage({\n * model: 'virtual-try-on-preview-08-04',\n * source: {\n * personImage: personImage,\n * productImages: [productImage],\n * },\n * config: {\n * numberOfImages: 1,\n * },\n * });\n * console.log(response2?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n async recontextImage(\n params: types.RecontextImageParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.recontextImageParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.recontextImageResponseFromVertex(apiResponse);\n const typedResp = new types.RecontextImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Segments an image, creating a mask of a specified area.\n *\n * @param params - The parameters for segmenting an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.segmentImage({\n * model: 'image-segmentation-001',\n * source: {\n * image: image,\n * },\n * config: {\n * mode: 'foreground',\n * },\n * });\n * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes);\n * ```\n */\n async segmentImage(\n params: types.SegmentImageParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.segmentImageParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.segmentImageResponseFromVertex(apiResponse);\n const typedResp = new types.SegmentImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Fetches information about a model by name.\n *\n * @example\n * ```ts\n * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'});\n * ```\n */\n async get(params: types.GetModelParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromVertex(apiResponse);\n\n return resp as types.Model;\n });\n } else {\n const body = converters.getModelParametersToMldev(this.apiClient, params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromMldev(apiResponse);\n\n return resp as types.Model;\n });\n }\n }\n\n private async listInternal(\n params: types.ListModelsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listModelsParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{models_url}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListModelsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listModelsResponseFromVertex(apiResponse);\n const typedResp = new types.ListModelsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listModelsParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{models_url}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListModelsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listModelsResponseFromMldev(apiResponse);\n const typedResp = new types.ListModelsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates a tuned model by its name.\n *\n * @param params - The parameters for updating the model.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.update({\n * model: 'tuned-model-name',\n * config: {\n * displayName: 'New display name',\n * description: 'New description',\n * },\n * });\n * ```\n */\n async update(params: types.UpdateModelParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromVertex(apiResponse);\n\n return resp as types.Model;\n });\n } else {\n const body = converters.updateModelParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromMldev(apiResponse);\n\n return resp as types.Model;\n });\n }\n }\n\n /**\n * Deletes a tuned model by its name.\n *\n * @param params - The parameters for deleting the model.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.delete({model: 'tuned-model-name'});\n * ```\n */\n async delete(\n params: types.DeleteModelParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteModelResponseFromVertex();\n const typedResp = new types.DeleteModelResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteModelParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteModelResponseFromMldev();\n const typedResp = new types.DeleteModelResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Counts the number of tokens in the given contents. Multimodal input is\n * supported for Gemini models.\n *\n * @param params - The parameters for counting tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.countTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'The quick brown fox jumps over the lazy dog.'\n * });\n * console.log(response);\n * ```\n */\n async countTokens(\n params: types.CountTokensParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.countTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.CountTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromVertex(apiResponse);\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.countTokensParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.CountTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromMldev(apiResponse);\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Given a list of contents, returns a corresponding TokensInfo containing\n * the list of tokens and list of token ids.\n *\n * This method is not supported by the Gemini Developer API.\n *\n * @param params - The parameters for computing tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.computeTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'What is your name?'\n * });\n * console.log(response);\n * ```\n */\n async computeTokens(\n params: types.ComputeTokensParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.computeTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:computeTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ComputeTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.computeTokensResponseFromVertex(apiResponse);\n const typedResp = new types.ComputeTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Generates videos based on a text description and configuration.\n *\n * @param params - The parameters for generating videos.\n * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method.\n *\n * @example\n * ```ts\n * const operation = await ai.models.generateVideos({\n * model: 'veo-2.0-generate-001',\n * prompt: 'A neon hologram of a cat driving at top speed',\n * config: {\n * numberOfVideos: 1\n * });\n *\n * while (!operation.done) {\n * await new Promise(resolve => setTimeout(resolve, 10000));\n * operation = await ai.operations.getVideosOperation({operation: operation});\n * }\n *\n * console.log(operation.response?.generatedVideos?.[0]?.video?.uri);\n * ```\n */\n\n private async generateVideosInternal(\n params: types.GenerateVideosParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateVideosParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromVertex(apiResponse);\n const typedResp = new types.GenerateVideosOperation();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateVideosParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromMldev(apiResponse);\n const typedResp = new types.GenerateVideosOperation();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as types from '../types.js';\n\nexport function getOperationParametersToMldev(\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getOperationParametersToVertex(\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fetchPredictOperationParametersToVertex(\n fromObject: types.FetchPredictOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(toObject, ['operationName'], fromOperationName);\n }\n\n const fromResourceName = common.getValueByPath(fromObject, ['resourceName']);\n if (fromResourceName != null) {\n common.setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_operations_converters.js';\nimport * as types from './types.js';\n\nexport class Operations extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param parameters The parameters for the get operation request.\n * @return The updated Operation object, with the latest status or result.\n */\n async getVideosOperation(\n parameters: types.OperationGetParameters<\n types.GenerateVideosResponse,\n types.GenerateVideosOperation\n >,\n ): Promise {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n let httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n const rawOperation = await this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: true,\n });\n } else {\n const rawOperation = await this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: false,\n });\n }\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param parameters The parameters for the get operation request.\n * @return The updated Operation object, with the latest status or result.\n */\n async get>(\n parameters: types.OperationGetParameters,\n ): Promise> {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n let httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n const rawOperation = await this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: true,\n });\n } else {\n const rawOperation = await this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: false,\n });\n }\n }\n\n private async getVideosOperationInternal(\n params: types.GetOperationParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getOperationParametersToVertex(params);\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n } else {\n const body = converters.getOperationParametersToMldev(params);\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n }\n }\n\n private async fetchPredictVideosOperationInternal(\n params: types.FetchPredictOperationParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.fetchPredictOperationParametersToVertex(params);\n path = common.formatMap(\n '{resourceName}:fetchPredictOperation',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n if (common.getValueByPath(fromObject, ['excludeDomains']) !== undefined) {\n throw new Error('excludeDomains parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToMldev(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n if (common.getValueByPath(fromObject, ['transparent']) !== undefined) {\n throw new Error('transparent parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToMldev(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToMldev(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToMldev(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToMldev(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToMldev(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToMldev(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToMldev(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToMldev(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToMldev(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectConstraintsToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectConstraints,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateAuthTokenConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromNewSessionExpireTime = common.getValueByPath(fromObject, [\n 'newSessionExpireTime',\n ]);\n if (parentObject !== undefined && fromNewSessionExpireTime != null) {\n common.setValueByPath(\n parentObject,\n ['newSessionExpireTime'],\n fromNewSessionExpireTime,\n );\n }\n\n const fromUses = common.getValueByPath(fromObject, ['uses']);\n if (parentObject !== undefined && fromUses != null) {\n common.setValueByPath(parentObject, ['uses'], fromUses);\n }\n\n const fromLiveConnectConstraints = common.getValueByPath(fromObject, [\n 'liveConnectConstraints',\n ]);\n if (parentObject !== undefined && fromLiveConnectConstraints != null) {\n common.setValueByPath(\n parentObject,\n ['bidiGenerateContentSetup'],\n liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints),\n );\n }\n\n const fromLockAdditionalFields = common.getValueByPath(fromObject, [\n 'lockAdditionalFields',\n ]);\n if (parentObject !== undefined && fromLockAdditionalFields != null) {\n common.setValueByPath(\n parentObject,\n ['fieldMask'],\n fromLockAdditionalFields,\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateAuthTokenParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createAuthTokenConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenParametersToVertex(\n fromObject: types.CreateAuthTokenParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['config']) !== undefined) {\n throw new Error('config parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function authTokenFromMldev(\n fromObject: types.AuthToken,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function authTokenFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_tokens_converters.js';\nimport * as types from './types.js';\n\n/**\n * Returns a comma-separated list of field masks from a given object.\n *\n * @param setup The object to extract field masks from.\n * @return A comma-separated list of field masks.\n */\nfunction getFieldMasks(setup: Record): string {\n const fields: string[] = [];\n\n for (const key in setup) {\n if (Object.prototype.hasOwnProperty.call(setup, key)) {\n const value = setup[key];\n // 2nd layer, recursively get field masks see TODO(b/418290100)\n if (\n typeof value === 'object' &&\n value != null &&\n Object.keys(value).length > 0\n ) {\n const field = Object.keys(value).map((kk) => `${key}.${kk}`);\n fields.push(...field);\n } else {\n fields.push(key); // 1st layer\n }\n }\n }\n\n return fields.join(',');\n}\n\n/**\n * Converts bidiGenerateContentSetup.\n * @param requestDict - The request dictionary.\n * @param config - The configuration object.\n * @return - The modified request dictionary.\n */\nfunction convertBidiSetupToTokenSetup(\n requestDict: Record,\n config?: {lockAdditionalFields?: string[]},\n): Record {\n // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup.\n let setupForMaskGeneration: Record | null = null;\n const bidiGenerateContentSetupValue = requestDict['bidiGenerateContentSetup'];\n if (\n typeof bidiGenerateContentSetupValue === 'object' &&\n bidiGenerateContentSetupValue !== null &&\n 'setup' in bidiGenerateContentSetupValue\n ) {\n // Now we know bidiGenerateContentSetupValue is an object and has a 'setup'\n // property.\n const innerSetup = (bidiGenerateContentSetupValue as {setup: unknown})\n .setup;\n\n if (typeof innerSetup === 'object' && innerSetup !== null) {\n // Valid inner setup found.\n requestDict['bidiGenerateContentSetup'] = innerSetup;\n setupForMaskGeneration = innerSetup as Record;\n } else {\n // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as\n // if bidiGenerateContentSetup is invalid.\n delete requestDict['bidiGenerateContentSetup'];\n }\n } else if (bidiGenerateContentSetupValue !== undefined) {\n // `bidiGenerateContentSetup` exists but not in the expected\n // shape {setup: {...}}; treat as invalid.\n delete requestDict['bidiGenerateContentSetup'];\n }\n\n const preExistingFieldMask = requestDict['fieldMask'];\n // Handle mask generation setup.\n if (setupForMaskGeneration) {\n const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration);\n\n if (\n Array.isArray(config?.lockAdditionalFields) &&\n config?.lockAdditionalFields.length === 0\n ) {\n // Case 1: lockAdditionalFields is an empty array. Lock only fields from\n // bidi setup.\n if (generatedMaskFromBidi) {\n // Only assign if mask is not empty\n requestDict['fieldMask'] = generatedMaskFromBidi;\n } else {\n delete requestDict['fieldMask']; // If mask is empty, effectively no\n // specific fields locked by bidi\n }\n } else if (\n config?.lockAdditionalFields &&\n config.lockAdditionalFields.length > 0 &&\n preExistingFieldMask !== null &&\n Array.isArray(preExistingFieldMask) &&\n preExistingFieldMask.length > 0\n ) {\n // Case 2: Lock fields from bidi setup + additional fields\n // (preExistingFieldMask).\n\n const generationConfigFields = [\n 'temperature',\n 'topK',\n 'topP',\n 'maxOutputTokens',\n 'responseModalities',\n 'seed',\n 'speechConfig',\n ];\n\n let mappedFieldsFromPreExisting: string[] = [];\n if (preExistingFieldMask.length > 0) {\n mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => {\n if (generationConfigFields.includes(field)) {\n return `generationConfig.${field}`;\n }\n return field; // Keep original field name if not in\n // generationConfigFields\n });\n }\n\n const finalMaskParts: string[] = [];\n if (generatedMaskFromBidi) {\n finalMaskParts.push(generatedMaskFromBidi);\n }\n if (mappedFieldsFromPreExisting.length > 0) {\n finalMaskParts.push(...mappedFieldsFromPreExisting);\n }\n\n if (finalMaskParts.length > 0) {\n requestDict['fieldMask'] = finalMaskParts.join(',');\n } else {\n // If no fields from bidi and no valid additional fields from\n // pre-existing mask.\n delete requestDict['fieldMask'];\n }\n } else {\n // Case 3: \"Lock all fields\" (meaning, don't send a field_mask, let server\n // defaults apply or all are mutable). This is hit if:\n // - `config.lockAdditionalFields` is undefined.\n // - `config.lockAdditionalFields` is non-empty, BUT\n // `preExistingFieldMask` is null, not a string, or an empty string.\n delete requestDict['fieldMask'];\n }\n } else {\n // No valid `bidiGenerateContentSetup` was found or extracted.\n // \"Lock additional null fields if any\".\n if (\n preExistingFieldMask !== null &&\n Array.isArray(preExistingFieldMask) &&\n preExistingFieldMask.length > 0\n ) {\n // If there's a pre-existing field mask, it's a string, and it's not\n // empty, then we should lock all fields.\n requestDict['fieldMask'] = preExistingFieldMask.join(',');\n } else {\n delete requestDict['fieldMask'];\n }\n }\n\n return requestDict;\n}\n\nexport class Tokens extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n /**\n * Creates an ephemeral auth token resource.\n *\n * @experimental\n *\n * @remarks\n * Ephemeral auth tokens is only supported in the Gemini Developer API.\n * It can be used for the session connection to the Live constrained API.\n * Support in v1alpha only.\n *\n * @param params - The parameters for the create request.\n * @return The created auth token.\n *\n * @example\n * ```ts\n * const ai = new GoogleGenAI({\n * apiKey: token.name,\n * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only.\n * });\n *\n * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig\n * // when using the token in Live API sessions. Each session connection can\n * // use a different configuration.\n * const config: CreateAuthTokenConfig = {\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 2: If LiveEphemeralParameters is set, lock all fields in\n * // LiveConnectConfig when using the token in Live API sessions. For\n * // example, changing `outputAudioTranscription` in the Live API\n * // connection will be ignored by the API.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * }\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is\n * // set, lock LiveConnectConfig with set and additional fields (e.g.\n * // responseModalities, systemInstruction, temperature in this example) when\n * // using the token in Live API sessions.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * },\n * lockAdditionalFields: ['temperature'],\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is\n * // empty array, lock LiveConnectConfig with set fields (e.g.\n * // responseModalities, systemInstruction in this example) when using the\n * // token in Live API sessions.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * },\n * lockAdditionalFields: [],\n * }\n * const token = await ai.tokens.create(config);\n * ```\n */\n\n async create(\n params: types.CreateAuthTokenParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'The client.tokens.create method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createAuthTokenParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'auth_tokens',\n body['_url'] as Record,\n );\n\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const transformedBody = convertBidiSetupToTokenSetup(body, params.config);\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(transformedBody),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.authTokenFromMldev(apiResponse);\n\n return resp as types.AuthToken;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function getTuningJobParametersToMldev(\n fromObject: types.GetTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsConfigToMldev(\n fromObject: types.ListTuningJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsParametersToMldev(\n fromObject: types.ListTuningJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listTuningJobsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function tuningExampleToMldev(\n fromObject: types.TuningExample,\n): Record {\n const toObject: Record = {};\n\n const fromTextInput = common.getValueByPath(fromObject, ['textInput']);\n if (fromTextInput != null) {\n common.setValueByPath(toObject, ['textInput'], fromTextInput);\n }\n\n const fromOutput = common.getValueByPath(fromObject, ['output']);\n if (fromOutput != null) {\n common.setValueByPath(toObject, ['output'], fromOutput);\n }\n\n return toObject;\n}\n\nexport function tuningDatasetToMldev(\n fromObject: types.TuningDataset,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['vertexDatasetResource']) !== undefined\n ) {\n throw new Error(\n 'vertexDatasetResource parameter is not supported in Gemini API.',\n );\n }\n\n const fromExamples = common.getValueByPath(fromObject, ['examples']);\n if (fromExamples != null) {\n let transformedList = fromExamples;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningExampleToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['examples', 'examples'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createTuningJobConfigToMldev(\n fromObject: types.CreateTuningJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['validationDataset']) !== undefined) {\n throw new Error(\n 'validationDataset parameter is not supported in Gemini API.',\n );\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (parentObject !== undefined && fromTunedModelDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['displayName'],\n fromTunedModelDisplayName,\n );\n }\n\n if (common.getValueByPath(fromObject, ['description']) !== undefined) {\n throw new Error('description parameter is not supported in Gemini API.');\n }\n\n const fromEpochCount = common.getValueByPath(fromObject, ['epochCount']);\n if (parentObject !== undefined && fromEpochCount != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'epochCount'],\n fromEpochCount,\n );\n }\n\n const fromLearningRateMultiplier = common.getValueByPath(fromObject, [\n 'learningRateMultiplier',\n ]);\n if (fromLearningRateMultiplier != null) {\n common.setValueByPath(\n toObject,\n ['tuningTask', 'hyperparameters', 'learningRateMultiplier'],\n fromLearningRateMultiplier,\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['exportLastCheckpointOnly']) !==\n undefined\n ) {\n throw new Error(\n 'exportLastCheckpointOnly parameter is not supported in Gemini API.',\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['preTunedModelCheckpointId']) !==\n undefined\n ) {\n throw new Error(\n 'preTunedModelCheckpointId parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['adapterSize']) !== undefined) {\n throw new Error('adapterSize parameter is not supported in Gemini API.');\n }\n\n const fromBatchSize = common.getValueByPath(fromObject, ['batchSize']);\n if (parentObject !== undefined && fromBatchSize != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'batchSize'],\n fromBatchSize,\n );\n }\n\n const fromLearningRate = common.getValueByPath(fromObject, ['learningRate']);\n if (parentObject !== undefined && fromLearningRate != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'learningRate'],\n fromLearningRate,\n );\n }\n\n return toObject;\n}\n\nexport function createTuningJobParametersPrivateToMldev(\n fromObject: types.CreateTuningJobParametersPrivate,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromPreTunedModel = common.getValueByPath(fromObject, [\n 'preTunedModel',\n ]);\n if (fromPreTunedModel != null) {\n common.setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel);\n }\n\n const fromTrainingDataset = common.getValueByPath(fromObject, [\n 'trainingDataset',\n ]);\n if (fromTrainingDataset != null) {\n common.setValueByPath(\n toObject,\n ['tuningTask', 'trainingData'],\n tuningDatasetToMldev(fromTrainingDataset),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createTuningJobConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getTuningJobParametersToVertex(\n fromObject: types.GetTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsConfigToVertex(\n fromObject: types.ListTuningJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsParametersToVertex(\n fromObject: types.ListTuningJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listTuningJobsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function tuningDatasetToVertex(\n fromObject: types.TuningDataset,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (parentObject !== undefined && fromGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromGcsUri,\n );\n }\n\n const fromVertexDatasetResource = common.getValueByPath(fromObject, [\n 'vertexDatasetResource',\n ]);\n if (parentObject !== undefined && fromVertexDatasetResource != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromVertexDatasetResource,\n );\n }\n\n if (common.getValueByPath(fromObject, ['examples']) !== undefined) {\n throw new Error('examples parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function tuningValidationDatasetToVertex(\n fromObject: types.TuningValidationDataset,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['validationDatasetUri'], fromGcsUri);\n }\n\n const fromVertexDatasetResource = common.getValueByPath(fromObject, [\n 'vertexDatasetResource',\n ]);\n if (parentObject !== undefined && fromVertexDatasetResource != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromVertexDatasetResource,\n );\n }\n\n return toObject;\n}\n\nexport function createTuningJobConfigToVertex(\n fromObject: types.CreateTuningJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromValidationDataset = common.getValueByPath(fromObject, [\n 'validationDataset',\n ]);\n if (parentObject !== undefined && fromValidationDataset != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec'],\n tuningValidationDatasetToVertex(fromValidationDataset, toObject),\n );\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (parentObject !== undefined && fromTunedModelDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromEpochCount = common.getValueByPath(fromObject, ['epochCount']);\n if (parentObject !== undefined && fromEpochCount != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'epochCount'],\n fromEpochCount,\n );\n }\n\n const fromLearningRateMultiplier = common.getValueByPath(fromObject, [\n 'learningRateMultiplier',\n ]);\n if (parentObject !== undefined && fromLearningRateMultiplier != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'],\n fromLearningRateMultiplier,\n );\n }\n\n const fromExportLastCheckpointOnly = common.getValueByPath(fromObject, [\n 'exportLastCheckpointOnly',\n ]);\n if (parentObject !== undefined && fromExportLastCheckpointOnly != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'exportLastCheckpointOnly'],\n fromExportLastCheckpointOnly,\n );\n }\n\n const fromPreTunedModelCheckpointId = common.getValueByPath(fromObject, [\n 'preTunedModelCheckpointId',\n ]);\n if (fromPreTunedModelCheckpointId != null) {\n common.setValueByPath(\n toObject,\n ['preTunedModel', 'checkpointId'],\n fromPreTunedModelCheckpointId,\n );\n }\n\n const fromAdapterSize = common.getValueByPath(fromObject, ['adapterSize']);\n if (parentObject !== undefined && fromAdapterSize != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'],\n fromAdapterSize,\n );\n }\n\n if (common.getValueByPath(fromObject, ['batchSize']) !== undefined) {\n throw new Error('batchSize parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['learningRate']) !== undefined) {\n throw new Error('learningRate parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function createTuningJobParametersPrivateToVertex(\n fromObject: types.CreateTuningJobParametersPrivate,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromPreTunedModel = common.getValueByPath(fromObject, [\n 'preTunedModel',\n ]);\n if (fromPreTunedModel != null) {\n common.setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel);\n }\n\n const fromTrainingDataset = common.getValueByPath(fromObject, [\n 'trainingDataset',\n ]);\n if (fromTrainingDataset != null) {\n common.setValueByPath(\n toObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n tuningDatasetToVertex(fromTrainingDataset, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createTuningJobConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function tunedModelFromMldev(\n fromObject: types.TunedModel,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['name']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['name']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n return toObject;\n}\n\nexport function tuningJobFromMldev(\n fromObject: types.TuningJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tTuningJobStatus(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, [\n 'tuningTask',\n 'startTime',\n ]);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, [\n 'tuningTask',\n 'completeTime',\n ]);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTunedModel = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModel != null) {\n common.setValueByPath(\n toObject,\n ['tunedModel'],\n tunedModelFromMldev(fromTunedModel),\n );\n }\n\n const fromCustomBaseModel = common.getValueByPath(fromObject, [\n 'customBaseModel',\n ]);\n if (fromCustomBaseModel != null) {\n common.setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel);\n }\n\n const fromExperiment = common.getValueByPath(fromObject, ['experiment']);\n if (fromExperiment != null) {\n common.setValueByPath(toObject, ['experiment'], fromExperiment);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromOutputUri = common.getValueByPath(fromObject, ['outputUri']);\n if (fromOutputUri != null) {\n common.setValueByPath(toObject, ['outputUri'], fromOutputUri);\n }\n\n const fromPipelineJob = common.getValueByPath(fromObject, ['pipelineJob']);\n if (fromPipelineJob != null) {\n common.setValueByPath(toObject, ['pipelineJob'], fromPipelineJob);\n }\n\n const fromServiceAccount = common.getValueByPath(fromObject, [\n 'serviceAccount',\n ]);\n if (fromServiceAccount != null) {\n common.setValueByPath(toObject, ['serviceAccount'], fromServiceAccount);\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (fromTunedModelDisplayName != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n return toObject;\n}\n\nexport function listTuningJobsResponseFromMldev(\n fromObject: types.ListTuningJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromTuningJobs = common.getValueByPath(fromObject, ['tunedModels']);\n if (fromTuningJobs != null) {\n let transformedList = fromTuningJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningJobFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['tuningJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function tuningOperationFromMldev(\n fromObject: types.TuningOperation,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n return toObject;\n}\n\nexport function tunedModelCheckpointFromVertex(\n fromObject: types.TunedModelCheckpoint,\n): Record {\n const toObject: Record = {};\n\n const fromCheckpointId = common.getValueByPath(fromObject, ['checkpointId']);\n if (fromCheckpointId != null) {\n common.setValueByPath(toObject, ['checkpointId'], fromCheckpointId);\n }\n\n const fromEpoch = common.getValueByPath(fromObject, ['epoch']);\n if (fromEpoch != null) {\n common.setValueByPath(toObject, ['epoch'], fromEpoch);\n }\n\n const fromStep = common.getValueByPath(fromObject, ['step']);\n if (fromStep != null) {\n common.setValueByPath(toObject, ['step'], fromStep);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['endpoint']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n return toObject;\n}\n\nexport function tunedModelFromVertex(\n fromObject: types.TunedModel,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['endpoint']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n const fromCheckpoints = common.getValueByPath(fromObject, ['checkpoints']);\n if (fromCheckpoints != null) {\n let transformedList = fromCheckpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tunedModelCheckpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['checkpoints'], transformedList);\n }\n\n return toObject;\n}\n\nexport function tuningJobFromVertex(\n fromObject: types.TuningJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tTuningJobStatus(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTunedModel = common.getValueByPath(fromObject, ['tunedModel']);\n if (fromTunedModel != null) {\n common.setValueByPath(\n toObject,\n ['tunedModel'],\n tunedModelFromVertex(fromTunedModel),\n );\n }\n\n const fromPreTunedModel = common.getValueByPath(fromObject, [\n 'preTunedModel',\n ]);\n if (fromPreTunedModel != null) {\n common.setValueByPath(toObject, ['preTunedModel'], fromPreTunedModel);\n }\n\n const fromSupervisedTuningSpec = common.getValueByPath(fromObject, [\n 'supervisedTuningSpec',\n ]);\n if (fromSupervisedTuningSpec != null) {\n common.setValueByPath(\n toObject,\n ['supervisedTuningSpec'],\n fromSupervisedTuningSpec,\n );\n }\n\n const fromTuningDataStats = common.getValueByPath(fromObject, [\n 'tuningDataStats',\n ]);\n if (fromTuningDataStats != null) {\n common.setValueByPath(toObject, ['tuningDataStats'], fromTuningDataStats);\n }\n\n const fromEncryptionSpec = common.getValueByPath(fromObject, [\n 'encryptionSpec',\n ]);\n if (fromEncryptionSpec != null) {\n common.setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec);\n }\n\n const fromPartnerModelTuningSpec = common.getValueByPath(fromObject, [\n 'partnerModelTuningSpec',\n ]);\n if (fromPartnerModelTuningSpec != null) {\n common.setValueByPath(\n toObject,\n ['partnerModelTuningSpec'],\n fromPartnerModelTuningSpec,\n );\n }\n\n const fromCustomBaseModel = common.getValueByPath(fromObject, [\n 'customBaseModel',\n ]);\n if (fromCustomBaseModel != null) {\n common.setValueByPath(toObject, ['customBaseModel'], fromCustomBaseModel);\n }\n\n const fromExperiment = common.getValueByPath(fromObject, ['experiment']);\n if (fromExperiment != null) {\n common.setValueByPath(toObject, ['experiment'], fromExperiment);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromOutputUri = common.getValueByPath(fromObject, ['outputUri']);\n if (fromOutputUri != null) {\n common.setValueByPath(toObject, ['outputUri'], fromOutputUri);\n }\n\n const fromPipelineJob = common.getValueByPath(fromObject, ['pipelineJob']);\n if (fromPipelineJob != null) {\n common.setValueByPath(toObject, ['pipelineJob'], fromPipelineJob);\n }\n\n const fromServiceAccount = common.getValueByPath(fromObject, [\n 'serviceAccount',\n ]);\n if (fromServiceAccount != null) {\n common.setValueByPath(toObject, ['serviceAccount'], fromServiceAccount);\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (fromTunedModelDisplayName != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n return toObject;\n}\n\nexport function listTuningJobsResponseFromVertex(\n fromObject: types.ListTuningJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromTuningJobs = common.getValueByPath(fromObject, ['tuningJobs']);\n if (fromTuningJobs != null) {\n let transformedList = fromTuningJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningJobFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['tuningJobs'], transformedList);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_tunings_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Tunings extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets a TuningJob.\n *\n * @param name - The resource name of the tuning job.\n * @return - A TuningJob object.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n get = async (\n params: types.GetTuningJobParameters,\n ): Promise => {\n return await this.getInternal(params);\n };\n\n /**\n * Lists tuning jobs.\n *\n * @param config - The configuration for the list request.\n * @return - A list of tuning jobs.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n list = async (\n params: types.ListTuningJobsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_TUNING_JOBS,\n (x: types.ListTuningJobsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a supervised fine-tuning job.\n *\n * @param params - The parameters for the tuning job.\n * @return - A TuningJob operation.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n tune = async (\n params: types.CreateTuningJobParameters,\n ): Promise => {\n if (this.apiClient.isVertexAI()) {\n if (params.baseModel.startsWith('projects/')) {\n const preTunedModel: types.PreTunedModel = {\n tunedModelName: params.baseModel,\n };\n const paramsPrivate: types.CreateTuningJobParametersPrivate = {\n ...params,\n preTunedModel: preTunedModel,\n };\n paramsPrivate.baseModel = undefined;\n return await this.tuneInternal(paramsPrivate);\n } else {\n const paramsPrivate: types.CreateTuningJobParametersPrivate = {\n ...params,\n };\n return await this.tuneInternal(paramsPrivate);\n }\n } else {\n const paramsPrivate: types.CreateTuningJobParametersPrivate = {\n ...params,\n };\n const operation = await this.tuneMldevInternal(paramsPrivate);\n let tunedModelName = '';\n if (\n operation['metadata'] !== undefined &&\n operation['metadata']['tunedModel'] !== undefined\n ) {\n tunedModelName = operation['metadata']['tunedModel'] as string;\n } else if (\n operation['name'] !== undefined &&\n operation['name'].includes('/operations/')\n ) {\n tunedModelName = operation['name'].split('/operations/')[0];\n }\n const tuningJob: types.TuningJob = {\n name: tunedModelName,\n state: types.JobState.JOB_STATE_QUEUED,\n };\n\n return tuningJob;\n }\n };\n\n private async getInternal(\n params: types.GetTuningJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getTuningJobParametersToVertex(params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromVertex(apiResponse);\n\n return resp as types.TuningJob;\n });\n } else {\n const body = converters.getTuningJobParametersToMldev(params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromMldev(apiResponse);\n\n return resp as types.TuningJob;\n });\n }\n }\n\n private async listInternal(\n params: types.ListTuningJobsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listTuningJobsParametersToVertex(params);\n path = common.formatMap(\n 'tuningJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListTuningJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listTuningJobsResponseFromVertex(apiResponse);\n const typedResp = new types.ListTuningJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listTuningJobsParametersToMldev(params);\n path = common.formatMap(\n 'tunedModels',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListTuningJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listTuningJobsResponseFromMldev(apiResponse);\n const typedResp = new types.ListTuningJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async tuneInternal(\n params: types.CreateTuningJobParametersPrivate,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createTuningJobParametersPrivateToVertex(params);\n path = common.formatMap(\n 'tuningJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromVertex(apiResponse);\n\n return resp as types.TuningJob;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n private async tuneMldevInternal(\n params: types.CreateTuningJobParametersPrivate,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createTuningJobParametersPrivateToMldev(params);\n path = common.formatMap(\n 'tunedModels',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningOperation;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningOperationFromMldev(apiResponse);\n\n return resp as types.TuningOperation;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from '../_api_client.js';\nimport {Downloader} from '../_downloader.js';\nimport {DownloadFileParameters} from '../types.js';\n\nexport class BrowserDownloader implements Downloader {\n async download(\n _params: DownloadFileParameters,\n _apiClient: ApiClient,\n ): Promise {\n throw new Error(\n 'Download to file is not supported in the browser, please use a browser compliant download like an tag.',\n );\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {ApiClient} from '../_api_client.js';\nimport {FileStat, Uploader} from '../_uploader.js';\nimport {File, HttpResponse} from '../types.js';\n\nimport {crossError} from './_cross_error.js';\n\nexport const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes\nexport const MAX_RETRY_COUNT = 3;\nexport const INITIAL_RETRY_DELAY_MS = 1000;\nexport const DELAY_MULTIPLIER = 2;\nexport const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status';\n\nexport class CrossUploader implements Uploader {\n async upload(\n file: string | Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return uploadBlob(file, uploadUrl, apiClient);\n }\n }\n\n async stat(file: string | Blob): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return getBlobStat(file);\n }\n }\n}\n\nexport async function uploadBlob(\n file: Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n): Promise {\n let fileSize = 0;\n let offset = 0;\n let response: HttpResponse = new HttpResponse(new Response());\n let uploadCommand = 'upload';\n fileSize = file.size;\n while (offset < fileSize) {\n const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);\n const chunk = file.slice(offset, offset + chunkSize);\n if (offset + chunkSize >= fileSize) {\n uploadCommand += ', finalize';\n }\n let retryCount = 0;\n let currentDelayMs = INITIAL_RETRY_DELAY_MS;\n while (retryCount < MAX_RETRY_COUNT) {\n response = await apiClient.request({\n path: '',\n body: chunk,\n httpMethod: 'POST',\n httpOptions: {\n apiVersion: '',\n baseUrl: uploadUrl,\n headers: {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': String(offset),\n 'Content-Length': String(chunkSize),\n },\n },\n });\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) {\n break;\n }\n retryCount++;\n await sleep(currentDelayMs);\n currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;\n }\n offset += chunkSize;\n // The `x-goog-upload-status` header field can be `active`, `final` and\n //`cancelled` in resposne.\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'active') {\n break;\n }\n // TODO(b/401391430) Investigate why the upload status is not finalized\n // even though all content has been uploaded.\n if (fileSize <= offset) {\n throw new Error(\n 'All content has been uploaded, but the upload status is not finalized.',\n );\n }\n }\n const responseJson = (await response?.json()) as Record<\n string,\n File | unknown\n >;\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'final') {\n throw new Error('Failed to upload file: Upload status is not finalized.');\n }\n return responseJson['file'] as File;\n}\n\nexport async function getBlobStat(file: Blob): Promise {\n const fileStat: FileStat = {size: file.size, type: file.type};\n return fileStat;\n}\n\nexport function sleep(ms: number): Promise {\n return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {ApiClient} from '../_api_client.js';\nimport {FileStat, Uploader} from '../_uploader.js';\nimport {getBlobStat, uploadBlob} from '../cross/_cross_uploader.js';\nimport {File} from '../types.js';\n\nexport class BrowserUploader implements Uploader {\n async upload(\n file: string | Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n if (typeof file === 'string') {\n throw new Error('File path is not supported in browser uploader.');\n }\n\n return await uploadBlob(file, uploadUrl, apiClient);\n }\n\n async stat(file: string | Blob): Promise {\n if (typeof file === 'string') {\n throw new Error('File path is not supported in browser uploader.');\n } else {\n return await getBlobStat(file);\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n WebSocketCallbacks,\n WebSocketFactory,\n WebSocket as Ws,\n} from '../_websocket.js';\n\nexport class BrowserWebSocketFactory implements WebSocketFactory {\n create(\n url: string,\n headers: Record,\n callbacks: WebSocketCallbacks,\n ): Ws {\n return new BrowserWebSocket(url, headers, callbacks);\n }\n}\n\nexport class BrowserWebSocket implements Ws {\n private ws?: WebSocket;\n\n constructor(\n private readonly url: string,\n private readonly headers: Record,\n private readonly callbacks: WebSocketCallbacks,\n ) {}\n\n connect(): void {\n this.ws = new WebSocket(this.url);\n\n this.ws.onopen = this.callbacks.onopen;\n this.ws.onerror = this.callbacks.onerror;\n this.ws.onclose = this.callbacks.onclose;\n this.ws.onmessage = this.callbacks.onmessage;\n }\n\n send(message: string) {\n if (this.ws === undefined) {\n throw new Error('WebSocket is not connected');\n }\n\n this.ws.send(message);\n }\n\n close() {\n if (this.ws === undefined) {\n throw new Error('WebSocket is not connected');\n }\n\n this.ws.close();\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from '../_auth.js';\n\nexport const GOOGLE_API_KEY_HEADER = 'x-goog-api-key';\n// TODO(b/395122533): We need a secure client side authentication mechanism.\nexport class WebAuth implements Auth {\n constructor(private readonly apiKey: string) {}\n\n async addAuthHeaders(headers: Headers): Promise {\n if (headers.get(GOOGLE_API_KEY_HEADER) !== null) {\n return;\n }\n\n if (this.apiKey.startsWith('auth_tokens/')) {\n throw new Error('Ephemeral tokens are only supported by the live API.');\n }\n\n // Check if API key is empty or null\n if (!this.apiKey) {\n throw new Error('API key is missing. Please provide a valid API key.');\n }\n headers.append(GOOGLE_API_KEY_HEADER, this.apiKey);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from '../_api_client.js';\nimport {getBaseUrl} from '../_base_url.js';\nimport {Batches} from '../batches.js';\nimport {Caches} from '../caches.js';\nimport {Chats} from '../chats.js';\nimport {GoogleGenAIOptions} from '../client.js';\nimport {Files} from '../files.js';\nimport {Live} from '../live.js';\nimport {Models} from '../models.js';\nimport {Operations} from '../operations.js';\nimport {Tokens} from '../tokens.js';\nimport {Tunings} from '../tunings.js';\n\nimport {BrowserDownloader} from './_browser_downloader.js';\nimport {BrowserUploader} from './_browser_uploader.js';\nimport {BrowserWebSocketFactory} from './_browser_websocket.js';\nimport {WebAuth} from './_web_auth.js';\n\nconst LANGUAGE_LABEL_PREFIX = 'gl-node/';\n\n/**\n * The Google GenAI SDK.\n *\n * @remarks\n * Provides access to the GenAI features through either the {@link\n * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or\n * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI\n * API}.\n *\n * The {@link GoogleGenAIOptions.vertexai} value determines which of the API\n * services to use.\n *\n * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be\n * set. When using Vertex AI, currently only {@link GoogleGenAIOptions.apiKey}\n * is supported via Express mode. {@link GoogleGenAIOptions.project} and {@link\n * GoogleGenAIOptions.location} should not be set.\n *\n * @example\n * Initializing the SDK for using the Gemini API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n *\n * @example\n * Initializing the SDK for using the Vertex AI API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({\n * vertexai: true,\n * project: 'PROJECT_ID',\n * location: 'PROJECT_LOCATION'\n * });\n * ```\n *\n */\nexport class GoogleGenAI {\n protected readonly apiClient: ApiClient;\n private readonly apiKey?: string;\n public readonly vertexai: boolean;\n private readonly apiVersion?: string;\n readonly models: Models;\n readonly live: Live;\n readonly batches: Batches;\n readonly chats: Chats;\n readonly caches: Caches;\n readonly files: Files;\n readonly operations: Operations;\n readonly authTokens: Tokens;\n readonly tunings: Tunings;\n\n constructor(options: GoogleGenAIOptions) {\n if (options.apiKey == null) {\n throw new Error('An API Key must be set when running in a browser');\n }\n // Web client only supports API key mode for Vertex AI.\n if (options.project || options.location) {\n throw new Error(\n 'Vertex AI project based authentication is not supported on browser runtimes. Please do not provide a project or location.',\n );\n }\n this.vertexai = options.vertexai ?? false;\n\n this.apiKey = options.apiKey;\n\n const baseUrl = getBaseUrl(\n options.httpOptions,\n options.vertexai,\n /*vertexBaseUrlFromEnv*/ undefined,\n /*geminiBaseUrlFromEnv*/ undefined,\n );\n if (baseUrl) {\n if (options.httpOptions) {\n options.httpOptions.baseUrl = baseUrl;\n } else {\n options.httpOptions = {baseUrl: baseUrl};\n }\n }\n\n this.apiVersion = options.apiVersion;\n const auth = new WebAuth(this.apiKey);\n this.apiClient = new ApiClient({\n auth: auth,\n apiVersion: this.apiVersion,\n apiKey: this.apiKey,\n vertexai: this.vertexai,\n httpOptions: options.httpOptions,\n userAgentExtra: LANGUAGE_LABEL_PREFIX + 'web',\n uploader: new BrowserUploader(),\n downloader: new BrowserDownloader(),\n });\n this.models = new Models(this.apiClient);\n this.live = new Live(this.apiClient, auth, new BrowserWebSocketFactory());\n this.batches = new Batches(this.apiClient);\n this.chats = new Chats(this.models, this.apiClient);\n this.caches = new Caches(this.apiClient);\n this.files = new Files(this.apiClient);\n this.operations = new Operations(this.apiClient);\n this.authTokens = new Tokens(this.apiClient);\n this.tunings = new Tunings(this.apiClient);\n }\n}\n"],"names":["tBytes","types.Type","baseTransformers.tBytes","videoMetadataToMldev","common.getValueByPath","common.setValueByPath","blobToMldev","fileDataToMldev","partToMldev","contentToMldev","schemaToMldev","safetySettingToMldev","functionDeclarationToMldev","intervalToMldev","googleSearchToMldev","dynamicRetrievalConfigToMldev","googleSearchRetrievalToMldev","urlContextToMldev","toolComputerUseToMldev","toolToMldev","functionCallingConfigToMldev","latLngToMldev","retrievalConfigToMldev","toolConfigToMldev","prebuiltVoiceConfigToMldev","voiceConfigToMldev","speakerVoiceConfigToMldev","multiSpeakerVoiceConfigToMldev","speechConfigToMldev","thinkingConfigToMldev","generateContentConfigToMldev","t.tContent","t.tSchema","t.tTools","t.tTool","t.tCachedContentName","t.tSpeechConfig","t.tModel","t.tContents","t.tBatchJobSource","t.tBatchJobName","t.tBatchJobDestination","videoMetadataFromMldev","blobFromMldev","fileDataFromMldev","partFromMldev","contentFromMldev","citationMetadataFromMldev","urlMetadataFromMldev","urlContextMetadataFromMldev","candidateFromMldev","generateContentResponseFromMldev","t.tJobState","converters.createBatchJobParametersToMldev","common.formatMap","converters.batchJobFromMldev","converters.createBatchJobParametersToVertex","converters.batchJobFromVertex","converters.getBatchJobParametersToVertex","converters.getBatchJobParametersToMldev","converters.cancelBatchJobParametersToVertex","converters.cancelBatchJobParametersToMldev","converters.listBatchJobsParametersToVertex","converters.listBatchJobsResponseFromVertex","types.ListBatchJobsResponse","converters.listBatchJobsParametersToMldev","converters.listBatchJobsResponseFromMldev","converters.deleteBatchJobParametersToVertex","converters.deleteResourceJobFromVertex","converters.deleteBatchJobParametersToMldev","converters.deleteResourceJobFromMldev","t.tCachesModel","videoMetadataToVertex","blobToVertex","fileDataToVertex","partToVertex","contentToVertex","functionDeclarationToVertex","intervalToVertex","googleSearchToVertex","dynamicRetrievalConfigToVertex","googleSearchRetrievalToVertex","enterpriseWebSearchToVertex","apiKeyConfigToVertex","authConfigToVertex","googleMapsToVertex","urlContextToVertex","toolComputerUseToVertex","toolToVertex","functionCallingConfigToVertex","latLngToVertex","retrievalConfigToVertex","toolConfigToVertex","converters.createCachedContentParametersToVertex","converters.cachedContentFromVertex","converters.createCachedContentParametersToMldev","converters.cachedContentFromMldev","converters.getCachedContentParametersToVertex","converters.getCachedContentParametersToMldev","converters.deleteCachedContentParametersToVertex","converters.deleteCachedContentResponseFromVertex","types.DeleteCachedContentResponse","converters.deleteCachedContentParametersToMldev","converters.deleteCachedContentResponseFromMldev","converters.updateCachedContentParametersToVertex","converters.updateCachedContentParametersToMldev","converters.listCachedContentsParametersToVertex","converters.listCachedContentsResponseFromVertex","types.ListCachedContentsResponse","converters.listCachedContentsParametersToMldev","converters.listCachedContentsResponseFromMldev","t.tFileName","converters.fileFromMldev","converters.listFilesParametersToMldev","converters.listFilesResponseFromMldev","types.ListFilesResponse","converters.createFileParametersToMldev","converters.createFileResponseFromMldev","types.CreateFileResponse","converters.getFileParametersToMldev","converters.deleteFileParametersToMldev","converters.deleteFileResponseFromMldev","types.DeleteFileResponse","sessionResumptionConfigToMldev","audioTranscriptionConfigToMldev","automaticActivityDetectionToMldev","realtimeInputConfigToMldev","slidingWindowToMldev","contextWindowCompressionConfigToMldev","proactivityConfigToMldev","liveConnectConfigToMldev","t.tLiveSpeechConfig","t.tBlobs","t.tAudioBlob","t.tImageBlob","prebuiltVoiceConfigToVertex","voiceConfigToVertex","speechConfigToVertex","videoMetadataFromVertex","blobFromVertex","fileDataFromVertex","partFromVertex","contentFromVertex","t.tContentsForEmbed","t.tModelsUrl","t.tBytes","t.tExtractModels","handleWebSocketMessage","types.LiveMusicServerMessage","converters.liveMusicServerMessageFromMldev","mapToHeaders","headersToMap","converters.liveMusicClientSetupToMldev","converters.liveMusicClientMessageToMldev","converters.liveMusicSetWeightedPromptsParametersToMldev","converters.liveMusicClientContentToMldev","converters.liveMusicSetConfigParametersToMldev","types.LiveMusicPlaybackControl","types.LiveServerMessage","converters.liveServerMessageFromVertex","converters.liveServerMessageFromMldev","types.Modality","converters.liveConnectParametersToVertex","converters.liveConnectParametersToMldev","converters.liveSendRealtimeInputParametersToVertex","converters.liveSendRealtimeInputParametersToMldev","types.GenerateContentResponse","converters.generateContentParametersToVertex","converters.generateContentResponseFromVertex","converters.generateContentParametersToMldev","converters.generateContentResponseFromMldev","converters.embedContentParametersToVertex","converters.embedContentResponseFromVertex","types.EmbedContentResponse","converters.embedContentParametersToMldev","converters.embedContentResponseFromMldev","converters.generateImagesParametersToVertex","converters.generateImagesResponseFromVertex","types.GenerateImagesResponse","converters.generateImagesParametersToMldev","converters.generateImagesResponseFromMldev","converters.editImageParametersInternalToVertex","converters.editImageResponseFromVertex","types.EditImageResponse","converters.upscaleImageAPIParametersInternalToVertex","converters.upscaleImageResponseFromVertex","types.UpscaleImageResponse","converters.recontextImageParametersToVertex","converters.recontextImageResponseFromVertex","types.RecontextImageResponse","converters.segmentImageParametersToVertex","converters.segmentImageResponseFromVertex","types.SegmentImageResponse","converters.getModelParametersToVertex","converters.modelFromVertex","converters.getModelParametersToMldev","converters.modelFromMldev","converters.listModelsParametersToVertex","converters.listModelsResponseFromVertex","types.ListModelsResponse","converters.listModelsParametersToMldev","converters.listModelsResponseFromMldev","converters.updateModelParametersToVertex","converters.updateModelParametersToMldev","converters.deleteModelParametersToVertex","converters.deleteModelResponseFromVertex","types.DeleteModelResponse","converters.deleteModelParametersToMldev","converters.deleteModelResponseFromMldev","converters.countTokensParametersToVertex","converters.countTokensResponseFromVertex","types.CountTokensResponse","converters.countTokensParametersToMldev","converters.countTokensResponseFromMldev","converters.computeTokensParametersToVertex","converters.computeTokensResponseFromVertex","types.ComputeTokensResponse","converters.generateVideosParametersToVertex","converters.generateVideosOperationFromVertex","types.GenerateVideosOperation","converters.generateVideosParametersToMldev","converters.generateVideosOperationFromMldev","converters.getOperationParametersToVertex","converters.getOperationParametersToMldev","converters.fetchPredictOperationParametersToVertex","converters.createAuthTokenParametersToMldev","converters.authTokenFromMldev","t.tTuningJobStatus","types.JobState","converters.getTuningJobParametersToVertex","converters.tuningJobFromVertex","converters.getTuningJobParametersToMldev","converters.tuningJobFromMldev","converters.listTuningJobsParametersToVertex","converters.listTuningJobsResponseFromVertex","types.ListTuningJobsResponse","converters.listTuningJobsParametersToMldev","converters.listTuningJobsResponseFromMldev","converters.createTuningJobParametersPrivateToVertex","converters.createTuningJobParametersPrivateToMldev","converters.tuningOperationFromMldev"],"mappings":"AAAA;;;;AAIG;AAIH,IAAI,qBAAqB,GAAuB,SAAS;AACzD,IAAI,qBAAqB,GAAuB,SAAS;AAUzD;;;;;;;;;;;;;;;;;;;AAmBG;AACG,SAAU,kBAAkB,CAAC,aAAgC,EAAA;AACjE,IAAA,qBAAqB,GAAG,aAAa,CAAC,SAAS;AAC/C,IAAA,qBAAqB,GAAG,aAAa,CAAC,SAAS;AACjD;AAEA;;AAEG;SACa,kBAAkB,GAAA;IAChC,OAAO;AACL,QAAA,SAAS,EAAE,qBAAqB;AAChC,QAAA,SAAS,EAAE,qBAAqB;KACjC;AACH;AAEA;;;;;AAKG;AACG,SAAU,UAAU,CACxB,WAAoC,EACpC,QAA6B,EAC7B,oBAAwC,EACxC,oBAAwC,EAAA;;IAExC,IAAI,EAAC,WAAW,KAAX,IAAA,IAAA,WAAW,uBAAX,WAAW,CAAE,OAAO,CAAA,EAAE;AACzB,QAAA,MAAM,eAAe,GAAG,kBAAkB,EAAE;AAC5C,QAAA,IAAI,QAAQ,EAAE;AACZ,YAAA,OAAO,MAAA,eAAe,CAAC,SAAS,MAAA,IAAA,IAAA,EAAA,KAAA,MAAA,GAAA,EAAA,GAAI,oBAAoB;AACzD;AAAM,aAAA;AACL,YAAA,OAAO,MAAA,eAAe,CAAC,SAAS,MAAA,IAAA,IAAA,EAAA,KAAA,MAAA,GAAA,EAAA,GAAI,oBAAoB;AACzD;AACF;IAED,OAAO,WAAW,CAAC,OAAO;AAC5B;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AS,CAAC;QAChD,IAAI,CAAC,UAAU,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;QAC5C,IAAI,CAAC,OAAO,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC;;AAE7C;;;;"} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/web/web.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/web/web.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5a53804ab9f11da34dbec486f447695a96f1e7da --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/dist/web/web.d.ts @@ -0,0 +1,7706 @@ +// @ts-ignore +import type { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { GoogleAuthOptions } from 'google-auth-library'; + +/** Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface ActivityEnd { +} + +/** The different ways of handling user activity. */ +export declare enum ActivityHandling { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ACTIVITY_HANDLING_UNSPECIFIED = "ACTIVITY_HANDLING_UNSPECIFIED", + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + START_OF_ACTIVITY_INTERRUPTS = "START_OF_ACTIVITY_INTERRUPTS", + /** + * The model's response will not be interrupted. + */ + NO_INTERRUPTION = "NO_INTERRUPTION" +} + +/** Marks the start of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface ActivityStart { +} + +/** Optional. Adapter size for tuning. */ +export declare enum AdapterSize { + /** + * Adapter size is unspecified. + */ + ADAPTER_SIZE_UNSPECIFIED = "ADAPTER_SIZE_UNSPECIFIED", + /** + * Adapter size 1. + */ + ADAPTER_SIZE_ONE = "ADAPTER_SIZE_ONE", + /** + * Adapter size 2. + */ + ADAPTER_SIZE_TWO = "ADAPTER_SIZE_TWO", + /** + * Adapter size 4. + */ + ADAPTER_SIZE_FOUR = "ADAPTER_SIZE_FOUR", + /** + * Adapter size 8. + */ + ADAPTER_SIZE_EIGHT = "ADAPTER_SIZE_EIGHT", + /** + * Adapter size 16. + */ + ADAPTER_SIZE_SIXTEEN = "ADAPTER_SIZE_SIXTEEN", + /** + * Adapter size 32. + */ + ADAPTER_SIZE_THIRTY_TWO = "ADAPTER_SIZE_THIRTY_TWO" +} + +/** The generic reusable api auth config. Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto) instead. */ +export declare interface ApiAuth { + /** The API secret. */ + apiKeyConfig?: ApiAuthApiKeyConfig; +} + +/** The API secret. */ +export declare interface ApiAuthApiKeyConfig { + /** Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version} */ + apiKeySecretVersion?: string; + /** The API key string. Either this or `api_key_secret_version` must be set. */ + apiKeyString?: string; +} + +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +declare class ApiClient { + readonly clientOptions: ApiClientInitOptions; + constructor(opts: ApiClientInitOptions); + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + private baseUrlFromProjectLocation; + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + private normalizeAuthParameters; + isVertexAI(): boolean; + getProject(): string | undefined; + getLocation(): string | undefined; + getApiVersion(): string; + getBaseUrl(): string; + getRequestUrl(): string; + getHeaders(): Record; + private getRequestUrlInternal; + getBaseResourcePath(): string; + getApiKey(): string | undefined; + getWebsocketBaseUrl(): string; + setBaseUrl(url: string): void; + private constructUrl; + private shouldPrependVertexProjectPath; + request(request: HttpRequest): Promise; + private patchHttpOptions; + requestStream(request: HttpRequest): Promise>; + private includeExtraHttpOptionsToRequestInit; + private unaryApiCall; + private streamApiCall; + processStreamResponse(response: Response): AsyncGenerator; + private apiCall; + getDefaultHeaders(): Record; + private getHeadersInternal; + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + uploadFile(file: string | Blob, config?: UploadFileConfig): Promise; + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + downloadFile(params: DownloadFileParameters): Promise; + private fetchUploadUrl; +} + +/** + * Options for initializing the ApiClient. The ApiClient uses the parameters + * for authentication purposes as well as to infer if SDK should send the + * request to Vertex AI or Gemini API. + */ +declare interface ApiClientInitOptions { + /** + * The object used for adding authentication headers to API requests. + */ + auth: Auth; + /** + * The uploader to use for uploading files. This field is required for + * creating a client, will be set through the Node_client or Web_client. + */ + uploader: Uploader; + /** + * Optional. The downloader to use for downloading files. This field is + * required for creating a client, will be set through the Node_client or + * Web_client. + */ + downloader: Downloader; + /** + * Optional. The Google Cloud project ID for Vertex AI users. + * It is not the numeric project name. + * If not provided, SDK will try to resolve it from runtime environment. + */ + project?: string; + /** + * Optional. The Google Cloud project location for Vertex AI users. + * If not provided, SDK will try to resolve it from runtime environment. + */ + location?: string; + /** + * The API Key. This is required for Gemini API users. + */ + apiKey?: string; + /** + * Optional. Set to true if you intend to call Vertex AI endpoints. + * If unset, default SDK behavior is to call Gemini API. + */ + vertexai?: boolean; + /** + * Optional. The API version for the endpoint. + * If unset, SDK will choose a default api version. + */ + apiVersion?: string; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; + /** + * Optional. An extra string to append at the end of the User-Agent header. + * + * This can be used to e.g specify the runtime and its version. + */ + userAgentExtra?: string; +} + +/** + * API errors raised by the GenAI API. + */ +export declare class ApiError extends Error { + /** HTTP status code */ + status: number; + constructor(options: ApiErrorInfo); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Details for errors from calling the API. + */ +export declare interface ApiErrorInfo { + /** The error message. */ + message: string; + /** The HTTP status code. */ + status: number; +} + +/** Config for authentication with API key. */ +export declare interface ApiKeyConfig { + /** The API key to be used in the request directly. */ + apiKeyString?: string; +} + +/** The API spec that the external API implements. */ +export declare enum ApiSpec { + /** + * Unspecified API spec. This value should not be used. + */ + API_SPEC_UNSPECIFIED = "API_SPEC_UNSPECIFIED", + /** + * Simple search API spec. + */ + SIMPLE_SEARCH = "SIMPLE_SEARCH", + /** + * Elastic search API spec. + */ + ELASTIC_SEARCH = "ELASTIC_SEARCH" +} + +/** Representation of an audio chunk. */ +export declare interface AudioChunk { + /** Raw bytes of audio data. + * @remarks Encoded as base64 string. */ + data?: string; + /** MIME type of the audio chunk. */ + mimeType?: string; + /** Prompts and config used for generating this audio chunk. */ + sourceMetadata?: LiveMusicSourceMetadata; +} + +/** The audio transcription configuration in Setup. */ +export declare interface AudioTranscriptionConfig { +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * The Auth interface is used to authenticate with the API service. + */ +declare interface Auth { + /** + * Sets the headers needed to authenticate with the API service. + * + * @param headers - The Headers object that will be updated with the authentication headers. + */ + addAuthHeaders(headers: Headers): Promise; +} + +/** Auth configuration to run the extension. */ +export declare interface AuthConfig { + /** Config for API key auth. */ + apiKeyConfig?: ApiKeyConfig; + /** Type of auth scheme. */ + authType?: AuthType; + /** Config for Google Service Account auth. */ + googleServiceAccountConfig?: AuthConfigGoogleServiceAccountConfig; + /** Config for HTTP Basic auth. */ + httpBasicAuthConfig?: AuthConfigHttpBasicAuthConfig; + /** Config for user oauth. */ + oauthConfig?: AuthConfigOauthConfig; + /** Config for user OIDC auth. */ + oidcConfig?: AuthConfigOidcConfig; +} + +/** Config for Google Service Account Authentication. */ +export declare interface AuthConfigGoogleServiceAccountConfig { + /** Optional. The service account that the extension execution service runs as. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified service account. - If not specified, the Vertex AI Extension Service Agent will be used to execute the Extension. */ + serviceAccount?: string; +} + +/** Config for HTTP Basic Authentication. */ +export declare interface AuthConfigHttpBasicAuthConfig { + /** Required. The name of the SecretManager secret version resource storing the base64 encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource. */ + credentialSecret?: string; +} + +/** Config for user oauth. */ +export declare interface AuthConfigOauthConfig { + /** Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */ + accessToken?: string; + /** The service account used to generate access tokens for executing the Extension. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the provided service account. */ + serviceAccount?: string; +} + +/** Config for user OIDC auth. */ +export declare interface AuthConfigOidcConfig { + /** OpenID Connect formatted ID token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */ + idToken?: string; + /** The service account used to generate an OpenID Connect (OIDC)-compatible JWT token signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc). - The audience for the token will be set to the URL in the server url defined in the OpenApi spec. - If the service account is provided, the service account should grant `iam.serviceAccounts.getOpenIdToken` permission to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents). */ + serviceAccount?: string; +} + +/** Config for auth_tokens.create parameters. */ +export declare interface AuthToken { + /** The name of the auth token. */ + name?: string; +} + +/** Type of auth scheme. */ +export declare enum AuthType { + AUTH_TYPE_UNSPECIFIED = "AUTH_TYPE_UNSPECIFIED", + /** + * No Auth. + */ + NO_AUTH = "NO_AUTH", + /** + * API Key Auth. + */ + API_KEY_AUTH = "API_KEY_AUTH", + /** + * HTTP Basic Auth. + */ + HTTP_BASIC_AUTH = "HTTP_BASIC_AUTH", + /** + * Google Service Account Auth. + */ + GOOGLE_SERVICE_ACCOUNT_AUTH = "GOOGLE_SERVICE_ACCOUNT_AUTH", + /** + * OAuth auth. + */ + OAUTH = "OAUTH", + /** + * OpenID Connect (OIDC) Auth. + */ + OIDC_AUTH = "OIDC_AUTH" +} + +/** Configures automatic detection of activity. */ +export declare interface AutomaticActivityDetection { + /** If enabled, detected voice and text input count as activity. If disabled, the client must send activity signals. */ + disabled?: boolean; + /** Determines how likely speech is to be detected. */ + startOfSpeechSensitivity?: StartSensitivity; + /** Determines how likely detected speech is ended. */ + endOfSpeechSensitivity?: EndSensitivity; + /** The required duration of detected speech before start-of-speech is committed. The lower this value the more sensitive the start-of-speech detection is and the shorter speech can be recognized. However, this also increases the probability of false positives. */ + prefixPaddingMs?: number; + /** The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency. */ + silenceDurationMs?: number; +} + +/** The configuration for automatic function calling. */ +export declare interface AutomaticFunctionCallingConfig { + /** Whether to disable automatic function calling. + If not set or set to False, will enable automatic function calling. + If set to True, will disable automatic function calling. + */ + disable?: boolean; + /** If automatic function calling is enabled, + maximum number of remote calls for automatic function calling. + This number should be a positive integer. + If not set, SDK will set maximum number of remote calls to 10. + */ + maximumRemoteCalls?: number; + /** If automatic function calling is enabled, + whether to ignore call history to the response. + If not set, SDK will set ignore_call_history to false, + and will append the call history to + GenerateContentResponse.automatic_function_calling_history. + */ + ignoreCallHistory?: boolean; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +declare class BaseModule { +} + +/** + * Parameters for setting the base URLs for the Gemini API and Vertex AI API. + */ +export declare interface BaseUrlParameters { + geminiUrl?: string; + vertexUrl?: string; +} + +export declare class Batches extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + create: (params: types.CreateBatchJobParameters) => Promise; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + list: (params?: types.ListBatchJobsParameters) => Promise>; + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + private createInternal; + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + get(params: types.GetBatchJobParameters): Promise; + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + cancel(params: types.CancelBatchJobParameters): Promise; + private listInternal; + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + delete(params: types.DeleteBatchJobParameters): Promise; +} + +/** Config for batches.create return value. */ +export declare interface BatchJob { + /** The resource name of the BatchJob. Output only.". + */ + name?: string; + /** The display name of the BatchJob. + */ + displayName?: string; + /** The state of the BatchJob. + */ + state?: JobState; + /** Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED. */ + error?: JobError; + /** The time when the BatchJob was created. + */ + createTime?: string; + /** Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state. */ + startTime?: string; + /** The time when the BatchJob was completed. + */ + endTime?: string; + /** The time when the BatchJob was last updated. + */ + updateTime?: string; + /** The name of the model that produces the predictions via the BatchJob. + */ + model?: string; + /** Configuration for the input data. + */ + src?: BatchJobSource; + /** Configuration for the output data. + */ + dest?: BatchJobDestination; +} + +/** Config for `des` parameter. */ +export declare interface BatchJobDestination { + /** Storage format of the output files. Must be one of: + 'jsonl', 'bigquery'. + */ + format?: string; + /** The Google Cloud Storage URI to the output file. + */ + gcsUri?: string; + /** The BigQuery URI to the output table. + */ + bigqueryUri?: string; + /** The Gemini Developer API's file resource name of the output data + (e.g. "files/12345"). The file will be a JSONL file with a single response + per line. The responses will be GenerateContentResponse messages formatted + as JSON. The responses will be written in the same order as the input + requests. + */ + fileName?: string; + /** The responses to the requests in the batch. Returned when the batch was + built using inlined requests. The responses will be in the same order as + the input requests. + */ + inlinedResponses?: InlinedResponse[]; +} + +export declare type BatchJobDestinationUnion = BatchJobDestination | string; + +/** Config for `src` parameter. */ +export declare interface BatchJobSource { + /** Storage format of the input files. Must be one of: + 'jsonl', 'bigquery'. + */ + format?: string; + /** The Google Cloud Storage URIs to input files. + */ + gcsUri?: string[]; + /** The BigQuery URI to input table. + */ + bigqueryUri?: string; + /** The Gemini Developer API's file resource name of the input data + (e.g. "files/12345"). + */ + fileName?: string; + /** The Gemini Developer API's inlined input data to run batch job. + */ + inlinedRequests?: InlinedRequest[]; +} + +export declare type BatchJobSourceUnion = BatchJobSource | InlinedRequest[] | string; + +/** Defines the function behavior. Defaults to `BLOCKING`. */ +export declare enum Behavior { + /** + * This value is unused. + */ + UNSPECIFIED = "UNSPECIFIED", + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + BLOCKING = "BLOCKING", + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + NON_BLOCKING = "NON_BLOCKING" +} + +/** Content blob. */ +declare interface Blob_2 { + /** Optional. Display name of the blob. Used to provide a label or filename to distinguish blobs. This field is not currently used in the Gemini GenerateContent calls. */ + displayName?: string; + /** Required. Raw bytes. + * @remarks Encoded as base64 string. */ + data?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} +export { Blob_2 as Blob } + +export declare type BlobImageUnion = Blob_2; + +/** Output only. Blocked reason. */ +export declare enum BlockedReason { + /** + * Unspecified blocked reason. + */ + BLOCKED_REASON_UNSPECIFIED = "BLOCKED_REASON_UNSPECIFIED", + /** + * Candidates blocked due to safety. + */ + SAFETY = "SAFETY", + /** + * Candidates blocked due to other reason. + */ + OTHER = "OTHER", + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BLOCKLIST = "BLOCKLIST", + /** + * Candidates blocked due to prohibited content. + */ + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + /** + * Candidates blocked due to unsafe image generation content. + */ + IMAGE_SAFETY = "IMAGE_SAFETY" +} + +/** A resource used in LLM queries for users to explicitly specify what to cache. */ +export declare interface CachedContent { + /** The server-generated resource name of the cached content. */ + name?: string; + /** The user-generated meaningful display name of the cached content. */ + displayName?: string; + /** The name of the publisher model to use for cached content. */ + model?: string; + /** Creation time of the cache entry. */ + createTime?: string; + /** When the cache entry was last updated in UTC time. */ + updateTime?: string; + /** Expiration time of the cached content. */ + expireTime?: string; + /** Metadata on the usage of the cached content. */ + usageMetadata?: CachedContentUsageMetadata; +} + +/** Metadata on the usage of the cached content. */ +export declare interface CachedContentUsageMetadata { + /** Duration of audio in seconds. */ + audioDurationSeconds?: number; + /** Number of images. */ + imageCount?: number; + /** Number of text characters. */ + textCount?: number; + /** Total number of tokens that the cached content consumes. */ + totalTokenCount?: number; + /** Duration of video in seconds. */ + videoDurationSeconds?: number; +} + +export declare class Caches extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + list: (params?: types.ListCachedContentsParameters) => Promise>; + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + create(params: types.CreateCachedContentParameters): Promise; + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + get(params: types.GetCachedContentParameters): Promise; + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + delete(params: types.DeleteCachedContentParameters): Promise; + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + update(params: types.UpdateCachedContentParameters): Promise; + private listInternal; +} + +/** + * CallableTool is an invokable tool that can be executed with external + * application (e.g., via Model Context Protocol) or local functions with + * function calling. + */ +export declare interface CallableTool { + /** + * Returns tool that can be called by Gemini. + */ + tool(): Promise; + /** + * Executes the callable tool with the given function call arguments and + * returns the response parts from the tool execution. + */ + callTool(functionCalls: FunctionCall[]): Promise; +} + +/** + * CallableToolConfig is the configuration for a callable tool. + */ +export declare interface CallableToolConfig { + /** + * Specifies the model's behavior after invoking this tool. + */ + behavior?: Behavior; + /** + * Timeout for remote calls in milliseconds. Note this timeout applies only to + * tool remote calls, and not making HTTP requests to the API. */ + timeout?: number; +} + +/** Optional parameters. */ +export declare interface CancelBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.cancel parameters. */ +export declare interface CancelBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: CancelBatchJobConfig; +} + +/** A response candidate generated from the model. */ +export declare interface Candidate { + /** Contains the multi-part content of the response. + */ + content?: Content; + /** Source attribution of the generated content. + */ + citationMetadata?: CitationMetadata; + /** Describes the reason the model stopped generating tokens. + */ + finishMessage?: string; + /** Number of tokens for this candidate. + */ + tokenCount?: number; + /** The reason why the model stopped generating tokens. + If empty, the model has not stopped generating the tokens. + */ + finishReason?: FinishReason; + /** Metadata related to url context retrieval tool. */ + urlContextMetadata?: UrlContextMetadata; + /** Output only. Average log probability score of the candidate. */ + avgLogprobs?: number; + /** Output only. Metadata specifies sources used to ground generated content. */ + groundingMetadata?: GroundingMetadata; + /** Output only. Index of the candidate. */ + index?: number; + /** Output only. Log-likelihood scores for the response tokens and top tokens */ + logprobsResult?: LogprobsResult; + /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */ + safetyRatings?: SafetyRating[]; +} + +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +export declare class Chat { + private readonly apiClient; + private readonly modelsModule; + private readonly model; + private readonly config; + private history; + private sendPromise; + constructor(apiClient: ApiClient, modelsModule: Models, model: string, config?: types.GenerateContentConfig, history?: types.Content[]); + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + sendMessage(params: types.SendMessageParameters): Promise; + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + sendMessageStream(params: types.SendMessageParameters): Promise>; + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated?: boolean): types.Content[]; + private processStreamResponse; + private recordHistory; +} + +/** + * A utility class to create a chat session. + */ +export declare class Chats { + private readonly modelsModule; + private readonly apiClient; + constructor(modelsModule: Models, apiClient: ApiClient); + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params: types.CreateChatParameters): Chat; +} + +/** Describes the machine learning model version checkpoint. */ +export declare interface Checkpoint { + /** The ID of the checkpoint. + */ + checkpointId?: string; + /** The epoch of the checkpoint. + */ + epoch?: string; + /** The step of the checkpoint. + */ + step?: string; +} + +/** Source attributions for content. */ +export declare interface Citation { + /** Output only. End index into the content. */ + endIndex?: number; + /** Output only. License of the attribution. */ + license?: string; + /** Output only. Publication date of the attribution. */ + publicationDate?: GoogleTypeDate; + /** Output only. Start index into the content. */ + startIndex?: number; + /** Output only. Title of the attribution. */ + title?: string; + /** Output only. Url reference of the attribution. */ + uri?: string; +} + +/** Citation information when the model quotes another source. */ +export declare interface CitationMetadata { + /** Contains citation information when the model directly quotes, at + length, from another source. Can include traditional websites and code + repositories. + */ + citations?: Citation[]; +} + +/** Result of executing the [ExecutableCode]. Only generated when using the [CodeExecution] tool, and always follows a `part` containing the [ExecutableCode]. */ +export declare interface CodeExecutionResult { + /** Required. Outcome of the code execution. */ + outcome?: Outcome; + /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */ + output?: string; +} + +/** Optional parameters for computing tokens. */ +export declare interface ComputeTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for computing tokens. */ +export declare interface ComputeTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Optional parameters for the request. + */ + config?: ComputeTokensConfig; +} + +/** Response for computing tokens. */ +export declare class ComputeTokensResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */ + tokensInfo?: TokensInfo[]; +} + +/** Contains the multi-part content of a message. */ +export declare interface Content { + /** List of parts that constitute a single message. Each part may have + a different IANA MIME type. */ + parts?: Part[]; + /** Optional. The producer of the content. Must be either 'user' or + 'model'. Useful to set for multi-turn conversations, otherwise can be + empty. If role is not specified, SDK will determine the role. */ + role?: string; +} + +/** The embedding generated from an input content. */ +export declare interface ContentEmbedding { + /** A list of floats representing an embedding. + */ + values?: number[]; + /** Vertex API only. Statistics of the input text associated with this + embedding. + */ + statistics?: ContentEmbeddingStatistics; +} + +/** Statistics of the input text associated with the result of content embedding. */ +export declare interface ContentEmbeddingStatistics { + /** Vertex API only. If the input text was truncated due to having + a length longer than the allowed maximum input. + */ + truncated?: boolean; + /** Vertex API only. Number of tokens of the input text. + */ + tokenCount?: number; +} + +export declare type ContentListUnion = Content | Content[] | PartUnion | PartUnion[]; + +export declare type ContentUnion = Content | PartUnion[] | PartUnion; + +/** Enables context window compression -- mechanism managing model context window so it does not exceed given length. */ +export declare interface ContextWindowCompressionConfig { + /** Number of tokens (before running turn) that triggers context window compression mechanism. */ + triggerTokens?: string; + /** Sliding window compression mechanism. */ + slidingWindow?: SlidingWindow; +} + +/** Configuration for a Control reference image. */ +export declare interface ControlReferenceConfig { + /** The type of control reference image to use. */ + controlType?: ControlReferenceType; + /** Defaults to False. When set to True, the control image will be + computed by the model based on the control type. When set to False, + the control image must be provided by the user. */ + enableControlImageComputation?: boolean; +} + +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +export declare class ControlReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the control reference image. */ + config?: ControlReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the control type of a control reference image. */ +export declare enum ControlReferenceType { + CONTROL_TYPE_DEFAULT = "CONTROL_TYPE_DEFAULT", + CONTROL_TYPE_CANNY = "CONTROL_TYPE_CANNY", + CONTROL_TYPE_SCRIBBLE = "CONTROL_TYPE_SCRIBBLE", + CONTROL_TYPE_FACE_MESH = "CONTROL_TYPE_FACE_MESH" +} + +/** Config for the count_tokens method. */ +export declare interface CountTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Instructions for the model to steer it toward better performance. + */ + systemInstruction?: ContentUnion; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: Tool[]; + /** Configuration that the model uses to generate the response. Not + supported by the Gemini Developer API. + */ + generationConfig?: GenerationConfig; +} + +/** Parameters for counting tokens. */ +export declare interface CountTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Configuration for counting tokens. */ + config?: CountTokensConfig; +} + +/** Response for counting tokens. */ +export declare class CountTokensResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Total number of tokens. */ + totalTokens?: number; + /** Number of tokens in the cached part of the prompt (the cached content). */ + cachedContentTokenCount?: number; +} + +/** Optional parameters. */ +export declare interface CreateAuthTokenConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** An optional time after which, when using the resulting token, + messages in Live API sessions will be rejected. (Gemini may + preemptively close the session after this time.) + + If not set then this defaults to 30 minutes in the future. If set, this + value must be less than 20 hours in the future. */ + expireTime?: string; + /** The time after which new Live API sessions using the token + resulting from this request will be rejected. + + If not set this defaults to 60 seconds in the future. If set, this value + must be less than 20 hours in the future. */ + newSessionExpireTime?: string; + /** The number of times the token can be used. If this value is zero + then no limit is applied. Default is 1. Resuming a Live API session does + not count as a use. */ + uses?: number; + /** Configuration specific to Live API connections created using this token. */ + liveConnectConstraints?: LiveConnectConstraints; + /** Additional fields to lock in the effective LiveConnectParameters. */ + lockAdditionalFields?: string[]; +} + +/** Config for auth_tokens.create parameters. */ +export declare interface CreateAuthTokenParameters { + /** Optional parameters for the request. */ + config?: CreateAuthTokenConfig; +} + +/** Config for optional parameters. */ +export declare interface CreateBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The user-defined name of this BatchJob. + */ + displayName?: string; + /** GCS or BigQuery URI prefix for the output predictions. Example: + "gs://path/to/output/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + dest?: BatchJobDestinationUnion; +} + +/** Config for batches.create parameters. */ +export declare interface CreateBatchJobParameters { + /** The name of the model to produces the predictions via the BatchJob. + */ + model?: string; + /** GCS URI(-s) or BigQuery URI to your input data to run batch job. + Example: "gs://path/to/input/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + src: BatchJobSourceUnion; + /** Optional parameters for creating a BatchJob. + */ + config?: CreateBatchJobConfig; +} + +/** Optional configuration for cached content creation. */ +export declare interface CreateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; + /** The user-generated meaningful display name of the cached content. + */ + displayName?: string; + /** The content to cache. + */ + contents?: ContentListUnion; + /** Developer set system instruction. + */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + */ + tools?: Tool[]; + /** Configuration for the tools to use. This config is shared for all tools. + */ + toolConfig?: ToolConfig; + /** The Cloud KMS resource identifier of the customer managed + encryption key used to protect a resource. + The key needs to be in the same region as where the compute resource is + created. See + https://cloud.google.com/vertex-ai/docs/general/cmek for more + details. If this is set, then all created CachedContent objects + will be encrypted with the provided encryption key. + Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key} + */ + kmsKeyName?: string; +} + +/** Parameters for caches.create method. */ +export declare interface CreateCachedContentParameters { + /** ID of the model to use. Example: gemini-2.0-flash */ + model: string; + /** Configuration that contains optional parameters. + */ + config?: CreateCachedContentConfig; +} + +/** Parameters for initializing a new chat session. + + These parameters are used when creating a chat session with the + `chats.create()` method. + */ +export declare interface CreateChatParameters { + /** The name of the model to use for the chat session. + + For example: 'gemini-2.0-flash', 'gemini-2.0-flash-lite', etc. See Gemini API + docs to find the available models. + */ + model: string; + /** Config for the entire chat session. + + This config applies to all requests within the session + unless overridden by a per-request `config` in `SendMessageParameters`. + */ + config?: GenerateContentConfig; + /** The initial conversation history for the chat session. + + This allows you to start the chat with a pre-existing history. The history + must be a list of `Content` alternating between 'user' and 'model' roles. + It should start with a 'user' message. + */ + history?: Content[]; +} + +/** Used to override the default configuration. */ +export declare interface CreateFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the private _create method. */ +export declare interface CreateFileParameters { + /** The file to be uploaded. + mime_type: (Required) The MIME type of the file. Must be provided. + name: (Optional) The name of the file in the destination (e.g. + 'files/sample-image'). + display_name: (Optional) The display name of the file. + */ + file: File_2; + /** Used to override the default configuration. */ + config?: CreateFileConfig; +} + +/** Response for the create file method. */ +export declare class CreateFileResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; +} + +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +export declare function createModelContent(partOrString: PartListUnion | string): Content; + +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +export declare function createPartFromBase64(data: string, mimeType: string): Part; + +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +export declare function createPartFromCodeExecutionResult(outcome: Outcome, output: string): Part; + +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +export declare function createPartFromExecutableCode(code: string, language: Language): Part; + +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +export declare function createPartFromFunctionCall(name: string, args: Record): Part; + +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +export declare function createPartFromFunctionResponse(id: string, name: string, response: Record): Part; + +/** + * Creates a `Part` object from a `text` string. + */ +export declare function createPartFromText(text: string): Part; + +/** + * Creates a `Part` object from a `URI` string. + */ +export declare function createPartFromUri(uri: string, mimeType: string): Part; + +/** Supervised fine-tuning job creation request - optional fields. */ +export declare interface CreateTuningJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + validationDataset?: TuningValidationDataset; + /** The display name of the tuned Model. The name can be up to 128 characters long and can consist of any UTF-8 characters. */ + tunedModelDisplayName?: string; + /** The description of the TuningJob */ + description?: string; + /** Number of complete passes the model makes over the entire training dataset during training. */ + epochCount?: number; + /** Multiplier for adjusting the default learning rate. */ + learningRateMultiplier?: number; + /** If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. */ + exportLastCheckpointOnly?: boolean; + /** The optional checkpoint id of the pre-tuned model to use for tuning, if applicable. */ + preTunedModelCheckpointId?: string; + /** Adapter size for tuning. */ + adapterSize?: AdapterSize; + /** The batch size hyperparameter for tuning. If not set, a default of 4 or 16 will be used based on the number of training examples. */ + batchSize?: number; + /** The learning rate hyperparameter for tuning. If not set, a default of 0.001 or 0.0002 will be calculated based on the number of training examples. */ + learningRate?: number; +} + +/** Supervised fine-tuning job creation parameters - optional fields. */ +export declare interface CreateTuningJobParameters { + /** The base model that is being tuned, e.g., "gemini-2.5-flash". */ + baseModel: string; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDataset: TuningDataset; + /** Configuration for the tuning job. */ + config?: CreateTuningJobConfig; +} + +/** Supervised fine-tuning job creation parameters - optional fields. */ +export declare interface CreateTuningJobParametersPrivate { + /** The base model that is being tuned, e.g., "gemini-2.5-flash". */ + baseModel?: string; + /** The PreTunedModel that is being tuned. */ + preTunedModel?: PreTunedModel; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDataset: TuningDataset; + /** Configuration for the tuning job. */ + config?: CreateTuningJobConfig; +} + +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +export declare function createUserContent(partOrString: PartListUnion | string): Content; + +/** Distribution computed over a tuning dataset. */ +export declare interface DatasetDistribution { + /** Output only. Defines the histogram bucket. */ + buckets?: DatasetDistributionDistributionBucket[]; + /** Output only. The maximum of the population values. */ + max?: number; + /** Output only. The arithmetic mean of the values in the population. */ + mean?: number; + /** Output only. The median of the values in the population. */ + median?: number; + /** Output only. The minimum of the population values. */ + min?: number; + /** Output only. The 5th percentile of the values in the population. */ + p5?: number; + /** Output only. The 95th percentile of the values in the population. */ + p95?: number; + /** Output only. Sum of a given population of values. */ + sum?: number; +} + +/** Dataset bucket used to create a histogram for the distribution given a population of values. */ +export declare interface DatasetDistributionDistributionBucket { + /** Output only. Number of values in the bucket. */ + count?: string; + /** Output only. Left bound of the bucket. */ + left?: number; + /** Output only. Right bound of the bucket. */ + right?: number; +} + +/** Statistics computed over a tuning dataset. */ +export declare interface DatasetStats { + /** Output only. Number of billable characters in the tuning dataset. */ + totalBillableCharacterCount?: string; + /** Output only. Number of tuning characters in the tuning dataset. */ + totalTuningCharacterCount?: string; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user messages in the training dataset uri. */ + userDatasetExamples?: Content[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the messages per example. */ + userMessagePerExampleDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: DatasetDistribution; +} + +/** Optional parameters for models.get method. */ +export declare interface DeleteBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.delete parameters. */ +export declare interface DeleteBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: DeleteBatchJobConfig; +} + +/** Optional parameters for caches.delete method. */ +export declare interface DeleteCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for caches.delete method. */ +export declare interface DeleteCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: DeleteCachedContentConfig; +} + +/** Empty response for caches.delete method. */ +export declare class DeleteCachedContentResponse { +} + +/** Used to override the default configuration. */ +export declare interface DeleteFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the get method. */ +export declare interface DeleteFileParameters { + /** The name identifier for the file to be deleted. */ + name: string; + /** Used to override the default configuration. */ + config?: DeleteFileConfig; +} + +/** Response for the delete file method. */ +export declare class DeleteFileResponse { +} + +/** Configuration for deleting a tuned model. */ +export declare interface DeleteModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for deleting a tuned model. */ +export declare interface DeleteModelParameters { + model: string; + /** Optional parameters for the request. */ + config?: DeleteModelConfig; +} + +export declare class DeleteModelResponse { +} + +/** The return value of delete operation. */ +export declare interface DeleteResourceJob { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + name?: string; + done?: boolean; + error?: JobError; +} + +/** Statistics computed for datasets used for distillation. */ +export declare interface DistillationDataStats { + /** Output only. Statistics computed for the training dataset. */ + trainingDatasetStats?: DatasetStats; +} + +export declare type DownloadableFileUnion = string | File_2 | GeneratedVideo | Video; + +declare interface Downloader { + /** + * Downloads a file to the given location. + * + * @param params The parameters for downloading the file. + * @param apiClient The ApiClient to use for uploading. + * @return A Promises that resolves when the download is complete. + */ + download(params: DownloadFileParameters, apiClient: ApiClient): Promise; +} + +/** Used to override the default configuration. */ +export declare interface DownloadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters used to download a file. */ +export declare interface DownloadFileParameters { + /** The file to download. It can be a file name, a file object or a generated video. */ + file: DownloadableFileUnion; + /** Location where the file should be downloaded to. */ + downloadPath: string; + /** Configuration to for the download operation. */ + config?: DownloadFileConfig; +} + +/** Describes the options to customize dynamic retrieval. */ +export declare interface DynamicRetrievalConfig { + /** The mode of the predictor to be used in dynamic retrieval. */ + mode?: DynamicRetrievalConfigMode; + /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */ + dynamicThreshold?: number; +} + +/** Config for the dynamic retrieval config mode. */ +export declare enum DynamicRetrievalConfigMode { + /** + * Always trigger retrieval. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Run retrieval only when system decides it is necessary. + */ + MODE_DYNAMIC = "MODE_DYNAMIC" +} + +/** Configuration for editing an image. */ +export declare interface EditImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage URI used to store the generated images. + */ + outputGcsUri?: string; + /** Description of what to discourage in the generated images. + */ + negativePrompt?: string; + /** Number of images to generate. + */ + numberOfImages?: number; + /** Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9". + */ + aspectRatio?: string; + /** Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality. + */ + guidanceScale?: number; + /** Random seed for image generation. This is not available when + ``add_watermark`` is set to true. + */ + seed?: number; + /** Filter level for safety filtering. + */ + safetyFilterLevel?: SafetyFilterLevel; + /** Allows generation of people by the model. + */ + personGeneration?: PersonGeneration; + /** Whether to report the safety scores of each generated image and + the positive prompt in the response. + */ + includeSafetyAttributes?: boolean; + /** Whether to include the Responsible AI filter reason if the image + is filtered out of the response. + */ + includeRaiReason?: boolean; + /** Language of the text in the prompt. + */ + language?: ImagePromptLanguage; + /** MIME type of the generated image. + */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). + */ + outputCompressionQuality?: number; + /** Whether to add a watermark to the generated images. + */ + addWatermark?: boolean; + /** Describes the editing mode for the request. */ + editMode?: EditMode; + /** The number of sampling steps. A higher value has better image + quality, while a lower value has better latency. */ + baseSteps?: number; +} + +/** Parameters for the request to edit an image. */ +export declare interface EditImageParameters { + /** The model to use. */ + model: string; + /** A text description of the edit to apply to the image. */ + prompt: string; + /** The reference images for Imagen 3 editing. */ + referenceImages: ReferenceImage[]; + /** Configuration for editing. */ + config?: EditImageConfig; +} + +/** Response for the request to edit an image. */ +export declare class EditImageResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** Enum representing the Imagen 3 Edit mode. */ +export declare enum EditMode { + EDIT_MODE_DEFAULT = "EDIT_MODE_DEFAULT", + EDIT_MODE_INPAINT_REMOVAL = "EDIT_MODE_INPAINT_REMOVAL", + EDIT_MODE_INPAINT_INSERTION = "EDIT_MODE_INPAINT_INSERTION", + EDIT_MODE_OUTPAINT = "EDIT_MODE_OUTPAINT", + EDIT_MODE_CONTROLLED_EDITING = "EDIT_MODE_CONTROLLED_EDITING", + EDIT_MODE_STYLE = "EDIT_MODE_STYLE", + EDIT_MODE_BGSWAP = "EDIT_MODE_BGSWAP", + EDIT_MODE_PRODUCT_IMAGE = "EDIT_MODE_PRODUCT_IMAGE" +} + +/** Optional parameters for the embed_content method. */ +export declare interface EmbedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Type of task for which the embedding will be used. + */ + taskType?: string; + /** Title for the text. Only applicable when TaskType is + `RETRIEVAL_DOCUMENT`. + */ + title?: string; + /** Reduced dimension for the output embedding. If set, + excessive values in the output embedding are truncated from the end. + Supported by newer models since 2024 only. You cannot set this value if + using the earlier model (`models/embedding-001`). + */ + outputDimensionality?: number; + /** Vertex API only. The MIME type of the input. + */ + mimeType?: string; + /** Vertex API only. Whether to silently truncate inputs longer than + the max sequence length. If this option is set to false, oversized inputs + will lead to an INVALID_ARGUMENT error, similar to other text APIs. + */ + autoTruncate?: boolean; +} + +/** Request-level metadata for the Vertex Embed Content API. */ +export declare interface EmbedContentMetadata { + /** Vertex API only. The total number of billable characters included + in the request. + */ + billableCharacterCount?: number; +} + +/** Parameters for the embed_content method. */ +export declare interface EmbedContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The content to embed. Only the `parts.text` fields will be counted. + */ + contents: ContentListUnion; + /** Configuration that contains optional parameters. + */ + config?: EmbedContentConfig; +} + +/** Response for the embed_content method. */ +export declare class EmbedContentResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** The embeddings for each request, in the same order as provided in + the batch request. + */ + embeddings?: ContentEmbedding[]; + /** Vertex API only. Metadata about the request. + */ + metadata?: EmbedContentMetadata; +} + +/** Represents a customer-managed encryption key spec that can be applied to a top-level resource. */ +export declare interface EncryptionSpec { + /** Required. The Cloud KMS resource identifier of the customer managed encryption key used to protect a resource. Has the form: `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`. The key needs to be in the same region as where the compute resource is created. */ + kmsKeyName?: string; +} + +/** An endpoint where you deploy models. */ +export declare interface Endpoint { + /** Resource name of the endpoint. */ + name?: string; + /** ID of the model that's deployed to the endpoint. */ + deployedModelId?: string; +} + +/** End of speech sensitivity. */ +export declare enum EndSensitivity { + /** + * The default is END_SENSITIVITY_LOW. + */ + END_SENSITIVITY_UNSPECIFIED = "END_SENSITIVITY_UNSPECIFIED", + /** + * Automatic detection ends speech more often. + */ + END_SENSITIVITY_HIGH = "END_SENSITIVITY_HIGH", + /** + * Automatic detection ends speech less often. + */ + END_SENSITIVITY_LOW = "END_SENSITIVITY_LOW" +} + +/** Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. */ +export declare interface EnterpriseWebSearch { + /** Optional. List of domains to be excluded from the search results. The default limit is 2000 domains. */ + excludeDomains?: string[]; +} + +/** An entity representing the segmented area. */ +export declare interface EntityLabel { + /** The label of the segmented entity. */ + label?: string; + /** The confidence score of the detected label. */ + score?: number; +} + +/** The environment being operated. */ +export declare enum Environment { + /** + * Defaults to browser. + */ + ENVIRONMENT_UNSPECIFIED = "ENVIRONMENT_UNSPECIFIED", + /** + * Operates in a web browser. + */ + ENVIRONMENT_BROWSER = "ENVIRONMENT_BROWSER" +} + +/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [CodeExecution] tool, in which the code will be automatically executed, and a corresponding [CodeExecutionResult] will also be generated. */ +export declare interface ExecutableCode { + /** Required. The code to be executed. */ + code?: string; + /** Required. Programming language of the `code`. */ + language?: Language; +} + +/** Retrieve from data source powered by external API for grounding. The external API is not owned by Google, but need to follow the pre-defined API spec. */ +export declare interface ExternalApi { + /** The authentication config to access the API. Deprecated. Please use auth_config instead. */ + apiAuth?: ApiAuth; + /** The API spec that the external API implements. */ + apiSpec?: ApiSpec; + /** The authentication config to access the API. */ + authConfig?: AuthConfig; + /** Parameters for the elastic search API. */ + elasticSearchParams?: ExternalApiElasticSearchParams; + /** The endpoint of the external API. The system will call the API at this endpoint to retrieve the data for grounding. Example: https://acme.com:443/search */ + endpoint?: string; + /** Parameters for the simple search API. */ + simpleSearchParams?: ExternalApiSimpleSearchParams; +} + +/** The search parameters to use for the ELASTIC_SEARCH spec. */ +export declare interface ExternalApiElasticSearchParams { + /** The ElasticSearch index to use. */ + index?: string; + /** Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as the `num_hits` param. */ + numHits?: number; + /** The ElasticSearch search template to use. */ + searchTemplate?: string; +} + +/** The search parameters to use for SIMPLE_SEARCH spec. */ +export declare interface ExternalApiSimpleSearchParams { +} + +/** Options for feature selection preference. */ +export declare enum FeatureSelectionPreference { + FEATURE_SELECTION_PREFERENCE_UNSPECIFIED = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED", + PRIORITIZE_QUALITY = "PRIORITIZE_QUALITY", + BALANCED = "BALANCED", + PRIORITIZE_COST = "PRIORITIZE_COST" +} + +export declare interface FetchPredictOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the fetchPredictOperation method. */ +export declare interface FetchPredictOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + resourceName: string; + /** Used to override the default configuration. */ + config?: FetchPredictOperationConfig; +} + +/** A file uploaded to the API. */ +declare interface File_2 { + /** The `File` resource name. The ID (name excluding the "files/" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */ + name?: string; + /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */ + displayName?: string; + /** Output only. MIME type of the file. */ + mimeType?: string; + /** Output only. Size of the file in bytes. */ + sizeBytes?: string; + /** Output only. The timestamp of when the `File` was created. */ + createTime?: string; + /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */ + expirationTime?: string; + /** Output only. The timestamp of when the `File` was last updated. */ + updateTime?: string; + /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */ + sha256Hash?: string; + /** Output only. The URI of the `File`. */ + uri?: string; + /** Output only. The URI of the `File`, only set for downloadable (generated) files. */ + downloadUri?: string; + /** Output only. Processing state of the File. */ + state?: FileState; + /** Output only. The source of the `File`. */ + source?: FileSource; + /** Output only. Metadata for a video. */ + videoMetadata?: Record; + /** Output only. Error status if File processing failed. */ + error?: FileStatus; +} +export { File_2 as File } + +/** URI based data. */ +export declare interface FileData { + /** Optional. Display name of the file data. Used to provide a label or filename to distinguish file datas. It is not currently used in the Gemini GenerateContent calls. */ + displayName?: string; + /** Required. URI. */ + fileUri?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} + +export declare class Files extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + list: (params?: types.ListFilesParameters) => Promise>; + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + upload(params: types.UploadFileParameters): Promise; + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + download(params: types.DownloadFileParameters): Promise; + private listInternal; + private createInternal; + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + get(params: types.GetFileParameters): Promise; + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + delete(params: types.DeleteFileParameters): Promise; +} + +/** Source of the File. */ +export declare enum FileSource { + SOURCE_UNSPECIFIED = "SOURCE_UNSPECIFIED", + UPLOADED = "UPLOADED", + GENERATED = "GENERATED" +} + +/** + * Represents the size and mimeType of a file. The information is used to + * request the upload URL from the https://generativelanguage.googleapis.com/upload/v1beta/files endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface FileStat { + /** + * The size of the file in bytes. + */ + size: number; + /** + * The MIME type of the file. + */ + type: string | undefined; +} + +/** State for the lifecycle of a File. */ +export declare enum FileState { + STATE_UNSPECIFIED = "STATE_UNSPECIFIED", + PROCESSING = "PROCESSING", + ACTIVE = "ACTIVE", + FAILED = "FAILED" +} + +/** Status of a File that uses a common error model. */ +export declare interface FileStatus { + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: Record[]; + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + message?: string; + /** The status code. 0 for OK, 1 for CANCELLED */ + code?: number; +} + +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +export declare enum FinishReason { + /** + * The finish reason is unspecified. + */ + FINISH_REASON_UNSPECIFIED = "FINISH_REASON_UNSPECIFIED", + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + STOP = "STOP", + /** + * Token generation reached the configured maximum output tokens. + */ + MAX_TOKENS = "MAX_TOKENS", + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + SAFETY = "SAFETY", + /** + * The token generation stopped because of potential recitation. + */ + RECITATION = "RECITATION", + /** + * The token generation stopped because of using an unsupported language. + */ + LANGUAGE = "LANGUAGE", + /** + * All other reasons that stopped the token generation. + */ + OTHER = "OTHER", + /** + * Token generation stopped because the content contains forbidden terms. + */ + BLOCKLIST = "BLOCKLIST", + /** + * Token generation stopped for potentially containing prohibited content. + */ + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + /** + * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). + */ + SPII = "SPII", + /** + * The function call generated by the model is invalid. + */ + MALFORMED_FUNCTION_CALL = "MALFORMED_FUNCTION_CALL", + /** + * Token generation stopped because generated images have safety violations. + */ + IMAGE_SAFETY = "IMAGE_SAFETY", + /** + * The tool call generated by the model is invalid. + */ + UNEXPECTED_TOOL_CALL = "UNEXPECTED_TOOL_CALL" +} + +/** A function call. */ +export declare interface FunctionCall { + /** The unique id of the function call. If populated, the client to execute the + `function_call` and return the response with the matching `id`. */ + id?: string; + /** Optional. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */ + args?: Record; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */ + name?: string; +} + +/** Function calling config. */ +export declare interface FunctionCallingConfig { + /** Optional. Function calling mode. */ + mode?: FunctionCallingConfigMode; + /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */ + allowedFunctionNames?: string[]; +} + +/** Config for the function calling config mode. */ +export declare enum FunctionCallingConfigMode { + /** + * The function calling config mode is unspecified. Should not be used. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + AUTO = "AUTO", + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + ANY = "ANY", + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + NONE = "NONE" +} + +/** Defines a function that the model can generate JSON inputs for. + + The inputs are based on `OpenAPI 3.0 specifications + `_. + */ +export declare interface FunctionDeclaration { + /** Defines the function behavior. */ + behavior?: Behavior; + /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */ + description?: string; + /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */ + name?: string; + /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */ + parameters?: Schema; + /** Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "integer" } }, "additionalProperties": false, "required": ["name", "age"], "propertyOrdering": ["name", "age"] } ``` This field is mutually exclusive with `parameters`. */ + parametersJsonSchema?: unknown; + /** Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function. */ + response?: Schema; + /** Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`. */ + responseJsonSchema?: unknown; +} + +/** A function response. */ +export declare class FunctionResponse { + /** Signals that function call continues, and more responses will be returned, turning the function call into a generator. Is only applicable to NON_BLOCKING function calls (see FunctionDeclaration.behavior for details), ignored otherwise. If false, the default, future responses will not be considered. Is only applicable to NON_BLOCKING function calls, is ignored otherwise. If set to false, future responses will not be considered. It is allowed to return empty `response` with `will_continue=False` to signal that the function call is finished. */ + willContinue?: boolean; + /** Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. */ + scheduling?: FunctionResponseScheduling; + /** Optional. The id of the function call this response is for. Populated by the client to match the corresponding function call `id`. */ + id?: string; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */ + name?: string; + /** Required. The function response in JSON object format. Use "output" key to specify function output and "error" key to specify error details (if any). If "output" and "error" keys are not specified, then whole "response" is treated as function output. */ + response?: Record; +} + +/** Specifies how the response should be scheduled in the conversation. */ +export declare enum FunctionResponseScheduling { + /** + * This value is unused. + */ + SCHEDULING_UNSPECIFIED = "SCHEDULING_UNSPECIFIED", + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + SILENT = "SILENT", + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + WHEN_IDLE = "WHEN_IDLE", + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + INTERRUPT = "INTERRUPT" +} + +/** Input example for preference optimization. */ +export declare interface GeminiPreferenceExample { + /** List of completions for a given prompt. */ + completions?: GeminiPreferenceExampleCompletion[]; + /** Multi-turn contents that represents the Prompt. */ + contents?: Content[]; +} + +/** Completion and its preference score. */ +export declare interface GeminiPreferenceExampleCompletion { + /** Single turn completion for the given prompt. */ + completion?: Content; + /** The score for the given completion. */ + score?: number; +} + +/** Optional model configuration parameters. + + For more information, see `Content generation parameters + `_. + */ +export declare interface GenerateContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Instructions for the model to steer it toward better performance. + For example, "Answer as concisely as possible" or "Don't use technical + terms in your response". + */ + systemInstruction?: ContentUnion; + /** Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + */ + temperature?: number; + /** Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + */ + topP?: number; + /** For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + */ + topK?: number; + /** Number of response variations to return. + */ + candidateCount?: number; + /** Maximum number of tokens that can be generated in the response. + */ + maxOutputTokens?: number; + /** List of strings that tells the model to stop generating text if one + of the strings is encountered in the response. + */ + stopSequences?: string[]; + /** Whether to return the log probabilities of the tokens that were + chosen by the model at each step. + */ + responseLogprobs?: boolean; + /** Number of top candidate tokens to return the log probabilities for + at each generation step. + */ + logprobs?: number; + /** Positive values penalize tokens that already appear in the + generated text, increasing the probability of generating more diverse + content. + */ + presencePenalty?: number; + /** Positive values penalize tokens that repeatedly appear in the + generated text, increasing the probability of generating more diverse + content. + */ + frequencyPenalty?: number; + /** When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + */ + seed?: number; + /** Output response mimetype of the generated candidate text. + Supported mimetype: + - `text/plain`: (default) Text output. + - `application/json`: JSON response in the candidates. + The model needs to be prompted to output the appropriate response type, + otherwise the behavior is undefined. + This is a preview feature. + */ + responseMimeType?: string; + /** The `Schema` object allows the definition of input and output data types. + These types can be objects, but also primitives and arrays. + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema). + If set, a compatible response_mime_type must also be set. + Compatible mimetypes: `application/json`: Schema for JSON response. + */ + responseSchema?: SchemaUnion; + /** Optional. Output schema of the generated response. + This is an alternative to `response_schema` that accepts [JSON + Schema](https://json-schema.org/). If set, `response_schema` must be + omitted, but `response_mime_type` is required. While the full JSON Schema + may be sent, not all features are supported. Specifically, only the + following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` + - `type` - `format` - `title` - `description` - `enum` (for strings and + numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - + `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - + `properties` - `additionalProperties` - `required` The non-standard + `propertyOrdering` property may also be set. Cyclic references are + unrolled to a limited degree and, as such, may only be used within + non-required properties. (Nullable properties are not sufficient.) If + `$ref` is set on a sub-schema, no other properties, except for than those + starting as a `$`, may be set. */ + responseJsonSchema?: unknown; + /** Configuration for model router requests. + */ + routingConfig?: GenerationConfigRoutingConfig; + /** Configuration for model selection. + */ + modelSelectionConfig?: ModelSelectionConfig; + /** Safety settings in the request to block unsafe content in the + response. + */ + safetySettings?: SafetySetting[]; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: ToolListUnion; + /** Associates model output to a specific function call. + */ + toolConfig?: ToolConfig; + /** Labels with user-defined metadata to break down billed charges. */ + labels?: Record; + /** Resource name of a context cache that can be used in subsequent + requests. + */ + cachedContent?: string; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. + */ + responseModalities?: string[]; + /** If specified, the media resolution specified will be used. + */ + mediaResolution?: MediaResolution; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfigUnion; + /** If enabled, audio timestamp will be included in the request to the + model. + */ + audioTimestamp?: boolean; + /** The configuration for automatic function calling. + */ + automaticFunctionCalling?: AutomaticFunctionCallingConfig; + /** The thinking features configuration. + */ + thinkingConfig?: ThinkingConfig; +} + +/** Config for models.generate_content parameters. */ +export declare interface GenerateContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Content of the request. + */ + contents: ContentListUnion; + /** Configuration that contains optional model parameters. + */ + config?: GenerateContentConfig; +} + +/** Response message for PredictionService.GenerateContent. */ +export declare class GenerateContentResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Response variations returned by the model. + */ + candidates?: Candidate[]; + /** Timestamp when the request is made to the server. + */ + createTime?: string; + /** The history of automatic function calling. + */ + automaticFunctionCallingHistory?: Content[]; + /** Output only. The model version used to generate the response. */ + modelVersion?: string; + /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */ + promptFeedback?: GenerateContentResponsePromptFeedback; + /** Output only. response_id is used to identify each response. It is the encoding of the event_id. */ + responseId?: string; + /** Usage metadata about the response(s). */ + usageMetadata?: GenerateContentResponseUsageMetadata; + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text(): string | undefined; + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data(): string | undefined; + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls(): FunctionCall[] | undefined; + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode(): string | undefined; + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult(): string | undefined; +} + +/** Content filter results for a prompt sent in the request. */ +export declare class GenerateContentResponsePromptFeedback { + /** Output only. Blocked reason. */ + blockReason?: BlockedReason; + /** Output only. A readable block reason message. */ + blockReasonMessage?: string; + /** Output only. Safety ratings. */ + safetyRatings?: SafetyRating[]; +} + +/** Usage metadata about response(s). */ +export declare class GenerateContentResponseUsageMetadata { + /** Output only. List of modalities of the cached content in the request input. */ + cacheTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens in the cached part in the input (the cached content). */ + cachedContentTokenCount?: number; + /** Number of tokens in the response(s). */ + candidatesTokenCount?: number; + /** Output only. List of modalities that were returned in the response. */ + candidatesTokensDetails?: ModalityTokenCount[]; + /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */ + promptTokenCount?: number; + /** Output only. List of modalities that were processed in the request input. */ + promptTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens present in thoughts output. */ + thoughtsTokenCount?: number; + /** Output only. Number of tokens present in tool-use prompt(s). */ + toolUsePromptTokenCount?: number; + /** Output only. List of modalities that were processed for tool-use request inputs. */ + toolUsePromptTokensDetails?: ModalityTokenCount[]; + /** Total token count for prompt, response candidates, and tool-use prompts (if present). */ + totalTokenCount?: number; + /** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ + trafficType?: TrafficType; +} + +/** An output image. */ +export declare interface GeneratedImage { + /** The output image data. + */ + image?: Image_2; + /** Responsible AI filter reason if the image is filtered out of the + response. + */ + raiFilteredReason?: string; + /** Safety attributes of the image. Lists of RAI categories and their + scores of each content. + */ + safetyAttributes?: SafetyAttributes; + /** The rewritten prompt used for the image generation if the prompt + enhancer is enabled. + */ + enhancedPrompt?: string; +} + +/** A generated image mask. */ +export declare interface GeneratedImageMask { + /** The generated image mask. */ + mask?: Image_2; + /** The detected entities on the segmented area. */ + labels?: EntityLabel[]; +} + +/** A generated video. */ +export declare interface GeneratedVideo { + /** The output video */ + video?: Video; +} + +/** The config for generating an images. */ +export declare interface GenerateImagesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage URI used to store the generated images. + */ + outputGcsUri?: string; + /** Description of what to discourage in the generated images. + */ + negativePrompt?: string; + /** Number of images to generate. + */ + numberOfImages?: number; + /** Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9". + */ + aspectRatio?: string; + /** Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality. + */ + guidanceScale?: number; + /** Random seed for image generation. This is not available when + ``add_watermark`` is set to true. + */ + seed?: number; + /** Filter level for safety filtering. + */ + safetyFilterLevel?: SafetyFilterLevel; + /** Allows generation of people by the model. + */ + personGeneration?: PersonGeneration; + /** Whether to report the safety scores of each generated image and + the positive prompt in the response. + */ + includeSafetyAttributes?: boolean; + /** Whether to include the Responsible AI filter reason if the image + is filtered out of the response. + */ + includeRaiReason?: boolean; + /** Language of the text in the prompt. + */ + language?: ImagePromptLanguage; + /** MIME type of the generated image. + */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). + */ + outputCompressionQuality?: number; + /** Whether to add a watermark to the generated images. + */ + addWatermark?: boolean; + /** The size of the largest dimension of the generated image. + Supported sizes are 1K and 2K (not supported for Imagen 3 models). + */ + imageSize?: string; + /** Whether to use the prompt rewriting logic. + */ + enhancePrompt?: boolean; +} + +/** The parameters for generating images. */ +export declare interface GenerateImagesParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Text prompt that typically describes the images to output. + */ + prompt: string; + /** Configuration for generating images. + */ + config?: GenerateImagesConfig; +} + +/** The output images response. */ +export declare class GenerateImagesResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** List of generated images. + */ + generatedImages?: GeneratedImage[]; + /** Safety attributes of the positive prompt. Only populated if + ``include_safety_attributes`` is set to True. + */ + positivePromptSafetyAttributes?: SafetyAttributes; +} + +/** Configuration for generating videos. */ +export declare interface GenerateVideosConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Number of output videos. */ + numberOfVideos?: number; + /** The gcs bucket where to save the generated videos. */ + outputGcsUri?: string; + /** Frames per second for video generation. */ + fps?: number; + /** Duration of the clip for video generation in seconds. */ + durationSeconds?: number; + /** The RNG seed. If RNG seed is exactly same for each request with unchanged inputs, the prediction results will be consistent. Otherwise, a random RNG seed will be used each time to produce a different result. */ + seed?: number; + /** The aspect ratio for the generated video. 16:9 (landscape) and 9:16 (portrait) are supported. */ + aspectRatio?: string; + /** The resolution for the generated video. 720p and 1080p are supported. */ + resolution?: string; + /** Whether allow to generate person videos, and restrict to specific ages. Supported values are: dont_allow, allow_adult. */ + personGeneration?: string; + /** The pubsub topic where to publish the video generation progress. */ + pubsubTopic?: string; + /** Optional field in addition to the text content. Negative prompts can be explicitly stated here to help generate the video. */ + negativePrompt?: string; + /** Whether to use the prompt rewriting logic. */ + enhancePrompt?: boolean; + /** Whether to generate audio along with the video. */ + generateAudio?: boolean; + /** Image to use as the last frame of generated videos. Only supported for image to video use cases. */ + lastFrame?: Image_2; + /** The images to use as the references to generate the videos. + If this field is provided, the text prompt field must also be provided. + The image, video, or last_frame field are not supported. Each image must + be associated with a type. Veo 2 supports up to 3 asset images *or* 1 + style image. */ + referenceImages?: VideoGenerationReferenceImage[]; + /** Compression quality of the generated videos. */ + compressionQuality?: VideoCompressionQuality; +} + +/** A video generation long-running operation. */ +export declare class GenerateVideosOperation implements Operation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The response if the operation is successful. */ + response?: GenerateVideosResponse; + /** The full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }: OperationFromAPIResponseParameters): Operation; +} + +/** Class that represents the parameters for generating videos. */ +export declare interface GenerateVideosParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The text prompt for generating the videos. Optional for image to video use cases. */ + prompt?: string; + /** The input image for generating the videos. + Optional if prompt or video is provided. */ + image?: Image_2; + /** The input video for video extension use cases. + Optional if prompt or image is provided. */ + video?: Video; + /** Configuration for generating videos. */ + config?: GenerateVideosConfig; +} + +/** Response with generated videos. */ +export declare class GenerateVideosResponse { + /** List of the generated videos */ + generatedVideos?: GeneratedVideo[]; + /** Returns if any videos were filtered due to RAI policies. */ + raiMediaFilteredCount?: number; + /** Returns rai failure reasons if any. */ + raiMediaFilteredReasons?: string[]; +} + +/** Generation config. */ +export declare interface GenerationConfig { + /** Optional. Config for model selection. */ + modelSelectionConfig?: ModelSelectionConfig; + /** Optional. If enabled, audio timestamp will be included in the request to the model. */ + audioTimestamp?: boolean; + /** Optional. Number of candidates to generate. */ + candidateCount?: number; + /** Optional. If enabled, the model will detect emotions and adapt its responses accordingly. */ + enableAffectiveDialog?: boolean; + /** Optional. Frequency penalties. */ + frequencyPenalty?: number; + /** Optional. Logit probabilities. */ + logprobs?: number; + /** Optional. The maximum number of output tokens to generate per message. */ + maxOutputTokens?: number; + /** Optional. If specified, the media resolution specified will be used. */ + mediaResolution?: MediaResolution; + /** Optional. Positive penalties. */ + presencePenalty?: number; + /** Optional. Output schema of the generated response. This is an alternative to `response_schema` that accepts [JSON Schema](https://json-schema.org/). If set, `response_schema` must be omitted, but `response_mime_type` is required. While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` - `type` - `format` - `title` - `description` - `enum` (for strings and numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - `properties` - `additionalProperties` - `required` The non-standard `propertyOrdering` property may also be set. Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If `$ref` is set on a sub-schema, no other properties, except for than those starting as a `$`, may be set. */ + responseJsonSchema?: unknown; + /** Optional. If true, export the logprobs results in response. */ + responseLogprobs?: boolean; + /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */ + responseMimeType?: string; + /** Optional. The modalities of the response. */ + responseModalities?: Modality[]; + /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */ + responseSchema?: Schema; + /** Optional. Routing configuration. */ + routingConfig?: GenerationConfigRoutingConfig; + /** Optional. Seed. */ + seed?: number; + /** Optional. The speech generation config. */ + speechConfig?: SpeechConfig; + /** Optional. Stop sequences. */ + stopSequences?: string[]; + /** Optional. Controls the randomness of predictions. */ + temperature?: number; + /** Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking. */ + thinkingConfig?: GenerationConfigThinkingConfig; + /** Optional. If specified, top-k sampling will be used. */ + topK?: number; + /** Optional. If specified, nucleus sampling will be used. */ + topP?: number; +} + +/** The configuration for routing the request to a specific model. */ +export declare interface GenerationConfigRoutingConfig { + /** Automated routing. */ + autoMode?: GenerationConfigRoutingConfigAutoRoutingMode; + /** Manual routing. */ + manualMode?: GenerationConfigRoutingConfigManualRoutingMode; +} + +/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */ +export declare interface GenerationConfigRoutingConfigAutoRoutingMode { + /** The model routing preference. */ + modelRoutingPreference?: 'UNKNOWN' | 'PRIORITIZE_QUALITY' | 'BALANCED' | 'PRIORITIZE_COST'; +} + +/** When manual routing is set, the specified model will be used directly. */ +export declare interface GenerationConfigRoutingConfigManualRoutingMode { + /** The model name to use. Only the public LLM models are accepted. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */ + modelName?: string; +} + +/** Config for thinking features. */ +export declare interface GenerationConfigThinkingConfig { + /** Optional. Indicates whether to include thoughts in the response. If true, thoughts are returned only when available. */ + includeThoughts?: boolean; + /** Optional. Indicates the thinking budget in tokens. */ + thinkingBudget?: number; +} + +/** Optional parameters. */ +export declare interface GetBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.get parameters. */ +export declare interface GetBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: GetBatchJobConfig; +} + +/** Optional parameters for caches.get method. */ +export declare interface GetCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for caches.get method. */ +export declare interface GetCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: GetCachedContentConfig; +} + +/** Used to override the default configuration. */ +export declare interface GetFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the get method. */ +export declare interface GetFileParameters { + /** The name identifier for the file to retrieve. */ + name: string; + /** Used to override the default configuration. */ + config?: GetFileConfig; +} + +/** Optional parameters for models.get method. */ +export declare interface GetModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +export declare interface GetModelParameters { + model: string; + /** Optional parameters for the request. */ + config?: GetModelConfig; +} + +export declare interface GetOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the GET method. */ +export declare interface GetOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + /** Used to override the default configuration. */ + config?: GetOperationConfig; +} + +/** Optional parameters for tunings.get method. */ +export declare interface GetTuningJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the get method. */ +export declare interface GetTuningJobParameters { + name: string; + /** Optional parameters for the request. */ + config?: GetTuningJobConfig; +} + +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link + * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or + * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI + * API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API + * services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be + * set. When using Vertex AI, currently only {@link GoogleGenAIOptions.apiKey} + * is supported via Express mode. {@link GoogleGenAIOptions.project} and {@link + * GoogleGenAIOptions.location} should not be set. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +export declare class GoogleGenAI { + protected readonly apiClient: ApiClient; + private readonly apiKey?; + readonly vertexai: boolean; + private readonly apiVersion?; + readonly models: Models; + readonly live: Live; + readonly batches: Batches; + readonly chats: Chats; + readonly caches: Caches; + readonly files: Files; + readonly operations: Operations; + readonly authTokens: Tokens; + readonly tunings: Tunings; + constructor(options: GoogleGenAIOptions); +} + +/** + * Google Gen AI SDK's configuration options. + * + * See {@link GoogleGenAI} for usage samples. + */ +export declare interface GoogleGenAIOptions { + /** + * Optional. Determines whether to use the Vertex AI or the Gemini API. + * + * @remarks + * When true, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API} will used. + * When false, the {@link https://ai.google.dev/api | Gemini API} will be used. + * + * If unset, default SDK behavior is to use the Gemini API service. + */ + vertexai?: boolean; + /** + * Optional. The Google Cloud project ID for Vertex AI clients. + * + * Find your project ID: https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + */ + project?: string; + /** + * Optional. The Google Cloud project {@link https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations | location} for Vertex AI clients. + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + location?: string; + /** + * The API Key, required for Gemini API clients. + * + * @remarks + * Required on browser runtimes. + */ + apiKey?: string; + /** + * Optional. The API version to use. + * + * @remarks + * If unset, the default API version will be used. + */ + apiVersion?: string; + /** + * Optional. Authentication options defined by the by google-auth-library for Vertex AI clients. + * + * @remarks + * @see {@link https://github.com/googleapis/google-auth-library-nodejs/blob/v9.15.0/src/auth/googleauth.ts | GoogleAuthOptions interface in google-auth-library-nodejs}. + * + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + googleAuthOptions?: GoogleAuthOptions; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; +} + +/** Tool to support Google Maps in Model. */ +export declare interface GoogleMaps { + /** Optional. Auth config for the Google Maps tool. */ + authConfig?: AuthConfig; +} + +/** The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). */ +export declare interface GoogleRpcStatus { + /** The status code, which should be an enum value of google.rpc.Code. */ + code?: number; + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: Record[]; + /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */ + message?: string; +} + +/** Tool to support Google Search in Model. Powered by Google. */ +export declare interface GoogleSearch { + /** Optional. Filter search results to a specific time range. + If customers set a start time, they must set an end time (and vice versa). + */ + timeRangeFilter?: Interval; + /** Optional. List of domains to be excluded from the search results. + The default limit is 2000 domains. */ + excludeDomains?: string[]; +} + +/** Tool to retrieve public web data for grounding, powered by Google. */ +export declare interface GoogleSearchRetrieval { + /** Specifies the dynamic retrieval configuration for the given source. */ + dynamicRetrievalConfig?: DynamicRetrievalConfig; +} + +/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */ +export declare interface GoogleTypeDate { + /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */ + day?: number; + /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */ + month?: number; + /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */ + year?: number; +} + +/** Grounding chunk. */ +export declare interface GroundingChunk { + /** Grounding chunk from Google Maps. */ + maps?: GroundingChunkMaps; + /** Grounding chunk from context retrieved by the retrieval tools. */ + retrievedContext?: GroundingChunkRetrievedContext; + /** Grounding chunk from the web. */ + web?: GroundingChunkWeb; +} + +/** Chunk from Google Maps. */ +export declare interface GroundingChunkMaps { + /** Sources used to generate the place answer. This includes review snippets and photos that were used to generate the answer, as well as uris to flag content. */ + placeAnswerSources?: GroundingChunkMapsPlaceAnswerSources; + /** This Place's resource name, in `places/{place_id}` format. Can be used to look up the Place. */ + placeId?: string; + /** Text of the chunk. */ + text?: string; + /** Title of the chunk. */ + title?: string; + /** URI reference of the chunk. */ + uri?: string; +} + +/** Sources used to generate the place answer. */ +export declare interface GroundingChunkMapsPlaceAnswerSources { + /** A link where users can flag a problem with the generated answer. */ + flagContentUri?: string; + /** Snippets of reviews that are used to generate the answer. */ + reviewSnippets?: GroundingChunkMapsPlaceAnswerSourcesReviewSnippet[]; +} + +/** Author attribution for a photo or review. */ +export declare interface GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution { + /** Name of the author of the Photo or Review. */ + displayName?: string; + /** Profile photo URI of the author of the Photo or Review. */ + photoUri?: string; + /** URI of the author of the Photo or Review. */ + uri?: string; +} + +/** Encapsulates a review snippet. */ +export declare interface GroundingChunkMapsPlaceAnswerSourcesReviewSnippet { + /** This review's author. */ + authorAttribution?: GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution; + /** A link where users can flag a problem with the review. */ + flagContentUri?: string; + /** A link to show the review on Google Maps. */ + googleMapsUri?: string; + /** A string of formatted recent time, expressing the review time relative to the current time in a form appropriate for the language and country. */ + relativePublishTimeDescription?: string; + /** A reference representing this place review which may be used to look up this place review again. */ + review?: string; +} + +/** Chunk from context retrieved by the retrieval tools. */ +export declare interface GroundingChunkRetrievedContext { + /** Output only. The full document name for the referenced Vertex AI Search document. */ + documentName?: string; + /** Additional context for the RAG retrieval result. This is only populated when using the RAG retrieval tool. */ + ragChunk?: RagChunk; + /** Text of the attribution. */ + text?: string; + /** Title of the attribution. */ + title?: string; + /** URI reference of the attribution. */ + uri?: string; +} + +/** Chunk from the web. */ +export declare interface GroundingChunkWeb { + /** Domain of the (original) URI. */ + domain?: string; + /** Title of the chunk. */ + title?: string; + /** URI reference of the chunk. */ + uri?: string; +} + +/** Metadata returned to client when grounding is enabled. */ +export declare interface GroundingMetadata { + /** Optional. Output only. Resource name of the Google Maps widget context token to be used with the PlacesContextElement widget to render contextual data. This is populated only for Google Maps grounding. */ + googleMapsWidgetContextToken?: string; + /** List of supporting references retrieved from specified grounding source. */ + groundingChunks?: GroundingChunk[]; + /** Optional. List of grounding support. */ + groundingSupports?: GroundingSupport[]; + /** Optional. Output only. Retrieval metadata. */ + retrievalMetadata?: RetrievalMetadata; + /** Optional. Queries executed by the retrieval tools. */ + retrievalQueries?: string[]; + /** Optional. Google search entry for the following-up web searches. */ + searchEntryPoint?: SearchEntryPoint; + /** Optional. Web search queries for the following-up web search. */ + webSearchQueries?: string[]; +} + +/** Grounding support. */ +export declare interface GroundingSupport { + /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. For Gemini 2.0 and before, this list must have the same size as the grounding_chunk_indices. For Gemini 2.5 and after, this list will be empty and should be ignored. */ + confidenceScores?: number[]; + /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */ + groundingChunkIndices?: number[]; + /** Segment of the content this support belongs to. */ + segment?: Segment; +} + +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +export declare enum HarmBlockMethod { + /** + * The harm block method is unspecified. + */ + HARM_BLOCK_METHOD_UNSPECIFIED = "HARM_BLOCK_METHOD_UNSPECIFIED", + /** + * The harm block method uses both probability and severity scores. + */ + SEVERITY = "SEVERITY", + /** + * The harm block method uses the probability score. + */ + PROBABILITY = "PROBABILITY" +} + +/** Required. The harm block threshold. */ +export declare enum HarmBlockThreshold { + /** + * Unspecified harm block threshold. + */ + HARM_BLOCK_THRESHOLD_UNSPECIFIED = "HARM_BLOCK_THRESHOLD_UNSPECIFIED", + /** + * Block low threshold and above (i.e. block more). + */ + BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", + /** + * Block medium threshold and above. + */ + BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", + /** + * Block only high threshold (i.e. block less). + */ + BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", + /** + * Block none. + */ + BLOCK_NONE = "BLOCK_NONE", + /** + * Turn off the safety filter. + */ + OFF = "OFF" +} + +/** Required. Harm category. */ +export declare enum HarmCategory { + /** + * The harm category is unspecified. + */ + HARM_CATEGORY_UNSPECIFIED = "HARM_CATEGORY_UNSPECIFIED", + /** + * The harm category is hate speech. + */ + HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH", + /** + * The harm category is dangerous content. + */ + HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT", + /** + * The harm category is harassment. + */ + HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT", + /** + * The harm category is sexually explicit content. + */ + HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT", + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HARM_CATEGORY_CIVIC_INTEGRITY = "HARM_CATEGORY_CIVIC_INTEGRITY", + /** + * The harm category is image hate. + */ + HARM_CATEGORY_IMAGE_HATE = "HARM_CATEGORY_IMAGE_HATE", + /** + * The harm category is image dangerous content. + */ + HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT", + /** + * The harm category is image harassment. + */ + HARM_CATEGORY_IMAGE_HARASSMENT = "HARM_CATEGORY_IMAGE_HARASSMENT", + /** + * The harm category is image sexually explicit content. + */ + HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT" +} + +/** Output only. Harm probability levels in the content. */ +export declare enum HarmProbability { + /** + * Harm probability unspecified. + */ + HARM_PROBABILITY_UNSPECIFIED = "HARM_PROBABILITY_UNSPECIFIED", + /** + * Negligible level of harm. + */ + NEGLIGIBLE = "NEGLIGIBLE", + /** + * Low level of harm. + */ + LOW = "LOW", + /** + * Medium level of harm. + */ + MEDIUM = "MEDIUM", + /** + * High level of harm. + */ + HIGH = "HIGH" +} + +/** Output only. Harm severity levels in the content. */ +export declare enum HarmSeverity { + /** + * Harm severity unspecified. + */ + HARM_SEVERITY_UNSPECIFIED = "HARM_SEVERITY_UNSPECIFIED", + /** + * Negligible level of harm severity. + */ + HARM_SEVERITY_NEGLIGIBLE = "HARM_SEVERITY_NEGLIGIBLE", + /** + * Low level of harm severity. + */ + HARM_SEVERITY_LOW = "HARM_SEVERITY_LOW", + /** + * Medium level of harm severity. + */ + HARM_SEVERITY_MEDIUM = "HARM_SEVERITY_MEDIUM", + /** + * High level of harm severity. + */ + HARM_SEVERITY_HIGH = "HARM_SEVERITY_HIGH" +} + +/** HTTP options to be used in each of the requests. */ +export declare interface HttpOptions { + /** The base URL for the AI platform service endpoint. */ + baseUrl?: string; + /** Specifies the version of the API to use. */ + apiVersion?: string; + /** Additional HTTP headers to be sent with the request. */ + headers?: Record; + /** Timeout for the request in milliseconds. */ + timeout?: number; + /** Extra parameters to add to the request body. + The structure must match the backend API's request structure. + - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest + - GeminiAPI backend API docs: https://ai.google.dev/api/rest */ + extraBody?: Record; +} + +/** + * Represents the necessary information to send a request to an API endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface HttpRequest { + /** + * URL path from the modules, this path is appended to the base API URL to + * form the complete request URL. + * + * If you wish to set full URL, use httpOptions.baseUrl instead. Example to + * set full URL in the request: + * + * const request: HttpRequest = { + * path: '', + * httpOptions: { + * baseUrl: 'https://', + * apiVersion: '', + * }, + * httpMethod: 'GET', + * }; + * + * The result URL will be: https:// + * + */ + path: string; + /** + * Optional query parameters to be appended to the request URL. + */ + queryParams?: Record; + /** + * Optional request body in json string or Blob format, GET request doesn't + * need a request body. + */ + body?: string | Blob; + /** + * The HTTP method to be used for the request. + */ + httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE'; + /** + * Optional set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; + /** + * Optional abort signal which can be used to cancel the request. + */ + abortSignal?: AbortSignal; +} + +/** A wrapper class for the http response. */ +export declare class HttpResponse { + /** Used to retain the processed HTTP headers in the response. */ + headers?: Record; + /** + * The original http response. + */ + responseInternal: Response; + constructor(response: Response); + json(): Promise; +} + +/** An image. */ +declare interface Image_2 { + /** The Cloud Storage URI of the image. ``Image`` can contain a value + for this field or the ``image_bytes`` field but not both. + */ + gcsUri?: string; + /** The image bytes data. ``Image`` can contain a value for this field + or the ``gcs_uri`` field but not both. + + * @remarks Encoded as base64 string. */ + imageBytes?: string; + /** The MIME type of the image. */ + mimeType?: string; +} +export { Image_2 as Image } + +/** Enum that specifies the language of the text in the prompt. */ +export declare enum ImagePromptLanguage { + /** + * Auto-detect the language. + */ + auto = "auto", + /** + * English + */ + en = "en", + /** + * Japanese + */ + ja = "ja", + /** + * Korean + */ + ko = "ko", + /** + * Hindi + */ + hi = "hi", + /** + * Chinese + */ + zh = "zh", + /** + * Portuguese + */ + pt = "pt", + /** + * Spanish + */ + es = "es" +} + +/** Config for inlined request. */ +export declare interface InlinedRequest { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model?: string; + /** Content of the request. + */ + contents?: ContentListUnion; + /** Configuration that contains optional model parameters. + */ + config?: GenerateContentConfig; +} + +/** Config for `inlined_responses` parameter. */ +export declare class InlinedResponse { + /** The response to the request. + */ + response?: GenerateContentResponse; + /** The error encountered while processing the request. + */ + error?: JobError; +} + +/** Represents a time interval, encoded as a start time (inclusive) and an end time (exclusive). + + The start time must be less than or equal to the end time. + When the start equals the end time, the interval is an empty interval. + (matches no time) + When both start and end are unspecified, the interval matches any time. + */ +export declare interface Interval { + /** The start time of the interval. */ + startTime?: string; + /** The end time of the interval. */ + endTime?: string; +} + +/** Job error. */ +export declare interface JobError { + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: string[]; + /** The status code. */ + code?: number; + /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the `details` field. */ + message?: string; +} + +/** Job state. */ +export declare enum JobState { + /** + * The job state is unspecified. + */ + JOB_STATE_UNSPECIFIED = "JOB_STATE_UNSPECIFIED", + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JOB_STATE_QUEUED = "JOB_STATE_QUEUED", + /** + * The service is preparing to run the job. + */ + JOB_STATE_PENDING = "JOB_STATE_PENDING", + /** + * The job is in progress. + */ + JOB_STATE_RUNNING = "JOB_STATE_RUNNING", + /** + * The job completed successfully. + */ + JOB_STATE_SUCCEEDED = "JOB_STATE_SUCCEEDED", + /** + * The job failed. + */ + JOB_STATE_FAILED = "JOB_STATE_FAILED", + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JOB_STATE_CANCELLING = "JOB_STATE_CANCELLING", + /** + * The job has been cancelled. + */ + JOB_STATE_CANCELLED = "JOB_STATE_CANCELLED", + /** + * The job has been stopped, and can be resumed. + */ + JOB_STATE_PAUSED = "JOB_STATE_PAUSED", + /** + * The job has expired. + */ + JOB_STATE_EXPIRED = "JOB_STATE_EXPIRED", + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JOB_STATE_UPDATING = "JOB_STATE_UPDATING", + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JOB_STATE_PARTIALLY_SUCCEEDED = "JOB_STATE_PARTIALLY_SUCCEEDED" +} + +/** Required. Programming language of the `code`. */ +export declare enum Language { + /** + * Unspecified language. This value should not be used. + */ + LANGUAGE_UNSPECIFIED = "LANGUAGE_UNSPECIFIED", + /** + * Python >= 3.10, with numpy and simpy available. + */ + PYTHON = "PYTHON" +} + +/** An object that represents a latitude/longitude pair. + + This is expressed as a pair of doubles to represent degrees latitude and + degrees longitude. Unless specified otherwise, this object must conform to the + + WGS84 standard. Values must be within normalized ranges. + */ +export declare interface LatLng { + /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */ + latitude?: number; + /** The longitude in degrees. It must be in the range [-180.0, +180.0] */ + longitude?: number; +} + +/** Config for optional parameters. */ +export declare interface ListBatchJobsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; +} + +/** Config for batches.list parameters. */ +export declare interface ListBatchJobsParameters { + config?: ListBatchJobsConfig; +} + +/** Config for batches.list return value. */ +export declare class ListBatchJobsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + batchJobs?: BatchJob[]; +} + +/** Config for caches.list method. */ +export declare interface ListCachedContentsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; +} + +/** Parameters for caches.list method. */ +export declare interface ListCachedContentsParameters { + /** Configuration that contains optional parameters. + */ + config?: ListCachedContentsConfig; +} + +export declare class ListCachedContentsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + /** List of cached contents. + */ + cachedContents?: CachedContent[]; +} + +/** Used to override the default configuration. */ +export declare interface ListFilesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; +} + +/** Generates the parameters for the list method. */ +export declare interface ListFilesParameters { + /** Used to override the default configuration. */ + config?: ListFilesConfig; +} + +/** Response for the list files method. */ +export declare class ListFilesResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** A token to retrieve next page of results. */ + nextPageToken?: string; + /** The list of files. */ + files?: File_2[]; +} + +export declare interface ListModelsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; + /** Set true to list base models, false to list tuned models. */ + queryBase?: boolean; +} + +export declare interface ListModelsParameters { + config?: ListModelsConfig; +} + +export declare class ListModelsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + models?: Model[]; +} + +/** Configuration for the list tuning jobs method. */ +export declare interface ListTuningJobsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; +} + +/** Parameters for the list tuning jobs method. */ +export declare interface ListTuningJobsParameters { + config?: ListTuningJobsConfig; +} + +/** Response for the list tuning jobs method. */ +export declare class ListTuningJobsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** A token to retrieve the next page of results. Pass to ListTuningJobsRequest.page_token to obtain that page. */ + nextPageToken?: string; + /** List of TuningJobs in the requested page. */ + tuningJobs?: TuningJob[]; +} + +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +export declare class Live { + private readonly apiClient; + private readonly auth; + private readonly webSocketFactory; + readonly music: LiveMusic; + constructor(apiClient: ApiClient, auth: Auth, webSocketFactory: WebSocketFactory); + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + connect(params: types.LiveConnectParameters): Promise; + private isCallableTool; +} + +/** Callbacks for the live API. */ +export declare interface LiveCallbacks { + /** + * Called when the websocket connection is established. + */ + onopen?: (() => void) | null; + /** + * Called when a message is received from the server. + */ + onmessage: (e: LiveServerMessage) => void; + /** + * Called when an error occurs. + */ + onerror?: ((e: ErrorEvent) => void) | null; + /** + * Called when the websocket connection is closed. + */ + onclose?: ((e: CloseEvent) => void) | null; +} + +/** Incremental update of the current conversation delivered from the client. + + All the content here will unconditionally be appended to the conversation + history and used as part of the prompt to the model to generate content. + + A message here will interrupt any current model generation. + */ +export declare interface LiveClientContent { + /** The content appended to the current conversation with the model. + + For single-turn queries, this is a single instance. For multi-turn + queries, this is a repeated field that contains conversation history and + latest request. + */ + turns?: Content[]; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Messages sent by the client in the API call. */ +export declare interface LiveClientMessage { + /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */ + setup?: LiveClientSetup; + /** Incremental update of the current conversation delivered from the client. */ + clientContent?: LiveClientContent; + /** User input that is sent in real time. */ + realtimeInput?: LiveClientRealtimeInput; + /** Response to a `ToolCallMessage` received from the server. */ + toolResponse?: LiveClientToolResponse; +} + +/** User input that is sent in real time. + + This is different from `LiveClientContent` in a few ways: + + - Can be sent continuously without interruption to model generation. + - If there is a need to mix data interleaved across the + `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to + optimize for best response, but there are no guarantees. + - End of turn is not explicitly specified, but is rather derived from user + activity (for example, end of speech). + - Even before the end of turn, the data is processed incrementally + to optimize for a fast start of the response from the model. + - Is always assumed to be the user's input (cannot be used to populate + conversation history). + */ +export declare interface LiveClientRealtimeInput { + /** Inlined bytes data for media input. */ + mediaChunks?: Blob_2[]; + /** The realtime audio input stream. */ + audio?: Blob_2; + /** + Indicates that the audio stream has ended, e.g. because the microphone was + turned off. + + This should only be sent when automatic activity detection is enabled + (which is the default). + + The client can reopen the stream by sending an audio message. + */ + audioStreamEnd?: boolean; + /** The realtime video input stream. */ + video?: Blob_2; + /** The realtime text input stream. */ + text?: string; + /** Marks the start of user activity. */ + activityStart?: ActivityStart; + /** Marks the end of user activity. */ + activityEnd?: ActivityEnd; +} + +/** Message contains configuration that will apply for the duration of the streaming session. */ +export declare interface LiveClientSetup { + /** + The fully qualified name of the publisher model or tuned model endpoint to + use. + */ + model?: string; + /** The generation configuration for the session. + Note: only a subset of fields are supported. + */ + generationConfig?: GenerationConfig; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; + /** Configures the realtime input behavior in BidiGenerateContent. */ + realtimeInputConfig?: RealtimeInputConfig; + /** Configures session resumption mechanism. + + If included server will send SessionResumptionUpdate messages. */ + sessionResumption?: SessionResumptionConfig; + /** Configures context window compression mechanism. + + If included, server will compress context window to fit into given length. */ + contextWindowCompression?: ContextWindowCompressionConfig; + /** The transcription of the input aligns with the input audio language. + */ + inputAudioTranscription?: AudioTranscriptionConfig; + /** The transcription of the output aligns with the language code + specified for the output audio. + */ + outputAudioTranscription?: AudioTranscriptionConfig; + /** Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input. */ + proactivity?: ProactivityConfig; +} + +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +export declare class LiveClientToolResponse { + /** The response to the function calls. */ + functionResponses?: FunctionResponse[]; +} + +/** Session config for the API connection. */ +export declare interface LiveConnectConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The generation configuration for the session. */ + generationConfig?: GenerationConfig; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. Defaults to AUDIO if not specified. + */ + responseModalities?: Modality[]; + /** Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + */ + temperature?: number; + /** Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + */ + topP?: number; + /** For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + */ + topK?: number; + /** Maximum number of tokens that can be generated in the response. + */ + maxOutputTokens?: number; + /** If specified, the media resolution specified will be used. + */ + mediaResolution?: MediaResolution; + /** When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + */ + seed?: number; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfig; + /** If enabled, the model will detect emotions and adapt its responses accordingly. */ + enableAffectiveDialog?: boolean; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; + /** Configures session resumption mechanism. + + If included the server will send SessionResumptionUpdate messages. */ + sessionResumption?: SessionResumptionConfig; + /** The transcription of the input aligns with the input audio language. + */ + inputAudioTranscription?: AudioTranscriptionConfig; + /** The transcription of the output aligns with the language code + specified for the output audio. + */ + outputAudioTranscription?: AudioTranscriptionConfig; + /** Configures the realtime input behavior in BidiGenerateContent. */ + realtimeInputConfig?: RealtimeInputConfig; + /** Configures context window compression mechanism. + + If included, server will compress context window to fit into given length. */ + contextWindowCompression?: ContextWindowCompressionConfig; + /** Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input. */ + proactivity?: ProactivityConfig; +} + +/** Config for LiveConnectConstraints for Auth Token creation. */ +export declare interface LiveConnectConstraints { + /** ID of the model to configure in the ephemeral token for Live API. + For a list of models, see `Gemini models + `. */ + model?: string; + /** Configuration specific to Live API connections created using this token. */ + config?: LiveConnectConfig; +} + +/** Parameters for connecting to the live API. */ +export declare interface LiveConnectParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** callbacks */ + callbacks: LiveCallbacks; + /** Optional configuration parameters for the request. + */ + config?: LiveConnectConfig; +} + +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +declare class LiveMusic { + private readonly apiClient; + private readonly auth; + private readonly webSocketFactory; + constructor(apiClient: ApiClient, auth: Auth, webSocketFactory: WebSocketFactory); + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + connect(params: types.LiveMusicConnectParameters): Promise; +} + +/** Callbacks for the realtime music API. */ +export declare interface LiveMusicCallbacks { + /** + * Called when a message is received from the server. + */ + onmessage: (e: LiveMusicServerMessage) => void; + /** + * Called when an error occurs. + */ + onerror?: ((e: ErrorEvent) => void) | null; + /** + * Called when the websocket connection is closed. + */ + onclose?: ((e: CloseEvent) => void) | null; +} + +/** User input to start or steer the music. */ +export declare interface LiveMusicClientContent { + /** Weighted prompts as the model input. */ + weightedPrompts?: WeightedPrompt[]; +} + +/** Messages sent by the client in the LiveMusicClientMessage call. */ +export declare interface LiveMusicClientMessage { + /** Message to be sent in the first (and only in the first) `LiveMusicClientMessage`. + Clients should wait for a `LiveMusicSetupComplete` message before + sending any additional messages. */ + setup?: LiveMusicClientSetup; + /** User input to influence music generation. */ + clientContent?: LiveMusicClientContent; + /** Configuration for music generation. */ + musicGenerationConfig?: LiveMusicGenerationConfig; + /** Playback control signal for the music generation. */ + playbackControl?: LiveMusicPlaybackControl; +} + +/** Message to be sent by the system when connecting to the API. */ +export declare interface LiveMusicClientSetup { + /** The model's resource name. Format: `models/{model}`. */ + model?: string; +} + +/** Parameters for connecting to the live API. */ +export declare interface LiveMusicConnectParameters { + /** The model's resource name. */ + model: string; + /** Callbacks invoked on server events. */ + callbacks: LiveMusicCallbacks; +} + +/** A prompt that was filtered with the reason. */ +export declare interface LiveMusicFilteredPrompt { + /** The text prompt that was filtered. */ + text?: string; + /** The reason the prompt was filtered. */ + filteredReason?: string; +} + +/** Configuration for music generation. */ +export declare interface LiveMusicGenerationConfig { + /** Controls the variance in audio generation. Higher values produce + higher variance. Range is [0.0, 3.0]. */ + temperature?: number; + /** Controls how the model selects tokens for output. Samples the topK + tokens with the highest probabilities. Range is [1, 1000]. */ + topK?: number; + /** Seeds audio generation. If not set, the request uses a randomly + generated seed. */ + seed?: number; + /** Controls how closely the model follows prompts. + Higher guidance follows more closely, but will make transitions more + abrupt. Range is [0.0, 6.0]. */ + guidance?: number; + /** Beats per minute. Range is [60, 200]. */ + bpm?: number; + /** Density of sounds. Range is [0.0, 1.0]. */ + density?: number; + /** Brightness of the music. Range is [0.0, 1.0]. */ + brightness?: number; + /** Scale of the generated music. */ + scale?: Scale; + /** Whether the audio output should contain bass. */ + muteBass?: boolean; + /** Whether the audio output should contain drums. */ + muteDrums?: boolean; + /** Whether the audio output should contain only bass and drums. */ + onlyBassAndDrums?: boolean; + /** The mode of music generation. Default mode is QUALITY. */ + musicGenerationMode?: MusicGenerationMode; +} + +/** The playback control signal to apply to the music generation. */ +export declare enum LiveMusicPlaybackControl { + /** + * This value is unused. + */ + PLAYBACK_CONTROL_UNSPECIFIED = "PLAYBACK_CONTROL_UNSPECIFIED", + /** + * Start generating the music. + */ + PLAY = "PLAY", + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + PAUSE = "PAUSE", + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + STOP = "STOP", + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + RESET_CONTEXT = "RESET_CONTEXT" +} + +/** Server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. + Clients may choose to buffer and play it out in real time. + */ +export declare interface LiveMusicServerContent { + /** The audio chunks that the model has generated. */ + audioChunks?: AudioChunk[]; +} + +/** Response message for the LiveMusicClientMessage call. */ +export declare class LiveMusicServerMessage { + /** Message sent in response to a `LiveMusicClientSetup` message from the client. + Clients should wait for this message before sending any additional messages. */ + setupComplete?: LiveMusicServerSetupComplete; + /** Content generated by the model in response to client messages. */ + serverContent?: LiveMusicServerContent; + /** A prompt that was filtered with the reason. */ + filteredPrompt?: LiveMusicFilteredPrompt; + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk(): AudioChunk | undefined; +} + +/** Sent in response to a `LiveMusicClientSetup` message from the client. */ +export declare interface LiveMusicServerSetupComplete { +} + +/** + Represents a connection to the API. + + @experimental + */ +export declare class LiveMusicSession { + readonly conn: WebSocket_2; + private readonly apiClient; + constructor(conn: WebSocket_2, apiClient: ApiClient); + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + setWeightedPrompts(params: types.LiveMusicSetWeightedPromptsParameters): Promise; + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + setMusicGenerationConfig(params: types.LiveMusicSetConfigParameters): Promise; + private sendPlaybackControl; + /** + * Start the music stream. + * + * @experimental + */ + play(): void; + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause(): void; + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop(): void; + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext(): void; + /** + Terminates the WebSocket connection. + + @experimental + */ + close(): void; +} + +/** Parameters for setting config for the live music API. */ +export declare interface LiveMusicSetConfigParameters { + /** Configuration for music generation. */ + musicGenerationConfig: LiveMusicGenerationConfig; +} + +/** Parameters for setting weighted prompts for the live music API. */ +export declare interface LiveMusicSetWeightedPromptsParameters { + /** A map of text prompts to weights to use for the generation request. */ + weightedPrompts: WeightedPrompt[]; +} + +/** Prompts and config used for generating this audio chunk. */ +export declare interface LiveMusicSourceMetadata { + /** Weighted prompts for generating this audio chunk. */ + clientContent?: LiveMusicClientContent; + /** Music generation config for generating this audio chunk. */ + musicGenerationConfig?: LiveMusicGenerationConfig; +} + +/** Parameters for sending client content to the live API. */ +export declare interface LiveSendClientContentParameters { + /** Client content to send to the session. */ + turns?: ContentListUnion; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Parameters for sending realtime input to the live API. */ +export declare interface LiveSendRealtimeInputParameters { + /** Realtime input to send to the session. */ + media?: BlobImageUnion; + /** The realtime audio input stream. */ + audio?: Blob_2; + /** + Indicates that the audio stream has ended, e.g. because the microphone was + turned off. + + This should only be sent when automatic activity detection is enabled + (which is the default). + + The client can reopen the stream by sending an audio message. + */ + audioStreamEnd?: boolean; + /** The realtime video input stream. */ + video?: BlobImageUnion; + /** The realtime text input stream. */ + text?: string; + /** Marks the start of user activity. */ + activityStart?: ActivityStart; + /** Marks the end of user activity. */ + activityEnd?: ActivityEnd; +} + +/** Parameters for sending tool responses to the live API. */ +export declare class LiveSendToolResponseParameters { + /** Tool responses to send to the session. */ + functionResponses: FunctionResponse[] | FunctionResponse; +} + +/** Incremental server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. Clients + may choose to buffer and play it out in real time. + */ +export declare interface LiveServerContent { + /** The content that the model has generated as part of the current conversation with the user. */ + modelTurn?: Content; + /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */ + turnComplete?: boolean; + /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */ + interrupted?: boolean; + /** Metadata returned to client when grounding is enabled. */ + groundingMetadata?: GroundingMetadata; + /** If true, indicates that the model is done generating. When model is + interrupted while generating there will be no generation_complete message + in interrupted turn, it will go through interrupted > turn_complete. + When model assumes realtime playback there will be delay between + generation_complete and turn_complete that is caused by model + waiting for playback to finish. If true, indicates that the model + has finished generating all content. This is a signal to the client + that it can stop sending messages. */ + generationComplete?: boolean; + /** Input transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn. */ + inputTranscription?: Transcription; + /** Output transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn. + */ + outputTranscription?: Transcription; + /** Metadata related to url context retrieval tool. */ + urlContextMetadata?: UrlContextMetadata; +} + +/** Server will not be able to service client soon. */ +export declare interface LiveServerGoAway { + /** The remaining time before the connection will be terminated as ABORTED. The minimal time returned here is specified differently together with the rate limits for a given model. */ + timeLeft?: string; +} + +/** Response message for API call. */ +export declare class LiveServerMessage { + /** Sent in response to a `LiveClientSetup` message from the client. */ + setupComplete?: LiveServerSetupComplete; + /** Content generated by the model in response to client messages. */ + serverContent?: LiveServerContent; + /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ + toolCall?: LiveServerToolCall; + /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */ + toolCallCancellation?: LiveServerToolCallCancellation; + /** Usage metadata about model response(s). */ + usageMetadata?: UsageMetadata; + /** Server will disconnect soon. */ + goAway?: LiveServerGoAway; + /** Update of the session resumption state. */ + sessionResumptionUpdate?: LiveServerSessionResumptionUpdate; + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text(): string | undefined; + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data(): string | undefined; +} + +/** Update of the session resumption state. + + Only sent if `session_resumption` was set in the connection config. + */ +export declare interface LiveServerSessionResumptionUpdate { + /** New handle that represents state that can be resumed. Empty if `resumable`=false. */ + newHandle?: string; + /** True if session can be resumed at this point. It might be not possible to resume session at some points. In that case we send update empty new_handle and resumable=false. Example of such case could be model executing function calls or just generating. Resuming session (using previous session token) in such state will result in some data loss. */ + resumable?: boolean; + /** Index of last message sent by client that is included in state represented by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent` is set. + + Presence of this index allows users to transparently reconnect and avoid issue of losing some part of realtime audio input/video. If client wishes to temporarily disconnect (for example as result of receiving GoAway) they can do it without losing state by buffering messages sent since last `SessionResmumptionTokenUpdate`. This field will enable them to limit buffering (avoid keeping all requests in RAM). + + Note: This should not be used for when resuming a session at some time later -- in those cases partial audio and video frames arelikely not needed. */ + lastConsumedClientMessageIndex?: string; +} + +export declare interface LiveServerSetupComplete { + /** The session id of the live session. */ + sessionId?: string; +} + +/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ +export declare interface LiveServerToolCall { + /** The function call to be executed. */ + functionCalls?: FunctionCall[]; +} + +/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. + + If there were side-effects to those tool calls, clients may attempt to undo + the tool calls. This message occurs only in cases where the clients interrupt + server turns. + */ +export declare interface LiveServerToolCallCancellation { + /** The ids of the tool calls to be cancelled. */ + ids?: string[]; +} + +/** Logprobs Result */ +export declare interface LogprobsResult { + /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */ + chosenCandidates?: LogprobsResultCandidate[]; + /** Length = total number of decoding steps. */ + topCandidates?: LogprobsResultTopCandidates[]; +} + +/** Candidate for the logprobs token and score. */ +export declare interface LogprobsResultCandidate { + /** The candidate's log probability. */ + logProbability?: number; + /** The candidate's token string value. */ + token?: string; + /** The candidate's token id value. */ + tokenId?: number; +} + +/** Candidates with top log probabilities at each decoding step. */ +export declare interface LogprobsResultTopCandidates { + /** Sorted by log probability in descending order. */ + candidates?: LogprobsResultCandidate[]; +} + +/** Configuration for a Mask reference image. */ +export declare interface MaskReferenceConfig { + /** Prompts the model to generate a mask instead of you needing to + provide one (unless MASK_MODE_USER_PROVIDED is used). */ + maskMode?: MaskReferenceMode; + /** A list of up to 5 class ids to use for semantic segmentation. + Automatically creates an image mask based on specific objects. */ + segmentationClasses?: number[]; + /** Dilation percentage of the mask provided. + Float between 0 and 1. */ + maskDilation?: number; +} + +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +export declare class MaskReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the mask reference image. */ + config?: MaskReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the mask mode of a mask reference image. */ +export declare enum MaskReferenceMode { + MASK_MODE_DEFAULT = "MASK_MODE_DEFAULT", + MASK_MODE_USER_PROVIDED = "MASK_MODE_USER_PROVIDED", + MASK_MODE_BACKGROUND = "MASK_MODE_BACKGROUND", + MASK_MODE_FOREGROUND = "MASK_MODE_FOREGROUND", + MASK_MODE_SEMANTIC = "MASK_MODE_SEMANTIC" +} + +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +export declare function mcpToTool(...args: [...Client[], CallableToolConfig | Client]): CallableTool; + +/** Server content modalities. */ +export declare enum MediaModality { + /** + * The modality is unspecified. + */ + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + /** + * Plain text. + */ + TEXT = "TEXT", + /** + * Images. + */ + IMAGE = "IMAGE", + /** + * Video. + */ + VIDEO = "VIDEO", + /** + * Audio. + */ + AUDIO = "AUDIO", + /** + * Document, e.g. PDF. + */ + DOCUMENT = "DOCUMENT" +} + +/** The media resolution to use. */ +export declare enum MediaResolution { + /** + * Media resolution has not been set + */ + MEDIA_RESOLUTION_UNSPECIFIED = "MEDIA_RESOLUTION_UNSPECIFIED", + /** + * Media resolution set to low (64 tokens). + */ + MEDIA_RESOLUTION_LOW = "MEDIA_RESOLUTION_LOW", + /** + * Media resolution set to medium (256 tokens). + */ + MEDIA_RESOLUTION_MEDIUM = "MEDIA_RESOLUTION_MEDIUM", + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MEDIA_RESOLUTION_HIGH = "MEDIA_RESOLUTION_HIGH" +} + +/** Server content modalities. */ +export declare enum Modality { + /** + * The modality is unspecified. + */ + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + /** + * Indicates the model should return text + */ + TEXT = "TEXT", + /** + * Indicates the model should return images. + */ + IMAGE = "IMAGE", + /** + * Indicates the model should return audio. + */ + AUDIO = "AUDIO" +} + +/** Represents token counting info for a single modality. */ +export declare interface ModalityTokenCount { + /** The modality associated with this token count. */ + modality?: MediaModality; + /** Number of tokens. */ + tokenCount?: number; +} + +/** The mode of the predictor to be used in dynamic retrieval. */ +export declare enum Mode { + /** + * Always trigger retrieval. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Run retrieval only when system decides it is necessary. + */ + MODE_DYNAMIC = "MODE_DYNAMIC" +} + +/** A trained machine learning model. */ +export declare interface Model { + /** Resource name of the model. */ + name?: string; + /** Display name of the model. */ + displayName?: string; + /** Description of the model. */ + description?: string; + /** Version ID of the model. A new version is committed when a new + model version is uploaded or trained under an existing model ID. The + version ID is an auto-incrementing decimal number in string + representation. */ + version?: string; + /** List of deployed models created from this base model. Note that a + model could have been deployed to endpoints in different locations. */ + endpoints?: Endpoint[]; + /** Labels with user-defined metadata to organize your models. */ + labels?: Record; + /** Information about the tuned model from the base model. */ + tunedModelInfo?: TunedModelInfo; + /** The maximum number of input tokens that the model can handle. */ + inputTokenLimit?: number; + /** The maximum number of output tokens that the model can generate. */ + outputTokenLimit?: number; + /** List of actions that are supported by the model. */ + supportedActions?: string[]; + /** The default checkpoint id of a model version. + */ + defaultCheckpointId?: string; + /** The checkpoints of the model. */ + checkpoints?: Checkpoint[]; +} + +export declare class Models extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + generateContent: (params: types.GenerateContentParameters) => Promise; + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + private maybeMoveToResponseJsonSchem; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + generateContentStream: (params: types.GenerateContentParameters) => Promise>; + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + private processParamsMaybeAddMcpUsage; + private initAfcToolsMap; + private processAfcStream; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + generateImages: (params: types.GenerateImagesParameters) => Promise; + list: (params?: types.ListModelsParameters) => Promise>; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + editImage: (params: types.EditImageParameters) => Promise; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + upscaleImage: (params: types.UpscaleImageParameters) => Promise; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + generateVideos: (params: types.GenerateVideosParameters) => Promise; + private generateContentInternal; + private generateContentStreamInternal; + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + embedContent(params: types.EmbedContentParameters): Promise; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + private generateImagesInternal; + private editImageInternal; + private upscaleImageInternal; + /** + * Recontextualizes an image. + * + * There are two types of recontextualization currently supported: + * 1) Imagen Product Recontext - Generate images of products in new scenes + * and contexts. + * 2) Virtual Try-On: Generate images of persons modeling fashion products. + * + * @param params - The parameters for recontextualizing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response1 = await ai.models.recontextImage({ + * model: 'imagen-product-recontext-preview-06-30', + * source: { + * prompt: 'In a modern kitchen setting.', + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response1?.generatedImages?.[0]?.image?.imageBytes); + * + * const response2 = await ai.models.recontextImage({ + * model: 'virtual-try-on-preview-08-04', + * source: { + * personImage: personImage, + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response2?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + recontextImage(params: types.RecontextImageParameters): Promise; + /** + * Segments an image, creating a mask of a specified area. + * + * @param params - The parameters for segmenting an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.segmentImage({ + * model: 'image-segmentation-001', + * source: { + * image: image, + * }, + * config: { + * mode: 'foreground', + * }, + * }); + * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes); + * ``` + */ + segmentImage(params: types.SegmentImageParameters): Promise; + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + get(params: types.GetModelParameters): Promise; + private listInternal; + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + update(params: types.UpdateModelParameters): Promise; + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + delete(params: types.DeleteModelParameters): Promise; + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + countTokens(params: types.CountTokensParameters): Promise; + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + computeTokens(params: types.ComputeTokensParameters): Promise; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + private generateVideosInternal; +} + +/** Config for model selection. */ +export declare interface ModelSelectionConfig { + /** Options for feature selection preference. */ + featureSelectionPreference?: FeatureSelectionPreference; +} + +/** The configuration for the multi-speaker setup. */ +export declare interface MultiSpeakerVoiceConfig { + /** The configuration for the speaker to use. */ + speakerVoiceConfigs?: SpeakerVoiceConfig[]; +} + +/** The mode of music generation. */ +export declare enum MusicGenerationMode { + /** + * Rely on the server default generation mode. + */ + MUSIC_GENERATION_MODE_UNSPECIFIED = "MUSIC_GENERATION_MODE_UNSPECIFIED", + /** + * Steer text prompts to regions of latent space with higher quality + music. + */ + QUALITY = "QUALITY", + /** + * Steer text prompts to regions of latent space with a larger + diversity of music. + */ + DIVERSITY = "DIVERSITY", + /** + * Steer text prompts to regions of latent space more likely to + generate music with vocals. + */ + VOCALIZATION = "VOCALIZATION" +} + +/** A long-running operation. */ +export declare interface Operation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The response if the operation is successful. */ + response?: T; + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI, }: OperationFromAPIResponseParameters): Operation; +} + +/** Parameters of the fromAPIResponse method of the Operation class. */ +export declare interface OperationFromAPIResponseParameters { + /** The API response to be converted to an Operation. */ + apiResponse: Record; + /** Whether the API response is from Vertex AI. */ + isVertexAI: boolean; +} + +/** Parameters for the get method of the operations module. */ +export declare interface OperationGetParameters> { + /** The operation to be retrieved. */ + operation: U; + /** Used to override the default configuration. */ + config?: GetOperationConfig; +} + +export declare class Operations extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + getVideosOperation(parameters: types.OperationGetParameters): Promise; + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + get>(parameters: types.OperationGetParameters): Promise>; + private getVideosOperationInternal; + private fetchPredictVideosOperationInternal; +} + +/** Required. Outcome of the code execution. */ +export declare enum Outcome { + /** + * Unspecified status. This value should not be used. + */ + OUTCOME_UNSPECIFIED = "OUTCOME_UNSPECIFIED", + /** + * Code execution completed successfully. + */ + OUTCOME_OK = "OUTCOME_OK", + /** + * Code execution finished but with a failure. `stderr` should contain the reason. + */ + OUTCOME_FAILED = "OUTCOME_FAILED", + /** + * Code execution ran for too long, and was cancelled. There may or may not be a partial output present. + */ + OUTCOME_DEADLINE_EXCEEDED = "OUTCOME_DEADLINE_EXCEEDED" +} + +export declare enum PagedItem { + PAGED_ITEM_BATCH_JOBS = "batchJobs", + PAGED_ITEM_MODELS = "models", + PAGED_ITEM_TUNING_JOBS = "tuningJobs", + PAGED_ITEM_FILES = "files", + PAGED_ITEM_CACHED_CONTENTS = "cachedContents" +} + +declare interface PagedItemConfig { + config?: { + pageToken?: string; + pageSize?: number; + }; +} + +declare interface PagedItemResponse { + nextPageToken?: string; + sdkHttpResponse?: types.HttpResponse; + batchJobs?: T[]; + models?: T[]; + tuningJobs?: T[]; + files?: T[]; + cachedContents?: T[]; +} + +/** + * Pager class for iterating through paginated results. + */ +export declare class Pager implements AsyncIterable { + private nameInternal; + private pageInternal; + private paramsInternal; + private pageInternalSize; + private sdkHttpResponseInternal?; + protected requestInternal: (params: PagedItemConfig) => Promise>; + protected idxInternal: number; + constructor(name: PagedItem, request: (params: PagedItemConfig) => Promise>, response: PagedItemResponse, params: PagedItemConfig); + private init; + private initNextPage; + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page(): T[]; + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name(): PagedItem; + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize(): number; + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse(): types.HttpResponse | undefined; + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params(): PagedItemConfig; + /** + * Returns the total number of items in the current page. + */ + get pageLength(): number; + /** + * Returns the item at the given index. + */ + getItem(index: number): T; + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator](): AsyncIterator; + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + nextPage(): Promise; + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage(): boolean; +} + +/** A datatype containing media content. + + Exactly one field within a Part should be set, representing the specific type + of content being conveyed. Using multiple fields within the same `Part` + instance is considered invalid. + */ +export declare interface Part { + /** Metadata for a given video. */ + videoMetadata?: VideoMetadata; + /** Indicates if the part is thought from the model. */ + thought?: boolean; + /** Optional. Inlined bytes data. */ + inlineData?: Blob_2; + /** Optional. URI based data. */ + fileData?: FileData; + /** An opaque signature for the thought so it can be reused in subsequent requests. + * @remarks Encoded as base64 string. */ + thoughtSignature?: string; + /** Optional. Result of executing the [ExecutableCode]. */ + codeExecutionResult?: CodeExecutionResult; + /** Optional. Code generated by the model that is meant to be executed. */ + executableCode?: ExecutableCode; + /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */ + functionCall?: FunctionCall; + /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */ + functionResponse?: FunctionResponse; + /** Optional. Text part (can be code). */ + text?: string; +} + +export declare type PartListUnion = PartUnion[] | PartUnion; + +/** Tuning spec for Partner models. */ +export declare interface PartnerModelTuningSpec { + /** Hyperparameters for tuning. The accepted hyper_parameters and their valid range of values will differ depending on the base model. */ + hyperParameters?: Record; + /** Required. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDatasetUri?: string; + /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */ + validationDatasetUri?: string; +} + +export declare type PartUnion = Part | string; + +/** Enum that controls the generation of people. */ +export declare enum PersonGeneration { + /** + * Block generation of images of people. + */ + DONT_ALLOW = "DONT_ALLOW", + /** + * Generate images of adults, but not children. + */ + ALLOW_ADULT = "ALLOW_ADULT", + /** + * Generate images that include adults and children. + */ + ALLOW_ALL = "ALLOW_ALL" +} + +/** The configuration for the prebuilt speaker to use. */ +export declare interface PrebuiltVoiceConfig { + /** The name of the prebuilt voice to use. */ + voiceName?: string; +} + +/** Statistics computed for datasets used for preference optimization. */ +export declare interface PreferenceOptimizationDataStats { + /** Output only. Dataset distributions for scores variance per example. */ + scoreVariancePerExampleDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for scores. */ + scoresDistribution?: DatasetDistribution; + /** Output only. Number of billable tokens in the tuning dataset. */ + totalBillableTokenCount?: string; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user examples in the training dataset. */ + userDatasetExamples?: GeminiPreferenceExample[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: DatasetDistribution; +} + +/** A pre-tuned model for continuous tuning. */ +export declare interface PreTunedModel { + /** Output only. The name of the base model this PreTunedModel was tuned from. */ + baseModel?: string; + /** Optional. The source checkpoint id. If not specified, the default checkpoint will be used. */ + checkpointId?: string; + /** The resource name of the Model. E.g., a model resource name with a specified version id or alias: `projects/{project}/locations/{location}/models/{model}@{version_id}` `projects/{project}/locations/{location}/models/{model}@{alias}` Or, omit the version id to use the default version: `projects/{project}/locations/{location}/models/{model}` */ + tunedModelName?: string; +} + +/** Config for proactivity features. */ +export declare interface ProactivityConfig { + /** If enabled, the model can reject responding to the last prompt. For + example, this allows the model to ignore out of context speech or to stay + silent if the user did not make a request, yet. */ + proactiveAudio?: boolean; +} + +/** An image of the product. */ +export declare interface ProductImage { + /** An image of the product to be recontextualized. */ + productImage?: Image_2; +} + +/** A RagChunk includes the content of a chunk of a RagFile, and associated metadata. */ +export declare interface RagChunk { + /** If populated, represents where the chunk starts and ends in the document. */ + pageSpan?: RagChunkPageSpan; + /** The content of the chunk. */ + text?: string; +} + +/** Represents where the chunk starts and ends in the document. */ +export declare interface RagChunkPageSpan { + /** Page where chunk starts in the document. Inclusive. 1-indexed. */ + firstPage?: number; + /** Page where chunk ends in the document. Inclusive. 1-indexed. */ + lastPage?: number; +} + +/** Specifies the context retrieval config. */ +export declare interface RagRetrievalConfig { + /** Optional. Config for filters. */ + filter?: RagRetrievalConfigFilter; + /** Optional. Config for Hybrid Search. */ + hybridSearch?: RagRetrievalConfigHybridSearch; + /** Optional. Config for ranking and reranking. */ + ranking?: RagRetrievalConfigRanking; + /** Optional. The number of contexts to retrieve. */ + topK?: number; +} + +/** Config for filters. */ +export declare interface RagRetrievalConfigFilter { + /** Optional. String for metadata filtering. */ + metadataFilter?: string; + /** Optional. Only returns contexts with vector distance smaller than the threshold. */ + vectorDistanceThreshold?: number; + /** Optional. Only returns contexts with vector similarity larger than the threshold. */ + vectorSimilarityThreshold?: number; +} + +/** Config for Hybrid Search. */ +export declare interface RagRetrievalConfigHybridSearch { + /** Optional. Alpha value controls the weight between dense and sparse vector search results. The range is [0, 1], while 0 means sparse vector search only and 1 means dense vector search only. The default value is 0.5 which balances sparse and dense vector search equally. */ + alpha?: number; +} + +/** Config for ranking and reranking. */ +export declare interface RagRetrievalConfigRanking { + /** Optional. Config for LlmRanker. */ + llmRanker?: RagRetrievalConfigRankingLlmRanker; + /** Optional. Config for Rank Service. */ + rankService?: RagRetrievalConfigRankingRankService; +} + +/** Config for LlmRanker. */ +export declare interface RagRetrievalConfigRankingLlmRanker { + /** Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */ + modelName?: string; +} + +/** Config for Rank Service. */ +export declare interface RagRetrievalConfigRankingRankService { + /** Optional. The model name of the rank service. Format: `semantic-ranker-512@latest` */ + modelName?: string; +} + +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +export declare class RawReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface RealtimeInputConfig { + /** If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals. */ + automaticActivityDetection?: AutomaticActivityDetection; + /** Defines what effect activity has. */ + activityHandling?: ActivityHandling; + /** Defines which input is included in the user's turn. */ + turnCoverage?: TurnCoverage; +} + +/** Configuration for recontextualizing an image. */ +export declare interface RecontextImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Number of images to generate. */ + numberOfImages?: number; + /** The number of sampling steps. A higher value has better image + quality, while a lower value has better latency. */ + baseSteps?: number; + /** Cloud Storage URI used to store the generated images. */ + outputGcsUri?: string; + /** Random seed for image generation. */ + seed?: number; + /** Filter level for safety filtering. */ + safetyFilterLevel?: SafetyFilterLevel; + /** Whether allow to generate person images, and restrict to specific + ages. */ + personGeneration?: PersonGeneration; + /** MIME type of the generated image. */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). */ + outputCompressionQuality?: number; + /** Whether to use the prompt rewriting logic. */ + enhancePrompt?: boolean; +} + +/** The parameters for recontextualizing an image. */ +export declare interface RecontextImageParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** A set of source input(s) for image recontextualization. */ + source: RecontextImageSource; + /** Configuration for image recontextualization. */ + config?: RecontextImageConfig; +} + +/** The output images response. */ +export declare class RecontextImageResponse { + /** List of generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** A set of source input(s) for image recontextualization. */ +export declare interface RecontextImageSource { + /** A text prompt for guiding the model during image + recontextualization. Not supported for Virtual Try-On. */ + prompt?: string; + /** Image of the person or subject who will be wearing the + product(s). */ + personImage?: Image_2; + /** A list of product images. */ + productImages?: ProductImage[]; +} + +export declare type ReferenceImage = RawReferenceImage | MaskReferenceImage | ControlReferenceImage | StyleReferenceImage | SubjectReferenceImage; + +/** Private class that represents a Reference image that is sent to API. */ +declare interface ReferenceImageAPIInternal { + /** The reference image for the editing operation. */ + referenceImage?: types.Image; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the mask reference image. */ + maskImageConfig?: types.MaskReferenceConfig; + /** Configuration for the control reference image. */ + controlImageConfig?: types.ControlReferenceConfig; + /** Configuration for the style reference image. */ + styleImageConfig?: types.StyleReferenceConfig; + /** Configuration for the subject reference image. */ + subjectImageConfig?: types.SubjectReferenceConfig; +} + +/** Represents a recorded session. */ +export declare interface ReplayFile { + replayId?: string; + interactions?: ReplayInteraction[]; +} + +/** Represents a single interaction, request and response in a replay. */ +export declare interface ReplayInteraction { + request?: ReplayRequest; + response?: ReplayResponse; +} + +/** Represents a single request in a replay. */ +export declare interface ReplayRequest { + method?: string; + url?: string; + headers?: Record; + bodySegments?: Record[]; +} + +/** Represents a single response in a replay. */ +export declare class ReplayResponse { + statusCode?: number; + headers?: Record; + bodySegments?: Record[]; + sdkResponseSegments?: Record[]; +} + +/** Defines a retrieval tool that model can call to access external knowledge. */ +export declare interface Retrieval { + /** Optional. Deprecated. This option is no longer supported. */ + disableAttribution?: boolean; + /** Use data source powered by external API for grounding. */ + externalApi?: ExternalApi; + /** Set to use data source powered by Vertex AI Search. */ + vertexAiSearch?: VertexAISearch; + /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */ + vertexRagStore?: VertexRagStore; +} + +/** Retrieval config. + */ +export declare interface RetrievalConfig { + /** Optional. The location of the user. */ + latLng?: LatLng; + /** The language code of the user. */ + languageCode?: string; +} + +/** Metadata related to retrieval in the grounding flow. */ +export declare interface RetrievalMetadata { + /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */ + googleSearchDynamicRetrievalScore?: number; +} + +/** Safety attributes of a GeneratedImage or the user-provided prompt. */ +export declare interface SafetyAttributes { + /** List of RAI categories. + */ + categories?: string[]; + /** List of scores of each categories. + */ + scores?: number[]; + /** Internal use only. + */ + contentType?: string; +} + +/** Enum that controls the safety filter level for objectionable content. */ +export declare enum SafetyFilterLevel { + BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", + BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", + BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", + BLOCK_NONE = "BLOCK_NONE" +} + +/** Safety rating corresponding to the generated content. */ +export declare interface SafetyRating { + /** Output only. Indicates whether the content was filtered out because of this rating. */ + blocked?: boolean; + /** Output only. Harm category. */ + category?: HarmCategory; + /** Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If minors are detected in the output image, the threshold of each safety category will be overwritten if user sets a lower threshold. */ + overwrittenThreshold?: HarmBlockThreshold; + /** Output only. Harm probability levels in the content. */ + probability?: HarmProbability; + /** Output only. Harm probability score. */ + probabilityScore?: number; + /** Output only. Harm severity levels in the content. */ + severity?: HarmSeverity; + /** Output only. Harm severity score. */ + severityScore?: number; +} + +/** Safety settings. */ +export declare interface SafetySetting { + /** Determines if the harm block method uses probability or probability + and severity scores. */ + method?: HarmBlockMethod; + /** Required. Harm category. */ + category?: HarmCategory; + /** Required. The harm block threshold. */ + threshold?: HarmBlockThreshold; +} + +/** Scale of the generated music. */ +export declare enum Scale { + /** + * Default value. This value is unused. + */ + SCALE_UNSPECIFIED = "SCALE_UNSPECIFIED", + /** + * C major or A minor. + */ + C_MAJOR_A_MINOR = "C_MAJOR_A_MINOR", + /** + * Db major or Bb minor. + */ + D_FLAT_MAJOR_B_FLAT_MINOR = "D_FLAT_MAJOR_B_FLAT_MINOR", + /** + * D major or B minor. + */ + D_MAJOR_B_MINOR = "D_MAJOR_B_MINOR", + /** + * Eb major or C minor + */ + E_FLAT_MAJOR_C_MINOR = "E_FLAT_MAJOR_C_MINOR", + /** + * E major or Db minor. + */ + E_MAJOR_D_FLAT_MINOR = "E_MAJOR_D_FLAT_MINOR", + /** + * F major or D minor. + */ + F_MAJOR_D_MINOR = "F_MAJOR_D_MINOR", + /** + * Gb major or Eb minor. + */ + G_FLAT_MAJOR_E_FLAT_MINOR = "G_FLAT_MAJOR_E_FLAT_MINOR", + /** + * G major or E minor. + */ + G_MAJOR_E_MINOR = "G_MAJOR_E_MINOR", + /** + * Ab major or F minor. + */ + A_FLAT_MAJOR_F_MINOR = "A_FLAT_MAJOR_F_MINOR", + /** + * A major or Gb minor. + */ + A_MAJOR_G_FLAT_MINOR = "A_MAJOR_G_FLAT_MINOR", + /** + * Bb major or G minor. + */ + B_FLAT_MAJOR_G_MINOR = "B_FLAT_MAJOR_G_MINOR", + /** + * B major or Ab minor. + */ + B_MAJOR_A_FLAT_MINOR = "B_MAJOR_A_FLAT_MINOR" +} + +/** Schema is used to define the format of input/output data. + + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may + be added in the future as needed. + */ +export declare interface Schema { + /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */ + anyOf?: Schema[]; + /** Optional. Default value of the data. */ + default?: unknown; + /** Optional. The description of the data. */ + description?: string; + /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:["101", "201", "301"]} */ + enum?: string[]; + /** Optional. Example of the object. Will only populated when the object is the root. */ + example?: unknown; + /** Optional. The format of the data. Supported formats: for NUMBER type: "float", "double" for INTEGER type: "int32", "int64" for STRING type: "email", "byte", etc */ + format?: string; + /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */ + items?: Schema; + /** Optional. Maximum number of the elements for Type.ARRAY. */ + maxItems?: string; + /** Optional. Maximum length of the Type.STRING */ + maxLength?: string; + /** Optional. Maximum number of the properties for Type.OBJECT. */ + maxProperties?: string; + /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */ + maximum?: number; + /** Optional. Minimum number of the elements for Type.ARRAY. */ + minItems?: string; + /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */ + minLength?: string; + /** Optional. Minimum number of the properties for Type.OBJECT. */ + minProperties?: string; + /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */ + minimum?: number; + /** Optional. Indicates if the value may be null. */ + nullable?: boolean; + /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */ + pattern?: string; + /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */ + properties?: Record; + /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */ + propertyOrdering?: string[]; + /** Optional. Required properties of Type.OBJECT. */ + required?: string[]; + /** Optional. The title of the Schema. */ + title?: string; + /** Optional. The type of the data. */ + type?: Type; +} + +export declare type SchemaUnion = Schema | unknown; + +/** An image mask representing a brush scribble. */ +export declare interface ScribbleImage { + /** The brush scribble to guide segmentation. Valid for the interactive mode. */ + image?: Image_2; +} + +/** Google search entry point. */ +export declare interface SearchEntryPoint { + /** Optional. Web content snippet that can be embedded in a web page or an app webview. */ + renderedContent?: string; + /** Optional. Base64 encoded JSON representing array of tuple. + * @remarks Encoded as base64 string. */ + sdkBlob?: string; +} + +/** Segment of the content. */ +export declare interface Segment { + /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */ + endIndex?: number; + /** Output only. The index of a Part object within its parent Content object. */ + partIndex?: number; + /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */ + startIndex?: number; + /** Output only. The text corresponding to the segment from the response. */ + text?: string; +} + +/** Configuration for segmenting an image. */ +export declare interface SegmentImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The segmentation mode to use. */ + mode?: SegmentMode; + /** The maximum number of predictions to return up to, by top + confidence score. */ + maxPredictions?: number; + /** The confidence score threshold for the detections as a decimal + value. Only predictions with a confidence score higher than this + threshold will be returned. */ + confidenceThreshold?: number; + /** A decimal value representing how much dilation to apply to the + masks. 0 for no dilation. 1.0 means the masked area covers the whole + image. */ + maskDilation?: number; + /** The binary color threshold to apply to the masks. The threshold + can be set to a decimal value between 0 and 255 non-inclusive. + Set to -1 for no binary color thresholding. */ + binaryColorThreshold?: number; +} + +/** The parameters for segmenting an image. */ +export declare interface SegmentImageParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** A set of source input(s) for image segmentation. */ + source: SegmentImageSource; + /** Configuration for image segmentation. */ + config?: SegmentImageConfig; +} + +/** The output images response. */ +export declare class SegmentImageResponse { + /** List of generated image masks. + */ + generatedMasks?: GeneratedImageMask[]; +} + +/** A set of source input(s) for image segmentation. */ +export declare interface SegmentImageSource { + /** A text prompt for guiding the model during image segmentation. + Required for prompt mode and semantic mode, disallowed for other modes. */ + prompt?: string; + /** The image to be segmented. */ + image?: Image_2; + /** The brush scribble to guide segmentation. + Required for the interactive mode, disallowed for other modes. */ + scribbleImage?: ScribbleImage; +} + +/** Enum that represents the segmentation mode. */ +export declare enum SegmentMode { + FOREGROUND = "FOREGROUND", + BACKGROUND = "BACKGROUND", + PROMPT = "PROMPT", + SEMANTIC = "SEMANTIC", + INTERACTIVE = "INTERACTIVE" +} + +/** Parameters for sending a message within a chat session. + + These parameters are used with the `chat.sendMessage()` method. + */ +export declare interface SendMessageParameters { + /** The message to send to the model. + + The SDK will combine all parts into a single 'user' content to send to + the model. + */ + message: PartListUnion; + /** Config for this specific request. + + Please note that the per-request config does not change the chat level + config, nor inherit from it. If you intend to use some values from the + chat's default config, you must explicitly copy them into this per-request + config. + */ + config?: GenerateContentConfig; +} + +/** + Represents a connection to the API. + + @experimental + */ +export declare class Session { + readonly conn: WebSocket_2; + private readonly apiClient; + constructor(conn: WebSocket_2, apiClient: ApiClient); + private tLiveClientContent; + private tLiveClienttToolResponse; + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params: types.LiveSendClientContentParameters): void; + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params: types.LiveSendRealtimeInputParameters): void; + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params: types.LiveSendToolResponseParameters): void; + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close(): void; +} + +/** Configuration of session resumption mechanism. + + Included in `LiveConnectConfig.session_resumption`. If included server + will send `LiveServerSessionResumptionUpdate` messages. + */ +export declare interface SessionResumptionConfig { + /** Session resumption handle of previous session (session to restore). + + If not present new session will be started. */ + handle?: string; + /** If set the server will send `last_consumed_client_message_index` in the `session_resumption_update` messages to allow for transparent reconnections. */ + transparent?: boolean; +} + +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +export declare function setDefaultBaseUrls(baseUrlParams: BaseUrlParameters): void; + +/** Context window will be truncated by keeping only suffix of it. + + Context window will always be cut at start of USER role turn. System + instructions and `BidiGenerateContentSetup.prefix_turns` will not be + subject to the sliding window mechanism, they will always stay at the + beginning of context window. + */ +export declare interface SlidingWindow { + /** Session reduction target -- how many tokens we should keep. Window shortening operation has some latency costs, so we should avoid running it on every turn. Should be < trigger_tokens. If not set, trigger_tokens/2 is assumed. */ + targetTokens?: string; +} + +/** The configuration for the speaker to use. */ +export declare interface SpeakerVoiceConfig { + /** The name of the speaker to use. Should be the same as in the + prompt. */ + speaker?: string; + /** The configuration for the voice to use. */ + voiceConfig?: VoiceConfig; +} + +/** The speech generation configuration. */ +export declare interface SpeechConfig { + /** The configuration for the speaker to use. + */ + voiceConfig?: VoiceConfig; + /** The configuration for the multi-speaker setup. + It is mutually exclusive with the voice_config field. + */ + multiSpeakerVoiceConfig?: MultiSpeakerVoiceConfig; + /** Language code (ISO 639. e.g. en-US) for the speech synthesization. + Only available for Live API. + */ + languageCode?: string; +} + +export declare type SpeechConfigUnion = SpeechConfig | string; + +/** Start of speech sensitivity. */ +export declare enum StartSensitivity { + /** + * The default is START_SENSITIVITY_LOW. + */ + START_SENSITIVITY_UNSPECIFIED = "START_SENSITIVITY_UNSPECIFIED", + /** + * Automatic detection will detect the start of speech more often. + */ + START_SENSITIVITY_HIGH = "START_SENSITIVITY_HIGH", + /** + * Automatic detection will detect the start of speech less often. + */ + START_SENSITIVITY_LOW = "START_SENSITIVITY_LOW" +} + +/** Configuration for a Style reference image. */ +export declare interface StyleReferenceConfig { + /** A text description of the style to use for the generated image. */ + styleDescription?: string; +} + +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +export declare class StyleReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the style reference image. */ + config?: StyleReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Configuration for a Subject reference image. */ +export declare interface SubjectReferenceConfig { + /** The subject type of a subject reference image. */ + subjectType?: SubjectReferenceType; + /** Subject description for the image. */ + subjectDescription?: string; +} + +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +export declare class SubjectReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the subject reference image. */ + config?: SubjectReferenceConfig; + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the subject type of a subject reference image. */ +export declare enum SubjectReferenceType { + SUBJECT_TYPE_DEFAULT = "SUBJECT_TYPE_DEFAULT", + SUBJECT_TYPE_PERSON = "SUBJECT_TYPE_PERSON", + SUBJECT_TYPE_ANIMAL = "SUBJECT_TYPE_ANIMAL", + SUBJECT_TYPE_PRODUCT = "SUBJECT_TYPE_PRODUCT" +} + +/** Hyperparameters for SFT. */ +export declare interface SupervisedHyperParameters { + /** Optional. Adapter size for tuning. */ + adapterSize?: AdapterSize; + /** Optional. Batch size for tuning. This feature is only available for open source models. */ + batchSize?: string; + /** Optional. Number of complete passes the model makes over the entire training dataset during training. */ + epochCount?: string; + /** Optional. Learning rate for tuning. Mutually exclusive with `learning_rate_multiplier`. This feature is only available for open source models. */ + learningRate?: number; + /** Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with `learning_rate`. This feature is only available for 1P models. */ + learningRateMultiplier?: number; +} + +/** Dataset distribution for Supervised Tuning. */ +export declare interface SupervisedTuningDatasetDistribution { + /** Output only. Sum of a given population of values that are billable. */ + billableSum?: string; + /** Output only. Defines the histogram bucket. */ + buckets?: SupervisedTuningDatasetDistributionDatasetBucket[]; + /** Output only. The maximum of the population values. */ + max?: number; + /** Output only. The arithmetic mean of the values in the population. */ + mean?: number; + /** Output only. The median of the values in the population. */ + median?: number; + /** Output only. The minimum of the population values. */ + min?: number; + /** Output only. The 5th percentile of the values in the population. */ + p5?: number; + /** Output only. The 95th percentile of the values in the population. */ + p95?: number; + /** Output only. Sum of a given population of values. */ + sum?: string; +} + +/** Dataset bucket used to create a histogram for the distribution given a population of values. */ +export declare interface SupervisedTuningDatasetDistributionDatasetBucket { + /** Output only. Number of values in the bucket. */ + count?: number; + /** Output only. Left bound of the bucket. */ + left?: number; + /** Output only. Right bound of the bucket. */ + right?: number; +} + +/** Tuning data statistics for Supervised Tuning. */ +export declare interface SupervisedTuningDataStats { + /** Output only. For each index in `truncated_example_indices`, the user-facing reason why the example was dropped. */ + droppedExampleReasons?: string[]; + /** Output only. Number of billable characters in the tuning dataset. */ + totalBillableCharacterCount?: string; + /** Output only. Number of billable tokens in the tuning dataset. */ + totalBillableTokenCount?: string; + /** Output only. The number of examples in the dataset that have been dropped. An example can be dropped for reasons including: too many tokens, contains an invalid image, contains too many images, etc. */ + totalTruncatedExampleCount?: string; + /** Output only. Number of tuning characters in the tuning dataset. */ + totalTuningCharacterCount?: string; + /** Output only. A partial sample of the indices (starting from 1) of the dropped examples. */ + truncatedExampleIndices?: string[]; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user messages in the training dataset uri. */ + userDatasetExamples?: Content[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: SupervisedTuningDatasetDistribution; + /** Output only. Dataset distributions for the messages per example. */ + userMessagePerExampleDistribution?: SupervisedTuningDatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: SupervisedTuningDatasetDistribution; +} + +/** Tuning Spec for Supervised Tuning for first party models. */ +export declare interface SupervisedTuningSpec { + /** Optional. If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. Default is false. */ + exportLastCheckpointOnly?: boolean; + /** Optional. Hyperparameters for SFT. */ + hyperParameters?: SupervisedHyperParameters; + /** Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */ + trainingDatasetUri?: string; + /** Tuning mode. */ + tuningMode?: TuningMode; + /** Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */ + validationDatasetUri?: string; +} + +export declare interface TestTableFile { + comment?: string; + testMethod?: string; + parameterNames?: string[]; + testTable?: TestTableItem[]; +} + +export declare interface TestTableItem { + /** The name of the test. This is used to derive the replay id. */ + name?: string; + /** The parameters to the test. Use pydantic models. */ + parameters?: Record; + /** Expects an exception for MLDev matching the string. */ + exceptionIfMldev?: string; + /** Expects an exception for Vertex matching the string. */ + exceptionIfVertex?: string; + /** Use if you don't want to use the default replay id which is derived from the test name. */ + overrideReplayId?: string; + /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */ + hasUnion?: boolean; + /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */ + skipInApiMode?: string; + /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */ + ignoreKeys?: string[]; +} + +/** The thinking features configuration. */ +export declare interface ThinkingConfig { + /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available. + */ + includeThoughts?: boolean; + /** Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent. + */ + thinkingBudget?: number; +} + +export declare class Tokens extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + create(params: types.CreateAuthTokenParameters): Promise; +} + +/** Tokens info with a list of tokens and the corresponding list of token ids. */ +export declare interface TokensInfo { + /** Optional. Optional fields for the role from the corresponding Content. */ + role?: string; + /** A list of token ids from the input. */ + tokenIds?: string[]; + /** A list of tokens from the input. + * @remarks Encoded as base64 string. */ + tokens?: string[]; +} + +/** Tool details of a tool that the model may use to generate a response. */ +export declare interface Tool { + /** List of function declarations that the tool supports. */ + functionDeclarations?: FunctionDeclaration[]; + /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */ + retrieval?: Retrieval; + /** Optional. Google Search tool type. Specialized retrieval tool + that is powered by Google Search. */ + googleSearch?: GoogleSearch; + /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */ + googleSearchRetrieval?: GoogleSearchRetrieval; + /** Optional. Enterprise web search tool type. Specialized retrieval + tool that is powered by Vertex AI Search and Sec4 compliance. */ + enterpriseWebSearch?: EnterpriseWebSearch; + /** Optional. Google Maps tool type. Specialized retrieval tool + that is powered by Google Maps. */ + googleMaps?: GoogleMaps; + /** Optional. Tool to support URL context retrieval. */ + urlContext?: UrlContext; + /** Optional. Tool to support the model interacting directly with the + computer. If enabled, it automatically populates computer-use specific + Function Declarations. */ + computerUse?: ToolComputerUse; + /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. */ + codeExecution?: ToolCodeExecution; +} + +/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */ +export declare interface ToolCodeExecution { +} + +/** Tool to support computer use. */ +export declare interface ToolComputerUse { + /** Required. The environment being operated. */ + environment?: Environment; +} + +/** Tool config. + + This config is shared for all tools provided in the request. + */ +export declare interface ToolConfig { + /** Optional. Function calling config. */ + functionCallingConfig?: FunctionCallingConfig; + /** Optional. Retrieval config. */ + retrievalConfig?: RetrievalConfig; +} + +export declare type ToolListUnion = ToolUnion[]; + +export declare type ToolUnion = Tool | CallableTool; + +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +export declare enum TrafficType { + /** + * Unspecified request traffic type. + */ + TRAFFIC_TYPE_UNSPECIFIED = "TRAFFIC_TYPE_UNSPECIFIED", + /** + * Type for Pay-As-You-Go traffic. + */ + ON_DEMAND = "ON_DEMAND", + /** + * Type for Provisioned Throughput traffic. + */ + PROVISIONED_THROUGHPUT = "PROVISIONED_THROUGHPUT" +} + +/** Audio transcription in Server Conent. */ +export declare interface Transcription { + /** Transcription text. + */ + text?: string; + /** The bool indicates the end of the transcription. + */ + finished?: boolean; +} + +export declare interface TunedModel { + /** Output only. The resource name of the TunedModel. Format: `projects/{project}/locations/{location}/models/{model}@{version_id}` When tuning from a base model, the version_id will be 1. For continuous tuning, the version id will be incremented by 1 from the last version id in the parent model. E.g., `projects/{project}/locations/{location}/models/{model}@{last_version_id + 1}` */ + model?: string; + /** Output only. A resource name of an Endpoint. Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. */ + endpoint?: string; + /** The checkpoints associated with this TunedModel. + This field is only populated for tuning jobs that enable intermediate + checkpoints. */ + checkpoints?: TunedModelCheckpoint[]; +} + +/** TunedModelCheckpoint for the Tuned Model of a Tuning Job. */ +export declare interface TunedModelCheckpoint { + /** The ID of the checkpoint. + */ + checkpointId?: string; + /** The epoch of the checkpoint. + */ + epoch?: string; + /** The step of the checkpoint. + */ + step?: string; + /** The Endpoint resource name that the checkpoint is deployed to. + Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. + */ + endpoint?: string; +} + +/** A tuned machine learning model. */ +export declare interface TunedModelInfo { + /** ID of the base model that you want to tune. */ + baseModel?: string; + /** Date and time when the base model was created. */ + createTime?: string; + /** Date and time when the base model was last updated. */ + updateTime?: string; +} + +/** Supervised fine-tuning training dataset. */ +export declare interface TuningDataset { + /** GCS URI of the file containing training dataset in JSONL format. */ + gcsUri?: string; + /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */ + vertexDatasetResource?: string; + /** Inline examples with simple input/output text. */ + examples?: TuningExample[]; +} + +/** The tuning data statistic values for TuningJob. */ +export declare interface TuningDataStats { + /** Output only. Statistics for distillation. */ + distillationDataStats?: DistillationDataStats; + /** Output only. Statistics for preference optimization. */ + preferenceOptimizationDataStats?: PreferenceOptimizationDataStats; + /** The SFT Tuning data stats. */ + supervisedTuningDataStats?: SupervisedTuningDataStats; +} + +export declare interface TuningExample { + /** Text model input. */ + textInput?: string; + /** The expected model output. */ + output?: string; +} + +/** A tuning job. */ +export declare interface TuningJob { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}` */ + name?: string; + /** Output only. The detailed state of the job. */ + state?: JobState; + /** Output only. Time when the TuningJob was created. */ + createTime?: string; + /** Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING` state. */ + startTime?: string; + /** Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`. */ + endTime?: string; + /** Output only. Time when the TuningJob was most recently updated. */ + updateTime?: string; + /** Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. */ + error?: GoogleRpcStatus; + /** Optional. The description of the TuningJob. */ + description?: string; + /** The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */ + baseModel?: string; + /** Output only. The tuned model resources associated with this TuningJob. */ + tunedModel?: TunedModel; + /** The pre-tuned model for continuous tuning. */ + preTunedModel?: PreTunedModel; + /** Tuning Spec for Supervised Fine Tuning. */ + supervisedTuningSpec?: SupervisedTuningSpec; + /** Output only. The tuning data statistics associated with this TuningJob. */ + tuningDataStats?: TuningDataStats; + /** Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with the provided encryption key. */ + encryptionSpec?: EncryptionSpec; + /** Tuning Spec for open sourced and third party Partner models. */ + partnerModelTuningSpec?: PartnerModelTuningSpec; + /** Optional. The user-provided path to custom model weights. Set this field to tune a custom model. The path must be a Cloud Storage directory that contains the model weights in .safetensors format along with associated model metadata files. If this field is set, the base_model field must still be set to indicate which base model the custom model is derived from. This feature is only available for open source models. */ + customBaseModel?: string; + /** Output only. The Experiment associated with this TuningJob. */ + experiment?: string; + /** Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. */ + labels?: Record; + /** Optional. Cloud Storage path to the directory where tuning job outputs are written to. This field is only available and required for open source models. */ + outputUri?: string; + /** Output only. The resource name of the PipelineJob associated with the TuningJob. Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`. */ + pipelineJob?: string; + /** The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission on this service account. */ + serviceAccount?: string; + /** Optional. The display name of the TunedModel. The name can be up to 128 characters long and can consist of any UTF-8 characters. */ + tunedModelDisplayName?: string; +} + +/** Tuning mode. */ +export declare enum TuningMode { + /** + * Tuning mode is unspecified. + */ + TUNING_MODE_UNSPECIFIED = "TUNING_MODE_UNSPECIFIED", + /** + * Full fine-tuning mode. + */ + TUNING_MODE_FULL = "TUNING_MODE_FULL", + /** + * PEFT adapter tuning mode. + */ + TUNING_MODE_PEFT_ADAPTER = "TUNING_MODE_PEFT_ADAPTER" +} + +/** A long-running operation. */ +export declare interface TuningOperation { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; +} + +declare class Tunings extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + get: (params: types.GetTuningJobParameters) => Promise; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + list: (params?: types.ListTuningJobsParameters) => Promise>; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + tune: (params: types.CreateTuningJobParameters) => Promise; + private getInternal; + private listInternal; + private tuneInternal; + private tuneMldevInternal; +} + +export declare interface TuningValidationDataset { + /** GCS URI of the file containing validation dataset in JSONL format. */ + gcsUri?: string; + /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */ + vertexDatasetResource?: string; +} + +/** Options about which input is included in the user's turn. */ +export declare enum TurnCoverage { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TURN_COVERAGE_UNSPECIFIED = "TURN_COVERAGE_UNSPECIFIED", + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TURN_INCLUDES_ONLY_ACTIVITY = "TURN_INCLUDES_ONLY_ACTIVITY", + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TURN_INCLUDES_ALL_INPUT = "TURN_INCLUDES_ALL_INPUT" +} + +/** Optional. The type of the data. */ +export declare enum Type { + /** + * Not specified, should not be used. + */ + TYPE_UNSPECIFIED = "TYPE_UNSPECIFIED", + /** + * OpenAPI string type + */ + STRING = "STRING", + /** + * OpenAPI number type + */ + NUMBER = "NUMBER", + /** + * OpenAPI integer type + */ + INTEGER = "INTEGER", + /** + * OpenAPI boolean type + */ + BOOLEAN = "BOOLEAN", + /** + * OpenAPI array type + */ + ARRAY = "ARRAY", + /** + * OpenAPI object type + */ + OBJECT = "OBJECT", + /** + * Null type + */ + NULL = "NULL" +} + +declare namespace types { + export { + createPartFromUri, + createPartFromText, + createPartFromFunctionCall, + createPartFromFunctionResponse, + createPartFromBase64, + createPartFromCodeExecutionResult, + createPartFromExecutableCode, + createUserContent, + createModelContent, + Outcome, + Language, + Type, + HarmCategory, + HarmBlockMethod, + HarmBlockThreshold, + Mode, + AuthType, + ApiSpec, + UrlRetrievalStatus, + FinishReason, + HarmProbability, + HarmSeverity, + BlockedReason, + TrafficType, + Modality, + MediaResolution, + JobState, + TuningMode, + AdapterSize, + FeatureSelectionPreference, + Behavior, + DynamicRetrievalConfigMode, + Environment, + FunctionCallingConfigMode, + SafetyFilterLevel, + PersonGeneration, + ImagePromptLanguage, + MaskReferenceMode, + ControlReferenceType, + SubjectReferenceType, + EditMode, + SegmentMode, + VideoCompressionQuality, + FileState, + FileSource, + MediaModality, + StartSensitivity, + EndSensitivity, + ActivityHandling, + TurnCoverage, + FunctionResponseScheduling, + Scale, + MusicGenerationMode, + LiveMusicPlaybackControl, + VideoMetadata, + Blob_2 as Blob, + FileData, + CodeExecutionResult, + ExecutableCode, + FunctionCall, + FunctionResponse, + Part, + Content, + HttpOptions, + Schema, + ModelSelectionConfig, + SafetySetting, + FunctionDeclaration, + Interval, + GoogleSearch, + DynamicRetrievalConfig, + GoogleSearchRetrieval, + EnterpriseWebSearch, + ApiKeyConfig, + AuthConfigGoogleServiceAccountConfig, + AuthConfigHttpBasicAuthConfig, + AuthConfigOauthConfig, + AuthConfigOidcConfig, + AuthConfig, + GoogleMaps, + UrlContext, + ToolComputerUse, + ApiAuthApiKeyConfig, + ApiAuth, + ExternalApiElasticSearchParams, + ExternalApiSimpleSearchParams, + ExternalApi, + VertexAISearchDataStoreSpec, + VertexAISearch, + VertexRagStoreRagResource, + RagRetrievalConfigFilter, + RagRetrievalConfigHybridSearch, + RagRetrievalConfigRankingLlmRanker, + RagRetrievalConfigRankingRankService, + RagRetrievalConfigRanking, + RagRetrievalConfig, + VertexRagStore, + Retrieval, + ToolCodeExecution, + Tool, + FunctionCallingConfig, + LatLng, + RetrievalConfig, + ToolConfig, + PrebuiltVoiceConfig, + VoiceConfig, + SpeakerVoiceConfig, + MultiSpeakerVoiceConfig, + SpeechConfig, + AutomaticFunctionCallingConfig, + ThinkingConfig, + GenerationConfigRoutingConfigAutoRoutingMode, + GenerationConfigRoutingConfigManualRoutingMode, + GenerationConfigRoutingConfig, + GenerateContentConfig, + GenerateContentParameters, + HttpResponse, + LiveCallbacks, + GoogleTypeDate, + Citation, + CitationMetadata, + UrlMetadata, + UrlContextMetadata, + GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution, + GroundingChunkMapsPlaceAnswerSourcesReviewSnippet, + GroundingChunkMapsPlaceAnswerSources, + GroundingChunkMaps, + RagChunkPageSpan, + RagChunk, + GroundingChunkRetrievedContext, + GroundingChunkWeb, + GroundingChunk, + Segment, + GroundingSupport, + RetrievalMetadata, + SearchEntryPoint, + GroundingMetadata, + LogprobsResultCandidate, + LogprobsResultTopCandidates, + LogprobsResult, + SafetyRating, + Candidate, + GenerateContentResponsePromptFeedback, + ModalityTokenCount, + GenerateContentResponseUsageMetadata, + GenerateContentResponse, + ReferenceImage, + EditImageParameters, + EmbedContentConfig, + EmbedContentParameters, + ContentEmbeddingStatistics, + ContentEmbedding, + EmbedContentMetadata, + EmbedContentResponse, + GenerateImagesConfig, + GenerateImagesParameters, + Image_2 as Image, + SafetyAttributes, + GeneratedImage, + GenerateImagesResponse, + MaskReferenceConfig, + ControlReferenceConfig, + StyleReferenceConfig, + SubjectReferenceConfig, + EditImageConfig, + EditImageResponse, + UpscaleImageResponse, + ProductImage, + RecontextImageSource, + RecontextImageConfig, + RecontextImageParameters, + RecontextImageResponse, + ScribbleImage, + SegmentImageSource, + SegmentImageConfig, + SegmentImageParameters, + EntityLabel, + GeneratedImageMask, + SegmentImageResponse, + GetModelConfig, + GetModelParameters, + Endpoint, + TunedModelInfo, + Checkpoint, + Model, + ListModelsConfig, + ListModelsParameters, + ListModelsResponse, + UpdateModelConfig, + UpdateModelParameters, + DeleteModelConfig, + DeleteModelParameters, + DeleteModelResponse, + GenerationConfigThinkingConfig, + GenerationConfig, + CountTokensConfig, + CountTokensParameters, + CountTokensResponse, + ComputeTokensConfig, + ComputeTokensParameters, + TokensInfo, + ComputeTokensResponse, + Video, + VideoGenerationReferenceImage, + GenerateVideosConfig, + GenerateVideosParameters, + GeneratedVideo, + GenerateVideosResponse, + GetTuningJobConfig, + GetTuningJobParameters, + TunedModelCheckpoint, + TunedModel, + GoogleRpcStatus, + PreTunedModel, + SupervisedHyperParameters, + SupervisedTuningSpec, + DatasetDistributionDistributionBucket, + DatasetDistribution, + DatasetStats, + DistillationDataStats, + GeminiPreferenceExampleCompletion, + GeminiPreferenceExample, + PreferenceOptimizationDataStats, + SupervisedTuningDatasetDistributionDatasetBucket, + SupervisedTuningDatasetDistribution, + SupervisedTuningDataStats, + TuningDataStats, + EncryptionSpec, + PartnerModelTuningSpec, + TuningJob, + ListTuningJobsConfig, + ListTuningJobsParameters, + ListTuningJobsResponse, + TuningExample, + TuningDataset, + TuningValidationDataset, + CreateTuningJobConfig, + CreateTuningJobParametersPrivate, + TuningOperation, + CreateCachedContentConfig, + CreateCachedContentParameters, + CachedContentUsageMetadata, + CachedContent, + GetCachedContentConfig, + GetCachedContentParameters, + DeleteCachedContentConfig, + DeleteCachedContentParameters, + DeleteCachedContentResponse, + UpdateCachedContentConfig, + UpdateCachedContentParameters, + ListCachedContentsConfig, + ListCachedContentsParameters, + ListCachedContentsResponse, + ListFilesConfig, + ListFilesParameters, + FileStatus, + File_2 as File, + ListFilesResponse, + CreateFileConfig, + CreateFileParameters, + CreateFileResponse, + GetFileConfig, + GetFileParameters, + DeleteFileConfig, + DeleteFileParameters, + DeleteFileResponse, + InlinedRequest, + BatchJobSource, + JobError, + InlinedResponse, + BatchJobDestination, + CreateBatchJobConfig, + CreateBatchJobParameters, + BatchJob, + GetBatchJobConfig, + GetBatchJobParameters, + CancelBatchJobConfig, + CancelBatchJobParameters, + ListBatchJobsConfig, + ListBatchJobsParameters, + ListBatchJobsResponse, + DeleteBatchJobConfig, + DeleteBatchJobParameters, + DeleteResourceJob, + GetOperationConfig, + GetOperationParameters, + FetchPredictOperationConfig, + FetchPredictOperationParameters, + TestTableItem, + TestTableFile, + ReplayRequest, + ReplayResponse, + ReplayInteraction, + ReplayFile, + UploadFileConfig, + DownloadFileConfig, + DownloadFileParameters, + UpscaleImageConfig, + UpscaleImageParameters, + RawReferenceImage, + MaskReferenceImage, + ControlReferenceImage, + StyleReferenceImage, + SubjectReferenceImage, + LiveServerSetupComplete, + Transcription, + LiveServerContent, + LiveServerToolCall, + LiveServerToolCallCancellation, + UsageMetadata, + LiveServerGoAway, + LiveServerSessionResumptionUpdate, + LiveServerMessage, + OperationGetParameters, + OperationFromAPIResponseParameters, + Operation, + GenerateVideosOperation, + AutomaticActivityDetection, + RealtimeInputConfig, + SessionResumptionConfig, + SlidingWindow, + ContextWindowCompressionConfig, + AudioTranscriptionConfig, + ProactivityConfig, + LiveClientSetup, + LiveClientContent, + ActivityStart, + ActivityEnd, + LiveClientRealtimeInput, + LiveClientToolResponse, + LiveSendRealtimeInputParameters, + LiveClientMessage, + LiveConnectConfig, + LiveConnectParameters, + CreateChatParameters, + SendMessageParameters, + LiveSendClientContentParameters, + LiveSendToolResponseParameters, + LiveMusicClientSetup, + WeightedPrompt, + LiveMusicClientContent, + LiveMusicGenerationConfig, + LiveMusicClientMessage, + LiveMusicServerSetupComplete, + LiveMusicSourceMetadata, + AudioChunk, + LiveMusicServerContent, + LiveMusicFilteredPrompt, + LiveMusicServerMessage, + LiveMusicCallbacks, + UploadFileParameters, + CallableTool, + CallableToolConfig, + LiveMusicConnectParameters, + LiveMusicSetConfigParameters, + LiveMusicSetWeightedPromptsParameters, + AuthToken, + LiveConnectConstraints, + CreateAuthTokenConfig, + CreateAuthTokenParameters, + CreateTuningJobParameters, + BlobImageUnion, + PartUnion, + PartListUnion, + ContentUnion, + ContentListUnion, + SchemaUnion, + SpeechConfigUnion, + ToolUnion, + ToolListUnion, + DownloadableFileUnion, + BatchJobSourceUnion, + BatchJobDestinationUnion + } +} + +/** Optional parameters for caches.update method. */ +export declare interface UpdateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; +} + +export declare interface UpdateCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Configuration that contains optional parameters. + */ + config?: UpdateCachedContentConfig; +} + +/** Configuration for updating a tuned model. */ +export declare interface UpdateModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + displayName?: string; + description?: string; + defaultCheckpointId?: string; +} + +/** Configuration for updating a tuned model. */ +export declare interface UpdateModelParameters { + model: string; + config?: UpdateModelConfig; +} + +declare interface Uploader { + /** + * Uploads a file to the given upload url. + * + * @param file The file to upload. file is in string type or a Blob. + * @param uploadUrl The upload URL as a string is where the file will be + * uploaded to. The uploadUrl must be a url that was returned by the + * https://generativelanguage.googleapis.com/upload/v1beta/files endpoint + * @param apiClient The ApiClient to use for uploading. + * @return A Promise that resolves to types.File. + */ + upload(file: string | Blob, uploadUrl: string, apiClient: ApiClient): Promise; + /** + * Returns the file's mimeType and the size of a given file. If the file is a + * string path, the file type is determined by the file extension. If the + * file's type cannot be determined, the type will be set to undefined. + * + * @param file The file to get the stat for. Can be a string path or a Blob. + * @return A Promise that resolves to the file stat of the given file. + */ + stat(file: string | Blob): Promise; +} + +/** Used to override the default configuration. */ +export declare interface UploadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */ + name?: string; + /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */ + mimeType?: string; + /** Optional display name of the file. */ + displayName?: string; +} + +/** Parameters for the upload file method. */ +export declare interface UploadFileParameters { + /** The string path to the file to be uploaded or a Blob object. */ + file: string | globalThis.Blob; + /** Configuration that contains optional parameters. */ + config?: UploadFileConfig; +} + +/** Configuration for upscaling an image. + + For more information on this configuration, refer to + the `Imagen API reference documentation + `_. + */ +export declare interface UpscaleImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Whether to include a reason for filtered-out images in the + response. */ + includeRaiReason?: boolean; + /** The image format that the output should be saved as. */ + outputMimeType?: string; + /** The level of compression if the ``output_mime_type`` is + ``image/jpeg``. */ + outputCompressionQuality?: number; + /** Whether to add an image enhancing step before upscaling. + It is expected to suppress the noise and JPEG compression artifacts + from the input image. */ + enhanceInputImage?: boolean; + /** With a higher image preservation factor, the original image + pixels are more respected. With a lower image preservation factor, the + output image will have be more different from the input image, but + with finer details and less noise. */ + imagePreservationFactor?: number; +} + +/** User-facing config UpscaleImageParameters. */ +export declare interface UpscaleImageParameters { + /** The model to use. */ + model: string; + /** The input image to upscale. */ + image: Image_2; + /** The factor to upscale the image (x2 or x4). */ + upscaleFactor: string; + /** Configuration for upscaling. */ + config?: UpscaleImageConfig; +} + +export declare class UpscaleImageResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** Tool to support URL context retrieval. */ +export declare interface UrlContext { +} + +/** Metadata related to url context retrieval tool. */ +export declare interface UrlContextMetadata { + /** List of url context. */ + urlMetadata?: UrlMetadata[]; +} + +/** Context for a single url retrieval. */ +export declare interface UrlMetadata { + /** The URL retrieved by the tool. */ + retrievedUrl?: string; + /** Status of the url retrieval. */ + urlRetrievalStatus?: UrlRetrievalStatus; +} + +/** Status of the url retrieval. */ +export declare enum UrlRetrievalStatus { + /** + * Default value. This value is unused + */ + URL_RETRIEVAL_STATUS_UNSPECIFIED = "URL_RETRIEVAL_STATUS_UNSPECIFIED", + /** + * Url retrieval is successful. + */ + URL_RETRIEVAL_STATUS_SUCCESS = "URL_RETRIEVAL_STATUS_SUCCESS", + /** + * Url retrieval is failed due to error. + */ + URL_RETRIEVAL_STATUS_ERROR = "URL_RETRIEVAL_STATUS_ERROR", + /** + * Url retrieval is failed because the content is behind paywall. + */ + URL_RETRIEVAL_STATUS_PAYWALL = "URL_RETRIEVAL_STATUS_PAYWALL", + /** + * Url retrieval is failed because the content is unsafe. + */ + URL_RETRIEVAL_STATUS_UNSAFE = "URL_RETRIEVAL_STATUS_UNSAFE" +} + +/** Usage metadata about response(s). */ +export declare interface UsageMetadata { + /** Number of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */ + promptTokenCount?: number; + /** Number of tokens in the cached part of the prompt (the cached content). */ + cachedContentTokenCount?: number; + /** Total number of tokens across all the generated response candidates. */ + responseTokenCount?: number; + /** Number of tokens present in tool-use prompt(s). */ + toolUsePromptTokenCount?: number; + /** Number of tokens of thoughts for thinking models. */ + thoughtsTokenCount?: number; + /** Total token count for prompt, response candidates, and tool-use prompts(if present). */ + totalTokenCount?: number; + /** List of modalities that were processed in the request input. */ + promptTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were processed in the cache input. */ + cacheTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were returned in the response. */ + responseTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were processed in the tool-use prompt. */ + toolUsePromptTokensDetails?: ModalityTokenCount[]; + /** Traffic type. This shows whether a request consumes Pay-As-You-Go + or Provisioned Throughput quota. */ + trafficType?: TrafficType; +} + +/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */ +export declare interface VertexAISearch { + /** Specifications that define the specific DataStores to be searched, along with configurations for those data stores. This is only considered for Engines with multiple data stores. It should only be set if engine is used. */ + dataStoreSpecs?: VertexAISearchDataStoreSpec[]; + /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */ + datastore?: string; + /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */ + engine?: string; + /** Optional. Filter strings to be passed to the search API. */ + filter?: string; + /** Optional. Number of search results to return per query. The default value is 10. The maximumm allowed value is 10. */ + maxResults?: number; +} + +/** Define data stores within engine to filter on in a search call and configurations for those data stores. For more information, see https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec */ +export declare interface VertexAISearchDataStoreSpec { + /** Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */ + dataStore?: string; + /** Optional. Filter specification to filter documents in the data store specified by data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata) */ + filter?: string; +} + +/** Retrieve from Vertex RAG Store for grounding. */ +export declare interface VertexRagStore { + /** Optional. Deprecated. Please use rag_resources instead. */ + ragCorpora?: string[]; + /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */ + ragResources?: VertexRagStoreRagResource[]; + /** Optional. The retrieval config for the Rag query. */ + ragRetrievalConfig?: RagRetrievalConfig; + /** Optional. Number of top k results to return from the selected corpora. */ + similarityTopK?: number; + /** Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal Live API, if `store_context` bool is specified, Gemini will leverage it to automatically memorize the interactions between the client and Gemini, and retrieve context when needed to augment the response generation for users' ongoing and future interactions. */ + storeContext?: boolean; + /** Optional. Only return results with vector distance smaller than the threshold. */ + vectorDistanceThreshold?: number; +} + +/** The definition of the Rag resource. */ +export declare interface VertexRagStoreRagResource { + /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */ + ragCorpus?: string; + /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */ + ragFileIds?: string[]; +} + +/** A generated video. */ +export declare interface Video { + /** Path to another storage. */ + uri?: string; + /** Video bytes. + * @remarks Encoded as base64 string. */ + videoBytes?: string; + /** Video encoding, for example "video/mp4". */ + mimeType?: string; +} + +/** Enum that controls the compression quality of the generated videos. */ +export declare enum VideoCompressionQuality { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + OPTIMIZED = "OPTIMIZED", + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + LOSSLESS = "LOSSLESS" +} + +/** A reference image for video generation. */ +export declare interface VideoGenerationReferenceImage { + /** The reference image. + */ + image?: Image_2; + /** The type of the reference image, which defines how the reference + image will be used to generate the video. Supported values are 'asset' + or 'style'. */ + referenceType?: string; +} + +/** Describes how the video in the Part should be used by the model. */ +export declare interface VideoMetadata { + /** The frame rate of the video sent to the model. If not specified, the + default value will be 1.0. The fps range is (0.0, 24.0]. */ + fps?: number; + /** Optional. The end offset of the video. */ + endOffset?: string; + /** Optional. The start offset of the video. */ + startOffset?: string; +} + +/** The configuration for the voice to use. */ +export declare interface VoiceConfig { + /** The configuration for the speaker to use. + */ + prebuiltVoiceConfig?: PrebuiltVoiceConfig; +} + +declare interface WebSocket_2 { + /** + * Connects the socket to the server. + */ + connect(): void; + /** + * Sends a message to the server. + */ + send(message: string): void; + /** + * Closes the socket connection. + */ + close(): void; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +declare interface WebSocketCallbacks { + onopen: () => void; + onerror: (e: any) => void; + onmessage: (e: any) => void; + onclose: (e: any) => void; +} + +declare interface WebSocketFactory { + /** + * Returns a new WebSocket instance. + */ + create(url: string, headers: Record, callbacks: WebSocketCallbacks): WebSocket_2; +} + +/** Maps a prompt to a relative weight to steer music generation. */ +export declare interface WeightedPrompt { + /** Text prompt. */ + text?: string; + /** Weight of the prompt. The weight is used to control the relative + importance of the prompt. Higher weights are more important than lower + weights. + + Weight must not be 0. Weights of all weighted_prompts in this + LiveMusicClientContent message will be normalized. */ + weight?: number; +} + +export { } diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7666aff879d6b8175a80f014060c2b5084523489 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node/package.json @@ -0,0 +1,4 @@ +{ + "name": "@google/genai/node", + "main": "../dist/node/index.js" +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/CHANGELOG.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..1053528f114423f5de3d298a4b74079047041873 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/CHANGELOG.md @@ -0,0 +1,397 @@ +# Changelog + +## [6.7.1](https://github.com/googleapis/gaxios/compare/v6.7.0...v6.7.1) (2024-08-13) + + +### Bug Fixes + +* Release uuid rollback ([#641](https://github.com/googleapis/gaxios/issues/641)) ([2e21115](https://github.com/googleapis/gaxios/commit/2e211158d5351d81de4e84f999ec3b41475ec0cd)) + +## [6.7.0](https://github.com/googleapis/gaxios/compare/v6.6.0...v6.7.0) (2024-06-27) + + +### Features + +* Add additional retry configuration options ([#634](https://github.com/googleapis/gaxios/issues/634)) ([cb5c833](https://github.com/googleapis/gaxios/commit/cb5c833a9750bf6d0c0f8e27992bb44bd953566c)) + + +### Bug Fixes + +* **deps:** Update dependency uuid to v10 ([#629](https://github.com/googleapis/gaxios/issues/629)) ([6ff684e](https://github.com/googleapis/gaxios/commit/6ff684e6e6e5f4e5e6d270685b2ac0e4d28bc964)) + +## [6.6.0](https://github.com/googleapis/gaxios/compare/v6.5.0...v6.6.0) (2024-05-15) + + +### Features + +* Add request and response interceptors ([#619](https://github.com/googleapis/gaxios/issues/619)) ([059fe77](https://github.com/googleapis/gaxios/commit/059fe7708e6d98cc44814ec1fad7d412668a05b9)) + +## [6.5.0](https://github.com/googleapis/gaxios/compare/v6.4.0...v6.5.0) (2024-04-09) + + +### Features + +* Retry `408` by Default ([#616](https://github.com/googleapis/gaxios/issues/616)) ([9331f79](https://github.com/googleapis/gaxios/commit/9331f79f9c9d0c1f4f1f995e1928323f4feb5427)) +* Support `proxy` option ([#614](https://github.com/googleapis/gaxios/issues/614)) ([2d14b3f](https://github.com/googleapis/gaxios/commit/2d14b3f54bc97111cb184cecf2379b55ceaca3c2)) + +## [6.4.0](https://github.com/googleapis/gaxios/compare/v6.3.0...v6.4.0) (2024-04-03) + + +### Features + +* Enhance Error Redaction ([#609](https://github.com/googleapis/gaxios/issues/609)) ([b1d2875](https://github.com/googleapis/gaxios/commit/b1d28759110f91b37746f9b88aba92bf52df2fcc)) +* Support multipart/related requests ([#610](https://github.com/googleapis/gaxios/issues/610)) ([086c824](https://github.com/googleapis/gaxios/commit/086c8240652bd893dff0dd4c097ef00f5777564e)) + + +### Bug Fixes + +* Error Redactor Case-Insensitive Matching ([#613](https://github.com/googleapis/gaxios/issues/613)) ([05e65ef](https://github.com/googleapis/gaxios/commit/05e65efda6d13e760d4f7f87be7d6cebeba3cc64)) + +## [6.3.0](https://github.com/googleapis/gaxios/compare/v6.2.0...v6.3.0) (2024-02-01) + + +### Features + +* Support URL objects ([#598](https://github.com/googleapis/gaxios/issues/598)) ([ef40c61](https://github.com/googleapis/gaxios/commit/ef40c61fabf0a48b2f08be085ee0c56dc32cf78c)) + +## [6.2.0](https://github.com/googleapis/gaxios/compare/v6.1.1...v6.2.0) (2024-01-31) + + +### Features + +* Extend `instanceof` Support for GaxiosError ([#593](https://github.com/googleapis/gaxios/issues/593)) ([4fd1fe2](https://github.com/googleapis/gaxios/commit/4fd1fe2c91b9888c4f976cf91e752d407b99ec75)) + + +### Bug Fixes + +* Do Not Mutate Config for Redacted Retries ([#597](https://github.com/googleapis/gaxios/issues/597)) ([4d1a551](https://github.com/googleapis/gaxios/commit/4d1a55134940031a1e0ff2392ab0b08c186166f0)) +* Return text when content type is text/* ([#579](https://github.com/googleapis/gaxios/issues/579)) ([3cc1c76](https://github.com/googleapis/gaxios/commit/3cc1c76a08d98daac01c83bed6f9480320ec0a37)) + +## [6.1.1](https://github.com/googleapis/gaxios/compare/v6.1.0...v6.1.1) (2023-09-07) + + +### Bug Fixes + +* Don't throw an error within a `GaxiosError` ([#569](https://github.com/googleapis/gaxios/issues/569)) ([035d9dd](https://github.com/googleapis/gaxios/commit/035d9dd833c3ad63148bc50facaee421f4792192)) + +## [6.1.0](https://github.com/googleapis/gaxios/compare/v6.0.4...v6.1.0) (2023-08-11) + + +### Features + +* Prevent Auth Logging by Default ([#565](https://github.com/googleapis/gaxios/issues/565)) ([b28e562](https://github.com/googleapis/gaxios/commit/b28e5628f5964e2ecc04cc1df8a54948567a4b48)) + +## [6.0.4](https://github.com/googleapis/gaxios/compare/v6.0.3...v6.0.4) (2023-08-03) + + +### Bug Fixes + +* **deps:** Update https-proxy-agent to 7.0.1 and fix imports and tests ([#560](https://github.com/googleapis/gaxios/issues/560)) ([5c877e2](https://github.com/googleapis/gaxios/commit/5c877e28c3c9336a87b50536c074cb215b779d8e)) + +## [6.0.3](https://github.com/googleapis/gaxios/compare/v6.0.2...v6.0.3) (2023-07-24) + + +### Bug Fixes + +* Handle invalid json when Content-Type=application/json ([#558](https://github.com/googleapis/gaxios/issues/558)) ([71602eb](https://github.com/googleapis/gaxios/commit/71602ebc2ab18d5af904b152723756f57fb13bce)) + +## [6.0.2](https://github.com/googleapis/gaxios/compare/v6.0.1...v6.0.2) (2023-07-20) + + +### Bug Fixes + +* Revert attempting to convert 'text/plain', leave as data in GaxiosError ([#556](https://github.com/googleapis/gaxios/issues/556)) ([d603bde](https://github.com/googleapis/gaxios/commit/d603bde35f698564c028108d24c6891cec3b8ea1)) + +## [6.0.1](https://github.com/googleapis/gaxios/compare/v6.0.0...v6.0.1) (2023-07-20) + + +### Bug Fixes + +* Add text to responseType switch statement ([#554](https://github.com/googleapis/gaxios/issues/554)) ([899cf1f](https://github.com/googleapis/gaxios/commit/899cf1fb088f49927624d526f6de212837a31b9d)) + +## [6.0.0](https://github.com/googleapis/gaxios/compare/v5.1.3...v6.0.0) (2023-07-12) + + +### ⚠ BREAKING CHANGES + +* add status as a number to GaxiosError, change code to error code as a string ([#552](https://github.com/googleapis/gaxios/issues/552)) +* migrate to Node 14 ([#548](https://github.com/googleapis/gaxios/issues/548)) +* examine response content-type if no contentType is set ([#535](https://github.com/googleapis/gaxios/issues/535)) + +### Bug Fixes + +* Add status as a number to GaxiosError, change code to error code as a string ([#552](https://github.com/googleapis/gaxios/issues/552)) ([88ba2e9](https://github.com/googleapis/gaxios/commit/88ba2e99e32b66d84725c9ea9ad95152bd1dc653)) +* Examine response content-type if no contentType is set ([#535](https://github.com/googleapis/gaxios/issues/535)) ([cd8ca7b](https://github.com/googleapis/gaxios/commit/cd8ca7b209f0ba932082a80ace8fec608a71facf)) + + +### Miscellaneous Chores + +* Migrate to Node 14 ([#548](https://github.com/googleapis/gaxios/issues/548)) ([b9b26eb](https://github.com/googleapis/gaxios/commit/b9b26eb2c4af35633efd91770aa24c4b5d9019b4)) + +## [5.1.3](https://github.com/googleapis/gaxios/compare/v5.1.2...v5.1.3) (2023-07-05) + + +### Bug Fixes + +* Translate GaxiosError message to object regardless of return type (return data as default) ([#546](https://github.com/googleapis/gaxios/issues/546)) ([adfd570](https://github.com/googleapis/gaxios/commit/adfd57068a98d03921d5383fed11a652a21d59dd)) + +## [5.1.2](https://github.com/googleapis/gaxios/compare/v5.1.1...v5.1.2) (2023-06-25) + + +### Bug Fixes + +* Revert changes to error handling due to downstream breakage ([#544](https://github.com/googleapis/gaxios/issues/544)) ([64fbf07](https://github.com/googleapis/gaxios/commit/64fbf07f3697f40b75a9e7dbe8bff7f6243a9e12)) + +## [5.1.1](https://github.com/googleapis/gaxios/compare/v5.1.0...v5.1.1) (2023-06-23) + + +### Bug Fixes + +* Translate GaxiosError message to object regardless of return type ([#537](https://github.com/googleapis/gaxios/issues/537)) ([563c653](https://github.com/googleapis/gaxios/commit/563c6537a06bc64d5c6e918090c00ec7a586cecb)) + +## [5.1.0](https://github.com/googleapis/gaxios/compare/v5.0.2...v5.1.0) (2023-03-06) + + +### Features + +* Add support for custom backoff ([#498](https://github.com/googleapis/gaxios/issues/498)) ([4a34467](https://github.com/googleapis/gaxios/commit/4a344678110864d97818a8272ebcc5e1c4921b52)) + +## [5.0.2](https://github.com/googleapis/gaxios/compare/v5.0.1...v5.0.2) (2022-09-09) + + +### Bug Fixes + +* Do not import the whole google-gax from proto JS ([#1553](https://github.com/googleapis/gaxios/issues/1553)) ([#501](https://github.com/googleapis/gaxios/issues/501)) ([6f58d1e](https://github.com/googleapis/gaxios/commit/6f58d1e80ce6b196d17fbc75dc47d8d20804920a)) +* use google-gax v3.3.0 ([6f58d1e](https://github.com/googleapis/gaxios/commit/6f58d1e80ce6b196d17fbc75dc47d8d20804920a)) + +## [5.0.1](https://github.com/googleapis/gaxios/compare/v5.0.0...v5.0.1) (2022-07-04) + + +### Bug Fixes + +* **types:** loosen AbortSignal type ([5a379ca](https://github.com/googleapis/gaxios/commit/5a379ca123f08f286c4774711a7a3293bffc1ea6)) + +## [5.0.0](https://github.com/googleapis/gaxios/compare/v4.3.3...v5.0.0) (2022-04-20) + + +### ⚠ BREAKING CHANGES + +* drop node 10 from engines list, update typescript to 4.6.3 (#477) + +### Features + +* handling missing process global ([c30395b](https://github.com/googleapis/gaxios/commit/c30395bbf34d889e75c7c72a7dff701dc7a98244)) + + +### Build System + +* drop node 10 from engines list, update typescript to 4.6.3 ([#477](https://github.com/googleapis/gaxios/issues/477)) ([a926962](https://github.com/googleapis/gaxios/commit/a9269624a70aa6305599cc0af079d0225ed6af50)) + +### [4.3.3](https://github.com/googleapis/gaxios/compare/v4.3.2...v4.3.3) (2022-04-08) + + +### Bug Fixes + +* do not stringify form data ([#475](https://github.com/googleapis/gaxios/issues/475)) ([17370dc](https://github.com/googleapis/gaxios/commit/17370dcdfd4568d7f3f0855961030d238166836a)) + +### [4.3.2](https://www.github.com/googleapis/gaxios/compare/v4.3.1...v4.3.2) (2021-09-14) + + +### Bug Fixes + +* address codeql warning with hostname matches ([#415](https://www.github.com/googleapis/gaxios/issues/415)) ([5a4d060](https://www.github.com/googleapis/gaxios/commit/5a4d06019343aa08e1bcf8e05108e22ac3b12636)) + +### [4.3.1](https://www.github.com/googleapis/gaxios/compare/v4.3.0...v4.3.1) (2021-09-02) + + +### Bug Fixes + +* **build:** switch primary branch to main ([#427](https://www.github.com/googleapis/gaxios/issues/427)) ([819219e](https://www.github.com/googleapis/gaxios/commit/819219ed742814259c525bdf5721b28234019c08)) + +## [4.3.0](https://www.github.com/googleapis/gaxios/compare/v4.2.1...v4.3.0) (2021-05-26) + + +### Features + +* allow cert and key to be provided for mTLS ([#399](https://www.github.com/googleapis/gaxios/issues/399)) ([d74ab91](https://www.github.com/googleapis/gaxios/commit/d74ab9125d581e46d655614729872e79317c740d)) + +### [4.2.1](https://www.github.com/googleapis/gaxios/compare/v4.2.0...v4.2.1) (2021-04-20) + + +### Bug Fixes + +* **deps:** upgrade webpack and karma-webpack ([#379](https://www.github.com/googleapis/gaxios/issues/379)) ([75c9013](https://www.github.com/googleapis/gaxios/commit/75c90132e99c2f960c01e0faf0f8e947c920aa73)) + +## [4.2.0](https://www.github.com/googleapis/gaxios/compare/v4.1.0...v4.2.0) (2021-03-01) + + +### Features + +* handle application/x-www-form-urlencoded/Buffer ([#374](https://www.github.com/googleapis/gaxios/issues/374)) ([ce21e9c](https://www.github.com/googleapis/gaxios/commit/ce21e9ccd228578a9f90bb2fddff797cec4a9402)) + +## [4.1.0](https://www.github.com/googleapis/gaxios/compare/v4.0.1...v4.1.0) (2020-12-08) + + +### Features + +* add an option to configure the fetch impl ([#342](https://www.github.com/googleapis/gaxios/issues/342)) ([2e081ef](https://www.github.com/googleapis/gaxios/commit/2e081ef161d84aa435788e8d525d393dc7964117)) +* add no_proxy env variable ([#361](https://www.github.com/googleapis/gaxios/issues/361)) ([efe72a7](https://www.github.com/googleapis/gaxios/commit/efe72a71de81d466160dde5da551f7a41acc3ac4)) + +### [4.0.1](https://www.github.com/googleapis/gaxios/compare/v4.0.0...v4.0.1) (2020-10-27) + + +### Bug Fixes + +* prevent bonus ? with empty qs params ([#357](https://www.github.com/googleapis/gaxios/issues/357)) ([b155f76](https://www.github.com/googleapis/gaxios/commit/b155f76cbc4c234da1d99c26691296702342c205)) + +## [4.0.0](https://www.github.com/googleapis/gaxios/compare/v3.2.0...v4.0.0) (2020-10-21) + + +### ⚠ BREAKING CHANGES + +* parameters in `url` and parameters provided via params will now be combined. + +### Bug Fixes + +* drop requirement on URL/combine url and params ([#338](https://www.github.com/googleapis/gaxios/issues/338)) ([e166bc6](https://www.github.com/googleapis/gaxios/commit/e166bc6721fd979070ab3d9c69b71ffe9ee061c7)) + +## [3.2.0](https://www.github.com/googleapis/gaxios/compare/v3.1.0...v3.2.0) (2020-09-14) + + +### Features + +* add initial retry delay, and set default to 100ms ([#336](https://www.github.com/googleapis/gaxios/issues/336)) ([870326b](https://www.github.com/googleapis/gaxios/commit/870326b8245f16fafde0b0c32cfd2f277946e3a1)) + +## [3.1.0](https://www.github.com/googleapis/gaxios/compare/v3.0.4...v3.1.0) (2020-07-30) + + +### Features + +* pass default adapter to adapter option ([#319](https://www.github.com/googleapis/gaxios/issues/319)) ([cf06bd9](https://www.github.com/googleapis/gaxios/commit/cf06bd9f51cbe707ed5973e390d31a091d4537c1)) + +### [3.0.4](https://www.github.com/googleapis/gaxios/compare/v3.0.3...v3.0.4) (2020-07-09) + + +### Bug Fixes + +* typeo in nodejs .gitattribute ([#306](https://www.github.com/googleapis/gaxios/issues/306)) ([8514672](https://www.github.com/googleapis/gaxios/commit/8514672f9d56bc6f077dcbab050b3342d4e343c6)) + +### [3.0.3](https://www.github.com/googleapis/gaxios/compare/v3.0.2...v3.0.3) (2020-04-20) + + +### Bug Fixes + +* apache license URL ([#468](https://www.github.com/googleapis/gaxios/issues/468)) ([#272](https://www.github.com/googleapis/gaxios/issues/272)) ([cf1b7cb](https://www.github.com/googleapis/gaxios/commit/cf1b7cb66e4c98405236834e63349931b4f35b90)) + +### [3.0.2](https://www.github.com/googleapis/gaxios/compare/v3.0.1...v3.0.2) (2020-03-24) + + +### Bug Fixes + +* continue replacing application/x-www-form-urlencoded with application/json ([#263](https://www.github.com/googleapis/gaxios/issues/263)) ([dca176d](https://www.github.com/googleapis/gaxios/commit/dca176df0990f2c22255f9764405c496ea07ada2)) + +### [3.0.1](https://www.github.com/googleapis/gaxios/compare/v3.0.0...v3.0.1) (2020-03-23) + + +### Bug Fixes + +* allow an alternate JSON content-type to be set ([#257](https://www.github.com/googleapis/gaxios/issues/257)) ([698a29f](https://www.github.com/googleapis/gaxios/commit/698a29ff3b22f30ea99ad190c4592940bef88f1f)) + +## [3.0.0](https://www.github.com/googleapis/gaxios/compare/v2.3.2...v3.0.0) (2020-03-19) + + +### ⚠ BREAKING CHANGES + +* **deps:** TypeScript introduced breaking changes in generated code in 3.7.x +* drop Node 8 from engines field (#254) + +### Features + +* drop Node 8 from engines field ([#254](https://www.github.com/googleapis/gaxios/issues/254)) ([8c9fff7](https://www.github.com/googleapis/gaxios/commit/8c9fff7f92f70f029292c906c62d194c1d58827d)) +* **deps:** updates to latest TypeScript ([#253](https://www.github.com/googleapis/gaxios/issues/253)) ([054267b](https://www.github.com/googleapis/gaxios/commit/054267bf12e1801c134e3b5cae92dcc5ea041fab)) + +### [2.3.2](https://www.github.com/googleapis/gaxios/compare/v2.3.1...v2.3.2) (2020-02-28) + + +### Bug Fixes + +* update github repo in package ([#239](https://www.github.com/googleapis/gaxios/issues/239)) ([7e750cb](https://www.github.com/googleapis/gaxios/commit/7e750cbaaa59812817d725c74fb9d364c4b71096)) + +### [2.3.1](https://www.github.com/googleapis/gaxios/compare/v2.3.0...v2.3.1) (2020-02-13) + + +### Bug Fixes + +* **deps:** update dependency https-proxy-agent to v5 ([#233](https://www.github.com/googleapis/gaxios/issues/233)) ([56de0a8](https://www.github.com/googleapis/gaxios/commit/56de0a824a2f9622e3e4d4bdd41adccd812a30b4)) + +## [2.3.0](https://www.github.com/googleapis/gaxios/compare/v2.2.2...v2.3.0) (2020-01-31) + + +### Features + +* add promise support for onRetryAttempt and shouldRetry ([#223](https://www.github.com/googleapis/gaxios/issues/223)) ([061afa3](https://www.github.com/googleapis/gaxios/commit/061afa381a51d39823e63accf3dacd16e191f3b9)) + +### [2.2.2](https://www.github.com/googleapis/gaxios/compare/v2.2.1...v2.2.2) (2020-01-08) + + +### Bug Fixes + +* **build:** add publication configuration ([#218](https://www.github.com/googleapis/gaxios/issues/218)) ([43e581f](https://www.github.com/googleapis/gaxios/commit/43e581ff4ed5e79d72f6f29748a5eebb6bff1229)) + +### [2.2.1](https://www.github.com/googleapis/gaxios/compare/v2.2.0...v2.2.1) (2020-01-04) + + +### Bug Fixes + +* **deps:** update dependency https-proxy-agent to v4 ([#201](https://www.github.com/googleapis/gaxios/issues/201)) ([5cdeef2](https://www.github.com/googleapis/gaxios/commit/5cdeef288a0c5c544c0dc2659aafbb2215d06c4b)) +* remove retryDelay option ([#203](https://www.github.com/googleapis/gaxios/issues/203)) ([d21e08d](https://www.github.com/googleapis/gaxios/commit/d21e08d2aada980d39bc5ca7093d54452be2d646)) + +## [2.2.0](https://www.github.com/googleapis/gaxios/compare/v2.1.1...v2.2.0) (2019-12-05) + + +### Features + +* populate GaxiosResponse with raw response information (res.url) ([#189](https://www.github.com/googleapis/gaxios/issues/189)) ([53a7f54](https://www.github.com/googleapis/gaxios/commit/53a7f54cc0f20320d7a6a21a9a9f36050cec2eec)) + + +### Bug Fixes + +* don't retry a request that is aborted intentionally ([#190](https://www.github.com/googleapis/gaxios/issues/190)) ([ba9777b](https://www.github.com/googleapis/gaxios/commit/ba9777b15b5262f8288a8bb3cca49a1de8427d8e)) +* **deps:** pin TypeScript below 3.7.0 ([5373f07](https://www.github.com/googleapis/gaxios/commit/5373f0793a765965a8221ecad2f99257ed1b7444)) + +### [2.1.1](https://www.github.com/googleapis/gaxios/compare/v2.1.0...v2.1.1) (2019-11-15) + + +### Bug Fixes + +* **docs:** snippets are now replaced in jsdoc comments ([#183](https://www.github.com/googleapis/gaxios/issues/183)) ([8dd1324](https://www.github.com/googleapis/gaxios/commit/8dd1324256590bd2f2e9015c813950e1cd8cb330)) + +## [2.1.0](https://www.github.com/googleapis/gaxios/compare/v2.0.3...v2.1.0) (2019-10-09) + + +### Bug Fixes + +* **deps:** update dependency https-proxy-agent to v3 ([#172](https://www.github.com/googleapis/gaxios/issues/172)) ([4a38f35](https://www.github.com/googleapis/gaxios/commit/4a38f35)) + + +### Features + +* **TypeScript:** agent can now be passed as builder method, rather than agent instance ([c84ddd6](https://www.github.com/googleapis/gaxios/commit/c84ddd6)) + +### [2.0.3](https://www.github.com/googleapis/gaxios/compare/v2.0.2...v2.0.3) (2019-09-11) + + +### Bug Fixes + +* do not override content-type if its given ([#158](https://www.github.com/googleapis/gaxios/issues/158)) ([f49e0e6](https://www.github.com/googleapis/gaxios/commit/f49e0e6)) +* improve stream detection logic ([6c41537](https://www.github.com/googleapis/gaxios/commit/6c41537)) +* revert header change ([#161](https://www.github.com/googleapis/gaxios/issues/161)) ([b0f6a8b](https://www.github.com/googleapis/gaxios/commit/b0f6a8b)) + +### [2.0.2](https://www.github.com/googleapis/gaxios/compare/v2.0.1...v2.0.2) (2019-07-23) + + +### Bug Fixes + +* check for existence of fetch before using it ([#138](https://www.github.com/googleapis/gaxios/issues/138)) ([79eb58d](https://www.github.com/googleapis/gaxios/commit/79eb58d)) +* **docs:** make anchors work in jsdoc ([#139](https://www.github.com/googleapis/gaxios/issues/139)) ([85103bb](https://www.github.com/googleapis/gaxios/commit/85103bb)) +* prevent double option processing ([#142](https://www.github.com/googleapis/gaxios/issues/142)) ([19b4b3c](https://www.github.com/googleapis/gaxios/commit/19b4b3c)) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/LICENSE b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/README.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7cf8b6b8ee610390ff553649b96a61b7146c76ee --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/README.md @@ -0,0 +1,210 @@ +# gaxios + +[![npm version](https://img.shields.io/npm/v/gaxios.svg)](https://www.npmjs.org/package/gaxios) +[![codecov](https://codecov.io/gh/googleapis/gaxios/branch/master/graph/badge.svg)](https://codecov.io/gh/googleapis/gaxios) +[![Code Style: Google](https://img.shields.io/badge/code%20style-google-blueviolet.svg)](https://github.com/google/gts) + +> An HTTP request client that provides an `axios` like interface over top of `node-fetch`. + +## Install + +```sh +$ npm install gaxios +``` + +## Example + +```js +const {request} = require('gaxios'); +const res = await request({ + url: 'https://www.googleapis.com/discovery/v1/apis/', +}); +``` + +## Setting Defaults + +Gaxios supports setting default properties both on the default instance, and on additional instances. This is often useful when making many requests to the same domain with the same base settings. For example: + +```js +const gaxios = require('gaxios'); +gaxios.instance.defaults = { + baseURL: 'https://example.com' + headers: { + Authorization: 'SOME_TOKEN' + } +} +gaxios.request({url: '/data'}).then(...); +``` + +Note that setting default values will take precedence +over other authentication methods, i.e., application default credentials. + +## Request Options + +```ts +interface GaxiosOptions = { + // The url to which the request should be sent. Required. + url: string, + + // The HTTP method to use for the request. Defaults to `GET`. + method: 'GET', + + // The base Url to use for the request. Prepended to the `url` property above. + baseURL: 'https://example.com'; + + // The HTTP methods to be sent with the request. + headers: { 'some': 'header' }, + + // The data to send in the body of the request. Data objects will be + // serialized as JSON. + // + // Note: if you would like to provide a Content-Type header other than + // application/json you you must provide a string or readable stream, rather + // than an object: + // data: JSON.stringify({some: 'data'}) + // data: fs.readFile('./some-data.jpeg') + data: { + some: 'data' + }, + + // The max size of the http response content in bytes allowed. + // Defaults to `0`, which is the same as unset. + maxContentLength: 2000, + + // The max number of HTTP redirects to follow. + // Defaults to 100. + maxRedirects: 100, + + // The querystring parameters that will be encoded using `qs` and + // appended to the url + params: { + querystring: 'parameters' + }, + + // By default, we use the `querystring` package in node core to serialize + // querystring parameters. You can override that and provide your + // own implementation. + paramsSerializer: (params) => { + return qs.stringify(params); + }, + + // The timeout for the HTTP request in milliseconds. Defaults to 0. + timeout: 1000, + + // Optional method to override making the actual HTTP request. Useful + // for writing tests and instrumentation + adapter?: async (options, defaultAdapter) => { + const res = await defaultAdapter(options); + res.data = { + ...res.data, + extraProperty: 'your extra property', + }; + return res; + }; + + // The expected return type of the request. Options are: + // json | stream | blob | arraybuffer | text | unknown + // Defaults to `unknown`. + responseType: 'unknown', + + // The node.js http agent to use for the request. + agent: someHttpsAgent, + + // Custom function to determine if the response is valid based on the + // status code. Defaults to (>= 200 && < 300) + validateStatus: (status: number) => true, + + // Implementation of `fetch` to use when making the API call. By default, + // will use the browser context if available, and fall back to `node-fetch` + // in node.js otherwise. + fetchImplementation?: typeof fetch; + + // Configuration for retrying of requests. + retryConfig: { + // The number of times to retry the request. Defaults to 3. + retry?: number; + + // The number of retries already attempted. + currentRetryAttempt?: number; + + // The HTTP Methods that will be automatically retried. + // Defaults to ['GET','PUT','HEAD','OPTIONS','DELETE'] + httpMethodsToRetry?: string[]; + + // The HTTP response status codes that will automatically be retried. + // Defaults to: [[100, 199], [408, 408], [429, 429], [500, 599]] + statusCodesToRetry?: number[][]; + + // Function to invoke when a retry attempt is made. + onRetryAttempt?: (err: GaxiosError) => Promise | void; + + // Function to invoke which determines if you should retry + shouldRetry?: (err: GaxiosError) => Promise | boolean; + + // When there is no response, the number of retries to attempt. Defaults to 2. + noResponseRetries?: number; + + // The amount of time to initially delay the retry, in ms. Defaults to 100ms. + retryDelay?: number; + }, + + // Enables default configuration for retries. + retry: boolean, + + // Cancelling a request requires the `abort-controller` library. + // See https://github.com/bitinn/node-fetch#request-cancellation-with-abortsignal + signal?: AbortSignal + + /** + * A collection of parts to send as a `Content-Type: multipart/related` request. + */ + multipart?: GaxiosMultipartOptions; + + /** + * An optional proxy to use for requests. + * Available via `process.env.HTTP_PROXY` and `process.env.HTTPS_PROXY` as well - with a preference for the this config option when multiple are available. + * The `agent` option overrides this. + * + * @see {@link GaxiosOptions.noProxy} + * @see {@link GaxiosOptions.agent} + */ + proxy?: string | URL; + /** + * A list for excluding traffic for proxies. + * Available via `process.env.NO_PROXY` as well as a common-separated list of strings - merged with any local `noProxy` rules. + * + * - When provided a string, it is matched by + * - Wildcard `*.` and `.` matching are available. (e.g. `.example.com` or `*.example.com`) + * - When provided a URL, it is matched by the `.origin` property. + * - For example, requesting `https://example.com` with the following `noProxy`s would result in a no proxy use: + * - new URL('https://example.com') + * - new URL('https://example.com:443') + * - The following would be used with a proxy: + * - new URL('http://example.com:80') + * - new URL('https://example.com:8443') + * - When provided a regular expression it is used to match the stringified URL + * + * @see {@link GaxiosOptions.proxy} + */ + noProxy?: (string | URL | RegExp)[]; + + /** + * An experimental, customizable error redactor. + * + * Set `false` to disable. + * + * @remarks + * + * This does not replace the requirement for an active Data Loss Prevention (DLP) provider. For DLP suggestions, see: + * - https://cloud.google.com/sensitive-data-protection/docs/redacting-sensitive-data#dlp_deidentify_replace_infotype-nodejs + * - https://cloud.google.com/sensitive-data-protection/docs/infotypes-reference#credentials_and_secrets + * + * @experimental + */ + errorRedactor?: typeof defaultErrorRedactor | false; +} +``` + +## License + +[Apache-2.0](https://github.com/googleapis/gaxios/blob/master/LICENSE) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/common.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/common.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..93589ac9e88ff8eee79c65234c58cc546714a8a0 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/common.d.ts @@ -0,0 +1,274 @@ +import { Agent } from 'http'; +import { URL } from 'url'; +import { Readable } from 'stream'; +/** + * Support `instanceof` operator for `GaxiosError`s in different versions of this library. + * + * @see {@link GaxiosError[Symbol.hasInstance]} + */ +export declare const GAXIOS_ERROR_SYMBOL: unique symbol; +export declare class GaxiosError extends Error { + config: GaxiosOptions; + response?: GaxiosResponse | undefined; + error?: (Error | NodeJS.ErrnoException) | undefined; + /** + * An Error code. + * See {@link https://nodejs.org/api/errors.html#errorcode error.code} + * + * @example + * 'ECONNRESET' + */ + code?: string; + /** + * An HTTP Status code. + * See {@link https://developer.mozilla.org/en-US/docs/Web/API/Response/status Response: status property} + * + * @example + * 500 + */ + status?: number; + /** + * Support `instanceof` operator for `GaxiosError` across builds/duplicated files. + * + * @see {@link GAXIOS_ERROR_SYMBOL} + * @see {@link GaxiosError[Symbol.hasInstance]} + * @see {@link https://github.com/microsoft/TypeScript/issues/13965#issuecomment-278570200} + * @see {@link https://stackoverflow.com/questions/46618852/require-and-instanceof} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance#reverting_to_default_instanceof_behavior} + */ + [GAXIOS_ERROR_SYMBOL]: string; + /** + * Support `instanceof` operator for `GaxiosError` across builds/duplicated files. + * + * @see {@link GAXIOS_ERROR_SYMBOL} + * @see {@link GaxiosError[GAXIOS_ERROR_SYMBOL]} + */ + static [Symbol.hasInstance](instance: unknown): boolean; + constructor(message: string, config: GaxiosOptions, response?: GaxiosResponse | undefined, error?: (Error | NodeJS.ErrnoException) | undefined); +} +export interface Headers { + [index: string]: any; +} +export type GaxiosPromise = Promise>; +export interface GaxiosXMLHttpRequest { + responseURL: string; +} +export interface GaxiosResponse { + config: GaxiosOptions; + data: T; + status: number; + statusText: string; + headers: Headers; + request: GaxiosXMLHttpRequest; +} +export interface GaxiosMultipartOptions { + headers: Headers; + content: string | Readable; +} +/** + * Request options that are used to form the request. + */ +export interface GaxiosOptions { + /** + * Optional method to override making the actual HTTP request. Useful + * for writing tests. + */ + adapter?: (options: GaxiosOptions, defaultAdapter: (options: GaxiosOptions) => GaxiosPromise) => GaxiosPromise; + url?: string | URL; + /** + * @deprecated + */ + baseUrl?: string; + baseURL?: string | URL; + method?: 'GET' | 'HEAD' | 'POST' | 'DELETE' | 'PUT' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'; + headers?: Headers; + data?: any; + body?: any; + /** + * The maximum size of the http response content in bytes allowed. + */ + maxContentLength?: number; + /** + * The maximum number of redirects to follow. Defaults to 20. + */ + maxRedirects?: number; + follow?: number; + /** + * A collection of parts to send as a `Content-Type: multipart/related` request. + */ + multipart?: GaxiosMultipartOptions[]; + params?: any; + paramsSerializer?: (params: { + [index: string]: string | number; + }) => string; + timeout?: number; + /** + * @deprecated ignored + */ + onUploadProgress?: (progressEvent: any) => void; + responseType?: 'arraybuffer' | 'blob' | 'json' | 'text' | 'stream' | 'unknown'; + agent?: Agent | ((parsedUrl: URL) => Agent); + validateStatus?: (status: number) => boolean; + retryConfig?: RetryConfig; + retry?: boolean; + signal?: any; + size?: number; + /** + * Implementation of `fetch` to use when making the API call. By default, + * will use the browser context if available, and fall back to `node-fetch` + * in node.js otherwise. + */ + fetchImplementation?: FetchImplementation; + cert?: string; + key?: string; + /** + * An optional proxy to use for requests. + * Available via `process.env.HTTP_PROXY` and `process.env.HTTPS_PROXY` as well - with a preference for the this config option when multiple are available. + * The {@link GaxiosOptions.agent `agent`} option overrides this. + * + * @see {@link GaxiosOptions.noProxy} + * @see {@link GaxiosOptions.agent} + */ + proxy?: string | URL; + /** + * A list for excluding traffic for proxies. + * Available via `process.env.NO_PROXY` as well as a common-separated list of strings - merged with any local `noProxy` rules. + * + * - When provided a string, it is matched by + * - Wildcard `*.` and `.` matching are available. (e.g. `.example.com` or `*.example.com`) + * - When provided a URL, it is matched by the `.origin` property. + * - For example, requesting `https://example.com` with the following `noProxy`s would result in a no proxy use: + * - new URL('https://example.com') + * - new URL('https://example.com:443') + * - The following would be used with a proxy: + * - new URL('http://example.com:80') + * - new URL('https://example.com:8443') + * - When provided a regular expression it is used to match the stringified URL + * + * @see {@link GaxiosOptions.proxy} + */ + noProxy?: (string | URL | RegExp)[]; + /** + * An experimental error redactor. + * + * @remarks + * + * This does not replace the requirement for an active Data Loss Prevention (DLP) provider. For DLP suggestions, see: + * - https://cloud.google.com/sensitive-data-protection/docs/redacting-sensitive-data#dlp_deidentify_replace_infotype-nodejs + * - https://cloud.google.com/sensitive-data-protection/docs/infotypes-reference#credentials_and_secrets + * + * @experimental + */ + errorRedactor?: typeof defaultErrorRedactor | false; +} +/** + * A partial object of `GaxiosResponse` with only redactable keys + * + * @experimental + */ +export type RedactableGaxiosOptions = Pick; +/** + * A partial object of `GaxiosResponse` with only redactable keys + * + * @experimental + */ +export type RedactableGaxiosResponse = Pick, 'config' | 'data' | 'headers'>; +/** + * Configuration for the Gaxios `request` method. + */ +export interface RetryConfig { + /** + * The number of times to retry the request. Defaults to 3. + */ + retry?: number; + /** + * The number of retries already attempted. + */ + currentRetryAttempt?: number; + /** + * The amount of time to initially delay the retry, in ms. Defaults to 100ms. + */ + retryDelay?: number; + /** + * The HTTP Methods that will be automatically retried. + * Defaults to ['GET','PUT','HEAD','OPTIONS','DELETE'] + */ + httpMethodsToRetry?: string[]; + /** + * The HTTP response status codes that will automatically be retried. + * Defaults to: [[100, 199], [408, 408], [429, 429], [500, 599]] + */ + statusCodesToRetry?: number[][]; + /** + * Function to invoke when a retry attempt is made. + */ + onRetryAttempt?: (err: GaxiosError) => Promise | void; + /** + * Function to invoke which determines if you should retry + */ + shouldRetry?: (err: GaxiosError) => Promise | boolean; + /** + * When there is no response, the number of retries to attempt. Defaults to 2. + */ + noResponseRetries?: number; + /** + * Function to invoke which returns a promise. After the promise resolves, + * the retry will be triggered. If provided, this will be used in-place of + * the `retryDelay` + */ + retryBackoff?: (err: GaxiosError, defaultBackoffMs: number) => Promise; + /** + * Time that the initial request was made. Users should not set this directly. + */ + timeOfFirstRequest?: number; + /** + * The length of time to keep retrying in ms. The last sleep period will + * be shortened as necessary, so that the last retry runs at deadline (and not + * considerably beyond it). The total time starting from when the initial + * request is sent, after which an error will be returned, regardless of the + * retrying attempts made meanwhile. Defaults to Number.MAX_SAFE_INTEGER indicating to effectively + * ignore totalTimeout. + */ + totalTimeout?: number; + maxRetryDelay?: number; + retryDelayMultiplier?: number; +} +export type FetchImplementation = (input: FetchRequestInfo, init?: FetchRequestInit) => Promise; +export type FetchRequestInfo = any; +export interface FetchResponse { + readonly status: number; + readonly statusText: string; + readonly url: string; + readonly body: unknown | null; + arrayBuffer(): Promise; + blob(): Promise; + readonly headers: FetchHeaders; + json(): Promise; + text(): Promise; +} +export interface FetchRequestInit { + method?: string; +} +export interface FetchHeaders { + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + has(name: string): boolean; + set(name: string, value: string): void; + forEach(callbackfn: (value: string, key: string) => void, thisArg?: any): void; +} +/** + * An experimental error redactor. + * + * @param config Config to potentially redact properties of + * @param response Config to potentially redact properties of + * + * @experimental + */ +export declare function defaultErrorRedactor(data: { + config?: RedactableGaxiosOptions; + response?: RedactableGaxiosResponse; +}): { + config?: RedactableGaxiosOptions; + response?: RedactableGaxiosResponse; +}; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/common.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/common.js new file mode 100644 index 0000000000000000000000000000000000000000..4e9dceae3f03f102f659aeb1619a484388416e77 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/common.js @@ -0,0 +1,188 @@ +"use strict"; +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +var _a; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GaxiosError = exports.GAXIOS_ERROR_SYMBOL = void 0; +exports.defaultErrorRedactor = defaultErrorRedactor; +const url_1 = require("url"); +const util_1 = require("./util"); +const extend_1 = __importDefault(require("extend")); +/** + * Support `instanceof` operator for `GaxiosError`s in different versions of this library. + * + * @see {@link GaxiosError[Symbol.hasInstance]} + */ +exports.GAXIOS_ERROR_SYMBOL = Symbol.for(`${util_1.pkg.name}-gaxios-error`); +/* eslint-disable-next-line @typescript-eslint/no-explicit-any */ +class GaxiosError extends Error { + /** + * Support `instanceof` operator for `GaxiosError` across builds/duplicated files. + * + * @see {@link GAXIOS_ERROR_SYMBOL} + * @see {@link GaxiosError[GAXIOS_ERROR_SYMBOL]} + */ + static [(_a = exports.GAXIOS_ERROR_SYMBOL, Symbol.hasInstance)](instance) { + if (instance && + typeof instance === 'object' && + exports.GAXIOS_ERROR_SYMBOL in instance && + instance[exports.GAXIOS_ERROR_SYMBOL] === util_1.pkg.version) { + return true; + } + // fallback to native + return Function.prototype[Symbol.hasInstance].call(GaxiosError, instance); + } + constructor(message, config, response, error) { + var _b; + super(message); + this.config = config; + this.response = response; + this.error = error; + /** + * Support `instanceof` operator for `GaxiosError` across builds/duplicated files. + * + * @see {@link GAXIOS_ERROR_SYMBOL} + * @see {@link GaxiosError[Symbol.hasInstance]} + * @see {@link https://github.com/microsoft/TypeScript/issues/13965#issuecomment-278570200} + * @see {@link https://stackoverflow.com/questions/46618852/require-and-instanceof} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance#reverting_to_default_instanceof_behavior} + */ + this[_a] = util_1.pkg.version; + // deep-copy config as we do not want to mutate + // the existing config for future retries/use + this.config = (0, extend_1.default)(true, {}, config); + if (this.response) { + this.response.config = (0, extend_1.default)(true, {}, this.response.config); + } + if (this.response) { + try { + this.response.data = translateData(this.config.responseType, (_b = this.response) === null || _b === void 0 ? void 0 : _b.data); + } + catch (_c) { + // best effort - don't throw an error within an error + // we could set `this.response.config.responseType = 'unknown'`, but + // that would mutate future calls with this config object. + } + this.status = this.response.status; + } + if (error && 'code' in error && error.code) { + this.code = error.code; + } + if (config.errorRedactor) { + config.errorRedactor({ + config: this.config, + response: this.response, + }); + } + } +} +exports.GaxiosError = GaxiosError; +function translateData(responseType, data) { + switch (responseType) { + case 'stream': + return data; + case 'json': + return JSON.parse(JSON.stringify(data)); + case 'arraybuffer': + return JSON.parse(Buffer.from(data).toString('utf8')); + case 'blob': + return JSON.parse(data.text()); + default: + return data; + } +} +/** + * An experimental error redactor. + * + * @param config Config to potentially redact properties of + * @param response Config to potentially redact properties of + * + * @experimental + */ +function defaultErrorRedactor(data) { + const REDACT = '< - See `errorRedactor` option in `gaxios` for configuration>.'; + function redactHeaders(headers) { + if (!headers) + return; + for (const key of Object.keys(headers)) { + // any casing of `Authentication` + if (/^authentication$/i.test(key)) { + headers[key] = REDACT; + } + // any casing of `Authorization` + if (/^authorization$/i.test(key)) { + headers[key] = REDACT; + } + // anything containing secret, such as 'client secret' + if (/secret/i.test(key)) { + headers[key] = REDACT; + } + } + } + function redactString(obj, key) { + if (typeof obj === 'object' && + obj !== null && + typeof obj[key] === 'string') { + const text = obj[key]; + if (/grant_type=/i.test(text) || + /assertion=/i.test(text) || + /secret/i.test(text)) { + obj[key] = REDACT; + } + } + } + function redactObject(obj) { + if (typeof obj === 'object' && obj !== null) { + if ('grant_type' in obj) { + obj['grant_type'] = REDACT; + } + if ('assertion' in obj) { + obj['assertion'] = REDACT; + } + if ('client_secret' in obj) { + obj['client_secret'] = REDACT; + } + } + } + if (data.config) { + redactHeaders(data.config.headers); + redactString(data.config, 'data'); + redactObject(data.config.data); + redactString(data.config, 'body'); + redactObject(data.config.body); + try { + const url = new url_1.URL('', data.config.url); + if (url.searchParams.has('token')) { + url.searchParams.set('token', REDACT); + } + if (url.searchParams.has('client_secret')) { + url.searchParams.set('client_secret', REDACT); + } + data.config.url = url.toString(); + } + catch (_b) { + // ignore error - no need to parse an invalid URL + } + } + if (data.response) { + defaultErrorRedactor({ config: data.response.config }); + redactHeaders(data.response.headers); + redactString(data.response, 'data'); + redactObject(data.response.data); + } + return data; +} +//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/common.js.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/common.js.map new file mode 100644 index 0000000000000000000000000000000000000000..4ee2d43221fa83855f9c5d7f58d8eec0a466a388 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common.js","sourceRoot":"","sources":["../../src/common.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;;;;;AAwZjC,oDAiGC;AAtfD,6BAAwB;AAExB,iCAA2B;AAC3B,oDAA4B;AAG5B;;;;GAIG;AACU,QAAA,mBAAmB,GAAG,MAAM,CAAC,GAAG,CAAC,GAAG,UAAG,CAAC,IAAI,eAAe,CAAC,CAAC;AAE1E,iEAAiE;AACjE,MAAa,WAAqB,SAAQ,KAAK;IA6B7C;;;;;OAKG;IACH,MAAM,CAAC,OARN,2BAAmB,EAQZ,MAAM,CAAC,WAAW,EAAC,CAAC,QAAiB;QAC3C,IACE,QAAQ;YACR,OAAO,QAAQ,KAAK,QAAQ;YAC5B,2BAA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/genai/node_modules/gaxios/build/src/gaxios.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/gaxios.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..031d4b7050ff78760bf1981f44e0f8f2dca6ae3f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/gaxios.d.ts @@ -0,0 +1,62 @@ +import { Agent } from 'http'; +import { URL } from 'url'; +import { GaxiosOptions, GaxiosPromise, GaxiosResponse } from './common'; +import { GaxiosInterceptorManager } from './interceptor'; +export declare class Gaxios { + #private; + protected agentCache: Map Agent)>; + /** + * Default HTTP options that will be used for every HTTP request. + */ + defaults: GaxiosOptions; + /** + * Interceptors + */ + interceptors: { + request: GaxiosInterceptorManager; + response: GaxiosInterceptorManager; + }; + /** + * The Gaxios class is responsible for making HTTP requests. + * @param defaults The default set of options to be used for this instance. + */ + constructor(defaults?: GaxiosOptions); + /** + * Perform an HTTP request with the given options. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + request(opts?: GaxiosOptions): GaxiosPromise; + private _defaultAdapter; + /** + * Internal, retryable version of the `request` method. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + protected _request(opts?: GaxiosOptions): GaxiosPromise; + private getResponseData; + /** + * By default, throw for any non-2xx status code + * @param status status code from the HTTP response + */ + private validateStatus; + /** + * Encode a set of key/value pars into a querystring format (?foo=bar&baz=boo) + * @param params key value pars to encode + */ + private paramsSerializer; + private translateResponse; + /** + * Attempts to parse a response by looking at the Content-Type header. + * @param {FetchResponse} response the HTTP response. + * @returns {Promise} a promise that resolves to the response data. + */ + private getResponseDataFromContentType; + /** + * Creates an async generator that yields the pieces of a multipart/related request body. + * This implementation follows the spec: https://www.ietf.org/rfc/rfc2387.txt. However, recursive + * multipart/related requests are not currently supported. + * + * @param {GaxioMultipartOptions[]} multipartOptions the pieces to turn into a multipart/related body. + * @param {string} boundary the boundary string to be placed between each part. + */ + private getMultipartRequest; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/gaxios.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/gaxios.js new file mode 100644 index 0000000000000000000000000000000000000000..b9fc1c0978857f2dcb954ce154049b74858e5dcd --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/gaxios.js @@ -0,0 +1,480 @@ +"use strict"; +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +var _Gaxios_instances, _a, _Gaxios_urlMayUseProxy, _Gaxios_applyRequestInterceptors, _Gaxios_applyResponseInterceptors, _Gaxios_prepareRequest, _Gaxios_proxyAgent, _Gaxios_getProxyAgent; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Gaxios = void 0; +const extend_1 = __importDefault(require("extend")); +const https_1 = require("https"); +const node_fetch_1 = __importDefault(require("node-fetch")); +const querystring_1 = __importDefault(require("querystring")); +const is_stream_1 = __importDefault(require("is-stream")); +const url_1 = require("url"); +const common_1 = require("./common"); +const retry_1 = require("./retry"); +const stream_1 = require("stream"); +const uuid_1 = require("uuid"); +const interceptor_1 = require("./interceptor"); +/* eslint-disable @typescript-eslint/no-explicit-any */ +const fetch = hasFetch() ? window.fetch : node_fetch_1.default; +function hasWindow() { + return typeof window !== 'undefined' && !!window; +} +function hasFetch() { + return hasWindow() && !!window.fetch; +} +function hasBuffer() { + return typeof Buffer !== 'undefined'; +} +function hasHeader(options, header) { + return !!getHeader(options, header); +} +function getHeader(options, header) { + header = header.toLowerCase(); + for (const key of Object.keys((options === null || options === void 0 ? void 0 : options.headers) || {})) { + if (header === key.toLowerCase()) { + return options.headers[key]; + } + } + return undefined; +} +class Gaxios { + /** + * The Gaxios class is responsible for making HTTP requests. + * @param defaults The default set of options to be used for this instance. + */ + constructor(defaults) { + _Gaxios_instances.add(this); + this.agentCache = new Map(); + this.defaults = defaults || {}; + this.interceptors = { + request: new interceptor_1.GaxiosInterceptorManager(), + response: new interceptor_1.GaxiosInterceptorManager(), + }; + } + /** + * Perform an HTTP request with the given options. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + async request(opts = {}) { + opts = await __classPrivateFieldGet(this, _Gaxios_instances, "m", _Gaxios_prepareRequest).call(this, opts); + opts = await __classPrivateFieldGet(this, _Gaxios_instances, "m", _Gaxios_applyRequestInterceptors).call(this, opts); + return __classPrivateFieldGet(this, _Gaxios_instances, "m", _Gaxios_applyResponseInterceptors).call(this, this._request(opts)); + } + async _defaultAdapter(opts) { + const fetchImpl = opts.fetchImplementation || fetch; + const res = (await fetchImpl(opts.url, opts)); + const data = await this.getResponseData(opts, res); + return this.translateResponse(opts, res, data); + } + /** + * Internal, retryable version of the `request` method. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + async _request(opts = {}) { + var _b; + try { + let translatedResponse; + if (opts.adapter) { + translatedResponse = await opts.adapter(opts, this._defaultAdapter.bind(this)); + } + else { + translatedResponse = await this._defaultAdapter(opts); + } + if (!opts.validateStatus(translatedResponse.status)) { + if (opts.responseType === 'stream') { + let response = ''; + await new Promise(resolve => { + (translatedResponse === null || translatedResponse === void 0 ? void 0 : translatedResponse.data).on('data', chunk => { + response += chunk; + }); + (translatedResponse === null || translatedResponse === void 0 ? void 0 : translatedResponse.data).on('end', resolve); + }); + translatedResponse.data = response; + } + throw new common_1.GaxiosError(`Request failed with status code ${translatedResponse.status}`, opts, translatedResponse); + } + return translatedResponse; + } + catch (e) { + const err = e instanceof common_1.GaxiosError + ? e + : new common_1.GaxiosError(e.message, opts, undefined, e); + const { shouldRetry, config } = await (0, retry_1.getRetryConfig)(err); + if (shouldRetry && config) { + err.config.retryConfig.currentRetryAttempt = + config.retryConfig.currentRetryAttempt; + // The error's config could be redacted - therefore we only want to + // copy the retry state over to the existing config + opts.retryConfig = (_b = err.config) === null || _b === void 0 ? void 0 : _b.retryConfig; + return this._request(opts); + } + throw err; + } + } + async getResponseData(opts, res) { + switch (opts.responseType) { + case 'stream': + return res.body; + case 'json': { + let data = await res.text(); + try { + data = JSON.parse(data); + } + catch (_b) { + // continue + } + return data; + } + case 'arraybuffer': + return res.arrayBuffer(); + case 'blob': + return res.blob(); + case 'text': + return res.text(); + default: + return this.getResponseDataFromContentType(res); + } + } + /** + * By default, throw for any non-2xx status code + * @param status status code from the HTTP response + */ + validateStatus(status) { + return status >= 200 && status < 300; + } + /** + * Encode a set of key/value pars into a querystring format (?foo=bar&baz=boo) + * @param params key value pars to encode + */ + paramsSerializer(params) { + return querystring_1.default.stringify(params); + } + translateResponse(opts, res, data) { + // headers need to be converted from a map to an obj + const headers = {}; + res.headers.forEach((value, key) => { + headers[key] = value; + }); + return { + config: opts, + data: data, + headers, + status: res.status, + statusText: res.statusText, + // XMLHttpRequestLike + request: { + responseURL: res.url, + }, + }; + } + /** + * Attempts to parse a response by looking at the Content-Type header. + * @param {FetchResponse} response the HTTP response. + * @returns {Promise} a promise that resolves to the response data. + */ + async getResponseDataFromContentType(response) { + let contentType = response.headers.get('Content-Type'); + if (contentType === null) { + // Maintain existing functionality by calling text() + return response.text(); + } + contentType = contentType.toLowerCase(); + if (contentType.includes('application/json')) { + let data = await response.text(); + try { + data = JSON.parse(data); + } + catch (_b) { + // continue + } + return data; + } + else if (contentType.match(/^text\//)) { + return response.text(); + } + else { + // If the content type is something not easily handled, just return the raw data (blob) + return response.blob(); + } + } + /** + * Creates an async generator that yields the pieces of a multipart/related request body. + * This implementation follows the spec: https://www.ietf.org/rfc/rfc2387.txt. However, recursive + * multipart/related requests are not currently supported. + * + * @param {GaxioMultipartOptions[]} multipartOptions the pieces to turn into a multipart/related body. + * @param {string} boundary the boundary string to be placed between each part. + */ + async *getMultipartRequest(multipartOptions, boundary) { + const finale = `--${boundary}--`; + for (const currentPart of multipartOptions) { + const partContentType = currentPart.headers['Content-Type'] || 'application/octet-stream'; + const preamble = `--${boundary}\r\nContent-Type: ${partContentType}\r\n\r\n`; + yield preamble; + if (typeof currentPart.content === 'string') { + yield currentPart.content; + } + else { + yield* currentPart.content; + } + yield '\r\n'; + } + yield finale; + } +} +exports.Gaxios = Gaxios; +_a = Gaxios, _Gaxios_instances = new WeakSet(), _Gaxios_urlMayUseProxy = function _Gaxios_urlMayUseProxy(url, noProxy = []) { + var _b, _c; + const candidate = new url_1.URL(url); + const noProxyList = [...noProxy]; + const noProxyEnvList = ((_c = ((_b = process.env.NO_PROXY) !== null && _b !== void 0 ? _b : process.env.no_proxy)) === null || _c === void 0 ? void 0 : _c.split(',')) || []; + for (const rule of noProxyEnvList) { + noProxyList.push(rule.trim()); + } + for (const rule of noProxyList) { + // Match regex + if (rule instanceof RegExp) { + if (rule.test(candidate.toString())) { + return false; + } + } + // Match URL + else if (rule instanceof url_1.URL) { + if (rule.origin === candidate.origin) { + return false; + } + } + // Match string regex + else if (rule.startsWith('*.') || rule.startsWith('.')) { + const cleanedRule = rule.replace(/^\*\./, '.'); + if (candidate.hostname.endsWith(cleanedRule)) { + return false; + } + } + // Basic string match + else if (rule === candidate.origin || + rule === candidate.hostname || + rule === candidate.href) { + return false; + } + } + return true; +}, _Gaxios_applyRequestInterceptors = +/** + * Applies the request interceptors. The request interceptors are applied after the + * call to prepareRequest is completed. + * + * @param {GaxiosOptions} options The current set of options. + * + * @returns {Promise} Promise that resolves to the set of options or response after interceptors are applied. + */ +async function _Gaxios_applyRequestInterceptors(options) { + let promiseChain = Promise.resolve(options); + for (const interceptor of this.interceptors.request.values()) { + if (interceptor) { + promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected); + } + } + return promiseChain; +}, _Gaxios_applyResponseInterceptors = +/** + * Applies the response interceptors. The response interceptors are applied after the + * call to request is made. + * + * @param {GaxiosOptions} options The current set of options. + * + * @returns {Promise} Promise that resolves to the set of options or response after interceptors are applied. + */ +async function _Gaxios_applyResponseInterceptors(response) { + let promiseChain = Promise.resolve(response); + for (const interceptor of this.interceptors.response.values()) { + if (interceptor) { + promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected); + } + } + return promiseChain; +}, _Gaxios_prepareRequest = +/** + * Validates the options, merges them with defaults, and prepare request. + * + * @param options The original options passed from the client. + * @returns Prepared options, ready to make a request + */ +async function _Gaxios_prepareRequest(options) { + var _b, _c, _d, _e; + const opts = (0, extend_1.default)(true, {}, this.defaults, options); + if (!opts.url) { + throw new Error('URL is required.'); + } + // baseUrl has been deprecated, remove in 2.0 + const baseUrl = opts.baseUrl || opts.baseURL; + if (baseUrl) { + opts.url = baseUrl.toString() + opts.url; + } + opts.paramsSerializer = opts.paramsSerializer || this.paramsSerializer; + if (opts.params && Object.keys(opts.params).length > 0) { + let additionalQueryParams = opts.paramsSerializer(opts.params); + if (additionalQueryParams.startsWith('?')) { + additionalQueryParams = additionalQueryParams.slice(1); + } + const prefix = opts.url.toString().includes('?') ? '&' : '?'; + opts.url = opts.url + prefix + additionalQueryParams; + } + if (typeof options.maxContentLength === 'number') { + opts.size = options.maxContentLength; + } + if (typeof options.maxRedirects === 'number') { + opts.follow = options.maxRedirects; + } + opts.headers = opts.headers || {}; + if (opts.multipart === undefined && opts.data) { + const isFormData = typeof FormData === 'undefined' + ? false + : (opts === null || opts === void 0 ? void 0 : opts.data) instanceof FormData; + if (is_stream_1.default.readable(opts.data)) { + opts.body = opts.data; + } + else if (hasBuffer() && Buffer.isBuffer(opts.data)) { + // Do not attempt to JSON.stringify() a Buffer: + opts.body = opts.data; + if (!hasHeader(opts, 'Content-Type')) { + opts.headers['Content-Type'] = 'application/json'; + } + } + else if (typeof opts.data === 'object') { + // If www-form-urlencoded content type has been set, but data is + // provided as an object, serialize the content using querystring: + if (!isFormData) { + if (getHeader(opts, 'content-type') === + 'application/x-www-form-urlencoded') { + opts.body = opts.paramsSerializer(opts.data); + } + else { + // } else if (!(opts.data instanceof FormData)) { + if (!hasHeader(opts, 'Content-Type')) { + opts.headers['Content-Type'] = 'application/json'; + } + opts.body = JSON.stringify(opts.data); + } + } + } + else { + opts.body = opts.data; + } + } + else if (opts.multipart && opts.multipart.length > 0) { + // note: once the minimum version reaches Node 16, + // this can be replaced with randomUUID() function from crypto + // and the dependency on UUID removed + const boundary = (0, uuid_1.v4)(); + opts.headers['Content-Type'] = `multipart/related; boundary=${boundary}`; + const bodyStream = new stream_1.PassThrough(); + opts.body = bodyStream; + (0, stream_1.pipeline)(this.getMultipartRequest(opts.multipart, boundary), bodyStream, () => { }); + } + opts.validateStatus = opts.validateStatus || this.validateStatus; + opts.responseType = opts.responseType || 'unknown'; + if (!opts.headers['Accept'] && opts.responseType === 'json') { + opts.headers['Accept'] = 'application/json'; + } + opts.method = opts.method || 'GET'; + const proxy = opts.proxy || + ((_b = process === null || process === void 0 ? void 0 : process.env) === null || _b === void 0 ? void 0 : _b.HTTPS_PROXY) || + ((_c = process === null || process === void 0 ? void 0 : process.env) === null || _c === void 0 ? void 0 : _c.https_proxy) || + ((_d = process === null || process === void 0 ? void 0 : process.env) === null || _d === void 0 ? void 0 : _d.HTTP_PROXY) || + ((_e = process === null || process === void 0 ? void 0 : process.env) === null || _e === void 0 ? void 0 : _e.http_proxy); + const urlMayUseProxy = __classPrivateFieldGet(this, _Gaxios_instances, "m", _Gaxios_urlMayUseProxy).call(this, opts.url, opts.noProxy); + if (opts.agent) { + // don't do any of the following options - use the user-provided agent. + } + else if (proxy && urlMayUseProxy) { + const HttpsProxyAgent = await __classPrivateFieldGet(_a, _a, "m", _Gaxios_getProxyAgent).call(_a); + if (this.agentCache.has(proxy)) { + opts.agent = this.agentCache.get(proxy); + } + else { + opts.agent = new HttpsProxyAgent(proxy, { + cert: opts.cert, + key: opts.key, + }); + this.agentCache.set(proxy, opts.agent); + } + } + else if (opts.cert && opts.key) { + // Configure client for mTLS + if (this.agentCache.has(opts.key)) { + opts.agent = this.agentCache.get(opts.key); + } + else { + opts.agent = new https_1.Agent({ + cert: opts.cert, + key: opts.key, + }); + this.agentCache.set(opts.key, opts.agent); + } + } + if (typeof opts.errorRedactor !== 'function' && + opts.errorRedactor !== false) { + opts.errorRedactor = common_1.defaultErrorRedactor; + } + return opts; +}, _Gaxios_getProxyAgent = async function _Gaxios_getProxyAgent() { + __classPrivateFieldSet(this, _a, __classPrivateFieldGet(this, _a, "f", _Gaxios_proxyAgent) || (await Promise.resolve().then(() => __importStar(require('https-proxy-agent')))).HttpsProxyAgent, "f", _Gaxios_proxyAgent); + return __classPrivateFieldGet(this, _a, "f", _Gaxios_proxyAgent); +}; +/** + * A cache for the lazily-loaded proxy agent. + * + * Should use {@link Gaxios[#getProxyAgent]} to retrieve. + */ +// using `import` to dynamically import the types here +_Gaxios_proxyAgent = { value: void 0 }; +//# sourceMappingURL=gaxios.js.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/gaxios.js.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/gaxios.js.map new file mode 100644 index 0000000000000000000000000000000000000000..ff6e97f47272b9aa1520e4a29635d07e271ee7bd --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/gaxios.js.map @@ -0,0 +1 @@ +{"version":3,"file":"gaxios.js","sourceRoot":"","sources":["../../src/gaxios.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEjC,oDAA4B;AAE5B,iCAA0C;AAC1C,4DAAmC;AACnC,8DAA6B;AAC7B,0DAAiC;AACjC,6BAAwB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EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;QACzC,CAAC;IACH,CAAC;SAAM,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;QACjC,4BAA4B;QAC5B,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YAClC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC7C,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,KAAK,GAAG,IAAI,aAAU,CAAC;gBAC1B,IAAI,EAAE,IAAI,CAAC,IAAI;gBACf,GAAG,EAAE,IAAI,CAAC,GAAG;aACd,CAAC,CAAC;YACH,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;QAC5C,CAAC;IACH,CAAC;IAED,IACE,OAAO,IAAI,CAAC,aAAa,KAAK,UAAU;QACxC,IAAI,CAAC,aAAa,KAAK,KAAK,EAC5B,CAAC;QACD,IAAI,CAAC,aAAa,GAAG,6BAAoB,CAAC;IAC5C,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC,0BAkHM,KAAK;IACV,8FAAqB,CAAC,wDAAa,mBAAmB,GAAC,CAAC,CAAC,eAAe,0BAAA,CAAC;IAEzE,OAAO,uBAAA,IAAI,8BAAY,CAAC;AAC1B,CAAC;AAjBD;;;;GAIG;AACH,sDAAsD;AAC/C,sCAAW,CAAsD"} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bcc782103b63ac750862e0ace0d0fa15826b01d6 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/index.d.ts @@ -0,0 +1,15 @@ +import { GaxiosOptions } from './common'; +import { Gaxios } from './gaxios'; +export { GaxiosError, GaxiosPromise, GaxiosResponse, Headers, RetryConfig, } from './common'; +export { Gaxios, GaxiosOptions }; +export * from './interceptor'; +/** + * The default instance used when the `request` method is directly + * invoked. + */ +export declare const instance: Gaxios; +/** + * Make an HTTP request using the given options. + * @param opts Options for the request + */ +export declare function request(opts: GaxiosOptions): Promise>; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..cbda152229f396f9ca4da2dc7f19fd9ca7f03f6b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/index.js @@ -0,0 +1,48 @@ +"use strict"; +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.instance = exports.Gaxios = exports.GaxiosError = void 0; +exports.request = request; +const gaxios_1 = require("./gaxios"); +Object.defineProperty(exports, "Gaxios", { enumerable: true, get: function () { return gaxios_1.Gaxios; } }); +var common_1 = require("./common"); +Object.defineProperty(exports, "GaxiosError", { enumerable: true, get: function () { return common_1.GaxiosError; } }); +__exportStar(require("./interceptor"), exports); +/** + * The default instance used when the `request` method is directly + * invoked. + */ +exports.instance = new gaxios_1.Gaxios(); +/** + * Make an HTTP request using the given options. + * @param opts Options for the request + */ +async function request(opts) { + return exports.instance.request(opts); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/index.js.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..731822f1029f8c989c7b326c50ee77737585c441 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;;;;;;;;;;;;;;;AAyBjC,0BAEC;AAxBD,qCAAgC;AASxB,uFATA,eAAM,OASA;AAPd,mCAMkB;AALhB,qGAAA,WAAW,OAAA;AAOb,gDAA8B;AAE9B;;;GAGG;AACU,QAAA,QAAQ,GAAG,IAAI,eAAM,EAAE,CAAC;AAErC;;;GAGG;AACI,KAAK,UAAU,OAAO,CAAI,IAAmB;IAClD,OAAO,gBAAQ,CAAC,OAAO,CAAI,IAAI,CAAC,CAAC;AACnC,CAAC"} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/interceptor.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/interceptor.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..62ab938bd82bf04301d586d715cf6590d5450259 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/interceptor.d.ts @@ -0,0 +1,25 @@ +import { GaxiosError, GaxiosOptions, GaxiosResponse } from './common'; +/** + * Interceptors that can be run for requests or responses. These interceptors run asynchronously. + */ +export interface GaxiosInterceptor { + /** + * Function to be run when applying an interceptor. + * + * @param {T} configOrResponse The current configuration or response. + * @returns {Promise} Promise that resolves to the modified set of options or response. + */ + resolved?: (configOrResponse: T) => Promise; + /** + * Function to be run if the previous call to resolved throws / rejects or the request results in an invalid status + * as determined by the call to validateStatus. + * + * @param {GaxiosError} err The error thrown from the previously called resolved function. + */ + rejected?: (err: GaxiosError) => void; +} +/** + * Class to manage collections of GaxiosInterceptors for both requests and responses. + */ +export declare class GaxiosInterceptorManager extends Set | null> { +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/interceptor.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/interceptor.js new file mode 100644 index 0000000000000000000000000000000000000000..c5e632e92b959eb0c51a1dd3183af9b896f0b200 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/interceptor.js @@ -0,0 +1,22 @@ +"use strict"; +// Copyright 2024 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GaxiosInterceptorManager = void 0; +/** + * Class to manage collections of GaxiosInterceptors for both requests and responses. + */ +class GaxiosInterceptorManager extends Set { +} +exports.GaxiosInterceptorManager = GaxiosInterceptorManager; +//# sourceMappingURL=interceptor.js.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/interceptor.js.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/interceptor.js.map new file mode 100644 index 0000000000000000000000000000000000000000..cfd39c207e6aa68aef6973800add6e1c7290eb51 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/interceptor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"interceptor.js","sourceRoot":"","sources":["../../src/interceptor.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AAwBjC;;GAEG;AACH,MAAa,wBAEX,SAAQ,GAAgC;CAAG;AAF7C,4DAE6C"} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/retry.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/retry.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cfc5ee28ac2c78f0adcad005b200f898a41327e2 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/retry.d.ts @@ -0,0 +1,8 @@ +import { GaxiosError } from './common'; +export declare function getRetryConfig(err: GaxiosError): Promise<{ + shouldRetry: boolean; + config?: undefined; +} | { + shouldRetry: boolean; + config: import("./common").GaxiosOptions; +}>; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/retry.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/retry.js new file mode 100644 index 0000000000000000000000000000000000000000..16074a40c744c2ce5f117b82d31f29580b427994 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/retry.js @@ -0,0 +1,166 @@ +"use strict"; +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRetryConfig = getRetryConfig; +async function getRetryConfig(err) { + let config = getConfig(err); + if (!err || !err.config || (!config && !err.config.retry)) { + return { shouldRetry: false }; + } + config = config || {}; + config.currentRetryAttempt = config.currentRetryAttempt || 0; + config.retry = + config.retry === undefined || config.retry === null ? 3 : config.retry; + config.httpMethodsToRetry = config.httpMethodsToRetry || [ + 'GET', + 'HEAD', + 'PUT', + 'OPTIONS', + 'DELETE', + ]; + config.noResponseRetries = + config.noResponseRetries === undefined || config.noResponseRetries === null + ? 2 + : config.noResponseRetries; + config.retryDelayMultiplier = config.retryDelayMultiplier + ? config.retryDelayMultiplier + : 2; + config.timeOfFirstRequest = config.timeOfFirstRequest + ? config.timeOfFirstRequest + : Date.now(); + config.totalTimeout = config.totalTimeout + ? config.totalTimeout + : Number.MAX_SAFE_INTEGER; + config.maxRetryDelay = config.maxRetryDelay + ? config.maxRetryDelay + : Number.MAX_SAFE_INTEGER; + // If this wasn't in the list of status codes where we want + // to automatically retry, return. + const retryRanges = [ + // https://en.wikipedia.org/wiki/List_of_HTTP_status_codes + // 1xx - Retry (Informational, request still processing) + // 2xx - Do not retry (Success) + // 3xx - Do not retry (Redirect) + // 4xx - Do not retry (Client errors) + // 408 - Retry ("Request Timeout") + // 429 - Retry ("Too Many Requests") + // 5xx - Retry (Server errors) + [100, 199], + [408, 408], + [429, 429], + [500, 599], + ]; + config.statusCodesToRetry = config.statusCodesToRetry || retryRanges; + // Put the config back into the err + err.config.retryConfig = config; + // Determine if we should retry the request + const shouldRetryFn = config.shouldRetry || shouldRetryRequest; + if (!(await shouldRetryFn(err))) { + return { shouldRetry: false, config: err.config }; + } + const delay = getNextRetryDelay(config); + // We're going to retry! Incremenent the counter. + err.config.retryConfig.currentRetryAttempt += 1; + // Create a promise that invokes the retry after the backOffDelay + const backoff = config.retryBackoff + ? config.retryBackoff(err, delay) + : new Promise(resolve => { + setTimeout(resolve, delay); + }); + // Notify the user if they added an `onRetryAttempt` handler + if (config.onRetryAttempt) { + config.onRetryAttempt(err); + } + // Return the promise in which recalls Gaxios to retry the request + await backoff; + return { shouldRetry: true, config: err.config }; +} +/** + * Determine based on config if we should retry the request. + * @param err The GaxiosError passed to the interceptor. + */ +function shouldRetryRequest(err) { + var _a; + const config = getConfig(err); + // node-fetch raises an AbortError if signaled: + // https://github.com/bitinn/node-fetch#request-cancellation-with-abortsignal + if (err.name === 'AbortError' || ((_a = err.error) === null || _a === void 0 ? void 0 : _a.name) === 'AbortError') { + return false; + } + // If there's no config, or retries are disabled, return. + if (!config || config.retry === 0) { + return false; + } + // Check if this error has no response (ETIMEDOUT, ENOTFOUND, etc) + if (!err.response && + (config.currentRetryAttempt || 0) >= config.noResponseRetries) { + return false; + } + // Only retry with configured HttpMethods. + if (!err.config.method || + config.httpMethodsToRetry.indexOf(err.config.method.toUpperCase()) < 0) { + return false; + } + // If this wasn't in the list of status codes where we want + // to automatically retry, return. + if (err.response && err.response.status) { + let isInRange = false; + for (const [min, max] of config.statusCodesToRetry) { + const status = err.response.status; + if (status >= min && status <= max) { + isInRange = true; + break; + } + } + if (!isInRange) { + return false; + } + } + // If we are out of retry attempts, return + config.currentRetryAttempt = config.currentRetryAttempt || 0; + if (config.currentRetryAttempt >= config.retry) { + return false; + } + return true; +} +/** + * Acquire the raxConfig object from an GaxiosError if available. + * @param err The Gaxios error with a config object. + */ +function getConfig(err) { + if (err && err.config && err.config.retryConfig) { + return err.config.retryConfig; + } + return; +} +/** + * Gets the delay to wait before the next retry. + * + * @param {RetryConfig} config The current set of retry options + * @returns {number} the amount of ms to wait before the next retry attempt. + */ +function getNextRetryDelay(config) { + var _a; + // Calculate time to wait with exponential backoff. + // If this is the first retry, look for a configured retryDelay. + const retryDelay = config.currentRetryAttempt ? 0 : (_a = config.retryDelay) !== null && _a !== void 0 ? _a : 100; + // Formula: retryDelay + ((retryDelayMultiplier^currentRetryAttempt - 1 / 2) * 1000) + const calculatedDelay = retryDelay + + ((Math.pow(config.retryDelayMultiplier, config.currentRetryAttempt) - 1) / + 2) * + 1000; + const maxAllowableDelay = config.totalTimeout - (Date.now() - config.timeOfFirstRequest); + return Math.min(calculatedDelay, maxAllowableDelay, config.maxRetryDelay); +} +//# sourceMappingURL=retry.js.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/retry.js.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/retry.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b289e5d799814ed8c6017759cf6b80fcfcb5712f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/gen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AC,CAAC,MAAA,MAAM,CAAC,UAAU,mCAAI,GAAG,CAAC;IAC7E,oFAAoF;IACpF,MAAM,eAAe,GACnB,UAAU;QACV,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,oBAAqB,EAAE,MAAM,CAAC,mBAAoB,CAAC,GAAG,CAAC,CAAC;YACxE,CAAC,CAAC;YACF,IAAI,CAAC;IACT,MAAM,iBAAiB,GACrB,MAAM,CAAC,YAAa,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,MAAM,CAAC,kBAAmB,CAAC,CAAC;IAEnE,OAAO,IAAI,CAAC,GAAG,CAAC,eAAe,EAAE,iBAAiB,EAAE,MAAM,CAAC,aAAc,CAAC,CAAC;AAC7E,CAAC"} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/util.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/util.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..53d5b74ff6c62c6159e4bc86a2589291b3b4f6dc --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/util.d.ts @@ -0,0 +1,4 @@ +export declare const pkg: { + name: string; + version: string; +}; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/util.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/util.js new file mode 100644 index 0000000000000000000000000000000000000000..be4184488cda464c06c10ff984de5eae99db2094 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/util.js @@ -0,0 +1,17 @@ +"use strict"; +// Copyright 2023 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.pkg = void 0; +exports.pkg = require('../../package.json'); +//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/util.js.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/util.js.map new file mode 100644 index 0000000000000000000000000000000000000000..575083929f94eadee3a83e2d4b81d5b8d3d9a83d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/build/src/util.js.map @@ -0,0 +1 @@ +{"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/util.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AAEpB,QAAA,GAAG,GAGZ,OAAO,CAAC,oBAAoB,CAAC,CAAC"} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f47ade9a61aea8368c78f8ac5ced10091828717e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gaxios/package.json @@ -0,0 +1,96 @@ +{ + "name": "gaxios", + "version": "6.7.1", + "description": "A simple common HTTP client specifically for Google APIs and services.", + "main": "build/src/index.js", + "types": "build/src/index.d.ts", + "files": [ + "build/src" + ], + "scripts": { + "lint": "gts check", + "test": "c8 mocha build/test", + "presystem-test": "npm run compile", + "system-test": "mocha build/system-test --timeout 80000", + "compile": "tsc -p .", + "fix": "gts fix", + "prepare": "npm run compile", + "pretest": "npm run compile", + "webpack": "webpack", + "prebrowser-test": "npm run compile", + "browser-test": "node build/browser-test/browser-test-runner.js", + "docs": "compodoc src/", + "docs-test": "linkinator docs", + "predocs-test": "npm run docs", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + "prelint": "cd samples; npm link ../; npm install", + "clean": "gts clean", + "precompile": "gts clean" + }, + "repository": "googleapis/gaxios", + "keywords": [ + "google" + ], + "engines": { + "node": ">=14" + }, + "author": "Google, LLC", + "license": "Apache-2.0", + "devDependencies": { + "@babel/plugin-proposal-private-methods": "^7.18.6", + "@compodoc/compodoc": "1.1.19", + "@types/cors": "^2.8.6", + "@types/express": "^4.16.1", + "@types/extend": "^3.0.1", + "@types/mocha": "^9.0.0", + "@types/multiparty": "0.0.36", + "@types/mv": "^2.1.0", + "@types/ncp": "^2.0.1", + "@types/node": "^20.0.0", + "@types/node-fetch": "^2.5.7", + "@types/sinon": "^17.0.0", + "@types/tmp": "0.2.6", + "@types/uuid": "^10.0.0", + "abort-controller": "^3.0.0", + "assert": "^2.0.0", + "browserify": "^17.0.0", + "c8": "^8.0.0", + "cheerio": "1.0.0-rc.10", + "cors": "^2.8.5", + "execa": "^5.0.0", + "express": "^4.16.4", + "form-data": "^4.0.0", + "gts": "^5.0.0", + "is-docker": "^2.0.0", + "karma": "^6.0.0", + "karma-chrome-launcher": "^3.0.0", + "karma-coverage": "^2.0.0", + "karma-firefox-launcher": "^2.0.0", + "karma-mocha": "^2.0.0", + "karma-remap-coverage": "^0.1.5", + "karma-sourcemap-loader": "^0.4.0", + "karma-webpack": "5.0.0", + "linkinator": "^3.0.0", + "mocha": "^8.0.0", + "multiparty": "^4.2.1", + "mv": "^2.1.1", + "ncp": "^2.0.0", + "nock": "^13.0.0", + "null-loader": "^4.0.0", + "puppeteer": "^19.0.0", + "sinon": "^18.0.0", + "stream-browserify": "^3.0.0", + "tmp": "0.2.3", + "ts-loader": "^8.0.0", + "typescript": "^5.1.6", + "webpack": "^5.35.0", + "webpack-cli": "^4.0.0" + }, + "dependencies": { + "extend": "^3.0.2", + "https-proxy-agent": "^7.0.1", + "is-stream": "^2.0.0", + "node-fetch": "^2.6.9", + "uuid": "^9.0.1" + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/CHANGELOG.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..c82697f6c6b77ec180967fcb17ae050c8c6558e4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/CHANGELOG.md @@ -0,0 +1,463 @@ +# Changelog + +[npm history][1] + +[1]: https://www.npmjs.com/package/gcp-metadata?activeTab=versions + +## [6.1.1](https://github.com/googleapis/gcp-metadata/compare/v6.1.0...v6.1.1) (2025-01-30) + + +### Bug Fixes + +* Add extra logging for incorrect headers ([#637](https://github.com/googleapis/gcp-metadata/issues/637)) ([edafa87](https://github.com/googleapis/gcp-metadata/commit/edafa87e020ffe28983048de5da183ceb0483bfa)) +* Add extra logging for incorrect headers ([#637](https://github.com/googleapis/gcp-metadata/issues/637)) ([#647](https://github.com/googleapis/gcp-metadata/issues/647)) ([ccbb98e](https://github.com/googleapis/gcp-metadata/commit/ccbb98e3519496414ab654769072d3397153b4b2)) + +## [6.1.0](https://github.com/googleapis/gcp-metadata/compare/v6.0.0...v6.1.0) (2023-11-10) + + +### Features + +* Add `universe` metadata handler ([#596](https://github.com/googleapis/gcp-metadata/issues/596)) ([0c02016](https://github.com/googleapis/gcp-metadata/commit/0c02016756754cddde6c4402fac1ceb6a318e82d)) +* Bulk Metadata Requests ([#598](https://github.com/googleapis/gcp-metadata/issues/598)) ([0a51378](https://github.com/googleapis/gcp-metadata/commit/0a513788537173570f9910d368dd36717de7233b)) + + +### Bug Fixes + +* Repo Metadata ([#595](https://github.com/googleapis/gcp-metadata/issues/595)) ([470a872](https://github.com/googleapis/gcp-metadata/commit/470a8722df2b2fb2da1b076b73414d2e28a3ff4e)) + +## [6.0.0](https://github.com/googleapis/gcp-metadata/compare/v5.3.0...v6.0.0) (2023-07-17) + + +### ⚠ BREAKING CHANGES + +* upgrade to Node 14, and update gaxios, ts, and gts ([#571](https://github.com/googleapis/gcp-metadata/issues/571)) + +### Miscellaneous Chores + +* Upgrade to Node 14, and update gaxios, ts, and gts ([#571](https://github.com/googleapis/gcp-metadata/issues/571)) ([88ff3ff](https://github.com/googleapis/gcp-metadata/commit/88ff3ff3d9bd8be32126e7fe76cbf33e401f8db7)) + +## [5.3.0](https://github.com/googleapis/gcp-metadata/compare/v5.2.0...v5.3.0) (2023-06-28) + + +### Features + +* Metadata Server Detection Configuration ([#562](https://github.com/googleapis/gcp-metadata/issues/562)) ([8c7c715](https://github.com/googleapis/gcp-metadata/commit/8c7c715f1fc22ad65554a745a93915713ca6698f)) + +## [5.2.0](https://github.com/googleapis/gcp-metadata/compare/v5.1.0...v5.2.0) (2023-01-03) + + +### Features + +* Export `gcp-residency` tools ([#552](https://github.com/googleapis/gcp-metadata/issues/552)) ([ba9ae24](https://github.com/googleapis/gcp-metadata/commit/ba9ae24331b53199f81e97b6a88414050cfcf546)) + +## [5.1.0](https://github.com/googleapis/gcp-metadata/compare/v5.0.1...v5.1.0) (2022-12-07) + + +### Features + +* Extend GCP Residency Detection Support ([#528](https://github.com/googleapis/gcp-metadata/issues/528)) ([2b35bb0](https://github.com/googleapis/gcp-metadata/commit/2b35bb0e6fb1a18294aeeebba91a6bf7b400385a)) + +## [5.0.1](https://github.com/googleapis/gcp-metadata/compare/v5.0.0...v5.0.1) (2022-09-09) + + +### Bug Fixes + +* Remove pip install statements ([#1546](https://github.com/googleapis/gcp-metadata/issues/1546)) ([#529](https://github.com/googleapis/gcp-metadata/issues/529)) ([064c64c](https://github.com/googleapis/gcp-metadata/commit/064c64cec160ffe645e6946a5125960e3e269d7f)) + +## [5.0.0](https://github.com/googleapis/gcp-metadata/compare/v4.3.1...v5.0.0) (2022-04-22) + + +### ⚠ BREAKING CHANGES + +* drop node 10, update typescript to 4.6.3 (#519) + +### Build System + +* drop node 10, update typescript to 4.6.3 ([#519](https://github.com/googleapis/gcp-metadata/issues/519)) ([688749b](https://github.com/googleapis/gcp-metadata/commit/688749bc50407f3cd127a0b10ae09487d6fe5aea)) + +### [4.3.1](https://www.github.com/googleapis/gcp-metadata/compare/v4.3.0...v4.3.1) (2021-09-02) + + +### Bug Fixes + +* **build:** switch primary branch to main ([#481](https://www.github.com/googleapis/gcp-metadata/issues/481)) ([8a7965c](https://www.github.com/googleapis/gcp-metadata/commit/8a7965c47c077ef766e4b416358630c0b24b0af2)) + +## [4.3.0](https://www.github.com/googleapis/gcp-metadata/compare/v4.2.1...v4.3.0) (2021-06-10) + + +### Features + +* add `gcf-owl-bot[bot]` to `ignoreAuthors` ([#450](https://www.github.com/googleapis/gcp-metadata/issues/450)) ([6a0f9ad](https://www.github.com/googleapis/gcp-metadata/commit/6a0f9ad09b6d16370d08c5d60541ce3ef64a9f97)) + +### [4.2.1](https://www.github.com/googleapis/gcp-metadata/compare/v4.2.0...v4.2.1) (2020-10-29) + + +### Bug Fixes + +* **deps:** update dependency gaxios to v4 ([#420](https://www.github.com/googleapis/gcp-metadata/issues/420)) ([b99fb07](https://www.github.com/googleapis/gcp-metadata/commit/b99fb0764b8dbb8b083f73b8007816914db4f09a)) + +## [4.2.0](https://www.github.com/googleapis/gcp-metadata/compare/v4.1.4...v4.2.0) (2020-09-15) + + +### Features + +* add support for GCE_METADATA_HOST environment variable ([#406](https://www.github.com/googleapis/gcp-metadata/issues/406)) ([eaf128a](https://www.github.com/googleapis/gcp-metadata/commit/eaf128ad5afc4357cde72d19b017b9474c070fea)) + +### [4.1.4](https://www.github.com/googleapis/gcp-metadata/compare/v4.1.3...v4.1.4) (2020-07-15) + + +### Bug Fixes + +* **deps:** update dependency json-bigint to v1 ([#382](https://www.github.com/googleapis/gcp-metadata/issues/382)) ([ab4d8c3](https://www.github.com/googleapis/gcp-metadata/commit/ab4d8c3022903206d433bafc47c27815c6f85e36)) + +### [4.1.3](https://www.github.com/googleapis/gcp-metadata/compare/v4.1.2...v4.1.3) (2020-07-13) + + +### Bug Fixes + +* **deps:** update dependency json-bigint to ^0.4.0 ([#378](https://www.github.com/googleapis/gcp-metadata/issues/378)) ([b214280](https://www.github.com/googleapis/gcp-metadata/commit/b2142807928c8c032509277900d35fccd1023f0f)) + +### [4.1.2](https://www.github.com/googleapis/gcp-metadata/compare/v4.1.1...v4.1.2) (2020-07-10) + + +### Bug Fixes + +* **deps:** roll back dependency gcp-metadata to ^4.1.0 ([#373](https://www.github.com/googleapis/gcp-metadata/issues/373)) ([a45adef](https://www.github.com/googleapis/gcp-metadata/commit/a45adefd92418faa08c8a5014cedb844d1eb3ae6)) + +### [4.1.1](https://www.github.com/googleapis/gcp-metadata/compare/v4.1.0...v4.1.1) (2020-07-09) + + +### Bug Fixes + +* typeo in nodejs .gitattribute ([#371](https://www.github.com/googleapis/gcp-metadata/issues/371)) ([5b4bb1c](https://www.github.com/googleapis/gcp-metadata/commit/5b4bb1c85e67e3ef0a6d1ec2ea316d560e03092f)) + +## [4.1.0](https://www.github.com/googleapis/gcp-metadata/compare/v4.0.1...v4.1.0) (2020-05-05) + + +### Features + +* Introduces the GCE_METADATA_IP to allow using a different IP address for the GCE metadata server. ([#346](https://www.github.com/googleapis/gcp-metadata/issues/346)) ([ec0f82d](https://www.github.com/googleapis/gcp-metadata/commit/ec0f82d022b4b3aac95e94ee1d8e53cfac3b14a4)) + + +### Bug Fixes + +* do not check secondary host if GCE_METADATA_IP set ([#352](https://www.github.com/googleapis/gcp-metadata/issues/352)) ([64fa7d6](https://www.github.com/googleapis/gcp-metadata/commit/64fa7d68cbb76f455a3bfdcb27d58e7775eb789a)) +* warn rather than throwing when we fail to connect to metadata server ([#351](https://www.github.com/googleapis/gcp-metadata/issues/351)) ([754a6c0](https://www.github.com/googleapis/gcp-metadata/commit/754a6c07d1a72615cbb5ebf9ee04475a9a12f1c0)) + +### [4.0.1](https://www.github.com/googleapis/gcp-metadata/compare/v4.0.0...v4.0.1) (2020-04-14) + + +### Bug Fixes + +* **deps:** update dependency gaxios to v3 ([#326](https://www.github.com/googleapis/gcp-metadata/issues/326)) ([5667178](https://www.github.com/googleapis/gcp-metadata/commit/5667178429baff71ad5dab2a96f97f27b2106d57)) +* apache license URL ([#468](https://www.github.com/googleapis/gcp-metadata/issues/468)) ([#336](https://www.github.com/googleapis/gcp-metadata/issues/336)) ([195dcd2](https://www.github.com/googleapis/gcp-metadata/commit/195dcd2d227ba496949e7ec0dcd77e5b9269066c)) + +## [4.0.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.5.0...v4.0.0) (2020-03-19) + + +### ⚠ BREAKING CHANGES + +* typescript@3.7.x has breaking changes; compiler now targets es2015 +* drops Node 8 from engines field (#315) + +### Features + +* drops Node 8 from engines field ([#315](https://www.github.com/googleapis/gcp-metadata/issues/315)) ([acb6233](https://www.github.com/googleapis/gcp-metadata/commit/acb62337e8ba7f0b259ae4e553f19c5786207d84)) + + +### Build System + +* switch to latest typescirpt/gts ([#317](https://www.github.com/googleapis/gcp-metadata/issues/317)) ([fbb7158](https://www.github.com/googleapis/gcp-metadata/commit/fbb7158be62c9f1949b69079e35113be1e10495c)) + +## [3.5.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.4.0...v3.5.0) (2020-03-03) + + +### Features + +* add ECONNREFUSED to list of known errors for isAvailable() ([#309](https://www.github.com/googleapis/gcp-metadata/issues/309)) ([17ff6ea](https://www.github.com/googleapis/gcp-metadata/commit/17ff6ea361d02de31463532d4ab4040bf6276e0b)) + +## [3.4.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.3.1...v3.4.0) (2020-02-24) + + +### Features + +* significantly increase timeout if GCF environment detected ([#300](https://www.github.com/googleapis/gcp-metadata/issues/300)) ([8e507c6](https://www.github.com/googleapis/gcp-metadata/commit/8e507c645f69a11f508884b3181dc4414e579fcc)) + +### [3.3.1](https://www.github.com/googleapis/gcp-metadata/compare/v3.3.0...v3.3.1) (2020-01-30) + + +### Bug Fixes + +* **isAvailable:** handle EHOSTDOWN and EHOSTUNREACH error codes ([#291](https://www.github.com/googleapis/gcp-metadata/issues/291)) ([ba8d9f5](https://www.github.com/googleapis/gcp-metadata/commit/ba8d9f50eac6cf8b439c1b66c48ace146c75f6e2)) + +## [3.3.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.2.3...v3.3.0) (2019-12-16) + + +### Features + +* add environment variable for configuring environment detection ([#275](https://www.github.com/googleapis/gcp-metadata/issues/275)) ([580cfa4](https://www.github.com/googleapis/gcp-metadata/commit/580cfa4a5f5d0041aa09ae85cfc5a4575dd3957f)) +* cache response from isAvailable() method ([#274](https://www.github.com/googleapis/gcp-metadata/issues/274)) ([a05e13f](https://www.github.com/googleapis/gcp-metadata/commit/a05e13f1d1d61b1f9b9b1703bc37cdbdc022c93b)) + + +### Bug Fixes + +* fastFailMetadataRequest should not reject, if response already happened ([#273](https://www.github.com/googleapis/gcp-metadata/issues/273)) ([a6590c4](https://www.github.com/googleapis/gcp-metadata/commit/a6590c4fd8bc2dff3995c83d4c9175d5bd9f5e4a)) + +### [3.2.3](https://www.github.com/googleapis/gcp-metadata/compare/v3.2.2...v3.2.3) (2019-12-12) + + +### Bug Fixes + +* **deps:** pin TypeScript below 3.7.0 ([e4bf622](https://www.github.com/googleapis/gcp-metadata/commit/e4bf622e6654a51ddffc0921a15250130591db2f)) + +### [3.2.2](https://www.github.com/googleapis/gcp-metadata/compare/v3.2.1...v3.2.2) (2019-11-13) + + +### Bug Fixes + +* **docs:** add jsdoc-region-tag plugin ([#264](https://www.github.com/googleapis/gcp-metadata/issues/264)) ([af8362b](https://www.github.com/googleapis/gcp-metadata/commit/af8362b5a35d270af00cb3696bbf7344810e9b0c)) + +### [3.2.1](https://www.github.com/googleapis/gcp-metadata/compare/v3.2.0...v3.2.1) (2019-11-08) + + +### Bug Fixes + +* **deps:** update gaxios ([#257](https://www.github.com/googleapis/gcp-metadata/issues/257)) ([ba6e0b6](https://www.github.com/googleapis/gcp-metadata/commit/ba6e0b668635b4aa4ed10535ff021c02b2edf5ea)) + +## [3.2.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.1.0...v3.2.0) (2019-10-10) + + +### Features + +* add DEBUG_AUTH for digging into authentication issues ([#254](https://www.github.com/googleapis/gcp-metadata/issues/254)) ([804156d](https://www.github.com/googleapis/gcp-metadata/commit/804156d)) + +## [3.1.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.0.0...v3.1.0) (2019-10-07) + + +### Features + +* don't throw on ENETUNREACH ([#250](https://www.github.com/googleapis/gcp-metadata/issues/250)) ([88f2101](https://www.github.com/googleapis/gcp-metadata/commit/88f2101)) + +## [3.0.0](https://www.github.com/googleapis/gcp-metadata/compare/v2.0.4...v3.0.0) (2019-09-17) + + +### ⚠ BREAKING CHANGES + +* isAvailable now tries both DNS and IP, choosing whichever responds first (#239) + +### Features + +* isAvailable now tries both DNS and IP, choosing whichever responds first ([#239](https://www.github.com/googleapis/gcp-metadata/issues/239)) ([25bc116](https://www.github.com/googleapis/gcp-metadata/commit/25bc116)) + +### [2.0.4](https://www.github.com/googleapis/gcp-metadata/compare/v2.0.3...v2.0.4) (2019-09-13) + + +### Bug Fixes + +* IP address takes 15 seconds to timeout, vs., metadata returning immediately ([#235](https://www.github.com/googleapis/gcp-metadata/issues/235)) ([d04207b](https://www.github.com/googleapis/gcp-metadata/commit/d04207b)) +* use 3s timeout rather than 15 default ([#237](https://www.github.com/googleapis/gcp-metadata/issues/237)) ([231ca5c](https://www.github.com/googleapis/gcp-metadata/commit/231ca5c)) + +### [2.0.3](https://www.github.com/googleapis/gcp-metadata/compare/v2.0.2...v2.0.3) (2019-09-12) + + +### Bug Fixes + +* use IP for metadata server ([#233](https://www.github.com/googleapis/gcp-metadata/issues/233)) ([20a15cb](https://www.github.com/googleapis/gcp-metadata/commit/20a15cb)) + +### [2.0.2](https://www.github.com/googleapis/gcp-metadata/compare/v2.0.1...v2.0.2) (2019-08-26) + + +### Bug Fixes + +* allow calls with no request, add JSON proto ([#224](https://www.github.com/googleapis/gcp-metadata/issues/224)) ([dc758b1](https://www.github.com/googleapis/gcp-metadata/commit/dc758b1)) + +### [2.0.1](https://www.github.com/googleapis/gcp-metadata/compare/v2.0.0...v2.0.1) (2019-06-26) + + +### Bug Fixes + +* **docs:** make anchors work in jsdoc ([#212](https://www.github.com/googleapis/gcp-metadata/issues/212)) ([9174b43](https://www.github.com/googleapis/gcp-metadata/commit/9174b43)) + +## [2.0.0](https://www.github.com/googleapis/gcp-metadata/compare/v1.0.0...v2.0.0) (2019-05-07) + + +### Bug Fixes + +* **deps:** update dependency gaxios to v2 ([#191](https://www.github.com/googleapis/gcp-metadata/issues/191)) ([ac8c1ef](https://www.github.com/googleapis/gcp-metadata/commit/ac8c1ef)) + + +### Build System + +* upgrade engines field to >=8.10.0 ([#194](https://www.github.com/googleapis/gcp-metadata/issues/194)) ([97c23c8](https://www.github.com/googleapis/gcp-metadata/commit/97c23c8)) + + +### BREAKING CHANGES + +* upgrade engines field to >=8.10.0 (#194) + +## v1.0.0 + +02-14-2019 16:00 PST + +### Bug Fixes +- fix: ask gaxios for text and not json ([#152](https://github.com/googleapis/gcp-metadata/pull/152)) + +### Documentation +- docs: update links in contrib guide ([#168](https://github.com/googleapis/gcp-metadata/pull/168)) +- docs: add lint/fix example to contributing guide ([#160](https://github.com/googleapis/gcp-metadata/pull/160)) + +### Internal / Testing Changes +- build: use linkinator for docs test ([#166](https://github.com/googleapis/gcp-metadata/pull/166)) +- chore(deps): update dependency @types/tmp to v0.0.34 ([#167](https://github.com/googleapis/gcp-metadata/pull/167)) +- build: create docs test npm scripts ([#165](https://github.com/googleapis/gcp-metadata/pull/165)) +- test: run system tests on GCB ([#157](https://github.com/googleapis/gcp-metadata/pull/157)) +- build: test using @grpc/grpc-js in CI ([#164](https://github.com/googleapis/gcp-metadata/pull/164)) +- chore: move CONTRIBUTING.md to root ([#162](https://github.com/googleapis/gcp-metadata/pull/162)) +- chore(deps): update dependency gcx to v0.1.1 ([#159](https://github.com/googleapis/gcp-metadata/pull/159)) +- chore(deps): update dependency gcx to v0.1.0 ([#158](https://github.com/googleapis/gcp-metadata/pull/158)) +- chore(deps): update dependency gcx to v0.0.4 ([#155](https://github.com/googleapis/gcp-metadata/pull/155)) +- chore(deps): update dependency googleapis to v37 ([#156](https://github.com/googleapis/gcp-metadata/pull/156)) +- build: ignore googleapis.com in doc link check ([#153](https://github.com/googleapis/gcp-metadata/pull/153)) +- build: check broken links in generated docs ([#149](https://github.com/googleapis/gcp-metadata/pull/149)) +- chore(build): inject yoshi automation key ([#148](https://github.com/googleapis/gcp-metadata/pull/148)) + +## v0.9.3 + +12-10-2018 16:16 PST + +### Dependencies +- chore(deps): update dependency googleapis to v36 ([#135](https://github.com/googleapis/gcp-metadata/pull/135)) +- chore(deps): use gaxios for http requests ([#121](https://github.com/googleapis/gcp-metadata/pull/121)) +- chore(deps): update dependency gts to ^0.9.0 ([#123](https://github.com/googleapis/gcp-metadata/pull/123)) + +### Internal / Testing Changes +- fix(build): fix Kokoro release script ([#141](https://github.com/googleapis/gcp-metadata/pull/141)) +- Release v0.9.2 ([#140](https://github.com/googleapis/gcp-metadata/pull/140)) +- build: add Kokoro configs for autorelease ([#138](https://github.com/googleapis/gcp-metadata/pull/138)) +- Release gcp-metadata v0.9.1 ([#139](https://github.com/googleapis/gcp-metadata/pull/139)) +- chore: always nyc report before calling codecov ([#134](https://github.com/googleapis/gcp-metadata/pull/134)) +- chore: nyc ignore build/test by default ([#133](https://github.com/googleapis/gcp-metadata/pull/133)) +- Sync repo build files ([#131](https://github.com/googleapis/gcp-metadata/pull/131)) +- fix(build): fix system key decryption ([#128](https://github.com/googleapis/gcp-metadata/pull/128)) +- refactor: use execa, move post install test to system ([#127](https://github.com/googleapis/gcp-metadata/pull/127)) +- chore: add a synth.metadata +- test: add a system test ([#126](https://github.com/googleapis/gcp-metadata/pull/126)) +- chore: update eslintignore config ([#122](https://github.com/googleapis/gcp-metadata/pull/122)) +- chore: use latest npm on Windows ([#120](https://github.com/googleapis/gcp-metadata/pull/120)) +- chore: update CircleCI config ([#119](https://github.com/googleapis/gcp-metadata/pull/119)) +- chore: include build in eslintignore ([#115](https://github.com/googleapis/gcp-metadata/pull/115)) + +## v0.9.2 + +12-10-2018 14:01 PST + +- chore(deps): update dependency googleapis to v36 ([#135](https://github.com/googleapis/gcp-metadata/pull/135)) +- chore: always nyc report before calling codecov ([#134](https://github.com/googleapis/gcp-metadata/pull/134)) +- chore: nyc ignore build/test by default ([#133](https://github.com/googleapis/gcp-metadata/pull/133)) +- chore: Re-generated to pick up changes in the API or client library generator. ([#131](https://github.com/googleapis/gcp-metadata/pull/131)) +- fix(build): fix system key decryption ([#128](https://github.com/googleapis/gcp-metadata/pull/128)) +- chore(deps): use gaxios for http requests ([#121](https://github.com/googleapis/gcp-metadata/pull/121)) +- refactor: use execa, move post install test to system ([#127](https://github.com/googleapis/gcp-metadata/pull/127)) +- chore: add a synth.metadata +- test: add a system test ([#126](https://github.com/googleapis/gcp-metadata/pull/126)) +- chore(deps): update dependency gts to ^0.9.0 ([#123](https://github.com/googleapis/gcp-metadata/pull/123)) +- chore: update eslintignore config ([#122](https://github.com/googleapis/gcp-metadata/pull/122)) +- chore: use latest npm on Windows ([#120](https://github.com/googleapis/gcp-metadata/pull/120)) +- chore: update CircleCI config ([#119](https://github.com/googleapis/gcp-metadata/pull/119)) +- chore: include build in eslintignore ([#115](https://github.com/googleapis/gcp-metadata/pull/115)) +- build: add Kokoro configs for autorelease ([#138](https://github.com/googleapis/gcp-metadata/pull/138)) + +## v0.9.1 + +12-10-2018 11:53 PST + +- chore(deps): update dependency googleapis to v36 ([#135](https://github.com/googleapis/gcp-metadata/pull/135)) +- chore: always nyc report before calling codecov ([#134](https://github.com/googleapis/gcp-metadata/pull/134)) +- chore: nyc ignore build/test by default ([#133](https://github.com/googleapis/gcp-metadata/pull/133)) +- chore: Re-generated to pick up changes in the API or client library generator. ([#131](https://github.com/googleapis/gcp-metadata/pull/131)) +- fix(build): fix system key decryption ([#128](https://github.com/googleapis/gcp-metadata/pull/128)) +- chore(deps): use gaxios for http requests ([#121](https://github.com/googleapis/gcp-metadata/pull/121)) +- refactor: use execa, move post install test to system ([#127](https://github.com/googleapis/gcp-metadata/pull/127)) +- chore: add a synth.metadata +- test: add a system test ([#126](https://github.com/googleapis/gcp-metadata/pull/126)) +- chore(deps): update dependency gts to ^0.9.0 ([#123](https://github.com/googleapis/gcp-metadata/pull/123)) +- chore: update eslintignore config ([#122](https://github.com/googleapis/gcp-metadata/pull/122)) +- chore: use latest npm on Windows ([#120](https://github.com/googleapis/gcp-metadata/pull/120)) +- chore: update CircleCI config ([#119](https://github.com/googleapis/gcp-metadata/pull/119)) +- chore: include build in eslintignore ([#115](https://github.com/googleapis/gcp-metadata/pull/115)) + +## v0.9.0 + +10-26-2018 13:10 PDT + +- feat: allow custom headers ([#109](https://github.com/googleapis/gcp-metadata/pull/109)) +- chore: update issue templates ([#108](https://github.com/googleapis/gcp-metadata/pull/108)) +- chore: remove old issue template ([#106](https://github.com/googleapis/gcp-metadata/pull/106)) +- build: run tests on node11 ([#105](https://github.com/googleapis/gcp-metadata/pull/105)) +- chores(build): do not collect sponge.xml from windows builds ([#104](https://github.com/googleapis/gcp-metadata/pull/104)) +- chores(build): run codecov on continuous builds ([#102](https://github.com/googleapis/gcp-metadata/pull/102)) +- chore(deps): update dependency nock to v10 ([#103](https://github.com/googleapis/gcp-metadata/pull/103)) +- chore: update new issue template ([#101](https://github.com/googleapis/gcp-metadata/pull/101)) +- build: fix codecov uploading on Kokoro ([#97](https://github.com/googleapis/gcp-metadata/pull/97)) +- Update kokoro config ([#95](https://github.com/googleapis/gcp-metadata/pull/95)) +- Update CI config ([#93](https://github.com/googleapis/gcp-metadata/pull/93)) +- Update kokoro config ([#91](https://github.com/googleapis/gcp-metadata/pull/91)) +- Re-generate library using /synth.py ([#90](https://github.com/googleapis/gcp-metadata/pull/90)) +- test: remove appveyor config ([#89](https://github.com/googleapis/gcp-metadata/pull/89)) +- Update kokoro config ([#88](https://github.com/googleapis/gcp-metadata/pull/88)) +- Enable prefer-const in the eslint config ([#87](https://github.com/googleapis/gcp-metadata/pull/87)) +- Enable no-var in eslint ([#86](https://github.com/googleapis/gcp-metadata/pull/86)) + +### New Features + +A new option, `headers`, has been added to allow metadata queries to be sent with custom headers. + +## v0.8.0 + +**This release has breaking changes**. Please take care when upgrading to the latest version. + +#### Dropped support for Node.js 4.x and 9.x +This library is no longer tested against versions 4.x and 9.x of Node.js. Please upgrade to the latest supported LTS version! + +#### Return type of `instance()` and `project()` has changed +The `instance()` and `project()` methods are much more selective about which properties they will accept. + +The only accepted properties are `params` and `properties`. The `instance()` and `project()` methods also now directly return the data instead of a response object. + +#### Changes in how large number valued properties are handled + +Previously large number-valued properties were being silently losing precision when +returned by this library (as a number). In the cases where a number valued property +returned by the metadata service is too large to represent as a JavaScript number, we +will now return the value as a BigNumber (from the bignumber.js) library. Numbers that +do fit into the JavaScript number range will continue to be returned as numbers. +For more details see [#74](https://github.com/googleapis/gcp-metadata/pull/74). + +### Breaking Changes +- chore: drop support for node.js 4 and 9 ([#68](https://github.com/googleapis/gcp-metadata/pull/68)) +- fix: quarantine axios config ([#62](https://github.com/googleapis/gcp-metadata/pull/62)) + +### Implementation Changes +- fix: properly handle large numbers in responses ([#74](https://github.com/googleapis/gcp-metadata/pull/74)) + +### Dependencies +- chore(deps): update dependency pify to v4 ([#73](https://github.com/googleapis/gcp-metadata/pull/73)) + +### Internal / Testing Changes +- Move to the new github org ([#84](https://github.com/googleapis/gcp-metadata/pull/84)) +- Update CI config ([#83](https://github.com/googleapis/gcp-metadata/pull/83)) +- Retry npm install in CI ([#81](https://github.com/googleapis/gcp-metadata/pull/81)) +- Update CI config ([#79](https://github.com/googleapis/gcp-metadata/pull/79)) +- chore(deps): update dependency nyc to v13 ([#77](https://github.com/googleapis/gcp-metadata/pull/77)) +- add key for system tests +- increase kitchen test timeout +- add a lint npm script +- update npm scripts +- add a synth file and run it ([#75](https://github.com/googleapis/gcp-metadata/pull/75)) +- chore(deps): update dependency assert-rejects to v1 ([#72](https://github.com/googleapis/gcp-metadata/pull/72)) +- chore: ignore package-log.json ([#71](https://github.com/googleapis/gcp-metadata/pull/71)) +- chore: update renovate config ([#70](https://github.com/googleapis/gcp-metadata/pull/70)) +- test: throw on deprecation +- chore(deps): update dependency typescript to v3 ([#67](https://github.com/googleapis/gcp-metadata/pull/67)) +- chore: make it OSPO compliant ([#66](https://github.com/googleapis/gcp-metadata/pull/66)) +- chore(deps): update dependency gts to ^0.8.0 ([#65](https://github.com/googleapis/gcp-metadata/pull/65)) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/LICENSE b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/README.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d0c1b9d19157c1f79eae3728504bfcad8ff56dcd --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/README.md @@ -0,0 +1,235 @@ +[//]: # "This README.md file is auto-generated, all changes to this file will be lost." +[//]: # "To regenerate it, use `python -m synthtool`." +Google Cloud Platform logo + +# [GCP Metadata: Node.js Client](https://github.com/googleapis/gcp-metadata) + +[![release level](https://img.shields.io/badge/release%20level-stable-brightgreen.svg?style=flat)](https://cloud.google.com/terms/launch-stages) +[![npm version](https://img.shields.io/npm/v/gcp-metadata.svg)](https://www.npmjs.org/package/gcp-metadata) + + + + +Get the metadata from a Google Cloud Platform environment + + +A comprehensive list of changes in each version may be found in +[the CHANGELOG](https://github.com/googleapis/gcp-metadata/blob/main/CHANGELOG.md). + +* [GCP Metadata Node.js Client API Reference][client-docs] +* [GCP Metadata Documentation][product-docs] +* [github.com/googleapis/gcp-metadata](https://github.com/googleapis/gcp-metadata) + +Read more about the client libraries for Cloud APIs, including the older +Google APIs Client Libraries, in [Client Libraries Explained][explained]. + +[explained]: https://cloud.google.com/apis/docs/client-libraries-explained + +**Table of contents:** + + +* [Quickstart](#quickstart) + + * [Installing the client library](#installing-the-client-library) + * [Using the client library](#using-the-client-library) +* [Samples](#samples) +* [Versioning](#versioning) +* [Contributing](#contributing) +* [License](#license) + +## Quickstart + +### Installing the client library + +```bash +npm install gcp-metadata +``` + + +### Using the client library + +```javascript +const gcpMetadata = require('gcp-metadata'); + +async function quickstart() { + // check to see if this code can access a metadata server + const isAvailable = await gcpMetadata.isAvailable(); + console.log(`Is available: ${isAvailable}`); + + // Instance and Project level metadata will only be available if + // running inside of a Google Cloud compute environment such as + // Cloud Functions, App Engine, Kubernetes Engine, or Compute Engine. + // To learn more about the differences between instance and project + // level metadata, see: + // https://cloud.google.com/compute/docs/storing-retrieving-metadata#project-instance-metadata + if (isAvailable) { + // grab all top level metadata from the service + const instanceMetadata = await gcpMetadata.instance(); + console.log('Instance metadata:'); + console.log(instanceMetadata); + + // get all project level metadata + const projectMetadata = await gcpMetadata.project(); + console.log('Project metadata:'); + console.log(projectMetadata); + } +} + +quickstart(); + +``` + +#### Check to see if the metadata server is available +```js +const isAvailable = await gcpMetadata.isAvailable(); +``` + +#### Access all metadata + +```js +const data = await gcpMetadata.instance(); +console.log(data); // ... All metadata properties +``` + +#### Access specific properties +```js +const data = await gcpMetadata.instance('hostname'); +console.log(data); // ...Instance hostname +const projectId = await gcpMetadata.project('project-id'); +console.log(projectId); // ...Project ID of the running instance +``` + +#### Access nested properties with the relative path +```js +const data = await gcpMetadata.instance('service-accounts/default/email'); +console.log(data); // ...Email address of the Compute identity service account +``` + +#### Access specific properties with query parameters +```js +const data = await gcpMetadata.instance({ + property: 'tags', + params: { alt: 'text' } +}); +console.log(data) // ...Tags as newline-delimited list +``` + +#### Access with custom headers +```js +await gcpMetadata.instance({ + headers: { 'no-trace': '1' } +}); // ...Request is untraced +``` + +### Take care with large number valued properties + +In some cases number valued properties returned by the Metadata Service may be +too large to be representable as JavaScript numbers. In such cases we return +those values as `BigNumber` objects (from the [bignumber.js](https://github.com/MikeMcl/bignumber.js) library). Numbers +that fit within the JavaScript number range will be returned as normal number +values. + +```js +const id = await gcpMetadata.instance('id'); +console.log(id) // ... BigNumber { s: 1, e: 18, c: [ 45200, 31799277581759 ] } +console.log(id.toString()) // ... 4520031799277581759 +``` + +### Environment variables + +* `GCE_METADATA_HOST`: provide an alternate host or IP to perform lookup against (useful, for example, you're connecting through a custom proxy server). + + For example: + ``` + export GCE_METADATA_HOST='169.254.169.254' + ``` + +* `DETECT_GCP_RETRIES`: number representing number of retries that should be attempted on metadata lookup. + +* `DEBUG_AUTH`: emit debugging logs + +* `METADATA_SERVER_DETECTION`: configure desired metadata server availability check behavior. + + * `assume-present`: don't try to ping the metadata server, but assume it's present + * `none`: don't try to ping the metadata server, but don't try to use it either + * `bios-only`: treat the result of a BIOS probe as canonical (don't fall back to pinging) + * `ping-only`: skip the BIOS probe, and go straight to pinging + + +## Samples + +Samples are in the [`samples/`](https://github.com/googleapis/gcp-metadata/tree/main/samples) directory. Each sample's `README.md` has instructions for running its sample. + +| Sample | Source Code | Try it | +| --------------------------- | --------------------------------- | ------ | +| Quickstart | [source code](https://github.com/googleapis/gcp-metadata/blob/main/samples/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/gcp-metadata&page=editor&open_in_editor=samples/quickstart.js,samples/README.md) | + + + +The [GCP Metadata Node.js Client API Reference][client-docs] documentation +also contains samples. + +## Supported Node.js Versions + +Our client libraries follow the [Node.js release schedule](https://github.com/nodejs/release#release-schedule). +Libraries are compatible with all current _active_ and _maintenance_ versions of +Node.js. +If you are using an end-of-life version of Node.js, we recommend that you update +as soon as possible to an actively supported LTS version. + +Google's client libraries support legacy versions of Node.js runtimes on a +best-efforts basis with the following warnings: + +* Legacy versions are not tested in continuous integration. +* Some security patches and features cannot be backported. +* Dependencies cannot be kept up-to-date. + +Client libraries targeting some end-of-life versions of Node.js are available, and +can be installed through npm [dist-tags](https://docs.npmjs.com/cli/dist-tag). +The dist-tags follow the naming convention `legacy-(version)`. +For example, `npm install gcp-metadata@legacy-8` installs client libraries +for versions compatible with Node.js 8. + +## Versioning + +This library follows [Semantic Versioning](http://semver.org/). + + + +This library is considered to be **stable**. The code surface will not change in backwards-incompatible ways +unless absolutely necessary (e.g. because of critical security issues) or with +an extensive deprecation period. Issues and requests against **stable** libraries +are addressed with the highest priority. + + + + + + +More Information: [Google Cloud Platform Launch Stages][launch_stages] + +[launch_stages]: https://cloud.google.com/terms/launch-stages + +## Contributing + +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/gcp-metadata/blob/main/CONTRIBUTING.md). + +Please note that this `README.md`, the `samples/README.md`, +and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`) +are generated from a central template. To edit one of these files, make an edit +to its templates in +[directory](https://github.com/googleapis/synthtool). + +## License + +Apache Version 2.0 + +See [LICENSE](https://github.com/googleapis/gcp-metadata/blob/main/LICENSE) + +[client-docs]: https://cloud.google.com/nodejs/docs/reference/gcp-metadata/latest +[product-docs]: https://cloud.google.com/compute/docs/storing-retrieving-metadata +[shell_img]: https://gstatic.com/cloudssh/images/open-btn.png +[projects]: https://console.cloud.google.com/project +[billing]: https://support.google.com/cloud/answer/6293499#enable-billing + +[auth]: https://cloud.google.com/docs/authentication/external/set-up-adc-local diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/build/src/gcp-residency.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/build/src/gcp-residency.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f39896ffcfaab3e3a165ead792425bb9b06d0efc --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/build/src/gcp-residency.d.ts @@ -0,0 +1,57 @@ +/** + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Known paths unique to Google Compute Engine Linux instances + */ +export declare const GCE_LINUX_BIOS_PATHS: { + BIOS_DATE: string; + BIOS_VENDOR: string; +}; +/** + * Determines if the process is running on a Google Cloud Serverless environment (Cloud Run or Cloud Functions instance). + * + * Uses the: + * - {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}. + * - {@link https://cloud.google.com/functions/docs/env-var Cloud Functions environment variables}. + * + * @returns {boolean} `true` if the process is running on GCP serverless, `false` otherwise. + */ +export declare function isGoogleCloudServerless(): boolean; +/** + * Determines if the process is running on a Linux Google Compute Engine instance. + * + * @returns {boolean} `true` if the process is running on Linux GCE, `false` otherwise. + */ +export declare function isGoogleComputeEngineLinux(): boolean; +/** + * Determines if the process is running on a Google Compute Engine instance with a known + * MAC address. + * + * @returns {boolean} `true` if the process is running on GCE (as determined by MAC address), `false` otherwise. + */ +export declare function isGoogleComputeEngineMACAddress(): boolean; +/** + * Determines if the process is running on a Google Compute Engine instance. + * + * @returns {boolean} `true` if the process is running on GCE, `false` otherwise. + */ +export declare function isGoogleComputeEngine(): boolean; +/** + * Determines if the process is running on Google Cloud Platform. + * + * @returns {boolean} `true` if the process is running on GCP, `false` otherwise. + */ +export declare function detectGCPResidency(): boolean; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/build/src/gcp-residency.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/build/src/gcp-residency.js new file mode 100644 index 0000000000000000000000000000000000000000..83e7dbfa73c699432e3af4935d036d791c0066aa --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/build/src/gcp-residency.js @@ -0,0 +1,114 @@ +"use strict"; +/** + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GCE_LINUX_BIOS_PATHS = void 0; +exports.isGoogleCloudServerless = isGoogleCloudServerless; +exports.isGoogleComputeEngineLinux = isGoogleComputeEngineLinux; +exports.isGoogleComputeEngineMACAddress = isGoogleComputeEngineMACAddress; +exports.isGoogleComputeEngine = isGoogleComputeEngine; +exports.detectGCPResidency = detectGCPResidency; +const fs_1 = require("fs"); +const os_1 = require("os"); +/** + * Known paths unique to Google Compute Engine Linux instances + */ +exports.GCE_LINUX_BIOS_PATHS = { + BIOS_DATE: '/sys/class/dmi/id/bios_date', + BIOS_VENDOR: '/sys/class/dmi/id/bios_vendor', +}; +const GCE_MAC_ADDRESS_REGEX = /^42:01/; +/** + * Determines if the process is running on a Google Cloud Serverless environment (Cloud Run or Cloud Functions instance). + * + * Uses the: + * - {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}. + * - {@link https://cloud.google.com/functions/docs/env-var Cloud Functions environment variables}. + * + * @returns {boolean} `true` if the process is running on GCP serverless, `false` otherwise. + */ +function isGoogleCloudServerless() { + /** + * `CLOUD_RUN_JOB` is used for Cloud Run Jobs + * - See {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}. + * + * `FUNCTION_NAME` is used in older Cloud Functions environments: + * - See {@link https://cloud.google.com/functions/docs/env-var Python 3.7 and Go 1.11}. + * + * `K_SERVICE` is used in Cloud Run and newer Cloud Functions environments: + * - See {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}. + * - See {@link https://cloud.google.com/functions/docs/env-var Cloud Functions newer runtimes}. + */ + const isGFEnvironment = process.env.CLOUD_RUN_JOB || + process.env.FUNCTION_NAME || + process.env.K_SERVICE; + return !!isGFEnvironment; +} +/** + * Determines if the process is running on a Linux Google Compute Engine instance. + * + * @returns {boolean} `true` if the process is running on Linux GCE, `false` otherwise. + */ +function isGoogleComputeEngineLinux() { + if ((0, os_1.platform)() !== 'linux') + return false; + try { + // ensure this file exist + (0, fs_1.statSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_DATE); + // ensure this file exist and matches + const biosVendor = (0, fs_1.readFileSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR, 'utf8'); + return /Google/.test(biosVendor); + } + catch (_a) { + return false; + } +} +/** + * Determines if the process is running on a Google Compute Engine instance with a known + * MAC address. + * + * @returns {boolean} `true` if the process is running on GCE (as determined by MAC address), `false` otherwise. + */ +function isGoogleComputeEngineMACAddress() { + const interfaces = (0, os_1.networkInterfaces)(); + for (const item of Object.values(interfaces)) { + if (!item) + continue; + for (const { mac } of item) { + if (GCE_MAC_ADDRESS_REGEX.test(mac)) { + return true; + } + } + } + return false; +} +/** + * Determines if the process is running on a Google Compute Engine instance. + * + * @returns {boolean} `true` if the process is running on GCE, `false` otherwise. + */ +function isGoogleComputeEngine() { + return isGoogleComputeEngineLinux() || isGoogleComputeEngineMACAddress(); +} +/** + * Determines if the process is running on Google Cloud Platform. + * + * @returns {boolean} `true` if the process is running on GCP, `false` otherwise. + */ +function detectGCPResidency() { + return isGoogleCloudServerless() || isGoogleComputeEngine(); +} +//# sourceMappingURL=gcp-residency.js.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/build/src/gcp-residency.js.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/build/src/gcp-residency.js.map new file mode 100644 index 0000000000000000000000000000000000000000..e32c69fa0e459ae88f818752163d760296393677 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/build/src/gcp-residency.js.map @@ -0,0 +1 @@ +{"version":3,"file":"gcp-residency.js","sourceRoot":"","sources":["../../src/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,CAAC;YACzB,IAAI,qBAAqB,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;gBACpC,OAAO,IAAI,CAAC;YACd,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;GAIG;AACH,SAAgB,qBAAqB;IACnC,OAAO,0BAA0B,EAAE,IAAI,+BAA+B,EAAE,CAAC;AAC3E,CAAC;AAED;;;;GAIG;AACH,SAAgB,kBAAkB;IAChC,OAAO,uBAAuB,EAAE,IAAI,qBAAqB,EAAE,CAAC;AAC9D,CAAC"} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/build/src/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/build/src/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..25705e7feadd0e3e8901e1b6290ca9a59f4f4fd3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/build/src/index.d.ts @@ -0,0 +1,156 @@ +/** + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { OutgoingHttpHeaders } from 'http'; +export declare const BASE_PATH = "/computeMetadata/v1"; +export declare const HOST_ADDRESS = "http://169.254.169.254"; +export declare const SECONDARY_HOST_ADDRESS = "http://metadata.google.internal."; +export declare const HEADER_NAME = "Metadata-Flavor"; +export declare const HEADER_VALUE = "Google"; +export declare const HEADERS: Readonly<{ + "Metadata-Flavor": "Google"; +}>; +/** + * Metadata server detection override options. + * + * Available via `process.env.METADATA_SERVER_DETECTION`. + */ +export declare const METADATA_SERVER_DETECTION: Readonly<{ + 'assume-present': "don't try to ping the metadata server, but assume it's present"; + none: "don't try to ping the metadata server, but don't try to use it either"; + 'bios-only': "treat the result of a BIOS probe as canonical (don't fall back to pinging)"; + 'ping-only': "skip the BIOS probe, and go straight to pinging"; +}>; +export interface Options { + params?: { + [index: string]: string; + }; + property?: string; + headers?: OutgoingHttpHeaders; +} +export interface MetadataAccessor { + /** + * + * @example + * + * // equivalent to `project('project-id')`; + * const metadataKey = 'project/project-id'; + */ + metadataKey: string; + params?: Options['params']; + headers?: Options['headers']; + noResponseRetries?: number; + fastFail?: boolean; +} +export type BulkResults = { + [key in T[number]['metadataKey']]: ReturnType; +}; +/** + * Obtain metadata for the current GCE instance. + * + * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} + * + * @example + * ``` + * const serviceAccount: {} = await instance('service-accounts/'); + * const serviceAccountEmail: string = await instance('service-accounts/default/email'); + * ``` + */ +export declare function instance(options?: string | Options): Promise; +/** + * Obtain metadata for the current GCP project. + * + * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} + * + * @example + * ``` + * const projectId: string = await project('project-id'); + * const numericProjectId: number = await project('numeric-project-id'); + * ``` + */ +export declare function project(options?: string | Options): Promise; +/** + * Obtain metadata for the current universe. + * + * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} + * + * @example + * ``` + * const universeDomain: string = await universe('universe-domain'); + * ``` + */ +export declare function universe(options?: string | Options): Promise; +/** + * Retrieve metadata items in parallel. + * + * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} + * + * @example + * ``` + * const data = await bulk([ + * { + * metadataKey: 'instance', + * }, + * { + * metadataKey: 'project/project-id', + * }, + * ] as const); + * + * // data.instance; + * // data['project/project-id']; + * ``` + * + * @param properties The metadata properties to retrieve + * @returns The metadata in `metadatakey:value` format + */ +export declare function bulk[], R extends BulkResults = BulkResults>(properties: T): Promise; +/** + * Determine if the metadata server is currently available. + */ +export declare function isAvailable(): Promise; +/** + * reset the memoized isAvailable() lookup. + */ +export declare function resetIsAvailableCache(): void; +/** + * A cache for the detected GCP Residency. + */ +export declare let gcpResidencyCache: boolean | null; +/** + * Detects GCP Residency. + * Caches results to reduce costs for subsequent calls. + * + * @see setGCPResidency for setting + */ +export declare function getGCPResidency(): boolean; +/** + * Sets the detected GCP Residency. + * Useful for forcing metadata server detection behavior. + * + * Set `null` to autodetect the environment (default behavior). + * @see getGCPResidency for getting + */ +export declare function setGCPResidency(value?: boolean | null): void; +/** + * Obtain the timeout for requests to the metadata server. + * + * In certain environments and conditions requests can take longer than + * the default timeout to complete. This function will determine the + * appropriate timeout based on the environment. + * + * @returns {number} a request timeout duration in milliseconds. + */ +export declare function requestTimeout(): number; +export * from './gcp-residency'; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/build/src/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/build/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..134593628daaceb4f97340d6f0fffc7a930f5e72 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/build/src/index.js @@ -0,0 +1,408 @@ +"use strict"; +/** + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.gcpResidencyCache = exports.METADATA_SERVER_DETECTION = exports.HEADERS = exports.HEADER_VALUE = exports.HEADER_NAME = exports.SECONDARY_HOST_ADDRESS = exports.HOST_ADDRESS = exports.BASE_PATH = void 0; +exports.instance = instance; +exports.project = project; +exports.universe = universe; +exports.bulk = bulk; +exports.isAvailable = isAvailable; +exports.resetIsAvailableCache = resetIsAvailableCache; +exports.getGCPResidency = getGCPResidency; +exports.setGCPResidency = setGCPResidency; +exports.requestTimeout = requestTimeout; +const gaxios_1 = require("gaxios"); +const jsonBigint = require("json-bigint"); +const gcp_residency_1 = require("./gcp-residency"); +const logger = require("google-logging-utils"); +exports.BASE_PATH = '/computeMetadata/v1'; +exports.HOST_ADDRESS = 'http://169.254.169.254'; +exports.SECONDARY_HOST_ADDRESS = 'http://metadata.google.internal.'; +exports.HEADER_NAME = 'Metadata-Flavor'; +exports.HEADER_VALUE = 'Google'; +exports.HEADERS = Object.freeze({ [exports.HEADER_NAME]: exports.HEADER_VALUE }); +const log = logger.log('gcp metadata'); +/** + * Metadata server detection override options. + * + * Available via `process.env.METADATA_SERVER_DETECTION`. + */ +exports.METADATA_SERVER_DETECTION = Object.freeze({ + 'assume-present': "don't try to ping the metadata server, but assume it's present", + none: "don't try to ping the metadata server, but don't try to use it either", + 'bios-only': "treat the result of a BIOS probe as canonical (don't fall back to pinging)", + 'ping-only': 'skip the BIOS probe, and go straight to pinging', +}); +/** + * Returns the base URL while taking into account the GCE_METADATA_HOST + * environment variable if it exists. + * + * @returns The base URL, e.g., http://169.254.169.254/computeMetadata/v1. + */ +function getBaseUrl(baseUrl) { + if (!baseUrl) { + baseUrl = + process.env.GCE_METADATA_IP || + process.env.GCE_METADATA_HOST || + exports.HOST_ADDRESS; + } + // If no scheme is provided default to HTTP: + if (!/^https?:\/\//.test(baseUrl)) { + baseUrl = `http://${baseUrl}`; + } + return new URL(exports.BASE_PATH, baseUrl).href; +} +// Accepts an options object passed from the user to the API. In previous +// versions of the API, it referred to a `Request` or an `Axios` request +// options object. Now it refers to an object with very limited property +// names. This is here to help ensure users don't pass invalid options when +// they upgrade from 0.4 to 0.5 to 0.8. +function validate(options) { + Object.keys(options).forEach(key => { + switch (key) { + case 'params': + case 'property': + case 'headers': + break; + case 'qs': + throw new Error("'qs' is not a valid configuration option. Please use 'params' instead."); + default: + throw new Error(`'${key}' is not a valid configuration option.`); + } + }); +} +async function metadataAccessor(type, options = {}, noResponseRetries = 3, fastFail = false) { + let metadataKey = ''; + let params = {}; + let headers = {}; + if (typeof type === 'object') { + const metadataAccessor = type; + metadataKey = metadataAccessor.metadataKey; + params = metadataAccessor.params || params; + headers = metadataAccessor.headers || headers; + noResponseRetries = metadataAccessor.noResponseRetries || noResponseRetries; + fastFail = metadataAccessor.fastFail || fastFail; + } + else { + metadataKey = type; + } + if (typeof options === 'string') { + metadataKey += `/${options}`; + } + else { + validate(options); + if (options.property) { + metadataKey += `/${options.property}`; + } + headers = options.headers || headers; + params = options.params || params; + } + const requestMethod = fastFail ? fastFailMetadataRequest : gaxios_1.request; + const req = { + url: `${getBaseUrl()}/${metadataKey}`, + headers: { ...exports.HEADERS, ...headers }, + retryConfig: { noResponseRetries }, + params, + responseType: 'text', + timeout: requestTimeout(), + }; + log.info('instance request %j', req); + const res = await requestMethod(req); + log.info('instance metadata is %s', res.data); + // NOTE: node.js converts all incoming headers to lower case. + if (res.headers[exports.HEADER_NAME.toLowerCase()] !== exports.HEADER_VALUE) { + throw new Error(`Invalid response from metadata service: incorrect ${exports.HEADER_NAME} header. Expected '${exports.HEADER_VALUE}', got ${res.headers[exports.HEADER_NAME.toLowerCase()] ? `'${res.headers[exports.HEADER_NAME.toLowerCase()]}'` : 'no header'}`); + } + if (typeof res.data === 'string') { + try { + return jsonBigint.parse(res.data); + } + catch (_a) { + /* ignore */ + } + } + return res.data; +} +async function fastFailMetadataRequest(options) { + var _a; + const secondaryOptions = { + ...options, + url: (_a = options.url) === null || _a === void 0 ? void 0 : _a.toString().replace(getBaseUrl(), getBaseUrl(exports.SECONDARY_HOST_ADDRESS)), + }; + // We race a connection between DNS/IP to metadata server. There are a couple + // reasons for this: + // + // 1. the DNS is slow in some GCP environments; by checking both, we might + // detect the runtime environment signficantly faster. + // 2. we can't just check the IP, which is tarpitted and slow to respond + // on a user's local machine. + // + // Additional logic has been added to make sure that we don't create an + // unhandled rejection in scenarios where a failure happens sometime + // after a success. + // + // Note, however, if a failure happens prior to a success, a rejection should + // occur, this is for folks running locally. + // + let responded = false; + const r1 = (0, gaxios_1.request)(options) + .then(res => { + responded = true; + return res; + }) + .catch(err => { + if (responded) { + return r2; + } + else { + responded = true; + throw err; + } + }); + const r2 = (0, gaxios_1.request)(secondaryOptions) + .then(res => { + responded = true; + return res; + }) + .catch(err => { + if (responded) { + return r1; + } + else { + responded = true; + throw err; + } + }); + return Promise.race([r1, r2]); +} +/** + * Obtain metadata for the current GCE instance. + * + * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} + * + * @example + * ``` + * const serviceAccount: {} = await instance('service-accounts/'); + * const serviceAccountEmail: string = await instance('service-accounts/default/email'); + * ``` + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function instance(options) { + return metadataAccessor('instance', options); +} +/** + * Obtain metadata for the current GCP project. + * + * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} + * + * @example + * ``` + * const projectId: string = await project('project-id'); + * const numericProjectId: number = await project('numeric-project-id'); + * ``` + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function project(options) { + return metadataAccessor('project', options); +} +/** + * Obtain metadata for the current universe. + * + * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} + * + * @example + * ``` + * const universeDomain: string = await universe('universe-domain'); + * ``` + */ +function universe(options) { + return metadataAccessor('universe', options); +} +/** + * Retrieve metadata items in parallel. + * + * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} + * + * @example + * ``` + * const data = await bulk([ + * { + * metadataKey: 'instance', + * }, + * { + * metadataKey: 'project/project-id', + * }, + * ] as const); + * + * // data.instance; + * // data['project/project-id']; + * ``` + * + * @param properties The metadata properties to retrieve + * @returns The metadata in `metadatakey:value` format + */ +async function bulk(properties) { + const r = {}; + await Promise.all(properties.map(item => { + return (async () => { + const res = await metadataAccessor(item); + const key = item.metadataKey; + r[key] = res; + })(); + })); + return r; +} +/* + * How many times should we retry detecting GCP environment. + */ +function detectGCPAvailableRetries() { + return process.env.DETECT_GCP_RETRIES + ? Number(process.env.DETECT_GCP_RETRIES) + : 0; +} +let cachedIsAvailableResponse; +/** + * Determine if the metadata server is currently available. + */ +async function isAvailable() { + if (process.env.METADATA_SERVER_DETECTION) { + const value = process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase(); + if (!(value in exports.METADATA_SERVER_DETECTION)) { + throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${value}\`, but it should be \`${Object.keys(exports.METADATA_SERVER_DETECTION).join('`, `')}\`, or unset`); + } + switch (value) { + case 'assume-present': + return true; + case 'none': + return false; + case 'bios-only': + return getGCPResidency(); + case 'ping-only': + // continue, we want to ping the server + } + } + try { + // If a user is instantiating several GCP libraries at the same time, + // this may result in multiple calls to isAvailable(), to detect the + // runtime environment. We use the same promise for each of these calls + // to reduce the network load. + if (cachedIsAvailableResponse === undefined) { + cachedIsAvailableResponse = metadataAccessor('instance', undefined, detectGCPAvailableRetries(), + // If the default HOST_ADDRESS has been overridden, we should not + // make an effort to try SECONDARY_HOST_ADDRESS (as we are likely in + // a non-GCP environment): + !(process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST)); + } + await cachedIsAvailableResponse; + return true; + } + catch (e) { + const err = e; + if (process.env.DEBUG_AUTH) { + console.info(err); + } + if (err.type === 'request-timeout') { + // If running in a GCP environment, metadata endpoint should return + // within ms. + return false; + } + if (err.response && err.response.status === 404) { + return false; + } + else { + if (!(err.response && err.response.status === 404) && + // A warning is emitted if we see an unexpected err.code, or err.code + // is not populated: + (!err.code || + ![ + 'EHOSTDOWN', + 'EHOSTUNREACH', + 'ENETUNREACH', + 'ENOENT', + 'ENOTFOUND', + 'ECONNREFUSED', + ].includes(err.code))) { + let code = 'UNKNOWN'; + if (err.code) + code = err.code; + process.emitWarning(`received unexpected error = ${err.message} code = ${code}`, 'MetadataLookupWarning'); + } + // Failure to resolve the metadata service means that it is not available. + return false; + } + } +} +/** + * reset the memoized isAvailable() lookup. + */ +function resetIsAvailableCache() { + cachedIsAvailableResponse = undefined; +} +/** + * A cache for the detected GCP Residency. + */ +exports.gcpResidencyCache = null; +/** + * Detects GCP Residency. + * Caches results to reduce costs for subsequent calls. + * + * @see setGCPResidency for setting + */ +function getGCPResidency() { + if (exports.gcpResidencyCache === null) { + setGCPResidency(); + } + return exports.gcpResidencyCache; +} +/** + * Sets the detected GCP Residency. + * Useful for forcing metadata server detection behavior. + * + * Set `null` to autodetect the environment (default behavior). + * @see getGCPResidency for getting + */ +function setGCPResidency(value = null) { + exports.gcpResidencyCache = value !== null ? value : (0, gcp_residency_1.detectGCPResidency)(); +} +/** + * Obtain the timeout for requests to the metadata server. + * + * In certain environments and conditions requests can take longer than + * the default timeout to complete. This function will determine the + * appropriate timeout based on the environment. + * + * @returns {number} a request timeout duration in milliseconds. + */ +function requestTimeout() { + return getGCPResidency() ? 0 : 3000; +} +__exportStar(require("./gcp-residency"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/build/src/index.js.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/build/src/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..eace7978e1ead6ee142a9efe2fc9f9a5bf142739 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/build/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;AA8OH,4BAEC;AAcD,0BAEC;AAYD,4BAEC;AAyBD,oBAkBC;AAgBD,kCAmFC;AAKD,sDAEC;AAaD,0CAMC;AASD,0CAEC;AAWD,wCAEC;AA5cD,mCAA2E;AAE3E,0CAA2C;AAC3C,mDAAmD;AACnD,+CAA+C;AAElC,QAAA,SAAS,GAAG,qBAAqB,CAAC;AAClC,QAAA,YAAY,GAAG,wBAAwB,CAAC;AACxC,QAAA,sBAAsB,GAAG,kCAAkC,CAAC;AAE5D,QAAA,WAAW,GAAG,iBAAiB,CAAC;AAChC,QAAA,YAAY,GAAG,QAAQ,CAAC;AACxB,QAAA,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,EAAC,CAAC,mBAAW,CAAC,EAAE,oBAAY,EAAC,CAAC,CAAC;AAEpE,MAAM,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;AAEvC;;;;GAIG;AACU,QAAA,yBAAyB,GAAG,MAAM,CAAC,MAAM,CAAC;IACrD,gBAAgB,EACd,gEAAgE;IAClE,IAAI,EAAE,uEAAuE;IAC7E,WAAW,EACT,4EAA4E;IAC9E,WAAW,EAAE,iDAAiD;CAC/D,CAAC,CAAC;AA2BH;;;;;GAKG;AACH,SAAS,UAAU,CAAC,OAAgB;IAClC,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO;YACL,OAAO,CAAC,GAAG,CAAC,eAAe;gBA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;YAC1E,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;AACH,CAAC;AAED;;GAEG;AACH,SAAgB,qBAAqB;IACnC,yBAAyB,GAAG,SAAS,CAAC;AACxC,CAAC;AAED;;GAEG;AACQ,QAAA,iBAAiB,GAAmB,IAAI,CAAC;AAEpD;;;;;GAKG;AACH,SAAgB,eAAe;IAC7B,IAAI,yBAAiB,KAAK,IAAI,EAAE,CAAC;QAC/B,eAAe,EAAE,CAAC;IACpB,CAAC;IAED,OAAO,yBAAkB,CAAC;AAC5B,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,eAAe,CAAC,QAAwB,IAAI;IAC1D,yBAAiB,GAAG,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAA,kCAAkB,GAAE,CAAC;AACpE,CAAC;AAED;;;;;;;;GAQG;AACH,SAAgB,cAAc;IAC5B,OAAO,eAAe,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AACtC,CAAC;AAED,kDAAgC"} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d1df1b8a6791284fddb90ba591ec8c55034ec361 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gcp-metadata/package.json @@ -0,0 +1,73 @@ +{ + "name": "gcp-metadata", + "version": "6.1.1", + "description": "Get the metadata from a Google Cloud Platform environment", + "repository": "googleapis/gcp-metadata", + "main": "./build/src/index.js", + "types": "./build/src/index.d.ts", + "files": [ + "build/src" + ], + "scripts": { + "compile": "cross-env NODE_OPTIONS=--max-old-space-size=8192 tsc -p .", + "fix": "gts fix", + "pretest": "npm run compile", + "prepare": "npm run compile", + "samples-test": "npm link && cd samples/ && npm link ../ && npm test && cd ../", + "presystem-test": "npm run compile", + "system-test": "mocha build/system-test --timeout 600000", + "test": "c8 mocha --timeout=5000 build/test", + "docs": "jsdoc -c .jsdoc.js", + "lint": "gts check", + "docs-test": "linkinator docs", + "predocs-test": "npm run docs", + "prelint": "cd samples; npm link ../; npm install", + "clean": "gts clean", + "precompile": "gts clean" + }, + "keywords": [ + "google cloud platform", + "google cloud", + "google", + "app engine", + "compute engine", + "metadata server", + "metadata" + ], + "author": "Google LLC", + "license": "Apache-2.0", + "dependencies": { + "gaxios": "^6.1.1", + "google-logging-utils": "^0.0.2", + "json-bigint": "^1.0.0" + }, + "devDependencies": { + "@google-cloud/functions": "^3.0.0", + "@types/json-bigint": "^1.0.0", + "@types/mocha": "^9.0.0", + "@types/ncp": "^2.0.1", + "@types/node": "^20.0.0", + "@types/sinon": "^17.0.0", + "@types/tmp": "0.2.6", + "@types/uuid": "^9.0.0", + "c8": "^9.0.0", + "cross-env": "^7.0.3", + "gcbuild": "^1.3.4", + "gcx": "^1.0.0", + "gts": "^5.0.0", + "linkinator": "^3.0.0", + "jsdoc": "^4.0.0", + "jsdoc-fresh": "^3.0.0", + "jsdoc-region-tag": "^3.0.0", + "mocha": "^8.0.0", + "ncp": "^2.0.0", + "nock": "^13.0.0", + "sinon": "^17.0.0", + "tmp": "^0.2.0", + "typescript": "^5.1.6", + "uuid": "^9.0.0" + }, + "engines": { + "node": ">=14" + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/CHANGELOG.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..dc942a7d060a483212cf715376f86262e2361f30 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/CHANGELOG.md @@ -0,0 +1,1394 @@ +# Changelog + +[npm history][1] + +[1]: https://www.npmjs.com/package/google-auth-library?activeTab=versions + +## [9.15.1](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.15.0...v9.15.1) (2025-01-24) + + +### Bug Fixes + +* Resolve typo in document ([#1901](https://github.com/googleapis/google-auth-library-nodejs/issues/1901)) ([12f2c87](https://github.com/googleapis/google-auth-library-nodejs/commit/12f2c87266de0a3ccd33e6b4993cab3537f9a242)) + +## [9.15.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.14.2...v9.15.0) (2024-11-01) + + +### Features + +* Impersonated Universe Domain Support ([#1875](https://github.com/googleapis/google-auth-library-nodejs/issues/1875)) ([902bf8b](https://github.com/googleapis/google-auth-library-nodejs/commit/902bf8b7faf8f7a0735011c252907282f550cd14)) + +## [9.14.2](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.14.1...v9.14.2) (2024-10-09) + + +### Bug Fixes + +* Disable Universe Domain Check ([#1878](https://github.com/googleapis/google-auth-library-nodejs/issues/1878)) ([8adb44c](https://github.com/googleapis/google-auth-library-nodejs/commit/8adb44c738b88bfc44e57b0694c3815d138a40e5)) + +## [9.14.1](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.14.0...v9.14.1) (2024-08-30) + + +### Performance Improvements + +* **GoogleAuth:** Improve Client Creation From Files/Streams Perf ([#1856](https://github.com/googleapis/google-auth-library-nodejs/issues/1856)) ([85d9d6f](https://github.com/googleapis/google-auth-library-nodejs/commit/85d9d6fe312f5ed68db22a28b84b6c8f257f9ec9)) + +## [9.14.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.13.0...v9.14.0) (2024-08-19) + + +### Features + +* Add `AnyAuthClient` type ([#1843](https://github.com/googleapis/google-auth-library-nodejs/issues/1843)) ([3ae120d](https://github.com/googleapis/google-auth-library-nodejs/commit/3ae120d0a45c95e36c59c9ac8286483938781f30)) +* Extend API Key Support ([#1835](https://github.com/googleapis/google-auth-library-nodejs/issues/1835)) ([5fc3bcc](https://github.com/googleapis/google-auth-library-nodejs/commit/5fc3bccacc74082f71983595dd7654b1b60be0f8)) +* Group Concurrent `getClient` Requests ([#1848](https://github.com/googleapis/google-auth-library-nodejs/issues/1848)) ([243ce28](https://github.com/googleapis/google-auth-library-nodejs/commit/243ce284bedd101a15a0e738a59a7db808c2ad3f)) + + +### Bug Fixes + +* **deps:** Update dependency @googleapis/iam to v21 ([#1847](https://github.com/googleapis/google-auth-library-nodejs/issues/1847)) ([e9459f3](https://github.com/googleapis/google-auth-library-nodejs/commit/e9459f3d11418ce8afd4fe87cd92d4b2d06457ba)) + +## [9.13.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.12.0...v9.13.0) (2024-07-29) + + +### Features + +* Group Concurrent Access Token Requests for Base External Clients ([#1840](https://github.com/googleapis/google-auth-library-nodejs/issues/1840)) ([0e08fc5](https://github.com/googleapis/google-auth-library-nodejs/commit/0e08fc58eb61bba431ab4f217f7f7ad3a7dce9df)) + +## [9.12.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.11.0...v9.12.0) (2024-07-26) + + +### Features + +* Expose More Public API Types ([#1838](https://github.com/googleapis/google-auth-library-nodejs/issues/1838)) ([5745a49](https://github.com/googleapis/google-auth-library-nodejs/commit/5745a49df31ff87c0e53edf44671f3a10c024d9f)) + + +### Bug Fixes + +* **deps:** Update dependency @googleapis/iam to v19 ([#1823](https://github.com/googleapis/google-auth-library-nodejs/issues/1823)) ([b070ffb](https://github.com/googleapis/google-auth-library-nodejs/commit/b070ffbfeb35a7f4552e86bf1840645096951b58)) +* **deps:** Update dependency @googleapis/iam to v20 ([#1832](https://github.com/googleapis/google-auth-library-nodejs/issues/1832)) ([e31a831](https://github.com/googleapis/google-auth-library-nodejs/commit/e31a831417692e730f79d42608bd543046070ae3)) + +## [9.11.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.10.0...v9.11.0) (2024-06-01) + + +### Features + +* Adding support of client authentication method. ([#1814](https://github.com/googleapis/google-auth-library-nodejs/issues/1814)) ([4a14e8c](https://github.com/googleapis/google-auth-library-nodejs/commit/4a14e8c3bdcfa9d8531a231b00b946728530ce12)) + +## [9.10.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.9.0...v9.10.0) (2024-05-10) + + +### Features + +* Implement `UserRefreshClient#fetchIdToken` ([#1811](https://github.com/googleapis/google-auth-library-nodejs/issues/1811)) ([ae8bc54](https://github.com/googleapis/google-auth-library-nodejs/commit/ae8bc5476f5d93c8516d9a9eb553e7ce7c00edd5)) + + +### Bug Fixes + +* **deps:** Update dependency @googleapis/iam to v16 ([#1803](https://github.com/googleapis/google-auth-library-nodejs/issues/1803)) ([40406a0](https://github.com/googleapis/google-auth-library-nodejs/commit/40406a0512cde1d75d2af7dd23aa7aa7de38d30b)) +* **deps:** Update dependency @googleapis/iam to v17 ([#1808](https://github.com/googleapis/google-auth-library-nodejs/issues/1808)) ([4d67f07](https://github.com/googleapis/google-auth-library-nodejs/commit/4d67f07380f690a99c8facf7266db7cb2d6c69b3)) +* **deps:** Update dependency @googleapis/iam to v18 ([#1809](https://github.com/googleapis/google-auth-library-nodejs/issues/1809)) ([b2b9676](https://github.com/googleapis/google-auth-library-nodejs/commit/b2b9676f933c012fb2cd1789ad80b927af0de07c)) + +## [9.9.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.8.0...v9.9.0) (2024-04-18) + + +### Features + +* Adds suppliers for custom subject token and AWS credentials ([#1795](https://github.com/googleapis/google-auth-library-nodejs/issues/1795)) ([c680b5d](https://github.com/googleapis/google-auth-library-nodejs/commit/c680b5ddfa526d414ad1250bb6f5af69c498b909)) + +## [9.8.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.7.0...v9.8.0) (2024-04-12) + + +### Features + +* Enable Retries For Auth Requests ([#1791](https://github.com/googleapis/google-auth-library-nodejs/issues/1791)) ([9b69a31](https://github.com/googleapis/google-auth-library-nodejs/commit/9b69a3119c2d0dfe12d41a5f77658d35a2c92d74)) +* Improve `gaxios` exposure ([#1794](https://github.com/googleapis/google-auth-library-nodejs/issues/1794)) ([5058726](https://github.com/googleapis/google-auth-library-nodejs/commit/5058726e2234a2da4edd31f0898465798943ebe6)) + + +### Bug Fixes + +* **deps:** Update dependency open to v10 ([#1782](https://github.com/googleapis/google-auth-library-nodejs/issues/1782)) ([16e5cae](https://github.com/googleapis/google-auth-library-nodejs/commit/16e5cae1d56d5c3dd6cc3bdca5ecdfb534eaf529)) +* **deps:** Update dependency opn to v6 ([#1775](https://github.com/googleapis/google-auth-library-nodejs/issues/1775)) ([fc8dfe9](https://github.com/googleapis/google-auth-library-nodejs/commit/fc8dfe9d373e30dd1bd06eb8cbb8b52e735b4d83)) + +## [9.7.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.6.3...v9.7.0) (2024-03-12) + + +### Features + +* `PassThrough` AuthClient ([#1771](https://github.com/googleapis/google-auth-library-nodejs/issues/1771)) ([0003bee](https://github.com/googleapis/google-auth-library-nodejs/commit/0003bee317dd8e99b553857edfffeb4a47a4af26)) + + +### Bug Fixes + +* **deps:** Update dependency @googleapis/iam to v15 ([#1772](https://github.com/googleapis/google-auth-library-nodejs/issues/1772)) ([f45f975](https://github.com/googleapis/google-auth-library-nodejs/commit/f45f9753a7c83bc04616a1bdbaf687b3f38a17d2)) +* Making aws request signer get a new session token each time security credentials are requested. ([#1765](https://github.com/googleapis/google-auth-library-nodejs/issues/1765)) ([6a6e496](https://github.com/googleapis/google-auth-library-nodejs/commit/6a6e49634863f61487688724d0d20632e03f0299)) + +## [9.6.3](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.6.2...v9.6.3) (2024-02-06) + + +### Bug Fixes + +* Always sign with `scopes` on Non-Default Universes ([#1752](https://github.com/googleapis/google-auth-library-nodejs/issues/1752)) ([f3d3a03](https://github.com/googleapis/google-auth-library-nodejs/commit/f3d3a03dbce42a400c11457131dd1fabc206826a)) + +## [9.6.2](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.6.1...v9.6.2) (2024-02-02) + + +### Bug Fixes + +* Allow Get Universe Without Credentials ([#1748](https://github.com/googleapis/google-auth-library-nodejs/issues/1748)) ([696db72](https://github.com/googleapis/google-auth-library-nodejs/commit/696db72bb8644739768d20375d670813d4490714)) + +## [9.6.1](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.6.0...v9.6.1) (2024-02-01) + + +### Bug Fixes + +* Universe Domain Resolution ([#1745](https://github.com/googleapis/google-auth-library-nodejs/issues/1745)) ([a4f9f9c](https://github.com/googleapis/google-auth-library-nodejs/commit/a4f9f9c65853a37e6e83861c5d22533dba774037)) + +## [9.6.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.5.0...v9.6.0) (2024-01-29) + + +### Features + +* Open More Endpoints for Customization ([#1721](https://github.com/googleapis/google-auth-library-nodejs/issues/1721)) ([effbf87](https://github.com/googleapis/google-auth-library-nodejs/commit/effbf87f6f0fd11a0cb1c749dad81737926dc436)) +* Use self-signed JWTs when non-default Universe Domains ([#1722](https://github.com/googleapis/google-auth-library-nodejs/issues/1722)) ([7e9876e](https://github.com/googleapis/google-auth-library-nodejs/commit/7e9876e2496b073220ca270368da7e9522da88f9)) + + +### Bug Fixes + +* Revert Missing `WORKFORCE_AUDIENCE_PATTERN` ([#1740](https://github.com/googleapis/google-auth-library-nodejs/issues/1740)) ([422de68](https://github.com/googleapis/google-auth-library-nodejs/commit/422de68d8d9ea66e6bf1fea923f61c8af0842420)) + +## [9.5.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.4.2...v9.5.0) (2024-01-25) + + +### Features + +* Improve Universe Domain Ergonomics ([#1732](https://github.com/googleapis/google-auth-library-nodejs/issues/1732)) ([eec82f5](https://github.com/googleapis/google-auth-library-nodejs/commit/eec82f5f48a250744b5c3200ef247c3eae184e2f)) + + +### Bug Fixes + +* **deps:** Update dependency @googleapis/iam to v14 ([#1725](https://github.com/googleapis/google-auth-library-nodejs/issues/1725)) ([594bf2c](https://github.com/googleapis/google-auth-library-nodejs/commit/594bf2cc808c03733274d6b08d92f1d4b12dd630)) +* Typos in samples ([#1728](https://github.com/googleapis/google-auth-library-nodejs/issues/1728)) ([058a503](https://github.com/googleapis/google-auth-library-nodejs/commit/058a5035e3e4df35663c6b3adef2dda617271849)) + +## [9.4.2](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.4.1...v9.4.2) (2024-01-04) + + +### Bug Fixes + +* **deps:** Update dependency @googleapis/iam to v13 ([#1710](https://github.com/googleapis/google-auth-library-nodejs/issues/1710)) ([7ae4aae](https://github.com/googleapis/google-auth-library-nodejs/commit/7ae4aaea0311de1a3e10f4e86a1ef93ff00656b5)) +* Expand credentials type ([#1719](https://github.com/googleapis/google-auth-library-nodejs/issues/1719)) ([846c8e9](https://github.com/googleapis/google-auth-library-nodejs/commit/846c8e96cc36feb05148c16e12127e805e388189)) + +## [9.4.1](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.4.0...v9.4.1) (2023-12-01) + + +### Bug Fixes + +* Support 404 When `GaxiosError` != `GaxiosError` ([#1707](https://github.com/googleapis/google-auth-library-nodejs/issues/1707)) ([704674f](https://github.com/googleapis/google-auth-library-nodejs/commit/704674fe14750d31e7d3a58d6f9b2387c89fb184)) + +## [9.4.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.3.0...v9.4.0) (2023-11-30) + + +### Features + +* Update gcp metadata dependency ([#1703](https://github.com/googleapis/google-auth-library-nodejs/issues/1703)) ([615bdd9](https://github.com/googleapis/google-auth-library-nodejs/commit/615bdd92d1eb1a2a5b8d8c2675fd53350d5fbc21)) + +## [9.3.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.2.0...v9.3.0) (2023-11-29) + + +### Features + +* Add impersonated signer ([#1694](https://github.com/googleapis/google-auth-library-nodejs/issues/1694)) ([cb78a1b](https://github.com/googleapis/google-auth-library-nodejs/commit/cb78a1bfb4104e05be85877fee56d703f749e525)) +* Retrieve `universe_domain` for Compute clients ([#1692](https://github.com/googleapis/google-auth-library-nodejs/issues/1692)) ([a735ec5](https://github.com/googleapis/google-auth-library-nodejs/commit/a735ec5f5e280a1c47f0f4d5e99acf228d5a320a)) + + +### Bug Fixes + +* Verifier algorithm ([#1696](https://github.com/googleapis/google-auth-library-nodejs/issues/1696)) ([c5080a0](https://github.com/googleapis/google-auth-library-nodejs/commit/c5080a0d56b52b90b5d26cfc5f7343afb58199a4)) + +## [9.2.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.1.0...v9.2.0) (2023-10-26) + + +### Features + +* Unify Base `AuthClient` Options ([#1663](https://github.com/googleapis/google-auth-library-nodejs/issues/1663)) ([5ac6705](https://github.com/googleapis/google-auth-library-nodejs/commit/5ac67052f6c19e93c3e8c4e1636fad4737fcee08)) + + +### Bug Fixes + +* **deps:** Update dependency @googleapis/iam to v12 ([#1671](https://github.com/googleapis/google-auth-library-nodejs/issues/1671)) ([4f94ffe](https://github.com/googleapis/google-auth-library-nodejs/commit/4f94ffe474ee41b560813b81e8d621be848d38d0)) +* DOS security risks ([#1668](https://github.com/googleapis/google-auth-library-nodejs/issues/1668)) ([b25d4f5](https://github.com/googleapis/google-auth-library-nodejs/commit/b25d4f54f88c52c8496ef65f5ab2a75122100f2c)) +* Increase max asset size ([#1682](https://github.com/googleapis/google-auth-library-nodejs/issues/1682)) ([edb9401](https://github.com/googleapis/google-auth-library-nodejs/commit/edb94018cadd2ad796ccec5496e3bfcbade39c7f)) +* Remove broken source maps ([#1669](https://github.com/googleapis/google-auth-library-nodejs/issues/1669)) ([56cb3ad](https://github.com/googleapis/google-auth-library-nodejs/commit/56cb3ad24c5e4b6952169b88d0a43e89cbf1252e)) + +## [9.1.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v9.0.0...v9.1.0) (2023-10-02) + + +### Features + +* Byoid metrics ([#1595](https://github.com/googleapis/google-auth-library-nodejs/issues/1595)) ([fe09d6b](https://github.com/googleapis/google-auth-library-nodejs/commit/fe09d6b4eb5a8215d21564a97bcc7ea5beb570bf)) +* Expose `gcp-metadata` ([#1655](https://github.com/googleapis/google-auth-library-nodejs/issues/1655)) ([d76140f](https://github.com/googleapis/google-auth-library-nodejs/commit/d76140f253c3903a22ed9087623be05e79a220f9)) +* Expose Compute's Service Account Email ([#1656](https://github.com/googleapis/google-auth-library-nodejs/issues/1656)) ([ef29297](https://github.com/googleapis/google-auth-library-nodejs/commit/ef29297215eb907c511627543391db9b43c1eac5)) +* Extend `universe_domain` support ([#1633](https://github.com/googleapis/google-auth-library-nodejs/issues/1633)) ([4ee02da](https://github.com/googleapis/google-auth-library-nodejs/commit/4ee02da4f6934eeb9550b8b659d1abda85194e6b)) +* Support Instantiating OAuth2Client with Credentials ([#1652](https://github.com/googleapis/google-auth-library-nodejs/issues/1652)) ([4339d64](https://github.com/googleapis/google-auth-library-nodejs/commit/4339d6410da7b792f96d31f62800507313c25430)) + + +### Bug Fixes + +* **deps:** Update dependency @google-cloud/storage to v7 ([#1629](https://github.com/googleapis/google-auth-library-nodejs/issues/1629)) ([8075b6f](https://github.com/googleapis/google-auth-library-nodejs/commit/8075b6fbb347067ec231134fb4388ab9bcd1bde0)) +* **deps:** Update dependency @googleapis/iam to v11 ([#1622](https://github.com/googleapis/google-auth-library-nodejs/issues/1622)) ([03c0ac9](https://github.com/googleapis/google-auth-library-nodejs/commit/03c0ac9950217ec08ac9ad66eaaa4e9a9e67d423)) +* **deps:** Update dependency google-auth-library to v9 ([#1618](https://github.com/googleapis/google-auth-library-nodejs/issues/1618)) ([1873fef](https://github.com/googleapis/google-auth-library-nodejs/commit/1873fefcdf4df00ff40b0f311e40dcdd402f799e)) +* **deps:** Update dependency puppeteer to v21 ([#1627](https://github.com/googleapis/google-auth-library-nodejs/issues/1627)) ([dd04fbd](https://github.com/googleapis/google-auth-library-nodejs/commit/dd04fbdeb17e457a09b06a4abc2aedf511f355ea)) +* Workforce Audience Pattern ([#1654](https://github.com/googleapis/google-auth-library-nodejs/issues/1654)) ([77eeaed](https://github.com/googleapis/google-auth-library-nodejs/commit/77eeaed1d66c89e855a15db0bb6b9dbd96179c8f)) + +## [9.0.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.9.0...v9.0.0) (2023-07-20) + + +### ⚠ BREAKING CHANGES + +* **deps:** upgrade node-gtoken to 7.0.0 ([#1590](https://github.com/googleapis/google-auth-library-nodejs/issues/1590)) +* make transporter attribute type more generic ([#1406](https://github.com/googleapis/google-auth-library-nodejs/issues/1406)) +* migrate to Node 14 ([#1582](https://github.com/googleapis/google-auth-library-nodejs/issues/1582)) +* remove arrify and fast-text-encoding ([#1583](https://github.com/googleapis/google-auth-library-nodejs/issues/1583)) + +### Features + +* Make transporter attribute type more generic ([#1406](https://github.com/googleapis/google-auth-library-nodejs/issues/1406)) ([dfac525](https://github.com/googleapis/google-auth-library-nodejs/commit/dfac5259fa573f25960949ae1c2f98bc78962717)) + + +### Bug Fixes + +* **deps:** Update dependency @googleapis/iam to v10 ([#1588](https://github.com/googleapis/google-auth-library-nodejs/issues/1588)) ([f95a153](https://github.com/googleapis/google-auth-library-nodejs/commit/f95a153409735a1f4c470fd7de18bf9ab5d5e771)) + + +### Build System + +* Remove arrify and fast-text-encoding ([#1583](https://github.com/googleapis/google-auth-library-nodejs/issues/1583)) ([d736da3](https://github.com/googleapis/google-auth-library-nodejs/commit/d736da3fa5536650ae6a3aebbcae408254ebd035)) + + +### Miscellaneous Chores + +* **deps:** Upgrade node-gtoken to 7.0.0 ([#1590](https://github.com/googleapis/google-auth-library-nodejs/issues/1590)) ([8738df9](https://github.com/googleapis/google-auth-library-nodejs/commit/8738df9e24c62213b5a78e34a70cdcf456a794fa)) +* Migrate to Node 14 ([#1582](https://github.com/googleapis/google-auth-library-nodejs/issues/1582)) ([6004dca](https://github.com/googleapis/google-auth-library-nodejs/commit/6004dca8d7e7aca7e570b56afd84d3c7f5d40242)) + +## [8.9.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.8.0...v8.9.0) (2023-06-29) + + +### Features + +* Adds universe_domain field to base external client ([#1548](https://github.com/googleapis/google-auth-library-nodejs/issues/1548)) ([7412d7c](https://github.com/googleapis/google-auth-library-nodejs/commit/7412d7c55c688601199b5201b29cfbe63c4c7a70)) +* Utilize `gcp-metadata`'s GCP Residency Check ([#1513](https://github.com/googleapis/google-auth-library-nodejs/issues/1513)) ([43377ac](https://github.com/googleapis/google-auth-library-nodejs/commit/43377ac7af1ece14b82b053b504449f257d11af6)) + + +### Bug Fixes + +* **deps:** Update dependency @googleapis/iam to v8 ([#1581](https://github.com/googleapis/google-auth-library-nodejs/issues/1581)) ([7373b75](https://github.com/googleapis/google-auth-library-nodejs/commit/7373b75c2205876f38ec2697f23758176a327fc7)) +* **deps:** Update dependency puppeteer to v20 ([#1550](https://github.com/googleapis/google-auth-library-nodejs/issues/1550)) ([3563c16](https://github.com/googleapis/google-auth-library-nodejs/commit/3563c16e2376729e399fefc0b1fad7bff78c296e)) +* IdTokenClient expiry_date check ([#1555](https://github.com/googleapis/google-auth-library-nodejs/issues/1555)) ([efcdef1](https://github.com/googleapis/google-auth-library-nodejs/commit/efcdef190fd94537d79087e7fcb26e5925a46173)) +* KeepAlive sample ([#1561](https://github.com/googleapis/google-auth-library-nodejs/issues/1561)) ([e3ab824](https://github.com/googleapis/google-auth-library-nodejs/commit/e3ab8247761b0a61f25e08a1b8fd6b200a4be200)) +* Make universeDomain private ([#1552](https://github.com/googleapis/google-auth-library-nodejs/issues/1552)) ([73b63d5](https://github.com/googleapis/google-auth-library-nodejs/commit/73b63d56fad8da033307e1be501a8846a5311211)) +* Remove auth lib version from x-goog-api-client header ([#1558](https://github.com/googleapis/google-auth-library-nodejs/issues/1558)) ([ce6013c](https://github.com/googleapis/google-auth-library-nodejs/commit/ce6013c6132ba2b82a1f8cba0a15c4710536204c)) + +## [8.8.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.7.0...v8.8.0) (2023-04-25) + + +### Features + +* Add External Account Authorized User client type ([#1530](https://github.com/googleapis/google-auth-library-nodejs/issues/1530)) ([06d4ef3](https://github.com/googleapis/google-auth-library-nodejs/commit/06d4ef3cc9ba1651af5b1f90c02b231862822ba2)) +* Document External Account Authorized User Credentials ([#1540](https://github.com/googleapis/google-auth-library-nodejs/issues/1540)) ([c6138be](https://github.com/googleapis/google-auth-library-nodejs/commit/c6138be12753c68d7645843451e1e3f9146e515a)) + + +### Bug Fixes + +* **deps:** Update `gcp-metadata` to v5.2.0 ([#1502](https://github.com/googleapis/google-auth-library-nodejs/issues/1502)) ([2562d11](https://github.com/googleapis/google-auth-library-nodejs/commit/2562d1192e0f89a3232897b8e27f24a14d5222f2)) +* **deps:** Update dependency @googleapis/iam to v4 ([#1482](https://github.com/googleapis/google-auth-library-nodejs/issues/1482)) ([00d6135](https://github.com/googleapis/google-auth-library-nodejs/commit/00d6135f35a1aa193d50fad6b3ec28a7fda9df66)) +* **deps:** Update dependency @googleapis/iam to v5 ([#1526](https://github.com/googleapis/google-auth-library-nodejs/issues/1526)) ([a1f9835](https://github.com/googleapis/google-auth-library-nodejs/commit/a1f9835fe155722206046d6bb5b56f9e53f2fe9a)) +* **deps:** Update dependency @googleapis/iam to v6 ([#1536](https://github.com/googleapis/google-auth-library-nodejs/issues/1536)) ([86a4de8](https://github.com/googleapis/google-auth-library-nodejs/commit/86a4de82c0de3efeb4b9b05a6ef34bd98cce398c)) +* **deps:** Update dependency @googleapis/iam to v7 ([#1538](https://github.com/googleapis/google-auth-library-nodejs/issues/1538)) ([fdb67dc](https://github.com/googleapis/google-auth-library-nodejs/commit/fdb67dc634f7fa2fcf8977d6d488cc91e9a7cccb)) +* Do not call metadata server if security creds and region are retrievable through environment vars ([#1493](https://github.com/googleapis/google-auth-library-nodejs/issues/1493)) ([d4de941](https://github.com/googleapis/google-auth-library-nodejs/commit/d4de9412e12f1f6f23f2a7c0d176dc5d2543e607)) +* Removing 3pi config URL validation ([#1517](https://github.com/googleapis/google-auth-library-nodejs/issues/1517)) ([a278d19](https://github.com/googleapis/google-auth-library-nodejs/commit/a278d19a0b211b13e5cf5176d40128e704b55780)) +* Removing aws url validation ([#1531](https://github.com/googleapis/google-auth-library-nodejs/issues/1531)) ([f4d9335](https://github.com/googleapis/google-auth-library-nodejs/commit/f4d933579cb5b9e50adf6e679a73cc78388ad8f8)) + +## [8.7.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.6.0...v8.7.0) (2022-11-08) + + +### Features + +* Introduce environment variable for quota project ([#1478](https://github.com/googleapis/google-auth-library-nodejs/issues/1478)) ([8706abc](https://github.com/googleapis/google-auth-library-nodejs/commit/8706abc64bb7d7b4336597589abb011150015a8c)) + + +### Bug Fixes + +* **deps:** Update dependency puppeteer to v19 ([#1476](https://github.com/googleapis/google-auth-library-nodejs/issues/1476)) ([86b258d](https://github.com/googleapis/google-auth-library-nodejs/commit/86b258da699810ead624419333a1a7f998f1b376)) +* Validate url domain for aws metadata urls ([#1484](https://github.com/googleapis/google-auth-library-nodejs/issues/1484)) ([6dc4e58](https://github.com/googleapis/google-auth-library-nodejs/commit/6dc4e583dfd3aa3030dfbf959ee1c68a259abe2f)) + +## [8.6.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.5.2...v8.6.0) (2022-10-06) + + +### Features + +* Adding validation for psc endpoints ([#1473](https://github.com/googleapis/google-auth-library-nodejs/issues/1473)) ([4bbd13f](https://github.com/googleapis/google-auth-library-nodejs/commit/4bbd13fbf9081e004209d0ffc336648cff0c529e)) +* **samples:** Auth samples ([#1444](https://github.com/googleapis/google-auth-library-nodejs/issues/1444)) ([137883a](https://github.com/googleapis/google-auth-library-nodejs/commit/137883aff56c9e847abb6445c89a76a27536fe26)) + +## [8.5.2](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.5.1...v8.5.2) (2022-09-22) + + +### Bug Fixes + +* **deps:** Update dependency puppeteer to v17 ([#1452](https://github.com/googleapis/google-auth-library-nodejs/issues/1452)) ([b317b59](https://github.com/googleapis/google-auth-library-nodejs/commit/b317b5963c18a598fceb85d4f32cc8cd64bb9b7b)) +* **deps:** Update dependency puppeteer to v18 ([#1471](https://github.com/googleapis/google-auth-library-nodejs/issues/1471)) ([9a2a918](https://github.com/googleapis/google-auth-library-nodejs/commit/9a2a9188c674c41a6a67095c3b102a7dc545fff5)) + +## [8.5.1](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.5.0...v8.5.1) (2022-08-31) + + +### Bug Fixes + +* do not use #private ([#1454](https://github.com/googleapis/google-auth-library-nodejs/issues/1454)) ([6c30274](https://github.com/googleapis/google-auth-library-nodejs/commit/6c302746c9eb4778619dec5f2f5f6e940af8086a)) + +## [8.5.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.4.0...v8.5.0) (2022-08-31) + + +### Features + +* Support Not Requiring `projectId` When Not Required ([#1448](https://github.com/googleapis/google-auth-library-nodejs/issues/1448)) ([b37489b](https://github.com/googleapis/google-auth-library-nodejs/commit/b37489b6bc17645d3ea23fbceb2326adb296240b)) + + +### Bug Fixes + +* add hashes to requirements.txt ([#1544](https://github.com/googleapis/google-auth-library-nodejs/issues/1544)) ([#1449](https://github.com/googleapis/google-auth-library-nodejs/issues/1449)) ([54afa8e](https://github.com/googleapis/google-auth-library-nodejs/commit/54afa8ef184c8a68c9930d67d850b7334c28ecaf)) +* remove `projectId` check for `signBlob` calls ([6c04661](https://github.com/googleapis/google-auth-library-nodejs/commit/6c04661c6950532a8239cb95f0509a9d5368ffcc)) + +## [8.4.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.3.0...v8.4.0) (2022-08-23) + + +### Features + +* adding configurable token lifespan support ([#1441](https://github.com/googleapis/google-auth-library-nodejs/issues/1441)) ([178e3b8](https://github.com/googleapis/google-auth-library-nodejs/commit/178e3b83104f5a050f09e17d522d36c8feca632c)) + + +### Bug Fixes + +* **functions:** clarify auth comments ([#1427](https://github.com/googleapis/google-auth-library-nodejs/issues/1427)) ([7e06732](https://github.com/googleapis/google-auth-library-nodejs/commit/7e067327634281bba948c9cc6bc99c7ab860f827)) + +## [8.3.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.2.0...v8.3.0) (2022-08-19) + + +### Features + +* Add `generateIdToken` support for `Impersonated` Clients ([#1439](https://github.com/googleapis/google-auth-library-nodejs/issues/1439)) ([4ace981](https://github.com/googleapis/google-auth-library-nodejs/commit/4ace981ba1d37a9a00201a1c91e1b79c8cdb5cec)) + +## [8.2.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.1.1...v8.2.0) (2022-08-11) + + +### Features + +* adds Pluggable Auth support ([#1437](https://github.com/googleapis/google-auth-library-nodejs/issues/1437)) ([ed7ef7a](https://github.com/googleapis/google-auth-library-nodejs/commit/ed7ef7a5d1fa6bf5d06bdaab278052fd3930fb7f)) + +## [8.1.1](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.1.0...v8.1.1) (2022-07-08) + + +### Bug Fixes + +* **deps:** update dependency puppeteer to v15 ([#1424](https://github.com/googleapis/google-auth-library-nodejs/issues/1424)) ([1462f2c](https://github.com/googleapis/google-auth-library-nodejs/commit/1462f2c533da22b0a07130b25c41df046d4d713d)) + +## [8.1.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.0.3...v8.1.0) (2022-06-30) + + +### Features + +* handle impersonated ADC ([#1425](https://github.com/googleapis/google-auth-library-nodejs/issues/1425)) ([835be89](https://github.com/googleapis/google-auth-library-nodejs/commit/835be89687c2dff19f34e8b55645d3d611339e14)) + +## [8.0.3](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.0.2...v8.0.3) (2022-06-17) + + +### Bug Fixes + +* **deps:** update dependency @googleapis/iam to v3 ([#1421](https://github.com/googleapis/google-auth-library-nodejs/issues/1421)) ([0dc8857](https://github.com/googleapis/google-auth-library-nodejs/commit/0dc88572958520ddd4834aa982d41b98851895d9)) + +### [8.0.2](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.0.1...v8.0.2) (2022-04-27) + + +### Bug Fixes + +* Fixing Implementation of GoogleAuth.sign() for external account credentials ([#1397](https://github.com/googleapis/google-auth-library-nodejs/issues/1397)) ([b0ddb75](https://github.com/googleapis/google-auth-library-nodejs/commit/b0ddb7512fb9ed1e51b6874b7376d7e1f26be644)) + +### [8.0.1](https://github.com/googleapis/google-auth-library-nodejs/compare/v8.0.0...v8.0.1) (2022-04-22) + + +### Bug Fixes + +* **deps:** update dependency gaxios to v5 ([#1398](https://github.com/googleapis/google-auth-library-nodejs/issues/1398)) ([cbd7d4f](https://github.com/googleapis/google-auth-library-nodejs/commit/cbd7d4f471046afa05ff4539c9a93bba998b318c)) +* **deps:** update dependency google-auth-library to v8 ([#1399](https://github.com/googleapis/google-auth-library-nodejs/issues/1399)) ([9a8be63](https://github.com/googleapis/google-auth-library-nodejs/commit/9a8be636eaea979979426558dca40def9c0e569e)) + +## [8.0.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v7.14.1...v8.0.0) (2022-04-20) + + +### ⚠ BREAKING CHANGES + +* Set Node v12 to minimum supported version & Upgrade TypeScript (#1392) +* remove deprecated DeprecatedGetClientOptions (#1393) + +### Code Refactoring + +* remove deprecated DeprecatedGetClientOptions ([#1393](https://github.com/googleapis/google-auth-library-nodejs/issues/1393)) ([9c02941](https://github.com/googleapis/google-auth-library-nodejs/commit/9c02941e52514f8e3b07fedb01439fc313046063)) + + +### Build System + +* Set Node v12 to minimum supported version & Upgrade TypeScript ([#1392](https://github.com/googleapis/google-auth-library-nodejs/issues/1392)) ([b7bcedb](https://github.com/googleapis/google-auth-library-nodejs/commit/b7bcedb9e4ec24217a861016f3378460af7598c7)) + +### [7.14.1](https://github.com/googleapis/google-auth-library-nodejs/compare/v7.14.0...v7.14.1) (2022-03-09) + + +### Bug Fixes + +* **serverless:** clean up ID token example ([#1380](https://github.com/googleapis/google-auth-library-nodejs/issues/1380)) ([db27f1b](https://github.com/googleapis/google-auth-library-nodejs/commit/db27f1bc31efaa9df28da2e0a1229ee3ebea0751)) + +## [7.14.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v7.13.0...v7.14.0) (2022-02-22) + + +### Features + +* Add AWS Session Token to Metadata Requests ([#1363](https://github.com/googleapis/google-auth-library-nodejs/issues/1363)) ([9ea3e98](https://github.com/googleapis/google-auth-library-nodejs/commit/9ea3e98582e8a69dedef89952ae08d64c49f48ef)) + + +### Bug Fixes + +* Rename `auth` to `authClient` & Use Generics for `AuthClient` ([#1371](https://github.com/googleapis/google-auth-library-nodejs/issues/1371)) ([8373000](https://github.com/googleapis/google-auth-library-nodejs/commit/8373000b2240cb694e9492f849e5cc7e13c89b1a)) + +## [7.13.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v7.12.0...v7.13.0) (2022-02-17) + + +### Features + +* Support instantiating `GoogleAuth` with an `AuthClient` ([#1364](https://github.com/googleapis/google-auth-library-nodejs/issues/1364)) ([8839b5b](https://github.com/googleapis/google-auth-library-nodejs/commit/8839b5b12531ae4966b38795ed818ad138eb326a)) + +## [7.12.0](https://github.com/googleapis/google-auth-library-nodejs/compare/v7.11.0...v7.12.0) (2022-02-09) + + +### Features + +* Export `AuthClient` ([#1361](https://github.com/googleapis/google-auth-library-nodejs/issues/1361)) ([88f42ec](https://github.com/googleapis/google-auth-library-nodejs/commit/88f42eca1a02ab5768e02538f2dc639d196de9fb)) + +## [7.11.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.10.4...v7.11.0) (2021-12-15) + + +### Features + +* adds README, samples and integration tests for downscoping with CAB ([#1311](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1311)) ([4549116](https://www.github.com/googleapis/google-auth-library-nodejs/commit/454911637eca6a1272a729b2b2dfcf690c53fe29)) + +### [7.10.4](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.10.3...v7.10.4) (2021-12-13) + + +### Bug Fixes + +* **deps:** update dependency puppeteer to v13 ([#1334](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1334)) ([e05548d](https://www.github.com/googleapis/google-auth-library-nodejs/commit/e05548dfb431638d618aa8b846d0944541387033)) + +### [7.10.3](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.10.2...v7.10.3) (2021-11-29) + + +### Bug Fixes + +* **deps:** update dependency puppeteer to v12 ([#1325](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1325)) ([110ddc2](https://www.github.com/googleapis/google-auth-library-nodejs/commit/110ddc245b768888a88d8c7211f0b0391326cc10)) + +### [7.10.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.10.1...v7.10.2) (2021-11-03) + + +### Bug Fixes + +* **deps:** update dependency puppeteer to v11 ([#1312](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1312)) ([b3ba9ac](https://www.github.com/googleapis/google-auth-library-nodejs/commit/b3ba9ac834de86022a78ac540995fa35857d6670)) + +### [7.10.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.10.0...v7.10.1) (2021-10-14) + + +### Bug Fixes + +* **security:** explicitly update keypair dependency ([94401a6](https://www.github.com/googleapis/google-auth-library-nodejs/commit/94401a6b73eeaf370aeaf9cbf92f23f4fc7bde9b)) + +## [7.10.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.9.2...v7.10.0) (2021-09-28) + + +### Features + +* add workforce config support. ([#1251](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1251)) ([fe29e38](https://www.github.com/googleapis/google-auth-library-nodejs/commit/fe29e384820f1c97ca62478c55813aad3f8ecbea)) + +### [7.9.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.9.1...v7.9.2) (2021-09-16) + + +### Bug Fixes + +* **deps:** update dependency @googleapis/iam to v2 ([#1253](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1253)) ([59b8243](https://www.github.com/googleapis/google-auth-library-nodejs/commit/59b82436d6b9b68b6ae0e0e81d4b797d964acae2)) + +### [7.9.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.9.0...v7.9.1) (2021-09-02) + + +### Bug Fixes + +* **build:** switch to main branch ([#1249](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1249)) ([2c72de4](https://www.github.com/googleapis/google-auth-library-nodejs/commit/2c72de4ef7c07ddb4586094faf117715ab50143e)) + +## [7.9.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.8.0...v7.9.0) (2021-09-02) + + +### Features + +* wire up implementation of DownscopedClient. ([#1232](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1232)) ([baa1318](https://www.github.com/googleapis/google-auth-library-nodejs/commit/baa13185836bb299b769c034bfb7d37231eea8d1)) + +## [7.8.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.7.0...v7.8.0) (2021-08-30) + + +### Features + +* use self-signed JWTs if alwaysUseJWTAccessWithScope is true ([#1196](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1196)) ([ad3f652](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ad3f652e8e859d8d8a69dfe9df01d001862fe0ae)) + +## [7.7.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.6.2...v7.7.0) (2021-08-27) + + +### Features + +* add refreshHandler callback to OAuth 2.0 client to handle token refresh ([#1213](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1213)) ([2fcab77](https://www.github.com/googleapis/google-auth-library-nodejs/commit/2fcab77a1fae85489829f22ec95cc66b0b284342)) + +### [7.6.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.6.1...v7.6.2) (2021-08-17) + + +### Bug Fixes + +* validate token_url and service_account_impersonation_url ([#1229](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1229)) ([0360bb7](https://www.github.com/googleapis/google-auth-library-nodejs/commit/0360bb722aaa082c36c1e1919bf5df27efbe15b3)) + +### [7.6.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.6.0...v7.6.1) (2021-08-13) + + +### Bug Fixes + +* use updated variable name for self-signed JWTs ([#1233](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1233)) ([ef41fe5](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ef41fe59b423125c607e3ad20896a35f12f5365b)) + +## [7.6.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.5.0...v7.6.0) (2021-08-10) + + +### Features + +* add GoogleAuth.sign() support to external account client ([#1227](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1227)) ([1ca3b73](https://www.github.com/googleapis/google-auth-library-nodejs/commit/1ca3b733427d951ed624e1129fca510d84d5d0fe)) + +## [7.5.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.4.1...v7.5.0) (2021-08-04) + + +### Features + +* Adds support for STS response not returning expires_in field. ([#1216](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1216)) ([24bb456](https://www.github.com/googleapis/google-auth-library-nodejs/commit/24bb4568820c2692b1b3ff29835a38fdb3f28c9e)) + +### [7.4.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.4.0...v7.4.1) (2021-07-29) + + +### Bug Fixes + +* **downscoped-client:** bug fixes for downscoped client implementation. ([#1219](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1219)) ([4fbe67e](https://www.github.com/googleapis/google-auth-library-nodejs/commit/4fbe67e08bce3f31193d3bb7b93c4cc1251e66a2)) + +## [7.4.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.3.0...v7.4.0) (2021-07-29) + + +### Features + +* **impersonated:** add impersonated credentials auth ([#1207](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1207)) ([ab1cd31](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ab1cd31e07d45424f614e0401d1068df2fbd914c)) + +## [7.3.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.2.0...v7.3.0) (2021-07-02) + + +### Features + +* add useJWTAccessWithScope and defaultServicePath variable ([#1204](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1204)) ([79e100e](https://www.github.com/googleapis/google-auth-library-nodejs/commit/79e100e9ddc64f34e34d0e91c8188f1818e33a1c)) + +## [7.2.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.1.2...v7.2.0) (2021-06-30) + + +### Features + +* Implement DownscopedClient#getAccessToken() and unit test ([#1201](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1201)) ([faa6677](https://www.github.com/googleapis/google-auth-library-nodejs/commit/faa6677fe72c8fc671a2190abe45897ac58cc42e)) + +### [7.1.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.1.1...v7.1.2) (2021-06-10) + + +### Bug Fixes + +* use iam client library to setup test ([#1173](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1173)) ([74ac5db](https://www.github.com/googleapis/google-auth-library-nodejs/commit/74ac5db59f9eff8fa4f3bdb6acc0647a1a4f491f)) + +### [7.1.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.1.0...v7.1.1) (2021-06-02) + + +### Bug Fixes + +* **deps:** update dependency puppeteer to v10 ([#1182](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1182)) ([003e3ee](https://www.github.com/googleapis/google-auth-library-nodejs/commit/003e3ee5d8aeb749c07a4a4db2b75a5882988cc3)) + +## [7.1.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.0.4...v7.1.0) (2021-05-21) + + +### Features + +* add `gcf-owl-bot[bot]` to `ignoreAuthors` ([#1174](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1174)) ([f377adc](https://www.github.com/googleapis/google-auth-library-nodejs/commit/f377adc01ca16687bb905aa14f6c62a23e90aaa9)) +* add detection for Cloud Run ([#1177](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1177)) ([4512363](https://www.github.com/googleapis/google-auth-library-nodejs/commit/4512363cf712dff5f178af0e7022c258775dfec7)) + +### [7.0.4](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.0.3...v7.0.4) (2021-04-06) + + +### Bug Fixes + +* do not suppress external project ID determination errors ([#1153](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1153)) ([6c1c91d](https://www.github.com/googleapis/google-auth-library-nodejs/commit/6c1c91dac6c31d762b03774a385d780a824fce97)) + +### [7.0.3](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.0.2...v7.0.3) (2021-03-23) + + +### Bug Fixes + +* support AWS_DEFAULT_REGION for determining AWS region ([#1149](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1149)) ([9ae2d30](https://www.github.com/googleapis/google-auth-library-nodejs/commit/9ae2d30c15c9bce3cae70ccbe6e227c096005695)) + +### [7.0.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.0.1...v7.0.2) (2021-02-10) + + +### Bug Fixes + +* expose `BaseExternalAccountClient` and `BaseExternalAccountClientOptions` ([#1142](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1142)) ([1d62c04](https://www.github.com/googleapis/google-auth-library-nodejs/commit/1d62c04dfa117b6a81e8c78385dc72792369cf21)) + +### [7.0.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.0.0...v7.0.1) (2021-02-09) + + +### Bug Fixes + +* **deps:** update dependency google-auth-library to v7 ([#1140](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1140)) ([9c717f7](https://www.github.com/googleapis/google-auth-library-nodejs/commit/9c717f70ca155b24edd5511b6038679db25b85b7)) + +## [7.0.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.1.6...v7.0.0) (2021-02-08) + + +### ⚠ BREAKING CHANGES + +* integrates external_accounts with `GoogleAuth` and ADC (#1052) +* workload identity federation support (#1131) + +### Features + +* adds service account impersonation to `ExternalAccountClient` ([#1041](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1041)) ([997f124](https://www.github.com/googleapis/google-auth-library-nodejs/commit/997f124a5c02dfa44879a759bf701a9fa4c3ba90)) +* adds text/json credential_source support to IdentityPoolClients ([#1059](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1059)) ([997f124](https://www.github.com/googleapis/google-auth-library-nodejs/commit/997f124a5c02dfa44879a759bf701a9fa4c3ba90)) +* defines `ExternalAccountClient` used to instantiate external account clients ([#1050](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1050)) ([997f124](https://www.github.com/googleapis/google-auth-library-nodejs/commit/997f124a5c02dfa44879a759bf701a9fa4c3ba90)) +* defines `IdentityPoolClient` used for K8s and Azure workloads ([#1042](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1042)) ([997f124](https://www.github.com/googleapis/google-auth-library-nodejs/commit/997f124a5c02dfa44879a759bf701a9fa4c3ba90)) +* defines ExternalAccountClient abstract class for external_account credentials ([#1030](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1030)) ([997f124](https://www.github.com/googleapis/google-auth-library-nodejs/commit/997f124a5c02dfa44879a759bf701a9fa4c3ba90)) +* get AWS region from environment variable ([#1067](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1067)) ([997f124](https://www.github.com/googleapis/google-auth-library-nodejs/commit/997f124a5c02dfa44879a759bf701a9fa4c3ba90)) +* implements AWS signature version 4 for signing requests ([#1047](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1047)) ([997f124](https://www.github.com/googleapis/google-auth-library-nodejs/commit/997f124a5c02dfa44879a759bf701a9fa4c3ba90)) +* implements the OAuth token exchange spec based on rfc8693 ([#1026](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1026)) ([997f124](https://www.github.com/googleapis/google-auth-library-nodejs/commit/997f124a5c02dfa44879a759bf701a9fa4c3ba90)) +* integrates external_accounts with `GoogleAuth` and ADC ([#1052](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1052)) ([997f124](https://www.github.com/googleapis/google-auth-library-nodejs/commit/997f124a5c02dfa44879a759bf701a9fa4c3ba90)) +* workload identity federation support ([#1131](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1131)) ([997f124](https://www.github.com/googleapis/google-auth-library-nodejs/commit/997f124a5c02dfa44879a759bf701a9fa4c3ba90)) + + +### Bug Fixes + +* **deps:** update dependency puppeteer to v6 ([#1129](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1129)) ([5240fb0](https://www.github.com/googleapis/google-auth-library-nodejs/commit/5240fb0e7ba5503d562659a0d1d7c952bc44ce0e)) +* **deps:** update dependency puppeteer to v7 ([#1134](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1134)) ([02d0d73](https://www.github.com/googleapis/google-auth-library-nodejs/commit/02d0d73a5f0d2fc7de9b13b160e4e7074652f9d0)) + +### [6.1.6](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.1.5...v6.1.6) (2021-01-27) + + +### Bug Fixes + +* call addSharedMetadataHeaders even when token has not expired ([#1116](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1116)) ([aad043d](https://www.github.com/googleapis/google-auth-library-nodejs/commit/aad043d20df3f1e44f56c58a21f15000b6fe970d)) + +### [6.1.5](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.1.4...v6.1.5) (2021-01-22) + + +### Bug Fixes + +* support PEM and p12 when using factory ([#1120](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1120)) ([c2ead4c](https://www.github.com/googleapis/google-auth-library-nodejs/commit/c2ead4cc7650f100b883c9296fce628f17085992)) + +### [6.1.4](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.1.3...v6.1.4) (2020-12-22) + + +### Bug Fixes + +* move accessToken to headers instead of parameter ([#1108](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1108)) ([67b0cc3](https://www.github.com/googleapis/google-auth-library-nodejs/commit/67b0cc3077860a1583bcf18ce50aeff58bbb5496)) + +### [6.1.3](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.1.2...v6.1.3) (2020-10-22) + + +### Bug Fixes + +* **deps:** update dependency gaxios to v4 ([#1086](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1086)) ([f2678ff](https://www.github.com/googleapis/google-auth-library-nodejs/commit/f2678ff5f8f5a0ee33924278b58e0a6e3122cb12)) + +### [6.1.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.1.1...v6.1.2) (2020-10-19) + + +### Bug Fixes + +* update gcp-metadata to catch a json-bigint security fix ([#1078](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1078)) ([125fe09](https://www.github.com/googleapis/google-auth-library-nodejs/commit/125fe0924a2206ebb0c83ece9947524e7b135803)) + +### [6.1.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.1.0...v6.1.1) (2020-10-06) + + +### Bug Fixes + +* **deps:** upgrade gtoken ([#1064](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1064)) ([9116f24](https://www.github.com/googleapis/google-auth-library-nodejs/commit/9116f247486d6376feca505bbfa42a91d5e579e2)) + +## [6.1.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.0.8...v6.1.0) (2020-09-22) + + +### Features + +* default self-signed JWTs ([#1054](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1054)) ([b4d139d](https://www.github.com/googleapis/google-auth-library-nodejs/commit/b4d139d9ee27f886ca8cc5478615c052700fff48)) + +### [6.0.8](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.0.7...v6.0.8) (2020-08-13) + + +### Bug Fixes + +* **deps:** roll back dependency google-auth-library to ^6.0.6 ([#1033](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1033)) ([eb54ee9](https://www.github.com/googleapis/google-auth-library-nodejs/commit/eb54ee9369d9e5a01d164ccf7f826858d44827fd)) + +### [6.0.7](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.0.6...v6.0.7) (2020-08-11) + + +### Bug Fixes + +* migrate token info API to not pass token in query string ([#991](https://www.github.com/googleapis/google-auth-library-nodejs/issues/991)) ([a7e5701](https://www.github.com/googleapis/google-auth-library-nodejs/commit/a7e5701a8394d79fe93d28794467747a23cf9ff4)) + +### [6.0.6](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.0.5...v6.0.6) (2020-07-30) + + +### Bug Fixes + +* **types:** include scope in credentials type ([#1007](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1007)) ([a2b7d23](https://www.github.com/googleapis/google-auth-library-nodejs/commit/a2b7d23caa5bf253c7c0756396f1b58216182089)) + +### [6.0.5](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.0.4...v6.0.5) (2020-07-13) + + +### Bug Fixes + +* **deps:** update dependency lru-cache to v6 ([#995](https://www.github.com/googleapis/google-auth-library-nodejs/issues/995)) ([3c07566](https://www.github.com/googleapis/google-auth-library-nodejs/commit/3c07566f0384611227030e9b381fc6e6707e526b)) + +### [6.0.4](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.0.3...v6.0.4) (2020-07-09) + + +### Bug Fixes + +* typeo in nodejs .gitattribute ([#993](https://www.github.com/googleapis/google-auth-library-nodejs/issues/993)) ([ad12ceb](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ad12ceb3309b7db7394fe1fe1d5e7b2e4901141d)) + +### [6.0.3](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.0.2...v6.0.3) (2020-07-06) + + +### Bug Fixes + +* **deps:** update dependency puppeteer to v5 ([#986](https://www.github.com/googleapis/google-auth-library-nodejs/issues/986)) ([7cfe6f2](https://www.github.com/googleapis/google-auth-library-nodejs/commit/7cfe6f200b9c04fe4805d1b1e3a2e03a9668e551)) + +### [6.0.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.0.1...v6.0.2) (2020-06-16) + + +### Bug Fixes + +* **deps:** update dependency puppeteer to v4 ([#976](https://www.github.com/googleapis/google-auth-library-nodejs/issues/976)) ([9ddfb9b](https://www.github.com/googleapis/google-auth-library-nodejs/commit/9ddfb9befedd10d6c82cbf799c1afea9ba10d444)) +* **tsc:** audience property is not mandatory on verifyIdToken ([#972](https://www.github.com/googleapis/google-auth-library-nodejs/issues/972)) ([17a7e24](https://www.github.com/googleapis/google-auth-library-nodejs/commit/17a7e247cdb798ddf3173cf44ab762665cbce0a1)) +* **types:** add locale property to idtoken ([#974](https://www.github.com/googleapis/google-auth-library-nodejs/issues/974)) ([ebf9bed](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ebf9beda30f251da6adb9ec0bf943019ea0171c5)), closes [#973](https://www.github.com/googleapis/google-auth-library-nodejs/issues/973) + +### [6.0.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v6.0.0...v6.0.1) (2020-05-21) + + +### Bug Fixes + +* **deps:** update dependency google-auth-library to v6 ([#930](https://www.github.com/googleapis/google-auth-library-nodejs/issues/930)) ([81fdabe](https://www.github.com/googleapis/google-auth-library-nodejs/commit/81fdabe6fb7f0b8c5114c0d835680a28def822e2)) +* apache license URL ([#468](https://www.github.com/googleapis/google-auth-library-nodejs/issues/468)) ([#936](https://www.github.com/googleapis/google-auth-library-nodejs/issues/936)) ([53831cf](https://www.github.com/googleapis/google-auth-library-nodejs/commit/53831cf72f6669d13692c5665fef5062dc8f6c1a)) +* **deps:** update dependency puppeteer to v3 ([#944](https://www.github.com/googleapis/google-auth-library-nodejs/issues/944)) ([4d6fba0](https://www.github.com/googleapis/google-auth-library-nodejs/commit/4d6fba034cb0e70092656e9aff1ba419fdfca880)) +* fixing tsc error caused by @types/node update ([#965](https://www.github.com/googleapis/google-auth-library-nodejs/issues/965)) ([b94edb0](https://www.github.com/googleapis/google-auth-library-nodejs/commit/b94edb0716572593e4e9cb8a9b9bbfa567f71625)) +* gcp-metadata now warns rather than throwing ([#956](https://www.github.com/googleapis/google-auth-library-nodejs/issues/956)) ([89e16c2](https://www.github.com/googleapis/google-auth-library-nodejs/commit/89e16c2401101d086a8f9d05b8f0771b5c74157c)) + +## [6.0.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.10.1...v6.0.0) (2020-03-26) + + +### ⚠ BREAKING CHANGES + +* typescript@3.7.x introduced some breaking changes in +generated code. +* require node 10 in engines field (#926) +* remove deprecated methods (#906) + +### Features + +* require node 10 in engines field ([#926](https://www.github.com/googleapis/google-auth-library-nodejs/issues/926)) ([d89c59a](https://www.github.com/googleapis/google-auth-library-nodejs/commit/d89c59a316e9ca5b8c351128ee3e2d91e9729d5c)) + + +### Bug Fixes + +* do not warn for SDK creds ([#905](https://www.github.com/googleapis/google-auth-library-nodejs/issues/905)) ([9536840](https://www.github.com/googleapis/google-auth-library-nodejs/commit/9536840f88e77f747bbbc2c1b5b4289018fc23c9)) +* use iamcredentials API to sign blobs ([#908](https://www.github.com/googleapis/google-auth-library-nodejs/issues/908)) ([7b8e4c5](https://www.github.com/googleapis/google-auth-library-nodejs/commit/7b8e4c52e31bb3d448c3ff8c05002188900eaa04)) +* **deps:** update dependency gaxios to v3 ([#917](https://www.github.com/googleapis/google-auth-library-nodejs/issues/917)) ([1f4bf61](https://www.github.com/googleapis/google-auth-library-nodejs/commit/1f4bf6128a0dcf22cfe1ec492b2192f513836cb2)) +* **deps:** update dependency gcp-metadata to v4 ([#918](https://www.github.com/googleapis/google-auth-library-nodejs/issues/918)) ([d337131](https://www.github.com/googleapis/google-auth-library-nodejs/commit/d337131d009cc1f8182f7a1f8a9034433ee3fbf7)) +* **types:** add additional fields to TokenInfo ([#907](https://www.github.com/googleapis/google-auth-library-nodejs/issues/907)) ([5b48eb8](https://www.github.com/googleapis/google-auth-library-nodejs/commit/5b48eb86c108c47d317a0eb96b47c0cae86f98cb)) + + +### Build System + +* update to latest gts and TypeScript ([#927](https://www.github.com/googleapis/google-auth-library-nodejs/issues/927)) ([e11e18c](https://www.github.com/googleapis/google-auth-library-nodejs/commit/e11e18cb33eb60a666980d061c54bb8891cdd242)) + + +### Miscellaneous Chores + +* remove deprecated methods ([#906](https://www.github.com/googleapis/google-auth-library-nodejs/issues/906)) ([f453fb7](https://www.github.com/googleapis/google-auth-library-nodejs/commit/f453fb7d8355e6dc74800b18d6f43c4e91d4acc9)) + +### [5.10.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.10.0...v5.10.1) (2020-02-25) + + +### Bug Fixes + +* if GCF environment detected, increase library timeout ([#899](https://www.github.com/googleapis/google-auth-library-nodejs/issues/899)) ([2577ff2](https://www.github.com/googleapis/google-auth-library-nodejs/commit/2577ff28bf22dfc58bd09e7365471c16f359f109)) + +## [5.10.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.9.2...v5.10.0) (2020-02-20) + + +### Features + +* support for verifying ES256 and retrieving IAP public keys ([#887](https://www.github.com/googleapis/google-auth-library-nodejs/issues/887)) ([a98e386](https://www.github.com/googleapis/google-auth-library-nodejs/commit/a98e38678dc4a5e963356378c75c658e36dccd01)) + + +### Bug Fixes + +* **docs:** correct links in README ([f6a3194](https://www.github.com/googleapis/google-auth-library-nodejs/commit/f6a3194ff6df97d4fd833ae69ec80c05eab46e7b)), closes [#891](https://www.github.com/googleapis/google-auth-library-nodejs/issues/891) + +### [5.9.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.9.1...v5.9.2) (2020-01-28) + + +### Bug Fixes + +* populate credentials.refresh_token if provided ([#881](https://www.github.com/googleapis/google-auth-library-nodejs/issues/881)) ([63c4637](https://www.github.com/googleapis/google-auth-library-nodejs/commit/63c4637c57e4113a7b01bf78933a8bff0356c104)) + +### [5.9.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.9.0...v5.9.1) (2020-01-16) + + +### Bug Fixes + +* ensures GCE metadata sets email field for ID tokens ([#874](https://www.github.com/googleapis/google-auth-library-nodejs/issues/874)) ([e45b73d](https://www.github.com/googleapis/google-auth-library-nodejs/commit/e45b73dbb22e1c2d8115882006a21337c7d9bd63)) + +## [5.9.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.8.0...v5.9.0) (2020-01-14) + + +### Features + +* add methods for fetching and using id tokens ([#867](https://www.github.com/googleapis/google-auth-library-nodejs/issues/867)) ([8036f1a](https://www.github.com/googleapis/google-auth-library-nodejs/commit/8036f1a51d1a103b08daf62c7ce372c9f68cd9d4)) +* export LoginTicket and TokenPayload ([#870](https://www.github.com/googleapis/google-auth-library-nodejs/issues/870)) ([539ea5e](https://www.github.com/googleapis/google-auth-library-nodejs/commit/539ea5e804386b79ecf469838fff19465aeb2ca6)) + +## [5.8.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.7.0...v5.8.0) (2020-01-06) + + +### Features + +* cache results of getEnv() ([#857](https://www.github.com/googleapis/google-auth-library-nodejs/issues/857)) ([d4545a9](https://www.github.com/googleapis/google-auth-library-nodejs/commit/d4545a9001184fac0b67e7073e463e3efd345037)) + + +### Bug Fixes + +* **deps:** update dependency jws to v4 ([#851](https://www.github.com/googleapis/google-auth-library-nodejs/issues/851)) ([71366d4](https://www.github.com/googleapis/google-auth-library-nodejs/commit/71366d43406047ce9e1d818d59a14191fb678e3a)) + +## [5.7.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.6.1...v5.7.0) (2019-12-10) + + +### Features + +* make x-goog-user-project work for additional auth clients ([#848](https://www.github.com/googleapis/google-auth-library-nodejs/issues/848)) ([46af865](https://www.github.com/googleapis/google-auth-library-nodejs/commit/46af865172103c6f28712d78b30c2291487cbe86)) + +### [5.6.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.6.0...v5.6.1) (2019-12-05) + + +### Bug Fixes + +* **deps:** pin TypeScript below 3.7.0 ([#845](https://www.github.com/googleapis/google-auth-library-nodejs/issues/845)) ([a9c6e92](https://www.github.com/googleapis/google-auth-library-nodejs/commit/a9c6e9284efe8102974c57c9824ed6275d743c7a)) +* **docs:** improve types and docs for generateCodeVerifierAsync ([#840](https://www.github.com/googleapis/google-auth-library-nodejs/issues/840)) ([04dae9c](https://www.github.com/googleapis/google-auth-library-nodejs/commit/04dae9c271f0099025188489c61fd245d482832b)) + +## [5.6.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.5.1...v5.6.0) (2019-12-02) + + +### Features + +* populate x-goog-user-project for requestAsync ([#837](https://www.github.com/googleapis/google-auth-library-nodejs/issues/837)) ([5a068fb](https://www.github.com/googleapis/google-auth-library-nodejs/commit/5a068fb8f5a3827ab70404f1d9699a97f962bdad)) +* set x-goog-user-project header, with quota_project from default credentials ([#829](https://www.github.com/googleapis/google-auth-library-nodejs/issues/829)) ([3240d16](https://www.github.com/googleapis/google-auth-library-nodejs/commit/3240d16f05171781fe6d70d64c476bceb25805a5)) + + +### Bug Fixes + +* **deps:** update dependency puppeteer to v2 ([#821](https://www.github.com/googleapis/google-auth-library-nodejs/issues/821)) ([2c04117](https://www.github.com/googleapis/google-auth-library-nodejs/commit/2c0411708761cc7debdda1af1e593d82cb4aed31)) +* **docs:** add jsdoc-region-tag plugin ([#826](https://www.github.com/googleapis/google-auth-library-nodejs/issues/826)) ([558677f](https://www.github.com/googleapis/google-auth-library-nodejs/commit/558677fd90d3451e9ac4bf6d0b98907e3313f287)) +* expand on x-goog-user-project to handle auth.getClient() ([#831](https://www.github.com/googleapis/google-auth-library-nodejs/issues/831)) ([3646b7f](https://www.github.com/googleapis/google-auth-library-nodejs/commit/3646b7f9deb296aaff602dd2168ce93f014ce840)) +* use quota_project_id field instead of quota_project ([#832](https://www.github.com/googleapis/google-auth-library-nodejs/issues/832)) ([8933966](https://www.github.com/googleapis/google-auth-library-nodejs/commit/8933966659f3b07f5454a2756fa52d92fea147d2)) + +### [5.5.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.5.0...v5.5.1) (2019-10-22) + + +### Bug Fixes + +* **deps:** update gaxios dependency ([#817](https://www.github.com/googleapis/google-auth-library-nodejs/issues/817)) ([6730698](https://www.github.com/googleapis/google-auth-library-nodejs/commit/6730698b876eb52889acfead33bc4af52a8a7ba5)) +* don't append x-goog-api-client multiple times ([#820](https://www.github.com/googleapis/google-auth-library-nodejs/issues/820)) ([a46b271](https://www.github.com/googleapis/google-auth-library-nodejs/commit/a46b271947b635377eacbdfcd22ae363ce9260a1)) + +## [5.5.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.4.1...v5.5.0) (2019-10-14) + + +### Features + +* **refresh:** add forceRefreshOnFailure flag for refreshing token on error ([#790](https://www.github.com/googleapis/google-auth-library-nodejs/issues/790)) ([54cf477](https://www.github.com/googleapis/google-auth-library-nodejs/commit/54cf4770f487fd1db48f2444c86109ca97608ed1)) + +### [5.4.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.4.0...v5.4.1) (2019-10-10) + + +### Bug Fixes + +* **deps:** updats to gcp-metadata with debug option ([#811](https://www.github.com/googleapis/google-auth-library-nodejs/issues/811)) ([744e3e8](https://www.github.com/googleapis/google-auth-library-nodejs/commit/744e3e8fea223eb4fb115ef0a4d36ad88fc6921a)) + +## [5.4.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.3.0...v5.4.0) (2019-10-08) + + +### Features + +* do not deprecate refreshAccessToken ([#804](https://www.github.com/googleapis/google-auth-library-nodejs/issues/804)) ([f05de11](https://www.github.com/googleapis/google-auth-library-nodejs/commit/f05de11)) + +## [5.3.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.2.2...v5.3.0) (2019-09-27) + + +### Features + +* if token expires soon, force refresh ([#794](https://www.github.com/googleapis/google-auth-library-nodejs/issues/794)) ([fecd4f4](https://www.github.com/googleapis/google-auth-library-nodejs/commit/fecd4f4)) + +### [5.2.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.2.1...v5.2.2) (2019-09-17) + + +### Bug Fixes + +* **deps:** update to gcp-metadata and address envDetect performance issues ([#787](https://www.github.com/googleapis/google-auth-library-nodejs/issues/787)) ([651b5d4](https://www.github.com/googleapis/google-auth-library-nodejs/commit/651b5d4)) + +### [5.2.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.2.0...v5.2.1) (2019-09-06) + + +### Bug Fixes + +* **deps:** nock@next has types that work with our libraries ([#783](https://www.github.com/googleapis/google-auth-library-nodejs/issues/783)) ([a253709](https://www.github.com/googleapis/google-auth-library-nodejs/commit/a253709)) +* **docs:** fix variable name in README.md ([#782](https://www.github.com/googleapis/google-auth-library-nodejs/issues/782)) ([d8c70b9](https://www.github.com/googleapis/google-auth-library-nodejs/commit/d8c70b9)) + +## [5.2.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.1.2...v5.2.0) (2019-08-09) + + +### Features + +* populate x-goog-api-client header for auth ([#772](https://www.github.com/googleapis/google-auth-library-nodejs/issues/772)) ([526dcf6](https://www.github.com/googleapis/google-auth-library-nodejs/commit/526dcf6)) + +### [5.1.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.1.1...v5.1.2) (2019-08-05) + + +### Bug Fixes + +* **deps:** upgrade to gtoken 4.x ([#763](https://www.github.com/googleapis/google-auth-library-nodejs/issues/763)) ([a1fcc25](https://www.github.com/googleapis/google-auth-library-nodejs/commit/a1fcc25)) + +### [5.1.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.1.0...v5.1.1) (2019-07-29) + + +### Bug Fixes + +* **deps:** update dependency google-auth-library to v5 ([#759](https://www.github.com/googleapis/google-auth-library-nodejs/issues/759)) ([e32a12b](https://www.github.com/googleapis/google-auth-library-nodejs/commit/e32a12b)) + +## [5.1.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.0.0...v5.1.0) (2019-07-24) + + +### Features + +* **types:** expose ProjectIdCallback interface ([#753](https://www.github.com/googleapis/google-auth-library-nodejs/issues/753)) ([5577f0d](https://www.github.com/googleapis/google-auth-library-nodejs/commit/5577f0d)) + +## [5.0.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.2.6...v5.0.0) (2019-07-23) + + +### ⚠ BREAKING CHANGES + +* getOptions() no longer accepts GoogleAuthOptions (#749) + +### Code Refactoring + +* getOptions() no longer accepts GoogleAuthOptions ([#749](https://www.github.com/googleapis/google-auth-library-nodejs/issues/749)) ([ba58e3b](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ba58e3b)) + +### [4.2.6](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.2.5...v4.2.6) (2019-07-23) + + +### Bug Fixes + +* use FUNCTION_TARGET to detect GCF 10 and above ([#748](https://www.github.com/googleapis/google-auth-library-nodejs/issues/748)) ([ca17685](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ca17685)) + +### [4.2.5](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.2.4...v4.2.5) (2019-06-26) + + +### Bug Fixes + +* **docs:** make anchors work in jsdoc ([#742](https://www.github.com/googleapis/google-auth-library-nodejs/issues/742)) ([7901456](https://www.github.com/googleapis/google-auth-library-nodejs/commit/7901456)) + +### [4.2.4](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.2.3...v4.2.4) (2019-06-25) + + +### Bug Fixes + +* only require fast-text-encoding when needed ([#740](https://www.github.com/googleapis/google-auth-library-nodejs/issues/740)) ([04fcd77](https://www.github.com/googleapis/google-auth-library-nodejs/commit/04fcd77)) + +### [4.2.3](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.2.2...v4.2.3) (2019-06-24) + + +### Bug Fixes + +* feature detection to check for browser ([#738](https://www.github.com/googleapis/google-auth-library-nodejs/issues/738)) ([83a5ba5](https://www.github.com/googleapis/google-auth-library-nodejs/commit/83a5ba5)) + +### [4.2.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.2.1...v4.2.2) (2019-06-18) + + +### Bug Fixes + +* **compute:** correctly specify scopes when fetching token ([#735](https://www.github.com/googleapis/google-auth-library-nodejs/issues/735)) ([4803e3c](https://www.github.com/googleapis/google-auth-library-nodejs/commit/4803e3c)) + +### [4.2.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.2.0...v4.2.1) (2019-06-14) + + +### Bug Fixes + +* **docs:** move to new client docs URL ([#733](https://www.github.com/googleapis/google-auth-library-nodejs/issues/733)) ([cfbbe2a](https://www.github.com/googleapis/google-auth-library-nodejs/commit/cfbbe2a)) + +## [4.2.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.1.0...v4.2.0) (2019-06-05) + + +### Bug Fixes + +* pad base64 strings for base64js ([#722](https://www.github.com/googleapis/google-auth-library-nodejs/issues/722)) ([81e0a23](https://www.github.com/googleapis/google-auth-library-nodejs/commit/81e0a23)) + + +### Features + +* make both crypto implementations support sign ([#727](https://www.github.com/googleapis/google-auth-library-nodejs/issues/727)) ([e445fb3](https://www.github.com/googleapis/google-auth-library-nodejs/commit/e445fb3)) + +## [4.1.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.0.0...v4.1.0) (2019-05-29) + + +### Bug Fixes + +* **deps:** update dependency google-auth-library to v4 ([#705](https://www.github.com/googleapis/google-auth-library-nodejs/issues/705)) ([2b13344](https://www.github.com/googleapis/google-auth-library-nodejs/commit/2b13344)) + + +### Features + +* use X-Goog-Api-Key header ([#719](https://www.github.com/googleapis/google-auth-library-nodejs/issues/719)) ([35471d0](https://www.github.com/googleapis/google-auth-library-nodejs/commit/35471d0)) + +## [4.0.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v3.1.2...v4.0.0) (2019-05-08) + + +### Bug Fixes + +* **deps:** update dependency arrify to v2 ([#684](https://www.github.com/googleapis/google-auth-library-nodejs/issues/684)) ([1757ee2](https://www.github.com/googleapis/google-auth-library-nodejs/commit/1757ee2)) +* **deps:** update dependency gaxios to v2 ([#681](https://www.github.com/googleapis/google-auth-library-nodejs/issues/681)) ([770ad2f](https://www.github.com/googleapis/google-auth-library-nodejs/commit/770ad2f)) +* **deps:** update dependency gcp-metadata to v2 ([#701](https://www.github.com/googleapis/google-auth-library-nodejs/issues/701)) ([be20528](https://www.github.com/googleapis/google-auth-library-nodejs/commit/be20528)) +* **deps:** update dependency gtoken to v3 ([#702](https://www.github.com/googleapis/google-auth-library-nodejs/issues/702)) ([2c538e5](https://www.github.com/googleapis/google-auth-library-nodejs/commit/2c538e5)) +* re-throw original exception and preserve message in compute client ([#668](https://www.github.com/googleapis/google-auth-library-nodejs/issues/668)) ([dffd1cc](https://www.github.com/googleapis/google-auth-library-nodejs/commit/dffd1cc)) +* surface original stack trace and message with errors ([#651](https://www.github.com/googleapis/google-auth-library-nodejs/issues/651)) ([8fb65eb](https://www.github.com/googleapis/google-auth-library-nodejs/commit/8fb65eb)) +* throw on missing refresh token in all cases ([#670](https://www.github.com/googleapis/google-auth-library-nodejs/issues/670)) ([0a02946](https://www.github.com/googleapis/google-auth-library-nodejs/commit/0a02946)) +* throw when adc cannot acquire a projectId ([#658](https://www.github.com/googleapis/google-auth-library-nodejs/issues/658)) ([ba48164](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ba48164)) +* **deps:** update dependency semver to v6 ([#655](https://www.github.com/googleapis/google-auth-library-nodejs/issues/655)) ([ec56c88](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ec56c88)) + + +### Build System + +* upgrade engines field to >=8.10.0 ([#686](https://www.github.com/googleapis/google-auth-library-nodejs/issues/686)) ([377d5c6](https://www.github.com/googleapis/google-auth-library-nodejs/commit/377d5c6)) + + +### Features + +* support scopes on compute credentials ([#642](https://www.github.com/googleapis/google-auth-library-nodejs/issues/642)) ([1811b7f](https://www.github.com/googleapis/google-auth-library-nodejs/commit/1811b7f)) + + +### BREAKING CHANGES + +* upgrade engines field to >=8.10.0 (#686) + +## v3.1.2 + +03-22-2019 15:38 PDT + +### Implementation Changes +- fix: getCredential(): load credentials with getClient() ([#648](https://github.com/google/google-auth-library-nodejs/pull/648)) + +### Internal / Testing Changes +- chore: publish to npm using wombat ([#645](https://github.com/google/google-auth-library-nodejs/pull/645)) + +## v3.1.1 + +03-18-2019 08:32 PDT + +### Bug Fixes +- fix: Avoid loading fast-text-encoding if not in browser environment ([#627](https://github.com/google/google-auth-library-nodejs/pull/627)) + +### Dependencies +- fix(deps): update dependency gcp-metadata to v1 ([#632](https://github.com/google/google-auth-library-nodejs/pull/632)) + +### Documentation +- docs: update links in contrib guide ([#630](https://github.com/google/google-auth-library-nodejs/pull/630)) + +### Internal / Testing Changes +- build: use per-repo publish token ([#641](https://github.com/google/google-auth-library-nodejs/pull/641)) +- build: Add docuploader credentials to node publish jobs ([#639](https://github.com/google/google-auth-library-nodejs/pull/639)) +- build: use node10 to run samples-test, system-test etc ([#638](https://github.com/google/google-auth-library-nodejs/pull/638)) +- build: update release configuration +- chore(deps): update dependency @types/lru-cache to v5 ([#635](https://github.com/google/google-auth-library-nodejs/pull/635)) +- chore(deps): update dependency mocha to v6 +- chore: fix lint ([#631](https://github.com/google/google-auth-library-nodejs/pull/631)) +- build: use linkinator for docs test ([#628](https://github.com/google/google-auth-library-nodejs/pull/628)) +- chore(deps): update dependency @types/tmp to ^0.0.34 ([#629](https://github.com/google/google-auth-library-nodejs/pull/629)) +- build: create docs test npm scripts ([#625](https://github.com/google/google-auth-library-nodejs/pull/625)) +- build: test using @grpc/grpc-js in CI ([#624](https://github.com/google/google-auth-library-nodejs/pull/624)) + +## v3.1.0 + +02-08-2019 08:29 PST + +### Bug fixes +- fix: use key file when fetching project id ([#618](https://github.com/googleapis/google-auth-library-nodejs/pull/618)) +- fix: Throw error if there is no refresh token despite the necessity of refreshing ([#605](https://github.com/googleapis/google-auth-library-nodejs/pull/605)) + +### New Features +- feat: allow passing constructor options to getClient ([#611](https://github.com/googleapis/google-auth-library-nodejs/pull/611)) + +### Documentation +- docs: update contributing path in README ([#621](https://github.com/googleapis/google-auth-library-nodejs/pull/621)) +- chore: move CONTRIBUTING.md to root ([#619](https://github.com/googleapis/google-auth-library-nodejs/pull/619)) +- docs: add lint/fix example to contributing guide ([#615](https://github.com/googleapis/google-auth-library-nodejs/pull/615)) +- docs: use the People API for samples ([#609](https://github.com/googleapis/google-auth-library-nodejs/pull/609)) + +### Internal / Testing Changes +- chore(deps): update dependency typescript to ~3.3.0 ([#612](https://github.com/googleapis/google-auth-library-nodejs/pull/612)) +- chore(deps): update dependency eslint-config-prettier to v4 ([#604](https://github.com/googleapis/google-auth-library-nodejs/pull/604)) +- build: ignore googleapis.com in doc link check ([#602](https://github.com/googleapis/google-auth-library-nodejs/pull/602)) +- chore(deps): update dependency karma to v4 ([#603](https://github.com/googleapis/google-auth-library-nodejs/pull/603)) + +## v3.0.1 + +01-16-2019 21:04 PST + +### Bug Fixes +- fix(deps): upgrade to the latest gaxios ([#596](https://github.com/googleapis/google-auth-library-nodejs/pull/596)) + +## v3.0.0 + +01-16-2019 10:00 PST + +Welcome to 3.0 🎉 This release has it all. New features, bug fixes, breaking changes, performance improvements - something for everyone! The biggest addition to this release is support for the browser via Webpack. + +**This release has breaking changes.** This release has a few breaking changes. These changes are unlikely to affect most clients. + +#### BREAKING: Migration from `axios` to `gaxios` +The 2.0 version of this library used the [axios](https://github.com/axios/axios) library for making HTTP requests. In the 3.0 release, this has been replaced by a *mostly* API compatible library [gaxios](https://github.com/JustinBeckwith/gaxios). The new request library natively supports proxies, and comes with a smaller dependency chain. While this is mostly an implementation detail, the `request` method was directly exposed via the `GoogleAuth.request` and `OAuth2Client.request` methods. The gaxios library aims to provide an API compatible implementation of axios, but that can never be 100% promised. If you run into bugs or differences that cause issues - please do let us know. + +#### BREAKING: `generateCodeVerifier` is now `generateCodeVerifierAsync` +The `OAuth2Client.generateCodeVerifier` method has been replaced by the `OAuth2Client.generateCodeVerifierAsync` method. It has changed from a synchronous method to an asynchronous method to support async browser crypto APIs required for Webpack support. + +#### BREAKING: `verifySignedJwtWithCerts` is now `verifySignedJwtWithCertsAsync` +The `OAuth2Client.verifySignedJwtWithCerts` method has been replaced by the `OAuth2Client.verifySignedJwtWithCertsAsync` method. It has changed from a synchronous method to an asynchronous method to support async browser crypto APIs required for Webpack support. + + +### New Features +- feat: make it webpackable ([#371](https://github.com/google/google-auth-library-nodejs/pull/371)) + +### Bug Fixes +- fix: accept lowercase env vars ([#578](https://github.com/google/google-auth-library-nodejs/pull/578)) + +### Dependencies +- chore(deps): update gtoken ([#592](https://github.com/google/google-auth-library-nodejs/pull/592)) +- fix(deps): upgrade to gcp-metadata v0.9.3 ([#586](https://github.com/google/google-auth-library-nodejs/pull/586)) + +### Documentation +- docs: update bug report link ([#585](https://github.com/google/google-auth-library-nodejs/pull/585)) +- docs: clarify access and refresh token docs ([#577](https://github.com/google/google-auth-library-nodejs/pull/577)) + +### Internal / Testing Changes +- refactor(deps): use `gaxios` for HTTP requests instead of `axios` ([#593](https://github.com/google/google-auth-library-nodejs/pull/593)) +- fix: some browser fixes ([#590](https://github.com/google/google-auth-library-nodejs/pull/590)) +- chore(deps): update dependency ts-loader to v5 ([#588](https://github.com/google/google-auth-library-nodejs/pull/588)) +- chore(deps): update dependency karma to v3 ([#587](https://github.com/google/google-auth-library-nodejs/pull/587)) +- build: check broken links in generated docs ([#579](https://github.com/google/google-auth-library-nodejs/pull/579)) +- chore(deps): drop unused dep on typedoc ([#583](https://github.com/google/google-auth-library-nodejs/pull/583)) +- build: add browser test running on Kokoro ([#584](https://github.com/google/google-auth-library-nodejs/pull/584)) +- test: improve samples and add tests ([#576](https://github.com/google/google-auth-library-nodejs/pull/576)) + +## v2.0.2 + +12-16-2018 10:48 PST + +### Fixes +- fix(types): export GCPEnv type ([#569](https://github.com/google/google-auth-library-nodejs/pull/569)) +- fix: use post for token revocation ([#524](https://github.com/google/google-auth-library-nodejs/pull/524)) + +### Dependencies +- fix(deps): update dependency lru-cache to v5 ([#541](https://github.com/google/google-auth-library-nodejs/pull/541)) + +### Documentation +- docs: add ref docs again ([#553](https://github.com/google/google-auth-library-nodejs/pull/553)) +- docs: clean up the readme ([#554](https://github.com/google/google-auth-library-nodejs/pull/554)) + +### Internal / Testing Changes +- chore(deps): update dependency @types/sinon to v7 ([#568](https://github.com/google/google-auth-library-nodejs/pull/568)) +- refactor: use execa for install tests, run eslint on samples ([#559](https://github.com/google/google-auth-library-nodejs/pull/559)) +- chore(build): inject yoshi automation key ([#566](https://github.com/google/google-auth-library-nodejs/pull/566)) +- chore: update nyc and eslint configs ([#565](https://github.com/google/google-auth-library-nodejs/pull/565)) +- chore: fix publish.sh permission +x ([#563](https://github.com/google/google-auth-library-nodejs/pull/563)) +- fix(build): fix Kokoro release script ([#562](https://github.com/google/google-auth-library-nodejs/pull/562)) +- build: add Kokoro configs for autorelease ([#561](https://github.com/google/google-auth-library-nodejs/pull/561)) +- chore: always nyc report before calling codecov ([#557](https://github.com/google/google-auth-library-nodejs/pull/557)) +- chore: nyc ignore build/test by default ([#556](https://github.com/google/google-auth-library-nodejs/pull/556)) +- chore(build): update the prettier and renovate config ([#552](https://github.com/google/google-auth-library-nodejs/pull/552)) +- chore: update license file ([#551](https://github.com/google/google-auth-library-nodejs/pull/551)) +- fix(build): fix system key decryption ([#547](https://github.com/google/google-auth-library-nodejs/pull/547)) +- chore(deps): update dependency typescript to ~3.2.0 ([#546](https://github.com/google/google-auth-library-nodejs/pull/546)) +- chore(deps): unpin sinon ([#544](https://github.com/google/google-auth-library-nodejs/pull/544)) +- refactor: drop non-required modules ([#542](https://github.com/google/google-auth-library-nodejs/pull/542)) +- chore: add synth.metadata ([#537](https://github.com/google/google-auth-library-nodejs/pull/537)) +- fix: Pin @types/sinon to last compatible version ([#538](https://github.com/google/google-auth-library-nodejs/pull/538)) +- chore(deps): update dependency gts to ^0.9.0 ([#531](https://github.com/google/google-auth-library-nodejs/pull/531)) +- chore: update eslintignore config ([#530](https://github.com/google/google-auth-library-nodejs/pull/530)) +- chore: drop contributors from multiple places ([#528](https://github.com/google/google-auth-library-nodejs/pull/528)) +- chore: use latest npm on Windows ([#527](https://github.com/google/google-auth-library-nodejs/pull/527)) +- chore: update CircleCI config ([#523](https://github.com/google/google-auth-library-nodejs/pull/523)) +- chore: include build in eslintignore ([#516](https://github.com/google/google-auth-library-nodejs/pull/516)) + +## v2.0.1 + +### Implementation Changes +- fix: verifyIdToken will never return null ([#488](https://github.com/google/google-auth-library-nodejs/pull/488)) +- Update the url to application default credentials ([#470](https://github.com/google/google-auth-library-nodejs/pull/470)) +- Update omitted parameter 'hd' ([#467](https://github.com/google/google-auth-library-nodejs/pull/467)) + +### Dependencies +- chore(deps): update dependency nock to v10 ([#501](https://github.com/google/google-auth-library-nodejs/pull/501)) +- chore(deps): update dependency sinon to v7 ([#502](https://github.com/google/google-auth-library-nodejs/pull/502)) +- chore(deps): update dependency typescript to v3.1.3 ([#503](https://github.com/google/google-auth-library-nodejs/pull/503)) +- chore(deps): update dependency gh-pages to v2 ([#499](https://github.com/google/google-auth-library-nodejs/pull/499)) +- chore(deps): update dependency typedoc to ^0.13.0 ([#497](https://github.com/google/google-auth-library-nodejs/pull/497)) + +### Documentation +- docs: Remove code format from Application Default Credentials ([#483](https://github.com/google/google-auth-library-nodejs/pull/483)) +- docs: replace google/ with googleapis/ in URIs ([#472](https://github.com/google/google-auth-library-nodejs/pull/472)) +- Fix typo in readme ([#469](https://github.com/google/google-auth-library-nodejs/pull/469)) +- Update samples and docs for 2.0 ([#459](https://github.com/google/google-auth-library-nodejs/pull/459)) + +### Internal / Testing Changes +- chore: update issue templates ([#509](https://github.com/google/google-auth-library-nodejs/pull/509)) +- chore: remove old issue template ([#507](https://github.com/google/google-auth-library-nodejs/pull/507)) +- build: run tests on node11 ([#506](https://github.com/google/google-auth-library-nodejs/pull/506)) +- chore(build): drop hard rejection and update gts in the kitchen test ([#504](https://github.com/google/google-auth-library-nodejs/pull/504)) +- chores(build): do not collect sponge.xml from windows builds ([#500](https://github.com/google/google-auth-library-nodejs/pull/500)) +- chores(build): run codecov on continuous builds ([#495](https://github.com/google/google-auth-library-nodejs/pull/495)) +- chore: update new issue template ([#494](https://github.com/google/google-auth-library-nodejs/pull/494)) +- build: fix codecov uploading on Kokoro ([#490](https://github.com/google/google-auth-library-nodejs/pull/490)) +- test: move kitchen sink tests to system-test ([#489](https://github.com/google/google-auth-library-nodejs/pull/489)) +- Update kokoro config ([#482](https://github.com/google/google-auth-library-nodejs/pull/482)) +- fix: export additional typescript types ([#479](https://github.com/google/google-auth-library-nodejs/pull/479)) +- Don't publish sourcemaps ([#478](https://github.com/google/google-auth-library-nodejs/pull/478)) +- test: remove appveyor config ([#477](https://github.com/google/google-auth-library-nodejs/pull/477)) +- Enable prefer-const in the eslint config ([#473](https://github.com/google/google-auth-library-nodejs/pull/473)) +- Enable no-var in eslint ([#471](https://github.com/google/google-auth-library-nodejs/pull/471)) +- Update CI config ([#468](https://github.com/google/google-auth-library-nodejs/pull/468)) +- Retry npm install in CI ([#465](https://github.com/google/google-auth-library-nodejs/pull/465)) +- Update Kokoro config ([#462](https://github.com/google/google-auth-library-nodejs/pull/462)) + +## v2.0.0 + +Well hello 2.0 🎉 **This release has multiple breaking changes**. It also has a lot of bug fixes. + +### Breaking Changes + +#### Support for node.js 4.x and 9.x has been dropped +These versions of node.js are no longer supported. + +#### The `getRequestMetadata` method has been deprecated +The `getRequestMetadata` method has been deprecated on the `IAM`, `OAuth2`, `JWT`, and `JWTAccess` classes. The `getRequestHeaders` method should be used instead. The methods have a subtle difference: the `getRequestMetadata` method returns an object with a headers property, which contains the authorization header. The `getRequestHeaders` method simply returns the headers. + +##### Old code +```js +const client = await auth.getClient(); +const res = await client.getRequestMetadata(); +const headers = res.headers; +``` + +##### New code +```js +const client = await auth.getClient(); +const headers = await client.getRequestHeaders(); +``` + +#### The `createScopedRequired` method has been deprecated +The `createScopedRequired` method has been deprecated on multiple classes. The `createScopedRequired` and `createScoped` methods on the `JWT` class were largely in place to help inform clients when scopes were required in an application default credential scenario. Instead of checking if scopes are required after creating the client, instead scopes should just be passed either into the `GoogleAuth.getClient` method, or directly into the `JWT` constructor. + +##### Old code +```js +auth.getApplicationDefault(function(err, authClient) { + if (err) { + return callback(err); + } + if (authClient.createScopedRequired && authClient.createScopedRequired()) { + authClient = authClient.createScoped([ + 'https://www.googleapis.com/auth/cloud-platform' + ]); + } + callback(null, authClient); +}); +``` + +##### New code +```js +const client = await auth.getClient({ + scopes: ['https://www.googleapis.com/auth/cloud-platform'] +}); +``` + +#### Deprecate `refreshAccessToken` + +_Note: `refreshAccessToken` is no longer deprecated._ + +`getAccessToken`, `getRequestMetadata`, and `request` methods will all refresh the token if needed automatically. + +You should not need to invoke `refreshAccessToken` directly except in [certain edge-cases](https://github.com/googleapis/google-auth-library-nodejs/issues/575). + +### Features +- Set private_key_id in JWT access token header like other google auth libraries. (#450) + +### Bug Fixes +- fix: support HTTPS proxies (#405) +- fix: export missing interfaces (#437) +- fix: Use new auth URIs (#434) +- docs: Fix broken link (#423) +- fix: surface file read streams (#413) +- fix: prevent unhandled rejections by avoid .catch (#404) +- fix: use gcp-metadata for compute credentials (#409) +- Add Code of Conduct +- fix: Warn when using user credentials from the Cloud SDK (#399) +- fix: use `Buffer.from` instead of `new Buffer` (#400) +- fix: Fix link format in README.md (#385) + +### Breaking changes +- chore: deprecate getRequestMetadata (#414) +- fix: deprecate the `createScopedRequired` methods (#410) +- fix: drop support for node.js 4.x and 9.x (#417) +- fix: deprecate the `refreshAccessToken` methods (#411) +- fix: deprecate the `getDefaultProjectId` method (#402) +- fix: drop support for node.js 4 (#401) + +### Build / Test changes +- Run synth to make build tools consistent (#455) +- Add a package.json for samples and cleanup README (#454) +- chore(deps): update dependency typedoc to ^0.12.0 (#453) +- chore: move examples => samples + synth (#448) +- chore(deps): update dependency nyc to v13 (#452) +- chore(deps): update dependency pify to v4 (#447) +- chore(deps): update dependency assert-rejects to v1 (#446) +- chore: ignore package-lock.json (#445) +- chore: update renovate config (#442) +- chore(deps): lock file maintenance (#443) +- chore: remove greenkeeper badge (#440) +- test: throw on deprecation +- chore: add intelli-espower-loader for running tests (#430) +- chore(deps): update dependency typescript to v3 (#432) +- chore(deps): lock file maintenance (#431) +- test: use strictEqual in tests (#425) +- chore(deps): lock file maintenance (#428) +- chore: Configure Renovate (#424) +- chore: Update gts to the latest version 🚀 (#422) +- chore: update gcp-metadata for isAvailable fix (#420) +- refactor: use assert.reject in the tests (#415) +- refactor: cleanup types for certificates (#412) +- test: run tests with hard-rejection (#397) +- cleanup: straighten nested try-catch (#394) +- test: getDefaultProjectId should prefer config (#388) +- chore(package): Update gts to the latest version 🚀 (#387) +- chore(package): update sinon to version 6.0.0 (#386) + +## Upgrading to 1.x +The `1.x` release includes a variety of bug fixes, new features, and breaking changes. Please take care, and see [the release notes](https://github.com/googleapis/google-auth-library-nodejs/releases/tag/v1.0.0) for a list of breaking changes, and the upgrade guide. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/LICENSE b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/README.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4e9255efb59acaa945e58e05ebf2840222c3302b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/README.md @@ -0,0 +1,1470 @@ +[//]: # "This README.md file is auto-generated, all changes to this file will be lost." +[//]: # "To regenerate it, use `python -m synthtool`." +Google Cloud Platform logo + +# [Google Auth Library: Node.js Client](https://github.com/googleapis/google-auth-library-nodejs) + +[![release level](https://img.shields.io/badge/release%20level-stable-brightgreen.svg?style=flat)](https://cloud.google.com/terms/launch-stages) +[![npm version](https://img.shields.io/npm/v/google-auth-library.svg)](https://www.npmjs.org/package/google-auth-library) + + + + +This is Google's officially supported [node.js](http://nodejs.org/) client library for using OAuth 2.0 authorization and authentication with Google APIs. + + +A comprehensive list of changes in each version may be found in +[the CHANGELOG](https://github.com/googleapis/google-auth-library-nodejs/blob/main/CHANGELOG.md). + +* [Google Auth Library Node.js Client API Reference][client-docs] +* [Google Auth Library Documentation][product-docs] +* [github.com/googleapis/google-auth-library-nodejs](https://github.com/googleapis/google-auth-library-nodejs) + +Read more about the client libraries for Cloud APIs, including the older +Google APIs Client Libraries, in [Client Libraries Explained][explained]. + +[explained]: https://cloud.google.com/apis/docs/client-libraries-explained + +**Table of contents:** + + +* [Quickstart](#quickstart) + + * [Installing the client library](#installing-the-client-library) + +* [Samples](#samples) +* [Versioning](#versioning) +* [Contributing](#contributing) +* [License](#license) + +## Quickstart + +### Installing the client library + +```bash +npm install google-auth-library +``` + +## Ways to authenticate +This library provides a variety of ways to authenticate to your Google services. +- [Application Default Credentials](#choosing-the-correct-credential-type-automatically) - Use Application Default Credentials when you use a single identity for all users in your application. Especially useful for applications running on Google Cloud. Application Default Credentials also support workload identity federation to access Google Cloud resources from non-Google Cloud platforms. +- [OAuth 2](#oauth2) - Use OAuth2 when you need to perform actions on behalf of the end user. +- [JSON Web Tokens](#json-web-tokens) - Use JWT when you are using a single identity for all users. Especially useful for server->server or server->API communication. +- [Google Compute](#compute) - Directly use a service account on Google Cloud Platform. Useful for server->server or server->API communication. +- [Workload Identity Federation](#workload-identity-federation) - Use workload identity federation to access Google Cloud resources from Amazon Web Services (AWS), Microsoft Azure or any identity provider that supports OpenID Connect (OIDC). +- [Workforce Identity Federation](#workforce-identity-federation) - Use workforce identity federation to access Google Cloud resources using an external identity provider (IdP) to authenticate and authorize a workforce—a group of users, such as employees, partners, and contractors—using IAM, so that the users can access Google Cloud services. +- [Impersonated Credentials Client](#impersonated-credentials-client) - access protected resources on behalf of another service account. +- [Downscoped Client](#downscoped-client) - Use Downscoped Client with Credential Access Boundary to generate a short-lived credential with downscoped, restricted IAM permissions that can use for Cloud Storage. + +## Application Default Credentials +This library provides an implementation of [Application Default Credentials](https://cloud.google.com/docs/authentication/getting-started) for Node.js. The [Application Default Credentials](https://cloud.google.com/docs/authentication/getting-started) provide a simple way to get authorization credentials for use in calling Google APIs. + +They are best suited for cases when the call needs to have the same identity and authorization level for the application independent of the user. This is the recommended approach to authorize calls to Cloud APIs, particularly when you're building an application that uses Google Cloud Platform. + +Application Default Credentials also support workload identity federation to access Google Cloud resources from non-Google Cloud platforms including Amazon Web Services (AWS), Microsoft Azure or any identity provider that supports OpenID Connect (OIDC). Workload identity federation is recommended for non-Google Cloud environments as it avoids the need to download, manage and store service account private keys locally, see: [Workload Identity Federation](#workload-identity-federation). + +#### Download your Service Account Credentials JSON file + +To use Application Default Credentials, You first need to download a set of JSON credentials for your project. Go to **APIs & Auth** > **Credentials** in the [Google Developers Console](https://console.cloud.google.com/) and select **Service account** from the **Add credentials** dropdown. + +> This file is your *only copy* of these credentials. It should never be +> committed with your source code, and should be stored securely. + +Once downloaded, store the path to this file in the `GOOGLE_APPLICATION_CREDENTIALS` environment variable. + +#### Enable the API you want to use + +Before making your API call, you must be sure the API you're calling has been enabled. Go to **APIs & Auth** > **APIs** in the [Google Developers Console](https://console.cloud.google.com/) and enable the APIs you'd like to call. For the example below, you must enable the `DNS API`. + + +#### Choosing the correct credential type automatically + +Rather than manually creating an OAuth2 client, JWT client, or Compute client, the auth library can create the correct credential type for you, depending upon the environment your code is running under. + +For example, a JWT auth client will be created when your code is running on your local developer machine, and a Compute client will be created when the same code is running on Google Cloud Platform. If you need a specific set of scopes, you can pass those in the form of a string or an array to the `GoogleAuth` constructor. + +The code below shows how to retrieve a default credential type, depending upon the runtime environment. + +```js +const {GoogleAuth} = require('google-auth-library'); + +/** +* Instead of specifying the type of client you'd like to use (JWT, OAuth2, etc) +* this library will automatically choose the right client based on the environment. +*/ +async function main() { + const auth = new GoogleAuth({ + scopes: 'https://www.googleapis.com/auth/cloud-platform' + }); + const client = await auth.getClient(); + const projectId = await auth.getProjectId(); + const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; + const res = await client.request({ url }); + console.log(res.data); +} + +main().catch(console.error); +``` + +## OAuth2 + +This library comes with an [OAuth2](https://developers.google.com/identity/protocols/OAuth2) client that allows you to retrieve an access token and refreshes the token and retry the request seamlessly if you also provide an `expiry_date` and the token is expired. The basics of Google's OAuth2 implementation is explained on [Google Authorization and Authentication documentation](https://developers.google.com/accounts/docs/OAuth2Login). + +In the following examples, you may need a `CLIENT_ID`, `CLIENT_SECRET` and `REDIRECT_URL`. You can find these pieces of information by going to the [Developer Console](https://console.cloud.google.com/), clicking your project > APIs & auth > credentials. + +For more information about OAuth2 and how it works, [see here](https://developers.google.com/identity/protocols/OAuth2). + +#### A complete OAuth2 example + +Let's take a look at a complete example. + +``` js +const {OAuth2Client} = require('google-auth-library'); +const http = require('http'); +const url = require('url'); +const open = require('open'); +const destroyer = require('server-destroy'); + +// Download your OAuth2 configuration from the Google +const keys = require('./oauth2.keys.json'); + +/** +* Start by acquiring a pre-authenticated oAuth2 client. +*/ +async function main() { + const oAuth2Client = await getAuthenticatedClient(); + // Make a simple request to the People API using our pre-authenticated client. The `request()` method + // takes an GaxiosOptions object. Visit https://github.com/JustinBeckwith/gaxios. + const url = 'https://people.googleapis.com/v1/people/me?personFields=names'; + const res = await oAuth2Client.request({url}); + console.log(res.data); + + // After acquiring an access_token, you may want to check on the audience, expiration, + // or original scopes requested. You can do that with the `getTokenInfo` method. + const tokenInfo = await oAuth2Client.getTokenInfo( + oAuth2Client.credentials.access_token + ); + console.log(tokenInfo); +} + +/** +* Create a new OAuth2Client, and go through the OAuth2 content +* workflow. Return the full client to the callback. +*/ +function getAuthenticatedClient() { + return new Promise((resolve, reject) => { + // create an oAuth client to authorize the API call. Secrets are kept in a `keys.json` file, + // which should be downloaded from the Google Developers Console. + const oAuth2Client = new OAuth2Client( + keys.web.client_id, + keys.web.client_secret, + keys.web.redirect_uris[0] + ); + + // Generate the url that will be used for the consent dialog. + const authorizeUrl = oAuth2Client.generateAuthUrl({ + access_type: 'offline', + scope: 'https://www.googleapis.com/auth/userinfo.profile', + }); + + // Open an http server to accept the oauth callback. In this simple example, the + // only request to our webserver is to /oauth2callback?code= + const server = http + .createServer(async (req, res) => { + try { + if (req.url.indexOf('/oauth2callback') > -1) { + // acquire the code from the querystring, and close the web server. + const qs = new url.URL(req.url, 'http://localhost:3000') + .searchParams; + const code = qs.get('code'); + console.log(`Code is ${code}`); + res.end('Authentication successful! Please return to the console.'); + server.destroy(); + + // Now that we have the code, use that to acquire tokens. + const r = await oAuth2Client.getToken(code); + // Make sure to set the credentials on the OAuth2 client. + oAuth2Client.setCredentials(r.tokens); + console.info('Tokens acquired.'); + resolve(oAuth2Client); + } + } catch (e) { + reject(e); + } + }) + .listen(3000, () => { + // open the browser to the authorize url to start the workflow + open(authorizeUrl, {wait: false}).then(cp => cp.unref()); + }); + destroyer(server); + }); +} + +main().catch(console.error); +``` + +#### Handling token events + +This library will automatically obtain an `access_token`, and automatically refresh the `access_token` if a `refresh_token` is present. The `refresh_token` is only returned on the [first authorization](https://github.com/googleapis/google-api-nodejs-client/issues/750#issuecomment-304521450), so if you want to make sure you store it safely. An easy way to make sure you always store the most recent tokens is to use the `tokens` event: + +```js +const client = await auth.getClient(); + +client.on('tokens', (tokens) => { + if (tokens.refresh_token) { + // store the refresh_token in my database! + console.log(tokens.refresh_token); + } + console.log(tokens.access_token); +}); + +const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; +const res = await client.request({ url }); +// The `tokens` event would now be raised if this was the first request +``` + +#### Retrieve access token +With the code returned, you can ask for an access token as shown below: + +``` js +const tokens = await oauth2Client.getToken(code); +// Now tokens contains an access_token and an optional refresh_token. Save them. +oauth2Client.setCredentials(tokens); +``` + +#### Obtaining a new Refresh Token +If you need to obtain a new `refresh_token`, ensure the call to `generateAuthUrl` sets the `access_type` to `offline`. The refresh token will only be returned for the first authorization by the user. To force consent, set the `prompt` property to `consent`: + +```js +// Generate the url that will be used for the consent dialog. +const authorizeUrl = oAuth2Client.generateAuthUrl({ + // To get a refresh token, you MUST set access_type to `offline`. + access_type: 'offline', + // set the appropriate scopes + scope: 'https://www.googleapis.com/auth/userinfo.profile', + // A refresh token is only returned the first time the user + // consents to providing access. For illustration purposes, + // setting the prompt to 'consent' will force this consent + // every time, forcing a refresh_token to be returned. + prompt: 'consent' +}); +``` + +#### Checking `access_token` information +After obtaining and storing an `access_token`, at a later time you may want to go check the expiration date, +original scopes, or audience for the token. To get the token info, you can use the `getTokenInfo` method: + +```js +// after acquiring an oAuth2Client... +const tokenInfo = await oAuth2Client.getTokenInfo('my-access-token'); + +// take a look at the scopes originally provisioned for the access token +console.log(tokenInfo.scopes); +``` + +This method will throw if the token is invalid. + +#### Using an API Key + +An API key can be provided to the constructor: +```js +const client = new OAuth2Client({ + apiKey: 'my-api-key' +}); +``` + +Note, classes that extend from this can utilize this parameter as well, such as `JWT` and `UserRefreshClient`. + +Additionally, an API key can be used in `GoogleAuth` via the `clientOptions` parameter and will be passed to any generated `OAuth2Client` instances: +```js +const auth = new GoogleAuth({ + clientOptions: { + apiKey: 'my-api-key' + } +}) +``` + +API Key support varies by API. + +## JSON Web Tokens +The Google Developers Console provides a `.json` file that you can use to configure a JWT auth client and authenticate your requests, for example when using a service account. + +``` js +const {JWT} = require('google-auth-library'); +const keys = require('./jwt.keys.json'); + +async function main() { + const client = new JWT({ + email: keys.client_email, + key: keys.private_key, + scopes: ['https://www.googleapis.com/auth/cloud-platform'], + }); + const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`; + const res = await client.request({url}); + console.log(res.data); +} + +main().catch(console.error); +``` + +The parameters for the JWT auth client including how to use it with a `.pem` file are explained in [samples/jwt.js](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/jwt.js). + +#### Loading credentials from environment variables +Instead of loading credentials from a key file, you can also provide them using an environment variable and the `GoogleAuth.fromJSON()` method. This is particularly convenient for systems that deploy directly from source control (Heroku, App Engine, etc). + +Start by exporting your credentials: + +``` +$ export CREDS='{ + "type": "service_account", + "project_id": "your-project-id", + "private_key_id": "your-private-key-id", + "private_key": "your-private-key", + "client_email": "your-client-email", + "client_id": "your-client-id", + "auth_uri": "https://accounts.google.com/o/oauth2/auth", + "token_uri": "https://accounts.google.com/o/oauth2/token", + "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", + "client_x509_cert_url": "your-cert-url" +}' +``` +Now you can create a new client from the credentials: + +```js +const {auth} = require('google-auth-library'); + +// load the environment variable with our keys +const keysEnvVar = process.env['CREDS']; +if (!keysEnvVar) { + throw new Error('The $CREDS environment variable was not found!'); +} +const keys = JSON.parse(keysEnvVar); + +async function main() { + // load the JWT or UserRefreshClient from the keys + const client = auth.fromJSON(keys); + client.scopes = ['https://www.googleapis.com/auth/cloud-platform']; + const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`; + const res = await client.request({url}); + console.log(res.data); +} + +main().catch(console.error); +``` + +**Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to [Validate credential configurations from external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials). + +#### Using a Proxy +You can set the `HTTPS_PROXY` or `https_proxy` environment variables to proxy HTTPS requests. When `HTTPS_PROXY` or `https_proxy` are set, they will be used to proxy SSL requests that do not have an explicit proxy configuration option present. + +## Compute +If your application is running on Google Cloud Platform, you can authenticate using the default service account or by specifying a specific service account. + +**Note**: In most cases, you will want to use [Application Default Credentials](#choosing-the-correct-credential-type-automatically). Direct use of the `Compute` class is for very specific scenarios. + +``` js +const {auth, Compute} = require('google-auth-library'); + +async function main() { + const client = new Compute({ + // Specifying the service account email is optional. + serviceAccountEmail: 'my-service-account@example.com' + }); + const projectId = await auth.getProjectId(); + const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; + const res = await client.request({url}); + console.log(res.data); +} + +main().catch(console.error); +``` + +## Workload Identity Federation + +Using workload identity federation, your application can access Google Cloud resources from Amazon Web Services (AWS), Microsoft Azure or any identity provider that supports OpenID Connect (OIDC). + +Traditionally, applications running outside Google Cloud have used service account keys to access Google Cloud resources. Using identity federation, you can allow your workload to impersonate a service account. +This lets you access Google Cloud resources directly, eliminating the maintenance and security burden associated with service account keys. + +### Accessing resources from AWS + +In order to access Google Cloud resources from Amazon Web Services (AWS), the following requirements are needed: +- A workload identity pool needs to be created. +- AWS needs to be added as an identity provider in the workload identity pool (The Google [organization policy](https://cloud.google.com/iam/docs/manage-workload-identity-pools-providers#restrict) needs to allow federation from AWS). +- Permission to impersonate a service account needs to be granted to the external identity. + +Follow the detailed [instructions](https://cloud.google.com/iam/docs/access-resources-aws) on how to configure workload identity federation from AWS. + +After configuring the AWS provider to impersonate a service account, a credential configuration file needs to be generated. +Unlike service account credential files, the generated credential configuration file will only contain non-sensitive metadata to instruct the library on how to retrieve external subject tokens and exchange them for service account access tokens. +The configuration file can be generated by using the [gcloud CLI](https://cloud.google.com/sdk/). + +To generate the AWS workload identity configuration, run the following command: + +```bash +# Generate an AWS configuration file. +gcloud iam workload-identity-pools create-cred-config \ + projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AWS_PROVIDER_ID \ + --service-account $SERVICE_ACCOUNT_EMAIL \ + --aws \ + --output-file /path/to/generated/config.json +``` + +Where the following variables need to be substituted: +- `$PROJECT_NUMBER`: The Google Cloud project number. +- `$POOL_ID`: The workload identity pool ID. +- `$AWS_PROVIDER_ID`: The AWS provider ID. +- `$SERVICE_ACCOUNT_EMAIL`: The email of the service account to impersonate. + +This will generate the configuration file in the specified output file. + +If you want to use the AWS IMDSv2 flow, you can add the field below to the credential_source in your AWS ADC configuration file: +"imdsv2_session_token_url": "http://169.254.169.254/latest/api/token" +The gcloud create-cred-config command will be updated to support this soon. + +You can now [start using the Auth library](#using-external-identities) to call Google Cloud resources from AWS. + +### Accessing resources from AWS using a custom AWS security credentials supplier. + +In order to access Google Cloud resources from Amazon Web Services (AWS), the following requirements are needed: +- A workload identity pool needs to be created. +- AWS needs to be added as an identity provider in the workload identity pool (The Google [organization policy](https://cloud.google.com/iam/docs/manage-workload-identity-pools-providers#restrict) needs to allow federation from AWS). +- Permission to impersonate a service account needs to be granted to the external identity. + +Follow the detailed [instructions](https://cloud.google.com/iam/docs/access-resources-aws) on how to configure workload identity federation from AWS. + +If you want to use AWS security credentials that cannot be retrieved using methods supported natively by this library, +a custom AwsSecurityCredentialsSupplier implementation may be specified when creating an AWS client. The supplier must +return valid, unexpired AWS security credentials when called by the GCP credential. Currently, using ADC with your AWS +workloads is only supported with EC2. An example of a good use case for using a custom credential suppliers is when +your workloads are running in other AWS environments, such as ECS, EKS, Fargate, etc. + +Note that the client does not cache the returned AWS security credentials, so caching logic should be implemented in the supplier to prevent multiple requests for the same resources. + +```ts +import { AwsClient, AwsSecurityCredentials, AwsSecurityCredentialsSupplier, ExternalAccountSupplierContext } from 'google-auth-library'; +import { fromNodeProviderChain } from '@aws-sdk/credential-providers'; +import { Storage } from '@google-cloud/storage'; + +class AwsSupplier implements AwsSecurityCredentialsSupplier { + private readonly region: string + + constructor(region: string) { + this.region = options.region; + } + + async getAwsRegion(context: ExternalAccountSupplierContext): Promise { + // Return the AWS region i.e. "us-east-2". + return this.region + } + + async getAwsSecurityCredentials( + context: ExternalAccountSupplierContext + ): Promise { + // Retrieve the AWS credentails. + const awsCredentialsProvider = fromNodeProviderChain(); + const awsCredentials = await awsCredentialsProvider(); + + // Parse the AWS credentials into a AWS security credentials instance and + // return them. + const awsSecurityCredentials = { + accessKeyId: awsCredentials.accessKeyId, + secretAccessKey: awsCredentials.secretAccessKey, + token: awsCredentials.sessionToken + } + return awsSecurityCredentials; + } +} + +const clientOptions = { + audience: '//iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$WORKLOAD_POOL_ID/providers/$PROVIDER_ID', // Set the GCP audience. + subject_token_type: 'urn:ietf:params:aws:token-type:aws4_request', // Set the subject token type. + aws_security_credentials_supplier: new AwsSupplier("AWS_REGION") // Set the custom supplier. + service_account_impersonation_url: 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/$EMAIL:generateAccessToken', // Set the service account impersonation url. +} + +// Create a new Auth client and use it to create service client, i.e. storage. +const authClient = new AwsClient(clientOptions); +const storage = new Storage({ authClient }); +``` + +Where the [audience](https://cloud.google.com/iam/docs/best-practices-for-using-workload-identity-federation#provider-audience) is: `//iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$WORKLOAD_POOL_ID/providers/$PROVIDER_ID` + +Where the following variables need to be substituted: + +* `$PROJECT_NUMBER`: The Google Cloud project number. +* `$WORKLOAD_POOL_ID`: The workload pool ID. +* `$PROVIDER_ID`: The provider ID. + + +The values for audience, service account impersonation URL, and any other builder field can also be found by generating a [credential configuration file with the gcloud CLI](https://cloud.google.com/sdk/gcloud/reference/iam/workload-identity-pools/create-cred-config). + +### Access resources from Microsoft Azure + +In order to access Google Cloud resources from Microsoft Azure, the following requirements are needed: +- A workload identity pool needs to be created. +- Azure needs to be added as an identity provider in the workload identity pool (The Google [organization policy](https://cloud.google.com/iam/docs/manage-workload-identity-pools-providers#restrict) needs to allow federation from Azure). +- The Azure tenant needs to be configured for identity federation. +- Permission to impersonate a service account needs to be granted to the external identity. + +Follow the detailed [instructions](https://cloud.google.com/iam/docs/access-resources-azure) on how to configure workload identity federation from Microsoft Azure. + +After configuring the Azure provider to impersonate a service account, a credential configuration file needs to be generated. +Unlike service account credential files, the generated credential configuration file will only contain non-sensitive metadata to instruct the library on how to retrieve external subject tokens and exchange them for service account access tokens. +The configuration file can be generated by using the [gcloud CLI](https://cloud.google.com/sdk/). + +To generate the Azure workload identity configuration, run the following command: + +```bash +# Generate an Azure configuration file. +gcloud iam workload-identity-pools create-cred-config \ + projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AZURE_PROVIDER_ID \ + --service-account $SERVICE_ACCOUNT_EMAIL \ + --azure \ + --output-file /path/to/generated/config.json +``` + +Where the following variables need to be substituted: +- `$PROJECT_NUMBER`: The Google Cloud project number. +- `$POOL_ID`: The workload identity pool ID. +- `$AZURE_PROVIDER_ID`: The Azure provider ID. +- `$SERVICE_ACCOUNT_EMAIL`: The email of the service account to impersonate. + +This will generate the configuration file in the specified output file. + +You can now [start using the Auth library](#using-external-identities) to call Google Cloud resources from Azure. + +### Accessing resources from an OIDC identity provider + +In order to access Google Cloud resources from an identity provider that supports [OpenID Connect (OIDC)](https://openid.net/connect/), the following requirements are needed: +- A workload identity pool needs to be created. +- An OIDC identity provider needs to be added in the workload identity pool (The Google [organization policy](https://cloud.google.com/iam/docs/manage-workload-identity-pools-providers#restrict) needs to allow federation from the identity provider). +- Permission to impersonate a service account needs to be granted to the external identity. + +Follow the detailed [instructions](https://cloud.google.com/iam/docs/access-resources-oidc) on how to configure workload identity federation from an OIDC identity provider. + +After configuring the OIDC provider to impersonate a service account, a credential configuration file needs to be generated. +Unlike service account credential files, the generated credential configuration file will only contain non-sensitive metadata to instruct the library on how to retrieve external subject tokens and exchange them for service account access tokens. +The configuration file can be generated by using the [gcloud CLI](https://cloud.google.com/sdk/). + +For OIDC providers, the Auth library can retrieve OIDC tokens either from a local file location (file-sourced credentials) or from a local server (URL-sourced credentials). + +**File-sourced credentials** +For file-sourced credentials, a background process needs to be continuously refreshing the file location with a new OIDC token prior to expiration. +For tokens with one hour lifetimes, the token needs to be updated in the file every hour. The token can be stored directly as plain text or in JSON format. + +To generate a file-sourced OIDC configuration, run the following command: + +```bash +# Generate an OIDC configuration file for file-sourced credentials. +gcloud iam workload-identity-pools create-cred-config \ + projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$OIDC_PROVIDER_ID \ + --service-account $SERVICE_ACCOUNT_EMAIL \ + --credential-source-file $PATH_TO_OIDC_ID_TOKEN \ + # Optional arguments for file types. Default is "text": + # --credential-source-type "json" \ + # Optional argument for the field that contains the OIDC credential. + # This is required for json. + # --credential-source-field-name "id_token" \ + --output-file /path/to/generated/config.json +``` + +Where the following variables need to be substituted: +- `$PROJECT_NUMBER`: The Google Cloud project number. +- `$POOL_ID`: The workload identity pool ID. +- `$OIDC_PROVIDER_ID`: The OIDC provider ID. +- `$SERVICE_ACCOUNT_EMAIL`: The email of the service account to impersonate. +- `$PATH_TO_OIDC_ID_TOKEN`: The file path where the OIDC token will be retrieved from. + +This will generate the configuration file in the specified output file. + +**URL-sourced credentials** +For URL-sourced credentials, a local server needs to host a GET endpoint to return the OIDC token. The response can be in plain text or JSON. +Additional required request headers can also be specified. + +To generate a URL-sourced OIDC workload identity configuration, run the following command: + +```bash +# Generate an OIDC configuration file for URL-sourced credentials. +gcloud iam workload-identity-pools create-cred-config \ + projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$OIDC_PROVIDER_ID \ + --service-account $SERVICE_ACCOUNT_EMAIL \ + --credential-source-url $URL_TO_GET_OIDC_TOKEN \ + --credential-source-headers $HEADER_KEY=$HEADER_VALUE \ + # Optional arguments for file types. Default is "text": + # --credential-source-type "json" \ + # Optional argument for the field that contains the OIDC credential. + # This is required for json. + # --credential-source-field-name "id_token" \ + --output-file /path/to/generated/config.json +``` + +Where the following variables need to be substituted: +- `$PROJECT_NUMBER`: The Google Cloud project number. +- `$POOL_ID`: The workload identity pool ID. +- `$OIDC_PROVIDER_ID`: The OIDC provider ID. +- `$SERVICE_ACCOUNT_EMAIL`: The email of the service account to impersonate. +- `$URL_TO_GET_OIDC_TOKEN`: The URL of the local server endpoint to call to retrieve the OIDC token. +- `$HEADER_KEY` and `$HEADER_VALUE`: The additional header key/value pairs to pass along the GET request to `$URL_TO_GET_OIDC_TOKEN`, e.g. `Metadata-Flavor=Google`. + +### Accessing resources from an OIDC or SAML2.0 identity provider using a custom supplier + +If you want to use OIDC or SAML2.0 that cannot be retrieved using methods supported natively by this library, +a custom SubjectTokenSupplier implementation may be specified when creating an identity pool client. The supplier must +return a valid, unexpired subject token when called by the GCP credential. + +Note that the client does not cache the returned subject token, so caching logic should be implemented in the supplier to prevent multiple requests for the same resources. + +```ts +class CustomSupplier implements SubjectTokenSupplier { + async getSubjectToken( + context: ExternalAccountSupplierContext + ): Promise { + const audience = context.audience; + const subjectTokenType = context.subjectTokenType; + // Return a valid subject token for the requested audience and subject token type. + } +} + +const clientOptions = { + audience: '//iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$WORKLOAD_POOL_ID/providers/$PROVIDER_ID', // Set the GCP audience. + subject_token_type: 'urn:ietf:params:oauth:token-type:id_token', // Set the subject token type. + subject_token_supplier: new CustomSupplier() // Set the custom supplier. +} + +const client = new CustomSupplier(clientOptions); +``` + +Where the [audience](https://cloud.google.com/iam/docs/best-practices-for-using-workload-identity-federation#provider-audience) is: `//iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$WORKLOAD_POOL_ID/providers/$PROVIDER_ID` + +Where the following variables need to be substituted: + +* `$PROJECT_NUMBER`: The Google Cloud project number. +* `$WORKLOAD_POOL_ID`: The workload pool ID. +* `$PROVIDER_ID`: The provider ID. + +The values for audience, service account impersonation URL, and any other builder field can also be found by generating a [credential configuration file with the gcloud CLI](https://cloud.google.com/sdk/gcloud/reference/iam/workload-identity-pools/create-cred-config). + +#### Using External Account Authorized User workforce credentials + +[External account authorized user credentials](https://cloud.google.com/iam/docs/workforce-obtaining-short-lived-credentials#browser-based-sign-in) allow you to sign in with a web browser to an external identity provider account via the +gcloud CLI and create a configuration for the auth library to use. + +To generate an external account authorized user workforce identity configuration, run the following command: + +```bash +gcloud auth application-default login --login-config=$LOGIN_CONFIG +``` + +Where the following variable needs to be substituted: +- `$LOGIN_CONFIG`: The login config file generated with the cloud console or + [gcloud iam workforce-pools create-login-config](https://cloud.google.com/sdk/gcloud/reference/iam/workforce-pools/create-login-config) + +This will open a browser flow for you to sign in via the configured third party identity provider +and then will store the external account authorized user configuration at the well known ADC location. +The auth library will then use the provided refresh token from the configuration to generate and refresh +an access token to call Google Cloud services. + +Note that the default lifetime of the refresh token is one hour, after which a new configuration will need to be generated from the gcloud CLI. +The lifetime can be modified by changing the [session duration of the workforce pool](https://cloud.google.com/iam/docs/reference/rest/v1/locations.workforcePools), and can be set as high as 12 hours. + +#### Using Executable-sourced credentials with OIDC and SAML + +**Executable-sourced credentials** +For executable-sourced credentials, a local executable is used to retrieve the 3rd party token. +The executable must handle providing a valid, unexpired OIDC ID token or SAML assertion in JSON format +to stdout. + +To use executable-sourced credentials, the `GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES` +environment variable must be set to `1`. + +To generate an executable-sourced workload identity configuration, run the following command: + +```bash +# Generate a configuration file for executable-sourced credentials. +gcloud iam workload-identity-pools create-cred-config \ + projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$PROVIDER_ID \ + --service-account=$SERVICE_ACCOUNT_EMAIL \ + --subject-token-type=$SUBJECT_TOKEN_TYPE \ + # The absolute path for the program, including arguments. + # e.g. --executable-command="/path/to/command --foo=bar" + --executable-command=$EXECUTABLE_COMMAND \ + # Optional argument for the executable timeout. Defaults to 30s. + # --executable-timeout-millis=$EXECUTABLE_TIMEOUT \ + # Optional argument for the absolute path to the executable output file. + # See below on how this argument impacts the library behaviour. + # --executable-output-file=$EXECUTABLE_OUTPUT_FILE \ + --output-file /path/to/generated/config.json +``` +Where the following variables need to be substituted: +- `$PROJECT_NUMBER`: The Google Cloud project number. +- `$POOL_ID`: The workload identity pool ID. +- `$PROVIDER_ID`: The OIDC or SAML provider ID. +- `$SERVICE_ACCOUNT_EMAIL`: The email of the service account to impersonate. +- `$SUBJECT_TOKEN_TYPE`: The subject token type. +- `$EXECUTABLE_COMMAND`: The full command to run, including arguments. Must be an absolute path to the program. + +The `--executable-timeout-millis` flag is optional. This is the duration for which +the auth library will wait for the executable to finish, in milliseconds. +Defaults to 30 seconds when not provided. The maximum allowed value is 2 minutes. +The minimum is 5 seconds. + +The `--executable-output-file` flag is optional. If provided, the file path must +point to the 3PI credential response generated by the executable. This is useful +for caching the credentials. By specifying this path, the Auth libraries will first +check for its existence before running the executable. By caching the executable JSON +response to this file, it improves performance as it avoids the need to run the executable +until the cached credentials in the output file are expired. The executable must +handle writing to this file - the auth libraries will only attempt to read from +this location. The format of contents in the file should match the JSON format +expected by the executable shown below. + +To retrieve the 3rd party token, the library will call the executable +using the command specified. The executable's output must adhere to the response format +specified below. It must output the response to stdout. + +A sample successful executable OIDC response: +```json +{ + "version": 1, + "success": true, + "token_type": "urn:ietf:params:oauth:token-type:id_token", + "id_token": "HEADER.PAYLOAD.SIGNATURE", + "expiration_time": 1620499962 +} +``` + +A sample successful executable SAML response: +```json +{ + "version": 1, + "success": true, + "token_type": "urn:ietf:params:oauth:token-type:saml2", + "saml_response": "...", + "expiration_time": 1620499962 +} +``` +For successful responses, the `expiration_time` field is only required +when an output file is specified in the credential configuration. + +A sample executable error response: +```json +{ + "version": 1, + "success": false, + "code": "401", + "message": "Caller not authorized." +} +``` +These are all required fields for an error response. The code and message +fields will be used by the library as part of the thrown exception. + +Response format fields summary: +* `version`: The version of the JSON output. Currently, only version 1 is supported. +* `success`: The status of the response. When true, the response must contain the 3rd party token + and token type. The response must also contain the expiration time if an output file was specified in the credential configuration. + The executable must also exit with exit code 0. + When false, the response must contain the error code and message fields and exit with a non-zero value. +* `token_type`: The 3rd party subject token type. Must be *urn:ietf:params:oauth:token-type:jwt*, +*urn:ietf:params:oauth:token-type:id_token*, or *urn:ietf:params:oauth:token-type:saml2*. +* `id_token`: The 3rd party OIDC token. +* `saml_response`: The 3rd party SAML response. +* `expiration_time`: The 3rd party subject token expiration time in seconds (unix epoch time). +* `code`: The error code string. +* `message`: The error message. + +All response types must include both the `version` and `success` fields. +* Successful responses must include the `token_type` and one of +`id_token` or `saml_response`. The `expiration_time` field must also be present if an output file was specified in +the credential configuration. +* Error responses must include both the `code` and `message` fields. + +The library will populate the following environment variables when the executable is run: +* `GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE`: The audience field from the credential configuration. Always present. +* `GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL`: The service account email. Only present when service account impersonation is used. +* `GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE`: The output file location from the credential configuration. Only present when specified in the credential configuration. +* `GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE`: This expected subject token type. Always present. + +These environment variables can be used by the executable to avoid hard-coding these values. + +##### Security considerations +The following security practices are highly recommended: +* Access to the script should be restricted as it will be displaying credentials to stdout. This ensures that rogue processes do not gain access to the script. +* The configuration file should not be modifiable. Write access should be restricted to avoid processes modifying the executable command portion. + +Given the complexity of using executable-sourced credentials, it is recommended to use +the existing supported mechanisms (file-sourced/URL-sourced) for providing 3rd party +credentials unless they do not meet your specific requirements. + +You can now [use the Auth library](#using-external-identities) to call Google Cloud +resources from an OIDC or SAML provider. + +#### Configurable Token Lifetime +When creating a credential configuration with workload identity federation using service account impersonation, you can provide an optional argument to configure the service account access token lifetime. + +To generate the configuration with configurable token lifetime, run the following command (this example uses an AWS configuration, but the token lifetime can be configured for all workload identity federation providers): + +```bash +# Generate an AWS configuration file with configurable token lifetime. +gcloud iam workload-identity-pools create-cred-config \ + projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AWS_PROVIDER_ID \ + --service-account $SERVICE_ACCOUNT_EMAIL \ + --aws \ + --output-file /path/to/generated/config.json \ + --service-account-token-lifetime-seconds $TOKEN_LIFETIME +``` + + Where the following variables need to be substituted: +- `$PROJECT_NUMBER`: The Google Cloud project number. +- `$POOL_ID`: The workload identity pool ID. +- `$AWS_PROVIDER_ID`: The AWS provider ID. +- `$SERVICE_ACCOUNT_EMAIL`: The email of the service account to impersonate. +- `$TOKEN_LIFETIME`: The desired lifetime duration of the service account access token in seconds. + +The `service-account-token-lifetime-seconds` flag is optional. If not provided, this defaults to one hour. +The minimum allowed value is 600 (10 minutes) and the maximum allowed value is 43200 (12 hours). +If a lifetime greater than one hour is required, the service account must be added as an allowed value in an Organization Policy that enforces the `constraints/iam.allowServiceAccountCredentialLifetimeExtension` constraint. + +Note that configuring a short lifetime (e.g. 10 minutes) will result in the library initiating the entire token exchange flow every 10 minutes, which will call the 3rd party token provider even if the 3rd party token is not expired. + +## Workforce Identity Federation + +[Workforce identity federation](https://cloud.google.com/iam/docs/workforce-identity-federation) lets you use an +external identity provider (IdP) to authenticate and authorize a workforce—a group of users, such as employees, +partners, and contractors—using IAM, so that the users can access Google Cloud services. Workforce identity federation +extends Google Cloud's identity capabilities to support syncless, attribute-based single sign on. + +With workforce identity federation, your workforce can access Google Cloud resources using an external +identity provider (IdP) that supports OpenID Connect (OIDC) or SAML 2.0 such as Azure Active Directory (Azure AD), +Active Directory Federation Services (AD FS), Okta, and others. + +### Accessing resources using an OIDC or SAML 2.0 identity provider + +In order to access Google Cloud resources from an identity provider that supports [OpenID Connect (OIDC)](https://openid.net/connect/), +the following requirements are needed: +- A workforce identity pool needs to be created. +- An OIDC or SAML 2.0 identity provider needs to be added in the workforce pool. + +Follow the detailed [instructions](https://cloud.google.com/iam/docs/configuring-workforce-identity-federation) on how +to configure workforce identity federation. + +After configuring an OIDC or SAML 2.0 provider, a credential configuration +file needs to be generated. The generated credential configuration file contains non-sensitive metadata to instruct the +library on how to retrieve external subject tokens and exchange them for GCP access tokens. +The configuration file can be generated by using the [gcloud CLI](https://cloud.google.com/sdk/). + +The Auth library can retrieve external subject tokens from a local file location +(file-sourced credentials), from a local server (URL-sourced credentials) or by calling an executable +(executable-sourced credentials). + +**File-sourced credentials** +For file-sourced credentials, a background process needs to be continuously refreshing the file +location with a new subject token prior to expiration. For tokens with one hour lifetimes, the token +needs to be updated in the file every hour. The token can be stored directly as plain text or in +JSON format. + +To generate a file-sourced OIDC configuration, run the following command: + +```bash +# Generate an OIDC configuration file for file-sourced credentials. +gcloud iam workforce-pools create-cred-config \ + locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ + --subject-token-type=urn:ietf:params:oauth:token-type:id_token \ + --credential-source-file=$PATH_TO_OIDC_ID_TOKEN \ + --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ + # Optional arguments for file types. Default is "text": + # --credential-source-type "json" \ + # Optional argument for the field that contains the OIDC credential. + # This is required for json. + # --credential-source-field-name "id_token" \ + --output-file=/path/to/generated/config.json +``` +Where the following variables need to be substituted: +- `$WORKFORCE_POOL_ID`: The workforce pool ID. +- `$PROVIDER_ID`: The provider ID. +- `$PATH_TO_OIDC_ID_TOKEN`: The file path used to retrieve the OIDC token. +- `$WORKFORCE_POOL_USER_PROJECT`: The project number associated with the [workforce pools user project](https://cloud.google.com/iam/docs/workforce-identity-federation#workforce-pools-user-project). + +To generate a file-sourced SAML configuration, run the following command: + +```bash +# Generate a SAML configuration file for file-sourced credentials. +gcloud iam workforce-pools create-cred-config \ + locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ + --credential-source-file=$PATH_TO_SAML_ASSERTION \ + --subject-token-type=urn:ietf:params:oauth:token-type:saml2 \ + --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ + --output-file=/path/to/generated/config.json +``` + +Where the following variables need to be substituted: +- `$WORKFORCE_POOL_ID`: The workforce pool ID. +- `$PROVIDER_ID`: The provider ID. +- `$PATH_TO_SAML_ASSERTION`: The file path used to retrieve the base64-encoded SAML assertion. +- `$WORKFORCE_POOL_USER_PROJECT`: The project number associated with the [workforce pools user project](https://cloud.google.com/iam/docs/workforce-identity-federation#workforce-pools-user-project). + +These commands generate the configuration file in the specified output file. + +**URL-sourced credentials** +For URL-sourced credentials, a local server needs to host a GET endpoint to return the OIDC token. +The response can be in plain text or JSON. Additional required request headers can also be +specified. + +To generate a URL-sourced OIDC workforce identity configuration, run the following command: + +```bash +# Generate an OIDC configuration file for URL-sourced credentials. +gcloud iam workforce-pools create-cred-config \ + locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ + --subject-token-type=urn:ietf:params:oauth:token-type:id_token \ + --credential-source-url=$URL_TO_RETURN_OIDC_ID_TOKEN \ + --credential-source-headers $HEADER_KEY=$HEADER_VALUE \ + --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ + --output-file=/path/to/generated/config.json +``` + +Where the following variables need to be substituted: +- `$WORKFORCE_POOL_ID`: The workforce pool ID. +- `$PROVIDER_ID`: The provider ID. +- `$URL_TO_RETURN_OIDC_ID_TOKEN`: The URL of the local server endpoint. +- `$HEADER_KEY` and `$HEADER_VALUE`: The additional header key/value pairs to pass along the GET request to + `$URL_TO_GET_OIDC_TOKEN`, e.g. `Metadata-Flavor=Google`. +- `$WORKFORCE_POOL_USER_PROJECT`: The project number associated with the [workforce pools user project](https://cloud.google.com/iam/docs/workforce-identity-federation#workforce-pools-user-project). + +To generate a URL-sourced SAML configuration, run the following command: + +```bash +# Generate a SAML configuration file for file-sourced credentials. +gcloud iam workforce-pools create-cred-config \ + locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ + --subject-token-type=urn:ietf:params:oauth:token-type:saml2 \ + --credential-source-url=$URL_TO_GET_SAML_ASSERTION \ + --credential-source-headers $HEADER_KEY=$HEADER_VALUE \ + --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ + --output-file=/path/to/generated/config.json +``` + +These commands generate the configuration file in the specified output file. + +Where the following variables need to be substituted: +- `$WORKFORCE_POOL_ID`: The workforce pool ID. +- `$PROVIDER_ID`: The provider ID. +- `$URL_TO_GET_SAML_ASSERTION`: The URL of the local server endpoint. +- `$HEADER_KEY` and `$HEADER_VALUE`: The additional header key/value pairs to pass along the GET request to + `$URL_TO_GET_SAML_ASSERTION`, e.g. `Metadata-Flavor=Google`. +- `$WORKFORCE_POOL_USER_PROJECT`: The project number associated with the [workforce pools user project](https://cloud.google.com/iam/docs/workforce-identity-federation#workforce-pools-user-project). + +### Using Executable-sourced workforce credentials with OIDC and SAML + +**Executable-sourced credentials** +For executable-sourced credentials, a local executable is used to retrieve the 3rd party token. +The executable must handle providing a valid, unexpired OIDC ID token or SAML assertion in JSON format +to stdout. + +To use executable-sourced credentials, the `GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES` +environment variable must be set to `1`. + +To generate an executable-sourced workforce identity configuration, run the following command: + +```bash +# Generate a configuration file for executable-sourced credentials. +gcloud iam workforce-pools create-cred-config \ + locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ + --subject-token-type=$SUBJECT_TOKEN_TYPE \ + # The absolute path for the program, including arguments. + # e.g. --executable-command="/path/to/command --foo=bar" + --executable-command=$EXECUTABLE_COMMAND \ + # Optional argument for the executable timeout. Defaults to 30s. + # --executable-timeout-millis=$EXECUTABLE_TIMEOUT \ + # Optional argument for the absolute path to the executable output file. + # See below on how this argument impacts the library behaviour. + # --executable-output-file=$EXECUTABLE_OUTPUT_FILE \ + --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ + --output-file /path/to/generated/config.json +``` +Where the following variables need to be substituted: +- `$WORKFORCE_POOL_ID`: The workforce pool ID. +- `$PROVIDER_ID`: The provider ID. +- `$SUBJECT_TOKEN_TYPE`: The subject token type. +- `$EXECUTABLE_COMMAND`: The full command to run, including arguments. Must be an absolute path to the program. +- `$WORKFORCE_POOL_USER_PROJECT`: The project number associated with the [workforce pools user project](https://cloud.google.com/iam/docs/workforce-identity-federation#workforce-pools-user-project). + +The `--executable-timeout-millis` flag is optional. This is the duration for which +the auth library will wait for the executable to finish, in milliseconds. +Defaults to 30 seconds when not provided. The maximum allowed value is 2 minutes. +The minimum is 5 seconds. + +The `--executable-output-file` flag is optional. If provided, the file path must +point to the 3rd party credential response generated by the executable. This is useful +for caching the credentials. By specifying this path, the Auth libraries will first +check for its existence before running the executable. By caching the executable JSON +response to this file, it improves performance as it avoids the need to run the executable +until the cached credentials in the output file are expired. The executable must +handle writing to this file - the auth libraries will only attempt to read from +this location. The format of contents in the file should match the JSON format +expected by the executable shown below. + +To retrieve the 3rd party token, the library will call the executable +using the command specified. The executable's output must adhere to the response format +specified below. It must output the response to stdout. + +Refer to the [using executable-sourced credentials with Workload Identity Federation](#using-executable-sourced-credentials-with-oidc-and-saml) +above for the executable response specification. + +##### Security considerations +The following security practices are highly recommended: +* Access to the script should be restricted as it will be displaying credentials to stdout. This ensures that rogue processes do not gain access to the script. +* The configuration file should not be modifiable. Write access should be restricted to avoid processes modifying the executable command portion. + +Given the complexity of using executable-sourced credentials, it is recommended to use +the existing supported mechanisms (file-sourced/URL-sourced) for providing 3rd party +credentials unless they do not meet your specific requirements. + +You can now [use the Auth library](#using-external-identities) to call Google Cloud +resources from an OIDC or SAML provider. + +### Accessing resources from an OIDC or SAML2.0 identity provider using a custom supplier + +If you want to use OIDC or SAML2.0 that cannot be retrieved using methods supported natively by this library, +a custom SubjectTokenSupplier implementation may be specified when creating an identity pool client. The supplier must +return a valid, unexpired subject token when called by the GCP credential. + +Note that the client does not cache the returned subject token, so caching logic should be implemented in the supplier to prevent multiple requests for the same resources. + +```ts +class CustomSupplier implements SubjectTokenSupplier { + async getSubjectToken( + context: ExternalAccountSupplierContext + ): Promise { + const audience = context.audience; + const subjectTokenType = context.subjectTokenType; + // Return a valid subject token for the requested audience and subject token type. + } +} + +const clientOptions = { + audience: '//iam.googleapis.com/locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID', // Set the GCP audience. + subject_token_type: 'urn:ietf:params:oauth:token-type:id_token', // Set the subject token type. + subject_token_supplier: new CustomSupplier() // Set the custom supplier. +} + +const client = new CustomSupplier(clientOptions); +``` + +Where the audience is: `//iam.googleapis.com/locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID` + +Where the following variables need to be substituted: + +* `$WORKFORCE_POOL_ID`: The worforce pool ID. +* `$PROVIDER_ID`: The provider ID. + +and the workforce pool user project is the project number associated with the [workforce pools user project](https://cloud.google.com/iam/docs/workforce-identity-federation#workforce-pools-user-project). + +The values for audience, service account impersonation URL, and any other builder field can also be found by generating a [credential configuration file with the gcloud CLI](https://cloud.google.com/iam/docs/workforce-obtaining-short-lived-credentials#use_configuration_files_for_sign-in). + +### Using External Identities + +External identities (AWS, Azure and OIDC-based providers) can be used with `Application Default Credentials`. +In order to use external identities with Application Default Credentials, you need to generate the JSON credentials configuration file for your external identity as described above. +Once generated, store the path to this file in the `GOOGLE_APPLICATION_CREDENTIALS` environment variable. + +```bash +export GOOGLE_APPLICATION_CREDENTIALS=/path/to/config.json +``` + +The library can now automatically choose the right type of client and initialize credentials from the context provided in the configuration file. + +```js +async function main() { + const auth = new GoogleAuth({ + scopes: 'https://www.googleapis.com/auth/cloud-platform' + }); + const client = await auth.getClient(); + const projectId = await auth.getProjectId(); + // List all buckets in a project. + const url = `https://storage.googleapis.com/storage/v1/b?project=${projectId}`; + const res = await client.request({ url }); + console.log(res.data); +} +``` + +When using external identities with Application Default Credentials in Node.js, the `roles/browser` role needs to be granted to the service account. +The `Cloud Resource Manager API` should also be enabled on the project. +This is needed since the library will try to auto-discover the project ID from the current environment using the impersonated credential. +To avoid this requirement, the project ID can be explicitly specified on initialization. + +```js +const auth = new GoogleAuth({ + scopes: 'https://www.googleapis.com/auth/cloud-platform', + // Pass the project ID explicitly to avoid the need to grant `roles/browser` to the service account + // or enable Cloud Resource Manager API on the project. + projectId: 'CLOUD_RESOURCE_PROJECT_ID', +}); +``` + +You can also explicitly initialize external account clients using the generated configuration file. + +```js +const {ExternalAccountClient} = require('google-auth-library'); +const jsonConfig = require('/path/to/config.json'); + +async function main() { + const client = ExternalAccountClient.fromJSON(jsonConfig); + client.scopes = ['https://www.googleapis.com/auth/cloud-platform']; + // List all buckets in a project. + const url = `https://storage.googleapis.com/storage/v1/b?project=${projectId}`; + const res = await client.request({url}); + console.log(res.data); +} +``` + +#### Security Considerations +Note that this library does not perform any validation on the token_url, token_info_url, or service_account_impersonation_url fields of the credential configuration. It is not recommended to use a credential configuration that you did not generate with the gcloud CLI unless you verify that the URL fields point to a googleapis.com domain. + +## Working with ID Tokens +### Fetching ID Tokens +If your application is running on Cloud Run or Cloud Functions, or using Cloud Identity-Aware +Proxy (IAP), you will need to fetch an ID token to access your application. For +this, use the method `getIdTokenClient` on the `GoogleAuth` client. + +For invoking Cloud Run services, your service account will need the +[`Cloud Run Invoker`](https://cloud.google.com/run/docs/authenticating/service-to-service) +IAM permission. + +For invoking Cloud Functions, your service account will need the +[`Function Invoker`](https://cloud.google.com/functions/docs/securing/authenticating#function-to-function) +IAM permission. + +``` js +// Make a request to a protected Cloud Run service. +const {GoogleAuth} = require('google-auth-library'); + +async function main() { + const url = 'https://cloud-run-1234-uc.a.run.app'; + const auth = new GoogleAuth(); + const client = await auth.getIdTokenClient(url); + const res = await client.request({url}); + console.log(res.data); +} + +main().catch(console.error); +``` + +A complete example can be found in [`samples/idtokens-serverless.js`](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idtokens-serverless.js). + +For invoking Cloud Identity-Aware Proxy, you will need to pass the Client ID +used when you set up your protected resource as the target audience. + +``` js +// Make a request to a protected Cloud Identity-Aware Proxy (IAP) resource +const {GoogleAuth} = require('google-auth-library'); + +async function main() + const targetAudience = 'iap-client-id'; + const url = 'https://iap-url.com'; + const auth = new GoogleAuth(); + const client = await auth.getIdTokenClient(targetAudience); + const res = await client.request({url}); + console.log(res.data); +} + +main().catch(console.error); +``` + +A complete example can be found in [`samples/idtokens-iap.js`](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idtokens-iap.js). + +### Verifying ID Tokens + +If you've [secured your IAP app with signed headers](https://cloud.google.com/iap/docs/signed-headers-howto), +you can use this library to verify the IAP header: + +```js +const {OAuth2Client} = require('google-auth-library'); +// Expected audience for App Engine. +const expectedAudience = `/projects/your-project-number/apps/your-project-id`; +// IAP issuer +const issuers = ['https://cloud.google.com/iap']; +// Verify the token. OAuth2Client throws an Error if verification fails +const oAuth2Client = new OAuth2Client(); +const response = await oAuth2Client.getIapCerts(); +const ticket = await oAuth2Client.verifySignedJwtWithCertsAsync( + idToken, + response.pubkeys, + expectedAudience, + issuers +); + +// Print out the info contained in the IAP ID token +console.log(ticket) +``` + +A complete example can be found in [`samples/verifyIdToken-iap.js`](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/verifyIdToken-iap.js). + +## Impersonated Credentials Client + +Google Cloud Impersonated credentials used for [Creating short-lived service account credentials](https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials). + +Provides authentication for applications where local credentials impersonates a remote service account using [IAM Credentials API](https://cloud.google.com/iam/docs/reference/credentials/rest). + +An Impersonated Credentials Client is instantiated with a `sourceClient`. This +client should use credentials that have the "Service Account Token Creator" role (`roles/iam.serviceAccountTokenCreator`), +and should authenticate with the `https://www.googleapis.com/auth/cloud-platform`, or `https://www.googleapis.com/auth/iam` scopes. + +`sourceClient` is used by the Impersonated +Credentials Client to impersonate a target service account with a specified +set of scopes. + +### Sample Usage + +```javascript +const { GoogleAuth, Impersonated } = require('google-auth-library'); +const { SecretManagerServiceClient } = require('@google-cloud/secret-manager'); + +async function main() { + + // Acquire source credentials: + const auth = new GoogleAuth(); + const client = await auth.getClient(); + + // Impersonate new credentials: + let targetClient = new Impersonated({ + sourceClient: client, + targetPrincipal: 'impersonated-account@projectID.iam.gserviceaccount.com', + lifetime: 30, + delegates: [], + targetScopes: ['https://www.googleapis.com/auth/cloud-platform'] + }); + + // Get impersonated credentials: + const authHeaders = await targetClient.getRequestHeaders(); + // Do something with `authHeaders.Authorization`. + + // Use impersonated credentials: + const url = 'https://www.googleapis.com/storage/v1/b?project=anotherProjectID' + const resp = await targetClient.request({ url }); + for (const bucket of resp.data.items) { + console.log(bucket.name); + } + + // Use impersonated credentials with google-cloud client library + // Note: this works only with certain cloud client libraries utilizing gRPC + // e.g., SecretManager, KMS, AIPlatform + // will not currently work with libraries using REST, e.g., Storage, Compute + const smClient = new SecretManagerServiceClient({ + projectId: anotherProjectID, + auth: { + getClient: () => targetClient, + }, + }); + const secretName = 'projects/anotherProjectNumber/secrets/someProjectName/versions/1'; + const [accessResponse] = await smClient.accessSecretVersion({ + name: secretName, + }); + + const responsePayload = accessResponse.payload.data.toString('utf8'); + // Do something with the secret contained in `responsePayload`. +}; + +main(); +``` + +## Downscoped Client + +[Downscoping with Credential Access Boundaries](https://cloud.google.com/iam/docs/downscoping-short-lived-credentials) is used to restrict the Identity and Access Management (IAM) permissions that a short-lived credential can use. + +The `DownscopedClient` class can be used to produce a downscoped access token from a +`CredentialAccessBoundary` and a source credential. The Credential Access Boundary specifies which resources the newly created credential can access, as well as an upper bound on the permissions that are available on each resource. Using downscoped credentials ensures tokens in flight always have the least privileges, e.g. Principle of Least Privilege. + +> Notice: Only Cloud Storage supports Credential Access Boundaries for now. + +### Sample Usage +There are two entities needed to generate and use credentials generated from +Downscoped Client with Credential Access Boundaries. + +- Token broker: This is the entity with elevated permissions. This entity has the permissions needed to generate downscoped tokens. The common pattern of usage is to have a token broker with elevated access generate these downscoped credentials from higher access source credentials and pass the downscoped short-lived access tokens to a token consumer via some secure authenticated channel for limited access to Google Cloud Storage resources. + +``` js +const {GoogleAuth, DownscopedClient} = require('google-auth-library'); +// Define CAB rules which will restrict the downscoped token to have readonly +// access to objects starting with "customer-a" in bucket "bucket_name". +const cabRules = { + accessBoundary: { + accessBoundaryRules: [ + { + availableResource: `//storage.googleapis.com/projects/_/buckets/bucket_name`, + availablePermissions: ['inRole:roles/storage.objectViewer'], + availabilityCondition: { + expression: + `resource.name.startsWith('projects/_/buckets/` + + `bucket_name/objects/customer-a)` + } + }, + ], + }, +}; + +// This will use ADC to get the credentials used for the downscoped client. +const googleAuth = new GoogleAuth({ + scopes: ['https://www.googleapis.com/auth/cloud-platform'] +}); + +// Obtain an authenticated client via ADC. +const client = await googleAuth.getClient(); + +// Use the client to create a DownscopedClient. +const cabClient = new DownscopedClient(client, cab); + +// Refresh the tokens. +const refreshedAccessToken = await cabClient.getAccessToken(); + +// This will need to be passed to the token consumer. +access_token = refreshedAccessToken.token; +expiry_date = refreshedAccessToken.expirationTime; +``` + +A token broker can be set up on a server in a private network. Various workloads +(token consumers) in the same network will send authenticated requests to that broker for downscoped tokens to access or modify specific google cloud storage buckets. + +The broker will instantiate downscoped credentials instances that can be used to generate short lived downscoped access tokens which will be passed to the token consumer. + +- Token consumer: This is the consumer of the downscoped tokens. This entity does not have the direct ability to generate access tokens and instead relies on the token broker to provide it with downscoped tokens to run operations on GCS buckets. It is assumed that the downscoped token consumer may have its own mechanism to authenticate itself with the token broker. + +``` js +const {OAuth2Client} = require('google-auth-library'); +const {Storage} = require('@google-cloud/storage'); + +// Create the OAuth credentials (the consumer). +const oauth2Client = new OAuth2Client(); +// We are defining a refresh handler instead of a one-time access +// token/expiry pair. +// This will allow the consumer to obtain new downscoped tokens on +// demand every time a token is expired, without any additional code +// changes. +oauth2Client.refreshHandler = async () => { + // The common pattern of usage is to have a token broker pass the + // downscoped short-lived access tokens to a token consumer via some + // secure authenticated channel. + const refreshedAccessToken = await cabClient.getAccessToken(); + return { + access_token: refreshedAccessToken.token, + expiry_date: refreshedAccessToken.expirationTime, + } +}; + +// Use the consumer client to define storageOptions and create a GCS object. +const storageOptions = { + projectId: 'my_project_id', + authClient: oauth2Client, +}; + +const storage = new Storage(storageOptions); + +const downloadFile = await storage + .bucket('bucket_name') + .file('customer-a-data.txt') + .download(); +console.log(downloadFile.toString('utf8')); + +main().catch(console.error); +``` + + +## Samples + +Samples are in the [`samples/`](https://github.com/googleapis/google-auth-library-nodejs/tree/main/samples) directory. Each sample's `README.md` has instructions for running its sample. + +| Sample | Source Code | Try it | +| --------------------------- | --------------------------------- | ------ | +| Adc | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/adc.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/adc.js,samples/README.md) | +| Authenticate API Key | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/authenticateAPIKey.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/authenticateAPIKey.js,samples/README.md) | +| Authenticate Explicit | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/authenticateExplicit.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/authenticateExplicit.js,samples/README.md) | +| Authenticate Implicit With Adc | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/authenticateImplicitWithAdc.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/authenticateImplicitWithAdc.js,samples/README.md) | +| Compute | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/compute.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/compute.js,samples/README.md) | +| Credentials | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/credentials.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/credentials.js,samples/README.md) | +| Downscopedclient | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/downscopedclient.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/downscopedclient.js,samples/README.md) | +| Headers | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/headers.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/headers.js,samples/README.md) | +| Id Token From Impersonated Credentials | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idTokenFromImpersonatedCredentials.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/idTokenFromImpersonatedCredentials.js,samples/README.md) | +| Id Token From Metadata Server | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idTokenFromMetadataServer.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/idTokenFromMetadataServer.js,samples/README.md) | +| Id Token From Service Account | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idTokenFromServiceAccount.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/idTokenFromServiceAccount.js,samples/README.md) | +| ID Tokens for Identity-Aware Proxy (IAP) | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idtokens-iap.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/idtokens-iap.js,samples/README.md) | +| ID Tokens for Serverless | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/idtokens-serverless.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/idtokens-serverless.js,samples/README.md) | +| Jwt | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/jwt.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/jwt.js,samples/README.md) | +| Keepalive | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/keepalive.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/keepalive.js,samples/README.md) | +| Keyfile | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/keyfile.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/keyfile.js,samples/README.md) | +| Oauth2-code Verifier | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/oauth2-codeVerifier.js,samples/README.md) | +| Oauth2 | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/oauth2.js,samples/README.md) | +| Sign Blob | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/signBlob.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/signBlob.js,samples/README.md) | +| Sign Blob Impersonated | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/signBlobImpersonated.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/signBlobImpersonated.js,samples/README.md) | +| Verify Google Id Token | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/verifyGoogleIdToken.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/verifyGoogleIdToken.js,samples/README.md) | +| Verifying ID Tokens from Identity-Aware Proxy (IAP) | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/verifyIdToken-iap.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/verifyIdToken-iap.js,samples/README.md) | +| Verify Id Token | [source code](https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/verifyIdToken.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-auth-library-nodejs&page=editor&open_in_editor=samples/verifyIdToken.js,samples/README.md) | + + + +The [Google Auth Library Node.js Client API Reference][client-docs] documentation +also contains samples. + +## Supported Node.js Versions + +Our client libraries follow the [Node.js release schedule](https://github.com/nodejs/release#release-schedule). +Libraries are compatible with all current _active_ and _maintenance_ versions of +Node.js. +If you are using an end-of-life version of Node.js, we recommend that you update +as soon as possible to an actively supported LTS version. + +Google's client libraries support legacy versions of Node.js runtimes on a +best-efforts basis with the following warnings: + +* Legacy versions are not tested in continuous integration. +* Some security patches and features cannot be backported. +* Dependencies cannot be kept up-to-date. + +Client libraries targeting some end-of-life versions of Node.js are available, and +can be installed through npm [dist-tags](https://docs.npmjs.com/cli/dist-tag). +The dist-tags follow the naming convention `legacy-(version)`. +For example, `npm install google-auth-library@legacy-8` installs client libraries +for versions compatible with Node.js 8. + +## Versioning + +This library follows [Semantic Versioning](http://semver.org/). + + + +This library is considered to be **stable**. The code surface will not change in backwards-incompatible ways +unless absolutely necessary (e.g. because of critical security issues) or with +an extensive deprecation period. Issues and requests against **stable** libraries +are addressed with the highest priority. + + + + + + +More Information: [Google Cloud Platform Launch Stages][launch_stages] + +[launch_stages]: https://cloud.google.com/terms/launch-stages + +## Contributing + +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-auth-library-nodejs/blob/main/CONTRIBUTING.md). + +Please note that this `README.md`, the `samples/README.md`, +and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`) +are generated from a central template. To edit one of these files, make an edit +to its templates in +[directory](https://github.com/googleapis/synthtool). + +## License + +Apache Version 2.0 + +See [LICENSE](https://github.com/googleapis/google-auth-library-nodejs/blob/main/LICENSE) + +[client-docs]: https://cloud.google.com/nodejs/docs/reference/google-auth-library/latest +[product-docs]: https://cloud.google.com/docs/authentication/ +[shell_img]: https://gstatic.com/cloudssh/images/open-btn.png +[projects]: https://console.cloud.google.com/project +[billing]: https://support.google.com/cloud/answer/6293499#enable-billing + +[auth]: https://cloud.google.com/docs/authentication/external/set-up-adc-local diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/authclient.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/authclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..22b020cd5e8d20251ce80f14b097518e767ef73d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/authclient.d.ts @@ -0,0 +1,202 @@ +import { EventEmitter } from 'events'; +import { Gaxios, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +import { Transporter } from '../transporters'; +import { Credentials } from './credentials'; +import { GetAccessTokenResponse, Headers } from './oauth2client'; +import { OriginalAndCamel } from '../util'; +/** + * Base auth configurations (e.g. from JWT or `.json` files) with conventional + * camelCased options. + * + * @privateRemarks + * + * This interface is purposely not exported so that it can be removed once + * {@link https://github.com/microsoft/TypeScript/issues/50715} has been + * resolved. Then, we can use {@link OriginalAndCamel} to shrink this interface. + * + * Tracking: {@link https://github.com/googleapis/google-auth-library-nodejs/issues/1686} + */ +interface AuthJSONOptions { + /** + * The project ID corresponding to the current credentials if available. + */ + project_id: string | null; + /** + * An alias for {@link AuthJSONOptions.project_id `project_id`}. + */ + projectId: AuthJSONOptions['project_id']; + /** + * The quota project ID. The quota project can be used by client libraries for the billing purpose. + * See {@link https://cloud.google.com/docs/quota Working with quotas} + */ + quota_project_id: string; + /** + * An alias for {@link AuthJSONOptions.quota_project_id `quota_project_id`}. + */ + quotaProjectId: AuthJSONOptions['quota_project_id']; + /** + * The default service domain for a given Cloud universe. + * + * @example + * 'googleapis.com' + */ + universe_domain: string; + /** + * An alias for {@link AuthJSONOptions.universe_domain `universe_domain`}. + */ + universeDomain: AuthJSONOptions['universe_domain']; +} +/** + * Base `AuthClient` configuration. + * + * The camelCased options are aliases of the snake_cased options, supporting both + * JSON API and JS conventions. + */ +export interface AuthClientOptions extends Partial> { + /** + * An API key to use, optional. + */ + apiKey?: string; + credentials?: Credentials; + /** + * A `Gaxios` or `Transporter` instance to use for `AuthClient` requests. + */ + transporter?: Gaxios | Transporter; + /** + * Provides default options to the transporter, such as {@link GaxiosOptions.agent `agent`} or + * {@link GaxiosOptions.retryConfig `retryConfig`}. + */ + transporterOptions?: GaxiosOptions; + /** + * The expiration threshold in milliseconds before forcing token refresh of + * unexpired tokens. + */ + eagerRefreshThresholdMillis?: number; + /** + * Whether to attempt to refresh tokens on status 401/403 responses + * even if an attempt is made to refresh the token preemptively based + * on the expiry_date. + */ + forceRefreshOnFailure?: boolean; +} +/** + * The default cloud universe + * + * @see {@link AuthJSONOptions.universe_domain} + */ +export declare const DEFAULT_UNIVERSE = "googleapis.com"; +/** + * The default {@link AuthClientOptions.eagerRefreshThresholdMillis} + */ +export declare const DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS: number; +/** + * Defines the root interface for all clients that generate credentials + * for calling Google APIs. All clients should implement this interface. + */ +export interface CredentialsClient { + projectId?: AuthClientOptions['projectId']; + eagerRefreshThresholdMillis: NonNullable; + forceRefreshOnFailure: NonNullable; + /** + * @return A promise that resolves with the current GCP access token + * response. If the current credential is expired, a new one is retrieved. + */ + getAccessToken(): Promise; + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * The result has the form: + * { Authorization: 'Bearer ' } + * @param url The URI being authorized. + */ + getRequestHeaders(url?: string): Promise; + /** + * Provides an alternative Gaxios request implementation with auth credentials + */ + request(opts: GaxiosOptions): GaxiosPromise; + /** + * Sets the auth credentials. + */ + setCredentials(credentials: Credentials): void; + /** + * Subscribes a listener to the tokens event triggered when a token is + * generated. + * + * @param event The tokens event to subscribe to. + * @param listener The listener that triggers on event trigger. + * @return The current client instance. + */ + on(event: 'tokens', listener: (tokens: Credentials) => void): this; +} +export declare interface AuthClient { + on(event: 'tokens', listener: (tokens: Credentials) => void): this; +} +export declare abstract class AuthClient extends EventEmitter implements CredentialsClient { + apiKey?: string; + projectId?: string | null; + /** + * The quota project ID. The quota project can be used by client libraries for the billing purpose. + * See {@link https://cloud.google.com/docs/quota Working with quotas} + */ + quotaProjectId?: string; + transporter: Transporter; + credentials: Credentials; + eagerRefreshThresholdMillis: number; + forceRefreshOnFailure: boolean; + universeDomain: string; + constructor(opts?: AuthClientOptions); + /** + * Return the {@link Gaxios `Gaxios`} instance from the {@link AuthClient.transporter}. + * + * @expiremental + */ + get gaxios(): Gaxios | null; + /** + * Provides an alternative Gaxios request implementation with auth credentials + */ + abstract request(opts: GaxiosOptions): GaxiosPromise; + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * The result has the form: + * { Authorization: 'Bearer ' } + * @param url The URI being authorized. + */ + abstract getRequestHeaders(url?: string): Promise; + /** + * @return A promise that resolves with the current GCP access token + * response. If the current credential is expired, a new one is retrieved. + */ + abstract getAccessToken(): Promise<{ + token?: string | null; + res?: GaxiosResponse | null; + }>; + /** + * Sets the auth credentials. + */ + setCredentials(credentials: Credentials): void; + /** + * Append additional headers, e.g., x-goog-user-project, shared across the + * classes inheriting AuthClient. This method should be used by any method + * that overrides getRequestMetadataAsync(), which is a shared helper for + * setting request information in both gRPC and HTTP API calls. + * + * @param headers object to append additional headers to. + */ + protected addSharedMetadataHeaders(headers: Headers): Headers; + /** + * Retry config for Auth-related requests. + * + * @remarks + * + * This is not a part of the default {@link AuthClient.transporter transporter/gaxios} + * config as some downstream APIs would prefer if customers explicitly enable retries, + * such as GCS. + */ + protected static get RETRY_CONFIG(): GaxiosOptions; +} +export {}; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/authclient.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/authclient.js new file mode 100644 index 0000000000000000000000000000000000000000..f80ca5878bb0e4b382ed06ddca353e6fc937da89 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/authclient.js @@ -0,0 +1,116 @@ +"use strict"; +// Copyright 2012 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AuthClient = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = exports.DEFAULT_UNIVERSE = void 0; +const events_1 = require("events"); +const gaxios_1 = require("gaxios"); +const transporters_1 = require("../transporters"); +const util_1 = require("../util"); +/** + * The default cloud universe + * + * @see {@link AuthJSONOptions.universe_domain} + */ +exports.DEFAULT_UNIVERSE = 'googleapis.com'; +/** + * The default {@link AuthClientOptions.eagerRefreshThresholdMillis} + */ +exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = 5 * 60 * 1000; +class AuthClient extends events_1.EventEmitter { + constructor(opts = {}) { + var _a, _b, _c, _d, _e; + super(); + this.credentials = {}; + this.eagerRefreshThresholdMillis = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS; + this.forceRefreshOnFailure = false; + this.universeDomain = exports.DEFAULT_UNIVERSE; + const options = (0, util_1.originalOrCamelOptions)(opts); + // Shared auth options + this.apiKey = opts.apiKey; + this.projectId = (_a = options.get('project_id')) !== null && _a !== void 0 ? _a : null; + this.quotaProjectId = options.get('quota_project_id'); + this.credentials = (_b = options.get('credentials')) !== null && _b !== void 0 ? _b : {}; + this.universeDomain = (_c = options.get('universe_domain')) !== null && _c !== void 0 ? _c : exports.DEFAULT_UNIVERSE; + // Shared client options + this.transporter = (_d = opts.transporter) !== null && _d !== void 0 ? _d : new transporters_1.DefaultTransporter(); + if (opts.transporterOptions) { + this.transporter.defaults = opts.transporterOptions; + } + if (opts.eagerRefreshThresholdMillis) { + this.eagerRefreshThresholdMillis = opts.eagerRefreshThresholdMillis; + } + this.forceRefreshOnFailure = (_e = opts.forceRefreshOnFailure) !== null && _e !== void 0 ? _e : false; + } + /** + * Return the {@link Gaxios `Gaxios`} instance from the {@link AuthClient.transporter}. + * + * @expiremental + */ + get gaxios() { + if (this.transporter instanceof gaxios_1.Gaxios) { + return this.transporter; + } + else if (this.transporter instanceof transporters_1.DefaultTransporter) { + return this.transporter.instance; + } + else if ('instance' in this.transporter && + this.transporter.instance instanceof gaxios_1.Gaxios) { + return this.transporter.instance; + } + return null; + } + /** + * Sets the auth credentials. + */ + setCredentials(credentials) { + this.credentials = credentials; + } + /** + * Append additional headers, e.g., x-goog-user-project, shared across the + * classes inheriting AuthClient. This method should be used by any method + * that overrides getRequestMetadataAsync(), which is a shared helper for + * setting request information in both gRPC and HTTP API calls. + * + * @param headers object to append additional headers to. + */ + addSharedMetadataHeaders(headers) { + // quota_project_id, stored in application_default_credentials.json, is set in + // the x-goog-user-project header, to indicate an alternate account for + // billing and quota: + if (!headers['x-goog-user-project'] && // don't override a value the user sets. + this.quotaProjectId) { + headers['x-goog-user-project'] = this.quotaProjectId; + } + return headers; + } + /** + * Retry config for Auth-related requests. + * + * @remarks + * + * This is not a part of the default {@link AuthClient.transporter transporter/gaxios} + * config as some downstream APIs would prefer if customers explicitly enable retries, + * such as GCS. + */ + static get RETRY_CONFIG() { + return { + retry: true, + retryConfig: { + httpMethodsToRetry: ['GET', 'PUT', 'POST', 'HEAD', 'OPTIONS', 'DELETE'], + }, + }; + } +} +exports.AuthClient = AuthClient; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/awsclient.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/awsclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a3bc138225f1dcaf1a86295b417c346eb84dfd52 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/awsclient.d.ts @@ -0,0 +1,120 @@ +import { AwsSecurityCredentials } from './awsrequestsigner'; +import { BaseExternalAccountClient, BaseExternalAccountClientOptions, ExternalAccountSupplierContext } from './baseexternalclient'; +import { AuthClientOptions } from './authclient'; +import { SnakeToCamelObject } from '../util'; +/** + * AWS credentials JSON interface. This is used for AWS workloads. + */ +export interface AwsClientOptions extends BaseExternalAccountClientOptions { + /** + * Object containing options to retrieve AWS security credentials. A valid credential + * source or a aws security credentials supplier should be specified. + */ + credential_source?: { + /** + * AWS environment ID. Currently only 'AWS1' is supported. + */ + environment_id: string; + /** + * The EC2 metadata URL to retrieve the current AWS region from. If this is + * not provided, the region should be present in the AWS_REGION or AWS_DEFAULT_REGION + * environment variables. + */ + region_url?: string; + /** + * The EC2 metadata URL to retrieve AWS security credentials. If this is not provided, + * the credentials should be present in the AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, + * and AWS_SESSION_TOKEN environment variables. + */ + url?: string; + /** + * The regional GetCallerIdentity action URL, used to determine the account + * ID and its roles. + */ + regional_cred_verification_url: string; + /** + * The imdsv2 session token url is used to fetch session token from AWS + * which is later sent through headers for metadata requests. If the + * field is missing, then session token won't be fetched and sent with + * the metadata requests. + * The session token is required for IMDSv2 but optional for IMDSv1 + */ + imdsv2_session_token_url?: string; + }; + /** + * The AWS security credentials supplier to call to retrieve the AWS region + * and AWS security credentials. Either this or a valid credential source + * must be specified. + */ + aws_security_credentials_supplier?: AwsSecurityCredentialsSupplier; +} +/** + * Supplier interface for AWS security credentials. This can be implemented to + * return an AWS region and AWS security credentials. These credentials can + * then be exchanged for a GCP token by an {@link AwsClient}. + */ +export interface AwsSecurityCredentialsSupplier { + /** + * Gets the active AWS region. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link AwsClient}, contains the requested audience and subject token type + * for the external account identity as well as the transport from the + * calling client to use for requests. + * @return A promise that resolves with the AWS region string. + */ + getAwsRegion: (context: ExternalAccountSupplierContext) => Promise; + /** + * Gets valid AWS security credentials for the requested external account + * identity. Note that these are not cached by the calling {@link AwsClient}, + * so caching should be including in the implementation. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link AwsClient}, contains the requested audience and subject token type + * for the external account identity as well as the transport from the + * calling client to use for requests. + * @return A promise that resolves with the requested {@link AwsSecurityCredentials}. + */ + getAwsSecurityCredentials: (context: ExternalAccountSupplierContext) => Promise; +} +/** + * AWS external account client. This is used for AWS workloads, where + * AWS STS GetCallerIdentity serialized signed requests are exchanged for + * GCP access token. + */ +export declare class AwsClient extends BaseExternalAccountClient { + #private; + private readonly environmentId?; + private readonly awsSecurityCredentialsSupplier; + private readonly regionalCredVerificationUrl; + private awsRequestSigner; + private region; + /** + * @deprecated AWS client no validates the EC2 metadata address. + **/ + static AWS_EC2_METADATA_IPV4_ADDRESS: string; + /** + * @deprecated AWS client no validates the EC2 metadata address. + **/ + static AWS_EC2_METADATA_IPV6_ADDRESS: string; + /** + * Instantiates an AwsClient instance using the provided JSON + * object loaded from an external account credentials file. + * An error is thrown if the credential is not a valid AWS credential. + * @param options The external account options object typically loaded + * from the external account JSON credential file. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options: AwsClientOptions | SnakeToCamelObject, additionalOptions?: AuthClientOptions); + private validateEnvironmentId; + /** + * Triggered when an external subject token is needed to be exchanged for a + * GCP access token via GCP STS endpoint. This will call the + * {@link AwsSecurityCredentialsSupplier} to retrieve an AWS region and AWS + * Security Credentials, then use them to create a signed AWS STS request that + * can be exchanged for a GCP access token. + * @return A promise that resolves with the external subject token. + */ + retrieveSubjectToken(): Promise; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/awsclient.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/awsclient.js new file mode 100644 index 0000000000000000000000000000000000000000..c2bebd4ed5a28fce5832ef187c148c71e4ee0c2f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/awsclient.js @@ -0,0 +1,164 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _a, _AwsClient_DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AwsClient = void 0; +const awsrequestsigner_1 = require("./awsrequestsigner"); +const baseexternalclient_1 = require("./baseexternalclient"); +const defaultawssecuritycredentialssupplier_1 = require("./defaultawssecuritycredentialssupplier"); +const util_1 = require("../util"); +/** + * AWS external account client. This is used for AWS workloads, where + * AWS STS GetCallerIdentity serialized signed requests are exchanged for + * GCP access token. + */ +class AwsClient extends baseexternalclient_1.BaseExternalAccountClient { + /** + * Instantiates an AwsClient instance using the provided JSON + * object loaded from an external account credentials file. + * An error is thrown if the credential is not a valid AWS credential. + * @param options The external account options object typically loaded + * from the external account JSON credential file. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options, additionalOptions) { + super(options, additionalOptions); + const opts = (0, util_1.originalOrCamelOptions)(options); + const credentialSource = opts.get('credential_source'); + const awsSecurityCredentialsSupplier = opts.get('aws_security_credentials_supplier'); + // Validate credential sourcing configuration. + if (!credentialSource && !awsSecurityCredentialsSupplier) { + throw new Error('A credential source or AWS security credentials supplier must be specified.'); + } + if (credentialSource && awsSecurityCredentialsSupplier) { + throw new Error('Only one of credential source or AWS security credentials supplier can be specified.'); + } + if (awsSecurityCredentialsSupplier) { + this.awsSecurityCredentialsSupplier = awsSecurityCredentialsSupplier; + this.regionalCredVerificationUrl = + __classPrivateFieldGet(_a, _a, "f", _AwsClient_DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL); + this.credentialSourceType = 'programmatic'; + } + else { + const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource); + this.environmentId = credentialSourceOpts.get('environment_id'); + // This is only required if the AWS region is not available in the + // AWS_REGION or AWS_DEFAULT_REGION environment variables. + const regionUrl = credentialSourceOpts.get('region_url'); + // This is only required if AWS security credentials are not available in + // environment variables. + const securityCredentialsUrl = credentialSourceOpts.get('url'); + const imdsV2SessionTokenUrl = credentialSourceOpts.get('imdsv2_session_token_url'); + this.awsSecurityCredentialsSupplier = + new defaultawssecuritycredentialssupplier_1.DefaultAwsSecurityCredentialsSupplier({ + regionUrl: regionUrl, + securityCredentialsUrl: securityCredentialsUrl, + imdsV2SessionTokenUrl: imdsV2SessionTokenUrl, + }); + this.regionalCredVerificationUrl = credentialSourceOpts.get('regional_cred_verification_url'); + this.credentialSourceType = 'aws'; + // Data validators. + this.validateEnvironmentId(); + } + this.awsRequestSigner = null; + this.region = ''; + } + validateEnvironmentId() { + var _b; + const match = (_b = this.environmentId) === null || _b === void 0 ? void 0 : _b.match(/^(aws)(\d+)$/); + if (!match || !this.regionalCredVerificationUrl) { + throw new Error('No valid AWS "credential_source" provided'); + } + else if (parseInt(match[2], 10) !== 1) { + throw new Error(`aws version "${match[2]}" is not supported in the current build.`); + } + } + /** + * Triggered when an external subject token is needed to be exchanged for a + * GCP access token via GCP STS endpoint. This will call the + * {@link AwsSecurityCredentialsSupplier} to retrieve an AWS region and AWS + * Security Credentials, then use them to create a signed AWS STS request that + * can be exchanged for a GCP access token. + * @return A promise that resolves with the external subject token. + */ + async retrieveSubjectToken() { + // Initialize AWS request signer if not already initialized. + if (!this.awsRequestSigner) { + this.region = await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext); + this.awsRequestSigner = new awsrequestsigner_1.AwsRequestSigner(async () => { + return this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext); + }, this.region); + } + // Generate signed request to AWS STS GetCallerIdentity API. + // Use the required regional endpoint. Otherwise, the request will fail. + const options = await this.awsRequestSigner.getRequestOptions({ + ..._a.RETRY_CONFIG, + url: this.regionalCredVerificationUrl.replace('{region}', this.region), + method: 'POST', + }); + // The GCP STS endpoint expects the headers to be formatted as: + // [ + // {key: 'x-amz-date', value: '...'}, + // {key: 'Authorization', value: '...'}, + // ... + // ] + // And then serialized as: + // encodeURIComponent(JSON.stringify({ + // url: '...', + // method: 'POST', + // headers: [{key: 'x-amz-date', value: '...'}, ...] + // })) + const reformattedHeader = []; + const extendedHeaders = Object.assign({ + // The full, canonical resource name of the workload identity pool + // provider, with or without the HTTPS prefix. + // Including this header as part of the signature is recommended to + // ensure data integrity. + 'x-goog-cloud-target-resource': this.audience, + }, options.headers); + // Reformat header to GCP STS expected format. + for (const key in extendedHeaders) { + reformattedHeader.push({ + key, + value: extendedHeaders[key], + }); + } + // Serialize the reformatted signed request. + return encodeURIComponent(JSON.stringify({ + url: options.url, + method: options.method, + headers: reformattedHeader, + })); + } +} +exports.AwsClient = AwsClient; +_a = AwsClient; +_AwsClient_DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL = { value: 'https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15' }; +/** + * @deprecated AWS client no validates the EC2 metadata address. + **/ +AwsClient.AWS_EC2_METADATA_IPV4_ADDRESS = '169.254.169.254'; +/** + * @deprecated AWS client no validates the EC2 metadata address. + **/ +AwsClient.AWS_EC2_METADATA_IPV6_ADDRESS = 'fd00:ec2::254'; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/awsrequestsigner.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/awsrequestsigner.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3467e973f6879bae31286a5c37aa9b511e93ee96 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/awsrequestsigner.d.ts @@ -0,0 +1,40 @@ +import { GaxiosOptions } from 'gaxios'; +/** + * Interface defining AWS security credentials. + * These are either determined from AWS security_credentials endpoint or + * AWS environment variables. + */ +export interface AwsSecurityCredentials { + accessKeyId: string; + secretAccessKey: string; + token?: string; +} +/** + * Implements an AWS API request signer based on the AWS Signature Version 4 + * signing process. + * https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html + */ +export declare class AwsRequestSigner { + private readonly getCredentials; + private readonly region; + private readonly crypto; + /** + * Instantiates an AWS API request signer used to send authenticated signed + * requests to AWS APIs based on the AWS Signature Version 4 signing process. + * This also provides a mechanism to generate the signed request without + * sending it. + * @param getCredentials A mechanism to retrieve AWS security credentials + * when needed. + * @param region The AWS region to use. + */ + constructor(getCredentials: () => Promise, region: string); + /** + * Generates the signed request for the provided HTTP request for calling + * an AWS API. This follows the steps described at: + * https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html + * @param amzOptions The AWS request options that need to be signed. + * @return A promise that resolves with the GaxiosOptions containing the + * signed HTTP request parameters. + */ + getRequestOptions(amzOptions: GaxiosOptions): Promise; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js new file mode 100644 index 0000000000000000000000000000000000000000..882a9a9188fab3ff33fcdb50b6c4f3c389e404c4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js @@ -0,0 +1,209 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AwsRequestSigner = void 0; +const crypto_1 = require("../crypto/crypto"); +/** AWS Signature Version 4 signing algorithm identifier. */ +const AWS_ALGORITHM = 'AWS4-HMAC-SHA256'; +/** + * The termination string for the AWS credential scope value as defined in + * https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html + */ +const AWS_REQUEST_TYPE = 'aws4_request'; +/** + * Implements an AWS API request signer based on the AWS Signature Version 4 + * signing process. + * https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html + */ +class AwsRequestSigner { + /** + * Instantiates an AWS API request signer used to send authenticated signed + * requests to AWS APIs based on the AWS Signature Version 4 signing process. + * This also provides a mechanism to generate the signed request without + * sending it. + * @param getCredentials A mechanism to retrieve AWS security credentials + * when needed. + * @param region The AWS region to use. + */ + constructor(getCredentials, region) { + this.getCredentials = getCredentials; + this.region = region; + this.crypto = (0, crypto_1.createCrypto)(); + } + /** + * Generates the signed request for the provided HTTP request for calling + * an AWS API. This follows the steps described at: + * https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html + * @param amzOptions The AWS request options that need to be signed. + * @return A promise that resolves with the GaxiosOptions containing the + * signed HTTP request parameters. + */ + async getRequestOptions(amzOptions) { + if (!amzOptions.url) { + throw new Error('"url" is required in "amzOptions"'); + } + // Stringify JSON requests. This will be set in the request body of the + // generated signed request. + const requestPayloadData = typeof amzOptions.data === 'object' + ? JSON.stringify(amzOptions.data) + : amzOptions.data; + const url = amzOptions.url; + const method = amzOptions.method || 'GET'; + const requestPayload = amzOptions.body || requestPayloadData; + const additionalAmzHeaders = amzOptions.headers; + const awsSecurityCredentials = await this.getCredentials(); + const uri = new URL(url); + const headerMap = await generateAuthenticationHeaderMap({ + crypto: this.crypto, + host: uri.host, + canonicalUri: uri.pathname, + canonicalQuerystring: uri.search.substr(1), + method, + region: this.region, + securityCredentials: awsSecurityCredentials, + requestPayload, + additionalAmzHeaders, + }); + // Append additional optional headers, eg. X-Amz-Target, Content-Type, etc. + const headers = Object.assign( + // Add x-amz-date if available. + headerMap.amzDate ? { 'x-amz-date': headerMap.amzDate } : {}, { + Authorization: headerMap.authorizationHeader, + host: uri.host, + }, additionalAmzHeaders || {}); + if (awsSecurityCredentials.token) { + Object.assign(headers, { + 'x-amz-security-token': awsSecurityCredentials.token, + }); + } + const awsSignedReq = { + url, + method: method, + headers, + }; + if (typeof requestPayload !== 'undefined') { + awsSignedReq.body = requestPayload; + } + return awsSignedReq; + } +} +exports.AwsRequestSigner = AwsRequestSigner; +/** + * Creates the HMAC-SHA256 hash of the provided message using the + * provided key. + * + * @param crypto The crypto instance used to facilitate cryptographic + * operations. + * @param key The HMAC-SHA256 key to use. + * @param msg The message to hash. + * @return The computed hash bytes. + */ +async function sign(crypto, key, msg) { + return await crypto.signWithHmacSha256(key, msg); +} +/** + * Calculates the signing key used to calculate the signature for + * AWS Signature Version 4 based on: + * https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html + * + * @param crypto The crypto instance used to facilitate cryptographic + * operations. + * @param key The AWS secret access key. + * @param dateStamp The '%Y%m%d' date format. + * @param region The AWS region. + * @param serviceName The AWS service name, eg. sts. + * @return The signing key bytes. + */ +async function getSigningKey(crypto, key, dateStamp, region, serviceName) { + const kDate = await sign(crypto, `AWS4${key}`, dateStamp); + const kRegion = await sign(crypto, kDate, region); + const kService = await sign(crypto, kRegion, serviceName); + const kSigning = await sign(crypto, kService, 'aws4_request'); + return kSigning; +} +/** + * Generates the authentication header map needed for generating the AWS + * Signature Version 4 signed request. + * + * @param option The options needed to compute the authentication header map. + * @return The AWS authentication header map which constitutes of the following + * components: amz-date, authorization header and canonical query string. + */ +async function generateAuthenticationHeaderMap(options) { + const additionalAmzHeaders = options.additionalAmzHeaders || {}; + const requestPayload = options.requestPayload || ''; + // iam.amazonaws.com host => iam service. + // sts.us-east-2.amazonaws.com => sts service. + const serviceName = options.host.split('.')[0]; + const now = new Date(); + // Format: '%Y%m%dT%H%M%SZ'. + const amzDate = now + .toISOString() + .replace(/[-:]/g, '') + .replace(/\.[0-9]+/, ''); + // Format: '%Y%m%d'. + const dateStamp = now.toISOString().replace(/[-]/g, '').replace(/T.*/, ''); + // Change all additional headers to be lower case. + const reformattedAdditionalAmzHeaders = {}; + Object.keys(additionalAmzHeaders).forEach(key => { + reformattedAdditionalAmzHeaders[key.toLowerCase()] = + additionalAmzHeaders[key]; + }); + // Add AWS token if available. + if (options.securityCredentials.token) { + reformattedAdditionalAmzHeaders['x-amz-security-token'] = + options.securityCredentials.token; + } + // Header keys need to be sorted alphabetically. + const amzHeaders = Object.assign({ + host: options.host, + }, + // Previously the date was not fixed with x-amz- and could be provided manually. + // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.req + reformattedAdditionalAmzHeaders.date ? {} : { 'x-amz-date': amzDate }, reformattedAdditionalAmzHeaders); + let canonicalHeaders = ''; + const signedHeadersList = Object.keys(amzHeaders).sort(); + signedHeadersList.forEach(key => { + canonicalHeaders += `${key}:${amzHeaders[key]}\n`; + }); + const signedHeaders = signedHeadersList.join(';'); + const payloadHash = await options.crypto.sha256DigestHex(requestPayload); + // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html + const canonicalRequest = `${options.method}\n` + + `${options.canonicalUri}\n` + + `${options.canonicalQuerystring}\n` + + `${canonicalHeaders}\n` + + `${signedHeaders}\n` + + `${payloadHash}`; + const credentialScope = `${dateStamp}/${options.region}/${serviceName}/${AWS_REQUEST_TYPE}`; + // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html + const stringToSign = `${AWS_ALGORITHM}\n` + + `${amzDate}\n` + + `${credentialScope}\n` + + (await options.crypto.sha256DigestHex(canonicalRequest)); + // https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html + const signingKey = await getSigningKey(options.crypto, options.securityCredentials.secretAccessKey, dateStamp, options.region, serviceName); + const signature = await sign(options.crypto, signingKey, stringToSign); + // https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html + const authorizationHeader = `${AWS_ALGORITHM} Credential=${options.securityCredentials.accessKeyId}/` + + `${credentialScope}, SignedHeaders=${signedHeaders}, ` + + `Signature=${(0, crypto_1.fromArrayBufferToHex)(signature)}`; + return { + // Do not return x-amz-date if date is available. + amzDate: reformattedAdditionalAmzHeaders.date ? undefined : amzDate, + authorizationHeader, + canonicalQuerystring: options.canonicalQuerystring, + }; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/baseexternalclient.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/baseexternalclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..af14bee08e9606d31c21074a6afc7d1096bdacb2 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/baseexternalclient.d.ts @@ -0,0 +1,322 @@ +import { Gaxios, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +import { Credentials } from './credentials'; +import { AuthClient, AuthClientOptions } from './authclient'; +import { BodyResponseCallback, Transporter } from '../transporters'; +import { GetAccessTokenResponse, Headers } from './oauth2client'; +import { SnakeToCamelObject } from '../util'; +/** + * Offset to take into account network delays and server clock skews. + */ +export declare const EXPIRATION_TIME_OFFSET: number; +/** + * The credentials JSON file type for external account clients. + * There are 3 types of JSON configs: + * 1. authorized_user => Google end user credential + * 2. service_account => Google service account credential + * 3. external_Account => non-GCP service (eg. AWS, Azure, K8s) + */ +export declare const EXTERNAL_ACCOUNT_TYPE = "external_account"; +/** + * Cloud resource manager URL used to retrieve project information. + * + * @deprecated use {@link BaseExternalAccountClient.cloudResourceManagerURL} instead + **/ +export declare const CLOUD_RESOURCE_MANAGER = "https://cloudresourcemanager.googleapis.com/v1/projects/"; +/** + * For backwards compatibility. + */ +export { DEFAULT_UNIVERSE } from './authclient'; +/** + * Shared options used to build {@link ExternalAccountClient} and + * {@link ExternalAccountAuthorizedUserClient}. + */ +export interface SharedExternalAccountClientOptions extends AuthClientOptions { + /** + * The Security Token Service audience, which is usually the fully specified + * resource name of the workload or workforce pool provider. + */ + audience: string; + /** + * The Security Token Service token URL used to exchange the third party token + * for a GCP access token. If not provided, will default to + * 'https://sts.googleapis.com/v1/token' + */ + token_url?: string; +} +/** + * Interface containing context about the requested external identity. This is + * passed on all requests from external account clients to external identity suppliers. + */ +export interface ExternalAccountSupplierContext { + /** + * The requested external account audience. For example: + * * "//iam.googleapis.com/locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID" + * * "//iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/providers/PROVIDER_ID" + */ + audience: string; + /** + * The requested subject token type. Expected values include: + * * "urn:ietf:params:oauth:token-type:jwt" + * * "urn:ietf:params:aws:token-type:aws4_request" + * * "urn:ietf:params:oauth:token-type:saml2" + * * "urn:ietf:params:oauth:token-type:id_token" + */ + subjectTokenType: string; + /** The {@link Gaxios} or {@link Transporter} instance from + * the calling external account to use for requests. + */ + transporter: Transporter | Gaxios; +} +/** + * Base external account credentials json interface. + */ +export interface BaseExternalAccountClientOptions extends SharedExternalAccountClientOptions { + /** + * Credential type, should always be 'external_account'. + */ + type?: string; + /** + * The Security Token Service subject token type based on the OAuth 2.0 + * token exchange spec. Expected values include: + * * 'urn:ietf:params:oauth:token-type:jwt' + * * 'urn:ietf:params:aws:token-type:aws4_request' + * * 'urn:ietf:params:oauth:token-type:saml2' + * * 'urn:ietf:params:oauth:token-type:id_token' + */ + subject_token_type: string; + /** + * The URL for the service account impersonation request. This URL is required + * for some APIs. If this URL is not available, the access token from the + * Security Token Service is used directly. + */ + service_account_impersonation_url?: string; + /** + * Object containing additional options for service account impersonation. + */ + service_account_impersonation?: { + /** + * The desired lifetime of the impersonated service account access token. + * If not provided, the default lifetime will be 3600 seconds. + */ + token_lifetime_seconds?: number; + }; + /** + * The endpoint used to retrieve account related information. + */ + token_info_url?: string; + /** + * Client ID of the service account from the console. + */ + client_id?: string; + /** + * Client secret of the service account from the console. + */ + client_secret?: string; + /** + * The workforce pool user project. Required when using a workforce identity + * pool. + */ + workforce_pool_user_project?: string; + /** + * The scopes to request during the authorization grant. + */ + scopes?: string[]; + /** + * @example + * https://cloudresourcemanager.googleapis.com/v1/projects/ + **/ + cloud_resource_manager_url?: string | URL; +} +/** + * Interface defining the successful response for iamcredentials + * generateAccessToken API. + * https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateAccessToken + */ +export interface IamGenerateAccessTokenResponse { + accessToken: string; + /** + * ISO format used for expiration time. + * + * @example + * '2014-10-02T15:01:23.045123456Z' + */ + expireTime: string; +} +/** + * Interface defining the project information response returned by the cloud + * resource manager. + * https://cloud.google.com/resource-manager/reference/rest/v1/projects#Project + */ +export interface ProjectInfo { + projectNumber: string; + projectId: string; + lifecycleState: string; + name: string; + createTime?: string; + parent: { + [key: string]: any; + }; +} +/** + * Internal interface for tracking the access token expiration time. + */ +interface CredentialsWithResponse extends Credentials { + res?: GaxiosResponse | null; +} +/** + * Base external account client. This is used to instantiate AuthClients for + * exchanging external account credentials for GCP access token and authorizing + * requests to GCP APIs. + * The base class implements common logic for exchanging various type of + * external credentials for GCP access token. The logic of determining and + * retrieving the external credential based on the environment and + * credential_source will be left for the subclasses. + */ +export declare abstract class BaseExternalAccountClient extends AuthClient { + #private; + /** + * OAuth scopes for the GCP access token to use. When not provided, + * the default https://www.googleapis.com/auth/cloud-platform is + * used. + */ + scopes?: string | string[]; + private cachedAccessToken; + protected readonly audience: string; + protected readonly subjectTokenType: string; + private readonly serviceAccountImpersonationUrl?; + private readonly serviceAccountImpersonationLifetime?; + private readonly stsCredential; + private readonly clientAuth?; + private readonly workforcePoolUserProject?; + projectNumber: string | null; + private readonly configLifetimeRequested; + protected credentialSourceType?: string; + /** + * @example + * ```ts + * new URL('https://cloudresourcemanager.googleapis.com/v1/projects/'); + * ``` + */ + protected cloudResourceManagerURL: URL | string; + protected supplierContext: ExternalAccountSupplierContext; + /** + * Instantiate a BaseExternalAccountClient instance using the provided JSON + * object loaded from an external account credentials file. + * @param options The external account options object typically loaded + * from the external account JSON credential file. The camelCased options + * are aliases for the snake_cased options. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options: BaseExternalAccountClientOptions | SnakeToCamelObject, additionalOptions?: AuthClientOptions); + /** The service account email to be impersonated, if available. */ + getServiceAccountEmail(): string | null; + /** + * Provides a mechanism to inject GCP access tokens directly. + * When the provided credential expires, a new credential, using the + * external account options, is retrieved. + * @param credentials The Credentials object to set on the current client. + */ + setCredentials(credentials: Credentials): void; + /** + * Triggered when a external subject token is needed to be exchanged for a GCP + * access token via GCP STS endpoint. + * This abstract method needs to be implemented by subclasses depending on + * the type of external credential used. + * @return A promise that resolves with the external subject token. + */ + abstract retrieveSubjectToken(): Promise; + /** + * @return A promise that resolves with the current GCP access token + * response. If the current credential is expired, a new one is retrieved. + */ + getAccessToken(): Promise; + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * The result has the form: + * { Authorization: 'Bearer ' } + */ + getRequestHeaders(): Promise; + /** + * Provides a request implementation with OAuth 2.0 flow. In cases of + * HTTP 401 and 403 responses, it automatically asks for a new access token + * and replays the unsuccessful request. + * @param opts Request options. + * @param callback callback. + * @return A promise that resolves with the HTTP response when no callback is + * provided. + */ + request(opts: GaxiosOptions): GaxiosPromise; + request(opts: GaxiosOptions, callback: BodyResponseCallback): void; + /** + * @return A promise that resolves with the project ID corresponding to the + * current workload identity pool or current workforce pool if + * determinable. For workforce pool credential, it returns the project ID + * corresponding to the workforcePoolUserProject. + * This is introduced to match the current pattern of using the Auth + * library: + * const projectId = await auth.getProjectId(); + * const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; + * const res = await client.request({ url }); + * The resource may not have permission + * (resourcemanager.projects.get) to call this API or the required + * scopes may not be selected: + * https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes + */ + getProjectId(): Promise; + /** + * Authenticates the provided HTTP request, processes it and resolves with the + * returned response. + * @param opts The HTTP request options. + * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure. + * @return A promise that resolves with the successful response. + */ + protected requestAsync(opts: GaxiosOptions, reAuthRetried?: boolean): Promise>; + /** + * Forces token refresh, even if unexpired tokens are currently cached. + * External credentials are exchanged for GCP access tokens via the token + * exchange endpoint and other settings provided in the client options + * object. + * If the service_account_impersonation_url is provided, an additional + * step to exchange the external account GCP access token for a service + * account impersonated token is performed. + * @return A promise that resolves with the fresh GCP access tokens. + */ + protected refreshAccessTokenAsync(): Promise; + /** + * Returns the workload identity pool project number if it is determinable + * from the audience resource name. + * @param audience The STS audience used to determine the project number. + * @return The project number associated with the workload identity pool, if + * this can be determined from the STS audience field. Otherwise, null is + * returned. + */ + private getProjectNumber; + /** + * Exchanges an external account GCP access token for a service + * account impersonated access token using iamcredentials + * GenerateAccessToken API. + * @param token The access token to exchange for a service account access + * token. + * @return A promise that resolves with the service account impersonated + * credentials response. + */ + private getImpersonatedAccessToken; + /** + * Returns whether the provided credentials are expired or not. + * If there is no expiry time, assumes the token is not expired or expiring. + * @param accessToken The credentials to check for expiration. + * @return Whether the credentials are expired or not. + */ + private isExpired; + /** + * @return The list of scopes for the requested GCP access token. + */ + private getScopesArray; + private getMetricsHeaderValue; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/baseexternalclient.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/baseexternalclient.js new file mode 100644 index 0000000000000000000000000000000000000000..c39861bff996c5c29e75855990d617cec5185c18 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/baseexternalclient.js @@ -0,0 +1,468 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var _BaseExternalAccountClient_instances, _BaseExternalAccountClient_pendingAccessToken, _BaseExternalAccountClient_internalRefreshAccessTokenAsync; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BaseExternalAccountClient = exports.DEFAULT_UNIVERSE = exports.CLOUD_RESOURCE_MANAGER = exports.EXTERNAL_ACCOUNT_TYPE = exports.EXPIRATION_TIME_OFFSET = void 0; +const stream = require("stream"); +const authclient_1 = require("./authclient"); +const sts = require("./stscredentials"); +const util_1 = require("../util"); +/** + * The required token exchange grant_type: rfc8693#section-2.1 + */ +const STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange'; +/** + * The requested token exchange requested_token_type: rfc8693#section-2.1 + */ +const STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token'; +/** The default OAuth scope to request when none is provided. */ +const DEFAULT_OAUTH_SCOPE = 'https://www.googleapis.com/auth/cloud-platform'; +/** Default impersonated token lifespan in seconds.*/ +const DEFAULT_TOKEN_LIFESPAN = 3600; +/** + * Offset to take into account network delays and server clock skews. + */ +exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000; +/** + * The credentials JSON file type for external account clients. + * There are 3 types of JSON configs: + * 1. authorized_user => Google end user credential + * 2. service_account => Google service account credential + * 3. external_Account => non-GCP service (eg. AWS, Azure, K8s) + */ +exports.EXTERNAL_ACCOUNT_TYPE = 'external_account'; +/** + * Cloud resource manager URL used to retrieve project information. + * + * @deprecated use {@link BaseExternalAccountClient.cloudResourceManagerURL} instead + **/ +exports.CLOUD_RESOURCE_MANAGER = 'https://cloudresourcemanager.googleapis.com/v1/projects/'; +/** The workforce audience pattern. */ +const WORKFORCE_AUDIENCE_PATTERN = '//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+'; +const DEFAULT_TOKEN_URL = 'https://sts.{universeDomain}/v1/token'; +// eslint-disable-next-line @typescript-eslint/no-var-requires +const pkg = require('../../../package.json'); +/** + * For backwards compatibility. + */ +var authclient_2 = require("./authclient"); +Object.defineProperty(exports, "DEFAULT_UNIVERSE", { enumerable: true, get: function () { return authclient_2.DEFAULT_UNIVERSE; } }); +/** + * Base external account client. This is used to instantiate AuthClients for + * exchanging external account credentials for GCP access token and authorizing + * requests to GCP APIs. + * The base class implements common logic for exchanging various type of + * external credentials for GCP access token. The logic of determining and + * retrieving the external credential based on the environment and + * credential_source will be left for the subclasses. + */ +class BaseExternalAccountClient extends authclient_1.AuthClient { + /** + * Instantiate a BaseExternalAccountClient instance using the provided JSON + * object loaded from an external account credentials file. + * @param options The external account options object typically loaded + * from the external account JSON credential file. The camelCased options + * are aliases for the snake_cased options. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options, additionalOptions) { + var _a; + super({ ...options, ...additionalOptions }); + _BaseExternalAccountClient_instances.add(this); + /** + * A pending access token request. Used for concurrent calls. + */ + _BaseExternalAccountClient_pendingAccessToken.set(this, null); + const opts = (0, util_1.originalOrCamelOptions)(options); + const type = opts.get('type'); + if (type && type !== exports.EXTERNAL_ACCOUNT_TYPE) { + throw new Error(`Expected "${exports.EXTERNAL_ACCOUNT_TYPE}" type but ` + + `received "${options.type}"`); + } + const clientId = opts.get('client_id'); + const clientSecret = opts.get('client_secret'); + const tokenUrl = (_a = opts.get('token_url')) !== null && _a !== void 0 ? _a : DEFAULT_TOKEN_URL.replace('{universeDomain}', this.universeDomain); + const subjectTokenType = opts.get('subject_token_type'); + const workforcePoolUserProject = opts.get('workforce_pool_user_project'); + const serviceAccountImpersonationUrl = opts.get('service_account_impersonation_url'); + const serviceAccountImpersonation = opts.get('service_account_impersonation'); + const serviceAccountImpersonationLifetime = (0, util_1.originalOrCamelOptions)(serviceAccountImpersonation).get('token_lifetime_seconds'); + this.cloudResourceManagerURL = new URL(opts.get('cloud_resource_manager_url') || + `https://cloudresourcemanager.${this.universeDomain}/v1/projects/`); + if (clientId) { + this.clientAuth = { + confidentialClientType: 'basic', + clientId, + clientSecret, + }; + } + this.stsCredential = new sts.StsCredentials(tokenUrl, this.clientAuth); + this.scopes = opts.get('scopes') || [DEFAULT_OAUTH_SCOPE]; + this.cachedAccessToken = null; + this.audience = opts.get('audience'); + this.subjectTokenType = subjectTokenType; + this.workforcePoolUserProject = workforcePoolUserProject; + const workforceAudiencePattern = new RegExp(WORKFORCE_AUDIENCE_PATTERN); + if (this.workforcePoolUserProject && + !this.audience.match(workforceAudiencePattern)) { + throw new Error('workforcePoolUserProject should not be set for non-workforce pool ' + + 'credentials.'); + } + this.serviceAccountImpersonationUrl = serviceAccountImpersonationUrl; + this.serviceAccountImpersonationLifetime = + serviceAccountImpersonationLifetime; + if (this.serviceAccountImpersonationLifetime) { + this.configLifetimeRequested = true; + } + else { + this.configLifetimeRequested = false; + this.serviceAccountImpersonationLifetime = DEFAULT_TOKEN_LIFESPAN; + } + this.projectNumber = this.getProjectNumber(this.audience); + this.supplierContext = { + audience: this.audience, + subjectTokenType: this.subjectTokenType, + transporter: this.transporter, + }; + } + /** The service account email to be impersonated, if available. */ + getServiceAccountEmail() { + var _a; + if (this.serviceAccountImpersonationUrl) { + if (this.serviceAccountImpersonationUrl.length > 256) { + /** + * Prevents DOS attacks. + * @see {@link https://github.com/googleapis/google-auth-library-nodejs/security/code-scanning/84} + **/ + throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`); + } + // Parse email from URL. The formal looks as follows: + // https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/name@project-id.iam.gserviceaccount.com:generateAccessToken + const re = /serviceAccounts\/(?[^:]+):generateAccessToken$/; + const result = re.exec(this.serviceAccountImpersonationUrl); + return ((_a = result === null || result === void 0 ? void 0 : result.groups) === null || _a === void 0 ? void 0 : _a.email) || null; + } + return null; + } + /** + * Provides a mechanism to inject GCP access tokens directly. + * When the provided credential expires, a new credential, using the + * external account options, is retrieved. + * @param credentials The Credentials object to set on the current client. + */ + setCredentials(credentials) { + super.setCredentials(credentials); + this.cachedAccessToken = credentials; + } + /** + * @return A promise that resolves with the current GCP access token + * response. If the current credential is expired, a new one is retrieved. + */ + async getAccessToken() { + // If cached access token is unavailable or expired, force refresh. + if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) { + await this.refreshAccessTokenAsync(); + } + // Return GCP access token in GetAccessTokenResponse format. + return { + token: this.cachedAccessToken.access_token, + res: this.cachedAccessToken.res, + }; + } + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * The result has the form: + * { Authorization: 'Bearer ' } + */ + async getRequestHeaders() { + const accessTokenResponse = await this.getAccessToken(); + const headers = { + Authorization: `Bearer ${accessTokenResponse.token}`, + }; + return this.addSharedMetadataHeaders(headers); + } + request(opts, callback) { + if (callback) { + this.requestAsync(opts).then(r => callback(null, r), e => { + return callback(e, e.response); + }); + } + else { + return this.requestAsync(opts); + } + } + /** + * @return A promise that resolves with the project ID corresponding to the + * current workload identity pool or current workforce pool if + * determinable. For workforce pool credential, it returns the project ID + * corresponding to the workforcePoolUserProject. + * This is introduced to match the current pattern of using the Auth + * library: + * const projectId = await auth.getProjectId(); + * const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; + * const res = await client.request({ url }); + * The resource may not have permission + * (resourcemanager.projects.get) to call this API or the required + * scopes may not be selected: + * https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes + */ + async getProjectId() { + const projectNumber = this.projectNumber || this.workforcePoolUserProject; + if (this.projectId) { + // Return previously determined project ID. + return this.projectId; + } + else if (projectNumber) { + // Preferable not to use request() to avoid retrial policies. + const headers = await this.getRequestHeaders(); + const response = await this.transporter.request({ + ...BaseExternalAccountClient.RETRY_CONFIG, + headers, + url: `${this.cloudResourceManagerURL.toString()}${projectNumber}`, + responseType: 'json', + }); + this.projectId = response.data.projectId; + return this.projectId; + } + return null; + } + /** + * Authenticates the provided HTTP request, processes it and resolves with the + * returned response. + * @param opts The HTTP request options. + * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure. + * @return A promise that resolves with the successful response. + */ + async requestAsync(opts, reAuthRetried = false) { + let response; + try { + const requestHeaders = await this.getRequestHeaders(); + opts.headers = opts.headers || {}; + if (requestHeaders && requestHeaders['x-goog-user-project']) { + opts.headers['x-goog-user-project'] = + requestHeaders['x-goog-user-project']; + } + if (requestHeaders && requestHeaders.Authorization) { + opts.headers.Authorization = requestHeaders.Authorization; + } + response = await this.transporter.request(opts); + } + catch (e) { + const res = e.response; + if (res) { + const statusCode = res.status; + // Retry the request for metadata if the following criteria are true: + // - We haven't already retried. It only makes sense to retry once. + // - The response was a 401 or a 403 + // - The request didn't send a readableStream + // - forceRefreshOnFailure is true + const isReadableStream = res.config.data instanceof stream.Readable; + const isAuthErr = statusCode === 401 || statusCode === 403; + if (!reAuthRetried && + isAuthErr && + !isReadableStream && + this.forceRefreshOnFailure) { + await this.refreshAccessTokenAsync(); + return await this.requestAsync(opts, true); + } + } + throw e; + } + return response; + } + /** + * Forces token refresh, even if unexpired tokens are currently cached. + * External credentials are exchanged for GCP access tokens via the token + * exchange endpoint and other settings provided in the client options + * object. + * If the service_account_impersonation_url is provided, an additional + * step to exchange the external account GCP access token for a service + * account impersonated token is performed. + * @return A promise that resolves with the fresh GCP access tokens. + */ + async refreshAccessTokenAsync() { + // Use an existing access token request, or cache a new one + __classPrivateFieldSet(this, _BaseExternalAccountClient_pendingAccessToken, __classPrivateFieldGet(this, _BaseExternalAccountClient_pendingAccessToken, "f") || __classPrivateFieldGet(this, _BaseExternalAccountClient_instances, "m", _BaseExternalAccountClient_internalRefreshAccessTokenAsync).call(this), "f"); + try { + return await __classPrivateFieldGet(this, _BaseExternalAccountClient_pendingAccessToken, "f"); + } + finally { + // clear pending access token for future requests + __classPrivateFieldSet(this, _BaseExternalAccountClient_pendingAccessToken, null, "f"); + } + } + /** + * Returns the workload identity pool project number if it is determinable + * from the audience resource name. + * @param audience The STS audience used to determine the project number. + * @return The project number associated with the workload identity pool, if + * this can be determined from the STS audience field. Otherwise, null is + * returned. + */ + getProjectNumber(audience) { + // STS audience pattern: + // //iam.googleapis.com/projects/$PROJECT_NUMBER/locations/... + const match = audience.match(/\/projects\/([^/]+)/); + if (!match) { + return null; + } + return match[1]; + } + /** + * Exchanges an external account GCP access token for a service + * account impersonated access token using iamcredentials + * GenerateAccessToken API. + * @param token The access token to exchange for a service account access + * token. + * @return A promise that resolves with the service account impersonated + * credentials response. + */ + async getImpersonatedAccessToken(token) { + const opts = { + ...BaseExternalAccountClient.RETRY_CONFIG, + url: this.serviceAccountImpersonationUrl, + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token}`, + }, + data: { + scope: this.getScopesArray(), + lifetime: this.serviceAccountImpersonationLifetime + 's', + }, + responseType: 'json', + }; + const response = await this.transporter.request(opts); + const successResponse = response.data; + return { + access_token: successResponse.accessToken, + // Convert from ISO format to timestamp. + expiry_date: new Date(successResponse.expireTime).getTime(), + res: response, + }; + } + /** + * Returns whether the provided credentials are expired or not. + * If there is no expiry time, assumes the token is not expired or expiring. + * @param accessToken The credentials to check for expiration. + * @return Whether the credentials are expired or not. + */ + isExpired(accessToken) { + const now = new Date().getTime(); + return accessToken.expiry_date + ? now >= accessToken.expiry_date - this.eagerRefreshThresholdMillis + : false; + } + /** + * @return The list of scopes for the requested GCP access token. + */ + getScopesArray() { + // Since scopes can be provided as string or array, the type should + // be normalized. + if (typeof this.scopes === 'string') { + return [this.scopes]; + } + return this.scopes || [DEFAULT_OAUTH_SCOPE]; + } + getMetricsHeaderValue() { + const nodeVersion = process.version.replace(/^v/, ''); + const saImpersonation = this.serviceAccountImpersonationUrl !== undefined; + const credentialSourceType = this.credentialSourceType + ? this.credentialSourceType + : 'unknown'; + return `gl-node/${nodeVersion} auth/${pkg.version} google-byoid-sdk source/${credentialSourceType} sa-impersonation/${saImpersonation} config-lifetime/${this.configLifetimeRequested}`; + } +} +exports.BaseExternalAccountClient = BaseExternalAccountClient; +_BaseExternalAccountClient_pendingAccessToken = new WeakMap(), _BaseExternalAccountClient_instances = new WeakSet(), _BaseExternalAccountClient_internalRefreshAccessTokenAsync = async function _BaseExternalAccountClient_internalRefreshAccessTokenAsync() { + // Retrieve the external credential. + const subjectToken = await this.retrieveSubjectToken(); + // Construct the STS credentials options. + const stsCredentialsOptions = { + grantType: STS_GRANT_TYPE, + audience: this.audience, + requestedTokenType: STS_REQUEST_TOKEN_TYPE, + subjectToken, + subjectTokenType: this.subjectTokenType, + // generateAccessToken requires the provided access token to have + // scopes: + // https://www.googleapis.com/auth/iam or + // https://www.googleapis.com/auth/cloud-platform + // The new service account access token scopes will match the user + // provided ones. + scope: this.serviceAccountImpersonationUrl + ? [DEFAULT_OAUTH_SCOPE] + : this.getScopesArray(), + }; + // Exchange the external credentials for a GCP access token. + // Client auth is prioritized over passing the workforcePoolUserProject + // parameter for STS token exchange. + const additionalOptions = !this.clientAuth && this.workforcePoolUserProject + ? { userProject: this.workforcePoolUserProject } + : undefined; + const additionalHeaders = { + 'x-goog-api-client': this.getMetricsHeaderValue(), + }; + const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, additionalHeaders, additionalOptions); + if (this.serviceAccountImpersonationUrl) { + this.cachedAccessToken = await this.getImpersonatedAccessToken(stsResponse.access_token); + } + else if (stsResponse.expires_in) { + // Save response in cached access token. + this.cachedAccessToken = { + access_token: stsResponse.access_token, + expiry_date: new Date().getTime() + stsResponse.expires_in * 1000, + res: stsResponse.res, + }; + } + else { + // Save response in cached access token. + this.cachedAccessToken = { + access_token: stsResponse.access_token, + res: stsResponse.res, + }; + } + // Save credentials. + this.credentials = {}; + Object.assign(this.credentials, this.cachedAccessToken); + delete this.credentials.res; + // Trigger tokens event to notify external listeners. + this.emit('tokens', { + refresh_token: null, + expiry_date: this.cachedAccessToken.expiry_date, + access_token: this.cachedAccessToken.access_token, + token_type: 'Bearer', + id_token: null, + }); + // Return the cached access token. + return this.cachedAccessToken; +}; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/computeclient.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/computeclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2d883668072b3024cc45d65b75af4ac7d5df4a60 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/computeclient.d.ts @@ -0,0 +1,37 @@ +import { GaxiosError } from 'gaxios'; +import { GetTokenResponse, OAuth2Client, OAuth2ClientOptions } from './oauth2client'; +export interface ComputeOptions extends OAuth2ClientOptions { + /** + * The service account email to use, or 'default'. A Compute Engine instance + * may have multiple service accounts. + */ + serviceAccountEmail?: string; + /** + * The scopes that will be requested when acquiring service account + * credentials. Only applicable to modern App Engine and Cloud Function + * runtimes as of March 2019. + */ + scopes?: string | string[]; +} +export declare class Compute extends OAuth2Client { + readonly serviceAccountEmail: string; + scopes: string[]; + /** + * Google Compute Engine service account credentials. + * + * Retrieve access token from the metadata server. + * See: https://cloud.google.com/compute/docs/access/authenticate-workloads#applications + */ + constructor(options?: ComputeOptions); + /** + * Refreshes the access token. + * @param refreshToken Unused parameter + */ + protected refreshTokenNoCache(refreshToken?: string | null): Promise; + /** + * Fetches an ID token. + * @param targetAudience the audience for the fetched ID token. + */ + fetchIdToken(targetAudience: string): Promise; + protected wrapError(e: GaxiosError): void; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/computeclient.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/computeclient.js new file mode 100644 index 0000000000000000000000000000000000000000..4554e03e4b498bcc27e6c481fc3f03dfc6472996 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/computeclient.js @@ -0,0 +1,117 @@ +"use strict"; +// Copyright 2013 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Compute = void 0; +const gaxios_1 = require("gaxios"); +const gcpMetadata = require("gcp-metadata"); +const oauth2client_1 = require("./oauth2client"); +class Compute extends oauth2client_1.OAuth2Client { + /** + * Google Compute Engine service account credentials. + * + * Retrieve access token from the metadata server. + * See: https://cloud.google.com/compute/docs/access/authenticate-workloads#applications + */ + constructor(options = {}) { + super(options); + // Start with an expired refresh token, which will automatically be + // refreshed before the first API call is made. + this.credentials = { expiry_date: 1, refresh_token: 'compute-placeholder' }; + this.serviceAccountEmail = options.serviceAccountEmail || 'default'; + this.scopes = Array.isArray(options.scopes) + ? options.scopes + : options.scopes + ? [options.scopes] + : []; + } + /** + * Refreshes the access token. + * @param refreshToken Unused parameter + */ + async refreshTokenNoCache( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + refreshToken) { + const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`; + let data; + try { + const instanceOptions = { + property: tokenPath, + }; + if (this.scopes.length > 0) { + instanceOptions.params = { + scopes: this.scopes.join(','), + }; + } + data = await gcpMetadata.instance(instanceOptions); + } + catch (e) { + if (e instanceof gaxios_1.GaxiosError) { + e.message = `Could not refresh access token: ${e.message}`; + this.wrapError(e); + } + throw e; + } + const tokens = data; + if (data && data.expires_in) { + tokens.expiry_date = new Date().getTime() + data.expires_in * 1000; + delete tokens.expires_in; + } + this.emit('tokens', tokens); + return { tokens, res: null }; + } + /** + * Fetches an ID token. + * @param targetAudience the audience for the fetched ID token. + */ + async fetchIdToken(targetAudience) { + const idTokenPath = `service-accounts/${this.serviceAccountEmail}/identity` + + `?format=full&audience=${targetAudience}`; + let idToken; + try { + const instanceOptions = { + property: idTokenPath, + }; + idToken = await gcpMetadata.instance(instanceOptions); + } + catch (e) { + if (e instanceof Error) { + e.message = `Could not fetch ID token: ${e.message}`; + } + throw e; + } + return idToken; + } + wrapError(e) { + const res = e.response; + if (res && res.status) { + e.status = res.status; + if (res.status === 403) { + e.message = + 'A Forbidden error was returned while attempting to retrieve an access ' + + 'token for the Compute Engine built-in service account. This may be because the Compute ' + + 'Engine instance does not have the correct permission scopes specified: ' + + e.message; + } + else if (res.status === 404) { + e.message = + 'A Not Found error was returned while attempting to retrieve an access' + + 'token for the Compute Engine built-in service account. This may be because the Compute ' + + 'Engine instance does not have any permission scopes specified: ' + + e.message; + } + } + } +} +exports.Compute = Compute; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/credentials.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/credentials.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..896b014ccb8d6c6b54b13f6b3da2b019a7b74c1c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/credentials.d.ts @@ -0,0 +1,75 @@ +export interface Credentials { + /** + * This field is only present if the access_type parameter was set to offline in the authentication request. For details, see Refresh tokens. + */ + refresh_token?: string | null; + /** + * The time in ms at which this token is thought to expire. + */ + expiry_date?: number | null; + /** + * A token that can be sent to a Google API. + */ + access_token?: string | null; + /** + * Identifies the type of token returned. At this time, this field always has the value Bearer. + */ + token_type?: string | null; + /** + * A JWT that contains identity information about the user that is digitally signed by Google. + */ + id_token?: string | null; + /** + * The scopes of access granted by the access_token expressed as a list of space-delimited, case-sensitive strings. + */ + scope?: string; +} +export interface CredentialRequest { + /** + * This field is only present if the access_type parameter was set to offline in the authentication request. For details, see Refresh tokens. + */ + refresh_token?: string; + /** + * A token that can be sent to a Google API. + */ + access_token?: string; + /** + * Identifies the type of token returned. At this time, this field always has the value Bearer. + */ + token_type?: string; + /** + * The remaining lifetime of the access token in seconds. + */ + expires_in?: number; + /** + * A JWT that contains identity information about the user that is digitally signed by Google. + */ + id_token?: string; + /** + * The scopes of access granted by the access_token expressed as a list of space-delimited, case-sensitive strings. + */ + scope?: string; +} +export interface JWTInput { + type?: string; + client_email?: string; + private_key?: string; + private_key_id?: string; + project_id?: string; + client_id?: string; + client_secret?: string; + refresh_token?: string; + quota_project_id?: string; + universe_domain?: string; +} +export interface ImpersonatedJWTInput { + type?: string; + source_credentials?: JWTInput; + service_account_impersonation_url?: string; + delegates?: string[]; +} +export interface CredentialBody { + client_email?: string; + private_key?: string; + universe_domain?: string; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/credentials.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/credentials.js new file mode 100644 index 0000000000000000000000000000000000000000..8db999f000222a5ed71d9058531eef39e2801a9f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/credentials.js @@ -0,0 +1,15 @@ +"use strict"; +// Copyright 2014 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..62a2fa41464d57aa6850157938c567be5e0fa3e5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.d.ts @@ -0,0 +1,79 @@ +import { ExternalAccountSupplierContext } from './baseexternalclient'; +import { GaxiosOptions } from 'gaxios'; +import { AwsSecurityCredentialsSupplier } from './awsclient'; +import { AwsSecurityCredentials } from './awsrequestsigner'; +/** + * Interface defining the options used to build a {@link DefaultAwsSecurityCredentialsSupplier}. + */ +export interface DefaultAwsSecurityCredentialsSupplierOptions { + /** + * The URL to call to retrieve the active AWS region. + **/ + regionUrl?: string; + /** + * The URL to call to retrieve AWS security credentials. + **/ + securityCredentialsUrl?: string; + /** + ** The URL to call to retrieve the IMDSV2 session token. + **/ + imdsV2SessionTokenUrl?: string; + /** + * Additional Gaxios options to use when making requests to the AWS metadata + * endpoints. + */ + additionalGaxiosOptions?: GaxiosOptions; +} +/** + * Internal AWS security credentials supplier implementation used by {@link AwsClient} + * when a credential source is provided instead of a user defined supplier. + * The logic is summarized as: + * 1. If imdsv2_session_token_url is provided in the credential source, then + * fetch the aws session token and include it in the headers of the + * metadata requests. This is a requirement for IDMSv2 but optional + * for IDMSv1. + * 2. Retrieve AWS region from availability-zone. + * 3a. Check AWS credentials in environment variables. If not found, get + * from security-credentials endpoint. + * 3b. Get AWS credentials from security-credentials endpoint. In order + * to retrieve this, the AWS role needs to be determined by calling + * security-credentials endpoint without any argument. Then the + * credentials can be retrieved via: security-credentials/role_name + * 4. Generate the signed request to AWS STS GetCallerIdentity action. + * 5. Inject x-goog-cloud-target-resource into header and serialize the + * signed request. This will be the subject-token to pass to GCP STS. + */ +export declare class DefaultAwsSecurityCredentialsSupplier implements AwsSecurityCredentialsSupplier { + #private; + private readonly regionUrl?; + private readonly securityCredentialsUrl?; + private readonly imdsV2SessionTokenUrl?; + private readonly additionalGaxiosOptions?; + /** + * Instantiates a new DefaultAwsSecurityCredentialsSupplier using information + * from the credential_source stored in the ADC file. + * @param opts The default aws security credentials supplier options object to + * build the supplier with. + */ + constructor(opts: DefaultAwsSecurityCredentialsSupplierOptions); + /** + * Returns the active AWS region. This first checks to see if the region + * is available as an environment variable. If it is not, then the supplier + * will call the region URL. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link AwsClient}, contains the requested audience and subject token type + * for the external account identity. + * @return A promise that resolves with the AWS region string. + */ + getAwsRegion(context: ExternalAccountSupplierContext): Promise; + /** + * Returns AWS security credentials. This first checks to see if the credentials + * is available as environment variables. If it is not, then the supplier + * will call the security credentials URL. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link AwsClient}, contains the requested audience and subject token type + * for the external account identity. + * @return A promise that resolves with the AWS security credentials. + */ + getAwsSecurityCredentials(context: ExternalAccountSupplierContext): Promise; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js new file mode 100644 index 0000000000000000000000000000000000000000..83d95bc38ae5b14428a997deab9f50ff7e61ebb0 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js @@ -0,0 +1,196 @@ +"use strict"; +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _DefaultAwsSecurityCredentialsSupplier_instances, _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken, _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName, _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials, _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get, _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DefaultAwsSecurityCredentialsSupplier = void 0; +/** + * Internal AWS security credentials supplier implementation used by {@link AwsClient} + * when a credential source is provided instead of a user defined supplier. + * The logic is summarized as: + * 1. If imdsv2_session_token_url is provided in the credential source, then + * fetch the aws session token and include it in the headers of the + * metadata requests. This is a requirement for IDMSv2 but optional + * for IDMSv1. + * 2. Retrieve AWS region from availability-zone. + * 3a. Check AWS credentials in environment variables. If not found, get + * from security-credentials endpoint. + * 3b. Get AWS credentials from security-credentials endpoint. In order + * to retrieve this, the AWS role needs to be determined by calling + * security-credentials endpoint without any argument. Then the + * credentials can be retrieved via: security-credentials/role_name + * 4. Generate the signed request to AWS STS GetCallerIdentity action. + * 5. Inject x-goog-cloud-target-resource into header and serialize the + * signed request. This will be the subject-token to pass to GCP STS. + */ +class DefaultAwsSecurityCredentialsSupplier { + /** + * Instantiates a new DefaultAwsSecurityCredentialsSupplier using information + * from the credential_source stored in the ADC file. + * @param opts The default aws security credentials supplier options object to + * build the supplier with. + */ + constructor(opts) { + _DefaultAwsSecurityCredentialsSupplier_instances.add(this); + this.regionUrl = opts.regionUrl; + this.securityCredentialsUrl = opts.securityCredentialsUrl; + this.imdsV2SessionTokenUrl = opts.imdsV2SessionTokenUrl; + this.additionalGaxiosOptions = opts.additionalGaxiosOptions; + } + /** + * Returns the active AWS region. This first checks to see if the region + * is available as an environment variable. If it is not, then the supplier + * will call the region URL. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link AwsClient}, contains the requested audience and subject token type + * for the external account identity. + * @return A promise that resolves with the AWS region string. + */ + async getAwsRegion(context) { + // Priority order for region determination: + // AWS_REGION > AWS_DEFAULT_REGION > metadata server. + if (__classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get)) { + return __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get); + } + const metadataHeaders = {}; + if (!__classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get) && this.imdsV2SessionTokenUrl) { + metadataHeaders['x-aws-ec2-metadata-token'] = + await __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken).call(this, context.transporter); + } + if (!this.regionUrl) { + throw new Error('Unable to determine AWS region due to missing ' + + '"options.credential_source.region_url"'); + } + const opts = { + ...this.additionalGaxiosOptions, + url: this.regionUrl, + method: 'GET', + responseType: 'text', + headers: metadataHeaders, + }; + const response = await context.transporter.request(opts); + // Remove last character. For example, if us-east-2b is returned, + // the region would be us-east-2. + return response.data.substr(0, response.data.length - 1); + } + /** + * Returns AWS security credentials. This first checks to see if the credentials + * is available as environment variables. If it is not, then the supplier + * will call the security credentials URL. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link AwsClient}, contains the requested audience and subject token type + * for the external account identity. + * @return A promise that resolves with the AWS security credentials. + */ + async getAwsSecurityCredentials(context) { + // Check environment variables for permanent credentials first. + // https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html + if (__classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get)) { + return __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get); + } + const metadataHeaders = {}; + if (this.imdsV2SessionTokenUrl) { + metadataHeaders['x-aws-ec2-metadata-token'] = + await __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken).call(this, context.transporter); + } + // Since the role on a VM can change, we don't need to cache it. + const roleName = await __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName).call(this, metadataHeaders, context.transporter); + // Temporary credentials typically last for several hours. + // Expiration is returned in response. + // Consider future optimization of this logic to cache AWS tokens + // until their natural expiration. + const awsCreds = await __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials).call(this, roleName, metadataHeaders, context.transporter); + return { + accessKeyId: awsCreds.AccessKeyId, + secretAccessKey: awsCreds.SecretAccessKey, + token: awsCreds.Token, + }; + } +} +exports.DefaultAwsSecurityCredentialsSupplier = DefaultAwsSecurityCredentialsSupplier; +_DefaultAwsSecurityCredentialsSupplier_instances = new WeakSet(), _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken = +/** + * @param transporter The transporter to use for requests. + * @return A promise that resolves with the IMDSv2 Session Token. + */ +async function _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken(transporter) { + const opts = { + ...this.additionalGaxiosOptions, + url: this.imdsV2SessionTokenUrl, + method: 'PUT', + responseType: 'text', + headers: { 'x-aws-ec2-metadata-token-ttl-seconds': '300' }, + }; + const response = await transporter.request(opts); + return response.data; +}, _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName = +/** + * @param headers The headers to be used in the metadata request. + * @param transporter The transporter to use for requests. + * @return A promise that resolves with the assigned role to the current + * AWS VM. This is needed for calling the security-credentials endpoint. + */ +async function _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName(headers, transporter) { + if (!this.securityCredentialsUrl) { + throw new Error('Unable to determine AWS role name due to missing ' + + '"options.credential_source.url"'); + } + const opts = { + ...this.additionalGaxiosOptions, + url: this.securityCredentialsUrl, + method: 'GET', + responseType: 'text', + headers: headers, + }; + const response = await transporter.request(opts); + return response.data; +}, _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials = +/** + * Retrieves the temporary AWS credentials by calling the security-credentials + * endpoint as specified in the `credential_source` object. + * @param roleName The role attached to the current VM. + * @param headers The headers to be used in the metadata request. + * @param transporter The transporter to use for requests. + * @return A promise that resolves with the temporary AWS credentials + * needed for creating the GetCallerIdentity signed request. + */ +async function _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials(roleName, headers, transporter) { + const response = await transporter.request({ + ...this.additionalGaxiosOptions, + url: `${this.securityCredentialsUrl}/${roleName}`, + responseType: 'json', + headers: headers, + }); + return response.data; +}, _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get = function _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get() { + // The AWS region can be provided through AWS_REGION or AWS_DEFAULT_REGION. + // Only one is required. + return (process.env['AWS_REGION'] || process.env['AWS_DEFAULT_REGION'] || null); +}, _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get = function _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get() { + // Both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are required. + if (process.env['AWS_ACCESS_KEY_ID'] && + process.env['AWS_SECRET_ACCESS_KEY']) { + return { + accessKeyId: process.env['AWS_ACCESS_KEY_ID'], + secretAccessKey: process.env['AWS_SECRET_ACCESS_KEY'], + token: process.env['AWS_SESSION_TOKEN'], + }; + } + return null; +}; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/downscopedclient.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/downscopedclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..028379bf641a9b7bbb52da4a6d00f6900395c62a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/downscopedclient.d.ts @@ -0,0 +1,139 @@ +import { GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +import { BodyResponseCallback } from '../transporters'; +import { Credentials } from './credentials'; +import { AuthClient, AuthClientOptions } from './authclient'; +import { GetAccessTokenResponse, Headers } from './oauth2client'; +/** + * The maximum number of access boundary rules a Credential Access Boundary + * can contain. + */ +export declare const MAX_ACCESS_BOUNDARY_RULES_COUNT = 10; +/** + * Offset to take into account network delays and server clock skews. + */ +export declare const EXPIRATION_TIME_OFFSET: number; +/** + * Internal interface for tracking the access token expiration time. + */ +interface CredentialsWithResponse extends Credentials { + res?: GaxiosResponse | null; +} +/** + * Internal interface for tracking and returning the Downscoped access token + * expiration time in epoch time (seconds). + */ +interface DownscopedAccessTokenResponse extends GetAccessTokenResponse { + expirationTime?: number | null; +} +/** + * Defines an upper bound of permissions available for a GCP credential. + */ +export interface CredentialAccessBoundary { + accessBoundary: { + accessBoundaryRules: AccessBoundaryRule[]; + }; +} +/** Defines an upper bound of permissions on a particular resource. */ +interface AccessBoundaryRule { + availablePermissions: string[]; + availableResource: string; + availabilityCondition?: AvailabilityCondition; +} +/** + * An optional condition that can be used as part of a + * CredentialAccessBoundary to further restrict permissions. + */ +interface AvailabilityCondition { + expression: string; + title?: string; + description?: string; +} +/** + * Defines a set of Google credentials that are downscoped from an existing set + * of Google OAuth2 credentials. This is useful to restrict the Identity and + * Access Management (IAM) permissions that a short-lived credential can use. + * The common pattern of usage is to have a token broker with elevated access + * generate these downscoped credentials from higher access source credentials + * and pass the downscoped short-lived access tokens to a token consumer via + * some secure authenticated channel for limited access to Google Cloud Storage + * resources. + */ +export declare class DownscopedClient extends AuthClient { + private readonly authClient; + private readonly credentialAccessBoundary; + private cachedDownscopedAccessToken; + private readonly stsCredential; + /** + * Instantiates a downscoped client object using the provided source + * AuthClient and credential access boundary rules. + * To downscope permissions of a source AuthClient, a Credential Access + * Boundary that specifies which resources the new credential can access, as + * well as an upper bound on the permissions that are available on each + * resource, has to be defined. A downscoped client can then be instantiated + * using the source AuthClient and the Credential Access Boundary. + * @param authClient The source AuthClient to be downscoped based on the + * provided Credential Access Boundary rules. + * @param credentialAccessBoundary The Credential Access Boundary which + * contains a list of access boundary rules. Each rule contains information + * on the resource that the rule applies to, the upper bound of the + * permissions that are available on that resource and an optional + * condition to further restrict permissions. + * @param additionalOptions **DEPRECATED, set this in the provided `authClient`.** + * Optional additional behavior customization options. + * @param quotaProjectId **DEPRECATED, set this in the provided `authClient`.** + * Optional quota project id for setting up in the x-goog-user-project header. + */ + constructor(authClient: AuthClient, credentialAccessBoundary: CredentialAccessBoundary, additionalOptions?: AuthClientOptions, quotaProjectId?: string); + /** + * Provides a mechanism to inject Downscoped access tokens directly. + * The expiry_date field is required to facilitate determination of the token + * expiration which would make it easier for the token consumer to handle. + * @param credentials The Credentials object to set on the current client. + */ + setCredentials(credentials: Credentials): void; + getAccessToken(): Promise; + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * The result has the form: + * { Authorization: 'Bearer ' } + */ + getRequestHeaders(): Promise; + /** + * Provides a request implementation with OAuth 2.0 flow. In cases of + * HTTP 401 and 403 responses, it automatically asks for a new access token + * and replays the unsuccessful request. + * @param opts Request options. + * @param callback callback. + * @return A promise that resolves with the HTTP response when no callback + * is provided. + */ + request(opts: GaxiosOptions): GaxiosPromise; + request(opts: GaxiosOptions, callback: BodyResponseCallback): void; + /** + * Authenticates the provided HTTP request, processes it and resolves with the + * returned response. + * @param opts The HTTP request options. + * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure + * @return A promise that resolves with the successful response. + */ + protected requestAsync(opts: GaxiosOptions, reAuthRetried?: boolean): Promise>; + /** + * Forces token refresh, even if unexpired tokens are currently cached. + * GCP access tokens are retrieved from authclient object/source credential. + * Then GCP access tokens are exchanged for downscoped access tokens via the + * token exchange endpoint. + * @return A promise that resolves with the fresh downscoped access token. + */ + protected refreshAccessTokenAsync(): Promise; + /** + * Returns whether the provided credentials are expired or not. + * If there is no expiry time, assumes the token is not expired or expiring. + * @param downscopedAccessToken The credentials to check for expiration. + * @return Whether the credentials are expired or not. + */ + private isExpired; +} +export {}; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/downscopedclient.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/downscopedclient.js new file mode 100644 index 0000000000000000000000000000000000000000..92529742681da872c3be14ff41b5f0d603301ea3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/downscopedclient.js @@ -0,0 +1,262 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DownscopedClient = exports.EXPIRATION_TIME_OFFSET = exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = void 0; +const stream = require("stream"); +const authclient_1 = require("./authclient"); +const sts = require("./stscredentials"); +/** + * The required token exchange grant_type: rfc8693#section-2.1 + */ +const STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange'; +/** + * The requested token exchange requested_token_type: rfc8693#section-2.1 + */ +const STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token'; +/** + * The requested token exchange subject_token_type: rfc8693#section-2.1 + */ +const STS_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token'; +/** + * The maximum number of access boundary rules a Credential Access Boundary + * can contain. + */ +exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = 10; +/** + * Offset to take into account network delays and server clock skews. + */ +exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000; +/** + * Defines a set of Google credentials that are downscoped from an existing set + * of Google OAuth2 credentials. This is useful to restrict the Identity and + * Access Management (IAM) permissions that a short-lived credential can use. + * The common pattern of usage is to have a token broker with elevated access + * generate these downscoped credentials from higher access source credentials + * and pass the downscoped short-lived access tokens to a token consumer via + * some secure authenticated channel for limited access to Google Cloud Storage + * resources. + */ +class DownscopedClient extends authclient_1.AuthClient { + /** + * Instantiates a downscoped client object using the provided source + * AuthClient and credential access boundary rules. + * To downscope permissions of a source AuthClient, a Credential Access + * Boundary that specifies which resources the new credential can access, as + * well as an upper bound on the permissions that are available on each + * resource, has to be defined. A downscoped client can then be instantiated + * using the source AuthClient and the Credential Access Boundary. + * @param authClient The source AuthClient to be downscoped based on the + * provided Credential Access Boundary rules. + * @param credentialAccessBoundary The Credential Access Boundary which + * contains a list of access boundary rules. Each rule contains information + * on the resource that the rule applies to, the upper bound of the + * permissions that are available on that resource and an optional + * condition to further restrict permissions. + * @param additionalOptions **DEPRECATED, set this in the provided `authClient`.** + * Optional additional behavior customization options. + * @param quotaProjectId **DEPRECATED, set this in the provided `authClient`.** + * Optional quota project id for setting up in the x-goog-user-project header. + */ + constructor(authClient, credentialAccessBoundary, additionalOptions, quotaProjectId) { + super({ ...additionalOptions, quotaProjectId }); + this.authClient = authClient; + this.credentialAccessBoundary = credentialAccessBoundary; + // Check 1-10 Access Boundary Rules are defined within Credential Access + // Boundary. + if (credentialAccessBoundary.accessBoundary.accessBoundaryRules.length === 0) { + throw new Error('At least one access boundary rule needs to be defined.'); + } + else if (credentialAccessBoundary.accessBoundary.accessBoundaryRules.length > + exports.MAX_ACCESS_BOUNDARY_RULES_COUNT) { + throw new Error('The provided access boundary has more than ' + + `${exports.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`); + } + // Check at least one permission should be defined in each Access Boundary + // Rule. + for (const rule of credentialAccessBoundary.accessBoundary + .accessBoundaryRules) { + if (rule.availablePermissions.length === 0) { + throw new Error('At least one permission should be defined in access boundary rules.'); + } + } + this.stsCredential = new sts.StsCredentials(`https://sts.${this.universeDomain}/v1/token`); + this.cachedDownscopedAccessToken = null; + } + /** + * Provides a mechanism to inject Downscoped access tokens directly. + * The expiry_date field is required to facilitate determination of the token + * expiration which would make it easier for the token consumer to handle. + * @param credentials The Credentials object to set on the current client. + */ + setCredentials(credentials) { + if (!credentials.expiry_date) { + throw new Error('The access token expiry_date field is missing in the provided ' + + 'credentials.'); + } + super.setCredentials(credentials); + this.cachedDownscopedAccessToken = credentials; + } + async getAccessToken() { + // If the cached access token is unavailable or expired, force refresh. + // The Downscoped access token will be returned in + // DownscopedAccessTokenResponse format. + if (!this.cachedDownscopedAccessToken || + this.isExpired(this.cachedDownscopedAccessToken)) { + await this.refreshAccessTokenAsync(); + } + // Return Downscoped access token in DownscopedAccessTokenResponse format. + return { + token: this.cachedDownscopedAccessToken.access_token, + expirationTime: this.cachedDownscopedAccessToken.expiry_date, + res: this.cachedDownscopedAccessToken.res, + }; + } + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * The result has the form: + * { Authorization: 'Bearer ' } + */ + async getRequestHeaders() { + const accessTokenResponse = await this.getAccessToken(); + const headers = { + Authorization: `Bearer ${accessTokenResponse.token}`, + }; + return this.addSharedMetadataHeaders(headers); + } + request(opts, callback) { + if (callback) { + this.requestAsync(opts).then(r => callback(null, r), e => { + return callback(e, e.response); + }); + } + else { + return this.requestAsync(opts); + } + } + /** + * Authenticates the provided HTTP request, processes it and resolves with the + * returned response. + * @param opts The HTTP request options. + * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure + * @return A promise that resolves with the successful response. + */ + async requestAsync(opts, reAuthRetried = false) { + let response; + try { + const requestHeaders = await this.getRequestHeaders(); + opts.headers = opts.headers || {}; + if (requestHeaders && requestHeaders['x-goog-user-project']) { + opts.headers['x-goog-user-project'] = + requestHeaders['x-goog-user-project']; + } + if (requestHeaders && requestHeaders.Authorization) { + opts.headers.Authorization = requestHeaders.Authorization; + } + response = await this.transporter.request(opts); + } + catch (e) { + const res = e.response; + if (res) { + const statusCode = res.status; + // Retry the request for metadata if the following criteria are true: + // - We haven't already retried. It only makes sense to retry once. + // - The response was a 401 or a 403 + // - The request didn't send a readableStream + // - forceRefreshOnFailure is true + const isReadableStream = res.config.data instanceof stream.Readable; + const isAuthErr = statusCode === 401 || statusCode === 403; + if (!reAuthRetried && + isAuthErr && + !isReadableStream && + this.forceRefreshOnFailure) { + await this.refreshAccessTokenAsync(); + return await this.requestAsync(opts, true); + } + } + throw e; + } + return response; + } + /** + * Forces token refresh, even if unexpired tokens are currently cached. + * GCP access tokens are retrieved from authclient object/source credential. + * Then GCP access tokens are exchanged for downscoped access tokens via the + * token exchange endpoint. + * @return A promise that resolves with the fresh downscoped access token. + */ + async refreshAccessTokenAsync() { + var _a; + // Retrieve GCP access token from source credential. + const subjectToken = (await this.authClient.getAccessToken()).token; + // Construct the STS credentials options. + const stsCredentialsOptions = { + grantType: STS_GRANT_TYPE, + requestedTokenType: STS_REQUEST_TOKEN_TYPE, + subjectToken: subjectToken, + subjectTokenType: STS_SUBJECT_TOKEN_TYPE, + }; + // Exchange the source AuthClient access token for a Downscoped access + // token. + const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, undefined, this.credentialAccessBoundary); + /** + * The STS endpoint will only return the expiration time for the downscoped + * access token if the original access token represents a service account. + * The downscoped token's expiration time will always match the source + * credential expiration. When no expires_in is returned, we can copy the + * source credential's expiration time. + */ + const sourceCredExpireDate = ((_a = this.authClient.credentials) === null || _a === void 0 ? void 0 : _a.expiry_date) || null; + const expiryDate = stsResponse.expires_in + ? new Date().getTime() + stsResponse.expires_in * 1000 + : sourceCredExpireDate; + // Save response in cached access token. + this.cachedDownscopedAccessToken = { + access_token: stsResponse.access_token, + expiry_date: expiryDate, + res: stsResponse.res, + }; + // Save credentials. + this.credentials = {}; + Object.assign(this.credentials, this.cachedDownscopedAccessToken); + delete this.credentials.res; + // Trigger tokens event to notify external listeners. + this.emit('tokens', { + refresh_token: null, + expiry_date: this.cachedDownscopedAccessToken.expiry_date, + access_token: this.cachedDownscopedAccessToken.access_token, + token_type: 'Bearer', + id_token: null, + }); + // Return the cached access token. + return this.cachedDownscopedAccessToken; + } + /** + * Returns whether the provided credentials are expired or not. + * If there is no expiry time, assumes the token is not expired or expiring. + * @param downscopedAccessToken The credentials to check for expiration. + * @return Whether the credentials are expired or not. + */ + isExpired(downscopedAccessToken) { + const now = new Date().getTime(); + return downscopedAccessToken.expiry_date + ? now >= + downscopedAccessToken.expiry_date - this.eagerRefreshThresholdMillis + : false; + } +} +exports.DownscopedClient = DownscopedClient; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/envDetect.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/envDetect.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2fc01c6d7c24f53d7f21d5e5fa5c5807a4d09bf9 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/envDetect.d.ts @@ -0,0 +1,10 @@ +export declare enum GCPEnv { + APP_ENGINE = "APP_ENGINE", + KUBERNETES_ENGINE = "KUBERNETES_ENGINE", + CLOUD_FUNCTIONS = "CLOUD_FUNCTIONS", + COMPUTE_ENGINE = "COMPUTE_ENGINE", + CLOUD_RUN = "CLOUD_RUN", + NONE = "NONE" +} +export declare function clear(): void; +export declare function getEnv(): Promise; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/envDetect.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/envDetect.js new file mode 100644 index 0000000000000000000000000000000000000000..73fb915c5b202c8898898db17da60595002a78c1 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/envDetect.js @@ -0,0 +1,89 @@ +"use strict"; +// Copyright 2018 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GCPEnv = void 0; +exports.clear = clear; +exports.getEnv = getEnv; +const gcpMetadata = require("gcp-metadata"); +var GCPEnv; +(function (GCPEnv) { + GCPEnv["APP_ENGINE"] = "APP_ENGINE"; + GCPEnv["KUBERNETES_ENGINE"] = "KUBERNETES_ENGINE"; + GCPEnv["CLOUD_FUNCTIONS"] = "CLOUD_FUNCTIONS"; + GCPEnv["COMPUTE_ENGINE"] = "COMPUTE_ENGINE"; + GCPEnv["CLOUD_RUN"] = "CLOUD_RUN"; + GCPEnv["NONE"] = "NONE"; +})(GCPEnv || (exports.GCPEnv = GCPEnv = {})); +let envPromise; +function clear() { + envPromise = undefined; +} +async function getEnv() { + if (envPromise) { + return envPromise; + } + envPromise = getEnvMemoized(); + return envPromise; +} +async function getEnvMemoized() { + let env = GCPEnv.NONE; + if (isAppEngine()) { + env = GCPEnv.APP_ENGINE; + } + else if (isCloudFunction()) { + env = GCPEnv.CLOUD_FUNCTIONS; + } + else if (await isComputeEngine()) { + if (await isKubernetesEngine()) { + env = GCPEnv.KUBERNETES_ENGINE; + } + else if (isCloudRun()) { + env = GCPEnv.CLOUD_RUN; + } + else { + env = GCPEnv.COMPUTE_ENGINE; + } + } + else { + env = GCPEnv.NONE; + } + return env; +} +function isAppEngine() { + return !!(process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME); +} +function isCloudFunction() { + return !!(process.env.FUNCTION_NAME || process.env.FUNCTION_TARGET); +} +/** + * This check only verifies that the environment is running knative. + * This must be run *after* checking for Kubernetes, otherwise it will + * return a false positive. + */ +function isCloudRun() { + return !!process.env.K_CONFIGURATION; +} +async function isKubernetesEngine() { + try { + await gcpMetadata.instance('attributes/cluster-name'); + return true; + } + catch (e) { + return false; + } +} +async function isComputeEngine() { + return gcpMetadata.isAvailable(); +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/executable-response.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/executable-response.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..259d276940a262600152c5ff565c76df0b5ee77a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/executable-response.d.ts @@ -0,0 +1,137 @@ +/** + * Interface defining the JSON formatted response of a 3rd party executable + * used by the pluggable auth client. + */ +export interface ExecutableResponseJson { + /** + * The version of the JSON response. Only version 1 is currently supported. + * Always required. + */ + version: number; + /** + * Whether the executable ran successfully. Always required. + */ + success: boolean; + /** + * The epoch time for expiration of the token in seconds, required for + * successful responses. + */ + expiration_time?: number; + /** + * The type of subject token in the response, currently supported values are: + * urn:ietf:params:oauth:token-type:saml2 + * urn:ietf:params:oauth:token-type:id_token + * urn:ietf:params:oauth:token-type:jwt + */ + token_type?: string; + /** + * The error code from the executable, required when unsuccessful. + */ + code?: string; + /** + * The error message from the executable, required when unsuccessful. + */ + message?: string; + /** + * The ID token to be used as a subject token when token_type is id_token or jwt. + */ + id_token?: string; + /** + * The response to be used as a subject token when token_type is saml2. + */ + saml_response?: string; +} +/** + * Defines the response of a 3rd party executable run by the pluggable auth client. + */ +export declare class ExecutableResponse { + /** + * The version of the Executable response. Only version 1 is currently supported. + */ + readonly version: number; + /** + * Whether the executable ran successfully. + */ + readonly success: boolean; + /** + * The epoch time for expiration of the token in seconds. + */ + readonly expirationTime?: number; + /** + * The type of subject token in the response, currently supported values are: + * urn:ietf:params:oauth:token-type:saml2 + * urn:ietf:params:oauth:token-type:id_token + * urn:ietf:params:oauth:token-type:jwt + */ + readonly tokenType?: string; + /** + * The error code from the executable. + */ + readonly errorCode?: string; + /** + * The error message from the executable. + */ + readonly errorMessage?: string; + /** + * The subject token from the executable, format depends on tokenType. + */ + readonly subjectToken?: string; + /** + * Instantiates an ExecutableResponse instance using the provided JSON object + * from the output of the executable. + * @param responseJson Response from a 3rd party executable, loaded from a + * run of the executable or a cached output file. + */ + constructor(responseJson: ExecutableResponseJson); + /** + * @return A boolean representing if the response has a valid token. Returns + * true when the response was successful and the token is not expired. + */ + isValid(): boolean; + /** + * @return A boolean representing if the response is expired. Returns true if the + * provided timeout has passed. + */ + isExpired(): boolean; +} +/** + * An error thrown by the ExecutableResponse class. + */ +export declare class ExecutableResponseError extends Error { + constructor(message: string); +} +/** + * An error thrown when the 'version' field in an executable response is missing or invalid. + */ +export declare class InvalidVersionFieldError extends ExecutableResponseError { +} +/** + * An error thrown when the 'success' field in an executable response is missing or invalid. + */ +export declare class InvalidSuccessFieldError extends ExecutableResponseError { +} +/** + * An error thrown when the 'expiration_time' field in an executable response is missing or invalid. + */ +export declare class InvalidExpirationTimeFieldError extends ExecutableResponseError { +} +/** + * An error thrown when the 'token_type' field in an executable response is missing or invalid. + */ +export declare class InvalidTokenTypeFieldError extends ExecutableResponseError { +} +/** + * An error thrown when the 'code' field in an executable response is missing or invalid. + */ +export declare class InvalidCodeFieldError extends ExecutableResponseError { +} +/** + * An error thrown when the 'message' field in an executable response is missing or invalid. + */ +export declare class InvalidMessageFieldError extends ExecutableResponseError { +} +/** + * An error thrown when the subject token in an executable response is missing or invalid. + */ +export declare class InvalidSubjectTokenError extends ExecutableResponseError { +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/executable-response.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/executable-response.js new file mode 100644 index 0000000000000000000000000000000000000000..be4e818c37e917a1bde771d587bf68dbb05e36e4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/executable-response.js @@ -0,0 +1,146 @@ +"use strict"; +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InvalidSubjectTokenError = exports.InvalidMessageFieldError = exports.InvalidCodeFieldError = exports.InvalidTokenTypeFieldError = exports.InvalidExpirationTimeFieldError = exports.InvalidSuccessFieldError = exports.InvalidVersionFieldError = exports.ExecutableResponseError = exports.ExecutableResponse = void 0; +const SAML_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:saml2'; +const OIDC_SUBJECT_TOKEN_TYPE1 = 'urn:ietf:params:oauth:token-type:id_token'; +const OIDC_SUBJECT_TOKEN_TYPE2 = 'urn:ietf:params:oauth:token-type:jwt'; +/** + * Defines the response of a 3rd party executable run by the pluggable auth client. + */ +class ExecutableResponse { + /** + * Instantiates an ExecutableResponse instance using the provided JSON object + * from the output of the executable. + * @param responseJson Response from a 3rd party executable, loaded from a + * run of the executable or a cached output file. + */ + constructor(responseJson) { + // Check that the required fields exist in the json response. + if (!responseJson.version) { + throw new InvalidVersionFieldError("Executable response must contain a 'version' field."); + } + if (responseJson.success === undefined) { + throw new InvalidSuccessFieldError("Executable response must contain a 'success' field."); + } + this.version = responseJson.version; + this.success = responseJson.success; + // Validate required fields for a successful response. + if (this.success) { + this.expirationTime = responseJson.expiration_time; + this.tokenType = responseJson.token_type; + // Validate token type field. + if (this.tokenType !== SAML_SUBJECT_TOKEN_TYPE && + this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE1 && + this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE2) { + throw new InvalidTokenTypeFieldError("Executable response must contain a 'token_type' field when successful " + + `and it must be one of ${OIDC_SUBJECT_TOKEN_TYPE1}, ${OIDC_SUBJECT_TOKEN_TYPE2}, or ${SAML_SUBJECT_TOKEN_TYPE}.`); + } + // Validate subject token. + if (this.tokenType === SAML_SUBJECT_TOKEN_TYPE) { + if (!responseJson.saml_response) { + throw new InvalidSubjectTokenError(`Executable response must contain a 'saml_response' field when token_type=${SAML_SUBJECT_TOKEN_TYPE}.`); + } + this.subjectToken = responseJson.saml_response; + } + else { + if (!responseJson.id_token) { + throw new InvalidSubjectTokenError("Executable response must contain a 'id_token' field when " + + `token_type=${OIDC_SUBJECT_TOKEN_TYPE1} or ${OIDC_SUBJECT_TOKEN_TYPE2}.`); + } + this.subjectToken = responseJson.id_token; + } + } + else { + // Both code and message must be provided for unsuccessful responses. + if (!responseJson.code) { + throw new InvalidCodeFieldError("Executable response must contain a 'code' field when unsuccessful."); + } + if (!responseJson.message) { + throw new InvalidMessageFieldError("Executable response must contain a 'message' field when unsuccessful."); + } + this.errorCode = responseJson.code; + this.errorMessage = responseJson.message; + } + } + /** + * @return A boolean representing if the response has a valid token. Returns + * true when the response was successful and the token is not expired. + */ + isValid() { + return !this.isExpired() && this.success; + } + /** + * @return A boolean representing if the response is expired. Returns true if the + * provided timeout has passed. + */ + isExpired() { + return (this.expirationTime !== undefined && + this.expirationTime < Math.round(Date.now() / 1000)); + } +} +exports.ExecutableResponse = ExecutableResponse; +/** + * An error thrown by the ExecutableResponse class. + */ +class ExecutableResponseError extends Error { + constructor(message) { + super(message); + Object.setPrototypeOf(this, new.target.prototype); + } +} +exports.ExecutableResponseError = ExecutableResponseError; +/** + * An error thrown when the 'version' field in an executable response is missing or invalid. + */ +class InvalidVersionFieldError extends ExecutableResponseError { +} +exports.InvalidVersionFieldError = InvalidVersionFieldError; +/** + * An error thrown when the 'success' field in an executable response is missing or invalid. + */ +class InvalidSuccessFieldError extends ExecutableResponseError { +} +exports.InvalidSuccessFieldError = InvalidSuccessFieldError; +/** + * An error thrown when the 'expiration_time' field in an executable response is missing or invalid. + */ +class InvalidExpirationTimeFieldError extends ExecutableResponseError { +} +exports.InvalidExpirationTimeFieldError = InvalidExpirationTimeFieldError; +/** + * An error thrown when the 'token_type' field in an executable response is missing or invalid. + */ +class InvalidTokenTypeFieldError extends ExecutableResponseError { +} +exports.InvalidTokenTypeFieldError = InvalidTokenTypeFieldError; +/** + * An error thrown when the 'code' field in an executable response is missing or invalid. + */ +class InvalidCodeFieldError extends ExecutableResponseError { +} +exports.InvalidCodeFieldError = InvalidCodeFieldError; +/** + * An error thrown when the 'message' field in an executable response is missing or invalid. + */ +class InvalidMessageFieldError extends ExecutableResponseError { +} +exports.InvalidMessageFieldError = InvalidMessageFieldError; +/** + * An error thrown when the subject token in an executable response is missing or invalid. + */ +class InvalidSubjectTokenError extends ExecutableResponseError { +} +exports.InvalidSubjectTokenError = InvalidSubjectTokenError; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1707debe4951b76cf5d1bfd2aee070cafe115cca --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.d.ts @@ -0,0 +1,78 @@ +import { AuthClient, AuthClientOptions } from './authclient'; +import { Headers } from './oauth2client'; +import { BodyResponseCallback } from '../transporters'; +import { GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +import { Credentials } from './credentials'; +import { SharedExternalAccountClientOptions } from './baseexternalclient'; +/** + * The credentials JSON file type for external account authorized user clients. + */ +export declare const EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = "external_account_authorized_user"; +/** + * External Account Authorized User Credentials JSON interface. + */ +export interface ExternalAccountAuthorizedUserClientOptions extends SharedExternalAccountClientOptions { + type: typeof EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE; + client_id: string; + client_secret: string; + refresh_token: string; + token_info_url: string; + revoke_url?: string; +} +/** + * Internal interface for tracking the access token expiration time. + */ +interface CredentialsWithResponse extends Credentials { + res?: GaxiosResponse | null; +} +/** + * External Account Authorized User Client. This is used for OAuth2 credentials + * sourced using external identities through Workforce Identity Federation. + * Obtaining the initial access and refresh token can be done through the + * Google Cloud CLI. + */ +export declare class ExternalAccountAuthorizedUserClient extends AuthClient { + private cachedAccessToken; + private readonly externalAccountAuthorizedUserHandler; + private refreshToken; + /** + * Instantiates an ExternalAccountAuthorizedUserClient instances using the + * provided JSON object loaded from a credentials files. + * An error is throws if the credential is not valid. + * @param options The external account authorized user option object typically + * from the external accoutn authorized user JSON credential file. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options: ExternalAccountAuthorizedUserClientOptions, additionalOptions?: AuthClientOptions); + getAccessToken(): Promise<{ + token?: string | null; + res?: GaxiosResponse | null; + }>; + getRequestHeaders(): Promise; + request(opts: GaxiosOptions): GaxiosPromise; + request(opts: GaxiosOptions, callback: BodyResponseCallback): void; + /** + * Authenticates the provided HTTP request, processes it and resolves with the + * returned response. + * @param opts The HTTP request options. + * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure. + * @return A promise that resolves with the successful response. + */ + protected requestAsync(opts: GaxiosOptions, reAuthRetried?: boolean): Promise>; + /** + * Forces token refresh, even if unexpired tokens are currently cached. + * @return A promise that resolves with the refreshed credential. + */ + protected refreshAccessTokenAsync(): Promise; + /** + * Returns whether the provided credentials are expired or not. + * If there is no expiry time, assumes the token is not expired or expiring. + * @param credentials The credentials to check for expiration. + * @return Whether the credentials are expired or not. + */ + private isExpired; +} +export {}; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js new file mode 100644 index 0000000000000000000000000000000000000000..b7147a3d0421476923a227ad7f9366466fb3b8ba --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js @@ -0,0 +1,239 @@ +"use strict"; +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ExternalAccountAuthorizedUserClient = exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = void 0; +const authclient_1 = require("./authclient"); +const oauth2common_1 = require("./oauth2common"); +const gaxios_1 = require("gaxios"); +const stream = require("stream"); +const baseexternalclient_1 = require("./baseexternalclient"); +/** + * The credentials JSON file type for external account authorized user clients. + */ +exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = 'external_account_authorized_user'; +const DEFAULT_TOKEN_URL = 'https://sts.{universeDomain}/v1/oauthtoken'; +/** + * Handler for token refresh requests sent to the token_url endpoint for external + * authorized user credentials. + */ +class ExternalAccountAuthorizedUserHandler extends oauth2common_1.OAuthClientAuthHandler { + /** + * Initializes an ExternalAccountAuthorizedUserHandler instance. + * @param url The URL of the token refresh endpoint. + * @param transporter The transporter to use for the refresh request. + * @param clientAuthentication The client authentication credentials to use + * for the refresh request. + */ + constructor(url, transporter, clientAuthentication) { + super(clientAuthentication); + this.url = url; + this.transporter = transporter; + } + /** + * Requests a new access token from the token_url endpoint using the provided + * refresh token. + * @param refreshToken The refresh token to use to generate a new access token. + * @param additionalHeaders Optional additional headers to pass along the + * request. + * @return A promise that resolves with the token refresh response containing + * the requested access token and its expiration time. + */ + async refreshToken(refreshToken, additionalHeaders) { + const values = new URLSearchParams({ + grant_type: 'refresh_token', + refresh_token: refreshToken, + }); + const headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + ...additionalHeaders, + }; + const opts = { + ...ExternalAccountAuthorizedUserHandler.RETRY_CONFIG, + url: this.url, + method: 'POST', + headers, + data: values.toString(), + responseType: 'json', + }; + // Apply OAuth client authentication. + this.applyClientAuthenticationOptions(opts); + try { + const response = await this.transporter.request(opts); + // Successful response. + const tokenRefreshResponse = response.data; + tokenRefreshResponse.res = response; + return tokenRefreshResponse; + } + catch (error) { + // Translate error to OAuthError. + if (error instanceof gaxios_1.GaxiosError && error.response) { + throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, + // Preserve other fields from the original error. + error); + } + // Request could fail before the server responds. + throw error; + } + } +} +/** + * External Account Authorized User Client. This is used for OAuth2 credentials + * sourced using external identities through Workforce Identity Federation. + * Obtaining the initial access and refresh token can be done through the + * Google Cloud CLI. + */ +class ExternalAccountAuthorizedUserClient extends authclient_1.AuthClient { + /** + * Instantiates an ExternalAccountAuthorizedUserClient instances using the + * provided JSON object loaded from a credentials files. + * An error is throws if the credential is not valid. + * @param options The external account authorized user option object typically + * from the external accoutn authorized user JSON credential file. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options, additionalOptions) { + var _a; + super({ ...options, ...additionalOptions }); + if (options.universe_domain) { + this.universeDomain = options.universe_domain; + } + this.refreshToken = options.refresh_token; + const clientAuth = { + confidentialClientType: 'basic', + clientId: options.client_id, + clientSecret: options.client_secret, + }; + this.externalAccountAuthorizedUserHandler = + new ExternalAccountAuthorizedUserHandler((_a = options.token_url) !== null && _a !== void 0 ? _a : DEFAULT_TOKEN_URL.replace('{universeDomain}', this.universeDomain), this.transporter, clientAuth); + this.cachedAccessToken = null; + this.quotaProjectId = options.quota_project_id; + // As threshold could be zero, + // eagerRefreshThresholdMillis || EXPIRATION_TIME_OFFSET will override the + // zero value. + if (typeof (additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.eagerRefreshThresholdMillis) !== 'number') { + this.eagerRefreshThresholdMillis = baseexternalclient_1.EXPIRATION_TIME_OFFSET; + } + else { + this.eagerRefreshThresholdMillis = additionalOptions + .eagerRefreshThresholdMillis; + } + this.forceRefreshOnFailure = !!(additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.forceRefreshOnFailure); + } + async getAccessToken() { + // If cached access token is unavailable or expired, force refresh. + if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) { + await this.refreshAccessTokenAsync(); + } + // Return GCP access token in GetAccessTokenResponse format. + return { + token: this.cachedAccessToken.access_token, + res: this.cachedAccessToken.res, + }; + } + async getRequestHeaders() { + const accessTokenResponse = await this.getAccessToken(); + const headers = { + Authorization: `Bearer ${accessTokenResponse.token}`, + }; + return this.addSharedMetadataHeaders(headers); + } + request(opts, callback) { + if (callback) { + this.requestAsync(opts).then(r => callback(null, r), e => { + return callback(e, e.response); + }); + } + else { + return this.requestAsync(opts); + } + } + /** + * Authenticates the provided HTTP request, processes it and resolves with the + * returned response. + * @param opts The HTTP request options. + * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure. + * @return A promise that resolves with the successful response. + */ + async requestAsync(opts, reAuthRetried = false) { + let response; + try { + const requestHeaders = await this.getRequestHeaders(); + opts.headers = opts.headers || {}; + if (requestHeaders && requestHeaders['x-goog-user-project']) { + opts.headers['x-goog-user-project'] = + requestHeaders['x-goog-user-project']; + } + if (requestHeaders && requestHeaders.Authorization) { + opts.headers.Authorization = requestHeaders.Authorization; + } + response = await this.transporter.request(opts); + } + catch (e) { + const res = e.response; + if (res) { + const statusCode = res.status; + // Retry the request for metadata if the following criteria are true: + // - We haven't already retried. It only makes sense to retry once. + // - The response was a 401 or a 403 + // - The request didn't send a readableStream + // - forceRefreshOnFailure is true + const isReadableStream = res.config.data instanceof stream.Readable; + const isAuthErr = statusCode === 401 || statusCode === 403; + if (!reAuthRetried && + isAuthErr && + !isReadableStream && + this.forceRefreshOnFailure) { + await this.refreshAccessTokenAsync(); + return await this.requestAsync(opts, true); + } + } + throw e; + } + return response; + } + /** + * Forces token refresh, even if unexpired tokens are currently cached. + * @return A promise that resolves with the refreshed credential. + */ + async refreshAccessTokenAsync() { + // Refresh the access token using the refresh token. + const refreshResponse = await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken); + this.cachedAccessToken = { + access_token: refreshResponse.access_token, + expiry_date: new Date().getTime() + refreshResponse.expires_in * 1000, + res: refreshResponse.res, + }; + if (refreshResponse.refresh_token !== undefined) { + this.refreshToken = refreshResponse.refresh_token; + } + return this.cachedAccessToken; + } + /** + * Returns whether the provided credentials are expired or not. + * If there is no expiry time, assumes the token is not expired or expiring. + * @param credentials The credentials to check for expiration. + * @return Whether the credentials are expired or not. + */ + isExpired(credentials) { + const now = new Date().getTime(); + return credentials.expiry_date + ? now >= credentials.expiry_date - this.eagerRefreshThresholdMillis + : false; + } +} +exports.ExternalAccountAuthorizedUserClient = ExternalAccountAuthorizedUserClient; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/externalclient.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/externalclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..90caac546f598f0148954fe69372bc4fde98609c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/externalclient.d.ts @@ -0,0 +1,26 @@ +import { BaseExternalAccountClient } from './baseexternalclient'; +import { IdentityPoolClientOptions } from './identitypoolclient'; +import { AwsClientOptions } from './awsclient'; +import { PluggableAuthClientOptions } from './pluggable-auth-client'; +import { AuthClientOptions } from './authclient'; +export type ExternalAccountClientOptions = IdentityPoolClientOptions | AwsClientOptions | PluggableAuthClientOptions; +/** + * Dummy class with no constructor. Developers are expected to use fromJSON. + */ +export declare class ExternalAccountClient { + constructor(); + /** + * This static method will instantiate the + * corresponding type of external account credential depending on the + * underlying credential source. + * @param options The external account options object typically loaded + * from the external account JSON credential file. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + * @return A BaseExternalAccountClient instance or null if the options + * provided do not correspond to an external account credential. + */ + static fromJSON(options: ExternalAccountClientOptions, additionalOptions?: AuthClientOptions): BaseExternalAccountClient | null; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/externalclient.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/externalclient.js new file mode 100644 index 0000000000000000000000000000000000000000..54860ead367e2f018f4bfb886f24dfa170d09e0c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/externalclient.js @@ -0,0 +1,64 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ExternalAccountClient = void 0; +const baseexternalclient_1 = require("./baseexternalclient"); +const identitypoolclient_1 = require("./identitypoolclient"); +const awsclient_1 = require("./awsclient"); +const pluggable_auth_client_1 = require("./pluggable-auth-client"); +/** + * Dummy class with no constructor. Developers are expected to use fromJSON. + */ +class ExternalAccountClient { + constructor() { + throw new Error('ExternalAccountClients should be initialized via: ' + + 'ExternalAccountClient.fromJSON(), ' + + 'directly via explicit constructors, eg. ' + + 'new AwsClient(options), new IdentityPoolClient(options), new' + + 'PluggableAuthClientOptions, or via ' + + 'new GoogleAuth(options).getClient()'); + } + /** + * This static method will instantiate the + * corresponding type of external account credential depending on the + * underlying credential source. + * @param options The external account options object typically loaded + * from the external account JSON credential file. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + * @return A BaseExternalAccountClient instance or null if the options + * provided do not correspond to an external account credential. + */ + static fromJSON(options, additionalOptions) { + var _a, _b; + if (options && options.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { + if ((_a = options.credential_source) === null || _a === void 0 ? void 0 : _a.environment_id) { + return new awsclient_1.AwsClient(options, additionalOptions); + } + else if ((_b = options.credential_source) === null || _b === void 0 ? void 0 : _b.executable) { + return new pluggable_auth_client_1.PluggableAuthClient(options, additionalOptions); + } + else { + return new identitypoolclient_1.IdentityPoolClient(options, additionalOptions); + } + } + else { + return null; + } + } +} +exports.ExternalAccountClient = ExternalAccountClient; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7a67d4077139bc7cb3988cc3c7756b8e9bfc7012 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.d.ts @@ -0,0 +1,42 @@ +import { ExternalAccountSupplierContext } from './baseexternalclient'; +import { SubjectTokenFormatType, SubjectTokenSupplier } from './identitypoolclient'; +/** + * Interface that defines options used to build a {@link FileSubjectTokenSupplier} + */ +export interface FileSubjectTokenSupplierOptions { + /** + * The file path where the external credential is located. + */ + filePath: string; + /** + * The token file or URL response type (JSON or text). + */ + formatType: SubjectTokenFormatType; + /** + * For JSON response types, this is the subject_token field name. For Azure, + * this is access_token. For text response types, this is ignored. + */ + subjectTokenFieldName?: string; +} +/** + * Internal subject token supplier implementation used when a file location + * is configured in the credential configuration used to build an {@link IdentityPoolClient} + */ +export declare class FileSubjectTokenSupplier implements SubjectTokenSupplier { + private readonly filePath; + private readonly formatType; + private readonly subjectTokenFieldName?; + /** + * Instantiates a new file based subject token supplier. + * @param opts The file subject token supplier options to build the supplier + * with. + */ + constructor(opts: FileSubjectTokenSupplierOptions); + /** + * Returns the subject token stored at the file specified in the constructor. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link IdentityPoolClient}, contains the requested audience and subject + * token type for the external account identity. Not used. + */ + getSubjectToken(context: ExternalAccountSupplierContext): Promise; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js new file mode 100644 index 0000000000000000000000000000000000000000..abf9bed14a3bfd107877e15bfc8b88d3fc1472fa --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js @@ -0,0 +1,81 @@ +"use strict"; +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var _a, _b, _c; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FileSubjectTokenSupplier = void 0; +const util_1 = require("util"); +const fs = require("fs"); +// fs.readfile is undefined in browser karma tests causing +// `npm run browser-test` to fail as test.oauth2.ts imports this file via +// src/index.ts. +// Fallback to void function to avoid promisify throwing a TypeError. +const readFile = (0, util_1.promisify)((_a = fs.readFile) !== null && _a !== void 0 ? _a : (() => { })); +const realpath = (0, util_1.promisify)((_b = fs.realpath) !== null && _b !== void 0 ? _b : (() => { })); +const lstat = (0, util_1.promisify)((_c = fs.lstat) !== null && _c !== void 0 ? _c : (() => { })); +/** + * Internal subject token supplier implementation used when a file location + * is configured in the credential configuration used to build an {@link IdentityPoolClient} + */ +class FileSubjectTokenSupplier { + /** + * Instantiates a new file based subject token supplier. + * @param opts The file subject token supplier options to build the supplier + * with. + */ + constructor(opts) { + this.filePath = opts.filePath; + this.formatType = opts.formatType; + this.subjectTokenFieldName = opts.subjectTokenFieldName; + } + /** + * Returns the subject token stored at the file specified in the constructor. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link IdentityPoolClient}, contains the requested audience and subject + * token type for the external account identity. Not used. + */ + async getSubjectToken(context) { + // Make sure there is a file at the path. lstatSync will throw if there is + // nothing there. + let parsedFilePath = this.filePath; + try { + // Resolve path to actual file in case of symlink. Expect a thrown error + // if not resolvable. + parsedFilePath = await realpath(parsedFilePath); + if (!(await lstat(parsedFilePath)).isFile()) { + throw new Error(); + } + } + catch (err) { + if (err instanceof Error) { + err.message = `The file at ${parsedFilePath} does not exist, or it is not a file. ${err.message}`; + } + throw err; + } + let subjectToken; + const rawText = await readFile(parsedFilePath, { encoding: 'utf8' }); + if (this.formatType === 'text') { + subjectToken = rawText; + } + else if (this.formatType === 'json' && this.subjectTokenFieldName) { + const json = JSON.parse(rawText); + subjectToken = json[this.subjectTokenFieldName]; + } + if (!subjectToken) { + throw new Error('Unable to parse the subject_token from the credential_source file'); + } + return subjectToken; + } +} +exports.FileSubjectTokenSupplier = FileSubjectTokenSupplier; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/googleauth.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/googleauth.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..099c280b39318a10d12ba8f48170a91fbba249b1 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/googleauth.d.ts @@ -0,0 +1,375 @@ +import { GaxiosOptions, GaxiosResponse } from 'gaxios'; +import * as stream from 'stream'; +import { DefaultTransporter, Transporter } from '../transporters'; +import { CredentialBody, ImpersonatedJWTInput, JWTInput } from './credentials'; +import { IdTokenClient } from './idtokenclient'; +import { GCPEnv } from './envDetect'; +import { JWT, JWTOptions } from './jwtclient'; +import { Headers, OAuth2ClientOptions } from './oauth2client'; +import { UserRefreshClient, UserRefreshClientOptions } from './refreshclient'; +import { Impersonated, ImpersonatedOptions } from './impersonated'; +import { ExternalAccountClientOptions } from './externalclient'; +import { BaseExternalAccountClient } from './baseexternalclient'; +import { AuthClient, AuthClientOptions } from './authclient'; +import { ExternalAccountAuthorizedUserClient } from './externalAccountAuthorizedUserClient'; +import { AnyAuthClient } from '..'; +/** + * Defines all types of explicit clients that are determined via ADC JSON + * config file. + */ +export type JSONClient = JWT | UserRefreshClient | BaseExternalAccountClient | ExternalAccountAuthorizedUserClient | Impersonated; +export interface ProjectIdCallback { + (err?: Error | null, projectId?: string | null): void; +} +export interface CredentialCallback { + (err: Error | null, result?: JSONClient): void; +} +export interface ADCCallback { + (err: Error | null, credential?: AuthClient, projectId?: string | null): void; +} +export interface ADCResponse { + credential: AuthClient; + projectId: string | null; +} +export interface GoogleAuthOptions { + /** + * An API key to use, optional. Cannot be used with {@link GoogleAuthOptions.credentials `credentials`}. + */ + apiKey?: string; + /** + * An `AuthClient` to use + */ + authClient?: T; + /** + * Path to a .json, .pem, or .p12 key file + */ + keyFilename?: string; + /** + * Path to a .json, .pem, or .p12 key file + */ + keyFile?: string; + /** + * Object containing client_email and private_key properties, or the + * external account client options. + * Cannot be used with {@link GoogleAuthOptions.apiKey `apiKey`}. + * + * @remarks + * + * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}. + */ + credentials?: JWTInput | ExternalAccountClientOptions; + /** + * Options object passed to the constructor of the client + */ + clientOptions?: JWTOptions | OAuth2ClientOptions | UserRefreshClientOptions | ImpersonatedOptions; + /** + * Required scopes for the desired API request + */ + scopes?: string | string[]; + /** + * Your project ID. + */ + projectId?: string; + /** + * The default service domain for a given Cloud universe. + * + * This is an ergonomic equivalent to {@link clientOptions}'s `universeDomain` + * property and will be set for all generated {@link AuthClient}s. + */ + universeDomain?: string; +} +export declare const CLOUD_SDK_CLIENT_ID = "764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com"; +export declare const GoogleAuthExceptionMessages: { + readonly API_KEY_WITH_CREDENTIALS: "API Keys and Credentials are mutually exclusive authentication methods and cannot be used together."; + readonly NO_PROJECT_ID_FOUND: string; + readonly NO_CREDENTIALS_FOUND: string; + readonly NO_ADC_FOUND: "Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information."; + readonly NO_UNIVERSE_DOMAIN_FOUND: string; +}; +export declare class GoogleAuth { + #private; + transporter?: Transporter; + /** + * Caches a value indicating whether the auth layer is running on Google + * Compute Engine. + * @private + */ + private checkIsGCE?; + useJWTAccessWithScope?: boolean; + defaultServicePath?: string; + get isGCE(): boolean | undefined; + private _findProjectIdPromise?; + private _cachedProjectId?; + jsonContent: JWTInput | ExternalAccountClientOptions | null; + apiKey: string | null; + cachedCredential: AnyAuthClient | T | null; + /** + * Scopes populated by the client library by default. We differentiate between + * these and user defined scopes when deciding whether to use a self-signed JWT. + */ + defaultScopes?: string | string[]; + private keyFilename?; + private scopes?; + private clientOptions; + /** + * Export DefaultTransporter as a static property of the class. + */ + static DefaultTransporter: typeof DefaultTransporter; + /** + * Configuration is resolved in the following order of precedence: + * - {@link GoogleAuthOptions.credentials `credentials`} + * - {@link GoogleAuthOptions.keyFilename `keyFilename`} + * - {@link GoogleAuthOptions.keyFile `keyFile`} + * + * {@link GoogleAuthOptions.clientOptions `clientOptions`} are passed to the + * {@link AuthClient `AuthClient`s}. + * + * @param opts + */ + constructor(opts?: GoogleAuthOptions); + setGapicJWTValues(client: JWT): void; + /** + * Obtains the default project ID for the application. + * + * Retrieves in the following order of precedence: + * - The `projectId` provided in this object's construction + * - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable + * - GOOGLE_APPLICATION_CREDENTIALS JSON file + * - Cloud SDK: `gcloud config config-helper --format json` + * - GCE project ID from metadata server + */ + getProjectId(): Promise; + getProjectId(callback: ProjectIdCallback): void; + /** + * A temporary method for internal `getProjectId` usages where `null` is + * acceptable. In a future major release, `getProjectId` should return `null` + * (as the `Promise` base signature describes) and this private + * method should be removed. + * + * @returns Promise that resolves with project id (or `null`) + */ + private getProjectIdOptional; + /** + * A private method for finding and caching a projectId. + * + * Supports environments in order of precedence: + * - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable + * - GOOGLE_APPLICATION_CREDENTIALS JSON file + * - Cloud SDK: `gcloud config config-helper --format json` + * - GCE project ID from metadata server + * + * @returns projectId + */ + private findAndCacheProjectId; + private getProjectIdAsync; + /** + * Retrieves a universe domain from the metadata server via + * {@link gcpMetadata.universe}. + * + * @returns a universe domain + */ + getUniverseDomainFromMetadataServer(): Promise; + /** + * Retrieves, caches, and returns the universe domain in the following order + * of precedence: + * - The universe domain in {@link GoogleAuth.clientOptions} + * - An existing or ADC {@link AuthClient}'s universe domain + * - {@link gcpMetadata.universe}, if {@link Compute} client + * + * @returns The universe domain + */ + getUniverseDomain(): Promise; + /** + * @returns Any scopes (user-specified or default scopes specified by the + * client library) that need to be set on the current Auth client. + */ + private getAnyScopes; + /** + * Obtains the default service-level credentials for the application. + * @param callback Optional callback. + * @returns Promise that resolves with the ADCResponse (if no callback was + * passed). + */ + getApplicationDefault(): Promise; + getApplicationDefault(callback: ADCCallback): void; + getApplicationDefault(options: AuthClientOptions): Promise; + getApplicationDefault(options: AuthClientOptions, callback: ADCCallback): void; + private getApplicationDefaultAsync; + /** + * Determines whether the auth layer is running on Google Compute Engine. + * Checks for GCP Residency, then fallback to checking if metadata server + * is available. + * + * @returns A promise that resolves with the boolean. + * @api private + */ + _checkIsGCE(): Promise; + /** + * Attempts to load default credentials from the environment variable path.. + * @returns Promise that resolves with the OAuth2Client or null. + * @api private + */ + _tryGetApplicationCredentialsFromEnvironmentVariable(options?: AuthClientOptions): Promise; + /** + * Attempts to load default credentials from a well-known file location + * @return Promise that resolves with the OAuth2Client or null. + * @api private + */ + _tryGetApplicationCredentialsFromWellKnownFile(options?: AuthClientOptions): Promise; + /** + * Attempts to load default credentials from a file at the given path.. + * @param filePath The path to the file to read. + * @returns Promise that resolves with the OAuth2Client + * @api private + */ + _getApplicationCredentialsFromFilePath(filePath: string, options?: AuthClientOptions): Promise; + /** + * Create a credentials instance using a given impersonated input options. + * @param json The impersonated input object. + * @returns JWT or UserRefresh Client with data + */ + fromImpersonatedJSON(json: ImpersonatedJWTInput): Impersonated; + /** + * Create a credentials instance using the given input options. + * This client is not cached. + * + * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}. + * + * @param json The input object. + * @param options The JWT or UserRefresh options for the client + * @returns JWT or UserRefresh Client with data + */ + fromJSON(json: JWTInput | ImpersonatedJWTInput, options?: AuthClientOptions): JSONClient; + /** + * Return a JWT or UserRefreshClient from JavaScript object, caching both the + * object used to instantiate and the client. + * @param json The input object. + * @param options The JWT or UserRefresh options for the client + * @returns JWT or UserRefresh Client with data + */ + private _cacheClientFromJSON; + /** + * Create a credentials instance using the given input stream. + * @param inputStream The input stream. + * @param callback Optional callback. + */ + fromStream(inputStream: stream.Readable): Promise; + fromStream(inputStream: stream.Readable, callback: CredentialCallback): void; + fromStream(inputStream: stream.Readable, options: AuthClientOptions): Promise; + fromStream(inputStream: stream.Readable, options: AuthClientOptions, callback: CredentialCallback): void; + private fromStreamAsync; + /** + * Create a credentials instance using the given API key string. + * The created client is not cached. In order to create and cache it use the {@link GoogleAuth.getClient `getClient`} method after first providing an {@link GoogleAuth.apiKey `apiKey`}. + * + * @param apiKey The API key string + * @param options An optional options object. + * @returns A JWT loaded from the key + */ + fromAPIKey(apiKey: string, options?: AuthClientOptions): JWT; + /** + * Determines whether the current operating system is Windows. + * @api private + */ + private _isWindows; + /** + * Run the Google Cloud SDK command that prints the default project ID + */ + private getDefaultServiceProjectId; + /** + * Loads the project id from environment variables. + * @api private + */ + private getProductionProjectId; + /** + * Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file. + * @api private + */ + private getFileProjectId; + /** + * Gets the project ID from external account client if available. + */ + private getExternalAccountClientProjectId; + /** + * Gets the Compute Engine project ID if it can be inferred. + */ + private getGCEProjectId; + /** + * The callback function handles a credential object that contains the + * client_email and private_key (if exists). + * getCredentials first checks if the client is using an external account and + * uses the service account email in place of client_email. + * If that doesn't exist, it checks for these values from the user JSON. + * If the user JSON doesn't exist, and the environment is on GCE, it gets the + * client_email from the cloud metadata server. + * @param callback Callback that handles the credential object that contains + * a client_email and optional private key, or the error. + * returned + */ + getCredentials(): Promise; + getCredentials(callback: (err: Error | null, credentials?: CredentialBody) => void): void; + private getCredentialsAsync; + /** + * Automatically obtain an {@link AuthClient `AuthClient`} based on the + * provided configuration. If no options were passed, use Application + * Default Credentials. + */ + getClient(): Promise; + /** + * Creates a client which will fetch an ID token for authorization. + * @param targetAudience the audience for the fetched ID token. + * @returns IdTokenClient for making HTTP calls authenticated with ID tokens. + */ + getIdTokenClient(targetAudience: string): Promise; + /** + * Automatically obtain application default credentials, and return + * an access token for making requests. + */ + getAccessToken(): Promise; + /** + * Obtain the HTTP headers that will provide authorization for a given + * request. + */ + getRequestHeaders(url?: string): Promise; + /** + * Obtain credentials for a request, then attach the appropriate headers to + * the request options. + * @param opts Axios or Request options on which to attach the headers + */ + authorizeRequest(opts: { + url?: string; + uri?: string; + headers?: Headers; + }): Promise<{ + url?: string; + uri?: string; + headers?: Headers; + }>; + /** + * Automatically obtain application default credentials, and make an + * HTTP request using the given options. + * @param opts Axios request options for the HTTP request. + */ + request(opts: GaxiosOptions): Promise>; + /** + * Determine the compute environment in which the code is running. + */ + getEnv(): Promise; + /** + * Sign the given data with the current private key, or go out + * to the IAM API to sign it. + * @param data The data to be signed. + * @param endpoint A custom endpoint to use. + * + * @example + * ``` + * sign('data', 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/'); + * ``` + */ + sign(data: string, endpoint?: string): Promise; + private signBlob; +} +export interface SignBlobResponse { + keyId: string; + signedBlob: string; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/googleauth.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/googleauth.js new file mode 100644 index 0000000000000000000000000000000000000000..1f68a8d7da74432426bb0c217696546b4342041b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/googleauth.js @@ -0,0 +1,841 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var _GoogleAuth_instances, _GoogleAuth_pendingAuthClient, _GoogleAuth_prepareAndCacheClient, _GoogleAuth_determineClient; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GoogleAuth = exports.GoogleAuthExceptionMessages = exports.CLOUD_SDK_CLIENT_ID = void 0; +const child_process_1 = require("child_process"); +const fs = require("fs"); +const gcpMetadata = require("gcp-metadata"); +const os = require("os"); +const path = require("path"); +const crypto_1 = require("../crypto/crypto"); +const transporters_1 = require("../transporters"); +const computeclient_1 = require("./computeclient"); +const idtokenclient_1 = require("./idtokenclient"); +const envDetect_1 = require("./envDetect"); +const jwtclient_1 = require("./jwtclient"); +const refreshclient_1 = require("./refreshclient"); +const impersonated_1 = require("./impersonated"); +const externalclient_1 = require("./externalclient"); +const baseexternalclient_1 = require("./baseexternalclient"); +const authclient_1 = require("./authclient"); +const externalAccountAuthorizedUserClient_1 = require("./externalAccountAuthorizedUserClient"); +const util_1 = require("../util"); +exports.CLOUD_SDK_CLIENT_ID = '764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com'; +exports.GoogleAuthExceptionMessages = { + API_KEY_WITH_CREDENTIALS: 'API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.', + NO_PROJECT_ID_FOUND: 'Unable to detect a Project Id in the current environment. \n' + + 'To learn more about authentication and Google APIs, visit: \n' + + 'https://cloud.google.com/docs/authentication/getting-started', + NO_CREDENTIALS_FOUND: 'Unable to find credentials in current environment. \n' + + 'To learn more about authentication and Google APIs, visit: \n' + + 'https://cloud.google.com/docs/authentication/getting-started', + NO_ADC_FOUND: 'Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.', + NO_UNIVERSE_DOMAIN_FOUND: 'Unable to detect a Universe Domain in the current environment.\n' + + 'To learn more about Universe Domain retrieval, visit: \n' + + 'https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys', +}; +class GoogleAuth { + // Note: this properly is only public to satisfy unit tests. + // https://github.com/Microsoft/TypeScript/issues/5228 + get isGCE() { + return this.checkIsGCE; + } + /** + * Configuration is resolved in the following order of precedence: + * - {@link GoogleAuthOptions.credentials `credentials`} + * - {@link GoogleAuthOptions.keyFilename `keyFilename`} + * - {@link GoogleAuthOptions.keyFile `keyFile`} + * + * {@link GoogleAuthOptions.clientOptions `clientOptions`} are passed to the + * {@link AuthClient `AuthClient`s}. + * + * @param opts + */ + constructor(opts = {}) { + _GoogleAuth_instances.add(this); + /** + * Caches a value indicating whether the auth layer is running on Google + * Compute Engine. + * @private + */ + this.checkIsGCE = undefined; + // To save the contents of the JSON credential file + this.jsonContent = null; + this.cachedCredential = null; + /** + * A pending {@link AuthClient}. Used for concurrent {@link GoogleAuth.getClient} calls. + */ + _GoogleAuth_pendingAuthClient.set(this, null); + this.clientOptions = {}; + this._cachedProjectId = opts.projectId || null; + this.cachedCredential = opts.authClient || null; + this.keyFilename = opts.keyFilename || opts.keyFile; + this.scopes = opts.scopes; + this.clientOptions = opts.clientOptions || {}; + this.jsonContent = opts.credentials || null; + this.apiKey = opts.apiKey || this.clientOptions.apiKey || null; + // Cannot use both API Key + Credentials + if (this.apiKey && (this.jsonContent || this.clientOptions.credentials)) { + throw new RangeError(exports.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS); + } + if (opts.universeDomain) { + this.clientOptions.universeDomain = opts.universeDomain; + } + } + // GAPIC client libraries should always use self-signed JWTs. The following + // variables are set on the JWT client in order to indicate the type of library, + // and sign the JWT with the correct audience and scopes (if not supplied). + setGapicJWTValues(client) { + client.defaultServicePath = this.defaultServicePath; + client.useJWTAccessWithScope = this.useJWTAccessWithScope; + client.defaultScopes = this.defaultScopes; + } + getProjectId(callback) { + if (callback) { + this.getProjectIdAsync().then(r => callback(null, r), callback); + } + else { + return this.getProjectIdAsync(); + } + } + /** + * A temporary method for internal `getProjectId` usages where `null` is + * acceptable. In a future major release, `getProjectId` should return `null` + * (as the `Promise` base signature describes) and this private + * method should be removed. + * + * @returns Promise that resolves with project id (or `null`) + */ + async getProjectIdOptional() { + try { + return await this.getProjectId(); + } + catch (e) { + if (e instanceof Error && + e.message === exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND) { + return null; + } + else { + throw e; + } + } + } + /** + * A private method for finding and caching a projectId. + * + * Supports environments in order of precedence: + * - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable + * - GOOGLE_APPLICATION_CREDENTIALS JSON file + * - Cloud SDK: `gcloud config config-helper --format json` + * - GCE project ID from metadata server + * + * @returns projectId + */ + async findAndCacheProjectId() { + let projectId = null; + projectId || (projectId = await this.getProductionProjectId()); + projectId || (projectId = await this.getFileProjectId()); + projectId || (projectId = await this.getDefaultServiceProjectId()); + projectId || (projectId = await this.getGCEProjectId()); + projectId || (projectId = await this.getExternalAccountClientProjectId()); + if (projectId) { + this._cachedProjectId = projectId; + return projectId; + } + else { + throw new Error(exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND); + } + } + async getProjectIdAsync() { + if (this._cachedProjectId) { + return this._cachedProjectId; + } + if (!this._findProjectIdPromise) { + this._findProjectIdPromise = this.findAndCacheProjectId(); + } + return this._findProjectIdPromise; + } + /** + * Retrieves a universe domain from the metadata server via + * {@link gcpMetadata.universe}. + * + * @returns a universe domain + */ + async getUniverseDomainFromMetadataServer() { + var _a; + let universeDomain; + try { + universeDomain = await gcpMetadata.universe('universe-domain'); + universeDomain || (universeDomain = authclient_1.DEFAULT_UNIVERSE); + } + catch (e) { + if (e && ((_a = e === null || e === void 0 ? void 0 : e.response) === null || _a === void 0 ? void 0 : _a.status) === 404) { + universeDomain = authclient_1.DEFAULT_UNIVERSE; + } + else { + throw e; + } + } + return universeDomain; + } + /** + * Retrieves, caches, and returns the universe domain in the following order + * of precedence: + * - The universe domain in {@link GoogleAuth.clientOptions} + * - An existing or ADC {@link AuthClient}'s universe domain + * - {@link gcpMetadata.universe}, if {@link Compute} client + * + * @returns The universe domain + */ + async getUniverseDomain() { + let universeDomain = (0, util_1.originalOrCamelOptions)(this.clientOptions).get('universe_domain'); + try { + universeDomain !== null && universeDomain !== void 0 ? universeDomain : (universeDomain = (await this.getClient()).universeDomain); + } + catch (_a) { + // client or ADC is not available + universeDomain !== null && universeDomain !== void 0 ? universeDomain : (universeDomain = authclient_1.DEFAULT_UNIVERSE); + } + return universeDomain; + } + /** + * @returns Any scopes (user-specified or default scopes specified by the + * client library) that need to be set on the current Auth client. + */ + getAnyScopes() { + return this.scopes || this.defaultScopes; + } + getApplicationDefault(optionsOrCallback = {}, callback) { + let options; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else { + options = optionsOrCallback; + } + if (callback) { + this.getApplicationDefaultAsync(options).then(r => callback(null, r.credential, r.projectId), callback); + } + else { + return this.getApplicationDefaultAsync(options); + } + } + async getApplicationDefaultAsync(options = {}) { + // If we've already got a cached credential, return it. + // This will also preserve one's configured quota project, in case they + // set one directly on the credential previously. + if (this.cachedCredential) { + // cache, while preserving existing quota project preferences + return await __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, this.cachedCredential, null); + } + let credential; + // Check for the existence of a local environment variable pointing to the + // location of the credential file. This is typically used in local + // developer scenarios. + credential = + await this._tryGetApplicationCredentialsFromEnvironmentVariable(options); + if (credential) { + if (credential instanceof jwtclient_1.JWT) { + credential.scopes = this.scopes; + } + else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) { + credential.scopes = this.getAnyScopes(); + } + return await __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, credential); + } + // Look in the well-known credential file location. + credential = + await this._tryGetApplicationCredentialsFromWellKnownFile(options); + if (credential) { + if (credential instanceof jwtclient_1.JWT) { + credential.scopes = this.scopes; + } + else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) { + credential.scopes = this.getAnyScopes(); + } + return await __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, credential); + } + // Determine if we're running on GCE. + if (await this._checkIsGCE()) { + options.scopes = this.getAnyScopes(); + return await __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, new computeclient_1.Compute(options)); + } + throw new Error(exports.GoogleAuthExceptionMessages.NO_ADC_FOUND); + } + /** + * Determines whether the auth layer is running on Google Compute Engine. + * Checks for GCP Residency, then fallback to checking if metadata server + * is available. + * + * @returns A promise that resolves with the boolean. + * @api private + */ + async _checkIsGCE() { + if (this.checkIsGCE === undefined) { + this.checkIsGCE = + gcpMetadata.getGCPResidency() || (await gcpMetadata.isAvailable()); + } + return this.checkIsGCE; + } + /** + * Attempts to load default credentials from the environment variable path.. + * @returns Promise that resolves with the OAuth2Client or null. + * @api private + */ + async _tryGetApplicationCredentialsFromEnvironmentVariable(options) { + const credentialsPath = process.env['GOOGLE_APPLICATION_CREDENTIALS'] || + process.env['google_application_credentials']; + if (!credentialsPath || credentialsPath.length === 0) { + return null; + } + try { + return this._getApplicationCredentialsFromFilePath(credentialsPath, options); + } + catch (e) { + if (e instanceof Error) { + e.message = `Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e.message}`; + } + throw e; + } + } + /** + * Attempts to load default credentials from a well-known file location + * @return Promise that resolves with the OAuth2Client or null. + * @api private + */ + async _tryGetApplicationCredentialsFromWellKnownFile(options) { + // First, figure out the location of the file, depending upon the OS type. + let location = null; + if (this._isWindows()) { + // Windows + location = process.env['APPDATA']; + } + else { + // Linux or Mac + const home = process.env['HOME']; + if (home) { + location = path.join(home, '.config'); + } + } + // If we found the root path, expand it. + if (location) { + location = path.join(location, 'gcloud', 'application_default_credentials.json'); + if (!fs.existsSync(location)) { + location = null; + } + } + // The file does not exist. + if (!location) { + return null; + } + // The file seems to exist. Try to use it. + const client = await this._getApplicationCredentialsFromFilePath(location, options); + return client; + } + /** + * Attempts to load default credentials from a file at the given path.. + * @param filePath The path to the file to read. + * @returns Promise that resolves with the OAuth2Client + * @api private + */ + async _getApplicationCredentialsFromFilePath(filePath, options = {}) { + // Make sure the path looks like a string. + if (!filePath || filePath.length === 0) { + throw new Error('The file path is invalid.'); + } + // Make sure there is a file at the path. lstatSync will throw if there is + // nothing there. + try { + // Resolve path to actual file in case of symlink. Expect a thrown error + // if not resolvable. + filePath = fs.realpathSync(filePath); + if (!fs.lstatSync(filePath).isFile()) { + throw new Error(); + } + } + catch (err) { + if (err instanceof Error) { + err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`; + } + throw err; + } + // Now open a read stream on the file, and parse it. + const readStream = fs.createReadStream(filePath); + return this.fromStream(readStream, options); + } + /** + * Create a credentials instance using a given impersonated input options. + * @param json The impersonated input object. + * @returns JWT or UserRefresh Client with data + */ + fromImpersonatedJSON(json) { + var _a, _b, _c, _d; + if (!json) { + throw new Error('Must pass in a JSON object containing an impersonated refresh token'); + } + if (json.type !== impersonated_1.IMPERSONATED_ACCOUNT_TYPE) { + throw new Error(`The incoming JSON object does not have the "${impersonated_1.IMPERSONATED_ACCOUNT_TYPE}" type`); + } + if (!json.source_credentials) { + throw new Error('The incoming JSON object does not contain a source_credentials field'); + } + if (!json.service_account_impersonation_url) { + throw new Error('The incoming JSON object does not contain a service_account_impersonation_url field'); + } + const sourceClient = this.fromJSON(json.source_credentials); + if (((_a = json.service_account_impersonation_url) === null || _a === void 0 ? void 0 : _a.length) > 256) { + /** + * Prevents DOS attacks. + * @see {@link https://github.com/googleapis/google-auth-library-nodejs/security/code-scanning/85} + **/ + throw new RangeError(`Target principal is too long: ${json.service_account_impersonation_url}`); + } + // Extract service account from service_account_impersonation_url + const targetPrincipal = (_c = (_b = /(?[^/]+):(generateAccessToken|generateIdToken)$/.exec(json.service_account_impersonation_url)) === null || _b === void 0 ? void 0 : _b.groups) === null || _c === void 0 ? void 0 : _c.target; + if (!targetPrincipal) { + throw new RangeError(`Cannot extract target principal from ${json.service_account_impersonation_url}`); + } + const targetScopes = (_d = this.getAnyScopes()) !== null && _d !== void 0 ? _d : []; + return new impersonated_1.Impersonated({ + ...json, + sourceClient, + targetPrincipal, + targetScopes: Array.isArray(targetScopes) ? targetScopes : [targetScopes], + }); + } + /** + * Create a credentials instance using the given input options. + * This client is not cached. + * + * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}. + * + * @param json The input object. + * @param options The JWT or UserRefresh options for the client + * @returns JWT or UserRefresh Client with data + */ + fromJSON(json, options = {}) { + let client; + // user's preferred universe domain + const preferredUniverseDomain = (0, util_1.originalOrCamelOptions)(options).get('universe_domain'); + if (json.type === refreshclient_1.USER_REFRESH_ACCOUNT_TYPE) { + client = new refreshclient_1.UserRefreshClient(options); + client.fromJSON(json); + } + else if (json.type === impersonated_1.IMPERSONATED_ACCOUNT_TYPE) { + client = this.fromImpersonatedJSON(json); + } + else if (json.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { + client = externalclient_1.ExternalAccountClient.fromJSON(json, options); + client.scopes = this.getAnyScopes(); + } + else if (json.type === externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE) { + client = new externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient(json, options); + } + else { + options.scopes = this.scopes; + client = new jwtclient_1.JWT(options); + this.setGapicJWTValues(client); + client.fromJSON(json); + } + if (preferredUniverseDomain) { + client.universeDomain = preferredUniverseDomain; + } + return client; + } + /** + * Return a JWT or UserRefreshClient from JavaScript object, caching both the + * object used to instantiate and the client. + * @param json The input object. + * @param options The JWT or UserRefresh options for the client + * @returns JWT or UserRefresh Client with data + */ + _cacheClientFromJSON(json, options) { + const client = this.fromJSON(json, options); + // cache both raw data used to instantiate client and client itself. + this.jsonContent = json; + this.cachedCredential = client; + return client; + } + fromStream(inputStream, optionsOrCallback = {}, callback) { + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else { + options = optionsOrCallback; + } + if (callback) { + this.fromStreamAsync(inputStream, options).then(r => callback(null, r), callback); + } + else { + return this.fromStreamAsync(inputStream, options); + } + } + fromStreamAsync(inputStream, options) { + return new Promise((resolve, reject) => { + if (!inputStream) { + throw new Error('Must pass in a stream containing the Google auth settings.'); + } + const chunks = []; + inputStream + .setEncoding('utf8') + .on('error', reject) + .on('data', chunk => chunks.push(chunk)) + .on('end', () => { + try { + try { + const data = JSON.parse(chunks.join('')); + const r = this._cacheClientFromJSON(data, options); + return resolve(r); + } + catch (err) { + // If we failed parsing this.keyFileName, assume that it + // is a PEM or p12 certificate: + if (!this.keyFilename) + throw err; + const client = new jwtclient_1.JWT({ + ...this.clientOptions, + keyFile: this.keyFilename, + }); + this.cachedCredential = client; + this.setGapicJWTValues(client); + return resolve(client); + } + } + catch (err) { + return reject(err); + } + }); + }); + } + /** + * Create a credentials instance using the given API key string. + * The created client is not cached. In order to create and cache it use the {@link GoogleAuth.getClient `getClient`} method after first providing an {@link GoogleAuth.apiKey `apiKey`}. + * + * @param apiKey The API key string + * @param options An optional options object. + * @returns A JWT loaded from the key + */ + fromAPIKey(apiKey, options = {}) { + return new jwtclient_1.JWT({ ...options, apiKey }); + } + /** + * Determines whether the current operating system is Windows. + * @api private + */ + _isWindows() { + const sys = os.platform(); + if (sys && sys.length >= 3) { + if (sys.substring(0, 3).toLowerCase() === 'win') { + return true; + } + } + return false; + } + /** + * Run the Google Cloud SDK command that prints the default project ID + */ + async getDefaultServiceProjectId() { + return new Promise(resolve => { + (0, child_process_1.exec)('gcloud config config-helper --format json', (err, stdout) => { + if (!err && stdout) { + try { + const projectId = JSON.parse(stdout).configuration.properties.core.project; + resolve(projectId); + return; + } + catch (e) { + // ignore errors + } + } + resolve(null); + }); + }); + } + /** + * Loads the project id from environment variables. + * @api private + */ + getProductionProjectId() { + return (process.env['GCLOUD_PROJECT'] || + process.env['GOOGLE_CLOUD_PROJECT'] || + process.env['gcloud_project'] || + process.env['google_cloud_project']); + } + /** + * Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file. + * @api private + */ + async getFileProjectId() { + if (this.cachedCredential) { + // Try to read the project ID from the cached credentials file + return this.cachedCredential.projectId; + } + // Ensure the projectId is loaded from the keyFile if available. + if (this.keyFilename) { + const creds = await this.getClient(); + if (creds && creds.projectId) { + return creds.projectId; + } + } + // Try to load a credentials file and read its project ID + const r = await this._tryGetApplicationCredentialsFromEnvironmentVariable(); + if (r) { + return r.projectId; + } + else { + return null; + } + } + /** + * Gets the project ID from external account client if available. + */ + async getExternalAccountClientProjectId() { + if (!this.jsonContent || this.jsonContent.type !== baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { + return null; + } + const creds = await this.getClient(); + // Do not suppress the underlying error, as the error could contain helpful + // information for debugging and fixing. This is especially true for + // external account creds as in order to get the project ID, the following + // operations have to succeed: + // 1. Valid credentials file should be supplied. + // 2. Ability to retrieve access tokens from STS token exchange API. + // 3. Ability to exchange for service account impersonated credentials (if + // enabled). + // 4. Ability to get project info using the access token from step 2 or 3. + // Without surfacing the error, it is harder for developers to determine + // which step went wrong. + return await creds.getProjectId(); + } + /** + * Gets the Compute Engine project ID if it can be inferred. + */ + async getGCEProjectId() { + try { + const r = await gcpMetadata.project('project-id'); + return r; + } + catch (e) { + // Ignore any errors + return null; + } + } + getCredentials(callback) { + if (callback) { + this.getCredentialsAsync().then(r => callback(null, r), callback); + } + else { + return this.getCredentialsAsync(); + } + } + async getCredentialsAsync() { + const client = await this.getClient(); + if (client instanceof impersonated_1.Impersonated) { + return { client_email: client.getTargetPrincipal() }; + } + if (client instanceof baseexternalclient_1.BaseExternalAccountClient) { + const serviceAccountEmail = client.getServiceAccountEmail(); + if (serviceAccountEmail) { + return { + client_email: serviceAccountEmail, + universe_domain: client.universeDomain, + }; + } + } + if (this.jsonContent) { + return { + client_email: this.jsonContent.client_email, + private_key: this.jsonContent.private_key, + universe_domain: this.jsonContent.universe_domain, + }; + } + if (await this._checkIsGCE()) { + const [client_email, universe_domain] = await Promise.all([ + gcpMetadata.instance('service-accounts/default/email'), + this.getUniverseDomain(), + ]); + return { client_email, universe_domain }; + } + throw new Error(exports.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND); + } + /** + * Automatically obtain an {@link AuthClient `AuthClient`} based on the + * provided configuration. If no options were passed, use Application + * Default Credentials. + */ + async getClient() { + if (this.cachedCredential) { + return this.cachedCredential; + } + // Use an existing auth client request, or cache a new one + __classPrivateFieldSet(this, _GoogleAuth_pendingAuthClient, __classPrivateFieldGet(this, _GoogleAuth_pendingAuthClient, "f") || __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_determineClient).call(this), "f"); + try { + return await __classPrivateFieldGet(this, _GoogleAuth_pendingAuthClient, "f"); + } + finally { + // reset the pending auth client in case it is changed later + __classPrivateFieldSet(this, _GoogleAuth_pendingAuthClient, null, "f"); + } + } + /** + * Creates a client which will fetch an ID token for authorization. + * @param targetAudience the audience for the fetched ID token. + * @returns IdTokenClient for making HTTP calls authenticated with ID tokens. + */ + async getIdTokenClient(targetAudience) { + const client = await this.getClient(); + if (!('fetchIdToken' in client)) { + throw new Error('Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.'); + } + return new idtokenclient_1.IdTokenClient({ targetAudience, idTokenProvider: client }); + } + /** + * Automatically obtain application default credentials, and return + * an access token for making requests. + */ + async getAccessToken() { + const client = await this.getClient(); + return (await client.getAccessToken()).token; + } + /** + * Obtain the HTTP headers that will provide authorization for a given + * request. + */ + async getRequestHeaders(url) { + const client = await this.getClient(); + return client.getRequestHeaders(url); + } + /** + * Obtain credentials for a request, then attach the appropriate headers to + * the request options. + * @param opts Axios or Request options on which to attach the headers + */ + async authorizeRequest(opts) { + opts = opts || {}; + const url = opts.url || opts.uri; + const client = await this.getClient(); + const headers = await client.getRequestHeaders(url); + opts.headers = Object.assign(opts.headers || {}, headers); + return opts; + } + /** + * Automatically obtain application default credentials, and make an + * HTTP request using the given options. + * @param opts Axios request options for the HTTP request. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async request(opts) { + const client = await this.getClient(); + return client.request(opts); + } + /** + * Determine the compute environment in which the code is running. + */ + getEnv() { + return (0, envDetect_1.getEnv)(); + } + /** + * Sign the given data with the current private key, or go out + * to the IAM API to sign it. + * @param data The data to be signed. + * @param endpoint A custom endpoint to use. + * + * @example + * ``` + * sign('data', 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/'); + * ``` + */ + async sign(data, endpoint) { + const client = await this.getClient(); + const universe = await this.getUniverseDomain(); + endpoint = + endpoint || + `https://iamcredentials.${universe}/v1/projects/-/serviceAccounts/`; + if (client instanceof impersonated_1.Impersonated) { + const signed = await client.sign(data); + return signed.signedBlob; + } + const crypto = (0, crypto_1.createCrypto)(); + if (client instanceof jwtclient_1.JWT && client.key) { + const sign = await crypto.sign(client.key, data); + return sign; + } + const creds = await this.getCredentials(); + if (!creds.client_email) { + throw new Error('Cannot sign data without `client_email`.'); + } + return this.signBlob(crypto, creds.client_email, data, endpoint); + } + async signBlob(crypto, emailOrUniqueId, data, endpoint) { + const url = new URL(endpoint + `${emailOrUniqueId}:signBlob`); + const res = await this.request({ + method: 'POST', + url: url.href, + data: { + payload: crypto.encodeBase64StringUtf8(data), + }, + retry: true, + retryConfig: { + httpMethodsToRetry: ['POST'], + }, + }); + return res.data.signedBlob; + } +} +exports.GoogleAuth = GoogleAuth; +_GoogleAuth_pendingAuthClient = new WeakMap(), _GoogleAuth_instances = new WeakSet(), _GoogleAuth_prepareAndCacheClient = async function _GoogleAuth_prepareAndCacheClient(credential, quotaProjectIdOverride = process.env['GOOGLE_CLOUD_QUOTA_PROJECT'] || null) { + const projectId = await this.getProjectIdOptional(); + if (quotaProjectIdOverride) { + credential.quotaProjectId = quotaProjectIdOverride; + } + this.cachedCredential = credential; + return { credential, projectId }; +}, _GoogleAuth_determineClient = async function _GoogleAuth_determineClient() { + if (this.jsonContent) { + return this._cacheClientFromJSON(this.jsonContent, this.clientOptions); + } + else if (this.keyFilename) { + const filePath = path.resolve(this.keyFilename); + const stream = fs.createReadStream(filePath); + return await this.fromStreamAsync(stream, this.clientOptions); + } + else if (this.apiKey) { + const client = await this.fromAPIKey(this.apiKey, this.clientOptions); + client.scopes = this.scopes; + const { credential } = await __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, client); + return credential; + } + else { + const { credential } = await this.getApplicationDefaultAsync(this.clientOptions); + return credential; + } +}; +/** + * Export DefaultTransporter as a static property of the class. + */ +GoogleAuth.DefaultTransporter = transporters_1.DefaultTransporter; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/iam.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/iam.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..93470a4439cb77cb5f703701f424c481306920a4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/iam.d.ts @@ -0,0 +1,23 @@ +export interface RequestMetadata { + 'x-goog-iam-authority-selector': string; + 'x-goog-iam-authorization-token': string; +} +export declare class IAMAuth { + selector: string; + token: string; + /** + * IAM credentials. + * + * @param selector the iam authority selector + * @param token the token + * @constructor + */ + constructor(selector: string, token: string); + /** + * Acquire the HTTP headers required to make an authenticated request. + */ + getRequestHeaders(): { + 'x-goog-iam-authority-selector': string; + 'x-goog-iam-authorization-token': string; + }; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/iam.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/iam.js new file mode 100644 index 0000000000000000000000000000000000000000..e837114fecf95b891e4fc948fd87b1bcdbc2e1c1 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/iam.js @@ -0,0 +1,41 @@ +"use strict"; +// Copyright 2014 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IAMAuth = void 0; +class IAMAuth { + /** + * IAM credentials. + * + * @param selector the iam authority selector + * @param token the token + * @constructor + */ + constructor(selector, token) { + this.selector = selector; + this.token = token; + this.selector = selector; + this.token = token; + } + /** + * Acquire the HTTP headers required to make an authenticated request. + */ + getRequestHeaders() { + return { + 'x-goog-iam-authority-selector': this.selector, + 'x-goog-iam-authorization-token': this.token, + }; + } +} +exports.IAMAuth = IAMAuth; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/identitypoolclient.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/identitypoolclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1b2e6c14ad3c3df6e9a34abd332d008b9fc8b65e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/identitypoolclient.d.ts @@ -0,0 +1,102 @@ +import { BaseExternalAccountClient, BaseExternalAccountClientOptions, ExternalAccountSupplierContext } from './baseexternalclient'; +import { AuthClientOptions } from './authclient'; +import { SnakeToCamelObject } from '../util'; +export type SubjectTokenFormatType = 'json' | 'text'; +export interface SubjectTokenJsonResponse { + [key: string]: string; +} +/** + * Supplier interface for subject tokens. This can be implemented to + * return a subject token which can then be exchanged for a GCP token by an + * {@link IdentityPoolClient}. + */ +export interface SubjectTokenSupplier { + /** + * Gets a valid subject token for the requested external account identity. + * Note that these are not cached by the calling {@link IdentityPoolClient}, + * so caching should be including in the implementation. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link IdentityPoolClient}, contains the requested audience and subject token type + * for the external account identity as well as the transport from the + * calling client to use for requests. + * @return A promise that resolves with the requested subject token string. + */ + getSubjectToken: (context: ExternalAccountSupplierContext) => Promise; +} +/** + * Url-sourced/file-sourced credentials json interface. + * This is used for K8s and Azure workloads. + */ +export interface IdentityPoolClientOptions extends BaseExternalAccountClientOptions { + /** + * Object containing options to retrieve identity pool credentials. A valid credential + * source or a subject token supplier must be specified. + */ + credential_source?: { + /** + * The file location to read the subject token from. Either this or a URL + * should be specified. + */ + file?: string; + /** + * The URL to call to retrieve the subject token. Either this or a file + * location should be specified. + */ + url?: string; + /** + * Optional headers to send on the request to the specified URL. + */ + headers?: { + [key: string]: string; + }; + /** + * The format that the subject token is in the file or the URL response. + * If not provided, will default to reading the text string directly. + */ + format?: { + /** + * The format type. Can either be 'text' or 'json'. + */ + type: SubjectTokenFormatType; + /** + * The field name containing the subject token value if the type is 'json'. + */ + subject_token_field_name?: string; + }; + }; + /** + * The subject token supplier to call to retrieve the subject token to exchange + * for a GCP access token. Either this or a valid credential source should + * be specified. + */ + subject_token_supplier?: SubjectTokenSupplier; +} +/** + * Defines the Url-sourced and file-sourced external account clients mainly + * used for K8s and Azure workloads. + */ +export declare class IdentityPoolClient extends BaseExternalAccountClient { + private readonly subjectTokenSupplier; + /** + * Instantiate an IdentityPoolClient instance using the provided JSON + * object loaded from an external account credentials file. + * An error is thrown if the credential is not a valid file-sourced or + * url-sourced credential or a workforce pool user project is provided + * with a non workforce audience. + * @param options The external account options object typically loaded + * from the external account JSON credential file. The camelCased options + * are aliases for the snake_cased options. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options: IdentityPoolClientOptions | SnakeToCamelObject, additionalOptions?: AuthClientOptions); + /** + * Triggered when a external subject token is needed to be exchanged for a GCP + * access token via GCP STS endpoint. Gets a subject token by calling + * the configured {@link SubjectTokenSupplier} + * @return A promise that resolves with the external subject token. + */ + retrieveSubjectToken(): Promise; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/identitypoolclient.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/identitypoolclient.js new file mode 100644 index 0000000000000000000000000000000000000000..c2e2307484b91da59be1e6e9520f6e706b3bc009 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/identitypoolclient.js @@ -0,0 +1,107 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IdentityPoolClient = void 0; +const baseexternalclient_1 = require("./baseexternalclient"); +const util_1 = require("../util"); +const filesubjecttokensupplier_1 = require("./filesubjecttokensupplier"); +const urlsubjecttokensupplier_1 = require("./urlsubjecttokensupplier"); +/** + * Defines the Url-sourced and file-sourced external account clients mainly + * used for K8s and Azure workloads. + */ +class IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient { + /** + * Instantiate an IdentityPoolClient instance using the provided JSON + * object loaded from an external account credentials file. + * An error is thrown if the credential is not a valid file-sourced or + * url-sourced credential or a workforce pool user project is provided + * with a non workforce audience. + * @param options The external account options object typically loaded + * from the external account JSON credential file. The camelCased options + * are aliases for the snake_cased options. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options, additionalOptions) { + super(options, additionalOptions); + const opts = (0, util_1.originalOrCamelOptions)(options); + const credentialSource = opts.get('credential_source'); + const subjectTokenSupplier = opts.get('subject_token_supplier'); + // Validate credential sourcing configuration. + if (!credentialSource && !subjectTokenSupplier) { + throw new Error('A credential source or subject token supplier must be specified.'); + } + if (credentialSource && subjectTokenSupplier) { + throw new Error('Only one of credential source or subject token supplier can be specified.'); + } + if (subjectTokenSupplier) { + this.subjectTokenSupplier = subjectTokenSupplier; + this.credentialSourceType = 'programmatic'; + } + else { + const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource); + const formatOpts = (0, util_1.originalOrCamelOptions)(credentialSourceOpts.get('format')); + // Text is the default format type. + const formatType = formatOpts.get('type') || 'text'; + const formatSubjectTokenFieldName = formatOpts.get('subject_token_field_name'); + if (formatType !== 'json' && formatType !== 'text') { + throw new Error(`Invalid credential_source format "${formatType}"`); + } + if (formatType === 'json' && !formatSubjectTokenFieldName) { + throw new Error('Missing subject_token_field_name for JSON credential_source format'); + } + const file = credentialSourceOpts.get('file'); + const url = credentialSourceOpts.get('url'); + const headers = credentialSourceOpts.get('headers'); + if (file && url) { + throw new Error('No valid Identity Pool "credential_source" provided, must be either file or url.'); + } + else if (file && !url) { + this.credentialSourceType = 'file'; + this.subjectTokenSupplier = new filesubjecttokensupplier_1.FileSubjectTokenSupplier({ + filePath: file, + formatType: formatType, + subjectTokenFieldName: formatSubjectTokenFieldName, + }); + } + else if (!file && url) { + this.credentialSourceType = 'url'; + this.subjectTokenSupplier = new urlsubjecttokensupplier_1.UrlSubjectTokenSupplier({ + url: url, + formatType: formatType, + subjectTokenFieldName: formatSubjectTokenFieldName, + headers: headers, + additionalGaxiosOptions: IdentityPoolClient.RETRY_CONFIG, + }); + } + else { + throw new Error('No valid Identity Pool "credential_source" provided, must be either file or url.'); + } + } + } + /** + * Triggered when a external subject token is needed to be exchanged for a GCP + * access token via GCP STS endpoint. Gets a subject token by calling + * the configured {@link SubjectTokenSupplier} + * @return A promise that resolves with the external subject token. + */ + async retrieveSubjectToken() { + return this.subjectTokenSupplier.getSubjectToken(this.supplierContext); + } +} +exports.IdentityPoolClient = IdentityPoolClient; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/idtokenclient.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/idtokenclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..311d29d078f95274db9727eecd55571bf39010c2 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/idtokenclient.d.ts @@ -0,0 +1,27 @@ +import { OAuth2Client, OAuth2ClientOptions, RequestMetadataResponse } from './oauth2client'; +export interface IdTokenOptions extends OAuth2ClientOptions { + /** + * The client to make the request to fetch an ID token. + */ + idTokenProvider: IdTokenProvider; + /** + * The audience to use when requesting an ID token. + */ + targetAudience: string; +} +export interface IdTokenProvider { + fetchIdToken: (targetAudience: string) => Promise; +} +export declare class IdTokenClient extends OAuth2Client { + targetAudience: string; + idTokenProvider: IdTokenProvider; + /** + * Google ID Token client + * + * Retrieve ID token from the metadata server. + * See: https://cloud.google.com/docs/authentication/get-id-token#metadata-server + */ + constructor(options: IdTokenOptions); + protected getRequestMetadataAsync(url?: string | null): Promise; + private getIdTokenExpiryDate; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/idtokenclient.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/idtokenclient.js new file mode 100644 index 0000000000000000000000000000000000000000..77e6fa3c98e170c7942644817225028f56422ee0 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/idtokenclient.js @@ -0,0 +1,55 @@ +"use strict"; +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IdTokenClient = void 0; +const oauth2client_1 = require("./oauth2client"); +class IdTokenClient extends oauth2client_1.OAuth2Client { + /** + * Google ID Token client + * + * Retrieve ID token from the metadata server. + * See: https://cloud.google.com/docs/authentication/get-id-token#metadata-server + */ + constructor(options) { + super(options); + this.targetAudience = options.targetAudience; + this.idTokenProvider = options.idTokenProvider; + } + async getRequestMetadataAsync( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + url) { + if (!this.credentials.id_token || + !this.credentials.expiry_date || + this.isTokenExpiring()) { + const idToken = await this.idTokenProvider.fetchIdToken(this.targetAudience); + this.credentials = { + id_token: idToken, + expiry_date: this.getIdTokenExpiryDate(idToken), + }; + } + const headers = { + Authorization: 'Bearer ' + this.credentials.id_token, + }; + return { headers }; + } + getIdTokenExpiryDate(idToken) { + const payloadB64 = idToken.split('.')[1]; + if (payloadB64) { + const payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('ascii')); + return payload.exp * 1000; + } + } +} +exports.IdTokenClient = IdTokenClient; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/impersonated.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/impersonated.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fed007ddc70dfd31b2132c3a923c8833a82a0ada --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/impersonated.d.ts @@ -0,0 +1,127 @@ +/** + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { GetTokenResponse, OAuth2Client, OAuth2ClientOptions } from './oauth2client'; +import { AuthClient } from './authclient'; +import { IdTokenProvider } from './idtokenclient'; +import { SignBlobResponse } from './googleauth'; +export interface ImpersonatedOptions extends OAuth2ClientOptions { + /** + * Client used to perform exchange for impersonated client. + */ + sourceClient?: AuthClient; + /** + * The service account to impersonate. + */ + targetPrincipal?: string; + /** + * Scopes to request during the authorization grant. + */ + targetScopes?: string[]; + /** + * The chained list of delegates required to grant the final access_token. + */ + delegates?: string[]; + /** + * Number of seconds the delegated credential should be valid. + */ + lifetime?: number | 3600; + /** + * API endpoint to fetch token from. + */ + endpoint?: string; +} +export declare const IMPERSONATED_ACCOUNT_TYPE = "impersonated_service_account"; +export interface TokenResponse { + accessToken: string; + expireTime: string; +} +export interface FetchIdTokenOptions { + /** + * Include the service account email in the token. + * If set to `true`, the token will contain `email` and `email_verified` claims. + */ + includeEmail: boolean; +} +export interface FetchIdTokenResponse { + /** The OpenId Connect ID token. */ + token: string; +} +export declare class Impersonated extends OAuth2Client implements IdTokenProvider { + private sourceClient; + private targetPrincipal; + private targetScopes; + private delegates; + private lifetime; + private endpoint; + /** + * Impersonated service account credentials. + * + * Create a new access token by impersonating another service account. + * + * Impersonated Credentials allowing credentials issued to a user or + * service account to impersonate another. The source project using + * Impersonated Credentials must enable the "IAMCredentials" API. + * Also, the target service account must grant the orginating principal + * the "Service Account Token Creator" IAM role. + * + * @param {object} options - The configuration object. + * @param {object} [options.sourceClient] the source credential used as to + * acquire the impersonated credentials. + * @param {string} [options.targetPrincipal] the service account to + * impersonate. + * @param {string[]} [options.delegates] the chained list of delegates + * required to grant the final access_token. If set, the sequence of + * identities must have "Service Account Token Creator" capability granted to + * the preceding identity. For example, if set to [serviceAccountB, + * serviceAccountC], the sourceCredential must have the Token Creator role on + * serviceAccountB. serviceAccountB must have the Token Creator on + * serviceAccountC. Finally, C must have Token Creator on target_principal. + * If left unset, sourceCredential must have that role on targetPrincipal. + * @param {string[]} [options.targetScopes] scopes to request during the + * authorization grant. + * @param {number} [options.lifetime] number of seconds the delegated + * credential should be valid for up to 3600 seconds by default, or 43,200 + * seconds by extending the token's lifetime, see: + * https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth + * @param {string} [options.endpoint] api endpoint override. + */ + constructor(options?: ImpersonatedOptions); + /** + * Signs some bytes. + * + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob Reference Documentation} + * @param blobToSign String to sign. + * + * @returns A {@link SignBlobResponse} denoting the keyID and signedBlob in base64 string + */ + sign(blobToSign: string): Promise; + /** The service account email to be impersonated. */ + getTargetPrincipal(): string; + /** + * Refreshes the access token. + */ + protected refreshToken(): Promise; + /** + * Generates an OpenID Connect ID token for a service account. + * + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateIdToken Reference Documentation} + * + * @param targetAudience the audience for the fetched ID token. + * @param options the for the request + * @return an OpenID Connect ID token + */ + fetchIdToken(targetAudience: string, options?: FetchIdTokenOptions): Promise; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/impersonated.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/impersonated.js new file mode 100644 index 0000000000000000000000000000000000000000..46c07c98f877ed996b868a5a3e09f1361633f7bf --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/impersonated.js @@ -0,0 +1,186 @@ +"use strict"; +/** + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Impersonated = exports.IMPERSONATED_ACCOUNT_TYPE = void 0; +const oauth2client_1 = require("./oauth2client"); +const gaxios_1 = require("gaxios"); +const util_1 = require("../util"); +exports.IMPERSONATED_ACCOUNT_TYPE = 'impersonated_service_account'; +class Impersonated extends oauth2client_1.OAuth2Client { + /** + * Impersonated service account credentials. + * + * Create a new access token by impersonating another service account. + * + * Impersonated Credentials allowing credentials issued to a user or + * service account to impersonate another. The source project using + * Impersonated Credentials must enable the "IAMCredentials" API. + * Also, the target service account must grant the orginating principal + * the "Service Account Token Creator" IAM role. + * + * @param {object} options - The configuration object. + * @param {object} [options.sourceClient] the source credential used as to + * acquire the impersonated credentials. + * @param {string} [options.targetPrincipal] the service account to + * impersonate. + * @param {string[]} [options.delegates] the chained list of delegates + * required to grant the final access_token. If set, the sequence of + * identities must have "Service Account Token Creator" capability granted to + * the preceding identity. For example, if set to [serviceAccountB, + * serviceAccountC], the sourceCredential must have the Token Creator role on + * serviceAccountB. serviceAccountB must have the Token Creator on + * serviceAccountC. Finally, C must have Token Creator on target_principal. + * If left unset, sourceCredential must have that role on targetPrincipal. + * @param {string[]} [options.targetScopes] scopes to request during the + * authorization grant. + * @param {number} [options.lifetime] number of seconds the delegated + * credential should be valid for up to 3600 seconds by default, or 43,200 + * seconds by extending the token's lifetime, see: + * https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth + * @param {string} [options.endpoint] api endpoint override. + */ + constructor(options = {}) { + var _a, _b, _c, _d, _e, _f; + super(options); + // Start with an expired refresh token, which will automatically be + // refreshed before the first API call is made. + this.credentials = { + expiry_date: 1, + refresh_token: 'impersonated-placeholder', + }; + this.sourceClient = (_a = options.sourceClient) !== null && _a !== void 0 ? _a : new oauth2client_1.OAuth2Client(); + this.targetPrincipal = (_b = options.targetPrincipal) !== null && _b !== void 0 ? _b : ''; + this.delegates = (_c = options.delegates) !== null && _c !== void 0 ? _c : []; + this.targetScopes = (_d = options.targetScopes) !== null && _d !== void 0 ? _d : []; + this.lifetime = (_e = options.lifetime) !== null && _e !== void 0 ? _e : 3600; + const usingExplicitUniverseDomain = !!(0, util_1.originalOrCamelOptions)(options).get('universe_domain'); + if (!usingExplicitUniverseDomain) { + // override the default universe with the source's universe + this.universeDomain = this.sourceClient.universeDomain; + } + else if (this.sourceClient.universeDomain !== this.universeDomain) { + // non-default universe and is not matching the source - this could be a credential leak + throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`); + } + this.endpoint = + (_f = options.endpoint) !== null && _f !== void 0 ? _f : `https://iamcredentials.${this.universeDomain}`; + } + /** + * Signs some bytes. + * + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob Reference Documentation} + * @param blobToSign String to sign. + * + * @returns A {@link SignBlobResponse} denoting the keyID and signedBlob in base64 string + */ + async sign(blobToSign) { + await this.sourceClient.getAccessToken(); + const name = `projects/-/serviceAccounts/${this.targetPrincipal}`; + const u = `${this.endpoint}/v1/${name}:signBlob`; + const body = { + delegates: this.delegates, + payload: Buffer.from(blobToSign).toString('base64'), + }; + const res = await this.sourceClient.request({ + ...Impersonated.RETRY_CONFIG, + url: u, + data: body, + method: 'POST', + }); + return res.data; + } + /** The service account email to be impersonated. */ + getTargetPrincipal() { + return this.targetPrincipal; + } + /** + * Refreshes the access token. + */ + async refreshToken() { + var _a, _b, _c, _d, _e, _f; + try { + await this.sourceClient.getAccessToken(); + const name = 'projects/-/serviceAccounts/' + this.targetPrincipal; + const u = `${this.endpoint}/v1/${name}:generateAccessToken`; + const body = { + delegates: this.delegates, + scope: this.targetScopes, + lifetime: this.lifetime + 's', + }; + const res = await this.sourceClient.request({ + ...Impersonated.RETRY_CONFIG, + url: u, + data: body, + method: 'POST', + }); + const tokenResponse = res.data; + this.credentials.access_token = tokenResponse.accessToken; + this.credentials.expiry_date = Date.parse(tokenResponse.expireTime); + return { + tokens: this.credentials, + res, + }; + } + catch (error) { + if (!(error instanceof Error)) + throw error; + let status = 0; + let message = ''; + if (error instanceof gaxios_1.GaxiosError) { + status = (_c = (_b = (_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.error) === null || _c === void 0 ? void 0 : _c.status; + message = (_f = (_e = (_d = error === null || error === void 0 ? void 0 : error.response) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.error) === null || _f === void 0 ? void 0 : _f.message; + } + if (status && message) { + error.message = `${status}: unable to impersonate: ${message}`; + throw error; + } + else { + error.message = `unable to impersonate: ${error}`; + throw error; + } + } + } + /** + * Generates an OpenID Connect ID token for a service account. + * + * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateIdToken Reference Documentation} + * + * @param targetAudience the audience for the fetched ID token. + * @param options the for the request + * @return an OpenID Connect ID token + */ + async fetchIdToken(targetAudience, options) { + var _a, _b; + await this.sourceClient.getAccessToken(); + const name = `projects/-/serviceAccounts/${this.targetPrincipal}`; + const u = `${this.endpoint}/v1/${name}:generateIdToken`; + const body = { + delegates: this.delegates, + audience: targetAudience, + includeEmail: (_a = options === null || options === void 0 ? void 0 : options.includeEmail) !== null && _a !== void 0 ? _a : true, + useEmailAzp: (_b = options === null || options === void 0 ? void 0 : options.includeEmail) !== null && _b !== void 0 ? _b : true, + }; + const res = await this.sourceClient.request({ + ...Impersonated.RETRY_CONFIG, + url: u, + data: body, + method: 'POST', + }); + return res.data.token; + } +} +exports.Impersonated = Impersonated; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/jwtaccess.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/jwtaccess.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9244650289d612825dc171aeddd2ee9d3170c3a3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/jwtaccess.d.ts @@ -0,0 +1,62 @@ +import * as stream from 'stream'; +import { JWTInput } from './credentials'; +import { Headers } from './oauth2client'; +export interface Claims { + [index: string]: string; +} +export declare class JWTAccess { + email?: string | null; + key?: string | null; + keyId?: string | null; + projectId?: string; + eagerRefreshThresholdMillis: number; + private cache; + /** + * JWTAccess service account credentials. + * + * Create a new access token by using the credential to create a new JWT token + * that's recognized as the access token. + * + * @param email the service account email address. + * @param key the private key that will be used to sign the token. + * @param keyId the ID of the private key used to sign the token. + */ + constructor(email?: string | null, key?: string | null, keyId?: string | null, eagerRefreshThresholdMillis?: number); + /** + * Ensures that we're caching a key appropriately, giving precedence to scopes vs. url + * + * @param url The URI being authorized. + * @param scopes The scope or scopes being authorized + * @returns A string that returns the cached key. + */ + getCachedKey(url?: string, scopes?: string | string[]): string; + /** + * Get a non-expired access token, after refreshing if necessary. + * + * @param url The URI being authorized. + * @param additionalClaims An object with a set of additional claims to + * include in the payload. + * @returns An object that includes the authorization header. + */ + getRequestHeaders(url?: string, additionalClaims?: Claims, scopes?: string | string[]): Headers; + /** + * Returns an expiration time for the JWT token. + * + * @param iat The issued at time for the JWT. + * @returns An expiration time for the JWT. + */ + private static getExpirationTime; + /** + * Create a JWTAccess credentials instance using the given input options. + * @param json The input object. + */ + fromJSON(json: JWTInput): void; + /** + * Create a JWTAccess credentials instance using the given input stream. + * @param inputStream The input stream. + * @param callback Optional callback. + */ + fromStream(inputStream: stream.Readable): Promise; + fromStream(inputStream: stream.Readable, callback: (err?: Error) => void): void; + private fromStreamAsync; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/jwtaccess.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/jwtaccess.js new file mode 100644 index 0000000000000000000000000000000000000000..664387b520b7499bd371751fd49e8e662d4b471c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/jwtaccess.js @@ -0,0 +1,192 @@ +"use strict"; +// Copyright 2015 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.JWTAccess = void 0; +const jws = require("jws"); +const util_1 = require("../util"); +const DEFAULT_HEADER = { + alg: 'RS256', + typ: 'JWT', +}; +class JWTAccess { + /** + * JWTAccess service account credentials. + * + * Create a new access token by using the credential to create a new JWT token + * that's recognized as the access token. + * + * @param email the service account email address. + * @param key the private key that will be used to sign the token. + * @param keyId the ID of the private key used to sign the token. + */ + constructor(email, key, keyId, eagerRefreshThresholdMillis) { + this.cache = new util_1.LRUCache({ + capacity: 500, + maxAge: 60 * 60 * 1000, + }); + this.email = email; + this.key = key; + this.keyId = keyId; + this.eagerRefreshThresholdMillis = + eagerRefreshThresholdMillis !== null && eagerRefreshThresholdMillis !== void 0 ? eagerRefreshThresholdMillis : 5 * 60 * 1000; + } + /** + * Ensures that we're caching a key appropriately, giving precedence to scopes vs. url + * + * @param url The URI being authorized. + * @param scopes The scope or scopes being authorized + * @returns A string that returns the cached key. + */ + getCachedKey(url, scopes) { + let cacheKey = url; + if (scopes && Array.isArray(scopes) && scopes.length) { + cacheKey = url ? `${url}_${scopes.join('_')}` : `${scopes.join('_')}`; + } + else if (typeof scopes === 'string') { + cacheKey = url ? `${url}_${scopes}` : scopes; + } + if (!cacheKey) { + throw Error('Scopes or url must be provided'); + } + return cacheKey; + } + /** + * Get a non-expired access token, after refreshing if necessary. + * + * @param url The URI being authorized. + * @param additionalClaims An object with a set of additional claims to + * include in the payload. + * @returns An object that includes the authorization header. + */ + getRequestHeaders(url, additionalClaims, scopes) { + // Return cached authorization headers, unless we are within + // eagerRefreshThresholdMillis ms of them expiring: + const key = this.getCachedKey(url, scopes); + const cachedToken = this.cache.get(key); + const now = Date.now(); + if (cachedToken && + cachedToken.expiration - now > this.eagerRefreshThresholdMillis) { + return cachedToken.headers; + } + const iat = Math.floor(Date.now() / 1000); + const exp = JWTAccess.getExpirationTime(iat); + let defaultClaims; + // Turn scopes into space-separated string + if (Array.isArray(scopes)) { + scopes = scopes.join(' '); + } + // If scopes are specified, sign with scopes + if (scopes) { + defaultClaims = { + iss: this.email, + sub: this.email, + scope: scopes, + exp, + iat, + }; + } + else { + defaultClaims = { + iss: this.email, + sub: this.email, + aud: url, + exp, + iat, + }; + } + // if additionalClaims are provided, ensure they do not collide with + // other required claims. + if (additionalClaims) { + for (const claim in defaultClaims) { + if (additionalClaims[claim]) { + throw new Error(`The '${claim}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`); + } + } + } + const header = this.keyId + ? { ...DEFAULT_HEADER, kid: this.keyId } + : DEFAULT_HEADER; + const payload = Object.assign(defaultClaims, additionalClaims); + // Sign the jwt and add it to the cache + const signedJWT = jws.sign({ header, payload, secret: this.key }); + const headers = { Authorization: `Bearer ${signedJWT}` }; + this.cache.set(key, { + expiration: exp * 1000, + headers, + }); + return headers; + } + /** + * Returns an expiration time for the JWT token. + * + * @param iat The issued at time for the JWT. + * @returns An expiration time for the JWT. + */ + static getExpirationTime(iat) { + const exp = iat + 3600; // 3600 seconds = 1 hour + return exp; + } + /** + * Create a JWTAccess credentials instance using the given input options. + * @param json The input object. + */ + fromJSON(json) { + if (!json) { + throw new Error('Must pass in a JSON object containing the service account auth settings.'); + } + if (!json.client_email) { + throw new Error('The incoming JSON object does not contain a client_email field'); + } + if (!json.private_key) { + throw new Error('The incoming JSON object does not contain a private_key field'); + } + // Extract the relevant information from the json key file. + this.email = json.client_email; + this.key = json.private_key; + this.keyId = json.private_key_id; + this.projectId = json.project_id; + } + fromStream(inputStream, callback) { + if (callback) { + this.fromStreamAsync(inputStream).then(() => callback(), callback); + } + else { + return this.fromStreamAsync(inputStream); + } + } + fromStreamAsync(inputStream) { + return new Promise((resolve, reject) => { + if (!inputStream) { + reject(new Error('Must pass in a stream containing the service account auth settings.')); + } + let s = ''; + inputStream + .setEncoding('utf8') + .on('data', chunk => (s += chunk)) + .on('error', reject) + .on('end', () => { + try { + const data = JSON.parse(s); + this.fromJSON(data); + resolve(); + } + catch (err) { + reject(err); + } + }); + }); + } +} +exports.JWTAccess = JWTAccess; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/jwtclient.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/jwtclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1d8ab2a61e28a7cf5b09b7ac9287866b370cd1a9 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/jwtclient.d.ts @@ -0,0 +1,117 @@ +import { GoogleToken } from 'gtoken'; +import * as stream from 'stream'; +import { CredentialBody, Credentials, JWTInput } from './credentials'; +import { IdTokenProvider } from './idtokenclient'; +import { GetTokenResponse, OAuth2Client, OAuth2ClientOptions, RequestMetadataResponse } from './oauth2client'; +export interface JWTOptions extends OAuth2ClientOptions { + email?: string; + keyFile?: string; + key?: string; + keyId?: string; + scopes?: string | string[]; + subject?: string; + additionalClaims?: {}; +} +export declare class JWT extends OAuth2Client implements IdTokenProvider { + email?: string; + keyFile?: string; + key?: string; + keyId?: string; + defaultScopes?: string | string[]; + scopes?: string | string[]; + scope?: string; + subject?: string; + gtoken?: GoogleToken; + additionalClaims?: {}; + useJWTAccessWithScope?: boolean; + defaultServicePath?: string; + private access?; + /** + * JWT service account credentials. + * + * Retrieve access token using gtoken. + * + * @param email service account email address. + * @param keyFile path to private key file. + * @param key value of key + * @param scopes list of requested scopes or a single scope. + * @param subject impersonated account's email address. + * @param key_id the ID of the key + */ + constructor(options: JWTOptions); + constructor(email?: string, keyFile?: string, key?: string, scopes?: string | string[], subject?: string, keyId?: string); + /** + * Creates a copy of the credential with the specified scopes. + * @param scopes List of requested scopes or a single scope. + * @return The cloned instance. + */ + createScoped(scopes?: string | string[]): JWT; + /** + * Obtains the metadata to be sent with the request. + * + * @param url the URI being authorized. + */ + protected getRequestMetadataAsync(url?: string | null): Promise; + /** + * Fetches an ID token. + * @param targetAudience the audience for the fetched ID token. + */ + fetchIdToken(targetAudience: string): Promise; + /** + * Determine if there are currently scopes available. + */ + private hasUserScopes; + /** + * Are there any default or user scopes defined. + */ + private hasAnyScopes; + /** + * Get the initial access token using gToken. + * @param callback Optional callback. + * @returns Promise that resolves with credentials + */ + authorize(): Promise; + authorize(callback: (err: Error | null, result?: Credentials) => void): void; + private authorizeAsync; + /** + * Refreshes the access token. + * @param refreshToken ignored + * @private + */ + protected refreshTokenNoCache(refreshToken?: string | null): Promise; + /** + * Create a gToken if it doesn't already exist. + */ + private createGToken; + /** + * Create a JWT credentials instance using the given input options. + * @param json The input object. + * + * @remarks + * + * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}. + */ + fromJSON(json: JWTInput): void; + /** + * Create a JWT credentials instance using the given input stream. + * @param inputStream The input stream. + * @param callback Optional callback. + * + * @remarks + * + * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}. + */ + fromStream(inputStream: stream.Readable): Promise; + fromStream(inputStream: stream.Readable, callback: (err?: Error | null) => void): void; + private fromStreamAsync; + /** + * Creates a JWT credentials instance using an API Key for authentication. + * @param apiKey The API Key in string form. + */ + fromAPIKey(apiKey: string): void; + /** + * Using the key or keyFile on the JWT client, obtain an object that contains + * the key and the client email. + */ + getCredentials(): Promise; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/jwtclient.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/jwtclient.js new file mode 100644 index 0000000000000000000000000000000000000000..d068b7d2463db6bbb38f44f9a7258d9e303b27e2 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/jwtclient.js @@ -0,0 +1,284 @@ +"use strict"; +// Copyright 2013 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.JWT = void 0; +const gtoken_1 = require("gtoken"); +const jwtaccess_1 = require("./jwtaccess"); +const oauth2client_1 = require("./oauth2client"); +const authclient_1 = require("./authclient"); +class JWT extends oauth2client_1.OAuth2Client { + constructor(optionsOrEmail, keyFile, key, scopes, subject, keyId) { + const opts = optionsOrEmail && typeof optionsOrEmail === 'object' + ? optionsOrEmail + : { email: optionsOrEmail, keyFile, key, keyId, scopes, subject }; + super(opts); + this.email = opts.email; + this.keyFile = opts.keyFile; + this.key = opts.key; + this.keyId = opts.keyId; + this.scopes = opts.scopes; + this.subject = opts.subject; + this.additionalClaims = opts.additionalClaims; + // Start with an expired refresh token, which will automatically be + // refreshed before the first API call is made. + this.credentials = { refresh_token: 'jwt-placeholder', expiry_date: 1 }; + } + /** + * Creates a copy of the credential with the specified scopes. + * @param scopes List of requested scopes or a single scope. + * @return The cloned instance. + */ + createScoped(scopes) { + const jwt = new JWT(this); + jwt.scopes = scopes; + return jwt; + } + /** + * Obtains the metadata to be sent with the request. + * + * @param url the URI being authorized. + */ + async getRequestMetadataAsync(url) { + url = this.defaultServicePath ? `https://${this.defaultServicePath}/` : url; + const useSelfSignedJWT = (!this.hasUserScopes() && url) || + (this.useJWTAccessWithScope && this.hasAnyScopes()) || + this.universeDomain !== authclient_1.DEFAULT_UNIVERSE; + if (this.subject && this.universeDomain !== authclient_1.DEFAULT_UNIVERSE) { + throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${authclient_1.DEFAULT_UNIVERSE}`); + } + if (!this.apiKey && useSelfSignedJWT) { + if (this.additionalClaims && + this.additionalClaims.target_audience) { + const { tokens } = await this.refreshToken(); + return { + headers: this.addSharedMetadataHeaders({ + Authorization: `Bearer ${tokens.id_token}`, + }), + }; + } + else { + // no scopes have been set, but a uri has been provided. Use JWTAccess + // credentials. + if (!this.access) { + this.access = new jwtaccess_1.JWTAccess(this.email, this.key, this.keyId, this.eagerRefreshThresholdMillis); + } + let scopes; + if (this.hasUserScopes()) { + scopes = this.scopes; + } + else if (!url) { + scopes = this.defaultScopes; + } + const useScopes = this.useJWTAccessWithScope || + this.universeDomain !== authclient_1.DEFAULT_UNIVERSE; + const headers = await this.access.getRequestHeaders(url !== null && url !== void 0 ? url : undefined, this.additionalClaims, + // Scopes take precedent over audience for signing, + // so we only provide them if `useJWTAccessWithScope` is on or + // if we are in a non-default universe + useScopes ? scopes : undefined); + return { headers: this.addSharedMetadataHeaders(headers) }; + } + } + else if (this.hasAnyScopes() || this.apiKey) { + return super.getRequestMetadataAsync(url); + } + else { + // If no audience, apiKey, or scopes are provided, we should not attempt + // to populate any headers: + return { headers: {} }; + } + } + /** + * Fetches an ID token. + * @param targetAudience the audience for the fetched ID token. + */ + async fetchIdToken(targetAudience) { + // Create a new gToken for fetching an ID token + const gtoken = new gtoken_1.GoogleToken({ + iss: this.email, + sub: this.subject, + scope: this.scopes || this.defaultScopes, + keyFile: this.keyFile, + key: this.key, + additionalClaims: { target_audience: targetAudience }, + transporter: this.transporter, + }); + await gtoken.getToken({ + forceRefresh: true, + }); + if (!gtoken.idToken) { + throw new Error('Unknown error: Failed to fetch ID token'); + } + return gtoken.idToken; + } + /** + * Determine if there are currently scopes available. + */ + hasUserScopes() { + if (!this.scopes) { + return false; + } + return this.scopes.length > 0; + } + /** + * Are there any default or user scopes defined. + */ + hasAnyScopes() { + if (this.scopes && this.scopes.length > 0) + return true; + if (this.defaultScopes && this.defaultScopes.length > 0) + return true; + return false; + } + authorize(callback) { + if (callback) { + this.authorizeAsync().then(r => callback(null, r), callback); + } + else { + return this.authorizeAsync(); + } + } + async authorizeAsync() { + const result = await this.refreshToken(); + if (!result) { + throw new Error('No result returned'); + } + this.credentials = result.tokens; + this.credentials.refresh_token = 'jwt-placeholder'; + this.key = this.gtoken.key; + this.email = this.gtoken.iss; + return result.tokens; + } + /** + * Refreshes the access token. + * @param refreshToken ignored + * @private + */ + async refreshTokenNoCache( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + refreshToken) { + const gtoken = this.createGToken(); + const token = await gtoken.getToken({ + forceRefresh: this.isTokenExpiring(), + }); + const tokens = { + access_token: token.access_token, + token_type: 'Bearer', + expiry_date: gtoken.expiresAt, + id_token: gtoken.idToken, + }; + this.emit('tokens', tokens); + return { res: null, tokens }; + } + /** + * Create a gToken if it doesn't already exist. + */ + createGToken() { + if (!this.gtoken) { + this.gtoken = new gtoken_1.GoogleToken({ + iss: this.email, + sub: this.subject, + scope: this.scopes || this.defaultScopes, + keyFile: this.keyFile, + key: this.key, + additionalClaims: this.additionalClaims, + transporter: this.transporter, + }); + } + return this.gtoken; + } + /** + * Create a JWT credentials instance using the given input options. + * @param json The input object. + * + * @remarks + * + * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}. + */ + fromJSON(json) { + if (!json) { + throw new Error('Must pass in a JSON object containing the service account auth settings.'); + } + if (!json.client_email) { + throw new Error('The incoming JSON object does not contain a client_email field'); + } + if (!json.private_key) { + throw new Error('The incoming JSON object does not contain a private_key field'); + } + // Extract the relevant information from the json key file. + this.email = json.client_email; + this.key = json.private_key; + this.keyId = json.private_key_id; + this.projectId = json.project_id; + this.quotaProjectId = json.quota_project_id; + this.universeDomain = json.universe_domain || this.universeDomain; + } + fromStream(inputStream, callback) { + if (callback) { + this.fromStreamAsync(inputStream).then(() => callback(), callback); + } + else { + return this.fromStreamAsync(inputStream); + } + } + fromStreamAsync(inputStream) { + return new Promise((resolve, reject) => { + if (!inputStream) { + throw new Error('Must pass in a stream containing the service account auth settings.'); + } + let s = ''; + inputStream + .setEncoding('utf8') + .on('error', reject) + .on('data', chunk => (s += chunk)) + .on('end', () => { + try { + const data = JSON.parse(s); + this.fromJSON(data); + resolve(); + } + catch (e) { + reject(e); + } + }); + }); + } + /** + * Creates a JWT credentials instance using an API Key for authentication. + * @param apiKey The API Key in string form. + */ + fromAPIKey(apiKey) { + if (typeof apiKey !== 'string') { + throw new Error('Must provide an API Key string.'); + } + this.apiKey = apiKey; + } + /** + * Using the key or keyFile on the JWT client, obtain an object that contains + * the key and the client email. + */ + async getCredentials() { + if (this.key) { + return { private_key: this.key, client_email: this.email }; + } + else if (this.keyFile) { + const gtoken = this.createGToken(); + const creds = await gtoken.getCredentials(this.keyFile); + return { private_key: creds.privateKey, client_email: creds.clientEmail }; + } + throw new Error('A key or a keyFile must be provided to getCredentials.'); + } +} +exports.JWT = JWT; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/loginticket.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/loginticket.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..33fd407a648d7904313936ccd016d81324a1a3fb --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/loginticket.d.ts @@ -0,0 +1,140 @@ +export declare class LoginTicket { + private envelope?; + private payload?; + /** + * Create a simple class to extract user ID from an ID Token + * + * @param {string} env Envelope of the jwt + * @param {TokenPayload} pay Payload of the jwt + * @constructor + */ + constructor(env?: string, pay?: TokenPayload); + getEnvelope(): string | undefined; + getPayload(): TokenPayload | undefined; + /** + * Create a simple class to extract user ID from an ID Token + * + * @return The user ID + */ + getUserId(): string | null; + /** + * Returns attributes from the login ticket. This can contain + * various information about the user session. + * + * @return The envelope and payload + */ + getAttributes(): { + envelope: string | undefined; + payload: TokenPayload | undefined; + }; +} +export interface TokenPayload { + /** + * The Issuer Identifier for the Issuer of the response. Always + * https://accounts.google.com or accounts.google.com for Google ID tokens. + */ + iss: string; + /** + * Access token hash. Provides validation that the access token is tied to the + * identity token. If the ID token is issued with an access token in the + * server flow, this is always included. This can be used as an alternate + * mechanism to protect against cross-site request forgery attacks, but if you + * follow Step 1 and Step 3 it is not necessary to verify the access token. + */ + at_hash?: string; + /** + * True if the user's e-mail address has been verified; otherwise false. + */ + email_verified?: boolean; + /** + * An identifier for the user, unique among all Google accounts and never + * reused. A Google account can have multiple emails at different points in + * time, but the sub value is never changed. Use sub within your application + * as the unique-identifier key for the user. + */ + sub: string; + /** + * The client_id of the authorized presenter. This claim is only needed when + * the party requesting the ID token is not the same as the audience of the ID + * token. This may be the case at Google for hybrid apps where a web + * application and Android app have a different client_id but share the same + * project. + */ + azp?: string; + /** + * The user's email address. This may not be unique and is not suitable for + * use as a primary key. Provided only if your scope included the string + * "email". + */ + email?: string; + /** + * The URL of the user's profile page. Might be provided when: + * - The request scope included the string "profile" + * - The ID token is returned from a token refresh + * - When profile claims are present, you can use them to update your app's + * user records. Note that this claim is never guaranteed to be present. + */ + profile?: string; + /** + * The URL of the user's profile picture. Might be provided when: + * - The request scope included the string "profile" + * - The ID token is returned from a token refresh + * - When picture claims are present, you can use them to update your app's + * user records. Note that this claim is never guaranteed to be present. + */ + picture?: string; + /** + * The user's full name, in a displayable form. Might be provided when: + * - The request scope included the string "profile" + * - The ID token is returned from a token refresh + * - When name claims are present, you can use them to update your app's user + * records. Note that this claim is never guaranteed to be present. + */ + name?: string; + /** + * The user's given name, in a displayable form. Might be provided when: + * - The request scope included the string "profile" + * - The ID token is returned from a token refresh + * - When name claims are present, you can use them to update your app's user + * records. Note that this claim is never guaranteed to be present. + */ + given_name?: string; + /** + * The user's family name, in a displayable form. Might be provided when: + * - The request scope included the string "profile" + * - The ID token is returned from a token refresh + * - When name claims are present, you can use them to update your app's user + * records. Note that this claim is never guaranteed to be present. + */ + family_name?: string; + /** + * Identifies the audience that this ID token is intended for. It must be one + * of the OAuth 2.0 client IDs of your application. + */ + aud: string; + /** + * The time the ID token was issued, represented in Unix time (integer + * seconds). + */ + iat: number; + /** + * The time the ID token expires, represented in Unix time (integer seconds). + */ + exp: number; + /** + * The value of the nonce supplied by your app in the authentication request. + * You should enforce protection against replay attacks by ensuring it is + * presented only once. + */ + nonce?: string; + /** + * The hosted G Suite domain of the user. Provided only if the user belongs to + * a hosted domain. + */ + hd?: string; + /** + * The user's locale, represented by a BCP 47 language tag. + * Might be provided when a name claim is present. + */ + locale?: string; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/loginticket.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/loginticket.js new file mode 100644 index 0000000000000000000000000000000000000000..9a1687b6841e1bca24800f480d950a099fcf64fb --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/loginticket.js @@ -0,0 +1,57 @@ +"use strict"; +// Copyright 2014 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LoginTicket = void 0; +class LoginTicket { + /** + * Create a simple class to extract user ID from an ID Token + * + * @param {string} env Envelope of the jwt + * @param {TokenPayload} pay Payload of the jwt + * @constructor + */ + constructor(env, pay) { + this.envelope = env; + this.payload = pay; + } + getEnvelope() { + return this.envelope; + } + getPayload() { + return this.payload; + } + /** + * Create a simple class to extract user ID from an ID Token + * + * @return The user ID + */ + getUserId() { + const payload = this.getPayload(); + if (payload && payload.sub) { + return payload.sub; + } + return null; + } + /** + * Returns attributes from the login ticket. This can contain + * various information about the user session. + * + * @return The envelope and payload + */ + getAttributes() { + return { envelope: this.getEnvelope(), payload: this.getPayload() }; + } +} +exports.LoginTicket = LoginTicket; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/oauth2client.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/oauth2client.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7080d080a99d8b9d5e43b9d615d50dadfe0a18e2 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/oauth2client.d.ts @@ -0,0 +1,575 @@ +import { GaxiosError, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +import * as querystring from 'querystring'; +import { JwkCertificate } from '../crypto/crypto'; +import { BodyResponseCallback } from '../transporters'; +import { AuthClient, AuthClientOptions } from './authclient'; +import { Credentials } from './credentials'; +import { LoginTicket } from './loginticket'; +/** + * The results from the `generateCodeVerifierAsync` method. To learn more, + * See the sample: + * https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js + */ +export interface CodeVerifierResults { + /** + * The code verifier that will be used when calling `getToken` to obtain a new + * access token. + */ + codeVerifier: string; + /** + * The code_challenge that should be sent with the `generateAuthUrl` call + * to obtain a verifiable authentication url. + */ + codeChallenge?: string; +} +export interface Certificates { + [index: string]: string | JwkCertificate; +} +export interface PublicKeys { + [index: string]: string; +} +export interface Headers { + [index: string]: string; +} +export declare enum CodeChallengeMethod { + Plain = "plain", + S256 = "S256" +} +export declare enum CertificateFormat { + PEM = "PEM", + JWK = "JWK" +} +/** + * The client authentication type. Supported values are basic, post, and none. + * https://datatracker.ietf.org/doc/html/rfc7591#section-2 + */ +export declare enum ClientAuthentication { + ClientSecretPost = "ClientSecretPost", + ClientSecretBasic = "ClientSecretBasic", + None = "None" +} +export interface GetTokenOptions { + code: string; + codeVerifier?: string; + /** + * The client ID for your application. The value passed into the constructor + * will be used if not provided. Must match any client_id option passed to + * a corresponding call to generateAuthUrl. + */ + client_id?: string; + /** + * Determines where the API server redirects the user after the user + * completes the authorization flow. The value passed into the constructor + * will be used if not provided. Must match any redirect_uri option passed to + * a corresponding call to generateAuthUrl. + */ + redirect_uri?: string; +} +export interface TokenInfo { + /** + * The application that is the intended user of the access token. + */ + aud: string; + /** + * This value lets you correlate profile information from multiple Google + * APIs. It is only present in the response if you included the profile scope + * in your request in step 1. The field value is an immutable identifier for + * the logged-in user that can be used to create and manage user sessions in + * your application. The identifier is the same regardless of which client ID + * is used to retrieve it. This enables multiple applications in the same + * organization to correlate profile information. + */ + user_id?: string; + /** + * An array of scopes that the user granted access to. + */ + scopes: string[]; + /** + * The datetime when the token becomes invalid. + */ + expiry_date: number; + /** + * An identifier for the user, unique among all Google accounts and never + * reused. A Google account can have multiple emails at different points in + * time, but the sub value is never changed. Use sub within your application + * as the unique-identifier key for the user. + */ + sub?: string; + /** + * The client_id of the authorized presenter. This claim is only needed when + * the party requesting the ID token is not the same as the audience of the ID + * token. This may be the case at Google for hybrid apps where a web + * application and Android app have a different client_id but share the same + * project. + */ + azp?: string; + /** + * Indicates whether your application can refresh access tokens + * when the user is not present at the browser. Valid parameter values are + * 'online', which is the default value, and 'offline'. Set the value to + * 'offline' if your application needs to refresh access tokens when the user + * is not present at the browser. This value instructs the Google + * authorization server to return a refresh token and an access token the + * first time that your application exchanges an authorization code for + * tokens. + */ + access_type?: string; + /** + * The user's email address. This value may not be unique to this user and + * is not suitable for use as a primary key. Provided only if your scope + * included the email scope value. + */ + email?: string; + /** + * True if the user's e-mail address has been verified; otherwise false. + */ + email_verified?: boolean; +} +export interface GenerateAuthUrlOpts { + /** + * Recommended. Indicates whether your application can refresh access tokens + * when the user is not present at the browser. Valid parameter values are + * 'online', which is the default value, and 'offline'. Set the value to + * 'offline' if your application needs to refresh access tokens when the user + * is not present at the browser. This value instructs the Google + * authorization server to return a refresh token and an access token the + * first time that your application exchanges an authorization code for + * tokens. + */ + access_type?: string; + /** + * The hd (hosted domain) parameter streamlines the login process for G Suite + * hosted accounts. By including the domain of the G Suite user (for example, + * mycollege.edu), you can indicate that the account selection UI should be + * optimized for accounts at that domain. To optimize for G Suite accounts + * generally instead of just one domain, use an asterisk: hd=*. + * Don't rely on this UI optimization to control who can access your app, + * as client-side requests can be modified. Be sure to validate that the + * returned ID token has an hd claim value that matches what you expect + * (e.g. mycolledge.edu). Unlike the request parameter, the ID token claim is + * contained within a security token from Google, so the value can be trusted. + */ + hd?: string; + /** + * The 'response_type' will always be set to 'CODE'. + */ + response_type?: string; + /** + * The client ID for your application. The value passed into the constructor + * will be used if not provided. You can find this value in the API Console. + */ + client_id?: string; + /** + * Determines where the API server redirects the user after the user + * completes the authorization flow. The value must exactly match one of the + * 'redirect_uri' values listed for your project in the API Console. Note that + * the http or https scheme, case, and trailing slash ('/') must all match. + * The value passed into the constructor will be used if not provided. + */ + redirect_uri?: string; + /** + * Required. A space-delimited list of scopes that identify the resources that + * your application could access on the user's behalf. These values inform the + * consent screen that Google displays to the user. Scopes enable your + * application to only request access to the resources that it needs while + * also enabling users to control the amount of access that they grant to your + * application. Thus, there is an inverse relationship between the number of + * scopes requested and the likelihood of obtaining user consent. The + * OAuth 2.0 API Scopes document provides a full list of scopes that you might + * use to access Google APIs. We recommend that your application request + * access to authorization scopes in context whenever possible. By requesting + * access to user data in context, via incremental authorization, you help + * users to more easily understand why your application needs the access it is + * requesting. + */ + scope?: string[] | string; + /** + * Recommended. Specifies any string value that your application uses to + * maintain state between your authorization request and the authorization + * server's response. The server returns the exact value that you send as a + * name=value pair in the hash (#) fragment of the 'redirect_uri' after the + * user consents to or denies your application's access request. You can use + * this parameter for several purposes, such as directing the user to the + * correct resource in your application, sending nonces, and mitigating + * cross-site request forgery. Since your redirect_uri can be guessed, using a + * state value can increase your assurance that an incoming connection is the + * result of an authentication request. If you generate a random string or + * encode the hash of a cookie or another value that captures the client's + * state, you can validate the response to additionally ensure that the + * request and response originated in the same browser, providing protection + * against attacks such as cross-site request forgery. See the OpenID Connect + * documentation for an example of how to create and confirm a state token. + */ + state?: string; + /** + * Optional. Enables applications to use incremental authorization to request + * access to additional scopes in context. If you set this parameter's value + * to true and the authorization request is granted, then the new access token + * will also cover any scopes to which the user previously granted the + * application access. See the incremental authorization section for examples. + */ + include_granted_scopes?: boolean; + /** + * Optional. If your application knows which user is trying to authenticate, + * it can use this parameter to provide a hint to the Google Authentication + * Server. The server uses the hint to simplify the login flow either by + * prefilling the email field in the sign-in form or by selecting the + * appropriate multi-login session. Set the parameter value to an email + * address or sub identifier, which is equivalent to the user's Google ID. + */ + login_hint?: string; + /** + * Optional. A space-delimited, case-sensitive list of prompts to present the + * user. If you don't specify this parameter, the user will be prompted only + * the first time your app requests access. Possible values are: + * + * 'none' - Donot display any authentication or consent screens. Must not be + * specified with other values. + * 'consent' - Prompt the user for consent. + * 'select_account' - Prompt the user to select an account. + */ + prompt?: string; + /** + * Recommended. Specifies what method was used to encode a 'code_verifier' + * that will be used during authorization code exchange. This parameter must + * be used with the 'code_challenge' parameter. The value of the + * 'code_challenge_method' defaults to "plain" if not present in the request + * that includes a 'code_challenge'. The only supported values for this + * parameter are "S256" or "plain". + */ + code_challenge_method?: CodeChallengeMethod; + /** + * Recommended. Specifies an encoded 'code_verifier' that will be used as a + * server-side challenge during authorization code exchange. This parameter + * must be used with the 'code_challenge' parameter described above. + */ + code_challenge?: string; + /** + * A way for developers and/or the auth team to provide a set of key value + * pairs to be added as query parameters to the authorization url. + */ + [key: string]: querystring.ParsedUrlQueryInput[keyof querystring.ParsedUrlQueryInput]; +} +export interface AccessTokenResponse { + access_token: string; + expiry_date: number; +} +export interface GetRefreshHandlerCallback { + (): Promise; +} +export interface GetTokenCallback { + (err: GaxiosError | null, token?: Credentials | null, res?: GaxiosResponse | null): void; +} +export interface GetTokenResponse { + tokens: Credentials; + res: GaxiosResponse | null; +} +export interface GetAccessTokenCallback { + (err: GaxiosError | null, token?: string | null, res?: GaxiosResponse | null): void; +} +export interface GetAccessTokenResponse { + token?: string | null; + res?: GaxiosResponse | null; +} +export interface RefreshAccessTokenCallback { + (err: GaxiosError | null, credentials?: Credentials | null, res?: GaxiosResponse | null): void; +} +export interface RefreshAccessTokenResponse { + credentials: Credentials; + res: GaxiosResponse | null; +} +export interface RequestMetadataResponse { + headers: Headers; + res?: GaxiosResponse | null; +} +export interface RequestMetadataCallback { + (err: GaxiosError | null, headers?: Headers, res?: GaxiosResponse | null): void; +} +export interface GetFederatedSignonCertsCallback { + (err: GaxiosError | null, certs?: Certificates, response?: GaxiosResponse | null): void; +} +export interface FederatedSignonCertsResponse { + certs: Certificates; + format: CertificateFormat; + res?: GaxiosResponse | null; +} +export interface GetIapPublicKeysCallback { + (err: GaxiosError | null, pubkeys?: PublicKeys, response?: GaxiosResponse | null): void; +} +export interface IapPublicKeysResponse { + pubkeys: PublicKeys; + res?: GaxiosResponse | null; +} +export interface RevokeCredentialsResult { + success: boolean; +} +export interface VerifyIdTokenOptions { + idToken: string; + audience?: string | string[]; + maxExpiry?: number; +} +export interface OAuth2ClientEndpoints { + /** + * The endpoint for viewing access token information + * + * @example + * 'https://oauth2.googleapis.com/tokeninfo' + */ + tokenInfoUrl: string | URL; + /** + * The base URL for auth endpoints. + * + * @example + * 'https://accounts.google.com/o/oauth2/v2/auth' + */ + oauth2AuthBaseUrl: string | URL; + /** + * The base endpoint for token retrieval + * . + * @example + * 'https://oauth2.googleapis.com/token' + */ + oauth2TokenUrl: string | URL; + /** + * The base endpoint to revoke tokens. + * + * @example + * 'https://oauth2.googleapis.com/revoke' + */ + oauth2RevokeUrl: string | URL; + /** + * Sign on certificates in PEM format. + * + * @example + * 'https://www.googleapis.com/oauth2/v1/certs' + */ + oauth2FederatedSignonPemCertsUrl: string | URL; + /** + * Sign on certificates in JWK format. + * + * @example + * 'https://www.googleapis.com/oauth2/v3/certs' + */ + oauth2FederatedSignonJwkCertsUrl: string | URL; + /** + * IAP Public Key URL. + * This URL contains a JSON dictionary that maps the `kid` claims to the public key values. + * + * @example + * 'https://www.gstatic.com/iap/verify/public_key' + */ + oauth2IapPublicKeyUrl: string | URL; +} +export interface OAuth2ClientOptions extends AuthClientOptions { + clientId?: string; + clientSecret?: string; + redirectUri?: string; + /** + * Customizable endpoints. + */ + endpoints?: Partial; + /** + * The allowed OAuth2 token issuers. + */ + issuers?: string[]; + /** + * The client authentication type. Supported values are basic, post, and none. + * Defaults to post if not provided. + * https://datatracker.ietf.org/doc/html/rfc7591#section-2 + */ + clientAuthentication?: ClientAuthentication; +} +export type RefreshOptions = Pick; +export declare class OAuth2Client extends AuthClient { + private redirectUri?; + private certificateCache; + private certificateExpiry; + private certificateCacheFormat; + protected refreshTokenPromises: Map>; + readonly endpoints: Readonly; + readonly issuers: string[]; + readonly clientAuthentication: ClientAuthentication; + _clientId?: string; + _clientSecret?: string; + refreshHandler?: GetRefreshHandlerCallback; + /** + * Handles OAuth2 flow for Google APIs. + * + * @param clientId The authentication client ID. + * @param clientSecret The authentication client secret. + * @param redirectUri The URI to redirect to after completing the auth + * request. + * @param opts optional options for overriding the given parameters. + * @constructor + */ + constructor(options?: OAuth2ClientOptions); + constructor(clientId?: string, clientSecret?: string, redirectUri?: string); + /** + * @deprecated use instance's {@link OAuth2Client.endpoints} + */ + protected static readonly GOOGLE_TOKEN_INFO_URL = "https://oauth2.googleapis.com/tokeninfo"; + /** + * Clock skew - five minutes in seconds + */ + private static readonly CLOCK_SKEW_SECS_; + /** + * The default max Token Lifetime is one day in seconds + */ + private static readonly DEFAULT_MAX_TOKEN_LIFETIME_SECS_; + /** + * Generates URL for consent page landing. + * @param opts Options. + * @return URL to consent page. + */ + generateAuthUrl(opts?: GenerateAuthUrlOpts): string; + generateCodeVerifier(): void; + /** + * Convenience method to automatically generate a code_verifier, and its + * resulting SHA256. If used, this must be paired with a S256 + * code_challenge_method. + * + * For a full example see: + * https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js + */ + generateCodeVerifierAsync(): Promise; + /** + * Gets the access token for the given code. + * @param code The authorization code. + * @param callback Optional callback fn. + */ + getToken(code: string): Promise; + getToken(options: GetTokenOptions): Promise; + getToken(code: string, callback: GetTokenCallback): void; + getToken(options: GetTokenOptions, callback: GetTokenCallback): void; + private getTokenAsync; + /** + * Refreshes the access token. + * @param refresh_token Existing refresh token. + * @private + */ + protected refreshToken(refreshToken?: string | null): Promise; + protected refreshTokenNoCache(refreshToken?: string | null): Promise; + /** + * Retrieves the access token using refresh token + * + * @param callback callback + */ + refreshAccessToken(): Promise; + refreshAccessToken(callback: RefreshAccessTokenCallback): void; + private refreshAccessTokenAsync; + /** + * Get a non-expired access token, after refreshing if necessary + * + * @param callback Callback to call with the access token + */ + getAccessToken(): Promise; + getAccessToken(callback: GetAccessTokenCallback): void; + private getAccessTokenAsync; + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * In OAuth2Client, the result has the form: + * { Authorization: 'Bearer ' } + * @param url The optional url being authorized + */ + getRequestHeaders(url?: string): Promise; + protected getRequestMetadataAsync(url?: string | URL | null): Promise; + /** + * Generates an URL to revoke the given token. + * @param token The existing token to be revoked. + * + * @deprecated use instance method {@link OAuth2Client.getRevokeTokenURL} + */ + static getRevokeTokenUrl(token: string): string; + /** + * Generates a URL to revoke the given token. + * + * @param token The existing token to be revoked. + */ + getRevokeTokenURL(token: string): URL; + /** + * Revokes the access given to token. + * @param token The existing token to be revoked. + * @param callback Optional callback fn. + */ + revokeToken(token: string): GaxiosPromise; + revokeToken(token: string, callback: BodyResponseCallback): void; + /** + * Revokes access token and clears the credentials object + * @param callback callback + */ + revokeCredentials(): GaxiosPromise; + revokeCredentials(callback: BodyResponseCallback): void; + private revokeCredentialsAsync; + /** + * Provides a request implementation with OAuth 2.0 flow. If credentials have + * a refresh_token, in cases of HTTP 401 and 403 responses, it automatically + * asks for a new access token and replays the unsuccessful request. + * @param opts Request options. + * @param callback callback. + * @return Request object + */ + request(opts: GaxiosOptions): GaxiosPromise; + request(opts: GaxiosOptions, callback: BodyResponseCallback): void; + protected requestAsync(opts: GaxiosOptions, reAuthRetried?: boolean): Promise>; + /** + * Verify id token is token by checking the certs and audience + * @param options that contains all options. + * @param callback Callback supplying GoogleLogin if successful + */ + verifyIdToken(options: VerifyIdTokenOptions): Promise; + verifyIdToken(options: VerifyIdTokenOptions, callback: (err: Error | null, login?: LoginTicket) => void): void; + private verifyIdTokenAsync; + /** + * Obtains information about the provisioned access token. Especially useful + * if you want to check the scopes that were provisioned to a given token. + * + * @param accessToken Required. The Access Token for which you want to get + * user info. + */ + getTokenInfo(accessToken: string): Promise; + /** + * Gets federated sign-on certificates to use for verifying identity tokens. + * Returns certs as array structure, where keys are key ids, and values + * are certificates in either PEM or JWK format. + * @param callback Callback supplying the certificates + */ + getFederatedSignonCerts(): Promise; + getFederatedSignonCerts(callback: GetFederatedSignonCertsCallback): void; + getFederatedSignonCertsAsync(): Promise; + /** + * Gets federated sign-on certificates to use for verifying identity tokens. + * Returns certs as array structure, where keys are key ids, and values + * are certificates in either PEM or JWK format. + * @param callback Callback supplying the certificates + */ + getIapPublicKeys(): Promise; + getIapPublicKeys(callback: GetIapPublicKeysCallback): void; + getIapPublicKeysAsync(): Promise; + verifySignedJwtWithCerts(): void; + /** + * Verify the id token is signed with the correct certificate + * and is from the correct audience. + * @param jwt The jwt to verify (The ID Token in this case). + * @param certs The array of certs to test the jwt against. + * @param requiredAudience The audience to test the jwt against. + * @param issuers The allowed issuers of the jwt (Optional). + * @param maxExpiry The max expiry the certificate can be (Optional). + * @return Returns a promise resolving to LoginTicket on verification. + */ + verifySignedJwtWithCertsAsync(jwt: string, certs: Certificates | PublicKeys, requiredAudience?: string | string[], issuers?: string[], maxExpiry?: number): Promise; + /** + * Returns a promise that resolves with AccessTokenResponse type if + * refreshHandler is defined. + * If not, nothing is returned. + */ + private processAndValidateRefreshHandler; + /** + * Returns true if a token is expired or will expire within + * eagerRefreshThresholdMillismilliseconds. + * If there is no expiry time, assumes the token is not expired or expiring. + */ + protected isTokenExpiring(): boolean; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/oauth2client.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/oauth2client.js new file mode 100644 index 0000000000000000000000000000000000000000..3764bda9358fb44853cfff358495caec0f59ae56 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/oauth2client.js @@ -0,0 +1,794 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OAuth2Client = exports.ClientAuthentication = exports.CertificateFormat = exports.CodeChallengeMethod = void 0; +const gaxios_1 = require("gaxios"); +const querystring = require("querystring"); +const stream = require("stream"); +const formatEcdsa = require("ecdsa-sig-formatter"); +const crypto_1 = require("../crypto/crypto"); +const authclient_1 = require("./authclient"); +const loginticket_1 = require("./loginticket"); +var CodeChallengeMethod; +(function (CodeChallengeMethod) { + CodeChallengeMethod["Plain"] = "plain"; + CodeChallengeMethod["S256"] = "S256"; +})(CodeChallengeMethod || (exports.CodeChallengeMethod = CodeChallengeMethod = {})); +var CertificateFormat; +(function (CertificateFormat) { + CertificateFormat["PEM"] = "PEM"; + CertificateFormat["JWK"] = "JWK"; +})(CertificateFormat || (exports.CertificateFormat = CertificateFormat = {})); +/** + * The client authentication type. Supported values are basic, post, and none. + * https://datatracker.ietf.org/doc/html/rfc7591#section-2 + */ +var ClientAuthentication; +(function (ClientAuthentication) { + ClientAuthentication["ClientSecretPost"] = "ClientSecretPost"; + ClientAuthentication["ClientSecretBasic"] = "ClientSecretBasic"; + ClientAuthentication["None"] = "None"; +})(ClientAuthentication || (exports.ClientAuthentication = ClientAuthentication = {})); +class OAuth2Client extends authclient_1.AuthClient { + constructor(optionsOrClientId, clientSecret, redirectUri) { + const opts = optionsOrClientId && typeof optionsOrClientId === 'object' + ? optionsOrClientId + : { clientId: optionsOrClientId, clientSecret, redirectUri }; + super(opts); + this.certificateCache = {}; + this.certificateExpiry = null; + this.certificateCacheFormat = CertificateFormat.PEM; + this.refreshTokenPromises = new Map(); + this._clientId = opts.clientId; + this._clientSecret = opts.clientSecret; + this.redirectUri = opts.redirectUri; + this.endpoints = { + tokenInfoUrl: 'https://oauth2.googleapis.com/tokeninfo', + oauth2AuthBaseUrl: 'https://accounts.google.com/o/oauth2/v2/auth', + oauth2TokenUrl: 'https://oauth2.googleapis.com/token', + oauth2RevokeUrl: 'https://oauth2.googleapis.com/revoke', + oauth2FederatedSignonPemCertsUrl: 'https://www.googleapis.com/oauth2/v1/certs', + oauth2FederatedSignonJwkCertsUrl: 'https://www.googleapis.com/oauth2/v3/certs', + oauth2IapPublicKeyUrl: 'https://www.gstatic.com/iap/verify/public_key', + ...opts.endpoints, + }; + this.clientAuthentication = + opts.clientAuthentication || ClientAuthentication.ClientSecretPost; + this.issuers = opts.issuers || [ + 'accounts.google.com', + 'https://accounts.google.com', + this.universeDomain, + ]; + } + /** + * Generates URL for consent page landing. + * @param opts Options. + * @return URL to consent page. + */ + generateAuthUrl(opts = {}) { + if (opts.code_challenge_method && !opts.code_challenge) { + throw new Error('If a code_challenge_method is provided, code_challenge must be included.'); + } + opts.response_type = opts.response_type || 'code'; + opts.client_id = opts.client_id || this._clientId; + opts.redirect_uri = opts.redirect_uri || this.redirectUri; + // Allow scopes to be passed either as array or a string + if (Array.isArray(opts.scope)) { + opts.scope = opts.scope.join(' '); + } + const rootUrl = this.endpoints.oauth2AuthBaseUrl.toString(); + return (rootUrl + + '?' + + querystring.stringify(opts)); + } + generateCodeVerifier() { + // To make the code compatible with browser SubtleCrypto we need to make + // this method async. + throw new Error('generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.'); + } + /** + * Convenience method to automatically generate a code_verifier, and its + * resulting SHA256. If used, this must be paired with a S256 + * code_challenge_method. + * + * For a full example see: + * https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js + */ + async generateCodeVerifierAsync() { + // base64 encoding uses 6 bits per character, and we want to generate128 + // characters. 6*128/8 = 96. + const crypto = (0, crypto_1.createCrypto)(); + const randomString = crypto.randomBytesBase64(96); + // The valid characters in the code_verifier are [A-Z]/[a-z]/[0-9]/ + // "-"/"."/"_"/"~". Base64 encoded strings are pretty close, so we're just + // swapping out a few chars. + const codeVerifier = randomString + .replace(/\+/g, '~') + .replace(/=/g, '_') + .replace(/\//g, '-'); + // Generate the base64 encoded SHA256 + const unencodedCodeChallenge = await crypto.sha256DigestBase64(codeVerifier); + // We need to use base64UrlEncoding instead of standard base64 + const codeChallenge = unencodedCodeChallenge + .split('=')[0] + .replace(/\+/g, '-') + .replace(/\//g, '_'); + return { codeVerifier, codeChallenge }; + } + getToken(codeOrOptions, callback) { + const options = typeof codeOrOptions === 'string' ? { code: codeOrOptions } : codeOrOptions; + if (callback) { + this.getTokenAsync(options).then(r => callback(null, r.tokens, r.res), e => callback(e, null, e.response)); + } + else { + return this.getTokenAsync(options); + } + } + async getTokenAsync(options) { + const url = this.endpoints.oauth2TokenUrl.toString(); + const headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + }; + const values = { + client_id: options.client_id || this._clientId, + code_verifier: options.codeVerifier, + code: options.code, + grant_type: 'authorization_code', + redirect_uri: options.redirect_uri || this.redirectUri, + }; + if (this.clientAuthentication === ClientAuthentication.ClientSecretBasic) { + const basic = Buffer.from(`${this._clientId}:${this._clientSecret}`); + headers['Authorization'] = `Basic ${basic.toString('base64')}`; + } + if (this.clientAuthentication === ClientAuthentication.ClientSecretPost) { + values.client_secret = this._clientSecret; + } + const res = await this.transporter.request({ + ...OAuth2Client.RETRY_CONFIG, + method: 'POST', + url, + data: querystring.stringify(values), + headers, + }); + const tokens = res.data; + if (res.data && res.data.expires_in) { + tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000; + delete tokens.expires_in; + } + this.emit('tokens', tokens); + return { tokens, res }; + } + /** + * Refreshes the access token. + * @param refresh_token Existing refresh token. + * @private + */ + async refreshToken(refreshToken) { + if (!refreshToken) { + return this.refreshTokenNoCache(refreshToken); + } + // If a request to refresh using the same token has started, + // return the same promise. + if (this.refreshTokenPromises.has(refreshToken)) { + return this.refreshTokenPromises.get(refreshToken); + } + const p = this.refreshTokenNoCache(refreshToken).then(r => { + this.refreshTokenPromises.delete(refreshToken); + return r; + }, e => { + this.refreshTokenPromises.delete(refreshToken); + throw e; + }); + this.refreshTokenPromises.set(refreshToken, p); + return p; + } + async refreshTokenNoCache(refreshToken) { + var _a; + if (!refreshToken) { + throw new Error('No refresh token is set.'); + } + const url = this.endpoints.oauth2TokenUrl.toString(); + const data = { + refresh_token: refreshToken, + client_id: this._clientId, + client_secret: this._clientSecret, + grant_type: 'refresh_token', + }; + let res; + try { + // request for new token + res = await this.transporter.request({ + ...OAuth2Client.RETRY_CONFIG, + method: 'POST', + url, + data: querystring.stringify(data), + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + }); + } + catch (e) { + if (e instanceof gaxios_1.GaxiosError && + e.message === 'invalid_grant' && + ((_a = e.response) === null || _a === void 0 ? void 0 : _a.data) && + /ReAuth/i.test(e.response.data.error_description)) { + e.message = JSON.stringify(e.response.data); + } + throw e; + } + const tokens = res.data; + // TODO: de-duplicate this code from a few spots + if (res.data && res.data.expires_in) { + tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000; + delete tokens.expires_in; + } + this.emit('tokens', tokens); + return { tokens, res }; + } + refreshAccessToken(callback) { + if (callback) { + this.refreshAccessTokenAsync().then(r => callback(null, r.credentials, r.res), callback); + } + else { + return this.refreshAccessTokenAsync(); + } + } + async refreshAccessTokenAsync() { + const r = await this.refreshToken(this.credentials.refresh_token); + const tokens = r.tokens; + tokens.refresh_token = this.credentials.refresh_token; + this.credentials = tokens; + return { credentials: this.credentials, res: r.res }; + } + getAccessToken(callback) { + if (callback) { + this.getAccessTokenAsync().then(r => callback(null, r.token, r.res), callback); + } + else { + return this.getAccessTokenAsync(); + } + } + async getAccessTokenAsync() { + const shouldRefresh = !this.credentials.access_token || this.isTokenExpiring(); + if (shouldRefresh) { + if (!this.credentials.refresh_token) { + if (this.refreshHandler) { + const refreshedAccessToken = await this.processAndValidateRefreshHandler(); + if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) { + this.setCredentials(refreshedAccessToken); + return { token: this.credentials.access_token }; + } + } + else { + throw new Error('No refresh token or refresh handler callback is set.'); + } + } + const r = await this.refreshAccessTokenAsync(); + if (!r.credentials || (r.credentials && !r.credentials.access_token)) { + throw new Error('Could not refresh access token.'); + } + return { token: r.credentials.access_token, res: r.res }; + } + else { + return { token: this.credentials.access_token }; + } + } + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * In OAuth2Client, the result has the form: + * { Authorization: 'Bearer ' } + * @param url The optional url being authorized + */ + async getRequestHeaders(url) { + const headers = (await this.getRequestMetadataAsync(url)).headers; + return headers; + } + async getRequestMetadataAsync( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + url) { + const thisCreds = this.credentials; + if (!thisCreds.access_token && + !thisCreds.refresh_token && + !this.apiKey && + !this.refreshHandler) { + throw new Error('No access, refresh token, API key or refresh handler callback is set.'); + } + if (thisCreds.access_token && !this.isTokenExpiring()) { + thisCreds.token_type = thisCreds.token_type || 'Bearer'; + const headers = { + Authorization: thisCreds.token_type + ' ' + thisCreds.access_token, + }; + return { headers: this.addSharedMetadataHeaders(headers) }; + } + // If refreshHandler exists, call processAndValidateRefreshHandler(). + if (this.refreshHandler) { + const refreshedAccessToken = await this.processAndValidateRefreshHandler(); + if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) { + this.setCredentials(refreshedAccessToken); + const headers = { + Authorization: 'Bearer ' + this.credentials.access_token, + }; + return { headers: this.addSharedMetadataHeaders(headers) }; + } + } + if (this.apiKey) { + return { headers: { 'X-Goog-Api-Key': this.apiKey } }; + } + let r = null; + let tokens = null; + try { + r = await this.refreshToken(thisCreds.refresh_token); + tokens = r.tokens; + } + catch (err) { + const e = err; + if (e.response && + (e.response.status === 403 || e.response.status === 404)) { + e.message = `Could not refresh access token: ${e.message}`; + } + throw e; + } + const credentials = this.credentials; + credentials.token_type = credentials.token_type || 'Bearer'; + tokens.refresh_token = credentials.refresh_token; + this.credentials = tokens; + const headers = { + Authorization: credentials.token_type + ' ' + tokens.access_token, + }; + return { headers: this.addSharedMetadataHeaders(headers), res: r.res }; + } + /** + * Generates an URL to revoke the given token. + * @param token The existing token to be revoked. + * + * @deprecated use instance method {@link OAuth2Client.getRevokeTokenURL} + */ + static getRevokeTokenUrl(token) { + return new OAuth2Client().getRevokeTokenURL(token).toString(); + } + /** + * Generates a URL to revoke the given token. + * + * @param token The existing token to be revoked. + */ + getRevokeTokenURL(token) { + const url = new URL(this.endpoints.oauth2RevokeUrl); + url.searchParams.append('token', token); + return url; + } + revokeToken(token, callback) { + const opts = { + ...OAuth2Client.RETRY_CONFIG, + url: this.getRevokeTokenURL(token).toString(), + method: 'POST', + }; + if (callback) { + this.transporter + .request(opts) + .then(r => callback(null, r), callback); + } + else { + return this.transporter.request(opts); + } + } + revokeCredentials(callback) { + if (callback) { + this.revokeCredentialsAsync().then(res => callback(null, res), callback); + } + else { + return this.revokeCredentialsAsync(); + } + } + async revokeCredentialsAsync() { + const token = this.credentials.access_token; + this.credentials = {}; + if (token) { + return this.revokeToken(token); + } + else { + throw new Error('No access token to revoke.'); + } + } + request(opts, callback) { + if (callback) { + this.requestAsync(opts).then(r => callback(null, r), e => { + return callback(e, e.response); + }); + } + else { + return this.requestAsync(opts); + } + } + async requestAsync(opts, reAuthRetried = false) { + let r2; + try { + const r = await this.getRequestMetadataAsync(opts.url); + opts.headers = opts.headers || {}; + if (r.headers && r.headers['x-goog-user-project']) { + opts.headers['x-goog-user-project'] = r.headers['x-goog-user-project']; + } + if (r.headers && r.headers.Authorization) { + opts.headers.Authorization = r.headers.Authorization; + } + if (this.apiKey) { + opts.headers['X-Goog-Api-Key'] = this.apiKey; + } + r2 = await this.transporter.request(opts); + } + catch (e) { + const res = e.response; + if (res) { + const statusCode = res.status; + // Retry the request for metadata if the following criteria are true: + // - We haven't already retried. It only makes sense to retry once. + // - The response was a 401 or a 403 + // - The request didn't send a readableStream + // - An access_token and refresh_token were available, but either no + // expiry_date was available or the forceRefreshOnFailure flag is set. + // The absent expiry_date case can happen when developers stash the + // access_token and refresh_token for later use, but the access_token + // fails on the first try because it's expired. Some developers may + // choose to enable forceRefreshOnFailure to mitigate time-related + // errors. + // Or the following criteria are true: + // - We haven't already retried. It only makes sense to retry once. + // - The response was a 401 or a 403 + // - The request didn't send a readableStream + // - No refresh_token was available + // - An access_token and a refreshHandler callback were available, but + // either no expiry_date was available or the forceRefreshOnFailure + // flag is set. The access_token fails on the first try because it's + // expired. Some developers may choose to enable forceRefreshOnFailure + // to mitigate time-related errors. + const mayRequireRefresh = this.credentials && + this.credentials.access_token && + this.credentials.refresh_token && + (!this.credentials.expiry_date || this.forceRefreshOnFailure); + const mayRequireRefreshWithNoRefreshToken = this.credentials && + this.credentials.access_token && + !this.credentials.refresh_token && + (!this.credentials.expiry_date || this.forceRefreshOnFailure) && + this.refreshHandler; + const isReadableStream = res.config.data instanceof stream.Readable; + const isAuthErr = statusCode === 401 || statusCode === 403; + if (!reAuthRetried && + isAuthErr && + !isReadableStream && + mayRequireRefresh) { + await this.refreshAccessTokenAsync(); + return this.requestAsync(opts, true); + } + else if (!reAuthRetried && + isAuthErr && + !isReadableStream && + mayRequireRefreshWithNoRefreshToken) { + const refreshedAccessToken = await this.processAndValidateRefreshHandler(); + if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) { + this.setCredentials(refreshedAccessToken); + } + return this.requestAsync(opts, true); + } + } + throw e; + } + return r2; + } + verifyIdToken(options, callback) { + // This function used to accept two arguments instead of an options object. + // Check the types to help users upgrade with less pain. + // This check can be removed after a 2.0 release. + if (callback && typeof callback !== 'function') { + throw new Error('This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.'); + } + if (callback) { + this.verifyIdTokenAsync(options).then(r => callback(null, r), callback); + } + else { + return this.verifyIdTokenAsync(options); + } + } + async verifyIdTokenAsync(options) { + if (!options.idToken) { + throw new Error('The verifyIdToken method requires an ID Token'); + } + const response = await this.getFederatedSignonCertsAsync(); + const login = await this.verifySignedJwtWithCertsAsync(options.idToken, response.certs, options.audience, this.issuers, options.maxExpiry); + return login; + } + /** + * Obtains information about the provisioned access token. Especially useful + * if you want to check the scopes that were provisioned to a given token. + * + * @param accessToken Required. The Access Token for which you want to get + * user info. + */ + async getTokenInfo(accessToken) { + const { data } = await this.transporter.request({ + ...OAuth2Client.RETRY_CONFIG, + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + Authorization: `Bearer ${accessToken}`, + }, + url: this.endpoints.tokenInfoUrl.toString(), + }); + const info = Object.assign({ + expiry_date: new Date().getTime() + data.expires_in * 1000, + scopes: data.scope.split(' '), + }, data); + delete info.expires_in; + delete info.scope; + return info; + } + getFederatedSignonCerts(callback) { + if (callback) { + this.getFederatedSignonCertsAsync().then(r => callback(null, r.certs, r.res), callback); + } + else { + return this.getFederatedSignonCertsAsync(); + } + } + async getFederatedSignonCertsAsync() { + const nowTime = new Date().getTime(); + const format = (0, crypto_1.hasBrowserCrypto)() + ? CertificateFormat.JWK + : CertificateFormat.PEM; + if (this.certificateExpiry && + nowTime < this.certificateExpiry.getTime() && + this.certificateCacheFormat === format) { + return { certs: this.certificateCache, format }; + } + let res; + let url; + switch (format) { + case CertificateFormat.PEM: + url = this.endpoints.oauth2FederatedSignonPemCertsUrl.toString(); + break; + case CertificateFormat.JWK: + url = this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString(); + break; + default: + throw new Error(`Unsupported certificate format ${format}`); + } + try { + res = await this.transporter.request({ + ...OAuth2Client.RETRY_CONFIG, + url, + }); + } + catch (e) { + if (e instanceof Error) { + e.message = `Failed to retrieve verification certificates: ${e.message}`; + } + throw e; + } + const cacheControl = res ? res.headers['cache-control'] : undefined; + let cacheAge = -1; + if (cacheControl) { + const pattern = new RegExp('max-age=([0-9]*)'); + const regexResult = pattern.exec(cacheControl); + if (regexResult && regexResult.length === 2) { + // Cache results with max-age (in seconds) + cacheAge = Number(regexResult[1]) * 1000; // milliseconds + } + } + let certificates = {}; + switch (format) { + case CertificateFormat.PEM: + certificates = res.data; + break; + case CertificateFormat.JWK: + for (const key of res.data.keys) { + certificates[key.kid] = key; + } + break; + default: + throw new Error(`Unsupported certificate format ${format}`); + } + const now = new Date(); + this.certificateExpiry = + cacheAge === -1 ? null : new Date(now.getTime() + cacheAge); + this.certificateCache = certificates; + this.certificateCacheFormat = format; + return { certs: certificates, format, res }; + } + getIapPublicKeys(callback) { + if (callback) { + this.getIapPublicKeysAsync().then(r => callback(null, r.pubkeys, r.res), callback); + } + else { + return this.getIapPublicKeysAsync(); + } + } + async getIapPublicKeysAsync() { + let res; + const url = this.endpoints.oauth2IapPublicKeyUrl.toString(); + try { + res = await this.transporter.request({ + ...OAuth2Client.RETRY_CONFIG, + url, + }); + } + catch (e) { + if (e instanceof Error) { + e.message = `Failed to retrieve verification certificates: ${e.message}`; + } + throw e; + } + return { pubkeys: res.data, res }; + } + verifySignedJwtWithCerts() { + // To make the code compatible with browser SubtleCrypto we need to make + // this method async. + throw new Error('verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.'); + } + /** + * Verify the id token is signed with the correct certificate + * and is from the correct audience. + * @param jwt The jwt to verify (The ID Token in this case). + * @param certs The array of certs to test the jwt against. + * @param requiredAudience The audience to test the jwt against. + * @param issuers The allowed issuers of the jwt (Optional). + * @param maxExpiry The max expiry the certificate can be (Optional). + * @return Returns a promise resolving to LoginTicket on verification. + */ + async verifySignedJwtWithCertsAsync(jwt, certs, requiredAudience, issuers, maxExpiry) { + const crypto = (0, crypto_1.createCrypto)(); + if (!maxExpiry) { + maxExpiry = OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_; + } + const segments = jwt.split('.'); + if (segments.length !== 3) { + throw new Error('Wrong number of segments in token: ' + jwt); + } + const signed = segments[0] + '.' + segments[1]; + let signature = segments[2]; + let envelope; + let payload; + try { + envelope = JSON.parse(crypto.decodeBase64StringUtf8(segments[0])); + } + catch (err) { + if (err instanceof Error) { + err.message = `Can't parse token envelope: ${segments[0]}': ${err.message}`; + } + throw err; + } + if (!envelope) { + throw new Error("Can't parse token envelope: " + segments[0]); + } + try { + payload = JSON.parse(crypto.decodeBase64StringUtf8(segments[1])); + } + catch (err) { + if (err instanceof Error) { + err.message = `Can't parse token payload '${segments[0]}`; + } + throw err; + } + if (!payload) { + throw new Error("Can't parse token payload: " + segments[1]); + } + if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) { + // If this is not present, then there's no reason to attempt verification + throw new Error('No pem found for envelope: ' + JSON.stringify(envelope)); + } + const cert = certs[envelope.kid]; + if (envelope.alg === 'ES256') { + signature = formatEcdsa.joseToDer(signature, 'ES256').toString('base64'); + } + const verified = await crypto.verify(cert, signed, signature); + if (!verified) { + throw new Error('Invalid token signature: ' + jwt); + } + if (!payload.iat) { + throw new Error('No issue time in token: ' + JSON.stringify(payload)); + } + if (!payload.exp) { + throw new Error('No expiration time in token: ' + JSON.stringify(payload)); + } + const iat = Number(payload.iat); + if (isNaN(iat)) + throw new Error('iat field using invalid format'); + const exp = Number(payload.exp); + if (isNaN(exp)) + throw new Error('exp field using invalid format'); + const now = new Date().getTime() / 1000; + if (exp >= now + maxExpiry) { + throw new Error('Expiration time too far in future: ' + JSON.stringify(payload)); + } + const earliest = iat - OAuth2Client.CLOCK_SKEW_SECS_; + const latest = exp + OAuth2Client.CLOCK_SKEW_SECS_; + if (now < earliest) { + throw new Error('Token used too early, ' + + now + + ' < ' + + earliest + + ': ' + + JSON.stringify(payload)); + } + if (now > latest) { + throw new Error('Token used too late, ' + + now + + ' > ' + + latest + + ': ' + + JSON.stringify(payload)); + } + if (issuers && issuers.indexOf(payload.iss) < 0) { + throw new Error('Invalid issuer, expected one of [' + + issuers + + '], but got ' + + payload.iss); + } + // Check the audience matches if we have one + if (typeof requiredAudience !== 'undefined' && requiredAudience !== null) { + const aud = payload.aud; + let audVerified = false; + // If the requiredAudience is an array, check if it contains token + // audience + if (requiredAudience.constructor === Array) { + audVerified = requiredAudience.indexOf(aud) > -1; + } + else { + audVerified = aud === requiredAudience; + } + if (!audVerified) { + throw new Error('Wrong recipient, payload audience != requiredAudience'); + } + } + return new loginticket_1.LoginTicket(envelope, payload); + } + /** + * Returns a promise that resolves with AccessTokenResponse type if + * refreshHandler is defined. + * If not, nothing is returned. + */ + async processAndValidateRefreshHandler() { + if (this.refreshHandler) { + const accessTokenResponse = await this.refreshHandler(); + if (!accessTokenResponse.access_token) { + throw new Error('No access token is returned by the refreshHandler callback.'); + } + return accessTokenResponse; + } + return; + } + /** + * Returns true if a token is expired or will expire within + * eagerRefreshThresholdMillismilliseconds. + * If there is no expiry time, assumes the token is not expired or expiring. + */ + isTokenExpiring() { + const expiryDate = this.credentials.expiry_date; + return expiryDate + ? expiryDate <= new Date().getTime() + this.eagerRefreshThresholdMillis + : false; + } +} +exports.OAuth2Client = OAuth2Client; +/** + * @deprecated use instance's {@link OAuth2Client.endpoints} + */ +OAuth2Client.GOOGLE_TOKEN_INFO_URL = 'https://oauth2.googleapis.com/tokeninfo'; +/** + * Clock skew - five minutes in seconds + */ +OAuth2Client.CLOCK_SKEW_SECS_ = 300; +/** + * The default max Token Lifetime is one day in seconds + */ +OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_ = 86400; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/oauth2common.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/oauth2common.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..84916be9c0ea6eba1afe15d28129ffe2ea066301 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/oauth2common.d.ts @@ -0,0 +1,92 @@ +import { GaxiosOptions } from 'gaxios'; +/** + * OAuth error codes. + * https://tools.ietf.org/html/rfc6749#section-5.2 + */ +type OAuthErrorCode = 'invalid_request' | 'invalid_client' | 'invalid_grant' | 'unauthorized_client' | 'unsupported_grant_type' | 'invalid_scope' | string; +/** + * The standard OAuth error response. + * https://tools.ietf.org/html/rfc6749#section-5.2 + */ +export interface OAuthErrorResponse { + error: OAuthErrorCode; + error_description?: string; + error_uri?: string; +} +/** + * OAuth client authentication types. + * https://tools.ietf.org/html/rfc6749#section-2.3 + */ +export type ConfidentialClientType = 'basic' | 'request-body'; +/** + * Defines the client authentication credentials for basic and request-body + * credentials. + * https://tools.ietf.org/html/rfc6749#section-2.3.1 + */ +export interface ClientAuthentication { + confidentialClientType: ConfidentialClientType; + clientId: string; + clientSecret?: string; +} +/** + * Abstract class for handling client authentication in OAuth-based + * operations. + * When request-body client authentication is used, only application/json and + * application/x-www-form-urlencoded content types for HTTP methods that support + * request bodies are supported. + */ +export declare abstract class OAuthClientAuthHandler { + private readonly clientAuthentication?; + private crypto; + /** + * Instantiates an OAuth client authentication handler. + * @param clientAuthentication The client auth credentials. + */ + constructor(clientAuthentication?: ClientAuthentication | undefined); + /** + * Applies client authentication on the OAuth request's headers or POST + * body but does not process the request. + * @param opts The GaxiosOptions whose headers or data are to be modified + * depending on the client authentication mechanism to be used. + * @param bearerToken The optional bearer token to use for authentication. + * When this is used, no client authentication credentials are needed. + */ + protected applyClientAuthenticationOptions(opts: GaxiosOptions, bearerToken?: string): void; + /** + * Applies client authentication on the request's header if either + * basic authentication or bearer token authentication is selected. + * + * @param opts The GaxiosOptions whose headers or data are to be modified + * depending on the client authentication mechanism to be used. + * @param bearerToken The optional bearer token to use for authentication. + * When this is used, no client authentication credentials are needed. + */ + private injectAuthenticatedHeaders; + /** + * Applies client authentication on the request's body if request-body + * client authentication is selected. + * + * @param opts The GaxiosOptions whose headers or data are to be modified + * depending on the client authentication mechanism to be used. + */ + private injectAuthenticatedRequestBody; + /** + * Retry config for Auth-related requests. + * + * @remarks + * + * This is not a part of the default {@link AuthClient.transporter transporter/gaxios} + * config as some downstream APIs would prefer if customers explicitly enable retries, + * such as GCS. + */ + protected static get RETRY_CONFIG(): GaxiosOptions; +} +/** + * Converts an OAuth error response to a native JavaScript Error. + * @param resp The OAuth error response to convert to a native Error object. + * @param err The optional original error. If provided, the error properties + * will be copied to the new error. + * @return The converted native Error object. + */ +export declare function getErrorFromOAuthErrorResponse(resp: OAuthErrorResponse, err?: Error): Error; +export {}; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/oauth2common.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/oauth2common.js new file mode 100644 index 0000000000000000000000000000000000000000..f580c1e360aa0c813767c9aa41f71930a319b6e2 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/oauth2common.js @@ -0,0 +1,192 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OAuthClientAuthHandler = void 0; +exports.getErrorFromOAuthErrorResponse = getErrorFromOAuthErrorResponse; +const querystring = require("querystring"); +const crypto_1 = require("../crypto/crypto"); +/** List of HTTP methods that accept request bodies. */ +const METHODS_SUPPORTING_REQUEST_BODY = ['PUT', 'POST', 'PATCH']; +/** + * Abstract class for handling client authentication in OAuth-based + * operations. + * When request-body client authentication is used, only application/json and + * application/x-www-form-urlencoded content types for HTTP methods that support + * request bodies are supported. + */ +class OAuthClientAuthHandler { + /** + * Instantiates an OAuth client authentication handler. + * @param clientAuthentication The client auth credentials. + */ + constructor(clientAuthentication) { + this.clientAuthentication = clientAuthentication; + this.crypto = (0, crypto_1.createCrypto)(); + } + /** + * Applies client authentication on the OAuth request's headers or POST + * body but does not process the request. + * @param opts The GaxiosOptions whose headers or data are to be modified + * depending on the client authentication mechanism to be used. + * @param bearerToken The optional bearer token to use for authentication. + * When this is used, no client authentication credentials are needed. + */ + applyClientAuthenticationOptions(opts, bearerToken) { + // Inject authenticated header. + this.injectAuthenticatedHeaders(opts, bearerToken); + // Inject authenticated request body. + if (!bearerToken) { + this.injectAuthenticatedRequestBody(opts); + } + } + /** + * Applies client authentication on the request's header if either + * basic authentication or bearer token authentication is selected. + * + * @param opts The GaxiosOptions whose headers or data are to be modified + * depending on the client authentication mechanism to be used. + * @param bearerToken The optional bearer token to use for authentication. + * When this is used, no client authentication credentials are needed. + */ + injectAuthenticatedHeaders(opts, bearerToken) { + var _a; + // Bearer token prioritized higher than basic Auth. + if (bearerToken) { + opts.headers = opts.headers || {}; + Object.assign(opts.headers, { + Authorization: `Bearer ${bearerToken}}`, + }); + } + else if (((_a = this.clientAuthentication) === null || _a === void 0 ? void 0 : _a.confidentialClientType) === 'basic') { + opts.headers = opts.headers || {}; + const clientId = this.clientAuthentication.clientId; + const clientSecret = this.clientAuthentication.clientSecret || ''; + const base64EncodedCreds = this.crypto.encodeBase64StringUtf8(`${clientId}:${clientSecret}`); + Object.assign(opts.headers, { + Authorization: `Basic ${base64EncodedCreds}`, + }); + } + } + /** + * Applies client authentication on the request's body if request-body + * client authentication is selected. + * + * @param opts The GaxiosOptions whose headers or data are to be modified + * depending on the client authentication mechanism to be used. + */ + injectAuthenticatedRequestBody(opts) { + var _a; + if (((_a = this.clientAuthentication) === null || _a === void 0 ? void 0 : _a.confidentialClientType) === 'request-body') { + const method = (opts.method || 'GET').toUpperCase(); + // Inject authenticated request body. + if (METHODS_SUPPORTING_REQUEST_BODY.indexOf(method) !== -1) { + // Get content-type. + let contentType; + const headers = opts.headers || {}; + for (const key in headers) { + if (key.toLowerCase() === 'content-type' && headers[key]) { + contentType = headers[key].toLowerCase(); + break; + } + } + if (contentType === 'application/x-www-form-urlencoded') { + opts.data = opts.data || ''; + const data = querystring.parse(opts.data); + Object.assign(data, { + client_id: this.clientAuthentication.clientId, + client_secret: this.clientAuthentication.clientSecret || '', + }); + opts.data = querystring.stringify(data); + } + else if (contentType === 'application/json') { + opts.data = opts.data || {}; + Object.assign(opts.data, { + client_id: this.clientAuthentication.clientId, + client_secret: this.clientAuthentication.clientSecret || '', + }); + } + else { + throw new Error(`${contentType} content-types are not supported with ` + + `${this.clientAuthentication.confidentialClientType} ` + + 'client authentication'); + } + } + else { + throw new Error(`${method} HTTP method does not support ` + + `${this.clientAuthentication.confidentialClientType} ` + + 'client authentication'); + } + } + } + /** + * Retry config for Auth-related requests. + * + * @remarks + * + * This is not a part of the default {@link AuthClient.transporter transporter/gaxios} + * config as some downstream APIs would prefer if customers explicitly enable retries, + * such as GCS. + */ + static get RETRY_CONFIG() { + return { + retry: true, + retryConfig: { + httpMethodsToRetry: ['GET', 'PUT', 'POST', 'HEAD', 'OPTIONS', 'DELETE'], + }, + }; + } +} +exports.OAuthClientAuthHandler = OAuthClientAuthHandler; +/** + * Converts an OAuth error response to a native JavaScript Error. + * @param resp The OAuth error response to convert to a native Error object. + * @param err The optional original error. If provided, the error properties + * will be copied to the new error. + * @return The converted native Error object. + */ +function getErrorFromOAuthErrorResponse(resp, err) { + // Error response. + const errorCode = resp.error; + const errorDescription = resp.error_description; + const errorUri = resp.error_uri; + let message = `Error code ${errorCode}`; + if (typeof errorDescription !== 'undefined') { + message += `: ${errorDescription}`; + } + if (typeof errorUri !== 'undefined') { + message += ` - ${errorUri}`; + } + const newError = new Error(message); + // Copy properties from original error to newly generated error. + if (err) { + const keys = Object.keys(err); + if (err.stack) { + // Copy error.stack if available. + keys.push('stack'); + } + keys.forEach(key => { + // Do not overwrite the message field. + if (key !== 'message') { + Object.defineProperty(newError, key, { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + value: err[key], + writable: false, + enumerable: true, + }); + } + }); + } + return newError; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/passthrough.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/passthrough.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6ec4617d2869ce6eb4b1d93c29465d4f0092f6a8 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/passthrough.d.ts @@ -0,0 +1,38 @@ +import { GaxiosOptions } from 'gaxios'; +import { AuthClient } from './authclient'; +import { GetAccessTokenResponse, Headers } from './oauth2client'; +/** + * An AuthClient without any Authentication information. Useful for: + * - Anonymous access + * - Local Emulators + * - Testing Environments + * + */ +export declare class PassThroughClient extends AuthClient { + /** + * Creates a request without any authentication headers or checks. + * + * @remarks + * + * In testing environments it may be useful to change the provided + * {@link AuthClient.transporter} for any desired request overrides/handling. + * + * @param opts + * @returns The response of the request. + */ + request(opts: GaxiosOptions): Promise>; + /** + * A required method of the base class. + * Always will return an empty object. + * + * @returns {} + */ + getAccessToken(): Promise; + /** + * A required method of the base class. + * Always will return an empty object. + * + * @returns {} + */ + getRequestHeaders(): Promise; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/passthrough.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/passthrough.js new file mode 100644 index 0000000000000000000000000000000000000000..07e9812bfc8a45b61592d20301b20c46b84c975c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/passthrough.js @@ -0,0 +1,61 @@ +"use strict"; +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PassThroughClient = void 0; +const authclient_1 = require("./authclient"); +/** + * An AuthClient without any Authentication information. Useful for: + * - Anonymous access + * - Local Emulators + * - Testing Environments + * + */ +class PassThroughClient extends authclient_1.AuthClient { + /** + * Creates a request without any authentication headers or checks. + * + * @remarks + * + * In testing environments it may be useful to change the provided + * {@link AuthClient.transporter} for any desired request overrides/handling. + * + * @param opts + * @returns The response of the request. + */ + async request(opts) { + return this.transporter.request(opts); + } + /** + * A required method of the base class. + * Always will return an empty object. + * + * @returns {} + */ + async getAccessToken() { + return {}; + } + /** + * A required method of the base class. + * Always will return an empty object. + * + * @returns {} + */ + async getRequestHeaders() { + return {}; + } +} +exports.PassThroughClient = PassThroughClient; +const a = new PassThroughClient(); +a.getAccessToken(); diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6b4e62f6a07a9ee0068eccbceda8413db27c3039 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.d.ts @@ -0,0 +1,155 @@ +import { BaseExternalAccountClient, BaseExternalAccountClientOptions } from './baseexternalclient'; +import { AuthClientOptions } from './authclient'; +/** + * Defines the credential source portion of the configuration for PluggableAuthClient. + * + *

Command is the only required field. If timeout_millis is not specified, the library will + * default to a 30-second timeout. + * + *

+ * Sample credential source for Pluggable Auth Client:
+ * {
+ *   ...
+ *   "credential_source": {
+ *     "executable": {
+ *       "command": "/path/to/get/credentials.sh --arg1=value1 --arg2=value2",
+ *       "timeout_millis": 5000,
+ *       "output_file": "/path/to/generated/cached/credentials"
+ *     }
+ *   }
+ * }
+ * 
+ */ +export interface PluggableAuthClientOptions extends BaseExternalAccountClientOptions { + credential_source: { + executable: { + /** + * The command used to retrieve the 3rd party token. + */ + command: string; + /** + * The timeout for executable to run in milliseconds. If none is provided it + * will be set to the default timeout of 30 seconds. + */ + timeout_millis?: number; + /** + * An optional output file location that will be checked for a cached response + * from a previous run of the executable. + */ + output_file?: string; + }; + }; +} +/** + * Error thrown from the executable run by PluggableAuthClient. + */ +export declare class ExecutableError extends Error { + /** + * The exit code returned by the executable. + */ + readonly code: string; + constructor(message: string, code: string); +} +/** + * PluggableAuthClient enables the exchange of workload identity pool external credentials for + * Google access tokens by retrieving 3rd party tokens through a user supplied executable. These + * scripts/executables are completely independent of the Google Cloud Auth libraries. These + * credentials plug into ADC and will call the specified executable to retrieve the 3rd party token + * to be exchanged for a Google access token. + * + *

To use these credentials, the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable + * must be set to '1'. This is for security reasons. + * + *

Both OIDC and SAML are supported. The executable must adhere to a specific response format + * defined below. + * + *

The executable must print out the 3rd party token to STDOUT in JSON format. When an + * output_file is specified in the credential configuration, the executable must also handle writing the + * JSON response to this file. + * + *

+ * OIDC response sample:
+ * {
+ *   "version": 1,
+ *   "success": true,
+ *   "token_type": "urn:ietf:params:oauth:token-type:id_token",
+ *   "id_token": "HEADER.PAYLOAD.SIGNATURE",
+ *   "expiration_time": 1620433341
+ * }
+ *
+ * SAML2 response sample:
+ * {
+ *   "version": 1,
+ *   "success": true,
+ *   "token_type": "urn:ietf:params:oauth:token-type:saml2",
+ *   "saml_response": "...",
+ *   "expiration_time": 1620433341
+ * }
+ *
+ * Error response sample:
+ * {
+ *   "version": 1,
+ *   "success": false,
+ *   "code": "401",
+ *   "message": "Error message."
+ * }
+ * 
+ * + *

The "expiration_time" field in the JSON response is only required for successful + * responses when an output file was specified in the credential configuration + * + *

The auth libraries will populate certain environment variables that will be accessible by the + * executable, such as: GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE, GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE, + * GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE, GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL, and + * GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE. + * + *

Please see this repositories README for a complete executable request/response specification. + */ +export declare class PluggableAuthClient extends BaseExternalAccountClient { + /** + * The command used to retrieve the third party token. + */ + private readonly command; + /** + * The timeout in milliseconds for running executable, + * set to default if none provided. + */ + private readonly timeoutMillis; + /** + * The path to file to check for cached executable response. + */ + private readonly outputFile?; + /** + * Executable and output file handler. + */ + private readonly handler; + /** + * Instantiates a PluggableAuthClient instance using the provided JSON + * object loaded from an external account credentials file. + * An error is thrown if the credential is not a valid pluggable auth credential. + * @param options The external account options object typically loaded from + * the external account JSON credential file. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options: PluggableAuthClientOptions, additionalOptions?: AuthClientOptions); + /** + * Triggered when an external subject token is needed to be exchanged for a + * GCP access token via GCP STS endpoint. + * This uses the `options.credential_source` object to figure out how + * to retrieve the token using the current environment. In this case, + * this calls a user provided executable which returns the subject token. + * The logic is summarized as: + * 1. Validated that the executable is allowed to run. The + * GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment must be set to + * 1 for security reasons. + * 2. If an output file is specified by the user, check the file location + * for a response. If the file exists and contains a valid response, + * return the subject token from the file. + * 3. Call the provided executable and return response. + * @return A promise that resolves with the external subject token. + */ + retrieveSubjectToken(): Promise; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js new file mode 100644 index 0000000000000000000000000000000000000000..acb299d3b1b7ca1cf5195b09b1f973699cfd4683 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js @@ -0,0 +1,215 @@ +"use strict"; +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PluggableAuthClient = exports.ExecutableError = void 0; +const baseexternalclient_1 = require("./baseexternalclient"); +const executable_response_1 = require("./executable-response"); +const pluggable_auth_handler_1 = require("./pluggable-auth-handler"); +/** + * Error thrown from the executable run by PluggableAuthClient. + */ +class ExecutableError extends Error { + constructor(message, code) { + super(`The executable failed with exit code: ${code} and error message: ${message}.`); + this.code = code; + Object.setPrototypeOf(this, new.target.prototype); + } +} +exports.ExecutableError = ExecutableError; +/** + * The default executable timeout when none is provided, in milliseconds. + */ +const DEFAULT_EXECUTABLE_TIMEOUT_MILLIS = 30 * 1000; +/** + * The minimum allowed executable timeout in milliseconds. + */ +const MINIMUM_EXECUTABLE_TIMEOUT_MILLIS = 5 * 1000; +/** + * The maximum allowed executable timeout in milliseconds. + */ +const MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS = 120 * 1000; +/** + * The environment variable to check to see if executable can be run. + * Value must be set to '1' for the executable to run. + */ +const GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES = 'GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES'; +/** + * The maximum currently supported executable version. + */ +const MAXIMUM_EXECUTABLE_VERSION = 1; +/** + * PluggableAuthClient enables the exchange of workload identity pool external credentials for + * Google access tokens by retrieving 3rd party tokens through a user supplied executable. These + * scripts/executables are completely independent of the Google Cloud Auth libraries. These + * credentials plug into ADC and will call the specified executable to retrieve the 3rd party token + * to be exchanged for a Google access token. + * + *

To use these credentials, the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable + * must be set to '1'. This is for security reasons. + * + *

Both OIDC and SAML are supported. The executable must adhere to a specific response format + * defined below. + * + *

The executable must print out the 3rd party token to STDOUT in JSON format. When an + * output_file is specified in the credential configuration, the executable must also handle writing the + * JSON response to this file. + * + *

+ * OIDC response sample:
+ * {
+ *   "version": 1,
+ *   "success": true,
+ *   "token_type": "urn:ietf:params:oauth:token-type:id_token",
+ *   "id_token": "HEADER.PAYLOAD.SIGNATURE",
+ *   "expiration_time": 1620433341
+ * }
+ *
+ * SAML2 response sample:
+ * {
+ *   "version": 1,
+ *   "success": true,
+ *   "token_type": "urn:ietf:params:oauth:token-type:saml2",
+ *   "saml_response": "...",
+ *   "expiration_time": 1620433341
+ * }
+ *
+ * Error response sample:
+ * {
+ *   "version": 1,
+ *   "success": false,
+ *   "code": "401",
+ *   "message": "Error message."
+ * }
+ * 
+ * + *

The "expiration_time" field in the JSON response is only required for successful + * responses when an output file was specified in the credential configuration + * + *

The auth libraries will populate certain environment variables that will be accessible by the + * executable, such as: GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE, GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE, + * GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE, GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL, and + * GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE. + * + *

Please see this repositories README for a complete executable request/response specification. + */ +class PluggableAuthClient extends baseexternalclient_1.BaseExternalAccountClient { + /** + * Instantiates a PluggableAuthClient instance using the provided JSON + * object loaded from an external account credentials file. + * An error is thrown if the credential is not a valid pluggable auth credential. + * @param options The external account options object typically loaded from + * the external account JSON credential file. + * @param additionalOptions **DEPRECATED, all options are available in the + * `options` parameter.** Optional additional behavior customization options. + * These currently customize expiration threshold time and whether to retry + * on 401/403 API request errors. + */ + constructor(options, additionalOptions) { + super(options, additionalOptions); + if (!options.credential_source.executable) { + throw new Error('No valid Pluggable Auth "credential_source" provided.'); + } + this.command = options.credential_source.executable.command; + if (!this.command) { + throw new Error('No valid Pluggable Auth "credential_source" provided.'); + } + // Check if the provided timeout exists and if it is valid. + if (options.credential_source.executable.timeout_millis === undefined) { + this.timeoutMillis = DEFAULT_EXECUTABLE_TIMEOUT_MILLIS; + } + else { + this.timeoutMillis = options.credential_source.executable.timeout_millis; + if (this.timeoutMillis < MINIMUM_EXECUTABLE_TIMEOUT_MILLIS || + this.timeoutMillis > MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS) { + throw new Error(`Timeout must be between ${MINIMUM_EXECUTABLE_TIMEOUT_MILLIS} and ` + + `${MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS} milliseconds.`); + } + } + this.outputFile = options.credential_source.executable.output_file; + this.handler = new pluggable_auth_handler_1.PluggableAuthHandler({ + command: this.command, + timeoutMillis: this.timeoutMillis, + outputFile: this.outputFile, + }); + this.credentialSourceType = 'executable'; + } + /** + * Triggered when an external subject token is needed to be exchanged for a + * GCP access token via GCP STS endpoint. + * This uses the `options.credential_source` object to figure out how + * to retrieve the token using the current environment. In this case, + * this calls a user provided executable which returns the subject token. + * The logic is summarized as: + * 1. Validated that the executable is allowed to run. The + * GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment must be set to + * 1 for security reasons. + * 2. If an output file is specified by the user, check the file location + * for a response. If the file exists and contains a valid response, + * return the subject token from the file. + * 3. Call the provided executable and return response. + * @return A promise that resolves with the external subject token. + */ + async retrieveSubjectToken() { + // Check if the executable is allowed to run. + if (process.env[GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES] !== '1') { + throw new Error('Pluggable Auth executables need to be explicitly allowed to run by ' + + 'setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment ' + + 'Variable to 1.'); + } + let executableResponse = undefined; + // Try to get cached executable response from output file. + if (this.outputFile) { + executableResponse = await this.handler.retrieveCachedResponse(); + } + // If no response from output file, call the executable. + if (!executableResponse) { + // Set up environment map with required values for the executable. + const envMap = new Map(); + envMap.set('GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE', this.audience); + envMap.set('GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE', this.subjectTokenType); + // Always set to 0 because interactive mode is not supported. + envMap.set('GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE', '0'); + if (this.outputFile) { + envMap.set('GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE', this.outputFile); + } + const serviceAccountEmail = this.getServiceAccountEmail(); + if (serviceAccountEmail) { + envMap.set('GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL', serviceAccountEmail); + } + executableResponse = + await this.handler.retrieveResponseFromExecutable(envMap); + } + if (executableResponse.version > MAXIMUM_EXECUTABLE_VERSION) { + throw new Error(`Version of executable is not currently supported, maximum supported version is ${MAXIMUM_EXECUTABLE_VERSION}.`); + } + // Check that response was successful. + if (!executableResponse.success) { + throw new ExecutableError(executableResponse.errorMessage, executableResponse.errorCode); + } + // Check that response contains expiration time if output file was specified. + if (this.outputFile) { + if (!executableResponse.expirationTime) { + throw new executable_response_1.InvalidExpirationTimeFieldError('The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.'); + } + } + // Check that response is not expired. + if (executableResponse.isExpired()) { + throw new Error('Executable response is expired.'); + } + // Return subject token from response. + return executableResponse.subjectToken; + } +} +exports.PluggableAuthClient = PluggableAuthClient; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e5ddd024541de64f6c5d2522c2d20cb97b19fc91 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.d.ts @@ -0,0 +1,51 @@ +import { ExecutableResponse } from './executable-response'; +/** + * Defines the options used for the PluggableAuthHandler class. + */ +export interface PluggableAuthHandlerOptions { + /** + * The command used to retrieve the third party token. + */ + command: string; + /** + * The timeout in milliseconds for running executable, + * set to default if none provided. + */ + timeoutMillis: number; + /** + * The path to file to check for cached executable response. + */ + outputFile?: string; +} +/** + * A handler used to retrieve 3rd party token responses from user defined + * executables and cached file output for the PluggableAuthClient class. + */ +export declare class PluggableAuthHandler { + private readonly commandComponents; + private readonly timeoutMillis; + private readonly outputFile?; + /** + * Instantiates a PluggableAuthHandler instance using the provided + * PluggableAuthHandlerOptions object. + */ + constructor(options: PluggableAuthHandlerOptions); + /** + * Calls user provided executable to get a 3rd party subject token and + * returns the response. + * @param envMap a Map of additional Environment Variables required for + * the executable. + * @return A promise that resolves with the executable response. + */ + retrieveResponseFromExecutable(envMap: Map): Promise; + /** + * Checks user provided output file for response from previous run of + * executable and return the response if it exists, is formatted correctly, and is not expired. + */ + retrieveCachedResponse(): Promise; + /** + * Parses given command string into component array, splitting on spaces unless + * spaces are between quotation marks. + */ + private static parseCommand; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js new file mode 100644 index 0000000000000000000000000000000000000000..47fa27699f9c191eeaf4cf37506a0b3adc04e597 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js @@ -0,0 +1,156 @@ +"use strict"; +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PluggableAuthHandler = void 0; +const pluggable_auth_client_1 = require("./pluggable-auth-client"); +const executable_response_1 = require("./executable-response"); +const childProcess = require("child_process"); +const fs = require("fs"); +/** + * A handler used to retrieve 3rd party token responses from user defined + * executables and cached file output for the PluggableAuthClient class. + */ +class PluggableAuthHandler { + /** + * Instantiates a PluggableAuthHandler instance using the provided + * PluggableAuthHandlerOptions object. + */ + constructor(options) { + if (!options.command) { + throw new Error('No command provided.'); + } + this.commandComponents = PluggableAuthHandler.parseCommand(options.command); + this.timeoutMillis = options.timeoutMillis; + if (!this.timeoutMillis) { + throw new Error('No timeoutMillis provided.'); + } + this.outputFile = options.outputFile; + } + /** + * Calls user provided executable to get a 3rd party subject token and + * returns the response. + * @param envMap a Map of additional Environment Variables required for + * the executable. + * @return A promise that resolves with the executable response. + */ + retrieveResponseFromExecutable(envMap) { + return new Promise((resolve, reject) => { + // Spawn process to run executable using added environment variables. + const child = childProcess.spawn(this.commandComponents[0], this.commandComponents.slice(1), { + env: { ...process.env, ...Object.fromEntries(envMap) }, + }); + let output = ''; + // Append stdout to output as executable runs. + child.stdout.on('data', (data) => { + output += data; + }); + // Append stderr as executable runs. + child.stderr.on('data', (err) => { + output += err; + }); + // Set up a timeout to end the child process and throw an error. + const timeout = setTimeout(() => { + // Kill child process and remove listeners so 'close' event doesn't get + // read after child process is killed. + child.removeAllListeners(); + child.kill(); + return reject(new Error('The executable failed to finish within the timeout specified.')); + }, this.timeoutMillis); + child.on('close', (code) => { + // Cancel timeout if executable closes before timeout is reached. + clearTimeout(timeout); + if (code === 0) { + // If the executable completed successfully, try to return the parsed response. + try { + const responseJson = JSON.parse(output); + const response = new executable_response_1.ExecutableResponse(responseJson); + return resolve(response); + } + catch (error) { + if (error instanceof executable_response_1.ExecutableResponseError) { + return reject(error); + } + return reject(new executable_response_1.ExecutableResponseError(`The executable returned an invalid response: ${output}`)); + } + } + else { + return reject(new pluggable_auth_client_1.ExecutableError(output, code.toString())); + } + }); + }); + } + /** + * Checks user provided output file for response from previous run of + * executable and return the response if it exists, is formatted correctly, and is not expired. + */ + async retrieveCachedResponse() { + if (!this.outputFile || this.outputFile.length === 0) { + return undefined; + } + let filePath; + try { + filePath = await fs.promises.realpath(this.outputFile); + } + catch (_a) { + // If file path cannot be resolved, return undefined. + return undefined; + } + if (!(await fs.promises.lstat(filePath)).isFile()) { + // If path does not lead to file, return undefined. + return undefined; + } + const responseString = await fs.promises.readFile(filePath, { + encoding: 'utf8', + }); + if (responseString === '') { + return undefined; + } + try { + const responseJson = JSON.parse(responseString); + const response = new executable_response_1.ExecutableResponse(responseJson); + // Check if response is successful and unexpired. + if (response.isValid()) { + return new executable_response_1.ExecutableResponse(responseJson); + } + return undefined; + } + catch (error) { + if (error instanceof executable_response_1.ExecutableResponseError) { + throw error; + } + throw new executable_response_1.ExecutableResponseError(`The output file contained an invalid response: ${responseString}`); + } + } + /** + * Parses given command string into component array, splitting on spaces unless + * spaces are between quotation marks. + */ + static parseCommand(command) { + // Split the command into components by splitting on spaces, + // unless spaces are contained in quotation marks. + const components = command.match(/(?:[^\s"]+|"[^"]*")+/g); + if (!components) { + throw new Error(`Provided command: "${command}" could not be parsed.`); + } + // Remove quotation marks from the beginning and end of each component if they are present. + for (let i = 0; i < components.length; i++) { + if (components[i][0] === '"' && components[i].slice(-1) === '"') { + components[i] = components[i].slice(1, -1); + } + } + return components; + } +} +exports.PluggableAuthHandler = PluggableAuthHandler; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/refreshclient.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/refreshclient.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c84459a8214020e7d79d6ba320cdc62c0568cb96 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/refreshclient.d.ts @@ -0,0 +1,50 @@ +import * as stream from 'stream'; +import { JWTInput } from './credentials'; +import { GetTokenResponse, OAuth2Client, OAuth2ClientOptions } from './oauth2client'; +export declare const USER_REFRESH_ACCOUNT_TYPE = "authorized_user"; +export interface UserRefreshClientOptions extends OAuth2ClientOptions { + clientId?: string; + clientSecret?: string; + refreshToken?: string; +} +export declare class UserRefreshClient extends OAuth2Client { + _refreshToken?: string | null; + /** + * User Refresh Token credentials. + * + * @param clientId The authentication client ID. + * @param clientSecret The authentication client secret. + * @param refreshToken The authentication refresh token. + */ + constructor(clientId?: string, clientSecret?: string, refreshToken?: string); + constructor(options: UserRefreshClientOptions); + constructor(clientId?: string, clientSecret?: string, refreshToken?: string); + /** + * Refreshes the access token. + * @param refreshToken An ignored refreshToken.. + * @param callback Optional callback. + */ + protected refreshTokenNoCache(refreshToken?: string | null): Promise; + fetchIdToken(targetAudience: string): Promise; + /** + * Create a UserRefreshClient credentials instance using the given input + * options. + * @param json The input object. + */ + fromJSON(json: JWTInput): void; + /** + * Create a UserRefreshClient credentials instance using the given input + * stream. + * @param inputStream The input stream. + * @param callback Optional callback. + */ + fromStream(inputStream: stream.Readable): Promise; + fromStream(inputStream: stream.Readable, callback: (err?: Error) => void): void; + private fromStreamAsync; + /** + * Create a UserRefreshClient credentials instance using the given input + * options. + * @param json The input object. + */ + static fromJSON(json: JWTInput): UserRefreshClient; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/refreshclient.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/refreshclient.js new file mode 100644 index 0000000000000000000000000000000000000000..85a5f181812a1fc2e1ff168a70c4be807e5b8362 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/refreshclient.js @@ -0,0 +1,132 @@ +"use strict"; +// Copyright 2015 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UserRefreshClient = exports.USER_REFRESH_ACCOUNT_TYPE = void 0; +const oauth2client_1 = require("./oauth2client"); +const querystring_1 = require("querystring"); +exports.USER_REFRESH_ACCOUNT_TYPE = 'authorized_user'; +class UserRefreshClient extends oauth2client_1.OAuth2Client { + constructor(optionsOrClientId, clientSecret, refreshToken, eagerRefreshThresholdMillis, forceRefreshOnFailure) { + const opts = optionsOrClientId && typeof optionsOrClientId === 'object' + ? optionsOrClientId + : { + clientId: optionsOrClientId, + clientSecret, + refreshToken, + eagerRefreshThresholdMillis, + forceRefreshOnFailure, + }; + super(opts); + this._refreshToken = opts.refreshToken; + this.credentials.refresh_token = opts.refreshToken; + } + /** + * Refreshes the access token. + * @param refreshToken An ignored refreshToken.. + * @param callback Optional callback. + */ + async refreshTokenNoCache( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + refreshToken) { + return super.refreshTokenNoCache(this._refreshToken); + } + async fetchIdToken(targetAudience) { + const res = await this.transporter.request({ + ...UserRefreshClient.RETRY_CONFIG, + url: this.endpoints.oauth2TokenUrl, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + }, + method: 'POST', + data: (0, querystring_1.stringify)({ + client_id: this._clientId, + client_secret: this._clientSecret, + grant_type: 'refresh_token', + refresh_token: this._refreshToken, + target_audience: targetAudience, + }), + }); + return res.data.id_token; + } + /** + * Create a UserRefreshClient credentials instance using the given input + * options. + * @param json The input object. + */ + fromJSON(json) { + if (!json) { + throw new Error('Must pass in a JSON object containing the user refresh token'); + } + if (json.type !== 'authorized_user') { + throw new Error('The incoming JSON object does not have the "authorized_user" type'); + } + if (!json.client_id) { + throw new Error('The incoming JSON object does not contain a client_id field'); + } + if (!json.client_secret) { + throw new Error('The incoming JSON object does not contain a client_secret field'); + } + if (!json.refresh_token) { + throw new Error('The incoming JSON object does not contain a refresh_token field'); + } + this._clientId = json.client_id; + this._clientSecret = json.client_secret; + this._refreshToken = json.refresh_token; + this.credentials.refresh_token = json.refresh_token; + this.quotaProjectId = json.quota_project_id; + this.universeDomain = json.universe_domain || this.universeDomain; + } + fromStream(inputStream, callback) { + if (callback) { + this.fromStreamAsync(inputStream).then(() => callback(), callback); + } + else { + return this.fromStreamAsync(inputStream); + } + } + async fromStreamAsync(inputStream) { + return new Promise((resolve, reject) => { + if (!inputStream) { + return reject(new Error('Must pass in a stream containing the user refresh token.')); + } + let s = ''; + inputStream + .setEncoding('utf8') + .on('error', reject) + .on('data', chunk => (s += chunk)) + .on('end', () => { + try { + const data = JSON.parse(s); + this.fromJSON(data); + return resolve(); + } + catch (err) { + return reject(err); + } + }); + }); + } + /** + * Create a UserRefreshClient credentials instance using the given input + * options. + * @param json The input object. + */ + static fromJSON(json) { + const client = new UserRefreshClient(); + client.fromJSON(json); + return client; + } +} +exports.UserRefreshClient = UserRefreshClient; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/stscredentials.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/stscredentials.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c9adf5e501c4bba41cd89ef72b430e005c6f912 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/stscredentials.d.ts @@ -0,0 +1,114 @@ +import { GaxiosResponse } from 'gaxios'; +import { Headers } from './oauth2client'; +import { ClientAuthentication, OAuthClientAuthHandler } from './oauth2common'; +/** + * Defines the interface needed to initialize an StsCredentials instance. + * The interface does not directly map to the spec and instead is converted + * to be compliant with the JavaScript style guide. This is because this is + * instantiated internally. + * StsCredentials implement the OAuth 2.0 token exchange based on + * https://tools.ietf.org/html/rfc8693. + * Request options are defined in + * https://tools.ietf.org/html/rfc8693#section-2.1 + */ +export interface StsCredentialsOptions { + /** + * REQUIRED. The value "urn:ietf:params:oauth:grant-type:token-exchange" + * indicates that a token exchange is being performed. + */ + grantType: string; + /** + * OPTIONAL. A URI that indicates the target service or resource where the + * client intends to use the requested security token. + */ + resource?: string; + /** + * OPTIONAL. The logical name of the target service where the client + * intends to use the requested security token. This serves a purpose + * similar to the "resource" parameter but with the client providing a + * logical name for the target service. + */ + audience?: string; + /** + * OPTIONAL. A list of space-delimited, case-sensitive strings, as defined + * in Section 3.3 of [RFC6749], that allow the client to specify the desired + * scope of the requested security token in the context of the service or + * resource where the token will be used. + */ + scope?: string[]; + /** + * OPTIONAL. An identifier, as described in Section 3 of [RFC8693], eg. + * "urn:ietf:params:oauth:token-type:access_token" for the type of the + * requested security token. + */ + requestedTokenType?: string; + /** + * REQUIRED. A security token that represents the identity of the party on + * behalf of whom the request is being made. + */ + subjectToken: string; + /** + * REQUIRED. An identifier, as described in Section 3 of [RFC8693], that + * indicates the type of the security token in the "subject_token" parameter. + */ + subjectTokenType: string; + actingParty?: { + /** + * OPTIONAL. A security token that represents the identity of the acting + * party. Typically, this will be the party that is authorized to use the + * requested security token and act on behalf of the subject. + */ + actorToken: string; + /** + * An identifier, as described in Section 3, that indicates the type of the + * security token in the "actor_token" parameter. This is REQUIRED when the + * "actor_token" parameter is present in the request but MUST NOT be + * included otherwise. + */ + actorTokenType: string; + }; +} +/** + * Defines the OAuth 2.0 token exchange successful response based on + * https://tools.ietf.org/html/rfc8693#section-2.2.1 + */ +export interface StsSuccessfulResponse { + access_token: string; + issued_token_type: string; + token_type: string; + expires_in?: number; + refresh_token?: string; + scope?: string; + res?: GaxiosResponse | null; +} +/** + * Implements the OAuth 2.0 token exchange based on + * https://tools.ietf.org/html/rfc8693 + */ +export declare class StsCredentials extends OAuthClientAuthHandler { + private readonly tokenExchangeEndpoint; + private transporter; + /** + * Initializes an STS credentials instance. + * @param tokenExchangeEndpoint The token exchange endpoint. + * @param clientAuthentication The client authentication credentials if + * available. + */ + constructor(tokenExchangeEndpoint: string | URL, clientAuthentication?: ClientAuthentication); + /** + * Exchanges the provided token for another type of token based on the + * rfc8693 spec. + * @param stsCredentialsOptions The token exchange options used to populate + * the token exchange request. + * @param additionalHeaders Optional additional headers to pass along the + * request. + * @param options Optional additional GCP-specific non-spec defined options + * to send with the request. + * Example: `&options=${encodeUriComponent(JSON.stringified(options))}` + * @return A promise that resolves with the token exchange response containing + * the requested token and its expiration time. + */ + exchangeToken(stsCredentialsOptions: StsCredentialsOptions, additionalHeaders?: Headers, options?: { + [key: string]: any; + }): Promise; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/stscredentials.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/stscredentials.js new file mode 100644 index 0000000000000000000000000000000000000000..46edef1c3121113fe8c1030563045f88137491e4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/stscredentials.js @@ -0,0 +1,109 @@ +"use strict"; +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StsCredentials = void 0; +const gaxios_1 = require("gaxios"); +const querystring = require("querystring"); +const transporters_1 = require("../transporters"); +const oauth2common_1 = require("./oauth2common"); +/** + * Implements the OAuth 2.0 token exchange based on + * https://tools.ietf.org/html/rfc8693 + */ +class StsCredentials extends oauth2common_1.OAuthClientAuthHandler { + /** + * Initializes an STS credentials instance. + * @param tokenExchangeEndpoint The token exchange endpoint. + * @param clientAuthentication The client authentication credentials if + * available. + */ + constructor(tokenExchangeEndpoint, clientAuthentication) { + super(clientAuthentication); + this.tokenExchangeEndpoint = tokenExchangeEndpoint; + this.transporter = new transporters_1.DefaultTransporter(); + } + /** + * Exchanges the provided token for another type of token based on the + * rfc8693 spec. + * @param stsCredentialsOptions The token exchange options used to populate + * the token exchange request. + * @param additionalHeaders Optional additional headers to pass along the + * request. + * @param options Optional additional GCP-specific non-spec defined options + * to send with the request. + * Example: `&options=${encodeUriComponent(JSON.stringified(options))}` + * @return A promise that resolves with the token exchange response containing + * the requested token and its expiration time. + */ + async exchangeToken(stsCredentialsOptions, additionalHeaders, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + options) { + var _a, _b, _c; + const values = { + grant_type: stsCredentialsOptions.grantType, + resource: stsCredentialsOptions.resource, + audience: stsCredentialsOptions.audience, + scope: (_a = stsCredentialsOptions.scope) === null || _a === void 0 ? void 0 : _a.join(' '), + requested_token_type: stsCredentialsOptions.requestedTokenType, + subject_token: stsCredentialsOptions.subjectToken, + subject_token_type: stsCredentialsOptions.subjectTokenType, + actor_token: (_b = stsCredentialsOptions.actingParty) === null || _b === void 0 ? void 0 : _b.actorToken, + actor_token_type: (_c = stsCredentialsOptions.actingParty) === null || _c === void 0 ? void 0 : _c.actorTokenType, + // Non-standard GCP-specific options. + options: options && JSON.stringify(options), + }; + // Remove undefined fields. + Object.keys(values).forEach(key => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (typeof values[key] === 'undefined') { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + delete values[key]; + } + }); + const headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + }; + // Inject additional STS headers if available. + Object.assign(headers, additionalHeaders || {}); + const opts = { + ...StsCredentials.RETRY_CONFIG, + url: this.tokenExchangeEndpoint.toString(), + method: 'POST', + headers, + data: querystring.stringify(values), + responseType: 'json', + }; + // Apply OAuth client authentication. + this.applyClientAuthenticationOptions(opts); + try { + const response = await this.transporter.request(opts); + // Successful response. + const stsSuccessfulResponse = response.data; + stsSuccessfulResponse.res = response; + return stsSuccessfulResponse; + } + catch (error) { + // Translate error to OAuthError. + if (error instanceof gaxios_1.GaxiosError && error.response) { + throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, + // Preserve other fields from the original error. + error); + } + // Request could fail before the server responds. + throw error; + } + } +} +exports.StsCredentials = StsCredentials; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1c6d088395e397c8d58bf516cb9e5deeb83fd16d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.d.ts @@ -0,0 +1,57 @@ +import { ExternalAccountSupplierContext } from './baseexternalclient'; +import { GaxiosOptions } from 'gaxios'; +import { SubjectTokenFormatType, SubjectTokenSupplier } from './identitypoolclient'; +/** + * Interface that defines options used to build a {@link UrlSubjectTokenSupplier} + */ +export interface UrlSubjectTokenSupplierOptions { + /** + * The URL to call to retrieve the subject token. This is typically a local + * metadata server. + */ + url: string; + /** + * The token file or URL response type (JSON or text). + */ + formatType: SubjectTokenFormatType; + /** + * For JSON response types, this is the subject_token field name. For Azure, + * this is access_token. For text response types, this is ignored. + */ + subjectTokenFieldName?: string; + /** + * The optional additional headers to send with the request to the metadata + * server url. + */ + headers?: { + [key: string]: string; + }; + /** + * Additional gaxios options to use for the request to the specified URL. + */ + additionalGaxiosOptions?: GaxiosOptions; +} +/** + * Internal subject token supplier implementation used when a URL + * is configured in the credential configuration used to build an {@link IdentityPoolClient} + */ +export declare class UrlSubjectTokenSupplier implements SubjectTokenSupplier { + private readonly url; + private readonly headers?; + private readonly formatType; + private readonly subjectTokenFieldName?; + private readonly additionalGaxiosOptions?; + /** + * Instantiates a URL subject token supplier. + * @param opts The URL subject token supplier options to build the supplier with. + */ + constructor(opts: UrlSubjectTokenSupplierOptions); + /** + * Sends a GET request to the URL provided in the constructor and resolves + * with the returned external subject token. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link IdentityPoolClient}, contains the requested audience and subject + * token type for the external account identity. Not used. + */ + getSubjectToken(context: ExternalAccountSupplierContext): Promise; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js new file mode 100644 index 0000000000000000000000000000000000000000..317736e5dafda923cb71b50b456169b4576db194 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js @@ -0,0 +1,63 @@ +"use strict"; +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UrlSubjectTokenSupplier = void 0; +/** + * Internal subject token supplier implementation used when a URL + * is configured in the credential configuration used to build an {@link IdentityPoolClient} + */ +class UrlSubjectTokenSupplier { + /** + * Instantiates a URL subject token supplier. + * @param opts The URL subject token supplier options to build the supplier with. + */ + constructor(opts) { + this.url = opts.url; + this.formatType = opts.formatType; + this.subjectTokenFieldName = opts.subjectTokenFieldName; + this.headers = opts.headers; + this.additionalGaxiosOptions = opts.additionalGaxiosOptions; + } + /** + * Sends a GET request to the URL provided in the constructor and resolves + * with the returned external subject token. + * @param context {@link ExternalAccountSupplierContext} from the calling + * {@link IdentityPoolClient}, contains the requested audience and subject + * token type for the external account identity. Not used. + */ + async getSubjectToken(context) { + const opts = { + ...this.additionalGaxiosOptions, + url: this.url, + method: 'GET', + headers: this.headers, + responseType: this.formatType, + }; + let subjectToken; + if (this.formatType === 'text') { + const response = await context.transporter.request(opts); + subjectToken = response.data; + } + else if (this.formatType === 'json' && this.subjectTokenFieldName) { + const response = await context.transporter.request(opts); + subjectToken = response.data[this.subjectTokenFieldName]; + } + if (!subjectToken) { + throw new Error('Unable to parse the subject_token from the credential_source URL'); + } + return subjectToken; + } +} +exports.UrlSubjectTokenSupplier = UrlSubjectTokenSupplier; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/browser/crypto.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/browser/crypto.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e0ed1aef7b80c761959d78be32aaf71c00da7564 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/browser/crypto.d.ts @@ -0,0 +1,27 @@ +import { Crypto, JwkCertificate } from '../crypto'; +export declare class BrowserCrypto implements Crypto { + constructor(); + sha256DigestBase64(str: string): Promise; + randomBytesBase64(count: number): string; + private static padBase64; + verify(pubkey: JwkCertificate, data: string, signature: string): Promise; + sign(privateKey: JwkCertificate, data: string): Promise; + decodeBase64StringUtf8(base64: string): string; + encodeBase64StringUtf8(text: string): string; + /** + * Computes the SHA-256 hash of the provided string. + * @param str The plain text string to hash. + * @return A promise that resolves with the SHA-256 hash of the provided + * string in hexadecimal encoding. + */ + sha256DigestHex(str: string): Promise; + /** + * Computes the HMAC hash of a message using the provided crypto key and the + * SHA-256 algorithm. + * @param key The secret crypto key in utf-8 or ArrayBuffer format. + * @param msg The plain text message. + * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer + * format. + */ + signWithHmacSha256(key: string | ArrayBuffer, msg: string): Promise; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/browser/crypto.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/browser/crypto.js new file mode 100644 index 0000000000000000000000000000000000000000..ccc6b5713d3d115862cf61bb4b2c20f321bb580e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/browser/crypto.js @@ -0,0 +1,126 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +/* global window */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BrowserCrypto = void 0; +// This file implements crypto functions we need using in-browser +// SubtleCrypto interface `window.crypto.subtle`. +const base64js = require("base64-js"); +const crypto_1 = require("../crypto"); +class BrowserCrypto { + constructor() { + if (typeof window === 'undefined' || + window.crypto === undefined || + window.crypto.subtle === undefined) { + throw new Error("SubtleCrypto not found. Make sure it's an https:// website."); + } + } + async sha256DigestBase64(str) { + // SubtleCrypto digest() method is async, so we must make + // this method async as well. + // To calculate SHA256 digest using SubtleCrypto, we first + // need to convert an input string to an ArrayBuffer: + const inputBuffer = new TextEncoder().encode(str); + // Result is ArrayBuffer as well. + const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer); + return base64js.fromByteArray(new Uint8Array(outputBuffer)); + } + randomBytesBase64(count) { + const array = new Uint8Array(count); + window.crypto.getRandomValues(array); + return base64js.fromByteArray(array); + } + static padBase64(base64) { + // base64js requires padding, so let's add some '=' + while (base64.length % 4 !== 0) { + base64 += '='; + } + return base64; + } + async verify(pubkey, data, signature) { + const algo = { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: 'SHA-256' }, + }; + const dataArray = new TextEncoder().encode(data); + const signatureArray = base64js.toByteArray(BrowserCrypto.padBase64(signature)); + const cryptoKey = await window.crypto.subtle.importKey('jwk', pubkey, algo, true, ['verify']); + // SubtleCrypto's verify method is async so we must make + // this method async as well. + const result = await window.crypto.subtle.verify(algo, cryptoKey, signatureArray, dataArray); + return result; + } + async sign(privateKey, data) { + const algo = { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: 'SHA-256' }, + }; + const dataArray = new TextEncoder().encode(data); + const cryptoKey = await window.crypto.subtle.importKey('jwk', privateKey, algo, true, ['sign']); + // SubtleCrypto's sign method is async so we must make + // this method async as well. + const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray); + return base64js.fromByteArray(new Uint8Array(result)); + } + decodeBase64StringUtf8(base64) { + const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base64)); + const result = new TextDecoder().decode(uint8array); + return result; + } + encodeBase64StringUtf8(text) { + const uint8array = new TextEncoder().encode(text); + const result = base64js.fromByteArray(uint8array); + return result; + } + /** + * Computes the SHA-256 hash of the provided string. + * @param str The plain text string to hash. + * @return A promise that resolves with the SHA-256 hash of the provided + * string in hexadecimal encoding. + */ + async sha256DigestHex(str) { + // SubtleCrypto digest() method is async, so we must make + // this method async as well. + // To calculate SHA256 digest using SubtleCrypto, we first + // need to convert an input string to an ArrayBuffer: + const inputBuffer = new TextEncoder().encode(str); + // Result is ArrayBuffer as well. + const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer); + return (0, crypto_1.fromArrayBufferToHex)(outputBuffer); + } + /** + * Computes the HMAC hash of a message using the provided crypto key and the + * SHA-256 algorithm. + * @param key The secret crypto key in utf-8 or ArrayBuffer format. + * @param msg The plain text message. + * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer + * format. + */ + async signWithHmacSha256(key, msg) { + // Convert key, if provided in ArrayBuffer format, to string. + const rawKey = typeof key === 'string' + ? key + : String.fromCharCode(...new Uint16Array(key)); + const enc = new TextEncoder(); + const cryptoKey = await window.crypto.subtle.importKey('raw', enc.encode(rawKey), { + name: 'HMAC', + hash: { + name: 'SHA-256', + }, + }, false, ['sign']); + return window.crypto.subtle.sign('HMAC', cryptoKey, enc.encode(msg)); + } +} +exports.BrowserCrypto = BrowserCrypto; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/crypto.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/crypto.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7897f68b675209f5faec410f47d15cd4163f0b9c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/crypto.d.ts @@ -0,0 +1,44 @@ +export interface JwkCertificate { + kty: string; + alg: string; + use?: string; + kid: string; + n: string; + e: string; +} +export interface CryptoSigner { + update(data: string): void; + sign(key: string, outputFormat: string): string; +} +export interface Crypto { + sha256DigestBase64(str: string): Promise; + randomBytesBase64(n: number): string; + verify(pubkey: string | JwkCertificate, data: string | Buffer, signature: string): Promise; + sign(privateKey: string | JwkCertificate, data: string | Buffer): Promise; + decodeBase64StringUtf8(base64: string): string; + encodeBase64StringUtf8(text: string): string; + /** + * Computes the SHA-256 hash of the provided string. + * @param str The plain text string to hash. + * @return A promise that resolves with the SHA-256 hash of the provided + * string in hexadecimal encoding. + */ + sha256DigestHex(str: string): Promise; + /** + * Computes the HMAC hash of a message using the provided crypto key and the + * SHA-256 algorithm. + * @param key The secret crypto key in utf-8 or ArrayBuffer format. + * @param msg The plain text message. + * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer + * format. + */ + signWithHmacSha256(key: string | ArrayBuffer, msg: string): Promise; +} +export declare function createCrypto(): Crypto; +export declare function hasBrowserCrypto(): boolean; +/** + * Converts an ArrayBuffer to a hexadecimal string. + * @param arrayBuffer The ArrayBuffer to convert to hexadecimal string. + * @return The hexadecimal encoding of the ArrayBuffer. + */ +export declare function fromArrayBufferToHex(arrayBuffer: ArrayBuffer): string; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/crypto.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/crypto.js new file mode 100644 index 0000000000000000000000000000000000000000..b66fddaebb9e5d8533c5bd42e7326a0247b5db50 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/crypto.js @@ -0,0 +1,47 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +/* global window */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createCrypto = createCrypto; +exports.hasBrowserCrypto = hasBrowserCrypto; +exports.fromArrayBufferToHex = fromArrayBufferToHex; +const crypto_1 = require("./browser/crypto"); +const crypto_2 = require("./node/crypto"); +function createCrypto() { + if (hasBrowserCrypto()) { + return new crypto_1.BrowserCrypto(); + } + return new crypto_2.NodeCrypto(); +} +function hasBrowserCrypto() { + return (typeof window !== 'undefined' && + typeof window.crypto !== 'undefined' && + typeof window.crypto.subtle !== 'undefined'); +} +/** + * Converts an ArrayBuffer to a hexadecimal string. + * @param arrayBuffer The ArrayBuffer to convert to hexadecimal string. + * @return The hexadecimal encoding of the ArrayBuffer. + */ +function fromArrayBufferToHex(arrayBuffer) { + // Convert buffer to byte array. + const byteArray = Array.from(new Uint8Array(arrayBuffer)); + // Convert bytes to hex string. + return byteArray + .map(byte => { + return byte.toString(16).padStart(2, '0'); + }) + .join(''); +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/node/crypto.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/node/crypto.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8a56b117df31c920faa2878a714b5f9c8a6635ec --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/node/crypto.d.ts @@ -0,0 +1,25 @@ +import { Crypto } from '../crypto'; +export declare class NodeCrypto implements Crypto { + sha256DigestBase64(str: string): Promise; + randomBytesBase64(count: number): string; + verify(pubkey: string, data: string | Buffer, signature: string): Promise; + sign(privateKey: string, data: string | Buffer): Promise; + decodeBase64StringUtf8(base64: string): string; + encodeBase64StringUtf8(text: string): string; + /** + * Computes the SHA-256 hash of the provided string. + * @param str The plain text string to hash. + * @return A promise that resolves with the SHA-256 hash of the provided + * string in hexadecimal encoding. + */ + sha256DigestHex(str: string): Promise; + /** + * Computes the HMAC hash of a message using the provided crypto key and the + * SHA-256 algorithm. + * @param key The secret crypto key in utf-8 or ArrayBuffer format. + * @param msg The plain text message. + * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer + * format. + */ + signWithHmacSha256(key: string | ArrayBuffer, msg: string): Promise; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/node/crypto.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/node/crypto.js new file mode 100644 index 0000000000000000000000000000000000000000..26ede463f7d7abc55676ea17fe94cc7d6ce17577 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/crypto/node/crypto.js @@ -0,0 +1,82 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NodeCrypto = void 0; +const crypto = require("crypto"); +class NodeCrypto { + async sha256DigestBase64(str) { + return crypto.createHash('sha256').update(str).digest('base64'); + } + randomBytesBase64(count) { + return crypto.randomBytes(count).toString('base64'); + } + async verify(pubkey, data, signature) { + const verifier = crypto.createVerify('RSA-SHA256'); + verifier.update(data); + verifier.end(); + return verifier.verify(pubkey, signature, 'base64'); + } + async sign(privateKey, data) { + const signer = crypto.createSign('RSA-SHA256'); + signer.update(data); + signer.end(); + return signer.sign(privateKey, 'base64'); + } + decodeBase64StringUtf8(base64) { + return Buffer.from(base64, 'base64').toString('utf-8'); + } + encodeBase64StringUtf8(text) { + return Buffer.from(text, 'utf-8').toString('base64'); + } + /** + * Computes the SHA-256 hash of the provided string. + * @param str The plain text string to hash. + * @return A promise that resolves with the SHA-256 hash of the provided + * string in hexadecimal encoding. + */ + async sha256DigestHex(str) { + return crypto.createHash('sha256').update(str).digest('hex'); + } + /** + * Computes the HMAC hash of a message using the provided crypto key and the + * SHA-256 algorithm. + * @param key The secret crypto key in utf-8 or ArrayBuffer format. + * @param msg The plain text message. + * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer + * format. + */ + async signWithHmacSha256(key, msg) { + const cryptoKey = typeof key === 'string' ? key : toBuffer(key); + return toArrayBuffer(crypto.createHmac('sha256', cryptoKey).update(msg).digest()); + } +} +exports.NodeCrypto = NodeCrypto; +/** + * Converts a Node.js Buffer to an ArrayBuffer. + * https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer + * @param buffer The Buffer input to covert. + * @return The ArrayBuffer representation of the input. + */ +function toArrayBuffer(buffer) { + return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength); +} +/** + * Converts an ArrayBuffer to a Node.js Buffer. + * @param arrayBuffer The ArrayBuffer input to covert. + * @return The Buffer representation of the input. + */ +function toBuffer(arrayBuffer) { + return Buffer.from(arrayBuffer); +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd44dc5efa414866b0604a09bc8776d61a0dedd9 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/index.d.ts @@ -0,0 +1,33 @@ +import { GoogleAuth } from './auth/googleauth'; +export * as gcpMetadata from 'gcp-metadata'; +export * as gaxios from 'gaxios'; +import { AuthClient } from './auth/authclient'; +export { AuthClient, DEFAULT_UNIVERSE } from './auth/authclient'; +export { Compute, ComputeOptions } from './auth/computeclient'; +export { CredentialBody, CredentialRequest, Credentials, JWTInput, } from './auth/credentials'; +export { GCPEnv } from './auth/envDetect'; +export { GoogleAuthOptions, ProjectIdCallback } from './auth/googleauth'; +export { IAMAuth, RequestMetadata } from './auth/iam'; +export { IdTokenClient, IdTokenProvider } from './auth/idtokenclient'; +export { Claims, JWTAccess } from './auth/jwtaccess'; +export { JWT, JWTOptions } from './auth/jwtclient'; +export { Impersonated, ImpersonatedOptions } from './auth/impersonated'; +export { Certificates, CodeChallengeMethod, CodeVerifierResults, GenerateAuthUrlOpts, GetTokenOptions, OAuth2Client, OAuth2ClientOptions, RefreshOptions, TokenInfo, VerifyIdTokenOptions, ClientAuthentication, } from './auth/oauth2client'; +export { LoginTicket, TokenPayload } from './auth/loginticket'; +export { UserRefreshClient, UserRefreshClientOptions, } from './auth/refreshclient'; +export { AwsClient, AwsClientOptions, AwsSecurityCredentialsSupplier, } from './auth/awsclient'; +export { AwsSecurityCredentials, AwsRequestSigner, } from './auth/awsrequestsigner'; +export { IdentityPoolClient, IdentityPoolClientOptions, SubjectTokenSupplier, } from './auth/identitypoolclient'; +export { ExternalAccountClient, ExternalAccountClientOptions, } from './auth/externalclient'; +export { BaseExternalAccountClient, BaseExternalAccountClientOptions, SharedExternalAccountClientOptions, ExternalAccountSupplierContext, IamGenerateAccessTokenResponse, } from './auth/baseexternalclient'; +export { CredentialAccessBoundary, DownscopedClient, } from './auth/downscopedclient'; +export { PluggableAuthClient, PluggableAuthClientOptions, ExecutableError, } from './auth/pluggable-auth-client'; +export { PassThroughClient } from './auth/passthrough'; +export { DefaultTransporter } from './transporters'; +type ALL_EXPORTS = (typeof import('./'))[keyof typeof import('./')]; +/** + * A union type for all {@link AuthClient `AuthClient`}s. + */ +export type AnyAuthClient = InstanceType>; +declare const auth: GoogleAuth; +export { auth, GoogleAuth }; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e0691c2dae1df67a0f208a97213b8c6feb001827 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/index.js @@ -0,0 +1,68 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GoogleAuth = exports.auth = exports.DefaultTransporter = exports.PassThroughClient = exports.ExecutableError = exports.PluggableAuthClient = exports.DownscopedClient = exports.BaseExternalAccountClient = exports.ExternalAccountClient = exports.IdentityPoolClient = exports.AwsRequestSigner = exports.AwsClient = exports.UserRefreshClient = exports.LoginTicket = exports.ClientAuthentication = exports.OAuth2Client = exports.CodeChallengeMethod = exports.Impersonated = exports.JWT = exports.JWTAccess = exports.IdTokenClient = exports.IAMAuth = exports.GCPEnv = exports.Compute = exports.DEFAULT_UNIVERSE = exports.AuthClient = exports.gaxios = exports.gcpMetadata = void 0; +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +const googleauth_1 = require("./auth/googleauth"); +Object.defineProperty(exports, "GoogleAuth", { enumerable: true, get: function () { return googleauth_1.GoogleAuth; } }); +// Export common deps to ensure types/instances are the exact match. Useful +// for consistently configuring the library across versions. +exports.gcpMetadata = require("gcp-metadata"); +exports.gaxios = require("gaxios"); +var authclient_1 = require("./auth/authclient"); +Object.defineProperty(exports, "AuthClient", { enumerable: true, get: function () { return authclient_1.AuthClient; } }); +Object.defineProperty(exports, "DEFAULT_UNIVERSE", { enumerable: true, get: function () { return authclient_1.DEFAULT_UNIVERSE; } }); +var computeclient_1 = require("./auth/computeclient"); +Object.defineProperty(exports, "Compute", { enumerable: true, get: function () { return computeclient_1.Compute; } }); +var envDetect_1 = require("./auth/envDetect"); +Object.defineProperty(exports, "GCPEnv", { enumerable: true, get: function () { return envDetect_1.GCPEnv; } }); +var iam_1 = require("./auth/iam"); +Object.defineProperty(exports, "IAMAuth", { enumerable: true, get: function () { return iam_1.IAMAuth; } }); +var idtokenclient_1 = require("./auth/idtokenclient"); +Object.defineProperty(exports, "IdTokenClient", { enumerable: true, get: function () { return idtokenclient_1.IdTokenClient; } }); +var jwtaccess_1 = require("./auth/jwtaccess"); +Object.defineProperty(exports, "JWTAccess", { enumerable: true, get: function () { return jwtaccess_1.JWTAccess; } }); +var jwtclient_1 = require("./auth/jwtclient"); +Object.defineProperty(exports, "JWT", { enumerable: true, get: function () { return jwtclient_1.JWT; } }); +var impersonated_1 = require("./auth/impersonated"); +Object.defineProperty(exports, "Impersonated", { enumerable: true, get: function () { return impersonated_1.Impersonated; } }); +var oauth2client_1 = require("./auth/oauth2client"); +Object.defineProperty(exports, "CodeChallengeMethod", { enumerable: true, get: function () { return oauth2client_1.CodeChallengeMethod; } }); +Object.defineProperty(exports, "OAuth2Client", { enumerable: true, get: function () { return oauth2client_1.OAuth2Client; } }); +Object.defineProperty(exports, "ClientAuthentication", { enumerable: true, get: function () { return oauth2client_1.ClientAuthentication; } }); +var loginticket_1 = require("./auth/loginticket"); +Object.defineProperty(exports, "LoginTicket", { enumerable: true, get: function () { return loginticket_1.LoginTicket; } }); +var refreshclient_1 = require("./auth/refreshclient"); +Object.defineProperty(exports, "UserRefreshClient", { enumerable: true, get: function () { return refreshclient_1.UserRefreshClient; } }); +var awsclient_1 = require("./auth/awsclient"); +Object.defineProperty(exports, "AwsClient", { enumerable: true, get: function () { return awsclient_1.AwsClient; } }); +var awsrequestsigner_1 = require("./auth/awsrequestsigner"); +Object.defineProperty(exports, "AwsRequestSigner", { enumerable: true, get: function () { return awsrequestsigner_1.AwsRequestSigner; } }); +var identitypoolclient_1 = require("./auth/identitypoolclient"); +Object.defineProperty(exports, "IdentityPoolClient", { enumerable: true, get: function () { return identitypoolclient_1.IdentityPoolClient; } }); +var externalclient_1 = require("./auth/externalclient"); +Object.defineProperty(exports, "ExternalAccountClient", { enumerable: true, get: function () { return externalclient_1.ExternalAccountClient; } }); +var baseexternalclient_1 = require("./auth/baseexternalclient"); +Object.defineProperty(exports, "BaseExternalAccountClient", { enumerable: true, get: function () { return baseexternalclient_1.BaseExternalAccountClient; } }); +var downscopedclient_1 = require("./auth/downscopedclient"); +Object.defineProperty(exports, "DownscopedClient", { enumerable: true, get: function () { return downscopedclient_1.DownscopedClient; } }); +var pluggable_auth_client_1 = require("./auth/pluggable-auth-client"); +Object.defineProperty(exports, "PluggableAuthClient", { enumerable: true, get: function () { return pluggable_auth_client_1.PluggableAuthClient; } }); +Object.defineProperty(exports, "ExecutableError", { enumerable: true, get: function () { return pluggable_auth_client_1.ExecutableError; } }); +var passthrough_1 = require("./auth/passthrough"); +Object.defineProperty(exports, "PassThroughClient", { enumerable: true, get: function () { return passthrough_1.PassThroughClient; } }); +var transporters_1 = require("./transporters"); +Object.defineProperty(exports, "DefaultTransporter", { enumerable: true, get: function () { return transporters_1.DefaultTransporter; } }); +const auth = new googleauth_1.GoogleAuth(); +exports.auth = auth; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/messages.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/messages.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9de99bc725a01946752d4e65940e218d545bb1fa --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/messages.d.ts @@ -0,0 +1,11 @@ +export declare enum WarningTypes { + WARNING = "Warning", + DEPRECATION = "DeprecationWarning" +} +export declare function warn(warning: Warning): void; +export interface Warning { + code: string; + type: WarningTypes; + message: string; + warned?: boolean; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/messages.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/messages.js new file mode 100644 index 0000000000000000000000000000000000000000..9a45c3d89d6d04f09c6250bc65f95752d43fd09b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/messages.js @@ -0,0 +1,39 @@ +"use strict"; +// Copyright 2018 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WarningTypes = void 0; +exports.warn = warn; +var WarningTypes; +(function (WarningTypes) { + WarningTypes["WARNING"] = "Warning"; + WarningTypes["DEPRECATION"] = "DeprecationWarning"; +})(WarningTypes || (exports.WarningTypes = WarningTypes = {})); +function warn(warning) { + // Only show a given warning once + if (warning.warned) { + return; + } + warning.warned = true; + if (typeof process !== 'undefined' && process.emitWarning) { + // @types/node doesn't recognize the emitWarning syntax which + // accepts a config object, so `as any` it is + // https://nodejs.org/docs/latest-v8.x/api/process.html#process_process_emitwarning_warning_options + // eslint-disable-next-line @typescript-eslint/no-explicit-any + process.emitWarning(warning.message, warning); + } + else { + console.warn(warning.message); + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/options.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/options.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ede9689dd2dde9b188e11fe4ef0ad0149a1a07f6 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/options.d.ts @@ -0,0 +1 @@ +export declare function validate(options: any): void; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/options.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/options.js new file mode 100644 index 0000000000000000000000000000000000000000..a6db1a6fd112595252e2f36a3c088727328b76d1 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/options.js @@ -0,0 +1,34 @@ +"use strict"; +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validate = validate; +// Accepts an options object passed from the user to the API. In the +// previous version of the API, it referred to a `Request` options object. +// Now it refers to an Axiox Request Config object. This is here to help +// ensure users don't pass invalid options when they upgrade from 0.x to 1.x. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function validate(options) { + const vpairs = [ + { invalid: 'uri', expected: 'url' }, + { invalid: 'json', expected: 'data' }, + { invalid: 'qs', expected: 'params' }, + ]; + for (const pair of vpairs) { + if (options[pair.invalid]) { + const e = `'${pair.invalid}' is not a valid configuration option. Please use '${pair.expected}' instead. This library is using Axios for requests. Please see https://github.com/axios/axios to learn more about the valid request options.`; + throw new Error(e); + } + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/transporters.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/transporters.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b0ff7f2cc028ba302a364f98c34f61b0192923c3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/transporters.d.ts @@ -0,0 +1,40 @@ +import { Gaxios, GaxiosError, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +export interface Transporter { + defaults?: GaxiosOptions; + request(opts: GaxiosOptions): GaxiosPromise; +} +export interface BodyResponseCallback { + (err: Error | null, res?: GaxiosResponse | null): void; +} +export interface RequestError extends GaxiosError { + errors: Error[]; +} +export declare class DefaultTransporter implements Transporter { + /** + * Default user agent. + */ + static readonly USER_AGENT: string; + /** + * A configurable, replacable `Gaxios` instance. + */ + instance: Gaxios; + /** + * Configures request options before making a request. + * @param opts GaxiosOptions options. + * @return Configured options. + */ + configure(opts?: GaxiosOptions): GaxiosOptions; + /** + * Makes a request using Gaxios with given options. + * @param opts GaxiosOptions options. + * @param callback optional callback that contains GaxiosResponse object. + * @return GaxiosPromise, assuming no callback is passed. + */ + request(opts: GaxiosOptions): GaxiosPromise; + get defaults(): GaxiosOptions; + set defaults(opts: GaxiosOptions); + /** + * Changes the error to include details from the body. + */ + private processError; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/transporters.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/transporters.js new file mode 100644 index 0000000000000000000000000000000000000000..7e9d072e52cba77c48ca77cd7a85797258ae59bc --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/transporters.js @@ -0,0 +1,110 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DefaultTransporter = void 0; +const gaxios_1 = require("gaxios"); +const options_1 = require("./options"); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const pkg = require('../../package.json'); +const PRODUCT_NAME = 'google-api-nodejs-client'; +class DefaultTransporter { + constructor() { + /** + * A configurable, replacable `Gaxios` instance. + */ + this.instance = new gaxios_1.Gaxios(); + } + /** + * Configures request options before making a request. + * @param opts GaxiosOptions options. + * @return Configured options. + */ + configure(opts = {}) { + opts.headers = opts.headers || {}; + if (typeof window === 'undefined') { + // set transporter user agent if not in browser + const uaValue = opts.headers['User-Agent']; + if (!uaValue) { + opts.headers['User-Agent'] = DefaultTransporter.USER_AGENT; + } + else if (!uaValue.includes(`${PRODUCT_NAME}/`)) { + opts.headers['User-Agent'] = + `${uaValue} ${DefaultTransporter.USER_AGENT}`; + } + // track google-auth-library-nodejs version: + if (!opts.headers['x-goog-api-client']) { + const nodeVersion = process.version.replace(/^v/, ''); + opts.headers['x-goog-api-client'] = `gl-node/${nodeVersion}`; + } + } + return opts; + } + /** + * Makes a request using Gaxios with given options. + * @param opts GaxiosOptions options. + * @param callback optional callback that contains GaxiosResponse object. + * @return GaxiosPromise, assuming no callback is passed. + */ + request(opts) { + // ensure the user isn't passing in request-style options + opts = this.configure(opts); + (0, options_1.validate)(opts); + return this.instance.request(opts).catch(e => { + throw this.processError(e); + }); + } + get defaults() { + return this.instance.defaults; + } + set defaults(opts) { + this.instance.defaults = opts; + } + /** + * Changes the error to include details from the body. + */ + processError(e) { + const res = e.response; + const err = e; + const body = res ? res.data : null; + if (res && body && body.error && res.status !== 200) { + if (typeof body.error === 'string') { + err.message = body.error; + err.status = res.status; + } + else if (Array.isArray(body.error.errors)) { + err.message = body.error.errors + .map((err2) => err2.message) + .join('\n'); + err.code = body.error.code; + err.errors = body.error.errors; + } + else { + err.message = body.error.message; + err.code = body.error.code; + } + } + else if (res && res.status >= 400) { + // Consider all 4xx and 5xx responses errors. + err.message = body; + err.status = res.status; + } + return err; + } +} +exports.DefaultTransporter = DefaultTransporter; +/** + * Default user agent. + */ +DefaultTransporter.USER_AGENT = `${PRODUCT_NAME}/${pkg.version}`; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/util.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/util.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2c01475dbffdc119d6795948c98af920a2680442 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/util.d.ts @@ -0,0 +1,151 @@ +/** + * A utility for converting snake_case to camelCase. + * + * For, for example `my_snake_string` becomes `mySnakeString`. + * + * @internal + */ +export type SnakeToCamel = S extends `${infer FirstWord}_${infer Remainder}` ? `${FirstWord}${Capitalize>}` : S; +/** + * A utility for converting an type's keys from snake_case + * to camelCase, if the keys are strings. + * + * For example: + * + * ```ts + * { + * my_snake_string: boolean; + * myCamelString: string; + * my_snake_obj: { + * my_snake_obj_string: string; + * }; + * } + * ``` + * + * becomes: + * + * ```ts + * { + * mySnakeString: boolean; + * myCamelString: string; + * mySnakeObj: { + * mySnakeObjString: string; + * } + * } + * ``` + * + * @remarks + * + * The generated documentation for the camelCase'd properties won't be available + * until {@link https://github.com/microsoft/TypeScript/issues/50715} has been + * resolved. + * + * @internal + */ +export type SnakeToCamelObject = { + [K in keyof T as SnakeToCamel]: T[K] extends {} ? SnakeToCamelObject : T[K]; +}; +/** + * A utility for adding camelCase versions of a type's snake_case keys, if the + * keys are strings, preserving any existing keys. + * + * For example: + * + * ```ts + * { + * my_snake_boolean: boolean; + * myCamelString: string; + * my_snake_obj: { + * my_snake_obj_string: string; + * }; + * } + * ``` + * + * becomes: + * + * ```ts + * { + * my_snake_boolean: boolean; + * mySnakeBoolean: boolean; + * myCamelString: string; + * my_snake_obj: { + * my_snake_obj_string: string; + * }; + * mySnakeObj: { + * mySnakeObjString: string; + * } + * } + * ``` + * @remarks + * + * The generated documentation for the camelCase'd properties won't be available + * until {@link https://github.com/microsoft/TypeScript/issues/50715} has been + * resolved. + * + * Tracking: {@link https://github.com/googleapis/google-auth-library-nodejs/issues/1686} + * + * @internal + */ +export type OriginalAndCamel = { + [K in keyof T as K | SnakeToCamel]: T[K] extends {} ? OriginalAndCamel : T[K]; +}; +/** + * Returns the camel case of a provided string. + * + * @remarks + * + * Match any `_` and not `_` pair, then return the uppercase of the not `_` + * character. + * + * @internal + * + * @param str the string to convert + * @returns the camelCase'd string + */ +export declare function snakeToCamel(str: T): SnakeToCamel; +/** + * Get the value of `obj[key]` or `obj[camelCaseKey]`, with a preference + * for original, non-camelCase key. + * + * @param obj object to lookup a value in + * @returns a `get` function for getting `obj[key || snakeKey]`, if available + */ +export declare function originalOrCamelOptions(obj?: T): { + get: & string>(key: K) => OriginalAndCamel[K]; +}; +export interface LRUCacheOptions { + /** + * The maximum number of items to cache. + */ + capacity: number; + /** + * An optional max age for items in milliseconds. + */ + maxAge?: number; +} +/** + * A simple LRU cache utility. + * Not meant for external usage. + * + * @experimental + * @internal + */ +export declare class LRUCache { + #private; + readonly capacity: number; + maxAge?: number; + constructor(options: LRUCacheOptions); + /** + * Add an item to the cache. + * + * @param key the key to upsert + * @param value the value of the key + */ + set(key: string, value: T): void; + /** + * Get an item from the cache. + * + * @param key the key to retrieve + */ + get(key: string): T | undefined; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/util.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/util.js new file mode 100644 index 0000000000000000000000000000000000000000..856b7051d6bebecda60ae7a1f2557a22478fe083 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/build/src/util.js @@ -0,0 +1,125 @@ +"use strict"; +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _LRUCache_instances, _LRUCache_cache, _LRUCache_moveToEnd, _LRUCache_evict; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LRUCache = void 0; +exports.snakeToCamel = snakeToCamel; +exports.originalOrCamelOptions = originalOrCamelOptions; +/** + * Returns the camel case of a provided string. + * + * @remarks + * + * Match any `_` and not `_` pair, then return the uppercase of the not `_` + * character. + * + * @internal + * + * @param str the string to convert + * @returns the camelCase'd string + */ +function snakeToCamel(str) { + return str.replace(/([_][^_])/g, match => match.slice(1).toUpperCase()); +} +/** + * Get the value of `obj[key]` or `obj[camelCaseKey]`, with a preference + * for original, non-camelCase key. + * + * @param obj object to lookup a value in + * @returns a `get` function for getting `obj[key || snakeKey]`, if available + */ +function originalOrCamelOptions(obj) { + /** + * + * @param key an index of object, preferably snake_case + * @returns the value `obj[key || snakeKey]`, if available + */ + function get(key) { + var _a; + const o = (obj || {}); + return (_a = o[key]) !== null && _a !== void 0 ? _a : o[snakeToCamel(key)]; + } + return { get }; +} +/** + * A simple LRU cache utility. + * Not meant for external usage. + * + * @experimental + * @internal + */ +class LRUCache { + constructor(options) { + _LRUCache_instances.add(this); + /** + * Maps are in order. Thus, the older item is the first item. + * + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map} + */ + _LRUCache_cache.set(this, new Map()); + this.capacity = options.capacity; + this.maxAge = options.maxAge; + } + /** + * Add an item to the cache. + * + * @param key the key to upsert + * @param value the value of the key + */ + set(key, value) { + __classPrivateFieldGet(this, _LRUCache_instances, "m", _LRUCache_moveToEnd).call(this, key, value); + __classPrivateFieldGet(this, _LRUCache_instances, "m", _LRUCache_evict).call(this); + } + /** + * Get an item from the cache. + * + * @param key the key to retrieve + */ + get(key) { + const item = __classPrivateFieldGet(this, _LRUCache_cache, "f").get(key); + if (!item) + return; + __classPrivateFieldGet(this, _LRUCache_instances, "m", _LRUCache_moveToEnd).call(this, key, item.value); + __classPrivateFieldGet(this, _LRUCache_instances, "m", _LRUCache_evict).call(this); + return item.value; + } +} +exports.LRUCache = LRUCache; +_LRUCache_cache = new WeakMap(), _LRUCache_instances = new WeakSet(), _LRUCache_moveToEnd = function _LRUCache_moveToEnd(key, value) { + __classPrivateFieldGet(this, _LRUCache_cache, "f").delete(key); + __classPrivateFieldGet(this, _LRUCache_cache, "f").set(key, { + value, + lastAccessed: Date.now(), + }); +}, _LRUCache_evict = function _LRUCache_evict() { + const cutoffDate = this.maxAge ? Date.now() - this.maxAge : 0; + /** + * Because we know Maps are in order, this item is both the + * last item in the list (capacity) and oldest (maxAge). + */ + let oldestItem = __classPrivateFieldGet(this, _LRUCache_cache, "f").entries().next(); + while (!oldestItem.done && + (__classPrivateFieldGet(this, _LRUCache_cache, "f").size > this.capacity || // too many + oldestItem.value[1].lastAccessed < cutoffDate) // too old + ) { + __classPrivateFieldGet(this, _LRUCache_cache, "f").delete(oldestItem.value[0]); + oldestItem = __classPrivateFieldGet(this, _LRUCache_cache, "f").entries().next(); + } +}; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a7e3231ed6a91a4c897abdc77805f9c6eb5acbfb --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-auth-library/package.json @@ -0,0 +1,94 @@ +{ + "name": "google-auth-library", + "version": "9.15.1", + "author": "Google Inc.", + "description": "Google APIs Authentication Client Library for Node.js", + "engines": { + "node": ">=14" + }, + "main": "./build/src/index.js", + "types": "./build/src/index.d.ts", + "repository": "googleapis/google-auth-library-nodejs.git", + "keywords": [ + "google", + "api", + "google apis", + "client", + "client library" + ], + "dependencies": { + "base64-js": "^1.3.0", + "ecdsa-sig-formatter": "^1.0.11", + "gaxios": "^6.1.1", + "gcp-metadata": "^6.1.0", + "gtoken": "^7.0.0", + "jws": "^4.0.0" + }, + "devDependencies": { + "@types/base64-js": "^1.2.5", + "@types/chai": "^4.1.7", + "@types/jws": "^3.1.0", + "@types/mocha": "^9.0.0", + "@types/mv": "^2.1.0", + "@types/ncp": "^2.0.1", + "@types/node": "^20.4.2", + "@types/sinon": "^17.0.0", + "assert-rejects": "^1.0.0", + "c8": "^8.0.0", + "chai": "^4.2.0", + "cheerio": "1.0.0-rc.12", + "codecov": "^3.0.2", + "engine.io": "6.6.2", + "gts": "^5.0.0", + "is-docker": "^2.0.0", + "jsdoc": "^4.0.0", + "jsdoc-fresh": "^3.0.0", + "jsdoc-region-tag": "^3.0.0", + "karma": "^6.0.0", + "karma-chrome-launcher": "^3.0.0", + "karma-coverage": "^2.0.0", + "karma-firefox-launcher": "^2.0.0", + "karma-mocha": "^2.0.0", + "karma-sourcemap-loader": "^0.4.0", + "karma-webpack": "5.0.0", + "keypair": "^1.0.4", + "linkinator": "^4.0.0", + "mocha": "^9.2.2", + "mv": "^2.1.1", + "ncp": "^2.0.0", + "nock": "^13.0.0", + "null-loader": "^4.0.0", + "pdfmake": "0.2.12", + "puppeteer": "^21.0.0", + "sinon": "^18.0.0", + "ts-loader": "^8.0.0", + "typescript": "^5.1.6", + "webpack": "^5.21.2", + "webpack-cli": "^4.0.0" + }, + "files": [ + "build/src", + "!build/src/**/*.map" + ], + "scripts": { + "test": "c8 mocha build/test", + "clean": "gts clean", + "prepare": "npm run compile", + "lint": "gts check", + "compile": "tsc -p .", + "fix": "gts fix", + "pretest": "npm run compile -- --sourceMap", + "docs": "jsdoc -c .jsdoc.json", + "samples-setup": "cd samples/ && npm link ../ && npm run setup && cd ../", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + "system-test": "mocha build/system-test --timeout 60000", + "presystem-test": "npm run compile -- --sourceMap", + "webpack": "webpack", + "browser-test": "karma start", + "docs-test": "linkinator docs", + "predocs-test": "npm run docs", + "prelint": "cd samples; npm link ../; npm install", + "precompile": "gts clean" + }, + "license": "Apache-2.0" +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/LICENSE b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/colours.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/colours.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ff55f9f6be91c7e83505b8e60c9053f6fc03afa7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/colours.d.ts @@ -0,0 +1,29 @@ +import * as tty from 'node:tty'; +/** + * Handles figuring out if we can use ANSI colours and handing out the escape codes. + * + * This is for package-internal use only, and may change at any time. + * + * @private + * @internal + */ +export declare class Colours { + static enabled: boolean; + static reset: string; + static bright: string; + static dim: string; + static red: string; + static green: string; + static yellow: string; + static blue: string; + static magenta: string; + static cyan: string; + static white: string; + static grey: string; + /** + * @param stream The stream (e.g. process.stderr) + * @returns true if the stream should have colourization enabled + */ + static isEnabled(stream: tty.WriteStream): boolean; + static refresh(): void; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/colours.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/colours.js new file mode 100644 index 0000000000000000000000000000000000000000..5132d72d481abe6dee1e997b9fff47811a509008 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/colours.js @@ -0,0 +1,80 @@ +"use strict"; +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Colours = void 0; +/** + * Handles figuring out if we can use ANSI colours and handing out the escape codes. + * + * This is for package-internal use only, and may change at any time. + * + * @private + * @internal + */ +class Colours { + /** + * @param stream The stream (e.g. process.stderr) + * @returns true if the stream should have colourization enabled + */ + static isEnabled(stream) { + return (stream.isTTY && + (typeof stream.getColorDepth === 'function' + ? stream.getColorDepth() > 2 + : true)); + } + static refresh() { + Colours.enabled = Colours.isEnabled(process.stderr); + if (!this.enabled) { + Colours.reset = ''; + Colours.bright = ''; + Colours.dim = ''; + Colours.red = ''; + Colours.green = ''; + Colours.yellow = ''; + Colours.blue = ''; + Colours.magenta = ''; + Colours.cyan = ''; + Colours.white = ''; + Colours.grey = ''; + } + else { + Colours.reset = '\u001b[0m'; + Colours.bright = '\u001b[1m'; + Colours.dim = '\u001b[2m'; + Colours.red = '\u001b[31m'; + Colours.green = '\u001b[32m'; + Colours.yellow = '\u001b[33m'; + Colours.blue = '\u001b[34m'; + Colours.magenta = '\u001b[35m'; + Colours.cyan = '\u001b[36m'; + Colours.white = '\u001b[37m'; + Colours.grey = '\u001b[90m'; + } + } +} +exports.Colours = Colours; +Colours.enabled = false; +Colours.reset = ''; +Colours.bright = ''; +Colours.dim = ''; +Colours.red = ''; +Colours.green = ''; +Colours.yellow = ''; +Colours.blue = ''; +Colours.magenta = ''; +Colours.cyan = ''; +Colours.white = ''; +Colours.grey = ''; +Colours.refresh(); +//# sourceMappingURL=colours.js.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/colours.js.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/colours.js.map new file mode 100644 index 0000000000000000000000000000000000000000..dbfe6032d981380d5362883e532f18e19ac31b38 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/colours.js.map @@ -0,0 +1 @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AAM,GAAG,WAAW,CAAC;YAC7B,OAAO,CAAC,GAAG,GAAG,WAAW,CAAC;YAC1B,OAAO,CAAC,GAAG,GAAG,YAAY,CAAC;YAC3B,OAAO,CAAC,KAAK,GAAG,YAAY,CAAC;YAC7B,OAAO,CAAC,MAAM,GAAG,YAAY,CAAC;YAC9B,OAAO,CAAC,IAAI,GAAG,YAAY,CAAC;YAC5B,OAAO,CAAC,OAAO,GAAG,YAAY,CAAC;YAC/B,OAAO,CAAC,IAAI,GAAG,YAAY,CAAC;YAC5B,OAAO,CAAC,KAAK,GAAG,YAAY,CAAC;YAC7B,OAAO,CAAC,IAAI,GAAG,YAAY,CAAC;QAC9B,CAAC;IACH,CAAC;;AAvDH,0BAwDC;AAvDQ,eAAO,GAAG,KAAK,CAAC;AAChB,aAAK,GAAG,EAAE,CAAC;AACX,cAAM,GAAG,EAAE,CAAC;AACZ,WAAG,GAAG,EAAE,CAAC;AAET,WAAG,GAAG,EAAE,CAAC;AACT,aAAK,GAAG,EAAE,CAAC;AACX,cAAM,GAAG,EAAE,CAAC;AACZ,YAAI,GAAG,EAAE,CAAC;AACV,eAAO,GAAG,EAAE,CAAC;AACb,YAAI,GAAG,EAAE,CAAC;AACV,aAAK,GAAG,EAAE,CAAC;AACX,YAAI,GAAG,EAAE,CAAC;AA6CnB,OAAO,CAAC,OAAO,EAAE,CAAC"} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a163f85f950acb1226df3d387e3904210cd98d8c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/index.d.ts @@ -0,0 +1 @@ +export * from './logging-utils'; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a2d5d17a875fa7eeb66b01062414409251c5898c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/index.js @@ -0,0 +1,31 @@ +"use strict"; +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./logging-utils"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/index.js.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..edf4a2f1f1dc905dfd0f5593949b5e543d7d7e0f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,kDAAkD;AAClD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;;;;;;;;;;;;;;AAEjC,kDAAgC"} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/logging-utils.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/logging-utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e0fa8fad7f672bee094cf7ce934fd48b1dc8626a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/logging-utils.d.ts @@ -0,0 +1,222 @@ +import { EventEmitter } from 'node:events'; +/** + * This module defines an ad-hoc debug logger for Google Cloud Platform + * client libraries in Node. An ad-hoc debug logger is a tool which lets + * users use an external, unified interface (in this case, environment + * variables) to determine what logging they want to see at runtime. This + * isn't necessarily fed into the console, but is meant to be under the + * control of the user. The kind of logging that will be produced by this + * is more like "call retry happened", not "event you'd want to record + * in Cloud Logger". + * + * More for Googlers implementing libraries with it: + * go/cloud-client-logging-design + */ +/** + * Possible log levels. These are a subset of Cloud Observability levels. + * https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity + */ +export declare enum LogSeverity { + DEFAULT = "DEFAULT", + DEBUG = "DEBUG", + INFO = "INFO", + WARNING = "WARNING", + ERROR = "ERROR" +} +/** + * A set of suggested log metadata fields. + */ +export interface LogFields { + /** + * Log level - undefined/null === DEFAULT. + */ + severity?: LogSeverity; + /** + * If this log is associated with an OpenTelemetry trace, you can put the + * trace ID here to pass on that association. + */ + telemetryTraceId?: string; + /** + * If this log is associated with an OpenTelemetry trace, you can put the + * span ID here to pass on that association. + */ + telemetrySpanId?: string; + /** + * This is a catch-all for any other items you might want to go into + * structured logs. Library implementers, please see the spec docs above + * for the items envisioned to go here. + */ + other?: unknown; +} +/** + * Adds typings for event sinks. + */ +export declare interface AdhocDebugLogger { + on(event: 'log', listener: (fields: LogFields, args: unknown[]) => void): this; + on(event: string, listener: Function): this; +} +/** + * Our logger instance. This actually contains the meat of dealing + * with log lines, including EventEmitter. This contains the function + * that will be passed back to users of the package. + */ +export declare class AdhocDebugLogger extends EventEmitter { + namespace: string; + upstream: AdhocDebugLogCallable; + func: AdhocDebugLogFunction; + /** + * @param upstream The backend will pass a function that will be + * called whenever our logger function is invoked. + */ + constructor(namespace: string, upstream: AdhocDebugLogCallable); + invoke(fields: LogFields, ...args: unknown[]): void; + invokeSeverity(severity: LogSeverity, ...args: unknown[]): void; +} +/** + * This can be used in place of a real logger while waiting for Promises or disabling logging. + */ +export declare const placeholder: AdhocDebugLogFunction; +/** + * When the user receives a log function (below), this will be the basic function + * call interface for it. + */ +export interface AdhocDebugLogCallable { + (fields: LogFields, ...args: unknown[]): void; +} +/** + * Adds typing info for the EventEmitter we're adding to the returned function. + * + * Note that this interface may change at any time, as we're reserving the + * right to add new backends at the logger level. + * + * @private + * @internal + */ +export interface AdhocDebugLogFunction extends AdhocDebugLogCallable { + instance: AdhocDebugLogger; + on(event: 'log', listener: (fields: LogFields, args: unknown[]) => void): this; + debug(...args: unknown[]): void; + info(...args: unknown[]): void; + warn(...args: unknown[]): void; + error(...args: unknown[]): void; + sublog(namespace: string): AdhocDebugLogFunction; +} +/** + * One of these can be passed to support a third-party backend, like "debug". + * We're splitting this out because ESM can complicate optional module loading. + * + * Note that this interface may change at any time, as we're reserving the + * right to add new backends at the logger level. + * + * @private + * @internal + */ +export interface DebugLogBackend { + /** + * Outputs a log to this backend. + * + * @param namespace The "system" that will be used for filtering. This may also + * include a "subsystem" in the form "system:subsystem". + * @param fields Logging fields to be included as metadata. + * @param args Any parameters to passed to a utils.format() type formatter. + */ + log(namespace: string, fields: LogFields, ...args: unknown[]): void; + /** + * Passes in the system/subsystem filters from the global environment variables. + * This lets the backend merge with any native ones. + * + * @param filters A list of wildcards matching systems or system:subsystem pairs. + */ + setFilters(filters: string[]): void; +} +/** + * The base class for debug logging backends. It's possible to use this, but the + * same non-guarantees above still apply (unstable interface, etc). + * + * @private + * @internal + */ +export declare abstract class DebugLogBackendBase implements DebugLogBackend { + cached: Map; + filters: string[]; + filtersSet: boolean; + constructor(); + /** + * Creates a callback function that we can call to send log lines out. + * + * @param namespace The system/subsystem namespace. + */ + abstract makeLogger(namespace: string): AdhocDebugLogCallable; + /** + * Provides a callback for the subclass to hook if it needs to do something + * specific with `this.filters`. + */ + abstract setFilters(): void; + log(namespace: string, fields: LogFields, ...args: unknown[]): void; +} +/** + * @returns A backend based on Node util.debuglog; this is the default. + */ +export declare function getNodeBackend(): DebugLogBackend; +type DebugPackage = any; +/** + * Creates a "debug" package backend. The user must call require('debug') and pass + * the resulting object to this function. + * + * ``` + * setBackend(getDebugBackend(require('debug'))) + * ``` + * + * https://www.npmjs.com/package/debug + * + * Note: Google does not explicitly endorse or recommend this package; it's just + * being provided as an option. + * + * @returns A backend based on the npm "debug" package. + */ +export declare function getDebugBackend(debugPkg: DebugPackage): DebugLogBackend; +/** + * Creates a "structured logging" backend. This pretty much works like the + * Node logger, but it outputs structured logging JSON matching Google + * Cloud's ingestion specs instead of plain text. + * + * ``` + * setBackend(getStructuredBackend()) + * ``` + * + * @param upstream If you want to use something besides the Node backend to + * write the actual log lines into, pass that here. + * @returns A backend based on Google Cloud structured logging. + */ +export declare function getStructuredBackend(upstream?: DebugLogBackend): DebugLogBackend; +/** + * The environment variables that we standardized on, for all ad-hoc logging. + */ +export declare const env: { + /** + * Filter wildcards specific to the Node syntax, and similar to the built-in + * utils.debuglog() environment variable. If missing, disables logging. + */ + nodeEnables: string; +}; +/** + * Set the backend to use for our log output. + * - A backend object + * - null to disable logging + * - undefined for "nothing yet", defaults to the Node backend + * + * @param backend Results from one of the get*Backend() functions. + */ +export declare function setBackend(backend: DebugLogBackend | null): void; +/** + * Creates a logging function. Multiple calls to this with the same namespace + * will produce the same logger, with the same event emitter hooks. + * + * Namespaces can be a simple string ("system" name), or a qualified string + * (system:subsystem), which can be used for filtering, or for "system:*". + * + * @param namespace The namespace, a descriptive text string. + * @returns A function you can call that works similar to console.log(). + */ +export declare function log(namespace: string, parent?: AdhocDebugLogFunction): AdhocDebugLogFunction; +export {}; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/logging-utils.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/logging-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..1f205b9c2c4841ec53fa8593f05c6bf4429bdaf4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/logging-utils.js @@ -0,0 +1,406 @@ +"use strict"; +// Copyright 2021-2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.env = exports.DebugLogBackendBase = exports.placeholder = exports.AdhocDebugLogger = exports.LogSeverity = void 0; +exports.getNodeBackend = getNodeBackend; +exports.getDebugBackend = getDebugBackend; +exports.getStructuredBackend = getStructuredBackend; +exports.setBackend = setBackend; +exports.log = log; +const node_events_1 = require("node:events"); +const process = __importStar(require("node:process")); +const util = __importStar(require("node:util")); +const colours_1 = require("./colours"); +// Some functions (as noted) are based on the Node standard library, from +// the following file: +// +// https://github.com/nodejs/node/blob/main/lib/internal/util/debuglog.js +/** + * This module defines an ad-hoc debug logger for Google Cloud Platform + * client libraries in Node. An ad-hoc debug logger is a tool which lets + * users use an external, unified interface (in this case, environment + * variables) to determine what logging they want to see at runtime. This + * isn't necessarily fed into the console, but is meant to be under the + * control of the user. The kind of logging that will be produced by this + * is more like "call retry happened", not "event you'd want to record + * in Cloud Logger". + * + * More for Googlers implementing libraries with it: + * go/cloud-client-logging-design + */ +/** + * Possible log levels. These are a subset of Cloud Observability levels. + * https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity + */ +var LogSeverity; +(function (LogSeverity) { + LogSeverity["DEFAULT"] = "DEFAULT"; + LogSeverity["DEBUG"] = "DEBUG"; + LogSeverity["INFO"] = "INFO"; + LogSeverity["WARNING"] = "WARNING"; + LogSeverity["ERROR"] = "ERROR"; +})(LogSeverity || (exports.LogSeverity = LogSeverity = {})); +/** + * Our logger instance. This actually contains the meat of dealing + * with log lines, including EventEmitter. This contains the function + * that will be passed back to users of the package. + */ +class AdhocDebugLogger extends node_events_1.EventEmitter { + /** + * @param upstream The backend will pass a function that will be + * called whenever our logger function is invoked. + */ + constructor(namespace, upstream) { + super(); + this.namespace = namespace; + this.upstream = upstream; + this.func = Object.assign(this.invoke.bind(this), { + // Also add an instance pointer back to us. + instance: this, + // And pull over the EventEmitter functionality. + on: (event, listener) => this.on(event, listener), + }); + // Convenience methods for log levels. + this.func.debug = (...args) => this.invokeSeverity(LogSeverity.DEBUG, ...args); + this.func.info = (...args) => this.invokeSeverity(LogSeverity.INFO, ...args); + this.func.warn = (...args) => this.invokeSeverity(LogSeverity.WARNING, ...args); + this.func.error = (...args) => this.invokeSeverity(LogSeverity.ERROR, ...args); + this.func.sublog = (namespace) => log(namespace, this.func); + } + invoke(fields, ...args) { + // Push out any upstream logger first. + if (this.upstream) { + this.upstream(fields, ...args); + } + // Emit sink events. + this.emit('log', fields, args); + } + invokeSeverity(severity, ...args) { + this.invoke({ severity }, ...args); + } +} +exports.AdhocDebugLogger = AdhocDebugLogger; +/** + * This can be used in place of a real logger while waiting for Promises or disabling logging. + */ +exports.placeholder = new AdhocDebugLogger('', () => { }).func; +/** + * The base class for debug logging backends. It's possible to use this, but the + * same non-guarantees above still apply (unstable interface, etc). + * + * @private + * @internal + */ +class DebugLogBackendBase { + constructor() { + var _a; + this.cached = new Map(); + this.filters = []; + this.filtersSet = false; + // Look for the Node config variable for what systems to enable. We'll store + // these for the log method below, which will call setFilters() once. + let nodeFlag = (_a = process.env[exports.env.nodeEnables]) !== null && _a !== void 0 ? _a : '*'; + if (nodeFlag === 'all') { + nodeFlag = '*'; + } + this.filters = nodeFlag.split(','); + } + log(namespace, fields, ...args) { + try { + if (!this.filtersSet) { + this.setFilters(); + this.filtersSet = true; + } + let logger = this.cached.get(namespace); + if (!logger) { + logger = this.makeLogger(namespace); + this.cached.set(namespace, logger); + } + logger(fields, ...args); + } + catch (e) { + // Silently ignore all errors; we don't want them to interfere with + // the user's running app. + // e; + console.error(e); + } + } +} +exports.DebugLogBackendBase = DebugLogBackendBase; +// The basic backend. This one definitely works, but it's less feature-filled. +// +// Rather than using util.debuglog, this implements the same basic logic directly. +// The reason for this decision is that debuglog checks the value of the +// NODE_DEBUG environment variable before any user code runs; we therefore +// can't pipe our own enables into it (and util.debuglog will never print unless +// the user duplicates it into NODE_DEBUG, which isn't reasonable). +// +class NodeBackend extends DebugLogBackendBase { + constructor() { + super(...arguments); + // Default to allowing all systems, since we gate earlier based on whether the + // variable is empty. + this.enabledRegexp = /.*/g; + } + isEnabled(namespace) { + return this.enabledRegexp.test(namespace); + } + makeLogger(namespace) { + if (!this.enabledRegexp.test(namespace)) { + return () => { }; + } + return (fields, ...args) => { + var _a; + // TODO: `fields` needs to be turned into a string here, one way or another. + const nscolour = `${colours_1.Colours.green}${namespace}${colours_1.Colours.reset}`; + const pid = `${colours_1.Colours.yellow}${process.pid}${colours_1.Colours.reset}`; + let level; + switch (fields.severity) { + case LogSeverity.ERROR: + level = `${colours_1.Colours.red}${fields.severity}${colours_1.Colours.reset}`; + break; + case LogSeverity.INFO: + level = `${colours_1.Colours.magenta}${fields.severity}${colours_1.Colours.reset}`; + break; + case LogSeverity.WARNING: + level = `${colours_1.Colours.yellow}${fields.severity}${colours_1.Colours.reset}`; + break; + default: + level = (_a = fields.severity) !== null && _a !== void 0 ? _a : LogSeverity.DEFAULT; + break; + } + const msg = util.formatWithOptions({ colors: colours_1.Colours.enabled }, ...args); + const filteredFields = Object.assign({}, fields); + delete filteredFields.severity; + const fieldsJson = Object.getOwnPropertyNames(filteredFields).length + ? JSON.stringify(filteredFields) + : ''; + const fieldsColour = fieldsJson + ? `${colours_1.Colours.grey}${fieldsJson}${colours_1.Colours.reset}` + : ''; + console.error('%s [%s|%s] %s%s', pid, nscolour, level, msg, fieldsJson ? ` ${fieldsColour}` : ''); + }; + } + // Regexp patterns below are from here: + // https://github.com/nodejs/node/blob/c0aebed4b3395bd65d54b18d1fd00f071002ac20/lib/internal/util/debuglog.js#L36 + setFilters() { + const totalFilters = this.filters.join(','); + const regexp = totalFilters + .replace(/[|\\{}()[\]^$+?.]/g, '\\$&') + .replace(/\*/g, '.*') + .replace(/,/g, '$|^'); + this.enabledRegexp = new RegExp(`^${regexp}$`, 'i'); + } +} +/** + * @returns A backend based on Node util.debuglog; this is the default. + */ +function getNodeBackend() { + return new NodeBackend(); +} +class DebugBackend extends DebugLogBackendBase { + constructor(pkg) { + super(); + this.debugPkg = pkg; + } + makeLogger(namespace) { + const debugLogger = this.debugPkg(namespace); + return (fields, ...args) => { + // TODO: `fields` needs to be turned into a string here. + debugLogger(args[0], ...args.slice(1)); + }; + } + setFilters() { + var _a; + const existingFilters = (_a = process.env['NODE_DEBUG']) !== null && _a !== void 0 ? _a : ''; + process.env['NODE_DEBUG'] = `${existingFilters}${existingFilters ? ',' : ''}${this.filters.join(',')}`; + } +} +/** + * Creates a "debug" package backend. The user must call require('debug') and pass + * the resulting object to this function. + * + * ``` + * setBackend(getDebugBackend(require('debug'))) + * ``` + * + * https://www.npmjs.com/package/debug + * + * Note: Google does not explicitly endorse or recommend this package; it's just + * being provided as an option. + * + * @returns A backend based on the npm "debug" package. + */ +function getDebugBackend(debugPkg) { + return new DebugBackend(debugPkg); +} +/** + * This pretty much works like the Node logger, but it outputs structured + * logging JSON matching Google Cloud's ingestion specs. Rather than handling + * its own output, it wraps another backend. The passed backend must be a subclass + * of `DebugLogBackendBase` (any of the backends exposed by this package will work). + */ +class StructuredBackend extends DebugLogBackendBase { + constructor(upstream) { + var _a; + super(); + this.upstream = (_a = upstream) !== null && _a !== void 0 ? _a : new NodeBackend(); + } + makeLogger(namespace) { + const debugLogger = this.upstream.makeLogger(namespace); + return (fields, ...args) => { + var _a; + const severity = (_a = fields.severity) !== null && _a !== void 0 ? _a : LogSeverity.INFO; + const json = Object.assign({ + severity, + message: util.format(...args), + }, fields); + const jsonString = JSON.stringify(json); + debugLogger(fields, jsonString); + }; + } + setFilters() { + this.upstream.setFilters(); + } +} +/** + * Creates a "structured logging" backend. This pretty much works like the + * Node logger, but it outputs structured logging JSON matching Google + * Cloud's ingestion specs instead of plain text. + * + * ``` + * setBackend(getStructuredBackend()) + * ``` + * + * @param upstream If you want to use something besides the Node backend to + * write the actual log lines into, pass that here. + * @returns A backend based on Google Cloud structured logging. + */ +function getStructuredBackend(upstream) { + return new StructuredBackend(upstream); +} +/** + * The environment variables that we standardized on, for all ad-hoc logging. + */ +exports.env = { + /** + * Filter wildcards specific to the Node syntax, and similar to the built-in + * utils.debuglog() environment variable. If missing, disables logging. + */ + nodeEnables: 'GOOGLE_SDK_NODE_LOGGING', +}; +// Keep a copy of all namespaced loggers so users can reliably .on() them. +// Note that these cached functions will need to deal with changes in the backend. +const loggerCache = new Map(); +// Our current global backend. This might be: +let cachedBackend = undefined; +/** + * Set the backend to use for our log output. + * - A backend object + * - null to disable logging + * - undefined for "nothing yet", defaults to the Node backend + * + * @param backend Results from one of the get*Backend() functions. + */ +function setBackend(backend) { + cachedBackend = backend; + loggerCache.clear(); +} +/** + * Creates a logging function. Multiple calls to this with the same namespace + * will produce the same logger, with the same event emitter hooks. + * + * Namespaces can be a simple string ("system" name), or a qualified string + * (system:subsystem), which can be used for filtering, or for "system:*". + * + * @param namespace The namespace, a descriptive text string. + * @returns A function you can call that works similar to console.log(). + */ +function log(namespace, parent) { + // If the enable flag isn't set, do nothing. + const enablesFlag = process.env[exports.env.nodeEnables]; + if (!enablesFlag) { + return exports.placeholder; + } + // This might happen mostly if the typings are dropped in a user's code, + // or if they're calling from JavaScript. + if (!namespace) { + return exports.placeholder; + } + // Handle sub-loggers. + if (parent) { + namespace = `${parent.instance.namespace}:${namespace}`; + } + // Reuse loggers so things like event sinks are persistent. + const existing = loggerCache.get(namespace); + if (existing) { + return existing.func; + } + // Do we have a backend yet? + if (cachedBackend === null) { + // Explicitly disabled. + return exports.placeholder; + } + else if (cachedBackend === undefined) { + // One hasn't been made yet, so default to Node. + cachedBackend = getNodeBackend(); + } + // The logger is further wrapped so we can handle the backend changing out. + const logger = (() => { + let previousBackend = undefined; + const newLogger = new AdhocDebugLogger(namespace, (fields, ...args) => { + if (previousBackend !== cachedBackend) { + // Did the user pass a custom backend? + if (cachedBackend === null) { + // Explicitly disabled. + return; + } + else if (cachedBackend === undefined) { + // One hasn't been made yet, so default to Node. + cachedBackend = getNodeBackend(); + } + previousBackend = cachedBackend; + } + cachedBackend === null || cachedBackend === void 0 ? void 0 : cachedBackend.log(namespace, fields, ...args); + }); + return newLogger; + })(); + loggerCache.set(namespace, logger); + return logger.func; +} +//# sourceMappingURL=logging-utils.js.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/logging-utils.js.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/logging-utils.js.map new file mode 100644 index 0000000000000000000000000000000000000000..8e3011d9f1abcef18bf8e92e84e6310dd614df17 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/logging-utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"logging-utils.js","sourceRoot":"","sources":["../../src/logging-utils.ts"],"names":[],"mappings":";AAAA,iCAAiC;AACjC,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,kDAAkD;AAClD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;;;;;;;;;;;;;;;;;;;;;;;;AAoVjC,wCAEC;AA+CD,0CAEC;AAmDD,oDAIC;AA4BD,gCAGC;AAYD,kBA+DC;AAtiBD,6CAAyC;AACzC,sDAAwC;AACxC,gDAAkC;AAClC,uCAAkC;AAElC,yEAAyE;AACzE,sBAAsB;AACtB,EAAE;AACF,yE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B,uBAAuB;QACvB,OAAO,mBAAW,CAAC;IACrB,CAAC;SAAM,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;QACvC,gDAAgD;QAChD,aAAa,GAAG,cAAc,EAAE,CAAC;IACnC,CAAC;IAED,2EAA2E;IAC3E,MAAM,MAAM,GAAqB,CAAC,GAAG,EAAE;QACrC,IAAI,eAAe,GAAgC,SAAS,CAAC;QAC7D,MAAM,SAAS,GAAG,IAAI,gBAAgB,CACpC,SAAS,EACT,CAAC,MAAiB,EAAE,GAAG,IAAe,EAAE,EAAE;YACxC,IAAI,eAAe,KAAK,aAAa,EAAE,CAAC;gBACtC,sCAAsC;gBACtC,IAAI,aAAa,KAAK,IAAI,EAAE,CAAC;oBAC3B,uBAAuB;oBACvB,OAAO;gBACT,CAAC;qBAAM,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;oBACvC,gDAAgD;oBAChD,aAAa,GAAG,cAAc,EAAE,CAAC;gBACnC,CAAC;gBAED,eAAe,GAAG,aAAa,CAAC;YAClC,CAAC;YAED,aAAa,aAAb,aAAa,uBAAb,aAAa,CAAE,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC,CAAC;QACjD,CAAC,CACF,CAAC;QACF,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,EAAE,CAAC;IAEL,WAAW,CAAC,GAAG,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;IACnC,OAAO,MAAM,CAAC,IAAI,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/temporal.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/temporal.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..82da9ab790e59035d03b9884c7e7a1c55599e02d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/temporal.d.ts @@ -0,0 +1,45 @@ +/** + * Simplified interface analogous to the tc39 Temporal.Duration + * parameter to from(). This doesn't support the full gamut (years, days). + */ +export interface DurationLike { + hours?: number; + minutes?: number; + seconds?: number; + millis?: number; +} +/** + * Simplified list of values to pass to Duration.totalOf(). This + * list is taken from the tc39 Temporal.Duration proposal, but + * larger and smaller units have been left off. + */ +export type TotalOfUnit = 'hour' | 'minute' | 'second' | 'millisecond'; +/** + * Duration class with an interface similar to the tc39 Temporal + * proposal. Since it's not fully finalized, and polyfills have + * inconsistent compatibility, for now this shim class will be + * used to set durations in Pub/Sub. + * + * This class will remain here for at least the next major version, + * eventually to be replaced by the tc39 Temporal built-in. + * + * https://tc39.es/proposal-temporal/docs/duration.html + */ +export declare class Duration { + private millis; + private static secondInMillis; + private static minuteInMillis; + private static hourInMillis; + private constructor(); + /** + * Calculates the total number of units of type 'totalOf' that would + * fit inside this duration. + */ + totalOf(totalOf: TotalOfUnit): number; + /** + * Creates a Duration from a DurationLike, which is an object + * containing zero or more of the following: hours, seconds, + * minutes, millis. + */ + static from(durationLike: DurationLike): Duration; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/temporal.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/temporal.js new file mode 100644 index 0000000000000000000000000000000000000000..fa59c24a98d71e7416ae6eef792b03be2279d466 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/temporal.js @@ -0,0 +1,68 @@ +"use strict"; +// Copyright 2022-2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Duration = void 0; +/** + * Duration class with an interface similar to the tc39 Temporal + * proposal. Since it's not fully finalized, and polyfills have + * inconsistent compatibility, for now this shim class will be + * used to set durations in Pub/Sub. + * + * This class will remain here for at least the next major version, + * eventually to be replaced by the tc39 Temporal built-in. + * + * https://tc39.es/proposal-temporal/docs/duration.html + */ +class Duration { + constructor(millis) { + this.millis = millis; + } + /** + * Calculates the total number of units of type 'totalOf' that would + * fit inside this duration. + */ + totalOf(totalOf) { + switch (totalOf) { + case 'hour': + return this.millis / Duration.hourInMillis; + case 'minute': + return this.millis / Duration.minuteInMillis; + case 'second': + return this.millis / Duration.secondInMillis; + case 'millisecond': + return this.millis; + default: + throw new Error(`Invalid unit in call to totalOf(): ${totalOf}`); + } + } + /** + * Creates a Duration from a DurationLike, which is an object + * containing zero or more of the following: hours, seconds, + * minutes, millis. + */ + static from(durationLike) { + var _a, _b, _c, _d; + let millis = (_a = durationLike.millis) !== null && _a !== void 0 ? _a : 0; + millis += ((_b = durationLike.seconds) !== null && _b !== void 0 ? _b : 0) * Duration.secondInMillis; + millis += ((_c = durationLike.minutes) !== null && _c !== void 0 ? _c : 0) * Duration.minuteInMillis; + millis += ((_d = durationLike.hours) !== null && _d !== void 0 ? _d : 0) * Duration.hourInMillis; + return new Duration(millis); + } +} +exports.Duration = Duration; +Duration.secondInMillis = 1000; +Duration.minuteInMillis = Duration.secondInMillis * 60; +Duration.hourInMillis = Duration.minuteInMillis * 60; +//# sourceMappingURL=temporal.js.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/temporal.js.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/temporal.js.map new file mode 100644 index 0000000000000000000000000000000000000000..c38c4461edb24c1cf136af85554ea66d7492ee0c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/build/src/temporal.js.map @@ -0,0 +1 @@ +{"version":3,"file":"temporal.js","sourceRoot":"","sources":["../../src/temporal.ts"],"names":[],"mappings":";AAAA,iCAAiC;AACjC,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,kDAAkD;AAClD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;AA6BjC;;;;;;;;;;GAUG;AACH,MAAa,QAAQ;IAOnB,YAAoB,MAAc;QAChC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED;;;OAGG;IACH,OAAO,CAAC,OAAoB;QAC1B,QAAQ,OAAO,EAAE,CAAC;YAChB,KAAK,MAAM;gBACT,OAAO,IAAI,CAAC,MAAM,GAAG,QAAQ,CAAC,YAAY,CAAC;YAC7C,KAAK,QAAQ;gBACX,OAAO,IAAI,CAAC,MAAM,GAAG,QAAQ,CAAC,cAAc,CAAC;YAC/C,KAAK,QAAQ;gBACX,OAAO,IAAI,CAAC,MAAM,GAAG,QAAQ,CAAC,cAAc,CAAC;YAC/C,KAAK,aAAa;gBAChB,OAAO,IAAI,CAAC,MAAM,CAAC;YACrB;gBACE,MAAM,IAAI,KAAK,CAAC,sCAAsC,OAAO,EAAE,CAAC,CAAC;QACrE,CAAC;IACH,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,IAAI,CAAC,YAA0B;;QACpC,IAAI,MAAM,GAAG,MAAA,YAAY,CAAC,MAAM,mCAAI,CAAC,CAAC;QACtC,MAAM,IAAI,CAAC,MAAA,YAAY,CAAC,OAAO,mCAAI,CAAC,CAAC,GAAG,QAAQ,CAAC,cAAc,CAAC;QAChE,MAAM,IAAI,CAAC,MAAA,YAAY,CAAC,OAAO,mCAAI,CAAC,CAAC,GAAG,QAAQ,CAAC,cAAc,CAAC;QAChE,MAAM,IAAI,CAAC,MAAA,YAAY,CAAC,KAAK,mCAAI,CAAC,CAAC,GAAG,QAAQ,CAAC,YAAY,CAAC;QAE5D,OAAO,IAAI,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC9B,CAAC;;AA1CH,4BA2CC;AAxCgB,uBAAc,GAAG,IAAI,CAAC;AACtB,uBAAc,GAAG,QAAQ,CAAC,cAAc,GAAG,EAAE,CAAC;AAC9C,qBAAY,GAAG,QAAQ,CAAC,cAAc,GAAG,EAAE,CAAC"} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7ffe48d70fa7f3e3a635c7b15866ed5164c228b2 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/google-logging-utils/package.json @@ -0,0 +1,39 @@ +{ + "name": "google-logging-utils", + "version": "0.0.2", + "description": "An ad-hoc debug logger package for other libraries", + "main": "build/src/index.js", + "files": [ + "build/src" + ], + "scripts": { + "pretest": "npm run prepare", + "test": "c8 mocha build/test", + "lint": "gts check test src samples", + "clean": "gts clean", + "compile": "tsc -p . && cp -r test/fixtures build/test", + "fix": "gts fix", + "prepare": "npm run compile", + "precompile": "gts clean", + "samples-test": "echo no samples 🙀", + "system-test": "echo no system tests 🙀" + }, + "author": "Google API Authors", + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "https://github.com/googleapis/gax-nodejs.git", + "directory": "logging-utils" + }, + "devDependencies": { + "@types/mocha": "^10.0.10", + "@types/node": "^22.9.1", + "c8": "^9.0.0", + "gts": "^5.0.0", + "mocha": "^9.0.0", + "typescript": "^5.1.6" + }, + "engines": { + "node": ">=14" + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gtoken/CHANGELOG.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gtoken/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..6b5ccceb95acdd41068abf774c2a7037f55fedfc --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gtoken/CHANGELOG.md @@ -0,0 +1,372 @@ +# Changelog + +[npm history][1] + +[1]: https://www.npmjs.com/package/gtoken?activeTab=versions + +## [7.1.0](https://github.com/googleapis/node-gtoken/compare/v7.0.1...v7.1.0) (2024-02-01) + + +### Features + +* Enable Token Retries ([#481](https://github.com/googleapis/node-gtoken/issues/481)) ([ed9f91e](https://github.com/googleapis/node-gtoken/commit/ed9f91e4764744426de95fd2510b68ee53677514)) + +## [7.0.1](https://github.com/googleapis/node-gtoken/compare/v7.0.0...v7.0.1) (2023-07-12) + + +### Bug Fixes + +* **deps:** Update gaxios to 6.0.0 ([#462](https://github.com/googleapis/node-gtoken/issues/462)) ([c05a2b3](https://github.com/googleapis/node-gtoken/commit/c05a2b35d1bb369fc54f80784d9361c0d6cbc2e7)) + +## [7.0.0](https://github.com/googleapis/node-gtoken/compare/v6.1.2...v7.0.0) (2023-07-11) + + +### ⚠ BREAKING CHANGES + +* move to node 14 as minimum version ([#457](https://github.com/googleapis/node-gtoken/issues/457)) +* remove support for conversion of *.p12 to *.pem ([#452](https://github.com/googleapis/node-gtoken/issues/452)) + +### Features + +* Remove support for conversion of *.p12 to *.pem ([#452](https://github.com/googleapis/node-gtoken/issues/452)) ([522a96d](https://github.com/googleapis/node-gtoken/commit/522a96dd38ad5d486e9337f72efdf1a5523fded4)) + + +### Miscellaneous Chores + +* Move to node 14 as minimum version ([#457](https://github.com/googleapis/node-gtoken/issues/457)) ([429df81](https://github.com/googleapis/node-gtoken/commit/429df814cd4224d5eacce72cfe8e924e53cc7f30)) + +## [6.1.2](https://github.com/googleapis/node-gtoken/compare/v6.1.1...v6.1.2) (2022-08-23) + + +### Bug Fixes + +* remove pip install statements ([#1546](https://github.com/googleapis/node-gtoken/issues/1546)) ([#440](https://github.com/googleapis/node-gtoken/issues/440)) ([6fb8562](https://github.com/googleapis/node-gtoken/commit/6fb856207b07112096c033adb6d3f0edf5e5093d)) + +## [6.1.1](https://github.com/googleapis/node-gtoken/compare/v6.1.0...v6.1.1) (2022-08-04) + + +### Bug Fixes + +* **deps:** update gaxios to 5.0.1 ([#436](https://github.com/googleapis/node-gtoken/issues/436)) ([0d5d0e9](https://github.com/googleapis/node-gtoken/commit/0d5d0e9c6ec51911f1e44d97c02dc0cd791c7d05)) + +## [6.1.0](https://github.com/googleapis/node-gtoken/compare/v6.0.1...v6.1.0) (2022-06-28) + + +### Features + +* allow customizing the http client ([#426](https://github.com/googleapis/node-gtoken/issues/426)) ([408ad04](https://github.com/googleapis/node-gtoken/commit/408ad048a2595313717bf427fc34aa29a6e7fb3c)) + +## [6.0.1](https://github.com/googleapis/node-gtoken/compare/v6.0.0...v6.0.1) (2022-06-07) + + +### Bug Fixes + +* **deps:** update dependency google-p12-pem to v4 ([#430](https://github.com/googleapis/node-gtoken/issues/430)) ([bd0848b](https://github.com/googleapis/node-gtoken/commit/bd0848b15554742e2fd73b05073bd84e1aec2a3f)) + +## [6.0.0](https://github.com/googleapis/node-gtoken/compare/v5.3.2...v6.0.0) (2022-05-10) + + +### ⚠ BREAKING CHANGES + +* update library to use Node 12 (#428) + +### Build System + +* update library to use Node 12 ([#428](https://github.com/googleapis/node-gtoken/issues/428)) ([288b662](https://github.com/googleapis/node-gtoken/commit/288b662d990ce53a6824ddc67c384253487fdc04)) + +### [5.3.2](https://github.com/googleapis/node-gtoken/compare/v5.3.1...v5.3.2) (2022-01-28) + + +### Bug Fixes + +* upgrade google-p12-pem to 3.1.3 ([#413](https://github.com/googleapis/node-gtoken/issues/413)) ([c3cebaf](https://github.com/googleapis/node-gtoken/commit/c3cebaf620c62f57385804fe5d852ce3e6398dc1)) + +### [5.3.1](https://www.github.com/googleapis/node-gtoken/compare/v5.3.0...v5.3.1) (2021-08-11) + + +### Bug Fixes + +* **build:** migrate to using main branch ([#392](https://www.github.com/googleapis/node-gtoken/issues/392)) ([992e3c5](https://www.github.com/googleapis/node-gtoken/commit/992e3c5e1520a376269b2476e5ce225f6ee96e2b)) + +## [5.3.0](https://www.github.com/googleapis/node-gtoken/compare/v5.2.1...v5.3.0) (2021-06-10) + + +### Features + +* add `gcf-owl-bot[bot]` to `ignoreAuthors` ([#369](https://www.github.com/googleapis/node-gtoken/issues/369)) ([3142215](https://www.github.com/googleapis/node-gtoken/commit/3142215277ae2daa33f7fb3300f09ef438ded01f)) + +### [5.2.1](https://www.github.com/googleapis/node-gtoken/compare/v5.2.0...v5.2.1) (2021-01-26) + + +### Bug Fixes + +* **deps:** remove dependency on mime ([#357](https://www.github.com/googleapis/node-gtoken/issues/357)) ([0a1e6b3](https://www.github.com/googleapis/node-gtoken/commit/0a1e6b32206364106631c0ca8cdd2e325de2af32)) + +## [5.2.0](https://www.github.com/googleapis/node-gtoken/compare/v5.1.0...v5.2.0) (2021-01-14) + + +### Features + +* request new tokens before they expire ([#349](https://www.github.com/googleapis/node-gtoken/issues/349)) ([e84d9a3](https://www.github.com/googleapis/node-gtoken/commit/e84d9a31517c1449141708a0a2cddd9d0129fa95)) + +## [5.1.0](https://www.github.com/googleapis/node-gtoken/compare/v5.0.5...v5.1.0) (2020-11-14) + + +### Features + +* dedupe concurrent requests ([#351](https://www.github.com/googleapis/node-gtoken/issues/351)) ([9001f1d](https://www.github.com/googleapis/node-gtoken/commit/9001f1d00931f480d40fa323c9b527beaef2254a)) + +### [5.0.5](https://www.github.com/googleapis/node-gtoken/compare/v5.0.4...v5.0.5) (2020-10-22) + + +### Bug Fixes + +* **deps:** update dependency gaxios to v4 ([#342](https://www.github.com/googleapis/node-gtoken/issues/342)) ([7954a19](https://www.github.com/googleapis/node-gtoken/commit/7954a197e923469b031f0833a2016fa0378285b1)) + +### [5.0.4](https://www.github.com/googleapis/node-gtoken/compare/v5.0.3...v5.0.4) (2020-10-06) + + +### Bug Fixes + +* **deps:** upgrade google-p12-pem ([#337](https://www.github.com/googleapis/node-gtoken/issues/337)) ([77a749d](https://www.github.com/googleapis/node-gtoken/commit/77a749d646c7ccc68e974f27827a9d538dfea784)) + +### [5.0.3](https://www.github.com/googleapis/node-gtoken/compare/v5.0.2...v5.0.3) (2020-07-27) + + +### Bug Fixes + +* move gitattributes files to node templates ([#322](https://www.github.com/googleapis/node-gtoken/issues/322)) ([1d1786b](https://www.github.com/googleapis/node-gtoken/commit/1d1786b8915cd9a33577237ec6a6148a29e11a88)) + +### [5.0.2](https://www.github.com/googleapis/node-gtoken/compare/v5.0.1...v5.0.2) (2020-07-09) + + +### Bug Fixes + +* typeo in nodejs .gitattribute ([#311](https://www.github.com/googleapis/node-gtoken/issues/311)) ([8e17b4c](https://www.github.com/googleapis/node-gtoken/commit/8e17b4c0757832b2d31178684a6b24e1759d9f76)) + +### [5.0.1](https://www.github.com/googleapis/node-gtoken/compare/v5.0.0...v5.0.1) (2020-04-13) + + +### Bug Fixes + +* **deps:** update dependency gaxios to v3 ([#287](https://www.github.com/googleapis/node-gtoken/issues/287)) ([033731e](https://www.github.com/googleapis/node-gtoken/commit/033731e128fef0034b07b13183044e5060809418)) +* **deps:** update dependency google-p12-pem to v3 ([#280](https://www.github.com/googleapis/node-gtoken/issues/280)) ([25121b0](https://www.github.com/googleapis/node-gtoken/commit/25121b00cc9a4d32854f36ea8bc4bbd2cb77afbb)) +* apache license URL ([#468](https://www.github.com/googleapis/node-gtoken/issues/468)) ([#293](https://www.github.com/googleapis/node-gtoken/issues/293)) ([14a5bcd](https://www.github.com/googleapis/node-gtoken/commit/14a5bcd52d7b18d787c620451471e904784222d9)) + +## [5.0.0](https://www.github.com/googleapis/node-gtoken/compare/v4.1.4...v5.0.0) (2020-03-24) + + +### ⚠ BREAKING CHANGES + +* drop Node 8 from engines (#284) +* typescript@3.7.x introduced breaking changes to compiled code + +### Features + +* drop Node 8 from engines ([#284](https://www.github.com/googleapis/node-gtoken/issues/284)) ([209e007](https://www.github.com/googleapis/node-gtoken/commit/209e00746116a82a3cf9acc158aff12a4971f3d0)) + + +### Build System + +* update gts and typescript ([#283](https://www.github.com/googleapis/node-gtoken/issues/283)) ([ff076dc](https://www.github.com/googleapis/node-gtoken/commit/ff076dcb3da229238e7bed28d739c48986652c78)) + +### [4.1.4](https://www.github.com/googleapis/node-gtoken/compare/v4.1.3...v4.1.4) (2020-01-06) + + +### Bug Fixes + +* **deps:** pin TypeScript below 3.7.0 ([f1ae7b6](https://www.github.com/googleapis/node-gtoken/commit/f1ae7b64ead1c918546ae5bbe8546dfb4ecc788a)) +* **deps:** update dependency jws to v4 ([#251](https://www.github.com/googleapis/node-gtoken/issues/251)) ([e13542f](https://www.github.com/googleapis/node-gtoken/commit/e13542f888a81ed3ced0023e9b78ed25264b1d1c)) + +### [4.1.3](https://www.github.com/googleapis/node-gtoken/compare/v4.1.2...v4.1.3) (2019-11-15) + + +### Bug Fixes + +* **deps:** use typescript ~3.6.0 ([#246](https://www.github.com/googleapis/node-gtoken/issues/246)) ([5f725b7](https://www.github.com/googleapis/node-gtoken/commit/5f725b71f080e83058b1a23340acadc0c8704123)) + +### [4.1.2](https://www.github.com/googleapis/node-gtoken/compare/v4.1.1...v4.1.2) (2019-11-13) + + +### Bug Fixes + +* **docs:** add jsdoc-region-tag plugin ([#242](https://www.github.com/googleapis/node-gtoken/issues/242)) ([994c5cc](https://www.github.com/googleapis/node-gtoken/commit/994c5ccf92731599aa63b84c29a9d5f6b1431cc5)) + +### [4.1.1](https://www.github.com/googleapis/node-gtoken/compare/v4.1.0...v4.1.1) (2019-10-31) + + +### Bug Fixes + +* **deps:** update gaxios to 2.1.0 ([#238](https://www.github.com/googleapis/node-gtoken/issues/238)) ([bb12064](https://www.github.com/googleapis/node-gtoken/commit/bb1206420388399ef8992efe54c70bdb3fdcd965)) + +## [4.1.0](https://www.github.com/googleapis/node-gtoken/compare/v4.0.0...v4.1.0) (2019-09-24) + + +### Features + +* allow upstream libraries to force token refresh ([#229](https://www.github.com/googleapis/node-gtoken/issues/229)) ([1fd4dd1](https://www.github.com/googleapis/node-gtoken/commit/1fd4dd1)) + +## [4.0.0](https://www.github.com/googleapis/node-gtoken/compare/v3.0.2...v4.0.0) (2019-07-09) + + +### ⚠ BREAKING CHANGES + +* This commit creates multiple breaking changes. The `getToken()` +method previously returned `Promise`, where the string was the +`access_token` returned from the response. However, the `oauth2` endpoint could +return a variety of other fields, such as an `id_token` in special cases. + +```js +const token = await getToken(); +// old response: 'some.access.token' +// new response: { access_token: 'some.access.token'} +``` + +To further support this change, the `GoogleToken` class no longer exposes +a `token` variable. It now exposes `rawToken`, `accessToken`, and `idToken` +fields which can be used to access the relevant values returned in the +response. + +### Bug Fixes + +* expose all fields from response ([#218](https://www.github.com/googleapis/node-gtoken/issues/218)) ([d463370](https://www.github.com/googleapis/node-gtoken/commit/d463370)) + +### [3.0.2](https://www.github.com/googleapis/node-gtoken/compare/v3.0.1...v3.0.2) (2019-06-26) + + +### Bug Fixes + +* **docs:** make anchors work in jsdoc ([#215](https://www.github.com/googleapis/node-gtoken/issues/215)) ([c5f6c89](https://www.github.com/googleapis/node-gtoken/commit/c5f6c89)) + +### [3.0.1](https://www.github.com/googleapis/node-gtoken/compare/v3.0.0...v3.0.1) (2019-06-13) + + +### Bug Fixes + +* **docs:** move to new client docs URL ([#212](https://www.github.com/googleapis/node-gtoken/issues/212)) ([b7a8c75](https://www.github.com/googleapis/node-gtoken/commit/b7a8c75)) + +## [3.0.0](https://www.github.com/googleapis/node-gtoken/compare/v2.3.3...v3.0.0) (2019-05-07) + + +### Bug Fixes + +* **deps:** update dependency gaxios to v2 ([#191](https://www.github.com/googleapis/node-gtoken/issues/191)) ([da65ea7](https://www.github.com/googleapis/node-gtoken/commit/da65ea7)) +* **deps:** update dependency google-p12-pem to v2 ([#196](https://www.github.com/googleapis/node-gtoken/issues/196)) ([b510f06](https://www.github.com/googleapis/node-gtoken/commit/b510f06)) +* fs.readFile does not exist in browser ([#186](https://www.github.com/googleapis/node-gtoken/issues/186)) ([a16d8e7](https://www.github.com/googleapis/node-gtoken/commit/a16d8e7)) + + +### Build System + +* upgrade engines field to >=8.10.0 ([#194](https://www.github.com/googleapis/node-gtoken/issues/194)) ([ee4d6c8](https://www.github.com/googleapis/node-gtoken/commit/ee4d6c8)) + + +### BREAKING CHANGES + +* upgrade engines field to >=8.10.0 (#194) + +## v2.3.3 + +03-13-2019 14:54 PDT + +### Bug Fixes +- fix: propagate error message ([#173](https://github.com/google/node-gtoken/pull/173)) + +### Documentation +- docs: update links in contrib guide ([#171](https://github.com/google/node-gtoken/pull/171)) +- docs: move CONTRIBUTING.md to root ([#166](https://github.com/google/node-gtoken/pull/166)) +- docs: add lint/fix example to contributing guide ([#164](https://github.com/google/node-gtoken/pull/164)) + +### Internal / Testing Changes +- build: Add docuploader credentials to node publish jobs ([#176](https://github.com/google/node-gtoken/pull/176)) +- build: use node10 to run samples-test, system-test etc ([#175](https://github.com/google/node-gtoken/pull/175)) +- build: update release configuration +- chore(deps): update dependency mocha to v6 +- build: use linkinator for docs test ([#170](https://github.com/google/node-gtoken/pull/170)) +- build: create docs test npm scripts ([#169](https://github.com/google/node-gtoken/pull/169)) +- build: test using @grpc/grpc-js in CI ([#168](https://github.com/google/node-gtoken/pull/168)) +- build: ignore googleapis.com in doc link check ([#162](https://github.com/google/node-gtoken/pull/162)) +- build: check for 404s on all docs + +## v2.3.2 + +01-09-2019 13:40 PST + +### Documentation +- docs: generate docs with compodoc ([#154](https://github.com/googleapis/node-gtoken/pull/154)) +- docs: fix up the readme ([#153](https://github.com/googleapis/node-gtoken/pull/153)) + +### Internal / Testing Changes +- build: Re-generated to pick up changes in the API or client library generator. ([#158](https://github.com/googleapis/node-gtoken/pull/158)) +- build: check broken links in generated docs ([#152](https://github.com/googleapis/node-gtoken/pull/152)) +- fix: add a system test and get it passing ([#150](https://github.com/googleapis/node-gtoken/pull/150)) +- chore(build): inject yoshi automation key ([#149](https://github.com/googleapis/node-gtoken/pull/149)) + +## v2.3.1 + +12-10-2018 15:28 PST + +### Dependencies +- fix(deps): update dependency pify to v4 ([#87](https://github.com/google/node-gtoken/pull/87)) +- fix(deps): use gaxios for http requests ([#125](https://github.com/google/node-gtoken/pull/125)) + +### Internal / Testing Changes +- build: add Kokoro configs for autorelease ([#143](https://github.com/google/node-gtoken/pull/143)) +- chore: always nyc report before calling codecov ([#141](https://github.com/google/node-gtoken/pull/141)) +- chore: nyc ignore build/test by default ([#140](https://github.com/google/node-gtoken/pull/140)) +- chore: update synth metadata and templates ([#138](https://github.com/google/node-gtoken/pull/138)) +- fix(build): fix system key decryption ([#133](https://github.com/google/node-gtoken/pull/133)) +- chore(deps): update dependency typescript to ~3.2.0 ([#132](https://github.com/google/node-gtoken/pull/132)) +- chore: add a synth.metadata +- chore(deps): update dependency gts to ^0.9.0 ([#127](https://github.com/google/node-gtoken/pull/127)) +- chore: update eslintignore config ([#126](https://github.com/google/node-gtoken/pull/126)) +- chore: use latest npm on Windows ([#124](https://github.com/google/node-gtoken/pull/124)) +- chore: update CircleCI config ([#123](https://github.com/google/node-gtoken/pull/123)) +- chore: include build in eslintignore ([#120](https://github.com/google/node-gtoken/pull/120)) +- chore: update issue templates ([#116](https://github.com/google/node-gtoken/pull/116)) +- chore: remove old issue template ([#114](https://github.com/google/node-gtoken/pull/114)) +- build: run tests on node11 ([#113](https://github.com/google/node-gtoken/pull/113)) +- chore(deps): update dependency nock to v10 ([#111](https://github.com/google/node-gtoken/pull/111)) +- chores(build): do not collect sponge.xml from windows builds ([#112](https://github.com/google/node-gtoken/pull/112)) +- chore(deps): update dependency typescript to ~3.1.0 ([#110](https://github.com/google/node-gtoken/pull/110)) +- chores(build): run codecov on continuous builds ([#109](https://github.com/google/node-gtoken/pull/109)) +- chore: update new issue template ([#108](https://github.com/google/node-gtoken/pull/108)) +- chore: update CI config ([#105](https://github.com/google/node-gtoken/pull/105)) +- Update kokoro config ([#103](https://github.com/google/node-gtoken/pull/103)) +- Update CI config ([#101](https://github.com/google/node-gtoken/pull/101)) +- Don't publish sourcemaps ([#99](https://github.com/google/node-gtoken/pull/99)) +- Update kokoro config ([#97](https://github.com/google/node-gtoken/pull/97)) +- test: remove appveyor config ([#96](https://github.com/google/node-gtoken/pull/96)) +- Update CI config ([#95](https://github.com/google/node-gtoken/pull/95)) +- Enable prefer-const in the eslint config ([#94](https://github.com/google/node-gtoken/pull/94)) +- Enable no-var in eslint ([#93](https://github.com/google/node-gtoken/pull/93)) +- Update CI config ([#92](https://github.com/google/node-gtoken/pull/92)) +- Add synth and update CI config ([#91](https://github.com/google/node-gtoken/pull/91)) +- Retry npm install in CI ([#90](https://github.com/google/node-gtoken/pull/90)) +- chore(deps): update dependency nyc to v13 ([#88](https://github.com/google/node-gtoken/pull/88)) +- chore: ignore package-log.json ([#86](https://github.com/google/node-gtoken/pull/86)) +- chore: update renovate config ([#83](https://github.com/google/node-gtoken/pull/83)) +- chore(deps): lock file maintenance ([#85](https://github.com/google/node-gtoken/pull/85)) +- chore: remove greenkeeper badge ([#82](https://github.com/google/node-gtoken/pull/82)) +- test: throw on deprecation ([#81](https://github.com/google/node-gtoken/pull/81)) +- chore(deps): update dependency typescript to v3 ([#80](https://github.com/google/node-gtoken/pull/80)) +- chore: move mocha options to mocha.opts ([#78](https://github.com/google/node-gtoken/pull/78)) +- chore(deps): lock file maintenance ([#79](https://github.com/google/node-gtoken/pull/79)) +- test: use strictEqual in tests ([#76](https://github.com/google/node-gtoken/pull/76)) +- chore(deps): lock file maintenance ([#77](https://github.com/google/node-gtoken/pull/77)) +- chore(deps): update dependency typescript to ~2.9.0 ([#75](https://github.com/google/node-gtoken/pull/75)) +- chore: Configure Renovate ([#74](https://github.com/google/node-gtoken/pull/74)) +- Update gts to the latest version 🚀 ([#73](https://github.com/google/node-gtoken/pull/73)) +- Add Code of Conduct +- build: start testing against Node 10 ([#69](https://github.com/google/node-gtoken/pull/69)) +- chore(package): update nyc to version 12.0.2 ([#67](https://github.com/google/node-gtoken/pull/67)) +- chore(package): update @types/node to version 10.0.3 ([#65](https://github.com/google/node-gtoken/pull/65)) + +### 2.0.0 +New features: +- API now supports callback and promise based workflows + +Breaking changes: +- `GoogleToken` is now a class type, and must be instantiated. +- `GoogleToken.expires_at` renamed to `GoogleToken.expiresAt` +- `GoogleToken.raw_token` renamed to `GoogleToken.rawToken` +- `GoogleToken.token_expires` renamed to `GoogleToken.tokenExpires` diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gtoken/LICENSE b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gtoken/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..061e6a68e0b277837f672e8e287eb8f0bf0b0d5f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gtoken/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Ryan Seys + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gtoken/README.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gtoken/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9dcb82ee5a9608e014a4f6f22e5398f1f68b33ce --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gtoken/README.md @@ -0,0 +1,187 @@ +Google Cloud Platform logo + +# [node-gtoken](https://github.com/googleapis/node-gtoken) + +[![npm version][npm-image]][npm-url] +[![Known Vulnerabilities][snyk-image]][snyk-url] +[![codecov][codecov-image]][codecov-url] +[![Code Style: Google][gts-image]][gts-url] + +> Node.js Google Authentication Service Account Tokens + +This is a low level utility library used to interact with Google Authentication services. **In most cases, you probably want to use the [google-auth-library](https://github.com/googleapis/google-auth-library-nodejs) instead.** + +* [gtoken API Reference][client-docs] +* [github.com/googleapis/node-gtoken](https://github.com/googleapis/node-gtoken) + +## Installation + +``` sh +npm install gtoken +``` + +## Usage + +### Use with a `.pem` or `.json` key file: + +``` js +const { GoogleToken } = require('gtoken'); +const gtoken = new GoogleToken({ + keyFile: 'path/to/key.pem', // or path to .json key file + email: 'my_service_account_email@developer.gserviceaccount.com', + scope: ['https://scope1', 'https://scope2'], // or space-delimited string of scopes + eagerRefreshThresholdMillis: 5 * 60 * 1000 +}); + +gtoken.getToken((err, tokens) => { + if (err) { + console.log(err); + return; + } + console.log(tokens); + // { + // access_token: 'very-secret-token', + // expires_in: 3600, + // token_type: 'Bearer' + // } +}); +``` + +You can also use the async/await style API: + +``` js +const tokens = await gtoken.getToken() +console.log(tokens); +``` + +Or use promises: + +```js +gtoken.getToken() + .then(tokens => { + console.log(tokens) + }) + .catch(console.error); +``` + +### Use with a service account `.json` key file: + +``` js +const { GoogleToken } = require('gtoken'); +const gtoken = new GoogleToken({ + keyFile: 'path/to/key.json', + scope: ['https://scope1', 'https://scope2'], // or space-delimited string of scopes + eagerRefreshThresholdMillis: 5 * 60 * 1000 +}); + +gtoken.getToken((err, tokens) => { + if (err) { + console.log(err); + return; + } + console.log(tokens); +}); +``` + +### Pass the private key as a string directly: + +``` js +const key = '-----BEGIN RSA PRIVATE KEY-----\nXXXXXXXXXXX...'; +const { GoogleToken } = require('gtoken'); +const gtoken = new GoogleToken({ + email: 'my_service_account_email@developer.gserviceaccount.com', + scope: ['https://scope1', 'https://scope2'], // or space-delimited string of scopes + key: key, + eagerRefreshThresholdMillis: 5 * 60 * 1000 +}); +``` + +## Options + +> Various options that can be set when creating initializing the `gtoken` object. + +- `options.email or options.iss`: The service account email address. +- `options.scope`: An array of scope strings or space-delimited string of scopes. +- `options.sub`: The email address of the user requesting delegated access. +- `options.keyFile`: The filename of `.json` key or `.pem` key. +- `options.key`: The raw RSA private key value, in place of using `options.keyFile`. +- `options.additionalClaims`: Additional claims to include in the JWT when requesting a token. +- `options.eagerRefreshThresholdMillis`: How long must a token be valid for in order to return it from the cache. Defaults to 0. + +### .getToken(callback) + +> Returns the cached tokens or requests a new one and returns it. + +``` js +gtoken.getToken((err, token) => { + console.log(err || token); + // gtoken.rawToken value is also set +}); +``` + +### .getCredentials('path/to/key.json') + +> Given a keyfile, returns the key and (if available) the client email. + +```js +const creds = await gtoken.getCredentials('path/to/key.json'); +``` + +### Properties + +> Various properties set on the gtoken object after call to `.getToken()`. + +- `gtoken.idToken`: The OIDC token returned (if any). +- `gtoken.accessToken`: The access token. +- `gtoken.expiresAt`: The expiry date as milliseconds since 1970/01/01 +- `gtoken.key`: The raw key value. +- `gtoken.rawToken`: Most recent raw token data received from Google. + +### .hasExpired() + +> Returns true if the token has expired, or token does not exist. + +``` js +const tokens = await gtoken.getToken(); +gtoken.hasExpired(); // false +``` + +### .revokeToken() + +> Revoke the token if set. + +``` js +await gtoken.revokeToken(); +console.log('Token revoked!'); +``` + +## Downloading your private `.json` key from Google + +1. Open the [Google Developer Console][gdevconsole]. +2. Open your project and under "APIs & auth", click Credentials. +3. Generate a new `.json` key and download it into your project. + +## Converting your `.p12` key to a `.pem` key + +If you'd like to convert to a `.pem` for use later, use OpenSSL if you have it installed. + +``` sh +$ openssl pkcs12 -in key.p12 -nodes -nocerts > key.pem +``` + +Don't forget, the passphrase when converting these files is the string `'notasecret'` + +## License + +[MIT](https://github.com/googleapis/node-gtoken/blob/main/LICENSE) + +[codecov-image]: https://codecov.io/gh/googleapis/node-gtoken/branch/main/graph/badge.svg +[codecov-url]: https://codecov.io/gh/googleapis/node-gtoken +[gdevconsole]: https://console.developers.google.com +[gts-image]: https://img.shields.io/badge/code%20style-google-blueviolet.svg +[gts-url]: https://www.npmjs.com/package/gts +[npm-image]: https://img.shields.io/npm/v/gtoken.svg +[npm-url]: https://npmjs.org/package/gtoken +[snyk-image]: https://snyk.io/test/github/googleapis/node-gtoken/badge.svg +[snyk-url]: https://snyk.io/test/github/googleapis/node-gtoken +[client-docs]: https://googleapis.dev/nodejs/gtoken/latest/ diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gtoken/build/src/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gtoken/build/src/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2ffe342984b38b45059d129c753bbaf4d98f8532 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gtoken/build/src/index.d.ts @@ -0,0 +1,93 @@ +/** + * Copyright 2018 Google LLC + * + * Distributed under MIT license. + * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT + */ +import { GaxiosOptions, GaxiosPromise } from 'gaxios'; +export interface Transporter { + request(opts: GaxiosOptions): GaxiosPromise; +} +export type GetTokenCallback = (err: Error | null, token?: TokenData) => void; +export interface Credentials { + privateKey: string; + clientEmail?: string; +} +export interface TokenData { + refresh_token?: string; + expires_in?: number; + access_token?: string; + token_type?: string; + id_token?: string; +} +export interface TokenOptions { + keyFile?: string; + key?: string; + email?: string; + iss?: string; + sub?: string; + scope?: string | string[]; + additionalClaims?: {}; + eagerRefreshThresholdMillis?: number; + transporter?: Transporter; +} +export interface GetTokenOptions { + forceRefresh?: boolean; +} +export declare class GoogleToken { + #private; + get accessToken(): string | undefined; + get idToken(): string | undefined; + get tokenType(): string | undefined; + get refreshToken(): string | undefined; + expiresAt?: number; + key?: string; + keyFile?: string; + iss?: string; + sub?: string; + scope?: string; + rawToken?: TokenData; + tokenExpires?: number; + email?: string; + additionalClaims?: {}; + eagerRefreshThresholdMillis?: number; + transporter: Transporter; + /** + * Create a GoogleToken. + * + * @param options Configuration object. + */ + constructor(options?: TokenOptions); + /** + * Returns whether the token has expired. + * + * @return true if the token has expired, false otherwise. + */ + hasExpired(): boolean; + /** + * Returns whether the token will expire within eagerRefreshThresholdMillis + * + * @return true if the token will be expired within eagerRefreshThresholdMillis, false otherwise. + */ + isTokenExpiring(): boolean; + /** + * Returns a cached token or retrieves a new one from Google. + * + * @param callback The callback function. + */ + getToken(opts?: GetTokenOptions): Promise; + getToken(callback: GetTokenCallback, opts?: GetTokenOptions): void; + /** + * Given a keyFile, extract the key and client email if available + * @param keyFile Path to a json, pem, or p12 file that contains the key. + * @returns an object with privateKey and clientEmail properties + */ + getCredentials(keyFile: string): Promise; + /** + * Revoke the token if one is set. + * + * @param callback The callback function. + */ + revokeToken(): Promise; + revokeToken(callback: (err?: Error) => void): void; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gtoken/build/src/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gtoken/build/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..bf4504236db77c30b8f39ce4c27a07dab23ec9cf --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gtoken/build/src/index.js @@ -0,0 +1,276 @@ +"use strict"; +/** + * Copyright 2018 Google LLC + * + * Distributed under MIT license. + * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT + */ +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var _GoogleToken_instances, _GoogleToken_inFlightRequest, _GoogleToken_getTokenAsync, _GoogleToken_getTokenAsyncInner, _GoogleToken_ensureEmail, _GoogleToken_revokeTokenAsync, _GoogleToken_configure, _GoogleToken_requestToken; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GoogleToken = void 0; +const fs = require("fs"); +const gaxios_1 = require("gaxios"); +const jws = require("jws"); +const path = require("path"); +const util_1 = require("util"); +const readFile = fs.readFile + ? (0, util_1.promisify)(fs.readFile) + : async () => { + // if running in the web-browser, fs.readFile may not have been shimmed. + throw new ErrorWithCode('use key rather than keyFile.', 'MISSING_CREDENTIALS'); + }; +const GOOGLE_TOKEN_URL = 'https://www.googleapis.com/oauth2/v4/token'; +const GOOGLE_REVOKE_TOKEN_URL = 'https://accounts.google.com/o/oauth2/revoke?token='; +class ErrorWithCode extends Error { + constructor(message, code) { + super(message); + this.code = code; + } +} +class GoogleToken { + get accessToken() { + return this.rawToken ? this.rawToken.access_token : undefined; + } + get idToken() { + return this.rawToken ? this.rawToken.id_token : undefined; + } + get tokenType() { + return this.rawToken ? this.rawToken.token_type : undefined; + } + get refreshToken() { + return this.rawToken ? this.rawToken.refresh_token : undefined; + } + /** + * Create a GoogleToken. + * + * @param options Configuration object. + */ + constructor(options) { + _GoogleToken_instances.add(this); + this.transporter = { + request: opts => (0, gaxios_1.request)(opts), + }; + _GoogleToken_inFlightRequest.set(this, void 0); + __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_configure).call(this, options); + } + /** + * Returns whether the token has expired. + * + * @return true if the token has expired, false otherwise. + */ + hasExpired() { + const now = new Date().getTime(); + if (this.rawToken && this.expiresAt) { + return now >= this.expiresAt; + } + else { + return true; + } + } + /** + * Returns whether the token will expire within eagerRefreshThresholdMillis + * + * @return true if the token will be expired within eagerRefreshThresholdMillis, false otherwise. + */ + isTokenExpiring() { + var _a; + const now = new Date().getTime(); + const eagerRefreshThresholdMillis = (_a = this.eagerRefreshThresholdMillis) !== null && _a !== void 0 ? _a : 0; + if (this.rawToken && this.expiresAt) { + return this.expiresAt <= now + eagerRefreshThresholdMillis; + } + else { + return true; + } + } + getToken(callback, opts = {}) { + if (typeof callback === 'object') { + opts = callback; + callback = undefined; + } + opts = Object.assign({ + forceRefresh: false, + }, opts); + if (callback) { + const cb = callback; + __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_getTokenAsync).call(this, opts).then(t => cb(null, t), callback); + return; + } + return __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_getTokenAsync).call(this, opts); + } + /** + * Given a keyFile, extract the key and client email if available + * @param keyFile Path to a json, pem, or p12 file that contains the key. + * @returns an object with privateKey and clientEmail properties + */ + async getCredentials(keyFile) { + const ext = path.extname(keyFile); + switch (ext) { + case '.json': { + const key = await readFile(keyFile, 'utf8'); + const body = JSON.parse(key); + const privateKey = body.private_key; + const clientEmail = body.client_email; + if (!privateKey || !clientEmail) { + throw new ErrorWithCode('private_key and client_email are required.', 'MISSING_CREDENTIALS'); + } + return { privateKey, clientEmail }; + } + case '.der': + case '.crt': + case '.pem': { + const privateKey = await readFile(keyFile, 'utf8'); + return { privateKey }; + } + case '.p12': + case '.pfx': { + throw new ErrorWithCode('*.p12 certificates are not supported after v6.1.2. ' + + 'Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.', 'UNKNOWN_CERTIFICATE_TYPE'); + } + default: + throw new ErrorWithCode('Unknown certificate type. Type is determined based on file extension. ' + + 'Current supported extensions are *.json, and *.pem.', 'UNKNOWN_CERTIFICATE_TYPE'); + } + } + revokeToken(callback) { + if (callback) { + __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_revokeTokenAsync).call(this).then(() => callback(), callback); + return; + } + return __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_revokeTokenAsync).call(this); + } +} +exports.GoogleToken = GoogleToken; +_GoogleToken_inFlightRequest = new WeakMap(), _GoogleToken_instances = new WeakSet(), _GoogleToken_getTokenAsync = async function _GoogleToken_getTokenAsync(opts) { + if (__classPrivateFieldGet(this, _GoogleToken_inFlightRequest, "f") && !opts.forceRefresh) { + return __classPrivateFieldGet(this, _GoogleToken_inFlightRequest, "f"); + } + try { + return await (__classPrivateFieldSet(this, _GoogleToken_inFlightRequest, __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_getTokenAsyncInner).call(this, opts), "f")); + } + finally { + __classPrivateFieldSet(this, _GoogleToken_inFlightRequest, undefined, "f"); + } +}, _GoogleToken_getTokenAsyncInner = async function _GoogleToken_getTokenAsyncInner(opts) { + if (this.isTokenExpiring() === false && opts.forceRefresh === false) { + return Promise.resolve(this.rawToken); + } + if (!this.key && !this.keyFile) { + throw new Error('No key or keyFile set.'); + } + if (!this.key && this.keyFile) { + const creds = await this.getCredentials(this.keyFile); + this.key = creds.privateKey; + this.iss = creds.clientEmail || this.iss; + if (!creds.clientEmail) { + __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_ensureEmail).call(this); + } + } + return __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_requestToken).call(this); +}, _GoogleToken_ensureEmail = function _GoogleToken_ensureEmail() { + if (!this.iss) { + throw new ErrorWithCode('email is required.', 'MISSING_CREDENTIALS'); + } +}, _GoogleToken_revokeTokenAsync = async function _GoogleToken_revokeTokenAsync() { + if (!this.accessToken) { + throw new Error('No token to revoke.'); + } + const url = GOOGLE_REVOKE_TOKEN_URL + this.accessToken; + await this.transporter.request({ + url, + retry: true, + }); + __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_configure).call(this, { + email: this.iss, + sub: this.sub, + key: this.key, + keyFile: this.keyFile, + scope: this.scope, + additionalClaims: this.additionalClaims, + }); +}, _GoogleToken_configure = function _GoogleToken_configure(options = {}) { + this.keyFile = options.keyFile; + this.key = options.key; + this.rawToken = undefined; + this.iss = options.email || options.iss; + this.sub = options.sub; + this.additionalClaims = options.additionalClaims; + if (typeof options.scope === 'object') { + this.scope = options.scope.join(' '); + } + else { + this.scope = options.scope; + } + this.eagerRefreshThresholdMillis = options.eagerRefreshThresholdMillis; + if (options.transporter) { + this.transporter = options.transporter; + } +}, _GoogleToken_requestToken = +/** + * Request the token from Google. + */ +async function _GoogleToken_requestToken() { + var _a, _b; + const iat = Math.floor(new Date().getTime() / 1000); + const additionalClaims = this.additionalClaims || {}; + const payload = Object.assign({ + iss: this.iss, + scope: this.scope, + aud: GOOGLE_TOKEN_URL, + exp: iat + 3600, + iat, + sub: this.sub, + }, additionalClaims); + const signedJWT = jws.sign({ + header: { alg: 'RS256' }, + payload, + secret: this.key, + }); + try { + const r = await this.transporter.request({ + method: 'POST', + url: GOOGLE_TOKEN_URL, + data: { + grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', + assertion: signedJWT, + }, + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + responseType: 'json', + retryConfig: { + httpMethodsToRetry: ['POST'], + }, + }); + this.rawToken = r.data; + this.expiresAt = + r.data.expires_in === null || r.data.expires_in === undefined + ? undefined + : (iat + r.data.expires_in) * 1000; + return this.rawToken; + } + catch (e) { + this.rawToken = undefined; + this.tokenExpires = undefined; + const body = e.response && ((_a = e.response) === null || _a === void 0 ? void 0 : _a.data) + ? (_b = e.response) === null || _b === void 0 ? void 0 : _b.data + : {}; + if (body.error) { + const desc = body.error_description + ? `: ${body.error_description}` + : ''; + e.message = `${body.error}${desc}`; + } + throw e; + } +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gtoken/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gtoken/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3c76f387960365717de2c218ea78bc202e76a8a6 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/gtoken/package.json @@ -0,0 +1,62 @@ +{ + "name": "gtoken", + "version": "7.1.0", + "description": "Node.js Google Authentication Service Account Tokens", + "main": "./build/src/index.js", + "types": "./build/src/index.d.ts", + "engines": { + "node": ">=14.0.0" + }, + "repository": "google/node-gtoken", + "scripts": { + "lint": "gts check", + "clean": "gts clean", + "fix": "gts fix", + "compile": "tsc -p .", + "test": "c8 mocha build/test", + "prepare": "npm run compile", + "pretest": "npm run compile", + "presystem-test": "npm run compile", + "system-test": "mocha build/system-test", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + "docs": "compodoc src/", + "docs-test": "linkinator docs", + "predocs-test": "npm run docs", + "prelint": "cd samples; npm link ../; npm install", + "precompile": "gts clean" + }, + "keywords": [ + "google", + "service", + "account", + "api", + "token", + "api", + "auth" + ], + "author": { + "name": "Google, LLC" + }, + "license": "MIT", + "dependencies": { + "gaxios": "^6.0.0", + "jws": "^4.0.0" + }, + "devDependencies": { + "@babel/plugin-proposal-private-methods": "^7.18.6", + "@compodoc/compodoc": "^1.1.7", + "@types/jws": "^3.1.0", + "@types/mocha": "^9.0.0", + "@types/node": "^20.0.0", + "c8": "^9.0.0", + "gts": "^5.0.0", + "linkinator": "^4.0.0", + "mocha": "^9.2.2", + "nock": "^13.0.0", + "typescript": "^5.1.6" + }, + "files": [ + "build/src", + "!build/src/**/*.map" + ] +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/is-stream/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/is-stream/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..eee2e83e81045a552f9e373173a32fb988ceb19d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/is-stream/index.d.ts @@ -0,0 +1,79 @@ +import * as stream from 'stream'; + +declare const isStream: { + /** + @returns Whether `stream` is a [`Stream`](https://nodejs.org/api/stream.html#stream_stream). + + @example + ``` + import * as fs from 'fs'; + import isStream = require('is-stream'); + + isStream(fs.createReadStream('unicorn.png')); + //=> true + + isStream({}); + //=> false + ``` + */ + (stream: unknown): stream is stream.Stream; + + /** + @returns Whether `stream` is a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable). + + @example + ``` + import * as fs from 'fs'; + import isStream = require('is-stream'); + + isStream.writable(fs.createWriteStrem('unicorn.txt')); + //=> true + ``` + */ + writable(stream: unknown): stream is stream.Writable; + + /** + @returns Whether `stream` is a [`stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable). + + @example + ``` + import * as fs from 'fs'; + import isStream = require('is-stream'); + + isStream.readable(fs.createReadStream('unicorn.png')); + //=> true + ``` + */ + readable(stream: unknown): stream is stream.Readable; + + /** + @returns Whether `stream` is a [`stream.Duplex`](https://nodejs.org/api/stream.html#stream_class_stream_duplex). + + @example + ``` + import {Duplex} from 'stream'; + import isStream = require('is-stream'); + + isStream.duplex(new Duplex()); + //=> true + ``` + */ + duplex(stream: unknown): stream is stream.Duplex; + + /** + @returns Whether `stream` is a [`stream.Transform`](https://nodejs.org/api/stream.html#stream_class_stream_transform). + + @example + ``` + import * as fs from 'fs'; + import Stringify = require('streaming-json-stringify'); + import isStream = require('is-stream'); + + isStream.transform(Stringify()); + //=> true + ``` + */ + transform(input: unknown): input is stream.Transform; +}; + +export = isStream; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/is-stream/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/is-stream/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2e43434daa19bc911c0dce631cadca79733497f4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/is-stream/index.js @@ -0,0 +1,28 @@ +'use strict'; + +const isStream = stream => + stream !== null && + typeof stream === 'object' && + typeof stream.pipe === 'function'; + +isStream.writable = stream => + isStream(stream) && + stream.writable !== false && + typeof stream._write === 'function' && + typeof stream._writableState === 'object'; + +isStream.readable = stream => + isStream(stream) && + stream.readable !== false && + typeof stream._read === 'function' && + typeof stream._readableState === 'object'; + +isStream.duplex = stream => + isStream.writable(stream) && + isStream.readable(stream); + +isStream.transform = stream => + isStream.duplex(stream) && + typeof stream._transform === 'function'; + +module.exports = isStream; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/is-stream/license b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/is-stream/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/is-stream/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/is-stream/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/is-stream/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c3b56739228bc028ad575227fdf07abdabe2c100 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/is-stream/package.json @@ -0,0 +1,42 @@ +{ + "name": "is-stream", + "version": "2.0.1", + "description": "Check if something is a Node.js stream", + "license": "MIT", + "repository": "sindresorhus/is-stream", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "stream", + "type", + "streams", + "writable", + "readable", + "duplex", + "transform", + "check", + "detect", + "is" + ], + "devDependencies": { + "@types/node": "^11.13.6", + "ava": "^1.4.1", + "tempy": "^0.3.0", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/is-stream/readme.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/is-stream/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..19308e7335a2965c55ec679488d6688118ea892c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/is-stream/readme.md @@ -0,0 +1,60 @@ +# is-stream + +> Check if something is a [Node.js stream](https://nodejs.org/api/stream.html) + +## Install + +``` +$ npm install is-stream +``` + +## Usage + +```js +const fs = require('fs'); +const isStream = require('is-stream'); + +isStream(fs.createReadStream('unicorn.png')); +//=> true + +isStream({}); +//=> false +``` + +## API + +### isStream(stream) + +Returns a `boolean` for whether it's a [`Stream`](https://nodejs.org/api/stream.html#stream_stream). + +#### isStream.writable(stream) + +Returns a `boolean` for whether it's a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable). + +#### isStream.readable(stream) + +Returns a `boolean` for whether it's a [`stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable). + +#### isStream.duplex(stream) + +Returns a `boolean` for whether it's a [`stream.Duplex`](https://nodejs.org/api/stream.html#stream_class_stream_duplex). + +#### isStream.transform(stream) + +Returns a `boolean` for whether it's a [`stream.Transform`](https://nodejs.org/api/stream.html#stream_class_stream_transform). + +## Related + +- [is-file-stream](https://github.com/jamestalmage/is-file-stream) - Detect if a stream is a file stream + +--- + +

+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/LICENSE.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..660ffecb58b02f27a562c193c71f14b7b573fc96 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/LICENSE.md @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 David Frank + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/README.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/README.md new file mode 100644 index 0000000000000000000000000000000000000000..55f09b7ffe21daa5ce7211c671b4c13fac894a69 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/README.md @@ -0,0 +1,634 @@ +node-fetch +========== + +[![npm version][npm-image]][npm-url] +[![build status][travis-image]][travis-url] +[![coverage status][codecov-image]][codecov-url] +[![install size][install-size-image]][install-size-url] +[![Discord][discord-image]][discord-url] + +A light-weight module that brings `window.fetch` to Node.js + +(We are looking for [v2 maintainers and collaborators](https://github.com/bitinn/node-fetch/issues/567)) + +[![Backers][opencollective-image]][opencollective-url] + + + +- [Motivation](#motivation) +- [Features](#features) +- [Difference from client-side fetch](#difference-from-client-side-fetch) +- [Installation](#installation) +- [Loading and configuring the module](#loading-and-configuring-the-module) +- [Common Usage](#common-usage) + - [Plain text or HTML](#plain-text-or-html) + - [JSON](#json) + - [Simple Post](#simple-post) + - [Post with JSON](#post-with-json) + - [Post with form parameters](#post-with-form-parameters) + - [Handling exceptions](#handling-exceptions) + - [Handling client and server errors](#handling-client-and-server-errors) +- [Advanced Usage](#advanced-usage) + - [Streams](#streams) + - [Buffer](#buffer) + - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data) + - [Extract Set-Cookie Header](#extract-set-cookie-header) + - [Post data using a file stream](#post-data-using-a-file-stream) + - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart) + - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal) +- [API](#api) + - [fetch(url[, options])](#fetchurl-options) + - [Options](#options) + - [Class: Request](#class-request) + - [Class: Response](#class-response) + - [Class: Headers](#class-headers) + - [Interface: Body](#interface-body) + - [Class: FetchError](#class-fetcherror) +- [License](#license) +- [Acknowledgement](#acknowledgement) + + + +## Motivation + +Instead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime. + +See Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side). + +## Features + +- Stay consistent with `window.fetch` API. +- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences. +- Use native promise but allow substituting it with [insert your favorite promise library]. +- Use native Node streams for body on both request and response. +- Decode content encoding (gzip/deflate) properly and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically. +- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors](ERROR-HANDLING.md) for troubleshooting. + +## Difference from client-side fetch + +- See [Known Differences](LIMITS.md) for details. +- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue. +- Pull requests are welcomed too! + +## Installation + +Current stable release (`2.x`) + +```sh +$ npm install node-fetch +``` + +## Loading and configuring the module +We suggest you load the module via `require` until the stabilization of ES modules in node: +```js +const fetch = require('node-fetch'); +``` + +If you are using a Promise library other than native, set it through `fetch.Promise`: +```js +const Bluebird = require('bluebird'); + +fetch.Promise = Bluebird; +``` + +## Common Usage + +NOTE: The documentation below is up-to-date with `2.x` releases; see the [`1.x` readme](https://github.com/bitinn/node-fetch/blob/1.x/README.md), [changelog](https://github.com/bitinn/node-fetch/blob/1.x/CHANGELOG.md) and [2.x upgrade guide](UPGRADE-GUIDE.md) for the differences. + +#### Plain text or HTML +```js +fetch('https://github.com/') + .then(res => res.text()) + .then(body => console.log(body)); +``` + +#### JSON + +```js + +fetch('https://api.github.com/users/github') + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Simple Post +```js +fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' }) + .then(res => res.json()) // expecting a json response + .then(json => console.log(json)); +``` + +#### Post with JSON + +```js +const body = { a: 1 }; + +fetch('https://httpbin.org/post', { + method: 'post', + body: JSON.stringify(body), + headers: { 'Content-Type': 'application/json' }, + }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Post with form parameters +`URLSearchParams` is available in Node.js as of v7.5.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods. + +NOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such: + +```js +const { URLSearchParams } = require('url'); + +const params = new URLSearchParams(); +params.append('a', 1); + +fetch('https://httpbin.org/post', { method: 'POST', body: params }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Handling exceptions +NOTE: 3xx-5xx responses are *NOT* exceptions and should be handled in `then()`; see the next section for more information. + +Adding a catch to the fetch promise chain will catch *all* exceptions, such as errors originating from node core libraries, network errors and operational errors, which are instances of FetchError. See the [error handling document](ERROR-HANDLING.md) for more details. + +```js +fetch('https://domain.invalid/') + .catch(err => console.error(err)); +``` + +#### Handling client and server errors +It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses: + +```js +function checkStatus(res) { + if (res.ok) { // res.status >= 200 && res.status < 300 + return res; + } else { + throw MyCustomError(res.statusText); + } +} + +fetch('https://httpbin.org/status/400') + .then(checkStatus) + .then(res => console.log('will not get here...')) +``` + +## Advanced Usage + +#### Streams +The "Node.js way" is to use streams when possible: + +```js +fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') + .then(res => { + const dest = fs.createWriteStream('./octocat.png'); + res.body.pipe(dest); + }); +``` + +In Node.js 14 you can also use async iterators to read `body`; however, be careful to catch +errors -- the longer a response runs, the more likely it is to encounter an error. + +```js +const fetch = require('node-fetch'); +const response = await fetch('https://httpbin.org/stream/3'); +try { + for await (const chunk of response.body) { + console.dir(JSON.parse(chunk.toString())); + } +} catch (err) { + console.error(err.stack); +} +``` + +In Node.js 12 you can also use async iterators to read `body`; however, async iterators with streams +did not mature until Node.js 14, so you need to do some extra work to ensure you handle errors +directly from the stream and wait on it response to fully close. + +```js +const fetch = require('node-fetch'); +const read = async body => { + let error; + body.on('error', err => { + error = err; + }); + for await (const chunk of body) { + console.dir(JSON.parse(chunk.toString())); + } + return new Promise((resolve, reject) => { + body.on('close', () => { + error ? reject(error) : resolve(); + }); + }); +}; +try { + const response = await fetch('https://httpbin.org/stream/3'); + await read(response.body); +} catch (err) { + console.error(err.stack); +} +``` + +#### Buffer +If you prefer to cache binary data in full, use buffer(). (NOTE: `buffer()` is a `node-fetch`-only API) + +```js +const fileType = require('file-type'); + +fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') + .then(res => res.buffer()) + .then(buffer => fileType(buffer)) + .then(type => { /* ... */ }); +``` + +#### Accessing Headers and other Meta data +```js +fetch('https://github.com/') + .then(res => { + console.log(res.ok); + console.log(res.status); + console.log(res.statusText); + console.log(res.headers.raw()); + console.log(res.headers.get('content-type')); + }); +``` + +#### Extract Set-Cookie Header + +Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API. + +```js +fetch(url).then(res => { + // returns an array of values, instead of a string of comma-separated values + console.log(res.headers.raw()['set-cookie']); +}); +``` + +#### Post data using a file stream + +```js +const { createReadStream } = require('fs'); + +const stream = createReadStream('input.txt'); + +fetch('https://httpbin.org/post', { method: 'POST', body: stream }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Post with form-data (detect multipart) + +```js +const FormData = require('form-data'); + +const form = new FormData(); +form.append('a', 1); + +fetch('https://httpbin.org/post', { method: 'POST', body: form }) + .then(res => res.json()) + .then(json => console.log(json)); + +// OR, using custom headers +// NOTE: getHeaders() is non-standard API + +const form = new FormData(); +form.append('a', 1); + +const options = { + method: 'POST', + body: form, + headers: form.getHeaders() +} + +fetch('https://httpbin.org/post', options) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Request cancellation with AbortSignal + +> NOTE: You may cancel streamed requests only on Node >= v8.0.0 + +You may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller). + +An example of timing out a request after 150ms could be achieved as the following: + +```js +import AbortController from 'abort-controller'; + +const controller = new AbortController(); +const timeout = setTimeout( + () => { controller.abort(); }, + 150, +); + +fetch(url, { signal: controller.signal }) + .then(res => res.json()) + .then( + data => { + useData(data) + }, + err => { + if (err.name === 'AbortError') { + // request was aborted + } + }, + ) + .finally(() => { + clearTimeout(timeout); + }); +``` + +See [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js) for more examples. + + +## API + +### fetch(url[, options]) + +- `url` A string representing the URL for fetching +- `options` [Options](#fetch-options) for the HTTP(S) request +- Returns: Promise<[Response](#class-response)> + +Perform an HTTP(S) fetch. + +`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`. + + +### Options + +The default values are shown after each option key. + +```js +{ + // These properties are part of the Fetch Standard + method: 'GET', + headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below) + body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream + redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect + signal: null, // pass an instance of AbortSignal to optionally abort requests + + // The following properties are node-fetch extensions + follow: 20, // maximum redirect count. 0 to not follow redirect + timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead. + compress: true, // support gzip/deflate content encoding. false to disable + size: 0, // maximum response body size in bytes. 0 to disable + agent: null // http(s).Agent instance or function that returns an instance (see below) +} +``` + +##### Default Headers + +If no values are set, the following request headers will be sent automatically: + +Header | Value +------------------- | -------------------------------------------------------- +`Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_ +`Accept` | `*/*` +`Content-Length` | _(automatically calculated, if possible)_ +`Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ +`User-Agent` | `node-fetch/1.0 (+https://github.com/bitinn/node-fetch)` + +Note: when `body` is a `Stream`, `Content-Length` is not set automatically. + +##### Custom Agent + +The `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following: + +- Support self-signed certificate +- Use only IPv4 or IPv6 +- Custom DNS Lookup + +See [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information. + +If no agent is specified, the default agent provided by Node.js is used. Note that [this changed in Node.js 19](https://github.com/nodejs/node/blob/4267b92604ad78584244488e7f7508a690cb80d0/lib/_http_agent.js#L564) to have `keepalive` true by default. If you wish to enable `keepalive` in an earlier version of Node.js, you can override the agent as per the following code sample. + +In addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol. + +```js +const httpAgent = new http.Agent({ + keepAlive: true +}); +const httpsAgent = new https.Agent({ + keepAlive: true +}); + +const options = { + agent: function (_parsedURL) { + if (_parsedURL.protocol == 'http:') { + return httpAgent; + } else { + return httpsAgent; + } + } +} +``` + + +### Class: Request + +An HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface. + +Due to the nature of Node.js, the following properties are not implemented at this moment: + +- `type` +- `destination` +- `referrer` +- `referrerPolicy` +- `mode` +- `credentials` +- `cache` +- `integrity` +- `keepalive` + +The following node-fetch extension properties are provided: + +- `follow` +- `compress` +- `counter` +- `agent` + +See [options](#fetch-options) for exact meaning of these extensions. + +#### new Request(input[, options]) + +*(spec-compliant)* + +- `input` A string representing a URL, or another `Request` (which will be cloned) +- `options` [Options][#fetch-options] for the HTTP(S) request + +Constructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request). + +In most cases, directly `fetch(url, options)` is simpler than creating a `Request` object. + + +### Class: Response + +An HTTP(S) response. This class implements the [Body](#iface-body) interface. + +The following properties are not implemented in node-fetch at this moment: + +- `Response.error()` +- `Response.redirect()` +- `type` +- `trailer` + +#### new Response([body[, options]]) + +*(spec-compliant)* + +- `body` A `String` or [`Readable` stream][node-readable] +- `options` A [`ResponseInit`][response-init] options dictionary + +Constructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response). + +Because Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly. + +#### response.ok + +*(spec-compliant)* + +Convenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300. + +#### response.redirected + +*(spec-compliant)* + +Convenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0. + + +### Class: Headers + +This class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented. + +#### new Headers([init]) + +*(spec-compliant)* + +- `init` Optional argument to pre-fill the `Headers` object + +Construct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object. + +```js +// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class + +const meta = { + 'Content-Type': 'text/xml', + 'Breaking-Bad': '<3' +}; +const headers = new Headers(meta); + +// The above is equivalent to +const meta = [ + [ 'Content-Type', 'text/xml' ], + [ 'Breaking-Bad', '<3' ] +]; +const headers = new Headers(meta); + +// You can in fact use any iterable objects, like a Map or even another Headers +const meta = new Map(); +meta.set('Content-Type', 'text/xml'); +meta.set('Breaking-Bad', '<3'); +const headers = new Headers(meta); +const copyOfHeaders = new Headers(headers); +``` + + +### Interface: Body + +`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes. + +The following methods are not yet implemented in node-fetch at this moment: + +- `formData()` + +#### body.body + +*(deviation from spec)* + +* Node.js [`Readable` stream][node-readable] + +Data are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable]. + +#### body.bodyUsed + +*(spec-compliant)* + +* `Boolean` + +A boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again. + +#### body.arrayBuffer() +#### body.blob() +#### body.json() +#### body.text() + +*(spec-compliant)* + +* Returns: Promise + +Consume the body and return a promise that will resolve to one of these formats. + +#### body.buffer() + +*(node-fetch extension)* + +* Returns: Promise<Buffer> + +Consume the body and return a promise that will resolve to a Buffer. + +#### body.textConverted() + +*(node-fetch extension)* + +* Returns: Promise<String> + +Identical to `body.text()`, except instead of always converting to UTF-8, encoding sniffing will be performed and text converted to UTF-8 if possible. + +(This API requires an optional dependency of the npm package [encoding](https://www.npmjs.com/package/encoding), which you need to install manually. `webpack` users may see [a warning message](https://github.com/bitinn/node-fetch/issues/412#issuecomment-379007792) due to this optional dependency.) + + +### Class: FetchError + +*(node-fetch extension)* + +An operational error in the fetching process. See [ERROR-HANDLING.md][] for more info. + + +### Class: AbortError + +*(node-fetch extension)* + +An Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info. + +## Acknowledgement + +Thanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference. + +`node-fetch` v1 was maintained by [@bitinn](https://github.com/bitinn); v2 was maintained by [@TimothyGu](https://github.com/timothygu), [@bitinn](https://github.com/bitinn) and [@jimmywarting](https://github.com/jimmywarting); v2 readme is written by [@jkantr](https://github.com/jkantr). + +## License + +MIT + +[npm-image]: https://flat.badgen.net/npm/v/node-fetch +[npm-url]: https://www.npmjs.com/package/node-fetch +[travis-image]: https://flat.badgen.net/travis/bitinn/node-fetch +[travis-url]: https://travis-ci.org/bitinn/node-fetch +[codecov-image]: https://flat.badgen.net/codecov/c/github/bitinn/node-fetch/master +[codecov-url]: https://codecov.io/gh/bitinn/node-fetch +[install-size-image]: https://flat.badgen.net/packagephobia/install/node-fetch +[install-size-url]: https://packagephobia.now.sh/result?p=node-fetch +[discord-image]: https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord&style=flat-square +[discord-url]: https://discord.gg/Zxbndcm +[opencollective-image]: https://opencollective.com/node-fetch/backers.svg +[opencollective-url]: https://opencollective.com/node-fetch +[whatwg-fetch]: https://fetch.spec.whatwg.org/ +[response-init]: https://fetch.spec.whatwg.org/#responseinit +[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams +[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers +[LIMITS.md]: https://github.com/bitinn/node-fetch/blob/master/LIMITS.md +[ERROR-HANDLING.md]: https://github.com/bitinn/node-fetch/blob/master/ERROR-HANDLING.md +[UPGRADE-GUIDE.md]: https://github.com/bitinn/node-fetch/blob/master/UPGRADE-GUIDE.md diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/browser.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..ee86265ae3adab9f03cf10f486384735417320e6 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/browser.js @@ -0,0 +1,25 @@ +"use strict"; + +// ref: https://github.com/tc39/proposal-global +var getGlobal = function () { + // the only reliable means to get the global object is + // `Function('return this')()` + // However, this causes CSP violations in Chrome apps. + if (typeof self !== 'undefined') { return self; } + if (typeof window !== 'undefined') { return window; } + if (typeof global !== 'undefined') { return global; } + throw new Error('unable to locate global object'); +} + +var globalObject = getGlobal(); + +module.exports = exports = globalObject.fetch; + +// Needed for TypeScript and Webpack. +if (globalObject.fetch) { + exports.default = globalObject.fetch.bind(globalObject); +} + +exports.Headers = globalObject.Headers; +exports.Request = globalObject.Request; +exports.Response = globalObject.Response; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/lib/index.es.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/lib/index.es.js new file mode 100644 index 0000000000000000000000000000000000000000..aae9799c1a8798d5899ffed6deda4c98b7007b48 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/lib/index.es.js @@ -0,0 +1,1777 @@ +process.emitWarning("The .es.js file is deprecated. Use .mjs instead."); + +import Stream from 'stream'; +import http from 'http'; +import Url from 'url'; +import whatwgUrl from 'whatwg-url'; +import https from 'https'; +import zlib from 'zlib'; + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +export default fetch; +export { Headers, Request, Response, FetchError, AbortError }; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/lib/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..567ff5da58e83683bec0ea9e86221041ddf9435f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/lib/index.js @@ -0,0 +1,1787 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var Stream = _interopDefault(require('stream')); +var http = _interopDefault(require('http')); +var Url = _interopDefault(require('url')); +var whatwgUrl = _interopDefault(require('whatwg-url')); +var https = _interopDefault(require('https')); +var zlib = _interopDefault(require('zlib')); + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +module.exports = exports = fetch; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = exports; +exports.Headers = Headers; +exports.Request = Request; +exports.Response = Response; +exports.FetchError = FetchError; +exports.AbortError = AbortError; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/lib/index.mjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/lib/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2863dd9c318754a77c6bfb57ec5e7db8759abd8b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/lib/index.mjs @@ -0,0 +1,1775 @@ +import Stream from 'stream'; +import http from 'http'; +import Url from 'url'; +import whatwgUrl from 'whatwg-url'; +import https from 'https'; +import zlib from 'zlib'; + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +export default fetch; +export { Headers, Request, Response, FetchError, AbortError }; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e0be17689a436a7734b168e8d12f5e97e054f0a5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/node-fetch/package.json @@ -0,0 +1,89 @@ +{ + "name": "node-fetch", + "version": "2.7.0", + "description": "A light-weight module that brings window.fetch to node.js", + "main": "lib/index.js", + "browser": "./browser.js", + "module": "lib/index.mjs", + "files": [ + "lib/index.js", + "lib/index.mjs", + "lib/index.es.js", + "browser.js" + ], + "engines": { + "node": "4.x || >=6.0.0" + }, + "scripts": { + "build": "cross-env BABEL_ENV=rollup rollup -c", + "prepare": "npm run build", + "test": "cross-env BABEL_ENV=test mocha --require babel-register --throw-deprecation test/test.js", + "report": "cross-env BABEL_ENV=coverage nyc --reporter lcov --reporter text mocha -R spec test/test.js", + "coverage": "cross-env BABEL_ENV=coverage nyc --reporter json --reporter text mocha -R spec test/test.js && codecov -f coverage/coverage-final.json" + }, + "repository": { + "type": "git", + "url": "https://github.com/bitinn/node-fetch.git" + }, + "keywords": [ + "fetch", + "http", + "promise" + ], + "author": "David Frank", + "license": "MIT", + "bugs": { + "url": "https://github.com/bitinn/node-fetch/issues" + }, + "homepage": "https://github.com/bitinn/node-fetch", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + }, + "devDependencies": { + "@ungap/url-search-params": "^0.1.2", + "abort-controller": "^1.1.0", + "abortcontroller-polyfill": "^1.3.0", + "babel-core": "^6.26.3", + "babel-plugin-istanbul": "^4.1.6", + "babel-plugin-transform-async-generator-functions": "^6.24.1", + "babel-polyfill": "^6.26.0", + "babel-preset-env": "1.4.0", + "babel-register": "^6.16.3", + "chai": "^3.5.0", + "chai-as-promised": "^7.1.1", + "chai-iterator": "^1.1.1", + "chai-string": "~1.3.0", + "codecov": "3.3.0", + "cross-env": "^5.2.0", + "form-data": "^2.3.3", + "is-builtin-module": "^1.0.0", + "mocha": "^5.0.0", + "nyc": "11.9.0", + "parted": "^0.1.1", + "promise": "^8.0.3", + "resumer": "0.0.0", + "rollup": "^0.63.4", + "rollup-plugin-babel": "^3.0.7", + "string-to-arraybuffer": "^1.0.2", + "teeny-request": "3.7.0" + }, + "release": { + "branches": [ + "+([0-9]).x", + "main", + "next", + { + "name": "beta", + "prerelease": true + } + ] + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/CHANGELOG.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..0412ad8a67cb18f38b7457b9fe0608eef68d0822 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/CHANGELOG.md @@ -0,0 +1,274 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +## [9.0.1](https://github.com/uuidjs/uuid/compare/v9.0.0...v9.0.1) (2023-09-12) + +### build + +- Fix CI to work with Node.js 20.x + +## [9.0.0](https://github.com/uuidjs/uuid/compare/v8.3.2...v9.0.0) (2022-09-05) + +### ⚠ BREAKING CHANGES + +- Drop Node.js 10.x support. This library always aims at supporting one EOLed LTS release which by this time now is 12.x which has reached EOL 30 Apr 2022. + +- Remove the minified UMD build from the package. + + Minified code is hard to audit and since this is a widely used library it seems more appropriate nowadays to optimize for auditability than to ship a legacy module format that, at best, serves educational purposes nowadays. + + For production browser use cases, users should be using a bundler. For educational purposes, today's online sandboxes like replit.com offer convenient ways to load npm modules, so the use case for UMD through repos like UNPKG or jsDelivr has largely vanished. + +- Drop IE 11 and Safari 10 support. Drop support for browsers that don't correctly implement const/let and default arguments, and no longer transpile the browser build to ES2015. + + This also removes the fallback on msCrypto instead of the crypto API. + + Browser tests are run in the first supported version of each supported browser and in the latest (as of this commit) version available on Browserstack. + +### Features + +- optimize uuid.v1 by 1.3x uuid.v4 by 4.3x (430%) ([#597](https://github.com/uuidjs/uuid/issues/597)) ([3a033f6](https://github.com/uuidjs/uuid/commit/3a033f6bab6bb3780ece6d645b902548043280bc)) +- remove UMD build ([#645](https://github.com/uuidjs/uuid/issues/645)) ([e948a0f](https://github.com/uuidjs/uuid/commit/e948a0f22bf22f4619b27bd913885e478e20fe6f)), closes [#620](https://github.com/uuidjs/uuid/issues/620) +- use native crypto.randomUUID when available ([#600](https://github.com/uuidjs/uuid/issues/600)) ([c9e076c](https://github.com/uuidjs/uuid/commit/c9e076c852edad7e9a06baaa1d148cf4eda6c6c4)) + +### Bug Fixes + +- add Jest/jsdom compatibility ([#642](https://github.com/uuidjs/uuid/issues/642)) ([16f9c46](https://github.com/uuidjs/uuid/commit/16f9c469edf46f0786164cdf4dc980743984a6fd)) +- change default export to named function ([#545](https://github.com/uuidjs/uuid/issues/545)) ([c57bc5a](https://github.com/uuidjs/uuid/commit/c57bc5a9a0653273aa639cda9177ce52efabe42a)) +- handle error when parameter is not set in v3 and v5 ([#622](https://github.com/uuidjs/uuid/issues/622)) ([fcd7388](https://github.com/uuidjs/uuid/commit/fcd73881692d9fabb63872576ba28e30ff852091)) +- run npm audit fix ([#644](https://github.com/uuidjs/uuid/issues/644)) ([04686f5](https://github.com/uuidjs/uuid/commit/04686f54c5fed2cfffc1b619f4970c4bb8532353)) +- upgrading from uuid3 broken link ([#568](https://github.com/uuidjs/uuid/issues/568)) ([1c849da](https://github.com/uuidjs/uuid/commit/1c849da6e164259e72e18636726345b13a7eddd6)) + +### build + +- drop Node.js 8.x from babel transpile target ([#603](https://github.com/uuidjs/uuid/issues/603)) ([aa11485](https://github.com/uuidjs/uuid/commit/aa114858260402107ec8a1e1a825dea0a259bcb5)) +- drop support for legacy browsers (IE11, Safari 10) ([#604](https://github.com/uuidjs/uuid/issues/604)) ([0f433e5](https://github.com/uuidjs/uuid/commit/0f433e5ec444edacd53016de67db021102f36148)) + +- drop node 10.x to upgrade dev dependencies ([#653](https://github.com/uuidjs/uuid/issues/653)) ([28a5712](https://github.com/uuidjs/uuid/commit/28a571283f8abda6b9d85e689f95b7d3ee9e282e)), closes [#643](https://github.com/uuidjs/uuid/issues/643) + +### [8.3.2](https://github.com/uuidjs/uuid/compare/v8.3.1...v8.3.2) (2020-12-08) + +### Bug Fixes + +- lazy load getRandomValues ([#537](https://github.com/uuidjs/uuid/issues/537)) ([16c8f6d](https://github.com/uuidjs/uuid/commit/16c8f6df2f6b09b4d6235602d6a591188320a82e)), closes [#536](https://github.com/uuidjs/uuid/issues/536) + +### [8.3.1](https://github.com/uuidjs/uuid/compare/v8.3.0...v8.3.1) (2020-10-04) + +### Bug Fixes + +- support expo>=39.0.0 ([#515](https://github.com/uuidjs/uuid/issues/515)) ([c65a0f3](https://github.com/uuidjs/uuid/commit/c65a0f3fa73b901959d638d1e3591dfacdbed867)), closes [#375](https://github.com/uuidjs/uuid/issues/375) + +## [8.3.0](https://github.com/uuidjs/uuid/compare/v8.2.0...v8.3.0) (2020-07-27) + +### Features + +- add parse/stringify/validate/version/NIL APIs ([#479](https://github.com/uuidjs/uuid/issues/479)) ([0e6c10b](https://github.com/uuidjs/uuid/commit/0e6c10ba1bf9517796ff23c052fc0468eedfd5f4)), closes [#475](https://github.com/uuidjs/uuid/issues/475) [#478](https://github.com/uuidjs/uuid/issues/478) [#480](https://github.com/uuidjs/uuid/issues/480) [#481](https://github.com/uuidjs/uuid/issues/481) [#180](https://github.com/uuidjs/uuid/issues/180) + +## [8.2.0](https://github.com/uuidjs/uuid/compare/v8.1.0...v8.2.0) (2020-06-23) + +### Features + +- improve performance of v1 string representation ([#453](https://github.com/uuidjs/uuid/issues/453)) ([0ee0b67](https://github.com/uuidjs/uuid/commit/0ee0b67c37846529c66089880414d29f3ae132d5)) +- remove deprecated v4 string parameter ([#454](https://github.com/uuidjs/uuid/issues/454)) ([88ce3ca](https://github.com/uuidjs/uuid/commit/88ce3ca0ba046f60856de62c7ce03f7ba98ba46c)), closes [#437](https://github.com/uuidjs/uuid/issues/437) +- support jspm ([#473](https://github.com/uuidjs/uuid/issues/473)) ([e9f2587](https://github.com/uuidjs/uuid/commit/e9f2587a92575cac31bc1d4ae944e17c09756659)) + +### Bug Fixes + +- prepare package exports for webpack 5 ([#468](https://github.com/uuidjs/uuid/issues/468)) ([8d6e6a5](https://github.com/uuidjs/uuid/commit/8d6e6a5f8965ca9575eb4d92e99a43435f4a58a8)) + +## [8.1.0](https://github.com/uuidjs/uuid/compare/v8.0.0...v8.1.0) (2020-05-20) + +### Features + +- improve v4 performance by reusing random number array ([#435](https://github.com/uuidjs/uuid/issues/435)) ([bf4af0d](https://github.com/uuidjs/uuid/commit/bf4af0d711b4d2ed03d1f74fd12ad0baa87dc79d)) +- optimize V8 performance of bytesToUuid ([#434](https://github.com/uuidjs/uuid/issues/434)) ([e156415](https://github.com/uuidjs/uuid/commit/e156415448ec1af2351fa0b6660cfb22581971f2)) + +### Bug Fixes + +- export package.json required by react-native and bundlers ([#449](https://github.com/uuidjs/uuid/issues/449)) ([be1c8fe](https://github.com/uuidjs/uuid/commit/be1c8fe9a3206c358e0059b52fafd7213aa48a52)), closes [ai/nanoevents#44](https://github.com/ai/nanoevents/issues/44#issuecomment-602010343) [#444](https://github.com/uuidjs/uuid/issues/444) + +## [8.0.0](https://github.com/uuidjs/uuid/compare/v7.0.3...v8.0.0) (2020-04-29) + +### ⚠ BREAKING CHANGES + +- For native ECMAScript Module (ESM) usage in Node.js only named exports are exposed, there is no more default export. + + ```diff + -import uuid from 'uuid'; + -console.log(uuid.v4()); // -> 'cd6c3b08-0adc-4f4b-a6ef-36087a1c9869' + +import { v4 as uuidv4 } from 'uuid'; + +uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' + ``` + +- Deep requiring specific algorithms of this library like `require('uuid/v4')`, which has been deprecated in `uuid@7`, is no longer supported. + + Instead use the named exports that this module exports. + + For ECMAScript Modules (ESM): + + ```diff + -import uuidv4 from 'uuid/v4'; + +import { v4 as uuidv4 } from 'uuid'; + uuidv4(); + ``` + + For CommonJS: + + ```diff + -const uuidv4 = require('uuid/v4'); + +const { v4: uuidv4 } = require('uuid'); + uuidv4(); + ``` + +### Features + +- native Node.js ES Modules (wrapper approach) ([#423](https://github.com/uuidjs/uuid/issues/423)) ([2d9f590](https://github.com/uuidjs/uuid/commit/2d9f590ad9701d692625c07ed62f0a0f91227991)), closes [#245](https://github.com/uuidjs/uuid/issues/245) [#419](https://github.com/uuidjs/uuid/issues/419) [#342](https://github.com/uuidjs/uuid/issues/342) +- remove deep requires ([#426](https://github.com/uuidjs/uuid/issues/426)) ([daf72b8](https://github.com/uuidjs/uuid/commit/daf72b84ceb20272a81bb5fbddb05dd95922cbba)) + +### Bug Fixes + +- add CommonJS syntax example to README quickstart section ([#417](https://github.com/uuidjs/uuid/issues/417)) ([e0ec840](https://github.com/uuidjs/uuid/commit/e0ec8402c7ad44b7ef0453036c612f5db513fda0)) + +### [7.0.3](https://github.com/uuidjs/uuid/compare/v7.0.2...v7.0.3) (2020-03-31) + +### Bug Fixes + +- make deep require deprecation warning work in browsers ([#409](https://github.com/uuidjs/uuid/issues/409)) ([4b71107](https://github.com/uuidjs/uuid/commit/4b71107d8c0d2ef56861ede6403fc9dc35a1e6bf)), closes [#408](https://github.com/uuidjs/uuid/issues/408) + +### [7.0.2](https://github.com/uuidjs/uuid/compare/v7.0.1...v7.0.2) (2020-03-04) + +### Bug Fixes + +- make access to msCrypto consistent ([#393](https://github.com/uuidjs/uuid/issues/393)) ([8bf2a20](https://github.com/uuidjs/uuid/commit/8bf2a20f3565df743da7215eebdbada9d2df118c)) +- simplify link in deprecation warning ([#391](https://github.com/uuidjs/uuid/issues/391)) ([bb2c8e4](https://github.com/uuidjs/uuid/commit/bb2c8e4e9f4c5f9c1eaaf3ea59710c633cd90cb7)) +- update links to match content in readme ([#386](https://github.com/uuidjs/uuid/issues/386)) ([44f2f86](https://github.com/uuidjs/uuid/commit/44f2f86e9d2bbf14ee5f0f00f72a3db1292666d4)) + +### [7.0.1](https://github.com/uuidjs/uuid/compare/v7.0.0...v7.0.1) (2020-02-25) + +### Bug Fixes + +- clean up esm builds for node and browser ([#383](https://github.com/uuidjs/uuid/issues/383)) ([59e6a49](https://github.com/uuidjs/uuid/commit/59e6a49e7ce7b3e8fb0f3ee52b9daae72af467dc)) +- provide browser versions independent from module system ([#380](https://github.com/uuidjs/uuid/issues/380)) ([4344a22](https://github.com/uuidjs/uuid/commit/4344a22e7aed33be8627eeaaf05360f256a21753)), closes [#378](https://github.com/uuidjs/uuid/issues/378) + +## [7.0.0](https://github.com/uuidjs/uuid/compare/v3.4.0...v7.0.0) (2020-02-24) + +### ⚠ BREAKING CHANGES + +- The default export, which used to be the v4() method but which was already discouraged in v3.x of this library, has been removed. +- Explicitly note that deep imports of the different uuid version functions are deprecated and no longer encouraged and that ECMAScript module named imports should be used instead. Emit a deprecation warning for people who deep-require the different algorithm variants. +- Remove builtin support for insecure random number generators in the browser. Users who want that will have to supply their own random number generator function. +- Remove support for generating v3 and v5 UUIDs in Node.js<4.x +- Convert code base to ECMAScript Modules (ESM) and release CommonJS build for node and ESM build for browser bundlers. + +### Features + +- add UMD build to npm package ([#357](https://github.com/uuidjs/uuid/issues/357)) ([4e75adf](https://github.com/uuidjs/uuid/commit/4e75adf435196f28e3fbbe0185d654b5ded7ca2c)), closes [#345](https://github.com/uuidjs/uuid/issues/345) +- add various es module and CommonJS examples ([b238510](https://github.com/uuidjs/uuid/commit/b238510bf352463521f74bab175a3af9b7a42555)) +- ensure that docs are up-to-date in CI ([ee5e77d](https://github.com/uuidjs/uuid/commit/ee5e77db547474f5a8f23d6c857a6d399209986b)) +- hybrid CommonJS & ECMAScript modules build ([a3f078f](https://github.com/uuidjs/uuid/commit/a3f078faa0baff69ab41aed08e041f8f9c8993d0)) +- remove insecure fallback random number generator ([3a5842b](https://github.com/uuidjs/uuid/commit/3a5842b141a6e5de0ae338f391661e6b84b167c9)), closes [#173](https://github.com/uuidjs/uuid/issues/173) +- remove support for pre Node.js v4 Buffer API ([#356](https://github.com/uuidjs/uuid/issues/356)) ([b59b5c5](https://github.com/uuidjs/uuid/commit/b59b5c5ecad271c5453f1a156f011671f6d35627)) +- rename repository to github:uuidjs/uuid ([#351](https://github.com/uuidjs/uuid/issues/351)) ([c37a518](https://github.com/uuidjs/uuid/commit/c37a518e367ac4b6d0aa62dba1bc6ce9e85020f7)), closes [#338](https://github.com/uuidjs/uuid/issues/338) + +### Bug Fixes + +- add deep-require proxies for local testing and adjust tests ([#365](https://github.com/uuidjs/uuid/issues/365)) ([7fedc79](https://github.com/uuidjs/uuid/commit/7fedc79ac8fda4bfd1c566c7f05ef4ac13b2db48)) +- add note about removal of default export ([#372](https://github.com/uuidjs/uuid/issues/372)) ([12749b7](https://github.com/uuidjs/uuid/commit/12749b700eb49db8a9759fd306d8be05dbfbd58c)), closes [#370](https://github.com/uuidjs/uuid/issues/370) +- deprecated deep requiring of the different algorithm versions ([#361](https://github.com/uuidjs/uuid/issues/361)) ([c0bdf15](https://github.com/uuidjs/uuid/commit/c0bdf15e417639b1aeb0b247b2fb11f7a0a26b23)) + +## [3.4.0](https://github.com/uuidjs/uuid/compare/v3.3.3...v3.4.0) (2020-01-16) + +### Features + +- rename repository to github:uuidjs/uuid ([#351](https://github.com/uuidjs/uuid/issues/351)) ([e2d7314](https://github.com/uuidjs/uuid/commit/e2d7314)), closes [#338](https://github.com/uuidjs/uuid/issues/338) + +## [3.3.3](https://github.com/uuidjs/uuid/compare/v3.3.2...v3.3.3) (2019-08-19) + +### Bug Fixes + +- no longer run ci tests on node v4 +- upgrade dependencies + +## [3.3.2](https://github.com/uuidjs/uuid/compare/v3.3.1...v3.3.2) (2018-06-28) + +### Bug Fixes + +- typo ([305d877](https://github.com/uuidjs/uuid/commit/305d877)) + +## [3.3.1](https://github.com/uuidjs/uuid/compare/v3.3.0...v3.3.1) (2018-06-28) + +### Bug Fixes + +- fix [#284](https://github.com/uuidjs/uuid/issues/284) by setting function name in try-catch ([f2a60f2](https://github.com/uuidjs/uuid/commit/f2a60f2)) + +# [3.3.0](https://github.com/uuidjs/uuid/compare/v3.2.1...v3.3.0) (2018-06-22) + +### Bug Fixes + +- assignment to readonly property to allow running in strict mode ([#270](https://github.com/uuidjs/uuid/issues/270)) ([d062fdc](https://github.com/uuidjs/uuid/commit/d062fdc)) +- fix [#229](https://github.com/uuidjs/uuid/issues/229) ([c9684d4](https://github.com/uuidjs/uuid/commit/c9684d4)) +- Get correct version of IE11 crypto ([#274](https://github.com/uuidjs/uuid/issues/274)) ([153d331](https://github.com/uuidjs/uuid/commit/153d331)) +- mem issue when generating uuid ([#267](https://github.com/uuidjs/uuid/issues/267)) ([c47702c](https://github.com/uuidjs/uuid/commit/c47702c)) + +### Features + +- enforce Conventional Commit style commit messages ([#282](https://github.com/uuidjs/uuid/issues/282)) ([cc9a182](https://github.com/uuidjs/uuid/commit/cc9a182)) + +## [3.2.1](https://github.com/uuidjs/uuid/compare/v3.2.0...v3.2.1) (2018-01-16) + +### Bug Fixes + +- use msCrypto if available. Fixes [#241](https://github.com/uuidjs/uuid/issues/241) ([#247](https://github.com/uuidjs/uuid/issues/247)) ([1fef18b](https://github.com/uuidjs/uuid/commit/1fef18b)) + +# [3.2.0](https://github.com/uuidjs/uuid/compare/v3.1.0...v3.2.0) (2018-01-16) + +### Bug Fixes + +- remove mistakenly added typescript dependency, rollback version (standard-version will auto-increment) ([09fa824](https://github.com/uuidjs/uuid/commit/09fa824)) +- use msCrypto if available. Fixes [#241](https://github.com/uuidjs/uuid/issues/241) ([#247](https://github.com/uuidjs/uuid/issues/247)) ([1fef18b](https://github.com/uuidjs/uuid/commit/1fef18b)) + +### Features + +- Add v3 Support ([#217](https://github.com/uuidjs/uuid/issues/217)) ([d94f726](https://github.com/uuidjs/uuid/commit/d94f726)) + +# [3.1.0](https://github.com/uuidjs/uuid/compare/v3.1.0...v3.0.1) (2017-06-17) + +### Bug Fixes + +- (fix) Add .npmignore file to exclude test/ and other non-essential files from packing. (#183) +- Fix typo (#178) +- Simple typo fix (#165) + +### Features + +- v5 support in CLI (#197) +- V5 support (#188) + +# 3.0.1 (2016-11-28) + +- split uuid versions into separate files + +# 3.0.0 (2016-11-17) + +- remove .parse and .unparse + +# 2.0.0 + +- Removed uuid.BufferClass + +# 1.4.0 + +- Improved module context detection +- Removed public RNG functions + +# 1.3.2 + +- Improve tests and handling of v1() options (Issue #24) +- Expose RNG option to allow for perf testing with different generators + +# 1.3.0 + +- Support for version 1 ids, thanks to [@ctavan](https://github.com/ctavan)! +- Support for node.js crypto API +- De-emphasizing performance in favor of a) cryptographic quality PRNGs where available and b) more manageable code diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/CONTRIBUTING.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..4a4503d02ca583abaf879d97e9bf7e7c813c8a85 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/CONTRIBUTING.md @@ -0,0 +1,18 @@ +# Contributing + +Please feel free to file GitHub Issues or propose Pull Requests. We're always happy to discuss improvements to this library! + +## Testing + +```shell +npm test +``` + +## Releasing + +Releases are supposed to be done from master, version bumping is automated through [`standard-version`](https://github.com/conventional-changelog/standard-version): + +```shell +npm run release -- --dry-run # verify output manually +npm run release # follow the instructions from the output of this command +``` diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/LICENSE.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..3934168364063216aa8805f06e3a1a8605133d68 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/LICENSE.md @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2010-2020 Robert Kieffer and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/README.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4f51e0980403a26464533f210a8fb0cdcd66c32a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/README.md @@ -0,0 +1,466 @@ + + + +# uuid [![CI](https://github.com/uuidjs/uuid/workflows/CI/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ACI) [![Browser](https://github.com/uuidjs/uuid/workflows/Browser/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ABrowser) + +For the creation of [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) UUIDs + +- **Complete** - Support for RFC4122 version 1, 3, 4, and 5 UUIDs +- **Cross-platform** - Support for ... + - CommonJS, [ECMAScript Modules](#ecmascript-modules) and [CDN builds](#cdn-builds) + - NodeJS 12+ ([LTS releases](https://github.com/nodejs/Release)) + - Chrome, Safari, Firefox, Edge browsers + - Webpack and rollup.js module bundlers + - [React Native / Expo](#react-native--expo) +- **Secure** - Cryptographically-strong random values +- **Small** - Zero-dependency, small footprint, plays nice with "tree shaking" packagers +- **CLI** - Includes the [`uuid` command line](#command-line) utility + +> **Note** Upgrading from `uuid@3`? Your code is probably okay, but check out [Upgrading From `uuid@3`](#upgrading-from-uuid3) for details. + +> **Note** Only interested in creating a version 4 UUID? You might be able to use [`crypto.randomUUID()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID), eliminating the need to install this library. + +## Quickstart + +To create a random UUID... + +**1. Install** + +```shell +npm install uuid +``` + +**2. Create a UUID** (ES6 module syntax) + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' +``` + +... or using CommonJS syntax: + +```javascript +const { v4: uuidv4 } = require('uuid'); +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +For timestamp UUIDs, namespace UUIDs, and other options read on ... + +## API Summary + +| | | | +| --- | --- | --- | +| [`uuid.NIL`](#uuidnil) | The nil UUID string (all zeros) | New in `uuid@8.3` | +| [`uuid.parse()`](#uuidparsestr) | Convert UUID string to array of bytes | New in `uuid@8.3` | +| [`uuid.stringify()`](#uuidstringifyarr-offset) | Convert array of bytes to UUID string | New in `uuid@8.3` | +| [`uuid.v1()`](#uuidv1options-buffer-offset) | Create a version 1 (timestamp) UUID | | +| [`uuid.v3()`](#uuidv3name-namespace-buffer-offset) | Create a version 3 (namespace w/ MD5) UUID | | +| [`uuid.v4()`](#uuidv4options-buffer-offset) | Create a version 4 (random) UUID | | +| [`uuid.v5()`](#uuidv5name-namespace-buffer-offset) | Create a version 5 (namespace w/ SHA-1) UUID | | +| [`uuid.validate()`](#uuidvalidatestr) | Test a string to see if it is a valid UUID | New in `uuid@8.3` | +| [`uuid.version()`](#uuidversionstr) | Detect RFC version of a UUID | New in `uuid@8.3` | + +## API + +### uuid.NIL + +The nil UUID string (all zeros). + +Example: + +```javascript +import { NIL as NIL_UUID } from 'uuid'; + +NIL_UUID; // ⇨ '00000000-0000-0000-0000-000000000000' +``` + +### uuid.parse(str) + +Convert UUID string to array of bytes + +| | | +| --------- | ---------------------------------------- | +| `str` | A valid UUID `String` | +| _returns_ | `Uint8Array[16]` | +| _throws_ | `TypeError` if `str` is not a valid UUID | + +Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left ↠ right order of hex-pairs in UUID strings. As shown in the example below. + +Example: + +```javascript +import { parse as uuidParse } from 'uuid'; + +// Parse a UUID +const bytes = uuidParse('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); + +// Convert to hex strings to show byte order (for documentation purposes) +[...bytes].map((v) => v.toString(16).padStart(2, '0')); // ⇨ + // [ + // '6e', 'c0', 'bd', '7f', + // '11', 'c0', '43', 'da', + // '97', '5e', '2a', '8a', + // 'd9', 'eb', 'ae', '0b' + // ] +``` + +### uuid.stringify(arr[, offset]) + +Convert array of bytes to UUID string + +| | | +| -------------- | ---------------------------------------------------------------------------- | +| `arr` | `Array`-like collection of 16 values (starting from `offset`) between 0-255. | +| [`offset` = 0] | `Number` Starting index in the Array | +| _returns_ | `String` | +| _throws_ | `TypeError` if a valid UUID string cannot be generated | + +Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left ↠ right order of hex-pairs in UUID strings. As shown in the example below. + +Example: + +```javascript +import { stringify as uuidStringify } from 'uuid'; + +const uuidBytes = [ + 0x6e, 0xc0, 0xbd, 0x7f, 0x11, 0xc0, 0x43, 0xda, 0x97, 0x5e, 0x2a, 0x8a, 0xd9, 0xeb, 0xae, 0x0b, +]; + +uuidStringify(uuidBytes); // ⇨ '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b' +``` + +### uuid.v1([options[, buffer[, offset]]]) + +Create an RFC version 1 (timestamp) UUID + +| | | +| --- | --- | +| [`options`] | `Object` with one or more of the following properties: | +| [`options.node` ] | RFC "node" field as an `Array[6]` of byte values (per 4.1.6) | +| [`options.clockseq`] | RFC "clock sequence" as a `Number` between 0 - 0x3fff | +| [`options.msecs`] | RFC "timestamp" field (`Number` of milliseconds, unix epoch) | +| [`options.nsecs`] | RFC "timestamp" field (`Number` of nanoseconds to add to `msecs`, should be 0-10,000) | +| [`options.random`] | `Array` of 16 random bytes (0-255) | +| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | +| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | +| _throws_ | `Error` if more than 10M UUIDs/sec are requested | + +Note: The default [node id](https://tools.ietf.org/html/rfc4122#section-4.1.6) (the last 12 digits in the UUID) is generated once, randomly, on process startup, and then remains unchanged for the duration of the process. + +Note: `options.random` and `options.rng` are only meaningful on the very first call to `v1()`, where they may be passed to initialize the internal `node` and `clockseq` fields. + +Example: + +```javascript +import { v1 as uuidv1 } from 'uuid'; + +uuidv1(); // ⇨ '2c5ea4c0-4067-11e9-8bad-9b1deb4d3b7d' +``` + +Example using `options`: + +```javascript +import { v1 as uuidv1 } from 'uuid'; + +const v1options = { + node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab], + clockseq: 0x1234, + msecs: new Date('2011-11-01').getTime(), + nsecs: 5678, +}; +uuidv1(v1options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab' +``` + +### uuid.v3(name, namespace[, buffer[, offset]]) + +Create an RFC version 3 (namespace w/ MD5) UUID + +API is identical to `v5()`, but uses "v3" instead. + +⚠️ Note: Per the RFC, "_If backward compatibility is not an issue, SHA-1 [Version 5] is preferred_." + +### uuid.v4([options[, buffer[, offset]]]) + +Create an RFC version 4 (random) UUID + +| | | +| --- | --- | +| [`options`] | `Object` with one or more of the following properties: | +| [`options.random`] | `Array` of 16 random bytes (0-255) | +| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | +| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | + +Example: + +```javascript +import { v4 as uuidv4 } from 'uuid'; + +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +Example using predefined `random` values: + +```javascript +import { v4 as uuidv4 } from 'uuid'; + +const v4options = { + random: [ + 0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea, 0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36, + ], +}; +uuidv4(v4options); // ⇨ '109156be-c4fb-41ea-b1b4-efe1671c5836' +``` + +### uuid.v5(name, namespace[, buffer[, offset]]) + +Create an RFC version 5 (namespace w/ SHA-1) UUID + +| | | +| --- | --- | +| `name` | `String \| Array` | +| `namespace` | `String \| Array[16]` Namespace UUID | +| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | + +Note: The RFC `DNS` and `URL` namespaces are available as `v5.DNS` and `v5.URL`. + +Example with custom namespace: + +```javascript +import { v5 as uuidv5 } from 'uuid'; + +// Define a custom namespace. Readers, create your own using something like +// https://www.uuidgenerator.net/ +const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; + +uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681' +``` + +Example with RFC `URL` namespace: + +```javascript +import { v5 as uuidv5 } from 'uuid'; + +uuidv5('https://www.w3.org/', uuidv5.URL); // ⇨ 'c106a26a-21bb-5538-8bf2-57095d1976c1' +``` + +### uuid.validate(str) + +Test a string to see if it is a valid UUID + +| | | +| --------- | --------------------------------------------------- | +| `str` | `String` to validate | +| _returns_ | `true` if string is a valid UUID, `false` otherwise | + +Example: + +```javascript +import { validate as uuidValidate } from 'uuid'; + +uuidValidate('not a UUID'); // ⇨ false +uuidValidate('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ true +``` + +Using `validate` and `version` together it is possible to do per-version validation, e.g. validate for only v4 UUIds. + +```javascript +import { version as uuidVersion } from 'uuid'; +import { validate as uuidValidate } from 'uuid'; + +function uuidValidateV4(uuid) { + return uuidValidate(uuid) && uuidVersion(uuid) === 4; +} + +const v1Uuid = 'd9428888-122b-11e1-b85c-61cd3cbb3210'; +const v4Uuid = '109156be-c4fb-41ea-b1b4-efe1671c5836'; + +uuidValidateV4(v4Uuid); // ⇨ true +uuidValidateV4(v1Uuid); // ⇨ false +``` + +### uuid.version(str) + +Detect RFC version of a UUID + +| | | +| --------- | ---------------------------------------- | +| `str` | A valid UUID `String` | +| _returns_ | `Number` The RFC version of the UUID | +| _throws_ | `TypeError` if `str` is not a valid UUID | + +Example: + +```javascript +import { version as uuidVersion } from 'uuid'; + +uuidVersion('45637ec4-c85f-11ea-87d0-0242ac130003'); // ⇨ 1 +uuidVersion('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ 4 +``` + +## Command Line + +UUIDs can be generated from the command line using `uuid`. + +```shell +$ npx uuid +ddeb27fb-d9a0-4624-be4d-4615062daed4 +``` + +The default is to generate version 4 UUIDS, however the other versions are supported. Type `uuid --help` for details: + +```shell +$ npx uuid --help + +Usage: + uuid + uuid v1 + uuid v3 + uuid v4 + uuid v5 + uuid --help + +Note: may be "URL" or "DNS" to use the corresponding UUIDs +defined by RFC4122 +``` + +## ECMAScript Modules + +This library comes with [ECMAScript Modules](https://www.ecma-international.org/ecma-262/6.0/#sec-modules) (ESM) support for Node.js versions that support it ([example](./examples/node-esmodules/)) as well as bundlers like [rollup.js](https://rollupjs.org/guide/en/#tree-shaking) ([example](./examples/browser-rollup/)) and [webpack](https://webpack.js.org/guides/tree-shaking/) ([example](./examples/browser-webpack/)) (targeting both, Node.js and browser environments). + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +To run the examples you must first create a dist build of this library in the module root: + +```shell +npm run build +``` + +## CDN Builds + +### ECMAScript Modules + +To load this module directly into modern browsers that [support loading ECMAScript Modules](https://caniuse.com/#feat=es6-module) you can make use of [jspm](https://jspm.org/): + +```html + +``` + +### UMD + +As of `uuid@9` [UMD (Universal Module Definition)](https://github.com/umdjs/umd) builds are no longer shipped with this library. + +If you need a UMD build of this library, use a bundler like Webpack or Rollup. Alternatively, refer to the documentation of [`uuid@8.3.2`](https://github.com/uuidjs/uuid/blob/v8.3.2/README.md#umd) which was the last version that shipped UMD builds. + +## Known issues + +### Duplicate UUIDs (Googlebot) + +This module may generate duplicate UUIDs when run in clients with _deterministic_ random number generators, such as [Googlebot crawlers](https://developers.google.com/search/docs/advanced/crawling/overview-google-crawlers). This can cause problems for apps that expect client-generated UUIDs to always be unique. Developers should be prepared for this and have a strategy for dealing with possible collisions, such as: + +- Check for duplicate UUIDs, fail gracefully +- Disable write operations for Googlebot clients + +### "getRandomValues() not supported" + +This error occurs in environments where the standard [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) API is not supported. This issue can be resolved by adding an appropriate polyfill: + +### React Native / Expo + +1. Install [`react-native-get-random-values`](https://github.com/LinusU/react-native-get-random-values#readme) +1. Import it _before_ `uuid`. Since `uuid` might also appear as a transitive dependency of some other imports it's safest to just import `react-native-get-random-values` as the very first thing in your entry point: + +```javascript +import 'react-native-get-random-values'; +import { v4 as uuidv4 } from 'uuid'; +``` + +Note: If you are using Expo, you must be using at least `react-native-get-random-values@1.5.0` and `expo@39.0.0`. + +### Web Workers / Service Workers (Edge <= 18) + +[In Edge <= 18, Web Crypto is not supported in Web Workers or Service Workers](https://caniuse.com/#feat=cryptography) and we are not aware of a polyfill (let us know if you find one, please). + +### IE 11 (Internet Explorer) + +Support for IE11 and other legacy browsers has been dropped as of `uuid@9`. If you need to support legacy browsers, you can always transpile the uuid module source yourself (e.g. using [Babel](https://babeljs.io/)). + +## Upgrading From `uuid@7` + +### Only Named Exports Supported When Using with Node.js ESM + +`uuid@7` did not come with native ECMAScript Module (ESM) support for Node.js. Importing it in Node.js ESM consequently imported the CommonJS source with a default export. This library now comes with true Node.js ESM support and only provides named exports. + +Instead of doing: + +```javascript +import uuid from 'uuid'; +uuid.v4(); +``` + +you will now have to use the named exports: + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); +``` + +### Deep Requires No Longer Supported + +Deep requires like `require('uuid/v4')` [which have been deprecated in `uuid@7`](#deep-requires-now-deprecated) are no longer supported. + +## Upgrading From `uuid@3` + +"_Wait... what happened to `uuid@4` thru `uuid@6`?!?_" + +In order to avoid confusion with RFC [version 4](#uuidv4options-buffer-offset) and [version 5](#uuidv5name-namespace-buffer-offset) UUIDs, and a possible [version 6](http://gh.peabody.io/uuidv6/), releases 4 thru 6 of this module have been skipped. + +### Deep Requires Now Deprecated + +`uuid@3` encouraged the use of deep requires to minimize the bundle size of browser builds: + +```javascript +const uuidv4 = require('uuid/v4'); // <== NOW DEPRECATED! +uuidv4(); +``` + +As of `uuid@7` this library now provides ECMAScript modules builds, which allow packagers like Webpack and Rollup to do "tree-shaking" to remove dead code. Instead, use the `import` syntax: + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); +``` + +... or for CommonJS: + +```javascript +const { v4: uuidv4 } = require('uuid'); +uuidv4(); +``` + +### Default Export Removed + +`uuid@3` was exporting the Version 4 UUID method as a default export: + +```javascript +const uuid = require('uuid'); // <== REMOVED! +``` + +This usage pattern was already discouraged in `uuid@3` and has been removed in `uuid@7`. + +--- + +Markdown generated from [README_js.md](README_js.md) by diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/bin/uuid b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/bin/uuid new file mode 100644 index 0000000000000000000000000000000000000000..f38d2ee19e7d3597c8a3fc18cb275c5028164b1f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/bin/uuid @@ -0,0 +1,2 @@ +#!/usr/bin/env node +require('../uuid-bin'); diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5586dd3d054861bcb4d30439ea14b6def606f57f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/index.js @@ -0,0 +1,79 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "NIL", { + enumerable: true, + get: function get() { + return _nil.default; + } +}); +Object.defineProperty(exports, "parse", { + enumerable: true, + get: function get() { + return _parse.default; + } +}); +Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function get() { + return _stringify.default; + } +}); +Object.defineProperty(exports, "v1", { + enumerable: true, + get: function get() { + return _v.default; + } +}); +Object.defineProperty(exports, "v3", { + enumerable: true, + get: function get() { + return _v2.default; + } +}); +Object.defineProperty(exports, "v4", { + enumerable: true, + get: function get() { + return _v3.default; + } +}); +Object.defineProperty(exports, "v5", { + enumerable: true, + get: function get() { + return _v4.default; + } +}); +Object.defineProperty(exports, "validate", { + enumerable: true, + get: function get() { + return _validate.default; + } +}); +Object.defineProperty(exports, "version", { + enumerable: true, + get: function get() { + return _version.default; + } +}); + +var _v = _interopRequireDefault(require("./v1.js")); + +var _v2 = _interopRequireDefault(require("./v3.js")); + +var _v3 = _interopRequireDefault(require("./v4.js")); + +var _v4 = _interopRequireDefault(require("./v5.js")); + +var _nil = _interopRequireDefault(require("./nil.js")); + +var _version = _interopRequireDefault(require("./version.js")); + +var _validate = _interopRequireDefault(require("./validate.js")); + +var _stringify = _interopRequireDefault(require("./stringify.js")); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/md5.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/md5.js new file mode 100644 index 0000000000000000000000000000000000000000..7a4582ace686897b291f71b50b1ac4cbe1744239 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/md5.js @@ -0,0 +1,223 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ +function md5(bytes) { + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = new Uint8Array(msg.length); + + for (let i = 0; i < msg.length; ++i) { + bytes[i] = msg.charCodeAt(i); + } + } + + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); +} +/* + * Convert an array of little-endian words to an array of bytes + */ + + +function md5ToHexEncodedArray(input) { + const output = []; + const length32 = input.length * 32; + const hexTab = '0123456789abcdef'; + + for (let i = 0; i < length32; i += 8) { + const x = input[i >> 5] >>> i % 32 & 0xff; + const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); + } + + return output; +} +/** + * Calculate output length with padding and bit length + */ + + +function getOutputLength(inputLength8) { + return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; +} +/* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + + +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[getOutputLength(len) - 1] = len; + let a = 1732584193; + let b = -271733879; + let c = -1732584194; + let d = 271733878; + + for (let i = 0; i < x.length; i += 16) { + const olda = a; + const oldb = b; + const oldc = c; + const oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + + return [a, b, c, d]; +} +/* + * Convert an array bytes to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ + + +function bytesToWords(input) { + if (input.length === 0) { + return []; + } + + const length8 = input.length * 8; + const output = new Uint32Array(getOutputLength(length8)); + + for (let i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } + + return output; +} +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + + +function safeAdd(x, y) { + const lsw = (x & 0xffff) + (y & 0xffff); + const msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; +} +/* + * Bitwise rotate a 32-bit number to the left. + */ + + +function bitRotateLeft(num, cnt) { + return num << cnt | num >>> 32 - cnt; +} +/* + * These functions implement the four basic operations the algorithm uses. + */ + + +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} + +function md5ff(a, b, c, d, x, s, t) { + return md5cmn(b & c | ~b & d, a, b, x, s, t); +} + +function md5gg(a, b, c, d, x, s, t) { + return md5cmn(b & d | c & ~d, a, b, x, s, t); +} + +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} + +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} + +var _default = md5; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/native.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/native.js new file mode 100644 index 0000000000000000000000000000000000000000..c2eea59d087389ab4a0f1be9ede38b7b2ba4595a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/native.js @@ -0,0 +1,11 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto); +var _default = { + randomUUID +}; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/nil.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/nil.js new file mode 100644 index 0000000000000000000000000000000000000000..7ade577b256b25919a4d06a8d432507daef8d3ed --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/nil.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = '00000000-0000-0000-0000-000000000000'; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/parse.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..4c69fc39e74c2e0858b85333753db64f58a1a5ac --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/parse.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function parse(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +var _default = parse; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/regex.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/regex.js new file mode 100644 index 0000000000000000000000000000000000000000..1ef91d64c80e220e599881771a9bd231879a538f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/regex.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/rng.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/rng.js new file mode 100644 index 0000000000000000000000000000000000000000..d067cdb04e4186ab517bb8c4eb48d76975d01303 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/rng.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rng; +// Unique ID creation requires a high quality random # generator. In the browser we therefore +// require the crypto API and do not support built-in fallback to lower quality random number +// generators (like Math.random()). +let getRandomValues; +const rnds8 = new Uint8Array(16); + +function rng() { + // lazy load so that environments that need to polyfill have a chance to do so + if (!getRandomValues) { + // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. + getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto); + + if (!getRandomValues) { + throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); + } + } + + return getRandomValues(rnds8); +} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/sha1.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/sha1.js new file mode 100644 index 0000000000000000000000000000000000000000..24cbcedca58c8ad42d50498a9ffa3241fc85c16a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/sha1.js @@ -0,0 +1,104 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; + + case 1: + return x ^ y ^ z; + + case 2: + return x & y ^ x & z ^ y & z; + + case 3: + return x ^ y ^ z; + } +} + +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} + +function sha1(bytes) { + const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = []; + + for (let i = 0; i < msg.length; ++i) { + bytes.push(msg.charCodeAt(i)); + } + } else if (!Array.isArray(bytes)) { + // Convert Array-like to Array + bytes = Array.prototype.slice.call(bytes); + } + + bytes.push(0x80); + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + + for (let i = 0; i < N; ++i) { + const arr = new Uint32Array(16); + + for (let j = 0; j < 16; ++j) { + arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; + } + + M[i] = arr; + } + + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; + + for (let i = 0; i < N; ++i) { + const W = new Uint32Array(80); + + for (let t = 0; t < 16; ++t) { + W[t] = M[i][t]; + } + + for (let t = 16; t < 80; ++t) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } + + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; +} + +var _default = sha1; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/stringify.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/stringify.js new file mode 100644 index 0000000000000000000000000000000000000000..390bf8918f4d42be870e23ff3da4ba2ed8d0d68d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/stringify.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +exports.unsafeStringify = unsafeStringify; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} + +function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; +} + +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!(0, _validate.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +var _default = stringify; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v1.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v1.js new file mode 100644 index 0000000000000000000000000000000000000000..125bc58f79fa0bd952c39bafd8949c69eaf3c780 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v1.js @@ -0,0 +1,107 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _stringify = require("./stringify.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || _rng.default)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || (0, _stringify.unsafeStringify)(b); +} + +var _default = v1; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v3.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v3.js new file mode 100644 index 0000000000000000000000000000000000000000..6b47ff517535a6d8c00d6afaff55b0332f825c9c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v3.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _md = _interopRequireDefault(require("./md5.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = v3; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v35.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v35.js new file mode 100644 index 0000000000000000000000000000000000000000..7c522d97a116ac03324325fc8d847ee628ed3cc8 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v35.js @@ -0,0 +1,80 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.URL = exports.DNS = void 0; +exports.default = v35; + +var _stringify = require("./stringify.js"); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.DNS = DNS; +const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = URL; + +function v35(name, version, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + var _namespace; + + if (typeof value === 'string') { + value = stringToBytes(value); + } + + if (typeof namespace === 'string') { + namespace = (0, _parse.default)(namespace); + } + + if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return (0, _stringify.unsafeStringify)(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v4.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v4.js new file mode 100644 index 0000000000000000000000000000000000000000..959d69869035ef028def85484d20834673804c8a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v4.js @@ -0,0 +1,43 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _native = _interopRequireDefault(require("./native.js")); + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _stringify = require("./stringify.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function v4(options, buf, offset) { + if (_native.default.randomUUID && !buf && !options) { + return _native.default.randomUUID(); + } + + options = options || {}; + + const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return (0, _stringify.unsafeStringify)(rnds); +} + +var _default = v4; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v5.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v5.js new file mode 100644 index 0000000000000000000000000000000000000000..99d615e096c5e176d7a97cb25f17862a317a970d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/v5.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _sha = _interopRequireDefault(require("./sha1.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = v5; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/validate.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/validate.js new file mode 100644 index 0000000000000000000000000000000000000000..fd052157d4400d572c97905c9b077a8b26dff0d5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/validate.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _regex = _interopRequireDefault(require("./regex.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function validate(uuid) { + return typeof uuid === 'string' && _regex.default.test(uuid); +} + +var _default = validate; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/version.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/version.js new file mode 100644 index 0000000000000000000000000000000000000000..f63af01ad44a4433ed1240abd2cc318ef28b47b6 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/commonjs-browser/version.js @@ -0,0 +1,21 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function version(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.slice(14, 15), 16); +} + +var _default = version; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1db6f6d25b2b6a79d6c650cac2fad395408e1ac2 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/index.js @@ -0,0 +1,9 @@ +export { default as v1 } from './v1.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as NIL } from './nil.js'; +export { default as version } from './version.js'; +export { default as validate } from './validate.js'; +export { default as stringify } from './stringify.js'; +export { default as parse } from './parse.js'; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/md5.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/md5.js new file mode 100644 index 0000000000000000000000000000000000000000..f12212ea3d678e87ae64809b79bbbd98c23e6f50 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/md5.js @@ -0,0 +1,215 @@ +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ +function md5(bytes) { + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = new Uint8Array(msg.length); + + for (let i = 0; i < msg.length; ++i) { + bytes[i] = msg.charCodeAt(i); + } + } + + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); +} +/* + * Convert an array of little-endian words to an array of bytes + */ + + +function md5ToHexEncodedArray(input) { + const output = []; + const length32 = input.length * 32; + const hexTab = '0123456789abcdef'; + + for (let i = 0; i < length32; i += 8) { + const x = input[i >> 5] >>> i % 32 & 0xff; + const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); + } + + return output; +} +/** + * Calculate output length with padding and bit length + */ + + +function getOutputLength(inputLength8) { + return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; +} +/* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + + +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[getOutputLength(len) - 1] = len; + let a = 1732584193; + let b = -271733879; + let c = -1732584194; + let d = 271733878; + + for (let i = 0; i < x.length; i += 16) { + const olda = a; + const oldb = b; + const oldc = c; + const oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + + return [a, b, c, d]; +} +/* + * Convert an array bytes to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ + + +function bytesToWords(input) { + if (input.length === 0) { + return []; + } + + const length8 = input.length * 8; + const output = new Uint32Array(getOutputLength(length8)); + + for (let i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } + + return output; +} +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + + +function safeAdd(x, y) { + const lsw = (x & 0xffff) + (y & 0xffff); + const msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; +} +/* + * Bitwise rotate a 32-bit number to the left. + */ + + +function bitRotateLeft(num, cnt) { + return num << cnt | num >>> 32 - cnt; +} +/* + * These functions implement the four basic operations the algorithm uses. + */ + + +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} + +function md5ff(a, b, c, d, x, s, t) { + return md5cmn(b & c | ~b & d, a, b, x, s, t); +} + +function md5gg(a, b, c, d, x, s, t) { + return md5cmn(b & d | c & ~d, a, b, x, s, t); +} + +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} + +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} + +export default md5; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/native.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/native.js new file mode 100644 index 0000000000000000000000000000000000000000..b22292cd1068763ae15fe9e1dc495647cdb6fc2d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/native.js @@ -0,0 +1,4 @@ +const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto); +export default { + randomUUID +}; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/nil.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/nil.js new file mode 100644 index 0000000000000000000000000000000000000000..b36324c2aa3faa177230ac9916f02e5fff0a6cd3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/nil.js @@ -0,0 +1 @@ +export default '00000000-0000-0000-0000-000000000000'; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/parse.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..6421c5d5a08e42325718a2caad1f47154eff9de9 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/parse.js @@ -0,0 +1,35 @@ +import validate from './validate.js'; + +function parse(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +export default parse; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/regex.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/regex.js new file mode 100644 index 0000000000000000000000000000000000000000..3da8673a5cdf3c408c8ae00fad6aed9777d2ae69 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/regex.js @@ -0,0 +1 @@ +export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/rng.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/rng.js new file mode 100644 index 0000000000000000000000000000000000000000..6e652346d42fbfa5194e33196336372799c568cd --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/rng.js @@ -0,0 +1,18 @@ +// Unique ID creation requires a high quality random # generator. In the browser we therefore +// require the crypto API and do not support built-in fallback to lower quality random number +// generators (like Math.random()). +let getRandomValues; +const rnds8 = new Uint8Array(16); +export default function rng() { + // lazy load so that environments that need to polyfill have a chance to do so + if (!getRandomValues) { + // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. + getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto); + + if (!getRandomValues) { + throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); + } + } + + return getRandomValues(rnds8); +} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/sha1.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/sha1.js new file mode 100644 index 0000000000000000000000000000000000000000..d3c25659a79ac408f2ceb0da0a919ddebd0a93eb --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/sha1.js @@ -0,0 +1,96 @@ +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; + + case 1: + return x ^ y ^ z; + + case 2: + return x & y ^ x & z ^ y & z; + + case 3: + return x ^ y ^ z; + } +} + +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} + +function sha1(bytes) { + const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = []; + + for (let i = 0; i < msg.length; ++i) { + bytes.push(msg.charCodeAt(i)); + } + } else if (!Array.isArray(bytes)) { + // Convert Array-like to Array + bytes = Array.prototype.slice.call(bytes); + } + + bytes.push(0x80); + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + + for (let i = 0; i < N; ++i) { + const arr = new Uint32Array(16); + + for (let j = 0; j < 16; ++j) { + arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; + } + + M[i] = arr; + } + + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; + + for (let i = 0; i < N; ++i) { + const W = new Uint32Array(80); + + for (let t = 0; t < 16; ++t) { + W[t] = M[i][t]; + } + + for (let t = 16; t < 80; ++t) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } + + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; +} + +export default sha1; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/stringify.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/stringify.js new file mode 100644 index 0000000000000000000000000000000000000000..a6e4c8864ddaf1a1bd9f36839a7975bef7822698 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/stringify.js @@ -0,0 +1,33 @@ +import validate from './validate.js'; +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ + +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} + +export function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; +} + +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!validate(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +export default stringify; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v1.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v1.js new file mode 100644 index 0000000000000000000000000000000000000000..382e5d795e1aea61202b73dbc0827b259c4b1237 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v1.js @@ -0,0 +1,95 @@ +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; // **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html + +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || rng)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || unsafeStringify(b); +} + +export default v1; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v3.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v3.js new file mode 100644 index 0000000000000000000000000000000000000000..09063b860499e6a7cf4b374be124df5dded05457 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v3.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import md5 from './md5.js'; +const v3 = v35('v3', 0x30, md5); +export default v3; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v35.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v35.js new file mode 100644 index 0000000000000000000000000000000000000000..3355e1f55ca218503a7246ac411d38847718768c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v35.js @@ -0,0 +1,66 @@ +import { unsafeStringify } from './stringify.js'; +import parse from './parse.js'; + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +export const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +export const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +export default function v35(name, version, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + var _namespace; + + if (typeof value === 'string') { + value = stringToBytes(value); + } + + if (typeof namespace === 'string') { + namespace = parse(namespace); + } + + if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return unsafeStringify(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v4.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v4.js new file mode 100644 index 0000000000000000000000000000000000000000..95ea87991ea56d596b4612d4d063f45906b13c12 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v4.js @@ -0,0 +1,29 @@ +import native from './native.js'; +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; + +function v4(options, buf, offset) { + if (native.randomUUID && !buf && !options) { + return native.randomUUID(); + } + + options = options || {}; + const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return unsafeStringify(rnds); +} + +export default v4; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v5.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v5.js new file mode 100644 index 0000000000000000000000000000000000000000..e87fe317d70a00942dd870c8c1c9155b517aa957 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/v5.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import sha1 from './sha1.js'; +const v5 = v35('v5', 0x50, sha1); +export default v5; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/validate.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/validate.js new file mode 100644 index 0000000000000000000000000000000000000000..f1cdc7af49bcfc2a66fb1efb3532095e85ce8415 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/validate.js @@ -0,0 +1,7 @@ +import REGEX from './regex.js'; + +function validate(uuid) { + return typeof uuid === 'string' && REGEX.test(uuid); +} + +export default validate; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/version.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/version.js new file mode 100644 index 0000000000000000000000000000000000000000..936307630f5ddb07ffdb28e5d343ae12f5e84026 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-browser/version.js @@ -0,0 +1,11 @@ +import validate from './validate.js'; + +function version(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.slice(14, 15), 16); +} + +export default version; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1db6f6d25b2b6a79d6c650cac2fad395408e1ac2 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/index.js @@ -0,0 +1,9 @@ +export { default as v1 } from './v1.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as NIL } from './nil.js'; +export { default as version } from './version.js'; +export { default as validate } from './validate.js'; +export { default as stringify } from './stringify.js'; +export { default as parse } from './parse.js'; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/md5.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/md5.js new file mode 100644 index 0000000000000000000000000000000000000000..4d68b040f6c192f73ccbf8d724a19b196fca0de1 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/md5.js @@ -0,0 +1,13 @@ +import crypto from 'crypto'; + +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return crypto.createHash('md5').update(bytes).digest(); +} + +export default md5; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/native.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/native.js new file mode 100644 index 0000000000000000000000000000000000000000..f0d1992614bb9acf0470614818f05340647f9c04 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/native.js @@ -0,0 +1,4 @@ +import crypto from 'crypto'; +export default { + randomUUID: crypto.randomUUID +}; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/nil.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/nil.js new file mode 100644 index 0000000000000000000000000000000000000000..b36324c2aa3faa177230ac9916f02e5fff0a6cd3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/nil.js @@ -0,0 +1 @@ +export default '00000000-0000-0000-0000-000000000000'; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/parse.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..6421c5d5a08e42325718a2caad1f47154eff9de9 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/parse.js @@ -0,0 +1,35 @@ +import validate from './validate.js'; + +function parse(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +export default parse; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/regex.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/regex.js new file mode 100644 index 0000000000000000000000000000000000000000..3da8673a5cdf3c408c8ae00fad6aed9777d2ae69 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/regex.js @@ -0,0 +1 @@ +export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/rng.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/rng.js new file mode 100644 index 0000000000000000000000000000000000000000..80062449a297eb936b592ee631bcec8f273256c9 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/rng.js @@ -0,0 +1,12 @@ +import crypto from 'crypto'; +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate + +let poolPtr = rnds8Pool.length; +export default function rng() { + if (poolPtr > rnds8Pool.length - 16) { + crypto.randomFillSync(rnds8Pool); + poolPtr = 0; + } + + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/sha1.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/sha1.js new file mode 100644 index 0000000000000000000000000000000000000000..e23850b441a0c0d52d0d0aa75ed49cf0b88cd72b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/sha1.js @@ -0,0 +1,13 @@ +import crypto from 'crypto'; + +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return crypto.createHash('sha1').update(bytes).digest(); +} + +export default sha1; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/stringify.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/stringify.js new file mode 100644 index 0000000000000000000000000000000000000000..a6e4c8864ddaf1a1bd9f36839a7975bef7822698 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/stringify.js @@ -0,0 +1,33 @@ +import validate from './validate.js'; +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ + +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} + +export function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; +} + +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!validate(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +export default stringify; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v1.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v1.js new file mode 100644 index 0000000000000000000000000000000000000000..382e5d795e1aea61202b73dbc0827b259c4b1237 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v1.js @@ -0,0 +1,95 @@ +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; // **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html + +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || rng)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || unsafeStringify(b); +} + +export default v1; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v3.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v3.js new file mode 100644 index 0000000000000000000000000000000000000000..09063b860499e6a7cf4b374be124df5dded05457 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v3.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import md5 from './md5.js'; +const v3 = v35('v3', 0x30, md5); +export default v3; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v35.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v35.js new file mode 100644 index 0000000000000000000000000000000000000000..3355e1f55ca218503a7246ac411d38847718768c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v35.js @@ -0,0 +1,66 @@ +import { unsafeStringify } from './stringify.js'; +import parse from './parse.js'; + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +export const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +export const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +export default function v35(name, version, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + var _namespace; + + if (typeof value === 'string') { + value = stringToBytes(value); + } + + if (typeof namespace === 'string') { + namespace = parse(namespace); + } + + if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return unsafeStringify(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v4.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v4.js new file mode 100644 index 0000000000000000000000000000000000000000..95ea87991ea56d596b4612d4d063f45906b13c12 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v4.js @@ -0,0 +1,29 @@ +import native from './native.js'; +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; + +function v4(options, buf, offset) { + if (native.randomUUID && !buf && !options) { + return native.randomUUID(); + } + + options = options || {}; + const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return unsafeStringify(rnds); +} + +export default v4; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v5.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v5.js new file mode 100644 index 0000000000000000000000000000000000000000..e87fe317d70a00942dd870c8c1c9155b517aa957 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/v5.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import sha1 from './sha1.js'; +const v5 = v35('v5', 0x50, sha1); +export default v5; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/validate.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/validate.js new file mode 100644 index 0000000000000000000000000000000000000000..f1cdc7af49bcfc2a66fb1efb3532095e85ce8415 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/validate.js @@ -0,0 +1,7 @@ +import REGEX from './regex.js'; + +function validate(uuid) { + return typeof uuid === 'string' && REGEX.test(uuid); +} + +export default validate; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/version.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/version.js new file mode 100644 index 0000000000000000000000000000000000000000..936307630f5ddb07ffdb28e5d343ae12f5e84026 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/esm-node/version.js @@ -0,0 +1,11 @@ +import validate from './validate.js'; + +function version(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.slice(14, 15), 16); +} + +export default version; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..88d676a296c72340af4b11006eb2a9e0ab153338 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/index.js @@ -0,0 +1,79 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "NIL", { + enumerable: true, + get: function () { + return _nil.default; + } +}); +Object.defineProperty(exports, "parse", { + enumerable: true, + get: function () { + return _parse.default; + } +}); +Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function () { + return _stringify.default; + } +}); +Object.defineProperty(exports, "v1", { + enumerable: true, + get: function () { + return _v.default; + } +}); +Object.defineProperty(exports, "v3", { + enumerable: true, + get: function () { + return _v2.default; + } +}); +Object.defineProperty(exports, "v4", { + enumerable: true, + get: function () { + return _v3.default; + } +}); +Object.defineProperty(exports, "v5", { + enumerable: true, + get: function () { + return _v4.default; + } +}); +Object.defineProperty(exports, "validate", { + enumerable: true, + get: function () { + return _validate.default; + } +}); +Object.defineProperty(exports, "version", { + enumerable: true, + get: function () { + return _version.default; + } +}); + +var _v = _interopRequireDefault(require("./v1.js")); + +var _v2 = _interopRequireDefault(require("./v3.js")); + +var _v3 = _interopRequireDefault(require("./v4.js")); + +var _v4 = _interopRequireDefault(require("./v5.js")); + +var _nil = _interopRequireDefault(require("./nil.js")); + +var _version = _interopRequireDefault(require("./version.js")); + +var _validate = _interopRequireDefault(require("./validate.js")); + +var _stringify = _interopRequireDefault(require("./stringify.js")); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/md5-browser.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/md5-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..7a4582ace686897b291f71b50b1ac4cbe1744239 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/md5-browser.js @@ -0,0 +1,223 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ +function md5(bytes) { + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = new Uint8Array(msg.length); + + for (let i = 0; i < msg.length; ++i) { + bytes[i] = msg.charCodeAt(i); + } + } + + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); +} +/* + * Convert an array of little-endian words to an array of bytes + */ + + +function md5ToHexEncodedArray(input) { + const output = []; + const length32 = input.length * 32; + const hexTab = '0123456789abcdef'; + + for (let i = 0; i < length32; i += 8) { + const x = input[i >> 5] >>> i % 32 & 0xff; + const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); + } + + return output; +} +/** + * Calculate output length with padding and bit length + */ + + +function getOutputLength(inputLength8) { + return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; +} +/* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + + +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[getOutputLength(len) - 1] = len; + let a = 1732584193; + let b = -271733879; + let c = -1732584194; + let d = 271733878; + + for (let i = 0; i < x.length; i += 16) { + const olda = a; + const oldb = b; + const oldc = c; + const oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + + return [a, b, c, d]; +} +/* + * Convert an array bytes to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ + + +function bytesToWords(input) { + if (input.length === 0) { + return []; + } + + const length8 = input.length * 8; + const output = new Uint32Array(getOutputLength(length8)); + + for (let i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } + + return output; +} +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + + +function safeAdd(x, y) { + const lsw = (x & 0xffff) + (y & 0xffff); + const msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; +} +/* + * Bitwise rotate a 32-bit number to the left. + */ + + +function bitRotateLeft(num, cnt) { + return num << cnt | num >>> 32 - cnt; +} +/* + * These functions implement the four basic operations the algorithm uses. + */ + + +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} + +function md5ff(a, b, c, d, x, s, t) { + return md5cmn(b & c | ~b & d, a, b, x, s, t); +} + +function md5gg(a, b, c, d, x, s, t) { + return md5cmn(b & d | c & ~d, a, b, x, s, t); +} + +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} + +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} + +var _default = md5; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/md5.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/md5.js new file mode 100644 index 0000000000000000000000000000000000000000..824d48167a980e1ea70732421b05f66c8622a12f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/md5.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return _crypto.default.createHash('md5').update(bytes).digest(); +} + +var _default = md5; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/native-browser.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/native-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..c2eea59d087389ab4a0f1be9ede38b7b2ba4595a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/native-browser.js @@ -0,0 +1,11 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto); +var _default = { + randomUUID +}; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/native.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/native.js new file mode 100644 index 0000000000000000000000000000000000000000..de80469138d0df75c2f8886e69841a5bbc3e5e1f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/native.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var _default = { + randomUUID: _crypto.default.randomUUID +}; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/nil.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/nil.js new file mode 100644 index 0000000000000000000000000000000000000000..7ade577b256b25919a4d06a8d432507daef8d3ed --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/nil.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = '00000000-0000-0000-0000-000000000000'; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/parse.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..4c69fc39e74c2e0858b85333753db64f58a1a5ac --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/parse.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function parse(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +var _default = parse; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/regex.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/regex.js new file mode 100644 index 0000000000000000000000000000000000000000..1ef91d64c80e220e599881771a9bd231879a538f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/regex.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/rng-browser.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/rng-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..d067cdb04e4186ab517bb8c4eb48d76975d01303 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/rng-browser.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rng; +// Unique ID creation requires a high quality random # generator. In the browser we therefore +// require the crypto API and do not support built-in fallback to lower quality random number +// generators (like Math.random()). +let getRandomValues; +const rnds8 = new Uint8Array(16); + +function rng() { + // lazy load so that environments that need to polyfill have a chance to do so + if (!getRandomValues) { + // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. + getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto); + + if (!getRandomValues) { + throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); + } + } + + return getRandomValues(rnds8); +} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/rng.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/rng.js new file mode 100644 index 0000000000000000000000000000000000000000..3507f93772a910b44fffb4df2f0e7daeed6586ae --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/rng.js @@ -0,0 +1,24 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rng; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate + +let poolPtr = rnds8Pool.length; + +function rng() { + if (poolPtr > rnds8Pool.length - 16) { + _crypto.default.randomFillSync(rnds8Pool); + + poolPtr = 0; + } + + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/sha1-browser.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/sha1-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..24cbcedca58c8ad42d50498a9ffa3241fc85c16a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/sha1-browser.js @@ -0,0 +1,104 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; + + case 1: + return x ^ y ^ z; + + case 2: + return x & y ^ x & z ^ y & z; + + case 3: + return x ^ y ^ z; + } +} + +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} + +function sha1(bytes) { + const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = []; + + for (let i = 0; i < msg.length; ++i) { + bytes.push(msg.charCodeAt(i)); + } + } else if (!Array.isArray(bytes)) { + // Convert Array-like to Array + bytes = Array.prototype.slice.call(bytes); + } + + bytes.push(0x80); + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + + for (let i = 0; i < N; ++i) { + const arr = new Uint32Array(16); + + for (let j = 0; j < 16; ++j) { + arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; + } + + M[i] = arr; + } + + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; + + for (let i = 0; i < N; ++i) { + const W = new Uint32Array(80); + + for (let t = 0; t < 16; ++t) { + W[t] = M[i][t]; + } + + for (let t = 16; t < 80; ++t) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } + + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; +} + +var _default = sha1; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/sha1.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/sha1.js new file mode 100644 index 0000000000000000000000000000000000000000..03bdd63cedadafd8dd4ef2c2d186f89826cf80b0 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/sha1.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return _crypto.default.createHash('sha1').update(bytes).digest(); +} + +var _default = sha1; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/stringify.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/stringify.js new file mode 100644 index 0000000000000000000000000000000000000000..390bf8918f4d42be870e23ff3da4ba2ed8d0d68d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/stringify.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +exports.unsafeStringify = unsafeStringify; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} + +function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; +} + +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!(0, _validate.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +var _default = stringify; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/uuid-bin.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/uuid-bin.js new file mode 100644 index 0000000000000000000000000000000000000000..50a7a9f17a065c7d2a409327643f41dee6f4136c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/uuid-bin.js @@ -0,0 +1,85 @@ +"use strict"; + +var _assert = _interopRequireDefault(require("assert")); + +var _v = _interopRequireDefault(require("./v1.js")); + +var _v2 = _interopRequireDefault(require("./v3.js")); + +var _v3 = _interopRequireDefault(require("./v4.js")); + +var _v4 = _interopRequireDefault(require("./v5.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function usage() { + console.log('Usage:'); + console.log(' uuid'); + console.log(' uuid v1'); + console.log(' uuid v3 '); + console.log(' uuid v4'); + console.log(' uuid v5 '); + console.log(' uuid --help'); + console.log('\nNote: may be "URL" or "DNS" to use the corresponding UUIDs defined by RFC4122'); +} + +const args = process.argv.slice(2); + +if (args.indexOf('--help') >= 0) { + usage(); + process.exit(0); +} + +const version = args.shift() || 'v4'; + +switch (version) { + case 'v1': + console.log((0, _v.default)()); + break; + + case 'v3': + { + const name = args.shift(); + let namespace = args.shift(); + (0, _assert.default)(name != null, 'v3 name not specified'); + (0, _assert.default)(namespace != null, 'v3 namespace not specified'); + + if (namespace === 'URL') { + namespace = _v2.default.URL; + } + + if (namespace === 'DNS') { + namespace = _v2.default.DNS; + } + + console.log((0, _v2.default)(name, namespace)); + break; + } + + case 'v4': + console.log((0, _v3.default)()); + break; + + case 'v5': + { + const name = args.shift(); + let namespace = args.shift(); + (0, _assert.default)(name != null, 'v5 name not specified'); + (0, _assert.default)(namespace != null, 'v5 namespace not specified'); + + if (namespace === 'URL') { + namespace = _v4.default.URL; + } + + if (namespace === 'DNS') { + namespace = _v4.default.DNS; + } + + console.log((0, _v4.default)(name, namespace)); + break; + } + + default: + usage(); + process.exit(1); +} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/v1.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/v1.js new file mode 100644 index 0000000000000000000000000000000000000000..125bc58f79fa0bd952c39bafd8949c69eaf3c780 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/v1.js @@ -0,0 +1,107 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _stringify = require("./stringify.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || _rng.default)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || (0, _stringify.unsafeStringify)(b); +} + +var _default = v1; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/v3.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/v3.js new file mode 100644 index 0000000000000000000000000000000000000000..6b47ff517535a6d8c00d6afaff55b0332f825c9c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/v3.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _md = _interopRequireDefault(require("./md5.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = v3; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/v35.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/v35.js new file mode 100644 index 0000000000000000000000000000000000000000..7c522d97a116ac03324325fc8d847ee628ed3cc8 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/v35.js @@ -0,0 +1,80 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.URL = exports.DNS = void 0; +exports.default = v35; + +var _stringify = require("./stringify.js"); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.DNS = DNS; +const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = URL; + +function v35(name, version, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + var _namespace; + + if (typeof value === 'string') { + value = stringToBytes(value); + } + + if (typeof namespace === 'string') { + namespace = (0, _parse.default)(namespace); + } + + if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return (0, _stringify.unsafeStringify)(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/v4.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/v4.js new file mode 100644 index 0000000000000000000000000000000000000000..959d69869035ef028def85484d20834673804c8a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/v4.js @@ -0,0 +1,43 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _native = _interopRequireDefault(require("./native.js")); + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _stringify = require("./stringify.js"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function v4(options, buf, offset) { + if (_native.default.randomUUID && !buf && !options) { + return _native.default.randomUUID(); + } + + options = options || {}; + + const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return (0, _stringify.unsafeStringify)(rnds); +} + +var _default = v4; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/v5.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/v5.js new file mode 100644 index 0000000000000000000000000000000000000000..99d615e096c5e176d7a97cb25f17862a317a970d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/v5.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _sha = _interopRequireDefault(require("./sha1.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = v5; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/validate.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/validate.js new file mode 100644 index 0000000000000000000000000000000000000000..fd052157d4400d572c97905c9b077a8b26dff0d5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/validate.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _regex = _interopRequireDefault(require("./regex.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function validate(uuid) { + return typeof uuid === 'string' && _regex.default.test(uuid); +} + +var _default = validate; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/version.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/version.js new file mode 100644 index 0000000000000000000000000000000000000000..f63af01ad44a4433ed1240abd2cc318ef28b47b6 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/dist/version.js @@ -0,0 +1,21 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function version(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.slice(14, 15), 16); +} + +var _default = version; +exports.default = _default; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6cc33618cba37b0fbd4d65b40db9622543163a27 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/package.json @@ -0,0 +1,135 @@ +{ + "name": "uuid", + "version": "9.0.1", + "description": "RFC4122 (v1, v4, and v5) UUIDs", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "commitlint": { + "extends": [ + "@commitlint/config-conventional" + ] + }, + "keywords": [ + "uuid", + "guid", + "rfc4122" + ], + "license": "MIT", + "bin": { + "uuid": "./dist/bin/uuid" + }, + "sideEffects": false, + "main": "./dist/index.js", + "exports": { + ".": { + "node": { + "module": "./dist/esm-node/index.js", + "require": "./dist/index.js", + "import": "./wrapper.mjs" + }, + "browser": { + "import": "./dist/esm-browser/index.js", + "require": "./dist/commonjs-browser/index.js" + }, + "default": "./dist/esm-browser/index.js" + }, + "./package.json": "./package.json" + }, + "module": "./dist/esm-node/index.js", + "browser": { + "./dist/md5.js": "./dist/md5-browser.js", + "./dist/native.js": "./dist/native-browser.js", + "./dist/rng.js": "./dist/rng-browser.js", + "./dist/sha1.js": "./dist/sha1-browser.js", + "./dist/esm-node/index.js": "./dist/esm-browser/index.js" + }, + "files": [ + "CHANGELOG.md", + "CONTRIBUTING.md", + "LICENSE.md", + "README.md", + "dist", + "wrapper.mjs" + ], + "devDependencies": { + "@babel/cli": "7.18.10", + "@babel/core": "7.18.10", + "@babel/eslint-parser": "7.18.9", + "@babel/preset-env": "7.18.10", + "@commitlint/cli": "17.0.3", + "@commitlint/config-conventional": "17.0.3", + "bundlewatch": "0.3.3", + "eslint": "8.21.0", + "eslint-config-prettier": "8.5.0", + "eslint-config-standard": "17.0.0", + "eslint-plugin-import": "2.26.0", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-prettier": "4.2.1", + "eslint-plugin-promise": "6.0.0", + "husky": "8.0.1", + "jest": "28.1.3", + "lint-staged": "13.0.3", + "npm-run-all": "4.1.5", + "optional-dev-dependency": "2.0.1", + "prettier": "2.7.1", + "random-seed": "0.3.0", + "runmd": "1.3.9", + "standard-version": "9.5.0" + }, + "optionalDevDependencies": { + "@wdio/browserstack-service": "7.16.10", + "@wdio/cli": "7.16.10", + "@wdio/jasmine-framework": "7.16.6", + "@wdio/local-runner": "7.16.10", + "@wdio/spec-reporter": "7.16.9", + "@wdio/static-server-service": "7.16.6" + }, + "scripts": { + "examples:browser:webpack:build": "cd examples/browser-webpack && npm install && npm run build", + "examples:browser:rollup:build": "cd examples/browser-rollup && npm install && npm run build", + "examples:node:commonjs:test": "cd examples/node-commonjs && npm install && npm test", + "examples:node:esmodules:test": "cd examples/node-esmodules && npm install && npm test", + "examples:node:jest:test": "cd examples/node-jest && npm install && npm test", + "prepare": "cd $( git rev-parse --show-toplevel ) && husky install", + "lint": "npm run eslint:check && npm run prettier:check", + "eslint:check": "eslint src/ test/ examples/ *.js", + "eslint:fix": "eslint --fix src/ test/ examples/ *.js", + "pretest": "[ -n $CI ] || npm run build", + "test": "BABEL_ENV=commonjsNode node --throw-deprecation node_modules/.bin/jest test/unit/", + "pretest:browser": "optional-dev-dependency && npm run build && npm-run-all --parallel examples:browser:**", + "test:browser": "wdio run ./wdio.conf.js", + "pretest:node": "npm run build", + "test:node": "npm-run-all --parallel examples:node:**", + "test:pack": "./scripts/testpack.sh", + "pretest:benchmark": "npm run build", + "test:benchmark": "cd examples/benchmark && npm install && npm test", + "prettier:check": "prettier --check '**/*.{js,jsx,json,md}'", + "prettier:fix": "prettier --write '**/*.{js,jsx,json,md}'", + "bundlewatch": "npm run pretest:browser && bundlewatch --config bundlewatch.config.json", + "md": "runmd --watch --output=README.md README_js.md", + "docs": "( node --version | grep -q 'v18' ) && ( npm run build && npx runmd --output=README.md README_js.md )", + "docs:diff": "npm run docs && git diff --quiet README.md", + "build": "./scripts/build.sh", + "prepack": "npm run build", + "release": "standard-version --no-verify" + }, + "repository": { + "type": "git", + "url": "https://github.com/uuidjs/uuid.git" + }, + "lint-staged": { + "*.{js,jsx,json,md}": [ + "prettier --write" + ], + "*.{js,jsx}": [ + "eslint --fix" + ] + }, + "standard-version": { + "scripts": { + "postchangelog": "prettier --write CHANGELOG.md" + } + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/wrapper.mjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/wrapper.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c31e9cef45e2b96a11ded81ac2170391022dc2f6 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/node_modules/uuid/wrapper.mjs @@ -0,0 +1,10 @@ +import uuid from './dist/index.js'; +export const v1 = uuid.v1; +export const v3 = uuid.v3; +export const v4 = uuid.v4; +export const v5 = uuid.v5; +export const NIL = uuid.NIL; +export const version = uuid.version; +export const validate = uuid.validate; +export const stringify = uuid.stringify; +export const parse = uuid.parse; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6b921a7c805aae4907aa707809bccce7cfd9a709 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/package.json @@ -0,0 +1,129 @@ +{ + "name": "@google/genai", + "version": "1.15.0", + "description": "", + "type": "module", + "main": "dist/node/index.mjs", + "module": "dist/web/index.mjs", + "browser": "dist/web/index.mjs", + "typings": "dist/genai.d.ts", + "exports": { + ".": { + "browser": { + "types": "./dist/web/web.d.ts", + "import": "./dist/web/index.mjs", + "default": "./dist/web/index.mjs" + }, + "node": { + "types": "./dist/node/node.d.ts", + "import": "./dist/node/index.mjs", + "require": "./dist/node/index.cjs", + "default": "./dist/node/index.mjs" + }, + "types": "./dist/genai.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.cjs", + "default": "./dist/index.mjs" + }, + "./web": { + "types": "./dist/web/web.d.ts", + "import": "./dist/web/index.mjs", + "default": "./dist/web/index.mjs" + }, + "./node": { + "types": "./dist/node/node.d.ts", + "import": "./dist/node/index.mjs", + "default": "./dist/node/index.mjs" + } + }, + "scripts": { + "prepare": "npm run build-prod", + "build": "rollup -c && npm-run-all --parallel api-extractor:dev:* && node scripts/ignore_missing_mcp_dep.js", + "build-prod": "rollup -c && npm-run-all --parallel api-extractor:prod:* && node scripts/ignore_missing_mcp_dep.js", + "api-extractor:dev:main": "api-extractor run --local --verbose", + "api-extractor:dev:node": "api-extractor run -c api-extractor.node.json --local --verbose", + "api-extractor:dev:web": "api-extractor run -c api-extractor.web.json --local --verbose", + "api-extractor:prod:main": "api-extractor run --verbose", + "api-extractor:prod:node": "api-extractor run -c api-extractor.node.json --verbose", + "api-extractor:prod:web": "api-extractor run -c api-extractor.web.json --verbose", + "unit-test": "tsc && jasmine dist/test/unit/**/*_test.js dist/test/unit/*_test.js", + "system-test": "tsc && jasmine dist/test/system/**/*_test.js", + "test-server-tests": "tsc && GOOGLE_CLOUD_PROJECT=googcloudproj GOOGLE_CLOUD_LOCATION=googcloudloc jasmine dist/test/system/node/*_test.js -- --test-server", + "test-server-tests:record": "tsc && jasmine --fail-fast dist/test/system/node/*_test.js -- --test-server --record", + "docs": "typedoc && node --loader ts-node/esm scripts/add_docsite_license_headers.ts", + "pages-main": "node --loader ts-node/esm scripts/generate_pages.ts main", + "pages-release": "node --loader ts-node/esm scripts/generate_pages.ts release", + "format": "prettier '**/*.ts' '**/*.mjs' '**/*.json' --write", + "lint": "eslint '**/*.ts'", + "lint-fix": "eslint --fix '**/*.ts'", + "coverage-report": "./test/generate_report.sh" + }, + "engines": { + "node": ">=20.0.0" + }, + "files": [ + "dist/genai.d.ts", + "dist/index.mjs", + "dist/index.cjs", + "dist/index.mjs.map", + "dist/node/index.mjs", + "dist/node/index.cjs", + "dist/node/index.mjs.map", + "dist/node/node.d.ts", + "dist/web/index.mjs", + "dist/web/index.mjs.map", + "dist/web/web.d.ts", + "node/package.json", + "web/package.json" + ], + "devDependencies": { + "@eslint/js": "9.20.0", + "@microsoft/api-extractor": "^7.52.9", + "@rollup/plugin-json": "^6.1.0", + "@types/jasmine": "^5.1.2", + "@types/node": "^20.9.0", + "@types/unist": "^3.0.3", + "@types/ws": "^8.5.14", + "c8": "^10.1.3", + "eslint": "8.57.0", + "gts": "^5.2.0", + "jasmine": "^5.5.0", + "jasmine-reporters": "^2.4.0", + "npm-run-all": "^4.1.5", + "nyc": "^17.1.0", + "prettier": "3.3.3", + "prettier-plugin-organize-imports": "^4.1.0", + "rollup-plugin-typescript2": "^0.36.0", + "test-server-sdk": "^0.2.6", + "ts-node": "^10.9.2", + "tslib": "^2.8.1", + "tsx": "^4.19.4", + "typedoc": "^0.27.0", + "typescript": "~5.2.0", + "typescript-eslint": "8.24.1", + "zod": "^3.22.4", + "zod-to-json-schema": "^3.22.4" + }, + "dependencies": { + "google-auth-library": "^9.14.2", + "ws": "^8.18.0" + }, + "peerDependencies": { + "@modelcontextprotocol/sdk": "^1.11.0" + }, + "peerDependenciesMeta": { + "@modelcontextprotocol/sdk": { + "optional": true + } + }, + "repository": { + "type": "git", + "url": "https://github.com/googleapis/js-genai.git" + }, + "bugs": { + "url": "https://github.com/googleapis/js-genai/issues" + }, + "homepage": "https://github.com/googleapis/js-genai#readme", + "author": "", + "license": "Apache-2.0" +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/web/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/web/package.json new file mode 100644 index 0000000000000000000000000000000000000000..606dd1fa893dc854552e057f122276ea30da27ce --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@google/genai/web/package.json @@ -0,0 +1,4 @@ +{ + "name": "@google/genai/web", + "module": "../dist/web/index.mjs" +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/LICENSE.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..61ece8cc92afb41fdb1552ec1f72ac147b9eaceb --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/LICENSE.md @@ -0,0 +1,23 @@ +(MIT) + +Original code Copyright Julian Gruber + +Port to TypeScript Copyright Isaac Z. Schlueter + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/README.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ed10c70aab6f52ffef4df2d0a1c19412febb949e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/README.md @@ -0,0 +1,60 @@ +# @isaacs/balanced-match + +A hybrid CJS/ESM TypeScript fork of +[balanced-match](http://npm.im/balanced-match). + +Match balanced string pairs, like `{` and `}` or `` and ``. Supports regular expressions as well! + +[![CI](https://github.com/juliangruber/balanced-match/actions/workflows/ci.yml/badge.svg)](https://github.com/juliangruber/balanced-match/actions/workflows/ci.yml) +[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) + +## Example + +Get the first matching pair of braces: + +```js +import { balanced } from '@isaacs/balanced-match' + +console.log(balanced('{', '}', 'pre{in{nested}}post')) +console.log(balanced('{', '}', 'pre{first}between{second}post')) +console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')) +``` + +The matches are: + +```bash +$ node example.js +{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } +{ start: 3, + end: 9, + pre: 'pre', + body: 'first', + post: 'between{second}post' } +{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } +``` + +## API + +### const m = balanced(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +object with those keys: + +- **start** the index of the first match of `a` +- **end** the index of the matching `b` +- **pre** the preamble, `a` and `b` not included +- **body** the match, `a` and `b` not included +- **post** the postscript, `a` and `b` not included + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. + +### const r = balanced.range(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +array with indexes: `[ , ]`. + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f819cfd016012ff5607febb82aaab715244f8fab --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.d.ts @@ -0,0 +1,9 @@ +export declare const balanced: (a: string | RegExp, b: string | RegExp, str: string) => false | { + start: number; + end: number; + pre: string; + body: string; + post: string; +} | undefined; +export declare const range: (a: string, b: string, str: string) => undefined | [number, number]; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.d.ts.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..6306762c77d77b909214a5d7af014b2eb156bbb3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,QAAQ,GACnB,GAAG,MAAM,GAAG,MAAM,EAClB,GAAG,MAAM,GAAG,MAAM,EAClB,KAAK,MAAM;;;;;;aAgBZ,CAAA;AAOD,eAAO,MAAM,KAAK,GAChB,GAAG,MAAM,EACT,GAAG,MAAM,EACT,KAAK,MAAM,KACV,SAAS,GAAG,CAAC,MAAM,EAAE,MAAM,CA2C7B,CAAA"} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0c9014bac153187d5b0e3d1d214a5d1c71eefd32 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.js @@ -0,0 +1,59 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.range = exports.balanced = void 0; +const balanced = (a, b, str) => { + const ma = a instanceof RegExp ? maybeMatch(a, str) : a; + const mb = b instanceof RegExp ? maybeMatch(b, str) : b; + const r = ma !== null && mb != null && (0, exports.range)(ma, mb, str); + return (r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + ma.length, r[1]), + post: str.slice(r[1] + mb.length), + }); +}; +exports.balanced = balanced; +const maybeMatch = (reg, str) => { + const m = str.match(reg); + return m ? m[0] : null; +}; +const range = (a, b, str) => { + let begs, beg, left, right = undefined, result; + let ai = str.indexOf(a); + let bi = str.indexOf(b, ai + 1); + let i = ai; + if (ai >= 0 && bi > 0) { + if (a === b) { + return [ai, bi]; + } + begs = []; + left = str.length; + while (i >= 0 && !result) { + if (i === ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } + else if (begs.length === 1) { + const r = begs.pop(); + if (r !== undefined) + result = [r, bi]; + } + else { + beg = begs.pop(); + if (beg !== undefined && beg < left) { + left = beg; + right = bi; + } + bi = str.indexOf(b, i + 1); + } + i = ai < bi && ai >= 0 ? ai : bi; + } + if (begs.length && right !== undefined) { + result = [left, right]; + } + } + return result; +}; +exports.range = range; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.js.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..83f547ca9d33d5e0cc5a6e38b1dab4b9060a2bc7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAO,MAAM,QAAQ,GAAG,CACtB,CAAkB,EAClB,CAAkB,EAClB,GAAW,EACX,EAAE;IACF,MAAM,EAAE,GAAG,CAAC,YAAY,MAAM,CAAC,CAAC,CA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C,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAA;QAClC,CAAC;QAED,IAAI,IAAI,CAAC,MAAM,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACvC,MAAM,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;QACxB,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAA;AACf,CAAC,CAAA;AA/CY,QAAA,KAAK,SA+CjB","sourcesContent":["export const balanced = (\n a: string | RegExp,\n b: string | RegExp,\n str: string,\n) => {\n const ma = a instanceof RegExp ? maybeMatch(a, str) : a\n const mb = b instanceof RegExp ? maybeMatch(b, str) : b\n\n const r = ma !== null && mb != null && range(ma, mb, str)\n\n return (\n r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + ma.length, r[1]),\n post: str.slice(r[1] + mb.length),\n }\n )\n}\n\nconst maybeMatch = (reg: RegExp, str: string) => {\n const m = str.match(reg)\n return m ? m[0] : null\n}\n\nexport const range = (\n a: string,\n b: string,\n str: string,\n): undefined | [number, number] => {\n let begs: number[],\n beg: number | undefined,\n left: number,\n right: number | undefined = undefined,\n result: undefined | [number, number]\n let ai = str.indexOf(a)\n let bi = str.indexOf(b, ai + 1)\n let i = ai\n\n if (ai >= 0 && bi > 0) {\n if (a === b) {\n return [ai, bi]\n }\n begs = []\n left = str.length\n\n while (i >= 0 && !result) {\n if (i === ai) {\n begs.push(i)\n ai = str.indexOf(a, i + 1)\n } else if (begs.length === 1) {\n const r = begs.pop()\n if (r !== undefined) result = [r, bi]\n } else {\n beg = begs.pop()\n if (beg !== undefined && beg < left) {\n left = beg\n right = bi\n }\n\n bi = str.indexOf(b, i + 1)\n }\n\n i = ai < bi && ai >= 0 ? ai : bi\n }\n\n if (begs.length && right !== undefined) {\n result = [left, right]\n }\n }\n\n return result\n}\n"]} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5bbefffbabee392d1855491b84dc0a716b6a3bf2 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f819cfd016012ff5607febb82aaab715244f8fab --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.d.ts @@ -0,0 +1,9 @@ +export declare const balanced: (a: string | RegExp, b: string | RegExp, str: string) => false | { + start: number; + end: number; + pre: string; + body: string; + post: string; +} | undefined; +export declare const range: (a: string, b: string, str: string) => undefined | [number, number]; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.d.ts.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..6306762c77d77b909214a5d7af014b2eb156bbb3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,QAAQ,GACnB,GAAG,MAAM,GAAG,MAAM,EAClB,GAAG,MAAM,GAAG,MAAM,EAClB,KAAK,MAAM;;;;;;aAgBZ,CAAA;AAOD,eAAO,MAAM,KAAK,GAChB,GAAG,MAAM,EACT,GAAG,MAAM,EACT,KAAK,MAAM,KACV,SAAS,GAAG,CAAC,MAAM,EAAE,MAAM,CA2C7B,CAAA"} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fe81200f9d676da19bf1bf088ecef7944290e38a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.js @@ -0,0 +1,54 @@ +export const balanced = (a, b, str) => { + const ma = a instanceof RegExp ? maybeMatch(a, str) : a; + const mb = b instanceof RegExp ? maybeMatch(b, str) : b; + const r = ma !== null && mb != null && range(ma, mb, str); + return (r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + ma.length, r[1]), + post: str.slice(r[1] + mb.length), + }); +}; +const maybeMatch = (reg, str) => { + const m = str.match(reg); + return m ? m[0] : null; +}; +export const range = (a, b, str) => { + let begs, beg, left, right = undefined, result; + let ai = str.indexOf(a); + let bi = str.indexOf(b, ai + 1); + let i = ai; + if (ai >= 0 && bi > 0) { + if (a === b) { + return [ai, bi]; + } + begs = []; + left = str.length; + while (i >= 0 && !result) { + if (i === ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } + else if (begs.length === 1) { + const r = begs.pop(); + if (r !== undefined) + result = [r, bi]; + } + else { + beg = begs.pop(); + if (beg !== undefined && beg < left) { + left = beg; + right = bi; + } + bi = str.indexOf(b, i + 1); + } + i = ai < bi && ai >= 0 ? ai : bi; + } + if (begs.length && right !== undefined) { + result = [left, right]; + } + } + return result; +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.js.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..b476cae229324756c8359ea6545e7494f13e63d7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,QAAQ,GAAG,CACtB,CAAkB,EAClB,CAAkB,EAClB,GAAW,EACX,EAAE;IACF,MAAM,EAAE,GAAG,CAAC,YAAY,MAAM,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IACvD,MAAM,EAAE,GAAG,CAAC,YAAY,MAAM,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;IAEvD,MAAM,CAAC,GAAG,EAAE,KAAK,IAAI,IAAI,EAAE,IAAI,IAAI,IAAI,KAAK,CAAC,EAAE,EAAE,EAAE,EAAE,GAAG,CAAC,CAAA;IAEzD,OAAO,CACL,CAAC,IAAI;QACH,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;QACX,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC;QACT,GAAG,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QACvB,IAAI,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QACvC,IAAI,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC;KAClC,CACF,CAAA;AACH,CAAC,CAAA;AAED,MAAM,UAAU,GAAG,CAAC,GAAW,EAA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,CAAC,CAAA;YACvC,CAAC;iBAAM,CAAC;gBACN,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;gBAChB,IAAI,GAAG,KAAK,SAAS,IAAI,GAAG,GAAG,IAAI,EAAE,CAAC;oBACpC,IAAI,GAAG,GAAG,CAAA;oBACV,KAAK,GAAG,EAAE,CAAA;gBACZ,CAAC;gBAED,EAAE,GAAG,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAA;YAC5B,CAAC;YAED,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAA;QAClC,CAAC;QAED,IAAI,IAAI,CAAC,MAAM,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACvC,MAAM,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;QACxB,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAA;AACf,CAAC,CAAA","sourcesContent":["export const balanced = (\n a: string | RegExp,\n b: string | RegExp,\n str: string,\n) => {\n const ma = a instanceof RegExp ? maybeMatch(a, str) : a\n const mb = b instanceof RegExp ? maybeMatch(b, str) : b\n\n const r = ma !== null && mb != null && range(ma, mb, str)\n\n return (\n r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + ma.length, r[1]),\n post: str.slice(r[1] + mb.length),\n }\n )\n}\n\nconst maybeMatch = (reg: RegExp, str: string) => {\n const m = str.match(reg)\n return m ? m[0] : null\n}\n\nexport const range = (\n a: string,\n b: string,\n str: string,\n): undefined | [number, number] => {\n let begs: number[],\n beg: number | undefined,\n left: number,\n right: number | undefined = undefined,\n result: undefined | [number, number]\n let ai = str.indexOf(a)\n let bi = str.indexOf(b, ai + 1)\n let i = ai\n\n if (ai >= 0 && bi > 0) {\n if (a === b) {\n return [ai, bi]\n }\n begs = []\n left = str.length\n\n while (i >= 0 && !result) {\n if (i === ai) {\n begs.push(i)\n ai = str.indexOf(a, i + 1)\n } else if (begs.length === 1) {\n const r = begs.pop()\n if (r !== undefined) result = [r, bi]\n } else {\n beg = begs.pop()\n if (beg !== undefined && beg < left) {\n left = beg\n right = bi\n }\n\n bi = str.indexOf(b, i + 1)\n }\n\n i = ai < bi && ai >= 0 ? ai : bi\n }\n\n if (begs.length && right !== undefined) {\n result = [left, right]\n }\n }\n\n return result\n}\n"]} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3dbc1ca591c0557e35b6004aeba250e6a70b56e3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/package.json new file mode 100644 index 0000000000000000000000000000000000000000..49296e6af443c4c424844aa2c73081c3e34b8c8c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/balanced-match/package.json @@ -0,0 +1,79 @@ +{ + "name": "@isaacs/balanced-match", + "description": "Match balanced character pairs, like \"{\" and \"}\"", + "version": "4.0.1", + "files": [ + "dist" + ], + "repository": { + "type": "git", + "url": "git://github.com/isaacs/balanced-match.git" + }, + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + } + }, + "type": "module", + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "prepare": "tshy", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "tap", + "snap": "tap", + "format": "prettier --write . --loglevel warn", + "benchmark": "node benchmark/index.js", + "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" + }, + "prettier": { + "semi": false, + "printWidth": 80, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf" + }, + "devDependencies": { + "@types/brace-expansion": "^1.1.2", + "@types/node": "^24.0.0", + "mkdirp": "^3.0.1", + "prettier": "^3.3.2", + "tap": "^21.1.0", + "tshy": "^3.0.2", + "typedoc": "^0.28.5" + }, + "keywords": [ + "match", + "regexp", + "test", + "balanced", + "parse" + ], + "license": "MIT", + "engines": { + "node": "20 || >=22" + }, + "tshy": { + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts" + } + }, + "main": "./dist/commonjs/index.js", + "types": "./dist/commonjs/index.d.ts", + "module": "./dist/esm/index.js" +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/LICENSE b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..46e7b75c91ced041ae473299398af2b0472dc352 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/LICENSE @@ -0,0 +1,23 @@ +MIT License + +Copyright Julian Gruber + +TypeScript port Copyright Isaac Z. Schlueter + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/README.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/README.md new file mode 100644 index 0000000000000000000000000000000000000000..56097c9830ade0bc5b4a42bf44fb928190c1becc --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/README.md @@ -0,0 +1,86 @@ +# @isaacs/brace-expansion + +A hybrid CJS/ESM TypeScript fork of +[brace-expansion](http://npm.im/brace-expansion). + +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), +as known from sh/bash, in JavaScript. + +[![CI](https://github.com/juliangruber/brace-expansion/actions/workflows/ci.yml/badge.svg)](https://github.com/juliangruber/brace-expansion/actions/workflows/ci.yml) +[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) + +## Example + +```js +import { expand } from '@isaacs/brace-expansion' + +expand('file-{a,b,c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('-v{,,}') +// => ['-v', '-v', '-v'] + +expand('file{0..2}.jpg') +// => ['file0.jpg', 'file1.jpg', 'file2.jpg'] + +expand('file-{a..c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('file{2..0}.jpg') +// => ['file2.jpg', 'file1.jpg', 'file0.jpg'] + +expand('file{0..4..2}.jpg') +// => ['file0.jpg', 'file2.jpg', 'file4.jpg'] + +expand('file-{a..e..2}.jpg') +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] + +expand('file{00..10..5}.jpg') +// => ['file00.jpg', 'file05.jpg', 'file10.jpg'] + +expand('{{A..C},{a..c}}') +// => ['A', 'B', 'C', 'a', 'b', 'c'] + +expand('ppp{,config,oe{,conf}}') +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] +``` + +## API + +```js +import { expand } from '@isaacs/brace-expansion' +``` + +### const expanded = expand(str) + +Return an array of all possible and valid expansions of `str`. If none are +found, `[str]` is returned. + +Valid expansions are: + +```js +/^(.*,)+(.+)?$/ +// {a,b,...} +``` + +A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +A numeric sequence from `x` to `y` inclusive, with optional increment. +If `x` or `y` start with a leading `0`, all the numbers will be padded +to have equal length. Negative numbers and backwards iteration work too. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +An alphabetic sequence from `x` to `y` inclusive, with optional increment. +`x` and `y` must be exactly one character, and if given, `incr` must be a +number. + +For compatibility reasons, the string `${` is not eligible for brace expansion. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c51cda1bb399ab26f2d949c03cceb45ecda66597 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.d.ts @@ -0,0 +1,2 @@ +export declare function expand(str: string): string[]; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.d.ts.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..27f432d98dd6c9c8749e4d0b0b1e30740330701c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAwEA,wBAAgB,MAAM,CAAC,GAAG,EAAE,MAAM,YAgBjC"} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..99cee69d560e24a30934a93db3c116532e257417 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.js @@ -0,0 +1,196 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.expand = expand; +const balanced_match_1 = require("@isaacs/balanced-match"); +const escSlash = '\0SLASH' + Math.random() + '\0'; +const escOpen = '\0OPEN' + Math.random() + '\0'; +const escClose = '\0CLOSE' + Math.random() + '\0'; +const escComma = '\0COMMA' + Math.random() + '\0'; +const escPeriod = '\0PERIOD' + Math.random() + '\0'; +const escSlashPattern = new RegExp(escSlash, 'g'); +const escOpenPattern = new RegExp(escOpen, 'g'); +const escClosePattern = new RegExp(escClose, 'g'); +const escCommaPattern = new RegExp(escComma, 'g'); +const escPeriodPattern = new RegExp(escPeriod, 'g'); +const slashPattern = /\\\\/g; +const openPattern = /\\{/g; +const closePattern = /\\}/g; +const commaPattern = /\\,/g; +const periodPattern = /\\./g; +function numeric(str) { + return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0); +} +function escapeBraces(str) { + return str + .replace(slashPattern, escSlash) + .replace(openPattern, escOpen) + .replace(closePattern, escClose) + .replace(commaPattern, escComma) + .replace(periodPattern, escPeriod); +} +function unescapeBraces(str) { + return str + .replace(escSlashPattern, '\\') + .replace(escOpenPattern, '{') + .replace(escClosePattern, '}') + .replace(escCommaPattern, ',') + .replace(escPeriodPattern, '.'); +} +/** + * Basically just str.split(","), but handling cases + * where we have nested braced sections, which should be + * treated as individual members, like {a,{b,c},d} + */ +function parseCommaParts(str) { + if (!str) { + return ['']; + } + const parts = []; + const m = (0, balanced_match_1.balanced)('{', '}', str); + if (!m) { + return str.split(','); + } + const { pre, body, post } = m; + const p = pre.split(','); + p[p.length - 1] += '{' + body + '}'; + const postParts = parseCommaParts(post); + if (post.length) { + ; + p[p.length - 1] += postParts.shift(); + p.push.apply(p, postParts); + } + parts.push.apply(parts, p); + return parts; +} +function expand(str) { + if (!str) { + return []; + } + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.slice(0, 2) === '{}') { + str = '\\{\\}' + str.slice(2); + } + return expand_(escapeBraces(str), true).map(unescapeBraces); +} +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} +function expand_(str, isTop) { + /** @type {string[]} */ + const expansions = []; + const m = (0, balanced_match_1.balanced)('{', '}', str); + if (!m) + return [str]; + // no need to expand pre, since it is guaranteed to be free of brace-sets + const pre = m.pre; + const post = m.post.length ? expand_(m.post, false) : ['']; + if (/\$$/.test(m.pre)) { + for (let k = 0; k < post.length; k++) { + const expansion = pre + '{' + m.body + '}' + post[k]; + expansions.push(expansion); + } + } + else { + const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + const isSequence = isNumericSequence || isAlphaSequence; + const isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,(?!,).*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand_(str); + } + return [str]; + } + let n; + if (isSequence) { + n = m.body.split(/\.\./); + } + else { + n = parseCommaParts(m.body); + if (n.length === 1 && n[0] !== undefined) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand_(n[0], false).map(embrace); + //XXX is this necessary? Can't seem to hit it in tests. + /* c8 ignore start */ + if (n.length === 1) { + return post.map(p => m.pre + n[0] + p); + } + /* c8 ignore stop */ + } + } + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + let N; + if (isSequence && n[0] !== undefined && n[1] !== undefined) { + const x = numeric(n[0]); + const y = numeric(n[1]); + const width = Math.max(n[0].length, n[1].length); + let incr = n.length === 3 && n[2] !== undefined ? Math.abs(numeric(n[2])) : 1; + let test = lte; + const reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + const pad = n.some(isPadded); + N = []; + for (let i = x; test(i, y); i += incr) { + let c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') { + c = ''; + } + } + else { + c = String(i); + if (pad) { + const need = width - c.length; + if (need > 0) { + const z = new Array(need + 1).join('0'); + if (i < 0) { + c = '-' + z + c.slice(1); + } + else { + c = z + c; + } + } + } + } + N.push(c); + } + } + else { + N = []; + for (let j = 0; j < n.length; j++) { + N.push.apply(N, expand_(n[j], false)); + } + } + for (let j = 0; j < N.length; j++) { + for (let k = 0; k < post.length; k++) { + const expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) { + expansions.push(expansion); + } + } + } + } + return expansions; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.js.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6c3f6c4c12190b032384b7ddb291c3c279339364 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;AAwEA,wBAgBC;AAxFD,2DAAiD;AAEjD,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACjD,MAAM,OAAO,GAAG,QAAQ,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AAC/C,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACjD,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACjD,MAAM,SAAS,GAAG,UAAU,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACnD,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjD,MAAM,cAAc,GAAG,IAAI,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,CAAA;AAC/C,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjD,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAA;AACjD,MAAM,gBAAgB,GAAG,IAAI,MAAM,CAAC,SAAS,EAAE,GAAG,CAAC,CAAA;AACnD,MAAM,YAAY,GAAG,OAAO,CAAA;AAC5B,MAAM,WAAW,GAAG,MAAM,CAAA;AAC1B,M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AI,CAAC,KAAK,IAAI,UAAU,IAAI,SAAS,EAAE,CAAC;oBACtC,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;gBAC5B,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,UAAU,CAAA;AACnB,CAAC","sourcesContent":["import { balanced } from '@isaacs/balanced-match'\n\nconst escSlash = '\\0SLASH' + Math.random() + '\\0'\nconst escOpen = '\\0OPEN' + Math.random() + '\\0'\nconst escClose = '\\0CLOSE' + Math.random() + '\\0'\nconst escComma = '\\0COMMA' + Math.random() + '\\0'\nconst escPeriod = '\\0PERIOD' + Math.random() + '\\0'\nconst escSlashPattern = new RegExp(escSlash, 'g')\nconst escOpenPattern = new RegExp(escOpen, 'g')\nconst escClosePattern = new RegExp(escClose, 'g')\nconst escCommaPattern = new RegExp(escComma, 'g')\nconst escPeriodPattern = new RegExp(escPeriod, 'g')\nconst slashPattern = /\\\\\\\\/g\nconst openPattern = /\\\\{/g\nconst closePattern = /\\\\}/g\nconst commaPattern = /\\\\,/g\nconst periodPattern = /\\\\./g\n\nfunction numeric(str: string) {\n return !isNaN(str as any) ? parseInt(str, 10) : str.charCodeAt(0)\n}\n\nfunction escapeBraces(str: string) {\n return str\n .replace(slashPattern, escSlash)\n .replace(openPattern, escOpen)\n .replace(closePattern, escClose)\n .replace(commaPattern, escComma)\n .replace(periodPattern, escPeriod)\n}\n\nfunction unescapeBraces(str: string) {\n return str\n .replace(escSlashPattern, '\\\\')\n .replace(escOpenPattern, '{')\n .replace(escClosePattern, '}')\n .replace(escCommaPattern, ',')\n .replace(escPeriodPattern, '.')\n}\n\n/**\n * Basically just str.split(\",\"), but handling cases\n * where we have nested braced sections, which should be\n * treated as individual members, like {a,{b,c},d}\n */\nfunction parseCommaParts(str: string) {\n if (!str) {\n return ['']\n }\n\n const parts: string[] = []\n const m = balanced('{', '}', str)\n\n if (!m) {\n return str.split(',')\n }\n\n const { pre, body, post } = m\n const p = pre.split(',')\n\n p[p.length - 1] += '{' + body + '}'\n const postParts = parseCommaParts(post)\n if (post.length) {\n ;(p[p.length - 1] as string) += postParts.shift()\n p.push.apply(p, postParts)\n }\n\n parts.push.apply(parts, p)\n\n return parts\n}\n\nexport function expand(str: string) {\n if (!str) {\n return []\n }\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.slice(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.slice(2)\n }\n\n return expand_(escapeBraces(str), true).map(unescapeBraces)\n}\n\nfunction embrace(str: string) {\n return '{' + str + '}'\n}\n\nfunction isPadded(el: string) {\n return /^-?0\\d/.test(el)\n}\n\nfunction lte(i: number, y: number) {\n return i <= y\n}\n\nfunction gte(i: number, y: number) {\n return i >= y\n}\n\nfunction expand_(str: string, isTop?: boolean): string[] {\n /** @type {string[]} */\n const expansions: string[] = []\n\n const m = balanced('{', '}', str)\n if (!m) return [str]\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n const pre = m.pre\n const post: string[] = m.post.length ? expand_(m.post, false) : ['']\n\n if (/\\$$/.test(m.pre)) {\n for (let k = 0; k < post.length; k++) {\n const expansion = pre + '{' + m.body + '}' + post[k]\n expansions.push(expansion)\n }\n } else {\n const isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body)\n const isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(m.body)\n const isSequence = isNumericSequence || isAlphaSequence\n const isOptions = m.body.indexOf(',') >= 0\n if (!isSequence && !isOptions) {\n // {a},b}\n if (m.post.match(/,(?!,).*\\}/)) {\n str = m.pre + '{' + m.body + escClose + m.post\n return expand_(str)\n }\n return [str]\n }\n\n let n: string[]\n if (isSequence) {\n n = m.body.split(/\\.\\./)\n } else {\n n = parseCommaParts(m.body)\n if (n.length === 1 && n[0] !== undefined) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand_(n[0], false).map(embrace)\n //XXX is this necessary? Can't seem to hit it in tests.\n /* c8 ignore start */\n if (n.length === 1) {\n return post.map(p => m.pre + n[0] + p)\n }\n /* c8 ignore stop */\n }\n }\n\n // at this point, n is the parts, and we know it's not a comma set\n // with a single entry.\n let N: string[]\n\n if (isSequence && n[0] !== undefined && n[1] !== undefined) {\n const x = numeric(n[0])\n const y = numeric(n[1])\n const width = Math.max(n[0].length, n[1].length)\n let incr =\n n.length === 3 && n[2] !== undefined ? Math.abs(numeric(n[2])) : 1\n let test = lte\n const reverse = y < x\n if (reverse) {\n incr *= -1\n test = gte\n }\n const pad = n.some(isPadded)\n\n N = []\n\n for (let i = x; test(i, y); i += incr) {\n let c\n if (isAlphaSequence) {\n c = String.fromCharCode(i)\n if (c === '\\\\') {\n c = ''\n }\n } else {\n c = String(i)\n if (pad) {\n const need = width - c.length\n if (need > 0) {\n const z = new Array(need + 1).join('0')\n if (i < 0) {\n c = '-' + z + c.slice(1)\n } else {\n c = z + c\n }\n }\n }\n }\n N.push(c)\n }\n } else {\n N = []\n\n for (let j = 0; j < n.length; j++) {\n N.push.apply(N, expand_(n[j] as string, false))\n }\n }\n\n for (let j = 0; j < N.length; j++) {\n for (let k = 0; k < post.length; k++) {\n const expansion = pre + N[j] + post[k]\n if (!isTop || isSequence || expansion) {\n expansions.push(expansion)\n }\n }\n }\n }\n\n return expansions\n}\n"]} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5bbefffbabee392d1855491b84dc0a716b6a3bf2 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c51cda1bb399ab26f2d949c03cceb45ecda66597 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.d.ts @@ -0,0 +1,2 @@ +export declare function expand(str: string): string[]; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.d.ts.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.d.ts.map new file mode 100644 index 0000000000000000000000000000000000000000..27f432d98dd6c9c8749e4d0b0b1e30740330701c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAwEA,wBAAgB,MAAM,CAAC,GAAG,EAAE,MAAM,YAgBjC"} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ebb88ed4117c87e40d30ee9418c9b2278435de1c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.js @@ -0,0 +1,193 @@ +import { balanced } from '@isaacs/balanced-match'; +const escSlash = '\0SLASH' + Math.random() + '\0'; +const escOpen = '\0OPEN' + Math.random() + '\0'; +const escClose = '\0CLOSE' + Math.random() + '\0'; +const escComma = '\0COMMA' + Math.random() + '\0'; +const escPeriod = '\0PERIOD' + Math.random() + '\0'; +const escSlashPattern = new RegExp(escSlash, 'g'); +const escOpenPattern = new RegExp(escOpen, 'g'); +const escClosePattern = new RegExp(escClose, 'g'); +const escCommaPattern = new RegExp(escComma, 'g'); +const escPeriodPattern = new RegExp(escPeriod, 'g'); +const slashPattern = /\\\\/g; +const openPattern = /\\{/g; +const closePattern = /\\}/g; +const commaPattern = /\\,/g; +const periodPattern = /\\./g; +function numeric(str) { + return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0); +} +function escapeBraces(str) { + return str + .replace(slashPattern, escSlash) + .replace(openPattern, escOpen) + .replace(closePattern, escClose) + .replace(commaPattern, escComma) + .replace(periodPattern, escPeriod); +} +function unescapeBraces(str) { + return str + .replace(escSlashPattern, '\\') + .replace(escOpenPattern, '{') + .replace(escClosePattern, '}') + .replace(escCommaPattern, ',') + .replace(escPeriodPattern, '.'); +} +/** + * Basically just str.split(","), but handling cases + * where we have nested braced sections, which should be + * treated as individual members, like {a,{b,c},d} + */ +function parseCommaParts(str) { + if (!str) { + return ['']; + } + const parts = []; + const m = balanced('{', '}', str); + if (!m) { + return str.split(','); + } + const { pre, body, post } = m; + const p = pre.split(','); + p[p.length - 1] += '{' + body + '}'; + const postParts = parseCommaParts(post); + if (post.length) { + ; + p[p.length - 1] += postParts.shift(); + p.push.apply(p, postParts); + } + parts.push.apply(parts, p); + return parts; +} +export function expand(str) { + if (!str) { + return []; + } + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.slice(0, 2) === '{}') { + str = '\\{\\}' + str.slice(2); + } + return expand_(escapeBraces(str), true).map(unescapeBraces); +} +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} +function expand_(str, isTop) { + /** @type {string[]} */ + const expansions = []; + const m = balanced('{', '}', str); + if (!m) + return [str]; + // no need to expand pre, since it is guaranteed to be free of brace-sets + const pre = m.pre; + const post = m.post.length ? expand_(m.post, false) : ['']; + if (/\$$/.test(m.pre)) { + for (let k = 0; k < post.length; k++) { + const expansion = pre + '{' + m.body + '}' + post[k]; + expansions.push(expansion); + } + } + else { + const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + const isSequence = isNumericSequence || isAlphaSequence; + const isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,(?!,).*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand_(str); + } + return [str]; + } + let n; + if (isSequence) { + n = m.body.split(/\.\./); + } + else { + n = parseCommaParts(m.body); + if (n.length === 1 && n[0] !== undefined) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand_(n[0], false).map(embrace); + //XXX is this necessary? Can't seem to hit it in tests. + /* c8 ignore start */ + if (n.length === 1) { + return post.map(p => m.pre + n[0] + p); + } + /* c8 ignore stop */ + } + } + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + let N; + if (isSequence && n[0] !== undefined && n[1] !== undefined) { + const x = numeric(n[0]); + const y = numeric(n[1]); + const width = Math.max(n[0].length, n[1].length); + let incr = n.length === 3 && n[2] !== undefined ? Math.abs(numeric(n[2])) : 1; + let test = lte; + const reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + const pad = n.some(isPadded); + N = []; + for (let i = x; test(i, y); i += incr) { + let c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') { + c = ''; + } + } + else { + c = String(i); + if (pad) { + const need = width - c.length; + if (need > 0) { + const z = new Array(need + 1).join('0'); + if (i < 0) { + c = '-' + z + c.slice(1); + } + else { + c = z + c; + } + } + } + } + N.push(c); + } + } + else { + N = []; + for (let j = 0; j < n.length; j++) { + N.push.apply(N, expand_(n[j], false)); + } + } + for (let j = 0; j < N.length; j++) { + for (let k = 0; k < post.length; k++) { + const expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) { + expansions.push(expansion); + } + } + } + } + return expansions; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.js.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..85c33de61a809638b528c565e532fec712531e6b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAA;AAEjD,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACjD,MAAM,OAAO,GAAG,QAAQ,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AAC/C,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACjD,MAAM,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACjD,MAAM,SAAS,GAAG,UAAU,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAA;AACnD,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,QAAQ,EA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,CAAC,CAAC,CAAC,CAAW,EAAE,KAAK,CAAC,CAAC,CAAA;YACjD,CAAC;QACH,CAAC;QAED,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YAClC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;gBACrC,MAAM,SAAS,GAAG,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;gBACtC,IAAI,CAAC,KAAK,IAAI,UAAU,IAAI,SAAS,EAAE,CAAC;oBACtC,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;gBAC5B,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,UAAU,CAAA;AACnB,CAAC","sourcesContent":["import { balanced } from '@isaacs/balanced-match'\n\nconst escSlash = '\\0SLASH' + Math.random() + '\\0'\nconst escOpen = '\\0OPEN' + Math.random() + '\\0'\nconst escClose = '\\0CLOSE' + Math.random() + '\\0'\nconst escComma = '\\0COMMA' + Math.random() + '\\0'\nconst escPeriod = '\\0PERIOD' + Math.random() + '\\0'\nconst escSlashPattern = new RegExp(escSlash, 'g')\nconst escOpenPattern = new RegExp(escOpen, 'g')\nconst escClosePattern = new RegExp(escClose, 'g')\nconst escCommaPattern = new RegExp(escComma, 'g')\nconst escPeriodPattern = new RegExp(escPeriod, 'g')\nconst slashPattern = /\\\\\\\\/g\nconst openPattern = /\\\\{/g\nconst closePattern = /\\\\}/g\nconst commaPattern = /\\\\,/g\nconst periodPattern = /\\\\./g\n\nfunction numeric(str: string) {\n return !isNaN(str as any) ? parseInt(str, 10) : str.charCodeAt(0)\n}\n\nfunction escapeBraces(str: string) {\n return str\n .replace(slashPattern, escSlash)\n .replace(openPattern, escOpen)\n .replace(closePattern, escClose)\n .replace(commaPattern, escComma)\n .replace(periodPattern, escPeriod)\n}\n\nfunction unescapeBraces(str: string) {\n return str\n .replace(escSlashPattern, '\\\\')\n .replace(escOpenPattern, '{')\n .replace(escClosePattern, '}')\n .replace(escCommaPattern, ',')\n .replace(escPeriodPattern, '.')\n}\n\n/**\n * Basically just str.split(\",\"), but handling cases\n * where we have nested braced sections, which should be\n * treated as individual members, like {a,{b,c},d}\n */\nfunction parseCommaParts(str: string) {\n if (!str) {\n return ['']\n }\n\n const parts: string[] = []\n const m = balanced('{', '}', str)\n\n if (!m) {\n return str.split(',')\n }\n\n const { pre, body, post } = m\n const p = pre.split(',')\n\n p[p.length - 1] += '{' + body + '}'\n const postParts = parseCommaParts(post)\n if (post.length) {\n ;(p[p.length - 1] as string) += postParts.shift()\n p.push.apply(p, postParts)\n }\n\n parts.push.apply(parts, p)\n\n return parts\n}\n\nexport function expand(str: string) {\n if (!str) {\n return []\n }\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.slice(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.slice(2)\n }\n\n return expand_(escapeBraces(str), true).map(unescapeBraces)\n}\n\nfunction embrace(str: string) {\n return '{' + str + '}'\n}\n\nfunction isPadded(el: string) {\n return /^-?0\\d/.test(el)\n}\n\nfunction lte(i: number, y: number) {\n return i <= y\n}\n\nfunction gte(i: number, y: number) {\n return i >= y\n}\n\nfunction expand_(str: string, isTop?: boolean): string[] {\n /** @type {string[]} */\n const expansions: string[] = []\n\n const m = balanced('{', '}', str)\n if (!m) return [str]\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n const pre = m.pre\n const post: string[] = m.post.length ? expand_(m.post, false) : ['']\n\n if (/\\$$/.test(m.pre)) {\n for (let k = 0; k < post.length; k++) {\n const expansion = pre + '{' + m.body + '}' + post[k]\n expansions.push(expansion)\n }\n } else {\n const isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body)\n const isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(m.body)\n const isSequence = isNumericSequence || isAlphaSequence\n const isOptions = m.body.indexOf(',') >= 0\n if (!isSequence && !isOptions) {\n // {a},b}\n if (m.post.match(/,(?!,).*\\}/)) {\n str = m.pre + '{' + m.body + escClose + m.post\n return expand_(str)\n }\n return [str]\n }\n\n let n: string[]\n if (isSequence) {\n n = m.body.split(/\\.\\./)\n } else {\n n = parseCommaParts(m.body)\n if (n.length === 1 && n[0] !== undefined) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand_(n[0], false).map(embrace)\n //XXX is this necessary? Can't seem to hit it in tests.\n /* c8 ignore start */\n if (n.length === 1) {\n return post.map(p => m.pre + n[0] + p)\n }\n /* c8 ignore stop */\n }\n }\n\n // at this point, n is the parts, and we know it's not a comma set\n // with a single entry.\n let N: string[]\n\n if (isSequence && n[0] !== undefined && n[1] !== undefined) {\n const x = numeric(n[0])\n const y = numeric(n[1])\n const width = Math.max(n[0].length, n[1].length)\n let incr =\n n.length === 3 && n[2] !== undefined ? Math.abs(numeric(n[2])) : 1\n let test = lte\n const reverse = y < x\n if (reverse) {\n incr *= -1\n test = gte\n }\n const pad = n.some(isPadded)\n\n N = []\n\n for (let i = x; test(i, y); i += incr) {\n let c\n if (isAlphaSequence) {\n c = String.fromCharCode(i)\n if (c === '\\\\') {\n c = ''\n }\n } else {\n c = String(i)\n if (pad) {\n const need = width - c.length\n if (need > 0) {\n const z = new Array(need + 1).join('0')\n if (i < 0) {\n c = '-' + z + c.slice(1)\n } else {\n c = z + c\n }\n }\n }\n }\n N.push(c)\n }\n } else {\n N = []\n\n for (let j = 0; j < n.length; j++) {\n N.push.apply(N, expand_(n[j] as string, false))\n }\n }\n\n for (let j = 0; j < N.length; j++) {\n for (let k = 0; k < post.length; k++) {\n const expansion = pre + N[j] + post[k]\n if (!isTop || isSequence || expansion) {\n expansions.push(expansion)\n }\n }\n }\n }\n\n return expansions\n}\n"]} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3dbc1ca591c0557e35b6004aeba250e6a70b56e3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/package.json new file mode 100644 index 0000000000000000000000000000000000000000..cf1035688398b9b4d136c21b9de1e9ace6089b5c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/brace-expansion/package.json @@ -0,0 +1,71 @@ +{ + "name": "@isaacs/brace-expansion", + "description": "Brace expansion as known from sh/bash", + "version": "5.0.0", + "files": [ + "dist" + ], + "exports": { + "./package.json": "./package.json", + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + } + }, + "type": "module", + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "prepare": "tshy", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "tap", + "snap": "tap", + "format": "prettier --write . --loglevel warn", + "benchmark": "node benchmark/index.js", + "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" + }, + "prettier": { + "semi": false, + "printWidth": 80, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf" + }, + "devDependencies": { + "@types/brace-expansion": "^1.1.2", + "@types/node": "^24.0.0", + "mkdirp": "^3.0.1", + "prettier": "^3.3.2", + "tap": "^21.1.0", + "tshy": "^3.0.2", + "typedoc": "^0.28.5" + }, + "dependencies": { + "@isaacs/balanced-match": "^4.0.1" + }, + "license": "MIT", + "engines": { + "node": "20 || >=22" + }, + "tshy": { + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts" + } + }, + "main": "./dist/commonjs/index.js", + "types": "./dist/commonjs/index.d.ts", + "module": "./dist/esm/index.js" +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/cliui/LICENSE.txt b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/cliui/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..c7e27478a3eff8862ca150f10d1b93a5ac866af2 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/cliui/LICENSE.txt @@ -0,0 +1,14 @@ +Copyright (c) 2015, Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/cliui/README.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/cliui/README.md new file mode 100644 index 0000000000000000000000000000000000000000..488064267d56947677a7785195035a5aa475cd6f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/cliui/README.md @@ -0,0 +1,143 @@ +# @isaacs/cliui + +Temporary fork of [cliui](http://npm.im/cliui). + +![ci](https://github.com/yargs/cliui/workflows/ci/badge.svg) +[![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) +[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) +![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/cliui) + +easily create complex multi-column command-line-interfaces. + +## Example + +```js +const ui = require('cliui')() + +ui.div('Usage: $0 [command] [options]') + +ui.div({ + text: 'Options:', + padding: [2, 0, 1, 0] +}) + +ui.div( + { + text: "-f, --file", + width: 20, + padding: [0, 4, 0, 4] + }, + { + text: "the file to load." + + chalk.green("(if this description is long it wraps).") + , + width: 20 + }, + { + text: chalk.red("[required]"), + align: 'right' + } +) + +console.log(ui.toString()) +``` + +## Deno/ESM Support + +As of `v7` `cliui` supports [Deno](https://github.com/denoland/deno) and +[ESM](https://nodejs.org/api/esm.html#esm_ecmascript_modules): + +```typescript +import cliui from "https://deno.land/x/cliui/deno.ts"; + +const ui = cliui({}) + +ui.div('Usage: $0 [command] [options]') + +ui.div({ + text: 'Options:', + padding: [2, 0, 1, 0] +}) + +ui.div({ + text: "-f, --file", + width: 20, + padding: [0, 4, 0, 4] +}) + +console.log(ui.toString()) +``` + + + +## Layout DSL + +cliui exposes a simple layout DSL: + +If you create a single `ui.div`, passing a string rather than an +object: + +* `\n`: characters will be interpreted as new rows. +* `\t`: characters will be interpreted as new columns. +* `\s`: characters will be interpreted as padding. + +**as an example...** + +```js +var ui = require('./')({ + width: 60 +}) + +ui.div( + 'Usage: node ./bin/foo.js\n' + + ' \t provide a regex\n' + + ' \t provide a glob\t [required]' +) + +console.log(ui.toString()) +``` + +**will output:** + +```shell +Usage: node ./bin/foo.js + provide a regex + provide a glob [required] +``` + +## Methods + +```js +cliui = require('cliui') +``` + +### cliui({width: integer}) + +Specify the maximum width of the UI being generated. +If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`. + +### cliui({wrap: boolean}) + +Enable or disable the wrapping of text in a column. + +### cliui.div(column, column, column) + +Create a row with any number of columns, a column +can either be a string, or an object with the following +options: + +* **text:** some text to place in the column. +* **width:** the width of a column. +* **align:** alignment, `right` or `center`. +* **padding:** `[top, right, bottom, left]`. +* **border:** should a border be placed around the div? + +### cliui.span(column, column, column) + +Similar to `div`, except the next row will be appended without +a new line being created. + +### cliui.resetOutput() + +Resets the UI elements of the current cliui instance, maintaining the values +set for `width` and `wrap`. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/cliui/build/index.cjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/cliui/build/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..aca2b8507ac0f34d914ea50268da62158cf935cf --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/cliui/build/index.cjs @@ -0,0 +1,317 @@ +'use strict'; + +const align = { + right: alignRight, + center: alignCenter +}; +const top = 0; +const right = 1; +const bottom = 2; +const left = 3; +class UI { + constructor(opts) { + var _a; + this.width = opts.width; + /* c8 ignore start */ + this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true; + /* c8 ignore stop */ + this.rows = []; + } + span(...args) { + const cols = this.div(...args); + cols.span = true; + } + resetOutput() { + this.rows = []; + } + div(...args) { + if (args.length === 0) { + this.div(''); + } + if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') { + return this.applyLayoutDSL(args[0]); + } + const cols = args.map(arg => { + if (typeof arg === 'string') { + return this.colFromString(arg); + } + return arg; + }); + this.rows.push(cols); + return cols; + } + shouldApplyLayoutDSL(...args) { + return args.length === 1 && typeof args[0] === 'string' && + /[\t\n]/.test(args[0]); + } + applyLayoutDSL(str) { + const rows = str.split('\n').map(row => row.split('\t')); + let leftColumnWidth = 0; + // simple heuristic for layout, make sure the + // second column lines up along the left-hand. + // don't allow the first column to take up more + // than 50% of the screen. + rows.forEach(columns => { + if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) { + leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0])); + } + }); + // generate a table: + // replacing ' ' with padding calculations. + // using the algorithmically generated width. + rows.forEach(columns => { + this.div(...columns.map((r, i) => { + return { + text: r.trim(), + padding: this.measurePadding(r), + width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined + }; + })); + }); + return this.rows[this.rows.length - 1]; + } + colFromString(text) { + return { + text, + padding: this.measurePadding(text) + }; + } + measurePadding(str) { + // measure padding without ansi escape codes + const noAnsi = mixin.stripAnsi(str); + return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length]; + } + toString() { + const lines = []; + this.rows.forEach(row => { + this.rowToString(row, lines); + }); + // don't display any lines with the + // hidden flag set. + return lines + .filter(line => !line.hidden) + .map(line => line.text) + .join('\n'); + } + rowToString(row, lines) { + this.rasterize(row).forEach((rrow, r) => { + let str = ''; + rrow.forEach((col, c) => { + const { width } = row[c]; // the width with padding. + const wrapWidth = this.negatePadding(row[c]); // the width without padding. + let ts = col; // temporary string used during alignment/padding. + if (wrapWidth > mixin.stringWidth(col)) { + ts += ' '.repeat(wrapWidth - mixin.stringWidth(col)); + } + // align the string within its column. + if (row[c].align && row[c].align !== 'left' && this.wrap) { + const fn = align[row[c].align]; + ts = fn(ts, wrapWidth); + if (mixin.stringWidth(ts) < wrapWidth) { + /* c8 ignore start */ + const w = width || 0; + /* c8 ignore stop */ + ts += ' '.repeat(w - mixin.stringWidth(ts) - 1); + } + } + // apply border and padding to string. + const padding = row[c].padding || [0, 0, 0, 0]; + if (padding[left]) { + str += ' '.repeat(padding[left]); + } + str += addBorder(row[c], ts, '| '); + str += ts; + str += addBorder(row[c], ts, ' |'); + if (padding[right]) { + str += ' '.repeat(padding[right]); + } + // if prior row is span, try to render the + // current row on the prior line. + if (r === 0 && lines.length > 0) { + str = this.renderInline(str, lines[lines.length - 1]); + } + }); + // remove trailing whitespace. + lines.push({ + text: str.replace(/ +$/, ''), + span: row.span + }); + }); + return lines; + } + // if the full 'source' can render in + // the target line, do so. + renderInline(source, previousLine) { + const match = source.match(/^ */); + /* c8 ignore start */ + const leadingWhitespace = match ? match[0].length : 0; + /* c8 ignore stop */ + const target = previousLine.text; + const targetTextWidth = mixin.stringWidth(target.trimEnd()); + if (!previousLine.span) { + return source; + } + // if we're not applying wrapping logic, + // just always append to the span. + if (!this.wrap) { + previousLine.hidden = true; + return target + source; + } + if (leadingWhitespace < targetTextWidth) { + return source; + } + previousLine.hidden = true; + return target.trimEnd() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimStart(); + } + rasterize(row) { + const rrows = []; + const widths = this.columnWidths(row); + let wrapped; + // word wrap all columns, and create + // a data-structure that is easy to rasterize. + row.forEach((col, c) => { + // leave room for left and right padding. + col.width = widths[c]; + if (this.wrap) { + wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n'); + } + else { + wrapped = col.text.split('\n'); + } + if (col.border) { + wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.'); + wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'"); + } + // add top and bottom padding. + if (col.padding) { + wrapped.unshift(...new Array(col.padding[top] || 0).fill('')); + wrapped.push(...new Array(col.padding[bottom] || 0).fill('')); + } + wrapped.forEach((str, r) => { + if (!rrows[r]) { + rrows.push([]); + } + const rrow = rrows[r]; + for (let i = 0; i < c; i++) { + if (rrow[i] === undefined) { + rrow.push(''); + } + } + rrow.push(str); + }); + }); + return rrows; + } + negatePadding(col) { + /* c8 ignore start */ + let wrapWidth = col.width || 0; + /* c8 ignore stop */ + if (col.padding) { + wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0); + } + if (col.border) { + wrapWidth -= 4; + } + return wrapWidth; + } + columnWidths(row) { + if (!this.wrap) { + return row.map(col => { + return col.width || mixin.stringWidth(col.text); + }); + } + let unset = row.length; + let remainingWidth = this.width; + // column widths can be set in config. + const widths = row.map(col => { + if (col.width) { + unset--; + remainingWidth -= col.width; + return col.width; + } + return undefined; + }); + // any unset widths should be calculated. + /* c8 ignore start */ + const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0; + /* c8 ignore stop */ + return widths.map((w, i) => { + if (w === undefined) { + return Math.max(unsetWidth, _minWidth(row[i])); + } + return w; + }); + } +} +function addBorder(col, ts, style) { + if (col.border) { + if (/[.']-+[.']/.test(ts)) { + return ''; + } + if (ts.trim().length !== 0) { + return style; + } + return ' '; + } + return ''; +} +// calculates the minimum width of +// a column, based on padding preferences. +function _minWidth(col) { + const padding = col.padding || []; + const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0); + if (col.border) { + return minWidth + 4; + } + return minWidth; +} +function getWindowWidth() { + /* c8 ignore start */ + if (typeof process === 'object' && process.stdout && process.stdout.columns) { + return process.stdout.columns; + } + return 80; +} +/* c8 ignore stop */ +function alignRight(str, width) { + str = str.trim(); + const strWidth = mixin.stringWidth(str); + if (strWidth < width) { + return ' '.repeat(width - strWidth) + str; + } + return str; +} +function alignCenter(str, width) { + str = str.trim(); + const strWidth = mixin.stringWidth(str); + /* c8 ignore start */ + if (strWidth >= width) { + return str; + } + /* c8 ignore stop */ + return ' '.repeat((width - strWidth) >> 1) + str; +} +let mixin; +function cliui(opts, _mixin) { + mixin = _mixin; + return new UI({ + /* c8 ignore start */ + width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(), + wrap: opts === null || opts === void 0 ? void 0 : opts.wrap + /* c8 ignore stop */ + }); +} + +// Bootstrap cliui with CommonJS dependencies: +const stringWidth = require('string-width-cjs'); +const stripAnsi = require('strip-ansi-cjs'); +const wrap = require('wrap-ansi-cjs'); +function ui(opts) { + return cliui(opts, { + stringWidth, + stripAnsi, + wrap + }); +} + +module.exports = ui; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/cliui/build/index.d.cts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/cliui/build/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..4567f945e81a73dc2e589f153913910fa2f5fea9 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/cliui/build/index.d.cts @@ -0,0 +1,43 @@ +interface UIOptions { + width: number; + wrap?: boolean; + rows?: string[]; +} +interface Column { + text: string; + width?: number; + align?: "right" | "left" | "center"; + padding: number[]; + border?: boolean; +} +interface ColumnArray extends Array { + span: boolean; +} +interface Line { + hidden?: boolean; + text: string; + span?: boolean; +} +declare class UI { + width: number; + wrap: boolean; + rows: ColumnArray[]; + constructor(opts: UIOptions); + span(...args: ColumnArray): void; + resetOutput(): void; + div(...args: (Column | string)[]): ColumnArray; + private shouldApplyLayoutDSL; + private applyLayoutDSL; + private colFromString; + private measurePadding; + toString(): string; + rowToString(row: ColumnArray, lines: Line[]): Line[]; + // if the full 'source' can render in + // the target line, do so. + private renderInline; + private rasterize; + private negatePadding; + private columnWidths; +} +declare function ui(opts: UIOptions): UI; +export { ui as default }; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/cliui/build/lib/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/cliui/build/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..587b5ecd3e773b9f5aeb07720b13407a5974b0cc --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/cliui/build/lib/index.js @@ -0,0 +1,302 @@ +'use strict'; +const align = { + right: alignRight, + center: alignCenter +}; +const top = 0; +const right = 1; +const bottom = 2; +const left = 3; +export class UI { + constructor(opts) { + var _a; + this.width = opts.width; + /* c8 ignore start */ + this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true; + /* c8 ignore stop */ + this.rows = []; + } + span(...args) { + const cols = this.div(...args); + cols.span = true; + } + resetOutput() { + this.rows = []; + } + div(...args) { + if (args.length === 0) { + this.div(''); + } + if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') { + return this.applyLayoutDSL(args[0]); + } + const cols = args.map(arg => { + if (typeof arg === 'string') { + return this.colFromString(arg); + } + return arg; + }); + this.rows.push(cols); + return cols; + } + shouldApplyLayoutDSL(...args) { + return args.length === 1 && typeof args[0] === 'string' && + /[\t\n]/.test(args[0]); + } + applyLayoutDSL(str) { + const rows = str.split('\n').map(row => row.split('\t')); + let leftColumnWidth = 0; + // simple heuristic for layout, make sure the + // second column lines up along the left-hand. + // don't allow the first column to take up more + // than 50% of the screen. + rows.forEach(columns => { + if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) { + leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0])); + } + }); + // generate a table: + // replacing ' ' with padding calculations. + // using the algorithmically generated width. + rows.forEach(columns => { + this.div(...columns.map((r, i) => { + return { + text: r.trim(), + padding: this.measurePadding(r), + width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined + }; + })); + }); + return this.rows[this.rows.length - 1]; + } + colFromString(text) { + return { + text, + padding: this.measurePadding(text) + }; + } + measurePadding(str) { + // measure padding without ansi escape codes + const noAnsi = mixin.stripAnsi(str); + return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length]; + } + toString() { + const lines = []; + this.rows.forEach(row => { + this.rowToString(row, lines); + }); + // don't display any lines with the + // hidden flag set. + return lines + .filter(line => !line.hidden) + .map(line => line.text) + .join('\n'); + } + rowToString(row, lines) { + this.rasterize(row).forEach((rrow, r) => { + let str = ''; + rrow.forEach((col, c) => { + const { width } = row[c]; // the width with padding. + const wrapWidth = this.negatePadding(row[c]); // the width without padding. + let ts = col; // temporary string used during alignment/padding. + if (wrapWidth > mixin.stringWidth(col)) { + ts += ' '.repeat(wrapWidth - mixin.stringWidth(col)); + } + // align the string within its column. + if (row[c].align && row[c].align !== 'left' && this.wrap) { + const fn = align[row[c].align]; + ts = fn(ts, wrapWidth); + if (mixin.stringWidth(ts) < wrapWidth) { + /* c8 ignore start */ + const w = width || 0; + /* c8 ignore stop */ + ts += ' '.repeat(w - mixin.stringWidth(ts) - 1); + } + } + // apply border and padding to string. + const padding = row[c].padding || [0, 0, 0, 0]; + if (padding[left]) { + str += ' '.repeat(padding[left]); + } + str += addBorder(row[c], ts, '| '); + str += ts; + str += addBorder(row[c], ts, ' |'); + if (padding[right]) { + str += ' '.repeat(padding[right]); + } + // if prior row is span, try to render the + // current row on the prior line. + if (r === 0 && lines.length > 0) { + str = this.renderInline(str, lines[lines.length - 1]); + } + }); + // remove trailing whitespace. + lines.push({ + text: str.replace(/ +$/, ''), + span: row.span + }); + }); + return lines; + } + // if the full 'source' can render in + // the target line, do so. + renderInline(source, previousLine) { + const match = source.match(/^ */); + /* c8 ignore start */ + const leadingWhitespace = match ? match[0].length : 0; + /* c8 ignore stop */ + const target = previousLine.text; + const targetTextWidth = mixin.stringWidth(target.trimEnd()); + if (!previousLine.span) { + return source; + } + // if we're not applying wrapping logic, + // just always append to the span. + if (!this.wrap) { + previousLine.hidden = true; + return target + source; + } + if (leadingWhitespace < targetTextWidth) { + return source; + } + previousLine.hidden = true; + return target.trimEnd() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimStart(); + } + rasterize(row) { + const rrows = []; + const widths = this.columnWidths(row); + let wrapped; + // word wrap all columns, and create + // a data-structure that is easy to rasterize. + row.forEach((col, c) => { + // leave room for left and right padding. + col.width = widths[c]; + if (this.wrap) { + wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n'); + } + else { + wrapped = col.text.split('\n'); + } + if (col.border) { + wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.'); + wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'"); + } + // add top and bottom padding. + if (col.padding) { + wrapped.unshift(...new Array(col.padding[top] || 0).fill('')); + wrapped.push(...new Array(col.padding[bottom] || 0).fill('')); + } + wrapped.forEach((str, r) => { + if (!rrows[r]) { + rrows.push([]); + } + const rrow = rrows[r]; + for (let i = 0; i < c; i++) { + if (rrow[i] === undefined) { + rrow.push(''); + } + } + rrow.push(str); + }); + }); + return rrows; + } + negatePadding(col) { + /* c8 ignore start */ + let wrapWidth = col.width || 0; + /* c8 ignore stop */ + if (col.padding) { + wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0); + } + if (col.border) { + wrapWidth -= 4; + } + return wrapWidth; + } + columnWidths(row) { + if (!this.wrap) { + return row.map(col => { + return col.width || mixin.stringWidth(col.text); + }); + } + let unset = row.length; + let remainingWidth = this.width; + // column widths can be set in config. + const widths = row.map(col => { + if (col.width) { + unset--; + remainingWidth -= col.width; + return col.width; + } + return undefined; + }); + // any unset widths should be calculated. + /* c8 ignore start */ + const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0; + /* c8 ignore stop */ + return widths.map((w, i) => { + if (w === undefined) { + return Math.max(unsetWidth, _minWidth(row[i])); + } + return w; + }); + } +} +function addBorder(col, ts, style) { + if (col.border) { + if (/[.']-+[.']/.test(ts)) { + return ''; + } + if (ts.trim().length !== 0) { + return style; + } + return ' '; + } + return ''; +} +// calculates the minimum width of +// a column, based on padding preferences. +function _minWidth(col) { + const padding = col.padding || []; + const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0); + if (col.border) { + return minWidth + 4; + } + return minWidth; +} +function getWindowWidth() { + /* c8 ignore start */ + if (typeof process === 'object' && process.stdout && process.stdout.columns) { + return process.stdout.columns; + } + return 80; +} +/* c8 ignore stop */ +function alignRight(str, width) { + str = str.trim(); + const strWidth = mixin.stringWidth(str); + if (strWidth < width) { + return ' '.repeat(width - strWidth) + str; + } + return str; +} +function alignCenter(str, width) { + str = str.trim(); + const strWidth = mixin.stringWidth(str); + /* c8 ignore start */ + if (strWidth >= width) { + return str; + } + /* c8 ignore stop */ + return ' '.repeat((width - strWidth) >> 1) + str; +} +let mixin; +export function cliui(opts, _mixin) { + mixin = _mixin; + return new UI({ + /* c8 ignore start */ + width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(), + wrap: opts === null || opts === void 0 ? void 0 : opts.wrap + /* c8 ignore stop */ + }); +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/cliui/index.mjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/cliui/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5177519af372221f252cda2d75ac66385f44f753 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/cliui/index.mjs @@ -0,0 +1,14 @@ +// Bootstrap cliui with ESM dependencies: +import { cliui } from './build/lib/index.js' + +import stringWidth from 'string-width' +import stripAnsi from 'strip-ansi' +import wrap from 'wrap-ansi' + +export default function ui (opts) { + return cliui(opts, { + stringWidth, + stripAnsi, + wrap + }) +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/cliui/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/cliui/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7a952532def5d499f626274e49fa8cc3032b6429 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@isaacs/cliui/package.json @@ -0,0 +1,86 @@ +{ + "name": "@isaacs/cliui", + "version": "8.0.2", + "description": "easily create complex multi-column command-line-interfaces", + "main": "build/index.cjs", + "exports": { + ".": [ + { + "import": "./index.mjs", + "require": "./build/index.cjs" + }, + "./build/index.cjs" + ] + }, + "type": "module", + "module": "./index.mjs", + "scripts": { + "check": "standardx '**/*.ts' && standardx '**/*.js' && standardx '**/*.cjs'", + "fix": "standardx --fix '**/*.ts' && standardx --fix '**/*.js' && standardx --fix '**/*.cjs'", + "pretest": "rimraf build && tsc -p tsconfig.test.json && cross-env NODE_ENV=test npm run build:cjs", + "test": "c8 mocha ./test/*.cjs", + "test:esm": "c8 mocha ./test/**/*.mjs", + "postest": "check", + "coverage": "c8 report --check-coverage", + "precompile": "rimraf build", + "compile": "tsc", + "postcompile": "npm run build:cjs", + "build:cjs": "rollup -c", + "prepare": "npm run compile" + }, + "repository": "yargs/cliui", + "standard": { + "ignore": [ + "**/example/**" + ], + "globals": [ + "it" + ] + }, + "keywords": [ + "cli", + "command-line", + "layout", + "design", + "console", + "wrap", + "table" + ], + "author": "Ben Coe ", + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "devDependencies": { + "@types/node": "^14.0.27", + "@typescript-eslint/eslint-plugin": "^4.0.0", + "@typescript-eslint/parser": "^4.0.0", + "c8": "^7.3.0", + "chai": "^4.2.0", + "chalk": "^4.1.0", + "cross-env": "^7.0.2", + "eslint": "^7.6.0", + "eslint-plugin-import": "^2.22.0", + "eslint-plugin-node": "^11.1.0", + "gts": "^3.0.0", + "mocha": "^10.0.0", + "rimraf": "^3.0.2", + "rollup": "^2.23.1", + "rollup-plugin-ts": "^3.0.2", + "standardx": "^7.0.0", + "typescript": "^4.0.0" + }, + "files": [ + "build", + "index.mjs", + "!*.d.ts" + ], + "engines": { + "node": ">=12" + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@lukeed/ms/dist/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@lukeed/ms/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..001b3fb74dd272de22456d23dd8a1f5c39289229 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@lukeed/ms/dist/index.js @@ -0,0 +1,37 @@ +var RGX = /^(-?(?:\d+)?\.?\d+) *(m(?:illiseconds?|s(?:ecs?)?))?(s(?:ec(?:onds?|s)?)?)?(m(?:in(?:utes?|s)?)?)?(h(?:ours?|rs?)?)?(d(?:ays?)?)?(w(?:eeks?|ks?)?)?(y(?:ears?|rs?)?)?$/, + SEC = 1e3, + MIN = SEC * 60, + HOUR = MIN * 60, + DAY = HOUR * 24, + YEAR = DAY * 365.25; + +function parse(val) { + var num, arr = val.toLowerCase().match(RGX); + if (arr != null && (num = parseFloat(arr[1]))) { + if (arr[3] != null) return num * SEC; + if (arr[4] != null) return num * MIN; + if (arr[5] != null) return num * HOUR; + if (arr[6] != null) return num * DAY; + if (arr[7] != null) return num * DAY * 7; + if (arr[8] != null) return num * YEAR; + return num; + } +} + +function fmt(val, pfx, str, long) { + var num = (val | 0) === val ? val : ~~(val + 0.5); + return pfx + num + (long ? (' ' + str + (num != 1 ? 's' : '')) : str[0]); +} + +function format(num, long) { + var pfx = num < 0 ? '-' : '', abs = num < 0 ? -num : num; + if (abs < SEC) return num + (long ? ' ms' : 'ms'); + if (abs < MIN) return fmt(abs / SEC, pfx, 'second', long); + if (abs < HOUR) return fmt(abs / MIN, pfx, 'minute', long); + if (abs < DAY) return fmt(abs / HOUR, pfx, 'hour', long); + if (abs < YEAR) return fmt(abs / DAY, pfx, 'day', long); + return fmt(abs / YEAR, pfx, 'year', long); +} + +exports.format = format; +exports.parse = parse; \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@lukeed/ms/dist/index.min.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@lukeed/ms/dist/index.min.js new file mode 100644 index 0000000000000000000000000000000000000000..d05cff52d1b4b00e235de0cb2da0c78d113740c9 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@lukeed/ms/dist/index.min.js @@ -0,0 +1 @@ +!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n(e.ms={})}(this,(function(e){var n=/^(-?(?:\d+)?\.?\d+) *(m(?:illiseconds?|s(?:ecs?)?))?(s(?:ec(?:onds?|s)?)?)?(m(?:in(?:utes?|s)?)?)?(h(?:ours?|rs?)?)?(d(?:ays?)?)?(w(?:eeks?|ks?)?)?(y(?:ears?|rs?)?)?$/,s=864e5,o=365.25*s;function r(e,n,s,o){var r=(0|e)===e?e:~~(e+.5);return n+r+(o?" "+s+(1!=r?"s":""):s[0])}e.format=function(e,n){var t=e<0?"-":"",u=e<0?-e:e;return u<1e3?e+(n?" ms":"ms"):u<6e4?r(u/1e3,t,"second",n):u<36e5?r(u/6e4,t,"minute",n):u (lukeed.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@lukeed/ms/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@lukeed/ms/package.json new file mode 100644 index 0000000000000000000000000000000000000000..142a7a933564e154a113b362205e393b198cc8f4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@lukeed/ms/package.json @@ -0,0 +1,48 @@ +{ + "umd:name": "ms", + "version": "2.0.2", + "name": "@lukeed/ms", + "repository": "lukeed/ms", + "description": "A tiny (414B) and fast utility to convert milliseconds to and from strings.", + "unpkg": "dist/index.min.js", + "module": "dist/index.mjs", + "main": "dist/index.js", + "types": "index.d.ts", + "license": "MIT", + "author": { + "name": "Luke Edwards", + "email": "luke.edwards05@gmail.com", + "url": "https://lukeed.com" + }, + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "build": "bundt", + "test": "uvu -r esm test" + }, + "files": [ + "*.d.ts", + "dist" + ], + "keywords": [ + "ms", + "time", + "format", + "milliseconds", + "convert" + ], + "devDependencies": { + "bundt": "1.1.2", + "esm": "3.2.25", + "uvu": "0.5.1" + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@lukeed/ms/readme.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@lukeed/ms/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..d1e2994d23edacbabaf5dabbc1f2b1dfc7782580 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@lukeed/ms/readme.md @@ -0,0 +1,133 @@ +# ms [![CI](https://github.com/lukeed/ms/workflows/CI/badge.svg)](https://github.com/lukeed/ms/actions) [![codecov](https://badgen.net/codecov/c/github/lukeed/ms)](https://codecov.io/gh/lukeed/ms) + +> A tiny (414B) and [fast](#benchmarks) utility to convert milliseconds to and from strings. + +--- + +***NOTICE:** This is a fork of [vercel/ms](https://github.com/vercel/ms)!*
+In June 2019, I [opened a PR](https://github.com/zeit/ms/pull/120) with signficiant performance and code size improvements. After nearly 2 years of silence, it was eventually closed. :cry: A year into my wait, I started anew (this repo), hoping to improve upon my own improvements. + +--- + +This module is delivered as: + +* **CommonJS**: [`dist/index.js`](https://unpkg.com/@lukeed/ms/dist/index.js) +* **ES Module**: [`dist/index.mjs`](https://unpkg.com/@lukeed/ms/dist/index.mjs) +* **UMD**: [`dist/index.min.js`](https://unpkg.com/@lukeed/ms/dist/index.min.js) + +## Install + +``` +$ npm install --save @lukeed/ms +``` + + +## Usage + +```js +import { parse, format } from '@lukeed/ms'; + +// string => number +parse('2 days'); //=> 172800000 +parse('1d'); //=> 86400000 +parse('10h'); //=> 36000000 +parse('2.5 hrs'); //=> 9000000 +parse('2h'); //=> 7200000 +parse('1m'); //=> 60000 +parse('5s'); //=> 5000 +parse('1y'); //=> 31557600000 +parse('100'); //=> 100 +parse('-3 days'); //=> -259200000 +parse('-1h'); //=> -3600000 +parse('-200'); //=> -200 + +// number => string +format(60000); //=> '1m' +format(2 * 60000); //=> '2m' +format(-3 * 60000); //=> '-3m' +format(parse('10 hours')); //=> '10h' + +// number => string (long) +format(60000, true); //=> '1 minute' +format(2 * 60000, true); //=> '2 minutes' +format(-3 * 60000, true); //=> '-3 minutes' +format(parse('10 hours'), true); //=> '10 hours' +``` + + +## API + +### ms.parse(input) +Returns: `Number` + +Parses the input string, returning the number of milliseconds. + +#### input +Type: `String` + +The human-readable time string; eg: `10min`, `10m`, `10 minutes`. + + +### ms.format(milli, long?) +Returns: `Number` + +Formats the millisecond count to a human-readable time string. + +> **Important:** The output will be rounded to the nearest whole integer. + +#### milli +Type: `Number` + +The number of milliseconds. + +#### long +Type: `Boolean`
+Default: `false` + +Whether or not the output should use the interval's long/full form; eg `hour` or `hours` instead of `h`. + +> **Note:** When `long`, the count and interval will be separated by a single space.
Also, when `long`, the interval may be pluralized; eg `1 second` vs `2 seconds`. + + +## Benchmarks + +> Running on Node.js v12.18.4 + +``` +Validation :: parse + ✔ lukeed/ms + ✔ zeit/ms + +Benchmark :: "parse" + lukeed/ms x 351,319 ops/sec ±0.31% (96 runs sampled) + zeit/ms x 245,576 ops/sec ±1.66% (94 runs sampled) + +Benchmark :: "parse" (long) + lukeed/ms x 335,538 ops/sec ±0.50% (94 runs sampled) + zeit/ms x 265,410 ops/sec ±1.72% (95 runs sampled) + + +Validation :: format + ✔ lukeed/ms + ✔ zeit/ms + +Benchmark :: "format" + lukeed/ms x 4,109,440 ops/sec ±0.35% (94 runs sampled) + zeit/ms x 3,420,198 ops/sec ±1.61% (94 runs sampled) + +Benchmark :: "format" (long) + lukeed/ms x 3,402,872 ops/sec ±0.14% (97 runs sampled) + zeit/ms x 1,344,908 ops/sec ±3.68% (96 runs sampled) +``` + + +## Credits + +This is obviously a fork of [zeit/ms](https://github.com/zeit/ms). + +I opened a [PR in June 2019](https://github.com/zeit/ms/pull/120) that introduced significant performance gains and code reduction — it was ignored for nearly two years. This repository is a from-scratch re-implementation that takes the goals of that PR a bit further. + + +## License + +MIT © [Luke Edwards](https://lukeed.com) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/.eslintrc.cjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/.eslintrc.cjs new file mode 100644 index 0000000000000000000000000000000000000000..7c1cc302ee5fb723880eb5eaad588e53430ad98e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/.eslintrc.cjs @@ -0,0 +1,19 @@ +module.exports = { + root: true, + env: { + node: true, + }, + extends: [ + "eslint:recommended", + "plugin:@typescript-eslint/recommended", + ], + parser: "@typescript-eslint/parser", + parserOptions: { + ecmaVersion: 2020, + sourceType: "module", + }, + rules: { + "@typescript-eslint/no-unused-vars": "warn", + "@typescript-eslint/no-explicit-any": "warn", + }, +}; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/CONTRIBUTING.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..7360d63274a9a40d2d78e8ff74aa88542bcb803d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/CONTRIBUTING.md @@ -0,0 +1,51 @@ +# Contributing to LLMs + +Thank you for your interest in contributing! Please follow these guidelines to ensure smooth collaboration. + +## Development Environment + +- Node.js 18+ +- Recommended package manager: npm or pnpm +- Recommended editor: VSCode + TypeScript plugin + +## Branch & PR Guidelines + +- Create feature/bugfix branches from the latest `main` branch. +- Each feature/fix should be in a separate branch, avoid mixing unrelated changes. +- PR titles should be concise; descriptions must state the purpose, scope, and testing method. +- Ensure local build and tests pass before submitting a PR. + +## Code Style + +- Strict TypeScript mode. +- 2-space indentation. +- Prefer `@/` alias for imports. +- Keep comments clear and up-to-date. + +## Commit Message Convention + +- feat: new feature +- fix: bug fix +- docs: documentation +- refactor: refactor +- test: test related +- chore: build/deps/chore + +## Testing + +- Add/modify unit tests for new/changed features. +- Run `npm test` to ensure all tests pass. + +## Review Process + +- PRs will be reviewed by maintainers/reviewers. +- Address review comments promptly. +- Only merge after approval. + +## FAQ + +- Path alias not working? Check `tsconfig.json` and ensure your runtime supports it. +- Dependency install failed? Try switching npm/pnpm registry or upgrading Node. +- For other issues, please open an issue. + +--- diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/README.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ced4d13479fd0d731510f6d8e3604e7dcf05d109 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/README.md @@ -0,0 +1,74 @@ +# LLMs + +> A universal LLM API transformation server, initially developed for the [claude-code-router](https://github.com/musistudio/claude-code-router). + +## How it works + +The LLM API transformation server acts as a middleware to standardize requests and responses between different LLM providers (Anthropic, Gemini, Deepseek, etc.). It uses a modular transformer system to handle provider-specific API formats. + +### Key Components + +1. **Transformers**: Each provider (e.g., Anthropic, Gemini) has a dedicated transformer class that implements: + + - `transformRequestIn`: Converts the provider's request format to a unified format. + - `transformResponseIn`: Converts the provider's response format to a unified format. + - `transformRequestOut`: Converts the unified request format to the provider's format. + - `transformResponseOut`: Converts the unified response format back to the provider's format. + - `endPoint`: Specifies the API endpoint for the provider (e.g., "/v1/messages" for Anthropic). + +2. **Unified Formats**: + + - Requests and responses are standardized using `UnifiedChatRequest` and `UnifiedChatResponse` types. + +3. **Streaming Support**: + - Handles real-time streaming responses for providers like Anthropic, converting chunked data into a standardized format. + +### Data Flow + +1. **Request**: + + - Incoming provider-specific requests are transformed into the unified format. + - The unified request is processed by the server. + +2. **Response**: + - The server's unified response is transformed back into the provider's format. + - Streaming responses are handled with chunked data conversion. + +### Example Transformers + +- **Anthropic**: Converts between OpenAI-style and Anthropic-style message formats. +- **Gemini**: Adjusts tool definitions and parameter formats for Gemini compatibility. +- **Deepseek**: Enforces token limits and handles reasoning content in streams. + +## Run this repo + +- **Install dependencies:** + ```sh + npm install + # or pnpm install + ``` +- **Development:** + ```sh + npm run dev + # Uses nodemon + tsx for hot-reloading src/server.ts + ``` +- **Build:** + ```sh + npm run build + # Outputs to dist/cjs and dist/esm + ``` +- **Test:** + ```sh + npm test + # See CLAUDE.md for details + ``` +- **Path alias:** + - `@` is mapped to the `src` directory, use `import xxx from '@/xxx'`. +- **Environment variables:** + - Supports `.env` and `config.json`, see `src/services/config.ts`. + +--- + +## Working with this repo + +[👉 Contributing Guide](./CONTRIBUTING.md) diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/pino-file.cjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/pino-file.cjs new file mode 100644 index 0000000000000000000000000000000000000000..d34a55d3dceffa07d41c1346c3a1639562376e7c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/pino-file.cjs @@ -0,0 +1,103 @@ +"use strict";var x=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var _e=x((Tf,wt)=>{"use strict";var Y=e=>e&&typeof e.message=="string",Se=e=>{if(!e)return;let t=e.cause;if(typeof t=="function"){let r=e.cause();return Y(r)?r:void 0}else return Y(t)?t:void 0},pt=(e,t)=>{if(!Y(e))return"";let r=e.stack||"";if(t.has(e))return r+` +causes have become circular...`;let n=Se(e);return n?(t.add(e),r+` +caused by: `+pt(n,t)):r},kn=e=>pt(e,new Set),bt=(e,t,r)=>{if(!Y(e))return"";let n=r?"":e.message||"";if(t.has(e))return n+": ...";let i=Se(e);if(i){t.add(e);let o=typeof e.cause=="function";return n+(o?"":": ")+bt(i,t,o)}else return n},Rn=e=>bt(e,new Set);wt.exports={isErrorLike:Y,getErrorCause:Se,stackWithCauses:kn,messageWithCauses:Rn}});var Ee=x((kf,_t)=>{"use strict";var Bn=Symbol("circular-ref-tag"),te=Symbol("pino-raw-err-ref"),St=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[te]},set:function(e){this[te]=e}}});Object.defineProperty(St,te,{writable:!0,value:{}});_t.exports={pinoErrProto:St,pinoErrorSymbols:{seen:Bn,rawSymbol:te}}});var xt=x((Rf,Ot)=>{"use strict";Ot.exports=xe;var{messageWithCauses:In,stackWithCauses:qn,isErrorLike:Et}=_e(),{pinoErrProto:Cn,pinoErrorSymbols:Nn}=Ee(),{seen:Oe}=Nn,{toString:Dn}=Object.prototype;function xe(e){if(!Et(e))return e;e[Oe]=void 0;let t=Object.create(Cn);t.type=Dn.call(e.constructor)==="[object Function]"?e.constructor.name:e.name,t.message=In(e),t.stack=qn(e),Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(r=>xe(r)));for(let r in e)if(t[r]===void 0){let n=e[r];Et(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,Oe)&&(t[r]=xe(n)):t[r]=n}return delete e[Oe],t.raw=e,t}});var Lt=x((Bf,vt)=>{"use strict";vt.exports=ne;var{isErrorLike:ve}=_e(),{pinoErrProto:Pn,pinoErrorSymbols:zn}=Ee(),{seen:re}=zn,{toString:Wn}=Object.prototype;function ne(e){if(!ve(e))return e;e[re]=void 0;let t=Object.create(Pn);t.type=Wn.call(e.constructor)==="[object Function]"?e.constructor.name:e.name,t.message=e.message,t.stack=e.stack,Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(r=>ne(r))),ve(e.cause)&&!Object.prototype.hasOwnProperty.call(e.cause,re)&&(t.cause=ne(e.cause));for(let r in e)if(t[r]===void 0){let n=e[r];ve(n)?Object.prototype.hasOwnProperty.call(n,re)||(t[r]=ne(n)):t[r]=n}return delete e[re],t.raw=e,t}});var Tt=x((If,jt)=>{"use strict";jt.exports={mapHttpRequest:Mn,reqSerializer:At};var Le=Symbol("pino-raw-req-ref"),$t=Object.create({},{id:{enumerable:!0,writable:!0,value:""},method:{enumerable:!0,writable:!0,value:""},url:{enumerable:!0,writable:!0,value:""},query:{enumerable:!0,writable:!0,value:""},params:{enumerable:!0,writable:!0,value:""},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:""},remotePort:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Le]},set:function(e){this[Le]=e}}});Object.defineProperty($t,Le,{writable:!0,value:{}});function At(e){let t=e.info||e.socket,r=Object.create($t);if(r.id=typeof e.id=="function"?e.id():e.id||(e.info?e.info.id:void 0),r.method=e.method,e.originalUrl)r.url=e.originalUrl;else{let n=e.path;r.url=typeof n=="string"?n:e.url?e.url.path||e.url:void 0}return e.query&&(r.query=e.query),e.params&&(r.params=e.params),r.headers=e.headers,r.remoteAddress=t&&t.remoteAddress,r.remotePort=t&&t.remotePort,r.raw=e.raw||e,r}function Mn(e){return{req:At(e)}}});var It=x((qf,Bt)=>{"use strict";Bt.exports={mapHttpResponse:Fn,resSerializer:Rt};var $e=Symbol("pino-raw-res-ref"),kt=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[$e]},set:function(e){this[$e]=e}}});Object.defineProperty(kt,$e,{writable:!0,value:{}});function Rt(e){let t=Object.create(kt);return t.statusCode=e.headersSent?e.statusCode:null,t.headers=e.getHeaders?e.getHeaders():e._headers,t.raw=e,t}function Fn(e){return{res:Rt(e)}}});var je=x((Cf,qt)=>{"use strict";var Ae=xt(),Vn=Lt(),ie=Tt(),se=It();qt.exports={err:Ae,errWithCause:Vn,mapHttpRequest:ie.mapHttpRequest,mapHttpResponse:se.mapHttpResponse,req:ie.reqSerializer,res:se.resSerializer,wrapErrorSerializer:function(t){return t===Ae?t:function(n){return t(Ae(n))}},wrapRequestSerializer:function(t){return t===ie.reqSerializer?t:function(n){return t(ie.reqSerializer(n))}},wrapResponseSerializer:function(t){return t===se.resSerializer?t:function(n){return t(se.resSerializer(n))}}}});var Te=x((Nf,Ct)=>{"use strict";function Kn(e,t){return t}Ct.exports=function(){let t=Error.prepareStackTrace;Error.prepareStackTrace=Kn;let r=new Error().stack;if(Error.prepareStackTrace=t,!Array.isArray(r))return;let n=r.slice(2),i=[];for(let o of n)o&&i.push(o.getFileName());return i}});var Dt=x((Df,Nt)=>{"use strict";Nt.exports=Jn;function Jn(e={}){let{ERR_PATHS_MUST_BE_STRINGS:t=()=>"fast-redact - Paths must be (non-empty) strings",ERR_INVALID_PATH:r=n=>`fast-redact \u2013 Invalid path (${n})`}=e;return function({paths:i}){i.forEach(o=>{if(typeof o!="string")throw Error(t());try{if(/〇/.test(o))throw Error();let f=(o[0]==="["?"":".")+o.replace(/^\*/,"\u3007").replace(/\.\*/g,".\u3007").replace(/\[\*\]/g,"[\u3007]");if(/\n|\r|;/.test(f)||/\/\*/.test(f))throw Error();Function(` + 'use strict' + const o = new Proxy({}, { get: () => o, set: () => { throw Error() } }); + const \u3007 = null; + o${f} + if ([o${f}].length !== 1) throw Error()`)()}catch{throw Error(r(o))}})}}});var oe=x((Pf,Pt)=>{"use strict";Pt.exports=/[^.[\]]+|\[((?:.)*?)\]/g});var Wt=x((zf,zt)=>{"use strict";var Un=oe();zt.exports=Gn;function Gn({paths:e}){let t=[];var r=0;let n=e.reduce(function(i,o,f){var c=o.match(Un).map(h=>h.replace(/'|"|`/g,""));let d=o[0]==="[";c=c.map(h=>h[0]==="["?h.substr(1,h.length-2):h);let y=c.indexOf("*");if(y>-1){let h=c.slice(0,y),l=h.join("."),p=c.slice(y+1,c.length),u=p.length>0;r++,t.push({before:h,beforeStr:l,after:p,nested:u})}else i[o]={path:c,val:void 0,precensored:!1,circle:"",escPath:JSON.stringify(o),leadingBracket:d};return i},{});return{wildcards:t,wcLen:r,secret:n}}});var Ft=x((Wf,Mt)=>{"use strict";var Hn=oe();Mt.exports=Xn;function Xn({secret:e,serialize:t,wcLen:r,strict:n,isCensorFct:i,censorFctTakesPath:o},f){let c=Function("o",` + if (typeof o !== 'object' || o == null) { + ${ei(n,t)} + } + const { censor, secret } = this + const originalSecret = {} + const secretKeys = Object.keys(secret) + for (var i = 0; i < secretKeys.length; i++) { + originalSecret[secretKeys[i]] = secret[secretKeys[i]] + } + + ${Yn(e,i,o)} + this.compileRestore() + ${Qn(r>0,i,o)} + this.secret = originalSecret + ${Zn(t)} + `).bind(f);return c.state=f,t===!1&&(c.restore=d=>f.restore(d)),c}function Yn(e,t,r){return Object.keys(e).map(n=>{let{escPath:i,leadingBracket:o,path:f}=e[n],c=o?1:0,d=o?"":".",y=[];for(var h;(h=Hn.exec(n))!==null;){let[,s]=h,{index:m,input:g}=h;m>c&&y.push(g.substring(0,m-(s?0:1)))}var l=y.map(s=>`o${d}${s}`).join(" && ");l.length===0?l+=`o${d}${n} != null`:l+=` && o${d}${n} != null`;let p=` + switch (true) { + ${y.reverse().map(s=>` + case o${d}${s} === censor: + secret[${i}].circle = ${JSON.stringify(s)} + break + `).join(` +`)} + } + `,u=r?`val, ${JSON.stringify(f)}`:"val";return` + if (${l}) { + const val = o${d}${n} + if (val === censor) { + secret[${i}].precensored = true + } else { + secret[${i}].val = val + o${d}${n} = ${t?`censor(${u})`:"censor"} + ${p} + } + } + `}).join(` +`)}function Qn(e,t,r){return e===!0?` + { + const { wildcards, wcLen, groupRedact, nestedRedact } = this + for (var i = 0; i < wcLen; i++) { + const { before, beforeStr, after, nested } = wildcards[i] + if (nested === true) { + secret[beforeStr] = secret[beforeStr] || [] + nestedRedact(secret[beforeStr], o, before, after, censor, ${t}, ${r}) + } else secret[beforeStr] = groupRedact(o, before, censor, ${t}, ${r}) + } + } + `:""}function Zn(e){return e===!1?"return o":` + var s = this.serialize(o) + this.restore(o) + return s + `}function ei(e,t){return e===!0?"throw Error('fast-redact: primitives cannot be redacted')":t===!1?"return o":"return this.serialize(o)"}});var Re=x((Mf,Jt)=>{"use strict";Jt.exports={groupRedact:ri,groupRestore:ti,nestedRedact:ii,nestedRestore:ni};function ti({keys:e,values:t,target:r}){if(r==null||typeof r=="string")return;let n=e.length;for(var i=0;i0;f--)o=o[n[f]];o[n[0]]=i}}function ii(e,t,r,n,i,o,f){let c=Vt(t,r);if(c==null)return;let d=Object.keys(c),y=d.length;for(var h=0;h{"use strict";var{groupRestore:li,nestedRestore:fi}=Re();Ut.exports=ci;function ci(){return function(){if(this.restore){this.restore.state.secret=this.secret;return}let{secret:t,wcLen:r}=this,n=Object.keys(t),i=ui(t,n),o=r>0,f=o?{secret:t,groupRestore:li,nestedRestore:fi}:{secret:t};this.restore=Function("o",ai(i,n,o)).bind(f),this.restore.state=f}}function ui(e,t){return t.map(r=>{let{circle:n,escPath:i,leadingBracket:o}=e[r],c=n?`o.${n} = secret[${i}].val`:`o${o?"":"."}${r} = secret[${i}].val`,d=`secret[${i}].val = undefined`;return` + if (secret[${i}].val !== undefined) { + try { ${c} } catch (e) {} + ${d} + } + `}).join("")}function ai(e,t,r){return` + const secret = this.secret + ${r===!0?` + const keys = Object.keys(secret) + const len = keys.length + for (var i = len - 1; i >= ${t.length}; i--) { + const k = keys[i] + const o = secret[k] + if (o) { + if (o.flat === true) this.groupRestore(o) + else this.nestedRestore(o) + secret[k] = null + } + } + `:""} + ${e} + return o + `}});var Xt=x((Vf,Ht)=>{"use strict";Ht.exports=hi;function hi(e){let{secret:t,censor:r,compileRestore:n,serialize:i,groupRedact:o,nestedRedact:f,wildcards:c,wcLen:d}=e,y=[{secret:t,censor:r,compileRestore:n}];return i!==!1&&y.push({serialize:i}),d>0&&y.push({groupRedact:o,nestedRedact:f,wildcards:c,wcLen:d}),Object.assign(...y)}});var Zt=x((Kf,Qt)=>{"use strict";var Yt=Dt(),di=Wt(),yi=Ft(),gi=Gt(),{groupRedact:mi,nestedRedact:pi}=Re(),bi=Xt(),wi=oe(),Si=Yt(),Be=e=>e;Be.restore=Be;var _i="[REDACTED]";Ie.rx=wi;Ie.validator=Yt;Qt.exports=Ie;function Ie(e={}){let t=Array.from(new Set(e.paths||[])),r="serialize"in e&&(e.serialize===!1||typeof e.serialize=="function")?e.serialize:JSON.stringify,n=e.remove;if(n===!0&&r!==JSON.stringify)throw Error("fast-redact \u2013 remove option may only be set when serializer is JSON.stringify");let i=n===!0?void 0:"censor"in e?e.censor:_i,o=typeof i=="function",f=o&&i.length>1;if(t.length===0)return r||Be;Si({paths:t,serialize:r,censor:i});let{wildcards:c,wcLen:d,secret:y}=di({paths:t,censor:i}),h=gi(),l="strict"in e?e.strict:!0;return yi({secret:y,wcLen:d,serialize:r,strict:l,isCensorFct:o,censorFctTakesPath:f},bi({secret:y,censor:i,compileRestore:h,serialize:r,groupRedact:mi,nestedRedact:pi,wildcards:c,wcLen:d}))}});var G=x((Jf,er)=>{"use strict";var Ei=Symbol("pino.setLevel"),Oi=Symbol("pino.getLevel"),xi=Symbol("pino.levelVal"),vi=Symbol("pino.levelComp"),Li=Symbol("pino.useLevelLabels"),$i=Symbol("pino.useOnlyCustomLevels"),Ai=Symbol("pino.mixin"),ji=Symbol("pino.lsCache"),Ti=Symbol("pino.chindings"),ki=Symbol("pino.asJson"),Ri=Symbol("pino.write"),Bi=Symbol("pino.redactFmt"),Ii=Symbol("pino.time"),qi=Symbol("pino.timeSliceIndex"),Ci=Symbol("pino.stream"),Ni=Symbol("pino.stringify"),Di=Symbol("pino.stringifySafe"),Pi=Symbol("pino.stringifiers"),zi=Symbol("pino.end"),Wi=Symbol("pino.formatOpts"),Mi=Symbol("pino.messageKey"),Fi=Symbol("pino.errorKey"),Vi=Symbol("pino.nestedKey"),Ki=Symbol("pino.nestedKeyStr"),Ji=Symbol("pino.mixinMergeStrategy"),Ui=Symbol("pino.msgPrefix"),Gi=Symbol("pino.wildcardFirst"),Hi=Symbol.for("pino.serializers"),Xi=Symbol.for("pino.formatters"),Yi=Symbol.for("pino.hooks"),Qi=Symbol.for("pino.metadata");er.exports={setLevelSym:Ei,getLevelSym:Oi,levelValSym:xi,levelCompSym:vi,useLevelLabelsSym:Li,mixinSym:Ai,lsCacheSym:ji,chindingsSym:Ti,asJsonSym:ki,writeSym:Ri,serializersSym:Hi,redactFmtSym:Bi,timeSym:Ii,timeSliceIndexSym:qi,streamSym:Ci,stringifySym:Ni,stringifySafeSym:Di,stringifiersSym:Pi,endSym:zi,formatOptsSym:Wi,messageKeySym:Mi,errorKeySym:Fi,nestedKeySym:Vi,wildcardFirstSym:Gi,needsMetadataGsym:Qi,useOnlyCustomLevelsSym:$i,formattersSym:Xi,hooksSym:Yi,nestedKeyStrSym:Ki,mixinMergeStrategySym:Ji,msgPrefixSym:Ui}});var Ne=x((Uf,ir)=>{"use strict";var Ce=Zt(),{redactFmtSym:Zi,wildcardFirstSym:le}=G(),{rx:qe,validator:es}=Ce,tr=es({ERR_PATHS_MUST_BE_STRINGS:()=>"pino \u2013 redacted paths must be strings",ERR_INVALID_PATH:e=>`pino \u2013 redact paths array contains an invalid path (${e})`}),rr="[Redacted]",nr=!1;function ts(e,t){let{paths:r,censor:n}=rs(e),i=r.reduce((c,d)=>{qe.lastIndex=0;let y=qe.exec(d),h=qe.exec(d),l=y[1]!==void 0?y[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):y[0];if(l==="*"&&(l=le),h===null)return c[l]=null,c;if(c[l]===null)return c;let{index:p}=h,u=`${d.substr(p,d.length-1)}`;return c[l]=c[l]||[],l!==le&&c[l].length===0&&c[l].push(...c[le]||[]),l===le&&Object.keys(c).forEach(function(s){c[s]&&c[s].push(u)}),c[l].push(u),c},{}),o={[Zi]:Ce({paths:r,censor:n,serialize:t,strict:nr})},f=(...c)=>t(typeof n=="function"?n(...c):n);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((c,d)=>{if(i[d]===null)c[d]=y=>f(y,[d]);else{let y=typeof n=="function"?(h,l)=>n(h,[d,...l]):n;c[d]=Ce({paths:i[d],censor:y,serialize:t,strict:nr})}return c},o)}function rs(e){if(Array.isArray(e))return e={paths:e,censor:rr},tr(e),e;let{paths:t,censor:r=rr,remove:n}=e;if(Array.isArray(t)===!1)throw Error("pino \u2013 redact must contain an array of strings");return n===!0&&(r=void 0),tr({paths:t,censor:r}),{paths:t,censor:r}}ir.exports=ts});var or=x((Gf,sr)=>{"use strict";var ns=()=>"",is=()=>`,"time":${Date.now()}`,ss=()=>`,"time":${Math.round(Date.now()/1e3)}`,os=()=>`,"time":"${new Date(Date.now()).toISOString()}"`;sr.exports={nullTime:ns,epochTime:is,unixTime:ss,isoTime:os}});var fr=x((Hf,lr)=>{"use strict";function ls(e){try{return JSON.stringify(e)}catch{return'"[Circular]"'}}lr.exports=fs;function fs(e,t,r){var n=r&&r.stringify||ls,i=1;if(typeof e=="object"&&e!==null){var o=t.length+i;if(o===1)return e;var f=new Array(o);f[0]=n(e);for(var c=1;c-1?l:0,e.charCodeAt(u+1)){case 100:case 102:if(h>=d||t[h]==null)break;l=d||t[h]==null)break;l=d||t[h]===void 0)break;l",l=u+2,u++;break}y+=n(t[h]),l=u+2,u++;break;case 115:if(h>=d)break;l{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let t=function(r){if((r>0&&r<1/0)===!1)throw typeof r!="number"&&typeof r!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(e,0,0,Number(r))},e=new Int32Array(new SharedArrayBuffer(4));De.exports=t}else{let e=function(t){if((t>0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let n=Date.now()+Number(t);for(;n>Date.now(););};De.exports=e}});var mr=x((Yf,gr)=>{"use strict";var j=require("fs"),cs=require("events"),us=require("util").inherits,cr=require("path"),We=Pe(),as=require("assert"),fe=100,ce=Buffer.allocUnsafe(0),hs=16*1024,ur="buffer",ar="utf8",[ds,ys]=(process.versions.node||"0.0").split(".").map(Number),gs=ds>=22&&ys>=7;function hr(e,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function r(o,f){if(o){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount("error")>0&&t.emit("error",o)}):t.emit("error",o);return}let c=t._reopening;t.fd=f,t.file=e,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit("ready")):t.emit("ready"),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():c&&process.nextTick(()=>t.emit("drain")))}let n=t.append?"a":"w",i=t.mode;if(t.sync)try{t.mkdir&&j.mkdirSync(cr.dirname(e),{recursive:!0});let o=j.openSync(e,n,i);r(null,o)}catch(o){throw r(o),o}else t.mkdir?j.mkdir(cr.dirname(e),{recursive:!0},o=>{if(o)return r(o);j.open(e,n,i,r)}):j.open(e,n,i,r)}function C(e){if(!(this instanceof C))return new C(e);let{fd:t,dest:r,minLength:n,maxLength:i,maxWrite:o,periodicFlush:f,sync:c,append:d=!0,mkdir:y,retryEAGAIN:h,fsync:l,contentMode:p,mode:u}=e||{};t=t||r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(n||0,16387),this.file=null,this.destroyed=!1,this.minLength=n||0,this.maxLength=i||0,this.maxWrite=o||hs,this._periodicFlush=f||0,this._periodicFlushTimer=void 0,this.sync=c||!1,this.writable=!0,this._fsync=l||!1,this.append=d||!1,this.mode=u,this.retryEAGAIN=h||(()=>!0),this.mkdir=y||!1;let s,m;if(p===ur)this._writingBuf=ce,this.write=bs,this.flush=Ss,this.flushSync=Es,this._actualWrite=xs,s=()=>j.writeSync(this.fd,this._writingBuf),m=()=>j.write(this.fd,this._writingBuf,this.release);else if(p===void 0||p===ar)this._writingBuf="",this.write=ps,this.flush=ws,this.flushSync=_s,this._actualWrite=Os,s=()=>j.writeSync(this.fd,this._writingBuf,"utf8"),m=()=>j.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${ar}" and "${ur}", but passed ${p}`);if(typeof t=="number")this.fd=t,process.nextTick(()=>this.emit("ready"));else if(typeof t=="string")hr(t,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(g,S)=>{if(g){if((g.code==="EAGAIN"||g.code==="EBUSY")&&this.retryEAGAIN(g,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{We(fe),this.release(void 0,0)}catch(_){this.release(_)}else setTimeout(m,fe);else this._writing=!1,this.emit("error",g);return}this.emit("write",S);let b=ze(this._writingBuf,this._len,S);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){m();return}try{do{let _=s(),O=ze(this._writingBuf,this._len,_);this._len=O.len,this._writingBuf=O.writingBuf}while(this._writingBuf.length)}catch(_){this.release(_);return}}this._fsync&&j.fsyncSync(this.fd);let w=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):w>this.minLength?this._actualWrite():this._ending?w>0?this._actualWrite():(this._writing=!1,ue(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(ms,this)):this.emit("drain"))},this.on("newListener",function(g){g==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function ze(e,t,r){return typeof e=="string"&&Buffer.byteLength(e)!==r&&(r=Buffer.from(e).subarray(0,r).toString().length),t=Math.max(t-r,0),e=e.slice(r),{writingBuf:e,len:t}}function ms(e){e.listenerCount("drain")>0&&(e._asyncDrainScheduled=!1,e.emit("drain"))}us(C,cs);function dr(e,t){return e.length===0?ce:e.length===1?e[0]:Buffer.concat(e,t)}function ps(e){if(this.destroyed)throw new Error("SonicBoom destroyed");let t=this._len+e.length,r=this._bufs;return this.maxLength&&t>this.maxLength?(this.emit("drop",e),this._lenthis.maxWrite?r.push(""+e):r[r.length-1]+=e,this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._lenthis.maxLength?(this.emit("drop",e),this._lenthis.maxWrite?(r.push([e]),n.push(e.length)):(r[r.length-1].push(e),n[n.length-1]+=e.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len{if(this._fsync)this._flushPending=!1,e();else try{j.fsync(this.fd,n=>{this._flushPending=!1,e(n)})}catch(n){e(n)}this.off("error",r)},r=n=>{this._flushPending=!1,e(n),this.off("drain",t)};this.once("drain",t),this.once("error",r)}function ws(e){if(e!=null&&typeof e!="function")throw new Error("flush cb must be a function");if(this.destroyed){let t=new Error("SonicBoom destroyed");if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&yr.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function Ss(e){if(e!=null&&typeof e!="function")throw new Error("flush cb must be a function");if(this.destroyed){let t=new Error("SonicBoom destroyed");if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&yr.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}C.prototype.reopen=function(e){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(e&&(this.file=e),this._reopening=!0,this._writing)return;let t=this.fd;this.once("ready",()=>{t!==this.fd&&j.close(t,r=>{if(r)return this.emit("error",r)})}),hr(this.file,this)};C.prototype.end=function(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():ue(this)))};function _s(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let e="";for(;this._bufs.length||e;){e.length<=0&&(e=this._bufs[0]);try{let t=j.writeSync(this.fd,e,"utf8"),r=ze(e,this._len,t);e=r.writingBuf,this._len=r.len,e.length<=0&&this._bufs.shift()}catch(t){if((t.code==="EAGAIN"||t.code==="EBUSY")&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;We(fe)}}try{j.fsyncSync(this.fd)}catch{}}function Es(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=ce);let e=ce;for(;this._bufs.length||e.length;){e.length<=0&&(e=dr(this._bufs[0],this._lens[0]));try{let t=j.writeSync(this.fd,e);e=e.subarray(t),this._len=Math.max(this._len-t,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code==="EAGAIN"||t.code==="EBUSY")&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;We(fe)}}}C.prototype.destroy=function(){this.destroyed||ue(this)};function Os(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf||this._bufs.shift()||"",this.sync)try{let t=j.writeSync(this.fd,this._writingBuf,"utf8");e(null,t)}catch(t){e(t)}else j.write(this.fd,this._writingBuf,"utf8",e)}function xs(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:dr(this._bufs.shift(),this._lens.shift()),this.sync)try{let t=j.writeSync(this.fd,this._writingBuf);e(null,t)}catch(t){e(t)}else gs&&(this._writingBuf=Buffer.from(this._writingBuf)),j.write(this.fd,this._writingBuf,e)}function ue(e){if(e.fd===-1){e.once("ready",ue.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],as(typeof e.fd=="number",`sonic.fd must be a number, got ${typeof e.fd}`);try{j.fsync(e.fd,t)}catch{}function t(){e.fd!==1&&e.fd!==2?j.close(e.fd,r):r()}function r(n){if(n){e.emit("error",n);return}e._ending&&!e._writing&&e.emit("finish"),e.emit("close")}}C.SonicBoom=C;C.default=C;gr.exports=C});var Me=x((Qf,_r)=>{"use strict";var N={exit:[],beforeExit:[]},pr={exit:$s,beforeExit:As},H;function vs(){H===void 0&&(H=new FinalizationRegistry(js))}function Ls(e){N[e].length>0||process.on(e,pr[e])}function br(e){N[e].length>0||(process.removeListener(e,pr[e]),N.exit.length===0&&N.beforeExit.length===0&&(H=void 0))}function $s(){wr("exit")}function As(){wr("beforeExit")}function wr(e){for(let t of N[e]){let r=t.deref(),n=t.fn;r!==void 0&&n(r,e)}N[e]=[]}function js(e){for(let t of["exit","beforeExit"]){let r=N[t].indexOf(e);N[t].splice(r,r+1),br(t)}}function Sr(e,t,r){if(t===void 0)throw new Error("the object can't be undefined");Ls(e);let n=new WeakRef(t);n.fn=r,vs(),H.register(t,n),N[e].push(n)}function Ts(e,t){Sr("exit",e,t)}function ks(e,t){Sr("beforeExit",e,t)}function Rs(e){if(H!==void 0){H.unregister(e);for(let t of["exit","beforeExit"])N[t]=N[t].filter(r=>{let n=r.deref();return n&&n!==e}),br(t)}}_r.exports={register:Ts,registerBeforeExit:ks,unregister:Rs}});var Er=x((Zf,Bs)=>{Bs.exports={name:"thread-stream",version:"3.1.0",description:"A streaming way to send data to a Node.js Worker Thread",main:"index.js",types:"index.d.ts",dependencies:{"real-require":"^0.2.0"},devDependencies:{"@types/node":"^20.1.0","@types/tap":"^15.0.0","@yao-pkg/pkg":"^5.11.5",desm:"^1.3.0",fastbench:"^1.0.1",husky:"^9.0.6","pino-elasticsearch":"^8.0.0","sonic-boom":"^4.0.1",standard:"^17.0.0",tap:"^16.2.0","ts-node":"^10.8.0",typescript:"^5.3.2","why-is-node-running":"^2.2.2"},scripts:{build:"tsc --noEmit",test:'standard && npm run build && npm run transpile && tap "test/**/*.test.*js" && tap --ts test/*.test.*ts',"test:ci":"standard && npm run transpile && npm run test:ci:js && npm run test:ci:ts","test:ci:js":'tap --no-check-coverage --timeout=120 --coverage-report=lcovonly "test/**/*.test.*js"',"test:ci:ts":'tap --ts --no-check-coverage --coverage-report=lcovonly "test/**/*.test.*ts"',"test:yarn":'npm run transpile && tap "test/**/*.test.js" --no-check-coverage',transpile:"sh ./test/ts/transpile.sh",prepare:"husky install"},standard:{ignore:["test/ts/**/*","test/syntax-error.mjs"]},repository:{type:"git",url:"git+https://github.com/mcollina/thread-stream.git"},keywords:["worker","thread","threads","stream"],author:"Matteo Collina ",license:"MIT",bugs:{url:"https://github.com/mcollina/thread-stream/issues"},homepage:"https://github.com/mcollina/thread-stream#readme"}});var xr=x((ec,Or)=>{"use strict";function Is(e,t,r,n,i){let o=Date.now()+n,f=Atomics.load(e,t);if(f===r){i(null,"ok");return}let c=f,d=y=>{Date.now()>o?i(null,"timed-out"):setTimeout(()=>{c=f,f=Atomics.load(e,t),f===c?d(y>=1e3?1e3:y*2):f===r?i(null,"ok"):i(null,"not-equal")},y)};d(1)}function qs(e,t,r,n,i){let o=Date.now()+n,f=Atomics.load(e,t);if(f!==r){i(null,"ok");return}let c=d=>{Date.now()>o?i(null,"timed-out"):setTimeout(()=>{f=Atomics.load(e,t),f!==r?i(null,"ok"):c(d>=1e3?1e3:d*2)},d)};c(1)}Or.exports={wait:Is,waitDiff:qs}});var Lr=x((tc,vr)=>{"use strict";vr.exports={WRITE_INDEX:4,READ_INDEX:8}});var kr=x((rc,Tr)=>{"use strict";var{version:Cs}=Er(),{EventEmitter:Ns}=require("events"),{Worker:Ds}=require("worker_threads"),{join:Ps}=require("path"),{pathToFileURL:zs}=require("url"),{wait:Ws}=xr(),{WRITE_INDEX:R,READ_INDEX:D}=Lr(),Ms=require("buffer"),Fs=require("assert"),a=Symbol("kImpl"),Vs=Ms.constants.MAX_STRING_LENGTH,Z=class{constructor(t){this._value=t}deref(){return this._value}},he=class{register(){}unregister(){}},Ks=process.env.NODE_V8_COVERAGE?he:global.FinalizationRegistry||he,Js=process.env.NODE_V8_COVERAGE?Z:global.WeakRef||Z,$r=new Ks(e=>{e.exited||e.terminate()});function Us(e,t){let{filename:r,workerData:n}=t,o=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||Ps(__dirname,"lib","worker.js"),f=new Ds(o,{...t.workerOpts,trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:zs(r).href,dataBuf:e[a].dataBuf,stateBuf:e[a].stateBuf,workerData:{$context:{threadStreamVersion:Cs},...n}}});return f.stream=new Z(e),f.on("message",Gs),f.on("exit",jr),$r.register(e,f),f}function Ar(e){Fs(!e[a].sync),e[a].needDrain&&(e[a].needDrain=!1,e.emit("drain"))}function ae(e){let t=Atomics.load(e[a].state,R),r=e[a].data.length-t;if(r>0){if(e[a].buf.length===0){e[a].flushing=!1,e[a].ending?Ue(e):e[a].needDrain&&process.nextTick(Ar,e);return}let n=e[a].buf.slice(0,r),i=Buffer.byteLength(n);i<=r?(e[a].buf=e[a].buf.slice(r),de(e,n,ae.bind(null,e))):e.flush(()=>{if(!e.destroyed){for(Atomics.store(e[a].state,D,0),Atomics.store(e[a].state,R,0);i>e[a].data.length;)r=r/2,n=e[a].buf.slice(0,r),i=Buffer.byteLength(n);e[a].buf=e[a].buf.slice(r),de(e,n,ae.bind(null,e))}})}else if(r===0){if(t===0&&e[a].buf.length===0)return;e.flush(()=>{Atomics.store(e[a].state,D,0),Atomics.store(e[a].state,R,0),ae(e)})}else P(e,new Error("overwritten"))}function Gs(e){let t=this.stream.deref();if(t===void 0){this.exited=!0,this.terminate();return}switch(e.code){case"READY":this.stream=new Js(t),t.flush(()=>{t[a].ready=!0,t.emit("ready")});break;case"ERROR":P(t,e.err);break;case"EVENT":Array.isArray(e.args)?t.emit(e.name,...e.args):t.emit(e.name,e.args);break;case"WARNING":process.emitWarning(e.err);break;default:P(t,new Error("this should not happen: "+e.code))}}function jr(e){let t=this.stream.deref();t!==void 0&&($r.unregister(t),t.worker.exited=!0,t.worker.off("exit",jr),P(t,e!==0?new Error("the worker thread exited"):null))}var Ve=class extends Ns{constructor(t={}){if(super(),t.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[a]={},this[a].stateBuf=new SharedArrayBuffer(128),this[a].state=new Int32Array(this[a].stateBuf),this[a].dataBuf=new SharedArrayBuffer(t.bufferSize||4*1024*1024),this[a].data=Buffer.from(this[a].dataBuf),this[a].sync=t.sync||!1,this[a].ending=!1,this[a].ended=!1,this[a].needDrain=!1,this[a].destroyed=!1,this[a].flushing=!1,this[a].ready=!1,this[a].finished=!1,this[a].errored=null,this[a].closed=!1,this[a].buf="",this.worker=Us(this,t),this.on("message",(r,n)=>{this.worker.postMessage(r,n)})}write(t){if(this[a].destroyed)return Ke(this,new Error("the worker has exited")),!1;if(this[a].ending)return Ke(this,new Error("the worker is ending")),!1;if(this[a].flushing&&this[a].buf.length+t.length>=Vs)try{Fe(this),this[a].flushing=!0}catch(r){return P(this,r),!1}if(this[a].buf+=t,this[a].sync)try{return Fe(this),!0}catch(r){return P(this,r),!1}return this[a].flushing||(this[a].flushing=!0,setImmediate(ae,this)),this[a].needDrain=this[a].data.length-this[a].buf.length-Atomics.load(this[a].state,R)<=0,!this[a].needDrain}end(){this[a].destroyed||(this[a].ending=!0,Ue(this))}flush(t){if(this[a].destroyed){typeof t=="function"&&process.nextTick(t,new Error("the worker has exited"));return}let r=Atomics.load(this[a].state,R);Ws(this[a].state,D,r,1/0,(n,i)=>{if(n){P(this,n),process.nextTick(t,n);return}if(i==="not-equal"){this.flush(t);return}process.nextTick(t)})}flushSync(){this[a].destroyed||(Fe(this),Je(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[a].ready}get destroyed(){return this[a].destroyed}get closed(){return this[a].closed}get writable(){return!this[a].destroyed&&!this[a].ending}get writableEnded(){return this[a].ending}get writableFinished(){return this[a].finished}get writableNeedDrain(){return this[a].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[a].errored}};function Ke(e,t){setImmediate(()=>{e.emit("error",t)})}function P(e,t){e[a].destroyed||(e[a].destroyed=!0,t&&(e[a].errored=t,Ke(e,t)),e.worker.exited?setImmediate(()=>{e[a].closed=!0,e.emit("close")}):e.worker.terminate().catch(()=>{}).then(()=>{e[a].closed=!0,e.emit("close")}))}function de(e,t,r){let n=Atomics.load(e[a].state,R),i=Buffer.byteLength(t);return e[a].data.write(t,n),Atomics.store(e[a].state,R,n+i),Atomics.notify(e[a].state,R),r(),!0}function Ue(e){if(!(e[a].ended||!e[a].ending||e[a].flushing)){e[a].ended=!0;try{e.flushSync();let t=Atomics.load(e[a].state,D);Atomics.store(e[a].state,R,-1),Atomics.notify(e[a].state,R);let r=0;for(;t!==-1;){if(Atomics.wait(e[a].state,D,t,1e3),t=Atomics.load(e[a].state,D),t===-2){P(e,new Error("end() failed"));return}if(++r===10){P(e,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{e[a].finished=!0,e.emit("finish")})}catch(t){P(e,t)}}}function Fe(e){let t=()=>{e[a].ending?Ue(e):e[a].needDrain&&process.nextTick(Ar,e)};for(e[a].flushing=!1;e[a].buf.length!==0;){let r=Atomics.load(e[a].state,R),n=e[a].data.length-r;if(n===0){Je(e),Atomics.store(e[a].state,D,0),Atomics.store(e[a].state,R,0);continue}else if(n<0)throw new Error("overwritten");let i=e[a].buf.slice(0,n),o=Buffer.byteLength(i);if(o<=n)e[a].buf=e[a].buf.slice(n),de(e,i,t);else{for(Je(e),Atomics.store(e[a].state,D,0),Atomics.store(e[a].state,R,0);o>e[a].buf.length;)n=n/2,i=e[a].buf.slice(0,n),o=Buffer.byteLength(i);e[a].buf=e[a].buf.slice(n),de(e,i,t)}}}function Je(e){if(e[a].flushing)throw new Error("unable to flush while flushing");let t=Atomics.load(e[a].state,R),r=0;for(;;){let n=Atomics.load(e[a].state,D);if(n===-2)throw Error("_flushSync failed");if(n!==t)Atomics.wait(e[a].state,D,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}Tr.exports=Ve});var Xe=x((nc,Rr)=>{"use strict";var{createRequire:Hs}=require("module"),Xs=Te(),{join:Ge,isAbsolute:Ys,sep:Qs}=require("node:path"),Zs=Pe(),He=Me(),eo=kr();function to(e){He.register(e,no),He.registerBeforeExit(e,io),e.on("close",function(){He.unregister(e)})}function ro(e,t,r,n){let i=new eo({filename:e,workerData:t,workerOpts:r,sync:n});i.on("ready",o),i.on("close",function(){process.removeListener("exit",f)}),process.on("exit",f);function o(){process.removeListener("exit",f),i.unref(),r.autoEnd!==!1&&to(i)}function f(){i.closed||(i.flushSync(),Zs(100),i.end())}return i}function no(e){e.ref(),e.flushSync(),e.end(),e.once("close",function(){e.unref()})}function io(e){e.flushSync()}function so(e){let{pipeline:t,targets:r,levels:n,dedupe:i,worker:o={},caller:f=Xs(),sync:c=!1}=e,d={...e.options},y=typeof f=="string"?[f]:f,h="__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{},l=e.target;if(l&&r)throw new Error("only one of target or targets can be specified");return r?(l=h["pino-worker"]||Ge(__dirname,"worker.js"),d.targets=r.filter(u=>u.target).map(u=>({...u,target:p(u.target)})),d.pipelines=r.filter(u=>u.pipeline).map(u=>u.pipeline.map(s=>({...s,level:u.level,target:p(s.target)})))):t&&(l=h["pino-worker"]||Ge(__dirname,"worker.js"),d.pipelines=[t.map(u=>({...u,target:p(u.target)}))]),n&&(d.levels=n),i&&(d.dedupe=i),d.pinoWillSendConfig=!0,ro(p(l),d,o,c);function p(u){if(u=h[u]||u,Ys(u)||u.indexOf("file://")===0)return u;if(u==="pino/file")return Ge(__dirname,"..","file.js");let s;for(let m of y)try{let g=m==="node:repl"?process.cwd()+Qs:m;s=Hs(g).resolve(u);break}catch{continue}if(!s)throw new Error(`unable to determine transport target for "${u}"`);return s}}Rr.exports=so});var me=x((ic,Fr)=>{"use strict";var Br=fr(),{mapHttpRequest:oo,mapHttpResponse:lo}=je(),Qe=mr(),Ir=Me(),{lsCacheSym:fo,chindingsSym:Nr,writeSym:qr,serializersSym:Dr,formatOptsSym:Cr,endSym:co,stringifiersSym:Pr,stringifySym:zr,stringifySafeSym:Ze,wildcardFirstSym:Wr,nestedKeySym:uo,formattersSym:Mr,messageKeySym:ao,errorKeySym:ho,nestedKeyStrSym:yo,msgPrefixSym:ye}=G(),{isMainThread:go}=require("worker_threads"),mo=Xe();function X(){}function po(e,t){if(!t)return r;return function(...i){t.call(this,i,r,e)};function r(n,...i){if(typeof n=="object"){let o=n;n!==null&&(n.method&&n.headers&&n.socket?n=oo(n):typeof n.setHeader=="function"&&(n=lo(n)));let f;o===null&&i.length===0?f=[null]:(o=i.shift(),f=i),typeof this[ye]=="string"&&o!==void 0&&o!==null&&(o=this[ye]+o),this[qr](n,Br(o,f,this[Cr]),e)}else{let o=n===void 0?i.shift():n;typeof this[ye]=="string"&&o!==void 0&&o!==null&&(o=this[ye]+o),this[qr](null,Br(o,i,this[Cr]),e)}}}function Ye(e){let t="",r=0,n=!1,i=255,o=e.length;if(o>100)return JSON.stringify(e);for(var f=0;f=32;f++)i=e.charCodeAt(f),(i===34||i===92)&&(t+=e.slice(r,f)+"\\",r=f,n=!0);return n?t+=e.slice(r):t=e,i<32?JSON.stringify(e):'"'+t+'"'}function bo(e,t,r,n){let i=this[zr],o=this[Ze],f=this[Pr],c=this[co],d=this[Nr],y=this[Dr],h=this[Mr],l=this[ao],p=this[ho],u=this[fo][r]+n;u=u+d;let s;h.log&&(e=h.log(e));let m=f[Wr],g="";for(let b in e)if(s=e[b],Object.prototype.hasOwnProperty.call(e,b)&&s!==void 0){y[b]?s=y[b](s):b===p&&y.err&&(s=y.err(s));let w=f[b]||m;switch(typeof s){case"undefined":case"function":continue;case"number":Number.isFinite(s)===!1&&(s=null);case"boolean":w&&(s=w(s));break;case"string":s=(w||Ye)(s);break;default:s=(w||i)(s,o)}if(s===void 0)continue;let _=Ye(b);g+=","+_+":"+s}let S="";if(t!==void 0){s=y[l]?y[l](t):t;let b=f[l]||m;switch(typeof s){case"function":break;case"number":Number.isFinite(s)===!1&&(s=null);case"boolean":b&&(s=b(s)),S=',"'+l+'":'+s;break;case"string":s=(b||Ye)(s),S=',"'+l+'":'+s;break;default:s=(b||i)(s,o),S=',"'+l+'":'+s}}return this[uo]&&g?u+this[yo]+g.slice(1)+"}"+S+c:u+g+S+c}function wo(e,t){let r,n=e[Nr],i=e[zr],o=e[Ze],f=e[Pr],c=f[Wr],d=e[Dr],y=e[Mr].bindings;t=y(t);for(let h in t)if(r=t[h],(h!=="level"&&h!=="serializers"&&h!=="formatters"&&h!=="customLevels"&&t.hasOwnProperty(h)&&r!==void 0)===!0){if(r=d[h]?d[h](r):r,r=(f[h]||c||i)(r,o),r===void 0)continue;n+=',"'+h+'":'+r}return n}function So(e){return e.write!==e.constructor.prototype.write}function ge(e){let t=new Qe(e);return t.on("error",r),!e.sync&&go&&(Ir.register(t,_o),t.on("close",function(){Ir.unregister(t)})),t;function r(n){if(n.code==="EPIPE"){t.write=X,t.end=X,t.flushSync=X,t.destroy=X;return}t.removeListener("error",r),t.emit("error",n)}}function _o(e,t){e.destroyed||(t==="beforeExit"?(e.flush(),e.on("drain",function(){e.end()})):e.flushSync())}function Eo(e){return function(r,n,i={},o){if(typeof i=="string")o=ge({dest:i}),i={};else if(typeof o=="string"){if(i&&i.transport)throw Error("only one of option.transport or stream can be specified");o=ge({dest:o})}else if(i instanceof Qe||i.writable||i._writableState)o=i,i={};else if(i.transport){if(i.transport instanceof Qe||i.transport.writable||i.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(i.transport.targets&&i.transport.targets.length&&i.formatters&&typeof i.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let d;i.customLevels&&(d=i.useOnlyCustomLevels?i.customLevels:Object.assign({},i.levels,i.customLevels)),o=mo({caller:n,...i.transport,levels:d})}if(i=Object.assign({},e,i),i.serializers=Object.assign({},e.serializers,i.serializers),i.formatters=Object.assign({},e.formatters,i.formatters),i.prettyPrint)throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:f,onChild:c}=i;return f===!1&&(i.level="silent"),c||(i.onChild=X),o||(So(process.stdout)?o=process.stdout:o=ge({fd:process.stdout.fd||1})),{opts:i,stream:o}}}function Oo(e,t){try{return JSON.stringify(e)}catch{try{return(t||this[Ze])(e)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function xo(e,t,r){return{level:e,bindings:t,log:r}}function vo(e){let t=Number(e);return typeof e=="string"&&Number.isFinite(t)?t:e===void 0?1:e}Fr.exports={noop:X,buildSafeSonicBoom:ge,asChindings:wo,asJson:bo,genLog:po,createArgsNormalizer:Eo,stringify:Oo,buildFormatters:xo,normalizeDestFileDescriptor:vo}});var pe=x((sc,Vr)=>{var Lo={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},$o={ASC:"ASC",DESC:"DESC"};Vr.exports={DEFAULT_LEVELS:Lo,SORTING_ORDER:$o}});var rt=x((oc,Gr)=>{"use strict";var{lsCacheSym:Ao,levelValSym:et,useOnlyCustomLevelsSym:jo,streamSym:To,formattersSym:ko,hooksSym:Ro,levelCompSym:Kr}=G(),{noop:Bo,genLog:V}=me(),{DEFAULT_LEVELS:z,SORTING_ORDER:Jr}=pe(),Ur={fatal:e=>{let t=V(z.fatal,e);return function(...r){let n=this[To];if(t.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:e=>V(z.error,e),warn:e=>V(z.warn,e),info:e=>V(z.info,e),debug:e=>V(z.debug,e),trace:e=>V(z.trace,e)},tt=Object.keys(z).reduce((e,t)=>(e[z[t]]=t,e),{}),Io=Object.keys(tt).reduce((e,t)=>(e[t]='{"level":'+Number(t),e),{});function qo(e){let t=e[ko].level,{labels:r}=e.levels,n={};for(let i in r){let o=t(r[i],Number(i));n[i]=JSON.stringify(o).slice(0,-1)}return e[Ao]=n,e}function Co(e,t){if(t)return!1;switch(e){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function No(e){let{labels:t,values:r}=this.levels;if(typeof e=="number"){if(t[e]===void 0)throw Error("unknown level value"+e);e=t[e]}if(r[e]===void 0)throw Error("unknown level "+e);let n=this[et],i=this[et]=r[e],o=this[jo],f=this[Kr],c=this[Ro].logMethod;for(let d in r){if(f(r[d],i)===!1){this[d]=Bo;continue}this[d]=Co(d,o)?Ur[d](c):V(r[d],c)}this.emit("level-change",e,i,t[n],n,this)}function Do(e){let{levels:t,levelVal:r}=this;return t&&t.labels?t.labels[r]:""}function Po(e){let{values:t}=this.levels,r=t[e];return r!==void 0&&this[Kr](r,this[et])}function zo(e,t,r){return e===Jr.DESC?t<=r:t>=r}function Wo(e){return typeof e=="string"?zo.bind(null,e):e}function Mo(e=null,t=!1){let r=e?Object.keys(e).reduce((o,f)=>(o[e[f]]=f,o),{}):null,n=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),t?null:tt,r),i=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:z,e);return{labels:n,values:i}}function Fo(e,t,r){if(typeof e=="number"){if(![].concat(Object.keys(t||{}).map(o=>t[o]),r?[]:Object.keys(tt).map(o=>+o),1/0).includes(e))throw Error(`default level:${e} must be included in custom levels`);return}let n=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),r?null:z,t);if(!(e in n))throw Error(`default level:${e} must be included in custom levels`)}function Vo(e,t){let{labels:r,values:n}=e;for(let i in t){if(i in n)throw Error("levels cannot be overridden");if(t[i]in r)throw Error("pre-existing level values cannot be used for new levels")}}function Ko(e){if(typeof e!="function"&&!(typeof e=="string"&&Object.values(Jr).includes(e)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}Gr.exports={initialLsCache:Io,genLsCache:qo,levelMethods:Ur,getLevel:Do,setLevel:No,isLevelEnabled:Po,mappings:Mo,assertNoLevelCollisions:Vo,assertDefaultLevelFound:Fo,genLevelComparison:Wo,assertLevelComparison:Ko}});var nt=x((lc,Hr)=>{"use strict";Hr.exports={version:"9.7.0"}});var ln=x((cc,on)=>{"use strict";var{EventEmitter:Jo}=require("node:events"),{lsCacheSym:Uo,levelValSym:Go,setLevelSym:st,getLevelSym:Xr,chindingsSym:ot,parsedChindingsSym:Ho,mixinSym:Xo,asJsonSym:tn,writeSym:Yo,mixinMergeStrategySym:Qo,timeSym:Zo,timeSliceIndexSym:el,streamSym:rn,serializersSym:K,formattersSym:it,errorKeySym:tl,messageKeySym:rl,useOnlyCustomLevelsSym:nl,needsMetadataGsym:il,redactFmtSym:sl,stringifySym:ol,formatOptsSym:ll,stringifiersSym:fl,msgPrefixSym:Yr,hooksSym:cl}=G(),{getLevel:ul,setLevel:al,isLevelEnabled:hl,mappings:dl,initialLsCache:yl,genLsCache:gl,assertNoLevelCollisions:ml}=rt(),{asChindings:nn,asJson:pl,buildFormatters:Qr,stringify:Zr}=me(),{version:bl}=nt(),wl=Ne(),Sl=class{},sn={constructor:Sl,child:_l,bindings:El,setBindings:Ol,flush:$l,isLevelEnabled:hl,version:bl,get level(){return this[Xr]()},set level(e){this[st](e)},get levelVal(){return this[Go]},set levelVal(e){throw Error("levelVal is read-only")},[Uo]:yl,[Yo]:vl,[tn]:pl,[Xr]:ul,[st]:al};Object.setPrototypeOf(sn,Jo.prototype);on.exports=function(){return Object.create(sn)};var en=e=>e;function _l(e,t){if(!e)throw Error("missing bindings for child Pino");t=t||{};let r=this[K],n=this[it],i=Object.create(this);if(t.hasOwnProperty("serializers")===!0){i[K]=Object.create(null);for(let h in r)i[K][h]=r[h];let d=Object.getOwnPropertySymbols(r);for(var o=0;o{"use strict";var{hasOwnProperty:ee}=Object.prototype,U=ct();U.configure=ct;U.stringify=U;U.default=U;ut.stringify=U;ut.configure=ct;un.exports=U;var Al=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function M(e){return e.length<5e3&&!Al.test(e)?`"${e}"`:JSON.stringify(e)}function lt(e,t){if(e.length>200||t)return e.sort(t);for(let r=1;rn;)e[i]=e[i-1],i--;e[i]=n}return e}var jl=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function ft(e){return jl.call(e)!==void 0&&e.length!==0}function fn(e,t,r){e.length= 1`)}return r===void 0?1/0:r}function J(e){return e===1?"1 item":`${e} items`}function Bl(e){let t=new Set;for(let r of e)(typeof r=="string"||typeof r=="number")&&t.add(String(r));return t}function Il(e){if(ee.call(e,"strict")){let t=e.strict;if(typeof t!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(t)return r=>{let n=`Object can not safely be stringified. Received type ${typeof r}`;throw typeof r!="function"&&(n+=` (${r.toString()})`),new Error(n)}}}function ct(e){e={...e};let t=Il(e);t&&(e.bigint===void 0&&(e.bigint=!1),"circularValue"in e||(e.circularValue=Error));let r=Tl(e),n=Rl(e,"bigint"),i=kl(e),o=typeof i=="function"?i:void 0,f=cn(e,"maximumDepth"),c=cn(e,"maximumBreadth");function d(u,s,m,g,S,b){let w=s[u];switch(typeof w=="object"&&w!==null&&typeof w.toJSON=="function"&&(w=w.toJSON(u)),w=g.call(s,u,w),typeof w){case"string":return M(w);case"object":{if(w===null)return"null";if(m.indexOf(w)!==-1)return r;let _="",O=",",v=b;if(Array.isArray(w)){if(w.length===0)return"[]";if(fc){let F=w.length-c-1;_+=`${O}"... ${J(F)} not stringified"`}return S!==""&&(_+=` +${v}`),m.pop(),`[${_}]`}let L=Object.keys(w),$=L.length;if($===0)return"{}";if(fc){let T=$-c;_+=`${A}"...":${E}"${J(T)} not stringified"`,A=O}return S!==""&&A.length>1&&(_=` +${b}${_} +${v}`),m.pop(),`{${_}}`}case"number":return isFinite(w)?String(w):t?t(w):"null";case"boolean":return w===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(w);default:return t?t(w):void 0}}function y(u,s,m,g,S,b){switch(typeof s=="object"&&s!==null&&typeof s.toJSON=="function"&&(s=s.toJSON(u)),typeof s){case"string":return M(s);case"object":{if(s===null)return"null";if(m.indexOf(s)!==-1)return r;let w=b,_="",O=",";if(Array.isArray(s)){if(s.length===0)return"[]";if(fc){let k=s.length-c-1;_+=`${O}"... ${J(k)} not stringified"`}return S!==""&&(_+=` +${w}`),m.pop(),`[${_}]`}m.push(s);let v="";S!==""&&(b+=S,O=`, +${b}`,v=" ");let L="";for(let $ of g){let E=y($,s[$],m,g,S,b);E!==void 0&&(_+=`${L}${M($)}:${v}${E}`,L=O)}return S!==""&&L.length>1&&(_=` +${b}${_} +${w}`),m.pop(),`{${_}}`}case"number":return isFinite(s)?String(s):t?t(s):"null";case"boolean":return s===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(s);default:return t?t(s):void 0}}function h(u,s,m,g,S){switch(typeof s){case"string":return M(s);case"object":{if(s===null)return"null";if(typeof s.toJSON=="function"){if(s=s.toJSON(u),typeof s!="object")return h(u,s,m,g,S);if(s===null)return"null"}if(m.indexOf(s)!==-1)return r;let b=S;if(Array.isArray(s)){if(s.length===0)return"[]";if(fc){let I=s.length-c-1;E+=`${A}"... ${J(I)} not stringified"`}return E+=` +${b}`,m.pop(),`[${E}]`}let w=Object.keys(s),_=w.length;if(_===0)return"{}";if(fc){let E=_-c;v+=`${L}"...": "${J(E)} not stringified"`,L=O}return L!==""&&(v=` +${S}${v} +${b}`),m.pop(),`{${v}}`}case"number":return isFinite(s)?String(s):t?t(s):"null";case"boolean":return s===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(s);default:return t?t(s):void 0}}function l(u,s,m){switch(typeof s){case"string":return M(s);case"object":{if(s===null)return"null";if(typeof s.toJSON=="function"){if(s=s.toJSON(u),typeof s!="object")return l(u,s,m);if(s===null)return"null"}if(m.indexOf(s)!==-1)return r;let g="",S=s.length!==void 0;if(S&&Array.isArray(s)){if(s.length===0)return"[]";if(fc){let E=s.length-c-1;g+=`,"... ${J(E)} not stringified"`}return m.pop(),`[${g}]`}let b=Object.keys(s),w=b.length;if(w===0)return"{}";if(fc){let v=w-c;g+=`${_}"...":"${J(v)} not stringified"`}return m.pop(),`{${g}}`}case"number":return isFinite(s)?String(s):t?t(s):"null";case"boolean":return s===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(s);default:return t?t(s):void 0}}function p(u,s,m){if(arguments.length>1){let g="";if(typeof m=="number"?g=" ".repeat(Math.min(m,10)):typeof m=="string"&&(g=m.slice(0,10)),s!=null){if(typeof s=="function")return d("",{"":u},[],s,g,"");if(Array.isArray(s))return y("",u,[],Bl(s),g,"")}if(g.length!==0)return h("",u,[],g,"")}return l("",u,[])}return p}});var yn=x((uc,dn)=>{"use strict";var at=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:hn}=pe(),ql=hn.info;function Cl(e,t){let r=0;e=e||[],t=t||{dedupe:!1};let n=Object.create(hn);n.silent=1/0,t.levels&&typeof t.levels=="object"&&Object.keys(t.levels).forEach(l=>{n[l]=t.levels[l]});let i={write:o,add:d,emit:f,flushSync:c,end:y,minLevel:0,streams:[],clone:h,[at]:!0,streamLevels:n};return Array.isArray(e)?e.forEach(d,i):d.call(i,e),e=null,i;function o(l){let p,u=this.lastLevel,{streams:s}=this,m=0,g;for(let S=Dl(s.length,t.dedupe);zl(S,s.length,t.dedupe);S=Pl(S,t.dedupe))if(p=s[S],p.level<=u){if(m!==0&&m!==p.level)break;if(g=p.stream,g[at]){let{lastTime:b,lastMsg:w,lastObj:_,lastLogger:O}=this;g.lastLevel=u,g.lastTime=b,g.lastMsg=w,g.lastObj=_,g.lastLogger=O}g.write(l),t.dedupe&&(m=p.level)}else if(!t.dedupe)break}function f(...l){for(let{stream:p}of this.streams)typeof p.emit=="function"&&p.emit(...l)}function c(){for(let{stream:l}of this.streams)typeof l.flushSync=="function"&&l.flushSync()}function d(l){if(!l)return i;let p=typeof l.write=="function"||l.stream,u=l.write?l:l.stream;if(!p)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:s,streamLevels:m}=this,g;typeof l.levelVal=="number"?g=l.levelVal:typeof l.level=="string"?g=m[l.level]:typeof l.level=="number"?g=l.level:g=ql;let S={stream:u,level:g,levelVal:void 0,id:r++};return s.unshift(S),s.sort(Nl),this.minLevel=s[0].level,i}function y(){for(let{stream:l}of this.streams)typeof l.flushSync=="function"&&l.flushSync(),l.end()}function h(l){let p=new Array(this.streams.length);for(let u=0;u=0:e{function be(e){try{return require("path").join(`${process.cwd()}${require("path").sep}dist/cjs`.replace(/\\/g,"/"),e)}catch{return new Function("p","return new URL(p, import.meta.url).pathname")(e)}}globalThis.__bundlerPathsOverrides={...globalThis.__bundlerPathsOverrides||{},"thread-stream-worker":be("./thread-stream-worker.cjs"),"pino-worker":be("./pino-worker.cjs"),"pino/file":be("./pino-file.cjs"),"pino-roll":be("./pino-roll.cjs")};var Wl=require("node:os"),En=je(),Ml=Te(),Fl=Ne(),On=or(),Vl=ln(),xn=G(),{configure:Kl}=an(),{assertDefaultLevelFound:Jl,mappings:vn,genLsCache:Ul,genLevelComparison:Gl,assertLevelComparison:Hl}=rt(),{DEFAULT_LEVELS:Ln,SORTING_ORDER:Xl}=pe(),{createArgsNormalizer:Yl,asChindings:Ql,buildSafeSonicBoom:gn,buildFormatters:Zl,stringify:ht,normalizeDestFileDescriptor:mn,noop:ef}=me(),{version:tf}=nt(),{chindingsSym:pn,redactFmtSym:rf,serializersSym:bn,timeSym:nf,timeSliceIndexSym:sf,streamSym:of,stringifySym:wn,stringifySafeSym:dt,stringifiersSym:Sn,setLevelSym:lf,endSym:ff,formatOptsSym:cf,messageKeySym:uf,errorKeySym:af,nestedKeySym:hf,mixinSym:df,levelCompSym:yf,useOnlyCustomLevelsSym:gf,formattersSym:_n,hooksSym:mf,nestedKeyStrSym:pf,mixinMergeStrategySym:bf,msgPrefixSym:wf}=xn,{epochTime:$n,nullTime:Sf}=On,{pid:_f}=process,Ef=Wl.hostname(),Of=En.err,xf={level:"info",levelComparison:Xl.ASC,levels:Ln,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:_f,hostname:Ef},serializers:Object.assign(Object.create(null),{err:Of}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:$n,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},vf=Yl(xf),Lf=Object.assign(Object.create(null),En);function yt(...e){let t={},{opts:r,stream:n}=vf(t,Ml(),...e);r.level&&typeof r.level=="string"&&Ln[r.level.toLowerCase()]!==void 0&&(r.level=r.level.toLowerCase());let{redact:i,crlf:o,serializers:f,timestamp:c,messageKey:d,errorKey:y,nestedKey:h,base:l,name:p,level:u,customLevels:s,levelComparison:m,mixin:g,mixinMergeStrategy:S,useOnlyCustomLevels:b,formatters:w,hooks:_,depthLimit:O,edgeLimit:v,onChild:L,msgPrefix:$}=r,E=Kl({maximumDepth:O,maximumBreadth:v}),A=Zl(w.level,w.bindings,w.log),k=ht.bind({[dt]:E}),T=i?Fl(i,k):{},B=i?{stringify:T[rf]}:{stringify:k},I="}"+(o?`\r +`:` +`),F=Ql.bind(null,{[pn]:"",[bn]:f,[Sn]:T,[wn]:ht,[dt]:E,[_n]:A}),we="";l!==null&&(p===void 0?we=F(l):we=F(Object.assign({},l,{name:p})));let gt=c instanceof Function?c:c?$n:Sf,jn=gt().indexOf(":")+1;if(b&&!s)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(g&&typeof g!="function")throw Error(`Unknown mixin type "${typeof g}" - expected "function"`);if($&&typeof $!="string")throw Error(`Unknown msgPrefix type "${typeof $}" - expected "string"`);Jl(u,s,b);let mt=vn(s,b);typeof n.emit=="function"&&n.emit("message",{code:"PINO_CONFIG",config:{levels:mt,messageKey:d,errorKey:y}}),Hl(m);let Tn=Gl(m);return Object.assign(t,{levels:mt,[yf]:Tn,[gf]:b,[of]:n,[nf]:gt,[sf]:jn,[wn]:ht,[dt]:E,[Sn]:T,[ff]:I,[cf]:B,[uf]:d,[af]:y,[hf]:h,[pf]:h?`,${JSON.stringify(h)}:{`:"",[bn]:f,[df]:g,[bf]:S,[pn]:we,[_n]:A,[mf]:_,silent:ef,onChild:L,[wf]:$}),Object.setPrototypeOf(t,Vl()),Ul(t),t[lf](u),t}q.exports=yt;q.exports.destination=(e=process.stdout.fd)=>typeof e=="object"?(e.dest=mn(e.dest||process.stdout.fd),gn(e)):gn({dest:mn(e),minLength:0});q.exports.transport=Xe();q.exports.multistream=yn();q.exports.levels=vn();q.exports.stdSerializers=Lf;q.exports.stdTimeFunctions=Object.assign({},On);q.exports.symbols=xn;q.exports.version=tf;q.exports.default=yt;q.exports.pino=yt});var $f=An(),{once:Af}=require("node:events");module.exports=async function(e={}){let t=Object.assign({},e,{dest:e.destination||1,sync:!1});delete t.destination;let r=$f.destination(t);return await Af(r,"ready"),r}; +//# sourceMappingURL=pino-file.cjs.map diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/pino-file.cjs.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/pino-file.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..451877694608e839e31689f9a13c6c55de664ef9 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/pino-file.cjs.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err-helpers.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err-proto.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err-with-cause.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/req.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/res.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/caller.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/validator.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/rx.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/parse.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/redactor.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/modifiers.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/restorer.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/state.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/symbols.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/redaction.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/time.js", "../../node_modules/.pnpm/quick-format-unescaped@4.0.4/node_modules/quick-format-unescaped/index.js", "../../node_modules/.pnpm/atomic-sleep@1.0.0/node_modules/atomic-sleep/index.js", "../../node_modules/.pnpm/sonic-boom@4.2.0/node_modules/sonic-boom/index.js", "../../node_modules/.pnpm/on-exit-leak-free@2.1.2/node_modules/on-exit-leak-free/index.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/package.json", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/wait.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/indexes.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/transport.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/tools.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/constants.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/levels.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/meta.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/proto.js", "../../node_modules/.pnpm/safe-stable-stringify@2.5.0/node_modules/safe-stable-stringify/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/multistream.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/pino.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/file.js"], + "sourcesContent": ["'use strict'\n\n// **************************************************************\n// * Code initially copied/adapted from \"pony-cause\" npm module *\n// * Please upstream improvements there *\n// **************************************************************\n\nconst isErrorLike = (err) => {\n return err && typeof err.message === 'string'\n}\n\n/**\n * @param {Error|{ cause?: unknown|(()=>err)}} err\n * @returns {Error|Object|undefined}\n */\nconst getErrorCause = (err) => {\n if (!err) return\n\n /** @type {unknown} */\n // @ts-ignore\n const cause = err.cause\n\n // VError / NError style causes\n if (typeof cause === 'function') {\n // @ts-ignore\n const causeResult = err.cause()\n\n return isErrorLike(causeResult)\n ? causeResult\n : undefined\n } else {\n return isErrorLike(cause)\n ? cause\n : undefined\n }\n}\n\n/**\n * Internal method that keeps a track of which error we have already added, to avoid circular recursion\n *\n * @private\n * @param {Error} err\n * @param {Set} seen\n * @returns {string}\n */\nconst _stackWithCauses = (err, seen) => {\n if (!isErrorLike(err)) return ''\n\n const stack = err.stack || ''\n\n // Ensure we don't go circular or crazily deep\n if (seen.has(err)) {\n return stack + '\\ncauses have become circular...'\n }\n\n const cause = getErrorCause(err)\n\n if (cause) {\n seen.add(err)\n return (stack + '\\ncaused by: ' + _stackWithCauses(cause, seen))\n } else {\n return stack\n }\n}\n\n/**\n * @param {Error} err\n * @returns {string}\n */\nconst stackWithCauses = (err) => _stackWithCauses(err, new Set())\n\n/**\n * Internal method that keeps a track of which error we have already added, to avoid circular recursion\n *\n * @private\n * @param {Error} err\n * @param {Set} seen\n * @param {boolean} [skip]\n * @returns {string}\n */\nconst _messageWithCauses = (err, seen, skip) => {\n if (!isErrorLike(err)) return ''\n\n const message = skip ? '' : (err.message || '')\n\n // Ensure we don't go circular or crazily deep\n if (seen.has(err)) {\n return message + ': ...'\n }\n\n const cause = getErrorCause(err)\n\n if (cause) {\n seen.add(err)\n\n // @ts-ignore\n const skipIfVErrorStyleCause = typeof err.cause === 'function'\n\n return (message +\n (skipIfVErrorStyleCause ? '' : ': ') +\n _messageWithCauses(cause, seen, skipIfVErrorStyleCause))\n } else {\n return message\n }\n}\n\n/**\n * @param {Error} err\n * @returns {string}\n */\nconst messageWithCauses = (err) => _messageWithCauses(err, new Set())\n\nmodule.exports = {\n isErrorLike,\n getErrorCause,\n stackWithCauses,\n messageWithCauses\n}\n", "'use strict'\n\nconst seen = Symbol('circular-ref-tag')\nconst rawSymbol = Symbol('pino-raw-err-ref')\n\nconst pinoErrProto = Object.create({}, {\n type: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n message: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n stack: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n aggregateErrors: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoErrProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nmodule.exports = {\n pinoErrProto,\n pinoErrorSymbols: {\n seen,\n rawSymbol\n }\n}\n", "'use strict'\n\nmodule.exports = errSerializer\n\nconst { messageWithCauses, stackWithCauses, isErrorLike } = require('./err-helpers')\nconst { pinoErrProto, pinoErrorSymbols } = require('./err-proto')\nconst { seen } = pinoErrorSymbols\n\nconst { toString } = Object.prototype\n\nfunction errSerializer (err) {\n if (!isErrorLike(err)) {\n return err\n }\n\n err[seen] = undefined // tag to prevent re-looking at this\n const _err = Object.create(pinoErrProto)\n _err.type = toString.call(err.constructor) === '[object Function]'\n ? err.constructor.name\n : err.name\n _err.message = messageWithCauses(err)\n _err.stack = stackWithCauses(err)\n\n if (Array.isArray(err.errors)) {\n _err.aggregateErrors = err.errors.map(err => errSerializer(err))\n }\n\n for (const key in err) {\n if (_err[key] === undefined) {\n const val = err[key]\n if (isErrorLike(val)) {\n // We append cause messages and stacks to _err, therefore skipping causes here\n if (key !== 'cause' && !Object.prototype.hasOwnProperty.call(val, seen)) {\n _err[key] = errSerializer(val)\n }\n } else {\n _err[key] = val\n }\n }\n }\n\n delete err[seen] // clean up tag in case err is serialized again later\n _err.raw = err\n return _err\n}\n", "'use strict'\n\nmodule.exports = errWithCauseSerializer\n\nconst { isErrorLike } = require('./err-helpers')\nconst { pinoErrProto, pinoErrorSymbols } = require('./err-proto')\nconst { seen } = pinoErrorSymbols\n\nconst { toString } = Object.prototype\n\nfunction errWithCauseSerializer (err) {\n if (!isErrorLike(err)) {\n return err\n }\n\n err[seen] = undefined // tag to prevent re-looking at this\n const _err = Object.create(pinoErrProto)\n _err.type = toString.call(err.constructor) === '[object Function]'\n ? err.constructor.name\n : err.name\n _err.message = err.message\n _err.stack = err.stack\n\n if (Array.isArray(err.errors)) {\n _err.aggregateErrors = err.errors.map(err => errWithCauseSerializer(err))\n }\n\n if (isErrorLike(err.cause) && !Object.prototype.hasOwnProperty.call(err.cause, seen)) {\n _err.cause = errWithCauseSerializer(err.cause)\n }\n\n for (const key in err) {\n if (_err[key] === undefined) {\n const val = err[key]\n if (isErrorLike(val)) {\n if (!Object.prototype.hasOwnProperty.call(val, seen)) {\n _err[key] = errWithCauseSerializer(val)\n }\n } else {\n _err[key] = val\n }\n }\n }\n\n delete err[seen] // clean up tag in case err is serialized again later\n _err.raw = err\n return _err\n}\n", "'use strict'\n\nmodule.exports = {\n mapHttpRequest,\n reqSerializer\n}\n\nconst rawSymbol = Symbol('pino-raw-req-ref')\nconst pinoReqProto = Object.create({}, {\n id: {\n enumerable: true,\n writable: true,\n value: ''\n },\n method: {\n enumerable: true,\n writable: true,\n value: ''\n },\n url: {\n enumerable: true,\n writable: true,\n value: ''\n },\n query: {\n enumerable: true,\n writable: true,\n value: ''\n },\n params: {\n enumerable: true,\n writable: true,\n value: ''\n },\n headers: {\n enumerable: true,\n writable: true,\n value: {}\n },\n remoteAddress: {\n enumerable: true,\n writable: true,\n value: ''\n },\n remotePort: {\n enumerable: true,\n writable: true,\n value: ''\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoReqProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nfunction reqSerializer (req) {\n // req.info is for hapi compat.\n const connection = req.info || req.socket\n const _req = Object.create(pinoReqProto)\n _req.id = (typeof req.id === 'function' ? req.id() : (req.id || (req.info ? req.info.id : undefined)))\n _req.method = req.method\n // req.originalUrl is for expressjs compat.\n if (req.originalUrl) {\n _req.url = req.originalUrl\n } else {\n const path = req.path\n // path for safe hapi compat.\n _req.url = typeof path === 'string' ? path : (req.url ? req.url.path || req.url : undefined)\n }\n\n if (req.query) {\n _req.query = req.query\n }\n\n if (req.params) {\n _req.params = req.params\n }\n\n _req.headers = req.headers\n _req.remoteAddress = connection && connection.remoteAddress\n _req.remotePort = connection && connection.remotePort\n // req.raw is for hapi compat/equivalence\n _req.raw = req.raw || req\n return _req\n}\n\nfunction mapHttpRequest (req) {\n return {\n req: reqSerializer(req)\n }\n}\n", "'use strict'\n\nmodule.exports = {\n mapHttpResponse,\n resSerializer\n}\n\nconst rawSymbol = Symbol('pino-raw-res-ref')\nconst pinoResProto = Object.create({}, {\n statusCode: {\n enumerable: true,\n writable: true,\n value: 0\n },\n headers: {\n enumerable: true,\n writable: true,\n value: ''\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoResProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nfunction resSerializer (res) {\n const _res = Object.create(pinoResProto)\n _res.statusCode = res.headersSent ? res.statusCode : null\n _res.headers = res.getHeaders ? res.getHeaders() : res._headers\n _res.raw = res\n return _res\n}\n\nfunction mapHttpResponse (res) {\n return {\n res: resSerializer(res)\n }\n}\n", "'use strict'\n\nconst errSerializer = require('./lib/err')\nconst errWithCauseSerializer = require('./lib/err-with-cause')\nconst reqSerializers = require('./lib/req')\nconst resSerializers = require('./lib/res')\n\nmodule.exports = {\n err: errSerializer,\n errWithCause: errWithCauseSerializer,\n mapHttpRequest: reqSerializers.mapHttpRequest,\n mapHttpResponse: resSerializers.mapHttpResponse,\n req: reqSerializers.reqSerializer,\n res: resSerializers.resSerializer,\n\n wrapErrorSerializer: function wrapErrorSerializer (customSerializer) {\n if (customSerializer === errSerializer) return customSerializer\n return function wrapErrSerializer (err) {\n return customSerializer(errSerializer(err))\n }\n },\n\n wrapRequestSerializer: function wrapRequestSerializer (customSerializer) {\n if (customSerializer === reqSerializers.reqSerializer) return customSerializer\n return function wrappedReqSerializer (req) {\n return customSerializer(reqSerializers.reqSerializer(req))\n }\n },\n\n wrapResponseSerializer: function wrapResponseSerializer (customSerializer) {\n if (customSerializer === resSerializers.resSerializer) return customSerializer\n return function wrappedResSerializer (res) {\n return customSerializer(resSerializers.resSerializer(res))\n }\n }\n}\n", "'use strict'\n\nfunction noOpPrepareStackTrace (_, stack) {\n return stack\n}\n\nmodule.exports = function getCallers () {\n const originalPrepare = Error.prepareStackTrace\n Error.prepareStackTrace = noOpPrepareStackTrace\n const stack = new Error().stack\n Error.prepareStackTrace = originalPrepare\n\n if (!Array.isArray(stack)) {\n return undefined\n }\n\n const entries = stack.slice(2)\n\n const fileNames = []\n\n for (const entry of entries) {\n if (!entry) {\n continue\n }\n\n fileNames.push(entry.getFileName())\n }\n\n return fileNames\n}\n", "'use strict'\n\nmodule.exports = validator\n\nfunction validator (opts = {}) {\n const {\n ERR_PATHS_MUST_BE_STRINGS = () => 'fast-redact - Paths must be (non-empty) strings',\n ERR_INVALID_PATH = (s) => `fast-redact \u2013 Invalid path (${s})`\n } = opts\n\n return function validate ({ paths }) {\n paths.forEach((s) => {\n if (typeof s !== 'string') {\n throw Error(ERR_PATHS_MUST_BE_STRINGS())\n }\n try {\n if (/\u3007/.test(s)) throw Error()\n const expr = (s[0] === '[' ? '' : '.') + s.replace(/^\\*/, '\u3007').replace(/\\.\\*/g, '.\u3007').replace(/\\[\\*\\]/g, '[\u3007]')\n if (/\\n|\\r|;/.test(expr)) throw Error()\n if (/\\/\\*/.test(expr)) throw Error()\n /* eslint-disable-next-line */\n Function(`\n 'use strict'\n const o = new Proxy({}, { get: () => o, set: () => { throw Error() } });\n const \u3007 = null;\n o${expr}\n if ([o${expr}].length !== 1) throw Error()`)()\n } catch (e) {\n throw Error(ERR_INVALID_PATH(s))\n }\n })\n }\n}\n", "'use strict'\n\nmodule.exports = /[^.[\\]]+|\\[((?:.)*?)\\]/g\n\n/*\nRegular expression explanation:\n\nAlt 1: /[^.[\\]]+/ - Match one or more characters that are *not* a dot (.)\n opening square bracket ([) or closing square bracket (])\n\nAlt 2: /\\[((?:.)*?)\\]/ - If the char IS dot or square bracket, then create a capture\n group (which will be capture group $1) that matches anything\n within square brackets. Expansion is lazy so it will\n stop matching as soon as the first closing bracket is met `]`\n (rather than continuing to match until the final closing bracket).\n*/\n", "'use strict'\n\nconst rx = require('./rx')\n\nmodule.exports = parse\n\nfunction parse ({ paths }) {\n const wildcards = []\n var wcLen = 0\n const secret = paths.reduce(function (o, strPath, ix) {\n var path = strPath.match(rx).map((p) => p.replace(/'|\"|`/g, ''))\n const leadingBracket = strPath[0] === '['\n path = path.map((p) => {\n if (p[0] === '[') return p.substr(1, p.length - 2)\n else return p\n })\n const star = path.indexOf('*')\n if (star > -1) {\n const before = path.slice(0, star)\n const beforeStr = before.join('.')\n const after = path.slice(star + 1, path.length)\n const nested = after.length > 0\n wcLen++\n wildcards.push({\n before,\n beforeStr,\n after,\n nested\n })\n } else {\n o[strPath] = {\n path: path,\n val: undefined,\n precensored: false,\n circle: '',\n escPath: JSON.stringify(strPath),\n leadingBracket: leadingBracket\n }\n }\n return o\n }, {})\n\n return { wildcards, wcLen, secret }\n}\n", "'use strict'\n\nconst rx = require('./rx')\n\nmodule.exports = redactor\n\nfunction redactor ({ secret, serialize, wcLen, strict, isCensorFct, censorFctTakesPath }, state) {\n /* eslint-disable-next-line */\n const redact = Function('o', `\n if (typeof o !== 'object' || o == null) {\n ${strictImpl(strict, serialize)}\n }\n const { censor, secret } = this\n const originalSecret = {}\n const secretKeys = Object.keys(secret)\n for (var i = 0; i < secretKeys.length; i++) {\n originalSecret[secretKeys[i]] = secret[secretKeys[i]]\n }\n\n ${redactTmpl(secret, isCensorFct, censorFctTakesPath)}\n this.compileRestore()\n ${dynamicRedactTmpl(wcLen > 0, isCensorFct, censorFctTakesPath)}\n this.secret = originalSecret\n ${resultTmpl(serialize)}\n `).bind(state)\n\n redact.state = state\n\n if (serialize === false) {\n redact.restore = (o) => state.restore(o)\n }\n\n return redact\n}\n\nfunction redactTmpl (secret, isCensorFct, censorFctTakesPath) {\n return Object.keys(secret).map((path) => {\n const { escPath, leadingBracket, path: arrPath } = secret[path]\n const skip = leadingBracket ? 1 : 0\n const delim = leadingBracket ? '' : '.'\n const hops = []\n var match\n while ((match = rx.exec(path)) !== null) {\n const [ , ix ] = match\n const { index, input } = match\n if (index > skip) hops.push(input.substring(0, index - (ix ? 0 : 1)))\n }\n var existence = hops.map((p) => `o${delim}${p}`).join(' && ')\n if (existence.length === 0) existence += `o${delim}${path} != null`\n else existence += ` && o${delim}${path} != null`\n\n const circularDetection = `\n switch (true) {\n ${hops.reverse().map((p) => `\n case o${delim}${p} === censor:\n secret[${escPath}].circle = ${JSON.stringify(p)}\n break\n `).join('\\n')}\n }\n `\n\n const censorArgs = censorFctTakesPath\n ? `val, ${JSON.stringify(arrPath)}`\n : `val`\n\n return `\n if (${existence}) {\n const val = o${delim}${path}\n if (val === censor) {\n secret[${escPath}].precensored = true\n } else {\n secret[${escPath}].val = val\n o${delim}${path} = ${isCensorFct ? `censor(${censorArgs})` : 'censor'}\n ${circularDetection}\n }\n }\n `\n }).join('\\n')\n}\n\nfunction dynamicRedactTmpl (hasWildcards, isCensorFct, censorFctTakesPath) {\n return hasWildcards === true ? `\n {\n const { wildcards, wcLen, groupRedact, nestedRedact } = this\n for (var i = 0; i < wcLen; i++) {\n const { before, beforeStr, after, nested } = wildcards[i]\n if (nested === true) {\n secret[beforeStr] = secret[beforeStr] || []\n nestedRedact(secret[beforeStr], o, before, after, censor, ${isCensorFct}, ${censorFctTakesPath})\n } else secret[beforeStr] = groupRedact(o, before, censor, ${isCensorFct}, ${censorFctTakesPath})\n }\n }\n ` : ''\n}\n\nfunction resultTmpl (serialize) {\n return serialize === false ? `return o` : `\n var s = this.serialize(o)\n this.restore(o)\n return s\n `\n}\n\nfunction strictImpl (strict, serialize) {\n return strict === true\n ? `throw Error('fast-redact: primitives cannot be redacted')`\n : serialize === false ? `return o` : `return this.serialize(o)`\n}\n", "'use strict'\n\nmodule.exports = {\n groupRedact,\n groupRestore,\n nestedRedact,\n nestedRestore\n}\n\nfunction groupRestore ({ keys, values, target }) {\n if (target == null || typeof target === 'string') return\n const length = keys.length\n for (var i = 0; i < length; i++) {\n const k = keys[i]\n target[k] = values[i]\n }\n}\n\nfunction groupRedact (o, path, censor, isCensorFct, censorFctTakesPath) {\n const target = get(o, path)\n if (target == null || typeof target === 'string') return { keys: null, values: null, target, flat: true }\n const keys = Object.keys(target)\n const keysLength = keys.length\n const pathLength = path.length\n const pathWithKey = censorFctTakesPath ? [...path] : undefined\n const values = new Array(keysLength)\n\n for (var i = 0; i < keysLength; i++) {\n const key = keys[i]\n values[i] = target[key]\n\n if (censorFctTakesPath) {\n pathWithKey[pathLength] = key\n target[key] = censor(target[key], pathWithKey)\n } else if (isCensorFct) {\n target[key] = censor(target[key])\n } else {\n target[key] = censor\n }\n }\n return { keys, values, target, flat: true }\n}\n\n/**\n * @param {RestoreInstruction[]} instructions a set of instructions for restoring values to objects\n */\nfunction nestedRestore (instructions) {\n for (let i = 0; i < instructions.length; i++) {\n const { target, path, value } = instructions[i]\n let current = target\n for (let i = path.length - 1; i > 0; i--) {\n current = current[path[i]]\n }\n current[path[0]] = value\n }\n}\n\nfunction nestedRedact (store, o, path, ns, censor, isCensorFct, censorFctTakesPath) {\n const target = get(o, path)\n if (target == null) return\n const keys = Object.keys(target)\n const keysLength = keys.length\n for (var i = 0; i < keysLength; i++) {\n const key = keys[i]\n specialSet(store, target, key, path, ns, censor, isCensorFct, censorFctTakesPath)\n }\n return store\n}\n\nfunction has (obj, prop) {\n return obj !== undefined && obj !== null\n ? ('hasOwn' in Object ? Object.hasOwn(obj, prop) : Object.prototype.hasOwnProperty.call(obj, prop))\n : false\n}\n\nfunction specialSet (store, o, k, path, afterPath, censor, isCensorFct, censorFctTakesPath) {\n const afterPathLen = afterPath.length\n const lastPathIndex = afterPathLen - 1\n const originalKey = k\n var i = -1\n var n\n var nv\n var ov\n var oov = null\n var wc = null\n var kIsWc\n var wcov\n var consecutive = false\n var level = 0\n // need to track depth of the `redactPath` tree\n var depth = 0\n var redactPathCurrent = tree()\n ov = n = o[k]\n if (typeof n !== 'object') return\n while (n != null && ++i < afterPathLen) {\n depth += 1\n k = afterPath[i]\n oov = ov\n if (k !== '*' && !wc && !(typeof n === 'object' && k in n)) {\n break\n }\n if (k === '*') {\n if (wc === '*') {\n consecutive = true\n }\n wc = k\n if (i !== lastPathIndex) {\n continue\n }\n }\n if (wc) {\n const wcKeys = Object.keys(n)\n for (var j = 0; j < wcKeys.length; j++) {\n const wck = wcKeys[j]\n wcov = n[wck]\n kIsWc = k === '*'\n if (consecutive) {\n redactPathCurrent = node(redactPathCurrent, wck, depth)\n level = i\n ov = iterateNthLevel(wcov, level - 1, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, o[originalKey], depth + 1)\n } else {\n if (kIsWc || (typeof wcov === 'object' && wcov !== null && k in wcov)) {\n if (kIsWc) {\n ov = wcov\n } else {\n ov = wcov[k]\n }\n nv = (i !== lastPathIndex)\n ? ov\n : (isCensorFct\n ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))\n : censor)\n if (kIsWc) {\n const rv = restoreInstr(node(redactPathCurrent, wck, depth), ov, o[originalKey])\n store.push(rv)\n n[wck] = nv\n } else {\n if (wcov[k] === nv) {\n // pass\n } else if ((nv === undefined && censor !== undefined) || (has(wcov, k) && nv === ov)) {\n redactPathCurrent = node(redactPathCurrent, wck, depth)\n } else {\n redactPathCurrent = node(redactPathCurrent, wck, depth)\n const rv = restoreInstr(node(redactPathCurrent, k, depth + 1), ov, o[originalKey])\n store.push(rv)\n wcov[k] = nv\n }\n }\n }\n }\n }\n wc = null\n } else {\n ov = n[k]\n redactPathCurrent = node(redactPathCurrent, k, depth)\n nv = (i !== lastPathIndex)\n ? ov\n : (isCensorFct\n ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))\n : censor)\n if ((has(n, k) && nv === ov) || (nv === undefined && censor !== undefined)) {\n // pass\n } else {\n const rv = restoreInstr(redactPathCurrent, ov, o[originalKey])\n store.push(rv)\n n[k] = nv\n }\n n = n[k]\n }\n if (typeof n !== 'object') break\n // prevent circular structure, see https://github.com/pinojs/pino/issues/1513\n if (ov === oov || typeof ov === 'undefined') {\n // pass\n }\n }\n}\n\nfunction get (o, p) {\n var i = -1\n var l = p.length\n var n = o\n while (n != null && ++i < l) {\n n = n[p[i]]\n }\n return n\n}\n\nfunction iterateNthLevel (wcov, level, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, parent, depth) {\n if (level === 0) {\n if (kIsWc || (typeof wcov === 'object' && wcov !== null && k in wcov)) {\n if (kIsWc) {\n ov = wcov\n } else {\n ov = wcov[k]\n }\n nv = (i !== lastPathIndex)\n ? ov\n : (isCensorFct\n ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))\n : censor)\n if (kIsWc) {\n const rv = restoreInstr(redactPathCurrent, ov, parent)\n store.push(rv)\n n[wck] = nv\n } else {\n if (wcov[k] === nv) {\n // pass\n } else if ((nv === undefined && censor !== undefined) || (has(wcov, k) && nv === ov)) {\n // pass\n } else {\n const rv = restoreInstr(node(redactPathCurrent, k, depth + 1), ov, parent)\n store.push(rv)\n wcov[k] = nv\n }\n }\n }\n }\n for (const key in wcov) {\n if (typeof wcov[key] === 'object') {\n redactPathCurrent = node(redactPathCurrent, key, depth)\n iterateNthLevel(wcov[key], level - 1, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, parent, depth + 1)\n }\n }\n}\n\n/**\n * @typedef {object} TreeNode\n * @prop {TreeNode} [parent] reference to the parent of this node in the tree, or `null` if there is no parent\n * @prop {string} key the key that this node represents (key here being part of the path being redacted\n * @prop {TreeNode[]} children the child nodes of this node\n * @prop {number} depth the depth of this node in the tree\n */\n\n/**\n * instantiate a new, empty tree\n * @returns {TreeNode}\n */\nfunction tree () {\n return { parent: null, key: null, children: [], depth: 0 }\n}\n\n/**\n * creates a new node in the tree, attaching it as a child of the provided parent node\n * if the specified depth matches the parent depth, adds the new node as a _sibling_ of the parent instead\n * @param {TreeNode} parent the parent node to add a new node to (if the parent depth matches the provided `depth` value, will instead add as a sibling of this\n * @param {string} key the key that the new node represents (key here being part of the path being redacted)\n * @param {number} depth the depth of the new node in the tree - used to determing whether to add the new node as a child or sibling of the provided `parent` node\n * @returns {TreeNode} a reference to the newly created node in the tree\n */\nfunction node (parent, key, depth) {\n if (parent.depth === depth) {\n return node(parent.parent, key, depth)\n }\n\n var child = {\n parent,\n key,\n depth,\n children: []\n }\n\n parent.children.push(child)\n\n return child\n}\n\n/**\n * @typedef {object} RestoreInstruction\n * @prop {string[]} path a reverse-order path that can be used to find the correct insertion point to restore a `value` for the given `parent` object\n * @prop {*} value the value to restore\n * @prop {object} target the object to restore the `value` in\n */\n\n/**\n * create a restore instruction for the given redactPath node\n * generates a path in reverse order by walking up the redactPath tree\n * @param {TreeNode} node a tree node that should be at the bottom of the redact path (i.e. have no children) - this will be used to walk up the redact path tree to construct the path needed to restore\n * @param {*} value the value to restore\n * @param {object} target a reference to the parent object to apply the restore instruction to\n * @returns {RestoreInstruction} an instruction used to restore a nested value for a specific object\n */\nfunction restoreInstr (node, value, target) {\n let current = node\n const path = []\n do {\n path.push(current.key)\n current = current.parent\n } while (current.parent != null)\n\n return { path, value, target }\n}\n", "'use strict'\n\nconst { groupRestore, nestedRestore } = require('./modifiers')\n\nmodule.exports = restorer\n\nfunction restorer () {\n return function compileRestore () {\n if (this.restore) {\n this.restore.state.secret = this.secret\n return\n }\n const { secret, wcLen } = this\n const paths = Object.keys(secret)\n const resetters = resetTmpl(secret, paths)\n const hasWildcards = wcLen > 0\n const state = hasWildcards ? { secret, groupRestore, nestedRestore } : { secret }\n /* eslint-disable-next-line */\n this.restore = Function(\n 'o',\n restoreTmpl(resetters, paths, hasWildcards)\n ).bind(state)\n this.restore.state = state\n }\n}\n\n/**\n * Mutates the original object to be censored by restoring its original values\n * prior to censoring.\n *\n * @param {object} secret Compiled object describing which target fields should\n * be censored and the field states.\n * @param {string[]} paths The list of paths to censor as provided at\n * initialization time.\n *\n * @returns {string} String of JavaScript to be used by `Function()`. The\n * string compiles to the function that does the work in the description.\n */\nfunction resetTmpl (secret, paths) {\n return paths.map((path) => {\n const { circle, escPath, leadingBracket } = secret[path]\n const delim = leadingBracket ? '' : '.'\n const reset = circle\n ? `o.${circle} = secret[${escPath}].val`\n : `o${delim}${path} = secret[${escPath}].val`\n const clear = `secret[${escPath}].val = undefined`\n return `\n if (secret[${escPath}].val !== undefined) {\n try { ${reset} } catch (e) {}\n ${clear}\n }\n `\n }).join('')\n}\n\n/**\n * Creates the body of the restore function\n *\n * Restoration of the redacted object happens\n * backwards, in reverse order of redactions,\n * so that repeated redactions on the same object\n * property can be eventually rolled back to the\n * original value.\n *\n * This way dynamic redactions are restored first,\n * starting from the last one working backwards and\n * followed by the static ones.\n *\n * @returns {string} the body of the restore function\n */\nfunction restoreTmpl (resetters, paths, hasWildcards) {\n const dynamicReset = hasWildcards === true ? `\n const keys = Object.keys(secret)\n const len = keys.length\n for (var i = len - 1; i >= ${paths.length}; i--) {\n const k = keys[i]\n const o = secret[k]\n if (o) {\n if (o.flat === true) this.groupRestore(o)\n else this.nestedRestore(o)\n secret[k] = null\n }\n }\n ` : ''\n\n return `\n const secret = this.secret\n ${dynamicReset}\n ${resetters}\n return o\n `\n}\n", "'use strict'\n\nmodule.exports = state\n\nfunction state (o) {\n const {\n secret,\n censor,\n compileRestore,\n serialize,\n groupRedact,\n nestedRedact,\n wildcards,\n wcLen\n } = o\n const builder = [{ secret, censor, compileRestore }]\n if (serialize !== false) builder.push({ serialize })\n if (wcLen > 0) builder.push({ groupRedact, nestedRedact, wildcards, wcLen })\n return Object.assign(...builder)\n}\n", "'use strict'\n\nconst validator = require('./lib/validator')\nconst parse = require('./lib/parse')\nconst redactor = require('./lib/redactor')\nconst restorer = require('./lib/restorer')\nconst { groupRedact, nestedRedact } = require('./lib/modifiers')\nconst state = require('./lib/state')\nconst rx = require('./lib/rx')\nconst validate = validator()\nconst noop = (o) => o\nnoop.restore = noop\n\nconst DEFAULT_CENSOR = '[REDACTED]'\nfastRedact.rx = rx\nfastRedact.validator = validator\n\nmodule.exports = fastRedact\n\nfunction fastRedact (opts = {}) {\n const paths = Array.from(new Set(opts.paths || []))\n const serialize = 'serialize' in opts ? (\n opts.serialize === false ? opts.serialize\n : (typeof opts.serialize === 'function' ? opts.serialize : JSON.stringify)\n ) : JSON.stringify\n const remove = opts.remove\n if (remove === true && serialize !== JSON.stringify) {\n throw Error('fast-redact \u2013 remove option may only be set when serializer is JSON.stringify')\n }\n const censor = remove === true\n ? undefined\n : 'censor' in opts ? opts.censor : DEFAULT_CENSOR\n\n const isCensorFct = typeof censor === 'function'\n const censorFctTakesPath = isCensorFct && censor.length > 1\n\n if (paths.length === 0) return serialize || noop\n\n validate({ paths, serialize, censor })\n\n const { wildcards, wcLen, secret } = parse({ paths, censor })\n\n const compileRestore = restorer()\n const strict = 'strict' in opts ? opts.strict : true\n\n return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({\n secret,\n censor,\n compileRestore,\n serialize,\n groupRedact,\n nestedRedact,\n wildcards,\n wcLen\n }))\n}\n", "'use strict'\n\nconst setLevelSym = Symbol('pino.setLevel')\nconst getLevelSym = Symbol('pino.getLevel')\nconst levelValSym = Symbol('pino.levelVal')\nconst levelCompSym = Symbol('pino.levelComp')\nconst useLevelLabelsSym = Symbol('pino.useLevelLabels')\nconst useOnlyCustomLevelsSym = Symbol('pino.useOnlyCustomLevels')\nconst mixinSym = Symbol('pino.mixin')\n\nconst lsCacheSym = Symbol('pino.lsCache')\nconst chindingsSym = Symbol('pino.chindings')\n\nconst asJsonSym = Symbol('pino.asJson')\nconst writeSym = Symbol('pino.write')\nconst redactFmtSym = Symbol('pino.redactFmt')\n\nconst timeSym = Symbol('pino.time')\nconst timeSliceIndexSym = Symbol('pino.timeSliceIndex')\nconst streamSym = Symbol('pino.stream')\nconst stringifySym = Symbol('pino.stringify')\nconst stringifySafeSym = Symbol('pino.stringifySafe')\nconst stringifiersSym = Symbol('pino.stringifiers')\nconst endSym = Symbol('pino.end')\nconst formatOptsSym = Symbol('pino.formatOpts')\nconst messageKeySym = Symbol('pino.messageKey')\nconst errorKeySym = Symbol('pino.errorKey')\nconst nestedKeySym = Symbol('pino.nestedKey')\nconst nestedKeyStrSym = Symbol('pino.nestedKeyStr')\nconst mixinMergeStrategySym = Symbol('pino.mixinMergeStrategy')\nconst msgPrefixSym = Symbol('pino.msgPrefix')\n\nconst wildcardFirstSym = Symbol('pino.wildcardFirst')\n\n// public symbols, no need to use the same pino\n// version for these\nconst serializersSym = Symbol.for('pino.serializers')\nconst formattersSym = Symbol.for('pino.formatters')\nconst hooksSym = Symbol.for('pino.hooks')\nconst needsMetadataGsym = Symbol.for('pino.metadata')\n\nmodule.exports = {\n setLevelSym,\n getLevelSym,\n levelValSym,\n levelCompSym,\n useLevelLabelsSym,\n mixinSym,\n lsCacheSym,\n chindingsSym,\n asJsonSym,\n writeSym,\n serializersSym,\n redactFmtSym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n stringifySym,\n stringifySafeSym,\n stringifiersSym,\n endSym,\n formatOptsSym,\n messageKeySym,\n errorKeySym,\n nestedKeySym,\n wildcardFirstSym,\n needsMetadataGsym,\n useOnlyCustomLevelsSym,\n formattersSym,\n hooksSym,\n nestedKeyStrSym,\n mixinMergeStrategySym,\n msgPrefixSym\n}\n", "'use strict'\n\nconst fastRedact = require('fast-redact')\nconst { redactFmtSym, wildcardFirstSym } = require('./symbols')\nconst { rx, validator } = fastRedact\n\nconst validate = validator({\n ERR_PATHS_MUST_BE_STRINGS: () => 'pino \u2013 redacted paths must be strings',\n ERR_INVALID_PATH: (s) => `pino \u2013 redact paths array contains an invalid path (${s})`\n})\n\nconst CENSOR = '[Redacted]'\nconst strict = false // TODO should this be configurable?\n\nfunction redaction (opts, serialize) {\n const { paths, censor } = handle(opts)\n\n const shape = paths.reduce((o, str) => {\n rx.lastIndex = 0\n const first = rx.exec(str)\n const next = rx.exec(str)\n\n // ns is the top-level path segment, brackets + quoting removed.\n let ns = first[1] !== undefined\n ? first[1].replace(/^(?:\"|'|`)(.*)(?:\"|'|`)$/, '$1')\n : first[0]\n\n if (ns === '*') {\n ns = wildcardFirstSym\n }\n\n // top level key:\n if (next === null) {\n o[ns] = null\n return o\n }\n\n // path with at least two segments:\n // if ns is already redacted at the top level, ignore lower level redactions\n if (o[ns] === null) {\n return o\n }\n\n const { index } = next\n const nextPath = `${str.substr(index, str.length - 1)}`\n\n o[ns] = o[ns] || []\n\n // shape is a mix of paths beginning with literal values and wildcard\n // paths [ \"a.b.c\", \"*.b.z\" ] should reduce to a shape of\n // { \"a\": [ \"b.c\", \"b.z\" ], *: [ \"b.z\" ] }\n // note: \"b.z\" is in both \"a\" and * arrays because \"a\" matches the wildcard.\n // (* entry has wildcardFirstSym as key)\n if (ns !== wildcardFirstSym && o[ns].length === 0) {\n // first time ns's get all '*' redactions so far\n o[ns].push(...(o[wildcardFirstSym] || []))\n }\n\n if (ns === wildcardFirstSym) {\n // new * path gets added to all previously registered literal ns's.\n Object.keys(o).forEach(function (k) {\n if (o[k]) {\n o[k].push(nextPath)\n }\n })\n }\n\n o[ns].push(nextPath)\n return o\n }, {})\n\n // the redactor assigned to the format symbol key\n // provides top level redaction for instances where\n // an object is interpolated into the msg string\n const result = {\n [redactFmtSym]: fastRedact({ paths, censor, serialize, strict })\n }\n\n const topCensor = (...args) => {\n return typeof censor === 'function' ? serialize(censor(...args)) : serialize(censor)\n }\n\n return [...Object.keys(shape), ...Object.getOwnPropertySymbols(shape)].reduce((o, k) => {\n // top level key:\n if (shape[k] === null) {\n o[k] = (value) => topCensor(value, [k])\n } else {\n const wrappedCensor = typeof censor === 'function'\n ? (value, path) => {\n return censor(value, [k, ...path])\n }\n : censor\n o[k] = fastRedact({\n paths: shape[k],\n censor: wrappedCensor,\n serialize,\n strict\n })\n }\n return o\n }, result)\n}\n\nfunction handle (opts) {\n if (Array.isArray(opts)) {\n opts = { paths: opts, censor: CENSOR }\n validate(opts)\n return opts\n }\n let { paths, censor = CENSOR, remove } = opts\n if (Array.isArray(paths) === false) { throw Error('pino \u2013 redact must contain an array of strings') }\n if (remove === true) censor = undefined\n validate({ paths, censor })\n\n return { paths, censor }\n}\n\nmodule.exports = redaction\n", "'use strict'\n\nconst nullTime = () => ''\n\nconst epochTime = () => `,\"time\":${Date.now()}`\n\nconst unixTime = () => `,\"time\":${Math.round(Date.now() / 1000.0)}`\n\nconst isoTime = () => `,\"time\":\"${new Date(Date.now()).toISOString()}\"` // using Date.now() for testability\n\nmodule.exports = { nullTime, epochTime, unixTime, isoTime }\n", "'use strict'\nfunction tryStringify (o) {\n try { return JSON.stringify(o) } catch(e) { return '\"[Circular]\"' }\n}\n\nmodule.exports = format\n\nfunction format(f, args, opts) {\n var ss = (opts && opts.stringify) || tryStringify\n var offset = 1\n if (typeof f === 'object' && f !== null) {\n var len = args.length + offset\n if (len === 1) return f\n var objects = new Array(len)\n objects[0] = ss(f)\n for (var index = 1; index < len; index++) {\n objects[index] = ss(args[index])\n }\n return objects.join(' ')\n }\n if (typeof f !== 'string') {\n return f\n }\n var argLen = args.length\n if (argLen === 0) return f\n var str = ''\n var a = 1 - offset\n var lastPos = -1\n var flen = (f && f.length) || 0\n for (var i = 0; i < flen;) {\n if (f.charCodeAt(i) === 37 && i + 1 < flen) {\n lastPos = lastPos > -1 ? lastPos : 0\n switch (f.charCodeAt(i + 1)) {\n case 100: // 'd'\n case 102: // 'f'\n if (a >= argLen)\n break\n if (args[a] == null) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += Number(args[a])\n lastPos = i + 2\n i++\n break\n case 105: // 'i'\n if (a >= argLen)\n break\n if (args[a] == null) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += Math.floor(Number(args[a]))\n lastPos = i + 2\n i++\n break\n case 79: // 'O'\n case 111: // 'o'\n case 106: // 'j'\n if (a >= argLen)\n break\n if (args[a] === undefined) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n var type = typeof args[a]\n if (type === 'string') {\n str += '\\'' + args[a] + '\\''\n lastPos = i + 2\n i++\n break\n }\n if (type === 'function') {\n str += args[a].name || ''\n lastPos = i + 2\n i++\n break\n }\n str += ss(args[a])\n lastPos = i + 2\n i++\n break\n case 115: // 's'\n if (a >= argLen)\n break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += String(args[a])\n lastPos = i + 2\n i++\n break\n case 37: // '%'\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += '%'\n lastPos = i + 2\n i++\n a--\n break\n }\n ++a\n }\n ++i\n }\n if (lastPos === -1)\n return f\n else if (lastPos < flen) {\n str += f.slice(lastPos)\n }\n\n return str\n}\n", "'use strict'\n\n/* global SharedArrayBuffer, Atomics */\n\nif (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') {\n const nil = new Int32Array(new SharedArrayBuffer(4))\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n\n Atomics.wait(nil, 0, 0, Number(ms))\n }\n module.exports = sleep\n} else {\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n const target = Date.now() + Number(ms)\n while (target > Date.now()){}\n }\n\n module.exports = sleep\n\n}\n", "'use strict'\n\nconst fs = require('fs')\nconst EventEmitter = require('events')\nconst inherits = require('util').inherits\nconst path = require('path')\nconst sleep = require('atomic-sleep')\nconst assert = require('assert')\n\nconst BUSY_WRITE_TIMEOUT = 100\nconst kEmptyBuffer = Buffer.allocUnsafe(0)\n\n// 16 KB. Don't write more than docker buffer size.\n// https://github.com/moby/moby/blob/513ec73831269947d38a644c278ce3cac36783b2/daemon/logger/copier.go#L13\nconst MAX_WRITE = 16 * 1024\n\nconst kContentModeBuffer = 'buffer'\nconst kContentModeUtf8 = 'utf8'\n\nconst [major, minor] = (process.versions.node || '0.0').split('.').map(Number)\nconst kCopyBuffer = major >= 22 && minor >= 7\n\nfunction openFile (file, sonic) {\n sonic._opening = true\n sonic._writing = true\n sonic._asyncDrainScheduled = false\n\n // NOTE: 'error' and 'ready' events emitted below only relevant when sonic.sync===false\n // for sync mode, there is no way to add a listener that will receive these\n\n function fileOpened (err, fd) {\n if (err) {\n sonic._reopening = false\n sonic._writing = false\n sonic._opening = false\n\n if (sonic.sync) {\n process.nextTick(() => {\n if (sonic.listenerCount('error') > 0) {\n sonic.emit('error', err)\n }\n })\n } else {\n sonic.emit('error', err)\n }\n return\n }\n\n const reopening = sonic._reopening\n\n sonic.fd = fd\n sonic.file = file\n sonic._reopening = false\n sonic._opening = false\n sonic._writing = false\n\n if (sonic.sync) {\n process.nextTick(() => sonic.emit('ready'))\n } else {\n sonic.emit('ready')\n }\n\n if (sonic.destroyed) {\n return\n }\n\n // start\n if ((!sonic._writing && sonic._len > sonic.minLength) || sonic._flushPending) {\n sonic._actualWrite()\n } else if (reopening) {\n process.nextTick(() => sonic.emit('drain'))\n }\n }\n\n const flags = sonic.append ? 'a' : 'w'\n const mode = sonic.mode\n\n if (sonic.sync) {\n try {\n if (sonic.mkdir) fs.mkdirSync(path.dirname(file), { recursive: true })\n const fd = fs.openSync(file, flags, mode)\n fileOpened(null, fd)\n } catch (err) {\n fileOpened(err)\n throw err\n }\n } else if (sonic.mkdir) {\n fs.mkdir(path.dirname(file), { recursive: true }, (err) => {\n if (err) return fileOpened(err)\n fs.open(file, flags, mode, fileOpened)\n })\n } else {\n fs.open(file, flags, mode, fileOpened)\n }\n}\n\nfunction SonicBoom (opts) {\n if (!(this instanceof SonicBoom)) {\n return new SonicBoom(opts)\n }\n\n let { fd, dest, minLength, maxLength, maxWrite, periodicFlush, sync, append = true, mkdir, retryEAGAIN, fsync, contentMode, mode } = opts || {}\n\n fd = fd || dest\n\n this._len = 0\n this.fd = -1\n this._bufs = []\n this._lens = []\n this._writing = false\n this._ending = false\n this._reopening = false\n this._asyncDrainScheduled = false\n this._flushPending = false\n this._hwm = Math.max(minLength || 0, 16387)\n this.file = null\n this.destroyed = false\n this.minLength = minLength || 0\n this.maxLength = maxLength || 0\n this.maxWrite = maxWrite || MAX_WRITE\n this._periodicFlush = periodicFlush || 0\n this._periodicFlushTimer = undefined\n this.sync = sync || false\n this.writable = true\n this._fsync = fsync || false\n this.append = append || false\n this.mode = mode\n this.retryEAGAIN = retryEAGAIN || (() => true)\n this.mkdir = mkdir || false\n\n let fsWriteSync\n let fsWrite\n if (contentMode === kContentModeBuffer) {\n this._writingBuf = kEmptyBuffer\n this.write = writeBuffer\n this.flush = flushBuffer\n this.flushSync = flushBufferSync\n this._actualWrite = actualWriteBuffer\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf)\n fsWrite = () => fs.write(this.fd, this._writingBuf, this.release)\n } else if (contentMode === undefined || contentMode === kContentModeUtf8) {\n this._writingBuf = ''\n this.write = write\n this.flush = flush\n this.flushSync = flushSync\n this._actualWrite = actualWrite\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf, 'utf8')\n fsWrite = () => fs.write(this.fd, this._writingBuf, 'utf8', this.release)\n } else {\n throw new Error(`SonicBoom supports \"${kContentModeUtf8}\" and \"${kContentModeBuffer}\", but passed ${contentMode}`)\n }\n\n if (typeof fd === 'number') {\n this.fd = fd\n process.nextTick(() => this.emit('ready'))\n } else if (typeof fd === 'string') {\n openFile(fd, this)\n } else {\n throw new Error('SonicBoom supports only file descriptors and files')\n }\n if (this.minLength >= this.maxWrite) {\n throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`)\n }\n\n this.release = (err, n) => {\n if (err) {\n if ((err.code === 'EAGAIN' || err.code === 'EBUSY') && this.retryEAGAIN(err, this._writingBuf.length, this._len - this._writingBuf.length)) {\n if (this.sync) {\n // This error code should not happen in sync mode, because it is\n // not using the underlining operating system asynchronous functions.\n // However it happens, and so we handle it.\n // Ref: https://github.com/pinojs/pino/issues/783\n try {\n sleep(BUSY_WRITE_TIMEOUT)\n this.release(undefined, 0)\n } catch (err) {\n this.release(err)\n }\n } else {\n // Let's give the destination some time to process the chunk.\n setTimeout(fsWrite, BUSY_WRITE_TIMEOUT)\n }\n } else {\n this._writing = false\n\n this.emit('error', err)\n }\n return\n }\n\n this.emit('write', n)\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n\n if (this._writingBuf.length) {\n if (!this.sync) {\n fsWrite()\n return\n }\n\n try {\n do {\n const n = fsWriteSync()\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n } while (this._writingBuf.length)\n } catch (err) {\n this.release(err)\n return\n }\n }\n\n if (this._fsync) {\n fs.fsyncSync(this.fd)\n }\n\n const len = this._len\n if (this._reopening) {\n this._writing = false\n this._reopening = false\n this.reopen()\n } else if (len > this.minLength) {\n this._actualWrite()\n } else if (this._ending) {\n if (len > 0) {\n this._actualWrite()\n } else {\n this._writing = false\n actualClose(this)\n }\n } else {\n this._writing = false\n if (this.sync) {\n if (!this._asyncDrainScheduled) {\n this._asyncDrainScheduled = true\n process.nextTick(emitDrain, this)\n }\n } else {\n this.emit('drain')\n }\n }\n }\n\n this.on('newListener', function (name) {\n if (name === 'drain') {\n this._asyncDrainScheduled = false\n }\n })\n\n if (this._periodicFlush !== 0) {\n this._periodicFlushTimer = setInterval(() => this.flush(null), this._periodicFlush)\n this._periodicFlushTimer.unref()\n }\n}\n\n/**\n * Release the writingBuf after fs.write n bytes data\n * @param {string | Buffer} writingBuf - currently writing buffer, usually be instance._writingBuf.\n * @param {number} len - currently buffer length, usually be instance._len.\n * @param {number} n - number of bytes fs already written\n * @returns {{writingBuf: string | Buffer, len: number}} released writingBuf and length\n */\nfunction releaseWritingBuf (writingBuf, len, n) {\n // if Buffer.byteLength is equal to n, that means writingBuf contains no multi-byte character\n if (typeof writingBuf === 'string' && Buffer.byteLength(writingBuf) !== n) {\n // Since the fs.write callback parameter `n` means how many bytes the passed of string\n // We calculate the original string length for avoiding the multi-byte character issue\n n = Buffer.from(writingBuf).subarray(0, n).toString().length\n }\n len = Math.max(len - n, 0)\n writingBuf = writingBuf.slice(n)\n return { writingBuf, len }\n}\n\nfunction emitDrain (sonic) {\n const hasListeners = sonic.listenerCount('drain') > 0\n if (!hasListeners) return\n sonic._asyncDrainScheduled = false\n sonic.emit('drain')\n}\n\ninherits(SonicBoom, EventEmitter)\n\nfunction mergeBuf (bufs, len) {\n if (bufs.length === 0) {\n return kEmptyBuffer\n }\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return Buffer.concat(bufs, len)\n}\n\nfunction write (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n bufs[bufs.length - 1].length + data.length > this.maxWrite\n ) {\n bufs.push('' + data)\n } else {\n bufs[bufs.length - 1] += data\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction writeBuffer (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n const lens = this._lens\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n lens[lens.length - 1] + data.length > this.maxWrite\n ) {\n bufs.push([data])\n lens.push(data.length)\n } else {\n bufs[bufs.length - 1].push(data)\n lens[lens.length - 1] += data.length\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction callFlushCallbackOnDrain (cb) {\n this._flushPending = true\n const onDrain = () => {\n // only if _fsync is false to avoid double fsync\n if (!this._fsync) {\n try {\n fs.fsync(this.fd, (err) => {\n this._flushPending = false\n cb(err)\n })\n } catch (err) {\n cb(err)\n }\n } else {\n this._flushPending = false\n cb()\n }\n this.off('error', onError)\n }\n const onError = (err) => {\n this._flushPending = false\n cb(err)\n this.off('drain', onDrain)\n }\n\n this.once('drain', onDrain)\n this.once('error', onError)\n}\n\nfunction flush (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push('')\n }\n\n this._actualWrite()\n}\n\nfunction flushBuffer (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push([])\n this._lens.push(0)\n }\n\n this._actualWrite()\n}\n\nSonicBoom.prototype.reopen = function (file) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.reopen(file)\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n if (!this.file) {\n throw new Error('Unable to reopen a file descriptor, you must pass a file to SonicBoom')\n }\n\n if (file) {\n this.file = file\n }\n this._reopening = true\n\n if (this._writing) {\n return\n }\n\n const fd = this.fd\n this.once('ready', () => {\n if (fd !== this.fd) {\n fs.close(fd, (err) => {\n if (err) {\n return this.emit('error', err)\n }\n })\n }\n })\n\n openFile(this.file, this)\n}\n\nSonicBoom.prototype.end = function () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.end()\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n this._ending = true\n\n if (this._writing) {\n return\n }\n\n if (this._len > 0 && this.fd >= 0) {\n this._actualWrite()\n } else {\n actualClose(this)\n }\n}\n\nfunction flushSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift(this._writingBuf)\n this._writingBuf = ''\n }\n\n let buf = ''\n while (this._bufs.length || buf) {\n if (buf.length <= 0) {\n buf = this._bufs[0]\n }\n try {\n const n = fs.writeSync(this.fd, buf, 'utf8')\n const releasedBufObj = releaseWritingBuf(buf, this._len, n)\n buf = releasedBufObj.writingBuf\n this._len = releasedBufObj.len\n if (buf.length <= 0) {\n this._bufs.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n\n try {\n fs.fsyncSync(this.fd)\n } catch {\n // Skip the error. The fd might not support fsync.\n }\n}\n\nfunction flushBufferSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift([this._writingBuf])\n this._writingBuf = kEmptyBuffer\n }\n\n let buf = kEmptyBuffer\n while (this._bufs.length || buf.length) {\n if (buf.length <= 0) {\n buf = mergeBuf(this._bufs[0], this._lens[0])\n }\n try {\n const n = fs.writeSync(this.fd, buf)\n buf = buf.subarray(n)\n this._len = Math.max(this._len - n, 0)\n if (buf.length <= 0) {\n this._bufs.shift()\n this._lens.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n}\n\nSonicBoom.prototype.destroy = function () {\n if (this.destroyed) {\n return\n }\n actualClose(this)\n}\n\nfunction actualWrite () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf || this._bufs.shift() || ''\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf, 'utf8')\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n fs.write(this.fd, this._writingBuf, 'utf8', release)\n }\n}\n\nfunction actualWriteBuffer () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift())\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf)\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n // fs.write will need to copy string to buffer anyway so\n // we do it here to avoid the overhead of calculating the buffer size\n // in releaseWritingBuf.\n if (kCopyBuffer) {\n this._writingBuf = Buffer.from(this._writingBuf)\n }\n fs.write(this.fd, this._writingBuf, release)\n }\n}\n\nfunction actualClose (sonic) {\n if (sonic.fd === -1) {\n sonic.once('ready', actualClose.bind(null, sonic))\n return\n }\n\n if (sonic._periodicFlushTimer !== undefined) {\n clearInterval(sonic._periodicFlushTimer)\n }\n\n sonic.destroyed = true\n sonic._bufs = []\n sonic._lens = []\n\n assert(typeof sonic.fd === 'number', `sonic.fd must be a number, got ${typeof sonic.fd}`)\n try {\n fs.fsync(sonic.fd, closeWrapped)\n } catch {\n }\n\n function closeWrapped () {\n // We skip errors in fsync\n\n if (sonic.fd !== 1 && sonic.fd !== 2) {\n fs.close(sonic.fd, done)\n } else {\n done()\n }\n }\n\n function done (err) {\n if (err) {\n sonic.emit('error', err)\n return\n }\n\n if (sonic._ending && !sonic._writing) {\n sonic.emit('finish')\n }\n sonic.emit('close')\n }\n}\n\n/**\n * These export configurations enable JS and TS developers\n * to consumer SonicBoom in whatever way best suits their needs.\n * Some examples of supported import syntax includes:\n * - `const SonicBoom = require('SonicBoom')`\n * - `const { SonicBoom } = require('SonicBoom')`\n * - `import * as SonicBoom from 'SonicBoom'`\n * - `import { SonicBoom } from 'SonicBoom'`\n * - `import SonicBoom from 'SonicBoom'`\n */\nSonicBoom.SonicBoom = SonicBoom\nSonicBoom.default = SonicBoom\nmodule.exports = SonicBoom\n", "'use strict'\n\nconst refs = {\n exit: [],\n beforeExit: []\n}\nconst functions = {\n exit: onExit,\n beforeExit: onBeforeExit\n}\n\nlet registry\n\nfunction ensureRegistry () {\n if (registry === undefined) {\n registry = new FinalizationRegistry(clear)\n }\n}\n\nfunction install (event) {\n if (refs[event].length > 0) {\n return\n }\n\n process.on(event, functions[event])\n}\n\nfunction uninstall (event) {\n if (refs[event].length > 0) {\n return\n }\n process.removeListener(event, functions[event])\n if (refs.exit.length === 0 && refs.beforeExit.length === 0) {\n registry = undefined\n }\n}\n\nfunction onExit () {\n callRefs('exit')\n}\n\nfunction onBeforeExit () {\n callRefs('beforeExit')\n}\n\nfunction callRefs (event) {\n for (const ref of refs[event]) {\n const obj = ref.deref()\n const fn = ref.fn\n\n // This should always happen, however GC is\n // undeterministic so it might not happen.\n /* istanbul ignore else */\n if (obj !== undefined) {\n fn(obj, event)\n }\n }\n refs[event] = []\n}\n\nfunction clear (ref) {\n for (const event of ['exit', 'beforeExit']) {\n const index = refs[event].indexOf(ref)\n refs[event].splice(index, index + 1)\n uninstall(event)\n }\n}\n\nfunction _register (event, obj, fn) {\n if (obj === undefined) {\n throw new Error('the object can\\'t be undefined')\n }\n install(event)\n const ref = new WeakRef(obj)\n ref.fn = fn\n\n ensureRegistry()\n registry.register(obj, ref)\n refs[event].push(ref)\n}\n\nfunction register (obj, fn) {\n _register('exit', obj, fn)\n}\n\nfunction registerBeforeExit (obj, fn) {\n _register('beforeExit', obj, fn)\n}\n\nfunction unregister (obj) {\n if (registry === undefined) {\n return\n }\n registry.unregister(obj)\n for (const event of ['exit', 'beforeExit']) {\n refs[event] = refs[event].filter((ref) => {\n const _obj = ref.deref()\n return _obj && _obj !== obj\n })\n uninstall(event)\n }\n}\n\nmodule.exports = {\n register,\n registerBeforeExit,\n unregister\n}\n", "{\n \"name\": \"thread-stream\",\n \"version\": \"3.1.0\",\n \"description\": \"A streaming way to send data to a Node.js Worker Thread\",\n \"main\": \"index.js\",\n \"types\": \"index.d.ts\",\n \"dependencies\": {\n \"real-require\": \"^0.2.0\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^20.1.0\",\n \"@types/tap\": \"^15.0.0\",\n \"@yao-pkg/pkg\": \"^5.11.5\",\n \"desm\": \"^1.3.0\",\n \"fastbench\": \"^1.0.1\",\n \"husky\": \"^9.0.6\",\n \"pino-elasticsearch\": \"^8.0.0\",\n \"sonic-boom\": \"^4.0.1\",\n \"standard\": \"^17.0.0\",\n \"tap\": \"^16.2.0\",\n \"ts-node\": \"^10.8.0\",\n \"typescript\": \"^5.3.2\",\n \"why-is-node-running\": \"^2.2.2\"\n },\n \"scripts\": {\n \"build\": \"tsc --noEmit\",\n \"test\": \"standard && npm run build && npm run transpile && tap \\\"test/**/*.test.*js\\\" && tap --ts test/*.test.*ts\",\n \"test:ci\": \"standard && npm run transpile && npm run test:ci:js && npm run test:ci:ts\",\n \"test:ci:js\": \"tap --no-check-coverage --timeout=120 --coverage-report=lcovonly \\\"test/**/*.test.*js\\\"\",\n \"test:ci:ts\": \"tap --ts --no-check-coverage --coverage-report=lcovonly \\\"test/**/*.test.*ts\\\"\",\n \"test:yarn\": \"npm run transpile && tap \\\"test/**/*.test.js\\\" --no-check-coverage\",\n \"transpile\": \"sh ./test/ts/transpile.sh\",\n \"prepare\": \"husky install\"\n },\n \"standard\": {\n \"ignore\": [\n \"test/ts/**/*\",\n \"test/syntax-error.mjs\"\n ]\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/mcollina/thread-stream.git\"\n },\n \"keywords\": [\n \"worker\",\n \"thread\",\n \"threads\",\n \"stream\"\n ],\n \"author\": \"Matteo Collina \",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/mcollina/thread-stream/issues\"\n },\n \"homepage\": \"https://github.com/mcollina/thread-stream#readme\"\n}\n", "'use strict'\n\nconst MAX_TIMEOUT = 1000\n\nfunction wait (state, index, expected, timeout, done) {\n const max = Date.now() + timeout\n let current = Atomics.load(state, index)\n if (current === expected) {\n done(null, 'ok')\n return\n }\n let prior = current\n const check = (backoff) => {\n if (Date.now() > max) {\n done(null, 'timed-out')\n } else {\n setTimeout(() => {\n prior = current\n current = Atomics.load(state, index)\n if (current === prior) {\n check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)\n } else {\n if (current === expected) done(null, 'ok')\n else done(null, 'not-equal')\n }\n }, backoff)\n }\n }\n check(1)\n}\n\n// let waitDiffCount = 0\nfunction waitDiff (state, index, expected, timeout, done) {\n // const id = waitDiffCount++\n // process._rawDebug(`>>> waitDiff ${id}`)\n const max = Date.now() + timeout\n let current = Atomics.load(state, index)\n if (current !== expected) {\n done(null, 'ok')\n return\n }\n const check = (backoff) => {\n // process._rawDebug(`${id} ${index} current ${current} expected ${expected}`)\n // process._rawDebug('' + backoff)\n if (Date.now() > max) {\n done(null, 'timed-out')\n } else {\n setTimeout(() => {\n current = Atomics.load(state, index)\n if (current !== expected) {\n done(null, 'ok')\n } else {\n check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)\n }\n }, backoff)\n }\n }\n check(1)\n}\n\nmodule.exports = { wait, waitDiff }\n", "'use strict'\n\nconst WRITE_INDEX = 4\nconst READ_INDEX = 8\n\nmodule.exports = {\n WRITE_INDEX,\n READ_INDEX\n}\n", "'use strict'\n\nconst { version } = require('./package.json')\nconst { EventEmitter } = require('events')\nconst { Worker } = require('worker_threads')\nconst { join } = require('path')\nconst { pathToFileURL } = require('url')\nconst { wait } = require('./lib/wait')\nconst {\n WRITE_INDEX,\n READ_INDEX\n} = require('./lib/indexes')\nconst buffer = require('buffer')\nconst assert = require('assert')\n\nconst kImpl = Symbol('kImpl')\n\n// V8 limit for string size\nconst MAX_STRING = buffer.constants.MAX_STRING_LENGTH\n\nclass FakeWeakRef {\n constructor (value) {\n this._value = value\n }\n\n deref () {\n return this._value\n }\n}\n\nclass FakeFinalizationRegistry {\n register () {}\n\n unregister () {}\n}\n\n// Currently using FinalizationRegistry with code coverage breaks the world\n// Ref: https://github.com/nodejs/node/issues/49344\nconst FinalizationRegistry = process.env.NODE_V8_COVERAGE ? FakeFinalizationRegistry : global.FinalizationRegistry || FakeFinalizationRegistry\nconst WeakRef = process.env.NODE_V8_COVERAGE ? FakeWeakRef : global.WeakRef || FakeWeakRef\n\nconst registry = new FinalizationRegistry((worker) => {\n if (worker.exited) {\n return\n }\n worker.terminate()\n})\n\nfunction createWorker (stream, opts) {\n const { filename, workerData } = opts\n\n const bundlerOverrides = '__bundlerPathsOverrides' in globalThis ? globalThis.__bundlerPathsOverrides : {}\n const toExecute = bundlerOverrides['thread-stream-worker'] || join(__dirname, 'lib', 'worker.js')\n\n const worker = new Worker(toExecute, {\n ...opts.workerOpts,\n trackUnmanagedFds: false,\n workerData: {\n filename: filename.indexOf('file://') === 0\n ? filename\n : pathToFileURL(filename).href,\n dataBuf: stream[kImpl].dataBuf,\n stateBuf: stream[kImpl].stateBuf,\n workerData: {\n $context: {\n threadStreamVersion: version\n },\n ...workerData\n }\n }\n })\n\n // We keep a strong reference for now,\n // we need to start writing first\n worker.stream = new FakeWeakRef(stream)\n\n worker.on('message', onWorkerMessage)\n worker.on('exit', onWorkerExit)\n registry.register(stream, worker)\n\n return worker\n}\n\nfunction drain (stream) {\n assert(!stream[kImpl].sync)\n if (stream[kImpl].needDrain) {\n stream[kImpl].needDrain = false\n stream.emit('drain')\n }\n}\n\nfunction nextFlush (stream) {\n const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n let leftover = stream[kImpl].data.length - writeIndex\n\n if (leftover > 0) {\n if (stream[kImpl].buf.length === 0) {\n stream[kImpl].flushing = false\n\n if (stream[kImpl].ending) {\n end(stream)\n } else if (stream[kImpl].needDrain) {\n process.nextTick(drain, stream)\n }\n\n return\n }\n\n let toWrite = stream[kImpl].buf.slice(0, leftover)\n let toWriteBytes = Buffer.byteLength(toWrite)\n if (toWriteBytes <= leftover) {\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n // process._rawDebug('writing ' + toWrite.length)\n write(stream, toWrite, nextFlush.bind(null, stream))\n } else {\n // multi-byte utf-8\n stream.flush(() => {\n // err is already handled in flush()\n if (stream.destroyed) {\n return\n }\n\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n\n // Find a toWrite length that fits the buffer\n // it must exists as the buffer is at least 4 bytes length\n // and the max utf-8 length for a char is 4 bytes.\n while (toWriteBytes > stream[kImpl].data.length) {\n leftover = leftover / 2\n toWrite = stream[kImpl].buf.slice(0, leftover)\n toWriteBytes = Buffer.byteLength(toWrite)\n }\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n write(stream, toWrite, nextFlush.bind(null, stream))\n })\n }\n } else if (leftover === 0) {\n if (writeIndex === 0 && stream[kImpl].buf.length === 0) {\n // we had a flushSync in the meanwhile\n return\n }\n stream.flush(() => {\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n nextFlush(stream)\n })\n } else {\n // This should never happen\n destroy(stream, new Error('overwritten'))\n }\n}\n\nfunction onWorkerMessage (msg) {\n const stream = this.stream.deref()\n if (stream === undefined) {\n this.exited = true\n // Terminate the worker.\n this.terminate()\n return\n }\n\n switch (msg.code) {\n case 'READY':\n // Replace the FakeWeakRef with a\n // proper one.\n this.stream = new WeakRef(stream)\n\n stream.flush(() => {\n stream[kImpl].ready = true\n stream.emit('ready')\n })\n break\n case 'ERROR':\n destroy(stream, msg.err)\n break\n case 'EVENT':\n if (Array.isArray(msg.args)) {\n stream.emit(msg.name, ...msg.args)\n } else {\n stream.emit(msg.name, msg.args)\n }\n break\n case 'WARNING':\n process.emitWarning(msg.err)\n break\n default:\n destroy(stream, new Error('this should not happen: ' + msg.code))\n }\n}\n\nfunction onWorkerExit (code) {\n const stream = this.stream.deref()\n if (stream === undefined) {\n // Nothing to do, the worker already exit\n return\n }\n registry.unregister(stream)\n stream.worker.exited = true\n stream.worker.off('exit', onWorkerExit)\n destroy(stream, code !== 0 ? new Error('the worker thread exited') : null)\n}\n\nclass ThreadStream extends EventEmitter {\n constructor (opts = {}) {\n super()\n\n if (opts.bufferSize < 4) {\n throw new Error('bufferSize must at least fit a 4-byte utf-8 char')\n }\n\n this[kImpl] = {}\n this[kImpl].stateBuf = new SharedArrayBuffer(128)\n this[kImpl].state = new Int32Array(this[kImpl].stateBuf)\n this[kImpl].dataBuf = new SharedArrayBuffer(opts.bufferSize || 4 * 1024 * 1024)\n this[kImpl].data = Buffer.from(this[kImpl].dataBuf)\n this[kImpl].sync = opts.sync || false\n this[kImpl].ending = false\n this[kImpl].ended = false\n this[kImpl].needDrain = false\n this[kImpl].destroyed = false\n this[kImpl].flushing = false\n this[kImpl].ready = false\n this[kImpl].finished = false\n this[kImpl].errored = null\n this[kImpl].closed = false\n this[kImpl].buf = ''\n\n // TODO (fix): Make private?\n this.worker = createWorker(this, opts) // TODO (fix): make private\n this.on('message', (message, transferList) => {\n this.worker.postMessage(message, transferList)\n })\n }\n\n write (data) {\n if (this[kImpl].destroyed) {\n error(this, new Error('the worker has exited'))\n return false\n }\n\n if (this[kImpl].ending) {\n error(this, new Error('the worker is ending'))\n return false\n }\n\n if (this[kImpl].flushing && this[kImpl].buf.length + data.length >= MAX_STRING) {\n try {\n writeSync(this)\n this[kImpl].flushing = true\n } catch (err) {\n destroy(this, err)\n return false\n }\n }\n\n this[kImpl].buf += data\n\n if (this[kImpl].sync) {\n try {\n writeSync(this)\n return true\n } catch (err) {\n destroy(this, err)\n return false\n }\n }\n\n if (!this[kImpl].flushing) {\n this[kImpl].flushing = true\n setImmediate(nextFlush, this)\n }\n\n this[kImpl].needDrain = this[kImpl].data.length - this[kImpl].buf.length - Atomics.load(this[kImpl].state, WRITE_INDEX) <= 0\n return !this[kImpl].needDrain\n }\n\n end () {\n if (this[kImpl].destroyed) {\n return\n }\n\n this[kImpl].ending = true\n end(this)\n }\n\n flush (cb) {\n if (this[kImpl].destroyed) {\n if (typeof cb === 'function') {\n process.nextTick(cb, new Error('the worker has exited'))\n }\n return\n }\n\n // TODO write all .buf\n const writeIndex = Atomics.load(this[kImpl].state, WRITE_INDEX)\n // process._rawDebug(`(flush) readIndex (${Atomics.load(this.state, READ_INDEX)}) writeIndex (${Atomics.load(this.state, WRITE_INDEX)})`)\n wait(this[kImpl].state, READ_INDEX, writeIndex, Infinity, (err, res) => {\n if (err) {\n destroy(this, err)\n process.nextTick(cb, err)\n return\n }\n if (res === 'not-equal') {\n // TODO handle deadlock\n this.flush(cb)\n return\n }\n process.nextTick(cb)\n })\n }\n\n flushSync () {\n if (this[kImpl].destroyed) {\n return\n }\n\n writeSync(this)\n flushSync(this)\n }\n\n unref () {\n this.worker.unref()\n }\n\n ref () {\n this.worker.ref()\n }\n\n get ready () {\n return this[kImpl].ready\n }\n\n get destroyed () {\n return this[kImpl].destroyed\n }\n\n get closed () {\n return this[kImpl].closed\n }\n\n get writable () {\n return !this[kImpl].destroyed && !this[kImpl].ending\n }\n\n get writableEnded () {\n return this[kImpl].ending\n }\n\n get writableFinished () {\n return this[kImpl].finished\n }\n\n get writableNeedDrain () {\n return this[kImpl].needDrain\n }\n\n get writableObjectMode () {\n return false\n }\n\n get writableErrored () {\n return this[kImpl].errored\n }\n}\n\nfunction error (stream, err) {\n setImmediate(() => {\n stream.emit('error', err)\n })\n}\n\nfunction destroy (stream, err) {\n if (stream[kImpl].destroyed) {\n return\n }\n stream[kImpl].destroyed = true\n\n if (err) {\n stream[kImpl].errored = err\n error(stream, err)\n }\n\n if (!stream.worker.exited) {\n stream.worker.terminate()\n .catch(() => {})\n .then(() => {\n stream[kImpl].closed = true\n stream.emit('close')\n })\n } else {\n setImmediate(() => {\n stream[kImpl].closed = true\n stream.emit('close')\n })\n }\n}\n\nfunction write (stream, data, cb) {\n // data is smaller than the shared buffer length\n const current = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n const length = Buffer.byteLength(data)\n stream[kImpl].data.write(data, current)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, current + length)\n Atomics.notify(stream[kImpl].state, WRITE_INDEX)\n cb()\n return true\n}\n\nfunction end (stream) {\n if (stream[kImpl].ended || !stream[kImpl].ending || stream[kImpl].flushing) {\n return\n }\n stream[kImpl].ended = true\n\n try {\n stream.flushSync()\n\n let readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n // process._rawDebug('writing index')\n Atomics.store(stream[kImpl].state, WRITE_INDEX, -1)\n // process._rawDebug(`(end) readIndex (${Atomics.load(stream.state, READ_INDEX)}) writeIndex (${Atomics.load(stream.state, WRITE_INDEX)})`)\n Atomics.notify(stream[kImpl].state, WRITE_INDEX)\n\n // Wait for the process to complete\n let spins = 0\n while (readIndex !== -1) {\n // process._rawDebug(`read = ${read}`)\n Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000)\n readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n if (readIndex === -2) {\n destroy(stream, new Error('end() failed'))\n return\n }\n\n if (++spins === 10) {\n destroy(stream, new Error('end() took too long (10s)'))\n return\n }\n }\n\n process.nextTick(() => {\n stream[kImpl].finished = true\n stream.emit('finish')\n })\n } catch (err) {\n destroy(stream, err)\n }\n // process._rawDebug('end finished...')\n}\n\nfunction writeSync (stream) {\n const cb = () => {\n if (stream[kImpl].ending) {\n end(stream)\n } else if (stream[kImpl].needDrain) {\n process.nextTick(drain, stream)\n }\n }\n stream[kImpl].flushing = false\n\n while (stream[kImpl].buf.length !== 0) {\n const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n let leftover = stream[kImpl].data.length - writeIndex\n if (leftover === 0) {\n flushSync(stream)\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n continue\n } else if (leftover < 0) {\n // stream should never happen\n throw new Error('overwritten')\n }\n\n let toWrite = stream[kImpl].buf.slice(0, leftover)\n let toWriteBytes = Buffer.byteLength(toWrite)\n if (toWriteBytes <= leftover) {\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n // process._rawDebug('writing ' + toWrite.length)\n write(stream, toWrite, cb)\n } else {\n // multi-byte utf-8\n flushSync(stream)\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n\n // Find a toWrite length that fits the buffer\n // it must exists as the buffer is at least 4 bytes length\n // and the max utf-8 length for a char is 4 bytes.\n while (toWriteBytes > stream[kImpl].buf.length) {\n leftover = leftover / 2\n toWrite = stream[kImpl].buf.slice(0, leftover)\n toWriteBytes = Buffer.byteLength(toWrite)\n }\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n write(stream, toWrite, cb)\n }\n }\n}\n\nfunction flushSync (stream) {\n if (stream[kImpl].flushing) {\n throw new Error('unable to flush while flushing')\n }\n\n // process._rawDebug('flushSync started')\n\n const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n\n let spins = 0\n\n // TODO handle deadlock\n while (true) {\n const readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n if (readIndex === -2) {\n throw Error('_flushSync failed')\n }\n\n // process._rawDebug(`(flushSync) readIndex (${readIndex}) writeIndex (${writeIndex})`)\n if (readIndex !== writeIndex) {\n // TODO stream timeouts for some reason.\n Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000)\n } else {\n break\n }\n\n if (++spins === 10) {\n throw new Error('_flushSync took too long (10s)')\n }\n }\n // process._rawDebug('flushSync finished')\n}\n\nmodule.exports = ThreadStream\n", "'use strict'\n\nconst { createRequire } = require('module')\nconst getCallers = require('./caller')\nconst { join, isAbsolute, sep } = require('node:path')\nconst sleep = require('atomic-sleep')\nconst onExit = require('on-exit-leak-free')\nconst ThreadStream = require('thread-stream')\n\nfunction setupOnExit (stream) {\n // This is leak free, it does not leave event handlers\n onExit.register(stream, autoEnd)\n onExit.registerBeforeExit(stream, flush)\n\n stream.on('close', function () {\n onExit.unregister(stream)\n })\n}\n\nfunction buildStream (filename, workerData, workerOpts, sync) {\n const stream = new ThreadStream({\n filename,\n workerData,\n workerOpts,\n sync\n })\n\n stream.on('ready', onReady)\n stream.on('close', function () {\n process.removeListener('exit', onExit)\n })\n\n process.on('exit', onExit)\n\n function onReady () {\n process.removeListener('exit', onExit)\n stream.unref()\n\n if (workerOpts.autoEnd !== false) {\n setupOnExit(stream)\n }\n }\n\n function onExit () {\n /* istanbul ignore next */\n if (stream.closed) {\n return\n }\n stream.flushSync()\n // Apparently there is a very sporadic race condition\n // that in certain OS would prevent the messages to be flushed\n // because the thread might not have been created still.\n // Unfortunately we need to sleep(100) in this case.\n sleep(100)\n stream.end()\n }\n\n return stream\n}\n\nfunction autoEnd (stream) {\n stream.ref()\n stream.flushSync()\n stream.end()\n stream.once('close', function () {\n stream.unref()\n })\n}\n\nfunction flush (stream) {\n stream.flushSync()\n}\n\nfunction transport (fullOptions) {\n const { pipeline, targets, levels, dedupe, worker = {}, caller = getCallers(), sync = false } = fullOptions\n\n const options = {\n ...fullOptions.options\n }\n\n // Backwards compatibility\n const callers = typeof caller === 'string' ? [caller] : caller\n\n // This will be eventually modified by bundlers\n const bundlerOverrides = '__bundlerPathsOverrides' in globalThis ? globalThis.__bundlerPathsOverrides : {}\n\n let target = fullOptions.target\n\n if (target && targets) {\n throw new Error('only one of target or targets can be specified')\n }\n\n if (targets) {\n target = bundlerOverrides['pino-worker'] || join(__dirname, 'worker.js')\n options.targets = targets.filter(dest => dest.target).map((dest) => {\n return {\n ...dest,\n target: fixTarget(dest.target)\n }\n })\n options.pipelines = targets.filter(dest => dest.pipeline).map((dest) => {\n return dest.pipeline.map((t) => {\n return {\n ...t,\n level: dest.level, // duplicate the pipeline `level` property defined in the upper level\n target: fixTarget(t.target)\n }\n })\n })\n } else if (pipeline) {\n target = bundlerOverrides['pino-worker'] || join(__dirname, 'worker.js')\n options.pipelines = [pipeline.map((dest) => {\n return {\n ...dest,\n target: fixTarget(dest.target)\n }\n })]\n }\n\n if (levels) {\n options.levels = levels\n }\n\n if (dedupe) {\n options.dedupe = dedupe\n }\n\n options.pinoWillSendConfig = true\n\n return buildStream(fixTarget(target), options, worker, sync)\n\n function fixTarget (origin) {\n origin = bundlerOverrides[origin] || origin\n\n if (isAbsolute(origin) || origin.indexOf('file://') === 0) {\n return origin\n }\n\n if (origin === 'pino/file') {\n return join(__dirname, '..', 'file.js')\n }\n\n let fixTarget\n\n for (const filePath of callers) {\n try {\n const context = filePath === 'node:repl'\n ? process.cwd() + sep\n : filePath\n\n fixTarget = createRequire(context).resolve(origin)\n break\n } catch (err) {\n // Silent catch\n continue\n }\n }\n\n if (!fixTarget) {\n throw new Error(`unable to determine transport target for \"${origin}\"`)\n }\n\n return fixTarget\n }\n}\n\nmodule.exports = transport\n", "'use strict'\n\n/* eslint no-prototype-builtins: 0 */\n\nconst format = require('quick-format-unescaped')\nconst { mapHttpRequest, mapHttpResponse } = require('pino-std-serializers')\nconst SonicBoom = require('sonic-boom')\nconst onExit = require('on-exit-leak-free')\nconst {\n lsCacheSym,\n chindingsSym,\n writeSym,\n serializersSym,\n formatOptsSym,\n endSym,\n stringifiersSym,\n stringifySym,\n stringifySafeSym,\n wildcardFirstSym,\n nestedKeySym,\n formattersSym,\n messageKeySym,\n errorKeySym,\n nestedKeyStrSym,\n msgPrefixSym\n} = require('./symbols')\nconst { isMainThread } = require('worker_threads')\nconst transport = require('./transport')\n\nfunction noop () {\n}\n\nfunction genLog (level, hook) {\n if (!hook) return LOG\n\n return function hookWrappedLog (...args) {\n hook.call(this, args, LOG, level)\n }\n\n function LOG (o, ...n) {\n if (typeof o === 'object') {\n let msg = o\n if (o !== null) {\n if (o.method && o.headers && o.socket) {\n o = mapHttpRequest(o)\n } else if (typeof o.setHeader === 'function') {\n o = mapHttpResponse(o)\n }\n }\n let formatParams\n if (msg === null && n.length === 0) {\n formatParams = [null]\n } else {\n msg = n.shift()\n formatParams = n\n }\n // We do not use a coercive check for `msg` as it is\n // measurably slower than the explicit checks.\n if (typeof this[msgPrefixSym] === 'string' && msg !== undefined && msg !== null) {\n msg = this[msgPrefixSym] + msg\n }\n this[writeSym](o, format(msg, formatParams, this[formatOptsSym]), level)\n } else {\n let msg = o === undefined ? n.shift() : o\n\n // We do not use a coercive check for `msg` as it is\n // measurably slower than the explicit checks.\n if (typeof this[msgPrefixSym] === 'string' && msg !== undefined && msg !== null) {\n msg = this[msgPrefixSym] + msg\n }\n this[writeSym](null, format(msg, n, this[formatOptsSym]), level)\n }\n }\n}\n\n// magically escape strings for json\n// relying on their charCodeAt\n// everything below 32 needs JSON.stringify()\n// 34 and 92 happens all the time, so we\n// have a fast case for them\nfunction asString (str) {\n let result = ''\n let last = 0\n let found = false\n let point = 255\n const l = str.length\n if (l > 100) {\n return JSON.stringify(str)\n }\n for (var i = 0; i < l && point >= 32; i++) {\n point = str.charCodeAt(i)\n if (point === 34 || point === 92) {\n result += str.slice(last, i) + '\\\\'\n last = i\n found = true\n }\n }\n if (!found) {\n result = str\n } else {\n result += str.slice(last)\n }\n return point < 32 ? JSON.stringify(str) : '\"' + result + '\"'\n}\n\nfunction asJson (obj, msg, num, time) {\n const stringify = this[stringifySym]\n const stringifySafe = this[stringifySafeSym]\n const stringifiers = this[stringifiersSym]\n const end = this[endSym]\n const chindings = this[chindingsSym]\n const serializers = this[serializersSym]\n const formatters = this[formattersSym]\n const messageKey = this[messageKeySym]\n const errorKey = this[errorKeySym]\n let data = this[lsCacheSym][num] + time\n\n // we need the child bindings added to the output first so instance logged\n // objects can take precedence when JSON.parse-ing the resulting log line\n data = data + chindings\n\n let value\n if (formatters.log) {\n obj = formatters.log(obj)\n }\n const wildcardStringifier = stringifiers[wildcardFirstSym]\n let propStr = ''\n for (const key in obj) {\n value = obj[key]\n if (Object.prototype.hasOwnProperty.call(obj, key) && value !== undefined) {\n if (serializers[key]) {\n value = serializers[key](value)\n } else if (key === errorKey && serializers.err) {\n value = serializers.err(value)\n }\n\n const stringifier = stringifiers[key] || wildcardStringifier\n\n switch (typeof value) {\n case 'undefined':\n case 'function':\n continue\n case 'number':\n /* eslint no-fallthrough: \"off\" */\n if (Number.isFinite(value) === false) {\n value = null\n }\n // this case explicitly falls through to the next one\n case 'boolean':\n if (stringifier) value = stringifier(value)\n break\n case 'string':\n value = (stringifier || asString)(value)\n break\n default:\n value = (stringifier || stringify)(value, stringifySafe)\n }\n if (value === undefined) continue\n const strKey = asString(key)\n propStr += ',' + strKey + ':' + value\n }\n }\n\n let msgStr = ''\n if (msg !== undefined) {\n value = serializers[messageKey] ? serializers[messageKey](msg) : msg\n const stringifier = stringifiers[messageKey] || wildcardStringifier\n\n switch (typeof value) {\n case 'function':\n break\n case 'number':\n /* eslint no-fallthrough: \"off\" */\n if (Number.isFinite(value) === false) {\n value = null\n }\n // this case explicitly falls through to the next one\n case 'boolean':\n if (stringifier) value = stringifier(value)\n msgStr = ',\"' + messageKey + '\":' + value\n break\n case 'string':\n value = (stringifier || asString)(value)\n msgStr = ',\"' + messageKey + '\":' + value\n break\n default:\n value = (stringifier || stringify)(value, stringifySafe)\n msgStr = ',\"' + messageKey + '\":' + value\n }\n }\n\n if (this[nestedKeySym] && propStr) {\n // place all the obj properties under the specified key\n // the nested key is already formatted from the constructor\n return data + this[nestedKeyStrSym] + propStr.slice(1) + '}' + msgStr + end\n } else {\n return data + propStr + msgStr + end\n }\n}\n\nfunction asChindings (instance, bindings) {\n let value\n let data = instance[chindingsSym]\n const stringify = instance[stringifySym]\n const stringifySafe = instance[stringifySafeSym]\n const stringifiers = instance[stringifiersSym]\n const wildcardStringifier = stringifiers[wildcardFirstSym]\n const serializers = instance[serializersSym]\n const formatter = instance[formattersSym].bindings\n bindings = formatter(bindings)\n\n for (const key in bindings) {\n value = bindings[key]\n const valid = key !== 'level' &&\n key !== 'serializers' &&\n key !== 'formatters' &&\n key !== 'customLevels' &&\n bindings.hasOwnProperty(key) &&\n value !== undefined\n if (valid === true) {\n value = serializers[key] ? serializers[key](value) : value\n value = (stringifiers[key] || wildcardStringifier || stringify)(value, stringifySafe)\n if (value === undefined) continue\n data += ',\"' + key + '\":' + value\n }\n }\n return data\n}\n\nfunction hasBeenTampered (stream) {\n return stream.write !== stream.constructor.prototype.write\n}\n\nfunction buildSafeSonicBoom (opts) {\n const stream = new SonicBoom(opts)\n stream.on('error', filterBrokenPipe)\n // If we are sync: false, we must flush on exit\n if (!opts.sync && isMainThread) {\n onExit.register(stream, autoEnd)\n\n stream.on('close', function () {\n onExit.unregister(stream)\n })\n }\n return stream\n\n function filterBrokenPipe (err) {\n // Impossible to replicate across all operating systems\n /* istanbul ignore next */\n if (err.code === 'EPIPE') {\n // If we get EPIPE, we should stop logging here\n // however we have no control to the consumer of\n // SonicBoom, so we just overwrite the write method\n stream.write = noop\n stream.end = noop\n stream.flushSync = noop\n stream.destroy = noop\n return\n }\n stream.removeListener('error', filterBrokenPipe)\n stream.emit('error', err)\n }\n}\n\nfunction autoEnd (stream, eventName) {\n // This check is needed only on some platforms\n /* istanbul ignore next */\n if (stream.destroyed) {\n return\n }\n\n if (eventName === 'beforeExit') {\n // We still have an event loop, let's use it\n stream.flush()\n stream.on('drain', function () {\n stream.end()\n })\n } else {\n // For some reason istanbul is not detecting this, but it's there\n /* istanbul ignore next */\n // We do not have an event loop, so flush synchronously\n stream.flushSync()\n }\n}\n\nfunction createArgsNormalizer (defaultOptions) {\n return function normalizeArgs (instance, caller, opts = {}, stream) {\n // support stream as a string\n if (typeof opts === 'string') {\n stream = buildSafeSonicBoom({ dest: opts })\n opts = {}\n } else if (typeof stream === 'string') {\n if (opts && opts.transport) {\n throw Error('only one of option.transport or stream can be specified')\n }\n stream = buildSafeSonicBoom({ dest: stream })\n } else if (opts instanceof SonicBoom || opts.writable || opts._writableState) {\n stream = opts\n opts = {}\n } else if (opts.transport) {\n if (opts.transport instanceof SonicBoom || opts.transport.writable || opts.transport._writableState) {\n throw Error('option.transport do not allow stream, please pass to option directly. e.g. pino(transport)')\n }\n if (opts.transport.targets && opts.transport.targets.length && opts.formatters && typeof opts.formatters.level === 'function') {\n throw Error('option.transport.targets do not allow custom level formatters')\n }\n\n let customLevels\n if (opts.customLevels) {\n customLevels = opts.useOnlyCustomLevels ? opts.customLevels : Object.assign({}, opts.levels, opts.customLevels)\n }\n stream = transport({ caller, ...opts.transport, levels: customLevels })\n }\n opts = Object.assign({}, defaultOptions, opts)\n opts.serializers = Object.assign({}, defaultOptions.serializers, opts.serializers)\n opts.formatters = Object.assign({}, defaultOptions.formatters, opts.formatters)\n\n if (opts.prettyPrint) {\n throw new Error('prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)')\n }\n\n const { enabled, onChild } = opts\n if (enabled === false) opts.level = 'silent'\n if (!onChild) opts.onChild = noop\n if (!stream) {\n if (!hasBeenTampered(process.stdout)) {\n // If process.stdout.fd is undefined, it means that we are running\n // in a worker thread. Let's assume we are logging to file descriptor 1.\n stream = buildSafeSonicBoom({ fd: process.stdout.fd || 1 })\n } else {\n stream = process.stdout\n }\n }\n return { opts, stream }\n }\n}\n\nfunction stringify (obj, stringifySafeFn) {\n try {\n return JSON.stringify(obj)\n } catch (_) {\n try {\n const stringify = stringifySafeFn || this[stringifySafeSym]\n return stringify(obj)\n } catch (_) {\n return '\"[unable to serialize, circular reference is too complex to analyze]\"'\n }\n }\n}\n\nfunction buildFormatters (level, bindings, log) {\n return {\n level,\n bindings,\n log\n }\n}\n\n/**\n * Convert a string integer file descriptor to a proper native integer\n * file descriptor.\n *\n * @param {string} destination The file descriptor string to attempt to convert.\n *\n * @returns {Number}\n */\nfunction normalizeDestFileDescriptor (destination) {\n const fd = Number(destination)\n if (typeof destination === 'string' && Number.isFinite(fd)) {\n return fd\n }\n // destination could be undefined if we are in a worker\n if (destination === undefined) {\n // This is stdout in UNIX systems\n return 1\n }\n return destination\n}\n\nmodule.exports = {\n noop,\n buildSafeSonicBoom,\n asChindings,\n asJson,\n genLog,\n createArgsNormalizer,\n stringify,\n buildFormatters,\n normalizeDestFileDescriptor\n}\n", "/**\n * Represents default log level values\n *\n * @enum {number}\n */\nconst DEFAULT_LEVELS = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60\n}\n\n/**\n * Represents sort order direction: `ascending` or `descending`\n *\n * @enum {string}\n */\nconst SORTING_ORDER = {\n ASC: 'ASC',\n DESC: 'DESC'\n}\n\nmodule.exports = {\n DEFAULT_LEVELS,\n SORTING_ORDER\n}\n", "'use strict'\n/* eslint no-prototype-builtins: 0 */\nconst {\n lsCacheSym,\n levelValSym,\n useOnlyCustomLevelsSym,\n streamSym,\n formattersSym,\n hooksSym,\n levelCompSym\n} = require('./symbols')\nconst { noop, genLog } = require('./tools')\nconst { DEFAULT_LEVELS, SORTING_ORDER } = require('./constants')\n\nconst levelMethods = {\n fatal: (hook) => {\n const logFatal = genLog(DEFAULT_LEVELS.fatal, hook)\n return function (...args) {\n const stream = this[streamSym]\n logFatal.call(this, ...args)\n if (typeof stream.flushSync === 'function') {\n try {\n stream.flushSync()\n } catch (e) {\n // https://github.com/pinojs/pino/pull/740#discussion_r346788313\n }\n }\n }\n },\n error: (hook) => genLog(DEFAULT_LEVELS.error, hook),\n warn: (hook) => genLog(DEFAULT_LEVELS.warn, hook),\n info: (hook) => genLog(DEFAULT_LEVELS.info, hook),\n debug: (hook) => genLog(DEFAULT_LEVELS.debug, hook),\n trace: (hook) => genLog(DEFAULT_LEVELS.trace, hook)\n}\n\nconst nums = Object.keys(DEFAULT_LEVELS).reduce((o, k) => {\n o[DEFAULT_LEVELS[k]] = k\n return o\n}, {})\n\nconst initialLsCache = Object.keys(nums).reduce((o, k) => {\n o[k] = '{\"level\":' + Number(k)\n return o\n}, {})\n\nfunction genLsCache (instance) {\n const formatter = instance[formattersSym].level\n const { labels } = instance.levels\n const cache = {}\n for (const label in labels) {\n const level = formatter(labels[label], Number(label))\n cache[label] = JSON.stringify(level).slice(0, -1)\n }\n instance[lsCacheSym] = cache\n return instance\n}\n\nfunction isStandardLevel (level, useOnlyCustomLevels) {\n if (useOnlyCustomLevels) {\n return false\n }\n\n switch (level) {\n case 'fatal':\n case 'error':\n case 'warn':\n case 'info':\n case 'debug':\n case 'trace':\n return true\n default:\n return false\n }\n}\n\nfunction setLevel (level) {\n const { labels, values } = this.levels\n if (typeof level === 'number') {\n if (labels[level] === undefined) throw Error('unknown level value' + level)\n level = labels[level]\n }\n if (values[level] === undefined) throw Error('unknown level ' + level)\n const preLevelVal = this[levelValSym]\n const levelVal = this[levelValSym] = values[level]\n const useOnlyCustomLevelsVal = this[useOnlyCustomLevelsSym]\n const levelComparison = this[levelCompSym]\n const hook = this[hooksSym].logMethod\n\n for (const key in values) {\n if (levelComparison(values[key], levelVal) === false) {\n this[key] = noop\n continue\n }\n this[key] = isStandardLevel(key, useOnlyCustomLevelsVal) ? levelMethods[key](hook) : genLog(values[key], hook)\n }\n\n this.emit(\n 'level-change',\n level,\n levelVal,\n labels[preLevelVal],\n preLevelVal,\n this\n )\n}\n\nfunction getLevel (level) {\n const { levels, levelVal } = this\n // protection against potential loss of Pino scope from serializers (edge case with circular refs - https://github.com/pinojs/pino/issues/833)\n return (levels && levels.labels) ? levels.labels[levelVal] : ''\n}\n\nfunction isLevelEnabled (logLevel) {\n const { values } = this.levels\n const logLevelVal = values[logLevel]\n return logLevelVal !== undefined && this[levelCompSym](logLevelVal, this[levelValSym])\n}\n\n/**\n * Determine if the given `current` level is enabled by comparing it\n * against the current threshold (`expected`).\n *\n * @param {SORTING_ORDER} direction comparison direction \"ASC\" or \"DESC\"\n * @param {number} current current log level number representation\n * @param {number} expected threshold value to compare with\n * @returns {boolean}\n */\nfunction compareLevel (direction, current, expected) {\n if (direction === SORTING_ORDER.DESC) {\n return current <= expected\n }\n\n return current >= expected\n}\n\n/**\n * Create a level comparison function based on `levelComparison`\n * it could a default function which compares levels either in \"ascending\" or \"descending\" order or custom comparison function\n *\n * @param {SORTING_ORDER | Function} levelComparison sort levels order direction or custom comparison function\n * @returns Function\n */\nfunction genLevelComparison (levelComparison) {\n if (typeof levelComparison === 'string') {\n return compareLevel.bind(null, levelComparison)\n }\n\n return levelComparison\n}\n\nfunction mappings (customLevels = null, useOnlyCustomLevels = false) {\n const customNums = customLevels\n /* eslint-disable */\n ? Object.keys(customLevels).reduce((o, k) => {\n o[customLevels[k]] = k\n return o\n }, {})\n : null\n /* eslint-enable */\n\n const labels = Object.assign(\n Object.create(Object.prototype, { Infinity: { value: 'silent' } }),\n useOnlyCustomLevels ? null : nums,\n customNums\n )\n const values = Object.assign(\n Object.create(Object.prototype, { silent: { value: Infinity } }),\n useOnlyCustomLevels ? null : DEFAULT_LEVELS,\n customLevels\n )\n return { labels, values }\n}\n\nfunction assertDefaultLevelFound (defaultLevel, customLevels, useOnlyCustomLevels) {\n if (typeof defaultLevel === 'number') {\n const values = [].concat(\n Object.keys(customLevels || {}).map(key => customLevels[key]),\n useOnlyCustomLevels ? [] : Object.keys(nums).map(level => +level),\n Infinity\n )\n if (!values.includes(defaultLevel)) {\n throw Error(`default level:${defaultLevel} must be included in custom levels`)\n }\n return\n }\n\n const labels = Object.assign(\n Object.create(Object.prototype, { silent: { value: Infinity } }),\n useOnlyCustomLevels ? null : DEFAULT_LEVELS,\n customLevels\n )\n if (!(defaultLevel in labels)) {\n throw Error(`default level:${defaultLevel} must be included in custom levels`)\n }\n}\n\nfunction assertNoLevelCollisions (levels, customLevels) {\n const { labels, values } = levels\n for (const k in customLevels) {\n if (k in values) {\n throw Error('levels cannot be overridden')\n }\n if (customLevels[k] in labels) {\n throw Error('pre-existing level values cannot be used for new levels')\n }\n }\n}\n\n/**\n * Validates whether `levelComparison` is correct\n *\n * @throws Error\n * @param {SORTING_ORDER | Function} levelComparison - value to validate\n * @returns\n */\nfunction assertLevelComparison (levelComparison) {\n if (typeof levelComparison === 'function') {\n return\n }\n\n if (typeof levelComparison === 'string' && Object.values(SORTING_ORDER).includes(levelComparison)) {\n return\n }\n\n throw new Error('Levels comparison should be one of \"ASC\", \"DESC\" or \"function\" type')\n}\n\nmodule.exports = {\n initialLsCache,\n genLsCache,\n levelMethods,\n getLevel,\n setLevel,\n isLevelEnabled,\n mappings,\n assertNoLevelCollisions,\n assertDefaultLevelFound,\n genLevelComparison,\n assertLevelComparison\n}\n", "'use strict'\n\nmodule.exports = { version: '9.7.0' }\n", "'use strict'\n\n/* eslint no-prototype-builtins: 0 */\n\nconst { EventEmitter } = require('node:events')\nconst {\n lsCacheSym,\n levelValSym,\n setLevelSym,\n getLevelSym,\n chindingsSym,\n parsedChindingsSym,\n mixinSym,\n asJsonSym,\n writeSym,\n mixinMergeStrategySym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n serializersSym,\n formattersSym,\n errorKeySym,\n messageKeySym,\n useOnlyCustomLevelsSym,\n needsMetadataGsym,\n redactFmtSym,\n stringifySym,\n formatOptsSym,\n stringifiersSym,\n msgPrefixSym,\n hooksSym\n} = require('./symbols')\nconst {\n getLevel,\n setLevel,\n isLevelEnabled,\n mappings,\n initialLsCache,\n genLsCache,\n assertNoLevelCollisions\n} = require('./levels')\nconst {\n asChindings,\n asJson,\n buildFormatters,\n stringify\n} = require('./tools')\nconst {\n version\n} = require('./meta')\nconst redaction = require('./redaction')\n\n// note: use of class is satirical\n// https://github.com/pinojs/pino/pull/433#pullrequestreview-127703127\nconst constructor = class Pino {}\nconst prototype = {\n constructor,\n child,\n bindings,\n setBindings,\n flush,\n isLevelEnabled,\n version,\n get level () { return this[getLevelSym]() },\n set level (lvl) { this[setLevelSym](lvl) },\n get levelVal () { return this[levelValSym] },\n set levelVal (n) { throw Error('levelVal is read-only') },\n [lsCacheSym]: initialLsCache,\n [writeSym]: write,\n [asJsonSym]: asJson,\n [getLevelSym]: getLevel,\n [setLevelSym]: setLevel\n}\n\nObject.setPrototypeOf(prototype, EventEmitter.prototype)\n\n// exporting and consuming the prototype object using factory pattern fixes scoping issues with getters when serializing\nmodule.exports = function () {\n return Object.create(prototype)\n}\n\nconst resetChildingsFormatter = bindings => bindings\nfunction child (bindings, options) {\n if (!bindings) {\n throw Error('missing bindings for child Pino')\n }\n options = options || {} // default options to empty object\n const serializers = this[serializersSym]\n const formatters = this[formattersSym]\n const instance = Object.create(this)\n\n if (options.hasOwnProperty('serializers') === true) {\n instance[serializersSym] = Object.create(null)\n\n for (const k in serializers) {\n instance[serializersSym][k] = serializers[k]\n }\n const parentSymbols = Object.getOwnPropertySymbols(serializers)\n /* eslint no-var: off */\n for (var i = 0; i < parentSymbols.length; i++) {\n const ks = parentSymbols[i]\n instance[serializersSym][ks] = serializers[ks]\n }\n\n for (const bk in options.serializers) {\n instance[serializersSym][bk] = options.serializers[bk]\n }\n const bindingsSymbols = Object.getOwnPropertySymbols(options.serializers)\n for (var bi = 0; bi < bindingsSymbols.length; bi++) {\n const bks = bindingsSymbols[bi]\n instance[serializersSym][bks] = options.serializers[bks]\n }\n } else instance[serializersSym] = serializers\n if (options.hasOwnProperty('formatters')) {\n const { level, bindings: chindings, log } = options.formatters\n instance[formattersSym] = buildFormatters(\n level || formatters.level,\n chindings || resetChildingsFormatter,\n log || formatters.log\n )\n } else {\n instance[formattersSym] = buildFormatters(\n formatters.level,\n resetChildingsFormatter,\n formatters.log\n )\n }\n if (options.hasOwnProperty('customLevels') === true) {\n assertNoLevelCollisions(this.levels, options.customLevels)\n instance.levels = mappings(options.customLevels, instance[useOnlyCustomLevelsSym])\n genLsCache(instance)\n }\n\n // redact must place before asChindings and only replace if exist\n if ((typeof options.redact === 'object' && options.redact !== null) || Array.isArray(options.redact)) {\n instance.redact = options.redact // replace redact directly\n const stringifiers = redaction(instance.redact, stringify)\n const formatOpts = { stringify: stringifiers[redactFmtSym] }\n instance[stringifySym] = stringify\n instance[stringifiersSym] = stringifiers\n instance[formatOptsSym] = formatOpts\n }\n\n if (typeof options.msgPrefix === 'string') {\n instance[msgPrefixSym] = (this[msgPrefixSym] || '') + options.msgPrefix\n }\n\n instance[chindingsSym] = asChindings(instance, bindings)\n const childLevel = options.level || this.level\n instance[setLevelSym](childLevel)\n this.onChild(instance)\n return instance\n}\n\nfunction bindings () {\n const chindings = this[chindingsSym]\n const chindingsJson = `{${chindings.substr(1)}}` // at least contains ,\"pid\":7068,\"hostname\":\"myMac\"\n const bindingsFromJson = JSON.parse(chindingsJson)\n delete bindingsFromJson.pid\n delete bindingsFromJson.hostname\n return bindingsFromJson\n}\n\nfunction setBindings (newBindings) {\n const chindings = asChindings(this, newBindings)\n this[chindingsSym] = chindings\n delete this[parsedChindingsSym]\n}\n\n/**\n * Default strategy for creating `mergeObject` from arguments and the result from `mixin()`.\n * Fields from `mergeObject` have higher priority in this strategy.\n *\n * @param {Object} mergeObject The object a user has supplied to the logging function.\n * @param {Object} mixinObject The result of the `mixin` method.\n * @return {Object}\n */\nfunction defaultMixinMergeStrategy (mergeObject, mixinObject) {\n return Object.assign(mixinObject, mergeObject)\n}\n\nfunction write (_obj, msg, num) {\n const t = this[timeSym]()\n const mixin = this[mixinSym]\n const errorKey = this[errorKeySym]\n const messageKey = this[messageKeySym]\n const mixinMergeStrategy = this[mixinMergeStrategySym] || defaultMixinMergeStrategy\n let obj\n const streamWriteHook = this[hooksSym].streamWrite\n\n if (_obj === undefined || _obj === null) {\n obj = {}\n } else if (_obj instanceof Error) {\n obj = { [errorKey]: _obj }\n if (msg === undefined) {\n msg = _obj.message\n }\n } else {\n obj = _obj\n if (msg === undefined && _obj[messageKey] === undefined && _obj[errorKey]) {\n msg = _obj[errorKey].message\n }\n }\n\n if (mixin) {\n obj = mixinMergeStrategy(obj, mixin(obj, num, this))\n }\n\n const s = this[asJsonSym](obj, msg, num, t)\n\n const stream = this[streamSym]\n if (stream[needsMetadataGsym] === true) {\n stream.lastLevel = num\n stream.lastObj = obj\n stream.lastMsg = msg\n stream.lastTime = t.slice(this[timeSliceIndexSym])\n stream.lastLogger = this // for child loggers\n }\n stream.write(streamWriteHook ? streamWriteHook(s) : s)\n}\n\nfunction noop () {}\n\nfunction flush (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw Error('callback must be a function')\n }\n\n const stream = this[streamSym]\n\n if (typeof stream.flush === 'function') {\n stream.flush(cb || noop)\n } else if (cb) cb()\n}\n", "'use strict'\n\nconst { hasOwnProperty } = Object.prototype\n\nconst stringify = configure()\n\n// @ts-expect-error\nstringify.configure = configure\n// @ts-expect-error\nstringify.stringify = stringify\n\n// @ts-expect-error\nstringify.default = stringify\n\n// @ts-expect-error used for named export\nexports.stringify = stringify\n// @ts-expect-error used for named export\nexports.configure = configure\n\nmodule.exports = stringify\n\n// eslint-disable-next-line no-control-regex\nconst strEscapeSequencesRegExp = /[\\u0000-\\u001f\\u0022\\u005c\\ud800-\\udfff]/\n\n// Escape C0 control characters, double quotes, the backslash and every code\n// unit with a numeric value in the inclusive range 0xD800 to 0xDFFF.\nfunction strEscape (str) {\n // Some magic numbers that worked out fine while benchmarking with v8 8.0\n if (str.length < 5000 && !strEscapeSequencesRegExp.test(str)) {\n return `\"${str}\"`\n }\n return JSON.stringify(str)\n}\n\nfunction sort (array, comparator) {\n // Insertion sort is very efficient for small input sizes, but it has a bad\n // worst case complexity. Thus, use native array sort for bigger values.\n if (array.length > 2e2 || comparator) {\n return array.sort(comparator)\n }\n for (let i = 1; i < array.length; i++) {\n const currentValue = array[i]\n let position = i\n while (position !== 0 && array[position - 1] > currentValue) {\n array[position] = array[position - 1]\n position--\n }\n array[position] = currentValue\n }\n return array\n}\n\nconst typedArrayPrototypeGetSymbolToStringTag =\n Object.getOwnPropertyDescriptor(\n Object.getPrototypeOf(\n Object.getPrototypeOf(\n new Int8Array()\n )\n ),\n Symbol.toStringTag\n ).get\n\nfunction isTypedArrayWithEntries (value) {\n return typedArrayPrototypeGetSymbolToStringTag.call(value) !== undefined && value.length !== 0\n}\n\nfunction stringifyTypedArray (array, separator, maximumBreadth) {\n if (array.length < maximumBreadth) {\n maximumBreadth = array.length\n }\n const whitespace = separator === ',' ? '' : ' '\n let res = `\"0\":${whitespace}${array[0]}`\n for (let i = 1; i < maximumBreadth; i++) {\n res += `${separator}\"${i}\":${whitespace}${array[i]}`\n }\n return res\n}\n\nfunction getCircularValueOption (options) {\n if (hasOwnProperty.call(options, 'circularValue')) {\n const circularValue = options.circularValue\n if (typeof circularValue === 'string') {\n return `\"${circularValue}\"`\n }\n if (circularValue == null) {\n return circularValue\n }\n if (circularValue === Error || circularValue === TypeError) {\n return {\n toString () {\n throw new TypeError('Converting circular structure to JSON')\n }\n }\n }\n throw new TypeError('The \"circularValue\" argument must be of type string or the value null or undefined')\n }\n return '\"[Circular]\"'\n}\n\nfunction getDeterministicOption (options) {\n let value\n if (hasOwnProperty.call(options, 'deterministic')) {\n value = options.deterministic\n if (typeof value !== 'boolean' && typeof value !== 'function') {\n throw new TypeError('The \"deterministic\" argument must be of type boolean or comparator function')\n }\n }\n return value === undefined ? true : value\n}\n\nfunction getBooleanOption (options, key) {\n let value\n if (hasOwnProperty.call(options, key)) {\n value = options[key]\n if (typeof value !== 'boolean') {\n throw new TypeError(`The \"${key}\" argument must be of type boolean`)\n }\n }\n return value === undefined ? true : value\n}\n\nfunction getPositiveIntegerOption (options, key) {\n let value\n if (hasOwnProperty.call(options, key)) {\n value = options[key]\n if (typeof value !== 'number') {\n throw new TypeError(`The \"${key}\" argument must be of type number`)\n }\n if (!Number.isInteger(value)) {\n throw new TypeError(`The \"${key}\" argument must be an integer`)\n }\n if (value < 1) {\n throw new RangeError(`The \"${key}\" argument must be >= 1`)\n }\n }\n return value === undefined ? Infinity : value\n}\n\nfunction getItemCount (number) {\n if (number === 1) {\n return '1 item'\n }\n return `${number} items`\n}\n\nfunction getUniqueReplacerSet (replacerArray) {\n const replacerSet = new Set()\n for (const value of replacerArray) {\n if (typeof value === 'string' || typeof value === 'number') {\n replacerSet.add(String(value))\n }\n }\n return replacerSet\n}\n\nfunction getStrictOption (options) {\n if (hasOwnProperty.call(options, 'strict')) {\n const value = options.strict\n if (typeof value !== 'boolean') {\n throw new TypeError('The \"strict\" argument must be of type boolean')\n }\n if (value) {\n return (value) => {\n let message = `Object can not safely be stringified. Received type ${typeof value}`\n if (typeof value !== 'function') message += ` (${value.toString()})`\n throw new Error(message)\n }\n }\n }\n}\n\nfunction configure (options) {\n options = { ...options }\n const fail = getStrictOption(options)\n if (fail) {\n if (options.bigint === undefined) {\n options.bigint = false\n }\n if (!('circularValue' in options)) {\n options.circularValue = Error\n }\n }\n const circularValue = getCircularValueOption(options)\n const bigint = getBooleanOption(options, 'bigint')\n const deterministic = getDeterministicOption(options)\n const comparator = typeof deterministic === 'function' ? deterministic : undefined\n const maximumDepth = getPositiveIntegerOption(options, 'maximumDepth')\n const maximumBreadth = getPositiveIntegerOption(options, 'maximumBreadth')\n\n function stringifyFnReplacer (key, parent, stack, replacer, spacer, indentation) {\n let value = parent[key]\n\n if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n }\n value = replacer.call(parent, key, value)\n\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n\n let res = ''\n let join = ','\n const originalIndentation = indentation\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n if (spacer !== '') {\n indentation += spacer\n res += `\\n${indentation}`\n join = `,\\n${indentation}`\n }\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n res += join\n }\n const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n if (spacer !== '') {\n res += `\\n${originalIndentation}`\n }\n stack.pop()\n return `[${res}]`\n }\n\n let keys = Object.keys(value)\n const keyLength = keys.length\n if (keyLength === 0) {\n return '{}'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Object]\"'\n }\n let whitespace = ''\n let separator = ''\n if (spacer !== '') {\n indentation += spacer\n join = `,\\n${indentation}`\n whitespace = ' '\n }\n const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n if (deterministic && !isTypedArrayWithEntries(value)) {\n keys = sort(keys, comparator)\n }\n stack.push(value)\n for (let i = 0; i < maximumPropertiesToStringify; i++) {\n const key = keys[i]\n const tmp = stringifyFnReplacer(key, value, stack, replacer, spacer, indentation)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}:${whitespace}${tmp}`\n separator = join\n }\n }\n if (keyLength > maximumBreadth) {\n const removedKeys = keyLength - maximumBreadth\n res += `${separator}\"...\":${whitespace}\"${getItemCount(removedKeys)} not stringified\"`\n separator = join\n }\n if (spacer !== '' && separator.length > 1) {\n res = `\\n${indentation}${res}\\n${originalIndentation}`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringifyArrayReplacer (key, value, stack, replacer, spacer, indentation) {\n if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n }\n\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n\n const originalIndentation = indentation\n let res = ''\n let join = ','\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n if (spacer !== '') {\n indentation += spacer\n res += `\\n${indentation}`\n join = `,\\n${indentation}`\n }\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n res += join\n }\n const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n if (spacer !== '') {\n res += `\\n${originalIndentation}`\n }\n stack.pop()\n return `[${res}]`\n }\n stack.push(value)\n let whitespace = ''\n if (spacer !== '') {\n indentation += spacer\n join = `,\\n${indentation}`\n whitespace = ' '\n }\n let separator = ''\n for (const key of replacer) {\n const tmp = stringifyArrayReplacer(key, value[key], stack, replacer, spacer, indentation)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}:${whitespace}${tmp}`\n separator = join\n }\n }\n if (spacer !== '' && separator.length > 1) {\n res = `\\n${indentation}${res}\\n${originalIndentation}`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringifyIndent (key, value, stack, spacer, indentation) {\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n // Prevent calling `toJSON` again.\n if (typeof value !== 'object') {\n return stringifyIndent(key, value, stack, spacer, indentation)\n }\n if (value === null) {\n return 'null'\n }\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n const originalIndentation = indentation\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n indentation += spacer\n let res = `\\n${indentation}`\n const join = `,\\n${indentation}`\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n res += join\n }\n const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n res += `\\n${originalIndentation}`\n stack.pop()\n return `[${res}]`\n }\n\n let keys = Object.keys(value)\n const keyLength = keys.length\n if (keyLength === 0) {\n return '{}'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Object]\"'\n }\n indentation += spacer\n const join = `,\\n${indentation}`\n let res = ''\n let separator = ''\n let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n if (isTypedArrayWithEntries(value)) {\n res += stringifyTypedArray(value, join, maximumBreadth)\n keys = keys.slice(value.length)\n maximumPropertiesToStringify -= value.length\n separator = join\n }\n if (deterministic) {\n keys = sort(keys, comparator)\n }\n stack.push(value)\n for (let i = 0; i < maximumPropertiesToStringify; i++) {\n const key = keys[i]\n const tmp = stringifyIndent(key, value[key], stack, spacer, indentation)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}: ${tmp}`\n separator = join\n }\n }\n if (keyLength > maximumBreadth) {\n const removedKeys = keyLength - maximumBreadth\n res += `${separator}\"...\": \"${getItemCount(removedKeys)} not stringified\"`\n separator = join\n }\n if (separator !== '') {\n res = `\\n${indentation}${res}\\n${originalIndentation}`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringifySimple (key, value, stack) {\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n // Prevent calling `toJSON` again\n if (typeof value !== 'object') {\n return stringifySimple(key, value, stack)\n }\n if (value === null) {\n return 'null'\n }\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n\n let res = ''\n\n const hasLength = value.length !== undefined\n if (hasLength && Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifySimple(String(i), value[i], stack)\n res += tmp !== undefined ? tmp : 'null'\n res += ','\n }\n const tmp = stringifySimple(String(i), value[i], stack)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `,\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n stack.pop()\n return `[${res}]`\n }\n\n let keys = Object.keys(value)\n const keyLength = keys.length\n if (keyLength === 0) {\n return '{}'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Object]\"'\n }\n let separator = ''\n let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n if (hasLength && isTypedArrayWithEntries(value)) {\n res += stringifyTypedArray(value, ',', maximumBreadth)\n keys = keys.slice(value.length)\n maximumPropertiesToStringify -= value.length\n separator = ','\n }\n if (deterministic) {\n keys = sort(keys, comparator)\n }\n stack.push(value)\n for (let i = 0; i < maximumPropertiesToStringify; i++) {\n const key = keys[i]\n const tmp = stringifySimple(key, value[key], stack)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}:${tmp}`\n separator = ','\n }\n }\n if (keyLength > maximumBreadth) {\n const removedKeys = keyLength - maximumBreadth\n res += `${separator}\"...\":\"${getItemCount(removedKeys)} not stringified\"`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringify (value, replacer, space) {\n if (arguments.length > 1) {\n let spacer = ''\n if (typeof space === 'number') {\n spacer = ' '.repeat(Math.min(space, 10))\n } else if (typeof space === 'string') {\n spacer = space.slice(0, 10)\n }\n if (replacer != null) {\n if (typeof replacer === 'function') {\n return stringifyFnReplacer('', { '': value }, [], replacer, spacer, '')\n }\n if (Array.isArray(replacer)) {\n return stringifyArrayReplacer('', value, [], getUniqueReplacerSet(replacer), spacer, '')\n }\n }\n if (spacer.length !== 0) {\n return stringifyIndent('', value, [], spacer, '')\n }\n }\n return stringifySimple('', value, [])\n }\n\n return stringify\n}\n", "'use strict'\n\nconst metadata = Symbol.for('pino.metadata')\nconst { DEFAULT_LEVELS } = require('./constants')\n\nconst DEFAULT_INFO_LEVEL = DEFAULT_LEVELS.info\n\nfunction multistream (streamsArray, opts) {\n let counter = 0\n streamsArray = streamsArray || []\n opts = opts || { dedupe: false }\n\n const streamLevels = Object.create(DEFAULT_LEVELS)\n streamLevels.silent = Infinity\n if (opts.levels && typeof opts.levels === 'object') {\n Object.keys(opts.levels).forEach(i => {\n streamLevels[i] = opts.levels[i]\n })\n }\n\n const res = {\n write,\n add,\n emit,\n flushSync,\n end,\n minLevel: 0,\n streams: [],\n clone,\n [metadata]: true,\n streamLevels\n }\n\n if (Array.isArray(streamsArray)) {\n streamsArray.forEach(add, res)\n } else {\n add.call(res, streamsArray)\n }\n\n // clean this object up\n // or it will stay allocated forever\n // as it is closed on the following closures\n streamsArray = null\n\n return res\n\n // we can exit early because the streams are ordered by level\n function write (data) {\n let dest\n const level = this.lastLevel\n const { streams } = this\n // for handling situation when several streams has the same level\n let recordedLevel = 0\n let stream\n\n // if dedupe set to true we send logs to the stream with the highest level\n // therefore, we have to change sorting order\n for (let i = initLoopVar(streams.length, opts.dedupe); checkLoopVar(i, streams.length, opts.dedupe); i = adjustLoopVar(i, opts.dedupe)) {\n dest = streams[i]\n if (dest.level <= level) {\n if (recordedLevel !== 0 && recordedLevel !== dest.level) {\n break\n }\n stream = dest.stream\n if (stream[metadata]) {\n const { lastTime, lastMsg, lastObj, lastLogger } = this\n stream.lastLevel = level\n stream.lastTime = lastTime\n stream.lastMsg = lastMsg\n stream.lastObj = lastObj\n stream.lastLogger = lastLogger\n }\n stream.write(data)\n if (opts.dedupe) {\n recordedLevel = dest.level\n }\n } else if (!opts.dedupe) {\n break\n }\n }\n }\n\n function emit (...args) {\n for (const { stream } of this.streams) {\n if (typeof stream.emit === 'function') {\n stream.emit(...args)\n }\n }\n }\n\n function flushSync () {\n for (const { stream } of this.streams) {\n if (typeof stream.flushSync === 'function') {\n stream.flushSync()\n }\n }\n }\n\n function add (dest) {\n if (!dest) {\n return res\n }\n\n // Check that dest implements either StreamEntry or DestinationStream\n const isStream = typeof dest.write === 'function' || dest.stream\n const stream_ = dest.write ? dest : dest.stream\n // This is necessary to provide a meaningful error message, otherwise it throws somewhere inside write()\n if (!isStream) {\n throw Error('stream object needs to implement either StreamEntry or DestinationStream interface')\n }\n\n const { streams, streamLevels } = this\n\n let level\n if (typeof dest.levelVal === 'number') {\n level = dest.levelVal\n } else if (typeof dest.level === 'string') {\n level = streamLevels[dest.level]\n } else if (typeof dest.level === 'number') {\n level = dest.level\n } else {\n level = DEFAULT_INFO_LEVEL\n }\n\n const dest_ = {\n stream: stream_,\n level,\n levelVal: undefined,\n id: counter++\n }\n\n streams.unshift(dest_)\n streams.sort(compareByLevel)\n\n this.minLevel = streams[0].level\n\n return res\n }\n\n function end () {\n for (const { stream } of this.streams) {\n if (typeof stream.flushSync === 'function') {\n stream.flushSync()\n }\n stream.end()\n }\n }\n\n function clone (level) {\n const streams = new Array(this.streams.length)\n\n for (let i = 0; i < streams.length; i++) {\n streams[i] = {\n level,\n stream: this.streams[i].stream\n }\n }\n\n return {\n write,\n add,\n minLevel: level,\n streams,\n clone,\n emit,\n flushSync,\n [metadata]: true\n }\n }\n}\n\nfunction compareByLevel (a, b) {\n return a.level - b.level\n}\n\nfunction initLoopVar (length, dedupe) {\n return dedupe ? length - 1 : 0\n}\n\nfunction adjustLoopVar (i, dedupe) {\n return dedupe ? i - 1 : i + 1\n}\n\nfunction checkLoopVar (i, length, dedupe) {\n return dedupe ? i >= 0 : i < length\n}\n\nmodule.exports = multistream\n", "\n function pinoBundlerAbsolutePath(p) {\n try {\n return require('path').join(`${process.cwd()}${require('path').sep}dist/cjs`.replace(/\\\\/g, '/'), p)\n } catch(e) {\n const f = new Function('p', 'return new URL(p, import.meta.url).pathname');\n return f(p)\n }\n }\n \n globalThis.__bundlerPathsOverrides = { ...(globalThis.__bundlerPathsOverrides || {}), 'thread-stream-worker': pinoBundlerAbsolutePath('./thread-stream-worker.cjs'),'pino-worker': pinoBundlerAbsolutePath('./pino-worker.cjs'),'pino/file': pinoBundlerAbsolutePath('./pino-file.cjs'),'pino-roll': pinoBundlerAbsolutePath('./pino-roll.cjs')}\n 'use strict'\n\nconst os = require('node:os')\nconst stdSerializers = require('pino-std-serializers')\nconst caller = require('./lib/caller')\nconst redaction = require('./lib/redaction')\nconst time = require('./lib/time')\nconst proto = require('./lib/proto')\nconst symbols = require('./lib/symbols')\nconst { configure } = require('safe-stable-stringify')\nconst { assertDefaultLevelFound, mappings, genLsCache, genLevelComparison, assertLevelComparison } = require('./lib/levels')\nconst { DEFAULT_LEVELS, SORTING_ORDER } = require('./lib/constants')\nconst {\n createArgsNormalizer,\n asChindings,\n buildSafeSonicBoom,\n buildFormatters,\n stringify,\n normalizeDestFileDescriptor,\n noop\n} = require('./lib/tools')\nconst { version } = require('./lib/meta')\nconst {\n chindingsSym,\n redactFmtSym,\n serializersSym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n stringifySym,\n stringifySafeSym,\n stringifiersSym,\n setLevelSym,\n endSym,\n formatOptsSym,\n messageKeySym,\n errorKeySym,\n nestedKeySym,\n mixinSym,\n levelCompSym,\n useOnlyCustomLevelsSym,\n formattersSym,\n hooksSym,\n nestedKeyStrSym,\n mixinMergeStrategySym,\n msgPrefixSym\n} = symbols\nconst { epochTime, nullTime } = time\nconst { pid } = process\nconst hostname = os.hostname()\nconst defaultErrorSerializer = stdSerializers.err\nconst defaultOptions = {\n level: 'info',\n levelComparison: SORTING_ORDER.ASC,\n levels: DEFAULT_LEVELS,\n messageKey: 'msg',\n errorKey: 'err',\n nestedKey: null,\n enabled: true,\n base: { pid, hostname },\n serializers: Object.assign(Object.create(null), {\n err: defaultErrorSerializer\n }),\n formatters: Object.assign(Object.create(null), {\n bindings (bindings) {\n return bindings\n },\n level (label, number) {\n return { level: number }\n }\n }),\n hooks: {\n logMethod: undefined,\n streamWrite: undefined\n },\n timestamp: epochTime,\n name: undefined,\n redact: null,\n customLevels: null,\n useOnlyCustomLevels: false,\n depthLimit: 5,\n edgeLimit: 100\n}\n\nconst normalize = createArgsNormalizer(defaultOptions)\n\nconst serializers = Object.assign(Object.create(null), stdSerializers)\n\nfunction pino (...args) {\n const instance = {}\n const { opts, stream } = normalize(instance, caller(), ...args)\n\n if (opts.level && typeof opts.level === 'string' && DEFAULT_LEVELS[opts.level.toLowerCase()] !== undefined) opts.level = opts.level.toLowerCase()\n\n const {\n redact,\n crlf,\n serializers,\n timestamp,\n messageKey,\n errorKey,\n nestedKey,\n base,\n name,\n level,\n customLevels,\n levelComparison,\n mixin,\n mixinMergeStrategy,\n useOnlyCustomLevels,\n formatters,\n hooks,\n depthLimit,\n edgeLimit,\n onChild,\n msgPrefix\n } = opts\n\n const stringifySafe = configure({\n maximumDepth: depthLimit,\n maximumBreadth: edgeLimit\n })\n\n const allFormatters = buildFormatters(\n formatters.level,\n formatters.bindings,\n formatters.log\n )\n\n const stringifyFn = stringify.bind({\n [stringifySafeSym]: stringifySafe\n })\n const stringifiers = redact ? redaction(redact, stringifyFn) : {}\n const formatOpts = redact\n ? { stringify: stringifiers[redactFmtSym] }\n : { stringify: stringifyFn }\n const end = '}' + (crlf ? '\\r\\n' : '\\n')\n const coreChindings = asChindings.bind(null, {\n [chindingsSym]: '',\n [serializersSym]: serializers,\n [stringifiersSym]: stringifiers,\n [stringifySym]: stringify,\n [stringifySafeSym]: stringifySafe,\n [formattersSym]: allFormatters\n })\n\n let chindings = ''\n if (base !== null) {\n if (name === undefined) {\n chindings = coreChindings(base)\n } else {\n chindings = coreChindings(Object.assign({}, base, { name }))\n }\n }\n\n const time = (timestamp instanceof Function)\n ? timestamp\n : (timestamp ? epochTime : nullTime)\n const timeSliceIndex = time().indexOf(':') + 1\n\n if (useOnlyCustomLevels && !customLevels) throw Error('customLevels is required if useOnlyCustomLevels is set true')\n if (mixin && typeof mixin !== 'function') throw Error(`Unknown mixin type \"${typeof mixin}\" - expected \"function\"`)\n if (msgPrefix && typeof msgPrefix !== 'string') throw Error(`Unknown msgPrefix type \"${typeof msgPrefix}\" - expected \"string\"`)\n\n assertDefaultLevelFound(level, customLevels, useOnlyCustomLevels)\n const levels = mappings(customLevels, useOnlyCustomLevels)\n\n if (typeof stream.emit === 'function') {\n stream.emit('message', { code: 'PINO_CONFIG', config: { levels, messageKey, errorKey } })\n }\n\n assertLevelComparison(levelComparison)\n const levelCompFunc = genLevelComparison(levelComparison)\n\n Object.assign(instance, {\n levels,\n [levelCompSym]: levelCompFunc,\n [useOnlyCustomLevelsSym]: useOnlyCustomLevels,\n [streamSym]: stream,\n [timeSym]: time,\n [timeSliceIndexSym]: timeSliceIndex,\n [stringifySym]: stringify,\n [stringifySafeSym]: stringifySafe,\n [stringifiersSym]: stringifiers,\n [endSym]: end,\n [formatOptsSym]: formatOpts,\n [messageKeySym]: messageKey,\n [errorKeySym]: errorKey,\n [nestedKeySym]: nestedKey,\n // protect against injection\n [nestedKeyStrSym]: nestedKey ? `,${JSON.stringify(nestedKey)}:{` : '',\n [serializersSym]: serializers,\n [mixinSym]: mixin,\n [mixinMergeStrategySym]: mixinMergeStrategy,\n [chindingsSym]: chindings,\n [formattersSym]: allFormatters,\n [hooksSym]: hooks,\n silent: noop,\n onChild,\n [msgPrefixSym]: msgPrefix\n })\n\n Object.setPrototypeOf(instance, proto())\n\n genLsCache(instance)\n\n instance[setLevelSym](level)\n\n return instance\n}\n\nmodule.exports = pino\n\nmodule.exports.destination = (dest = process.stdout.fd) => {\n if (typeof dest === 'object') {\n dest.dest = normalizeDestFileDescriptor(dest.dest || process.stdout.fd)\n return buildSafeSonicBoom(dest)\n } else {\n return buildSafeSonicBoom({ dest: normalizeDestFileDescriptor(dest), minLength: 0 })\n }\n}\n\nmodule.exports.transport = require('./lib/transport')\nmodule.exports.multistream = require('./lib/multistream')\n\nmodule.exports.levels = mappings()\nmodule.exports.stdSerializers = serializers\nmodule.exports.stdTimeFunctions = Object.assign({}, time)\nmodule.exports.symbols = symbols\nmodule.exports.version = version\n\n// Enables default and name export with TypeScript and Babel\nmodule.exports.default = pino\nmodule.exports.pino = pino\n", "'use strict'\n\nconst pino = require('./pino')\nconst { once } = require('node:events')\n\nmodule.exports = async function (opts = {}) {\n const destOpts = Object.assign({}, opts, { dest: opts.destination || 1, sync: false })\n delete destOpts.destination\n const destination = pino.destination(destOpts)\n await once(destination, 'ready')\n return destination\n}\n"], + "mappings": "2EAAA,IAAAA,GAAAC,EAAA,CAAAC,GAAAC,KAAA,cAOA,IAAMC,EAAeC,GACZA,GAAO,OAAOA,EAAI,SAAY,SAOjCC,GAAiBD,GAAQ,CAC7B,GAAI,CAACA,EAAK,OAIV,IAAME,EAAQF,EAAI,MAGlB,GAAI,OAAOE,GAAU,WAAY,CAE/B,IAAMC,EAAcH,EAAI,MAAM,EAE9B,OAAOD,EAAYI,CAAW,EAC1BA,EACA,MACN,KACE,QAAOJ,EAAYG,CAAK,EACpBA,EACA,MAER,EAUME,GAAmB,CAACJ,EAAKK,IAAS,CACtC,GAAI,CAACN,EAAYC,CAAG,EAAG,MAAO,GAE9B,IAAMM,EAAQN,EAAI,OAAS,GAG3B,GAAIK,EAAK,IAAIL,CAAG,EACd,OAAOM,EAAQ;AAAA,gCAGjB,IAAMJ,EAAQD,GAAcD,CAAG,EAE/B,OAAIE,GACFG,EAA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ACzC,EAAQ,EAAGmC,EACZ,OAAQxD,GACR,QAAA2D,EACA,CAACnC,EAAY,EAAGoC,CAClB,CAAC,EAED,OAAO,eAAetB,EAAUtD,GAAM,CAAC,EAEvCK,GAAWiD,CAAQ,EAEnBA,EAAS3B,EAAW,EAAEsC,CAAK,EAEpBX,CACT,CAEA9D,EAAO,QAAU4D,GAEjB5D,EAAO,QAAQ,YAAc,CAACgG,EAAO,QAAQ,OAAO,KAC9C,OAAOA,GAAS,UAClBA,EAAK,KAAOzE,GAA4ByE,EAAK,MAAQ,QAAQ,OAAO,EAAE,EAC/D5E,GAAmB4E,CAAI,GAEvB5E,GAAmB,CAAE,KAAMG,GAA4ByE,CAAI,EAAG,UAAW,CAAE,CAAC,EAIvFhG,EAAO,QAAQ,UAAY,KAC3BA,EAAO,QAAQ,YAAc,KAE7BA,EAAO,QAAQ,OAASY,GAAS,EACjCZ,EAAO,QAAQ,eAAiB2D,GAChC3D,EAAO,QAAQ,iBAAmB,OAAO,OAAO,CAAC,EAAGO,EAAI,EACxDP,EAAO,QAAQ,QAAUS,GACzBT,EAAO,QAAQ,QAAUyB,GAGzBzB,EAAO,QAAQ,QAAU4D,GACzB5D,EAAO,QAAQ,KAAO4D,KClPtB,IAAMqC,GAAO,KACP,CAAE,KAAAC,EAAK,EAAI,QAAQ,aAAa,EAEtC,OAAO,QAAU,eAAgBC,EAAO,CAAC,EAAG,CAC1C,IAAMC,EAAW,OAAO,OAAO,CAAC,EAAGD,EAAM,CAAE,KAAMA,EAAK,aAAe,EAAG,KAAM,EAAM,CAAC,EACrF,OAAOC,EAAS,YAChB,IAAMC,EAAcJ,GAAK,YAAYG,CAAQ,EAC7C,aAAMF,GAAKG,EAAa,OAAO,EACxBA,CACT", + "names": ["require_err_helpers", "__commonJSMin", "exports", "module", "isErrorLike", "err", "getErrorCause", "cause", "causeResult", "_stackWithCauses", "seen", "stack", "stackWithCauses", "_messageWithCauses", "skip", "message", "skipIfVErrorStyleCause", "messageWithCauses", "require_err_proto", "__commonJSMin", "exports", "module", "seen", "rawSymbol", "pinoErrProto", "val", "require_err", "__commonJSMin", "exports", "module", "errSerializer", "messageWithCauses", "stackWithCauses", "isErrorLike", "pinoErrProto", "pinoErrorSymbols", "seen", "toString", "err", "_err", "key", "val", "require_err_with_cause", "__commonJSMin", "exports", "module", "errWithCauseSerializer", "isErrorLike", "pinoErrProto", "pinoErrorSymbols", "seen", "toString", "err", "_err", "key", "val", "require_req", "__commonJSMin", "exports", "module", "mapHttpRequest", "reqSerializer", "rawSymbol", "pinoReqProto", "val", "req", "connection", "_req", "path", "require_res", "__commonJSMin", "exports", "module", "mapHttpResponse", "resSerializer", "rawSymbol", "pinoResProto", "val", "res", "_res", "require_pino_std_serializers", "__commonJSMin", "exports", "module", "errSerializer", "errWithCauseSerializer", "reqSerializers", "resSerializers", "customSerializer", "err", "req", "res", "require_caller", "__commonJSMin", "exports", "module", "noOpPrepareStackTrace", "_", "stack", "originalPrepare", "entries", "fileNames", "entry", "require_validator", "__commonJSMin", "exports", "module", "validator", "opts", "ERR_PATHS_MUST_BE_STRINGS", "ERR_INVALID_PATH", "s", "paths", "expr", "require_rx", "__commonJSMin", "exports", "module", "require_parse", "__commonJSMin", "exports", "module", "rx", "parse", "paths", "wildcards", "wcLen", "secret", "o", "strPath", "ix", "path", "p", "leadingBracket", "star", "before", "beforeStr", "after", "nested", "require_redactor", "__commonJSMin", "exports", "module", "rx", "redactor", "secret", "serialize", "wcLen", "strict", "isCensorFct", "censorFctTakesPath", "state", "redact", "strictImpl", "redactTmpl", "dynamicRedactTmpl", "resultTmpl", "o", "path", "escPath", "leadingBracket", "arrPath", "skip", "delim", "hops", "match", "ix", "index", "input", "existence", "p", "circularDetection", "censorArgs", "hasWildcards", "require_modifiers", "__commonJSMin", "exports", "module", "groupRedact", "groupRestore", "nestedRedact", "nestedRestore", "keys", "values", "target", "length", "k", "o", "path", "censor", "isCensorFct", "censorFctTakesPath", "get", "keysLength", "pathLength", "pathWithKey", "i", "key", "instructions", "value", "current", "store", "ns", "specialSet", "has", "obj", "prop", "afterPath", "afterPathLen", "lastPathIndex", "originalKey", "n", "nv", "ov", "oov", "wc", "kIsWc", "wcov", "consecutive", "level", "depth", "redactPathCurrent", "tree", "wcKeys", "j", "wck", "node", "iterateNthLevel", "rv", "restoreInstr", "p", "l", "parent", "child", "require_restorer", "__commonJSMin", "exports", "module", "groupRestore", "nestedRestore", "restorer", "secret", "wcLen", "paths", "resetters", "resetTmpl", "hasWildcards", "state", "restoreTmpl", "path", "circle", "escPath", "leadingBracket", "reset", "clear", "require_state", "__commonJSMin", "exports", "module", "state", "o", "secret", "censor", "compileRestore", "serialize", "groupRedact", "nestedRedact", "wildcards", "wcLen", "builder", "require_fast_redact", "__commonJSMin", "exports", "module", "validator", "parse", "redactor", "restorer", "groupRedact", "nestedRedact", "state", "rx", "validate", "noop", "o", "DEFAULT_CENSOR", "fastRedact", "opts", "paths", "serialize", "remove", "censor", "isCensorFct", "censorFctTakesPath", "wildcards", "wcLen", "secret", "compileRestore", "strict", "require_symbols", "__commonJSMin", "exports", "module", "setLevelSym", "getLevelSym", "levelValSym", "levelCompSym", "useLevelLabelsSym", "useOnlyCustomLevelsSym", "mixinSym", "lsCacheSym", "chindingsSym", "asJsonSym", "writeSym", "redactFmtSym", "timeSym", "timeSliceIndexSym", "streamSym", "stringifySym", "stringifySafeSym", "stringifiersSym", "endSym", "formatOptsSym", "messageKeySym", "errorKeySym", "nestedKeySym", "nestedKeyStrSym", "mixinMergeStrategySym", "msgPrefixSym", "wildcardFirstSym", "serializersSym", "formattersSym", "hooksSym", "needsMetadataGsym", "require_redaction", "__commonJSMin", "exports", "module", "fastRedact", "redactFmtSym", "wildcardFirstSym", "rx", "validator", "validate", "s", "CENSOR", "strict", "redaction", "opts", "serialize", "paths", "censor", "handle", "shape", "o", "str", "first", "next", "ns", "index", "nextPath", "k", "result", "topCensor", "args", "value", "wrappedCensor", "path", "remove", "require_time", "__commonJSMin", "exports", "module", "nullTime", "epochTime", "unixTime", "isoTime", "require_quick_format_unescaped", "__commonJSMin", "exports", "module", "tryStringify", "o", "format", "f", "args", "opts", "ss", "offset", "len", "objects", "index", "argLen", "str", "a", "lastPos", "flen", "i", "type", "require_atomic_sleep", "__commonJSMin", "exports", "module", "sleep", "ms", "nil", "target", "require_sonic_boom", "__commonJSMin", "exports", "module", "fs", "EventEmitter", "inherits", "path", "sleep", "assert", "BUSY_WRITE_TIMEOUT", "kEmptyBuffer", "MAX_WRITE", "kContentModeBuffer", "kContentModeUtf8", "major", "minor", "kCopyBuffer", "openFile", "file", "sonic", "fileOpened", "err", "fd", "reopening", "flags", "mode", "SonicBoom", "opts", "dest", "minLength", "maxLength", "maxWrite", "periodicFlush", "sync", "append", "mkdir", "retryEAGAIN", "fsync", "contentMode", "fsWriteSync", "fsWrite", "writeBuffer", "flushBuffer", "flushBufferSync", "actualWriteBuffer", "write", "flush", "flushSync", "actualWrite", "n", "releasedBufObj", "releaseWritingBuf", "len", "actualClose", "emitDrain", "name", "writingBuf", "mergeBuf", "bufs", "data", "lens", "callFlushCallbackOnDrain", "cb", "onDrain", "onError", "error", "buf", "release", "written", "closeWrapped", "done", "require_on_exit_leak_free", "__commonJSMin", "exports", "module", "refs", "functions", "onExit", "onBeforeExit", "registry", "ensureRegistry", "clear", "install", "event", "uninstall", "callRefs", "ref", "obj", "fn", "index", "_register", "register", "registerBeforeExit", "unregister", "_obj", "require_package", "__commonJSMin", "exports", "module", "require_wait", "__commonJSMin", "exports", "module", "wait", "state", "index", "expected", "timeout", "done", "max", "current", "prior", "check", "backoff", "waitDiff", "require_indexes", "__commonJSMin", "exports", "module", "require_thread_stream", "__commonJSMin", "exports", "module", "version", "EventEmitter", "Worker", "join", "pathToFileURL", "wait", "WRITE_INDEX", "READ_INDEX", "buffer", "assert", "kImpl", "MAX_STRING", "FakeWeakRef", "value", "FakeFinalizationRegistry", "FinalizationRegistry", "WeakRef", "registry", "worker", "createWorker", "stream", "opts", "filename", "workerData", "toExecute", "onWorkerMessage", "onWorkerExit", "drain", "nextFlush", "writeIndex", "leftover", "end", "toWrite", "toWriteBytes", "write", "destroy", "msg", "code", "ThreadStream", "message", "transferList", "data", "error", "writeSync", "err", "cb", "res", "flushSync", "current", "length", "readIndex", "spins", "require_transport", "__commonJSMin", "exports", "module", "createRequire", "getCallers", "join", "isAbsolute", "sep", "sleep", "onExit", "ThreadStream", "setupOnExit", "stream", "autoEnd", "flush", "buildStream", "filename", "workerData", "workerOpts", "sync", "onReady", "transport", "fullOptions", "pipeline", "targets", "levels", "dedupe", "worker", "caller", "options", "callers", "bundlerOverrides", "target", "dest", "fixTarget", "t", "origin", "filePath", "context", "require_tools", "__commonJSMin", "exports", "module", "format", "mapHttpRequest", "mapHttpResponse", "SonicBoom", "onExit", "lsCacheSym", "chindingsSym", "writeSym", "serializersSym", "formatOptsSym", "endSym", "stringifiersSym", "stringifySym", "stringifySafeSym", "wildcardFirstSym", "nestedKeySym", "formattersSym", "messageKeySym", "errorKeySym", "nestedKeyStrSym", "msgPrefixSym", "isMainThread", "transport", "noop", "genLog", "level", "hook", "LOG", "args", "o", "n", "msg", "formatParams", "asString", "str", "result", "last", "found", "point", "l", "i", "asJson", "obj", "num", "time", "stringify", "stringifySafe", "stringifiers", "end", "chindings", "serializers", "formatters", "messageKey", "errorKey", "data", "value", "wildcardStringifier", "propStr", "key", "stringifier", "strKey", "msgStr", "asChindings", "instance", "bindings", "formatter", "hasBeenTampered", "stream", "buildSafeSonicBoom", "opts", "filterBrokenPipe", "autoEnd", "err", "eventName", "createArgsNormalizer", "defaultOptions", "caller", "customLevels", "enabled", "onChild", "stringifySafeFn", "buildFormatters", "log", "normalizeDestFileDescriptor", "destination", "fd", "require_constants", "__commonJSMin", "exports", "module", "DEFAULT_LEVELS", "SORTING_ORDER", "require_levels", "__commonJSMin", "exports", "module", "lsCacheSym", "levelValSym", "useOnlyCustomLevelsSym", "streamSym", "formattersSym", "hooksSym", "levelCompSym", "noop", "genLog", "DEFAULT_LEVELS", "SORTING_ORDER", "levelMethods", "hook", "logFatal", "args", "stream", "nums", "o", "k", "initialLsCache", "genLsCache", "instance", "formatter", "labels", "cache", "label", "level", "isStandardLevel", "useOnlyCustomLevels", "setLevel", "values", "preLevelVal", "levelVal", "useOnlyCustomLevelsVal", "levelComparison", "key", "getLevel", "levels", "isLevelEnabled", "logLevel", "logLevelVal", "compareLevel", "direction", "current", "expected", "genLevelComparison", "mappings", "customLevels", "customNums", "assertDefaultLevelFound", "defaultLevel", "assertNoLevelCollisions", "assertLevelComparison", "require_meta", "__commonJSMin", "exports", "module", "require_proto", "__commonJSMin", "exports", "module", "EventEmitter", "lsCacheSym", "levelValSym", "setLevelSym", "getLevelSym", "chindingsSym", "parsedChindingsSym", "mixinSym", "asJsonSym", "writeSym", "mixinMergeStrategySym", "timeSym", "timeSliceIndexSym", "streamSym", "serializersSym", "formattersSym", "errorKeySym", "messageKeySym", "useOnlyCustomLevelsSym", "needsMetadataGsym", "redactFmtSym", "stringifySym", "formatOptsSym", "stringifiersSym", "msgPrefixSym", "hooksSym", "getLevel", "setLevel", "isLevelEnabled", "mappings", "initialLsCache", "genLsCache", "assertNoLevelCollisions", "asChindings", "asJson", "buildFormatters", "stringify", "version", "redaction", "constructor", "prototype", "child", "bindings", "setBindings", "flush", "lvl", "n", "write", "resetChildingsFormatter", "options", "serializers", "formatters", "instance", "k", "parentSymbols", "i", "ks", "bk", "bindingsSymbols", "bi", "bks", "level", "chindings", "log", "stringifiers", "formatOpts", "childLevel", "chindingsJson", "bindingsFromJson", "newBindings", "defaultMixinMergeStrategy", "mergeObject", "mixinObject", "_obj", "msg", "num", "t", "mixin", "errorKey", "messageKey", "mixinMergeStrategy", "obj", "streamWriteHook", "s", "stream", "noop", "cb", "require_safe_stable_stringify", "__commonJSMin", "exports", "module", "hasOwnProperty", "stringify", "configure", "strEscapeSequencesRegExp", "strEscape", "str", "sort", "array", "comparator", "i", "currentValue", "position", "typedArrayPrototypeGetSymbolToStringTag", "isTypedArrayWithEntries", "value", "stringifyTypedArray", "separator", "maximumBreadth", "whitespace", "res", "getCircularValueOption", "options", "circularValue", "getDeterministicOption", "getBooleanOption", "key", "getPositiveIntegerOption", "getItemCount", "number", "getUniqueReplacerSet", "replacerArray", "replacerSet", "getStrictOption", "message", "fail", "bigint", "deterministic", "maximumDepth", "stringifyFnReplacer", "parent", "stack", "replacer", "spacer", "indentation", "join", "originalIndentation", "maximumValuesToStringify", "tmp", "removedKeys", "keys", "keyLength", "maximumPropertiesToStringify", "stringifyArrayReplacer", "stringifyIndent", "stringifySimple", "hasLength", "space", "require_multistream", "__commonJSMin", "exports", "module", "metadata", "DEFAULT_LEVELS", "DEFAULT_INFO_LEVEL", "multistream", "streamsArray", "opts", "counter", "streamLevels", "i", "res", "write", "add", "emit", "flushSync", "end", "clone", "data", "dest", "level", "streams", "recordedLevel", "stream", "initLoopVar", "checkLoopVar", "adjustLoopVar", "lastTime", "lastMsg", "lastObj", "lastLogger", "args", "isStream", "stream_", "dest_", "compareByLevel", "a", "b", "length", "dedupe", "require_pino", "__commonJSMin", "exports", "module", "pinoBundlerAbsolutePath", "p", "os", "stdSerializers", "caller", "redaction", "time", "proto", "symbols", "configure", "assertDefaultLevelFound", "mappings", "genLsCache", "genLevelComparison", "assertLevelComparison", "DEFAULT_LEVELS", "SORTING_ORDER", "createArgsNormalizer", "asChindings", "buildSafeSonicBoom", "buildFormatters", "stringify", "normalizeDestFileDescriptor", "noop", "version", "chindingsSym", "redactFmtSym", "serializersSym", "timeSym", "timeSliceIndexSym", "streamSym", "stringifySym", "stringifySafeSym", "stringifiersSym", "setLevelSym", "endSym", "formatOptsSym", "messageKeySym", "errorKeySym", "nestedKeySym", "mixinSym", "levelCompSym", "useOnlyCustomLevelsSym", "formattersSym", "hooksSym", "nestedKeyStrSym", "mixinMergeStrategySym", "msgPrefixSym", "epochTime", "nullTime", "pid", "hostname", "defaultErrorSerializer", "defaultOptions", "bindings", "label", "number", "normalize", "serializers", "pino", "args", "instance", "opts", "stream", "redact", "crlf", "timestamp", "messageKey", "errorKey", "nestedKey", "base", "name", "level", "customLevels", "levelComparison", "mixin", "mixinMergeStrategy", "useOnlyCustomLevels", "formatters", "hooks", "depthLimit", "edgeLimit", "onChild", "msgPrefix", "stringifySafe", "allFormatters", "stringifyFn", "stringifiers", "formatOpts", "end", "coreChindings", "chindings", "timeSliceIndex", "levels", "levelCompFunc", "dest", "pino", "once", "opts", "destOpts", "destination"] +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/pino-roll.cjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/pino-roll.cjs new file mode 100644 index 0000000000000000000000000000000000000000..089c50f44a0778b5c5eda180b06d7d4e77909192 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/pino-roll.cjs @@ -0,0 +1,2 @@ +"use strict";var s=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports);var Zo=s((YW,pr)=>{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let r=function(t){if((t>0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(e,0,0,Number(t))},e=new Int32Array(new SharedArrayBuffer(4));pr.exports=r}else{let e=function(r){if((r>0&&r<1/0)===!1)throw typeof r!="number"&&typeof r!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let n=Date.now()+Number(r);for(;n>Date.now(););};pr.exports=e}});var ko=s((WW,yo)=>{"use strict";var j=require("fs"),yg=require("events"),kg=require("util").inherits,Xo=require("path"),Dr=Zo(),ev=require("assert"),Re=100,Ae=Buffer.allocUnsafe(0),rv=16*1024,Vo="buffer",Go="utf8",[tv,nv]=(process.versions.node||"0.0").split(".").map(Number),iv=tv>=22&&nv>=7;function Uo(e,r){r._opening=!0,r._writing=!0,r._asyncDrainScheduled=!1;function t(a,o){if(a){r._reopening=!1,r._writing=!1,r._opening=!1,r.sync?process.nextTick(()=>{r.listenerCount("error")>0&&r.emit("error",a)}):r.emit("error",a);return}let c=r._reopening;r.fd=o,r.file=e,r._reopening=!1,r._opening=!1,r._writing=!1,r.sync?process.nextTick(()=>r.emit("ready")):r.emit("ready"),!r.destroyed&&(!r._writing&&r._len>r.minLength||r._flushPending?r._actualWrite():c&&process.nextTick(()=>r.emit("drain")))}let n=r.append?"a":"w",u=r.mode;if(r.sync)try{r.mkdir&&j.mkdirSync(Xo.dirname(e),{recursive:!0});let a=j.openSync(e,n,u);t(null,a)}catch(a){throw t(a),a}else r.mkdir?j.mkdir(Xo.dirname(e),{recursive:!0},a=>{if(a)return t(a);j.open(e,n,u,t)}):j.open(e,n,u,t)}function F(e){if(!(this instanceof F))return new F(e);let{fd:r,dest:t,minLength:n,maxLength:u,maxWrite:a,periodicFlush:o,sync:c,append:f=!0,mkdir:d,retryEAGAIN:h,fsync:_,contentMode:g,mode:p}=e||{};r=r||t,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(n||0,16387),this.file=null,this.destroyed=!1,this.minLength=n||0,this.maxLength=u||0,this.maxWrite=a||rv,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=c||!1,this.writable=!0,this._fsync=_||!1,this.append=f||!1,this.mode=p,this.retryEAGAIN=h||(()=>!0),this.mkdir=d||!1;let q,x;if(g===Vo)this._writingBuf=Ae,this.write=sv,this.flush=cv,this.flushSync=dv,this._actualWrite=hv,q=()=>j.writeSync(this.fd,this._writingBuf),x=()=>j.write(this.fd,this._writingBuf,this.release);else if(g===void 0||g===Go)this._writingBuf="",this.write=av,this.flush=ov,this.flushSync=fv,this._actualWrite=lv,q=()=>j.writeSync(this.fd,this._writingBuf,"utf8"),x=()=>j.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${Go}" and "${Vo}", but passed ${g}`);if(typeof r=="number")this.fd=r,process.nextTick(()=>this.emit("ready"));else if(typeof r=="string")Uo(r,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(m,D)=>{if(m){if((m.code==="EAGAIN"||m.code==="EBUSY")&&this.retryEAGAIN(m,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{Dr(Re),this.release(void 0,0)}catch(Q){this.release(Q)}else setTimeout(x,Re);else this._writing=!1,this.emit("error",m);return}this.emit("write",D);let E=Mr(this._writingBuf,this._len,D);if(this._len=E.len,this._writingBuf=E.writingBuf,this._writingBuf.length){if(!this.sync){x();return}try{do{let Q=q(),me=Mr(this._writingBuf,this._len,Q);this._len=me.len,this._writingBuf=me.writingBuf}while(this._writingBuf.length)}catch(Q){this.release(Q);return}}this._fsync&&j.fsyncSync(this.fd);let B=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):B>this.minLength?this._actualWrite():this._ending?B>0?this._actualWrite():(this._writing=!1,$e(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(uv,this)):this.emit("drain"))},this.on("newListener",function(m){m==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function Mr(e,r,t){return typeof e=="string"&&Buffer.byteLength(e)!==t&&(t=Buffer.from(e).subarray(0,t).toString().length),r=Math.max(r-t,0),e=e.slice(t),{writingBuf:e,len:r}}function uv(e){e.listenerCount("drain")>0&&(e._asyncDrainScheduled=!1,e.emit("drain"))}kg(F,yg);function Jo(e,r){return e.length===0?Ae:e.length===1?e[0]:Buffer.concat(e,r)}function av(e){if(this.destroyed)throw new Error("SonicBoom destroyed");let r=this._len+e.length,t=this._bufs;return this.maxLength&&r>this.maxLength?(this.emit("drop",e),this._lenthis.maxWrite?t.push(""+e):t[t.length-1]+=e,this._len=r,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._lenthis.maxLength?(this.emit("drop",e),this._lenthis.maxWrite?(t.push([e]),n.push(e.length)):(t[t.length-1].push(e),n[n.length-1]+=e.length),this._len=r,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len{if(this._fsync)this._flushPending=!1,e();else try{j.fsync(this.fd,n=>{this._flushPending=!1,e(n)})}catch(n){e(n)}this.off("error",t)},t=n=>{this._flushPending=!1,e(n),this.off("drain",r)};this.once("drain",r),this.once("error",t)}function ov(e){if(e!=null&&typeof e!="function")throw new Error("flush cb must be a function");if(this.destroyed){let r=new Error("SonicBoom destroyed");if(e){e(r);return}throw r}if(this.minLength<=0){e?.();return}e&&Ko.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function cv(e){if(e!=null&&typeof e!="function")throw new Error("flush cb must be a function");if(this.destroyed){let r=new Error("SonicBoom destroyed");if(e){e(r);return}throw r}if(this.minLength<=0){e?.();return}e&&Ko.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}F.prototype.reopen=function(e){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(e&&(this.file=e),this._reopening=!0,this._writing)return;let r=this.fd;this.once("ready",()=>{r!==this.fd&&j.close(r,t=>{if(t)return this.emit("error",t)})}),Uo(this.file,this)};F.prototype.end=function(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():$e(this)))};function fv(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let e="";for(;this._bufs.length||e;){e.length<=0&&(e=this._bufs[0]);try{let r=j.writeSync(this.fd,e,"utf8"),t=Mr(e,this._len,r);e=t.writingBuf,this._len=t.len,e.length<=0&&this._bufs.shift()}catch(r){if((r.code==="EAGAIN"||r.code==="EBUSY")&&!this.retryEAGAIN(r,e.length,this._len-e.length))throw r;Dr(Re)}}try{j.fsyncSync(this.fd)}catch{}}function dv(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=Ae);let e=Ae;for(;this._bufs.length||e.length;){e.length<=0&&(e=Jo(this._bufs[0],this._lens[0]));try{let r=j.writeSync(this.fd,e);e=e.subarray(r),this._len=Math.max(this._len-r,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(r){if((r.code==="EAGAIN"||r.code==="EBUSY")&&!this.retryEAGAIN(r,e.length,this._len-e.length))throw r;Dr(Re)}}}F.prototype.destroy=function(){this.destroyed||$e(this)};function lv(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf||this._bufs.shift()||"",this.sync)try{let r=j.writeSync(this.fd,this._writingBuf,"utf8");e(null,r)}catch(r){e(r)}else j.write(this.fd,this._writingBuf,"utf8",e)}function hv(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:Jo(this._bufs.shift(),this._lens.shift()),this.sync)try{let r=j.writeSync(this.fd,this._writingBuf);e(null,r)}catch(r){e(r)}else iv&&(this._writingBuf=Buffer.from(this._writingBuf)),j.write(this.fd,this._writingBuf,e)}function $e(e){if(e.fd===-1){e.once("ready",$e.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],ev(typeof e.fd=="number",`sonic.fd must be a number, got ${typeof e.fd}`);try{j.fsync(e.fd,r)}catch{}function r(){e.fd!==1&&e.fd!==2?j.close(e.fd,t):t()}function t(n){if(n){e.emit("error",n);return}e._ending&&!e._writing&&e.emit("finish"),e.emit("close")}}F.SonicBoom=F;F.default=F;yo.exports=F});var O=s(v=>{"use strict";v.secondsInYear=v.secondsInWeek=v.secondsInQuarter=v.secondsInMonth=v.secondsInMinute=v.secondsInHour=v.secondsInDay=v.quartersInYear=v.monthsInYear=v.monthsInQuarter=v.minutesInYear=v.minutesInMonth=v.minutesInHour=v.minutesInDay=v.minTime=v.millisecondsInWeek=v.millisecondsInSecond=v.millisecondsInMinute=v.millisecondsInHour=v.millisecondsInDay=v.maxTime=v.daysInYear=v.daysInWeek=v.constructFromSymbol=void 0;var SW=v.daysInWeek=7,_v=v.daysInYear=365.2425,mv=v.maxTime=Math.pow(10,8)*24*60*60*1e3,FW=v.minTime=-mv,NW=v.millisecondsInWeek=6048e5,HW=v.millisecondsInDay=864e5,LW=v.millisecondsInMinute=6e4,CW=v.millisecondsInHour=36e5,zW=v.millisecondsInSecond=1e3,BW=v.minutesInYear=525600,QW=v.minutesInMonth=43200,RW=v.minutesInDay=1440,AW=v.minutesInHour=60,$W=v.monthsInQuarter=3,ZW=v.monthsInYear=12,XW=v.quartersInYear=4,bv=v.secondsInHour=3600,VW=v.secondsInMinute=60,ec=v.secondsInDay=bv*24,GW=v.secondsInWeek=ec*7,gv=v.secondsInYear=ec*_v,vv=v.secondsInMonth=gv/12,UW=v.secondsInQuarter=vv*3,JW=v.constructFromSymbol=Symbol.for("constructDateFrom")});var b=s(tc=>{"use strict";tc.constructFrom=xv;var rc=O();function xv(e,r){return typeof e=="function"?e(r):e&&typeof e=="object"&&rc.constructFromSymbol in e?e[rc.constructFromSymbol](r):e instanceof Date?new e.constructor(r):new Date(r)}});var l=s(nc=>{"use strict";nc.toDate=qv;var Ov=b();function qv(e,r){return(0,Ov.constructFrom)(r||e,e)}});var H=s(ic=>{"use strict";ic.addDays=Dv;var pv=b(),Mv=l();function Dv(e,r,t){let n=(0,Mv.toDate)(e,t?.in);return isNaN(r)?(0,pv.constructFrom)(t?.in||e,NaN):(r&&n.setDate(n.getDate()+r),n)}});var se=s(ac=>{"use strict";ac.addMonths=Pv;var uc=b(),wv=l();function Pv(e,r,t){let n=(0,wv.toDate)(e,t?.in);if(isNaN(r))return(0,uc.constructFrom)(t?.in||e,NaN);if(!r)return n;let u=n.getDate(),a=(0,uc.constructFrom)(t?.in||e,n.getTime());a.setMonth(n.getMonth()+r+1,0);let o=a.getDate();return u>=o?a:(n.setFullYear(a.getFullYear(),a.getMonth(),u),n)}});var wr=s(sc=>{"use strict";sc.add=Yv;var jv=H(),Iv=se(),Tv=b(),Ev=l();function Yv(e,r,t){let{years:n=0,months:u=0,weeks:a=0,days:o=0,hours:c=0,minutes:f=0,seconds:d=0}=r,h=(0,Ev.toDate)(e,t?.in),_=u||n?(0,Iv.addMonths)(h,u+n*12):h,g=o||a?(0,jv.addDays)(_,o+a*7):_,p=f+c*60,x=(d+p*60)*1e3;return(0,Tv.constructFrom)(t?.in||e,+g+x)}});var Pr=s(oc=>{"use strict";oc.isSaturday=Sv;var Wv=l();function Sv(e,r){return(0,Wv.toDate)(e,r?.in).getDay()===6}});var jr=s(cc=>{"use strict";cc.isSunday=Nv;var Fv=l();function Nv(e,r){return(0,Fv.toDate)(e,r?.in).getDay()===0}});var be=s(fc=>{"use strict";fc.isWeekend=Lv;var Hv=l();function Lv(e,r){let t=(0,Hv.toDate)(e,r?.in).getDay();return t===0||t===6}});var Tr=s(dc=>{"use strict";dc.addBusinessDays=Rv;var Cv=b(),zv=Pr(),Bv=jr(),Ir=be(),Qv=l();function Rv(e,r,t){let n=(0,Qv.toDate)(e,t?.in),u=(0,Ir.isWeekend)(n,t);if(isNaN(r))return(0,Cv.constructFrom)(t?.in,NaN);let a=n.getHours(),o=r<0?-1:1,c=Math.trunc(r/5);n.setDate(n.getDate()+c*7);let f=Math.abs(r%5);for(;f>0;)n.setDate(n.getDate()+o),(0,Ir.isWeekend)(n,t)||(f-=1);return u&&(0,Ir.isWeekend)(n,t)&&r!==0&&((0,zv.isSaturday)(n,t)&&n.setDate(n.getDate()+(o<0?2:-1)),(0,Bv.isSunday)(n,t)&&n.setDate(n.getDate()+(o<0?1:-2))),n.setHours(a),n}});var ge=s(lc=>{"use strict";lc.addMilliseconds=Zv;var Av=b(),$v=l();function Zv(e,r,t){return(0,Av.constructFrom)(t?.in||e,+(0,$v.toDate)(e)+r)}});var Er=s(hc=>{"use strict";hc.addHours=Gv;var Xv=ge(),Vv=O();function Gv(e,r,t){return(0,Xv.addMilliseconds)(e,r*Vv.millisecondsInHour,t)}});var Y=s(Yr=>{"use strict";Yr.getDefaultOptions=Uv;Yr.setDefaultOptions=Jv;var _c={};function Uv(){return _c}function Jv(e){_c=e}});var N=s(mc=>{"use strict";mc.startOfWeek=kv;var Kv=Y(),yv=l();function kv(e,r){let t=(0,Kv.getDefaultOptions)(),n=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,u=(0,yv.toDate)(e,r?.in),a=u.getDay(),o=(a{"use strict";bc.startOfISOWeek=rx;var ex=N();function rx(e,r){return(0,ex.startOfWeek)(e,{...r,weekStartsOn:1})}});var U=s(xc=>{"use strict";xc.getISOWeekYear=nx;var gc=b(),vc=L(),tx=l();function nx(e,r){let t=(0,tx.toDate)(e,r?.in),n=t.getFullYear(),u=(0,gc.constructFrom)(t,0);u.setFullYear(n+1,0,4),u.setHours(0,0,0,0);let a=(0,vc.startOfISOWeek)(u),o=(0,gc.constructFrom)(t,0);o.setFullYear(n,0,4),o.setHours(0,0,0,0);let c=(0,vc.startOfISOWeek)(o);return t.getTime()>=a.getTime()?n+1:t.getTime()>=c.getTime()?n:n-1}});var R=s(Oc=>{"use strict";Oc.getTimezoneOffsetInMilliseconds=ux;var ix=l();function ux(e){let r=(0,ix.toDate)(e),t=new Date(Date.UTC(r.getFullYear(),r.getMonth(),r.getDate(),r.getHours(),r.getMinutes(),r.getSeconds(),r.getMilliseconds()));return t.setUTCFullYear(r.getFullYear()),+e-+t}});var P=s(qc=>{"use strict";qc.normalizeDates=sx;var ax=b();function sx(e,...r){let t=ax.constructFrom.bind(null,e||r.find(n=>typeof n=="object"));return r.map(t)}});var ve=s(pc=>{"use strict";pc.startOfDay=cx;var ox=l();function cx(e,r){let t=(0,ox.toDate)(e,r?.in);return t.setHours(0,0,0,0),t}});var A=s(wc=>{"use strict";wc.differenceInCalendarDays=lx;var Mc=R(),fx=P(),dx=O(),Dc=ve();function lx(e,r,t){let[n,u]=(0,fx.normalizeDates)(t?.in,e,r),a=(0,Dc.startOfDay)(n),o=(0,Dc.startOfDay)(u),c=+a-(0,Mc.getTimezoneOffsetInMilliseconds)(a),f=+o-(0,Mc.getTimezoneOffsetInMilliseconds)(o);return Math.round((c-f)/dx.millisecondsInDay)}});var oe=s(Pc=>{"use strict";Pc.startOfISOWeekYear=bx;var hx=b(),_x=U(),mx=L();function bx(e,r){let t=(0,_x.getISOWeekYear)(e,r),n=(0,hx.constructFrom)(r?.in||e,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),(0,mx.startOfISOWeek)(n)}});var Wr=s(Ic=>{"use strict";Ic.setISOWeekYear=Ox;var gx=b(),vx=A(),jc=oe(),xx=l();function Ox(e,r,t){let n=(0,xx.toDate)(e,t?.in),u=(0,vx.differenceInCalendarDays)(n,(0,jc.startOfISOWeekYear)(n,t)),a=(0,gx.constructFrom)(t?.in||e,0);return a.setFullYear(r,0,4),a.setHours(0,0,0,0),n=(0,jc.startOfISOWeekYear)(a),n.setDate(n.getDate()+u),n}});var Sr=s(Tc=>{"use strict";Tc.addISOWeekYears=Mx;var qx=U(),px=Wr();function Mx(e,r,t){return(0,px.setISOWeekYear)(e,(0,qx.getISOWeekYear)(e,t)+r,t)}});var Ze=s(Ec=>{"use strict";Ec.addMinutes=Px;var Dx=O(),wx=l();function Px(e,r,t){let n=(0,wx.toDate)(e,t?.in);return n.setTime(n.getTime()+r*Dx.millisecondsInMinute),n}});var Xe=s(Yc=>{"use strict";Yc.addQuarters=Ix;var jx=se();function Ix(e,r,t){return(0,jx.addMonths)(e,r*3,t)}});var Fr=s(Wc=>{"use strict";Wc.addSeconds=Ex;var Tx=ge();function Ex(e,r,t){return(0,Tx.addMilliseconds)(e,r*1e3,t)}});var xe=s(Sc=>{"use strict";Sc.addWeeks=Wx;var Yx=H();function Wx(e,r,t){return(0,Yx.addDays)(e,r*7,t)}});var Nr=s(Fc=>{"use strict";Fc.addYears=Fx;var Sx=se();function Fx(e,r,t){return(0,Sx.addMonths)(e,r*12,t)}});var Hc=s(Nc=>{"use strict";Nc.areIntervalsOverlapping=Nx;var Ve=l();function Nx(e,r,t){let[n,u]=[+(0,Ve.toDate)(e.start,t?.in),+(0,Ve.toDate)(e.end,t?.in)].sort((c,f)=>c-f),[a,o]=[+(0,Ve.toDate)(r.start,t?.in),+(0,Ve.toDate)(r.end,t?.in)].sort((c,f)=>c-f);return t?.inclusive?n<=o&&a<=u:n{"use strict";Cc.max=Lx;var Lc=b(),Hx=l();function Lx(e,r){let t,n=r?.in;return e.forEach(u=>{!n&&typeof u=="object"&&(n=Lc.constructFrom.bind(null,u));let a=(0,Hx.toDate)(u,n);(!t||t{"use strict";Bc.min=zx;var zc=b(),Cx=l();function zx(e,r){let t,n=r?.in;return e.forEach(u=>{!n&&typeof u=="object"&&(n=zc.constructFrom.bind(null,u));let a=(0,Cx.toDate)(u,n);(!t||t>a||isNaN(+a))&&(t=a)}),(0,zc.constructFrom)(n,t||NaN)}});var Rc=s(Qc=>{"use strict";Qc.clamp=Ax;var Bx=P(),Qx=Hr(),Rx=Lr();function Ax(e,r,t){let[n,u,a]=(0,Bx.normalizeDates)(t?.in,e,r.start,r.end);return(0,Rx.min)([(0,Qx.max)([n,u],t),a],t)}});var Cr=s($c=>{"use strict";$c.closestIndexTo=$x;var Ac=l();function $x(e,r){let t=+(0,Ac.toDate)(e);if(isNaN(t))return NaN;let n,u;return r.forEach((a,o)=>{let c=(0,Ac.toDate)(a);if(isNaN(+c)){n=NaN,u=NaN;return}let f=Math.abs(t-+c);(n==null||f{"use strict";Zc.closestTo=Gx;var Zx=P(),Xx=Cr(),Vx=b();function Gx(e,r,t){let[n,...u]=(0,Zx.normalizeDates)(t?.in,e,...r),a=(0,Xx.closestIndexTo)(n,u);if(typeof a=="number"&&isNaN(a))return(0,Vx.constructFrom)(n,NaN);if(a!==void 0)return u[a]}});var re=s(Gc=>{"use strict";Gc.compareAsc=Ux;var Vc=l();function Ux(e,r){let t=+(0,Vc.toDate)(e)-+(0,Vc.toDate)(r);return t<0?-1:t>0?1:t}});var Kc=s(Jc=>{"use strict";Jc.compareDesc=Jx;var Uc=l();function Jx(e,r){let t=+(0,Uc.toDate)(e)-+(0,Uc.toDate)(r);return t>0?-1:t<0?1:t}});var T=s(yc=>{"use strict";yc.constructNow=yx;var Kx=b();function yx(e){return(0,Kx.constructFrom)(e,Date.now())}});var ef=s(kc=>{"use strict";kc.daysToWeeks=eO;var kx=O();function eO(e){let r=Math.trunc(e/kx.daysInWeek);return r===0?0:r}});var ce=s(tf=>{"use strict";tf.isSameDay=tO;var rO=P(),rf=ve();function tO(e,r,t){let[n,u]=(0,rO.normalizeDates)(t?.in,e,r);return+(0,rf.startOfDay)(n)==+(0,rf.startOfDay)(u)}});var zr=s(nf=>{"use strict";nf.isDate=nO;function nO(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}});var $=s(uf=>{"use strict";uf.isValid=aO;var iO=zr(),uO=l();function aO(e){return!(!(0,iO.isDate)(e)&&typeof e!="number"||isNaN(+(0,uO.toDate)(e)))}});var cf=s(of=>{"use strict";of.differenceInBusinessDays=dO;var sO=P(),af=H(),oO=A(),cO=ce(),sf=$(),fO=be();function dO(e,r,t){let[n,u]=(0,sO.normalizeDates)(t?.in,e,r);if(!(0,sf.isValid)(n)||!(0,sf.isValid)(u))return NaN;let a=(0,oO.differenceInCalendarDays)(n,u),o=a<0?-1:1,c=Math.trunc(a/7),f=c*5,d=(0,af.addDays)(u,c*7);for(;!(0,cO.isSameDay)(n,d);)f+=(0,fO.isWeekend)(d,t)?0:o,d=(0,af.addDays)(d,o);return f===0?0:f}});var Br=s(df=>{"use strict";df.differenceInCalendarISOWeekYears=hO;var lO=P(),ff=U();function hO(e,r,t){let[n,u]=(0,lO.normalizeDates)(t?.in,e,r);return(0,ff.getISOWeekYear)(n,t)-(0,ff.getISOWeekYear)(u,t)}});var mf=s(_f=>{"use strict";_f.differenceInCalendarISOWeeks=bO;var lf=R(),_O=P(),mO=O(),hf=L();function bO(e,r,t){let[n,u]=(0,_O.normalizeDates)(t?.in,e,r),a=(0,hf.startOfISOWeek)(n),o=(0,hf.startOfISOWeek)(u),c=+a-(0,lf.getTimezoneOffsetInMilliseconds)(a),f=+o-(0,lf.getTimezoneOffsetInMilliseconds)(o);return Math.round((c-f)/mO.millisecondsInWeek)}});var Ge=s(bf=>{"use strict";bf.differenceInCalendarMonths=vO;var gO=P();function vO(e,r,t){let[n,u]=(0,gO.normalizeDates)(t?.in,e,r),a=n.getFullYear()-u.getFullYear(),o=n.getMonth()-u.getMonth();return a*12+o}});var Qr=s(gf=>{"use strict";gf.getQuarter=OO;var xO=l();function OO(e,r){let t=(0,xO.toDate)(e,r?.in);return Math.trunc(t.getMonth()/3)+1}});var Rr=s(xf=>{"use strict";xf.differenceInCalendarQuarters=pO;var qO=P(),vf=Qr();function pO(e,r,t){let[n,u]=(0,qO.normalizeDates)(t?.in,e,r),a=n.getFullYear()-u.getFullYear(),o=(0,vf.getQuarter)(n)-(0,vf.getQuarter)(u);return a*4+o}});var Ue=s(pf=>{"use strict";pf.differenceInCalendarWeeks=wO;var Of=R(),MO=P(),DO=O(),qf=N();function wO(e,r,t){let[n,u]=(0,MO.normalizeDates)(t?.in,e,r),a=(0,qf.startOfWeek)(n,t),o=(0,qf.startOfWeek)(u,t),c=+a-(0,Of.getTimezoneOffsetInMilliseconds)(a),f=+o-(0,Of.getTimezoneOffsetInMilliseconds)(o);return Math.round((c-f)/DO.millisecondsInWeek)}});var Je=s(Mf=>{"use strict";Mf.differenceInCalendarYears=jO;var PO=P();function jO(e,r,t){let[n,u]=(0,PO.normalizeDates)(t?.in,e,r);return n.getFullYear()-u.getFullYear()}});var Ke=s(wf=>{"use strict";wf.differenceInDays=EO;var IO=P(),TO=A();function EO(e,r,t){let[n,u]=(0,IO.normalizeDates)(t?.in,e,r),a=Df(n,u),o=Math.abs((0,TO.differenceInCalendarDays)(n,u));n.setDate(n.getDate()-a*o);let c=+(Df(n,u)===-a),f=a*(o-c);return f===0?0:f}function Df(e,r){let t=e.getFullYear()-r.getFullYear()||e.getMonth()-r.getMonth()||e.getDate()-r.getDate()||e.getHours()-r.getHours()||e.getMinutes()-r.getMinutes()||e.getSeconds()-r.getSeconds()||e.getMilliseconds()-r.getMilliseconds();return t<0?-1:t>0?1:t}});var Z=s(Pf=>{"use strict";Pf.getRoundingMethod=YO;function YO(e){return r=>{let n=(e?Math[e]:Math.trunc)(r);return n===0?0:n}}});var ye=s(jf=>{"use strict";jf.differenceInHours=NO;var WO=Z(),SO=P(),FO=O();function NO(e,r,t){let[n,u]=(0,SO.normalizeDates)(t?.in,e,r),a=(+n-+u)/FO.millisecondsInHour;return(0,WO.getRoundingMethod)(t?.roundingMethod)(a)}});var Ar=s(If=>{"use strict";If.subISOWeekYears=LO;var HO=Sr();function LO(e,r,t){return(0,HO.addISOWeekYears)(e,-r,t)}});var Yf=s(Ef=>{"use strict";Ef.differenceInISOWeekYears=QO;var CO=P(),Tf=re(),zO=Br(),BO=Ar();function QO(e,r,t){let[n,u]=(0,CO.normalizeDates)(t?.in,e,r),a=(0,Tf.compareAsc)(n,u),o=Math.abs((0,zO.differenceInCalendarISOWeekYears)(n,u,t)),c=(0,BO.subISOWeekYears)(n,a*o,t),f=+((0,Tf.compareAsc)(c,u)===-a),d=a*(o-f);return d===0?0:d}});var ke=s(Sf=>{"use strict";Sf.differenceInMilliseconds=RO;var Wf=l();function RO(e,r){return+(0,Wf.toDate)(e)-+(0,Wf.toDate)(r)}});var er=s(Ff=>{"use strict";Ff.differenceInMinutes=XO;var AO=Z(),$O=O(),ZO=ke();function XO(e,r,t){let n=(0,ZO.differenceInMilliseconds)(e,r)/$O.millisecondsInMinute;return(0,AO.getRoundingMethod)(t?.roundingMethod)(n)}});var rr=s(Nf=>{"use strict";Nf.endOfDay=GO;var VO=l();function GO(e,r){let t=(0,VO.toDate)(e,r?.in);return t.setHours(23,59,59,999),t}});var tr=s(Hf=>{"use strict";Hf.endOfMonth=JO;var UO=l();function JO(e,r){let t=(0,UO.toDate)(e,r?.in),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}});var $r=s(Lf=>{"use strict";Lf.isLastDayOfMonth=eq;var KO=rr(),yO=tr(),kO=l();function eq(e,r){let t=(0,kO.toDate)(e,r?.in);return+(0,KO.endOfDay)(t,r)==+(0,yO.endOfMonth)(t,r)}});var Oe=s(Cf=>{"use strict";Cf.differenceInMonths=iq;var rq=P(),Zr=re(),tq=Ge(),nq=$r();function iq(e,r,t){let[n,u,a]=(0,rq.normalizeDates)(t?.in,e,e,r),o=(0,Zr.compareAsc)(u,a),c=Math.abs((0,tq.differenceInCalendarMonths)(u,a));if(c<1)return 0;u.getMonth()===1&&u.getDate()>27&&u.setDate(30),u.setMonth(u.getMonth()-o*c);let f=(0,Zr.compareAsc)(u,a)===-o;(0,nq.isLastDayOfMonth)(n)&&c===1&&(0,Zr.compareAsc)(n,a)===1&&(f=!1);let d=o*(c-+f);return d===0?0:d}});var Bf=s(zf=>{"use strict";zf.differenceInQuarters=sq;var uq=Z(),aq=Oe();function sq(e,r,t){let n=(0,aq.differenceInMonths)(e,r,t)/3;return(0,uq.getRoundingMethod)(t?.roundingMethod)(n)}});var qe=s(Qf=>{"use strict";Qf.differenceInSeconds=fq;var oq=Z(),cq=ke();function fq(e,r,t){let n=(0,cq.differenceInMilliseconds)(e,r)/1e3;return(0,oq.getRoundingMethod)(t?.roundingMethod)(n)}});var Af=s(Rf=>{"use strict";Rf.differenceInWeeks=hq;var dq=Z(),lq=Ke();function hq(e,r,t){let n=(0,lq.differenceInDays)(e,r,t)/7;return(0,dq.getRoundingMethod)(t?.roundingMethod)(n)}});var Xr=s(Zf=>{"use strict";Zf.differenceInYears=bq;var _q=P(),$f=re(),mq=Je();function bq(e,r,t){let[n,u]=(0,_q.normalizeDates)(t?.in,e,r),a=(0,$f.compareAsc)(n,u),o=Math.abs((0,mq.differenceInCalendarYears)(n,u));n.setFullYear(1584),u.setFullYear(1584);let c=(0,$f.compareAsc)(n,u)===-a,f=a*(o-+c);return f===0?0:f}});var C=s(Xf=>{"use strict";Xf.normalizeInterval=vq;var gq=P();function vq(e,r){let[t,n]=(0,gq.normalizeDates)(e,r.start,r.end);return{start:t,end:n}}});var Vr=s(Vf=>{"use strict";Vf.eachDayOfInterval=qq;var xq=C(),Oq=b();function qq(e,r){let{start:t,end:n}=(0,xq.normalizeInterval)(r?.in,e),u=+t>+n,a=u?+t:+n,o=u?n:t;o.setHours(0,0,0,0);let c=r?.step??1;if(!c)return[];c<0&&(c=-c,u=!u);let f=[];for(;+o<=a;)f.push((0,Oq.constructFrom)(t,o)),o.setDate(o.getDate()+c),o.setHours(0,0,0,0);return u?f.reverse():f}});var Uf=s(Gf=>{"use strict";Gf.eachHourOfInterval=Dq;var pq=C(),Mq=b();function Dq(e,r){let{start:t,end:n}=(0,pq.normalizeInterval)(r?.in,e),u=+t>+n,a=u?+t:+n,o=u?n:t;o.setMinutes(0,0,0);let c=r?.step??1;if(!c)return[];c<0&&(c=-c,u=!u);let f=[];for(;+o<=a;)f.push((0,Mq.constructFrom)(t,o)),o.setHours(o.getHours()+c);return u?f.reverse():f}});var Kf=s(Jf=>{"use strict";Jf.eachMinuteOfInterval=Iq;var wq=C(),Pq=Ze(),jq=b();function Iq(e,r){let{start:t,end:n}=(0,wq.normalizeInterval)(r?.in,e);t.setSeconds(0,0);let u=+t>+n,a=u?+t:+n,o=u?n:t,c=r?.step??1;if(!c)return[];c<0&&(c=-c,u=!u);let f=[];for(;+o<=a;)f.push((0,jq.constructFrom)(t,o)),o=(0,Pq.addMinutes)(o,c);return u?f.reverse():f}});var kf=s(yf=>{"use strict";yf.eachMonthOfInterval=Yq;var Tq=C(),Eq=b();function Yq(e,r){let{start:t,end:n}=(0,Tq.normalizeInterval)(r?.in,e),u=+t>+n,a=u?+t:+n,o=u?n:t;o.setHours(0,0,0,0),o.setDate(1);let c=r?.step??1;if(!c)return[];c<0&&(c=-c,u=!u);let f=[];for(;+o<=a;)f.push((0,Eq.constructFrom)(t,o)),o.setMonth(o.getMonth()+c);return u?f.reverse():f}});var nr=s(ed=>{"use strict";ed.startOfQuarter=Sq;var Wq=l();function Sq(e,r){let t=(0,Wq.toDate)(e,r?.in),n=t.getMonth(),u=n-n%3;return t.setMonth(u,1),t.setHours(0,0,0,0),t}});var td=s(rd=>{"use strict";rd.eachQuarterOfInterval=Lq;var Fq=C(),Nq=Xe(),Hq=b(),ir=nr();function Lq(e,r){let{start:t,end:n}=(0,Fq.normalizeInterval)(r?.in,e),u=+t>+n,a=u?+(0,ir.startOfQuarter)(t):+(0,ir.startOfQuarter)(n),o=u?(0,ir.startOfQuarter)(n):(0,ir.startOfQuarter)(t),c=r?.step??1;if(!c)return[];c<0&&(c=-c,u=!u);let f=[];for(;+o<=a;)f.push((0,Hq.constructFrom)(t,o)),o=(0,Nq.addQuarters)(o,c);return u?f.reverse():f}});var id=s(nd=>{"use strict";nd.eachWeekOfInterval=Qq;var Cq=C(),zq=xe(),Bq=b(),ur=N();function Qq(e,r){let{start:t,end:n}=(0,Cq.normalizeInterval)(r?.in,e),u=+t>+n,a=u?(0,ur.startOfWeek)(n,r):(0,ur.startOfWeek)(t,r),o=u?(0,ur.startOfWeek)(t,r):(0,ur.startOfWeek)(n,r);a.setHours(15),o.setHours(15);let c=+o.getTime(),f=a,d=r?.step??1;if(!d)return[];d<0&&(d=-d,u=!u);let h=[];for(;+f<=c;)f.setHours(0),h.push((0,Bq.constructFrom)(t,f)),f=(0,zq.addWeeks)(f,d),f.setHours(15);return u?h.reverse():h}});var ar=s(ud=>{"use strict";ud.eachWeekendOfInterval=Xq;var Rq=C(),Aq=b(),$q=Vr(),Zq=be();function Xq(e,r){let{start:t,end:n}=(0,Rq.normalizeInterval)(r?.in,e),u=(0,$q.eachDayOfInterval)({start:t,end:n},r),a=[],o=0;for(;o{"use strict";ad.startOfMonth=Gq;var Vq=l();function Gq(e,r){let t=(0,Vq.toDate)(e,r?.in);return t.setDate(1),t.setHours(0,0,0,0),t}});var od=s(sd=>{"use strict";sd.eachWeekendOfMonth=yq;var Uq=ar(),Jq=tr(),Kq=pe();function yq(e,r){let t=(0,Kq.startOfMonth)(e,r),n=(0,Jq.endOfMonth)(e,r);return(0,Uq.eachWeekendOfInterval)({start:t,end:n},r)}});var Gr=s(cd=>{"use strict";cd.endOfYear=ep;var kq=l();function ep(e,r){let t=(0,kq.toDate)(e,r?.in),n=t.getFullYear();return t.setFullYear(n+1,0,0),t.setHours(23,59,59,999),t}});var sr=s(fd=>{"use strict";fd.startOfYear=tp;var rp=l();function tp(e,r){let t=(0,rp.toDate)(e,r?.in);return t.setFullYear(t.getFullYear(),0,1),t.setHours(0,0,0,0),t}});var ld=s(dd=>{"use strict";dd.eachWeekendOfYear=ap;var np=ar(),ip=Gr(),up=sr();function ap(e,r){let t=(0,up.startOfYear)(e,r),n=(0,ip.endOfYear)(e,r);return(0,np.eachWeekendOfInterval)({start:t,end:n},r)}});var _d=s(hd=>{"use strict";hd.eachYearOfInterval=cp;var sp=C(),op=b();function cp(e,r){let{start:t,end:n}=(0,sp.normalizeInterval)(r?.in,e),u=+t>+n,a=u?+t:+n,o=u?n:t;o.setHours(0,0,0,0),o.setMonth(0,1);let c=r?.step??1;if(!c)return[];c<0&&(c=-c,u=!u);let f=[];for(;+o<=a;)f.push((0,op.constructFrom)(t,o)),o.setFullYear(o.getFullYear()+c);return u?f.reverse():f}});var bd=s(md=>{"use strict";md.endOfDecade=dp;var fp=l();function dp(e,r){let t=(0,fp.toDate)(e,r?.in),n=t.getFullYear(),u=9+Math.floor(n/10)*10;return t.setFullYear(u,11,31),t.setHours(23,59,59,999),t}});var vd=s(gd=>{"use strict";gd.endOfHour=hp;var lp=l();function hp(e,r){let t=(0,lp.toDate)(e,r?.in);return t.setMinutes(59,59,999),t}});var Ur=s(xd=>{"use strict";xd.endOfWeek=bp;var _p=Y(),mp=l();function bp(e,r){let t=(0,_p.getDefaultOptions)(),n=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,u=(0,mp.toDate)(e,r?.in),a=u.getDay(),o=(a{"use strict";Od.endOfISOWeek=vp;var gp=Ur();function vp(e,r){return(0,gp.endOfWeek)(e,{...r,weekStartsOn:1})}});var Md=s(pd=>{"use strict";pd.endOfISOWeekYear=pp;var xp=b(),Op=U(),qp=L();function pp(e,r){let t=(0,Op.getISOWeekYear)(e,r),n=(0,xp.constructFrom)(r?.in||e,0);n.setFullYear(t+1,0,4),n.setHours(0,0,0,0);let u=(0,qp.startOfISOWeek)(n,r);return u.setMilliseconds(u.getMilliseconds()-1),u}});var wd=s(Dd=>{"use strict";Dd.endOfMinute=Dp;var Mp=l();function Dp(e,r){let t=(0,Mp.toDate)(e,r?.in);return t.setSeconds(59,999),t}});var jd=s(Pd=>{"use strict";Pd.endOfQuarter=Pp;var wp=l();function Pp(e,r){let t=(0,wp.toDate)(e,r?.in),n=t.getMonth(),u=n-n%3+3;return t.setMonth(u,0),t.setHours(23,59,59,999),t}});var Td=s(Id=>{"use strict";Id.endOfSecond=Ip;var jp=l();function Ip(e,r){let t=(0,jp.toDate)(e,r?.in);return t.setMilliseconds(999),t}});var Yd=s(Ed=>{"use strict";Ed.endOfToday=Ep;var Tp=rr();function Ep(e){return(0,Tp.endOfDay)(Date.now(),e)}});var Fd=s(Sd=>{"use strict";Sd.endOfTomorrow=Yp;var Wd=T();function Yp(e){let r=(0,Wd.constructNow)(e?.in),t=r.getFullYear(),n=r.getMonth(),u=r.getDate(),a=(0,Wd.constructNow)(e?.in);return a.setFullYear(t,n,u+1),a.setHours(23,59,59,999),e?.in?e.in(a):a}});var Hd=s(Nd=>{"use strict";Nd.endOfYesterday=Fp;var Wp=b(),Sp=T();function Fp(e){let r=(0,Sp.constructNow)(e?.in),t=(0,Wp.constructFrom)(e?.in,0);return t.setFullYear(r.getFullYear(),r.getMonth(),r.getDate()-1),t.setHours(23,59,59,999),t}});var Ld=s(Jr=>{"use strict";Jr.formatDistance=void 0;var Np={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},Hp=(e,r,t)=>{let n,u=Np[e];return typeof u=="string"?n=u:r===1?n=u.one:n=u.other.replace("{{count}}",r.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"in "+n:n+" ago":n};Jr.formatDistance=Hp});var zd=s(Cd=>{"use strict";Cd.buildFormatLongFn=Lp;function Lp(e){return(r={})=>{let t=r.width?String(r.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}});var Bd=s(yr=>{"use strict";yr.formatLong=void 0;var Kr=zd(),Cp={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},zp={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},Bp={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},NF=yr.formatLong={date:(0,Kr.buildFormatLongFn)({formats:Cp,defaultWidth:"full"}),time:(0,Kr.buildFormatLongFn)({formats:zp,defaultWidth:"full"}),dateTime:(0,Kr.buildFormatLongFn)({formats:Bp,defaultWidth:"full"})}});var Qd=s(kr=>{"use strict";kr.formatRelative=void 0;var Qp={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Rp=(e,r,t,n)=>Qp[e];kr.formatRelative=Rp});var Ad=s(Rd=>{"use strict";Rd.buildLocalizeFn=Ap;function Ap(e){return(r,t)=>{let n=t?.context?String(t.context):"standalone",u;if(n==="formatting"&&e.formattingValues){let o=e.defaultFormattingWidth||e.defaultWidth,c=t?.width?String(t.width):o;u=e.formattingValues[c]||e.formattingValues[o]}else{let o=e.defaultWidth,c=t?.width?String(t.width):e.defaultWidth;u=e.values[c]||e.values[o]}let a=e.argumentCallback?e.argumentCallback(r):r;return u[a]}}});var $d=s(et=>{"use strict";et.localize=void 0;var Me=Ad(),$p={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},Zp={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},Xp={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},Vp={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},Gp={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},Up={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},Jp=(e,r)=>{let t=Number(e),n=t%100;if(n>20||n<10)switch(n%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},zF=et.localize={ordinalNumber:Jp,era:(0,Me.buildLocalizeFn)({values:$p,defaultWidth:"wide"}),quarter:(0,Me.buildLocalizeFn)({values:Zp,defaultWidth:"wide",argumentCallback:e=>e-1}),month:(0,Me.buildLocalizeFn)({values:Xp,defaultWidth:"wide"}),day:(0,Me.buildLocalizeFn)({values:Vp,defaultWidth:"wide"}),dayPeriod:(0,Me.buildLocalizeFn)({values:Gp,defaultWidth:"wide",formattingValues:Up,defaultFormattingWidth:"wide"})}});var Xd=s(Zd=>{"use strict";Zd.buildMatchFn=Kp;function Kp(e){return(r,t={})=>{let n=t.width,u=n&&e.matchPatterns[n]||e.matchPatterns[e.defaultMatchWidth],a=r.match(u);if(!a)return null;let o=a[0],c=n&&e.parsePatterns[n]||e.parsePatterns[e.defaultParseWidth],f=Array.isArray(c)?kp(c,_=>_.test(o)):yp(c,_=>_.test(o)),d;d=e.valueCallback?e.valueCallback(f):f,d=t.valueCallback?t.valueCallback(d):d;let h=r.slice(o.length);return{value:d,rest:h}}}function yp(e,r){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&r(e[t]))return t}function kp(e,r){for(let t=0;t{"use strict";Vd.buildMatchPatternFn=eM;function eM(e){return(r,t={})=>{let n=r.match(e.matchPattern);if(!n)return null;let u=n[0],a=r.match(e.parsePattern);if(!a)return null;let o=e.valueCallback?e.valueCallback(a[0]):a[0];o=t.valueCallback?t.valueCallback(o):o;let c=r.slice(u.length);return{value:o,rest:c}}}});var Ud=s(rt=>{"use strict";rt.match=void 0;var De=Xd(),rM=Gd(),tM=/^(\d+)(th|st|nd|rd)?/i,nM=/\d+/i,iM={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},uM={any:[/^b/i,/^(a|c)/i]},aM={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},sM={any:[/1/i,/2/i,/3/i,/4/i]},oM={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},cM={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},fM={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},dM={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},lM={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},hM={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},AF=rt.match={ordinalNumber:(0,rM.buildMatchPatternFn)({matchPattern:tM,parsePattern:nM,valueCallback:e=>parseInt(e,10)}),era:(0,De.buildMatchFn)({matchPatterns:iM,defaultMatchWidth:"wide",parsePatterns:uM,defaultParseWidth:"any"}),quarter:(0,De.buildMatchFn)({matchPatterns:aM,defaultMatchWidth:"wide",parsePatterns:sM,defaultParseWidth:"any",valueCallback:e=>e+1}),month:(0,De.buildMatchFn)({matchPatterns:oM,defaultMatchWidth:"wide",parsePatterns:cM,defaultParseWidth:"any"}),day:(0,De.buildMatchFn)({matchPatterns:fM,defaultMatchWidth:"wide",parsePatterns:dM,defaultParseWidth:"any"}),dayPeriod:(0,De.buildMatchFn)({matchPatterns:lM,defaultMatchWidth:"any",parsePatterns:hM,defaultParseWidth:"any"})}});var Jd=s(tt=>{"use strict";tt.enUS=void 0;var _M=Ld(),mM=Bd(),bM=Qd(),gM=$d(),vM=Ud(),ZF=tt.enUS={code:"en-US",formatDistance:_M.formatDistance,formatLong:mM.formatLong,formatRelative:bM.formatRelative,localize:gM.localize,match:vM.match,options:{weekStartsOn:0,firstWeekContainsDate:1}}});var te=s(Kd=>{"use strict";Object.defineProperty(Kd,"defaultLocale",{enumerable:!0,get:function(){return xM.enUS}});var xM=Jd()});var nt=s(yd=>{"use strict";yd.getDayOfYear=MM;var OM=A(),qM=sr(),pM=l();function MM(e,r){let t=(0,pM.toDate)(e,r?.in);return(0,OM.differenceInCalendarDays)(t,(0,qM.startOfYear)(t))+1}});var or=s(kd=>{"use strict";kd.getISOWeek=IM;var DM=O(),wM=L(),PM=oe(),jM=l();function IM(e,r){let t=(0,jM.toDate)(e,r?.in),n=+(0,wM.startOfISOWeek)(t)-+(0,PM.startOfISOWeekYear)(t);return Math.round(n/DM.millisecondsInWeek)+1}});var we=s(tl=>{"use strict";tl.getWeekYear=YM;var TM=Y(),el=b(),rl=N(),EM=l();function YM(e,r){let t=(0,EM.toDate)(e,r?.in),n=t.getFullYear(),u=(0,TM.getDefaultOptions)(),a=r?.firstWeekContainsDate??r?.locale?.options?.firstWeekContainsDate??u.firstWeekContainsDate??u.locale?.options?.firstWeekContainsDate??1,o=(0,el.constructFrom)(r?.in||e,0);o.setFullYear(n+1,0,a),o.setHours(0,0,0,0);let c=(0,rl.startOfWeek)(o,r),f=(0,el.constructFrom)(r?.in||e,0);f.setFullYear(n,0,a),f.setHours(0,0,0,0);let d=(0,rl.startOfWeek)(f,r);return+t>=+c?n+1:+t>=+d?n:n-1}});var cr=s(nl=>{"use strict";nl.startOfWeekYear=HM;var WM=Y(),SM=b(),FM=we(),NM=N();function HM(e,r){let t=(0,WM.getDefaultOptions)(),n=r?.firstWeekContainsDate??r?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,u=(0,FM.getWeekYear)(e,r),a=(0,SM.constructFrom)(r?.in||e,0);return a.setFullYear(u,0,n),a.setHours(0,0,0,0),(0,NM.startOfWeek)(a,r)}});var fr=s(il=>{"use strict";il.getWeek=QM;var LM=O(),CM=N(),zM=cr(),BM=l();function QM(e,r){let t=(0,BM.toDate)(e,r?.in),n=+(0,CM.startOfWeek)(t,r)-+(0,zM.startOfWeekYear)(t,r);return Math.round(n/LM.millisecondsInWeek)+1}});var ne=s(ul=>{"use strict";ul.addLeadingZeros=RM;function RM(e,r){let t=e<0?"-":"",n=Math.abs(e).toString().padStart(r,"0");return t+n}});var ut=s(it=>{"use strict";it.lightFormatters=void 0;var J=ne(),eN=it.lightFormatters={y(e,r){let t=e.getFullYear(),n=t>0?t:1-t;return(0,J.addLeadingZeros)(r==="yy"?n%100:n,r.length)},M(e,r){let t=e.getMonth();return r==="M"?String(t+1):(0,J.addLeadingZeros)(t+1,2)},d(e,r){return(0,J.addLeadingZeros)(e.getDate(),r.length)},a(e,r){let t=e.getHours()/12>=1?"pm":"am";switch(r){case"a":case"aa":return t.toUpperCase();case"aaa":return t;case"aaaaa":return t[0];case"aaaa":default:return t==="am"?"a.m.":"p.m."}},h(e,r){return(0,J.addLeadingZeros)(e.getHours()%12||12,r.length)},H(e,r){return(0,J.addLeadingZeros)(e.getHours(),r.length)},m(e,r){return(0,J.addLeadingZeros)(e.getMinutes(),r.length)},s(e,r){return(0,J.addLeadingZeros)(e.getSeconds(),r.length)},S(e,r){let t=r.length,n=e.getMilliseconds(),u=Math.trunc(n*Math.pow(10,t-3));return(0,J.addLeadingZeros)(u,r.length)}}});var ol=s(at=>{"use strict";at.formatters=void 0;var AM=nt(),$M=or(),ZM=U(),XM=fr(),VM=we(),I=ne(),K=ut(),fe={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},tN=at.formatters={G:function(e,r,t){let n=e.getFullYear()>0?1:0;switch(r){case"G":case"GG":case"GGG":return t.era(n,{width:"abbreviated"});case"GGGGG":return t.era(n,{width:"narrow"});case"GGGG":default:return t.era(n,{width:"wide"})}},y:function(e,r,t){if(r==="yo"){let n=e.getFullYear(),u=n>0?n:1-n;return t.ordinalNumber(u,{unit:"year"})}return K.lightFormatters.y(e,r)},Y:function(e,r,t,n){let u=(0,VM.getWeekYear)(e,n),a=u>0?u:1-u;if(r==="YY"){let o=a%100;return(0,I.addLeadingZeros)(o,2)}return r==="Yo"?t.ordinalNumber(a,{unit:"year"}):(0,I.addLeadingZeros)(a,r.length)},R:function(e,r){let t=(0,ZM.getISOWeekYear)(e);return(0,I.addLeadingZeros)(t,r.length)},u:function(e,r){let t=e.getFullYear();return(0,I.addLeadingZeros)(t,r.length)},Q:function(e,r,t){let n=Math.ceil((e.getMonth()+1)/3);switch(r){case"Q":return String(n);case"QQ":return(0,I.addLeadingZeros)(n,2);case"Qo":return t.ordinalNumber(n,{unit:"quarter"});case"QQQ":return t.quarter(n,{width:"abbreviated",context:"formatting"});case"QQQQQ":return t.quarter(n,{width:"narrow",context:"formatting"});case"QQQQ":default:return t.quarter(n,{width:"wide",context:"formatting"})}},q:function(e,r,t){let n=Math.ceil((e.getMonth()+1)/3);switch(r){case"q":return String(n);case"qq":return(0,I.addLeadingZeros)(n,2);case"qo":return t.ordinalNumber(n,{unit:"quarter"});case"qqq":return t.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return t.quarter(n,{width:"wide",context:"standalone"})}},M:function(e,r,t){let n=e.getMonth();switch(r){case"M":case"MM":return K.lightFormatters.M(e,r);case"Mo":return t.ordinalNumber(n+1,{unit:"month"});case"MMM":return t.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return t.month(n,{width:"wide",context:"formatting"})}},L:function(e,r,t){let n=e.getMonth();switch(r){case"L":return String(n+1);case"LL":return(0,I.addLeadingZeros)(n+1,2);case"Lo":return t.ordinalNumber(n+1,{unit:"month"});case"LLL":return t.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return t.month(n,{width:"wide",context:"standalone"})}},w:function(e,r,t,n){let u=(0,XM.getWeek)(e,n);return r==="wo"?t.ordinalNumber(u,{unit:"week"}):(0,I.addLeadingZeros)(u,r.length)},I:function(e,r,t){let n=(0,$M.getISOWeek)(e);return r==="Io"?t.ordinalNumber(n,{unit:"week"}):(0,I.addLeadingZeros)(n,r.length)},d:function(e,r,t){return r==="do"?t.ordinalNumber(e.getDate(),{unit:"date"}):K.lightFormatters.d(e,r)},D:function(e,r,t){let n=(0,AM.getDayOfYear)(e);return r==="Do"?t.ordinalNumber(n,{unit:"dayOfYear"}):(0,I.addLeadingZeros)(n,r.length)},E:function(e,r,t){let n=e.getDay();switch(r){case"E":case"EE":case"EEE":return t.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(n,{width:"short",context:"formatting"});case"EEEE":default:return t.day(n,{width:"wide",context:"formatting"})}},e:function(e,r,t,n){let u=e.getDay(),a=(u-n.weekStartsOn+8)%7||7;switch(r){case"e":return String(a);case"ee":return(0,I.addLeadingZeros)(a,2);case"eo":return t.ordinalNumber(a,{unit:"day"});case"eee":return t.day(u,{width:"abbreviated",context:"formatting"});case"eeeee":return t.day(u,{width:"narrow",context:"formatting"});case"eeeeee":return t.day(u,{width:"short",context:"formatting"});case"eeee":default:return t.day(u,{width:"wide",context:"formatting"})}},c:function(e,r,t,n){let u=e.getDay(),a=(u-n.weekStartsOn+8)%7||7;switch(r){case"c":return String(a);case"cc":return(0,I.addLeadingZeros)(a,r.length);case"co":return t.ordinalNumber(a,{unit:"day"});case"ccc":return t.day(u,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(u,{width:"narrow",context:"standalone"});case"cccccc":return t.day(u,{width:"short",context:"standalone"});case"cccc":default:return t.day(u,{width:"wide",context:"standalone"})}},i:function(e,r,t){let n=e.getDay(),u=n===0?7:n;switch(r){case"i":return String(u);case"ii":return(0,I.addLeadingZeros)(u,r.length);case"io":return t.ordinalNumber(u,{unit:"day"});case"iii":return t.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return t.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return t.day(n,{width:"short",context:"formatting"});case"iiii":default:return t.day(n,{width:"wide",context:"formatting"})}},a:function(e,r,t){let u=e.getHours()/12>=1?"pm":"am";switch(r){case"a":case"aa":return t.dayPeriod(u,{width:"abbreviated",context:"formatting"});case"aaa":return t.dayPeriod(u,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return t.dayPeriod(u,{width:"narrow",context:"formatting"});case"aaaa":default:return t.dayPeriod(u,{width:"wide",context:"formatting"})}},b:function(e,r,t){let n=e.getHours(),u;switch(n===12?u=fe.noon:n===0?u=fe.midnight:u=n/12>=1?"pm":"am",r){case"b":case"bb":return t.dayPeriod(u,{width:"abbreviated",context:"formatting"});case"bbb":return t.dayPeriod(u,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return t.dayPeriod(u,{width:"narrow",context:"formatting"});case"bbbb":default:return t.dayPeriod(u,{width:"wide",context:"formatting"})}},B:function(e,r,t){let n=e.getHours(),u;switch(n>=17?u=fe.evening:n>=12?u=fe.afternoon:n>=4?u=fe.morning:u=fe.night,r){case"B":case"BB":case"BBB":return t.dayPeriod(u,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(u,{width:"narrow",context:"formatting"});case"BBBB":default:return t.dayPeriod(u,{width:"wide",context:"formatting"})}},h:function(e,r,t){if(r==="ho"){let n=e.getHours()%12;return n===0&&(n=12),t.ordinalNumber(n,{unit:"hour"})}return K.lightFormatters.h(e,r)},H:function(e,r,t){return r==="Ho"?t.ordinalNumber(e.getHours(),{unit:"hour"}):K.lightFormatters.H(e,r)},K:function(e,r,t){let n=e.getHours()%12;return r==="Ko"?t.ordinalNumber(n,{unit:"hour"}):(0,I.addLeadingZeros)(n,r.length)},k:function(e,r,t){let n=e.getHours();return n===0&&(n=24),r==="ko"?t.ordinalNumber(n,{unit:"hour"}):(0,I.addLeadingZeros)(n,r.length)},m:function(e,r,t){return r==="mo"?t.ordinalNumber(e.getMinutes(),{unit:"minute"}):K.lightFormatters.m(e,r)},s:function(e,r,t){return r==="so"?t.ordinalNumber(e.getSeconds(),{unit:"second"}):K.lightFormatters.s(e,r)},S:function(e,r){return K.lightFormatters.S(e,r)},X:function(e,r,t){let n=e.getTimezoneOffset();if(n===0)return"Z";switch(r){case"X":return sl(n);case"XXXX":case"XX":return ie(n);case"XXXXX":case"XXX":default:return ie(n,":")}},x:function(e,r,t){let n=e.getTimezoneOffset();switch(r){case"x":return sl(n);case"xxxx":case"xx":return ie(n);case"xxxxx":case"xxx":default:return ie(n,":")}},O:function(e,r,t){let n=e.getTimezoneOffset();switch(r){case"O":case"OO":case"OOO":return"GMT"+al(n,":");case"OOOO":default:return"GMT"+ie(n,":")}},z:function(e,r,t){let n=e.getTimezoneOffset();switch(r){case"z":case"zz":case"zzz":return"GMT"+al(n,":");case"zzzz":default:return"GMT"+ie(n,":")}},t:function(e,r,t){let n=Math.trunc(+e/1e3);return(0,I.addLeadingZeros)(n,r.length)},T:function(e,r,t){return(0,I.addLeadingZeros)(+e,r.length)}};function al(e,r=""){let t=e>0?"-":"+",n=Math.abs(e),u=Math.trunc(n/60),a=n%60;return a===0?t+String(u):t+String(u)+r+(0,I.addLeadingZeros)(a,2)}function sl(e,r){return e%60===0?(e>0?"-":"+")+(0,I.addLeadingZeros)(Math.abs(e)/60,2):ie(e,r)}function ie(e,r=""){let t=e>0?"-":"+",n=Math.abs(e),u=(0,I.addLeadingZeros)(Math.trunc(n/60),2),a=(0,I.addLeadingZeros)(n%60,2);return t+u+r+a}});var ot=s(st=>{"use strict";st.longFormatters=void 0;var cl=(e,r)=>{switch(e){case"P":return r.date({width:"short"});case"PP":return r.date({width:"medium"});case"PPP":return r.date({width:"long"});case"PPPP":default:return r.date({width:"full"})}},fl=(e,r)=>{switch(e){case"p":return r.time({width:"short"});case"pp":return r.time({width:"medium"});case"ppp":return r.time({width:"long"});case"pppp":default:return r.time({width:"full"})}},GM=(e,r)=>{let t=e.match(/(P+)(p+)?/)||[],n=t[1],u=t[2];if(!u)return cl(e,r);let a;switch(n){case"P":a=r.dateTime({width:"short"});break;case"PP":a=r.dateTime({width:"medium"});break;case"PPP":a=r.dateTime({width:"long"});break;case"PPPP":default:a=r.dateTime({width:"full"});break}return a.replace("{{date}}",cl(n,r)).replace("{{time}}",fl(u,r))},iN=st.longFormatters={p:fl,P:GM}});var ct=s(dr=>{"use strict";dr.isProtectedDayOfYearToken=yM;dr.isProtectedWeekYearToken=kM;dr.warnOrThrowProtectedError=eD;var UM=/^D+$/,JM=/^Y+$/,KM=["D","DD","YY","YYYY"];function yM(e){return UM.test(e)}function kM(e){return JM.test(e)}function eD(e,r,t){let n=rD(e,r,t);if(console.warn(n),KM.includes(e))throw new RangeError(n)}function rD(e,r,t){let n=e[0]==="Y"?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${r}\`) for formatting ${n} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}});var lt=s(Pe=>{"use strict";Pe.format=Pe.formatDate=dD;Object.defineProperty(Pe,"formatters",{enumerable:!0,get:function(){return dt.formatters}});Object.defineProperty(Pe,"longFormatters",{enumerable:!0,get:function(){return dl.longFormatters}});var tD=te(),nD=Y(),dt=ol(),dl=ot(),ft=ct(),iD=$(),uD=l(),aD=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,sD=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,oD=/^'([^]*?)'?$/,cD=/''/g,fD=/[a-zA-Z]/;function dD(e,r,t){let n=(0,nD.getDefaultOptions)(),u=t?.locale??n.locale??tD.defaultLocale,a=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,o=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??n.weekStartsOn??n.locale?.options?.weekStartsOn??0,c=(0,uD.toDate)(e,t?.in);if(!(0,iD.isValid)(c))throw new RangeError("Invalid time value");let f=r.match(sD).map(h=>{let _=h[0];if(_==="p"||_==="P"){let g=dl.longFormatters[_];return g(h,u.formatLong)}return h}).join("").match(aD).map(h=>{if(h==="''")return{isToken:!1,value:"'"};let _=h[0];if(_==="'")return{isToken:!1,value:lD(h)};if(dt.formatters[_])return{isToken:!0,value:h};if(_.match(fD))throw new RangeError("Format string contains an unescaped latin alphabet character `"+_+"`");return{isToken:!1,value:h}});u.localize.preprocessor&&(f=u.localize.preprocessor(c,f));let d={firstWeekContainsDate:a,weekStartsOn:o,locale:u};return f.map(h=>{if(!h.isToken)return h.value;let _=h.value;(!t?.useAdditionalWeekYearTokens&&(0,ft.isProtectedWeekYearToken)(_)||!t?.useAdditionalDayOfYearTokens&&(0,ft.isProtectedDayOfYearToken)(_))&&(0,ft.warnOrThrowProtectedError)(_,r,String(e));let g=dt.formatters[_[0]];return g(c,_,u.localize,d)}).join("")}function lD(e){let r=e.match(oD);return r?r[1].replace(cD,"'"):e}});var ht=s(hl=>{"use strict";hl.formatDistance=xD;var hD=te(),_D=Y(),ll=R(),mD=P(),bD=re(),de=O(),gD=Oe(),vD=qe();function xD(e,r,t){let n=(0,_D.getDefaultOptions)(),u=t?.locale??n.locale??hD.defaultLocale,a=2520,o=(0,bD.compareAsc)(e,r);if(isNaN(o))throw new RangeError("Invalid time value");let c=Object.assign({},t,{addSuffix:t?.addSuffix,comparison:o}),[f,d]=(0,mD.normalizeDates)(t?.in,...o>0?[r,e]:[e,r]),h=(0,vD.differenceInSeconds)(d,f),_=((0,ll.getTimezoneOffsetInMilliseconds)(d)-(0,ll.getTimezoneOffsetInMilliseconds)(f))/1e3,g=Math.round((h-_)/60),p;if(g<2)return t?.includeSeconds?h<5?u.formatDistance("lessThanXSeconds",5,c):h<10?u.formatDistance("lessThanXSeconds",10,c):h<20?u.formatDistance("lessThanXSeconds",20,c):h<40?u.formatDistance("halfAMinute",0,c):h<60?u.formatDistance("lessThanXMinutes",1,c):u.formatDistance("xMinutes",1,c):g===0?u.formatDistance("lessThanXMinutes",1,c):u.formatDistance("xMinutes",g,c);if(g<45)return u.formatDistance("xMinutes",g,c);if(g<90)return u.formatDistance("aboutXHours",1,c);if(g{"use strict";ml.formatDistanceStrict=wD;var OD=te(),qD=Y(),pD=Z(),_l=R(),MD=P(),DD=re(),y=O();function wD(e,r,t){let n=(0,qD.getDefaultOptions)(),u=t?.locale??n.locale??OD.defaultLocale,a=(0,DD.compareAsc)(e,r);if(isNaN(a))throw new RangeError("Invalid time value");let o=Object.assign({},t,{addSuffix:t?.addSuffix,comparison:a}),[c,f]=(0,MD.normalizeDates)(t?.in,...a>0?[r,e]:[e,r]),d=(0,pD.getRoundingMethod)(t?.roundingMethod??"round"),h=f.getTime()-c.getTime(),_=h/y.millisecondsInMinute,g=(0,_l.getTimezoneOffsetInMilliseconds)(f)-(0,_l.getTimezoneOffsetInMilliseconds)(c),p=(h-g)/y.millisecondsInMinute,q=t?.unit,x;if(q?x=q:_<1?x="second":_<60?x="minute":_{"use strict";bl.formatDistanceToNow=ID;var PD=T(),jD=ht();function ID(e,r){return(0,jD.formatDistance)(e,(0,PD.constructNow)(e),r)}});var xl=s(vl=>{"use strict";vl.formatDistanceToNowStrict=YD;var TD=T(),ED=_t();function YD(e,r){return(0,ED.formatDistanceStrict)(e,(0,TD.constructNow)(e),r)}});var ql=s(Ol=>{"use strict";Ol.formatDuration=ND;var WD=te(),SD=Y(),FD=["years","months","weeks","days","hours","minutes","seconds"];function ND(e,r){let t=(0,SD.getDefaultOptions)(),n=r?.locale??t.locale??WD.defaultLocale,u=r?.format??FD,a=r?.zero??!1,o=r?.delimiter??" ";return n.formatDistance?u.reduce((f,d)=>{let h=`x${d.replace(/(^.)/,g=>g.toUpperCase())}`,_=e[d];return _!==void 0&&(a||e[d])?f.concat(n.formatDistance(h,_)):f},[]).join(o):""}});var Ml=s(pl=>{"use strict";pl.formatISO=LD;var k=ne(),HD=l();function LD(e,r){let t=(0,HD.toDate)(e,r?.in);if(isNaN(+t))throw new RangeError("Invalid time value");let n=r?.format??"extended",u=r?.representation??"complete",a="",o="",c=n==="extended"?"-":"",f=n==="extended"?":":"";if(u!=="time"){let d=(0,k.addLeadingZeros)(t.getDate(),2),h=(0,k.addLeadingZeros)(t.getMonth()+1,2);a=`${(0,k.addLeadingZeros)(t.getFullYear(),4)}${c}${h}${c}${d}`}if(u!=="date"){let d=t.getTimezoneOffset();if(d!==0){let x=Math.abs(d),m=(0,k.addLeadingZeros)(Math.trunc(x/60),2),D=(0,k.addLeadingZeros)(x%60,2);o=`${d<0?"+":"-"}${m}:${D}`}else o="Z";let h=(0,k.addLeadingZeros)(t.getHours(),2),_=(0,k.addLeadingZeros)(t.getMinutes(),2),g=(0,k.addLeadingZeros)(t.getSeconds(),2),p=a===""?"":"T",q=[h,_,g].join(f);a=`${a}${p}${q}${o}`}return a}});var wl=s(Dl=>{"use strict";Dl.formatISO9075=BD;var le=ne(),CD=$(),zD=l();function BD(e,r){let t=(0,zD.toDate)(e,r?.in);if(!(0,CD.isValid)(t))throw new RangeError("Invalid time value");let n=r?.format??"extended",u=r?.representation??"complete",a="",o=n==="extended"?"-":"",c=n==="extended"?":":"";if(u!=="time"){let f=(0,le.addLeadingZeros)(t.getDate(),2),d=(0,le.addLeadingZeros)(t.getMonth()+1,2);a=`${(0,le.addLeadingZeros)(t.getFullYear(),4)}${o}${d}${o}${f}`}if(u!=="date"){let f=(0,le.addLeadingZeros)(t.getHours(),2),d=(0,le.addLeadingZeros)(t.getMinutes(),2),h=(0,le.addLeadingZeros)(t.getSeconds(),2);a=`${a}${a===""?"":" "}${f}${c}${d}${c}${h}`}return a}});var jl=s(Pl=>{"use strict";Pl.formatISODuration=QD;function QD(e){let{years:r=0,months:t=0,days:n=0,hours:u=0,minutes:a=0,seconds:o=0}=e;return`P${r}Y${t}M${n}DT${u}H${a}M${o}S`}});var Tl=s(Il=>{"use strict";Il.formatRFC3339=$D;var ee=ne(),RD=$(),AD=l();function $D(e,r){let t=(0,AD.toDate)(e,r?.in);if(!(0,RD.isValid)(t))throw new RangeError("Invalid time value");let n=r?.fractionDigits??0,u=(0,ee.addLeadingZeros)(t.getDate(),2),a=(0,ee.addLeadingZeros)(t.getMonth()+1,2),o=t.getFullYear(),c=(0,ee.addLeadingZeros)(t.getHours(),2),f=(0,ee.addLeadingZeros)(t.getMinutes(),2),d=(0,ee.addLeadingZeros)(t.getSeconds(),2),h="";if(n>0){let p=t.getMilliseconds(),q=Math.trunc(p*Math.pow(10,n-3));h="."+(0,ee.addLeadingZeros)(q,n)}let _="",g=t.getTimezoneOffset();if(g!==0){let p=Math.abs(g),q=(0,ee.addLeadingZeros)(Math.trunc(p/60),2),x=(0,ee.addLeadingZeros)(p%60,2);_=`${g<0?"+":"-"}${q}:${x}`}else _="Z";return`${o}-${a}-${u}T${c}:${f}:${d}${h}${_}`}});var Yl=s(El=>{"use strict";El.formatRFC7231=UD;var lr=ne(),ZD=$(),XD=l(),VD=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],GD=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function UD(e){let r=(0,XD.toDate)(e);if(!(0,ZD.isValid)(r))throw new RangeError("Invalid time value");let t=VD[r.getUTCDay()],n=(0,lr.addLeadingZeros)(r.getUTCDate(),2),u=GD[r.getUTCMonth()],a=r.getUTCFullYear(),o=(0,lr.addLeadingZeros)(r.getUTCHours(),2),c=(0,lr.addLeadingZeros)(r.getUTCMinutes(),2),f=(0,lr.addLeadingZeros)(r.getUTCSeconds(),2);return`${t}, ${n} ${u} ${a} ${o}:${c}:${f} GMT`}});var Sl=s(Wl=>{"use strict";Wl.formatRelative=rw;var JD=te(),KD=Y(),yD=P(),kD=A(),ew=lt();function rw(e,r,t){let[n,u]=(0,yD.normalizeDates)(t?.in,e,r),a=(0,KD.getDefaultOptions)(),o=t?.locale??a.locale??JD.defaultLocale,c=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??a.weekStartsOn??a.locale?.options?.weekStartsOn??0,f=(0,kD.differenceInCalendarDays)(n,u);if(isNaN(f))throw new RangeError("Invalid time value");let d;f<-6?d="other":f<-1?d="lastWeek":f<0?d="yesterday":f<1?d="today":f<2?d="tomorrow":f<7?d="nextWeek":d="other";let h=o.formatRelative(d,n,u,{locale:o,weekStartsOn:c});return(0,ew.format)(n,h,{locale:o,weekStartsOn:c})}});var Nl=s(Fl=>{"use strict";Fl.fromUnixTime=nw;var tw=l();function nw(e,r){return(0,tw.toDate)(e*1e3,r?.in)}});var mt=s(Hl=>{"use strict";Hl.getDate=uw;var iw=l();function uw(e,r){return(0,iw.toDate)(e,r?.in).getDate()}});var je=s(Ll=>{"use strict";Ll.getDay=sw;var aw=l();function sw(e,r){return(0,aw.toDate)(e,r?.in).getDay()}});var bt=s(Cl=>{"use strict";Cl.getDaysInMonth=fw;var ow=b(),cw=l();function fw(e,r){let t=(0,cw.toDate)(e,r?.in),n=t.getFullYear(),u=t.getMonth(),a=(0,ow.constructFrom)(t,0);return a.setFullYear(n,u+1,0),a.setHours(0,0,0,0),a.getDate()}});var gt=s(zl=>{"use strict";zl.isLeapYear=lw;var dw=l();function lw(e,r){let n=(0,dw.toDate)(e,r?.in).getFullYear();return n%400===0||n%4===0&&n%100!==0}});var Ql=s(Bl=>{"use strict";Bl.getDaysInYear=mw;var hw=gt(),_w=l();function mw(e,r){let t=(0,_w.toDate)(e,r?.in);return Number.isNaN(+t)?NaN:(0,hw.isLeapYear)(t)?366:365}});var Al=s(Rl=>{"use strict";Rl.getDecade=gw;var bw=l();function gw(e,r){let n=(0,bw.toDate)(e,r?.in).getFullYear();return Math.floor(n/10)*10}});var vt=s($l=>{"use strict";$l.getDefaultOptions=xw;var vw=Y();function xw(){return Object.assign({},(0,vw.getDefaultOptions)())}});var Xl=s(Zl=>{"use strict";Zl.getHours=qw;var Ow=l();function qw(e,r){return(0,Ow.toDate)(e,r?.in).getHours()}});var xt=s(Vl=>{"use strict";Vl.getISODay=Mw;var pw=l();function Mw(e,r){let t=(0,pw.toDate)(e,r?.in).getDay();return t===0?7:t}});var Jl=s(Ul=>{"use strict";Ul.getISOWeeksInYear=Pw;var Dw=xe(),ww=O(),Gl=oe();function Pw(e,r){let t=(0,Gl.startOfISOWeekYear)(e,r),u=+(0,Gl.startOfISOWeekYear)((0,Dw.addWeeks)(t,60))-+t;return Math.round(u/ww.millisecondsInWeek)}});var yl=s(Kl=>{"use strict";Kl.getMilliseconds=Iw;var jw=l();function Iw(e){return(0,jw.toDate)(e).getMilliseconds()}});var eh=s(kl=>{"use strict";kl.getMinutes=Ew;var Tw=l();function Ew(e,r){return(0,Tw.toDate)(e,r?.in).getMinutes()}});var th=s(rh=>{"use strict";rh.getMonth=Ww;var Yw=l();function Ww(e,r){return(0,Yw.toDate)(e,r?.in).getMonth()}});var uh=s(ih=>{"use strict";ih.getOverlappingDaysInIntervals=Fw;var nh=R(),Sw=O(),hr=l();function Fw(e,r){let[t,n]=[+(0,hr.toDate)(e.start),+(0,hr.toDate)(e.end)].sort((_,g)=>_-g),[u,a]=[+(0,hr.toDate)(r.start),+(0,hr.toDate)(r.end)].sort((_,g)=>_-g);if(!(tn?n:a,h=d-(0,nh.getTimezoneOffsetInMilliseconds)(d);return Math.ceil((h-f)/Sw.millisecondsInDay)}});var sh=s(ah=>{"use strict";ah.getSeconds=Hw;var Nw=l();function Hw(e){return(0,Nw.toDate)(e).getSeconds()}});var ch=s(oh=>{"use strict";oh.getTime=Cw;var Lw=l();function Cw(e){return+(0,Lw.toDate)(e)}});var dh=s(fh=>{"use strict";fh.getUnixTime=Bw;var zw=l();function Bw(e){return Math.trunc(+(0,zw.toDate)(e)/1e3)}});var hh=s(lh=>{"use strict";lh.getWeekOfMonth=Xw;var Qw=Y(),Rw=mt(),Aw=je(),$w=pe(),Zw=l();function Xw(e,r){let t=(0,Qw.getDefaultOptions)(),n=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,u=(0,Rw.getDate)((0,Zw.toDate)(e,r?.in));if(isNaN(u))return NaN;let a=(0,Aw.getDay)((0,$w.startOfMonth)(e,r)),o=n-a;o<=0&&(o+=7);let c=u-o;return Math.ceil(c/7)+1}});var Ot=s(mh=>{"use strict";mh.lastDayOfMonth=Vw;var _h=l();function Vw(e,r){let t=(0,_h.toDate)(e,r?.in),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(0,0,0,0),(0,_h.toDate)(t,r?.in)}});var gh=s(bh=>{"use strict";bh.getWeeksInMonth=yw;var Gw=Ue(),Uw=Ot(),Jw=pe(),Kw=l();function yw(e,r){let t=(0,Kw.toDate)(e,r?.in);return(0,Gw.differenceInCalendarWeeks)((0,Uw.lastDayOfMonth)(t,r),(0,Jw.startOfMonth)(t,r),r)+1}});var xh=s(vh=>{"use strict";vh.getYear=eP;var kw=l();function eP(e,r){return(0,kw.toDate)(e,r?.in).getFullYear()}});var qh=s(Oh=>{"use strict";Oh.hoursToMilliseconds=tP;var rP=O();function tP(e){return Math.trunc(e*rP.millisecondsInHour)}});var Mh=s(ph=>{"use strict";ph.hoursToMinutes=iP;var nP=O();function iP(e){return Math.trunc(e*nP.minutesInHour)}});var wh=s(Dh=>{"use strict";Dh.hoursToSeconds=aP;var uP=O();function aP(e){return Math.trunc(e*uP.secondsInHour)}});var jh=s(Ph=>{"use strict";Ph.interval=oP;var sP=P();function oP(e,r,t){let[n,u]=(0,sP.normalizeDates)(t?.in,e,r);if(isNaN(+n))throw new TypeError("Start date is invalid");if(isNaN(+u))throw new TypeError("End date is invalid");if(t?.assertPositive&&+n>+u)throw new TypeError("End date must be after start date");return{start:n,end:u}}});var Th=s(Ih=>{"use strict";Ih.intervalToDuration=bP;var cP=C(),Ie=wr(),fP=Ke(),dP=ye(),lP=er(),hP=Oe(),_P=qe(),mP=Xr();function bP(e,r){let{start:t,end:n}=(0,cP.normalizeInterval)(r?.in,e),u={},a=(0,mP.differenceInYears)(n,t);a&&(u.years=a);let o=(0,Ie.add)(t,{years:u.years}),c=(0,hP.differenceInMonths)(n,o);c&&(u.months=c);let f=(0,Ie.add)(o,{months:u.months}),d=(0,fP.differenceInDays)(n,f);d&&(u.days=d);let h=(0,Ie.add)(f,{days:u.days}),_=(0,dP.differenceInHours)(n,h);_&&(u.hours=_);let g=(0,Ie.add)(h,{hours:u.hours}),p=(0,lP.differenceInMinutes)(n,g);p&&(u.minutes=p);let q=(0,Ie.add)(g,{minutes:u.minutes}),x=(0,_P.differenceInSeconds)(n,q);return x&&(u.seconds=x),u}});var Yh=s(Eh=>{"use strict";Eh.intlFormat=vP;var gP=l();function vP(e,r,t){let n;return xP(r)?n=r:t=r,new Intl.DateTimeFormat(t?.locale,n).format((0,gP.toDate)(e))}function xP(e){return e!==void 0&&!("locale"in e)}});var Lh=s(Hh=>{"use strict";Hh.intlFormatDistance=qP;var OP=P(),ue=O(),qt=A(),Wh=Ge(),pt=Rr(),Sh=Ue(),Mt=Je(),Fh=ye(),Nh=er(),Dt=qe();function qP(e,r,t){let n=0,u,[a,o]=(0,OP.normalizeDates)(t?.in,e,r);if(t?.unit)u=t?.unit,u==="second"?n=(0,Dt.differenceInSeconds)(a,o):u==="minute"?n=(0,Nh.differenceInMinutes)(a,o):u==="hour"?n=(0,Fh.differenceInHours)(a,o):u==="day"?n=(0,qt.differenceInCalendarDays)(a,o):u==="week"?n=(0,Sh.differenceInCalendarWeeks)(a,o):u==="month"?n=(0,Wh.differenceInCalendarMonths)(a,o):u==="quarter"?n=(0,pt.differenceInCalendarQuarters)(a,o):u==="year"&&(n=(0,Mt.differenceInCalendarYears)(a,o));else{let f=(0,Dt.differenceInSeconds)(a,o);Math.abs(f){"use strict";zh.isAfter=pP;var Ch=l();function pP(e,r){return+(0,Ch.toDate)(e)>+(0,Ch.toDate)(r)}});var Ah=s(Rh=>{"use strict";Rh.isBefore=MP;var Qh=l();function MP(e,r){return+(0,Qh.toDate)(e)<+(0,Qh.toDate)(r)}});var Xh=s(Zh=>{"use strict";Zh.isEqual=DP;var $h=l();function DP(e,r){return+(0,$h.toDate)(e)==+(0,$h.toDate)(r)}});var Gh=s(Vh=>{"use strict";Vh.isExists=wP;function wP(e,r,t){let n=new Date(e,r,t);return n.getFullYear()===e&&n.getMonth()===r&&n.getDate()===t}});var Jh=s(Uh=>{"use strict";Uh.isFirstDayOfMonth=jP;var PP=l();function jP(e,r){return(0,PP.toDate)(e,r?.in).getDate()===1}});var yh=s(Kh=>{"use strict";Kh.isFriday=TP;var IP=l();function TP(e,r){return(0,IP.toDate)(e,r?.in).getDay()===5}});var e_=s(kh=>{"use strict";kh.isFuture=YP;var EP=l();function YP(e){return+(0,EP.toDate)(e)>Date.now()}});var wt=s(r_=>{"use strict";r_.transpose=SP;var WP=b();function SP(e,r){let t=FP(r)?new r(0):(0,WP.constructFrom)(r,0);return t.setFullYear(e.getFullYear(),e.getMonth(),e.getDate()),t.setHours(e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()),t}function FP(e){return typeof e=="function"&&e.prototype?.constructor===e}});var It=s(ae=>{"use strict";ae.ValueSetter=ae.Setter=ae.DateTimezoneSetter=void 0;var t_=b(),NP=wt(),HP=10,Te=class{subPriority=0;validate(r,t){return!0}};ae.Setter=Te;var Pt=class extends Te{constructor(r,t,n,u,a){super(),this.value=r,this.validateValue=t,this.setValue=n,this.priority=u,a&&(this.subPriority=a)}validate(r,t){return this.validateValue(r,this.value,t)}set(r,t,n){return this.setValue(r,t,this.value,n)}};ae.ValueSetter=Pt;var jt=class extends Te{priority=HP;subPriority=-1;constructor(r,t){super(),this.context=r||(n=>(0,t_.constructFrom)(t,n))}set(r,t){return t.timestampIsSet?r:(0,t_.constructFrom)(r,(0,NP.transpose)(r,this.context))}};ae.DateTimezoneSetter=jt});var M=s(Et=>{"use strict";Et.Parser=void 0;var LP=It(),Tt=class{run(r,t,n,u){let a=this.parse(r,t,n,u);return a?{setter:new LP.ValueSetter(a.value,this.validate,this.set,this.priority,this.subPriority),rest:a.rest}:null}validate(r,t,n){return!0}};Et.Parser=Tt});var n_=s(Wt=>{"use strict";Wt.EraParser=void 0;var CP=M(),Yt=class extends CP.Parser{priority=140;parse(r,t,n){switch(t){case"G":case"GG":case"GGG":return n.era(r,{width:"abbreviated"})||n.era(r,{width:"narrow"});case"GGGGG":return n.era(r,{width:"narrow"});case"GGGG":default:return n.era(r,{width:"wide"})||n.era(r,{width:"abbreviated"})||n.era(r,{width:"narrow"})}}set(r,t,n){return t.era=n,r.setFullYear(n,0,1),r.setHours(0,0,0,0),r}incompatibleTokens=["R","u","t","T"]};Wt.EraParser=Yt});var W=s(Ee=>{"use strict";Ee.timezonePatterns=Ee.numericPatterns=void 0;var u3=Ee.numericPatterns={month:/^(1[0-2]|0?\d)/,date:/^(3[0-1]|[0-2]?\d)/,dayOfYear:/^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,week:/^(5[0-3]|[0-4]?\d)/,hour23h:/^(2[0-3]|[0-1]?\d)/,hour24h:/^(2[0-4]|[0-1]?\d)/,hour11h:/^(1[0-1]|0?\d)/,hour12h:/^(1[0-2]|0?\d)/,minute:/^[0-5]?\d/,second:/^[0-5]?\d/,singleDigit:/^\d/,twoDigits:/^\d{1,2}/,threeDigits:/^\d{1,3}/,fourDigits:/^\d{1,4}/,anyDigitsSigned:/^-?\d+/,singleDigitSigned:/^-?\d/,twoDigitsSigned:/^-?\d{1,2}/,threeDigitsSigned:/^-?\d{1,3}/,fourDigitsSigned:/^-?\d{1,4}/},a3=Ee.timezonePatterns={basicOptionalMinutes:/^([+-])(\d{2})(\d{2})?|Z/,basic:/^([+-])(\d{2})(\d{2})|Z/,basicOptionalSeconds:/^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,extended:/^([+-])(\d{2}):(\d{2})|Z/,extendedOptionalSeconds:/^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/}});var w=s(z=>{"use strict";z.dayPeriodEnumToHours=$P;z.isLeapYearIndex=XP;z.mapValue=zP;z.normalizeTwoDigitYear=ZP;z.parseAnyDigitsSigned=QP;z.parseNDigits=RP;z.parseNDigitsSigned=AP;z.parseNumericPattern=S;z.parseTimezonePattern=BP;var St=O(),X=W();function zP(e,r){return e&&{value:r(e.value),rest:e.rest}}function S(e,r){let t=r.match(e);return t?{value:parseInt(t[0],10),rest:r.slice(t[0].length)}:null}function BP(e,r){let t=r.match(e);if(!t)return null;if(t[0]==="Z")return{value:0,rest:r.slice(1)};let n=t[1]==="+"?1:-1,u=t[2]?parseInt(t[2],10):0,a=t[3]?parseInt(t[3],10):0,o=t[5]?parseInt(t[5],10):0;return{value:n*(u*St.millisecondsInHour+a*St.millisecondsInMinute+o*St.millisecondsInSecond),rest:r.slice(t[0].length)}}function QP(e){return S(X.numericPatterns.anyDigitsSigned,e)}function RP(e,r){switch(e){case 1:return S(X.numericPatterns.singleDigit,r);case 2:return S(X.numericPatterns.twoDigits,r);case 3:return S(X.numericPatterns.threeDigits,r);case 4:return S(X.numericPatterns.fourDigits,r);default:return S(new RegExp("^\\d{1,"+e+"}"),r)}}function AP(e,r){switch(e){case 1:return S(X.numericPatterns.singleDigitSigned,r);case 2:return S(X.numericPatterns.twoDigitsSigned,r);case 3:return S(X.numericPatterns.threeDigitsSigned,r);case 4:return S(X.numericPatterns.fourDigitsSigned,r);default:return S(new RegExp("^-?\\d{1,"+e+"}"),r)}}function $P(e){switch(e){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;case"am":case"midnight":case"night":default:return 0}}function ZP(e,r){let t=r>0,n=t?r:1-r,u;if(n<=50)u=e||100;else{let a=n+50,o=Math.trunc(a/100)*100,c=e>=a%100;u=e+o-(c?100:0)}return t?u:1-u}function XP(e){return e%400===0||e%4===0&&e%100!==0}});var i_=s(Nt=>{"use strict";Nt.YearParser=void 0;var VP=M(),he=w(),Ft=class extends VP.Parser{priority=130;incompatibleTokens=["Y","R","u","w","I","i","e","c","t","T"];parse(r,t,n){let u=a=>({year:a,isTwoDigitYear:t==="yy"});switch(t){case"y":return(0,he.mapValue)((0,he.parseNDigits)(4,r),u);case"yo":return(0,he.mapValue)(n.ordinalNumber(r,{unit:"year"}),u);default:return(0,he.mapValue)((0,he.parseNDigits)(t.length,r),u)}}validate(r,t){return t.isTwoDigitYear||t.year>0}set(r,t,n){let u=r.getFullYear();if(n.isTwoDigitYear){let o=(0,he.normalizeTwoDigitYear)(n.year,u);return r.setFullYear(o,0,1),r.setHours(0,0,0,0),r}let a=!("era"in t)||t.era===1?n.year:1-n.year;return r.setFullYear(a,0,1),r.setHours(0,0,0,0),r}};Nt.YearParser=Ft});var a_=s(Lt=>{"use strict";Lt.LocalWeekYearParser=void 0;var GP=we(),u_=N(),UP=M(),_e=w(),Ht=class extends UP.Parser{priority=130;parse(r,t,n){let u=a=>({year:a,isTwoDigitYear:t==="YY"});switch(t){case"Y":return(0,_e.mapValue)((0,_e.parseNDigits)(4,r),u);case"Yo":return(0,_e.mapValue)(n.ordinalNumber(r,{unit:"year"}),u);default:return(0,_e.mapValue)((0,_e.parseNDigits)(t.length,r),u)}}validate(r,t){return t.isTwoDigitYear||t.year>0}set(r,t,n,u){let a=(0,GP.getWeekYear)(r,u);if(n.isTwoDigitYear){let c=(0,_e.normalizeTwoDigitYear)(n.year,a);return r.setFullYear(c,0,u.firstWeekContainsDate),r.setHours(0,0,0,0),(0,u_.startOfWeek)(r,u)}let o=!("era"in t)||t.era===1?n.year:1-n.year;return r.setFullYear(o,0,u.firstWeekContainsDate),r.setHours(0,0,0,0),(0,u_.startOfWeek)(r,u)}incompatibleTokens=["y","R","u","Q","q","M","L","I","d","D","i","t","T"]};Lt.LocalWeekYearParser=Ht});var o_=s(zt=>{"use strict";zt.ISOWeekYearParser=void 0;var JP=L(),KP=b(),yP=M(),s_=w(),Ct=class extends yP.Parser{priority=130;parse(r,t){return t==="R"?(0,s_.parseNDigitsSigned)(4,r):(0,s_.parseNDigitsSigned)(t.length,r)}set(r,t,n){let u=(0,KP.constructFrom)(r,0);return u.setFullYear(n,0,4),u.setHours(0,0,0,0),(0,JP.startOfISOWeek)(u)}incompatibleTokens=["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"]};zt.ISOWeekYearParser=Ct});var f_=s(Qt=>{"use strict";Qt.ExtendedYearParser=void 0;var kP=M(),c_=w(),Bt=class extends kP.Parser{priority=130;parse(r,t){return t==="u"?(0,c_.parseNDigitsSigned)(4,r):(0,c_.parseNDigitsSigned)(t.length,r)}set(r,t,n){return r.setFullYear(n,0,1),r.setHours(0,0,0,0),r}incompatibleTokens=["G","y","Y","R","w","I","i","e","c","t","T"]};Qt.ExtendedYearParser=Bt});var d_=s(At=>{"use strict";At.QuarterParser=void 0;var e1=M(),r1=w(),Rt=class extends e1.Parser{priority=120;parse(r,t,n){switch(t){case"Q":case"QQ":return(0,r1.parseNDigits)(t.length,r);case"Qo":return n.ordinalNumber(r,{unit:"quarter"});case"QQQ":return n.quarter(r,{width:"abbreviated",context:"formatting"})||n.quarter(r,{width:"narrow",context:"formatting"});case"QQQQQ":return n.quarter(r,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(r,{width:"wide",context:"formatting"})||n.quarter(r,{width:"abbreviated",context:"formatting"})||n.quarter(r,{width:"narrow",context:"formatting"})}}validate(r,t){return t>=1&&t<=4}set(r,t,n){return r.setMonth((n-1)*3,1),r.setHours(0,0,0,0),r}incompatibleTokens=["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"]};At.QuarterParser=Rt});var l_=s(Zt=>{"use strict";Zt.StandAloneQuarterParser=void 0;var t1=M(),n1=w(),$t=class extends t1.Parser{priority=120;parse(r,t,n){switch(t){case"q":case"qq":return(0,n1.parseNDigits)(t.length,r);case"qo":return n.ordinalNumber(r,{unit:"quarter"});case"qqq":return n.quarter(r,{width:"abbreviated",context:"standalone"})||n.quarter(r,{width:"narrow",context:"standalone"});case"qqqqq":return n.quarter(r,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(r,{width:"wide",context:"standalone"})||n.quarter(r,{width:"abbreviated",context:"standalone"})||n.quarter(r,{width:"narrow",context:"standalone"})}}validate(r,t){return t>=1&&t<=4}set(r,t,n){return r.setMonth((n-1)*3,1),r.setHours(0,0,0,0),r}incompatibleTokens=["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"]};Zt.StandAloneQuarterParser=$t});var h_=s(Vt=>{"use strict";Vt.MonthParser=void 0;var i1=W(),u1=M(),Ye=w(),Xt=class extends u1.Parser{incompatibleTokens=["Y","R","q","Q","L","w","I","D","i","e","c","t","T"];priority=110;parse(r,t,n){let u=a=>a-1;switch(t){case"M":return(0,Ye.mapValue)((0,Ye.parseNumericPattern)(i1.numericPatterns.month,r),u);case"MM":return(0,Ye.mapValue)((0,Ye.parseNDigits)(2,r),u);case"Mo":return(0,Ye.mapValue)(n.ordinalNumber(r,{unit:"month"}),u);case"MMM":return n.month(r,{width:"abbreviated",context:"formatting"})||n.month(r,{width:"narrow",context:"formatting"});case"MMMMM":return n.month(r,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(r,{width:"wide",context:"formatting"})||n.month(r,{width:"abbreviated",context:"formatting"})||n.month(r,{width:"narrow",context:"formatting"})}}validate(r,t){return t>=0&&t<=11}set(r,t,n){return r.setMonth(n,1),r.setHours(0,0,0,0),r}};Vt.MonthParser=Xt});var __=s(Ut=>{"use strict";Ut.StandAloneMonthParser=void 0;var a1=W(),s1=M(),We=w(),Gt=class extends s1.Parser{priority=110;parse(r,t,n){let u=a=>a-1;switch(t){case"L":return(0,We.mapValue)((0,We.parseNumericPattern)(a1.numericPatterns.month,r),u);case"LL":return(0,We.mapValue)((0,We.parseNDigits)(2,r),u);case"Lo":return(0,We.mapValue)(n.ordinalNumber(r,{unit:"month"}),u);case"LLL":return n.month(r,{width:"abbreviated",context:"standalone"})||n.month(r,{width:"narrow",context:"standalone"});case"LLLLL":return n.month(r,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(r,{width:"wide",context:"standalone"})||n.month(r,{width:"abbreviated",context:"standalone"})||n.month(r,{width:"narrow",context:"standalone"})}}validate(r,t){return t>=0&&t<=11}set(r,t,n){return r.setMonth(n,1),r.setHours(0,0,0,0),r}incompatibleTokens=["Y","R","q","Q","M","w","I","D","i","e","c","t","T"]};Ut.StandAloneMonthParser=Gt});var Jt=s(b_=>{"use strict";b_.setWeek=c1;var o1=fr(),m_=l();function c1(e,r,t){let n=(0,m_.toDate)(e,t?.in),u=(0,o1.getWeek)(n,t)-r;return n.setDate(n.getDate()-u*7),(0,m_.toDate)(n,t?.in)}});var v_=s(yt=>{"use strict";yt.LocalWeekParser=void 0;var f1=Jt(),d1=N(),l1=W(),h1=M(),g_=w(),Kt=class extends h1.Parser{priority=100;parse(r,t,n){switch(t){case"w":return(0,g_.parseNumericPattern)(l1.numericPatterns.week,r);case"wo":return n.ordinalNumber(r,{unit:"week"});default:return(0,g_.parseNDigits)(t.length,r)}}validate(r,t){return t>=1&&t<=53}set(r,t,n,u){return(0,d1.startOfWeek)((0,f1.setWeek)(r,n,u),u)}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","i","t","T"]};yt.LocalWeekParser=Kt});var kt=s(x_=>{"use strict";x_.setISOWeek=b1;var _1=or(),m1=l();function b1(e,r,t){let n=(0,m1.toDate)(e,t?.in),u=(0,_1.getISOWeek)(n,t)-r;return n.setDate(n.getDate()-u*7),n}});var q_=s(rn=>{"use strict";rn.ISOWeekParser=void 0;var g1=kt(),v1=L(),x1=W(),O1=M(),O_=w(),en=class extends O1.Parser{priority=100;parse(r,t,n){switch(t){case"I":return(0,O_.parseNumericPattern)(x1.numericPatterns.week,r);case"Io":return n.ordinalNumber(r,{unit:"week"});default:return(0,O_.parseNDigits)(t.length,r)}}validate(r,t){return t>=1&&t<=53}set(r,t,n){return(0,v1.startOfISOWeek)((0,g1.setISOWeek)(r,n))}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"]};rn.ISOWeekParser=en});var p_=s(un=>{"use strict";un.DateParser=void 0;var q1=W(),p1=M(),tn=w(),M1=[31,28,31,30,31,30,31,31,30,31,30,31],D1=[31,29,31,30,31,30,31,31,30,31,30,31],nn=class extends p1.Parser{priority=90;subPriority=1;parse(r,t,n){switch(t){case"d":return(0,tn.parseNumericPattern)(q1.numericPatterns.date,r);case"do":return n.ordinalNumber(r,{unit:"date"});default:return(0,tn.parseNDigits)(t.length,r)}}validate(r,t){let n=r.getFullYear(),u=(0,tn.isLeapYearIndex)(n),a=r.getMonth();return u?t>=1&&t<=D1[a]:t>=1&&t<=M1[a]}set(r,t,n){return r.setDate(n),r.setHours(0,0,0,0),r}incompatibleTokens=["Y","R","q","Q","w","I","D","i","e","c","t","T"]};un.DateParser=nn});var M_=s(on=>{"use strict";on.DayOfYearParser=void 0;var w1=W(),P1=M(),an=w(),sn=class extends P1.Parser{priority=90;subpriority=1;parse(r,t,n){switch(t){case"D":case"DD":return(0,an.parseNumericPattern)(w1.numericPatterns.dayOfYear,r);case"Do":return n.ordinalNumber(r,{unit:"date"});default:return(0,an.parseNDigits)(t.length,r)}}validate(r,t){let n=r.getFullYear();return(0,an.isLeapYearIndex)(n)?t>=1&&t<=366:t>=1&&t<=365}set(r,t,n){return r.setMonth(0,n),r.setHours(0,0,0,0),r}incompatibleTokens=["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"]};on.DayOfYearParser=sn});var Se=s(D_=>{"use strict";D_.setDay=E1;var j1=Y(),I1=H(),T1=l();function E1(e,r,t){let n=(0,j1.getDefaultOptions)(),u=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??n.weekStartsOn??n.locale?.options?.weekStartsOn??0,a=(0,T1.toDate)(e,t?.in),o=a.getDay(),f=(r%7+7)%7,d=7-u,h=r<0||r>6?r-(o+d)%7:(f+d)%7-(o+d)%7;return(0,I1.addDays)(a,h,t)}});var w_=s(fn=>{"use strict";fn.DayParser=void 0;var Y1=Se(),W1=M(),cn=class extends W1.Parser{priority=90;parse(r,t,n){switch(t){case"E":case"EE":case"EEE":return n.day(r,{width:"abbreviated",context:"formatting"})||n.day(r,{width:"short",context:"formatting"})||n.day(r,{width:"narrow",context:"formatting"});case"EEEEE":return n.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(r,{width:"short",context:"formatting"})||n.day(r,{width:"narrow",context:"formatting"});case"EEEE":default:return n.day(r,{width:"wide",context:"formatting"})||n.day(r,{width:"abbreviated",context:"formatting"})||n.day(r,{width:"short",context:"formatting"})||n.day(r,{width:"narrow",context:"formatting"})}}validate(r,t){return t>=0&&t<=6}set(r,t,n,u){return r=(0,Y1.setDay)(r,n,u),r.setHours(0,0,0,0),r}incompatibleTokens=["D","i","e","c","t","T"]};fn.DayParser=cn});var P_=s(hn=>{"use strict";hn.LocalDayParser=void 0;var S1=Se(),F1=M(),dn=w(),ln=class extends F1.Parser{priority=90;parse(r,t,n,u){let a=o=>{let c=Math.floor((o-1)/7)*7;return(o+u.weekStartsOn+6)%7+c};switch(t){case"e":case"ee":return(0,dn.mapValue)((0,dn.parseNDigits)(t.length,r),a);case"eo":return(0,dn.mapValue)(n.ordinalNumber(r,{unit:"day"}),a);case"eee":return n.day(r,{width:"abbreviated",context:"formatting"})||n.day(r,{width:"short",context:"formatting"})||n.day(r,{width:"narrow",context:"formatting"});case"eeeee":return n.day(r,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(r,{width:"short",context:"formatting"})||n.day(r,{width:"narrow",context:"formatting"});case"eeee":default:return n.day(r,{width:"wide",context:"formatting"})||n.day(r,{width:"abbreviated",context:"formatting"})||n.day(r,{width:"short",context:"formatting"})||n.day(r,{width:"narrow",context:"formatting"})}}validate(r,t){return t>=0&&t<=6}set(r,t,n,u){return r=(0,S1.setDay)(r,n,u),r.setHours(0,0,0,0),r}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"]};hn.LocalDayParser=ln});var j_=s(bn=>{"use strict";bn.StandAloneLocalDayParser=void 0;var N1=Se(),H1=M(),_n=w(),mn=class extends H1.Parser{priority=90;parse(r,t,n,u){let a=o=>{let c=Math.floor((o-1)/7)*7;return(o+u.weekStartsOn+6)%7+c};switch(t){case"c":case"cc":return(0,_n.mapValue)((0,_n.parseNDigits)(t.length,r),a);case"co":return(0,_n.mapValue)(n.ordinalNumber(r,{unit:"day"}),a);case"ccc":return n.day(r,{width:"abbreviated",context:"standalone"})||n.day(r,{width:"short",context:"standalone"})||n.day(r,{width:"narrow",context:"standalone"});case"ccccc":return n.day(r,{width:"narrow",context:"standalone"});case"cccccc":return n.day(r,{width:"short",context:"standalone"})||n.day(r,{width:"narrow",context:"standalone"});case"cccc":default:return n.day(r,{width:"wide",context:"standalone"})||n.day(r,{width:"abbreviated",context:"standalone"})||n.day(r,{width:"short",context:"standalone"})||n.day(r,{width:"narrow",context:"standalone"})}}validate(r,t){return t>=0&&t<=6}set(r,t,n,u){return r=(0,N1.setDay)(r,n,u),r.setHours(0,0,0,0),r}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"]};bn.StandAloneLocalDayParser=mn});var gn=s(I_=>{"use strict";I_.setISODay=B1;var L1=H(),C1=xt(),z1=l();function B1(e,r,t){let n=(0,z1.toDate)(e,t?.in),u=(0,C1.getISODay)(n,t),a=r-u;return(0,L1.addDays)(n,a,t)}});var T_=s(xn=>{"use strict";xn.ISODayParser=void 0;var Q1=gn(),R1=M(),Fe=w(),vn=class extends R1.Parser{priority=90;parse(r,t,n){let u=a=>a===0?7:a;switch(t){case"i":case"ii":return(0,Fe.parseNDigits)(t.length,r);case"io":return n.ordinalNumber(r,{unit:"day"});case"iii":return(0,Fe.mapValue)(n.day(r,{width:"abbreviated",context:"formatting"})||n.day(r,{width:"short",context:"formatting"})||n.day(r,{width:"narrow",context:"formatting"}),u);case"iiiii":return(0,Fe.mapValue)(n.day(r,{width:"narrow",context:"formatting"}),u);case"iiiiii":return(0,Fe.mapValue)(n.day(r,{width:"short",context:"formatting"})||n.day(r,{width:"narrow",context:"formatting"}),u);case"iiii":default:return(0,Fe.mapValue)(n.day(r,{width:"wide",context:"formatting"})||n.day(r,{width:"abbreviated",context:"formatting"})||n.day(r,{width:"short",context:"formatting"})||n.day(r,{width:"narrow",context:"formatting"}),u)}}validate(r,t){return t>=1&&t<=7}set(r,t,n){return r=(0,Q1.setISODay)(r,n),r.setHours(0,0,0,0),r}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"]};xn.ISODayParser=vn});var E_=s(qn=>{"use strict";qn.AMPMParser=void 0;var A1=M(),$1=w(),On=class extends A1.Parser{priority=80;parse(r,t,n){switch(t){case"a":case"aa":case"aaa":return n.dayPeriod(r,{width:"abbreviated",context:"formatting"})||n.dayPeriod(r,{width:"narrow",context:"formatting"});case"aaaaa":return n.dayPeriod(r,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(r,{width:"wide",context:"formatting"})||n.dayPeriod(r,{width:"abbreviated",context:"formatting"})||n.dayPeriod(r,{width:"narrow",context:"formatting"})}}set(r,t,n){return r.setHours((0,$1.dayPeriodEnumToHours)(n),0,0,0),r}incompatibleTokens=["b","B","H","k","t","T"]};qn.AMPMParser=On});var Y_=s(Mn=>{"use strict";Mn.AMPMMidnightParser=void 0;var Z1=M(),X1=w(),pn=class extends Z1.Parser{priority=80;parse(r,t,n){switch(t){case"b":case"bb":case"bbb":return n.dayPeriod(r,{width:"abbreviated",context:"formatting"})||n.dayPeriod(r,{width:"narrow",context:"formatting"});case"bbbbb":return n.dayPeriod(r,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(r,{width:"wide",context:"formatting"})||n.dayPeriod(r,{width:"abbreviated",context:"formatting"})||n.dayPeriod(r,{width:"narrow",context:"formatting"})}}set(r,t,n){return r.setHours((0,X1.dayPeriodEnumToHours)(n),0,0,0),r}incompatibleTokens=["a","B","H","k","t","T"]};Mn.AMPMMidnightParser=pn});var W_=s(wn=>{"use strict";wn.DayPeriodParser=void 0;var V1=M(),G1=w(),Dn=class extends V1.Parser{priority=80;parse(r,t,n){switch(t){case"B":case"BB":case"BBB":return n.dayPeriod(r,{width:"abbreviated",context:"formatting"})||n.dayPeriod(r,{width:"narrow",context:"formatting"});case"BBBBB":return n.dayPeriod(r,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(r,{width:"wide",context:"formatting"})||n.dayPeriod(r,{width:"abbreviated",context:"formatting"})||n.dayPeriod(r,{width:"narrow",context:"formatting"})}}set(r,t,n){return r.setHours((0,G1.dayPeriodEnumToHours)(n),0,0,0),r}incompatibleTokens=["a","b","t","T"]};wn.DayPeriodParser=Dn});var F_=s(jn=>{"use strict";jn.Hour1to12Parser=void 0;var U1=W(),J1=M(),S_=w(),Pn=class extends J1.Parser{priority=70;parse(r,t,n){switch(t){case"h":return(0,S_.parseNumericPattern)(U1.numericPatterns.hour12h,r);case"ho":return n.ordinalNumber(r,{unit:"hour"});default:return(0,S_.parseNDigits)(t.length,r)}}validate(r,t){return t>=1&&t<=12}set(r,t,n){let u=r.getHours()>=12;return u&&n<12?r.setHours(n+12,0,0,0):!u&&n===12?r.setHours(0,0,0,0):r.setHours(n,0,0,0),r}incompatibleTokens=["H","K","k","t","T"]};jn.Hour1to12Parser=Pn});var H_=s(Tn=>{"use strict";Tn.Hour0to23Parser=void 0;var K1=W(),y1=M(),N_=w(),In=class extends y1.Parser{priority=70;parse(r,t,n){switch(t){case"H":return(0,N_.parseNumericPattern)(K1.numericPatterns.hour23h,r);case"Ho":return n.ordinalNumber(r,{unit:"hour"});default:return(0,N_.parseNDigits)(t.length,r)}}validate(r,t){return t>=0&&t<=23}set(r,t,n){return r.setHours(n,0,0,0),r}incompatibleTokens=["a","b","h","K","k","t","T"]};Tn.Hour0to23Parser=In});var C_=s(Yn=>{"use strict";Yn.Hour0To11Parser=void 0;var k1=W(),ej=M(),L_=w(),En=class extends ej.Parser{priority=70;parse(r,t,n){switch(t){case"K":return(0,L_.parseNumericPattern)(k1.numericPatterns.hour11h,r);case"Ko":return n.ordinalNumber(r,{unit:"hour"});default:return(0,L_.parseNDigits)(t.length,r)}}validate(r,t){return t>=0&&t<=11}set(r,t,n){return r.getHours()>=12&&n<12?r.setHours(n+12,0,0,0):r.setHours(n,0,0,0),r}incompatibleTokens=["h","H","k","t","T"]};Yn.Hour0To11Parser=En});var B_=s(Sn=>{"use strict";Sn.Hour1To24Parser=void 0;var rj=W(),tj=M(),z_=w(),Wn=class extends tj.Parser{priority=70;parse(r,t,n){switch(t){case"k":return(0,z_.parseNumericPattern)(rj.numericPatterns.hour24h,r);case"ko":return n.ordinalNumber(r,{unit:"hour"});default:return(0,z_.parseNDigits)(t.length,r)}}validate(r,t){return t>=1&&t<=24}set(r,t,n){let u=n<=24?n%24:n;return r.setHours(u,0,0,0),r}incompatibleTokens=["a","b","h","H","K","t","T"]};Sn.Hour1To24Parser=Wn});var R_=s(Nn=>{"use strict";Nn.MinuteParser=void 0;var nj=W(),ij=M(),Q_=w(),Fn=class extends ij.Parser{priority=60;parse(r,t,n){switch(t){case"m":return(0,Q_.parseNumericPattern)(nj.numericPatterns.minute,r);case"mo":return n.ordinalNumber(r,{unit:"minute"});default:return(0,Q_.parseNDigits)(t.length,r)}}validate(r,t){return t>=0&&t<=59}set(r,t,n){return r.setMinutes(n,0,0),r}incompatibleTokens=["t","T"]};Nn.MinuteParser=Fn});var $_=s(Ln=>{"use strict";Ln.SecondParser=void 0;var uj=W(),aj=M(),A_=w(),Hn=class extends aj.Parser{priority=50;parse(r,t,n){switch(t){case"s":return(0,A_.parseNumericPattern)(uj.numericPatterns.second,r);case"so":return n.ordinalNumber(r,{unit:"second"});default:return(0,A_.parseNDigits)(t.length,r)}}validate(r,t){return t>=0&&t<=59}set(r,t,n){return r.setSeconds(n,0),r}incompatibleTokens=["t","T"]};Ln.SecondParser=Hn});var X_=s(zn=>{"use strict";zn.FractionOfSecondParser=void 0;var sj=M(),Z_=w(),Cn=class extends sj.Parser{priority=30;parse(r,t){let n=u=>Math.trunc(u*Math.pow(10,-t.length+3));return(0,Z_.mapValue)((0,Z_.parseNDigits)(t.length,r),n)}set(r,t,n){return r.setMilliseconds(n),r}incompatibleTokens=["t","T"]};zn.FractionOfSecondParser=Cn});var V_=s(Qn=>{"use strict";Qn.ISOTimezoneWithZParser=void 0;var oj=b(),cj=R(),Ne=W(),fj=M(),He=w(),Bn=class extends fj.Parser{priority=10;parse(r,t){switch(t){case"X":return(0,He.parseTimezonePattern)(Ne.timezonePatterns.basicOptionalMinutes,r);case"XX":return(0,He.parseTimezonePattern)(Ne.timezonePatterns.basic,r);case"XXXX":return(0,He.parseTimezonePattern)(Ne.timezonePatterns.basicOptionalSeconds,r);case"XXXXX":return(0,He.parseTimezonePattern)(Ne.timezonePatterns.extendedOptionalSeconds,r);case"XXX":default:return(0,He.parseTimezonePattern)(Ne.timezonePatterns.extended,r)}}set(r,t,n){return t.timestampIsSet?r:(0,oj.constructFrom)(r,r.getTime()-(0,cj.getTimezoneOffsetInMilliseconds)(r)-n)}incompatibleTokens=["t","T","x"]};Qn.ISOTimezoneWithZParser=Bn});var G_=s(An=>{"use strict";An.ISOTimezoneParser=void 0;var dj=b(),lj=R(),Le=W(),hj=M(),Ce=w(),Rn=class extends hj.Parser{priority=10;parse(r,t){switch(t){case"x":return(0,Ce.parseTimezonePattern)(Le.timezonePatterns.basicOptionalMinutes,r);case"xx":return(0,Ce.parseTimezonePattern)(Le.timezonePatterns.basic,r);case"xxxx":return(0,Ce.parseTimezonePattern)(Le.timezonePatterns.basicOptionalSeconds,r);case"xxxxx":return(0,Ce.parseTimezonePattern)(Le.timezonePatterns.extendedOptionalSeconds,r);case"xxx":default:return(0,Ce.parseTimezonePattern)(Le.timezonePatterns.extended,r)}}set(r,t,n){return t.timestampIsSet?r:(0,dj.constructFrom)(r,r.getTime()-(0,lj.getTimezoneOffsetInMilliseconds)(r)-n)}incompatibleTokens=["t","T","X"]};An.ISOTimezoneParser=Rn});var U_=s(Zn=>{"use strict";Zn.TimestampSecondsParser=void 0;var _j=b(),mj=M(),bj=w(),$n=class extends mj.Parser{priority=40;parse(r){return(0,bj.parseAnyDigitsSigned)(r)}set(r,t,n){return[(0,_j.constructFrom)(r,n*1e3),{timestampIsSet:!0}]}incompatibleTokens="*"};Zn.TimestampSecondsParser=$n});var J_=s(Vn=>{"use strict";Vn.TimestampMillisecondsParser=void 0;var gj=b(),vj=M(),xj=w(),Xn=class extends vj.Parser{priority=20;parse(r){return(0,xj.parseAnyDigitsSigned)(r)}set(r,t,n){return[(0,gj.constructFrom)(r,n),{timestampIsSet:!0}]}incompatibleTokens="*"};Vn.TimestampMillisecondsParser=Xn});var K_=s(Gn=>{"use strict";Gn.parsers=void 0;var Oj=n_(),qj=i_(),pj=a_(),Mj=o_(),Dj=f_(),wj=d_(),Pj=l_(),jj=h_(),Ij=__(),Tj=v_(),Ej=q_(),Yj=p_(),Wj=M_(),Sj=w_(),Fj=P_(),Nj=j_(),Hj=T_(),Lj=E_(),Cj=Y_(),zj=W_(),Bj=F_(),Qj=H_(),Rj=C_(),Aj=B_(),$j=R_(),Zj=$_(),Xj=X_(),Vj=V_(),Gj=G_(),Uj=U_(),Jj=J_(),A3=Gn.parsers={G:new Oj.EraParser,y:new qj.YearParser,Y:new pj.LocalWeekYearParser,R:new Mj.ISOWeekYearParser,u:new Dj.ExtendedYearParser,Q:new wj.QuarterParser,q:new Pj.StandAloneQuarterParser,M:new jj.MonthParser,L:new Ij.StandAloneMonthParser,w:new Tj.LocalWeekParser,I:new Ej.ISOWeekParser,d:new Yj.DateParser,D:new Wj.DayOfYearParser,E:new Sj.DayParser,e:new Fj.LocalDayParser,c:new Nj.StandAloneLocalDayParser,i:new Hj.ISODayParser,a:new Lj.AMPMParser,b:new Cj.AMPMMidnightParser,B:new zj.DayPeriodParser,h:new Bj.Hour1to12Parser,H:new Qj.Hour0to23Parser,K:new Rj.Hour0To11Parser,k:new Aj.Hour1To24Parser,m:new $j.MinuteParser,s:new Zj.SecondParser,S:new Xj.FractionOfSecondParser,X:new Vj.ISOTimezoneWithZParser,x:new Gj.ISOTimezoneParser,t:new Uj.TimestampSecondsParser,T:new Jj.TimestampMillisecondsParser}});var Jn=s(mr=>{"use strict";Object.defineProperty(mr,"longFormatters",{enumerable:!0,get:function(){return Un.longFormatters}});mr.parse=sI;Object.defineProperty(mr,"parsers",{enumerable:!0,get:function(){return k_.parsers}});var Kj=te(),Un=ot(),_r=ct(),yj=b(),kj=vt(),y_=l(),eI=It(),k_=K_(),rI=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,tI=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,nI=/^'([^]*?)'?$/,iI=/''/g,uI=/\S/,aI=/[a-zA-Z]/;function sI(e,r,t,n){let u=()=>(0,yj.constructFrom)(n?.in||t,NaN),a=(0,kj.getDefaultOptions)(),o=n?.locale??a.locale??Kj.defaultLocale,c=n?.firstWeekContainsDate??n?.locale?.options?.firstWeekContainsDate??a.firstWeekContainsDate??a.locale?.options?.firstWeekContainsDate??1,f=n?.weekStartsOn??n?.locale?.options?.weekStartsOn??a.weekStartsOn??a.locale?.options?.weekStartsOn??0;if(!r)return e?u():(0,y_.toDate)(t,n?.in);let d={firstWeekContainsDate:c,weekStartsOn:f,locale:o},h=[new eI.DateTimezoneSetter(n?.in,t)],_=r.match(tI).map(m=>{let D=m[0];if(D in Un.longFormatters){let E=Un.longFormatters[D];return E(m,o.formatLong)}return m}).join("").match(rI),g=[];for(let m of _){!n?.useAdditionalWeekYearTokens&&(0,_r.isProtectedWeekYearToken)(m)&&(0,_r.warnOrThrowProtectedError)(m,r,e),!n?.useAdditionalDayOfYearTokens&&(0,_r.isProtectedDayOfYearToken)(m)&&(0,_r.warnOrThrowProtectedError)(m,r,e);let D=m[0],E=k_.parsers[D];if(E){let{incompatibleTokens:B}=E;if(Array.isArray(B)){let me=g.find($o=>B.includes($o.token)||$o.token===D);if(me)throw new RangeError(`The format string mustn't contain \`${me.fullToken}\` and \`${m}\` at the same time`)}else if(E.incompatibleTokens==="*"&&g.length>0)throw new RangeError(`The format string mustn't contain \`${m}\` and any other token at the same time`);g.push({token:D,fullToken:m});let Q=E.run(e,m,o.match,d);if(!Q)return u();h.push(Q.setter),e=Q.rest}else{if(D.match(aI))throw new RangeError("Format string contains an unescaped latin alphabet character `"+D+"`");if(m==="''"?m="'":D==="'"&&(m=oI(m)),e.indexOf(m)===0)e=e.slice(m.length);else return u()}}if(e.length>0&&uI.test(e))return u();let p=h.map(m=>m.priority).sort((m,D)=>D-m).filter((m,D,E)=>E.indexOf(m)===D).map(m=>h.filter(D=>D.priority===m).sort((D,E)=>E.subPriority-D.subPriority)).map(m=>m[0]),q=(0,y_.toDate)(t,n?.in);if(isNaN(+q))return u();let x={};for(let m of p){if(!m.validate(q,d))return u();let D=m.set(q,x,d);Array.isArray(D)?(q=D[0],Object.assign(x,D[1])):q=D}return q}function oI(e){return e.match(nI)[1].replace(iI,"'")}});var rm=s(em=>{"use strict";em.isMatch=dI;var cI=$(),fI=Jn();function dI(e,r,t){return(0,cI.isValid)((0,fI.parse)(e,r,new Date,t))}});var nm=s(tm=>{"use strict";tm.isMonday=hI;var lI=l();function hI(e,r){return(0,lI.toDate)(e,r?.in).getDay()===1}});var um=s(im=>{"use strict";im.isPast=mI;var _I=l();function mI(e){return+(0,_I.toDate)(e){"use strict";am.startOfHour=gI;var bI=l();function gI(e,r){let t=(0,bI.toDate)(e,r?.in);return t.setMinutes(0,0,0),t}});var yn=s(om=>{"use strict";om.isSameHour=xI;var vI=P(),sm=Kn();function xI(e,r,t){let[n,u]=(0,vI.normalizeDates)(t?.in,e,r);return+(0,sm.startOfHour)(n)==+(0,sm.startOfHour)(u)}});var br=s(fm=>{"use strict";fm.isSameWeek=qI;var OI=P(),cm=N();function qI(e,r,t){let[n,u]=(0,OI.normalizeDates)(t?.in,e,r);return+(0,cm.startOfWeek)(n,t)==+(0,cm.startOfWeek)(u,t)}});var kn=s(dm=>{"use strict";dm.isSameISOWeek=MI;var pI=br();function MI(e,r,t){return(0,pI.isSameWeek)(e,r,{...t,weekStartsOn:1})}});var _m=s(hm=>{"use strict";hm.isSameISOWeekYear=wI;var lm=oe(),DI=P();function wI(e,r,t){let[n,u]=(0,DI.normalizeDates)(t?.in,e,r);return+(0,lm.startOfISOWeekYear)(n)==+(0,lm.startOfISOWeekYear)(u)}});var ei=s(mm=>{"use strict";mm.startOfMinute=jI;var PI=l();function jI(e,r){let t=(0,PI.toDate)(e,r?.in);return t.setSeconds(0,0),t}});var ri=s(gm=>{"use strict";gm.isSameMinute=II;var bm=ei();function II(e,r){return+(0,bm.startOfMinute)(e)==+(0,bm.startOfMinute)(r)}});var ti=s(vm=>{"use strict";vm.isSameMonth=EI;var TI=P();function EI(e,r,t){let[n,u]=(0,TI.normalizeDates)(t?.in,e,r);return n.getFullYear()===u.getFullYear()&&n.getMonth()===u.getMonth()}});var ni=s(Om=>{"use strict";Om.isSameQuarter=WI;var YI=P(),xm=nr();function WI(e,r,t){let[n,u]=(0,YI.normalizeDates)(t?.in,e,r);return+(0,xm.startOfQuarter)(n)==+(0,xm.startOfQuarter)(u)}});var ii=s(qm=>{"use strict";qm.startOfSecond=FI;var SI=l();function FI(e,r){let t=(0,SI.toDate)(e,r?.in);return t.setMilliseconds(0),t}});var ui=s(Mm=>{"use strict";Mm.isSameSecond=NI;var pm=ii();function NI(e,r){return+(0,pm.startOfSecond)(e)==+(0,pm.startOfSecond)(r)}});var ai=s(Dm=>{"use strict";Dm.isSameYear=LI;var HI=P();function LI(e,r,t){let[n,u]=(0,HI.normalizeDates)(t?.in,e,r);return n.getFullYear()===u.getFullYear()}});var Pm=s(wm=>{"use strict";wm.isThisHour=QI;var CI=T(),zI=yn(),BI=l();function QI(e,r){return(0,zI.isSameHour)((0,BI.toDate)(e,r?.in),(0,CI.constructNow)(r?.in||e))}});var Im=s(jm=>{"use strict";jm.isThisISOWeek=ZI;var RI=b(),AI=T(),$I=kn();function ZI(e,r){return(0,$I.isSameISOWeek)((0,RI.constructFrom)(r?.in||e,e),(0,AI.constructNow)(r?.in||e))}});var Em=s(Tm=>{"use strict";Tm.isThisMinute=GI;var XI=T(),VI=ri();function GI(e){return(0,VI.isSameMinute)(e,(0,XI.constructNow)(e))}});var Wm=s(Ym=>{"use strict";Ym.isThisMonth=yI;var UI=b(),JI=T(),KI=ti();function yI(e,r){return(0,KI.isSameMonth)((0,UI.constructFrom)(r?.in||e,e),(0,JI.constructNow)(r?.in||e))}});var Fm=s(Sm=>{"use strict";Sm.isThisQuarter=tT;var kI=b(),eT=T(),rT=ni();function tT(e,r){return(0,rT.isSameQuarter)((0,kI.constructFrom)(r?.in||e,e),(0,eT.constructNow)(r?.in||e))}});var Hm=s(Nm=>{"use strict";Nm.isThisSecond=uT;var nT=T(),iT=ui();function uT(e){return(0,iT.isSameSecond)(e,(0,nT.constructNow)(e))}});var Cm=s(Lm=>{"use strict";Lm.isThisWeek=cT;var aT=b(),sT=T(),oT=br();function cT(e,r){return(0,oT.isSameWeek)((0,aT.constructFrom)(r?.in||e,e),(0,sT.constructNow)(r?.in||e),r)}});var Bm=s(zm=>{"use strict";zm.isThisYear=hT;var fT=b(),dT=T(),lT=ai();function hT(e,r){return(0,lT.isSameYear)((0,fT.constructFrom)(r?.in||e,e),(0,dT.constructNow)(r?.in||e))}});var Rm=s(Qm=>{"use strict";Qm.isThursday=mT;var _T=l();function mT(e,r){return(0,_T.toDate)(e,r?.in).getDay()===4}});var $m=s(Am=>{"use strict";Am.isToday=xT;var bT=b(),gT=T(),vT=ce();function xT(e,r){return(0,vT.isSameDay)((0,bT.constructFrom)(r?.in||e,e),(0,gT.constructNow)(r?.in||e))}});var Xm=s(Zm=>{"use strict";Zm.isTomorrow=MT;var OT=H(),qT=T(),pT=ce();function MT(e,r){return(0,pT.isSameDay)(e,(0,OT.addDays)((0,qT.constructNow)(r?.in||e),1),r)}});var Gm=s(Vm=>{"use strict";Vm.isTuesday=wT;var DT=l();function wT(e,r){return(0,DT.toDate)(e,r?.in).getDay()===2}});var Jm=s(Um=>{"use strict";Um.isWednesday=jT;var PT=l();function jT(e,r){return(0,PT.toDate)(e,r?.in).getDay()===3}});var ym=s(Km=>{"use strict";Km.isWithinInterval=IT;var si=l();function IT(e,r,t){let n=+(0,si.toDate)(e,t?.in),[u,a]=[+(0,si.toDate)(r.start,t?.in),+(0,si.toDate)(r.end,t?.in)].sort((o,c)=>o-c);return n>=u&&n<=a}});var ze=s(km=>{"use strict";km.subDays=ET;var TT=H();function ET(e,r,t){return(0,TT.addDays)(e,-r,t)}});var r0=s(e0=>{"use strict";e0.isYesterday=NT;var YT=b(),WT=T(),ST=ce(),FT=ze();function NT(e,r){return(0,ST.isSameDay)((0,YT.constructFrom)(r?.in||e,e),(0,FT.subDays)((0,WT.constructNow)(r?.in||e),1))}});var i0=s(n0=>{"use strict";n0.lastDayOfDecade=HT;var t0=l();function HT(e,r){let t=(0,t0.toDate)(e,r?.in),n=t.getFullYear(),u=9+Math.floor(n/10)*10;return t.setFullYear(u+1,0,0),t.setHours(0,0,0,0),(0,t0.toDate)(t,r?.in)}});var oi=s(u0=>{"use strict";u0.lastDayOfWeek=zT;var LT=Y(),CT=l();function zT(e,r){let t=(0,LT.getDefaultOptions)(),n=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,u=(0,CT.toDate)(e,r?.in),a=u.getDay(),o=(a{"use strict";a0.lastDayOfISOWeek=QT;var BT=oi();function QT(e,r){return(0,BT.lastDayOfWeek)(e,{...r,weekStartsOn:1})}});var c0=s(o0=>{"use strict";o0.lastDayOfISOWeekYear=ZT;var RT=b(),AT=U(),$T=L();function ZT(e,r){let t=(0,AT.getISOWeekYear)(e,r),n=(0,RT.constructFrom)(r?.in||e,0);n.setFullYear(t+1,0,4),n.setHours(0,0,0,0);let u=(0,$T.startOfISOWeek)(n,r);return u.setDate(u.getDate()-1),u}});var d0=s(f0=>{"use strict";f0.lastDayOfQuarter=VT;var XT=l();function VT(e,r){let t=(0,XT.toDate)(e,r?.in),n=t.getMonth(),u=n-n%3+3;return t.setMonth(u,0),t.setHours(0,0,0,0),t}});var h0=s(l0=>{"use strict";l0.lastDayOfYear=UT;var GT=l();function UT(e,r){let t=(0,GT.toDate)(e,r?.in),n=t.getFullYear();return t.setFullYear(n+1,0,0),t.setHours(0,0,0,0),t}});var m0=s(ci=>{"use strict";ci.lightFormat=tE;Object.defineProperty(ci,"lightFormatters",{enumerable:!0,get:function(){return _0.lightFormatters}});var _0=ut(),JT=$(),KT=l(),yT=/(\w)\1*|''|'(''|[^'])+('|$)|./g,kT=/^'([^]*?)'?$/,eE=/''/g,rE=/[a-zA-Z]/;function tE(e,r){let t=(0,KT.toDate)(e);if(!(0,JT.isValid)(t))throw new RangeError("Invalid time value");let n=r.match(yT);return n?n.map(a=>{if(a==="''")return"'";let o=a[0];if(o==="'")return nE(a);let c=_0.lightFormatters[o];if(c)return c(t,a);if(o.match(rE))throw new RangeError("Format string contains an unescaped latin alphabet character `"+o+"`");return a}).join(""):""}function nE(e){let r=e.match(kT);return r?r[1].replace(eE,"'"):e}});var v0=s(g0=>{"use strict";g0.milliseconds=iE;var b0=O();function iE({years:e,months:r,weeks:t,days:n,hours:u,minutes:a,seconds:o}){let c=0;e&&(c+=e*b0.daysInYear),r&&(c+=r*(b0.daysInYear/12)),t&&(c+=t*7),n&&(c+=n);let f=c*24*60*60;return u&&(f+=u*60*60),a&&(f+=a*60),o&&(f+=o),Math.trunc(f*1e3)}});var O0=s(x0=>{"use strict";x0.millisecondsToHours=aE;var uE=O();function aE(e){let r=e/uE.millisecondsInHour;return Math.trunc(r)}});var p0=s(q0=>{"use strict";q0.millisecondsToMinutes=oE;var sE=O();function oE(e){let r=e/sE.millisecondsInMinute;return Math.trunc(r)}});var D0=s(M0=>{"use strict";M0.millisecondsToSeconds=fE;var cE=O();function fE(e){let r=e/cE.millisecondsInSecond;return Math.trunc(r)}});var P0=s(w0=>{"use strict";w0.minutesToHours=lE;var dE=O();function lE(e){let r=e/dE.minutesInHour;return Math.trunc(r)}});var I0=s(j0=>{"use strict";j0.minutesToMilliseconds=_E;var hE=O();function _E(e){return Math.trunc(e*hE.millisecondsInMinute)}});var E0=s(T0=>{"use strict";T0.minutesToSeconds=bE;var mE=O();function bE(e){return Math.trunc(e*mE.secondsInMinute)}});var W0=s(Y0=>{"use strict";Y0.monthsToQuarters=vE;var gE=O();function vE(e){let r=e/gE.monthsInQuarter;return Math.trunc(r)}});var F0=s(S0=>{"use strict";S0.monthsToYears=OE;var xE=O();function OE(e){let r=e/xE.monthsInYear;return Math.trunc(r)}});var V=s(N0=>{"use strict";N0.nextDay=ME;var qE=H(),pE=je();function ME(e,r,t){let n=r-(0,pE.getDay)(e,t);return n<=0&&(n+=7),(0,qE.addDays)(e,n,t)}});var L0=s(H0=>{"use strict";H0.nextFriday=wE;var DE=V();function wE(e,r){return(0,DE.nextDay)(e,5,r)}});var z0=s(C0=>{"use strict";C0.nextMonday=jE;var PE=V();function jE(e,r){return(0,PE.nextDay)(e,1,r)}});var Q0=s(B0=>{"use strict";B0.nextSaturday=TE;var IE=V();function TE(e,r){return(0,IE.nextDay)(e,6,r)}});var A0=s(R0=>{"use strict";R0.nextSunday=YE;var EE=V();function YE(e,r){return(0,EE.nextDay)(e,0,r)}});var Z0=s($0=>{"use strict";$0.nextThursday=SE;var WE=V();function SE(e,r){return(0,WE.nextDay)(e,4,r)}});var V0=s(X0=>{"use strict";X0.nextTuesday=NE;var FE=V();function NE(e,r){return(0,FE.nextDay)(e,2,r)}});var U0=s(G0=>{"use strict";G0.nextWednesday=LE;var HE=V();function LE(e,r){return(0,HE.nextDay)(e,3,r)}});var k0=s(y0=>{"use strict";y0.parseISO=zE;var vr=O(),CE=b(),J0=l();function zE(e,r){let t=()=>(0,CE.constructFrom)(r?.in,NaN),n=r?.additionalDigits??2,u=AE(e),a;if(u.date){let d=$E(u.date,n);a=ZE(d.restDateString,d.year)}if(!a||isNaN(+a))return t();let o=+a,c=0,f;if(u.time&&(c=XE(u.time),isNaN(c)))return t();if(u.timezone){if(f=VE(u.timezone),isNaN(f))return t()}else{let d=new Date(o+c),h=(0,J0.toDate)(0,r?.in);return h.setFullYear(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()),h.setHours(d.getUTCHours(),d.getUTCMinutes(),d.getUTCSeconds(),d.getUTCMilliseconds()),h}return(0,J0.toDate)(o+c+f,r?.in)}var gr={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},BE=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,QE=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,RE=/^([+-])(\d{2})(?::?(\d{2}))?$/;function AE(e){let r={},t=e.split(gr.dateTimeDelimiter),n;if(t.length>2)return r;if(/:/.test(t[0])?n=t[0]:(r.date=t[0],n=t[1],gr.timeZoneDelimiter.test(r.date)&&(r.date=e.split(gr.timeZoneDelimiter)[0],n=e.substr(r.date.length,e.length))),n){let u=gr.timezone.exec(n);u?(r.time=n.replace(u[1],""),r.timezone=u[1]):r.time=n}return r}function $E(e,r){let t=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+r)+"})|(\\d{2}|[+-]\\d{"+(2+r)+"})$)"),n=e.match(t);if(!n)return{year:NaN,restDateString:""};let u=n[1]?parseInt(n[1]):null,a=n[2]?parseInt(n[2]):null;return{year:a===null?u:a*100,restDateString:e.slice((n[1]||n[2]).length)}}function ZE(e,r){if(r===null)return new Date(NaN);let t=e.match(BE);if(!t)return new Date(NaN);let n=!!t[4],u=Be(t[1]),a=Be(t[2])-1,o=Be(t[3]),c=Be(t[4]),f=Be(t[5])-1;if(n)return yE(r,c,f)?GE(r,c,f):new Date(NaN);{let d=new Date(0);return!JE(r,a,o)||!KE(r,u)?new Date(NaN):(d.setUTCFullYear(r,a,Math.max(u,o)),d)}}function Be(e){return e?parseInt(e):1}function XE(e){let r=e.match(QE);if(!r)return NaN;let t=fi(r[1]),n=fi(r[2]),u=fi(r[3]);return kE(t,n,u)?t*vr.millisecondsInHour+n*vr.millisecondsInMinute+u*1e3:NaN}function fi(e){return e&&parseFloat(e.replace(",","."))||0}function VE(e){if(e==="Z")return 0;let r=e.match(RE);if(!r)return 0;let t=r[1]==="+"?-1:1,n=parseInt(r[2]),u=r[3]&&parseInt(r[3])||0;return e2(n,u)?t*(n*vr.millisecondsInHour+u*vr.millisecondsInMinute):NaN}function GE(e,r,t){let n=new Date(0);n.setUTCFullYear(e,0,4);let u=n.getUTCDay()||7,a=(r-1)*7+t+1-u;return n.setUTCDate(n.getUTCDate()+a),n}var UE=[31,null,31,30,31,30,31,31,30,31,30,31];function K0(e){return e%400===0||e%4===0&&e%100!==0}function JE(e,r,t){return r>=0&&r<=11&&t>=1&&t<=(UE[r]||(K0(e)?29:28))}function KE(e,r){return r>=1&&r<=(K0(e)?366:365)}function yE(e,r,t){return r>=1&&r<=53&&t>=0&&t<=6}function kE(e,r,t){return e===24?r===0&&t===0:t>=0&&t<60&&r>=0&&r<60&&e>=0&&e<25}function e2(e,r){return r>=0&&r<=59}});var tb=s(rb=>{"use strict";rb.parseJSON=r2;var eb=l();function r2(e,r){let t=e.match(/(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{0,7}))?(?:Z|(.)(\d{2}):?(\d{2})?)?/);return t?(0,eb.toDate)(Date.UTC(+t[1],+t[2]-1,+t[3],+t[4]-(+t[9]||0)*(t[8]=="-"?-1:1),+t[5]-(+t[10]||0)*(t[8]=="-"?-1:1),+t[6],+((t[7]||"0")+"00").substring(0,3)),r?.in):(0,eb.toDate)(NaN,r?.in)}});var G=s(nb=>{"use strict";nb.previousDay=i2;var t2=je(),n2=ze();function i2(e,r,t){let n=(0,t2.getDay)(e,t)-r;return n<=0&&(n+=7),(0,n2.subDays)(e,n,t)}});var ub=s(ib=>{"use strict";ib.previousFriday=a2;var u2=G();function a2(e,r){return(0,u2.previousDay)(e,5,r)}});var sb=s(ab=>{"use strict";ab.previousMonday=o2;var s2=G();function o2(e,r){return(0,s2.previousDay)(e,1,r)}});var cb=s(ob=>{"use strict";ob.previousSaturday=f2;var c2=G();function f2(e,r){return(0,c2.previousDay)(e,6,r)}});var db=s(fb=>{"use strict";fb.previousSunday=l2;var d2=G();function l2(e,r){return(0,d2.previousDay)(e,0,r)}});var hb=s(lb=>{"use strict";lb.previousThursday=_2;var h2=G();function _2(e,r){return(0,h2.previousDay)(e,4,r)}});var mb=s(_b=>{"use strict";_b.previousTuesday=b2;var m2=G();function b2(e,r){return(0,m2.previousDay)(e,2,r)}});var gb=s(bb=>{"use strict";bb.previousWednesday=v2;var g2=G();function v2(e,r){return(0,g2.previousDay)(e,3,r)}});var xb=s(vb=>{"use strict";vb.quartersToMonths=O2;var x2=O();function O2(e){return Math.trunc(e*x2.monthsInQuarter)}});var qb=s(Ob=>{"use strict";Ob.quartersToYears=p2;var q2=O();function p2(e){let r=e/q2.quartersInYear;return Math.trunc(r)}});var Mb=s(pb=>{"use strict";pb.roundToNearestHours=P2;var M2=Z(),D2=b(),w2=l();function P2(e,r){let t=r?.nearestTo??1;if(t<1||t>12)return(0,D2.constructFrom)(r?.in||e,NaN);let n=(0,w2.toDate)(e,r?.in),u=n.getMinutes()/60,a=n.getSeconds()/60/60,o=n.getMilliseconds()/1e3/60/60,c=n.getHours()+u+a+o,f=r?.roundingMethod??"round",h=(0,M2.getRoundingMethod)(f)(c/t)*t;return n.setHours(h,0,0,0),n}});var wb=s(Db=>{"use strict";Db.roundToNearestMinutes=E2;var j2=Z(),I2=b(),T2=l();function E2(e,r){let t=r?.nearestTo??1;if(t<1||t>30)return(0,I2.constructFrom)(e,NaN);let n=(0,T2.toDate)(e,r?.in),u=n.getSeconds()/60,a=n.getMilliseconds()/1e3/60,o=n.getMinutes()+u+a,c=r?.roundingMethod??"round",d=(0,j2.getRoundingMethod)(c)(o/t)*t;return n.setMinutes(d,0,0),n}});var jb=s(Pb=>{"use strict";Pb.secondsToHours=W2;var Y2=O();function W2(e){let r=e/Y2.secondsInHour;return Math.trunc(r)}});var Tb=s(Ib=>{"use strict";Ib.secondsToMilliseconds=F2;var S2=O();function F2(e){return e*S2.millisecondsInSecond}});var Yb=s(Eb=>{"use strict";Eb.secondsToMinutes=H2;var N2=O();function H2(e){let r=e/N2.secondsInMinute;return Math.trunc(r)}});var xr=s(Wb=>{"use strict";Wb.setMonth=B2;var L2=b(),C2=bt(),z2=l();function B2(e,r,t){let n=(0,z2.toDate)(e,t?.in),u=n.getFullYear(),a=n.getDate(),o=(0,L2.constructFrom)(t?.in||e,0);o.setFullYear(u,r,15),o.setHours(0,0,0,0);let c=(0,C2.getDaysInMonth)(o);return n.setMonth(r,Math.min(a,c)),n}});var Fb=s(Sb=>{"use strict";Sb.set=$2;var Q2=b(),R2=xr(),A2=l();function $2(e,r,t){let n=(0,A2.toDate)(e,t?.in);return isNaN(+n)?(0,Q2.constructFrom)(t?.in||e,NaN):(r.year!=null&&n.setFullYear(r.year),r.month!=null&&(n=(0,R2.setMonth)(n,r.month)),r.date!=null&&n.setDate(r.date),r.hours!=null&&n.setHours(r.hours),r.minutes!=null&&n.setMinutes(r.minutes),r.seconds!=null&&n.setSeconds(r.seconds),r.milliseconds!=null&&n.setMilliseconds(r.milliseconds),n)}});var Hb=s(Nb=>{"use strict";Nb.setDate=X2;var Z2=l();function X2(e,r,t){let n=(0,Z2.toDate)(e,t?.in);return n.setDate(r),n}});var Cb=s(Lb=>{"use strict";Lb.setDayOfYear=G2;var V2=l();function G2(e,r,t){let n=(0,V2.toDate)(e,t?.in);return n.setMonth(0),n.setDate(r),n}});var Qb=s(Bb=>{"use strict";Bb.setDefaultOptions=U2;var zb=Y();function U2(e){let r={},t=(0,zb.getDefaultOptions)();for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n]);for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]===void 0?delete r[n]:r[n]=e[n]);(0,zb.setDefaultOptions)(r)}});var Ab=s(Rb=>{"use strict";Rb.setHours=K2;var J2=l();function K2(e,r,t){let n=(0,J2.toDate)(e,t?.in);return n.setHours(r),n}});var Zb=s($b=>{"use strict";$b.setMilliseconds=k2;var y2=l();function k2(e,r,t){let n=(0,y2.toDate)(e,t?.in);return n.setMilliseconds(r),n}});var Vb=s(Xb=>{"use strict";Xb.setMinutes=rY;var eY=l();function rY(e,r,t){let n=(0,eY.toDate)(e,t?.in);return n.setMinutes(r),n}});var Ub=s(Gb=>{"use strict";Gb.setQuarter=iY;var tY=xr(),nY=l();function iY(e,r,t){let n=(0,nY.toDate)(e,t?.in),u=Math.trunc(n.getMonth()/3)+1,a=r-u;return(0,tY.setMonth)(n,n.getMonth()+a*3)}});var Kb=s(Jb=>{"use strict";Jb.setSeconds=aY;var uY=l();function aY(e,r,t){let n=(0,uY.toDate)(e,t?.in);return n.setSeconds(r),n}});var eg=s(kb=>{"use strict";kb.setWeekYear=dY;var sY=Y(),oY=b(),cY=A(),yb=cr(),fY=l();function dY(e,r,t){let n=(0,sY.getDefaultOptions)(),u=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,a=(0,cY.differenceInCalendarDays)((0,fY.toDate)(e,t?.in),(0,yb.startOfWeekYear)(e,t),t),o=(0,oY.constructFrom)(t?.in||e,0);o.setFullYear(r,0,u),o.setHours(0,0,0,0);let c=(0,yb.startOfWeekYear)(o,t);return c.setDate(c.getDate()+a),c}});var tg=s(rg=>{"use strict";rg.setYear=_Y;var lY=b(),hY=l();function _Y(e,r,t){let n=(0,hY.toDate)(e,t?.in);return isNaN(+n)?(0,lY.constructFrom)(t?.in||e,NaN):(n.setFullYear(r),n)}});var ig=s(ng=>{"use strict";ng.startOfDecade=bY;var mY=l();function bY(e,r){let t=(0,mY.toDate)(e,r?.in),n=t.getFullYear(),u=Math.floor(n/10)*10;return t.setFullYear(u,0,1),t.setHours(0,0,0,0),t}});var ag=s(ug=>{"use strict";ug.startOfToday=vY;var gY=ve();function vY(e){return(0,gY.startOfDay)(Date.now(),e)}});var og=s(sg=>{"use strict";sg.startOfTomorrow=qY;var xY=b(),OY=T();function qY(e){let r=(0,OY.constructNow)(e?.in),t=r.getFullYear(),n=r.getMonth(),u=r.getDate(),a=(0,xY.constructFrom)(e?.in,0);return a.setFullYear(t,n,u+1),a.setHours(0,0,0,0),a}});var dg=s(fg=>{"use strict";fg.startOfYesterday=pY;var cg=T();function pY(e){let r=(0,cg.constructNow)(e?.in),t=r.getFullYear(),n=r.getMonth(),u=r.getDate(),a=(0,cg.constructNow)(e?.in);return a.setFullYear(t,n,u-1),a.setHours(0,0,0,0),a}});var di=s(lg=>{"use strict";lg.subMonths=DY;var MY=se();function DY(e,r,t){return(0,MY.addMonths)(e,-r,t)}});var _g=s(hg=>{"use strict";hg.sub=IY;var wY=b(),PY=ze(),jY=di();function IY(e,r,t){let{years:n=0,months:u=0,weeks:a=0,days:o=0,hours:c=0,minutes:f=0,seconds:d=0}=r,h=(0,jY.subMonths)(e,u+n*12,t),_=(0,PY.subDays)(h,o+a*7,t),g=f+c*60,q=(d+g*60)*1e3;return(0,wY.constructFrom)(t?.in||e,+_-q)}});var bg=s(mg=>{"use strict";mg.subBusinessDays=EY;var TY=Tr();function EY(e,r,t){return(0,TY.addBusinessDays)(e,-r,t)}});var vg=s(gg=>{"use strict";gg.subHours=WY;var YY=Er();function WY(e,r,t){return(0,YY.addHours)(e,-r,t)}});var Og=s(xg=>{"use strict";xg.subMilliseconds=FY;var SY=ge();function FY(e,r,t){return(0,SY.addMilliseconds)(e,-r,t)}});var pg=s(qg=>{"use strict";qg.subMinutes=HY;var NY=Ze();function HY(e,r,t){return(0,NY.addMinutes)(e,-r,t)}});var Dg=s(Mg=>{"use strict";Mg.subQuarters=CY;var LY=Xe();function CY(e,r,t){return(0,LY.addQuarters)(e,-r,t)}});var Pg=s(wg=>{"use strict";wg.subSeconds=BY;var zY=Fr();function BY(e,r,t){return(0,zY.addSeconds)(e,-r,t)}});var Ig=s(jg=>{"use strict";jg.subWeeks=RY;var QY=xe();function RY(e,r,t){return(0,QY.addWeeks)(e,-r,t)}});var Eg=s(Tg=>{"use strict";Tg.subYears=$Y;var AY=Nr();function $Y(e,r,t){return(0,AY.addYears)(e,-r,t)}});var Wg=s(Yg=>{"use strict";Yg.weeksToDays=XY;var ZY=O();function XY(e){return Math.trunc(e*ZY.daysInWeek)}});var Fg=s(Sg=>{"use strict";Sg.yearsToDays=GY;var VY=O();function GY(e){return Math.trunc(e*VY.daysInYear)}});var Hg=s(Ng=>{"use strict";Ng.yearsToMonths=JY;var UY=O();function JY(e){return Math.trunc(e*UY.monthsInYear)}});var Cg=s(Lg=>{"use strict";Lg.yearsToQuarters=yY;var KY=O();function yY(e){return Math.trunc(e*KY.quartersInYear)}});var zg=s(i=>{"use strict";var li=wr();Object.keys(li).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===li[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return li[e]}})});var hi=Tr();Object.keys(hi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===hi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return hi[e]}})});var _i=H();Object.keys(_i).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===_i[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return _i[e]}})});var mi=Er();Object.keys(mi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===mi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return mi[e]}})});var bi=Sr();Object.keys(bi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===bi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return bi[e]}})});var gi=ge();Object.keys(gi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===gi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return gi[e]}})});var vi=Ze();Object.keys(vi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===vi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return vi[e]}})});var xi=se();Object.keys(xi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===xi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return xi[e]}})});var Oi=Xe();Object.keys(Oi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Oi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Oi[e]}})});var qi=Fr();Object.keys(qi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===qi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return qi[e]}})});var pi=xe();Object.keys(pi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===pi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return pi[e]}})});var Mi=Nr();Object.keys(Mi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Mi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Mi[e]}})});var Di=Hc();Object.keys(Di).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Di[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Di[e]}})});var wi=Rc();Object.keys(wi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===wi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return wi[e]}})});var Pi=Cr();Object.keys(Pi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Pi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Pi[e]}})});var ji=Xc();Object.keys(ji).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ji[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ji[e]}})});var Ii=re();Object.keys(Ii).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ii[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ii[e]}})});var Ti=Kc();Object.keys(Ti).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ti[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ti[e]}})});var Ei=b();Object.keys(Ei).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ei[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ei[e]}})});var Yi=T();Object.keys(Yi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Yi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Yi[e]}})});var Wi=ef();Object.keys(Wi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Wi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Wi[e]}})});var Si=cf();Object.keys(Si).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Si[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Si[e]}})});var Fi=A();Object.keys(Fi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Fi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Fi[e]}})});var Ni=Br();Object.keys(Ni).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ni[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ni[e]}})});var Hi=mf();Object.keys(Hi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Hi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Hi[e]}})});var Li=Ge();Object.keys(Li).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Li[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Li[e]}})});var Ci=Rr();Object.keys(Ci).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ci[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ci[e]}})});var zi=Ue();Object.keys(zi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===zi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return zi[e]}})});var Bi=Je();Object.keys(Bi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Bi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Bi[e]}})});var Qi=Ke();Object.keys(Qi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Qi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Qi[e]}})});var Ri=ye();Object.keys(Ri).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ri[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ri[e]}})});var Ai=Yf();Object.keys(Ai).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ai[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ai[e]}})});var $i=ke();Object.keys($i).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===$i[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return $i[e]}})});var Zi=er();Object.keys(Zi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Zi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Zi[e]}})});var Xi=Oe();Object.keys(Xi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Xi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Xi[e]}})});var Vi=Bf();Object.keys(Vi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Vi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Vi[e]}})});var Gi=qe();Object.keys(Gi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Gi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Gi[e]}})});var Ui=Af();Object.keys(Ui).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ui[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ui[e]}})});var Ji=Xr();Object.keys(Ji).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ji[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ji[e]}})});var Ki=Vr();Object.keys(Ki).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ki[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ki[e]}})});var yi=Uf();Object.keys(yi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===yi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return yi[e]}})});var ki=Kf();Object.keys(ki).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ki[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ki[e]}})});var eu=kf();Object.keys(eu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===eu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return eu[e]}})});var ru=td();Object.keys(ru).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ru[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ru[e]}})});var tu=id();Object.keys(tu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===tu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return tu[e]}})});var nu=ar();Object.keys(nu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===nu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return nu[e]}})});var iu=od();Object.keys(iu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===iu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return iu[e]}})});var uu=ld();Object.keys(uu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===uu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return uu[e]}})});var au=_d();Object.keys(au).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===au[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return au[e]}})});var su=rr();Object.keys(su).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===su[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return su[e]}})});var ou=bd();Object.keys(ou).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ou[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ou[e]}})});var cu=vd();Object.keys(cu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===cu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return cu[e]}})});var fu=qd();Object.keys(fu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===fu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return fu[e]}})});var du=Md();Object.keys(du).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===du[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return du[e]}})});var lu=wd();Object.keys(lu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===lu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return lu[e]}})});var hu=tr();Object.keys(hu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===hu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return hu[e]}})});var _u=jd();Object.keys(_u).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===_u[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return _u[e]}})});var mu=Td();Object.keys(mu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===mu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return mu[e]}})});var bu=Yd();Object.keys(bu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===bu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return bu[e]}})});var gu=Fd();Object.keys(gu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===gu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return gu[e]}})});var vu=Ur();Object.keys(vu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===vu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return vu[e]}})});var xu=Gr();Object.keys(xu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===xu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return xu[e]}})});var Ou=Hd();Object.keys(Ou).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ou[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ou[e]}})});var qu=lt();Object.keys(qu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===qu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return qu[e]}})});var pu=ht();Object.keys(pu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===pu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return pu[e]}})});var Mu=_t();Object.keys(Mu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Mu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Mu[e]}})});var Du=gl();Object.keys(Du).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Du[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Du[e]}})});var wu=xl();Object.keys(wu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===wu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return wu[e]}})});var Pu=ql();Object.keys(Pu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Pu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Pu[e]}})});var ju=Ml();Object.keys(ju).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ju[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ju[e]}})});var Iu=wl();Object.keys(Iu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Iu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Iu[e]}})});var Tu=jl();Object.keys(Tu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Tu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Tu[e]}})});var Eu=Tl();Object.keys(Eu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Eu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Eu[e]}})});var Yu=Yl();Object.keys(Yu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Yu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Yu[e]}})});var Wu=Sl();Object.keys(Wu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Wu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Wu[e]}})});var Su=Nl();Object.keys(Su).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Su[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Su[e]}})});var Fu=mt();Object.keys(Fu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Fu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Fu[e]}})});var Nu=je();Object.keys(Nu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Nu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Nu[e]}})});var Hu=nt();Object.keys(Hu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Hu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Hu[e]}})});var Lu=bt();Object.keys(Lu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Lu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Lu[e]}})});var Cu=Ql();Object.keys(Cu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Cu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Cu[e]}})});var zu=Al();Object.keys(zu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===zu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return zu[e]}})});var Bu=vt();Object.keys(Bu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Bu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Bu[e]}})});var Qu=Xl();Object.keys(Qu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Qu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Qu[e]}})});var Ru=xt();Object.keys(Ru).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ru[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ru[e]}})});var Au=or();Object.keys(Au).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Au[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Au[e]}})});var $u=U();Object.keys($u).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===$u[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return $u[e]}})});var Zu=Jl();Object.keys(Zu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Zu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Zu[e]}})});var Xu=yl();Object.keys(Xu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Xu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Xu[e]}})});var Vu=eh();Object.keys(Vu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Vu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Vu[e]}})});var Gu=th();Object.keys(Gu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Gu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Gu[e]}})});var Uu=uh();Object.keys(Uu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Uu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Uu[e]}})});var Ju=Qr();Object.keys(Ju).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ju[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ju[e]}})});var Ku=sh();Object.keys(Ku).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ku[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ku[e]}})});var yu=ch();Object.keys(yu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===yu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return yu[e]}})});var ku=dh();Object.keys(ku).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ku[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ku[e]}})});var ea=fr();Object.keys(ea).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ea[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ea[e]}})});var ra=hh();Object.keys(ra).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ra[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ra[e]}})});var ta=we();Object.keys(ta).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ta[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ta[e]}})});var na=gh();Object.keys(na).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===na[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return na[e]}})});var ia=xh();Object.keys(ia).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ia[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ia[e]}})});var ua=qh();Object.keys(ua).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ua[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ua[e]}})});var aa=Mh();Object.keys(aa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===aa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return aa[e]}})});var sa=wh();Object.keys(sa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===sa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return sa[e]}})});var oa=jh();Object.keys(oa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===oa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return oa[e]}})});var ca=Th();Object.keys(ca).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ca[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ca[e]}})});var fa=Yh();Object.keys(fa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===fa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return fa[e]}})});var da=Lh();Object.keys(da).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===da[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return da[e]}})});var la=Bh();Object.keys(la).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===la[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return la[e]}})});var ha=Ah();Object.keys(ha).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ha[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ha[e]}})});var _a=zr();Object.keys(_a).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===_a[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return _a[e]}})});var ma=Xh();Object.keys(ma).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ma[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ma[e]}})});var ba=Gh();Object.keys(ba).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ba[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ba[e]}})});var ga=Jh();Object.keys(ga).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ga[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ga[e]}})});var va=yh();Object.keys(va).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===va[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return va[e]}})});var xa=e_();Object.keys(xa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===xa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return xa[e]}})});var Oa=$r();Object.keys(Oa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Oa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Oa[e]}})});var qa=gt();Object.keys(qa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===qa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return qa[e]}})});var pa=rm();Object.keys(pa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===pa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return pa[e]}})});var Ma=nm();Object.keys(Ma).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ma[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ma[e]}})});var Da=um();Object.keys(Da).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Da[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Da[e]}})});var wa=ce();Object.keys(wa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===wa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return wa[e]}})});var Pa=yn();Object.keys(Pa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Pa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Pa[e]}})});var ja=kn();Object.keys(ja).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ja[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ja[e]}})});var Ia=_m();Object.keys(Ia).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ia[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ia[e]}})});var Ta=ri();Object.keys(Ta).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ta[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ta[e]}})});var Ea=ti();Object.keys(Ea).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ea[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ea[e]}})});var Ya=ni();Object.keys(Ya).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ya[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ya[e]}})});var Wa=ui();Object.keys(Wa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Wa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Wa[e]}})});var Sa=br();Object.keys(Sa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Sa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Sa[e]}})});var Fa=ai();Object.keys(Fa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Fa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Fa[e]}})});var Na=Pr();Object.keys(Na).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Na[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Na[e]}})});var Ha=jr();Object.keys(Ha).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ha[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ha[e]}})});var La=Pm();Object.keys(La).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===La[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return La[e]}})});var Ca=Im();Object.keys(Ca).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ca[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ca[e]}})});var za=Em();Object.keys(za).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===za[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return za[e]}})});var Ba=Wm();Object.keys(Ba).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ba[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ba[e]}})});var Qa=Fm();Object.keys(Qa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Qa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Qa[e]}})});var Ra=Hm();Object.keys(Ra).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ra[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ra[e]}})});var Aa=Cm();Object.keys(Aa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Aa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Aa[e]}})});var $a=Bm();Object.keys($a).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===$a[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return $a[e]}})});var Za=Rm();Object.keys(Za).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Za[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Za[e]}})});var Xa=$m();Object.keys(Xa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Xa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Xa[e]}})});var Va=Xm();Object.keys(Va).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Va[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Va[e]}})});var Ga=Gm();Object.keys(Ga).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ga[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ga[e]}})});var Ua=$();Object.keys(Ua).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ua[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ua[e]}})});var Ja=Jm();Object.keys(Ja).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ja[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ja[e]}})});var Ka=be();Object.keys(Ka).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ka[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ka[e]}})});var ya=ym();Object.keys(ya).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ya[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ya[e]}})});var ka=r0();Object.keys(ka).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ka[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ka[e]}})});var es=i0();Object.keys(es).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===es[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return es[e]}})});var rs=s0();Object.keys(rs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===rs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return rs[e]}})});var ts=c0();Object.keys(ts).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ts[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ts[e]}})});var ns=Ot();Object.keys(ns).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ns[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ns[e]}})});var is=d0();Object.keys(is).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===is[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return is[e]}})});var us=oi();Object.keys(us).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===us[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return us[e]}})});var as=h0();Object.keys(as).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===as[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return as[e]}})});var ss=m0();Object.keys(ss).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ss[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ss[e]}})});var os=Hr();Object.keys(os).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===os[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return os[e]}})});var cs=v0();Object.keys(cs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===cs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return cs[e]}})});var fs=O0();Object.keys(fs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===fs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return fs[e]}})});var ds=p0();Object.keys(ds).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ds[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ds[e]}})});var ls=D0();Object.keys(ls).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ls[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ls[e]}})});var hs=Lr();Object.keys(hs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===hs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return hs[e]}})});var _s=P0();Object.keys(_s).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===_s[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return _s[e]}})});var ms=I0();Object.keys(ms).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ms[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ms[e]}})});var bs=E0();Object.keys(bs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===bs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return bs[e]}})});var gs=W0();Object.keys(gs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===gs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return gs[e]}})});var vs=F0();Object.keys(vs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===vs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return vs[e]}})});var xs=V();Object.keys(xs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===xs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return xs[e]}})});var Os=L0();Object.keys(Os).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Os[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Os[e]}})});var qs=z0();Object.keys(qs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===qs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return qs[e]}})});var ps=Q0();Object.keys(ps).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ps[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ps[e]}})});var Ms=A0();Object.keys(Ms).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ms[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ms[e]}})});var Ds=Z0();Object.keys(Ds).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ds[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ds[e]}})});var ws=V0();Object.keys(ws).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ws[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ws[e]}})});var Ps=U0();Object.keys(Ps).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ps[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ps[e]}})});var js=Jn();Object.keys(js).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===js[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return js[e]}})});var Is=k0();Object.keys(Is).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Is[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Is[e]}})});var Ts=tb();Object.keys(Ts).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ts[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ts[e]}})});var Es=G();Object.keys(Es).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Es[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Es[e]}})});var Ys=ub();Object.keys(Ys).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ys[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ys[e]}})});var Ws=sb();Object.keys(Ws).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ws[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ws[e]}})});var Ss=cb();Object.keys(Ss).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ss[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ss[e]}})});var Fs=db();Object.keys(Fs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Fs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Fs[e]}})});var Ns=hb();Object.keys(Ns).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ns[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ns[e]}})});var Hs=mb();Object.keys(Hs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Hs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Hs[e]}})});var Ls=gb();Object.keys(Ls).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ls[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ls[e]}})});var Cs=xb();Object.keys(Cs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Cs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Cs[e]}})});var zs=qb();Object.keys(zs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===zs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return zs[e]}})});var Bs=Mb();Object.keys(Bs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Bs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Bs[e]}})});var Qs=wb();Object.keys(Qs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Qs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Qs[e]}})});var Rs=jb();Object.keys(Rs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Rs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Rs[e]}})});var As=Tb();Object.keys(As).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===As[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return As[e]}})});var $s=Yb();Object.keys($s).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===$s[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return $s[e]}})});var Zs=Fb();Object.keys(Zs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Zs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Zs[e]}})});var Xs=Hb();Object.keys(Xs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Xs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Xs[e]}})});var Vs=Se();Object.keys(Vs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Vs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Vs[e]}})});var Gs=Cb();Object.keys(Gs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Gs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Gs[e]}})});var Us=Qb();Object.keys(Us).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Us[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Us[e]}})});var Js=Ab();Object.keys(Js).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Js[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Js[e]}})});var Ks=gn();Object.keys(Ks).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ks[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ks[e]}})});var ys=kt();Object.keys(ys).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ys[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ys[e]}})});var ks=Wr();Object.keys(ks).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ks[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ks[e]}})});var eo=Zb();Object.keys(eo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===eo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return eo[e]}})});var ro=Vb();Object.keys(ro).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ro[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ro[e]}})});var to=xr();Object.keys(to).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===to[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return to[e]}})});var no=Ub();Object.keys(no).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===no[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return no[e]}})});var io=Kb();Object.keys(io).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===io[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return io[e]}})});var uo=Jt();Object.keys(uo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===uo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return uo[e]}})});var ao=eg();Object.keys(ao).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ao[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ao[e]}})});var so=tg();Object.keys(so).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===so[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return so[e]}})});var oo=ve();Object.keys(oo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===oo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return oo[e]}})});var co=ig();Object.keys(co).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===co[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return co[e]}})});var fo=Kn();Object.keys(fo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===fo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return fo[e]}})});var lo=L();Object.keys(lo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===lo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return lo[e]}})});var ho=oe();Object.keys(ho).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ho[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ho[e]}})});var _o=ei();Object.keys(_o).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===_o[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return _o[e]}})});var mo=pe();Object.keys(mo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===mo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return mo[e]}})});var bo=nr();Object.keys(bo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===bo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return bo[e]}})});var go=ii();Object.keys(go).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===go[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return go[e]}})});var vo=ag();Object.keys(vo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===vo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return vo[e]}})});var xo=og();Object.keys(xo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===xo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return xo[e]}})});var Oo=N();Object.keys(Oo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Oo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Oo[e]}})});var qo=cr();Object.keys(qo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===qo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return qo[e]}})});var po=sr();Object.keys(po).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===po[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return po[e]}})});var Mo=dg();Object.keys(Mo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Mo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Mo[e]}})});var Do=_g();Object.keys(Do).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Do[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Do[e]}})});var wo=bg();Object.keys(wo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===wo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return wo[e]}})});var Po=ze();Object.keys(Po).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Po[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Po[e]}})});var jo=vg();Object.keys(jo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===jo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return jo[e]}})});var Io=Ar();Object.keys(Io).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Io[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Io[e]}})});var To=Og();Object.keys(To).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===To[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return To[e]}})});var Eo=pg();Object.keys(Eo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Eo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Eo[e]}})});var Yo=di();Object.keys(Yo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Yo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Yo[e]}})});var Wo=Dg();Object.keys(Wo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Wo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Wo[e]}})});var So=Pg();Object.keys(So).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===So[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return So[e]}})});var Fo=Ig();Object.keys(Fo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Fo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Fo[e]}})});var No=Eg();Object.keys(No).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===No[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return No[e]}})});var Ho=l();Object.keys(Ho).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ho[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ho[e]}})});var Lo=wt();Object.keys(Lo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Lo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Lo[e]}})});var Co=Wg();Object.keys(Co).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Co[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Co[e]}})});var zo=Fg();Object.keys(zo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===zo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return zo[e]}})});var Bo=Hg();Object.keys(Bo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Bo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Bo[e]}})});var Qo=Cg();Object.keys(Qo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Qo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Qo[e]}})})});var Ug=s((QL,Gg)=>{"use strict";var{readdir:Bg,stat:Qg,unlink:Ro,symlink:kY,lstat:eW,readlink:rW}=require("fs/promises"),{dirname:Rg,join:Or}=require("path"),{format:tW,addDays:nW,addHours:iW,parse:uW,isValid:aW}=zg();function sW(e){let r=1048576;if(typeof e!="string"&&typeof e!="number")return null;if(typeof e=="string"){let t=e.match(/^([\d.]+)(\w?)$/);if(t){let n=t[2]?.toLowerCase();e=+t[1],r=n==="g"?1024**3:n==="k"?1024:n==="b"?1:1024**2}else throw new Error(`${e} is not a valid size in KB, MB or GB`)}return e*r}function oW(e){let r=new Date;if(e==="daily"){let t=r.setHours(0,0,0,0);return{frequency:e,start:t,next:Ag(t)}}if(e==="hourly"){let t=r.setMinutes(0,0,0);return{frequency:e,start:t,next:$g(t)}}if(typeof e=="number"){let t=r.getTime()-r.getTime()%e;return{frequency:e,start:t,next:Zg(e)}}if(e)throw new Error(`${e} is neither a supported frequency or a number of milliseconds`);return null}function cW(e){if(e){if(typeof e!="object")throw new Error("limit must be an object");if(typeof e.count!="number"||e.count<=0)throw new Error("limit.count must be a number greater than 0");if(typeof e.removeOtherLogFiles<"u"&&typeof e.removeOtherLogFiles!="boolean")throw new Error("limit.removeOtherLogFiles must be boolean")}}function Ag(e){return nW(new Date(e),1).setHours(0,0,0,0)}function $g(e){return iW(new Date(e),1).setMinutes(0,0,0)}function Zg(e){let r=Date.now();return r-r%e+e}function fW(e){return e==="daily"?Ag(new Date().setHours(0,0,0,0)):e==="hourly"?$g(new Date().setMinutes(0,0,0)):Zg(e)}function Qe(e){if(!e)throw new Error("No file name provided");return typeof e=="function"?e():e}function dW(e,r,t=1,n){let u=r?`.${r}`:"",a=typeof n!="string"?"":n.startsWith(".")?n:`.${n}`;return`${Qe(e)}${u}.${t}${a}`}function Xg(e,r,t,n){let u=Qe(r);if(!e.startsWith(u))return!1;let a=e.slice(u.length+1).split("."),o=1;typeof t=="string"&&t.length>0&&o++,typeof n=="string"&&n.length>0&&o++;let c=typeof n!="string"?"":n.startsWith(".")?n.slice(1):n;if(a.length!==o)return!1;if(c.length>0){let _=a.pop();if(c!==_)return!1}let f=a.pop(),d=Number(f);if(!Number.isInteger(d))return!1;let h=0;if(typeof t=="string"&&t.length>0){let _=uW(a[0],t,new Date);if(!aW(_))return!1;h=_.getTime()}return{fileName:e,fileTime:h,fileNumber:d}}async function lW(e){try{return(await Qg(e)).size}catch{return 0}}async function hW(e,r=null){let t=Qe(e);try{return(await _W(Rg(t),r)).sort((u,a)=>a-u)[0]}catch{return 1}}async function _W(e,r){let t=[1];for(let n of await Bg(e)){if(r&&!await bW(Or(e,n),r))continue;let u=mW(n);u&&t.push(u)}return t}function mW(e){let r=e.match(/(\d+)$/);return r?+r[1]:null}function qr(e){return e.split(/(\\|\/)/g).pop()}async function bW(e,r){let{birthtimeMs:t}=await Qg(e);return t>=r}async function gW({count:e,removeOtherLogFiles:r,baseFile:t,dateFormat:n,extension:u,createdFileNames:a,newFileName:o}){if(r){let c=[],f=Qe(t).split(/(\\|\/)/g),d=f.pop();for(let h of await Bg(Or(...f))){let _=Xg(h,d,n,u);_&&c.push(_)}c=c.sort((h,_)=>h.fileTime===_.fileTime?h.fileNumber-_.fileNumber:h.fileTime-_.fileTime),c.length>e&&await Promise.allSettled(c.slice(0,c.length-e).map(h=>Ro(Or(...f,h.fileName))))}else if(a.push(o),a.length>e){let c=a.splice(0,a.length-1-e);await Promise.allSettled(c.map(f=>Ro(f)))}}async function Vg(e,r){if((await eW(r).then(n=>n,()=>null))?.isSymbolicLink()){let n=await rW(r);if(qr(n)===qr(e))return!1;await Ro(r)}return!0}async function vW(e){let r=Or(Rg(e),"current.log");return await Vg(e,r)&&await kY(qr(e),r),!1}function xW(e){if(/[/\\?%*:|"<>]/g.test(e))throw new Error(`${e} contains invalid characters`);return!0}function OW(e,r,t=!1){if(!(e&&r?.start&&r.next))return null;try{return tW(t?r.start:r.next,e)}catch{throw new Error(`${e} must be a valid date format`)}}Gg.exports={buildFileName:dW,identifyLogFile:Xg,removeOldFiles:gW,checkSymlink:Vg,createSymlink:vW,detectLastNumber:hW,extractFileName:qr,parseFrequency:oW,getNext:fW,parseSize:sW,getFileName:Qe,getFileSize:lW,validateLimitOptions:cW,parseDate:OW,validateDateFormat:xW}});var qW=ko(),{buildFileName:Ao,removeOldFiles:pW,createSymlink:Jg,detectLastNumber:MW,parseSize:DW,parseFrequency:wW,getNext:PW,getFileSize:jW,validateLimitOptions:IW,parseDate:Kg,validateDateFormat:TW}=Ug();module.exports=async function({file:e,size:r,frequency:t,extension:n,limit:u,symlink:a,dateFormat:o,...c}={}){IW(u),TW(o);let f=wW(t),d=Kg(o,f,!0),h=await MW(e,f?.start,o),_=Ao(e,d,h,n),g=[_],p=await jW(_),q=DW(r),x=new qW({...c,dest:_});a&&Jg(_);let m;f&&(x.once("close",()=>{clearTimeout(m)}),E()),q&&x.on("write",B=>{p+=B,_===x.file&&p>=q&&(p=0,_=Ao(e,d,++h,n),x.once("drain",D))});function D(){x.reopen(_),a&&Jg(_),u&&pW({...u,baseFile:e,dateFormat:o,extension:n,createdFileNames:g,newFileName:_})}function E(){clearTimeout(m),m=setTimeout(()=>{let B=d;d=Kg(o,f),o&&d&&d!==B&&(h=0),_=Ao(e,d,++h,n),D(),f.next=PW(t),E()},f.next-Date.now())}return x}; +//# sourceMappingURL=pino-roll.cjs.map diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/pino-roll.cjs.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/pino-roll.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..5f862a5b43c268386dedfbdd002004b24c7c7f9f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/pino-roll.cjs.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/.pnpm/atomic-sleep@1.0.0/node_modules/atomic-sleep/index.js", "../../node_modules/.pnpm/sonic-boom@4.2.0/node_modules/sonic-boom/index.js", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/constants.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/constructFrom.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/toDate.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addMonths.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/add.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSaturday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSunday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isWeekend.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addBusinessDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/defaultOptions.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfISOWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISOWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/getTimezoneOffsetInMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/normalizeDates.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfDay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfISOWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setISOWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addISOWeekYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addQuarters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addWeeks.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/areIntervalsOverlapping.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/max.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/min.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/clamp.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/closestIndexTo.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/closestTo.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/compareAsc.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/compareDesc.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/constructNow.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/daysToWeeks.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameDay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isDate.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isValid.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInBusinessDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarISOWeekYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarISOWeeks.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarMonths.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getQuarter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarQuarters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarWeeks.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/getRoundingMethod.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subISOWeekYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInISOWeekYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfDay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isLastDayOfMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInMonths.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInQuarters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInWeeks.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/normalizeInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachDayOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachHourOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachMinuteOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachMonthOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfQuarter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachQuarterOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachWeekOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachWeekendOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachWeekendOfMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachWeekendOfYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachYearOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfDecade.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfHour.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfISOWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfISOWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfMinute.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfQuarter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfSecond.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfToday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfTomorrow.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfYesterday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/formatDistance.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildFormatLongFn.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/formatLong.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/formatRelative.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildLocalizeFn.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/localize.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildMatchFn.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildMatchPatternFn.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/match.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/defaultLocale.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDayOfYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISOWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/addLeadingZeros.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/format/lightFormatters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/format/formatters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/format/longFormatters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/protectedTokens.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/format.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistance.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistanceStrict.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistanceToNow.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistanceToNowStrict.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDuration.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatISO.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatISO9075.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatISODuration.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatRFC3339.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatRFC7231.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatRelative.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/fromUnixTime.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDate.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDaysInMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isLeapYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDaysInYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDecade.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDefaultOptions.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISODay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISOWeeksInYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getOverlappingDaysInIntervals.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getTime.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getUnixTime.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeekOfMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeeksInMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/hoursToMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/hoursToMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/hoursToSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/interval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/intervalToDuration.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/intlFormat.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/intlFormatDistance.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isAfter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isBefore.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isEqual.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isExists.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isFirstDayOfMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isFriday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isFuture.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/transpose.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/Setter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/Parser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/EraParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/constants.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/utils.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/YearParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/LocalWeekYearParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/ISOWeekYearParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/ExtendedYearParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/QuarterParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/StandAloneQuarterParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/MonthParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/StandAloneMonthParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/LocalWeekParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setISOWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/ISOWeekParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/DateParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/DayOfYearParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setDay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/DayParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/LocalDayParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/StandAloneLocalDayParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setISODay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/ISODayParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/AMPMParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/AMPMMidnightParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/DayPeriodParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/Hour1to12Parser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/Hour0to23Parser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/Hour0To11Parser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/Hour1To24Parser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/MinuteParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/SecondParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/FractionOfSecondParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/ISOTimezoneWithZParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/ISOTimezoneParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/TimestampSecondsParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/TimestampMillisecondsParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isMatch.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isMonday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isPast.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfHour.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameHour.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameISOWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameISOWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfMinute.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameMinute.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameQuarter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfSecond.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameSecond.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisHour.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisISOWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisMinute.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisQuarter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisSecond.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThursday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isToday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isTomorrow.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isTuesday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isWednesday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isWithinInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isYesterday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfDecade.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfISOWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfISOWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfQuarter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lightFormat.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/milliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/millisecondsToHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/millisecondsToMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/millisecondsToSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/minutesToHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/minutesToMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/minutesToSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/monthsToQuarters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/monthsToYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextDay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextFriday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextMonday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextSaturday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextSunday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextThursday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextTuesday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextWednesday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parseISO.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parseJSON.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousDay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousFriday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousMonday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousSaturday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousSunday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousThursday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousTuesday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousWednesday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/quartersToMonths.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/quartersToYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/roundToNearestHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/roundToNearestMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/secondsToHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/secondsToMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/secondsToMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/set.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setDate.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setDayOfYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setDefaultOptions.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setQuarter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfDecade.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfToday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfTomorrow.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfYesterday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subMonths.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/sub.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subBusinessDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subQuarters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subWeeks.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/weeksToDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/yearsToDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/yearsToMonths.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/yearsToQuarters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/index.cjs", "../../node_modules/.pnpm/pino-roll@3.1.0/node_modules/pino-roll/lib/utils.js", "../../node_modules/.pnpm/pino-roll@3.1.0/node_modules/pino-roll/pino-roll.js"], + "sourcesContent": ["'use strict'\n\n/* global SharedArrayBuffer, Atomics */\n\nif (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') {\n const nil = new Int32Array(new SharedArrayBuffer(4))\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n\n Atomics.wait(nil, 0, 0, Number(ms))\n }\n module.exports = sleep\n} else {\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n const target = Date.now() + Number(ms)\n while (target > Date.now()){}\n }\n\n module.exports = sleep\n\n}\n", "'use strict'\n\nconst fs = require('fs')\nconst EventEmitter = require('events')\nconst inherits = require('util').inherits\nconst path = require('path')\nconst sleep = require('atomic-sleep')\nconst assert = require('assert')\n\nconst BUSY_WRITE_TIMEOUT = 100\nconst kEmptyBuffer = Buffer.allocUnsafe(0)\n\n// 16 KB. Don't write more than docker buffer size.\n// https://github.com/moby/moby/blob/513ec73831269947d38a644c278ce3cac36783b2/daemon/logger/copier.go#L13\nconst MAX_WRITE = 16 * 1024\n\nconst kContentModeBuffer = 'buffer'\nconst kContentModeUtf8 = 'utf8'\n\nconst [major, minor] = (process.versions.node || '0.0').split('.').map(Number)\nconst kCopyBuffer = major >= 22 && minor >= 7\n\nfunction openFile (file, sonic) {\n sonic._opening = true\n sonic._writing = true\n sonic._asyncDrainScheduled = false\n\n // NOTE: 'error' and 'ready' events emitted below only relevant when sonic.sync===false\n // for sync mode, there is no way to add a listener that will receive these\n\n function fileOpened (err, fd) {\n if (err) {\n sonic._reopening = false\n sonic._writing = false\n sonic._opening = false\n\n if (sonic.sync) {\n process.nextTick(() => {\n if (sonic.listenerCount('error') > 0) {\n sonic.emit('error', err)\n }\n })\n } else {\n sonic.emit('error', err)\n }\n return\n }\n\n const reopening = sonic._reopening\n\n sonic.fd = fd\n sonic.file = file\n sonic._reopening = false\n sonic._opening = false\n sonic._writing = false\n\n if (sonic.sync) {\n process.nextTick(() => sonic.emit('ready'))\n } else {\n sonic.emit('ready')\n }\n\n if (sonic.destroyed) {\n return\n }\n\n // start\n if ((!sonic._writing && sonic._len > sonic.minLength) || sonic._flushPending) {\n sonic._actualWrite()\n } else if (reopening) {\n process.nextTick(() => sonic.emit('drain'))\n }\n }\n\n const flags = sonic.append ? 'a' : 'w'\n const mode = sonic.mode\n\n if (sonic.sync) {\n try {\n if (sonic.mkdir) fs.mkdirSync(path.dirname(file), { recursive: true })\n const fd = fs.openSync(file, flags, mode)\n fileOpened(null, fd)\n } catch (err) {\n fileOpened(err)\n throw err\n }\n } else if (sonic.mkdir) {\n fs.mkdir(path.dirname(file), { recursive: true }, (err) => {\n if (err) return fileOpened(err)\n fs.open(file, flags, mode, fileOpened)\n })\n } else {\n fs.open(file, flags, mode, fileOpened)\n }\n}\n\nfunction SonicBoom (opts) {\n if (!(this instanceof SonicBoom)) {\n return new SonicBoom(opts)\n }\n\n let { fd, dest, minLength, maxLength, maxWrite, periodicFlush, sync, append = true, mkdir, retryEAGAIN, fsync, contentMode, mode } = opts || {}\n\n fd = fd || dest\n\n this._len = 0\n this.fd = -1\n this._bufs = []\n this._lens = []\n this._writing = false\n this._ending = false\n this._reopening = false\n this._asyncDrainScheduled = false\n this._flushPending = false\n this._hwm = Math.max(minLength || 0, 16387)\n this.file = null\n this.destroyed = false\n this.minLength = minLength || 0\n this.maxLength = maxLength || 0\n this.maxWrite = maxWrite || MAX_WRITE\n this._periodicFlush = periodicFlush || 0\n this._periodicFlushTimer = undefined\n this.sync = sync || false\n this.writable = true\n this._fsync = fsync || false\n this.append = append || false\n this.mode = mode\n this.retryEAGAIN = retryEAGAIN || (() => true)\n this.mkdir = mkdir || false\n\n let fsWriteSync\n let fsWrite\n if (contentMode === kContentModeBuffer) {\n this._writingBuf = kEmptyBuffer\n this.write = writeBuffer\n this.flush = flushBuffer\n this.flushSync = flushBufferSync\n this._actualWrite = actualWriteBuffer\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf)\n fsWrite = () => fs.write(this.fd, this._writingBuf, this.release)\n } else if (contentMode === undefined || contentMode === kContentModeUtf8) {\n this._writingBuf = ''\n this.write = write\n this.flush = flush\n this.flushSync = flushSync\n this._actualWrite = actualWrite\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf, 'utf8')\n fsWrite = () => fs.write(this.fd, this._writingBuf, 'utf8', this.release)\n } else {\n throw new Error(`SonicBoom supports \"${kContentModeUtf8}\" and \"${kContentModeBuffer}\", but passed ${contentMode}`)\n }\n\n if (typeof fd === 'number') {\n this.fd = fd\n process.nextTick(() => this.emit('ready'))\n } else if (typeof fd === 'string') {\n openFile(fd, this)\n } else {\n throw new Error('SonicBoom supports only file descriptors and files')\n }\n if (this.minLength >= this.maxWrite) {\n throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`)\n }\n\n this.release = (err, n) => {\n if (err) {\n if ((err.code === 'EAGAIN' || err.code === 'EBUSY') && this.retryEAGAIN(err, this._writingBuf.length, this._len - this._writingBuf.length)) {\n if (this.sync) {\n // This error code should not happen in sync mode, because it is\n // not using the underlining operating system asynchronous functions.\n // However it happens, and so we handle it.\n // Ref: https://github.com/pinojs/pino/issues/783\n try {\n sleep(BUSY_WRITE_TIMEOUT)\n this.release(undefined, 0)\n } catch (err) {\n this.release(err)\n }\n } else {\n // Let's give the destination some time to process the chunk.\n setTimeout(fsWrite, BUSY_WRITE_TIMEOUT)\n }\n } else {\n this._writing = false\n\n this.emit('error', err)\n }\n return\n }\n\n this.emit('write', n)\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n\n if (this._writingBuf.length) {\n if (!this.sync) {\n fsWrite()\n return\n }\n\n try {\n do {\n const n = fsWriteSync()\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n } while (this._writingBuf.length)\n } catch (err) {\n this.release(err)\n return\n }\n }\n\n if (this._fsync) {\n fs.fsyncSync(this.fd)\n }\n\n const len = this._len\n if (this._reopening) {\n this._writing = false\n this._reopening = false\n this.reopen()\n } else if (len > this.minLength) {\n this._actualWrite()\n } else if (this._ending) {\n if (len > 0) {\n this._actualWrite()\n } else {\n this._writing = false\n actualClose(this)\n }\n } else {\n this._writing = false\n if (this.sync) {\n if (!this._asyncDrainScheduled) {\n this._asyncDrainScheduled = true\n process.nextTick(emitDrain, this)\n }\n } else {\n this.emit('drain')\n }\n }\n }\n\n this.on('newListener', function (name) {\n if (name === 'drain') {\n this._asyncDrainScheduled = false\n }\n })\n\n if (this._periodicFlush !== 0) {\n this._periodicFlushTimer = setInterval(() => this.flush(null), this._periodicFlush)\n this._periodicFlushTimer.unref()\n }\n}\n\n/**\n * Release the writingBuf after fs.write n bytes data\n * @param {string | Buffer} writingBuf - currently writing buffer, usually be instance._writingBuf.\n * @param {number} len - currently buffer length, usually be instance._len.\n * @param {number} n - number of bytes fs already written\n * @returns {{writingBuf: string | Buffer, len: number}} released writingBuf and length\n */\nfunction releaseWritingBuf (writingBuf, len, n) {\n // if Buffer.byteLength is equal to n, that means writingBuf contains no multi-byte character\n if (typeof writingBuf === 'string' && Buffer.byteLength(writingBuf) !== n) {\n // Since the fs.write callback parameter `n` means how many bytes the passed of string\n // We calculate the original string length for avoiding the multi-byte character issue\n n = Buffer.from(writingBuf).subarray(0, n).toString().length\n }\n len = Math.max(len - n, 0)\n writingBuf = writingBuf.slice(n)\n return { writingBuf, len }\n}\n\nfunction emitDrain (sonic) {\n const hasListeners = sonic.listenerCount('drain') > 0\n if (!hasListeners) return\n sonic._asyncDrainScheduled = false\n sonic.emit('drain')\n}\n\ninherits(SonicBoom, EventEmitter)\n\nfunction mergeBuf (bufs, len) {\n if (bufs.length === 0) {\n return kEmptyBuffer\n }\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return Buffer.concat(bufs, len)\n}\n\nfunction write (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n bufs[bufs.length - 1].length + data.length > this.maxWrite\n ) {\n bufs.push('' + data)\n } else {\n bufs[bufs.length - 1] += data\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction writeBuffer (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n const lens = this._lens\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n lens[lens.length - 1] + data.length > this.maxWrite\n ) {\n bufs.push([data])\n lens.push(data.length)\n } else {\n bufs[bufs.length - 1].push(data)\n lens[lens.length - 1] += data.length\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction callFlushCallbackOnDrain (cb) {\n this._flushPending = true\n const onDrain = () => {\n // only if _fsync is false to avoid double fsync\n if (!this._fsync) {\n try {\n fs.fsync(this.fd, (err) => {\n this._flushPending = false\n cb(err)\n })\n } catch (err) {\n cb(err)\n }\n } else {\n this._flushPending = false\n cb()\n }\n this.off('error', onError)\n }\n const onError = (err) => {\n this._flushPending = false\n cb(err)\n this.off('drain', onDrain)\n }\n\n this.once('drain', onDrain)\n this.once('error', onError)\n}\n\nfunction flush (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push('')\n }\n\n this._actualWrite()\n}\n\nfunction flushBuffer (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push([])\n this._lens.push(0)\n }\n\n this._actualWrite()\n}\n\nSonicBoom.prototype.reopen = function (file) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.reopen(file)\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n if (!this.file) {\n throw new Error('Unable to reopen a file descriptor, you must pass a file to SonicBoom')\n }\n\n if (file) {\n this.file = file\n }\n this._reopening = true\n\n if (this._writing) {\n return\n }\n\n const fd = this.fd\n this.once('ready', () => {\n if (fd !== this.fd) {\n fs.close(fd, (err) => {\n if (err) {\n return this.emit('error', err)\n }\n })\n }\n })\n\n openFile(this.file, this)\n}\n\nSonicBoom.prototype.end = function () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.end()\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n this._ending = true\n\n if (this._writing) {\n return\n }\n\n if (this._len > 0 && this.fd >= 0) {\n this._actualWrite()\n } else {\n actualClose(this)\n }\n}\n\nfunction flushSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift(this._writingBuf)\n this._writingBuf = ''\n }\n\n let buf = ''\n while (this._bufs.length || buf) {\n if (buf.length <= 0) {\n buf = this._bufs[0]\n }\n try {\n const n = fs.writeSync(this.fd, buf, 'utf8')\n const releasedBufObj = releaseWritingBuf(buf, this._len, n)\n buf = releasedBufObj.writingBuf\n this._len = releasedBufObj.len\n if (buf.length <= 0) {\n this._bufs.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n\n try {\n fs.fsyncSync(this.fd)\n } catch {\n // Skip the error. The fd might not support fsync.\n }\n}\n\nfunction flushBufferSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift([this._writingBuf])\n this._writingBuf = kEmptyBuffer\n }\n\n let buf = kEmptyBuffer\n while (this._bufs.length || buf.length) {\n if (buf.length <= 0) {\n buf = mergeBuf(this._bufs[0], this._lens[0])\n }\n try {\n const n = fs.writeSync(this.fd, buf)\n buf = buf.subarray(n)\n this._len = Math.max(this._len - n, 0)\n if (buf.length <= 0) {\n this._bufs.shift()\n this._lens.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n}\n\nSonicBoom.prototype.destroy = function () {\n if (this.destroyed) {\n return\n }\n actualClose(this)\n}\n\nfunction actualWrite () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf || this._bufs.shift() || ''\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf, 'utf8')\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n fs.write(this.fd, this._writingBuf, 'utf8', release)\n }\n}\n\nfunction actualWriteBuffer () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift())\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf)\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n // fs.write will need to copy string to buffer anyway so\n // we do it here to avoid the overhead of calculating the buffer size\n // in releaseWritingBuf.\n if (kCopyBuffer) {\n this._writingBuf = Buffer.from(this._writingBuf)\n }\n fs.write(this.fd, this._writingBuf, release)\n }\n}\n\nfunction actualClose (sonic) {\n if (sonic.fd === -1) {\n sonic.once('ready', actualClose.bind(null, sonic))\n return\n }\n\n if (sonic._periodicFlushTimer !== undefined) {\n clearInterval(sonic._periodicFlushTimer)\n }\n\n sonic.destroyed = true\n sonic._bufs = []\n sonic._lens = []\n\n assert(typeof sonic.fd === 'number', `sonic.fd must be a number, got ${typeof sonic.fd}`)\n try {\n fs.fsync(sonic.fd, closeWrapped)\n } catch {\n }\n\n function closeWrapped () {\n // We skip errors in fsync\n\n if (sonic.fd !== 1 && sonic.fd !== 2) {\n fs.close(sonic.fd, done)\n } else {\n done()\n }\n }\n\n function done (err) {\n if (err) {\n sonic.emit('error', err)\n return\n }\n\n if (sonic._ending && !sonic._writing) {\n sonic.emit('finish')\n }\n sonic.emit('close')\n }\n}\n\n/**\n * These export configurations enable JS and TS developers\n * to consumer SonicBoom in whatever way best suits their needs.\n * Some examples of supported import syntax includes:\n * - `const SonicBoom = require('SonicBoom')`\n * - `const { SonicBoom } = require('SonicBoom')`\n * - `import * as SonicBoom from 'SonicBoom'`\n * - `import { SonicBoom } from 'SonicBoom'`\n * - `import SonicBoom from 'SonicBoom'`\n */\nSonicBoom.SonicBoom = SonicBoom\nSonicBoom.default = SonicBoom\nmodule.exports = SonicBoom\n", "\"use strict\";\nexports.secondsInYear =\n exports.secondsInWeek =\n exports.secondsInQuarter =\n exports.secondsInMonth =\n exports.secondsInMinute =\n exports.secondsInHour =\n exports.secondsInDay =\n exports.quartersInYear =\n exports.monthsInYear =\n exports.monthsInQuarter =\n exports.minutesInYear =\n exports.minutesInMonth =\n exports.minutesInHour =\n exports.minutesInDay =\n exports.minTime =\n exports.millisecondsInWeek =\n exports.millisecondsInSecond =\n exports.millisecondsInMinute =\n exports.millisecondsInHour =\n exports.millisecondsInDay =\n exports.maxTime =\n exports.daysInYear =\n exports.daysInWeek =\n exports.constructFromSymbol =\n void 0; /**\n * @module constants\n * @summary Useful constants\n * @description\n * Collection of useful date constants.\n *\n * The constants could be imported from `date-fns/constants`:\n *\n * ```ts\n * import { maxTime, minTime } from \"date-fns/constants\";\n *\n * function isAllowedTime(time) {\n * return time <= maxTime && time >= minTime;\n * }\n * ```\n */\n\n/**\n * @constant\n * @name daysInWeek\n * @summary Days in 1 week.\n */\nconst daysInWeek = (exports.daysInWeek = 7);\n\n/**\n * @constant\n * @name daysInYear\n * @summary Days in 1 year.\n *\n * @description\n * How many days in a year.\n *\n * One years equals 365.2425 days according to the formula:\n *\n * > Leap year occurs every 4 years, except for years that are divisible by 100 and not divisible by 400.\n * > 1 mean year = (365+1/4-1/100+1/400) days = 365.2425 days\n */\nconst daysInYear = (exports.daysInYear = 365.2425);\n\n/**\n * @constant\n * @name maxTime\n * @summary Maximum allowed time.\n *\n * @example\n * import { maxTime } from \"date-fns/constants\";\n *\n * const isValid = 8640000000000001 <= maxTime;\n * //=> false\n *\n * new Date(8640000000000001);\n * //=> Invalid Date\n */\nconst maxTime = (exports.maxTime = Math.pow(10, 8) * 24 * 60 * 60 * 1000);\n\n/**\n * @constant\n * @name minTime\n * @summary Minimum allowed time.\n *\n * @example\n * import { minTime } from \"date-fns/constants\";\n *\n * const isValid = -8640000000000001 >= minTime;\n * //=> false\n *\n * new Date(-8640000000000001)\n * //=> Invalid Date\n */\nconst minTime = (exports.minTime = -maxTime);\n\n/**\n * @constant\n * @name millisecondsInWeek\n * @summary Milliseconds in 1 week.\n */\nconst millisecondsInWeek = (exports.millisecondsInWeek = 604800000);\n\n/**\n * @constant\n * @name millisecondsInDay\n * @summary Milliseconds in 1 day.\n */\nconst millisecondsInDay = (exports.millisecondsInDay = 86400000);\n\n/**\n * @constant\n * @name millisecondsInMinute\n * @summary Milliseconds in 1 minute\n */\nconst millisecondsInMinute = (exports.millisecondsInMinute = 60000);\n\n/**\n * @constant\n * @name millisecondsInHour\n * @summary Milliseconds in 1 hour\n */\nconst millisecondsInHour = (exports.millisecondsInHour = 3600000);\n\n/**\n * @constant\n * @name millisecondsInSecond\n * @summary Milliseconds in 1 second\n */\nconst millisecondsInSecond = (exports.millisecondsInSecond = 1000);\n\n/**\n * @constant\n * @name minutesInYear\n * @summary Minutes in 1 year.\n */\nconst minutesInYear = (exports.minutesInYear = 525600);\n\n/**\n * @constant\n * @name minutesInMonth\n * @summary Minutes in 1 month.\n */\nconst minutesInMonth = (exports.minutesInMonth = 43200);\n\n/**\n * @constant\n * @name minutesInDay\n * @summary Minutes in 1 day.\n */\nconst minutesInDay = (exports.minutesInDay = 1440);\n\n/**\n * @constant\n * @name minutesInHour\n * @summary Minutes in 1 hour.\n */\nconst minutesInHour = (exports.minutesInHour = 60);\n\n/**\n * @constant\n * @name monthsInQuarter\n * @summary Months in 1 quarter.\n */\nconst monthsInQuarter = (exports.monthsInQuarter = 3);\n\n/**\n * @constant\n * @name monthsInYear\n * @summary Months in 1 year.\n */\nconst monthsInYear = (exports.monthsInYear = 12);\n\n/**\n * @constant\n * @name quartersInYear\n * @summary Quarters in 1 year\n */\nconst quartersInYear = (exports.quartersInYear = 4);\n\n/**\n * @constant\n * @name secondsInHour\n * @summary Seconds in 1 hour.\n */\nconst secondsInHour = (exports.secondsInHour = 3600);\n\n/**\n * @constant\n * @name secondsInMinute\n * @summary Seconds in 1 minute.\n */\nconst secondsInMinute = (exports.secondsInMinute = 60);\n\n/**\n * @constant\n * @name secondsInDay\n * @summary Seconds in 1 day.\n */\nconst secondsInDay = (exports.secondsInDay = secondsInHour * 24);\n\n/**\n * @constant\n * @name secondsInWeek\n * @summary Seconds in 1 week.\n */\nconst secondsInWeek = (exports.secondsInWeek = secondsInDay * 7);\n\n/**\n * @constant\n * @name secondsInYear\n * @summary Seconds in 1 year.\n */\nconst secondsInYear = (exports.secondsInYear = secondsInDay * daysInYear);\n\n/**\n * @constant\n * @name secondsInMonth\n * @summary Seconds in 1 month\n */\nconst secondsInMonth = (exports.secondsInMonth = secondsInYear / 12);\n\n/**\n * @constant\n * @name secondsInQuarter\n * @summary Seconds in 1 quarter.\n */\nconst secondsInQuarter = (exports.secondsInQuarter = secondsInMonth * 3);\n\n/**\n * @constant\n * @name constructFromSymbol\n * @summary Symbol enabling Date extensions to inherit properties from the reference date.\n *\n * The symbol is used to enable the `constructFrom` function to construct a date\n * using a reference date and a value. It allows to transfer extra properties\n * from the reference date to the new date. It's useful for extensions like\n * [`TZDate`](https://github.com/date-fns/tz) that accept a time zone as\n * a constructor argument.\n */\nconst constructFromSymbol = (exports.constructFromSymbol =\n Symbol.for(\"constructDateFrom\"));\n", "\"use strict\";\nexports.constructFrom = constructFrom;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name constructFrom\n * @category Generic Helpers\n * @summary Constructs a date using the reference date and the value\n *\n * @description\n * The function constructs a new date using the constructor from the reference\n * date and the given value. It helps to build generic functions that accept\n * date extensions.\n *\n * It defaults to `Date` if the passed reference date is a number or a string.\n *\n * Starting from v3.7.0, it allows to construct a date using `[Symbol.for(\"constructDateFrom\")]`\n * enabling to transfer extra properties from the reference date to the new date.\n * It's useful for extensions like [`TZDate`](https://github.com/date-fns/tz)\n * that accept a time zone as a constructor argument.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n *\n * @param date - The reference date to take constructor from\n * @param value - The value to create the date\n *\n * @returns Date initialized using the given date and value\n *\n * @example\n * import { constructFrom } from \"date-fns\";\n *\n * // A function that clones a date preserving the original type\n * function cloneDate(date: DateType): DateType {\n * return constructFrom(\n * date, // Use constructor from the given date\n * date.getTime() // Use the date value to create a new date\n * );\n * }\n */\nfunction constructFrom(date, value) {\n if (typeof date === \"function\") return date(value);\n\n if (date && typeof date === \"object\" && _index.constructFromSymbol in date)\n return date[_index.constructFromSymbol](value);\n\n if (date instanceof Date) return new date.constructor(value);\n\n return new Date(value);\n}\n", "\"use strict\";\nexports.toDate = toDate;\nvar _index = require(\"./constructFrom.cjs\");\n\n/**\n * @name toDate\n * @category Common Helpers\n * @summary Convert the given argument to an instance of Date.\n *\n * @description\n * Convert the given argument to an instance of Date.\n *\n * If the argument is an instance of Date, the function returns its clone.\n *\n * If the argument is a number, it is treated as a timestamp.\n *\n * If the argument is none of the above, the function returns Invalid Date.\n *\n * Starting from v3.7.0, it clones a date using `[Symbol.for(\"constructDateFrom\")]`\n * enabling to transfer extra properties from the reference date to the new date.\n * It's useful for extensions like [`TZDate`](https://github.com/date-fns/tz)\n * that accept a time zone as a constructor argument.\n *\n * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param argument - The value to convert\n *\n * @returns The parsed date in the local time zone\n *\n * @example\n * // Clone the date:\n * const result = toDate(new Date(2014, 1, 11, 11, 30, 30))\n * //=> Tue Feb 11 2014 11:30:30\n *\n * @example\n * // Convert the timestamp to date:\n * const result = toDate(1392098430000)\n * //=> Tue Feb 11 2014 11:30:30\n */\nfunction toDate(argument, context) {\n // [TODO] Get rid of `toDate` or `constructFrom`?\n return (0, _index.constructFrom)(context || argument, argument);\n}\n", "\"use strict\";\nexports.addDays = addDays;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link addDays} function options.\n */\n\n/**\n * @name addDays\n * @category Day Helpers\n * @summary Add the specified number of days to the given date.\n *\n * @description\n * Add the specified number of days to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of days to be added.\n * @param options - An object with options\n *\n * @returns The new date with the days added\n *\n * @example\n * // Add 10 days to 1 September 2014:\n * const result = addDays(new Date(2014, 8, 1), 10)\n * //=> Thu Sep 11 2014 00:00:00\n */\nfunction addDays(date, amount, options) {\n const _date = (0, _index2.toDate)(date, options?.in);\n if (isNaN(amount)) return (0, _index.constructFrom)(options?.in || date, NaN);\n\n // If 0 days, no-op to avoid changing times in the hour before end of DST\n if (!amount) return _date;\n\n _date.setDate(_date.getDate() + amount);\n return _date;\n}\n", "\"use strict\";\nexports.addMonths = addMonths;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link addMonths} function options.\n */\n\n/**\n * @name addMonths\n * @category Month Helpers\n * @summary Add the specified number of months to the given date.\n *\n * @description\n * Add the specified number of months to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of months to be added.\n * @param options - The options object\n *\n * @returns The new date with the months added\n *\n * @example\n * // Add 5 months to 1 September 2014:\n * const result = addMonths(new Date(2014, 8, 1), 5)\n * //=> Sun Feb 01 2015 00:00:00\n *\n * // Add one month to 30 January 2023:\n * const result = addMonths(new Date(2023, 0, 30), 1)\n * //=> Tue Feb 28 2023 00:00:00\n */\nfunction addMonths(date, amount, options) {\n const _date = (0, _index2.toDate)(date, options?.in);\n if (isNaN(amount)) return (0, _index.constructFrom)(options?.in || date, NaN);\n if (!amount) {\n // If 0 months, no-op to avoid changing times in the hour before end of DST\n return _date;\n }\n const dayOfMonth = _date.getDate();\n\n // The JS Date object supports date math by accepting out-of-bounds values for\n // month, day, etc. For example, new Date(2020, 0, 0) returns 31 Dec 2019 and\n // new Date(2020, 13, 1) returns 1 Feb 2021. This is *almost* the behavior we\n // want except that dates will wrap around the end of a month, meaning that\n // new Date(2020, 13, 31) will return 3 Mar 2021 not 28 Feb 2021 as desired. So\n // we'll default to the end of the desired month by adding 1 to the desired\n // month and using a date of 0 to back up one day to the end of the desired\n // month.\n const endOfDesiredMonth = (0, _index.constructFrom)(\n options?.in || date,\n _date.getTime(),\n );\n endOfDesiredMonth.setMonth(_date.getMonth() + amount + 1, 0);\n const daysInMonth = endOfDesiredMonth.getDate();\n if (dayOfMonth >= daysInMonth) {\n // If we're already at the end of the month, then this is the correct date\n // and we're done.\n return endOfDesiredMonth;\n } else {\n // Otherwise, we now know that setting the original day-of-month value won't\n // cause an overflow, so set the desired day-of-month. Note that we can't\n // just set the date of `endOfDesiredMonth` because that object may have had\n // its time changed in the unusual case where where a DST transition was on\n // the last day of the month and its local time was in the hour skipped or\n // repeated next to a DST transition. So we use `date` instead which is\n // guaranteed to still have the original time.\n _date.setFullYear(\n endOfDesiredMonth.getFullYear(),\n endOfDesiredMonth.getMonth(),\n dayOfMonth,\n );\n return _date;\n }\n}\n", "\"use strict\";\nexports.add = add;\nvar _index = require(\"./addDays.cjs\");\nvar _index2 = require(\"./addMonths.cjs\");\nvar _index3 = require(\"./constructFrom.cjs\");\nvar _index4 = require(\"./toDate.cjs\");\n\n/**\n * The {@link add} function options.\n */\n\n/**\n * @name add\n * @category Common Helpers\n * @summary Add the specified years, months, weeks, days, hours, minutes, and seconds to the given date.\n *\n * @description\n * Add the specified years, months, weeks, days, hours, minutes, and seconds to the given date.\n *\n * @typeParam DateType - The `Date` type the function operates on. Gets inferred from passed arguments. Allows using extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param duration - The object with years, months, weeks, days, hours, minutes, and seconds to be added.\n * @param options - An object with options\n *\n * @returns The new date with the seconds added\n *\n * @example\n * // Add the following duration to 1 September 2014, 10:19:50\n * const result = add(new Date(2014, 8, 1, 10, 19, 50), {\n * years: 2,\n * months: 9,\n * weeks: 1,\n * days: 7,\n * hours: 5,\n * minutes: 9,\n * seconds: 30,\n * })\n * //=> Thu Jun 15 2017 15:29:20\n */\nfunction add(date, duration, options) {\n const {\n years = 0,\n months = 0,\n weeks = 0,\n days = 0,\n hours = 0,\n minutes = 0,\n seconds = 0,\n } = duration;\n\n // Add years and months\n const _date = (0, _index4.toDate)(date, options?.in);\n const dateWithMonths =\n months || years\n ? (0, _index2.addMonths)(_date, months + years * 12)\n : _date;\n\n // Add weeks and days\n const dateWithDays =\n days || weeks\n ? (0, _index.addDays)(dateWithMonths, days + weeks * 7)\n : dateWithMonths;\n\n // Add days, hours, minutes, and seconds\n const minutesToAdd = minutes + hours * 60;\n const secondsToAdd = seconds + minutesToAdd * 60;\n const msToAdd = secondsToAdd * 1000;\n\n return (0, _index3.constructFrom)(\n options?.in || date,\n +dateWithDays + msToAdd,\n );\n}\n", "\"use strict\";\nexports.isSaturday = isSaturday;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isSaturday} function options.\n */\n\n/**\n * @name isSaturday\n * @category Weekday Helpers\n * @summary Is the given date Saturday?\n *\n * @description\n * Is the given date Saturday?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is Saturday\n *\n * @example\n * // Is 27 September 2014 Saturday?\n * const result = isSaturday(new Date(2014, 8, 27))\n * //=> true\n */\nfunction isSaturday(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay() === 6;\n}\n", "\"use strict\";\nexports.isSunday = isSunday;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isSunday} function options.\n */\n\n/**\n * @name isSunday\n * @category Weekday Helpers\n * @summary Is the given date Sunday?\n *\n * @description\n * Is the given date Sunday?\n *\n * @param date - The date to check\n * @param options - The options object\n *\n * @returns The date is Sunday\n *\n * @example\n * // Is 21 September 2014 Sunday?\n * const result = isSunday(new Date(2014, 8, 21))\n * //=> true\n */\nfunction isSunday(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay() === 0;\n}\n", "\"use strict\";\nexports.isWeekend = isWeekend;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isWeekend} function options.\n */\n\n/**\n * @name isWeekend\n * @category Weekday Helpers\n * @summary Does the given date fall on a weekend?\n *\n * @description\n * Does the given date fall on a weekend? A weekend is either Saturday (`6`) or Sunday (`0`).\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date falls on a weekend\n *\n * @example\n * // Does 5 October 2014 fall on a weekend?\n * const result = isWeekend(new Date(2014, 9, 5))\n * //=> true\n */\nfunction isWeekend(date, options) {\n const day = (0, _index.toDate)(date, options?.in).getDay();\n return day === 0 || day === 6;\n}\n", "\"use strict\";\nexports.addBusinessDays = addBusinessDays;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./isSaturday.cjs\");\nvar _index3 = require(\"./isSunday.cjs\");\nvar _index4 = require(\"./isWeekend.cjs\");\nvar _index5 = require(\"./toDate.cjs\");\n\n/**\n * The {@link addBusinessDays} function options.\n */\n\n/**\n * @name addBusinessDays\n * @category Day Helpers\n * @summary Add the specified number of business days (mon - fri) to the given date.\n *\n * @description\n * Add the specified number of business days (mon - fri) to the given date, ignoring weekends.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of business days to be added.\n * @param options - An object with options\n *\n * @returns The new date with the business days added\n *\n * @example\n * // Add 10 business days to 1 September 2014:\n * const result = addBusinessDays(new Date(2014, 8, 1), 10)\n * //=> Mon Sep 15 2014 00:00:00 (skipped weekend days)\n */\nfunction addBusinessDays(date, amount, options) {\n const _date = (0, _index5.toDate)(date, options?.in);\n const startedOnWeekend = (0, _index4.isWeekend)(_date, options);\n\n if (isNaN(amount)) return (0, _index.constructFrom)(options?.in, NaN);\n\n const hours = _date.getHours();\n const sign = amount < 0 ? -1 : 1;\n const fullWeeks = Math.trunc(amount / 5);\n\n _date.setDate(_date.getDate() + fullWeeks * 7);\n\n // Get remaining days not part of a full week\n let restDays = Math.abs(amount % 5);\n\n // Loops over remaining days\n while (restDays > 0) {\n _date.setDate(_date.getDate() + sign);\n if (!(0, _index4.isWeekend)(_date, options)) restDays -= 1;\n }\n\n // If the date is a weekend day and we reduce a dividable of\n // 5 from it, we land on a weekend date.\n // To counter this, we add days accordingly to land on the next business day\n if (\n startedOnWeekend &&\n (0, _index4.isWeekend)(_date, options) &&\n amount !== 0\n ) {\n // If we're reducing days, we want to add days until we land on a weekday\n // If we're adding days we want to reduce days until we land on a weekday\n if ((0, _index2.isSaturday)(_date, options))\n _date.setDate(_date.getDate() + (sign < 0 ? 2 : -1));\n if ((0, _index3.isSunday)(_date, options))\n _date.setDate(_date.getDate() + (sign < 0 ? 1 : -2));\n }\n\n // Restore hours to avoid DST lag\n _date.setHours(hours);\n\n return _date;\n}\n", "\"use strict\";\nexports.addMilliseconds = addMilliseconds;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link addMilliseconds} function options.\n */\n\n/**\n * @name addMilliseconds\n * @category Millisecond Helpers\n * @summary Add the specified number of milliseconds to the given date.\n *\n * @description\n * Add the specified number of milliseconds to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of milliseconds to be added.\n * @param options - The options object\n *\n * @returns The new date with the milliseconds added\n *\n * @example\n * // Add 750 milliseconds to 10 July 2014 12:45:30.000:\n * const result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)\n * //=> Thu Jul 10 2014 12:45:30.750\n */\nfunction addMilliseconds(date, amount, options) {\n return (0, _index.constructFrom)(\n options?.in || date,\n +(0, _index2.toDate)(date) + amount,\n );\n}\n", "\"use strict\";\nexports.addHours = addHours;\nvar _index = require(\"./addMilliseconds.cjs\");\nvar _index2 = require(\"./constants.cjs\");\n\n/**\n * The {@link addHours} function options.\n */\n\n/**\n * @name addHours\n * @category Hour Helpers\n * @summary Add the specified number of hours to the given date.\n *\n * @description\n * Add the specified number of hours to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of hours to be added\n * @param options - An object with options\n *\n * @returns The new date with the hours added\n *\n * @example\n * // Add 2 hours to 10 July 2014 23:00:00:\n * const result = addHours(new Date(2014, 6, 10, 23, 0), 2)\n * //=> Fri Jul 11 2014 01:00:00\n */\nfunction addHours(date, amount, options) {\n return (0, _index.addMilliseconds)(\n date,\n amount * _index2.millisecondsInHour,\n options,\n );\n}\n", "\"use strict\";\nexports.getDefaultOptions = getDefaultOptions;\nexports.setDefaultOptions = setDefaultOptions;\n\nlet defaultOptions = {};\n\nfunction getDefaultOptions() {\n return defaultOptions;\n}\n\nfunction setDefaultOptions(newOptions) {\n defaultOptions = newOptions;\n}\n", "\"use strict\";\nexports.startOfWeek = startOfWeek;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfWeek} function options.\n */\n\n/**\n * @name startOfWeek\n * @category Week Helpers\n * @summary Return the start of a week for the given date.\n *\n * @description\n * Return the start of a week for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of a week\n *\n * @example\n * // The start of a week for 2 September 2014 11:55:00:\n * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Sun Aug 31 2014 00:00:00\n *\n * @example\n * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00:\n * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })\n * //=> Mon Sep 01 2014 00:00:00\n */\nfunction startOfWeek(date, options) {\n const defaultOptions = (0, _index.getDefaultOptions)();\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const _date = (0, _index2.toDate)(date, options?.in);\n const day = _date.getDay();\n const diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;\n\n _date.setDate(_date.getDate() - diff);\n _date.setHours(0, 0, 0, 0);\n return _date;\n}\n", "\"use strict\";\nexports.startOfISOWeek = startOfISOWeek;\nvar _index = require(\"./startOfWeek.cjs\");\n\n/**\n * The {@link startOfISOWeek} function options.\n */\n\n/**\n * @name startOfISOWeek\n * @category ISO Week Helpers\n * @summary Return the start of an ISO week for the given date.\n *\n * @description\n * Return the start of an ISO week for the given date.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of an ISO week\n *\n * @example\n * // The start of an ISO week for 2 September 2014 11:55:00:\n * const result = startOfISOWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Mon Sep 01 2014 00:00:00\n */\nfunction startOfISOWeek(date, options) {\n return (0, _index.startOfWeek)(date, { ...options, weekStartsOn: 1 });\n}\n", "\"use strict\";\nexports.getISOWeekYear = getISOWeekYear;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./startOfISOWeek.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getISOWeekYear} function options.\n */\n\n/**\n * @name getISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Get the ISO week-numbering year of the given date.\n *\n * @description\n * Get the ISO week-numbering year of the given date,\n * which always starts 3 days before the year's first Thursday.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param date - The given date\n *\n * @returns The ISO week-numbering year\n *\n * @example\n * // Which ISO-week numbering year is 2 January 2005?\n * const result = getISOWeekYear(new Date(2005, 0, 2))\n * //=> 2004\n */\nfunction getISOWeekYear(date, options) {\n const _date = (0, _index3.toDate)(date, options?.in);\n const year = _date.getFullYear();\n\n const fourthOfJanuaryOfNextYear = (0, _index.constructFrom)(_date, 0);\n fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);\n fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);\n const startOfNextYear = (0, _index2.startOfISOWeek)(\n fourthOfJanuaryOfNextYear,\n );\n\n const fourthOfJanuaryOfThisYear = (0, _index.constructFrom)(_date, 0);\n fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4);\n fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0);\n const startOfThisYear = (0, _index2.startOfISOWeek)(\n fourthOfJanuaryOfThisYear,\n );\n\n if (_date.getTime() >= startOfNextYear.getTime()) {\n return year + 1;\n } else if (_date.getTime() >= startOfThisYear.getTime()) {\n return year;\n } else {\n return year - 1;\n }\n}\n", "\"use strict\";\nexports.getTimezoneOffsetInMilliseconds = getTimezoneOffsetInMilliseconds;\nvar _index = require(\"../toDate.cjs\");\n\n/**\n * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds.\n * They usually appear for dates that denote time before the timezones were introduced\n * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891\n * and GMT+01:00:00 after that date)\n *\n * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above,\n * which would lead to incorrect calculations.\n *\n * This function returns the timezone offset in milliseconds that takes seconds in account.\n */\nfunction getTimezoneOffsetInMilliseconds(date) {\n const _date = (0, _index.toDate)(date);\n const utcDate = new Date(\n Date.UTC(\n _date.getFullYear(),\n _date.getMonth(),\n _date.getDate(),\n _date.getHours(),\n _date.getMinutes(),\n _date.getSeconds(),\n _date.getMilliseconds(),\n ),\n );\n utcDate.setUTCFullYear(_date.getFullYear());\n return +date - +utcDate;\n}\n", "\"use strict\";\nexports.normalizeDates = normalizeDates;\nvar _index = require(\"../constructFrom.cjs\");\n\nfunction normalizeDates(context, ...dates) {\n const normalize = _index.constructFrom.bind(\n null,\n context || dates.find((date) => typeof date === \"object\"),\n );\n return dates.map(normalize);\n}\n", "\"use strict\";\nexports.startOfDay = startOfDay;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfDay} function options.\n */\n\n/**\n * @name startOfDay\n * @category Day Helpers\n * @summary Return the start of a day for the given date.\n *\n * @description\n * Return the start of a day for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The start of a day\n *\n * @example\n * // The start of a day for 2 September 2014 11:55:00:\n * const result = startOfDay(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 02 2014 00:00:00\n */\nfunction startOfDay(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setHours(0, 0, 0, 0);\n return _date;\n}\n", "\"use strict\";\nexports.differenceInCalendarDays = differenceInCalendarDays;\nvar _index = require(\"./_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _index2 = require(\"./_lib/normalizeDates.cjs\");\nvar _index3 = require(\"./constants.cjs\");\nvar _index4 = require(\"./startOfDay.cjs\");\n\n/**\n * The {@link differenceInCalendarDays} function options.\n */\n\n/**\n * @name differenceInCalendarDays\n * @category Day Helpers\n * @summary Get the number of calendar days between the given dates.\n *\n * @description\n * Get the number of calendar days between the given dates. This means that the times are removed\n * from the dates and then the difference in days is calculated.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - The options object\n *\n * @returns The number of calendar days\n *\n * @example\n * // How many calendar days are between\n * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?\n * const result = differenceInCalendarDays(\n * new Date(2012, 6, 2, 0, 0),\n * new Date(2011, 6, 2, 23, 0)\n * )\n * //=> 366\n * // How many calendar days are between\n * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?\n * const result = differenceInCalendarDays(\n * new Date(2011, 6, 3, 0, 1),\n * new Date(2011, 6, 2, 23, 59)\n * )\n * //=> 1\n */\nfunction differenceInCalendarDays(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index2.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const laterStartOfDay = (0, _index4.startOfDay)(laterDate_);\n const earlierStartOfDay = (0, _index4.startOfDay)(earlierDate_);\n\n const laterTimestamp =\n +laterStartOfDay -\n (0, _index.getTimezoneOffsetInMilliseconds)(laterStartOfDay);\n const earlierTimestamp =\n +earlierStartOfDay -\n (0, _index.getTimezoneOffsetInMilliseconds)(earlierStartOfDay);\n\n // Round the number of days to the nearest integer because the number of\n // milliseconds in a day is not constant (e.g. it's different in the week of\n // the daylight saving time clock shift).\n return Math.round(\n (laterTimestamp - earlierTimestamp) / _index3.millisecondsInDay,\n );\n}\n", "\"use strict\";\nexports.startOfISOWeekYear = startOfISOWeekYear;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./getISOWeekYear.cjs\");\nvar _index3 = require(\"./startOfISOWeek.cjs\");\n\n/**\n * The {@link startOfISOWeekYear} function options.\n */\n\n/**\n * @name startOfISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Return the start of an ISO week-numbering year for the given date.\n *\n * @description\n * Return the start of an ISO week-numbering year,\n * which always starts 3 days before the year's first Thursday.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of an ISO week-numbering year\n *\n * @example\n * // The start of an ISO week-numbering year for 2 July 2005:\n * const result = startOfISOWeekYear(new Date(2005, 6, 2))\n * //=> Mon Jan 03 2005 00:00:00\n */\nfunction startOfISOWeekYear(date, options) {\n const year = (0, _index2.getISOWeekYear)(date, options);\n const fourthOfJanuary = (0, _index.constructFrom)(options?.in || date, 0);\n fourthOfJanuary.setFullYear(year, 0, 4);\n fourthOfJanuary.setHours(0, 0, 0, 0);\n return (0, _index3.startOfISOWeek)(fourthOfJanuary);\n}\n", "\"use strict\";\nexports.setISOWeekYear = setISOWeekYear;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./differenceInCalendarDays.cjs\");\nvar _index3 = require(\"./startOfISOWeekYear.cjs\");\nvar _index4 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setISOWeekYear} function options.\n */\n\n/**\n * @name setISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Set the ISO week-numbering year to the given date.\n *\n * @description\n * Set the ISO week-numbering year to the given date,\n * saving the week number and the weekday number.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows using extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param weekYear - The ISO week-numbering year of the new date\n * @param options - An object with options\n *\n * @returns The new date with the ISO week-numbering year set\n *\n * @example\n * // Set ISO week-numbering year 2007 to 29 December 2008:\n * const result = setISOWeekYear(new Date(2008, 11, 29), 2007)\n * //=> Mon Jan 01 2007 00:00:00\n */\nfunction setISOWeekYear(date, weekYear, options) {\n let _date = (0, _index4.toDate)(date, options?.in);\n const diff = (0, _index2.differenceInCalendarDays)(\n _date,\n (0, _index3.startOfISOWeekYear)(_date, options),\n );\n const fourthOfJanuary = (0, _index.constructFrom)(options?.in || date, 0);\n fourthOfJanuary.setFullYear(weekYear, 0, 4);\n fourthOfJanuary.setHours(0, 0, 0, 0);\n _date = (0, _index3.startOfISOWeekYear)(fourthOfJanuary);\n _date.setDate(_date.getDate() + diff);\n return _date;\n}\n", "\"use strict\";\nexports.addISOWeekYears = addISOWeekYears;\nvar _index = require(\"./getISOWeekYear.cjs\");\nvar _index2 = require(\"./setISOWeekYear.cjs\");\n\n/**\n * The {@link addISOWeekYears} function options.\n */\n\n/**\n * @name addISOWeekYears\n * @category ISO Week-Numbering Year Helpers\n * @summary Add the specified number of ISO week-numbering years to the given date.\n *\n * @description\n * Add the specified number of ISO week-numbering years to the given date.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n *\n * @param date - The date to be changed\n * @param amount - The amount of ISO week-numbering years to be added.\n * @param options - An object with options\n *\n * @returns The new date with the ISO week-numbering years added\n *\n * @example\n * // Add 5 ISO week-numbering years to 2 July 2010:\n * const result = addISOWeekYears(new Date(2010, 6, 2), 5)\n * //=> Fri Jun 26 2015 00:00:00\n */\nfunction addISOWeekYears(date, amount, options) {\n return (0, _index2.setISOWeekYear)(\n date,\n (0, _index.getISOWeekYear)(date, options) + amount,\n options,\n );\n}\n", "\"use strict\";\nexports.addMinutes = addMinutes;\nvar _index = require(\"./constants.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link addMinutes} function options.\n */\n\n/**\n * @name addMinutes\n * @category Minute Helpers\n * @summary Add the specified number of minutes to the given date.\n *\n * @description\n * Add the specified number of minutes to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of minutes to be added.\n * @param options - An object with options\n *\n * @returns The new date with the minutes added\n *\n * @example\n * // Add 30 minutes to 10 July 2014 12:00:00:\n * const result = addMinutes(new Date(2014, 6, 10, 12, 0), 30)\n * //=> Thu Jul 10 2014 12:30:00\n */\nfunction addMinutes(date, amount, options) {\n const _date = (0, _index2.toDate)(date, options?.in);\n _date.setTime(_date.getTime() + amount * _index.millisecondsInMinute);\n return _date;\n}\n", "\"use strict\";\nexports.addQuarters = addQuarters;\nvar _index = require(\"./addMonths.cjs\");\n\n/**\n * The {@link addQuarters} function options.\n */\n\n/**\n * @name addQuarters\n * @category Quarter Helpers\n * @summary Add the specified number of year quarters to the given date.\n *\n * @description\n * Add the specified number of year quarters to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of quarters to be added.\n * @param options - An object with options\n *\n * @returns The new date with the quarters added\n *\n * @example\n * // Add 1 quarter to 1 September 2014:\n * const result = addQuarters(new Date(2014, 8, 1), 1)\n * //=; Mon Dec 01 2014 00:00:00\n */\nfunction addQuarters(date, amount, options) {\n return (0, _index.addMonths)(date, amount * 3, options);\n}\n", "\"use strict\";\nexports.addSeconds = addSeconds;\nvar _index = require(\"./addMilliseconds.cjs\");\n\n/**\n * The {@link addSeconds} function options.\n */\n\n/**\n * @name addSeconds\n * @category Second Helpers\n * @summary Add the specified number of seconds to the given date.\n *\n * @description\n * Add the specified number of seconds to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of seconds to be added.\n * @param options - An object with options\n *\n * @returns The new date with the seconds added\n *\n * @example\n * // Add 30 seconds to 10 July 2014 12:45:00:\n * const result = addSeconds(new Date(2014, 6, 10, 12, 45, 0), 30)\n * //=> Thu Jul 10 2014 12:45:30\n */\nfunction addSeconds(date, amount, options) {\n return (0, _index.addMilliseconds)(date, amount * 1000, options);\n}\n", "\"use strict\";\nexports.addWeeks = addWeeks;\nvar _index = require(\"./addDays.cjs\");\n\n/**\n * The {@link addWeeks} function options.\n */\n\n/**\n * @name addWeeks\n * @category Week Helpers\n * @summary Add the specified number of weeks to the given date.\n *\n * @description\n * Add the specified number of weeks to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of weeks to be added.\n * @param options - An object with options\n *\n * @returns The new date with the weeks added\n *\n * @example\n * // Add 4 weeks to 1 September 2014:\n * const result = addWeeks(new Date(2014, 8, 1), 4)\n * //=> Mon Sep 29 2014 00:00:00\n */\nfunction addWeeks(date, amount, options) {\n return (0, _index.addDays)(date, amount * 7, options);\n}\n", "\"use strict\";\nexports.addYears = addYears;\nvar _index = require(\"./addMonths.cjs\");\n\n/**\n * The {@link addYears} function options.\n */\n\n/**\n * @name addYears\n * @category Year Helpers\n * @summary Add the specified number of years to the given date.\n *\n * @description\n * Add the specified number of years to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type.\n *\n * @param date - The date to be changed\n * @param amount - The amount of years to be added.\n * @param options - The options\n *\n * @returns The new date with the years added\n *\n * @example\n * // Add 5 years to 1 September 2014:\n * const result = addYears(new Date(2014, 8, 1), 5)\n * //=> Sun Sep 01 2019 00:00:00\n */\nfunction addYears(date, amount, options) {\n return (0, _index.addMonths)(date, amount * 12, options);\n}\n", "\"use strict\";\nexports.areIntervalsOverlapping = areIntervalsOverlapping;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link areIntervalsOverlapping} function options.\n */\n\n/**\n * @name areIntervalsOverlapping\n * @category Interval Helpers\n * @summary Is the given time interval overlapping with another time interval?\n *\n * @description\n * Is the given time interval overlapping with another time interval? Adjacent intervals do not count as overlapping unless `inclusive` is set to `true`.\n *\n * @param intervalLeft - The first interval to compare.\n * @param intervalRight - The second interval to compare.\n * @param options - The object with options\n *\n * @returns Whether the time intervals are overlapping\n *\n * @example\n * // For overlapping time intervals:\n * areIntervalsOverlapping(\n * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },\n * { start: new Date(2014, 0, 17), end: new Date(2014, 0, 21) }\n * )\n * //=> true\n *\n * @example\n * // For non-overlapping time intervals:\n * areIntervalsOverlapping(\n * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },\n * { start: new Date(2014, 0, 21), end: new Date(2014, 0, 22) }\n * )\n * //=> false\n *\n * @example\n * // For adjacent time intervals:\n * areIntervalsOverlapping(\n * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },\n * { start: new Date(2014, 0, 20), end: new Date(2014, 0, 30) }\n * )\n * //=> false\n *\n * @example\n * // Using the inclusive option:\n * areIntervalsOverlapping(\n * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },\n * { start: new Date(2014, 0, 20), end: new Date(2014, 0, 24) },\n * { inclusive: true }\n * )\n * //=> true\n */\nfunction areIntervalsOverlapping(intervalLeft, intervalRight, options) {\n const [leftStartTime, leftEndTime] = [\n +(0, _index.toDate)(intervalLeft.start, options?.in),\n +(0, _index.toDate)(intervalLeft.end, options?.in),\n ].sort((a, b) => a - b);\n const [rightStartTime, rightEndTime] = [\n +(0, _index.toDate)(intervalRight.start, options?.in),\n +(0, _index.toDate)(intervalRight.end, options?.in),\n ].sort((a, b) => a - b);\n\n if (options?.inclusive)\n return leftStartTime <= rightEndTime && rightStartTime <= leftEndTime;\n\n return leftStartTime < rightEndTime && rightStartTime < leftEndTime;\n}\n", "\"use strict\";\nexports.max = max;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link max} function options.\n */\n\n/**\n * @name max\n * @category Common Helpers\n * @summary Return the latest of the given dates.\n *\n * @description\n * Return the latest of the given dates.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param dates - The dates to compare\n *\n * @returns The latest of the dates\n *\n * @example\n * // Which of these dates is the latest?\n * const result = max([\n * new Date(1989, 6, 10),\n * new Date(1987, 1, 11),\n * new Date(1995, 6, 2),\n * new Date(1990, 0, 1)\n * ])\n * //=> Sun Jul 02 1995 00:00:00\n */\nfunction max(dates, options) {\n let result;\n let context = options?.in;\n\n dates.forEach((date) => {\n // Use the first date object as the context function\n if (!context && typeof date === \"object\")\n context = _index.constructFrom.bind(null, date);\n\n const date_ = (0, _index2.toDate)(date, context);\n if (!result || result < date_ || isNaN(+date_)) result = date_;\n });\n\n return (0, _index.constructFrom)(context, result || NaN);\n}\n", "\"use strict\";\nexports.min = min;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link min} function options.\n */\n\n/**\n * @name min\n * @category Common Helpers\n * @summary Returns the earliest of the given dates.\n *\n * @description\n * Returns the earliest of the given dates.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param dates - The dates to compare\n *\n * @returns The earliest of the dates\n *\n * @example\n * // Which of these dates is the earliest?\n * const result = min([\n * new Date(1989, 6, 10),\n * new Date(1987, 1, 11),\n * new Date(1995, 6, 2),\n * new Date(1990, 0, 1)\n * ])\n * //=> Wed Feb 11 1987 00:00:00\n */\nfunction min(dates, options) {\n let result;\n let context = options?.in;\n\n dates.forEach((date) => {\n // Use the first date object as the context function\n if (!context && typeof date === \"object\")\n context = _index.constructFrom.bind(null, date);\n\n const date_ = (0, _index2.toDate)(date, context);\n if (!result || result > date_ || isNaN(+date_)) result = date_;\n });\n\n return (0, _index.constructFrom)(context, result || NaN);\n}\n", "\"use strict\";\nexports.clamp = clamp;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./max.cjs\");\nvar _index3 = require(\"./min.cjs\");\n\n/**\n * The {@link clamp} function options.\n */\n\n/**\n * The {@link clamp} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the date argument,\n * then the start interval date, and finally the end interval date. If\n * a context function is passed, it uses the context function return type.\n */\n\n/**\n * @name clamp\n * @category Interval Helpers\n * @summary Return a date bounded by the start and the end of the given interval.\n *\n * @description\n * Clamps a date to the lower bound with the start of the interval and the upper\n * bound with the end of the interval.\n *\n * - When the date is less than the start of the interval, the start is returned.\n * - When the date is greater than the end of the interval, the end is returned.\n * - Otherwise the date is returned.\n *\n * @typeParam DateType - Date argument type.\n * @typeParam IntervalType - Interval argument type.\n * @typeParam Options - Options type.\n *\n * @param date - The date to be bounded\n * @param interval - The interval to bound to\n * @param options - An object with options\n *\n * @returns The date bounded by the start and the end of the interval\n *\n * @example\n * // What is Mar 21, 2021 bounded to an interval starting at Mar 22, 2021 and ending at Apr 01, 2021\n * const result = clamp(new Date(2021, 2, 21), {\n * start: new Date(2021, 2, 22),\n * end: new Date(2021, 3, 1),\n * })\n * //=> Mon Mar 22 2021 00:00:00\n */\nfunction clamp(date, interval, options) {\n const [date_, start, end] = (0, _index.normalizeDates)(\n options?.in,\n date,\n interval.start,\n interval.end,\n );\n\n return (0, _index3.min)(\n [(0, _index2.max)([date_, start], options), end],\n options,\n );\n}\n", "\"use strict\";\nexports.closestIndexTo = closestIndexTo;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name closestIndexTo\n * @category Common Helpers\n * @summary Return an index of the closest date from the array comparing to the given date.\n *\n * @description\n * Return an index of the closest date from the array comparing to the given date.\n *\n * @param dateToCompare - The date to compare with\n * @param dates - The array to search\n *\n * @returns An index of the date closest to the given date or undefined if no valid value is given\n *\n * @example\n * // Which date is closer to 6 September 2015?\n * const dateToCompare = new Date(2015, 8, 6)\n * const datesArray = [\n * new Date(2015, 0, 1),\n * new Date(2016, 0, 1),\n * new Date(2017, 0, 1)\n * ]\n * const result = closestIndexTo(dateToCompare, datesArray)\n * //=> 1\n */\nfunction closestIndexTo(dateToCompare, dates) {\n // [TODO] It would be better to return -1 here rather than undefined, as this\n // is how JS behaves, but it would be a breaking change, so we need\n // to consider it for v4.\n const timeToCompare = +(0, _index.toDate)(dateToCompare);\n\n if (isNaN(timeToCompare)) return NaN;\n\n let result;\n let minDistance;\n dates.forEach((date, index) => {\n const date_ = (0, _index.toDate)(date);\n\n if (isNaN(+date_)) {\n result = NaN;\n minDistance = NaN;\n return;\n }\n\n const distance = Math.abs(timeToCompare - +date_);\n if (result == null || distance < minDistance) {\n result = index;\n minDistance = distance;\n }\n });\n\n return result;\n}\n", "\"use strict\";\nexports.closestTo = closestTo;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./closestIndexTo.cjs\");\nvar _index3 = require(\"./constructFrom.cjs\");\n\n/**\n * The {@link closestTo} function options.\n */\n\n/**\n * The {@link closestTo} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the date argument,\n * then the start interval date, and finally the end interval date. If\n * a context function is passed, it uses the context function return type.\n */\n\n/**\n * @name closestTo\n * @category Common Helpers\n * @summary Return a date from the array closest to the given date.\n *\n * @description\n * Return a date from the array closest to the given date.\n *\n * @typeParam DateToCompare - Date to compare argument type.\n * @typeParam DatesType - Dates array argument type.\n * @typeParam Options - Options type.\n *\n * @param dateToCompare - The date to compare with\n * @param dates - The array to search\n *\n * @returns The date from the array closest to the given date or undefined if no valid value is given\n *\n * @example\n * // Which date is closer to 6 September 2015: 1 January 2000 or 1 January 2030?\n * const dateToCompare = new Date(2015, 8, 6)\n * const result = closestTo(dateToCompare, [\n * new Date(2000, 0, 1),\n * new Date(2030, 0, 1)\n * ])\n * //=> Tue Jan 01 2030 00:00:00\n */\nfunction closestTo(dateToCompare, dates, options) {\n const [dateToCompare_, ...dates_] = (0, _index.normalizeDates)(\n options?.in,\n dateToCompare,\n ...dates,\n );\n\n const index = (0, _index2.closestIndexTo)(dateToCompare_, dates_);\n\n if (typeof index === \"number\" && isNaN(index))\n return (0, _index3.constructFrom)(dateToCompare_, NaN);\n\n if (index !== undefined) return dates_[index];\n}\n", "\"use strict\";\nexports.compareAsc = compareAsc;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name compareAsc\n * @category Common Helpers\n * @summary Compare the two dates and return -1, 0 or 1.\n *\n * @description\n * Compare the two dates and return 1 if the first date is after the second,\n * -1 if the first date is before the second or 0 if dates are equal.\n *\n * @param dateLeft - The first date to compare\n * @param dateRight - The second date to compare\n *\n * @returns The result of the comparison\n *\n * @example\n * // Compare 11 February 1987 and 10 July 1989:\n * const result = compareAsc(new Date(1987, 1, 11), new Date(1989, 6, 10))\n * //=> -1\n *\n * @example\n * // Sort the array of dates:\n * const result = [\n * new Date(1995, 6, 2),\n * new Date(1987, 1, 11),\n * new Date(1989, 6, 10)\n * ].sort(compareAsc)\n * //=> [\n * // Wed Feb 11 1987 00:00:00,\n * // Mon Jul 10 1989 00:00:00,\n * // Sun Jul 02 1995 00:00:00\n * // ]\n */\nfunction compareAsc(dateLeft, dateRight) {\n const diff = +(0, _index.toDate)(dateLeft) - +(0, _index.toDate)(dateRight);\n\n if (diff < 0) return -1;\n else if (diff > 0) return 1;\n\n // Return 0 if diff is 0; return NaN if diff is NaN\n return diff;\n}\n", "\"use strict\";\nexports.compareDesc = compareDesc;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name compareDesc\n * @category Common Helpers\n * @summary Compare the two dates reverse chronologically and return -1, 0 or 1.\n *\n * @description\n * Compare the two dates and return -1 if the first date is after the second,\n * 1 if the first date is before the second or 0 if dates are equal.\n *\n * @param dateLeft - The first date to compare\n * @param dateRight - The second date to compare\n *\n * @returns The result of the comparison\n *\n * @example\n * // Compare 11 February 1987 and 10 July 1989 reverse chronologically:\n * const result = compareDesc(new Date(1987, 1, 11), new Date(1989, 6, 10))\n * //=> 1\n *\n * @example\n * // Sort the array of dates in reverse chronological order:\n * const result = [\n * new Date(1995, 6, 2),\n * new Date(1987, 1, 11),\n * new Date(1989, 6, 10)\n * ].sort(compareDesc)\n * //=> [\n * // Sun Jul 02 1995 00:00:00,\n * // Mon Jul 10 1989 00:00:00,\n * // Wed Feb 11 1987 00:00:00\n * // ]\n */\nfunction compareDesc(dateLeft, dateRight) {\n const diff = +(0, _index.toDate)(dateLeft) - +(0, _index.toDate)(dateRight);\n\n if (diff > 0) return -1;\n else if (diff < 0) return 1;\n\n // Return 0 if diff is 0; return NaN if diff is NaN\n return diff;\n}\n", "\"use strict\";\nexports.constructNow = constructNow;\nvar _index = require(\"./constructFrom.cjs\");\n\n/**\n * @name constructNow\n * @category Generic Helpers\n * @summary Constructs a new current date using the passed value constructor.\n * @pure false\n *\n * @description\n * The function constructs a new current date using the constructor from\n * the reference date. It helps to build generic functions that accept date\n * extensions and use the current date.\n *\n * It defaults to `Date` if the passed reference date is a number or a string.\n *\n * @param date - The reference date to take constructor from\n *\n * @returns Current date initialized using the given date constructor\n *\n * @example\n * import { constructNow, isSameDay } from 'date-fns'\n *\n * function isToday(\n * date: DateArg,\n * ): boolean {\n * // If we were to use `new Date()` directly, the function would behave\n * // differently in different timezones and return false for the same date.\n * return isSameDay(date, constructNow(date));\n * }\n */\nfunction constructNow(date) {\n return (0, _index.constructFrom)(date, Date.now());\n}\n", "\"use strict\";\nexports.daysToWeeks = daysToWeeks;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name daysToWeeks\n * @category Conversion Helpers\n * @summary Convert days to weeks.\n *\n * @description\n * Convert a number of days to a full number of weeks.\n *\n * @param days - The number of days to be converted\n *\n * @returns The number of days converted in weeks\n *\n * @example\n * // Convert 14 days to weeks:\n * const result = daysToWeeks(14)\n * //=> 2\n *\n * @example\n * // It uses trunc rounding:\n * const result = daysToWeeks(13)\n * //=> 1\n */\nfunction daysToWeeks(days) {\n const result = Math.trunc(days / _index.daysInWeek);\n // Prevent negative zero\n return result === 0 ? 0 : result;\n}\n", "\"use strict\";\nexports.isSameDay = isSameDay;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./startOfDay.cjs\");\n\n/**\n * The {@link isSameDay} function options.\n */\n\n/**\n * @name isSameDay\n * @category Day Helpers\n * @summary Are the given dates in the same day (and year and month)?\n *\n * @description\n * Are the given dates in the same day (and year and month)?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same day (and year and month)\n *\n * @example\n * // Are 4 September 06:00:00 and 4 September 18:00:00 in the same day?\n * const result = isSameDay(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 4, 18, 0))\n * //=> true\n *\n * @example\n * // Are 4 September and 4 October in the same day?\n * const result = isSameDay(new Date(2014, 8, 4), new Date(2014, 9, 4))\n * //=> false\n *\n * @example\n * // Are 4 September, 2014 and 4 September, 2015 in the same day?\n * const result = isSameDay(new Date(2014, 8, 4), new Date(2015, 8, 4))\n * //=> false\n */\nfunction isSameDay(laterDate, earlierDate, options) {\n const [dateLeft_, dateRight_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return (\n +(0, _index2.startOfDay)(dateLeft_) === +(0, _index2.startOfDay)(dateRight_)\n );\n}\n", "\"use strict\";\nexports.isDate = isDate; /**\n * @name isDate\n * @category Common Helpers\n * @summary Is the given value a date?\n *\n * @description\n * Returns true if the given value is an instance of Date. The function works for dates transferred across iframes.\n *\n * @param value - The value to check\n *\n * @returns True if the given value is a date\n *\n * @example\n * // For a valid date:\n * const result = isDate(new Date())\n * //=> true\n *\n * @example\n * // For an invalid date:\n * const result = isDate(new Date(NaN))\n * //=> true\n *\n * @example\n * // For some value:\n * const result = isDate('2014-02-31')\n * //=> false\n *\n * @example\n * // For an object:\n * const result = isDate({})\n * //=> false\n */\nfunction isDate(value) {\n return (\n value instanceof Date ||\n (typeof value === \"object\" &&\n Object.prototype.toString.call(value) === \"[object Date]\")\n );\n}\n", "\"use strict\";\nexports.isValid = isValid;\nvar _index = require(\"./isDate.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * @name isValid\n * @category Common Helpers\n * @summary Is the given date valid?\n *\n * @description\n * Returns false if argument is Invalid Date and true otherwise.\n * Argument is converted to Date using `toDate`. See [toDate](https://date-fns.org/docs/toDate)\n * Invalid Date is a Date, whose time value is NaN.\n *\n * Time value of Date: http://es5.github.io/#x15.9.1.1\n *\n * @param date - The date to check\n *\n * @returns The date is valid\n *\n * @example\n * // For the valid date:\n * const result = isValid(new Date(2014, 1, 31))\n * //=> true\n *\n * @example\n * // For the value, convertible into a date:\n * const result = isValid(1393804800000)\n * //=> true\n *\n * @example\n * // For the invalid date:\n * const result = isValid(new Date(''))\n * //=> false\n */\nfunction isValid(date) {\n return !(\n (!(0, _index.isDate)(date) && typeof date !== \"number\") ||\n isNaN(+(0, _index2.toDate)(date))\n );\n}\n", "\"use strict\";\nexports.differenceInBusinessDays = differenceInBusinessDays;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./addDays.cjs\");\nvar _index3 = require(\"./differenceInCalendarDays.cjs\");\nvar _index4 = require(\"./isSameDay.cjs\");\nvar _index5 = require(\"./isValid.cjs\");\nvar _index6 = require(\"./isWeekend.cjs\");\n\n/**\n * The {@link differenceInBusinessDays} function options.\n */\n\n/**\n * @name differenceInBusinessDays\n * @category Day Helpers\n * @summary Get the number of business days between the given dates.\n *\n * @description\n * Get the number of business day periods between the given dates.\n * Business days being days that aren't in the weekend.\n * Like `differenceInCalendarDays`, the function removes the times from\n * the dates before calculating the difference.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of business days\n *\n * @example\n * // How many business days are between\n * // 10 January 2014 and 20 July 2014?\n * const result = differenceInBusinessDays(\n * new Date(2014, 6, 20),\n * new Date(2014, 0, 10)\n * )\n * //=> 136\n *\n * // How many business days are between\n * // 30 November 2021 and 1 November 2021?\n * const result = differenceInBusinessDays(\n * new Date(2021, 10, 30),\n * new Date(2021, 10, 1)\n * )\n * //=> 21\n *\n * // How many business days are between\n * // 1 November 2021 and 1 December 2021?\n * const result = differenceInBusinessDays(\n * new Date(2021, 10, 1),\n * new Date(2021, 11, 1)\n * )\n * //=> -22\n *\n * // How many business days are between\n * // 1 November 2021 and 1 November 2021 ?\n * const result = differenceInBusinessDays(\n * new Date(2021, 10, 1),\n * new Date(2021, 10, 1)\n * )\n * //=> 0\n */\nfunction differenceInBusinessDays(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n if (!(0, _index5.isValid)(laterDate_) || !(0, _index5.isValid)(earlierDate_))\n return NaN;\n\n const diff = (0, _index3.differenceInCalendarDays)(laterDate_, earlierDate_);\n const sign = diff < 0 ? -1 : 1;\n const weeks = Math.trunc(diff / 7);\n\n let result = weeks * 5;\n let movingDate = (0, _index2.addDays)(earlierDate_, weeks * 7);\n\n // the loop below will run at most 6 times to account for the remaining days that don't makeup a full week\n while (!(0, _index4.isSameDay)(laterDate_, movingDate)) {\n // sign is used to account for both negative and positive differences\n result += (0, _index6.isWeekend)(movingDate, options) ? 0 : sign;\n movingDate = (0, _index2.addDays)(movingDate, sign);\n }\n\n // Prevent negative zero\n return result === 0 ? 0 : result;\n}\n", "\"use strict\";\nexports.differenceInCalendarISOWeekYears = differenceInCalendarISOWeekYears;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./getISOWeekYear.cjs\");\n\n/**\n * The {@link differenceInCalendarISOWeekYears} function options.\n */\n\n/**\n * @name differenceInCalendarISOWeekYears\n * @category ISO Week-Numbering Year Helpers\n * @summary Get the number of calendar ISO week-numbering years between the given dates.\n *\n * @description\n * Get the number of calendar ISO week-numbering years between the given dates.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of calendar ISO week-numbering years\n *\n * @example\n * // How many calendar ISO week-numbering years are 1 January 2010 and 1 January 2012?\n * const result = differenceInCalendarISOWeekYears(\n * new Date(2012, 0, 1),\n * new Date(2010, 0, 1)\n * )\n * //=> 2\n */\nfunction differenceInCalendarISOWeekYears(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return (\n (0, _index2.getISOWeekYear)(laterDate_, options) -\n (0, _index2.getISOWeekYear)(earlierDate_, options)\n );\n}\n", "\"use strict\";\nexports.differenceInCalendarISOWeeks = differenceInCalendarISOWeeks;\nvar _index = require(\"./_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _index2 = require(\"./_lib/normalizeDates.cjs\");\nvar _index3 = require(\"./constants.cjs\");\nvar _index4 = require(\"./startOfISOWeek.cjs\");\n\n/**\n * The {@link differenceInCalendarISOWeeks} function options.\n */\n\n/**\n * @name differenceInCalendarISOWeeks\n * @category ISO Week Helpers\n * @summary Get the number of calendar ISO weeks between the given dates.\n *\n * @description\n * Get the number of calendar ISO weeks between the given dates.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of calendar ISO weeks\n *\n * @example\n * // How many calendar ISO weeks are between 6 July 2014 and 21 July 2014?\n * const result = differenceInCalendarISOWeeks(\n * new Date(2014, 6, 21),\n * new Date(2014, 6, 6),\n * );\n * //=> 3\n */\nfunction differenceInCalendarISOWeeks(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index2.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const startOfISOWeekLeft = (0, _index4.startOfISOWeek)(laterDate_);\n const startOfISOWeekRight = (0, _index4.startOfISOWeek)(earlierDate_);\n\n const timestampLeft =\n +startOfISOWeekLeft -\n (0, _index.getTimezoneOffsetInMilliseconds)(startOfISOWeekLeft);\n const timestampRight =\n +startOfISOWeekRight -\n (0, _index.getTimezoneOffsetInMilliseconds)(startOfISOWeekRight);\n\n // Round the number of weeks to the nearest integer because the number of\n // milliseconds in a week is not constant (e.g. it's different in the week of\n // the daylight saving time clock shift).\n return Math.round(\n (timestampLeft - timestampRight) / _index3.millisecondsInWeek,\n );\n}\n", "\"use strict\";\nexports.differenceInCalendarMonths = differenceInCalendarMonths;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\n\n/**\n * The {@link differenceInCalendarMonths} function options.\n */\n\n/**\n * @name differenceInCalendarMonths\n * @category Month Helpers\n * @summary Get the number of calendar months between the given dates.\n *\n * @description\n * Get the number of calendar months between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of calendar months\n *\n * @example\n * // How many calendar months are between 31 January 2014 and 1 September 2014?\n * const result = differenceInCalendarMonths(\n * new Date(2014, 8, 1),\n * new Date(2014, 0, 31)\n * )\n * //=> 8\n */\nfunction differenceInCalendarMonths(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const yearsDiff = laterDate_.getFullYear() - earlierDate_.getFullYear();\n const monthsDiff = laterDate_.getMonth() - earlierDate_.getMonth();\n\n return yearsDiff * 12 + monthsDiff;\n}\n", "\"use strict\";\nexports.getQuarter = getQuarter;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getQuarter} function options.\n */\n\n/**\n * @name getQuarter\n * @category Quarter Helpers\n * @summary Get the year quarter of the given date.\n *\n * @description\n * Get the year quarter of the given date.\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The quarter\n *\n * @example\n * // Which quarter is 2 July 2014?\n * const result = getQuarter(new Date(2014, 6, 2));\n * //=> 3\n */\nfunction getQuarter(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const quarter = Math.trunc(_date.getMonth() / 3) + 1;\n return quarter;\n}\n", "\"use strict\";\nexports.differenceInCalendarQuarters = differenceInCalendarQuarters;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./getQuarter.cjs\");\n\n/**\n * The {@link differenceInCalendarQuarters} function options.\n */\n\n/**\n * @name differenceInCalendarQuarters\n * @category Quarter Helpers\n * @summary Get the number of calendar quarters between the given dates.\n *\n * @description\n * Get the number of calendar quarters between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of calendar quarters\n *\n * @example\n * // How many calendar quarters are between 31 December 2013 and 2 July 2014?\n * const result = differenceInCalendarQuarters(\n * new Date(2014, 6, 2),\n * new Date(2013, 11, 31)\n * )\n * //=> 3\n */\nfunction differenceInCalendarQuarters(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const yearsDiff = laterDate_.getFullYear() - earlierDate_.getFullYear();\n const quartersDiff =\n (0, _index2.getQuarter)(laterDate_) - (0, _index2.getQuarter)(earlierDate_);\n\n return yearsDiff * 4 + quartersDiff;\n}\n", "\"use strict\";\nexports.differenceInCalendarWeeks = differenceInCalendarWeeks;\nvar _index = require(\"./_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _index2 = require(\"./_lib/normalizeDates.cjs\");\nvar _index3 = require(\"./constants.cjs\");\nvar _index4 = require(\"./startOfWeek.cjs\");\n\n/**\n * The {@link differenceInCalendarWeeks} function options.\n */\n\n/**\n * @name differenceInCalendarWeeks\n * @category Week Helpers\n * @summary Get the number of calendar weeks between the given dates.\n *\n * @description\n * Get the number of calendar weeks between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options.\n *\n * @returns The number of calendar weeks\n *\n * @example\n * // How many calendar weeks are between 5 July 2014 and 20 July 2014?\n * const result = differenceInCalendarWeeks(\n * new Date(2014, 6, 20),\n * new Date(2014, 6, 5)\n * )\n * //=> 3\n *\n * @example\n * // If the week starts on Monday,\n * // how many calendar weeks are between 5 July 2014 and 20 July 2014?\n * const result = differenceInCalendarWeeks(\n * new Date(2014, 6, 20),\n * new Date(2014, 6, 5),\n * { weekStartsOn: 1 }\n * )\n * //=> 2\n */\nfunction differenceInCalendarWeeks(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index2.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const laterStartOfWeek = (0, _index4.startOfWeek)(laterDate_, options);\n const earlierStartOfWeek = (0, _index4.startOfWeek)(earlierDate_, options);\n\n const laterTimestamp =\n +laterStartOfWeek -\n (0, _index.getTimezoneOffsetInMilliseconds)(laterStartOfWeek);\n const earlierTimestamp =\n +earlierStartOfWeek -\n (0, _index.getTimezoneOffsetInMilliseconds)(earlierStartOfWeek);\n\n return Math.round(\n (laterTimestamp - earlierTimestamp) / _index3.millisecondsInWeek,\n );\n}\n", "\"use strict\";\nexports.differenceInCalendarYears = differenceInCalendarYears;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\n\n/**\n * The {@link differenceInCalendarYears} function options.\n */\n\n/**\n * @name differenceInCalendarYears\n * @category Year Helpers\n * @summary Get the number of calendar years between the given dates.\n *\n * @description\n * Get the number of calendar years between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n\n * @returns The number of calendar years\n *\n * @example\n * // How many calendar years are between 31 December 2013 and 11 February 2015?\n * const result = differenceInCalendarYears(\n * new Date(2015, 1, 11),\n * new Date(2013, 11, 31)\n * );\n * //=> 2\n */\nfunction differenceInCalendarYears(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return laterDate_.getFullYear() - earlierDate_.getFullYear();\n}\n", "\"use strict\";\nexports.differenceInDays = differenceInDays;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./differenceInCalendarDays.cjs\");\n\n/**\n * The {@link differenceInDays} function options.\n */\n\n/**\n * @name differenceInDays\n * @category Day Helpers\n * @summary Get the number of full days between the given dates.\n *\n * @description\n * Get the number of full day periods between two dates. Fractional days are\n * truncated towards zero.\n *\n * One \"full day\" is the distance between a local time in one day to the same\n * local time on the next or previous day. A full day can sometimes be less than\n * or more than 24 hours if a daylight savings change happens between two dates.\n *\n * To ignore DST and only measure exact 24-hour periods, use this instead:\n * `Math.trunc(differenceInHours(dateLeft, dateRight)/24)|0`.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of full days according to the local timezone\n *\n * @example\n * // How many full days are between\n * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?\n * const result = differenceInDays(\n * new Date(2012, 6, 2, 0, 0),\n * new Date(2011, 6, 2, 23, 0)\n * )\n * //=> 365\n *\n * @example\n * // How many full days are between\n * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?\n * const result = differenceInDays(\n * new Date(2011, 6, 3, 0, 1),\n * new Date(2011, 6, 2, 23, 59)\n * )\n * //=> 0\n *\n * @example\n * // How many full days are between\n * // 1 March 2020 0:00 and 1 June 2020 0:00 ?\n * // Note: because local time is used, the\n * // result will always be 92 days, even in\n * // time zones where DST starts and the\n * // period has only 92*24-1 hours.\n * const result = differenceInDays(\n * new Date(2020, 5, 1),\n * new Date(2020, 2, 1)\n * )\n * //=> 92\n */\nfunction differenceInDays(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const sign = compareLocalAsc(laterDate_, earlierDate_);\n const difference = Math.abs(\n (0, _index2.differenceInCalendarDays)(laterDate_, earlierDate_),\n );\n\n laterDate_.setDate(laterDate_.getDate() - sign * difference);\n\n // Math.abs(diff in full days - diff in calendar days) === 1 if last calendar day is not full\n // If so, result must be decreased by 1 in absolute value\n const isLastDayNotFull = Number(\n compareLocalAsc(laterDate_, earlierDate_) === -sign,\n );\n\n const result = sign * (difference - isLastDayNotFull);\n // Prevent negative zero\n return result === 0 ? 0 : result;\n}\n\n// Like `compareAsc` but uses local time not UTC, which is needed\n// for accurate equality comparisons of UTC timestamps that end up\n// having the same representation in local time, e.g. one hour before\n// DST ends vs. the instant that DST ends.\nfunction compareLocalAsc(laterDate, earlierDate) {\n const diff =\n laterDate.getFullYear() - earlierDate.getFullYear() ||\n laterDate.getMonth() - earlierDate.getMonth() ||\n laterDate.getDate() - earlierDate.getDate() ||\n laterDate.getHours() - earlierDate.getHours() ||\n laterDate.getMinutes() - earlierDate.getMinutes() ||\n laterDate.getSeconds() - earlierDate.getSeconds() ||\n laterDate.getMilliseconds() - earlierDate.getMilliseconds();\n\n if (diff < 0) return -1;\n if (diff > 0) return 1;\n\n // Return 0 if diff is 0; return NaN if diff is NaN\n return diff;\n}\n", "\"use strict\";\nexports.getRoundingMethod = getRoundingMethod;\n\nfunction getRoundingMethod(method) {\n return (number) => {\n const round = method ? Math[method] : Math.trunc;\n const result = round(number);\n // Prevent negative zero\n return result === 0 ? 0 : result;\n };\n}\n", "\"use strict\";\nexports.differenceInHours = differenceInHours;\nvar _index = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index2 = require(\"./_lib/normalizeDates.cjs\");\nvar _index3 = require(\"./constants.cjs\");\n\n/**\n * The {@link differenceInHours} function options.\n */\n\n/**\n * @name differenceInHours\n * @category Hour Helpers\n * @summary Get the number of hours between the given dates.\n *\n * @description\n * Get the number of hours between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options.\n *\n * @returns The number of hours\n *\n * @example\n * // How many hours are between 2 July 2014 06:50:00 and 2 July 2014 19:00:00?\n * const result = differenceInHours(\n * new Date(2014, 6, 2, 19, 0),\n * new Date(2014, 6, 2, 6, 50)\n * )\n * //=> 12\n */\nfunction differenceInHours(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index2.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n const diff = (+laterDate_ - +earlierDate_) / _index3.millisecondsInHour;\n return (0, _index.getRoundingMethod)(options?.roundingMethod)(diff);\n}\n", "\"use strict\";\nexports.subISOWeekYears = subISOWeekYears;\nvar _index = require(\"./addISOWeekYears.cjs\");\n\n/**\n * The {@link subISOWeekYears} function options.\n */\n\n/**\n * @name subISOWeekYears\n * @category ISO Week-Numbering Year Helpers\n * @summary Subtract the specified number of ISO week-numbering years from the given date.\n *\n * @description\n * Subtract the specified number of ISO week-numbering years from the given date.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of ISO week-numbering years to be subtracted.\n * @param options - The options\n *\n * @returns The new date with the ISO week-numbering years subtracted\n *\n * @example\n * // Subtract 5 ISO week-numbering years from 1 September 2014:\n * const result = subISOWeekYears(new Date(2014, 8, 1), 5)\n * //=> Mon Aug 31 2009 00:00:00\n */\nfunction subISOWeekYears(date, amount, options) {\n return (0, _index.addISOWeekYears)(date, -amount, options);\n}\n", "\"use strict\";\nexports.differenceInISOWeekYears = differenceInISOWeekYears;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./compareAsc.cjs\");\nvar _index3 = require(\"./differenceInCalendarISOWeekYears.cjs\");\nvar _index4 = require(\"./subISOWeekYears.cjs\");\n\n/**\n * The {@link differenceInISOWeekYears} function options.\n */\n\n/**\n * @name differenceInISOWeekYears\n * @category ISO Week-Numbering Year Helpers\n * @summary Get the number of full ISO week-numbering years between the given dates.\n *\n * @description\n * Get the number of full ISO week-numbering years between the given dates.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - The options\n *\n * @returns The number of full ISO week-numbering years\n *\n * @example\n * // How many full ISO week-numbering years are between 1 January 2010 and 1 January 2012?\n * const result = differenceInISOWeekYears(\n * new Date(2012, 0, 1),\n * new Date(2010, 0, 1)\n * )\n * // => 1\n */\nfunction differenceInISOWeekYears(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const sign = (0, _index2.compareAsc)(laterDate_, earlierDate_);\n const diff = Math.abs(\n (0, _index3.differenceInCalendarISOWeekYears)(\n laterDate_,\n earlierDate_,\n options,\n ),\n );\n\n const adjustedDate = (0, _index4.subISOWeekYears)(\n laterDate_,\n sign * diff,\n options,\n );\n\n const isLastISOWeekYearNotFull = Number(\n (0, _index2.compareAsc)(adjustedDate, earlierDate_) === -sign,\n );\n const result = sign * (diff - isLastISOWeekYearNotFull);\n\n // Prevent negative zero\n return result === 0 ? 0 : result;\n}\n", "\"use strict\";\nexports.differenceInMilliseconds = differenceInMilliseconds;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name differenceInMilliseconds\n * @category Millisecond Helpers\n * @summary Get the number of milliseconds between the given dates.\n *\n * @description\n * Get the number of milliseconds between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n *\n * @returns The number of milliseconds\n *\n * @example\n * // How many milliseconds are between\n * // 2 July 2014 12:30:20.600 and 2 July 2014 12:30:21.700?\n * const result = differenceInMilliseconds(\n * new Date(2014, 6, 2, 12, 30, 21, 700),\n * new Date(2014, 6, 2, 12, 30, 20, 600)\n * )\n * //=> 1100\n */\nfunction differenceInMilliseconds(laterDate, earlierDate) {\n return +(0, _index.toDate)(laterDate) - +(0, _index.toDate)(earlierDate);\n}\n", "\"use strict\";\nexports.differenceInMinutes = differenceInMinutes;\nvar _index = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index2 = require(\"./constants.cjs\");\nvar _index3 = require(\"./differenceInMilliseconds.cjs\");\n\n/**\n * The {@link differenceInMinutes} function options.\n */\n\n/**\n * @name differenceInMinutes\n * @category Minute Helpers\n * @summary Get the number of minutes between the given dates.\n *\n * @description\n * Get the signed number of full (rounded towards 0) minutes between the given dates.\n *\n * @param dateLeft - The later date\n * @param dateRight - The earlier date\n * @param options - An object with options.\n *\n * @returns The number of minutes\n *\n * @example\n * // How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00?\n * const result = differenceInMinutes(\n * new Date(2014, 6, 2, 12, 20, 0),\n * new Date(2014, 6, 2, 12, 7, 59)\n * )\n * //=> 12\n *\n * @example\n * // How many minutes are between 10:01:59 and 10:00:00\n * const result = differenceInMinutes(\n * new Date(2000, 0, 1, 10, 0, 0),\n * new Date(2000, 0, 1, 10, 1, 59)\n * )\n * //=> -1\n */\nfunction differenceInMinutes(dateLeft, dateRight, options) {\n const diff =\n (0, _index3.differenceInMilliseconds)(dateLeft, dateRight) /\n _index2.millisecondsInMinute;\n return (0, _index.getRoundingMethod)(options?.roundingMethod)(diff);\n}\n", "\"use strict\";\nexports.endOfDay = endOfDay;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfDay} function options.\n */\n\n/**\n * @name endOfDay\n * @category Day Helpers\n * @summary Return the end of a day for the given date.\n *\n * @description\n * Return the end of a day for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a day\n *\n * @example\n * // The end of a day for 2 September 2014 11:55:00:\n * const result = endOfDay(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 02 2014 23:59:59.999\n */\nfunction endOfDay(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setHours(23, 59, 59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.endOfMonth = endOfMonth;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfMonth} function options.\n */\n\n/**\n * @name endOfMonth\n * @category Month Helpers\n * @summary Return the end of a month for the given date.\n *\n * @description\n * Return the end of a month for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a month\n *\n * @example\n * // The end of a month for 2 September 2014 11:55:00:\n * const result = endOfMonth(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 30 2014 23:59:59.999\n */\nfunction endOfMonth(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const month = _date.getMonth();\n _date.setFullYear(_date.getFullYear(), month + 1, 0);\n _date.setHours(23, 59, 59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.isLastDayOfMonth = isLastDayOfMonth;\nvar _index = require(\"./endOfDay.cjs\");\nvar _index2 = require(\"./endOfMonth.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * @name isLastDayOfMonth\n * @category Month Helpers\n * @summary Is the given date the last day of a month?\n *\n * @description\n * Is the given date the last day of a month?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is the last day of a month\n *\n * @example\n * // Is 28 February 2014 the last day of a month?\n * const result = isLastDayOfMonth(new Date(2014, 1, 28))\n * //=> true\n */\nfunction isLastDayOfMonth(date, options) {\n const _date = (0, _index3.toDate)(date, options?.in);\n return (\n +(0, _index.endOfDay)(_date, options) ===\n +(0, _index2.endOfMonth)(_date, options)\n );\n}\n", "\"use strict\";\nexports.differenceInMonths = differenceInMonths;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./compareAsc.cjs\");\nvar _index3 = require(\"./differenceInCalendarMonths.cjs\");\nvar _index4 = require(\"./isLastDayOfMonth.cjs\");\n\n/**\n * The {@link differenceInMonths} function options.\n */\n\n/**\n * @name differenceInMonths\n * @category Month Helpers\n * @summary Get the number of full months between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of full months\n *\n * @example\n * // How many full months are between 31 January 2014 and 1 September 2014?\n * const result = differenceInMonths(new Date(2014, 8, 1), new Date(2014, 0, 31))\n * //=> 7\n */\nfunction differenceInMonths(laterDate, earlierDate, options) {\n const [laterDate_, workingLaterDate, earlierDate_] = (0,\n _index.normalizeDates)(options?.in, laterDate, laterDate, earlierDate);\n\n const sign = (0, _index2.compareAsc)(workingLaterDate, earlierDate_);\n const difference = Math.abs(\n (0, _index3.differenceInCalendarMonths)(workingLaterDate, earlierDate_),\n );\n\n if (difference < 1) return 0;\n\n if (workingLaterDate.getMonth() === 1 && workingLaterDate.getDate() > 27)\n workingLaterDate.setDate(30);\n\n workingLaterDate.setMonth(workingLaterDate.getMonth() - sign * difference);\n\n let isLastMonthNotFull =\n (0, _index2.compareAsc)(workingLaterDate, earlierDate_) === -sign;\n\n if (\n (0, _index4.isLastDayOfMonth)(laterDate_) &&\n difference === 1 &&\n (0, _index2.compareAsc)(laterDate_, earlierDate_) === 1\n ) {\n isLastMonthNotFull = false;\n }\n\n const result = sign * (difference - +isLastMonthNotFull);\n return result === 0 ? 0 : result;\n}\n", "\"use strict\";\nexports.differenceInQuarters = differenceInQuarters;\nvar _index = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index2 = require(\"./differenceInMonths.cjs\");\n\n/**\n * The {@link differenceInQuarters} function options.\n */\n\n/**\n * @name differenceInQuarters\n * @category Quarter Helpers\n * @summary Get the number of quarters between the given dates.\n *\n * @description\n * Get the number of quarters between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options.\n *\n * @returns The number of full quarters\n *\n * @example\n * // How many full quarters are between 31 December 2013 and 2 July 2014?\n * const result = differenceInQuarters(new Date(2014, 6, 2), new Date(2013, 11, 31))\n * //=> 2\n */\nfunction differenceInQuarters(laterDate, earlierDate, options) {\n const diff =\n (0, _index2.differenceInMonths)(laterDate, earlierDate, options) / 3;\n return (0, _index.getRoundingMethod)(options?.roundingMethod)(diff);\n}\n", "\"use strict\";\nexports.differenceInSeconds = differenceInSeconds;\nvar _index = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index2 = require(\"./differenceInMilliseconds.cjs\");\n\n/**\n * The {@link differenceInSeconds} function options.\n */\n\n/**\n * @name differenceInSeconds\n * @category Second Helpers\n * @summary Get the number of seconds between the given dates.\n *\n * @description\n * Get the number of seconds between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options.\n *\n * @returns The number of seconds\n *\n * @example\n * // How many seconds are between\n * // 2 July 2014 12:30:07.999 and 2 July 2014 12:30:20.000?\n * const result = differenceInSeconds(\n * new Date(2014, 6, 2, 12, 30, 20, 0),\n * new Date(2014, 6, 2, 12, 30, 7, 999)\n * )\n * //=> 12\n */\nfunction differenceInSeconds(laterDate, earlierDate, options) {\n const diff =\n (0, _index2.differenceInMilliseconds)(laterDate, earlierDate) / 1000;\n return (0, _index.getRoundingMethod)(options?.roundingMethod)(diff);\n}\n", "\"use strict\";\nexports.differenceInWeeks = differenceInWeeks;\nvar _index = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index2 = require(\"./differenceInDays.cjs\");\n\n/**\n * The {@link differenceInWeeks} function options.\n */\n\n/**\n * @name differenceInWeeks\n * @category Week Helpers\n * @summary Get the number of full weeks between the given dates.\n *\n * @description\n * Get the number of full weeks between two dates. Fractional weeks are\n * truncated towards zero by default.\n *\n * One \"full week\" is the distance between a local time in one day to the same\n * local time 7 days earlier or later. A full week can sometimes be less than\n * or more than 7*24 hours if a daylight savings change happens between two dates.\n *\n * To ignore DST and only measure exact 7*24-hour periods, use this instead:\n * `Math.trunc(differenceInHours(dateLeft, dateRight)/(7*24))|0`.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of full weeks\n *\n * @example\n * // How many full weeks are between 5 July 2014 and 20 July 2014?\n * const result = differenceInWeeks(new Date(2014, 6, 20), new Date(2014, 6, 5))\n * //=> 2\n *\n * @example\n * // How many full weeks are between\n * // 1 March 2020 0:00 and 6 June 2020 0:00 ?\n * // Note: because local time is used, the\n * // result will always be 8 weeks (54 days),\n * // even if DST starts and the period has\n * // only 54*24-1 hours.\n * const result = differenceInWeeks(\n * new Date(2020, 5, 1),\n * new Date(2020, 2, 6)\n * )\n * //=> 8\n */\nfunction differenceInWeeks(laterDate, earlierDate, options) {\n const diff =\n (0, _index2.differenceInDays)(laterDate, earlierDate, options) / 7;\n return (0, _index.getRoundingMethod)(options?.roundingMethod)(diff);\n}\n", "\"use strict\";\nexports.differenceInYears = differenceInYears;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./compareAsc.cjs\");\nvar _index3 = require(\"./differenceInCalendarYears.cjs\");\n\n/**\n * The {@link differenceInYears} function options.\n */\n\n/**\n * @name differenceInYears\n * @category Year Helpers\n * @summary Get the number of full years between the given dates.\n *\n * @description\n * Get the number of full years between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of full years\n *\n * @example\n * // How many full years are between 31 December 2013 and 11 February 2015?\n * const result = differenceInYears(new Date(2015, 1, 11), new Date(2013, 11, 31))\n * //=> 1\n */\nfunction differenceInYears(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n // -1 if the left date is earlier than the right date\n // 2023-12-31 - 2024-01-01 = -1\n const sign = (0, _index2.compareAsc)(laterDate_, earlierDate_);\n\n // First calculate the difference in calendar years\n // 2024-01-01 - 2023-12-31 = 1 year\n const diff = Math.abs(\n (0, _index3.differenceInCalendarYears)(laterDate_, earlierDate_),\n );\n\n // Now we need to calculate if the difference is full. To do that we set\n // both dates to the same year and check if the both date's month and day\n // form a full year.\n laterDate_.setFullYear(1584);\n earlierDate_.setFullYear(1584);\n\n // For it to be true, when the later date is indeed later than the earlier date\n // (2026-02-01 - 2023-12-10 = 3 years), the difference is full if\n // the normalized later date is also later than the normalized earlier date.\n // In our example, 1584-02-01 is earlier than 1584-12-10, so the difference\n // is partial, hence we need to subtract 1 from the difference 3 - 1 = 2.\n const partial = (0, _index2.compareAsc)(laterDate_, earlierDate_) === -sign;\n\n const result = sign * (diff - +partial);\n\n // Prevent negative zero\n return result === 0 ? 0 : result;\n}\n", "\"use strict\";\nexports.normalizeInterval = normalizeInterval;\nvar _index = require(\"./normalizeDates.cjs\");\n\nfunction normalizeInterval(context, interval) {\n const [start, end] = (0, _index.normalizeDates)(\n context,\n interval.start,\n interval.end,\n );\n return { start, end };\n}\n", "\"use strict\";\nexports.eachDayOfInterval = eachDayOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\n\n/**\n * The {@link eachDayOfInterval} function options.\n */\n\n/**\n * The {@link eachDayOfInterval} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the date argument,\n * then the start interval date, and finally the end interval date. If\n * a context function is passed, it uses the context function return type.\n */\n\n/**\n * @name eachDayOfInterval\n * @category Interval Helpers\n * @summary Return the array of dates within the specified time interval.\n *\n * @description\n * Return the array of dates within the specified time interval.\n *\n * @typeParam IntervalType - Interval type.\n * @typeParam Options - Options type.\n *\n * @param interval - The interval.\n * @param options - An object with options.\n *\n * @returns The array with starts of days from the day of the interval start to the day of the interval end\n *\n * @example\n * // Each day between 6 October 2014 and 10 October 2014:\n * const result = eachDayOfInterval({\n * start: new Date(2014, 9, 6),\n * end: new Date(2014, 9, 10)\n * })\n * //=> [\n * // Mon Oct 06 2014 00:00:00,\n * // Tue Oct 07 2014 00:00:00,\n * // Wed Oct 08 2014 00:00:00,\n * // Thu Oct 09 2014 00:00:00,\n * // Fri Oct 10 2014 00:00:00\n * // ]\n */\nfunction eachDayOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n\n let reversed = +start > +end;\n const endTime = reversed ? +start : +end;\n const date = reversed ? end : start;\n date.setHours(0, 0, 0, 0);\n\n let step = options?.step ?? 1;\n if (!step) return [];\n if (step < 0) {\n step = -step;\n reversed = !reversed;\n }\n\n const dates = [];\n\n while (+date <= endTime) {\n dates.push((0, _index2.constructFrom)(start, date));\n date.setDate(date.getDate() + step);\n date.setHours(0, 0, 0, 0);\n }\n\n return reversed ? dates.reverse() : dates;\n}\n", "\"use strict\";\nexports.eachHourOfInterval = eachHourOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\n\n/**\n * The {@link eachHourOfInterval} function options.\n */\n\n/**\n * The {@link eachHourOfInterval} function result type.\n * Resolves to the appropriate date type based on inputs.\n */\n\n/**\n * @name eachHourOfInterval\n * @category Interval Helpers\n * @summary Return the array of hours within the specified time interval.\n *\n * @description\n * Return the array of hours within the specified time interval.\n *\n * @typeParam IntervalType - Interval type.\n * @typeParam Options - Options type.\n *\n * @param interval - The interval.\n * @param options - An object with options.\n *\n * @returns The array with starts of hours from the hour of the interval start to the hour of the interval end\n *\n * @example\n * // Each hour between 6 October 2014, 12:00 and 6 October 2014, 15:00\n * const result = eachHourOfInterval({\n * start: new Date(2014, 9, 6, 12),\n * end: new Date(2014, 9, 6, 15)\n * });\n * //=> [\n * // Mon Oct 06 2014 12:00:00,\n * // Mon Oct 06 2014 13:00:00,\n * // Mon Oct 06 2014 14:00:00,\n * // Mon Oct 06 2014 15:00:00\n * // ]\n */\nfunction eachHourOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n\n let reversed = +start > +end;\n const endTime = reversed ? +start : +end;\n const date = reversed ? end : start;\n date.setMinutes(0, 0, 0);\n\n let step = options?.step ?? 1;\n if (!step) return [];\n if (step < 0) {\n step = -step;\n reversed = !reversed;\n }\n\n const dates = [];\n\n while (+date <= endTime) {\n dates.push((0, _index2.constructFrom)(start, date));\n date.setHours(date.getHours() + step);\n }\n\n return reversed ? dates.reverse() : dates;\n}\n", "\"use strict\";\nexports.eachMinuteOfInterval = eachMinuteOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./addMinutes.cjs\");\nvar _index3 = require(\"./constructFrom.cjs\");\n\n/**\n * The {@link eachMinuteOfInterval} function options.\n */\n\n/**\n * The {@link eachMinuteOfInterval} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the date argument,\n * then the start interval date, and finally the end interval date. If\n * a context function is passed, it uses the context function return type.\n */\n\n/**\n * @name eachMinuteOfInterval\n * @category Interval Helpers\n * @summary Return the array of minutes within the specified time interval.\n *\n * @description\n * Returns the array of minutes within the specified time interval.\n *\n * @typeParam IntervalType - Interval type.\n * @typeParam Options - Options type.\n *\n * @param interval - The interval.\n * @param options - An object with options.\n *\n * @returns The array with starts of minutes from the minute of the interval start to the minute of the interval end\n *\n * @example\n * // Each minute between 14 October 2020, 13:00 and 14 October 2020, 13:03\n * const result = eachMinuteOfInterval({\n * start: new Date(2014, 9, 14, 13),\n * end: new Date(2014, 9, 14, 13, 3)\n * })\n * //=> [\n * // Wed Oct 14 2014 13:00:00,\n * // Wed Oct 14 2014 13:01:00,\n * // Wed Oct 14 2014 13:02:00,\n * // Wed Oct 14 2014 13:03:00\n * // ]\n */\nfunction eachMinuteOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n // Set to the start of the minute\n start.setSeconds(0, 0);\n\n let reversed = +start > +end;\n const endTime = reversed ? +start : +end;\n let date = reversed ? end : start;\n\n let step = options?.step ?? 1;\n if (!step) return [];\n if (step < 0) {\n step = -step;\n reversed = !reversed;\n }\n\n const dates = [];\n\n while (+date <= endTime) {\n dates.push((0, _index3.constructFrom)(start, date));\n date = (0, _index2.addMinutes)(date, step);\n }\n\n return reversed ? dates.reverse() : dates;\n}\n", "\"use strict\";\nexports.eachMonthOfInterval = eachMonthOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\n\n/**\n * The {@link eachMonthOfInterval} function options.\n */\n\n/**\n * The {@link eachMonthOfInterval} function result type. It resolves the proper data type.\n */\n\n/**\n * @name eachMonthOfInterval\n * @category Interval Helpers\n * @summary Return the array of months within the specified time interval.\n *\n * @description\n * Return the array of months within the specified time interval.\n *\n * @typeParam IntervalType - Interval type.\n * @typeParam Options - Options type.\n *\n * @param interval - The interval.\n * @param options - An object with options.\n *\n * @returns The array with starts of months from the month of the interval start to the month of the interval end\n *\n * @example\n * // Each month between 6 February 2014 and 10 August 2014:\n * const result = eachMonthOfInterval({\n * start: new Date(2014, 1, 6),\n * end: new Date(2014, 7, 10)\n * })\n * //=> [\n * // Sat Feb 01 2014 00:00:00,\n * // Sat Mar 01 2014 00:00:00,\n * // Tue Apr 01 2014 00:00:00,\n * // Thu May 01 2014 00:00:00,\n * // Sun Jun 01 2014 00:00:00,\n * // Tue Jul 01 2014 00:00:00,\n * // Fri Aug 01 2014 00:00:00\n * // ]\n */\nfunction eachMonthOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n\n let reversed = +start > +end;\n const endTime = reversed ? +start : +end;\n const date = reversed ? end : start;\n date.setHours(0, 0, 0, 0);\n date.setDate(1);\n\n let step = options?.step ?? 1;\n if (!step) return [];\n if (step < 0) {\n step = -step;\n reversed = !reversed;\n }\n\n const dates = [];\n\n while (+date <= endTime) {\n dates.push((0, _index2.constructFrom)(start, date));\n date.setMonth(date.getMonth() + step);\n }\n\n return reversed ? dates.reverse() : dates;\n}\n", "\"use strict\";\nexports.startOfQuarter = startOfQuarter;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfQuarter} function options.\n */\n\n/**\n * @name startOfQuarter\n * @category Quarter Helpers\n * @summary Return the start of a year quarter for the given date.\n *\n * @description\n * Return the start of a year quarter for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The start of a quarter\n *\n * @example\n * // The start of a quarter for 2 September 2014 11:55:00:\n * const result = startOfQuarter(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Jul 01 2014 00:00:00\n */\nfunction startOfQuarter(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const currentMonth = _date.getMonth();\n const month = currentMonth - (currentMonth % 3);\n _date.setMonth(month, 1);\n _date.setHours(0, 0, 0, 0);\n return _date;\n}\n", "\"use strict\";\nexports.eachQuarterOfInterval = eachQuarterOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./addQuarters.cjs\");\nvar _index3 = require(\"./constructFrom.cjs\");\nvar _index4 = require(\"./startOfQuarter.cjs\");\n\n/**\n * The {@link eachQuarterOfInterval} function options.\n */\n\n/**\n * The {@link eachQuarterOfInterval} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the date argument,\n * then the start interval date, and finally the end interval date. If\n * a context function is passed, it uses the context function return type.\n */\n\n/**\n * @name eachQuarterOfInterval\n * @category Interval Helpers\n * @summary Return the array of quarters within the specified time interval.\n *\n * @description\n * Return the array of quarters within the specified time interval.\n *\n * @typeParam IntervalType - Interval type.\n * @typeParam Options - Options type.\n *\n * @param interval - The interval\n * @param options - An object with options\n *\n * @returns The array with starts of quarters from the quarter of the interval start to the quarter of the interval end\n *\n * @example\n * // Each quarter within interval 6 February 2014 - 10 August 2014:\n * const result = eachQuarterOfInterval({\n * start: new Date(2014, 1, 6),\n * end: new Date(2014, 7, 10),\n * })\n * //=> [\n * // Wed Jan 01 2014 00:00:00,\n * // Tue Apr 01 2014 00:00:00,\n * // Tue Jul 01 2014 00:00:00,\n * // ]\n */\nfunction eachQuarterOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n\n let reversed = +start > +end;\n const endTime = reversed\n ? +(0, _index4.startOfQuarter)(start)\n : +(0, _index4.startOfQuarter)(end);\n let date = reversed\n ? (0, _index4.startOfQuarter)(end)\n : (0, _index4.startOfQuarter)(start);\n\n let step = options?.step ?? 1;\n if (!step) return [];\n if (step < 0) {\n step = -step;\n reversed = !reversed;\n }\n\n const dates = [];\n\n while (+date <= endTime) {\n dates.push((0, _index3.constructFrom)(start, date));\n date = (0, _index2.addQuarters)(date, step);\n }\n\n return reversed ? dates.reverse() : dates;\n}\n", "\"use strict\";\nexports.eachWeekOfInterval = eachWeekOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./addWeeks.cjs\");\nvar _index3 = require(\"./constructFrom.cjs\");\nvar _index4 = require(\"./startOfWeek.cjs\");\n\n/**\n * The {@link eachWeekOfInterval} function options.\n */\n\n/**\n * The {@link eachWeekOfInterval} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the interval start date,\n * then the end interval date. If a context function is passed, it uses the context function return type.\n */\n\n/**\n * @name eachWeekOfInterval\n * @category Interval Helpers\n * @summary Return the array of weeks within the specified time interval.\n *\n * @description\n * Return the array of weeks within the specified time interval.\n *\n * @param interval - The interval.\n * @param options - An object with options.\n *\n * @returns The array with starts of weeks from the week of the interval start to the week of the interval end\n *\n * @example\n * // Each week within interval 6 October 2014 - 23 November 2014:\n * const result = eachWeekOfInterval({\n * start: new Date(2014, 9, 6),\n * end: new Date(2014, 10, 23)\n * })\n * //=> [\n * // Sun Oct 05 2014 00:00:00,\n * // Sun Oct 12 2014 00:00:00,\n * // Sun Oct 19 2014 00:00:00,\n * // Sun Oct 26 2014 00:00:00,\n * // Sun Nov 02 2014 00:00:00,\n * // Sun Nov 09 2014 00:00:00,\n * // Sun Nov 16 2014 00:00:00,\n * // Sun Nov 23 2014 00:00:00\n * // ]\n */\nfunction eachWeekOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n\n let reversed = +start > +end;\n const startDateWeek = reversed\n ? (0, _index4.startOfWeek)(end, options)\n : (0, _index4.startOfWeek)(start, options);\n const endDateWeek = reversed\n ? (0, _index4.startOfWeek)(start, options)\n : (0, _index4.startOfWeek)(end, options);\n\n startDateWeek.setHours(15);\n endDateWeek.setHours(15);\n\n const endTime = +endDateWeek.getTime();\n let currentDate = startDateWeek;\n\n let step = options?.step ?? 1;\n if (!step) return [];\n if (step < 0) {\n step = -step;\n reversed = !reversed;\n }\n\n const dates = [];\n\n while (+currentDate <= endTime) {\n currentDate.setHours(0);\n dates.push((0, _index3.constructFrom)(start, currentDate));\n currentDate = (0, _index2.addWeeks)(currentDate, step);\n currentDate.setHours(15);\n }\n\n return reversed ? dates.reverse() : dates;\n}\n", "\"use strict\";\nexports.eachWeekendOfInterval = eachWeekendOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\nvar _index3 = require(\"./eachDayOfInterval.cjs\");\nvar _index4 = require(\"./isWeekend.cjs\");\n\n/**\n * The {@link eachWeekendOfInterval} function options.\n */\n\n/**\n * The {@link eachWeekendOfInterval} function result type.\n */\n\n/**\n * @name eachWeekendOfInterval\n * @category Interval Helpers\n * @summary List all the Saturdays and Sundays in the given date interval.\n *\n * @description\n * Get all the Saturdays and Sundays in the given date interval.\n *\n * @typeParam IntervalType - Interval type.\n * @typeParam Options - Options type.\n *\n * @param interval - The given interval\n * @param options - An object with options\n *\n * @returns An array containing all the Saturdays and Sundays\n *\n * @example\n * // Lists all Saturdays and Sundays in the given date interval\n * const result = eachWeekendOfInterval({\n * start: new Date(2018, 8, 17),\n * end: new Date(2018, 8, 30)\n * })\n * //=> [\n * // Sat Sep 22 2018 00:00:00,\n * // Sun Sep 23 2018 00:00:00,\n * // Sat Sep 29 2018 00:00:00,\n * // Sun Sep 30 2018 00:00:00\n * // ]\n */\nfunction eachWeekendOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n const dateInterval = (0, _index3.eachDayOfInterval)({ start, end }, options);\n const weekends = [];\n let index = 0;\n while (index < dateInterval.length) {\n const date = dateInterval[index++];\n if ((0, _index4.isWeekend)(date))\n weekends.push((0, _index2.constructFrom)(start, date));\n }\n return weekends;\n}\n", "\"use strict\";\nexports.startOfMonth = startOfMonth;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfMonth} function options.\n */\n\n/**\n * @name startOfMonth\n * @category Month Helpers\n * @summary Return the start of a month for the given date.\n *\n * @description\n * Return the start of a month for the given date. The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments.\n * Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed,\n * or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of a month\n *\n * @example\n * // The start of a month for 2 September 2014 11:55:00:\n * const result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Mon Sep 01 2014 00:00:00\n */\nfunction startOfMonth(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setDate(1);\n _date.setHours(0, 0, 0, 0);\n return _date;\n}\n", "\"use strict\";\nexports.eachWeekendOfMonth = eachWeekendOfMonth;\nvar _index = require(\"./eachWeekendOfInterval.cjs\");\nvar _index2 = require(\"./endOfMonth.cjs\");\nvar _index3 = require(\"./startOfMonth.cjs\");\n\n/**\n * The {@link eachWeekendOfMonth} function options.\n */\n\n/**\n * @name eachWeekendOfMonth\n * @category Month Helpers\n * @summary List all the Saturdays and Sundays in the given month.\n *\n * @description\n * Get all the Saturdays and Sundays in the given month.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The given month\n * @param options - An object with options\n *\n * @returns An array containing all the Saturdays and Sundays\n *\n * @example\n * // Lists all Saturdays and Sundays in the given month\n * const result = eachWeekendOfMonth(new Date(2022, 1, 1))\n * //=> [\n * // Sat Feb 05 2022 00:00:00,\n * // Sun Feb 06 2022 00:00:00,\n * // Sat Feb 12 2022 00:00:00,\n * // Sun Feb 13 2022 00:00:00,\n * // Sat Feb 19 2022 00:00:00,\n * // Sun Feb 20 2022 00:00:00,\n * // Sat Feb 26 2022 00:00:00,\n * // Sun Feb 27 2022 00:00:00\n * // ]\n */\nfunction eachWeekendOfMonth(date, options) {\n const start = (0, _index3.startOfMonth)(date, options);\n const end = (0, _index2.endOfMonth)(date, options);\n return (0, _index.eachWeekendOfInterval)({ start, end }, options);\n}\n", "\"use strict\";\nexports.endOfYear = endOfYear;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfYear} function options.\n */\n\n/**\n * @name endOfYear\n * @category Year Helpers\n * @summary Return the end of a year for the given date.\n *\n * @description\n * Return the end of a year for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The end of a year\n *\n * @example\n * // The end of a year for 2 September 2014 11:55:00:\n * const result = endOfYear(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Wed Dec 31 2014 23:59:59.999\n */\nfunction endOfYear(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const year = _date.getFullYear();\n _date.setFullYear(year + 1, 0, 0);\n _date.setHours(23, 59, 59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.startOfYear = startOfYear;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfYear} function options.\n */\n\n/**\n * @name startOfYear\n * @category Year Helpers\n * @summary Return the start of a year for the given date.\n *\n * @description\n * Return the start of a year for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The start of a year\n *\n * @example\n * // The start of a year for 2 September 2014 11:55:00:\n * const result = startOfYear(new Date(2014, 8, 2, 11, 55, 00))\n * //=> Wed Jan 01 2014 00:00:00\n */\nfunction startOfYear(date, options) {\n const date_ = (0, _index.toDate)(date, options?.in);\n date_.setFullYear(date_.getFullYear(), 0, 1);\n date_.setHours(0, 0, 0, 0);\n return date_;\n}\n", "\"use strict\";\nexports.eachWeekendOfYear = eachWeekendOfYear;\nvar _index = require(\"./eachWeekendOfInterval.cjs\");\nvar _index2 = require(\"./endOfYear.cjs\");\nvar _index3 = require(\"./startOfYear.cjs\");\n\n/**\n * The {@link eachWeekendOfYear} function options.\n */\n\n/**\n * @name eachWeekendOfYear\n * @category Year Helpers\n * @summary List all the Saturdays and Sundays in the year.\n *\n * @description\n * Get all the Saturdays and Sundays in the year.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The given year\n * @param options - An object with options\n *\n * @returns An array containing all the Saturdays and Sundays\n *\n * @example\n * // Lists all Saturdays and Sundays in the year\n * const result = eachWeekendOfYear(new Date(2020, 1, 1))\n * //=> [\n * // Sat Jan 03 2020 00:00:00,\n * // Sun Jan 04 2020 00:00:00,\n * // ...\n * // Sun Dec 27 2020 00:00:00\n * // ]\n * ]\n */\nfunction eachWeekendOfYear(date, options) {\n const start = (0, _index3.startOfYear)(date, options);\n const end = (0, _index2.endOfYear)(date, options);\n return (0, _index.eachWeekendOfInterval)({ start, end }, options);\n}\n", "\"use strict\";\nexports.eachYearOfInterval = eachYearOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\n\n/**\n * The {@link eachYearOfInterval} function options.\n */\n\n/**\n * The {@link eachYearOfInterval} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the date argument,\n * then the start interval date, and finally the end interval date. If\n * a context function is passed, it uses the context function return type.\n */\n\n/**\n * @name eachYearOfInterval\n * @category Interval Helpers\n * @summary Return the array of yearly timestamps within the specified time interval.\n *\n * @description\n * Return the array of yearly timestamps within the specified time interval.\n *\n * @typeParam IntervalType - Interval type.\n * @typeParam Options - Options type.\n *\n * @param interval - The interval.\n * @param options - An object with options.\n *\n * @returns The array with starts of yearly timestamps from the month of the interval start to the month of the interval end\n *\n * @example\n * // Each year between 6 February 2014 and 10 August 2017:\n * const result = eachYearOfInterval({\n * start: new Date(2014, 1, 6),\n * end: new Date(2017, 7, 10)\n * })\n * //=> [\n * // Wed Jan 01 2014 00:00:00,\n * // Thu Jan 01 2015 00:00:00,\n * // Fri Jan 01 2016 00:00:00,\n * // Sun Jan 01 2017 00:00:00\n * // ]\n */\nfunction eachYearOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n\n let reversed = +start > +end;\n const endTime = reversed ? +start : +end;\n const date = reversed ? end : start;\n date.setHours(0, 0, 0, 0);\n date.setMonth(0, 1);\n\n let step = options?.step ?? 1;\n if (!step) return [];\n if (step < 0) {\n step = -step;\n reversed = !reversed;\n }\n\n const dates = [];\n\n while (+date <= endTime) {\n dates.push((0, _index2.constructFrom)(start, date));\n date.setFullYear(date.getFullYear() + step);\n }\n\n return reversed ? dates.reverse() : dates;\n}\n", "\"use strict\";\nexports.endOfDecade = endOfDecade;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfDecade} function options.\n */\n\n/**\n * @name endOfDecade\n * @category Decade Helpers\n * @summary Return the end of a decade for the given date.\n *\n * @description\n * Return the end of a decade for the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a decade\n *\n * @example\n * // The end of a decade for 12 May 1984 00:00:00:\n * const result = endOfDecade(new Date(1984, 4, 12, 00, 00, 00))\n * //=> Dec 31 1989 23:59:59.999\n */\nfunction endOfDecade(date, options) {\n // TODO: Switch to more technical definition in of decades that start with 1\n // end with 0. I.e. 2001-2010 instead of current 2000-2009. It's a breaking\n // change, so it can only be done in 4.0.\n const _date = (0, _index.toDate)(date, options?.in);\n const year = _date.getFullYear();\n const decade = 9 + Math.floor(year / 10) * 10;\n _date.setFullYear(decade, 11, 31);\n _date.setHours(23, 59, 59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.endOfHour = endOfHour;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfHour} function options.\n */\n\n/**\n * @name endOfHour\n * @category Hour Helpers\n * @summary Return the end of an hour for the given date.\n *\n * @description\n * Return the end of an hour for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of an hour\n *\n * @example\n * // The end of an hour for 2 September 2014 11:55:00:\n * const result = endOfHour(new Date(2014, 8, 2, 11, 55))\n * //=> Tue Sep 02 2014 11:59:59.999\n */\nfunction endOfHour(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setMinutes(59, 59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.endOfWeek = endOfWeek;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfWeek} function options.\n */\n\n/**\n * @name endOfWeek\n * @category Week Helpers\n * @summary Return the end of a week for the given date.\n *\n * @description\n * Return the end of a week for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a week\n *\n * @example\n * // The end of a week for 2 September 2014 11:55:00:\n * const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Sat Sep 06 2014 23:59:59.999\n *\n * @example\n * // If the week starts on Monday, the end of the week for 2 September 2014 11:55:00:\n * const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })\n * //=> Sun Sep 07 2014 23:59:59.999\n */\nfunction endOfWeek(date, options) {\n const defaultOptions = (0, _index.getDefaultOptions)();\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const _date = (0, _index2.toDate)(date, options?.in);\n const day = _date.getDay();\n const diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);\n\n _date.setDate(_date.getDate() + diff);\n _date.setHours(23, 59, 59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.endOfISOWeek = endOfISOWeek;\nvar _index = require(\"./endOfWeek.cjs\");\n\n/**\n * The {@link endOfISOWeek} function options.\n */\n\n/**\n * @name endOfISOWeek\n * @category ISO Week Helpers\n * @summary Return the end of an ISO week for the given date.\n *\n * @description\n * Return the end of an ISO week for the given date.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of an ISO week\n *\n * @example\n * // The end of an ISO week for 2 September 2014 11:55:00:\n * const result = endOfISOWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Sun Sep 07 2014 23:59:59.999\n */\nfunction endOfISOWeek(date, options) {\n return (0, _index.endOfWeek)(date, { ...options, weekStartsOn: 1 });\n}\n", "\"use strict\";\nexports.endOfISOWeekYear = endOfISOWeekYear;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./getISOWeekYear.cjs\");\nvar _index3 = require(\"./startOfISOWeek.cjs\");\n\n/**\n * The {@link endOfISOWeekYear} function options.\n */\n\n/**\n * @name endOfISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Return the end of an ISO week-numbering year for the given date.\n *\n * @description\n * Return the end of an ISO week-numbering year,\n * which always starts 3 days before the year's first Thursday.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ContextDate - The `Date` type of the context function.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The end of an ISO week-numbering year\n *\n * @example\n * // The end of an ISO week-numbering year for 2 July 2005:\n * const result = endOfISOWeekYear(new Date(2005, 6, 2))\n * //=> Sun Jan 01 2006 23:59:59.999\n */\nfunction endOfISOWeekYear(date, options) {\n const year = (0, _index2.getISOWeekYear)(date, options);\n const fourthOfJanuaryOfNextYear = (0, _index.constructFrom)(\n options?.in || date,\n 0,\n );\n fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);\n fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);\n const _date = (0, _index3.startOfISOWeek)(fourthOfJanuaryOfNextYear, options);\n _date.setMilliseconds(_date.getMilliseconds() - 1);\n return _date;\n}\n", "\"use strict\";\nexports.endOfMinute = endOfMinute;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfMinute} function options.\n */\n\n/**\n * @name endOfMinute\n * @category Minute Helpers\n * @summary Return the end of a minute for the given date.\n *\n * @description\n * Return the end of a minute for the given date.\n * The result will be in the local timezone or the provided context.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a minute\n *\n * @example\n * // The end of a minute for 1 December 2014 22:15:45.400:\n * const result = endOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400))\n * //=> Mon Dec 01 2014 22:15:59.999\n */\nfunction endOfMinute(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setSeconds(59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.endOfQuarter = endOfQuarter;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfQuarter} function options.\n */\n\n/**\n * @name endOfQuarter\n * @category Quarter Helpers\n * @summary Return the end of a year quarter for the given date.\n *\n * @description\n * Return the end of a year quarter for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a quarter\n *\n * @example\n * // The end of a quarter for 2 September 2014 11:55:00:\n * const result = endOfQuarter(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 30 2014 23:59:59.999\n */\nfunction endOfQuarter(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const currentMonth = _date.getMonth();\n const month = currentMonth - (currentMonth % 3) + 3;\n _date.setMonth(month, 0);\n _date.setHours(23, 59, 59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.endOfSecond = endOfSecond;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfSecond} function options.\n */\n\n/**\n * @name endOfSecond\n * @category Second Helpers\n * @summary Return the end of a second for the given date.\n *\n * @description\n * Return the end of a second for the given date.\n * The result will be in the local timezone if no `in` option is specified.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a second\n *\n * @example\n * // The end of a second for 1 December 2014 22:15:45.400:\n * const result = endOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400))\n * //=> Mon Dec 01 2014 22:15:45.999\n */\nfunction endOfSecond(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setMilliseconds(999);\n return _date;\n}\n", "\"use strict\";\nexports.endOfToday = endOfToday;\nvar _index = require(\"./endOfDay.cjs\");\n\n/**\n * The {@link endOfToday} function options.\n */\n\n/**\n * @name endOfToday\n * @category Day Helpers\n * @summary Return the end of today.\n * @pure false\n *\n * @description\n * Return the end of today.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param options - The options\n *\n * @returns The end of today\n *\n * @example\n * // If today is 6 October 2014:\n * const result = endOfToday()\n * //=> Mon Oct 6 2014 23:59:59.999\n */\nfunction endOfToday(options) {\n return (0, _index.endOfDay)(Date.now(), options);\n}\n", "\"use strict\";\nexports.endOfTomorrow = endOfTomorrow;\nvar _index = require(\"./constructNow.cjs\");\n\n/**\n * The {@link endOfTomorrow} function options.\n */\n\n/**\n * @name endOfTomorrow\n * @category Day Helpers\n * @summary Return the end of tomorrow.\n * @pure false\n *\n * @description\n * Return the end of tomorrow.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param options - The options\n * @returns The end of tomorrow\n *\n * @example\n * // If today is 6 October 2014:\n * const result = endOfTomorrow()\n * //=> Tue Oct 7 2014 23:59:59.999\n */\nfunction endOfTomorrow(options) {\n const now = (0, _index.constructNow)(options?.in);\n const year = now.getFullYear();\n const month = now.getMonth();\n const day = now.getDate();\n\n const date = (0, _index.constructNow)(options?.in);\n date.setFullYear(year, month, day + 1);\n date.setHours(23, 59, 59, 999);\n return options?.in ? options.in(date) : date;\n}\n", "\"use strict\";\nexports.endOfYesterday = endOfYesterday;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\n\n/**\n * The {@link endOfYesterday} function options.\n */\n\n/**\n * @name endOfYesterday\n * @category Day Helpers\n * @summary Return the end of yesterday.\n * @pure false\n *\n * @description\n * Return the end of yesterday.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @returns The end of yesterday\n *\n * @example\n * // If today is 6 October 2014:\n * const result = endOfYesterday()\n * //=> Sun Oct 5 2014 23:59:59.999\n */\nfunction endOfYesterday(options) {\n const now = (0, _index2.constructNow)(options?.in);\n const date = (0, _index.constructFrom)(options?.in, 0);\n date.setFullYear(now.getFullYear(), now.getMonth(), now.getDate() - 1);\n date.setHours(23, 59, 59, 999);\n return date;\n}\n", "\"use strict\";\nexports.formatDistance = void 0;\n\nconst formatDistanceLocale = {\n lessThanXSeconds: {\n one: \"less than a second\",\n other: \"less than {{count}} seconds\",\n },\n\n xSeconds: {\n one: \"1 second\",\n other: \"{{count}} seconds\",\n },\n\n halfAMinute: \"half a minute\",\n\n lessThanXMinutes: {\n one: \"less than a minute\",\n other: \"less than {{count}} minutes\",\n },\n\n xMinutes: {\n one: \"1 minute\",\n other: \"{{count}} minutes\",\n },\n\n aboutXHours: {\n one: \"about 1 hour\",\n other: \"about {{count}} hours\",\n },\n\n xHours: {\n one: \"1 hour\",\n other: \"{{count}} hours\",\n },\n\n xDays: {\n one: \"1 day\",\n other: \"{{count}} days\",\n },\n\n aboutXWeeks: {\n one: \"about 1 week\",\n other: \"about {{count}} weeks\",\n },\n\n xWeeks: {\n one: \"1 week\",\n other: \"{{count}} weeks\",\n },\n\n aboutXMonths: {\n one: \"about 1 month\",\n other: \"about {{count}} months\",\n },\n\n xMonths: {\n one: \"1 month\",\n other: \"{{count}} months\",\n },\n\n aboutXYears: {\n one: \"about 1 year\",\n other: \"about {{count}} years\",\n },\n\n xYears: {\n one: \"1 year\",\n other: \"{{count}} years\",\n },\n\n overXYears: {\n one: \"over 1 year\",\n other: \"over {{count}} years\",\n },\n\n almostXYears: {\n one: \"almost 1 year\",\n other: \"almost {{count}} years\",\n },\n};\n\nconst formatDistance = (token, count, options) => {\n let result;\n\n const tokenValue = formatDistanceLocale[token];\n if (typeof tokenValue === \"string\") {\n result = tokenValue;\n } else if (count === 1) {\n result = tokenValue.one;\n } else {\n result = tokenValue.other.replace(\"{{count}}\", count.toString());\n }\n\n if (options?.addSuffix) {\n if (options.comparison && options.comparison > 0) {\n return \"in \" + result;\n } else {\n return result + \" ago\";\n }\n }\n\n return result;\n};\nexports.formatDistance = formatDistance;\n", "\"use strict\";\nexports.buildFormatLongFn = buildFormatLongFn;\n\nfunction buildFormatLongFn(args) {\n return (options = {}) => {\n // TODO: Remove String()\n const width = options.width ? String(options.width) : args.defaultWidth;\n const format = args.formats[width] || args.formats[args.defaultWidth];\n return format;\n };\n}\n", "\"use strict\";\nexports.formatLong = void 0;\nvar _index = require(\"../../_lib/buildFormatLongFn.cjs\");\n\nconst dateFormats = {\n full: \"EEEE, MMMM do, y\",\n long: \"MMMM do, y\",\n medium: \"MMM d, y\",\n short: \"MM/dd/yyyy\",\n};\n\nconst timeFormats = {\n full: \"h:mm:ss a zzzz\",\n long: \"h:mm:ss a z\",\n medium: \"h:mm:ss a\",\n short: \"h:mm a\",\n};\n\nconst dateTimeFormats = {\n full: \"{{date}} 'at' {{time}}\",\n long: \"{{date}} 'at' {{time}}\",\n medium: \"{{date}}, {{time}}\",\n short: \"{{date}}, {{time}}\",\n};\n\nconst formatLong = (exports.formatLong = {\n date: (0, _index.buildFormatLongFn)({\n formats: dateFormats,\n defaultWidth: \"full\",\n }),\n\n time: (0, _index.buildFormatLongFn)({\n formats: timeFormats,\n defaultWidth: \"full\",\n }),\n\n dateTime: (0, _index.buildFormatLongFn)({\n formats: dateTimeFormats,\n defaultWidth: \"full\",\n }),\n});\n", "\"use strict\";\nexports.formatRelative = void 0;\n\nconst formatRelativeLocale = {\n lastWeek: \"'last' eeee 'at' p\",\n yesterday: \"'yesterday at' p\",\n today: \"'today at' p\",\n tomorrow: \"'tomorrow at' p\",\n nextWeek: \"eeee 'at' p\",\n other: \"P\",\n};\n\nconst formatRelative = (token, _date, _baseDate, _options) =>\n formatRelativeLocale[token];\nexports.formatRelative = formatRelative;\n", "\"use strict\";\nexports.buildLocalizeFn = buildLocalizeFn;\n\n/**\n * The localize function argument callback which allows to convert raw value to\n * the actual type.\n *\n * @param value - The value to convert\n *\n * @returns The converted value\n */\n\n/**\n * The map of localized values for each width.\n */\n\n/**\n * The index type of the locale unit value. It types conversion of units of\n * values that don't start at 0 (i.e. quarters).\n */\n\n/**\n * Converts the unit value to the tuple of values.\n */\n\n/**\n * The tuple of localized era values. The first element represents BC,\n * the second element represents AD.\n */\n\n/**\n * The tuple of localized quarter values. The first element represents Q1.\n */\n\n/**\n * The tuple of localized day values. The first element represents Sunday.\n */\n\n/**\n * The tuple of localized month values. The first element represents January.\n */\n\nfunction buildLocalizeFn(args) {\n return (value, options) => {\n const context = options?.context ? String(options.context) : \"standalone\";\n\n let valuesArray;\n if (context === \"formatting\" && args.formattingValues) {\n const defaultWidth = args.defaultFormattingWidth || args.defaultWidth;\n const width = options?.width ? String(options.width) : defaultWidth;\n\n valuesArray =\n args.formattingValues[width] || args.formattingValues[defaultWidth];\n } else {\n const defaultWidth = args.defaultWidth;\n const width = options?.width ? String(options.width) : args.defaultWidth;\n\n valuesArray = args.values[width] || args.values[defaultWidth];\n }\n const index = args.argumentCallback ? args.argumentCallback(value) : value;\n\n // @ts-expect-error - For some reason TypeScript just don't want to match it, no matter how hard we try. I challenge you to try to remove it!\n return valuesArray[index];\n };\n}\n", "\"use strict\";\nexports.localize = void 0;\nvar _index = require(\"../../_lib/buildLocalizeFn.cjs\");\n\nconst eraValues = {\n narrow: [\"B\", \"A\"],\n abbreviated: [\"BC\", \"AD\"],\n wide: [\"Before Christ\", \"Anno Domini\"],\n};\n\nconst quarterValues = {\n narrow: [\"1\", \"2\", \"3\", \"4\"],\n abbreviated: [\"Q1\", \"Q2\", \"Q3\", \"Q4\"],\n wide: [\"1st quarter\", \"2nd quarter\", \"3rd quarter\", \"4th quarter\"],\n};\n\n// Note: in English, the names of days of the week and months are capitalized.\n// If you are making a new locale based on this one, check if the same is true for the language you're working on.\n// Generally, formatted dates should look like they are in the middle of a sentence,\n// e.g. in Spanish language the weekdays and months should be in the lowercase.\nconst monthValues = {\n narrow: [\"J\", \"F\", \"M\", \"A\", \"M\", \"J\", \"J\", \"A\", \"S\", \"O\", \"N\", \"D\"],\n abbreviated: [\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n ],\n\n wide: [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n ],\n};\n\nconst dayValues = {\n narrow: [\"S\", \"M\", \"T\", \"W\", \"T\", \"F\", \"S\"],\n short: [\"Su\", \"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\"],\n abbreviated: [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"],\n wide: [\n \"Sunday\",\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\",\n ],\n};\n\nconst dayPeriodValues = {\n narrow: {\n am: \"a\",\n pm: \"p\",\n midnight: \"mi\",\n noon: \"n\",\n morning: \"morning\",\n afternoon: \"afternoon\",\n evening: \"evening\",\n night: \"night\",\n },\n abbreviated: {\n am: \"AM\",\n pm: \"PM\",\n midnight: \"midnight\",\n noon: \"noon\",\n morning: \"morning\",\n afternoon: \"afternoon\",\n evening: \"evening\",\n night: \"night\",\n },\n wide: {\n am: \"a.m.\",\n pm: \"p.m.\",\n midnight: \"midnight\",\n noon: \"noon\",\n morning: \"morning\",\n afternoon: \"afternoon\",\n evening: \"evening\",\n night: \"night\",\n },\n};\n\nconst formattingDayPeriodValues = {\n narrow: {\n am: \"a\",\n pm: \"p\",\n midnight: \"mi\",\n noon: \"n\",\n morning: \"in the morning\",\n afternoon: \"in the afternoon\",\n evening: \"in the evening\",\n night: \"at night\",\n },\n abbreviated: {\n am: \"AM\",\n pm: \"PM\",\n midnight: \"midnight\",\n noon: \"noon\",\n morning: \"in the morning\",\n afternoon: \"in the afternoon\",\n evening: \"in the evening\",\n night: \"at night\",\n },\n wide: {\n am: \"a.m.\",\n pm: \"p.m.\",\n midnight: \"midnight\",\n noon: \"noon\",\n morning: \"in the morning\",\n afternoon: \"in the afternoon\",\n evening: \"in the evening\",\n night: \"at night\",\n },\n};\n\nconst ordinalNumber = (dirtyNumber, _options) => {\n const number = Number(dirtyNumber);\n\n // If ordinal numbers depend on context, for example,\n // if they are different for different grammatical genders,\n // use `options.unit`.\n //\n // `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear',\n // 'day', 'hour', 'minute', 'second'.\n\n const rem100 = number % 100;\n if (rem100 > 20 || rem100 < 10) {\n switch (rem100 % 10) {\n case 1:\n return number + \"st\";\n case 2:\n return number + \"nd\";\n case 3:\n return number + \"rd\";\n }\n }\n return number + \"th\";\n};\n\nconst localize = (exports.localize = {\n ordinalNumber,\n\n era: (0, _index.buildLocalizeFn)({\n values: eraValues,\n defaultWidth: \"wide\",\n }),\n\n quarter: (0, _index.buildLocalizeFn)({\n values: quarterValues,\n defaultWidth: \"wide\",\n argumentCallback: (quarter) => quarter - 1,\n }),\n\n month: (0, _index.buildLocalizeFn)({\n values: monthValues,\n defaultWidth: \"wide\",\n }),\n\n day: (0, _index.buildLocalizeFn)({\n values: dayValues,\n defaultWidth: \"wide\",\n }),\n\n dayPeriod: (0, _index.buildLocalizeFn)({\n values: dayPeriodValues,\n defaultWidth: \"wide\",\n formattingValues: formattingDayPeriodValues,\n defaultFormattingWidth: \"wide\",\n }),\n});\n", "\"use strict\";\nexports.buildMatchFn = buildMatchFn;\n\nfunction buildMatchFn(args) {\n return (string, options = {}) => {\n const width = options.width;\n\n const matchPattern =\n (width && args.matchPatterns[width]) ||\n args.matchPatterns[args.defaultMatchWidth];\n const matchResult = string.match(matchPattern);\n\n if (!matchResult) {\n return null;\n }\n const matchedString = matchResult[0];\n\n const parsePatterns =\n (width && args.parsePatterns[width]) ||\n args.parsePatterns[args.defaultParseWidth];\n\n const key = Array.isArray(parsePatterns)\n ? findIndex(parsePatterns, (pattern) => pattern.test(matchedString))\n : // [TODO] -- I challenge you to fix the type\n findKey(parsePatterns, (pattern) => pattern.test(matchedString));\n\n let value;\n\n value = args.valueCallback ? args.valueCallback(key) : key;\n value = options.valueCallback\n ? // [TODO] -- I challenge you to fix the type\n options.valueCallback(value)\n : value;\n\n const rest = string.slice(matchedString.length);\n\n return { value, rest };\n };\n}\n\nfunction findKey(object, predicate) {\n for (const key in object) {\n if (\n Object.prototype.hasOwnProperty.call(object, key) &&\n predicate(object[key])\n ) {\n return key;\n }\n }\n return undefined;\n}\n\nfunction findIndex(array, predicate) {\n for (let key = 0; key < array.length; key++) {\n if (predicate(array[key])) {\n return key;\n }\n }\n return undefined;\n}\n", "\"use strict\";\nexports.buildMatchPatternFn = buildMatchPatternFn;\n\nfunction buildMatchPatternFn(args) {\n return (string, options = {}) => {\n const matchResult = string.match(args.matchPattern);\n if (!matchResult) return null;\n const matchedString = matchResult[0];\n\n const parseResult = string.match(args.parsePattern);\n if (!parseResult) return null;\n let value = args.valueCallback\n ? args.valueCallback(parseResult[0])\n : parseResult[0];\n\n // [TODO] I challenge you to fix the type\n value = options.valueCallback ? options.valueCallback(value) : value;\n\n const rest = string.slice(matchedString.length);\n\n return { value, rest };\n };\n}\n", "\"use strict\";\nexports.match = void 0;\n\nvar _index = require(\"../../_lib/buildMatchFn.cjs\");\nvar _index2 = require(\"../../_lib/buildMatchPatternFn.cjs\");\n\nconst matchOrdinalNumberPattern = /^(\\d+)(th|st|nd|rd)?/i;\nconst parseOrdinalNumberPattern = /\\d+/i;\n\nconst matchEraPatterns = {\n narrow: /^(b|a)/i,\n abbreviated: /^(b\\.?\\s?c\\.?|b\\.?\\s?c\\.?\\s?e\\.?|a\\.?\\s?d\\.?|c\\.?\\s?e\\.?)/i,\n wide: /^(before christ|before common era|anno domini|common era)/i,\n};\nconst parseEraPatterns = {\n any: [/^b/i, /^(a|c)/i],\n};\n\nconst matchQuarterPatterns = {\n narrow: /^[1234]/i,\n abbreviated: /^q[1234]/i,\n wide: /^[1234](th|st|nd|rd)? quarter/i,\n};\nconst parseQuarterPatterns = {\n any: [/1/i, /2/i, /3/i, /4/i],\n};\n\nconst matchMonthPatterns = {\n narrow: /^[jfmasond]/i,\n abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,\n wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i,\n};\nconst parseMonthPatterns = {\n narrow: [\n /^j/i,\n /^f/i,\n /^m/i,\n /^a/i,\n /^m/i,\n /^j/i,\n /^j/i,\n /^a/i,\n /^s/i,\n /^o/i,\n /^n/i,\n /^d/i,\n ],\n\n any: [\n /^ja/i,\n /^f/i,\n /^mar/i,\n /^ap/i,\n /^may/i,\n /^jun/i,\n /^jul/i,\n /^au/i,\n /^s/i,\n /^o/i,\n /^n/i,\n /^d/i,\n ],\n};\n\nconst matchDayPatterns = {\n narrow: /^[smtwf]/i,\n short: /^(su|mo|tu|we|th|fr|sa)/i,\n abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,\n wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i,\n};\nconst parseDayPatterns = {\n narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],\n any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i],\n};\n\nconst matchDayPeriodPatterns = {\n narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,\n any: /^([ap]\\.?\\s?m\\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i,\n};\nconst parseDayPeriodPatterns = {\n any: {\n am: /^a/i,\n pm: /^p/i,\n midnight: /^mi/i,\n noon: /^no/i,\n morning: /morning/i,\n afternoon: /afternoon/i,\n evening: /evening/i,\n night: /night/i,\n },\n};\n\nconst match = (exports.match = {\n ordinalNumber: (0, _index2.buildMatchPatternFn)({\n matchPattern: matchOrdinalNumberPattern,\n parsePattern: parseOrdinalNumberPattern,\n valueCallback: (value) => parseInt(value, 10),\n }),\n\n era: (0, _index.buildMatchFn)({\n matchPatterns: matchEraPatterns,\n defaultMatchWidth: \"wide\",\n parsePatterns: parseEraPatterns,\n defaultParseWidth: \"any\",\n }),\n\n quarter: (0, _index.buildMatchFn)({\n matchPatterns: matchQuarterPatterns,\n defaultMatchWidth: \"wide\",\n parsePatterns: parseQuarterPatterns,\n defaultParseWidth: \"any\",\n valueCallback: (index) => index + 1,\n }),\n\n month: (0, _index.buildMatchFn)({\n matchPatterns: matchMonthPatterns,\n defaultMatchWidth: \"wide\",\n parsePatterns: parseMonthPatterns,\n defaultParseWidth: \"any\",\n }),\n\n day: (0, _index.buildMatchFn)({\n matchPatterns: matchDayPatterns,\n defaultMatchWidth: \"wide\",\n parsePatterns: parseDayPatterns,\n defaultParseWidth: \"any\",\n }),\n\n dayPeriod: (0, _index.buildMatchFn)({\n matchPatterns: matchDayPeriodPatterns,\n defaultMatchWidth: \"any\",\n parsePatterns: parseDayPeriodPatterns,\n defaultParseWidth: \"any\",\n }),\n});\n", "\"use strict\";\nexports.enUS = void 0;\nvar _index = require(\"./en-US/_lib/formatDistance.cjs\");\nvar _index2 = require(\"./en-US/_lib/formatLong.cjs\");\nvar _index3 = require(\"./en-US/_lib/formatRelative.cjs\");\nvar _index4 = require(\"./en-US/_lib/localize.cjs\");\nvar _index5 = require(\"./en-US/_lib/match.cjs\");\n\n/**\n * @category Locales\n * @summary English locale (United States).\n * @language English\n * @iso-639-2 eng\n * @author Sasha Koss [@kossnocorp](https://github.com/kossnocorp)\n * @author Lesha Koss [@leshakoss](https://github.com/leshakoss)\n */\nconst enUS = (exports.enUS = {\n code: \"en-US\",\n formatDistance: _index.formatDistance,\n formatLong: _index2.formatLong,\n formatRelative: _index3.formatRelative,\n localize: _index4.localize,\n match: _index5.match,\n options: {\n weekStartsOn: 0 /* Sunday */,\n firstWeekContainsDate: 1,\n },\n});\n", "\"use strict\";\nObject.defineProperty(exports, \"defaultLocale\", {\n enumerable: true,\n get: function () {\n return _index.enUS;\n },\n});\nvar _index = require(\"../locale/en-US.cjs\");\n", "\"use strict\";\nexports.getDayOfYear = getDayOfYear;\nvar _index = require(\"./differenceInCalendarDays.cjs\");\nvar _index2 = require(\"./startOfYear.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getDayOfYear} function options.\n */\n\n/**\n * @name getDayOfYear\n * @category Day Helpers\n * @summary Get the day of the year of the given date.\n *\n * @description\n * Get the day of the year of the given date.\n *\n * @param date - The given date\n * @param options - The options\n *\n * @returns The day of year\n *\n * @example\n * // Which day of the year is 2 July 2014?\n * const result = getDayOfYear(new Date(2014, 6, 2))\n * //=> 183\n */\nfunction getDayOfYear(date, options) {\n const _date = (0, _index3.toDate)(date, options?.in);\n const diff = (0, _index.differenceInCalendarDays)(\n _date,\n (0, _index2.startOfYear)(_date),\n );\n const dayOfYear = diff + 1;\n return dayOfYear;\n}\n", "\"use strict\";\nexports.getISOWeek = getISOWeek;\nvar _index = require(\"./constants.cjs\");\nvar _index2 = require(\"./startOfISOWeek.cjs\");\nvar _index3 = require(\"./startOfISOWeekYear.cjs\");\nvar _index4 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getISOWeek} function options.\n */\n\n/**\n * @name getISOWeek\n * @category ISO Week Helpers\n * @summary Get the ISO week of the given date.\n *\n * @description\n * Get the ISO week of the given date.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param date - The given date\n * @param options - The options\n *\n * @returns The ISO week\n *\n * @example\n * // Which week of the ISO-week numbering year is 2 January 2005?\n * const result = getISOWeek(new Date(2005, 0, 2))\n * //=> 53\n */\nfunction getISOWeek(date, options) {\n const _date = (0, _index4.toDate)(date, options?.in);\n const diff =\n +(0, _index2.startOfISOWeek)(_date) -\n +(0, _index3.startOfISOWeekYear)(_date);\n\n // Round the number of weeks to the nearest integer because the number of\n // milliseconds in a week is not constant (e.g. it's different in the week of\n // the daylight saving time clock shift).\n return Math.round(diff / _index.millisecondsInWeek) + 1;\n}\n", "\"use strict\";\nexports.getWeekYear = getWeekYear;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\nvar _index3 = require(\"./startOfWeek.cjs\");\nvar _index4 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getWeekYear} function options.\n */\n\n/**\n * @name getWeekYear\n * @category Week-Numbering Year Helpers\n * @summary Get the local week-numbering year of the given date.\n *\n * @description\n * Get the local week-numbering year of the given date.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system\n *\n * @param date - The given date\n * @param options - An object with options.\n *\n * @returns The local week-numbering year\n *\n * @example\n * // Which week numbering year is 26 December 2004 with the default settings?\n * const result = getWeekYear(new Date(2004, 11, 26))\n * //=> 2005\n *\n * @example\n * // Which week numbering year is 26 December 2004 if week starts on Saturday?\n * const result = getWeekYear(new Date(2004, 11, 26), { weekStartsOn: 6 })\n * //=> 2004\n *\n * @example\n * // Which week numbering year is 26 December 2004 if the first week contains 4 January?\n * const result = getWeekYear(new Date(2004, 11, 26), { firstWeekContainsDate: 4 })\n * //=> 2004\n */\nfunction getWeekYear(date, options) {\n const _date = (0, _index4.toDate)(date, options?.in);\n const year = _date.getFullYear();\n\n const defaultOptions = (0, _index.getDefaultOptions)();\n const firstWeekContainsDate =\n options?.firstWeekContainsDate ??\n options?.locale?.options?.firstWeekContainsDate ??\n defaultOptions.firstWeekContainsDate ??\n defaultOptions.locale?.options?.firstWeekContainsDate ??\n 1;\n\n const firstWeekOfNextYear = (0, _index2.constructFrom)(\n options?.in || date,\n 0,\n );\n firstWeekOfNextYear.setFullYear(year + 1, 0, firstWeekContainsDate);\n firstWeekOfNextYear.setHours(0, 0, 0, 0);\n const startOfNextYear = (0, _index3.startOfWeek)(\n firstWeekOfNextYear,\n options,\n );\n\n const firstWeekOfThisYear = (0, _index2.constructFrom)(\n options?.in || date,\n 0,\n );\n firstWeekOfThisYear.setFullYear(year, 0, firstWeekContainsDate);\n firstWeekOfThisYear.setHours(0, 0, 0, 0);\n const startOfThisYear = (0, _index3.startOfWeek)(\n firstWeekOfThisYear,\n options,\n );\n\n if (+_date >= +startOfNextYear) {\n return year + 1;\n } else if (+_date >= +startOfThisYear) {\n return year;\n } else {\n return year - 1;\n }\n}\n", "\"use strict\";\nexports.startOfWeekYear = startOfWeekYear;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\nvar _index3 = require(\"./getWeekYear.cjs\");\nvar _index4 = require(\"./startOfWeek.cjs\");\n\n/**\n * The {@link startOfWeekYear} function options.\n */\n\n/**\n * @name startOfWeekYear\n * @category Week-Numbering Year Helpers\n * @summary Return the start of a local week-numbering year for the given date.\n *\n * @description\n * Return the start of a local week-numbering year.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of a week-numbering year\n *\n * @example\n * // The start of an a week-numbering year for 2 July 2005 with default settings:\n * const result = startOfWeekYear(new Date(2005, 6, 2))\n * //=> Sun Dec 26 2004 00:00:00\n *\n * @example\n * // The start of a week-numbering year for 2 July 2005\n * // if Monday is the first day of week\n * // and 4 January is always in the first week of the year:\n * const result = startOfWeekYear(new Date(2005, 6, 2), {\n * weekStartsOn: 1,\n * firstWeekContainsDate: 4\n * })\n * //=> Mon Jan 03 2005 00:00:00\n */\nfunction startOfWeekYear(date, options) {\n const defaultOptions = (0, _index.getDefaultOptions)();\n const firstWeekContainsDate =\n options?.firstWeekContainsDate ??\n options?.locale?.options?.firstWeekContainsDate ??\n defaultOptions.firstWeekContainsDate ??\n defaultOptions.locale?.options?.firstWeekContainsDate ??\n 1;\n\n const year = (0, _index3.getWeekYear)(date, options);\n const firstWeek = (0, _index2.constructFrom)(options?.in || date, 0);\n firstWeek.setFullYear(year, 0, firstWeekContainsDate);\n firstWeek.setHours(0, 0, 0, 0);\n const _date = (0, _index4.startOfWeek)(firstWeek, options);\n return _date;\n}\n", "\"use strict\";\nexports.getWeek = getWeek;\nvar _index = require(\"./constants.cjs\");\nvar _index2 = require(\"./startOfWeek.cjs\");\nvar _index3 = require(\"./startOfWeekYear.cjs\");\nvar _index4 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getWeek} function options.\n */\n\n/**\n * @name getWeek\n * @category Week Helpers\n * @summary Get the local week index of the given date.\n *\n * @description\n * Get the local week index of the given date.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The week\n *\n * @example\n * // Which week of the local week numbering year is 2 January 2005 with default options?\n * const result = getWeek(new Date(2005, 0, 2))\n * //=> 2\n *\n * @example\n * // Which week of the local week numbering year is 2 January 2005,\n * // if Monday is the first day of the week,\n * // and the first week of the year always contains 4 January?\n * const result = getWeek(new Date(2005, 0, 2), {\n * weekStartsOn: 1,\n * firstWeekContainsDate: 4\n * })\n * //=> 53\n */\nfunction getWeek(date, options) {\n const _date = (0, _index4.toDate)(date, options?.in);\n const diff =\n +(0, _index2.startOfWeek)(_date, options) -\n +(0, _index3.startOfWeekYear)(_date, options);\n\n // Round the number of weeks to the nearest integer because the number of\n // milliseconds in a week is not constant (e.g. it's different in the week of\n // the daylight saving time clock shift).\n return Math.round(diff / _index.millisecondsInWeek) + 1;\n}\n", "\"use strict\";\nexports.addLeadingZeros = addLeadingZeros;\nfunction addLeadingZeros(number, targetLength) {\n const sign = number < 0 ? \"-\" : \"\";\n const output = Math.abs(number).toString().padStart(targetLength, \"0\");\n return sign + output;\n}\n", "\"use strict\";\nexports.lightFormatters = void 0;\nvar _index = require(\"../addLeadingZeros.cjs\");\n\n/*\n * | | Unit | | Unit |\n * |-----|--------------------------------|-----|--------------------------------|\n * | a | AM, PM | A* | |\n * | d | Day of month | D | |\n * | h | Hour [1-12] | H | Hour [0-23] |\n * | m | Minute | M | Month |\n * | s | Second | S | Fraction of second |\n * | y | Year (abs) | Y | |\n *\n * Letters marked by * are not implemented but reserved by Unicode standard.\n */\n\nconst lightFormatters = (exports.lightFormatters = {\n // Year\n y(date, token) {\n // From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_tokens\n // | Year | y | yy | yyy | yyyy | yyyyy |\n // |----------|-------|----|-------|-------|-------|\n // | AD 1 | 1 | 01 | 001 | 0001 | 00001 |\n // | AD 12 | 12 | 12 | 012 | 0012 | 00012 |\n // | AD 123 | 123 | 23 | 123 | 0123 | 00123 |\n // | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 |\n // | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |\n\n const signedYear = date.getFullYear();\n // Returns 1 for 1 BC (which is year 0 in JavaScript)\n const year = signedYear > 0 ? signedYear : 1 - signedYear;\n return (0, _index.addLeadingZeros)(\n token === \"yy\" ? year % 100 : year,\n token.length,\n );\n },\n\n // Month\n M(date, token) {\n const month = date.getMonth();\n return token === \"M\"\n ? String(month + 1)\n : (0, _index.addLeadingZeros)(month + 1, 2);\n },\n\n // Day of the month\n d(date, token) {\n return (0, _index.addLeadingZeros)(date.getDate(), token.length);\n },\n\n // AM or PM\n a(date, token) {\n const dayPeriodEnumValue = date.getHours() / 12 >= 1 ? \"pm\" : \"am\";\n\n switch (token) {\n case \"a\":\n case \"aa\":\n return dayPeriodEnumValue.toUpperCase();\n case \"aaa\":\n return dayPeriodEnumValue;\n case \"aaaaa\":\n return dayPeriodEnumValue[0];\n case \"aaaa\":\n default:\n return dayPeriodEnumValue === \"am\" ? \"a.m.\" : \"p.m.\";\n }\n },\n\n // Hour [1-12]\n h(date, token) {\n return (0, _index.addLeadingZeros)(\n date.getHours() % 12 || 12,\n token.length,\n );\n },\n\n // Hour [0-23]\n H(date, token) {\n return (0, _index.addLeadingZeros)(date.getHours(), token.length);\n },\n\n // Minute\n m(date, token) {\n return (0, _index.addLeadingZeros)(date.getMinutes(), token.length);\n },\n\n // Second\n s(date, token) {\n return (0, _index.addLeadingZeros)(date.getSeconds(), token.length);\n },\n\n // Fraction of second\n S(date, token) {\n const numberOfDigits = token.length;\n const milliseconds = date.getMilliseconds();\n const fractionalSeconds = Math.trunc(\n milliseconds * Math.pow(10, numberOfDigits - 3),\n );\n return (0, _index.addLeadingZeros)(fractionalSeconds, token.length);\n },\n});\n", "\"use strict\";\nexports.formatters = void 0;\nvar _index = require(\"../../getDayOfYear.cjs\");\nvar _index2 = require(\"../../getISOWeek.cjs\");\nvar _index3 = require(\"../../getISOWeekYear.cjs\");\nvar _index4 = require(\"../../getWeek.cjs\");\nvar _index5 = require(\"../../getWeekYear.cjs\");\n\nvar _index6 = require(\"../addLeadingZeros.cjs\");\nvar _index7 = require(\"./lightFormatters.cjs\");\n\nconst dayPeriodEnum = {\n am: \"am\",\n pm: \"pm\",\n midnight: \"midnight\",\n noon: \"noon\",\n morning: \"morning\",\n afternoon: \"afternoon\",\n evening: \"evening\",\n night: \"night\",\n};\n\n/*\n * | | Unit | | Unit |\n * |-----|--------------------------------|-----|--------------------------------|\n * | a | AM, PM | A* | Milliseconds in day |\n * | b | AM, PM, noon, midnight | B | Flexible day period |\n * | c | Stand-alone local day of week | C* | Localized hour w/ day period |\n * | d | Day of month | D | Day of year |\n * | e | Local day of week | E | Day of week |\n * | f | | F* | Day of week in month |\n * | g* | Modified Julian day | G | Era |\n * | h | Hour [1-12] | H | Hour [0-23] |\n * | i! | ISO day of week | I! | ISO week of year |\n * | j* | Localized hour w/ day period | J* | Localized hour w/o day period |\n * | k | Hour [1-24] | K | Hour [0-11] |\n * | l* | (deprecated) | L | Stand-alone month |\n * | m | Minute | M | Month |\n * | n | | N | |\n * | o! | Ordinal number modifier | O | Timezone (GMT) |\n * | p! | Long localized time | P! | Long localized date |\n * | q | Stand-alone quarter | Q | Quarter |\n * | r* | Related Gregorian year | R! | ISO week-numbering year |\n * | s | Second | S | Fraction of second |\n * | t! | Seconds timestamp | T! | Milliseconds timestamp |\n * | u | Extended year | U* | Cyclic year |\n * | v* | Timezone (generic non-locat.) | V* | Timezone (location) |\n * | w | Local week of year | W* | Week of month |\n * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) |\n * | y | Year (abs) | Y | Local week-numbering year |\n * | z | Timezone (specific non-locat.) | Z* | Timezone (aliases) |\n *\n * Letters marked by * are not implemented but reserved by Unicode standard.\n *\n * Letters marked by ! are non-standard, but implemented by date-fns:\n * - `o` modifies the previous token to turn it into an ordinal (see `format` docs)\n * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,\n * i.e. 7 for Sunday, 1 for Monday, etc.\n * - `I` is ISO week of year, as opposed to `w` which is local week of year.\n * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.\n * `R` is supposed to be used in conjunction with `I` and `i`\n * for universal ISO week-numbering date, whereas\n * `Y` is supposed to be used in conjunction with `w` and `e`\n * for week-numbering date specific to the locale.\n * - `P` is long localized date format\n * - `p` is long localized time format\n */\n\nconst formatters = (exports.formatters = {\n // Era\n G: function (date, token, localize) {\n const era = date.getFullYear() > 0 ? 1 : 0;\n switch (token) {\n // AD, BC\n case \"G\":\n case \"GG\":\n case \"GGG\":\n return localize.era(era, { width: \"abbreviated\" });\n // A, B\n case \"GGGGG\":\n return localize.era(era, { width: \"narrow\" });\n // Anno Domini, Before Christ\n case \"GGGG\":\n default:\n return localize.era(era, { width: \"wide\" });\n }\n },\n\n // Year\n y: function (date, token, localize) {\n // Ordinal number\n if (token === \"yo\") {\n const signedYear = date.getFullYear();\n // Returns 1 for 1 BC (which is year 0 in JavaScript)\n const year = signedYear > 0 ? signedYear : 1 - signedYear;\n return localize.ordinalNumber(year, { unit: \"year\" });\n }\n\n return _index7.lightFormatters.y(date, token);\n },\n\n // Local week-numbering year\n Y: function (date, token, localize, options) {\n const signedWeekYear = (0, _index5.getWeekYear)(date, options);\n // Returns 1 for 1 BC (which is year 0 in JavaScript)\n const weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear;\n\n // Two digit year\n if (token === \"YY\") {\n const twoDigitYear = weekYear % 100;\n return (0, _index6.addLeadingZeros)(twoDigitYear, 2);\n }\n\n // Ordinal number\n if (token === \"Yo\") {\n return localize.ordinalNumber(weekYear, { unit: \"year\" });\n }\n\n // Padding\n return (0, _index6.addLeadingZeros)(weekYear, token.length);\n },\n\n // ISO week-numbering year\n R: function (date, token) {\n const isoWeekYear = (0, _index3.getISOWeekYear)(date);\n\n // Padding\n return (0, _index6.addLeadingZeros)(isoWeekYear, token.length);\n },\n\n // Extended year. This is a single number designating the year of this calendar system.\n // The main difference between `y` and `u` localizers are B.C. years:\n // | Year | `y` | `u` |\n // |------|-----|-----|\n // | AC 1 | 1 | 1 |\n // | BC 1 | 1 | 0 |\n // | BC 2 | 2 | -1 |\n // Also `yy` always returns the last two digits of a year,\n // while `uu` pads single digit years to 2 characters and returns other years unchanged.\n u: function (date, token) {\n const year = date.getFullYear();\n return (0, _index6.addLeadingZeros)(year, token.length);\n },\n\n // Quarter\n Q: function (date, token, localize) {\n const quarter = Math.ceil((date.getMonth() + 1) / 3);\n switch (token) {\n // 1, 2, 3, 4\n case \"Q\":\n return String(quarter);\n // 01, 02, 03, 04\n case \"QQ\":\n return (0, _index6.addLeadingZeros)(quarter, 2);\n // 1st, 2nd, 3rd, 4th\n case \"Qo\":\n return localize.ordinalNumber(quarter, { unit: \"quarter\" });\n // Q1, Q2, Q3, Q4\n case \"QQQ\":\n return localize.quarter(quarter, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n // 1, 2, 3, 4 (narrow quarter; could be not numerical)\n case \"QQQQQ\":\n return localize.quarter(quarter, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // 1st quarter, 2nd quarter, ...\n case \"QQQQ\":\n default:\n return localize.quarter(quarter, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // Stand-alone quarter\n q: function (date, token, localize) {\n const quarter = Math.ceil((date.getMonth() + 1) / 3);\n switch (token) {\n // 1, 2, 3, 4\n case \"q\":\n return String(quarter);\n // 01, 02, 03, 04\n case \"qq\":\n return (0, _index6.addLeadingZeros)(quarter, 2);\n // 1st, 2nd, 3rd, 4th\n case \"qo\":\n return localize.ordinalNumber(quarter, { unit: \"quarter\" });\n // Q1, Q2, Q3, Q4\n case \"qqq\":\n return localize.quarter(quarter, {\n width: \"abbreviated\",\n context: \"standalone\",\n });\n // 1, 2, 3, 4 (narrow quarter; could be not numerical)\n case \"qqqqq\":\n return localize.quarter(quarter, {\n width: \"narrow\",\n context: \"standalone\",\n });\n // 1st quarter, 2nd quarter, ...\n case \"qqqq\":\n default:\n return localize.quarter(quarter, {\n width: \"wide\",\n context: \"standalone\",\n });\n }\n },\n\n // Month\n M: function (date, token, localize) {\n const month = date.getMonth();\n switch (token) {\n case \"M\":\n case \"MM\":\n return _index7.lightFormatters.M(date, token);\n // 1st, 2nd, ..., 12th\n case \"Mo\":\n return localize.ordinalNumber(month + 1, { unit: \"month\" });\n // Jan, Feb, ..., Dec\n case \"MMM\":\n return localize.month(month, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n // J, F, ..., D\n case \"MMMMM\":\n return localize.month(month, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // January, February, ..., December\n case \"MMMM\":\n default:\n return localize.month(month, { width: \"wide\", context: \"formatting\" });\n }\n },\n\n // Stand-alone month\n L: function (date, token, localize) {\n const month = date.getMonth();\n switch (token) {\n // 1, 2, ..., 12\n case \"L\":\n return String(month + 1);\n // 01, 02, ..., 12\n case \"LL\":\n return (0, _index6.addLeadingZeros)(month + 1, 2);\n // 1st, 2nd, ..., 12th\n case \"Lo\":\n return localize.ordinalNumber(month + 1, { unit: \"month\" });\n // Jan, Feb, ..., Dec\n case \"LLL\":\n return localize.month(month, {\n width: \"abbreviated\",\n context: \"standalone\",\n });\n // J, F, ..., D\n case \"LLLLL\":\n return localize.month(month, {\n width: \"narrow\",\n context: \"standalone\",\n });\n // January, February, ..., December\n case \"LLLL\":\n default:\n return localize.month(month, { width: \"wide\", context: \"standalone\" });\n }\n },\n\n // Local week of year\n w: function (date, token, localize, options) {\n const week = (0, _index4.getWeek)(date, options);\n\n if (token === \"wo\") {\n return localize.ordinalNumber(week, { unit: \"week\" });\n }\n\n return (0, _index6.addLeadingZeros)(week, token.length);\n },\n\n // ISO week of year\n I: function (date, token, localize) {\n const isoWeek = (0, _index2.getISOWeek)(date);\n\n if (token === \"Io\") {\n return localize.ordinalNumber(isoWeek, { unit: \"week\" });\n }\n\n return (0, _index6.addLeadingZeros)(isoWeek, token.length);\n },\n\n // Day of the month\n d: function (date, token, localize) {\n if (token === \"do\") {\n return localize.ordinalNumber(date.getDate(), { unit: \"date\" });\n }\n\n return _index7.lightFormatters.d(date, token);\n },\n\n // Day of year\n D: function (date, token, localize) {\n const dayOfYear = (0, _index.getDayOfYear)(date);\n\n if (token === \"Do\") {\n return localize.ordinalNumber(dayOfYear, { unit: \"dayOfYear\" });\n }\n\n return (0, _index6.addLeadingZeros)(dayOfYear, token.length);\n },\n\n // Day of week\n E: function (date, token, localize) {\n const dayOfWeek = date.getDay();\n switch (token) {\n // Tue\n case \"E\":\n case \"EE\":\n case \"EEE\":\n return localize.day(dayOfWeek, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n // T\n case \"EEEEE\":\n return localize.day(dayOfWeek, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // Tu\n case \"EEEEEE\":\n return localize.day(dayOfWeek, {\n width: \"short\",\n context: \"formatting\",\n });\n // Tuesday\n case \"EEEE\":\n default:\n return localize.day(dayOfWeek, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // Local day of week\n e: function (date, token, localize, options) {\n const dayOfWeek = date.getDay();\n const localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;\n switch (token) {\n // Numerical value (Nth day of week with current locale or weekStartsOn)\n case \"e\":\n return String(localDayOfWeek);\n // Padded numerical value\n case \"ee\":\n return (0, _index6.addLeadingZeros)(localDayOfWeek, 2);\n // 1st, 2nd, ..., 7th\n case \"eo\":\n return localize.ordinalNumber(localDayOfWeek, { unit: \"day\" });\n case \"eee\":\n return localize.day(dayOfWeek, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n // T\n case \"eeeee\":\n return localize.day(dayOfWeek, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // Tu\n case \"eeeeee\":\n return localize.day(dayOfWeek, {\n width: \"short\",\n context: \"formatting\",\n });\n // Tuesday\n case \"eeee\":\n default:\n return localize.day(dayOfWeek, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // Stand-alone local day of week\n c: function (date, token, localize, options) {\n const dayOfWeek = date.getDay();\n const localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;\n switch (token) {\n // Numerical value (same as in `e`)\n case \"c\":\n return String(localDayOfWeek);\n // Padded numerical value\n case \"cc\":\n return (0, _index6.addLeadingZeros)(localDayOfWeek, token.length);\n // 1st, 2nd, ..., 7th\n case \"co\":\n return localize.ordinalNumber(localDayOfWeek, { unit: \"day\" });\n case \"ccc\":\n return localize.day(dayOfWeek, {\n width: \"abbreviated\",\n context: \"standalone\",\n });\n // T\n case \"ccccc\":\n return localize.day(dayOfWeek, {\n width: \"narrow\",\n context: \"standalone\",\n });\n // Tu\n case \"cccccc\":\n return localize.day(dayOfWeek, {\n width: \"short\",\n context: \"standalone\",\n });\n // Tuesday\n case \"cccc\":\n default:\n return localize.day(dayOfWeek, {\n width: \"wide\",\n context: \"standalone\",\n });\n }\n },\n\n // ISO day of week\n i: function (date, token, localize) {\n const dayOfWeek = date.getDay();\n const isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;\n switch (token) {\n // 2\n case \"i\":\n return String(isoDayOfWeek);\n // 02\n case \"ii\":\n return (0, _index6.addLeadingZeros)(isoDayOfWeek, token.length);\n // 2nd\n case \"io\":\n return localize.ordinalNumber(isoDayOfWeek, { unit: \"day\" });\n // Tue\n case \"iii\":\n return localize.day(dayOfWeek, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n // T\n case \"iiiii\":\n return localize.day(dayOfWeek, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // Tu\n case \"iiiiii\":\n return localize.day(dayOfWeek, {\n width: \"short\",\n context: \"formatting\",\n });\n // Tuesday\n case \"iiii\":\n default:\n return localize.day(dayOfWeek, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // AM or PM\n a: function (date, token, localize) {\n const hours = date.getHours();\n const dayPeriodEnumValue = hours / 12 >= 1 ? \"pm\" : \"am\";\n\n switch (token) {\n case \"a\":\n case \"aa\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n case \"aaa\":\n return localize\n .dayPeriod(dayPeriodEnumValue, {\n width: \"abbreviated\",\n context: \"formatting\",\n })\n .toLowerCase();\n case \"aaaaa\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"narrow\",\n context: \"formatting\",\n });\n case \"aaaa\":\n default:\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // AM, PM, midnight, noon\n b: function (date, token, localize) {\n const hours = date.getHours();\n let dayPeriodEnumValue;\n if (hours === 12) {\n dayPeriodEnumValue = dayPeriodEnum.noon;\n } else if (hours === 0) {\n dayPeriodEnumValue = dayPeriodEnum.midnight;\n } else {\n dayPeriodEnumValue = hours / 12 >= 1 ? \"pm\" : \"am\";\n }\n\n switch (token) {\n case \"b\":\n case \"bb\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n case \"bbb\":\n return localize\n .dayPeriod(dayPeriodEnumValue, {\n width: \"abbreviated\",\n context: \"formatting\",\n })\n .toLowerCase();\n case \"bbbbb\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"narrow\",\n context: \"formatting\",\n });\n case \"bbbb\":\n default:\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // in the morning, in the afternoon, in the evening, at night\n B: function (date, token, localize) {\n const hours = date.getHours();\n let dayPeriodEnumValue;\n if (hours >= 17) {\n dayPeriodEnumValue = dayPeriodEnum.evening;\n } else if (hours >= 12) {\n dayPeriodEnumValue = dayPeriodEnum.afternoon;\n } else if (hours >= 4) {\n dayPeriodEnumValue = dayPeriodEnum.morning;\n } else {\n dayPeriodEnumValue = dayPeriodEnum.night;\n }\n\n switch (token) {\n case \"B\":\n case \"BB\":\n case \"BBB\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n case \"BBBBB\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"narrow\",\n context: \"formatting\",\n });\n case \"BBBB\":\n default:\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // Hour [1-12]\n h: function (date, token, localize) {\n if (token === \"ho\") {\n let hours = date.getHours() % 12;\n if (hours === 0) hours = 12;\n return localize.ordinalNumber(hours, { unit: \"hour\" });\n }\n\n return _index7.lightFormatters.h(date, token);\n },\n\n // Hour [0-23]\n H: function (date, token, localize) {\n if (token === \"Ho\") {\n return localize.ordinalNumber(date.getHours(), { unit: \"hour\" });\n }\n\n return _index7.lightFormatters.H(date, token);\n },\n\n // Hour [0-11]\n K: function (date, token, localize) {\n const hours = date.getHours() % 12;\n\n if (token === \"Ko\") {\n return localize.ordinalNumber(hours, { unit: \"hour\" });\n }\n\n return (0, _index6.addLeadingZeros)(hours, token.length);\n },\n\n // Hour [1-24]\n k: function (date, token, localize) {\n let hours = date.getHours();\n if (hours === 0) hours = 24;\n\n if (token === \"ko\") {\n return localize.ordinalNumber(hours, { unit: \"hour\" });\n }\n\n return (0, _index6.addLeadingZeros)(hours, token.length);\n },\n\n // Minute\n m: function (date, token, localize) {\n if (token === \"mo\") {\n return localize.ordinalNumber(date.getMinutes(), { unit: \"minute\" });\n }\n\n return _index7.lightFormatters.m(date, token);\n },\n\n // Second\n s: function (date, token, localize) {\n if (token === \"so\") {\n return localize.ordinalNumber(date.getSeconds(), { unit: \"second\" });\n }\n\n return _index7.lightFormatters.s(date, token);\n },\n\n // Fraction of second\n S: function (date, token) {\n return _index7.lightFormatters.S(date, token);\n },\n\n // Timezone (ISO-8601. If offset is 0, output is always `'Z'`)\n X: function (date, token, _localize) {\n const timezoneOffset = date.getTimezoneOffset();\n\n if (timezoneOffset === 0) {\n return \"Z\";\n }\n\n switch (token) {\n // Hours and optional minutes\n case \"X\":\n return formatTimezoneWithOptionalMinutes(timezoneOffset);\n\n // Hours, minutes and optional seconds without `:` delimiter\n // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n // so this token always has the same output as `XX`\n case \"XXXX\":\n case \"XX\": // Hours and minutes without `:` delimiter\n return formatTimezone(timezoneOffset);\n\n // Hours, minutes and optional seconds with `:` delimiter\n // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n // so this token always has the same output as `XXX`\n case \"XXXXX\":\n case \"XXX\": // Hours and minutes with `:` delimiter\n default:\n return formatTimezone(timezoneOffset, \":\");\n }\n },\n\n // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)\n x: function (date, token, _localize) {\n const timezoneOffset = date.getTimezoneOffset();\n\n switch (token) {\n // Hours and optional minutes\n case \"x\":\n return formatTimezoneWithOptionalMinutes(timezoneOffset);\n\n // Hours, minutes and optional seconds without `:` delimiter\n // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n // so this token always has the same output as `xx`\n case \"xxxx\":\n case \"xx\": // Hours and minutes without `:` delimiter\n return formatTimezone(timezoneOffset);\n\n // Hours, minutes and optional seconds with `:` delimiter\n // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n // so this token always has the same output as `xxx`\n case \"xxxxx\":\n case \"xxx\": // Hours and minutes with `:` delimiter\n default:\n return formatTimezone(timezoneOffset, \":\");\n }\n },\n\n // Timezone (GMT)\n O: function (date, token, _localize) {\n const timezoneOffset = date.getTimezoneOffset();\n\n switch (token) {\n // Short\n case \"O\":\n case \"OO\":\n case \"OOO\":\n return \"GMT\" + formatTimezoneShort(timezoneOffset, \":\");\n // Long\n case \"OOOO\":\n default:\n return \"GMT\" + formatTimezone(timezoneOffset, \":\");\n }\n },\n\n // Timezone (specific non-location)\n z: function (date, token, _localize) {\n const timezoneOffset = date.getTimezoneOffset();\n\n switch (token) {\n // Short\n case \"z\":\n case \"zz\":\n case \"zzz\":\n return \"GMT\" + formatTimezoneShort(timezoneOffset, \":\");\n // Long\n case \"zzzz\":\n default:\n return \"GMT\" + formatTimezone(timezoneOffset, \":\");\n }\n },\n\n // Seconds timestamp\n t: function (date, token, _localize) {\n const timestamp = Math.trunc(+date / 1000);\n return (0, _index6.addLeadingZeros)(timestamp, token.length);\n },\n\n // Milliseconds timestamp\n T: function (date, token, _localize) {\n return (0, _index6.addLeadingZeros)(+date, token.length);\n },\n});\n\nfunction formatTimezoneShort(offset, delimiter = \"\") {\n const sign = offset > 0 ? \"-\" : \"+\";\n const absOffset = Math.abs(offset);\n const hours = Math.trunc(absOffset / 60);\n const minutes = absOffset % 60;\n if (minutes === 0) {\n return sign + String(hours);\n }\n return (\n sign + String(hours) + delimiter + (0, _index6.addLeadingZeros)(minutes, 2)\n );\n}\n\nfunction formatTimezoneWithOptionalMinutes(offset, delimiter) {\n if (offset % 60 === 0) {\n const sign = offset > 0 ? \"-\" : \"+\";\n return sign + (0, _index6.addLeadingZeros)(Math.abs(offset) / 60, 2);\n }\n return formatTimezone(offset, delimiter);\n}\n\nfunction formatTimezone(offset, delimiter = \"\") {\n const sign = offset > 0 ? \"-\" : \"+\";\n const absOffset = Math.abs(offset);\n const hours = (0, _index6.addLeadingZeros)(Math.trunc(absOffset / 60), 2);\n const minutes = (0, _index6.addLeadingZeros)(absOffset % 60, 2);\n return sign + hours + delimiter + minutes;\n}\n", "\"use strict\";\nexports.longFormatters = void 0;\n\nconst dateLongFormatter = (pattern, formatLong) => {\n switch (pattern) {\n case \"P\":\n return formatLong.date({ width: \"short\" });\n case \"PP\":\n return formatLong.date({ width: \"medium\" });\n case \"PPP\":\n return formatLong.date({ width: \"long\" });\n case \"PPPP\":\n default:\n return formatLong.date({ width: \"full\" });\n }\n};\n\nconst timeLongFormatter = (pattern, formatLong) => {\n switch (pattern) {\n case \"p\":\n return formatLong.time({ width: \"short\" });\n case \"pp\":\n return formatLong.time({ width: \"medium\" });\n case \"ppp\":\n return formatLong.time({ width: \"long\" });\n case \"pppp\":\n default:\n return formatLong.time({ width: \"full\" });\n }\n};\n\nconst dateTimeLongFormatter = (pattern, formatLong) => {\n const matchResult = pattern.match(/(P+)(p+)?/) || [];\n const datePattern = matchResult[1];\n const timePattern = matchResult[2];\n\n if (!timePattern) {\n return dateLongFormatter(pattern, formatLong);\n }\n\n let dateTimeFormat;\n\n switch (datePattern) {\n case \"P\":\n dateTimeFormat = formatLong.dateTime({ width: \"short\" });\n break;\n case \"PP\":\n dateTimeFormat = formatLong.dateTime({ width: \"medium\" });\n break;\n case \"PPP\":\n dateTimeFormat = formatLong.dateTime({ width: \"long\" });\n break;\n case \"PPPP\":\n default:\n dateTimeFormat = formatLong.dateTime({ width: \"full\" });\n break;\n }\n\n return dateTimeFormat\n .replace(\"{{date}}\", dateLongFormatter(datePattern, formatLong))\n .replace(\"{{time}}\", timeLongFormatter(timePattern, formatLong));\n};\n\nconst longFormatters = (exports.longFormatters = {\n p: timeLongFormatter,\n P: dateTimeLongFormatter,\n});\n", "\"use strict\";\nexports.isProtectedDayOfYearToken = isProtectedDayOfYearToken;\nexports.isProtectedWeekYearToken = isProtectedWeekYearToken;\nexports.warnOrThrowProtectedError = warnOrThrowProtectedError;\nconst dayOfYearTokenRE = /^D+$/;\nconst weekYearTokenRE = /^Y+$/;\n\nconst throwTokens = [\"D\", \"DD\", \"YY\", \"YYYY\"];\n\nfunction isProtectedDayOfYearToken(token) {\n return dayOfYearTokenRE.test(token);\n}\n\nfunction isProtectedWeekYearToken(token) {\n return weekYearTokenRE.test(token);\n}\n\nfunction warnOrThrowProtectedError(token, format, input) {\n const _message = message(token, format, input);\n console.warn(_message);\n if (throwTokens.includes(token)) throw new RangeError(_message);\n}\n\nfunction message(token, format, input) {\n const subject = token[0] === \"Y\" ? \"years\" : \"days of the month\";\n return `Use \\`${token.toLowerCase()}\\` instead of \\`${token}\\` (in \\`${format}\\`) for formatting ${subject} to the input \\`${input}\\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`;\n}\n", "\"use strict\";\nexports.format = exports.formatDate = format;\nObject.defineProperty(exports, \"formatters\", {\n enumerable: true,\n get: function () {\n return _index3.formatters;\n },\n});\nObject.defineProperty(exports, \"longFormatters\", {\n enumerable: true,\n get: function () {\n return _index4.longFormatters;\n },\n});\nvar _index = require(\"./_lib/defaultLocale.cjs\");\nvar _index2 = require(\"./_lib/defaultOptions.cjs\");\nvar _index3 = require(\"./_lib/format/formatters.cjs\");\nvar _index4 = require(\"./_lib/format/longFormatters.cjs\");\nvar _index5 = require(\"./_lib/protectedTokens.cjs\");\n\nvar _index6 = require(\"./isValid.cjs\");\nvar _index7 = require(\"./toDate.cjs\");\n\n// Rexports of internal for libraries to use.\n// See: https://github.com/date-fns/date-fns/issues/3638#issuecomment-1877082874\n\n// This RegExp consists of three parts separated by `|`:\n// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token\n// (one of the certain letters followed by `o`)\n// - (\\w)\\1* matches any sequences of the same letter\n// - '' matches two quote characters in a row\n// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),\n// except a single quote symbol, which ends the sequence.\n// Two quote characters do not end the sequence.\n// If there is no matching single quote\n// then the sequence will continue until the end of the string.\n// - . matches any single character unmatched by previous parts of the RegExps\nconst formattingTokensRegExp =\n /[yYQqMLwIdDecihHKkms]o|(\\w)\\1*|''|'(''|[^'])+('|$)|./g;\n\n// This RegExp catches symbols escaped by quotes, and also\n// sequences of symbols P, p, and the combinations like `PPPPPPPppppp`\nconst longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;\n\nconst escapedStringRegExp = /^'([^]*?)'?$/;\nconst doubleQuoteRegExp = /''/g;\nconst unescapedLatinCharacterRegExp = /[a-zA-Z]/;\n\n/**\n * The {@link format} function options.\n */\n\n/**\n * @name format\n * @alias formatDate\n * @category Common Helpers\n * @summary Format the date.\n *\n * @description\n * Return the formatted date string in the given format. The result may vary by locale.\n *\n * > \u26A0\uFE0F Please note that the `format` tokens differ from Moment.js and other libraries.\n * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * The characters wrapped between two single quotes characters (') are escaped.\n * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.\n * (see the last example)\n *\n * Format of the string is based on Unicode Technical Standard #35:\n * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n * with a few additions (see note 7 below the table).\n *\n * Accepted patterns:\n * | Unit | Pattern | Result examples | Notes |\n * |---------------------------------|---------|-----------------------------------|-------|\n * | Era | G..GGG | AD, BC | |\n * | | GGGG | Anno Domini, Before Christ | 2 |\n * | | GGGGG | A, B | |\n * | Calendar year | y | 44, 1, 1900, 2017 | 5 |\n * | | yo | 44th, 1st, 0th, 17th | 5,7 |\n * | | yy | 44, 01, 00, 17 | 5 |\n * | | yyy | 044, 001, 1900, 2017 | 5 |\n * | | yyyy | 0044, 0001, 1900, 2017 | 5 |\n * | | yyyyy | ... | 3,5 |\n * | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 |\n * | | Yo | 44th, 1st, 1900th, 2017th | 5,7 |\n * | | YY | 44, 01, 00, 17 | 5,8 |\n * | | YYY | 044, 001, 1900, 2017 | 5 |\n * | | YYYY | 0044, 0001, 1900, 2017 | 5,8 |\n * | | YYYYY | ... | 3,5 |\n * | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 |\n * | | RR | -43, 00, 01, 1900, 2017 | 5,7 |\n * | | RRR | -043, 000, 001, 1900, 2017 | 5,7 |\n * | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 |\n * | | RRRRR | ... | 3,5,7 |\n * | Extended year | u | -43, 0, 1, 1900, 2017 | 5 |\n * | | uu | -43, 01, 1900, 2017 | 5 |\n * | | uuu | -043, 001, 1900, 2017 | 5 |\n * | | uuuu | -0043, 0001, 1900, 2017 | 5 |\n * | | uuuuu | ... | 3,5 |\n * | Quarter (formatting) | Q | 1, 2, 3, 4 | |\n * | | Qo | 1st, 2nd, 3rd, 4th | 7 |\n * | | QQ | 01, 02, 03, 04 | |\n * | | QQQ | Q1, Q2, Q3, Q4 | |\n * | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |\n * | | QQQQQ | 1, 2, 3, 4 | 4 |\n * | Quarter (stand-alone) | q | 1, 2, 3, 4 | |\n * | | qo | 1st, 2nd, 3rd, 4th | 7 |\n * | | qq | 01, 02, 03, 04 | |\n * | | qqq | Q1, Q2, Q3, Q4 | |\n * | | qqqq | 1st quarter, 2nd quarter, ... | 2 |\n * | | qqqqq | 1, 2, 3, 4 | 4 |\n * | Month (formatting) | M | 1, 2, ..., 12 | |\n * | | Mo | 1st, 2nd, ..., 12th | 7 |\n * | | MM | 01, 02, ..., 12 | |\n * | | MMM | Jan, Feb, ..., Dec | |\n * | | MMMM | January, February, ..., December | 2 |\n * | | MMMMM | J, F, ..., D | |\n * | Month (stand-alone) | L | 1, 2, ..., 12 | |\n * | | Lo | 1st, 2nd, ..., 12th | 7 |\n * | | LL | 01, 02, ..., 12 | |\n * | | LLL | Jan, Feb, ..., Dec | |\n * | | LLLL | January, February, ..., December | 2 |\n * | | LLLLL | J, F, ..., D | |\n * | Local week of year | w | 1, 2, ..., 53 | |\n * | | wo | 1st, 2nd, ..., 53th | 7 |\n * | | ww | 01, 02, ..., 53 | |\n * | ISO week of year | I | 1, 2, ..., 53 | 7 |\n * | | Io | 1st, 2nd, ..., 53th | 7 |\n * | | II | 01, 02, ..., 53 | 7 |\n * | Day of month | d | 1, 2, ..., 31 | |\n * | | do | 1st, 2nd, ..., 31st | 7 |\n * | | dd | 01, 02, ..., 31 | |\n * | Day of year | D | 1, 2, ..., 365, 366 | 9 |\n * | | Do | 1st, 2nd, ..., 365th, 366th | 7 |\n * | | DD | 01, 02, ..., 365, 366 | 9 |\n * | | DDD | 001, 002, ..., 365, 366 | |\n * | | DDDD | ... | 3 |\n * | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Sun | |\n * | | EEEE | Monday, Tuesday, ..., Sunday | 2 |\n * | | EEEEE | M, T, W, T, F, S, S | |\n * | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 |\n * | | io | 1st, 2nd, ..., 7th | 7 |\n * | | ii | 01, 02, ..., 07 | 7 |\n * | | iii | Mon, Tue, Wed, ..., Sun | 7 |\n * | | iiii | Monday, Tuesday, ..., Sunday | 2,7 |\n * | | iiiii | M, T, W, T, F, S, S | 7 |\n * | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 7 |\n * | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | |\n * | | eo | 2nd, 3rd, ..., 1st | 7 |\n * | | ee | 02, 03, ..., 01 | |\n * | | eee | Mon, Tue, Wed, ..., Sun | |\n * | | eeee | Monday, Tuesday, ..., Sunday | 2 |\n * | | eeeee | M, T, W, T, F, S, S | |\n * | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | |\n * | | co | 2nd, 3rd, ..., 1st | 7 |\n * | | cc | 02, 03, ..., 01 | |\n * | | ccc | Mon, Tue, Wed, ..., Sun | |\n * | | cccc | Monday, Tuesday, ..., Sunday | 2 |\n * | | ccccc | M, T, W, T, F, S, S | |\n * | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | AM, PM | a..aa | AM, PM | |\n * | | aaa | am, pm | |\n * | | aaaa | a.m., p.m. | 2 |\n * | | aaaaa | a, p | |\n * | AM, PM, noon, midnight | b..bb | AM, PM, noon, midnight | |\n * | | bbb | am, pm, noon, midnight | |\n * | | bbbb | a.m., p.m., noon, midnight | 2 |\n * | | bbbbb | a, p, n, mi | |\n * | Flexible day period | B..BBB | at night, in the morning, ... | |\n * | | BBBB | at night, in the morning, ... | 2 |\n * | | BBBBB | at night, in the morning, ... | |\n * | Hour [1-12] | h | 1, 2, ..., 11, 12 | |\n * | | ho | 1st, 2nd, ..., 11th, 12th | 7 |\n * | | hh | 01, 02, ..., 11, 12 | |\n * | Hour [0-23] | H | 0, 1, 2, ..., 23 | |\n * | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 |\n * | | HH | 00, 01, 02, ..., 23 | |\n * | Hour [0-11] | K | 1, 2, ..., 11, 0 | |\n * | | Ko | 1st, 2nd, ..., 11th, 0th | 7 |\n * | | KK | 01, 02, ..., 11, 00 | |\n * | Hour [1-24] | k | 24, 1, 2, ..., 23 | |\n * | | ko | 24th, 1st, 2nd, ..., 23rd | 7 |\n * | | kk | 24, 01, 02, ..., 23 | |\n * | Minute | m | 0, 1, ..., 59 | |\n * | | mo | 0th, 1st, ..., 59th | 7 |\n * | | mm | 00, 01, ..., 59 | |\n * | Second | s | 0, 1, ..., 59 | |\n * | | so | 0th, 1st, ..., 59th | 7 |\n * | | ss | 00, 01, ..., 59 | |\n * | Fraction of second | S | 0, 1, ..., 9 | |\n * | | SS | 00, 01, ..., 99 | |\n * | | SSS | 000, 001, ..., 999 | |\n * | | SSSS | ... | 3 |\n * | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | |\n * | | XX | -0800, +0530, Z | |\n * | | XXX | -08:00, +05:30, Z | |\n * | | XXXX | -0800, +0530, Z, +123456 | 2 |\n * | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |\n * | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | |\n * | | xx | -0800, +0530, +0000 | |\n * | | xxx | -08:00, +05:30, +00:00 | 2 |\n * | | xxxx | -0800, +0530, +0000, +123456 | |\n * | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |\n * | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | |\n * | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 |\n * | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 |\n * | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 |\n * | Seconds timestamp | t | 512969520 | 7 |\n * | | tt | ... | 3,7 |\n * | Milliseconds timestamp | T | 512969520900 | 7 |\n * | | TT | ... | 3,7 |\n * | Long localized date | P | 04/29/1453 | 7 |\n * | | PP | Apr 29, 1453 | 7 |\n * | | PPP | April 29th, 1453 | 7 |\n * | | PPPP | Friday, April 29th, 1453 | 2,7 |\n * | Long localized time | p | 12:00 AM | 7 |\n * | | pp | 12:00:00 AM | 7 |\n * | | ppp | 12:00:00 AM GMT+2 | 7 |\n * | | pppp | 12:00:00 AM GMT+02:00 | 2,7 |\n * | Combination of date and time | Pp | 04/29/1453, 12:00 AM | 7 |\n * | | PPpp | Apr 29, 1453, 12:00:00 AM | 7 |\n * | | PPPppp | April 29th, 1453 at ... | 7 |\n * | | PPPPpppp| Friday, April 29th, 1453 at ... | 2,7 |\n * Notes:\n * 1. \"Formatting\" units (e.g. formatting quarter) in the default en-US locale\n * are the same as \"stand-alone\" units, but are different in some languages.\n * \"Formatting\" units are declined according to the rules of the language\n * in the context of a date. \"Stand-alone\" units are always nominative singular:\n *\n * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`\n *\n * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`\n *\n * 2. Any sequence of the identical letters is a pattern, unless it is escaped by\n * the single quote characters (see below).\n * If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`)\n * the output will be the same as default pattern for this unit, usually\n * the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units\n * are marked with \"2\" in the last column of the table.\n *\n * `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'`\n *\n * `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'`\n *\n * `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'`\n *\n * `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'`\n *\n * `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'`\n *\n * 3. Some patterns could be unlimited length (such as `yyyyyyyy`).\n * The output will be padded with zeros to match the length of the pattern.\n *\n * `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'`\n *\n * 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.\n * These tokens represent the shortest form of the quarter.\n *\n * 5. The main difference between `y` and `u` patterns are B.C. years:\n *\n * | Year | `y` | `u` |\n * |------|-----|-----|\n * | AC 1 | 1 | 1 |\n * | BC 1 | 1 | 0 |\n * | BC 2 | 2 | -1 |\n *\n * Also `yy` always returns the last two digits of a year,\n * while `uu` pads single digit years to 2 characters and returns other years unchanged:\n *\n * | Year | `yy` | `uu` |\n * |------|------|------|\n * | 1 | 01 | 01 |\n * | 14 | 14 | 14 |\n * | 376 | 76 | 376 |\n * | 1453 | 53 | 1453 |\n *\n * The same difference is true for local and ISO week-numbering years (`Y` and `R`),\n * except local week-numbering years are dependent on `options.weekStartsOn`\n * and `options.firstWeekContainsDate` (compare [getISOWeekYear](https://date-fns.org/docs/getISOWeekYear)\n * and [getWeekYear](https://date-fns.org/docs/getWeekYear)).\n *\n * 6. Specific non-location timezones are currently unavailable in `date-fns`,\n * so right now these tokens fall back to GMT timezones.\n *\n * 7. These patterns are not in the Unicode Technical Standard #35:\n * - `i`: ISO day of week\n * - `I`: ISO week of year\n * - `R`: ISO week-numbering year\n * - `t`: seconds timestamp\n * - `T`: milliseconds timestamp\n * - `o`: ordinal number modifier\n * - `P`: long localized date\n * - `p`: long localized time\n *\n * 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.\n * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * 9. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.\n * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * @param date - The original date\n * @param format - The string of tokens\n * @param options - An object with options\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n * @throws `options.locale` must contain `localize` property\n * @throws `options.locale` must contain `formatLong` property\n * @throws use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws format string contains an unescaped latin alphabet character\n *\n * @example\n * // Represent 11 February 2014 in middle-endian format:\n * const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy')\n * //=> '02/11/2014'\n *\n * @example\n * // Represent 2 July 2014 in Esperanto:\n * import { eoLocale } from 'date-fns/locale/eo'\n * const result = format(new Date(2014, 6, 2), \"do 'de' MMMM yyyy\", {\n * locale: eoLocale\n * })\n * //=> '2-a de julio 2014'\n *\n * @example\n * // Escape string by single quote characters:\n * const result = format(new Date(2014, 6, 2, 15), \"h 'o''clock'\")\n * //=> \"3 o'clock\"\n */\nfunction format(date, formatStr, options) {\n const defaultOptions = (0, _index2.getDefaultOptions)();\n const locale =\n options?.locale ?? defaultOptions.locale ?? _index.defaultLocale;\n\n const firstWeekContainsDate =\n options?.firstWeekContainsDate ??\n options?.locale?.options?.firstWeekContainsDate ??\n defaultOptions.firstWeekContainsDate ??\n defaultOptions.locale?.options?.firstWeekContainsDate ??\n 1;\n\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const originalDate = (0, _index7.toDate)(date, options?.in);\n\n if (!(0, _index6.isValid)(originalDate)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n let parts = formatStr\n .match(longFormattingTokensRegExp)\n .map((substring) => {\n const firstCharacter = substring[0];\n if (firstCharacter === \"p\" || firstCharacter === \"P\") {\n const longFormatter = _index4.longFormatters[firstCharacter];\n return longFormatter(substring, locale.formatLong);\n }\n return substring;\n })\n .join(\"\")\n .match(formattingTokensRegExp)\n .map((substring) => {\n // Replace two single quote characters with one single quote character\n if (substring === \"''\") {\n return { isToken: false, value: \"'\" };\n }\n\n const firstCharacter = substring[0];\n if (firstCharacter === \"'\") {\n return { isToken: false, value: cleanEscapedString(substring) };\n }\n\n if (_index3.formatters[firstCharacter]) {\n return { isToken: true, value: substring };\n }\n\n if (firstCharacter.match(unescapedLatinCharacterRegExp)) {\n throw new RangeError(\n \"Format string contains an unescaped latin alphabet character `\" +\n firstCharacter +\n \"`\",\n );\n }\n\n return { isToken: false, value: substring };\n });\n\n // invoke localize preprocessor (only for french locales at the moment)\n if (locale.localize.preprocessor) {\n parts = locale.localize.preprocessor(originalDate, parts);\n }\n\n const formatterOptions = {\n firstWeekContainsDate,\n weekStartsOn,\n locale,\n };\n\n return parts\n .map((part) => {\n if (!part.isToken) return part.value;\n\n const token = part.value;\n\n if (\n (!options?.useAdditionalWeekYearTokens &&\n (0, _index5.isProtectedWeekYearToken)(token)) ||\n (!options?.useAdditionalDayOfYearTokens &&\n (0, _index5.isProtectedDayOfYearToken)(token))\n ) {\n (0, _index5.warnOrThrowProtectedError)(token, formatStr, String(date));\n }\n\n const formatter = _index3.formatters[token[0]];\n return formatter(originalDate, token, locale.localize, formatterOptions);\n })\n .join(\"\");\n}\n\nfunction cleanEscapedString(input) {\n const matched = input.match(escapedStringRegExp);\n\n if (!matched) {\n return input;\n }\n\n return matched[1].replace(doubleQuoteRegExp, \"'\");\n}\n", "\"use strict\";\nexports.formatDistance = formatDistance;\nvar _index = require(\"./_lib/defaultLocale.cjs\");\nvar _index2 = require(\"./_lib/defaultOptions.cjs\");\nvar _index3 = require(\"./_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _index4 = require(\"./_lib/normalizeDates.cjs\");\nvar _index5 = require(\"./compareAsc.cjs\");\nvar _index6 = require(\"./constants.cjs\");\nvar _index7 = require(\"./differenceInMonths.cjs\");\nvar _index8 = require(\"./differenceInSeconds.cjs\");\n\n/**\n * The {@link formatDistance} function options.\n */\n\n/**\n * @name formatDistance\n * @category Common Helpers\n * @summary Return the distance between the given dates in words.\n *\n * @description\n * Return the distance between the given dates in words.\n *\n * | Distance between dates | Result |\n * |-------------------------------------------------------------------|---------------------|\n * | 0 ... 30 secs | less than a minute |\n * | 30 secs ... 1 min 30 secs | 1 minute |\n * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes |\n * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour |\n * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours |\n * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day |\n * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days |\n * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month |\n * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months |\n * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months |\n * | 1 yr ... 1 yr 3 months | about 1 year |\n * | 1 yr 3 months ... 1 yr 9 month s | over 1 year |\n * | 1 yr 9 months ... 2 yrs | almost 2 years |\n * | N yrs ... N yrs 3 months | about N years |\n * | N yrs 3 months ... N yrs 9 months | over N years |\n * | N yrs 9 months ... N+1 yrs | almost N+1 years |\n *\n * With `options.includeSeconds == true`:\n * | Distance between dates | Result |\n * |------------------------|----------------------|\n * | 0 secs ... 5 secs | less than 5 seconds |\n * | 5 secs ... 10 secs | less than 10 seconds |\n * | 10 secs ... 20 secs | less than 20 seconds |\n * | 20 secs ... 40 secs | half a minute |\n * | 40 secs ... 60 secs | less than a minute |\n * | 60 secs ... 90 secs | 1 minute |\n *\n * @param laterDate - The date\n * @param earlierDate - The date to compare with\n * @param options - An object with options\n *\n * @returns The distance in words\n *\n * @throws `date` must not be Invalid Date\n * @throws `baseDate` must not be Invalid Date\n * @throws `options.locale` must contain `formatDistance` property\n *\n * @example\n * // What is the distance between 2 July 2014 and 1 January 2015?\n * const result = formatDistance(new Date(2014, 6, 2), new Date(2015, 0, 1))\n * //=> '6 months'\n *\n * @example\n * // What is the distance between 1 January 2015 00:00:15\n * // and 1 January 2015 00:00:00, including seconds?\n * const result = formatDistance(\n * new Date(2015, 0, 1, 0, 0, 15),\n * new Date(2015, 0, 1, 0, 0, 0),\n * { includeSeconds: true }\n * )\n * //=> 'less than 20 seconds'\n *\n * @example\n * // What is the distance from 1 January 2016\n * // to 1 January 2015, with a suffix?\n * const result = formatDistance(new Date(2015, 0, 1), new Date(2016, 0, 1), {\n * addSuffix: true\n * })\n * //=> 'about 1 year ago'\n *\n * @example\n * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto?\n * import { eoLocale } from 'date-fns/locale/eo'\n * const result = formatDistance(new Date(2016, 7, 1), new Date(2015, 0, 1), {\n * locale: eoLocale\n * })\n * //=> 'pli ol 1 jaro'\n */\nfunction formatDistance(laterDate, earlierDate, options) {\n const defaultOptions = (0, _index2.getDefaultOptions)();\n const locale =\n options?.locale ?? defaultOptions.locale ?? _index.defaultLocale;\n const minutesInAlmostTwoDays = 2520;\n\n const comparison = (0, _index5.compareAsc)(laterDate, earlierDate);\n\n if (isNaN(comparison)) throw new RangeError(\"Invalid time value\");\n\n const localizeOptions = Object.assign({}, options, {\n addSuffix: options?.addSuffix,\n comparison: comparison,\n });\n\n const [laterDate_, earlierDate_] = (0, _index4.normalizeDates)(\n options?.in,\n ...(comparison > 0 ? [earlierDate, laterDate] : [laterDate, earlierDate]),\n );\n\n const seconds = (0, _index8.differenceInSeconds)(earlierDate_, laterDate_);\n const offsetInSeconds =\n ((0, _index3.getTimezoneOffsetInMilliseconds)(earlierDate_) -\n (0, _index3.getTimezoneOffsetInMilliseconds)(laterDate_)) /\n 1000;\n const minutes = Math.round((seconds - offsetInSeconds) / 60);\n let months;\n\n // 0 up to 2 mins\n if (minutes < 2) {\n if (options?.includeSeconds) {\n if (seconds < 5) {\n return locale.formatDistance(\"lessThanXSeconds\", 5, localizeOptions);\n } else if (seconds < 10) {\n return locale.formatDistance(\"lessThanXSeconds\", 10, localizeOptions);\n } else if (seconds < 20) {\n return locale.formatDistance(\"lessThanXSeconds\", 20, localizeOptions);\n } else if (seconds < 40) {\n return locale.formatDistance(\"halfAMinute\", 0, localizeOptions);\n } else if (seconds < 60) {\n return locale.formatDistance(\"lessThanXMinutes\", 1, localizeOptions);\n } else {\n return locale.formatDistance(\"xMinutes\", 1, localizeOptions);\n }\n } else {\n if (minutes === 0) {\n return locale.formatDistance(\"lessThanXMinutes\", 1, localizeOptions);\n } else {\n return locale.formatDistance(\"xMinutes\", minutes, localizeOptions);\n }\n }\n\n // 2 mins up to 0.75 hrs\n } else if (minutes < 45) {\n return locale.formatDistance(\"xMinutes\", minutes, localizeOptions);\n\n // 0.75 hrs up to 1.5 hrs\n } else if (minutes < 90) {\n return locale.formatDistance(\"aboutXHours\", 1, localizeOptions);\n\n // 1.5 hrs up to 24 hrs\n } else if (minutes < _index6.minutesInDay) {\n const hours = Math.round(minutes / 60);\n return locale.formatDistance(\"aboutXHours\", hours, localizeOptions);\n\n // 1 day up to 1.75 days\n } else if (minutes < minutesInAlmostTwoDays) {\n return locale.formatDistance(\"xDays\", 1, localizeOptions);\n\n // 1.75 days up to 30 days\n } else if (minutes < _index6.minutesInMonth) {\n const days = Math.round(minutes / _index6.minutesInDay);\n return locale.formatDistance(\"xDays\", days, localizeOptions);\n\n // 1 month up to 2 months\n } else if (minutes < _index6.minutesInMonth * 2) {\n months = Math.round(minutes / _index6.minutesInMonth);\n return locale.formatDistance(\"aboutXMonths\", months, localizeOptions);\n }\n\n months = (0, _index7.differenceInMonths)(earlierDate_, laterDate_);\n\n // 2 months up to 12 months\n if (months < 12) {\n const nearestMonth = Math.round(minutes / _index6.minutesInMonth);\n return locale.formatDistance(\"xMonths\", nearestMonth, localizeOptions);\n\n // 1 year up to max Date\n } else {\n const monthsSinceStartOfYear = months % 12;\n const years = Math.trunc(months / 12);\n\n // N years up to 1 years 3 months\n if (monthsSinceStartOfYear < 3) {\n return locale.formatDistance(\"aboutXYears\", years, localizeOptions);\n\n // N years 3 months up to N years 9 months\n } else if (monthsSinceStartOfYear < 9) {\n return locale.formatDistance(\"overXYears\", years, localizeOptions);\n\n // N years 9 months up to N year 12 months\n } else {\n return locale.formatDistance(\"almostXYears\", years + 1, localizeOptions);\n }\n }\n}\n", "\"use strict\";\nexports.formatDistanceStrict = formatDistanceStrict;\nvar _index = require(\"./_lib/defaultLocale.cjs\");\nvar _index2 = require(\"./_lib/defaultOptions.cjs\");\nvar _index3 = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index4 = require(\"./_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _index5 = require(\"./_lib/normalizeDates.cjs\");\nvar _index6 = require(\"./compareAsc.cjs\");\nvar _index7 = require(\"./constants.cjs\");\n\n/**\n * The {@link formatDistanceStrict} function options.\n */\n\n/**\n * The unit used to format the distance in {@link formatDistanceStrict}.\n */\n\n/**\n * @name formatDistanceStrict\n * @category Common Helpers\n * @summary Return the distance between the given dates in words.\n *\n * @description\n * Return the distance between the given dates in words, using strict units.\n * This is like `formatDistance`, but does not use helpers like 'almost', 'over',\n * 'less than' and the like.\n *\n * | Distance between dates | Result |\n * |------------------------|---------------------|\n * | 0 ... 59 secs | [0..59] seconds |\n * | 1 ... 59 mins | [1..59] minutes |\n * | 1 ... 23 hrs | [1..23] hours |\n * | 1 ... 29 days | [1..29] days |\n * | 1 ... 11 months | [1..11] months |\n * | 1 ... N years | [1..N] years |\n *\n * @param laterDate - The date\n * @param earlierDate - The date to compare with\n * @param options - An object with options\n *\n * @returns The distance in words\n *\n * @throws `date` must not be Invalid Date\n * @throws `baseDate` must not be Invalid Date\n * @throws `options.unit` must be 'second', 'minute', 'hour', 'day', 'month' or 'year'\n * @throws `options.locale` must contain `formatDistance` property\n *\n * @example\n * // What is the distance between 2 July 2014 and 1 January 2015?\n * const result = formatDistanceStrict(new Date(2014, 6, 2), new Date(2015, 0, 2))\n * //=> '6 months'\n *\n * @example\n * // What is the distance between 1 January 2015 00:00:15\n * // and 1 January 2015 00:00:00?\n * const result = formatDistanceStrict(\n * new Date(2015, 0, 1, 0, 0, 15),\n * new Date(2015, 0, 1, 0, 0, 0)\n * )\n * //=> '15 seconds'\n *\n * @example\n * // What is the distance from 1 January 2016\n * // to 1 January 2015, with a suffix?\n * const result = formatDistanceStrict(new Date(2015, 0, 1), new Date(2016, 0, 1), {\n * addSuffix: true\n * })\n * //=> '1 year ago'\n *\n * @example\n * // What is the distance from 1 January 2016\n * // to 1 January 2015, in minutes?\n * const result = formatDistanceStrict(new Date(2016, 0, 1), new Date(2015, 0, 1), {\n * unit: 'minute'\n * })\n * //=> '525600 minutes'\n *\n * @example\n * // What is the distance from 1 January 2015\n * // to 28 January 2015, in months, rounded up?\n * const result = formatDistanceStrict(new Date(2015, 0, 28), new Date(2015, 0, 1), {\n * unit: 'month',\n * roundingMethod: 'ceil'\n * })\n * //=> '1 month'\n *\n * @example\n * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto?\n * import { eoLocale } from 'date-fns/locale/eo'\n * const result = formatDistanceStrict(new Date(2016, 7, 1), new Date(2015, 0, 1), {\n * locale: eoLocale\n * })\n * //=> '1 jaro'\n */\n\nfunction formatDistanceStrict(laterDate, earlierDate, options) {\n const defaultOptions = (0, _index2.getDefaultOptions)();\n const locale =\n options?.locale ?? defaultOptions.locale ?? _index.defaultLocale;\n\n const comparison = (0, _index6.compareAsc)(laterDate, earlierDate);\n\n if (isNaN(comparison)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n const localizeOptions = Object.assign({}, options, {\n addSuffix: options?.addSuffix,\n comparison: comparison,\n });\n\n const [laterDate_, earlierDate_] = (0, _index5.normalizeDates)(\n options?.in,\n ...(comparison > 0 ? [earlierDate, laterDate] : [laterDate, earlierDate]),\n );\n\n const roundingMethod = (0, _index3.getRoundingMethod)(\n options?.roundingMethod ?? \"round\",\n );\n\n const milliseconds = earlierDate_.getTime() - laterDate_.getTime();\n const minutes = milliseconds / _index7.millisecondsInMinute;\n\n const timezoneOffset =\n (0, _index4.getTimezoneOffsetInMilliseconds)(earlierDate_) -\n (0, _index4.getTimezoneOffsetInMilliseconds)(laterDate_);\n\n // Use DST-normalized difference in minutes for years, months and days;\n // use regular difference in minutes for hours, minutes and seconds.\n const dstNormalizedMinutes =\n (milliseconds - timezoneOffset) / _index7.millisecondsInMinute;\n\n const defaultUnit = options?.unit;\n let unit;\n if (!defaultUnit) {\n if (minutes < 1) {\n unit = \"second\";\n } else if (minutes < 60) {\n unit = \"minute\";\n } else if (minutes < _index7.minutesInDay) {\n unit = \"hour\";\n } else if (dstNormalizedMinutes < _index7.minutesInMonth) {\n unit = \"day\";\n } else if (dstNormalizedMinutes < _index7.minutesInYear) {\n unit = \"month\";\n } else {\n unit = \"year\";\n }\n } else {\n unit = defaultUnit;\n }\n\n // 0 up to 60 seconds\n if (unit === \"second\") {\n const seconds = roundingMethod(milliseconds / 1000);\n return locale.formatDistance(\"xSeconds\", seconds, localizeOptions);\n\n // 1 up to 60 mins\n } else if (unit === \"minute\") {\n const roundedMinutes = roundingMethod(minutes);\n return locale.formatDistance(\"xMinutes\", roundedMinutes, localizeOptions);\n\n // 1 up to 24 hours\n } else if (unit === \"hour\") {\n const hours = roundingMethod(minutes / 60);\n return locale.formatDistance(\"xHours\", hours, localizeOptions);\n\n // 1 up to 30 days\n } else if (unit === \"day\") {\n const days = roundingMethod(dstNormalizedMinutes / _index7.minutesInDay);\n return locale.formatDistance(\"xDays\", days, localizeOptions);\n\n // 1 up to 12 months\n } else if (unit === \"month\") {\n const months = roundingMethod(\n dstNormalizedMinutes / _index7.minutesInMonth,\n );\n return months === 12 && defaultUnit !== \"month\"\n ? locale.formatDistance(\"xYears\", 1, localizeOptions)\n : locale.formatDistance(\"xMonths\", months, localizeOptions);\n\n // 1 year up to max Date\n } else {\n const years = roundingMethod(dstNormalizedMinutes / _index7.minutesInYear);\n return locale.formatDistance(\"xYears\", years, localizeOptions);\n }\n}\n", "\"use strict\";\nexports.formatDistanceToNow = formatDistanceToNow;\nvar _index = require(\"./constructNow.cjs\");\n\nvar _index2 = require(\"./formatDistance.cjs\");\n\n/**\n * The {@link formatDistanceToNow} function options.\n */\n\n/**\n * @name formatDistanceToNow\n * @category Common Helpers\n * @summary Return the distance between the given date and now in words.\n * @pure false\n *\n * @description\n * Return the distance between the given date and now in words.\n *\n * | Distance to now | Result |\n * |-------------------------------------------------------------------|---------------------|\n * | 0 ... 30 secs | less than a minute |\n * | 30 secs ... 1 min 30 secs | 1 minute |\n * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes |\n * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour |\n * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours |\n * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day |\n * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days |\n * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month |\n * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months |\n * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months |\n * | 1 yr ... 1 yr 3 months | about 1 year |\n * | 1 yr 3 months ... 1 yr 9 month s | over 1 year |\n * | 1 yr 9 months ... 2 yrs | almost 2 years |\n * | N yrs ... N yrs 3 months | about N years |\n * | N yrs 3 months ... N yrs 9 months | over N years |\n * | N yrs 9 months ... N+1 yrs | almost N+1 years |\n *\n * With `options.includeSeconds == true`:\n * | Distance to now | Result |\n * |---------------------|----------------------|\n * | 0 secs ... 5 secs | less than 5 seconds |\n * | 5 secs ... 10 secs | less than 10 seconds |\n * | 10 secs ... 20 secs | less than 20 seconds |\n * | 20 secs ... 40 secs | half a minute |\n * | 40 secs ... 60 secs | less than a minute |\n * | 60 secs ... 90 secs | 1 minute |\n *\n * @param date - The given date\n * @param options - The object with options\n *\n * @returns The distance in words\n *\n * @throws `date` must not be Invalid Date\n * @throws `options.locale` must contain `formatDistance` property\n *\n * @example\n * // If today is 1 January 2015, what is the distance to 2 July 2014?\n * const result = formatDistanceToNow(\n * new Date(2014, 6, 2)\n * )\n * //=> '6 months'\n *\n * @example\n * // If now is 1 January 2015 00:00:00,\n * // what is the distance to 1 January 2015 00:00:15, including seconds?\n * const result = formatDistanceToNow(\n * new Date(2015, 0, 1, 0, 0, 15),\n * {includeSeconds: true}\n * )\n * //=> 'less than 20 seconds'\n *\n * @example\n * // If today is 1 January 2015,\n * // what is the distance to 1 January 2016, with a suffix?\n * const result = formatDistanceToNow(\n * new Date(2016, 0, 1),\n * {addSuffix: true}\n * )\n * //=> 'in about 1 year'\n *\n * @example\n * // If today is 1 January 2015,\n * // what is the distance to 1 August 2016 in Esperanto?\n * const eoLocale = require('date-fns/locale/eo')\n * const result = formatDistanceToNow(\n * new Date(2016, 7, 1),\n * {locale: eoLocale}\n * )\n * //=> 'pli ol 1 jaro'\n */\nfunction formatDistanceToNow(date, options) {\n return (0, _index2.formatDistance)(\n date,\n (0, _index.constructNow)(date),\n options,\n );\n}\n", "\"use strict\";\nexports.formatDistanceToNowStrict = formatDistanceToNowStrict;\nvar _index = require(\"./constructNow.cjs\");\n\nvar _index2 = require(\"./formatDistanceStrict.cjs\");\n\n/**\n * The {@link formatDistanceToNowStrict} function options.\n */\n\n/**\n * @name formatDistanceToNowStrict\n * @category Common Helpers\n * @summary Return the distance between the given date and now in words.\n * @pure false\n *\n * @description\n * Return the distance between the given dates in words, using strict units.\n * This is like `formatDistance`, but does not use helpers like 'almost', 'over',\n * 'less than' and the like.\n *\n * | Distance between dates | Result |\n * |------------------------|---------------------|\n * | 0 ... 59 secs | [0..59] seconds |\n * | 1 ... 59 mins | [1..59] minutes |\n * | 1 ... 23 hrs | [1..23] hours |\n * | 1 ... 29 days | [1..29] days |\n * | 1 ... 11 months | [1..11] months |\n * | 1 ... N years | [1..N] years |\n *\n * @param date - The given date\n * @param options - An object with options.\n *\n * @returns The distance in words\n *\n * @throws `date` must not be Invalid Date\n * @throws `options.locale` must contain `formatDistance` property\n *\n * @example\n * // If today is 1 January 2015, what is the distance to 2 July 2014?\n * const result = formatDistanceToNowStrict(\n * new Date(2014, 6, 2)\n * )\n * //=> '6 months'\n *\n * @example\n * // If now is 1 January 2015 00:00:00,\n * // what is the distance to 1 January 2015 00:00:15, including seconds?\n * const result = formatDistanceToNowStrict(\n * new Date(2015, 0, 1, 0, 0, 15)\n * )\n * //=> '15 seconds'\n *\n * @example\n * // If today is 1 January 2015,\n * // what is the distance to 1 January 2016, with a suffix?\n * const result = formatDistanceToNowStrict(\n * new Date(2016, 0, 1),\n * {addSuffix: true}\n * )\n * //=> 'in 1 year'\n *\n * @example\n * // If today is 28 January 2015,\n * // what is the distance to 1 January 2015, in months, rounded up??\n * const result = formatDistanceToNowStrict(new Date(2015, 0, 1), {\n * unit: 'month',\n * roundingMethod: 'ceil'\n * })\n * //=> '1 month'\n *\n * @example\n * // If today is 1 January 2015,\n * // what is the distance to 1 January 2016 in Esperanto?\n * const eoLocale = require('date-fns/locale/eo')\n * const result = formatDistanceToNowStrict(\n * new Date(2016, 0, 1),\n * {locale: eoLocale}\n * )\n * //=> '1 jaro'\n */\nfunction formatDistanceToNowStrict(date, options) {\n return (0, _index2.formatDistanceStrict)(\n date,\n (0, _index.constructNow)(date),\n options,\n );\n}\n", "\"use strict\";\nexports.formatDuration = formatDuration;\n\nvar _index = require(\"./_lib/defaultLocale.cjs\");\nvar _index2 = require(\"./_lib/defaultOptions.cjs\");\n\n/**\n * The {@link formatDuration} function options.\n */\n\nconst defaultFormat = [\n \"years\",\n \"months\",\n \"weeks\",\n \"days\",\n \"hours\",\n \"minutes\",\n \"seconds\",\n];\n\n/**\n * @name formatDuration\n * @category Common Helpers\n * @summary Formats a duration in human-readable format\n *\n * @description\n * Return human-readable duration string i.e. \"9 months 2 days\"\n *\n * @param duration - The duration to format\n * @param options - An object with options.\n *\n * @returns The formatted date string\n *\n * @example\n * // Format full duration\n * formatDuration({\n * years: 2,\n * months: 9,\n * weeks: 1,\n * days: 7,\n * hours: 5,\n * minutes: 9,\n * seconds: 30\n * })\n * //=> '2 years 9 months 1 week 7 days 5 hours 9 minutes 30 seconds'\n *\n * @example\n * // Format partial duration\n * formatDuration({ months: 9, days: 2 })\n * //=> '9 months 2 days'\n *\n * @example\n * // Customize the format\n * formatDuration(\n * {\n * years: 2,\n * months: 9,\n * weeks: 1,\n * days: 7,\n * hours: 5,\n * minutes: 9,\n * seconds: 30\n * },\n * { format: ['months', 'weeks'] }\n * ) === '9 months 1 week'\n *\n * @example\n * // Customize the zeros presence\n * formatDuration({ years: 0, months: 9 })\n * //=> '9 months'\n * formatDuration({ years: 0, months: 9 }, { zero: true })\n * //=> '0 years 9 months'\n *\n * @example\n * // Customize the delimiter\n * formatDuration({ years: 2, months: 9, weeks: 3 }, { delimiter: ', ' })\n * //=> '2 years, 9 months, 3 weeks'\n */\nfunction formatDuration(duration, options) {\n const defaultOptions = (0, _index2.getDefaultOptions)();\n const locale =\n options?.locale ?? defaultOptions.locale ?? _index.defaultLocale;\n const format = options?.format ?? defaultFormat;\n const zero = options?.zero ?? false;\n const delimiter = options?.delimiter ?? \" \";\n\n if (!locale.formatDistance) {\n return \"\";\n }\n\n const result = format\n .reduce((acc, unit) => {\n const token = `x${unit.replace(/(^.)/, (m) => m.toUpperCase())}`;\n const value = duration[unit];\n if (value !== undefined && (zero || duration[unit])) {\n return acc.concat(locale.formatDistance(token, value));\n }\n return acc;\n }, [])\n .join(delimiter);\n\n return result;\n}\n", "\"use strict\";\nexports.formatISO = formatISO;\nvar _index = require(\"./_lib/addLeadingZeros.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link formatISO} function options.\n */\n\n/**\n * @name formatISO\n * @category Common Helpers\n * @summary Format the date according to the ISO 8601 standard (https://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a003169814.htm).\n *\n * @description\n * Return the formatted date string in ISO 8601 format. Options may be passed to control the parts and notations of the date.\n *\n * @param date - The original date\n * @param options - An object with options.\n *\n * @returns The formatted date string (in local time zone)\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 18 September 2019 in ISO 8601 format (local time zone is UTC):\n * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52))\n * //=> '2019-09-18T19:00:52Z'\n *\n * @example\n * // Represent 18 September 2019 in ISO 8601, short format (local time zone is UTC):\n * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52), { format: 'basic' })\n * //=> '20190918T190052'\n *\n * @example\n * // Represent 18 September 2019 in ISO 8601 format, date only:\n * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52), { representation: 'date' })\n * //=> '2019-09-18'\n *\n * @example\n * // Represent 18 September 2019 in ISO 8601 format, time only (local time zone is UTC):\n * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52), { representation: 'time' })\n * //=> '19:00:52Z'\n */\nfunction formatISO(date, options) {\n const date_ = (0, _index2.toDate)(date, options?.in);\n\n if (isNaN(+date_)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n const format = options?.format ?? \"extended\";\n const representation = options?.representation ?? \"complete\";\n\n let result = \"\";\n let tzOffset = \"\";\n\n const dateDelimiter = format === \"extended\" ? \"-\" : \"\";\n const timeDelimiter = format === \"extended\" ? \":\" : \"\";\n\n // Representation is either 'date' or 'complete'\n if (representation !== \"time\") {\n const day = (0, _index.addLeadingZeros)(date_.getDate(), 2);\n const month = (0, _index.addLeadingZeros)(date_.getMonth() + 1, 2);\n const year = (0, _index.addLeadingZeros)(date_.getFullYear(), 4);\n\n // yyyyMMdd or yyyy-MM-dd.\n result = `${year}${dateDelimiter}${month}${dateDelimiter}${day}`;\n }\n\n // Representation is either 'time' or 'complete'\n if (representation !== \"date\") {\n // Add the timezone.\n const offset = date_.getTimezoneOffset();\n\n if (offset !== 0) {\n const absoluteOffset = Math.abs(offset);\n const hourOffset = (0, _index.addLeadingZeros)(\n Math.trunc(absoluteOffset / 60),\n 2,\n );\n const minuteOffset = (0, _index.addLeadingZeros)(absoluteOffset % 60, 2);\n // If less than 0, the sign is +, because it is ahead of time.\n const sign = offset < 0 ? \"+\" : \"-\";\n\n tzOffset = `${sign}${hourOffset}:${minuteOffset}`;\n } else {\n tzOffset = \"Z\";\n }\n\n const hour = (0, _index.addLeadingZeros)(date_.getHours(), 2);\n const minute = (0, _index.addLeadingZeros)(date_.getMinutes(), 2);\n const second = (0, _index.addLeadingZeros)(date_.getSeconds(), 2);\n\n // If there's also date, separate it with time with 'T'\n const separator = result === \"\" ? \"\" : \"T\";\n\n // Creates a time string consisting of hour, minute, and second, separated by delimiters, if defined.\n const time = [hour, minute, second].join(timeDelimiter);\n\n // HHmmss or HH:mm:ss.\n result = `${result}${separator}${time}${tzOffset}`;\n }\n\n return result;\n}\n", "\"use strict\";\nexports.formatISO9075 = formatISO9075;\nvar _index = require(\"./_lib/addLeadingZeros.cjs\");\nvar _index2 = require(\"./isValid.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link formatISO9075} function options.\n */\n\n/**\n * @name formatISO9075\n * @category Common Helpers\n * @summary Format the date according to the ISO 9075 standard (https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_get-format).\n *\n * @description\n * Return the formatted date string in ISO 9075 format. Options may be passed to control the parts and notations of the date.\n *\n * @param date - The original date\n * @param options - An object with options.\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 18 September 2019 in ISO 9075 format:\n * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52))\n * //=> '2019-09-18 19:00:52'\n *\n * @example\n * // Represent 18 September 2019 in ISO 9075, short format:\n * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { format: 'basic' })\n * //=> '20190918 190052'\n *\n * @example\n * // Represent 18 September 2019 in ISO 9075 format, date only:\n * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { representation: 'date' })\n * //=> '2019-09-18'\n *\n * @example\n * // Represent 18 September 2019 in ISO 9075 format, time only:\n * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { representation: 'time' })\n * //=> '19:00:52'\n */\nfunction formatISO9075(date, options) {\n const date_ = (0, _index3.toDate)(date, options?.in);\n\n if (!(0, _index2.isValid)(date_)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n const format = options?.format ?? \"extended\";\n const representation = options?.representation ?? \"complete\";\n\n let result = \"\";\n\n const dateDelimiter = format === \"extended\" ? \"-\" : \"\";\n const timeDelimiter = format === \"extended\" ? \":\" : \"\";\n\n // Representation is either 'date' or 'complete'\n if (representation !== \"time\") {\n const day = (0, _index.addLeadingZeros)(date_.getDate(), 2);\n const month = (0, _index.addLeadingZeros)(date_.getMonth() + 1, 2);\n const year = (0, _index.addLeadingZeros)(date_.getFullYear(), 4);\n\n // yyyyMMdd or yyyy-MM-dd.\n result = `${year}${dateDelimiter}${month}${dateDelimiter}${day}`;\n }\n\n // Representation is either 'time' or 'complete'\n if (representation !== \"date\") {\n const hour = (0, _index.addLeadingZeros)(date_.getHours(), 2);\n const minute = (0, _index.addLeadingZeros)(date_.getMinutes(), 2);\n const second = (0, _index.addLeadingZeros)(date_.getSeconds(), 2);\n\n // If there's also date, separate it with time with a space\n const separator = result === \"\" ? \"\" : \" \";\n\n // HHmmss or HH:mm:ss.\n result = `${result}${separator}${hour}${timeDelimiter}${minute}${timeDelimiter}${second}`;\n }\n\n return result;\n}\n", "\"use strict\";\nexports.formatISODuration = formatISODuration;\n\n/**\n * @name formatISODuration\n * @category Common Helpers\n * @summary Format a duration object according as ISO 8601 duration string\n *\n * @description\n * Format a duration object according to the ISO 8601 duration standard (https://www.digi.com/resources/documentation/digidocs//90001488-13/reference/r_iso_8601_duration_format.htm)\n *\n * @param duration - The duration to format\n *\n * @returns The ISO 8601 duration string\n *\n * @example\n * // Format the given duration as ISO 8601 string\n * const result = formatISODuration({\n * years: 39,\n * months: 2,\n * days: 20,\n * hours: 7,\n * minutes: 5,\n * seconds: 0\n * })\n * //=> 'P39Y2M20DT0H0M0S'\n */\nfunction formatISODuration(duration) {\n const {\n years = 0,\n months = 0,\n days = 0,\n hours = 0,\n minutes = 0,\n seconds = 0,\n } = duration;\n\n return `P${years}Y${months}M${days}DT${hours}H${minutes}M${seconds}S`;\n}\n", "\"use strict\";\nexports.formatRFC3339 = formatRFC3339;\nvar _index = require(\"./_lib/addLeadingZeros.cjs\");\nvar _index2 = require(\"./isValid.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link formatRFC3339} function options.\n */\n\n/**\n * @name formatRFC3339\n * @category Common Helpers\n * @summary Format the date according to the RFC 3339 standard (https://tools.ietf.org/html/rfc3339#section-5.6).\n *\n * @description\n * Return the formatted date string in RFC 3339 format. Options may be passed to control the parts and notations of the date.\n *\n * @param date - The original date\n * @param options - An object with options.\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 18 September 2019 in RFC 3339 format:\n * formatRFC3339(new Date(2019, 8, 18, 19, 0, 52))\n * //=> '2019-09-18T19:00:52Z'\n *\n * @example\n * // Represent 18 September 2019 in RFC 3339 format, 3 digits of second fraction\n * formatRFC3339(new Date(2019, 8, 18, 19, 0, 52, 234), {\n * fractionDigits: 3\n * })\n * //=> '2019-09-18T19:00:52.234Z'\n */\nfunction formatRFC3339(date, options) {\n const date_ = (0, _index3.toDate)(date, options?.in);\n\n if (!(0, _index2.isValid)(date_)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n const fractionDigits = options?.fractionDigits ?? 0;\n\n const day = (0, _index.addLeadingZeros)(date_.getDate(), 2);\n const month = (0, _index.addLeadingZeros)(date_.getMonth() + 1, 2);\n const year = date_.getFullYear();\n\n const hour = (0, _index.addLeadingZeros)(date_.getHours(), 2);\n const minute = (0, _index.addLeadingZeros)(date_.getMinutes(), 2);\n const second = (0, _index.addLeadingZeros)(date_.getSeconds(), 2);\n\n let fractionalSecond = \"\";\n if (fractionDigits > 0) {\n const milliseconds = date_.getMilliseconds();\n const fractionalSeconds = Math.trunc(\n milliseconds * Math.pow(10, fractionDigits - 3),\n );\n fractionalSecond =\n \".\" + (0, _index.addLeadingZeros)(fractionalSeconds, fractionDigits);\n }\n\n let offset = \"\";\n const tzOffset = date_.getTimezoneOffset();\n\n if (tzOffset !== 0) {\n const absoluteOffset = Math.abs(tzOffset);\n const hourOffset = (0, _index.addLeadingZeros)(\n Math.trunc(absoluteOffset / 60),\n 2,\n );\n const minuteOffset = (0, _index.addLeadingZeros)(absoluteOffset % 60, 2);\n // If less than 0, the sign is +, because it is ahead of time.\n const sign = tzOffset < 0 ? \"+\" : \"-\";\n\n offset = `${sign}${hourOffset}:${minuteOffset}`;\n } else {\n offset = \"Z\";\n }\n\n return `${year}-${month}-${day}T${hour}:${minute}:${second}${fractionalSecond}${offset}`;\n}\n", "\"use strict\";\nexports.formatRFC7231 = formatRFC7231;\nvar _index = require(\"./_lib/addLeadingZeros.cjs\");\nvar _index2 = require(\"./isValid.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\nconst days = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n\nconst months = [\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n];\n\n/**\n * @name formatRFC7231\n * @category Common Helpers\n * @summary Format the date according to the RFC 7231 standard (https://tools.ietf.org/html/rfc7231#section-7.1.1.1).\n *\n * @description\n * Return the formatted date string in RFC 7231 format.\n * The result will always be in UTC timezone.\n *\n * @param date - The original date\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 18 September 2019 in RFC 7231 format:\n * const result = formatRFC7231(new Date(2019, 8, 18, 19, 0, 52))\n * //=> 'Wed, 18 Sep 2019 19:00:52 GMT'\n */\nfunction formatRFC7231(date) {\n const _date = (0, _index3.toDate)(date);\n\n if (!(0, _index2.isValid)(_date)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n const dayName = days[_date.getUTCDay()];\n const dayOfMonth = (0, _index.addLeadingZeros)(_date.getUTCDate(), 2);\n const monthName = months[_date.getUTCMonth()];\n const year = _date.getUTCFullYear();\n\n const hour = (0, _index.addLeadingZeros)(_date.getUTCHours(), 2);\n const minute = (0, _index.addLeadingZeros)(_date.getUTCMinutes(), 2);\n const second = (0, _index.addLeadingZeros)(_date.getUTCSeconds(), 2);\n\n // Result variables.\n return `${dayName}, ${dayOfMonth} ${monthName} ${year} ${hour}:${minute}:${second} GMT`;\n}\n", "\"use strict\";\nexports.formatRelative = formatRelative;\nvar _index = require(\"./_lib/defaultLocale.cjs\");\nvar _index2 = require(\"./_lib/defaultOptions.cjs\");\nvar _index3 = require(\"./_lib/normalizeDates.cjs\");\nvar _index4 = require(\"./differenceInCalendarDays.cjs\");\nvar _index5 = require(\"./format.cjs\");\n\n/**\n * The {@link formatRelative} function options.\n */\n\n/**\n * @name formatRelative\n * @category Common Helpers\n * @summary Represent the date in words relative to the given base date.\n *\n * @description\n * Represent the date in words relative to the given base date.\n *\n * | Distance to the base date | Result |\n * |---------------------------|---------------------------|\n * | Previous 6 days | last Sunday at 04:30 AM |\n * | Last day | yesterday at 04:30 AM |\n * | Same day | today at 04:30 AM |\n * | Next day | tomorrow at 04:30 AM |\n * | Next 6 days | Sunday at 04:30 AM |\n * | Other | 12/31/2017 |\n *\n * @param date - The date to format\n * @param baseDate - The date to compare with\n * @param options - An object with options\n *\n * @returns The date in words\n *\n * @throws `date` must not be Invalid Date\n * @throws `baseDate` must not be Invalid Date\n * @throws `options.locale` must contain `localize` property\n * @throws `options.locale` must contain `formatLong` property\n * @throws `options.locale` must contain `formatRelative` property\n *\n * @example\n * // Represent the date of 6 days ago in words relative to the given base date. In this example, today is Wednesday\n * const result = formatRelative(subDays(new Date(), 6), new Date())\n * //=> \"last Thursday at 12:45 AM\"\n */\nfunction formatRelative(date, baseDate, options) {\n const [date_, baseDate_] = (0, _index3.normalizeDates)(\n options?.in,\n date,\n baseDate,\n );\n\n const defaultOptions = (0, _index2.getDefaultOptions)();\n const locale =\n options?.locale ?? defaultOptions.locale ?? _index.defaultLocale;\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const diff = (0, _index4.differenceInCalendarDays)(date_, baseDate_);\n\n if (isNaN(diff)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n let token;\n if (diff < -6) {\n token = \"other\";\n } else if (diff < -1) {\n token = \"lastWeek\";\n } else if (diff < 0) {\n token = \"yesterday\";\n } else if (diff < 1) {\n token = \"today\";\n } else if (diff < 2) {\n token = \"tomorrow\";\n } else if (diff < 7) {\n token = \"nextWeek\";\n } else {\n token = \"other\";\n }\n\n const formatStr = locale.formatRelative(token, date_, baseDate_, {\n locale,\n weekStartsOn,\n });\n return (0, _index5.format)(date_, formatStr, { locale, weekStartsOn });\n}\n", "\"use strict\";\nexports.fromUnixTime = fromUnixTime;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link fromUnixTime} function options.\n */\n\n/**\n * @name fromUnixTime\n * @category Timestamp Helpers\n * @summary Create a date from a Unix timestamp.\n *\n * @description\n * Create a date from a Unix timestamp (in seconds). Decimal values will be discarded.\n *\n * @param unixTime - The given Unix timestamp (in seconds)\n * @param options - An object with options. Allows to pass a context.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n *\n * @returns The date\n *\n * @example\n * // Create the date 29 February 2012 11:45:05:\n * const result = fromUnixTime(1330515905)\n * //=> Wed Feb 29 2012 11:45:05\n */\nfunction fromUnixTime(unixTime, options) {\n return (0, _index.toDate)(unixTime * 1000, options?.in);\n}\n", "\"use strict\";\nexports.getDate = getDate;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getDate} function options.\n */\n\n/**\n * @name getDate\n * @category Day Helpers\n * @summary Get the day of the month of the given date.\n *\n * @description\n * Get the day of the month of the given date.\n *\n * @param date - The given date\n * @param options - An object with options.\n *\n * @returns The day of month\n *\n * @example\n * // Which day of the month is 29 February 2012?\n * const result = getDate(new Date(2012, 1, 29))\n * //=> 29\n */\nfunction getDate(date, options) {\n return (0, _index.toDate)(date, options?.in).getDate();\n}\n", "\"use strict\";\nexports.getDay = getDay;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getDay} function options.\n */\n\n/**\n * @name getDay\n * @category Weekday Helpers\n * @summary Get the day of the week of the given date.\n *\n * @description\n * Get the day of the week of the given date.\n *\n * @param date - The given date\n * @param options - The options\n *\n * @returns The day of week, 0 represents Sunday\n *\n * @example\n * // Which day of the week is 29 February 2012?\n * const result = getDay(new Date(2012, 1, 29))\n * //=> 3\n */\nfunction getDay(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay();\n}\n", "\"use strict\";\nexports.getDaysInMonth = getDaysInMonth;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getDaysInMonth} function options.\n */\n\n/**\n * @name getDaysInMonth\n * @category Month Helpers\n * @summary Get the number of days in a month of the given date.\n *\n * @description\n * Get the number of days in a month of the given date, considering the context if provided.\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The number of days in a month\n *\n * @example\n * // How many days are in February 2000?\n * const result = getDaysInMonth(new Date(2000, 1))\n * //=> 29\n */\nfunction getDaysInMonth(date, options) {\n const _date = (0, _index2.toDate)(date, options?.in);\n const year = _date.getFullYear();\n const monthIndex = _date.getMonth();\n const lastDayOfMonth = (0, _index.constructFrom)(_date, 0);\n lastDayOfMonth.setFullYear(year, monthIndex + 1, 0);\n lastDayOfMonth.setHours(0, 0, 0, 0);\n return lastDayOfMonth.getDate();\n}\n", "\"use strict\";\nexports.isLeapYear = isLeapYear;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name isLeapYear\n * @category Year Helpers\n * @summary Is the given date in the leap year?\n *\n * @description\n * Is the given date in the leap year?\n *\n * @param date - The date to check\n * @param options - The options object\n *\n * @returns The date is in the leap year\n *\n * @example\n * // Is 1 September 2012 in the leap year?\n * const result = isLeapYear(new Date(2012, 8, 1))\n * //=> true\n */\nfunction isLeapYear(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const year = _date.getFullYear();\n return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);\n}\n", "\"use strict\";\nexports.getDaysInYear = getDaysInYear;\nvar _index = require(\"./isLeapYear.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getDaysInYear} function options.\n */\n\n/**\n * @name getDaysInYear\n * @category Year Helpers\n * @summary Get the number of days in a year of the given date.\n *\n * @description\n * Get the number of days in a year of the given date.\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The number of days in a year\n *\n * @example\n * // How many days are in 2012?\n * const result = getDaysInYear(new Date(2012, 0, 1))\n * //=> 366\n */\nfunction getDaysInYear(date, options) {\n const _date = (0, _index2.toDate)(date, options?.in);\n if (Number.isNaN(+_date)) return NaN;\n return (0, _index.isLeapYear)(_date) ? 366 : 365;\n}\n", "\"use strict\";\nexports.getDecade = getDecade;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getDecade} function options.\n */\n\n/**\n * @name getDecade\n * @category Decade Helpers\n * @summary Get the decade of the given date.\n *\n * @description\n * Get the decade of the given date.\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The year of decade\n *\n * @example\n * // Which decade belongs 27 November 1942?\n * const result = getDecade(new Date(1942, 10, 27))\n * //=> 1940\n */\nfunction getDecade(date, options) {\n // TODO: Switch to more technical definition in of decades that start with 1\n // end with 0. I.e. 2001-2010 instead of current 2000-2009. It's a breaking\n // change, so it can only be done in 4.0.\n const _date = (0, _index.toDate)(date, options?.in);\n const year = _date.getFullYear();\n const decade = Math.floor(year / 10) * 10;\n return decade;\n}\n", "\"use strict\";\nexports.getDefaultOptions = getDefaultOptions;\n\nvar _index = require(\"./_lib/defaultOptions.cjs\");\n\n/**\n * @name getDefaultOptions\n * @category Common Helpers\n * @summary Get default options.\n * @pure false\n *\n * @description\n * Returns an object that contains defaults for\n * `options.locale`, `options.weekStartsOn` and `options.firstWeekContainsDate`\n * arguments for all functions.\n *\n * You can change these with [setDefaultOptions](https://date-fns.org/docs/setDefaultOptions).\n *\n * @returns The default options\n *\n * @example\n * const result = getDefaultOptions()\n * //=> {}\n *\n * @example\n * setDefaultOptions({ weekStarsOn: 1, firstWeekContainsDate: 4 })\n * const result = getDefaultOptions()\n * //=> { weekStarsOn: 1, firstWeekContainsDate: 4 }\n */\nfunction getDefaultOptions() {\n return Object.assign({}, (0, _index.getDefaultOptions)());\n}\n", "\"use strict\";\nexports.getHours = getHours;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getHours} function options.\n */\n\n/**\n * @name getHours\n * @category Hour Helpers\n * @summary Get the hours of the given date.\n *\n * @description\n * Get the hours of the given date.\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The hours\n *\n * @example\n * // Get the hours of 29 February 2012 11:45:00:\n * const result = getHours(new Date(2012, 1, 29, 11, 45))\n * //=> 11\n */\nfunction getHours(date, options) {\n return (0, _index.toDate)(date, options?.in).getHours();\n}\n", "\"use strict\";\nexports.getISODay = getISODay;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getISODay} function options.\n */\n\n/**\n * @name getISODay\n * @category Weekday Helpers\n * @summary Get the day of the ISO week of the given date.\n *\n * @description\n * Get the day of the ISO week of the given date,\n * which is 7 for Sunday, 1 for Monday etc.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The day of ISO week\n *\n * @example\n * // Which day of the ISO week is 26 February 2012?\n * const result = getISODay(new Date(2012, 1, 26))\n * //=> 7\n */\nfunction getISODay(date, options) {\n const day = (0, _index.toDate)(date, options?.in).getDay();\n return day === 0 ? 7 : day;\n}\n", "\"use strict\";\nexports.getISOWeeksInYear = getISOWeeksInYear;\nvar _index = require(\"./addWeeks.cjs\");\nvar _index2 = require(\"./constants.cjs\");\nvar _index3 = require(\"./startOfISOWeekYear.cjs\");\n\n/**\n * The {@link getISOWeeksInYear} function options.\n */\n\n/**\n * @name getISOWeeksInYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Get the number of weeks in an ISO week-numbering year of the given date.\n *\n * @description\n * Get the number of weeks in an ISO week-numbering year of the given date.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The number of ISO weeks in a year\n *\n * @example\n * // How many weeks are in ISO week-numbering year 2015?\n * const result = getISOWeeksInYear(new Date(2015, 1, 11))\n * //=> 53\n */\nfunction getISOWeeksInYear(date, options) {\n const thisYear = (0, _index3.startOfISOWeekYear)(date, options);\n const nextYear = (0, _index3.startOfISOWeekYear)(\n (0, _index.addWeeks)(thisYear, 60),\n );\n const diff = +nextYear - +thisYear;\n\n // Round the number of weeks to the nearest integer because the number of\n // milliseconds in a week is not constant (e.g. it's different in the week of\n // the daylight saving time clock shift).\n return Math.round(diff / _index2.millisecondsInWeek);\n}\n", "\"use strict\";\nexports.getMilliseconds = getMilliseconds;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name getMilliseconds\n * @category Millisecond Helpers\n * @summary Get the milliseconds of the given date.\n *\n * @description\n * Get the milliseconds of the given date.\n *\n * @param date - The given date\n *\n * @returns The milliseconds\n *\n * @example\n * // Get the milliseconds of 29 February 2012 11:45:05.123:\n * const result = getMilliseconds(new Date(2012, 1, 29, 11, 45, 5, 123))\n * //=> 123\n */\nfunction getMilliseconds(date) {\n return (0, _index.toDate)(date).getMilliseconds();\n}\n", "\"use strict\";\nexports.getMinutes = getMinutes;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getMinutes} function options.\n */\n\n/**\n * @name getMinutes\n * @category Minute Helpers\n * @summary Get the minutes of the given date.\n *\n * @description\n * Get the minutes of the given date.\n *\n * @param date - The given date\n * @param options - The options\n *\n * @returns The minutes\n *\n * @example\n * // Get the minutes of 29 February 2012 11:45:05:\n * const result = getMinutes(new Date(2012, 1, 29, 11, 45, 5))\n * //=> 45\n */\nfunction getMinutes(date, options) {\n return (0, _index.toDate)(date, options?.in).getMinutes();\n}\n", "\"use strict\";\nexports.getMonth = getMonth;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getMonth} function options.\n */\n\n/**\n * @name getMonth\n * @category Month Helpers\n * @summary Get the month of the given date.\n *\n * @description\n * Get the month of the given date.\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The month index (0-11)\n *\n * @example\n * // Which month is 29 February 2012?\n * const result = getMonth(new Date(2012, 1, 29))\n * //=> 1\n */\nfunction getMonth(date, options) {\n return (0, _index.toDate)(date, options?.in).getMonth();\n}\n", "\"use strict\";\nexports.getOverlappingDaysInIntervals = getOverlappingDaysInIntervals;\nvar _index = require(\"./_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _index2 = require(\"./constants.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * @name getOverlappingDaysInIntervals\n * @category Interval Helpers\n * @summary Get the number of days that overlap in two time intervals\n *\n * @description\n * Get the number of days that overlap in two time intervals. It uses the time\n * between dates to calculate the number of days, rounding it up to include\n * partial days.\n *\n * Two equal 0-length intervals will result in 0. Two equal 1ms intervals will\n * result in 1.\n *\n * @param intervalLeft - The first interval to compare.\n * @param intervalRight - The second interval to compare.\n * @param options - An object with options\n *\n * @returns The number of days that overlap in two time intervals\n *\n * @example\n * // For overlapping time intervals adds 1 for each started overlapping day:\n * getOverlappingDaysInIntervals(\n * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },\n * { start: new Date(2014, 0, 17), end: new Date(2014, 0, 21) }\n * )\n * //=> 3\n *\n * @example\n * // For non-overlapping time intervals returns 0:\n * getOverlappingDaysInIntervals(\n * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },\n * { start: new Date(2014, 0, 21), end: new Date(2014, 0, 22) }\n * )\n * //=> 0\n */\n\nfunction getOverlappingDaysInIntervals(intervalLeft, intervalRight) {\n const [leftStart, leftEnd] = [\n +(0, _index3.toDate)(intervalLeft.start),\n +(0, _index3.toDate)(intervalLeft.end),\n ].sort((a, b) => a - b);\n const [rightStart, rightEnd] = [\n +(0, _index3.toDate)(intervalRight.start),\n +(0, _index3.toDate)(intervalRight.end),\n ].sort((a, b) => a - b);\n\n // Prevent NaN result if intervals don't overlap at all.\n const isOverlapping = leftStart < rightEnd && rightStart < leftEnd;\n if (!isOverlapping) return 0;\n\n // Remove the timezone offset to negate the DST effect on calculations.\n const overlapLeft = rightStart < leftStart ? leftStart : rightStart;\n const left =\n overlapLeft - (0, _index.getTimezoneOffsetInMilliseconds)(overlapLeft);\n const overlapRight = rightEnd > leftEnd ? leftEnd : rightEnd;\n const right =\n overlapRight - (0, _index.getTimezoneOffsetInMilliseconds)(overlapRight);\n\n // Ceil the number to include partial days too.\n return Math.ceil((right - left) / _index2.millisecondsInDay);\n}\n", "\"use strict\";\nexports.getSeconds = getSeconds;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name getSeconds\n * @category Second Helpers\n * @summary Get the seconds of the given date.\n *\n * @description\n * Get the seconds of the given date.\n *\n * @param date - The given date\n *\n * @returns The seconds\n *\n * @example\n * // Get the seconds of 29 February 2012 11:45:05.123:\n * const result = getSeconds(new Date(2012, 1, 29, 11, 45, 5, 123))\n * //=> 5\n */\nfunction getSeconds(date) {\n return (0, _index.toDate)(date).getSeconds();\n}\n", "\"use strict\";\nexports.getTime = getTime;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name getTime\n * @category Timestamp Helpers\n * @summary Get the milliseconds timestamp of the given date.\n *\n * @description\n * Get the milliseconds timestamp of the given date.\n *\n * @param date - The given date\n *\n * @returns The timestamp\n *\n * @example\n * // Get the timestamp of 29 February 2012 11:45:05.123:\n * const result = getTime(new Date(2012, 1, 29, 11, 45, 5, 123))\n * //=> 1330515905123\n */\nfunction getTime(date) {\n return +(0, _index.toDate)(date);\n}\n", "\"use strict\";\nexports.getUnixTime = getUnixTime;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name getUnixTime\n * @category Timestamp Helpers\n * @summary Get the seconds timestamp of the given date.\n *\n * @description\n * Get the seconds timestamp of the given date.\n *\n * @param date - The given date\n *\n * @returns The timestamp\n *\n * @example\n * // Get the timestamp of 29 February 2012 11:45:05 CET:\n * const result = getUnixTime(new Date(2012, 1, 29, 11, 45, 5))\n * //=> 1330512305\n */\nfunction getUnixTime(date) {\n return Math.trunc(+(0, _index.toDate)(date) / 1000);\n}\n", "\"use strict\";\nexports.getWeekOfMonth = getWeekOfMonth;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./getDate.cjs\");\nvar _index3 = require(\"./getDay.cjs\");\nvar _index4 = require(\"./startOfMonth.cjs\");\nvar _index5 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getWeekOfMonth} function options.\n */\n\n/**\n * @name getWeekOfMonth\n * @category Week Helpers\n * @summary Get the week of the month of the given date.\n *\n * @description\n * Get the week of the month of the given date.\n *\n * @param date - The given date\n * @param options - An object with options.\n *\n * @returns The week of month\n *\n * @example\n * // Which week of the month is 9 November 2017?\n * const result = getWeekOfMonth(new Date(2017, 10, 9))\n * //=> 2\n */\nfunction getWeekOfMonth(date, options) {\n const defaultOptions = (0, _index.getDefaultOptions)();\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const currentDayOfMonth = (0, _index2.getDate)(\n (0, _index5.toDate)(date, options?.in),\n );\n if (isNaN(currentDayOfMonth)) return NaN;\n\n const startWeekDay = (0, _index3.getDay)(\n (0, _index4.startOfMonth)(date, options),\n );\n\n let lastDayOfFirstWeek = weekStartsOn - startWeekDay;\n if (lastDayOfFirstWeek <= 0) lastDayOfFirstWeek += 7;\n\n const remainingDaysAfterFirstWeek = currentDayOfMonth - lastDayOfFirstWeek;\n return Math.ceil(remainingDaysAfterFirstWeek / 7) + 1;\n}\n", "\"use strict\";\nexports.lastDayOfMonth = lastDayOfMonth;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link lastDayOfMonth} function options.\n */\n\n/**\n * @name lastDayOfMonth\n * @category Month Helpers\n * @summary Return the last day of a month for the given date.\n *\n * @description\n * Return the last day of a month for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The last day of a month\n *\n * @example\n * // The last day of a month for 2 September 2014 11:55:00:\n * const result = lastDayOfMonth(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 30 2014 00:00:00\n */\nfunction lastDayOfMonth(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const month = _date.getMonth();\n _date.setFullYear(_date.getFullYear(), month + 1, 0);\n _date.setHours(0, 0, 0, 0);\n return (0, _index.toDate)(_date, options?.in);\n}\n", "\"use strict\";\nexports.getWeeksInMonth = getWeeksInMonth;\nvar _index = require(\"./differenceInCalendarWeeks.cjs\");\nvar _index2 = require(\"./lastDayOfMonth.cjs\");\nvar _index3 = require(\"./startOfMonth.cjs\");\nvar _index4 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getWeeksInMonth} function options.\n */\n\n/**\n * @name getWeeksInMonth\n * @category Week Helpers\n * @summary Get the number of calendar weeks a month spans.\n *\n * @description\n * Get the number of calendar weeks the month in the given date spans.\n *\n * @param date - The given date\n * @param options - An object with options.\n *\n * @returns The number of calendar weeks\n *\n * @example\n * // How many calendar weeks does February 2015 span?\n * const result = getWeeksInMonth(new Date(2015, 1, 8))\n * //=> 4\n *\n * @example\n * // If the week starts on Monday,\n * // how many calendar weeks does July 2017 span?\n * const result = getWeeksInMonth(new Date(2017, 6, 5), { weekStartsOn: 1 })\n * //=> 6\n */\nfunction getWeeksInMonth(date, options) {\n const contextDate = (0, _index4.toDate)(date, options?.in);\n return (\n (0, _index.differenceInCalendarWeeks)(\n (0, _index2.lastDayOfMonth)(contextDate, options),\n (0, _index3.startOfMonth)(contextDate, options),\n options,\n ) + 1\n );\n}\n", "\"use strict\";\nexports.getYear = getYear;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getYear} function options.\n */\n\n/**\n * @name getYear\n * @category Year Helpers\n * @summary Get the year of the given date.\n *\n * @description\n * Get the year of the given date.\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The year\n *\n * @example\n * // Which year is 2 July 2014?\n * const result = getYear(new Date(2014, 6, 2))\n * //=> 2014\n */\nfunction getYear(date, options) {\n return (0, _index.toDate)(date, options?.in).getFullYear();\n}\n", "\"use strict\";\nexports.hoursToMilliseconds = hoursToMilliseconds;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name hoursToMilliseconds\n * @category Conversion Helpers\n * @summary Convert hours to milliseconds.\n *\n * @description\n * Convert a number of hours to a full number of milliseconds.\n *\n * @param hours - number of hours to be converted\n *\n * @returns The number of hours converted to milliseconds\n *\n * @example\n * // Convert 2 hours to milliseconds:\n * const result = hoursToMilliseconds(2)\n * //=> 7200000\n */\nfunction hoursToMilliseconds(hours) {\n return Math.trunc(hours * _index.millisecondsInHour);\n}\n", "\"use strict\";\nexports.hoursToMinutes = hoursToMinutes;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name hoursToMinutes\n * @category Conversion Helpers\n * @summary Convert hours to minutes.\n *\n * @description\n * Convert a number of hours to a full number of minutes.\n *\n * @param hours - number of hours to be converted\n *\n * @returns The number of hours converted in minutes\n *\n * @example\n * // Convert 2 hours to minutes:\n * const result = hoursToMinutes(2)\n * //=> 120\n */\nfunction hoursToMinutes(hours) {\n return Math.trunc(hours * _index.minutesInHour);\n}\n", "\"use strict\";\nexports.hoursToSeconds = hoursToSeconds;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name hoursToSeconds\n * @category Conversion Helpers\n * @summary Convert hours to seconds.\n *\n * @description\n * Convert a number of hours to a full number of seconds.\n *\n * @param hours - The number of hours to be converted\n *\n * @returns The number of hours converted in seconds\n *\n * @example\n * // Convert 2 hours to seconds:\n * const result = hoursToSeconds(2)\n * //=> 7200\n */\nfunction hoursToSeconds(hours) {\n return Math.trunc(hours * _index.secondsInHour);\n}\n", "\"use strict\";\nexports.interval = interval;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\n\n/**\n * The {@link interval} function options.\n */\n\n/**\n * The {@link interval} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the start argument,\n * then the end interval date. If a context function is passed, it uses the context\n * function return type.\n */\n\n/**\n * @name interval\n * @category Interval Helpers\n * @summary Creates an interval object and validates its values.\n *\n * @description\n * Creates a normalized interval object and validates its values. If the interval is invalid, an exception is thrown.\n *\n * @typeParam StartDate - Start date type.\n * @typeParam EndDate - End date type.\n * @typeParam Options - Options type.\n *\n * @param start - The start of the interval.\n * @param end - The end of the interval.\n * @param options - The options object.\n *\n * @throws `Start date is invalid` when `start` is invalid.\n * @throws `End date is invalid` when `end` is invalid.\n * @throws `End date must be after start date` when end is before `start` and `options.assertPositive` is true.\n *\n * @returns The normalized and validated interval object.\n */\nfunction interval(start, end, options) {\n const [_start, _end] = (0, _index.normalizeDates)(options?.in, start, end);\n\n if (isNaN(+_start)) throw new TypeError(\"Start date is invalid\");\n if (isNaN(+_end)) throw new TypeError(\"End date is invalid\");\n\n if (options?.assertPositive && +_start > +_end)\n throw new TypeError(\"End date must be after start date\");\n\n return { start: _start, end: _end };\n}\n", "\"use strict\";\nexports.intervalToDuration = intervalToDuration;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./add.cjs\");\nvar _index3 = require(\"./differenceInDays.cjs\");\nvar _index4 = require(\"./differenceInHours.cjs\");\nvar _index5 = require(\"./differenceInMinutes.cjs\");\nvar _index6 = require(\"./differenceInMonths.cjs\");\nvar _index7 = require(\"./differenceInSeconds.cjs\");\nvar _index8 = require(\"./differenceInYears.cjs\");\n\n/**\n * The {@link intervalToDuration} function options.\n */\n\n/**\n * @name intervalToDuration\n * @category Common Helpers\n * @summary Convert interval to duration\n *\n * @description\n * Convert an interval object to a duration object.\n *\n * @param interval - The interval to convert to duration\n * @param options - The context options\n *\n * @returns The duration object\n *\n * @example\n * // Get the duration between January 15, 1929 and April 4, 1968.\n * intervalToDuration({\n * start: new Date(1929, 0, 15, 12, 0, 0),\n * end: new Date(1968, 3, 4, 19, 5, 0)\n * });\n * //=> { years: 39, months: 2, days: 20, hours: 7, minutes: 5, seconds: 0 }\n */\nfunction intervalToDuration(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n const duration = {};\n\n const years = (0, _index8.differenceInYears)(end, start);\n if (years) duration.years = years;\n\n const remainingMonths = (0, _index2.add)(start, { years: duration.years });\n const months = (0, _index6.differenceInMonths)(end, remainingMonths);\n if (months) duration.months = months;\n\n const remainingDays = (0, _index2.add)(remainingMonths, {\n months: duration.months,\n });\n const days = (0, _index3.differenceInDays)(end, remainingDays);\n if (days) duration.days = days;\n\n const remainingHours = (0, _index2.add)(remainingDays, {\n days: duration.days,\n });\n const hours = (0, _index4.differenceInHours)(end, remainingHours);\n if (hours) duration.hours = hours;\n\n const remainingMinutes = (0, _index2.add)(remainingHours, {\n hours: duration.hours,\n });\n const minutes = (0, _index5.differenceInMinutes)(end, remainingMinutes);\n if (minutes) duration.minutes = minutes;\n\n const remainingSeconds = (0, _index2.add)(remainingMinutes, {\n minutes: duration.minutes,\n });\n const seconds = (0, _index7.differenceInSeconds)(end, remainingSeconds);\n if (seconds) duration.seconds = seconds;\n\n return duration;\n}\n", "\"use strict\";\nexports.intlFormat = intlFormat;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The locale string (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).\n * @deprecated\n *\n * [TODO] Remove in v4\n */\n\n/**\n * The format options (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options)\n */\n\n/**\n * The locale options.\n */\n\n/**\n * @name intlFormat\n * @category Common Helpers\n * @summary Format the date with Intl.DateTimeFormat (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat).\n *\n * @description\n * Return the formatted date string in the given format.\n * The method uses [`Intl.DateTimeFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) inside.\n * formatOptions are the same as [`Intl.DateTimeFormat` options](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat#using_options)\n *\n * > \u26A0\uFE0F Please note that before Node version 13.0.0, only the locale data for en-US is available by default.\n *\n * @param date - The date to format\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 4 October 2019 in middle-endian format:\n * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456))\n * //=> 10/4/2019\n */\n\n/**\n * @param date - The date to format\n * @param localeOptions - An object with locale\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 4 October 2019 in Korean.\n * // Convert the date with locale's options.\n * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456), {\n * locale: 'ko-KR',\n * })\n * //=> 2019. 10. 4.\n */\n\n/**\n * @param date - The date to format\n * @param formatOptions - The format options\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 4 October 2019.\n * // Convert the date with format's options.\n * const result = intlFormat.default(new Date(2019, 9, 4, 12, 30, 13, 456), {\n * year: 'numeric',\n * month: 'numeric',\n * day: 'numeric',\n * hour: 'numeric',\n * })\n * //=> 10/4/2019, 12 PM\n */\n\n/**\n * @param date - The date to format\n * @param formatOptions - The format options\n * @param localeOptions - An object with locale\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 4 October 2019 in German.\n * // Convert the date with format's options and locale's options.\n * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456), {\n * weekday: 'long',\n * year: 'numeric',\n * month: 'long',\n * day: 'numeric',\n * }, {\n * locale: 'de-DE',\n * })\n * //=> Freitag, 4. Oktober 2019\n */\n\nfunction intlFormat(date, formatOrLocale, localeOptions) {\n let formatOptions;\n\n if (isFormatOptions(formatOrLocale)) {\n formatOptions = formatOrLocale;\n } else {\n localeOptions = formatOrLocale;\n }\n\n return new Intl.DateTimeFormat(localeOptions?.locale, formatOptions).format(\n (0, _index.toDate)(date),\n );\n}\n\nfunction isFormatOptions(opts) {\n return opts !== undefined && !(\"locale\" in opts);\n}\n", "\"use strict\";\nexports.intlFormatDistance = intlFormatDistance;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./constants.cjs\");\n\nvar _index3 = require(\"./differenceInCalendarDays.cjs\");\nvar _index4 = require(\"./differenceInCalendarMonths.cjs\");\nvar _index5 = require(\"./differenceInCalendarQuarters.cjs\");\nvar _index6 = require(\"./differenceInCalendarWeeks.cjs\");\nvar _index7 = require(\"./differenceInCalendarYears.cjs\");\nvar _index8 = require(\"./differenceInHours.cjs\");\nvar _index9 = require(\"./differenceInMinutes.cjs\");\nvar _index10 = require(\"./differenceInSeconds.cjs\");\n\n/**\n * The {@link intlFormatDistance} function options.\n */\n\n/**\n * The unit used to format the distance in {@link intlFormatDistance}.\n */\n\n/**\n * @name intlFormatDistance\n * @category Common Helpers\n * @summary Formats distance between two dates in a human-readable format\n * @description\n * The function calculates the difference between two dates and formats it as a human-readable string.\n *\n * The function will pick the most appropriate unit depending on the distance between dates. For example, if the distance is a few hours, it might return `x hours`. If the distance is a few months, it might return `x months`.\n *\n * You can also specify a unit to force using it regardless of the distance to get a result like `123456 hours`.\n *\n * See the table below for the unit picking logic:\n *\n * | Distance between dates | Result (past) | Result (future) |\n * | ---------------------- | -------------- | --------------- |\n * | 0 seconds | now | now |\n * | 1-59 seconds | X seconds ago | in X seconds |\n * | 1-59 minutes | X minutes ago | in X minutes |\n * | 1-23 hours | X hours ago | in X hours |\n * | 1 day | yesterday | tomorrow |\n * | 2-6 days | X days ago | in X days |\n * | 7 days | last week | next week |\n * | 8 days-1 month | X weeks ago | in X weeks |\n * | 1 month | last month | next month |\n * | 2-3 months | X months ago | in X months |\n * | 1 quarter | last quarter | next quarter |\n * | 2-3 quarters | X quarters ago | in X quarters |\n * | 1 year | last year | next year |\n * | 2+ years | X years ago | in X years |\n *\n * @param laterDate - The date\n * @param earlierDate - The date to compare with.\n * @param options - An object with options.\n * See MDN for details [Locale identification and negotiation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation)\n * The narrow one could be similar to the short one for some locales.\n *\n * @returns The distance in words according to language-sensitive relative time formatting.\n *\n * @throws `date` must not be Invalid Date\n * @throws `baseDate` must not be Invalid Date\n * @throws `options.unit` must not be invalid Unit\n * @throws `options.locale` must not be invalid locale\n * @throws `options.localeMatcher` must not be invalid localeMatcher\n * @throws `options.numeric` must not be invalid numeric\n * @throws `options.style` must not be invalid style\n *\n * @example\n * // What is the distance between the dates when the fist date is after the second?\n * intlFormatDistance(\n * new Date(1986, 3, 4, 11, 30, 0),\n * new Date(1986, 3, 4, 10, 30, 0)\n * )\n * //=> 'in 1 hour'\n *\n * // What is the distance between the dates when the fist date is before the second?\n * intlFormatDistance(\n * new Date(1986, 3, 4, 10, 30, 0),\n * new Date(1986, 3, 4, 11, 30, 0)\n * )\n * //=> '1 hour ago'\n *\n * @example\n * // Use the unit option to force the function to output the result in quarters. Without setting it, the example would return \"next year\"\n * intlFormatDistance(\n * new Date(1987, 6, 4, 10, 30, 0),\n * new Date(1986, 3, 4, 10, 30, 0),\n * { unit: 'quarter' }\n * )\n * //=> 'in 5 quarters'\n *\n * @example\n * // Use the locale option to get the result in Spanish. Without setting it, the example would return \"in 1 hour\".\n * intlFormatDistance(\n * new Date(1986, 3, 4, 11, 30, 0),\n * new Date(1986, 3, 4, 10, 30, 0),\n * { locale: 'es' }\n * )\n * //=> 'dentro de 1 hora'\n *\n * @example\n * // Use the numeric option to force the function to use numeric values. Without setting it, the example would return \"tomorrow\".\n * intlFormatDistance(\n * new Date(1986, 3, 5, 11, 30, 0),\n * new Date(1986, 3, 4, 11, 30, 0),\n * { numeric: 'always' }\n * )\n * //=> 'in 1 day'\n *\n * @example\n * // Use the style option to force the function to use short values. Without setting it, the example would return \"in 2 years\".\n * intlFormatDistance(\n * new Date(1988, 3, 4, 11, 30, 0),\n * new Date(1986, 3, 4, 11, 30, 0),\n * { style: 'short' }\n * )\n * //=> 'in 2 yr'\n */\nfunction intlFormatDistance(laterDate, earlierDate, options) {\n let value = 0;\n let unit;\n\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n if (!options?.unit) {\n // Get the unit based on diffInSeconds calculations if no unit is specified\n const diffInSeconds = (0, _index10.differenceInSeconds)(\n laterDate_,\n earlierDate_,\n ); // The smallest unit\n\n if (Math.abs(diffInSeconds) < _index2.secondsInMinute) {\n value = (0, _index10.differenceInSeconds)(laterDate_, earlierDate_);\n unit = \"second\";\n } else if (Math.abs(diffInSeconds) < _index2.secondsInHour) {\n value = (0, _index9.differenceInMinutes)(laterDate_, earlierDate_);\n unit = \"minute\";\n } else if (\n Math.abs(diffInSeconds) < _index2.secondsInDay &&\n Math.abs(\n (0, _index3.differenceInCalendarDays)(laterDate_, earlierDate_),\n ) < 1\n ) {\n value = (0, _index8.differenceInHours)(laterDate_, earlierDate_);\n unit = \"hour\";\n } else if (\n Math.abs(diffInSeconds) < _index2.secondsInWeek &&\n (value = (0, _index3.differenceInCalendarDays)(\n laterDate_,\n earlierDate_,\n )) &&\n Math.abs(value) < 7\n ) {\n unit = \"day\";\n } else if (Math.abs(diffInSeconds) < _index2.secondsInMonth) {\n value = (0, _index6.differenceInCalendarWeeks)(laterDate_, earlierDate_);\n unit = \"week\";\n } else if (Math.abs(diffInSeconds) < _index2.secondsInQuarter) {\n value = (0, _index4.differenceInCalendarMonths)(laterDate_, earlierDate_);\n unit = \"month\";\n } else if (Math.abs(diffInSeconds) < _index2.secondsInYear) {\n if (\n (0, _index5.differenceInCalendarQuarters)(laterDate_, earlierDate_) < 4\n ) {\n // To filter out cases that are less than a year but match 4 quarters\n value = (0, _index5.differenceInCalendarQuarters)(\n laterDate_,\n earlierDate_,\n );\n unit = \"quarter\";\n } else {\n value = (0, _index7.differenceInCalendarYears)(\n laterDate_,\n earlierDate_,\n );\n unit = \"year\";\n }\n } else {\n value = (0, _index7.differenceInCalendarYears)(laterDate_, earlierDate_);\n unit = \"year\";\n }\n } else {\n // Get the value if unit is specified\n unit = options?.unit;\n if (unit === \"second\") {\n value = (0, _index10.differenceInSeconds)(laterDate_, earlierDate_);\n } else if (unit === \"minute\") {\n value = (0, _index9.differenceInMinutes)(laterDate_, earlierDate_);\n } else if (unit === \"hour\") {\n value = (0, _index8.differenceInHours)(laterDate_, earlierDate_);\n } else if (unit === \"day\") {\n value = (0, _index3.differenceInCalendarDays)(laterDate_, earlierDate_);\n } else if (unit === \"week\") {\n value = (0, _index6.differenceInCalendarWeeks)(laterDate_, earlierDate_);\n } else if (unit === \"month\") {\n value = (0, _index4.differenceInCalendarMonths)(laterDate_, earlierDate_);\n } else if (unit === \"quarter\") {\n value = (0, _index5.differenceInCalendarQuarters)(\n laterDate_,\n earlierDate_,\n );\n } else if (unit === \"year\") {\n value = (0, _index7.differenceInCalendarYears)(laterDate_, earlierDate_);\n }\n }\n\n const rtf = new Intl.RelativeTimeFormat(options?.locale, {\n numeric: \"auto\",\n ...options,\n });\n\n return rtf.format(value, unit);\n}\n", "\"use strict\";\nexports.isAfter = isAfter;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name isAfter\n * @category Common Helpers\n * @summary Is the first date after the second one?\n *\n * @description\n * Is the first date after the second one?\n *\n * @param date - The date that should be after the other one to return true\n * @param dateToCompare - The date to compare with\n *\n * @returns The first date is after the second date\n *\n * @example\n * // Is 10 July 1989 after 11 February 1987?\n * const result = isAfter(new Date(1989, 6, 10), new Date(1987, 1, 11))\n * //=> true\n */\nfunction isAfter(date, dateToCompare) {\n return +(0, _index.toDate)(date) > +(0, _index.toDate)(dateToCompare);\n}\n", "\"use strict\";\nexports.isBefore = isBefore;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name isBefore\n * @category Common Helpers\n * @summary Is the first date before the second one?\n *\n * @description\n * Is the first date before the second one?\n *\n * @param date - The date that should be before the other one to return true\n * @param dateToCompare - The date to compare with\n *\n * @returns The first date is before the second date\n *\n * @example\n * // Is 10 July 1989 before 11 February 1987?\n * const result = isBefore(new Date(1989, 6, 10), new Date(1987, 1, 11))\n * //=> false\n */\nfunction isBefore(date, dateToCompare) {\n return +(0, _index.toDate)(date) < +(0, _index.toDate)(dateToCompare);\n}\n", "\"use strict\";\nexports.isEqual = isEqual;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name isEqual\n * @category Common Helpers\n * @summary Are the given dates equal?\n *\n * @description\n * Are the given dates equal?\n *\n * @param dateLeft - The first date to compare\n * @param dateRight - The second date to compare\n *\n * @returns The dates are equal\n *\n * @example\n * // Are 2 July 2014 06:30:45.000 and 2 July 2014 06:30:45.500 equal?\n * const result = isEqual(\n * new Date(2014, 6, 2, 6, 30, 45, 0),\n * new Date(2014, 6, 2, 6, 30, 45, 500)\n * )\n * //=> false\n */\nfunction isEqual(leftDate, rightDate) {\n return +(0, _index.toDate)(leftDate) === +(0, _index.toDate)(rightDate);\n}\n", "\"use strict\";\nexports.isExists = isExists; /**\n * @name isExists\n * @category Common Helpers\n * @summary Is the given date exists?\n *\n * @description\n * Checks if the given arguments convert to an existing date.\n *\n * @param year - The year of the date to check\n * @param month - The month of the date to check\n * @param day - The day of the date to check\n *\n * @returns `true` if the date exists\n *\n * @example\n * // For the valid date:\n * const result = isExists(2018, 0, 31)\n * //=> true\n *\n * @example\n * // For the invalid date:\n * const result = isExists(2018, 1, 31)\n * //=> false\n */\nfunction isExists(year, month, day) {\n const date = new Date(year, month, day);\n return (\n date.getFullYear() === year &&\n date.getMonth() === month &&\n date.getDate() === day\n );\n}\n", "\"use strict\";\nexports.isFirstDayOfMonth = isFirstDayOfMonth;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isFirstDayOfMonth} function options.\n */\n\n/**\n * @name isFirstDayOfMonth\n * @category Month Helpers\n * @summary Is the given date the first day of a month?\n *\n * @description\n * Is the given date the first day of a month?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is the first day of a month\n *\n * @example\n * // Is 1 September 2014 the first day of a month?\n * const result = isFirstDayOfMonth(new Date(2014, 8, 1))\n * //=> true\n */\nfunction isFirstDayOfMonth(date, options) {\n return (0, _index.toDate)(date, options?.in).getDate() === 1;\n}\n", "\"use strict\";\nexports.isFriday = isFriday;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isFriday} function options.\n */\n\n/**\n * @name isFriday\n * @category Weekday Helpers\n * @summary Is the given date Friday?\n *\n * @description\n * Is the given date Friday?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is Friday\n *\n * @example\n * // Is 26 September 2014 Friday?\n * const result = isFriday(new Date(2014, 8, 26))\n * //=> true\n */\nfunction isFriday(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay() === 5;\n}\n", "\"use strict\";\nexports.isFuture = isFuture;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name isFuture\n * @category Common Helpers\n * @summary Is the given date in the future?\n * @pure false\n *\n * @description\n * Is the given date in the future?\n *\n * @param date - The date to check\n *\n * @returns The date is in the future\n *\n * @example\n * // If today is 6 October 2014, is 31 December 2014 in the future?\n * const result = isFuture(new Date(2014, 11, 31))\n * //=> true\n */\nfunction isFuture(date) {\n return +(0, _index.toDate)(date) > Date.now();\n}\n", "\"use strict\";\nexports.transpose = transpose;\nvar _index = require(\"./constructFrom.cjs\");\n\n/**\n * @name transpose\n * @category Generic Helpers\n * @summary Transpose the date to the given constructor.\n *\n * @description\n * The function transposes the date to the given constructor. It helps you\n * to transpose the date in the system time zone to say `UTCDate` or any other\n * date extension.\n *\n * @typeParam InputDate - The input `Date` type derived from the passed argument.\n * @typeParam ResultDate - The result `Date` type derived from the passed constructor.\n *\n * @param date - The date to use values from\n * @param constructor - The date constructor to use\n *\n * @returns Date transposed to the given constructor\n *\n * @example\n * // Create July 10, 2022 00:00 in locale time zone\n * const date = new Date(2022, 6, 10)\n * //=> 'Sun Jul 10 2022 00:00:00 GMT+0800 (Singapore Standard Time)'\n *\n * @example\n * // Transpose the date to July 10, 2022 00:00 in UTC\n * transpose(date, UTCDate)\n * //=> 'Sun Jul 10 2022 00:00:00 GMT+0000 (Coordinated Universal Time)'\n */\nfunction transpose(date, constructor) {\n const date_ = isConstructor(constructor)\n ? new constructor(0)\n : (0, _index.constructFrom)(constructor, 0);\n date_.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());\n date_.setHours(\n date.getHours(),\n date.getMinutes(),\n date.getSeconds(),\n date.getMilliseconds(),\n );\n return date_;\n}\n\nfunction isConstructor(constructor) {\n return (\n typeof constructor === \"function\" &&\n constructor.prototype?.constructor === constructor\n );\n}\n", "\"use strict\";\nexports.ValueSetter = exports.Setter = exports.DateTimezoneSetter = void 0;\nvar _index = require(\"../../constructFrom.cjs\");\nvar _index2 = require(\"../../transpose.cjs\");\n\nconst TIMEZONE_UNIT_PRIORITY = 10;\n\nclass Setter {\n subPriority = 0;\n\n validate(_utcDate, _options) {\n return true;\n }\n}\nexports.Setter = Setter;\n\nclass ValueSetter extends Setter {\n constructor(\n value,\n\n validateValue,\n\n setValue,\n\n priority,\n subPriority,\n ) {\n super();\n this.value = value;\n this.validateValue = validateValue;\n this.setValue = setValue;\n this.priority = priority;\n if (subPriority) {\n this.subPriority = subPriority;\n }\n }\n\n validate(date, options) {\n return this.validateValue(date, this.value, options);\n }\n\n set(date, flags, options) {\n return this.setValue(date, flags, this.value, options);\n }\n}\nexports.ValueSetter = ValueSetter;\n\nclass DateTimezoneSetter extends Setter {\n priority = TIMEZONE_UNIT_PRIORITY;\n subPriority = -1;\n\n constructor(context, reference) {\n super();\n this.context =\n context || ((date) => (0, _index.constructFrom)(reference, date));\n }\n\n set(date, flags) {\n if (flags.timestampIsSet) return date;\n return (0, _index.constructFrom)(\n date,\n (0, _index2.transpose)(date, this.context),\n );\n }\n}\nexports.DateTimezoneSetter = DateTimezoneSetter;\n", "\"use strict\";\nexports.Parser = void 0;\nvar _Setter = require(\"./Setter.cjs\");\n\nclass Parser {\n run(dateString, token, match, options) {\n const result = this.parse(dateString, token, match, options);\n if (!result) {\n return null;\n }\n\n return {\n setter: new _Setter.ValueSetter(\n result.value,\n this.validate,\n this.set,\n this.priority,\n this.subPriority,\n ),\n rest: result.rest,\n };\n }\n\n validate(_utcDate, _value, _options) {\n return true;\n }\n}\nexports.Parser = Parser;\n", "\"use strict\";\nexports.EraParser = void 0;\n\nvar _Parser = require(\"../Parser.cjs\");\n\nclass EraParser extends _Parser.Parser {\n priority = 140;\n\n parse(dateString, token, match) {\n switch (token) {\n // AD, BC\n case \"G\":\n case \"GG\":\n case \"GGG\":\n return (\n match.era(dateString, { width: \"abbreviated\" }) ||\n match.era(dateString, { width: \"narrow\" })\n );\n\n // A, B\n case \"GGGGG\":\n return match.era(dateString, { width: \"narrow\" });\n // Anno Domini, Before Christ\n case \"GGGG\":\n default:\n return (\n match.era(dateString, { width: \"wide\" }) ||\n match.era(dateString, { width: \"abbreviated\" }) ||\n match.era(dateString, { width: \"narrow\" })\n );\n }\n }\n\n set(date, flags, value) {\n flags.era = value;\n date.setFullYear(value, 0, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"R\", \"u\", \"t\", \"T\"];\n}\nexports.EraParser = EraParser;\n", "\"use strict\";\nexports.timezonePatterns = exports.numericPatterns = void 0;\nconst numericPatterns = (exports.numericPatterns = {\n month: /^(1[0-2]|0?\\d)/, // 0 to 12\n date: /^(3[0-1]|[0-2]?\\d)/, // 0 to 31\n dayOfYear: /^(36[0-6]|3[0-5]\\d|[0-2]?\\d?\\d)/, // 0 to 366\n week: /^(5[0-3]|[0-4]?\\d)/, // 0 to 53\n hour23h: /^(2[0-3]|[0-1]?\\d)/, // 0 to 23\n hour24h: /^(2[0-4]|[0-1]?\\d)/, // 0 to 24\n hour11h: /^(1[0-1]|0?\\d)/, // 0 to 11\n hour12h: /^(1[0-2]|0?\\d)/, // 0 to 12\n minute: /^[0-5]?\\d/, // 0 to 59\n second: /^[0-5]?\\d/, // 0 to 59\n\n singleDigit: /^\\d/, // 0 to 9\n twoDigits: /^\\d{1,2}/, // 0 to 99\n threeDigits: /^\\d{1,3}/, // 0 to 999\n fourDigits: /^\\d{1,4}/, // 0 to 9999\n\n anyDigitsSigned: /^-?\\d+/,\n singleDigitSigned: /^-?\\d/, // 0 to 9, -0 to -9\n twoDigitsSigned: /^-?\\d{1,2}/, // 0 to 99, -0 to -99\n threeDigitsSigned: /^-?\\d{1,3}/, // 0 to 999, -0 to -999\n fourDigitsSigned: /^-?\\d{1,4}/, // 0 to 9999, -0 to -9999\n});\n\nconst timezonePatterns = (exports.timezonePatterns = {\n basicOptionalMinutes: /^([+-])(\\d{2})(\\d{2})?|Z/,\n basic: /^([+-])(\\d{2})(\\d{2})|Z/,\n basicOptionalSeconds: /^([+-])(\\d{2})(\\d{2})((\\d{2}))?|Z/,\n extended: /^([+-])(\\d{2}):(\\d{2})|Z/,\n extendedOptionalSeconds: /^([+-])(\\d{2}):(\\d{2})(:(\\d{2}))?|Z/,\n});\n", "\"use strict\";\nexports.dayPeriodEnumToHours = dayPeriodEnumToHours;\nexports.isLeapYearIndex = isLeapYearIndex;\nexports.mapValue = mapValue;\nexports.normalizeTwoDigitYear = normalizeTwoDigitYear;\nexports.parseAnyDigitsSigned = parseAnyDigitsSigned;\nexports.parseNDigits = parseNDigits;\nexports.parseNDigitsSigned = parseNDigitsSigned;\nexports.parseNumericPattern = parseNumericPattern;\nexports.parseTimezonePattern = parseTimezonePattern;\nvar _index = require(\"../../constants.cjs\");\n\nvar _constants = require(\"./constants.cjs\");\n\nfunction mapValue(parseFnResult, mapFn) {\n if (!parseFnResult) {\n return parseFnResult;\n }\n\n return {\n value: mapFn(parseFnResult.value),\n rest: parseFnResult.rest,\n };\n}\n\nfunction parseNumericPattern(pattern, dateString) {\n const matchResult = dateString.match(pattern);\n\n if (!matchResult) {\n return null;\n }\n\n return {\n value: parseInt(matchResult[0], 10),\n rest: dateString.slice(matchResult[0].length),\n };\n}\n\nfunction parseTimezonePattern(pattern, dateString) {\n const matchResult = dateString.match(pattern);\n\n if (!matchResult) {\n return null;\n }\n\n // Input is 'Z'\n if (matchResult[0] === \"Z\") {\n return {\n value: 0,\n rest: dateString.slice(1),\n };\n }\n\n const sign = matchResult[1] === \"+\" ? 1 : -1;\n const hours = matchResult[2] ? parseInt(matchResult[2], 10) : 0;\n const minutes = matchResult[3] ? parseInt(matchResult[3], 10) : 0;\n const seconds = matchResult[5] ? parseInt(matchResult[5], 10) : 0;\n\n return {\n value:\n sign *\n (hours * _index.millisecondsInHour +\n minutes * _index.millisecondsInMinute +\n seconds * _index.millisecondsInSecond),\n rest: dateString.slice(matchResult[0].length),\n };\n}\n\nfunction parseAnyDigitsSigned(dateString) {\n return parseNumericPattern(\n _constants.numericPatterns.anyDigitsSigned,\n dateString,\n );\n}\n\nfunction parseNDigits(n, dateString) {\n switch (n) {\n case 1:\n return parseNumericPattern(\n _constants.numericPatterns.singleDigit,\n dateString,\n );\n case 2:\n return parseNumericPattern(\n _constants.numericPatterns.twoDigits,\n dateString,\n );\n case 3:\n return parseNumericPattern(\n _constants.numericPatterns.threeDigits,\n dateString,\n );\n case 4:\n return parseNumericPattern(\n _constants.numericPatterns.fourDigits,\n dateString,\n );\n default:\n return parseNumericPattern(new RegExp(\"^\\\\d{1,\" + n + \"}\"), dateString);\n }\n}\n\nfunction parseNDigitsSigned(n, dateString) {\n switch (n) {\n case 1:\n return parseNumericPattern(\n _constants.numericPatterns.singleDigitSigned,\n dateString,\n );\n case 2:\n return parseNumericPattern(\n _constants.numericPatterns.twoDigitsSigned,\n dateString,\n );\n case 3:\n return parseNumericPattern(\n _constants.numericPatterns.threeDigitsSigned,\n dateString,\n );\n case 4:\n return parseNumericPattern(\n _constants.numericPatterns.fourDigitsSigned,\n dateString,\n );\n default:\n return parseNumericPattern(new RegExp(\"^-?\\\\d{1,\" + n + \"}\"), dateString);\n }\n}\n\nfunction dayPeriodEnumToHours(dayPeriod) {\n switch (dayPeriod) {\n case \"morning\":\n return 4;\n case \"evening\":\n return 17;\n case \"pm\":\n case \"noon\":\n case \"afternoon\":\n return 12;\n case \"am\":\n case \"midnight\":\n case \"night\":\n default:\n return 0;\n }\n}\n\nfunction normalizeTwoDigitYear(twoDigitYear, currentYear) {\n const isCommonEra = currentYear > 0;\n // Absolute number of the current year:\n // 1 -> 1 AC\n // 0 -> 1 BC\n // -1 -> 2 BC\n const absCurrentYear = isCommonEra ? currentYear : 1 - currentYear;\n\n let result;\n if (absCurrentYear <= 50) {\n result = twoDigitYear || 100;\n } else {\n const rangeEnd = absCurrentYear + 50;\n const rangeEndCentury = Math.trunc(rangeEnd / 100) * 100;\n const isPreviousCentury = twoDigitYear >= rangeEnd % 100;\n result = twoDigitYear + rangeEndCentury - (isPreviousCentury ? 100 : 0);\n }\n\n return isCommonEra ? result : 1 - result;\n}\n\nfunction isLeapYearIndex(year) {\n return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);\n}\n", "\"use strict\";\nexports.YearParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns\n// | Year | y | yy | yyy | yyyy | yyyyy |\n// |----------|-------|----|-------|-------|-------|\n// | AD 1 | 1 | 01 | 001 | 0001 | 00001 |\n// | AD 12 | 12 | 12 | 012 | 0012 | 00012 |\n// | AD 123 | 123 | 23 | 123 | 0123 | 00123 |\n// | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 |\n// | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |\nclass YearParser extends _Parser.Parser {\n priority = 130;\n incompatibleTokens = [\"Y\", \"R\", \"u\", \"w\", \"I\", \"i\", \"e\", \"c\", \"t\", \"T\"];\n\n parse(dateString, token, match) {\n const valueCallback = (year) => ({\n year,\n isTwoDigitYear: token === \"yy\",\n });\n\n switch (token) {\n case \"y\":\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(4, dateString),\n valueCallback,\n );\n case \"yo\":\n return (0, _utils.mapValue)(\n match.ordinalNumber(dateString, {\n unit: \"year\",\n }),\n valueCallback,\n );\n default:\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(token.length, dateString),\n valueCallback,\n );\n }\n }\n\n validate(_date, value) {\n return value.isTwoDigitYear || value.year > 0;\n }\n\n set(date, flags, value) {\n const currentYear = date.getFullYear();\n\n if (value.isTwoDigitYear) {\n const normalizedTwoDigitYear = (0, _utils.normalizeTwoDigitYear)(\n value.year,\n currentYear,\n );\n date.setFullYear(normalizedTwoDigitYear, 0, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n const year =\n !(\"era\" in flags) || flags.era === 1 ? value.year : 1 - value.year;\n date.setFullYear(year, 0, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n}\nexports.YearParser = YearParser;\n", "\"use strict\";\nexports.LocalWeekYearParser = void 0;\nvar _index = require(\"../../../getWeekYear.cjs\");\n\nvar _index2 = require(\"../../../startOfWeek.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// Local week-numbering year\nclass LocalWeekYearParser extends _Parser.Parser {\n priority = 130;\n\n parse(dateString, token, match) {\n const valueCallback = (year) => ({\n year,\n isTwoDigitYear: token === \"YY\",\n });\n\n switch (token) {\n case \"Y\":\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(4, dateString),\n valueCallback,\n );\n case \"Yo\":\n return (0, _utils.mapValue)(\n match.ordinalNumber(dateString, {\n unit: \"year\",\n }),\n valueCallback,\n );\n default:\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(token.length, dateString),\n valueCallback,\n );\n }\n }\n\n validate(_date, value) {\n return value.isTwoDigitYear || value.year > 0;\n }\n\n set(date, flags, value, options) {\n const currentYear = (0, _index.getWeekYear)(date, options);\n\n if (value.isTwoDigitYear) {\n const normalizedTwoDigitYear = (0, _utils.normalizeTwoDigitYear)(\n value.year,\n currentYear,\n );\n date.setFullYear(\n normalizedTwoDigitYear,\n 0,\n options.firstWeekContainsDate,\n );\n date.setHours(0, 0, 0, 0);\n return (0, _index2.startOfWeek)(date, options);\n }\n\n const year =\n !(\"era\" in flags) || flags.era === 1 ? value.year : 1 - value.year;\n date.setFullYear(year, 0, options.firstWeekContainsDate);\n date.setHours(0, 0, 0, 0);\n return (0, _index2.startOfWeek)(date, options);\n }\n\n incompatibleTokens = [\n \"y\",\n \"R\",\n \"u\",\n \"Q\",\n \"q\",\n \"M\",\n \"L\",\n \"I\",\n \"d\",\n \"D\",\n \"i\",\n \"t\",\n \"T\",\n ];\n}\nexports.LocalWeekYearParser = LocalWeekYearParser;\n", "\"use strict\";\nexports.ISOWeekYearParser = void 0;\nvar _index = require(\"../../../startOfISOWeek.cjs\");\nvar _index2 = require(\"../../../constructFrom.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// ISO week-numbering year\nclass ISOWeekYearParser extends _Parser.Parser {\n priority = 130;\n\n parse(dateString, token) {\n if (token === \"R\") {\n return (0, _utils.parseNDigitsSigned)(4, dateString);\n }\n\n return (0, _utils.parseNDigitsSigned)(token.length, dateString);\n }\n\n set(date, _flags, value) {\n const firstWeekOfYear = (0, _index2.constructFrom)(date, 0);\n firstWeekOfYear.setFullYear(value, 0, 4);\n firstWeekOfYear.setHours(0, 0, 0, 0);\n return (0, _index.startOfISOWeek)(firstWeekOfYear);\n }\n\n incompatibleTokens = [\n \"G\",\n \"y\",\n \"Y\",\n \"u\",\n \"Q\",\n \"q\",\n \"M\",\n \"L\",\n \"w\",\n \"d\",\n \"D\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.ISOWeekYearParser = ISOWeekYearParser;\n", "\"use strict\";\nexports.ExtendedYearParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass ExtendedYearParser extends _Parser.Parser {\n priority = 130;\n\n parse(dateString, token) {\n if (token === \"u\") {\n return (0, _utils.parseNDigitsSigned)(4, dateString);\n }\n\n return (0, _utils.parseNDigitsSigned)(token.length, dateString);\n }\n\n set(date, _flags, value) {\n date.setFullYear(value, 0, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"G\", \"y\", \"Y\", \"R\", \"w\", \"I\", \"i\", \"e\", \"c\", \"t\", \"T\"];\n}\nexports.ExtendedYearParser = ExtendedYearParser;\n", "\"use strict\";\nexports.QuarterParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass QuarterParser extends _Parser.Parser {\n priority = 120;\n\n parse(dateString, token, match) {\n switch (token) {\n // 1, 2, 3, 4\n case \"Q\":\n case \"QQ\": // 01, 02, 03, 04\n return (0, _utils.parseNDigits)(token.length, dateString);\n // 1st, 2nd, 3rd, 4th\n case \"Qo\":\n return match.ordinalNumber(dateString, { unit: \"quarter\" });\n // Q1, Q2, Q3, Q4\n case \"QQQ\":\n return (\n match.quarter(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.quarter(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n\n // 1, 2, 3, 4 (narrow quarter; could be not numerical)\n case \"QQQQQ\":\n return match.quarter(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // 1st quarter, 2nd quarter, ...\n case \"QQQQ\":\n default:\n return (\n match.quarter(dateString, {\n width: \"wide\",\n context: \"formatting\",\n }) ||\n match.quarter(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.quarter(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n }\n }\n\n validate(_date, value) {\n return value >= 1 && value <= 4;\n }\n\n set(date, _flags, value) {\n date.setMonth((value - 1) * 3, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"Y\",\n \"R\",\n \"q\",\n \"M\",\n \"L\",\n \"w\",\n \"I\",\n \"d\",\n \"D\",\n \"i\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.QuarterParser = QuarterParser;\n", "\"use strict\";\nexports.StandAloneQuarterParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass StandAloneQuarterParser extends _Parser.Parser {\n priority = 120;\n\n parse(dateString, token, match) {\n switch (token) {\n // 1, 2, 3, 4\n case \"q\":\n case \"qq\": // 01, 02, 03, 04\n return (0, _utils.parseNDigits)(token.length, dateString);\n // 1st, 2nd, 3rd, 4th\n case \"qo\":\n return match.ordinalNumber(dateString, { unit: \"quarter\" });\n // Q1, Q2, Q3, Q4\n case \"qqq\":\n return (\n match.quarter(dateString, {\n width: \"abbreviated\",\n context: \"standalone\",\n }) ||\n match.quarter(dateString, {\n width: \"narrow\",\n context: \"standalone\",\n })\n );\n\n // 1, 2, 3, 4 (narrow quarter; could be not numerical)\n case \"qqqqq\":\n return match.quarter(dateString, {\n width: \"narrow\",\n context: \"standalone\",\n });\n // 1st quarter, 2nd quarter, ...\n case \"qqqq\":\n default:\n return (\n match.quarter(dateString, {\n width: \"wide\",\n context: \"standalone\",\n }) ||\n match.quarter(dateString, {\n width: \"abbreviated\",\n context: \"standalone\",\n }) ||\n match.quarter(dateString, {\n width: \"narrow\",\n context: \"standalone\",\n })\n );\n }\n }\n\n validate(_date, value) {\n return value >= 1 && value <= 4;\n }\n\n set(date, _flags, value) {\n date.setMonth((value - 1) * 3, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"Y\",\n \"R\",\n \"Q\",\n \"M\",\n \"L\",\n \"w\",\n \"I\",\n \"d\",\n \"D\",\n \"i\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.StandAloneQuarterParser = StandAloneQuarterParser;\n", "\"use strict\";\nexports.MonthParser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass MonthParser extends _Parser.Parser {\n incompatibleTokens = [\n \"Y\",\n \"R\",\n \"q\",\n \"Q\",\n \"L\",\n \"w\",\n \"I\",\n \"D\",\n \"i\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n\n priority = 110;\n\n parse(dateString, token, match) {\n const valueCallback = (value) => value - 1;\n\n switch (token) {\n // 1, 2, ..., 12\n case \"M\":\n return (0, _utils.mapValue)(\n (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.month,\n dateString,\n ),\n valueCallback,\n );\n // 01, 02, ..., 12\n case \"MM\":\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(2, dateString),\n valueCallback,\n );\n // 1st, 2nd, ..., 12th\n case \"Mo\":\n return (0, _utils.mapValue)(\n match.ordinalNumber(dateString, {\n unit: \"month\",\n }),\n valueCallback,\n );\n // Jan, Feb, ..., Dec\n case \"MMM\":\n return (\n match.month(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.month(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n\n // J, F, ..., D\n case \"MMMMM\":\n return match.month(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // January, February, ..., December\n case \"MMMM\":\n default:\n return (\n match.month(dateString, { width: \"wide\", context: \"formatting\" }) ||\n match.month(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.month(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 11;\n }\n\n set(date, _flags, value) {\n date.setMonth(value, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n}\nexports.MonthParser = MonthParser;\n", "\"use strict\";\nexports.StandAloneMonthParser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass StandAloneMonthParser extends _Parser.Parser {\n priority = 110;\n\n parse(dateString, token, match) {\n const valueCallback = (value) => value - 1;\n\n switch (token) {\n // 1, 2, ..., 12\n case \"L\":\n return (0, _utils.mapValue)(\n (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.month,\n dateString,\n ),\n valueCallback,\n );\n // 01, 02, ..., 12\n case \"LL\":\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(2, dateString),\n valueCallback,\n );\n // 1st, 2nd, ..., 12th\n case \"Lo\":\n return (0, _utils.mapValue)(\n match.ordinalNumber(dateString, {\n unit: \"month\",\n }),\n valueCallback,\n );\n // Jan, Feb, ..., Dec\n case \"LLL\":\n return (\n match.month(dateString, {\n width: \"abbreviated\",\n context: \"standalone\",\n }) ||\n match.month(dateString, { width: \"narrow\", context: \"standalone\" })\n );\n\n // J, F, ..., D\n case \"LLLLL\":\n return match.month(dateString, {\n width: \"narrow\",\n context: \"standalone\",\n });\n // January, February, ..., December\n case \"LLLL\":\n default:\n return (\n match.month(dateString, { width: \"wide\", context: \"standalone\" }) ||\n match.month(dateString, {\n width: \"abbreviated\",\n context: \"standalone\",\n }) ||\n match.month(dateString, { width: \"narrow\", context: \"standalone\" })\n );\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 11;\n }\n\n set(date, _flags, value) {\n date.setMonth(value, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"Y\",\n \"R\",\n \"q\",\n \"Q\",\n \"M\",\n \"w\",\n \"I\",\n \"D\",\n \"i\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.StandAloneMonthParser = StandAloneMonthParser;\n", "\"use strict\";\nexports.setWeek = setWeek;\nvar _index = require(\"./getWeek.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setWeek} function options.\n */\n\n/**\n * @name setWeek\n * @category Week Helpers\n * @summary Set the local week to the given date.\n *\n * @description\n * Set the local week to the given date, saving the weekday number.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param week - The week of the new date\n * @param options - An object with options\n *\n * @returns The new date with the local week set\n *\n * @example\n * // Set the 1st week to 2 January 2005 with default options:\n * const result = setWeek(new Date(2005, 0, 2), 1)\n * //=> Sun Dec 26 2004 00:00:00\n *\n * @example\n * // Set the 1st week to 2 January 2005,\n * // if Monday is the first day of the week,\n * // and the first week of the year always contains 4 January:\n * const result = setWeek(new Date(2005, 0, 2), 1, {\n * weekStartsOn: 1,\n * firstWeekContainsDate: 4\n * })\n * //=> Sun Jan 4 2004 00:00:00\n */\nfunction setWeek(date, week, options) {\n const date_ = (0, _index2.toDate)(date, options?.in);\n const diff = (0, _index.getWeek)(date_, options) - week;\n date_.setDate(date_.getDate() - diff * 7);\n return (0, _index2.toDate)(date_, options?.in);\n}\n", "\"use strict\";\nexports.LocalWeekParser = void 0;\nvar _index = require(\"../../../setWeek.cjs\");\nvar _index2 = require(\"../../../startOfWeek.cjs\");\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// Local week of year\nclass LocalWeekParser extends _Parser.Parser {\n priority = 100;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"w\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.week,\n dateString,\n );\n case \"wo\":\n return match.ordinalNumber(dateString, { unit: \"week\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 1 && value <= 53;\n }\n\n set(date, _flags, value, options) {\n return (0, _index2.startOfWeek)(\n (0, _index.setWeek)(date, value, options),\n options,\n );\n }\n\n incompatibleTokens = [\n \"y\",\n \"R\",\n \"u\",\n \"q\",\n \"Q\",\n \"M\",\n \"L\",\n \"I\",\n \"d\",\n \"D\",\n \"i\",\n \"t\",\n \"T\",\n ];\n}\nexports.LocalWeekParser = LocalWeekParser;\n", "\"use strict\";\nexports.setISOWeek = setISOWeek;\nvar _index = require(\"./getISOWeek.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setISOWeek} function options.\n */\n\n/**\n * @name setISOWeek\n * @category ISO Week Helpers\n * @summary Set the ISO week to the given date.\n *\n * @description\n * Set the ISO week to the given date, saving the weekday number.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The `Date` type of the context function.\n *\n * @param date - The date to be changed\n * @param week - The ISO week of the new date\n * @param options - An object with options\n *\n * @returns The new date with the ISO week set\n *\n * @example\n * // Set the 53rd ISO week to 7 August 2004:\n * const result = setISOWeek(new Date(2004, 7, 7), 53)\n * //=> Sat Jan 01 2005 00:00:00\n */\nfunction setISOWeek(date, week, options) {\n const _date = (0, _index2.toDate)(date, options?.in);\n const diff = (0, _index.getISOWeek)(_date, options) - week;\n _date.setDate(_date.getDate() - diff * 7);\n return _date;\n}\n", "\"use strict\";\nexports.ISOWeekParser = void 0;\nvar _index = require(\"../../../setISOWeek.cjs\");\nvar _index2 = require(\"../../../startOfISOWeek.cjs\");\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// ISO week of year\nclass ISOWeekParser extends _Parser.Parser {\n priority = 100;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"I\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.week,\n dateString,\n );\n case \"Io\":\n return match.ordinalNumber(dateString, { unit: \"week\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 1 && value <= 53;\n }\n\n set(date, _flags, value) {\n return (0, _index2.startOfISOWeek)((0, _index.setISOWeek)(date, value));\n }\n\n incompatibleTokens = [\n \"y\",\n \"Y\",\n \"u\",\n \"q\",\n \"Q\",\n \"M\",\n \"L\",\n \"w\",\n \"d\",\n \"D\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.ISOWeekParser = ISOWeekParser;\n", "\"use strict\";\nexports.DateParser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nconst DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\nconst DAYS_IN_MONTH_LEAP_YEAR = [\n 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,\n];\n\n// Day of the month\nclass DateParser extends _Parser.Parser {\n priority = 90;\n subPriority = 1;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"d\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.date,\n dateString,\n );\n case \"do\":\n return match.ordinalNumber(dateString, { unit: \"date\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(date, value) {\n const year = date.getFullYear();\n const isLeapYear = (0, _utils.isLeapYearIndex)(year);\n const month = date.getMonth();\n if (isLeapYear) {\n return value >= 1 && value <= DAYS_IN_MONTH_LEAP_YEAR[month];\n } else {\n return value >= 1 && value <= DAYS_IN_MONTH[month];\n }\n }\n\n set(date, _flags, value) {\n date.setDate(value);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"Y\",\n \"R\",\n \"q\",\n \"Q\",\n \"w\",\n \"I\",\n \"D\",\n \"i\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.DateParser = DateParser;\n", "\"use strict\";\nexports.DayOfYearParser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass DayOfYearParser extends _Parser.Parser {\n priority = 90;\n\n subpriority = 1;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"D\":\n case \"DD\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.dayOfYear,\n dateString,\n );\n case \"Do\":\n return match.ordinalNumber(dateString, { unit: \"date\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(date, value) {\n const year = date.getFullYear();\n const isLeapYear = (0, _utils.isLeapYearIndex)(year);\n if (isLeapYear) {\n return value >= 1 && value <= 366;\n } else {\n return value >= 1 && value <= 365;\n }\n }\n\n set(date, _flags, value) {\n date.setMonth(0, value);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"Y\",\n \"R\",\n \"q\",\n \"Q\",\n \"M\",\n \"L\",\n \"w\",\n \"I\",\n \"d\",\n \"E\",\n \"i\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.DayOfYearParser = DayOfYearParser;\n", "\"use strict\";\nexports.setDay = setDay;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./addDays.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setDay} function options.\n */\n\n/**\n * @name setDay\n * @category Weekday Helpers\n * @summary Set the day of the week to the given date.\n *\n * @description\n * Set the day of the week to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param day - The day of the week of the new date\n * @param options - An object with options.\n *\n * @returns The new date with the day of the week set\n *\n * @example\n * // Set week day to Sunday, with the default weekStartsOn of Sunday:\n * const result = setDay(new Date(2014, 8, 1), 0)\n * //=> Sun Aug 31 2014 00:00:00\n *\n * @example\n * // Set week day to Sunday, with a weekStartsOn of Monday:\n * const result = setDay(new Date(2014, 8, 1), 0, { weekStartsOn: 1 })\n * //=> Sun Sep 07 2014 00:00:00\n */\nfunction setDay(date, day, options) {\n const defaultOptions = (0, _index.getDefaultOptions)();\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const date_ = (0, _index3.toDate)(date, options?.in);\n const currentDay = date_.getDay();\n\n const remainder = day % 7;\n const dayIndex = (remainder + 7) % 7;\n\n const delta = 7 - weekStartsOn;\n const diff =\n day < 0 || day > 6\n ? day - ((currentDay + delta) % 7)\n : ((dayIndex + delta) % 7) - ((currentDay + delta) % 7);\n return (0, _index2.addDays)(date_, diff, options);\n}\n", "\"use strict\";\nexports.DayParser = void 0;\nvar _index = require(\"../../../setDay.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\n// Day of week\nclass DayParser extends _Parser.Parser {\n priority = 90;\n\n parse(dateString, token, match) {\n switch (token) {\n // Tue\n case \"E\":\n case \"EE\":\n case \"EEE\":\n return (\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.day(dateString, { width: \"short\", context: \"formatting\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n\n // T\n case \"EEEEE\":\n return match.day(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // Tu\n case \"EEEEEE\":\n return (\n match.day(dateString, { width: \"short\", context: \"formatting\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n\n // Tuesday\n case \"EEEE\":\n default:\n return (\n match.day(dateString, { width: \"wide\", context: \"formatting\" }) ||\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.day(dateString, { width: \"short\", context: \"formatting\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 6;\n }\n\n set(date, _flags, value, options) {\n date = (0, _index.setDay)(date, value, options);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"D\", \"i\", \"e\", \"c\", \"t\", \"T\"];\n}\nexports.DayParser = DayParser;\n", "\"use strict\";\nexports.LocalDayParser = void 0;\nvar _index = require(\"../../../setDay.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// Local day of week\nclass LocalDayParser extends _Parser.Parser {\n priority = 90;\n parse(dateString, token, match, options) {\n const valueCallback = (value) => {\n // We want here floor instead of trunc, so we get -7 for value 0 instead of 0\n const wholeWeekDays = Math.floor((value - 1) / 7) * 7;\n return ((value + options.weekStartsOn + 6) % 7) + wholeWeekDays;\n };\n\n switch (token) {\n // 3\n case \"e\":\n case \"ee\": // 03\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(token.length, dateString),\n valueCallback,\n );\n // 3rd\n case \"eo\":\n return (0, _utils.mapValue)(\n match.ordinalNumber(dateString, {\n unit: \"day\",\n }),\n valueCallback,\n );\n // Tue\n case \"eee\":\n return (\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.day(dateString, { width: \"short\", context: \"formatting\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n\n // T\n case \"eeeee\":\n return match.day(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // Tu\n case \"eeeeee\":\n return (\n match.day(dateString, { width: \"short\", context: \"formatting\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n\n // Tuesday\n case \"eeee\":\n default:\n return (\n match.day(dateString, { width: \"wide\", context: \"formatting\" }) ||\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.day(dateString, { width: \"short\", context: \"formatting\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 6;\n }\n\n set(date, _flags, value, options) {\n date = (0, _index.setDay)(date, value, options);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"y\",\n \"R\",\n \"u\",\n \"q\",\n \"Q\",\n \"M\",\n \"L\",\n \"I\",\n \"d\",\n \"D\",\n \"E\",\n \"i\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.LocalDayParser = LocalDayParser;\n", "\"use strict\";\nexports.StandAloneLocalDayParser = void 0;\nvar _index = require(\"../../../setDay.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// Stand-alone local day of week\nclass StandAloneLocalDayParser extends _Parser.Parser {\n priority = 90;\n\n parse(dateString, token, match, options) {\n const valueCallback = (value) => {\n // We want here floor instead of trunc, so we get -7 for value 0 instead of 0\n const wholeWeekDays = Math.floor((value - 1) / 7) * 7;\n return ((value + options.weekStartsOn + 6) % 7) + wholeWeekDays;\n };\n\n switch (token) {\n // 3\n case \"c\":\n case \"cc\": // 03\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(token.length, dateString),\n valueCallback,\n );\n // 3rd\n case \"co\":\n return (0, _utils.mapValue)(\n match.ordinalNumber(dateString, {\n unit: \"day\",\n }),\n valueCallback,\n );\n // Tue\n case \"ccc\":\n return (\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"standalone\",\n }) ||\n match.day(dateString, { width: \"short\", context: \"standalone\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"standalone\" })\n );\n\n // T\n case \"ccccc\":\n return match.day(dateString, {\n width: \"narrow\",\n context: \"standalone\",\n });\n // Tu\n case \"cccccc\":\n return (\n match.day(dateString, { width: \"short\", context: \"standalone\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"standalone\" })\n );\n\n // Tuesday\n case \"cccc\":\n default:\n return (\n match.day(dateString, { width: \"wide\", context: \"standalone\" }) ||\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"standalone\",\n }) ||\n match.day(dateString, { width: \"short\", context: \"standalone\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"standalone\" })\n );\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 6;\n }\n\n set(date, _flags, value, options) {\n date = (0, _index.setDay)(date, value, options);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"y\",\n \"R\",\n \"u\",\n \"q\",\n \"Q\",\n \"M\",\n \"L\",\n \"I\",\n \"d\",\n \"D\",\n \"E\",\n \"i\",\n \"e\",\n \"t\",\n \"T\",\n ];\n}\nexports.StandAloneLocalDayParser = StandAloneLocalDayParser;\n", "\"use strict\";\nexports.setISODay = setISODay;\nvar _index = require(\"./addDays.cjs\");\nvar _index2 = require(\"./getISODay.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setISODay} function options.\n */\n\n/**\n * @name setISODay\n * @category Weekday Helpers\n * @summary Set the day of the ISO week to the given date.\n *\n * @description\n * Set the day of the ISO week to the given date.\n * ISO week starts with Monday.\n * 7 is the index of Sunday, 1 is the index of Monday, etc.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param day - The day of the ISO week of the new date\n * @param options - An object with options\n *\n * @returns The new date with the day of the ISO week set\n *\n * @example\n * // Set Sunday to 1 September 2014:\n * const result = setISODay(new Date(2014, 8, 1), 7)\n * //=> Sun Sep 07 2014 00:00:00\n */\nfunction setISODay(date, day, options) {\n const date_ = (0, _index3.toDate)(date, options?.in);\n const currentDay = (0, _index2.getISODay)(date_, options);\n const diff = day - currentDay;\n return (0, _index.addDays)(date_, diff, options);\n}\n", "\"use strict\";\nexports.ISODayParser = void 0;\nvar _index = require(\"../../../setISODay.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// ISO day of week\nclass ISODayParser extends _Parser.Parser {\n priority = 90;\n\n parse(dateString, token, match) {\n const valueCallback = (value) => {\n if (value === 0) {\n return 7;\n }\n return value;\n };\n\n switch (token) {\n // 2\n case \"i\":\n case \"ii\": // 02\n return (0, _utils.parseNDigits)(token.length, dateString);\n // 2nd\n case \"io\":\n return match.ordinalNumber(dateString, { unit: \"day\" });\n // Tue\n case \"iii\":\n return (0, _utils.mapValue)(\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.day(dateString, {\n width: \"short\",\n context: \"formatting\",\n }) ||\n match.day(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n }),\n valueCallback,\n );\n // T\n case \"iiiii\":\n return (0, _utils.mapValue)(\n match.day(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n }),\n valueCallback,\n );\n // Tu\n case \"iiiiii\":\n return (0, _utils.mapValue)(\n match.day(dateString, {\n width: \"short\",\n context: \"formatting\",\n }) ||\n match.day(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n }),\n valueCallback,\n );\n // Tuesday\n case \"iiii\":\n default:\n return (0, _utils.mapValue)(\n match.day(dateString, {\n width: \"wide\",\n context: \"formatting\",\n }) ||\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.day(dateString, {\n width: \"short\",\n context: \"formatting\",\n }) ||\n match.day(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n }),\n valueCallback,\n );\n }\n }\n\n validate(_date, value) {\n return value >= 1 && value <= 7;\n }\n\n set(date, _flags, value) {\n date = (0, _index.setISODay)(date, value);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"y\",\n \"Y\",\n \"u\",\n \"q\",\n \"Q\",\n \"M\",\n \"L\",\n \"w\",\n \"d\",\n \"D\",\n \"E\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.ISODayParser = ISODayParser;\n", "\"use strict\";\nexports.AMPMParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass AMPMParser extends _Parser.Parser {\n priority = 80;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"a\":\n case \"aa\":\n case \"aaa\":\n return (\n match.dayPeriod(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n\n case \"aaaaa\":\n return match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n });\n case \"aaaa\":\n default:\n return (\n match.dayPeriod(dateString, {\n width: \"wide\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n }\n }\n\n set(date, _flags, value) {\n date.setHours((0, _utils.dayPeriodEnumToHours)(value), 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"b\", \"B\", \"H\", \"k\", \"t\", \"T\"];\n}\nexports.AMPMParser = AMPMParser;\n", "\"use strict\";\nexports.AMPMMidnightParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass AMPMMidnightParser extends _Parser.Parser {\n priority = 80;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"b\":\n case \"bb\":\n case \"bbb\":\n return (\n match.dayPeriod(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n\n case \"bbbbb\":\n return match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n });\n case \"bbbb\":\n default:\n return (\n match.dayPeriod(dateString, {\n width: \"wide\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n }\n }\n\n set(date, _flags, value) {\n date.setHours((0, _utils.dayPeriodEnumToHours)(value), 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"a\", \"B\", \"H\", \"k\", \"t\", \"T\"];\n}\nexports.AMPMMidnightParser = AMPMMidnightParser;\n", "\"use strict\";\nexports.DayPeriodParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// in the morning, in the afternoon, in the evening, at night\nclass DayPeriodParser extends _Parser.Parser {\n priority = 80;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"B\":\n case \"BB\":\n case \"BBB\":\n return (\n match.dayPeriod(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n\n case \"BBBBB\":\n return match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n });\n case \"BBBB\":\n default:\n return (\n match.dayPeriod(dateString, {\n width: \"wide\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n }\n }\n\n set(date, _flags, value) {\n date.setHours((0, _utils.dayPeriodEnumToHours)(value), 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"a\", \"b\", \"t\", \"T\"];\n}\nexports.DayPeriodParser = DayPeriodParser;\n", "\"use strict\";\nexports.Hour1to12Parser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass Hour1to12Parser extends _Parser.Parser {\n priority = 70;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"h\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.hour12h,\n dateString,\n );\n case \"ho\":\n return match.ordinalNumber(dateString, { unit: \"hour\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 1 && value <= 12;\n }\n\n set(date, _flags, value) {\n const isPM = date.getHours() >= 12;\n if (isPM && value < 12) {\n date.setHours(value + 12, 0, 0, 0);\n } else if (!isPM && value === 12) {\n date.setHours(0, 0, 0, 0);\n } else {\n date.setHours(value, 0, 0, 0);\n }\n return date;\n }\n\n incompatibleTokens = [\"H\", \"K\", \"k\", \"t\", \"T\"];\n}\nexports.Hour1to12Parser = Hour1to12Parser;\n", "\"use strict\";\nexports.Hour0to23Parser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass Hour0to23Parser extends _Parser.Parser {\n priority = 70;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"H\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.hour23h,\n dateString,\n );\n case \"Ho\":\n return match.ordinalNumber(dateString, { unit: \"hour\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 23;\n }\n\n set(date, _flags, value) {\n date.setHours(value, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"a\", \"b\", \"h\", \"K\", \"k\", \"t\", \"T\"];\n}\nexports.Hour0to23Parser = Hour0to23Parser;\n", "\"use strict\";\nexports.Hour0To11Parser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass Hour0To11Parser extends _Parser.Parser {\n priority = 70;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"K\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.hour11h,\n dateString,\n );\n case \"Ko\":\n return match.ordinalNumber(dateString, { unit: \"hour\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 11;\n }\n\n set(date, _flags, value) {\n const isPM = date.getHours() >= 12;\n if (isPM && value < 12) {\n date.setHours(value + 12, 0, 0, 0);\n } else {\n date.setHours(value, 0, 0, 0);\n }\n return date;\n }\n\n incompatibleTokens = [\"h\", \"H\", \"k\", \"t\", \"T\"];\n}\nexports.Hour0To11Parser = Hour0To11Parser;\n", "\"use strict\";\nexports.Hour1To24Parser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass Hour1To24Parser extends _Parser.Parser {\n priority = 70;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"k\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.hour24h,\n dateString,\n );\n case \"ko\":\n return match.ordinalNumber(dateString, { unit: \"hour\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 1 && value <= 24;\n }\n\n set(date, _flags, value) {\n const hours = value <= 24 ? value % 24 : value;\n date.setHours(hours, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"a\", \"b\", \"h\", \"H\", \"K\", \"t\", \"T\"];\n}\nexports.Hour1To24Parser = Hour1To24Parser;\n", "\"use strict\";\nexports.MinuteParser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass MinuteParser extends _Parser.Parser {\n priority = 60;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"m\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.minute,\n dateString,\n );\n case \"mo\":\n return match.ordinalNumber(dateString, { unit: \"minute\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 59;\n }\n\n set(date, _flags, value) {\n date.setMinutes(value, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"t\", \"T\"];\n}\nexports.MinuteParser = MinuteParser;\n", "\"use strict\";\nexports.SecondParser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass SecondParser extends _Parser.Parser {\n priority = 50;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"s\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.second,\n dateString,\n );\n case \"so\":\n return match.ordinalNumber(dateString, { unit: \"second\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 59;\n }\n\n set(date, _flags, value) {\n date.setSeconds(value, 0);\n return date;\n }\n\n incompatibleTokens = [\"t\", \"T\"];\n}\nexports.SecondParser = SecondParser;\n", "\"use strict\";\nexports.FractionOfSecondParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass FractionOfSecondParser extends _Parser.Parser {\n priority = 30;\n\n parse(dateString, token) {\n const valueCallback = (value) =>\n Math.trunc(value * Math.pow(10, -token.length + 3));\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(token.length, dateString),\n valueCallback,\n );\n }\n\n set(date, _flags, value) {\n date.setMilliseconds(value);\n return date;\n }\n\n incompatibleTokens = [\"t\", \"T\"];\n}\nexports.FractionOfSecondParser = FractionOfSecondParser;\n", "\"use strict\";\nexports.ISOTimezoneWithZParser = void 0;\nvar _index = require(\"../../../constructFrom.cjs\");\nvar _index2 = require(\"../../../_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// Timezone (ISO-8601. +00:00 is `'Z'`)\nclass ISOTimezoneWithZParser extends _Parser.Parser {\n priority = 10;\n\n parse(dateString, token) {\n switch (token) {\n case \"X\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.basicOptionalMinutes,\n dateString,\n );\n case \"XX\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.basic,\n dateString,\n );\n case \"XXXX\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.basicOptionalSeconds,\n dateString,\n );\n case \"XXXXX\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.extendedOptionalSeconds,\n dateString,\n );\n case \"XXX\":\n default:\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.extended,\n dateString,\n );\n }\n }\n\n set(date, flags, value) {\n if (flags.timestampIsSet) return date;\n return (0, _index.constructFrom)(\n date,\n date.getTime() -\n (0, _index2.getTimezoneOffsetInMilliseconds)(date) -\n value,\n );\n }\n\n incompatibleTokens = [\"t\", \"T\", \"x\"];\n}\nexports.ISOTimezoneWithZParser = ISOTimezoneWithZParser;\n", "\"use strict\";\nexports.ISOTimezoneParser = void 0;\nvar _index = require(\"../../../constructFrom.cjs\");\nvar _index2 = require(\"../../../_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// Timezone (ISO-8601)\nclass ISOTimezoneParser extends _Parser.Parser {\n priority = 10;\n\n parse(dateString, token) {\n switch (token) {\n case \"x\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.basicOptionalMinutes,\n dateString,\n );\n case \"xx\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.basic,\n dateString,\n );\n case \"xxxx\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.basicOptionalSeconds,\n dateString,\n );\n case \"xxxxx\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.extendedOptionalSeconds,\n dateString,\n );\n case \"xxx\":\n default:\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.extended,\n dateString,\n );\n }\n }\n\n set(date, flags, value) {\n if (flags.timestampIsSet) return date;\n return (0, _index.constructFrom)(\n date,\n date.getTime() -\n (0, _index2.getTimezoneOffsetInMilliseconds)(date) -\n value,\n );\n }\n\n incompatibleTokens = [\"t\", \"T\", \"X\"];\n}\nexports.ISOTimezoneParser = ISOTimezoneParser;\n", "\"use strict\";\nexports.TimestampSecondsParser = void 0;\nvar _index = require(\"../../../constructFrom.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass TimestampSecondsParser extends _Parser.Parser {\n priority = 40;\n\n parse(dateString) {\n return (0, _utils.parseAnyDigitsSigned)(dateString);\n }\n\n set(date, _flags, value) {\n return [\n (0, _index.constructFrom)(date, value * 1000),\n { timestampIsSet: true },\n ];\n }\n\n incompatibleTokens = \"*\";\n}\nexports.TimestampSecondsParser = TimestampSecondsParser;\n", "\"use strict\";\nexports.TimestampMillisecondsParser = void 0;\nvar _index = require(\"../../../constructFrom.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass TimestampMillisecondsParser extends _Parser.Parser {\n priority = 20;\n\n parse(dateString) {\n return (0, _utils.parseAnyDigitsSigned)(dateString);\n }\n\n set(date, _flags, value) {\n return [(0, _index.constructFrom)(date, value), { timestampIsSet: true }];\n }\n\n incompatibleTokens = \"*\";\n}\nexports.TimestampMillisecondsParser = TimestampMillisecondsParser;\n", "\"use strict\";\nexports.parsers = void 0;\nvar _EraParser = require(\"./parsers/EraParser.cjs\");\nvar _YearParser = require(\"./parsers/YearParser.cjs\");\nvar _LocalWeekYearParser = require(\"./parsers/LocalWeekYearParser.cjs\");\nvar _ISOWeekYearParser = require(\"./parsers/ISOWeekYearParser.cjs\");\nvar _ExtendedYearParser = require(\"./parsers/ExtendedYearParser.cjs\");\nvar _QuarterParser = require(\"./parsers/QuarterParser.cjs\");\nvar _StandAloneQuarterParser = require(\"./parsers/StandAloneQuarterParser.cjs\");\nvar _MonthParser = require(\"./parsers/MonthParser.cjs\");\nvar _StandAloneMonthParser = require(\"./parsers/StandAloneMonthParser.cjs\");\nvar _LocalWeekParser = require(\"./parsers/LocalWeekParser.cjs\");\nvar _ISOWeekParser = require(\"./parsers/ISOWeekParser.cjs\");\nvar _DateParser = require(\"./parsers/DateParser.cjs\");\nvar _DayOfYearParser = require(\"./parsers/DayOfYearParser.cjs\");\nvar _DayParser = require(\"./parsers/DayParser.cjs\");\nvar _LocalDayParser = require(\"./parsers/LocalDayParser.cjs\");\nvar _StandAloneLocalDayParser = require(\"./parsers/StandAloneLocalDayParser.cjs\");\nvar _ISODayParser = require(\"./parsers/ISODayParser.cjs\");\nvar _AMPMParser = require(\"./parsers/AMPMParser.cjs\");\nvar _AMPMMidnightParser = require(\"./parsers/AMPMMidnightParser.cjs\");\nvar _DayPeriodParser = require(\"./parsers/DayPeriodParser.cjs\");\nvar _Hour1to12Parser = require(\"./parsers/Hour1to12Parser.cjs\");\nvar _Hour0to23Parser = require(\"./parsers/Hour0to23Parser.cjs\");\nvar _Hour0To11Parser = require(\"./parsers/Hour0To11Parser.cjs\");\nvar _Hour1To24Parser = require(\"./parsers/Hour1To24Parser.cjs\");\nvar _MinuteParser = require(\"./parsers/MinuteParser.cjs\");\nvar _SecondParser = require(\"./parsers/SecondParser.cjs\");\nvar _FractionOfSecondParser = require(\"./parsers/FractionOfSecondParser.cjs\");\nvar _ISOTimezoneWithZParser = require(\"./parsers/ISOTimezoneWithZParser.cjs\");\nvar _ISOTimezoneParser = require(\"./parsers/ISOTimezoneParser.cjs\");\nvar _TimestampSecondsParser = require(\"./parsers/TimestampSecondsParser.cjs\");\nvar _TimestampMillisecondsParser = require(\"./parsers/TimestampMillisecondsParser.cjs\");\n\n/*\n * | | Unit | | Unit |\n * |-----|--------------------------------|-----|--------------------------------|\n * | a | AM, PM | A* | Milliseconds in day |\n * | b | AM, PM, noon, midnight | B | Flexible day period |\n * | c | Stand-alone local day of week | C* | Localized hour w/ day period |\n * | d | Day of month | D | Day of year |\n * | e | Local day of week | E | Day of week |\n * | f | | F* | Day of week in month |\n * | g* | Modified Julian day | G | Era |\n * | h | Hour [1-12] | H | Hour [0-23] |\n * | i! | ISO day of week | I! | ISO week of year |\n * | j* | Localized hour w/ day period | J* | Localized hour w/o day period |\n * | k | Hour [1-24] | K | Hour [0-11] |\n * | l* | (deprecated) | L | Stand-alone month |\n * | m | Minute | M | Month |\n * | n | | N | |\n * | o! | Ordinal number modifier | O* | Timezone (GMT) |\n * | p | | P | |\n * | q | Stand-alone quarter | Q | Quarter |\n * | r* | Related Gregorian year | R! | ISO week-numbering year |\n * | s | Second | S | Fraction of second |\n * | t! | Seconds timestamp | T! | Milliseconds timestamp |\n * | u | Extended year | U* | Cyclic year |\n * | v* | Timezone (generic non-locat.) | V* | Timezone (location) |\n * | w | Local week of year | W* | Week of month |\n * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) |\n * | y | Year (abs) | Y | Local week-numbering year |\n * | z* | Timezone (specific non-locat.) | Z* | Timezone (aliases) |\n *\n * Letters marked by * are not implemented but reserved by Unicode standard.\n *\n * Letters marked by ! are non-standard, but implemented by date-fns:\n * - `o` modifies the previous token to turn it into an ordinal (see `parse` docs)\n * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,\n * i.e. 7 for Sunday, 1 for Monday, etc.\n * - `I` is ISO week of year, as opposed to `w` which is local week of year.\n * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.\n * `R` is supposed to be used in conjunction with `I` and `i`\n * for universal ISO week-numbering date, whereas\n * `Y` is supposed to be used in conjunction with `w` and `e`\n * for week-numbering date specific to the locale.\n */\nconst parsers = (exports.parsers = {\n G: new _EraParser.EraParser(),\n y: new _YearParser.YearParser(),\n Y: new _LocalWeekYearParser.LocalWeekYearParser(),\n R: new _ISOWeekYearParser.ISOWeekYearParser(),\n u: new _ExtendedYearParser.ExtendedYearParser(),\n Q: new _QuarterParser.QuarterParser(),\n q: new _StandAloneQuarterParser.StandAloneQuarterParser(),\n M: new _MonthParser.MonthParser(),\n L: new _StandAloneMonthParser.StandAloneMonthParser(),\n w: new _LocalWeekParser.LocalWeekParser(),\n I: new _ISOWeekParser.ISOWeekParser(),\n d: new _DateParser.DateParser(),\n D: new _DayOfYearParser.DayOfYearParser(),\n E: new _DayParser.DayParser(),\n e: new _LocalDayParser.LocalDayParser(),\n c: new _StandAloneLocalDayParser.StandAloneLocalDayParser(),\n i: new _ISODayParser.ISODayParser(),\n a: new _AMPMParser.AMPMParser(),\n b: new _AMPMMidnightParser.AMPMMidnightParser(),\n B: new _DayPeriodParser.DayPeriodParser(),\n h: new _Hour1to12Parser.Hour1to12Parser(),\n H: new _Hour0to23Parser.Hour0to23Parser(),\n K: new _Hour0To11Parser.Hour0To11Parser(),\n k: new _Hour1To24Parser.Hour1To24Parser(),\n m: new _MinuteParser.MinuteParser(),\n s: new _SecondParser.SecondParser(),\n S: new _FractionOfSecondParser.FractionOfSecondParser(),\n X: new _ISOTimezoneWithZParser.ISOTimezoneWithZParser(),\n x: new _ISOTimezoneParser.ISOTimezoneParser(),\n t: new _TimestampSecondsParser.TimestampSecondsParser(),\n T: new _TimestampMillisecondsParser.TimestampMillisecondsParser(),\n});\n", "\"use strict\";\nObject.defineProperty(exports, \"longFormatters\", {\n enumerable: true,\n get: function () {\n return _index2.longFormatters;\n },\n});\nexports.parse = parse;\nObject.defineProperty(exports, \"parsers\", {\n enumerable: true,\n get: function () {\n return _index7.parsers;\n },\n});\nvar _index = require(\"./_lib/defaultLocale.cjs\");\nvar _index2 = require(\"./_lib/format/longFormatters.cjs\");\nvar _index3 = require(\"./_lib/protectedTokens.cjs\");\n\nvar _index4 = require(\"./constructFrom.cjs\");\nvar _index5 = require(\"./getDefaultOptions.cjs\");\nvar _index6 = require(\"./toDate.cjs\");\n\nvar _Setter = require(\"./parse/_lib/Setter.cjs\");\nvar _index7 = require(\"./parse/_lib/parsers.cjs\");\n\n// Rexports of internal for libraries to use.\n// See: https://github.com/date-fns/date-fns/issues/3638#issuecomment-1877082874\n\n/**\n * The {@link parse} function options.\n */\n\n// This RegExp consists of three parts separated by `|`:\n// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token\n// (one of the certain letters followed by `o`)\n// - (\\w)\\1* matches any sequences of the same letter\n// - '' matches two quote characters in a row\n// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),\n// except a single quote symbol, which ends the sequence.\n// Two quote characters do not end the sequence.\n// If there is no matching single quote\n// then the sequence will continue until the end of the string.\n// - . matches any single character unmatched by previous parts of the RegExps\nconst formattingTokensRegExp =\n /[yYQqMLwIdDecihHKkms]o|(\\w)\\1*|''|'(''|[^'])+('|$)|./g;\n\n// This RegExp catches symbols escaped by quotes, and also\n// sequences of symbols P, p, and the combinations like `PPPPPPPppppp`\nconst longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;\n\nconst escapedStringRegExp = /^'([^]*?)'?$/;\nconst doubleQuoteRegExp = /''/g;\n\nconst notWhitespaceRegExp = /\\S/;\nconst unescapedLatinCharacterRegExp = /[a-zA-Z]/;\n\n/**\n * @name parse\n * @category Common Helpers\n * @summary Parse the date.\n *\n * @description\n * Return the date parsed from string using the given format string.\n *\n * > \u26A0\uFE0F Please note that the `format` tokens differ from Moment.js and other libraries.\n * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * The characters in the format string wrapped between two single quotes characters (') are escaped.\n * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.\n *\n * Format of the format string is based on Unicode Technical Standard #35:\n * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n * with a few additions (see note 5 below the table).\n *\n * Not all tokens are compatible. Combinations that don't make sense or could lead to bugs are prohibited\n * and will throw `RangeError`. For example usage of 24-hour format token with AM/PM token will throw an exception:\n *\n * ```javascript\n * parse('23 AM', 'HH a', new Date())\n * //=> RangeError: The format string mustn't contain `HH` and `a` at the same time\n * ```\n *\n * See the compatibility table: https://docs.google.com/spreadsheets/d/e/2PACX-1vQOPU3xUhplll6dyoMmVUXHKl_8CRDs6_ueLmex3SoqwhuolkuN3O05l4rqx5h1dKX8eb46Ul-CCSrq/pubhtml?gid=0&single=true\n *\n * Accepted format string patterns:\n * | Unit |Prior| Pattern | Result examples | Notes |\n * |---------------------------------|-----|---------|-----------------------------------|-------|\n * | Era | 140 | G..GGG | AD, BC | |\n * | | | GGGG | Anno Domini, Before Christ | 2 |\n * | | | GGGGG | A, B | |\n * | Calendar year | 130 | y | 44, 1, 1900, 2017, 9999 | 4 |\n * | | | yo | 44th, 1st, 1900th, 9999999th | 4,5 |\n * | | | yy | 44, 01, 00, 17 | 4 |\n * | | | yyy | 044, 001, 123, 999 | 4 |\n * | | | yyyy | 0044, 0001, 1900, 2017 | 4 |\n * | | | yyyyy | ... | 2,4 |\n * | Local week-numbering year | 130 | Y | 44, 1, 1900, 2017, 9000 | 4 |\n * | | | Yo | 44th, 1st, 1900th, 9999999th | 4,5 |\n * | | | YY | 44, 01, 00, 17 | 4,6 |\n * | | | YYY | 044, 001, 123, 999 | 4 |\n * | | | YYYY | 0044, 0001, 1900, 2017 | 4,6 |\n * | | | YYYYY | ... | 2,4 |\n * | ISO week-numbering year | 130 | R | -43, 1, 1900, 2017, 9999, -9999 | 4,5 |\n * | | | RR | -43, 01, 00, 17 | 4,5 |\n * | | | RRR | -043, 001, 123, 999, -999 | 4,5 |\n * | | | RRRR | -0043, 0001, 2017, 9999, -9999 | 4,5 |\n * | | | RRRRR | ... | 2,4,5 |\n * | Extended year | 130 | u | -43, 1, 1900, 2017, 9999, -999 | 4 |\n * | | | uu | -43, 01, 99, -99 | 4 |\n * | | | uuu | -043, 001, 123, 999, -999 | 4 |\n * | | | uuuu | -0043, 0001, 2017, 9999, -9999 | 4 |\n * | | | uuuuu | ... | 2,4 |\n * | Quarter (formatting) | 120 | Q | 1, 2, 3, 4 | |\n * | | | Qo | 1st, 2nd, 3rd, 4th | 5 |\n * | | | QQ | 01, 02, 03, 04 | |\n * | | | QQQ | Q1, Q2, Q3, Q4 | |\n * | | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |\n * | | | QQQQQ | 1, 2, 3, 4 | 4 |\n * | Quarter (stand-alone) | 120 | q | 1, 2, 3, 4 | |\n * | | | qo | 1st, 2nd, 3rd, 4th | 5 |\n * | | | qq | 01, 02, 03, 04 | |\n * | | | qqq | Q1, Q2, Q3, Q4 | |\n * | | | qqqq | 1st quarter, 2nd quarter, ... | 2 |\n * | | | qqqqq | 1, 2, 3, 4 | 3 |\n * | Month (formatting) | 110 | M | 1, 2, ..., 12 | |\n * | | | Mo | 1st, 2nd, ..., 12th | 5 |\n * | | | MM | 01, 02, ..., 12 | |\n * | | | MMM | Jan, Feb, ..., Dec | |\n * | | | MMMM | January, February, ..., December | 2 |\n * | | | MMMMM | J, F, ..., D | |\n * | Month (stand-alone) | 110 | L | 1, 2, ..., 12 | |\n * | | | Lo | 1st, 2nd, ..., 12th | 5 |\n * | | | LL | 01, 02, ..., 12 | |\n * | | | LLL | Jan, Feb, ..., Dec | |\n * | | | LLLL | January, February, ..., December | 2 |\n * | | | LLLLL | J, F, ..., D | |\n * | Local week of year | 100 | w | 1, 2, ..., 53 | |\n * | | | wo | 1st, 2nd, ..., 53th | 5 |\n * | | | ww | 01, 02, ..., 53 | |\n * | ISO week of year | 100 | I | 1, 2, ..., 53 | 5 |\n * | | | Io | 1st, 2nd, ..., 53th | 5 |\n * | | | II | 01, 02, ..., 53 | 5 |\n * | Day of month | 90 | d | 1, 2, ..., 31 | |\n * | | | do | 1st, 2nd, ..., 31st | 5 |\n * | | | dd | 01, 02, ..., 31 | |\n * | Day of year | 90 | D | 1, 2, ..., 365, 366 | 7 |\n * | | | Do | 1st, 2nd, ..., 365th, 366th | 5 |\n * | | | DD | 01, 02, ..., 365, 366 | 7 |\n * | | | DDD | 001, 002, ..., 365, 366 | |\n * | | | DDDD | ... | 2 |\n * | Day of week (formatting) | 90 | E..EEE | Mon, Tue, Wed, ..., Sun | |\n * | | | EEEE | Monday, Tuesday, ..., Sunday | 2 |\n * | | | EEEEE | M, T, W, T, F, S, S | |\n * | | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | ISO day of week (formatting) | 90 | i | 1, 2, 3, ..., 7 | 5 |\n * | | | io | 1st, 2nd, ..., 7th | 5 |\n * | | | ii | 01, 02, ..., 07 | 5 |\n * | | | iii | Mon, Tue, Wed, ..., Sun | 5 |\n * | | | iiii | Monday, Tuesday, ..., Sunday | 2,5 |\n * | | | iiiii | M, T, W, T, F, S, S | 5 |\n * | | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 5 |\n * | Local day of week (formatting) | 90 | e | 2, 3, 4, ..., 1 | |\n * | | | eo | 2nd, 3rd, ..., 1st | 5 |\n * | | | ee | 02, 03, ..., 01 | |\n * | | | eee | Mon, Tue, Wed, ..., Sun | |\n * | | | eeee | Monday, Tuesday, ..., Sunday | 2 |\n * | | | eeeee | M, T, W, T, F, S, S | |\n * | | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | Local day of week (stand-alone) | 90 | c | 2, 3, 4, ..., 1 | |\n * | | | co | 2nd, 3rd, ..., 1st | 5 |\n * | | | cc | 02, 03, ..., 01 | |\n * | | | ccc | Mon, Tue, Wed, ..., Sun | |\n * | | | cccc | Monday, Tuesday, ..., Sunday | 2 |\n * | | | ccccc | M, T, W, T, F, S, S | |\n * | | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | AM, PM | 80 | a..aaa | AM, PM | |\n * | | | aaaa | a.m., p.m. | 2 |\n * | | | aaaaa | a, p | |\n * | AM, PM, noon, midnight | 80 | b..bbb | AM, PM, noon, midnight | |\n * | | | bbbb | a.m., p.m., noon, midnight | 2 |\n * | | | bbbbb | a, p, n, mi | |\n * | Flexible day period | 80 | B..BBB | at night, in the morning, ... | |\n * | | | BBBB | at night, in the morning, ... | 2 |\n * | | | BBBBB | at night, in the morning, ... | |\n * | Hour [1-12] | 70 | h | 1, 2, ..., 11, 12 | |\n * | | | ho | 1st, 2nd, ..., 11th, 12th | 5 |\n * | | | hh | 01, 02, ..., 11, 12 | |\n * | Hour [0-23] | 70 | H | 0, 1, 2, ..., 23 | |\n * | | | Ho | 0th, 1st, 2nd, ..., 23rd | 5 |\n * | | | HH | 00, 01, 02, ..., 23 | |\n * | Hour [0-11] | 70 | K | 1, 2, ..., 11, 0 | |\n * | | | Ko | 1st, 2nd, ..., 11th, 0th | 5 |\n * | | | KK | 01, 02, ..., 11, 00 | |\n * | Hour [1-24] | 70 | k | 24, 1, 2, ..., 23 | |\n * | | | ko | 24th, 1st, 2nd, ..., 23rd | 5 |\n * | | | kk | 24, 01, 02, ..., 23 | |\n * | Minute | 60 | m | 0, 1, ..., 59 | |\n * | | | mo | 0th, 1st, ..., 59th | 5 |\n * | | | mm | 00, 01, ..., 59 | |\n * | Second | 50 | s | 0, 1, ..., 59 | |\n * | | | so | 0th, 1st, ..., 59th | 5 |\n * | | | ss | 00, 01, ..., 59 | |\n * | Seconds timestamp | 40 | t | 512969520 | |\n * | | | tt | ... | 2 |\n * | Fraction of second | 30 | S | 0, 1, ..., 9 | |\n * | | | SS | 00, 01, ..., 99 | |\n * | | | SSS | 000, 001, ..., 999 | |\n * | | | SSSS | ... | 2 |\n * | Milliseconds timestamp | 20 | T | 512969520900 | |\n * | | | TT | ... | 2 |\n * | Timezone (ISO-8601 w/ Z) | 10 | X | -08, +0530, Z | |\n * | | | XX | -0800, +0530, Z | |\n * | | | XXX | -08:00, +05:30, Z | |\n * | | | XXXX | -0800, +0530, Z, +123456 | 2 |\n * | | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |\n * | Timezone (ISO-8601 w/o Z) | 10 | x | -08, +0530, +00 | |\n * | | | xx | -0800, +0530, +0000 | |\n * | | | xxx | -08:00, +05:30, +00:00 | 2 |\n * | | | xxxx | -0800, +0530, +0000, +123456 | |\n * | | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |\n * | Long localized date | NA | P | 05/29/1453 | 5,8 |\n * | | | PP | May 29, 1453 | |\n * | | | PPP | May 29th, 1453 | |\n * | | | PPPP | Sunday, May 29th, 1453 | 2,5,8 |\n * | Long localized time | NA | p | 12:00 AM | 5,8 |\n * | | | pp | 12:00:00 AM | |\n * | Combination of date and time | NA | Pp | 05/29/1453, 12:00 AM | |\n * | | | PPpp | May 29, 1453, 12:00:00 AM | |\n * | | | PPPpp | May 29th, 1453 at ... | |\n * | | | PPPPpp | Sunday, May 29th, 1453 at ... | 2,5,8 |\n * Notes:\n * 1. \"Formatting\" units (e.g. formatting quarter) in the default en-US locale\n * are the same as \"stand-alone\" units, but are different in some languages.\n * \"Formatting\" units are declined according to the rules of the language\n * in the context of a date. \"Stand-alone\" units are always nominative singular.\n * In `format` function, they will produce different result:\n *\n * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`\n *\n * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`\n *\n * `parse` will try to match both formatting and stand-alone units interchangeably.\n *\n * 2. Any sequence of the identical letters is a pattern, unless it is escaped by\n * the single quote characters (see below).\n * If the sequence is longer than listed in table:\n * - for numerical units (`yyyyyyyy`) `parse` will try to match a number\n * as wide as the sequence\n * - for text units (`MMMMMMMM`) `parse` will try to match the widest variation of the unit.\n * These variations are marked with \"2\" in the last column of the table.\n *\n * 3. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.\n * These tokens represent the shortest form of the quarter.\n *\n * 4. The main difference between `y` and `u` patterns are B.C. years:\n *\n * | Year | `y` | `u` |\n * |------|-----|-----|\n * | AC 1 | 1 | 1 |\n * | BC 1 | 1 | 0 |\n * | BC 2 | 2 | -1 |\n *\n * Also `yy` will try to guess the century of two digit year by proximity with `referenceDate`:\n *\n * `parse('50', 'yy', new Date(2018, 0, 1)) //=> Sat Jan 01 2050 00:00:00`\n *\n * `parse('75', 'yy', new Date(2018, 0, 1)) //=> Wed Jan 01 1975 00:00:00`\n *\n * while `uu` will just assign the year as is:\n *\n * `parse('50', 'uu', new Date(2018, 0, 1)) //=> Sat Jan 01 0050 00:00:00`\n *\n * `parse('75', 'uu', new Date(2018, 0, 1)) //=> Tue Jan 01 0075 00:00:00`\n *\n * The same difference is true for local and ISO week-numbering years (`Y` and `R`),\n * except local week-numbering years are dependent on `options.weekStartsOn`\n * and `options.firstWeekContainsDate` (compare [setISOWeekYear](https://date-fns.org/docs/setISOWeekYear)\n * and [setWeekYear](https://date-fns.org/docs/setWeekYear)).\n *\n * 5. These patterns are not in the Unicode Technical Standard #35:\n * - `i`: ISO day of week\n * - `I`: ISO week of year\n * - `R`: ISO week-numbering year\n * - `o`: ordinal number modifier\n * - `P`: long localized date\n * - `p`: long localized time\n *\n * 6. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.\n * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * 7. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.\n * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * 8. `P+` tokens do not have a defined priority since they are merely aliases to other tokens based\n * on the given locale.\n *\n * using `en-US` locale: `P` => `MM/dd/yyyy`\n * using `en-US` locale: `p` => `hh:mm a`\n * using `pt-BR` locale: `P` => `dd/MM/yyyy`\n * using `pt-BR` locale: `p` => `HH:mm`\n *\n * Values will be assigned to the date in the descending order of its unit's priority.\n * Units of an equal priority overwrite each other in the order of appearance.\n *\n * If no values of higher priority are parsed (e.g. when parsing string 'January 1st' without a year),\n * the values will be taken from 3rd argument `referenceDate` which works as a context of parsing.\n *\n * `referenceDate` must be passed for correct work of the function.\n * If you're not sure which `referenceDate` to supply, create a new instance of Date:\n * `parse('02/11/2014', 'MM/dd/yyyy', new Date())`\n * In this case parsing will be done in the context of the current date.\n * If `referenceDate` is `Invalid Date` or a value not convertible to valid `Date`,\n * then `Invalid Date` will be returned.\n *\n * The result may vary by locale.\n *\n * If `formatString` matches with `dateString` but does not provides tokens, `referenceDate` will be returned.\n *\n * If parsing failed, `Invalid Date` will be returned.\n * Invalid Date is a Date, whose time value is NaN.\n * Time value of Date: http://es5.github.io/#x15.9.1.1\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param dateStr - The string to parse\n * @param formatStr - The string of tokens\n * @param referenceDate - defines values missing from the parsed dateString\n * @param options - An object with options.\n * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * @returns The parsed date\n *\n * @throws `options.locale` must contain `match` property\n * @throws use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws format string contains an unescaped latin alphabet character\n *\n * @example\n * // Parse 11 February 2014 from middle-endian format:\n * var result = parse('02/11/2014', 'MM/dd/yyyy', new Date())\n * //=> Tue Feb 11 2014 00:00:00\n *\n * @example\n * // Parse 28th of February in Esperanto locale in the context of 2010 year:\n * import eo from 'date-fns/locale/eo'\n * var result = parse('28-a de februaro', \"do 'de' MMMM\", new Date(2010, 0, 1), {\n * locale: eo\n * })\n * //=> Sun Feb 28 2010 00:00:00\n */\nfunction parse(dateStr, formatStr, referenceDate, options) {\n const invalidDate = () =>\n (0, _index4.constructFrom)(options?.in || referenceDate, NaN);\n const defaultOptions = (0, _index5.getDefaultOptions)();\n const locale =\n options?.locale ?? defaultOptions.locale ?? _index.defaultLocale;\n\n const firstWeekContainsDate =\n options?.firstWeekContainsDate ??\n options?.locale?.options?.firstWeekContainsDate ??\n defaultOptions.firstWeekContainsDate ??\n defaultOptions.locale?.options?.firstWeekContainsDate ??\n 1;\n\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n if (!formatStr)\n return dateStr\n ? invalidDate()\n : (0, _index6.toDate)(referenceDate, options?.in);\n\n const subFnOptions = {\n firstWeekContainsDate,\n weekStartsOn,\n locale,\n };\n\n // If timezone isn't specified, it will try to use the context or\n // the reference date and fallback to the system time zone.\n const setters = [new _Setter.DateTimezoneSetter(options?.in, referenceDate)];\n\n const tokens = formatStr\n .match(longFormattingTokensRegExp)\n .map((substring) => {\n const firstCharacter = substring[0];\n if (firstCharacter in _index2.longFormatters) {\n const longFormatter = _index2.longFormatters[firstCharacter];\n return longFormatter(substring, locale.formatLong);\n }\n return substring;\n })\n .join(\"\")\n .match(formattingTokensRegExp);\n\n const usedTokens = [];\n\n for (let token of tokens) {\n if (\n !options?.useAdditionalWeekYearTokens &&\n (0, _index3.isProtectedWeekYearToken)(token)\n ) {\n (0, _index3.warnOrThrowProtectedError)(token, formatStr, dateStr);\n }\n if (\n !options?.useAdditionalDayOfYearTokens &&\n (0, _index3.isProtectedDayOfYearToken)(token)\n ) {\n (0, _index3.warnOrThrowProtectedError)(token, formatStr, dateStr);\n }\n\n const firstCharacter = token[0];\n const parser = _index7.parsers[firstCharacter];\n if (parser) {\n const { incompatibleTokens } = parser;\n if (Array.isArray(incompatibleTokens)) {\n const incompatibleToken = usedTokens.find(\n (usedToken) =>\n incompatibleTokens.includes(usedToken.token) ||\n usedToken.token === firstCharacter,\n );\n if (incompatibleToken) {\n throw new RangeError(\n `The format string mustn't contain \\`${incompatibleToken.fullToken}\\` and \\`${token}\\` at the same time`,\n );\n }\n } else if (parser.incompatibleTokens === \"*\" && usedTokens.length > 0) {\n throw new RangeError(\n `The format string mustn't contain \\`${token}\\` and any other token at the same time`,\n );\n }\n\n usedTokens.push({ token: firstCharacter, fullToken: token });\n\n const parseResult = parser.run(\n dateStr,\n token,\n locale.match,\n subFnOptions,\n );\n\n if (!parseResult) {\n return invalidDate();\n }\n\n setters.push(parseResult.setter);\n\n dateStr = parseResult.rest;\n } else {\n if (firstCharacter.match(unescapedLatinCharacterRegExp)) {\n throw new RangeError(\n \"Format string contains an unescaped latin alphabet character `\" +\n firstCharacter +\n \"`\",\n );\n }\n\n // Replace two single quote characters with one single quote character\n if (token === \"''\") {\n token = \"'\";\n } else if (firstCharacter === \"'\") {\n token = cleanEscapedString(token);\n }\n\n // Cut token from string, or, if string doesn't match the token, return Invalid Date\n if (dateStr.indexOf(token) === 0) {\n dateStr = dateStr.slice(token.length);\n } else {\n return invalidDate();\n }\n }\n }\n\n // Check if the remaining input contains something other than whitespace\n if (dateStr.length > 0 && notWhitespaceRegExp.test(dateStr)) {\n return invalidDate();\n }\n\n const uniquePrioritySetters = setters\n .map((setter) => setter.priority)\n .sort((a, b) => b - a)\n .filter((priority, index, array) => array.indexOf(priority) === index)\n .map((priority) =>\n setters\n .filter((setter) => setter.priority === priority)\n .sort((a, b) => b.subPriority - a.subPriority),\n )\n .map((setterArray) => setterArray[0]);\n\n let date = (0, _index6.toDate)(referenceDate, options?.in);\n\n if (isNaN(+date)) return invalidDate();\n\n const flags = {};\n for (const setter of uniquePrioritySetters) {\n if (!setter.validate(date, subFnOptions)) {\n return invalidDate();\n }\n\n const result = setter.set(date, flags, subFnOptions);\n // Result is tuple (date, flags)\n if (Array.isArray(result)) {\n date = result[0];\n Object.assign(flags, result[1]);\n // Result is date\n } else {\n date = result;\n }\n }\n\n return date;\n}\n\nfunction cleanEscapedString(input) {\n return input.match(escapedStringRegExp)[1].replace(doubleQuoteRegExp, \"'\");\n}\n", "\"use strict\";\nexports.isMatch = isMatch;\nvar _index = require(\"./isValid.cjs\");\nvar _index2 = require(\"./parse.cjs\");\n\n/**\n * The {@link isMatch} function options.\n */\n\n/**\n * @name isMatch\n * @category Common Helpers\n * @summary validates the date string against given formats\n *\n * @description\n * Return the true if given date is string correct against the given format else\n * will return false.\n *\n * > \u26A0\uFE0F Please note that the `format` tokens differ from Moment.js and other libraries.\n * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * The characters in the format string wrapped between two single quotes characters (') are escaped.\n * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.\n *\n * Format of the format string is based on Unicode Technical Standard #35:\n * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n * with a few additions (see note 5 below the table).\n *\n * Not all tokens are compatible. Combinations that don't make sense or could lead to bugs are prohibited\n * and will throw `RangeError`. For example usage of 24-hour format token with AM/PM token will throw an exception:\n *\n * ```javascript\n * isMatch('23 AM', 'HH a')\n * //=> RangeError: The format string mustn't contain `HH` and `a` at the same time\n * ```\n *\n * See the compatibility table: https://docs.google.com/spreadsheets/d/e/2PACX-1vQOPU3xUhplll6dyoMmVUXHKl_8CRDs6_ueLmex3SoqwhuolkuN3O05l4rqx5h1dKX8eb46Ul-CCSrq/pubhtml?gid=0&single=true\n *\n * Accepted format string patterns:\n * | Unit |Prior| Pattern | Result examples | Notes |\n * |---------------------------------|-----|---------|-----------------------------------|-------|\n * | Era | 140 | G..GGG | AD, BC | |\n * | | | GGGG | Anno Domini, Before Christ | 2 |\n * | | | GGGGG | A, B | |\n * | Calendar year | 130 | y | 44, 1, 1900, 2017, 9999 | 4 |\n * | | | yo | 44th, 1st, 1900th, 9999999th | 4,5 |\n * | | | yy | 44, 01, 00, 17 | 4 |\n * | | | yyy | 044, 001, 123, 999 | 4 |\n * | | | yyyy | 0044, 0001, 1900, 2017 | 4 |\n * | | | yyyyy | ... | 2,4 |\n * | Local week-numbering year | 130 | Y | 44, 1, 1900, 2017, 9000 | 4 |\n * | | | Yo | 44th, 1st, 1900th, 9999999th | 4,5 |\n * | | | YY | 44, 01, 00, 17 | 4,6 |\n * | | | YYY | 044, 001, 123, 999 | 4 |\n * | | | YYYY | 0044, 0001, 1900, 2017 | 4,6 |\n * | | | YYYYY | ... | 2,4 |\n * | ISO week-numbering year | 130 | R | -43, 1, 1900, 2017, 9999, -9999 | 4,5 |\n * | | | RR | -43, 01, 00, 17 | 4,5 |\n * | | | RRR | -043, 001, 123, 999, -999 | 4,5 |\n * | | | RRRR | -0043, 0001, 2017, 9999, -9999 | 4,5 |\n * | | | RRRRR | ... | 2,4,5 |\n * | Extended year | 130 | u | -43, 1, 1900, 2017, 9999, -999 | 4 |\n * | | | uu | -43, 01, 99, -99 | 4 |\n * | | | uuu | -043, 001, 123, 999, -999 | 4 |\n * | | | uuuu | -0043, 0001, 2017, 9999, -9999 | 4 |\n * | | | uuuuu | ... | 2,4 |\n * | Quarter (formatting) | 120 | Q | 1, 2, 3, 4 | |\n * | | | Qo | 1st, 2nd, 3rd, 4th | 5 |\n * | | | QQ | 01, 02, 03, 04 | |\n * | | | QQQ | Q1, Q2, Q3, Q4 | |\n * | | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |\n * | | | QQQQQ | 1, 2, 3, 4 | 4 |\n * | Quarter (stand-alone) | 120 | q | 1, 2, 3, 4 | |\n * | | | qo | 1st, 2nd, 3rd, 4th | 5 |\n * | | | qq | 01, 02, 03, 04 | |\n * | | | qqq | Q1, Q2, Q3, Q4 | |\n * | | | qqqq | 1st quarter, 2nd quarter, ... | 2 |\n * | | | qqqqq | 1, 2, 3, 4 | 3 |\n * | Month (formatting) | 110 | M | 1, 2, ..., 12 | |\n * | | | Mo | 1st, 2nd, ..., 12th | 5 |\n * | | | MM | 01, 02, ..., 12 | |\n * | | | MMM | Jan, Feb, ..., Dec | |\n * | | | MMMM | January, February, ..., December | 2 |\n * | | | MMMMM | J, F, ..., D | |\n * | Month (stand-alone) | 110 | L | 1, 2, ..., 12 | |\n * | | | Lo | 1st, 2nd, ..., 12th | 5 |\n * | | | LL | 01, 02, ..., 12 | |\n * | | | LLL | Jan, Feb, ..., Dec | |\n * | | | LLLL | January, February, ..., December | 2 |\n * | | | LLLLL | J, F, ..., D | |\n * | Local week of year | 100 | w | 1, 2, ..., 53 | |\n * | | | wo | 1st, 2nd, ..., 53th | 5 |\n * | | | ww | 01, 02, ..., 53 | |\n * | ISO week of year | 100 | I | 1, 2, ..., 53 | 5 |\n * | | | Io | 1st, 2nd, ..., 53th | 5 |\n * | | | II | 01, 02, ..., 53 | 5 |\n * | Day of month | 90 | d | 1, 2, ..., 31 | |\n * | | | do | 1st, 2nd, ..., 31st | 5 |\n * | | | dd | 01, 02, ..., 31 | |\n * | Day of year | 90 | D | 1, 2, ..., 365, 366 | 7 |\n * | | | Do | 1st, 2nd, ..., 365th, 366th | 5 |\n * | | | DD | 01, 02, ..., 365, 366 | 7 |\n * | | | DDD | 001, 002, ..., 365, 366 | |\n * | | | DDDD | ... | 2 |\n * | Day of week (formatting) | 90 | E..EEE | Mon, Tue, Wed, ..., Su | |\n * | | | EEEE | Monday, Tuesday, ..., Sunday | 2 |\n * | | | EEEEE | M, T, W, T, F, S, S | |\n * | | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | ISO day of week (formatting) | 90 | i | 1, 2, 3, ..., 7 | 5 |\n * | | | io | 1st, 2nd, ..., 7th | 5 |\n * | | | ii | 01, 02, ..., 07 | 5 |\n * | | | iii | Mon, Tue, Wed, ..., Su | 5 |\n * | | | iiii | Monday, Tuesday, ..., Sunday | 2,5 |\n * | | | iiiii | M, T, W, T, F, S, S | 5 |\n * | | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 5 |\n * | Local day of week (formatting) | 90 | e | 2, 3, 4, ..., 1 | |\n * | | | eo | 2nd, 3rd, ..., 1st | 5 |\n * | | | ee | 02, 03, ..., 01 | |\n * | | | eee | Mon, Tue, Wed, ..., Su | |\n * | | | eeee | Monday, Tuesday, ..., Sunday | 2 |\n * | | | eeeee | M, T, W, T, F, S, S | |\n * | | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | Local day of week (stand-alone) | 90 | c | 2, 3, 4, ..., 1 | |\n * | | | co | 2nd, 3rd, ..., 1st | 5 |\n * | | | cc | 02, 03, ..., 01 | |\n * | | | ccc | Mon, Tue, Wed, ..., Su | |\n * | | | cccc | Monday, Tuesday, ..., Sunday | 2 |\n * | | | ccccc | M, T, W, T, F, S, S | |\n * | | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | AM, PM | 80 | a..aaa | AM, PM | |\n * | | | aaaa | a.m., p.m. | 2 |\n * | | | aaaaa | a, p | |\n * | AM, PM, noon, midnight | 80 | b..bbb | AM, PM, noon, midnight | |\n * | | | bbbb | a.m., p.m., noon, midnight | 2 |\n * | | | bbbbb | a, p, n, mi | |\n * | Flexible day period | 80 | B..BBB | at night, in the morning, ... | |\n * | | | BBBB | at night, in the morning, ... | 2 |\n * | | | BBBBB | at night, in the morning, ... | |\n * | Hour [1-12] | 70 | h | 1, 2, ..., 11, 12 | |\n * | | | ho | 1st, 2nd, ..., 11th, 12th | 5 |\n * | | | hh | 01, 02, ..., 11, 12 | |\n * | Hour [0-23] | 70 | H | 0, 1, 2, ..., 23 | |\n * | | | Ho | 0th, 1st, 2nd, ..., 23rd | 5 |\n * | | | HH | 00, 01, 02, ..., 23 | |\n * | Hour [0-11] | 70 | K | 1, 2, ..., 11, 0 | |\n * | | | Ko | 1st, 2nd, ..., 11th, 0th | 5 |\n * | | | KK | 01, 02, ..., 11, 00 | |\n * | Hour [1-24] | 70 | k | 24, 1, 2, ..., 23 | |\n * | | | ko | 24th, 1st, 2nd, ..., 23rd | 5 |\n * | | | kk | 24, 01, 02, ..., 23 | |\n * | Minute | 60 | m | 0, 1, ..., 59 | |\n * | | | mo | 0th, 1st, ..., 59th | 5 |\n * | | | mm | 00, 01, ..., 59 | |\n * | Second | 50 | s | 0, 1, ..., 59 | |\n * | | | so | 0th, 1st, ..., 59th | 5 |\n * | | | ss | 00, 01, ..., 59 | |\n * | Seconds timestamp | 40 | t | 512969520 | |\n * | | | tt | ... | 2 |\n * | Fraction of second | 30 | S | 0, 1, ..., 9 | |\n * | | | SS | 00, 01, ..., 99 | |\n * | | | SSS | 000, 001, ..., 999 | |\n * | | | SSSS | ... | 2 |\n * | Milliseconds timestamp | 20 | T | 512969520900 | |\n * | | | TT | ... | 2 |\n * | Timezone (ISO-8601 w/ Z) | 10 | X | -08, +0530, Z | |\n * | | | XX | -0800, +0530, Z | |\n * | | | XXX | -08:00, +05:30, Z | |\n * | | | XXXX | -0800, +0530, Z, +123456 | 2 |\n * | | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |\n * | Timezone (ISO-8601 w/o Z) | 10 | x | -08, +0530, +00 | |\n * | | | xx | -0800, +0530, +0000 | |\n * | | | xxx | -08:00, +05:30, +00:00 | 2 |\n * | | | xxxx | -0800, +0530, +0000, +123456 | |\n * | | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |\n * | Long localized date | NA | P | 05/29/1453 | 5,8 |\n * | | | PP | May 29, 1453 | |\n * | | | PPP | May 29th, 1453 | |\n * | | | PPPP | Sunday, May 29th, 1453 | 2,5,8 |\n * | Long localized time | NA | p | 12:00 AM | 5,8 |\n * | | | pp | 12:00:00 AM | |\n * | Combination of date and time | NA | Pp | 05/29/1453, 12:00 AM | |\n * | | | PPpp | May 29, 1453, 12:00:00 AM | |\n * | | | PPPpp | May 29th, 1453 at ... | |\n * | | | PPPPpp | Sunday, May 29th, 1453 at ... | 2,5,8 |\n * Notes:\n * 1. \"Formatting\" units (e.g. formatting quarter) in the default en-US locale\n * are the same as \"stand-alone\" units, but are different in some languages.\n * \"Formatting\" units are declined according to the rules of the language\n * in the context of a date. \"Stand-alone\" units are always nominative singular.\n * In `format` function, they will produce different result:\n *\n * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`\n *\n * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`\n *\n * `isMatch` will try to match both formatting and stand-alone units interchangeably.\n *\n * 2. Any sequence of the identical letters is a pattern, unless it is escaped by\n * the single quote characters (see below).\n * If the sequence is longer than listed in table:\n * - for numerical units (`yyyyyyyy`) `isMatch` will try to match a number\n * as wide as the sequence\n * - for text units (`MMMMMMMM`) `isMatch` will try to match the widest variation of the unit.\n * These variations are marked with \"2\" in the last column of the table.\n *\n * 3. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.\n * These tokens represent the shortest form of the quarter.\n *\n * 4. The main difference between `y` and `u` patterns are B.C. years:\n *\n * | Year | `y` | `u` |\n * |------|-----|-----|\n * | AC 1 | 1 | 1 |\n * | BC 1 | 1 | 0 |\n * | BC 2 | 2 | -1 |\n *\n * Also `yy` will try to guess the century of two digit year by proximity with `referenceDate`:\n *\n * `isMatch('50', 'yy') //=> true`\n *\n * `isMatch('75', 'yy') //=> true`\n *\n * while `uu` will use the year as is:\n *\n * `isMatch('50', 'uu') //=> true`\n *\n * `isMatch('75', 'uu') //=> true`\n *\n * The same difference is true for local and ISO week-numbering years (`Y` and `R`),\n * except local week-numbering years are dependent on `options.weekStartsOn`\n * and `options.firstWeekContainsDate` (compare [setISOWeekYear](https://date-fns.org/docs/setISOWeekYear)\n * and [setWeekYear](https://date-fns.org/docs/setWeekYear)).\n *\n * 5. These patterns are not in the Unicode Technical Standard #35:\n * - `i`: ISO day of week\n * - `I`: ISO week of year\n * - `R`: ISO week-numbering year\n * - `o`: ordinal number modifier\n * - `P`: long localized date\n * - `p`: long localized time\n *\n * 6. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.\n * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * 7. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.\n * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * 8. `P+` tokens do not have a defined priority since they are merely aliases to other tokens based\n * on the given locale.\n *\n * using `en-US` locale: `P` => `MM/dd/yyyy`\n * using `en-US` locale: `p` => `hh:mm a`\n * using `pt-BR` locale: `P` => `dd/MM/yyyy`\n * using `pt-BR` locale: `p` => `HH:mm`\n *\n * Values will be checked in the descending order of its unit's priority.\n * Units of an equal priority overwrite each other in the order of appearance.\n *\n * If no values of higher priority are matched (e.g. when matching string 'January 1st' without a year),\n * the values will be taken from today's using `new Date()` date which works as a context of parsing.\n *\n * The result may vary by locale.\n *\n * If `formatString` matches with `dateString` but does not provides tokens, `referenceDate` will be returned.\n *\n * @param dateStr - The date string to verify\n * @param format - The string of tokens\n * @param options - An object with options.\n * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * @returns Is format string a match for date string?\n *\n * @throws `options.locale` must contain `match` property\n * @throws use `yyyy` instead of `YYYY` for formatting years; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `yy` instead of `YY` for formatting years; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `d` instead of `D` for formatting days of the month; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `dd` instead of `DD` for formatting days of the month; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws format string contains an unescaped latin alphabet character\n *\n * @example\n * // Match 11 February 2014 from middle-endian format:\n * const result = isMatch('02/11/2014', 'MM/dd/yyyy')\n * //=> true\n *\n * @example\n * // Match 28th of February in Esperanto locale in the context of 2010 year:\n * import eo from 'date-fns/locale/eo'\n * const result = isMatch('28-a de februaro', \"do 'de' MMMM\", {\n * locale: eo\n * })\n * //=> true\n */\nfunction isMatch(dateStr, formatStr, options) {\n return (0, _index.isValid)(\n (0, _index2.parse)(dateStr, formatStr, new Date(), options),\n );\n}\n", "\"use strict\";\nexports.isMonday = isMonday;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isMonday} function options.\n */\n\n/**\n * @name isMonday\n * @category Weekday Helpers\n * @summary Is the given date Monday?\n *\n * @description\n * Is the given date Monday?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is Monday\n *\n * @example\n * // Is 22 September 2014 Monday?\n * const result = isMonday(new Date(2014, 8, 22))\n * //=> true\n */\nfunction isMonday(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay() === 1;\n}\n", "\"use strict\";\nexports.isPast = isPast;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name isPast\n * @category Common Helpers\n * @summary Is the given date in the past?\n * @pure false\n *\n * @description\n * Is the given date in the past?\n *\n * @param date - The date to check\n *\n * @returns The date is in the past\n *\n * @example\n * // If today is 6 October 2014, is 2 July 2014 in the past?\n * const result = isPast(new Date(2014, 6, 2))\n * //=> true\n */\nfunction isPast(date) {\n return +(0, _index.toDate)(date) < Date.now();\n}\n", "\"use strict\";\nexports.startOfHour = startOfHour;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfHour} function options.\n */\n\n/**\n * @name startOfHour\n * @category Hour Helpers\n * @summary Return the start of an hour for the given date.\n *\n * @description\n * Return the start of an hour for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of an hour\n *\n * @example\n * // The start of an hour for 2 September 2014 11:55:00:\n * const result = startOfHour(new Date(2014, 8, 2, 11, 55))\n * //=> Tue Sep 02 2014 11:00:00\n */\nfunction startOfHour(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setMinutes(0, 0, 0);\n return _date;\n}\n", "\"use strict\";\nexports.isSameHour = isSameHour;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./startOfHour.cjs\");\n\n/**\n * The {@link isSameHour} function options.\n */\n\n/**\n * @name isSameHour\n * @category Hour Helpers\n * @summary Are the given dates in the same hour (and same day)?\n *\n * @description\n * Are the given dates in the same hour (and same day)?\n *\n * @param dateLeft - The first date to check\n * @param dateRight - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same hour (and same day)\n *\n * @example\n * // Are 4 September 2014 06:00:00 and 4 September 06:30:00 in the same hour?\n * const result = isSameHour(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 4, 6, 30))\n * //=> true\n *\n * @example\n * // Are 4 September 2014 06:00:00 and 5 September 06:00:00 in the same hour?\n * const result = isSameHour(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 5, 6, 0))\n * //=> false\n */\nfunction isSameHour(dateLeft, dateRight, options) {\n const [dateLeft_, dateRight_] = (0, _index.normalizeDates)(\n options?.in,\n dateLeft,\n dateRight,\n );\n return (\n +(0, _index2.startOfHour)(dateLeft_) ===\n +(0, _index2.startOfHour)(dateRight_)\n );\n}\n", "\"use strict\";\nexports.isSameWeek = isSameWeek;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./startOfWeek.cjs\");\n\n/**\n * The {@link isSameWeek} function options.\n */\n\n/**\n * @name isSameWeek\n * @category Week Helpers\n * @summary Are the given dates in the same week (and month and year)?\n *\n * @description\n * Are the given dates in the same week (and month and year)?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same week (and month and year)\n *\n * @example\n * // Are 31 August 2014 and 4 September 2014 in the same week?\n * const result = isSameWeek(new Date(2014, 7, 31), new Date(2014, 8, 4))\n * //=> true\n *\n * @example\n * // If week starts with Monday,\n * // are 31 August 2014 and 4 September 2014 in the same week?\n * const result = isSameWeek(new Date(2014, 7, 31), new Date(2014, 8, 4), {\n * weekStartsOn: 1\n * })\n * //=> false\n *\n * @example\n * // Are 1 January 2014 and 1 January 2015 in the same week?\n * const result = isSameWeek(new Date(2014, 0, 1), new Date(2015, 0, 1))\n * //=> false\n */\nfunction isSameWeek(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return (\n +(0, _index2.startOfWeek)(laterDate_, options) ===\n +(0, _index2.startOfWeek)(earlierDate_, options)\n );\n}\n", "\"use strict\";\nexports.isSameISOWeek = isSameISOWeek;\nvar _index = require(\"./isSameWeek.cjs\");\n\n/**\n * The {@link isSameISOWeek} function options.\n */\n\n/**\n * @name isSameISOWeek\n * @category ISO Week Helpers\n * @summary Are the given dates in the same ISO week (and year)?\n *\n * @description\n * Are the given dates in the same ISO week (and year)?\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same ISO week (and year)\n *\n * @example\n * // Are 1 September 2014 and 7 September 2014 in the same ISO week?\n * const result = isSameISOWeek(new Date(2014, 8, 1), new Date(2014, 8, 7))\n * //=> true\n *\n * @example\n * // Are 1 September 2014 and 1 September 2015 in the same ISO week?\n * const result = isSameISOWeek(new Date(2014, 8, 1), new Date(2015, 8, 1))\n * //=> false\n */\nfunction isSameISOWeek(laterDate, earlierDate, options) {\n return (0, _index.isSameWeek)(laterDate, earlierDate, {\n ...options,\n weekStartsOn: 1,\n });\n}\n", "\"use strict\";\nexports.isSameISOWeekYear = isSameISOWeekYear;\nvar _index = require(\"./startOfISOWeekYear.cjs\");\n\nvar _index2 = require(\"./_lib/normalizeDates.cjs\");\n\n/**\n * The {@link isSameISOWeekYear} function options.\n */\n\n/**\n * @name isSameISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Are the given dates in the same ISO week-numbering year?\n *\n * @description\n * Are the given dates in the same ISO week-numbering year?\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same ISO week-numbering year\n *\n * @example\n * // Are 29 December 2003 and 2 January 2005 in the same ISO week-numbering year?\n * const result = isSameISOWeekYear(new Date(2003, 11, 29), new Date(2005, 0, 2))\n * //=> true\n */\nfunction isSameISOWeekYear(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index2.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return (\n +(0, _index.startOfISOWeekYear)(laterDate_) ===\n +(0, _index.startOfISOWeekYear)(earlierDate_)\n );\n}\n", "\"use strict\";\nexports.startOfMinute = startOfMinute;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfMinute} function options.\n */\n\n/**\n * @name startOfMinute\n * @category Minute Helpers\n * @summary Return the start of a minute for the given date.\n *\n * @description\n * Return the start of a minute for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of a minute\n *\n * @example\n * // The start of a minute for 1 December 2014 22:15:45.400:\n * const result = startOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400))\n * //=> Mon Dec 01 2014 22:15:00\n */\nfunction startOfMinute(date, options) {\n const date_ = (0, _index.toDate)(date, options?.in);\n date_.setSeconds(0, 0);\n return date_;\n}\n", "\"use strict\";\nexports.isSameMinute = isSameMinute;\nvar _index = require(\"./startOfMinute.cjs\");\n\n/**\n * @name isSameMinute\n * @category Minute Helpers\n * @summary Are the given dates in the same minute (and hour and day)?\n *\n * @description\n * Are the given dates in the same minute (and hour and day)?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n *\n * @returns The dates are in the same minute (and hour and day)\n *\n * @example\n * // Are 4 September 2014 06:30:00 and 4 September 2014 06:30:15 in the same minute?\n * const result = isSameMinute(\n * new Date(2014, 8, 4, 6, 30),\n * new Date(2014, 8, 4, 6, 30, 15)\n * )\n * //=> true\n *\n * @example\n * // Are 4 September 2014 06:30:00 and 5 September 2014 06:30:00 in the same minute?\n * const result = isSameMinute(\n * new Date(2014, 8, 4, 6, 30),\n * new Date(2014, 8, 5, 6, 30)\n * )\n * //=> false\n */\nfunction isSameMinute(laterDate, earlierDate) {\n return (\n +(0, _index.startOfMinute)(laterDate) ===\n +(0, _index.startOfMinute)(earlierDate)\n );\n}\n", "\"use strict\";\nexports.isSameMonth = isSameMonth;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\n\n/**\n * The {@link isSameMonth} function options.\n */\n\n/**\n * @name isSameMonth\n * @category Month Helpers\n * @summary Are the given dates in the same month (and year)?\n *\n * @description\n * Are the given dates in the same month (and year)?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same month (and year)\n *\n * @example\n * // Are 2 September 2014 and 25 September 2014 in the same month?\n * const result = isSameMonth(new Date(2014, 8, 2), new Date(2014, 8, 25))\n * //=> true\n *\n * @example\n * // Are 2 September 2014 and 25 September 2015 in the same month?\n * const result = isSameMonth(new Date(2014, 8, 2), new Date(2015, 8, 25))\n * //=> false\n */\nfunction isSameMonth(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return (\n laterDate_.getFullYear() === earlierDate_.getFullYear() &&\n laterDate_.getMonth() === earlierDate_.getMonth()\n );\n}\n", "\"use strict\";\nexports.isSameQuarter = isSameQuarter;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./startOfQuarter.cjs\");\n\n/**\n * The {@link isSameQuarter} function options.\n */\n\n/**\n * @name isSameQuarter\n * @category Quarter Helpers\n * @summary Are the given dates in the same quarter (and year)?\n *\n * @description\n * Are the given dates in the same quarter (and year)?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same quarter (and year)\n *\n * @example\n * // Are 1 January 2014 and 8 March 2014 in the same quarter?\n * const result = isSameQuarter(new Date(2014, 0, 1), new Date(2014, 2, 8))\n * //=> true\n *\n * @example\n * // Are 1 January 2014 and 1 January 2015 in the same quarter?\n * const result = isSameQuarter(new Date(2014, 0, 1), new Date(2015, 0, 1))\n * //=> false\n */\nfunction isSameQuarter(laterDate, earlierDate, options) {\n const [dateLeft_, dateRight_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return (\n +(0, _index2.startOfQuarter)(dateLeft_) ===\n +(0, _index2.startOfQuarter)(dateRight_)\n );\n}\n", "\"use strict\";\nexports.startOfSecond = startOfSecond;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfSecond} function options.\n */\n\n/**\n * @name startOfSecond\n * @category Second Helpers\n * @summary Return the start of a second for the given date.\n *\n * @description\n * Return the start of a second for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The start of a second\n *\n * @example\n * // The start of a second for 1 December 2014 22:15:45.400:\n * const result = startOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400))\n * //=> Mon Dec 01 2014 22:15:45.000\n */\nfunction startOfSecond(date, options) {\n const date_ = (0, _index.toDate)(date, options?.in);\n date_.setMilliseconds(0);\n return date_;\n}\n", "\"use strict\";\nexports.isSameSecond = isSameSecond;\nvar _index = require(\"./startOfSecond.cjs\");\n\n/**\n * @name isSameSecond\n * @category Second Helpers\n * @summary Are the given dates in the same second (and hour and day)?\n *\n * @description\n * Are the given dates in the same second (and hour and day)?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n *\n * @returns The dates are in the same second (and hour and day)\n *\n * @example\n * // Are 4 September 2014 06:30:15.000 and 4 September 2014 06:30.15.500 in the same second?\n * const result = isSameSecond(\n * new Date(2014, 8, 4, 6, 30, 15),\n * new Date(2014, 8, 4, 6, 30, 15, 500)\n * )\n * //=> true\n *\n * @example\n * // Are 4 September 2014 06:00:15.000 and 4 September 2014 06:01.15.000 in the same second?\n * const result = isSameSecond(\n * new Date(2014, 8, 4, 6, 0, 15),\n * new Date(2014, 8, 4, 6, 1, 15)\n * )\n * //=> false\n *\n * @example\n * // Are 4 September 2014 06:00:15.000 and 5 September 2014 06:00.15.000 in the same second?\n * const result = isSameSecond(\n * new Date(2014, 8, 4, 6, 0, 15),\n * new Date(2014, 8, 5, 6, 0, 15)\n * )\n * //=> false\n */\nfunction isSameSecond(laterDate, earlierDate) {\n return (\n +(0, _index.startOfSecond)(laterDate) ===\n +(0, _index.startOfSecond)(earlierDate)\n );\n}\n", "\"use strict\";\nexports.isSameYear = isSameYear;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\n\n/**\n * The {@link isSameYear} function options.\n */\n\n/**\n * @name isSameYear\n * @category Year Helpers\n * @summary Are the given dates in the same year?\n *\n * @description\n * Are the given dates in the same year?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same year\n *\n * @example\n * // Are 2 September 2014 and 25 September 2014 in the same year?\n * const result = isSameYear(new Date(2014, 8, 2), new Date(2014, 8, 25))\n * //=> true\n */\nfunction isSameYear(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return laterDate_.getFullYear() === earlierDate_.getFullYear();\n}\n", "\"use strict\";\nexports.isThisHour = isThisHour;\nvar _index = require(\"./constructNow.cjs\");\nvar _index2 = require(\"./isSameHour.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link isThisHour} function options.\n */\n\n/**\n * @name isThisHour\n * @category Hour Helpers\n * @summary Is the given date in the same hour as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same hour as the current date?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is in this hour\n *\n * @example\n * // If now is 25 September 2014 18:30:15.500,\n * // is 25 September 2014 18:00:00 in this hour?\n * const result = isThisHour(new Date(2014, 8, 25, 18))\n * //=> true\n */\nfunction isThisHour(date, options) {\n return (0, _index2.isSameHour)(\n (0, _index3.toDate)(date, options?.in),\n (0, _index.constructNow)(options?.in || date),\n );\n}\n", "\"use strict\";\nexports.isThisISOWeek = isThisISOWeek;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameISOWeek.cjs\");\n\n/**\n * The {@link isThisISOWeek} function options.\n */\n\n/**\n * @name isThisISOWeek\n * @category ISO Week Helpers\n * @summary Is the given date in the same ISO week as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same ISO week as the current date?\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is in this ISO week\n *\n * @example\n * // If today is 25 September 2014, is 22 September 2014 in this ISO week?\n * const result = isThisISOWeek(new Date(2014, 8, 22))\n * //=> true\n */\nfunction isThisISOWeek(date, options) {\n return (0, _index3.isSameISOWeek)(\n (0, _index.constructFrom)(options?.in || date, date),\n (0, _index2.constructNow)(options?.in || date),\n );\n}\n", "\"use strict\";\nexports.isThisMinute = isThisMinute;\nvar _index = require(\"./constructNow.cjs\");\nvar _index2 = require(\"./isSameMinute.cjs\");\n\n/**\n * @name isThisMinute\n * @category Minute Helpers\n * @summary Is the given date in the same minute as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same minute as the current date?\n *\n * @param date - The date to check\n *\n * @returns The date is in this minute\n *\n * @example\n * // If now is 25 September 2014 18:30:15.500,\n * // is 25 September 2014 18:30:00 in this minute?\n * const result = isThisMinute(new Date(2014, 8, 25, 18, 30))\n * //=> true\n */\n\nfunction isThisMinute(date) {\n return (0, _index2.isSameMinute)(date, (0, _index.constructNow)(date));\n}\n", "\"use strict\";\nexports.isThisMonth = isThisMonth;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameMonth.cjs\");\n\n/**\n * The {@link isThisMonth} function options.\n */\n\n/**\n * @name isThisMonth\n * @category Month Helpers\n * @summary Is the given date in the same month as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same month as the current date?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is in this month\n *\n * @example\n * // If today is 25 September 2014, is 15 September 2014 in this month?\n * const result = isThisMonth(new Date(2014, 8, 15))\n * //=> true\n */\nfunction isThisMonth(date, options) {\n return (0, _index3.isSameMonth)(\n (0, _index.constructFrom)(options?.in || date, date),\n (0, _index2.constructNow)(options?.in || date),\n );\n}\n", "\"use strict\";\nexports.isThisQuarter = isThisQuarter;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameQuarter.cjs\");\n\n/**\n * The {@link isThisQuarter} function options.\n */\n\n/**\n * @name isThisQuarter\n * @category Quarter Helpers\n * @summary Is the given date in the same quarter as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same quarter as the current date?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is in this quarter\n *\n * @example\n * // If today is 25 September 2014, is 2 July 2014 in this quarter?\n * const result = isThisQuarter(new Date(2014, 6, 2))\n * //=> true\n */\nfunction isThisQuarter(date, options) {\n return (0, _index3.isSameQuarter)(\n (0, _index.constructFrom)(options?.in || date, date),\n (0, _index2.constructNow)(options?.in || date),\n );\n}\n", "\"use strict\";\nexports.isThisSecond = isThisSecond;\nvar _index = require(\"./constructNow.cjs\");\nvar _index2 = require(\"./isSameSecond.cjs\");\n\n/**\n * @name isThisSecond\n * @category Second Helpers\n * @summary Is the given date in the same second as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same second as the current date?\n *\n * @param date - The date to check\n *\n * @returns The date is in this second\n *\n * @example\n * // If now is 25 September 2014 18:30:15.500,\n * // is 25 September 2014 18:30:15.000 in this second?\n * const result = isThisSecond(new Date(2014, 8, 25, 18, 30, 15))\n * //=> true\n */\nfunction isThisSecond(date) {\n return (0, _index2.isSameSecond)(date, (0, _index.constructNow)(date));\n}\n", "\"use strict\";\nexports.isThisWeek = isThisWeek;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameWeek.cjs\");\n\n/**\n * The {@link isThisWeek} function options.\n */\n\n/**\n * @name isThisWeek\n * @category Week Helpers\n * @summary Is the given date in the same week as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same week as the current date?\n *\n * @param date - The date to check\n * @param options - The object with options\n *\n * @returns The date is in this week\n *\n * @example\n * // If today is 25 September 2014, is 21 September 2014 in this week?\n * const result = isThisWeek(new Date(2014, 8, 21))\n * //=> true\n *\n * @example\n * // If today is 25 September 2014 and week starts with Monday\n * // is 21 September 2014 in this week?\n * const result = isThisWeek(new Date(2014, 8, 21), { weekStartsOn: 1 })\n * //=> false\n */\nfunction isThisWeek(date, options) {\n return (0, _index3.isSameWeek)(\n (0, _index.constructFrom)(options?.in || date, date),\n (0, _index2.constructNow)(options?.in || date),\n options,\n );\n}\n", "\"use strict\";\nexports.isThisYear = isThisYear;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameYear.cjs\");\n\n/**\n * The {@link isThisYear} function options.\n */\n\n/**\n * @name isThisYear\n * @category Year Helpers\n * @summary Is the given date in the same year as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same year as the current date?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is in this year\n *\n * @example\n * // If today is 25 September 2014, is 2 July 2014 in this year?\n * const result = isThisYear(new Date(2014, 6, 2))\n * //=> true\n */\nfunction isThisYear(date, options) {\n return (0, _index3.isSameYear)(\n (0, _index.constructFrom)(options?.in || date, date),\n (0, _index2.constructNow)(options?.in || date),\n );\n}\n", "\"use strict\";\nexports.isThursday = isThursday;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isThursday} function options.\n */\n\n/**\n * @name isThursday\n * @category Weekday Helpers\n * @summary Is the given date Thursday?\n *\n * @description\n * Is the given date Thursday?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is Thursday\n *\n * @example\n * // Is 25 September 2014 Thursday?\n * const result = isThursday(new Date(2014, 8, 25))\n * //=> true\n */\nfunction isThursday(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay() === 4;\n}\n", "\"use strict\";\nexports.isToday = isToday;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameDay.cjs\");\n\n/**\n * The {@link isToday} function options.\n */\n\n/**\n * @name isToday\n * @category Day Helpers\n * @summary Is the given date today?\n * @pure false\n *\n * @description\n * Is the given date today?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is today\n *\n * @example\n * // If today is 6 October 2014, is 6 October 14:00:00 today?\n * const result = isToday(new Date(2014, 9, 6, 14, 0))\n * //=> true\n */\nfunction isToday(date, options) {\n return (0, _index3.isSameDay)(\n (0, _index.constructFrom)(options?.in || date, date),\n (0, _index2.constructNow)(options?.in || date),\n );\n}\n", "\"use strict\";\nexports.isTomorrow = isTomorrow;\nvar _index = require(\"./addDays.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameDay.cjs\");\n\n/**\n * The {@link isTomorrow} function options.\n */\n\n/**\n * @name isTomorrow\n * @category Day Helpers\n * @summary Is the given date tomorrow?\n * @pure false\n *\n * @description\n * Is the given date tomorrow?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is tomorrow\n *\n * @example\n * // If today is 6 October 2014, is 7 October 14:00:00 tomorrow?\n * const result = isTomorrow(new Date(2014, 9, 7, 14, 0))\n * //=> true\n */\nfunction isTomorrow(date, options) {\n return (0, _index3.isSameDay)(\n date,\n (0, _index.addDays)((0, _index2.constructNow)(options?.in || date), 1),\n options,\n );\n}\n", "\"use strict\";\nexports.isTuesday = isTuesday;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isTuesday} function options.\n */\n\n/**\n * @name isTuesday\n * @category Weekday Helpers\n * @summary Is the given date Tuesday?\n *\n * @description\n * Is the given date Tuesday?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is Tuesday\n *\n * @example\n * // Is 23 September 2014 Tuesday?\n * const result = isTuesday(new Date(2014, 8, 23))\n * //=> true\n */\nfunction isTuesday(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay() === 2;\n}\n", "\"use strict\";\nexports.isWednesday = isWednesday;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isWednesday} function options.\n */\n\n/**\n * @name isWednesday\n * @category Weekday Helpers\n * @summary Is the given date Wednesday?\n *\n * @description\n * Is the given date Wednesday?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is Wednesday\n *\n * @example\n * // Is 24 September 2014 Wednesday?\n * const result = isWednesday(new Date(2014, 8, 24))\n * //=> true\n */\nfunction isWednesday(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay() === 3;\n}\n", "\"use strict\";\nexports.isWithinInterval = isWithinInterval;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isWithinInterval} function options.\n */\n\n/**\n * @name isWithinInterval\n * @category Interval Helpers\n * @summary Is the given date within the interval?\n *\n * @description\n * Is the given date within the interval? (Including start and end.)\n *\n * @param date - The date to check\n * @param interval - The interval to check\n * @param options - An object with options\n *\n * @returns The date is within the interval\n *\n * @example\n * // For the date within the interval:\n * isWithinInterval(new Date(2014, 0, 3), {\n * start: new Date(2014, 0, 1),\n * end: new Date(2014, 0, 7)\n * })\n * // => true\n *\n * @example\n * // For the date outside of the interval:\n * isWithinInterval(new Date(2014, 0, 10), {\n * start: new Date(2014, 0, 1),\n * end: new Date(2014, 0, 7)\n * })\n * // => false\n *\n * @example\n * // For date equal to the interval start:\n * isWithinInterval(date, { start, end: date })\n * // => true\n *\n * @example\n * // For date equal to the interval end:\n * isWithinInterval(date, { start: date, end })\n * // => true\n */\nfunction isWithinInterval(date, interval, options) {\n const time = +(0, _index.toDate)(date, options?.in);\n const [startTime, endTime] = [\n +(0, _index.toDate)(interval.start, options?.in),\n +(0, _index.toDate)(interval.end, options?.in),\n ].sort((a, b) => a - b);\n\n return time >= startTime && time <= endTime;\n}\n", "\"use strict\";\nexports.subDays = subDays;\nvar _index = require(\"./addDays.cjs\");\n\n/**\n * The {@link subDays} function options.\n */\n\n/**\n * @name subDays\n * @category Day Helpers\n * @summary Subtract the specified number of days from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of days to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the days subtracted\n *\n * @example\n * // Subtract 10 days from 1 September 2014:\n * const result = subDays(new Date(2014, 8, 1), 10)\n * //=> Fri Aug 22 2014 00:00:00\n */\nfunction subDays(date, amount, options) {\n return (0, _index.addDays)(date, -amount, options);\n}\n", "\"use strict\";\nexports.isYesterday = isYesterday;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameDay.cjs\");\nvar _index4 = require(\"./subDays.cjs\");\n\n/**\n * The {@link isYesterday} function options.\n */\n\n/**\n * @name isYesterday\n * @category Day Helpers\n * @summary Is the given date yesterday?\n * @pure false\n *\n * @description\n * Is the given date yesterday?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is yesterday\n *\n * @example\n * // If today is 6 October 2014, is 5 October 14:00:00 yesterday?\n * const result = isYesterday(new Date(2014, 9, 5, 14, 0))\n * //=> true\n */\nfunction isYesterday(date, options) {\n return (0, _index3.isSameDay)(\n (0, _index.constructFrom)(options?.in || date, date),\n (0, _index4.subDays)((0, _index2.constructNow)(options?.in || date), 1),\n );\n}\n", "\"use strict\";\nexports.lastDayOfDecade = lastDayOfDecade;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link lastDayOfDecade} function options.\n */\n\n/**\n * @name lastDayOfDecade\n * @category Decade Helpers\n * @summary Return the last day of a decade for the given date.\n *\n * @description\n * Return the last day of a decade for the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows using extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type; inferred from arguments or specified by context.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The last day of a decade\n *\n * @example\n * // The last day of a decade for 21 December 2012 21:12:00:\n * const result = lastDayOfDecade(new Date(2012, 11, 21, 21, 12, 00))\n * //=> Wed Dec 31 2019 00:00:00\n */\nfunction lastDayOfDecade(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const year = _date.getFullYear();\n const decade = 9 + Math.floor(year / 10) * 10;\n _date.setFullYear(decade + 1, 0, 0);\n _date.setHours(0, 0, 0, 0);\n return (0, _index.toDate)(_date, options?.in);\n}\n", "\"use strict\";\nexports.lastDayOfWeek = lastDayOfWeek;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link lastDayOfWeek} function options.\n */\n\n/**\n * @name lastDayOfWeek\n * @category Week Helpers\n * @summary Return the last day of a week for the given date.\n *\n * @description\n * Return the last day of a week for the given date.\n * The result will be in the local timezone unless a context is specified.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The last day of a week\n */\nfunction lastDayOfWeek(date, options) {\n const defaultOptions = (0, _index.getDefaultOptions)();\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const _date = (0, _index2.toDate)(date, options?.in);\n const day = _date.getDay();\n const diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);\n\n _date.setHours(0, 0, 0, 0);\n _date.setDate(_date.getDate() + diff);\n\n return _date;\n}\n", "\"use strict\";\nexports.lastDayOfISOWeek = lastDayOfISOWeek;\nvar _index = require(\"./lastDayOfWeek.cjs\");\n\n/**\n * The {@link lastDayOfISOWeek} function options.\n */\n\n/**\n * @name lastDayOfISOWeek\n * @category ISO Week Helpers\n * @summary Return the last day of an ISO week for the given date.\n *\n * @description\n * Return the last day of an ISO week for the given date.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The Date type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [UTCDate](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The last day of an ISO week\n *\n * @example\n * // The last day of an ISO week for 2 September 2014 11:55:00:\n * const result = lastDayOfISOWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Sun Sep 07 2014 00:00:00\n */\nfunction lastDayOfISOWeek(date, options) {\n return (0, _index.lastDayOfWeek)(date, { ...options, weekStartsOn: 1 });\n}\n", "\"use strict\";\nexports.lastDayOfISOWeekYear = lastDayOfISOWeekYear;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./getISOWeekYear.cjs\");\nvar _index3 = require(\"./startOfISOWeek.cjs\");\n\n/**\n * The {@link lastDayOfISOWeekYear} function options.\n */\n\n/**\n * @name lastDayOfISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Return the last day of an ISO week-numbering year for the given date.\n *\n * @description\n * Return the last day of an ISO week-numbering year,\n * which always starts 3 days before the year's first Thursday.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of an ISO week-numbering year\n *\n * @example\n * // The last day of an ISO week-numbering year for 2 July 2005:\n * const result = lastDayOfISOWeekYear(new Date(2005, 6, 2))\n * //=> Sun Jan 01 2006 00:00:00\n */\nfunction lastDayOfISOWeekYear(date, options) {\n const year = (0, _index2.getISOWeekYear)(date, options);\n const fourthOfJanuary = (0, _index.constructFrom)(options?.in || date, 0);\n fourthOfJanuary.setFullYear(year + 1, 0, 4);\n fourthOfJanuary.setHours(0, 0, 0, 0);\n\n const date_ = (0, _index3.startOfISOWeek)(fourthOfJanuary, options);\n date_.setDate(date_.getDate() - 1);\n return date_;\n}\n", "\"use strict\";\nexports.lastDayOfQuarter = lastDayOfQuarter;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link lastDayOfQuarter} function options.\n */\n\n/**\n * @name lastDayOfQuarter\n * @category Quarter Helpers\n * @summary Return the last day of a year quarter for the given date.\n *\n * @description\n * Return the last day of a year quarter for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The last day of a quarter\n *\n * @example\n * // The last day of a quarter for 2 September 2014 11:55:00:\n * const result = lastDayOfQuarter(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 30 2014 00:00:00\n */\nfunction lastDayOfQuarter(date, options) {\n const date_ = (0, _index.toDate)(date, options?.in);\n const currentMonth = date_.getMonth();\n const month = currentMonth - (currentMonth % 3) + 3;\n date_.setMonth(month, 0);\n date_.setHours(0, 0, 0, 0);\n return date_;\n}\n", "\"use strict\";\nexports.lastDayOfYear = lastDayOfYear;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link lastDayOfYear} function options.\n */\n\n/**\n * @name lastDayOfYear\n * @category Year Helpers\n * @summary Return the last day of a year for the given date.\n *\n * @description\n * Return the last day of a year for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The last day of a year\n *\n * @example\n * // The last day of a year for 2 September 2014 11:55:00:\n * const result = lastDayOfYear(new Date(2014, 8, 2, 11, 55, 00))\n * //=> Wed Dec 31 2014 00:00:00\n */\nfunction lastDayOfYear(date, options) {\n const date_ = (0, _index.toDate)(date, options?.in);\n const year = date_.getFullYear();\n date_.setFullYear(year + 1, 0, 0);\n date_.setHours(0, 0, 0, 0);\n return date_;\n}\n", "\"use strict\";\nexports.lightFormat = lightFormat;\nObject.defineProperty(exports, \"lightFormatters\", {\n enumerable: true,\n get: function () {\n return _index.lightFormatters;\n },\n});\nvar _index = require(\"./_lib/format/lightFormatters.cjs\");\nvar _index2 = require(\"./isValid.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n// Rexports of internal for libraries to use.\n// See: https://github.com/date-fns/date-fns/issues/3638#issuecomment-1877082874\n\n// This RegExp consists of three parts separated by `|`:\n// - (\\w)\\1* matches any sequences of the same letter\n// - '' matches two quote characters in a row\n// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),\n// except a single quote symbol, which ends the sequence.\n// Two quote characters do not end the sequence.\n// If there is no matching single quote\n// then the sequence will continue until the end of the string.\n// - . matches any single character unmatched by previous parts of the RegExps\nconst formattingTokensRegExp = /(\\w)\\1*|''|'(''|[^'])+('|$)|./g;\n\nconst escapedStringRegExp = /^'([^]*?)'?$/;\nconst doubleQuoteRegExp = /''/g;\nconst unescapedLatinCharacterRegExp = /[a-zA-Z]/;\n\n/**\n * @private\n */\n\n/**\n * @name lightFormat\n * @category Common Helpers\n * @summary Format the date.\n *\n * @description\n * Return the formatted date string in the given format. Unlike `format`,\n * `lightFormat` doesn't use locales and outputs date using the most popular tokens.\n *\n * > \u26A0\uFE0F Please note that the `lightFormat` tokens differ from Moment.js and other libraries.\n * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * The characters wrapped between two single quotes characters (') are escaped.\n * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.\n *\n * Format of the string is based on Unicode Technical Standard #35:\n * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n *\n * Accepted patterns:\n * | Unit | Pattern | Result examples |\n * |---------------------------------|---------|-----------------------------------|\n * | AM, PM | a..aaa | AM, PM |\n * | | aaaa | a.m., p.m. |\n * | | aaaaa | a, p |\n * | Calendar year | y | 44, 1, 1900, 2017 |\n * | | yy | 44, 01, 00, 17 |\n * | | yyy | 044, 001, 000, 017 |\n * | | yyyy | 0044, 0001, 1900, 2017 |\n * | Month (formatting) | M | 1, 2, ..., 12 |\n * | | MM | 01, 02, ..., 12 |\n * | Day of month | d | 1, 2, ..., 31 |\n * | | dd | 01, 02, ..., 31 |\n * | Hour [1-12] | h | 1, 2, ..., 11, 12 |\n * | | hh | 01, 02, ..., 11, 12 |\n * | Hour [0-23] | H | 0, 1, 2, ..., 23 |\n * | | HH | 00, 01, 02, ..., 23 |\n * | Minute | m | 0, 1, ..., 59 |\n * | | mm | 00, 01, ..., 59 |\n * | Second | s | 0, 1, ..., 59 |\n * | | ss | 00, 01, ..., 59 |\n * | Fraction of second | S | 0, 1, ..., 9 |\n * | | SS | 00, 01, ..., 99 |\n * | | SSS | 000, 001, ..., 999 |\n * | | SSSS | ... |\n *\n * @param date - The original date\n * @param format - The string of tokens\n *\n * @returns The formatted date string\n *\n * @throws `Invalid time value` if the date is invalid\n * @throws format string contains an unescaped latin alphabet character\n *\n * @example\n * const result = lightFormat(new Date(2014, 1, 11), 'yyyy-MM-dd')\n * //=> '2014-02-11'\n */\nfunction lightFormat(date, formatStr) {\n const date_ = (0, _index3.toDate)(date);\n\n if (!(0, _index2.isValid)(date_)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n const tokens = formatStr.match(formattingTokensRegExp);\n\n // The only case when formattingTokensRegExp doesn't match the string is when it's empty\n if (!tokens) return \"\";\n\n const result = tokens\n .map((substring) => {\n // Replace two single quote characters with one single quote character\n if (substring === \"''\") {\n return \"'\";\n }\n\n const firstCharacter = substring[0];\n if (firstCharacter === \"'\") {\n return cleanEscapedString(substring);\n }\n\n const formatter = _index.lightFormatters[firstCharacter];\n if (formatter) {\n return formatter(date_, substring);\n }\n\n if (firstCharacter.match(unescapedLatinCharacterRegExp)) {\n throw new RangeError(\n \"Format string contains an unescaped latin alphabet character `\" +\n firstCharacter +\n \"`\",\n );\n }\n\n return substring;\n })\n .join(\"\");\n\n return result;\n}\n\nfunction cleanEscapedString(input) {\n const matches = input.match(escapedStringRegExp);\n if (!matches) return input;\n return matches[1].replace(doubleQuoteRegExp, \"'\");\n}\n", "\"use strict\";\nexports.milliseconds = milliseconds;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name milliseconds\n * @category Millisecond Helpers\n * @summary\n * Returns the number of milliseconds in the specified, years, months, weeks, days, hours, minutes and seconds.\n *\n * @description\n * Returns the number of milliseconds in the specified, years, months, weeks, days, hours, minutes and seconds.\n *\n * One years equals 365.2425 days according to the formula:\n *\n * > Leap year occurs every 4 years, except for years that are divisible by 100 and not divisible by 400.\n * > 1 mean year = (365+1/4-1/100+1/400) days = 365.2425 days\n *\n * One month is a year divided by 12.\n *\n * @param duration - The object with years, months, weeks, days, hours, minutes and seconds to be added.\n *\n * @returns The milliseconds\n *\n * @example\n * // 1 year in milliseconds\n * milliseconds({ years: 1 })\n * //=> 31556952000\n *\n * // 3 months in milliseconds\n * milliseconds({ months: 3 })\n * //=> 7889238000\n */\nfunction milliseconds({ years, months, weeks, days, hours, minutes, seconds }) {\n let totalDays = 0;\n\n if (years) totalDays += years * _index.daysInYear;\n if (months) totalDays += months * (_index.daysInYear / 12);\n if (weeks) totalDays += weeks * 7;\n if (days) totalDays += days;\n\n let totalSeconds = totalDays * 24 * 60 * 60;\n\n if (hours) totalSeconds += hours * 60 * 60;\n if (minutes) totalSeconds += minutes * 60;\n if (seconds) totalSeconds += seconds;\n\n return Math.trunc(totalSeconds * 1000);\n}\n", "\"use strict\";\nexports.millisecondsToHours = millisecondsToHours;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name millisecondsToHours\n * @category Conversion Helpers\n * @summary Convert milliseconds to hours.\n *\n * @description\n * Convert a number of milliseconds to a full number of hours.\n *\n * @param milliseconds - The number of milliseconds to be converted\n *\n * @returns The number of milliseconds converted in hours\n *\n * @example\n * // Convert 7200000 milliseconds to hours:\n * const result = millisecondsToHours(7200000)\n * //=> 2\n *\n * @example\n * // It uses floor rounding:\n * const result = millisecondsToHours(7199999)\n * //=> 1\n */\nfunction millisecondsToHours(milliseconds) {\n const hours = milliseconds / _index.millisecondsInHour;\n return Math.trunc(hours);\n}\n", "\"use strict\";\nexports.millisecondsToMinutes = millisecondsToMinutes;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name millisecondsToMinutes\n * @category Conversion Helpers\n * @summary Convert milliseconds to minutes.\n *\n * @description\n * Convert a number of milliseconds to a full number of minutes.\n *\n * @param milliseconds - The number of milliseconds to be converted\n *\n * @returns The number of milliseconds converted in minutes\n *\n * @example\n * // Convert 60000 milliseconds to minutes:\n * const result = millisecondsToMinutes(60000)\n * //=> 1\n *\n * @example\n * // It uses floor rounding:\n * const result = millisecondsToMinutes(119999)\n * //=> 1\n */\nfunction millisecondsToMinutes(milliseconds) {\n const minutes = milliseconds / _index.millisecondsInMinute;\n return Math.trunc(minutes);\n}\n", "\"use strict\";\nexports.millisecondsToSeconds = millisecondsToSeconds;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name millisecondsToSeconds\n * @category Conversion Helpers\n * @summary Convert milliseconds to seconds.\n *\n * @description\n * Convert a number of milliseconds to a full number of seconds.\n *\n * @param milliseconds - The number of milliseconds to be converted\n *\n * @returns The number of milliseconds converted in seconds\n *\n * @example\n * // Convert 1000 milliseconds to seconds:\n * const result = millisecondsToSeconds(1000)\n * //=> 1\n *\n * @example\n * // It uses floor rounding:\n * const result = millisecondsToSeconds(1999)\n * //=> 1\n */\nfunction millisecondsToSeconds(milliseconds) {\n const seconds = milliseconds / _index.millisecondsInSecond;\n return Math.trunc(seconds);\n}\n", "\"use strict\";\nexports.minutesToHours = minutesToHours;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name minutesToHours\n * @category Conversion Helpers\n * @summary Convert minutes to hours.\n *\n * @description\n * Convert a number of minutes to a full number of hours.\n *\n * @param minutes - The number of minutes to be converted\n *\n * @returns The number of minutes converted in hours\n *\n * @example\n * // Convert 140 minutes to hours:\n * const result = minutesToHours(120)\n * //=> 2\n *\n * @example\n * // It uses floor rounding:\n * const result = minutesToHours(179)\n * //=> 2\n */\nfunction minutesToHours(minutes) {\n const hours = minutes / _index.minutesInHour;\n return Math.trunc(hours);\n}\n", "\"use strict\";\nexports.minutesToMilliseconds = minutesToMilliseconds;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name minutesToMilliseconds\n * @category Conversion Helpers\n * @summary Convert minutes to milliseconds.\n *\n * @description\n * Convert a number of minutes to a full number of milliseconds.\n *\n * @param minutes - The number of minutes to be converted\n *\n * @returns The number of minutes converted in milliseconds\n *\n * @example\n * // Convert 2 minutes to milliseconds\n * const result = minutesToMilliseconds(2)\n * //=> 120000\n */\nfunction minutesToMilliseconds(minutes) {\n return Math.trunc(minutes * _index.millisecondsInMinute);\n}\n", "\"use strict\";\nexports.minutesToSeconds = minutesToSeconds;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name minutesToSeconds\n * @category Conversion Helpers\n * @summary Convert minutes to seconds.\n *\n * @description\n * Convert a number of minutes to a full number of seconds.\n *\n * @param minutes - The number of minutes to be converted\n *\n * @returns The number of minutes converted in seconds\n *\n * @example\n * // Convert 2 minutes to seconds\n * const result = minutesToSeconds(2)\n * //=> 120\n */\nfunction minutesToSeconds(minutes) {\n return Math.trunc(minutes * _index.secondsInMinute);\n}\n", "\"use strict\";\nexports.monthsToQuarters = monthsToQuarters;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name monthsToQuarters\n * @category Conversion Helpers\n * @summary Convert number of months to quarters.\n *\n * @description\n * Convert a number of months to a full number of quarters.\n *\n * @param months - The number of months to be converted.\n *\n * @returns The number of months converted in quarters\n *\n * @example\n * // Convert 6 months to quarters:\n * const result = monthsToQuarters(6)\n * //=> 2\n *\n * @example\n * // It uses floor rounding:\n * const result = monthsToQuarters(7)\n * //=> 2\n */\nfunction monthsToQuarters(months) {\n const quarters = months / _index.monthsInQuarter;\n return Math.trunc(quarters);\n}\n", "\"use strict\";\nexports.monthsToYears = monthsToYears;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name monthsToYears\n * @category Conversion Helpers\n * @summary Convert number of months to years.\n *\n * @description\n * Convert a number of months to a full number of years.\n *\n * @param months - The number of months to be converted\n *\n * @returns The number of months converted in years\n *\n * @example\n * // Convert 36 months to years:\n * const result = monthsToYears(36)\n * //=> 3\n *\n * // It uses floor rounding:\n * const result = monthsToYears(40)\n * //=> 3\n */\nfunction monthsToYears(months) {\n const years = months / _index.monthsInYear;\n return Math.trunc(years);\n}\n", "\"use strict\";\nexports.nextDay = nextDay;\nvar _index = require(\"./addDays.cjs\");\nvar _index2 = require(\"./getDay.cjs\");\n\n/**\n * The {@link nextDay} function options.\n */\n\n/**\n * @name nextDay\n * @category Weekday Helpers\n * @summary When is the next day of the week? 0-6 the day of the week, 0 represents Sunday.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to check\n * @param day - Day of the week\n * @param options - An object with options\n *\n * @returns The date is the next day of the week\n *\n * @example\n * // When is the next Monday after Mar, 20, 2020?\n * const result = nextDay(new Date(2020, 2, 20), 1)\n * //=> Mon Mar 23 2020 00:00:00\n *\n * @example\n * // When is the next Tuesday after Mar, 21, 2020?\n * const result = nextDay(new Date(2020, 2, 21), 2)\n * //=> Tue Mar 24 2020 00:00:00\n */\nfunction nextDay(date, day, options) {\n let delta = day - (0, _index2.getDay)(date, options);\n if (delta <= 0) delta += 7;\n\n return (0, _index.addDays)(date, delta, options);\n}\n", "\"use strict\";\nexports.nextFriday = nextFriday;\nvar _index = require(\"./nextDay.cjs\");\n\n/**\n * The {@link nextFriday} function options.\n */\n\n/**\n * @name nextFriday\n * @category Weekday Helpers\n * @summary When is the next Friday?\n *\n * @description\n * When is the next Friday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The next Friday\n *\n * @example\n * // When is the next Friday after Mar, 22, 2020?\n * const result = nextFriday(new Date(2020, 2, 22))\n * //=> Fri Mar 27 2020 00:00:00\n */\nfunction nextFriday(date, options) {\n return (0, _index.nextDay)(date, 5, options);\n}\n", "\"use strict\";\nexports.nextMonday = nextMonday;\nvar _index = require(\"./nextDay.cjs\");\n\n/**\n * The {@link nextMonday} function options.\n */\n\n/**\n * @name nextMonday\n * @category Weekday Helpers\n * @summary When is the next Monday?\n *\n * @description\n * When is the next Monday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, returned from the context function if passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The next Monday\n *\n * @example\n * // When is the next Monday after Mar, 22, 2020?\n * const result = nextMonday(new Date(2020, 2, 22))\n * //=> Mon Mar 23 2020 00:00:00\n */\nfunction nextMonday(date, options) {\n return (0, _index.nextDay)(date, 1, options);\n}\n", "\"use strict\";\nexports.nextSaturday = nextSaturday;\nvar _index = require(\"./nextDay.cjs\");\n\n/**\n * The {@link nextSaturday} function options.\n */\n\n/**\n * @name nextSaturday\n * @category Weekday Helpers\n * @summary When is the next Saturday?\n *\n * @description\n * When is the next Saturday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The next Saturday\n *\n * @example\n * // When is the next Saturday after Mar, 22, 2020?\n * const result = nextSaturday(new Date(2020, 2, 22))\n * //=> Sat Mar 28 2020 00:00:00\n */\nfunction nextSaturday(date, options) {\n return (0, _index.nextDay)(date, 6, options);\n}\n", "\"use strict\";\nexports.nextSunday = nextSunday;\nvar _index = require(\"./nextDay.cjs\");\n\n/**\n * The {@link nextSunday} function options.\n */\n\n/**\n * @name nextSunday\n * @category Weekday Helpers\n * @summary When is the next Sunday?\n *\n * @description\n * When is the next Sunday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned if a context is provided.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The next Sunday\n *\n * @example\n * // When is the next Sunday after March 22, 2020?\n * const result = nextSunday(new Date(2020, 2, 22))\n * //=> Sun Mar 29 2020 00:00:00\n */\nfunction nextSunday(date, options) {\n return (0, _index.nextDay)(date, 0, options);\n}\n", "\"use strict\";\nexports.nextThursday = nextThursday;\nvar _index = require(\"./nextDay.cjs\");\n\n/**\n * The {@link nextThursday} function options.\n */\n\n/**\n * @name nextThursday\n * @category Weekday Helpers\n * @summary When is the next Thursday?\n *\n * @description\n * When is the next Thursday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The next Thursday\n *\n * @example\n * // When is the next Thursday after Mar, 22, 2020?\n * const result = nextThursday(new Date(2020, 2, 22))\n * //=> Thur Mar 26 2020 00:00:00\n */\nfunction nextThursday(date, options) {\n return (0, _index.nextDay)(date, 4, options);\n}\n", "\"use strict\";\nexports.nextTuesday = nextTuesday;\nvar _index = require(\"./nextDay.cjs\");\n\n/**\n * The {@link nextTuesday} function options.\n */\n\n/**\n * @name nextTuesday\n * @category Weekday Helpers\n * @summary When is the next Tuesday?\n *\n * @description\n * When is the next Tuesday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The next Tuesday\n *\n * @example\n * // When is the next Tuesday after Mar, 22, 2020?\n * const result = nextTuesday(new Date(2020, 2, 22))\n * //=> Tue Mar 24 2020 00:00:00\n */\nfunction nextTuesday(date, options) {\n return (0, _index.nextDay)(date, 2, options);\n}\n", "\"use strict\";\nexports.nextWednesday = nextWednesday;\nvar _index = require(\"./nextDay.cjs\");\n\n/**\n * The {@link nextWednesday} function options.\n */\n\n/**\n * @name nextWednesday\n * @category Weekday Helpers\n * @summary When is the next Wednesday?\n *\n * @description\n * When is the next Wednesday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The next Wednesday\n *\n * @example\n * // When is the next Wednesday after Mar, 22, 2020?\n * const result = nextWednesday(new Date(2020, 2, 22))\n * //=> Wed Mar 25 2020 00:00:00\n */\nfunction nextWednesday(date, options) {\n return (0, _index.nextDay)(date, 3, options);\n}\n", "\"use strict\";\nexports.parseISO = parseISO;\nvar _index = require(\"./constants.cjs\");\n\nvar _index2 = require(\"./constructFrom.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link parseISO} function options.\n */\n\n/**\n * @name parseISO\n * @category Common Helpers\n * @summary Parse ISO string\n *\n * @description\n * Parse the given string in ISO 8601 format and return an instance of Date.\n *\n * Function accepts complete ISO 8601 formats as well as partial implementations.\n * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601\n *\n * If the argument isn't a string, the function cannot parse the string or\n * the values are invalid, it returns Invalid Date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param argument - The value to convert\n * @param options - An object with options\n *\n * @returns The parsed date in the local time zone\n *\n * @example\n * // Convert string '2014-02-11T11:30:30' to date:\n * const result = parseISO('2014-02-11T11:30:30')\n * //=> Tue Feb 11 2014 11:30:30\n *\n * @example\n * // Convert string '+02014101' to date,\n * // if the additional number of digits in the extended year format is 1:\n * const result = parseISO('+02014101', { additionalDigits: 1 })\n * //=> Fri Apr 11 2014 00:00:00\n */\nfunction parseISO(argument, options) {\n const invalidDate = () => (0, _index2.constructFrom)(options?.in, NaN);\n\n const additionalDigits = options?.additionalDigits ?? 2;\n const dateStrings = splitDateString(argument);\n\n let date;\n if (dateStrings.date) {\n const parseYearResult = parseYear(dateStrings.date, additionalDigits);\n date = parseDate(parseYearResult.restDateString, parseYearResult.year);\n }\n\n if (!date || isNaN(+date)) return invalidDate();\n\n const timestamp = +date;\n let time = 0;\n let offset;\n\n if (dateStrings.time) {\n time = parseTime(dateStrings.time);\n if (isNaN(time)) return invalidDate();\n }\n\n if (dateStrings.timezone) {\n offset = parseTimezone(dateStrings.timezone);\n if (isNaN(offset)) return invalidDate();\n } else {\n const tmpDate = new Date(timestamp + time);\n const result = (0, _index3.toDate)(0, options?.in);\n result.setFullYear(\n tmpDate.getUTCFullYear(),\n tmpDate.getUTCMonth(),\n tmpDate.getUTCDate(),\n );\n result.setHours(\n tmpDate.getUTCHours(),\n tmpDate.getUTCMinutes(),\n tmpDate.getUTCSeconds(),\n tmpDate.getUTCMilliseconds(),\n );\n return result;\n }\n\n return (0, _index3.toDate)(timestamp + time + offset, options?.in);\n}\n\nconst patterns = {\n dateTimeDelimiter: /[T ]/,\n timeZoneDelimiter: /[Z ]/i,\n timezone: /([Z+-].*)$/,\n};\n\nconst dateRegex =\n /^-?(?:(\\d{3})|(\\d{2})(?:-?(\\d{2}))?|W(\\d{2})(?:-?(\\d{1}))?|)$/;\nconst timeRegex =\n /^(\\d{2}(?:[.,]\\d*)?)(?::?(\\d{2}(?:[.,]\\d*)?))?(?::?(\\d{2}(?:[.,]\\d*)?))?$/;\nconst timezoneRegex = /^([+-])(\\d{2})(?::?(\\d{2}))?$/;\n\nfunction splitDateString(dateString) {\n const dateStrings = {};\n const array = dateString.split(patterns.dateTimeDelimiter);\n let timeString;\n\n // The regex match should only return at maximum two array elements.\n // [date], [time], or [date, time].\n if (array.length > 2) {\n return dateStrings;\n }\n\n if (/:/.test(array[0])) {\n timeString = array[0];\n } else {\n dateStrings.date = array[0];\n timeString = array[1];\n if (patterns.timeZoneDelimiter.test(dateStrings.date)) {\n dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0];\n timeString = dateString.substr(\n dateStrings.date.length,\n dateString.length,\n );\n }\n }\n\n if (timeString) {\n const token = patterns.timezone.exec(timeString);\n if (token) {\n dateStrings.time = timeString.replace(token[1], \"\");\n dateStrings.timezone = token[1];\n } else {\n dateStrings.time = timeString;\n }\n }\n\n return dateStrings;\n}\n\nfunction parseYear(dateString, additionalDigits) {\n const regex = new RegExp(\n \"^(?:(\\\\d{4}|[+-]\\\\d{\" +\n (4 + additionalDigits) +\n \"})|(\\\\d{2}|[+-]\\\\d{\" +\n (2 + additionalDigits) +\n \"})$)\",\n );\n\n const captures = dateString.match(regex);\n // Invalid ISO-formatted year\n if (!captures) return { year: NaN, restDateString: \"\" };\n\n const year = captures[1] ? parseInt(captures[1]) : null;\n const century = captures[2] ? parseInt(captures[2]) : null;\n\n // either year or century is null, not both\n return {\n year: century === null ? year : century * 100,\n restDateString: dateString.slice((captures[1] || captures[2]).length),\n };\n}\n\nfunction parseDate(dateString, year) {\n // Invalid ISO-formatted year\n if (year === null) return new Date(NaN);\n\n const captures = dateString.match(dateRegex);\n // Invalid ISO-formatted string\n if (!captures) return new Date(NaN);\n\n const isWeekDate = !!captures[4];\n const dayOfYear = parseDateUnit(captures[1]);\n const month = parseDateUnit(captures[2]) - 1;\n const day = parseDateUnit(captures[3]);\n const week = parseDateUnit(captures[4]);\n const dayOfWeek = parseDateUnit(captures[5]) - 1;\n\n if (isWeekDate) {\n if (!validateWeekDate(year, week, dayOfWeek)) {\n return new Date(NaN);\n }\n return dayOfISOWeekYear(year, week, dayOfWeek);\n } else {\n const date = new Date(0);\n if (\n !validateDate(year, month, day) ||\n !validateDayOfYearDate(year, dayOfYear)\n ) {\n return new Date(NaN);\n }\n date.setUTCFullYear(year, month, Math.max(dayOfYear, day));\n return date;\n }\n}\n\nfunction parseDateUnit(value) {\n return value ? parseInt(value) : 1;\n}\n\nfunction parseTime(timeString) {\n const captures = timeString.match(timeRegex);\n if (!captures) return NaN; // Invalid ISO-formatted time\n\n const hours = parseTimeUnit(captures[1]);\n const minutes = parseTimeUnit(captures[2]);\n const seconds = parseTimeUnit(captures[3]);\n\n if (!validateTime(hours, minutes, seconds)) {\n return NaN;\n }\n\n return (\n hours * _index.millisecondsInHour +\n minutes * _index.millisecondsInMinute +\n seconds * 1000\n );\n}\n\nfunction parseTimeUnit(value) {\n return (value && parseFloat(value.replace(\",\", \".\"))) || 0;\n}\n\nfunction parseTimezone(timezoneString) {\n if (timezoneString === \"Z\") return 0;\n\n const captures = timezoneString.match(timezoneRegex);\n if (!captures) return 0;\n\n const sign = captures[1] === \"+\" ? -1 : 1;\n const hours = parseInt(captures[2]);\n const minutes = (captures[3] && parseInt(captures[3])) || 0;\n\n if (!validateTimezone(hours, minutes)) {\n return NaN;\n }\n\n return (\n sign *\n (hours * _index.millisecondsInHour + minutes * _index.millisecondsInMinute)\n );\n}\n\nfunction dayOfISOWeekYear(isoWeekYear, week, day) {\n const date = new Date(0);\n date.setUTCFullYear(isoWeekYear, 0, 4);\n const fourthOfJanuaryDay = date.getUTCDay() || 7;\n const diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay;\n date.setUTCDate(date.getUTCDate() + diff);\n return date;\n}\n\n// Validation functions\n\n// February is null to handle the leap year (using ||)\nconst daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\nfunction isLeapYearIndex(year) {\n return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);\n}\n\nfunction validateDate(year, month, date) {\n return (\n month >= 0 &&\n month <= 11 &&\n date >= 1 &&\n date <= (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28))\n );\n}\n\nfunction validateDayOfYearDate(year, dayOfYear) {\n return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex(year) ? 366 : 365);\n}\n\nfunction validateWeekDate(_year, week, day) {\n return week >= 1 && week <= 53 && day >= 0 && day <= 6;\n}\n\nfunction validateTime(hours, minutes, seconds) {\n if (hours === 24) {\n return minutes === 0 && seconds === 0;\n }\n\n return (\n seconds >= 0 &&\n seconds < 60 &&\n minutes >= 0 &&\n minutes < 60 &&\n hours >= 0 &&\n hours < 25\n );\n}\n\nfunction validateTimezone(_hours, minutes) {\n return minutes >= 0 && minutes <= 59;\n}\n", "\"use strict\";\nexports.parseJSON = parseJSON;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link parseJSON} function options.\n */\n\n/**\n * Converts a complete ISO date string in UTC time, the typical format for transmitting\n * a date in JSON, to a JavaScript `Date` instance.\n *\n * This is a minimal implementation for converting dates retrieved from a JSON API to\n * a `Date` instance which can be used with other functions in the `date-fns` library.\n * The following formats are supported:\n *\n * - `2000-03-15T05:20:10.123Z`: The output of `.toISOString()` and `JSON.stringify(new Date())`\n * - `2000-03-15T05:20:10Z`: Without milliseconds\n * - `2000-03-15T05:20:10+00:00`: With a zero offset, the default JSON encoded format in some other languages\n * - `2000-03-15T05:20:10+05:45`: With a positive or negative offset, the default JSON encoded format in some other languages\n * - `2000-03-15T05:20:10+0000`: With a zero offset without a colon\n * - `2000-03-15T05:20:10`: Without a trailing 'Z' symbol\n * - `2000-03-15T05:20:10.1234567`: Up to 7 digits in milliseconds field. Only first 3 are taken into account since JS does not allow fractional milliseconds\n * - `2000-03-15 05:20:10`: With a space instead of a 'T' separator for APIs returning a SQL date without reformatting\n *\n * For convenience and ease of use these other input types are also supported\n * via [toDate](https://date-fns.org/docs/toDate):\n *\n * - A `Date` instance will be cloned\n * - A `number` will be treated as a timestamp\n *\n * Any other input type or invalid date strings will return an `Invalid Date`.\n *\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param dateStr - A fully formed ISO8601 date string to convert\n * @param options - An object with options\n *\n * @returns The parsed date in the local time zone\n */\nfunction parseJSON(dateStr, options) {\n const parts = dateStr.match(\n /(\\d{4})-(\\d{2})-(\\d{2})[T ](\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{0,7}))?(?:Z|(.)(\\d{2}):?(\\d{2})?)?/,\n );\n\n if (!parts) return (0, _index.toDate)(NaN, options?.in);\n\n return (0, _index.toDate)(\n Date.UTC(\n +parts[1],\n +parts[2] - 1,\n +parts[3],\n +parts[4] - (+parts[9] || 0) * (parts[8] == \"-\" ? -1 : 1),\n +parts[5] - (+parts[10] || 0) * (parts[8] == \"-\" ? -1 : 1),\n +parts[6],\n +((parts[7] || \"0\") + \"00\").substring(0, 3),\n ),\n options?.in,\n );\n}\n", "\"use strict\";\nexports.previousDay = previousDay;\nvar _index = require(\"./getDay.cjs\");\nvar _index2 = require(\"./subDays.cjs\");\n\n/**\n * The {@link previousDay} function options.\n */\n\n/**\n * @name previousDay\n * @category Weekday Helpers\n * @summary When is the previous day of the week?\n *\n * @description\n * When is the previous day of the week? 0-6 the day of the week, 0 represents Sunday.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to check\n * @param day - The day of the week\n * @param options - An object with options\n *\n * @returns The date is the previous day of week\n *\n * @example\n * // When is the previous Monday before Mar, 20, 2020?\n * const result = previousDay(new Date(2020, 2, 20), 1)\n * //=> Mon Mar 16 2020 00:00:00\n *\n * @example\n * // When is the previous Tuesday before Mar, 21, 2020?\n * const result = previousDay(new Date(2020, 2, 21), 2)\n * //=> Tue Mar 17 2020 00:00:00\n */\nfunction previousDay(date, day, options) {\n let delta = (0, _index.getDay)(date, options) - day;\n if (delta <= 0) delta += 7;\n\n return (0, _index2.subDays)(date, delta, options);\n}\n", "\"use strict\";\nexports.previousFriday = previousFriday;\nvar _index = require(\"./previousDay.cjs\");\n\n/**\n * The {@link previousFriday} function options.\n */\n\n/**\n * @name previousFriday\n * @category Weekday Helpers\n * @summary When is the previous Friday?\n *\n * @description\n * When is the previous Friday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [UTCDate](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - The options\n *\n * @returns The previous Friday\n *\n * @example\n * // When is the previous Friday before Jun, 19, 2021?\n * const result = previousFriday(new Date(2021, 5, 19))\n * //=> Fri June 18 2021 00:00:00\n */\nfunction previousFriday(date, options) {\n return (0, _index.previousDay)(date, 5, options);\n}\n", "\"use strict\";\nexports.previousMonday = previousMonday;\nvar _index = require(\"./previousDay.cjs\");\n\n/**\n * The {@link previousMonday} function options.\n */\n\n/**\n * @name previousMonday\n * @category Weekday Helpers\n * @summary When is the previous Monday?\n *\n * @description\n * When is the previous Monday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The previous Monday\n *\n * @example\n * // When is the previous Monday before Jun, 18, 2021?\n * const result = previousMonday(new Date(2021, 5, 18))\n * //=> Mon June 14 2021 00:00:00\n */\nfunction previousMonday(date, options) {\n return (0, _index.previousDay)(date, 1, options);\n}\n", "\"use strict\";\nexports.previousSaturday = previousSaturday;\nvar _index = require(\"./previousDay.cjs\");\n\n/**\n * The {@link previousSaturday} function options.\n */\n\n/**\n * @name previousSaturday\n * @category Weekday Helpers\n * @summary When is the previous Saturday?\n *\n * @description\n * When is the previous Saturday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - The options\n *\n * @returns The previous Saturday\n *\n * @example\n * // When is the previous Saturday before Jun, 20, 2021?\n * const result = previousSaturday(new Date(2021, 5, 20))\n * //=> Sat June 19 2021 00:00:00\n */\nfunction previousSaturday(date, options) {\n return (0, _index.previousDay)(date, 6, options);\n}\n", "\"use strict\";\nexports.previousSunday = previousSunday;\nvar _index = require(\"./previousDay.cjs\");\n\n/**\n * The {@link previousSunday} function options.\n */\n\n/**\n * @name previousSunday\n * @category Weekday Helpers\n * @summary When is the previous Sunday?\n *\n * @description\n * When is the previous Sunday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - The options\n *\n * @returns The previous Sunday\n *\n * @example\n * // When is the previous Sunday before Jun, 21, 2021?\n * const result = previousSunday(new Date(2021, 5, 21))\n * //=> Sun June 20 2021 00:00:00\n */\nfunction previousSunday(date, options) {\n return (0, _index.previousDay)(date, 0, options);\n}\n", "\"use strict\";\nexports.previousThursday = previousThursday;\nvar _index = require(\"./previousDay.cjs\");\n\n/**\n * The {@link previousThursday} function options.\n */\n\n/**\n * @name previousThursday\n * @category Weekday Helpers\n * @summary When is the previous Thursday?\n *\n * @description\n * When is the previous Thursday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The previous Thursday\n *\n * @example\n * // When is the previous Thursday before Jun, 18, 2021?\n * const result = previousThursday(new Date(2021, 5, 18))\n * //=> Thu June 17 2021 00:00:00\n */\nfunction previousThursday(date, options) {\n return (0, _index.previousDay)(date, 4, options);\n}\n", "\"use strict\";\nexports.previousTuesday = previousTuesday;\nvar _index = require(\"./previousDay.cjs\");\n\n/**\n * The {@link previousTuesday} function options.\n */\n\n/**\n * @name previousTuesday\n * @category Weekday Helpers\n * @summary When is the previous Tuesday?\n *\n * @description\n * When is the previous Tuesday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The previous Tuesday\n *\n * @example\n * // When is the previous Tuesday before Jun, 18, 2021?\n * const result = previousTuesday(new Date(2021, 5, 18))\n * //=> Tue June 15 2021 00:00:00\n */\nfunction previousTuesday(date, options) {\n return (0, _index.previousDay)(date, 2, options);\n}\n", "\"use strict\";\nexports.previousWednesday = previousWednesday;\nvar _index = require(\"./previousDay.cjs\");\n\n/**\n * The {@link previousWednesday} function options.\n */\n\n/**\n * @name previousWednesday\n * @category Weekday Helpers\n * @summary When is the previous Wednesday?\n *\n * @description\n * When is the previous Wednesday?\n *\n * @typeParam DateType - The Date type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [UTCDate](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The previous Wednesday\n *\n * @example\n * // When is the previous Wednesday before Jun, 18, 2021?\n * const result = previousWednesday(new Date(2021, 5, 18))\n * //=> Wed June 16 2021 00:00:00\n */\nfunction previousWednesday(date, options) {\n return (0, _index.previousDay)(date, 3, options);\n}\n", "\"use strict\";\nexports.quartersToMonths = quartersToMonths;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name quartersToMonths\n * @category Conversion Helpers\n * @summary Convert number of quarters to months.\n *\n * @description\n * Convert a number of quarters to a full number of months.\n *\n * @param quarters - The number of quarters to be converted\n *\n * @returns The number of quarters converted in months\n *\n * @example\n * // Convert 2 quarters to months\n * const result = quartersToMonths(2)\n * //=> 6\n */\nfunction quartersToMonths(quarters) {\n return Math.trunc(quarters * _index.monthsInQuarter);\n}\n", "\"use strict\";\nexports.quartersToYears = quartersToYears;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name quartersToYears\n * @category Conversion Helpers\n * @summary Convert number of quarters to years.\n *\n * @description\n * Convert a number of quarters to a full number of years.\n *\n * @param quarters - The number of quarters to be converted\n *\n * @returns The number of quarters converted in years\n *\n * @example\n * // Convert 8 quarters to years\n * const result = quartersToYears(8)\n * //=> 2\n *\n * @example\n * // It uses floor rounding:\n * const result = quartersToYears(11)\n * //=> 2\n */\nfunction quartersToYears(quarters) {\n const years = quarters / _index.quartersInYear;\n return Math.trunc(years);\n}\n", "\"use strict\";\nexports.roundToNearestHours = roundToNearestHours;\nvar _index = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link roundToNearestHours} function options.\n */\n\n/**\n * @name roundToNearestHours\n * @category Hour Helpers\n * @summary Rounds the given date to the nearest hour\n *\n * @description\n * Rounds the given date to the nearest hour (or number of hours).\n * Rounds up when the given date is exactly between the nearest round hours.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to round\n * @param options - An object with options.\n *\n * @returns The new date rounded to the closest hour\n *\n * @example\n * // Round 10 July 2014 12:34:56 to nearest hour:\n * const result = roundToNearestHours(new Date(2014, 6, 10, 12, 34, 56))\n * //=> Thu Jul 10 2014 13:00:00\n *\n * @example\n * // Round 10 July 2014 12:34:56 to nearest half hour:\n * const result = roundToNearestHours(new Date(2014, 6, 10, 12, 34, 56), { nearestTo: 6 })\n * //=> Thu Jul 10 2014 12:00:00\n *\n * @example\n * // Round 10 July 2014 12:34:56 to nearest half hour:\n * const result = roundToNearestHours(new Date(2014, 6, 10, 12, 34, 56), { nearestTo: 8 })\n * //=> Thu Jul 10 2014 16:00:00\n *\n * @example\n * // Floor (rounds down) 10 July 2014 12:34:56 to nearest hour:\n * const result = roundToNearestHours(new Date(2014, 6, 10, 1, 23, 45), { roundingMethod: 'ceil' })\n * //=> Thu Jul 10 2014 02:00:00\n *\n * @example\n * // Ceil (rounds up) 10 July 2014 12:34:56 to nearest quarter hour:\n * const result = roundToNearestHours(new Date(2014, 6, 10, 12, 34, 56), { roundingMethod: 'floor', nearestTo: 8 })\n * //=> Thu Jul 10 2014 08:00:00\n */\nfunction roundToNearestHours(date, options) {\n const nearestTo = options?.nearestTo ?? 1;\n\n if (nearestTo < 1 || nearestTo > 12)\n return (0, _index2.constructFrom)(options?.in || date, NaN);\n\n const date_ = (0, _index3.toDate)(date, options?.in);\n const fractionalMinutes = date_.getMinutes() / 60;\n const fractionalSeconds = date_.getSeconds() / 60 / 60;\n const fractionalMilliseconds = date_.getMilliseconds() / 1000 / 60 / 60;\n const hours =\n date_.getHours() +\n fractionalMinutes +\n fractionalSeconds +\n fractionalMilliseconds;\n\n const method = options?.roundingMethod ?? \"round\";\n const roundingMethod = (0, _index.getRoundingMethod)(method);\n\n const roundedHours = roundingMethod(hours / nearestTo) * nearestTo;\n\n date_.setHours(roundedHours, 0, 0, 0);\n return date_;\n}\n", "\"use strict\";\nexports.roundToNearestMinutes = roundToNearestMinutes;\nvar _index = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link roundToNearestMinutes} function options.\n */\n\n/**\n * @name roundToNearestMinutes\n * @category Minute Helpers\n * @summary Rounds the given date to the nearest minute\n *\n * @description\n * Rounds the given date to the nearest minute (or number of minutes).\n * Rounds up when the given date is exactly between the nearest round minutes.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to round\n * @param options - An object with options.\n *\n * @returns The new date rounded to the closest minute\n *\n * @example\n * // Round 10 July 2014 12:12:34 to nearest minute:\n * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34))\n * //=> Thu Jul 10 2014 12:13:00\n *\n * @example\n * // Round 10 July 2014 12:12:34 to nearest quarter hour:\n * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34), { nearestTo: 15 })\n * //=> Thu Jul 10 2014 12:15:00\n *\n * @example\n * // Floor (rounds down) 10 July 2014 12:12:34 to nearest minute:\n * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34), { roundingMethod: 'floor' })\n * //=> Thu Jul 10 2014 12:12:00\n *\n * @example\n * // Ceil (rounds up) 10 July 2014 12:12:34 to nearest half hour:\n * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34), { roundingMethod: 'ceil', nearestTo: 30 })\n * //=> Thu Jul 10 2014 12:30:00\n */\nfunction roundToNearestMinutes(date, options) {\n const nearestTo = options?.nearestTo ?? 1;\n\n if (nearestTo < 1 || nearestTo > 30)\n return (0, _index2.constructFrom)(date, NaN);\n\n const date_ = (0, _index3.toDate)(date, options?.in);\n const fractionalSeconds = date_.getSeconds() / 60;\n const fractionalMilliseconds = date_.getMilliseconds() / 1000 / 60;\n const minutes =\n date_.getMinutes() + fractionalSeconds + fractionalMilliseconds;\n\n const method = options?.roundingMethod ?? \"round\";\n const roundingMethod = (0, _index.getRoundingMethod)(method);\n\n const roundedMinutes = roundingMethod(minutes / nearestTo) * nearestTo;\n\n date_.setMinutes(roundedMinutes, 0, 0);\n return date_;\n}\n", "\"use strict\";\nexports.secondsToHours = secondsToHours;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name secondsToHours\n * @category Conversion Helpers\n * @summary Convert seconds to hours.\n *\n * @description\n * Convert a number of seconds to a full number of hours.\n *\n * @param seconds - The number of seconds to be converted\n *\n * @returns The number of seconds converted in hours\n *\n * @example\n * // Convert 7200 seconds into hours\n * const result = secondsToHours(7200)\n * //=> 2\n *\n * @example\n * // It uses floor rounding:\n * const result = secondsToHours(7199)\n * //=> 1\n */\nfunction secondsToHours(seconds) {\n const hours = seconds / _index.secondsInHour;\n return Math.trunc(hours);\n}\n", "\"use strict\";\nexports.secondsToMilliseconds = secondsToMilliseconds;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name secondsToMilliseconds\n * @category Conversion Helpers\n * @summary Convert seconds to milliseconds.\n *\n * @description\n * Convert a number of seconds to a full number of milliseconds.\n *\n * @param seconds - The number of seconds to be converted\n *\n * @returns The number of seconds converted in milliseconds\n *\n * @example\n * // Convert 2 seconds into milliseconds\n * const result = secondsToMilliseconds(2)\n * //=> 2000\n */\nfunction secondsToMilliseconds(seconds) {\n return seconds * _index.millisecondsInSecond;\n}\n", "\"use strict\";\nexports.secondsToMinutes = secondsToMinutes;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name secondsToMinutes\n * @category Conversion Helpers\n * @summary Convert seconds to minutes.\n *\n * @description\n * Convert a number of seconds to a full number of minutes.\n *\n * @param seconds - The number of seconds to be converted\n *\n * @returns The number of seconds converted in minutes\n *\n * @example\n * // Convert 120 seconds into minutes\n * const result = secondsToMinutes(120)\n * //=> 2\n *\n * @example\n * // It uses floor rounding:\n * const result = secondsToMinutes(119)\n * //=> 1\n */\nfunction secondsToMinutes(seconds) {\n const minutes = seconds / _index.secondsInMinute;\n return Math.trunc(minutes);\n}\n", "\"use strict\";\nexports.setMonth = setMonth;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./getDaysInMonth.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setMonth} function options.\n */\n\n/**\n * @name setMonth\n * @category Month Helpers\n * @summary Set the month to the given date.\n *\n * @description\n * Set the month to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param month - The month index to set (0-11)\n * @param options - The options\n *\n * @returns The new date with the month set\n *\n * @example\n * // Set February to 1 September 2014:\n * const result = setMonth(new Date(2014, 8, 1), 1)\n * //=> Sat Feb 01 2014 00:00:00\n */\nfunction setMonth(date, month, options) {\n const _date = (0, _index3.toDate)(date, options?.in);\n const year = _date.getFullYear();\n const day = _date.getDate();\n\n const midMonth = (0, _index.constructFrom)(options?.in || date, 0);\n midMonth.setFullYear(year, month, 15);\n midMonth.setHours(0, 0, 0, 0);\n const daysInMonth = (0, _index2.getDaysInMonth)(midMonth);\n\n // Set the earlier date, allows to wrap Jan 31 to Feb 28\n _date.setMonth(month, Math.min(day, daysInMonth));\n return _date;\n}\n", "\"use strict\";\nexports.set = set;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./setMonth.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link set} function options.\n */\n\n/**\n * @name set\n * @category Common Helpers\n * @summary Set date values to a given date.\n *\n * @description\n * Set date values to a given date.\n *\n * Sets time values to date from object `values`.\n * A value is not set if it is undefined or null or doesn't exist in `values`.\n *\n * Note about bundle size: `set` does not internally use `setX` functions from date-fns but instead opts\n * to use native `Date#setX` methods. If you use this function, you may not want to include the\n * other `setX` functions that date-fns provides if you are concerned about the bundle size.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param values - The date values to be set\n * @param options - The options\n *\n * @returns The new date with options set\n *\n * @example\n * // Transform 1 September 2014 into 20 October 2015 in a single line:\n * const result = set(new Date(2014, 8, 20), { year: 2015, month: 9, date: 20 })\n * //=> Tue Oct 20 2015 00:00:00\n *\n * @example\n * // Set 12 PM to 1 September 2014 01:23:45 to 1 September 2014 12:00:00:\n * const result = set(new Date(2014, 8, 1, 1, 23, 45), { hours: 12 })\n * //=> Mon Sep 01 2014 12:23:45\n */\nfunction set(date, values, options) {\n let _date = (0, _index3.toDate)(date, options?.in);\n\n // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date\n if (isNaN(+_date)) return (0, _index.constructFrom)(options?.in || date, NaN);\n\n if (values.year != null) _date.setFullYear(values.year);\n if (values.month != null) _date = (0, _index2.setMonth)(_date, values.month);\n if (values.date != null) _date.setDate(values.date);\n if (values.hours != null) _date.setHours(values.hours);\n if (values.minutes != null) _date.setMinutes(values.minutes);\n if (values.seconds != null) _date.setSeconds(values.seconds);\n if (values.milliseconds != null) _date.setMilliseconds(values.milliseconds);\n\n return _date;\n}\n", "\"use strict\";\nexports.setDate = setDate;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link setDate} function options.\n */\n\n/**\n * @name setDate\n * @category Day Helpers\n * @summary Set the day of the month to the given date.\n *\n * @description\n * Set the day of the month to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows using extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param dayOfMonth - The day of the month of the new date\n * @param options - The options\n *\n * @returns The new date with the day of the month set\n *\n * @example\n * // Set the 30th day of the month to 1 September 2014:\n * const result = setDate(new Date(2014, 8, 1), 30)\n * //=> Tue Sep 30 2014 00:00:00\n */\nfunction setDate(date, dayOfMonth, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setDate(dayOfMonth);\n return _date;\n}\n", "\"use strict\";\nexports.setDayOfYear = setDayOfYear;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link setDayOfYear} function options.\n */\n\n/**\n * @name setDayOfYear\n * @category Day Helpers\n * @summary Set the day of the year to the given date.\n *\n * @description\n * Set the day of the year to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param dayOfYear - The day of the year of the new date\n * @param options - An object with options\n *\n * @returns The new date with the day of the year set\n *\n * @example\n * // Set the 2nd day of the year to 2 July 2014:\n * const result = setDayOfYear(new Date(2014, 6, 2), 2)\n * //=> Thu Jan 02 2014 00:00:00\n */\nfunction setDayOfYear(date, dayOfYear, options) {\n const date_ = (0, _index.toDate)(date, options?.in);\n date_.setMonth(0);\n date_.setDate(dayOfYear);\n return date_;\n}\n", "\"use strict\";\nexports.setDefaultOptions = setDefaultOptions;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\n\n/**\n * @name setDefaultOptions\n * @category Common Helpers\n * @summary Set default options including locale.\n * @pure false\n *\n * @description\n * Sets the defaults for\n * `options.locale`, `options.weekStartsOn` and `options.firstWeekContainsDate`\n * arguments for all functions.\n *\n * @param options - An object with options\n *\n * @example\n * // Set global locale:\n * import { es } from 'date-fns/locale'\n * setDefaultOptions({ locale: es })\n * const result = format(new Date(2014, 8, 2), 'PPPP')\n * //=> 'martes, 2 de septiembre de 2014'\n *\n * @example\n * // Start of the week for 2 September 2014:\n * const result = startOfWeek(new Date(2014, 8, 2))\n * //=> Sun Aug 31 2014 00:00:00\n *\n * @example\n * // Start of the week for 2 September 2014,\n * // when we set that week starts on Monday by default:\n * setDefaultOptions({ weekStartsOn: 1 })\n * const result = startOfWeek(new Date(2014, 8, 2))\n * //=> Mon Sep 01 2014 00:00:00\n *\n * @example\n * // Manually set options take priority over default options:\n * setDefaultOptions({ weekStartsOn: 1 })\n * const result = startOfWeek(new Date(2014, 8, 2), { weekStartsOn: 0 })\n * //=> Sun Aug 31 2014 00:00:00\n *\n * @example\n * // Remove the option by setting it to `undefined`:\n * setDefaultOptions({ weekStartsOn: 1 })\n * setDefaultOptions({ weekStartsOn: undefined })\n * const result = startOfWeek(new Date(2014, 8, 2))\n * //=> Sun Aug 31 2014 00:00:00\n */\nfunction setDefaultOptions(options) {\n const result = {};\n const defaultOptions = (0, _index.getDefaultOptions)();\n\n for (const property in defaultOptions) {\n if (Object.prototype.hasOwnProperty.call(defaultOptions, property)) {\n // [TODO] I challenge you to fix the type\n result[property] = defaultOptions[property];\n }\n }\n\n for (const property in options) {\n if (Object.prototype.hasOwnProperty.call(options, property)) {\n if (options[property] === undefined) {\n // [TODO] I challenge you to fix the type\n delete result[property];\n } else {\n // [TODO] I challenge you to fix the type\n result[property] = options[property];\n }\n }\n }\n\n (0, _index.setDefaultOptions)(result);\n}\n", "\"use strict\";\nexports.setHours = setHours;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link setHours} function options.\n */\n\n/**\n * @name setHours\n * @category Hour Helpers\n * @summary Set the hours to the given date.\n *\n * @description\n * Set the hours to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param hours - The hours of the new date\n * @param options - An object with options\n *\n * @returns The new date with the hours set\n *\n * @example\n * // Set 4 hours to 1 September 2014 11:30:00:\n * const result = setHours(new Date(2014, 8, 1, 11, 30), 4)\n * //=> Mon Sep 01 2014 04:30:00\n */\nfunction setHours(date, hours, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setHours(hours);\n return _date;\n}\n", "\"use strict\";\nexports.setMilliseconds = setMilliseconds;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link setMilliseconds} function options.\n */\n\n/**\n * @name setMilliseconds\n * @category Millisecond Helpers\n * @summary Set the milliseconds to the given date.\n *\n * @description\n * Set the milliseconds to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param milliseconds - The milliseconds of the new date\n * @param options - The options\n *\n * @returns The new date with the milliseconds set\n *\n * @example\n * // Set 300 milliseconds to 1 September 2014 11:30:40.500:\n * const result = setMilliseconds(new Date(2014, 8, 1, 11, 30, 40, 500), 300)\n * //=> Mon Sep 01 2014 11:30:40.300\n */\nfunction setMilliseconds(date, milliseconds, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setMilliseconds(milliseconds);\n return _date;\n}\n", "\"use strict\";\nexports.setMinutes = setMinutes;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link setMinutes} function options.\n */\n\n/**\n * @name setMinutes\n * @category Minute Helpers\n * @summary Set the minutes to the given date.\n *\n * @description\n * Set the minutes to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows using extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, returned from the context function, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param minutes - The minutes of the new date\n * @param options - An object with options\n *\n * @returns The new date with the minutes set\n *\n * @example\n * // Set 45 minutes to 1 September 2014 11:30:40:\n * const result = setMinutes(new Date(2014, 8, 1, 11, 30, 40), 45)\n * //=> Mon Sep 01 2014 11:45:40\n */\nfunction setMinutes(date, minutes, options) {\n const date_ = (0, _index.toDate)(date, options?.in);\n date_.setMinutes(minutes);\n return date_;\n}\n", "\"use strict\";\nexports.setQuarter = setQuarter;\nvar _index = require(\"./setMonth.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setQuarter} function options.\n */\n\n/**\n * @name setQuarter\n * @category Quarter Helpers\n * @summary Set the year quarter to the given date.\n *\n * @description\n * Set the year quarter to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param quarter - The quarter of the new date\n * @param options - The options\n *\n * @returns The new date with the quarter set\n *\n * @example\n * // Set the 2nd quarter to 2 July 2014:\n * const result = setQuarter(new Date(2014, 6, 2), 2)\n * //=> Wed Apr 02 2014 00:00:00\n */\nfunction setQuarter(date, quarter, options) {\n const date_ = (0, _index2.toDate)(date, options?.in);\n const oldQuarter = Math.trunc(date_.getMonth() / 3) + 1;\n const diff = quarter - oldQuarter;\n return (0, _index.setMonth)(date_, date_.getMonth() + diff * 3);\n}\n", "\"use strict\";\nexports.setSeconds = setSeconds;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link setSeconds} function options.\n */\n\n/**\n * @name setSeconds\n * @category Second Helpers\n * @summary Set the seconds to the given date, with context support.\n *\n * @description\n * Set the seconds to the given date, with an optional context for time zone specification.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param seconds - The seconds of the new date\n * @param options - An object with options\n *\n * @returns The new date with the seconds set\n *\n * @example\n * // Set 45 seconds to 1 September 2014 11:30:40:\n * const result = setSeconds(new Date(2014, 8, 1, 11, 30, 40), 45)\n * //=> Mon Sep 01 2014 11:30:45\n */\nfunction setSeconds(date, seconds, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setSeconds(seconds);\n return _date;\n}\n", "\"use strict\";\nexports.setWeekYear = setWeekYear;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\nvar _index3 = require(\"./differenceInCalendarDays.cjs\");\nvar _index4 = require(\"./startOfWeekYear.cjs\");\nvar _index5 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setWeekYear} function options.\n */\n\n/**\n * @name setWeekYear\n * @category Week-Numbering Year Helpers\n * @summary Set the local week-numbering year to the given date.\n *\n * @description\n * Set the local week-numbering year to the given date,\n * saving the week number and the weekday number.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param weekYear - The local week-numbering year of the new date\n * @param options - An object with options\n *\n * @returns The new date with the local week-numbering year set\n *\n * @example\n * // Set the local week-numbering year 2004 to 2 January 2010 with default options:\n * const result = setWeekYear(new Date(2010, 0, 2), 2004)\n * //=> Sat Jan 03 2004 00:00:00\n *\n * @example\n * // Set the local week-numbering year 2004 to 2 January 2010,\n * // if Monday is the first day of week\n * // and 4 January is always in the first week of the year:\n * const result = setWeekYear(new Date(2010, 0, 2), 2004, {\n * weekStartsOn: 1,\n * firstWeekContainsDate: 4\n * })\n * //=> Sat Jan 01 2005 00:00:00\n */\nfunction setWeekYear(date, weekYear, options) {\n const defaultOptions = (0, _index.getDefaultOptions)();\n const firstWeekContainsDate =\n options?.firstWeekContainsDate ??\n options?.locale?.options?.firstWeekContainsDate ??\n defaultOptions.firstWeekContainsDate ??\n defaultOptions.locale?.options?.firstWeekContainsDate ??\n 1;\n\n const diff = (0, _index3.differenceInCalendarDays)(\n (0, _index5.toDate)(date, options?.in),\n (0, _index4.startOfWeekYear)(date, options),\n options,\n );\n\n const firstWeek = (0, _index2.constructFrom)(options?.in || date, 0);\n firstWeek.setFullYear(weekYear, 0, firstWeekContainsDate);\n firstWeek.setHours(0, 0, 0, 0);\n\n const date_ = (0, _index4.startOfWeekYear)(firstWeek, options);\n date_.setDate(date_.getDate() + diff);\n return date_;\n}\n", "\"use strict\";\nexports.setYear = setYear;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setYear} function options.\n */\n\n/**\n * @name setYear\n * @category Year Helpers\n * @summary Set the year to the given date.\n *\n * @description\n * Set the year to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param year - The year of the new date\n * @param options - An object with options.\n *\n * @returns The new date with the year set\n *\n * @example\n * // Set year 2013 to 1 September 2014:\n * const result = setYear(new Date(2014, 8, 1), 2013)\n * //=> Sun Sep 01 2013 00:00:00\n */\nfunction setYear(date, year, options) {\n const date_ = (0, _index2.toDate)(date, options?.in);\n\n // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date\n if (isNaN(+date_)) return (0, _index.constructFrom)(options?.in || date, NaN);\n\n date_.setFullYear(year);\n return date_;\n}\n", "\"use strict\";\nexports.startOfDecade = startOfDecade;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfDecade} options.\n */\n\n/**\n * @name startOfDecade\n * @category Decade Helpers\n * @summary Return the start of a decade for the given date.\n *\n * @description\n * Return the start of a decade for the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of a decade\n *\n * @example\n * // The start of a decade for 21 October 2015 00:00:00:\n * const result = startOfDecade(new Date(2015, 9, 21, 00, 00, 00))\n * //=> Jan 01 2010 00:00:00\n */\nfunction startOfDecade(date, options) {\n // TODO: Switch to more technical definition in of decades that start with 1\n // end with 0. I.e. 2001-2010 instead of current 2000-2009. It's a breaking\n // change, so it can only be done in 4.0.\n const _date = (0, _index.toDate)(date, options?.in);\n const year = _date.getFullYear();\n const decade = Math.floor(year / 10) * 10;\n _date.setFullYear(decade, 0, 1);\n _date.setHours(0, 0, 0, 0);\n return _date;\n}\n", "\"use strict\";\nexports.startOfToday = startOfToday;\nvar _index = require(\"./startOfDay.cjs\");\n\n/**\n * The {@link startOfToday} function options.\n */\n\n/**\n * @name startOfToday\n * @category Day Helpers\n * @summary Return the start of today.\n * @pure false\n *\n * @description\n * Return the start of today.\n *\n * @typeParam ContextDate - The `Date` type of the context function.\n *\n * @param options - An object with options\n *\n * @returns The start of today\n *\n * @example\n * // If today is 6 October 2014:\n * const result = startOfToday()\n * //=> Mon Oct 6 2014 00:00:00\n */\nfunction startOfToday(options) {\n return (0, _index.startOfDay)(Date.now(), options);\n}\n", "\"use strict\";\nexports.startOfTomorrow = startOfTomorrow;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\n\n/**\n * The {@link startOfTomorrow} function options.\n */\n\n/**\n * @name startOfTomorrow\n * @category Day Helpers\n * @summary Return the start of tomorrow.\n * @pure false\n *\n * @typeParam ContextDate - The `Date` type of the context function.\n *\n * @param options - An object with options\n *\n * @returns The start of tomorrow\n *\n * @description\n * Return the start of tomorrow.\n *\n * @example\n * // If today is 6 October 2014:\n * const result = startOfTomorrow()\n * //=> Tue Oct 7 2014 00:00:00\n */\nfunction startOfTomorrow(options) {\n const now = (0, _index2.constructNow)(options?.in);\n const year = now.getFullYear();\n const month = now.getMonth();\n const day = now.getDate();\n\n const date = (0, _index.constructFrom)(options?.in, 0);\n date.setFullYear(year, month, day + 1);\n date.setHours(0, 0, 0, 0);\n return date;\n}\n", "\"use strict\";\nexports.startOfYesterday = startOfYesterday;\nvar _index = require(\"./constructNow.cjs\");\n\n/**\n * The {@link startOfYesterday} function options.\n */\n\n/**\n * @name startOfYesterday\n * @category Day Helpers\n * @summary Return the start of yesterday.\n * @pure false\n *\n * @typeParam ContextDate - The `Date` type of the context function.\n *\n * @param options - An object with options\n *\n * @description\n * Return the start of yesterday.\n *\n * @returns The start of yesterday\n *\n * @example\n * // If today is 6 October 2014:\n * const result = startOfYesterday()\n * //=> Sun Oct 5 2014 00:00:00\n */\nfunction startOfYesterday(options) {\n const now = (0, _index.constructNow)(options?.in);\n const year = now.getFullYear();\n const month = now.getMonth();\n const day = now.getDate();\n\n const date = (0, _index.constructNow)(options?.in);\n date.setFullYear(year, month, day - 1);\n date.setHours(0, 0, 0, 0);\n return date;\n}\n", "\"use strict\";\nexports.subMonths = subMonths;\nvar _index = require(\"./addMonths.cjs\");\n\n/**\n * The subMonths function options.\n */\n\n/**\n * @name subMonths\n * @category Month Helpers\n * @summary Subtract the specified number of months from the given date.\n *\n * @description\n * Subtract the specified number of months from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of months to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the months subtracted\n *\n * @example\n * // Subtract 5 months from 1 February 2015:\n * const result = subMonths(new Date(2015, 1, 1), 5)\n * //=> Mon Sep 01 2014 00:00:00\n */\nfunction subMonths(date, amount, options) {\n return (0, _index.addMonths)(date, -amount, options);\n}\n", "\"use strict\";\nexports.sub = sub;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./subDays.cjs\");\nvar _index3 = require(\"./subMonths.cjs\");\n\n/**\n * The {@link sub} function options.\n */\n\n/**\n * @name sub\n * @category Common Helpers\n * @summary Subtract the specified years, months, weeks, days, hours, minutes and seconds from the given date.\n *\n * @description\n * Subtract the specified years, months, weeks, days, hours, minutes and seconds from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param duration - The object with years, months, weeks, days, hours, minutes and seconds to be subtracted\n * @param options - An object with options\n *\n * | Key | Description |\n * |---------|------------------------------------|\n * | years | Amount of years to be subtracted |\n * | months | Amount of months to be subtracted |\n * | weeks | Amount of weeks to be subtracted |\n * | days | Amount of days to be subtracted |\n * | hours | Amount of hours to be subtracted |\n * | minutes | Amount of minutes to be subtracted |\n * | seconds | Amount of seconds to be subtracted |\n *\n * All values default to 0\n *\n * @returns The new date with the seconds subtracted\n *\n * @example\n * // Subtract the following duration from 15 June 2017 15:29:20\n * const result = sub(new Date(2017, 5, 15, 15, 29, 20), {\n * years: 2,\n * months: 9,\n * weeks: 1,\n * days: 7,\n * hours: 5,\n * minutes: 9,\n * seconds: 30\n * })\n * //=> Mon Sep 1 2014 10:19:50\n */\nfunction sub(date, duration, options) {\n const {\n years = 0,\n months = 0,\n weeks = 0,\n days = 0,\n hours = 0,\n minutes = 0,\n seconds = 0,\n } = duration;\n\n const withoutMonths = (0, _index3.subMonths)(\n date,\n months + years * 12,\n options,\n );\n const withoutDays = (0, _index2.subDays)(\n withoutMonths,\n days + weeks * 7,\n options,\n );\n\n const minutesToSub = minutes + hours * 60;\n const secondsToSub = seconds + minutesToSub * 60;\n const msToSub = secondsToSub * 1000;\n\n return (0, _index.constructFrom)(options?.in || date, +withoutDays - msToSub);\n}\n", "\"use strict\";\nexports.subBusinessDays = subBusinessDays;\nvar _index = require(\"./addBusinessDays.cjs\");\n\n/**\n * The {@link subBusinessDays} function options.\n */\n\n/**\n * @name subBusinessDays\n * @category Day Helpers\n * @summary Subtract the specified number of business days (mon - fri) from the given date.\n *\n * @description\n * Subtract the specified number of business days (mon - fri) from the given date, ignoring weekends.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of business days to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the business days subtracted\n *\n * @example\n * // Subtract 10 business days from 1 September 2014:\n * const result = subBusinessDays(new Date(2014, 8, 1), 10)\n * //=> Mon Aug 18 2014 00:00:00 (skipped weekend days)\n */\nfunction subBusinessDays(date, amount, options) {\n return (0, _index.addBusinessDays)(date, -amount, options);\n}\n", "\"use strict\";\nexports.subHours = subHours;\nvar _index = require(\"./addHours.cjs\");\n\n/**\n * The {@link subHours} function options.\n */\n\n/**\n * @name subHours\n * @category Hour Helpers\n * @summary Subtract the specified number of hours from the given date.\n *\n * @description\n * Subtract the specified number of hours from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of hours to be subtracted.\n * @param options - The options\n *\n * @returns The new date with the hours subtracted\n *\n * @example\n * // Subtract 2 hours from 11 July 2014 01:00:00:\n * const result = subHours(new Date(2014, 6, 11, 1, 0), 2)\n * //=> Thu Jul 10 2014 23:00:00\n */\nfunction subHours(date, amount, options) {\n return (0, _index.addHours)(date, -amount, options);\n}\n", "\"use strict\";\nexports.subMilliseconds = subMilliseconds;\nvar _index = require(\"./addMilliseconds.cjs\");\n\n/**\n * The {@link subMilliseconds} function options.\n */\n\n/**\n * Subtract the specified number of milliseconds from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of milliseconds to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the milliseconds subtracted\n */\nfunction subMilliseconds(date, amount, options) {\n return (0, _index.addMilliseconds)(date, -amount, options);\n}\n", "\"use strict\";\nexports.subMinutes = subMinutes;\nvar _index = require(\"./addMinutes.cjs\");\n\n/**\n * The {@link subMinutes} function options.\n */\n\n/**\n * @name subMinutes\n * @category Minute Helpers\n * @summary Subtract the specified number of minutes from the given date.\n *\n * @description\n * Subtract the specified number of minutes from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of minutes to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the minutes subtracted\n *\n * @example\n * // Subtract 30 minutes from 10 July 2014 12:00:00:\n * const result = subMinutes(new Date(2014, 6, 10, 12, 0), 30)\n * //=> Thu Jul 10 2014 11:30:00\n */\nfunction subMinutes(date, amount, options) {\n return (0, _index.addMinutes)(date, -amount, options);\n}\n", "\"use strict\";\nexports.subQuarters = subQuarters;\nvar _index = require(\"./addQuarters.cjs\");\n\n/**\n * The {@link subQuarters} function options.\n */\n\n/**\n * @name subQuarters\n * @category Quarter Helpers\n * @summary Subtract the specified number of year quarters from the given date.\n *\n * @description\n * Subtract the specified number of year quarters from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of quarters to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the quarters subtracted\n *\n * @example\n * // Subtract 3 quarters from 1 September 2014:\n * const result = subQuarters(new Date(2014, 8, 1), 3)\n * //=> Sun Dec 01 2013 00:00:00\n */\nfunction subQuarters(date, amount, options) {\n return (0, _index.addQuarters)(date, -amount, options);\n}\n", "\"use strict\";\nexports.subSeconds = subSeconds;\nvar _index = require(\"./addSeconds.cjs\");\n\n/**\n * The {@link subSeconds} function options.\n */\n\n/**\n * Subtract the specified number of seconds from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of seconds to be subtracted.\n * @param options - The options\n *\n * @returns The new date with the seconds subtracted\n *\n * @example\n * // Subtract 30 seconds from 10 July 2014 12:45:00:\n * const result = subSeconds(new Date(2014, 6, 10, 12, 45, 0), 30)\n * //=> Thu Jul 10 2014 12:44:30\n */\nfunction subSeconds(date, amount, options) {\n return (0, _index.addSeconds)(date, -amount, options);\n}\n", "\"use strict\";\nexports.subWeeks = subWeeks;\nvar _index = require(\"./addWeeks.cjs\");\n\n/**\n * The {@link subWeeks} function options.\n */\n\n/**\n * @name subWeeks\n * @category Week Helpers\n * @summary Subtract the specified number of weeks from the given date.\n *\n * @description\n * Subtract the specified number of weeks from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of weeks to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the weeks subtracted\n *\n * @example\n * // Subtract 4 weeks from 1 September 2014:\n * const result = subWeeks(new Date(2014, 8, 1), 4)\n * //=> Mon Aug 04 2014 00:00:00\n */\nfunction subWeeks(date, amount, options) {\n return (0, _index.addWeeks)(date, -amount, options);\n}\n", "\"use strict\";\nexports.subYears = subYears;\nvar _index = require(\"./addYears.cjs\");\n\n/**\n * The {@link subYears} function options.\n */\n\n/**\n * @name subYears\n * @category Year Helpers\n * @summary Subtract the specified number of years from the given date.\n *\n * @description\n * Subtract the specified number of years from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of years to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the years subtracted\n *\n * @example\n * // Subtract 5 years from 1 September 2014:\n * const result = subYears(new Date(2014, 8, 1), 5)\n * //=> Tue Sep 01 2009 00:00:00\n */\nfunction subYears(date, amount, options) {\n return (0, _index.addYears)(date, -amount, options);\n}\n", "\"use strict\";\nexports.weeksToDays = weeksToDays;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name weeksToDays\n * @category Conversion Helpers\n * @summary Convert weeks to days.\n *\n * @description\n * Convert a number of weeks to a full number of days.\n *\n * @param weeks - The number of weeks to be converted\n *\n * @returns The number of weeks converted in days\n *\n * @example\n * // Convert 2 weeks into days\n * const result = weeksToDays(2)\n * //=> 14\n */\nfunction weeksToDays(weeks) {\n return Math.trunc(weeks * _index.daysInWeek);\n}\n", "\"use strict\";\nexports.yearsToDays = yearsToDays;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name yearsToDays\n * @category Conversion Helpers\n * @summary Convert years to days.\n *\n * @description\n * Convert a number of years to a full number of days.\n *\n * @param years - The number of years to be converted\n *\n * @returns The number of years converted in days\n *\n * @example\n * // Convert 2 years into days\n * const result = yearsToDays(2)\n * //=> 730\n */\nfunction yearsToDays(years) {\n return Math.trunc(years * _index.daysInYear);\n}\n", "\"use strict\";\nexports.yearsToMonths = yearsToMonths;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name yearsToMonths\n * @category Conversion Helpers\n * @summary Convert years to months.\n *\n * @description\n * Convert a number of years to a full number of months.\n *\n * @param years - The number of years to be converted\n *\n * @returns The number of years converted in months\n *\n * @example\n * // Convert 2 years into months\n * const result = yearsToMonths(2)\n * //=> 24\n */\nfunction yearsToMonths(years) {\n return Math.trunc(years * _index.monthsInYear);\n}\n", "\"use strict\";\nexports.yearsToQuarters = yearsToQuarters;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name yearsToQuarters\n * @category Conversion Helpers\n * @summary Convert years to quarters.\n *\n * @description\n * Convert a number of years to a full number of quarters.\n *\n * @param years - The number of years to be converted\n *\n * @returns The number of years converted in quarters\n *\n * @example\n * // Convert 2 years to quarters\n * const result = yearsToQuarters(2)\n * //=> 8\n */\nfunction yearsToQuarters(years) {\n return Math.trunc(years * _index.quartersInYear);\n}\n", "\"use strict\";\n\nvar _index = require(\"./add.cjs\");\nObject.keys(_index).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index[key];\n },\n });\n});\nvar _index2 = require(\"./addBusinessDays.cjs\");\nObject.keys(_index2).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index2[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index2[key];\n },\n });\n});\nvar _index3 = require(\"./addDays.cjs\");\nObject.keys(_index3).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index3[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index3[key];\n },\n });\n});\nvar _index4 = require(\"./addHours.cjs\");\nObject.keys(_index4).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index4[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index4[key];\n },\n });\n});\nvar _index5 = require(\"./addISOWeekYears.cjs\");\nObject.keys(_index5).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index5[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index5[key];\n },\n });\n});\nvar _index6 = require(\"./addMilliseconds.cjs\");\nObject.keys(_index6).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index6[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index6[key];\n },\n });\n});\nvar _index7 = require(\"./addMinutes.cjs\");\nObject.keys(_index7).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index7[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index7[key];\n },\n });\n});\nvar _index8 = require(\"./addMonths.cjs\");\nObject.keys(_index8).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index8[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index8[key];\n },\n });\n});\nvar _index9 = require(\"./addQuarters.cjs\");\nObject.keys(_index9).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index9[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index9[key];\n },\n });\n});\nvar _index10 = require(\"./addSeconds.cjs\");\nObject.keys(_index10).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index10[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index10[key];\n },\n });\n});\nvar _index11 = require(\"./addWeeks.cjs\");\nObject.keys(_index11).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index11[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index11[key];\n },\n });\n});\nvar _index12 = require(\"./addYears.cjs\");\nObject.keys(_index12).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index12[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index12[key];\n },\n });\n});\nvar _index13 = require(\"./areIntervalsOverlapping.cjs\");\nObject.keys(_index13).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index13[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index13[key];\n },\n });\n});\nvar _index14 = require(\"./clamp.cjs\");\nObject.keys(_index14).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index14[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index14[key];\n },\n });\n});\nvar _index15 = require(\"./closestIndexTo.cjs\");\nObject.keys(_index15).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index15[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index15[key];\n },\n });\n});\nvar _index16 = require(\"./closestTo.cjs\");\nObject.keys(_index16).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index16[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index16[key];\n },\n });\n});\nvar _index17 = require(\"./compareAsc.cjs\");\nObject.keys(_index17).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index17[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index17[key];\n },\n });\n});\nvar _index18 = require(\"./compareDesc.cjs\");\nObject.keys(_index18).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index18[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index18[key];\n },\n });\n});\nvar _index19 = require(\"./constructFrom.cjs\");\nObject.keys(_index19).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index19[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index19[key];\n },\n });\n});\nvar _index20 = require(\"./constructNow.cjs\");\nObject.keys(_index20).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index20[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index20[key];\n },\n });\n});\nvar _index21 = require(\"./daysToWeeks.cjs\");\nObject.keys(_index21).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index21[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index21[key];\n },\n });\n});\nvar _index22 = require(\"./differenceInBusinessDays.cjs\");\nObject.keys(_index22).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index22[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index22[key];\n },\n });\n});\nvar _index23 = require(\"./differenceInCalendarDays.cjs\");\nObject.keys(_index23).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index23[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index23[key];\n },\n });\n});\nvar _index24 = require(\"./differenceInCalendarISOWeekYears.cjs\");\nObject.keys(_index24).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index24[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index24[key];\n },\n });\n});\nvar _index25 = require(\"./differenceInCalendarISOWeeks.cjs\");\nObject.keys(_index25).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index25[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index25[key];\n },\n });\n});\nvar _index26 = require(\"./differenceInCalendarMonths.cjs\");\nObject.keys(_index26).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index26[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index26[key];\n },\n });\n});\nvar _index27 = require(\"./differenceInCalendarQuarters.cjs\");\nObject.keys(_index27).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index27[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index27[key];\n },\n });\n});\nvar _index28 = require(\"./differenceInCalendarWeeks.cjs\");\nObject.keys(_index28).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index28[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index28[key];\n },\n });\n});\nvar _index29 = require(\"./differenceInCalendarYears.cjs\");\nObject.keys(_index29).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index29[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index29[key];\n },\n });\n});\nvar _index30 = require(\"./differenceInDays.cjs\");\nObject.keys(_index30).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index30[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index30[key];\n },\n });\n});\nvar _index31 = require(\"./differenceInHours.cjs\");\nObject.keys(_index31).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index31[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index31[key];\n },\n });\n});\nvar _index32 = require(\"./differenceInISOWeekYears.cjs\");\nObject.keys(_index32).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index32[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index32[key];\n },\n });\n});\nvar _index33 = require(\"./differenceInMilliseconds.cjs\");\nObject.keys(_index33).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index33[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index33[key];\n },\n });\n});\nvar _index34 = require(\"./differenceInMinutes.cjs\");\nObject.keys(_index34).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index34[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index34[key];\n },\n });\n});\nvar _index35 = require(\"./differenceInMonths.cjs\");\nObject.keys(_index35).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index35[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index35[key];\n },\n });\n});\nvar _index36 = require(\"./differenceInQuarters.cjs\");\nObject.keys(_index36).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index36[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index36[key];\n },\n });\n});\nvar _index37 = require(\"./differenceInSeconds.cjs\");\nObject.keys(_index37).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index37[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index37[key];\n },\n });\n});\nvar _index38 = require(\"./differenceInWeeks.cjs\");\nObject.keys(_index38).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index38[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index38[key];\n },\n });\n});\nvar _index39 = require(\"./differenceInYears.cjs\");\nObject.keys(_index39).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index39[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index39[key];\n },\n });\n});\nvar _index40 = require(\"./eachDayOfInterval.cjs\");\nObject.keys(_index40).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index40[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index40[key];\n },\n });\n});\nvar _index41 = require(\"./eachHourOfInterval.cjs\");\nObject.keys(_index41).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index41[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index41[key];\n },\n });\n});\nvar _index42 = require(\"./eachMinuteOfInterval.cjs\");\nObject.keys(_index42).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index42[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index42[key];\n },\n });\n});\nvar _index43 = require(\"./eachMonthOfInterval.cjs\");\nObject.keys(_index43).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index43[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index43[key];\n },\n });\n});\nvar _index44 = require(\"./eachQuarterOfInterval.cjs\");\nObject.keys(_index44).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index44[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index44[key];\n },\n });\n});\nvar _index45 = require(\"./eachWeekOfInterval.cjs\");\nObject.keys(_index45).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index45[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index45[key];\n },\n });\n});\nvar _index46 = require(\"./eachWeekendOfInterval.cjs\");\nObject.keys(_index46).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index46[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index46[key];\n },\n });\n});\nvar _index47 = require(\"./eachWeekendOfMonth.cjs\");\nObject.keys(_index47).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index47[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index47[key];\n },\n });\n});\nvar _index48 = require(\"./eachWeekendOfYear.cjs\");\nObject.keys(_index48).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index48[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index48[key];\n },\n });\n});\nvar _index49 = require(\"./eachYearOfInterval.cjs\");\nObject.keys(_index49).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index49[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index49[key];\n },\n });\n});\nvar _index50 = require(\"./endOfDay.cjs\");\nObject.keys(_index50).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index50[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index50[key];\n },\n });\n});\nvar _index51 = require(\"./endOfDecade.cjs\");\nObject.keys(_index51).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index51[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index51[key];\n },\n });\n});\nvar _index52 = require(\"./endOfHour.cjs\");\nObject.keys(_index52).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index52[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index52[key];\n },\n });\n});\nvar _index53 = require(\"./endOfISOWeek.cjs\");\nObject.keys(_index53).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index53[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index53[key];\n },\n });\n});\nvar _index54 = require(\"./endOfISOWeekYear.cjs\");\nObject.keys(_index54).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index54[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index54[key];\n },\n });\n});\nvar _index55 = require(\"./endOfMinute.cjs\");\nObject.keys(_index55).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index55[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index55[key];\n },\n });\n});\nvar _index56 = require(\"./endOfMonth.cjs\");\nObject.keys(_index56).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index56[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index56[key];\n },\n });\n});\nvar _index57 = require(\"./endOfQuarter.cjs\");\nObject.keys(_index57).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index57[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index57[key];\n },\n });\n});\nvar _index58 = require(\"./endOfSecond.cjs\");\nObject.keys(_index58).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index58[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index58[key];\n },\n });\n});\nvar _index59 = require(\"./endOfToday.cjs\");\nObject.keys(_index59).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index59[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index59[key];\n },\n });\n});\nvar _index60 = require(\"./endOfTomorrow.cjs\");\nObject.keys(_index60).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index60[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index60[key];\n },\n });\n});\nvar _index61 = require(\"./endOfWeek.cjs\");\nObject.keys(_index61).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index61[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index61[key];\n },\n });\n});\nvar _index62 = require(\"./endOfYear.cjs\");\nObject.keys(_index62).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index62[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index62[key];\n },\n });\n});\nvar _index63 = require(\"./endOfYesterday.cjs\");\nObject.keys(_index63).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index63[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index63[key];\n },\n });\n});\nvar _index64 = require(\"./format.cjs\");\nObject.keys(_index64).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index64[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index64[key];\n },\n });\n});\nvar _index65 = require(\"./formatDistance.cjs\");\nObject.keys(_index65).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index65[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index65[key];\n },\n });\n});\nvar _index66 = require(\"./formatDistanceStrict.cjs\");\nObject.keys(_index66).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index66[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index66[key];\n },\n });\n});\nvar _index67 = require(\"./formatDistanceToNow.cjs\");\nObject.keys(_index67).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index67[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index67[key];\n },\n });\n});\nvar _index68 = require(\"./formatDistanceToNowStrict.cjs\");\nObject.keys(_index68).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index68[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index68[key];\n },\n });\n});\nvar _index69 = require(\"./formatDuration.cjs\");\nObject.keys(_index69).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index69[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index69[key];\n },\n });\n});\nvar _index70 = require(\"./formatISO.cjs\");\nObject.keys(_index70).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index70[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index70[key];\n },\n });\n});\nvar _index71 = require(\"./formatISO9075.cjs\");\nObject.keys(_index71).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index71[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index71[key];\n },\n });\n});\nvar _index72 = require(\"./formatISODuration.cjs\");\nObject.keys(_index72).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index72[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index72[key];\n },\n });\n});\nvar _index73 = require(\"./formatRFC3339.cjs\");\nObject.keys(_index73).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index73[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index73[key];\n },\n });\n});\nvar _index74 = require(\"./formatRFC7231.cjs\");\nObject.keys(_index74).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index74[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index74[key];\n },\n });\n});\nvar _index75 = require(\"./formatRelative.cjs\");\nObject.keys(_index75).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index75[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index75[key];\n },\n });\n});\nvar _index76 = require(\"./fromUnixTime.cjs\");\nObject.keys(_index76).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index76[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index76[key];\n },\n });\n});\nvar _index77 = require(\"./getDate.cjs\");\nObject.keys(_index77).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index77[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index77[key];\n },\n });\n});\nvar _index78 = require(\"./getDay.cjs\");\nObject.keys(_index78).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index78[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index78[key];\n },\n });\n});\nvar _index79 = require(\"./getDayOfYear.cjs\");\nObject.keys(_index79).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index79[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index79[key];\n },\n });\n});\nvar _index80 = require(\"./getDaysInMonth.cjs\");\nObject.keys(_index80).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index80[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index80[key];\n },\n });\n});\nvar _index81 = require(\"./getDaysInYear.cjs\");\nObject.keys(_index81).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index81[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index81[key];\n },\n });\n});\nvar _index82 = require(\"./getDecade.cjs\");\nObject.keys(_index82).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index82[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index82[key];\n },\n });\n});\nvar _index83 = require(\"./getDefaultOptions.cjs\");\nObject.keys(_index83).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index83[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index83[key];\n },\n });\n});\nvar _index84 = require(\"./getHours.cjs\");\nObject.keys(_index84).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index84[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index84[key];\n },\n });\n});\nvar _index85 = require(\"./getISODay.cjs\");\nObject.keys(_index85).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index85[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index85[key];\n },\n });\n});\nvar _index86 = require(\"./getISOWeek.cjs\");\nObject.keys(_index86).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index86[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index86[key];\n },\n });\n});\nvar _index87 = require(\"./getISOWeekYear.cjs\");\nObject.keys(_index87).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index87[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index87[key];\n },\n });\n});\nvar _index88 = require(\"./getISOWeeksInYear.cjs\");\nObject.keys(_index88).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index88[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index88[key];\n },\n });\n});\nvar _index89 = require(\"./getMilliseconds.cjs\");\nObject.keys(_index89).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index89[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index89[key];\n },\n });\n});\nvar _index90 = require(\"./getMinutes.cjs\");\nObject.keys(_index90).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index90[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index90[key];\n },\n });\n});\nvar _index91 = require(\"./getMonth.cjs\");\nObject.keys(_index91).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index91[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index91[key];\n },\n });\n});\nvar _index92 = require(\"./getOverlappingDaysInIntervals.cjs\");\nObject.keys(_index92).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index92[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index92[key];\n },\n });\n});\nvar _index93 = require(\"./getQuarter.cjs\");\nObject.keys(_index93).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index93[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index93[key];\n },\n });\n});\nvar _index94 = require(\"./getSeconds.cjs\");\nObject.keys(_index94).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index94[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index94[key];\n },\n });\n});\nvar _index95 = require(\"./getTime.cjs\");\nObject.keys(_index95).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index95[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index95[key];\n },\n });\n});\nvar _index96 = require(\"./getUnixTime.cjs\");\nObject.keys(_index96).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index96[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index96[key];\n },\n });\n});\nvar _index97 = require(\"./getWeek.cjs\");\nObject.keys(_index97).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index97[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index97[key];\n },\n });\n});\nvar _index98 = require(\"./getWeekOfMonth.cjs\");\nObject.keys(_index98).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index98[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index98[key];\n },\n });\n});\nvar _index99 = require(\"./getWeekYear.cjs\");\nObject.keys(_index99).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index99[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index99[key];\n },\n });\n});\nvar _index100 = require(\"./getWeeksInMonth.cjs\");\nObject.keys(_index100).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index100[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index100[key];\n },\n });\n});\nvar _index101 = require(\"./getYear.cjs\");\nObject.keys(_index101).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index101[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index101[key];\n },\n });\n});\nvar _index102 = require(\"./hoursToMilliseconds.cjs\");\nObject.keys(_index102).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index102[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index102[key];\n },\n });\n});\nvar _index103 = require(\"./hoursToMinutes.cjs\");\nObject.keys(_index103).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index103[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index103[key];\n },\n });\n});\nvar _index104 = require(\"./hoursToSeconds.cjs\");\nObject.keys(_index104).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index104[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index104[key];\n },\n });\n});\nvar _index105 = require(\"./interval.cjs\");\nObject.keys(_index105).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index105[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index105[key];\n },\n });\n});\nvar _index106 = require(\"./intervalToDuration.cjs\");\nObject.keys(_index106).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index106[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index106[key];\n },\n });\n});\nvar _index107 = require(\"./intlFormat.cjs\");\nObject.keys(_index107).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index107[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index107[key];\n },\n });\n});\nvar _index108 = require(\"./intlFormatDistance.cjs\");\nObject.keys(_index108).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index108[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index108[key];\n },\n });\n});\nvar _index109 = require(\"./isAfter.cjs\");\nObject.keys(_index109).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index109[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index109[key];\n },\n });\n});\nvar _index110 = require(\"./isBefore.cjs\");\nObject.keys(_index110).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index110[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index110[key];\n },\n });\n});\nvar _index111 = require(\"./isDate.cjs\");\nObject.keys(_index111).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index111[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index111[key];\n },\n });\n});\nvar _index112 = require(\"./isEqual.cjs\");\nObject.keys(_index112).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index112[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index112[key];\n },\n });\n});\nvar _index113 = require(\"./isExists.cjs\");\nObject.keys(_index113).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index113[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index113[key];\n },\n });\n});\nvar _index114 = require(\"./isFirstDayOfMonth.cjs\");\nObject.keys(_index114).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index114[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index114[key];\n },\n });\n});\nvar _index115 = require(\"./isFriday.cjs\");\nObject.keys(_index115).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index115[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index115[key];\n },\n });\n});\nvar _index116 = require(\"./isFuture.cjs\");\nObject.keys(_index116).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index116[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index116[key];\n },\n });\n});\nvar _index117 = require(\"./isLastDayOfMonth.cjs\");\nObject.keys(_index117).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index117[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index117[key];\n },\n });\n});\nvar _index118 = require(\"./isLeapYear.cjs\");\nObject.keys(_index118).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index118[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index118[key];\n },\n });\n});\nvar _index119 = require(\"./isMatch.cjs\");\nObject.keys(_index119).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index119[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index119[key];\n },\n });\n});\nvar _index120 = require(\"./isMonday.cjs\");\nObject.keys(_index120).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index120[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index120[key];\n },\n });\n});\nvar _index121 = require(\"./isPast.cjs\");\nObject.keys(_index121).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index121[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index121[key];\n },\n });\n});\nvar _index122 = require(\"./isSameDay.cjs\");\nObject.keys(_index122).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index122[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index122[key];\n },\n });\n});\nvar _index123 = require(\"./isSameHour.cjs\");\nObject.keys(_index123).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index123[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index123[key];\n },\n });\n});\nvar _index124 = require(\"./isSameISOWeek.cjs\");\nObject.keys(_index124).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index124[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index124[key];\n },\n });\n});\nvar _index125 = require(\"./isSameISOWeekYear.cjs\");\nObject.keys(_index125).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index125[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index125[key];\n },\n });\n});\nvar _index126 = require(\"./isSameMinute.cjs\");\nObject.keys(_index126).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index126[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index126[key];\n },\n });\n});\nvar _index127 = require(\"./isSameMonth.cjs\");\nObject.keys(_index127).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index127[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index127[key];\n },\n });\n});\nvar _index128 = require(\"./isSameQuarter.cjs\");\nObject.keys(_index128).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index128[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index128[key];\n },\n });\n});\nvar _index129 = require(\"./isSameSecond.cjs\");\nObject.keys(_index129).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index129[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index129[key];\n },\n });\n});\nvar _index130 = require(\"./isSameWeek.cjs\");\nObject.keys(_index130).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index130[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index130[key];\n },\n });\n});\nvar _index131 = require(\"./isSameYear.cjs\");\nObject.keys(_index131).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index131[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index131[key];\n },\n });\n});\nvar _index132 = require(\"./isSaturday.cjs\");\nObject.keys(_index132).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index132[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index132[key];\n },\n });\n});\nvar _index133 = require(\"./isSunday.cjs\");\nObject.keys(_index133).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index133[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index133[key];\n },\n });\n});\nvar _index134 = require(\"./isThisHour.cjs\");\nObject.keys(_index134).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index134[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index134[key];\n },\n });\n});\nvar _index135 = require(\"./isThisISOWeek.cjs\");\nObject.keys(_index135).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index135[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index135[key];\n },\n });\n});\nvar _index136 = require(\"./isThisMinute.cjs\");\nObject.keys(_index136).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index136[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index136[key];\n },\n });\n});\nvar _index137 = require(\"./isThisMonth.cjs\");\nObject.keys(_index137).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index137[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index137[key];\n },\n });\n});\nvar _index138 = require(\"./isThisQuarter.cjs\");\nObject.keys(_index138).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index138[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index138[key];\n },\n });\n});\nvar _index139 = require(\"./isThisSecond.cjs\");\nObject.keys(_index139).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index139[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index139[key];\n },\n });\n});\nvar _index140 = require(\"./isThisWeek.cjs\");\nObject.keys(_index140).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index140[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index140[key];\n },\n });\n});\nvar _index141 = require(\"./isThisYear.cjs\");\nObject.keys(_index141).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index141[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index141[key];\n },\n });\n});\nvar _index142 = require(\"./isThursday.cjs\");\nObject.keys(_index142).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index142[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index142[key];\n },\n });\n});\nvar _index143 = require(\"./isToday.cjs\");\nObject.keys(_index143).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index143[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index143[key];\n },\n });\n});\nvar _index144 = require(\"./isTomorrow.cjs\");\nObject.keys(_index144).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index144[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index144[key];\n },\n });\n});\nvar _index145 = require(\"./isTuesday.cjs\");\nObject.keys(_index145).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index145[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index145[key];\n },\n });\n});\nvar _index146 = require(\"./isValid.cjs\");\nObject.keys(_index146).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index146[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index146[key];\n },\n });\n});\nvar _index147 = require(\"./isWednesday.cjs\");\nObject.keys(_index147).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index147[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index147[key];\n },\n });\n});\nvar _index148 = require(\"./isWeekend.cjs\");\nObject.keys(_index148).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index148[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index148[key];\n },\n });\n});\nvar _index149 = require(\"./isWithinInterval.cjs\");\nObject.keys(_index149).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index149[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index149[key];\n },\n });\n});\nvar _index150 = require(\"./isYesterday.cjs\");\nObject.keys(_index150).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index150[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index150[key];\n },\n });\n});\nvar _index151 = require(\"./lastDayOfDecade.cjs\");\nObject.keys(_index151).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index151[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index151[key];\n },\n });\n});\nvar _index152 = require(\"./lastDayOfISOWeek.cjs\");\nObject.keys(_index152).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index152[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index152[key];\n },\n });\n});\nvar _index153 = require(\"./lastDayOfISOWeekYear.cjs\");\nObject.keys(_index153).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index153[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index153[key];\n },\n });\n});\nvar _index154 = require(\"./lastDayOfMonth.cjs\");\nObject.keys(_index154).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index154[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index154[key];\n },\n });\n});\nvar _index155 = require(\"./lastDayOfQuarter.cjs\");\nObject.keys(_index155).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index155[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index155[key];\n },\n });\n});\nvar _index156 = require(\"./lastDayOfWeek.cjs\");\nObject.keys(_index156).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index156[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index156[key];\n },\n });\n});\nvar _index157 = require(\"./lastDayOfYear.cjs\");\nObject.keys(_index157).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index157[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index157[key];\n },\n });\n});\nvar _index158 = require(\"./lightFormat.cjs\");\nObject.keys(_index158).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index158[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index158[key];\n },\n });\n});\nvar _index159 = require(\"./max.cjs\");\nObject.keys(_index159).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index159[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index159[key];\n },\n });\n});\nvar _index160 = require(\"./milliseconds.cjs\");\nObject.keys(_index160).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index160[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index160[key];\n },\n });\n});\nvar _index161 = require(\"./millisecondsToHours.cjs\");\nObject.keys(_index161).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index161[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index161[key];\n },\n });\n});\nvar _index162 = require(\"./millisecondsToMinutes.cjs\");\nObject.keys(_index162).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index162[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index162[key];\n },\n });\n});\nvar _index163 = require(\"./millisecondsToSeconds.cjs\");\nObject.keys(_index163).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index163[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index163[key];\n },\n });\n});\nvar _index164 = require(\"./min.cjs\");\nObject.keys(_index164).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index164[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index164[key];\n },\n });\n});\nvar _index165 = require(\"./minutesToHours.cjs\");\nObject.keys(_index165).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index165[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index165[key];\n },\n });\n});\nvar _index166 = require(\"./minutesToMilliseconds.cjs\");\nObject.keys(_index166).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index166[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index166[key];\n },\n });\n});\nvar _index167 = require(\"./minutesToSeconds.cjs\");\nObject.keys(_index167).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index167[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index167[key];\n },\n });\n});\nvar _index168 = require(\"./monthsToQuarters.cjs\");\nObject.keys(_index168).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index168[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index168[key];\n },\n });\n});\nvar _index169 = require(\"./monthsToYears.cjs\");\nObject.keys(_index169).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index169[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index169[key];\n },\n });\n});\nvar _index170 = require(\"./nextDay.cjs\");\nObject.keys(_index170).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index170[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index170[key];\n },\n });\n});\nvar _index171 = require(\"./nextFriday.cjs\");\nObject.keys(_index171).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index171[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index171[key];\n },\n });\n});\nvar _index172 = require(\"./nextMonday.cjs\");\nObject.keys(_index172).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index172[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index172[key];\n },\n });\n});\nvar _index173 = require(\"./nextSaturday.cjs\");\nObject.keys(_index173).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index173[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index173[key];\n },\n });\n});\nvar _index174 = require(\"./nextSunday.cjs\");\nObject.keys(_index174).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index174[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index174[key];\n },\n });\n});\nvar _index175 = require(\"./nextThursday.cjs\");\nObject.keys(_index175).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index175[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index175[key];\n },\n });\n});\nvar _index176 = require(\"./nextTuesday.cjs\");\nObject.keys(_index176).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index176[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index176[key];\n },\n });\n});\nvar _index177 = require(\"./nextWednesday.cjs\");\nObject.keys(_index177).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index177[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index177[key];\n },\n });\n});\nvar _index178 = require(\"./parse.cjs\");\nObject.keys(_index178).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index178[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index178[key];\n },\n });\n});\nvar _index179 = require(\"./parseISO.cjs\");\nObject.keys(_index179).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index179[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index179[key];\n },\n });\n});\nvar _index180 = require(\"./parseJSON.cjs\");\nObject.keys(_index180).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index180[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index180[key];\n },\n });\n});\nvar _index181 = require(\"./previousDay.cjs\");\nObject.keys(_index181).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index181[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index181[key];\n },\n });\n});\nvar _index182 = require(\"./previousFriday.cjs\");\nObject.keys(_index182).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index182[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index182[key];\n },\n });\n});\nvar _index183 = require(\"./previousMonday.cjs\");\nObject.keys(_index183).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index183[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index183[key];\n },\n });\n});\nvar _index184 = require(\"./previousSaturday.cjs\");\nObject.keys(_index184).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index184[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index184[key];\n },\n });\n});\nvar _index185 = require(\"./previousSunday.cjs\");\nObject.keys(_index185).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index185[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index185[key];\n },\n });\n});\nvar _index186 = require(\"./previousThursday.cjs\");\nObject.keys(_index186).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index186[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index186[key];\n },\n });\n});\nvar _index187 = require(\"./previousTuesday.cjs\");\nObject.keys(_index187).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index187[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index187[key];\n },\n });\n});\nvar _index188 = require(\"./previousWednesday.cjs\");\nObject.keys(_index188).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index188[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index188[key];\n },\n });\n});\nvar _index189 = require(\"./quartersToMonths.cjs\");\nObject.keys(_index189).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index189[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index189[key];\n },\n });\n});\nvar _index190 = require(\"./quartersToYears.cjs\");\nObject.keys(_index190).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index190[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index190[key];\n },\n });\n});\nvar _index191 = require(\"./roundToNearestHours.cjs\");\nObject.keys(_index191).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index191[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index191[key];\n },\n });\n});\nvar _index192 = require(\"./roundToNearestMinutes.cjs\");\nObject.keys(_index192).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index192[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index192[key];\n },\n });\n});\nvar _index193 = require(\"./secondsToHours.cjs\");\nObject.keys(_index193).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index193[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index193[key];\n },\n });\n});\nvar _index194 = require(\"./secondsToMilliseconds.cjs\");\nObject.keys(_index194).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index194[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index194[key];\n },\n });\n});\nvar _index195 = require(\"./secondsToMinutes.cjs\");\nObject.keys(_index195).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index195[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index195[key];\n },\n });\n});\nvar _index196 = require(\"./set.cjs\");\nObject.keys(_index196).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index196[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index196[key];\n },\n });\n});\nvar _index197 = require(\"./setDate.cjs\");\nObject.keys(_index197).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index197[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index197[key];\n },\n });\n});\nvar _index198 = require(\"./setDay.cjs\");\nObject.keys(_index198).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index198[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index198[key];\n },\n });\n});\nvar _index199 = require(\"./setDayOfYear.cjs\");\nObject.keys(_index199).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index199[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index199[key];\n },\n });\n});\nvar _index200 = require(\"./setDefaultOptions.cjs\");\nObject.keys(_index200).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index200[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index200[key];\n },\n });\n});\nvar _index201 = require(\"./setHours.cjs\");\nObject.keys(_index201).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index201[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index201[key];\n },\n });\n});\nvar _index202 = require(\"./setISODay.cjs\");\nObject.keys(_index202).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index202[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index202[key];\n },\n });\n});\nvar _index203 = require(\"./setISOWeek.cjs\");\nObject.keys(_index203).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index203[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index203[key];\n },\n });\n});\nvar _index204 = require(\"./setISOWeekYear.cjs\");\nObject.keys(_index204).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index204[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index204[key];\n },\n });\n});\nvar _index205 = require(\"./setMilliseconds.cjs\");\nObject.keys(_index205).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index205[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index205[key];\n },\n });\n});\nvar _index206 = require(\"./setMinutes.cjs\");\nObject.keys(_index206).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index206[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index206[key];\n },\n });\n});\nvar _index207 = require(\"./setMonth.cjs\");\nObject.keys(_index207).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index207[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index207[key];\n },\n });\n});\nvar _index208 = require(\"./setQuarter.cjs\");\nObject.keys(_index208).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index208[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index208[key];\n },\n });\n});\nvar _index209 = require(\"./setSeconds.cjs\");\nObject.keys(_index209).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index209[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index209[key];\n },\n });\n});\nvar _index210 = require(\"./setWeek.cjs\");\nObject.keys(_index210).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index210[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index210[key];\n },\n });\n});\nvar _index211 = require(\"./setWeekYear.cjs\");\nObject.keys(_index211).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index211[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index211[key];\n },\n });\n});\nvar _index212 = require(\"./setYear.cjs\");\nObject.keys(_index212).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index212[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index212[key];\n },\n });\n});\nvar _index213 = require(\"./startOfDay.cjs\");\nObject.keys(_index213).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index213[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index213[key];\n },\n });\n});\nvar _index214 = require(\"./startOfDecade.cjs\");\nObject.keys(_index214).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index214[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index214[key];\n },\n });\n});\nvar _index215 = require(\"./startOfHour.cjs\");\nObject.keys(_index215).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index215[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index215[key];\n },\n });\n});\nvar _index216 = require(\"./startOfISOWeek.cjs\");\nObject.keys(_index216).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index216[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index216[key];\n },\n });\n});\nvar _index217 = require(\"./startOfISOWeekYear.cjs\");\nObject.keys(_index217).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index217[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index217[key];\n },\n });\n});\nvar _index218 = require(\"./startOfMinute.cjs\");\nObject.keys(_index218).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index218[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index218[key];\n },\n });\n});\nvar _index219 = require(\"./startOfMonth.cjs\");\nObject.keys(_index219).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index219[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index219[key];\n },\n });\n});\nvar _index220 = require(\"./startOfQuarter.cjs\");\nObject.keys(_index220).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index220[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index220[key];\n },\n });\n});\nvar _index221 = require(\"./startOfSecond.cjs\");\nObject.keys(_index221).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index221[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index221[key];\n },\n });\n});\nvar _index222 = require(\"./startOfToday.cjs\");\nObject.keys(_index222).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index222[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index222[key];\n },\n });\n});\nvar _index223 = require(\"./startOfTomorrow.cjs\");\nObject.keys(_index223).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index223[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index223[key];\n },\n });\n});\nvar _index224 = require(\"./startOfWeek.cjs\");\nObject.keys(_index224).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index224[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index224[key];\n },\n });\n});\nvar _index225 = require(\"./startOfWeekYear.cjs\");\nObject.keys(_index225).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index225[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index225[key];\n },\n });\n});\nvar _index226 = require(\"./startOfYear.cjs\");\nObject.keys(_index226).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index226[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index226[key];\n },\n });\n});\nvar _index227 = require(\"./startOfYesterday.cjs\");\nObject.keys(_index227).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index227[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index227[key];\n },\n });\n});\nvar _index228 = require(\"./sub.cjs\");\nObject.keys(_index228).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index228[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index228[key];\n },\n });\n});\nvar _index229 = require(\"./subBusinessDays.cjs\");\nObject.keys(_index229).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index229[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index229[key];\n },\n });\n});\nvar _index230 = require(\"./subDays.cjs\");\nObject.keys(_index230).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index230[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index230[key];\n },\n });\n});\nvar _index231 = require(\"./subHours.cjs\");\nObject.keys(_index231).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index231[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index231[key];\n },\n });\n});\nvar _index232 = require(\"./subISOWeekYears.cjs\");\nObject.keys(_index232).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index232[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index232[key];\n },\n });\n});\nvar _index233 = require(\"./subMilliseconds.cjs\");\nObject.keys(_index233).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index233[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index233[key];\n },\n });\n});\nvar _index234 = require(\"./subMinutes.cjs\");\nObject.keys(_index234).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index234[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index234[key];\n },\n });\n});\nvar _index235 = require(\"./subMonths.cjs\");\nObject.keys(_index235).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index235[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index235[key];\n },\n });\n});\nvar _index236 = require(\"./subQuarters.cjs\");\nObject.keys(_index236).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index236[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index236[key];\n },\n });\n});\nvar _index237 = require(\"./subSeconds.cjs\");\nObject.keys(_index237).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index237[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index237[key];\n },\n });\n});\nvar _index238 = require(\"./subWeeks.cjs\");\nObject.keys(_index238).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index238[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index238[key];\n },\n });\n});\nvar _index239 = require(\"./subYears.cjs\");\nObject.keys(_index239).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index239[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index239[key];\n },\n });\n});\nvar _index240 = require(\"./toDate.cjs\");\nObject.keys(_index240).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index240[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index240[key];\n },\n });\n});\nvar _index241 = require(\"./transpose.cjs\");\nObject.keys(_index241).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index241[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index241[key];\n },\n });\n});\nvar _index242 = require(\"./weeksToDays.cjs\");\nObject.keys(_index242).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index242[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index242[key];\n },\n });\n});\nvar _index243 = require(\"./yearsToDays.cjs\");\nObject.keys(_index243).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index243[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index243[key];\n },\n });\n});\nvar _index244 = require(\"./yearsToMonths.cjs\");\nObject.keys(_index244).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index244[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index244[key];\n },\n });\n});\nvar _index245 = require(\"./yearsToQuarters.cjs\");\nObject.keys(_index245).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index245[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index245[key];\n },\n });\n});\n", "'use strict'\n\nconst { readdir, stat, unlink, symlink, lstat, readlink } = require('fs/promises')\nconst { dirname, join } = require('path')\nconst { format, addDays, addHours, parse, isValid } = require('date-fns')\n\nfunction parseSize (size) {\n let multiplier = 1024 ** 2\n if (typeof size !== 'string' && typeof size !== 'number') {\n return null\n }\n if (typeof size === 'string') {\n const match = size.match(/^([\\d.]+)(\\w?)$/)\n if (match) {\n const unit = match[2]?.toLowerCase()\n size = +match[1]\n multiplier = unit === 'g' ? 1024 ** 3 : unit === 'k' ? 1024 : unit === 'b' ? 1 : 1024 ** 2\n } else {\n throw new Error(`${size} is not a valid size in KB, MB or GB`)\n }\n }\n return size * multiplier\n}\n\nfunction parseFrequency (frequency) {\n const today = new Date()\n if (frequency === 'daily') {\n const start = today.setHours(0, 0, 0, 0)\n return { frequency, start, next: getNextDay(start) }\n }\n if (frequency === 'hourly') {\n const start = today.setMinutes(0, 0, 0)\n return { frequency, start, next: getNextHour(start) }\n }\n if (typeof frequency === 'number') {\n const start = today.getTime() - today.getTime() % frequency\n return { frequency, start, next: getNextCustom(frequency) }\n }\n if (frequency) {\n throw new Error(`${frequency} is neither a supported frequency or a number of milliseconds`)\n }\n return null\n}\n\nfunction validateLimitOptions (limit) {\n if (limit) {\n if (typeof limit !== 'object') {\n throw new Error('limit must be an object')\n }\n if (typeof limit.count !== 'number' || limit.count <= 0) {\n throw new Error('limit.count must be a number greater than 0')\n }\n if (typeof limit.removeOtherLogFiles !== 'undefined' && typeof limit.removeOtherLogFiles !== 'boolean') {\n throw new Error('limit.removeOtherLogFiles must be boolean')\n }\n }\n}\n\nfunction getNextDay (start) {\n return addDays(new Date(start), 1).setHours(0, 0, 0, 0)\n}\n\nfunction getNextHour (start) {\n return addHours(new Date(start), 1).setMinutes(0, 0, 0)\n}\n\nfunction getNextCustom (frequency) {\n const time = Date.now()\n return time - time % frequency + frequency\n}\n\nfunction getNext (frequency) {\n if (frequency === 'daily') {\n return getNextDay(new Date().setHours(0, 0, 0, 0))\n }\n if (frequency === 'hourly') {\n return getNextHour(new Date().setMinutes(0, 0, 0))\n }\n return getNextCustom(frequency)\n}\n\nfunction getFileName (fileVal) {\n if (!fileVal) {\n throw new Error('No file name provided')\n }\n return typeof fileVal === 'function' ? fileVal() : fileVal\n}\n\nfunction buildFileName (fileVal, date, lastNumber = 1, extension) {\n const dateStr = date ? `.${date}` : ''\n const extensionStr = typeof extension !== 'string' ? '' : extension.startsWith('.') ? extension : `.${extension}`\n return `${getFileName(fileVal)}${dateStr}.${lastNumber}${extensionStr}`\n}\n\nfunction identifyLogFile (checkedFileName, fileVal, dateFormat, extension) {\n const baseFileNameStr = getFileName(fileVal)\n if (!checkedFileName.startsWith(baseFileNameStr)) return false\n const checkFileNameSegments = checkedFileName\n .slice(baseFileNameStr.length + 1)\n .split('.')\n let expectedSegmentCount = 1\n if (typeof dateFormat === 'string' && dateFormat.length > 0) expectedSegmentCount++\n if (typeof extension === 'string' && extension.length > 0) expectedSegmentCount++\n const extensionStr = typeof extension !== 'string' ? '' : extension.startsWith('.') ? extension.slice(1) : extension\n if (checkFileNameSegments.length !== expectedSegmentCount) return false\n if (extensionStr.length > 0) {\n const chkExtension = checkFileNameSegments.pop()\n if (extensionStr !== chkExtension) return false\n }\n const chkFileNumber = checkFileNameSegments.pop()\n const fileNumber = Number(chkFileNumber)\n if (!Number.isInteger(fileNumber)) {\n return false\n }\n let fileTime = 0\n if (typeof dateFormat === 'string' && dateFormat.length > 0) {\n const d = parse(checkFileNameSegments[0], dateFormat, new Date())\n if (!isValid(d)) return false\n fileTime = d.getTime()\n }\n return { fileName: checkedFileName, fileTime, fileNumber }\n}\n\nasync function getFileSize (filePath) {\n try {\n const fileStats = await stat(filePath)\n return fileStats.size\n } catch {\n return 0\n }\n}\n\nasync function detectLastNumber (fileVal, time = null) {\n const fileName = getFileName(fileVal)\n try {\n const numbers = await readFileTrailingNumbers(dirname(fileName), time)\n return numbers.sort((a, b) => b - a)[0]\n } catch {\n return 1\n }\n}\n\nasync function readFileTrailingNumbers (folder, time) {\n const numbers = [1]\n for (const file of await readdir(folder)) {\n if (time && !(await isMatchingTime(join(folder, file), time))) {\n continue\n }\n const number = extractTrailingNumber(file)\n if (number) {\n numbers.push(number)\n }\n }\n return numbers\n}\n\nfunction extractTrailingNumber (fileName) {\n const match = fileName.match(/(\\d+)$/)\n return match ? +match[1] : null\n}\n\nfunction extractFileName (fileName) {\n return fileName.split(/(\\\\|\\/)/g).pop()\n}\n\nasync function isMatchingTime (filePath, time) {\n const { birthtimeMs } = await stat(filePath)\n return birthtimeMs >= time\n}\n\nasync function removeOldFiles ({ count, removeOtherLogFiles, baseFile, dateFormat, extension, createdFileNames, newFileName }) {\n if (!removeOtherLogFiles) {\n createdFileNames.push(newFileName)\n if (createdFileNames.length > count) {\n const filesToRemove = createdFileNames.splice(0, createdFileNames.length - 1 - count)\n await Promise.allSettled(filesToRemove.map(file => unlink(file)))\n }\n } else {\n let files = []\n const pathSegments = getFileName(baseFile).split(/(\\\\|\\/)/g)\n const baseFileNameStr = pathSegments.pop()\n for (const fileEntry of await readdir(join(...pathSegments))) {\n const f = identifyLogFile(fileEntry, baseFileNameStr, dateFormat, extension)\n if (f) {\n files.push(f)\n }\n }\n files = files.sort((i, j) => {\n if (i.fileTime === j.fileTime) {\n return i.fileNumber - j.fileNumber\n }\n return i.fileTime - j.fileTime\n })\n if (files.length > count) {\n await Promise.allSettled(\n files\n .slice(0, files.length - count)\n .map(file => unlink(join(...pathSegments, file.fileName)))\n )\n }\n }\n}\n\nasync function checkSymlink (fileName, linkPath) {\n const stats = await lstat(linkPath).then(stats => stats, () => null)\n if (stats?.isSymbolicLink()) {\n const existingTarget = await readlink(linkPath)\n if (extractFileName(existingTarget) === extractFileName(fileName)) {\n return false\n }\n await unlink(linkPath)\n }\n return true\n}\n\nasync function createSymlink (fileVal) {\n const linkPath = join(dirname(fileVal), 'current.log')\n const shouldCreateSymlink = await checkSymlink(fileVal, linkPath)\n if (shouldCreateSymlink) {\n await symlink(extractFileName(fileVal), linkPath)\n }\n return false\n}\n\nfunction validateDateFormat (formatStr) {\n const invalidChars = /[/\\\\?%*:|\"<>]/g\n if (invalidChars.test(formatStr)) {\n throw new Error(`${formatStr} contains invalid characters`)\n }\n return true\n}\n\nfunction parseDate (formatStr, frequencySpec, parseStart = false) {\n if (!(formatStr && frequencySpec?.start && frequencySpec.next)) return null\n\n try {\n return format(parseStart ? frequencySpec.start : frequencySpec.next, formatStr)\n } catch (error) {\n throw new Error(`${formatStr} must be a valid date format`)\n }\n}\n\nmodule.exports = {\n buildFileName,\n identifyLogFile,\n removeOldFiles,\n checkSymlink,\n createSymlink,\n detectLastNumber,\n extractFileName,\n parseFrequency,\n getNext,\n parseSize,\n getFileName,\n getFileSize,\n validateLimitOptions,\n parseDate,\n validateDateFormat\n}\n", "'use strict'\n\nconst SonicBoom = require('sonic-boom')\nconst {\n buildFileName,\n removeOldFiles,\n createSymlink,\n detectLastNumber,\n parseSize,\n parseFrequency,\n getNext,\n getFileSize,\n validateLimitOptions,\n parseDate,\n validateDateFormat\n} = require('./lib/utils')\n\n/**\n * A function that returns a string path to the base file name\n *\n * @typedef {function} LogFilePath\n * @returns {string}\n */\n\n/**\n * @typedef {object} Options\n *\n * @property {string|LogFilePath} file - Absolute or relative path to the log file.\n * Your application needs the write right on the parent folder.\n * Number will be appended to this file name.\n * When the parent folder already contains numbered files, numbering will continue based on the highest number.\n * If this path does not exist, the logger with throw an error unless you set `mkdir` to `true`.\n *\n * @property {string|number} size? - When specified, the maximum size of a given log file.\n * Can be combined with frequency.\n * Use 'k', 'm' and 'g' to express values in KB, MB or GB.\n * Numerical values will be considered as MB.\n *\n * @property {string|number} frequency? - When specified, the amount of time a given log file is used.\n * Can be combined with size.\n * Use 'daily' or 'hourly' to rotate file every day (or every hour).\n * Existing file within the current day (or hour) will be re-used.\n * Numerical values will be considered as a number of milliseconds.\n * Using a numerical value will always create a new file upon startup.\n *\n * @property {string} extension? - When specified, appends a file extension after the file number.\n *\n * @property {boolean} symlink? - When specified, creates a symlink to the current log file.\n *\n * @property {LimitOptions} limit? - strategy used to remove oldest files when rotating them.\n *\n * @property {string} dateFormat? - When specified, appends the current date/time to the file name in the provided format.\n * Supports date formats from `date-fns` (see: https://date-fns.org/v4.1.0/docs/format), such as 'yyyy-MM-dd' and 'yyyy-MM-dd-hh'.\n */\n\n/**\n * @typedef {object} LimitOptions\n *\n * @property {number} count? -number of log files, **in addition to the currently used file**.\n * @property {boolean} removeOtherLogFiles? - when true, older file matching the log file format will also be removed.\n */\n\n/**\n * @typedef {Options & import('sonic-boom').SonicBoomOpts} PinoRollOptions\n */\n\n/**\n * Creates a Pino transport (a Sonic-boom stream) to writing into files.\n * Automatically rolls your files based on a given frequency, size, or both.\n *\n * @param {PinoRollOptions} options - to configure file destionation, and rolling rules.\n * @returns {SonicBoom} the Sonic boom steam, usabled as Pino transport.\n */\nmodule.exports = async function ({\n file,\n size,\n frequency,\n extension,\n limit,\n symlink,\n dateFormat,\n ...opts\n} = {}) {\n validateLimitOptions(limit)\n validateDateFormat(dateFormat)\n const frequencySpec = parseFrequency(frequency)\n\n let date = parseDate(dateFormat, frequencySpec, true)\n let number = await detectLastNumber(file, frequencySpec?.start, dateFormat)\n\n let fileName = buildFileName(file, date, number, extension)\n const createdFileNames = [fileName]\n let currentSize = await getFileSize(fileName)\n const maxSize = parseSize(size)\n\n const destination = new SonicBoom({ ...opts, dest: fileName })\n\n if (symlink) {\n createSymlink(fileName)\n }\n\n let rollTimeout\n if (frequencySpec) {\n destination.once('close', () => {\n clearTimeout(rollTimeout)\n })\n scheduleRoll()\n }\n\n if (maxSize) {\n destination.on('write', writtenSize => {\n currentSize += writtenSize\n if (fileName === destination.file && currentSize >= maxSize) {\n currentSize = 0\n fileName = buildFileName(file, date, ++number, extension)\n // delay to let the destination finish its write\n destination.once('drain', roll)\n }\n })\n }\n\n function roll () {\n destination.reopen(fileName)\n if (symlink) {\n createSymlink(fileName)\n }\n if (limit) {\n removeOldFiles({ ...limit, baseFile: file, dateFormat, extension, createdFileNames, newFileName: fileName })\n }\n }\n\n function scheduleRoll () {\n clearTimeout(rollTimeout)\n rollTimeout = setTimeout(() => {\n const prevDate = date\n date = parseDate(dateFormat, frequencySpec)\n if (dateFormat && date && date !== prevDate) number = 0\n fileName = buildFileName(file, date, ++number, extension)\n roll()\n frequencySpec.next = getNext(frequency)\n scheduleRoll()\n }, frequencySpec.next - Date.now())\n }\n\n return destination\n}\n"], + "mappings": "2EAAA,IAAAA,GAAAC,EAAA,CAAAC,GAAAC,KAAA,cAIA,GAAI,OAAO,kBAAsB,KAAe,OAAO,QAAY,IAAa,CAG9E,IAASC,EAAT,SAAgBC,EAAI,CAGlB,IADcA,EAAK,GAAKA,EAAK,OACf,GACZ,MAAI,OAAOA,GAAO,UAAY,OAAOA,GAAO,SACpC,UAAU,4BAA4B,EAExC,WAAW,0EAA0E,EAG7F,QAAQ,KAAKC,EAAK,EAAG,EAAG,OAAOD,CAAE,CAAC,CACpC,EAbMC,EAAM,IAAI,WAAW,IAAI,kBAAkB,CAAC,CAAC,EAcnDH,GAAO,QAAUC,CACnB,KAAO,CAEL,IAASA,EAAT,SAAgBC,EAAI,CAGlB,IADcA,EAAK,GAAKA,EAAK,OACf,GACZ,MAAI,OAAOA,GAAO,UAAY,OAAOA,GAAO,SACpC,UAAU,4BAA4B,EAExC,WAAW,0EAA0E,EAE7F,IAAME,EAAS,KAAK,IAAI,EAAI,OAAOF,CAAE,EACrC,KAAOE,EAAS,KAAK,IAAI,GAAE,CAC7B,EAEAJ,GAAO,QAAUC,CAEnB,ICrCA,IAAAI,GAAAC,EAAA,CAAAC,GAAAC,KAAA,cAEA,IAAMC,EAAK,QAAQ,IAAI,EACjBC,GAAe,QAAQ,QAAQ,EAC/BC,GAAW,QAAQ,MAAM,EAAE,SAC3BC,GAAO,QAAQ,MAAM,EACrBC,GAAQ,KACRC,GAAS,QAAQ,QAAQ,EAEzBC,GAAqB,IACrBC,GAAe,OAAO,YA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C,CAAW,CAC1B,CAAC,EACDC,EAAa,GAGXH,GACFC,EAAY,GAAG,QAASG,GAAe,CACrCL,GAAeK,EACXP,IAAaI,EAAY,MAAQF,GAAeC,IAClDD,EAAc,EACdF,EAAWtB,GAAcW,EAAMS,EAAM,EAAEC,EAAQP,CAAS,EAExDY,EAAY,KAAK,QAASI,CAAI,EAElC,CAAC,EAGH,SAASA,GAAQ,CACfJ,EAAY,OAAOJ,CAAQ,EACvBN,GACFd,GAAcoB,CAAQ,EAEpBP,GACFd,GAAe,CAAE,GAAGc,EAAO,SAAUJ,EAAM,WAAAM,EAAY,UAAAH,EAAW,iBAAAS,EAAkB,YAAaD,CAAS,CAAC,CAE/G,CAEA,SAASM,GAAgB,CACvB,aAAaD,CAAW,EACxBA,EAAc,WAAW,IAAM,CAC7B,IAAMI,EAAWX,EACjBA,EAAOX,GAAUQ,EAAYE,CAAa,EACtCF,GAAcG,GAAQA,IAASW,IAAUV,EAAS,GACtDC,EAAWtB,GAAcW,EAAMS,EAAM,EAAEC,EAAQP,CAAS,EACxDgB,EAAK,EACLX,EAAc,KAAOb,GAAQO,CAAS,EACtCe,EAAa,CACf,EAAGT,EAAc,KAAO,KAAK,IAAI,CAAC,CACpC,CAEA,OAAOO,CACT", + "names": ["require_atomic_sleep", "__commonJSMin", "exports", "module", "sleep", "ms", "nil", "target", "require_sonic_boom", "__commonJSMin", "exports", "module", "fs", "EventEmitter", "inherits", "path", "sleep", "assert", "BUSY_WRITE_TIMEOUT", "kEmptyBuffer", "MAX_WRITE", "kContentModeBuffer", "kContentModeUtf8", "major", "minor", "kCopyBuffer", "openFile", "file", "sonic", "fileOpened", "err", "fd", "reopening", "flags", "mode", "SonicBoom", "opts", "dest", "minLength", "maxLength", "maxWrite", "periodicFlush", "sync", "append", "mkdir", "retryEAGAIN", "fsync", "contentMode", "fsWriteSync", "fsWrite", "writeBuffer", "flushBuffer", "flushBufferSync", "actualWriteBuffer", "write", "flush", "flushSync", "actualWrite", "n", "releasedBufObj", "releaseWritingBuf", "len", "actualClose", "emitDrain", "name", "writingBuf", "mergeBuf", "bufs", "data", "lens", "callFlushCallbackOnDrain", "cb", "onDrain", "onError", "error", "buf", "release", "written", "closeWrapped", "done", "require_constants", "__commonJSMin", "exports", "daysInWeek", "daysInYear", "maxTime", "minTime", "millisecondsInWeek", "millisecondsInDay", "millisecondsInMinute", "millisecondsInHour", "millisecondsInSecond", "minutesInYear", "minutesInMonth", "minutesInDay", "minutesInHour", "monthsInQuarter", "monthsInYear", "quartersInYear", "secondsInHour", "secondsInMinute", "secondsInDay", "secondsInWeek", "secondsInYear", "secondsInMonth", "secondsInQuarter", "constructFromSymbol", "require_constructFrom", "__commonJSMin", "exports", "constructFrom", "_index", "date", "value", "require_toDate", "__commonJSMin", "exports", "toDate", "_index", "argument", "context", "require_addDays", "__commonJSMin", "exports", "addDays", "_index", "_index2", "date", "amount", "options", "_date", "require_addMonths", "__commonJSMin", "exports", "addMonths", "_index", "_index2", "date", "amount", "options", "_date", "dayOfMonth", "endOfDesiredMonth", "daysInMonth", "require_add", "__commonJSMin", "exports", "add", "_index", "_index2", "_index3", "_index4", "date", "duration", "options", "years", "months", "weeks", "days", "hours", "minutes", "seconds", "_date", "dateWithMonths", "dateWithDays", "minutesToAdd", "msToAdd", "require_isSaturday", "__commonJSMin", "exports", "isSaturday", "_index", "date", "options", "require_isSunday", "__commonJSMin", "exports", "isSunday", "_index", "date", "options", "require_isWeekend", "__commonJSMin", "exports", "isWeekend", "_index", "date", "options", "day", "require_addBusinessDays", "__commonJSMin", "exports", "addBusinessDays", "_index", "_index2", "_index3", "_index4", "_index5", "date", "amount", "options", "_date", "startedOnWeekend", "hours", "sign", "fullWeeks", "restDays", "require_addMilliseconds", "__commonJSMin", "exports", "addMilliseconds", "_index", "_index2", "date", "amount", "options", "require_addHours", "__commonJSMin", "exports", "addHours", "_index", "_index2", "date", "amount", "options", "require_defaultOptions", "__commonJSMin", "exports", "getDefaultOptions", "setDefaultOptions", "defaultOptions", "newOptions", "require_startOfWeek", "__commonJSMin", "exports", "startOfWeek", "_index", "_index2", "date", "options", "defaultOptions", "weekStartsOn", "_date", "day", "diff", "require_startOfISOWeek", "__commonJSMin", "exports", "startOfISOWeek", "_index", "date", "options", "require_getISOWeekYear", "__commonJSMin", "exports", "getISOWeekYear", "_index", "_index2", "_index3", "date", "options", "_date", "year", "fourthOfJanuaryOfNextYear", "startOfNextYear", "fourthOfJanuaryOfThisYear", "startOfThisYear", "require_getTimezoneOffsetInMilliseconds", "__commonJSMin", "exports", "getTimezoneOffsetInMilliseconds", "_index", "date", "_date", "utcDate", "require_normalizeDates", "__commonJSMin", "exports", "normalizeDates", "_index", "context", "dates", "normalize", "date", "require_startOfDay", "__commonJSMin", "exports", "startOfDay", "_index", "date", "options", "_date", "require_differenceInCalendarDays", "__commonJSMin", "exports", "differenceInCalendarDays", "_index", "_index2", "_index3", "_index4", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "laterStartOfDay", "earlierStartOfDay", "laterTimestamp", "earlierTimestamp", "require_startOfISOWeekYear", "__commonJSMin", "exports", "startOfISOWeekYear", "_index", "_index2", "_index3", "date", "options", "year", "fourthOfJanuary", "require_setISOWeekYear", "__commonJSMin", "exports", "setISOWeekYear", "_index", "_index2", "_index3", "_index4", "date", "weekYear", "options", "_date", "diff", "fourthOfJanuary", "require_addISOWeekYears", "__commonJSMin", "exports", "addISOWeekYears", "_index", "_index2", "date", "amount", "options", "require_addMinutes", "__commonJSMin", "exports", "addMinutes", "_index", "_index2", "date", "amount", "options", "_date", "require_addQuarters", "__commonJSMin", "exports", "addQuarters", "_index", "date", "amount", "options", "require_addSeconds", "__commonJSMin", "exports", "addSeconds", "_index", "date", "amount", "options", "require_addWeeks", "__commonJSMin", "exports", "addWeeks", "_index", "date", "amount", "options", "require_addYears", "__commonJSMin", "exports", "addYears", "_index", "date", "amount", "options", "require_areIntervalsOverlapping", "__commonJSMin", "exports", "areIntervalsOverlapping", "_index", "intervalLeft", "intervalRight", "options", "leftStartTime", "leftEndTime", "a", "b", "rightStartTime", "rightEndTime", "require_max", "__commonJSMin", "exports", "max", "_index", "_index2", "dates", "options", "result", "context", "date", "date_", "require_min", "__commonJSMin", "exports", "min", "_index", "_index2", "dates", "options", "result", "context", "date", "date_", "require_clamp", "__commonJSMin", "exports", "clamp", "_index", "_index2", "_index3", "date", "interval", "options", "date_", "start", "end", "require_closestIndexTo", "__commonJSMin", "exports", "closestIndexTo", "_index", "dateToCompare", "dates", "timeToCompare", "result", "minDistance", "date", "index", "date_", "distance", "require_closestTo", "__commonJSMin", "exports", "closestTo", "_index", "_index2", "_index3", "dateToCompare", "dates", "options", "dateToCompare_", "dates_", "index", "require_compareAsc", "__commonJSMin", "exports", "compareAsc", "_index", "dateLeft", "dateRight", "diff", "require_compareDesc", "__commonJSMin", "exports", "compareDesc", "_index", "dateLeft", "dateRight", "diff", "require_constructNow", "__commonJSMin", "exports", "constructNow", "_index", "date", "require_daysToWeeks", "__commonJSMin", "exports", "daysToWeeks", "_index", "days", "result", "require_isSameDay", "__commonJSMin", "exports", "isSameDay", "_index", "_index2", "laterDate", "earlierDate", "options", "dateLeft_", "dateRight_", "require_isDate", "__commonJSMin", "exports", "isDate", "value", "require_isValid", "__commonJSMin", "exports", "isValid", "_index", "_index2", "date", "require_differenceInBusinessDays", "__commonJSMin", "exports", "differenceInBusinessDays", "_index", "_index2", "_index3", "_index4", "_index5", "_index6", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "diff", "sign", "weeks", "result", "movingDate", "require_differenceInCalendarISOWeekYears", "__commonJSMin", "exports", "differenceInCalendarISOWeekYears", "_index", "_index2", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "require_differenceInCalendarISOWeeks", "__commonJSMin", "exports", "differenceInCalendarISOWeeks", "_index", "_index2", "_index3", "_index4", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "startOfISOWeekLeft", "startOfISOWeekRight", "timestampLeft", "timestampRight", "require_differenceInCalendarMonths", "__commonJSMin", "exports", "differenceInCalendarMonths", "_index", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "yearsDiff", "monthsDiff", "require_getQuarter", "__commonJSMin", "exports", "getQuarter", "_index", "date", "options", "_date", "require_differenceInCalendarQuarters", "__commonJSMin", "exports", "differenceInCalendarQuarters", "_index", "_index2", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "yearsDiff", "quartersDiff", "require_differenceInCalendarWeeks", "__commonJSMin", "exports", "differenceInCalendarWeeks", "_index", "_index2", "_index3", "_index4", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "laterStartOfWeek", "earlierStartOfWeek", "laterTimestamp", "earlierTimestamp", "require_differenceInCalendarYears", "__commonJSMin", "exports", "differenceInCalendarYears", "_index", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "require_differenceInDays", "__commonJSMin", "exports", "differenceInDays", "_index", "_index2", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "sign", "compareLocalAsc", "difference", "isLastDayNotFull", "result", "diff", "require_getRoundingMethod", "__commonJSMin", "exports", "getRoundingMethod", "method", "number", "result", "require_differenceInHours", "__commonJSMin", "exports", "differenceInHours", "_index", "_index2", "_index3", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "diff", "require_subISOWeekYears", "__commonJSMin", "exports", "subISOWeekYears", "_index", "date", "amount", "options", "require_differenceInISOWeekYears", "__commonJSMin", "exports", "differenceInISOWeekYears", "_index", "_index2", "_index3", "_index4", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "sign", "diff", "adjustedDate", "isLastISOWeekYearNotFull", "result", "require_differenceInMilliseconds", "__commonJSMin", "exports", "differenceInMilliseconds", "_index", "laterDate", "earlierDate", "require_differenceInMinutes", "__commonJSMin", "exports", "differenceInMinutes", "_index", "_index2", "_index3", "dateLeft", "dateRight", "options", "diff", "require_endOfDay", "__commonJSMin", "exports", "endOfDay", "_index", "date", "options", "_date", "require_endOfMonth", "__commonJSMin", "exports", "endOfMonth", "_index", "date", "options", "_date", "month", "require_isLastDayOfMonth", "__commonJSMin", "exports", "isLastDayOfMonth", "_index", "_index2", "_index3", "date", "options", "_date", "require_differenceInMonths", "__commonJSMin", "exports", "differenceInMonths", "_index", "_index2", "_index3", "_index4", "laterDate", "earlierDate", "options", "laterDate_", "workingLaterDate", "earlierDate_", "sign", "difference", "isLastMonthNotFull", "result", "require_differenceInQuarters", "__commonJSMin", "exports", "differenceInQuarters", "_index", "_index2", "laterDate", "earlierDate", "options", "diff", "require_differenceInSeconds", "__commonJSMin", "exports", "differenceInSeconds", "_index", "_index2", "laterDate", "earlierDate", "options", "diff", "require_differenceInWeeks", "__commonJSMin", "exports", "differenceInWeeks", "_index", "_index2", "laterDate", "earlierDate", "options", "diff", "require_differenceInYears", "__commonJSMin", "exports", "differenceInYears", "_index", "_index2", "_index3", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "sign", "diff", "partial", "result", "require_normalizeInterval", "__commonJSMin", "exports", "normalizeInterval", "_index", "context", "interval", "start", "end", "require_eachDayOfInterval", "__commonJSMin", "exports", "eachDayOfInterval", "_index", "_index2", "interval", "options", "start", "end", "reversed", "endTime", "date", "step", "dates", "require_eachHourOfInterval", "__commonJSMin", "exports", "eachHourOfInterval", "_index", "_index2", "interval", "options", "start", "end", "reversed", "endTime", "date", "step", "dates", "require_eachMinuteOfInterval", "__commonJSMin", "exports", "eachMinuteOfInterval", "_index", "_index2", "_index3", "interval", "options", "start", "end", "reversed", "endTime", "date", "step", "dates", "require_eachMonthOfInterval", "__commonJSMin", "exports", "eachMonthOfInterval", "_index", "_index2", "interval", "options", "start", "end", "reversed", "endTime", "date", "step", "dates", "require_startOfQuarter", "__commonJSMin", "exports", "startOfQuarter", "_index", "date", "options", "_date", "currentMonth", "month", "require_eachQuarterOfInterval", "__commonJSMin", "exports", "eachQuarterOfInterval", "_index", "_index2", "_index3", "_index4", "interval", "options", "start", "end", "reversed", "endTime", "date", "step", "dates", "require_eachWeekOfInterval", "__commonJSMin", "exports", "eachWeekOfInterval", "_index", "_index2", "_index3", "_index4", "interval", "options", "start", "end", "reversed", "startDateWeek", "endDateWeek", "endTime", "currentDate", "step", "dates", "require_eachWeekendOfInterval", "__commonJSMin", "exports", "eachWeekendOfInterval", "_index", "_index2", "_index3", "_index4", "interval", "options", "start", "end", "dateInterval", "weekends", "index", "date", "require_startOfMonth", "__commonJSMin", "exports", "startOfMonth", "_index", "date", "options", "_date", "require_eachWeekendOfMonth", "__commonJSMin", "exports", "eachWeekendOfMonth", "_index", "_index2", "_index3", "date", "options", "start", "end", "require_endOfYear", "__commonJSMin", "exports", "endOfYear", "_index", "date", "options", "_date", "year", "require_startOfYear", "__commonJSMin", "exports", "startOfYear", "_index", "date", "options", "date_", "require_eachWeekendOfYear", "__commonJSMin", "exports", "eachWeekendOfYear", "_index", "_index2", "_index3", "date", "options", "start", "end", "require_eachYearOfInterval", "__commonJSMin", "exports", "eachYearOfInterval", "_index", "_index2", "interval", "options", "start", "end", "reversed", "endTime", "date", "step", "dates", "require_endOfDecade", "__commonJSMin", "exports", "endOfDecade", "_index", "date", "options", "_date", "year", "decade", "require_endOfHour", "__commonJSMin", "exports", "endOfHour", "_index", "date", "options", "_date", "require_endOfWeek", "__commonJSMin", "exports", "endOfWeek", "_index", "_index2", "date", "options", "defaultOptions", "weekStartsOn", "_date", "day", "diff", "require_endOfISOWeek", "__commonJSMin", "exports", "endOfISOWeek", "_index", "date", "options", "require_endOfISOWeekYear", "__commonJSMin", "exports", "endOfISOWeekYear", "_index", "_index2", "_index3", "date", "options", "year", "fourthOfJanuaryOfNextYear", "_date", "require_endOfMinute", "__commonJSMin", "exports", "endOfMinute", "_index", "date", "options", "_date", "require_endOfQuarter", "__commonJSMin", "exports", "endOfQuarter", "_index", "date", "options", "_date", "currentMonth", "month", "require_endOfSecond", "__commonJSMin", "exports", "endOfSecond", "_index", "date", "options", "_date", "require_endOfToday", "__commonJSMin", "exports", "endOfToday", "_index", "options", "require_endOfTomorrow", "__commonJSMin", "exports", "endOfTomorrow", "_index", "options", "now", "year", "month", "day", "date", "require_endOfYesterday", "__commonJSMin", "exports", "endOfYesterday", "_index", "_index2", "options", "now", "date", "require_formatDistance", "__commonJSMin", "exports", "formatDistanceLocale", "formatDistance", "token", "count", "options", "result", "tokenValue", "require_buildFormatLongFn", "__commonJSMin", "exports", "buildFormatLongFn", "args", "options", "width", "require_formatLong", "__commonJSMin", "exports", "_index", "dateFormats", "timeFormats", "dateTimeFormats", "formatLong", "require_formatRelative", "__commonJSMin", "exports", "formatRelativeLocale", "formatRelative", "token", "_date", "_baseDate", "_options", "require_buildLocalizeFn", "__commonJSMin", "exports", "buildLocalizeFn", "args", "value", "options", "context", "valuesArray", "defaultWidth", "width", "index", "require_localize", "__commonJSMin", "exports", "_index", "eraValues", "quarterValues", "monthValues", "dayValues", "dayPeriodValues", "formattingDayPeriodValues", "ordinalNumber", "dirtyNumber", "_options", "number", "rem100", "localize", "quarter", "require_buildMatchFn", "__commonJSMin", "exports", "buildMatchFn", "args", "string", "options", "width", "matchPattern", "matchResult", "matchedString", "parsePatterns", "key", "findIndex", "pattern", "findKey", "value", "rest", "object", "predicate", "array", "require_buildMatchPatternFn", "__commonJSMin", "exports", "buildMatchPatternFn", "args", "string", "options", "matchResult", "matchedString", "parseResult", "value", "rest", "require_match", "__commonJSMin", "exports", "_index", "_index2", "matchOrdinalNumberPattern", "parseOrdinalNumberPattern", "matchEraPatterns", "parseEraPatterns", "matchQuarterPatterns", "parseQuarterPatterns", "matchMonthPatterns", "parseMonthPatterns", "matchDayPatterns", "parseDayPatterns", "matchDayPeriodPatterns", "parseDayPeriodPatterns", "match", "value", "index", "require_en_US", "__commonJSMin", "exports", "_index", "_index2", "_index3", "_index4", "_index5", "enUS", "require_defaultLocale", "__commonJSMin", "exports", "_index", "require_getDayOfYear", "__commonJSMin", "exports", "getDayOfYear", "_index", "_index2", "_index3", "date", "options", "_date", "require_getISOWeek", "__commonJSMin", "exports", "getISOWeek", "_index", "_index2", "_index3", "_index4", "date", "options", "_date", "diff", "require_getWeekYear", "__commonJSMin", "exports", "getWeekYear", "_index", "_index2", "_index3", "_index4", "date", "options", "_date", "year", "defaultOptions", "firstWeekContainsDate", "firstWeekOfNextYear", "startOfNextYear", "firstWeekOfThisYear", "startOfThisYear", "require_startOfWeekYear", "__commonJSMin", "exports", "startOfWeekYear", "_index", "_index2", "_index3", "_index4", "date", "options", "defaultOptions", "firstWeekContainsDate", "year", "firstWeek", "require_getWeek", "__commonJSMin", "exports", "getWeek", "_index", "_index2", "_index3", "_index4", "date", "options", "_date", "diff", "require_addLeadingZeros", "__commonJSMin", "exports", "addLeadingZeros", "number", "targetLength", "sign", "output", "require_lightFormatters", "__commonJSMin", "exports", "_index", "lightFormatters", "date", "token", "signedYear", "year", "month", "dayPeriodEnumValue", "numberOfDigits", "milliseconds", "fractionalSeconds", "require_formatters", "__commonJSMin", "exports", "_index", "_index2", "_index3", "_index4", "_index5", "_index6", "_index7", "dayPeriodEnum", "formatters", "date", "token", "localize", "era", "signedYear", "year", "options", "signedWeekYear", "weekYear", "twoDigitYear", "isoWeekYear", "quarter", "month", "week", "isoWeek", "dayOfYear", "dayOfWeek", "localDayOfWeek", "isoDayOfWeek", "dayPeriodEnumValue", "hours", "_localize", "timezoneOffset", "formatTimezoneWithOptionalMinutes", "formatTimezone", "formatTimezoneShort", "timestamp", "offset", "delimiter", "sign", "absOffset", "minutes", "require_longFormatters", "__commonJSMin", "exports", "dateLongFormatter", "pattern", "formatLong", "timeLongFormatter", "dateTimeLongFormatter", "matchResult", "datePattern", "timePattern", "dateTimeFormat", "longFormatters", "require_protectedTokens", "__commonJSMin", "exports", "isProtectedDayOfYearToken", "isProtectedWeekYearToken", "warnOrThrowProtectedError", "dayOfYearTokenRE", "weekYearTokenRE", "throwTokens", "token", "format", "input", "_message", "message", "subject", "require_format", "__commonJSMin", "exports", "format", "_index3", "_index4", "_index", "_index2", "_index5", "_index6", "_index7", "formattingTokensRegExp", "longFormattingTokensRegExp", "escapedStringRegExp", "doubleQuoteRegExp", "unescapedLatinCharacterRegExp", "date", "formatStr", "options", "defaultOptions", "locale", "firstWeekContainsDate", "weekStartsOn", "originalDate", "parts", "substring", "firstCharacter", "longFormatter", "cleanEscapedString", "formatterOptions", "part", "token", "formatter", "input", "matched", "require_formatDistance", "__commonJSMin", "exports", "formatDistance", "_index", "_index2", "_index3", "_index4", "_index5", "_index6", "_index7", "_index8", "laterDate", "earlierDate", "options", "defaultOptions", "locale", "minutesInAlmostTwoDays", "comparison", "localizeOptions", "laterDate_", "earlierDate_", "seconds", "offsetInSeconds", "minutes", "months", "hours", "days", "nearestMonth", "monthsSinceStartOfYear", "years", "require_formatDistanceStrict", "__commonJSMin", "exports", "formatDistanceStrict", "_index", "_index2", "_index3", "_index4", "_index5", "_index6", "_index7", "laterDate", "earlierDate", "options", "defaultOptions", "locale", "comparison", "localizeOptions", "laterDate_", "earlierDate_", "roundingMethod", "milliseconds", "minutes", "timezoneOffset", "dstNormalizedMinutes", "defaultUnit", "unit", "seconds", "roundedMinutes", "hours", "days", "months", "years", "require_formatDistanceToNow", "__commonJSMin", "exports", "formatDistanceToNow", "_index", "_index2", "date", "options", "require_formatDistanceToNowStrict", "__commonJSMin", "exports", "formatDistanceToNowStrict", "_index", "_index2", "date", "options", "require_formatDuration", "__commonJSMin", "exports", "formatDuration", "_index", "_index2", "defaultFormat", "duration", "options", "defaultOptions", "locale", "format", "zero", "delimiter", "acc", "unit", "token", "m", "value", "require_formatISO", "__commonJSMin", "exports", "formatISO", "_index", "_index2", "date", "options", "date_", "format", "representation", "result", "tzOffset", "dateDelimiter", "timeDelimiter", "day", "month", "offset", "absoluteOffset", "hourOffset", "minuteOffset", "hour", "minute", "second", "separator", "time", "require_formatISO9075", "__commonJSMin", "exports", "formatISO9075", "_index", "_index2", "_index3", "date", "options", "date_", "format", "representation", "result", "dateDelimiter", "timeDelimiter", "day", "month", "hour", "minute", "second", "require_formatISODuration", "__commonJSMin", "exports", "formatISODuration", "duration", "years", "months", "days", "hours", "minutes", "seconds", "require_formatRFC3339", "__commonJSMin", "exports", "formatRFC3339", "_index", "_index2", "_index3", "date", "options", "date_", "fractionDigits", "day", "month", "year", "hour", "minute", "second", "fractionalSecond", "milliseconds", "fractionalSeconds", "offset", "tzOffset", "absoluteOffset", "hourOffset", "minuteOffset", "require_formatRFC7231", "__commonJSMin", "exports", "formatRFC7231", "_index", "_index2", "_index3", "days", "months", "date", "_date", "dayName", "dayOfMonth", "monthName", "year", "hour", "minute", "second", "require_formatRelative", "__commonJSMin", "exports", "formatRelative", "_index", "_index2", "_index3", "_index4", "_index5", "date", "baseDate", "options", "date_", "baseDate_", "defaultOptions", "locale", "weekStartsOn", "diff", "token", "formatStr", "require_fromUnixTime", "__commonJSMin", "exports", "fromUnixTime", "_index", "unixTime", "options", "require_getDate", "__commonJSMin", "exports", "getDate", "_index", "date", "options", "require_getDay", "__commonJSMin", "exports", "getDay", "_index", "date", "options", "require_getDaysInMonth", "__commonJSMin", "exports", "getDaysInMonth", "_index", "_index2", "date", "options", "_date", "year", "monthIndex", "lastDayOfMonth", "require_isLeapYear", "__commonJSMin", "exports", "isLeapYear", "_index", "date", "options", "year", "require_getDaysInYear", "__commonJSMin", "exports", "getDaysInYear", "_index", "_index2", "date", "options", "_date", "require_getDecade", "__commonJSMin", "exports", "getDecade", "_index", "date", "options", "year", "require_getDefaultOptions", "__commonJSMin", "exports", "getDefaultOptions", "_index", "require_getHours", "__commonJSMin", "exports", "getHours", "_index", "date", "options", "require_getISODay", "__commonJSMin", "exports", "getISODay", "_index", "date", "options", "day", "require_getISOWeeksInYear", "__commonJSMin", "exports", "getISOWeeksInYear", "_index", "_index2", "_index3", "date", "options", "thisYear", "diff", "require_getMilliseconds", "__commonJSMin", "exports", "getMilliseconds", "_index", "date", "require_getMinutes", "__commonJSMin", "exports", "getMinutes", "_index", "date", "options", "require_getMonth", "__commonJSMin", "exports", "getMonth", "_index", "date", "options", "require_getOverlappingDaysInIntervals", "__commonJSMin", "exports", "getOverlappingDaysInIntervals", "_index", "_index2", "_index3", "intervalLeft", "intervalRight", "leftStart", "leftEnd", "a", "b", "rightStart", "rightEnd", "overlapLeft", "left", "overlapRight", "right", "require_getSeconds", "__commonJSMin", "exports", "getSeconds", "_index", "date", "require_getTime", "__commonJSMin", "exports", "getTime", "_index", "date", "require_getUnixTime", "__commonJSMin", "exports", "getUnixTime", "_index", "date", "require_getWeekOfMonth", "__commonJSMin", "exports", "getWeekOfMonth", "_index", "_index2", "_index3", "_index4", "_index5", "date", "options", "defaultOptions", "weekStartsOn", "currentDayOfMonth", "startWeekDay", "lastDayOfFirstWeek", "remainingDaysAfterFirstWeek", "require_lastDayOfMonth", "__commonJSMin", "exports", "lastDayOfMonth", "_index", "date", "options", "_date", "month", "require_getWeeksInMonth", "__commonJSMin", "exports", "getWeeksInMonth", "_index", "_index2", "_index3", "_index4", "date", "options", "contextDate", "require_getYear", "__commonJSMin", "exports", "getYear", "_index", "date", "options", "require_hoursToMilliseconds", "__commonJSMin", "exports", "hoursToMilliseconds", "_index", "hours", "require_hoursToMinutes", "__commonJSMin", "exports", "hoursToMinutes", "_index", "hours", "require_hoursToSeconds", "__commonJSMin", "exports", "hoursToSeconds", "_index", "hours", "require_interval", "__commonJSMin", "exports", "interval", "_index", "start", "end", "options", "_start", "_end", "require_intervalToDuration", "__commonJSMin", "exports", "intervalToDuration", "_index", "_index2", "_index3", "_index4", "_index5", "_index6", "_index7", "_index8", "interval", "options", "start", "end", "duration", "years", "remainingMonths", "months", "remainingDays", "days", "remainingHours", "hours", "remainingMinutes", "minutes", "remainingSeconds", "seconds", "require_intlFormat", "__commonJSMin", "exports", "intlFormat", "_index", "date", "formatOrLocale", "localeOptions", "formatOptions", "isFormatOptions", "opts", "require_intlFormatDistance", "__commonJSMin", "exports", "intlFormatDistance", "_index", "_index2", "_index3", "_index4", "_index5", "_index6", "_index7", "_index8", "_index9", "_index10", "laterDate", "earlierDate", "options", "value", "unit", "laterDate_", "earlierDate_", "diffInSeconds", "require_isAfter", "__commonJSMin", "exports", "isAfter", "_index", "date", "dateToCompare", "require_isBefore", "__commonJSMin", "exports", "isBefore", "_index", "date", "dateToCompare", "require_isEqual", "__commonJSMin", "exports", "isEqual", "_index", "leftDate", "rightDate", "require_isExists", "__commonJSMin", "exports", "isExists", "year", "month", "day", "date", "require_isFirstDayOfMonth", "__commonJSMin", "exports", "isFirstDayOfMonth", "_index", "date", "options", "require_isFriday", "__commonJSMin", "exports", "isFriday", "_index", "date", "options", "require_isFuture", "__commonJSMin", "exports", "isFuture", "_index", "date", "require_transpose", "__commonJSMin", "exports", "transpose", "_index", "date", "constructor", "date_", "isConstructor", "require_Setter", "__commonJSMin", "exports", "_index", "_index2", "TIMEZONE_UNIT_PRIORITY", "Setter", "_utcDate", "_options", "ValueSetter", "value", "validateValue", "setValue", "priority", "subPriority", "date", "options", "flags", "DateTimezoneSetter", "context", "reference", "require_Parser", "__commonJSMin", "exports", "_Setter", "Parser", "dateString", "token", "match", "options", "result", "_utcDate", "_value", "_options", "require_EraParser", "__commonJSMin", "exports", "_Parser", "EraParser", "dateString", "token", "match", "date", "flags", "value", "require_constants", "__commonJSMin", "exports", "numericPatterns", "timezonePatterns", "require_utils", "__commonJSMin", "exports", "dayPeriodEnumToHours", "isLeapYearIndex", "mapValue", "normalizeTwoDigitYear", "parseAnyDigitsSigned", "parseNDigits", "parseNDigitsSigned", "parseNumericPattern", "parseTimezonePattern", "_index", "_constants", "parseFnResult", "mapFn", "pattern", "dateString", "matchResult", "sign", "hours", "minutes", "seconds", "n", "dayPeriod", "twoDigitYear", "currentYear", "isCommonEra", "absCurrentYear", "result", "rangeEnd", "rangeEndCentury", "isPreviousCentury", "year", "require_YearParser", "__commonJSMin", "exports", "_Parser", "_utils", "YearParser", "dateString", "token", "match", "valueCallback", "year", "_date", "value", "date", "flags", "currentYear", "normalizedTwoDigitYear", "require_LocalWeekYearParser", "__commonJSMin", "exports", "_index", "_index2", "_Parser", "_utils", "LocalWeekYearParser", "dateString", "token", "match", "valueCallback", "year", "_date", "value", "date", "flags", "options", "currentYear", "normalizedTwoDigitYear", "require_ISOWeekYearParser", "__commonJSMin", "exports", "_index", "_index2", "_Parser", "_utils", "ISOWeekYearParser", "dateString", "token", "date", "_flags", "value", "firstWeekOfYear", "require_ExtendedYearParser", "__commonJSMin", "exports", "_Parser", "_utils", "ExtendedYearParser", "dateString", "token", "date", "_flags", "value", "require_QuarterParser", "__commonJSMin", "exports", "_Parser", "_utils", "QuarterParser", "dateString", "token", "match", "_date", "value", "date", "_flags", "require_StandAloneQuarterParser", "__commonJSMin", "exports", "_Parser", "_utils", "StandAloneQuarterParser", "dateString", "token", "match", "_date", "value", "date", "_flags", "require_MonthParser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "MonthParser", "dateString", "token", "match", "valueCallback", "value", "_date", "date", "_flags", "require_StandAloneMonthParser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "StandAloneMonthParser", "dateString", "token", "match", "valueCallback", "value", "_date", "date", "_flags", "require_setWeek", "__commonJSMin", "exports", "setWeek", "_index", "_index2", "date", "week", "options", "date_", "diff", "require_LocalWeekParser", "__commonJSMin", "exports", "_index", "_index2", "_constants", "_Parser", "_utils", "LocalWeekParser", "dateString", "token", "match", "_date", "value", "date", "_flags", "options", "require_setISOWeek", "__commonJSMin", "exports", "setISOWeek", "_index", "_index2", "date", "week", "options", "_date", "diff", "require_ISOWeekParser", "__commonJSMin", "exports", "_index", "_index2", "_constants", "_Parser", "_utils", "ISOWeekParser", "dateString", "token", "match", "_date", "value", "date", "_flags", "require_DateParser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "DAYS_IN_MONTH", "DAYS_IN_MONTH_LEAP_YEAR", "DateParser", "dateString", "token", "match", "date", "value", "year", "isLeapYear", "month", "_flags", "require_DayOfYearParser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "DayOfYearParser", "dateString", "token", "match", "date", "value", "year", "_flags", "require_setDay", "__commonJSMin", "exports", "setDay", "_index", "_index2", "_index3", "date", "day", "options", "defaultOptions", "weekStartsOn", "date_", "currentDay", "dayIndex", "delta", "diff", "require_DayParser", "__commonJSMin", "exports", "_index", "_Parser", "DayParser", "dateString", "token", "match", "_date", "value", "date", "_flags", "options", "require_LocalDayParser", "__commonJSMin", "exports", "_index", "_Parser", "_utils", "LocalDayParser", "dateString", "token", "match", "options", "valueCallback", "value", "wholeWeekDays", "_date", "date", "_flags", "require_StandAloneLocalDayParser", "__commonJSMin", "exports", "_index", "_Parser", "_utils", "StandAloneLocalDayParser", "dateString", "token", "match", "options", "valueCallback", "value", "wholeWeekDays", "_date", "date", "_flags", "require_setISODay", "__commonJSMin", "exports", "setISODay", "_index", "_index2", "_index3", "date", "day", "options", "date_", "currentDay", "diff", "require_ISODayParser", "__commonJSMin", "exports", "_index", "_Parser", "_utils", "ISODayParser", "dateString", "token", "match", "valueCallback", "value", "_date", "date", "_flags", "require_AMPMParser", "__commonJSMin", "exports", "_Parser", "_utils", "AMPMParser", "dateString", "token", "match", "date", "_flags", "value", "require_AMPMMidnightParser", "__commonJSMin", "exports", "_Parser", "_utils", "AMPMMidnightParser", "dateString", "token", "match", "date", "_flags", "value", "require_DayPeriodParser", "__commonJSMin", "exports", "_Parser", "_utils", "DayPeriodParser", "dateString", "token", "match", "date", "_flags", "value", "require_Hour1to12Parser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "Hour1to12Parser", "dateString", "token", "match", "_date", "value", "date", "_flags", "isPM", "require_Hour0to23Parser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "Hour0to23Parser", "dateString", "token", "match", "_date", "value", "date", "_flags", "require_Hour0To11Parser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "Hour0To11Parser", "dateString", "token", "match", "_date", "value", "date", "_flags", "require_Hour1To24Parser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "Hour1To24Parser", "dateString", "token", "match", "_date", "value", "date", "_flags", "hours", "require_MinuteParser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "MinuteParser", "dateString", "token", "match", "_date", "value", "date", "_flags", "require_SecondParser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "SecondParser", "dateString", "token", "match", "_date", "value", "date", "_flags", "require_FractionOfSecondParser", "__commonJSMin", "exports", "_Parser", "_utils", "FractionOfSecondParser", "dateString", "token", "valueCallback", "value", "date", "_flags", "require_ISOTimezoneWithZParser", "__commonJSMin", "exports", "_index", "_index2", "_constants", "_Parser", "_utils", "ISOTimezoneWithZParser", "dateString", "token", "date", "flags", "value", "require_ISOTimezoneParser", "__commonJSMin", "exports", "_index", "_index2", "_constants", "_Parser", "_utils", "ISOTimezoneParser", "dateString", "token", "date", "flags", "value", "require_TimestampSecondsParser", "__commonJSMin", "exports", "_index", "_Parser", "_utils", "TimestampSecondsParser", "dateString", "date", "_flags", "value", "require_TimestampMillisecondsParser", "__commonJSMin", "exports", "_index", "_Parser", "_utils", "TimestampMillisecondsParser", "dateString", "date", "_flags", "value", "require_parsers", "__commonJSMin", "exports", "_EraParser", "_YearParser", "_LocalWeekYearParser", "_ISOWeekYearParser", "_ExtendedYearParser", "_QuarterParser", "_StandAloneQuarterParser", "_MonthParser", "_StandAloneMonthParser", "_LocalWeekParser", "_ISOWeekParser", "_DateParser", "_DayOfYearParser", "_DayParser", "_LocalDayParser", "_StandAloneLocalDayParser", "_ISODayParser", "_AMPMParser", "_AMPMMidnightParser", "_DayPeriodParser", "_Hour1to12Parser", "_Hour0to23Parser", "_Hour0To11Parser", "_Hour1To24Parser", "_MinuteParser", "_SecondParser", "_FractionOfSecondParser", "_ISOTimezoneWithZParser", "_ISOTimezoneParser", "_TimestampSecondsParser", "_TimestampMillisecondsParser", "parsers", "require_parse", "__commonJSMin", "exports", "_index2", "parse", "_index7", "_index", "_index3", "_index4", "_index5", "_index6", "_Setter", "formattingTokensRegExp", "longFormattingTokensRegExp", "escapedStringRegExp", "doubleQuoteRegExp", "notWhitespaceRegExp", "unescapedLatinCharacterRegExp", "dateStr", "formatStr", "referenceDate", "options", "invalidDate", "defaultOptions", "locale", "firstWeekContainsDate", "weekStartsOn", "subFnOptions", "setters", "tokens", "substring", "firstCharacter", "longFormatter", "usedTokens", "token", "parser", "incompatibleTokens", "incompatibleToken", "usedToken", "parseResult", "cleanEscapedString", "uniquePrioritySetters", "setter", "a", "b", "priority", "index", "array", "setterArray", "date", "flags", "result", "input", "require_isMatch", "__commonJSMin", "exports", "isMatch", "_index", "_index2", "dateStr", "formatStr", "options", "require_isMonday", "__commonJSMin", "exports", "isMonday", "_index", "date", "options", "require_isPast", "__commonJSMin", "exports", "isPast", "_index", "date", "require_startOfHour", "__commonJSMin", "exports", "startOfHour", "_index", "date", "options", "_date", "require_isSameHour", "__commonJSMin", "exports", "isSameHour", "_index", "_index2", "dateLeft", "dateRight", "options", "dateLeft_", "dateRight_", "require_isSameWeek", "__commonJSMin", "exports", "isSameWeek", "_index", "_index2", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "require_isSameISOWeek", "__commonJSMin", "exports", "isSameISOWeek", "_index", "laterDate", "earlierDate", "options", "require_isSameISOWeekYear", "__commonJSMin", "exports", "isSameISOWeekYear", "_index", "_index2", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "require_startOfMinute", "__commonJSMin", "exports", "startOfMinute", "_index", "date", "options", "date_", "require_isSameMinute", "__commonJSMin", "exports", "isSameMinute", "_index", "laterDate", "earlierDate", "require_isSameMonth", "__commonJSMin", "exports", "isSameMonth", "_index", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "require_isSameQuarter", "__commonJSMin", "exports", "isSameQuarter", "_index", "_index2", "laterDate", "earlierDate", "options", "dateLeft_", "dateRight_", "require_startOfSecond", "__commonJSMin", "exports", "startOfSecond", "_index", "date", "options", "date_", "require_isSameSecond", "__commonJSMin", "exports", "isSameSecond", "_index", "laterDate", "earlierDate", "require_isSameYear", "__commonJSMin", "exports", "isSameYear", "_index", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "require_isThisHour", "__commonJSMin", "exports", "isThisHour", "_index", "_index2", "_index3", "date", "options", "require_isThisISOWeek", "__commonJSMin", "exports", "isThisISOWeek", "_index", "_index2", "_index3", "date", "options", "require_isThisMinute", "__commonJSMin", "exports", "isThisMinute", "_index", "_index2", "date", "require_isThisMonth", "__commonJSMin", "exports", "isThisMonth", "_index", "_index2", "_index3", "date", "options", "require_isThisQuarter", "__commonJSMin", "exports", "isThisQuarter", "_index", "_index2", "_index3", "date", "options", "require_isThisSecond", "__commonJSMin", "exports", "isThisSecond", "_index", "_index2", "date", "require_isThisWeek", "__commonJSMin", "exports", "isThisWeek", "_index", "_index2", "_index3", "date", "options", "require_isThisYear", "__commonJSMin", "exports", "isThisYear", "_index", "_index2", "_index3", "date", "options", "require_isThursday", "__commonJSMin", "exports", "isThursday", "_index", "date", "options", "require_isToday", "__commonJSMin", "exports", "isToday", "_index", "_index2", "_index3", "date", "options", "require_isTomorrow", "__commonJSMin", "exports", "isTomorrow", "_index", "_index2", "_index3", "date", "options", "require_isTuesday", "__commonJSMin", "exports", "isTuesday", "_index", "date", "options", "require_isWednesday", "__commonJSMin", "exports", "isWednesday", "_index", "date", "options", "require_isWithinInterval", "__commonJSMin", "exports", "isWithinInterval", "_index", "date", "interval", "options", "time", "startTime", "endTime", "a", "b", "require_subDays", "__commonJSMin", "exports", "subDays", "_index", "date", "amount", "options", "require_isYesterday", "__commonJSMin", "exports", "isYesterday", "_index", "_index2", "_index3", "_index4", "date", "options", "require_lastDayOfDecade", "__commonJSMin", "exports", "lastDayOfDecade", "_index", "date", "options", "_date", "year", "decade", "require_lastDayOfWeek", "__commonJSMin", "exports", "lastDayOfWeek", "_index", "_index2", "date", "options", "defaultOptions", "weekStartsOn", "_date", "day", "diff", "require_lastDayOfISOWeek", "__commonJSMin", "exports", "lastDayOfISOWeek", "_index", "date", "options", "require_lastDayOfISOWeekYear", "__commonJSMin", "exports", "lastDayOfISOWeekYear", "_index", "_index2", "_index3", "date", "options", "year", "fourthOfJanuary", "date_", "require_lastDayOfQuarter", "__commonJSMin", "exports", "lastDayOfQuarter", "_index", "date", "options", "date_", "currentMonth", "month", "require_lastDayOfYear", "__commonJSMin", "exports", "lastDayOfYear", "_index", "date", "options", "date_", "year", "require_lightFormat", "__commonJSMin", "exports", "lightFormat", "_index", "_index2", "_index3", "formattingTokensRegExp", "escapedStringRegExp", "doubleQuoteRegExp", "unescapedLatinCharacterRegExp", "date", "formatStr", "date_", "tokens", "substring", "firstCharacter", "cleanEscapedString", "formatter", "input", "matches", "require_milliseconds", "__commonJSMin", "exports", "milliseconds", "_index", "years", "months", "weeks", "days", "hours", "minutes", "seconds", "totalDays", "totalSeconds", "require_millisecondsToHours", "__commonJSMin", "exports", "millisecondsToHours", "_index", "milliseconds", "hours", "require_millisecondsToMinutes", "__commonJSMin", "exports", "millisecondsToMinutes", "_index", "milliseconds", "minutes", "require_millisecondsToSeconds", "__commonJSMin", "exports", "millisecondsToSeconds", "_index", "milliseconds", "seconds", "require_minutesToHours", "__commonJSMin", "exports", "minutesToHours", "_index", "minutes", "hours", "require_minutesToMilliseconds", "__commonJSMin", "exports", "minutesToMilliseconds", "_index", "minutes", "require_minutesToSeconds", "__commonJSMin", "exports", "minutesToSeconds", "_index", "minutes", "require_monthsToQuarters", "__commonJSMin", "exports", "monthsToQuarters", "_index", "months", "quarters", "require_monthsToYears", "__commonJSMin", "exports", "monthsToYears", "_index", "months", "years", "require_nextDay", "__commonJSMin", "exports", "nextDay", "_index", "_index2", "date", "day", "options", "delta", "require_nextFriday", "__commonJSMin", "exports", "nextFriday", "_index", "date", "options", "require_nextMonday", "__commonJSMin", "exports", "nextMonday", "_index", "date", "options", "require_nextSaturday", "__commonJSMin", "exports", "nextSaturday", "_index", "date", "options", "require_nextSunday", "__commonJSMin", "exports", "nextSunday", "_index", "date", "options", "require_nextThursday", "__commonJSMin", "exports", "nextThursday", "_index", "date", "options", "require_nextTuesday", "__commonJSMin", "exports", "nextTuesday", "_index", "date", "options", "require_nextWednesday", "__commonJSMin", "exports", "nextWednesday", "_index", "date", "options", "require_parseISO", "__commonJSMin", "exports", "parseISO", "_index", "_index2", "_index3", "argument", "options", "invalidDate", "additionalDigits", "dateStrings", "splitDateString", "date", "parseYearResult", "parseYear", "parseDate", "timestamp", "time", "offset", "parseTime", "parseTimezone", "tmpDate", "result", "patterns", "dateRegex", "timeRegex", "timezoneRegex", "dateString", "array", "timeString", "token", "regex", "captures", "year", "century", "isWeekDate", "dayOfYear", "parseDateUnit", "month", "day", "week", "dayOfWeek", "validateWeekDate", "dayOfISOWeekYear", "validateDate", "validateDayOfYearDate", "value", "hours", "parseTimeUnit", "minutes", "seconds", "validateTime", "timezoneString", "sign", "validateTimezone", "isoWeekYear", "fourthOfJanuaryDay", "diff", "daysInMonths", "isLeapYearIndex", "_year", "_hours", "require_parseJSON", "__commonJSMin", "exports", "parseJSON", "_index", "dateStr", "options", "parts", "require_previousDay", "__commonJSMin", "exports", "previousDay", "_index", "_index2", "date", "day", "options", "delta", "require_previousFriday", "__commonJSMin", "exports", "previousFriday", "_index", "date", "options", "require_previousMonday", "__commonJSMin", "exports", "previousMonday", "_index", "date", "options", "require_previousSaturday", "__commonJSMin", "exports", "previousSaturday", "_index", "date", "options", "require_previousSunday", "__commonJSMin", "exports", "previousSunday", "_index", "date", "options", "require_previousThursday", "__commonJSMin", "exports", "previousThursday", "_index", "date", "options", "require_previousTuesday", "__commonJSMin", "exports", "previousTuesday", "_index", "date", "options", "require_previousWednesday", "__commonJSMin", "exports", "previousWednesday", "_index", "date", "options", "require_quartersToMonths", "__commonJSMin", "exports", "quartersToMonths", "_index", "quarters", "require_quartersToYears", "__commonJSMin", "exports", "quartersToYears", "_index", "quarters", "years", "require_roundToNearestHours", "__commonJSMin", "exports", "roundToNearestHours", "_index", "_index2", "_index3", "date", "options", "nearestTo", "date_", "fractionalMinutes", "fractionalSeconds", "fractionalMilliseconds", "hours", "method", "roundedHours", "require_roundToNearestMinutes", "__commonJSMin", "exports", "roundToNearestMinutes", "_index", "_index2", "_index3", "date", "options", "nearestTo", "date_", "fractionalSeconds", "fractionalMilliseconds", "minutes", "method", "roundedMinutes", "require_secondsToHours", "__commonJSMin", "exports", "secondsToHours", "_index", "seconds", "hours", "require_secondsToMilliseconds", "__commonJSMin", "exports", "secondsToMilliseconds", "_index", "seconds", "require_secondsToMinutes", "__commonJSMin", "exports", "secondsToMinutes", "_index", "seconds", "minutes", "require_setMonth", "__commonJSMin", "exports", "setMonth", "_index", "_index2", "_index3", "date", "month", "options", "_date", "year", "day", "midMonth", "daysInMonth", "require_set", "__commonJSMin", "exports", "set", "_index", "_index2", "_index3", "date", "values", "options", "_date", "require_setDate", "__commonJSMin", "exports", "setDate", "_index", "date", "dayOfMonth", "options", "_date", "require_setDayOfYear", "__commonJSMin", "exports", "setDayOfYear", "_index", "date", "dayOfYear", "options", "date_", "require_setDefaultOptions", "__commonJSMin", "exports", "setDefaultOptions", "_index", "options", "result", "defaultOptions", "property", "require_setHours", "__commonJSMin", "exports", "setHours", "_index", "date", "hours", "options", "_date", "require_setMilliseconds", "__commonJSMin", "exports", "setMilliseconds", "_index", "date", "milliseconds", "options", "_date", "require_setMinutes", "__commonJSMin", "exports", "setMinutes", "_index", "date", "minutes", "options", "date_", "require_setQuarter", "__commonJSMin", "exports", "setQuarter", "_index", "_index2", "date", "quarter", "options", "date_", "oldQuarter", "diff", "require_setSeconds", "__commonJSMin", "exports", "setSeconds", "_index", "date", "seconds", "options", "_date", "require_setWeekYear", "__commonJSMin", "exports", "setWeekYear", "_index", "_index2", "_index3", "_index4", "_index5", "date", "weekYear", "options", "defaultOptions", "firstWeekContainsDate", "diff", "firstWeek", "date_", "require_setYear", "__commonJSMin", "exports", "setYear", "_index", "_index2", "date", "year", "options", "date_", "require_startOfDecade", "__commonJSMin", "exports", "startOfDecade", "_index", "date", "options", "_date", "year", "decade", "require_startOfToday", "__commonJSMin", "exports", "startOfToday", "_index", "options", "require_startOfTomorrow", "__commonJSMin", "exports", "startOfTomorrow", "_index", "_index2", "options", "now", "year", "month", "day", "date", "require_startOfYesterday", "__commonJSMin", "exports", "startOfYesterday", "_index", "options", "now", "year", "month", "day", "date", "require_subMonths", "__commonJSMin", "exports", "subMonths", "_index", "date", "amount", "options", "require_sub", "__commonJSMin", "exports", "sub", "_index", "_index2", "_index3", "date", "duration", "options", "years", "months", "weeks", "days", "hours", "minutes", "seconds", "withoutMonths", "withoutDays", "minutesToSub", "msToSub", "require_subBusinessDays", "__commonJSMin", "exports", "subBusinessDays", "_index", "date", "amount", "options", "require_subHours", "__commonJSMin", "exports", "subHours", "_index", "date", "amount", "options", "require_subMilliseconds", "__commonJSMin", "exports", "subMilliseconds", "_index", "date", "amount", "options", "require_subMinutes", "__commonJSMin", "exports", "subMinutes", "_index", "date", "amount", "options", "require_subQuarters", "__commonJSMin", "exports", "subQuarters", "_index", "date", "amount", "options", "require_subSeconds", "__commonJSMin", "exports", "subSeconds", "_index", "date", "amount", "options", "require_subWeeks", "__commonJSMin", "exports", "subWeeks", "_index", "date", "amount", "options", "require_subYears", "__commonJSMin", "exports", "subYears", "_index", "date", "amount", "options", "require_weeksToDays", "__commonJSMin", "exports", "weeksToDays", "_index", "weeks", "require_yearsToDays", "__commonJSMin", "exports", "yearsToDays", "_index", "years", "require_yearsToMonths", "__commonJSMin", "exports", "yearsToMonths", "_index", "years", "require_yearsToQuarters", "__commonJSMin", "exports", "yearsToQuarters", "_index", "years", "require_date_fns", "__commonJSMin", "exports", "_index", "key", "_index2", "_index3", "_index4", "_index5", "_index6", "_index7", "_index8", "_index9", "_index10", "_index11", "_index12", "_index13", "_index14", "_index15", "_index16", "_index17", "_index18", "_index19", "_index20", "_index21", "_index22", "_index23", "_index24", "_index25", "_index26", "_index27", "_index28", "_index29", "_index30", "_index31", "_index32", "_index33", "_index34", "_index35", "_index36", "_index37", "_index38", "_index39", "_index40", "_index41", "_index42", "_index43", "_index44", "_index45", "_index46", "_index47", "_index48", "_index49", "_index50", "_index51", "_index52", "_index53", "_index54", "_index55", "_index56", "_index57", "_index58", "_index59", "_index60", "_index61", "_index62", "_index63", "_index64", "_index65", "_index66", "_index67", "_index68", "_index69", "_index70", "_index71", "_index72", "_index73", "_index74", "_index75", "_index76", "_index77", "_index78", "_index79", "_index80", "_index81", "_index82", "_index83", "_index84", "_index85", "_index86", "_index87", "_index88", "_index89", "_index90", "_index91", "_index92", "_index93", "_index94", "_index95", "_index96", "_index97", "_index98", "_index99", "_index100", "_index101", "_index102", "_index103", "_index104", "_index105", "_index106", "_index107", "_index108", "_index109", "_index110", "_index111", "_index112", "_index113", "_index114", "_index115", "_index116", "_index117", "_index118", "_index119", "_index120", "_index121", "_index122", "_index123", "_index124", "_index125", "_index126", "_index127", "_index128", "_index129", "_index130", "_index131", "_index132", "_index133", "_index134", "_index135", "_index136", "_index137", "_index138", "_index139", "_index140", "_index141", "_index142", "_index143", "_index144", "_index145", "_index146", "_index147", "_index148", "_index149", "_index150", "_index151", "_index152", "_index153", "_index154", "_index155", "_index156", "_index157", "_index158", "_index159", "_index160", "_index161", "_index162", "_index163", "_index164", "_index165", "_index166", "_index167", "_index168", "_index169", "_index170", "_index171", "_index172", "_index173", "_index174", "_index175", "_index176", "_index177", "_index178", "_index179", "_index180", "_index181", "_index182", "_index183", "_index184", "_index185", "_index186", "_index187", "_index188", "_index189", "_index190", "_index191", "_index192", "_index193", "_index194", "_index195", "_index196", "_index197", "_index198", "_index199", "_index200", "_index201", "_index202", "_index203", "_index204", "_index205", "_index206", "_index207", "_index208", "_index209", "_index210", "_index211", "_index212", "_index213", "_index214", "_index215", "_index216", "_index217", "_index218", "_index219", "_index220", "_index221", "_index222", "_index223", "_index224", "_index225", "_index226", "_index227", "_index228", "_index229", "_index230", "_index231", "_index232", "_index233", "_index234", "_index235", "_index236", "_index237", "_index238", "_index239", "_index240", "_index241", "_index242", "_index243", "_index244", "_index245", "require_utils", "__commonJSMin", "exports", "module", "readdir", "stat", "unlink", "symlink", "lstat", "readlink", "dirname", "join", "format", "addDays", "addHours", "parse", "isValid", "parseSize", "size", "multiplier", "match", "unit", "parseFrequency", "frequency", "today", "start", "getNextDay", "getNextHour", "getNextCustom", "validateLimitOptions", "limit", "time", "getNext", "getFileName", "fileVal", "buildFileName", "date", "lastNumber", "extension", "dateStr", "extensionStr", "identifyLogFile", "checkedFileName", "dateFormat", "baseFileNameStr", "checkFileNameSegments", "expectedSegmentCount", "chkExtension", "chkFileNumber", "fileNumber", "fileTime", "d", "getFileSize", "filePath", "detectLastNumber", "fileName", "readFileTrailingNumbers", "a", "b", "folder", "numbers", "file", "isMatchingTime", "number", "extractTrailingNumber", "extractFileName", "birthtimeMs", "removeOldFiles", "count", "removeOtherLogFiles", "baseFile", "createdFileNames", "newFileName", "files", "pathSegments", "fileEntry", "f", "i", "j", "filesToRemove", "checkSymlink", "linkPath", "stats", "existingTarget", "createSymlink", "validateDateFormat", "formatStr", "parseDate", "frequencySpec", "parseStart", "SonicBoom", "buildFileName", "removeOldFiles", "createSymlink", "detectLastNumber", "parseSize", "parseFrequency", "getNext", "getFileSize", "validateLimitOptions", "parseDate", "validateDateFormat", "file", "size", "frequency", "extension", "limit", "symlink", "dateFormat", "opts", "frequencySpec", "date", "number", "fileName", "createdFileNames", "currentSize", "maxSize", "destination", "rollTimeout", "scheduleRoll", "writtenSize", "roll", "prevDate"] +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/pino-worker.cjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/pino-worker.cjs new file mode 100644 index 0000000000000000000000000000000000000000..0aa2f8e6e800489b4702d5024e3f72c6aa8e4010 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/pino-worker.cjs @@ -0,0 +1,104 @@ +"use strict";var v=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Oe=v((uu,Et)=>{"use strict";var Q=e=>e&&typeof e.message=="string",ve=e=>{if(!e)return;let t=e.cause;if(typeof t=="function"){let r=e.cause();return Q(r)?r:void 0}else return Q(t)?t:void 0},St=(e,t)=>{if(!Q(e))return"";let r=e.stack||"";if(t.has(e))return r+` +causes have become circular...`;let n=ve(e);return n?(t.add(e),r+` +caused by: `+St(n,t)):r},Gn=e=>St(e,new Set),_t=(e,t,r)=>{if(!Q(e))return"";let n=r?"":e.message||"";if(t.has(e))return n+": ...";let i=ve(e);if(i){t.add(e);let o=typeof e.cause=="function";return n+(o?"":": ")+_t(i,t,o)}else return n},Hn=e=>_t(e,new Set);Et.exports={isErrorLike:Q,getErrorCause:ve,stackWithCauses:Gn,messageWithCauses:Hn}});var xe=v((cu,Ot)=>{"use strict";var Xn=Symbol("circular-ref-tag"),ne=Symbol("pino-raw-err-ref"),vt=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[ne]},set:function(e){this[ne]=e}}});Object.defineProperty(vt,ne,{writable:!0,value:{}});Ot.exports={pinoErrProto:vt,pinoErrorSymbols:{seen:Xn,rawSymbol:ne}}});var $t=v((au,Lt)=>{"use strict";Lt.exports=$e;var{messageWithCauses:Yn,stackWithCauses:Qn,isErrorLike:xt}=Oe(),{pinoErrProto:Zn,pinoErrorSymbols:ei}=xe(),{seen:Le}=ei,{toString:ti}=Object.prototype;function $e(e){if(!xt(e))return e;e[Le]=void 0;let t=Object.create(Zn);t.type=ti.call(e.constructor)==="[object Function]"?e.constructor.name:e.name,t.message=Yn(e),t.stack=Qn(e),Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(r=>$e(r)));for(let r in e)if(t[r]===void 0){let n=e[r];xt(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,Le)&&(t[r]=$e(n)):t[r]=n}return delete e[Le],t.raw=e,t}});var At=v((hu,jt)=>{"use strict";jt.exports=se;var{isErrorLike:je}=Oe(),{pinoErrProto:ri,pinoErrorSymbols:ni}=xe(),{seen:ie}=ni,{toString:ii}=Object.prototype;function se(e){if(!je(e))return e;e[ie]=void 0;let t=Object.create(ri);t.type=ii.call(e.constructor)==="[object Function]"?e.constructor.name:e.name,t.message=e.message,t.stack=e.stack,Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(r=>se(r))),je(e.cause)&&!Object.prototype.hasOwnProperty.call(e.cause,ie)&&(t.cause=se(e.cause));for(let r in e)if(t[r]===void 0){let n=e[r];je(n)?Object.prototype.hasOwnProperty.call(n,ie)||(t[r]=se(n)):t[r]=n}return delete e[ie],t.raw=e,t}});var Bt=v((du,Rt)=>{"use strict";Rt.exports={mapHttpRequest:si,reqSerializer:kt};var Ae=Symbol("pino-raw-req-ref"),Tt=Object.create({},{id:{enumerable:!0,writable:!0,value:""},method:{enumerable:!0,writable:!0,value:""},url:{enumerable:!0,writable:!0,value:""},query:{enumerable:!0,writable:!0,value:""},params:{enumerable:!0,writable:!0,value:""},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:""},remotePort:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Ae]},set:function(e){this[Ae]=e}}});Object.defineProperty(Tt,Ae,{writable:!0,value:{}});function kt(e){let t=e.info||e.socket,r=Object.create(Tt);if(r.id=typeof e.id=="function"?e.id():e.id||(e.info?e.info.id:void 0),r.method=e.method,e.originalUrl)r.url=e.originalUrl;else{let n=e.path;r.url=typeof n=="string"?n:e.url?e.url.path||e.url:void 0}return e.query&&(r.query=e.query),e.params&&(r.params=e.params),r.headers=e.headers,r.remoteAddress=t&&t.remoteAddress,r.remotePort=t&&t.remotePort,r.raw=e.raw||e,r}function si(e){return{req:kt(e)}}});var Dt=v((yu,It)=>{"use strict";It.exports={mapHttpResponse:oi,resSerializer:Ct};var Te=Symbol("pino-raw-res-ref"),qt=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Te]},set:function(e){this[Te]=e}}});Object.defineProperty(qt,Te,{writable:!0,value:{}});function Ct(e){let t=Object.create(qt);return t.statusCode=e.headersSent?e.statusCode:null,t.headers=e.getHeaders?e.getHeaders():e._headers,t.raw=e,t}function oi(e){return{res:Ct(e)}}});var Re=v((mu,Nt)=>{"use strict";var ke=$t(),li=At(),oe=Bt(),le=Dt();Nt.exports={err:ke,errWithCause:li,mapHttpRequest:oe.mapHttpRequest,mapHttpResponse:le.mapHttpResponse,req:oe.reqSerializer,res:le.resSerializer,wrapErrorSerializer:function(t){return t===ke?t:function(n){return t(ke(n))}},wrapRequestSerializer:function(t){return t===oe.reqSerializer?t:function(n){return t(oe.reqSerializer(n))}},wrapResponseSerializer:function(t){return t===le.resSerializer?t:function(n){return t(le.resSerializer(n))}}}});var Be=v((gu,Pt)=>{"use strict";function fi(e,t){return t}Pt.exports=function(){let t=Error.prepareStackTrace;Error.prepareStackTrace=fi;let r=new Error().stack;if(Error.prepareStackTrace=t,!Array.isArray(r))return;let n=r.slice(2),i=[];for(let o of n)o&&i.push(o.getFileName());return i}});var Wt=v((pu,Mt)=>{"use strict";Mt.exports=ui;function ui(e={}){let{ERR_PATHS_MUST_BE_STRINGS:t=()=>"fast-redact - Paths must be (non-empty) strings",ERR_INVALID_PATH:r=n=>`fast-redact \u2013 Invalid path (${n})`}=e;return function({paths:i}){i.forEach(o=>{if(typeof o!="string")throw Error(t());try{if(/〇/.test(o))throw Error();let a=(o[0]==="["?"":".")+o.replace(/^\*/,"\u3007").replace(/\.\*/g,".\u3007").replace(/\[\*\]/g,"[\u3007]");if(/\n|\r|;/.test(a)||/\/\*/.test(a))throw Error();Function(` + 'use strict' + const o = new Proxy({}, { get: () => o, set: () => { throw Error() } }); + const \u3007 = null; + o${a} + if ([o${a}].length !== 1) throw Error()`)()}catch{throw Error(r(o))}})}}});var fe=v((bu,zt)=>{"use strict";zt.exports=/[^.[\]]+|\[((?:.)*?)\]/g});var Kt=v((wu,Ft)=>{"use strict";var ci=fe();Ft.exports=ai;function ai({paths:e}){let t=[];var r=0;let n=e.reduce(function(i,o,a){var f=o.match(ci).map(u=>u.replace(/'|"|`/g,""));let c=o[0]==="[";f=f.map(u=>u[0]==="["?u.substr(1,u.length-2):u);let h=f.indexOf("*");if(h>-1){let u=f.slice(0,h),l=u.join("."),p=f.slice(h+1,f.length),d=p.length>0;r++,t.push({before:u,beforeStr:l,after:p,nested:d})}else i[o]={path:f,val:void 0,precensored:!1,circle:"",escPath:JSON.stringify(o),leadingBracket:c};return i},{});return{wildcards:t,wcLen:r,secret:n}}});var Ut=v((Su,Vt)=>{"use strict";var hi=fe();Vt.exports=di;function di({secret:e,serialize:t,wcLen:r,strict:n,isCensorFct:i,censorFctTakesPath:o},a){let f=Function("o",` + if (typeof o !== 'object' || o == null) { + ${pi(n,t)} + } + const { censor, secret } = this + const originalSecret = {} + const secretKeys = Object.keys(secret) + for (var i = 0; i < secretKeys.length; i++) { + originalSecret[secretKeys[i]] = secret[secretKeys[i]] + } + + ${yi(e,i,o)} + this.compileRestore() + ${mi(r>0,i,o)} + this.secret = originalSecret + ${gi(t)} + `).bind(a);return f.state=a,t===!1&&(f.restore=c=>a.restore(c)),f}function yi(e,t,r){return Object.keys(e).map(n=>{let{escPath:i,leadingBracket:o,path:a}=e[n],f=o?1:0,c=o?"":".",h=[];for(var u;(u=hi.exec(n))!==null;){let[,s]=u,{index:g,input:m}=u;g>f&&h.push(m.substring(0,g-(s?0:1)))}var l=h.map(s=>`o${c}${s}`).join(" && ");l.length===0?l+=`o${c}${n} != null`:l+=` && o${c}${n} != null`;let p=` + switch (true) { + ${h.reverse().map(s=>` + case o${c}${s} === censor: + secret[${i}].circle = ${JSON.stringify(s)} + break + `).join(` +`)} + } + `,d=r?`val, ${JSON.stringify(a)}`:"val";return` + if (${l}) { + const val = o${c}${n} + if (val === censor) { + secret[${i}].precensored = true + } else { + secret[${i}].val = val + o${c}${n} = ${t?`censor(${d})`:"censor"} + ${p} + } + } + `}).join(` +`)}function mi(e,t,r){return e===!0?` + { + const { wildcards, wcLen, groupRedact, nestedRedact } = this + for (var i = 0; i < wcLen; i++) { + const { before, beforeStr, after, nested } = wildcards[i] + if (nested === true) { + secret[beforeStr] = secret[beforeStr] || [] + nestedRedact(secret[beforeStr], o, before, after, censor, ${t}, ${r}) + } else secret[beforeStr] = groupRedact(o, before, censor, ${t}, ${r}) + } + } + `:""}function gi(e){return e===!1?"return o":` + var s = this.serialize(o) + this.restore(o) + return s + `}function pi(e,t){return e===!0?"throw Error('fast-redact: primitives cannot be redacted')":t===!1?"return o":"return this.serialize(o)"}});var Ce=v((_u,Ht)=>{"use strict";Ht.exports={groupRedact:wi,groupRestore:bi,nestedRedact:_i,nestedRestore:Si};function bi({keys:e,values:t,target:r}){if(r==null||typeof r=="string")return;let n=e.length;for(var i=0;i0;a--)o=o[n[a]];o[n[0]]=i}}function _i(e,t,r,n,i,o,a){let f=Jt(t,r);if(f==null)return;let c=Object.keys(f),h=c.length;for(var u=0;u{"use strict";var{groupRestore:Oi,nestedRestore:xi}=Ce();Xt.exports=Li;function Li(){return function(){if(this.restore){this.restore.state.secret=this.secret;return}let{secret:t,wcLen:r}=this,n=Object.keys(t),i=$i(t,n),o=r>0,a=o?{secret:t,groupRestore:Oi,nestedRestore:xi}:{secret:t};this.restore=Function("o",ji(i,n,o)).bind(a),this.restore.state=a}}function $i(e,t){return t.map(r=>{let{circle:n,escPath:i,leadingBracket:o}=e[r],f=n?`o.${n} = secret[${i}].val`:`o${o?"":"."}${r} = secret[${i}].val`,c=`secret[${i}].val = undefined`;return` + if (secret[${i}].val !== undefined) { + try { ${f} } catch (e) {} + ${c} + } + `}).join("")}function ji(e,t,r){return` + const secret = this.secret + ${r===!0?` + const keys = Object.keys(secret) + const len = keys.length + for (var i = len - 1; i >= ${t.length}; i--) { + const k = keys[i] + const o = secret[k] + if (o) { + if (o.flat === true) this.groupRestore(o) + else this.nestedRestore(o) + secret[k] = null + } + } + `:""} + ${e} + return o + `}});var Zt=v((vu,Qt)=>{"use strict";Qt.exports=Ai;function Ai(e){let{secret:t,censor:r,compileRestore:n,serialize:i,groupRedact:o,nestedRedact:a,wildcards:f,wcLen:c}=e,h=[{secret:t,censor:r,compileRestore:n}];return i!==!1&&h.push({serialize:i}),c>0&&h.push({groupRedact:o,nestedRedact:a,wildcards:f,wcLen:c}),Object.assign(...h)}});var rr=v((Ou,tr)=>{"use strict";var er=Wt(),Ti=Kt(),ki=Ut(),Ri=Yt(),{groupRedact:Bi,nestedRedact:qi}=Ce(),Ci=Zt(),Ii=fe(),Di=er(),Ie=e=>e;Ie.restore=Ie;var Ni="[REDACTED]";De.rx=Ii;De.validator=er;tr.exports=De;function De(e={}){let t=Array.from(new Set(e.paths||[])),r="serialize"in e&&(e.serialize===!1||typeof e.serialize=="function")?e.serialize:JSON.stringify,n=e.remove;if(n===!0&&r!==JSON.stringify)throw Error("fast-redact \u2013 remove option may only be set when serializer is JSON.stringify");let i=n===!0?void 0:"censor"in e?e.censor:Ni,o=typeof i=="function",a=o&&i.length>1;if(t.length===0)return r||Ie;Di({paths:t,serialize:r,censor:i});let{wildcards:f,wcLen:c,secret:h}=Ti({paths:t,censor:i}),u=Ri(),l="strict"in e?e.strict:!0;return ki({secret:h,wcLen:c,serialize:r,strict:l,isCensorFct:o,censorFctTakesPath:a},Ci({secret:h,censor:i,compileRestore:u,serialize:r,groupRedact:Bi,nestedRedact:qi,wildcards:f,wcLen:c}))}});var H=v((xu,nr)=>{"use strict";var Pi=Symbol("pino.setLevel"),Mi=Symbol("pino.getLevel"),Wi=Symbol("pino.levelVal"),zi=Symbol("pino.levelComp"),Fi=Symbol("pino.useLevelLabels"),Ki=Symbol("pino.useOnlyCustomLevels"),Vi=Symbol("pino.mixin"),Ui=Symbol("pino.lsCache"),Ji=Symbol("pino.chindings"),Gi=Symbol("pino.asJson"),Hi=Symbol("pino.write"),Xi=Symbol("pino.redactFmt"),Yi=Symbol("pino.time"),Qi=Symbol("pino.timeSliceIndex"),Zi=Symbol("pino.stream"),es=Symbol("pino.stringify"),ts=Symbol("pino.stringifySafe"),rs=Symbol("pino.stringifiers"),ns=Symbol("pino.end"),is=Symbol("pino.formatOpts"),ss=Symbol("pino.messageKey"),os=Symbol("pino.errorKey"),ls=Symbol("pino.nestedKey"),fs=Symbol("pino.nestedKeyStr"),us=Symbol("pino.mixinMergeStrategy"),cs=Symbol("pino.msgPrefix"),as=Symbol("pino.wildcardFirst"),hs=Symbol.for("pino.serializers"),ds=Symbol.for("pino.formatters"),ys=Symbol.for("pino.hooks"),ms=Symbol.for("pino.metadata");nr.exports={setLevelSym:Pi,getLevelSym:Mi,levelValSym:Wi,levelCompSym:zi,useLevelLabelsSym:Fi,mixinSym:Vi,lsCacheSym:Ui,chindingsSym:Ji,asJsonSym:Gi,writeSym:Hi,serializersSym:hs,redactFmtSym:Xi,timeSym:Yi,timeSliceIndexSym:Qi,streamSym:Zi,stringifySym:es,stringifySafeSym:ts,stringifiersSym:rs,endSym:ns,formatOptsSym:is,messageKeySym:ss,errorKeySym:os,nestedKeySym:ls,wildcardFirstSym:as,needsMetadataGsym:ms,useOnlyCustomLevelsSym:Ki,formattersSym:ds,hooksSym:ys,nestedKeyStrSym:fs,mixinMergeStrategySym:us,msgPrefixSym:cs}});var Me=v((Lu,lr)=>{"use strict";var Pe=rr(),{redactFmtSym:gs,wildcardFirstSym:ue}=H(),{rx:Ne,validator:ps}=Pe,ir=ps({ERR_PATHS_MUST_BE_STRINGS:()=>"pino \u2013 redacted paths must be strings",ERR_INVALID_PATH:e=>`pino \u2013 redact paths array contains an invalid path (${e})`}),sr="[Redacted]",or=!1;function bs(e,t){let{paths:r,censor:n}=ws(e),i=r.reduce((f,c)=>{Ne.lastIndex=0;let h=Ne.exec(c),u=Ne.exec(c),l=h[1]!==void 0?h[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):h[0];if(l==="*"&&(l=ue),u===null)return f[l]=null,f;if(f[l]===null)return f;let{index:p}=u,d=`${c.substr(p,c.length-1)}`;return f[l]=f[l]||[],l!==ue&&f[l].length===0&&f[l].push(...f[ue]||[]),l===ue&&Object.keys(f).forEach(function(s){f[s]&&f[s].push(d)}),f[l].push(d),f},{}),o={[gs]:Pe({paths:r,censor:n,serialize:t,strict:or})},a=(...f)=>t(typeof n=="function"?n(...f):n);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((f,c)=>{if(i[c]===null)f[c]=h=>a(h,[c]);else{let h=typeof n=="function"?(u,l)=>n(u,[c,...l]):n;f[c]=Pe({paths:i[c],censor:h,serialize:t,strict:or})}return f},o)}function ws(e){if(Array.isArray(e))return e={paths:e,censor:sr},ir(e),e;let{paths:t,censor:r=sr,remove:n}=e;if(Array.isArray(t)===!1)throw Error("pino \u2013 redact must contain an array of strings");return n===!0&&(r=void 0),ir({paths:t,censor:r}),{paths:t,censor:r}}lr.exports=bs});var ur=v(($u,fr)=>{"use strict";var Ss=()=>"",_s=()=>`,"time":${Date.now()}`,Es=()=>`,"time":${Math.round(Date.now()/1e3)}`,vs=()=>`,"time":"${new Date(Date.now()).toISOString()}"`;fr.exports={nullTime:Ss,epochTime:_s,unixTime:Es,isoTime:vs}});var ar=v((ju,cr)=>{"use strict";function Os(e){try{return JSON.stringify(e)}catch{return'"[Circular]"'}}cr.exports=xs;function xs(e,t,r){var n=r&&r.stringify||Os,i=1;if(typeof e=="object"&&e!==null){var o=t.length+i;if(o===1)return e;var a=new Array(o);a[0]=n(e);for(var f=1;f-1?l:0,e.charCodeAt(d+1)){case 100:case 102:if(u>=c||t[u]==null)break;l=c||t[u]==null)break;l=c||t[u]===void 0)break;l",l=d+2,d++;break}h+=n(t[u]),l=d+2,d++;break;case 115:if(u>=c)break;l{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let t=function(r){if((r>0&&r<1/0)===!1)throw typeof r!="number"&&typeof r!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(e,0,0,Number(r))},e=new Int32Array(new SharedArrayBuffer(4));We.exports=t}else{let e=function(t){if((t>0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let n=Date.now()+Number(t);for(;n>Date.now(););};We.exports=e}});var wr=v((Tu,br)=>{"use strict";var A=require("fs"),Ls=require("events"),$s=require("util").inherits,hr=require("path"),Ke=ze(),js=require("assert"),ce=100,ae=Buffer.allocUnsafe(0),As=16*1024,dr="buffer",yr="utf8",[Ts,ks]=(process.versions.node||"0.0").split(".").map(Number),Rs=Ts>=22&&ks>=7;function mr(e,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function r(o,a){if(o){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount("error")>0&&t.emit("error",o)}):t.emit("error",o);return}let f=t._reopening;t.fd=a,t.file=e,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit("ready")):t.emit("ready"),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():f&&process.nextTick(()=>t.emit("drain")))}let n=t.append?"a":"w",i=t.mode;if(t.sync)try{t.mkdir&&A.mkdirSync(hr.dirname(e),{recursive:!0});let o=A.openSync(e,n,i);r(null,o)}catch(o){throw r(o),o}else t.mkdir?A.mkdir(hr.dirname(e),{recursive:!0},o=>{if(o)return r(o);A.open(e,n,i,r)}):A.open(e,n,i,r)}function I(e){if(!(this instanceof I))return new I(e);let{fd:t,dest:r,minLength:n,maxLength:i,maxWrite:o,periodicFlush:a,sync:f,append:c=!0,mkdir:h,retryEAGAIN:u,fsync:l,contentMode:p,mode:d}=e||{};t=t||r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(n||0,16387),this.file=null,this.destroyed=!1,this.minLength=n||0,this.maxLength=i||0,this.maxWrite=o||As,this._periodicFlush=a||0,this._periodicFlushTimer=void 0,this.sync=f||!1,this.writable=!0,this._fsync=l||!1,this.append=c||!1,this.mode=d,this.retryEAGAIN=u||(()=>!0),this.mkdir=h||!1;let s,g;if(p===dr)this._writingBuf=ae,this.write=Cs,this.flush=Ds,this.flushSync=Ps,this._actualWrite=Ws,s=()=>A.writeSync(this.fd,this._writingBuf),g=()=>A.write(this.fd,this._writingBuf,this.release);else if(p===void 0||p===yr)this._writingBuf="",this.write=qs,this.flush=Is,this.flushSync=Ns,this._actualWrite=Ms,s=()=>A.writeSync(this.fd,this._writingBuf,"utf8"),g=()=>A.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${yr}" and "${dr}", but passed ${p}`);if(typeof t=="number")this.fd=t,process.nextTick(()=>this.emit("ready"));else if(typeof t=="string")mr(t,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(m,S)=>{if(m){if((m.code==="EAGAIN"||m.code==="EBUSY")&&this.retryEAGAIN(m,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{Ke(ce),this.release(void 0,0)}catch(_){this.release(_)}else setTimeout(g,ce);else this._writing=!1,this.emit("error",m);return}this.emit("write",S);let b=Fe(this._writingBuf,this._len,S);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){g();return}try{do{let _=s(),O=Fe(this._writingBuf,this._len,_);this._len=O.len,this._writingBuf=O.writingBuf}while(this._writingBuf.length)}catch(_){this.release(_);return}}this._fsync&&A.fsyncSync(this.fd);let w=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):w>this.minLength?this._actualWrite():this._ending?w>0?this._actualWrite():(this._writing=!1,he(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(Bs,this)):this.emit("drain"))},this.on("newListener",function(m){m==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function Fe(e,t,r){return typeof e=="string"&&Buffer.byteLength(e)!==r&&(r=Buffer.from(e).subarray(0,r).toString().length),t=Math.max(t-r,0),e=e.slice(r),{writingBuf:e,len:t}}function Bs(e){e.listenerCount("drain")>0&&(e._asyncDrainScheduled=!1,e.emit("drain"))}$s(I,Ls);function gr(e,t){return e.length===0?ae:e.length===1?e[0]:Buffer.concat(e,t)}function qs(e){if(this.destroyed)throw new Error("SonicBoom destroyed");let t=this._len+e.length,r=this._bufs;return this.maxLength&&t>this.maxLength?(this.emit("drop",e),this._lenthis.maxWrite?r.push(""+e):r[r.length-1]+=e,this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._lenthis.maxLength?(this.emit("drop",e),this._lenthis.maxWrite?(r.push([e]),n.push(e.length)):(r[r.length-1].push(e),n[n.length-1]+=e.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len{if(this._fsync)this._flushPending=!1,e();else try{A.fsync(this.fd,n=>{this._flushPending=!1,e(n)})}catch(n){e(n)}this.off("error",r)},r=n=>{this._flushPending=!1,e(n),this.off("drain",t)};this.once("drain",t),this.once("error",r)}function Is(e){if(e!=null&&typeof e!="function")throw new Error("flush cb must be a function");if(this.destroyed){let t=new Error("SonicBoom destroyed");if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&pr.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function Ds(e){if(e!=null&&typeof e!="function")throw new Error("flush cb must be a function");if(this.destroyed){let t=new Error("SonicBoom destroyed");if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&pr.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}I.prototype.reopen=function(e){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(e&&(this.file=e),this._reopening=!0,this._writing)return;let t=this.fd;this.once("ready",()=>{t!==this.fd&&A.close(t,r=>{if(r)return this.emit("error",r)})}),mr(this.file,this)};I.prototype.end=function(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():he(this)))};function Ns(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let e="";for(;this._bufs.length||e;){e.length<=0&&(e=this._bufs[0]);try{let t=A.writeSync(this.fd,e,"utf8"),r=Fe(e,this._len,t);e=r.writingBuf,this._len=r.len,e.length<=0&&this._bufs.shift()}catch(t){if((t.code==="EAGAIN"||t.code==="EBUSY")&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;Ke(ce)}}try{A.fsyncSync(this.fd)}catch{}}function Ps(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=ae);let e=ae;for(;this._bufs.length||e.length;){e.length<=0&&(e=gr(this._bufs[0],this._lens[0]));try{let t=A.writeSync(this.fd,e);e=e.subarray(t),this._len=Math.max(this._len-t,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code==="EAGAIN"||t.code==="EBUSY")&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;Ke(ce)}}}I.prototype.destroy=function(){this.destroyed||he(this)};function Ms(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf||this._bufs.shift()||"",this.sync)try{let t=A.writeSync(this.fd,this._writingBuf,"utf8");e(null,t)}catch(t){e(t)}else A.write(this.fd,this._writingBuf,"utf8",e)}function Ws(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:gr(this._bufs.shift(),this._lens.shift()),this.sync)try{let t=A.writeSync(this.fd,this._writingBuf);e(null,t)}catch(t){e(t)}else Rs&&(this._writingBuf=Buffer.from(this._writingBuf)),A.write(this.fd,this._writingBuf,e)}function he(e){if(e.fd===-1){e.once("ready",he.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],js(typeof e.fd=="number",`sonic.fd must be a number, got ${typeof e.fd}`);try{A.fsync(e.fd,t)}catch{}function t(){e.fd!==1&&e.fd!==2?A.close(e.fd,r):r()}function r(n){if(n){e.emit("error",n);return}e._ending&&!e._writing&&e.emit("finish"),e.emit("close")}}I.SonicBoom=I;I.default=I;br.exports=I});var Ve=v((ku,Or)=>{"use strict";var D={exit:[],beforeExit:[]},Sr={exit:Ks,beforeExit:Vs},X;function zs(){X===void 0&&(X=new FinalizationRegistry(Us))}function Fs(e){D[e].length>0||process.on(e,Sr[e])}function _r(e){D[e].length>0||(process.removeListener(e,Sr[e]),D.exit.length===0&&D.beforeExit.length===0&&(X=void 0))}function Ks(){Er("exit")}function Vs(){Er("beforeExit")}function Er(e){for(let t of D[e]){let r=t.deref(),n=t.fn;r!==void 0&&n(r,e)}D[e]=[]}function Us(e){for(let t of["exit","beforeExit"]){let r=D[t].indexOf(e);D[t].splice(r,r+1),_r(t)}}function vr(e,t,r){if(t===void 0)throw new Error("the object can't be undefined");Fs(e);let n=new WeakRef(t);n.fn=r,zs(),X.register(t,n),D[e].push(n)}function Js(e,t){vr("exit",e,t)}function Gs(e,t){vr("beforeExit",e,t)}function Hs(e){if(X!==void 0){X.unregister(e);for(let t of["exit","beforeExit"])D[t]=D[t].filter(r=>{let n=r.deref();return n&&n!==e}),_r(t)}}Or.exports={register:Js,registerBeforeExit:Gs,unregister:Hs}});var xr=v((Ru,Xs)=>{Xs.exports={name:"thread-stream",version:"3.1.0",description:"A streaming way to send data to a Node.js Worker Thread",main:"index.js",types:"index.d.ts",dependencies:{"real-require":"^0.2.0"},devDependencies:{"@types/node":"^20.1.0","@types/tap":"^15.0.0","@yao-pkg/pkg":"^5.11.5",desm:"^1.3.0",fastbench:"^1.0.1",husky:"^9.0.6","pino-elasticsearch":"^8.0.0","sonic-boom":"^4.0.1",standard:"^17.0.0",tap:"^16.2.0","ts-node":"^10.8.0",typescript:"^5.3.2","why-is-node-running":"^2.2.2"},scripts:{build:"tsc --noEmit",test:'standard && npm run build && npm run transpile && tap "test/**/*.test.*js" && tap --ts test/*.test.*ts',"test:ci":"standard && npm run transpile && npm run test:ci:js && npm run test:ci:ts","test:ci:js":'tap --no-check-coverage --timeout=120 --coverage-report=lcovonly "test/**/*.test.*js"',"test:ci:ts":'tap --ts --no-check-coverage --coverage-report=lcovonly "test/**/*.test.*ts"',"test:yarn":'npm run transpile && tap "test/**/*.test.js" --no-check-coverage',transpile:"sh ./test/ts/transpile.sh",prepare:"husky install"},standard:{ignore:["test/ts/**/*","test/syntax-error.mjs"]},repository:{type:"git",url:"git+https://github.com/mcollina/thread-stream.git"},keywords:["worker","thread","threads","stream"],author:"Matteo Collina ",license:"MIT",bugs:{url:"https://github.com/mcollina/thread-stream/issues"},homepage:"https://github.com/mcollina/thread-stream#readme"}});var $r=v((Bu,Lr)=>{"use strict";function Ys(e,t,r,n,i){let o=Date.now()+n,a=Atomics.load(e,t);if(a===r){i(null,"ok");return}let f=a,c=h=>{Date.now()>o?i(null,"timed-out"):setTimeout(()=>{f=a,a=Atomics.load(e,t),a===f?c(h>=1e3?1e3:h*2):a===r?i(null,"ok"):i(null,"not-equal")},h)};c(1)}function Qs(e,t,r,n,i){let o=Date.now()+n,a=Atomics.load(e,t);if(a!==r){i(null,"ok");return}let f=c=>{Date.now()>o?i(null,"timed-out"):setTimeout(()=>{a=Atomics.load(e,t),a!==r?i(null,"ok"):f(c>=1e3?1e3:c*2)},c)};f(1)}Lr.exports={wait:Ys,waitDiff:Qs}});var Ar=v((qu,jr)=>{"use strict";jr.exports={WRITE_INDEX:4,READ_INDEX:8}});var qr=v((Cu,Br)=>{"use strict";var{version:Zs}=xr(),{EventEmitter:eo}=require("events"),{Worker:to}=require("worker_threads"),{join:ro}=require("path"),{pathToFileURL:no}=require("url"),{wait:io}=$r(),{WRITE_INDEX:R,READ_INDEX:N}=Ar(),so=require("buffer"),oo=require("assert"),y=Symbol("kImpl"),lo=so.constants.MAX_STRING_LENGTH,ee=class{constructor(t){this._value=t}deref(){return this._value}},ye=class{register(){}unregister(){}},fo=process.env.NODE_V8_COVERAGE?ye:global.FinalizationRegistry||ye,uo=process.env.NODE_V8_COVERAGE?ee:global.WeakRef||ee,Tr=new fo(e=>{e.exited||e.terminate()});function co(e,t){let{filename:r,workerData:n}=t,o=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||ro(__dirname,"lib","worker.js"),a=new to(o,{...t.workerOpts,trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:no(r).href,dataBuf:e[y].dataBuf,stateBuf:e[y].stateBuf,workerData:{$context:{threadStreamVersion:Zs},...n}}});return a.stream=new ee(e),a.on("message",ao),a.on("exit",Rr),Tr.register(e,a),a}function kr(e){oo(!e[y].sync),e[y].needDrain&&(e[y].needDrain=!1,e.emit("drain"))}function de(e){let t=Atomics.load(e[y].state,R),r=e[y].data.length-t;if(r>0){if(e[y].buf.length===0){e[y].flushing=!1,e[y].ending?Xe(e):e[y].needDrain&&process.nextTick(kr,e);return}let n=e[y].buf.slice(0,r),i=Buffer.byteLength(n);i<=r?(e[y].buf=e[y].buf.slice(r),me(e,n,de.bind(null,e))):e.flush(()=>{if(!e.destroyed){for(Atomics.store(e[y].state,N,0),Atomics.store(e[y].state,R,0);i>e[y].data.length;)r=r/2,n=e[y].buf.slice(0,r),i=Buffer.byteLength(n);e[y].buf=e[y].buf.slice(r),me(e,n,de.bind(null,e))}})}else if(r===0){if(t===0&&e[y].buf.length===0)return;e.flush(()=>{Atomics.store(e[y].state,N,0),Atomics.store(e[y].state,R,0),de(e)})}else P(e,new Error("overwritten"))}function ao(e){let t=this.stream.deref();if(t===void 0){this.exited=!0,this.terminate();return}switch(e.code){case"READY":this.stream=new uo(t),t.flush(()=>{t[y].ready=!0,t.emit("ready")});break;case"ERROR":P(t,e.err);break;case"EVENT":Array.isArray(e.args)?t.emit(e.name,...e.args):t.emit(e.name,e.args);break;case"WARNING":process.emitWarning(e.err);break;default:P(t,new Error("this should not happen: "+e.code))}}function Rr(e){let t=this.stream.deref();t!==void 0&&(Tr.unregister(t),t.worker.exited=!0,t.worker.off("exit",Rr),P(t,e!==0?new Error("the worker thread exited"):null))}var Je=class extends eo{constructor(t={}){if(super(),t.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[y]={},this[y].stateBuf=new SharedArrayBuffer(128),this[y].state=new Int32Array(this[y].stateBuf),this[y].dataBuf=new SharedArrayBuffer(t.bufferSize||4*1024*1024),this[y].data=Buffer.from(this[y].dataBuf),this[y].sync=t.sync||!1,this[y].ending=!1,this[y].ended=!1,this[y].needDrain=!1,this[y].destroyed=!1,this[y].flushing=!1,this[y].ready=!1,this[y].finished=!1,this[y].errored=null,this[y].closed=!1,this[y].buf="",this.worker=co(this,t),this.on("message",(r,n)=>{this.worker.postMessage(r,n)})}write(t){if(this[y].destroyed)return Ge(this,new Error("the worker has exited")),!1;if(this[y].ending)return Ge(this,new Error("the worker is ending")),!1;if(this[y].flushing&&this[y].buf.length+t.length>=lo)try{Ue(this),this[y].flushing=!0}catch(r){return P(this,r),!1}if(this[y].buf+=t,this[y].sync)try{return Ue(this),!0}catch(r){return P(this,r),!1}return this[y].flushing||(this[y].flushing=!0,setImmediate(de,this)),this[y].needDrain=this[y].data.length-this[y].buf.length-Atomics.load(this[y].state,R)<=0,!this[y].needDrain}end(){this[y].destroyed||(this[y].ending=!0,Xe(this))}flush(t){if(this[y].destroyed){typeof t=="function"&&process.nextTick(t,new Error("the worker has exited"));return}let r=Atomics.load(this[y].state,R);io(this[y].state,N,r,1/0,(n,i)=>{if(n){P(this,n),process.nextTick(t,n);return}if(i==="not-equal"){this.flush(t);return}process.nextTick(t)})}flushSync(){this[y].destroyed||(Ue(this),He(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[y].ready}get destroyed(){return this[y].destroyed}get closed(){return this[y].closed}get writable(){return!this[y].destroyed&&!this[y].ending}get writableEnded(){return this[y].ending}get writableFinished(){return this[y].finished}get writableNeedDrain(){return this[y].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[y].errored}};function Ge(e,t){setImmediate(()=>{e.emit("error",t)})}function P(e,t){e[y].destroyed||(e[y].destroyed=!0,t&&(e[y].errored=t,Ge(e,t)),e.worker.exited?setImmediate(()=>{e[y].closed=!0,e.emit("close")}):e.worker.terminate().catch(()=>{}).then(()=>{e[y].closed=!0,e.emit("close")}))}function me(e,t,r){let n=Atomics.load(e[y].state,R),i=Buffer.byteLength(t);return e[y].data.write(t,n),Atomics.store(e[y].state,R,n+i),Atomics.notify(e[y].state,R),r(),!0}function Xe(e){if(!(e[y].ended||!e[y].ending||e[y].flushing)){e[y].ended=!0;try{e.flushSync();let t=Atomics.load(e[y].state,N);Atomics.store(e[y].state,R,-1),Atomics.notify(e[y].state,R);let r=0;for(;t!==-1;){if(Atomics.wait(e[y].state,N,t,1e3),t=Atomics.load(e[y].state,N),t===-2){P(e,new Error("end() failed"));return}if(++r===10){P(e,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{e[y].finished=!0,e.emit("finish")})}catch(t){P(e,t)}}}function Ue(e){let t=()=>{e[y].ending?Xe(e):e[y].needDrain&&process.nextTick(kr,e)};for(e[y].flushing=!1;e[y].buf.length!==0;){let r=Atomics.load(e[y].state,R),n=e[y].data.length-r;if(n===0){He(e),Atomics.store(e[y].state,N,0),Atomics.store(e[y].state,R,0);continue}else if(n<0)throw new Error("overwritten");let i=e[y].buf.slice(0,n),o=Buffer.byteLength(i);if(o<=n)e[y].buf=e[y].buf.slice(n),me(e,i,t);else{for(He(e),Atomics.store(e[y].state,N,0),Atomics.store(e[y].state,R,0);o>e[y].buf.length;)n=n/2,i=e[y].buf.slice(0,n),o=Buffer.byteLength(i);e[y].buf=e[y].buf.slice(n),me(e,i,t)}}}function He(e){if(e[y].flushing)throw new Error("unable to flush while flushing");let t=Atomics.load(e[y].state,R),r=0;for(;;){let n=Atomics.load(e[y].state,N);if(n===-2)throw Error("_flushSync failed");if(n!==t)Atomics.wait(e[y].state,N,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}Br.exports=Je});var Ze=v((Iu,Cr)=>{"use strict";var{createRequire:ho}=require("module"),yo=Be(),{join:Ye,isAbsolute:mo,sep:go}=require("node:path"),po=ze(),Qe=Ve(),bo=qr();function wo(e){Qe.register(e,_o),Qe.registerBeforeExit(e,Eo),e.on("close",function(){Qe.unregister(e)})}function So(e,t,r,n){let i=new bo({filename:e,workerData:t,workerOpts:r,sync:n});i.on("ready",o),i.on("close",function(){process.removeListener("exit",a)}),process.on("exit",a);function o(){process.removeListener("exit",a),i.unref(),r.autoEnd!==!1&&wo(i)}function a(){i.closed||(i.flushSync(),po(100),i.end())}return i}function _o(e){e.ref(),e.flushSync(),e.end(),e.once("close",function(){e.unref()})}function Eo(e){e.flushSync()}function vo(e){let{pipeline:t,targets:r,levels:n,dedupe:i,worker:o={},caller:a=yo(),sync:f=!1}=e,c={...e.options},h=typeof a=="string"?[a]:a,u="__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{},l=e.target;if(l&&r)throw new Error("only one of target or targets can be specified");return r?(l=u["pino-worker"]||Ye(__dirname,"worker.js"),c.targets=r.filter(d=>d.target).map(d=>({...d,target:p(d.target)})),c.pipelines=r.filter(d=>d.pipeline).map(d=>d.pipeline.map(s=>({...s,level:d.level,target:p(s.target)})))):t&&(l=u["pino-worker"]||Ye(__dirname,"worker.js"),c.pipelines=[t.map(d=>({...d,target:p(d.target)}))]),n&&(c.levels=n),i&&(c.dedupe=i),c.pinoWillSendConfig=!0,So(p(l),c,o,f);function p(d){if(d=u[d]||d,mo(d)||d.indexOf("file://")===0)return d;if(d==="pino/file")return Ye(__dirname,"..","file.js");let s;for(let g of h)try{let m=g==="node:repl"?process.cwd()+go:g;s=ho(m).resolve(d);break}catch{continue}if(!s)throw new Error(`unable to determine transport target for "${d}"`);return s}}Cr.exports=vo});var be=v((Du,Ur)=>{"use strict";var Ir=ar(),{mapHttpRequest:Oo,mapHttpResponse:xo}=Re(),tt=wr(),Dr=Ve(),{lsCacheSym:Lo,chindingsSym:Mr,writeSym:Nr,serializersSym:Wr,formatOptsSym:Pr,endSym:$o,stringifiersSym:zr,stringifySym:Fr,stringifySafeSym:rt,wildcardFirstSym:Kr,nestedKeySym:jo,formattersSym:Vr,messageKeySym:Ao,errorKeySym:To,nestedKeyStrSym:ko,msgPrefixSym:ge}=H(),{isMainThread:Ro}=require("worker_threads"),Bo=Ze();function Y(){}function qo(e,t){if(!t)return r;return function(...i){t.call(this,i,r,e)};function r(n,...i){if(typeof n=="object"){let o=n;n!==null&&(n.method&&n.headers&&n.socket?n=Oo(n):typeof n.setHeader=="function"&&(n=xo(n)));let a;o===null&&i.length===0?a=[null]:(o=i.shift(),a=i),typeof this[ge]=="string"&&o!==void 0&&o!==null&&(o=this[ge]+o),this[Nr](n,Ir(o,a,this[Pr]),e)}else{let o=n===void 0?i.shift():n;typeof this[ge]=="string"&&o!==void 0&&o!==null&&(o=this[ge]+o),this[Nr](null,Ir(o,i,this[Pr]),e)}}}function et(e){let t="",r=0,n=!1,i=255,o=e.length;if(o>100)return JSON.stringify(e);for(var a=0;a=32;a++)i=e.charCodeAt(a),(i===34||i===92)&&(t+=e.slice(r,a)+"\\",r=a,n=!0);return n?t+=e.slice(r):t=e,i<32?JSON.stringify(e):'"'+t+'"'}function Co(e,t,r,n){let i=this[Fr],o=this[rt],a=this[zr],f=this[$o],c=this[Mr],h=this[Wr],u=this[Vr],l=this[Ao],p=this[To],d=this[Lo][r]+n;d=d+c;let s;u.log&&(e=u.log(e));let g=a[Kr],m="";for(let b in e)if(s=e[b],Object.prototype.hasOwnProperty.call(e,b)&&s!==void 0){h[b]?s=h[b](s):b===p&&h.err&&(s=h.err(s));let w=a[b]||g;switch(typeof s){case"undefined":case"function":continue;case"number":Number.isFinite(s)===!1&&(s=null);case"boolean":w&&(s=w(s));break;case"string":s=(w||et)(s);break;default:s=(w||i)(s,o)}if(s===void 0)continue;let _=et(b);m+=","+_+":"+s}let S="";if(t!==void 0){s=h[l]?h[l](t):t;let b=a[l]||g;switch(typeof s){case"function":break;case"number":Number.isFinite(s)===!1&&(s=null);case"boolean":b&&(s=b(s)),S=',"'+l+'":'+s;break;case"string":s=(b||et)(s),S=',"'+l+'":'+s;break;default:s=(b||i)(s,o),S=',"'+l+'":'+s}}return this[jo]&&m?d+this[ko]+m.slice(1)+"}"+S+f:d+m+S+f}function Io(e,t){let r,n=e[Mr],i=e[Fr],o=e[rt],a=e[zr],f=a[Kr],c=e[Wr],h=e[Vr].bindings;t=h(t);for(let u in t)if(r=t[u],(u!=="level"&&u!=="serializers"&&u!=="formatters"&&u!=="customLevels"&&t.hasOwnProperty(u)&&r!==void 0)===!0){if(r=c[u]?c[u](r):r,r=(a[u]||f||i)(r,o),r===void 0)continue;n+=',"'+u+'":'+r}return n}function Do(e){return e.write!==e.constructor.prototype.write}function pe(e){let t=new tt(e);return t.on("error",r),!e.sync&&Ro&&(Dr.register(t,No),t.on("close",function(){Dr.unregister(t)})),t;function r(n){if(n.code==="EPIPE"){t.write=Y,t.end=Y,t.flushSync=Y,t.destroy=Y;return}t.removeListener("error",r),t.emit("error",n)}}function No(e,t){e.destroyed||(t==="beforeExit"?(e.flush(),e.on("drain",function(){e.end()})):e.flushSync())}function Po(e){return function(r,n,i={},o){if(typeof i=="string")o=pe({dest:i}),i={};else if(typeof o=="string"){if(i&&i.transport)throw Error("only one of option.transport or stream can be specified");o=pe({dest:o})}else if(i instanceof tt||i.writable||i._writableState)o=i,i={};else if(i.transport){if(i.transport instanceof tt||i.transport.writable||i.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(i.transport.targets&&i.transport.targets.length&&i.formatters&&typeof i.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let c;i.customLevels&&(c=i.useOnlyCustomLevels?i.customLevels:Object.assign({},i.levels,i.customLevels)),o=Bo({caller:n,...i.transport,levels:c})}if(i=Object.assign({},e,i),i.serializers=Object.assign({},e.serializers,i.serializers),i.formatters=Object.assign({},e.formatters,i.formatters),i.prettyPrint)throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:a,onChild:f}=i;return a===!1&&(i.level="silent"),f||(i.onChild=Y),o||(Do(process.stdout)?o=process.stdout:o=pe({fd:process.stdout.fd||1})),{opts:i,stream:o}}}function Mo(e,t){try{return JSON.stringify(e)}catch{try{return(t||this[rt])(e)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function Wo(e,t,r){return{level:e,bindings:t,log:r}}function zo(e){let t=Number(e);return typeof e=="string"&&Number.isFinite(t)?t:e===void 0?1:e}Ur.exports={noop:Y,buildSafeSonicBoom:pe,asChindings:Io,asJson:Co,genLog:qo,createArgsNormalizer:Po,stringify:Mo,buildFormatters:Wo,normalizeDestFileDescriptor:zo}});var we=v((Nu,Jr)=>{var Fo={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},Ko={ASC:"ASC",DESC:"DESC"};Jr.exports={DEFAULT_LEVELS:Fo,SORTING_ORDER:Ko}});var st=v((Pu,Yr)=>{"use strict";var{lsCacheSym:Vo,levelValSym:nt,useOnlyCustomLevelsSym:Uo,streamSym:Jo,formattersSym:Go,hooksSym:Ho,levelCompSym:Gr}=H(),{noop:Xo,genLog:V}=be(),{DEFAULT_LEVELS:M,SORTING_ORDER:Hr}=we(),Xr={fatal:e=>{let t=V(M.fatal,e);return function(...r){let n=this[Jo];if(t.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:e=>V(M.error,e),warn:e=>V(M.warn,e),info:e=>V(M.info,e),debug:e=>V(M.debug,e),trace:e=>V(M.trace,e)},it=Object.keys(M).reduce((e,t)=>(e[M[t]]=t,e),{}),Yo=Object.keys(it).reduce((e,t)=>(e[t]='{"level":'+Number(t),e),{});function Qo(e){let t=e[Go].level,{labels:r}=e.levels,n={};for(let i in r){let o=t(r[i],Number(i));n[i]=JSON.stringify(o).slice(0,-1)}return e[Vo]=n,e}function Zo(e,t){if(t)return!1;switch(e){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function el(e){let{labels:t,values:r}=this.levels;if(typeof e=="number"){if(t[e]===void 0)throw Error("unknown level value"+e);e=t[e]}if(r[e]===void 0)throw Error("unknown level "+e);let n=this[nt],i=this[nt]=r[e],o=this[Uo],a=this[Gr],f=this[Ho].logMethod;for(let c in r){if(a(r[c],i)===!1){this[c]=Xo;continue}this[c]=Zo(c,o)?Xr[c](f):V(r[c],f)}this.emit("level-change",e,i,t[n],n,this)}function tl(e){let{levels:t,levelVal:r}=this;return t&&t.labels?t.labels[r]:""}function rl(e){let{values:t}=this.levels,r=t[e];return r!==void 0&&this[Gr](r,this[nt])}function nl(e,t,r){return e===Hr.DESC?t<=r:t>=r}function il(e){return typeof e=="string"?nl.bind(null,e):e}function sl(e=null,t=!1){let r=e?Object.keys(e).reduce((o,a)=>(o[e[a]]=a,o),{}):null,n=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),t?null:it,r),i=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:M,e);return{labels:n,values:i}}function ol(e,t,r){if(typeof e=="number"){if(![].concat(Object.keys(t||{}).map(o=>t[o]),r?[]:Object.keys(it).map(o=>+o),1/0).includes(e))throw Error(`default level:${e} must be included in custom levels`);return}let n=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),r?null:M,t);if(!(e in n))throw Error(`default level:${e} must be included in custom levels`)}function ll(e,t){let{labels:r,values:n}=e;for(let i in t){if(i in n)throw Error("levels cannot be overridden");if(t[i]in r)throw Error("pre-existing level values cannot be used for new levels")}}function fl(e){if(typeof e!="function"&&!(typeof e=="string"&&Object.values(Hr).includes(e)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}Yr.exports={initialLsCache:Yo,genLsCache:Qo,levelMethods:Xr,getLevel:tl,setLevel:el,isLevelEnabled:rl,mappings:sl,assertNoLevelCollisions:ll,assertDefaultLevelFound:ol,genLevelComparison:il,assertLevelComparison:fl}});var ot=v((Mu,Qr)=>{"use strict";Qr.exports={version:"9.7.0"}});var cn=v((zu,un)=>{"use strict";var{EventEmitter:ul}=require("node:events"),{lsCacheSym:cl,levelValSym:al,setLevelSym:ft,getLevelSym:Zr,chindingsSym:ut,parsedChindingsSym:hl,mixinSym:dl,asJsonSym:sn,writeSym:yl,mixinMergeStrategySym:ml,timeSym:gl,timeSliceIndexSym:pl,streamSym:on,serializersSym:U,formattersSym:lt,errorKeySym:bl,messageKeySym:wl,useOnlyCustomLevelsSym:Sl,needsMetadataGsym:_l,redactFmtSym:El,stringifySym:vl,formatOptsSym:Ol,stringifiersSym:xl,msgPrefixSym:en,hooksSym:Ll}=H(),{getLevel:$l,setLevel:jl,isLevelEnabled:Al,mappings:Tl,initialLsCache:kl,genLsCache:Rl,assertNoLevelCollisions:Bl}=st(),{asChindings:ln,asJson:ql,buildFormatters:tn,stringify:rn}=be(),{version:Cl}=ot(),Il=Me(),Dl=class{},fn={constructor:Dl,child:Nl,bindings:Pl,setBindings:Ml,flush:Kl,isLevelEnabled:Al,version:Cl,get level(){return this[Zr]()},set level(e){this[ft](e)},get levelVal(){return this[al]},set levelVal(e){throw Error("levelVal is read-only")},[cl]:kl,[yl]:zl,[sn]:ql,[Zr]:$l,[ft]:jl};Object.setPrototypeOf(fn,ul.prototype);un.exports=function(){return Object.create(fn)};var nn=e=>e;function Nl(e,t){if(!e)throw Error("missing bindings for child Pino");t=t||{};let r=this[U],n=this[lt],i=Object.create(this);if(t.hasOwnProperty("serializers")===!0){i[U]=Object.create(null);for(let u in r)i[U][u]=r[u];let c=Object.getOwnPropertySymbols(r);for(var o=0;o{"use strict";var{hasOwnProperty:te}=Object.prototype,G=ht();G.configure=ht;G.stringify=G;G.default=G;dt.stringify=G;dt.configure=ht;dn.exports=G;var Vl=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function z(e){return e.length<5e3&&!Vl.test(e)?`"${e}"`:JSON.stringify(e)}function ct(e,t){if(e.length>200||t)return e.sort(t);for(let r=1;rn;)e[i]=e[i-1],i--;e[i]=n}return e}var Ul=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function at(e){return Ul.call(e)!==void 0&&e.length!==0}function an(e,t,r){e.length= 1`)}return r===void 0?1/0:r}function J(e){return e===1?"1 item":`${e} items`}function Xl(e){let t=new Set;for(let r of e)(typeof r=="string"||typeof r=="number")&&t.add(String(r));return t}function Yl(e){if(te.call(e,"strict")){let t=e.strict;if(typeof t!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(t)return r=>{let n=`Object can not safely be stringified. Received type ${typeof r}`;throw typeof r!="function"&&(n+=` (${r.toString()})`),new Error(n)}}}function ht(e){e={...e};let t=Yl(e);t&&(e.bigint===void 0&&(e.bigint=!1),"circularValue"in e||(e.circularValue=Error));let r=Jl(e),n=Hl(e,"bigint"),i=Gl(e),o=typeof i=="function"?i:void 0,a=hn(e,"maximumDepth"),f=hn(e,"maximumBreadth");function c(d,s,g,m,S,b){let w=s[d];switch(typeof w=="object"&&w!==null&&typeof w.toJSON=="function"&&(w=w.toJSON(d)),w=m.call(s,d,w),typeof w){case"string":return z(w);case"object":{if(w===null)return"null";if(g.indexOf(w)!==-1)return r;let _="",O=",",x=b;if(Array.isArray(w)){if(w.length===0)return"[]";if(af){let K=w.length-f-1;_+=`${O}"... ${J(K)} not stringified"`}return S!==""&&(_+=` +${x}`),g.pop(),`[${_}]`}let L=Object.keys(w),$=L.length;if($===0)return"{}";if(af){let T=$-f;_+=`${j}"...":${E}"${J(T)} not stringified"`,j=O}return S!==""&&j.length>1&&(_=` +${b}${_} +${x}`),g.pop(),`{${_}}`}case"number":return isFinite(w)?String(w):t?t(w):"null";case"boolean":return w===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(w);default:return t?t(w):void 0}}function h(d,s,g,m,S,b){switch(typeof s=="object"&&s!==null&&typeof s.toJSON=="function"&&(s=s.toJSON(d)),typeof s){case"string":return z(s);case"object":{if(s===null)return"null";if(g.indexOf(s)!==-1)return r;let w=b,_="",O=",";if(Array.isArray(s)){if(s.length===0)return"[]";if(af){let k=s.length-f-1;_+=`${O}"... ${J(k)} not stringified"`}return S!==""&&(_+=` +${w}`),g.pop(),`[${_}]`}g.push(s);let x="";S!==""&&(b+=S,O=`, +${b}`,x=" ");let L="";for(let $ of m){let E=h($,s[$],g,m,S,b);E!==void 0&&(_+=`${L}${z($)}:${x}${E}`,L=O)}return S!==""&&L.length>1&&(_=` +${b}${_} +${w}`),g.pop(),`{${_}}`}case"number":return isFinite(s)?String(s):t?t(s):"null";case"boolean":return s===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(s);default:return t?t(s):void 0}}function u(d,s,g,m,S){switch(typeof s){case"string":return z(s);case"object":{if(s===null)return"null";if(typeof s.toJSON=="function"){if(s=s.toJSON(d),typeof s!="object")return u(d,s,g,m,S);if(s===null)return"null"}if(g.indexOf(s)!==-1)return r;let b=S;if(Array.isArray(s)){if(s.length===0)return"[]";if(af){let q=s.length-f-1;E+=`${j}"... ${J(q)} not stringified"`}return E+=` +${b}`,g.pop(),`[${E}]`}let w=Object.keys(s),_=w.length;if(_===0)return"{}";if(af){let E=_-f;x+=`${L}"...": "${J(E)} not stringified"`,L=O}return L!==""&&(x=` +${S}${x} +${b}`),g.pop(),`{${x}}`}case"number":return isFinite(s)?String(s):t?t(s):"null";case"boolean":return s===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(s);default:return t?t(s):void 0}}function l(d,s,g){switch(typeof s){case"string":return z(s);case"object":{if(s===null)return"null";if(typeof s.toJSON=="function"){if(s=s.toJSON(d),typeof s!="object")return l(d,s,g);if(s===null)return"null"}if(g.indexOf(s)!==-1)return r;let m="",S=s.length!==void 0;if(S&&Array.isArray(s)){if(s.length===0)return"[]";if(af){let E=s.length-f-1;m+=`,"... ${J(E)} not stringified"`}return g.pop(),`[${m}]`}let b=Object.keys(s),w=b.length;if(w===0)return"{}";if(af){let x=w-f;m+=`${_}"...":"${J(x)} not stringified"`}return g.pop(),`{${m}}`}case"number":return isFinite(s)?String(s):t?t(s):"null";case"boolean":return s===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(s);default:return t?t(s):void 0}}function p(d,s,g){if(arguments.length>1){let m="";if(typeof g=="number"?m=" ".repeat(Math.min(g,10)):typeof g=="string"&&(m=g.slice(0,10)),s!=null){if(typeof s=="function")return c("",{"":d},[],s,m,"");if(Array.isArray(s))return h("",d,[],Xl(s),m,"")}if(m.length!==0)return u("",d,[],m,"")}return l("",d,[])}return p}});var pn=v((Fu,gn)=>{"use strict";var yt=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:mn}=we(),Ql=mn.info;function Zl(e,t){let r=0;e=e||[],t=t||{dedupe:!1};let n=Object.create(mn);n.silent=1/0,t.levels&&typeof t.levels=="object"&&Object.keys(t.levels).forEach(l=>{n[l]=t.levels[l]});let i={write:o,add:c,emit:a,flushSync:f,end:h,minLevel:0,streams:[],clone:u,[yt]:!0,streamLevels:n};return Array.isArray(e)?e.forEach(c,i):c.call(i,e),e=null,i;function o(l){let p,d=this.lastLevel,{streams:s}=this,g=0,m;for(let S=tf(s.length,t.dedupe);nf(S,s.length,t.dedupe);S=rf(S,t.dedupe))if(p=s[S],p.level<=d){if(g!==0&&g!==p.level)break;if(m=p.stream,m[yt]){let{lastTime:b,lastMsg:w,lastObj:_,lastLogger:O}=this;m.lastLevel=d,m.lastTime=b,m.lastMsg=w,m.lastObj=_,m.lastLogger=O}m.write(l),t.dedupe&&(g=p.level)}else if(!t.dedupe)break}function a(...l){for(let{stream:p}of this.streams)typeof p.emit=="function"&&p.emit(...l)}function f(){for(let{stream:l}of this.streams)typeof l.flushSync=="function"&&l.flushSync()}function c(l){if(!l)return i;let p=typeof l.write=="function"||l.stream,d=l.write?l:l.stream;if(!p)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:s,streamLevels:g}=this,m;typeof l.levelVal=="number"?m=l.levelVal:typeof l.level=="string"?m=g[l.level]:typeof l.level=="number"?m=l.level:m=Ql;let S={stream:d,level:m,levelVal:void 0,id:r++};return s.unshift(S),s.sort(ef),this.minLevel=s[0].level,i}function h(){for(let{stream:l}of this.streams)typeof l.flushSync=="function"&&l.flushSync(),l.end()}function u(l){let p=new Array(this.streams.length);for(let d=0;d=0:e{function Se(e){try{return require("path").join(`${process.cwd()}${require("path").sep}dist/cjs`.replace(/\\/g,"/"),e)}catch{return new Function("p","return new URL(p, import.meta.url).pathname")(e)}}globalThis.__bundlerPathsOverrides={...globalThis.__bundlerPathsOverrides||{},"thread-stream-worker":Se("./thread-stream-worker.cjs"),"pino-worker":Se("./pino-worker.cjs"),"pino/file":Se("./pino-file.cjs"),"pino-roll":Se("./pino-roll.cjs")};var sf=require("node:os"),xn=Re(),of=Be(),lf=Me(),Ln=ur(),ff=cn(),$n=H(),{configure:uf}=yn(),{assertDefaultLevelFound:cf,mappings:jn,genLsCache:af,genLevelComparison:hf,assertLevelComparison:df}=st(),{DEFAULT_LEVELS:An,SORTING_ORDER:yf}=we(),{createArgsNormalizer:mf,asChindings:gf,buildSafeSonicBoom:bn,buildFormatters:pf,stringify:mt,normalizeDestFileDescriptor:wn,noop:bf}=be(),{version:wf}=ot(),{chindingsSym:Sn,redactFmtSym:Sf,serializersSym:_n,timeSym:_f,timeSliceIndexSym:Ef,streamSym:vf,stringifySym:En,stringifySafeSym:gt,stringifiersSym:vn,setLevelSym:Of,endSym:xf,formatOptsSym:Lf,messageKeySym:$f,errorKeySym:jf,nestedKeySym:Af,mixinSym:Tf,levelCompSym:kf,useOnlyCustomLevelsSym:Rf,formattersSym:On,hooksSym:Bf,nestedKeyStrSym:qf,mixinMergeStrategySym:Cf,msgPrefixSym:If}=$n,{epochTime:Tn,nullTime:Df}=Ln,{pid:Nf}=process,Pf=sf.hostname(),Mf=xn.err,Wf={level:"info",levelComparison:yf.ASC,levels:An,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:Nf,hostname:Pf},serializers:Object.assign(Object.create(null),{err:Mf}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:Tn,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},zf=mf(Wf),Ff=Object.assign(Object.create(null),xn);function pt(...e){let t={},{opts:r,stream:n}=zf(t,of(),...e);r.level&&typeof r.level=="string"&&An[r.level.toLowerCase()]!==void 0&&(r.level=r.level.toLowerCase());let{redact:i,crlf:o,serializers:a,timestamp:f,messageKey:c,errorKey:h,nestedKey:u,base:l,name:p,level:d,customLevels:s,levelComparison:g,mixin:m,mixinMergeStrategy:S,useOnlyCustomLevels:b,formatters:w,hooks:_,depthLimit:O,edgeLimit:x,onChild:L,msgPrefix:$}=r,E=uf({maximumDepth:O,maximumBreadth:x}),j=pf(w.level,w.bindings,w.log),k=mt.bind({[gt]:E}),T=i?lf(i,k):{},B=i?{stringify:T[Sf]}:{stringify:k},q="}"+(o?`\r +`:` +`),K=gf.bind(null,{[Sn]:"",[_n]:a,[vn]:T,[En]:mt,[gt]:E,[On]:j}),Ee="";l!==null&&(p===void 0?Ee=K(l):Ee=K(Object.assign({},l,{name:p})));let bt=f instanceof Function?f:f?Tn:Df,Un=bt().indexOf(":")+1;if(b&&!s)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(m&&typeof m!="function")throw Error(`Unknown mixin type "${typeof m}" - expected "function"`);if($&&typeof $!="string")throw Error(`Unknown msgPrefix type "${typeof $}" - expected "string"`);cf(d,s,b);let wt=jn(s,b);typeof n.emit=="function"&&n.emit("message",{code:"PINO_CONFIG",config:{levels:wt,messageKey:c,errorKey:h}}),df(g);let Jn=hf(g);return Object.assign(t,{levels:wt,[kf]:Jn,[Rf]:b,[vf]:n,[_f]:bt,[Ef]:Un,[En]:mt,[gt]:E,[vn]:T,[xf]:q,[Lf]:B,[$f]:c,[jf]:h,[Af]:u,[qf]:u?`,${JSON.stringify(u)}:{`:"",[_n]:a,[Tf]:m,[Cf]:S,[Sn]:Ee,[On]:j,[Bf]:_,silent:bf,onChild:L,[If]:$}),Object.setPrototypeOf(t,ff()),af(t),t[Of](d),t}C.exports=pt;C.exports.destination=(e=process.stdout.fd)=>typeof e=="object"?(e.dest=wn(e.dest||process.stdout.fd),bn(e)):bn({dest:wn(e),minLength:0});C.exports.transport=Ze();C.exports.multistream=pn();C.exports.levels=jn();C.exports.stdSerializers=Ff;C.exports.stdTimeFunctions=Object.assign({},Ln);C.exports.symbols=$n;C.exports.version=wf;C.exports.default=pt;C.exports.pino=pt});var Cn=v((Vu,qn)=>{"use strict";var{Transform:Kf}=require("stream"),{StringDecoder:Vf}=require("string_decoder"),F=Symbol("last"),_e=Symbol("decoder");function Uf(e,t,r){let n;if(this.overflow){if(n=this[_e].write(e).split(this.matcher),n.length===1)return r();n.shift(),this.overflow=!1}else this[F]+=this[_e].write(e),n=this[F].split(this.matcher);this[F]=n.pop();for(let i=0;ithis.maxLength,this.overflow&&!this.skipOverflow){r(new Error("maximum buffer reached"));return}r()}function Jf(e){if(this[F]+=this[_e].end(),this[F])try{Bn(this,this.mapper(this[F]))}catch(t){return e(t)}e()}function Bn(e,t){t!==void 0&&e.push(t)}function Rn(e){return e}function Gf(e,t,r){switch(e=e||/\r?\n/,t=t||Rn,r=r||{},arguments.length){case 1:typeof e=="function"?(t=e,e=/\r?\n/):typeof e=="object"&&!(e instanceof RegExp)&&!e[Symbol.split]&&(r=e,e=/\r?\n/);break;case 2:typeof e=="function"?(r=t,t=e,e=/\r?\n/):typeof t=="object"&&(r=t,t=Rn)}r=Object.assign({},r),r.autoDestroy=!0,r.transform=Uf,r.flush=Jf,r.readableObjectMode=!0;let n=new Kf(r);return n[F]="",n[_e]=new Vf("utf8"),n.matcher=e,n.mapper=t,n.maxLength=r.maxLength,n.skipOverflow=r.skipOverflow||!1,n.overflow=!1,n._destroy=function(i,o){this._writableState.errorEmitted=!1,o(i)},n}qn.exports=Gf});var Mn=v((Uu,Pn)=>{"use strict";var In=Symbol.for("pino.metadata"),Hf=Cn(),{Duplex:Xf}=require("stream"),{parentPort:Dn,workerData:Nn}=require("worker_threads");function Yf(){let e,t,r=new Promise((n,i)=>{e=n,t=i});return r.resolve=e,r.reject=t,r}Pn.exports=function(t,r={}){let n=r.expectPinoConfig===!0&&Nn?.workerData?.pinoWillSendConfig===!0,i=r.parse==="lines",o=typeof r.parseLine=="function"?r.parseLine:JSON.parse,a=r.close||Qf,f=Hf(function(h){let u;try{u=o(h)}catch(l){this.emit("unknown",h,l);return}if(u===null){this.emit("unknown",h,"Null value ignored");return}return typeof u!="object"&&(u={data:u,time:Date.now()}),f[In]&&(f.lastTime=u.time,f.lastLevel=u.level,f.lastObj=u),i?h:u},{autoDestroy:!0});if(f._destroy=function(h,u){let l=a(h,u);l&&typeof l.then=="function"&&l.then(u,u)},r.expectPinoConfig===!0&&Nn?.workerData?.pinoWillSendConfig!==!0&&setImmediate(()=>{f.emit("error",new Error("This transport is not compatible with the current version of pino. Please upgrade pino to the latest version."))}),r.metadata!==!1&&(f[In]=!0,f.lastTime=0,f.lastLevel=0,f.lastObj=null),n){let h={},u=Yf();return Dn.on("message",function l(p){p.code==="PINO_CONFIG"&&(h=p.config,u.resolve(),Dn.off("message",l))}),Object.defineProperties(f,{levels:{get(){return h.levels}},messageKey:{get(){return h.messageKey}},errorKey:{get(){return h.errorKey}}}),u.then(c)}return c();function c(){let h=t(f);if(h&&typeof h.catch=="function")h.catch(u=>{f.destroy(u)}),h=null;else if(r.enablePipelining&&h)return Xf.from({writable:f,readable:h});return f}};function Qf(e,t){process.nextTick(t,e)}});var zn=v((Ju,Wn)=>{var Zf=new Function("modulePath","return import(modulePath)");function eu(e){return typeof __non_webpack__require__=="function"?__non_webpack__require__(e):require(e)}Wn.exports={realImport:Zf,realRequire:eu}});var Kn=v((Gu,Fn)=>{"use strict";var{realImport:tu,realRequire:re}=zn();Fn.exports=ru;async function ru(e){let t;try{let r=e.startsWith("file://")?e:"file://"+e;r.endsWith(".ts")||r.endsWith(".cts")?(process[Symbol.for("ts-node.register.instance")]?re("ts-node/register"):process.env&&process.env.TS_NODE_DEV&&re("ts-node-dev"),t=re(decodeURIComponent(e))):t=await tu(r)}catch(r){if(r.code==="ENOTDIR"||r.code==="ERR_MODULE_NOT_FOUND")t=re(e);else if(r.code===void 0||r.code==="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING")try{t=re(decodeURIComponent(e))}catch{throw r}else throw r}if(typeof t=="object"&&(t=t.default),typeof t=="object"&&(t=t.default),typeof t!="function")throw Error("exported worker is not a function");return t}});var nu=require("node:events"),{pipeline:iu,PassThrough:su}=require("node:stream"),ou=kn(),lu=Mn(),Vn=Kn();module.exports=async function({targets:e,pipelines:t,levels:r,dedupe:n}){let i=[];if(e&&e.length&&(e=await Promise.all(e.map(async f=>{let h=await(await Vn(f.target))(f.options);return{level:f.level,stream:h}})),i.push(...e)),t&&t.length&&(t=await Promise.all(t.map(async f=>{let c,h=await Promise.all(f.map(async u=>(c=u.level,await(await Vn(u.target))(u.options))));return{level:c,stream:a(h)}})),i.push(...t)),i.length===1)return i[0].stream;return lu(o,{parse:"lines",metadata:!0,close(f,c){let h=0;for(let l of i)h++,l.stream.on("close",u),l.stream.end();function u(){--h===0&&c(f)}}});function o(f){let c=ou.multistream(i,{levels:r,dedupe:n});f.on("data",function(h){let{lastTime:u,lastMsg:l,lastObj:p,lastLevel:d}=this;c.lastLevel=d,c.lastTime=u,c.lastMsg=l,c.lastObj=p,c.write(h+` +`)})}function a(f){let c=new nu,h=new su({autoDestroy:!0,destroy(u,l){c.on("error",l),c.on("closed",l)}});return iu(h,...f,function(u){if(u&&u.code!=="ERR_STREAM_PREMATURE_CLOSE"){c.emit("error",u);return}c.emit("closed")}),h}}; +//# sourceMappingURL=pino-worker.cjs.map diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/pino-worker.cjs.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/pino-worker.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..6bfcad5b7cce15c77fdf8fda4f2a6f04096d87fe --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/pino-worker.cjs.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err-helpers.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err-proto.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err-with-cause.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/req.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/res.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/caller.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/validator.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/rx.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/parse.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/redactor.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/modifiers.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/restorer.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/state.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/symbols.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/redaction.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/time.js", "../../node_modules/.pnpm/quick-format-unescaped@4.0.4/node_modules/quick-format-unescaped/index.js", "../../node_modules/.pnpm/atomic-sleep@1.0.0/node_modules/atomic-sleep/index.js", "../../node_modules/.pnpm/sonic-boom@4.2.0/node_modules/sonic-boom/index.js", "../../node_modules/.pnpm/on-exit-leak-free@2.1.2/node_modules/on-exit-leak-free/index.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/package.json", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/wait.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/indexes.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/transport.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/tools.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/constants.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/levels.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/meta.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/proto.js", "../../node_modules/.pnpm/safe-stable-stringify@2.5.0/node_modules/safe-stable-stringify/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/multistream.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/pino.js", "../../node_modules/.pnpm/split2@4.2.0/node_modules/split2/index.js", "../../node_modules/.pnpm/pino-abstract-transport@2.0.0/node_modules/pino-abstract-transport/index.js", "../../node_modules/.pnpm/real-require@0.2.0/node_modules/real-require/src/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/transport-stream.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/worker.js"], + "sourcesContent": ["'use strict'\n\n// **************************************************************\n// * Code initially copied/adapted from \"pony-cause\" npm module *\n// * Please upstream improvements there *\n// **************************************************************\n\nconst isErrorLike = (err) => {\n return err && typeof err.message === 'string'\n}\n\n/**\n * @param {Error|{ cause?: unknown|(()=>err)}} err\n * @returns {Error|Object|undefined}\n */\nconst getErrorCause = (err) => {\n if (!err) return\n\n /** @type {unknown} */\n // @ts-ignore\n const cause = err.cause\n\n // VError / NError style causes\n if (typeof cause === 'function') {\n // @ts-ignore\n const causeResult = err.cause()\n\n return isErrorLike(causeResult)\n ? causeResult\n : undefined\n } else {\n return isErrorLike(cause)\n ? cause\n : undefined\n }\n}\n\n/**\n * Internal method that keeps a track of which error we have already added, to avoid circular recursion\n *\n * @private\n * @param {Error} err\n * @param {Set} seen\n * @returns {string}\n */\nconst _stackWithCauses = (err, seen) => {\n if (!isErrorLike(err)) return ''\n\n const stack = err.stack || ''\n\n // Ensure we don't go circular or crazily deep\n if (seen.has(err)) {\n return stack + '\\ncauses have become circular...'\n }\n\n const cause = getErrorCause(err)\n\n if (cause) {\n seen.add(err)\n return (stack + '\\ncaused by: ' + _stackWithCauses(cause, seen))\n } else {\n return stack\n }\n}\n\n/**\n * @param {Error} err\n * @returns {string}\n */\nconst stackWithCauses = (err) => _stackWithCauses(err, new Set())\n\n/**\n * Internal method that keeps a track of which error we have already added, to avoid circular recursion\n *\n * @private\n * @param {Error} err\n * @param {Set} seen\n * @param {boolean} [skip]\n * @returns {string}\n */\nconst _messageWithCauses = (err, seen, skip) => {\n if (!isErrorLike(err)) return ''\n\n const message = skip ? '' : (err.message || '')\n\n // Ensure we don't go circular or crazily deep\n if (seen.has(err)) {\n return message + ': ...'\n }\n\n const cause = getErrorCause(err)\n\n if (cause) {\n seen.add(err)\n\n // @ts-ignore\n const skipIfVErrorStyleCause = typeof err.cause === 'function'\n\n return (message +\n (skipIfVErrorStyleCause ? '' : ': ') +\n _messageWithCauses(cause, seen, skipIfVErrorStyleCause))\n } else {\n return message\n }\n}\n\n/**\n * @param {Error} err\n * @returns {string}\n */\nconst messageWithCauses = (err) => _messageWithCauses(err, new Set())\n\nmodule.exports = {\n isErrorLike,\n getErrorCause,\n stackWithCauses,\n messageWithCauses\n}\n", "'use strict'\n\nconst seen = Symbol('circular-ref-tag')\nconst rawSymbol = Symbol('pino-raw-err-ref')\n\nconst pinoErrProto = Object.create({}, {\n type: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n message: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n stack: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n aggregateErrors: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoErrProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nmodule.exports = {\n pinoErrProto,\n pinoErrorSymbols: {\n seen,\n rawSymbol\n }\n}\n", "'use strict'\n\nmodule.exports = errSerializer\n\nconst { messageWithCauses, stackWithCauses, isErrorLike } = require('./err-helpers')\nconst { pinoErrProto, pinoErrorSymbols } = require('./err-proto')\nconst { seen } = pinoErrorSymbols\n\nconst { toString } = Object.prototype\n\nfunction errSerializer (err) {\n if (!isErrorLike(err)) {\n return err\n }\n\n err[seen] = undefined // tag to prevent re-looking at this\n const _err = Object.create(pinoErrProto)\n _err.type = toString.call(err.constructor) === '[object Function]'\n ? err.constructor.name\n : err.name\n _err.message = messageWithCauses(err)\n _err.stack = stackWithCauses(err)\n\n if (Array.isArray(err.errors)) {\n _err.aggregateErrors = err.errors.map(err => errSerializer(err))\n }\n\n for (const key in err) {\n if (_err[key] === undefined) {\n const val = err[key]\n if (isErrorLike(val)) {\n // We append cause messages and stacks to _err, therefore skipping causes here\n if (key !== 'cause' && !Object.prototype.hasOwnProperty.call(val, seen)) {\n _err[key] = errSerializer(val)\n }\n } else {\n _err[key] = val\n }\n }\n }\n\n delete err[seen] // clean up tag in case err is serialized again later\n _err.raw = err\n return _err\n}\n", "'use strict'\n\nmodule.exports = errWithCauseSerializer\n\nconst { isErrorLike } = require('./err-helpers')\nconst { pinoErrProto, pinoErrorSymbols } = require('./err-proto')\nconst { seen } = pinoErrorSymbols\n\nconst { toString } = Object.prototype\n\nfunction errWithCauseSerializer (err) {\n if (!isErrorLike(err)) {\n return err\n }\n\n err[seen] = undefined // tag to prevent re-looking at this\n const _err = Object.create(pinoErrProto)\n _err.type = toString.call(err.constructor) === '[object Function]'\n ? err.constructor.name\n : err.name\n _err.message = err.message\n _err.stack = err.stack\n\n if (Array.isArray(err.errors)) {\n _err.aggregateErrors = err.errors.map(err => errWithCauseSerializer(err))\n }\n\n if (isErrorLike(err.cause) && !Object.prototype.hasOwnProperty.call(err.cause, seen)) {\n _err.cause = errWithCauseSerializer(err.cause)\n }\n\n for (const key in err) {\n if (_err[key] === undefined) {\n const val = err[key]\n if (isErrorLike(val)) {\n if (!Object.prototype.hasOwnProperty.call(val, seen)) {\n _err[key] = errWithCauseSerializer(val)\n }\n } else {\n _err[key] = val\n }\n }\n }\n\n delete err[seen] // clean up tag in case err is serialized again later\n _err.raw = err\n return _err\n}\n", "'use strict'\n\nmodule.exports = {\n mapHttpRequest,\n reqSerializer\n}\n\nconst rawSymbol = Symbol('pino-raw-req-ref')\nconst pinoReqProto = Object.create({}, {\n id: {\n enumerable: true,\n writable: true,\n value: ''\n },\n method: {\n enumerable: true,\n writable: true,\n value: ''\n },\n url: {\n enumerable: true,\n writable: true,\n value: ''\n },\n query: {\n enumerable: true,\n writable: true,\n value: ''\n },\n params: {\n enumerable: true,\n writable: true,\n value: ''\n },\n headers: {\n enumerable: true,\n writable: true,\n value: {}\n },\n remoteAddress: {\n enumerable: true,\n writable: true,\n value: ''\n },\n remotePort: {\n enumerable: true,\n writable: true,\n value: ''\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoReqProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nfunction reqSerializer (req) {\n // req.info is for hapi compat.\n const connection = req.info || req.socket\n const _req = Object.create(pinoReqProto)\n _req.id = (typeof req.id === 'function' ? req.id() : (req.id || (req.info ? req.info.id : undefined)))\n _req.method = req.method\n // req.originalUrl is for expressjs compat.\n if (req.originalUrl) {\n _req.url = req.originalUrl\n } else {\n const path = req.path\n // path for safe hapi compat.\n _req.url = typeof path === 'string' ? path : (req.url ? req.url.path || req.url : undefined)\n }\n\n if (req.query) {\n _req.query = req.query\n }\n\n if (req.params) {\n _req.params = req.params\n }\n\n _req.headers = req.headers\n _req.remoteAddress = connection && connection.remoteAddress\n _req.remotePort = connection && connection.remotePort\n // req.raw is for hapi compat/equivalence\n _req.raw = req.raw || req\n return _req\n}\n\nfunction mapHttpRequest (req) {\n return {\n req: reqSerializer(req)\n }\n}\n", "'use strict'\n\nmodule.exports = {\n mapHttpResponse,\n resSerializer\n}\n\nconst rawSymbol = Symbol('pino-raw-res-ref')\nconst pinoResProto = Object.create({}, {\n statusCode: {\n enumerable: true,\n writable: true,\n value: 0\n },\n headers: {\n enumerable: true,\n writable: true,\n value: ''\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoResProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nfunction resSerializer (res) {\n const _res = Object.create(pinoResProto)\n _res.statusCode = res.headersSent ? res.statusCode : null\n _res.headers = res.getHeaders ? res.getHeaders() : res._headers\n _res.raw = res\n return _res\n}\n\nfunction mapHttpResponse (res) {\n return {\n res: resSerializer(res)\n }\n}\n", "'use strict'\n\nconst errSerializer = require('./lib/err')\nconst errWithCauseSerializer = require('./lib/err-with-cause')\nconst reqSerializers = require('./lib/req')\nconst resSerializers = require('./lib/res')\n\nmodule.exports = {\n err: errSerializer,\n errWithCause: errWithCauseSerializer,\n mapHttpRequest: reqSerializers.mapHttpRequest,\n mapHttpResponse: resSerializers.mapHttpResponse,\n req: reqSerializers.reqSerializer,\n res: resSerializers.resSerializer,\n\n wrapErrorSerializer: function wrapErrorSerializer (customSerializer) {\n if (customSerializer === errSerializer) return customSerializer\n return function wrapErrSerializer (err) {\n return customSerializer(errSerializer(err))\n }\n },\n\n wrapRequestSerializer: function wrapRequestSerializer (customSerializer) {\n if (customSerializer === reqSerializers.reqSerializer) return customSerializer\n return function wrappedReqSerializer (req) {\n return customSerializer(reqSerializers.reqSerializer(req))\n }\n },\n\n wrapResponseSerializer: function wrapResponseSerializer (customSerializer) {\n if (customSerializer === resSerializers.resSerializer) return customSerializer\n return function wrappedResSerializer (res) {\n return customSerializer(resSerializers.resSerializer(res))\n }\n }\n}\n", "'use strict'\n\nfunction noOpPrepareStackTrace (_, stack) {\n return stack\n}\n\nmodule.exports = function getCallers () {\n const originalPrepare = Error.prepareStackTrace\n Error.prepareStackTrace = noOpPrepareStackTrace\n const stack = new Error().stack\n Error.prepareStackTrace = originalPrepare\n\n if (!Array.isArray(stack)) {\n return undefined\n }\n\n const entries = stack.slice(2)\n\n const fileNames = []\n\n for (const entry of entries) {\n if (!entry) {\n continue\n }\n\n fileNames.push(entry.getFileName())\n }\n\n return fileNames\n}\n", "'use strict'\n\nmodule.exports = validator\n\nfunction validator (opts = {}) {\n const {\n ERR_PATHS_MUST_BE_STRINGS = () => 'fast-redact - Paths must be (non-empty) strings',\n ERR_INVALID_PATH = (s) => `fast-redact \u2013 Invalid path (${s})`\n } = opts\n\n return function validate ({ paths }) {\n paths.forEach((s) => {\n if (typeof s !== 'string') {\n throw Error(ERR_PATHS_MUST_BE_STRINGS())\n }\n try {\n if (/\u3007/.test(s)) throw Error()\n const expr = (s[0] === '[' ? '' : '.') + s.replace(/^\\*/, '\u3007').replace(/\\.\\*/g, '.\u3007').replace(/\\[\\*\\]/g, '[\u3007]')\n if (/\\n|\\r|;/.test(expr)) throw Error()\n if (/\\/\\*/.test(expr)) throw Error()\n /* eslint-disable-next-line */\n Function(`\n 'use strict'\n const o = new Proxy({}, { get: () => o, set: () => { throw Error() } });\n const \u3007 = null;\n o${expr}\n if ([o${expr}].length !== 1) throw Error()`)()\n } catch (e) {\n throw Error(ERR_INVALID_PATH(s))\n }\n })\n }\n}\n", "'use strict'\n\nmodule.exports = /[^.[\\]]+|\\[((?:.)*?)\\]/g\n\n/*\nRegular expression explanation:\n\nAlt 1: /[^.[\\]]+/ - Match one or more characters that are *not* a dot (.)\n opening square bracket ([) or closing square bracket (])\n\nAlt 2: /\\[((?:.)*?)\\]/ - If the char IS dot or square bracket, then create a capture\n group (which will be capture group $1) that matches anything\n within square brackets. Expansion is lazy so it will\n stop matching as soon as the first closing bracket is met `]`\n (rather than continuing to match until the final closing bracket).\n*/\n", "'use strict'\n\nconst rx = require('./rx')\n\nmodule.exports = parse\n\nfunction parse ({ paths }) {\n const wildcards = []\n var wcLen = 0\n const secret = paths.reduce(function (o, strPath, ix) {\n var path = strPath.match(rx).map((p) => p.replace(/'|\"|`/g, ''))\n const leadingBracket = strPath[0] === '['\n path = path.map((p) => {\n if (p[0] === '[') return p.substr(1, p.length - 2)\n else return p\n })\n const star = path.indexOf('*')\n if (star > -1) {\n const before = path.slice(0, star)\n const beforeStr = before.join('.')\n const after = path.slice(star + 1, path.length)\n const nested = after.length > 0\n wcLen++\n wildcards.push({\n before,\n beforeStr,\n after,\n nested\n })\n } else {\n o[strPath] = {\n path: path,\n val: undefined,\n precensored: false,\n circle: '',\n escPath: JSON.stringify(strPath),\n leadingBracket: leadingBracket\n }\n }\n return o\n }, {})\n\n return { wildcards, wcLen, secret }\n}\n", "'use strict'\n\nconst rx = require('./rx')\n\nmodule.exports = redactor\n\nfunction redactor ({ secret, serialize, wcLen, strict, isCensorFct, censorFctTakesPath }, state) {\n /* eslint-disable-next-line */\n const redact = Function('o', `\n if (typeof o !== 'object' || o == null) {\n ${strictImpl(strict, serialize)}\n }\n const { censor, secret } = this\n const originalSecret = {}\n const secretKeys = Object.keys(secret)\n for (var i = 0; i < secretKeys.length; i++) {\n originalSecret[secretKeys[i]] = secret[secretKeys[i]]\n }\n\n ${redactTmpl(secret, isCensorFct, censorFctTakesPath)}\n this.compileRestore()\n ${dynamicRedactTmpl(wcLen > 0, isCensorFct, censorFctTakesPath)}\n this.secret = originalSecret\n ${resultTmpl(serialize)}\n `).bind(state)\n\n redact.state = state\n\n if (serialize === false) {\n redact.restore = (o) => state.restore(o)\n }\n\n return redact\n}\n\nfunction redactTmpl (secret, isCensorFct, censorFctTakesPath) {\n return Object.keys(secret).map((path) => {\n const { escPath, leadingBracket, path: arrPath } = secret[path]\n const skip = leadingBracket ? 1 : 0\n const delim = leadingBracket ? '' : '.'\n const hops = []\n var match\n while ((match = rx.exec(path)) !== null) {\n const [ , ix ] = match\n const { index, input } = match\n if (index > skip) hops.push(input.substring(0, index - (ix ? 0 : 1)))\n }\n var existence = hops.map((p) => `o${delim}${p}`).join(' && ')\n if (existence.length === 0) existence += `o${delim}${path} != null`\n else existence += ` && o${delim}${path} != null`\n\n const circularDetection = `\n switch (true) {\n ${hops.reverse().map((p) => `\n case o${delim}${p} === censor:\n secret[${escPath}].circle = ${JSON.stringify(p)}\n break\n `).join('\\n')}\n }\n `\n\n const censorArgs = censorFctTakesPath\n ? `val, ${JSON.stringify(arrPath)}`\n : `val`\n\n return `\n if (${existence}) {\n const val = o${delim}${path}\n if (val === censor) {\n secret[${escPath}].precensored = true\n } else {\n secret[${escPath}].val = val\n o${delim}${path} = ${isCensorFct ? `censor(${censorArgs})` : 'censor'}\n ${circularDetection}\n }\n }\n `\n }).join('\\n')\n}\n\nfunction dynamicRedactTmpl (hasWildcards, isCensorFct, censorFctTakesPath) {\n return hasWildcards === true ? `\n {\n const { wildcards, wcLen, groupRedact, nestedRedact } = this\n for (var i = 0; i < wcLen; i++) {\n const { before, beforeStr, after, nested } = wildcards[i]\n if (nested === true) {\n secret[beforeStr] = secret[beforeStr] || []\n nestedRedact(secret[beforeStr], o, before, after, censor, ${isCensorFct}, ${censorFctTakesPath})\n } else secret[beforeStr] = groupRedact(o, before, censor, ${isCensorFct}, ${censorFctTakesPath})\n }\n }\n ` : ''\n}\n\nfunction resultTmpl (serialize) {\n return serialize === false ? `return o` : `\n var s = this.serialize(o)\n this.restore(o)\n return s\n `\n}\n\nfunction strictImpl (strict, serialize) {\n return strict === true\n ? `throw Error('fast-redact: primitives cannot be redacted')`\n : serialize === false ? `return o` : `return this.serialize(o)`\n}\n", "'use strict'\n\nmodule.exports = {\n groupRedact,\n groupRestore,\n nestedRedact,\n nestedRestore\n}\n\nfunction groupRestore ({ keys, values, target }) {\n if (target == null || typeof target === 'string') return\n const length = keys.length\n for (var i = 0; i < length; i++) {\n const k = keys[i]\n target[k] = values[i]\n }\n}\n\nfunction groupRedact (o, path, censor, isCensorFct, censorFctTakesPath) {\n const target = get(o, path)\n if (target == null || typeof target === 'string') return { keys: null, values: null, target, flat: true }\n const keys = Object.keys(target)\n const keysLength = keys.length\n const pathLength = path.length\n const pathWithKey = censorFctTakesPath ? [...path] : undefined\n const values = new Array(keysLength)\n\n for (var i = 0; i < keysLength; i++) {\n const key = keys[i]\n values[i] = target[key]\n\n if (censorFctTakesPath) {\n pathWithKey[pathLength] = key\n target[key] = censor(target[key], pathWithKey)\n } else if (isCensorFct) {\n target[key] = censor(target[key])\n } else {\n target[key] = censor\n }\n }\n return { keys, values, target, flat: true }\n}\n\n/**\n * @param {RestoreInstruction[]} instructions a set of instructions for restoring values to objects\n */\nfunction nestedRestore (instructions) {\n for (let i = 0; i < instructions.length; i++) {\n const { target, path, value } = instructions[i]\n let current = target\n for (let i = path.length - 1; i > 0; i--) {\n current = current[path[i]]\n }\n current[path[0]] = value\n }\n}\n\nfunction nestedRedact (store, o, path, ns, censor, isCensorFct, censorFctTakesPath) {\n const target = get(o, path)\n if (target == null) return\n const keys = Object.keys(target)\n const keysLength = keys.length\n for (var i = 0; i < keysLength; i++) {\n const key = keys[i]\n specialSet(store, target, key, path, ns, censor, isCensorFct, censorFctTakesPath)\n }\n return store\n}\n\nfunction has (obj, prop) {\n return obj !== undefined && obj !== null\n ? ('hasOwn' in Object ? Object.hasOwn(obj, prop) : Object.prototype.hasOwnProperty.call(obj, prop))\n : false\n}\n\nfunction specialSet (store, o, k, path, afterPath, censor, isCensorFct, censorFctTakesPath) {\n const afterPathLen = afterPath.length\n const lastPathIndex = afterPathLen - 1\n const originalKey = k\n var i = -1\n var n\n var nv\n var ov\n var oov = null\n var wc = null\n var kIsWc\n var wcov\n var consecutive = false\n var level = 0\n // need to track depth of the `redactPath` tree\n var depth = 0\n var redactPathCurrent = tree()\n ov = n = o[k]\n if (typeof n !== 'object') return\n while (n != null && ++i < afterPathLen) {\n depth += 1\n k = afterPath[i]\n oov = ov\n if (k !== '*' && !wc && !(typeof n === 'object' && k in n)) {\n break\n }\n if (k === '*') {\n if (wc === '*') {\n consecutive = true\n }\n wc = k\n if (i !== lastPathIndex) {\n continue\n }\n }\n if (wc) {\n const wcKeys = Object.keys(n)\n for (var j = 0; j < wcKeys.length; j++) {\n const wck = wcKeys[j]\n wcov = n[wck]\n kIsWc = k === '*'\n if (consecutive) {\n redactPathCurrent = node(redactPathCurrent, wck, depth)\n level = i\n ov = iterateNthLevel(wcov, level - 1, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, o[originalKey], depth + 1)\n } else {\n if (kIsWc || (typeof wcov === 'object' && wcov !== null && k in wcov)) {\n if (kIsWc) {\n ov = wcov\n } else {\n ov = wcov[k]\n }\n nv = (i !== lastPathIndex)\n ? ov\n : (isCensorFct\n ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))\n : censor)\n if (kIsWc) {\n const rv = restoreInstr(node(redactPathCurrent, wck, depth), ov, o[originalKey])\n store.push(rv)\n n[wck] = nv\n } else {\n if (wcov[k] === nv) {\n // pass\n } else if ((nv === undefined && censor !== undefined) || (has(wcov, k) && nv === ov)) {\n redactPathCurrent = node(redactPathCurrent, wck, depth)\n } else {\n redactPathCurrent = node(redactPathCurrent, wck, depth)\n const rv = restoreInstr(node(redactPathCurrent, k, depth + 1), ov, o[originalKey])\n store.push(rv)\n wcov[k] = nv\n }\n }\n }\n }\n }\n wc = null\n } else {\n ov = n[k]\n redactPathCurrent = node(redactPathCurrent, k, depth)\n nv = (i !== lastPathIndex)\n ? ov\n : (isCensorFct\n ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))\n : censor)\n if ((has(n, k) && nv === ov) || (nv === undefined && censor !== undefined)) {\n // pass\n } else {\n const rv = restoreInstr(redactPathCurrent, ov, o[originalKey])\n store.push(rv)\n n[k] = nv\n }\n n = n[k]\n }\n if (typeof n !== 'object') break\n // prevent circular structure, see https://github.com/pinojs/pino/issues/1513\n if (ov === oov || typeof ov === 'undefined') {\n // pass\n }\n }\n}\n\nfunction get (o, p) {\n var i = -1\n var l = p.length\n var n = o\n while (n != null && ++i < l) {\n n = n[p[i]]\n }\n return n\n}\n\nfunction iterateNthLevel (wcov, level, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, parent, depth) {\n if (level === 0) {\n if (kIsWc || (typeof wcov === 'object' && wcov !== null && k in wcov)) {\n if (kIsWc) {\n ov = wcov\n } else {\n ov = wcov[k]\n }\n nv = (i !== lastPathIndex)\n ? ov\n : (isCensorFct\n ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))\n : censor)\n if (kIsWc) {\n const rv = restoreInstr(redactPathCurrent, ov, parent)\n store.push(rv)\n n[wck] = nv\n } else {\n if (wcov[k] === nv) {\n // pass\n } else if ((nv === undefined && censor !== undefined) || (has(wcov, k) && nv === ov)) {\n // pass\n } else {\n const rv = restoreInstr(node(redactPathCurrent, k, depth + 1), ov, parent)\n store.push(rv)\n wcov[k] = nv\n }\n }\n }\n }\n for (const key in wcov) {\n if (typeof wcov[key] === 'object') {\n redactPathCurrent = node(redactPathCurrent, key, depth)\n iterateNthLevel(wcov[key], level - 1, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, parent, depth + 1)\n }\n }\n}\n\n/**\n * @typedef {object} TreeNode\n * @prop {TreeNode} [parent] reference to the parent of this node in the tree, or `null` if there is no parent\n * @prop {string} key the key that this node represents (key here being part of the path being redacted\n * @prop {TreeNode[]} children the child nodes of this node\n * @prop {number} depth the depth of this node in the tree\n */\n\n/**\n * instantiate a new, empty tree\n * @returns {TreeNode}\n */\nfunction tree () {\n return { parent: null, key: null, children: [], depth: 0 }\n}\n\n/**\n * creates a new node in the tree, attaching it as a child of the provided parent node\n * if the specified depth matches the parent depth, adds the new node as a _sibling_ of the parent instead\n * @param {TreeNode} parent the parent node to add a new node to (if the parent depth matches the provided `depth` value, will instead add as a sibling of this\n * @param {string} key the key that the new node represents (key here being part of the path being redacted)\n * @param {number} depth the depth of the new node in the tree - used to determing whether to add the new node as a child or sibling of the provided `parent` node\n * @returns {TreeNode} a reference to the newly created node in the tree\n */\nfunction node (parent, key, depth) {\n if (parent.depth === depth) {\n return node(parent.parent, key, depth)\n }\n\n var child = {\n parent,\n key,\n depth,\n children: []\n }\n\n parent.children.push(child)\n\n return child\n}\n\n/**\n * @typedef {object} RestoreInstruction\n * @prop {string[]} path a reverse-order path that can be used to find the correct insertion point to restore a `value` for the given `parent` object\n * @prop {*} value the value to restore\n * @prop {object} target the object to restore the `value` in\n */\n\n/**\n * create a restore instruction for the given redactPath node\n * generates a path in reverse order by walking up the redactPath tree\n * @param {TreeNode} node a tree node that should be at the bottom of the redact path (i.e. have no children) - this will be used to walk up the redact path tree to construct the path needed to restore\n * @param {*} value the value to restore\n * @param {object} target a reference to the parent object to apply the restore instruction to\n * @returns {RestoreInstruction} an instruction used to restore a nested value for a specific object\n */\nfunction restoreInstr (node, value, target) {\n let current = node\n const path = []\n do {\n path.push(current.key)\n current = current.parent\n } while (current.parent != null)\n\n return { path, value, target }\n}\n", "'use strict'\n\nconst { groupRestore, nestedRestore } = require('./modifiers')\n\nmodule.exports = restorer\n\nfunction restorer () {\n return function compileRestore () {\n if (this.restore) {\n this.restore.state.secret = this.secret\n return\n }\n const { secret, wcLen } = this\n const paths = Object.keys(secret)\n const resetters = resetTmpl(secret, paths)\n const hasWildcards = wcLen > 0\n const state = hasWildcards ? { secret, groupRestore, nestedRestore } : { secret }\n /* eslint-disable-next-line */\n this.restore = Function(\n 'o',\n restoreTmpl(resetters, paths, hasWildcards)\n ).bind(state)\n this.restore.state = state\n }\n}\n\n/**\n * Mutates the original object to be censored by restoring its original values\n * prior to censoring.\n *\n * @param {object} secret Compiled object describing which target fields should\n * be censored and the field states.\n * @param {string[]} paths The list of paths to censor as provided at\n * initialization time.\n *\n * @returns {string} String of JavaScript to be used by `Function()`. The\n * string compiles to the function that does the work in the description.\n */\nfunction resetTmpl (secret, paths) {\n return paths.map((path) => {\n const { circle, escPath, leadingBracket } = secret[path]\n const delim = leadingBracket ? '' : '.'\n const reset = circle\n ? `o.${circle} = secret[${escPath}].val`\n : `o${delim}${path} = secret[${escPath}].val`\n const clear = `secret[${escPath}].val = undefined`\n return `\n if (secret[${escPath}].val !== undefined) {\n try { ${reset} } catch (e) {}\n ${clear}\n }\n `\n }).join('')\n}\n\n/**\n * Creates the body of the restore function\n *\n * Restoration of the redacted object happens\n * backwards, in reverse order of redactions,\n * so that repeated redactions on the same object\n * property can be eventually rolled back to the\n * original value.\n *\n * This way dynamic redactions are restored first,\n * starting from the last one working backwards and\n * followed by the static ones.\n *\n * @returns {string} the body of the restore function\n */\nfunction restoreTmpl (resetters, paths, hasWildcards) {\n const dynamicReset = hasWildcards === true ? `\n const keys = Object.keys(secret)\n const len = keys.length\n for (var i = len - 1; i >= ${paths.length}; i--) {\n const k = keys[i]\n const o = secret[k]\n if (o) {\n if (o.flat === true) this.groupRestore(o)\n else this.nestedRestore(o)\n secret[k] = null\n }\n }\n ` : ''\n\n return `\n const secret = this.secret\n ${dynamicReset}\n ${resetters}\n return o\n `\n}\n", "'use strict'\n\nmodule.exports = state\n\nfunction state (o) {\n const {\n secret,\n censor,\n compileRestore,\n serialize,\n groupRedact,\n nestedRedact,\n wildcards,\n wcLen\n } = o\n const builder = [{ secret, censor, compileRestore }]\n if (serialize !== false) builder.push({ serialize })\n if (wcLen > 0) builder.push({ groupRedact, nestedRedact, wildcards, wcLen })\n return Object.assign(...builder)\n}\n", "'use strict'\n\nconst validator = require('./lib/validator')\nconst parse = require('./lib/parse')\nconst redactor = require('./lib/redactor')\nconst restorer = require('./lib/restorer')\nconst { groupRedact, nestedRedact } = require('./lib/modifiers')\nconst state = require('./lib/state')\nconst rx = require('./lib/rx')\nconst validate = validator()\nconst noop = (o) => o\nnoop.restore = noop\n\nconst DEFAULT_CENSOR = '[REDACTED]'\nfastRedact.rx = rx\nfastRedact.validator = validator\n\nmodule.exports = fastRedact\n\nfunction fastRedact (opts = {}) {\n const paths = Array.from(new Set(opts.paths || []))\n const serialize = 'serialize' in opts ? (\n opts.serialize === false ? opts.serialize\n : (typeof opts.serialize === 'function' ? opts.serialize : JSON.stringify)\n ) : JSON.stringify\n const remove = opts.remove\n if (remove === true && serialize !== JSON.stringify) {\n throw Error('fast-redact \u2013 remove option may only be set when serializer is JSON.stringify')\n }\n const censor = remove === true\n ? undefined\n : 'censor' in opts ? opts.censor : DEFAULT_CENSOR\n\n const isCensorFct = typeof censor === 'function'\n const censorFctTakesPath = isCensorFct && censor.length > 1\n\n if (paths.length === 0) return serialize || noop\n\n validate({ paths, serialize, censor })\n\n const { wildcards, wcLen, secret } = parse({ paths, censor })\n\n const compileRestore = restorer()\n const strict = 'strict' in opts ? opts.strict : true\n\n return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({\n secret,\n censor,\n compileRestore,\n serialize,\n groupRedact,\n nestedRedact,\n wildcards,\n wcLen\n }))\n}\n", "'use strict'\n\nconst setLevelSym = Symbol('pino.setLevel')\nconst getLevelSym = Symbol('pino.getLevel')\nconst levelValSym = Symbol('pino.levelVal')\nconst levelCompSym = Symbol('pino.levelComp')\nconst useLevelLabelsSym = Symbol('pino.useLevelLabels')\nconst useOnlyCustomLevelsSym = Symbol('pino.useOnlyCustomLevels')\nconst mixinSym = Symbol('pino.mixin')\n\nconst lsCacheSym = Symbol('pino.lsCache')\nconst chindingsSym = Symbol('pino.chindings')\n\nconst asJsonSym = Symbol('pino.asJson')\nconst writeSym = Symbol('pino.write')\nconst redactFmtSym = Symbol('pino.redactFmt')\n\nconst timeSym = Symbol('pino.time')\nconst timeSliceIndexSym = Symbol('pino.timeSliceIndex')\nconst streamSym = Symbol('pino.stream')\nconst stringifySym = Symbol('pino.stringify')\nconst stringifySafeSym = Symbol('pino.stringifySafe')\nconst stringifiersSym = Symbol('pino.stringifiers')\nconst endSym = Symbol('pino.end')\nconst formatOptsSym = Symbol('pino.formatOpts')\nconst messageKeySym = Symbol('pino.messageKey')\nconst errorKeySym = Symbol('pino.errorKey')\nconst nestedKeySym = Symbol('pino.nestedKey')\nconst nestedKeyStrSym = Symbol('pino.nestedKeyStr')\nconst mixinMergeStrategySym = Symbol('pino.mixinMergeStrategy')\nconst msgPrefixSym = Symbol('pino.msgPrefix')\n\nconst wildcardFirstSym = Symbol('pino.wildcardFirst')\n\n// public symbols, no need to use the same pino\n// version for these\nconst serializersSym = Symbol.for('pino.serializers')\nconst formattersSym = Symbol.for('pino.formatters')\nconst hooksSym = Symbol.for('pino.hooks')\nconst needsMetadataGsym = Symbol.for('pino.metadata')\n\nmodule.exports = {\n setLevelSym,\n getLevelSym,\n levelValSym,\n levelCompSym,\n useLevelLabelsSym,\n mixinSym,\n lsCacheSym,\n chindingsSym,\n asJsonSym,\n writeSym,\n serializersSym,\n redactFmtSym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n stringifySym,\n stringifySafeSym,\n stringifiersSym,\n endSym,\n formatOptsSym,\n messageKeySym,\n errorKeySym,\n nestedKeySym,\n wildcardFirstSym,\n needsMetadataGsym,\n useOnlyCustomLevelsSym,\n formattersSym,\n hooksSym,\n nestedKeyStrSym,\n mixinMergeStrategySym,\n msgPrefixSym\n}\n", "'use strict'\n\nconst fastRedact = require('fast-redact')\nconst { redactFmtSym, wildcardFirstSym } = require('./symbols')\nconst { rx, validator } = fastRedact\n\nconst validate = validator({\n ERR_PATHS_MUST_BE_STRINGS: () => 'pino \u2013 redacted paths must be strings',\n ERR_INVALID_PATH: (s) => `pino \u2013 redact paths array contains an invalid path (${s})`\n})\n\nconst CENSOR = '[Redacted]'\nconst strict = false // TODO should this be configurable?\n\nfunction redaction (opts, serialize) {\n const { paths, censor } = handle(opts)\n\n const shape = paths.reduce((o, str) => {\n rx.lastIndex = 0\n const first = rx.exec(str)\n const next = rx.exec(str)\n\n // ns is the top-level path segment, brackets + quoting removed.\n let ns = first[1] !== undefined\n ? first[1].replace(/^(?:\"|'|`)(.*)(?:\"|'|`)$/, '$1')\n : first[0]\n\n if (ns === '*') {\n ns = wildcardFirstSym\n }\n\n // top level key:\n if (next === null) {\n o[ns] = null\n return o\n }\n\n // path with at least two segments:\n // if ns is already redacted at the top level, ignore lower level redactions\n if (o[ns] === null) {\n return o\n }\n\n const { index } = next\n const nextPath = `${str.substr(index, str.length - 1)}`\n\n o[ns] = o[ns] || []\n\n // shape is a mix of paths beginning with literal values and wildcard\n // paths [ \"a.b.c\", \"*.b.z\" ] should reduce to a shape of\n // { \"a\": [ \"b.c\", \"b.z\" ], *: [ \"b.z\" ] }\n // note: \"b.z\" is in both \"a\" and * arrays because \"a\" matches the wildcard.\n // (* entry has wildcardFirstSym as key)\n if (ns !== wildcardFirstSym && o[ns].length === 0) {\n // first time ns's get all '*' redactions so far\n o[ns].push(...(o[wildcardFirstSym] || []))\n }\n\n if (ns === wildcardFirstSym) {\n // new * path gets added to all previously registered literal ns's.\n Object.keys(o).forEach(function (k) {\n if (o[k]) {\n o[k].push(nextPath)\n }\n })\n }\n\n o[ns].push(nextPath)\n return o\n }, {})\n\n // the redactor assigned to the format symbol key\n // provides top level redaction for instances where\n // an object is interpolated into the msg string\n const result = {\n [redactFmtSym]: fastRedact({ paths, censor, serialize, strict })\n }\n\n const topCensor = (...args) => {\n return typeof censor === 'function' ? serialize(censor(...args)) : serialize(censor)\n }\n\n return [...Object.keys(shape), ...Object.getOwnPropertySymbols(shape)].reduce((o, k) => {\n // top level key:\n if (shape[k] === null) {\n o[k] = (value) => topCensor(value, [k])\n } else {\n const wrappedCensor = typeof censor === 'function'\n ? (value, path) => {\n return censor(value, [k, ...path])\n }\n : censor\n o[k] = fastRedact({\n paths: shape[k],\n censor: wrappedCensor,\n serialize,\n strict\n })\n }\n return o\n }, result)\n}\n\nfunction handle (opts) {\n if (Array.isArray(opts)) {\n opts = { paths: opts, censor: CENSOR }\n validate(opts)\n return opts\n }\n let { paths, censor = CENSOR, remove } = opts\n if (Array.isArray(paths) === false) { throw Error('pino \u2013 redact must contain an array of strings') }\n if (remove === true) censor = undefined\n validate({ paths, censor })\n\n return { paths, censor }\n}\n\nmodule.exports = redaction\n", "'use strict'\n\nconst nullTime = () => ''\n\nconst epochTime = () => `,\"time\":${Date.now()}`\n\nconst unixTime = () => `,\"time\":${Math.round(Date.now() / 1000.0)}`\n\nconst isoTime = () => `,\"time\":\"${new Date(Date.now()).toISOString()}\"` // using Date.now() for testability\n\nmodule.exports = { nullTime, epochTime, unixTime, isoTime }\n", "'use strict'\nfunction tryStringify (o) {\n try { return JSON.stringify(o) } catch(e) { return '\"[Circular]\"' }\n}\n\nmodule.exports = format\n\nfunction format(f, args, opts) {\n var ss = (opts && opts.stringify) || tryStringify\n var offset = 1\n if (typeof f === 'object' && f !== null) {\n var len = args.length + offset\n if (len === 1) return f\n var objects = new Array(len)\n objects[0] = ss(f)\n for (var index = 1; index < len; index++) {\n objects[index] = ss(args[index])\n }\n return objects.join(' ')\n }\n if (typeof f !== 'string') {\n return f\n }\n var argLen = args.length\n if (argLen === 0) return f\n var str = ''\n var a = 1 - offset\n var lastPos = -1\n var flen = (f && f.length) || 0\n for (var i = 0; i < flen;) {\n if (f.charCodeAt(i) === 37 && i + 1 < flen) {\n lastPos = lastPos > -1 ? lastPos : 0\n switch (f.charCodeAt(i + 1)) {\n case 100: // 'd'\n case 102: // 'f'\n if (a >= argLen)\n break\n if (args[a] == null) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += Number(args[a])\n lastPos = i + 2\n i++\n break\n case 105: // 'i'\n if (a >= argLen)\n break\n if (args[a] == null) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += Math.floor(Number(args[a]))\n lastPos = i + 2\n i++\n break\n case 79: // 'O'\n case 111: // 'o'\n case 106: // 'j'\n if (a >= argLen)\n break\n if (args[a] === undefined) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n var type = typeof args[a]\n if (type === 'string') {\n str += '\\'' + args[a] + '\\''\n lastPos = i + 2\n i++\n break\n }\n if (type === 'function') {\n str += args[a].name || ''\n lastPos = i + 2\n i++\n break\n }\n str += ss(args[a])\n lastPos = i + 2\n i++\n break\n case 115: // 's'\n if (a >= argLen)\n break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += String(args[a])\n lastPos = i + 2\n i++\n break\n case 37: // '%'\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += '%'\n lastPos = i + 2\n i++\n a--\n break\n }\n ++a\n }\n ++i\n }\n if (lastPos === -1)\n return f\n else if (lastPos < flen) {\n str += f.slice(lastPos)\n }\n\n return str\n}\n", "'use strict'\n\n/* global SharedArrayBuffer, Atomics */\n\nif (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') {\n const nil = new Int32Array(new SharedArrayBuffer(4))\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n\n Atomics.wait(nil, 0, 0, Number(ms))\n }\n module.exports = sleep\n} else {\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n const target = Date.now() + Number(ms)\n while (target > Date.now()){}\n }\n\n module.exports = sleep\n\n}\n", "'use strict'\n\nconst fs = require('fs')\nconst EventEmitter = require('events')\nconst inherits = require('util').inherits\nconst path = require('path')\nconst sleep = require('atomic-sleep')\nconst assert = require('assert')\n\nconst BUSY_WRITE_TIMEOUT = 100\nconst kEmptyBuffer = Buffer.allocUnsafe(0)\n\n// 16 KB. Don't write more than docker buffer size.\n// https://github.com/moby/moby/blob/513ec73831269947d38a644c278ce3cac36783b2/daemon/logger/copier.go#L13\nconst MAX_WRITE = 16 * 1024\n\nconst kContentModeBuffer = 'buffer'\nconst kContentModeUtf8 = 'utf8'\n\nconst [major, minor] = (process.versions.node || '0.0').split('.').map(Number)\nconst kCopyBuffer = major >= 22 && minor >= 7\n\nfunction openFile (file, sonic) {\n sonic._opening = true\n sonic._writing = true\n sonic._asyncDrainScheduled = false\n\n // NOTE: 'error' and 'ready' events emitted below only relevant when sonic.sync===false\n // for sync mode, there is no way to add a listener that will receive these\n\n function fileOpened (err, fd) {\n if (err) {\n sonic._reopening = false\n sonic._writing = false\n sonic._opening = false\n\n if (sonic.sync) {\n process.nextTick(() => {\n if (sonic.listenerCount('error') > 0) {\n sonic.emit('error', err)\n }\n })\n } else {\n sonic.emit('error', err)\n }\n return\n }\n\n const reopening = sonic._reopening\n\n sonic.fd = fd\n sonic.file = file\n sonic._reopening = false\n sonic._opening = false\n sonic._writing = false\n\n if (sonic.sync) {\n process.nextTick(() => sonic.emit('ready'))\n } else {\n sonic.emit('ready')\n }\n\n if (sonic.destroyed) {\n return\n }\n\n // start\n if ((!sonic._writing && sonic._len > sonic.minLength) || sonic._flushPending) {\n sonic._actualWrite()\n } else if (reopening) {\n process.nextTick(() => sonic.emit('drain'))\n }\n }\n\n const flags = sonic.append ? 'a' : 'w'\n const mode = sonic.mode\n\n if (sonic.sync) {\n try {\n if (sonic.mkdir) fs.mkdirSync(path.dirname(file), { recursive: true })\n const fd = fs.openSync(file, flags, mode)\n fileOpened(null, fd)\n } catch (err) {\n fileOpened(err)\n throw err\n }\n } else if (sonic.mkdir) {\n fs.mkdir(path.dirname(file), { recursive: true }, (err) => {\n if (err) return fileOpened(err)\n fs.open(file, flags, mode, fileOpened)\n })\n } else {\n fs.open(file, flags, mode, fileOpened)\n }\n}\n\nfunction SonicBoom (opts) {\n if (!(this instanceof SonicBoom)) {\n return new SonicBoom(opts)\n }\n\n let { fd, dest, minLength, maxLength, maxWrite, periodicFlush, sync, append = true, mkdir, retryEAGAIN, fsync, contentMode, mode } = opts || {}\n\n fd = fd || dest\n\n this._len = 0\n this.fd = -1\n this._bufs = []\n this._lens = []\n this._writing = false\n this._ending = false\n this._reopening = false\n this._asyncDrainScheduled = false\n this._flushPending = false\n this._hwm = Math.max(minLength || 0, 16387)\n this.file = null\n this.destroyed = false\n this.minLength = minLength || 0\n this.maxLength = maxLength || 0\n this.maxWrite = maxWrite || MAX_WRITE\n this._periodicFlush = periodicFlush || 0\n this._periodicFlushTimer = undefined\n this.sync = sync || false\n this.writable = true\n this._fsync = fsync || false\n this.append = append || false\n this.mode = mode\n this.retryEAGAIN = retryEAGAIN || (() => true)\n this.mkdir = mkdir || false\n\n let fsWriteSync\n let fsWrite\n if (contentMode === kContentModeBuffer) {\n this._writingBuf = kEmptyBuffer\n this.write = writeBuffer\n this.flush = flushBuffer\n this.flushSync = flushBufferSync\n this._actualWrite = actualWriteBuffer\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf)\n fsWrite = () => fs.write(this.fd, this._writingBuf, this.release)\n } else if (contentMode === undefined || contentMode === kContentModeUtf8) {\n this._writingBuf = ''\n this.write = write\n this.flush = flush\n this.flushSync = flushSync\n this._actualWrite = actualWrite\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf, 'utf8')\n fsWrite = () => fs.write(this.fd, this._writingBuf, 'utf8', this.release)\n } else {\n throw new Error(`SonicBoom supports \"${kContentModeUtf8}\" and \"${kContentModeBuffer}\", but passed ${contentMode}`)\n }\n\n if (typeof fd === 'number') {\n this.fd = fd\n process.nextTick(() => this.emit('ready'))\n } else if (typeof fd === 'string') {\n openFile(fd, this)\n } else {\n throw new Error('SonicBoom supports only file descriptors and files')\n }\n if (this.minLength >= this.maxWrite) {\n throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`)\n }\n\n this.release = (err, n) => {\n if (err) {\n if ((err.code === 'EAGAIN' || err.code === 'EBUSY') && this.retryEAGAIN(err, this._writingBuf.length, this._len - this._writingBuf.length)) {\n if (this.sync) {\n // This error code should not happen in sync mode, because it is\n // not using the underlining operating system asynchronous functions.\n // However it happens, and so we handle it.\n // Ref: https://github.com/pinojs/pino/issues/783\n try {\n sleep(BUSY_WRITE_TIMEOUT)\n this.release(undefined, 0)\n } catch (err) {\n this.release(err)\n }\n } else {\n // Let's give the destination some time to process the chunk.\n setTimeout(fsWrite, BUSY_WRITE_TIMEOUT)\n }\n } else {\n this._writing = false\n\n this.emit('error', err)\n }\n return\n }\n\n this.emit('write', n)\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n\n if (this._writingBuf.length) {\n if (!this.sync) {\n fsWrite()\n return\n }\n\n try {\n do {\n const n = fsWriteSync()\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n } while (this._writingBuf.length)\n } catch (err) {\n this.release(err)\n return\n }\n }\n\n if (this._fsync) {\n fs.fsyncSync(this.fd)\n }\n\n const len = this._len\n if (this._reopening) {\n this._writing = false\n this._reopening = false\n this.reopen()\n } else if (len > this.minLength) {\n this._actualWrite()\n } else if (this._ending) {\n if (len > 0) {\n this._actualWrite()\n } else {\n this._writing = false\n actualClose(this)\n }\n } else {\n this._writing = false\n if (this.sync) {\n if (!this._asyncDrainScheduled) {\n this._asyncDrainScheduled = true\n process.nextTick(emitDrain, this)\n }\n } else {\n this.emit('drain')\n }\n }\n }\n\n this.on('newListener', function (name) {\n if (name === 'drain') {\n this._asyncDrainScheduled = false\n }\n })\n\n if (this._periodicFlush !== 0) {\n this._periodicFlushTimer = setInterval(() => this.flush(null), this._periodicFlush)\n this._periodicFlushTimer.unref()\n }\n}\n\n/**\n * Release the writingBuf after fs.write n bytes data\n * @param {string | Buffer} writingBuf - currently writing buffer, usually be instance._writingBuf.\n * @param {number} len - currently buffer length, usually be instance._len.\n * @param {number} n - number of bytes fs already written\n * @returns {{writingBuf: string | Buffer, len: number}} released writingBuf and length\n */\nfunction releaseWritingBuf (writingBuf, len, n) {\n // if Buffer.byteLength is equal to n, that means writingBuf contains no multi-byte character\n if (typeof writingBuf === 'string' && Buffer.byteLength(writingBuf) !== n) {\n // Since the fs.write callback parameter `n` means how many bytes the passed of string\n // We calculate the original string length for avoiding the multi-byte character issue\n n = Buffer.from(writingBuf).subarray(0, n).toString().length\n }\n len = Math.max(len - n, 0)\n writingBuf = writingBuf.slice(n)\n return { writingBuf, len }\n}\n\nfunction emitDrain (sonic) {\n const hasListeners = sonic.listenerCount('drain') > 0\n if (!hasListeners) return\n sonic._asyncDrainScheduled = false\n sonic.emit('drain')\n}\n\ninherits(SonicBoom, EventEmitter)\n\nfunction mergeBuf (bufs, len) {\n if (bufs.length === 0) {\n return kEmptyBuffer\n }\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return Buffer.concat(bufs, len)\n}\n\nfunction write (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n bufs[bufs.length - 1].length + data.length > this.maxWrite\n ) {\n bufs.push('' + data)\n } else {\n bufs[bufs.length - 1] += data\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction writeBuffer (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n const lens = this._lens\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n lens[lens.length - 1] + data.length > this.maxWrite\n ) {\n bufs.push([data])\n lens.push(data.length)\n } else {\n bufs[bufs.length - 1].push(data)\n lens[lens.length - 1] += data.length\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction callFlushCallbackOnDrain (cb) {\n this._flushPending = true\n const onDrain = () => {\n // only if _fsync is false to avoid double fsync\n if (!this._fsync) {\n try {\n fs.fsync(this.fd, (err) => {\n this._flushPending = false\n cb(err)\n })\n } catch (err) {\n cb(err)\n }\n } else {\n this._flushPending = false\n cb()\n }\n this.off('error', onError)\n }\n const onError = (err) => {\n this._flushPending = false\n cb(err)\n this.off('drain', onDrain)\n }\n\n this.once('drain', onDrain)\n this.once('error', onError)\n}\n\nfunction flush (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push('')\n }\n\n this._actualWrite()\n}\n\nfunction flushBuffer (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push([])\n this._lens.push(0)\n }\n\n this._actualWrite()\n}\n\nSonicBoom.prototype.reopen = function (file) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.reopen(file)\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n if (!this.file) {\n throw new Error('Unable to reopen a file descriptor, you must pass a file to SonicBoom')\n }\n\n if (file) {\n this.file = file\n }\n this._reopening = true\n\n if (this._writing) {\n return\n }\n\n const fd = this.fd\n this.once('ready', () => {\n if (fd !== this.fd) {\n fs.close(fd, (err) => {\n if (err) {\n return this.emit('error', err)\n }\n })\n }\n })\n\n openFile(this.file, this)\n}\n\nSonicBoom.prototype.end = function () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.end()\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n this._ending = true\n\n if (this._writing) {\n return\n }\n\n if (this._len > 0 && this.fd >= 0) {\n this._actualWrite()\n } else {\n actualClose(this)\n }\n}\n\nfunction flushSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift(this._writingBuf)\n this._writingBuf = ''\n }\n\n let buf = ''\n while (this._bufs.length || buf) {\n if (buf.length <= 0) {\n buf = this._bufs[0]\n }\n try {\n const n = fs.writeSync(this.fd, buf, 'utf8')\n const releasedBufObj = releaseWritingBuf(buf, this._len, n)\n buf = releasedBufObj.writingBuf\n this._len = releasedBufObj.len\n if (buf.length <= 0) {\n this._bufs.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n\n try {\n fs.fsyncSync(this.fd)\n } catch {\n // Skip the error. The fd might not support fsync.\n }\n}\n\nfunction flushBufferSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift([this._writingBuf])\n this._writingBuf = kEmptyBuffer\n }\n\n let buf = kEmptyBuffer\n while (this._bufs.length || buf.length) {\n if (buf.length <= 0) {\n buf = mergeBuf(this._bufs[0], this._lens[0])\n }\n try {\n const n = fs.writeSync(this.fd, buf)\n buf = buf.subarray(n)\n this._len = Math.max(this._len - n, 0)\n if (buf.length <= 0) {\n this._bufs.shift()\n this._lens.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n}\n\nSonicBoom.prototype.destroy = function () {\n if (this.destroyed) {\n return\n }\n actualClose(this)\n}\n\nfunction actualWrite () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf || this._bufs.shift() || ''\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf, 'utf8')\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n fs.write(this.fd, this._writingBuf, 'utf8', release)\n }\n}\n\nfunction actualWriteBuffer () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift())\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf)\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n // fs.write will need to copy string to buffer anyway so\n // we do it here to avoid the overhead of calculating the buffer size\n // in releaseWritingBuf.\n if (kCopyBuffer) {\n this._writingBuf = Buffer.from(this._writingBuf)\n }\n fs.write(this.fd, this._writingBuf, release)\n }\n}\n\nfunction actualClose (sonic) {\n if (sonic.fd === -1) {\n sonic.once('ready', actualClose.bind(null, sonic))\n return\n }\n\n if (sonic._periodicFlushTimer !== undefined) {\n clearInterval(sonic._periodicFlushTimer)\n }\n\n sonic.destroyed = true\n sonic._bufs = []\n sonic._lens = []\n\n assert(typeof sonic.fd === 'number', `sonic.fd must be a number, got ${typeof sonic.fd}`)\n try {\n fs.fsync(sonic.fd, closeWrapped)\n } catch {\n }\n\n function closeWrapped () {\n // We skip errors in fsync\n\n if (sonic.fd !== 1 && sonic.fd !== 2) {\n fs.close(sonic.fd, done)\n } else {\n done()\n }\n }\n\n function done (err) {\n if (err) {\n sonic.emit('error', err)\n return\n }\n\n if (sonic._ending && !sonic._writing) {\n sonic.emit('finish')\n }\n sonic.emit('close')\n }\n}\n\n/**\n * These export configurations enable JS and TS developers\n * to consumer SonicBoom in whatever way best suits their needs.\n * Some examples of supported import syntax includes:\n * - `const SonicBoom = require('SonicBoom')`\n * - `const { SonicBoom } = require('SonicBoom')`\n * - `import * as SonicBoom from 'SonicBoom'`\n * - `import { SonicBoom } from 'SonicBoom'`\n * - `import SonicBoom from 'SonicBoom'`\n */\nSonicBoom.SonicBoom = SonicBoom\nSonicBoom.default = SonicBoom\nmodule.exports = SonicBoom\n", "'use strict'\n\nconst refs = {\n exit: [],\n beforeExit: []\n}\nconst functions = {\n exit: onExit,\n beforeExit: onBeforeExit\n}\n\nlet registry\n\nfunction ensureRegistry () {\n if (registry === undefined) {\n registry = new FinalizationRegistry(clear)\n }\n}\n\nfunction install (event) {\n if (refs[event].length > 0) {\n return\n }\n\n process.on(event, functions[event])\n}\n\nfunction uninstall (event) {\n if (refs[event].length > 0) {\n return\n }\n process.removeListener(event, functions[event])\n if (refs.exit.length === 0 && refs.beforeExit.length === 0) {\n registry = undefined\n }\n}\n\nfunction onExit () {\n callRefs('exit')\n}\n\nfunction onBeforeExit () {\n callRefs('beforeExit')\n}\n\nfunction callRefs (event) {\n for (const ref of refs[event]) {\n const obj = ref.deref()\n const fn = ref.fn\n\n // This should always happen, however GC is\n // undeterministic so it might not happen.\n /* istanbul ignore else */\n if (obj !== undefined) {\n fn(obj, event)\n }\n }\n refs[event] = []\n}\n\nfunction clear (ref) {\n for (const event of ['exit', 'beforeExit']) {\n const index = refs[event].indexOf(ref)\n refs[event].splice(index, index + 1)\n uninstall(event)\n }\n}\n\nfunction _register (event, obj, fn) {\n if (obj === undefined) {\n throw new Error('the object can\\'t be undefined')\n }\n install(event)\n const ref = new WeakRef(obj)\n ref.fn = fn\n\n ensureRegistry()\n registry.register(obj, ref)\n refs[event].push(ref)\n}\n\nfunction register (obj, fn) {\n _register('exit', obj, fn)\n}\n\nfunction registerBeforeExit (obj, fn) {\n _register('beforeExit', obj, fn)\n}\n\nfunction unregister (obj) {\n if (registry === undefined) {\n return\n }\n registry.unregister(obj)\n for (const event of ['exit', 'beforeExit']) {\n refs[event] = refs[event].filter((ref) => {\n const _obj = ref.deref()\n return _obj && _obj !== obj\n })\n uninstall(event)\n }\n}\n\nmodule.exports = {\n register,\n registerBeforeExit,\n unregister\n}\n", "{\n \"name\": \"thread-stream\",\n \"version\": \"3.1.0\",\n \"description\": \"A streaming way to send data to a Node.js Worker Thread\",\n \"main\": \"index.js\",\n \"types\": \"index.d.ts\",\n \"dependencies\": {\n \"real-require\": \"^0.2.0\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^20.1.0\",\n \"@types/tap\": \"^15.0.0\",\n \"@yao-pkg/pkg\": \"^5.11.5\",\n \"desm\": \"^1.3.0\",\n \"fastbench\": \"^1.0.1\",\n \"husky\": \"^9.0.6\",\n \"pino-elasticsearch\": \"^8.0.0\",\n \"sonic-boom\": \"^4.0.1\",\n \"standard\": \"^17.0.0\",\n \"tap\": \"^16.2.0\",\n \"ts-node\": \"^10.8.0\",\n \"typescript\": \"^5.3.2\",\n \"why-is-node-running\": \"^2.2.2\"\n },\n \"scripts\": {\n \"build\": \"tsc --noEmit\",\n \"test\": \"standard && npm run build && npm run transpile && tap \\\"test/**/*.test.*js\\\" && tap --ts test/*.test.*ts\",\n \"test:ci\": \"standard && npm run transpile && npm run test:ci:js && npm run test:ci:ts\",\n \"test:ci:js\": \"tap --no-check-coverage --timeout=120 --coverage-report=lcovonly \\\"test/**/*.test.*js\\\"\",\n \"test:ci:ts\": \"tap --ts --no-check-coverage --coverage-report=lcovonly \\\"test/**/*.test.*ts\\\"\",\n \"test:yarn\": \"npm run transpile && tap \\\"test/**/*.test.js\\\" --no-check-coverage\",\n \"transpile\": \"sh ./test/ts/transpile.sh\",\n \"prepare\": \"husky install\"\n },\n \"standard\": {\n \"ignore\": [\n \"test/ts/**/*\",\n \"test/syntax-error.mjs\"\n ]\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/mcollina/thread-stream.git\"\n },\n \"keywords\": [\n \"worker\",\n \"thread\",\n \"threads\",\n \"stream\"\n ],\n \"author\": \"Matteo Collina \",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/mcollina/thread-stream/issues\"\n },\n \"homepage\": \"https://github.com/mcollina/thread-stream#readme\"\n}\n", "'use strict'\n\nconst MAX_TIMEOUT = 1000\n\nfunction wait (state, index, expected, timeout, done) {\n const max = Date.now() + timeout\n let current = Atomics.load(state, index)\n if (current === expected) {\n done(null, 'ok')\n return\n }\n let prior = current\n const check = (backoff) => {\n if (Date.now() > max) {\n done(null, 'timed-out')\n } else {\n setTimeout(() => {\n prior = current\n current = Atomics.load(state, index)\n if (current === prior) {\n check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)\n } else {\n if (current === expected) done(null, 'ok')\n else done(null, 'not-equal')\n }\n }, backoff)\n }\n }\n check(1)\n}\n\n// let waitDiffCount = 0\nfunction waitDiff (state, index, expected, timeout, done) {\n // const id = waitDiffCount++\n // process._rawDebug(`>>> waitDiff ${id}`)\n const max = Date.now() + timeout\n let current = Atomics.load(state, index)\n if (current !== expected) {\n done(null, 'ok')\n return\n }\n const check = (backoff) => {\n // process._rawDebug(`${id} ${index} current ${current} expected ${expected}`)\n // process._rawDebug('' + backoff)\n if (Date.now() > max) {\n done(null, 'timed-out')\n } else {\n setTimeout(() => {\n current = Atomics.load(state, index)\n if (current !== expected) {\n done(null, 'ok')\n } else {\n check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)\n }\n }, backoff)\n }\n }\n check(1)\n}\n\nmodule.exports = { wait, waitDiff }\n", "'use strict'\n\nconst WRITE_INDEX = 4\nconst READ_INDEX = 8\n\nmodule.exports = {\n WRITE_INDEX,\n READ_INDEX\n}\n", "'use strict'\n\nconst { version } = require('./package.json')\nconst { EventEmitter } = require('events')\nconst { Worker } = require('worker_threads')\nconst { join } = require('path')\nconst { pathToFileURL } = require('url')\nconst { wait } = require('./lib/wait')\nconst {\n WRITE_INDEX,\n READ_INDEX\n} = require('./lib/indexes')\nconst buffer = require('buffer')\nconst assert = require('assert')\n\nconst kImpl = Symbol('kImpl')\n\n// V8 limit for string size\nconst MAX_STRING = buffer.constants.MAX_STRING_LENGTH\n\nclass FakeWeakRef {\n constructor (value) {\n this._value = value\n }\n\n deref () {\n return this._value\n }\n}\n\nclass FakeFinalizationRegistry {\n register () {}\n\n unregister () {}\n}\n\n// Currently using FinalizationRegistry with code coverage breaks the world\n// Ref: https://github.com/nodejs/node/issues/49344\nconst FinalizationRegistry = process.env.NODE_V8_COVERAGE ? FakeFinalizationRegistry : global.FinalizationRegistry || FakeFinalizationRegistry\nconst WeakRef = process.env.NODE_V8_COVERAGE ? FakeWeakRef : global.WeakRef || FakeWeakRef\n\nconst registry = new FinalizationRegistry((worker) => {\n if (worker.exited) {\n return\n }\n worker.terminate()\n})\n\nfunction createWorker (stream, opts) {\n const { filename, workerData } = opts\n\n const bundlerOverrides = '__bundlerPathsOverrides' in globalThis ? globalThis.__bundlerPathsOverrides : {}\n const toExecute = bundlerOverrides['thread-stream-worker'] || join(__dirname, 'lib', 'worker.js')\n\n const worker = new Worker(toExecute, {\n ...opts.workerOpts,\n trackUnmanagedFds: false,\n workerData: {\n filename: filename.indexOf('file://') === 0\n ? filename\n : pathToFileURL(filename).href,\n dataBuf: stream[kImpl].dataBuf,\n stateBuf: stream[kImpl].stateBuf,\n workerData: {\n $context: {\n threadStreamVersion: version\n },\n ...workerData\n }\n }\n })\n\n // We keep a strong reference for now,\n // we need to start writing first\n worker.stream = new FakeWeakRef(stream)\n\n worker.on('message', onWorkerMessage)\n worker.on('exit', onWorkerExit)\n registry.register(stream, worker)\n\n return worker\n}\n\nfunction drain (stream) {\n assert(!stream[kImpl].sync)\n if (stream[kImpl].needDrain) {\n stream[kImpl].needDrain = false\n stream.emit('drain')\n }\n}\n\nfunction nextFlush (stream) {\n const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n let leftover = stream[kImpl].data.length - writeIndex\n\n if (leftover > 0) {\n if (stream[kImpl].buf.length === 0) {\n stream[kImpl].flushing = false\n\n if (stream[kImpl].ending) {\n end(stream)\n } else if (stream[kImpl].needDrain) {\n process.nextTick(drain, stream)\n }\n\n return\n }\n\n let toWrite = stream[kImpl].buf.slice(0, leftover)\n let toWriteBytes = Buffer.byteLength(toWrite)\n if (toWriteBytes <= leftover) {\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n // process._rawDebug('writing ' + toWrite.length)\n write(stream, toWrite, nextFlush.bind(null, stream))\n } else {\n // multi-byte utf-8\n stream.flush(() => {\n // err is already handled in flush()\n if (stream.destroyed) {\n return\n }\n\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n\n // Find a toWrite length that fits the buffer\n // it must exists as the buffer is at least 4 bytes length\n // and the max utf-8 length for a char is 4 bytes.\n while (toWriteBytes > stream[kImpl].data.length) {\n leftover = leftover / 2\n toWrite = stream[kImpl].buf.slice(0, leftover)\n toWriteBytes = Buffer.byteLength(toWrite)\n }\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n write(stream, toWrite, nextFlush.bind(null, stream))\n })\n }\n } else if (leftover === 0) {\n if (writeIndex === 0 && stream[kImpl].buf.length === 0) {\n // we had a flushSync in the meanwhile\n return\n }\n stream.flush(() => {\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n nextFlush(stream)\n })\n } else {\n // This should never happen\n destroy(stream, new Error('overwritten'))\n }\n}\n\nfunction onWorkerMessage (msg) {\n const stream = this.stream.deref()\n if (stream === undefined) {\n this.exited = true\n // Terminate the worker.\n this.terminate()\n return\n }\n\n switch (msg.code) {\n case 'READY':\n // Replace the FakeWeakRef with a\n // proper one.\n this.stream = new WeakRef(stream)\n\n stream.flush(() => {\n stream[kImpl].ready = true\n stream.emit('ready')\n })\n break\n case 'ERROR':\n destroy(stream, msg.err)\n break\n case 'EVENT':\n if (Array.isArray(msg.args)) {\n stream.emit(msg.name, ...msg.args)\n } else {\n stream.emit(msg.name, msg.args)\n }\n break\n case 'WARNING':\n process.emitWarning(msg.err)\n break\n default:\n destroy(stream, new Error('this should not happen: ' + msg.code))\n }\n}\n\nfunction onWorkerExit (code) {\n const stream = this.stream.deref()\n if (stream === undefined) {\n // Nothing to do, the worker already exit\n return\n }\n registry.unregister(stream)\n stream.worker.exited = true\n stream.worker.off('exit', onWorkerExit)\n destroy(stream, code !== 0 ? new Error('the worker thread exited') : null)\n}\n\nclass ThreadStream extends EventEmitter {\n constructor (opts = {}) {\n super()\n\n if (opts.bufferSize < 4) {\n throw new Error('bufferSize must at least fit a 4-byte utf-8 char')\n }\n\n this[kImpl] = {}\n this[kImpl].stateBuf = new SharedArrayBuffer(128)\n this[kImpl].state = new Int32Array(this[kImpl].stateBuf)\n this[kImpl].dataBuf = new SharedArrayBuffer(opts.bufferSize || 4 * 1024 * 1024)\n this[kImpl].data = Buffer.from(this[kImpl].dataBuf)\n this[kImpl].sync = opts.sync || false\n this[kImpl].ending = false\n this[kImpl].ended = false\n this[kImpl].needDrain = false\n this[kImpl].destroyed = false\n this[kImpl].flushing = false\n this[kImpl].ready = false\n this[kImpl].finished = false\n this[kImpl].errored = null\n this[kImpl].closed = false\n this[kImpl].buf = ''\n\n // TODO (fix): Make private?\n this.worker = createWorker(this, opts) // TODO (fix): make private\n this.on('message', (message, transferList) => {\n this.worker.postMessage(message, transferList)\n })\n }\n\n write (data) {\n if (this[kImpl].destroyed) {\n error(this, new Error('the worker has exited'))\n return false\n }\n\n if (this[kImpl].ending) {\n error(this, new Error('the worker is ending'))\n return false\n }\n\n if (this[kImpl].flushing && this[kImpl].buf.length + data.length >= MAX_STRING) {\n try {\n writeSync(this)\n this[kImpl].flushing = true\n } catch (err) {\n destroy(this, err)\n return false\n }\n }\n\n this[kImpl].buf += data\n\n if (this[kImpl].sync) {\n try {\n writeSync(this)\n return true\n } catch (err) {\n destroy(this, err)\n return false\n }\n }\n\n if (!this[kImpl].flushing) {\n this[kImpl].flushing = true\n setImmediate(nextFlush, this)\n }\n\n this[kImpl].needDrain = this[kImpl].data.length - this[kImpl].buf.length - Atomics.load(this[kImpl].state, WRITE_INDEX) <= 0\n return !this[kImpl].needDrain\n }\n\n end () {\n if (this[kImpl].destroyed) {\n return\n }\n\n this[kImpl].ending = true\n end(this)\n }\n\n flush (cb) {\n if (this[kImpl].destroyed) {\n if (typeof cb === 'function') {\n process.nextTick(cb, new Error('the worker has exited'))\n }\n return\n }\n\n // TODO write all .buf\n const writeIndex = Atomics.load(this[kImpl].state, WRITE_INDEX)\n // process._rawDebug(`(flush) readIndex (${Atomics.load(this.state, READ_INDEX)}) writeIndex (${Atomics.load(this.state, WRITE_INDEX)})`)\n wait(this[kImpl].state, READ_INDEX, writeIndex, Infinity, (err, res) => {\n if (err) {\n destroy(this, err)\n process.nextTick(cb, err)\n return\n }\n if (res === 'not-equal') {\n // TODO handle deadlock\n this.flush(cb)\n return\n }\n process.nextTick(cb)\n })\n }\n\n flushSync () {\n if (this[kImpl].destroyed) {\n return\n }\n\n writeSync(this)\n flushSync(this)\n }\n\n unref () {\n this.worker.unref()\n }\n\n ref () {\n this.worker.ref()\n }\n\n get ready () {\n return this[kImpl].ready\n }\n\n get destroyed () {\n return this[kImpl].destroyed\n }\n\n get closed () {\n return this[kImpl].closed\n }\n\n get writable () {\n return !this[kImpl].destroyed && !this[kImpl].ending\n }\n\n get writableEnded () {\n return this[kImpl].ending\n }\n\n get writableFinished () {\n return this[kImpl].finished\n }\n\n get writableNeedDrain () {\n return this[kImpl].needDrain\n }\n\n get writableObjectMode () {\n return false\n }\n\n get writableErrored () {\n return this[kImpl].errored\n }\n}\n\nfunction error (stream, err) {\n setImmediate(() => {\n stream.emit('error', err)\n })\n}\n\nfunction destroy (stream, err) {\n if (stream[kImpl].destroyed) {\n return\n }\n stream[kImpl].destroyed = true\n\n if (err) {\n stream[kImpl].errored = err\n error(stream, err)\n }\n\n if (!stream.worker.exited) {\n stream.worker.terminate()\n .catch(() => {})\n .then(() => {\n stream[kImpl].closed = true\n stream.emit('close')\n })\n } else {\n setImmediate(() => {\n stream[kImpl].closed = true\n stream.emit('close')\n })\n }\n}\n\nfunction write (stream, data, cb) {\n // data is smaller than the shared buffer length\n const current = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n const length = Buffer.byteLength(data)\n stream[kImpl].data.write(data, current)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, current + length)\n Atomics.notify(stream[kImpl].state, WRITE_INDEX)\n cb()\n return true\n}\n\nfunction end (stream) {\n if (stream[kImpl].ended || !stream[kImpl].ending || stream[kImpl].flushing) {\n return\n }\n stream[kImpl].ended = true\n\n try {\n stream.flushSync()\n\n let readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n // process._rawDebug('writing index')\n Atomics.store(stream[kImpl].state, WRITE_INDEX, -1)\n // process._rawDebug(`(end) readIndex (${Atomics.load(stream.state, READ_INDEX)}) writeIndex (${Atomics.load(stream.state, WRITE_INDEX)})`)\n Atomics.notify(stream[kImpl].state, WRITE_INDEX)\n\n // Wait for the process to complete\n let spins = 0\n while (readIndex !== -1) {\n // process._rawDebug(`read = ${read}`)\n Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000)\n readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n if (readIndex === -2) {\n destroy(stream, new Error('end() failed'))\n return\n }\n\n if (++spins === 10) {\n destroy(stream, new Error('end() took too long (10s)'))\n return\n }\n }\n\n process.nextTick(() => {\n stream[kImpl].finished = true\n stream.emit('finish')\n })\n } catch (err) {\n destroy(stream, err)\n }\n // process._rawDebug('end finished...')\n}\n\nfunction writeSync (stream) {\n const cb = () => {\n if (stream[kImpl].ending) {\n end(stream)\n } else if (stream[kImpl].needDrain) {\n process.nextTick(drain, stream)\n }\n }\n stream[kImpl].flushing = false\n\n while (stream[kImpl].buf.length !== 0) {\n const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n let leftover = stream[kImpl].data.length - writeIndex\n if (leftover === 0) {\n flushSync(stream)\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n continue\n } else if (leftover < 0) {\n // stream should never happen\n throw new Error('overwritten')\n }\n\n let toWrite = stream[kImpl].buf.slice(0, leftover)\n let toWriteBytes = Buffer.byteLength(toWrite)\n if (toWriteBytes <= leftover) {\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n // process._rawDebug('writing ' + toWrite.length)\n write(stream, toWrite, cb)\n } else {\n // multi-byte utf-8\n flushSync(stream)\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n\n // Find a toWrite length that fits the buffer\n // it must exists as the buffer is at least 4 bytes length\n // and the max utf-8 length for a char is 4 bytes.\n while (toWriteBytes > stream[kImpl].buf.length) {\n leftover = leftover / 2\n toWrite = stream[kImpl].buf.slice(0, leftover)\n toWriteBytes = Buffer.byteLength(toWrite)\n }\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n write(stream, toWrite, cb)\n }\n }\n}\n\nfunction flushSync (stream) {\n if (stream[kImpl].flushing) {\n throw new Error('unable to flush while flushing')\n }\n\n // process._rawDebug('flushSync started')\n\n const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n\n let spins = 0\n\n // TODO handle deadlock\n while (true) {\n const readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n if (readIndex === -2) {\n throw Error('_flushSync failed')\n }\n\n // process._rawDebug(`(flushSync) readIndex (${readIndex}) writeIndex (${writeIndex})`)\n if (readIndex !== writeIndex) {\n // TODO stream timeouts for some reason.\n Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000)\n } else {\n break\n }\n\n if (++spins === 10) {\n throw new Error('_flushSync took too long (10s)')\n }\n }\n // process._rawDebug('flushSync finished')\n}\n\nmodule.exports = ThreadStream\n", "'use strict'\n\nconst { createRequire } = require('module')\nconst getCallers = require('./caller')\nconst { join, isAbsolute, sep } = require('node:path')\nconst sleep = require('atomic-sleep')\nconst onExit = require('on-exit-leak-free')\nconst ThreadStream = require('thread-stream')\n\nfunction setupOnExit (stream) {\n // This is leak free, it does not leave event handlers\n onExit.register(stream, autoEnd)\n onExit.registerBeforeExit(stream, flush)\n\n stream.on('close', function () {\n onExit.unregister(stream)\n })\n}\n\nfunction buildStream (filename, workerData, workerOpts, sync) {\n const stream = new ThreadStream({\n filename,\n workerData,\n workerOpts,\n sync\n })\n\n stream.on('ready', onReady)\n stream.on('close', function () {\n process.removeListener('exit', onExit)\n })\n\n process.on('exit', onExit)\n\n function onReady () {\n process.removeListener('exit', onExit)\n stream.unref()\n\n if (workerOpts.autoEnd !== false) {\n setupOnExit(stream)\n }\n }\n\n function onExit () {\n /* istanbul ignore next */\n if (stream.closed) {\n return\n }\n stream.flushSync()\n // Apparently there is a very sporadic race condition\n // that in certain OS would prevent the messages to be flushed\n // because the thread might not have been created still.\n // Unfortunately we need to sleep(100) in this case.\n sleep(100)\n stream.end()\n }\n\n return stream\n}\n\nfunction autoEnd (stream) {\n stream.ref()\n stream.flushSync()\n stream.end()\n stream.once('close', function () {\n stream.unref()\n })\n}\n\nfunction flush (stream) {\n stream.flushSync()\n}\n\nfunction transport (fullOptions) {\n const { pipeline, targets, levels, dedupe, worker = {}, caller = getCallers(), sync = false } = fullOptions\n\n const options = {\n ...fullOptions.options\n }\n\n // Backwards compatibility\n const callers = typeof caller === 'string' ? [caller] : caller\n\n // This will be eventually modified by bundlers\n const bundlerOverrides = '__bundlerPathsOverrides' in globalThis ? globalThis.__bundlerPathsOverrides : {}\n\n let target = fullOptions.target\n\n if (target && targets) {\n throw new Error('only one of target or targets can be specified')\n }\n\n if (targets) {\n target = bundlerOverrides['pino-worker'] || join(__dirname, 'worker.js')\n options.targets = targets.filter(dest => dest.target).map((dest) => {\n return {\n ...dest,\n target: fixTarget(dest.target)\n }\n })\n options.pipelines = targets.filter(dest => dest.pipeline).map((dest) => {\n return dest.pipeline.map((t) => {\n return {\n ...t,\n level: dest.level, // duplicate the pipeline `level` property defined in the upper level\n target: fixTarget(t.target)\n }\n })\n })\n } else if (pipeline) {\n target = bundlerOverrides['pino-worker'] || join(__dirname, 'worker.js')\n options.pipelines = [pipeline.map((dest) => {\n return {\n ...dest,\n target: fixTarget(dest.target)\n }\n })]\n }\n\n if (levels) {\n options.levels = levels\n }\n\n if (dedupe) {\n options.dedupe = dedupe\n }\n\n options.pinoWillSendConfig = true\n\n return buildStream(fixTarget(target), options, worker, sync)\n\n function fixTarget (origin) {\n origin = bundlerOverrides[origin] || origin\n\n if (isAbsolute(origin) || origin.indexOf('file://') === 0) {\n return origin\n }\n\n if (origin === 'pino/file') {\n return join(__dirname, '..', 'file.js')\n }\n\n let fixTarget\n\n for (const filePath of callers) {\n try {\n const context = filePath === 'node:repl'\n ? process.cwd() + sep\n : filePath\n\n fixTarget = createRequire(context).resolve(origin)\n break\n } catch (err) {\n // Silent catch\n continue\n }\n }\n\n if (!fixTarget) {\n throw new Error(`unable to determine transport target for \"${origin}\"`)\n }\n\n return fixTarget\n }\n}\n\nmodule.exports = transport\n", "'use strict'\n\n/* eslint no-prototype-builtins: 0 */\n\nconst format = require('quick-format-unescaped')\nconst { mapHttpRequest, mapHttpResponse } = require('pino-std-serializers')\nconst SonicBoom = require('sonic-boom')\nconst onExit = require('on-exit-leak-free')\nconst {\n lsCacheSym,\n chindingsSym,\n writeSym,\n serializersSym,\n formatOptsSym,\n endSym,\n stringifiersSym,\n stringifySym,\n stringifySafeSym,\n wildcardFirstSym,\n nestedKeySym,\n formattersSym,\n messageKeySym,\n errorKeySym,\n nestedKeyStrSym,\n msgPrefixSym\n} = require('./symbols')\nconst { isMainThread } = require('worker_threads')\nconst transport = require('./transport')\n\nfunction noop () {\n}\n\nfunction genLog (level, hook) {\n if (!hook) return LOG\n\n return function hookWrappedLog (...args) {\n hook.call(this, args, LOG, level)\n }\n\n function LOG (o, ...n) {\n if (typeof o === 'object') {\n let msg = o\n if (o !== null) {\n if (o.method && o.headers && o.socket) {\n o = mapHttpRequest(o)\n } else if (typeof o.setHeader === 'function') {\n o = mapHttpResponse(o)\n }\n }\n let formatParams\n if (msg === null && n.length === 0) {\n formatParams = [null]\n } else {\n msg = n.shift()\n formatParams = n\n }\n // We do not use a coercive check for `msg` as it is\n // measurably slower than the explicit checks.\n if (typeof this[msgPrefixSym] === 'string' && msg !== undefined && msg !== null) {\n msg = this[msgPrefixSym] + msg\n }\n this[writeSym](o, format(msg, formatParams, this[formatOptsSym]), level)\n } else {\n let msg = o === undefined ? n.shift() : o\n\n // We do not use a coercive check for `msg` as it is\n // measurably slower than the explicit checks.\n if (typeof this[msgPrefixSym] === 'string' && msg !== undefined && msg !== null) {\n msg = this[msgPrefixSym] + msg\n }\n this[writeSym](null, format(msg, n, this[formatOptsSym]), level)\n }\n }\n}\n\n// magically escape strings for json\n// relying on their charCodeAt\n// everything below 32 needs JSON.stringify()\n// 34 and 92 happens all the time, so we\n// have a fast case for them\nfunction asString (str) {\n let result = ''\n let last = 0\n let found = false\n let point = 255\n const l = str.length\n if (l > 100) {\n return JSON.stringify(str)\n }\n for (var i = 0; i < l && point >= 32; i++) {\n point = str.charCodeAt(i)\n if (point === 34 || point === 92) {\n result += str.slice(last, i) + '\\\\'\n last = i\n found = true\n }\n }\n if (!found) {\n result = str\n } else {\n result += str.slice(last)\n }\n return point < 32 ? JSON.stringify(str) : '\"' + result + '\"'\n}\n\nfunction asJson (obj, msg, num, time) {\n const stringify = this[stringifySym]\n const stringifySafe = this[stringifySafeSym]\n const stringifiers = this[stringifiersSym]\n const end = this[endSym]\n const chindings = this[chindingsSym]\n const serializers = this[serializersSym]\n const formatters = this[formattersSym]\n const messageKey = this[messageKeySym]\n const errorKey = this[errorKeySym]\n let data = this[lsCacheSym][num] + time\n\n // we need the child bindings added to the output first so instance logged\n // objects can take precedence when JSON.parse-ing the resulting log line\n data = data + chindings\n\n let value\n if (formatters.log) {\n obj = formatters.log(obj)\n }\n const wildcardStringifier = stringifiers[wildcardFirstSym]\n let propStr = ''\n for (const key in obj) {\n value = obj[key]\n if (Object.prototype.hasOwnProperty.call(obj, key) && value !== undefined) {\n if (serializers[key]) {\n value = serializers[key](value)\n } else if (key === errorKey && serializers.err) {\n value = serializers.err(value)\n }\n\n const stringifier = stringifiers[key] || wildcardStringifier\n\n switch (typeof value) {\n case 'undefined':\n case 'function':\n continue\n case 'number':\n /* eslint no-fallthrough: \"off\" */\n if (Number.isFinite(value) === false) {\n value = null\n }\n // this case explicitly falls through to the next one\n case 'boolean':\n if (stringifier) value = stringifier(value)\n break\n case 'string':\n value = (stringifier || asString)(value)\n break\n default:\n value = (stringifier || stringify)(value, stringifySafe)\n }\n if (value === undefined) continue\n const strKey = asString(key)\n propStr += ',' + strKey + ':' + value\n }\n }\n\n let msgStr = ''\n if (msg !== undefined) {\n value = serializers[messageKey] ? serializers[messageKey](msg) : msg\n const stringifier = stringifiers[messageKey] || wildcardStringifier\n\n switch (typeof value) {\n case 'function':\n break\n case 'number':\n /* eslint no-fallthrough: \"off\" */\n if (Number.isFinite(value) === false) {\n value = null\n }\n // this case explicitly falls through to the next one\n case 'boolean':\n if (stringifier) value = stringifier(value)\n msgStr = ',\"' + messageKey + '\":' + value\n break\n case 'string':\n value = (stringifier || asString)(value)\n msgStr = ',\"' + messageKey + '\":' + value\n break\n default:\n value = (stringifier || stringify)(value, stringifySafe)\n msgStr = ',\"' + messageKey + '\":' + value\n }\n }\n\n if (this[nestedKeySym] && propStr) {\n // place all the obj properties under the specified key\n // the nested key is already formatted from the constructor\n return data + this[nestedKeyStrSym] + propStr.slice(1) + '}' + msgStr + end\n } else {\n return data + propStr + msgStr + end\n }\n}\n\nfunction asChindings (instance, bindings) {\n let value\n let data = instance[chindingsSym]\n const stringify = instance[stringifySym]\n const stringifySafe = instance[stringifySafeSym]\n const stringifiers = instance[stringifiersSym]\n const wildcardStringifier = stringifiers[wildcardFirstSym]\n const serializers = instance[serializersSym]\n const formatter = instance[formattersSym].bindings\n bindings = formatter(bindings)\n\n for (const key in bindings) {\n value = bindings[key]\n const valid = key !== 'level' &&\n key !== 'serializers' &&\n key !== 'formatters' &&\n key !== 'customLevels' &&\n bindings.hasOwnProperty(key) &&\n value !== undefined\n if (valid === true) {\n value = serializers[key] ? serializers[key](value) : value\n value = (stringifiers[key] || wildcardStringifier || stringify)(value, stringifySafe)\n if (value === undefined) continue\n data += ',\"' + key + '\":' + value\n }\n }\n return data\n}\n\nfunction hasBeenTampered (stream) {\n return stream.write !== stream.constructor.prototype.write\n}\n\nfunction buildSafeSonicBoom (opts) {\n const stream = new SonicBoom(opts)\n stream.on('error', filterBrokenPipe)\n // If we are sync: false, we must flush on exit\n if (!opts.sync && isMainThread) {\n onExit.register(stream, autoEnd)\n\n stream.on('close', function () {\n onExit.unregister(stream)\n })\n }\n return stream\n\n function filterBrokenPipe (err) {\n // Impossible to replicate across all operating systems\n /* istanbul ignore next */\n if (err.code === 'EPIPE') {\n // If we get EPIPE, we should stop logging here\n // however we have no control to the consumer of\n // SonicBoom, so we just overwrite the write method\n stream.write = noop\n stream.end = noop\n stream.flushSync = noop\n stream.destroy = noop\n return\n }\n stream.removeListener('error', filterBrokenPipe)\n stream.emit('error', err)\n }\n}\n\nfunction autoEnd (stream, eventName) {\n // This check is needed only on some platforms\n /* istanbul ignore next */\n if (stream.destroyed) {\n return\n }\n\n if (eventName === 'beforeExit') {\n // We still have an event loop, let's use it\n stream.flush()\n stream.on('drain', function () {\n stream.end()\n })\n } else {\n // For some reason istanbul is not detecting this, but it's there\n /* istanbul ignore next */\n // We do not have an event loop, so flush synchronously\n stream.flushSync()\n }\n}\n\nfunction createArgsNormalizer (defaultOptions) {\n return function normalizeArgs (instance, caller, opts = {}, stream) {\n // support stream as a string\n if (typeof opts === 'string') {\n stream = buildSafeSonicBoom({ dest: opts })\n opts = {}\n } else if (typeof stream === 'string') {\n if (opts && opts.transport) {\n throw Error('only one of option.transport or stream can be specified')\n }\n stream = buildSafeSonicBoom({ dest: stream })\n } else if (opts instanceof SonicBoom || opts.writable || opts._writableState) {\n stream = opts\n opts = {}\n } else if (opts.transport) {\n if (opts.transport instanceof SonicBoom || opts.transport.writable || opts.transport._writableState) {\n throw Error('option.transport do not allow stream, please pass to option directly. e.g. pino(transport)')\n }\n if (opts.transport.targets && opts.transport.targets.length && opts.formatters && typeof opts.formatters.level === 'function') {\n throw Error('option.transport.targets do not allow custom level formatters')\n }\n\n let customLevels\n if (opts.customLevels) {\n customLevels = opts.useOnlyCustomLevels ? opts.customLevels : Object.assign({}, opts.levels, opts.customLevels)\n }\n stream = transport({ caller, ...opts.transport, levels: customLevels })\n }\n opts = Object.assign({}, defaultOptions, opts)\n opts.serializers = Object.assign({}, defaultOptions.serializers, opts.serializers)\n opts.formatters = Object.assign({}, defaultOptions.formatters, opts.formatters)\n\n if (opts.prettyPrint) {\n throw new Error('prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)')\n }\n\n const { enabled, onChild } = opts\n if (enabled === false) opts.level = 'silent'\n if (!onChild) opts.onChild = noop\n if (!stream) {\n if (!hasBeenTampered(process.stdout)) {\n // If process.stdout.fd is undefined, it means that we are running\n // in a worker thread. Let's assume we are logging to file descriptor 1.\n stream = buildSafeSonicBoom({ fd: process.stdout.fd || 1 })\n } else {\n stream = process.stdout\n }\n }\n return { opts, stream }\n }\n}\n\nfunction stringify (obj, stringifySafeFn) {\n try {\n return JSON.stringify(obj)\n } catch (_) {\n try {\n const stringify = stringifySafeFn || this[stringifySafeSym]\n return stringify(obj)\n } catch (_) {\n return '\"[unable to serialize, circular reference is too complex to analyze]\"'\n }\n }\n}\n\nfunction buildFormatters (level, bindings, log) {\n return {\n level,\n bindings,\n log\n }\n}\n\n/**\n * Convert a string integer file descriptor to a proper native integer\n * file descriptor.\n *\n * @param {string} destination The file descriptor string to attempt to convert.\n *\n * @returns {Number}\n */\nfunction normalizeDestFileDescriptor (destination) {\n const fd = Number(destination)\n if (typeof destination === 'string' && Number.isFinite(fd)) {\n return fd\n }\n // destination could be undefined if we are in a worker\n if (destination === undefined) {\n // This is stdout in UNIX systems\n return 1\n }\n return destination\n}\n\nmodule.exports = {\n noop,\n buildSafeSonicBoom,\n asChindings,\n asJson,\n genLog,\n createArgsNormalizer,\n stringify,\n buildFormatters,\n normalizeDestFileDescriptor\n}\n", "/**\n * Represents default log level values\n *\n * @enum {number}\n */\nconst DEFAULT_LEVELS = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60\n}\n\n/**\n * Represents sort order direction: `ascending` or `descending`\n *\n * @enum {string}\n */\nconst SORTING_ORDER = {\n ASC: 'ASC',\n DESC: 'DESC'\n}\n\nmodule.exports = {\n DEFAULT_LEVELS,\n SORTING_ORDER\n}\n", "'use strict'\n/* eslint no-prototype-builtins: 0 */\nconst {\n lsCacheSym,\n levelValSym,\n useOnlyCustomLevelsSym,\n streamSym,\n formattersSym,\n hooksSym,\n levelCompSym\n} = require('./symbols')\nconst { noop, genLog } = require('./tools')\nconst { DEFAULT_LEVELS, SORTING_ORDER } = require('./constants')\n\nconst levelMethods = {\n fatal: (hook) => {\n const logFatal = genLog(DEFAULT_LEVELS.fatal, hook)\n return function (...args) {\n const stream = this[streamSym]\n logFatal.call(this, ...args)\n if (typeof stream.flushSync === 'function') {\n try {\n stream.flushSync()\n } catch (e) {\n // https://github.com/pinojs/pino/pull/740#discussion_r346788313\n }\n }\n }\n },\n error: (hook) => genLog(DEFAULT_LEVELS.error, hook),\n warn: (hook) => genLog(DEFAULT_LEVELS.warn, hook),\n info: (hook) => genLog(DEFAULT_LEVELS.info, hook),\n debug: (hook) => genLog(DEFAULT_LEVELS.debug, hook),\n trace: (hook) => genLog(DEFAULT_LEVELS.trace, hook)\n}\n\nconst nums = Object.keys(DEFAULT_LEVELS).reduce((o, k) => {\n o[DEFAULT_LEVELS[k]] = k\n return o\n}, {})\n\nconst initialLsCache = Object.keys(nums).reduce((o, k) => {\n o[k] = '{\"level\":' + Number(k)\n return o\n}, {})\n\nfunction genLsCache (instance) {\n const formatter = instance[formattersSym].level\n const { labels } = instance.levels\n const cache = {}\n for (const label in labels) {\n const level = formatter(labels[label], Number(label))\n cache[label] = JSON.stringify(level).slice(0, -1)\n }\n instance[lsCacheSym] = cache\n return instance\n}\n\nfunction isStandardLevel (level, useOnlyCustomLevels) {\n if (useOnlyCustomLevels) {\n return false\n }\n\n switch (level) {\n case 'fatal':\n case 'error':\n case 'warn':\n case 'info':\n case 'debug':\n case 'trace':\n return true\n default:\n return false\n }\n}\n\nfunction setLevel (level) {\n const { labels, values } = this.levels\n if (typeof level === 'number') {\n if (labels[level] === undefined) throw Error('unknown level value' + level)\n level = labels[level]\n }\n if (values[level] === undefined) throw Error('unknown level ' + level)\n const preLevelVal = this[levelValSym]\n const levelVal = this[levelValSym] = values[level]\n const useOnlyCustomLevelsVal = this[useOnlyCustomLevelsSym]\n const levelComparison = this[levelCompSym]\n const hook = this[hooksSym].logMethod\n\n for (const key in values) {\n if (levelComparison(values[key], levelVal) === false) {\n this[key] = noop\n continue\n }\n this[key] = isStandardLevel(key, useOnlyCustomLevelsVal) ? levelMethods[key](hook) : genLog(values[key], hook)\n }\n\n this.emit(\n 'level-change',\n level,\n levelVal,\n labels[preLevelVal],\n preLevelVal,\n this\n )\n}\n\nfunction getLevel (level) {\n const { levels, levelVal } = this\n // protection against potential loss of Pino scope from serializers (edge case with circular refs - https://github.com/pinojs/pino/issues/833)\n return (levels && levels.labels) ? levels.labels[levelVal] : ''\n}\n\nfunction isLevelEnabled (logLevel) {\n const { values } = this.levels\n const logLevelVal = values[logLevel]\n return logLevelVal !== undefined && this[levelCompSym](logLevelVal, this[levelValSym])\n}\n\n/**\n * Determine if the given `current` level is enabled by comparing it\n * against the current threshold (`expected`).\n *\n * @param {SORTING_ORDER} direction comparison direction \"ASC\" or \"DESC\"\n * @param {number} current current log level number representation\n * @param {number} expected threshold value to compare with\n * @returns {boolean}\n */\nfunction compareLevel (direction, current, expected) {\n if (direction === SORTING_ORDER.DESC) {\n return current <= expected\n }\n\n return current >= expected\n}\n\n/**\n * Create a level comparison function based on `levelComparison`\n * it could a default function which compares levels either in \"ascending\" or \"descending\" order or custom comparison function\n *\n * @param {SORTING_ORDER | Function} levelComparison sort levels order direction or custom comparison function\n * @returns Function\n */\nfunction genLevelComparison (levelComparison) {\n if (typeof levelComparison === 'string') {\n return compareLevel.bind(null, levelComparison)\n }\n\n return levelComparison\n}\n\nfunction mappings (customLevels = null, useOnlyCustomLevels = false) {\n const customNums = customLevels\n /* eslint-disable */\n ? Object.keys(customLevels).reduce((o, k) => {\n o[customLevels[k]] = k\n return o\n }, {})\n : null\n /* eslint-enable */\n\n const labels = Object.assign(\n Object.create(Object.prototype, { Infinity: { value: 'silent' } }),\n useOnlyCustomLevels ? null : nums,\n customNums\n )\n const values = Object.assign(\n Object.create(Object.prototype, { silent: { value: Infinity } }),\n useOnlyCustomLevels ? null : DEFAULT_LEVELS,\n customLevels\n )\n return { labels, values }\n}\n\nfunction assertDefaultLevelFound (defaultLevel, customLevels, useOnlyCustomLevels) {\n if (typeof defaultLevel === 'number') {\n const values = [].concat(\n Object.keys(customLevels || {}).map(key => customLevels[key]),\n useOnlyCustomLevels ? [] : Object.keys(nums).map(level => +level),\n Infinity\n )\n if (!values.includes(defaultLevel)) {\n throw Error(`default level:${defaultLevel} must be included in custom levels`)\n }\n return\n }\n\n const labels = Object.assign(\n Object.create(Object.prototype, { silent: { value: Infinity } }),\n useOnlyCustomLevels ? null : DEFAULT_LEVELS,\n customLevels\n )\n if (!(defaultLevel in labels)) {\n throw Error(`default level:${defaultLevel} must be included in custom levels`)\n }\n}\n\nfunction assertNoLevelCollisions (levels, customLevels) {\n const { labels, values } = levels\n for (const k in customLevels) {\n if (k in values) {\n throw Error('levels cannot be overridden')\n }\n if (customLevels[k] in labels) {\n throw Error('pre-existing level values cannot be used for new levels')\n }\n }\n}\n\n/**\n * Validates whether `levelComparison` is correct\n *\n * @throws Error\n * @param {SORTING_ORDER | Function} levelComparison - value to validate\n * @returns\n */\nfunction assertLevelComparison (levelComparison) {\n if (typeof levelComparison === 'function') {\n return\n }\n\n if (typeof levelComparison === 'string' && Object.values(SORTING_ORDER).includes(levelComparison)) {\n return\n }\n\n throw new Error('Levels comparison should be one of \"ASC\", \"DESC\" or \"function\" type')\n}\n\nmodule.exports = {\n initialLsCache,\n genLsCache,\n levelMethods,\n getLevel,\n setLevel,\n isLevelEnabled,\n mappings,\n assertNoLevelCollisions,\n assertDefaultLevelFound,\n genLevelComparison,\n assertLevelComparison\n}\n", "'use strict'\n\nmodule.exports = { version: '9.7.0' }\n", "'use strict'\n\n/* eslint no-prototype-builtins: 0 */\n\nconst { EventEmitter } = require('node:events')\nconst {\n lsCacheSym,\n levelValSym,\n setLevelSym,\n getLevelSym,\n chindingsSym,\n parsedChindingsSym,\n mixinSym,\n asJsonSym,\n writeSym,\n mixinMergeStrategySym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n serializersSym,\n formattersSym,\n errorKeySym,\n messageKeySym,\n useOnlyCustomLevelsSym,\n needsMetadataGsym,\n redactFmtSym,\n stringifySym,\n formatOptsSym,\n stringifiersSym,\n msgPrefixSym,\n hooksSym\n} = require('./symbols')\nconst {\n getLevel,\n setLevel,\n isLevelEnabled,\n mappings,\n initialLsCache,\n genLsCache,\n assertNoLevelCollisions\n} = require('./levels')\nconst {\n asChindings,\n asJson,\n buildFormatters,\n stringify\n} = require('./tools')\nconst {\n version\n} = require('./meta')\nconst redaction = require('./redaction')\n\n// note: use of class is satirical\n// https://github.com/pinojs/pino/pull/433#pullrequestreview-127703127\nconst constructor = class Pino {}\nconst prototype = {\n constructor,\n child,\n bindings,\n setBindings,\n flush,\n isLevelEnabled,\n version,\n get level () { return this[getLevelSym]() },\n set level (lvl) { this[setLevelSym](lvl) },\n get levelVal () { return this[levelValSym] },\n set levelVal (n) { throw Error('levelVal is read-only') },\n [lsCacheSym]: initialLsCache,\n [writeSym]: write,\n [asJsonSym]: asJson,\n [getLevelSym]: getLevel,\n [setLevelSym]: setLevel\n}\n\nObject.setPrototypeOf(prototype, EventEmitter.prototype)\n\n// exporting and consuming the prototype object using factory pattern fixes scoping issues with getters when serializing\nmodule.exports = function () {\n return Object.create(prototype)\n}\n\nconst resetChildingsFormatter = bindings => bindings\nfunction child (bindings, options) {\n if (!bindings) {\n throw Error('missing bindings for child Pino')\n }\n options = options || {} // default options to empty object\n const serializers = this[serializersSym]\n const formatters = this[formattersSym]\n const instance = Object.create(this)\n\n if (options.hasOwnProperty('serializers') === true) {\n instance[serializersSym] = Object.create(null)\n\n for (const k in serializers) {\n instance[serializersSym][k] = serializers[k]\n }\n const parentSymbols = Object.getOwnPropertySymbols(serializers)\n /* eslint no-var: off */\n for (var i = 0; i < parentSymbols.length; i++) {\n const ks = parentSymbols[i]\n instance[serializersSym][ks] = serializers[ks]\n }\n\n for (const bk in options.serializers) {\n instance[serializersSym][bk] = options.serializers[bk]\n }\n const bindingsSymbols = Object.getOwnPropertySymbols(options.serializers)\n for (var bi = 0; bi < bindingsSymbols.length; bi++) {\n const bks = bindingsSymbols[bi]\n instance[serializersSym][bks] = options.serializers[bks]\n }\n } else instance[serializersSym] = serializers\n if (options.hasOwnProperty('formatters')) {\n const { level, bindings: chindings, log } = options.formatters\n instance[formattersSym] = buildFormatters(\n level || formatters.level,\n chindings || resetChildingsFormatter,\n log || formatters.log\n )\n } else {\n instance[formattersSym] = buildFormatters(\n formatters.level,\n resetChildingsFormatter,\n formatters.log\n )\n }\n if (options.hasOwnProperty('customLevels') === true) {\n assertNoLevelCollisions(this.levels, options.customLevels)\n instance.levels = mappings(options.customLevels, instance[useOnlyCustomLevelsSym])\n genLsCache(instance)\n }\n\n // redact must place before asChindings and only replace if exist\n if ((typeof options.redact === 'object' && options.redact !== null) || Array.isArray(options.redact)) {\n instance.redact = options.redact // replace redact directly\n const stringifiers = redaction(instance.redact, stringify)\n const formatOpts = { stringify: stringifiers[redactFmtSym] }\n instance[stringifySym] = stringify\n instance[stringifiersSym] = stringifiers\n instance[formatOptsSym] = formatOpts\n }\n\n if (typeof options.msgPrefix === 'string') {\n instance[msgPrefixSym] = (this[msgPrefixSym] || '') + options.msgPrefix\n }\n\n instance[chindingsSym] = asChindings(instance, bindings)\n const childLevel = options.level || this.level\n instance[setLevelSym](childLevel)\n this.onChild(instance)\n return instance\n}\n\nfunction bindings () {\n const chindings = this[chindingsSym]\n const chindingsJson = `{${chindings.substr(1)}}` // at least contains ,\"pid\":7068,\"hostname\":\"myMac\"\n const bindingsFromJson = JSON.parse(chindingsJson)\n delete bindingsFromJson.pid\n delete bindingsFromJson.hostname\n return bindingsFromJson\n}\n\nfunction setBindings (newBindings) {\n const chindings = asChindings(this, newBindings)\n this[chindingsSym] = chindings\n delete this[parsedChindingsSym]\n}\n\n/**\n * Default strategy for creating `mergeObject` from arguments and the result from `mixin()`.\n * Fields from `mergeObject` have higher priority in this strategy.\n *\n * @param {Object} mergeObject The object a user has supplied to the logging function.\n * @param {Object} mixinObject The result of the `mixin` method.\n * @return {Object}\n */\nfunction defaultMixinMergeStrategy (mergeObject, mixinObject) {\n return Object.assign(mixinObject, mergeObject)\n}\n\nfunction write (_obj, msg, num) {\n const t = this[timeSym]()\n const mixin = this[mixinSym]\n const errorKey = this[errorKeySym]\n const messageKey = this[messageKeySym]\n const mixinMergeStrategy = this[mixinMergeStrategySym] || defaultMixinMergeStrategy\n let obj\n const streamWriteHook = this[hooksSym].streamWrite\n\n if (_obj === undefined || _obj === null) {\n obj = {}\n } else if (_obj instanceof Error) {\n obj = { [errorKey]: _obj }\n if (msg === undefined) {\n msg = _obj.message\n }\n } else {\n obj = _obj\n if (msg === undefined && _obj[messageKey] === undefined && _obj[errorKey]) {\n msg = _obj[errorKey].message\n }\n }\n\n if (mixin) {\n obj = mixinMergeStrategy(obj, mixin(obj, num, this))\n }\n\n const s = this[asJsonSym](obj, msg, num, t)\n\n const stream = this[streamSym]\n if (stream[needsMetadataGsym] === true) {\n stream.lastLevel = num\n stream.lastObj = obj\n stream.lastMsg = msg\n stream.lastTime = t.slice(this[timeSliceIndexSym])\n stream.lastLogger = this // for child loggers\n }\n stream.write(streamWriteHook ? streamWriteHook(s) : s)\n}\n\nfunction noop () {}\n\nfunction flush (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw Error('callback must be a function')\n }\n\n const stream = this[streamSym]\n\n if (typeof stream.flush === 'function') {\n stream.flush(cb || noop)\n } else if (cb) cb()\n}\n", "'use strict'\n\nconst { hasOwnProperty } = Object.prototype\n\nconst stringify = configure()\n\n// @ts-expect-error\nstringify.configure = configure\n// @ts-expect-error\nstringify.stringify = stringify\n\n// @ts-expect-error\nstringify.default = stringify\n\n// @ts-expect-error used for named export\nexports.stringify = stringify\n// @ts-expect-error used for named export\nexports.configure = configure\n\nmodule.exports = stringify\n\n// eslint-disable-next-line no-control-regex\nconst strEscapeSequencesRegExp = /[\\u0000-\\u001f\\u0022\\u005c\\ud800-\\udfff]/\n\n// Escape C0 control characters, double quotes, the backslash and every code\n// unit with a numeric value in the inclusive range 0xD800 to 0xDFFF.\nfunction strEscape (str) {\n // Some magic numbers that worked out fine while benchmarking with v8 8.0\n if (str.length < 5000 && !strEscapeSequencesRegExp.test(str)) {\n return `\"${str}\"`\n }\n return JSON.stringify(str)\n}\n\nfunction sort (array, comparator) {\n // Insertion sort is very efficient for small input sizes, but it has a bad\n // worst case complexity. Thus, use native array sort for bigger values.\n if (array.length > 2e2 || comparator) {\n return array.sort(comparator)\n }\n for (let i = 1; i < array.length; i++) {\n const currentValue = array[i]\n let position = i\n while (position !== 0 && array[position - 1] > currentValue) {\n array[position] = array[position - 1]\n position--\n }\n array[position] = currentValue\n }\n return array\n}\n\nconst typedArrayPrototypeGetSymbolToStringTag =\n Object.getOwnPropertyDescriptor(\n Object.getPrototypeOf(\n Object.getPrototypeOf(\n new Int8Array()\n )\n ),\n Symbol.toStringTag\n ).get\n\nfunction isTypedArrayWithEntries (value) {\n return typedArrayPrototypeGetSymbolToStringTag.call(value) !== undefined && value.length !== 0\n}\n\nfunction stringifyTypedArray (array, separator, maximumBreadth) {\n if (array.length < maximumBreadth) {\n maximumBreadth = array.length\n }\n const whitespace = separator === ',' ? '' : ' '\n let res = `\"0\":${whitespace}${array[0]}`\n for (let i = 1; i < maximumBreadth; i++) {\n res += `${separator}\"${i}\":${whitespace}${array[i]}`\n }\n return res\n}\n\nfunction getCircularValueOption (options) {\n if (hasOwnProperty.call(options, 'circularValue')) {\n const circularValue = options.circularValue\n if (typeof circularValue === 'string') {\n return `\"${circularValue}\"`\n }\n if (circularValue == null) {\n return circularValue\n }\n if (circularValue === Error || circularValue === TypeError) {\n return {\n toString () {\n throw new TypeError('Converting circular structure to JSON')\n }\n }\n }\n throw new TypeError('The \"circularValue\" argument must be of type string or the value null or undefined')\n }\n return '\"[Circular]\"'\n}\n\nfunction getDeterministicOption (options) {\n let value\n if (hasOwnProperty.call(options, 'deterministic')) {\n value = options.deterministic\n if (typeof value !== 'boolean' && typeof value !== 'function') {\n throw new TypeError('The \"deterministic\" argument must be of type boolean or comparator function')\n }\n }\n return value === undefined ? true : value\n}\n\nfunction getBooleanOption (options, key) {\n let value\n if (hasOwnProperty.call(options, key)) {\n value = options[key]\n if (typeof value !== 'boolean') {\n throw new TypeError(`The \"${key}\" argument must be of type boolean`)\n }\n }\n return value === undefined ? true : value\n}\n\nfunction getPositiveIntegerOption (options, key) {\n let value\n if (hasOwnProperty.call(options, key)) {\n value = options[key]\n if (typeof value !== 'number') {\n throw new TypeError(`The \"${key}\" argument must be of type number`)\n }\n if (!Number.isInteger(value)) {\n throw new TypeError(`The \"${key}\" argument must be an integer`)\n }\n if (value < 1) {\n throw new RangeError(`The \"${key}\" argument must be >= 1`)\n }\n }\n return value === undefined ? Infinity : value\n}\n\nfunction getItemCount (number) {\n if (number === 1) {\n return '1 item'\n }\n return `${number} items`\n}\n\nfunction getUniqueReplacerSet (replacerArray) {\n const replacerSet = new Set()\n for (const value of replacerArray) {\n if (typeof value === 'string' || typeof value === 'number') {\n replacerSet.add(String(value))\n }\n }\n return replacerSet\n}\n\nfunction getStrictOption (options) {\n if (hasOwnProperty.call(options, 'strict')) {\n const value = options.strict\n if (typeof value !== 'boolean') {\n throw new TypeError('The \"strict\" argument must be of type boolean')\n }\n if (value) {\n return (value) => {\n let message = `Object can not safely be stringified. Received type ${typeof value}`\n if (typeof value !== 'function') message += ` (${value.toString()})`\n throw new Error(message)\n }\n }\n }\n}\n\nfunction configure (options) {\n options = { ...options }\n const fail = getStrictOption(options)\n if (fail) {\n if (options.bigint === undefined) {\n options.bigint = false\n }\n if (!('circularValue' in options)) {\n options.circularValue = Error\n }\n }\n const circularValue = getCircularValueOption(options)\n const bigint = getBooleanOption(options, 'bigint')\n const deterministic = getDeterministicOption(options)\n const comparator = typeof deterministic === 'function' ? deterministic : undefined\n const maximumDepth = getPositiveIntegerOption(options, 'maximumDepth')\n const maximumBreadth = getPositiveIntegerOption(options, 'maximumBreadth')\n\n function stringifyFnReplacer (key, parent, stack, replacer, spacer, indentation) {\n let value = parent[key]\n\n if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n }\n value = replacer.call(parent, key, value)\n\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n\n let res = ''\n let join = ','\n const originalIndentation = indentation\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n if (spacer !== '') {\n indentation += spacer\n res += `\\n${indentation}`\n join = `,\\n${indentation}`\n }\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n res += join\n }\n const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n if (spacer !== '') {\n res += `\\n${originalIndentation}`\n }\n stack.pop()\n return `[${res}]`\n }\n\n let keys = Object.keys(value)\n const keyLength = keys.length\n if (keyLength === 0) {\n return '{}'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Object]\"'\n }\n let whitespace = ''\n let separator = ''\n if (spacer !== '') {\n indentation += spacer\n join = `,\\n${indentation}`\n whitespace = ' '\n }\n const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n if (deterministic && !isTypedArrayWithEntries(value)) {\n keys = sort(keys, comparator)\n }\n stack.push(value)\n for (let i = 0; i < maximumPropertiesToStringify; i++) {\n const key = keys[i]\n const tmp = stringifyFnReplacer(key, value, stack, replacer, spacer, indentation)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}:${whitespace}${tmp}`\n separator = join\n }\n }\n if (keyLength > maximumBreadth) {\n const removedKeys = keyLength - maximumBreadth\n res += `${separator}\"...\":${whitespace}\"${getItemCount(removedKeys)} not stringified\"`\n separator = join\n }\n if (spacer !== '' && separator.length > 1) {\n res = `\\n${indentation}${res}\\n${originalIndentation}`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringifyArrayReplacer (key, value, stack, replacer, spacer, indentation) {\n if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n }\n\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n\n const originalIndentation = indentation\n let res = ''\n let join = ','\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n if (spacer !== '') {\n indentation += spacer\n res += `\\n${indentation}`\n join = `,\\n${indentation}`\n }\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n res += join\n }\n const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n if (spacer !== '') {\n res += `\\n${originalIndentation}`\n }\n stack.pop()\n return `[${res}]`\n }\n stack.push(value)\n let whitespace = ''\n if (spacer !== '') {\n indentation += spacer\n join = `,\\n${indentation}`\n whitespace = ' '\n }\n let separator = ''\n for (const key of replacer) {\n const tmp = stringifyArrayReplacer(key, value[key], stack, replacer, spacer, indentation)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}:${whitespace}${tmp}`\n separator = join\n }\n }\n if (spacer !== '' && separator.length > 1) {\n res = `\\n${indentation}${res}\\n${originalIndentation}`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringifyIndent (key, value, stack, spacer, indentation) {\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n // Prevent calling `toJSON` again.\n if (typeof value !== 'object') {\n return stringifyIndent(key, value, stack, spacer, indentation)\n }\n if (value === null) {\n return 'null'\n }\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n const originalIndentation = indentation\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n indentation += spacer\n let res = `\\n${indentation}`\n const join = `,\\n${indentation}`\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n res += join\n }\n const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n res += `\\n${originalIndentation}`\n stack.pop()\n return `[${res}]`\n }\n\n let keys = Object.keys(value)\n const keyLength = keys.length\n if (keyLength === 0) {\n return '{}'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Object]\"'\n }\n indentation += spacer\n const join = `,\\n${indentation}`\n let res = ''\n let separator = ''\n let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n if (isTypedArrayWithEntries(value)) {\n res += stringifyTypedArray(value, join, maximumBreadth)\n keys = keys.slice(value.length)\n maximumPropertiesToStringify -= value.length\n separator = join\n }\n if (deterministic) {\n keys = sort(keys, comparator)\n }\n stack.push(value)\n for (let i = 0; i < maximumPropertiesToStringify; i++) {\n const key = keys[i]\n const tmp = stringifyIndent(key, value[key], stack, spacer, indentation)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}: ${tmp}`\n separator = join\n }\n }\n if (keyLength > maximumBreadth) {\n const removedKeys = keyLength - maximumBreadth\n res += `${separator}\"...\": \"${getItemCount(removedKeys)} not stringified\"`\n separator = join\n }\n if (separator !== '') {\n res = `\\n${indentation}${res}\\n${originalIndentation}`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringifySimple (key, value, stack) {\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n // Prevent calling `toJSON` again\n if (typeof value !== 'object') {\n return stringifySimple(key, value, stack)\n }\n if (value === null) {\n return 'null'\n }\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n\n let res = ''\n\n const hasLength = value.length !== undefined\n if (hasLength && Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifySimple(String(i), value[i], stack)\n res += tmp !== undefined ? tmp : 'null'\n res += ','\n }\n const tmp = stringifySimple(String(i), value[i], stack)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `,\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n stack.pop()\n return `[${res}]`\n }\n\n let keys = Object.keys(value)\n const keyLength = keys.length\n if (keyLength === 0) {\n return '{}'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Object]\"'\n }\n let separator = ''\n let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n if (hasLength && isTypedArrayWithEntries(value)) {\n res += stringifyTypedArray(value, ',', maximumBreadth)\n keys = keys.slice(value.length)\n maximumPropertiesToStringify -= value.length\n separator = ','\n }\n if (deterministic) {\n keys = sort(keys, comparator)\n }\n stack.push(value)\n for (let i = 0; i < maximumPropertiesToStringify; i++) {\n const key = keys[i]\n const tmp = stringifySimple(key, value[key], stack)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}:${tmp}`\n separator = ','\n }\n }\n if (keyLength > maximumBreadth) {\n const removedKeys = keyLength - maximumBreadth\n res += `${separator}\"...\":\"${getItemCount(removedKeys)} not stringified\"`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringify (value, replacer, space) {\n if (arguments.length > 1) {\n let spacer = ''\n if (typeof space === 'number') {\n spacer = ' '.repeat(Math.min(space, 10))\n } else if (typeof space === 'string') {\n spacer = space.slice(0, 10)\n }\n if (replacer != null) {\n if (typeof replacer === 'function') {\n return stringifyFnReplacer('', { '': value }, [], replacer, spacer, '')\n }\n if (Array.isArray(replacer)) {\n return stringifyArrayReplacer('', value, [], getUniqueReplacerSet(replacer), spacer, '')\n }\n }\n if (spacer.length !== 0) {\n return stringifyIndent('', value, [], spacer, '')\n }\n }\n return stringifySimple('', value, [])\n }\n\n return stringify\n}\n", "'use strict'\n\nconst metadata = Symbol.for('pino.metadata')\nconst { DEFAULT_LEVELS } = require('./constants')\n\nconst DEFAULT_INFO_LEVEL = DEFAULT_LEVELS.info\n\nfunction multistream (streamsArray, opts) {\n let counter = 0\n streamsArray = streamsArray || []\n opts = opts || { dedupe: false }\n\n const streamLevels = Object.create(DEFAULT_LEVELS)\n streamLevels.silent = Infinity\n if (opts.levels && typeof opts.levels === 'object') {\n Object.keys(opts.levels).forEach(i => {\n streamLevels[i] = opts.levels[i]\n })\n }\n\n const res = {\n write,\n add,\n emit,\n flushSync,\n end,\n minLevel: 0,\n streams: [],\n clone,\n [metadata]: true,\n streamLevels\n }\n\n if (Array.isArray(streamsArray)) {\n streamsArray.forEach(add, res)\n } else {\n add.call(res, streamsArray)\n }\n\n // clean this object up\n // or it will stay allocated forever\n // as it is closed on the following closures\n streamsArray = null\n\n return res\n\n // we can exit early because the streams are ordered by level\n function write (data) {\n let dest\n const level = this.lastLevel\n const { streams } = this\n // for handling situation when several streams has the same level\n let recordedLevel = 0\n let stream\n\n // if dedupe set to true we send logs to the stream with the highest level\n // therefore, we have to change sorting order\n for (let i = initLoopVar(streams.length, opts.dedupe); checkLoopVar(i, streams.length, opts.dedupe); i = adjustLoopVar(i, opts.dedupe)) {\n dest = streams[i]\n if (dest.level <= level) {\n if (recordedLevel !== 0 && recordedLevel !== dest.level) {\n break\n }\n stream = dest.stream\n if (stream[metadata]) {\n const { lastTime, lastMsg, lastObj, lastLogger } = this\n stream.lastLevel = level\n stream.lastTime = lastTime\n stream.lastMsg = lastMsg\n stream.lastObj = lastObj\n stream.lastLogger = lastLogger\n }\n stream.write(data)\n if (opts.dedupe) {\n recordedLevel = dest.level\n }\n } else if (!opts.dedupe) {\n break\n }\n }\n }\n\n function emit (...args) {\n for (const { stream } of this.streams) {\n if (typeof stream.emit === 'function') {\n stream.emit(...args)\n }\n }\n }\n\n function flushSync () {\n for (const { stream } of this.streams) {\n if (typeof stream.flushSync === 'function') {\n stream.flushSync()\n }\n }\n }\n\n function add (dest) {\n if (!dest) {\n return res\n }\n\n // Check that dest implements either StreamEntry or DestinationStream\n const isStream = typeof dest.write === 'function' || dest.stream\n const stream_ = dest.write ? dest : dest.stream\n // This is necessary to provide a meaningful error message, otherwise it throws somewhere inside write()\n if (!isStream) {\n throw Error('stream object needs to implement either StreamEntry or DestinationStream interface')\n }\n\n const { streams, streamLevels } = this\n\n let level\n if (typeof dest.levelVal === 'number') {\n level = dest.levelVal\n } else if (typeof dest.level === 'string') {\n level = streamLevels[dest.level]\n } else if (typeof dest.level === 'number') {\n level = dest.level\n } else {\n level = DEFAULT_INFO_LEVEL\n }\n\n const dest_ = {\n stream: stream_,\n level,\n levelVal: undefined,\n id: counter++\n }\n\n streams.unshift(dest_)\n streams.sort(compareByLevel)\n\n this.minLevel = streams[0].level\n\n return res\n }\n\n function end () {\n for (const { stream } of this.streams) {\n if (typeof stream.flushSync === 'function') {\n stream.flushSync()\n }\n stream.end()\n }\n }\n\n function clone (level) {\n const streams = new Array(this.streams.length)\n\n for (let i = 0; i < streams.length; i++) {\n streams[i] = {\n level,\n stream: this.streams[i].stream\n }\n }\n\n return {\n write,\n add,\n minLevel: level,\n streams,\n clone,\n emit,\n flushSync,\n [metadata]: true\n }\n }\n}\n\nfunction compareByLevel (a, b) {\n return a.level - b.level\n}\n\nfunction initLoopVar (length, dedupe) {\n return dedupe ? length - 1 : 0\n}\n\nfunction adjustLoopVar (i, dedupe) {\n return dedupe ? i - 1 : i + 1\n}\n\nfunction checkLoopVar (i, length, dedupe) {\n return dedupe ? i >= 0 : i < length\n}\n\nmodule.exports = multistream\n", "\n function pinoBundlerAbsolutePath(p) {\n try {\n return require('path').join(`${process.cwd()}${require('path').sep}dist/cjs`.replace(/\\\\/g, '/'), p)\n } catch(e) {\n const f = new Function('p', 'return new URL(p, import.meta.url).pathname');\n return f(p)\n }\n }\n \n globalThis.__bundlerPathsOverrides = { ...(globalThis.__bundlerPathsOverrides || {}), 'thread-stream-worker': pinoBundlerAbsolutePath('./thread-stream-worker.cjs'),'pino-worker': pinoBundlerAbsolutePath('./pino-worker.cjs'),'pino/file': pinoBundlerAbsolutePath('./pino-file.cjs'),'pino-roll': pinoBundlerAbsolutePath('./pino-roll.cjs')}\n 'use strict'\n\nconst os = require('node:os')\nconst stdSerializers = require('pino-std-serializers')\nconst caller = require('./lib/caller')\nconst redaction = require('./lib/redaction')\nconst time = require('./lib/time')\nconst proto = require('./lib/proto')\nconst symbols = require('./lib/symbols')\nconst { configure } = require('safe-stable-stringify')\nconst { assertDefaultLevelFound, mappings, genLsCache, genLevelComparison, assertLevelComparison } = require('./lib/levels')\nconst { DEFAULT_LEVELS, SORTING_ORDER } = require('./lib/constants')\nconst {\n createArgsNormalizer,\n asChindings,\n buildSafeSonicBoom,\n buildFormatters,\n stringify,\n normalizeDestFileDescriptor,\n noop\n} = require('./lib/tools')\nconst { version } = require('./lib/meta')\nconst {\n chindingsSym,\n redactFmtSym,\n serializersSym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n stringifySym,\n stringifySafeSym,\n stringifiersSym,\n setLevelSym,\n endSym,\n formatOptsSym,\n messageKeySym,\n errorKeySym,\n nestedKeySym,\n mixinSym,\n levelCompSym,\n useOnlyCustomLevelsSym,\n formattersSym,\n hooksSym,\n nestedKeyStrSym,\n mixinMergeStrategySym,\n msgPrefixSym\n} = symbols\nconst { epochTime, nullTime } = time\nconst { pid } = process\nconst hostname = os.hostname()\nconst defaultErrorSerializer = stdSerializers.err\nconst defaultOptions = {\n level: 'info',\n levelComparison: SORTING_ORDER.ASC,\n levels: DEFAULT_LEVELS,\n messageKey: 'msg',\n errorKey: 'err',\n nestedKey: null,\n enabled: true,\n base: { pid, hostname },\n serializers: Object.assign(Object.create(null), {\n err: defaultErrorSerializer\n }),\n formatters: Object.assign(Object.create(null), {\n bindings (bindings) {\n return bindings\n },\n level (label, number) {\n return { level: number }\n }\n }),\n hooks: {\n logMethod: undefined,\n streamWrite: undefined\n },\n timestamp: epochTime,\n name: undefined,\n redact: null,\n customLevels: null,\n useOnlyCustomLevels: false,\n depthLimit: 5,\n edgeLimit: 100\n}\n\nconst normalize = createArgsNormalizer(defaultOptions)\n\nconst serializers = Object.assign(Object.create(null), stdSerializers)\n\nfunction pino (...args) {\n const instance = {}\n const { opts, stream } = normalize(instance, caller(), ...args)\n\n if (opts.level && typeof opts.level === 'string' && DEFAULT_LEVELS[opts.level.toLowerCase()] !== undefined) opts.level = opts.level.toLowerCase()\n\n const {\n redact,\n crlf,\n serializers,\n timestamp,\n messageKey,\n errorKey,\n nestedKey,\n base,\n name,\n level,\n customLevels,\n levelComparison,\n mixin,\n mixinMergeStrategy,\n useOnlyCustomLevels,\n formatters,\n hooks,\n depthLimit,\n edgeLimit,\n onChild,\n msgPrefix\n } = opts\n\n const stringifySafe = configure({\n maximumDepth: depthLimit,\n maximumBreadth: edgeLimit\n })\n\n const allFormatters = buildFormatters(\n formatters.level,\n formatters.bindings,\n formatters.log\n )\n\n const stringifyFn = stringify.bind({\n [stringifySafeSym]: stringifySafe\n })\n const stringifiers = redact ? redaction(redact, stringifyFn) : {}\n const formatOpts = redact\n ? { stringify: stringifiers[redactFmtSym] }\n : { stringify: stringifyFn }\n const end = '}' + (crlf ? '\\r\\n' : '\\n')\n const coreChindings = asChindings.bind(null, {\n [chindingsSym]: '',\n [serializersSym]: serializers,\n [stringifiersSym]: stringifiers,\n [stringifySym]: stringify,\n [stringifySafeSym]: stringifySafe,\n [formattersSym]: allFormatters\n })\n\n let chindings = ''\n if (base !== null) {\n if (name === undefined) {\n chindings = coreChindings(base)\n } else {\n chindings = coreChindings(Object.assign({}, base, { name }))\n }\n }\n\n const time = (timestamp instanceof Function)\n ? timestamp\n : (timestamp ? epochTime : nullTime)\n const timeSliceIndex = time().indexOf(':') + 1\n\n if (useOnlyCustomLevels && !customLevels) throw Error('customLevels is required if useOnlyCustomLevels is set true')\n if (mixin && typeof mixin !== 'function') throw Error(`Unknown mixin type \"${typeof mixin}\" - expected \"function\"`)\n if (msgPrefix && typeof msgPrefix !== 'string') throw Error(`Unknown msgPrefix type \"${typeof msgPrefix}\" - expected \"string\"`)\n\n assertDefaultLevelFound(level, customLevels, useOnlyCustomLevels)\n const levels = mappings(customLevels, useOnlyCustomLevels)\n\n if (typeof stream.emit === 'function') {\n stream.emit('message', { code: 'PINO_CONFIG', config: { levels, messageKey, errorKey } })\n }\n\n assertLevelComparison(levelComparison)\n const levelCompFunc = genLevelComparison(levelComparison)\n\n Object.assign(instance, {\n levels,\n [levelCompSym]: levelCompFunc,\n [useOnlyCustomLevelsSym]: useOnlyCustomLevels,\n [streamSym]: stream,\n [timeSym]: time,\n [timeSliceIndexSym]: timeSliceIndex,\n [stringifySym]: stringify,\n [stringifySafeSym]: stringifySafe,\n [stringifiersSym]: stringifiers,\n [endSym]: end,\n [formatOptsSym]: formatOpts,\n [messageKeySym]: messageKey,\n [errorKeySym]: errorKey,\n [nestedKeySym]: nestedKey,\n // protect against injection\n [nestedKeyStrSym]: nestedKey ? `,${JSON.stringify(nestedKey)}:{` : '',\n [serializersSym]: serializers,\n [mixinSym]: mixin,\n [mixinMergeStrategySym]: mixinMergeStrategy,\n [chindingsSym]: chindings,\n [formattersSym]: allFormatters,\n [hooksSym]: hooks,\n silent: noop,\n onChild,\n [msgPrefixSym]: msgPrefix\n })\n\n Object.setPrototypeOf(instance, proto())\n\n genLsCache(instance)\n\n instance[setLevelSym](level)\n\n return instance\n}\n\nmodule.exports = pino\n\nmodule.exports.destination = (dest = process.stdout.fd) => {\n if (typeof dest === 'object') {\n dest.dest = normalizeDestFileDescriptor(dest.dest || process.stdout.fd)\n return buildSafeSonicBoom(dest)\n } else {\n return buildSafeSonicBoom({ dest: normalizeDestFileDescriptor(dest), minLength: 0 })\n }\n}\n\nmodule.exports.transport = require('./lib/transport')\nmodule.exports.multistream = require('./lib/multistream')\n\nmodule.exports.levels = mappings()\nmodule.exports.stdSerializers = serializers\nmodule.exports.stdTimeFunctions = Object.assign({}, time)\nmodule.exports.symbols = symbols\nmodule.exports.version = version\n\n// Enables default and name export with TypeScript and Babel\nmodule.exports.default = pino\nmodule.exports.pino = pino\n", "/*\nCopyright (c) 2014-2021, Matteo Collina \n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted, provided that the above\ncopyright notice and this permission notice appear in all copies.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\nWITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\nANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR\nIN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*/\n\n'use strict'\n\nconst { Transform } = require('stream')\nconst { StringDecoder } = require('string_decoder')\nconst kLast = Symbol('last')\nconst kDecoder = Symbol('decoder')\n\nfunction transform (chunk, enc, cb) {\n let list\n if (this.overflow) { // Line buffer is full. Skip to start of next line.\n const buf = this[kDecoder].write(chunk)\n list = buf.split(this.matcher)\n\n if (list.length === 1) return cb() // Line ending not found. Discard entire chunk.\n\n // Line ending found. Discard trailing fragment of previous line and reset overflow state.\n list.shift()\n this.overflow = false\n } else {\n this[kLast] += this[kDecoder].write(chunk)\n list = this[kLast].split(this.matcher)\n }\n\n this[kLast] = list.pop()\n\n for (let i = 0; i < list.length; i++) {\n try {\n push(this, this.mapper(list[i]))\n } catch (error) {\n return cb(error)\n }\n }\n\n this.overflow = this[kLast].length > this.maxLength\n if (this.overflow && !this.skipOverflow) {\n cb(new Error('maximum buffer reached'))\n return\n }\n\n cb()\n}\n\nfunction flush (cb) {\n // forward any gibberish left in there\n this[kLast] += this[kDecoder].end()\n\n if (this[kLast]) {\n try {\n push(this, this.mapper(this[kLast]))\n } catch (error) {\n return cb(error)\n }\n }\n\n cb()\n}\n\nfunction push (self, val) {\n if (val !== undefined) {\n self.push(val)\n }\n}\n\nfunction noop (incoming) {\n return incoming\n}\n\nfunction split (matcher, mapper, options) {\n // Set defaults for any arguments not supplied.\n matcher = matcher || /\\r?\\n/\n mapper = mapper || noop\n options = options || {}\n\n // Test arguments explicitly.\n switch (arguments.length) {\n case 1:\n // If mapper is only argument.\n if (typeof matcher === 'function') {\n mapper = matcher\n matcher = /\\r?\\n/\n // If options is only argument.\n } else if (typeof matcher === 'object' && !(matcher instanceof RegExp) && !matcher[Symbol.split]) {\n options = matcher\n matcher = /\\r?\\n/\n }\n break\n\n case 2:\n // If mapper and options are arguments.\n if (typeof matcher === 'function') {\n options = mapper\n mapper = matcher\n matcher = /\\r?\\n/\n // If matcher and options are arguments.\n } else if (typeof mapper === 'object') {\n options = mapper\n mapper = noop\n }\n }\n\n options = Object.assign({}, options)\n options.autoDestroy = true\n options.transform = transform\n options.flush = flush\n options.readableObjectMode = true\n\n const stream = new Transform(options)\n\n stream[kLast] = ''\n stream[kDecoder] = new StringDecoder('utf8')\n stream.matcher = matcher\n stream.mapper = mapper\n stream.maxLength = options.maxLength\n stream.skipOverflow = options.skipOverflow || false\n stream.overflow = false\n stream._destroy = function (err, cb) {\n // Weird Node v12 bug that we need to work around\n this._writableState.errorEmitted = false\n cb(err)\n }\n\n return stream\n}\n\nmodule.exports = split\n", "'use strict'\n\nconst metadata = Symbol.for('pino.metadata')\nconst split = require('split2')\nconst { Duplex } = require('stream')\nconst { parentPort, workerData } = require('worker_threads')\n\nfunction createDeferred () {\n let resolve\n let reject\n const promise = new Promise((_resolve, _reject) => {\n resolve = _resolve\n reject = _reject\n })\n promise.resolve = resolve\n promise.reject = reject\n return promise\n}\n\nmodule.exports = function build (fn, opts = {}) {\n const waitForConfig = opts.expectPinoConfig === true && workerData?.workerData?.pinoWillSendConfig === true\n const parseLines = opts.parse === 'lines'\n const parseLine = typeof opts.parseLine === 'function' ? opts.parseLine : JSON.parse\n const close = opts.close || defaultClose\n const stream = split(function (line) {\n let value\n\n try {\n value = parseLine(line)\n } catch (error) {\n this.emit('unknown', line, error)\n return\n }\n\n if (value === null) {\n this.emit('unknown', line, 'Null value ignored')\n return\n }\n\n if (typeof value !== 'object') {\n value = {\n data: value,\n time: Date.now()\n }\n }\n\n if (stream[metadata]) {\n stream.lastTime = value.time\n stream.lastLevel = value.level\n stream.lastObj = value\n }\n\n if (parseLines) {\n return line\n }\n\n return value\n }, { autoDestroy: true })\n\n stream._destroy = function (err, cb) {\n const promise = close(err, cb)\n if (promise && typeof promise.then === 'function') {\n promise.then(cb, cb)\n }\n }\n\n if (opts.expectPinoConfig === true && workerData?.workerData?.pinoWillSendConfig !== true) {\n setImmediate(() => {\n stream.emit('error', new Error('This transport is not compatible with the current version of pino. Please upgrade pino to the latest version.'))\n })\n }\n\n if (opts.metadata !== false) {\n stream[metadata] = true\n stream.lastTime = 0\n stream.lastLevel = 0\n stream.lastObj = null\n }\n\n if (waitForConfig) {\n let pinoConfig = {}\n const configReceived = createDeferred()\n parentPort.on('message', function handleMessage (message) {\n if (message.code === 'PINO_CONFIG') {\n pinoConfig = message.config\n configReceived.resolve()\n parentPort.off('message', handleMessage)\n }\n })\n\n Object.defineProperties(stream, {\n levels: {\n get () { return pinoConfig.levels }\n },\n messageKey: {\n get () { return pinoConfig.messageKey }\n },\n errorKey: {\n get () { return pinoConfig.errorKey }\n }\n })\n\n return configReceived.then(finish)\n }\n\n return finish()\n\n function finish () {\n let res = fn(stream)\n\n if (res && typeof res.catch === 'function') {\n res.catch((err) => {\n stream.destroy(err)\n })\n\n // set it to null to not retain a reference to the promise\n res = null\n } else if (opts.enablePipelining && res) {\n return Duplex.from({ writable: stream, readable: res })\n }\n\n return stream\n }\n}\n\nfunction defaultClose (err, cb) {\n process.nextTick(cb, err)\n}\n", "/* eslint-disable no-new-func, camelcase */\n/* globals __non_webpack__require__ */\n\nconst realImport = new Function('modulePath', 'return import(modulePath)')\n\nfunction realRequire(modulePath) {\n if (typeof __non_webpack__require__ === 'function') {\n return __non_webpack__require__(modulePath)\n }\n\n return require(modulePath)\n}\n\nmodule.exports = { realImport, realRequire }\n", "'use strict'\n\nconst { realImport, realRequire } = require('real-require')\n\nmodule.exports = loadTransportStreamBuilder\n\n/**\n * Loads & returns a function to build transport streams\n * @param {string} target\n * @returns {Promise>}\n * @throws {Error} In case the target module does not export a function\n */\nasync function loadTransportStreamBuilder (target) {\n let fn\n try {\n const toLoad = target.startsWith('file://') ? target : 'file://' + target\n\n if (toLoad.endsWith('.ts') || toLoad.endsWith('.cts')) {\n // TODO: add support for the TSM modules loader ( https://github.com/lukeed/tsm ).\n if (process[Symbol.for('ts-node.register.instance')]) {\n realRequire('ts-node/register')\n } else if (process.env && process.env.TS_NODE_DEV) {\n realRequire('ts-node-dev')\n }\n // TODO: Support ES imports once tsc, tap & ts-node provide better compatibility guarantees.\n fn = realRequire(decodeURIComponent(target))\n } else {\n fn = (await realImport(toLoad))\n }\n } catch (error) {\n // See this PR for details: https://github.com/pinojs/thread-stream/pull/34\n if ((error.code === 'ENOTDIR' || error.code === 'ERR_MODULE_NOT_FOUND')) {\n fn = realRequire(target)\n } else if (error.code === undefined || error.code === 'ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING') {\n // When bundled with pkg, an undefined error is thrown when called with realImport\n // When bundled with pkg and using node v20, an ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING error is thrown when called with realImport\n // More info at: https://github.com/pinojs/thread-stream/issues/143\n try {\n fn = realRequire(decodeURIComponent(target))\n } catch {\n throw error\n }\n } else {\n throw error\n }\n }\n\n // Depending on how the default export is performed, and on how the code is\n // transpiled, we may find cases of two nested \"default\" objects.\n // See https://github.com/pinojs/pino/issues/1243#issuecomment-982774762\n if (typeof fn === 'object') fn = fn.default\n if (typeof fn === 'object') fn = fn.default\n if (typeof fn !== 'function') throw Error('exported worker is not a function')\n\n return fn\n}\n", "'use strict'\n\nconst EE = require('node:events')\nconst { pipeline, PassThrough } = require('node:stream')\nconst pino = require('../pino.js')\nconst build = require('pino-abstract-transport')\nconst loadTransportStreamBuilder = require('./transport-stream')\n\n// This file is not checked by the code coverage tool,\n// as it is not reliable.\n\n/* istanbul ignore file */\n\n/*\n * > Multiple targets & pipelines\n *\n *\n * \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2500\u2500\u2510\n * \u2502 \u2502 \u2502 p \u2502\n * \u2502 \u2502 \u2502 i \u2502\n * \u2502 target \u2502 \u2502 n \u2502\n * \u2502 \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2524 o \u2502\n * \u2502 targets \u2502 target \u2502 \u2502 . \u2502\n * \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25BA \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2524 m \u2502 source\n * \u2502 \u2502 target \u2502 \u2502 u \u2502 \u2502\n * \u2502 \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2524 l \u2502 \u2502write\n * \u2502 \u2502 \u2502 \u2502 t \u2502 \u25BC\n * \u2502 \u2502 pipeline \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502 \u2502 i \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n * \u2502 \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25BA \u2502 PassThrough \u251C\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2524 s \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502\n * \u2502 \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502 \u2502 t \u2502 write\u2502 Thread \u2502\n * \u2502 \u2502 \u2502 \u2502 r \u2502\u25C4\u2500\u2500\u2500\u2500\u2500\u2524 Stream \u2502\n * \u2502 \u2502 pipeline \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502 \u2502 e \u2502 \u2502 \u2502\n * \u2502 \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25BA \u2502 PassThrough \u251C\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2524 a \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n * \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502 \u2502 m \u2502\n * \u2502 \u2502 \u2502 \u2502\n * \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2518\n *\n *\n *\n * > One single pipeline or target\n *\n *\n * source\n * \u2502\n * \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502write\n * \u2502 \u2502 \u25BC\n * \u2502 \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n * \u2502 targets \u2502 target \u2502 \u2502 \u2502\n * \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25BA \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502 \u2502\n * \u2502 \u2502 \u2502 \u2502 \u2502\n * \u2502 \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502\n * \u2502 \u2502 \u2502 \u2502\n * \u2502 \u2502 \u2502 \u2502\n * \u2502 OR \u2502 \u2502 \u2502\n * \u2502 \u2502 \u2502 \u2502\n * \u2502 \u2502 \u2502 \u2502\n * \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502 \u2502 \u2502\n * \u2502 targets \u2502 pipeline \u2502 \u2502 \u2502 \u2502 Thread \u2502\n * \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25BA \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25BA\u2502 PassThrough \u251C\u2500\u2524 \u2502 Stream \u2502\n * \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502\n * \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502 \u2502 \u2502\n * \u2502 \u2502 \u2502 \u2502\n * \u2502 OR \u2502 write\u2502 \u2502\n * \u2502 \u2502\u25C4\u2500\u2500\u2500\u2500\u2500\u2524 \u2502\n * \u2502 \u2502 \u2502 \u2502\n * \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502 \u2502 \u2502\n * \u2502 pipeline \u2502 \u2502 \u2502 \u2502 \u2502\n * \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25BA\u2502 PassThrough \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502 \u2502\n * \u2502 \u2502 \u2502 \u2502 \u2502 \u2502\n * \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n * \u2502 \u2502\n * \u2502 \u2502\n * \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n */\n\nmodule.exports = async function ({ targets, pipelines, levels, dedupe }) {\n const targetStreams = []\n\n // Process targets\n if (targets && targets.length) {\n targets = await Promise.all(targets.map(async (t) => {\n const fn = await loadTransportStreamBuilder(t.target)\n const stream = await fn(t.options)\n return {\n level: t.level,\n stream\n }\n }))\n\n targetStreams.push(...targets)\n }\n\n // Process pipelines\n if (pipelines && pipelines.length) {\n pipelines = await Promise.all(\n pipelines.map(async (p) => {\n let level\n const pipeDests = await Promise.all(\n p.map(async (t) => {\n // level assigned to pipeline is duplicated over all its targets, just store it\n level = t.level\n const fn = await loadTransportStreamBuilder(t.target)\n const stream = await fn(t.options)\n return stream\n }\n ))\n\n return {\n level,\n stream: createPipeline(pipeDests)\n }\n })\n )\n targetStreams.push(...pipelines)\n }\n\n // Skip building the multistream step if either one single pipeline or target is defined and\n // return directly the stream instance back to TreadStream.\n // This is equivalent to define either:\n //\n // pino.transport({ target: ... })\n //\n // OR\n //\n // pino.transport({ pipeline: ... })\n if (targetStreams.length === 1) {\n return targetStreams[0].stream\n } else {\n return build(process, {\n parse: 'lines',\n metadata: true,\n close (err, cb) {\n let expected = 0\n for (const transport of targetStreams) {\n expected++\n transport.stream.on('close', closeCb)\n transport.stream.end()\n }\n\n function closeCb () {\n if (--expected === 0) {\n cb(err)\n }\n }\n }\n })\n }\n\n // TODO: Why split2 was not used for pipelines?\n function process (stream) {\n const multi = pino.multistream(targetStreams, { levels, dedupe })\n // TODO manage backpressure\n stream.on('data', function (chunk) {\n const { lastTime, lastMsg, lastObj, lastLevel } = this\n multi.lastLevel = lastLevel\n multi.lastTime = lastTime\n multi.lastMsg = lastMsg\n multi.lastObj = lastObj\n\n // TODO handle backpressure\n multi.write(chunk + '\\n')\n })\n }\n\n /**\n * Creates a pipeline using the provided streams and return an instance of `PassThrough` stream\n * as a source for the pipeline.\n *\n * @param {(TransformStream|WritableStream)[]} streams An array of streams.\n * All intermediate streams in the array *MUST* be `Transform` streams and only the last one `Writable`.\n * @returns A `PassThrough` stream instance representing the source stream of the pipeline\n */\n function createPipeline (streams) {\n const ee = new EE()\n const stream = new PassThrough({\n autoDestroy: true,\n destroy (_, cb) {\n ee.on('error', cb)\n ee.on('closed', cb)\n }\n })\n\n pipeline(stream, ...streams, function (err) {\n if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n ee.emit('error', err)\n return\n }\n\n ee.emit('closed')\n })\n\n return stream\n }\n}\n"], + "mappings": "2EAAA,IAAAA,GAAAC,EAAA,CAAAC,GAAAC,KAAA,cAOA,IAAMC,EAAeC,GACZA,GAAO,OAAOA,EAAI,SAAY,SAOjCC,GAAiBD,GAAQ,CAC7B,GAAI,CAACA,EAAK,OAIV,IAAME,EAAQF,EAAI,MAGlB,GAAI,OAAOE,GAAU,WAAY,CAE/B,IAAMC,EAAcH,EAAI,MAAM,EAE9B,OAAOD,EAAYI,CAAW,EAC1BA,EACA,MACN,KACE,QAAOJ,EAAYG,CAAK,EACpBA,EACA,MAER,EAUME,GAAmB,CAACJ,EAAKK,IAAS,CACtC,GAAI,CAACN,EAAYC,CAAG,EAAG,MAAO,GAE9B,IAAMM,EAAQN,EAAI,OAAS,GAG3B,GAAIK,EAAK,IAAIL,CAAG,EACd,OAAOM,EAAQ;AAAA,gCAGjB,IAAMJ,EAAQD,GAAcD,CAAG,EAE/B,OAAIE,GACFG,EAAK,IAAIL,CAAG,EACJM,EAAQ;AAAA,aAAkBF,GAAiBF,EAAOG,CAAI,GAEvDC,CAEX,EAMMC,GAAmBP,GAAQI,GAAiBJ,EAAK,IAAI,GAAK,EAW1DQ,GAAqB,CAACR,EAAKK,EAAMI,IAAS,CAC9C,GAAI,CAACV,EAAYC,CAAG,EAAG,MAAO,GAE9B,IAAMU,EAAUD,EAAO,GAAMT,EAAI,SAAW,GAG5C,GAAIK,EAAK,IAAIL,CAAG,EACd,OAAOU,EAAU,QAGnB,IAAMR,EAAQD,GAAcD,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,SAAAC,EAAU,QAAAC,EAAS,QAAAC,EAAS,UAAAC,CAAU,EAAI,KAClDL,EAAM,UAAYK,EAClBL,EAAM,SAAWE,EACjBF,EAAM,QAAUG,EAChBH,EAAM,QAAUI,EAGhBJ,EAAM,MAAMC,EAAQ;AAAA,CAAI,CAC1B,CAAC,CACH,CAUA,SAASR,EAAgBa,EAAS,CAChC,IAAMC,EAAK,IAAI9B,GACTY,EAAS,IAAIV,GAAY,CAC7B,YAAa,GACb,QAAS6B,EAAGZ,EAAI,CACdW,EAAG,GAAG,QAASX,CAAE,EACjBW,EAAG,GAAG,SAAUX,CAAE,CACpB,CACF,CAAC,EAED,OAAAlB,GAASW,EAAQ,GAAGiB,EAAS,SAAUX,EAAK,CAC1C,GAAIA,GAAOA,EAAI,OAAS,6BAA8B,CACpDY,EAAG,KAAK,QAASZ,CAAG,EACpB,MACF,CAEAY,EAAG,KAAK,QAAQ,CAClB,CAAC,EAEMlB,CACT,CACF", + "names": ["require_err_helpers", "__commonJSMin", "exports", "module", "isErrorLike", "err", "getErrorCause", "cause", "causeResult", "_stackWithCauses", "seen", "stack", "stackWithCauses", "_messageWithCauses", "skip", "message", "skipIfVErrorStyleCause", "messageWithCauses", "require_err_proto", "__commonJSMin", "exports", "module", "seen", "rawSymbol", "pinoErrProto", "val", "require_err", "__commonJSMin", "exports", "module", "errSerializer", "messageWithCauses", "stackWithCauses", "isErrorLike", "pinoErrProto", "pinoErrorSymbols", "seen", "toString", "err", "_err", "key", "val", "require_err_with_cause", "__commonJSMin", "exports", "module", "errWithCauseSerializer", "isErrorLike", "pinoErrProto", "pinoErrorSymbols", "seen", "toString", "err", "_err", "key", "val", "require_req", "__commonJSMin", "exports", "module", "mapHttpRequest", "reqSerializer", "rawSymbol", "pinoReqProto", "val", "req", "connection", "_req", "path", "require_res", "__commonJSMin", "exports", "module", "mapHttpResponse", "resSerializer", "rawSymbol", "pinoResProto", "val", "res", "_res", "require_pino_std_serializers", "__commonJSMin", "exports", "module", "errSerializer", "errWithCauseSerializer", "reqSerializers", "resSerializers", "customSerializer", "err", "req", "res", "require_caller", "__commonJSMin", "exports", "module", "noOpPrepareStackTrace", "_", "stack", "originalPrepare", "entries", "fileNames", "entry", "require_validator", "__commonJSMin", "exports", "module", "validator", "opts", "ERR_PATHS_MUST_BE_STRINGS", "ERR_INVALID_PATH", "s", "paths", "expr", "require_rx", "__commonJSMin", "exports", "module", "require_parse", "__commonJSMin", "exports", "module", "rx", "parse", "paths", "wildcards", "wcLen", "secret", "o", "strPath", "ix", "path", "p", "leadingBracket", "star", "before", "beforeStr", "after", "nested", "require_redactor", "__commonJSMin", "exports", "module", "rx", "redactor", "secret", "serialize", "wcLen", "strict", "isCensorFct", "censorFctTakesPath", "state", "redact", "strictImpl", "redactTmpl", "dynamicRedactTmpl", "resultTmpl", "o", "path", "escPath", "leadingBracket", "arrPath", "skip", "delim", "hops", "match", "ix", "index", "input", "existence", "p", "circularDetection", "censorArgs", "hasWildcards", "require_modifiers", "__commonJSMin", "exports", "module", "groupRedact", "groupRestore", "nestedRedact", "nestedRestore", "keys", "values", "target", "length", "k", "o", "path", "censor", "isCensorFct", "censorFctTakesPath", "get", "keysLength", "pathLength", "pathWithKey", "i", "key", "instructions", "value", "current", "store", "ns", "specialSet", "has", "obj", "prop", "afterPath", "afterPathLen", "lastPathIndex", "originalKey", "n", "nv", "ov", "oov", "wc", "kIsWc", "wcov", "consecutive", "level", "depth", "redactPathCurrent", "tree", "wcKeys", "j", "wck", "node", "iterateNthLevel", "rv", "restoreInstr", "p", "l", "parent", "child", "require_restorer", "__commonJSMin", "exports", "module", "groupRestore", "nestedRestore", "restorer", "secret", "wcLen", "paths", "resetters", "resetTmpl", "hasWildcards", "state", "restoreTmpl", "path", "circle", "escPath", "leadingBracket", "reset", "clear", "require_state", "__commonJSMin", "exports", "module", "state", "o", "secret", "censor", "compileRestore", "serialize", "groupRedact", "nestedRedact", "wildcards", "wcLen", "builder", "require_fast_redact", "__commonJSMin", "exports", "module", "validator", "parse", "redactor", "restorer", "groupRedact", "nestedRedact", "state", "rx", "validate", "noop", "o", "DEFAULT_CENSOR", "fastRedact", "opts", "paths", "serialize", "remove", "censor", "isCensorFct", "censorFctTakesPath", "wildcards", "wcLen", "secret", "compileRestore", "strict", "require_symbols", "__commonJSMin", "exports", "module", "setLevelSym", "getLevelSym", "levelValSym", "levelCompSym", "useLevelLabelsSym", "useOnlyCustomLevelsSym", "mixinSym", "lsCacheSym", "chindingsSym", "asJsonSym", "writeSym", "redactFmtSym", "timeSym", "timeSliceIndexSym", "streamSym", "stringifySym", "stringifySafeSym", "stringifiersSym", "endSym", "formatOptsSym", "messageKeySym", "errorKeySym", "nestedKeySym", "nestedKeyStrSym", "mixinMergeStrategySym", "msgPrefixSym", "wildcardFirstSym", "serializersSym", "formattersSym", "hooksSym", "needsMetadataGsym", "require_redaction", "__commonJSMin", "exports", "module", "fastRedact", "redactFmtSym", "wildcardFirstSym", "rx", "validator", "validate", "s", "CENSOR", "strict", "redaction", "opts", "serialize", "paths", "censor", "handle", "shape", "o", "str", "first", "next", "ns", "index", "nextPath", "k", "result", "topCensor", "args", "value", "wrappedCensor", "path", "remove", "require_time", "__commonJSMin", "exports", "module", "nullTime", "epochTime", "unixTime", "isoTime", "require_quick_format_unescaped", "__commonJSMin", "exports", "module", "tryStringify", "o", "format", "f", "args", "opts", "ss", "offset", "len", "objects", "index", "argLen", "str", "a", "lastPos", "flen", "i", "type", "require_atomic_sleep", "__commonJSMin", "exports", "module", "sleep", "ms", "nil", "target", "require_sonic_boom", "__commonJSMin", "exports", "module", "fs", "EventEmitter", "inherits", "path", "sleep", "assert", "BUSY_WRITE_TIMEOUT", "kEmptyBuffer", "MAX_WRITE", "kContentModeBuffer", "kContentModeUtf8", "major", "minor", "kCopyBuffer", "openFile", "file", "sonic", "fileOpened", "err", "fd", "reopening", "flags", "mode", "SonicBoom", "opts", "dest", "minLength", "maxLength", "maxWrite", "periodicFlush", "sync", "append", "mkdir", "retryEAGAIN", "fsync", "contentMode", "fsWriteSync", "fsWrite", "writeBuffer", "flushBuffer", "flushBufferSync", "actualWriteBuffer", "write", "flush", "flushSync", "actualWrite", "n", "releasedBufObj", "releaseWritingBuf", "len", "actualClose", "emitDrain", "name", "writingBuf", "mergeBuf", "bufs", "data", "lens", "callFlushCallbackOnDrain", "cb", "onDrain", "onError", "error", "buf", "release", "written", "closeWrapped", "done", "require_on_exit_leak_free", "__commonJSMin", "exports", "module", "refs", "functions", "onExit", "onBeforeExit", "registry", "ensureRegistry", "clear", "install", "event", "uninstall", "callRefs", "ref", "obj", "fn", "index", "_register", "register", "registerBeforeExit", "unregister", "_obj", "require_package", "__commonJSMin", "exports", "module", "require_wait", "__commonJSMin", "exports", "module", "wait", "state", "index", "expected", "timeout", "done", "max", "current", "prior", "check", "backoff", "waitDiff", "require_indexes", "__commonJSMin", "exports", "module", "require_thread_stream", "__commonJSMin", "exports", "module", "version", "EventEmitter", "Worker", "join", "pathToFileURL", "wait", "WRITE_INDEX", "READ_INDEX", "buffer", "assert", "kImpl", "MAX_STRING", "FakeWeakRef", "value", "FakeFinalizationRegistry", "FinalizationRegistry", "WeakRef", "registry", "worker", "createWorker", "stream", "opts", "filename", "workerData", "toExecute", "onWorkerMessage", "onWorkerExit", "drain", "nextFlush", "writeIndex", "leftover", "end", "toWrite", "toWriteBytes", "write", "destroy", "msg", "code", "ThreadStream", "message", "transferList", "data", "error", "writeSync", "err", "cb", "res", "flushSync", "current", "length", "readIndex", "spins", "require_transport", "__commonJSMin", "exports", "module", "createRequire", "getCallers", "join", "isAbsolute", "sep", "sleep", "onExit", "ThreadStream", "setupOnExit", "stream", "autoEnd", "flush", "buildStream", "filename", "workerData", "workerOpts", "sync", "onReady", "transport", "fullOptions", "pipeline", "targets", "levels", "dedupe", "worker", "caller", "options", "callers", "bundlerOverrides", "target", "dest", "fixTarget", "t", "origin", "filePath", "context", "require_tools", "__commonJSMin", "exports", "module", "format", "mapHttpRequest", "mapHttpResponse", "SonicBoom", "onExit", "lsCacheSym", "chindingsSym", "writeSym", "serializersSym", "formatOptsSym", "endSym", "stringifiersSym", "stringifySym", "stringifySafeSym", "wildcardFirstSym", "nestedKeySym", "formattersSym", "messageKeySym", "errorKeySym", "nestedKeyStrSym", "msgPrefixSym", "isMainThread", "transport", "noop", "genLog", "level", "hook", "LOG", "args", "o", "n", "msg", "formatParams", "asString", "str", "result", "last", "found", "point", "l", "i", "asJson", "obj", "num", "time", "stringify", "stringifySafe", "stringifiers", "end", "chindings", "serializers", "formatters", "messageKey", "errorKey", "data", "value", "wildcardStringifier", "propStr", "key", "stringifier", "strKey", "msgStr", "asChindings", "instance", "bindings", "formatter", "hasBeenTampered", "stream", "buildSafeSonicBoom", "opts", "filterBrokenPipe", "autoEnd", "err", "eventName", "createArgsNormalizer", "defaultOptions", "caller", "customLevels", "enabled", "onChild", "stringifySafeFn", "buildFormatters", "log", "normalizeDestFileDescriptor", "destination", "fd", "require_constants", "__commonJSMin", "exports", "module", "DEFAULT_LEVELS", "SORTING_ORDER", "require_levels", "__commonJSMin", "exports", "module", "lsCacheSym", "levelValSym", "useOnlyCustomLevelsSym", "streamSym", "formattersSym", "hooksSym", "levelCompSym", "noop", "genLog", "DEFAULT_LEVELS", "SORTING_ORDER", "levelMethods", "hook", "logFatal", "args", "stream", "nums", "o", "k", "initialLsCache", "genLsCache", "instance", "formatter", "labels", "cache", "label", "level", "isStandardLevel", "useOnlyCustomLevels", "setLevel", "values", "preLevelVal", "levelVal", "useOnlyCustomLevelsVal", "levelComparison", "key", "getLevel", "levels", "isLevelEnabled", "logLevel", "logLevelVal", "compareLevel", "direction", "current", "expected", "genLevelComparison", "mappings", "customLevels", "customNums", "assertDefaultLevelFound", "defaultLevel", "assertNoLevelCollisions", "assertLevelComparison", "require_meta", "__commonJSMin", "exports", "module", "require_proto", "__commonJSMin", "exports", "module", "EventEmitter", "lsCacheSym", "levelValSym", "setLevelSym", "getLevelSym", "chindingsSym", "parsedChindingsSym", "mixinSym", "asJsonSym", "writeSym", "mixinMergeStrategySym", "timeSym", "timeSliceIndexSym", "streamSym", "serializersSym", "formattersSym", "errorKeySym", "messageKeySym", "useOnlyCustomLevelsSym", "needsMetadataGsym", "redactFmtSym", "stringifySym", "formatOptsSym", "stringifiersSym", "msgPrefixSym", "hooksSym", "getLevel", "setLevel", "isLevelEnabled", "mappings", "initialLsCache", "genLsCache", "assertNoLevelCollisions", "asChindings", "asJson", "buildFormatters", "stringify", "version", "redaction", "constructor", "prototype", "child", "bindings", "setBindings", "flush", "lvl", "n", "write", "resetChildingsFormatter", "options", "serializers", "formatters", "instance", "k", "parentSymbols", "i", "ks", "bk", "bindingsSymbols", "bi", "bks", "level", "chindings", "log", "stringifiers", "formatOpts", "childLevel", "chindingsJson", "bindingsFromJson", "newBindings", "defaultMixinMergeStrategy", "mergeObject", "mixinObject", "_obj", "msg", "num", "t", "mixin", "errorKey", "messageKey", "mixinMergeStrategy", "obj", "streamWriteHook", "s", "stream", "noop", "cb", "require_safe_stable_stringify", "__commonJSMin", "exports", "module", "hasOwnProperty", "stringify", "configure", "strEscapeSequencesRegExp", "strEscape", "str", "sort", "array", "comparator", "i", "currentValue", "position", "typedArrayPrototypeGetSymbolToStringTag", "isTypedArrayWithEntries", "value", "stringifyTypedArray", "separator", "maximumBreadth", "whitespace", "res", "getCircularValueOption", "options", "circularValue", "getDeterministicOption", "getBooleanOption", "key", "getPositiveIntegerOption", "getItemCount", "number", "getUniqueReplacerSet", "replacerArray", "replacerSet", "getStrictOption", "message", "fail", "bigint", "deterministic", "maximumDepth", "stringifyFnReplacer", "parent", "stack", "replacer", "spacer", "indentation", "join", "originalIndentation", "maximumValuesToStringify", "tmp", "removedKeys", "keys", "keyLength", "maximumPropertiesToStringify", "stringifyArrayReplacer", "stringifyIndent", "stringifySimple", "hasLength", "space", "require_multistream", "__commonJSMin", "exports", "module", "metadata", "DEFAULT_LEVELS", "DEFAULT_INFO_LEVEL", "multistream", "streamsArray", "opts", "counter", "streamLevels", "i", "res", "write", "add", "emit", "flushSync", "end", "clone", "data", "dest", "level", "streams", "recordedLevel", "stream", "initLoopVar", "checkLoopVar", "adjustLoopVar", "lastTime", "lastMsg", "lastObj", "lastLogger", "args", "isStream", "stream_", "dest_", "compareByLevel", "a", "b", "length", "dedupe", "require_pino", "__commonJSMin", "exports", "module", "pinoBundlerAbsolutePath", "p", "os", "stdSerializers", "caller", "redaction", "time", "proto", "symbols", "configure", "assertDefaultLevelFound", "mappings", "genLsCache", "genLevelComparison", "assertLevelComparison", "DEFAULT_LEVELS", "SORTING_ORDER", "createArgsNormalizer", "asChindings", "buildSafeSonicBoom", "buildFormatters", "stringify", "normalizeDestFileDescriptor", "noop", "version", "chindingsSym", "redactFmtSym", "serializersSym", "timeSym", "timeSliceIndexSym", "streamSym", "stringifySym", "stringifySafeSym", "stringifiersSym", "setLevelSym", "endSym", "formatOptsSym", "messageKeySym", "errorKeySym", "nestedKeySym", "mixinSym", "levelCompSym", "useOnlyCustomLevelsSym", "formattersSym", "hooksSym", "nestedKeyStrSym", "mixinMergeStrategySym", "msgPrefixSym", "epochTime", "nullTime", "pid", "hostname", "defaultErrorSerializer", "defaultOptions", "bindings", "label", "number", "normalize", "serializers", "pino", "args", "instance", "opts", "stream", "redact", "crlf", "timestamp", "messageKey", "errorKey", "nestedKey", "base", "name", "level", "customLevels", "levelComparison", "mixin", "mixinMergeStrategy", "useOnlyCustomLevels", "formatters", "hooks", "depthLimit", "edgeLimit", "onChild", "msgPrefix", "stringifySafe", "allFormatters", "stringifyFn", "stringifiers", "formatOpts", "end", "coreChindings", "chindings", "timeSliceIndex", "levels", "levelCompFunc", "dest", "require_split2", "__commonJSMin", "exports", "module", "Transform", "StringDecoder", "kLast", "kDecoder", "transform", "chunk", "enc", "cb", "list", "push", "error", "flush", "self", "val", "noop", "incoming", "split", "matcher", "mapper", "options", "stream", "err", "require_pino_abstract_transport", "__commonJSMin", "exports", "module", "metadata", "split", "Duplex", "parentPort", "workerData", "createDeferred", "resolve", "reject", "promise", "_resolve", "_reject", "fn", "opts", "waitForConfig", "parseLines", "parseLine", "close", "defaultClose", "stream", "line", "value", "error", "err", "cb", "pinoConfig", "configReceived", "handleMessage", "message", "finish", "res", "require_src", "__commonJSMin", "exports", "module", "realImport", "realRequire", "modulePath", "require_transport_stream", "__commonJSMin", "exports", "module", "realImport", "realRequire", "loadTransportStreamBuilder", "target", "fn", "toLoad", "error", "EE", "pipeline", "PassThrough", "pino", "build", "loadTransportStreamBuilder", "targets", "pipelines", "levels", "dedupe", "targetStreams", "t", "stream", "p", "level", "pipeDests", "createPipeline", "process", "err", "cb", "expected", "transport", "closeCb", "multi", "chunk", "lastTime", "lastMsg", "lastObj", "lastLevel", "streams", "ee", "_"] +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/server.cjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/server.cjs new file mode 100644 index 0000000000000000000000000000000000000000..4808c4563981c74cb8b721eed51671c4d67f847e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/server.cjs @@ -0,0 +1,274 @@ +"use strict";var Ky=Object.create;var mo=Object.defineProperty;var Yy=Object.getOwnPropertyDescriptor;var Xy=Object.getOwnPropertyNames;var Qy=Object.getPrototypeOf,Zy=Object.prototype.hasOwnProperty;var Ue=(r,e)=>()=>(r&&(e=r(r=0)),e);var z=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ia=(r,e)=>{for(var t in e)mo(r,t,{get:e[t],enumerable:!0})},Tf=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Xy(e))!Zy.call(r,o)&&o!==t&&mo(r,o,{get:()=>e[o],enumerable:!(n=Yy(e,o))||n.enumerable});return r};var Me=(r,e,t)=>(t=r!=null?Ky(Qy(r)):{},Tf(e||!r||!r.__esModule?mo(t,"default",{value:r,enumerable:!0}):t,r)),e0=r=>Tf(mo({},"__esModule",{value:!0}),r);var Rf=z((Qw,go)=>{go.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;go.exports.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7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-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;go.exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0AC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-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06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\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/});var qa=z((Zw,kf)=>{var Na=Rf();kf.exports={isSpaceSeparator(r){return typeof r=="string"&&Na.Space_Separator.test(r)},isIdStartChar(r){return typeof r=="string"&&(r>="a"&&r<="z"||r>="A"&&r<="Z"||r==="$"||r==="_"||Na.ID_Start.test(r))},isIdContinueChar(r){return typeof r=="string"&&(r>="a"&&r<="z"||r>="A"&&r<="Z"||r>="0"&&r<="9"||r==="$"||r==="_"||r==="\u200C"||r==="\u200D"||Na.ID_Continue.test(r))},isDigit(r){return typeof r=="string"&&/[0-9]/.test(r)},isHexDigit(r){return typeof r=="string"&&/[0-9A-Fa-f]/.test(r)}}});var Bf=z((eA,xf)=>{var $e=qa(),La,Ze,fr,_o,kr,Bt,He,$a,is;xf.exports=function(e,t){La=String(e),Ze="start",fr=[],_o=0,kr=1,Bt=0,He=void 0,$a=void 0,is=void 0;do He=t0(),s0[Ze]();while(He.type!=="eof");return typeof t=="function"?Ua({"":is},"",t):is};function Ua(r,e,t){let n=r[e];if(n!=null&&typeof n=="object")if(Array.isArray(n))for(let o=0;o0;){let t=dr();if(!$e.isHexDigit(t))throw Oe($());r+=$()}return String.fromCodePoint(parseInt(r,16))}var s0={start(){if(He.type==="eof")throw Kr();ja()},beforePropertyName(){switch(He.type){case"identifier":case"string":$a=He.value,Ze="afterPropertyName";return;case"punctuator":yo();return;case"eof":throw Kr()}},afterPropertyName(){if(He.type==="eof")throw Kr();Ze="beforePropertyValue"},beforePropertyValue(){if(He.type==="eof")throw Kr();ja()},beforeArrayValue(){if(He.type==="eof")throw Kr();if(He.type==="punctuator"&&He.value==="]"){yo();return}ja()},afterPropertyValue(){if(He.type==="eof")throw Kr();switch(He.value){case",":Ze="beforePropertyName";return;case"}":yo()}},afterArrayValue(){if(He.type==="eof")throw Kr();switch(He.value){case",":Ze="beforeArrayValue";return;case"]":yo()}},end(){}};function ja(){let r;switch(He.type){case"punctuator":switch(He.value){case"{":r={};break;case"[":r=[];break}break;case"null":case"boolean":case"numeric":case"string":r=He.value;break}if(is===void 0)is=r;else{let e=fr[fr.length-1];Array.isArray(e)?e.push(r):Object.defineProperty(e,$a,{value:r,writable:!0,enumerable:!0,configurable:!0})}if(r!==null&&typeof r=="object")fr.push(r),Array.isArray(r)?Ze="beforeArrayValue":Ze="beforePropertyName";else{let e=fr[fr.length-1];e==null?Ze="end":Array.isArray(e)?Ze="afterArrayValue":Ze="afterPropertyValue"}}function yo(){fr.pop();let r=fr[fr.length-1];r==null?Ze="end":Array.isArray(r)?Ze="afterArrayValue":Ze="afterPropertyValue"}function Oe(r){return Co(r===void 0?`JSON5: invalid end of input at ${kr}:${Bt}`:`JSON5: invalid character '${Pf(r)}' at ${kr}:${Bt}`)}function Kr(){return Co(`JSON5: invalid end of input at ${kr}:${Bt}`)}function Ff(){return Bt-=5,Co(`JSON5: invalid identifier character at ${kr}:${Bt}`)}function o0(r){console.warn(`JSON5: '${Pf(r)}' in strings is not valid ECMAScript; consider escaping`)}function Pf(r){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[r])return e[r];if(r<" "){let t=r.charCodeAt(0).toString(16);return"\\x"+("00"+t).substring(t.length)}return r}function Co(r){let e=new SyntaxError(r);return e.lineNumber=kr,e.columnNumber=Bt,e}});var Nf=z((tA,If)=>{var Ha=qa();If.exports=function(e,t,n){let o=[],a="",u,l,f="",h;if(t!=null&&typeof t=="object"&&!Array.isArray(t)&&(n=t.space,h=t.quote,t=t.replacer),typeof t=="function")l=t;else if(Array.isArray(t)){u=[];for(let w of t){let g;typeof w=="string"?g=w:(typeof w=="number"||w instanceof String||w instanceof Number)&&(g=String(w)),g!==void 0&&u.indexOf(g)<0&&u.push(g)}}return n instanceof Number?n=Number(n):n instanceof String&&(n=String(n)),typeof n=="number"?n>0&&(n=Math.min(10,Math.floor(n)),f=" ".substr(0,n)):typeof n=="string"&&(f=n.substr(0,10)),d("",{"":e});function d(w,g){let C=g[w];switch(C!=null&&(typeof C.toJSON5=="function"?C=C.toJSON5(w):typeof C.toJSON=="function"&&(C=C.toJSON(w))),l&&(C=l.call(g,w,C)),C instanceof Number?C=Number(C):C instanceof String?C=String(C):C instanceof Boolean&&(C=C.valueOf()),C){case null:return"null";case!0:return"true";case!1:return"false"}if(typeof C=="string")return _(C,!1);if(typeof C=="number")return String(C);if(typeof C=="object")return Array.isArray(C)?v(C):E(C)}function _(w){let g={"'":.1,'"':.2},C={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},R="";for(let N=0;Ng[N]=0)throw TypeError("Converting circular structure to JSON5");o.push(w);let g=a;a=a+f;let C=u||Object.keys(w),R=[];for(let N of C){let j=d(N,w);if(j!==void 0){let L=P(N)+":";f!==""&&(L+=" "),L+=j,R.push(L)}}let S;if(R.length===0)S="{}";else{let N;if(f==="")N=R.join(","),S="{"+N+"}";else{let j=`, +`+a;N=R.join(j),S=`{ +`+a+N+`, +`+g+"}"}}return o.pop(),a=g,S}function P(w){if(w.length===0)return _(w,!0);let g=String.fromCodePoint(w.codePointAt(0));if(!Ha.isIdStartChar(g))return _(w,!0);for(let C=g.length;C=0)throw TypeError("Converting circular structure to JSON5");o.push(w);let g=a;a=a+f;let C=[];for(let S=0;S{var i0=Bf(),a0=Nf(),u0={parse:i0,stringify:a0};qf.exports=u0});var Va=z((FA,rd)=>{"use strict";var Fo=Object.prototype.hasOwnProperty,td=Object.prototype.toString,Kf=Object.defineProperty,Yf=Object.getOwnPropertyDescriptor,Xf=function(e){return typeof Array.isArray=="function"?Array.isArray(e):td.call(e)==="[object Array]"},Qf=function(e){if(!e||td.call(e)!=="[object Object]")return!1;var t=Fo.call(e,"constructor"),n=e.constructor&&e.constructor.prototype&&Fo.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!t&&!n)return!1;var o;for(o in e);return typeof o>"u"||Fo.call(e,o)},Zf=function(e,t){Kf&&t.name==="__proto__"?Kf(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},ed=function(e,t){if(t==="__proto__")if(Fo.call(e,t)){if(Yf)return Yf(e,t).value}else return;return e[t]};rd.exports=function r(){var e,t,n,o,a,u,l=arguments[0],f=1,h=arguments.length,d=!1;for(typeof l=="boolean"&&(d=l,l=arguments[1]||{},f=2),(l==null||typeof l!="object"&&typeof l!="function")&&(l={});f{b0.exports={name:"gaxios",version:"7.1.1",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:"googleapis/gaxios",keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","@types/tmp":"0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.0.0",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^4.0.0","jsdoc-region-tag":"^3.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.0-beta.13","null-loader":"^4.0.0","pack-n-play":"^3.0.0",puppeteer:"^24.0.0",sinon:"^20.0.0","stream-browserify":"^3.0.0",tmp:"0.2.3","ts-loader":"^9.5.2",typescript:"^5.8.3",webpack:"^5.35.0","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"}}});var od=z((PA,sd)=>{"use strict";var E0=nd();sd.exports={pkg:E0}});var Xa=z(At=>{"use strict";var ad=At&&At.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(At,"__esModule",{value:!0});At.GaxiosError=At.GAXIOS_ERROR_SYMBOL=void 0;At.defaultErrorRedactor=ud;var id=ad(Va()),w0=ad(od()),Ka=w0.default.pkg;At.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Ka.name}-gaxios-error`);var Ya=class r extends Error{config;response;code;status;error;[At.GAXIOS_ERROR_SYMBOL]=Ka.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&At.GAXIOS_ERROR_SYMBOL in e&&e[At.GAXIOS_ERROR_SYMBOL]===Ka.version?!0:Function.prototype[Symbol.hasInstance].call(r,e)}constructor(e,t,n,o){if(super(e,{cause:o}),this.config=t,this.response=n,this.error=o instanceof Error?o:void 0,this.config=(0,id.default)(!0,{},t),this.response&&(this.response.config=(0,id.default)(!0,{},this.response.config)),this.response){try{this.response.data=A0(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.code)}static extractAPIErrorFromResponse(e,t="The request failed"){let n=t;if(typeof e.data=="string"&&(n=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){n="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:n;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,a="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let u=[];for(let l of e.data.error.errors)typeof l=="object"&&"message"in l&&typeof l.message=="string"&&u.push(l.message);return Object.assign({message:u.join(` +`)||n,code:a,status:o},e.data.error)}return Object.assign({message:n,code:a,status:o},e.data.error)}}return{message:n,code:e.status,status:e.statusText}}};At.GaxiosError=Ya;function A0(r,e){switch(r){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function ud(r){let e="< - See `errorRedactor` option in `gaxios` for configuration>.";function t(a){a&&a.forEach((u,l)=>{(/^authentication$/i.test(l)||/^authorization$/i.test(l)||/secret/i.test(l))&&a.set(l,e)})}function n(a,u){if(typeof a=="object"&&a!==null&&typeof a[u]=="string"){let l=a[u];(/grant_type=/i.test(l)||/assertion=/i.test(l)||/secret/i.test(l))&&(a[u]=e)}}function o(a){!a||typeof a!="object"||(a instanceof FormData||a instanceof URLSearchParams||"forEach"in a&&"set"in a?a.forEach((u,l)=>{(["grant_type","assertion"].includes(l)||/secret/.test(l))&&a.set(l,e)}):("grant_type"in a&&(a.grant_type=e),"assertion"in a&&(a.assertion=e),"client_secret"in a&&(a.client_secret=e)))}return r.config&&(t(r.config.headers),n(r.config,"data"),o(r.config.data),n(r.config,"body"),o(r.config.body),r.config.url.searchParams.has("token")&&r.config.url.searchParams.set("token",e),r.config.url.searchParams.has("client_secret")&&r.config.url.searchParams.set("client_secret",e)),r.response&&(ud({config:r.response.config}),t(r.response.headers),r.response.bodyUsed&&(n(r.response,"data"),o(r.response.data))),r}});var ld=z(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.getRetryConfig=D0;async function D0(r){let e=cd(r);if(!r||!r.config||!e&&!r.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let t=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||t,r.config.retryConfig=e,!await(e.shouldRetry||S0)(r))return{shouldRetry:!1,config:r.config};let o=v0(e);r.config.retryConfig.currentRetryAttempt+=1;let a=e.retryBackoff?e.retryBackoff(r,o):new Promise(u=>{setTimeout(u,o)});return e.onRetryAttempt&&await e.onRetryAttempt(r),await a,{shouldRetry:!0,config:r.config}}function S0(r){let e=cd(r);if(r.config.signal?.aborted&&r.code!=="TimeoutError"||r.code==="AbortError"||!e||e.retry===0||!r.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(r.config.method?.toUpperCase()||"GET"))return!1;if(r.response&&r.response.status){let t=!1;for(let[n,o]of e.statusCodesToRetry){let a=r.response.status;if(a>=n&&a<=o){t=!0;break}}if(!t)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function cd(r){if(r&&r.config&&r.config.retryConfig)return r.config.retryConfig}function v0(r){let t=(r.currentRetryAttempt?0:r.retryDelay??100)+(Math.pow(r.retryDelayMultiplier,r.currentRetryAttempt)-1)/2*1e3,n=r.totalTimeout-(Date.now()-r.timeOfFirstRequest);return Math.min(t,n,r.maxRetryDelay)}});var eu=z(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});Oo.GaxiosInterceptorManager=void 0;var Za=class extends Set{};Oo.GaxiosInterceptorManager=Za});var dd=z((NA,fd)=>{var An=1e3,Dn=An*60,Sn=Dn*60,Yr=Sn*24,T0=Yr*7,R0=Yr*365.25;fd.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return k0(r);if(t==="number"&&isFinite(r))return e.long?O0(r):F0(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function k0(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*R0;case"weeks":case"week":case"w":return t*T0;case"days":case"day":case"d":return t*Yr;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Sn;case"minutes":case"minute":case"mins":case"min":case"m":return t*Dn;case"seconds":case"second":case"secs":case"sec":case"s":return t*An;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function F0(r){var e=Math.abs(r);return e>=Yr?Math.round(r/Yr)+"d":e>=Sn?Math.round(r/Sn)+"h":e>=Dn?Math.round(r/Dn)+"m":e>=An?Math.round(r/An)+"s":r+"ms"}function O0(r){var e=Math.abs(r);return e>=Yr?Po(r,e,Yr,"day"):e>=Sn?Po(r,e,Sn,"hour"):e>=Dn?Po(r,e,Dn,"minute"):e>=An?Po(r,e,An,"second"):r+" ms"}function Po(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var tu=z((qA,hd)=>{function P0(r){t.debug=t,t.default=t,t.coerce=f,t.disable=u,t.enable=o,t.enabled=l,t.humanize=dd(),t.destroy=h,Object.keys(r).forEach(d=>{t[d]=r[d]}),t.names=[],t.skips=[],t.formatters={};function e(d){let _=0;for(let E=0;E{if(L==="%%")return"%";N++;let K=t.formatters[H];if(typeof K=="function"){let W=g[N];L=K.call(C,W),g.splice(N,1),N--}return L}),t.formatArgs.call(C,g),(C.log||t.log).apply(C,g)}return w.namespace=d,w.useColors=t.useColors(),w.color=t.selectColor(d),w.extend=n,w.destroy=t.destroy,Object.defineProperty(w,"enabled",{enumerable:!0,configurable:!1,get:()=>E!==null?E:(P!==t.namespaces&&(P=t.namespaces,v=t.enabled(d)),v),set:g=>{E=g}}),typeof t.init=="function"&&t.init(w),w}function n(d,_){let E=t(this.namespace+(typeof _>"u"?":":_)+d);return E.log=this.log,E}function o(d){t.save(d),t.namespaces=d,t.names=[],t.skips=[];let _=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let E of _)E[0]==="-"?t.skips.push(E.slice(1)):t.names.push(E)}function a(d,_){let E=0,P=0,v=-1,w=0;for(;E"-"+_)].join(",");return t.enable(""),d}function l(d){for(let _ of t.skips)if(a(d,_))return!1;for(let _ of t.names)if(a(d,_))return!0;return!1}function f(d){return d instanceof Error?d.stack||d.message:d}function h(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}hd.exports=P0});var pd=z((st,xo)=>{st.formatArgs=B0;st.save=I0;st.load=N0;st.useColors=x0;st.storage=q0();st.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();st.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function x0(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function B0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+xo.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}st.log=console.debug||console.log||(()=>{});function I0(r){try{r?st.storage.setItem("debug",r):st.storage.removeItem("debug")}catch{}}function N0(){let r;try{r=st.storage.getItem("debug")||st.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function q0(){try{return localStorage}catch{}}xo.exports=tu()(st);var{formatters:j0}=xo.exports;j0.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var gd=z((jA,md)=>{"use strict";md.exports=(r,e)=>{e=e||process.argv;let t=r.startsWith("-")?"":r.length===1?"-":"--",n=e.indexOf(t+r),o=e.indexOf("--");return n!==-1&&(o===-1?!0:n{"use strict";var L0=require("os"),It=gd(),Ye=process.env,vn;It("no-color")||It("no-colors")||It("color=false")?vn=!1:(It("color")||It("colors")||It("color=true")||It("color=always"))&&(vn=!0);"FORCE_COLOR"in Ye&&(vn=Ye.FORCE_COLOR.length===0||parseInt(Ye.FORCE_COLOR,10)!==0);function U0(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function M0(r){if(vn===!1)return 0;if(It("color=16m")||It("color=full")||It("color=truecolor"))return 3;if(It("color=256"))return 2;if(r&&!r.isTTY&&vn!==!0)return 0;let e=vn?1:0;if(process.platform==="win32"){let t=L0.release().split(".");return Number(process.versions.node.split(".")[0])>=8&&Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("CI"in Ye)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some(t=>t in Ye)||Ye.CI_NAME==="codeship"?1:e;if("TEAMCITY_VERSION"in Ye)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Ye.TEAMCITY_VERSION)?1:0;if(Ye.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in Ye){let t=parseInt((Ye.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Ye.TERM_PROGRAM){case"iTerm.app":return t>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Ye.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Ye.TERM)||"COLORTERM"in Ye?1:(Ye.TERM==="dumb",e)}function ru(r){let e=M0(r);return U0(e)}yd.exports={supportsColor:ru,stdout:ru(process.stdout),stderr:ru(process.stderr)}});var bd=z((Ge,Io)=>{var $0=require("tty"),Bo=require("util");Ge.init=K0;Ge.log=z0;Ge.formatArgs=G0;Ge.save=J0;Ge.load=V0;Ge.useColors=H0;Ge.destroy=Bo.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Ge.colors=[6,2,3,4,5,1];try{let r=_d();r&&(r.stderr||r).level>=2&&(Ge.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}Ge.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(o,a)=>a.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),r[t]=n,r},{});function H0(){return"colors"in Ge.inspectOpts?!!Ge.inspectOpts.colors:$0.isatty(process.stderr.fd)}function G0(r){let{namespace:e,useColors:t}=this;if(t){let n=this.color,o="\x1B[3"+(n<8?n:"8;5;"+n),a=` ${o};1m${e} \x1B[0m`;r[0]=a+r[0].split(` +`).join(` +`+a),r.push(o+"m+"+Io.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=W0()+e+" "+r[0]}function W0(){return Ge.inspectOpts.hideDate?"":new Date().toISOString()+" "}function z0(...r){return process.stderr.write(Bo.formatWithOptions(Ge.inspectOpts,...r)+` +`)}function J0(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function V0(){return process.env.DEBUG}function K0(r){r.inspectOpts={};let e=Object.keys(Ge.inspectOpts);for(let t=0;te.trim()).join(" ")};Cd.O=function(r){return this.inspectOpts.colors=this.useColors,Bo.inspect(r,this.inspectOpts)}});var su=z((UA,nu)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?nu.exports=pd():nu.exports=bd()});var Ad=z(ot=>{"use strict";var Y0=ot&&ot.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),X0=ot&&ot.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),Ed=ot&&ot.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&Y0(e,r,t);return X0(e,r),e};Object.defineProperty(ot,"__esModule",{value:!0});ot.req=ot.json=ot.toBuffer=void 0;var Q0=Ed(require("http")),Z0=Ed(require("https"));async function wd(r){let e=0,t=[];for await(let n of r)e+=n.length,t.push(n);return Buffer.concat(t,e)}ot.toBuffer=wd;async function e_(r){let t=(await wd(r)).toString("utf8");try{return JSON.parse(t)}catch(n){let o=n;throw o.message+=` (input: ${t})`,o}}ot.json=e_;function t_(r,e={}){let n=((typeof r=="string"?r:r.href).startsWith("https:")?Z0:Q0).request(r,e),o=new Promise((a,u)=>{n.once("response",a).once("error",u).end()});return n.then=o.then.bind(o),n}ot.req=t_});var Td=z(lt=>{"use strict";var Sd=lt&<.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),r_=lt&<.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),vd=lt&<.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&Sd(e,r,t);return r_(e,r),e},n_=lt&<.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Sd(e,r,t)};Object.defineProperty(lt,"__esModule",{value:!0});lt.Agent=void 0;var s_=vd(require("net")),Dd=vd(require("http")),o_=require("https");n_(Ad(),lt);var zt=Symbol("AgentBaseInternalState"),ou=class extends Dd.Agent{constructor(e){super(e),this[zt]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:t}=new Error;return typeof t!="string"?!1:t.split(` +`).some(n=>n.indexOf("(https.js:")!==-1||n.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let t=new s_.Socket({writable:!1});return this.sockets[e].push(t),this.totalSocketCount++,t}decrementSockets(e,t){if(!this.sockets[e]||t===null)return;let n=this.sockets[e],o=n.indexOf(t);o!==-1&&(n.splice(o,1),this.totalSocketCount--,n.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?o_.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,t,n){let o={...t,secureEndpoint:this.isSecureEndpoint(t)},a=this.getName(o),u=this.incrementSockets(a);Promise.resolve().then(()=>this.connect(e,o)).then(l=>{if(this.decrementSockets(a,u),l instanceof Dd.Agent)try{return l.addRequest(e,o)}catch(f){return n(f)}this[zt].currentSocket=l,super.createSocket(e,t,n)},l=>{this.decrementSockets(a,u),n(l)})}createConnection(){let e=this[zt].currentSocket;if(this[zt].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[zt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[zt]&&(this[zt].defaultPort=e)}get protocol(){return this[zt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[zt]&&(this[zt].protocol=e)}};lt.Agent=ou});var Rd=z(Tn=>{"use strict";var i_=Tn&&Tn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Tn,"__esModule",{value:!0});Tn.parseProxyResponse=void 0;var a_=i_(su()),No=(0,a_.default)("https-proxy-agent:parse-proxy-response");function u_(r){return new Promise((e,t)=>{let n=0,o=[];function a(){let d=r.read();d?h(d):r.once("readable",a)}function u(){r.removeListener("end",l),r.removeListener("error",f),r.removeListener("readable",a)}function l(){u(),No("onend"),t(new Error("Proxy connection ended before receiving CONNECT response"))}function f(d){u(),No("onerror %o",d),t(d)}function h(d){o.push(d),n+=d.length;let _=Buffer.concat(o,n),E=_.indexOf(`\r +\r +`);if(E===-1){No("have not received end of HTTP headers yet..."),a();return}let P=_.slice(0,E).toString("ascii").split(`\r +`),v=P.shift();if(!v)return r.destroy(),t(new Error("No header received from proxy CONNECT response"));let w=v.split(" "),g=+w[1],C=w.slice(2).join(" "),R={};for(let S of P){if(!S)continue;let N=S.indexOf(":");if(N===-1)return r.destroy(),t(new Error(`Invalid header from proxy CONNECT response: "${S}"`));let j=S.slice(0,N).toLowerCase(),L=S.slice(N+1).trimStart(),H=R[j];typeof H=="string"?R[j]=[H,L]:Array.isArray(H)?H.push(L):R[j]=L}No("got proxy server response: %o %o",v,R),u(),e({connect:{statusCode:g,statusText:C,headers:R},buffered:_})}r.on("error",f),r.on("end",l),a()})}Tn.parseProxyResponse=u_});var Bd=z(Dt=>{"use strict";var c_=Dt&&Dt.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),l_=Dt&&Dt.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),Pd=Dt&&Dt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&c_(e,r,t);return l_(e,r),e},xd=Dt&&Dt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Dt,"__esModule",{value:!0});Dt.HttpsProxyAgent=void 0;var qo=Pd(require("net")),kd=Pd(require("tls")),f_=xd(require("assert")),d_=xd(su()),h_=Td(),p_=require("url"),m_=Rd(),cs=(0,d_.default)("https-proxy-agent"),Fd=r=>r.servername===void 0&&r.host&&!qo.isIP(r.host)?{...r,servername:r.host}:r,jo=class extends h_.Agent{constructor(e,t){super(t),this.options={path:void 0},this.proxy=typeof e=="string"?new p_.URL(e):e,this.proxyHeaders=t?.headers??{},cs("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let n=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),o=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...t?Od(t,"headers"):null,host:n,port:o}}async connect(e,t){let{proxy:n}=this;if(!t.host)throw new TypeError('No "host" provided');let o;n.protocol==="https:"?(cs("Creating `tls.Socket`: %o",this.connectOpts),o=kd.connect(Fd(this.connectOpts))):(cs("Creating `net.Socket`: %o",this.connectOpts),o=qo.connect(this.connectOpts));let a=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},u=qo.isIPv6(t.host)?`[${t.host}]`:t.host,l=`CONNECT ${u}:${t.port} HTTP/1.1\r +`;if(n.username||n.password){let E=`${decodeURIComponent(n.username)}:${decodeURIComponent(n.password)}`;a["Proxy-Authorization"]=`Basic ${Buffer.from(E).toString("base64")}`}a.Host=`${u}:${t.port}`,a["Proxy-Connection"]||(a["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let E of Object.keys(a))l+=`${E}: ${a[E]}\r +`;let f=(0,m_.parseProxyResponse)(o);o.write(`${l}\r +`);let{connect:h,buffered:d}=await f;if(e.emit("proxyConnect",h),this.emit("proxyConnect",h,e),h.statusCode===200)return e.once("socket",g_),t.secureEndpoint?(cs("Upgrading socket connection to TLS"),kd.connect({...Od(Fd(t),"host","path","port"),socket:o})):o;o.destroy();let _=new qo.Socket({writable:!1});return _.readable=!0,e.once("socket",E=>{cs("Replaying proxy buffer for failed request"),(0,f_.default)(E.listenerCount("data")>0),E.push(d),E.push(null)}),_}};jo.protocols=["http","https"];Dt.HttpsProxyAgent=jo;function g_(r){r.resume()}function Od(r,...e){let t={},n;for(n in r)e.includes(n)||(t[n]=r[n]);return t}});function y_(r){if(!/^data:/i.test(r))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');r=r.replace(/\r?\n/g,"");let e=r.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");let t=r.substring(5,e).split(";"),n="",o=!1,a=t[0]||"text/plain",u=a;for(let d=1;d{Id=y_});var jd=z((Lo,qd)=>{(function(r,e){typeof Lo=="object"&&typeof qd<"u"?e(Lo):typeof define=="function"&&define.amd?define(["exports"],e):(r=typeof globalThis<"u"?globalThis:r||self,e(r.WebStreamsPolyfill={}))})(Lo,function(r){"use strict";function e(){}function t(s){return typeof s=="object"&&s!==null||typeof s=="function"}let n=e;function o(s,i){try{Object.defineProperty(s,"name",{value:i,configurable:!0})}catch{}}let a=Promise,u=Promise.prototype.then,l=Promise.reject.bind(a);function f(s){return new a(s)}function h(s){return f(i=>i(s))}function d(s){return l(s)}function _(s,i,c){return u.call(s,i,c)}function E(s,i,c){_(_(s,i,c),void 0,n)}function P(s,i){E(s,i)}function v(s,i){E(s,void 0,i)}function w(s,i,c){return _(s,i,c)}function g(s){_(s,void 0,n)}let C=s=>{if(typeof queueMicrotask=="function")C=queueMicrotask;else{let i=h(void 0);C=c=>_(i,c)}return C(s)};function R(s,i,c){if(typeof s!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(s,i,c)}function S(s,i,c){try{return h(R(s,i,c))}catch(m){return d(m)}}let N=16384;class j{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(i){let c=this._back,m=c;c._elements.length===N-1&&(m={_elements:[],_next:void 0}),c._elements.push(i),m!==c&&(this._back=m,c._next=m),++this._size}shift(){let i=this._front,c=i,m=this._cursor,A=m+1,I=i._elements,U=I[m];return A===N&&(c=i._next,A=0),--this._size,this._cursor=A,i!==c&&(this._front=c),I[m]=void 0,U}forEach(i){let c=this._cursor,m=this._front,A=m._elements;for(;(c!==A.length||m._next!==void 0)&&!(c===A.length&&(m=m._next,A=m._elements,c=0,A.length===0));)i(A[c]),++c}peek(){let i=this._front,c=this._cursor;return i._elements[c]}}let L=Symbol("[[AbortSteps]]"),H=Symbol("[[ErrorSteps]]"),K=Symbol("[[CancelSteps]]"),W=Symbol("[[PullSteps]]"),we=Symbol("[[ReleaseSteps]]");function de(s,i){s._ownerReadableStream=i,i._reader=s,i._state==="readable"?fe(s):i._state==="closed"?ae(s):Q(s,i._storedError)}function le(s,i){let c=s._ownerReadableStream;return Pt(c,i)}function ge(s){let i=s._ownerReadableStream;i._state==="readable"?J(s,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):ne(s,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),i._readableStreamController[we](),i._reader=void 0,s._ownerReadableStream=void 0}function te(s){return new TypeError("Cannot "+s+" a stream using a released reader")}function fe(s){s._closedPromise=f((i,c)=>{s._closedPromise_resolve=i,s._closedPromise_reject=c})}function Q(s,i){fe(s),J(s,i)}function ae(s){fe(s),se(s)}function J(s,i){s._closedPromise_reject!==void 0&&(g(s._closedPromise),s._closedPromise_reject(i),s._closedPromise_resolve=void 0,s._closedPromise_reject=void 0)}function ne(s,i){Q(s,i)}function se(s){s._closedPromise_resolve!==void 0&&(s._closedPromise_resolve(void 0),s._closedPromise_resolve=void 0,s._closedPromise_reject=void 0)}let Be=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},qe=Math.trunc||function(s){return s<0?Math.ceil(s):Math.floor(s)};function G(s){return typeof s=="object"||typeof s=="function"}function he(s,i){if(s!==void 0&&!G(s))throw new TypeError(`${i} is not an object.`)}function be(s,i){if(typeof s!="function")throw new TypeError(`${i} is not a function.`)}function rr(s){return typeof s=="object"&&s!==null||typeof s=="function"}function Pe(s,i){if(!rr(s))throw new TypeError(`${i} is not an object.`)}function Ie(s,i,c){if(s===void 0)throw new TypeError(`Parameter ${i} is required in '${c}'.`)}function p(s,i,c){if(s===void 0)throw new TypeError(`${i} is required in '${c}'.`)}function y(s){return Number(s)}function b(s){return s===0?0:s}function x(s){return b(qe(s))}function T(s,i){let m=Number.MAX_SAFE_INTEGER,A=Number(s);if(A=b(A),!Be(A))throw new TypeError(`${i} is not a finite number`);if(A=x(A),A<0||A>m)throw new TypeError(`${i} is outside the accepted range of 0 to ${m}, inclusive`);return!Be(A)||A===0?0:A}function F(s,i){if(!Sr(s))throw new TypeError(`${i} is not a ReadableStream.`)}function q(s){return new M(s)}function D(s,i){s._reader._readRequests.push(i)}function k(s,i,c){let A=s._reader._readRequests.shift();c?A._closeSteps():A._chunkSteps(i)}function B(s){return s._reader._readRequests.length}function O(s){let i=s._reader;return!(i===void 0||!Y(i))}class M{constructor(i){if(Ie(i,1,"ReadableStreamDefaultReader"),F(i,"First parameter"),vr(i))throw new TypeError("This stream has already been locked for exclusive reading by another reader");de(this,i),this._readRequests=new j}get closed(){return Y(this)?this._closedPromise:d(xe("closed"))}cancel(i=void 0){return Y(this)?this._ownerReadableStream===void 0?d(te("cancel")):le(this,i):d(xe("cancel"))}read(){if(!Y(this))return d(xe("read"));if(this._ownerReadableStream===void 0)return d(te("read from"));let i,c,m=f((I,U)=>{i=I,c=U});return X(this,{_chunkSteps:I=>i({value:I,done:!1}),_closeSteps:()=>i({value:void 0,done:!0}),_errorSteps:I=>c(I)}),m}releaseLock(){if(!Y(this))throw xe("releaseLock");this._ownerReadableStream!==void 0&&Ee(this)}}Object.defineProperties(M.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(M.prototype.cancel,"cancel"),o(M.prototype.read,"read"),o(M.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(M.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function Y(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_readRequests")?!1:s instanceof M}function X(s,i){let c=s._ownerReadableStream;c._disturbed=!0,c._state==="closed"?i._closeSteps():c._state==="errored"?i._errorSteps(c._storedError):c._readableStreamController[W](i)}function Ee(s){ge(s);let i=new TypeError("Reader was released");ke(s,i)}function ke(s,i){let c=s._readRequests;s._readRequests=new j,c.forEach(m=>{m._errorSteps(i)})}function xe(s){return new TypeError(`ReadableStreamDefaultReader.prototype.${s} can only be used on a ReadableStreamDefaultReader`)}let Ce=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class Ae{constructor(i,c){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=i,this._preventCancel=c}next(){let i=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?w(this._ongoingPromise,i,i):i(),this._ongoingPromise}return(i){let c=()=>this._returnSteps(i);return this._ongoingPromise?w(this._ongoingPromise,c,c):c()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let i=this._reader,c,m,A=f((U,V)=>{c=U,m=V});return X(i,{_chunkSteps:U=>{this._ongoingPromise=void 0,C(()=>c({value:U,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,ge(i),c({value:void 0,done:!0})},_errorSteps:U=>{this._ongoingPromise=void 0,this._isFinished=!0,ge(i),m(U)}}),A}_returnSteps(i){if(this._isFinished)return Promise.resolve({value:i,done:!0});this._isFinished=!0;let c=this._reader;if(!this._preventCancel){let m=le(c,i);return ge(c),w(m,()=>({value:i,done:!0}))}return ge(c),h({value:i,done:!0})}}let je={next(){return cn(this)?this._asyncIteratorImpl.next():d(ln("next"))},return(s){return cn(this)?this._asyncIteratorImpl.return(s):d(ln("return"))}};Object.setPrototypeOf(je,Ce);function un(s,i){let c=q(s),m=new Ae(c,i),A=Object.create(je);return A._asyncIteratorImpl=m,A}function cn(s){if(!t(s)||!Object.prototype.hasOwnProperty.call(s,"_asyncIteratorImpl"))return!1;try{return s._asyncIteratorImpl instanceof Ae}catch{return!1}}function ln(s){return new TypeError(`ReadableStreamAsyncIterator.${s} can only be used on a ReadableSteamAsyncIterator`)}let ut=Number.isNaN||function(s){return s!==s};var nr,Ve,Le;function De(s){return s.slice()}function Dl(s,i,c,m,A){new Uint8Array(s).set(new Uint8Array(c,m,A),i)}let sr=s=>(typeof s.transfer=="function"?sr=i=>i.transfer():typeof structuredClone=="function"?sr=i=>structuredClone(i,{transfer:[i]}):sr=i=>i,sr(s)),Er=s=>(typeof s.detached=="boolean"?Er=i=>i.detached:Er=i=>i.byteLength===0,Er(s));function Sl(s,i,c){if(s.slice)return s.slice(i,c);let m=c-i,A=new ArrayBuffer(m);return Dl(A,0,s,i,m),A}function Ms(s,i){let c=s[i];if(c!=null){if(typeof c!="function")throw new TypeError(`${String(i)} is not a function`);return c}}function pg(s){let i={[Symbol.iterator]:()=>s.iterator},c=async function*(){return yield*i}(),m=c.next;return{iterator:c,nextMethod:m,done:!1}}let ua=(Le=(nr=Symbol.asyncIterator)!==null&&nr!==void 0?nr:(Ve=Symbol.for)===null||Ve===void 0?void 0:Ve.call(Symbol,"Symbol.asyncIterator"))!==null&&Le!==void 0?Le:"@@asyncIterator";function vl(s,i="sync",c){if(c===void 0)if(i==="async"){if(c=Ms(s,ua),c===void 0){let I=Ms(s,Symbol.iterator),U=vl(s,"sync",I);return pg(U)}}else c=Ms(s,Symbol.iterator);if(c===void 0)throw new TypeError("The object is not iterable");let m=R(c,s,[]);if(!t(m))throw new TypeError("The iterator method must return an object");let A=m.next;return{iterator:m,nextMethod:A,done:!1}}function mg(s){let i=R(s.nextMethod,s.iterator,[]);if(!t(i))throw new TypeError("The iterator.next() method must return an object");return i}function gg(s){return!!s.done}function yg(s){return s.value}function _g(s){return!(typeof s!="number"||ut(s)||s<0)}function Tl(s){let i=Sl(s.buffer,s.byteOffset,s.byteOffset+s.byteLength);return new Uint8Array(i)}function ca(s){let i=s._queue.shift();return s._queueTotalSize-=i.size,s._queueTotalSize<0&&(s._queueTotalSize=0),i.value}function la(s,i,c){if(!_g(c)||c===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");s._queue.push({value:i,size:c}),s._queueTotalSize+=c}function Cg(s){return s._queue.peek().value}function wr(s){s._queue=new j,s._queueTotalSize=0}function Rl(s){return s===DataView}function bg(s){return Rl(s.constructor)}function Eg(s){return Rl(s)?1:s.BYTES_PER_ELEMENT}class Ur{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!fa(this))throw ga("view");return this._view}respond(i){if(!fa(this))throw ga("respond");if(Ie(i,1,"respond"),i=T(i,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Er(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");Ws(this._associatedReadableByteStreamController,i)}respondWithNewView(i){if(!fa(this))throw ga("respondWithNewView");if(Ie(i,1,"respondWithNewView"),!ArrayBuffer.isView(i))throw new TypeError("You can only respond with array buffer views");if(this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Er(i.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");zs(this._associatedReadableByteStreamController,i)}}Object.defineProperties(Ur.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),o(Ur.prototype.respond,"respond"),o(Ur.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ur.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class or{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Mr(this))throw Qn("byobRequest");return ma(this)}get desiredSize(){if(!Mr(this))throw Qn("desiredSize");return jl(this)}close(){if(!Mr(this))throw Qn("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let i=this._controlledReadableByteStream._state;if(i!=="readable")throw new TypeError(`The stream (in ${i} state) is not in the readable state and cannot be closed`);Xn(this)}enqueue(i){if(!Mr(this))throw Qn("enqueue");if(Ie(i,1,"enqueue"),!ArrayBuffer.isView(i))throw new TypeError("chunk must be an array buffer view");if(i.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(i.buffer.byteLength===0)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");let c=this._controlledReadableByteStream._state;if(c!=="readable")throw new TypeError(`The stream (in ${c} state) is not in the readable state and cannot be enqueued to`);Gs(this,i)}error(i=void 0){if(!Mr(this))throw Qn("error");Et(this,i)}[K](i){kl(this),wr(this);let c=this._cancelAlgorithm(i);return Hs(this),c}[W](i){let c=this._controlledReadableByteStream;if(this._queueTotalSize>0){ql(this,i);return}let m=this._autoAllocateChunkSize;if(m!==void 0){let A;try{A=new ArrayBuffer(m)}catch(U){i._errorSteps(U);return}let I={buffer:A,bufferByteLength:m,byteOffset:0,byteLength:m,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(I)}D(c,i),$r(this)}[we](){if(this._pendingPullIntos.length>0){let i=this._pendingPullIntos.peek();i.readerType="none",this._pendingPullIntos=new j,this._pendingPullIntos.push(i)}}}Object.defineProperties(or.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),o(or.prototype.close,"close"),o(or.prototype.enqueue,"enqueue"),o(or.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(or.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function Mr(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_controlledReadableByteStream")?!1:s instanceof or}function fa(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_associatedReadableByteStreamController")?!1:s instanceof Ur}function $r(s){if(!vg(s))return;if(s._pulling){s._pullAgain=!0;return}s._pulling=!0;let c=s._pullAlgorithm();E(c,()=>(s._pulling=!1,s._pullAgain&&(s._pullAgain=!1,$r(s)),null),m=>(Et(s,m),null))}function kl(s){ha(s),s._pendingPullIntos=new j}function da(s,i){let c=!1;s._state==="closed"&&(c=!0);let m=Fl(i);i.readerType==="default"?k(s,m,c):Pg(s,m,c)}function Fl(s){let i=s.bytesFilled,c=s.elementSize;return new s.viewConstructor(s.buffer,s.byteOffset,i/c)}function $s(s,i,c,m){s._queue.push({buffer:i,byteOffset:c,byteLength:m}),s._queueTotalSize+=m}function Ol(s,i,c,m){let A;try{A=Sl(i,c,c+m)}catch(I){throw Et(s,I),I}$s(s,A,0,m)}function Pl(s,i){i.bytesFilled>0&&Ol(s,i.buffer,i.byteOffset,i.bytesFilled),fn(s)}function xl(s,i){let c=Math.min(s._queueTotalSize,i.byteLength-i.bytesFilled),m=i.bytesFilled+c,A=c,I=!1,U=m%i.elementSize,V=m-U;V>=i.minimumFill&&(A=V-i.bytesFilled,I=!0);let ie=s._queue;for(;A>0;){let ee=ie.peek(),ue=Math.min(A,ee.byteLength),me=i.byteOffset+i.bytesFilled;Dl(i.buffer,me,ee.buffer,ee.byteOffset,ue),ee.byteLength===ue?ie.shift():(ee.byteOffset+=ue,ee.byteLength-=ue),s._queueTotalSize-=ue,Bl(s,ue,i),A-=ue}return I}function Bl(s,i,c){c.bytesFilled+=i}function Il(s){s._queueTotalSize===0&&s._closeRequested?(Hs(s),ss(s._controlledReadableByteStream)):$r(s)}function ha(s){s._byobRequest!==null&&(s._byobRequest._associatedReadableByteStreamController=void 0,s._byobRequest._view=null,s._byobRequest=null)}function pa(s){for(;s._pendingPullIntos.length>0;){if(s._queueTotalSize===0)return;let i=s._pendingPullIntos.peek();xl(s,i)&&(fn(s),da(s._controlledReadableByteStream,i))}}function wg(s){let i=s._controlledReadableByteStream._reader;for(;i._readRequests.length>0;){if(s._queueTotalSize===0)return;let c=i._readRequests.shift();ql(s,c)}}function Ag(s,i,c,m){let A=s._controlledReadableByteStream,I=i.constructor,U=Eg(I),{byteOffset:V,byteLength:ie}=i,ee=c*U,ue;try{ue=sr(i.buffer)}catch(ve){m._errorSteps(ve);return}let me={buffer:ue,bufferByteLength:ue.byteLength,byteOffset:V,byteLength:ie,bytesFilled:0,minimumFill:ee,elementSize:U,viewConstructor:I,readerType:"byob"};if(s._pendingPullIntos.length>0){s._pendingPullIntos.push(me),Ml(A,m);return}if(A._state==="closed"){let ve=new I(me.buffer,me.byteOffset,0);m._closeSteps(ve);return}if(s._queueTotalSize>0){if(xl(s,me)){let ve=Fl(me);Il(s),m._chunkSteps(ve);return}if(s._closeRequested){let ve=new TypeError("Insufficient bytes to fill elements in the given buffer");Et(s,ve),m._errorSteps(ve);return}}s._pendingPullIntos.push(me),Ml(A,m),$r(s)}function Dg(s,i){i.readerType==="none"&&fn(s);let c=s._controlledReadableByteStream;if(ya(c))for(;$l(c)>0;){let m=fn(s);da(c,m)}}function Sg(s,i,c){if(Bl(s,i,c),c.readerType==="none"){Pl(s,c),pa(s);return}if(c.bytesFilled0){let A=c.byteOffset+c.bytesFilled;Ol(s,c.buffer,A-m,m)}c.bytesFilled-=m,da(s._controlledReadableByteStream,c),pa(s)}function Nl(s,i){let c=s._pendingPullIntos.peek();ha(s),s._controlledReadableByteStream._state==="closed"?Dg(s,c):Sg(s,i,c),$r(s)}function fn(s){return s._pendingPullIntos.shift()}function vg(s){let i=s._controlledReadableByteStream;return i._state!=="readable"||s._closeRequested||!s._started?!1:!!(O(i)&&B(i)>0||ya(i)&&$l(i)>0||jl(s)>0)}function Hs(s){s._pullAlgorithm=void 0,s._cancelAlgorithm=void 0}function Xn(s){let i=s._controlledReadableByteStream;if(!(s._closeRequested||i._state!=="readable")){if(s._queueTotalSize>0){s._closeRequested=!0;return}if(s._pendingPullIntos.length>0){let c=s._pendingPullIntos.peek();if(c.bytesFilled%c.elementSize!==0){let m=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Et(s,m),m}}Hs(s),ss(i)}}function Gs(s,i){let c=s._controlledReadableByteStream;if(s._closeRequested||c._state!=="readable")return;let{buffer:m,byteOffset:A,byteLength:I}=i;if(Er(m))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let U=sr(m);if(s._pendingPullIntos.length>0){let V=s._pendingPullIntos.peek();if(Er(V.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");ha(s),V.buffer=sr(V.buffer),V.readerType==="none"&&Pl(s,V)}if(O(c))if(wg(s),B(c)===0)$s(s,U,A,I);else{s._pendingPullIntos.length>0&&fn(s);let V=new Uint8Array(U,A,I);k(c,V,!1)}else ya(c)?($s(s,U,A,I),pa(s)):$s(s,U,A,I);$r(s)}function Et(s,i){let c=s._controlledReadableByteStream;c._state==="readable"&&(kl(s),wr(s),Hs(s),hf(c,i))}function ql(s,i){let c=s._queue.shift();s._queueTotalSize-=c.byteLength,Il(s);let m=new Uint8Array(c.buffer,c.byteOffset,c.byteLength);i._chunkSteps(m)}function ma(s){if(s._byobRequest===null&&s._pendingPullIntos.length>0){let i=s._pendingPullIntos.peek(),c=new Uint8Array(i.buffer,i.byteOffset+i.bytesFilled,i.byteLength-i.bytesFilled),m=Object.create(Ur.prototype);Rg(m,s,c),s._byobRequest=m}return s._byobRequest}function jl(s){let i=s._controlledReadableByteStream._state;return i==="errored"?null:i==="closed"?0:s._strategyHWM-s._queueTotalSize}function Ws(s,i){let c=s._pendingPullIntos.peek();if(s._controlledReadableByteStream._state==="closed"){if(i!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(i===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(c.bytesFilled+i>c.byteLength)throw new RangeError("bytesWritten out of range")}c.buffer=sr(c.buffer),Nl(s,i)}function zs(s,i){let c=s._pendingPullIntos.peek();if(s._controlledReadableByteStream._state==="closed"){if(i.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(i.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(c.byteOffset+c.bytesFilled!==i.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(c.bufferByteLength!==i.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(c.bytesFilled+i.byteLength>c.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let A=i.byteLength;c.buffer=sr(i.buffer),Nl(s,A)}function Ll(s,i,c,m,A,I,U){i._controlledReadableByteStream=s,i._pullAgain=!1,i._pulling=!1,i._byobRequest=null,i._queue=i._queueTotalSize=void 0,wr(i),i._closeRequested=!1,i._started=!1,i._strategyHWM=I,i._pullAlgorithm=m,i._cancelAlgorithm=A,i._autoAllocateChunkSize=U,i._pendingPullIntos=new j,s._readableStreamController=i;let V=c();E(h(V),()=>(i._started=!0,$r(i),null),ie=>(Et(i,ie),null))}function Tg(s,i,c){let m=Object.create(or.prototype),A,I,U;i.start!==void 0?A=()=>i.start(m):A=()=>{},i.pull!==void 0?I=()=>i.pull(m):I=()=>h(void 0),i.cancel!==void 0?U=ie=>i.cancel(ie):U=()=>h(void 0);let V=i.autoAllocateChunkSize;if(V===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");Ll(s,m,A,I,U,c,V)}function Rg(s,i,c){s._associatedReadableByteStreamController=i,s._view=c}function ga(s){return new TypeError(`ReadableStreamBYOBRequest.prototype.${s} can only be used on a ReadableStreamBYOBRequest`)}function Qn(s){return new TypeError(`ReadableByteStreamController.prototype.${s} can only be used on a ReadableByteStreamController`)}function kg(s,i){he(s,i);let c=s?.mode;return{mode:c===void 0?void 0:Fg(c,`${i} has member 'mode' that`)}}function Fg(s,i){if(s=`${s}`,s!=="byob")throw new TypeError(`${i} '${s}' is not a valid enumeration value for ReadableStreamReaderMode`);return s}function Og(s,i){var c;he(s,i);let m=(c=s?.min)!==null&&c!==void 0?c:1;return{min:T(m,`${i} has member 'min' that`)}}function Ul(s){return new Ar(s)}function Ml(s,i){s._reader._readIntoRequests.push(i)}function Pg(s,i,c){let A=s._reader._readIntoRequests.shift();c?A._closeSteps(i):A._chunkSteps(i)}function $l(s){return s._reader._readIntoRequests.length}function ya(s){let i=s._reader;return!(i===void 0||!Hr(i))}class Ar{constructor(i){if(Ie(i,1,"ReadableStreamBYOBReader"),F(i,"First parameter"),vr(i))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Mr(i._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");de(this,i),this._readIntoRequests=new j}get closed(){return Hr(this)?this._closedPromise:d(Js("closed"))}cancel(i=void 0){return Hr(this)?this._ownerReadableStream===void 0?d(te("cancel")):le(this,i):d(Js("cancel"))}read(i,c={}){if(!Hr(this))return d(Js("read"));if(!ArrayBuffer.isView(i))return d(new TypeError("view must be an array buffer view"));if(i.byteLength===0)return d(new TypeError("view must have non-zero byteLength"));if(i.buffer.byteLength===0)return d(new TypeError("view's buffer must have non-zero byteLength"));if(Er(i.buffer))return d(new TypeError("view's buffer has been detached"));let m;try{m=Og(c,"options")}catch(ee){return d(ee)}let A=m.min;if(A===0)return d(new TypeError("options.min must be greater than 0"));if(bg(i)){if(A>i.byteLength)return d(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(A>i.length)return d(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return d(te("read from"));let I,U,V=f((ee,ue)=>{I=ee,U=ue});return Hl(this,i,A,{_chunkSteps:ee=>I({value:ee,done:!1}),_closeSteps:ee=>I({value:ee,done:!0}),_errorSteps:ee=>U(ee)}),V}releaseLock(){if(!Hr(this))throw Js("releaseLock");this._ownerReadableStream!==void 0&&xg(this)}}Object.defineProperties(Ar.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(Ar.prototype.cancel,"cancel"),o(Ar.prototype.read,"read"),o(Ar.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ar.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function Hr(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_readIntoRequests")?!1:s instanceof Ar}function Hl(s,i,c,m){let A=s._ownerReadableStream;A._disturbed=!0,A._state==="errored"?m._errorSteps(A._storedError):Ag(A._readableStreamController,i,c,m)}function xg(s){ge(s);let i=new TypeError("Reader was released");Gl(s,i)}function Gl(s,i){let c=s._readIntoRequests;s._readIntoRequests=new j,c.forEach(m=>{m._errorSteps(i)})}function Js(s){return new TypeError(`ReadableStreamBYOBReader.prototype.${s} can only be used on a ReadableStreamBYOBReader`)}function Zn(s,i){let{highWaterMark:c}=s;if(c===void 0)return i;if(ut(c)||c<0)throw new RangeError("Invalid highWaterMark");return c}function Vs(s){let{size:i}=s;return i||(()=>1)}function Ks(s,i){he(s,i);let c=s?.highWaterMark,m=s?.size;return{highWaterMark:c===void 0?void 0:y(c),size:m===void 0?void 0:Bg(m,`${i} has member 'size' that`)}}function Bg(s,i){return be(s,i),c=>y(s(c))}function Ig(s,i){he(s,i);let c=s?.abort,m=s?.close,A=s?.start,I=s?.type,U=s?.write;return{abort:c===void 0?void 0:Ng(c,s,`${i} has member 'abort' that`),close:m===void 0?void 0:qg(m,s,`${i} has member 'close' that`),start:A===void 0?void 0:jg(A,s,`${i} has member 'start' that`),write:U===void 0?void 0:Lg(U,s,`${i} has member 'write' that`),type:I}}function Ng(s,i,c){return be(s,c),m=>S(s,i,[m])}function qg(s,i,c){return be(s,c),()=>S(s,i,[])}function jg(s,i,c){return be(s,c),m=>R(s,i,[m])}function Lg(s,i,c){return be(s,c),(m,A)=>S(s,i,[m,A])}function Wl(s,i){if(!dn(s))throw new TypeError(`${i} is not a WritableStream.`)}function Ug(s){if(typeof s!="object"||s===null)return!1;try{return typeof s.aborted=="boolean"}catch{return!1}}let Mg=typeof AbortController=="function";function $g(){if(Mg)return new AbortController}class Dr{constructor(i={},c={}){i===void 0?i=null:Pe(i,"First parameter");let m=Ks(c,"Second parameter"),A=Ig(i,"First parameter");if(Jl(this),A.type!==void 0)throw new RangeError("Invalid type is specified");let U=Vs(m),V=Zn(m,1);ry(this,A,V,U)}get locked(){if(!dn(this))throw eo("locked");return hn(this)}abort(i=void 0){return dn(this)?hn(this)?d(new TypeError("Cannot abort a stream that already has a writer")):Ys(this,i):d(eo("abort"))}close(){return dn(this)?hn(this)?d(new TypeError("Cannot close a stream that already has a writer")):Wt(this)?d(new TypeError("Cannot close an already-closing stream")):Vl(this):d(eo("close"))}getWriter(){if(!dn(this))throw eo("getWriter");return zl(this)}}Object.defineProperties(Dr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),o(Dr.prototype.abort,"abort"),o(Dr.prototype.close,"close"),o(Dr.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Dr.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function zl(s){return new ir(s)}function Hg(s,i,c,m,A=1,I=()=>1){let U=Object.create(Dr.prototype);Jl(U);let V=Object.create(pn.prototype);return ef(U,V,s,i,c,m,A,I),U}function Jl(s){s._state="writable",s._storedError=void 0,s._writer=void 0,s._writableStreamController=void 0,s._writeRequests=new j,s._inFlightWriteRequest=void 0,s._closeRequest=void 0,s._inFlightCloseRequest=void 0,s._pendingAbortRequest=void 0,s._backpressure=!1}function dn(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_writableStreamController")?!1:s instanceof Dr}function hn(s){return s._writer!==void 0}function Ys(s,i){var c;if(s._state==="closed"||s._state==="errored")return h(void 0);s._writableStreamController._abortReason=i,(c=s._writableStreamController._abortController)===null||c===void 0||c.abort(i);let m=s._state;if(m==="closed"||m==="errored")return h(void 0);if(s._pendingAbortRequest!==void 0)return s._pendingAbortRequest._promise;let A=!1;m==="erroring"&&(A=!0,i=void 0);let I=f((U,V)=>{s._pendingAbortRequest={_promise:void 0,_resolve:U,_reject:V,_reason:i,_wasAlreadyErroring:A}});return s._pendingAbortRequest._promise=I,A||Ca(s,i),I}function Vl(s){let i=s._state;if(i==="closed"||i==="errored")return d(new TypeError(`The stream (in ${i} state) is not in the writable state and cannot be closed`));let c=f((A,I)=>{let U={_resolve:A,_reject:I};s._closeRequest=U}),m=s._writer;return m!==void 0&&s._backpressure&&i==="writable"&&Ta(m),ny(s._writableStreamController),c}function Gg(s){return f((c,m)=>{let A={_resolve:c,_reject:m};s._writeRequests.push(A)})}function _a(s,i){if(s._state==="writable"){Ca(s,i);return}ba(s)}function Ca(s,i){let c=s._writableStreamController;s._state="erroring",s._storedError=i;let m=s._writer;m!==void 0&&Yl(m,i),!Kg(s)&&c._started&&ba(s)}function ba(s){s._state="errored",s._writableStreamController[H]();let i=s._storedError;if(s._writeRequests.forEach(A=>{A._reject(i)}),s._writeRequests=new j,s._pendingAbortRequest===void 0){Xs(s);return}let c=s._pendingAbortRequest;if(s._pendingAbortRequest=void 0,c._wasAlreadyErroring){c._reject(i),Xs(s);return}let m=s._writableStreamController[L](c._reason);E(m,()=>(c._resolve(),Xs(s),null),A=>(c._reject(A),Xs(s),null))}function Wg(s){s._inFlightWriteRequest._resolve(void 0),s._inFlightWriteRequest=void 0}function zg(s,i){s._inFlightWriteRequest._reject(i),s._inFlightWriteRequest=void 0,_a(s,i)}function Jg(s){s._inFlightCloseRequest._resolve(void 0),s._inFlightCloseRequest=void 0,s._state==="erroring"&&(s._storedError=void 0,s._pendingAbortRequest!==void 0&&(s._pendingAbortRequest._resolve(),s._pendingAbortRequest=void 0)),s._state="closed";let c=s._writer;c!==void 0&&sf(c)}function Vg(s,i){s._inFlightCloseRequest._reject(i),s._inFlightCloseRequest=void 0,s._pendingAbortRequest!==void 0&&(s._pendingAbortRequest._reject(i),s._pendingAbortRequest=void 0),_a(s,i)}function Wt(s){return!(s._closeRequest===void 0&&s._inFlightCloseRequest===void 0)}function Kg(s){return!(s._inFlightWriteRequest===void 0&&s._inFlightCloseRequest===void 0)}function Yg(s){s._inFlightCloseRequest=s._closeRequest,s._closeRequest=void 0}function Xg(s){s._inFlightWriteRequest=s._writeRequests.shift()}function Xs(s){s._closeRequest!==void 0&&(s._closeRequest._reject(s._storedError),s._closeRequest=void 0);let i=s._writer;i!==void 0&&Sa(i,s._storedError)}function Ea(s,i){let c=s._writer;c!==void 0&&i!==s._backpressure&&(i?ly(c):Ta(c)),s._backpressure=i}class ir{constructor(i){if(Ie(i,1,"WritableStreamDefaultWriter"),Wl(i,"First parameter"),hn(i))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=i,i._writer=this;let c=i._state;if(c==="writable")!Wt(i)&&i._backpressure?ro(this):of(this),to(this);else if(c==="erroring")va(this,i._storedError),to(this);else if(c==="closed")of(this),uy(this);else{let m=i._storedError;va(this,m),nf(this,m)}}get closed(){return Gr(this)?this._closedPromise:d(Wr("closed"))}get desiredSize(){if(!Gr(this))throw Wr("desiredSize");if(this._ownerWritableStream===void 0)throw ts("desiredSize");return ty(this)}get ready(){return Gr(this)?this._readyPromise:d(Wr("ready"))}abort(i=void 0){return Gr(this)?this._ownerWritableStream===void 0?d(ts("abort")):Qg(this,i):d(Wr("abort"))}close(){if(!Gr(this))return d(Wr("close"));let i=this._ownerWritableStream;return i===void 0?d(ts("close")):Wt(i)?d(new TypeError("Cannot close an already-closing stream")):Kl(this)}releaseLock(){if(!Gr(this))throw Wr("releaseLock");this._ownerWritableStream!==void 0&&Xl(this)}write(i=void 0){return Gr(this)?this._ownerWritableStream===void 0?d(ts("write to")):Ql(this,i):d(Wr("write"))}}Object.defineProperties(ir.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),o(ir.prototype.abort,"abort"),o(ir.prototype.close,"close"),o(ir.prototype.releaseLock,"releaseLock"),o(ir.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ir.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function Gr(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_ownerWritableStream")?!1:s instanceof ir}function Qg(s,i){let c=s._ownerWritableStream;return Ys(c,i)}function Kl(s){let i=s._ownerWritableStream;return Vl(i)}function Zg(s){let i=s._ownerWritableStream,c=i._state;return Wt(i)||c==="closed"?h(void 0):c==="errored"?d(i._storedError):Kl(s)}function ey(s,i){s._closedPromiseState==="pending"?Sa(s,i):cy(s,i)}function Yl(s,i){s._readyPromiseState==="pending"?af(s,i):fy(s,i)}function ty(s){let i=s._ownerWritableStream,c=i._state;return c==="errored"||c==="erroring"?null:c==="closed"?0:tf(i._writableStreamController)}function Xl(s){let i=s._ownerWritableStream,c=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");Yl(s,c),ey(s,c),i._writer=void 0,s._ownerWritableStream=void 0}function Ql(s,i){let c=s._ownerWritableStream,m=c._writableStreamController,A=sy(m,i);if(c!==s._ownerWritableStream)return d(ts("write to"));let I=c._state;if(I==="errored")return d(c._storedError);if(Wt(c)||I==="closed")return d(new TypeError("The stream is closing or closed and cannot be written to"));if(I==="erroring")return d(c._storedError);let U=Gg(c);return oy(m,i,A),U}let Zl={};class pn{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!wa(this))throw Da("abortReason");return this._abortReason}get signal(){if(!wa(this))throw Da("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(i=void 0){if(!wa(this))throw Da("error");this._controlledWritableStream._state==="writable"&&rf(this,i)}[L](i){let c=this._abortAlgorithm(i);return Qs(this),c}[H](){wr(this)}}Object.defineProperties(pn.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(pn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function wa(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_controlledWritableStream")?!1:s instanceof pn}function ef(s,i,c,m,A,I,U,V){i._controlledWritableStream=s,s._writableStreamController=i,i._queue=void 0,i._queueTotalSize=void 0,wr(i),i._abortReason=void 0,i._abortController=$g(),i._started=!1,i._strategySizeAlgorithm=V,i._strategyHWM=U,i._writeAlgorithm=m,i._closeAlgorithm=A,i._abortAlgorithm=I;let ie=Aa(i);Ea(s,ie);let ee=c(),ue=h(ee);E(ue,()=>(i._started=!0,Zs(i),null),me=>(i._started=!0,_a(s,me),null))}function ry(s,i,c,m){let A=Object.create(pn.prototype),I,U,V,ie;i.start!==void 0?I=()=>i.start(A):I=()=>{},i.write!==void 0?U=ee=>i.write(ee,A):U=()=>h(void 0),i.close!==void 0?V=()=>i.close():V=()=>h(void 0),i.abort!==void 0?ie=ee=>i.abort(ee):ie=()=>h(void 0),ef(s,A,I,U,V,ie,c,m)}function Qs(s){s._writeAlgorithm=void 0,s._closeAlgorithm=void 0,s._abortAlgorithm=void 0,s._strategySizeAlgorithm=void 0}function ny(s){la(s,Zl,0),Zs(s)}function sy(s,i){try{return s._strategySizeAlgorithm(i)}catch(c){return es(s,c),1}}function tf(s){return s._strategyHWM-s._queueTotalSize}function oy(s,i,c){try{la(s,i,c)}catch(A){es(s,A);return}let m=s._controlledWritableStream;if(!Wt(m)&&m._state==="writable"){let A=Aa(s);Ea(m,A)}Zs(s)}function Zs(s){let i=s._controlledWritableStream;if(!s._started||i._inFlightWriteRequest!==void 0)return;if(i._state==="erroring"){ba(i);return}if(s._queue.length===0)return;let m=Cg(s);m===Zl?iy(s):ay(s,m)}function es(s,i){s._controlledWritableStream._state==="writable"&&rf(s,i)}function iy(s){let i=s._controlledWritableStream;Yg(i),ca(s);let c=s._closeAlgorithm();Qs(s),E(c,()=>(Jg(i),null),m=>(Vg(i,m),null))}function ay(s,i){let c=s._controlledWritableStream;Xg(c);let m=s._writeAlgorithm(i);E(m,()=>{Wg(c);let A=c._state;if(ca(s),!Wt(c)&&A==="writable"){let I=Aa(s);Ea(c,I)}return Zs(s),null},A=>(c._state==="writable"&&Qs(s),zg(c,A),null))}function Aa(s){return tf(s)<=0}function rf(s,i){let c=s._controlledWritableStream;Qs(s),Ca(c,i)}function eo(s){return new TypeError(`WritableStream.prototype.${s} can only be used on a WritableStream`)}function Da(s){return new TypeError(`WritableStreamDefaultController.prototype.${s} can only be used on a WritableStreamDefaultController`)}function Wr(s){return new TypeError(`WritableStreamDefaultWriter.prototype.${s} can only be used on a WritableStreamDefaultWriter`)}function ts(s){return new TypeError("Cannot "+s+" a stream using a released writer")}function to(s){s._closedPromise=f((i,c)=>{s._closedPromise_resolve=i,s._closedPromise_reject=c,s._closedPromiseState="pending"})}function nf(s,i){to(s),Sa(s,i)}function uy(s){to(s),sf(s)}function Sa(s,i){s._closedPromise_reject!==void 0&&(g(s._closedPromise),s._closedPromise_reject(i),s._closedPromise_resolve=void 0,s._closedPromise_reject=void 0,s._closedPromiseState="rejected")}function cy(s,i){nf(s,i)}function sf(s){s._closedPromise_resolve!==void 0&&(s._closedPromise_resolve(void 0),s._closedPromise_resolve=void 0,s._closedPromise_reject=void 0,s._closedPromiseState="resolved")}function ro(s){s._readyPromise=f((i,c)=>{s._readyPromise_resolve=i,s._readyPromise_reject=c}),s._readyPromiseState="pending"}function va(s,i){ro(s),af(s,i)}function of(s){ro(s),Ta(s)}function af(s,i){s._readyPromise_reject!==void 0&&(g(s._readyPromise),s._readyPromise_reject(i),s._readyPromise_resolve=void 0,s._readyPromise_reject=void 0,s._readyPromiseState="rejected")}function ly(s){ro(s)}function fy(s,i){va(s,i)}function Ta(s){s._readyPromise_resolve!==void 0&&(s._readyPromise_resolve(void 0),s._readyPromise_resolve=void 0,s._readyPromise_reject=void 0,s._readyPromiseState="fulfilled")}function dy(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let Ra=dy();function hy(s){if(!(typeof s=="function"||typeof s=="object")||s.name!=="DOMException")return!1;try{return new s,!0}catch{return!1}}function py(){let s=Ra?.DOMException;return hy(s)?s:void 0}function my(){let s=function(c,m){this.message=c||"",this.name=m||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return o(s,"DOMException"),s.prototype=Object.create(Error.prototype),Object.defineProperty(s.prototype,"constructor",{value:s,writable:!0,configurable:!0}),s}let gy=py()||my();function uf(s,i,c,m,A,I){let U=q(s),V=zl(i);s._disturbed=!0;let ie=!1,ee=h(void 0);return f((ue,me)=>{let ve;if(I!==void 0){if(ve=()=>{let re=I.reason!==void 0?I.reason:new gy("Aborted","AbortError"),ye=[];m||ye.push(()=>i._state==="writable"?Ys(i,re):h(void 0)),A||ye.push(()=>s._state==="readable"?Pt(s,re):h(void 0)),rt(()=>Promise.all(ye.map(Te=>Te())),!0,re)},I.aborted){ve();return}I.addEventListener("abort",ve)}function xt(){return f((re,ye)=>{function Te(ct){ct?re():_(_n(),Te,ye)}Te(!1)})}function _n(){return ie?h(!0):_(V._readyPromise,()=>f((re,ye)=>{X(U,{_chunkSteps:Te=>{ee=_(Ql(V,Te),void 0,e),re(!1)},_closeSteps:()=>re(!0),_errorSteps:ye})}))}if(ur(s,U._closedPromise,re=>(m?wt(!0,re):rt(()=>Ys(i,re),!0,re),null)),ur(i,V._closedPromise,re=>(A?wt(!0,re):rt(()=>Pt(s,re),!0,re),null)),Qe(s,U._closedPromise,()=>(c?wt():rt(()=>Zg(V)),null)),Wt(i)||i._state==="closed"){let re=new TypeError("the destination writable stream closed before all data could be piped to it");A?wt(!0,re):rt(()=>Pt(s,re),!0,re)}g(xt());function Rr(){let re=ee;return _(ee,()=>re!==ee?Rr():void 0)}function ur(re,ye,Te){re._state==="errored"?Te(re._storedError):v(ye,Te)}function Qe(re,ye,Te){re._state==="closed"?Te():P(ye,Te)}function rt(re,ye,Te){if(ie)return;ie=!0,i._state==="writable"&&!Wt(i)?P(Rr(),ct):ct();function ct(){return E(re(),()=>cr(ye,Te),Cn=>cr(!0,Cn)),null}}function wt(re,ye){ie||(ie=!0,i._state==="writable"&&!Wt(i)?P(Rr(),()=>cr(re,ye)):cr(re,ye))}function cr(re,ye){return Xl(V),ge(U),I!==void 0&&I.removeEventListener("abort",ve),re?me(ye):ue(void 0),null}})}class ar{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!no(this))throw oo("desiredSize");return ka(this)}close(){if(!no(this))throw oo("close");if(!gn(this))throw new TypeError("The stream is not in a state that permits close");zr(this)}enqueue(i=void 0){if(!no(this))throw oo("enqueue");if(!gn(this))throw new TypeError("The stream is not in a state that permits enqueue");return mn(this,i)}error(i=void 0){if(!no(this))throw oo("error");Ot(this,i)}[K](i){wr(this);let c=this._cancelAlgorithm(i);return so(this),c}[W](i){let c=this._controlledReadableStream;if(this._queue.length>0){let m=ca(this);this._closeRequested&&this._queue.length===0?(so(this),ss(c)):rs(this),i._chunkSteps(m)}else D(c,i),rs(this)}[we](){}}Object.defineProperties(ar.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),o(ar.prototype.close,"close"),o(ar.prototype.enqueue,"enqueue"),o(ar.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ar.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function no(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_controlledReadableStream")?!1:s instanceof ar}function rs(s){if(!cf(s))return;if(s._pulling){s._pullAgain=!0;return}s._pulling=!0;let c=s._pullAlgorithm();E(c,()=>(s._pulling=!1,s._pullAgain&&(s._pullAgain=!1,rs(s)),null),m=>(Ot(s,m),null))}function cf(s){let i=s._controlledReadableStream;return!gn(s)||!s._started?!1:!!(vr(i)&&B(i)>0||ka(s)>0)}function so(s){s._pullAlgorithm=void 0,s._cancelAlgorithm=void 0,s._strategySizeAlgorithm=void 0}function zr(s){if(!gn(s))return;let i=s._controlledReadableStream;s._closeRequested=!0,s._queue.length===0&&(so(s),ss(i))}function mn(s,i){if(!gn(s))return;let c=s._controlledReadableStream;if(vr(c)&&B(c)>0)k(c,i,!1);else{let m;try{m=s._strategySizeAlgorithm(i)}catch(A){throw Ot(s,A),A}try{la(s,i,m)}catch(A){throw Ot(s,A),A}}rs(s)}function Ot(s,i){let c=s._controlledReadableStream;c._state==="readable"&&(wr(s),so(s),hf(c,i))}function ka(s){let i=s._controlledReadableStream._state;return i==="errored"?null:i==="closed"?0:s._strategyHWM-s._queueTotalSize}function yy(s){return!cf(s)}function gn(s){let i=s._controlledReadableStream._state;return!s._closeRequested&&i==="readable"}function lf(s,i,c,m,A,I,U){i._controlledReadableStream=s,i._queue=void 0,i._queueTotalSize=void 0,wr(i),i._started=!1,i._closeRequested=!1,i._pullAgain=!1,i._pulling=!1,i._strategySizeAlgorithm=U,i._strategyHWM=I,i._pullAlgorithm=m,i._cancelAlgorithm=A,s._readableStreamController=i;let V=c();E(h(V),()=>(i._started=!0,rs(i),null),ie=>(Ot(i,ie),null))}function _y(s,i,c,m){let A=Object.create(ar.prototype),I,U,V;i.start!==void 0?I=()=>i.start(A):I=()=>{},i.pull!==void 0?U=()=>i.pull(A):U=()=>h(void 0),i.cancel!==void 0?V=ie=>i.cancel(ie):V=()=>h(void 0),lf(s,A,I,U,V,c,m)}function oo(s){return new TypeError(`ReadableStreamDefaultController.prototype.${s} can only be used on a ReadableStreamDefaultController`)}function Cy(s,i){return Mr(s._readableStreamController)?Ey(s):by(s)}function by(s,i){let c=q(s),m=!1,A=!1,I=!1,U=!1,V,ie,ee,ue,me,ve=f(Qe=>{me=Qe});function xt(){return m?(A=!0,h(void 0)):(m=!0,X(c,{_chunkSteps:rt=>{C(()=>{A=!1;let wt=rt,cr=rt;I||mn(ee._readableStreamController,wt),U||mn(ue._readableStreamController,cr),m=!1,A&&xt()})},_closeSteps:()=>{m=!1,I||zr(ee._readableStreamController),U||zr(ue._readableStreamController),(!I||!U)&&me(void 0)},_errorSteps:()=>{m=!1}}),h(void 0))}function _n(Qe){if(I=!0,V=Qe,U){let rt=De([V,ie]),wt=Pt(s,rt);me(wt)}return ve}function Rr(Qe){if(U=!0,ie=Qe,I){let rt=De([V,ie]),wt=Pt(s,rt);me(wt)}return ve}function ur(){}return ee=ns(ur,xt,_n),ue=ns(ur,xt,Rr),v(c._closedPromise,Qe=>(Ot(ee._readableStreamController,Qe),Ot(ue._readableStreamController,Qe),(!I||!U)&&me(void 0),null)),[ee,ue]}function Ey(s){let i=q(s),c=!1,m=!1,A=!1,I=!1,U=!1,V,ie,ee,ue,me,ve=f(re=>{me=re});function xt(re){v(re._closedPromise,ye=>(re!==i||(Et(ee._readableStreamController,ye),Et(ue._readableStreamController,ye),(!I||!U)&&me(void 0)),null))}function _n(){Hr(i)&&(ge(i),i=q(s),xt(i)),X(i,{_chunkSteps:ye=>{C(()=>{m=!1,A=!1;let Te=ye,ct=ye;if(!I&&!U)try{ct=Tl(ye)}catch(Cn){Et(ee._readableStreamController,Cn),Et(ue._readableStreamController,Cn),me(Pt(s,Cn));return}I||Gs(ee._readableStreamController,Te),U||Gs(ue._readableStreamController,ct),c=!1,m?ur():A&&Qe()})},_closeSteps:()=>{c=!1,I||Xn(ee._readableStreamController),U||Xn(ue._readableStreamController),ee._readableStreamController._pendingPullIntos.length>0&&Ws(ee._readableStreamController,0),ue._readableStreamController._pendingPullIntos.length>0&&Ws(ue._readableStreamController,0),(!I||!U)&&me(void 0)},_errorSteps:()=>{c=!1}})}function Rr(re,ye){Y(i)&&(ge(i),i=Ul(s),xt(i));let Te=ye?ue:ee,ct=ye?ee:ue;Hl(i,re,1,{_chunkSteps:bn=>{C(()=>{m=!1,A=!1;let En=ye?U:I;if(ye?I:U)En||zs(Te._readableStreamController,bn);else{let vf;try{vf=Tl(bn)}catch(Ba){Et(Te._readableStreamController,Ba),Et(ct._readableStreamController,Ba),me(Pt(s,Ba));return}En||zs(Te._readableStreamController,bn),Gs(ct._readableStreamController,vf)}c=!1,m?ur():A&&Qe()})},_closeSteps:bn=>{c=!1;let En=ye?U:I,po=ye?I:U;En||Xn(Te._readableStreamController),po||Xn(ct._readableStreamController),bn!==void 0&&(En||zs(Te._readableStreamController,bn),!po&&ct._readableStreamController._pendingPullIntos.length>0&&Ws(ct._readableStreamController,0)),(!En||!po)&&me(void 0)},_errorSteps:()=>{c=!1}})}function ur(){if(c)return m=!0,h(void 0);c=!0;let re=ma(ee._readableStreamController);return re===null?_n():Rr(re._view,!1),h(void 0)}function Qe(){if(c)return A=!0,h(void 0);c=!0;let re=ma(ue._readableStreamController);return re===null?_n():Rr(re._view,!0),h(void 0)}function rt(re){if(I=!0,V=re,U){let ye=De([V,ie]),Te=Pt(s,ye);me(Te)}return ve}function wt(re){if(U=!0,ie=re,I){let ye=De([V,ie]),Te=Pt(s,ye);me(Te)}return ve}function cr(){}return ee=df(cr,ur,rt),ue=df(cr,Qe,wt),xt(i),[ee,ue]}function wy(s){return t(s)&&typeof s.getReader<"u"}function Ay(s){return wy(s)?Sy(s.getReader()):Dy(s)}function Dy(s){let i,c=vl(s,"async"),m=e;function A(){let U;try{U=mg(c)}catch(ie){return d(ie)}let V=h(U);return w(V,ie=>{if(!t(ie))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(gg(ie))zr(i._readableStreamController);else{let ue=yg(ie);mn(i._readableStreamController,ue)}})}function I(U){let V=c.iterator,ie;try{ie=Ms(V,"return")}catch(me){return d(me)}if(ie===void 0)return h(void 0);let ee;try{ee=R(ie,V,[U])}catch(me){return d(me)}let ue=h(ee);return w(ue,me=>{if(!t(me))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return i=ns(m,A,I,0),i}function Sy(s){let i,c=e;function m(){let I;try{I=s.read()}catch(U){return d(U)}return w(I,U=>{if(!t(U))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(U.done)zr(i._readableStreamController);else{let V=U.value;mn(i._readableStreamController,V)}})}function A(I){try{return h(s.cancel(I))}catch(U){return d(U)}}return i=ns(c,m,A,0),i}function vy(s,i){he(s,i);let c=s,m=c?.autoAllocateChunkSize,A=c?.cancel,I=c?.pull,U=c?.start,V=c?.type;return{autoAllocateChunkSize:m===void 0?void 0:T(m,`${i} has member 'autoAllocateChunkSize' that`),cancel:A===void 0?void 0:Ty(A,c,`${i} has member 'cancel' that`),pull:I===void 0?void 0:Ry(I,c,`${i} has member 'pull' that`),start:U===void 0?void 0:ky(U,c,`${i} has member 'start' that`),type:V===void 0?void 0:Fy(V,`${i} has member 'type' that`)}}function Ty(s,i,c){return be(s,c),m=>S(s,i,[m])}function Ry(s,i,c){return be(s,c),m=>S(s,i,[m])}function ky(s,i,c){return be(s,c),m=>R(s,i,[m])}function Fy(s,i){if(s=`${s}`,s!=="bytes")throw new TypeError(`${i} '${s}' is not a valid enumeration value for ReadableStreamType`);return s}function Oy(s,i){return he(s,i),{preventCancel:!!s?.preventCancel}}function ff(s,i){he(s,i);let c=s?.preventAbort,m=s?.preventCancel,A=s?.preventClose,I=s?.signal;return I!==void 0&&Py(I,`${i} has member 'signal' that`),{preventAbort:!!c,preventCancel:!!m,preventClose:!!A,signal:I}}function Py(s,i){if(!Ug(s))throw new TypeError(`${i} is not an AbortSignal.`)}function xy(s,i){he(s,i);let c=s?.readable;p(c,"readable","ReadableWritablePair"),F(c,`${i} has member 'readable' that`);let m=s?.writable;return p(m,"writable","ReadableWritablePair"),Wl(m,`${i} has member 'writable' that`),{readable:c,writable:m}}class Ke{constructor(i={},c={}){i===void 0?i=null:Pe(i,"First parameter");let m=Ks(c,"Second parameter"),A=vy(i,"First parameter");if(Fa(this),A.type==="bytes"){if(m.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let I=Zn(m,0);Tg(this,A,I)}else{let I=Vs(m),U=Zn(m,1);_y(this,A,U,I)}}get locked(){if(!Sr(this))throw Jr("locked");return vr(this)}cancel(i=void 0){return Sr(this)?vr(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):Pt(this,i):d(Jr("cancel"))}getReader(i=void 0){if(!Sr(this))throw Jr("getReader");return kg(i,"First parameter").mode===void 0?q(this):Ul(this)}pipeThrough(i,c={}){if(!Sr(this))throw Jr("pipeThrough");Ie(i,1,"pipeThrough");let m=xy(i,"First parameter"),A=ff(c,"Second parameter");if(vr(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(hn(m.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let I=uf(this,m.writable,A.preventClose,A.preventAbort,A.preventCancel,A.signal);return g(I),m.readable}pipeTo(i,c={}){if(!Sr(this))return d(Jr("pipeTo"));if(i===void 0)return d("Parameter 1 is required in 'pipeTo'.");if(!dn(i))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let m;try{m=ff(c,"Second parameter")}catch(A){return d(A)}return vr(this)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):hn(i)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):uf(this,i,m.preventClose,m.preventAbort,m.preventCancel,m.signal)}tee(){if(!Sr(this))throw Jr("tee");let i=Cy(this);return De(i)}values(i=void 0){if(!Sr(this))throw Jr("values");let c=Oy(i,"First parameter");return un(this,c.preventCancel)}[ua](i){return this.values(i)}static from(i){return Ay(i)}}Object.defineProperties(Ke,{from:{enumerable:!0}}),Object.defineProperties(Ke.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),o(Ke.from,"from"),o(Ke.prototype.cancel,"cancel"),o(Ke.prototype.getReader,"getReader"),o(Ke.prototype.pipeThrough,"pipeThrough"),o(Ke.prototype.pipeTo,"pipeTo"),o(Ke.prototype.tee,"tee"),o(Ke.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ke.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(Ke.prototype,ua,{value:Ke.prototype.values,writable:!0,configurable:!0});function ns(s,i,c,m=1,A=()=>1){let I=Object.create(Ke.prototype);Fa(I);let U=Object.create(ar.prototype);return lf(I,U,s,i,c,m,A),I}function df(s,i,c){let m=Object.create(Ke.prototype);Fa(m);let A=Object.create(or.prototype);return Ll(m,A,s,i,c,0,void 0),m}function Fa(s){s._state="readable",s._reader=void 0,s._storedError=void 0,s._disturbed=!1}function Sr(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_readableStreamController")?!1:s instanceof Ke}function vr(s){return s._reader!==void 0}function Pt(s,i){if(s._disturbed=!0,s._state==="closed")return h(void 0);if(s._state==="errored")return d(s._storedError);ss(s);let c=s._reader;if(c!==void 0&&Hr(c)){let A=c._readIntoRequests;c._readIntoRequests=new j,A.forEach(I=>{I._closeSteps(void 0)})}let m=s._readableStreamController[K](i);return w(m,e)}function ss(s){s._state="closed";let i=s._reader;if(i!==void 0&&(se(i),Y(i))){let c=i._readRequests;i._readRequests=new j,c.forEach(m=>{m._closeSteps()})}}function hf(s,i){s._state="errored",s._storedError=i;let c=s._reader;c!==void 0&&(J(c,i),Y(c)?ke(c,i):Gl(c,i))}function Jr(s){return new TypeError(`ReadableStream.prototype.${s} can only be used on a ReadableStream`)}function pf(s,i){he(s,i);let c=s?.highWaterMark;return p(c,"highWaterMark","QueuingStrategyInit"),{highWaterMark:y(c)}}let mf=s=>s.byteLength;o(mf,"size");class io{constructor(i){Ie(i,1,"ByteLengthQueuingStrategy"),i=pf(i,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=i.highWaterMark}get highWaterMark(){if(!yf(this))throw gf("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!yf(this))throw gf("size");return mf}}Object.defineProperties(io.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(io.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function gf(s){return new TypeError(`ByteLengthQueuingStrategy.prototype.${s} can only be used on a ByteLengthQueuingStrategy`)}function yf(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_byteLengthQueuingStrategyHighWaterMark")?!1:s instanceof io}let _f=()=>1;o(_f,"size");class ao{constructor(i){Ie(i,1,"CountQueuingStrategy"),i=pf(i,"First parameter"),this._countQueuingStrategyHighWaterMark=i.highWaterMark}get highWaterMark(){if(!bf(this))throw Cf("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!bf(this))throw Cf("size");return _f}}Object.defineProperties(ao.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ao.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function Cf(s){return new TypeError(`CountQueuingStrategy.prototype.${s} can only be used on a CountQueuingStrategy`)}function bf(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_countQueuingStrategyHighWaterMark")?!1:s instanceof ao}function By(s,i){he(s,i);let c=s?.cancel,m=s?.flush,A=s?.readableType,I=s?.start,U=s?.transform,V=s?.writableType;return{cancel:c===void 0?void 0:jy(c,s,`${i} has member 'cancel' that`),flush:m===void 0?void 0:Iy(m,s,`${i} has member 'flush' that`),readableType:A,start:I===void 0?void 0:Ny(I,s,`${i} has member 'start' that`),transform:U===void 0?void 0:qy(U,s,`${i} has member 'transform' that`),writableType:V}}function Iy(s,i,c){return be(s,c),m=>S(s,i,[m])}function Ny(s,i,c){return be(s,c),m=>R(s,i,[m])}function qy(s,i,c){return be(s,c),(m,A)=>S(s,i,[m,A])}function jy(s,i,c){return be(s,c),m=>S(s,i,[m])}class uo{constructor(i={},c={},m={}){i===void 0&&(i=null);let A=Ks(c,"Second parameter"),I=Ks(m,"Third parameter"),U=By(i,"First parameter");if(U.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(U.writableType!==void 0)throw new RangeError("Invalid writableType specified");let V=Zn(I,0),ie=Vs(I),ee=Zn(A,1),ue=Vs(A),me,ve=f(xt=>{me=xt});Ly(this,ve,ee,ue,V,ie),My(this,U),U.start!==void 0?me(U.start(this._transformStreamController)):me(void 0)}get readable(){if(!Ef(this))throw Sf("readable");return this._readable}get writable(){if(!Ef(this))throw Sf("writable");return this._writable}}Object.defineProperties(uo.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(uo.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function Ly(s,i,c,m,A,I){function U(){return i}function V(ve){return Gy(s,ve)}function ie(ve){return Wy(s,ve)}function ee(){return zy(s)}s._writable=Hg(U,V,ee,ie,c,m);function ue(){return Jy(s)}function me(ve){return Vy(s,ve)}s._readable=ns(U,ue,me,A,I),s._backpressure=void 0,s._backpressureChangePromise=void 0,s._backpressureChangePromise_resolve=void 0,co(s,!0),s._transformStreamController=void 0}function Ef(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_transformStreamController")?!1:s instanceof uo}function wf(s,i){Ot(s._readable._readableStreamController,i),Oa(s,i)}function Oa(s,i){fo(s._transformStreamController),es(s._writable._writableStreamController,i),Pa(s)}function Pa(s){s._backpressure&&co(s,!1)}function co(s,i){s._backpressureChangePromise!==void 0&&s._backpressureChangePromise_resolve(),s._backpressureChangePromise=f(c=>{s._backpressureChangePromise_resolve=c}),s._backpressure=i}class Tr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!lo(this))throw ho("desiredSize");let i=this._controlledTransformStream._readable._readableStreamController;return ka(i)}enqueue(i=void 0){if(!lo(this))throw ho("enqueue");Af(this,i)}error(i=void 0){if(!lo(this))throw ho("error");$y(this,i)}terminate(){if(!lo(this))throw ho("terminate");Hy(this)}}Object.defineProperties(Tr.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),o(Tr.prototype.enqueue,"enqueue"),o(Tr.prototype.error,"error"),o(Tr.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Tr.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function lo(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_controlledTransformStream")?!1:s instanceof Tr}function Uy(s,i,c,m,A){i._controlledTransformStream=s,s._transformStreamController=i,i._transformAlgorithm=c,i._flushAlgorithm=m,i._cancelAlgorithm=A,i._finishPromise=void 0,i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0}function My(s,i){let c=Object.create(Tr.prototype),m,A,I;i.transform!==void 0?m=U=>i.transform(U,c):m=U=>{try{return Af(c,U),h(void 0)}catch(V){return d(V)}},i.flush!==void 0?A=()=>i.flush(c):A=()=>h(void 0),i.cancel!==void 0?I=U=>i.cancel(U):I=()=>h(void 0),Uy(s,c,m,A,I)}function fo(s){s._transformAlgorithm=void 0,s._flushAlgorithm=void 0,s._cancelAlgorithm=void 0}function Af(s,i){let c=s._controlledTransformStream,m=c._readable._readableStreamController;if(!gn(m))throw new TypeError("Readable side is not in a state that permits enqueue");try{mn(m,i)}catch(I){throw Oa(c,I),c._readable._storedError}yy(m)!==c._backpressure&&co(c,!0)}function $y(s,i){wf(s._controlledTransformStream,i)}function Df(s,i){let c=s._transformAlgorithm(i);return w(c,void 0,m=>{throw wf(s._controlledTransformStream,m),m})}function Hy(s){let i=s._controlledTransformStream,c=i._readable._readableStreamController;zr(c);let m=new TypeError("TransformStream terminated");Oa(i,m)}function Gy(s,i){let c=s._transformStreamController;if(s._backpressure){let m=s._backpressureChangePromise;return w(m,()=>{let A=s._writable;if(A._state==="erroring")throw A._storedError;return Df(c,i)})}return Df(c,i)}function Wy(s,i){let c=s._transformStreamController;if(c._finishPromise!==void 0)return c._finishPromise;let m=s._readable;c._finishPromise=f((I,U)=>{c._finishPromise_resolve=I,c._finishPromise_reject=U});let A=c._cancelAlgorithm(i);return fo(c),E(A,()=>(m._state==="errored"?yn(c,m._storedError):(Ot(m._readableStreamController,i),xa(c)),null),I=>(Ot(m._readableStreamController,I),yn(c,I),null)),c._finishPromise}function zy(s){let i=s._transformStreamController;if(i._finishPromise!==void 0)return i._finishPromise;let c=s._readable;i._finishPromise=f((A,I)=>{i._finishPromise_resolve=A,i._finishPromise_reject=I});let m=i._flushAlgorithm();return fo(i),E(m,()=>(c._state==="errored"?yn(i,c._storedError):(zr(c._readableStreamController),xa(i)),null),A=>(Ot(c._readableStreamController,A),yn(i,A),null)),i._finishPromise}function Jy(s){return co(s,!1),s._backpressureChangePromise}function Vy(s,i){let c=s._transformStreamController;if(c._finishPromise!==void 0)return c._finishPromise;let m=s._writable;c._finishPromise=f((I,U)=>{c._finishPromise_resolve=I,c._finishPromise_reject=U});let A=c._cancelAlgorithm(i);return fo(c),E(A,()=>(m._state==="errored"?yn(c,m._storedError):(es(m._writableStreamController,i),Pa(s),xa(c)),null),I=>(es(m._writableStreamController,I),Pa(s),yn(c,I),null)),c._finishPromise}function ho(s){return new TypeError(`TransformStreamDefaultController.prototype.${s} can only be used on a TransformStreamDefaultController`)}function xa(s){s._finishPromise_resolve!==void 0&&(s._finishPromise_resolve(),s._finishPromise_resolve=void 0,s._finishPromise_reject=void 0)}function yn(s,i){s._finishPromise_reject!==void 0&&(g(s._finishPromise),s._finishPromise_reject(i),s._finishPromise_resolve=void 0,s._finishPromise_reject=void 0)}function Sf(s){return new TypeError(`TransformStream.prototype.${s} can only be used on a TransformStream`)}r.ByteLengthQueuingStrategy=io,r.CountQueuingStrategy=ao,r.ReadableByteStreamController=or,r.ReadableStream=Ke,r.ReadableStreamBYOBReader=Ar,r.ReadableStreamBYOBRequest=Ur,r.ReadableStreamDefaultController=ar,r.ReadableStreamDefaultReader=M,r.TransformStream=uo,r.TransformStreamDefaultController=Tr,r.WritableStream=Dr,r.WritableStreamDefaultController=pn,r.WritableStreamDefaultWriter=ir})});var Ld=z(()=>{if(!globalThis.ReadableStream)try{let r=require("node:process"),{emitWarning:e}=r;try{r.emitWarning=()=>{},Object.assign(globalThis,require("node:stream/web")),r.emitWarning=e}catch(t){throw r.emitWarning=e,t}}catch{Object.assign(globalThis,jd())}try{let{Blob:r}=require("buffer");r&&!r.prototype.stream&&(r.prototype.stream=function(t){let n=0,o=this;return new ReadableStream({type:"bytes",async pull(a){let l=await o.slice(n,Math.min(o.size,n+65536)).arrayBuffer();n+=l.byteLength,a.enqueue(new Uint8Array(l)),n===o.size&&a.close()}})})}catch{}});async function*iu(r,e=!0){for(let t of r)if("stream"in t)yield*t.stream();else if(ArrayBuffer.isView(t))if(e){let n=t.byteOffset,o=t.byteOffset+t.byteLength;for(;n!==o;){let a=Math.min(o-n,Ud),u=t.buffer.slice(n,n+a);n+=u.byteLength,yield new Uint8Array(u)}}else yield t;else{let n=0,o=t;for(;n!==o.size;){let u=await o.slice(n,Math.min(o.size,n+Ud)).arrayBuffer();n+=u.byteLength,yield new Uint8Array(u)}}}var VA,Ud,Md,__,Nt,ls=Ue(()=>{VA=Me(Ld(),1);Ud=65536;Md=class au{#e=[];#t="";#r=0;#n="transparent";constructor(e=[],t={}){if(typeof e!="object"||e===null)throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if(typeof e[Symbol.iterator]!="function")throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if(typeof t!="object"&&typeof t!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");t===null&&(t={});let n=new TextEncoder;for(let a of e){let u;ArrayBuffer.isView(a)?u=new Uint8Array(a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength)):a instanceof ArrayBuffer?u=new Uint8Array(a.slice(0)):a instanceof au?u=a:u=n.encode(`${a}`),this.#r+=ArrayBuffer.isView(u)?u.byteLength:u.size,this.#e.push(u)}this.#n=`${t.endings===void 0?"transparent":t.endings}`;let o=t.type===void 0?"":String(t.type);this.#t=/^[\x20-\x7E]*$/.test(o)?o:""}get size(){return this.#r}get type(){return this.#t}async text(){let e=new TextDecoder,t="";for await(let n of iu(this.#e,!1))t+=e.decode(n,{stream:!0});return t+=e.decode(),t}async arrayBuffer(){let e=new Uint8Array(this.size),t=0;for await(let n of iu(this.#e,!1))e.set(n,t),t+=n.length;return e.buffer}stream(){let e=iu(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(t){let n=await e.next();n.done?t.close():t.enqueue(n.value)},async cancel(){await e.return()}})}slice(e=0,t=this.size,n=""){let{size:o}=this,a=e<0?Math.max(o+e,0):Math.min(e,o),u=t<0?Math.max(o+t,0):Math.min(t,o),l=Math.max(u-a,0),f=this.#e,h=[],d=0;for(let E of f){if(d>=l)break;let P=ArrayBuffer.isView(E)?E.byteLength:E.size;if(a&&P<=a)a-=P,u-=P;else{let v;ArrayBuffer.isView(E)?(v=E.subarray(a,Math.min(P,u)),d+=v.byteLength):(v=E.slice(a,Math.min(P,u)),d+=v.size),u-=P,h.push(v),a=0}}let _=new au([],{type:String(n).toLowerCase()});return _.#r=l,_.#e=h,_}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](e){return e&&typeof e=="object"&&typeof e.constructor=="function"&&(typeof e.stream=="function"||typeof e.arrayBuffer=="function")&&/^(Blob|File)$/.test(e[Symbol.toStringTag])}};Object.defineProperties(Md.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});__=Md,Nt=__});var C_,b_,Or,uu=Ue(()=>{ls();C_=class extends Nt{#e=0;#t="";constructor(e,t,n={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,n),n===null&&(n={});let o=n.lastModified===void 0?Date.now():Number(n.lastModified);Number.isNaN(o)||(this.#e=o),this.#t=String(t)}get name(){return this.#t}get lastModified(){return this.#e}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](e){return!!e&&e instanceof Nt&&/^(File)$/.test(e[Symbol.toStringTag])}},b_=C_,Or=b_});function Gd(r,e=Nt){var t=`${$d()}${$d()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),n=[],o=`--${t}\r +Content-Disposition: form-data; name="`;return r.forEach((a,u)=>typeof a=="string"?n.push(o+cu(u)+`"\r +\r +${a.replace(/\r(?!\n)|(?{ls();uu();({toStringTag:fs,iterator:E_,hasInstance:w_}=Symbol),$d=Math.random,A_="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),Hd=(r,e,t)=>(r+="",/^(Blob|File)$/.test(e&&e[fs])?[(t=t!==void 0?t+"":e[fs]=="File"?e.name:"blob",r),e.name!==t||e[fs]=="blob"?new Or([e],t,e):e]:[r,e+""]),cu=(r,e)=>(e?r:r.replace(/\r?\n|\r/g,`\r +`)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),Xr=(r,e,t)=>{if(e.lengthtypeof e[t]!="function")}append(...e){Xr("append",arguments,2),this.#e.push(Hd(...e))}delete(e){Xr("delete",arguments,1),e+="",this.#e=this.#e.filter(([t])=>t!==e)}get(e){Xr("get",arguments,1),e+="";for(var t=this.#e,n=t.length,o=0;on[0]===e&&t.push(n[1])),t}has(e){return Xr("has",arguments,1),e+="",this.#e.some(t=>t[0]===e)}forEach(e,t){Xr("forEach",arguments,1);for(var[n,o]of this)e.call(t,o,n,this)}set(...e){Xr("set",arguments,2);var t=[],n=!0;e=Hd(...e),this.#e.forEach(o=>{o[0]===e[0]?n&&(n=!t.push(e)):t.push(o)}),n&&t.push(e),this.#e=t}*entries(){yield*this.#e}*keys(){for(var[e]of this)yield e}*values(){for(var[,e]of this)yield e}}});var hr,Mo=Ue(()=>{hr=class extends Error{constructor(e,t){super(e),Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}});var et,lu=Ue(()=>{Mo();et=class extends hr{constructor(e,t,n){super(e,t),n&&(this.code=this.errno=n.code,this.erroredSysCall=n.syscall)}}});var $o,fu,ds,Wd,zd,Jd,Ho=Ue(()=>{$o=Symbol.toStringTag,fu=r=>typeof r=="object"&&typeof r.append=="function"&&typeof r.delete=="function"&&typeof r.get=="function"&&typeof r.getAll=="function"&&typeof r.has=="function"&&typeof r.set=="function"&&typeof r.sort=="function"&&r[$o]==="URLSearchParams",ds=r=>r&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&typeof r.constructor=="function"&&/^(Blob|File)$/.test(r[$o]),Wd=r=>typeof r=="object"&&(r[$o]==="AbortSignal"||r[$o]==="EventTarget"),zd=(r,e)=>{let t=new URL(e).hostname,n=new URL(r).hostname;return t===n||t.endsWith(`.${n}`)},Jd=(r,e)=>{let t=new URL(e).protocol,n=new URL(r).protocol;return t===n}});var Kd=z((aD,Vd)=>{if(!globalThis.DOMException)try{let{MessageChannel:r}=require("worker_threads"),e=new r().port1,t=new ArrayBuffer;e.postMessage(t,[t,t])}catch(r){r.constructor.name==="DOMException"&&(globalThis.DOMException=r.constructor)}Vd.exports=globalThis.DOMException});var Qr,Yd,Xd,du,Qd,Zd,eh,th,rh,nh,Go,hu=Ue(()=>{Qr=require("node:fs"),Yd=require("node:path"),Xd=Me(Kd(),1);uu();ls();({stat:du}=Qr.promises),Qd=(r,e)=>rh((0,Qr.statSync)(r),r,e),Zd=(r,e)=>du(r).then(t=>rh(t,r,e)),eh=(r,e)=>du(r).then(t=>nh(t,r,e)),th=(r,e)=>nh((0,Qr.statSync)(r),r,e),rh=(r,e,t="")=>new Nt([new Go({path:e,size:r.size,lastModified:r.mtimeMs,start:0})],{type:t}),nh=(r,e,t="")=>new Or([new Go({path:e,size:r.size,lastModified:r.mtimeMs,start:0})],(0,Yd.basename)(e),{type:t,lastModified:r.mtimeMs}),Go=class r{#e;#t;constructor(e){this.#e=e.path,this.#t=e.start,this.size=e.size,this.lastModified=e.lastModified}slice(e,t){return new r({path:this.#e,lastModified:this.lastModified,size:t-e,start:this.#t+e})}async*stream(){let{mtimeMs:e}=await du(this.#e);if(e>this.lastModified)throw new Xd.default("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.","NotReadableError");yield*(0,Qr.createReadStream)(this.#e,{start:this.#t,end:this.#t+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}});var oh={};Ia(oh,{toFormData:()=>F_});function k_(r){let e=r.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let t=e[2]||e[3]||"",n=t.slice(t.lastIndexOf("\\")+1);return n=n.replace(/%22/g,'"'),n=n.replace(/&#(\d{4});/g,(o,a)=>String.fromCharCode(a)),n}async function F_(r,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let t=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!t)throw new TypeError("no or bad content-type header, no multipart boundary");let n=new pu(t[1]||t[2]),o,a,u,l,f,h,d=[],_=new Pr,E=C=>{u+=g.decode(C,{stream:!0})},P=C=>{d.push(C)},v=()=>{let C=new Or(d,h,{type:f});_.append(l,C)},w=()=>{_.append(l,u)},g=new TextDecoder("utf-8");g.decode(),n.onPartBegin=function(){n.onPartData=E,n.onPartEnd=w,o="",a="",u="",l="",f="",h=null,d.length=0},n.onHeaderField=function(C){o+=g.decode(C,{stream:!0})},n.onHeaderValue=function(C){a+=g.decode(C,{stream:!0})},n.onHeaderEnd=function(){if(a+=g.decode(),o=o.toLowerCase(),o==="content-disposition"){let C=a.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);C&&(l=C[2]||C[3]||""),h=k_(a),h&&(n.onPartData=P,n.onPartEnd=v)}else o==="content-type"&&(f=a);a="",o=""};for await(let C of r)n.write(C);return n.end(),_}var Jt,Re,sh,xr,Wo,zo,D_,hs,S_,v_,T_,R_,Zr,pu,ih=Ue(()=>{hu();Uo();Jt=0,Re={START_BOUNDARY:Jt++,HEADER_FIELD_START:Jt++,HEADER_FIELD:Jt++,HEADER_VALUE_START:Jt++,HEADER_VALUE:Jt++,HEADER_VALUE_ALMOST_DONE:Jt++,HEADERS_ALMOST_DONE:Jt++,PART_DATA_START:Jt++,PART_DATA:Jt++,END:Jt++},sh=1,xr={PART_BOUNDARY:sh,LAST_BOUNDARY:sh*=2},Wo=10,zo=13,D_=32,hs=45,S_=58,v_=97,T_=122,R_=r=>r|32,Zr=()=>{},pu=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=Zr,this.onHeaderField=Zr,this.onHeadersEnd=Zr,this.onHeaderValue=Zr,this.onPartBegin=Zr,this.onPartData=Zr,this.onPartEnd=Zr,this.boundaryChars={},e=`\r +--`+e;let t=new Uint8Array(e.length);for(let n=0;n{this[N+"Mark"]=t},C=N=>{delete this[N+"Mark"]},R=(N,j,L,H)=>{(j===void 0||j!==L)&&this[N](H&&H.subarray(j,L))},S=(N,j)=>{let L=N+"Mark";L in this&&(j?(R(N,this[L],t,e),delete this[L]):(R(N,this[L],e.length,e),this[L]=0))};for(t=0;tT_)return;break;case Re.HEADER_VALUE_START:if(v===D_)break;g("onHeaderValue"),h=Re.HEADER_VALUE;case Re.HEADER_VALUE:v===zo&&(S("onHeaderValue",!0),R("onHeaderEnd"),h=Re.HEADER_VALUE_ALMOST_DONE);break;case Re.HEADER_VALUE_ALMOST_DONE:if(v!==Wo)return;h=Re.HEADER_FIELD_START;break;case Re.HEADERS_ALMOST_DONE:if(v!==Wo)return;R("onHeadersEnd"),h=Re.PART_DATA_START;break;case Re.PART_DATA_START:h=Re.PART_DATA,g("onPartData");case Re.PART_DATA:if(o=f,f===0){for(t+=E;t0)a[f-1]=v;else if(o>0){let N=new Uint8Array(a.buffer,a.byteOffset,a.byteLength);R("onPartData",0,o,N),o=0,g("onPartData"),t--}break;case Re.END:break;default:throw new Error(`Unexpected state entered: ${h}`)}S("onHeaderField"),S("onHeaderValue"),S("onPartData"),this.index=f,this.state=h,this.flags=d}end(){if(this.state===Re.HEADER_FIELD_START&&this.index===0||this.state===Re.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==Re.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});async function mu(r){if(r[it].disturbed)throw new TypeError(`body used already for: ${r.url}`);if(r[it].disturbed=!0,r[it].error)throw r[it].error;let{body:e}=r;if(e===null)return ft.Buffer.alloc(0);if(!(e instanceof St.default))return ft.Buffer.alloc(0);let t=[],n=0;try{for await(let o of e){if(r.size>0&&n+o.length>r.size){let a=new et(`content size at ${r.url} over limit: ${r.size}`,"max-size");throw e.destroy(a),a}n+=o.length,t.push(o)}}catch(o){throw o instanceof hr?o:new et(`Invalid response body while trying to fetch ${r.url}: ${o.message}`,"system",o)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return t.every(o=>typeof o=="string")?ft.Buffer.from(t.join("")):ft.Buffer.concat(t,n)}catch(o){throw new et(`Could not create Buffer from response body for ${r.url}: ${o.message}`,"system",o)}else throw new et(`Premature close of server response while trying to fetch ${r.url}`)}var St,pr,ft,O_,it,Vt,Rn,P_,Jo,ah,uh,Vo=Ue(()=>{St=Me(require("node:stream"),1),pr=require("node:util"),ft=require("node:buffer");ls();Uo();lu();Mo();Ho();O_=(0,pr.promisify)(St.default.pipeline),it=Symbol("Body internals"),Vt=class{constructor(e,{size:t=0}={}){let n=null;e===null?e=null:fu(e)?e=ft.Buffer.from(e.toString()):ds(e)||ft.Buffer.isBuffer(e)||(pr.types.isAnyArrayBuffer(e)?e=ft.Buffer.from(e):ArrayBuffer.isView(e)?e=ft.Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof St.default||(e instanceof Pr?(e=Gd(e),n=e.type.split("=")[1]):e=ft.Buffer.from(String(e))));let o=e;ft.Buffer.isBuffer(e)?o=St.default.Readable.from(e):ds(e)&&(o=St.default.Readable.from(e.stream())),this[it]={body:e,stream:o,boundary:n,disturbed:!1,error:null},this.size=t,e instanceof St.default&&e.on("error",a=>{let u=a instanceof hr?a:new et(`Invalid response body while trying to fetch ${this.url}: ${a.message}`,"system",a);this[it].error=u})}get body(){return this[it].stream}get bodyUsed(){return this[it].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:n}=await mu(this);return e.slice(t,t+n)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let n=new Pr,o=new URLSearchParams(await this.text());for(let[a,u]of o)n.append(a,u);return n}let{toFormData:t}=await Promise.resolve().then(()=>(ih(),oh));return t(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[it].body&&this[it].body.type||"",t=await this.arrayBuffer();return new Nt([t],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await mu(this);return new TextDecoder().decode(e)}buffer(){return mu(this)}};Vt.prototype.buffer=(0,pr.deprecate)(Vt.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(Vt.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:(0,pr.deprecate)(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});Rn=(r,e)=>{let t,n,{body:o}=r[it];if(r.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof St.default&&typeof o.getBoundary!="function"&&(t=new St.PassThrough({highWaterMark:e}),n=new St.PassThrough({highWaterMark:e}),o.pipe(t),o.pipe(n),r[it].stream=t,o=n),o},P_=(0,pr.deprecate)(r=>r.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),Jo=(r,e)=>r===null?null:typeof r=="string"?"text/plain;charset=UTF-8":fu(r)?"application/x-www-form-urlencoded;charset=UTF-8":ds(r)?r.type||null:ft.Buffer.isBuffer(r)||pr.types.isAnyArrayBuffer(r)||ArrayBuffer.isView(r)?null:r instanceof Pr?`multipart/form-data; boundary=${e[it].boundary}`:r&&typeof r.getBoundary=="function"?`multipart/form-data;boundary=${P_(r)}`:r instanceof St.default?null:"text/plain;charset=UTF-8",ah=r=>{let{body:e}=r[it];return e===null?0:ds(e)?e.size:ft.Buffer.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},uh=async(r,{body:e})=>{e===null?r.end():await O_(e,r)}});function ch(r=[]){return new at(r.reduce((e,t,n,o)=>(n%2===0&&e.push(o.slice(n,n+2)),e),[]).filter(([e,t])=>{try{return Ko(e),yu(e,String(t)),!0}catch{return!1}}))}var gu,ps,Ko,yu,at,Yo=Ue(()=>{gu=require("node:util"),ps=Me(require("node:http"),1),Ko=typeof ps.default.validateHeaderName=="function"?ps.default.validateHeaderName:r=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(r)){let e=new TypeError(`Header name must be a valid HTTP token [${r}]`);throw Object.defineProperty(e,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),e}},yu=typeof ps.default.validateHeaderValue=="function"?ps.default.validateHeaderValue:(r,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let t=new TypeError(`Invalid character in header content ["${r}"]`);throw Object.defineProperty(t,"code",{value:"ERR_INVALID_CHAR"}),t}},at=class r extends URLSearchParams{constructor(e){let t=[];if(e instanceof r){let n=e.raw();for(let[o,a]of Object.entries(n))t.push(...a.map(u=>[o,u]))}else if(e!=null)if(typeof e=="object"&&!gu.types.isBoxedPrimitive(e)){let n=e[Symbol.iterator];if(n==null)t.push(...Object.entries(e));else{if(typeof n!="function")throw new TypeError("Header pairs must be iterable");t=[...e].map(o=>{if(typeof o!="object"||gu.types.isBoxedPrimitive(o))throw new TypeError("Each header pair must be an iterable object");return[...o]}).map(o=>{if(o.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return[...o]})}}else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence> or record)");return t=t.length>0?t.map(([n,o])=>(Ko(n),yu(n,String(o)),[String(n).toLowerCase(),String(o)])):void 0,super(t),new Proxy(this,{get(n,o,a){switch(o){case"append":case"set":return(u,l)=>(Ko(u),yu(u,String(l)),URLSearchParams.prototype[o].call(n,String(u).toLowerCase(),String(l)));case"delete":case"has":case"getAll":return u=>(Ko(u),URLSearchParams.prototype[o].call(n,String(u).toLowerCase()));case"keys":return()=>(n.sort(),new Set(URLSearchParams.prototype.keys.call(n)).keys());default:return Reflect.get(n,o,a)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let t=this.getAll(e);if(t.length===0)return null;let n=t.join(", ");return/^content-encoding$/i.test(e)&&(n=n.toLowerCase()),n}forEach(e,t=void 0){for(let n of this.keys())Reflect.apply(e,t,[this.get(n),n,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,t)=>(e[t]=this.getAll(t),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,t)=>{let n=this.getAll(t);return t==="host"?e[t]=n[0]:e[t]=n.length>1?n:n[0],e},{})}};Object.defineProperties(at.prototype,["get","entries","forEach","values"].reduce((r,e)=>(r[e]={enumerable:!0},r),{}))});var x_,ms,_u=Ue(()=>{x_=new Set([301,302,303,307,308]),ms=r=>x_.has(r)});var qt,dt,lh=Ue(()=>{Yo();Vo();_u();qt=Symbol("Response internals"),dt=class r extends Vt{constructor(e=null,t={}){super(e,t);let n=t.status!=null?t.status:200,o=new at(t.headers);if(e!==null&&!o.has("Content-Type")){let a=Jo(e,this);a&&o.append("Content-Type",a)}this[qt]={type:"default",url:t.url,status:n,statusText:t.statusText||"",headers:o,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[qt].type}get url(){return this[qt].url||""}get status(){return this[qt].status}get ok(){return this[qt].status>=200&&this[qt].status<300}get redirected(){return this[qt].counter>0}get statusText(){return this[qt].statusText}get headers(){return this[qt].headers}get highWaterMark(){return this[qt].highWaterMark}clone(){return new r(Rn(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,t=302){if(!ms(t))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new r(null,{headers:{location:new URL(e).toString()},status:t})}static error(){let e=new r(null,{status:0,statusText:""});return e[qt].type="error",e}static json(e=void 0,t={}){let n=JSON.stringify(e);if(n===void 0)throw new TypeError("data is not JSON serializable");let o=new at(t&&t.headers);return o.has("content-type")||o.set("content-type","application/json"),new r(n,{...t,headers:o})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(dt.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}})});var fh,dh=Ue(()=>{fh=r=>{if(r.search)return r.search;let e=r.href.length-1,t=r.hash||(r.href[e]==="#"?"#":"");return r.href[e-t.length]==="?"?"?":""}});function hh(r,e=!1){return r==null||(r=new URL(r),/^(about|blob|data):$/.test(r.protocol))?"no-referrer":(r.username="",r.password="",r.hash="",e&&(r.pathname="",r.search=""),r)}function yh(r){if(!mh.has(r))throw new TypeError(`Invalid referrerPolicy: ${r}`);return r}function B_(r){if(/^(http|ws)s:$/.test(r.protocol))return!0;let e=r.host.replace(/(^\[)|(]$)/g,""),t=(0,ph.isIP)(e);return t===4&&/^127\./.test(e)||t===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:r.host==="localhost"||r.host.endsWith(".localhost")?!1:r.protocol==="file:"}function kn(r){return/^about:(blank|srcdoc)$/.test(r)||r.protocol==="data:"||/^(blob|filesystem):$/.test(r.protocol)?!0:B_(r)}function _h(r,{referrerURLCallback:e,referrerOriginCallback:t}={}){if(r.referrer==="no-referrer"||r.referrerPolicy==="")return null;let n=r.referrerPolicy;if(r.referrer==="about:client")return"no-referrer";let o=r.referrer,a=hh(o),u=hh(o,!0);a.toString().length>4096&&(a=u),e&&(a=e(a)),t&&(u=t(u));let l=new URL(r.url);switch(n){case"no-referrer":return"no-referrer";case"origin":return u;case"unsafe-url":return a;case"strict-origin":return kn(a)&&!kn(l)?"no-referrer":u.toString();case"strict-origin-when-cross-origin":return a.origin===l.origin?a:kn(a)&&!kn(l)?"no-referrer":u;case"same-origin":return a.origin===l.origin?a:"no-referrer";case"origin-when-cross-origin":return a.origin===l.origin?a:u;case"no-referrer-when-downgrade":return kn(a)&&!kn(l)?"no-referrer":a;default:throw new TypeError(`Invalid referrerPolicy: ${n}`)}}function Ch(r){let e=(r.get("referrer-policy")||"").split(/[,\s]+/),t="";for(let n of e)n&&mh.has(n)&&(t=n);return t}var ph,mh,gh,Cu=Ue(()=>{ph=require("node:net");mh=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),gh="strict-origin-when-cross-origin"});var bh,Eh,We,gs,I_,Br,wh,Ah=Ue(()=>{bh=require("node:url"),Eh=require("node:util");Yo();Vo();Ho();dh();Cu();We=Symbol("Request internals"),gs=r=>typeof r=="object"&&typeof r[We]=="object",I_=(0,Eh.deprecate)(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Br=class r extends Vt{constructor(e,t={}){let n;if(gs(e)?n=new URL(e.url):(n=new URL(e),e={}),n.username!==""||n.password!=="")throw new TypeError(`${n} is an url with embedded credentials.`);let o=t.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),!gs(t)&&"data"in t&&I_(),(t.body!=null||gs(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let a=t.body?t.body:gs(e)&&e.body!==null?Rn(e):null;super(a,{size:t.size||e.size||0});let u=new at(t.headers||e.headers||{});if(a!==null&&!u.has("Content-Type")){let h=Jo(a,this);h&&u.set("Content-Type",h)}let l=gs(e)?e.signal:null;if("signal"in t&&(l=t.signal),l!=null&&!Wd(l))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let f=t.referrer==null?e.referrer:t.referrer;if(f==="")f="no-referrer";else if(f){let h=new URL(f);f=/^about:(\/\/)?client$/.test(h)?"client":h}else f=void 0;this[We]={method:o,redirect:t.redirect||e.redirect||"follow",headers:u,parsedURL:n,signal:l,referrer:f},this.follow=t.follow===void 0?e.follow===void 0?20:e.follow:t.follow,this.compress=t.compress===void 0?e.compress===void 0?!0:e.compress:t.compress,this.counter=t.counter||e.counter||0,this.agent=t.agent||e.agent,this.highWaterMark=t.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=t.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=t.referrerPolicy||e.referrerPolicy||""}get method(){return this[We].method}get url(){return(0,bh.format)(this[We].parsedURL)}get headers(){return this[We].headers}get redirect(){return this[We].redirect}get signal(){return this[We].signal}get referrer(){if(this[We].referrer==="no-referrer")return"";if(this[We].referrer==="client")return"about:client";if(this[We].referrer)return this[We].referrer.toString()}get referrerPolicy(){return this[We].referrerPolicy}set referrerPolicy(e){this[We].referrerPolicy=yh(e)}clone(){return new r(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(Br.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});wh=r=>{let{parsedURL:e}=r[We],t=new at(r[We].headers);t.has("Accept")||t.set("Accept","*/*");let n=null;if(r.body===null&&/^(post|put)$/i.test(r.method)&&(n="0"),r.body!==null){let l=ah(r);typeof l=="number"&&!Number.isNaN(l)&&(n=String(l))}n&&t.set("Content-Length",n),r.referrerPolicy===""&&(r.referrerPolicy=gh),r.referrer&&r.referrer!=="no-referrer"?r[We].referrer=_h(r):r[We].referrer="no-referrer",r[We].referrer instanceof URL&&t.set("Referer",r.referrer),t.has("User-Agent")||t.set("User-Agent","node-fetch"),r.compress&&!t.has("Accept-Encoding")&&t.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=r;typeof o=="function"&&(o=o(e));let a=fh(e),u={path:e.pathname+a,method:r.method,headers:t[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:r.insecureHTTPParser,agent:o};return{parsedURL:e,options:u}}});var ys,Dh=Ue(()=>{Mo();ys=class extends hr{constructor(e,t="aborted"){super(e,t)}}});var Th={};Ia(Th,{AbortError:()=>ys,Blob:()=>Nt,FetchError:()=>et,File:()=>Or,FormData:()=>Pr,Headers:()=>at,Request:()=>Br,Response:()=>dt,blobFrom:()=>Zd,blobFromSync:()=>Qd,default:()=>bu,fileFrom:()=>eh,fileFromSync:()=>th,isRedirect:()=>ms});async function bu(r,e){return new Promise((t,n)=>{let o=new Br(r,e),{parsedURL:a,options:u}=wh(o);if(!N_.has(a.protocol))throw new TypeError(`node-fetch cannot load ${r}. URL scheme "${a.protocol.replace(/:$/,"")}" is not supported.`);if(a.protocol==="data:"){let v=Id(o.url),w=new dt(v,{headers:{"Content-Type":v.typeFull}});t(w);return}let l=(a.protocol==="https:"?vh.default:Sh.default).request,{signal:f}=o,h=null,d=()=>{let v=new ys("The operation was aborted.");n(v),o.body&&o.body instanceof ht.default.Readable&&o.body.destroy(v),!(!h||!h.body)&&h.body.emit("error",v)};if(f&&f.aborted){d();return}let _=()=>{d(),P()},E=l(a.toString(),u);f&&f.addEventListener("abort",_);let P=()=>{E.abort(),f&&f.removeEventListener("abort",_)};E.on("error",v=>{n(new et(`request to ${o.url} failed, reason: ${v.message}`,"system",v)),P()}),q_(E,v=>{h&&h.body&&h.body.destroy(v)}),process.version<"v14"&&E.on("socket",v=>{let w;v.prependListener("end",()=>{w=v._eventsCount}),v.prependListener("close",g=>{if(h&&w{E.setTimeout(0);let w=ch(v.rawHeaders);if(ms(v.statusCode)){let N=w.get("Location"),j=null;try{j=N===null?null:new URL(N,o.url)}catch{if(o.redirect!=="manual"){n(new et(`uri requested responds with an invalid redirect URL: ${N}`,"invalid-redirect")),P();return}}switch(o.redirect){case"error":n(new et(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),P();return;case"manual":break;case"follow":{if(j===null)break;if(o.counter>=o.follow){n(new et(`maximum redirect reached at: ${o.url}`,"max-redirect")),P();return}let L={headers:new at(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:Rn(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!zd(o.url,j)||!Jd(o.url,j))for(let K of["authorization","www-authenticate","cookie","cookie2"])L.headers.delete(K);if(v.statusCode!==303&&o.body&&e.body instanceof ht.default.Readable){n(new et("Cannot follow redirect with body being a readable stream","unsupported-redirect")),P();return}(v.statusCode===303||(v.statusCode===301||v.statusCode===302)&&o.method==="POST")&&(L.method="GET",L.body=void 0,L.headers.delete("content-length"));let H=Ch(w);H&&(L.referrerPolicy=H),t(bu(new Br(j,L))),P();return}default:return n(new TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}f&&v.once("end",()=>{f.removeEventListener("abort",_)});let g=(0,ht.pipeline)(v,new ht.PassThrough,N=>{N&&n(N)});process.version<"v12.10"&&v.on("aborted",_);let C={url:o.url,status:v.statusCode,statusText:v.statusMessage,headers:w,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},R=w.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||R===null||v.statusCode===204||v.statusCode===304){h=new dt(g,C),t(h);return}let S={flush:en.default.Z_SYNC_FLUSH,finishFlush:en.default.Z_SYNC_FLUSH};if(R==="gzip"||R==="x-gzip"){g=(0,ht.pipeline)(g,en.default.createGunzip(S),N=>{N&&n(N)}),h=new dt(g,C),t(h);return}if(R==="deflate"||R==="x-deflate"){let N=(0,ht.pipeline)(v,new ht.PassThrough,j=>{j&&n(j)});N.once("data",j=>{(j[0]&15)===8?g=(0,ht.pipeline)(g,en.default.createInflate(),L=>{L&&n(L)}):g=(0,ht.pipeline)(g,en.default.createInflateRaw(),L=>{L&&n(L)}),h=new dt(g,C),t(h)}),N.once("end",()=>{h||(h=new dt(g,C),t(h))});return}if(R==="br"){g=(0,ht.pipeline)(g,en.default.createBrotliDecompress(),N=>{N&&n(N)}),h=new dt(g,C),t(h);return}h=new dt(g,C),t(h)}),uh(E,o).catch(n)})}function q_(r,e){let t=_s.Buffer.from(`0\r +\r +`),n=!1,o=!1,a;r.on("response",u=>{let{headers:l}=u;n=l["transfer-encoding"]==="chunked"&&!l["content-length"]}),r.on("socket",u=>{let l=()=>{if(n&&!o){let h=new Error("Premature close");h.code="ERR_STREAM_PREMATURE_CLOSE",e(h)}},f=h=>{o=_s.Buffer.compare(h.slice(-5),t)===0,!o&&a&&(o=_s.Buffer.compare(a.slice(-3),t.slice(0,3))===0&&_s.Buffer.compare(h.slice(-2),t.slice(3))===0),a=h};u.prependListener("close",l),u.on("data",f),r.on("close",()=>{u.removeListener("close",l),u.removeListener("data",f)})})}var Sh,vh,en,ht,_s,N_,Rh=Ue(()=>{Sh=Me(require("node:http"),1),vh=Me(require("node:https"),1),en=Me(require("node:zlib"),1),ht=Me(require("node:stream"),1),_s=require("node:buffer");Nd();Vo();lh();Yo();Ah();lu();Dh();_u();Uo();Ho();Cu();hu();N_=new Set(["data:","http:","https:"])});var Oh=z(On=>{"use strict";var j_=On&&On.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},Fn;Object.defineProperty(On,"__esModule",{value:!0});On.Gaxios=void 0;var L_=j_(Va()),U_=require("https"),tn=Xa(),M_=ld(),kh=require("stream"),Fh=eu(),$_=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),Xo=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Fh.GaxiosInterceptorManager,response:new Fh.GaxiosInterceptorManager}}fetch(...e){let t=e[0],n=e[1],o,a=new Headers;return typeof t=="string"?o=new URL(t):t instanceof URL?o=t:t&&t.url&&(o=new URL(t.url)),t&&typeof t=="object"&&"headers"in t&&Fn.mergeHeaders(a,t.headers),n&&Fn.mergeHeaders(a,new Headers(n.headers)),typeof t=="object"&&!(t instanceof URL)?this.request({...n,...t,headers:a,url:o}):this.request({...n,headers:a,url:o})}async request(e={}){let t=await this.#n(e);return t=await this.#t(t),this.#r(this._request(t))}async _defaultAdapter(e){let t=e.fetchImplementation||this.defaults.fetchImplementation||await Fn.#u(),n={...e};delete n.data;let o=await t(e.url,n),a=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:a}}),Object.assign(o,{config:e,data:a})}async _request(e){try{let t;if(e.adapter?t=await e.adapter(e,this._defaultAdapter.bind(this)):t=await this._defaultAdapter(e),!e.validateStatus(t.status)){if(e.responseType==="stream"){let o=[];for await(let a of e.data??[])o.push(a);t.data=o}let n=tn.GaxiosError.extractAPIErrorFromResponse(t,`Request failed with status code ${t.status}`);throw new tn.GaxiosError(n?.message,e,t,n)}return t}catch(t){let n;t instanceof tn.GaxiosError?n=t:t instanceof Error?n=new tn.GaxiosError(t.message,e,void 0,t):n=new tn.GaxiosError("Unexpected Gaxios Error",e,void 0,t);let{shouldRetry:o,config:a}=await(0,M_.getRetryConfig)(n);if(o&&a)return n.config.retryConfig.currentRetryAttempt=a.retryConfig.currentRetryAttempt,e.retryConfig=n.config?.retryConfig,this.#s(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(n),n}}async getResponseData(e,t){if(e.maxContentLength&&t.headers.has("content-length")&&e.maxContentLength=200&&e<300}async getResponseDataFromContentType(e){let t=e.headers.get("Content-Type");if(t===null)return e.text();if(t=t.toLowerCase(),t.includes("application/json")){let n=await e.text();try{n=JSON.parse(n)}catch{}return n}else return t.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,t){let n=`--${t}--`;for(let o of e){let a=o.headers.get("Content-Type")||"application/octet-stream";yield`--${t}\r +Content-Type: ${a}\r +\r +`,typeof o.content=="string"?yield o.content:yield*o.content,yield`\r +`}yield n}static#o;static#i;static async#a(){return this.#o||=(await Promise.resolve().then(()=>Me(Bd()))).HttpsProxyAgent,this.#o}static async#u(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(Rh(),Th))).default,this.#i}static mergeHeaders(e,...t){e=e instanceof Headers?e:new Headers(e);for(let n of t)(n instanceof Headers?n:new Headers(n)).forEach((a,u)=>{u==="set-cookie"?e.append(u,a):e.set(u,a)});return e}};On.Gaxios=Xo;Fn=Xo});var Je=z(tt=>{"use strict";var H_=tt&&tt.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),G_=tt&&tt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&H_(e,r,t)};Object.defineProperty(tt,"__esModule",{value:!0});tt.instance=tt.Gaxios=tt.GaxiosError=void 0;tt.request=z_;var Ph=Oh();Object.defineProperty(tt,"Gaxios",{enumerable:!0,get:function(){return Ph.Gaxios}});var W_=Xa();Object.defineProperty(tt,"GaxiosError",{enumerable:!0,get:function(){return W_.GaxiosError}});G_(eu(),tt);tt.instance=new Ph.Gaxios;async function z_(r){return tt.instance.request(r)}});var Eu=z((xh,Qo)=>{(function(r){"use strict";var e,t=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,n=Math.ceil,o=Math.floor,a="[BigNumber Error] ",u=a+"Number primitive has more than 15 significant digits: ",l=1e14,f=14,h=9007199254740991,d=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],_=1e7,E=1e9;function P(j){var L,H,K,W=G.prototype={constructor:G,toString:null,valueOf:null},we=new G(1),de=20,le=4,ge=-7,te=21,fe=-1e7,Q=1e7,ae=!1,J=1,ne=0,se={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},Be="0123456789abcdefghijklmnopqrstuvwxyz",qe=!0;function G(p,y){var b,x,T,F,q,D,k,B,O=this;if(!(O instanceof G))return new G(p,y);if(y==null){if(p&&p._isBigNumber===!0){O.s=p.s,!p.c||p.e>Q?O.c=O.e=null:p.e=10;q/=10,F++);F>Q?O.c=O.e=null:(O.e=F,O.c=[p]);return}B=String(p)}else{if(!t.test(B=String(p)))return K(O,B,D);O.s=B.charCodeAt(0)==45?(B=B.slice(1),-1):1}(F=B.indexOf("."))>-1&&(B=B.replace(".","")),(q=B.search(/e/i))>0?(F<0&&(F=q),F+=+B.slice(q+1),B=B.substring(0,q)):F<0&&(F=B.length)}else{if(C(y,2,Be.length,"Base"),y==10&&qe)return O=new G(p),Pe(O,de+O.e+1,le);if(B=String(p),D=typeof p=="number"){if(p*0!=0)return K(O,B,D,y);if(O.s=1/p<0?(B=B.slice(1),-1):1,G.DEBUG&&B.replace(/^0\.0*|\./,"").length>15)throw Error(u+p)}else O.s=B.charCodeAt(0)===45?(B=B.slice(1),-1):1;for(b=Be.slice(0,y),F=q=0,k=B.length;qF){F=k;continue}}else if(!T&&(B==B.toUpperCase()&&(B=B.toLowerCase())||B==B.toLowerCase()&&(B=B.toUpperCase()))){T=!0,q=-1,F=0;continue}return K(O,String(p),D,y)}D=!1,B=H(B,y,10,O.s),(F=B.indexOf("."))>-1?B=B.replace(".",""):F=B.length}for(q=0;B.charCodeAt(q)===48;q++);for(k=B.length;B.charCodeAt(--k)===48;);if(B=B.slice(q,++k)){if(k-=q,D&&G.DEBUG&&k>15&&(p>h||p!==o(p)))throw Error(u+O.s*p);if((F=F-q-1)>Q)O.c=O.e=null;else if(F=-E&&T<=E&&T===o(T)){if(x[0]===0){if(T===0&&x.length===1)return!0;break e}if(y=(T+1)%f,y<1&&(y+=f),String(x[0]).length==y){for(y=0;y=l||b!==o(b))break e;if(b!==0)return!0}}}else if(x===null&&T===null&&(F===null||F===1||F===-1))return!0;throw Error(a+"Invalid BigNumber: "+p)},G.maximum=G.max=function(){return be(arguments,-1)},G.minimum=G.min=function(){return be(arguments,1)},G.random=function(){var p=9007199254740992,y=Math.random()*p&2097151?function(){return o(Math.random()*p)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(b){var x,T,F,q,D,k=0,B=[],O=new G(we);if(b==null?b=de:C(b,0,E),q=n(b/f),ae)if(crypto.getRandomValues){for(x=crypto.getRandomValues(new Uint32Array(q*=2));k>>11),D>=9e15?(T=crypto.getRandomValues(new Uint32Array(2)),x[k]=T[0],x[k+1]=T[1]):(B.push(D%1e14),k+=2);k=q/2}else if(crypto.randomBytes){for(x=crypto.randomBytes(q*=7);k=9e15?crypto.randomBytes(7).copy(x,k):(B.push(D%1e14),k+=7);k=q/7}else throw ae=!1,Error(a+"crypto unavailable");if(!ae)for(;k=10;D/=10,k++);kT-1&&(D[q+1]==null&&(D[q+1]=0),D[q+1]+=D[q]/T|0,D[q]%=T)}return D.reverse()}return function(b,x,T,F,q){var D,k,B,O,M,Y,X,Ee,ke=b.indexOf("."),xe=de,Ce=le;for(ke>=0&&(O=ne,ne=0,b=b.replace(".",""),Ee=new G(x),Y=Ee.pow(b.length-ke),ne=O,Ee.c=y(N(w(Y.c),Y.e,"0"),10,T,p),Ee.e=Ee.c.length),X=y(b,x,T,q?(D=Be,p):(D=p,Be)),B=O=X.length;X[--O]==0;X.pop());if(!X[0])return D.charAt(0);if(ke<0?--B:(Y.c=X,Y.e=B,Y.s=F,Y=L(Y,Ee,xe,Ce,T),X=Y.c,M=Y.r,B=Y.e),k=B+xe+1,ke=X[k],O=T/2,M=M||k<0||X[k+1]!=null,M=Ce<4?(ke!=null||M)&&(Ce==0||Ce==(Y.s<0?3:2)):ke>O||ke==O&&(Ce==4||M||Ce==6&&X[k-1]&1||Ce==(Y.s<0?8:7)),k<1||!X[0])b=M?N(D.charAt(1),-xe,D.charAt(0)):D.charAt(0);else{if(X.length=k,M)for(--T;++X[--k]>T;)X[k]=0,k||(++B,X=[1].concat(X));for(O=X.length;!X[--O];);for(ke=0,b="";ke<=O;b+=D.charAt(X[ke++]));b=N(b,B,D.charAt(0))}return b}}(),L=function(){function p(x,T,F){var q,D,k,B,O=0,M=x.length,Y=T%_,X=T/_|0;for(x=x.slice();M--;)k=x[M]%_,B=x[M]/_|0,q=X*k+B*Y,D=Y*k+q%_*_+O,O=(D/F|0)+(q/_|0)+X*B,x[M]=D%F;return O&&(x=[O].concat(x)),x}function y(x,T,F,q){var D,k;if(F!=q)k=F>q?1:-1;else for(D=k=0;DT[D]?1:-1;break}return k}function b(x,T,F,q){for(var D=0;F--;)x[F]-=D,D=x[F]1;x.splice(0,1));}return function(x,T,F,q,D){var k,B,O,M,Y,X,Ee,ke,xe,Ce,Ae,je,un,cn,ln,ut,nr,Ve=x.s==T.s?1:-1,Le=x.c,De=T.c;if(!Le||!Le[0]||!De||!De[0])return new G(!x.s||!T.s||(Le?De&&Le[0]==De[0]:!De)?NaN:Le&&Le[0]==0||!De?Ve*0:Ve/0);for(ke=new G(Ve),xe=ke.c=[],B=x.e-T.e,Ve=F+B+1,D||(D=l,B=v(x.e/f)-v(T.e/f),Ve=Ve/f|0),O=0;De[O]==(Le[O]||0);O++);if(De[O]>(Le[O]||0)&&B--,Ve<0)xe.push(1),M=!0;else{for(cn=Le.length,ut=De.length,O=0,Ve+=2,Y=o(D/(De[0]+1)),Y>1&&(De=p(De,Y,D),Le=p(Le,Y,D),ut=De.length,cn=Le.length),un=ut,Ce=Le.slice(0,ut),Ae=Ce.length;Ae=D/2&&ln++;do{if(Y=0,k=y(De,Ce,ut,Ae),k<0){if(je=Ce[0],ut!=Ae&&(je=je*D+(Ce[1]||0)),Y=o(je/ln),Y>1)for(Y>=D&&(Y=D-1),X=p(De,Y,D),Ee=X.length,Ae=Ce.length;y(X,Ce,Ee,Ae)==1;)Y--,b(X,ut=10;Ve/=10,O++);Pe(ke,F+(ke.e=O+B*f-1)+1,q,M)}else ke.e=B,ke.r=+M;return ke}}();function he(p,y,b,x){var T,F,q,D,k;if(b==null?b=le:C(b,0,8),!p.c)return p.toString();if(T=p.c[0],q=p.e,y==null)k=w(p.c),k=x==1||x==2&&(q<=ge||q>=te)?S(k,q):N(k,q,"0");else if(p=Pe(new G(p),y,b),F=p.e,k=w(p.c),D=k.length,x==1||x==2&&(y<=F||F<=ge)){for(;Dq),k=N(k,F,"0"),F+1>D){if(--y>0)for(k+=".";y--;k+="0");}else if(y+=F-D,y>0)for(F+1==D&&(k+=".");y--;k+="0");return p.s<0&&T?"-"+k:k}function be(p,y){for(var b,x,T=1,F=new G(p[0]);T=10;T/=10,x++);return(b=x+b*f-1)>Q?p.c=p.e=null:b=10;D/=10,T++);if(F=y-T,F<0)F+=f,q=y,k=M[B=0],O=o(k/Y[T-q-1]%10);else if(B=n((F+1)/f),B>=M.length)if(x){for(;M.length<=B;M.push(0));k=O=0,T=1,F%=f,q=F-f+1}else break e;else{for(k=D=M[B],T=1;D>=10;D/=10,T++);F%=f,q=F-f+T,O=q<0?0:o(k/Y[T-q-1]%10)}if(x=x||y<0||M[B+1]!=null||(q<0?k:k%Y[T-q-1]),x=b<4?(O||x)&&(b==0||b==(p.s<0?3:2)):O>5||O==5&&(b==4||x||b==6&&(F>0?q>0?k/Y[T-q]:0:M[B-1])%10&1||b==(p.s<0?8:7)),y<1||!M[0])return M.length=0,x?(y-=p.e+1,M[0]=Y[(f-y%f)%f],p.e=-y||0):M[0]=p.e=0,p;if(F==0?(M.length=B,D=1,B--):(M.length=B+1,D=Y[f-F],M[B]=q>0?o(k/Y[T-q]%Y[q])*D:0),x)for(;;)if(B==0){for(F=1,q=M[0];q>=10;q/=10,F++);for(q=M[0]+=D,D=1;q>=10;q/=10,D++);F!=D&&(p.e++,M[0]==l&&(M[0]=1));break}else{if(M[B]+=D,M[B]!=l)break;M[B--]=0,D=1}for(F=M.length;M[--F]===0;M.pop());}p.e>Q?p.c=p.e=null:p.e=te?S(y,b):N(y,b,"0"),p.s<0?"-"+y:y)}return W.absoluteValue=W.abs=function(){var p=new G(this);return p.s<0&&(p.s=1),p},W.comparedTo=function(p,y){return g(this,new G(p,y))},W.decimalPlaces=W.dp=function(p,y){var b,x,T,F=this;if(p!=null)return C(p,0,E),y==null?y=le:C(y,0,8),Pe(new G(F),p+F.e+1,y);if(!(b=F.c))return null;if(x=((T=b.length-1)-v(this.e/f))*f,T=b[T])for(;T%10==0;T/=10,x--);return x<0&&(x=0),x},W.dividedBy=W.div=function(p,y){return L(this,new G(p,y),de,le)},W.dividedToIntegerBy=W.idiv=function(p,y){return L(this,new G(p,y),0,1)},W.exponentiatedBy=W.pow=function(p,y){var b,x,T,F,q,D,k,B,O,M=this;if(p=new G(p),p.c&&!p.isInteger())throw Error(a+"Exponent not an integer: "+Ie(p));if(y!=null&&(y=new G(y)),D=p.e>14,!M.c||!M.c[0]||M.c[0]==1&&!M.e&&M.c.length==1||!p.c||!p.c[0])return O=new G(Math.pow(+Ie(M),D?p.s*(2-R(p)):+Ie(p))),y?O.mod(y):O;if(k=p.s<0,y){if(y.c?!y.c[0]:!y.s)return new G(NaN);x=!k&&M.isInteger()&&y.isInteger(),x&&(M=M.mod(y))}else{if(p.e>9&&(M.e>0||M.e<-1||(M.e==0?M.c[0]>1||D&&M.c[1]>=24e7:M.c[0]<8e13||D&&M.c[0]<=9999975e7)))return F=M.s<0&&R(p)?-0:0,M.e>-1&&(F=1/F),new G(k?1/F:F);ne&&(F=n(ne/f+2))}for(D?(b=new G(.5),k&&(p.s=1),B=R(p)):(T=Math.abs(+Ie(p)),B=T%2),O=new G(we);;){if(B){if(O=O.times(M),!O.c)break;F?O.c.length>F&&(O.c.length=F):x&&(O=O.mod(y))}if(T){if(T=o(T/2),T===0)break;B=T%2}else if(p=p.times(b),Pe(p,p.e+1,1),p.e>14)B=R(p);else{if(T=+Ie(p),T===0)break;B=T%2}M=M.times(M),F?M.c&&M.c.length>F&&(M.c.length=F):x&&(M=M.mod(y))}return x?O:(k&&(O=we.div(O)),y?O.mod(y):F?Pe(O,ne,le,q):O)},W.integerValue=function(p){var y=new G(this);return p==null?p=le:C(p,0,8),Pe(y,y.e+1,p)},W.isEqualTo=W.eq=function(p,y){return g(this,new G(p,y))===0},W.isFinite=function(){return!!this.c},W.isGreaterThan=W.gt=function(p,y){return g(this,new G(p,y))>0},W.isGreaterThanOrEqualTo=W.gte=function(p,y){return(y=g(this,new G(p,y)))===1||y===0},W.isInteger=function(){return!!this.c&&v(this.e/f)>this.c.length-2},W.isLessThan=W.lt=function(p,y){return g(this,new G(p,y))<0},W.isLessThanOrEqualTo=W.lte=function(p,y){return(y=g(this,new G(p,y)))===-1||y===0},W.isNaN=function(){return!this.s},W.isNegative=function(){return this.s<0},W.isPositive=function(){return this.s>0},W.isZero=function(){return!!this.c&&this.c[0]==0},W.minus=function(p,y){var b,x,T,F,q=this,D=q.s;if(p=new G(p,y),y=p.s,!D||!y)return new G(NaN);if(D!=y)return p.s=-y,q.plus(p);var k=q.e/f,B=p.e/f,O=q.c,M=p.c;if(!k||!B){if(!O||!M)return O?(p.s=-y,p):new G(M?q:NaN);if(!O[0]||!M[0])return M[0]?(p.s=-y,p):new G(O[0]?q:le==3?-0:0)}if(k=v(k),B=v(B),O=O.slice(),D=k-B){for((F=D<0)?(D=-D,T=O):(B=k,T=M),T.reverse(),y=D;y--;T.push(0));T.reverse()}else for(x=(F=(D=O.length)<(y=M.length))?D:y,D=y=0;y0)for(;y--;O[b++]=0);for(y=l-1;x>D;){if(O[--x]=0;){for(b=0,Y=je[T]%xe,X=je[T]/xe|0,q=k,F=T+q;F>T;)B=Ae[--q]%xe,O=Ae[q]/xe|0,D=X*B+O*Y,B=Y*B+D%xe*xe+Ee[F]+b,b=(B/ke|0)+(D/xe|0)+X*O,Ee[F--]=B%ke;Ee[F]=b}return b?++x:Ee.splice(0,1),rr(p,Ee,x)},W.negated=function(){var p=new G(this);return p.s=-p.s||null,p},W.plus=function(p,y){var b,x=this,T=x.s;if(p=new G(p,y),y=p.s,!T||!y)return new G(NaN);if(T!=y)return p.s=-y,x.minus(p);var F=x.e/f,q=p.e/f,D=x.c,k=p.c;if(!F||!q){if(!D||!k)return new G(T/0);if(!D[0]||!k[0])return k[0]?p:new G(D[0]?x:T*0)}if(F=v(F),q=v(q),D=D.slice(),T=F-q){for(T>0?(q=F,b=k):(T=-T,b=D),b.reverse();T--;b.push(0));b.reverse()}for(T=D.length,y=k.length,T-y<0&&(b=k,k=D,D=b,y=T),T=0;y;)T=(D[--y]=D[y]+k[y]+T)/l|0,D[y]=l===D[y]?0:D[y]%l;return T&&(D=[T].concat(D),++q),rr(p,D,q)},W.precision=W.sd=function(p,y){var b,x,T,F=this;if(p!=null&&p!==!!p)return C(p,1,E),y==null?y=le:C(y,0,8),Pe(new G(F),p,y);if(!(b=F.c))return null;if(T=b.length-1,x=T*f+1,T=b[T]){for(;T%10==0;T/=10,x--);for(T=b[0];T>=10;T/=10,x++);}return p&&F.e+1>x&&(x=F.e+1),x},W.shiftedBy=function(p){return C(p,-h,h),this.times("1e"+p)},W.squareRoot=W.sqrt=function(){var p,y,b,x,T,F=this,q=F.c,D=F.s,k=F.e,B=de+4,O=new G("0.5");if(D!==1||!q||!q[0])return new G(!D||D<0&&(!q||q[0])?NaN:q?F:1/0);if(D=Math.sqrt(+Ie(F)),D==0||D==1/0?(y=w(q),(y.length+k)%2==0&&(y+="0"),D=Math.sqrt(+y),k=v((k+1)/2)-(k<0||k%2),D==1/0?y="5e"+k:(y=D.toExponential(),y=y.slice(0,y.indexOf("e")+1)+k),b=new G(y)):b=new G(D+""),b.c[0]){for(k=b.e,D=k+B,D<3&&(D=0);;)if(T=b,b=O.times(T.plus(L(F,T,B,1))),w(T.c).slice(0,D)===(y=w(b.c)).slice(0,D))if(b.e0&&Ee>0){for(F=Ee%D||D,O=X.substr(0,F);F0&&(O+=B+X.slice(F)),Y&&(O="-"+O)}x=M?O+(b.decimalSeparator||"")+((k=+b.fractionGroupSize)?M.replace(new RegExp("\\d{"+k+"}\\B","g"),"$&"+(b.fractionGroupSeparator||"")):M):O}return(b.prefix||"")+x+(b.suffix||"")},W.toFraction=function(p){var y,b,x,T,F,q,D,k,B,O,M,Y,X=this,Ee=X.c;if(p!=null&&(D=new G(p),!D.isInteger()&&(D.c||D.s!==1)||D.lt(we)))throw Error(a+"Argument "+(D.isInteger()?"out of range: ":"not an integer: ")+Ie(D));if(!Ee)return new G(X);for(y=new G(we),B=b=new G(we),x=k=new G(we),Y=w(Ee),F=y.e=Y.length-X.e-1,y.c[0]=d[(q=F%f)<0?f+q:q],p=!p||D.comparedTo(y)>0?F>0?y:B:D,q=Q,Q=1/0,D=new G(Y),k.c[0]=0;O=L(D,y,0,1),T=b.plus(O.times(x)),T.comparedTo(p)!=1;)b=x,x=T,B=k.plus(O.times(T=B)),k=T,y=D.minus(O.times(T=y)),D=T;return T=L(p.minus(b),x,0,1),k=k.plus(T.times(B)),b=b.plus(T.times(x)),k.s=B.s=X.s,F=F*2,M=L(B,x,F,le).minus(X).abs().comparedTo(L(k,b,F,le).minus(X).abs())<1?[B,x]:[k,b],Q=q,M},W.toNumber=function(){return+Ie(this)},W.toPrecision=function(p,y){return p!=null&&C(p,1,E),he(this,p,y,2)},W.toString=function(p){var y,b=this,x=b.s,T=b.e;return T===null?x?(y="Infinity",x<0&&(y="-"+y)):y="NaN":(p==null?y=T<=ge||T>=te?S(w(b.c),T):N(w(b.c),T,"0"):p===10&&qe?(b=Pe(new G(b),de+T+1,le),y=N(w(b.c),b.e,"0")):(C(p,2,Be.length,"Base"),y=H(N(w(b.c),T,"0"),10,p,x,!0)),x<0&&b.c[0]&&(y="-"+y)),y},W.valueOf=W.toJSON=function(){return Ie(this)},W._isBigNumber=!0,j!=null&&G.set(j),G}function v(j){var L=j|0;return j>0||j===L?L:L-1}function w(j){for(var L,H,K=1,W=j.length,we=j[0]+"";Kte^H?1:-1;for(le=(ge=W.length)<(te=we.length)?ge:te,de=0;dewe[de]^H?1:-1;return ge==te?0:ge>te^H?1:-1}function C(j,L,H,K){if(jH||j!==o(j))throw Error(a+(K||"Argument")+(typeof j=="number"?jH?" out of range: ":" not an integer: ":" not a primitive number: ")+String(j))}function R(j){var L=j.c.length-1;return v(j.e/f)==L&&j.c[L]%2!=0}function S(j,L){return(j.length>1?j.charAt(0)+"."+j.slice(1):j)+(L<0?"e":"e+")+L}function N(j,L,H){var K,W;if(L<0){for(W=H+".";++L;W+=H);j=W+j}else if(K=j.length,++L>K){for(W=H,L-=K;--L;W+=H);j+=W}else L{var Bh=Eu(),Ih=Nh.exports;(function(){"use strict";function r(h){return h<10?"0"+h:h}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,t=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n,o,a={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},u;function l(h){return t.lastIndex=0,t.test(h)?'"'+h.replace(t,function(d){var _=a[d];return typeof _=="string"?_:"\\u"+("0000"+d.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+h+'"'}function f(h,d){var _,E,P,v,w=n,g,C=d[h],R=C!=null&&(C instanceof Bh||Bh.isBigNumber(C));switch(C&&typeof C=="object"&&typeof C.toJSON=="function"&&(C=C.toJSON(h)),typeof u=="function"&&(C=u.call(d,h,C)),typeof C){case"string":return R?C:l(C);case"number":return isFinite(C)?String(C):"null";case"boolean":case"null":case"bigint":return String(C);case"object":if(!C)return"null";if(n+=o,g=[],Object.prototype.toString.apply(C)==="[object Array]"){for(v=C.length,_=0;_{var Zo=null,J_=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,V_=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/,K_=function(r){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(r!=null){if(r.strict===!0&&(e.strict=!0),r.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=r.alwaysParseAsBig===!0?r.alwaysParseAsBig:!1,e.useNativeBigInt=r.useNativeBigInt===!0?r.useNativeBigInt:!1,typeof r.constructorAction<"u")if(r.constructorAction==="error"||r.constructorAction==="ignore"||r.constructorAction==="preserve")e.constructorAction=r.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${r.constructorAction}`);if(typeof r.protoAction<"u")if(r.protoAction==="error"||r.protoAction==="ignore"||r.protoAction==="preserve")e.protoAction=r.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${r.protoAction}`)}var t,n,o={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:` +`,r:"\r",t:" "},a,u=function(w){throw{name:"SyntaxError",message:w,at:t,text:a}},l=function(w){return w&&w!==n&&u("Expected '"+w+"' instead of '"+n+"'"),n=a.charAt(t),t+=1,n},f=function(){var w,g="";for(n==="-"&&(g="-",l("-"));n>="0"&&n<="9";)g+=n,l();if(n===".")for(g+=".";l()&&n>="0"&&n<="9";)g+=n;if(n==="e"||n==="E")for(g+=n,l(),(n==="-"||n==="+")&&(g+=n,l());n>="0"&&n<="9";)g+=n,l();if(w=+g,!isFinite(w))u("Bad number");else return Zo==null&&(Zo=Eu()),g.length>15?e.storeAsString?g:e.useNativeBigInt?BigInt(g):new Zo(g):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(w):new Zo(w):w},h=function(){var w,g,C="",R;if(n==='"')for(var S=t;l();){if(n==='"')return t-1>S&&(C+=a.substring(S,t-1)),l(),C;if(n==="\\"){if(t-1>S&&(C+=a.substring(S,t-1)),l(),n==="u"){for(R=0,g=0;g<4&&(w=parseInt(l(),16),!!isFinite(w));g+=1)R=R*16+w;C+=String.fromCharCode(R)}else if(typeof o[n]=="string")C+=o[n];else break;S=t}}u("Bad string")},d=function(){for(;n&&n<=" ";)l()},_=function(){switch(n){case"t":return l("t"),l("r"),l("u"),l("e"),!0;case"f":return l("f"),l("a"),l("l"),l("s"),l("e"),!1;case"n":return l("n"),l("u"),l("l"),l("l"),null}u("Unexpected '"+n+"'")},E,P=function(){var w=[];if(n==="["){if(l("["),d(),n==="]")return l("]"),w;for(;n;){if(w.push(E()),d(),n==="]")return l("]"),w;l(","),d()}}u("Bad array")},v=function(){var w,g=Object.create(null);if(n==="{"){if(l("{"),d(),n==="}")return l("}"),g;for(;n;){if(w=h(),d(),l(":"),e.strict===!0&&Object.hasOwnProperty.call(g,w)&&u('Duplicate key "'+w+'"'),J_.test(w)===!0?e.protoAction==="error"?u("Object contains forbidden prototype property"):e.protoAction==="ignore"?E():g[w]=E():V_.test(w)===!0?e.constructorAction==="error"?u("Object contains forbidden constructor property"):e.constructorAction==="ignore"?E():g[w]=E():g[w]=E(),d(),n==="}")return l("}"),g;l(","),d()}}u("Bad object")};return E=function(){switch(d(),n){case"{":return v();case"[":return P();case'"':return h();case"-":return f();default:return n>="0"&&n<="9"?f():_()}},function(w,g){var C;return a=w+"",t=0,n=" ",C=E(),d(),n&&u("Syntax error"),typeof g=="function"?function R(S,N){var j,L,H=S[N];return H&&typeof H=="object"&&Object.keys(H).forEach(function(K){L=R(H,K),L!==void 0?H[K]=L:delete H[K]}),g.call(S,N,H)}({"":C},""):C}};jh.exports=K_});var $h=z((XD,ei)=>{var Uh=qh().stringify,Mh=Lh();ei.exports=function(r){return{parse:Mh(r),stringify:Uh}};ei.exports.parse=Mh();ei.exports.stringify=Uh});var wu=z(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.GCE_LINUX_BIOS_PATHS=void 0;jt.isGoogleCloudServerless=Wh;jt.isGoogleComputeEngineLinux=zh;jt.isGoogleComputeEngineMACAddress=Jh;jt.isGoogleComputeEngine=Vh;jt.detectGCPResidency=X_;var Hh=require("fs"),Gh=require("os");jt.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var Y_=/^42:01/;function Wh(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function zh(){if((0,Gh.platform)()!=="linux")return!1;try{(0,Hh.statSync)(jt.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let r=(0,Hh.readFileSync)(jt.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(r)}catch{return!1}}function Jh(){let r=(0,Gh.networkInterfaces)();for(let e of Object.values(r))if(e){for(let{mac:t}of e)if(Y_.test(t))return!0}return!1}function Vh(){return zh()||Jh()}function X_(){return Wh()||Vh()}});var Kh=z(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.Colours=void 0;var Xe=class r{static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth=="function"?e.getColorDepth()>2:!0)}static refresh(){r.enabled=r.isEnabled(process==null?void 0:process.stderr),this.enabled?(r.reset="\x1B[0m",r.bright="\x1B[1m",r.dim="\x1B[2m",r.red="\x1B[31m",r.green="\x1B[32m",r.yellow="\x1B[33m",r.blue="\x1B[34m",r.magenta="\x1B[35m",r.cyan="\x1B[36m",r.white="\x1B[37m",r.grey="\x1B[90m"):(r.reset="",r.bright="",r.dim="",r.red="",r.green="",r.yellow="",r.blue="",r.magenta="",r.cyan="",r.white="",r.grey="")}};ti.Colours=Xe;Xe.enabled=!1;Xe.reset="";Xe.bright="";Xe.dim="";Xe.red="";Xe.green="";Xe.yellow="";Xe.blue="";Xe.magenta="";Xe.cyan="";Xe.white="";Xe.grey="";Xe.refresh()});var Zh=z(Se=>{"use strict";var Q_=Se&&Se.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),Z_=Se&&Se.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),Yh=Se&&Se.__importStar||function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(n[n.length]=o);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),o=0;othis.on(n,o)}),this.func.debug=(...n)=>this.invokeSeverity(Lt.DEBUG,...n),this.func.info=(...n)=>this.invokeSeverity(Lt.INFO,...n),this.func.warn=(...n)=>this.invokeSeverity(Lt.WARNING,...n),this.func.error=(...n)=>this.invokeSeverity(Lt.ERROR,...n),this.func.sublog=n=>Qh(n,this.func)}invoke(e,...t){if(this.upstream)try{this.upstream(e,...t)}catch{}try{this.emit("log",e,t)}catch{}}invokeSeverity(e,...t){this.invoke({severity:e},...t)}};Se.AdhocDebugLogger=bs;Se.placeholder=new bs("",()=>{}).func;var Pn=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let t=(e=Cs.env[Se.env.nodeEnables])!==null&&e!==void 0?e:"*";t==="all"&&(t="*"),this.filters=t.split(",")}log(e,t,...n){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let o=this.cached.get(e);o||(o=this.makeLogger(e),this.cached.set(e,o)),o(t,...n)}catch(o){console.error(o)}}};Se.DebugLogBackendBase=Pn;var Au=class extends Pn{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(t,...n)=>{var o;let a=`${pt.Colours.green}${e}${pt.Colours.reset}`,u=`${pt.Colours.yellow}${Cs.pid}${pt.Colours.reset}`,l;switch(t.severity){case Lt.ERROR:l=`${pt.Colours.red}${t.severity}${pt.Colours.reset}`;break;case Lt.INFO:l=`${pt.Colours.magenta}${t.severity}${pt.Colours.reset}`;break;case Lt.WARNING:l=`${pt.Colours.yellow}${t.severity}${pt.Colours.reset}`;break;default:l=(o=t.severity)!==null&&o!==void 0?o:Lt.DEFAULT;break}let f=Xh.formatWithOptions({colors:pt.Colours.enabled},...n),h=Object.assign({},t);delete h.severity;let d=Object.getOwnPropertyNames(h).length?JSON.stringify(h):"",_=d?`${pt.Colours.grey}${d}${pt.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",u,a,l,f,d?` ${_}`:"")}:()=>{}}setFilters(){let t=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${t}$`,"i")}};function Du(){return new Au}var Su=class extends Pn{constructor(e){super(),this.debugPkg=e}makeLogger(e){let t=this.debugPkg(e);return(n,...o)=>{t(o[0],...o.slice(1))}}setFilters(){var e;let t=(e=Cs.env.NODE_DEBUG)!==null&&e!==void 0?e:"";Cs.env.NODE_DEBUG=`${t}${t?",":""}${this.filters.join(",")}`}};function tC(r){return new Su(r)}var vu=class extends Pn{constructor(e){var t;super(),this.upstream=(t=e)!==null&&t!==void 0?t:void 0}makeLogger(e){var t;let n=(t=this.upstream)===null||t===void 0?void 0:t.makeLogger(e);return(o,...a)=>{var u;let l=(u=o.severity)!==null&&u!==void 0?u:Lt.INFO,f=Object.assign({severity:l,message:Xh.format(...a)},o),h=JSON.stringify(f);n?n(o,h):console.log("%s",h)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function rC(r){return new vu(r)}Se.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var Tu=new Map,mt;function nC(r){mt=r,Tu.clear()}function Qh(r,e){if(!mt&&!Cs.env[Se.env.nodeEnables]||!r)return Se.placeholder;e&&(r=`${e.instance.namespace}:${r}`);let t=Tu.get(r);if(t)return t.func;if(mt===null)return Se.placeholder;mt===void 0&&(mt=Du());let n=(()=>{let o;return new bs(r,(u,...l)=>{if(o!==mt){if(mt===null)return;mt===void 0&&(mt=Du()),o=mt}mt?.log(r,u,...l)})})();return Tu.set(r,n),n.func}});var Ru=z(rn=>{"use strict";var sC=rn&&rn.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),oC=rn&&rn.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&sC(e,r,t)};Object.defineProperty(rn,"__esModule",{value:!0});oC(Zh(),rn)});var ws=z(oe=>{"use strict";var tp=oe&&oe.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),iC=oe&&oe.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),aC=oe&&oe.__importStar||function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(n[n.length]=o);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),o=0;o{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}})}async function Es(r,e={},t=3,n=!1){let o=new Headers(oe.HEADERS),a="",u={};if(typeof r=="object"){let _=r;new Headers(_.headers).forEach((E,P)=>o.set(P,E)),a=_.metadataKey,u=_.params||u,t=_.noResponseRetries||t,n=_.fastFail||n}else a=r;typeof e=="string"?a+=`/${e}`:(dC(e),e.property&&(a+=`/${e.property}`),new Headers(e.headers).forEach((_,E)=>o.set(E,_)),u=e.params||u);let l=n?hC:ku.request,f={url:`${Fu()}/${a}`,headers:o,retryConfig:{noResponseRetries:t},params:u,responseType:"text",timeout:np()};ep.info("instance request %j",f);let h=await l(f);ep.info("instance metadata is %s",h.data);let d=h.headers.get(oe.HEADER_NAME);if(d!==oe.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${oe.HEADER_NAME} header. Expected '${oe.HEADER_VALUE}', got ${d?`'${d}'`:"no header"}`);if(typeof h.data=="string")try{return cC.parse(h.data)}catch{}return h.data}async function hC(r){let e={...r,url:r.url?.toString().replace(Fu(),Fu(oe.SECONDARY_HOST_ADDRESS))},t=(0,ku.request)(r),n=(0,ku.request)(e);return Promise.any([t,n])}function pC(r){return Es("instance",r)}function mC(r){return Es("project",r)}function gC(r){return Es("universe",r)}async function yC(r){let e={};return await Promise.all(r.map(t=>(async()=>{let n=await Es(t),o=t.metadataKey;e[o]=n})())),e}function _C(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var ri;async function CC(){if(process.env.METADATA_SERVER_DETECTION){let r=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(r in oe.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${r}\`, but it should be \`${Object.keys(oe.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(r){case"assume-present":return!0;case"none":return!1;case"bios-only":return Ou();case"ping-only":}}try{return ri===void 0&&(ri=Es("instance",void 0,_C(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await ri,!0}catch(r){let e=r;if(process.env.DEBUG_AUTH&&console.info(e),e.type==="request-timeout"||e.response&&e.response.status===404)return!1;if(!(e.response&&e.response.status===404)&&(!e.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(e.code.toString()))){let t="UNKNOWN";e.code&&(t=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${t}`,"MetadataLookupWarning")}return!1}}function bC(){ri=void 0}oe.gcpResidencyCache=null;function Ou(){return oe.gcpResidencyCache===null&&rp(),oe.gcpResidencyCache}function rp(r=null){oe.gcpResidencyCache=r!==null?r:(0,lC.detectGCPResidency)()}function np(){return Ou()?0:3e3}uC(wu(),oe)});var ip=z(ni=>{"use strict";ni.byteLength=wC;ni.toByteArray=DC;ni.fromByteArray=TC;var Kt=[],vt=[],EC=typeof Uint8Array<"u"?Uint8Array:Array,Pu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(nn=0,sp=Pu.length;nn0)throw new Error("Invalid string. Length must be a multiple of 4");var t=r.indexOf("=");t===-1&&(t=e);var n=t===e?0:4-t%4;return[t,n]}function wC(r){var e=op(r),t=e[0],n=e[1];return(t+n)*3/4-n}function AC(r,e,t){return(e+t)*3/4-t}function DC(r){var e,t=op(r),n=t[0],o=t[1],a=new EC(AC(r,n,o)),u=0,l=o>0?n-4:n,f;for(f=0;f>16&255,a[u++]=e>>8&255,a[u++]=e&255;return o===2&&(e=vt[r.charCodeAt(f)]<<2|vt[r.charCodeAt(f+1)]>>4,a[u++]=e&255),o===1&&(e=vt[r.charCodeAt(f)]<<10|vt[r.charCodeAt(f+1)]<<4|vt[r.charCodeAt(f+2)]>>2,a[u++]=e>>8&255,a[u++]=e&255),a}function SC(r){return Kt[r>>18&63]+Kt[r>>12&63]+Kt[r>>6&63]+Kt[r&63]}function vC(r,e,t){for(var n,o=[],a=e;al?l:u+a));return n===1?(e=r[t-1],o.push(Kt[e>>2]+Kt[e<<4&63]+"==")):n===2&&(e=(r[t-2]<<8)+r[t-1],o.push(Kt[e>>10]+Kt[e>>4&63]+Kt[e<<2&63]+"=")),o.join("")}});var Bu=z(xu=>{"use strict";Object.defineProperty(xu,"__esModule",{value:!0});xu.fromArrayBufferToHex=RC;function RC(r){return Array.from(new Uint8Array(r)).map(t=>t.toString(16).padStart(2,"0")).join("")}});var ap=z(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.BrowserCrypto=void 0;var xn=ip(),kC=Bu(),Iu=class r{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let t=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",t);return xn.fromByteArray(new Uint8Array(n))}randomBytesBase64(e){let t=new Uint8Array(e);return window.crypto.getRandomValues(t),xn.fromByteArray(t)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,t,n){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},a=new TextEncoder().encode(t),u=xn.toByteArray(r.padBase64(n)),l=await window.crypto.subtle.importKey("jwk",e,o,!0,["verify"]);return await window.crypto.subtle.verify(o,l,u,a)}async sign(e,t){let n={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(t),a=await window.crypto.subtle.importKey("jwk",e,n,!0,["sign"]),u=await window.crypto.subtle.sign(n,a,o);return xn.fromByteArray(new Uint8Array(u))}decodeBase64StringUtf8(e){let t=xn.toByteArray(r.padBase64(e));return new TextDecoder().decode(t)}encodeBase64StringUtf8(e){let t=new TextEncoder().encode(e);return xn.fromByteArray(t)}async sha256DigestHex(e){let t=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",t);return(0,kC.fromArrayBufferToHex)(n)}async signWithHmacSha256(e,t){let n=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),o=new TextEncoder,a=await window.crypto.subtle.importKey("raw",o.encode(n),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",a,o.encode(t))}};si.BrowserCrypto=Iu});var up=z(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});oi.NodeCrypto=void 0;var Bn=require("crypto"),Nu=class{async sha256DigestBase64(e){return Bn.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return Bn.randomBytes(e).toString("base64")}async verify(e,t,n){let o=Bn.createVerify("RSA-SHA256");return o.update(t),o.end(),o.verify(e,n,"base64")}async sign(e,t){let n=Bn.createSign("RSA-SHA256");return n.update(t),n.end(),n.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return Bn.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,t){let n=typeof e=="string"?e:OC(e);return FC(Bn.createHmac("sha256",n).update(t).digest())}};oi.NodeCrypto=Nu;function FC(r){return r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)}function OC(r){return Buffer.from(r)}});var As=z(mr=>{"use strict";var PC=mr&&mr.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),xC=mr&&mr.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&PC(e,r,t)};Object.defineProperty(mr,"__esModule",{value:!0});mr.createCrypto=NC;mr.hasBrowserCrypto=cp;var BC=ap(),IC=up();xC(Bu(),mr);function NC(){return cp()?new BC.BrowserCrypto:new IC.NodeCrypto}function cp(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var In=z((qu,fp)=>{var ii=require("buffer"),Yt=ii.Buffer;function lp(r,e){for(var t in r)e[t]=r[t]}Yt.from&&Yt.alloc&&Yt.allocUnsafe&&Yt.allocUnsafeSlow?fp.exports=ii:(lp(ii,qu),qu.Buffer=sn);function sn(r,e,t){return Yt(r,e,t)}sn.prototype=Object.create(Yt.prototype);lp(Yt,sn);sn.from=function(r,e,t){if(typeof r=="number")throw new TypeError("Argument must not be a number");return Yt(r,e,t)};sn.alloc=function(r,e,t){if(typeof r!="number")throw new TypeError("Argument must be a number");var n=Yt(r);return e!==void 0?typeof t=="string"?n.fill(e,t):n.fill(e):n.fill(0),n};sn.allocUnsafe=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return Yt(r)};sn.allocUnsafeSlow=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return ii.SlowBuffer(r)}});var hp=z((uS,dp)=>{"use strict";function ju(r){var e=(r/8|0)+(r%8===0?0:1);return e}var qC={ES256:ju(256),ES384:ju(384),ES512:ju(521)};function jC(r){var e=qC[r];if(e)return e;throw new Error('Unknown algorithm "'+r+'"')}dp.exports=jC});var Lu=z((cS,Cp)=>{"use strict";var ai=In().Buffer,mp=hp(),ui=128,gp=0,LC=32,UC=16,MC=2,yp=UC|LC|gp<<6,ci=MC|gp<<6;function $C(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function _p(r){if(ai.isBuffer(r))return r;if(typeof r=="string")return ai.from(r,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function HC(r,e){r=_p(r);var t=mp(e),n=t+1,o=r.length,a=0;if(r[a++]!==yp)throw new Error('Could not find expected "seq"');var u=r[a++];if(u===(ui|1)&&(u=r[a++]),o-a=ui;return o&&--n,n}function GC(r,e){r=_p(r);var t=mp(e),n=r.length;if(n!==t*2)throw new TypeError('"'+e+'" signatures must be "'+t*2+'" bytes, saw "'+n+'"');var o=pp(r,0,t),a=pp(r,t,r.length),u=t-o,l=t-a,f=2+u+1+1+l,h=f{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.LRUCache=void 0;gr.snakeToCamel=Ep;gr.originalOrCamelOptions=VC;gr.removeUndefinedValuesInObject=KC;gr.isValidFile=YC;gr.getWellKnownCertificateConfigFileLocation=XC;var WC=require("fs"),zC=require("os"),Uu=require("path"),JC="certificate_config.json",bp="gcloud";function Ep(r){return r.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function VC(r){function e(t){let n=r||{};return n[t]??n[Ep(t)]}return{get:e}}var Mu=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,t){this.#e.delete(e),this.#e.set(e,{value:t,lastAccessed:Date.now()})}set(e,t){this.#t(e,t),this.#r()}get(e){let t=this.#e.get(e);if(t)return this.#t(e,t.value),this.#r(),t.value}#r(){let e=this.maxAge?Date.now()-this.maxAge:0,t=this.#e.entries().next();for(;!t.done&&(this.#e.size>this.capacity||t.value[1].lastAccessed{(t===void 0||t==="undefined")&&delete r[e]}),r}async function YC(r){try{return(await WC.promises.lstat(r)).isFile()}catch{return!1}}function XC(){let r=process.env.CLOUDSDK_CONFIG||(QC()?Uu.join(process.env.APPDATA||"",bp):Uu.join(process.env.HOME||"",".config",bp));return Uu.join(r,JC)}function QC(){return zC.platform().startsWith("win")}});var wp=z((fS,ZC)=>{ZC.exports={name:"google-auth-library",version:"10.2.0",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:"googleapis/google-auth-library-nodejs.git",keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.0.0","gcp-metadata":"^7.0.0","google-logging-utils":"^1.0.0",gtoken:"^8.0.0",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","assert-rejects":"^1.0.0",c8:"^10.0.0",codecov:"^3.0.2",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^4.0.0","jsdoc-region-tag":"^3.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",linkinator:"^6.1.2",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.1","null-loader":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","ts-loader":"^8.0.0",typescript:"^5.1.6",webpack:"^5.21.2","webpack-cli":"^4.0.0"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start","docs-test":"linkinator docs","predocs-test":"npm run docs",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0"}});var $u=z(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.USER_AGENT=Ir.PRODUCT_NAME=Ir.pkg=void 0;var Ap=wp();Ir.pkg=Ap;var Dp="google-api-nodejs-client";Ir.PRODUCT_NAME=Dp;var eb=`${Dp}/${Ap.version}`;Ir.USER_AGENT=eb});var gt=z(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.AuthClient=Mt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=Mt.DEFAULT_UNIVERSE=void 0;var tb=require("events"),Hu=Je(),rb=Ut(),nb=Ru(),Gu=$u();Mt.DEFAULT_UNIVERSE="googleapis.com";Mt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=5*60*1e3;var Wu=class r extends tb.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=Mt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=Mt.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let t=(0,rb.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=t.get("project_id")??null,this.quotaProjectId=t.get("quota_project_id"),this.credentials=t.get("credentials")??{},this.universeDomain=t.get("universe_domain")??Mt.DEFAULT_UNIVERSE,this.transporter=e.transporter??new Hu.Gaxios(e.transporterOptions),t.get("useAuthRequestParameters")!==!1&&(this.transporter.interceptors.request.add(r.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(r.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let t=e[0],n=e[1],o,a=new Headers;return typeof t=="string"?o=new URL(t):t instanceof URL?o=t:t&&t.url&&(o=new URL(t.url)),t&&typeof t=="object"&&"headers"in t&&Hu.Gaxios.mergeHeaders(a,t.headers),n&&Hu.Gaxios.mergeHeaders(a,new Headers(n.headers)),typeof t=="object"&&!(t instanceof URL)?this.request({...n,...t,headers:a,url:o}):this.request({...n,headers:a,url:o})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,t){let n=t.get("x-goog-user-project"),o=t.get("authorization");return n&&e.set("x-goog-user-project",n),o&&e.set("authorization",o),e}static log=(0,nb.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let n=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${n}`)}let t=e.headers.get("User-Agent");t?t.includes(`${Gu.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${t} ${Gu.USER_AGENT}`):e.headers.set("User-Agent",Gu.USER_AGENT);try{let n=e,o=n[r.RequestMethodNameSymbol],a=`${Math.floor(Math.random()*1e3)}`;n[r.RequestLogIdSymbol]=a;let u={url:e.url,headers:e.headers};o?r.log.info("%s [%s] request %j",o,a,u):r.log.info("[%s] request %j",a,u)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let t=e.config,n=t[r.RequestMethodNameSymbol],o=t[r.RequestLogIdSymbol];n?r.log.info("%s [%s] response %j",n,o,e.data):r.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let t=e.config,n=t[r.RequestMethodNameSymbol],o=t[r.RequestLogIdSymbol];n?r.log.info("%s [%s] error %j",n,o,e.response?.data):r.log.error("[%s] error %j",o,e.response?.data)}catch{}throw e}};static setMethodName(e,t){try{let n=e;n[r.RequestMethodNameSymbol]=t}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};Mt.AuthClient=Wu});var Ju=z(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});li.LoginTicket=void 0;var zu=class{envelope;payload;constructor(e,t){this.envelope=e,this.payload=t}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}};li.LoginTicket=zu});var on=z(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.OAuth2Client=Xt.ClientAuthentication=Xt.CertificateFormat=Xt.CodeChallengeMethod=void 0;var Sp=Je(),sb=require("querystring"),ob=require("stream"),ib=Lu(),vp=Ut(),Vu=As(),Nn=gt(),ab=Ju(),Tp;(function(r){r.Plain="plain",r.S256="S256"})(Tp||(Xt.CodeChallengeMethod=Tp={}));var yr;(function(r){r.PEM="PEM",r.JWK="JWK"})(yr||(Xt.CertificateFormat=yr={}));var Ds;(function(r){r.ClientSecretPost="ClientSecretPost",r.ClientSecretBasic="ClientSecretBasic",r.None="None"})(Ds||(Xt.ClientAuthentication=Ds={}));var Ku=class r extends Nn.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=yr.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},t,n){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:t,redirectUri:n}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints},this.clientAuthentication=e.clientAuthentication||Ds.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");return e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" ")),this.endpoints.oauth2AuthBaseUrl.toString()+"?"+sb.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,Vu.createCrypto)(),n=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),a=(await e.sha256DigestBase64(n)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:n,codeChallenge:a}}getToken(e,t){let n=typeof e=="string"?{code:e}:e;if(t)this.getTokenAsync(n).then(o=>t(null,o.tokens,o.res),o=>t(o,null,o.response));else return this.getTokenAsync(n)}async getTokenAsync(e){let t=this.endpoints.oauth2TokenUrl.toString(),n=new Headers,o={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===Ds.ClientSecretBasic){let f=Buffer.from(`${this._clientId}:${this._clientSecret}`);n.set("authorization",`Basic ${f.toString("base64")}`)}this.clientAuthentication===Ds.ClientSecretPost&&(o.client_secret=this._clientSecret);let a={...r.RETRY_CONFIG,method:"POST",url:t,data:new URLSearchParams((0,vp.removeUndefinedValuesInObject)(o)),headers:n};Nn.AuthClient.setMethodName(a,"getTokenAsync");let u=await this.transporter.request(a),l=u.data;return u.data&&u.data.expires_in&&(l.expiry_date=new Date().getTime()+u.data.expires_in*1e3,delete l.expires_in),this.emit("tokens",l),{tokens:l,res:u}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let t=this.refreshTokenNoCache(e).then(n=>(this.refreshTokenPromises.delete(e),n),n=>{throw this.refreshTokenPromises.delete(e),n});return this.refreshTokenPromises.set(e,t),t}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let t=this.endpoints.oauth2TokenUrl.toString(),n={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},o;try{let u={...r.RETRY_CONFIG,method:"POST",url:t,data:new URLSearchParams((0,vp.removeUndefinedValuesInObject)(n))};Nn.AuthClient.setMethodName(u,"refreshTokenNoCache"),o=await this.transporter.request(u)}catch(u){throw u instanceof Sp.GaxiosError&&u.message==="invalid_grant"&&u.response?.data&&/ReAuth/i.test(u.response.data.error_description)&&(u.message=JSON.stringify(u.response.data)),u}let a=o.data;return o.data&&o.data.expires_in&&(a.expiry_date=new Date().getTime()+o.data.expires_in*1e3,delete a.expires_in),this.emit("tokens",a),{tokens:a,res:o}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(t=>e(null,t.credentials,t.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),t=e.tokens;return t.refresh_token=this.credentials.refresh_token,this.credentials=t,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(t=>e(null,t.token,t.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let n=await this.processAndValidateRefreshHandler();if(n?.access_token)return this.setCredentials(n),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let t=await this.refreshAccessTokenAsync();if(!t.credentials||t.credentials&&!t.credentials.access_token)throw new Error("Could not refresh access token.");return{token:t.credentials.access_token,res:t.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let t=this.credentials;if(!t.access_token&&!t.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(t.access_token&&!this.isTokenExpiring()){t.token_type=t.token_type||"Bearer";let l=new Headers({authorization:t.token_type+" "+t.access_token});return{headers:this.addSharedMetadataHeaders(l)}}if(this.refreshHandler){let l=await this.processAndValidateRefreshHandler();if(l?.access_token){this.setCredentials(l);let f=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(f)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let n=null,o=null;try{n=await this.refreshToken(t.refresh_token),o=n.tokens}catch(l){let f=l;throw f.response&&(f.response.status===403||f.response.status===404)&&(f.message=`Could not refresh access token: ${f.message}`),f}let a=this.credentials;a.token_type=a.token_type||"Bearer",o.refresh_token=a.refresh_token,this.credentials=o;let u=new Headers({authorization:a.token_type+" "+o.access_token});return{headers:this.addSharedMetadataHeaders(u),res:n.res}}static getRevokeTokenUrl(e){return new r().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let t=new URL(this.endpoints.oauth2RevokeUrl);return t.searchParams.append("token",e),t}revokeToken(e,t){let n={...r.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(Nn.AuthClient.setMethodName(n,"revokeToken"),t)this.transporter.request(n).then(o=>t(null,o),t);else return this.transporter.request(n)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(t=>e(null,t),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw new Error("No access token to revoke.")}request(e,t){if(t)this.requestAsync(e).then(n=>t(null,n),n=>t(n,n.response));else return this.requestAsync(e)}async requestAsync(e,t=!1){try{let n=await this.getRequestMetadataAsync();return e.headers=Sp.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,n.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(n){let o=n.response;if(o){let a=o.status,u=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),l=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,f=o.config.data instanceof ob.Readable,h=a===401||a===403;if(!t&&h&&!f&&u)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!t&&h&&!f&&l){let d=await this.processAndValidateRefreshHandler();return d?.access_token&&this.setCredentials(d),this.requestAsync(e,!0)}}throw n}}verifyIdToken(e,t){if(t&&typeof t!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(t)this.verifyIdTokenAsync(e).then(n=>t(null,n),t);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let t=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,t.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:t}=await this.transporter.request({...r.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),n=Object.assign({expiry_date:new Date().getTime()+t.expires_in*1e3,scopes:t.scope.split(" ")},t);return delete n.expires_in,delete n.scope,n}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(t=>e(null,t.certs,t.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),t=(0,Vu.hasBrowserCrypto)()?yr.JWK:yr.PEM;if(this.certificateExpiry&&e[0-9]+)/.exec(a)?.groups?.maxAge;h&&(u=Number(h)*1e3)}let l={};switch(t){case yr.PEM:l=n.data;break;case yr.JWK:for(let h of n.data.keys)l[h.kid]=h;break;default:throw new Error(`Unsupported certificate format ${t}`)}let f=new Date;return this.certificateExpiry=u===-1?null:new Date(f.getTime()+u),this.certificateCache=l,this.certificateCacheFormat=t,{certs:l,format:t,res:n}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(t=>e(null,t.pubkeys,t.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,t=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let n={...r.RETRY_CONFIG,url:t};Nn.AuthClient.setMethodName(n,"getIapPublicKeysAsync"),e=await this.transporter.request(n)}catch(n){throw n instanceof Error&&(n.message=`Failed to retrieve verification certificates: ${n.message}`),n}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,t,n,o,a){let u=(0,Vu.createCrypto)();a||(a=r.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let l=e.split(".");if(l.length!==3)throw new Error("Wrong number of segments in token: "+e);let f=l[0]+"."+l[1],h=l[2],d,_;try{d=JSON.parse(u.decodeBase64StringUtf8(l[0]))}catch(S){throw S instanceof Error&&(S.message=`Can't parse token envelope: ${l[0]}': ${S.message}`),S}if(!d)throw new Error("Can't parse token envelope: "+l[0]);try{_=JSON.parse(u.decodeBase64StringUtf8(l[1]))}catch(S){throw S instanceof Error&&(S.message=`Can't parse token payload '${l[0]}`),S}if(!_)throw new Error("Can't parse token payload: "+l[1]);if(!Object.prototype.hasOwnProperty.call(t,d.kid))throw new Error("No pem found for envelope: "+JSON.stringify(d));let E=t[d.kid];if(d.alg==="ES256"&&(h=ib.joseToDer(h,"ES256").toString("base64")),!await u.verify(E,f,h))throw new Error("Invalid token signature: "+e);if(!_.iat)throw new Error("No issue time in token: "+JSON.stringify(_));if(!_.exp)throw new Error("No expiration time in token: "+JSON.stringify(_));let v=Number(_.iat);if(isNaN(v))throw new Error("iat field using invalid format");let w=Number(_.exp);if(isNaN(w))throw new Error("exp field using invalid format");let g=new Date().getTime()/1e3;if(w>=g+a)throw new Error("Expiration time too far in future: "+JSON.stringify(_));let C=v-r.CLOCK_SKEW_SECS_,R=w+r.CLOCK_SKEW_SECS_;if(gR)throw new Error("Token used too late, "+g+" > "+R+": "+JSON.stringify(_));if(o&&o.indexOf(_.iss)<0)throw new Error("Invalid issuer, expected one of ["+o+"], but got "+_.iss);if(typeof n<"u"&&n!==null){let S=_.aud,N=!1;if(n.constructor===Array?N=n.indexOf(S)>-1:N=S===n,!N)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new ab.LoginTicket(d,_)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};Xt.OAuth2Client=Ku});var Xu=z(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.Compute=void 0;var ub=Je(),Rp=ws(),cb=on(),Yu=class extends cb.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e=`service-accounts/${this.serviceAccountEmail}/token`,t;try{let o={property:e};this.scopes.length>0&&(o.params={scopes:this.scopes.join(",")}),t=await Rp.instance(o)}catch(o){throw o instanceof ub.GaxiosError&&(o.message=`Could not refresh access token: ${o.message}`,this.wrapError(o)),o}let n=t;return t&&t.expires_in&&(n.expiry_date=new Date().getTime()+t.expires_in*1e3,delete n.expires_in),this.emit("tokens",n),{tokens:n,res:null}}async fetchIdToken(e){let t=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,n;try{let o={property:t};n=await Rp.instance(o)}catch(o){throw o instanceof Error&&(o.message=`Could not fetch ID token: ${o.message}`),o}return n}wrapError(e){let t=e.response;t&&t.status&&(e.status=t.status,t.status===403?e.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+e.message:t.status===404&&(e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message))}};fi.Compute=Yu});var Zu=z(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.IdTokenClient=void 0;var lb=on(),Qu=class extends lb.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let t=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:t,expiry_date:this.getIdTokenExpiryDate(t)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let t=e.split(".")[1];if(t)return JSON.parse(Buffer.from(t,"base64").toString("ascii")).exp*1e3}};di.IdTokenClient=Qu});var ec=z(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.GCPEnv=void 0;qn.clear=fb;qn.getEnv=db;var kp=ws(),_r;(function(r){r.APP_ENGINE="APP_ENGINE",r.KUBERNETES_ENGINE="KUBERNETES_ENGINE",r.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",r.COMPUTE_ENGINE="COMPUTE_ENGINE",r.CLOUD_RUN="CLOUD_RUN",r.NONE="NONE"})(_r||(qn.GCPEnv=_r={}));var Ss;function fb(){Ss=void 0}async function db(){return Ss||(Ss=hb(),Ss)}async function hb(){let r=_r.NONE;return pb()?r=_r.APP_ENGINE:mb()?r=_r.CLOUD_FUNCTIONS:await _b()?await yb()?r=_r.KUBERNETES_ENGINE:gb()?r=_r.CLOUD_RUN:r=_r.COMPUTE_ENGINE:r=_r.NONE,r}function pb(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function mb(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function gb(){return!!process.env.K_CONFIGURATION}async function yb(){try{return await kp.instance("attributes/cluster-name"),!0}catch{return!1}}async function _b(){return kp.isAvailable()}});var tc=z((CS,Fp)=>{var hi=In().Buffer,Cb=require("stream"),bb=require("util");function pi(r){if(this.buffer=null,this.writable=!0,this.readable=!0,!r)return this.buffer=hi.alloc(0),this;if(typeof r.pipe=="function")return this.buffer=hi.alloc(0),r.pipe(this),this;if(r.length||typeof r=="object")return this.buffer=r,this.writable=!1,process.nextTick(function(){this.emit("end",r),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof r+")")}bb.inherits(pi,Cb);pi.prototype.write=function(e){this.buffer=hi.concat([this.buffer,hi.from(e)]),this.emit("data",e)};pi.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};Fp.exports=pi});var Pp=z((bS,Op)=>{"use strict";var vs=require("buffer").Buffer,rc=require("buffer").SlowBuffer;Op.exports=mi;function mi(r,e){if(!vs.isBuffer(r)||!vs.isBuffer(e)||r.length!==e.length)return!1;for(var t=0,n=0;n{var Ln=In().Buffer,Tt=require("crypto"),Bp=Lu(),xp=require("util"),Ab=`"%s" is not a valid algorithm. + Supported algorithms are: + "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,Ts="secret must be a string or buffer",jn="key must be a string or a buffer",Db="key must be a string, a buffer or an object",sc=typeof Tt.createPublicKey=="function";sc&&(jn+=" or a KeyObject",Ts+="or a KeyObject");function Ip(r){if(!Ln.isBuffer(r)&&typeof r!="string"&&(!sc||typeof r!="object"||typeof r.type!="string"||typeof r.asymmetricKeyType!="string"||typeof r.export!="function"))throw $t(jn)}function Np(r){if(!Ln.isBuffer(r)&&typeof r!="string"&&typeof r!="object")throw $t(Db)}function Sb(r){if(!Ln.isBuffer(r)){if(typeof r=="string")return r;if(!sc||typeof r!="object"||r.type!=="secret"||typeof r.export!="function")throw $t(Ts)}}function oc(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function qp(r){r=r.toString();var e=4-r.length%4;if(e!==4)for(var t=0;t{var Ib=require("buffer").Buffer;$p.exports=function(e){return typeof e=="string"?e:typeof e=="number"||Ib.isBuffer(e)?e.toString():JSON.stringify(e)}});var Vp=z((AS,Jp)=>{var Nb=In().Buffer,Hp=tc(),qb=ic(),jb=require("stream"),Gp=ac(),uc=require("util");function Wp(r,e){return Nb.from(r,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Lb(r,e,t){t=t||"utf8";var n=Wp(Gp(r),"binary"),o=Wp(Gp(e),t);return uc.format("%s.%s",n,o)}function zp(r){var e=r.header,t=r.payload,n=r.secret||r.privateKey,o=r.encoding,a=qb(e.alg),u=Lb(e,t,o),l=a.sign(u,n);return uc.format("%s.%s",u,l)}function gi(r){var e=r.secret||r.privateKey||r.key,t=new Hp(e);this.readable=!0,this.header=r.header,this.encoding=r.encoding,this.secret=this.privateKey=this.key=t,this.payload=new Hp(r.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}uc.inherits(gi,jb);gi.prototype.sign=function(){try{var e=zp({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(t){this.readable=!1,this.emit("error",t),this.emit("close")}};gi.sign=zp;Jp.exports=gi});var sm=z((DS,nm)=>{var Yp=In().Buffer,Kp=tc(),Ub=ic(),Mb=require("stream"),Xp=ac(),$b=require("util"),Hb=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function Gb(r){return Object.prototype.toString.call(r)==="[object Object]"}function Wb(r){if(Gb(r))return r;try{return JSON.parse(r)}catch{return}}function Qp(r){var e=r.split(".",1)[0];return Wb(Yp.from(e,"base64").toString("binary"))}function zb(r){return r.split(".",2).join(".")}function Zp(r){return r.split(".")[2]}function Jb(r,e){e=e||"utf8";var t=r.split(".")[1];return Yp.from(t,"base64").toString(e)}function em(r){return Hb.test(r)&&!!Qp(r)}function tm(r,e,t){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}r=Xp(r);var o=Zp(r),a=zb(r),u=Ub(e);return u.verify(a,o,t)}function rm(r,e){if(e=e||{},r=Xp(r),!em(r))return null;var t=Qp(r);if(!t)return null;var n=Jb(r);return(t.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:t,payload:n,signature:Zp(r)}}function Un(r){r=r||{};var e=r.secret||r.publicKey||r.key,t=new Kp(e);this.readable=!0,this.algorithm=r.algorithm,this.encoding=r.encoding,this.secret=this.publicKey=this.key=t,this.signature=new Kp(r.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}$b.inherits(Un,Mb);Un.prototype.verify=function(){try{var e=tm(this.signature.buffer,this.algorithm,this.key.buffer),t=rm(this.signature.buffer,this.encoding);return this.emit("done",e,t),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};Un.decode=rm;Un.isValid=em;Un.verify=tm;nm.exports=Un});var cc=z(Nr=>{var om=Vp(),yi=sm(),Vb=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Nr.ALGORITHMS=Vb;Nr.sign=om.sign;Nr.verify=yi.verify;Nr.decode=yi.decode;Nr.isValid=yi.isValid;Nr.createSign=function(e){return new om(e)};Nr.createVerify=function(e){return new yi(e)}});var bm=z(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});Ci.GoogleToken=void 0;var im=_i(require("fs")),Kb=Je(),Yb=_i(cc()),Xb=_i(require("path")),Qb=require("util");function _i(r,e){if(typeof WeakMap=="function")var t=new WeakMap,n=new WeakMap;return(_i=function(a,u){if(!u&&a&&a.__esModule)return a;var l,f,h={__proto__:null,default:a};if(a===null||Cr(a)!="object"&&typeof a!="function")return h;if(l=u?n:t){if(l.has(a))return l.get(a);l.set(a,h)}for(var d in a)d!=="default"&&{}.hasOwnProperty.call(a,d)&&((f=(l=Object.defineProperty)&&Object.getOwnPropertyDescriptor(a,d))&&(f.get||f.set)?l(h,d,f):h[d]=a[d]);return h})(r,e)}function Cr(r){"@babel/helpers - typeof";return Cr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Cr(r)}function Zb(r,e){mm(r,e),e.add(r)}function eE(r,e,t){mm(r,e),e.set(r,t)}function mm(r,e){if(e.has(r))throw new TypeError("Cannot initialize the same private elements twice on an object")}function am(r,e,t){return r.set(Ht(r,e),t),t}function um(r,e){return r.get(Ht(r,e))}function Ht(r,e,t){if(typeof r=="function"?r===e:r.has(e))return arguments.length<3?e:t;throw new TypeError("Private element is not present on this object")}function cm(r,e){for(var t=0;t3?(Q=ne===fe)&&(K=ae[(H=ae[4])?5:(H=3,3)],ae[4]=ae[5]=r):ae[0]<=J&&((Q=te<2&&Jfe||fe>ne)&&(ae[4]=te,ae[5]=fe,le.n=ne,H=0))}if(Q||te>1)return u;throw de=!0,fe}return function(te,fe,Q){if(W>1)throw TypeError("Generator is already running");for(de&&fe===1&&ge(fe,Q),H=fe,K=Q;(e=H<2?r:K)||!de;){L||(H?H<3?(H>1&&(le.n=-1),ge(H,K)):le.n=K:le.v=K);try{if(W=2,L){if(H||(te="next"),e=L[te]){if(!(e=e.call(L,K)))throw TypeError("iterator result is not an object");if(!e.done)return e;K=e.value,H<2&&(H=0)}else H===1&&(e=L.return)&&e.call(L),H<2&&(K=TypeError("The iterator does not provide a '"+te+"' method"),H=1);L=r}else if((e=(de=le.n<0)?K:S.call(N,le))!==u)break}catch(ae){L=r,H=1,K=ae}finally{W=1}}return{value:e,done:de}}}(P,w,g),!0),R}var u={};function l(){}function f(){}function h(){}e=Object.getPrototypeOf;var d=[][n]?e(e([][n]())):(_t(e={},n,function(){return this}),e),_=h.prototype=l.prototype=Object.create(d);function E(P){return Object.setPrototypeOf?Object.setPrototypeOf(P,h):(P.__proto__=h,_t(P,o,"GeneratorFunction")),P.prototype=Object.create(_),P}return f.prototype=h,_t(_,"constructor",h),_t(h,"constructor",f),f.displayName="GeneratorFunction",_t(h,o,"GeneratorFunction"),_t(_),_t(_,o,"Generator"),_t(_,n,function(){return this}),_t(_,"toString",function(){return"[object Generator]"}),(Ct=function(){return{w:a,m:E}})()}function _t(r,e,t,n){var o=Object.defineProperty;try{o({},"",{})}catch{o=0}_t=function(u,l,f,h){if(l)o?o(u,l,{value:f,enumerable:!h,configurable:!h,writable:!h}):u[l]=f;else{var d=function(E,P){_t(u,E,function(v){return this._invoke(E,P,v)})};d("next",0),d("throw",1),d("return",2)}},_t(r,e,t,n)}function lm(r,e,t,n,o,a,u){try{var l=r[a](u),f=l.value}catch(h){return void t(h)}l.done?e(f):Promise.resolve(f).then(n,o)}function Mn(r){return function(){var e=this,t=arguments;return new Promise(function(n,o){var a=r.apply(e,t);function u(f){lm(a,n,o,u,l,"next",f)}function l(f){lm(a,n,o,u,l,"throw",f)}u(void 0)})}}var fm=im.readFile?(0,Qb.promisify)(im.readFile):Mn(Ct().m(function r(){return Ct().w(function(e){for(;;)switch(e.n){case 0:throw new Fs("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},r)})),dm="https://oauth2.googleapis.com/token",uE="https://oauth2.googleapis.com/revoke?token=",Fs=function(r){function e(t,n){var o;return ym(this,e),o=tE(this,e,[t]),yt(o,"code",void 0),o.code=n,o}return sE(e,r),gm(e)}(lc(Error)),ks=new WeakMap,Qt=new WeakSet,vS=Ci.GoogleToken=function(){function r(e){ym(this,r),Zb(this,Qt),yt(this,"expiresAt",void 0),yt(this,"key",void 0),yt(this,"keyFile",void 0),yt(this,"iss",void 0),yt(this,"sub",void 0),yt(this,"scope",void 0),yt(this,"rawToken",void 0),yt(this,"tokenExpires",void 0),yt(this,"email",void 0),yt(this,"additionalClaims",void 0),yt(this,"eagerRefreshThresholdMillis",void 0),yt(this,"transporter",{request:function(n){return(0,Kb.request)(n)}}),eE(this,ks,void 0),Ht(Qt,this,Cm).call(this,e)}return gm(r,[{key:"accessToken",get:function(){return this.rawToken?this.rawToken.access_token:void 0}},{key:"idToken",get:function(){return this.rawToken?this.rawToken.id_token:void 0}},{key:"tokenType",get:function(){return this.rawToken?this.rawToken.token_type:void 0}},{key:"refreshToken",get:function(){return this.rawToken?this.rawToken.refresh_token:void 0}},{key:"hasExpired",value:function(){var t=new Date().getTime();return this.rawToken&&this.expiresAt?t>=this.expiresAt:!0}},{key:"isTokenExpiring",value:function(){var t,n=new Date().getTime(),o=(t=this.eagerRefreshThresholdMillis)!==null&&t!==void 0?t:0;return this.rawToken&&this.expiresAt?this.expiresAt<=n+o:!0}},{key:"getToken",value:function(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(Cr(t)==="object"&&(n=t,t=void 0),n=Object.assign({forceRefresh:!1},n),t){var o=t;Ht(Qt,this,hm).call(this,n).then(function(a){return o(null,a)},t);return}return Ht(Qt,this,hm).call(this,n)}},{key:"getCredentials",value:function(){var e=Mn(Ct().m(function n(o){var a,u,l,f,h,d,_;return Ct().w(function(E){for(;;)switch(E.n){case 0:a=Xb.extname(o),_=a,E.n=_===".json"?1:_===".der"||_===".crt"||_===".pem"?4:_===".p12"||_===".pfx"?6:7;break;case 1:return E.n=2,fm(o,"utf8");case 2:if(u=E.v,l=JSON.parse(u),f=l.private_key,h=l.client_email,!(!f||!h)){E.n=3;break}throw new Fs("private_key and client_email are required.","MISSING_CREDENTIALS");case 3:return E.a(2,{privateKey:f,clientEmail:h});case 4:return E.n=5,fm(o,"utf8");case 5:return d=E.v,E.a(2,{privateKey:d});case 6:throw new Fs("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.","UNKNOWN_CERTIFICATE_TYPE");case 7:throw new Fs("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE");case 8:return E.a(2)}},n)}));function t(n){return e.apply(this,arguments)}return t}()},{key:"revokeToken",value:function(t){if(t){Ht(Qt,this,pm).call(this).then(function(){return t()},t);return}return Ht(Qt,this,pm).call(this)}}])}();function hm(r){return fc.apply(this,arguments)}function fc(){return fc=Mn(Ct().m(function r(e){return Ct().w(function(t){for(;;)switch(t.n){case 0:if(!(um(ks,this)&&!e.forceRefresh)){t.n=1;break}return t.a(2,um(ks,this));case 1:return t.p=1,t.n=2,am(ks,this,Ht(Qt,this,cE).call(this,e));case 2:return t.a(2,t.v);case 3:return t.p=3,am(ks,this,void 0),t.f(3);case 4:return t.a(2)}},r,this,[[1,,3,4]])})),fc.apply(this,arguments)}function cE(r){return dc.apply(this,arguments)}function dc(){return dc=Mn(Ct().m(function r(e){var t;return Ct().w(function(n){for(;;)switch(n.n){case 0:if(!(this.isTokenExpiring()===!1&&e.forceRefresh===!1)){n.n=1;break}return n.a(2,Promise.resolve(this.rawToken));case 1:if(!(!this.key&&!this.keyFile)){n.n=2;break}throw new Error("No key or keyFile set.");case 2:if(!(!this.key&&this.keyFile)){n.n=4;break}return n.n=3,this.getCredentials(this.keyFile);case 3:t=n.v,this.key=t.privateKey,this.iss=t.clientEmail||this.iss,t.clientEmail||Ht(Qt,this,lE).call(this);case 4:return n.a(2,Ht(Qt,this,fE).call(this))}},r,this)})),dc.apply(this,arguments)}function lE(){if(!this.iss)throw new Fs("email is required.","MISSING_CREDENTIALS")}function pm(){return hc.apply(this,arguments)}function hc(){return hc=Mn(Ct().m(function r(){var e;return Ct().w(function(t){for(;;)switch(t.n){case 0:if(this.accessToken){t.n=1;break}throw new Error("No token to revoke.");case 1:return e=uE+this.accessToken,t.n=2,this.transporter.request({url:e,retry:!0});case 2:Ht(Qt,this,Cm).call(this,{email:this.iss,sub:this.sub,key:this.key,keyFile:this.keyFile,scope:this.scope,additionalClaims:this.additionalClaims});case 3:return t.a(2)}},r,this)})),hc.apply(this,arguments)}function Cm(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.keyFile=r.keyFile,this.key=r.key,this.rawToken=void 0,this.iss=r.email||r.iss,this.sub=r.sub,this.additionalClaims=r.additionalClaims,Cr(r.scope)==="object"?this.scope=r.scope.join(" "):this.scope=r.scope,this.eagerRefreshThresholdMillis=r.eagerRefreshThresholdMillis,r.transporter&&(this.transporter=r.transporter)}function fE(){return pc.apply(this,arguments)}function pc(){return pc=Mn(Ct().m(function r(){var e,t,n,o,a,u,l,f,h,d;return Ct().w(function(_){for(;;)switch(_.n){case 0:return e=Math.floor(new Date().getTime()/1e3),t=this.additionalClaims||{},n=Object.assign({iss:this.iss,scope:this.scope,aud:dm,exp:e+3600,iat:e,sub:this.sub},t),o=Yb.sign({header:{alg:"RS256"},payload:n,secret:this.key}),_.p=1,_.n=2,this.transporter.request({method:"POST",url:dm,data:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:o}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});case 2:return a=_.v,this.rawToken=a.data,this.expiresAt=a.data.expires_in===null||a.data.expires_in===void 0?void 0:(e+a.data.expires_in)*1e3,_.a(2,this.rawToken);case 3:throw _.p=3,d=_.v,this.rawToken=void 0,this.tokenExpires=void 0,f=d.response&&(u=d.response)!==null&&u!==void 0&&u.data?(l=d.response)===null||l===void 0?void 0:l.data:{},f.error&&(h=f.error_description?": ".concat(f.error_description):"",d.message="".concat(f.error).concat(h)),d;case 4:return _.a(2)}},r,this,[[1,3]])})),pc.apply(this,arguments)}});var yc=z(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.JWTAccess=void 0;var dE=cc(),hE=Ut(),Em={alg:"RS256",typ:"JWT"},gc=class r{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new hE.LRUCache({capacity:500,maxAge:60*60*1e3});constructor(e,t,n,o){this.email=e,this.key=t,this.keyId=n,this.eagerRefreshThresholdMillis=o??5*60*1e3}getCachedKey(e,t){let n=e;if(t&&Array.isArray(t)&&t.length?n=e?`${e}_${t.join("_")}`:`${t.join("_")}`:typeof t=="string"&&(n=e?`${e}_${t}`:t),!n)throw Error("Scopes or url must be provided");return n}getRequestHeaders(e,t,n){let o=this.getCachedKey(e,n),a=this.cache.get(o),u=Date.now();if(a&&a.expiration-u>this.eagerRefreshThresholdMillis)return new Headers(a.headers);let l=Math.floor(Date.now()/1e3),f=r.getExpirationTime(l),h;if(Array.isArray(n)&&(n=n.join(" ")),n?h={iss:this.email,sub:this.email,scope:n,exp:f,iat:l}:h={iss:this.email,sub:this.email,aud:e,exp:f,iat:l},t){for(let v in h)if(t[v])throw new Error(`The '${v}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let d=this.keyId?{...Em,kid:this.keyId}:Em,_=Object.assign(h,t),E=dE.sign({header:d,payload:_,secret:this.key}),P=new Headers({authorization:`Bearer ${E}`});return this.cache.set(o,{expiration:f*1e3,headers:P}),P}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,t){if(t)this.fromStreamAsync(e).then(()=>t(),t);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((t,n)=>{e||n(new Error("Must pass in a stream containing the service account auth settings."));let o="";e.setEncoding("utf8").on("data",a=>o+=a).on("error",n).on("end",()=>{try{let a=JSON.parse(o);this.fromJSON(a),t()}catch(a){n(a)}})})}};bi.JWTAccess=gc});var Cc=z(wi=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});wi.JWT=void 0;var wm=bm(),pE=yc(),mE=on(),Ei=gt(),_c=class r extends mE.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let t=new r(this);return t.scopes=e,t}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let t=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==Ei.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Ei.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Ei.DEFAULT_UNIVERSE}`);if(!this.apiKey&&t)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:n}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${n.id_token}`}))}}else{this.access||(this.access=new pE.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let n;this.hasUserScopes()?n=this.scopes:e||(n=this.defaultScopes);let o=this.useJWTAccessWithScope||this.universeDomain!==Ei.DEFAULT_UNIVERSE,a=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?n:void 0);return{headers:this.addSharedMetadataHeaders(a)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let t=new wm.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await t.getToken({forceRefresh:!0}),!t.idToken)throw new Error("Unknown error: Failed to fetch ID token");return t.idToken}hasUserScopes(){return this.scopes?this.scopes.length>0:!1}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0||this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(e)this.authorizeAsync().then(t=>e(null,t),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw new Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.key,this.email=this.gtoken.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),n={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};return this.emit("tokens",n),{res:null,tokens:n}}createGToken(){return this.gtoken||(this.gtoken=new wm.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,t){if(t)this.fromStreamAsync(e).then(()=>t(),t);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((t,n)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let o="";e.setEncoding("utf8").on("error",n).on("data",a=>o+=a).on("end",()=>{try{let a=JSON.parse(o);this.fromJSON(a),t()}catch(a){n(a)}})})}fromAPIKey(e){if(typeof e!="string")throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let t=await this.createGToken().getCredentials(this.keyFile);return{private_key:t.privateKey,client_email:t.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};wi.JWT=_c});var Ec=z($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.UserRefreshClient=$n.USER_REFRESH_ACCOUNT_TYPE=void 0;var gE=on(),yE=gt();$n.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var bc=class r extends gE.OAuth2Client{_refreshToken;constructor(e,t,n,o,a){let u=e&&typeof e=="object"?e:{clientId:e,clientSecret:t,refreshToken:n,eagerRefreshThresholdMillis:o,forceRefreshOnFailure:a};super(u),this._refreshToken=u.refreshToken,this.credentials.refresh_token=u.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let t={...r.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e})};return yE.AuthClient.setMethodName(t,"fetchIdToken"),(await this.transporter.request(t)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,t){if(t)this.fromStreamAsync(e).then(()=>t(),t);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((t,n)=>{if(!e)return n(new Error("Must pass in a stream containing the user refresh token."));let o="";e.setEncoding("utf8").on("error",n).on("data",a=>o+=a).on("end",()=>{try{let a=JSON.parse(o);return this.fromJSON(a),t()}catch(a){return n(a)}})})}static fromJSON(e){let t=new r;return t.fromJSON(e),t}};$n.UserRefreshClient=bc});var Ac=z(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.Impersonated=Hn.IMPERSONATED_ACCOUNT_TYPE=void 0;var Am=on(),_E=Je(),CE=Ut();Hn.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var wc=class r extends Am.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){if(super(e),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new Am.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,CE.originalOrCamelOptions)(e).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let t=`projects/-/serviceAccounts/${this.targetPrincipal}`,n=`${this.endpoint}/v1/${t}:signBlob`,o={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...r.RETRY_CONFIG,url:n,data:o,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,t=`${this.endpoint}/v1/${e}:generateAccessToken`,n={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},o=await this.sourceClient.request({...r.RETRY_CONFIG,url:t,data:n,method:"POST"}),a=o.data;return this.credentials.access_token=a.accessToken,this.credentials.expiry_date=Date.parse(a.expireTime),{tokens:this.credentials,res:o}}catch(e){if(!(e instanceof Error))throw e;let t=0,n="";throw e instanceof _E.GaxiosError&&(t=e?.response?.data?.error?.status,n=e?.response?.data?.error?.message),t&&n?(e.message=`${t}: unable to impersonate: ${n}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,t){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,o=`${this.endpoint}/v1/${n}:generateIdToken`,a={delegates:this.delegates,audience:e,includeEmail:t?.includeEmail??!0,useEmailAzp:t?.includeEmail??!0};return(await this.sourceClient.request({...r.RETRY_CONFIG,url:o,data:a,method:"POST"})).data.token}};Hn.Impersonated=wc});var Sc=z(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});xs.OAuthClientAuthHandler=void 0;xs.getErrorFromOAuthErrorResponse=wE;var Gn=Je(),bE=As(),EE=["PUT","POST","PATCH"],Dc=class{#e=(0,bE.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new Gn.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new Gn.Gaxios)}applyClientAuthenticationOptions(e,t){e.headers=Gn.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,t),t||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,t){if(t)e.headers=Gn.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${t}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=Gn.Gaxios.mergeHeaders(e.headers);let n=this.#t.clientId,o=this.#t.clientSecret||"",a=this.#e.encodeBase64StringUtf8(`${n}:${o}`);Gn.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${a}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let t=(e.method||"GET").toUpperCase();if(!EE.includes(t))throw new Error(`${t} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let o=new Headers(e.headers).get("content-type");if(o?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let a=new URLSearchParams(e.data??"");a.append("client_id",this.#t.clientId),a.append("client_secret",this.#t.clientSecret||""),e.data=a}else if(o?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw new Error(`${o} content-types are not supported with ${this.#t.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};xs.OAuthClientAuthHandler=Dc;function wE(r,e){let t=r.error,n=r.error_description,o=r.error_uri,a=`Error code ${t}`;typeof n<"u"&&(a+=`: ${n}`),typeof o<"u"&&(a+=` - ${o}`);let u=new Error(a);if(e){let l=Object.keys(e);e.stack&&l.push("stack"),l.forEach(f=>{f!=="message"&&Object.defineProperty(u,f,{value:e[f],writable:!1,enumerable:!0})})}return u}});var Di=z(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});Ai.StsCredentials=void 0;var AE=Je(),DE=gt(),Dm=Sc(),SE=Ut(),vc=class r extends Dm.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},t){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:t}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,t,n){let o={grant_type:e.grantType,resource:e.resource,audience:e.audience,scope:e.scope?.join(" "),requested_token_type:e.requestedTokenType,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,actor_token:e.actingParty?.actorToken,actor_token_type:e.actingParty?.actorTokenType,options:n&&JSON.stringify(n)},a={...r.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:t,data:new URLSearchParams((0,SE.removeUndefinedValuesInObject)(o))};DE.AuthClient.setMethodName(a,"exchangeToken"),this.applyClientAuthenticationOptions(a);try{let u=await this.transporter.request(a),l=u.data;return l.res=u,l}catch(u){throw u instanceof AE.GaxiosError&&u.response?(0,Dm.getErrorFromOAuthErrorResponse)(u.response.data,u):u}}};Ai.StsCredentials=vc});var qr=z(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.BaseExternalAccountClient=Rt.CLOUD_RESOURCE_MANAGER=Rt.EXTERNAL_ACCOUNT_TYPE=Rt.EXPIRATION_TIME_OFFSET=void 0;var vE=Je(),TE=require("stream"),Tc=gt(),RE=Di(),Sm=Ut(),kE=$u(),FE="urn:ietf:params:oauth:grant-type:token-exchange",OE="urn:ietf:params:oauth:token-type:access_token",Rc="https://www.googleapis.com/auth/cloud-platform",PE=3600;Rt.EXPIRATION_TIME_OFFSET=5*60*1e3;Rt.EXTERNAL_ACCOUNT_TYPE="external_account";Rt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var xE="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",BE="https://sts.{universeDomain}/v1/token",kc=class r extends Tc.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let t=(0,Sm.originalOrCamelOptions)(e),n=t.get("type");if(n&&n!==Rt.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Rt.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=t.get("client_id"),a=t.get("client_secret");this.tokenUrl=t.get("token_url")??BE.replace("{universeDomain}",this.universeDomain);let u=t.get("subject_token_type"),l=t.get("workforce_pool_user_project"),f=t.get("service_account_impersonation_url"),h=t.get("service_account_impersonation"),d=(0,Sm.originalOrCamelOptions)(h).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(t.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),o&&(this.clientAuth={confidentialClientType:"basic",clientId:o,clientSecret:a}),this.stsCredential=new RE.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=t.get("scopes")||[Rc],this.cachedAccessToken=null,this.audience=t.get("audience"),this.subjectTokenType=u,this.workforcePoolUserProject=l;let _=new RegExp(xE);if(this.workforcePoolUserProject&&!this.audience.match(_))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=f,this.serviceAccountImpersonationLifetime=d,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=PE),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(t)this.requestAsync(e).then(n=>t(null,n),n=>t(n,n.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let t=await this.getRequestHeaders(),n={...r.RETRY_CONFIG,headers:t,url:`${this.cloudResourceManagerURL.toString()}${e}`};Tc.AuthClient.setMethodName(n,"getProjectId");let o=await this.transporter.request(n);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,t=!1){let n;try{let o=await this.getRequestHeaders();e.headers=vE.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let a=o.response;if(a){let u=a.status,l=a.config.data instanceof TE.Readable;if(!t&&(u===401||u===403)&&!l&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),t={grantType:FE,audience:this.audience,requestedTokenType:OE,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[Rc]:this.getScopesArray()},n=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),a=await this.stsCredential.exchangeToken(t,o,n);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(a.access_token):a.expires_in?this.cachedAccessToken={access_token:a.access_token,expiry_date:new Date().getTime()+a.expires_in*1e3,res:a.res}:this.cachedAccessToken={access_token:a.access_token,res:a.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let t=e.match(/\/projects\/([^/]+)/);return t?t[1]:null}async getImpersonatedAccessToken(e){let t={...r.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"}};Tc.AuthClient.setMethodName(t,"getImpersonatedAccessToken");let n=await this.transporter.request(t),o=n.data;return{access_token:o.accessToken,expiry_date:new Date(o.expireTime).getTime(),res:n}}isExpired(e){let t=new Date().getTime();return e.expiry_date?t>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[Rc]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),t=this.serviceAccountImpersonationUrl!==void 0,n=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${kE.pkg.version} google-byoid-sdk source/${n} sa-impersonation/${t} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Rt.BaseExternalAccountClient=kc});var vm=z(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});Si.FileSubjectTokenSupplier=void 0;var Oc=require("util"),Pc=require("fs"),IE=(0,Oc.promisify)(Pc.readFile??(()=>{})),NE=(0,Oc.promisify)(Pc.realpath??(()=>{})),qE=(0,Oc.promisify)(Pc.lstat??(()=>{})),Fc=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{if(e=await NE(e),!(await qE(e)).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let t,n=await IE(e,{encoding:"utf8"});if(this.formatType==="text"?t=n:this.formatType==="json"&&this.subjectTokenFieldName&&(t=JSON.parse(n)[this.subjectTokenFieldName]),!t)throw new Error("Unable to parse the subject_token from the credential_source file");return t}};Si.FileSubjectTokenSupplier=Fc});var Tm=z(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});vi.UrlSubjectTokenSupplier=void 0;var jE=gt(),xc=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let t={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers};jE.AuthClient.setMethodName(t,"getSubjectToken");let n;if(this.formatType==="text"?n=(await e.transporter.request(t)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(n=(await e.transporter.request(t)).data[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source URL");return n}};vi.UrlSubjectTokenSupplier=xc});var Rm=z(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.CertificateSubjectTokenSupplier=bt.InvalidConfigurationError=bt.CertificateSourceUnavailableError=bt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var Ti=Ut(),Ri=require("fs"),ki=require("crypto"),LE=require("https");bt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var Zt=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};bt.CertificateSourceUnavailableError=Zt;var kt=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};bt.InvalidConfigurationError=kt;var Bc=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new kt("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new kt("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new kt("Cannot create mTLS Agent with missing certificate or key");return new LE.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:t}=await this.#t();return{cert:this.cert,key:this.key}=await this.#r(e,t),await this.#n(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,Ti.isValidFile)(e))return e;throw new Zt(`Provided certificate config path is invalid: ${e}`)}let t=process.env[bt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(t){if(await(0,Ti.isValidFile)(t))return t;throw new Zt(`Path from environment variable "${bt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${t}`)}let n=(0,Ti.getWellKnownCertificateConfigFileLocation)();if(await(0,Ti.isValidFile)(n))return n;throw new Zt(`Could not find certificate configuration file. Searched override path, the "${bt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${n}).`)}async#t(){let e=this.certificateConfigPath,t;try{t=await Ri.promises.readFile(e,"utf8")}catch{throw new Zt(`Failed to read certificate config file at: ${e}`)}try{let n=JSON.parse(t),o=n?.cert_configs?.workload?.cert_path,a=n?.cert_configs?.workload?.key_path;if(!o||!a)throw new kt(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:a}}catch(n){throw n instanceof kt?n:new kt(`Failed to parse certificate config from ${e}: ${n.message}`)}}async#r(e,t){let n,o;try{n=await Ri.promises.readFile(e),new ki.X509Certificate(n)}catch(a){let u=a instanceof Error?a.message:String(a);throw new Zt(`Failed to read certificate file at ${e}: ${u}`)}try{o=await Ri.promises.readFile(t),(0,ki.createPrivateKey)(o)}catch(a){let u=a instanceof Error?a.message:String(a);throw new Zt(`Failed to read private key file at ${t}: ${u}`)}return{cert:n,key:o}}async#n(e){let t=new ki.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([t.raw.toString("base64")]);try{let a=((await Ri.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((f,h)=>{try{return new ki.X509Certificate(f)}catch(d){let _=d instanceof Error?d.message:String(d);throw new kt(`Failed to parse certificate at index ${h} in trust chain file ${this.trustChainPath}: ${_}`)}}),u=a.findIndex(f=>t.raw.equals(f.raw)),l;if(u===-1)l=[t,...a];else if(u===0)l=a;else throw new kt(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${u}).`);return JSON.stringify(l.map(f=>f.raw.toString("base64")))}catch(n){if(n instanceof kt)throw n;let o=n instanceof Error?n.message:String(n);throw new Zt(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};bt.CertificateSubjectTokenSupplier=Bc});var qc=z(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});Fi.IdentityPoolClient=void 0;var UE=qr(),Ic=Ut(),ME=vm(),$E=Tm(),km=Rm(),HE=Di(),Fm=Je(),Nc=class r extends UE.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let t=(0,Ic.originalOrCamelOptions)(e),n=t.get("credential_source"),o=t.get("subject_token_supplier");if(!n&&!o)throw new Error("A credential source or subject token supplier must be specified.");if(n&&o)throw new Error("Only one of credential source or subject token supplier can be specified.");if(o)this.subjectTokenSupplier=o,this.credentialSourceType="programmatic";else{let a=(0,Ic.originalOrCamelOptions)(n),u=(0,Ic.originalOrCamelOptions)(a.get("format")),l=u.get("type")||"text",f=u.get("subject_token_field_name");if(l!=="json"&&l!=="text")throw new Error(`Invalid credential_source format "${l}"`);if(l==="json"&&!f)throw new Error("Missing subject_token_field_name for JSON credential_source format");let h=a.get("file"),d=a.get("url"),_=a.get("certificate"),E=a.get("headers");if(h&&d||d&&_||h&&_)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(h)this.credentialSourceType="file",this.subjectTokenSupplier=new ME.FileSubjectTokenSupplier({filePath:h,formatType:l,subjectTokenFieldName:f});else if(d)this.credentialSourceType="url",this.subjectTokenSupplier=new $E.UrlSubjectTokenSupplier({url:d,formatType:l,subjectTokenFieldName:f,headers:E,additionalGaxiosOptions:r.RETRY_CONFIG});else if(_){this.credentialSourceType="certificate";let P=new km.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:_.use_default_certificate_config,certificateConfigLocation:_.certificate_config_location,trustChainPath:_.trust_chain_path});this.subjectTokenSupplier=P}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof km.CertificateSubjectTokenSupplier){let t=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new HE.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new Fm.Gaxios({agent:t})}),this.transporter=new Fm.Gaxios({...this.transporter.defaults||{},agent:t})}return e}};Fi.IdentityPoolClient=Nc});var Lc=z(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});Pi.AwsRequestSigner=void 0;var Oi=Je(),Pm=As(),Om="AWS4-HMAC-SHA256",GE="aws4_request",jc=class{getCredentials;region;crypto;constructor(e,t){this.getCredentials=e,this.region=t,this.crypto=(0,Pm.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let t=typeof e.data=="object"?JSON.stringify(e.data):e.data,n=e.url,o=e.method||"GET",a=e.body||t,u=e.headers,l=await this.getCredentials(),f=new URL(n);if(typeof a!="string"&&a!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${a}`);let h=await zE({crypto:this.crypto,host:f.host,canonicalUri:f.pathname,canonicalQuerystring:f.search.slice(1),method:o,region:this.region,securityCredentials:l,requestPayload:a,additionalAmzHeaders:u}),d=Oi.Gaxios.mergeHeaders(h.amzDate?{"x-amz-date":h.amzDate}:{},{authorization:h.authorizationHeader,host:f.host},u||{});l.token&&Oi.Gaxios.mergeHeaders(d,{"x-amz-security-token":l.token});let _={url:n,method:o,headers:d};return a!==void 0&&(_.body=a),_}};Pi.AwsRequestSigner=jc;async function Bs(r,e,t){return await r.signWithHmacSha256(e,t)}async function WE(r,e,t,n,o){let a=await Bs(r,`AWS4${e}`,t),u=await Bs(r,a,n),l=await Bs(r,u,o);return await Bs(r,l,"aws4_request")}async function zE(r){let e=Oi.Gaxios.mergeHeaders(r.additionalAmzHeaders),t=r.requestPayload||"",n=r.host.split(".")[0],o=new Date,a=o.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),u=o.toISOString().replace(/[-]/g,"").replace(/T.*/,"");r.securityCredentials.token&&e.set("x-amz-security-token",r.securityCredentials.token);let l=Oi.Gaxios.mergeHeaders({host:r.host},e.has("date")?{}:{"x-amz-date":a},e),f="",h=[...l.keys()].sort();h.forEach(R=>{f+=`${R}:${l.get(R)} +`});let d=h.join(";"),_=await r.crypto.sha256DigestHex(t),E=`${r.method.toUpperCase()} +${r.canonicalUri} +${r.canonicalQuerystring} +${f} +${d} +${_}`,P=`${u}/${r.region}/${n}/${GE}`,v=`${Om} +${a} +${P} +`+await r.crypto.sha256DigestHex(E),w=await WE(r.crypto,r.securityCredentials.secretAccessKey,u,r.region,n),g=await Bs(r.crypto,w,v),C=`${Om} Credential=${r.securityCredentials.accessKeyId}/${P}, SignedHeaders=${d}, Signature=${(0,Pm.fromArrayBufferToHex)(g)}`;return{amzDate:e.has("date")?void 0:a,authorizationHeader:C,canonicalQuerystring:r.canonicalQuerystring}}});var xm=z(Bi=>{"use strict";Object.defineProperty(Bi,"__esModule",{value:!0});Bi.DefaultAwsSecurityCredentialsSupplier=void 0;var xi=gt(),Uc=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#n)return this.#n;let t=new Headers;if(!this.#n&&this.imdsV2SessionTokenUrl&&t.set("x-aws-ec2-metadata-token",await this.#e(e.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let n={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",headers:t};xi.AuthClient.setMethodName(n,"getAwsRegion");let o=await e.transporter.request(n);return o.data.substr(0,o.data.length-1)}async getAwsSecurityCredentials(e){if(this.#s)return this.#s;let t=new Headers;this.imdsV2SessionTokenUrl&&t.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let n=await this.#t(t,e.transporter),o=await this.#r(n,t,e.transporter);return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,token:o.Token}}async#e(e){let t={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return xi.AuthClient.setMethodName(t,"#getImdsV2SessionToken"),(await e.request(t)).data}async#t(e,t){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let n={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",headers:e};return xi.AuthClient.setMethodName(n,"#getAwsRoleName"),(await t.request(n)).data}async#r(e,t,n){let o={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:t};return xi.AuthClient.setMethodName(o,"#retrieveAwsSecurityCredentials"),(await n.request(o)).data}get#n(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#s(){return process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY?{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN}:null}};Bi.DefaultAwsSecurityCredentialsSupplier=Uc});var $c=z(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});Ii.AwsClient=void 0;var JE=Lc(),VE=qr(),KE=xm(),Bm=Ut(),YE=Je(),Mc=class r extends VE.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);let t=(0,Bm.originalOrCamelOptions)(e),n=t.get("credential_source"),o=t.get("aws_security_credentials_supplier");if(!n&&!o)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(n&&o)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(o)this.awsSecurityCredentialsSupplier=o,this.regionalCredVerificationUrl=r.#e,this.credentialSourceType="programmatic";else{let a=(0,Bm.originalOrCamelOptions)(n);this.environmentId=a.get("environment_id");let u=a.get("region_url"),l=a.get("url"),f=a.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new KE.DefaultAwsSecurityCredentialsSupplier({regionUrl:u,securityCredentialsUrl:l,imdsV2SessionTokenUrl:f}),this.regionalCredVerificationUrl=a.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(parseInt(e[2],10)!==1)throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new JE.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let e=await this.awsRequestSigner.getRequestOptions({...r.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),t=[];return YE.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,a)=>t.push({key:a,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:t}))}};Ii.AwsClient=Mc});var Jc=z(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.InvalidSubjectTokenError=Ne.InvalidMessageFieldError=Ne.InvalidCodeFieldError=Ne.InvalidTokenTypeFieldError=Ne.InvalidExpirationTimeFieldError=Ne.InvalidSuccessFieldError=Ne.InvalidVersionFieldError=Ne.ExecutableResponseError=Ne.ExecutableResponse=void 0;var Ni="urn:ietf:params:oauth:token-type:saml2",Hc="urn:ietf:params:oauth:token-type:id_token",Gc="urn:ietf:params:oauth:token-type:jwt",Wc=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new qi("Executable response must contain a 'version' field.");if(e.success===void 0)throw new ji("Executable response must contain a 'success' field.");if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==Ni&&this.tokenType!==Hc&&this.tokenType!==Gc)throw new Li(`Executable response must contain a 'token_type' field when successful and it must be one of ${Hc}, ${Gc}, or ${Ni}.`);if(this.tokenType===Ni){if(!e.saml_response)throw new Is(`Executable response must contain a 'saml_response' field when token_type=${Ni}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Is(`Executable response must contain a 'id_token' field when token_type=${Hc} or ${Gc}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new Ui("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new Mi("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.PluggableAuthHandler=Wn.ExecutableError=void 0;var an=Jc(),XE=require("child_process"),Vc=require("fs"),$i=class extends Error{code;constructor(e,t){super(`The executable failed with exit code: ${t} and error message: ${e}.`),this.code=t,Object.setPrototypeOf(this,new.target.prototype)}};Wn.ExecutableError=$i;var Kc=class r{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw new Error("No command provided.");if(this.commandComponents=r.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((t,n)=>{let o=XE.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),a="";o.stdout.on("data",l=>{a+=l}),o.stderr.on("data",l=>{a+=l});let u=setTimeout(()=>(o.removeAllListeners(),o.kill(),n(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);o.on("close",l=>{if(clearTimeout(u),l===0)try{let f=JSON.parse(a),h=new an.ExecutableResponse(f);return t(h)}catch(f){return f instanceof an.ExecutableResponseError?n(f):n(new an.ExecutableResponseError(`The executable returned an invalid response: ${a}`))}else return n(new $i(a,l.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Vc.promises.realpath(this.outputFile)}catch{return}if(!(await Vc.promises.lstat(e)).isFile())return;let t=await Vc.promises.readFile(e,{encoding:"utf8"});if(t!=="")try{let n=JSON.parse(t);return new an.ExecutableResponse(n).isValid()?new an.ExecutableResponse(n):void 0}catch(n){throw n instanceof an.ExecutableResponseError?n:new an.ExecutableResponseError(`The output file contained an invalid response: ${t}`)}}static parseCommand(e){let t=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!t)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let n=0;n{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.PluggableAuthClient=zn.ExecutableError=void 0;var QE=qr(),ZE=Jc(),Im=Yc(),ew=Yc();Object.defineProperty(zn,"ExecutableError",{enumerable:!0,get:function(){return ew.ExecutableError}});var tw=30*1e3,Nm=5*1e3,qm=120*1e3,rw="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",jm=1,Xc=class extends QE.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=tw;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillisqm)throw new Error(`Timeout must be between ${Nm} and ${qm} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new Im.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[rw]!=="1")throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let t=new Map;t.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),t.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),t.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&t.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let n=this.getServiceAccountEmail();n&&t.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",n),e=await this.handler.retrieveResponseFromExecutable(t)}if(e.version>jm)throw new Error(`Version of executable is not currently supported, maximum supported version is ${jm}.`);if(!e.success)throw new Im.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new ZE.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw new Error("Executable response is expired.");return e.subjectToken}};zn.PluggableAuthClient=Xc});var el=z(Hi=>{"use strict";Object.defineProperty(Hi,"__esModule",{value:!0});Hi.ExternalAccountClient=void 0;var nw=qr(),sw=qc(),ow=$c(),iw=Qc(),Zc=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return e&&e.type===nw.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new ow.AwsClient(e):e.credential_source?.executable?new iw.PluggableAuthClient(e):new sw.IdentityPoolClient(e):null}};Hi.ExternalAccountClient=Zc});var $m=z(Jn=>{"use strict";Object.defineProperty(Jn,"__esModule",{value:!0});Jn.ExternalAccountAuthorizedUserClient=Jn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var Um=gt(),Lm=Sc(),Mm=Je(),aw=require("stream"),uw=qr();Jn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var cw="https://sts.{universeDomain}/v1/oauthtoken",tl=class r extends Lm.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,t){let n={...r.RETRY_CONFIG,url:this.#e,method:"POST",headers:t,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e})};Um.AuthClient.setMethodName(n,"refreshToken"),this.applyClientAuthenticationOptions(n);try{let o=await this.transporter.request(n),a=o.data;return a.res=o,a}catch(o){throw o instanceof Mm.GaxiosError&&o.response?(0,Lm.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},rl=class extends Um.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let t={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new tl({tokenRefreshEndpoint:e.token_url??cw.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:t}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=uw.EXPIRATION_TIME_OFFSET:this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(t)this.requestAsync(e).then(n=>t(null,n),n=>t(n,n.response));else return this.requestAsync(e)}async requestAsync(e,t=!1){let n;try{let o=await this.getRequestHeaders();e.headers=Mm.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let a=o.response;if(a){let u=a.status,l=a.config.data instanceof aw.Readable;if(!t&&(u===401||u===403)&&!l&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1e3,res:e.res},e.refresh_token!==void 0&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let t=new Date().getTime();return e.expiry_date?t>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};Jn.ExternalAccountAuthorizedUserClient=rl});var zm=z(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.GoogleAuth=Gt.GoogleAuthExceptionMessages=void 0;var lw=require("child_process"),Ns=require("fs"),fw=Je(),qs=ws(),dw=require("os"),nl=require("path"),hw=As(),pw=Xu(),mw=Zu(),gw=ec(),Vn=Cc(),Hm=Ec(),Kn=Ac(),yw=el(),js=qr(),sl=gt(),Gm=$m(),Wm=Ut();Gt.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment. +To learn more about authentication and Google APIs, visit: +https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment. +To learn more about authentication and Google APIs, visit: +https://cloud.google.com/docs/authentication/getting-started`,NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:`Unable to detect a Universe Domain in the current environment. +To learn more about Universe Domain retrieval, visit: +https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var ol=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(Gt.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);e.universeDomain&&(this.clientOptions.universeDomain=e.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then(t=>e(null,t),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===Gt.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId(),e)return this._cachedProjectId=e,e;throw new Error(Gt.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await qs.universe("universe-domain"),e||=sl.DEFAULT_UNIVERSE}catch(t){if(t&&t?.response?.status===404)e=sl.DEFAULT_UNIVERSE;else throw t}return e}async getUniverseDomain(){let e=(0,Wm.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=sl.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},t){let n;if(typeof e=="function"?t=e:n=e,t)this.getApplicationDefaultAsync(n).then(o=>t(null,o.credential,o.projectId),t);else return this.getApplicationDefaultAsync(n)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let t;if(t=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),t)return t instanceof Vn.JWT?t.scopes=this.scopes:t instanceof js.BaseExternalAccountClient&&(t.scopes=this.getAnyScopes()),await this.#t(t);if(t=await this._tryGetApplicationCredentialsFromWellKnownFile(e),t)return t instanceof Vn.JWT?t.scopes=this.scopes:t instanceof js.BaseExternalAccountClient&&(t.scopes=this.getAnyScopes()),await this.#t(t);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new pw.Compute(e));throw new Error(Gt.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,t=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let n=await this.getProjectIdOptional();return t&&(e.quotaProjectId=t),this.cachedCredential=e,{credential:e,projectId:n}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=qs.getGCPResidency()||await qs.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let t=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!t||t.length===0)return null;try{return this._getApplicationCredentialsFromFilePath(t,e)}catch(n){throw n instanceof Error&&(n.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${n.message}`),n}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let t=null;if(this._isWindows())t=process.env.APPDATA;else{let o=process.env.HOME;o&&(t=nl.join(o,".config"))}return t&&(t=nl.join(t,"gcloud","application_default_credentials.json"),Ns.existsSync(t)||(t=null)),t?await this._getApplicationCredentialsFromFilePath(t,e):null}async _getApplicationCredentialsFromFilePath(e,t={}){if(!e||e.length===0)throw new Error("The file path is invalid.");try{if(e=Ns.realpathSync(e),!Ns.lstatSync(e).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let n=Ns.createReadStream(e);return this.fromStream(n,t)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==Kn.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Kn.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");let t=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let n=/(?[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!n)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let o=this.getAnyScopes()??[];return new Kn.Impersonated({...e,sourceClient:t,targetPrincipal:n,targetScopes:Array.isArray(o)?o:[o]})}fromJSON(e,t={}){let n,o=(0,Wm.originalOrCamelOptions)(t).get("universe_domain");return e.type===Hm.USER_REFRESH_ACCOUNT_TYPE?(n=new Hm.UserRefreshClient(t),n.fromJSON(e)):e.type===Kn.IMPERSONATED_ACCOUNT_TYPE?n=this.fromImpersonatedJSON(e):e.type===js.EXTERNAL_ACCOUNT_TYPE?(n=yw.ExternalAccountClient.fromJSON({...e,...t}),n.scopes=this.getAnyScopes()):e.type===Gm.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?n=new Gm.ExternalAccountAuthorizedUserClient({...e,...t}):(t.scopes=this.scopes,n=new Vn.JWT(t),this.setGapicJWTValues(n),n.fromJSON(e)),o&&(n.universeDomain=o),n}_cacheClientFromJSON(e,t){let n=this.fromJSON(e,t);return this.jsonContent=e,this.cachedCredential=n,n}fromStream(e,t={},n){let o={};if(typeof t=="function"?n=t:o=t,n)this.fromStreamAsync(e,o).then(a=>n(null,a),n);else return this.fromStreamAsync(e,o)}fromStreamAsync(e,t){return new Promise((n,o)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");let a=[];e.setEncoding("utf8").on("error",o).on("data",u=>a.push(u)).on("end",()=>{try{try{let u=JSON.parse(a.join("")),l=this._cacheClientFromJSON(u,t);return n(l)}catch(u){if(!this.keyFilename)throw u;let l=new Vn.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=l,this.setGapicJWTValues(l),n(l)}}catch(u){return o(u)}})})}fromAPIKey(e,t={}){return new Vn.JWT({...t,apiKey:e})}_isWindows(){let e=dw.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,lw.exec)("gcloud config config-helper --format json",(t,n)=>{if(!t&&n)try{let o=JSON.parse(n).configuration.properties.core.project;e(o);return}catch{}e(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let t=await this.getClient();if(t&&t.projectId)return t.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==js.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await qs.project("project-id")}catch{return null}}getCredentials(e){if(e)this.getCredentialsAsync().then(t=>e(null,t),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof Kn.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof js.BaseExternalAccountClient){let t=e.getServiceAccountEmail();if(t)return{client_email:t,universe_domain:e.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[t,n]=await Promise.all([qs.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:t,universe_domain:n}}throw new Error(Gt.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#r();try{return await this.#e}finally{this.#e=null}}async#r(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=nl.resolve(this.keyFilename),t=Ns.createReadStream(e);return await this.fromStreamAsync(t,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:t}=await this.#t(e);return t}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let t=await this.getClient();if(!("fetchIdToken"in t))throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new mw.IdTokenClient({targetAudience:e,idTokenProvider:t})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let t=e.url,o=await(await this.getClient()).getRequestHeaders(t);return e.headers=fw.Gaxios.mergeHeaders(e.headers,o),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,gw.getEnv)()}async sign(e,t){let n=await this.getClient(),o=await this.getUniverseDomain();if(t=t||`https://iamcredentials.${o}/v1/projects/-/serviceAccounts/`,n instanceof Kn.Impersonated)return(await n.sign(e)).signedBlob;let a=(0,hw.createCrypto)();if(n instanceof Vn.JWT&&n.key)return await a.sign(n.key,e);let u=await this.getCredentials();if(!u.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(a,u.client_email,e,t)}async signBlob(e,t,n,o){let a=new URL(o+`${t}:signBlob`);return(await this.request({method:"POST",url:a.href,data:{payload:e.encodeBase64StringUtf8(n)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};Gt.GoogleAuth=ol});var Jm=z(Gi=>{"use strict";Object.defineProperty(Gi,"__esModule",{value:!0});Gi.IAMAuth=void 0;var il=class{selector;token;constructor(e,t){this.selector=e,this.token=t,this.selector=e,this.token=t}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};Gi.IAMAuth=il});var Vm=z(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.DownscopedClient=tr.EXPIRATION_TIME_OFFSET=tr.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var _w=Je(),Cw=require("stream"),al=gt(),bw=Di(),Ew="urn:ietf:params:oauth:grant-type:token-exchange",ww="urn:ietf:params:oauth:token-type:access_token",Aw="urn:ietf:params:oauth:token-type:access_token";tr.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;tr.EXPIRATION_TIME_OFFSET=5*60*1e3;var ul=class extends al.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,t={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof al.AuthClient?{}:e),e instanceof al.AuthClient?(this.authClient=e,this.credentialAccessBoundary=t):(this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>tr.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${tr.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let n of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(n.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new bw.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(t)this.requestAsync(e).then(n=>t(null,n),n=>t(n,n.response));else return this.requestAsync(e)}async requestAsync(e,t=!1){let n;try{let o=await this.getRequestHeaders();e.headers=_w.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let a=o.response;if(a){let u=a.status,l=a.config.data instanceof Cw.Readable;if(!t&&(u===401||u===403)&&!l&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,t={grantType:Ew,requestedTokenType:ww,subjectToken:e,subjectTokenType:Aw},n=await this.stsCredential.exchangeToken(t,void 0,this.credentialAccessBoundary),o=this.authClient.credentials?.expiry_date||null,a=n.expires_in?new Date().getTime()+n.expires_in*1e3:o;return this.cachedDownscopedAccessToken={access_token:n.access_token,expiry_date:a,res:n.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){let t=new Date().getTime();return e.expiry_date?t>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};tr.DownscopedClient=ul});var Km=z(Wi=>{"use strict";Object.defineProperty(Wi,"__esModule",{value:!0});Wi.PassThroughClient=void 0;var Dw=gt(),cl=class extends Dw.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};Wi.PassThroughClient=cl});var fl=z(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.GoogleAuth=Z.auth=Z.PassThroughClient=Z.ExecutableError=Z.PluggableAuthClient=Z.DownscopedClient=Z.BaseExternalAccountClient=Z.ExternalAccountClient=Z.IdentityPoolClient=Z.AwsRequestSigner=Z.AwsClient=Z.UserRefreshClient=Z.LoginTicket=Z.ClientAuthentication=Z.OAuth2Client=Z.CodeChallengeMethod=Z.Impersonated=Z.JWT=Z.JWTAccess=Z.IdTokenClient=Z.IAMAuth=Z.GCPEnv=Z.Compute=Z.DEFAULT_UNIVERSE=Z.AuthClient=Z.gaxios=Z.gcpMetadata=void 0;var Ym=zm();Object.defineProperty(Z,"GoogleAuth",{enumerable:!0,get:function(){return Ym.GoogleAuth}});Z.gcpMetadata=ws();Z.gaxios=Je();var Xm=gt();Object.defineProperty(Z,"AuthClient",{enumerable:!0,get:function(){return Xm.AuthClient}});Object.defineProperty(Z,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return Xm.DEFAULT_UNIVERSE}});var Sw=Xu();Object.defineProperty(Z,"Compute",{enumerable:!0,get:function(){return Sw.Compute}});var vw=ec();Object.defineProperty(Z,"GCPEnv",{enumerable:!0,get:function(){return vw.GCPEnv}});var Tw=Jm();Object.defineProperty(Z,"IAMAuth",{enumerable:!0,get:function(){return Tw.IAMAuth}});var Rw=Zu();Object.defineProperty(Z,"IdTokenClient",{enumerable:!0,get:function(){return Rw.IdTokenClient}});var kw=yc();Object.defineProperty(Z,"JWTAccess",{enumerable:!0,get:function(){return kw.JWTAccess}});var Fw=Cc();Object.defineProperty(Z,"JWT",{enumerable:!0,get:function(){return Fw.JWT}});var Ow=Ac();Object.defineProperty(Z,"Impersonated",{enumerable:!0,get:function(){return Ow.Impersonated}});var ll=on();Object.defineProperty(Z,"CodeChallengeMethod",{enumerable:!0,get:function(){return ll.CodeChallengeMethod}});Object.defineProperty(Z,"OAuth2Client",{enumerable:!0,get:function(){return ll.OAuth2Client}});Object.defineProperty(Z,"ClientAuthentication",{enumerable:!0,get:function(){return ll.ClientAuthentication}});var Pw=Ju();Object.defineProperty(Z,"LoginTicket",{enumerable:!0,get:function(){return Pw.LoginTicket}});var xw=Ec();Object.defineProperty(Z,"UserRefreshClient",{enumerable:!0,get:function(){return xw.UserRefreshClient}});var Bw=$c();Object.defineProperty(Z,"AwsClient",{enumerable:!0,get:function(){return Bw.AwsClient}});var Iw=Lc();Object.defineProperty(Z,"AwsRequestSigner",{enumerable:!0,get:function(){return Iw.AwsRequestSigner}});var Nw=qc();Object.defineProperty(Z,"IdentityPoolClient",{enumerable:!0,get:function(){return Nw.IdentityPoolClient}});var qw=el();Object.defineProperty(Z,"ExternalAccountClient",{enumerable:!0,get:function(){return qw.ExternalAccountClient}});var jw=qr();Object.defineProperty(Z,"BaseExternalAccountClient",{enumerable:!0,get:function(){return jw.BaseExternalAccountClient}});var Lw=Vm();Object.defineProperty(Z,"DownscopedClient",{enumerable:!0,get:function(){return Lw.DownscopedClient}});var Qm=Qc();Object.defineProperty(Z,"PluggableAuthClient",{enumerable:!0,get:function(){return Qm.PluggableAuthClient}});Object.defineProperty(Z,"ExecutableError",{enumerable:!0,get:function(){return Qm.ExecutableError}});var Uw=Km();Object.defineProperty(Z,"PassThroughClient",{enumerable:!0,get:function(){return Uw.PassThroughClient}});var Mw=new Ym.GoogleAuth;Z.auth=Mw});var Yw={};Ia(Yw,{default:()=>Kw});module.exports=e0(Yw);var dg=Me(require("fastify"),1),hg=Me(require("@fastify/cors"),1);var as=require("fs"),Wa=require("path"),jf=require("dotenv"),Lf=Me(Ga(),1),bo=class{config={};options;constructor(e={jsonPath:"./config.json"}){this.options={envPath:e.envPath||".env",jsonPath:e.jsonPath,useEnvFile:!1,useJsonFile:e.useJsonFile!==!1,useEnvironmentVariables:e.useEnvironmentVariables!==!1,...e},this.loadConfig()}loadConfig(){this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),this.options.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useEnvFile&&this.loadEnvConfig(),this.config.LOG_FILE&&(process.env.LOG_FILE=this.config.LOG_FILE),this.config.LOG&&(process.env.LOG=this.config.LOG)}loadJsonConfig(){if(!this.options.jsonPath)return;let e=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:(0,Wa.join)(process.cwd(),this.options.jsonPath);if((0,as.existsSync)(e))try{let t=(0,as.readFileSync)(e,"utf-8"),n=Lf.default.parse(t);this.config={...this.config,...n},console.log(`Loaded JSON config from: ${e}`)}catch(t){console.warn(`Failed to load JSON config from ${e}:`,t)}else console.warn(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:(0,Wa.join)(process.cwd(),this.options.envPath);if((0,as.existsSync)(e))try{let t=(0,jf.config)({path:e});t.parsed&&(this.config={...this.config,...this.parseEnvConfig(t.parsed)})}catch(t){console.warn(`Failed to load .env config from ${e}:`,t)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let t={};return Object.assign(t,e),t}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,t){let n=this.config[e];return n!==void 0?n:t}getAll(){return{...this.config}}getHttpsProxy(){return this.get("HTTPS_PROXY")||this.get("https_proxy")||this.get("httpsProxy")||this.get("PROXY_URL")}has(e){return this.config[e]!==void 0}set(e,t){this.config[e]=t}reload(){this.config={},this.loadConfig()}getConfigSummary(){let e=[];return this.options.initialConfig&&e.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&e.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&e.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&e.push("Environment Variables"),`Config sources: ${e.join(", ")}`}};function nt(r,e=500,t="internal_error",n="api_error"){let o=new Error(r);return o.statusCode=e,o.code=t,o.type=n,o}async function Uf(r,e,t){e.log.error(r);let n=r.statusCode||500,o={error:{message:r.message+r.stack||"Internal Server Error",type:r.type||"api_error",code:r.code||"internal_error"}};return t.code(n).send(o)}var Mf=require("undici");function $f(r,e,t,n){let o=new Headers({"Content-Type":"application/json"});t.headers&&Object.entries(t.headers).forEach(([f,h])=>{h&&o.set(f,h)});let a,u=AbortSignal.timeout(t.TIMEOUT??60*1e3*60);if(t.signal){let f=new AbortController,h=()=>f.abort();t.signal.addEventListener("abort",h),u.addEventListener("abort",h),a=f.signal}else a=u;let l={method:"POST",headers:o,body:JSON.stringify(e),signal:a};return t.httpsProxy&&(l.dispatcher=new Mf.ProxyAgent(new URL(t.httpsProxy).toString())),n?.debug({request:l,headers:Object.fromEntries(o.entries()),requestUrl:typeof r=="string"?r:r.toString(),useProxy:t.httpsProxy},"final request"),fetch(typeof r=="string"?r:r.toString(),l)}var Hf="1.0.28";async function l0(r,e,t,n){let o=r.body,a=r.provider,u=t._server.providerService.getProvider(a);if(!u)throw nt(`Provider '${a}' not found`,404,"provider_not_found");let{requestBody:l,config:f,bypass:h}=await f0(o,u,n,r.headers),d=await h0(l,f,u,t,h,n),_=await p0(l,d,u,n,h);return m0(_,e,o)}async function f0(r,e,t,n){let o=r,a={},u=!1;if(u=d0(e,t,r),u&&(n instanceof Headers?n.delete("content-length"):delete n["content-length"],a.headers=n),!u&&typeof t.transformRequestOut=="function"){let l=await t.transformRequestOut(o);l.body?(o=l.body,a=l.config||{}):o=l}if(!u&&e.transformer?.use?.length)for(let l of e.transformer.use){if(!l||typeof l.transformRequestIn!="function")continue;let f=await l.transformRequestIn(o,e);f.body?(o=f.body,a={...a,...f.config}):o=f}if(!u&&e.transformer?.[r.model]?.use?.length)for(let l of e.transformer[r.model].use)!l||typeof l.transformRequestIn!="function"||(o=await l.transformRequestIn(o,e));return{requestBody:o,config:a,bypass:u}}function d0(r,e,t){return r.transformer?.use?.length===1&&r.transformer.use[0].name===e.name&&(!r.transformer?.[t.model]?.use.length||r.transformer?.[t.model]?.use.length===1&&r.transformer?.[t.model]?.use[0].name===e.name)}async function h0(r,e,t,n,o,a){let u=e.url||new URL(t.baseUrl);if(o&&typeof a.auth=="function"){let f=await a.auth(r,t);if(f.body){r=f.body;let h=e.headers||{};f.config?.headers&&(h={...h,...f.config.headers},delete h.host,delete f.config.headers),e={...e,...f.config,headers:h}}else r=f}let l=await $f(u,r,{httpsProxy:n._server.configService.getHttpsProxy(),...e,headers:{Authorization:`Bearer ${t.apiKey}`,...e?.headers||{}}},n.log);if(!l.ok){let f=await l.text();throw nt(`Error from provider(${t.name},${r.model}: ${l.status}): ${f}`,l.status,"provider_response_error")}return l}async function p0(r,e,t,n,o){let a=e;if(!o&&t.transformer?.use?.length)for(let u of Array.from(t.transformer.use).reverse())!u||typeof u.transformResponseOut!="function"||(a=await u.transformResponseOut(a));if(!o&&t.transformer?.[r.model]?.use?.length)for(let u of Array.from(t.transformer[r.model].use).reverse())!u||typeof u.transformResponseOut!="function"||(a=await u.transformResponseOut(a));return!o&&n.transformResponseIn&&(a=await n.transformResponseIn(a)),a}function m0(r,e,t){return r.ok||e.code(r.status),t.stream===!0?(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),e.send(r.body)):r.json()}var Gf=async r=>{r.get("/",async()=>({message:"LLMs API",version:Hf})),r.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()}));let e=r._server.transformerService.getTransformersWithEndpoint();for(let{transformer:t}of e)t.endPoint&&r.post(t.endPoint,async(n,o)=>l0(n,o,r,t));r.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(t,n)=>{let{name:o,baseUrl:a,apiKey:u,models:l}=t.body;if(!o?.trim())throw nt("Provider name is required",400,"invalid_request");if(!a||!g0(a))throw nt("Valid base URL is required",400,"invalid_request");if(!u?.trim())throw nt("API key is required",400,"invalid_request");if(!l||!Array.isArray(l)||l.length===0)throw nt("At least one model is required",400,"invalid_request");if(r._server.providerService.getProvider(t.body.name))throw nt(`Provider with name '${t.body.name}' already exists`,400,"provider_exists");return r._server.providerService.registerProvider(t.body)}),r.get("/providers",async()=>r._server.providerService.getProviders()),r.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{let n=r._server.providerService.getProvider(t.params.id);if(!n)throw nt("Provider not found",404,"provider_not_found");return n}),r.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},enabled:{type:"boolean"}}}}},async(t,n)=>{let o=r._server.providerService.updateProvider(t.params.id,t.body);if(!o)throw nt("Provider not found",404,"provider_not_found");return o}),r.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{if(!r._server.providerService.deleteProvider(t.params.id))throw nt("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),r.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(t,n)=>{if(!r._server.providerService.toggleProvider(t.params.id,t.body.enabled))throw nt("Provider not found",404,"provider_not_found");return{message:`Provider ${t.body.enabled?"enabled":"disabled"} successfully`}})};function g0(r){try{return new URL(r),!0}catch{return!1}}var Eo=class{constructor(e){this.providerService=e}registerProvider(e){return this.providerService.registerProvider(e)}getProviders(){return this.providerService.getProviders()}getProvider(e){return this.providerService.getProvider(e)}updateProvider(e,t){return this.providerService.updateProvider(e,t)}deleteProvider(e){return this.providerService.deleteProvider(e)}toggleProvider(e,t){return this.providerService.toggleProvider(e,t)}resolveRoute(e){let t=this.providerService.resolveModelRoute(e);if(!t)throw new Error(`Model ${e} not found. Available models: ${this.getAvailableModelNames().join(", ")}`);return t}async getAvailableModels(){return{object:"list",data:this.providerService.getAvailableModels().flatMap(t=>t.models.map(n=>({id:n,object:"model",provider:t.provider,created:Math.floor(Date.now()/1e3),owned_by:t.provider})))}}getAvailableModelNames(){return this.providerService.getModelRoutes().map(e=>e.fullModel)}getModelRoutes(){return this.providerService.getModelRoutes()}};var wo=class{constructor(e,t,n){this.configService=e;this.transformerService=t;this.logger=n;this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(t=>{try{if(!t.name||!t.api_base_url||!t.api_key)return;let n={};t.transformer&&Object.keys(t.transformer).forEach(o=>{o==="use"?Array.isArray(t.transformer.use)&&(n.use=t.transformer.use.map(a=>{if(Array.isArray(a)&&typeof a[0]=="string"){let u=this.transformerService.getTransformer(a[0]);if(u)return new u(a[1])}if(typeof a=="string"){let u=this.transformerService.getTransformer(a);return typeof u=="function"?new u:u}}).filter(a=>typeof a<"u")):Array.isArray(t.transformer[o]?.use)&&(n[o]={use:t.transformer[o].use.map(a=>{if(Array.isArray(a)&&typeof a[0]=="string"){let u=this.transformerService.getTransformer(a[0]);if(u)return new u(a[1])}if(typeof a=="string"){let u=this.transformerService.getTransformer(a);return typeof u=="function"?new u:u}}).filter(a=>typeof a<"u")})}),this.registerProvider({name:t.name,baseUrl:t.api_base_url,apiKey:t.api_key,models:t.models||[],transformer:t.transformer?n:void 0}),this.logger.info(`${t.name} provider registered`)}catch(n){this.logger.error(`${t.name} provider registered error: ${n}`)}})}registerProvider(e){let t={...e};return this.providers.set(t.name,t),e.models.forEach(n=>{let o=`${t.name},${n}`,a={provider:t.name,model:n,fullModel:o};this.modelRoutes.set(o,a),this.modelRoutes.has(n)||this.modelRoutes.set(n,a)}),t}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,t){let n=this.providers.get(e);if(!n)return null;let o={...n,...t,updatedAt:new Date};return this.providers.set(e,o),t.models&&(n.models.forEach(a=>{let u=`${n.id},${a}`;this.modelRoutes.delete(u),this.modelRoutes.delete(a)}),t.models.forEach(a=>{let u=`${n.name},${a}`,l={provider:n.name,model:a,fullModel:u};this.modelRoutes.set(u,l),this.modelRoutes.has(a)||this.modelRoutes.set(a,l)})),o}deleteProvider(e){let t=this.providers.get(e);return t?(t.models.forEach(n=>{let o=`${t.name},${n}`;this.modelRoutes.delete(o),this.modelRoutes.delete(n)}),this.providers.delete(e),!0):!1}toggleProvider(e,t){return!!this.providers.get(e)}resolveModelRoute(e){let t=this.modelRoutes.get(e);if(!t)return null;let n=this.providers.get(t.provider);return n?{provider:n,originalModel:e,targetModel:t.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(t=>{t.models.forEach(n=>{e.push(n),e.push(`${t.name},${n}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((t,n)=>{if(Array.isArray(n)){let[o,a={}]=n;t[o]=a}else t[n]={};return t},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(t=>{t.models.forEach(n=>{e.push({id:n,object:"model",owned_by:t.name,provider:t.name}),e.push({id:`${t.name},${n}`,object:"model",owned_by:t.name,provider:t.name})})}),{object:"list",data:e}}};var ze=[];for(let r=0;r<256;++r)ze.push((r+256).toString(16).slice(1));function Wf(r,e=0){return(ze[r[e+0]]+ze[r[e+1]]+ze[r[e+2]]+ze[r[e+3]]+"-"+ze[r[e+4]]+ze[r[e+5]]+"-"+ze[r[e+6]]+ze[r[e+7]]+"-"+ze[r[e+8]]+ze[r[e+9]]+"-"+ze[r[e+10]]+ze[r[e+11]]+ze[r[e+12]]+ze[r[e+13]]+ze[r[e+14]]+ze[r[e+15]]).toLowerCase()}var zf=require("crypto"),Do=new Uint8Array(256),Ao=Do.length;function za(){return Ao>Do.length-16&&((0,zf.randomFillSync)(Do),Ao=0),Do.slice(Ao,Ao+=16)}var Jf=require("crypto"),Ja={randomUUID:Jf.randomUUID};function y0(r,e,t){if(Ja.randomUUID&&!e&&!r)return Ja.randomUUID();r=r||{};let n=r.random??r.rng?.()??za();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(t=t||0,t<0||t+16>e.length)throw new RangeError(`UUID byte range ${t}:${t+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[t+o]=n[o];return e}return Wf(n)}var Fr=y0;var Vf=r=>r<=0?"none":r<=1024?"low":r<=8192?"medium":"high";var So=class{name="Anthropic";endPoint="/v1/messages";async auth(e,t){return{body:e,config:{headers:{"x-api-key":t.apiKey,authorization:void 0}}}}async transformRequestOut(e){let t=[];if(e.system){if(typeof e.system=="string")t.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let a=e.system.filter(u=>u.type==="text"&&u.text).map(u=>({type:"text",text:u.text,cache_control:u.cache_control}));t.push({role:"system",content:a})}}JSON.parse(JSON.stringify(e.messages||[]))?.forEach((a,u)=>{if(a.role==="user"||a.role==="assistant"){if(typeof a.content=="string"){t.push({role:a.role,content:a.content});return}if(Array.isArray(a.content)){if(a.role==="user"){let l=a.content.filter(h=>h.type==="tool_result"&&h.tool_use_id);l.length&&l.forEach((h,d)=>{let _={role:"tool",content:typeof h.content=="string"?h.content:JSON.stringify(h.content),tool_call_id:h.tool_use_id,cache_control:h.cache_control};t.push(_)});let f=a.content.filter(h=>h.type==="text"&&h.text||h.type==="image"&&h.source);f.length&&t.push({role:"user",content:f.map(h=>h?.type==="image"?{type:"image_url",image_url:{url:h.source?.type==="base64"?h.source.data:h.source.url},media_type:h.source.media_type}:h)})}else if(a.role==="assistant"){let l={role:"assistant",content:null},f=a.content.filter(d=>d.type==="text"&&d.text);f.length&&(l.content=f.map(d=>d.text).join(` +`));let h=a.content.filter(d=>d.type==="tool_use"&&d.id);h.length&&(l.tool_calls=h.map(d=>({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.input||{})}}))),t.push(l)}return}}});let o={messages:t,model:e.model,max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream,tools:e.tools?.length?this.convertAnthropicToolsToUnified(e.tools):void 0,tool_choice:e.tool_choice};return e.thinking&&(o.reasoning={effort:Vf(e.thinking.budget_tokens),enabled:e.thinking.type==="enabled"}),e.tool_choice&&(e.tool_choice.type==="tool"?o.tool_choice={type:"function",function:{name:e.tool_choice.name}}:o.tool_choice=e.tool_choice.type),o}async transformResponseIn(e,t){if(e.headers.get("Content-Type")?.includes("text/event-stream")){if(!e.body)throw new Error("Stream response body is null");let o=await this.convertOpenAIStreamToAnthropic(e.body);return new Response(o,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let o=await e.json(),a=this.convertOpenAIResponseToAnthropic(o);return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description||"",parameters:t.input_schema}}))}async convertOpenAIStreamToAnthropic(e){return new ReadableStream({start:async n=>{let o=new TextEncoder,a=`msg_${Date.now()}`,u=null,l="unknown",f=!1,h=!1,d=!1,_=new Map,E=new Map,P=0,v=0,w=0,g=!1,C=!1,R=0,S=-1,N=H=>{if(!g)try{n.enqueue(H);let K=new TextDecoder().decode(H);this.logger.debug({dataStr:K},"send data")}catch(K){if(K instanceof TypeError&&K.message.includes("Controller is already closed"))g=!0;else throw this.logger.debug(`send data error: ${K.message}`),K}},j=()=>{if(!g)try{if(S>=0){let K={type:"content_block_stop",index:S};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(K)} + +`)),S=-1}u?(N(o.encode(`event: message_delta +data: ${JSON.stringify(u)} + +`)),u=null):N(o.encode(`event: message_delta +data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:0,output_tokens:0,cache_read_input_tokens:0}})} + +`));let H={type:"message_stop"};N(o.encode(`event: message_stop +data: ${JSON.stringify(H)} + +`)),n.close(),g=!0}catch(H){if(H instanceof TypeError&&H.message.includes("Controller is already closed"))g=!0;else throw H}},L=null;try{L=e.getReader();let H=new TextDecoder,K="";for(;!g;){let{done:W,value:we}=await L.read();if(W)break;K+=H.decode(we,{stream:!0});let de=K.split(` +`);K=de.pop()||"";for(let le of de){if(g||d)break;if(!le.startsWith("data:"))continue;let ge=le.slice(5).trim();if(this.logger.debug(`recieved data: ${ge}`),ge!=="[DONE]")try{let te=JSON.parse(ge);if(P++,this.logger.debug({response:te},"Original Response"),te.error){let Q={type:"error",message:{type:"api_error",message:JSON.stringify(te.error)}};N(o.encode(`event: error +data: ${JSON.stringify(Q)} + +`));continue}if(l=te.model||l,!f&&!g&&!d){f=!0;let Q={type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:l,stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}};N(o.encode(`event: message_start +data: ${JSON.stringify(Q)} + +`))}let fe=te.choices?.[0];if(te.usage&&(u?u.usage={input_tokens:te.usage?.prompt_tokens||0,output_tokens:te.usage?.completion_tokens||0,cache_read_input_tokens:te.usage?.cache_read_input_tokens||0}:u={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:te.usage?.prompt_tokens||0,output_tokens:te.usage?.completion_tokens||0,cache_read_input_tokens:te.usage?.cache_read_input_tokens||0}}),!fe)continue;if(fe?.delta?.thinking&&!g&&!d){if(S>=0){let Q={type:"content_block_stop",index:S};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(Q)} + +`)),S=-1}if(!C){let Q={type:"content_block_start",index:R,content_block:{type:"thinking",thinking:""}};N(o.encode(`event: content_block_start +data: ${JSON.stringify(Q)} + +`)),S=R,C=!0}if(fe.delta.thinking.signature){let Q={type:"content_block_delta",index:R,delta:{type:"signature_delta",signature:fe.delta.thinking.signature}};N(o.encode(`event: content_block_delta +data: ${JSON.stringify(Q)} + +`));let ae={type:"content_block_stop",index:R};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(ae)} + +`)),S=-1,R++}else if(fe.delta.thinking.content){let Q={type:"content_block_delta",index:R,delta:{type:"thinking_delta",thinking:fe.delta.thinking.content||""}};N(o.encode(`event: content_block_delta +data: ${JSON.stringify(Q)} + +`))}}if(fe?.delta?.content&&!g&&!d){if(v++,S>=0&&!h){let ae={type:"content_block_stop",index:S};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(ae)} + +`)),S=-1}if(!h&&!d){h=!0;let Q={type:"content_block_start",index:R,content_block:{type:"text",text:""}};N(o.encode(`event: content_block_start +data: ${JSON.stringify(Q)} + +`)),S=R}if(!g&&!d){let Q={type:"content_block_delta",index:S,delta:{type:"text_delta",text:fe.delta.content}};N(o.encode(`event: content_block_delta +data: ${JSON.stringify(Q)} + +`))}}if(fe?.delta?.annotations?.length&&!g&&!d){if(S>=0&&h){let Q={type:"content_block_stop",index:S};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(Q)} + +`)),S=-1,h=!1}fe?.delta?.annotations.forEach(Q=>{R++;let ae={type:"content_block_start",index:R,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${Fr()}`,content:[{type:"web_search_result",title:Q.url_citation.title,url:Q.url_citation.url}]}};N(o.encode(`event: content_block_start +data: ${JSON.stringify(ae)} + +`));let J={type:"content_block_stop",index:R};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(J)} + +`)),S=-1})}if(fe?.delta?.tool_calls&&!g&&!d){w++;let Q=new Set;for(let ae of fe.delta.tool_calls){if(g)break;let J=ae.index??0;if(Q.has(J))continue;if(Q.add(J),!E.has(J)){if(S>=0){let be={type:"content_block_stop",index:S};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(be)} + +`)),S=-1}let se=R;E.set(J,se),R++;let Be=ae.id||`call_${Date.now()}_${J}`,qe=ae.function?.name||`tool_${J}`,G={type:"content_block_start",index:se,content_block:{type:"tool_use",id:Be,name:qe,input:{}}};N(o.encode(`event: content_block_start +data: ${JSON.stringify(G)} + +`)),S=se;let he={id:Be,name:qe,arguments:"",contentBlockIndex:se};_.set(J,he)}else if(ae.id&&ae.function?.name){let se=_.get(J);se.id.startsWith("call_")&&se.name.startsWith("tool_")&&(se.id=ae.id,se.name=ae.function.name)}if(ae.function?.arguments&&!g&&!d){let se=E.get(J);if(se===void 0)continue;let Be=_.get(J);Be&&(Be.arguments+=ae.function.arguments);try{let qe={type:"content_block_delta",index:se,delta:{type:"input_json_delta",partial_json:ae.function.arguments}};N(o.encode(`event: content_block_delta +data: ${JSON.stringify(qe)} + +`))}catch{try{let G=ae.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),he={type:"content_block_delta",index:se,delta:{type:"input_json_delta",partial_json:G}};N(o.encode(`event: content_block_delta +data: ${JSON.stringify(he)} + +`))}catch(G){console.error(G)}}}}}if(fe?.finish_reason&&!g&&!d){if(v===0&&w===0&&console.error("Warning: No content in the stream response!"),S>=0){let Q={type:"content_block_stop",index:S};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(Q)} + +`)),S=-1}g||(u={type:"message_delta",delta:{stop_reason:{stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[fe.finish_reason]||"end_turn",stop_sequence:null},usage:{input_tokens:te.usage?.prompt_tokens||0,output_tokens:te.usage?.completion_tokens||0,cache_read_input_tokens:te.usage?.cache_read_input_tokens||0}});break}}catch(te){this.logger?.error(`parseError: ${te.name} message: ${te.message} stack: ${te.stack} data: ${ge}`)}}}j()}catch(H){if(!g)try{n.error(H)}catch(K){console.error(K)}}finally{if(L)try{L.releaseLock()}catch(H){console.error(H)}}},cancel:n=>{this.logger.debug(`cancle stream: ${n}`)}})}convertOpenAIResponseToAnthropic(e){this.logger.debug({response:e},"Original OpenAI response");try{let t=e.choices[0];if(!t)throw new Error("No choices found in OpenAI response");let n=[];if(t.message.annotations){let a=`srvtoolu_${Fr()}`;n.push({type:"server_tool_use",id:a,name:"web_search",input:{query:""}}),n.push({type:"web_search_tool_result",tool_use_id:a,content:t.message.annotations.map(u=>({type:"web_search_result",url:u.url_citation.url,title:u.url_citation.title}))})}t.message.content&&n.push({type:"text",text:t.message.content}),t.message.tool_calls&&t.message.tool_calls.length>0&&t.message.tool_calls.forEach((a,u)=>{let l={};try{let f=a.function.arguments||"{}";typeof f=="object"?l=f:typeof f=="string"&&(l=JSON.parse(f))}catch{l={text:a.function.arguments||""}}n.push({type:"tool_use",id:a.id,name:a.function.name,input:l})});let o={id:e.id,type:"message",role:"assistant",model:e.model,content:n,stop_reason:t.finish_reason==="stop"?"end_turn":t.finish_reason==="length"?"max_tokens":t.finish_reason==="tool_calls"?"tool_use":t.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:e.usage?.prompt_tokens||0,output_tokens:e.usage?.completion_tokens||0}};return this.logger.debug({result:o},"Conversion complete, final Anthropic response"),o}catch{throw nt(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}};var wn={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function _0(r,e){r.includes("null")&&(e.nullable=!0);let t=r.filter(n=>n!=="null");if(t.length===1){let n=t[0].toUpperCase();e.type=Object.values(wn).includes(n)?n:wn.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let n of t){let o=n.toUpperCase();e.anyOf.push({type:Object.values(wn).includes(o)?o:wn.TYPE_UNSPECIFIED})}}}function us(r){let e={},t=["items"],n=["anyOf"],o=["properties"];if(r.type&&r.anyOf)throw new Error("type and anyOf cannot be both populated.");let a=r.anyOf;a!=null&&Array.isArray(a)&&a.length==2&&(a[0]&&a[0].type==="null"?(e.nullable=!0,r=a[1]):a[1]&&a[1].type==="null"&&(e.nullable=!0,r=a[0])),r.type&&Array.isArray(r.type)&&_0(r.type,e);for(let[u,l]of Object.entries(r))if(l!=null)if(u=="type"){if(l==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(l))continue;let f=l.toUpperCase();e.type=Object.values(wn).includes(f)?f:wn.TYPE_UNSPECIFIED}else if(t.includes(u))e[u]=us(l);else if(n.includes(u)){let f=[];for(let h of l){if(h.type=="null"){e.nullable=!0;continue}f.push(us(h))}e[u]=f}else if(o.includes(u)){let f={};for(let[h,d]of Object.entries(l))f[h]=us(d);e[u]=f}else{if(u==="additionalProperties")continue;e[u]=l}return e}function C0(r){if(r.functionDeclarations)for(let e of r.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=us(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=us(e.response));return r}function vo(r){let e=[],t=r.tools?.filter(u=>u.function.name!=="web_search")?.map(u=>({name:u.function.name,description:u.function.description,parametersJsonSchema:u.function.parameters}));t?.length&&e.push(C0({functionDeclarations:t})),r.tools?.find(u=>u.function.name==="web_search")&&e.push({googleSearch:{}});let a={contents:r.messages.map(u=>{let l;u.role==="assistant"?l="model":(["user","system","tool"].includes(u.role),l="user");let f=[];return typeof u.content=="string"?f.push({text:u.content}):Array.isArray(u.content)&&f.push(...u.content.map(h=>{if(h.type==="text")return{text:h.text||""};if(h.type==="image_url")return h.image_url.url.startsWith("http")?{file_data:{mime_type:h.media_type,file_uri:h.image_url.url}}:{inlineData:{mime_type:h.media_type,data:h.image_url.url}}})),Array.isArray(u.tool_calls)&&f.push(...u.tool_calls.map(h=>({functionCall:{id:h.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:h.function.name,args:JSON.parse(h.function.arguments||"{}")}}))),{role:l,parts:f}}),tools:e.length?e:void 0};if(r.tool_choice){let u={functionCallingConfig:{}};r.tool_choice==="auto"?u.functionCallingConfig.mode="auto":r.tool_choice==="none"?u.functionCallingConfig.mode="none":r.tool_choice==="required"?u.functionCallingConfig.mode="any":r.tool_choice?.function?.name&&(u.functionCallingConfig.mode="any",u.functionCallingConfig.allowedFunctionNames=[r.tool_choice?.function?.name]),a.toolConfig=u}return a}function To(r){let e=r.contents,t=r.tools,n=r.model,o=r.max_tokens,a=r.temperature,u=r.stream,l=r.tool_choice,f={messages:[],model:n,max_tokens:o,temperature:a,stream:u,tool_choice:l};return Array.isArray(e)&&e.forEach(h=>{typeof h=="string"?f.messages.push({role:"user",content:h}):typeof h.text=="string"?f.messages.push({role:"user",content:h.text||null}):h.role==="user"?f.messages.push({role:"user",content:h?.parts?.map(d=>({type:"text",text:d.text||""}))||[]}):h.role==="model"&&f.messages.push({role:"assistant",content:h?.parts?.map(d=>({type:"text",text:d.text||""}))||[]})}),Array.isArray(t)&&(f.tools=[],t.forEach(h=>{Array.isArray(h.functionDeclarations)&&h.functionDeclarations.forEach(d=>{f.tools.push({type:"function",function:{name:d.name,description:d.description,parameters:d.parameters}})})})),f}async function Ro(r,e,t){if(r.headers.get("Content-Type")?.includes("application/json")){let n=await r.json(),o=n.candidates[0].content?.parts?.filter(u=>u.functionCall)?.map(u=>({id:u.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:u.functionCall?.name,arguments:JSON.stringify(u.functionCall?.args||{})}}))||[],a={id:n.responseId,choices:[{finish_reason:n.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:n.candidates[0].content?.parts?.filter(u=>u.text)?.map(u=>u.text)?.join(` +`)||"",role:"assistant",tool_calls:o.length>0?o:void 0}}],created:parseInt(new Date().getTime()/1e3+"",10),model:n.modelVersion,object:"chat.completion",usage:{completion_tokens:n.usageMetadata.candidatesTokenCount,prompt_tokens:n.usageMetadata.promptTokenCount,cached_content_token_count:n.usageMetadata.cachedContentTokenCount||null,total_tokens:n.usageMetadata.totalTokenCount}};return new Response(JSON.stringify(a),{status:r.status,statusText:r.statusText,headers:r.headers})}else if(r.headers.get("Content-Type")?.includes("stream")){if(!r.body)return r;let n=new TextDecoder,o=new TextEncoder,a=(l,f)=>{if(l.startsWith("data: ")){let h=l.slice(6).trim();if(h){t?.debug({chunkStr:h},`${e} chunk:`);try{let d=JSON.parse(h);if(!d.candidates||!d.candidates[0]){log("Invalid chunk structure:",h);return}let _=d.candidates[0],E=_.content?.parts||[],P=E.filter(g=>g.functionCall).map(g=>({id:g.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:g.functionCall?.name,arguments:JSON.stringify(g.functionCall?.args||{})}})),w={choices:[{delta:{role:"assistant",content:E.filter(g=>g.text).map(g=>g.text).join(` +`)||"",tool_calls:P.length>0?P:void 0},finish_reason:_.finishReason?.toLowerCase()||null,index:_.index||(P.length>0?1:0),logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.responseId||"",model:d.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usageMetadata?.candidatesTokenCount||0,prompt_tokens:d.usageMetadata?.promptTokenCount||0,cached_content_token_count:d.usageMetadata?.cachedContentTokenCount||null,total_tokens:d.usageMetadata?.totalTokenCount||0}};_?.groundingMetadata?.groundingChunks?.length&&(w.choices[0].delta.annotations=_.groundingMetadata.groundingChunks.map((g,C)=>{let R=_?.groundingMetadata?.groundingSupports?.filter(S=>S.groundingChunkIndices?.includes(C));return{type:"url_citation",url_citation:{url:g?.web?.uri||"",title:g?.web?.title||"",content:R?.[0]?.segment?.text||"",start_index:R?.[0]?.segment?.startIndex||0,end_index:R?.[0]?.segment?.endIndex||0}}})),f.enqueue(o.encode(`data: ${JSON.stringify(w)} + +`))}catch(d){t?.error(`Error parsing ${e} stream chunk`,h,d.message)}}}},u=new ReadableStream({async start(l){let f=r.body.getReader(),h="";try{for(;;){let{done:d,value:_}=await f.read();if(d){h&&a(h,l);break}h+=n.decode(_,{stream:!0});let E=h.split(` +`);h=E.pop()||"";for(let P of E)a(P,l)}}catch(d){l.error(d)}finally{l.close()}}});return new Response(u,{status:r.status,statusText:r.statusText,headers:r.headers})}return r}var ko=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,t){return{body:vo(e),config:{url:new URL(`./${e.model}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,t.baseUrl),headers:{"x-goog-api-key":t.apiKey,Authorization:void 0}}}}transformRequestOut=To;async transformResponseOut(e){return Ro(e,this.name,this.logger)}};async function $w(){try{let{GoogleAuth:r}=await Promise.resolve().then(()=>Me(fl(),1));return(await(await new r({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(r){throw console.error("Error getting access token:",r),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods: +1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file +2. Run "gcloud auth application-default login" +3. Use Google Cloud environment with default service account`)}}var zi=class{name="vertex-gemini";async transformRequestIn(e,t){let n=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!n&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let l=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),f=JSON.parse(l);f&&f.project_id&&(n=f.project_id)}catch(u){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",u)}if(!n)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let a=await $w();return{body:vo(e),config:{url:new URL(`./v1beta1/projects/${n}/locations/${o}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,t.baseUrl.endsWith("/")?t.baseUrl:t.baseUrl+"/"||`https://${o}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${a}`,"x-goog-api-key":void 0}}}}transformRequestOut=To;async transformResponseOut(e){return Ro(e,this.name)}};var Ji=class{name="deepseek";async transformRequestIn(e){return e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,n=new TextEncoder,o="",a=!1,u="",l=new ReadableStream({async start(f){let h=e.body.getReader(),d=(E,P,v)=>{let w=E.split(` +`);for(let g of w)g.trim()&&P.enqueue(v.encode(g+` +`))},_=(E,P)=>{let{controller:v,encoder:w}=P;if(E.startsWith("data: ")&&E.trim()!=="data: [DONE]")try{let g=JSON.parse(E.slice(6));if(g.choices?.[0]?.delta?.reasoning_content){P.appendReasoningContent(g.choices[0].delta.reasoning_content);let C={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete C.choices[0].delta.reasoning_content;let R=`data: ${JSON.stringify(C)} + +`;v.enqueue(w.encode(R));return}if(g.choices?.[0]?.delta?.content&&P.reasoningContent()&&!P.isReasoningComplete()){P.setReasoningComplete(!0);let C=Date.now().toString(),R={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:P.reasoningContent(),signature:C}}}]};delete R.choices[0].delta.reasoning_content;let S=`data: ${JSON.stringify(R)} + +`;v.enqueue(w.encode(S))}if(g.choices[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0){P.isReasoningComplete()&&g.choices[0].index++;let C=`data: ${JSON.stringify(g)} + +`;v.enqueue(w.encode(C))}}catch{v.enqueue(w.encode(E+` +`))}else v.enqueue(w.encode(E+` +`))};try{for(;;){let{done:E,value:P}=await h.read();if(E){u.trim()&&d(u,f,n);break}let v=t.decode(P,{stream:!0});u+=v;let w=u.split(` +`);u=w.pop()||"";for(let g of w)if(g.trim())try{_(g,{controller:f,encoder:n,reasoningContent:()=>o,appendReasoningContent:C=>o+=C,isReasoningComplete:()=>a,setReasoningComplete:C=>a=C})}catch(C){console.error("Error processing line:",g,C),f.enqueue(n.encode(g+` +`))}}}catch(E){console.error("Stream error:",E),f.error(E)}finally{try{h.releaseLock()}catch(E){console.error("Error releasing reader lock:",E)}f.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Vi=class{name="tooluse";transformRequestIn(e){return e.messages.push({role:"system",content:"Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate."}),e.tools?.length&&(e.tool_choice="required",e.tools.push({type:"function",function:{name:"ExitTool",description:`Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode. +IMPORTANT: Before using this tool, ensure that none of the available tools are applicable to the current task. You must evaluate all available options \u2014 only if no suitable tool can help you complete the task should you use ExitTool to terminate tool mode. +Examples: +1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available. +2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();if(t?.choices?.[0]?.message.tool_calls?.length&&t?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let n=t?.choices[0]?.message.tool_calls[0],o=JSON.parse(n.function.arguments||"{}");t.choices[0].message.content=o.response||"",delete t.choices[0].message.tool_calls}return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,n=new TextEncoder,o=-1,a="",u="",l=new ReadableStream({async start(f){let h=e.body.getReader(),d=(E,P,v)=>{let w=E.split(` +`);for(let g of w)g.trim()&&P.enqueue(v.encode(g+` +`))},_=(E,P)=>{let{controller:v,encoder:w,exitToolIndex:g,setExitToolIndex:C,appendExitToolResponse:R}=P;if(E.startsWith("data: ")&&E.trim()!=="data: [DONE]")try{let S=JSON.parse(E.slice(6));if(S.choices[0]?.delta?.tool_calls?.length){let N=S.choices[0].delta.tool_calls[0];if(N.function?.name==="ExitTool"){C(N.index);return}else if(g()>-1&&N.index===g()&&N.function.arguments){R(N.function.arguments);try{let j=JSON.parse(P.exitToolResponse());S.choices=[{delta:{role:"assistant",content:j.response||""}}];let L=`data: ${JSON.stringify(S)} + +`;v.enqueue(w.encode(L))}catch{}return}}if(S.choices?.[0]?.delta&&Object.keys(S.choices[0].delta).length>0){let N=`data: ${JSON.stringify(S)} + +`;v.enqueue(w.encode(N))}}catch{v.enqueue(w.encode(E+` +`))}else v.enqueue(w.encode(E+` +`))};try{for(;;){let{done:E,value:P}=await h.read();if(E){u.trim()&&d(u,f,n);break}let v=t.decode(P,{stream:!0});u+=v;let w=u.split(` +`);u=w.pop()||"";for(let g of w)if(g.trim())try{_(g,{controller:f,encoder:n,exitToolIndex:()=>o,setExitToolIndex:C=>o=C,exitToolResponse:()=>a,appendExitToolResponse:C=>a+=C})}catch(C){console.error("Error processing line:",g,C),f.enqueue(n.encode(g+` +`))}}}catch(E){console.error("Stream error:",E),f.error(E)}finally{try{h.releaseLock()}catch(E){console.error("Error releasing reader lock:",E)}f.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Ki=class{constructor(e){this.options=e}static TransformerName="openrouter";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(t=>{Array.isArray(t.content)&&t.content.forEach(n=>{n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`data:${n.media_type};base64,${n.image_url.url}`),delete n.media_type)})}):e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(n=>{n.cache_control&&delete n.cache_control,n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`data:${n.media_type};base64,${n.image_url.url}`),delete n.media_type)}):t.cache_control&&delete t.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,n=new TextEncoder,o=!1,a="",u=!1,l=!1,f="",h=new ReadableStream({async start(d){let _=e.body.getReader(),E=(v,w,g)=>{let C=v.split(` +`);for(let R of C)R.trim()&&w.enqueue(g.encode(R+` +`))},P=(v,w)=>{let{controller:g,encoder:C}=w;if(v.startsWith("data: ")&&v.trim()!=="data: [DONE]"){let R=v.slice(6);try{let S=JSON.parse(R);if(S.usage&&(this.logger?.debug({usage:S.usage,hasToolCall:l},"usage"),S.choices[0].finish_reason=l?"tool_calls":"stop"),S.choices?.[0]?.finish_reason==="error"&&g.enqueue(C.encode(`data: ${JSON.stringify({error:S.choices?.[0].error})} + +`)),S.choices?.[0]?.delta?.content&&!w.hasTextContent()&&w.setHasTextContent(!0),S.choices?.[0]?.delta?.reasoning){w.appendReasoningContent(S.choices[0].delta.reasoning);let j={...S,choices:[{...S.choices?.[0],delta:{...S.choices[0].delta,thinking:{content:S.choices[0].delta.reasoning}}}]};j.choices?.[0]?.delta&&delete j.choices[0].delta.reasoning;let L=`data: ${JSON.stringify(j)} + +`;g.enqueue(C.encode(L));return}if(S.choices?.[0]?.delta?.content&&w.reasoningContent()&&!w.isReasoningComplete()){w.setReasoningComplete(!0);let j=Date.now().toString(),L={...S,choices:[{...S.choices?.[0],delta:{...S.choices[0].delta,content:null,thinking:{content:w.reasoningContent(),signature:j}}}]};L.choices?.[0]?.delta&&delete L.choices[0].delta.reasoning;let H=`data: ${JSON.stringify(L)} + +`;g.enqueue(C.encode(H))}S.choices?.[0]?.delta?.reasoning&&delete S.choices[0].delta.reasoning,S.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(S.choices?.[0]?.delta?.tool_calls[0].id,10))&&S.choices?.[0]?.delta?.tool_calls.forEach(j=>{j.id=`call_${Fr()}`}),S.choices?.[0]?.delta?.tool_calls?.length&&!l&&(l=!0),S.choices?.[0]?.delta?.tool_calls?.length&&w.hasTextContent()&&(typeof S.choices[0].index=="number"?S.choices[0].index+=1:S.choices[0].index=1);let N=`data: ${JSON.stringify(S)} + +`;g.enqueue(C.encode(N))}catch{g.enqueue(C.encode(v+` +`))}}else g.enqueue(C.encode(v+` +`))};try{for(;;){let{done:v,value:w}=await _.read();if(v){f.trim()&&E(f,d,n);break}if(!w||w.length===0)continue;let g;try{g=t.decode(w,{stream:!0})}catch(R){console.warn("Failed to decode chunk",R);continue}if(g.length===0)continue;if(f+=g,f.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let R=f.split(` +`);f=R.pop()||"";for(let S of R)if(S.trim())try{P(S,{controller:d,encoder:n,hasTextContent:()=>o,setHasTextContent:N=>o=N,reasoningContent:()=>a,appendReasoningContent:N=>a+=N,isReasoningComplete:()=>u,setReasoningComplete:N=>u=N})}catch(N){console.error("Error processing line:",S,N),d.enqueue(n.encode(S+` +`))}continue}let C=f.split(` +`);f=C.pop()||"";for(let R of C)if(R.trim())try{P(R,{controller:d,encoder:n,hasTextContent:()=>o,setHasTextContent:S=>o=S,reasoningContent:()=>a,appendReasoningContent:S=>a+=S,isReasoningComplete:()=>u,setReasoningComplete:S=>u=S})}catch(S){console.error("Error processing line:",R,S),d.enqueue(n.encode(R+` +`))}}}catch(v){console.error("Stream error:",v),d.error(v)}finally{try{_.releaseLock()}catch(v){console.error("Error releasing reader lock:",v)}d.close()}}});return new Response(h,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Yi=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens}static TransformerName="maxtoken";max_tokens;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),e}};var Xi=class{name="groq";async transformRequestIn(e){return e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(n=>{n.cache_control&&delete n.cache_control}):t.cache_control&&delete t.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(t=>{delete t.function.parameters.$schema}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,n=new TextEncoder,o=!1,a="",u=!1,l="",f=new ReadableStream({async start(h){let d=e.body.getReader(),_=(P,v,w)=>{let g=P.split(` +`);for(let C of g)C.trim()&&v.enqueue(w.encode(C+` +`))},E=(P,v)=>{let{controller:w,encoder:g}=v;if(P.startsWith("data: ")&&P.trim()!=="data: [DONE]"){let C=P.slice(6);try{let R=JSON.parse(C);if(R.error)throw new Error(JSON.stringify(R));R.choices?.[0]?.delta?.content&&!v.hasTextContent()&&v.setHasTextContent(!0),R.choices?.[0]?.delta?.tool_calls?.length&&R.choices?.[0]?.delta?.tool_calls.forEach(N=>{N.id=`call_${Fr()}`}),R.choices?.[0]?.delta?.tool_calls?.length&&v.hasTextContent()&&(typeof R.choices[0].index=="number"?R.choices[0].index+=1:R.choices[0].index=1);let S=`data: ${JSON.stringify(R)} + +`;w.enqueue(g.encode(S))}catch{w.enqueue(g.encode(P+` +`))}}else w.enqueue(g.encode(P+` +`))};try{for(;;){let{done:P,value:v}=await d.read();if(P){l.trim()&&_(l,h,n);break}if(!v||v.length===0)continue;let w;try{w=t.decode(v,{stream:!0})}catch(C){console.warn("Failed to decode chunk",C);continue}if(w.length===0)continue;if(l+=w,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let C=l.split(` +`);l=C.pop()||"";for(let R of C)if(R.trim())try{E(R,{controller:h,encoder:n,hasTextContent:()=>o,setHasTextContent:S=>o=S,reasoningContent:()=>a,appendReasoningContent:S=>a+=S,isReasoningComplete:()=>u,setReasoningComplete:S=>u=S})}catch(S){console.error("Error processing line:",R,S),h.enqueue(n.encode(R+` +`))}continue}let g=l.split(` +`);l=g.pop()||"";for(let C of g)if(C.trim())try{E(C,{controller:h,encoder:n,hasTextContent:()=>o,setHasTextContent:R=>o=R,reasoningContent:()=>a,appendReasoningContent:R=>a+=R,isReasoningComplete:()=>u,setReasoningComplete:R=>u=R})}catch(R){console.error("Error processing line:",C,R),h.enqueue(n.encode(C+` +`))}}}catch(P){console.error("Stream error:",P),h.error(P)}finally{try{d.releaseLock()}catch(P){console.error("Error releasing reader lock:",P)}h.close()}}});return new Response(f,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Qi=class{name="cleancache";async transformRequestIn(e){return Array.isArray(e.messages)&&e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(n=>{n.cache_control&&delete n.cache_control}):t.cache_control&&delete t.cache_control}),e}};var ig=Me(Ga(),1);var br=class extends Error{constructor(e,t){super(`${e} at position ${t}`),this.position=t}};function Zm(r){return/^[0-9A-Fa-f]$/.test(r)}function Lr(r){return r>="0"&&r<="9"}function eg(r){return r>=" "}function Ls(r){return`,:[]/{}() ++`.includes(r)}function dl(r){return r>="a"&&r<="z"||r>="A"&&r<="Z"||r==="_"||r==="$"}function hl(r){return r>="a"&&r<="z"||r>="A"&&r<="Z"||r==="_"||r==="$"||r>="0"&&r<="9"}var pl=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,ml=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function gl(r){return`,[]/{} ++`.includes(r)}function yl(r){return Us(r)||Hw.test(r)}var Hw=/^[[{\w-]$/;function tg(r){return r===` +`||r==="\r"||r===" "||r==="\b"||r==="\f"}function jr(r,e){let t=r.charCodeAt(e);return t===32||t===10||t===9||t===13}function rg(r,e){let t=r.charCodeAt(e);return t===32||t===9||t===13}function ng(r,e){let t=r.charCodeAt(e);return t===160||t>=8192&&t<=8202||t===8239||t===8287||t===12288}function Us(r){return _l(r)||Zi(r)}function _l(r){return r==='"'||r==="\u201C"||r==="\u201D"}function Cl(r){return r==='"'}function Zi(r){return r==="'"||r==="\u2018"||r==="\u2019"||r==="`"||r==="\xB4"}function bl(r){return r==="'"}function Yn(r,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=r.lastIndexOf(e);return n!==-1?r.substring(0,n)+(t?"":r.substring(n+1)):r}function Ft(r,e){let t=r.length;if(!jr(r,t-1))return r+e;for(;jr(r,t-1);)t--;return r.substring(0,t)+e+r.substring(t)}function sg(r,e,t){return r.substring(0,e)+r.substring(e+t)}function og(r){return/[,\n][ \t\r]*$/.test(r)}var Gw={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},Ww={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:` +`,r:"\r",t:" "};function El(r){let e=0,t="";h(["```","[```","{```"]),a()||te(),h(["```","```]","```}"]);let o=_(",");for(o&&u(),yl(r[e])&&og(t)?(o||(t=Ft(t,",")),C()):o&&(t=Yn(t,","));r[e]==="}"||r[e]==="]";)e++,u();if(e>=r.length)return t;ge();function a(){u();let J=w()||g()||R()||N()||j()||H(!1)||K();return u(),J}function u(){let J=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,ne=e,se=l(J);do se=f(),se&&(se=l(J));while(se);return e>ne}function l(J){let ne=J?jr:rg,se="";for(;;)if(ne(r,e))se+=r[e],e++;else if(ng(r,e))se+=" ",e++;else break;return se.length>0?(t+=se,!0):!1}function f(){if(r[e]==="/"&&r[e+1]==="*"){for(;e=r.length;Be||(yl(r[e])||qe?t=Ft(t,":"):Q()),a()||(Be||qe?t+="null":Q())}return r[e]==="}"?(t+="}",e++):t=Ft(t,"}"),!0}return!1}function g(){if(r[e]==="["){t+="[",e++,u(),E(",")&&u();let J=!0;for(;e0&&arguments[0]!==void 0?arguments[0]:!1,ne=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,se=r[e]==="\\";if(se&&(e++,se=!0),Us(r[e])){let Be=Cl(r[e])?Cl:bl(r[e])?bl:Zi(r[e])?Zi:_l,qe=e,G=t.length,he='"';for(e++;;){if(e>=r.length){let be=W(e-1);return!J&&Ls(r.charAt(be))?(e=qe,t=t.substring(0,G),R(!0)):(he=Ft(he,'"'),t+=he,!0)}if(e===ne)return he=Ft(he,'"'),t+=he,!0;if(Be(r[e])){let be=e,rr=he.length;if(he+='"',e++,t+=he,u(!1),J||e>=r.length||Ls(r[e])||Us(r[e])||Lr(r[e]))return S(),!0;let Pe=W(be-1),Ie=r.charAt(Pe);if(Ie===",")return e=qe,t=t.substring(0,G),R(!1,Pe);if(Ls(Ie))return e=qe,t=t.substring(0,G),R(!0);t=t.substring(0,G),e=be+1,he=`${he.substring(0,rr)}\\${he.substring(rr)}`}else if(J&&gl(r[e])){if(r[e-1]===":"&&pl.test(r.substring(qe+1,e+2)))for(;e=r.length?e=r.length:ae()}else he+=be,e+=2}else{let be=r.charAt(e);be==='"'&&r[e-1]!=="\\"?(he+=`\\${be}`,e++):tg(be)?(he+=Gw[be],e++):(eg(be)||le(be),he+=be,e++)}se&&P()}}return!1}function S(){let J=!1;for(u();r[e]==="+";){J=!0,e++,u(),t=Yn(t,'"',!0);let ne=t.length;R()?t=sg(t,ne,1):t=Ft(t,'"')}return J}function N(){let J=e;if(r[e]==="-"){if(e++,we())return de(J),!0;if(!Lr(r[e]))return e=J,!1}for(;Lr(r[e]);)e++;if(r[e]==="."){if(e++,we())return de(J),!0;if(!Lr(r[e]))return e=J,!1;for(;Lr(r[e]);)e++}if(r[e]==="e"||r[e]==="E"){if(e++,(r[e]==="-"||r[e]==="+")&&e++,we())return de(J),!0;if(!Lr(r[e]))return e=J,!1;for(;Lr(r[e]);)e++}if(!we())return e=J,!1;if(e>J){let ne=r.slice(J,e),se=/^0\d/.test(ne);return t+=se?`"${ne}"`:ne,!0}return!1}function j(){return L("true","true")||L("false","false")||L("null","null")||L("True","true")||L("False","false")||L("None","null")}function L(J,ne){return r.slice(e,e+J.length)===J?(t+=ne,e+=J.length,!0):!1}function H(J){let ne=e;if(dl(r[e])){for(;ene){for(;jr(r,e-1)&&e>0;)e--;let se=r.slice(ne,e);return t+=se==="undefined"?"null":JSON.stringify(se),r[e]==='"'&&e++,!0}}function K(){if(r[e]==="/"){let J=e;for(e++;e0&&jr(r,ne);)ne--;return ne}function we(){return e>=r.length||Ls(r[e])||jr(r,e)}function de(J){t+=`${r.slice(J,e)}0`}function le(J){throw new br(`Invalid character ${JSON.stringify(J)}`,e)}function ge(){throw new br(`Unexpected character ${JSON.stringify(r[e])}`,e)}function te(){throw new br("Unexpected end of json string",r.length)}function fe(){throw new br("Object key expected",e)}function Q(){throw new br("Colon expected",e)}function ae(){let J=r.slice(e,e+6);throw new br(`Invalid unicode character "${J}"`,e)}}function zw(r,e){return r[e]==="*"&&r[e+1]==="/"}function wl(r,e){if(!r||r.trim()===""||r==="{}")return"{}";try{return JSON.parse(r),e?.debug("\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u6807\u51C6JSON\u89E3\u6790\u6210\u529F / Tool arguments standard JSON parsing successful"),r}catch(t){try{let n=ig.default.parse(r);return e?.debug("\u5DE5\u5177\u8C03\u7528\u53C2\u6570JSON5\u89E3\u6790\u6210\u529F / Tool arguments JSON5 parsing successful"),JSON.stringify(n)}catch(n){try{let o=El(r);return e?.debug("\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u5B89\u5168\u4FEE\u590D\u6210\u529F / Tool arguments safely repaired"),o}catch(o){return e?.error(`JSON\u89E3\u6790\u5931\u8D25 / JSON parsing failed: ${t.message}. JSON5\u89E3\u6790\u5931\u8D25 / JSON5 parsing failed: ${n.message}. JSON\u4FEE\u590D\u5931\u8D25 / JSON repair failed: ${o.message}. \u8F93\u5165\u6570\u636E / Input data: ${JSON.stringify(r)}`),e?.debug("\u8FD4\u56DE\u5B89\u5168\u7684\u7A7A\u5BF9\u8C61\u4F5C\u4E3A\u540E\u5907\u65B9\u6848 / Returning safe empty object as fallback"),"{}"}}}}var ea=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();if(t?.choices?.[0]?.message?.tool_calls?.length)for(let n of t.choices[0].message.tool_calls)n.function?.arguments&&(n.function.arguments=wl(n.function.arguments,this.logger));return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,n=new TextEncoder,o={},a=!1,u="",l=!1,f=!1,h="",d=new ReadableStream({async start(_){let E=e.body.getReader(),P=(g,C,R)=>{let S=g.split(` +`);for(let N of S)N.trim()&&C.enqueue(R.encode(N+` +`))},v=(g,C,R)=>{let S="";try{S=wl(o.arguments||"",this.logger)}catch(H){console.error(`${H.message} ${H.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(o)}`),S=o.arguments||""}let N={role:"assistant",tool_calls:[{function:{name:o.name,arguments:S},id:o.id,index:o.index,type:"function"}]},j={...g,choices:[{...g.choices[0],delta:N}]};j.choices[0].delta.content!==void 0&&delete j.choices[0].delta.content;let L=`data: ${JSON.stringify(j)} + +`;C.enqueue(R.encode(L))},w=(g,C)=>{let{controller:R,encoder:S}=C;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let N=g.slice(6);try{let j=JSON.parse(N);if(j.choices?.[0]?.delta?.tool_calls?.length){let H=j.choices[0].delta.tool_calls[0];if(typeof o.index>"u"){o={index:H.index,name:H.function?.name||"",id:H.id||"",arguments:H.function?.arguments||""},H.function?.arguments&&(H.function.arguments="");let K=`data: ${JSON.stringify(j)} + +`;R.enqueue(S.encode(K));return}else if(o.index===H.index){H.function?.arguments&&(o.arguments+=H.function.arguments);return}else{v(j,R,S),o={index:H.index,name:H.function?.name||"",id:H.id||"",arguments:H.function?.arguments||""};return}}if(j.choices?.[0]?.finish_reason==="tool_calls"&&o.index!==void 0){v(j,R,S),o={};return}j.choices?.[0]?.delta?.tool_calls?.length&&C.hasTextContent()&&(typeof j.choices[0].index=="number"?j.choices[0].index+=1:j.choices[0].index=1);let L=`data: ${JSON.stringify(j)} + +`;R.enqueue(S.encode(L))}catch{R.enqueue(S.encode(g+` +`))}}else R.enqueue(S.encode(g+` +`))};try{for(;;){let{done:g,value:C}=await E.read();if(g){h.trim()&&P(h,_,n);break}if(!C||C.length===0)continue;let R;try{R=t.decode(C,{stream:!0})}catch(N){console.warn("Failed to decode chunk",N);continue}if(R.length===0)continue;if(h+=R,h.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let N=h.split(` +`);h=N.pop()||"";for(let j of N)if(j.trim())try{w(j,{controller:_,encoder:n,hasTextContent:()=>a,setHasTextContent:L=>a=L,reasoningContent:()=>u,appendReasoningContent:L=>u+=L,isReasoningComplete:()=>l,setReasoningComplete:L=>l=L})}catch(L){console.error("Error processing line:",j,L),_.enqueue(n.encode(j+` +`))}continue}let S=h.split(` +`);h=S.pop()||"";for(let N of S)if(N.trim())try{w(N,{controller:_,encoder:n,hasTextContent:()=>a,setHasTextContent:j=>a=j,reasoningContent:()=>u,appendReasoningContent:j=>u+=j,isReasoningComplete:()=>l,setReasoningComplete:j=>l=j})}catch(j){console.error("Error processing line:",N,j),_.enqueue(n.encode(N+` +`))}}}catch(g){console.error("Stream error:",g),_.error(g)}finally{try{E.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}_.close()}}});return new Response(d,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var ta=class{constructor(e){this.options=e;this.enable=this.options?.enable??!0}static TransformerName="reasoning";enable;async transformRequestIn(e){return this.enable?(e.reasoning&&(e.thinking={type:"enabled",budget_tokens:e.reasoning.max_tokens},e.enable_thinking=!0),e):(e.thinking={type:"disabled",budget_tokens:-1},e.enable_thinking=!1,e)}async transformResponseOut(e){if(!this.enable)return e;if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,n=new TextEncoder,o="",a=!1,u="",l=new ReadableStream({async start(f){let h=e.body.getReader(),d=(E,P,v)=>{let w=E.split(` +`);for(let g of w)g.trim()&&P.enqueue(v.encode(g+` +`))},_=(E,P)=>{let{controller:v,encoder:w}=P;if(this.logger?.debug({line:E},"Processing reason line"),E.startsWith("data: ")&&E.trim()!=="data: [DONE]")try{let g=JSON.parse(E.slice(6));if(g.choices?.[0]?.delta?.reasoning_content){P.appendReasoningContent(g.choices[0].delta.reasoning_content);let C={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete C.choices[0].delta.reasoning_content;let R=`data: ${JSON.stringify(C)} + +`;v.enqueue(w.encode(R));return}if((g.choices?.[0]?.delta?.content||g.choices?.[0]?.delta?.tool_calls)&&P.reasoningContent()&&!P.isReasoningComplete()){P.setReasoningComplete(!0);let C=Date.now().toString(),R={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:P.reasoningContent(),signature:C}}}]};delete R.choices[0].delta.reasoning_content;let S=`data: ${JSON.stringify(R)} + +`;v.enqueue(w.encode(S))}if(g.choices?.[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0){P.isReasoningComplete()&&g.choices[0].index++;let C=`data: ${JSON.stringify(g)} + +`;v.enqueue(w.encode(C))}}catch{v.enqueue(w.encode(E+` +`))}else v.enqueue(w.encode(E+` +`))};try{for(;;){let{done:E,value:P}=await h.read();if(E){u.trim()&&d(u,f,n);break}let v=t.decode(P,{stream:!0});u+=v;let w=u.split(` +`);u=w.pop()||"";for(let g of w)if(g.trim())try{_(g,{controller:f,encoder:n,reasoningContent:()=>o,appendReasoningContent:C=>o+=C,isReasoningComplete:()=>a,setReasoningComplete:C=>a=C})}catch(C){console.error("Error processing line:",g,C),f.enqueue(n.encode(g+` +`))}}}catch(E){console.error("Stream error:",E),f.error(E)}finally{try{h.releaseLock()}catch(E){console.error("Error releasing reader lock:",E)}f.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var ra=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens,this.temperature=this.options?.temperature,this.top_p=this.options?.top_p,this.top_k=this.options?.top_k,this.repetition_penalty=this.options?.repetition_penalty}name="sampling";max_tokens;temperature;top_p;top_k;repetition_penalty;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),typeof this.temperature<"u"&&(e.temperature=this.temperature),typeof this.top_p<"u"&&(e.top_p=this.top_p),typeof this.top_k<"u"&&(e.top_k=this.top_k),typeof this.repetition_penalty<"u"&&(e.repetition_penalty=this.repetition_penalty),e}};var na=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}};function ag(r){let e=[];for(let n=0;n{f.type==="text"?l.push({type:"text",text:f.text||""}):f.type==="image_url"&&l.push({type:"image",source:{type:"base64",media_type:f.media_type||"image/jpeg",data:f.image_url.url}})}),!(!a&&l.length===0&&!o.tool_calls&&!o.content)&&(a&&u&&l.length===0&&o.tool_calls&&l.push({type:"text",text:""}),e.push({role:o.role==="assistant"?"assistant":"user",content:l}))}let t={anthropic_version:"vertex-2023-10-16",messages:e,max_tokens:r.max_tokens||1e3,stream:r.stream||!1,...r.temperature&&{temperature:r.temperature}};return r.tools&&r.tools.length>0&&(t.tools=r.tools.map(n=>({name:n.function.name,description:n.function.description,input_schema:n.function.parameters}))),r.tool_choice&&(r.tool_choice==="auto"||r.tool_choice==="none"?t.tool_choice=r.tool_choice:typeof r.tool_choice=="string"&&(t.tool_choice={type:"tool",name:r.tool_choice})),t}function ug(r){let e=r,n={messages:e.messages.map(o=>{let a=o.content.map(u=>u.type==="text"?{type:"text",text:u.text||""}:u.type==="image"&&u.source?{type:"image_url",image_url:{url:u.source.data},media_type:u.source.media_type}:{type:"text",text:""});return{role:o.role,content:a}}),model:r.model||"claude-sonnet-4@20250514",max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream};return e.tools&&e.tools.length>0&&(n.tools=e.tools.map(o=>({type:"function",function:{name:o.name,description:o.description,parameters:{type:"object",properties:o.input_schema.properties,required:o.input_schema.required,additionalProperties:o.input_schema.additionalProperties,$schema:o.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?n.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(n.tool_choice=e.tool_choice.name)),n}async function cg(r,e,t){if(r.headers.get("Content-Type")?.includes("application/json")){let n=await r.json(),o;n.tool_use&&n.tool_use.length>0&&(o=n.tool_use.map(u=>({id:u.id,type:"function",function:{name:u.name,arguments:JSON.stringify(u.input)}})));let a={id:n.id,choices:[{finish_reason:n.stop_reason||null,index:0,message:{content:n.content[0]?.text||"",role:"assistant",...o&&{tool_calls:o}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:n.model,object:"chat.completion",usage:{completion_tokens:n.usage.output_tokens,prompt_tokens:n.usage.input_tokens,total_tokens:n.usage.input_tokens+n.usage.output_tokens}};return new Response(JSON.stringify(a),{status:r.status,statusText:r.statusText,headers:r.headers})}else if(r.headers.get("Content-Type")?.includes("stream")){if(!r.body)return r;let n=new TextDecoder,o=new TextEncoder,a=(l,f)=>{if(l.startsWith("data: ")){let h=l.slice(6).trim();if(h){t?.debug({chunkStr:h},`${e} chunk:`);try{let d=JSON.parse(h);if(d.type==="content_block_delta"&&d.delta?.type==="text_delta"){let _={choices:[{delta:{role:"assistant",content:d.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};f.enqueue(o.encode(`data: ${JSON.stringify(_)} + +`))}else if(d.type==="content_block_delta"&&d.delta?.type==="input_json_delta"){let _={choices:[{delta:{tool_calls:[{index:d.index||0,function:{arguments:d.delta.partial_json||""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};f.enqueue(o.encode(`data: ${JSON.stringify(_)} + +`))}else if(d.type==="content_block_start"&&d.content_block?.type==="tool_use"){let _={choices:[{delta:{tool_calls:[{index:d.index||0,id:d.content_block.id,type:"function",function:{name:d.content_block.name,arguments:""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};f.enqueue(o.encode(`data: ${JSON.stringify(_)} + +`))}else if(d.type==="message_delta"){let _={choices:[{delta:{},finish_reason:d.delta?.stop_reason==="tool_use"?"tool_calls":d.delta?.stop_reason==="max_tokens"?"length":d.delta?.stop_reason==="stop_sequence"?"content_filter":"stop",index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};f.enqueue(o.encode(`data: ${JSON.stringify(_)} + +`))}else if(d.type==="message_stop")f.enqueue(o.encode(`data: [DONE] + +`));else{let _={choices:[{delta:{role:"assistant",content:d.content?.[0]?.text||""},finish_reason:d.stop_reason?.toLowerCase()||null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};f.enqueue(o.encode(`data: ${JSON.stringify(_)} + +`))}}catch(d){t?.error(`Error parsing ${e} stream chunk`,h,d.message)}}}},u=new ReadableStream({async start(l){let f=r.body.getReader(),h="";try{for(;;){let{done:d,value:_}=await f.read();if(d){h&&a(h,l);break}h+=n.decode(_,{stream:!0});let E=h.split(` +`);h=E.pop()||"";for(let P of E)a(P,l)}}catch(d){l.error(d)}finally{l.close()}}});return new Response(u,{status:r.status,statusText:r.statusText,headers:r.headers})}return r}async function Jw(){try{let{GoogleAuth:r}=await Promise.resolve().then(()=>Me(fl(),1));return(await(await new r({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(r){throw console.error("Error getting access token:",r),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods: +1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file +2. Run "gcloud auth application-default login" +3. Use Google Cloud environment with default service account`)}}var sa=class{name="vertex-claude";async transformRequestIn(e,t){let n=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!n&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let l=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),f=JSON.parse(l);f&&f.project_id&&(n=f.project_id)}catch(u){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",u)}if(!n)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let a=await Jw();return{body:ag(e),config:{url:new URL(`/v1/projects/${n}/locations/${o}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${o}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return ug(e)}async transformResponseOut(e){return cg(e,this.name,this.logger)}};function lg(r){return typeof r=="string"?r:Array.isArray(r)?r.map(e=>typeof e=="string"?e:typeof e=="object"&&e!==null&&"type"in e&&e.type==="text"&&"text"in e&&typeof e.text=="string"?e.text:"").join(""):""}var oa=class{name="cerebras";async transformRequestIn(e,t){let n=JSON.parse(JSON.stringify(e));if(!n.model&&t.models&&t.models.length>0&&(n.model=t.models[0]),n.system!==void 0){let o=lg(n.system);n.messages||(n.messages=[]),n.messages.unshift({role:"system",content:o}),delete n.system}return n.messages&&Array.isArray(n.messages)&&(n.messages=n.messages.map(o=>{let a={...o};return a.content!==void 0&&(a.content=lg(a.content)),a})),{body:n,config:{headers:{Authorization:`Bearer ${t.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}};var ia=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var fg={AnthropicTransformer:So,GeminiTransformer:ko,VertexGeminiTransformer:zi,VertexClaudeTransformer:sa,DeepseekTransformer:Ji,TooluseTransformer:Vi,OpenrouterTransformer:Ki,MaxTokenTransformer:Yi,GroqTransformer:Xi,CleancacheTransformer:Qi,EnhanceToolTransformer:ea,ReasoningTransformer:ta,SamplingTransformer:ra,MaxCompletionTokens:na,CerebrasTransformer:oa,StreamOptionsTransformer:ia};var aa=class{constructor(e,t){this.configService=e;this.logger=t}transformers=new Map;registerTransformer(e,t){this.transformers.set(e,t),this.logger.info(`register transformer: ${e}${t.endPoint?` (endpoint: ${t.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[];return this.transformers.forEach((t,n)=>{t.endPoint&&e.push({name:n,transformer:t})}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((t,n)=>{t.endPoint||e.push({name:n,transformer:t})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let t=require(require.resolve(e.path));if(t){let n=new t(e.options);if(n&&typeof n=="object"&&(n.logger=this.logger),!n.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(n.name,n),!0}}return!1}catch(t){return this.logger.error(`load transformer (${e.path}) +error: ${t.message} +stack: ${t.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message} +Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(fg).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let t=new e;t&&typeof t=="object"&&(t.logger=this.logger),this.registerTransformer(t.name,t)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let t of e)await this.registerTransformerFromConfig(t)}};function Vw(r){let e=(0,dg.default)({bodyLimit:52428800,logger:r});return e.setErrorHandler(Uf),e.register(hg.default),e}var Al=class{app;configService;llmService;providerService;transformerService;constructor(e={}){this.app=Vw(e.logger??!0),this.configService=new bo(e),this.transformerService=new aa(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new wo(this.configService,this.transformerService,this.app.log),this.llmService=new Eo(this.providerService)})}async register(e,t){await this.app.register(e,t)}addHook(e,t){this.app.addHook(e,t)}async start(){try{this.app._server=this,this.app.addHook("preHandler",(n,o,a)=>{n.url.startsWith("/v1/messages")&&n.body&&(n.log.info({body:n.body},"request body"),n.body.stream,n.body.stream||(n.body.stream=!1)),a()}),this.app.addHook("preHandler",async(n,o)=>{if(!(n.url.startsWith("/api")||n.method!=="POST"))try{let a=n.body;if(!a||!a.model)return o.code(400).send({error:"Missing model in request body"});let[u,l]=a.model.split(",");a.model=l,n.provider=u;return}catch(a){return n.log.error("Error in modelProviderMiddleware:",a),o.code(500).send({error:"Internal server error"})}}),this.app.register(Gf);let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);let t=async n=>{this.app.log.info(`Received ${n}, shutting down gracefully...`),await this.app.close(),process.exit(0)};process.on("SIGINT",()=>t("SIGINT")),process.on("SIGTERM",()=>t("SIGTERM"))}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},Kw=Al; +/*! Bundled license information: + +web-streams-polyfill/dist/ponyfill.es2018.js: + (** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + *) + +fetch-blob/index.js: + (*! fetch-blob. MIT License. Jimmy Wärting *) + +formdata-polyfill/esm.min.js: + (*! formdata-polyfill. MIT License. Jimmy Wärting *) + +node-domexception/index.js: + (*! node-domexception. MIT License. Jimmy Wärting *) + +safe-buffer/index.js: + (*! safe-buffer. MIT License. Feross Aboukhadijeh *) + +gtoken/build/cjs/src/index.cjs: + (*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE *) +*/ +//# sourceMappingURL=server.cjs.map diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/server.cjs.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/server.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..59643e3c4d8b1ca44e9f80833985a2db580dd954 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/server.cjs.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/.pnpm/json5@2.2.3/node_modules/json5/lib/unicode.js", "../../node_modules/.pnpm/json5@2.2.3/node_modules/json5/lib/util.js", "../../node_modules/.pnpm/json5@2.2.3/node_modules/json5/lib/parse.js", "../../node_modules/.pnpm/json5@2.2.3/node_modules/json5/lib/stringify.js", "../../node_modules/.pnpm/json5@2.2.3/node_modules/json5/lib/index.js", "../../node_modules/.pnpm/extend@3.0.2/node_modules/extend/index.js", "../../node_modules/.pnpm/gaxios@7.1.1/node_modules/gaxios/package.json", "../../node_modules/.pnpm/gaxios@7.1.1/node_modules/gaxios/src/util.cts", "../../node_modules/.pnpm/gaxios@7.1.1/node_modules/gaxios/src/common.ts", "../../node_modules/.pnpm/gaxios@7.1.1/node_modules/gaxios/src/retry.ts", "../../node_modules/.pnpm/gaxios@7.1.1/node_modules/gaxios/src/interceptor.ts", "../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js", "../../node_modules/.pnpm/debug@4.4.1_supports-color@5.5.0/node_modules/debug/src/common.js", "../../node_modules/.pnpm/debug@4.4.1_supports-color@5.5.0/node_modules/debug/src/browser.js", "../../node_modules/.pnpm/has-flag@3.0.0/node_modules/has-flag/index.js", "../../node_modules/.pnpm/supports-color@5.5.0/node_modules/supports-color/index.js", "../../node_modules/.pnpm/debug@4.4.1_supports-color@5.5.0/node_modules/debug/src/node.js", "../../node_modules/.pnpm/debug@4.4.1_supports-color@5.5.0/node_modules/debug/src/index.js", "../../node_modules/.pnpm/agent-base@7.1.4/node_modules/agent-base/src/helpers.ts", "../../node_modules/.pnpm/agent-base@7.1.4/node_modules/agent-base/src/index.ts", "../../node_modules/.pnpm/https-proxy-agent@7.0.6/node_modules/https-proxy-agent/src/parse-proxy-response.ts", "../../node_modules/.pnpm/https-proxy-agent@7.0.6/node_modules/https-proxy-agent/src/index.ts", "../../node_modules/.pnpm/data-uri-to-buffer@4.0.1/node_modules/data-uri-to-buffer/src/index.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/utils.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/helpers/miscellaneous.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/helpers/webidl.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/simple-queue.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/abstract-ops/internal-methods.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/generic-reader.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/stub/number-isfinite.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/stub/math-trunc.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/basic.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/readable-stream.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/default-reader.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/target/es2018/stub/async-iterator-prototype.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/async-iterator.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/stub/number-isnan.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/abstract-ops/ecmascript.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/abstract-ops/miscellaneous.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/abstract-ops/queue-with-sizes.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/helpers/array-buffer-view.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/byte-stream-controller.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/reader-options.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/byob-reader.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/abstract-ops/queuing-strategy.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/queuing-strategy.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/underlying-sink.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/writable-stream.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/abort-signal.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/writable-stream.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/globals.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/stub/dom-exception.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/pipe.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/default-controller.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/tee.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/readable-stream-like.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/from.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/underlying-source.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/iterator-options.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/pipe-options.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/readable-writable-pair.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/queuing-strategy-init.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/byte-length-queuing-strategy.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/count-queuing-strategy.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/transformer.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/transform-stream.ts", "../../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/streams.cjs", "../../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/index.js", "../../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/file.js", "../../node_modules/.pnpm/formdata-polyfill@4.0.10/node_modules/formdata-polyfill/esm.min.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/base.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/fetch-error.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is.js", "../../node_modules/.pnpm/node-domexception@1.0.0/node_modules/node-domexception/index.js", "../../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/from.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/multipart-parser.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/body.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is-redirect.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/response.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/get-search.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/referrer.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/request.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/abort-error.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/index.js", "../../node_modules/.pnpm/gaxios@7.1.1/node_modules/gaxios/src/gaxios.ts", "../../node_modules/.pnpm/gaxios@7.1.1/node_modules/gaxios/src/index.ts", "../../node_modules/.pnpm/bignumber.js@9.3.1/node_modules/bignumber.js/bignumber.js", "../../node_modules/.pnpm/json-bigint@1.0.0/node_modules/json-bigint/lib/stringify.js", "../../node_modules/.pnpm/json-bigint@1.0.0/node_modules/json-bigint/lib/parse.js", "../../node_modules/.pnpm/json-bigint@1.0.0/node_modules/json-bigint/index.js", "../../node_modules/.pnpm/gcp-metadata@7.0.1/node_modules/gcp-metadata/src/gcp-residency.ts", "../../node_modules/.pnpm/google-logging-utils@1.1.1/node_modules/google-logging-utils/src/colours.ts", "../../node_modules/.pnpm/google-logging-utils@1.1.1/node_modules/google-logging-utils/src/logging-utils.ts", "../../node_modules/.pnpm/google-logging-utils@1.1.1/node_modules/google-logging-utils/src/index.ts", "../../node_modules/.pnpm/gcp-metadata@7.0.1/node_modules/gcp-metadata/src/index.ts", "../../node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/crypto/shared.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/crypto/browser/crypto.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/crypto/node/crypto.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/crypto/crypto.js", "../../node_modules/.pnpm/safe-buffer@5.2.1/node_modules/safe-buffer/index.js", "../../node_modules/.pnpm/ecdsa-sig-formatter@1.0.11/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js", "../../node_modules/.pnpm/ecdsa-sig-formatter@1.0.11/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/util.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/package.json", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/shared.cjs", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/authclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/loginticket.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/oauth2client.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/computeclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/idtokenclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/envDetect.js", "../../node_modules/.pnpm/jws@4.0.0/node_modules/jws/lib/data-stream.js", "../../node_modules/.pnpm/buffer-equal-constant-time@1.0.1/node_modules/buffer-equal-constant-time/index.js", "../../node_modules/.pnpm/jwa@2.0.1/node_modules/jwa/index.js", "../../node_modules/.pnpm/jws@4.0.0/node_modules/jws/lib/tostring.js", "../../node_modules/.pnpm/jws@4.0.0/node_modules/jws/lib/sign-stream.js", "../../node_modules/.pnpm/jws@4.0.0/node_modules/jws/lib/verify-stream.js", "../../node_modules/.pnpm/jws@4.0.0/node_modules/jws/index.js", "../../node_modules/.pnpm/gtoken@8.0.0/node_modules/gtoken/build/cjs/src/index.cjs", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/jwtaccess.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/jwtclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/refreshclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/impersonated.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/oauth2common.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/stscredentials.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/baseexternalclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/identitypoolclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/awsclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/executable-response.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/externalclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/googleauth.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/iam.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/downscopedclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/passthrough.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/index.js", "../../src/server.ts", "../../src/services/config.ts", "../../src/api/middleware.ts", "../../src/utils/request.ts", "../../package.json", "../../src/api/routes.ts", "../../src/services/llm.ts", "../../src/services/provider.ts", "../../node_modules/.pnpm/uuid@11.1.0/node_modules/uuid/dist/esm/stringify.js", "../../node_modules/.pnpm/uuid@11.1.0/node_modules/uuid/dist/esm/rng.js", "../../node_modules/.pnpm/uuid@11.1.0/node_modules/uuid/dist/esm/native.js", "../../node_modules/.pnpm/uuid@11.1.0/node_modules/uuid/dist/esm/v4.js", "../../src/utils/thinking.ts", "../../src/transformer/anthropic.transformer.ts", "../../src/utils/gemini.util.ts", "../../src/transformer/gemini.transformer.ts", "../../src/transformer/vertex-gemini.transformer.ts", "../../src/transformer/deepseek.transformer.ts", "../../src/transformer/tooluse.transformer.ts", "../../src/transformer/openrouter.transformer.ts", "../../src/transformer/maxtoken.transformer.ts", "../../src/transformer/groq.transformer.ts", "../../src/transformer/cleancache.transformer.ts", "../../src/utils/toolArgumentsParser.ts", "../../node_modules/.pnpm/jsonrepair@3.13.0/node_modules/jsonrepair/src/utils/JSONRepairError.ts", "../../node_modules/.pnpm/jsonrepair@3.13.0/node_modules/jsonrepair/src/utils/stringUtils.ts", "../../node_modules/.pnpm/jsonrepair@3.13.0/node_modules/jsonrepair/src/regular/jsonrepair.ts", "../../src/transformer/enhancetool.transformer.ts", "../../src/transformer/reasoning.transformer.ts", "../../src/transformer/sampling.transformer.ts", "../../src/transformer/maxcompletiontokens.transformer.ts", "../../src/utils/vertex-claude.util.ts", "../../src/transformer/vertex-claude.transformer.ts", "../../src/transformer/cerebras.transformer.ts", "../../src/transformer/streamoptions.transformer.ts", "../../src/transformer/index.ts", "../../src/services/transformer.ts"], + "sourcesContent": ["// This is a generated file. Do not edit.\nmodule.exports.Space_Separator = /[\\u1680\\u2000-\\u200A\\u202F\\u205F\\u3000]/\nmodule.exports.ID_Start = /[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086A\\u08A0-\\u08B4\\u08B6-\\u08BD\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u09FC\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0AF9\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58-\\u0C5A\\u0C60\\u0C61\\u0C80\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D54-\\u0D56\\u0D5F-\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u1884\\u1887-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1C80-\\u1C88\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312E\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FEA\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7AE\\uA7B0-\\uA7B7\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA8FD\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB65\\uAB70-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\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DCD0-\\uDCE8\\uDD03-\\uDD26\\uDD50-\\uDD72\\uDD76\\uDD83-\\uDDB2\\uDDC1-\\uDDC4\\uDDDA\\uDDDC\\uDE00-\\uDE11\\uDE13-\\uDE2B\\uDE80-\\uDE86\\uDE88\\uDE8A-\\uDE8D\\uDE8F-\\uDE9D\\uDE9F-\\uDEA8\\uDEB0-\\uDEDE\\uDF05-\\uDF0C\\uDF0F\\uDF10\\uDF13-\\uDF28\\uDF2A-\\uDF30\\uDF32\\uDF33\\uDF35-\\uDF39\\uDF3D\\uDF50\\uDF5D-\\uDF61]|\\uD805[\\uDC00-\\uDC34\\uDC47-\\uDC4A\\uDC80-\\uDCAF\\uDCC4\\uDCC5\\uDCC7\\uDD80-\\uDDAE\\uDDD8-\\uDDDB\\uDE00-\\uDE2F\\uDE44\\uDE80-\\uDEAA\\uDF00-\\uDF19]|\\uD806[\\uDCA0-\\uDCDF\\uDCFF\\uDE00\\uDE0B-\\uDE32\\uDE3A\\uDE50\\uDE5C-\\uDE83\\uDE86-\\uDE89\\uDEC0-\\uDEF8]|\\uD807[\\uDC00-\\uDC08\\uDC0A-\\uDC2E\\uDC40\\uDC72-\\uDC8F\\uDD00-\\uDD06\\uDD08\\uDD09\\uDD0B-\\uDD30\\uDD46]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC00-\\uDC6E\\uDC80-\\uDD43]|[\\uD80C\\uD81C-\\uD820\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872\\uD874-\\uD879][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2E]|\\uD811[\\uDC00-\\uDE46]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\uDED0-\\uDEED\\uDF00-\\uDF2F\\uDF40-\\uDF43\\uDF63-\\uDF77\\uDF7D-\\uDF8F]|\\uD81B[\\uDF00-\\uDF44\\uDF50\\uDF93-\\uDF9F\\uDFE0\\uDFE1]|\\uD821[\\uDC00-\\uDFEC]|\\uD822[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DC00-\\uDEA1\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0]|\\uD87E[\\uDC00-\\uDE1D]/\nmodule.exports.ID_Continue = /[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0300-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u0483-\\u0487\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0610-\\u061A\\u0620-\\u0669\\u066E-\\u06D3\\u06D5-\\u06DC\\u06DF-\\u06E8\\u06EA-\\u06FC\\u06FF\\u0710-\\u074A\\u074D-\\u07B1\\u07C0-\\u07F5\\u07FA\\u0800-\\u082D\\u0840-\\u085B\\u0860-\\u086A\\u08A0-\\u08B4\\u08B6-\\u08BD\\u08D4-\\u08E1\\u08E3-\\u0963\\u0966-\\u096F\\u0971-\\u0983\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BC-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CE\\u09D7\\u09DC\\u09DD\\u09DF-\\u09E3\\u09E6-\\u09F1\\u09FC\\u0A01-\\u0A03\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A59-\\u0A5C\\u0A5E\\u0A66-\\u0A75\\u0A81-\\u0A83\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\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7A-\\u0D7F\\u0D82\\u0D83\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DE6-\\u0DEF\\u0DF2\\u0DF3\\u0E01-\\u0E3A\\u0E40-\\u0E4E\\u0E50-\\u0E59\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB9\\u0EBB-\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EC8-\\u0ECD\\u0ED0-\\u0ED9\\u0EDC-\\u0EDF\\u0F00\\u0F18\\u0F19\\u0F20-\\u0F29\\u0F35\\u0F37\\u0F39\\u0F3E-\\u0F47\\u0F49-\\u0F6C\\u0F71-\\u0F84\\u0F86-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u1000-\\u1049\\u1050-\\u109D\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u135D-\\u135F\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1714\\u1720-\\u1734\\u1740-\\u1753\\u1760-\\u176C\\u176E-\\u1770\\u1772\\u1773\\u1780-\\u17D3\\u17D7\\u17DC\\u17DD\\u17E0-\\u17E9\\u180B-\\u180D\\u1810-\\u1819\\u1820-\\u1877\\u1880-\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1920-\\u192B\\u1930-\\u193B\\u1946-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u19D0-\\u19D9\\u1A00-\\u1A1B\\u1A20-\\u1A5E\\u1A60-\\u1A7C\\u1A7F-\\u1A89\\u1A90-\\u1A99\\u1AA7\\u1AB0-\\u1ABD\\u1B00-\\u1B4B\\u1B50-\\u1B59\\u1B6B-\\u1B73\\u1B80-\\u1BF3\\u1C00-\\u1C37\\u1C40-\\u1C49\\u1C4D-\\u1C7D\\u1C80-\\u1C88\\u1CD0-\\u1CD2\\u1CD4-\\u1CF9\\u1D00-\\u1DF9\\u1DFB-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u203F\\u2040\\u2054\\u2071\\u207F\\u2090-\\u209C\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D7F-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2DE0-\\u2DFF\\u2E2F\\u3005-\\u3007\\u3021-\\u302F\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u3099\\u309A\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312E\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FEA\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA62B\\uA640-\\uA66F\\uA674-\\uA67D\\uA67F-\\uA6F1\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7AE\\uA7B0-\\uA7B7\\uA7F7-\\uA827\\uA840-\\uA873\\uA880-\\uA8C5\\uA8D0-\\uA8D9\\uA8E0-\\uA8F7\\uA8FB\\uA8FD\\uA900-\\uA92D\\uA930-\\uA953\\uA960-\\uA97C\\uA980-\\uA9C0\\uA9CF-\\uA9D9\\uA9E0-\\uA9FE\\uAA00-\\uAA36\\uAA40-\\uAA4D\\uAA50-\\uAA59\\uAA60-\\uAA76\\uAA7A-\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEF\\uAAF2-\\uAAF6\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB65\\uAB70-\\uABEA\\uABEC\\uABED\\uABF0-\\uABF9\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE00-\\uFE0F\\uFE20-\\uFE2F\\uFE33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E36\\uDE3B-\\uDE6C\\uDE75\\uDE84\\uDE9B-\\uDE9F\\uDEA1-\\uDEAF]|\\uD838[\\uDC00-\\uDC06\\uDC08-\\uDC18\\uDC1B-\\uDC21\\uDC23\\uDC24\\uDC26-\\uDC2A]|\\uD83A[\\uDC00-\\uDCC4\\uDCD0-\\uDCD6\\uDD00-\\uDD4A\\uDD50-\\uDD59]|\\uD83B[\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD869[\\uDC00-\\uDED6\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF34\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEA1\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0]|\\uD87E[\\uDC00-\\uDE1D]|\\uDB40[\\uDD00-\\uDDEF]/\n", "const unicode = require('../lib/unicode')\n\nmodule.exports = {\n isSpaceSeparator (c) {\n return typeof c === 'string' && unicode.Space_Separator.test(c)\n },\n\n isIdStartChar (c) {\n return typeof c === 'string' && (\n (c >= 'a' && c <= 'z') ||\n (c >= 'A' && c <= 'Z') ||\n (c === '$') || (c === '_') ||\n unicode.ID_Start.test(c)\n )\n },\n\n isIdContinueChar (c) {\n return typeof c === 'string' && (\n (c >= 'a' && c <= 'z') ||\n (c >= 'A' && c <= 'Z') ||\n (c >= '0' && c <= '9') ||\n (c === '$') || (c === '_') ||\n (c === '\\u200C') || (c === '\\u200D') ||\n unicode.ID_Continue.test(c)\n )\n },\n\n isDigit (c) {\n return typeof c === 'string' && /[0-9]/.test(c)\n },\n\n isHexDigit (c) {\n return typeof c === 'string' && /[0-9A-Fa-f]/.test(c)\n },\n}\n", "const util = require('./util')\n\nlet source\nlet parseState\nlet stack\nlet pos\nlet line\nlet column\nlet token\nlet key\nlet root\n\nmodule.exports = function parse (text, reviver) {\n source = String(text)\n parseState = 'start'\n stack = []\n pos = 0\n line = 1\n column = 0\n token = undefined\n key = undefined\n root = undefined\n\n do {\n token = lex()\n\n // This code is unreachable.\n // if (!parseStates[parseState]) {\n // throw invalidParseState()\n // }\n\n parseStates[parseState]()\n } while (token.type !== 'eof')\n\n if (typeof reviver === 'function') {\n return internalize({'': root}, '', reviver)\n }\n\n return root\n}\n\nfunction internalize (holder, name, reviver) {\n const value = holder[name]\n if (value != null && typeof value === 'object') {\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n const key = String(i)\n const replacement = internalize(value, key, reviver)\n if (replacement === undefined) {\n delete value[key]\n } else {\n Object.defineProperty(value, key, {\n value: replacement,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n }\n }\n } else {\n for (const key in value) {\n const replacement = internalize(value, key, reviver)\n if (replacement === undefined) {\n delete value[key]\n } else {\n Object.defineProperty(value, key, {\n value: replacement,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n }\n }\n }\n }\n\n return reviver.call(holder, name, value)\n}\n\nlet lexState\nlet buffer\nlet doubleQuote\nlet sign\nlet c\n\nfunction lex () {\n lexState = 'default'\n buffer = ''\n doubleQuote = false\n sign = 1\n\n for (;;) {\n c = peek()\n\n // This code is unreachable.\n // if (!lexStates[lexState]) {\n // throw invalidLexState(lexState)\n // }\n\n const token = lexStates[lexState]()\n if (token) {\n return token\n }\n }\n}\n\nfunction peek () {\n if (source[pos]) {\n return String.fromCodePoint(source.codePointAt(pos))\n }\n}\n\nfunction read () {\n const c = peek()\n\n if (c === '\\n') {\n line++\n column = 0\n } else if (c) {\n column += c.length\n } else {\n column++\n }\n\n if (c) {\n pos += c.length\n }\n\n return c\n}\n\nconst lexStates = {\n default () {\n switch (c) {\n case '\\t':\n case '\\v':\n case '\\f':\n case ' ':\n case '\\u00A0':\n case '\\uFEFF':\n case '\\n':\n case '\\r':\n case '\\u2028':\n case '\\u2029':\n read()\n return\n\n case '/':\n read()\n lexState = 'comment'\n return\n\n case undefined:\n read()\n return newToken('eof')\n }\n\n if (util.isSpaceSeparator(c)) {\n read()\n return\n }\n\n // This code is unreachable.\n // if (!lexStates[parseState]) {\n // throw invalidLexState(parseState)\n // }\n\n return lexStates[parseState]()\n },\n\n comment () {\n switch (c) {\n case '*':\n read()\n lexState = 'multiLineComment'\n return\n\n case '/':\n read()\n lexState = 'singleLineComment'\n return\n }\n\n throw invalidChar(read())\n },\n\n multiLineComment () {\n switch (c) {\n case '*':\n read()\n lexState = 'multiLineCommentAsterisk'\n return\n\n case undefined:\n throw invalidChar(read())\n }\n\n read()\n },\n\n multiLineCommentAsterisk () {\n switch (c) {\n case '*':\n read()\n return\n\n case '/':\n read()\n lexState = 'default'\n return\n\n case undefined:\n throw invalidChar(read())\n }\n\n read()\n lexState = 'multiLineComment'\n },\n\n singleLineComment () {\n switch (c) {\n case '\\n':\n case '\\r':\n case '\\u2028':\n case '\\u2029':\n read()\n lexState = 'default'\n return\n\n case undefined:\n read()\n return newToken('eof')\n }\n\n read()\n },\n\n value () {\n switch (c) {\n case '{':\n case '[':\n return newToken('punctuator', read())\n\n case 'n':\n read()\n literal('ull')\n return newToken('null', null)\n\n case 't':\n read()\n literal('rue')\n return newToken('boolean', true)\n\n case 'f':\n read()\n literal('alse')\n return newToken('boolean', false)\n\n case '-':\n case '+':\n if (read() === '-') {\n sign = -1\n }\n\n lexState = 'sign'\n return\n\n case '.':\n buffer = read()\n lexState = 'decimalPointLeading'\n return\n\n case '0':\n buffer = read()\n lexState = 'zero'\n return\n\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n buffer = read()\n lexState = 'decimalInteger'\n return\n\n case 'I':\n read()\n literal('nfinity')\n return newToken('numeric', Infinity)\n\n case 'N':\n read()\n literal('aN')\n return newToken('numeric', NaN)\n\n case '\"':\n case \"'\":\n doubleQuote = (read() === '\"')\n buffer = ''\n lexState = 'string'\n return\n }\n\n throw invalidChar(read())\n },\n\n identifierNameStartEscape () {\n if (c !== 'u') {\n throw invalidChar(read())\n }\n\n read()\n const u = unicodeEscape()\n switch (u) {\n case '$':\n case '_':\n break\n\n default:\n if (!util.isIdStartChar(u)) {\n throw invalidIdentifier()\n }\n\n break\n }\n\n buffer += u\n lexState = 'identifierName'\n },\n\n identifierName () {\n switch (c) {\n case '$':\n case '_':\n case '\\u200C':\n case '\\u200D':\n buffer += read()\n return\n\n case '\\\\':\n read()\n lexState = 'identifierNameEscape'\n return\n }\n\n if (util.isIdContinueChar(c)) {\n buffer += read()\n return\n }\n\n return newToken('identifier', buffer)\n },\n\n identifierNameEscape () {\n if (c !== 'u') {\n throw invalidChar(read())\n }\n\n read()\n const u = unicodeEscape()\n switch (u) {\n case '$':\n case '_':\n case '\\u200C':\n case '\\u200D':\n break\n\n default:\n if (!util.isIdContinueChar(u)) {\n throw invalidIdentifier()\n }\n\n break\n }\n\n buffer += u\n lexState = 'identifierName'\n },\n\n sign () {\n switch (c) {\n case '.':\n buffer = read()\n lexState = 'decimalPointLeading'\n return\n\n case '0':\n buffer = read()\n lexState = 'zero'\n return\n\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n buffer = read()\n lexState = 'decimalInteger'\n return\n\n case 'I':\n read()\n literal('nfinity')\n return newToken('numeric', sign * Infinity)\n\n case 'N':\n read()\n literal('aN')\n return newToken('numeric', NaN)\n }\n\n throw invalidChar(read())\n },\n\n zero () {\n switch (c) {\n case '.':\n buffer += read()\n lexState = 'decimalPoint'\n return\n\n case 'e':\n case 'E':\n buffer += read()\n lexState = 'decimalExponent'\n return\n\n case 'x':\n case 'X':\n buffer += read()\n lexState = 'hexadecimal'\n return\n }\n\n return newToken('numeric', sign * 0)\n },\n\n decimalInteger () {\n switch (c) {\n case '.':\n buffer += read()\n lexState = 'decimalPoint'\n return\n\n case 'e':\n case 'E':\n buffer += read()\n lexState = 'decimalExponent'\n return\n }\n\n if (util.isDigit(c)) {\n buffer += read()\n return\n }\n\n return newToken('numeric', sign * Number(buffer))\n },\n\n decimalPointLeading () {\n if (util.isDigit(c)) {\n buffer += read()\n lexState = 'decimalFraction'\n return\n }\n\n throw invalidChar(read())\n },\n\n decimalPoint () {\n switch (c) {\n case 'e':\n case 'E':\n buffer += read()\n lexState = 'decimalExponent'\n return\n }\n\n if (util.isDigit(c)) {\n buffer += read()\n lexState = 'decimalFraction'\n return\n }\n\n return newToken('numeric', sign * Number(buffer))\n },\n\n decimalFraction () {\n switch (c) {\n case 'e':\n case 'E':\n buffer += read()\n lexState = 'decimalExponent'\n return\n }\n\n if (util.isDigit(c)) {\n buffer += read()\n return\n }\n\n return newToken('numeric', sign * Number(buffer))\n },\n\n decimalExponent () {\n switch (c) {\n case '+':\n case '-':\n buffer += read()\n lexState = 'decimalExponentSign'\n return\n }\n\n if (util.isDigit(c)) {\n buffer += read()\n lexState = 'decimalExponentInteger'\n return\n }\n\n throw invalidChar(read())\n },\n\n decimalExponentSign () {\n if (util.isDigit(c)) {\n buffer += read()\n lexState = 'decimalExponentInteger'\n return\n }\n\n throw invalidChar(read())\n },\n\n decimalExponentInteger () {\n if (util.isDigit(c)) {\n buffer += read()\n return\n }\n\n return newToken('numeric', sign * Number(buffer))\n },\n\n hexadecimal () {\n if (util.isHexDigit(c)) {\n buffer += read()\n lexState = 'hexadecimalInteger'\n return\n }\n\n throw invalidChar(read())\n },\n\n hexadecimalInteger () {\n if (util.isHexDigit(c)) {\n buffer += read()\n return\n }\n\n return newToken('numeric', sign * Number(buffer))\n },\n\n string () {\n switch (c) {\n case '\\\\':\n read()\n buffer += escape()\n return\n\n case '\"':\n if (doubleQuote) {\n read()\n return newToken('string', buffer)\n }\n\n buffer += read()\n return\n\n case \"'\":\n if (!doubleQuote) {\n read()\n return newToken('string', buffer)\n }\n\n buffer += read()\n return\n\n case '\\n':\n case '\\r':\n throw invalidChar(read())\n\n case '\\u2028':\n case '\\u2029':\n separatorChar(c)\n break\n\n case undefined:\n throw invalidChar(read())\n }\n\n buffer += read()\n },\n\n start () {\n switch (c) {\n case '{':\n case '[':\n return newToken('punctuator', read())\n\n // This code is unreachable since the default lexState handles eof.\n // case undefined:\n // return newToken('eof')\n }\n\n lexState = 'value'\n },\n\n beforePropertyName () {\n switch (c) {\n case '$':\n case '_':\n buffer = read()\n lexState = 'identifierName'\n return\n\n case '\\\\':\n read()\n lexState = 'identifierNameStartEscape'\n return\n\n case '}':\n return newToken('punctuator', read())\n\n case '\"':\n case \"'\":\n doubleQuote = (read() === '\"')\n lexState = 'string'\n return\n }\n\n if (util.isIdStartChar(c)) {\n buffer += read()\n lexState = 'identifierName'\n return\n }\n\n throw invalidChar(read())\n },\n\n afterPropertyName () {\n if (c === ':') {\n return newToken('punctuator', read())\n }\n\n throw invalidChar(read())\n },\n\n beforePropertyValue () {\n lexState = 'value'\n },\n\n afterPropertyValue () {\n switch (c) {\n case ',':\n case '}':\n return newToken('punctuator', read())\n }\n\n throw invalidChar(read())\n },\n\n beforeArrayValue () {\n if (c === ']') {\n return newToken('punctuator', read())\n }\n\n lexState = 'value'\n },\n\n afterArrayValue () {\n switch (c) {\n case ',':\n case ']':\n return newToken('punctuator', read())\n }\n\n throw invalidChar(read())\n },\n\n end () {\n // This code is unreachable since it's handled by the default lexState.\n // if (c === undefined) {\n // read()\n // return newToken('eof')\n // }\n\n throw invalidChar(read())\n },\n}\n\nfunction newToken (type, value) {\n return {\n type,\n value,\n line,\n column,\n }\n}\n\nfunction literal (s) {\n for (const c of s) {\n const p = peek()\n\n if (p !== c) {\n throw invalidChar(read())\n }\n\n read()\n }\n}\n\nfunction escape () {\n const c = peek()\n switch (c) {\n case 'b':\n read()\n return '\\b'\n\n case 'f':\n read()\n return '\\f'\n\n case 'n':\n read()\n return '\\n'\n\n case 'r':\n read()\n return '\\r'\n\n case 't':\n read()\n return '\\t'\n\n case 'v':\n read()\n return '\\v'\n\n case '0':\n read()\n if (util.isDigit(peek())) {\n throw invalidChar(read())\n }\n\n return '\\0'\n\n case 'x':\n read()\n return hexEscape()\n\n case 'u':\n read()\n return unicodeEscape()\n\n case '\\n':\n case '\\u2028':\n case '\\u2029':\n read()\n return ''\n\n case '\\r':\n read()\n if (peek() === '\\n') {\n read()\n }\n\n return ''\n\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n throw invalidChar(read())\n\n case undefined:\n throw invalidChar(read())\n }\n\n return read()\n}\n\nfunction hexEscape () {\n let buffer = ''\n let c = peek()\n\n if (!util.isHexDigit(c)) {\n throw invalidChar(read())\n }\n\n buffer += read()\n\n c = peek()\n if (!util.isHexDigit(c)) {\n throw invalidChar(read())\n }\n\n buffer += read()\n\n return String.fromCodePoint(parseInt(buffer, 16))\n}\n\nfunction unicodeEscape () {\n let buffer = ''\n let count = 4\n\n while (count-- > 0) {\n const c = peek()\n if (!util.isHexDigit(c)) {\n throw invalidChar(read())\n }\n\n buffer += read()\n }\n\n return String.fromCodePoint(parseInt(buffer, 16))\n}\n\nconst parseStates = {\n start () {\n if (token.type === 'eof') {\n throw invalidEOF()\n }\n\n push()\n },\n\n beforePropertyName () {\n switch (token.type) {\n case 'identifier':\n case 'string':\n key = token.value\n parseState = 'afterPropertyName'\n return\n\n case 'punctuator':\n // This code is unreachable since it's handled by the lexState.\n // if (token.value !== '}') {\n // throw invalidToken()\n // }\n\n pop()\n return\n\n case 'eof':\n throw invalidEOF()\n }\n\n // This code is unreachable since it's handled by the lexState.\n // throw invalidToken()\n },\n\n afterPropertyName () {\n // This code is unreachable since it's handled by the lexState.\n // if (token.type !== 'punctuator' || token.value !== ':') {\n // throw invalidToken()\n // }\n\n if (token.type === 'eof') {\n throw invalidEOF()\n }\n\n parseState = 'beforePropertyValue'\n },\n\n beforePropertyValue () {\n if (token.type === 'eof') {\n throw invalidEOF()\n }\n\n push()\n },\n\n beforeArrayValue () {\n if (token.type === 'eof') {\n throw invalidEOF()\n }\n\n if (token.type === 'punctuator' && token.value === ']') {\n pop()\n return\n }\n\n push()\n },\n\n afterPropertyValue () {\n // This code is unreachable since it's handled by the lexState.\n // if (token.type !== 'punctuator') {\n // throw invalidToken()\n // }\n\n if (token.type === 'eof') {\n throw invalidEOF()\n }\n\n switch (token.value) {\n case ',':\n parseState = 'beforePropertyName'\n return\n\n case '}':\n pop()\n }\n\n // This code is unreachable since it's handled by the lexState.\n // throw invalidToken()\n },\n\n afterArrayValue () {\n // This code is unreachable since it's handled by the lexState.\n // if (token.type !== 'punctuator') {\n // throw invalidToken()\n // }\n\n if (token.type === 'eof') {\n throw invalidEOF()\n }\n\n switch (token.value) {\n case ',':\n parseState = 'beforeArrayValue'\n return\n\n case ']':\n pop()\n }\n\n // This code is unreachable since it's handled by the lexState.\n // throw invalidToken()\n },\n\n end () {\n // This code is unreachable since it's handled by the lexState.\n // if (token.type !== 'eof') {\n // throw invalidToken()\n // }\n },\n}\n\nfunction push () {\n let value\n\n switch (token.type) {\n case 'punctuator':\n switch (token.value) {\n case '{':\n value = {}\n break\n\n case '[':\n value = []\n break\n }\n\n break\n\n case 'null':\n case 'boolean':\n case 'numeric':\n case 'string':\n value = token.value\n break\n\n // This code is unreachable.\n // default:\n // throw invalidToken()\n }\n\n if (root === undefined) {\n root = value\n } else {\n const parent = stack[stack.length - 1]\n if (Array.isArray(parent)) {\n parent.push(value)\n } else {\n Object.defineProperty(parent, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n }\n }\n\n if (value !== null && typeof value === 'object') {\n stack.push(value)\n\n if (Array.isArray(value)) {\n parseState = 'beforeArrayValue'\n } else {\n parseState = 'beforePropertyName'\n }\n } else {\n const current = stack[stack.length - 1]\n if (current == null) {\n parseState = 'end'\n } else if (Array.isArray(current)) {\n parseState = 'afterArrayValue'\n } else {\n parseState = 'afterPropertyValue'\n }\n }\n}\n\nfunction pop () {\n stack.pop()\n\n const current = stack[stack.length - 1]\n if (current == null) {\n parseState = 'end'\n } else if (Array.isArray(current)) {\n parseState = 'afterArrayValue'\n } else {\n parseState = 'afterPropertyValue'\n }\n}\n\n// This code is unreachable.\n// function invalidParseState () {\n// return new Error(`JSON5: invalid parse state '${parseState}'`)\n// }\n\n// This code is unreachable.\n// function invalidLexState (state) {\n// return new Error(`JSON5: invalid lex state '${state}'`)\n// }\n\nfunction invalidChar (c) {\n if (c === undefined) {\n return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)\n }\n\n return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)\n}\n\nfunction invalidEOF () {\n return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)\n}\n\n// This code is unreachable.\n// function invalidToken () {\n// if (token.type === 'eof') {\n// return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)\n// }\n\n// const c = String.fromCodePoint(token.value.codePointAt(0))\n// return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)\n// }\n\nfunction invalidIdentifier () {\n column -= 5\n return syntaxError(`JSON5: invalid identifier character at ${line}:${column}`)\n}\n\nfunction separatorChar (c) {\n console.warn(`JSON5: '${formatChar(c)}' in strings is not valid ECMAScript; consider escaping`)\n}\n\nfunction formatChar (c) {\n const replacements = {\n \"'\": \"\\\\'\",\n '\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n '\\v': '\\\\v',\n '\\0': '\\\\0',\n '\\u2028': '\\\\u2028',\n '\\u2029': '\\\\u2029',\n }\n\n if (replacements[c]) {\n return replacements[c]\n }\n\n if (c < ' ') {\n const hexString = c.charCodeAt(0).toString(16)\n return '\\\\x' + ('00' + hexString).substring(hexString.length)\n }\n\n return c\n}\n\nfunction syntaxError (message) {\n const err = new SyntaxError(message)\n err.lineNumber = line\n err.columnNumber = column\n return err\n}\n", "const util = require('./util')\n\nmodule.exports = function stringify (value, replacer, space) {\n const stack = []\n let indent = ''\n let propertyList\n let replacerFunc\n let gap = ''\n let quote\n\n if (\n replacer != null &&\n typeof replacer === 'object' &&\n !Array.isArray(replacer)\n ) {\n space = replacer.space\n quote = replacer.quote\n replacer = replacer.replacer\n }\n\n if (typeof replacer === 'function') {\n replacerFunc = replacer\n } else if (Array.isArray(replacer)) {\n propertyList = []\n for (const v of replacer) {\n let item\n\n if (typeof v === 'string') {\n item = v\n } else if (\n typeof v === 'number' ||\n v instanceof String ||\n v instanceof Number\n ) {\n item = String(v)\n }\n\n if (item !== undefined && propertyList.indexOf(item) < 0) {\n propertyList.push(item)\n }\n }\n }\n\n if (space instanceof Number) {\n space = Number(space)\n } else if (space instanceof String) {\n space = String(space)\n }\n\n if (typeof space === 'number') {\n if (space > 0) {\n space = Math.min(10, Math.floor(space))\n gap = ' '.substr(0, space)\n }\n } else if (typeof space === 'string') {\n gap = space.substr(0, 10)\n }\n\n return serializeProperty('', {'': value})\n\n function serializeProperty (key, holder) {\n let value = holder[key]\n if (value != null) {\n if (typeof value.toJSON5 === 'function') {\n value = value.toJSON5(key)\n } else if (typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n }\n }\n\n if (replacerFunc) {\n value = replacerFunc.call(holder, key, value)\n }\n\n if (value instanceof Number) {\n value = Number(value)\n } else if (value instanceof String) {\n value = String(value)\n } else if (value instanceof Boolean) {\n value = value.valueOf()\n }\n\n switch (value) {\n case null: return 'null'\n case true: return 'true'\n case false: return 'false'\n }\n\n if (typeof value === 'string') {\n return quoteString(value, false)\n }\n\n if (typeof value === 'number') {\n return String(value)\n }\n\n if (typeof value === 'object') {\n return Array.isArray(value) ? serializeArray(value) : serializeObject(value)\n }\n\n return undefined\n }\n\n function quoteString (value) {\n const quotes = {\n \"'\": 0.1,\n '\"': 0.2,\n }\n\n const replacements = {\n \"'\": \"\\\\'\",\n '\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n '\\v': '\\\\v',\n '\\0': '\\\\0',\n '\\u2028': '\\\\u2028',\n '\\u2029': '\\\\u2029',\n }\n\n let product = ''\n\n for (let i = 0; i < value.length; i++) {\n const c = value[i]\n switch (c) {\n case \"'\":\n case '\"':\n quotes[c]++\n product += c\n continue\n\n case '\\0':\n if (util.isDigit(value[i + 1])) {\n product += '\\\\x00'\n continue\n }\n }\n\n if (replacements[c]) {\n product += replacements[c]\n continue\n }\n\n if (c < ' ') {\n let hexString = c.charCodeAt(0).toString(16)\n product += '\\\\x' + ('00' + hexString).substring(hexString.length)\n continue\n }\n\n product += c\n }\n\n const quoteChar = quote || Object.keys(quotes).reduce((a, b) => (quotes[a] < quotes[b]) ? a : b)\n\n product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar])\n\n return quoteChar + product + quoteChar\n }\n\n function serializeObject (value) {\n if (stack.indexOf(value) >= 0) {\n throw TypeError('Converting circular structure to JSON5')\n }\n\n stack.push(value)\n\n let stepback = indent\n indent = indent + gap\n\n let keys = propertyList || Object.keys(value)\n let partial = []\n for (const key of keys) {\n const propertyString = serializeProperty(key, value)\n if (propertyString !== undefined) {\n let member = serializeKey(key) + ':'\n if (gap !== '') {\n member += ' '\n }\n member += propertyString\n partial.push(member)\n }\n }\n\n let final\n if (partial.length === 0) {\n final = '{}'\n } else {\n let properties\n if (gap === '') {\n properties = partial.join(',')\n final = '{' + properties + '}'\n } else {\n let separator = ',\\n' + indent\n properties = partial.join(separator)\n final = '{\\n' + indent + properties + ',\\n' + stepback + '}'\n }\n }\n\n stack.pop()\n indent = stepback\n return final\n }\n\n function serializeKey (key) {\n if (key.length === 0) {\n return quoteString(key, true)\n }\n\n const firstChar = String.fromCodePoint(key.codePointAt(0))\n if (!util.isIdStartChar(firstChar)) {\n return quoteString(key, true)\n }\n\n for (let i = firstChar.length; i < key.length; i++) {\n if (!util.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) {\n return quoteString(key, true)\n }\n }\n\n return key\n }\n\n function serializeArray (value) {\n if (stack.indexOf(value) >= 0) {\n throw TypeError('Converting circular structure to JSON5')\n }\n\n stack.push(value)\n\n let stepback = indent\n indent = indent + gap\n\n let partial = []\n for (let i = 0; i < value.length; i++) {\n const propertyString = serializeProperty(String(i), value)\n partial.push((propertyString !== undefined) ? propertyString : 'null')\n }\n\n let final\n if (partial.length === 0) {\n final = '[]'\n } else {\n if (gap === '') {\n let properties = partial.join(',')\n final = '[' + properties + ']'\n } else {\n let separator = ',\\n' + indent\n let properties = partial.join(separator)\n final = '[\\n' + indent + properties + ',\\n' + stepback + ']'\n }\n }\n\n stack.pop()\n indent = stepback\n return final\n }\n}\n", "const parse = require('./parse')\nconst stringify = require('./stringify')\n\nconst JSON5 = {\n parse,\n stringify,\n}\n\nmodule.exports = JSON5\n", "'use strict';\n\nvar hasOwn = Object.prototype.hasOwnProperty;\nvar toStr = Object.prototype.toString;\nvar defineProperty = Object.defineProperty;\nvar gOPD = Object.getOwnPropertyDescriptor;\n\nvar isArray = function isArray(arr) {\n\tif (typeof Array.isArray === 'function') {\n\t\treturn Array.isArray(arr);\n\t}\n\n\treturn toStr.call(arr) === '[object Array]';\n};\n\nvar isPlainObject = function isPlainObject(obj) {\n\tif (!obj || toStr.call(obj) !== '[object Object]') {\n\t\treturn false;\n\t}\n\n\tvar hasOwnConstructor = hasOwn.call(obj, 'constructor');\n\tvar hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');\n\t// Not own constructor property must be Object\n\tif (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {\n\t\treturn false;\n\t}\n\n\t// Own properties are enumerated firstly, so to speed up,\n\t// if last one is own, then all properties are own.\n\tvar key;\n\tfor (key in obj) { /**/ }\n\n\treturn typeof key === 'undefined' || hasOwn.call(obj, key);\n};\n\n// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target\nvar setProperty = function setProperty(target, options) {\n\tif (defineProperty && options.name === '__proto__') {\n\t\tdefineProperty(target, options.name, {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\tvalue: options.newValue,\n\t\t\twritable: true\n\t\t});\n\t} else {\n\t\ttarget[options.name] = options.newValue;\n\t}\n};\n\n// Return undefined instead of __proto__ if '__proto__' is not an own property\nvar getProperty = function getProperty(obj, name) {\n\tif (name === '__proto__') {\n\t\tif (!hasOwn.call(obj, name)) {\n\t\t\treturn void 0;\n\t\t} else if (gOPD) {\n\t\t\t// In early versions of node, obj['__proto__'] is buggy when obj has\n\t\t\t// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.\n\t\t\treturn gOPD(obj, name).value;\n\t\t}\n\t}\n\n\treturn obj[name];\n};\n\nmodule.exports = function extend() {\n\tvar options, name, src, copy, copyIsArray, clone;\n\tvar target = arguments[0];\n\tvar i = 1;\n\tvar length = arguments.length;\n\tvar deep = false;\n\n\t// Handle a deep copy situation\n\tif (typeof target === 'boolean') {\n\t\tdeep = target;\n\t\ttarget = arguments[1] || {};\n\t\t// skip the boolean and the target\n\t\ti = 2;\n\t}\n\tif (target == null || (typeof target !== 'object' && typeof target !== 'function')) {\n\t\ttarget = {};\n\t}\n\n\tfor (; i < length; ++i) {\n\t\toptions = arguments[i];\n\t\t// Only deal with non-null/undefined values\n\t\tif (options != null) {\n\t\t\t// Extend the base object\n\t\t\tfor (name in options) {\n\t\t\t\tsrc = getProperty(target, name);\n\t\t\t\tcopy = getProperty(options, name);\n\n\t\t\t\t// Prevent never-ending loop\n\t\t\t\tif (target !== copy) {\n\t\t\t\t\t// Recurse if we're merging plain objects or arrays\n\t\t\t\t\tif (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {\n\t\t\t\t\t\tif (copyIsArray) {\n\t\t\t\t\t\t\tcopyIsArray = false;\n\t\t\t\t\t\t\tclone = src && isArray(src) ? src : [];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tclone = src && isPlainObject(src) ? src : {};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Never move original objects, clone them\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: extend(deep, clone, copy) });\n\n\t\t\t\t\t// Don't bring in undefined values\n\t\t\t\t\t} else if (typeof copy !== 'undefined') {\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: copy });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return the modified object\n\treturn target;\n};\n", "{\n \"name\": \"gaxios\",\n \"version\": \"7.1.1\",\n \"description\": \"A simple common HTTP client specifically for Google APIs and services.\",\n \"main\": \"build/cjs/src/index.js\",\n \"types\": \"build/cjs/src/index.d.ts\",\n \"files\": [\n \"build/\"\n ],\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./build/esm/src/index.d.ts\",\n \"default\": \"./build/esm/src/index.js\"\n },\n \"require\": {\n \"types\": \"./build/cjs/src/index.d.ts\",\n \"default\": \"./build/cjs/src/index.js\"\n }\n }\n },\n \"scripts\": {\n \"lint\": \"gts check --no-inline-config\",\n \"test\": \"c8 mocha build/esm/test\",\n \"presystem-test\": \"npm run compile\",\n \"system-test\": \"mocha build/esm/system-test --timeout 80000\",\n \"compile\": \"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs\",\n \"fix\": \"gts fix\",\n \"prepare\": \"npm run compile\",\n \"pretest\": \"npm run compile\",\n \"webpack\": \"webpack\",\n \"prebrowser-test\": \"npm run compile\",\n \"browser-test\": \"node build/browser-test/browser-test-runner.js\",\n \"docs\": \"jsdoc -c .jsdoc.js\",\n \"docs-test\": \"linkinator docs\",\n \"predocs-test\": \"npm run docs\",\n \"samples-test\": \"cd samples/ && npm link ../ && npm test && cd ../\",\n \"prelint\": \"cd samples; npm link ../; npm install\",\n \"clean\": \"gts clean\"\n },\n \"repository\": \"googleapis/gaxios\",\n \"keywords\": [\n \"google\"\n ],\n \"engines\": {\n \"node\": \">=18\"\n },\n \"author\": \"Google, LLC\",\n \"license\": \"Apache-2.0\",\n \"devDependencies\": {\n \"@babel/plugin-proposal-private-methods\": \"^7.18.6\",\n \"@types/cors\": \"^2.8.6\",\n \"@types/express\": \"^5.0.0\",\n \"@types/extend\": \"^3.0.1\",\n \"@types/mocha\": \"^10.0.10\",\n \"@types/multiparty\": \"4.2.1\",\n \"@types/mv\": \"^2.1.0\",\n \"@types/ncp\": \"^2.0.1\",\n \"@types/node\": \"^22.0.0\",\n \"@types/sinon\": \"^17.0.0\",\n \"@types/tmp\": \"0.2.6\",\n \"assert\": \"^2.0.0\",\n \"browserify\": \"^17.0.0\",\n \"c8\": \"^10.0.0\",\n \"cors\": \"^2.8.5\",\n \"express\": \"^5.0.0\",\n \"gts\": \"^6.0.0\",\n \"is-docker\": \"^3.0.0\",\n \"jsdoc\": \"^4.0.0\",\n \"jsdoc-fresh\": \"^4.0.0\",\n \"jsdoc-region-tag\": \"^3.0.0\",\n \"karma\": \"^6.0.0\",\n \"karma-chrome-launcher\": \"^3.0.0\",\n \"karma-coverage\": \"^2.0.0\",\n \"karma-firefox-launcher\": \"^2.0.0\",\n \"karma-mocha\": \"^2.0.0\",\n \"karma-remap-coverage\": \"^0.1.5\",\n \"karma-sourcemap-loader\": \"^0.4.0\",\n \"karma-webpack\": \"^5.0.1\",\n \"linkinator\": \"^6.1.2\",\n \"mocha\": \"^11.1.0\",\n \"multiparty\": \"^4.2.1\",\n \"mv\": \"^2.1.1\",\n \"ncp\": \"^2.0.0\",\n \"nock\": \"^14.0.0-beta.13\",\n \"null-loader\": \"^4.0.0\",\n \"pack-n-play\": \"^3.0.0\",\n \"puppeteer\": \"^24.0.0\",\n \"sinon\": \"^20.0.0\",\n \"stream-browserify\": \"^3.0.0\",\n \"tmp\": \"0.2.3\",\n \"ts-loader\": \"^9.5.2\",\n \"typescript\": \"^5.8.3\",\n \"webpack\": \"^5.35.0\",\n \"webpack-cli\": \"^6.0.1\"\n },\n \"dependencies\": {\n \"extend\": \"^3.0.2\",\n \"https-proxy-agent\": \"^7.0.1\",\n \"node-fetch\": \"^3.3.2\"\n }\n}\n", null, null, null, null, "/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n", "\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(/\\s+/g, ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n", "/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n", "'use strict';\nmodule.exports = (flag, argv) => {\n\targv = argv || process.argv;\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst pos = argv.indexOf(prefix + flag);\n\tconst terminatorPos = argv.indexOf('--');\n\treturn pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);\n};\n", "'use strict';\nconst os = require('os');\nconst hasFlag = require('has-flag');\n\nconst env = process.env;\n\nlet forceColor;\nif (hasFlag('no-color') ||\n\thasFlag('no-colors') ||\n\thasFlag('color=false')) {\n\tforceColor = false;\n} else if (hasFlag('color') ||\n\thasFlag('colors') ||\n\thasFlag('color=true') ||\n\thasFlag('color=always')) {\n\tforceColor = true;\n}\nif ('FORCE_COLOR' in env) {\n\tforceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3\n\t};\n}\n\nfunction supportsColor(stream) {\n\tif (forceColor === false) {\n\t\treturn 0;\n\t}\n\n\tif (hasFlag('color=16m') ||\n\t\thasFlag('color=full') ||\n\t\thasFlag('color=truecolor')) {\n\t\treturn 3;\n\t}\n\n\tif (hasFlag('color=256')) {\n\t\treturn 2;\n\t}\n\n\tif (stream && !stream.isTTY && forceColor !== true) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor ? 1 : 0;\n\n\tif (process.platform === 'win32') {\n\t\t// Node.js 7.5.0 is the first version of Node.js to include a patch to\n\t\t// libuv that enables 256 color output on Windows. Anything earlier and it\n\t\t// won't work. However, here we target Node.js 8 at minimum as it is an LTS\n\t\t// release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows\n\t\t// release that supports 256 colors. Windows 10 build 14931 is the first release\n\t\t// that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(process.versions.node.split('.')[0]) >= 8 &&\n\t\t\tNumber(osRelease[0]) >= 10 &&\n\t\t\tNumber(osRelease[2]) >= 10586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app':\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\tcase 'Apple_Terminal':\n\t\t\t\treturn 2;\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\treturn min;\n}\n\nfunction getSupportLevel(stream) {\n\tconst level = supportsColor(stream);\n\treturn translateLevel(level);\n}\n\nmodule.exports = {\n\tsupportsColor: getSupportLevel,\n\tstdout: getSupportLevel(process.stdout),\n\tstderr: getSupportLevel(process.stderr)\n};\n", "/**\n * Module dependencies.\n */\n\nconst tty = require('tty');\nconst util = require('util');\n\n/**\n * This is the Node.js implementation of `debug()`.\n */\n\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.destroy = util.deprecate(\n\t() => {},\n\t'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'\n);\n\n/**\n * Colors.\n */\n\nexports.colors = [6, 2, 3, 4, 5, 1];\n\ntry {\n\t// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)\n\t// eslint-disable-next-line import/no-extraneous-dependencies\n\tconst supportsColor = require('supports-color');\n\n\tif (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {\n\t\texports.colors = [\n\t\t\t20,\n\t\t\t21,\n\t\t\t26,\n\t\t\t27,\n\t\t\t32,\n\t\t\t33,\n\t\t\t38,\n\t\t\t39,\n\t\t\t40,\n\t\t\t41,\n\t\t\t42,\n\t\t\t43,\n\t\t\t44,\n\t\t\t45,\n\t\t\t56,\n\t\t\t57,\n\t\t\t62,\n\t\t\t63,\n\t\t\t68,\n\t\t\t69,\n\t\t\t74,\n\t\t\t75,\n\t\t\t76,\n\t\t\t77,\n\t\t\t78,\n\t\t\t79,\n\t\t\t80,\n\t\t\t81,\n\t\t\t92,\n\t\t\t93,\n\t\t\t98,\n\t\t\t99,\n\t\t\t112,\n\t\t\t113,\n\t\t\t128,\n\t\t\t129,\n\t\t\t134,\n\t\t\t135,\n\t\t\t148,\n\t\t\t149,\n\t\t\t160,\n\t\t\t161,\n\t\t\t162,\n\t\t\t163,\n\t\t\t164,\n\t\t\t165,\n\t\t\t166,\n\t\t\t167,\n\t\t\t168,\n\t\t\t169,\n\t\t\t170,\n\t\t\t171,\n\t\t\t172,\n\t\t\t173,\n\t\t\t178,\n\t\t\t179,\n\t\t\t184,\n\t\t\t185,\n\t\t\t196,\n\t\t\t197,\n\t\t\t198,\n\t\t\t199,\n\t\t\t200,\n\t\t\t201,\n\t\t\t202,\n\t\t\t203,\n\t\t\t204,\n\t\t\t205,\n\t\t\t206,\n\t\t\t207,\n\t\t\t208,\n\t\t\t209,\n\t\t\t214,\n\t\t\t215,\n\t\t\t220,\n\t\t\t221\n\t\t];\n\t}\n} catch (error) {\n\t// Swallow - we only care if `supports-color` is available; it doesn't have to be.\n}\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(key => {\n\treturn /^debug_/i.test(key);\n}).reduce((obj, key) => {\n\t// Camel-case\n\tconst prop = key\n\t\t.substring(6)\n\t\t.toLowerCase()\n\t\t.replace(/_([a-z])/g, (_, k) => {\n\t\t\treturn k.toUpperCase();\n\t\t});\n\n\t// Coerce string value into JS value\n\tlet val = process.env[key];\n\tif (/^(yes|on|true|enabled)$/i.test(val)) {\n\t\tval = true;\n\t} else if (/^(no|off|false|disabled)$/i.test(val)) {\n\t\tval = false;\n\t} else if (val === 'null') {\n\t\tval = null;\n\t} else {\n\t\tval = Number(val);\n\t}\n\n\tobj[prop] = val;\n\treturn obj;\n}, {});\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n\treturn 'colors' in exports.inspectOpts ?\n\t\tBoolean(exports.inspectOpts.colors) :\n\t\ttty.isatty(process.stderr.fd);\n}\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\tconst {namespace: name, useColors} = this;\n\n\tif (useColors) {\n\t\tconst c = this.color;\n\t\tconst colorCode = '\\u001B[3' + (c < 8 ? c : '8;5;' + c);\n\t\tconst prefix = ` ${colorCode};1m${name} \\u001B[0m`;\n\n\t\targs[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n\t\targs.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\\u001B[0m');\n\t} else {\n\t\targs[0] = getDate() + name + ' ' + args[0];\n\t}\n}\n\nfunction getDate() {\n\tif (exports.inspectOpts.hideDate) {\n\t\treturn '';\n\t}\n\treturn new Date().toISOString() + ' ';\n}\n\n/**\n * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr.\n */\n\nfunction log(...args) {\n\treturn process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\tif (namespaces) {\n\t\tprocess.env.DEBUG = namespaces;\n\t} else {\n\t\t// If you set a process.env field to null or undefined, it gets cast to the\n\t\t// string 'null' or 'undefined'. Just delete instead.\n\t\tdelete process.env.DEBUG;\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n\treturn process.env.DEBUG;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init(debug) {\n\tdebug.inspectOpts = {};\n\n\tconst keys = Object.keys(exports.inspectOpts);\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tdebug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nformatters.o = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts)\n\t\t.split('\\n')\n\t\t.map(str => str.trim())\n\t\t.join(' ');\n};\n\n/**\n * Map %O to `util.inspect()`, allowing multiple lines if needed.\n */\n\nformatters.O = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts);\n};\n", "/**\n * Detect Electron renderer / nwjs process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {\n\tmodule.exports = require('./browser.js');\n} else {\n\tmodule.exports = require('./node.js');\n}\n", null, null, null, null, "export interface MimeBuffer extends Buffer {\n\ttype: string;\n\ttypeFull: string;\n\tcharset: string;\n}\n\n/**\n * Returns a `Buffer` instance from the given data URI `uri`.\n *\n * @param {String} uri Data URI to turn into a Buffer instance\n * @returns {Buffer} Buffer instance from Data URI\n * @api public\n */\nexport function dataUriToBuffer(uri: string): MimeBuffer {\n\tif (!/^data:/i.test(uri)) {\n\t\tthrow new TypeError(\n\t\t\t'`uri` does not appear to be a Data URI (must begin with \"data:\")'\n\t\t);\n\t}\n\n\t// strip newlines\n\turi = uri.replace(/\\r?\\n/g, '');\n\n\t// split the URI up into the \"metadata\" and the \"data\" portions\n\tconst firstComma = uri.indexOf(',');\n\tif (firstComma === -1 || firstComma <= 4) {\n\t\tthrow new TypeError('malformed data: URI');\n\t}\n\n\t// remove the \"data:\" scheme and parse the metadata\n\tconst meta = uri.substring(5, firstComma).split(';');\n\n\tlet charset = '';\n\tlet base64 = false;\n\tconst type = meta[0] || 'text/plain';\n\tlet typeFull = type;\n\tfor (let i = 1; i < meta.length; i++) {\n\t\tif (meta[i] === 'base64') {\n\t\t\tbase64 = true;\n\t\t} else if(meta[i]) {\n\t\t\ttypeFull += `;${ meta[i]}`;\n\t\t\tif (meta[i].indexOf('charset=') === 0) {\n\t\t\t\tcharset = meta[i].substring(8);\n\t\t\t}\n\t\t}\n\t}\n\t// defaults to US-ASCII only if type is not provided\n\tif (!meta[0] && !charset.length) {\n\t\ttypeFull += ';charset=US-ASCII';\n\t\tcharset = 'US-ASCII';\n\t}\n\n\t// get the encoded data portion and decode URI-encoded chars\n\tconst encoding = base64 ? 'base64' : 'ascii';\n\tconst data = unescape(uri.substring(firstComma + 1));\n\tconst buffer = Buffer.from(data, encoding) as MimeBuffer;\n\n\t// set `.type` and `.typeFull` properties to MIME type\n\tbuffer.type = type;\n\tbuffer.typeFull = typeFull;\n\n\t// set the `.charset` property\n\tbuffer.charset = charset;\n\n\treturn buffer;\n}\n\nexport default dataUriToBuffer;\n", "export function noop(): undefined {\n return undefined;\n}\n", "import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n", "import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n", "import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n", "export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n", "import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n", "/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n", "/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n", "import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n", "import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n", "import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n", "/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n", "/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n", "/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n", "import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n", "import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n", "import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n", "export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n", "import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n", "import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n", "import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n", "import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n", "import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n", "import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n", "import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n", "/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n", "import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n", "/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n", "/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n", "import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n", "import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n", "import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n", "import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n", "import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n", "import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n", "import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n", "import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n", "import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n", "import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n", "import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n", "import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n", "import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n", "import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n", "import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n", "/* c8 ignore start */\n// 64 KiB (same size chrome slice theirs blob into Uint8array's)\nconst POOL_SIZE = 65536\n\nif (!globalThis.ReadableStream) {\n // `node:stream/web` got introduced in v16.5.0 as experimental\n // and it's preferred over the polyfilled version. So we also\n // suppress the warning that gets emitted by NodeJS for using it.\n try {\n const process = require('node:process')\n const { emitWarning } = process\n try {\n process.emitWarning = () => {}\n Object.assign(globalThis, require('node:stream/web'))\n process.emitWarning = emitWarning\n } catch (error) {\n process.emitWarning = emitWarning\n throw error\n }\n } catch (error) {\n // fallback to polyfill implementation\n Object.assign(globalThis, require('web-streams-polyfill/dist/ponyfill.es2018.js'))\n }\n}\n\ntry {\n // Don't use node: prefix for this, require+node: is not supported until node v14.14\n // Only `import()` can use prefix in 12.20 and later\n const { Blob } = require('buffer')\n if (Blob && !Blob.prototype.stream) {\n Blob.prototype.stream = function name (params) {\n let position = 0\n const blob = this\n\n return new ReadableStream({\n type: 'bytes',\n async pull (ctrl) {\n const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE))\n const buffer = await chunk.arrayBuffer()\n position += buffer.byteLength\n ctrl.enqueue(new Uint8Array(buffer))\n\n if (position === blob.size) {\n ctrl.close()\n }\n }\n })\n }\n }\n} catch (error) {}\n/* c8 ignore end */\n", "/*! fetch-blob. MIT License. Jimmy W\u00E4rting */\n\n// TODO (jimmywarting): in the feature use conditional loading with top level await (requires 14.x)\n// Node has recently added whatwg stream into core\n\nimport './streams.cjs'\n\n// 64 KiB (same size chrome slice theirs blob into Uint8array's)\nconst POOL_SIZE = 65536\n\n/** @param {(Blob | Uint8Array)[]} parts */\nasync function * toIterator (parts, clone = true) {\n for (const part of parts) {\n if ('stream' in part) {\n yield * (/** @type {AsyncIterableIterator} */ (part.stream()))\n } else if (ArrayBuffer.isView(part)) {\n if (clone) {\n let position = part.byteOffset\n const end = part.byteOffset + part.byteLength\n while (position !== end) {\n const size = Math.min(end - position, POOL_SIZE)\n const chunk = part.buffer.slice(position, position + size)\n position += chunk.byteLength\n yield new Uint8Array(chunk)\n }\n } else {\n yield part\n }\n /* c8 ignore next 10 */\n } else {\n // For blobs that have arrayBuffer but no stream method (nodes buffer.Blob)\n let position = 0, b = (/** @type {Blob} */ (part))\n while (position !== b.size) {\n const chunk = b.slice(position, Math.min(b.size, position + POOL_SIZE))\n const buffer = await chunk.arrayBuffer()\n position += buffer.byteLength\n yield new Uint8Array(buffer)\n }\n }\n }\n}\n\nconst _Blob = class Blob {\n /** @type {Array.<(Blob|Uint8Array)>} */\n #parts = []\n #type = ''\n #size = 0\n #endings = 'transparent'\n\n /**\n * The Blob() constructor returns a new Blob object. The content\n * of the blob consists of the concatenation of the values given\n * in the parameter array.\n *\n * @param {*} blobParts\n * @param {{ type?: string, endings?: string }} [options]\n */\n constructor (blobParts = [], options = {}) {\n if (typeof blobParts !== 'object' || blobParts === null) {\n throw new TypeError('Failed to construct \\'Blob\\': The provided value cannot be converted to a sequence.')\n }\n\n if (typeof blobParts[Symbol.iterator] !== 'function') {\n throw new TypeError('Failed to construct \\'Blob\\': The object must have a callable @@iterator property.')\n }\n\n if (typeof options !== 'object' && typeof options !== 'function') {\n throw new TypeError('Failed to construct \\'Blob\\': parameter 2 cannot convert to dictionary.')\n }\n\n if (options === null) options = {}\n\n const encoder = new TextEncoder()\n for (const element of blobParts) {\n let part\n if (ArrayBuffer.isView(element)) {\n part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength))\n } else if (element instanceof ArrayBuffer) {\n part = new Uint8Array(element.slice(0))\n } else if (element instanceof Blob) {\n part = element\n } else {\n part = encoder.encode(`${element}`)\n }\n\n this.#size += ArrayBuffer.isView(part) ? part.byteLength : part.size\n this.#parts.push(part)\n }\n\n this.#endings = `${options.endings === undefined ? 'transparent' : options.endings}`\n const type = options.type === undefined ? '' : String(options.type)\n this.#type = /^[\\x20-\\x7E]*$/.test(type) ? type : ''\n }\n\n /**\n * The Blob interface's size property returns the\n * size of the Blob in bytes.\n */\n get size () {\n return this.#size\n }\n\n /**\n * The type property of a Blob object returns the MIME type of the file.\n */\n get type () {\n return this.#type\n }\n\n /**\n * The text() method in the Blob interface returns a Promise\n * that resolves with a string containing the contents of\n * the blob, interpreted as UTF-8.\n *\n * @return {Promise}\n */\n async text () {\n // More optimized than using this.arrayBuffer()\n // that requires twice as much ram\n const decoder = new TextDecoder()\n let str = ''\n for await (const part of toIterator(this.#parts, false)) {\n str += decoder.decode(part, { stream: true })\n }\n // Remaining\n str += decoder.decode()\n return str\n }\n\n /**\n * The arrayBuffer() method in the Blob interface returns a\n * Promise that resolves with the contents of the blob as\n * binary data contained in an ArrayBuffer.\n *\n * @return {Promise}\n */\n async arrayBuffer () {\n // Easier way... Just a unnecessary overhead\n // const view = new Uint8Array(this.size);\n // await this.stream().getReader({mode: 'byob'}).read(view);\n // return view.buffer;\n\n const data = new Uint8Array(this.size)\n let offset = 0\n for await (const chunk of toIterator(this.#parts, false)) {\n data.set(chunk, offset)\n offset += chunk.length\n }\n\n return data.buffer\n }\n\n stream () {\n const it = toIterator(this.#parts, true)\n\n return new globalThis.ReadableStream({\n // @ts-ignore\n type: 'bytes',\n async pull (ctrl) {\n const chunk = await it.next()\n chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value)\n },\n\n async cancel () {\n await it.return()\n }\n })\n }\n\n /**\n * The Blob interface's slice() method creates and returns a\n * new Blob object which contains data from a subset of the\n * blob on which it's called.\n *\n * @param {number} [start]\n * @param {number} [end]\n * @param {string} [type]\n */\n slice (start = 0, end = this.size, type = '') {\n const { size } = this\n\n let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size)\n let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size)\n\n const span = Math.max(relativeEnd - relativeStart, 0)\n const parts = this.#parts\n const blobParts = []\n let added = 0\n\n for (const part of parts) {\n // don't add the overflow to new blobParts\n if (added >= span) {\n break\n }\n\n const size = ArrayBuffer.isView(part) ? part.byteLength : part.size\n if (relativeStart && size <= relativeStart) {\n // Skip the beginning and change the relative\n // start & end position as we skip the unwanted parts\n relativeStart -= size\n relativeEnd -= size\n } else {\n let chunk\n if (ArrayBuffer.isView(part)) {\n chunk = part.subarray(relativeStart, Math.min(size, relativeEnd))\n added += chunk.byteLength\n } else {\n chunk = part.slice(relativeStart, Math.min(size, relativeEnd))\n added += chunk.size\n }\n relativeEnd -= size\n blobParts.push(chunk)\n relativeStart = 0 // All next sequential parts should start at 0\n }\n }\n\n const blob = new Blob([], { type: String(type).toLowerCase() })\n blob.#size = span\n blob.#parts = blobParts\n\n return blob\n }\n\n get [Symbol.toStringTag] () {\n return 'Blob'\n }\n\n static [Symbol.hasInstance] (object) {\n return (\n object &&\n typeof object === 'object' &&\n typeof object.constructor === 'function' &&\n (\n typeof object.stream === 'function' ||\n typeof object.arrayBuffer === 'function'\n ) &&\n /^(Blob|File)$/.test(object[Symbol.toStringTag])\n )\n }\n}\n\nObject.defineProperties(_Blob.prototype, {\n size: { enumerable: true },\n type: { enumerable: true },\n slice: { enumerable: true }\n})\n\n/** @type {typeof globalThis.Blob} */\nexport const Blob = _Blob\nexport default Blob\n", "import Blob from './index.js'\n\nconst _File = class File extends Blob {\n #lastModified = 0\n #name = ''\n\n /**\n * @param {*[]} fileBits\n * @param {string} fileName\n * @param {{lastModified?: number, type?: string}} options\n */// @ts-ignore\n constructor (fileBits, fileName, options = {}) {\n if (arguments.length < 2) {\n throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`)\n }\n super(fileBits, options)\n\n if (options === null) options = {}\n\n // Simulate WebIDL type casting for NaN value in lastModified option.\n const lastModified = options.lastModified === undefined ? Date.now() : Number(options.lastModified)\n if (!Number.isNaN(lastModified)) {\n this.#lastModified = lastModified\n }\n\n this.#name = String(fileName)\n }\n\n get name () {\n return this.#name\n }\n\n get lastModified () {\n return this.#lastModified\n }\n\n get [Symbol.toStringTag] () {\n return 'File'\n }\n\n static [Symbol.hasInstance] (object) {\n return !!object && object instanceof Blob &&\n /^(File)$/.test(object[Symbol.toStringTag])\n }\n}\n\n/** @type {typeof globalThis.File} */// @ts-ignore\nexport const File = _File\nexport default File\n", "/*! formdata-polyfill. MIT License. Jimmy W\u00E4rting */\n\nimport C from 'fetch-blob'\nimport F from 'fetch-blob/file.js'\n\nvar {toStringTag:t,iterator:i,hasInstance:h}=Symbol,\nr=Math.random,\nm='append,set,get,getAll,delete,keys,values,entries,forEach,constructor'.split(','),\nf=(a,b,c)=>(a+='',/^(Blob|File)$/.test(b && b[t])?[(c=c!==void 0?c+'':b[t]=='File'?b.name:'blob',a),b.name!==c||b[t]=='blob'?new F([b],c,b):b]:[a,b+'']),\ne=(c,f)=>(f?c:c.replace(/\\r?\\n|\\r/g,'\\r\\n')).replace(/\\n/g,'%0A').replace(/\\r/g,'%0D').replace(/\"/g,'%22'),\nx=(n, a, e)=>{if(a.lengthtypeof o[m]!='function')}\nappend(...a){x('append',arguments,2);this.#d.push(f(...a))}\ndelete(a){x('delete',arguments,1);a+='';this.#d=this.#d.filter(([b])=>b!==a)}\nget(a){x('get',arguments,1);a+='';for(var b=this.#d,l=b.length,c=0;cc[0]===a&&b.push(c[1]));return b}\nhas(a){x('has',arguments,1);a+='';return this.#d.some(b=>b[0]===a)}\nforEach(a,b){x('forEach',arguments,1);for(var [c,d]of this)a.call(b,d,c,this)}\nset(...a){x('set',arguments,2);var b=[],c=!0;a=f(...a);this.#d.forEach(d=>{d[0]===a[0]?c&&(c=!b.push(a)):b.push(d)});c&&b.push(a);this.#d=b}\n*entries(){yield*this.#d}\n*keys(){for(var[a]of this)yield a}\n*values(){for(var[,a]of this)yield a}}\n\n/** @param {FormData} F */\nexport function formDataToBlob (F,B=C){\nvar b=`${r()}${r()}`.replace(/\\./g, '').slice(-28).padStart(32, '-'),c=[],p=`--${b}\\r\\nContent-Disposition: form-data; name=\"`\nF.forEach((v,n)=>typeof v=='string'\n?c.push(p+e(n)+`\"\\r\\n\\r\\n${v.replace(/\\r(?!\\n)|(? {\n\treturn (\n\t\ttypeof object === 'object' &&\n\t\ttypeof object.append === 'function' &&\n\t\ttypeof object.delete === 'function' &&\n\t\ttypeof object.get === 'function' &&\n\t\ttypeof object.getAll === 'function' &&\n\t\ttypeof object.has === 'function' &&\n\t\ttypeof object.set === 'function' &&\n\t\ttypeof object.sort === 'function' &&\n\t\tobject[NAME] === 'URLSearchParams'\n\t);\n};\n\n/**\n * Check if `object` is a W3C `Blob` object (which `File` inherits from)\n * @param {*} object - Object to check for\n * @return {boolean}\n */\nexport const isBlob = object => {\n\treturn (\n\t\tobject &&\n\t\ttypeof object === 'object' &&\n\t\ttypeof object.arrayBuffer === 'function' &&\n\t\ttypeof object.type === 'string' &&\n\t\ttypeof object.stream === 'function' &&\n\t\ttypeof object.constructor === 'function' &&\n\t\t/^(Blob|File)$/.test(object[NAME])\n\t);\n};\n\n/**\n * Check if `obj` is an instance of AbortSignal.\n * @param {*} object - Object to check for\n * @return {boolean}\n */\nexport const isAbortSignal = object => {\n\treturn (\n\t\ttypeof object === 'object' && (\n\t\t\tobject[NAME] === 'AbortSignal' ||\n\t\t\tobject[NAME] === 'EventTarget'\n\t\t)\n\t);\n};\n\n/**\n * isDomainOrSubdomain reports whether sub is a subdomain (or exact match) of\n * the parent domain.\n *\n * Both domains must already be in canonical form.\n * @param {string|URL} original\n * @param {string|URL} destination\n */\nexport const isDomainOrSubdomain = (destination, original) => {\n\tconst orig = new URL(original).hostname;\n\tconst dest = new URL(destination).hostname;\n\n\treturn orig === dest || orig.endsWith(`.${dest}`);\n};\n\n/**\n * isSameProtocol reports whether the two provided URLs use the same protocol.\n *\n * Both domains must already be in canonical form.\n * @param {string|URL} original\n * @param {string|URL} destination\n */\nexport const isSameProtocol = (destination, original) => {\n\tconst orig = new URL(original).protocol;\n\tconst dest = new URL(destination).protocol;\n\n\treturn orig === dest;\n};\n", "/*! node-domexception. MIT License. Jimmy W\u00E4rting */\n\nif (!globalThis.DOMException) {\n try {\n const { MessageChannel } = require('worker_threads'),\n port = new MessageChannel().port1,\n ab = new ArrayBuffer()\n port.postMessage(ab, [ab, ab])\n } catch (err) {\n err.constructor.name === 'DOMException' && (\n globalThis.DOMException = err.constructor\n )\n }\n}\n\nmodule.exports = globalThis.DOMException\n", "import { statSync, createReadStream, promises as fs } from 'node:fs'\nimport { basename } from 'node:path'\nimport DOMException from 'node-domexception'\n\nimport File from './file.js'\nimport Blob from './index.js'\n\nconst { stat } = fs\n\n/**\n * @param {string} path filepath on the disk\n * @param {string} [type] mimetype to use\n */\nconst blobFromSync = (path, type) => fromBlob(statSync(path), path, type)\n\n/**\n * @param {string} path filepath on the disk\n * @param {string} [type] mimetype to use\n * @returns {Promise}\n */\nconst blobFrom = (path, type) => stat(path).then(stat => fromBlob(stat, path, type))\n\n/**\n * @param {string} path filepath on the disk\n * @param {string} [type] mimetype to use\n * @returns {Promise}\n */\nconst fileFrom = (path, type) => stat(path).then(stat => fromFile(stat, path, type))\n\n/**\n * @param {string} path filepath on the disk\n * @param {string} [type] mimetype to use\n */\nconst fileFromSync = (path, type) => fromFile(statSync(path), path, type)\n\n// @ts-ignore\nconst fromBlob = (stat, path, type = '') => new Blob([new BlobDataItem({\n path,\n size: stat.size,\n lastModified: stat.mtimeMs,\n start: 0\n})], { type })\n\n// @ts-ignore\nconst fromFile = (stat, path, type = '') => new File([new BlobDataItem({\n path,\n size: stat.size,\n lastModified: stat.mtimeMs,\n start: 0\n})], basename(path), { type, lastModified: stat.mtimeMs })\n\n/**\n * This is a blob backed up by a file on the disk\n * with minium requirement. Its wrapped around a Blob as a blobPart\n * so you have no direct access to this.\n *\n * @private\n */\nclass BlobDataItem {\n #path\n #start\n\n constructor (options) {\n this.#path = options.path\n this.#start = options.start\n this.size = options.size\n this.lastModified = options.lastModified\n }\n\n /**\n * Slicing arguments is first validated and formatted\n * to not be out of range by Blob.prototype.slice\n */\n slice (start, end) {\n return new BlobDataItem({\n path: this.#path,\n lastModified: this.lastModified,\n size: end - start,\n start: this.#start + start\n })\n }\n\n async * stream () {\n const { mtimeMs } = await stat(this.#path)\n if (mtimeMs > this.lastModified) {\n throw new DOMException('The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.', 'NotReadableError')\n }\n yield * createReadStream(this.#path, {\n start: this.#start,\n end: this.#start + this.size - 1\n })\n }\n\n get [Symbol.toStringTag] () {\n return 'Blob'\n }\n}\n\nexport default blobFromSync\nexport { File, Blob, blobFrom, blobFromSync, fileFrom, fileFromSync }\n", "import {File} from 'fetch-blob/from.js';\nimport {FormData} from 'formdata-polyfill/esm.min.js';\n\nlet s = 0;\nconst S = {\n\tSTART_BOUNDARY: s++,\n\tHEADER_FIELD_START: s++,\n\tHEADER_FIELD: s++,\n\tHEADER_VALUE_START: s++,\n\tHEADER_VALUE: s++,\n\tHEADER_VALUE_ALMOST_DONE: s++,\n\tHEADERS_ALMOST_DONE: s++,\n\tPART_DATA_START: s++,\n\tPART_DATA: s++,\n\tEND: s++\n};\n\nlet f = 1;\nconst F = {\n\tPART_BOUNDARY: f,\n\tLAST_BOUNDARY: f *= 2\n};\n\nconst LF = 10;\nconst CR = 13;\nconst SPACE = 32;\nconst HYPHEN = 45;\nconst COLON = 58;\nconst A = 97;\nconst Z = 122;\n\nconst lower = c => c | 0x20;\n\nconst noop = () => {};\n\nclass MultipartParser {\n\t/**\n\t * @param {string} boundary\n\t */\n\tconstructor(boundary) {\n\t\tthis.index = 0;\n\t\tthis.flags = 0;\n\n\t\tthis.onHeaderEnd = noop;\n\t\tthis.onHeaderField = noop;\n\t\tthis.onHeadersEnd = noop;\n\t\tthis.onHeaderValue = noop;\n\t\tthis.onPartBegin = noop;\n\t\tthis.onPartData = noop;\n\t\tthis.onPartEnd = noop;\n\n\t\tthis.boundaryChars = {};\n\n\t\tboundary = '\\r\\n--' + boundary;\n\t\tconst ui8a = new Uint8Array(boundary.length);\n\t\tfor (let i = 0; i < boundary.length; i++) {\n\t\t\tui8a[i] = boundary.charCodeAt(i);\n\t\t\tthis.boundaryChars[ui8a[i]] = true;\n\t\t}\n\n\t\tthis.boundary = ui8a;\n\t\tthis.lookbehind = new Uint8Array(this.boundary.length + 8);\n\t\tthis.state = S.START_BOUNDARY;\n\t}\n\n\t/**\n\t * @param {Uint8Array} data\n\t */\n\twrite(data) {\n\t\tlet i = 0;\n\t\tconst length_ = data.length;\n\t\tlet previousIndex = this.index;\n\t\tlet {lookbehind, boundary, boundaryChars, index, state, flags} = this;\n\t\tconst boundaryLength = this.boundary.length;\n\t\tconst boundaryEnd = boundaryLength - 1;\n\t\tconst bufferLength = data.length;\n\t\tlet c;\n\t\tlet cl;\n\n\t\tconst mark = name => {\n\t\t\tthis[name + 'Mark'] = i;\n\t\t};\n\n\t\tconst clear = name => {\n\t\t\tdelete this[name + 'Mark'];\n\t\t};\n\n\t\tconst callback = (callbackSymbol, start, end, ui8a) => {\n\t\t\tif (start === undefined || start !== end) {\n\t\t\t\tthis[callbackSymbol](ui8a && ui8a.subarray(start, end));\n\t\t\t}\n\t\t};\n\n\t\tconst dataCallback = (name, clear) => {\n\t\t\tconst markSymbol = name + 'Mark';\n\t\t\tif (!(markSymbol in this)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (clear) {\n\t\t\t\tcallback(name, this[markSymbol], i, data);\n\t\t\t\tdelete this[markSymbol];\n\t\t\t} else {\n\t\t\t\tcallback(name, this[markSymbol], data.length, data);\n\t\t\t\tthis[markSymbol] = 0;\n\t\t\t}\n\t\t};\n\n\t\tfor (i = 0; i < length_; i++) {\n\t\t\tc = data[i];\n\n\t\t\tswitch (state) {\n\t\t\t\tcase S.START_BOUNDARY:\n\t\t\t\t\tif (index === boundary.length - 2) {\n\t\t\t\t\t\tif (c === HYPHEN) {\n\t\t\t\t\t\t\tflags |= F.LAST_BOUNDARY;\n\t\t\t\t\t\t} else if (c !== CR) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else if (index - 1 === boundary.length - 2) {\n\t\t\t\t\t\tif (flags & F.LAST_BOUNDARY && c === HYPHEN) {\n\t\t\t\t\t\t\tstate = S.END;\n\t\t\t\t\t\t\tflags = 0;\n\t\t\t\t\t\t} else if (!(flags & F.LAST_BOUNDARY) && c === LF) {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t\tcallback('onPartBegin');\n\t\t\t\t\t\t\tstate = S.HEADER_FIELD_START;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c !== boundary[index + 2]) {\n\t\t\t\t\t\tindex = -2;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c === boundary[index + 2]) {\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADER_FIELD_START:\n\t\t\t\t\tstate = S.HEADER_FIELD;\n\t\t\t\t\tmark('onHeaderField');\n\t\t\t\t\tindex = 0;\n\t\t\t\t\t// falls through\n\t\t\t\tcase S.HEADER_FIELD:\n\t\t\t\t\tif (c === CR) {\n\t\t\t\t\t\tclear('onHeaderField');\n\t\t\t\t\t\tstate = S.HEADERS_ALMOST_DONE;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tindex++;\n\t\t\t\t\tif (c === HYPHEN) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c === COLON) {\n\t\t\t\t\t\tif (index === 1) {\n\t\t\t\t\t\t\t// empty header field\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdataCallback('onHeaderField', true);\n\t\t\t\t\t\tstate = S.HEADER_VALUE_START;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcl = lower(c);\n\t\t\t\t\tif (cl < A || cl > Z) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADER_VALUE_START:\n\t\t\t\t\tif (c === SPACE) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tmark('onHeaderValue');\n\t\t\t\t\tstate = S.HEADER_VALUE;\n\t\t\t\t\t// falls through\n\t\t\t\tcase S.HEADER_VALUE:\n\t\t\t\t\tif (c === CR) {\n\t\t\t\t\t\tdataCallback('onHeaderValue', true);\n\t\t\t\t\t\tcallback('onHeaderEnd');\n\t\t\t\t\t\tstate = S.HEADER_VALUE_ALMOST_DONE;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADER_VALUE_ALMOST_DONE:\n\t\t\t\t\tif (c !== LF) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tstate = S.HEADER_FIELD_START;\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADERS_ALMOST_DONE:\n\t\t\t\t\tif (c !== LF) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tcallback('onHeadersEnd');\n\t\t\t\t\tstate = S.PART_DATA_START;\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.PART_DATA_START:\n\t\t\t\t\tstate = S.PART_DATA;\n\t\t\t\t\tmark('onPartData');\n\t\t\t\t\t// falls through\n\t\t\t\tcase S.PART_DATA:\n\t\t\t\t\tpreviousIndex = index;\n\n\t\t\t\t\tif (index === 0) {\n\t\t\t\t\t\t// boyer-moore derrived algorithm to safely skip non-boundary data\n\t\t\t\t\t\ti += boundaryEnd;\n\t\t\t\t\t\twhile (i < bufferLength && !(data[i] in boundaryChars)) {\n\t\t\t\t\t\t\ti += boundaryLength;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ti -= boundaryEnd;\n\t\t\t\t\t\tc = data[i];\n\t\t\t\t\t}\n\n\t\t\t\t\tif (index < boundary.length) {\n\t\t\t\t\t\tif (boundary[index] === c) {\n\t\t\t\t\t\t\tif (index === 0) {\n\t\t\t\t\t\t\t\tdataCallback('onPartData', true);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tindex++;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (index === boundary.length) {\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t\tif (c === CR) {\n\t\t\t\t\t\t\t// CR = part boundary\n\t\t\t\t\t\t\tflags |= F.PART_BOUNDARY;\n\t\t\t\t\t\t} else if (c === HYPHEN) {\n\t\t\t\t\t\t\t// HYPHEN = end boundary\n\t\t\t\t\t\t\tflags |= F.LAST_BOUNDARY;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (index - 1 === boundary.length) {\n\t\t\t\t\t\tif (flags & F.PART_BOUNDARY) {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t\tif (c === LF) {\n\t\t\t\t\t\t\t\t// unset the PART_BOUNDARY flag\n\t\t\t\t\t\t\t\tflags &= ~F.PART_BOUNDARY;\n\t\t\t\t\t\t\t\tcallback('onPartEnd');\n\t\t\t\t\t\t\t\tcallback('onPartBegin');\n\t\t\t\t\t\t\t\tstate = S.HEADER_FIELD_START;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (flags & F.LAST_BOUNDARY) {\n\t\t\t\t\t\t\tif (c === HYPHEN) {\n\t\t\t\t\t\t\t\tcallback('onPartEnd');\n\t\t\t\t\t\t\t\tstate = S.END;\n\t\t\t\t\t\t\t\tflags = 0;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (index > 0) {\n\t\t\t\t\t\t// when matching a possible boundary, keep a lookbehind reference\n\t\t\t\t\t\t// in case it turns out to be a false lead\n\t\t\t\t\t\tlookbehind[index - 1] = c;\n\t\t\t\t\t} else if (previousIndex > 0) {\n\t\t\t\t\t\t// if our boundary turned out to be rubbish, the captured lookbehind\n\t\t\t\t\t\t// belongs to partData\n\t\t\t\t\t\tconst _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength);\n\t\t\t\t\t\tcallback('onPartData', 0, previousIndex, _lookbehind);\n\t\t\t\t\t\tpreviousIndex = 0;\n\t\t\t\t\t\tmark('onPartData');\n\n\t\t\t\t\t\t// reconsider the current character even so it interrupted the sequence\n\t\t\t\t\t\t// it could be the beginning of a new sequence\n\t\t\t\t\t\ti--;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.END:\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Error(`Unexpected state entered: ${state}`);\n\t\t\t}\n\t\t}\n\n\t\tdataCallback('onHeaderField');\n\t\tdataCallback('onHeaderValue');\n\t\tdataCallback('onPartData');\n\n\t\t// Update properties for the next call\n\t\tthis.index = index;\n\t\tthis.state = state;\n\t\tthis.flags = flags;\n\t}\n\n\tend() {\n\t\tif ((this.state === S.HEADER_FIELD_START && this.index === 0) ||\n\t\t\t(this.state === S.PART_DATA && this.index === this.boundary.length)) {\n\t\t\tthis.onPartEnd();\n\t\t} else if (this.state !== S.END) {\n\t\t\tthrow new Error('MultipartParser.end(): stream ended unexpectedly');\n\t\t}\n\t}\n}\n\nfunction _fileName(headerValue) {\n\t// matches either a quoted-string or a token (RFC 2616 section 19.5.1)\n\tconst m = headerValue.match(/\\bfilename=(\"(.*?)\"|([^()<>@,;:\\\\\"/[\\]?={}\\s\\t]+))($|;\\s)/i);\n\tif (!m) {\n\t\treturn;\n\t}\n\n\tconst match = m[2] || m[3] || '';\n\tlet filename = match.slice(match.lastIndexOf('\\\\') + 1);\n\tfilename = filename.replace(/%22/g, '\"');\n\tfilename = filename.replace(/&#(\\d{4});/g, (m, code) => {\n\t\treturn String.fromCharCode(code);\n\t});\n\treturn filename;\n}\n\nexport async function toFormData(Body, ct) {\n\tif (!/multipart/i.test(ct)) {\n\t\tthrow new TypeError('Failed to fetch');\n\t}\n\n\tconst m = ct.match(/boundary=(?:\"([^\"]+)\"|([^;]+))/i);\n\n\tif (!m) {\n\t\tthrow new TypeError('no or bad content-type header, no multipart boundary');\n\t}\n\n\tconst parser = new MultipartParser(m[1] || m[2]);\n\n\tlet headerField;\n\tlet headerValue;\n\tlet entryValue;\n\tlet entryName;\n\tlet contentType;\n\tlet filename;\n\tconst entryChunks = [];\n\tconst formData = new FormData();\n\n\tconst onPartData = ui8a => {\n\t\tentryValue += decoder.decode(ui8a, {stream: true});\n\t};\n\n\tconst appendToFile = ui8a => {\n\t\tentryChunks.push(ui8a);\n\t};\n\n\tconst appendFileToFormData = () => {\n\t\tconst file = new File(entryChunks, filename, {type: contentType});\n\t\tformData.append(entryName, file);\n\t};\n\n\tconst appendEntryToFormData = () => {\n\t\tformData.append(entryName, entryValue);\n\t};\n\n\tconst decoder = new TextDecoder('utf-8');\n\tdecoder.decode();\n\n\tparser.onPartBegin = function () {\n\t\tparser.onPartData = onPartData;\n\t\tparser.onPartEnd = appendEntryToFormData;\n\n\t\theaderField = '';\n\t\theaderValue = '';\n\t\tentryValue = '';\n\t\tentryName = '';\n\t\tcontentType = '';\n\t\tfilename = null;\n\t\tentryChunks.length = 0;\n\t};\n\n\tparser.onHeaderField = function (ui8a) {\n\t\theaderField += decoder.decode(ui8a, {stream: true});\n\t};\n\n\tparser.onHeaderValue = function (ui8a) {\n\t\theaderValue += decoder.decode(ui8a, {stream: true});\n\t};\n\n\tparser.onHeaderEnd = function () {\n\t\theaderValue += decoder.decode();\n\t\theaderField = headerField.toLowerCase();\n\n\t\tif (headerField === 'content-disposition') {\n\t\t\t// matches either a quoted-string or a token (RFC 2616 section 19.5.1)\n\t\t\tconst m = headerValue.match(/\\bname=(\"([^\"]*)\"|([^()<>@,;:\\\\\"/[\\]?={}\\s\\t]+))/i);\n\n\t\t\tif (m) {\n\t\t\t\tentryName = m[2] || m[3] || '';\n\t\t\t}\n\n\t\t\tfilename = _fileName(headerValue);\n\n\t\t\tif (filename) {\n\t\t\t\tparser.onPartData = appendToFile;\n\t\t\t\tparser.onPartEnd = appendFileToFormData;\n\t\t\t}\n\t\t} else if (headerField === 'content-type') {\n\t\t\tcontentType = headerValue;\n\t\t}\n\n\t\theaderValue = '';\n\t\theaderField = '';\n\t};\n\n\tfor await (const chunk of Body) {\n\t\tparser.write(chunk);\n\t}\n\n\tparser.end();\n\n\treturn formData;\n}\n", "\n/**\n * Body.js\n *\n * Body interface provides common methods for Request and Response\n */\n\nimport Stream, {PassThrough} from 'node:stream';\nimport {types, deprecate, promisify} from 'node:util';\nimport {Buffer} from 'node:buffer';\n\nimport Blob from 'fetch-blob';\nimport {FormData, formDataToBlob} from 'formdata-polyfill/esm.min.js';\n\nimport {FetchError} from './errors/fetch-error.js';\nimport {FetchBaseError} from './errors/base.js';\nimport {isBlob, isURLSearchParameters} from './utils/is.js';\n\nconst pipeline = promisify(Stream.pipeline);\nconst INTERNALS = Symbol('Body internals');\n\n/**\n * Body mixin\n *\n * Ref: https://fetch.spec.whatwg.org/#body\n *\n * @param Stream body Readable stream\n * @param Object opts Response options\n * @return Void\n */\nexport default class Body {\n\tconstructor(body, {\n\t\tsize = 0\n\t} = {}) {\n\t\tlet boundary = null;\n\n\t\tif (body === null) {\n\t\t\t// Body is undefined or null\n\t\t\tbody = null;\n\t\t} else if (isURLSearchParameters(body)) {\n\t\t\t// Body is a URLSearchParams\n\t\t\tbody = Buffer.from(body.toString());\n\t\t} else if (isBlob(body)) {\n\t\t\t// Body is blob\n\t\t} else if (Buffer.isBuffer(body)) {\n\t\t\t// Body is Buffer\n\t\t} else if (types.isAnyArrayBuffer(body)) {\n\t\t\t// Body is ArrayBuffer\n\t\t\tbody = Buffer.from(body);\n\t\t} else if (ArrayBuffer.isView(body)) {\n\t\t\t// Body is ArrayBufferView\n\t\t\tbody = Buffer.from(body.buffer, body.byteOffset, body.byteLength);\n\t\t} else if (body instanceof Stream) {\n\t\t\t// Body is stream\n\t\t} else if (body instanceof FormData) {\n\t\t\t// Body is FormData\n\t\t\tbody = formDataToBlob(body);\n\t\t\tboundary = body.type.split('=')[1];\n\t\t} else {\n\t\t\t// None of the above\n\t\t\t// coerce to string then buffer\n\t\t\tbody = Buffer.from(String(body));\n\t\t}\n\n\t\tlet stream = body;\n\n\t\tif (Buffer.isBuffer(body)) {\n\t\t\tstream = Stream.Readable.from(body);\n\t\t} else if (isBlob(body)) {\n\t\t\tstream = Stream.Readable.from(body.stream());\n\t\t}\n\n\t\tthis[INTERNALS] = {\n\t\t\tbody,\n\t\t\tstream,\n\t\t\tboundary,\n\t\t\tdisturbed: false,\n\t\t\terror: null\n\t\t};\n\t\tthis.size = size;\n\n\t\tif (body instanceof Stream) {\n\t\t\tbody.on('error', error_ => {\n\t\t\t\tconst error = error_ instanceof FetchBaseError ?\n\t\t\t\t\terror_ :\n\t\t\t\t\tnew FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, 'system', error_);\n\t\t\t\tthis[INTERNALS].error = error;\n\t\t\t});\n\t\t}\n\t}\n\n\tget body() {\n\t\treturn this[INTERNALS].stream;\n\t}\n\n\tget bodyUsed() {\n\t\treturn this[INTERNALS].disturbed;\n\t}\n\n\t/**\n\t * Decode response as ArrayBuffer\n\t *\n\t * @return Promise\n\t */\n\tasync arrayBuffer() {\n\t\tconst {buffer, byteOffset, byteLength} = await consumeBody(this);\n\t\treturn buffer.slice(byteOffset, byteOffset + byteLength);\n\t}\n\n\tasync formData() {\n\t\tconst ct = this.headers.get('content-type');\n\n\t\tif (ct.startsWith('application/x-www-form-urlencoded')) {\n\t\t\tconst formData = new FormData();\n\t\t\tconst parameters = new URLSearchParams(await this.text());\n\n\t\t\tfor (const [name, value] of parameters) {\n\t\t\t\tformData.append(name, value);\n\t\t\t}\n\n\t\t\treturn formData;\n\t\t}\n\n\t\tconst {toFormData} = await import('./utils/multipart-parser.js');\n\t\treturn toFormData(this.body, ct);\n\t}\n\n\t/**\n\t * Return raw response as Blob\n\t *\n\t * @return Promise\n\t */\n\tasync blob() {\n\t\tconst ct = (this.headers && this.headers.get('content-type')) || (this[INTERNALS].body && this[INTERNALS].body.type) || '';\n\t\tconst buf = await this.arrayBuffer();\n\n\t\treturn new Blob([buf], {\n\t\t\ttype: ct\n\t\t});\n\t}\n\n\t/**\n\t * Decode response as json\n\t *\n\t * @return Promise\n\t */\n\tasync json() {\n\t\tconst text = await this.text();\n\t\treturn JSON.parse(text);\n\t}\n\n\t/**\n\t * Decode response as text\n\t *\n\t * @return Promise\n\t */\n\tasync text() {\n\t\tconst buffer = await consumeBody(this);\n\t\treturn new TextDecoder().decode(buffer);\n\t}\n\n\t/**\n\t * Decode response as buffer (non-spec api)\n\t *\n\t * @return Promise\n\t */\n\tbuffer() {\n\t\treturn consumeBody(this);\n\t}\n}\n\nBody.prototype.buffer = deprecate(Body.prototype.buffer, 'Please use \\'response.arrayBuffer()\\' instead of \\'response.buffer()\\'', 'node-fetch#buffer');\n\n// In browsers, all properties are enumerable.\nObject.defineProperties(Body.prototype, {\n\tbody: {enumerable: true},\n\tbodyUsed: {enumerable: true},\n\tarrayBuffer: {enumerable: true},\n\tblob: {enumerable: true},\n\tjson: {enumerable: true},\n\ttext: {enumerable: true},\n\tdata: {get: deprecate(() => {},\n\t\t'data doesn\\'t exist, use json(), text(), arrayBuffer(), or body instead',\n\t\t'https://github.com/node-fetch/node-fetch/issues/1000 (response)')}\n});\n\n/**\n * Consume and convert an entire Body to a Buffer.\n *\n * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body\n *\n * @return Promise\n */\nasync function consumeBody(data) {\n\tif (data[INTERNALS].disturbed) {\n\t\tthrow new TypeError(`body used already for: ${data.url}`);\n\t}\n\n\tdata[INTERNALS].disturbed = true;\n\n\tif (data[INTERNALS].error) {\n\t\tthrow data[INTERNALS].error;\n\t}\n\n\tconst {body} = data;\n\n\t// Body is null\n\tif (body === null) {\n\t\treturn Buffer.alloc(0);\n\t}\n\n\t/* c8 ignore next 3 */\n\tif (!(body instanceof Stream)) {\n\t\treturn Buffer.alloc(0);\n\t}\n\n\t// Body is stream\n\t// get ready to actually consume the body\n\tconst accum = [];\n\tlet accumBytes = 0;\n\n\ttry {\n\t\tfor await (const chunk of body) {\n\t\t\tif (data.size > 0 && accumBytes + chunk.length > data.size) {\n\t\t\t\tconst error = new FetchError(`content size at ${data.url} over limit: ${data.size}`, 'max-size');\n\t\t\t\tbody.destroy(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t}\n\t} catch (error) {\n\t\tconst error_ = error instanceof FetchBaseError ? error : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error.message}`, 'system', error);\n\t\tthrow error_;\n\t}\n\n\tif (body.readableEnded === true || body._readableState.ended === true) {\n\t\ttry {\n\t\t\tif (accum.every(c => typeof c === 'string')) {\n\t\t\t\treturn Buffer.from(accum.join(''));\n\t\t\t}\n\n\t\t\treturn Buffer.concat(accum, accumBytes);\n\t\t} catch (error) {\n\t\t\tthrow new FetchError(`Could not create Buffer from response body for ${data.url}: ${error.message}`, 'system', error);\n\t\t}\n\t} else {\n\t\tthrow new FetchError(`Premature close of server response while trying to fetch ${data.url}`);\n\t}\n}\n\n/**\n * Clone body given Res/Req instance\n *\n * @param Mixed instance Response or Request instance\n * @param String highWaterMark highWaterMark for both PassThrough body streams\n * @return Mixed\n */\nexport const clone = (instance, highWaterMark) => {\n\tlet p1;\n\tlet p2;\n\tlet {body} = instance[INTERNALS];\n\n\t// Don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// Check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif ((body instanceof Stream) && (typeof body.getBoundary !== 'function')) {\n\t\t// Tee instance body\n\t\tp1 = new PassThrough({highWaterMark});\n\t\tp2 = new PassThrough({highWaterMark});\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// Set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].stream = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n};\n\nconst getNonSpecFormDataBoundary = deprecate(\n\tbody => body.getBoundary(),\n\t'form-data doesn\\'t follow the spec and requires special treatment. Use alternative package',\n\t'https://github.com/node-fetch/node-fetch/issues/1167'\n);\n\n/**\n * Performs the operation \"extract a `Content-Type` value from |object|\" as\n * specified in the specification:\n * https://fetch.spec.whatwg.org/#concept-bodyinit-extract\n *\n * This function assumes that instance.body is present.\n *\n * @param {any} body Any options.body input\n * @returns {string | null}\n */\nexport const extractContentType = (body, request) => {\n\t// Body is null or undefined\n\tif (body === null) {\n\t\treturn null;\n\t}\n\n\t// Body is string\n\tif (typeof body === 'string') {\n\t\treturn 'text/plain;charset=UTF-8';\n\t}\n\n\t// Body is a URLSearchParams\n\tif (isURLSearchParameters(body)) {\n\t\treturn 'application/x-www-form-urlencoded;charset=UTF-8';\n\t}\n\n\t// Body is blob\n\tif (isBlob(body)) {\n\t\treturn body.type || null;\n\t}\n\n\t// Body is a Buffer (Buffer, ArrayBuffer or ArrayBufferView)\n\tif (Buffer.isBuffer(body) || types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) {\n\t\treturn null;\n\t}\n\n\tif (body instanceof FormData) {\n\t\treturn `multipart/form-data; boundary=${request[INTERNALS].boundary}`;\n\t}\n\n\t// Detect form data input from form-data module\n\tif (body && typeof body.getBoundary === 'function') {\n\t\treturn `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`;\n\t}\n\n\t// Body is stream - can't really do much about this\n\tif (body instanceof Stream) {\n\t\treturn null;\n\t}\n\n\t// Body constructor defaults other things to string\n\treturn 'text/plain;charset=UTF-8';\n};\n\n/**\n * The Fetch Standard treats this as if \"total bytes\" is a property on the body.\n * For us, we have to explicitly get it with a function.\n *\n * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes\n *\n * @param {any} obj.body Body object from the Body instance.\n * @returns {number | null}\n */\nexport const getTotalBytes = request => {\n\tconst {body} = request[INTERNALS];\n\n\t// Body is null or undefined\n\tif (body === null) {\n\t\treturn 0;\n\t}\n\n\t// Body is Blob\n\tif (isBlob(body)) {\n\t\treturn body.size;\n\t}\n\n\t// Body is Buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn body.length;\n\t}\n\n\t// Detect form data input from form-data module\n\tif (body && typeof body.getLengthSync === 'function') {\n\t\treturn body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null;\n\t}\n\n\t// Body is stream\n\treturn null;\n};\n\n/**\n * Write a Body to a Node.js WritableStream (e.g. http.Request) object.\n *\n * @param {Stream.Writable} dest The stream to write to.\n * @param obj.body Body object from the Body instance.\n * @returns {Promise}\n */\nexport const writeToStream = async (dest, {body}) => {\n\tif (body === null) {\n\t\t// Body is null\n\t\tdest.end();\n\t} else {\n\t\t// Body is stream\n\t\tawait pipeline(body, dest);\n\t}\n};\n", "/**\n * Headers.js\n *\n * Headers class offers convenient helpers\n */\n\nimport {types} from 'node:util';\nimport http from 'node:http';\n\n/* c8 ignore next 9 */\nconst validateHeaderName = typeof http.validateHeaderName === 'function' ?\n\thttp.validateHeaderName :\n\tname => {\n\t\tif (!/^[\\^`\\-\\w!#$%&'*+.|~]+$/.test(name)) {\n\t\t\tconst error = new TypeError(`Header name must be a valid HTTP token [${name}]`);\n\t\t\tObject.defineProperty(error, 'code', {value: 'ERR_INVALID_HTTP_TOKEN'});\n\t\t\tthrow error;\n\t\t}\n\t};\n\n/* c8 ignore next 9 */\nconst validateHeaderValue = typeof http.validateHeaderValue === 'function' ?\n\thttp.validateHeaderValue :\n\t(name, value) => {\n\t\tif (/[^\\t\\u0020-\\u007E\\u0080-\\u00FF]/.test(value)) {\n\t\t\tconst error = new TypeError(`Invalid character in header content [\"${name}\"]`);\n\t\t\tObject.defineProperty(error, 'code', {value: 'ERR_INVALID_CHAR'});\n\t\t\tthrow error;\n\t\t}\n\t};\n\n/**\n * @typedef {Headers | Record | Iterable | Iterable>} HeadersInit\n */\n\n/**\n * This Fetch API interface allows you to perform various actions on HTTP request and response headers.\n * These actions include retrieving, setting, adding to, and removing.\n * A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs.\n * You can add to this using methods like append() (see Examples.)\n * In all methods of this interface, header names are matched by case-insensitive byte sequence.\n *\n */\nexport default class Headers extends URLSearchParams {\n\t/**\n\t * Headers class\n\t *\n\t * @constructor\n\t * @param {HeadersInit} [init] - Response headers\n\t */\n\tconstructor(init) {\n\t\t// Validate and normalize init object in [name, value(s)][]\n\t\t/** @type {string[][]} */\n\t\tlet result = [];\n\t\tif (init instanceof Headers) {\n\t\t\tconst raw = init.raw();\n\t\t\tfor (const [name, values] of Object.entries(raw)) {\n\t\t\t\tresult.push(...values.map(value => [name, value]));\n\t\t\t}\n\t\t} else if (init == null) { // eslint-disable-line no-eq-null, eqeqeq\n\t\t\t// No op\n\t\t} else if (typeof init === 'object' && !types.isBoxedPrimitive(init)) {\n\t\t\tconst method = init[Symbol.iterator];\n\t\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\t\tif (method == null) {\n\t\t\t\t// Record\n\t\t\t\tresult.push(...Object.entries(init));\n\t\t\t} else {\n\t\t\t\tif (typeof method !== 'function') {\n\t\t\t\t\tthrow new TypeError('Header pairs must be iterable');\n\t\t\t\t}\n\n\t\t\t\t// Sequence>\n\t\t\t\t// Note: per spec we have to first exhaust the lists then process them\n\t\t\t\tresult = [...init]\n\t\t\t\t\t.map(pair => {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\ttypeof pair !== 'object' || types.isBoxedPrimitive(pair)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthrow new TypeError('Each header pair must be an iterable object');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn [...pair];\n\t\t\t\t\t}).map(pair => {\n\t\t\t\t\t\tif (pair.length !== 2) {\n\t\t\t\t\t\t\tthrow new TypeError('Each header pair must be a name/value tuple');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn [...pair];\n\t\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new TypeError('Failed to construct \\'Headers\\': The provided value is not of type \\'(sequence> or record)');\n\t\t}\n\n\t\t// Validate and lowercase\n\t\tresult =\n\t\t\tresult.length > 0 ?\n\t\t\t\tresult.map(([name, value]) => {\n\t\t\t\t\tvalidateHeaderName(name);\n\t\t\t\t\tvalidateHeaderValue(name, String(value));\n\t\t\t\t\treturn [String(name).toLowerCase(), String(value)];\n\t\t\t\t}) :\n\t\t\t\tundefined;\n\n\t\tsuper(result);\n\n\t\t// Returning a Proxy that will lowercase key names, validate parameters and sort keys\n\t\t// eslint-disable-next-line no-constructor-return\n\t\treturn new Proxy(this, {\n\t\t\tget(target, p, receiver) {\n\t\t\t\tswitch (p) {\n\t\t\t\t\tcase 'append':\n\t\t\t\t\tcase 'set':\n\t\t\t\t\t\treturn (name, value) => {\n\t\t\t\t\t\t\tvalidateHeaderName(name);\n\t\t\t\t\t\t\tvalidateHeaderValue(name, String(value));\n\t\t\t\t\t\t\treturn URLSearchParams.prototype[p].call(\n\t\t\t\t\t\t\t\ttarget,\n\t\t\t\t\t\t\t\tString(name).toLowerCase(),\n\t\t\t\t\t\t\t\tString(value)\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t};\n\n\t\t\t\t\tcase 'delete':\n\t\t\t\t\tcase 'has':\n\t\t\t\t\tcase 'getAll':\n\t\t\t\t\t\treturn name => {\n\t\t\t\t\t\t\tvalidateHeaderName(name);\n\t\t\t\t\t\t\treturn URLSearchParams.prototype[p].call(\n\t\t\t\t\t\t\t\ttarget,\n\t\t\t\t\t\t\t\tString(name).toLowerCase()\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t};\n\n\t\t\t\t\tcase 'keys':\n\t\t\t\t\t\treturn () => {\n\t\t\t\t\t\t\ttarget.sort();\n\t\t\t\t\t\t\treturn new Set(URLSearchParams.prototype.keys.call(target)).keys();\n\t\t\t\t\t\t};\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn Reflect.get(target, p, receiver);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t/* c8 ignore next */\n\t}\n\n\tget [Symbol.toStringTag]() {\n\t\treturn this.constructor.name;\n\t}\n\n\ttoString() {\n\t\treturn Object.prototype.toString.call(this);\n\t}\n\n\tget(name) {\n\t\tconst values = this.getAll(name);\n\t\tif (values.length === 0) {\n\t\t\treturn null;\n\t\t}\n\n\t\tlet value = values.join(', ');\n\t\tif (/^content-encoding$/i.test(name)) {\n\t\t\tvalue = value.toLowerCase();\n\t\t}\n\n\t\treturn value;\n\t}\n\n\tforEach(callback, thisArg = undefined) {\n\t\tfor (const name of this.keys()) {\n\t\t\tReflect.apply(callback, thisArg, [this.get(name), name, this]);\n\t\t}\n\t}\n\n\t* values() {\n\t\tfor (const name of this.keys()) {\n\t\t\tyield this.get(name);\n\t\t}\n\t}\n\n\t/**\n\t * @type {() => IterableIterator<[string, string]>}\n\t */\n\t* entries() {\n\t\tfor (const name of this.keys()) {\n\t\t\tyield [name, this.get(name)];\n\t\t}\n\t}\n\n\t[Symbol.iterator]() {\n\t\treturn this.entries();\n\t}\n\n\t/**\n\t * Node-fetch non-spec method\n\t * returning all headers and their values as array\n\t * @returns {Record}\n\t */\n\traw() {\n\t\treturn [...this.keys()].reduce((result, key) => {\n\t\t\tresult[key] = this.getAll(key);\n\t\t\treturn result;\n\t\t}, {});\n\t}\n\n\t/**\n\t * For better console.log(headers) and also to convert Headers into Node.js Request compatible format\n\t */\n\t[Symbol.for('nodejs.util.inspect.custom')]() {\n\t\treturn [...this.keys()].reduce((result, key) => {\n\t\t\tconst values = this.getAll(key);\n\t\t\t// Http.request() only supports string as Host header.\n\t\t\t// This hack makes specifying custom Host header possible.\n\t\t\tif (key === 'host') {\n\t\t\t\tresult[key] = values[0];\n\t\t\t} else {\n\t\t\t\tresult[key] = values.length > 1 ? values : values[0];\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}, {});\n\t}\n}\n\n/**\n * Re-shaping object for Web IDL tests\n * Only need to do it for overridden methods\n */\nObject.defineProperties(\n\tHeaders.prototype,\n\t['get', 'entries', 'forEach', 'values'].reduce((result, property) => {\n\t\tresult[property] = {enumerable: true};\n\t\treturn result;\n\t}, {})\n);\n\n/**\n * Create a Headers object from an http.IncomingMessage.rawHeaders, ignoring those that do\n * not conform to HTTP grammar productions.\n * @param {import('http').IncomingMessage['rawHeaders']} headers\n */\nexport function fromRawHeaders(headers = []) {\n\treturn new Headers(\n\t\theaders\n\t\t\t// Split into pairs\n\t\t\t.reduce((result, value, index, array) => {\n\t\t\t\tif (index % 2 === 0) {\n\t\t\t\t\tresult.push(array.slice(index, index + 2));\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t}, [])\n\t\t\t.filter(([name, value]) => {\n\t\t\t\ttry {\n\t\t\t\t\tvalidateHeaderName(name);\n\t\t\t\t\tvalidateHeaderValue(name, String(value));\n\t\t\t\t\treturn true;\n\t\t\t\t} catch {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t})\n\n\t);\n}\n", "const redirectStatus = new Set([301, 302, 303, 307, 308]);\n\n/**\n * Redirect code matching\n *\n * @param {number} code - Status code\n * @return {boolean}\n */\nexport const isRedirect = code => {\n\treturn redirectStatus.has(code);\n};\n", "/**\n * Response.js\n *\n * Response class provides content decoding\n */\n\nimport Headers from './headers.js';\nimport Body, {clone, extractContentType} from './body.js';\nimport {isRedirect} from './utils/is-redirect.js';\n\nconst INTERNALS = Symbol('Response internals');\n\n/**\n * Response class\n *\n * Ref: https://fetch.spec.whatwg.org/#response-class\n *\n * @param Stream body Readable stream\n * @param Object opts Response options\n * @return Void\n */\nexport default class Response extends Body {\n\tconstructor(body = null, options = {}) {\n\t\tsuper(body, options);\n\n\t\t// eslint-disable-next-line no-eq-null, eqeqeq, no-negated-condition\n\t\tconst status = options.status != null ? options.status : 200;\n\n\t\tconst headers = new Headers(options.headers);\n\n\t\tif (body !== null && !headers.has('Content-Type')) {\n\t\t\tconst contentType = extractContentType(body, this);\n\t\t\tif (contentType) {\n\t\t\t\theaders.append('Content-Type', contentType);\n\t\t\t}\n\t\t}\n\n\t\tthis[INTERNALS] = {\n\t\t\ttype: 'default',\n\t\t\turl: options.url,\n\t\t\tstatus,\n\t\t\tstatusText: options.statusText || '',\n\t\t\theaders,\n\t\t\tcounter: options.counter,\n\t\t\thighWaterMark: options.highWaterMark\n\t\t};\n\t}\n\n\tget type() {\n\t\treturn this[INTERNALS].type;\n\t}\n\n\tget url() {\n\t\treturn this[INTERNALS].url || '';\n\t}\n\n\tget status() {\n\t\treturn this[INTERNALS].status;\n\t}\n\n\t/**\n\t * Convenience property representing if the request ended normally\n\t */\n\tget ok() {\n\t\treturn this[INTERNALS].status >= 200 && this[INTERNALS].status < 300;\n\t}\n\n\tget redirected() {\n\t\treturn this[INTERNALS].counter > 0;\n\t}\n\n\tget statusText() {\n\t\treturn this[INTERNALS].statusText;\n\t}\n\n\tget headers() {\n\t\treturn this[INTERNALS].headers;\n\t}\n\n\tget highWaterMark() {\n\t\treturn this[INTERNALS].highWaterMark;\n\t}\n\n\t/**\n\t * Clone this response\n\t *\n\t * @return Response\n\t */\n\tclone() {\n\t\treturn new Response(clone(this, this.highWaterMark), {\n\t\t\ttype: this.type,\n\t\t\turl: this.url,\n\t\t\tstatus: this.status,\n\t\t\tstatusText: this.statusText,\n\t\t\theaders: this.headers,\n\t\t\tok: this.ok,\n\t\t\tredirected: this.redirected,\n\t\t\tsize: this.size,\n\t\t\thighWaterMark: this.highWaterMark\n\t\t});\n\t}\n\n\t/**\n\t * @param {string} url The URL that the new response is to originate from.\n\t * @param {number} status An optional status code for the response (e.g., 302.)\n\t * @returns {Response} A Response object.\n\t */\n\tstatic redirect(url, status = 302) {\n\t\tif (!isRedirect(status)) {\n\t\t\tthrow new RangeError('Failed to execute \"redirect\" on \"response\": Invalid status code');\n\t\t}\n\n\t\treturn new Response(null, {\n\t\t\theaders: {\n\t\t\t\tlocation: new URL(url).toString()\n\t\t\t},\n\t\t\tstatus\n\t\t});\n\t}\n\n\tstatic error() {\n\t\tconst response = new Response(null, {status: 0, statusText: ''});\n\t\tresponse[INTERNALS].type = 'error';\n\t\treturn response;\n\t}\n\n\tstatic json(data = undefined, init = {}) {\n\t\tconst body = JSON.stringify(data);\n\n\t\tif (body === undefined) {\n\t\t\tthrow new TypeError('data is not JSON serializable');\n\t\t}\n\n\t\tconst headers = new Headers(init && init.headers);\n\n\t\tif (!headers.has('content-type')) {\n\t\t\theaders.set('content-type', 'application/json');\n\t\t}\n\n\t\treturn new Response(body, {\n\t\t\t...init,\n\t\t\theaders\n\t\t});\n\t}\n\n\tget [Symbol.toStringTag]() {\n\t\treturn 'Response';\n\t}\n}\n\nObject.defineProperties(Response.prototype, {\n\ttype: {enumerable: true},\n\turl: {enumerable: true},\n\tstatus: {enumerable: true},\n\tok: {enumerable: true},\n\tredirected: {enumerable: true},\n\tstatusText: {enumerable: true},\n\theaders: {enumerable: true},\n\tclone: {enumerable: true}\n});\n", "export const getSearch = parsedURL => {\n\tif (parsedURL.search) {\n\t\treturn parsedURL.search;\n\t}\n\n\tconst lastOffset = parsedURL.href.length - 1;\n\tconst hash = parsedURL.hash || (parsedURL.href[lastOffset] === '#' ? '#' : '');\n\treturn parsedURL.href[lastOffset - hash.length] === '?' ? '?' : '';\n};\n", "import {isIP} from 'node:net';\n\n/**\n * @external URL\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/URL|URL}\n */\n\n/**\n * @module utils/referrer\n * @private\n */\n\n/**\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#strip-url|Referrer Policy \u00A78.4. Strip url for use as a referrer}\n * @param {string} URL\n * @param {boolean} [originOnly=false]\n */\nexport function stripURLForUseAsAReferrer(url, originOnly = false) {\n\t// 1. If url is null, return no referrer.\n\tif (url == null) { // eslint-disable-line no-eq-null, eqeqeq\n\t\treturn 'no-referrer';\n\t}\n\n\turl = new URL(url);\n\n\t// 2. If url's scheme is a local scheme, then return no referrer.\n\tif (/^(about|blob|data):$/.test(url.protocol)) {\n\t\treturn 'no-referrer';\n\t}\n\n\t// 3. Set url's username to the empty string.\n\turl.username = '';\n\n\t// 4. Set url's password to null.\n\t// Note: `null` appears to be a mistake as this actually results in the password being `\"null\"`.\n\turl.password = '';\n\n\t// 5. Set url's fragment to null.\n\t// Note: `null` appears to be a mistake as this actually results in the fragment being `\"#null\"`.\n\turl.hash = '';\n\n\t// 6. If the origin-only flag is true, then:\n\tif (originOnly) {\n\t\t// 6.1. Set url's path to null.\n\t\t// Note: `null` appears to be a mistake as this actually results in the path being `\"/null\"`.\n\t\turl.pathname = '';\n\n\t\t// 6.2. Set url's query to null.\n\t\t// Note: `null` appears to be a mistake as this actually results in the query being `\"?null\"`.\n\t\turl.search = '';\n\t}\n\n\t// 7. Return url.\n\treturn url;\n}\n\n/**\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#enumdef-referrerpolicy|enum ReferrerPolicy}\n */\nexport const ReferrerPolicy = new Set([\n\t'',\n\t'no-referrer',\n\t'no-referrer-when-downgrade',\n\t'same-origin',\n\t'origin',\n\t'strict-origin',\n\t'origin-when-cross-origin',\n\t'strict-origin-when-cross-origin',\n\t'unsafe-url'\n]);\n\n/**\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#default-referrer-policy|default referrer policy}\n */\nexport const DEFAULT_REFERRER_POLICY = 'strict-origin-when-cross-origin';\n\n/**\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#referrer-policies|Referrer Policy \u00A73. Referrer Policies}\n * @param {string} referrerPolicy\n * @returns {string} referrerPolicy\n */\nexport function validateReferrerPolicy(referrerPolicy) {\n\tif (!ReferrerPolicy.has(referrerPolicy)) {\n\t\tthrow new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);\n\t}\n\n\treturn referrerPolicy;\n}\n\n/**\n * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy|Referrer Policy \u00A73.2. Is origin potentially trustworthy?}\n * @param {external:URL} url\n * @returns `true`: \"Potentially Trustworthy\", `false`: \"Not Trustworthy\"\n */\nexport function isOriginPotentiallyTrustworthy(url) {\n\t// 1. If origin is an opaque origin, return \"Not Trustworthy\".\n\t// Not applicable\n\n\t// 2. Assert: origin is a tuple origin.\n\t// Not for implementations\n\n\t// 3. If origin's scheme is either \"https\" or \"wss\", return \"Potentially Trustworthy\".\n\tif (/^(http|ws)s:$/.test(url.protocol)) {\n\t\treturn true;\n\t}\n\n\t// 4. If origin's host component matches one of the CIDR notations 127.0.0.0/8 or ::1/128 [RFC4632], return \"Potentially Trustworthy\".\n\tconst hostIp = url.host.replace(/(^\\[)|(]$)/g, '');\n\tconst hostIPVersion = isIP(hostIp);\n\n\tif (hostIPVersion === 4 && /^127\\./.test(hostIp)) {\n\t\treturn true;\n\t}\n\n\tif (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) {\n\t\treturn true;\n\t}\n\n\t// 5. If origin's host component is \"localhost\" or falls within \".localhost\", and the user agent conforms to the name resolution rules in [let-localhost-be-localhost], return \"Potentially Trustworthy\".\n\t// We are returning FALSE here because we cannot ensure conformance to\n\t// let-localhost-be-loalhost (https://tools.ietf.org/html/draft-west-let-localhost-be-localhost)\n\tif (url.host === 'localhost' || url.host.endsWith('.localhost')) {\n\t\treturn false;\n\t}\n\n\t// 6. If origin's scheme component is file, return \"Potentially Trustworthy\".\n\tif (url.protocol === 'file:') {\n\t\treturn true;\n\t}\n\n\t// 7. If origin's scheme component is one which the user agent considers to be authenticated, return \"Potentially Trustworthy\".\n\t// Not supported\n\n\t// 8. If origin has been configured as a trustworthy origin, return \"Potentially Trustworthy\".\n\t// Not supported\n\n\t// 9. Return \"Not Trustworthy\".\n\treturn false;\n}\n\n/**\n * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-url-trustworthy|Referrer Policy \u00A73.3. Is url potentially trustworthy?}\n * @param {external:URL} url\n * @returns `true`: \"Potentially Trustworthy\", `false`: \"Not Trustworthy\"\n */\nexport function isUrlPotentiallyTrustworthy(url) {\n\t// 1. If url is \"about:blank\" or \"about:srcdoc\", return \"Potentially Trustworthy\".\n\tif (/^about:(blank|srcdoc)$/.test(url)) {\n\t\treturn true;\n\t}\n\n\t// 2. If url's scheme is \"data\", return \"Potentially Trustworthy\".\n\tif (url.protocol === 'data:') {\n\t\treturn true;\n\t}\n\n\t// Note: The origin of blob: and filesystem: URLs is the origin of the context in which they were\n\t// created. Therefore, blobs created in a trustworthy origin will themselves be potentially\n\t// trustworthy.\n\tif (/^(blob|filesystem):$/.test(url.protocol)) {\n\t\treturn true;\n\t}\n\n\t// 3. Return the result of executing \u00A73.2 Is origin potentially trustworthy? on url's origin.\n\treturn isOriginPotentiallyTrustworthy(url);\n}\n\n/**\n * Modifies the referrerURL to enforce any extra security policy considerations.\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy \u00A78.3. Determine request's Referrer}, step 7\n * @callback module:utils/referrer~referrerURLCallback\n * @param {external:URL} referrerURL\n * @returns {external:URL} modified referrerURL\n */\n\n/**\n * Modifies the referrerOrigin to enforce any extra security policy considerations.\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy \u00A78.3. Determine request's Referrer}, step 7\n * @callback module:utils/referrer~referrerOriginCallback\n * @param {external:URL} referrerOrigin\n * @returns {external:URL} modified referrerOrigin\n */\n\n/**\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy \u00A78.3. Determine request's Referrer}\n * @param {Request} request\n * @param {object} o\n * @param {module:utils/referrer~referrerURLCallback} o.referrerURLCallback\n * @param {module:utils/referrer~referrerOriginCallback} o.referrerOriginCallback\n * @returns {external:URL} Request's referrer\n */\nexport function determineRequestsReferrer(request, {referrerURLCallback, referrerOriginCallback} = {}) {\n\t// There are 2 notes in the specification about invalid pre-conditions. We return null, here, for\n\t// these cases:\n\t// > Note: If request's referrer is \"no-referrer\", Fetch will not call into this algorithm.\n\t// > Note: If request's referrer policy is the empty string, Fetch will not call into this\n\t// > algorithm.\n\tif (request.referrer === 'no-referrer' || request.referrerPolicy === '') {\n\t\treturn null;\n\t}\n\n\t// 1. Let policy be request's associated referrer policy.\n\tconst policy = request.referrerPolicy;\n\n\t// 2. Let environment be request's client.\n\t// not applicable to node.js\n\n\t// 3. Switch on request's referrer:\n\tif (request.referrer === 'about:client') {\n\t\treturn 'no-referrer';\n\t}\n\n\t// \"a URL\": Let referrerSource be request's referrer.\n\tconst referrerSource = request.referrer;\n\n\t// 4. Let request's referrerURL be the result of stripping referrerSource for use as a referrer.\n\tlet referrerURL = stripURLForUseAsAReferrer(referrerSource);\n\n\t// 5. Let referrerOrigin be the result of stripping referrerSource for use as a referrer, with the\n\t// origin-only flag set to true.\n\tlet referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true);\n\n\t// 6. If the result of serializing referrerURL is a string whose length is greater than 4096, set\n\t// referrerURL to referrerOrigin.\n\tif (referrerURL.toString().length > 4096) {\n\t\treferrerURL = referrerOrigin;\n\t}\n\n\t// 7. The user agent MAY alter referrerURL or referrerOrigin at this point to enforce arbitrary\n\t// policy considerations in the interests of minimizing data leakage. For example, the user\n\t// agent could strip the URL down to an origin, modify its host, replace it with an empty\n\t// string, etc.\n\tif (referrerURLCallback) {\n\t\treferrerURL = referrerURLCallback(referrerURL);\n\t}\n\n\tif (referrerOriginCallback) {\n\t\treferrerOrigin = referrerOriginCallback(referrerOrigin);\n\t}\n\n\t// 8.Execute the statements corresponding to the value of policy:\n\tconst currentURL = new URL(request.url);\n\n\tswitch (policy) {\n\t\tcase 'no-referrer':\n\t\t\treturn 'no-referrer';\n\n\t\tcase 'origin':\n\t\t\treturn referrerOrigin;\n\n\t\tcase 'unsafe-url':\n\t\t\treturn referrerURL;\n\n\t\tcase 'strict-origin':\n\t\t\t// 1. If referrerURL is a potentially trustworthy URL and request's current URL is not a\n\t\t\t// potentially trustworthy URL, then return no referrer.\n\t\t\tif (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {\n\t\t\t\treturn 'no-referrer';\n\t\t\t}\n\n\t\t\t// 2. Return referrerOrigin.\n\t\t\treturn referrerOrigin.toString();\n\n\t\tcase 'strict-origin-when-cross-origin':\n\t\t\t// 1. If the origin of referrerURL and the origin of request's current URL are the same, then\n\t\t\t// return referrerURL.\n\t\t\tif (referrerURL.origin === currentURL.origin) {\n\t\t\t\treturn referrerURL;\n\t\t\t}\n\n\t\t\t// 2. If referrerURL is a potentially trustworthy URL and request's current URL is not a\n\t\t\t// potentially trustworthy URL, then return no referrer.\n\t\t\tif (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {\n\t\t\t\treturn 'no-referrer';\n\t\t\t}\n\n\t\t\t// 3. Return referrerOrigin.\n\t\t\treturn referrerOrigin;\n\n\t\tcase 'same-origin':\n\t\t\t// 1. If the origin of referrerURL and the origin of request's current URL are the same, then\n\t\t\t// return referrerURL.\n\t\t\tif (referrerURL.origin === currentURL.origin) {\n\t\t\t\treturn referrerURL;\n\t\t\t}\n\n\t\t\t// 2. Return no referrer.\n\t\t\treturn 'no-referrer';\n\n\t\tcase 'origin-when-cross-origin':\n\t\t\t// 1. If the origin of referrerURL and the origin of request's current URL are the same, then\n\t\t\t// return referrerURL.\n\t\t\tif (referrerURL.origin === currentURL.origin) {\n\t\t\t\treturn referrerURL;\n\t\t\t}\n\n\t\t\t// Return referrerOrigin.\n\t\t\treturn referrerOrigin;\n\n\t\tcase 'no-referrer-when-downgrade':\n\t\t\t// 1. If referrerURL is a potentially trustworthy URL and request's current URL is not a\n\t\t\t// potentially trustworthy URL, then return no referrer.\n\t\t\tif (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {\n\t\t\t\treturn 'no-referrer';\n\t\t\t}\n\n\t\t\t// 2. Return referrerURL.\n\t\t\treturn referrerURL;\n\n\t\tdefault:\n\t\t\tthrow new TypeError(`Invalid referrerPolicy: ${policy}`);\n\t}\n}\n\n/**\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#parse-referrer-policy-from-header|Referrer Policy \u00A78.1. Parse a referrer policy from a Referrer-Policy header}\n * @param {Headers} headers Response headers\n * @returns {string} policy\n */\nexport function parseReferrerPolicyFromHeader(headers) {\n\t// 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy`\n\t// and response\u2019s header list.\n\tconst policyTokens = (headers.get('referrer-policy') || '').split(/[,\\s]+/);\n\n\t// 2. Let policy be the empty string.\n\tlet policy = '';\n\n\t// 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty\n\t// string, then set policy to token.\n\t// Note: This algorithm loops over multiple policy values to allow deployment of new policy\n\t// values with fallbacks for older user agents, as described in \u00A7 11.1 Unknown Policy Values.\n\tfor (const token of policyTokens) {\n\t\tif (token && ReferrerPolicy.has(token)) {\n\t\t\tpolicy = token;\n\t\t}\n\t}\n\n\t// 4. Return policy.\n\treturn policy;\n}\n", "/**\n * Request.js\n *\n * Request class contains server only options\n *\n * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/.\n */\n\nimport {format as formatUrl} from 'node:url';\nimport {deprecate} from 'node:util';\nimport Headers from './headers.js';\nimport Body, {clone, extractContentType, getTotalBytes} from './body.js';\nimport {isAbortSignal} from './utils/is.js';\nimport {getSearch} from './utils/get-search.js';\nimport {\n\tvalidateReferrerPolicy, determineRequestsReferrer, DEFAULT_REFERRER_POLICY\n} from './utils/referrer.js';\n\nconst INTERNALS = Symbol('Request internals');\n\n/**\n * Check if `obj` is an instance of Request.\n *\n * @param {*} object\n * @return {boolean}\n */\nconst isRequest = object => {\n\treturn (\n\t\ttypeof object === 'object' &&\n\t\ttypeof object[INTERNALS] === 'object'\n\t);\n};\n\nconst doBadDataWarn = deprecate(() => {},\n\t'.data is not a valid RequestInit property, use .body instead',\n\t'https://github.com/node-fetch/node-fetch/issues/1000 (request)');\n\n/**\n * Request class\n *\n * Ref: https://fetch.spec.whatwg.org/#request-class\n *\n * @param Mixed input Url or Request instance\n * @param Object init Custom options\n * @return Void\n */\nexport default class Request extends Body {\n\tconstructor(input, init = {}) {\n\t\tlet parsedURL;\n\n\t\t// Normalize input and force URL to be encoded as UTF-8 (https://github.com/node-fetch/node-fetch/issues/245)\n\t\tif (isRequest(input)) {\n\t\t\tparsedURL = new URL(input.url);\n\t\t} else {\n\t\t\tparsedURL = new URL(input);\n\t\t\tinput = {};\n\t\t}\n\n\t\tif (parsedURL.username !== '' || parsedURL.password !== '') {\n\t\t\tthrow new TypeError(`${parsedURL} is an url with embedded credentials.`);\n\t\t}\n\n\t\tlet method = init.method || input.method || 'GET';\n\t\tif (/^(delete|get|head|options|post|put)$/i.test(method)) {\n\t\t\tmethod = method.toUpperCase();\n\t\t}\n\n\t\tif (!isRequest(init) && 'data' in init) {\n\t\t\tdoBadDataWarn();\n\t\t}\n\n\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\tif ((init.body != null || (isRequest(input) && input.body !== null)) &&\n\t\t\t(method === 'GET' || method === 'HEAD')) {\n\t\t\tthrow new TypeError('Request with GET/HEAD method cannot have body');\n\t\t}\n\n\t\tconst inputBody = init.body ?\n\t\t\tinit.body :\n\t\t\t(isRequest(input) && input.body !== null ?\n\t\t\t\tclone(input) :\n\t\t\t\tnull);\n\n\t\tsuper(inputBody, {\n\t\t\tsize: init.size || input.size || 0\n\t\t});\n\n\t\tconst headers = new Headers(init.headers || input.headers || {});\n\n\t\tif (inputBody !== null && !headers.has('Content-Type')) {\n\t\t\tconst contentType = extractContentType(inputBody, this);\n\t\t\tif (contentType) {\n\t\t\t\theaders.set('Content-Type', contentType);\n\t\t\t}\n\t\t}\n\n\t\tlet signal = isRequest(input) ?\n\t\t\tinput.signal :\n\t\t\tnull;\n\t\tif ('signal' in init) {\n\t\t\tsignal = init.signal;\n\t\t}\n\n\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\tif (signal != null && !isAbortSignal(signal)) {\n\t\t\tthrow new TypeError('Expected signal to be an instanceof AbortSignal or EventTarget');\n\t\t}\n\n\t\t// \u00A75.4, Request constructor steps, step 15.1\n\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\tlet referrer = init.referrer == null ? input.referrer : init.referrer;\n\t\tif (referrer === '') {\n\t\t\t// \u00A75.4, Request constructor steps, step 15.2\n\t\t\treferrer = 'no-referrer';\n\t\t} else if (referrer) {\n\t\t\t// \u00A75.4, Request constructor steps, step 15.3.1, 15.3.2\n\t\t\tconst parsedReferrer = new URL(referrer);\n\t\t\t// \u00A75.4, Request constructor steps, step 15.3.3, 15.3.4\n\t\t\treferrer = /^about:(\\/\\/)?client$/.test(parsedReferrer) ? 'client' : parsedReferrer;\n\t\t} else {\n\t\t\treferrer = undefined;\n\t\t}\n\n\t\tthis[INTERNALS] = {\n\t\t\tmethod,\n\t\t\tredirect: init.redirect || input.redirect || 'follow',\n\t\t\theaders,\n\t\t\tparsedURL,\n\t\t\tsignal,\n\t\t\treferrer\n\t\t};\n\n\t\t// Node-fetch-only options\n\t\tthis.follow = init.follow === undefined ? (input.follow === undefined ? 20 : input.follow) : init.follow;\n\t\tthis.compress = init.compress === undefined ? (input.compress === undefined ? true : input.compress) : init.compress;\n\t\tthis.counter = init.counter || input.counter || 0;\n\t\tthis.agent = init.agent || input.agent;\n\t\tthis.highWaterMark = init.highWaterMark || input.highWaterMark || 16384;\n\t\tthis.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false;\n\n\t\t// \u00A75.4, Request constructor steps, step 16.\n\t\t// Default is empty string per https://fetch.spec.whatwg.org/#concept-request-referrer-policy\n\t\tthis.referrerPolicy = init.referrerPolicy || input.referrerPolicy || '';\n\t}\n\n\t/** @returns {string} */\n\tget method() {\n\t\treturn this[INTERNALS].method;\n\t}\n\n\t/** @returns {string} */\n\tget url() {\n\t\treturn formatUrl(this[INTERNALS].parsedURL);\n\t}\n\n\t/** @returns {Headers} */\n\tget headers() {\n\t\treturn this[INTERNALS].headers;\n\t}\n\n\tget redirect() {\n\t\treturn this[INTERNALS].redirect;\n\t}\n\n\t/** @returns {AbortSignal} */\n\tget signal() {\n\t\treturn this[INTERNALS].signal;\n\t}\n\n\t// https://fetch.spec.whatwg.org/#dom-request-referrer\n\tget referrer() {\n\t\tif (this[INTERNALS].referrer === 'no-referrer') {\n\t\t\treturn '';\n\t\t}\n\n\t\tif (this[INTERNALS].referrer === 'client') {\n\t\t\treturn 'about:client';\n\t\t}\n\n\t\tif (this[INTERNALS].referrer) {\n\t\t\treturn this[INTERNALS].referrer.toString();\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tget referrerPolicy() {\n\t\treturn this[INTERNALS].referrerPolicy;\n\t}\n\n\tset referrerPolicy(referrerPolicy) {\n\t\tthis[INTERNALS].referrerPolicy = validateReferrerPolicy(referrerPolicy);\n\t}\n\n\t/**\n\t * Clone this request\n\t *\n\t * @return Request\n\t */\n\tclone() {\n\t\treturn new Request(this);\n\t}\n\n\tget [Symbol.toStringTag]() {\n\t\treturn 'Request';\n\t}\n}\n\nObject.defineProperties(Request.prototype, {\n\tmethod: {enumerable: true},\n\turl: {enumerable: true},\n\theaders: {enumerable: true},\n\tredirect: {enumerable: true},\n\tclone: {enumerable: true},\n\tsignal: {enumerable: true},\n\treferrer: {enumerable: true},\n\treferrerPolicy: {enumerable: true}\n});\n\n/**\n * Convert a Request to Node.js http request options.\n *\n * @param {Request} request - A Request instance\n * @return The options object to be passed to http.request\n */\nexport const getNodeRequestOptions = request => {\n\tconst {parsedURL} = request[INTERNALS];\n\tconst headers = new Headers(request[INTERNALS].headers);\n\n\t// Fetch step 1.3\n\tif (!headers.has('Accept')) {\n\t\theaders.set('Accept', '*/*');\n\t}\n\n\t// HTTP-network-or-cache fetch steps 2.4-2.7\n\tlet contentLengthValue = null;\n\tif (request.body === null && /^(post|put)$/i.test(request.method)) {\n\t\tcontentLengthValue = '0';\n\t}\n\n\tif (request.body !== null) {\n\t\tconst totalBytes = getTotalBytes(request);\n\t\t// Set Content-Length if totalBytes is a number (that is not NaN)\n\t\tif (typeof totalBytes === 'number' && !Number.isNaN(totalBytes)) {\n\t\t\tcontentLengthValue = String(totalBytes);\n\t\t}\n\t}\n\n\tif (contentLengthValue) {\n\t\theaders.set('Content-Length', contentLengthValue);\n\t}\n\n\t// 4.1. Main fetch, step 2.6\n\t// > If request's referrer policy is the empty string, then set request's referrer policy to the\n\t// > default referrer policy.\n\tif (request.referrerPolicy === '') {\n\t\trequest.referrerPolicy = DEFAULT_REFERRER_POLICY;\n\t}\n\n\t// 4.1. Main fetch, step 2.7\n\t// > If request's referrer is not \"no-referrer\", set request's referrer to the result of invoking\n\t// > determine request's referrer.\n\tif (request.referrer && request.referrer !== 'no-referrer') {\n\t\trequest[INTERNALS].referrer = determineRequestsReferrer(request);\n\t} else {\n\t\trequest[INTERNALS].referrer = 'no-referrer';\n\t}\n\n\t// 4.5. HTTP-network-or-cache fetch, step 6.9\n\t// > If httpRequest's referrer is a URL, then append `Referer`/httpRequest's referrer, serialized\n\t// > and isomorphic encoded, to httpRequest's header list.\n\tif (request[INTERNALS].referrer instanceof URL) {\n\t\theaders.set('Referer', request.referrer);\n\t}\n\n\t// HTTP-network-or-cache fetch step 2.11\n\tif (!headers.has('User-Agent')) {\n\t\theaders.set('User-Agent', 'node-fetch');\n\t}\n\n\t// HTTP-network-or-cache fetch step 2.15\n\tif (request.compress && !headers.has('Accept-Encoding')) {\n\t\theaders.set('Accept-Encoding', 'gzip, deflate, br');\n\t}\n\n\tlet {agent} = request;\n\tif (typeof agent === 'function') {\n\t\tagent = agent(parsedURL);\n\t}\n\n\t// HTTP-network fetch step 4.2\n\t// chunked encoding is handled by Node.js\n\n\tconst search = getSearch(parsedURL);\n\n\t// Pass the full URL directly to request(), but overwrite the following\n\t// options:\n\tconst options = {\n\t\t// Overwrite search to retain trailing ? (issue #776)\n\t\tpath: parsedURL.pathname + search,\n\t\t// The following options are not expressed in the URL\n\t\tmethod: request.method,\n\t\theaders: headers[Symbol.for('nodejs.util.inspect.custom')](),\n\t\tinsecureHTTPParser: request.insecureHTTPParser,\n\t\tagent\n\t};\n\n\treturn {\n\t\t/** @type {URL} */\n\t\tparsedURL,\n\t\toptions\n\t};\n};\n", "import {FetchBaseError} from './base.js';\n\n/**\n * AbortError interface for cancelled requests\n */\nexport class AbortError extends FetchBaseError {\n\tconstructor(message, type = 'aborted') {\n\t\tsuper(message, type);\n\t}\n}\n", "/**\n * Index.js\n *\n * a request API compatible with window.fetch\n *\n * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/.\n */\n\nimport http from 'node:http';\nimport https from 'node:https';\nimport zlib from 'node:zlib';\nimport Stream, {PassThrough, pipeline as pump} from 'node:stream';\nimport {Buffer} from 'node:buffer';\n\nimport dataUriToBuffer from 'data-uri-to-buffer';\n\nimport {writeToStream, clone} from './body.js';\nimport Response from './response.js';\nimport Headers, {fromRawHeaders} from './headers.js';\nimport Request, {getNodeRequestOptions} from './request.js';\nimport {FetchError} from './errors/fetch-error.js';\nimport {AbortError} from './errors/abort-error.js';\nimport {isRedirect} from './utils/is-redirect.js';\nimport {FormData} from 'formdata-polyfill/esm.min.js';\nimport {isDomainOrSubdomain, isSameProtocol} from './utils/is.js';\nimport {parseReferrerPolicyFromHeader} from './utils/referrer.js';\nimport {\n\tBlob,\n\tFile,\n\tfileFromSync,\n\tfileFrom,\n\tblobFromSync,\n\tblobFrom\n} from 'fetch-blob/from.js';\n\nexport {FormData, Headers, Request, Response, FetchError, AbortError, isRedirect};\nexport {Blob, File, fileFromSync, fileFrom, blobFromSync, blobFrom};\n\nconst supportedSchemas = new Set(['data:', 'http:', 'https:']);\n\n/**\n * Fetch function\n *\n * @param {string | URL | import('./request').default} url - Absolute url or Request instance\n * @param {*} [options_] - Fetch options\n * @return {Promise}\n */\nexport default async function fetch(url, options_) {\n\treturn new Promise((resolve, reject) => {\n\t\t// Build request object\n\t\tconst request = new Request(url, options_);\n\t\tconst {parsedURL, options} = getNodeRequestOptions(request);\n\t\tif (!supportedSchemas.has(parsedURL.protocol)) {\n\t\t\tthrow new TypeError(`node-fetch cannot load ${url}. URL scheme \"${parsedURL.protocol.replace(/:$/, '')}\" is not supported.`);\n\t\t}\n\n\t\tif (parsedURL.protocol === 'data:') {\n\t\t\tconst data = dataUriToBuffer(request.url);\n\t\t\tconst response = new Response(data, {headers: {'Content-Type': data.typeFull}});\n\t\t\tresolve(response);\n\t\t\treturn;\n\t\t}\n\n\t\t// Wrap http.request into fetch\n\t\tconst send = (parsedURL.protocol === 'https:' ? https : http).request;\n\t\tconst {signal} = request;\n\t\tlet response = null;\n\n\t\tconst abort = () => {\n\t\t\tconst error = new AbortError('The operation was aborted.');\n\t\t\treject(error);\n\t\t\tif (request.body && request.body instanceof Stream.Readable) {\n\t\t\t\trequest.body.destroy(error);\n\t\t\t}\n\n\t\t\tif (!response || !response.body) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tresponse.body.emit('error', error);\n\t\t};\n\n\t\tif (signal && signal.aborted) {\n\t\t\tabort();\n\t\t\treturn;\n\t\t}\n\n\t\tconst abortAndFinalize = () => {\n\t\t\tabort();\n\t\t\tfinalize();\n\t\t};\n\n\t\t// Send request\n\t\tconst request_ = send(parsedURL.toString(), options);\n\n\t\tif (signal) {\n\t\t\tsignal.addEventListener('abort', abortAndFinalize);\n\t\t}\n\n\t\tconst finalize = () => {\n\t\t\trequest_.abort();\n\t\t\tif (signal) {\n\t\t\t\tsignal.removeEventListener('abort', abortAndFinalize);\n\t\t\t}\n\t\t};\n\n\t\trequest_.on('error', error => {\n\t\t\treject(new FetchError(`request to ${request.url} failed, reason: ${error.message}`, 'system', error));\n\t\t\tfinalize();\n\t\t});\n\n\t\tfixResponseChunkedTransferBadEnding(request_, error => {\n\t\t\tif (response && response.body) {\n\t\t\t\tresponse.body.destroy(error);\n\t\t\t}\n\t\t});\n\n\t\t/* c8 ignore next 18 */\n\t\tif (process.version < 'v14') {\n\t\t\t// Before Node.js 14, pipeline() does not fully support async iterators and does not always\n\t\t\t// properly handle when the socket close/end events are out of order.\n\t\t\trequest_.on('socket', s => {\n\t\t\t\tlet endedWithEventsCount;\n\t\t\t\ts.prependListener('end', () => {\n\t\t\t\t\tendedWithEventsCount = s._eventsCount;\n\t\t\t\t});\n\t\t\t\ts.prependListener('close', hadError => {\n\t\t\t\t\t// if end happened before close but the socket didn't emit an error, do it now\n\t\t\t\t\tif (response && endedWithEventsCount < s._eventsCount && !hadError) {\n\t\t\t\t\t\tconst error = new Error('Premature close');\n\t\t\t\t\t\terror.code = 'ERR_STREAM_PREMATURE_CLOSE';\n\t\t\t\t\t\tresponse.body.emit('error', error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\trequest_.on('response', response_ => {\n\t\t\trequest_.setTimeout(0);\n\t\t\tconst headers = fromRawHeaders(response_.rawHeaders);\n\n\t\t\t// HTTP fetch step 5\n\t\t\tif (isRedirect(response_.statusCode)) {\n\t\t\t\t// HTTP fetch step 5.2\n\t\t\t\tconst location = headers.get('Location');\n\n\t\t\t\t// HTTP fetch step 5.3\n\t\t\t\tlet locationURL = null;\n\t\t\t\ttry {\n\t\t\t\t\tlocationURL = location === null ? null : new URL(location, request.url);\n\t\t\t\t} catch {\n\t\t\t\t\t// error here can only be invalid URL in Location: header\n\t\t\t\t\t// do not throw when options.redirect == manual\n\t\t\t\t\t// let the user extract the errorneous redirect URL\n\t\t\t\t\tif (request.redirect !== 'manual') {\n\t\t\t\t\t\treject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'));\n\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// HTTP fetch step 5.5\n\t\t\t\tswitch (request.redirect) {\n\t\t\t\t\tcase 'error':\n\t\t\t\t\t\treject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));\n\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\treturn;\n\t\t\t\t\tcase 'manual':\n\t\t\t\t\t\t// Nothing to do\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'follow': {\n\t\t\t\t\t\t// HTTP-redirect fetch step 2\n\t\t\t\t\t\tif (locationURL === null) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 5\n\t\t\t\t\t\tif (request.counter >= request.follow) {\n\t\t\t\t\t\t\treject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));\n\t\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 6 (counter increment)\n\t\t\t\t\t\t// Create a new Request object.\n\t\t\t\t\t\tconst requestOptions = {\n\t\t\t\t\t\t\theaders: new Headers(request.headers),\n\t\t\t\t\t\t\tfollow: request.follow,\n\t\t\t\t\t\t\tcounter: request.counter + 1,\n\t\t\t\t\t\t\tagent: request.agent,\n\t\t\t\t\t\t\tcompress: request.compress,\n\t\t\t\t\t\t\tmethod: request.method,\n\t\t\t\t\t\t\tbody: clone(request),\n\t\t\t\t\t\t\tsignal: request.signal,\n\t\t\t\t\t\t\tsize: request.size,\n\t\t\t\t\t\t\treferrer: request.referrer,\n\t\t\t\t\t\t\treferrerPolicy: request.referrerPolicy\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t// when forwarding sensitive headers like \"Authorization\",\n\t\t\t\t\t\t// \"WWW-Authenticate\", and \"Cookie\" to untrusted targets,\n\t\t\t\t\t\t// headers will be ignored when following a redirect to a domain\n\t\t\t\t\t\t// that is not a subdomain match or exact match of the initial domain.\n\t\t\t\t\t\t// For example, a redirect from \"foo.com\" to either \"foo.com\" or \"sub.foo.com\"\n\t\t\t\t\t\t// will forward the sensitive headers, but a redirect to \"bar.com\" will not.\n\t\t\t\t\t\t// headers will also be ignored when following a redirect to a domain using\n\t\t\t\t\t\t// a different protocol. For example, a redirect from \"https://foo.com\" to \"http://foo.com\"\n\t\t\t\t\t\t// will not forward the sensitive headers\n\t\t\t\t\t\tif (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) {\n\t\t\t\t\t\t\tfor (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) {\n\t\t\t\t\t\t\t\trequestOptions.headers.delete(name);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 9\n\t\t\t\t\t\tif (response_.statusCode !== 303 && request.body && options_.body instanceof Stream.Readable) {\n\t\t\t\t\t\t\treject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));\n\t\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 11\n\t\t\t\t\t\tif (response_.statusCode === 303 || ((response_.statusCode === 301 || response_.statusCode === 302) && request.method === 'POST')) {\n\t\t\t\t\t\t\trequestOptions.method = 'GET';\n\t\t\t\t\t\t\trequestOptions.body = undefined;\n\t\t\t\t\t\t\trequestOptions.headers.delete('content-length');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 14\n\t\t\t\t\t\tconst responseReferrerPolicy = parseReferrerPolicyFromHeader(headers);\n\t\t\t\t\t\tif (responseReferrerPolicy) {\n\t\t\t\t\t\t\trequestOptions.referrerPolicy = responseReferrerPolicy;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 15\n\t\t\t\t\t\tresolve(fetch(new Request(locationURL, requestOptions)));\n\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn reject(new TypeError(`Redirect option '${request.redirect}' is not a valid value of RequestRedirect`));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Prepare response\n\t\t\tif (signal) {\n\t\t\t\tresponse_.once('end', () => {\n\t\t\t\t\tsignal.removeEventListener('abort', abortAndFinalize);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tlet body = pump(response_, new PassThrough(), error => {\n\t\t\t\tif (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\t\t\t});\n\t\t\t// see https://github.com/nodejs/node/pull/29376\n\t\t\t/* c8 ignore next 3 */\n\t\t\tif (process.version < 'v12.10') {\n\t\t\t\tresponse_.on('aborted', abortAndFinalize);\n\t\t\t}\n\n\t\t\tconst responseOptions = {\n\t\t\t\turl: request.url,\n\t\t\t\tstatus: response_.statusCode,\n\t\t\t\tstatusText: response_.statusMessage,\n\t\t\t\theaders,\n\t\t\t\tsize: request.size,\n\t\t\t\tcounter: request.counter,\n\t\t\t\thighWaterMark: request.highWaterMark\n\t\t\t};\n\n\t\t\t// HTTP-network fetch step 12.1.1.3\n\t\t\tconst codings = headers.get('Content-Encoding');\n\n\t\t\t// HTTP-network fetch step 12.1.1.4: handle content codings\n\n\t\t\t// in following scenarios we ignore compression support\n\t\t\t// 1. compression support is disabled\n\t\t\t// 2. HEAD request\n\t\t\t// 3. no Content-Encoding header\n\t\t\t// 4. no content response (204)\n\t\t\t// 5. content not modified response (304)\n\t\t\tif (!request.compress || request.method === 'HEAD' || codings === null || response_.statusCode === 204 || response_.statusCode === 304) {\n\t\t\t\tresponse = new Response(body, responseOptions);\n\t\t\t\tresolve(response);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// For Node v6+\n\t\t\t// Be less strict when decoding compressed responses, since sometimes\n\t\t\t// servers send slightly invalid responses that are still accepted\n\t\t\t// by common browsers.\n\t\t\t// Always using Z_SYNC_FLUSH is what cURL does.\n\t\t\tconst zlibOptions = {\n\t\t\t\tflush: zlib.Z_SYNC_FLUSH,\n\t\t\t\tfinishFlush: zlib.Z_SYNC_FLUSH\n\t\t\t};\n\n\t\t\t// For gzip\n\t\t\tif (codings === 'gzip' || codings === 'x-gzip') {\n\t\t\t\tbody = pump(body, zlib.createGunzip(zlibOptions), error => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tresponse = new Response(body, responseOptions);\n\t\t\t\tresolve(response);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// For deflate\n\t\t\tif (codings === 'deflate' || codings === 'x-deflate') {\n\t\t\t\t// Handle the infamous raw deflate response from old servers\n\t\t\t\t// a hack for old IIS and Apache servers\n\t\t\t\tconst raw = pump(response_, new PassThrough(), error => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\traw.once('data', chunk => {\n\t\t\t\t\t// See http://stackoverflow.com/questions/37519828\n\t\t\t\t\tif ((chunk[0] & 0x0F) === 0x08) {\n\t\t\t\t\t\tbody = pump(body, zlib.createInflate(), error => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbody = pump(body, zlib.createInflateRaw(), error => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tresponse = new Response(body, responseOptions);\n\t\t\t\t\tresolve(response);\n\t\t\t\t});\n\t\t\t\traw.once('end', () => {\n\t\t\t\t\t// Some old IIS servers return zero-length OK deflate responses, so\n\t\t\t\t\t// 'data' is never emitted. See https://github.com/node-fetch/node-fetch/pull/903\n\t\t\t\t\tif (!response) {\n\t\t\t\t\t\tresponse = new Response(body, responseOptions);\n\t\t\t\t\t\tresolve(response);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// For br\n\t\t\tif (codings === 'br') {\n\t\t\t\tbody = pump(body, zlib.createBrotliDecompress(), error => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tresponse = new Response(body, responseOptions);\n\t\t\t\tresolve(response);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Otherwise, use response as-is\n\t\t\tresponse = new Response(body, responseOptions);\n\t\t\tresolve(response);\n\t\t});\n\n\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\twriteToStream(request_, request).catch(reject);\n\t});\n}\n\nfunction fixResponseChunkedTransferBadEnding(request, errorCallback) {\n\tconst LAST_CHUNK = Buffer.from('0\\r\\n\\r\\n');\n\n\tlet isChunkedTransfer = false;\n\tlet properLastChunkReceived = false;\n\tlet previousChunk;\n\n\trequest.on('response', response => {\n\t\tconst {headers} = response;\n\t\tisChunkedTransfer = headers['transfer-encoding'] === 'chunked' && !headers['content-length'];\n\t});\n\n\trequest.on('socket', socket => {\n\t\tconst onSocketClose = () => {\n\t\t\tif (isChunkedTransfer && !properLastChunkReceived) {\n\t\t\t\tconst error = new Error('Premature close');\n\t\t\t\terror.code = 'ERR_STREAM_PREMATURE_CLOSE';\n\t\t\t\terrorCallback(error);\n\t\t\t}\n\t\t};\n\n\t\tconst onData = buf => {\n\t\t\tproperLastChunkReceived = Buffer.compare(buf.slice(-5), LAST_CHUNK) === 0;\n\n\t\t\t// Sometimes final 0-length chunk and end of message code are in separate packets\n\t\t\tif (!properLastChunkReceived && previousChunk) {\n\t\t\t\tproperLastChunkReceived = (\n\t\t\t\t\tBuffer.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 &&\n\t\t\t\t\tBuffer.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tpreviousChunk = buf;\n\t\t};\n\n\t\tsocket.prependListener('close', onSocketClose);\n\t\tsocket.on('data', onData);\n\n\t\trequest.on('close', () => {\n\t\t\tsocket.removeListener('close', onSocketClose);\n\t\t\tsocket.removeListener('data', onData);\n\t\t});\n\t});\n}\n", null, null, ";(function (globalObject) {\r\n 'use strict';\r\n\r\n/*\r\n * bignumber.js v9.3.1\r\n * A JavaScript library for arbitrary-precision arithmetic.\r\n * https://github.com/MikeMcl/bignumber.js\r\n * Copyright (c) 2025 Michael Mclaughlin \r\n * MIT Licensed.\r\n *\r\n * BigNumber.prototype methods | BigNumber methods\r\n * |\r\n * absoluteValue abs | clone\r\n * comparedTo | config set\r\n * decimalPlaces dp | DECIMAL_PLACES\r\n * dividedBy div | ROUNDING_MODE\r\n * dividedToIntegerBy idiv | EXPONENTIAL_AT\r\n * exponentiatedBy pow | RANGE\r\n * integerValue | CRYPTO\r\n * isEqualTo eq | MODULO_MODE\r\n * isFinite | POW_PRECISION\r\n * isGreaterThan gt | FORMAT\r\n * isGreaterThanOrEqualTo gte | ALPHABET\r\n * isInteger | isBigNumber\r\n * isLessThan lt | maximum max\r\n * isLessThanOrEqualTo lte | minimum min\r\n * isNaN | random\r\n * isNegative | sum\r\n * isPositive |\r\n * isZero |\r\n * minus |\r\n * modulo mod |\r\n * multipliedBy times |\r\n * negated |\r\n * plus |\r\n * precision sd |\r\n * shiftedBy |\r\n * squareRoot sqrt |\r\n * toExponential |\r\n * toFixed |\r\n * toFormat |\r\n * toFraction |\r\n * toJSON |\r\n * toNumber |\r\n * toPrecision |\r\n * toString |\r\n * valueOf |\r\n *\r\n */\r\n\r\n\r\n var BigNumber,\r\n isNumeric = /^-?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i,\r\n mathceil = Math.ceil,\r\n mathfloor = Math.floor,\r\n\r\n bignumberError = '[BigNumber Error] ',\r\n tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ',\r\n\r\n BASE = 1e14,\r\n LOG_BASE = 14,\r\n MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1\r\n // MAX_INT32 = 0x7fffffff, // 2^31 - 1\r\n POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],\r\n SQRT_BASE = 1e7,\r\n\r\n // EDITABLE\r\n // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and\r\n // the arguments to toExponential, toFixed, toFormat, and toPrecision.\r\n MAX = 1E9; // 0 to MAX_INT32\r\n\r\n\r\n /*\r\n * Create and return a BigNumber constructor.\r\n */\r\n function clone(configObject) {\r\n var div, convertBase, parseNumeric,\r\n P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null },\r\n ONE = new BigNumber(1),\r\n\r\n\r\n //----------------------------- EDITABLE CONFIG DEFAULTS -------------------------------\r\n\r\n\r\n // The default values below must be integers within the inclusive ranges stated.\r\n // The values can also be changed at run-time using BigNumber.set.\r\n\r\n // The maximum number of decimal places for operations involving division.\r\n DECIMAL_PLACES = 20, // 0 to MAX\r\n\r\n // The rounding mode used when rounding to the above decimal places, and when using\r\n // toExponential, toFixed, toFormat and toPrecision, and round (default value).\r\n // UP 0 Away from zero.\r\n // DOWN 1 Towards zero.\r\n // CEIL 2 Towards +Infinity.\r\n // FLOOR 3 Towards -Infinity.\r\n // HALF_UP 4 Towards nearest neighbour. If equidistant, up.\r\n // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.\r\n // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.\r\n // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.\r\n // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.\r\n ROUNDING_MODE = 4, // 0 to 8\r\n\r\n // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]\r\n\r\n // The exponent value at and beneath which toString returns exponential notation.\r\n // Number type: -7\r\n TO_EXP_NEG = -7, // 0 to -MAX\r\n\r\n // The exponent value at and above which toString returns exponential notation.\r\n // Number type: 21\r\n TO_EXP_POS = 21, // 0 to MAX\r\n\r\n // RANGE : [MIN_EXP, MAX_EXP]\r\n\r\n // The minimum exponent value, beneath which underflow to zero occurs.\r\n // Number type: -324 (5e-324)\r\n MIN_EXP = -1e7, // -1 to -MAX\r\n\r\n // The maximum exponent value, above which overflow to Infinity occurs.\r\n // Number type: 308 (1.7976931348623157e+308)\r\n // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.\r\n MAX_EXP = 1e7, // 1 to MAX\r\n\r\n // Whether to use cryptographically-secure random number generation, if available.\r\n CRYPTO = false, // true or false\r\n\r\n // The modulo mode used when calculating the modulus: a mod n.\r\n // The quotient (q = a / n) is calculated according to the corresponding rounding mode.\r\n // The remainder (r) is calculated as: r = a - n * q.\r\n //\r\n // UP 0 The remainder is positive if the dividend is negative, else is negative.\r\n // DOWN 1 The remainder has the same sign as the dividend.\r\n // This modulo mode is commonly known as 'truncated division' and is\r\n // equivalent to (a % n) in JavaScript.\r\n // FLOOR 3 The remainder has the same sign as the divisor (Python %).\r\n // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.\r\n // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).\r\n // The remainder is always positive.\r\n //\r\n // The truncated division, floored division, Euclidian division and IEEE 754 remainder\r\n // modes are commonly used for the modulus operation.\r\n // Although the other rounding modes can also be used, they may not give useful results.\r\n MODULO_MODE = 1, // 0 to 9\r\n\r\n // The maximum number of significant digits of the result of the exponentiatedBy operation.\r\n // If POW_PRECISION is 0, there will be unlimited significant digits.\r\n POW_PRECISION = 0, // 0 to MAX\r\n\r\n // The format specification used by the BigNumber.prototype.toFormat method.\r\n FORMAT = {\r\n prefix: '',\r\n groupSize: 3,\r\n secondaryGroupSize: 0,\r\n groupSeparator: ',',\r\n decimalSeparator: '.',\r\n fractionGroupSize: 0,\r\n fractionGroupSeparator: '\\xA0', // non-breaking space\r\n suffix: ''\r\n },\r\n\r\n // The alphabet used for base conversion. It must be at least 2 characters long, with no '+',\r\n // '-', '.', whitespace, or repeated character.\r\n // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'\r\n ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz',\r\n alphabetHasNormalDecimalDigits = true;\r\n\r\n\r\n //------------------------------------------------------------------------------------------\r\n\r\n\r\n // CONSTRUCTOR\r\n\r\n\r\n /*\r\n * The BigNumber constructor and exported function.\r\n * Create and return a new instance of a BigNumber object.\r\n *\r\n * v {number|string|BigNumber} A numeric value.\r\n * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive.\r\n */\r\n function BigNumber(v, b) {\r\n var alphabet, c, caseChanged, e, i, isNum, len, str,\r\n x = this;\r\n\r\n // Enable constructor call without `new`.\r\n if (!(x instanceof BigNumber)) return new BigNumber(v, b);\r\n\r\n if (b == null) {\r\n\r\n if (v && v._isBigNumber === true) {\r\n x.s = v.s;\r\n\r\n if (!v.c || v.e > MAX_EXP) {\r\n x.c = x.e = null;\r\n } else if (v.e < MIN_EXP) {\r\n x.c = [x.e = 0];\r\n } else {\r\n x.e = v.e;\r\n x.c = v.c.slice();\r\n }\r\n\r\n return;\r\n }\r\n\r\n if ((isNum = typeof v == 'number') && v * 0 == 0) {\r\n\r\n // Use `1 / n` to handle minus zero also.\r\n x.s = 1 / v < 0 ? (v = -v, -1) : 1;\r\n\r\n // Fast path for integers, where n < 2147483648 (2**31).\r\n if (v === ~~v) {\r\n for (e = 0, i = v; i >= 10; i /= 10, e++);\r\n\r\n if (e > MAX_EXP) {\r\n x.c = x.e = null;\r\n } else {\r\n x.e = e;\r\n x.c = [v];\r\n }\r\n\r\n return;\r\n }\r\n\r\n str = String(v);\r\n } else {\r\n\r\n if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum);\r\n\r\n x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1;\r\n }\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n\r\n // Exponential form?\r\n if ((i = str.search(/e/i)) > 0) {\r\n\r\n // Determine exponent.\r\n if (e < 0) e = i;\r\n e += +str.slice(i + 1);\r\n str = str.substring(0, i);\r\n } else if (e < 0) {\r\n\r\n // Integer.\r\n e = str.length;\r\n }\r\n\r\n } else {\r\n\r\n // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'\r\n intCheck(b, 2, ALPHABET.length, 'Base');\r\n\r\n // Allow exponential notation to be used with base 10 argument, while\r\n // also rounding to DECIMAL_PLACES as with other bases.\r\n if (b == 10 && alphabetHasNormalDecimalDigits) {\r\n x = new BigNumber(v);\r\n return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE);\r\n }\r\n\r\n str = String(v);\r\n\r\n if (isNum = typeof v == 'number') {\r\n\r\n // Avoid potential interpretation of Infinity and NaN as base 44+ values.\r\n if (v * 0 != 0) return parseNumeric(x, str, isNum, b);\r\n\r\n x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1;\r\n\r\n // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'\r\n if (BigNumber.DEBUG && str.replace(/^0\\.0*|\\./, '').length > 15) {\r\n throw Error\r\n (tooManyDigits + v);\r\n }\r\n } else {\r\n x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1;\r\n }\r\n\r\n alphabet = ALPHABET.slice(0, b);\r\n e = i = 0;\r\n\r\n // Check that str is a valid base b number.\r\n // Don't use RegExp, so alphabet can contain special characters.\r\n for (len = str.length; i < len; i++) {\r\n if (alphabet.indexOf(c = str.charAt(i)) < 0) {\r\n if (c == '.') {\r\n\r\n // If '.' is not the first character and it has not be found before.\r\n if (i > e) {\r\n e = len;\r\n continue;\r\n }\r\n } else if (!caseChanged) {\r\n\r\n // Allow e.g. hexadecimal 'FF' as well as 'ff'.\r\n if (str == str.toUpperCase() && (str = str.toLowerCase()) ||\r\n str == str.toLowerCase() && (str = str.toUpperCase())) {\r\n caseChanged = true;\r\n i = -1;\r\n e = 0;\r\n continue;\r\n }\r\n }\r\n\r\n return parseNumeric(x, String(v), isNum, b);\r\n }\r\n }\r\n\r\n // Prevent later check for length on converted number.\r\n isNum = false;\r\n str = convertBase(str, b, 10, x.s);\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n else e = str.length;\r\n }\r\n\r\n // Determine leading zeros.\r\n for (i = 0; str.charCodeAt(i) === 48; i++);\r\n\r\n // Determine trailing zeros.\r\n for (len = str.length; str.charCodeAt(--len) === 48;);\r\n\r\n if (str = str.slice(i, ++len)) {\r\n len -= i;\r\n\r\n // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'\r\n if (isNum && BigNumber.DEBUG &&\r\n len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) {\r\n throw Error\r\n (tooManyDigits + (x.s * v));\r\n }\r\n\r\n // Overflow?\r\n if ((e = e - i - 1) > MAX_EXP) {\r\n\r\n // Infinity.\r\n x.c = x.e = null;\r\n\r\n // Underflow?\r\n } else if (e < MIN_EXP) {\r\n\r\n // Zero.\r\n x.c = [x.e = 0];\r\n } else {\r\n x.e = e;\r\n x.c = [];\r\n\r\n // Transform base\r\n\r\n // e is the base 10 exponent.\r\n // i is where to slice str to get the first element of the coefficient array.\r\n i = (e + 1) % LOG_BASE;\r\n if (e < 0) i += LOG_BASE; // i < 1\r\n\r\n if (i < len) {\r\n if (i) x.c.push(+str.slice(0, i));\r\n\r\n for (len -= LOG_BASE; i < len;) {\r\n x.c.push(+str.slice(i, i += LOG_BASE));\r\n }\r\n\r\n i = LOG_BASE - (str = str.slice(i)).length;\r\n } else {\r\n i -= len;\r\n }\r\n\r\n for (; i--; str += '0');\r\n x.c.push(+str);\r\n }\r\n } else {\r\n\r\n // Zero.\r\n x.c = [x.e = 0];\r\n }\r\n }\r\n\r\n\r\n // CONSTRUCTOR PROPERTIES\r\n\r\n\r\n BigNumber.clone = clone;\r\n\r\n BigNumber.ROUND_UP = 0;\r\n BigNumber.ROUND_DOWN = 1;\r\n BigNumber.ROUND_CEIL = 2;\r\n BigNumber.ROUND_FLOOR = 3;\r\n BigNumber.ROUND_HALF_UP = 4;\r\n BigNumber.ROUND_HALF_DOWN = 5;\r\n BigNumber.ROUND_HALF_EVEN = 6;\r\n BigNumber.ROUND_HALF_CEIL = 7;\r\n BigNumber.ROUND_HALF_FLOOR = 8;\r\n BigNumber.EUCLID = 9;\r\n\r\n\r\n /*\r\n * Configure infrequently-changing library-wide settings.\r\n *\r\n * Accept an object with the following optional properties (if the value of a property is\r\n * a number, it must be an integer within the inclusive range stated):\r\n *\r\n * DECIMAL_PLACES {number} 0 to MAX\r\n * ROUNDING_MODE {number} 0 to 8\r\n * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX]\r\n * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX]\r\n * CRYPTO {boolean} true or false\r\n * MODULO_MODE {number} 0 to 9\r\n * POW_PRECISION {number} 0 to MAX\r\n * ALPHABET {string} A string of two or more unique characters which does\r\n * not contain '.'.\r\n * FORMAT {object} An object with some of the following properties:\r\n * prefix {string}\r\n * groupSize {number}\r\n * secondaryGroupSize {number}\r\n * groupSeparator {string}\r\n * decimalSeparator {string}\r\n * fractionGroupSize {number}\r\n * fractionGroupSeparator {string}\r\n * suffix {string}\r\n *\r\n * (The values assigned to the above FORMAT object properties are not checked for validity.)\r\n *\r\n * E.g.\r\n * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })\r\n *\r\n * Ignore properties/parameters set to null or undefined, except for ALPHABET.\r\n *\r\n * Return an object with the properties current values.\r\n */\r\n BigNumber.config = BigNumber.set = function (obj) {\r\n var p, v;\r\n\r\n if (obj != null) {\r\n\r\n if (typeof obj == 'object') {\r\n\r\n // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.\r\n // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) {\r\n v = obj[p];\r\n intCheck(v, 0, MAX, p);\r\n DECIMAL_PLACES = v;\r\n }\r\n\r\n // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.\r\n // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) {\r\n v = obj[p];\r\n intCheck(v, 0, 8, p);\r\n ROUNDING_MODE = v;\r\n }\r\n\r\n // EXPONENTIAL_AT {number|number[]}\r\n // Integer, -MAX to MAX inclusive or\r\n // [integer -MAX to 0 inclusive, 0 to MAX inclusive].\r\n // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) {\r\n v = obj[p];\r\n if (v && v.pop) {\r\n intCheck(v[0], -MAX, 0, p);\r\n intCheck(v[1], 0, MAX, p);\r\n TO_EXP_NEG = v[0];\r\n TO_EXP_POS = v[1];\r\n } else {\r\n intCheck(v, -MAX, MAX, p);\r\n TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v);\r\n }\r\n }\r\n\r\n // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or\r\n // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].\r\n // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}'\r\n if (obj.hasOwnProperty(p = 'RANGE')) {\r\n v = obj[p];\r\n if (v && v.pop) {\r\n intCheck(v[0], -MAX, -1, p);\r\n intCheck(v[1], 1, MAX, p);\r\n MIN_EXP = v[0];\r\n MAX_EXP = v[1];\r\n } else {\r\n intCheck(v, -MAX, MAX, p);\r\n if (v) {\r\n MIN_EXP = -(MAX_EXP = v < 0 ? -v : v);\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' cannot be zero: ' + v);\r\n }\r\n }\r\n }\r\n\r\n // CRYPTO {boolean} true or false.\r\n // '[BigNumber Error] CRYPTO not true or false: {v}'\r\n // '[BigNumber Error] crypto unavailable'\r\n if (obj.hasOwnProperty(p = 'CRYPTO')) {\r\n v = obj[p];\r\n if (v === !!v) {\r\n if (v) {\r\n if (typeof crypto != 'undefined' && crypto &&\r\n (crypto.getRandomValues || crypto.randomBytes)) {\r\n CRYPTO = v;\r\n } else {\r\n CRYPTO = !v;\r\n throw Error\r\n (bignumberError + 'crypto unavailable');\r\n }\r\n } else {\r\n CRYPTO = v;\r\n }\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' not true or false: ' + v);\r\n }\r\n }\r\n\r\n // MODULO_MODE {number} Integer, 0 to 9 inclusive.\r\n // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'MODULO_MODE')) {\r\n v = obj[p];\r\n intCheck(v, 0, 9, p);\r\n MODULO_MODE = v;\r\n }\r\n\r\n // POW_PRECISION {number} Integer, 0 to MAX inclusive.\r\n // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'POW_PRECISION')) {\r\n v = obj[p];\r\n intCheck(v, 0, MAX, p);\r\n POW_PRECISION = v;\r\n }\r\n\r\n // FORMAT {object}\r\n // '[BigNumber Error] FORMAT not an object: {v}'\r\n if (obj.hasOwnProperty(p = 'FORMAT')) {\r\n v = obj[p];\r\n if (typeof v == 'object') FORMAT = v;\r\n else throw Error\r\n (bignumberError + p + ' not an object: ' + v);\r\n }\r\n\r\n // ALPHABET {string}\r\n // '[BigNumber Error] ALPHABET invalid: {v}'\r\n if (obj.hasOwnProperty(p = 'ALPHABET')) {\r\n v = obj[p];\r\n\r\n // Disallow if less than two characters,\r\n // or if it contains '+', '-', '.', whitespace, or a repeated character.\r\n if (typeof v == 'string' && !/^.?$|[+\\-.\\s]|(.).*\\1/.test(v)) {\r\n alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789';\r\n ALPHABET = v;\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' invalid: ' + v);\r\n }\r\n }\r\n\r\n } else {\r\n\r\n // '[BigNumber Error] Object expected: {v}'\r\n throw Error\r\n (bignumberError + 'Object expected: ' + obj);\r\n }\r\n }\r\n\r\n return {\r\n DECIMAL_PLACES: DECIMAL_PLACES,\r\n ROUNDING_MODE: ROUNDING_MODE,\r\n EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS],\r\n RANGE: [MIN_EXP, MAX_EXP],\r\n CRYPTO: CRYPTO,\r\n MODULO_MODE: MODULO_MODE,\r\n POW_PRECISION: POW_PRECISION,\r\n FORMAT: FORMAT,\r\n ALPHABET: ALPHABET\r\n };\r\n };\r\n\r\n\r\n /*\r\n * Return true if v is a BigNumber instance, otherwise return false.\r\n *\r\n * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed.\r\n *\r\n * v {any}\r\n *\r\n * '[BigNumber Error] Invalid BigNumber: {v}'\r\n */\r\n BigNumber.isBigNumber = function (v) {\r\n if (!v || v._isBigNumber !== true) return false;\r\n if (!BigNumber.DEBUG) return true;\r\n\r\n var i, n,\r\n c = v.c,\r\n e = v.e,\r\n s = v.s;\r\n\r\n out: if ({}.toString.call(c) == '[object Array]') {\r\n\r\n if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) {\r\n\r\n // If the first element is zero, the BigNumber value must be zero.\r\n if (c[0] === 0) {\r\n if (e === 0 && c.length === 1) return true;\r\n break out;\r\n }\r\n\r\n // Calculate number of digits that c[0] should have, based on the exponent.\r\n i = (e + 1) % LOG_BASE;\r\n if (i < 1) i += LOG_BASE;\r\n\r\n // Calculate number of digits of c[0].\r\n //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) {\r\n if (String(c[0]).length == i) {\r\n\r\n for (i = 0; i < c.length; i++) {\r\n n = c[i];\r\n if (n < 0 || n >= BASE || n !== mathfloor(n)) break out;\r\n }\r\n\r\n // Last element cannot be zero, unless it is the only element.\r\n if (n !== 0) return true;\r\n }\r\n }\r\n\r\n // Infinity/NaN\r\n } else if (c === null && e === null && (s === null || s === 1 || s === -1)) {\r\n return true;\r\n }\r\n\r\n throw Error\r\n (bignumberError + 'Invalid BigNumber: ' + v);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the maximum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.maximum = BigNumber.max = function () {\r\n return maxOrMin(arguments, -1);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the minimum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.minimum = BigNumber.min = function () {\r\n return maxOrMin(arguments, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,\r\n * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing\r\n * zeros are produced).\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}'\r\n * '[BigNumber Error] crypto unavailable'\r\n */\r\n BigNumber.random = (function () {\r\n var pow2_53 = 0x20000000000000;\r\n\r\n // Return a 53 bit integer n, where 0 <= n < 9007199254740992.\r\n // Check if Math.random() produces more than 32 bits of randomness.\r\n // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.\r\n // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.\r\n var random53bitInt = (Math.random() * pow2_53) & 0x1fffff\r\n ? function () { return mathfloor(Math.random() * pow2_53); }\r\n : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +\r\n (Math.random() * 0x800000 | 0); };\r\n\r\n return function (dp) {\r\n var a, b, e, k, v,\r\n i = 0,\r\n c = [],\r\n rand = new BigNumber(ONE);\r\n\r\n if (dp == null) dp = DECIMAL_PLACES;\r\n else intCheck(dp, 0, MAX);\r\n\r\n k = mathceil(dp / LOG_BASE);\r\n\r\n if (CRYPTO) {\r\n\r\n // Browsers supporting crypto.getRandomValues.\r\n if (crypto.getRandomValues) {\r\n\r\n a = crypto.getRandomValues(new Uint32Array(k *= 2));\r\n\r\n for (; i < k;) {\r\n\r\n // 53 bits:\r\n // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)\r\n // 11111 11111111 11111111 11111111 11100000 00000000 00000000\r\n // ((Math.pow(2, 32) - 1) >>> 11).toString(2)\r\n // 11111 11111111 11111111\r\n // 0x20000 is 2^21.\r\n v = a[i] * 0x20000 + (a[i + 1] >>> 11);\r\n\r\n // Rejection sampling:\r\n // 0 <= v < 9007199254740992\r\n // Probability that v >= 9e15, is\r\n // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251\r\n if (v >= 9e15) {\r\n b = crypto.getRandomValues(new Uint32Array(2));\r\n a[i] = b[0];\r\n a[i + 1] = b[1];\r\n } else {\r\n\r\n // 0 <= v <= 8999999999999999\r\n // 0 <= (v % 1e14) <= 99999999999999\r\n c.push(v % 1e14);\r\n i += 2;\r\n }\r\n }\r\n i = k / 2;\r\n\r\n // Node.js supporting crypto.randomBytes.\r\n } else if (crypto.randomBytes) {\r\n\r\n // buffer\r\n a = crypto.randomBytes(k *= 7);\r\n\r\n for (; i < k;) {\r\n\r\n // 0x1000000000000 is 2^48, 0x10000000000 is 2^40\r\n // 0x100000000 is 2^32, 0x1000000 is 2^24\r\n // 11111 11111111 11111111 11111111 11111111 11111111 11111111\r\n // 0 <= v < 9007199254740992\r\n v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) +\r\n (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) +\r\n (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6];\r\n\r\n if (v >= 9e15) {\r\n crypto.randomBytes(7).copy(a, i);\r\n } else {\r\n\r\n // 0 <= (v % 1e14) <= 99999999999999\r\n c.push(v % 1e14);\r\n i += 7;\r\n }\r\n }\r\n i = k / 7;\r\n } else {\r\n CRYPTO = false;\r\n throw Error\r\n (bignumberError + 'crypto unavailable');\r\n }\r\n }\r\n\r\n // Use Math.random.\r\n if (!CRYPTO) {\r\n\r\n for (; i < k;) {\r\n v = random53bitInt();\r\n if (v < 9e15) c[i++] = v % 1e14;\r\n }\r\n }\r\n\r\n k = c[--i];\r\n dp %= LOG_BASE;\r\n\r\n // Convert trailing digits to zeros according to dp.\r\n if (k && dp) {\r\n v = POWS_TEN[LOG_BASE - dp];\r\n c[i] = mathfloor(k / v) * v;\r\n }\r\n\r\n // Remove trailing elements which are zero.\r\n for (; c[i] === 0; c.pop(), i--);\r\n\r\n // Zero?\r\n if (i < 0) {\r\n c = [e = 0];\r\n } else {\r\n\r\n // Remove leading elements which are zero and adjust exponent accordingly.\r\n for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);\r\n\r\n // Count the digits of the first element of c to determine leading zeros, and...\r\n for (i = 1, v = c[0]; v >= 10; v /= 10, i++);\r\n\r\n // adjust the exponent accordingly.\r\n if (i < LOG_BASE) e -= LOG_BASE - i;\r\n }\r\n\r\n rand.e = e;\r\n rand.c = c;\r\n return rand;\r\n };\r\n })();\r\n\r\n\r\n /*\r\n * Return a BigNumber whose value is the sum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.sum = function () {\r\n var i = 1,\r\n args = arguments,\r\n sum = new BigNumber(args[0]);\r\n for (; i < args.length;) sum = sum.plus(args[i++]);\r\n return sum;\r\n };\r\n\r\n\r\n // PRIVATE FUNCTIONS\r\n\r\n\r\n // Called by BigNumber and BigNumber.prototype.toString.\r\n convertBase = (function () {\r\n var decimal = '0123456789';\r\n\r\n /*\r\n * Convert string of baseIn to an array of numbers of baseOut.\r\n * Eg. toBaseOut('255', 10, 16) returns [15, 15].\r\n * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5].\r\n */\r\n function toBaseOut(str, baseIn, baseOut, alphabet) {\r\n var j,\r\n arr = [0],\r\n arrL,\r\n i = 0,\r\n len = str.length;\r\n\r\n for (; i < len;) {\r\n for (arrL = arr.length; arrL--; arr[arrL] *= baseIn);\r\n\r\n arr[0] += alphabet.indexOf(str.charAt(i++));\r\n\r\n for (j = 0; j < arr.length; j++) {\r\n\r\n if (arr[j] > baseOut - 1) {\r\n if (arr[j + 1] == null) arr[j + 1] = 0;\r\n arr[j + 1] += arr[j] / baseOut | 0;\r\n arr[j] %= baseOut;\r\n }\r\n }\r\n }\r\n\r\n return arr.reverse();\r\n }\r\n\r\n // Convert a numeric string of baseIn to a numeric string of baseOut.\r\n // If the caller is toString, we are converting from base 10 to baseOut.\r\n // If the caller is BigNumber, we are converting from baseIn to base 10.\r\n return function (str, baseIn, baseOut, sign, callerIsToString) {\r\n var alphabet, d, e, k, r, x, xc, y,\r\n i = str.indexOf('.'),\r\n dp = DECIMAL_PLACES,\r\n rm = ROUNDING_MODE;\r\n\r\n // Non-integer.\r\n if (i >= 0) {\r\n k = POW_PRECISION;\r\n\r\n // Unlimited precision.\r\n POW_PRECISION = 0;\r\n str = str.replace('.', '');\r\n y = new BigNumber(baseIn);\r\n x = y.pow(str.length - i);\r\n POW_PRECISION = k;\r\n\r\n // Convert str as if an integer, then restore the fraction part by dividing the\r\n // result by its base raised to a power.\r\n\r\n y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'),\r\n 10, baseOut, decimal);\r\n y.e = y.c.length;\r\n }\r\n\r\n // Convert the number as integer.\r\n\r\n xc = toBaseOut(str, baseIn, baseOut, callerIsToString\r\n ? (alphabet = ALPHABET, decimal)\r\n : (alphabet = decimal, ALPHABET));\r\n\r\n // xc now represents str as an integer and converted to baseOut. e is the exponent.\r\n e = k = xc.length;\r\n\r\n // Remove trailing zeros.\r\n for (; xc[--k] == 0; xc.pop());\r\n\r\n // Zero?\r\n if (!xc[0]) return alphabet.charAt(0);\r\n\r\n // Does str represent an integer? If so, no need for the division.\r\n if (i < 0) {\r\n --e;\r\n } else {\r\n x.c = xc;\r\n x.e = e;\r\n\r\n // The sign is needed for correct rounding.\r\n x.s = sign;\r\n x = div(x, y, dp, rm, baseOut);\r\n xc = x.c;\r\n r = x.r;\r\n e = x.e;\r\n }\r\n\r\n // xc now represents str converted to baseOut.\r\n\r\n // The index of the rounding digit.\r\n d = e + dp + 1;\r\n\r\n // The rounding digit: the digit to the right of the digit that may be rounded up.\r\n i = xc[d];\r\n\r\n // Look at the rounding digits and mode to determine whether to round up.\r\n\r\n k = baseOut / 2;\r\n r = r || d < 0 || xc[d + 1] != null;\r\n\r\n r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n\r\n // If the index of the rounding digit is not greater than zero, or xc represents\r\n // zero, then the result of the base conversion is zero or, if rounding up, a value\r\n // such as 0.00001.\r\n if (d < 1 || !xc[0]) {\r\n\r\n // 1^-dp or 0\r\n str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0);\r\n } else {\r\n\r\n // Truncate xc to the required number of decimal places.\r\n xc.length = d;\r\n\r\n // Round up?\r\n if (r) {\r\n\r\n // Rounding up may mean the previous digit has to be rounded up and so on.\r\n for (--baseOut; ++xc[--d] > baseOut;) {\r\n xc[d] = 0;\r\n\r\n if (!d) {\r\n ++e;\r\n xc = [1].concat(xc);\r\n }\r\n }\r\n }\r\n\r\n // Determine trailing zeros.\r\n for (k = xc.length; !xc[--k];);\r\n\r\n // E.g. [4, 11, 15] becomes 4bf.\r\n for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++]));\r\n\r\n // Add leading zeros, decimal point and trailing zeros as required.\r\n str = toFixedPoint(str, e, alphabet.charAt(0));\r\n }\r\n\r\n // The caller will add the sign.\r\n return str;\r\n };\r\n })();\r\n\r\n\r\n // Perform division in the specified base. Called by div and convertBase.\r\n div = (function () {\r\n\r\n // Assume non-zero x and k.\r\n function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }\r\n\r\n function compare(a, b, aL, bL) {\r\n var i, cmp;\r\n\r\n if (aL != bL) {\r\n cmp = aL > bL ? 1 : -1;\r\n } else {\r\n\r\n for (i = cmp = 0; i < aL; i++) {\r\n\r\n if (a[i] != b[i]) {\r\n cmp = a[i] > b[i] ? 1 : -1;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n return cmp;\r\n }\r\n\r\n function subtract(a, b, aL, base) {\r\n var i = 0;\r\n\r\n // Subtract b from a.\r\n for (; aL--;) {\r\n a[aL] -= i;\r\n i = a[aL] < b[aL] ? 1 : 0;\r\n a[aL] = i * base + a[aL] - b[aL];\r\n }\r\n\r\n // Remove leading zeros.\r\n for (; !a[0] && a.length > 1; a.splice(0, 1));\r\n }\r\n\r\n // x: dividend, y: divisor.\r\n return function (x, y, dp, rm, base) {\r\n var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,\r\n yL, yz,\r\n s = x.s == y.s ? 1 : -1,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n // Either NaN, Infinity or 0?\r\n if (!xc || !xc[0] || !yc || !yc[0]) {\r\n\r\n return new BigNumber(\r\n\r\n // Return NaN if either NaN, or both Infinity or 0.\r\n !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN :\r\n\r\n // Return \u00B10 if x is \u00B10 or y is \u00B1Infinity, or return \u00B1Infinity as y is \u00B10.\r\n xc && xc[0] == 0 || !yc ? s * 0 : s / 0\r\n );\r\n }\r\n\r\n q = new BigNumber(s);\r\n qc = q.c = [];\r\n e = x.e - y.e;\r\n s = dp + e + 1;\r\n\r\n if (!base) {\r\n base = BASE;\r\n e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE);\r\n s = s / LOG_BASE | 0;\r\n }\r\n\r\n // Result exponent may be one less then the current value of e.\r\n // The coefficients of the BigNumbers from convertBase may have trailing zeros.\r\n for (i = 0; yc[i] == (xc[i] || 0); i++);\r\n\r\n if (yc[i] > (xc[i] || 0)) e--;\r\n\r\n if (s < 0) {\r\n qc.push(1);\r\n more = true;\r\n } else {\r\n xL = xc.length;\r\n yL = yc.length;\r\n i = 0;\r\n s += 2;\r\n\r\n // Normalise xc and yc so highest order digit of yc is >= base / 2.\r\n\r\n n = mathfloor(base / (yc[0] + 1));\r\n\r\n // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1.\r\n // if (n > 1 || n++ == 1 && yc[0] < base / 2) {\r\n if (n > 1) {\r\n yc = multiply(yc, n, base);\r\n xc = multiply(xc, n, base);\r\n yL = yc.length;\r\n xL = xc.length;\r\n }\r\n\r\n xi = yL;\r\n rem = xc.slice(0, yL);\r\n remL = rem.length;\r\n\r\n // Add zeros to make remainder as long as divisor.\r\n for (; remL < yL; rem[remL++] = 0);\r\n yz = yc.slice();\r\n yz = [0].concat(yz);\r\n yc0 = yc[0];\r\n if (yc[1] >= base / 2) yc0++;\r\n // Not necessary, but to prevent trial digit n > base, when using base 3.\r\n // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15;\r\n\r\n do {\r\n n = 0;\r\n\r\n // Compare divisor and remainder.\r\n cmp = compare(yc, rem, yL, remL);\r\n\r\n // If divisor < remainder.\r\n if (cmp < 0) {\r\n\r\n // Calculate trial digit, n.\r\n\r\n rem0 = rem[0];\r\n if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);\r\n\r\n // n is how many times the divisor goes into the current remainder.\r\n n = mathfloor(rem0 / yc0);\r\n\r\n // Algorithm:\r\n // product = divisor multiplied by trial digit (n).\r\n // Compare product and remainder.\r\n // If product is greater than remainder:\r\n // Subtract divisor from product, decrement trial digit.\r\n // Subtract product from remainder.\r\n // If product was less than remainder at the last compare:\r\n // Compare new remainder and divisor.\r\n // If remainder is greater than divisor:\r\n // Subtract divisor from remainder, increment trial digit.\r\n\r\n if (n > 1) {\r\n\r\n // n may be > base only when base is 3.\r\n if (n >= base) n = base - 1;\r\n\r\n // product = divisor * trial digit.\r\n prod = multiply(yc, n, base);\r\n prodL = prod.length;\r\n remL = rem.length;\r\n\r\n // Compare product and remainder.\r\n // If product > remainder then trial digit n too high.\r\n // n is 1 too high about 5% of the time, and is not known to have\r\n // ever been more than 1 too high.\r\n while (compare(prod, rem, prodL, remL) == 1) {\r\n n--;\r\n\r\n // Subtract divisor from product.\r\n subtract(prod, yL < prodL ? yz : yc, prodL, base);\r\n prodL = prod.length;\r\n cmp = 1;\r\n }\r\n } else {\r\n\r\n // n is 0 or 1, cmp is -1.\r\n // If n is 0, there is no need to compare yc and rem again below,\r\n // so change cmp to 1 to avoid it.\r\n // If n is 1, leave cmp as -1, so yc and rem are compared again.\r\n if (n == 0) {\r\n\r\n // divisor < remainder, so n must be at least 1.\r\n cmp = n = 1;\r\n }\r\n\r\n // product = divisor\r\n prod = yc.slice();\r\n prodL = prod.length;\r\n }\r\n\r\n if (prodL < remL) prod = [0].concat(prod);\r\n\r\n // Subtract product from remainder.\r\n subtract(rem, prod, remL, base);\r\n remL = rem.length;\r\n\r\n // If product was < remainder.\r\n if (cmp == -1) {\r\n\r\n // Compare divisor and new remainder.\r\n // If divisor < new remainder, subtract divisor from remainder.\r\n // Trial digit n too low.\r\n // n is 1 too low about 5% of the time, and very rarely 2 too low.\r\n while (compare(yc, rem, yL, remL) < 1) {\r\n n++;\r\n\r\n // Subtract divisor from remainder.\r\n subtract(rem, yL < remL ? yz : yc, remL, base);\r\n remL = rem.length;\r\n }\r\n }\r\n } else if (cmp === 0) {\r\n n++;\r\n rem = [0];\r\n } // else cmp === 1 and n will be 0\r\n\r\n // Add the next digit, n, to the result array.\r\n qc[i++] = n;\r\n\r\n // Update the remainder.\r\n if (rem[0]) {\r\n rem[remL++] = xc[xi] || 0;\r\n } else {\r\n rem = [xc[xi]];\r\n remL = 1;\r\n }\r\n } while ((xi++ < xL || rem[0] != null) && s--);\r\n\r\n more = rem[0] != null;\r\n\r\n // Leading zero?\r\n if (!qc[0]) qc.splice(0, 1);\r\n }\r\n\r\n if (base == BASE) {\r\n\r\n // To calculate q.e, first get the number of digits of qc[0].\r\n for (i = 1, s = qc[0]; s >= 10; s /= 10, i++);\r\n\r\n round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more);\r\n\r\n // Caller is convertBase.\r\n } else {\r\n q.e = e;\r\n q.r = +more;\r\n }\r\n\r\n return q;\r\n };\r\n })();\r\n\r\n\r\n /*\r\n * Return a string representing the value of BigNumber n in fixed-point or exponential\r\n * notation rounded to the specified decimal places or significant digits.\r\n *\r\n * n: a BigNumber.\r\n * i: the index of the last digit required (i.e. the digit that may be rounded up).\r\n * rm: the rounding mode.\r\n * id: 1 (toExponential) or 2 (toPrecision).\r\n */\r\n function format(n, i, rm, id) {\r\n var c0, e, ne, len, str;\r\n\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n if (!n.c) return n.toString();\r\n\r\n c0 = n.c[0];\r\n ne = n.e;\r\n\r\n if (i == null) {\r\n str = coeffToString(n.c);\r\n str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS)\r\n ? toExponential(str, ne)\r\n : toFixedPoint(str, ne, '0');\r\n } else {\r\n n = round(new BigNumber(n), i, rm);\r\n\r\n // n.e may have changed if the value was rounded up.\r\n e = n.e;\r\n\r\n str = coeffToString(n.c);\r\n len = str.length;\r\n\r\n // toPrecision returns exponential notation if the number of significant digits\r\n // specified is less than the number of digits necessary to represent the integer\r\n // part of the value in fixed-point notation.\r\n\r\n // Exponential notation.\r\n if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) {\r\n\r\n // Append zeros?\r\n for (; len < i; str += '0', len++);\r\n str = toExponential(str, e);\r\n\r\n // Fixed-point notation.\r\n } else {\r\n i -= ne + (id === 2 && e > ne);\r\n str = toFixedPoint(str, e, '0');\r\n\r\n // Append zeros?\r\n if (e + 1 > len) {\r\n if (--i > 0) for (str += '.'; i--; str += '0');\r\n } else {\r\n i += e - len;\r\n if (i > 0) {\r\n if (e + 1 == len) str += '.';\r\n for (; i--; str += '0');\r\n }\r\n }\r\n }\r\n }\r\n\r\n return n.s < 0 && c0 ? '-' + str : str;\r\n }\r\n\r\n\r\n // Handle BigNumber.max and BigNumber.min.\r\n // If any number is NaN, return NaN.\r\n function maxOrMin(args, n) {\r\n var k, y,\r\n i = 1,\r\n x = new BigNumber(args[0]);\r\n\r\n for (; i < args.length; i++) {\r\n y = new BigNumber(args[i]);\r\n if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) {\r\n x = y;\r\n }\r\n }\r\n\r\n return x;\r\n }\r\n\r\n\r\n /*\r\n * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.\r\n * Called by minus, plus and times.\r\n */\r\n function normalise(n, c, e) {\r\n var i = 1,\r\n j = c.length;\r\n\r\n // Remove trailing zeros.\r\n for (; !c[--j]; c.pop());\r\n\r\n // Calculate the base 10 exponent. First get the number of digits of c[0].\r\n for (j = c[0]; j >= 10; j /= 10, i++);\r\n\r\n // Overflow?\r\n if ((e = i + e * LOG_BASE - 1) > MAX_EXP) {\r\n\r\n // Infinity.\r\n n.c = n.e = null;\r\n\r\n // Underflow?\r\n } else if (e < MIN_EXP) {\r\n\r\n // Zero.\r\n n.c = [n.e = 0];\r\n } else {\r\n n.e = e;\r\n n.c = c;\r\n }\r\n\r\n return n;\r\n }\r\n\r\n\r\n // Handle values that fail the validity test in BigNumber.\r\n parseNumeric = (function () {\r\n var basePrefix = /^(-?)0([xbo])(?=\\w[\\w.]*$)/i,\r\n dotAfter = /^([^.]+)\\.$/,\r\n dotBefore = /^\\.([^.]+)$/,\r\n isInfinityOrNaN = /^-?(Infinity|NaN)$/,\r\n whitespaceOrPlus = /^\\s*\\+(?=[\\w.])|^\\s+|\\s+$/g;\r\n\r\n return function (x, str, isNum, b) {\r\n var base,\r\n s = isNum ? str : str.replace(whitespaceOrPlus, '');\r\n\r\n // No exception on \u00B1Infinity or NaN.\r\n if (isInfinityOrNaN.test(s)) {\r\n x.s = isNaN(s) ? null : s < 0 ? -1 : 1;\r\n } else {\r\n if (!isNum) {\r\n\r\n // basePrefix = /^(-?)0([xbo])(?=\\w[\\w.]*$)/i\r\n s = s.replace(basePrefix, function (m, p1, p2) {\r\n base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8;\r\n return !b || b == base ? p1 : m;\r\n });\r\n\r\n if (b) {\r\n base = b;\r\n\r\n // E.g. '1.' to '1', '.1' to '0.1'\r\n s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1');\r\n }\r\n\r\n if (str != s) return new BigNumber(s, base);\r\n }\r\n\r\n // '[BigNumber Error] Not a number: {n}'\r\n // '[BigNumber Error] Not a base {b} number: {n}'\r\n if (BigNumber.DEBUG) {\r\n throw Error\r\n (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str);\r\n }\r\n\r\n // NaN\r\n x.s = null;\r\n }\r\n\r\n x.c = x.e = null;\r\n }\r\n })();\r\n\r\n\r\n /*\r\n * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.\r\n * If r is truthy, it is known that there are more digits after the rounding digit.\r\n */\r\n function round(x, sd, rm, r) {\r\n var d, i, j, k, n, ni, rd,\r\n xc = x.c,\r\n pows10 = POWS_TEN;\r\n\r\n // if x is not Infinity or NaN...\r\n if (xc) {\r\n\r\n // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.\r\n // n is a base 1e14 number, the value of the element of array x.c containing rd.\r\n // ni is the index of n within x.c.\r\n // d is the number of digits of n.\r\n // i is the index of rd within n including leading zeros.\r\n // j is the actual index of rd within n (if < 0, rd is a leading zero).\r\n out: {\r\n\r\n // Get the number of digits of the first element of xc.\r\n for (d = 1, k = xc[0]; k >= 10; k /= 10, d++);\r\n i = sd - d;\r\n\r\n // If the rounding digit is in the first element of xc...\r\n if (i < 0) {\r\n i += LOG_BASE;\r\n j = sd;\r\n n = xc[ni = 0];\r\n\r\n // Get the rounding digit at index j of n.\r\n rd = mathfloor(n / pows10[d - j - 1] % 10);\r\n } else {\r\n ni = mathceil((i + 1) / LOG_BASE);\r\n\r\n if (ni >= xc.length) {\r\n\r\n if (r) {\r\n\r\n // Needed by sqrt.\r\n for (; xc.length <= ni; xc.push(0));\r\n n = rd = 0;\r\n d = 1;\r\n i %= LOG_BASE;\r\n j = i - LOG_BASE + 1;\r\n } else {\r\n break out;\r\n }\r\n } else {\r\n n = k = xc[ni];\r\n\r\n // Get the number of digits of n.\r\n for (d = 1; k >= 10; k /= 10, d++);\r\n\r\n // Get the index of rd within n.\r\n i %= LOG_BASE;\r\n\r\n // Get the index of rd within n, adjusted for leading zeros.\r\n // The number of leading zeros of n is given by LOG_BASE - d.\r\n j = i - LOG_BASE + d;\r\n\r\n // Get the rounding digit at index j of n.\r\n rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10);\r\n }\r\n }\r\n\r\n r = r || sd < 0 ||\r\n\r\n // Are there any non-zero digits after the rounding digit?\r\n // The expression n % pows10[d - j - 1] returns all digits of n to the right\r\n // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.\r\n xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]);\r\n\r\n r = rm < 4\r\n ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 &&\r\n\r\n // Check whether the digit to the left of the rounding digit is odd.\r\n ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n\r\n if (sd < 1 || !xc[0]) {\r\n xc.length = 0;\r\n\r\n if (r) {\r\n\r\n // Convert sd to decimal places.\r\n sd -= x.e + 1;\r\n\r\n // 1, 0.1, 0.01, 0.001, 0.0001 etc.\r\n xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE];\r\n x.e = -sd || 0;\r\n } else {\r\n\r\n // Zero.\r\n xc[0] = x.e = 0;\r\n }\r\n\r\n return x;\r\n }\r\n\r\n // Remove excess digits.\r\n if (i == 0) {\r\n xc.length = ni;\r\n k = 1;\r\n ni--;\r\n } else {\r\n xc.length = ni + 1;\r\n k = pows10[LOG_BASE - i];\r\n\r\n // E.g. 56700 becomes 56000 if 7 is the rounding digit.\r\n // j > 0 means i > number of leading zeros of n.\r\n xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0;\r\n }\r\n\r\n // Round up?\r\n if (r) {\r\n\r\n for (; ;) {\r\n\r\n // If the digit to be rounded up is in the first element of xc...\r\n if (ni == 0) {\r\n\r\n // i will be the length of xc[0] before k is added.\r\n for (i = 1, j = xc[0]; j >= 10; j /= 10, i++);\r\n j = xc[0] += k;\r\n for (k = 1; j >= 10; j /= 10, k++);\r\n\r\n // if i != k the length has increased.\r\n if (i != k) {\r\n x.e++;\r\n if (xc[0] == BASE) xc[0] = 1;\r\n }\r\n\r\n break;\r\n } else {\r\n xc[ni] += k;\r\n if (xc[ni] != BASE) break;\r\n xc[ni--] = 0;\r\n k = 1;\r\n }\r\n }\r\n }\r\n\r\n // Remove trailing zeros.\r\n for (i = xc.length; xc[--i] === 0; xc.pop());\r\n }\r\n\r\n // Overflow? Infinity.\r\n if (x.e > MAX_EXP) {\r\n x.c = x.e = null;\r\n\r\n // Underflow? Zero.\r\n } else if (x.e < MIN_EXP) {\r\n x.c = [x.e = 0];\r\n }\r\n }\r\n\r\n return x;\r\n }\r\n\r\n\r\n function valueOf(n) {\r\n var str,\r\n e = n.e;\r\n\r\n if (e === null) return n.toString();\r\n\r\n str = coeffToString(n.c);\r\n\r\n str = e <= TO_EXP_NEG || e >= TO_EXP_POS\r\n ? toExponential(str, e)\r\n : toFixedPoint(str, e, '0');\r\n\r\n return n.s < 0 ? '-' + str : str;\r\n }\r\n\r\n\r\n // PROTOTYPE/INSTANCE METHODS\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the absolute value of this BigNumber.\r\n */\r\n P.absoluteValue = P.abs = function () {\r\n var x = new BigNumber(this);\r\n if (x.s < 0) x.s = 1;\r\n return x;\r\n };\r\n\r\n\r\n /*\r\n * Return\r\n * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),\r\n * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),\r\n * 0 if they have the same value,\r\n * or null if the value of either is NaN.\r\n */\r\n P.comparedTo = function (y, b) {\r\n return compare(this, new BigNumber(y, b));\r\n };\r\n\r\n\r\n /*\r\n * If dp is undefined or null or true or false, return the number of decimal places of the\r\n * value of this BigNumber, or null if the value of this BigNumber is \u00B1Infinity or NaN.\r\n *\r\n * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this\r\n * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or\r\n * ROUNDING_MODE if rm is omitted.\r\n *\r\n * [dp] {number} Decimal places: integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.decimalPlaces = P.dp = function (dp, rm) {\r\n var c, n, v,\r\n x = this;\r\n\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n return round(new BigNumber(x), dp + x.e + 1, rm);\r\n }\r\n\r\n if (!(c = x.c)) return null;\r\n n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE;\r\n\r\n // Subtract the number of trailing zeros of the last number.\r\n if (v = c[v]) for (; v % 10 == 0; v /= 10, n--);\r\n if (n < 0) n = 0;\r\n\r\n return n;\r\n };\r\n\r\n\r\n /*\r\n * n / 0 = I\r\n * n / N = N\r\n * n / I = 0\r\n * 0 / n = 0\r\n * 0 / 0 = N\r\n * 0 / N = N\r\n * 0 / I = 0\r\n * N / n = N\r\n * N / 0 = N\r\n * N / N = N\r\n * N / I = N\r\n * I / n = I\r\n * I / 0 = I\r\n * I / N = N\r\n * I / I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber divided by the value of\r\n * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.\r\n */\r\n P.dividedBy = P.div = function (y, b) {\r\n return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the integer part of dividing the value of this\r\n * BigNumber by the value of BigNumber(y, b).\r\n */\r\n P.dividedToIntegerBy = P.idiv = function (y, b) {\r\n return div(this, new BigNumber(y, b), 0, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a BigNumber whose value is the value of this BigNumber exponentiated by n.\r\n *\r\n * If m is present, return the result modulo m.\r\n * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.\r\n * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE.\r\n *\r\n * The modular power operation works efficiently when x, n, and m are integers, otherwise it\r\n * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0.\r\n *\r\n * n {number|string|BigNumber} The exponent. An integer.\r\n * [m] {number|string|BigNumber} The modulus.\r\n *\r\n * '[BigNumber Error] Exponent not an integer: {n}'\r\n */\r\n P.exponentiatedBy = P.pow = function (n, m) {\r\n var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y,\r\n x = this;\r\n\r\n n = new BigNumber(n);\r\n\r\n // Allow NaN and \u00B1Infinity, but not other non-integers.\r\n if (n.c && !n.isInteger()) {\r\n throw Error\r\n (bignumberError + 'Exponent not an integer: ' + valueOf(n));\r\n }\r\n\r\n if (m != null) m = new BigNumber(m);\r\n\r\n // Exponent of MAX_SAFE_INTEGER is 15.\r\n nIsBig = n.e > 14;\r\n\r\n // If x is NaN, \u00B1Infinity, \u00B10 or \u00B11, or n is \u00B1Infinity, NaN or \u00B10.\r\n if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) {\r\n\r\n // The sign of the result of pow when x is negative depends on the evenness of n.\r\n // If +n overflows to \u00B1Infinity, the evenness of n would be not be known.\r\n y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n)));\r\n return m ? y.mod(m) : y;\r\n }\r\n\r\n nIsNeg = n.s < 0;\r\n\r\n if (m) {\r\n\r\n // x % m returns NaN if abs(m) is zero, or m is NaN.\r\n if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN);\r\n\r\n isModExp = !nIsNeg && x.isInteger() && m.isInteger();\r\n\r\n if (isModExp) x = x.mod(m);\r\n\r\n // Overflow to \u00B1Infinity: >=2**1e10 or >=1.0000024**1e15.\r\n // Underflow to \u00B10: <=0.79**1e10 or <=0.9999975**1e15.\r\n } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0\r\n // [1, 240000000]\r\n ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7\r\n // [80000000000000] [99999750000000]\r\n : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) {\r\n\r\n // If x is negative and n is odd, k = -0, else k = 0.\r\n k = x.s < 0 && isOdd(n) ? -0 : 0;\r\n\r\n // If x >= 1, k = \u00B1Infinity.\r\n if (x.e > -1) k = 1 / k;\r\n\r\n // If n is negative return \u00B10, else return \u00B1Infinity.\r\n return new BigNumber(nIsNeg ? 1 / k : k);\r\n\r\n } else if (POW_PRECISION) {\r\n\r\n // Truncating each coefficient array to a length of k after each multiplication\r\n // equates to truncating significant digits to POW_PRECISION + [28, 41],\r\n // i.e. there will be a minimum of 28 guard digits retained.\r\n k = mathceil(POW_PRECISION / LOG_BASE + 2);\r\n }\r\n\r\n if (nIsBig) {\r\n half = new BigNumber(0.5);\r\n if (nIsNeg) n.s = 1;\r\n nIsOdd = isOdd(n);\r\n } else {\r\n i = Math.abs(+valueOf(n));\r\n nIsOdd = i % 2;\r\n }\r\n\r\n y = new BigNumber(ONE);\r\n\r\n // Performs 54 loop iterations for n of 9007199254740991.\r\n for (; ;) {\r\n\r\n if (nIsOdd) {\r\n y = y.times(x);\r\n if (!y.c) break;\r\n\r\n if (k) {\r\n if (y.c.length > k) y.c.length = k;\r\n } else if (isModExp) {\r\n y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m));\r\n }\r\n }\r\n\r\n if (i) {\r\n i = mathfloor(i / 2);\r\n if (i === 0) break;\r\n nIsOdd = i % 2;\r\n } else {\r\n n = n.times(half);\r\n round(n, n.e + 1, 1);\r\n\r\n if (n.e > 14) {\r\n nIsOdd = isOdd(n);\r\n } else {\r\n i = +valueOf(n);\r\n if (i === 0) break;\r\n nIsOdd = i % 2;\r\n }\r\n }\r\n\r\n x = x.times(x);\r\n\r\n if (k) {\r\n if (x.c && x.c.length > k) x.c.length = k;\r\n } else if (isModExp) {\r\n x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m));\r\n }\r\n }\r\n\r\n if (isModExp) return y;\r\n if (nIsNeg) y = ONE.div(y);\r\n\r\n return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y;\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer\r\n * using rounding mode rm, or ROUNDING_MODE if rm is omitted.\r\n *\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}'\r\n */\r\n P.integerValue = function (rm) {\r\n var n = new BigNumber(this);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n return round(n, n.e + 1, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isEqualTo = P.eq = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is a finite number, otherwise return false.\r\n */\r\n P.isFinite = function () {\r\n return !!this.c;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isGreaterThan = P.gt = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is greater than or equal to the value of\r\n * BigNumber(y, b), otherwise return false.\r\n */\r\n P.isGreaterThanOrEqualTo = P.gte = function (y, b) {\r\n return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0;\r\n\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is an integer, otherwise return false.\r\n */\r\n P.isInteger = function () {\r\n return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isLessThan = P.lt = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is less than or equal to the value of\r\n * BigNumber(y, b), otherwise return false.\r\n */\r\n P.isLessThanOrEqualTo = P.lte = function (y, b) {\r\n return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is NaN, otherwise return false.\r\n */\r\n P.isNaN = function () {\r\n return !this.s;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is negative, otherwise return false.\r\n */\r\n P.isNegative = function () {\r\n return this.s < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is positive, otherwise return false.\r\n */\r\n P.isPositive = function () {\r\n return this.s > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is 0 or -0, otherwise return false.\r\n */\r\n P.isZero = function () {\r\n return !!this.c && this.c[0] == 0;\r\n };\r\n\r\n\r\n /*\r\n * n - 0 = n\r\n * n - N = N\r\n * n - I = -I\r\n * 0 - n = -n\r\n * 0 - 0 = 0\r\n * 0 - N = N\r\n * 0 - I = -I\r\n * N - n = N\r\n * N - 0 = N\r\n * N - N = N\r\n * N - I = N\r\n * I - n = I\r\n * I - 0 = I\r\n * I - N = N\r\n * I - I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber minus the value of\r\n * BigNumber(y, b).\r\n */\r\n P.minus = function (y, b) {\r\n var i, j, t, xLTy,\r\n x = this,\r\n a = x.s;\r\n\r\n y = new BigNumber(y, b);\r\n b = y.s;\r\n\r\n // Either NaN?\r\n if (!a || !b) return new BigNumber(NaN);\r\n\r\n // Signs differ?\r\n if (a != b) {\r\n y.s = -b;\r\n return x.plus(y);\r\n }\r\n\r\n var xe = x.e / LOG_BASE,\r\n ye = y.e / LOG_BASE,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n if (!xe || !ye) {\r\n\r\n // Either Infinity?\r\n if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN);\r\n\r\n // Either zero?\r\n if (!xc[0] || !yc[0]) {\r\n\r\n // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.\r\n return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x :\r\n\r\n // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity\r\n ROUNDING_MODE == 3 ? -0 : 0);\r\n }\r\n }\r\n\r\n xe = bitFloor(xe);\r\n ye = bitFloor(ye);\r\n xc = xc.slice();\r\n\r\n // Determine which is the bigger number.\r\n if (a = xe - ye) {\r\n\r\n if (xLTy = a < 0) {\r\n a = -a;\r\n t = xc;\r\n } else {\r\n ye = xe;\r\n t = yc;\r\n }\r\n\r\n t.reverse();\r\n\r\n // Prepend zeros to equalise exponents.\r\n for (b = a; b--; t.push(0));\r\n t.reverse();\r\n } else {\r\n\r\n // Exponents equal. Check digit by digit.\r\n j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b;\r\n\r\n for (a = b = 0; b < j; b++) {\r\n\r\n if (xc[b] != yc[b]) {\r\n xLTy = xc[b] < yc[b];\r\n break;\r\n }\r\n }\r\n }\r\n\r\n // x < y? Point xc to the array of the bigger number.\r\n if (xLTy) {\r\n t = xc;\r\n xc = yc;\r\n yc = t;\r\n y.s = -y.s;\r\n }\r\n\r\n b = (j = yc.length) - (i = xc.length);\r\n\r\n // Append zeros to xc if shorter.\r\n // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.\r\n if (b > 0) for (; b--; xc[i++] = 0);\r\n b = BASE - 1;\r\n\r\n // Subtract yc from xc.\r\n for (; j > a;) {\r\n\r\n if (xc[--j] < yc[j]) {\r\n for (i = j; i && !xc[--i]; xc[i] = b);\r\n --xc[i];\r\n xc[j] += BASE;\r\n }\r\n\r\n xc[j] -= yc[j];\r\n }\r\n\r\n // Remove leading zeros and adjust exponent accordingly.\r\n for (; xc[0] == 0; xc.splice(0, 1), --ye);\r\n\r\n // Zero?\r\n if (!xc[0]) {\r\n\r\n // Following IEEE 754 (2008) 6.3,\r\n // n - n = +0 but n - n = -0 when rounding towards -Infinity.\r\n y.s = ROUNDING_MODE == 3 ? -1 : 1;\r\n y.c = [y.e = 0];\r\n return y;\r\n }\r\n\r\n // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity\r\n // for finite x and y.\r\n return normalise(y, xc, ye);\r\n };\r\n\r\n\r\n /*\r\n * n % 0 = N\r\n * n % N = N\r\n * n % I = n\r\n * 0 % n = 0\r\n * -0 % n = -0\r\n * 0 % 0 = N\r\n * 0 % N = N\r\n * 0 % I = 0\r\n * N % n = N\r\n * N % 0 = N\r\n * N % N = N\r\n * N % I = N\r\n * I % n = N\r\n * I % 0 = N\r\n * I % N = N\r\n * I % I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber modulo the value of\r\n * BigNumber(y, b). The result depends on the value of MODULO_MODE.\r\n */\r\n P.modulo = P.mod = function (y, b) {\r\n var q, s,\r\n x = this;\r\n\r\n y = new BigNumber(y, b);\r\n\r\n // Return NaN if x is Infinity or NaN, or y is NaN or zero.\r\n if (!x.c || !y.s || y.c && !y.c[0]) {\r\n return new BigNumber(NaN);\r\n\r\n // Return x if y is Infinity or x is zero.\r\n } else if (!y.c || x.c && !x.c[0]) {\r\n return new BigNumber(x);\r\n }\r\n\r\n if (MODULO_MODE == 9) {\r\n\r\n // Euclidian division: q = sign(y) * floor(x / abs(y))\r\n // r = x - qy where 0 <= r < abs(y)\r\n s = y.s;\r\n y.s = 1;\r\n q = div(x, y, 0, 3);\r\n y.s = s;\r\n q.s *= s;\r\n } else {\r\n q = div(x, y, 0, MODULO_MODE);\r\n }\r\n\r\n y = x.minus(q.times(y));\r\n\r\n // To match JavaScript %, ensure sign of zero is sign of dividend.\r\n if (!y.c[0] && MODULO_MODE == 1) y.s = x.s;\r\n\r\n return y;\r\n };\r\n\r\n\r\n /*\r\n * n * 0 = 0\r\n * n * N = N\r\n * n * I = I\r\n * 0 * n = 0\r\n * 0 * 0 = 0\r\n * 0 * N = N\r\n * 0 * I = N\r\n * N * n = N\r\n * N * 0 = N\r\n * N * N = N\r\n * N * I = N\r\n * I * n = I\r\n * I * 0 = N\r\n * I * N = N\r\n * I * I = I\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value\r\n * of BigNumber(y, b).\r\n */\r\n P.multipliedBy = P.times = function (y, b) {\r\n var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,\r\n base, sqrtBase,\r\n x = this,\r\n xc = x.c,\r\n yc = (y = new BigNumber(y, b)).c;\r\n\r\n // Either NaN, \u00B1Infinity or \u00B10?\r\n if (!xc || !yc || !xc[0] || !yc[0]) {\r\n\r\n // Return NaN if either is NaN, or one is 0 and the other is Infinity.\r\n if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) {\r\n y.c = y.e = y.s = null;\r\n } else {\r\n y.s *= x.s;\r\n\r\n // Return \u00B1Infinity if either is \u00B1Infinity.\r\n if (!xc || !yc) {\r\n y.c = y.e = null;\r\n\r\n // Return \u00B10 if either is \u00B10.\r\n } else {\r\n y.c = [0];\r\n y.e = 0;\r\n }\r\n }\r\n\r\n return y;\r\n }\r\n\r\n e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE);\r\n y.s *= x.s;\r\n xcL = xc.length;\r\n ycL = yc.length;\r\n\r\n // Ensure xc points to longer array and xcL to its length.\r\n if (xcL < ycL) {\r\n zc = xc;\r\n xc = yc;\r\n yc = zc;\r\n i = xcL;\r\n xcL = ycL;\r\n ycL = i;\r\n }\r\n\r\n // Initialise the result array with zeros.\r\n for (i = xcL + ycL, zc = []; i--; zc.push(0));\r\n\r\n base = BASE;\r\n sqrtBase = SQRT_BASE;\r\n\r\n for (i = ycL; --i >= 0;) {\r\n c = 0;\r\n ylo = yc[i] % sqrtBase;\r\n yhi = yc[i] / sqrtBase | 0;\r\n\r\n for (k = xcL, j = i + k; j > i;) {\r\n xlo = xc[--k] % sqrtBase;\r\n xhi = xc[k] / sqrtBase | 0;\r\n m = yhi * xlo + xhi * ylo;\r\n xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c;\r\n c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi;\r\n zc[j--] = xlo % base;\r\n }\r\n\r\n zc[j] = c;\r\n }\r\n\r\n if (c) {\r\n ++e;\r\n } else {\r\n zc.splice(0, 1);\r\n }\r\n\r\n return normalise(y, zc, e);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber negated,\r\n * i.e. multiplied by -1.\r\n */\r\n P.negated = function () {\r\n var x = new BigNumber(this);\r\n x.s = -x.s || null;\r\n return x;\r\n };\r\n\r\n\r\n /*\r\n * n + 0 = n\r\n * n + N = N\r\n * n + I = I\r\n * 0 + n = n\r\n * 0 + 0 = 0\r\n * 0 + N = N\r\n * 0 + I = I\r\n * N + n = N\r\n * N + 0 = N\r\n * N + N = N\r\n * N + I = N\r\n * I + n = I\r\n * I + 0 = I\r\n * I + N = N\r\n * I + I = I\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber plus the value of\r\n * BigNumber(y, b).\r\n */\r\n P.plus = function (y, b) {\r\n var t,\r\n x = this,\r\n a = x.s;\r\n\r\n y = new BigNumber(y, b);\r\n b = y.s;\r\n\r\n // Either NaN?\r\n if (!a || !b) return new BigNumber(NaN);\r\n\r\n // Signs differ?\r\n if (a != b) {\r\n y.s = -b;\r\n return x.minus(y);\r\n }\r\n\r\n var xe = x.e / LOG_BASE,\r\n ye = y.e / LOG_BASE,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n if (!xe || !ye) {\r\n\r\n // Return \u00B1Infinity if either \u00B1Infinity.\r\n if (!xc || !yc) return new BigNumber(a / 0);\r\n\r\n // Either zero?\r\n // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.\r\n if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0);\r\n }\r\n\r\n xe = bitFloor(xe);\r\n ye = bitFloor(ye);\r\n xc = xc.slice();\r\n\r\n // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.\r\n if (a = xe - ye) {\r\n if (a > 0) {\r\n ye = xe;\r\n t = yc;\r\n } else {\r\n a = -a;\r\n t = xc;\r\n }\r\n\r\n t.reverse();\r\n for (; a--; t.push(0));\r\n t.reverse();\r\n }\r\n\r\n a = xc.length;\r\n b = yc.length;\r\n\r\n // Point xc to the longer array, and b to the shorter length.\r\n if (a - b < 0) {\r\n t = yc;\r\n yc = xc;\r\n xc = t;\r\n b = a;\r\n }\r\n\r\n // Only start adding at yc.length - 1 as the further digits of xc can be ignored.\r\n for (a = 0; b;) {\r\n a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0;\r\n xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;\r\n }\r\n\r\n if (a) {\r\n xc = [a].concat(xc);\r\n ++ye;\r\n }\r\n\r\n // No need to check for zero, as +x + +y != 0 && -x + -y != 0\r\n // ye = MAX_EXP + 1 possible\r\n return normalise(y, xc, ye);\r\n };\r\n\r\n\r\n /*\r\n * If sd is undefined or null or true or false, return the number of significant digits of\r\n * the value of this BigNumber, or null if the value of this BigNumber is \u00B1Infinity or NaN.\r\n * If sd is true include integer-part trailing zeros in the count.\r\n *\r\n * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this\r\n * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or\r\n * ROUNDING_MODE if rm is omitted.\r\n *\r\n * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive.\r\n * boolean: whether to count integer-part trailing zeros: true or false.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'\r\n */\r\n P.precision = P.sd = function (sd, rm) {\r\n var c, n, v,\r\n x = this;\r\n\r\n if (sd != null && sd !== !!sd) {\r\n intCheck(sd, 1, MAX);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n return round(new BigNumber(x), sd, rm);\r\n }\r\n\r\n if (!(c = x.c)) return null;\r\n v = c.length - 1;\r\n n = v * LOG_BASE + 1;\r\n\r\n if (v = c[v]) {\r\n\r\n // Subtract the number of trailing zeros of the last element.\r\n for (; v % 10 == 0; v /= 10, n--);\r\n\r\n // Add the number of digits of the first element.\r\n for (v = c[0]; v >= 10; v /= 10, n++);\r\n }\r\n\r\n if (sd && x.e + 1 > n) n = x.e + 1;\r\n\r\n return n;\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber shifted by k places\r\n * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.\r\n *\r\n * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}'\r\n */\r\n P.shiftedBy = function (k) {\r\n intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);\r\n return this.times('1e' + k);\r\n };\r\n\r\n\r\n /*\r\n * sqrt(-n) = N\r\n * sqrt(N) = N\r\n * sqrt(-I) = N\r\n * sqrt(I) = I\r\n * sqrt(0) = 0\r\n * sqrt(-0) = -0\r\n *\r\n * Return a new BigNumber whose value is the square root of the value of this BigNumber,\r\n * rounded according to DECIMAL_PLACES and ROUNDING_MODE.\r\n */\r\n P.squareRoot = P.sqrt = function () {\r\n var m, n, r, rep, t,\r\n x = this,\r\n c = x.c,\r\n s = x.s,\r\n e = x.e,\r\n dp = DECIMAL_PLACES + 4,\r\n half = new BigNumber('0.5');\r\n\r\n // Negative/NaN/Infinity/zero?\r\n if (s !== 1 || !c || !c[0]) {\r\n return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0);\r\n }\r\n\r\n // Initial estimate.\r\n s = Math.sqrt(+valueOf(x));\r\n\r\n // Math.sqrt underflow/overflow?\r\n // Pass x to Math.sqrt as integer, then adjust the exponent of the result.\r\n if (s == 0 || s == 1 / 0) {\r\n n = coeffToString(c);\r\n if ((n.length + e) % 2 == 0) n += '0';\r\n s = Math.sqrt(+n);\r\n e = bitFloor((e + 1) / 2) - (e < 0 || e % 2);\r\n\r\n if (s == 1 / 0) {\r\n n = '5e' + e;\r\n } else {\r\n n = s.toExponential();\r\n n = n.slice(0, n.indexOf('e') + 1) + e;\r\n }\r\n\r\n r = new BigNumber(n);\r\n } else {\r\n r = new BigNumber(s + '');\r\n }\r\n\r\n // Check for zero.\r\n // r could be zero if MIN_EXP is changed after the this value was created.\r\n // This would cause a division by zero (x/t) and hence Infinity below, which would cause\r\n // coeffToString to throw.\r\n if (r.c[0]) {\r\n e = r.e;\r\n s = e + dp;\r\n if (s < 3) s = 0;\r\n\r\n // Newton-Raphson iteration.\r\n for (; ;) {\r\n t = r;\r\n r = half.times(t.plus(div(x, t, dp, 1)));\r\n\r\n if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) {\r\n\r\n // The exponent of r may here be one less than the final result exponent,\r\n // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits\r\n // are indexed correctly.\r\n if (r.e < e) --s;\r\n n = n.slice(s - 3, s + 1);\r\n\r\n // The 4th rounding digit may be in error by -1 so if the 4 rounding digits\r\n // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the\r\n // iteration.\r\n if (n == '9999' || !rep && n == '4999') {\r\n\r\n // On the first iteration only, check to see if rounding up gives the\r\n // exact result as the nines may infinitely repeat.\r\n if (!rep) {\r\n round(t, t.e + DECIMAL_PLACES + 2, 0);\r\n\r\n if (t.times(t).eq(x)) {\r\n r = t;\r\n break;\r\n }\r\n }\r\n\r\n dp += 4;\r\n s += 4;\r\n rep = 1;\r\n } else {\r\n\r\n // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact\r\n // result. If not, then there are further digits and m will be truthy.\r\n if (!+n || !+n.slice(1) && n.charAt(0) == '5') {\r\n\r\n // Truncate to the first rounding digit.\r\n round(r, r.e + DECIMAL_PLACES + 2, 1);\r\n m = !r.times(r).eq(x);\r\n }\r\n\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in exponential notation and\r\n * rounded using ROUNDING_MODE to dp fixed decimal places.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.toExponential = function (dp, rm) {\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n dp++;\r\n }\r\n return format(this, dp, rm, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in fixed-point notation rounding\r\n * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.\r\n *\r\n * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',\r\n * but e.g. (-0.00001).toFixed(0) is '-0'.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.toFixed = function (dp, rm) {\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n dp = dp + this.e + 1;\r\n }\r\n return format(this, dp, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in fixed-point notation rounded\r\n * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties\r\n * of the format or FORMAT object (see BigNumber.set).\r\n *\r\n * The formatting object may contain some or all of the properties shown below.\r\n *\r\n * FORMAT = {\r\n * prefix: '',\r\n * groupSize: 3,\r\n * secondaryGroupSize: 0,\r\n * groupSeparator: ',',\r\n * decimalSeparator: '.',\r\n * fractionGroupSize: 0,\r\n * fractionGroupSeparator: '\\xA0', // non-breaking space\r\n * suffix: ''\r\n * };\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n * [format] {object} Formatting options. See FORMAT pbject above.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n * '[BigNumber Error] Argument not an object: {format}'\r\n */\r\n P.toFormat = function (dp, rm, format) {\r\n var str,\r\n x = this;\r\n\r\n if (format == null) {\r\n if (dp != null && rm && typeof rm == 'object') {\r\n format = rm;\r\n rm = null;\r\n } else if (dp && typeof dp == 'object') {\r\n format = dp;\r\n dp = rm = null;\r\n } else {\r\n format = FORMAT;\r\n }\r\n } else if (typeof format != 'object') {\r\n throw Error\r\n (bignumberError + 'Argument not an object: ' + format);\r\n }\r\n\r\n str = x.toFixed(dp, rm);\r\n\r\n if (x.c) {\r\n var i,\r\n arr = str.split('.'),\r\n g1 = +format.groupSize,\r\n g2 = +format.secondaryGroupSize,\r\n groupSeparator = format.groupSeparator || '',\r\n intPart = arr[0],\r\n fractionPart = arr[1],\r\n isNeg = x.s < 0,\r\n intDigits = isNeg ? intPart.slice(1) : intPart,\r\n len = intDigits.length;\r\n\r\n if (g2) {\r\n i = g1;\r\n g1 = g2;\r\n g2 = i;\r\n len -= i;\r\n }\r\n\r\n if (g1 > 0 && len > 0) {\r\n i = len % g1 || g1;\r\n intPart = intDigits.substr(0, i);\r\n for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1);\r\n if (g2 > 0) intPart += groupSeparator + intDigits.slice(i);\r\n if (isNeg) intPart = '-' + intPart;\r\n }\r\n\r\n str = fractionPart\r\n ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize)\r\n ? fractionPart.replace(new RegExp('\\\\d{' + g2 + '}\\\\B', 'g'),\r\n '$&' + (format.fractionGroupSeparator || ''))\r\n : fractionPart)\r\n : intPart;\r\n }\r\n\r\n return (format.prefix || '') + str + (format.suffix || '');\r\n };\r\n\r\n\r\n /*\r\n * Return an array of two BigNumbers representing the value of this BigNumber as a simple\r\n * fraction with an integer numerator and an integer denominator.\r\n * The denominator will be a positive non-zero value less than or equal to the specified\r\n * maximum denominator. If a maximum denominator is not specified, the denominator will be\r\n * the lowest value necessary to represent the number exactly.\r\n *\r\n * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator.\r\n *\r\n * '[BigNumber Error] Argument {not an integer|out of range} : {md}'\r\n */\r\n P.toFraction = function (md) {\r\n var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s,\r\n x = this,\r\n xc = x.c;\r\n\r\n if (md != null) {\r\n n = new BigNumber(md);\r\n\r\n // Throw if md is less than one or is not an integer, unless it is Infinity.\r\n if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) {\r\n throw Error\r\n (bignumberError + 'Argument ' +\r\n (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n));\r\n }\r\n }\r\n\r\n if (!xc) return new BigNumber(x);\r\n\r\n d = new BigNumber(ONE);\r\n n1 = d0 = new BigNumber(ONE);\r\n d1 = n0 = new BigNumber(ONE);\r\n s = coeffToString(xc);\r\n\r\n // Determine initial denominator.\r\n // d is a power of 10 and the minimum max denominator that specifies the value exactly.\r\n e = d.e = s.length - x.e - 1;\r\n d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp];\r\n md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n;\r\n\r\n exp = MAX_EXP;\r\n MAX_EXP = 1 / 0;\r\n n = new BigNumber(s);\r\n\r\n // n0 = d1 = 0\r\n n0.c[0] = 0;\r\n\r\n for (; ;) {\r\n q = div(n, d, 0, 1);\r\n d2 = d0.plus(q.times(d1));\r\n if (d2.comparedTo(md) == 1) break;\r\n d0 = d1;\r\n d1 = d2;\r\n n1 = n0.plus(q.times(d2 = n1));\r\n n0 = d2;\r\n d = n.minus(q.times(d2 = d));\r\n n = d2;\r\n }\r\n\r\n d2 = div(md.minus(d0), d1, 0, 1);\r\n n0 = n0.plus(d2.times(n1));\r\n d0 = d0.plus(d2.times(d1));\r\n n0.s = n1.s = x.s;\r\n e = e * 2;\r\n\r\n // Determine which fraction is closer to x, n0/d0 or n1/d1\r\n r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo(\r\n div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0];\r\n\r\n MAX_EXP = exp;\r\n\r\n return r;\r\n };\r\n\r\n\r\n /*\r\n * Return the value of this BigNumber converted to a number primitive.\r\n */\r\n P.toNumber = function () {\r\n return +valueOf(this);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber rounded to sd significant digits\r\n * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits\r\n * necessary to represent the integer part of the value in fixed-point notation, then use\r\n * exponential notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'\r\n */\r\n P.toPrecision = function (sd, rm) {\r\n if (sd != null) intCheck(sd, 1, MAX);\r\n return format(this, sd, rm, 2);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in base b, or base 10 if b is\r\n * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and\r\n * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent\r\n * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than\r\n * TO_EXP_NEG, return exponential notation.\r\n *\r\n * [b] {number} Integer, 2 to ALPHABET.length inclusive.\r\n *\r\n * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'\r\n */\r\n P.toString = function (b) {\r\n var str,\r\n n = this,\r\n s = n.s,\r\n e = n.e;\r\n\r\n // Infinity or NaN?\r\n if (e === null) {\r\n if (s) {\r\n str = 'Infinity';\r\n if (s < 0) str = '-' + str;\r\n } else {\r\n str = 'NaN';\r\n }\r\n } else {\r\n if (b == null) {\r\n str = e <= TO_EXP_NEG || e >= TO_EXP_POS\r\n ? toExponential(coeffToString(n.c), e)\r\n : toFixedPoint(coeffToString(n.c), e, '0');\r\n } else if (b === 10 && alphabetHasNormalDecimalDigits) {\r\n n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE);\r\n str = toFixedPoint(coeffToString(n.c), n.e, '0');\r\n } else {\r\n intCheck(b, 2, ALPHABET.length, 'Base');\r\n str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true);\r\n }\r\n\r\n if (s < 0 && n.c[0]) str = '-' + str;\r\n }\r\n\r\n return str;\r\n };\r\n\r\n\r\n /*\r\n * Return as toString, but do not accept a base argument, and include the minus sign for\r\n * negative zero.\r\n */\r\n P.valueOf = P.toJSON = function () {\r\n return valueOf(this);\r\n };\r\n\r\n\r\n P._isBigNumber = true;\r\n\r\n if (configObject != null) BigNumber.set(configObject);\r\n\r\n return BigNumber;\r\n }\r\n\r\n\r\n // PRIVATE HELPER FUNCTIONS\r\n\r\n // These functions don't need access to variables,\r\n // e.g. DECIMAL_PLACES, in the scope of the `clone` function above.\r\n\r\n\r\n function bitFloor(n) {\r\n var i = n | 0;\r\n return n > 0 || n === i ? i : i - 1;\r\n }\r\n\r\n\r\n // Return a coefficient array as a string of base 10 digits.\r\n function coeffToString(a) {\r\n var s, z,\r\n i = 1,\r\n j = a.length,\r\n r = a[0] + '';\r\n\r\n for (; i < j;) {\r\n s = a[i++] + '';\r\n z = LOG_BASE - s.length;\r\n for (; z--; s = '0' + s);\r\n r += s;\r\n }\r\n\r\n // Determine trailing zeros.\r\n for (j = r.length; r.charCodeAt(--j) === 48;);\r\n\r\n return r.slice(0, j + 1 || 1);\r\n }\r\n\r\n\r\n // Compare the value of BigNumbers x and y.\r\n function compare(x, y) {\r\n var a, b,\r\n xc = x.c,\r\n yc = y.c,\r\n i = x.s,\r\n j = y.s,\r\n k = x.e,\r\n l = y.e;\r\n\r\n // Either NaN?\r\n if (!i || !j) return null;\r\n\r\n a = xc && !xc[0];\r\n b = yc && !yc[0];\r\n\r\n // Either zero?\r\n if (a || b) return a ? b ? 0 : -j : i;\r\n\r\n // Signs differ?\r\n if (i != j) return i;\r\n\r\n a = i < 0;\r\n b = k == l;\r\n\r\n // Either Infinity?\r\n if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1;\r\n\r\n // Compare exponents.\r\n if (!b) return k > l ^ a ? 1 : -1;\r\n\r\n j = (k = xc.length) < (l = yc.length) ? k : l;\r\n\r\n // Compare digit by digit.\r\n for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1;\r\n\r\n // Compare lengths.\r\n return k == l ? 0 : k > l ^ a ? 1 : -1;\r\n }\r\n\r\n\r\n /*\r\n * Check that n is a primitive number, an integer, and in range, otherwise throw.\r\n */\r\n function intCheck(n, min, max, name) {\r\n if (n < min || n > max || n !== mathfloor(n)) {\r\n throw Error\r\n (bignumberError + (name || 'Argument') + (typeof n == 'number'\r\n ? n < min || n > max ? ' out of range: ' : ' not an integer: '\r\n : ' not a primitive number: ') + String(n));\r\n }\r\n }\r\n\r\n\r\n // Assumes finite n.\r\n function isOdd(n) {\r\n var k = n.c.length - 1;\r\n return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0;\r\n }\r\n\r\n\r\n function toExponential(str, e) {\r\n return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) +\r\n (e < 0 ? 'e' : 'e+') + e;\r\n }\r\n\r\n\r\n function toFixedPoint(str, e, z) {\r\n var len, zs;\r\n\r\n // Negative exponent?\r\n if (e < 0) {\r\n\r\n // Prepend zeros.\r\n for (zs = z + '.'; ++e; zs += z);\r\n str = zs + str;\r\n\r\n // Positive exponent\r\n } else {\r\n len = str.length;\r\n\r\n // Append zeros.\r\n if (++e > len) {\r\n for (zs = z, e -= len; --e; zs += z);\r\n str += zs;\r\n } else if (e < len) {\r\n str = str.slice(0, e) + '.' + str.slice(e);\r\n }\r\n }\r\n\r\n return str;\r\n }\r\n\r\n\r\n // EXPORT\r\n\r\n\r\n BigNumber = clone();\r\n BigNumber['default'] = BigNumber.BigNumber = BigNumber;\r\n\r\n // AMD.\r\n if (typeof define == 'function' && define.amd) {\r\n define(function () { return BigNumber; });\r\n\r\n // Node.js and other environments that support module.exports.\r\n } else if (typeof module != 'undefined' && module.exports) {\r\n module.exports = BigNumber;\r\n\r\n // Browser.\r\n } else {\r\n if (!globalObject) {\r\n globalObject = typeof self != 'undefined' && self ? self : window;\r\n }\r\n\r\n globalObject.BigNumber = BigNumber;\r\n }\r\n})(this);\r\n", "var BigNumber = require('bignumber.js');\n\n/*\n json2.js\n 2013-05-26\n\n Public Domain.\n\n NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.\n\n See http://www.JSON.org/js.html\n\n\n This code should be minified before deployment.\n See http://javascript.crockford.com/jsmin.html\n\n USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO\n NOT CONTROL.\n\n\n This file creates a global JSON object containing two methods: stringify\n and parse.\n\n JSON.stringify(value, replacer, space)\n value any JavaScript value, usually an object or array.\n\n replacer an optional parameter that determines how object\n values are stringified for objects. It can be a\n function or an array of strings.\n\n space an optional parameter that specifies the indentation\n of nested structures. If it is omitted, the text will\n be packed without extra whitespace. If it is a number,\n it will specify the number of spaces to indent at each\n level. If it is a string (such as '\\t' or ' '),\n it contains the characters used to indent at each level.\n\n This method produces a JSON text from a JavaScript value.\n\n When an object value is found, if the object contains a toJSON\n method, its toJSON method will be called and the result will be\n stringified. A toJSON method does not serialize: it returns the\n value represented by the name/value pair that should be serialized,\n or undefined if nothing should be serialized. The toJSON method\n will be passed the key associated with the value, and this will be\n bound to the value\n\n For example, this would serialize Dates as ISO strings.\n\n Date.prototype.toJSON = function (key) {\n function f(n) {\n // Format integers to have at least two digits.\n return n < 10 ? '0' + n : n;\n }\n\n return this.getUTCFullYear() + '-' +\n f(this.getUTCMonth() + 1) + '-' +\n f(this.getUTCDate()) + 'T' +\n f(this.getUTCHours()) + ':' +\n f(this.getUTCMinutes()) + ':' +\n f(this.getUTCSeconds()) + 'Z';\n };\n\n You can provide an optional replacer method. It will be passed the\n key and value of each member, with this bound to the containing\n object. The value that is returned from your method will be\n serialized. If your method returns undefined, then the member will\n be excluded from the serialization.\n\n If the replacer parameter is an array of strings, then it will be\n used to select the members to be serialized. It filters the results\n such that only members with keys listed in the replacer array are\n stringified.\n\n Values that do not have JSON representations, such as undefined or\n functions, will not be serialized. Such values in objects will be\n dropped; in arrays they will be replaced with null. You can use\n a replacer function to replace those with JSON values.\n JSON.stringify(undefined) returns undefined.\n\n The optional space parameter produces a stringification of the\n value that is filled with line breaks and indentation to make it\n easier to read.\n\n If the space parameter is a non-empty string, then that string will\n be used for indentation. If the space parameter is a number, then\n the indentation will be that many spaces.\n\n Example:\n\n text = JSON.stringify(['e', {pluribus: 'unum'}]);\n // text is '[\"e\",{\"pluribus\":\"unum\"}]'\n\n\n text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\\t');\n // text is '[\\n\\t\"e\",\\n\\t{\\n\\t\\t\"pluribus\": \"unum\"\\n\\t}\\n]'\n\n text = JSON.stringify([new Date()], function (key, value) {\n return this[key] instanceof Date ?\n 'Date(' + this[key] + ')' : value;\n });\n // text is '[\"Date(---current time---)\"]'\n\n\n JSON.parse(text, reviver)\n This method parses a JSON text to produce an object or array.\n It can throw a SyntaxError exception.\n\n The optional reviver parameter is a function that can filter and\n transform the results. It receives each of the keys and values,\n and its return value is used instead of the original value.\n If it returns what it received, then the structure is not modified.\n If it returns undefined then the member is deleted.\n\n Example:\n\n // Parse the text. Values that look like ISO date strings will\n // be converted to Date objects.\n\n myData = JSON.parse(text, function (key, value) {\n var a;\n if (typeof value === 'string') {\n a =\n/^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}(?:\\.\\d*)?)Z$/.exec(value);\n if (a) {\n return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],\n +a[5], +a[6]));\n }\n }\n return value;\n });\n\n myData = JSON.parse('[\"Date(09/09/2001)\"]', function (key, value) {\n var d;\n if (typeof value === 'string' &&\n value.slice(0, 5) === 'Date(' &&\n value.slice(-1) === ')') {\n d = new Date(value.slice(5, -1));\n if (d) {\n return d;\n }\n }\n return value;\n });\n\n\n This is a reference implementation. You are free to copy, modify, or\n redistribute.\n*/\n\n/*jslint evil: true, regexp: true */\n\n/*members \"\", \"\\b\", \"\\t\", \"\\n\", \"\\f\", \"\\r\", \"\\\"\", JSON, \"\\\\\", apply,\n call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,\n getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,\n lastIndex, length, parse, prototype, push, replace, slice, stringify,\n test, toJSON, toString, valueOf\n*/\n\n\n// Create a JSON object only if one does not already exist. We create the\n// methods in a closure to avoid creating global variables.\n\nvar JSON = module.exports;\n\n(function () {\n 'use strict';\n\n function f(n) {\n // Format integers to have at least two digits.\n return n < 10 ? '0' + n : n;\n }\n\n var cx = /[\\u0000\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]/g,\n escapable = /[\\\\\\\"\\x00-\\x1f\\x7f-\\x9f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]/g,\n gap,\n indent,\n meta = { // table of character substitutions\n '\\b': '\\\\b',\n '\\t': '\\\\t',\n '\\n': '\\\\n',\n '\\f': '\\\\f',\n '\\r': '\\\\r',\n '\"' : '\\\\\"',\n '\\\\': '\\\\\\\\'\n },\n rep;\n\n\n function quote(string) {\n\n// If the string contains no control characters, no quote characters, and no\n// backslash characters, then we can safely slap some quotes around it.\n// Otherwise we must also replace the offending characters with safe escape\n// sequences.\n\n escapable.lastIndex = 0;\n return escapable.test(string) ? '\"' + string.replace(escapable, function (a) {\n var c = meta[a];\n return typeof c === 'string'\n ? c\n : '\\\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);\n }) + '\"' : '\"' + string + '\"';\n }\n\n\n function str(key, holder) {\n\n// Produce a string from holder[key].\n\n var i, // The loop counter.\n k, // The member key.\n v, // The member value.\n length,\n mind = gap,\n partial,\n value = holder[key],\n isBigNumber = value != null && (value instanceof BigNumber || BigNumber.isBigNumber(value));\n\n// If the value has a toJSON method, call it to obtain a replacement value.\n\n if (value && typeof value === 'object' &&\n typeof value.toJSON === 'function') {\n value = value.toJSON(key);\n }\n\n// If we were called with a replacer function, then call the replacer to\n// obtain a replacement value.\n\n if (typeof rep === 'function') {\n value = rep.call(holder, key, value);\n }\n\n// What happens next depends on the value's type.\n\n switch (typeof value) {\n case 'string':\n if (isBigNumber) {\n return value;\n } else {\n return quote(value);\n }\n\n case 'number':\n\n// JSON numbers must be finite. Encode non-finite numbers as null.\n\n return isFinite(value) ? String(value) : 'null';\n\n case 'boolean':\n case 'null':\n case 'bigint':\n\n// If the value is a boolean or null, convert it to a string. Note:\n// typeof null does not produce 'null'. The case is included here in\n// the remote chance that this gets fixed someday.\n\n return String(value);\n\n// If the type is 'object', we might be dealing with an object or an array or\n// null.\n\n case 'object':\n\n// Due to a specification blunder in ECMAScript, typeof null is 'object',\n// so watch out for that case.\n\n if (!value) {\n return 'null';\n }\n\n// Make an array to hold the partial results of stringifying this object value.\n\n gap += indent;\n partial = [];\n\n// Is the value an array?\n\n if (Object.prototype.toString.apply(value) === '[object Array]') {\n\n// The value is an array. Stringify every element. Use null as a placeholder\n// for non-JSON values.\n\n length = value.length;\n for (i = 0; i < length; i += 1) {\n partial[i] = str(i, value) || 'null';\n }\n\n// Join all of the elements together, separated with commas, and wrap them in\n// brackets.\n\n v = partial.length === 0\n ? '[]'\n : gap\n ? '[\\n' + gap + partial.join(',\\n' + gap) + '\\n' + mind + ']'\n : '[' + partial.join(',') + ']';\n gap = mind;\n return v;\n }\n\n// If the replacer is an array, use it to select the members to be stringified.\n\n if (rep && typeof rep === 'object') {\n length = rep.length;\n for (i = 0; i < length; i += 1) {\n if (typeof rep[i] === 'string') {\n k = rep[i];\n v = str(k, value);\n if (v) {\n partial.push(quote(k) + (gap ? ': ' : ':') + v);\n }\n }\n }\n } else {\n\n// Otherwise, iterate through all of the keys in the object.\n\n Object.keys(value).forEach(function(k) {\n var v = str(k, value);\n if (v) {\n partial.push(quote(k) + (gap ? ': ' : ':') + v);\n }\n });\n }\n\n// Join all of the member texts together, separated with commas,\n// and wrap them in braces.\n\n v = partial.length === 0\n ? '{}'\n : gap\n ? '{\\n' + gap + partial.join(',\\n' + gap) + '\\n' + mind + '}'\n : '{' + partial.join(',') + '}';\n gap = mind;\n return v;\n }\n }\n\n// If the JSON object does not yet have a stringify method, give it one.\n\n if (typeof JSON.stringify !== 'function') {\n JSON.stringify = function (value, replacer, space) {\n\n// The stringify method takes a value and an optional replacer, and an optional\n// space parameter, and returns a JSON text. The replacer can be a function\n// that can replace values, or an array of strings that will select the keys.\n// A default replacer method can be provided. Use of the space parameter can\n// produce text that is more easily readable.\n\n var i;\n gap = '';\n indent = '';\n\n// If the space parameter is a number, make an indent string containing that\n// many spaces.\n\n if (typeof space === 'number') {\n for (i = 0; i < space; i += 1) {\n indent += ' ';\n }\n\n// If the space parameter is a string, it will be used as the indent string.\n\n } else if (typeof space === 'string') {\n indent = space;\n }\n\n// If there is a replacer, it must be a function or an array.\n// Otherwise, throw an error.\n\n rep = replacer;\n if (replacer && typeof replacer !== 'function' &&\n (typeof replacer !== 'object' ||\n typeof replacer.length !== 'number')) {\n throw new Error('JSON.stringify');\n }\n\n// Make a fake root object containing our value under the key of ''.\n// Return the result of stringifying the value.\n\n return str('', {'': value});\n };\n }\n}());\n", "var BigNumber = null;\n\n// regexpxs extracted from\n// (c) BSD-3-Clause\n// https://github.com/fastify/secure-json-parse/graphs/contributors and https://github.com/hapijs/bourne/graphs/contributors\n\nconst suspectProtoRx = /(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])(?:p|\\\\u0070)(?:r|\\\\u0072)(?:o|\\\\u006[Ff])(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])/;\nconst suspectConstructorRx = /(?:c|\\\\u0063)(?:o|\\\\u006[Ff])(?:n|\\\\u006[Ee])(?:s|\\\\u0073)(?:t|\\\\u0074)(?:r|\\\\u0072)(?:u|\\\\u0075)(?:c|\\\\u0063)(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:r|\\\\u0072)/;\n\n/*\n json_parse.js\n 2012-06-20\n\n Public Domain.\n\n NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.\n\n This file creates a json_parse function.\n During create you can (optionally) specify some behavioural switches\n\n require('json-bigint')(options)\n\n The optional options parameter holds switches that drive certain\n aspects of the parsing process:\n * options.strict = true will warn about duplicate-key usage in the json.\n The default (strict = false) will silently ignore those and overwrite\n values for keys that are in duplicate use.\n\n The resulting function follows this signature:\n json_parse(text, reviver)\n This method parses a JSON text to produce an object or array.\n It can throw a SyntaxError exception.\n\n The optional reviver parameter is a function that can filter and\n transform the results. It receives each of the keys and values,\n and its return value is used instead of the original value.\n If it returns what it received, then the structure is not modified.\n If it returns undefined then the member is deleted.\n\n Example:\n\n // Parse the text. Values that look like ISO date strings will\n // be converted to Date objects.\n\n myData = json_parse(text, function (key, value) {\n var a;\n if (typeof value === 'string') {\n a =\n/^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}(?:\\.\\d*)?)Z$/.exec(value);\n if (a) {\n return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],\n +a[5], +a[6]));\n }\n }\n return value;\n });\n\n This is a reference implementation. You are free to copy, modify, or\n redistribute.\n\n This code should be minified before deployment.\n See http://javascript.crockford.com/jsmin.html\n\n USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO\n NOT CONTROL.\n*/\n\n/*members \"\", \"\\\"\", \"\\/\", \"\\\\\", at, b, call, charAt, f, fromCharCode,\n hasOwnProperty, message, n, name, prototype, push, r, t, text\n*/\n\nvar json_parse = function (options) {\n 'use strict';\n\n // This is a function that can parse a JSON text, producing a JavaScript\n // data structure. It is a simple, recursive descent parser. It does not use\n // eval or regular expressions, so it can be used as a model for implementing\n // a JSON parser in other languages.\n\n // We are defining the function inside of another function to avoid creating\n // global variables.\n\n // Default options one can override by passing options to the parse()\n var _options = {\n strict: false, // not being strict means do not generate syntax errors for \"duplicate key\"\n storeAsString: false, // toggles whether the values should be stored as BigNumber (default) or a string\n alwaysParseAsBig: false, // toggles whether all numbers should be Big\n useNativeBigInt: false, // toggles whether to use native BigInt instead of bignumber.js\n protoAction: 'error',\n constructorAction: 'error',\n };\n\n // If there are options, then use them to override the default _options\n if (options !== undefined && options !== null) {\n if (options.strict === true) {\n _options.strict = true;\n }\n if (options.storeAsString === true) {\n _options.storeAsString = true;\n }\n _options.alwaysParseAsBig =\n options.alwaysParseAsBig === true ? options.alwaysParseAsBig : false;\n _options.useNativeBigInt =\n options.useNativeBigInt === true ? options.useNativeBigInt : false;\n\n if (typeof options.constructorAction !== 'undefined') {\n if (\n options.constructorAction === 'error' ||\n options.constructorAction === 'ignore' ||\n options.constructorAction === 'preserve'\n ) {\n _options.constructorAction = options.constructorAction;\n } else {\n throw new Error(\n `Incorrect value for constructorAction option, must be \"error\", \"ignore\" or undefined but passed ${options.constructorAction}`\n );\n }\n }\n\n if (typeof options.protoAction !== 'undefined') {\n if (\n options.protoAction === 'error' ||\n options.protoAction === 'ignore' ||\n options.protoAction === 'preserve'\n ) {\n _options.protoAction = options.protoAction;\n } else {\n throw new Error(\n `Incorrect value for protoAction option, must be \"error\", \"ignore\" or undefined but passed ${options.protoAction}`\n );\n }\n }\n }\n\n var at, // The index of the current character\n ch, // The current character\n escapee = {\n '\"': '\"',\n '\\\\': '\\\\',\n '/': '/',\n b: '\\b',\n f: '\\f',\n n: '\\n',\n r: '\\r',\n t: '\\t',\n },\n text,\n error = function (m) {\n // Call error when something is wrong.\n\n throw {\n name: 'SyntaxError',\n message: m,\n at: at,\n text: text,\n };\n },\n next = function (c) {\n // If a c parameter is provided, verify that it matches the current character.\n\n if (c && c !== ch) {\n error(\"Expected '\" + c + \"' instead of '\" + ch + \"'\");\n }\n\n // Get the next character. When there are no more characters,\n // return the empty string.\n\n ch = text.charAt(at);\n at += 1;\n return ch;\n },\n number = function () {\n // Parse a number value.\n\n var number,\n string = '';\n\n if (ch === '-') {\n string = '-';\n next('-');\n }\n while (ch >= '0' && ch <= '9') {\n string += ch;\n next();\n }\n if (ch === '.') {\n string += '.';\n while (next() && ch >= '0' && ch <= '9') {\n string += ch;\n }\n }\n if (ch === 'e' || ch === 'E') {\n string += ch;\n next();\n if (ch === '-' || ch === '+') {\n string += ch;\n next();\n }\n while (ch >= '0' && ch <= '9') {\n string += ch;\n next();\n }\n }\n number = +string;\n if (!isFinite(number)) {\n error('Bad number');\n } else {\n if (BigNumber == null) BigNumber = require('bignumber.js');\n //if (number > 9007199254740992 || number < -9007199254740992)\n // Bignumber has stricter check: everything with length > 15 digits disallowed\n if (string.length > 15)\n return _options.storeAsString\n ? string\n : _options.useNativeBigInt\n ? BigInt(string)\n : new BigNumber(string);\n else\n return !_options.alwaysParseAsBig\n ? number\n : _options.useNativeBigInt\n ? BigInt(number)\n : new BigNumber(number);\n }\n },\n string = function () {\n // Parse a string value.\n\n var hex,\n i,\n string = '',\n uffff;\n\n // When parsing for string values, we must look for \" and \\ characters.\n\n if (ch === '\"') {\n var startAt = at;\n while (next()) {\n if (ch === '\"') {\n if (at - 1 > startAt) string += text.substring(startAt, at - 1);\n next();\n return string;\n }\n if (ch === '\\\\') {\n if (at - 1 > startAt) string += text.substring(startAt, at - 1);\n next();\n if (ch === 'u') {\n uffff = 0;\n for (i = 0; i < 4; i += 1) {\n hex = parseInt(next(), 16);\n if (!isFinite(hex)) {\n break;\n }\n uffff = uffff * 16 + hex;\n }\n string += String.fromCharCode(uffff);\n } else if (typeof escapee[ch] === 'string') {\n string += escapee[ch];\n } else {\n break;\n }\n startAt = at;\n }\n }\n }\n error('Bad string');\n },\n white = function () {\n // Skip whitespace.\n\n while (ch && ch <= ' ') {\n next();\n }\n },\n word = function () {\n // true, false, or null.\n\n switch (ch) {\n case 't':\n next('t');\n next('r');\n next('u');\n next('e');\n return true;\n case 'f':\n next('f');\n next('a');\n next('l');\n next('s');\n next('e');\n return false;\n case 'n':\n next('n');\n next('u');\n next('l');\n next('l');\n return null;\n }\n error(\"Unexpected '\" + ch + \"'\");\n },\n value, // Place holder for the value function.\n array = function () {\n // Parse an array value.\n\n var array = [];\n\n if (ch === '[') {\n next('[');\n white();\n if (ch === ']') {\n next(']');\n return array; // empty array\n }\n while (ch) {\n array.push(value());\n white();\n if (ch === ']') {\n next(']');\n return array;\n }\n next(',');\n white();\n }\n }\n error('Bad array');\n },\n object = function () {\n // Parse an object value.\n\n var key,\n object = Object.create(null);\n\n if (ch === '{') {\n next('{');\n white();\n if (ch === '}') {\n next('}');\n return object; // empty object\n }\n while (ch) {\n key = string();\n white();\n next(':');\n if (\n _options.strict === true &&\n Object.hasOwnProperty.call(object, key)\n ) {\n error('Duplicate key \"' + key + '\"');\n }\n\n if (suspectProtoRx.test(key) === true) {\n if (_options.protoAction === 'error') {\n error('Object contains forbidden prototype property');\n } else if (_options.protoAction === 'ignore') {\n value();\n } else {\n object[key] = value();\n }\n } else if (suspectConstructorRx.test(key) === true) {\n if (_options.constructorAction === 'error') {\n error('Object contains forbidden constructor property');\n } else if (_options.constructorAction === 'ignore') {\n value();\n } else {\n object[key] = value();\n }\n } else {\n object[key] = value();\n }\n\n white();\n if (ch === '}') {\n next('}');\n return object;\n }\n next(',');\n white();\n }\n }\n error('Bad object');\n };\n\n value = function () {\n // Parse a JSON value. It could be an object, an array, a string, a number,\n // or a word.\n\n white();\n switch (ch) {\n case '{':\n return object();\n case '[':\n return array();\n case '\"':\n return string();\n case '-':\n return number();\n default:\n return ch >= '0' && ch <= '9' ? number() : word();\n }\n };\n\n // Return the json_parse function. It will have access to all of the above\n // functions and variables.\n\n return function (source, reviver) {\n var result;\n\n text = source + '';\n at = 0;\n ch = ' ';\n result = value();\n white();\n if (ch) {\n error('Syntax error');\n }\n\n // If there is a reviver function, we recursively walk the new structure,\n // passing each name/value pair to the reviver function for possible\n // transformation, starting with a temporary root object that holds the result\n // in an empty key. If there is not a reviver function, we simply return the\n // result.\n\n return typeof reviver === 'function'\n ? (function walk(holder, key) {\n var k,\n v,\n value = holder[key];\n if (value && typeof value === 'object') {\n Object.keys(value).forEach(function (k) {\n v = walk(value, k);\n if (v !== undefined) {\n value[k] = v;\n } else {\n delete value[k];\n }\n });\n }\n return reviver.call(holder, key, value);\n })({ '': result }, '')\n : result;\n };\n};\n\nmodule.exports = json_parse;\n", "var json_stringify = require('./lib/stringify.js').stringify;\nvar json_parse = require('./lib/parse.js');\n\nmodule.exports = function(options) {\n return {\n parse: json_parse(options),\n stringify: json_stringify\n }\n};\n//create the default method members with no options applied for backwards compatibility\nmodule.exports.parse = json_parse();\nmodule.exports.stringify = json_stringify;\n", null, null, null, null, null, "'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n", "\"use strict\";\n// Copyright 2025 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.fromArrayBufferToHex = fromArrayBufferToHex;\n/**\n * Converts an ArrayBuffer to a hexadecimal string.\n * @param arrayBuffer The ArrayBuffer to convert to hexadecimal string.\n * @return The hexadecimal encoding of the ArrayBuffer.\n */\nfunction fromArrayBufferToHex(arrayBuffer) {\n // Convert buffer to byte array.\n const byteArray = Array.from(new Uint8Array(arrayBuffer));\n // Convert bytes to hex string.\n return byteArray\n .map(byte => {\n return byte.toString(16).padStart(2, '0');\n })\n .join('');\n}\n//# sourceMappingURL=shared.js.map", "\"use strict\";\n// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/* global window */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BrowserCrypto = void 0;\n// This file implements crypto functions we need using in-browser\n// SubtleCrypto interface `window.crypto.subtle`.\nconst base64js = require(\"base64-js\");\nconst shared_1 = require(\"../shared\");\nclass BrowserCrypto {\n constructor() {\n if (typeof window === 'undefined' ||\n window.crypto === undefined ||\n window.crypto.subtle === undefined) {\n throw new Error(\"SubtleCrypto not found. Make sure it's an https:// website.\");\n }\n }\n async sha256DigestBase64(str) {\n // SubtleCrypto digest() method is async, so we must make\n // this method async as well.\n // To calculate SHA256 digest using SubtleCrypto, we first\n // need to convert an input string to an ArrayBuffer:\n const inputBuffer = new TextEncoder().encode(str);\n // Result is ArrayBuffer as well.\n const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer);\n return base64js.fromByteArray(new Uint8Array(outputBuffer));\n }\n randomBytesBase64(count) {\n const array = new Uint8Array(count);\n window.crypto.getRandomValues(array);\n return base64js.fromByteArray(array);\n }\n static padBase64(base64) {\n // base64js requires padding, so let's add some '='\n while (base64.length % 4 !== 0) {\n base64 += '=';\n }\n return base64;\n }\n async verify(pubkey, data, signature) {\n const algo = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' },\n };\n const dataArray = new TextEncoder().encode(data);\n const signatureArray = base64js.toByteArray(BrowserCrypto.padBase64(signature));\n const cryptoKey = await window.crypto.subtle.importKey('jwk', pubkey, algo, true, ['verify']);\n // SubtleCrypto's verify method is async so we must make\n // this method async as well.\n const result = await window.crypto.subtle.verify(algo, cryptoKey, signatureArray, dataArray);\n return result;\n }\n async sign(privateKey, data) {\n const algo = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' },\n };\n const dataArray = new TextEncoder().encode(data);\n const cryptoKey = await window.crypto.subtle.importKey('jwk', privateKey, algo, true, ['sign']);\n // SubtleCrypto's sign method is async so we must make\n // this method async as well.\n const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray);\n return base64js.fromByteArray(new Uint8Array(result));\n }\n decodeBase64StringUtf8(base64) {\n const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base64));\n const result = new TextDecoder().decode(uint8array);\n return result;\n }\n encodeBase64StringUtf8(text) {\n const uint8array = new TextEncoder().encode(text);\n const result = base64js.fromByteArray(uint8array);\n return result;\n }\n /**\n * Computes the SHA-256 hash of the provided string.\n * @param str The plain text string to hash.\n * @return A promise that resolves with the SHA-256 hash of the provided\n * string in hexadecimal encoding.\n */\n async sha256DigestHex(str) {\n // SubtleCrypto digest() method is async, so we must make\n // this method async as well.\n // To calculate SHA256 digest using SubtleCrypto, we first\n // need to convert an input string to an ArrayBuffer:\n const inputBuffer = new TextEncoder().encode(str);\n // Result is ArrayBuffer as well.\n const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer);\n return (0, shared_1.fromArrayBufferToHex)(outputBuffer);\n }\n /**\n * Computes the HMAC hash of a message using the provided crypto key and the\n * SHA-256 algorithm.\n * @param key The secret crypto key in utf-8 or ArrayBuffer format.\n * @param msg The plain text message.\n * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer\n * format.\n */\n async signWithHmacSha256(key, msg) {\n // Convert key, if provided in ArrayBuffer format, to string.\n const rawKey = typeof key === 'string'\n ? key\n : String.fromCharCode(...new Uint16Array(key));\n const enc = new TextEncoder();\n const cryptoKey = await window.crypto.subtle.importKey('raw', enc.encode(rawKey), {\n name: 'HMAC',\n hash: {\n name: 'SHA-256',\n },\n }, false, ['sign']);\n return window.crypto.subtle.sign('HMAC', cryptoKey, enc.encode(msg));\n }\n}\nexports.BrowserCrypto = BrowserCrypto;\n//# sourceMappingURL=crypto.js.map", "\"use strict\";\n// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.NodeCrypto = void 0;\nconst crypto = require(\"crypto\");\nclass NodeCrypto {\n async sha256DigestBase64(str) {\n return crypto.createHash('sha256').update(str).digest('base64');\n }\n randomBytesBase64(count) {\n return crypto.randomBytes(count).toString('base64');\n }\n async verify(pubkey, data, signature) {\n const verifier = crypto.createVerify('RSA-SHA256');\n verifier.update(data);\n verifier.end();\n return verifier.verify(pubkey, signature, 'base64');\n }\n async sign(privateKey, data) {\n const signer = crypto.createSign('RSA-SHA256');\n signer.update(data);\n signer.end();\n return signer.sign(privateKey, 'base64');\n }\n decodeBase64StringUtf8(base64) {\n return Buffer.from(base64, 'base64').toString('utf-8');\n }\n encodeBase64StringUtf8(text) {\n return Buffer.from(text, 'utf-8').toString('base64');\n }\n /**\n * Computes the SHA-256 hash of the provided string.\n * @param str The plain text string to hash.\n * @return A promise that resolves with the SHA-256 hash of the provided\n * string in hexadecimal encoding.\n */\n async sha256DigestHex(str) {\n return crypto.createHash('sha256').update(str).digest('hex');\n }\n /**\n * Computes the HMAC hash of a message using the provided crypto key and the\n * SHA-256 algorithm.\n * @param key The secret crypto key in utf-8 or ArrayBuffer format.\n * @param msg The plain text message.\n * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer\n * format.\n */\n async signWithHmacSha256(key, msg) {\n const cryptoKey = typeof key === 'string' ? key : toBuffer(key);\n return toArrayBuffer(crypto.createHmac('sha256', cryptoKey).update(msg).digest());\n }\n}\nexports.NodeCrypto = NodeCrypto;\n/**\n * Converts a Node.js Buffer to an ArrayBuffer.\n * https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer\n * @param buffer The Buffer input to covert.\n * @return The ArrayBuffer representation of the input.\n */\nfunction toArrayBuffer(buffer) {\n return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);\n}\n/**\n * Converts an ArrayBuffer to a Node.js Buffer.\n * @param arrayBuffer The ArrayBuffer input to covert.\n * @return The Buffer representation of the input.\n */\nfunction toBuffer(arrayBuffer) {\n return Buffer.from(arrayBuffer);\n}\n//# sourceMappingURL=crypto.js.map", "\"use strict\";\n// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/* global window */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createCrypto = createCrypto;\nexports.hasBrowserCrypto = hasBrowserCrypto;\nconst crypto_1 = require(\"./browser/crypto\");\nconst crypto_2 = require(\"./node/crypto\");\n__exportStar(require(\"./shared\"), exports);\n// Crypto interface will provide required crypto functions.\n// Use `createCrypto()` factory function to create an instance\n// of Crypto. It will either use Node.js `crypto` module, or\n// use browser's SubtleCrypto interface. Since most of the\n// SubtleCrypto methods return promises, we must make those\n// methods return promises here as well, even though in Node.js\n// they are synchronous.\nfunction createCrypto() {\n if (hasBrowserCrypto()) {\n return new crypto_1.BrowserCrypto();\n }\n return new crypto_2.NodeCrypto();\n}\nfunction hasBrowserCrypto() {\n return (typeof window !== 'undefined' &&\n typeof window.crypto !== 'undefined' &&\n typeof window.crypto.subtle !== 'undefined');\n}\n//# sourceMappingURL=crypto.js.map", "/*! safe-buffer. MIT License. Feross Aboukhadijeh */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n", "'use strict';\n\nfunction getParamSize(keySize) {\n\tvar result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1);\n\treturn result;\n}\n\nvar paramBytesForAlg = {\n\tES256: getParamSize(256),\n\tES384: getParamSize(384),\n\tES512: getParamSize(521)\n};\n\nfunction getParamBytesForAlg(alg) {\n\tvar paramBytes = paramBytesForAlg[alg];\n\tif (paramBytes) {\n\t\treturn paramBytes;\n\t}\n\n\tthrow new Error('Unknown algorithm \"' + alg + '\"');\n}\n\nmodule.exports = getParamBytesForAlg;\n", "'use strict';\n\nvar Buffer = require('safe-buffer').Buffer;\n\nvar getParamBytesForAlg = require('./param-bytes-for-alg');\n\nvar MAX_OCTET = 0x80,\n\tCLASS_UNIVERSAL = 0,\n\tPRIMITIVE_BIT = 0x20,\n\tTAG_SEQ = 0x10,\n\tTAG_INT = 0x02,\n\tENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6),\n\tENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6);\n\nfunction base64Url(base64) {\n\treturn base64\n\t\t.replace(/=/g, '')\n\t\t.replace(/\\+/g, '-')\n\t\t.replace(/\\//g, '_');\n}\n\nfunction signatureAsBuffer(signature) {\n\tif (Buffer.isBuffer(signature)) {\n\t\treturn signature;\n\t} else if ('string' === typeof signature) {\n\t\treturn Buffer.from(signature, 'base64');\n\t}\n\n\tthrow new TypeError('ECDSA signature must be a Base64 string or a Buffer');\n}\n\nfunction derToJose(signature, alg) {\n\tsignature = signatureAsBuffer(signature);\n\tvar paramBytes = getParamBytesForAlg(alg);\n\n\t// the DER encoded param should at most be the param size, plus a padding\n\t// zero, since due to being a signed integer\n\tvar maxEncodedParamLength = paramBytes + 1;\n\n\tvar inputLength = signature.length;\n\n\tvar offset = 0;\n\tif (signature[offset++] !== ENCODED_TAG_SEQ) {\n\t\tthrow new Error('Could not find expected \"seq\"');\n\t}\n\n\tvar seqLength = signature[offset++];\n\tif (seqLength === (MAX_OCTET | 1)) {\n\t\tseqLength = signature[offset++];\n\t}\n\n\tif (inputLength - offset < seqLength) {\n\t\tthrow new Error('\"seq\" specified length of \"' + seqLength + '\", only \"' + (inputLength - offset) + '\" remaining');\n\t}\n\n\tif (signature[offset++] !== ENCODED_TAG_INT) {\n\t\tthrow new Error('Could not find expected \"int\" for \"r\"');\n\t}\n\n\tvar rLength = signature[offset++];\n\n\tif (inputLength - offset - 2 < rLength) {\n\t\tthrow new Error('\"r\" specified length of \"' + rLength + '\", only \"' + (inputLength - offset - 2) + '\" available');\n\t}\n\n\tif (maxEncodedParamLength < rLength) {\n\t\tthrow new Error('\"r\" specified length of \"' + rLength + '\", max of \"' + maxEncodedParamLength + '\" is acceptable');\n\t}\n\n\tvar rOffset = offset;\n\toffset += rLength;\n\n\tif (signature[offset++] !== ENCODED_TAG_INT) {\n\t\tthrow new Error('Could not find expected \"int\" for \"s\"');\n\t}\n\n\tvar sLength = signature[offset++];\n\n\tif (inputLength - offset !== sLength) {\n\t\tthrow new Error('\"s\" specified length of \"' + sLength + '\", expected \"' + (inputLength - offset) + '\"');\n\t}\n\n\tif (maxEncodedParamLength < sLength) {\n\t\tthrow new Error('\"s\" specified length of \"' + sLength + '\", max of \"' + maxEncodedParamLength + '\" is acceptable');\n\t}\n\n\tvar sOffset = offset;\n\toffset += sLength;\n\n\tif (offset !== inputLength) {\n\t\tthrow new Error('Expected to consume entire buffer, but \"' + (inputLength - offset) + '\" bytes remain');\n\t}\n\n\tvar rPadding = paramBytes - rLength,\n\t\tsPadding = paramBytes - sLength;\n\n\tvar dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength);\n\n\tfor (offset = 0; offset < rPadding; ++offset) {\n\t\tdst[offset] = 0;\n\t}\n\tsignature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength);\n\n\toffset = paramBytes;\n\n\tfor (var o = offset; offset < o + sPadding; ++offset) {\n\t\tdst[offset] = 0;\n\t}\n\tsignature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength);\n\n\tdst = dst.toString('base64');\n\tdst = base64Url(dst);\n\n\treturn dst;\n}\n\nfunction countPadding(buf, start, stop) {\n\tvar padding = 0;\n\twhile (start + padding < stop && buf[start + padding] === 0) {\n\t\t++padding;\n\t}\n\n\tvar needsSign = buf[start + padding] >= MAX_OCTET;\n\tif (needsSign) {\n\t\t--padding;\n\t}\n\n\treturn padding;\n}\n\nfunction joseToDer(signature, alg) {\n\tsignature = signatureAsBuffer(signature);\n\tvar paramBytes = getParamBytesForAlg(alg);\n\n\tvar signatureBytes = signature.length;\n\tif (signatureBytes !== paramBytes * 2) {\n\t\tthrow new TypeError('\"' + alg + '\" signatures must be \"' + paramBytes * 2 + '\" bytes, saw \"' + signatureBytes + '\"');\n\t}\n\n\tvar rPadding = countPadding(signature, 0, paramBytes);\n\tvar sPadding = countPadding(signature, paramBytes, signature.length);\n\tvar rLength = paramBytes - rPadding;\n\tvar sLength = paramBytes - sPadding;\n\n\tvar rsBytes = 1 + 1 + rLength + 1 + 1 + sLength;\n\n\tvar shortLength = rsBytes < MAX_OCTET;\n\n\tvar dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes);\n\n\tvar offset = 0;\n\tdst[offset++] = ENCODED_TAG_SEQ;\n\tif (shortLength) {\n\t\t// Bit 8 has value \"0\"\n\t\t// bits 7-1 give the length.\n\t\tdst[offset++] = rsBytes;\n\t} else {\n\t\t// Bit 8 of first octet has value \"1\"\n\t\t// bits 7-1 give the number of additional length octets.\n\t\tdst[offset++] = MAX_OCTET\t| 1;\n\t\t// length, base 256\n\t\tdst[offset++] = rsBytes & 0xff;\n\t}\n\tdst[offset++] = ENCODED_TAG_INT;\n\tdst[offset++] = rLength;\n\tif (rPadding < 0) {\n\t\tdst[offset++] = 0;\n\t\toffset += signature.copy(dst, offset, 0, paramBytes);\n\t} else {\n\t\toffset += signature.copy(dst, offset, rPadding, paramBytes);\n\t}\n\tdst[offset++] = ENCODED_TAG_INT;\n\tdst[offset++] = sLength;\n\tif (sPadding < 0) {\n\t\tdst[offset++] = 0;\n\t\tsignature.copy(dst, offset, paramBytes);\n\t} else {\n\t\tsignature.copy(dst, offset, paramBytes + sPadding);\n\t}\n\n\treturn dst;\n}\n\nmodule.exports = {\n\tderToJose: derToJose,\n\tjoseToDer: joseToDer\n};\n", "\"use strict\";\n// Copyright 2023 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LRUCache = void 0;\nexports.snakeToCamel = snakeToCamel;\nexports.originalOrCamelOptions = originalOrCamelOptions;\nexports.removeUndefinedValuesInObject = removeUndefinedValuesInObject;\nexports.isValidFile = isValidFile;\nexports.getWellKnownCertificateConfigFileLocation = getWellKnownCertificateConfigFileLocation;\nconst fs = require(\"fs\");\nconst os = require(\"os\");\nconst path = require(\"path\");\nconst WELL_KNOWN_CERTIFICATE_CONFIG_FILE = 'certificate_config.json';\nconst CLOUDSDK_CONFIG_DIRECTORY = 'gcloud';\n/**\n * Returns the camel case of a provided string.\n *\n * @remarks\n *\n * Match any `_` and not `_` pair, then return the uppercase of the not `_`\n * character.\n *\n * @param str the string to convert\n * @returns the camelCase'd string\n */\nfunction snakeToCamel(str) {\n return str.replace(/([_][^_])/g, match => match.slice(1).toUpperCase());\n}\n/**\n * Get the value of `obj[key]` or `obj[camelCaseKey]`, with a preference\n * for original, non-camelCase key.\n *\n * @param obj object to lookup a value in\n * @returns a `get` function for getting `obj[key || snakeKey]`, if available\n */\nfunction originalOrCamelOptions(obj) {\n /**\n *\n * @param key an index of object, preferably snake_case\n * @returns the value `obj[key || snakeKey]`, if available\n */\n function get(key) {\n const o = (obj || {});\n return o[key] ?? o[snakeToCamel(key)];\n }\n return { get };\n}\n/**\n * A simple LRU cache utility.\n * Not meant for external usage.\n *\n * @experimental\n */\nclass LRUCache {\n capacity;\n /**\n * Maps are in order. Thus, the older item is the first item.\n *\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map}\n */\n #cache = new Map();\n maxAge;\n constructor(options) {\n this.capacity = options.capacity;\n this.maxAge = options.maxAge;\n }\n /**\n * Moves the key to the end of the cache.\n *\n * @param key the key to move\n * @param value the value of the key\n */\n #moveToEnd(key, value) {\n this.#cache.delete(key);\n this.#cache.set(key, {\n value,\n lastAccessed: Date.now(),\n });\n }\n /**\n * Add an item to the cache.\n *\n * @param key the key to upsert\n * @param value the value of the key\n */\n set(key, value) {\n this.#moveToEnd(key, value);\n this.#evict();\n }\n /**\n * Get an item from the cache.\n *\n * @param key the key to retrieve\n */\n get(key) {\n const item = this.#cache.get(key);\n if (!item)\n return;\n this.#moveToEnd(key, item.value);\n this.#evict();\n return item.value;\n }\n /**\n * Maintain the cache based on capacity and TTL.\n */\n #evict() {\n const cutoffDate = this.maxAge ? Date.now() - this.maxAge : 0;\n /**\n * Because we know Maps are in order, this item is both the\n * last item in the list (capacity) and oldest (maxAge).\n */\n let oldestItem = this.#cache.entries().next();\n while (!oldestItem.done &&\n (this.#cache.size > this.capacity || // too many\n oldestItem.value[1].lastAccessed < cutoffDate) // too old\n ) {\n this.#cache.delete(oldestItem.value[0]);\n oldestItem = this.#cache.entries().next();\n }\n }\n}\nexports.LRUCache = LRUCache;\n// Given and object remove fields where value is undefined.\nfunction removeUndefinedValuesInObject(object) {\n Object.entries(object).forEach(([key, value]) => {\n if (value === undefined || value === 'undefined') {\n delete object[key];\n }\n });\n return object;\n}\n/**\n * Helper to check if a path points to a valid file.\n */\nasync function isValidFile(filePath) {\n try {\n const stats = await fs.promises.lstat(filePath);\n return stats.isFile();\n }\n catch (e) {\n return false;\n }\n}\n/**\n * Determines the well-known gcloud location for the certificate config file.\n * @returns The platform-specific path to the configuration file.\n * @internal\n */\nfunction getWellKnownCertificateConfigFileLocation() {\n const configDir = process.env.CLOUDSDK_CONFIG ||\n (_isWindows()\n ? path.join(process.env.APPDATA || '', CLOUDSDK_CONFIG_DIRECTORY)\n : path.join(process.env.HOME || '', '.config', CLOUDSDK_CONFIG_DIRECTORY));\n return path.join(configDir, WELL_KNOWN_CERTIFICATE_CONFIG_FILE);\n}\n/**\n * Checks if the current operating system is Windows.\n * @returns True if the OS is Windows, false otherwise.\n * @internal\n */\nfunction _isWindows() {\n return os.platform().startsWith('win');\n}\n//# sourceMappingURL=util.js.map", "{\n \"name\": \"google-auth-library\",\n \"version\": \"10.2.0\",\n \"author\": \"Google Inc.\",\n \"description\": \"Google APIs Authentication Client Library for Node.js\",\n \"engines\": {\n \"node\": \">=18\"\n },\n \"main\": \"./build/src/index.js\",\n \"types\": \"./build/src/index.d.ts\",\n \"repository\": \"googleapis/google-auth-library-nodejs.git\",\n \"keywords\": [\n \"google\",\n \"api\",\n \"google apis\",\n \"client\",\n \"client library\"\n ],\n \"dependencies\": {\n \"base64-js\": \"^1.3.0\",\n \"ecdsa-sig-formatter\": \"^1.0.11\",\n \"gaxios\": \"^7.0.0\",\n \"gcp-metadata\": \"^7.0.0\",\n \"google-logging-utils\": \"^1.0.0\",\n \"gtoken\": \"^8.0.0\",\n \"jws\": \"^4.0.0\"\n },\n \"devDependencies\": {\n \"@types/base64-js\": \"^1.2.5\",\n \"@types/jws\": \"^3.1.0\",\n \"@types/mocha\": \"^10.0.10\",\n \"@types/mv\": \"^2.1.0\",\n \"@types/ncp\": \"^2.0.1\",\n \"@types/node\": \"^22.0.0\",\n \"@types/sinon\": \"^17.0.0\",\n \"assert-rejects\": \"^1.0.0\",\n \"c8\": \"^10.0.0\",\n \"codecov\": \"^3.0.2\",\n \"gts\": \"^6.0.0\",\n \"is-docker\": \"^3.0.0\",\n \"jsdoc\": \"^4.0.0\",\n \"jsdoc-fresh\": \"^4.0.0\",\n \"jsdoc-region-tag\": \"^3.0.0\",\n \"karma\": \"^6.0.0\",\n \"karma-chrome-launcher\": \"^3.0.0\",\n \"karma-coverage\": \"^2.0.0\",\n \"karma-firefox-launcher\": \"^2.0.0\",\n \"karma-mocha\": \"^2.0.0\",\n \"karma-sourcemap-loader\": \"^0.4.0\",\n \"karma-webpack\": \"^5.0.1\",\n \"keypair\": \"^1.0.4\",\n \"linkinator\": \"^6.1.2\",\n \"mocha\": \"^11.1.0\",\n \"mv\": \"^2.1.1\",\n \"ncp\": \"^2.0.0\",\n \"nock\": \"^14.0.1\",\n \"null-loader\": \"^4.0.0\",\n \"puppeteer\": \"^24.0.0\",\n \"sinon\": \"^21.0.0\",\n \"ts-loader\": \"^8.0.0\",\n \"typescript\": \"^5.1.6\",\n \"webpack\": \"^5.21.2\",\n \"webpack-cli\": \"^4.0.0\"\n },\n \"files\": [\n \"build/src\",\n \"!build/src/**/*.map\"\n ],\n \"scripts\": {\n \"test\": \"c8 mocha build/test\",\n \"clean\": \"gts clean\",\n \"prepare\": \"npm run compile\",\n \"lint\": \"gts check --no-inline-config\",\n \"compile\": \"tsc -p .\",\n \"fix\": \"gts fix\",\n \"pretest\": \"npm run compile -- --sourceMap\",\n \"docs\": \"jsdoc -c .jsdoc.js\",\n \"samples-setup\": \"cd samples/ && npm link ../ && npm run setup && cd ../\",\n \"samples-test\": \"cd samples/ && npm link ../ && npm test && cd ../\",\n \"system-test\": \"mocha build/system-test --timeout 60000\",\n \"presystem-test\": \"npm run compile -- --sourceMap\",\n \"webpack\": \"webpack\",\n \"browser-test\": \"karma start\",\n \"docs-test\": \"linkinator docs\",\n \"predocs-test\": \"npm run docs\",\n \"prelint\": \"cd samples; npm link ../; npm install\"\n },\n \"license\": \"Apache-2.0\"\n}\n", "\"use strict\";\n// Copyright 2023 Google LLC\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.USER_AGENT = exports.PRODUCT_NAME = exports.pkg = void 0;\nconst pkg = require('../../package.json');\nexports.pkg = pkg;\nconst PRODUCT_NAME = 'google-api-nodejs-client';\nexports.PRODUCT_NAME = PRODUCT_NAME;\nconst USER_AGENT = `${PRODUCT_NAME}/${pkg.version}`;\nexports.USER_AGENT = USER_AGENT;\n//# sourceMappingURL=shared.cjs.map", "\"use strict\";\n// Copyright 2012 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AuthClient = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = exports.DEFAULT_UNIVERSE = void 0;\nconst events_1 = require(\"events\");\nconst gaxios_1 = require(\"gaxios\");\nconst util_1 = require(\"../util\");\nconst google_logging_utils_1 = require(\"google-logging-utils\");\nconst shared_cjs_1 = require(\"../shared.cjs\");\n/**\n * The default cloud universe\n *\n * @see {@link AuthJSONOptions.universe_domain}\n */\nexports.DEFAULT_UNIVERSE = 'googleapis.com';\n/**\n * The default {@link AuthClientOptions.eagerRefreshThresholdMillis}\n */\nexports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = 5 * 60 * 1000;\n/**\n * The base of all Auth Clients.\n */\nclass AuthClient extends events_1.EventEmitter {\n apiKey;\n projectId;\n /**\n * The quota project ID. The quota project can be used by client libraries for the billing purpose.\n * See {@link https://cloud.google.com/docs/quota Working with quotas}\n */\n quotaProjectId;\n /**\n * The {@link Gaxios `Gaxios`} instance used for making requests.\n */\n transporter;\n credentials = {};\n eagerRefreshThresholdMillis = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;\n forceRefreshOnFailure = false;\n universeDomain = exports.DEFAULT_UNIVERSE;\n /**\n * Symbols that can be added to GaxiosOptions to specify the method name that is\n * making an RPC call, for logging purposes, as well as a string ID that can be\n * used to correlate calls and responses.\n */\n static RequestMethodNameSymbol = Symbol('request method name');\n static RequestLogIdSymbol = Symbol('request log id');\n constructor(opts = {}) {\n super();\n const options = (0, util_1.originalOrCamelOptions)(opts);\n // Shared auth options\n this.apiKey = opts.apiKey;\n this.projectId = options.get('project_id') ?? null;\n this.quotaProjectId = options.get('quota_project_id');\n this.credentials = options.get('credentials') ?? {};\n this.universeDomain = options.get('universe_domain') ?? exports.DEFAULT_UNIVERSE;\n // Shared client options\n this.transporter = opts.transporter ?? new gaxios_1.Gaxios(opts.transporterOptions);\n if (options.get('useAuthRequestParameters') !== false) {\n this.transporter.interceptors.request.add(AuthClient.DEFAULT_REQUEST_INTERCEPTOR);\n this.transporter.interceptors.response.add(AuthClient.DEFAULT_RESPONSE_INTERCEPTOR);\n }\n if (opts.eagerRefreshThresholdMillis) {\n this.eagerRefreshThresholdMillis = opts.eagerRefreshThresholdMillis;\n }\n this.forceRefreshOnFailure = opts.forceRefreshOnFailure ?? false;\n }\n /**\n * A {@link fetch `fetch`} compliant API for {@link AuthClient}.\n *\n * @see {@link AuthClient.request} for the classic method.\n *\n * @remarks\n *\n * This is useful as a drop-in replacement for `fetch` API usage.\n *\n * @example\n *\n * ```ts\n * const authClient = new AuthClient();\n * const fetchWithAuthClient: typeof fetch = (...args) => authClient.fetch(...args);\n * await fetchWithAuthClient('https://example.com');\n * ```\n *\n * @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters\n * @returns the {@link GaxiosResponse} with Gaxios-added properties\n */\n fetch(...args) {\n // Up to 2 parameters in either overload\n const input = args[0];\n const init = args[1];\n let url = undefined;\n const headers = new Headers();\n // prepare URL\n if (typeof input === 'string') {\n url = new URL(input);\n }\n else if (input instanceof URL) {\n url = input;\n }\n else if (input && input.url) {\n url = new URL(input.url);\n }\n // prepare headers\n if (input && typeof input === 'object' && 'headers' in input) {\n gaxios_1.Gaxios.mergeHeaders(headers, input.headers);\n }\n if (init) {\n gaxios_1.Gaxios.mergeHeaders(headers, new Headers(init.headers));\n }\n // prepare request\n if (typeof input === 'object' && !(input instanceof URL)) {\n // input must have been a non-URL object\n return this.request({ ...init, ...input, headers, url });\n }\n else {\n // input must have been a string or URL\n return this.request({ ...init, headers, url });\n }\n }\n /**\n * Sets the auth credentials.\n */\n setCredentials(credentials) {\n this.credentials = credentials;\n }\n /**\n * Append additional headers, e.g., x-goog-user-project, shared across the\n * classes inheriting AuthClient. This method should be used by any method\n * that overrides getRequestMetadataAsync(), which is a shared helper for\n * setting request information in both gRPC and HTTP API calls.\n *\n * @param headers object to append additional headers to.\n */\n addSharedMetadataHeaders(headers) {\n // quota_project_id, stored in application_default_credentials.json, is set in\n // the x-goog-user-project header, to indicate an alternate account for\n // billing and quota:\n if (!headers.has('x-goog-user-project') && // don't override a value the user sets.\n this.quotaProjectId) {\n headers.set('x-goog-user-project', this.quotaProjectId);\n }\n return headers;\n }\n /**\n * Adds the `x-goog-user-project` and `authorization` headers to the target Headers\n * object, if they exist on the source.\n *\n * @param target the headers to target\n * @param source the headers to source from\n * @returns the target headers\n */\n addUserProjectAndAuthHeaders(target, source) {\n const xGoogUserProject = source.get('x-goog-user-project');\n const authorizationHeader = source.get('authorization');\n if (xGoogUserProject) {\n target.set('x-goog-user-project', xGoogUserProject);\n }\n if (authorizationHeader) {\n target.set('authorization', authorizationHeader);\n }\n return target;\n }\n static log = (0, google_logging_utils_1.log)('auth');\n static DEFAULT_REQUEST_INTERCEPTOR = {\n resolved: async (config) => {\n // Set `x-goog-api-client`, if not already set\n if (!config.headers.has('x-goog-api-client')) {\n const nodeVersion = process.version.replace(/^v/, '');\n config.headers.set('x-goog-api-client', `gl-node/${nodeVersion}`);\n }\n // Set `User-Agent`\n const userAgent = config.headers.get('User-Agent');\n if (!userAgent) {\n config.headers.set('User-Agent', shared_cjs_1.USER_AGENT);\n }\n else if (!userAgent.includes(`${shared_cjs_1.PRODUCT_NAME}/`)) {\n config.headers.set('User-Agent', `${userAgent} ${shared_cjs_1.USER_AGENT}`);\n }\n try {\n const symbols = config;\n const methodName = symbols[AuthClient.RequestMethodNameSymbol];\n // This doesn't need to be very unique or interesting, it's just an aid for\n // matching requests to responses.\n const logId = `${Math.floor(Math.random() * 1000)}`;\n symbols[AuthClient.RequestLogIdSymbol] = logId;\n // Boil down the object we're printing out.\n const logObject = {\n url: config.url,\n headers: config.headers,\n };\n if (methodName) {\n AuthClient.log.info('%s [%s] request %j', methodName, logId, logObject);\n }\n else {\n AuthClient.log.info('[%s] request %j', logId, logObject);\n }\n }\n catch (e) {\n // Logging must not create new errors; swallow them all.\n }\n return config;\n },\n };\n static DEFAULT_RESPONSE_INTERCEPTOR = {\n resolved: async (response) => {\n try {\n const symbols = response.config;\n const methodName = symbols[AuthClient.RequestMethodNameSymbol];\n const logId = symbols[AuthClient.RequestLogIdSymbol];\n if (methodName) {\n AuthClient.log.info('%s [%s] response %j', methodName, logId, response.data);\n }\n else {\n AuthClient.log.info('[%s] response %j', logId, response.data);\n }\n }\n catch (e) {\n // Logging must not create new errors; swallow them all.\n }\n return response;\n },\n rejected: async (error) => {\n try {\n const symbols = error.config;\n const methodName = symbols[AuthClient.RequestMethodNameSymbol];\n const logId = symbols[AuthClient.RequestLogIdSymbol];\n if (methodName) {\n AuthClient.log.info('%s [%s] error %j', methodName, logId, error.response?.data);\n }\n else {\n AuthClient.log.error('[%s] error %j', logId, error.response?.data);\n }\n }\n catch (e) {\n // Logging must not create new errors; swallow them all.\n }\n // Re-throw the error.\n throw error;\n },\n };\n /**\n * Sets the method name that is making a Gaxios request, so that logging may tag\n * log lines with the operation.\n * @param config A Gaxios request config\n * @param methodName The method name making the call\n */\n static setMethodName(config, methodName) {\n try {\n const symbols = config;\n symbols[AuthClient.RequestMethodNameSymbol] = methodName;\n }\n catch (e) {\n // Logging must not create new errors; swallow them all.\n }\n }\n /**\n * Retry config for Auth-related requests.\n *\n * @remarks\n *\n * This is not a part of the default {@link AuthClient.transporter transporter/gaxios}\n * config as some downstream APIs would prefer if customers explicitly enable retries,\n * such as GCS.\n */\n static get RETRY_CONFIG() {\n return {\n retry: true,\n retryConfig: {\n httpMethodsToRetry: ['GET', 'PUT', 'POST', 'HEAD', 'OPTIONS', 'DELETE'],\n },\n };\n }\n}\nexports.AuthClient = AuthClient;\n//# sourceMappingURL=authclient.js.map", "\"use strict\";\n// Copyright 2014 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LoginTicket = void 0;\nclass LoginTicket {\n envelope;\n payload;\n /**\n * Create a simple class to extract user ID from an ID Token\n *\n * @param {string} env Envelope of the jwt\n * @param {TokenPayload} pay Payload of the jwt\n * @constructor\n */\n constructor(env, pay) {\n this.envelope = env;\n this.payload = pay;\n }\n getEnvelope() {\n return this.envelope;\n }\n getPayload() {\n return this.payload;\n }\n /**\n * Create a simple class to extract user ID from an ID Token\n *\n * @return The user ID\n */\n getUserId() {\n const payload = this.getPayload();\n if (payload && payload.sub) {\n return payload.sub;\n }\n return null;\n }\n /**\n * Returns attributes from the login ticket. This can contain\n * various information about the user session.\n *\n * @return The envelope and payload\n */\n getAttributes() {\n return { envelope: this.getEnvelope(), payload: this.getPayload() };\n }\n}\nexports.LoginTicket = LoginTicket;\n//# sourceMappingURL=loginticket.js.map", "\"use strict\";\n// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.OAuth2Client = exports.ClientAuthentication = exports.CertificateFormat = exports.CodeChallengeMethod = void 0;\nconst gaxios_1 = require(\"gaxios\");\nconst querystring = require(\"querystring\");\nconst stream = require(\"stream\");\nconst formatEcdsa = require(\"ecdsa-sig-formatter\");\nconst util_1 = require(\"../util\");\nconst crypto_1 = require(\"../crypto/crypto\");\nconst authclient_1 = require(\"./authclient\");\nconst loginticket_1 = require(\"./loginticket\");\nvar CodeChallengeMethod;\n(function (CodeChallengeMethod) {\n CodeChallengeMethod[\"Plain\"] = \"plain\";\n CodeChallengeMethod[\"S256\"] = \"S256\";\n})(CodeChallengeMethod || (exports.CodeChallengeMethod = CodeChallengeMethod = {}));\nvar CertificateFormat;\n(function (CertificateFormat) {\n CertificateFormat[\"PEM\"] = \"PEM\";\n CertificateFormat[\"JWK\"] = \"JWK\";\n})(CertificateFormat || (exports.CertificateFormat = CertificateFormat = {}));\n/**\n * The client authentication type. Supported values are basic, post, and none.\n * https://datatracker.ietf.org/doc/html/rfc7591#section-2\n */\nvar ClientAuthentication;\n(function (ClientAuthentication) {\n ClientAuthentication[\"ClientSecretPost\"] = \"ClientSecretPost\";\n ClientAuthentication[\"ClientSecretBasic\"] = \"ClientSecretBasic\";\n ClientAuthentication[\"None\"] = \"None\";\n})(ClientAuthentication || (exports.ClientAuthentication = ClientAuthentication = {}));\nclass OAuth2Client extends authclient_1.AuthClient {\n redirectUri;\n certificateCache = {};\n certificateExpiry = null;\n certificateCacheFormat = CertificateFormat.PEM;\n refreshTokenPromises = new Map();\n endpoints;\n issuers;\n clientAuthentication;\n // TODO: refactor tests to make this private\n _clientId;\n // TODO: refactor tests to make this private\n _clientSecret;\n refreshHandler;\n /**\n * An OAuth2 Client for Google APIs.\n *\n * @param options The OAuth2 Client Options. Passing an `clientId` directly is **@DEPRECATED**.\n * @param clientSecret **@DEPRECATED**. Provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead.\n * @param redirectUri **@DEPRECATED**. Provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead.\n */\n constructor(options = {}, \n /**\n * @deprecated - provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead\n */\n clientSecret, \n /**\n * @deprecated - provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead\n */\n redirectUri) {\n super(typeof options === 'object' ? options : {});\n if (typeof options !== 'object') {\n options = {\n clientId: options,\n clientSecret,\n redirectUri,\n };\n }\n this._clientId = options.clientId || options.client_id;\n this._clientSecret = options.clientSecret || options.client_secret;\n this.redirectUri = options.redirectUri || options.redirect_uris?.[0];\n this.endpoints = {\n tokenInfoUrl: 'https://oauth2.googleapis.com/tokeninfo',\n oauth2AuthBaseUrl: 'https://accounts.google.com/o/oauth2/v2/auth',\n oauth2TokenUrl: 'https://oauth2.googleapis.com/token',\n oauth2RevokeUrl: 'https://oauth2.googleapis.com/revoke',\n oauth2FederatedSignonPemCertsUrl: 'https://www.googleapis.com/oauth2/v1/certs',\n oauth2FederatedSignonJwkCertsUrl: 'https://www.googleapis.com/oauth2/v3/certs',\n oauth2IapPublicKeyUrl: 'https://www.gstatic.com/iap/verify/public_key',\n ...options.endpoints,\n };\n this.clientAuthentication =\n options.clientAuthentication || ClientAuthentication.ClientSecretPost;\n this.issuers = options.issuers || [\n 'accounts.google.com',\n 'https://accounts.google.com',\n this.universeDomain,\n ];\n }\n /**\n * @deprecated use instance's {@link OAuth2Client.endpoints}\n */\n static GOOGLE_TOKEN_INFO_URL = 'https://oauth2.googleapis.com/tokeninfo';\n /**\n * Clock skew - five minutes in seconds\n */\n static CLOCK_SKEW_SECS_ = 300;\n /**\n * The default max Token Lifetime is one day in seconds\n */\n static DEFAULT_MAX_TOKEN_LIFETIME_SECS_ = 86400;\n /**\n * Generates URL for consent page landing.\n * @param opts Options.\n * @return URL to consent page.\n */\n generateAuthUrl(opts = {}) {\n if (opts.code_challenge_method && !opts.code_challenge) {\n throw new Error('If a code_challenge_method is provided, code_challenge must be included.');\n }\n opts.response_type = opts.response_type || 'code';\n opts.client_id = opts.client_id || this._clientId;\n opts.redirect_uri = opts.redirect_uri || this.redirectUri;\n // Allow scopes to be passed either as array or a string\n if (Array.isArray(opts.scope)) {\n opts.scope = opts.scope.join(' ');\n }\n const rootUrl = this.endpoints.oauth2AuthBaseUrl.toString();\n return (rootUrl +\n '?' +\n querystring.stringify(opts));\n }\n generateCodeVerifier() {\n // To make the code compatible with browser SubtleCrypto we need to make\n // this method async.\n throw new Error('generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.');\n }\n /**\n * Convenience method to automatically generate a code_verifier, and its\n * resulting SHA256. If used, this must be paired with a S256\n * code_challenge_method.\n *\n * For a full example see:\n * https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js\n */\n async generateCodeVerifierAsync() {\n // base64 encoding uses 6 bits per character, and we want to generate128\n // characters. 6*128/8 = 96.\n const crypto = (0, crypto_1.createCrypto)();\n const randomString = crypto.randomBytesBase64(96);\n // The valid characters in the code_verifier are [A-Z]/[a-z]/[0-9]/\n // \"-\"/\".\"/\"_\"/\"~\". Base64 encoded strings are pretty close, so we're just\n // swapping out a few chars.\n const codeVerifier = randomString\n .replace(/\\+/g, '~')\n .replace(/=/g, '_')\n .replace(/\\//g, '-');\n // Generate the base64 encoded SHA256\n const unencodedCodeChallenge = await crypto.sha256DigestBase64(codeVerifier);\n // We need to use base64UrlEncoding instead of standard base64\n const codeChallenge = unencodedCodeChallenge\n .split('=')[0]\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n return { codeVerifier, codeChallenge };\n }\n getToken(codeOrOptions, callback) {\n const options = typeof codeOrOptions === 'string' ? { code: codeOrOptions } : codeOrOptions;\n if (callback) {\n this.getTokenAsync(options).then(r => callback(null, r.tokens, r.res), e => callback(e, null, e.response));\n }\n else {\n return this.getTokenAsync(options);\n }\n }\n async getTokenAsync(options) {\n const url = this.endpoints.oauth2TokenUrl.toString();\n const headers = new Headers();\n const values = {\n client_id: options.client_id || this._clientId,\n code_verifier: options.codeVerifier,\n code: options.code,\n grant_type: 'authorization_code',\n redirect_uri: options.redirect_uri || this.redirectUri,\n };\n if (this.clientAuthentication === ClientAuthentication.ClientSecretBasic) {\n const basic = Buffer.from(`${this._clientId}:${this._clientSecret}`);\n headers.set('authorization', `Basic ${basic.toString('base64')}`);\n }\n if (this.clientAuthentication === ClientAuthentication.ClientSecretPost) {\n values.client_secret = this._clientSecret;\n }\n const opts = {\n ...OAuth2Client.RETRY_CONFIG,\n method: 'POST',\n url,\n data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(values)),\n headers,\n };\n authclient_1.AuthClient.setMethodName(opts, 'getTokenAsync');\n const res = await this.transporter.request(opts);\n const tokens = res.data;\n if (res.data && res.data.expires_in) {\n tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000;\n delete tokens.expires_in;\n }\n this.emit('tokens', tokens);\n return { tokens, res };\n }\n /**\n * Refreshes the access token.\n * @param refresh_token Existing refresh token.\n * @private\n */\n async refreshToken(refreshToken) {\n if (!refreshToken) {\n return this.refreshTokenNoCache(refreshToken);\n }\n // If a request to refresh using the same token has started,\n // return the same promise.\n if (this.refreshTokenPromises.has(refreshToken)) {\n return this.refreshTokenPromises.get(refreshToken);\n }\n const p = this.refreshTokenNoCache(refreshToken).then(r => {\n this.refreshTokenPromises.delete(refreshToken);\n return r;\n }, e => {\n this.refreshTokenPromises.delete(refreshToken);\n throw e;\n });\n this.refreshTokenPromises.set(refreshToken, p);\n return p;\n }\n async refreshTokenNoCache(refreshToken) {\n if (!refreshToken) {\n throw new Error('No refresh token is set.');\n }\n const url = this.endpoints.oauth2TokenUrl.toString();\n const data = {\n refresh_token: refreshToken,\n client_id: this._clientId,\n client_secret: this._clientSecret,\n grant_type: 'refresh_token',\n };\n let res;\n try {\n const opts = {\n ...OAuth2Client.RETRY_CONFIG,\n method: 'POST',\n url,\n data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(data)),\n };\n authclient_1.AuthClient.setMethodName(opts, 'refreshTokenNoCache');\n // request for new token\n res = await this.transporter.request(opts);\n }\n catch (e) {\n if (e instanceof gaxios_1.GaxiosError &&\n e.message === 'invalid_grant' &&\n e.response?.data &&\n /ReAuth/i.test(e.response.data.error_description)) {\n e.message = JSON.stringify(e.response.data);\n }\n throw e;\n }\n const tokens = res.data;\n // TODO: de-duplicate this code from a few spots\n if (res.data && res.data.expires_in) {\n tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000;\n delete tokens.expires_in;\n }\n this.emit('tokens', tokens);\n return { tokens, res };\n }\n refreshAccessToken(callback) {\n if (callback) {\n this.refreshAccessTokenAsync().then(r => callback(null, r.credentials, r.res), callback);\n }\n else {\n return this.refreshAccessTokenAsync();\n }\n }\n async refreshAccessTokenAsync() {\n const r = await this.refreshToken(this.credentials.refresh_token);\n const tokens = r.tokens;\n tokens.refresh_token = this.credentials.refresh_token;\n this.credentials = tokens;\n return { credentials: this.credentials, res: r.res };\n }\n getAccessToken(callback) {\n if (callback) {\n this.getAccessTokenAsync().then(r => callback(null, r.token, r.res), callback);\n }\n else {\n return this.getAccessTokenAsync();\n }\n }\n async getAccessTokenAsync() {\n const shouldRefresh = !this.credentials.access_token || this.isTokenExpiring();\n if (shouldRefresh) {\n if (!this.credentials.refresh_token) {\n if (this.refreshHandler) {\n const refreshedAccessToken = await this.processAndValidateRefreshHandler();\n if (refreshedAccessToken?.access_token) {\n this.setCredentials(refreshedAccessToken);\n return { token: this.credentials.access_token };\n }\n }\n else {\n throw new Error('No refresh token or refresh handler callback is set.');\n }\n }\n const r = await this.refreshAccessTokenAsync();\n if (!r.credentials || (r.credentials && !r.credentials.access_token)) {\n throw new Error('Could not refresh access token.');\n }\n return { token: r.credentials.access_token, res: r.res };\n }\n else {\n return { token: this.credentials.access_token };\n }\n }\n /**\n * The main authentication interface. It takes an optional url which when\n * present is the endpoint being accessed, and returns a Promise which\n * resolves with authorization header fields.\n *\n * In OAuth2Client, the result has the form:\n * { authorization: 'Bearer ' }\n */\n async getRequestHeaders(url) {\n const headers = (await this.getRequestMetadataAsync(url)).headers;\n return headers;\n }\n async getRequestMetadataAsync(url) {\n url;\n const thisCreds = this.credentials;\n if (!thisCreds.access_token &&\n !thisCreds.refresh_token &&\n !this.apiKey &&\n !this.refreshHandler) {\n throw new Error('No access, refresh token, API key or refresh handler callback is set.');\n }\n if (thisCreds.access_token && !this.isTokenExpiring()) {\n thisCreds.token_type = thisCreds.token_type || 'Bearer';\n const headers = new Headers({\n authorization: thisCreds.token_type + ' ' + thisCreds.access_token,\n });\n return { headers: this.addSharedMetadataHeaders(headers) };\n }\n // If refreshHandler exists, call processAndValidateRefreshHandler().\n if (this.refreshHandler) {\n const refreshedAccessToken = await this.processAndValidateRefreshHandler();\n if (refreshedAccessToken?.access_token) {\n this.setCredentials(refreshedAccessToken);\n const headers = new Headers({\n authorization: 'Bearer ' + this.credentials.access_token,\n });\n return { headers: this.addSharedMetadataHeaders(headers) };\n }\n }\n if (this.apiKey) {\n return { headers: new Headers({ 'X-Goog-Api-Key': this.apiKey }) };\n }\n let r = null;\n let tokens = null;\n try {\n r = await this.refreshToken(thisCreds.refresh_token);\n tokens = r.tokens;\n }\n catch (err) {\n const e = err;\n if (e.response &&\n (e.response.status === 403 || e.response.status === 404)) {\n e.message = `Could not refresh access token: ${e.message}`;\n }\n throw e;\n }\n const credentials = this.credentials;\n credentials.token_type = credentials.token_type || 'Bearer';\n tokens.refresh_token = credentials.refresh_token;\n this.credentials = tokens;\n const headers = new Headers({\n authorization: credentials.token_type + ' ' + tokens.access_token,\n });\n return { headers: this.addSharedMetadataHeaders(headers), res: r.res };\n }\n /**\n * Generates an URL to revoke the given token.\n * @param token The existing token to be revoked.\n *\n * @deprecated use instance method {@link OAuth2Client.getRevokeTokenURL}\n */\n static getRevokeTokenUrl(token) {\n return new OAuth2Client().getRevokeTokenURL(token).toString();\n }\n /**\n * Generates a URL to revoke the given token.\n *\n * @param token The existing token to be revoked.\n */\n getRevokeTokenURL(token) {\n const url = new URL(this.endpoints.oauth2RevokeUrl);\n url.searchParams.append('token', token);\n return url;\n }\n revokeToken(token, callback) {\n const opts = {\n ...OAuth2Client.RETRY_CONFIG,\n url: this.getRevokeTokenURL(token).toString(),\n method: 'POST',\n };\n authclient_1.AuthClient.setMethodName(opts, 'revokeToken');\n if (callback) {\n this.transporter\n .request(opts)\n .then(r => callback(null, r), callback);\n }\n else {\n return this.transporter.request(opts);\n }\n }\n revokeCredentials(callback) {\n if (callback) {\n this.revokeCredentialsAsync().then(res => callback(null, res), callback);\n }\n else {\n return this.revokeCredentialsAsync();\n }\n }\n async revokeCredentialsAsync() {\n const token = this.credentials.access_token;\n this.credentials = {};\n if (token) {\n return this.revokeToken(token);\n }\n else {\n throw new Error('No access token to revoke.');\n }\n }\n request(opts, callback) {\n if (callback) {\n this.requestAsync(opts).then(r => callback(null, r), e => {\n return callback(e, e.response);\n });\n }\n else {\n return this.requestAsync(opts);\n }\n }\n async requestAsync(opts, reAuthRetried = false) {\n try {\n const r = await this.getRequestMetadataAsync();\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);\n this.addUserProjectAndAuthHeaders(opts.headers, r.headers);\n if (this.apiKey) {\n opts.headers.set('X-Goog-Api-Key', this.apiKey);\n }\n return await this.transporter.request(opts);\n }\n catch (e) {\n const res = e.response;\n if (res) {\n const statusCode = res.status;\n // Retry the request for metadata if the following criteria are true:\n // - We haven't already retried. It only makes sense to retry once.\n // - The response was a 401 or a 403\n // - The request didn't send a readableStream\n // - An access_token and refresh_token were available, but either no\n // expiry_date was available or the forceRefreshOnFailure flag is set.\n // The absent expiry_date case can happen when developers stash the\n // access_token and refresh_token for later use, but the access_token\n // fails on the first try because it's expired. Some developers may\n // choose to enable forceRefreshOnFailure to mitigate time-related\n // errors.\n // Or the following criteria are true:\n // - We haven't already retried. It only makes sense to retry once.\n // - The response was a 401 or a 403\n // - The request didn't send a readableStream\n // - No refresh_token was available\n // - An access_token and a refreshHandler callback were available, but\n // either no expiry_date was available or the forceRefreshOnFailure\n // flag is set. The access_token fails on the first try because it's\n // expired. Some developers may choose to enable forceRefreshOnFailure\n // to mitigate time-related errors.\n const mayRequireRefresh = this.credentials &&\n this.credentials.access_token &&\n this.credentials.refresh_token &&\n (!this.credentials.expiry_date || this.forceRefreshOnFailure);\n const mayRequireRefreshWithNoRefreshToken = this.credentials &&\n this.credentials.access_token &&\n !this.credentials.refresh_token &&\n (!this.credentials.expiry_date || this.forceRefreshOnFailure) &&\n this.refreshHandler;\n const isReadableStream = res.config.data instanceof stream.Readable;\n const isAuthErr = statusCode === 401 || statusCode === 403;\n if (!reAuthRetried &&\n isAuthErr &&\n !isReadableStream &&\n mayRequireRefresh) {\n await this.refreshAccessTokenAsync();\n return this.requestAsync(opts, true);\n }\n else if (!reAuthRetried &&\n isAuthErr &&\n !isReadableStream &&\n mayRequireRefreshWithNoRefreshToken) {\n const refreshedAccessToken = await this.processAndValidateRefreshHandler();\n if (refreshedAccessToken?.access_token) {\n this.setCredentials(refreshedAccessToken);\n }\n return this.requestAsync(opts, true);\n }\n }\n throw e;\n }\n }\n verifyIdToken(options, callback) {\n // This function used to accept two arguments instead of an options object.\n // Check the types to help users upgrade with less pain.\n // This check can be removed after a 2.0 release.\n if (callback && typeof callback !== 'function') {\n throw new Error('This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.');\n }\n if (callback) {\n this.verifyIdTokenAsync(options).then(r => callback(null, r), callback);\n }\n else {\n return this.verifyIdTokenAsync(options);\n }\n }\n async verifyIdTokenAsync(options) {\n if (!options.idToken) {\n throw new Error('The verifyIdToken method requires an ID Token');\n }\n const response = await this.getFederatedSignonCertsAsync();\n const login = await this.verifySignedJwtWithCertsAsync(options.idToken, response.certs, options.audience, this.issuers, options.maxExpiry);\n return login;\n }\n /**\n * Obtains information about the provisioned access token. Especially useful\n * if you want to check the scopes that were provisioned to a given token.\n *\n * @param accessToken Required. The Access Token for which you want to get\n * user info.\n */\n async getTokenInfo(accessToken) {\n const { data } = await this.transporter.request({\n ...OAuth2Client.RETRY_CONFIG,\n method: 'POST',\n headers: {\n 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',\n authorization: `Bearer ${accessToken}`,\n },\n url: this.endpoints.tokenInfoUrl.toString(),\n });\n const info = Object.assign({\n expiry_date: new Date().getTime() + data.expires_in * 1000,\n scopes: data.scope.split(' '),\n }, data);\n delete info.expires_in;\n delete info.scope;\n return info;\n }\n getFederatedSignonCerts(callback) {\n if (callback) {\n this.getFederatedSignonCertsAsync().then(r => callback(null, r.certs, r.res), callback);\n }\n else {\n return this.getFederatedSignonCertsAsync();\n }\n }\n async getFederatedSignonCertsAsync() {\n const nowTime = new Date().getTime();\n const format = (0, crypto_1.hasBrowserCrypto)()\n ? CertificateFormat.JWK\n : CertificateFormat.PEM;\n if (this.certificateExpiry &&\n nowTime < this.certificateExpiry.getTime() &&\n this.certificateCacheFormat === format) {\n return { certs: this.certificateCache, format };\n }\n let res;\n let url;\n switch (format) {\n case CertificateFormat.PEM:\n url = this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();\n break;\n case CertificateFormat.JWK:\n url = this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();\n break;\n default:\n throw new Error(`Unsupported certificate format ${format}`);\n }\n try {\n const opts = {\n ...OAuth2Client.RETRY_CONFIG,\n url,\n };\n authclient_1.AuthClient.setMethodName(opts, 'getFederatedSignonCertsAsync');\n res = await this.transporter.request(opts);\n }\n catch (e) {\n if (e instanceof Error) {\n e.message = `Failed to retrieve verification certificates: ${e.message}`;\n }\n throw e;\n }\n const cacheControl = res?.headers.get('cache-control');\n let cacheAge = -1;\n if (cacheControl) {\n const maxAge = /max-age=(?[0-9]+)/.exec(cacheControl)?.groups\n ?.maxAge;\n if (maxAge) {\n // Cache results with max-age (in seconds)\n cacheAge = Number(maxAge) * 1000; // milliseconds\n }\n }\n let certificates = {};\n switch (format) {\n case CertificateFormat.PEM:\n certificates = res.data;\n break;\n case CertificateFormat.JWK:\n for (const key of res.data.keys) {\n certificates[key.kid] = key;\n }\n break;\n default:\n throw new Error(`Unsupported certificate format ${format}`);\n }\n const now = new Date();\n this.certificateExpiry =\n cacheAge === -1 ? null : new Date(now.getTime() + cacheAge);\n this.certificateCache = certificates;\n this.certificateCacheFormat = format;\n return { certs: certificates, format, res };\n }\n getIapPublicKeys(callback) {\n if (callback) {\n this.getIapPublicKeysAsync().then(r => callback(null, r.pubkeys, r.res), callback);\n }\n else {\n return this.getIapPublicKeysAsync();\n }\n }\n async getIapPublicKeysAsync() {\n let res;\n const url = this.endpoints.oauth2IapPublicKeyUrl.toString();\n try {\n const opts = {\n ...OAuth2Client.RETRY_CONFIG,\n url,\n };\n authclient_1.AuthClient.setMethodName(opts, 'getIapPublicKeysAsync');\n res = await this.transporter.request(opts);\n }\n catch (e) {\n if (e instanceof Error) {\n e.message = `Failed to retrieve verification certificates: ${e.message}`;\n }\n throw e;\n }\n return { pubkeys: res.data, res };\n }\n verifySignedJwtWithCerts() {\n // To make the code compatible with browser SubtleCrypto we need to make\n // this method async.\n throw new Error('verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.');\n }\n /**\n * Verify the id token is signed with the correct certificate\n * and is from the correct audience.\n * @param jwt The jwt to verify (The ID Token in this case).\n * @param certs The array of certs to test the jwt against.\n * @param requiredAudience The audience to test the jwt against.\n * @param issuers The allowed issuers of the jwt (Optional).\n * @param maxExpiry The max expiry the certificate can be (Optional).\n * @return Returns a promise resolving to LoginTicket on verification.\n */\n async verifySignedJwtWithCertsAsync(jwt, certs, requiredAudience, issuers, maxExpiry) {\n const crypto = (0, crypto_1.createCrypto)();\n if (!maxExpiry) {\n maxExpiry = OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_;\n }\n const segments = jwt.split('.');\n if (segments.length !== 3) {\n throw new Error('Wrong number of segments in token: ' + jwt);\n }\n const signed = segments[0] + '.' + segments[1];\n let signature = segments[2];\n let envelope;\n let payload;\n try {\n envelope = JSON.parse(crypto.decodeBase64StringUtf8(segments[0]));\n }\n catch (err) {\n if (err instanceof Error) {\n err.message = `Can't parse token envelope: ${segments[0]}': ${err.message}`;\n }\n throw err;\n }\n if (!envelope) {\n throw new Error(\"Can't parse token envelope: \" + segments[0]);\n }\n try {\n payload = JSON.parse(crypto.decodeBase64StringUtf8(segments[1]));\n }\n catch (err) {\n if (err instanceof Error) {\n err.message = `Can't parse token payload '${segments[0]}`;\n }\n throw err;\n }\n if (!payload) {\n throw new Error(\"Can't parse token payload: \" + segments[1]);\n }\n if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) {\n // If this is not present, then there's no reason to attempt verification\n throw new Error('No pem found for envelope: ' + JSON.stringify(envelope));\n }\n const cert = certs[envelope.kid];\n if (envelope.alg === 'ES256') {\n signature = formatEcdsa.joseToDer(signature, 'ES256').toString('base64');\n }\n const verified = await crypto.verify(cert, signed, signature);\n if (!verified) {\n throw new Error('Invalid token signature: ' + jwt);\n }\n if (!payload.iat) {\n throw new Error('No issue time in token: ' + JSON.stringify(payload));\n }\n if (!payload.exp) {\n throw new Error('No expiration time in token: ' + JSON.stringify(payload));\n }\n const iat = Number(payload.iat);\n if (isNaN(iat))\n throw new Error('iat field using invalid format');\n const exp = Number(payload.exp);\n if (isNaN(exp))\n throw new Error('exp field using invalid format');\n const now = new Date().getTime() / 1000;\n if (exp >= now + maxExpiry) {\n throw new Error('Expiration time too far in future: ' + JSON.stringify(payload));\n }\n const earliest = iat - OAuth2Client.CLOCK_SKEW_SECS_;\n const latest = exp + OAuth2Client.CLOCK_SKEW_SECS_;\n if (now < earliest) {\n throw new Error('Token used too early, ' +\n now +\n ' < ' +\n earliest +\n ': ' +\n JSON.stringify(payload));\n }\n if (now > latest) {\n throw new Error('Token used too late, ' +\n now +\n ' > ' +\n latest +\n ': ' +\n JSON.stringify(payload));\n }\n if (issuers && issuers.indexOf(payload.iss) < 0) {\n throw new Error('Invalid issuer, expected one of [' +\n issuers +\n '], but got ' +\n payload.iss);\n }\n // Check the audience matches if we have one\n if (typeof requiredAudience !== 'undefined' && requiredAudience !== null) {\n const aud = payload.aud;\n let audVerified = false;\n // If the requiredAudience is an array, check if it contains token\n // audience\n if (requiredAudience.constructor === Array) {\n audVerified = requiredAudience.indexOf(aud) > -1;\n }\n else {\n audVerified = aud === requiredAudience;\n }\n if (!audVerified) {\n throw new Error('Wrong recipient, payload audience != requiredAudience');\n }\n }\n return new loginticket_1.LoginTicket(envelope, payload);\n }\n /**\n * Returns a promise that resolves with AccessTokenResponse type if\n * refreshHandler is defined.\n * If not, nothing is returned.\n */\n async processAndValidateRefreshHandler() {\n if (this.refreshHandler) {\n const accessTokenResponse = await this.refreshHandler();\n if (!accessTokenResponse.access_token) {\n throw new Error('No access token is returned by the refreshHandler callback.');\n }\n return accessTokenResponse;\n }\n return;\n }\n /**\n * Returns true if a token is expired or will expire within\n * eagerRefreshThresholdMillismilliseconds.\n * If there is no expiry time, assumes the token is not expired or expiring.\n */\n isTokenExpiring() {\n const expiryDate = this.credentials.expiry_date;\n return expiryDate\n ? expiryDate <= new Date().getTime() + this.eagerRefreshThresholdMillis\n : false;\n }\n}\nexports.OAuth2Client = OAuth2Client;\n//# sourceMappingURL=oauth2client.js.map", "\"use strict\";\n// Copyright 2013 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Compute = void 0;\nconst gaxios_1 = require(\"gaxios\");\nconst gcpMetadata = require(\"gcp-metadata\");\nconst oauth2client_1 = require(\"./oauth2client\");\nclass Compute extends oauth2client_1.OAuth2Client {\n serviceAccountEmail;\n scopes;\n /**\n * Google Compute Engine service account credentials.\n *\n * Retrieve access token from the metadata server.\n * See: https://cloud.google.com/compute/docs/access/authenticate-workloads#applications\n */\n constructor(options = {}) {\n super(options);\n // Start with an expired refresh token, which will automatically be\n // refreshed before the first API call is made.\n this.credentials = { expiry_date: 1, refresh_token: 'compute-placeholder' };\n this.serviceAccountEmail = options.serviceAccountEmail || 'default';\n this.scopes = Array.isArray(options.scopes)\n ? options.scopes\n : options.scopes\n ? [options.scopes]\n : [];\n }\n /**\n * Refreshes the access token.\n * @param refreshToken Unused parameter\n */\n async refreshTokenNoCache() {\n const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`;\n let data;\n try {\n const instanceOptions = {\n property: tokenPath,\n };\n if (this.scopes.length > 0) {\n instanceOptions.params = {\n scopes: this.scopes.join(','),\n };\n }\n data = await gcpMetadata.instance(instanceOptions);\n }\n catch (e) {\n if (e instanceof gaxios_1.GaxiosError) {\n e.message = `Could not refresh access token: ${e.message}`;\n this.wrapError(e);\n }\n throw e;\n }\n const tokens = data;\n if (data && data.expires_in) {\n tokens.expiry_date = new Date().getTime() + data.expires_in * 1000;\n delete tokens.expires_in;\n }\n this.emit('tokens', tokens);\n return { tokens, res: null };\n }\n /**\n * Fetches an ID token.\n * @param targetAudience the audience for the fetched ID token.\n */\n async fetchIdToken(targetAudience) {\n const idTokenPath = `service-accounts/${this.serviceAccountEmail}/identity` +\n `?format=full&audience=${targetAudience}`;\n let idToken;\n try {\n const instanceOptions = {\n property: idTokenPath,\n };\n idToken = await gcpMetadata.instance(instanceOptions);\n }\n catch (e) {\n if (e instanceof Error) {\n e.message = `Could not fetch ID token: ${e.message}`;\n }\n throw e;\n }\n return idToken;\n }\n wrapError(e) {\n const res = e.response;\n if (res && res.status) {\n e.status = res.status;\n if (res.status === 403) {\n e.message =\n 'A Forbidden error was returned while attempting to retrieve an access ' +\n 'token for the Compute Engine built-in service account. This may be because the Compute ' +\n 'Engine instance does not have the correct permission scopes specified: ' +\n e.message;\n }\n else if (res.status === 404) {\n e.message =\n 'A Not Found error was returned while attempting to retrieve an access' +\n 'token for the Compute Engine built-in service account. This may be because the Compute ' +\n 'Engine instance does not have any permission scopes specified: ' +\n e.message;\n }\n }\n }\n}\nexports.Compute = Compute;\n//# sourceMappingURL=computeclient.js.map", "\"use strict\";\n// Copyright 2020 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.IdTokenClient = void 0;\nconst oauth2client_1 = require(\"./oauth2client\");\nclass IdTokenClient extends oauth2client_1.OAuth2Client {\n targetAudience;\n idTokenProvider;\n /**\n * Google ID Token client\n *\n * Retrieve ID token from the metadata server.\n * See: https://cloud.google.com/docs/authentication/get-id-token#metadata-server\n */\n constructor(options) {\n super(options);\n this.targetAudience = options.targetAudience;\n this.idTokenProvider = options.idTokenProvider;\n }\n async getRequestMetadataAsync() {\n if (!this.credentials.id_token ||\n !this.credentials.expiry_date ||\n this.isTokenExpiring()) {\n const idToken = await this.idTokenProvider.fetchIdToken(this.targetAudience);\n this.credentials = {\n id_token: idToken,\n expiry_date: this.getIdTokenExpiryDate(idToken),\n };\n }\n const headers = new Headers({\n authorization: 'Bearer ' + this.credentials.id_token,\n });\n return { headers };\n }\n getIdTokenExpiryDate(idToken) {\n const payloadB64 = idToken.split('.')[1];\n if (payloadB64) {\n const payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('ascii'));\n return payload.exp * 1000;\n }\n }\n}\nexports.IdTokenClient = IdTokenClient;\n//# sourceMappingURL=idtokenclient.js.map", "\"use strict\";\n// Copyright 2018 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.GCPEnv = void 0;\nexports.clear = clear;\nexports.getEnv = getEnv;\nconst gcpMetadata = require(\"gcp-metadata\");\nvar GCPEnv;\n(function (GCPEnv) {\n GCPEnv[\"APP_ENGINE\"] = \"APP_ENGINE\";\n GCPEnv[\"KUBERNETES_ENGINE\"] = \"KUBERNETES_ENGINE\";\n GCPEnv[\"CLOUD_FUNCTIONS\"] = \"CLOUD_FUNCTIONS\";\n GCPEnv[\"COMPUTE_ENGINE\"] = \"COMPUTE_ENGINE\";\n GCPEnv[\"CLOUD_RUN\"] = \"CLOUD_RUN\";\n GCPEnv[\"NONE\"] = \"NONE\";\n})(GCPEnv || (exports.GCPEnv = GCPEnv = {}));\nlet envPromise;\nfunction clear() {\n envPromise = undefined;\n}\nasync function getEnv() {\n if (envPromise) {\n return envPromise;\n }\n envPromise = getEnvMemoized();\n return envPromise;\n}\nasync function getEnvMemoized() {\n let env = GCPEnv.NONE;\n if (isAppEngine()) {\n env = GCPEnv.APP_ENGINE;\n }\n else if (isCloudFunction()) {\n env = GCPEnv.CLOUD_FUNCTIONS;\n }\n else if (await isComputeEngine()) {\n if (await isKubernetesEngine()) {\n env = GCPEnv.KUBERNETES_ENGINE;\n }\n else if (isCloudRun()) {\n env = GCPEnv.CLOUD_RUN;\n }\n else {\n env = GCPEnv.COMPUTE_ENGINE;\n }\n }\n else {\n env = GCPEnv.NONE;\n }\n return env;\n}\nfunction isAppEngine() {\n return !!(process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME);\n}\nfunction isCloudFunction() {\n return !!(process.env.FUNCTION_NAME || process.env.FUNCTION_TARGET);\n}\n/**\n * This check only verifies that the environment is running knative.\n * This must be run *after* checking for Kubernetes, otherwise it will\n * return a false positive.\n */\nfunction isCloudRun() {\n return !!process.env.K_CONFIGURATION;\n}\nasync function isKubernetesEngine() {\n try {\n await gcpMetadata.instance('attributes/cluster-name');\n return true;\n }\n catch (e) {\n return false;\n }\n}\nasync function isComputeEngine() {\n return gcpMetadata.isAvailable();\n}\n//# sourceMappingURL=envDetect.js.map", "/*global module, process*/\nvar Buffer = require('safe-buffer').Buffer;\nvar Stream = require('stream');\nvar util = require('util');\n\nfunction DataStream(data) {\n this.buffer = null;\n this.writable = true;\n this.readable = true;\n\n // No input\n if (!data) {\n this.buffer = Buffer.alloc(0);\n return this;\n }\n\n // Stream\n if (typeof data.pipe === 'function') {\n this.buffer = Buffer.alloc(0);\n data.pipe(this);\n return this;\n }\n\n // Buffer or String\n // or Object (assumedly a passworded key)\n if (data.length || typeof data === 'object') {\n this.buffer = data;\n this.writable = false;\n process.nextTick(function () {\n this.emit('end', data);\n this.readable = false;\n this.emit('close');\n }.bind(this));\n return this;\n }\n\n throw new TypeError('Unexpected data type ('+ typeof data + ')');\n}\nutil.inherits(DataStream, Stream);\n\nDataStream.prototype.write = function write(data) {\n this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]);\n this.emit('data', data);\n};\n\nDataStream.prototype.end = function end(data) {\n if (data)\n this.write(data);\n this.emit('end', data);\n this.emit('close');\n this.writable = false;\n this.readable = false;\n};\n\nmodule.exports = DataStream;\n", "/*jshint node:true */\n'use strict';\nvar Buffer = require('buffer').Buffer; // browserify\nvar SlowBuffer = require('buffer').SlowBuffer;\n\nmodule.exports = bufferEq;\n\nfunction bufferEq(a, b) {\n\n // shortcutting on type is necessary for correctness\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n return false;\n }\n\n // buffer sizes should be well-known information, so despite this\n // shortcutting, it doesn't leak any information about the *contents* of the\n // buffers.\n if (a.length !== b.length) {\n return false;\n }\n\n var c = 0;\n for (var i = 0; i < a.length; i++) {\n /*jshint bitwise:false */\n c |= a[i] ^ b[i]; // XOR\n }\n return c === 0;\n}\n\nbufferEq.install = function() {\n Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) {\n return bufferEq(this, that);\n };\n};\n\nvar origBufEqual = Buffer.prototype.equal;\nvar origSlowBufEqual = SlowBuffer.prototype.equal;\nbufferEq.restore = function() {\n Buffer.prototype.equal = origBufEqual;\n SlowBuffer.prototype.equal = origSlowBufEqual;\n};\n", "var Buffer = require('safe-buffer').Buffer;\nvar crypto = require('crypto');\nvar formatEcdsa = require('ecdsa-sig-formatter');\nvar util = require('util');\n\nvar MSG_INVALID_ALGORITHM = '\"%s\" is not a valid algorithm.\\n Supported algorithms are:\\n \"HS256\", \"HS384\", \"HS512\", \"RS256\", \"RS384\", \"RS512\", \"PS256\", \"PS384\", \"PS512\", \"ES256\", \"ES384\", \"ES512\" and \"none\".'\nvar MSG_INVALID_SECRET = 'secret must be a string or buffer';\nvar MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer';\nvar MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object';\n\nvar supportsKeyObjects = typeof crypto.createPublicKey === 'function';\nif (supportsKeyObjects) {\n MSG_INVALID_VERIFIER_KEY += ' or a KeyObject';\n MSG_INVALID_SECRET += 'or a KeyObject';\n}\n\nfunction checkIsPublicKey(key) {\n if (Buffer.isBuffer(key)) {\n return;\n }\n\n if (typeof key === 'string') {\n return;\n }\n\n if (!supportsKeyObjects) {\n throw typeError(MSG_INVALID_VERIFIER_KEY);\n }\n\n if (typeof key !== 'object') {\n throw typeError(MSG_INVALID_VERIFIER_KEY);\n }\n\n if (typeof key.type !== 'string') {\n throw typeError(MSG_INVALID_VERIFIER_KEY);\n }\n\n if (typeof key.asymmetricKeyType !== 'string') {\n throw typeError(MSG_INVALID_VERIFIER_KEY);\n }\n\n if (typeof key.export !== 'function') {\n throw typeError(MSG_INVALID_VERIFIER_KEY);\n }\n};\n\nfunction checkIsPrivateKey(key) {\n if (Buffer.isBuffer(key)) {\n return;\n }\n\n if (typeof key === 'string') {\n return;\n }\n\n if (typeof key === 'object') {\n return;\n }\n\n throw typeError(MSG_INVALID_SIGNER_KEY);\n};\n\nfunction checkIsSecretKey(key) {\n if (Buffer.isBuffer(key)) {\n return;\n }\n\n if (typeof key === 'string') {\n return key;\n }\n\n if (!supportsKeyObjects) {\n throw typeError(MSG_INVALID_SECRET);\n }\n\n if (typeof key !== 'object') {\n throw typeError(MSG_INVALID_SECRET);\n }\n\n if (key.type !== 'secret') {\n throw typeError(MSG_INVALID_SECRET);\n }\n\n if (typeof key.export !== 'function') {\n throw typeError(MSG_INVALID_SECRET);\n }\n}\n\nfunction fromBase64(base64) {\n return base64\n .replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n}\n\nfunction toBase64(base64url) {\n base64url = base64url.toString();\n\n var padding = 4 - base64url.length % 4;\n if (padding !== 4) {\n for (var i = 0; i < padding; ++i) {\n base64url += '=';\n }\n }\n\n return base64url\n .replace(/\\-/g, '+')\n .replace(/_/g, '/');\n}\n\nfunction typeError(template) {\n var args = [].slice.call(arguments, 1);\n var errMsg = util.format.bind(util, template).apply(null, args);\n return new TypeError(errMsg);\n}\n\nfunction bufferOrString(obj) {\n return Buffer.isBuffer(obj) || typeof obj === 'string';\n}\n\nfunction normalizeInput(thing) {\n if (!bufferOrString(thing))\n thing = JSON.stringify(thing);\n return thing;\n}\n\nfunction createHmacSigner(bits) {\n return function sign(thing, secret) {\n checkIsSecretKey(secret);\n thing = normalizeInput(thing);\n var hmac = crypto.createHmac('sha' + bits, secret);\n var sig = (hmac.update(thing), hmac.digest('base64'))\n return fromBase64(sig);\n }\n}\n\nvar bufferEqual;\nvar timingSafeEqual = 'timingSafeEqual' in crypto ? function timingSafeEqual(a, b) {\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n\n return crypto.timingSafeEqual(a, b)\n} : function timingSafeEqual(a, b) {\n if (!bufferEqual) {\n bufferEqual = require('buffer-equal-constant-time');\n }\n\n return bufferEqual(a, b)\n}\n\nfunction createHmacVerifier(bits) {\n return function verify(thing, signature, secret) {\n var computedSig = createHmacSigner(bits)(thing, secret);\n return timingSafeEqual(Buffer.from(signature), Buffer.from(computedSig));\n }\n}\n\nfunction createKeySigner(bits) {\n return function sign(thing, privateKey) {\n checkIsPrivateKey(privateKey);\n thing = normalizeInput(thing);\n // Even though we are specifying \"RSA\" here, this works with ECDSA\n // keys as well.\n var signer = crypto.createSign('RSA-SHA' + bits);\n var sig = (signer.update(thing), signer.sign(privateKey, 'base64'));\n return fromBase64(sig);\n }\n}\n\nfunction createKeyVerifier(bits) {\n return function verify(thing, signature, publicKey) {\n checkIsPublicKey(publicKey);\n thing = normalizeInput(thing);\n signature = toBase64(signature);\n var verifier = crypto.createVerify('RSA-SHA' + bits);\n verifier.update(thing);\n return verifier.verify(publicKey, signature, 'base64');\n }\n}\n\nfunction createPSSKeySigner(bits) {\n return function sign(thing, privateKey) {\n checkIsPrivateKey(privateKey);\n thing = normalizeInput(thing);\n var signer = crypto.createSign('RSA-SHA' + bits);\n var sig = (signer.update(thing), signer.sign({\n key: privateKey,\n padding: crypto.constants.RSA_PKCS1_PSS_PADDING,\n saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST\n }, 'base64'));\n return fromBase64(sig);\n }\n}\n\nfunction createPSSKeyVerifier(bits) {\n return function verify(thing, signature, publicKey) {\n checkIsPublicKey(publicKey);\n thing = normalizeInput(thing);\n signature = toBase64(signature);\n var verifier = crypto.createVerify('RSA-SHA' + bits);\n verifier.update(thing);\n return verifier.verify({\n key: publicKey,\n padding: crypto.constants.RSA_PKCS1_PSS_PADDING,\n saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST\n }, signature, 'base64');\n }\n}\n\nfunction createECDSASigner(bits) {\n var inner = createKeySigner(bits);\n return function sign() {\n var signature = inner.apply(null, arguments);\n signature = formatEcdsa.derToJose(signature, 'ES' + bits);\n return signature;\n };\n}\n\nfunction createECDSAVerifer(bits) {\n var inner = createKeyVerifier(bits);\n return function verify(thing, signature, publicKey) {\n signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64');\n var result = inner(thing, signature, publicKey);\n return result;\n };\n}\n\nfunction createNoneSigner() {\n return function sign() {\n return '';\n }\n}\n\nfunction createNoneVerifier() {\n return function verify(thing, signature) {\n return signature === '';\n }\n}\n\nmodule.exports = function jwa(algorithm) {\n var signerFactories = {\n hs: createHmacSigner,\n rs: createKeySigner,\n ps: createPSSKeySigner,\n es: createECDSASigner,\n none: createNoneSigner,\n }\n var verifierFactories = {\n hs: createHmacVerifier,\n rs: createKeyVerifier,\n ps: createPSSKeyVerifier,\n es: createECDSAVerifer,\n none: createNoneVerifier,\n }\n var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);\n if (!match)\n throw typeError(MSG_INVALID_ALGORITHM, algorithm);\n var algo = (match[1] || match[3]).toLowerCase();\n var bits = match[2];\n\n return {\n sign: signerFactories[algo](bits),\n verify: verifierFactories[algo](bits),\n }\n};\n", "/*global module*/\nvar Buffer = require('buffer').Buffer;\n\nmodule.exports = function toString(obj) {\n if (typeof obj === 'string')\n return obj;\n if (typeof obj === 'number' || Buffer.isBuffer(obj))\n return obj.toString();\n return JSON.stringify(obj);\n};\n", "/*global module*/\nvar Buffer = require('safe-buffer').Buffer;\nvar DataStream = require('./data-stream');\nvar jwa = require('jwa');\nvar Stream = require('stream');\nvar toString = require('./tostring');\nvar util = require('util');\n\nfunction base64url(string, encoding) {\n return Buffer\n .from(string, encoding)\n .toString('base64')\n .replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n}\n\nfunction jwsSecuredInput(header, payload, encoding) {\n encoding = encoding || 'utf8';\n var encodedHeader = base64url(toString(header), 'binary');\n var encodedPayload = base64url(toString(payload), encoding);\n return util.format('%s.%s', encodedHeader, encodedPayload);\n}\n\nfunction jwsSign(opts) {\n var header = opts.header;\n var payload = opts.payload;\n var secretOrKey = opts.secret || opts.privateKey;\n var encoding = opts.encoding;\n var algo = jwa(header.alg);\n var securedInput = jwsSecuredInput(header, payload, encoding);\n var signature = algo.sign(securedInput, secretOrKey);\n return util.format('%s.%s', securedInput, signature);\n}\n\nfunction SignStream(opts) {\n var secret = opts.secret||opts.privateKey||opts.key;\n var secretStream = new DataStream(secret);\n this.readable = true;\n this.header = opts.header;\n this.encoding = opts.encoding;\n this.secret = this.privateKey = this.key = secretStream;\n this.payload = new DataStream(opts.payload);\n this.secret.once('close', function () {\n if (!this.payload.writable && this.readable)\n this.sign();\n }.bind(this));\n\n this.payload.once('close', function () {\n if (!this.secret.writable && this.readable)\n this.sign();\n }.bind(this));\n}\nutil.inherits(SignStream, Stream);\n\nSignStream.prototype.sign = function sign() {\n try {\n var signature = jwsSign({\n header: this.header,\n payload: this.payload.buffer,\n secret: this.secret.buffer,\n encoding: this.encoding\n });\n this.emit('done', signature);\n this.emit('data', signature);\n this.emit('end');\n this.readable = false;\n return signature;\n } catch (e) {\n this.readable = false;\n this.emit('error', e);\n this.emit('close');\n }\n};\n\nSignStream.sign = jwsSign;\n\nmodule.exports = SignStream;\n", "/*global module*/\nvar Buffer = require('safe-buffer').Buffer;\nvar DataStream = require('./data-stream');\nvar jwa = require('jwa');\nvar Stream = require('stream');\nvar toString = require('./tostring');\nvar util = require('util');\nvar JWS_REGEX = /^[a-zA-Z0-9\\-_]+?\\.[a-zA-Z0-9\\-_]+?\\.([a-zA-Z0-9\\-_]+)?$/;\n\nfunction isObject(thing) {\n return Object.prototype.toString.call(thing) === '[object Object]';\n}\n\nfunction safeJsonParse(thing) {\n if (isObject(thing))\n return thing;\n try { return JSON.parse(thing); }\n catch (e) { return undefined; }\n}\n\nfunction headerFromJWS(jwsSig) {\n var encodedHeader = jwsSig.split('.', 1)[0];\n return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary'));\n}\n\nfunction securedInputFromJWS(jwsSig) {\n return jwsSig.split('.', 2).join('.');\n}\n\nfunction signatureFromJWS(jwsSig) {\n return jwsSig.split('.')[2];\n}\n\nfunction payloadFromJWS(jwsSig, encoding) {\n encoding = encoding || 'utf8';\n var payload = jwsSig.split('.')[1];\n return Buffer.from(payload, 'base64').toString(encoding);\n}\n\nfunction isValidJws(string) {\n return JWS_REGEX.test(string) && !!headerFromJWS(string);\n}\n\nfunction jwsVerify(jwsSig, algorithm, secretOrKey) {\n if (!algorithm) {\n var err = new Error(\"Missing algorithm parameter for jws.verify\");\n err.code = \"MISSING_ALGORITHM\";\n throw err;\n }\n jwsSig = toString(jwsSig);\n var signature = signatureFromJWS(jwsSig);\n var securedInput = securedInputFromJWS(jwsSig);\n var algo = jwa(algorithm);\n return algo.verify(securedInput, signature, secretOrKey);\n}\n\nfunction jwsDecode(jwsSig, opts) {\n opts = opts || {};\n jwsSig = toString(jwsSig);\n\n if (!isValidJws(jwsSig))\n return null;\n\n var header = headerFromJWS(jwsSig);\n\n if (!header)\n return null;\n\n var payload = payloadFromJWS(jwsSig);\n if (header.typ === 'JWT' || opts.json)\n payload = JSON.parse(payload, opts.encoding);\n\n return {\n header: header,\n payload: payload,\n signature: signatureFromJWS(jwsSig)\n };\n}\n\nfunction VerifyStream(opts) {\n opts = opts || {};\n var secretOrKey = opts.secret||opts.publicKey||opts.key;\n var secretStream = new DataStream(secretOrKey);\n this.readable = true;\n this.algorithm = opts.algorithm;\n this.encoding = opts.encoding;\n this.secret = this.publicKey = this.key = secretStream;\n this.signature = new DataStream(opts.signature);\n this.secret.once('close', function () {\n if (!this.signature.writable && this.readable)\n this.verify();\n }.bind(this));\n\n this.signature.once('close', function () {\n if (!this.secret.writable && this.readable)\n this.verify();\n }.bind(this));\n}\nutil.inherits(VerifyStream, Stream);\nVerifyStream.prototype.verify = function verify() {\n try {\n var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer);\n var obj = jwsDecode(this.signature.buffer, this.encoding);\n this.emit('done', valid, obj);\n this.emit('data', valid);\n this.emit('end');\n this.readable = false;\n return valid;\n } catch (e) {\n this.readable = false;\n this.emit('error', e);\n this.emit('close');\n }\n};\n\nVerifyStream.decode = jwsDecode;\nVerifyStream.isValid = isValidJws;\nVerifyStream.verify = jwsVerify;\n\nmodule.exports = VerifyStream;\n", "/*global exports*/\nvar SignStream = require('./lib/sign-stream');\nvar VerifyStream = require('./lib/verify-stream');\n\nvar ALGORITHMS = [\n 'HS256', 'HS384', 'HS512',\n 'RS256', 'RS384', 'RS512',\n 'PS256', 'PS384', 'PS512',\n 'ES256', 'ES384', 'ES512'\n];\n\nexports.ALGORITHMS = ALGORITHMS;\nexports.sign = SignStream.sign;\nexports.verify = VerifyStream.verify;\nexports.decode = VerifyStream.decode;\nexports.isValid = VerifyStream.isValid;\nexports.createSign = function createSign(opts) {\n return new SignStream(opts);\n};\nexports.createVerify = function createVerify(opts) {\n return new VerifyStream(opts);\n};\n", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.GoogleToken = void 0;\nvar fs = _interopRequireWildcard(require(\"fs\"));\nvar _gaxios = require(\"gaxios\");\nvar jws = _interopRequireWildcard(require(\"jws\"));\nvar path = _interopRequireWildcard(require(\"path\"));\nvar _util = require(\"util\");\nfunction _interopRequireWildcard(e, t) { if (\"function\" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, \"default\": e }; if (null === e || \"object\" != _typeof(e) && \"function\" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t3 in e) \"default\" !== _t3 && {}.hasOwnProperty.call(e, _t3) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t3)) && (i.get || i.set) ? o(f, _t3, i) : f[_t3] = e[_t3]); return f; })(e, t); }\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _classPrivateMethodInitSpec(e, a) { _checkPrivateRedeclaration(e, a), a.add(e); }\nfunction _classPrivateFieldInitSpec(e, t, a) { _checkPrivateRedeclaration(e, t), t.set(e, a); }\nfunction _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError(\"Cannot initialize the same private elements twice on an object\"); }\nfunction _classPrivateFieldSet(s, a, r) { return s.set(_assertClassBrand(s, a), r), r; }\nfunction _classPrivateFieldGet(s, a) { return s.get(_assertClassBrand(s, a)); }\nfunction _assertClassBrand(e, t, n) { if (\"function\" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError(\"Private element is not present on this object\"); }\nfunction _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, \"value\" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }\nfunction _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, \"prototype\", { writable: !1 }), e; }\nfunction _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError(\"Cannot call a class as a function\"); }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(t, e) { if (e && (\"object\" == _typeof(e) || \"function\" == typeof e)) return e; if (void 0 !== e) throw new TypeError(\"Derived constructors may only return object or undefined\"); return _assertThisInitialized(t); }\nfunction _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); return e; }\nfunction _inherits(t, e) { if (\"function\" != typeof e && null !== e) throw new TypeError(\"Super expression must either be null or a function\"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, \"prototype\", { writable: !1 }), e && _setPrototypeOf(t, e); }\nfunction _wrapNativeSuper(t) { var r = \"function\" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if (\"function\" != typeof t) throw new TypeError(\"Super expression must either be null or a function\"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); }\nfunction _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf(\"[native code]\"); } catch (n) { return \"function\" == typeof t; } }\nfunction _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }\nfunction _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = \"function\" == typeof Symbol ? Symbol : {}, n = r.iterator || \"@@iterator\", o = r.toStringTag || \"@@toStringTag\"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, \"_invoke\", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError(\"Generator is already running\"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = \"next\"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError(\"iterator result is not an object\"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i[\"return\"]) && t.call(i), c < 2 && (u = TypeError(\"The iterator does not provide a '\" + o + \"' method\"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, \"GeneratorFunction\")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, \"constructor\", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, \"constructor\", GeneratorFunction), GeneratorFunction.displayName = \"GeneratorFunction\", _regeneratorDefine2(GeneratorFunctionPrototype, o, \"GeneratorFunction\"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, \"Generator\"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, \"toString\", function () { return \"[object Generator]\"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }\nfunction _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, \"\", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { if (r) i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n;else { var o = function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); }; o(\"next\", 0), o(\"throw\", 1), o(\"return\", 2); } }, _regeneratorDefine2(e, r, n, t); }\nfunction asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }\nfunction _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, \"next\", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, \"throw\", n); } _next(void 0); }); }; } /**\n * Copyright 2018 Google LLC\n *\n * Distributed under MIT license.\n * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT\n */\nvar readFile = fs.readFile ? (0, _util.promisify)(fs.readFile) : /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {\n return _regenerator().w(function (_context) {\n while (1) switch (_context.n) {\n case 0:\n throw new ErrorWithCode('use key rather than keyFile.', 'MISSING_CREDENTIALS');\n case 1:\n return _context.a(2);\n }\n }, _callee);\n}));\nvar GOOGLE_TOKEN_URL = 'https://oauth2.googleapis.com/token';\nvar GOOGLE_REVOKE_TOKEN_URL = 'https://oauth2.googleapis.com/revoke?token=';\nvar ErrorWithCode = /*#__PURE__*/function (_Error) {\n function ErrorWithCode(message, code) {\n var _this;\n _classCallCheck(this, ErrorWithCode);\n _this = _callSuper(this, ErrorWithCode, [message]);\n _defineProperty(_this, \"code\", void 0);\n _this.code = code;\n return _this;\n }\n _inherits(ErrorWithCode, _Error);\n return _createClass(ErrorWithCode);\n}(/*#__PURE__*/_wrapNativeSuper(Error));\nvar _inFlightRequest = /*#__PURE__*/new WeakMap();\nvar _GoogleToken_brand = /*#__PURE__*/new WeakSet();\nvar GoogleToken = exports.GoogleToken = /*#__PURE__*/function () {\n /**\n * Create a GoogleToken.\n *\n * @param options Configuration object.\n */\n function GoogleToken(_options) {\n _classCallCheck(this, GoogleToken);\n _classPrivateMethodInitSpec(this, _GoogleToken_brand);\n _defineProperty(this, \"expiresAt\", void 0);\n _defineProperty(this, \"key\", void 0);\n _defineProperty(this, \"keyFile\", void 0);\n _defineProperty(this, \"iss\", void 0);\n _defineProperty(this, \"sub\", void 0);\n _defineProperty(this, \"scope\", void 0);\n _defineProperty(this, \"rawToken\", void 0);\n _defineProperty(this, \"tokenExpires\", void 0);\n _defineProperty(this, \"email\", void 0);\n _defineProperty(this, \"additionalClaims\", void 0);\n _defineProperty(this, \"eagerRefreshThresholdMillis\", void 0);\n _defineProperty(this, \"transporter\", {\n request: function request(opts) {\n return (0, _gaxios.request)(opts);\n }\n });\n _classPrivateFieldInitSpec(this, _inFlightRequest, void 0);\n _assertClassBrand(_GoogleToken_brand, this, _configure).call(this, _options);\n }\n\n /**\n * Returns whether the token has expired.\n *\n * @return true if the token has expired, false otherwise.\n */\n return _createClass(GoogleToken, [{\n key: \"accessToken\",\n get: function get() {\n return this.rawToken ? this.rawToken.access_token : undefined;\n }\n }, {\n key: \"idToken\",\n get: function get() {\n return this.rawToken ? this.rawToken.id_token : undefined;\n }\n }, {\n key: \"tokenType\",\n get: function get() {\n return this.rawToken ? this.rawToken.token_type : undefined;\n }\n }, {\n key: \"refreshToken\",\n get: function get() {\n return this.rawToken ? this.rawToken.refresh_token : undefined;\n }\n }, {\n key: \"hasExpired\",\n value: function hasExpired() {\n var now = new Date().getTime();\n if (this.rawToken && this.expiresAt) {\n return now >= this.expiresAt;\n } else {\n return true;\n }\n }\n\n /**\n * Returns whether the token will expire within eagerRefreshThresholdMillis\n *\n * @return true if the token will be expired within eagerRefreshThresholdMillis, false otherwise.\n */\n }, {\n key: \"isTokenExpiring\",\n value: function isTokenExpiring() {\n var _this$eagerRefreshThr;\n var now = new Date().getTime();\n var eagerRefreshThresholdMillis = (_this$eagerRefreshThr = this.eagerRefreshThresholdMillis) !== null && _this$eagerRefreshThr !== void 0 ? _this$eagerRefreshThr : 0;\n if (this.rawToken && this.expiresAt) {\n return this.expiresAt <= now + eagerRefreshThresholdMillis;\n } else {\n return true;\n }\n }\n\n /**\n * Returns a cached token or retrieves a new one from Google.\n *\n * @param callback The callback function.\n */\n }, {\n key: \"getToken\",\n value: function getToken(callback) {\n var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n if (_typeof(callback) === 'object') {\n opts = callback;\n callback = undefined;\n }\n opts = Object.assign({\n forceRefresh: false\n }, opts);\n if (callback) {\n var cb = callback;\n _assertClassBrand(_GoogleToken_brand, this, _getTokenAsync).call(this, opts).then(function (t) {\n return cb(null, t);\n }, callback);\n return;\n }\n return _assertClassBrand(_GoogleToken_brand, this, _getTokenAsync).call(this, opts);\n }\n\n /**\n * Given a keyFile, extract the key and client email if available\n * @param keyFile Path to a json, pem, or p12 file that contains the key.\n * @returns an object with privateKey and clientEmail properties\n */\n }, {\n key: \"getCredentials\",\n value: (function () {\n var _getCredentials = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(keyFile) {\n var ext, key, body, privateKey, clientEmail, _privateKey, _t;\n return _regenerator().w(function (_context2) {\n while (1) switch (_context2.n) {\n case 0:\n ext = path.extname(keyFile);\n _t = ext;\n _context2.n = _t === '.json' ? 1 : _t === '.der' ? 4 : _t === '.crt' ? 4 : _t === '.pem' ? 4 : _t === '.p12' ? 6 : _t === '.pfx' ? 6 : 7;\n break;\n case 1:\n _context2.n = 2;\n return readFile(keyFile, 'utf8');\n case 2:\n key = _context2.v;\n body = JSON.parse(key);\n privateKey = body.private_key;\n clientEmail = body.client_email;\n if (!(!privateKey || !clientEmail)) {\n _context2.n = 3;\n break;\n }\n throw new ErrorWithCode('private_key and client_email are required.', 'MISSING_CREDENTIALS');\n case 3:\n return _context2.a(2, {\n privateKey: privateKey,\n clientEmail: clientEmail\n });\n case 4:\n _context2.n = 5;\n return readFile(keyFile, 'utf8');\n case 5:\n _privateKey = _context2.v;\n return _context2.a(2, {\n privateKey: _privateKey\n });\n case 6:\n throw new ErrorWithCode('*.p12 certificates are not supported after v6.1.2. ' + 'Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.', 'UNKNOWN_CERTIFICATE_TYPE');\n case 7:\n throw new ErrorWithCode('Unknown certificate type. Type is determined based on file extension. ' + 'Current supported extensions are *.json, and *.pem.', 'UNKNOWN_CERTIFICATE_TYPE');\n case 8:\n return _context2.a(2);\n }\n }, _callee2);\n }));\n function getCredentials(_x) {\n return _getCredentials.apply(this, arguments);\n }\n return getCredentials;\n }())\n }, {\n key: \"revokeToken\",\n value: function revokeToken(callback) {\n if (callback) {\n _assertClassBrand(_GoogleToken_brand, this, _revokeTokenAsync).call(this).then(function () {\n return callback();\n }, callback);\n return;\n }\n return _assertClassBrand(_GoogleToken_brand, this, _revokeTokenAsync).call(this);\n }\n }]);\n}();\nfunction _getTokenAsync(_x2) {\n return _getTokenAsync2.apply(this, arguments);\n}\nfunction _getTokenAsync2() {\n _getTokenAsync2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(opts) {\n return _regenerator().w(function (_context3) {\n while (1) switch (_context3.n) {\n case 0:\n if (!(_classPrivateFieldGet(_inFlightRequest, this) && !opts.forceRefresh)) {\n _context3.n = 1;\n break;\n }\n return _context3.a(2, _classPrivateFieldGet(_inFlightRequest, this));\n case 1:\n _context3.p = 1;\n _context3.n = 2;\n return _classPrivateFieldSet(_inFlightRequest, this, _assertClassBrand(_GoogleToken_brand, this, _getTokenAsyncInner).call(this, opts));\n case 2:\n return _context3.a(2, _context3.v);\n case 3:\n _context3.p = 3;\n _classPrivateFieldSet(_inFlightRequest, this, undefined);\n return _context3.f(3);\n case 4:\n return _context3.a(2);\n }\n }, _callee3, this, [[1,, 3, 4]]);\n }));\n return _getTokenAsync2.apply(this, arguments);\n}\nfunction _getTokenAsyncInner(_x3) {\n return _getTokenAsyncInner2.apply(this, arguments);\n}\nfunction _getTokenAsyncInner2() {\n _getTokenAsyncInner2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(opts) {\n var creds;\n return _regenerator().w(function (_context4) {\n while (1) switch (_context4.n) {\n case 0:\n if (!(this.isTokenExpiring() === false && opts.forceRefresh === false)) {\n _context4.n = 1;\n break;\n }\n return _context4.a(2, Promise.resolve(this.rawToken));\n case 1:\n if (!(!this.key && !this.keyFile)) {\n _context4.n = 2;\n break;\n }\n throw new Error('No key or keyFile set.');\n case 2:\n if (!(!this.key && this.keyFile)) {\n _context4.n = 4;\n break;\n }\n _context4.n = 3;\n return this.getCredentials(this.keyFile);\n case 3:\n creds = _context4.v;\n this.key = creds.privateKey;\n this.iss = creds.clientEmail || this.iss;\n if (!creds.clientEmail) {\n _assertClassBrand(_GoogleToken_brand, this, _ensureEmail).call(this);\n }\n case 4:\n return _context4.a(2, _assertClassBrand(_GoogleToken_brand, this, _requestToken).call(this));\n }\n }, _callee4, this);\n }));\n return _getTokenAsyncInner2.apply(this, arguments);\n}\nfunction _ensureEmail() {\n if (!this.iss) {\n throw new ErrorWithCode('email is required.', 'MISSING_CREDENTIALS');\n }\n}\nfunction _revokeTokenAsync() {\n return _revokeTokenAsync2.apply(this, arguments);\n}\nfunction _revokeTokenAsync2() {\n _revokeTokenAsync2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5() {\n var url;\n return _regenerator().w(function (_context5) {\n while (1) switch (_context5.n) {\n case 0:\n if (this.accessToken) {\n _context5.n = 1;\n break;\n }\n throw new Error('No token to revoke.');\n case 1:\n url = GOOGLE_REVOKE_TOKEN_URL + this.accessToken;\n _context5.n = 2;\n return this.transporter.request({\n url: url,\n retry: true\n });\n case 2:\n _assertClassBrand(_GoogleToken_brand, this, _configure).call(this, {\n email: this.iss,\n sub: this.sub,\n key: this.key,\n keyFile: this.keyFile,\n scope: this.scope,\n additionalClaims: this.additionalClaims\n });\n case 3:\n return _context5.a(2);\n }\n }, _callee5, this);\n }));\n return _revokeTokenAsync2.apply(this, arguments);\n}\n/**\n * Configure the GoogleToken for re-use.\n * @param {object} options Configuration object.\n */\nfunction _configure() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n this.keyFile = options.keyFile;\n this.key = options.key;\n this.rawToken = undefined;\n this.iss = options.email || options.iss;\n this.sub = options.sub;\n this.additionalClaims = options.additionalClaims;\n if (_typeof(options.scope) === 'object') {\n this.scope = options.scope.join(' ');\n } else {\n this.scope = options.scope;\n }\n this.eagerRefreshThresholdMillis = options.eagerRefreshThresholdMillis;\n if (options.transporter) {\n this.transporter = options.transporter;\n }\n}\n/**\n * Request the token from Google.\n */\nfunction _requestToken() {\n return _requestToken2.apply(this, arguments);\n}\nfunction _requestToken2() {\n _requestToken2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6() {\n var iat, additionalClaims, payload, signedJWT, r, _response, _response2, body, desc, _t2;\n return _regenerator().w(function (_context6) {\n while (1) switch (_context6.n) {\n case 0:\n iat = Math.floor(new Date().getTime() / 1000);\n additionalClaims = this.additionalClaims || {};\n payload = Object.assign({\n iss: this.iss,\n scope: this.scope,\n aud: GOOGLE_TOKEN_URL,\n exp: iat + 3600,\n iat: iat,\n sub: this.sub\n }, additionalClaims);\n signedJWT = jws.sign({\n header: {\n alg: 'RS256'\n },\n payload: payload,\n secret: this.key\n });\n _context6.p = 1;\n _context6.n = 2;\n return this.transporter.request({\n method: 'POST',\n url: GOOGLE_TOKEN_URL,\n data: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',\n assertion: signedJWT\n }),\n responseType: 'json',\n retryConfig: {\n httpMethodsToRetry: ['POST']\n }\n });\n case 2:\n r = _context6.v;\n this.rawToken = r.data;\n this.expiresAt = r.data.expires_in === null || r.data.expires_in === undefined ? undefined : (iat + r.data.expires_in) * 1000;\n return _context6.a(2, this.rawToken);\n case 3:\n _context6.p = 3;\n _t2 = _context6.v;\n this.rawToken = undefined;\n this.tokenExpires = undefined;\n body = _t2.response && (_response = _t2.response) !== null && _response !== void 0 && _response.data ? (_response2 = _t2.response) === null || _response2 === void 0 ? void 0 : _response2.data : {};\n if (body.error) {\n desc = body.error_description ? \": \".concat(body.error_description) : '';\n _t2.message = \"\".concat(body.error).concat(desc);\n }\n throw _t2;\n case 4:\n return _context6.a(2);\n }\n }, _callee6, this, [[1, 3]]);\n }));\n return _requestToken2.apply(this, arguments);\n}", "\"use strict\";\n// Copyright 2015 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.JWTAccess = void 0;\nconst jws = require(\"jws\");\nconst util_1 = require(\"../util\");\nconst DEFAULT_HEADER = {\n alg: 'RS256',\n typ: 'JWT',\n};\nclass JWTAccess {\n email;\n key;\n keyId;\n projectId;\n eagerRefreshThresholdMillis;\n cache = new util_1.LRUCache({\n capacity: 500,\n maxAge: 60 * 60 * 1000,\n });\n /**\n * JWTAccess service account credentials.\n *\n * Create a new access token by using the credential to create a new JWT token\n * that's recognized as the access token.\n *\n * @param email the service account email address.\n * @param key the private key that will be used to sign the token.\n * @param keyId the ID of the private key used to sign the token.\n */\n constructor(email, key, keyId, eagerRefreshThresholdMillis) {\n this.email = email;\n this.key = key;\n this.keyId = keyId;\n this.eagerRefreshThresholdMillis =\n eagerRefreshThresholdMillis ?? 5 * 60 * 1000;\n }\n /**\n * Ensures that we're caching a key appropriately, giving precedence to scopes vs. url\n *\n * @param url The URI being authorized.\n * @param scopes The scope or scopes being authorized\n * @returns A string that returns the cached key.\n */\n getCachedKey(url, scopes) {\n let cacheKey = url;\n if (scopes && Array.isArray(scopes) && scopes.length) {\n cacheKey = url ? `${url}_${scopes.join('_')}` : `${scopes.join('_')}`;\n }\n else if (typeof scopes === 'string') {\n cacheKey = url ? `${url}_${scopes}` : scopes;\n }\n if (!cacheKey) {\n throw Error('Scopes or url must be provided');\n }\n return cacheKey;\n }\n /**\n * Get a non-expired access token, after refreshing if necessary.\n *\n * @param url The URI being authorized.\n * @param additionalClaims An object with a set of additional claims to\n * include in the payload.\n * @returns An object that includes the authorization header.\n */\n getRequestHeaders(url, additionalClaims, scopes) {\n // Return cached authorization headers, unless we are within\n // eagerRefreshThresholdMillis ms of them expiring:\n const key = this.getCachedKey(url, scopes);\n const cachedToken = this.cache.get(key);\n const now = Date.now();\n if (cachedToken &&\n cachedToken.expiration - now > this.eagerRefreshThresholdMillis) {\n // Copying headers into a new `Headers` object to avoid potential leakage -\n // as this is a cache it is possible for multiple requests to reference this\n // same value.\n return new Headers(cachedToken.headers);\n }\n const iat = Math.floor(Date.now() / 1000);\n const exp = JWTAccess.getExpirationTime(iat);\n let defaultClaims;\n // Turn scopes into space-separated string\n if (Array.isArray(scopes)) {\n scopes = scopes.join(' ');\n }\n // If scopes are specified, sign with scopes\n if (scopes) {\n defaultClaims = {\n iss: this.email,\n sub: this.email,\n scope: scopes,\n exp,\n iat,\n };\n }\n else {\n defaultClaims = {\n iss: this.email,\n sub: this.email,\n aud: url,\n exp,\n iat,\n };\n }\n // if additionalClaims are provided, ensure they do not collide with\n // other required claims.\n if (additionalClaims) {\n for (const claim in defaultClaims) {\n if (additionalClaims[claim]) {\n throw new Error(`The '${claim}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`);\n }\n }\n }\n const header = this.keyId\n ? { ...DEFAULT_HEADER, kid: this.keyId }\n : DEFAULT_HEADER;\n const payload = Object.assign(defaultClaims, additionalClaims);\n // Sign the jwt and add it to the cache\n const signedJWT = jws.sign({ header, payload, secret: this.key });\n const headers = new Headers({ authorization: `Bearer ${signedJWT}` });\n this.cache.set(key, {\n expiration: exp * 1000,\n headers,\n });\n return headers;\n }\n /**\n * Returns an expiration time for the JWT token.\n *\n * @param iat The issued at time for the JWT.\n * @returns An expiration time for the JWT.\n */\n static getExpirationTime(iat) {\n const exp = iat + 3600; // 3600 seconds = 1 hour\n return exp;\n }\n /**\n * Create a JWTAccess credentials instance using the given input options.\n * @param json The input object.\n */\n fromJSON(json) {\n if (!json) {\n throw new Error('Must pass in a JSON object containing the service account auth settings.');\n }\n if (!json.client_email) {\n throw new Error('The incoming JSON object does not contain a client_email field');\n }\n if (!json.private_key) {\n throw new Error('The incoming JSON object does not contain a private_key field');\n }\n // Extract the relevant information from the json key file.\n this.email = json.client_email;\n this.key = json.private_key;\n this.keyId = json.private_key_id;\n this.projectId = json.project_id;\n }\n fromStream(inputStream, callback) {\n if (callback) {\n this.fromStreamAsync(inputStream).then(() => callback(), callback);\n }\n else {\n return this.fromStreamAsync(inputStream);\n }\n }\n fromStreamAsync(inputStream) {\n return new Promise((resolve, reject) => {\n if (!inputStream) {\n reject(new Error('Must pass in a stream containing the service account auth settings.'));\n }\n let s = '';\n inputStream\n .setEncoding('utf8')\n .on('data', chunk => (s += chunk))\n .on('error', reject)\n .on('end', () => {\n try {\n const data = JSON.parse(s);\n this.fromJSON(data);\n resolve();\n }\n catch (err) {\n reject(err);\n }\n });\n });\n }\n}\nexports.JWTAccess = JWTAccess;\n//# sourceMappingURL=jwtaccess.js.map", "\"use strict\";\n// Copyright 2013 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.JWT = void 0;\nconst gtoken_1 = require(\"gtoken\");\nconst jwtaccess_1 = require(\"./jwtaccess\");\nconst oauth2client_1 = require(\"./oauth2client\");\nconst authclient_1 = require(\"./authclient\");\nclass JWT extends oauth2client_1.OAuth2Client {\n email;\n keyFile;\n key;\n keyId;\n defaultScopes;\n scopes;\n scope;\n subject;\n gtoken;\n additionalClaims;\n useJWTAccessWithScope;\n defaultServicePath;\n access;\n /**\n * JWT service account credentials.\n *\n * Retrieve access token using gtoken.\n *\n * @param options the\n */\n constructor(options = {}) {\n super(options);\n this.email = options.email;\n this.keyFile = options.keyFile;\n this.key = options.key;\n this.keyId = options.keyId;\n this.scopes = options.scopes;\n this.subject = options.subject;\n this.additionalClaims = options.additionalClaims;\n // Start with an expired refresh token, which will automatically be\n // refreshed before the first API call is made.\n this.credentials = { refresh_token: 'jwt-placeholder', expiry_date: 1 };\n }\n /**\n * Creates a copy of the credential with the specified scopes.\n * @param scopes List of requested scopes or a single scope.\n * @return The cloned instance.\n */\n createScoped(scopes) {\n const jwt = new JWT(this);\n jwt.scopes = scopes;\n return jwt;\n }\n /**\n * Obtains the metadata to be sent with the request.\n *\n * @param url the URI being authorized.\n */\n async getRequestMetadataAsync(url) {\n url = this.defaultServicePath ? `https://${this.defaultServicePath}/` : url;\n const useSelfSignedJWT = (!this.hasUserScopes() && url) ||\n (this.useJWTAccessWithScope && this.hasAnyScopes()) ||\n this.universeDomain !== authclient_1.DEFAULT_UNIVERSE;\n if (this.subject && this.universeDomain !== authclient_1.DEFAULT_UNIVERSE) {\n throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${authclient_1.DEFAULT_UNIVERSE}`);\n }\n if (!this.apiKey && useSelfSignedJWT) {\n if (this.additionalClaims &&\n this.additionalClaims.target_audience) {\n const { tokens } = await this.refreshToken();\n return {\n headers: this.addSharedMetadataHeaders(new Headers({\n authorization: `Bearer ${tokens.id_token}`,\n })),\n };\n }\n else {\n // no scopes have been set, but a uri has been provided. Use JWTAccess\n // credentials.\n if (!this.access) {\n this.access = new jwtaccess_1.JWTAccess(this.email, this.key, this.keyId, this.eagerRefreshThresholdMillis);\n }\n let scopes;\n if (this.hasUserScopes()) {\n scopes = this.scopes;\n }\n else if (!url) {\n scopes = this.defaultScopes;\n }\n const useScopes = this.useJWTAccessWithScope ||\n this.universeDomain !== authclient_1.DEFAULT_UNIVERSE;\n const headers = await this.access.getRequestHeaders(url ?? undefined, this.additionalClaims, \n // Scopes take precedent over audience for signing,\n // so we only provide them if `useJWTAccessWithScope` is on or\n // if we are in a non-default universe\n useScopes ? scopes : undefined);\n return { headers: this.addSharedMetadataHeaders(headers) };\n }\n }\n else if (this.hasAnyScopes() || this.apiKey) {\n return super.getRequestMetadataAsync(url);\n }\n else {\n // If no audience, apiKey, or scopes are provided, we should not attempt\n // to populate any headers:\n return { headers: new Headers() };\n }\n }\n /**\n * Fetches an ID token.\n * @param targetAudience the audience for the fetched ID token.\n */\n async fetchIdToken(targetAudience) {\n // Create a new gToken for fetching an ID token\n const gtoken = new gtoken_1.GoogleToken({\n iss: this.email,\n sub: this.subject,\n scope: this.scopes || this.defaultScopes,\n keyFile: this.keyFile,\n key: this.key,\n additionalClaims: { target_audience: targetAudience },\n transporter: this.transporter,\n });\n await gtoken.getToken({\n forceRefresh: true,\n });\n if (!gtoken.idToken) {\n throw new Error('Unknown error: Failed to fetch ID token');\n }\n return gtoken.idToken;\n }\n /**\n * Determine if there are currently scopes available.\n */\n hasUserScopes() {\n if (!this.scopes) {\n return false;\n }\n return this.scopes.length > 0;\n }\n /**\n * Are there any default or user scopes defined.\n */\n hasAnyScopes() {\n if (this.scopes && this.scopes.length > 0)\n return true;\n if (this.defaultScopes && this.defaultScopes.length > 0)\n return true;\n return false;\n }\n authorize(callback) {\n if (callback) {\n this.authorizeAsync().then(r => callback(null, r), callback);\n }\n else {\n return this.authorizeAsync();\n }\n }\n async authorizeAsync() {\n const result = await this.refreshToken();\n if (!result) {\n throw new Error('No result returned');\n }\n this.credentials = result.tokens;\n this.credentials.refresh_token = 'jwt-placeholder';\n this.key = this.gtoken.key;\n this.email = this.gtoken.iss;\n return result.tokens;\n }\n /**\n * Refreshes the access token.\n * @param refreshToken ignored\n * @private\n */\n async refreshTokenNoCache() {\n const gtoken = this.createGToken();\n const token = await gtoken.getToken({\n forceRefresh: this.isTokenExpiring(),\n });\n const tokens = {\n access_token: token.access_token,\n token_type: 'Bearer',\n expiry_date: gtoken.expiresAt,\n id_token: gtoken.idToken,\n };\n this.emit('tokens', tokens);\n return { res: null, tokens };\n }\n /**\n * Create a gToken if it doesn't already exist.\n */\n createGToken() {\n if (!this.gtoken) {\n this.gtoken = new gtoken_1.GoogleToken({\n iss: this.email,\n sub: this.subject,\n scope: this.scopes || this.defaultScopes,\n keyFile: this.keyFile,\n key: this.key,\n additionalClaims: this.additionalClaims,\n transporter: this.transporter,\n });\n }\n return this.gtoken;\n }\n /**\n * Create a JWT credentials instance using the given input options.\n * @param json The input object.\n *\n * @remarks\n *\n * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}.\n */\n fromJSON(json) {\n if (!json) {\n throw new Error('Must pass in a JSON object containing the service account auth settings.');\n }\n if (!json.client_email) {\n throw new Error('The incoming JSON object does not contain a client_email field');\n }\n if (!json.private_key) {\n throw new Error('The incoming JSON object does not contain a private_key field');\n }\n // Extract the relevant information from the json key file.\n this.email = json.client_email;\n this.key = json.private_key;\n this.keyId = json.private_key_id;\n this.projectId = json.project_id;\n this.quotaProjectId = json.quota_project_id;\n this.universeDomain = json.universe_domain || this.universeDomain;\n }\n fromStream(inputStream, callback) {\n if (callback) {\n this.fromStreamAsync(inputStream).then(() => callback(), callback);\n }\n else {\n return this.fromStreamAsync(inputStream);\n }\n }\n fromStreamAsync(inputStream) {\n return new Promise((resolve, reject) => {\n if (!inputStream) {\n throw new Error('Must pass in a stream containing the service account auth settings.');\n }\n let s = '';\n inputStream\n .setEncoding('utf8')\n .on('error', reject)\n .on('data', chunk => (s += chunk))\n .on('end', () => {\n try {\n const data = JSON.parse(s);\n this.fromJSON(data);\n resolve();\n }\n catch (e) {\n reject(e);\n }\n });\n });\n }\n /**\n * Creates a JWT credentials instance using an API Key for authentication.\n * @param apiKey The API Key in string form.\n */\n fromAPIKey(apiKey) {\n if (typeof apiKey !== 'string') {\n throw new Error('Must provide an API Key string.');\n }\n this.apiKey = apiKey;\n }\n /**\n * Using the key or keyFile on the JWT client, obtain an object that contains\n * the key and the client email.\n */\n async getCredentials() {\n if (this.key) {\n return { private_key: this.key, client_email: this.email };\n }\n else if (this.keyFile) {\n const gtoken = this.createGToken();\n const creds = await gtoken.getCredentials(this.keyFile);\n return { private_key: creds.privateKey, client_email: creds.clientEmail };\n }\n throw new Error('A key or a keyFile must be provided to getCredentials.');\n }\n}\nexports.JWT = JWT;\n//# sourceMappingURL=jwtclient.js.map", "\"use strict\";\n// Copyright 2015 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.UserRefreshClient = exports.USER_REFRESH_ACCOUNT_TYPE = void 0;\nconst oauth2client_1 = require(\"./oauth2client\");\nconst authclient_1 = require(\"./authclient\");\nexports.USER_REFRESH_ACCOUNT_TYPE = 'authorized_user';\nclass UserRefreshClient extends oauth2client_1.OAuth2Client {\n // TODO: refactor tests to make this private\n // In a future gts release, the _propertyName rule will be lifted.\n // This is also a hard one because `this.refreshToken` is a function.\n _refreshToken;\n /**\n * The User Refresh Token client.\n *\n * @param optionsOrClientId The User Refresh Token client options. Passing an `clientId` directly is **@DEPRECATED**.\n * @param clientSecret **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.\n * @param refreshToken **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.\n * @param eagerRefreshThresholdMillis **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.\n * @param forceRefreshOnFailure **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.\n */\n constructor(optionsOrClientId, \n /**\n * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead\n */\n clientSecret, \n /**\n * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead\n */\n refreshToken, \n /**\n * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead\n */\n eagerRefreshThresholdMillis, \n /**\n * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead\n */\n forceRefreshOnFailure) {\n const opts = optionsOrClientId && typeof optionsOrClientId === 'object'\n ? optionsOrClientId\n : {\n clientId: optionsOrClientId,\n clientSecret,\n refreshToken,\n eagerRefreshThresholdMillis,\n forceRefreshOnFailure,\n };\n super(opts);\n this._refreshToken = opts.refreshToken;\n this.credentials.refresh_token = opts.refreshToken;\n }\n /**\n * Refreshes the access token.\n * @param refreshToken An ignored refreshToken..\n * @param callback Optional callback.\n */\n async refreshTokenNoCache() {\n return super.refreshTokenNoCache(this._refreshToken);\n }\n async fetchIdToken(targetAudience) {\n const opts = {\n ...UserRefreshClient.RETRY_CONFIG,\n url: this.endpoints.oauth2TokenUrl,\n method: 'POST',\n data: new URLSearchParams({\n client_id: this._clientId,\n client_secret: this._clientSecret,\n grant_type: 'refresh_token',\n refresh_token: this._refreshToken,\n target_audience: targetAudience,\n }),\n };\n authclient_1.AuthClient.setMethodName(opts, 'fetchIdToken');\n const res = await this.transporter.request(opts);\n return res.data.id_token;\n }\n /**\n * Create a UserRefreshClient credentials instance using the given input\n * options.\n * @param json The input object.\n */\n fromJSON(json) {\n if (!json) {\n throw new Error('Must pass in a JSON object containing the user refresh token');\n }\n if (json.type !== 'authorized_user') {\n throw new Error('The incoming JSON object does not have the \"authorized_user\" type');\n }\n if (!json.client_id) {\n throw new Error('The incoming JSON object does not contain a client_id field');\n }\n if (!json.client_secret) {\n throw new Error('The incoming JSON object does not contain a client_secret field');\n }\n if (!json.refresh_token) {\n throw new Error('The incoming JSON object does not contain a refresh_token field');\n }\n this._clientId = json.client_id;\n this._clientSecret = json.client_secret;\n this._refreshToken = json.refresh_token;\n this.credentials.refresh_token = json.refresh_token;\n this.quotaProjectId = json.quota_project_id;\n this.universeDomain = json.universe_domain || this.universeDomain;\n }\n fromStream(inputStream, callback) {\n if (callback) {\n this.fromStreamAsync(inputStream).then(() => callback(), callback);\n }\n else {\n return this.fromStreamAsync(inputStream);\n }\n }\n async fromStreamAsync(inputStream) {\n return new Promise((resolve, reject) => {\n if (!inputStream) {\n return reject(new Error('Must pass in a stream containing the user refresh token.'));\n }\n let s = '';\n inputStream\n .setEncoding('utf8')\n .on('error', reject)\n .on('data', chunk => (s += chunk))\n .on('end', () => {\n try {\n const data = JSON.parse(s);\n this.fromJSON(data);\n return resolve();\n }\n catch (err) {\n return reject(err);\n }\n });\n });\n }\n /**\n * Create a UserRefreshClient credentials instance using the given input\n * options.\n * @param json The input object.\n */\n static fromJSON(json) {\n const client = new UserRefreshClient();\n client.fromJSON(json);\n return client;\n }\n}\nexports.UserRefreshClient = UserRefreshClient;\n//# sourceMappingURL=refreshclient.js.map", "\"use strict\";\n/**\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Impersonated = exports.IMPERSONATED_ACCOUNT_TYPE = void 0;\nconst oauth2client_1 = require(\"./oauth2client\");\nconst gaxios_1 = require(\"gaxios\");\nconst util_1 = require(\"../util\");\nexports.IMPERSONATED_ACCOUNT_TYPE = 'impersonated_service_account';\nclass Impersonated extends oauth2client_1.OAuth2Client {\n sourceClient;\n targetPrincipal;\n targetScopes;\n delegates;\n lifetime;\n endpoint;\n /**\n * Impersonated service account credentials.\n *\n * Create a new access token by impersonating another service account.\n *\n * Impersonated Credentials allowing credentials issued to a user or\n * service account to impersonate another. The source project using\n * Impersonated Credentials must enable the \"IAMCredentials\" API.\n * Also, the target service account must grant the orginating principal\n * the \"Service Account Token Creator\" IAM role.\n *\n * @param {object} options - The configuration object.\n * @param {object} [options.sourceClient] the source credential used as to\n * acquire the impersonated credentials.\n * @param {string} [options.targetPrincipal] the service account to\n * impersonate.\n * @param {string[]} [options.delegates] the chained list of delegates\n * required to grant the final access_token. If set, the sequence of\n * identities must have \"Service Account Token Creator\" capability granted to\n * the preceding identity. For example, if set to [serviceAccountB,\n * serviceAccountC], the sourceCredential must have the Token Creator role on\n * serviceAccountB. serviceAccountB must have the Token Creator on\n * serviceAccountC. Finally, C must have Token Creator on target_principal.\n * If left unset, sourceCredential must have that role on targetPrincipal.\n * @param {string[]} [options.targetScopes] scopes to request during the\n * authorization grant.\n * @param {number} [options.lifetime] number of seconds the delegated\n * credential should be valid for up to 3600 seconds by default, or 43,200\n * seconds by extending the token's lifetime, see:\n * https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth\n * @param {string} [options.endpoint] api endpoint override.\n */\n constructor(options = {}) {\n super(options);\n // Start with an expired refresh token, which will automatically be\n // refreshed before the first API call is made.\n this.credentials = {\n expiry_date: 1,\n refresh_token: 'impersonated-placeholder',\n };\n this.sourceClient = options.sourceClient ?? new oauth2client_1.OAuth2Client();\n this.targetPrincipal = options.targetPrincipal ?? '';\n this.delegates = options.delegates ?? [];\n this.targetScopes = options.targetScopes ?? [];\n this.lifetime = options.lifetime ?? 3600;\n const usingExplicitUniverseDomain = !!(0, util_1.originalOrCamelOptions)(options).get('universe_domain');\n if (!usingExplicitUniverseDomain) {\n // override the default universe with the source's universe\n this.universeDomain = this.sourceClient.universeDomain;\n }\n else if (this.sourceClient.universeDomain !== this.universeDomain) {\n // non-default universe and is not matching the source - this could be a credential leak\n throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);\n }\n this.endpoint =\n options.endpoint ?? `https://iamcredentials.${this.universeDomain}`;\n }\n /**\n * Signs some bytes.\n *\n * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob Reference Documentation}\n * @param blobToSign String to sign.\n *\n * @returns A {@link SignBlobResponse} denoting the keyID and signedBlob in base64 string\n */\n async sign(blobToSign) {\n await this.sourceClient.getAccessToken();\n const name = `projects/-/serviceAccounts/${this.targetPrincipal}`;\n const u = `${this.endpoint}/v1/${name}:signBlob`;\n const body = {\n delegates: this.delegates,\n payload: Buffer.from(blobToSign).toString('base64'),\n };\n const res = await this.sourceClient.request({\n ...Impersonated.RETRY_CONFIG,\n url: u,\n data: body,\n method: 'POST',\n });\n return res.data;\n }\n /** The service account email to be impersonated. */\n getTargetPrincipal() {\n return this.targetPrincipal;\n }\n /**\n * Refreshes the access token.\n */\n async refreshToken() {\n try {\n await this.sourceClient.getAccessToken();\n const name = 'projects/-/serviceAccounts/' + this.targetPrincipal;\n const u = `${this.endpoint}/v1/${name}:generateAccessToken`;\n const body = {\n delegates: this.delegates,\n scope: this.targetScopes,\n lifetime: this.lifetime + 's',\n };\n const res = await this.sourceClient.request({\n ...Impersonated.RETRY_CONFIG,\n url: u,\n data: body,\n method: 'POST',\n });\n const tokenResponse = res.data;\n this.credentials.access_token = tokenResponse.accessToken;\n this.credentials.expiry_date = Date.parse(tokenResponse.expireTime);\n return {\n tokens: this.credentials,\n res,\n };\n }\n catch (error) {\n if (!(error instanceof Error))\n throw error;\n let status = 0;\n let message = '';\n if (error instanceof gaxios_1.GaxiosError) {\n status = error?.response?.data?.error?.status;\n message = error?.response?.data?.error?.message;\n }\n if (status && message) {\n error.message = `${status}: unable to impersonate: ${message}`;\n throw error;\n }\n else {\n error.message = `unable to impersonate: ${error}`;\n throw error;\n }\n }\n }\n /**\n * Generates an OpenID Connect ID token for a service account.\n *\n * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateIdToken Reference Documentation}\n *\n * @param targetAudience the audience for the fetched ID token.\n * @param options the for the request\n * @return an OpenID Connect ID token\n */\n async fetchIdToken(targetAudience, options) {\n await this.sourceClient.getAccessToken();\n const name = `projects/-/serviceAccounts/${this.targetPrincipal}`;\n const u = `${this.endpoint}/v1/${name}:generateIdToken`;\n const body = {\n delegates: this.delegates,\n audience: targetAudience,\n includeEmail: options?.includeEmail ?? true,\n useEmailAzp: options?.includeEmail ?? true,\n };\n const res = await this.sourceClient.request({\n ...Impersonated.RETRY_CONFIG,\n url: u,\n data: body,\n method: 'POST',\n });\n return res.data.token;\n }\n}\nexports.Impersonated = Impersonated;\n//# sourceMappingURL=impersonated.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.OAuthClientAuthHandler = void 0;\nexports.getErrorFromOAuthErrorResponse = getErrorFromOAuthErrorResponse;\nconst gaxios_1 = require(\"gaxios\");\nconst crypto_1 = require(\"../crypto/crypto\");\n/** List of HTTP methods that accept request bodies. */\nconst METHODS_SUPPORTING_REQUEST_BODY = ['PUT', 'POST', 'PATCH'];\n/**\n * Abstract class for handling client authentication in OAuth-based\n * operations.\n * When request-body client authentication is used, only application/json and\n * application/x-www-form-urlencoded content types for HTTP methods that support\n * request bodies are supported.\n */\nclass OAuthClientAuthHandler {\n #crypto = (0, crypto_1.createCrypto)();\n #clientAuthentication;\n transporter;\n /**\n * Instantiates an OAuth client authentication handler.\n * @param options The OAuth Client Auth Handler instance options. Passing an `ClientAuthentication` directly is **@DEPRECATED**.\n */\n constructor(options) {\n if (options && 'clientId' in options) {\n this.#clientAuthentication = options;\n this.transporter = new gaxios_1.Gaxios();\n }\n else {\n this.#clientAuthentication = options?.clientAuthentication;\n this.transporter = options?.transporter || new gaxios_1.Gaxios();\n }\n }\n /**\n * Applies client authentication on the OAuth request's headers or POST\n * body but does not process the request.\n * @param opts The GaxiosOptions whose headers or data are to be modified\n * depending on the client authentication mechanism to be used.\n * @param bearerToken The optional bearer token to use for authentication.\n * When this is used, no client authentication credentials are needed.\n */\n applyClientAuthenticationOptions(opts, bearerToken) {\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);\n // Inject authenticated header.\n this.injectAuthenticatedHeaders(opts, bearerToken);\n // Inject authenticated request body.\n if (!bearerToken) {\n this.injectAuthenticatedRequestBody(opts);\n }\n }\n /**\n * Applies client authentication on the request's header if either\n * basic authentication or bearer token authentication is selected.\n *\n * @param opts The GaxiosOptions whose headers or data are to be modified\n * depending on the client authentication mechanism to be used.\n * @param bearerToken The optional bearer token to use for authentication.\n * When this is used, no client authentication credentials are needed.\n */\n injectAuthenticatedHeaders(opts, bearerToken) {\n // Bearer token prioritized higher than basic Auth.\n if (bearerToken) {\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers, {\n authorization: `Bearer ${bearerToken}`,\n });\n }\n else if (this.#clientAuthentication?.confidentialClientType === 'basic') {\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);\n const clientId = this.#clientAuthentication.clientId;\n const clientSecret = this.#clientAuthentication.clientSecret || '';\n const base64EncodedCreds = this.#crypto.encodeBase64StringUtf8(`${clientId}:${clientSecret}`);\n gaxios_1.Gaxios.mergeHeaders(opts.headers, {\n authorization: `Basic ${base64EncodedCreds}`,\n });\n }\n }\n /**\n * Applies client authentication on the request's body if request-body\n * client authentication is selected.\n *\n * @param opts The GaxiosOptions whose headers or data are to be modified\n * depending on the client authentication mechanism to be used.\n */\n injectAuthenticatedRequestBody(opts) {\n if (this.#clientAuthentication?.confidentialClientType === 'request-body') {\n const method = (opts.method || 'GET').toUpperCase();\n if (!METHODS_SUPPORTING_REQUEST_BODY.includes(method)) {\n throw new Error(`${method} HTTP method does not support ` +\n `${this.#clientAuthentication.confidentialClientType} ` +\n 'client authentication');\n }\n // Get content-type\n const headers = new Headers(opts.headers);\n const contentType = headers.get('content-type');\n // Inject authenticated request body\n if (contentType?.startsWith('application/x-www-form-urlencoded') ||\n opts.data instanceof URLSearchParams) {\n const data = new URLSearchParams(opts.data ?? '');\n data.append('client_id', this.#clientAuthentication.clientId);\n data.append('client_secret', this.#clientAuthentication.clientSecret || '');\n opts.data = data;\n }\n else if (contentType?.startsWith('application/json')) {\n opts.data = opts.data || {};\n Object.assign(opts.data, {\n client_id: this.#clientAuthentication.clientId,\n client_secret: this.#clientAuthentication.clientSecret || '',\n });\n }\n else {\n throw new Error(`${contentType} content-types are not supported with ` +\n `${this.#clientAuthentication.confidentialClientType} ` +\n 'client authentication');\n }\n }\n }\n /**\n * Retry config for Auth-related requests.\n *\n * @remarks\n *\n * This is not a part of the default {@link AuthClient.transporter transporter/gaxios}\n * config as some downstream APIs would prefer if customers explicitly enable retries,\n * such as GCS.\n */\n static get RETRY_CONFIG() {\n return {\n retry: true,\n retryConfig: {\n httpMethodsToRetry: ['GET', 'PUT', 'POST', 'HEAD', 'OPTIONS', 'DELETE'],\n },\n };\n }\n}\nexports.OAuthClientAuthHandler = OAuthClientAuthHandler;\n/**\n * Converts an OAuth error response to a native JavaScript Error.\n * @param resp The OAuth error response to convert to a native Error object.\n * @param err The optional original error. If provided, the error properties\n * will be copied to the new error.\n * @return The converted native Error object.\n */\nfunction getErrorFromOAuthErrorResponse(resp, err) {\n // Error response.\n const errorCode = resp.error;\n const errorDescription = resp.error_description;\n const errorUri = resp.error_uri;\n let message = `Error code ${errorCode}`;\n if (typeof errorDescription !== 'undefined') {\n message += `: ${errorDescription}`;\n }\n if (typeof errorUri !== 'undefined') {\n message += ` - ${errorUri}`;\n }\n const newError = new Error(message);\n // Copy properties from original error to newly generated error.\n if (err) {\n const keys = Object.keys(err);\n if (err.stack) {\n // Copy error.stack if available.\n keys.push('stack');\n }\n keys.forEach(key => {\n // Do not overwrite the message field.\n if (key !== 'message') {\n Object.defineProperty(newError, key, {\n value: err[key],\n writable: false,\n enumerable: true,\n });\n }\n });\n }\n return newError;\n}\n//# sourceMappingURL=oauth2common.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.StsCredentials = void 0;\nconst gaxios_1 = require(\"gaxios\");\nconst authclient_1 = require(\"./authclient\");\nconst oauth2common_1 = require(\"./oauth2common\");\nconst util_1 = require(\"../util\");\n/**\n * Implements the OAuth 2.0 token exchange based on\n * https://tools.ietf.org/html/rfc8693\n */\nclass StsCredentials extends oauth2common_1.OAuthClientAuthHandler {\n #tokenExchangeEndpoint;\n /**\n * Initializes an STS credentials instance.\n *\n * @param options The STS credentials instance options. Passing an `tokenExchangeEndpoint` directly is **@DEPRECATED**.\n * @param clientAuthentication **@DEPRECATED**. Provide a {@link StsCredentialsConstructionOptions `StsCredentialsConstructionOptions`} object in the first parameter instead.\n */\n constructor(options = {\n tokenExchangeEndpoint: '',\n }, \n /**\n * @deprecated - provide a {@link StsCredentialsConstructionOptions `StsCredentialsConstructionOptions`} object in the first parameter instead\n */\n clientAuthentication) {\n if (typeof options !== 'object' || options instanceof URL) {\n options = {\n tokenExchangeEndpoint: options,\n clientAuthentication,\n };\n }\n super(options);\n this.#tokenExchangeEndpoint = options.tokenExchangeEndpoint;\n }\n /**\n * Exchanges the provided token for another type of token based on the\n * rfc8693 spec.\n * @param stsCredentialsOptions The token exchange options used to populate\n * the token exchange request.\n * @param additionalHeaders Optional additional headers to pass along the\n * request.\n * @param options Optional additional GCP-specific non-spec defined options\n * to send with the request.\n * Example: `&options=${encodeUriComponent(JSON.stringified(options))}`\n * @return A promise that resolves with the token exchange response containing\n * the requested token and its expiration time.\n */\n async exchangeToken(stsCredentialsOptions, headers, options) {\n const values = {\n grant_type: stsCredentialsOptions.grantType,\n resource: stsCredentialsOptions.resource,\n audience: stsCredentialsOptions.audience,\n scope: stsCredentialsOptions.scope?.join(' '),\n requested_token_type: stsCredentialsOptions.requestedTokenType,\n subject_token: stsCredentialsOptions.subjectToken,\n subject_token_type: stsCredentialsOptions.subjectTokenType,\n actor_token: stsCredentialsOptions.actingParty?.actorToken,\n actor_token_type: stsCredentialsOptions.actingParty?.actorTokenType,\n // Non-standard GCP-specific options.\n options: options && JSON.stringify(options),\n };\n const opts = {\n ...StsCredentials.RETRY_CONFIG,\n url: this.#tokenExchangeEndpoint.toString(),\n method: 'POST',\n headers,\n data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(values)),\n };\n authclient_1.AuthClient.setMethodName(opts, 'exchangeToken');\n // Apply OAuth client authentication.\n this.applyClientAuthenticationOptions(opts);\n try {\n const response = await this.transporter.request(opts);\n // Successful response.\n const stsSuccessfulResponse = response.data;\n stsSuccessfulResponse.res = response;\n return stsSuccessfulResponse;\n }\n catch (error) {\n // Translate error to OAuthError.\n if (error instanceof gaxios_1.GaxiosError && error.response) {\n throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, \n // Preserve other fields from the original error.\n error);\n }\n // Request could fail before the server responds.\n throw error;\n }\n }\n}\nexports.StsCredentials = StsCredentials;\n//# sourceMappingURL=stscredentials.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BaseExternalAccountClient = exports.CLOUD_RESOURCE_MANAGER = exports.EXTERNAL_ACCOUNT_TYPE = exports.EXPIRATION_TIME_OFFSET = void 0;\nconst gaxios_1 = require(\"gaxios\");\nconst stream = require(\"stream\");\nconst authclient_1 = require(\"./authclient\");\nconst sts = require(\"./stscredentials\");\nconst util_1 = require(\"../util\");\nconst shared_cjs_1 = require(\"../shared.cjs\");\n/**\n * The required token exchange grant_type: rfc8693#section-2.1\n */\nconst STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange';\n/**\n * The requested token exchange requested_token_type: rfc8693#section-2.1\n */\nconst STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';\n/** The default OAuth scope to request when none is provided. */\nconst DEFAULT_OAUTH_SCOPE = 'https://www.googleapis.com/auth/cloud-platform';\n/** Default impersonated token lifespan in seconds.*/\nconst DEFAULT_TOKEN_LIFESPAN = 3600;\n/**\n * Offset to take into account network delays and server clock skews.\n */\nexports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000;\n/**\n * The credentials JSON file type for external account clients.\n * There are 3 types of JSON configs:\n * 1. authorized_user => Google end user credential\n * 2. service_account => Google service account credential\n * 3. external_Account => non-GCP service (eg. AWS, Azure, K8s)\n */\nexports.EXTERNAL_ACCOUNT_TYPE = 'external_account';\n/**\n * Cloud resource manager URL used to retrieve project information.\n *\n * @deprecated use {@link BaseExternalAccountClient.cloudResourceManagerURL} instead\n **/\nexports.CLOUD_RESOURCE_MANAGER = 'https://cloudresourcemanager.googleapis.com/v1/projects/';\n/** The workforce audience pattern. */\nconst WORKFORCE_AUDIENCE_PATTERN = '//iam\\\\.googleapis\\\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+';\nconst DEFAULT_TOKEN_URL = 'https://sts.{universeDomain}/v1/token';\n/**\n * Base external account client. This is used to instantiate AuthClients for\n * exchanging external account credentials for GCP access token and authorizing\n * requests to GCP APIs.\n * The base class implements common logic for exchanging various type of\n * external credentials for GCP access token. The logic of determining and\n * retrieving the external credential based on the environment and\n * credential_source will be left for the subclasses.\n */\nclass BaseExternalAccountClient extends authclient_1.AuthClient {\n /**\n * OAuth scopes for the GCP access token to use. When not provided,\n * the default https://www.googleapis.com/auth/cloud-platform is\n * used.\n */\n scopes;\n projectNumber;\n audience;\n subjectTokenType;\n stsCredential;\n clientAuth;\n credentialSourceType;\n cachedAccessToken;\n serviceAccountImpersonationUrl;\n serviceAccountImpersonationLifetime;\n workforcePoolUserProject;\n configLifetimeRequested;\n tokenUrl;\n /**\n * @example\n * ```ts\n * new URL('https://cloudresourcemanager.googleapis.com/v1/projects/');\n * ```\n */\n cloudResourceManagerURL;\n supplierContext;\n /**\n * A pending access token request. Used for concurrent calls.\n */\n #pendingAccessToken = null;\n /**\n * Instantiate a BaseExternalAccountClient instance using the provided JSON\n * object loaded from an external account credentials file.\n * @param options The external account options object typically loaded\n * from the external account JSON credential file. The camelCased options\n * are aliases for the snake_cased options.\n */\n constructor(options) {\n super(options);\n const opts = (0, util_1.originalOrCamelOptions)(options);\n const type = opts.get('type');\n if (type && type !== exports.EXTERNAL_ACCOUNT_TYPE) {\n throw new Error(`Expected \"${exports.EXTERNAL_ACCOUNT_TYPE}\" type but ` +\n `received \"${options.type}\"`);\n }\n const clientId = opts.get('client_id');\n const clientSecret = opts.get('client_secret');\n this.tokenUrl =\n opts.get('token_url') ??\n DEFAULT_TOKEN_URL.replace('{universeDomain}', this.universeDomain);\n const subjectTokenType = opts.get('subject_token_type');\n const workforcePoolUserProject = opts.get('workforce_pool_user_project');\n const serviceAccountImpersonationUrl = opts.get('service_account_impersonation_url');\n const serviceAccountImpersonation = opts.get('service_account_impersonation');\n const serviceAccountImpersonationLifetime = (0, util_1.originalOrCamelOptions)(serviceAccountImpersonation).get('token_lifetime_seconds');\n this.cloudResourceManagerURL = new URL(opts.get('cloud_resource_manager_url') ||\n `https://cloudresourcemanager.${this.universeDomain}/v1/projects/`);\n if (clientId) {\n this.clientAuth = {\n confidentialClientType: 'basic',\n clientId,\n clientSecret,\n };\n }\n this.stsCredential = new sts.StsCredentials({\n tokenExchangeEndpoint: this.tokenUrl,\n clientAuthentication: this.clientAuth,\n });\n this.scopes = opts.get('scopes') || [DEFAULT_OAUTH_SCOPE];\n this.cachedAccessToken = null;\n this.audience = opts.get('audience');\n this.subjectTokenType = subjectTokenType;\n this.workforcePoolUserProject = workforcePoolUserProject;\n const workforceAudiencePattern = new RegExp(WORKFORCE_AUDIENCE_PATTERN);\n if (this.workforcePoolUserProject &&\n !this.audience.match(workforceAudiencePattern)) {\n throw new Error('workforcePoolUserProject should not be set for non-workforce pool ' +\n 'credentials.');\n }\n this.serviceAccountImpersonationUrl = serviceAccountImpersonationUrl;\n this.serviceAccountImpersonationLifetime =\n serviceAccountImpersonationLifetime;\n if (this.serviceAccountImpersonationLifetime) {\n this.configLifetimeRequested = true;\n }\n else {\n this.configLifetimeRequested = false;\n this.serviceAccountImpersonationLifetime = DEFAULT_TOKEN_LIFESPAN;\n }\n this.projectNumber = this.getProjectNumber(this.audience);\n this.supplierContext = {\n audience: this.audience,\n subjectTokenType: this.subjectTokenType,\n transporter: this.transporter,\n };\n }\n /** The service account email to be impersonated, if available. */\n getServiceAccountEmail() {\n if (this.serviceAccountImpersonationUrl) {\n if (this.serviceAccountImpersonationUrl.length > 256) {\n /**\n * Prevents DOS attacks.\n * @see {@link https://github.com/googleapis/google-auth-library-nodejs/security/code-scanning/84}\n **/\n throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);\n }\n // Parse email from URL. The formal looks as follows:\n // https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/name@project-id.iam.gserviceaccount.com:generateAccessToken\n const re = /serviceAccounts\\/(?[^:]+):generateAccessToken$/;\n const result = re.exec(this.serviceAccountImpersonationUrl);\n return result?.groups?.email || null;\n }\n return null;\n }\n /**\n * Provides a mechanism to inject GCP access tokens directly.\n * When the provided credential expires, a new credential, using the\n * external account options, is retrieved.\n * @param credentials The Credentials object to set on the current client.\n */\n setCredentials(credentials) {\n super.setCredentials(credentials);\n this.cachedAccessToken = credentials;\n }\n /**\n * @return A promise that resolves with the current GCP access token\n * response. If the current credential is expired, a new one is retrieved.\n */\n async getAccessToken() {\n // If cached access token is unavailable or expired, force refresh.\n if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) {\n await this.refreshAccessTokenAsync();\n }\n // Return GCP access token in GetAccessTokenResponse format.\n return {\n token: this.cachedAccessToken.access_token,\n res: this.cachedAccessToken.res,\n };\n }\n /**\n * The main authentication interface. It takes an optional url which when\n * present is the endpoint being accessed, and returns a Promise which\n * resolves with authorization header fields.\n *\n * The result has the form:\n * { authorization: 'Bearer ' }\n */\n async getRequestHeaders() {\n const accessTokenResponse = await this.getAccessToken();\n const headers = new Headers({\n authorization: `Bearer ${accessTokenResponse.token}`,\n });\n return this.addSharedMetadataHeaders(headers);\n }\n request(opts, callback) {\n if (callback) {\n this.requestAsync(opts).then(r => callback(null, r), e => {\n return callback(e, e.response);\n });\n }\n else {\n return this.requestAsync(opts);\n }\n }\n /**\n * @return A promise that resolves with the project ID corresponding to the\n * current workload identity pool or current workforce pool if\n * determinable. For workforce pool credential, it returns the project ID\n * corresponding to the workforcePoolUserProject.\n * This is introduced to match the current pattern of using the Auth\n * library:\n * const projectId = await auth.getProjectId();\n * const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;\n * const res = await client.request({ url });\n * The resource may not have permission\n * (resourcemanager.projects.get) to call this API or the required\n * scopes may not be selected:\n * https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes\n */\n async getProjectId() {\n const projectNumber = this.projectNumber || this.workforcePoolUserProject;\n if (this.projectId) {\n // Return previously determined project ID.\n return this.projectId;\n }\n else if (projectNumber) {\n // Preferable not to use request() to avoid retrial policies.\n const headers = await this.getRequestHeaders();\n const opts = {\n ...BaseExternalAccountClient.RETRY_CONFIG,\n headers,\n url: `${this.cloudResourceManagerURL.toString()}${projectNumber}`,\n };\n authclient_1.AuthClient.setMethodName(opts, 'getProjectId');\n const response = await this.transporter.request(opts);\n this.projectId = response.data.projectId;\n return this.projectId;\n }\n return null;\n }\n /**\n * Authenticates the provided HTTP request, processes it and resolves with the\n * returned response.\n * @param opts The HTTP request options.\n * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure.\n * @return A promise that resolves with the successful response.\n */\n async requestAsync(opts, reAuthRetried = false) {\n let response;\n try {\n const requestHeaders = await this.getRequestHeaders();\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);\n this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders);\n response = await this.transporter.request(opts);\n }\n catch (e) {\n const res = e.response;\n if (res) {\n const statusCode = res.status;\n // Retry the request for metadata if the following criteria are true:\n // - We haven't already retried. It only makes sense to retry once.\n // - The response was a 401 or a 403\n // - The request didn't send a readableStream\n // - forceRefreshOnFailure is true\n const isReadableStream = res.config.data instanceof stream.Readable;\n const isAuthErr = statusCode === 401 || statusCode === 403;\n if (!reAuthRetried &&\n isAuthErr &&\n !isReadableStream &&\n this.forceRefreshOnFailure) {\n await this.refreshAccessTokenAsync();\n return await this.requestAsync(opts, true);\n }\n }\n throw e;\n }\n return response;\n }\n /**\n * Forces token refresh, even if unexpired tokens are currently cached.\n * External credentials are exchanged for GCP access tokens via the token\n * exchange endpoint and other settings provided in the client options\n * object.\n * If the service_account_impersonation_url is provided, an additional\n * step to exchange the external account GCP access token for a service\n * account impersonated token is performed.\n * @return A promise that resolves with the fresh GCP access tokens.\n */\n async refreshAccessTokenAsync() {\n // Use an existing access token request, or cache a new one\n this.#pendingAccessToken =\n this.#pendingAccessToken || this.#internalRefreshAccessTokenAsync();\n try {\n return await this.#pendingAccessToken;\n }\n finally {\n // clear pending access token for future requests\n this.#pendingAccessToken = null;\n }\n }\n async #internalRefreshAccessTokenAsync() {\n // Retrieve the external credential.\n const subjectToken = await this.retrieveSubjectToken();\n // Construct the STS credentials options.\n const stsCredentialsOptions = {\n grantType: STS_GRANT_TYPE,\n audience: this.audience,\n requestedTokenType: STS_REQUEST_TOKEN_TYPE,\n subjectToken,\n subjectTokenType: this.subjectTokenType,\n // generateAccessToken requires the provided access token to have\n // scopes:\n // https://www.googleapis.com/auth/iam or\n // https://www.googleapis.com/auth/cloud-platform\n // The new service account access token scopes will match the user\n // provided ones.\n scope: this.serviceAccountImpersonationUrl\n ? [DEFAULT_OAUTH_SCOPE]\n : this.getScopesArray(),\n };\n // Exchange the external credentials for a GCP access token.\n // Client auth is prioritized over passing the workforcePoolUserProject\n // parameter for STS token exchange.\n const additionalOptions = !this.clientAuth && this.workforcePoolUserProject\n ? { userProject: this.workforcePoolUserProject }\n : undefined;\n const additionalHeaders = new Headers({\n 'x-goog-api-client': this.getMetricsHeaderValue(),\n });\n const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, additionalHeaders, additionalOptions);\n if (this.serviceAccountImpersonationUrl) {\n this.cachedAccessToken = await this.getImpersonatedAccessToken(stsResponse.access_token);\n }\n else if (stsResponse.expires_in) {\n // Save response in cached access token.\n this.cachedAccessToken = {\n access_token: stsResponse.access_token,\n expiry_date: new Date().getTime() + stsResponse.expires_in * 1000,\n res: stsResponse.res,\n };\n }\n else {\n // Save response in cached access token.\n this.cachedAccessToken = {\n access_token: stsResponse.access_token,\n res: stsResponse.res,\n };\n }\n // Save credentials.\n this.credentials = {};\n Object.assign(this.credentials, this.cachedAccessToken);\n delete this.credentials.res;\n // Trigger tokens event to notify external listeners.\n this.emit('tokens', {\n refresh_token: null,\n expiry_date: this.cachedAccessToken.expiry_date,\n access_token: this.cachedAccessToken.access_token,\n token_type: 'Bearer',\n id_token: null,\n });\n // Return the cached access token.\n return this.cachedAccessToken;\n }\n /**\n * Returns the workload identity pool project number if it is determinable\n * from the audience resource name.\n * @param audience The STS audience used to determine the project number.\n * @return The project number associated with the workload identity pool, if\n * this can be determined from the STS audience field. Otherwise, null is\n * returned.\n */\n getProjectNumber(audience) {\n // STS audience pattern:\n // //iam.googleapis.com/projects/$PROJECT_NUMBER/locations/...\n const match = audience.match(/\\/projects\\/([^/]+)/);\n if (!match) {\n return null;\n }\n return match[1];\n }\n /**\n * Exchanges an external account GCP access token for a service\n * account impersonated access token using iamcredentials\n * GenerateAccessToken API.\n * @param token The access token to exchange for a service account access\n * token.\n * @return A promise that resolves with the service account impersonated\n * credentials response.\n */\n async getImpersonatedAccessToken(token) {\n const opts = {\n ...BaseExternalAccountClient.RETRY_CONFIG,\n url: this.serviceAccountImpersonationUrl,\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${token}`,\n },\n data: {\n scope: this.getScopesArray(),\n lifetime: this.serviceAccountImpersonationLifetime + 's',\n },\n };\n authclient_1.AuthClient.setMethodName(opts, 'getImpersonatedAccessToken');\n const response = await this.transporter.request(opts);\n const successResponse = response.data;\n return {\n access_token: successResponse.accessToken,\n // Convert from ISO format to timestamp.\n expiry_date: new Date(successResponse.expireTime).getTime(),\n res: response,\n };\n }\n /**\n * Returns whether the provided credentials are expired or not.\n * If there is no expiry time, assumes the token is not expired or expiring.\n * @param accessToken The credentials to check for expiration.\n * @return Whether the credentials are expired or not.\n */\n isExpired(accessToken) {\n const now = new Date().getTime();\n return accessToken.expiry_date\n ? now >= accessToken.expiry_date - this.eagerRefreshThresholdMillis\n : false;\n }\n /**\n * @return The list of scopes for the requested GCP access token.\n */\n getScopesArray() {\n // Since scopes can be provided as string or array, the type should\n // be normalized.\n if (typeof this.scopes === 'string') {\n return [this.scopes];\n }\n return this.scopes || [DEFAULT_OAUTH_SCOPE];\n }\n getMetricsHeaderValue() {\n const nodeVersion = process.version.replace(/^v/, '');\n const saImpersonation = this.serviceAccountImpersonationUrl !== undefined;\n const credentialSourceType = this.credentialSourceType\n ? this.credentialSourceType\n : 'unknown';\n return `gl-node/${nodeVersion} auth/${shared_cjs_1.pkg.version} google-byoid-sdk source/${credentialSourceType} sa-impersonation/${saImpersonation} config-lifetime/${this.configLifetimeRequested}`;\n }\n getTokenUrl() {\n return this.tokenUrl;\n }\n}\nexports.BaseExternalAccountClient = BaseExternalAccountClient;\n//# sourceMappingURL=baseexternalclient.js.map", "\"use strict\";\n// Copyright 2024 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.FileSubjectTokenSupplier = void 0;\nconst util_1 = require(\"util\");\nconst fs = require(\"fs\");\n// fs.readfile is undefined in browser karma tests causing\n// `npm run browser-test` to fail as test.oauth2.ts imports this file via\n// src/index.ts.\n// Fallback to void function to avoid promisify throwing a TypeError.\nconst readFile = (0, util_1.promisify)(fs.readFile ?? (() => { }));\nconst realpath = (0, util_1.promisify)(fs.realpath ?? (() => { }));\nconst lstat = (0, util_1.promisify)(fs.lstat ?? (() => { }));\n/**\n * Internal subject token supplier implementation used when a file location\n * is configured in the credential configuration used to build an {@link IdentityPoolClient}\n */\nclass FileSubjectTokenSupplier {\n filePath;\n formatType;\n subjectTokenFieldName;\n /**\n * Instantiates a new file based subject token supplier.\n * @param opts The file subject token supplier options to build the supplier\n * with.\n */\n constructor(opts) {\n this.filePath = opts.filePath;\n this.formatType = opts.formatType;\n this.subjectTokenFieldName = opts.subjectTokenFieldName;\n }\n /**\n * Returns the subject token stored at the file specified in the constructor.\n * @param context {@link ExternalAccountSupplierContext} from the calling\n * {@link IdentityPoolClient}, contains the requested audience and subject\n * token type for the external account identity. Not used.\n */\n async getSubjectToken() {\n // Make sure there is a file at the path. lstatSync will throw if there is\n // nothing there.\n let parsedFilePath = this.filePath;\n try {\n // Resolve path to actual file in case of symlink. Expect a thrown error\n // if not resolvable.\n parsedFilePath = await realpath(parsedFilePath);\n if (!(await lstat(parsedFilePath)).isFile()) {\n throw new Error();\n }\n }\n catch (err) {\n if (err instanceof Error) {\n err.message = `The file at ${parsedFilePath} does not exist, or it is not a file. ${err.message}`;\n }\n throw err;\n }\n let subjectToken;\n const rawText = await readFile(parsedFilePath, { encoding: 'utf8' });\n if (this.formatType === 'text') {\n subjectToken = rawText;\n }\n else if (this.formatType === 'json' && this.subjectTokenFieldName) {\n const json = JSON.parse(rawText);\n subjectToken = json[this.subjectTokenFieldName];\n }\n if (!subjectToken) {\n throw new Error('Unable to parse the subject_token from the credential_source file');\n }\n return subjectToken;\n }\n}\nexports.FileSubjectTokenSupplier = FileSubjectTokenSupplier;\n//# sourceMappingURL=filesubjecttokensupplier.js.map", "\"use strict\";\n// Copyright 2024 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.UrlSubjectTokenSupplier = void 0;\nconst authclient_1 = require(\"./authclient\");\n/**\n * Internal subject token supplier implementation used when a URL\n * is configured in the credential configuration used to build an {@link IdentityPoolClient}\n */\nclass UrlSubjectTokenSupplier {\n url;\n headers;\n formatType;\n subjectTokenFieldName;\n additionalGaxiosOptions;\n /**\n * Instantiates a URL subject token supplier.\n * @param opts The URL subject token supplier options to build the supplier with.\n */\n constructor(opts) {\n this.url = opts.url;\n this.formatType = opts.formatType;\n this.subjectTokenFieldName = opts.subjectTokenFieldName;\n this.headers = opts.headers;\n this.additionalGaxiosOptions = opts.additionalGaxiosOptions;\n }\n /**\n * Sends a GET request to the URL provided in the constructor and resolves\n * with the returned external subject token.\n * @param context {@link ExternalAccountSupplierContext} from the calling\n * {@link IdentityPoolClient}, contains the requested audience and subject\n * token type for the external account identity. Not used.\n */\n async getSubjectToken(context) {\n const opts = {\n ...this.additionalGaxiosOptions,\n url: this.url,\n method: 'GET',\n headers: this.headers,\n };\n authclient_1.AuthClient.setMethodName(opts, 'getSubjectToken');\n let subjectToken;\n if (this.formatType === 'text') {\n const response = await context.transporter.request(opts);\n subjectToken = response.data;\n }\n else if (this.formatType === 'json' && this.subjectTokenFieldName) {\n const response = await context.transporter.request(opts);\n subjectToken = response.data[this.subjectTokenFieldName];\n }\n if (!subjectToken) {\n throw new Error('Unable to parse the subject_token from the credential_source URL');\n }\n return subjectToken;\n }\n}\nexports.UrlSubjectTokenSupplier = UrlSubjectTokenSupplier;\n//# sourceMappingURL=urlsubjecttokensupplier.js.map", "\"use strict\";\n// Copyright 2025 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CertificateSubjectTokenSupplier = exports.InvalidConfigurationError = exports.CertificateSourceUnavailableError = exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = void 0;\nconst util_1 = require(\"../util\");\nconst fs = require(\"fs\");\nconst crypto_1 = require(\"crypto\");\nconst https = require(\"https\");\nexports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = 'GOOGLE_API_CERTIFICATE_CONFIG';\n/**\n * Thrown when the certificate source cannot be located or accessed.\n */\nclass CertificateSourceUnavailableError extends Error {\n constructor(message) {\n super(message);\n this.name = 'CertificateSourceUnavailableError';\n }\n}\nexports.CertificateSourceUnavailableError = CertificateSourceUnavailableError;\n/**\n * Thrown for invalid configuration that is not related to file availability.\n */\nclass InvalidConfigurationError extends Error {\n constructor(message) {\n super(message);\n this.name = 'InvalidConfigurationError';\n }\n}\nexports.InvalidConfigurationError = InvalidConfigurationError;\n/**\n * A subject token supplier that uses a client certificate for authentication.\n * It provides the certificate chain as the subject token for identity federation.\n */\nclass CertificateSubjectTokenSupplier {\n certificateConfigPath;\n trustChainPath;\n cert;\n key;\n /**\n * Initializes a new instance of the CertificateSubjectTokenSupplier.\n * @param opts The configuration options for the supplier.\n */\n constructor(opts) {\n if (!opts.useDefaultCertificateConfig && !opts.certificateConfigLocation) {\n throw new InvalidConfigurationError('Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.');\n }\n if (opts.useDefaultCertificateConfig && opts.certificateConfigLocation) {\n throw new InvalidConfigurationError('Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.');\n }\n this.trustChainPath = opts.trustChainPath;\n this.certificateConfigPath = opts.certificateConfigLocation ?? '';\n }\n /**\n * Creates an HTTPS agent configured with the client certificate and private key for mTLS.\n * @returns An mTLS-configured https.Agent.\n */\n async createMtlsHttpsAgent() {\n if (!this.key || !this.cert) {\n throw new InvalidConfigurationError('Cannot create mTLS Agent with missing certificate or key');\n }\n return new https.Agent({ key: this.key, cert: this.cert });\n }\n /**\n * Constructs the subject token, which is the base64-encoded certificate chain.\n * @returns A promise that resolves with the subject token.\n */\n async getSubjectToken() {\n // The \"subject token\" in this context is the processed certificate chain.\n this.certificateConfigPath = await this.#resolveCertificateConfigFilePath();\n const { certPath, keyPath } = await this.#getCertAndKeyPaths();\n ({ cert: this.cert, key: this.key } = await this.#getKeyAndCert(certPath, keyPath));\n return await this.#processChainFromPaths(this.cert);\n }\n /**\n * Resolves the absolute path to the certificate configuration file\n * by checking the \"certificate_config_location\" provided in the ADC file,\n * or the \"GOOGLE_API_CERTIFICATE_CONFIG\" environment variable\n * or in the default gcloud path.\n * @param overridePath An optional path to check first.\n * @returns The resolved file path.\n */\n async #resolveCertificateConfigFilePath() {\n // 1. Check for the override path from constructor options.\n const overridePath = this.certificateConfigPath;\n if (overridePath) {\n if (await (0, util_1.isValidFile)(overridePath)) {\n return overridePath;\n }\n throw new CertificateSourceUnavailableError(`Provided certificate config path is invalid: ${overridePath}`);\n }\n // 2. Check the standard environment variable.\n const envPath = process.env[exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];\n if (envPath) {\n if (await (0, util_1.isValidFile)(envPath)) {\n return envPath;\n }\n throw new CertificateSourceUnavailableError(`Path from environment variable \"${exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}\" is invalid: ${envPath}`);\n }\n // 3. Check the well-known gcloud config location.\n const wellKnownPath = (0, util_1.getWellKnownCertificateConfigFileLocation)();\n if (await (0, util_1.isValidFile)(wellKnownPath)) {\n return wellKnownPath;\n }\n // 4. If none are found, throw an error.\n throw new CertificateSourceUnavailableError('Could not find certificate configuration file. Searched override path, ' +\n `the \"${exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}\" env var, and the gcloud path (${wellKnownPath}).`);\n }\n /**\n * Reads and parses the certificate config JSON file to extract the certificate and key paths.\n * @returns An object containing the certificate and key paths.\n */\n async #getCertAndKeyPaths() {\n const configPath = this.certificateConfigPath;\n let fileContents;\n try {\n fileContents = await fs.promises.readFile(configPath, 'utf8');\n }\n catch (err) {\n throw new CertificateSourceUnavailableError(`Failed to read certificate config file at: ${configPath}`);\n }\n try {\n const config = JSON.parse(fileContents);\n const certPath = config?.cert_configs?.workload?.cert_path;\n const keyPath = config?.cert_configs?.workload?.key_path;\n if (!certPath || !keyPath) {\n throw new InvalidConfigurationError(`Certificate config file (${configPath}) is missing required \"cert_path\" or \"key_path\" in the workload config.`);\n }\n return { certPath, keyPath };\n }\n catch (e) {\n if (e instanceof InvalidConfigurationError)\n throw e;\n throw new InvalidConfigurationError(`Failed to parse certificate config from ${configPath}: ${e.message}`);\n }\n }\n /**\n * Reads and parses the cert and key files get their content and check valid format.\n * @returns An object containing the cert content and key content in buffer format.\n */\n async #getKeyAndCert(certPath, keyPath) {\n let cert, key;\n try {\n cert = await fs.promises.readFile(certPath);\n new crypto_1.X509Certificate(cert);\n }\n catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new CertificateSourceUnavailableError(`Failed to read certificate file at ${certPath}: ${message}`);\n }\n try {\n key = await fs.promises.readFile(keyPath);\n (0, crypto_1.createPrivateKey)(key);\n }\n catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new CertificateSourceUnavailableError(`Failed to read private key file at ${keyPath}: ${message}`);\n }\n return { cert, key };\n }\n /**\n * Reads the leaf certificate and trust chain, combines them,\n * and returns a JSON array of base64-encoded certificates.\n * @returns A stringified JSON array of the certificate chain.\n */\n async #processChainFromPaths(leafCertBuffer) {\n const leafCert = new crypto_1.X509Certificate(leafCertBuffer);\n // If no trust chain is provided, just use the successfully parsed leaf certificate.\n if (!this.trustChainPath) {\n return JSON.stringify([leafCert.raw.toString('base64')]);\n }\n // Handle the trust chain logic.\n try {\n const chainPems = await fs.promises.readFile(this.trustChainPath, 'utf8');\n const pemBlocks = chainPems.match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g) ?? [];\n const chainCerts = pemBlocks.map((pem, index) => {\n try {\n return new crypto_1.X509Certificate(pem);\n }\n catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n // Throw a more precise error if a single certificate in the chain is invalid.\n throw new InvalidConfigurationError(`Failed to parse certificate at index ${index} in trust chain file ${this.trustChainPath}: ${message}`);\n }\n });\n const leafIndex = chainCerts.findIndex(chainCert => leafCert.raw.equals(chainCert.raw));\n let finalChain;\n if (leafIndex === -1) {\n // Leaf not found, so prepend it to the chain.\n finalChain = [leafCert, ...chainCerts];\n }\n else if (leafIndex === 0) {\n // Leaf is already the first element, so the chain is correctly ordered.\n finalChain = chainCerts;\n }\n else {\n // Leaf is in the chain but not at the top, which is invalid.\n throw new InvalidConfigurationError(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${leafIndex}).`);\n }\n return JSON.stringify(finalChain.map(cert => cert.raw.toString('base64')));\n }\n catch (err) {\n // Re-throw our specific configuration errors.\n if (err instanceof InvalidConfigurationError)\n throw err;\n const message = err instanceof Error ? err.message : String(err);\n throw new CertificateSourceUnavailableError(`Failed to process certificate chain from ${this.trustChainPath}: ${message}`);\n }\n }\n}\nexports.CertificateSubjectTokenSupplier = CertificateSubjectTokenSupplier;\n//# sourceMappingURL=certificatesubjecttokensupplier.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.IdentityPoolClient = void 0;\nconst baseexternalclient_1 = require(\"./baseexternalclient\");\nconst util_1 = require(\"../util\");\nconst filesubjecttokensupplier_1 = require(\"./filesubjecttokensupplier\");\nconst urlsubjecttokensupplier_1 = require(\"./urlsubjecttokensupplier\");\nconst certificatesubjecttokensupplier_1 = require(\"./certificatesubjecttokensupplier\");\nconst stscredentials_1 = require(\"./stscredentials\");\nconst gaxios_1 = require(\"gaxios\");\n/**\n * Defines the Url-sourced and file-sourced external account clients mainly\n * used for K8s and Azure workloads.\n */\nclass IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient {\n subjectTokenSupplier;\n /**\n * Instantiate an IdentityPoolClient instance using the provided JSON\n * object loaded from an external account credentials file.\n * An error is thrown if the credential is not a valid file-sourced or\n * url-sourced credential or a workforce pool user project is provided\n * with a non workforce audience.\n * @param options The external account options object typically loaded\n * from the external account JSON credential file. The camelCased options\n * are aliases for the snake_cased options.\n */\n constructor(options) {\n super(options);\n const opts = (0, util_1.originalOrCamelOptions)(options);\n const credentialSource = opts.get('credential_source');\n const subjectTokenSupplier = opts.get('subject_token_supplier');\n // Validate credential sourcing configuration.\n if (!credentialSource && !subjectTokenSupplier) {\n throw new Error('A credential source or subject token supplier must be specified.');\n }\n if (credentialSource && subjectTokenSupplier) {\n throw new Error('Only one of credential source or subject token supplier can be specified.');\n }\n if (subjectTokenSupplier) {\n this.subjectTokenSupplier = subjectTokenSupplier;\n this.credentialSourceType = 'programmatic';\n }\n else {\n const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource);\n const formatOpts = (0, util_1.originalOrCamelOptions)(credentialSourceOpts.get('format'));\n // Text is the default format type.\n const formatType = formatOpts.get('type') || 'text';\n const formatSubjectTokenFieldName = formatOpts.get('subject_token_field_name');\n if (formatType !== 'json' && formatType !== 'text') {\n throw new Error(`Invalid credential_source format \"${formatType}\"`);\n }\n if (formatType === 'json' && !formatSubjectTokenFieldName) {\n throw new Error('Missing subject_token_field_name for JSON credential_source format');\n }\n const file = credentialSourceOpts.get('file');\n const url = credentialSourceOpts.get('url');\n const certificate = credentialSourceOpts.get('certificate');\n const headers = credentialSourceOpts.get('headers');\n if ((file && url) || (url && certificate) || (file && certificate)) {\n throw new Error('No valid Identity Pool \"credential_source\" provided, must be either file, url, or certificate.');\n }\n else if (file) {\n this.credentialSourceType = 'file';\n this.subjectTokenSupplier = new filesubjecttokensupplier_1.FileSubjectTokenSupplier({\n filePath: file,\n formatType: formatType,\n subjectTokenFieldName: formatSubjectTokenFieldName,\n });\n }\n else if (url) {\n this.credentialSourceType = 'url';\n this.subjectTokenSupplier = new urlsubjecttokensupplier_1.UrlSubjectTokenSupplier({\n url: url,\n formatType: formatType,\n subjectTokenFieldName: formatSubjectTokenFieldName,\n headers: headers,\n additionalGaxiosOptions: IdentityPoolClient.RETRY_CONFIG,\n });\n }\n else if (certificate) {\n this.credentialSourceType = 'certificate';\n const certificateSubjecttokensupplier = new certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier({\n useDefaultCertificateConfig: certificate.use_default_certificate_config,\n certificateConfigLocation: certificate.certificate_config_location,\n trustChainPath: certificate.trust_chain_path,\n });\n this.subjectTokenSupplier = certificateSubjecttokensupplier;\n }\n else {\n throw new Error('No valid Identity Pool \"credential_source\" provided, must be either file, url, or certificate.');\n }\n }\n }\n /**\n * Triggered when a external subject token is needed to be exchanged for a GCP\n * access token via GCP STS endpoint. Gets a subject token by calling\n * the configured {@link SubjectTokenSupplier}\n * @return A promise that resolves with the external subject token.\n */\n async retrieveSubjectToken() {\n const subjectToken = await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);\n if (this.subjectTokenSupplier instanceof certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier) {\n const mtlsAgent = await this.subjectTokenSupplier.createMtlsHttpsAgent();\n this.stsCredential = new stscredentials_1.StsCredentials({\n tokenExchangeEndpoint: this.getTokenUrl(),\n clientAuthentication: this.clientAuth,\n transporter: new gaxios_1.Gaxios({ agent: mtlsAgent }),\n });\n this.transporter = new gaxios_1.Gaxios({\n ...(this.transporter.defaults || {}),\n agent: mtlsAgent,\n });\n }\n return subjectToken;\n }\n}\nexports.IdentityPoolClient = IdentityPoolClient;\n//# sourceMappingURL=identitypoolclient.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AwsRequestSigner = void 0;\nconst gaxios_1 = require(\"gaxios\");\nconst crypto_1 = require(\"../crypto/crypto\");\n/** AWS Signature Version 4 signing algorithm identifier. */\nconst AWS_ALGORITHM = 'AWS4-HMAC-SHA256';\n/**\n * The termination string for the AWS credential scope value as defined in\n * https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html\n */\nconst AWS_REQUEST_TYPE = 'aws4_request';\n/**\n * Implements an AWS API request signer based on the AWS Signature Version 4\n * signing process.\n * https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html\n */\nclass AwsRequestSigner {\n getCredentials;\n region;\n crypto;\n /**\n * Instantiates an AWS API request signer used to send authenticated signed\n * requests to AWS APIs based on the AWS Signature Version 4 signing process.\n * This also provides a mechanism to generate the signed request without\n * sending it.\n * @param getCredentials A mechanism to retrieve AWS security credentials\n * when needed.\n * @param region The AWS region to use.\n */\n constructor(getCredentials, region) {\n this.getCredentials = getCredentials;\n this.region = region;\n this.crypto = (0, crypto_1.createCrypto)();\n }\n /**\n * Generates the signed request for the provided HTTP request for calling\n * an AWS API. This follows the steps described at:\n * https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html\n * @param amzOptions The AWS request options that need to be signed.\n * @return A promise that resolves with the GaxiosOptions containing the\n * signed HTTP request parameters.\n */\n async getRequestOptions(amzOptions) {\n if (!amzOptions.url) {\n throw new RangeError('\"url\" is required in \"amzOptions\"');\n }\n // Stringify JSON requests. This will be set in the request body of the\n // generated signed request.\n const requestPayloadData = typeof amzOptions.data === 'object'\n ? JSON.stringify(amzOptions.data)\n : amzOptions.data;\n const url = amzOptions.url;\n const method = amzOptions.method || 'GET';\n const requestPayload = amzOptions.body || requestPayloadData;\n const additionalAmzHeaders = amzOptions.headers;\n const awsSecurityCredentials = await this.getCredentials();\n const uri = new URL(url);\n if (typeof requestPayload !== 'string' && requestPayload !== undefined) {\n throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${requestPayload}`);\n }\n const headerMap = await generateAuthenticationHeaderMap({\n crypto: this.crypto,\n host: uri.host,\n canonicalUri: uri.pathname,\n canonicalQuerystring: uri.search.slice(1),\n method,\n region: this.region,\n securityCredentials: awsSecurityCredentials,\n requestPayload,\n additionalAmzHeaders,\n });\n // Append additional optional headers, eg. X-Amz-Target, Content-Type, etc.\n const headers = gaxios_1.Gaxios.mergeHeaders(\n // Add x-amz-date if available.\n headerMap.amzDate ? { 'x-amz-date': headerMap.amzDate } : {}, {\n authorization: headerMap.authorizationHeader,\n host: uri.host,\n }, additionalAmzHeaders || {});\n if (awsSecurityCredentials.token) {\n gaxios_1.Gaxios.mergeHeaders(headers, {\n 'x-amz-security-token': awsSecurityCredentials.token,\n });\n }\n const awsSignedReq = {\n url,\n method: method,\n headers,\n };\n if (requestPayload !== undefined) {\n awsSignedReq.body = requestPayload;\n }\n return awsSignedReq;\n }\n}\nexports.AwsRequestSigner = AwsRequestSigner;\n/**\n * Creates the HMAC-SHA256 hash of the provided message using the\n * provided key.\n *\n * @param crypto The crypto instance used to facilitate cryptographic\n * operations.\n * @param key The HMAC-SHA256 key to use.\n * @param msg The message to hash.\n * @return The computed hash bytes.\n */\nasync function sign(crypto, key, msg) {\n return await crypto.signWithHmacSha256(key, msg);\n}\n/**\n * Calculates the signing key used to calculate the signature for\n * AWS Signature Version 4 based on:\n * https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html\n *\n * @param crypto The crypto instance used to facilitate cryptographic\n * operations.\n * @param key The AWS secret access key.\n * @param dateStamp The '%Y%m%d' date format.\n * @param region The AWS region.\n * @param serviceName The AWS service name, eg. sts.\n * @return The signing key bytes.\n */\nasync function getSigningKey(crypto, key, dateStamp, region, serviceName) {\n const kDate = await sign(crypto, `AWS4${key}`, dateStamp);\n const kRegion = await sign(crypto, kDate, region);\n const kService = await sign(crypto, kRegion, serviceName);\n const kSigning = await sign(crypto, kService, 'aws4_request');\n return kSigning;\n}\n/**\n * Generates the authentication header map needed for generating the AWS\n * Signature Version 4 signed request.\n *\n * @param option The options needed to compute the authentication header map.\n * @return The AWS authentication header map which constitutes of the following\n * components: amz-date, authorization header and canonical query string.\n */\nasync function generateAuthenticationHeaderMap(options) {\n const additionalAmzHeaders = gaxios_1.Gaxios.mergeHeaders(options.additionalAmzHeaders);\n const requestPayload = options.requestPayload || '';\n // iam.amazonaws.com host => iam service.\n // sts.us-east-2.amazonaws.com => sts service.\n const serviceName = options.host.split('.')[0];\n const now = new Date();\n // Format: '%Y%m%dT%H%M%SZ'.\n const amzDate = now\n .toISOString()\n .replace(/[-:]/g, '')\n .replace(/\\.[0-9]+/, '');\n // Format: '%Y%m%d'.\n const dateStamp = now.toISOString().replace(/[-]/g, '').replace(/T.*/, '');\n // Add AWS token if available.\n if (options.securityCredentials.token) {\n additionalAmzHeaders.set('x-amz-security-token', options.securityCredentials.token);\n }\n // Header keys need to be sorted alphabetically.\n const amzHeaders = gaxios_1.Gaxios.mergeHeaders({\n host: options.host,\n }, \n // Previously the date was not fixed with x-amz- and could be provided manually.\n // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.req\n additionalAmzHeaders.has('date') ? {} : { 'x-amz-date': amzDate }, additionalAmzHeaders);\n let canonicalHeaders = '';\n // TypeScript is missing `Headers#keys` at the time of writing\n const signedHeadersList = [\n ...amzHeaders.keys(),\n ].sort();\n signedHeadersList.forEach(key => {\n canonicalHeaders += `${key}:${amzHeaders.get(key)}\\n`;\n });\n const signedHeaders = signedHeadersList.join(';');\n const payloadHash = await options.crypto.sha256DigestHex(requestPayload);\n // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html\n const canonicalRequest = `${options.method.toUpperCase()}\\n` +\n `${options.canonicalUri}\\n` +\n `${options.canonicalQuerystring}\\n` +\n `${canonicalHeaders}\\n` +\n `${signedHeaders}\\n` +\n `${payloadHash}`;\n const credentialScope = `${dateStamp}/${options.region}/${serviceName}/${AWS_REQUEST_TYPE}`;\n // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html\n const stringToSign = `${AWS_ALGORITHM}\\n` +\n `${amzDate}\\n` +\n `${credentialScope}\\n` +\n (await options.crypto.sha256DigestHex(canonicalRequest));\n // https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html\n const signingKey = await getSigningKey(options.crypto, options.securityCredentials.secretAccessKey, dateStamp, options.region, serviceName);\n const signature = await sign(options.crypto, signingKey, stringToSign);\n // https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html\n const authorizationHeader = `${AWS_ALGORITHM} Credential=${options.securityCredentials.accessKeyId}/` +\n `${credentialScope}, SignedHeaders=${signedHeaders}, ` +\n `Signature=${(0, crypto_1.fromArrayBufferToHex)(signature)}`;\n return {\n // Do not return x-amz-date if date is available.\n amzDate: additionalAmzHeaders.has('date') ? undefined : amzDate,\n authorizationHeader,\n canonicalQuerystring: options.canonicalQuerystring,\n };\n}\n//# sourceMappingURL=awsrequestsigner.js.map", "\"use strict\";\n// Copyright 2024 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DefaultAwsSecurityCredentialsSupplier = void 0;\nconst authclient_1 = require(\"./authclient\");\n/**\n * Internal AWS security credentials supplier implementation used by {@link AwsClient}\n * when a credential source is provided instead of a user defined supplier.\n * The logic is summarized as:\n * 1. If imdsv2_session_token_url is provided in the credential source, then\n * fetch the aws session token and include it in the headers of the\n * metadata requests. This is a requirement for IDMSv2 but optional\n * for IDMSv1.\n * 2. Retrieve AWS region from availability-zone.\n * 3a. Check AWS credentials in environment variables. If not found, get\n * from security-credentials endpoint.\n * 3b. Get AWS credentials from security-credentials endpoint. In order\n * to retrieve this, the AWS role needs to be determined by calling\n * security-credentials endpoint without any argument. Then the\n * credentials can be retrieved via: security-credentials/role_name\n * 4. Generate the signed request to AWS STS GetCallerIdentity action.\n * 5. Inject x-goog-cloud-target-resource into header and serialize the\n * signed request. This will be the subject-token to pass to GCP STS.\n */\nclass DefaultAwsSecurityCredentialsSupplier {\n regionUrl;\n securityCredentialsUrl;\n imdsV2SessionTokenUrl;\n additionalGaxiosOptions;\n /**\n * Instantiates a new DefaultAwsSecurityCredentialsSupplier using information\n * from the credential_source stored in the ADC file.\n * @param opts The default aws security credentials supplier options object to\n * build the supplier with.\n */\n constructor(opts) {\n this.regionUrl = opts.regionUrl;\n this.securityCredentialsUrl = opts.securityCredentialsUrl;\n this.imdsV2SessionTokenUrl = opts.imdsV2SessionTokenUrl;\n this.additionalGaxiosOptions = opts.additionalGaxiosOptions;\n }\n /**\n * Returns the active AWS region. This first checks to see if the region\n * is available as an environment variable. If it is not, then the supplier\n * will call the region URL.\n * @param context {@link ExternalAccountSupplierContext} from the calling\n * {@link AwsClient}, contains the requested audience and subject token type\n * for the external account identity.\n * @return A promise that resolves with the AWS region string.\n */\n async getAwsRegion(context) {\n // Priority order for region determination:\n // AWS_REGION > AWS_DEFAULT_REGION > metadata server.\n if (this.#regionFromEnv) {\n return this.#regionFromEnv;\n }\n const metadataHeaders = new Headers();\n if (!this.#regionFromEnv && this.imdsV2SessionTokenUrl) {\n metadataHeaders.set('x-aws-ec2-metadata-token', await this.#getImdsV2SessionToken(context.transporter));\n }\n if (!this.regionUrl) {\n throw new RangeError('Unable to determine AWS region due to missing ' +\n '\"options.credential_source.region_url\"');\n }\n const opts = {\n ...this.additionalGaxiosOptions,\n url: this.regionUrl,\n method: 'GET',\n headers: metadataHeaders,\n };\n authclient_1.AuthClient.setMethodName(opts, 'getAwsRegion');\n const response = await context.transporter.request(opts);\n // Remove last character. For example, if us-east-2b is returned,\n // the region would be us-east-2.\n return response.data.substr(0, response.data.length - 1);\n }\n /**\n * Returns AWS security credentials. This first checks to see if the credentials\n * is available as environment variables. If it is not, then the supplier\n * will call the security credentials URL.\n * @param context {@link ExternalAccountSupplierContext} from the calling\n * {@link AwsClient}, contains the requested audience and subject token type\n * for the external account identity.\n * @return A promise that resolves with the AWS security credentials.\n */\n async getAwsSecurityCredentials(context) {\n // Check environment variables for permanent credentials first.\n // https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html\n if (this.#securityCredentialsFromEnv) {\n return this.#securityCredentialsFromEnv;\n }\n const metadataHeaders = new Headers();\n if (this.imdsV2SessionTokenUrl) {\n metadataHeaders.set('x-aws-ec2-metadata-token', await this.#getImdsV2SessionToken(context.transporter));\n }\n // Since the role on a VM can change, we don't need to cache it.\n const roleName = await this.#getAwsRoleName(metadataHeaders, context.transporter);\n // Temporary credentials typically last for several hours.\n // Expiration is returned in response.\n // Consider future optimization of this logic to cache AWS tokens\n // until their natural expiration.\n const awsCreds = await this.#retrieveAwsSecurityCredentials(roleName, metadataHeaders, context.transporter);\n return {\n accessKeyId: awsCreds.AccessKeyId,\n secretAccessKey: awsCreds.SecretAccessKey,\n token: awsCreds.Token,\n };\n }\n /**\n * @param transporter The transporter to use for requests.\n * @return A promise that resolves with the IMDSv2 Session Token.\n */\n async #getImdsV2SessionToken(transporter) {\n const opts = {\n ...this.additionalGaxiosOptions,\n url: this.imdsV2SessionTokenUrl,\n method: 'PUT',\n headers: { 'x-aws-ec2-metadata-token-ttl-seconds': '300' },\n };\n authclient_1.AuthClient.setMethodName(opts, '#getImdsV2SessionToken');\n const response = await transporter.request(opts);\n return response.data;\n }\n /**\n * @param headers The headers to be used in the metadata request.\n * @param transporter The transporter to use for requests.\n * @return A promise that resolves with the assigned role to the current\n * AWS VM. This is needed for calling the security-credentials endpoint.\n */\n async #getAwsRoleName(headers, transporter) {\n if (!this.securityCredentialsUrl) {\n throw new Error('Unable to determine AWS role name due to missing ' +\n '\"options.credential_source.url\"');\n }\n const opts = {\n ...this.additionalGaxiosOptions,\n url: this.securityCredentialsUrl,\n method: 'GET',\n headers: headers,\n };\n authclient_1.AuthClient.setMethodName(opts, '#getAwsRoleName');\n const response = await transporter.request(opts);\n return response.data;\n }\n /**\n * Retrieves the temporary AWS credentials by calling the security-credentials\n * endpoint as specified in the `credential_source` object.\n * @param roleName The role attached to the current VM.\n * @param headers The headers to be used in the metadata request.\n * @param transporter The transporter to use for requests.\n * @return A promise that resolves with the temporary AWS credentials\n * needed for creating the GetCallerIdentity signed request.\n */\n async #retrieveAwsSecurityCredentials(roleName, headers, transporter) {\n const opts = {\n ...this.additionalGaxiosOptions,\n url: `${this.securityCredentialsUrl}/${roleName}`,\n headers: headers,\n };\n authclient_1.AuthClient.setMethodName(opts, '#retrieveAwsSecurityCredentials');\n const response = await transporter.request(opts);\n return response.data;\n }\n get #regionFromEnv() {\n // The AWS region can be provided through AWS_REGION or AWS_DEFAULT_REGION.\n // Only one is required.\n return (process.env['AWS_REGION'] || process.env['AWS_DEFAULT_REGION'] || null);\n }\n get #securityCredentialsFromEnv() {\n // Both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are required.\n if (process.env['AWS_ACCESS_KEY_ID'] &&\n process.env['AWS_SECRET_ACCESS_KEY']) {\n return {\n accessKeyId: process.env['AWS_ACCESS_KEY_ID'],\n secretAccessKey: process.env['AWS_SECRET_ACCESS_KEY'],\n token: process.env['AWS_SESSION_TOKEN'],\n };\n }\n return null;\n }\n}\nexports.DefaultAwsSecurityCredentialsSupplier = DefaultAwsSecurityCredentialsSupplier;\n//# sourceMappingURL=defaultawssecuritycredentialssupplier.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AwsClient = void 0;\nconst awsrequestsigner_1 = require(\"./awsrequestsigner\");\nconst baseexternalclient_1 = require(\"./baseexternalclient\");\nconst defaultawssecuritycredentialssupplier_1 = require(\"./defaultawssecuritycredentialssupplier\");\nconst util_1 = require(\"../util\");\nconst gaxios_1 = require(\"gaxios\");\n/**\n * AWS external account client. This is used for AWS workloads, where\n * AWS STS GetCallerIdentity serialized signed requests are exchanged for\n * GCP access token.\n */\nclass AwsClient extends baseexternalclient_1.BaseExternalAccountClient {\n environmentId;\n awsSecurityCredentialsSupplier;\n regionalCredVerificationUrl;\n awsRequestSigner;\n region;\n static #DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL = 'https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15';\n /**\n * @deprecated AWS client no validates the EC2 metadata address.\n **/\n static AWS_EC2_METADATA_IPV4_ADDRESS = '169.254.169.254';\n /**\n * @deprecated AWS client no validates the EC2 metadata address.\n **/\n static AWS_EC2_METADATA_IPV6_ADDRESS = 'fd00:ec2::254';\n /**\n * Instantiates an AwsClient instance using the provided JSON\n * object loaded from an external account credentials file.\n * An error is thrown if the credential is not a valid AWS credential.\n * @param options The external account options object typically loaded\n * from the external account JSON credential file.\n */\n constructor(options) {\n super(options);\n const opts = (0, util_1.originalOrCamelOptions)(options);\n const credentialSource = opts.get('credential_source');\n const awsSecurityCredentialsSupplier = opts.get('aws_security_credentials_supplier');\n // Validate credential sourcing configuration.\n if (!credentialSource && !awsSecurityCredentialsSupplier) {\n throw new Error('A credential source or AWS security credentials supplier must be specified.');\n }\n if (credentialSource && awsSecurityCredentialsSupplier) {\n throw new Error('Only one of credential source or AWS security credentials supplier can be specified.');\n }\n if (awsSecurityCredentialsSupplier) {\n this.awsSecurityCredentialsSupplier = awsSecurityCredentialsSupplier;\n this.regionalCredVerificationUrl =\n AwsClient.#DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL;\n this.credentialSourceType = 'programmatic';\n }\n else {\n const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource);\n this.environmentId = credentialSourceOpts.get('environment_id');\n // This is only required if the AWS region is not available in the\n // AWS_REGION or AWS_DEFAULT_REGION environment variables.\n const regionUrl = credentialSourceOpts.get('region_url');\n // This is only required if AWS security credentials are not available in\n // environment variables.\n const securityCredentialsUrl = credentialSourceOpts.get('url');\n const imdsV2SessionTokenUrl = credentialSourceOpts.get('imdsv2_session_token_url');\n this.awsSecurityCredentialsSupplier =\n new defaultawssecuritycredentialssupplier_1.DefaultAwsSecurityCredentialsSupplier({\n regionUrl: regionUrl,\n securityCredentialsUrl: securityCredentialsUrl,\n imdsV2SessionTokenUrl: imdsV2SessionTokenUrl,\n });\n this.regionalCredVerificationUrl = credentialSourceOpts.get('regional_cred_verification_url');\n this.credentialSourceType = 'aws';\n // Data validators.\n this.validateEnvironmentId();\n }\n this.awsRequestSigner = null;\n this.region = '';\n }\n validateEnvironmentId() {\n const match = this.environmentId?.match(/^(aws)(\\d+)$/);\n if (!match || !this.regionalCredVerificationUrl) {\n throw new Error('No valid AWS \"credential_source\" provided');\n }\n else if (parseInt(match[2], 10) !== 1) {\n throw new Error(`aws version \"${match[2]}\" is not supported in the current build.`);\n }\n }\n /**\n * Triggered when an external subject token is needed to be exchanged for a\n * GCP access token via GCP STS endpoint. This will call the\n * {@link AwsSecurityCredentialsSupplier} to retrieve an AWS region and AWS\n * Security Credentials, then use them to create a signed AWS STS request that\n * can be exchanged for a GCP access token.\n * @return A promise that resolves with the external subject token.\n */\n async retrieveSubjectToken() {\n // Initialize AWS request signer if not already initialized.\n if (!this.awsRequestSigner) {\n this.region = await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext);\n this.awsRequestSigner = new awsrequestsigner_1.AwsRequestSigner(async () => {\n return this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext);\n }, this.region);\n }\n // Generate signed request to AWS STS GetCallerIdentity API.\n // Use the required regional endpoint. Otherwise, the request will fail.\n const options = await this.awsRequestSigner.getRequestOptions({\n ...AwsClient.RETRY_CONFIG,\n url: this.regionalCredVerificationUrl.replace('{region}', this.region),\n method: 'POST',\n });\n // The GCP STS endpoint expects the headers to be formatted as:\n // [\n // {key: 'x-amz-date', value: '...'},\n // {key: 'authorization', value: '...'},\n // ...\n // ]\n // And then serialized as:\n // encodeURIComponent(JSON.stringify({\n // url: '...',\n // method: 'POST',\n // headers: [{key: 'x-amz-date', value: '...'}, ...]\n // }))\n const reformattedHeader = [];\n const extendedHeaders = gaxios_1.Gaxios.mergeHeaders({\n // The full, canonical resource name of the workload identity pool\n // provider, with or without the HTTPS prefix.\n // Including this header as part of the signature is recommended to\n // ensure data integrity.\n 'x-goog-cloud-target-resource': this.audience,\n }, options.headers);\n // Reformat header to GCP STS expected format.\n extendedHeaders.forEach((value, key) => reformattedHeader.push({ key, value }));\n // Serialize the reformatted signed request.\n return encodeURIComponent(JSON.stringify({\n url: options.url,\n method: options.method,\n headers: reformattedHeader,\n }));\n }\n}\nexports.AwsClient = AwsClient;\n//# sourceMappingURL=awsclient.js.map", "\"use strict\";\n// Copyright 2022 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.InvalidSubjectTokenError = exports.InvalidMessageFieldError = exports.InvalidCodeFieldError = exports.InvalidTokenTypeFieldError = exports.InvalidExpirationTimeFieldError = exports.InvalidSuccessFieldError = exports.InvalidVersionFieldError = exports.ExecutableResponseError = exports.ExecutableResponse = void 0;\nconst SAML_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:saml2';\nconst OIDC_SUBJECT_TOKEN_TYPE1 = 'urn:ietf:params:oauth:token-type:id_token';\nconst OIDC_SUBJECT_TOKEN_TYPE2 = 'urn:ietf:params:oauth:token-type:jwt';\n/**\n * Defines the response of a 3rd party executable run by the pluggable auth client.\n */\nclass ExecutableResponse {\n /**\n * The version of the Executable response. Only version 1 is currently supported.\n */\n version;\n /**\n * Whether the executable ran successfully.\n */\n success;\n /**\n * The epoch time for expiration of the token in seconds.\n */\n expirationTime;\n /**\n * The type of subject token in the response, currently supported values are:\n * urn:ietf:params:oauth:token-type:saml2\n * urn:ietf:params:oauth:token-type:id_token\n * urn:ietf:params:oauth:token-type:jwt\n */\n tokenType;\n /**\n * The error code from the executable.\n */\n errorCode;\n /**\n * The error message from the executable.\n */\n errorMessage;\n /**\n * The subject token from the executable, format depends on tokenType.\n */\n subjectToken;\n /**\n * Instantiates an ExecutableResponse instance using the provided JSON object\n * from the output of the executable.\n * @param responseJson Response from a 3rd party executable, loaded from a\n * run of the executable or a cached output file.\n */\n constructor(responseJson) {\n // Check that the required fields exist in the json response.\n if (!responseJson.version) {\n throw new InvalidVersionFieldError(\"Executable response must contain a 'version' field.\");\n }\n if (responseJson.success === undefined) {\n throw new InvalidSuccessFieldError(\"Executable response must contain a 'success' field.\");\n }\n this.version = responseJson.version;\n this.success = responseJson.success;\n // Validate required fields for a successful response.\n if (this.success) {\n this.expirationTime = responseJson.expiration_time;\n this.tokenType = responseJson.token_type;\n // Validate token type field.\n if (this.tokenType !== SAML_SUBJECT_TOKEN_TYPE &&\n this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE1 &&\n this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE2) {\n throw new InvalidTokenTypeFieldError(\"Executable response must contain a 'token_type' field when successful \" +\n `and it must be one of ${OIDC_SUBJECT_TOKEN_TYPE1}, ${OIDC_SUBJECT_TOKEN_TYPE2}, or ${SAML_SUBJECT_TOKEN_TYPE}.`);\n }\n // Validate subject token.\n if (this.tokenType === SAML_SUBJECT_TOKEN_TYPE) {\n if (!responseJson.saml_response) {\n throw new InvalidSubjectTokenError(`Executable response must contain a 'saml_response' field when token_type=${SAML_SUBJECT_TOKEN_TYPE}.`);\n }\n this.subjectToken = responseJson.saml_response;\n }\n else {\n if (!responseJson.id_token) {\n throw new InvalidSubjectTokenError(\"Executable response must contain a 'id_token' field when \" +\n `token_type=${OIDC_SUBJECT_TOKEN_TYPE1} or ${OIDC_SUBJECT_TOKEN_TYPE2}.`);\n }\n this.subjectToken = responseJson.id_token;\n }\n }\n else {\n // Both code and message must be provided for unsuccessful responses.\n if (!responseJson.code) {\n throw new InvalidCodeFieldError(\"Executable response must contain a 'code' field when unsuccessful.\");\n }\n if (!responseJson.message) {\n throw new InvalidMessageFieldError(\"Executable response must contain a 'message' field when unsuccessful.\");\n }\n this.errorCode = responseJson.code;\n this.errorMessage = responseJson.message;\n }\n }\n /**\n * @return A boolean representing if the response has a valid token. Returns\n * true when the response was successful and the token is not expired.\n */\n isValid() {\n return !this.isExpired() && this.success;\n }\n /**\n * @return A boolean representing if the response is expired. Returns true if the\n * provided timeout has passed.\n */\n isExpired() {\n return (this.expirationTime !== undefined &&\n this.expirationTime < Math.round(Date.now() / 1000));\n }\n}\nexports.ExecutableResponse = ExecutableResponse;\n/**\n * An error thrown by the ExecutableResponse class.\n */\nclass ExecutableResponseError extends Error {\n constructor(message) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\nexports.ExecutableResponseError = ExecutableResponseError;\n/**\n * An error thrown when the 'version' field in an executable response is missing or invalid.\n */\nclass InvalidVersionFieldError extends ExecutableResponseError {\n}\nexports.InvalidVersionFieldError = InvalidVersionFieldError;\n/**\n * An error thrown when the 'success' field in an executable response is missing or invalid.\n */\nclass InvalidSuccessFieldError extends ExecutableResponseError {\n}\nexports.InvalidSuccessFieldError = InvalidSuccessFieldError;\n/**\n * An error thrown when the 'expiration_time' field in an executable response is missing or invalid.\n */\nclass InvalidExpirationTimeFieldError extends ExecutableResponseError {\n}\nexports.InvalidExpirationTimeFieldError = InvalidExpirationTimeFieldError;\n/**\n * An error thrown when the 'token_type' field in an executable response is missing or invalid.\n */\nclass InvalidTokenTypeFieldError extends ExecutableResponseError {\n}\nexports.InvalidTokenTypeFieldError = InvalidTokenTypeFieldError;\n/**\n * An error thrown when the 'code' field in an executable response is missing or invalid.\n */\nclass InvalidCodeFieldError extends ExecutableResponseError {\n}\nexports.InvalidCodeFieldError = InvalidCodeFieldError;\n/**\n * An error thrown when the 'message' field in an executable response is missing or invalid.\n */\nclass InvalidMessageFieldError extends ExecutableResponseError {\n}\nexports.InvalidMessageFieldError = InvalidMessageFieldError;\n/**\n * An error thrown when the subject token in an executable response is missing or invalid.\n */\nclass InvalidSubjectTokenError extends ExecutableResponseError {\n}\nexports.InvalidSubjectTokenError = InvalidSubjectTokenError;\n//# sourceMappingURL=executable-response.js.map", "\"use strict\";\n// Copyright 2022 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PluggableAuthHandler = exports.ExecutableError = void 0;\nconst executable_response_1 = require(\"./executable-response\");\nconst childProcess = require(\"child_process\");\nconst fs = require(\"fs\");\n/**\n * Error thrown from the executable run by PluggableAuthClient.\n */\nclass ExecutableError extends Error {\n /**\n * The exit code returned by the executable.\n */\n code;\n constructor(message, code) {\n super(`The executable failed with exit code: ${code} and error message: ${message}.`);\n this.code = code;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\nexports.ExecutableError = ExecutableError;\n/**\n * A handler used to retrieve 3rd party token responses from user defined\n * executables and cached file output for the PluggableAuthClient class.\n */\nclass PluggableAuthHandler {\n commandComponents;\n timeoutMillis;\n outputFile;\n /**\n * Instantiates a PluggableAuthHandler instance using the provided\n * PluggableAuthHandlerOptions object.\n */\n constructor(options) {\n if (!options.command) {\n throw new Error('No command provided.');\n }\n this.commandComponents = PluggableAuthHandler.parseCommand(options.command);\n this.timeoutMillis = options.timeoutMillis;\n if (!this.timeoutMillis) {\n throw new Error('No timeoutMillis provided.');\n }\n this.outputFile = options.outputFile;\n }\n /**\n * Calls user provided executable to get a 3rd party subject token and\n * returns the response.\n * @param envMap a Map of additional Environment Variables required for\n * the executable.\n * @return A promise that resolves with the executable response.\n */\n retrieveResponseFromExecutable(envMap) {\n return new Promise((resolve, reject) => {\n // Spawn process to run executable using added environment variables.\n const child = childProcess.spawn(this.commandComponents[0], this.commandComponents.slice(1), {\n env: { ...process.env, ...Object.fromEntries(envMap) },\n });\n let output = '';\n // Append stdout to output as executable runs.\n child.stdout.on('data', (data) => {\n output += data;\n });\n // Append stderr as executable runs.\n child.stderr.on('data', (err) => {\n output += err;\n });\n // Set up a timeout to end the child process and throw an error.\n const timeout = setTimeout(() => {\n // Kill child process and remove listeners so 'close' event doesn't get\n // read after child process is killed.\n child.removeAllListeners();\n child.kill();\n return reject(new Error('The executable failed to finish within the timeout specified.'));\n }, this.timeoutMillis);\n child.on('close', (code) => {\n // Cancel timeout if executable closes before timeout is reached.\n clearTimeout(timeout);\n if (code === 0) {\n // If the executable completed successfully, try to return the parsed response.\n try {\n const responseJson = JSON.parse(output);\n const response = new executable_response_1.ExecutableResponse(responseJson);\n return resolve(response);\n }\n catch (error) {\n if (error instanceof executable_response_1.ExecutableResponseError) {\n return reject(error);\n }\n return reject(new executable_response_1.ExecutableResponseError(`The executable returned an invalid response: ${output}`));\n }\n }\n else {\n return reject(new ExecutableError(output, code.toString()));\n }\n });\n });\n }\n /**\n * Checks user provided output file for response from previous run of\n * executable and return the response if it exists, is formatted correctly, and is not expired.\n */\n async retrieveCachedResponse() {\n if (!this.outputFile || this.outputFile.length === 0) {\n return undefined;\n }\n let filePath;\n try {\n filePath = await fs.promises.realpath(this.outputFile);\n }\n catch {\n // If file path cannot be resolved, return undefined.\n return undefined;\n }\n if (!(await fs.promises.lstat(filePath)).isFile()) {\n // If path does not lead to file, return undefined.\n return undefined;\n }\n const responseString = await fs.promises.readFile(filePath, {\n encoding: 'utf8',\n });\n if (responseString === '') {\n return undefined;\n }\n try {\n const responseJson = JSON.parse(responseString);\n const response = new executable_response_1.ExecutableResponse(responseJson);\n // Check if response is successful and unexpired.\n if (response.isValid()) {\n return new executable_response_1.ExecutableResponse(responseJson);\n }\n return undefined;\n }\n catch (error) {\n if (error instanceof executable_response_1.ExecutableResponseError) {\n throw error;\n }\n throw new executable_response_1.ExecutableResponseError(`The output file contained an invalid response: ${responseString}`);\n }\n }\n /**\n * Parses given command string into component array, splitting on spaces unless\n * spaces are between quotation marks.\n */\n static parseCommand(command) {\n // Split the command into components by splitting on spaces,\n // unless spaces are contained in quotation marks.\n const components = command.match(/(?:[^\\s\"]+|\"[^\"]*\")+/g);\n if (!components) {\n throw new Error(`Provided command: \"${command}\" could not be parsed.`);\n }\n // Remove quotation marks from the beginning and end of each component if they are present.\n for (let i = 0; i < components.length; i++) {\n if (components[i][0] === '\"' && components[i].slice(-1) === '\"') {\n components[i] = components[i].slice(1, -1);\n }\n }\n return components;\n }\n}\nexports.PluggableAuthHandler = PluggableAuthHandler;\n//# sourceMappingURL=pluggable-auth-handler.js.map", "\"use strict\";\n// Copyright 2022 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PluggableAuthClient = exports.ExecutableError = void 0;\nconst baseexternalclient_1 = require(\"./baseexternalclient\");\nconst executable_response_1 = require(\"./executable-response\");\nconst pluggable_auth_handler_1 = require(\"./pluggable-auth-handler\");\nvar pluggable_auth_handler_2 = require(\"./pluggable-auth-handler\");\nObject.defineProperty(exports, \"ExecutableError\", { enumerable: true, get: function () { return pluggable_auth_handler_2.ExecutableError; } });\n/**\n * The default executable timeout when none is provided, in milliseconds.\n */\nconst DEFAULT_EXECUTABLE_TIMEOUT_MILLIS = 30 * 1000;\n/**\n * The minimum allowed executable timeout in milliseconds.\n */\nconst MINIMUM_EXECUTABLE_TIMEOUT_MILLIS = 5 * 1000;\n/**\n * The maximum allowed executable timeout in milliseconds.\n */\nconst MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS = 120 * 1000;\n/**\n * The environment variable to check to see if executable can be run.\n * Value must be set to '1' for the executable to run.\n */\nconst GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES = 'GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES';\n/**\n * The maximum currently supported executable version.\n */\nconst MAXIMUM_EXECUTABLE_VERSION = 1;\n/**\n * PluggableAuthClient enables the exchange of workload identity pool external credentials for\n * Google access tokens by retrieving 3rd party tokens through a user supplied executable. These\n * scripts/executables are completely independent of the Google Cloud Auth libraries. These\n * credentials plug into ADC and will call the specified executable to retrieve the 3rd party token\n * to be exchanged for a Google access token.\n *\n *

To use these credentials, the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable\n * must be set to '1'. This is for security reasons.\n *\n *

Both OIDC and SAML are supported. The executable must adhere to a specific response format\n * defined below.\n *\n *

The executable must print out the 3rd party token to STDOUT in JSON format. When an\n * output_file is specified in the credential configuration, the executable must also handle writing the\n * JSON response to this file.\n *\n *

\n * OIDC response sample:\n * {\n *   \"version\": 1,\n *   \"success\": true,\n *   \"token_type\": \"urn:ietf:params:oauth:token-type:id_token\",\n *   \"id_token\": \"HEADER.PAYLOAD.SIGNATURE\",\n *   \"expiration_time\": 1620433341\n * }\n *\n * SAML2 response sample:\n * {\n *   \"version\": 1,\n *   \"success\": true,\n *   \"token_type\": \"urn:ietf:params:oauth:token-type:saml2\",\n *   \"saml_response\": \"...\",\n *   \"expiration_time\": 1620433341\n * }\n *\n * Error response sample:\n * {\n *   \"version\": 1,\n *   \"success\": false,\n *   \"code\": \"401\",\n *   \"message\": \"Error message.\"\n * }\n * 
\n *\n *

The \"expiration_time\" field in the JSON response is only required for successful\n * responses when an output file was specified in the credential configuration\n *\n *

The auth libraries will populate certain environment variables that will be accessible by the\n * executable, such as: GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE, GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE,\n * GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE, GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL, and\n * GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE.\n *\n *

Please see this repositories README for a complete executable request/response specification.\n */\nclass PluggableAuthClient extends baseexternalclient_1.BaseExternalAccountClient {\n /**\n * The command used to retrieve the third party token.\n */\n command;\n /**\n * The timeout in milliseconds for running executable,\n * set to default if none provided.\n */\n timeoutMillis;\n /**\n * The path to file to check for cached executable response.\n */\n outputFile;\n /**\n * Executable and output file handler.\n */\n handler;\n /**\n * Instantiates a PluggableAuthClient instance using the provided JSON\n * object loaded from an external account credentials file.\n * An error is thrown if the credential is not a valid pluggable auth credential.\n * @param options The external account options object typically loaded from\n * the external account JSON credential file.\n */\n constructor(options) {\n super(options);\n if (!options.credential_source.executable) {\n throw new Error('No valid Pluggable Auth \"credential_source\" provided.');\n }\n this.command = options.credential_source.executable.command;\n if (!this.command) {\n throw new Error('No valid Pluggable Auth \"credential_source\" provided.');\n }\n // Check if the provided timeout exists and if it is valid.\n if (options.credential_source.executable.timeout_millis === undefined) {\n this.timeoutMillis = DEFAULT_EXECUTABLE_TIMEOUT_MILLIS;\n }\n else {\n this.timeoutMillis = options.credential_source.executable.timeout_millis;\n if (this.timeoutMillis < MINIMUM_EXECUTABLE_TIMEOUT_MILLIS ||\n this.timeoutMillis > MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS) {\n throw new Error(`Timeout must be between ${MINIMUM_EXECUTABLE_TIMEOUT_MILLIS} and ` +\n `${MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS} milliseconds.`);\n }\n }\n this.outputFile = options.credential_source.executable.output_file;\n this.handler = new pluggable_auth_handler_1.PluggableAuthHandler({\n command: this.command,\n timeoutMillis: this.timeoutMillis,\n outputFile: this.outputFile,\n });\n this.credentialSourceType = 'executable';\n }\n /**\n * Triggered when an external subject token is needed to be exchanged for a\n * GCP access token via GCP STS endpoint.\n * This uses the `options.credential_source` object to figure out how\n * to retrieve the token using the current environment. In this case,\n * this calls a user provided executable which returns the subject token.\n * The logic is summarized as:\n * 1. Validated that the executable is allowed to run. The\n * GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment must be set to\n * 1 for security reasons.\n * 2. If an output file is specified by the user, check the file location\n * for a response. If the file exists and contains a valid response,\n * return the subject token from the file.\n * 3. Call the provided executable and return response.\n * @return A promise that resolves with the external subject token.\n */\n async retrieveSubjectToken() {\n // Check if the executable is allowed to run.\n if (process.env[GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES] !== '1') {\n throw new Error('Pluggable Auth executables need to be explicitly allowed to run by ' +\n 'setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment ' +\n 'Variable to 1.');\n }\n let executableResponse = undefined;\n // Try to get cached executable response from output file.\n if (this.outputFile) {\n executableResponse = await this.handler.retrieveCachedResponse();\n }\n // If no response from output file, call the executable.\n if (!executableResponse) {\n // Set up environment map with required values for the executable.\n const envMap = new Map();\n envMap.set('GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE', this.audience);\n envMap.set('GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE', this.subjectTokenType);\n // Always set to 0 because interactive mode is not supported.\n envMap.set('GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE', '0');\n if (this.outputFile) {\n envMap.set('GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE', this.outputFile);\n }\n const serviceAccountEmail = this.getServiceAccountEmail();\n if (serviceAccountEmail) {\n envMap.set('GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL', serviceAccountEmail);\n }\n executableResponse =\n await this.handler.retrieveResponseFromExecutable(envMap);\n }\n if (executableResponse.version > MAXIMUM_EXECUTABLE_VERSION) {\n throw new Error(`Version of executable is not currently supported, maximum supported version is ${MAXIMUM_EXECUTABLE_VERSION}.`);\n }\n // Check that response was successful.\n if (!executableResponse.success) {\n throw new pluggable_auth_handler_1.ExecutableError(executableResponse.errorMessage, executableResponse.errorCode);\n }\n // Check that response contains expiration time if output file was specified.\n if (this.outputFile) {\n if (!executableResponse.expirationTime) {\n throw new executable_response_1.InvalidExpirationTimeFieldError('The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.');\n }\n }\n // Check that response is not expired.\n if (executableResponse.isExpired()) {\n throw new Error('Executable response is expired.');\n }\n // Return subject token from response.\n return executableResponse.subjectToken;\n }\n}\nexports.PluggableAuthClient = PluggableAuthClient;\n//# sourceMappingURL=pluggable-auth-client.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ExternalAccountClient = void 0;\nconst baseexternalclient_1 = require(\"./baseexternalclient\");\nconst identitypoolclient_1 = require(\"./identitypoolclient\");\nconst awsclient_1 = require(\"./awsclient\");\nconst pluggable_auth_client_1 = require(\"./pluggable-auth-client\");\n/**\n * Dummy class with no constructor. Developers are expected to use fromJSON.\n */\nclass ExternalAccountClient {\n constructor() {\n throw new Error('ExternalAccountClients should be initialized via: ' +\n 'ExternalAccountClient.fromJSON(), ' +\n 'directly via explicit constructors, eg. ' +\n 'new AwsClient(options), new IdentityPoolClient(options), new' +\n 'PluggableAuthClientOptions, or via ' +\n 'new GoogleAuth(options).getClient()');\n }\n /**\n * This static method will instantiate the\n * corresponding type of external account credential depending on the\n * underlying credential source.\n * @param options The external account options object typically loaded\n * from the external account JSON credential file.\n * @return A BaseExternalAccountClient instance or null if the options\n * provided do not correspond to an external account credential.\n */\n static fromJSON(options) {\n if (options && options.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {\n if (options.credential_source?.environment_id) {\n return new awsclient_1.AwsClient(options);\n }\n else if (options.credential_source?.executable) {\n return new pluggable_auth_client_1.PluggableAuthClient(options);\n }\n else {\n return new identitypoolclient_1.IdentityPoolClient(options);\n }\n }\n else {\n return null;\n }\n }\n}\nexports.ExternalAccountClient = ExternalAccountClient;\n//# sourceMappingURL=externalclient.js.map", "\"use strict\";\n// Copyright 2023 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ExternalAccountAuthorizedUserClient = exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = void 0;\nconst authclient_1 = require(\"./authclient\");\nconst oauth2common_1 = require(\"./oauth2common\");\nconst gaxios_1 = require(\"gaxios\");\nconst stream = require(\"stream\");\nconst baseexternalclient_1 = require(\"./baseexternalclient\");\n/**\n * The credentials JSON file type for external account authorized user clients.\n */\nexports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = 'external_account_authorized_user';\nconst DEFAULT_TOKEN_URL = 'https://sts.{universeDomain}/v1/oauthtoken';\n/**\n * Handler for token refresh requests sent to the token_url endpoint for external\n * authorized user credentials.\n */\nclass ExternalAccountAuthorizedUserHandler extends oauth2common_1.OAuthClientAuthHandler {\n #tokenRefreshEndpoint;\n /**\n * Initializes an ExternalAccountAuthorizedUserHandler instance.\n * @param url The URL of the token refresh endpoint.\n * @param transporter The transporter to use for the refresh request.\n * @param clientAuthentication The client authentication credentials to use\n * for the refresh request.\n */\n constructor(options) {\n super(options);\n this.#tokenRefreshEndpoint = options.tokenRefreshEndpoint;\n }\n /**\n * Requests a new access token from the token_url endpoint using the provided\n * refresh token.\n * @param refreshToken The refresh token to use to generate a new access token.\n * @param additionalHeaders Optional additional headers to pass along the\n * request.\n * @return A promise that resolves with the token refresh response containing\n * the requested access token and its expiration time.\n */\n async refreshToken(refreshToken, headers) {\n const opts = {\n ...ExternalAccountAuthorizedUserHandler.RETRY_CONFIG,\n url: this.#tokenRefreshEndpoint,\n method: 'POST',\n headers,\n data: new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n }),\n };\n authclient_1.AuthClient.setMethodName(opts, 'refreshToken');\n // Apply OAuth client authentication.\n this.applyClientAuthenticationOptions(opts);\n try {\n const response = await this.transporter.request(opts);\n // Successful response.\n const tokenRefreshResponse = response.data;\n tokenRefreshResponse.res = response;\n return tokenRefreshResponse;\n }\n catch (error) {\n // Translate error to OAuthError.\n if (error instanceof gaxios_1.GaxiosError && error.response) {\n throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, \n // Preserve other fields from the original error.\n error);\n }\n // Request could fail before the server responds.\n throw error;\n }\n }\n}\n/**\n * External Account Authorized User Client. This is used for OAuth2 credentials\n * sourced using external identities through Workforce Identity Federation.\n * Obtaining the initial access and refresh token can be done through the\n * Google Cloud CLI.\n */\nclass ExternalAccountAuthorizedUserClient extends authclient_1.AuthClient {\n cachedAccessToken;\n externalAccountAuthorizedUserHandler;\n refreshToken;\n /**\n * Instantiates an ExternalAccountAuthorizedUserClient instances using the\n * provided JSON object loaded from a credentials files.\n * An error is throws if the credential is not valid.\n * @param options The external account authorized user option object typically\n * from the external accoutn authorized user JSON credential file.\n */\n constructor(options) {\n super(options);\n if (options.universe_domain) {\n this.universeDomain = options.universe_domain;\n }\n this.refreshToken = options.refresh_token;\n const clientAuthentication = {\n confidentialClientType: 'basic',\n clientId: options.client_id,\n clientSecret: options.client_secret,\n };\n this.externalAccountAuthorizedUserHandler =\n new ExternalAccountAuthorizedUserHandler({\n tokenRefreshEndpoint: options.token_url ??\n DEFAULT_TOKEN_URL.replace('{universeDomain}', this.universeDomain),\n transporter: this.transporter,\n clientAuthentication,\n });\n this.cachedAccessToken = null;\n this.quotaProjectId = options.quota_project_id;\n // As threshold could be zero,\n // eagerRefreshThresholdMillis || EXPIRATION_TIME_OFFSET will override the\n // zero value.\n if (typeof options?.eagerRefreshThresholdMillis !== 'number') {\n this.eagerRefreshThresholdMillis = baseexternalclient_1.EXPIRATION_TIME_OFFSET;\n }\n else {\n this.eagerRefreshThresholdMillis = options\n .eagerRefreshThresholdMillis;\n }\n this.forceRefreshOnFailure = !!options?.forceRefreshOnFailure;\n }\n async getAccessToken() {\n // If cached access token is unavailable or expired, force refresh.\n if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) {\n await this.refreshAccessTokenAsync();\n }\n // Return GCP access token in GetAccessTokenResponse format.\n return {\n token: this.cachedAccessToken.access_token,\n res: this.cachedAccessToken.res,\n };\n }\n async getRequestHeaders() {\n const accessTokenResponse = await this.getAccessToken();\n const headers = new Headers({\n authorization: `Bearer ${accessTokenResponse.token}`,\n });\n return this.addSharedMetadataHeaders(headers);\n }\n request(opts, callback) {\n if (callback) {\n this.requestAsync(opts).then(r => callback(null, r), e => {\n return callback(e, e.response);\n });\n }\n else {\n return this.requestAsync(opts);\n }\n }\n /**\n * Authenticates the provided HTTP request, processes it and resolves with the\n * returned response.\n * @param opts The HTTP request options.\n * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure.\n * @return A promise that resolves with the successful response.\n */\n async requestAsync(opts, reAuthRetried = false) {\n let response;\n try {\n const requestHeaders = await this.getRequestHeaders();\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);\n this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders);\n response = await this.transporter.request(opts);\n }\n catch (e) {\n const res = e.response;\n if (res) {\n const statusCode = res.status;\n // Retry the request for metadata if the following criteria are true:\n // - We haven't already retried. It only makes sense to retry once.\n // - The response was a 401 or a 403\n // - The request didn't send a readableStream\n // - forceRefreshOnFailure is true\n const isReadableStream = res.config.data instanceof stream.Readable;\n const isAuthErr = statusCode === 401 || statusCode === 403;\n if (!reAuthRetried &&\n isAuthErr &&\n !isReadableStream &&\n this.forceRefreshOnFailure) {\n await this.refreshAccessTokenAsync();\n return await this.requestAsync(opts, true);\n }\n }\n throw e;\n }\n return response;\n }\n /**\n * Forces token refresh, even if unexpired tokens are currently cached.\n * @return A promise that resolves with the refreshed credential.\n */\n async refreshAccessTokenAsync() {\n // Refresh the access token using the refresh token.\n const refreshResponse = await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);\n this.cachedAccessToken = {\n access_token: refreshResponse.access_token,\n expiry_date: new Date().getTime() + refreshResponse.expires_in * 1000,\n res: refreshResponse.res,\n };\n if (refreshResponse.refresh_token !== undefined) {\n this.refreshToken = refreshResponse.refresh_token;\n }\n return this.cachedAccessToken;\n }\n /**\n * Returns whether the provided credentials are expired or not.\n * If there is no expiry time, assumes the token is not expired or expiring.\n * @param credentials The credentials to check for expiration.\n * @return Whether the credentials are expired or not.\n */\n isExpired(credentials) {\n const now = new Date().getTime();\n return credentials.expiry_date\n ? now >= credentials.expiry_date - this.eagerRefreshThresholdMillis\n : false;\n }\n}\nexports.ExternalAccountAuthorizedUserClient = ExternalAccountAuthorizedUserClient;\n//# sourceMappingURL=externalAccountAuthorizedUserClient.js.map", "\"use strict\";\n// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.GoogleAuth = exports.GoogleAuthExceptionMessages = void 0;\nconst child_process_1 = require(\"child_process\");\nconst fs = require(\"fs\");\nconst gaxios_1 = require(\"gaxios\");\nconst gcpMetadata = require(\"gcp-metadata\");\nconst os = require(\"os\");\nconst path = require(\"path\");\nconst crypto_1 = require(\"../crypto/crypto\");\nconst computeclient_1 = require(\"./computeclient\");\nconst idtokenclient_1 = require(\"./idtokenclient\");\nconst envDetect_1 = require(\"./envDetect\");\nconst jwtclient_1 = require(\"./jwtclient\");\nconst refreshclient_1 = require(\"./refreshclient\");\nconst impersonated_1 = require(\"./impersonated\");\nconst externalclient_1 = require(\"./externalclient\");\nconst baseexternalclient_1 = require(\"./baseexternalclient\");\nconst authclient_1 = require(\"./authclient\");\nconst externalAccountAuthorizedUserClient_1 = require(\"./externalAccountAuthorizedUserClient\");\nconst util_1 = require(\"../util\");\nexports.GoogleAuthExceptionMessages = {\n API_KEY_WITH_CREDENTIALS: 'API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.',\n NO_PROJECT_ID_FOUND: 'Unable to detect a Project Id in the current environment. \\n' +\n 'To learn more about authentication and Google APIs, visit: \\n' +\n 'https://cloud.google.com/docs/authentication/getting-started',\n NO_CREDENTIALS_FOUND: 'Unable to find credentials in current environment. \\n' +\n 'To learn more about authentication and Google APIs, visit: \\n' +\n 'https://cloud.google.com/docs/authentication/getting-started',\n NO_ADC_FOUND: 'Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.',\n NO_UNIVERSE_DOMAIN_FOUND: 'Unable to detect a Universe Domain in the current environment.\\n' +\n 'To learn more about Universe Domain retrieval, visit: \\n' +\n 'https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys',\n};\nclass GoogleAuth {\n /**\n * Caches a value indicating whether the auth layer is running on Google\n * Compute Engine.\n * @private\n */\n checkIsGCE = undefined;\n useJWTAccessWithScope;\n defaultServicePath;\n // Note: this properly is only public to satisfy unit tests.\n // https://github.com/Microsoft/TypeScript/issues/5228\n get isGCE() {\n return this.checkIsGCE;\n }\n _findProjectIdPromise;\n _cachedProjectId;\n // To save the contents of the JSON credential file\n jsonContent = null;\n apiKey;\n cachedCredential = null;\n /**\n * A pending {@link AuthClient}. Used for concurrent {@link GoogleAuth.getClient} calls.\n */\n #pendingAuthClient = null;\n /**\n * Scopes populated by the client library by default. We differentiate between\n * these and user defined scopes when deciding whether to use a self-signed JWT.\n */\n defaultScopes;\n keyFilename;\n scopes;\n clientOptions = {};\n /**\n * Configuration is resolved in the following order of precedence:\n * - {@link GoogleAuthOptions.credentials `credentials`}\n * - {@link GoogleAuthOptions.keyFilename `keyFilename`}\n * - {@link GoogleAuthOptions.keyFile `keyFile`}\n *\n * {@link GoogleAuthOptions.clientOptions `clientOptions`} are passed to the\n * {@link AuthClient `AuthClient`s}.\n *\n * @param opts\n */\n constructor(opts = {}) {\n this._cachedProjectId = opts.projectId || null;\n this.cachedCredential = opts.authClient || null;\n this.keyFilename = opts.keyFilename || opts.keyFile;\n this.scopes = opts.scopes;\n this.clientOptions = opts.clientOptions || {};\n this.jsonContent = opts.credentials || null;\n this.apiKey = opts.apiKey || this.clientOptions.apiKey || null;\n // Cannot use both API Key + Credentials\n if (this.apiKey && (this.jsonContent || this.clientOptions.credentials)) {\n throw new RangeError(exports.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);\n }\n if (opts.universeDomain) {\n this.clientOptions.universeDomain = opts.universeDomain;\n }\n }\n // GAPIC client libraries should always use self-signed JWTs. The following\n // variables are set on the JWT client in order to indicate the type of library,\n // and sign the JWT with the correct audience and scopes (if not supplied).\n setGapicJWTValues(client) {\n client.defaultServicePath = this.defaultServicePath;\n client.useJWTAccessWithScope = this.useJWTAccessWithScope;\n client.defaultScopes = this.defaultScopes;\n }\n getProjectId(callback) {\n if (callback) {\n this.getProjectIdAsync().then(r => callback(null, r), callback);\n }\n else {\n return this.getProjectIdAsync();\n }\n }\n /**\n * A temporary method for internal `getProjectId` usages where `null` is\n * acceptable. In a future major release, `getProjectId` should return `null`\n * (as the `Promise` base signature describes) and this private\n * method should be removed.\n *\n * @returns Promise that resolves with project id (or `null`)\n */\n async getProjectIdOptional() {\n try {\n return await this.getProjectId();\n }\n catch (e) {\n if (e instanceof Error &&\n e.message === exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND) {\n return null;\n }\n else {\n throw e;\n }\n }\n }\n /**\n * A private method for finding and caching a projectId.\n *\n * Supports environments in order of precedence:\n * - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable\n * - GOOGLE_APPLICATION_CREDENTIALS JSON file\n * - Cloud SDK: `gcloud config config-helper --format json`\n * - GCE project ID from metadata server\n *\n * @returns projectId\n */\n async findAndCacheProjectId() {\n let projectId = null;\n projectId ||= await this.getProductionProjectId();\n projectId ||= await this.getFileProjectId();\n projectId ||= await this.getDefaultServiceProjectId();\n projectId ||= await this.getGCEProjectId();\n projectId ||= await this.getExternalAccountClientProjectId();\n if (projectId) {\n this._cachedProjectId = projectId;\n return projectId;\n }\n else {\n throw new Error(exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND);\n }\n }\n async getProjectIdAsync() {\n if (this._cachedProjectId) {\n return this._cachedProjectId;\n }\n if (!this._findProjectIdPromise) {\n this._findProjectIdPromise = this.findAndCacheProjectId();\n }\n return this._findProjectIdPromise;\n }\n /**\n * Retrieves a universe domain from the metadata server via\n * {@link gcpMetadata.universe}.\n *\n * @returns a universe domain\n */\n async getUniverseDomainFromMetadataServer() {\n let universeDomain;\n try {\n universeDomain = await gcpMetadata.universe('universe-domain');\n universeDomain ||= authclient_1.DEFAULT_UNIVERSE;\n }\n catch (e) {\n if (e && e?.response?.status === 404) {\n universeDomain = authclient_1.DEFAULT_UNIVERSE;\n }\n else {\n throw e;\n }\n }\n return universeDomain;\n }\n /**\n * Retrieves, caches, and returns the universe domain in the following order\n * of precedence:\n * - The universe domain in {@link GoogleAuth.clientOptions}\n * - An existing or ADC {@link AuthClient}'s universe domain\n * - {@link gcpMetadata.universe}, if {@link Compute} client\n *\n * @returns The universe domain\n */\n async getUniverseDomain() {\n let universeDomain = (0, util_1.originalOrCamelOptions)(this.clientOptions).get('universe_domain');\n try {\n universeDomain ??= (await this.getClient()).universeDomain;\n }\n catch {\n // client or ADC is not available\n universeDomain ??= authclient_1.DEFAULT_UNIVERSE;\n }\n return universeDomain;\n }\n /**\n * @returns Any scopes (user-specified or default scopes specified by the\n * client library) that need to be set on the current Auth client.\n */\n getAnyScopes() {\n return this.scopes || this.defaultScopes;\n }\n getApplicationDefault(optionsOrCallback = {}, callback) {\n let options;\n if (typeof optionsOrCallback === 'function') {\n callback = optionsOrCallback;\n }\n else {\n options = optionsOrCallback;\n }\n if (callback) {\n this.getApplicationDefaultAsync(options).then(r => callback(null, r.credential, r.projectId), callback);\n }\n else {\n return this.getApplicationDefaultAsync(options);\n }\n }\n async getApplicationDefaultAsync(options = {}) {\n // If we've already got a cached credential, return it.\n // This will also preserve one's configured quota project, in case they\n // set one directly on the credential previously.\n if (this.cachedCredential) {\n // cache, while preserving existing quota project preferences\n return await this.#prepareAndCacheClient(this.cachedCredential, null);\n }\n let credential;\n // Check for the existence of a local environment variable pointing to the\n // location of the credential file. This is typically used in local\n // developer scenarios.\n credential =\n await this._tryGetApplicationCredentialsFromEnvironmentVariable(options);\n if (credential) {\n if (credential instanceof jwtclient_1.JWT) {\n credential.scopes = this.scopes;\n }\n else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) {\n credential.scopes = this.getAnyScopes();\n }\n return await this.#prepareAndCacheClient(credential);\n }\n // Look in the well-known credential file location.\n credential =\n await this._tryGetApplicationCredentialsFromWellKnownFile(options);\n if (credential) {\n if (credential instanceof jwtclient_1.JWT) {\n credential.scopes = this.scopes;\n }\n else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) {\n credential.scopes = this.getAnyScopes();\n }\n return await this.#prepareAndCacheClient(credential);\n }\n // Determine if we're running on GCE.\n if (await this._checkIsGCE()) {\n options.scopes = this.getAnyScopes();\n return await this.#prepareAndCacheClient(new computeclient_1.Compute(options));\n }\n throw new Error(exports.GoogleAuthExceptionMessages.NO_ADC_FOUND);\n }\n async #prepareAndCacheClient(credential, quotaProjectIdOverride = process.env['GOOGLE_CLOUD_QUOTA_PROJECT'] || null) {\n const projectId = await this.getProjectIdOptional();\n if (quotaProjectIdOverride) {\n credential.quotaProjectId = quotaProjectIdOverride;\n }\n this.cachedCredential = credential;\n return { credential, projectId };\n }\n /**\n * Determines whether the auth layer is running on Google Compute Engine.\n * Checks for GCP Residency, then fallback to checking if metadata server\n * is available.\n *\n * @returns A promise that resolves with the boolean.\n * @api private\n */\n async _checkIsGCE() {\n if (this.checkIsGCE === undefined) {\n this.checkIsGCE =\n gcpMetadata.getGCPResidency() || (await gcpMetadata.isAvailable());\n }\n return this.checkIsGCE;\n }\n /**\n * Attempts to load default credentials from the environment variable path..\n * @returns Promise that resolves with the OAuth2Client or null.\n * @api private\n */\n async _tryGetApplicationCredentialsFromEnvironmentVariable(options) {\n const credentialsPath = process.env['GOOGLE_APPLICATION_CREDENTIALS'] ||\n process.env['google_application_credentials'];\n if (!credentialsPath || credentialsPath.length === 0) {\n return null;\n }\n try {\n return this._getApplicationCredentialsFromFilePath(credentialsPath, options);\n }\n catch (e) {\n if (e instanceof Error) {\n e.message = `Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e.message}`;\n }\n throw e;\n }\n }\n /**\n * Attempts to load default credentials from a well-known file location\n * @return Promise that resolves with the OAuth2Client or null.\n * @api private\n */\n async _tryGetApplicationCredentialsFromWellKnownFile(options) {\n // First, figure out the location of the file, depending upon the OS type.\n let location = null;\n if (this._isWindows()) {\n // Windows\n location = process.env['APPDATA'];\n }\n else {\n // Linux or Mac\n const home = process.env['HOME'];\n if (home) {\n location = path.join(home, '.config');\n }\n }\n // If we found the root path, expand it.\n if (location) {\n location = path.join(location, 'gcloud', 'application_default_credentials.json');\n if (!fs.existsSync(location)) {\n location = null;\n }\n }\n // The file does not exist.\n if (!location) {\n return null;\n }\n // The file seems to exist. Try to use it.\n const client = await this._getApplicationCredentialsFromFilePath(location, options);\n return client;\n }\n /**\n * Attempts to load default credentials from a file at the given path..\n * @param filePath The path to the file to read.\n * @returns Promise that resolves with the OAuth2Client\n * @api private\n */\n async _getApplicationCredentialsFromFilePath(filePath, options = {}) {\n // Make sure the path looks like a string.\n if (!filePath || filePath.length === 0) {\n throw new Error('The file path is invalid.');\n }\n // Make sure there is a file at the path. lstatSync will throw if there is\n // nothing there.\n try {\n // Resolve path to actual file in case of symlink. Expect a thrown error\n // if not resolvable.\n filePath = fs.realpathSync(filePath);\n if (!fs.lstatSync(filePath).isFile()) {\n throw new Error();\n }\n }\n catch (err) {\n if (err instanceof Error) {\n err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`;\n }\n throw err;\n }\n // Now open a read stream on the file, and parse it.\n const readStream = fs.createReadStream(filePath);\n return this.fromStream(readStream, options);\n }\n /**\n * Create a credentials instance using a given impersonated input options.\n * @param json The impersonated input object.\n * @returns JWT or UserRefresh Client with data\n */\n fromImpersonatedJSON(json) {\n if (!json) {\n throw new Error('Must pass in a JSON object containing an impersonated refresh token');\n }\n if (json.type !== impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {\n throw new Error(`The incoming JSON object does not have the \"${impersonated_1.IMPERSONATED_ACCOUNT_TYPE}\" type`);\n }\n if (!json.source_credentials) {\n throw new Error('The incoming JSON object does not contain a source_credentials field');\n }\n if (!json.service_account_impersonation_url) {\n throw new Error('The incoming JSON object does not contain a service_account_impersonation_url field');\n }\n const sourceClient = this.fromJSON(json.source_credentials);\n if (json.service_account_impersonation_url?.length > 256) {\n /**\n * Prevents DOS attacks.\n * @see {@link https://github.com/googleapis/google-auth-library-nodejs/security/code-scanning/85}\n **/\n throw new RangeError(`Target principal is too long: ${json.service_account_impersonation_url}`);\n }\n // Extract service account from service_account_impersonation_url\n const targetPrincipal = /(?[^/]+):(generateAccessToken|generateIdToken)$/.exec(json.service_account_impersonation_url)?.groups?.target;\n if (!targetPrincipal) {\n throw new RangeError(`Cannot extract target principal from ${json.service_account_impersonation_url}`);\n }\n const targetScopes = this.getAnyScopes() ?? [];\n return new impersonated_1.Impersonated({\n ...json,\n sourceClient,\n targetPrincipal,\n targetScopes: Array.isArray(targetScopes) ? targetScopes : [targetScopes],\n });\n }\n /**\n * Create a credentials instance using the given input options.\n * This client is not cached.\n *\n * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}.\n *\n * @param json The input object.\n * @param options The JWT or UserRefresh options for the client\n * @returns JWT or UserRefresh Client with data\n */\n fromJSON(json, options = {}) {\n let client;\n // user's preferred universe domain\n const preferredUniverseDomain = (0, util_1.originalOrCamelOptions)(options).get('universe_domain');\n if (json.type === refreshclient_1.USER_REFRESH_ACCOUNT_TYPE) {\n client = new refreshclient_1.UserRefreshClient(options);\n client.fromJSON(json);\n }\n else if (json.type === impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {\n client = this.fromImpersonatedJSON(json);\n }\n else if (json.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {\n client = externalclient_1.ExternalAccountClient.fromJSON({\n ...json,\n ...options,\n });\n client.scopes = this.getAnyScopes();\n }\n else if (json.type === externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE) {\n client = new externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient({\n ...json,\n ...options,\n });\n }\n else {\n options.scopes = this.scopes;\n client = new jwtclient_1.JWT(options);\n this.setGapicJWTValues(client);\n client.fromJSON(json);\n }\n if (preferredUniverseDomain) {\n client.universeDomain = preferredUniverseDomain;\n }\n return client;\n }\n /**\n * Return a JWT or UserRefreshClient from JavaScript object, caching both the\n * object used to instantiate and the client.\n * @param json The input object.\n * @param options The JWT or UserRefresh options for the client\n * @returns JWT or UserRefresh Client with data\n */\n _cacheClientFromJSON(json, options) {\n const client = this.fromJSON(json, options);\n // cache both raw data used to instantiate client and client itself.\n this.jsonContent = json;\n this.cachedCredential = client;\n return client;\n }\n fromStream(inputStream, optionsOrCallback = {}, callback) {\n let options = {};\n if (typeof optionsOrCallback === 'function') {\n callback = optionsOrCallback;\n }\n else {\n options = optionsOrCallback;\n }\n if (callback) {\n this.fromStreamAsync(inputStream, options).then(r => callback(null, r), callback);\n }\n else {\n return this.fromStreamAsync(inputStream, options);\n }\n }\n fromStreamAsync(inputStream, options) {\n return new Promise((resolve, reject) => {\n if (!inputStream) {\n throw new Error('Must pass in a stream containing the Google auth settings.');\n }\n const chunks = [];\n inputStream\n .setEncoding('utf8')\n .on('error', reject)\n .on('data', chunk => chunks.push(chunk))\n .on('end', () => {\n try {\n try {\n const data = JSON.parse(chunks.join(''));\n const r = this._cacheClientFromJSON(data, options);\n return resolve(r);\n }\n catch (err) {\n // If we failed parsing this.keyFileName, assume that it\n // is a PEM or p12 certificate:\n if (!this.keyFilename)\n throw err;\n const client = new jwtclient_1.JWT({\n ...this.clientOptions,\n keyFile: this.keyFilename,\n });\n this.cachedCredential = client;\n this.setGapicJWTValues(client);\n return resolve(client);\n }\n }\n catch (err) {\n return reject(err);\n }\n });\n });\n }\n /**\n * Create a credentials instance using the given API key string.\n * The created client is not cached. In order to create and cache it use the {@link GoogleAuth.getClient `getClient`} method after first providing an {@link GoogleAuth.apiKey `apiKey`}.\n *\n * @param apiKey The API key string\n * @param options An optional options object.\n * @returns A JWT loaded from the key\n */\n fromAPIKey(apiKey, options = {}) {\n return new jwtclient_1.JWT({ ...options, apiKey });\n }\n /**\n * Determines whether the current operating system is Windows.\n * @api private\n */\n _isWindows() {\n const sys = os.platform();\n if (sys && sys.length >= 3) {\n if (sys.substring(0, 3).toLowerCase() === 'win') {\n return true;\n }\n }\n return false;\n }\n /**\n * Run the Google Cloud SDK command that prints the default project ID\n */\n async getDefaultServiceProjectId() {\n return new Promise(resolve => {\n (0, child_process_1.exec)('gcloud config config-helper --format json', (err, stdout) => {\n if (!err && stdout) {\n try {\n const projectId = JSON.parse(stdout).configuration.properties.core.project;\n resolve(projectId);\n return;\n }\n catch (e) {\n // ignore errors\n }\n }\n resolve(null);\n });\n });\n }\n /**\n * Loads the project id from environment variables.\n * @api private\n */\n getProductionProjectId() {\n return (process.env['GCLOUD_PROJECT'] ||\n process.env['GOOGLE_CLOUD_PROJECT'] ||\n process.env['gcloud_project'] ||\n process.env['google_cloud_project']);\n }\n /**\n * Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file.\n * @api private\n */\n async getFileProjectId() {\n if (this.cachedCredential) {\n // Try to read the project ID from the cached credentials file\n return this.cachedCredential.projectId;\n }\n // Ensure the projectId is loaded from the keyFile if available.\n if (this.keyFilename) {\n const creds = await this.getClient();\n if (creds && creds.projectId) {\n return creds.projectId;\n }\n }\n // Try to load a credentials file and read its project ID\n const r = await this._tryGetApplicationCredentialsFromEnvironmentVariable();\n if (r) {\n return r.projectId;\n }\n else {\n return null;\n }\n }\n /**\n * Gets the project ID from external account client if available.\n */\n async getExternalAccountClientProjectId() {\n if (!this.jsonContent || this.jsonContent.type !== baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {\n return null;\n }\n const creds = await this.getClient();\n // Do not suppress the underlying error, as the error could contain helpful\n // information for debugging and fixing. This is especially true for\n // external account creds as in order to get the project ID, the following\n // operations have to succeed:\n // 1. Valid credentials file should be supplied.\n // 2. Ability to retrieve access tokens from STS token exchange API.\n // 3. Ability to exchange for service account impersonated credentials (if\n // enabled).\n // 4. Ability to get project info using the access token from step 2 or 3.\n // Without surfacing the error, it is harder for developers to determine\n // which step went wrong.\n return await creds.getProjectId();\n }\n /**\n * Gets the Compute Engine project ID if it can be inferred.\n */\n async getGCEProjectId() {\n try {\n const r = await gcpMetadata.project('project-id');\n return r;\n }\n catch (e) {\n // Ignore any errors\n return null;\n }\n }\n getCredentials(callback) {\n if (callback) {\n this.getCredentialsAsync().then(r => callback(null, r), callback);\n }\n else {\n return this.getCredentialsAsync();\n }\n }\n async getCredentialsAsync() {\n const client = await this.getClient();\n if (client instanceof impersonated_1.Impersonated) {\n return { client_email: client.getTargetPrincipal() };\n }\n if (client instanceof baseexternalclient_1.BaseExternalAccountClient) {\n const serviceAccountEmail = client.getServiceAccountEmail();\n if (serviceAccountEmail) {\n return {\n client_email: serviceAccountEmail,\n universe_domain: client.universeDomain,\n };\n }\n }\n if (this.jsonContent) {\n return {\n client_email: this.jsonContent.client_email,\n private_key: this.jsonContent.private_key,\n universe_domain: this.jsonContent.universe_domain,\n };\n }\n if (await this._checkIsGCE()) {\n const [client_email, universe_domain] = await Promise.all([\n gcpMetadata.instance('service-accounts/default/email'),\n this.getUniverseDomain(),\n ]);\n return { client_email, universe_domain };\n }\n throw new Error(exports.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND);\n }\n /**\n * Automatically obtain an {@link AuthClient `AuthClient`} based on the\n * provided configuration. If no options were passed, use Application\n * Default Credentials.\n */\n async getClient() {\n if (this.cachedCredential) {\n return this.cachedCredential;\n }\n // Use an existing auth client request, or cache a new one\n this.#pendingAuthClient =\n this.#pendingAuthClient || this.#determineClient();\n try {\n return await this.#pendingAuthClient;\n }\n finally {\n // reset the pending auth client in case it is changed later\n this.#pendingAuthClient = null;\n }\n }\n async #determineClient() {\n if (this.jsonContent) {\n return this._cacheClientFromJSON(this.jsonContent, this.clientOptions);\n }\n else if (this.keyFilename) {\n const filePath = path.resolve(this.keyFilename);\n const stream = fs.createReadStream(filePath);\n return await this.fromStreamAsync(stream, this.clientOptions);\n }\n else if (this.apiKey) {\n const client = await this.fromAPIKey(this.apiKey, this.clientOptions);\n client.scopes = this.scopes;\n const { credential } = await this.#prepareAndCacheClient(client);\n return credential;\n }\n else {\n const { credential } = await this.getApplicationDefaultAsync(this.clientOptions);\n return credential;\n }\n }\n /**\n * Creates a client which will fetch an ID token for authorization.\n * @param targetAudience the audience for the fetched ID token.\n * @returns IdTokenClient for making HTTP calls authenticated with ID tokens.\n */\n async getIdTokenClient(targetAudience) {\n const client = await this.getClient();\n if (!('fetchIdToken' in client)) {\n throw new Error('Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.');\n }\n return new idtokenclient_1.IdTokenClient({ targetAudience, idTokenProvider: client });\n }\n /**\n * Automatically obtain application default credentials, and return\n * an access token for making requests.\n */\n async getAccessToken() {\n const client = await this.getClient();\n return (await client.getAccessToken()).token;\n }\n /**\n * Obtain the HTTP headers that will provide authorization for a given\n * request.\n */\n async getRequestHeaders(url) {\n const client = await this.getClient();\n return client.getRequestHeaders(url);\n }\n /**\n * Obtain credentials for a request, then attach the appropriate headers to\n * the request options.\n * @param opts Axios or Request options on which to attach the headers\n */\n async authorizeRequest(opts = {}) {\n const url = opts.url;\n const client = await this.getClient();\n const headers = await client.getRequestHeaders(url);\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers, headers);\n return opts;\n }\n /**\n * A {@link fetch `fetch`} compliant API for {@link GoogleAuth}.\n *\n * @see {@link GoogleAuth.request} for the classic method.\n *\n * @remarks\n *\n * This is useful as a drop-in replacement for `fetch` API usage.\n *\n * @example\n *\n * ```ts\n * const auth = new GoogleAuth();\n * const fetchWithAuth: typeof fetch = (...args) => auth.fetch(...args);\n * await fetchWithAuth('https://example.com');\n * ```\n *\n * @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters\n * @returns the {@link GaxiosResponse} with Gaxios-added properties\n */\n async fetch(...args) {\n const client = await this.getClient();\n return client.fetch(...args);\n }\n /**\n * Automatically obtain application default credentials, and make an\n * HTTP request using the given options.\n *\n * @see {@link GoogleAuth.fetch} for the modern method.\n *\n * @param opts Axios request options for the HTTP request.\n */\n async request(opts) {\n const client = await this.getClient();\n return client.request(opts);\n }\n /**\n * Determine the compute environment in which the code is running.\n */\n getEnv() {\n return (0, envDetect_1.getEnv)();\n }\n /**\n * Sign the given data with the current private key, or go out\n * to the IAM API to sign it.\n * @param data The data to be signed.\n * @param endpoint A custom endpoint to use.\n *\n * @example\n * ```\n * sign('data', 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/');\n * ```\n */\n async sign(data, endpoint) {\n const client = await this.getClient();\n const universe = await this.getUniverseDomain();\n endpoint =\n endpoint ||\n `https://iamcredentials.${universe}/v1/projects/-/serviceAccounts/`;\n if (client instanceof impersonated_1.Impersonated) {\n const signed = await client.sign(data);\n return signed.signedBlob;\n }\n const crypto = (0, crypto_1.createCrypto)();\n if (client instanceof jwtclient_1.JWT && client.key) {\n const sign = await crypto.sign(client.key, data);\n return sign;\n }\n const creds = await this.getCredentials();\n if (!creds.client_email) {\n throw new Error('Cannot sign data without `client_email`.');\n }\n return this.signBlob(crypto, creds.client_email, data, endpoint);\n }\n async signBlob(crypto, emailOrUniqueId, data, endpoint) {\n const url = new URL(endpoint + `${emailOrUniqueId}:signBlob`);\n const res = await this.request({\n method: 'POST',\n url: url.href,\n data: {\n payload: crypto.encodeBase64StringUtf8(data),\n },\n retry: true,\n retryConfig: {\n httpMethodsToRetry: ['POST'],\n },\n });\n return res.data.signedBlob;\n }\n}\nexports.GoogleAuth = GoogleAuth;\n//# sourceMappingURL=googleauth.js.map", "\"use strict\";\n// Copyright 2014 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.IAMAuth = void 0;\nclass IAMAuth {\n selector;\n token;\n /**\n * IAM credentials.\n *\n * @param selector the iam authority selector\n * @param token the token\n * @constructor\n */\n constructor(selector, token) {\n this.selector = selector;\n this.token = token;\n this.selector = selector;\n this.token = token;\n }\n /**\n * Acquire the HTTP headers required to make an authenticated request.\n */\n getRequestHeaders() {\n return {\n 'x-goog-iam-authority-selector': this.selector,\n 'x-goog-iam-authorization-token': this.token,\n };\n }\n}\nexports.IAMAuth = IAMAuth;\n//# sourceMappingURL=iam.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DownscopedClient = exports.EXPIRATION_TIME_OFFSET = exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = void 0;\nconst gaxios_1 = require(\"gaxios\");\nconst stream = require(\"stream\");\nconst authclient_1 = require(\"./authclient\");\nconst sts = require(\"./stscredentials\");\n/**\n * The required token exchange grant_type: rfc8693#section-2.1\n */\nconst STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange';\n/**\n * The requested token exchange requested_token_type: rfc8693#section-2.1\n */\nconst STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';\n/**\n * The requested token exchange subject_token_type: rfc8693#section-2.1\n */\nconst STS_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';\n/**\n * The maximum number of access boundary rules a Credential Access Boundary\n * can contain.\n */\nexports.MAX_ACCESS_BOUNDARY_RULES_COUNT = 10;\n/**\n * Offset to take into account network delays and server clock skews.\n */\nexports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000;\n/**\n * Defines a set of Google credentials that are downscoped from an existing set\n * of Google OAuth2 credentials. This is useful to restrict the Identity and\n * Access Management (IAM) permissions that a short-lived credential can use.\n * The common pattern of usage is to have a token broker with elevated access\n * generate these downscoped credentials from higher access source credentials\n * and pass the downscoped short-lived access tokens to a token consumer via\n * some secure authenticated channel for limited access to Google Cloud Storage\n * resources.\n */\nclass DownscopedClient extends authclient_1.AuthClient {\n authClient;\n credentialAccessBoundary;\n cachedDownscopedAccessToken;\n stsCredential;\n /**\n * Instantiates a downscoped client object using the provided source\n * AuthClient and credential access boundary rules.\n * To downscope permissions of a source AuthClient, a Credential Access\n * Boundary that specifies which resources the new credential can access, as\n * well as an upper bound on the permissions that are available on each\n * resource, has to be defined. A downscoped client can then be instantiated\n * using the source AuthClient and the Credential Access Boundary.\n * @param options the {@link DownscopedClientOptions `DownscopedClientOptions`} to use. Passing an `AuthClient` directly is **@DEPRECATED**.\n * @param credentialAccessBoundary **@DEPRECATED**. Provide a {@link DownscopedClientOptions `DownscopedClientOptions`} object in the first parameter instead.\n */\n constructor(\n /**\n * AuthClient is for backwards-compatibility.\n */\n options, \n /**\n * @deprecated - provide a {@link DownscopedClientOptions `DownscopedClientOptions`} object in the first parameter instead\n */\n credentialAccessBoundary = {\n accessBoundary: {\n accessBoundaryRules: [],\n },\n }) {\n super(options instanceof authclient_1.AuthClient ? {} : options);\n if (options instanceof authclient_1.AuthClient) {\n this.authClient = options;\n this.credentialAccessBoundary = credentialAccessBoundary;\n }\n else {\n this.authClient = options.authClient;\n this.credentialAccessBoundary = options.credentialAccessBoundary;\n }\n // Check 1-10 Access Boundary Rules are defined within Credential Access\n // Boundary.\n if (this.credentialAccessBoundary.accessBoundary.accessBoundaryRules\n .length === 0) {\n throw new Error('At least one access boundary rule needs to be defined.');\n }\n else if (this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length >\n exports.MAX_ACCESS_BOUNDARY_RULES_COUNT) {\n throw new Error('The provided access boundary has more than ' +\n `${exports.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);\n }\n // Check at least one permission should be defined in each Access Boundary\n // Rule.\n for (const rule of this.credentialAccessBoundary.accessBoundary\n .accessBoundaryRules) {\n if (rule.availablePermissions.length === 0) {\n throw new Error('At least one permission should be defined in access boundary rules.');\n }\n }\n this.stsCredential = new sts.StsCredentials({\n tokenExchangeEndpoint: `https://sts.${this.universeDomain}/v1/token`,\n });\n this.cachedDownscopedAccessToken = null;\n }\n /**\n * Provides a mechanism to inject Downscoped access tokens directly.\n * The expiry_date field is required to facilitate determination of the token\n * expiration which would make it easier for the token consumer to handle.\n * @param credentials The Credentials object to set on the current client.\n */\n setCredentials(credentials) {\n if (!credentials.expiry_date) {\n throw new Error('The access token expiry_date field is missing in the provided ' +\n 'credentials.');\n }\n super.setCredentials(credentials);\n this.cachedDownscopedAccessToken = credentials;\n }\n async getAccessToken() {\n // If the cached access token is unavailable or expired, force refresh.\n // The Downscoped access token will be returned in\n // DownscopedAccessTokenResponse format.\n if (!this.cachedDownscopedAccessToken ||\n this.isExpired(this.cachedDownscopedAccessToken)) {\n await this.refreshAccessTokenAsync();\n }\n // Return Downscoped access token in DownscopedAccessTokenResponse format.\n return {\n token: this.cachedDownscopedAccessToken.access_token,\n expirationTime: this.cachedDownscopedAccessToken.expiry_date,\n res: this.cachedDownscopedAccessToken.res,\n };\n }\n /**\n * The main authentication interface. It takes an optional url which when\n * present is the endpoint being accessed, and returns a Promise which\n * resolves with authorization header fields.\n *\n * The result has the form:\n * { authorization: 'Bearer ' }\n */\n async getRequestHeaders() {\n const accessTokenResponse = await this.getAccessToken();\n const headers = new Headers({\n authorization: `Bearer ${accessTokenResponse.token}`,\n });\n return this.addSharedMetadataHeaders(headers);\n }\n request(opts, callback) {\n if (callback) {\n this.requestAsync(opts).then(r => callback(null, r), e => {\n return callback(e, e.response);\n });\n }\n else {\n return this.requestAsync(opts);\n }\n }\n /**\n * Authenticates the provided HTTP request, processes it and resolves with the\n * returned response.\n * @param opts The HTTP request options.\n * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure\n * @return A promise that resolves with the successful response.\n */\n async requestAsync(opts, reAuthRetried = false) {\n let response;\n try {\n const requestHeaders = await this.getRequestHeaders();\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);\n this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders);\n response = await this.transporter.request(opts);\n }\n catch (e) {\n const res = e.response;\n if (res) {\n const statusCode = res.status;\n // Retry the request for metadata if the following criteria are true:\n // - We haven't already retried. It only makes sense to retry once.\n // - The response was a 401 or a 403\n // - The request didn't send a readableStream\n // - forceRefreshOnFailure is true\n const isReadableStream = res.config.data instanceof stream.Readable;\n const isAuthErr = statusCode === 401 || statusCode === 403;\n if (!reAuthRetried &&\n isAuthErr &&\n !isReadableStream &&\n this.forceRefreshOnFailure) {\n await this.refreshAccessTokenAsync();\n return await this.requestAsync(opts, true);\n }\n }\n throw e;\n }\n return response;\n }\n /**\n * Forces token refresh, even if unexpired tokens are currently cached.\n * GCP access tokens are retrieved from authclient object/source credential.\n * Then GCP access tokens are exchanged for downscoped access tokens via the\n * token exchange endpoint.\n * @return A promise that resolves with the fresh downscoped access token.\n */\n async refreshAccessTokenAsync() {\n // Retrieve GCP access token from source credential.\n const subjectToken = (await this.authClient.getAccessToken()).token;\n // Construct the STS credentials options.\n const stsCredentialsOptions = {\n grantType: STS_GRANT_TYPE,\n requestedTokenType: STS_REQUEST_TOKEN_TYPE,\n subjectToken: subjectToken,\n subjectTokenType: STS_SUBJECT_TOKEN_TYPE,\n };\n // Exchange the source AuthClient access token for a Downscoped access\n // token.\n const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, undefined, this.credentialAccessBoundary);\n /**\n * The STS endpoint will only return the expiration time for the downscoped\n * access token if the original access token represents a service account.\n * The downscoped token's expiration time will always match the source\n * credential expiration. When no expires_in is returned, we can copy the\n * source credential's expiration time.\n */\n const sourceCredExpireDate = this.authClient.credentials?.expiry_date || null;\n const expiryDate = stsResponse.expires_in\n ? new Date().getTime() + stsResponse.expires_in * 1000\n : sourceCredExpireDate;\n // Save response in cached access token.\n this.cachedDownscopedAccessToken = {\n access_token: stsResponse.access_token,\n expiry_date: expiryDate,\n res: stsResponse.res,\n };\n // Save credentials.\n this.credentials = {};\n Object.assign(this.credentials, this.cachedDownscopedAccessToken);\n delete this.credentials.res;\n // Trigger tokens event to notify external listeners.\n this.emit('tokens', {\n refresh_token: null,\n expiry_date: this.cachedDownscopedAccessToken.expiry_date,\n access_token: this.cachedDownscopedAccessToken.access_token,\n token_type: 'Bearer',\n id_token: null,\n });\n // Return the cached access token.\n return this.cachedDownscopedAccessToken;\n }\n /**\n * Returns whether the provided credentials are expired or not.\n * If there is no expiry time, assumes the token is not expired or expiring.\n * @param downscopedAccessToken The credentials to check for expiration.\n * @return Whether the credentials are expired or not.\n */\n isExpired(downscopedAccessToken) {\n const now = new Date().getTime();\n return downscopedAccessToken.expiry_date\n ? now >=\n downscopedAccessToken.expiry_date - this.eagerRefreshThresholdMillis\n : false;\n }\n}\nexports.DownscopedClient = DownscopedClient;\n//# sourceMappingURL=downscopedclient.js.map", "\"use strict\";\n// Copyright 2024 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PassThroughClient = void 0;\nconst authclient_1 = require(\"./authclient\");\n/**\n * An AuthClient without any Authentication information. Useful for:\n * - Anonymous access\n * - Local Emulators\n * - Testing Environments\n *\n */\nclass PassThroughClient extends authclient_1.AuthClient {\n /**\n * Creates a request without any authentication headers or checks.\n *\n * @remarks\n *\n * In testing environments it may be useful to change the provided\n * {@link AuthClient.transporter} for any desired request overrides/handling.\n *\n * @param opts\n * @returns The response of the request.\n */\n async request(opts) {\n return this.transporter.request(opts);\n }\n /**\n * A required method of the base class.\n * Always will return an empty object.\n *\n * @returns {}\n */\n async getAccessToken() {\n return {};\n }\n /**\n * A required method of the base class.\n * Always will return an empty object.\n *\n * @returns {}\n */\n async getRequestHeaders() {\n return new Headers();\n }\n}\nexports.PassThroughClient = PassThroughClient;\n//# sourceMappingURL=passthrough.js.map", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.GoogleAuth = exports.auth = exports.PassThroughClient = exports.ExecutableError = exports.PluggableAuthClient = exports.DownscopedClient = exports.BaseExternalAccountClient = exports.ExternalAccountClient = exports.IdentityPoolClient = exports.AwsRequestSigner = exports.AwsClient = exports.UserRefreshClient = exports.LoginTicket = exports.ClientAuthentication = exports.OAuth2Client = exports.CodeChallengeMethod = exports.Impersonated = exports.JWT = exports.JWTAccess = exports.IdTokenClient = exports.IAMAuth = exports.GCPEnv = exports.Compute = exports.DEFAULT_UNIVERSE = exports.AuthClient = exports.gaxios = exports.gcpMetadata = void 0;\n// Copyright 2017 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nconst googleauth_1 = require(\"./auth/googleauth\");\nObject.defineProperty(exports, \"GoogleAuth\", { enumerable: true, get: function () { return googleauth_1.GoogleAuth; } });\n// Export common deps to ensure types/instances are the exact match. Useful\n// for consistently configuring the library across versions.\nexports.gcpMetadata = require(\"gcp-metadata\");\nexports.gaxios = require(\"gaxios\");\nvar authclient_1 = require(\"./auth/authclient\");\nObject.defineProperty(exports, \"AuthClient\", { enumerable: true, get: function () { return authclient_1.AuthClient; } });\nObject.defineProperty(exports, \"DEFAULT_UNIVERSE\", { enumerable: true, get: function () { return authclient_1.DEFAULT_UNIVERSE; } });\nvar computeclient_1 = require(\"./auth/computeclient\");\nObject.defineProperty(exports, \"Compute\", { enumerable: true, get: function () { return computeclient_1.Compute; } });\nvar envDetect_1 = require(\"./auth/envDetect\");\nObject.defineProperty(exports, \"GCPEnv\", { enumerable: true, get: function () { return envDetect_1.GCPEnv; } });\nvar iam_1 = require(\"./auth/iam\");\nObject.defineProperty(exports, \"IAMAuth\", { enumerable: true, get: function () { return iam_1.IAMAuth; } });\nvar idtokenclient_1 = require(\"./auth/idtokenclient\");\nObject.defineProperty(exports, \"IdTokenClient\", { enumerable: true, get: function () { return idtokenclient_1.IdTokenClient; } });\nvar jwtaccess_1 = require(\"./auth/jwtaccess\");\nObject.defineProperty(exports, \"JWTAccess\", { enumerable: true, get: function () { return jwtaccess_1.JWTAccess; } });\nvar jwtclient_1 = require(\"./auth/jwtclient\");\nObject.defineProperty(exports, \"JWT\", { enumerable: true, get: function () { return jwtclient_1.JWT; } });\nvar impersonated_1 = require(\"./auth/impersonated\");\nObject.defineProperty(exports, \"Impersonated\", { enumerable: true, get: function () { return impersonated_1.Impersonated; } });\nvar oauth2client_1 = require(\"./auth/oauth2client\");\nObject.defineProperty(exports, \"CodeChallengeMethod\", { enumerable: true, get: function () { return oauth2client_1.CodeChallengeMethod; } });\nObject.defineProperty(exports, \"OAuth2Client\", { enumerable: true, get: function () { return oauth2client_1.OAuth2Client; } });\nObject.defineProperty(exports, \"ClientAuthentication\", { enumerable: true, get: function () { return oauth2client_1.ClientAuthentication; } });\nvar loginticket_1 = require(\"./auth/loginticket\");\nObject.defineProperty(exports, \"LoginTicket\", { enumerable: true, get: function () { return loginticket_1.LoginTicket; } });\nvar refreshclient_1 = require(\"./auth/refreshclient\");\nObject.defineProperty(exports, \"UserRefreshClient\", { enumerable: true, get: function () { return refreshclient_1.UserRefreshClient; } });\nvar awsclient_1 = require(\"./auth/awsclient\");\nObject.defineProperty(exports, \"AwsClient\", { enumerable: true, get: function () { return awsclient_1.AwsClient; } });\nvar awsrequestsigner_1 = require(\"./auth/awsrequestsigner\");\nObject.defineProperty(exports, \"AwsRequestSigner\", { enumerable: true, get: function () { return awsrequestsigner_1.AwsRequestSigner; } });\nvar identitypoolclient_1 = require(\"./auth/identitypoolclient\");\nObject.defineProperty(exports, \"IdentityPoolClient\", { enumerable: true, get: function () { return identitypoolclient_1.IdentityPoolClient; } });\nvar externalclient_1 = require(\"./auth/externalclient\");\nObject.defineProperty(exports, \"ExternalAccountClient\", { enumerable: true, get: function () { return externalclient_1.ExternalAccountClient; } });\nvar baseexternalclient_1 = require(\"./auth/baseexternalclient\");\nObject.defineProperty(exports, \"BaseExternalAccountClient\", { enumerable: true, get: function () { return baseexternalclient_1.BaseExternalAccountClient; } });\nvar downscopedclient_1 = require(\"./auth/downscopedclient\");\nObject.defineProperty(exports, \"DownscopedClient\", { enumerable: true, get: function () { return downscopedclient_1.DownscopedClient; } });\nvar pluggable_auth_client_1 = require(\"./auth/pluggable-auth-client\");\nObject.defineProperty(exports, \"PluggableAuthClient\", { enumerable: true, get: function () { return pluggable_auth_client_1.PluggableAuthClient; } });\nObject.defineProperty(exports, \"ExecutableError\", { enumerable: true, get: function () { return pluggable_auth_client_1.ExecutableError; } });\nvar passthrough_1 = require(\"./auth/passthrough\");\nObject.defineProperty(exports, \"PassThroughClient\", { enumerable: true, get: function () { return passthrough_1.PassThroughClient; } });\nconst auth = new googleauth_1.GoogleAuth();\nexports.auth = auth;\n//# sourceMappingURL=index.js.map", "import Fastify, {\n FastifyInstance,\n FastifyReply,\n FastifyRequest,\n FastifyPluginAsync,\n FastifyPluginCallback,\n FastifyPluginOptions,\n FastifyRegisterOptions,\n preHandlerHookHandler,\n onRequestHookHandler,\n preParsingHookHandler,\n preValidationHookHandler,\n preSerializationHookHandler,\n onSendHookHandler,\n onResponseHookHandler,\n onTimeoutHookHandler,\n onErrorHookHandler,\n onRouteHookHandler,\n onRegisterHookHandler,\n onReadyHookHandler,\n onListenHookHandler,\n onCloseHookHandler,\n FastifyBaseLogger,\n FastifyLoggerOptions,\n} from \"fastify\";\nimport cors from \"@fastify/cors\";\nimport { ConfigService, AppConfig } from \"./services/config\";\nimport { errorHandler } from \"./api/middleware\";\nimport { registerApiRoutes } from \"./api/routes\";\nimport { LLMService } from \"./services/llm\";\nimport { ProviderService } from \"./services/provider\";\nimport { TransformerService } from \"./services/transformer\";\nimport { PinoLoggerOptions } from \"fastify/types/logger\";\n\n// Extend FastifyRequest to include custom properties\ndeclare module \"fastify\" {\n interface FastifyRequest {\n provider?: string;\n }\n interface FastifyInstance {\n _server?: Server;\n }\n}\n\ninterface ServerOptions {\n initialConfig?: AppConfig;\n logger?: boolean | PinoLoggerOptions;\n}\n\n// Application factory\nfunction createApp(logger: boolean | PinoLoggerOptions): FastifyInstance {\n const fastify = Fastify({\n bodyLimit: 50 * 1024 * 1024,\n logger,\n });\n\n // Register error handler\n fastify.setErrorHandler(errorHandler);\n\n // Register CORS\n fastify.register(cors);\n return fastify;\n}\n\n// Server class\nclass Server {\n private app: FastifyInstance;\n configService: ConfigService;\n llmService: LLMService;\n providerService: ProviderService;\n transformerService: TransformerService;\n\n constructor(options: ServerOptions = {}) {\n this.app = createApp(options.logger ?? true);\n this.configService = new ConfigService(options);\n this.transformerService = new TransformerService(\n this.configService,\n this.app.log\n );\n this.transformerService.initialize().finally(() => {\n this.providerService = new ProviderService(\n this.configService,\n this.transformerService,\n this.app.log\n );\n this.llmService = new LLMService(this.providerService);\n });\n }\n\n // Type-safe register method using Fastify native types\n async register(\n plugin: FastifyPluginAsync | FastifyPluginCallback,\n options?: FastifyRegisterOptions\n ): Promise {\n await (this.app as any).register(plugin, options);\n }\n\n // Type-safe addHook method with Fastify native types\n addHook(hookName: \"onRequest\", hookFunction: onRequestHookHandler): void;\n addHook(hookName: \"preParsing\", hookFunction: preParsingHookHandler): void;\n addHook(\n hookName: \"preValidation\",\n hookFunction: preValidationHookHandler\n ): void;\n addHook(hookName: \"preHandler\", hookFunction: preHandlerHookHandler): void;\n addHook(\n hookName: \"preSerialization\",\n hookFunction: preSerializationHookHandler\n ): void;\n addHook(hookName: \"onSend\", hookFunction: onSendHookHandler): void;\n addHook(hookName: \"onResponse\", hookFunction: onResponseHookHandler): void;\n addHook(hookName: \"onTimeout\", hookFunction: onTimeoutHookHandler): void;\n addHook(hookName: \"onError\", hookFunction: onErrorHookHandler): void;\n addHook(hookName: \"onRoute\", hookFunction: onRouteHookHandler): void;\n addHook(hookName: \"onRegister\", hookFunction: onRegisterHookHandler): void;\n addHook(hookName: \"onReady\", hookFunction: onReadyHookHandler): void;\n addHook(hookName: \"onListen\", hookFunction: onListenHookHandler): void;\n addHook(hookName: \"onClose\", hookFunction: onCloseHookHandler): void;\n public addHook(hookName: string, hookFunction: any): void {\n this.app.addHook(hookName as any, hookFunction);\n }\n\n async start(): Promise {\n try {\n this.app._server = this;\n\n this.app.addHook(\"preHandler\", (request, reply, done) => {\n if (request.url.startsWith('/v1/messages') && request.body) {\n request.log.info({ body: request.body }, \"request body\");\n request.body.stream === true\n if(!request.body.stream) {\n request.body.stream = false; // Ensure stream is false if not set\n }\n }\n done();\n });\n\n this.app.addHook(\n \"preHandler\",\n async (req: FastifyRequest, reply: FastifyReply) => {\n if (req.url.startsWith(\"/api\") || req.method !== \"POST\") return;\n try {\n const body = req.body as any;\n if (!body || !body.model) {\n return reply\n .code(400)\n .send({ error: \"Missing model in request body\" });\n }\n const [provider, model] = body.model.split(\",\");\n body.model = model;\n req.provider = provider;\n return;\n } catch (err) {\n req.log.error(\"Error in modelProviderMiddleware:\", err);\n return reply.code(500).send({ error: \"Internal server error\" });\n }\n }\n );\n\n this.app.register(registerApiRoutes);\n\n const address = await this.app.listen({\n port: parseInt(this.configService.get(\"PORT\") || \"3000\", 10),\n host: this.configService.get(\"HOST\") || \"127.0.0.1\",\n });\n\n this.app.log.info(`\uD83D\uDE80 LLMs API server listening on ${address}`);\n\n const shutdown = async (signal: string) => {\n this.app.log.info(`Received ${signal}, shutting down gracefully...`);\n await this.app.close();\n process.exit(0);\n };\n\n process.on(\"SIGINT\", () => shutdown(\"SIGINT\"));\n process.on(\"SIGTERM\", () => shutdown(\"SIGTERM\"));\n } catch (error) {\n this.app.log.error(`Error starting server: ${error}`);\n process.exit(1);\n }\n }\n}\n\n// Export for external use\nexport default Server;\n", "import { readFileSync, existsSync } from \"fs\";\nimport { join } from \"path\";\nimport { config } from \"dotenv\";\nimport JSON5 from 'json5';\n\nexport interface ConfigOptions {\n envPath?: string;\n jsonPath?: string;\n useEnvFile?: boolean;\n useJsonFile?: boolean;\n useEnvironmentVariables?: boolean;\n initialConfig?: AppConfig;\n}\n\nexport interface AppConfig {\n [key: string]: any;\n}\n\nexport class ConfigService {\n private config: AppConfig = {};\n private options: ConfigOptions;\n\n constructor(\n options: ConfigOptions = {\n jsonPath: \"./config.json\",\n }\n ) {\n this.options = {\n envPath: options.envPath || \".env\",\n jsonPath: options.jsonPath,\n useEnvFile: false,\n useJsonFile: options.useJsonFile !== false,\n useEnvironmentVariables: options.useEnvironmentVariables !== false,\n ...options,\n };\n\n this.loadConfig();\n }\n\n private loadConfig(): void {\n if (this.options.useJsonFile && this.options.jsonPath) {\n this.loadJsonConfig();\n }\n\n if (this.options.initialConfig) {\n this.config = { ...this.config, ...this.options.initialConfig };\n }\n\n if (this.options.useEnvFile) {\n this.loadEnvConfig();\n }\n\n // if (this.options.useEnvironmentVariables) {\n // this.loadEnvironmentVariables();\n // }\n\n if (this.config.LOG_FILE) {\n process.env.LOG_FILE = this.config.LOG_FILE;\n }\n if (this.config.LOG) {\n process.env.LOG = this.config.LOG;\n }\n }\n\n private loadJsonConfig(): void {\n if (!this.options.jsonPath) return;\n\n const jsonPath = this.isAbsolutePath(this.options.jsonPath)\n ? this.options.jsonPath\n : join(process.cwd(), this.options.jsonPath);\n\n if (existsSync(jsonPath)) {\n try {\n const jsonContent = readFileSync(jsonPath, \"utf-8\");\n const jsonConfig = JSON5.parse(jsonContent);\n this.config = { ...this.config, ...jsonConfig };\n console.log(`Loaded JSON config from: ${jsonPath}`);\n } catch (error) {\n console.warn(`Failed to load JSON config from ${jsonPath}:`, error);\n }\n } else {\n console.warn(`JSON config file not found: ${jsonPath}`);\n }\n }\n\n private loadEnvConfig(): void {\n const envPath = this.isAbsolutePath(this.options.envPath!)\n ? this.options.envPath!\n : join(process.cwd(), this.options.envPath!);\n\n if (existsSync(envPath)) {\n try {\n const result = config({ path: envPath });\n if (result.parsed) {\n this.config = {\n ...this.config,\n ...this.parseEnvConfig(result.parsed),\n };\n }\n } catch (error) {\n console.warn(`Failed to load .env config from ${envPath}:`, error);\n }\n }\n }\n\n private loadEnvironmentVariables(): void {\n const envConfig = this.parseEnvConfig(process.env);\n this.config = { ...this.config, ...envConfig };\n }\n\n private parseEnvConfig(\n env: Record\n ): Partial {\n const parsed: Partial = {};\n\n Object.assign(parsed, env);\n\n return parsed;\n }\n\n private isAbsolutePath(path: string): boolean {\n return path.startsWith(\"/\") || path.includes(\":\");\n }\n\n public get(key: keyof AppConfig): T | undefined;\n public get(key: keyof AppConfig, defaultValue: T): T;\n public get(key: keyof AppConfig, defaultValue?: T): T | undefined {\n const value = this.config[key];\n return value !== undefined ? (value as T) : defaultValue;\n }\n\n public getAll(): AppConfig {\n return { ...this.config };\n }\n\n public getHttpsProxy(): string | undefined {\n return (\n this.get(\"HTTPS_PROXY\") ||\n this.get(\"https_proxy\") ||\n this.get(\"httpsProxy\") ||\n this.get(\"PROXY_URL\")\n );\n }\n\n public has(key: keyof AppConfig): boolean {\n return this.config[key] !== undefined;\n }\n\n public set(key: keyof AppConfig, value: any): void {\n this.config[key] = value;\n }\n\n public reload(): void {\n this.config = {};\n this.loadConfig();\n }\n\n public getConfigSummary(): string {\n const summary: string[] = [];\n\n if (this.options.initialConfig) {\n summary.push(\"Initial Config\");\n }\n\n if (this.options.useJsonFile && this.options.jsonPath) {\n summary.push(`JSON: ${this.options.jsonPath}`);\n }\n\n if (this.options.useEnvFile) {\n summary.push(`ENV: ${this.options.envPath}`);\n }\n\n if (this.options.useEnvironmentVariables) {\n summary.push(\"Environment Variables\");\n }\n\n return `Config sources: ${summary.join(\", \")}`;\n }\n}\n", "import { FastifyRequest, FastifyReply } from \"fastify\";\n\nexport interface ApiError extends Error {\n statusCode?: number;\n code?: string;\n type?: string;\n}\n\nexport function createApiError(\n message: string,\n statusCode: number = 500,\n code: string = \"internal_error\",\n type: string = \"api_error\"\n): ApiError {\n const error = new Error(message) as ApiError;\n error.statusCode = statusCode;\n error.code = code;\n error.type = type;\n return error;\n}\n\nexport async function errorHandler(\n error: ApiError,\n request: FastifyRequest,\n reply: FastifyReply\n) {\n request.log.error(error);\n\n const statusCode = error.statusCode || 500;\n const response = {\n error: {\n message: error.message + error.stack || \"Internal Server Error\",\n type: error.type || \"api_error\",\n code: error.code || \"internal_error\",\n },\n };\n\n return reply.code(statusCode).send(response);\n}\n", "import { ProxyAgent } from \"undici\";\nimport { UnifiedChatRequest } from \"../types/llm\";\n\nexport function sendUnifiedRequest(\n url: URL | string,\n request: UnifiedChatRequest,\n config: any,\n logger?: any\n): Promise {\n const headers = new Headers({\n \"Content-Type\": \"application/json\",\n });\n if (config.headers) {\n Object.entries(config.headers).forEach(([key, value]) => {\n if (value) {\n headers.set(key, value as string);\n }\n });\n }\n let combinedSignal: AbortSignal;\n const timeoutSignal = AbortSignal.timeout(config.TIMEOUT ?? 60 * 1000 * 60);\n\n if (config.signal) {\n const controller = new AbortController();\n const abortHandler = () => controller.abort();\n config.signal.addEventListener(\"abort\", abortHandler);\n timeoutSignal.addEventListener(\"abort\", abortHandler);\n combinedSignal = controller.signal;\n } else {\n combinedSignal = timeoutSignal;\n }\n\n const fetchOptions: RequestInit = {\n method: \"POST\",\n headers: headers,\n body: JSON.stringify(request),\n signal: combinedSignal,\n };\n\n if (config.httpsProxy) {\n (fetchOptions as any).dispatcher = new ProxyAgent(\n new URL(config.httpsProxy).toString()\n );\n }\n logger?.debug(\n {\n request: fetchOptions,\n headers: Object.fromEntries(headers.entries()),\n requestUrl: typeof url === \"string\" ? url : url.toString(),\n useProxy: config.httpsProxy,\n },\n \"final request\"\n );\n return fetch(typeof url === \"string\" ? url : url.toString(), fetchOptions);\n}\n", "{\n \"name\": \"@musistudio/llms\",\n \"version\": \"1.0.28\",\n \"description\": \"A universal LLM API transformation server\",\n \"main\": \"dist/cjs/server.cjs\",\n \"module\": \"dist/esm/server.mjs\",\n \"type\": \"module\",\n \"exports\": {\n \".\": {\n \"import\": \"./dist/esm/server.mjs\",\n \"require\": \"./dist/cjs/server.cjs\"\n }\n },\n \"scripts\": {\n \"tsx\": \"tsx\",\n \"build\": \"tsx scripts/build.ts\",\n \"build:watch\": \"tsx scripts/build.ts --watch\",\n \"dev\": \"nodemon\",\n \"start\": \"node dist/cjs/server.cjs\",\n \"start:esm\": \"node dist/esm/server.mjs\",\n \"lint\": \"eslint src --ext .ts,.tsx\"\n },\n \"keywords\": [],\n \"author\": \"\",\n \"license\": \"MIT\",\n \"dependencies\": {\n \"@anthropic-ai/sdk\": \"^0.54.0\",\n \"@fastify/cors\": \"^11.0.1\",\n \"@google/genai\": \"^1.7.0\",\n \"dotenv\": \"^16.5.0\",\n \"fastify\": \"^5.4.0\",\n \"google-auth-library\": \"^10.1.0\",\n \"json5\": \"^2.2.3\",\n \"jsonrepair\": \"^3.13.0\",\n \"openai\": \"^5.6.0\",\n \"undici\": \"^7.10.0\",\n \"uuid\": \"^11.1.0\"\n },\n \"devDependencies\": {\n \"@types/chai\": \"^5.2.2\",\n \"@types/mocha\": \"^10.0.10\",\n \"@types/node\": \"^24.0.3\",\n \"@types/sinon\": \"^17.0.4\",\n \"@typescript-eslint/eslint-plugin\": \"^8.35.0\",\n \"@typescript-eslint/parser\": \"^8.35.0\",\n \"chai\": \"^5.2.0\",\n \"esbuild\": \"^0.25.5\",\n \"eslint\": \"^9.30.0\",\n \"nodemon\": \"^3.1.10\",\n \"sinon\": \"^21.0.0\",\n \"tsx\": \"^4.20.3\",\n \"typescript\": \"^5.8.3\",\n \"typescript-eslint\": \"^8.35.0\"\n }\n}\n", "import {\n FastifyInstance,\n FastifyPluginAsync,\n FastifyRequest,\n FastifyReply,\n} from \"fastify\";\nimport { RegisterProviderRequest, LLMProvider } from \"@/types/llm\";\nimport { sendUnifiedRequest } from \"@/utils/request\";\nimport { createApiError } from \"./middleware\";\nimport { version } from \"../../package.json\";\n\n/**\n * \u5904\u7406transformer\u7AEF\u70B9\u7684\u4E3B\u51FD\u6570\n * \u534F\u8C03\u6574\u4E2A\u8BF7\u6C42\u5904\u7406\u6D41\u7A0B\uFF1A\u9A8C\u8BC1\u63D0\u4F9B\u8005\u3001\u5904\u7406\u8BF7\u6C42\u8F6C\u6362\u5668\u3001\u53D1\u9001\u8BF7\u6C42\u3001\u5904\u7406\u54CD\u5E94\u8F6C\u6362\u5668\u3001\u683C\u5F0F\u5316\u54CD\u5E94\n */\nasync function handleTransformerEndpoint(\n req: FastifyRequest,\n reply: FastifyReply,\n fastify: FastifyInstance,\n transformer: any\n) {\n const body = req.body as any;\n const providerName = req.provider!;\n const provider = fastify._server!.providerService.getProvider(providerName);\n\n // \u9A8C\u8BC1\u63D0\u4F9B\u8005\u662F\u5426\u5B58\u5728\n if (!provider) {\n throw createApiError(\n `Provider '${providerName}' not found`,\n 404,\n \"provider_not_found\"\n );\n }\n\n // \u5904\u7406\u8BF7\u6C42\u8F6C\u6362\u5668\u94FE\n const { requestBody, config, bypass } = await processRequestTransformers(\n body,\n provider,\n transformer,\n req.headers\n );\n\n // \u53D1\u9001\u8BF7\u6C42\u5230LLM\u63D0\u4F9B\u8005\n const response = await sendRequestToProvider(\n requestBody,\n config,\n provider,\n fastify,\n bypass,\n transformer\n );\n\n // \u5904\u7406\u54CD\u5E94\u8F6C\u6362\u5668\u94FE\n const finalResponse = await processResponseTransformers(\n requestBody,\n response,\n provider,\n transformer,\n bypass\n );\n\n // \u683C\u5F0F\u5316\u5E76\u8FD4\u56DE\u54CD\u5E94\n return formatResponse(finalResponse, reply, body);\n}\n\n/**\n * \u5904\u7406\u8BF7\u6C42\u8F6C\u6362\u5668\u94FE\n * \u4F9D\u6B21\u6267\u884CtransformRequestOut\u3001provider transformers\u3001model-specific transformers\n * \u8FD4\u56DE\u5904\u7406\u540E\u7684\u8BF7\u6C42\u4F53\u3001\u914D\u7F6E\u548C\u662F\u5426\u8DF3\u8FC7\u8F6C\u6362\u5668\u7684\u6807\u5FD7\n */\nasync function processRequestTransformers(\n body: any,\n provider: any,\n transformer: any,\n headers: any\n) {\n let requestBody = body;\n let config = {};\n let bypass = false;\n\n // \u68C0\u67E5\u662F\u5426\u5E94\u8BE5\u8DF3\u8FC7\u8F6C\u6362\u5668\uFF08\u900F\u4F20\u53C2\u6570\uFF09\n bypass = shouldBypassTransformers(provider, transformer, body);\n\n if (bypass) {\n if (headers instanceof Headers) {\n headers.delete(\"content-length\");\n } else {\n delete headers[\"content-length\"];\n }\n config.headers = headers;\n }\n\n // \u6267\u884Ctransformer\u7684transformRequestOut\u65B9\u6CD5\n if (!bypass && typeof transformer.transformRequestOut === \"function\") {\n const transformOut = await transformer.transformRequestOut(requestBody);\n if (transformOut.body) {\n requestBody = transformOut.body;\n config = transformOut.config || {};\n } else {\n requestBody = transformOut;\n }\n }\n\n // \u6267\u884Cprovider\u7EA7\u522B\u7684\u8F6C\u6362\u5668\n if (!bypass && provider.transformer?.use?.length) {\n for (const providerTransformer of provider.transformer.use) {\n if (\n !providerTransformer ||\n typeof providerTransformer.transformRequestIn !== \"function\"\n ) {\n continue;\n }\n const transformIn = await providerTransformer.transformRequestIn(\n requestBody,\n provider\n );\n if (transformIn.body) {\n requestBody = transformIn.body;\n config = { ...config, ...transformIn.config };\n } else {\n requestBody = transformIn;\n }\n }\n }\n\n // \u6267\u884C\u6A21\u578B\u7279\u5B9A\u7684\u8F6C\u6362\u5668\n if (!bypass && provider.transformer?.[body.model]?.use?.length) {\n for (const modelTransformer of provider.transformer[body.model].use) {\n if (\n !modelTransformer ||\n typeof modelTransformer.transformRequestIn !== \"function\"\n ) {\n continue;\n }\n requestBody = await modelTransformer.transformRequestIn(\n requestBody,\n provider\n );\n }\n }\n\n return { requestBody, config, bypass };\n}\n\n/**\n * \u5224\u65AD\u662F\u5426\u5E94\u8BE5\u8DF3\u8FC7\u8F6C\u6362\u5668\uFF08\u900F\u4F20\u53C2\u6570\uFF09\n * \u5F53provider\u53EA\u4F7F\u7528\u4E00\u4E2Atransformer\u4E14\u8BE5transformer\u4E0E\u5F53\u524Dtransformer\u76F8\u540C\u65F6\uFF0C\u8DF3\u8FC7\u5176\u4ED6\u8F6C\u6362\u5668\n */\nfunction shouldBypassTransformers(\n provider: any,\n transformer: any,\n body: any\n): boolean {\n return (\n provider.transformer?.use?.length === 1 &&\n provider.transformer.use[0].name === transformer.name &&\n (!provider.transformer?.[body.model]?.use.length ||\n (provider.transformer?.[body.model]?.use.length === 1 &&\n provider.transformer?.[body.model]?.use[0].name === transformer.name))\n );\n}\n\n/**\n * \u53D1\u9001\u8BF7\u6C42\u5230LLM\u63D0\u4F9B\u8005\n * \u5904\u7406\u8BA4\u8BC1\u3001\u6784\u5EFA\u8BF7\u6C42\u914D\u7F6E\u3001\u53D1\u9001\u8BF7\u6C42\u5E76\u5904\u7406\u9519\u8BEF\n */\nasync function sendRequestToProvider(\n requestBody: any,\n config: any,\n provider: any,\n fastify: FastifyInstance,\n bypass: boolean,\n transformer: any\n) {\n const url = config.url || new URL(provider.baseUrl);\n\n // \u5728\u900F\u4F20\u53C2\u6570\u4E0B\u5904\u7406\u8BA4\u8BC1\n if (bypass && typeof transformer.auth === \"function\") {\n const auth = await transformer.auth(requestBody, provider);\n if (auth.body) {\n requestBody = auth.body;\n let headers = config.headers || {};\n if (auth.config?.headers) {\n headers = {\n ...headers,\n ...auth.config.headers,\n };\n delete headers.host;\n delete auth.config.headers;\n }\n config = {\n ...config,\n ...auth.config,\n headers,\n };\n } else {\n requestBody = auth;\n }\n }\n\n // \u53D1\u9001HTTP\u8BF7\u6C42\n const response = await sendUnifiedRequest(\n url,\n requestBody,\n {\n httpsProxy: fastify._server!.configService.getHttpsProxy(),\n ...config,\n headers: {\n Authorization: `Bearer ${provider.apiKey}`,\n ...(config?.headers || {}),\n },\n },\n fastify.log\n );\n\n // \u5904\u7406\u8BF7\u6C42\u9519\u8BEF\n if (!response.ok) {\n const errorText = await response.text();\n throw createApiError(\n `Error from provider(${provider.name},${requestBody.model}: ${response.status}): ${errorText}`,\n response.status,\n \"provider_response_error\"\n );\n }\n\n return response;\n}\n\n/**\n * \u5904\u7406\u54CD\u5E94\u8F6C\u6362\u5668\u94FE\n * \u4F9D\u6B21\u6267\u884Cprovider transformers\u3001model-specific transformers\u3001transformer\u7684transformResponseIn\n */\nasync function processResponseTransformers(\n requestBody: any,\n response: any,\n provider: any,\n transformer: any,\n bypass: boolean\n) {\n let finalResponse = response;\n\n // \u6267\u884Cprovider\u7EA7\u522B\u7684\u54CD\u5E94\u8F6C\u6362\u5668\n if (!bypass && provider.transformer?.use?.length) {\n for (const providerTransformer of Array.from(\n provider.transformer.use\n ).reverse()) {\n if (\n !providerTransformer ||\n typeof providerTransformer.transformResponseOut !== \"function\"\n ) {\n continue;\n }\n finalResponse = await providerTransformer.transformResponseOut(\n finalResponse\n );\n }\n }\n\n // \u6267\u884C\u6A21\u578B\u7279\u5B9A\u7684\u54CD\u5E94\u8F6C\u6362\u5668\n if (!bypass && provider.transformer?.[requestBody.model]?.use?.length) {\n for (const modelTransformer of Array.from(\n provider.transformer[requestBody.model].use\n ).reverse()) {\n if (\n !modelTransformer ||\n typeof modelTransformer.transformResponseOut !== \"function\"\n ) {\n continue;\n }\n finalResponse = await modelTransformer.transformResponseOut(\n finalResponse\n );\n }\n }\n\n // \u6267\u884Ctransformer\u7684transformResponseIn\u65B9\u6CD5\n if (!bypass && transformer.transformResponseIn) {\n finalResponse = await transformer.transformResponseIn(finalResponse);\n }\n\n return finalResponse;\n}\n\n/**\n * \u683C\u5F0F\u5316\u5E76\u8FD4\u56DE\u54CD\u5E94\n * \u5904\u7406HTTP\u72B6\u6001\u7801\u3001\u6D41\u5F0F\u54CD\u5E94\u548C\u666E\u901A\u54CD\u5E94\u7684\u683C\u5F0F\u5316\n */\nfunction formatResponse(response: any, reply: FastifyReply, body: any) {\n // \u8BBE\u7F6EHTTP\u72B6\u6001\u7801\n if (!response.ok) {\n reply.code(response.status);\n }\n\n // \u5904\u7406\u6D41\u5F0F\u54CD\u5E94\n const isStream = body.stream === true;\n if (isStream) {\n reply.header(\"Content-Type\", \"text/event-stream\");\n reply.header(\"Cache-Control\", \"no-cache\");\n reply.header(\"Connection\", \"keep-alive\");\n return reply.send(response.body);\n } else {\n // \u5904\u7406\u666E\u901AJSON\u54CD\u5E94\n return response.json();\n }\n}\n\nexport const registerApiRoutes: FastifyPluginAsync = async (\n fastify: FastifyInstance\n) => {\n // Health and info endpoints\n fastify.get(\"/\", async () => {\n return { message: \"LLMs API\", version };\n });\n\n fastify.get(\"/health\", async () => {\n return { status: \"ok\", timestamp: new Date().toISOString() };\n });\n\n const transformersWithEndpoint =\n fastify._server!.transformerService.getTransformersWithEndpoint();\n\n for (const { transformer } of transformersWithEndpoint) {\n if (transformer.endPoint) {\n fastify.post(\n transformer.endPoint,\n async (req: FastifyRequest, reply: FastifyReply) => {\n return handleTransformerEndpoint(req, reply, fastify, transformer);\n }\n );\n }\n }\n\n fastify.post(\n \"/providers\",\n {\n schema: {\n body: {\n type: \"object\",\n properties: {\n id: { type: \"string\" },\n name: { type: \"string\" },\n type: { type: \"string\", enum: [\"openai\", \"anthropic\"] },\n baseUrl: { type: \"string\" },\n apiKey: { type: \"string\" },\n models: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"id\", \"name\", \"type\", \"baseUrl\", \"apiKey\", \"models\"],\n },\n },\n },\n async (\n request: FastifyRequest<{ Body: RegisterProviderRequest }>,\n reply: FastifyReply\n ) => {\n // Validation\n const { name, baseUrl, apiKey, models } = request.body;\n\n if (!name?.trim()) {\n throw createApiError(\n \"Provider name is required\",\n 400,\n \"invalid_request\"\n );\n }\n\n if (!baseUrl || !isValidUrl(baseUrl)) {\n throw createApiError(\n \"Valid base URL is required\",\n 400,\n \"invalid_request\"\n );\n }\n\n if (!apiKey?.trim()) {\n throw createApiError(\"API key is required\", 400, \"invalid_request\");\n }\n\n if (!models || !Array.isArray(models) || models.length === 0) {\n throw createApiError(\n \"At least one model is required\",\n 400,\n \"invalid_request\"\n );\n }\n\n // Check if provider already exists\n if (fastify._server!.providerService.getProvider(request.body.name)) {\n throw createApiError(\n `Provider with name '${request.body.name}' already exists`,\n 400,\n \"provider_exists\"\n );\n }\n\n return fastify._server!.providerService.registerProvider(request.body);\n }\n );\n\n fastify.get(\"/providers\", async () => {\n return fastify._server!.providerService.getProviders();\n });\n\n fastify.get(\n \"/providers/:id\",\n {\n schema: {\n params: {\n type: \"object\",\n properties: { id: { type: \"string\" } },\n required: [\"id\"],\n },\n },\n },\n async (request: FastifyRequest<{ Params: { id: string } }>) => {\n const provider = fastify._server!.providerService.getProvider(\n request.params.id\n );\n if (!provider) {\n throw createApiError(\"Provider not found\", 404, \"provider_not_found\");\n }\n return provider;\n }\n );\n\n fastify.put(\n \"/providers/:id\",\n {\n schema: {\n params: {\n type: \"object\",\n properties: { id: { type: \"string\" } },\n required: [\"id\"],\n },\n body: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n type: { type: \"string\", enum: [\"openai\", \"anthropic\"] },\n baseUrl: { type: \"string\" },\n apiKey: { type: \"string\" },\n models: { type: \"array\", items: { type: \"string\" } },\n enabled: { type: \"boolean\" },\n },\n },\n },\n },\n async (\n request: FastifyRequest<{\n Params: { id: string };\n Body: Partial;\n }>,\n reply\n ) => {\n const provider = fastify._server!.providerService.updateProvider(\n request.params.id,\n request.body\n );\n if (!provider) {\n throw createApiError(\"Provider not found\", 404, \"provider_not_found\");\n }\n return provider;\n }\n );\n\n fastify.delete(\n \"/providers/:id\",\n {\n schema: {\n params: {\n type: \"object\",\n properties: { id: { type: \"string\" } },\n required: [\"id\"],\n },\n },\n },\n async (request: FastifyRequest<{ Params: { id: string } }>) => {\n const success = fastify._server!.providerService.deleteProvider(\n request.params.id\n );\n if (!success) {\n throw createApiError(\"Provider not found\", 404, \"provider_not_found\");\n }\n return { message: \"Provider deleted successfully\" };\n }\n );\n\n fastify.patch(\n \"/providers/:id/toggle\",\n {\n schema: {\n params: {\n type: \"object\",\n properties: { id: { type: \"string\" } },\n required: [\"id\"],\n },\n body: {\n type: \"object\",\n properties: { enabled: { type: \"boolean\" } },\n required: [\"enabled\"],\n },\n },\n },\n async (\n request: FastifyRequest<{\n Params: { id: string };\n Body: { enabled: boolean };\n }>,\n reply\n ) => {\n const success = fastify._server!.providerService.toggleProvider(\n request.params.id,\n request.body.enabled\n );\n if (!success) {\n throw createApiError(\"Provider not found\", 404, \"provider_not_found\");\n }\n return {\n message: `Provider ${\n request.body.enabled ? \"enabled\" : \"disabled\"\n } successfully`,\n };\n }\n );\n};\n\n// Helper function\nfunction isValidUrl(url: string): boolean {\n try {\n new URL(url);\n return true;\n } catch {\n return false;\n }\n}\n", "import { ProviderService } from \"./provider\";\nimport {\n LLMProvider,\n RegisterProviderRequest,\n RequestRouteInfo,\n} from \"../types/llm\";\n\nexport class LLMService {\n constructor(private readonly providerService: ProviderService) {\n }\n\n registerProvider(request: RegisterProviderRequest): LLMProvider {\n return this.providerService.registerProvider(request);\n }\n\n getProviders(): LLMProvider[] {\n return this.providerService.getProviders();\n }\n\n getProvider(id: string): LLMProvider | undefined {\n return this.providerService.getProvider(id);\n }\n\n updateProvider(\n id: string,\n updates: Partial\n ): LLMProvider | null {\n const result = this.providerService.updateProvider(id, updates);\n return result;\n }\n\n deleteProvider(id: string): boolean {\n const result = this.providerService.deleteProvider(id);\n return result;\n }\n\n toggleProvider(id: string, enabled: boolean): boolean {\n return this.providerService.toggleProvider(id, enabled);\n }\n\n private resolveRoute(modelName: string): RequestRouteInfo {\n const route = this.providerService.resolveModelRoute(modelName);\n if (!route) {\n throw new Error(\n `Model ${modelName} not found. Available models: ${this.getAvailableModelNames().join(\n \", \"\n )}`\n );\n }\n return route;\n }\n\n async getAvailableModels(): Promise {\n const providers = this.providerService.getAvailableModels();\n\n return {\n object: \"list\",\n data: providers.flatMap((provider) =>\n provider.models.map((model) => ({\n id: model,\n object: \"model\",\n provider: provider.provider,\n created: Math.floor(Date.now() / 1000),\n owned_by: provider.provider,\n }))\n ),\n };\n }\n\n private getAvailableModelNames(): string[] {\n return this.providerService\n .getModelRoutes()\n .map((route) => route.fullModel);\n }\n\n getModelRoutes() {\n return this.providerService.getModelRoutes();\n }\n}\n", "import { TransformerConstructor } from \"@/types/transformer\";\nimport {\n LLMProvider,\n RegisterProviderRequest,\n ModelRoute,\n RequestRouteInfo,\n ConfigProvider,\n} from \"../types/llm\";\nimport { ConfigService } from \"./config\";\nimport { TransformerService } from \"./transformer\";\n\nexport class ProviderService {\n private providers: Map = new Map();\n private modelRoutes: Map = new Map();\n\n constructor(private readonly configService: ConfigService, private readonly transformerService: TransformerService, private readonly logger: any) {\n this.initializeCustomProviders();\n }\n\n private initializeCustomProviders() {\n const providersConfig =\n this.configService.get(\"providers\");\n if (providersConfig && Array.isArray(providersConfig)) {\n this.initializeFromProvidersArray(providersConfig);\n return;\n }\n }\n\n private initializeFromProvidersArray(providersConfig: ConfigProvider[]) {\n providersConfig.forEach((providerConfig: ConfigProvider) => {\n try {\n if (\n !providerConfig.name ||\n !providerConfig.api_base_url ||\n !providerConfig.api_key\n ) {\n return;\n }\n\n const transformer: LLMProvider[\"transformer\"] = {}\n\n if (providerConfig.transformer) {\n Object.keys(providerConfig.transformer).forEach(key => {\n if (key === 'use') {\n if (Array.isArray(providerConfig.transformer.use)) {\n transformer.use = providerConfig.transformer.use.map((transformer) => {\n if (Array.isArray(transformer) && typeof transformer[0] === 'string') {\n const Constructor = this.transformerService.getTransformer(transformer[0]);\n if (Constructor) {\n return new (Constructor as TransformerConstructor)(transformer[1]);\n }\n }\n if (typeof transformer === 'string') {\n const transformerInstance = this.transformerService.getTransformer(transformer);\n if (typeof transformerInstance === 'function') {\n return new transformerInstance();\n }\n return transformerInstance;\n }\n }).filter((transformer) => typeof transformer !== 'undefined');\n }\n } else {\n if (Array.isArray(providerConfig.transformer[key]?.use)) {\n transformer[key] = {\n use: providerConfig.transformer[key].use.map((transformer) => {\n if (Array.isArray(transformer) && typeof transformer[0] === 'string') {\n const Constructor = this.transformerService.getTransformer(transformer[0]);\n if (Constructor) {\n return new (Constructor as TransformerConstructor)(transformer[1]);\n }\n }\n if (typeof transformer === 'string') {\n const transformerInstance = this.transformerService.getTransformer(transformer);\n if (typeof transformerInstance === 'function') {\n return new transformerInstance();\n }\n return transformerInstance;\n }\n }).filter((transformer) => typeof transformer !== 'undefined')\n }\n }\n }\n })\n }\n\n this.registerProvider({\n name: providerConfig.name,\n baseUrl: providerConfig.api_base_url,\n apiKey: providerConfig.api_key,\n models: providerConfig.models || [],\n transformer: providerConfig.transformer ? transformer : undefined,\n });\n\n this.logger.info(`${providerConfig.name} provider registered`);\n } catch (error) {\n this.logger.error(`${providerConfig.name} provider registered error: ${error}`);\n }\n });\n }\n\n registerProvider(request: RegisterProviderRequest): LLMProvider {\n const provider: LLMProvider = {\n ...request,\n };\n\n this.providers.set(provider.name, provider);\n\n request.models.forEach((model) => {\n const fullModel = `${provider.name},${model}`;\n const route: ModelRoute = {\n provider: provider.name,\n model,\n fullModel,\n };\n this.modelRoutes.set(fullModel, route);\n if (!this.modelRoutes.has(model)) {\n this.modelRoutes.set(model, route);\n }\n });\n\n return provider;\n }\n\n getProviders(): LLMProvider[] {\n return Array.from(this.providers.values());\n }\n\n getProvider(name: string): LLMProvider | undefined {\n return this.providers.get(name);\n }\n\n updateProvider(\n id: string,\n updates: Partial\n ): LLMProvider | null {\n const provider = this.providers.get(id);\n if (!provider) {\n return null;\n }\n\n const updatedProvider = {\n ...provider,\n ...updates,\n updatedAt: new Date(),\n };\n\n this.providers.set(id, updatedProvider);\n\n if (updates.models) {\n provider.models.forEach((model) => {\n const fullModel = `${provider.id},${model}`;\n this.modelRoutes.delete(fullModel);\n this.modelRoutes.delete(model);\n });\n\n updates.models.forEach((model) => {\n const fullModel = `${provider.name},${model}`;\n const route: ModelRoute = {\n provider: provider.name,\n model,\n fullModel,\n };\n this.modelRoutes.set(fullModel, route);\n if (!this.modelRoutes.has(model)) {\n this.modelRoutes.set(model, route);\n }\n });\n }\n\n return updatedProvider;\n }\n\n deleteProvider(id: string): boolean {\n const provider = this.providers.get(id);\n if (!provider) {\n return false;\n }\n\n provider.models.forEach((model) => {\n const fullModel = `${provider.name},${model}`;\n this.modelRoutes.delete(fullModel);\n this.modelRoutes.delete(model);\n });\n\n this.providers.delete(id);\n return true;\n }\n\n toggleProvider(name: string, enabled: boolean): boolean {\n const provider = this.providers.get(name);\n if (!provider) {\n return false;\n }\n return true;\n }\n\n resolveModelRoute(modelName: string): RequestRouteInfo | null {\n const route = this.modelRoutes.get(modelName);\n if (!route) {\n return null;\n }\n\n const provider = this.providers.get(route.provider);\n if (!provider) {\n return null;\n }\n\n return {\n provider,\n originalModel: modelName,\n targetModel: route.model,\n };\n }\n\n getAvailableModelNames(): string[] {\n const modelNames: string[] = [];\n this.providers.forEach((provider) => {\n provider.models.forEach((model) => {\n modelNames.push(model);\n modelNames.push(`${provider.name},${model}`);\n });\n });\n return modelNames;\n }\n\n getModelRoutes(): ModelRoute[] {\n return Array.from(this.modelRoutes.values());\n }\n\n private parseTransformerConfig(transformerConfig: any): any {\n if (!transformerConfig) return {};\n\n if (Array.isArray(transformerConfig)) {\n return transformerConfig.reduce((acc, item) => {\n if (Array.isArray(item)) {\n const [name, config = {}] = item;\n acc[name] = config;\n } else {\n acc[item] = {};\n }\n return acc;\n }, {});\n }\n\n return transformerConfig;\n }\n\n async getAvailableModels(): Promise<{\n object: string;\n data: Array<{\n id: string;\n object: string;\n owned_by: string;\n provider: string;\n }>;\n }> {\n const models: Array<{\n id: string;\n object: string;\n owned_by: string;\n provider: string;\n }> = [];\n\n this.providers.forEach((provider) => {\n provider.models.forEach((model) => {\n models.push({\n id: model,\n object: \"model\",\n owned_by: provider.name,\n provider: provider.name,\n });\n\n models.push({\n id: `${provider.name},${model}`,\n object: \"model\",\n owned_by: provider.name,\n provider: provider.name,\n });\n });\n });\n\n return {\n object: \"list\",\n data: models,\n };\n }\n}\n", "import validate from './validate.js';\nconst byteToHex = [];\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nexport function unsafeStringify(arr, offset = 0) {\n return (byteToHex[arr[offset + 0]] +\n byteToHex[arr[offset + 1]] +\n byteToHex[arr[offset + 2]] +\n byteToHex[arr[offset + 3]] +\n '-' +\n byteToHex[arr[offset + 4]] +\n byteToHex[arr[offset + 5]] +\n '-' +\n byteToHex[arr[offset + 6]] +\n byteToHex[arr[offset + 7]] +\n '-' +\n byteToHex[arr[offset + 8]] +\n byteToHex[arr[offset + 9]] +\n '-' +\n byteToHex[arr[offset + 10]] +\n byteToHex[arr[offset + 11]] +\n byteToHex[arr[offset + 12]] +\n byteToHex[arr[offset + 13]] +\n byteToHex[arr[offset + 14]] +\n byteToHex[arr[offset + 15]]).toLowerCase();\n}\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset);\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n return uuid;\n}\nexport default stringify;\n", "import { randomFillSync } from 'crypto';\nconst rnds8Pool = new Uint8Array(256);\nlet poolPtr = rnds8Pool.length;\nexport default function rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n return rnds8Pool.slice(poolPtr, (poolPtr += 16));\n}\n", "import { randomUUID } from 'crypto';\nexport default { randomUUID };\n", "import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n options = options || {};\n const rnds = options.random ?? options.rng?.() ?? rng();\n if (rnds.length < 16) {\n throw new Error('Random bytes length must be >= 16');\n }\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n if (buf) {\n offset = offset || 0;\n if (offset < 0 || offset + 16 > buf.length) {\n throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);\n }\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n return buf;\n }\n return unsafeStringify(rnds);\n}\nexport default v4;\n", "import { ThinkLevel } from \"@/types/llm\";\n\nexport const getThinkLevel = (thinking_budget: number): ThinkLevel => {\n if (thinking_budget <= 0) return \"none\";\n if (thinking_budget <= 1024) return \"low\";\n if (thinking_budget <= 8192) return \"medium\";\n return \"high\";\n};\n", "import { ChatCompletion } from \"openai/resources\";\nimport {\n LLMProvider,\n UnifiedChatRequest,\n UnifiedMessage,\n UnifiedTool,\n} from \"@/types/llm\";\nimport { Transformer, TransformerContext } from \"@/types/transformer\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { getThinkLevel } from \"@/utils/thinking\";\nimport { createApiError } from \"@/api/middleware\";\n\nexport class AnthropicTransformer implements Transformer {\n name = \"Anthropic\";\n endPoint = \"/v1/messages\";\n\n async auth(request: any, provider: LLMProvider): Promise {\n return {\n body: request,\n config: {\n headers: {\n \"x-api-key\": provider.apiKey,\n authorization: undefined,\n },\n },\n };\n }\n\n async transformRequestOut(\n request: Record\n ): Promise {\n const messages: UnifiedMessage[] = [];\n\n if (request.system) {\n if (typeof request.system === \"string\") {\n messages.push({\n role: \"system\",\n content: request.system,\n });\n } else if (Array.isArray(request.system) && request.system.length) {\n const textParts = request.system\n .filter((item: any) => item.type === \"text\" && item.text)\n .map((item: any) => ({\n type: \"text\" as const,\n text: item.text,\n cache_control: item.cache_control,\n }));\n messages.push({\n role: \"system\",\n content: textParts,\n });\n }\n }\n\n const requestMessages = JSON.parse(JSON.stringify(request.messages || []));\n\n requestMessages?.forEach((msg: any, index: number) => {\n if (msg.role === \"user\" || msg.role === \"assistant\") {\n if (typeof msg.content === \"string\") {\n messages.push({\n role: msg.role,\n content: msg.content,\n });\n return;\n }\n\n if (Array.isArray(msg.content)) {\n if (msg.role === \"user\") {\n const toolParts = msg.content.filter(\n (c: any) => c.type === \"tool_result\" && c.tool_use_id\n );\n if (toolParts.length) {\n toolParts.forEach((tool: any, toolIndex: number) => {\n const toolMessage: UnifiedMessage = {\n role: \"tool\",\n content:\n typeof tool.content === \"string\"\n ? tool.content\n : JSON.stringify(tool.content),\n tool_call_id: tool.tool_use_id,\n cache_control: tool.cache_control,\n };\n messages.push(toolMessage);\n });\n }\n\n const textAndMediaParts = msg.content.filter(\n (c: any) =>\n (c.type === \"text\" && c.text) ||\n (c.type === \"image\" && c.source)\n );\n if (textAndMediaParts.length) {\n messages.push({\n role: \"user\",\n content: textAndMediaParts.map((part: any) => {\n if (part?.type === \"image\") {\n return {\n type: \"image_url\",\n image_url: {\n url:\n part.source?.type === \"base64\"\n ? part.source.data\n : part.source.url,\n },\n media_type: part.source.media_type,\n };\n }\n return part;\n }),\n });\n }\n } else if (msg.role === \"assistant\") {\n const assistantMessage: UnifiedMessage = {\n role: \"assistant\",\n content: null,\n };\n const textParts = msg.content.filter(\n (c: any) => c.type === \"text\" && c.text\n );\n if (textParts.length) {\n assistantMessage.content = textParts\n .map((text: any) => text.text)\n .join(\"\\n\");\n }\n\n const toolCallParts = msg.content.filter(\n (c: any) => c.type === \"tool_use\" && c.id\n );\n if (toolCallParts.length) {\n assistantMessage.tool_calls = toolCallParts.map((tool: any) => {\n return {\n id: tool.id,\n type: \"function\" as const,\n function: {\n name: tool.name,\n arguments: JSON.stringify(tool.input || {}),\n },\n };\n });\n }\n messages.push(assistantMessage);\n }\n return;\n }\n }\n });\n\n const result: UnifiedChatRequest = {\n messages,\n model: request.model,\n max_tokens: request.max_tokens,\n temperature: request.temperature,\n stream: request.stream,\n tools: request.tools?.length\n ? this.convertAnthropicToolsToUnified(request.tools)\n : undefined,\n tool_choice: request.tool_choice,\n };\n if (request.thinking) {\n result.reasoning = {\n effort: getThinkLevel(request.thinking.budget_tokens),\n // max_tokens: request.thinking.budget_tokens,\n enabled: request.thinking.type === \"enabled\",\n };\n }\n if (request.tool_choice) {\n if (request.tool_choice.type === \"tool\") {\n result.tool_choice = {\n type: \"function\",\n function: { name: request.tool_choice.name },\n };\n } else {\n result.tool_choice = request.tool_choice.type;\n }\n }\n return result;\n }\n\n async transformResponseIn(\n response: Response,\n context?: TransformerContext\n ): Promise {\n const isStream = response.headers\n .get(\"Content-Type\")\n ?.includes(\"text/event-stream\");\n if (isStream) {\n if (!response.body) {\n throw new Error(\"Stream response body is null\");\n }\n const convertedStream = await this.convertOpenAIStreamToAnthropic(\n response.body\n );\n return new Response(convertedStream, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n } else {\n const data = await response.json();\n const anthropicResponse = this.convertOpenAIResponseToAnthropic(data);\n return new Response(JSON.stringify(anthropicResponse), {\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n }\n\n private convertAnthropicToolsToUnified(tools: any[]): UnifiedTool[] {\n return tools.map((tool) => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description || \"\",\n parameters: tool.input_schema,\n },\n }));\n }\n\n private async convertOpenAIStreamToAnthropic(\n openaiStream: ReadableStream\n ): Promise {\n const readable = new ReadableStream({\n start: async (controller) => {\n const encoder = new TextEncoder();\n const messageId = `msg_${Date.now()}`;\n let stopReasonMessageDelta: null | Record = null;\n let model = \"unknown\";\n let hasStarted = false;\n let hasTextContentStarted = false;\n let hasFinished = false;\n const toolCalls = new Map();\n const toolCallIndexToContentBlockIndex = new Map();\n let totalChunks = 0;\n let contentChunks = 0;\n let toolCallChunks = 0;\n let isClosed = false;\n let isThinkingStarted = false;\n let contentIndex = 0;\n let currentContentBlockIndex = -1; // Track the current content block index\n\n const safeEnqueue = (data: Uint8Array) => {\n if (!isClosed) {\n try {\n controller.enqueue(data);\n const dataStr = new TextDecoder().decode(data);\n this.logger.debug({ dataStr }, `send data`);\n } catch (error) {\n if (\n error instanceof TypeError &&\n error.message.includes(\"Controller is already closed\")\n ) {\n isClosed = true;\n } else {\n this.logger.debug(`send data error: ${error.message}`);\n throw error;\n }\n }\n }\n };\n\n const safeClose = () => {\n if (!isClosed) {\n try {\n // Close any remaining open content block\n if (currentContentBlockIndex >= 0) {\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: currentContentBlockIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n }\n\n if (stopReasonMessageDelta) {\n safeEnqueue(\n encoder.encode(\n `event: message_delta\\ndata: ${JSON.stringify(\n stopReasonMessageDelta\n )}\\n\\n`\n )\n );\n stopReasonMessageDelta = null;\n } else {\n safeEnqueue(\n encoder.encode(\n `event: message_delta\\ndata: ${JSON.stringify({\n type: \"message_delta\",\n delta: {\n stop_reason: \"end_turn\",\n stop_sequence: null,\n },\n usage: {\n input_tokens: 0,\n output_tokens: 0,\n cache_read_input_tokens: 0,\n },\n })}\\n\\n`\n )\n );\n }\n const messageStop = {\n type: \"message_stop\",\n };\n safeEnqueue(\n encoder.encode(\n `event: message_stop\\ndata: ${JSON.stringify(\n messageStop\n )}\\n\\n`\n )\n );\n controller.close();\n isClosed = true;\n } catch (error) {\n if (\n error instanceof TypeError &&\n error.message.includes(\"Controller is already closed\")\n ) {\n isClosed = true;\n } else {\n throw error;\n }\n }\n }\n };\n\n let reader: ReadableStreamDefaultReader | null = null;\n\n try {\n reader = openaiStream.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n while (true) {\n if (isClosed) {\n break;\n }\n\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (isClosed || hasFinished) break;\n\n if (!line.startsWith(\"data:\")) continue;\n const data = line.slice(5).trim();\n this.logger.debug(`recieved data: ${data}`);\n\n if (data === \"[DONE]\") {\n continue;\n }\n\n try {\n const chunk = JSON.parse(data);\n totalChunks++;\n this.logger.debug({ response: chunk }, `Original Response`);\n if (chunk.error) {\n const errorMessage = {\n type: \"error\",\n message: {\n type: \"api_error\",\n message: JSON.stringify(chunk.error),\n },\n };\n\n safeEnqueue(\n encoder.encode(\n `event: error\\ndata: ${JSON.stringify(errorMessage)}\\n\\n`\n )\n );\n continue;\n }\n\n model = chunk.model || model;\n\n if (!hasStarted && !isClosed && !hasFinished) {\n hasStarted = true;\n\n const messageStart = {\n type: \"message_start\",\n message: {\n id: messageId,\n type: \"message\",\n role: \"assistant\",\n content: [],\n model: model,\n stop_reason: null,\n stop_sequence: null,\n usage: {\n input_tokens: 0,\n output_tokens: 0,\n },\n },\n };\n\n safeEnqueue(\n encoder.encode(\n `event: message_start\\ndata: ${JSON.stringify(\n messageStart\n )}\\n\\n`\n )\n );\n }\n\n const choice = chunk.choices?.[0];\n if (chunk.usage) {\n if (!stopReasonMessageDelta) {\n stopReasonMessageDelta = {\n type: \"message_delta\",\n delta: {\n stop_reason: \"end_turn\",\n stop_sequence: null,\n },\n usage: {\n input_tokens: chunk.usage?.prompt_tokens || 0,\n output_tokens: chunk.usage?.completion_tokens || 0,\n cache_read_input_tokens:\n chunk.usage?.cache_read_input_tokens || 0,\n },\n };\n } else {\n stopReasonMessageDelta.usage = {\n input_tokens: chunk.usage?.prompt_tokens || 0,\n output_tokens: chunk.usage?.completion_tokens || 0,\n cache_read_input_tokens:\n chunk.usage?.cache_read_input_tokens || 0,\n };\n }\n }\n if (!choice) {\n continue;\n }\n\n if (choice?.delta?.thinking && !isClosed && !hasFinished) {\n // Close any previous content block if open\n if (currentContentBlockIndex >= 0) {\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: currentContentBlockIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n }\n\n if (!isThinkingStarted) {\n const contentBlockStart = {\n type: \"content_block_start\",\n index: contentIndex,\n content_block: { type: \"thinking\", thinking: \"\" },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_start\\ndata: ${JSON.stringify(\n contentBlockStart\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = contentIndex;\n isThinkingStarted = true;\n }\n if (choice.delta.thinking.signature) {\n const thinkingSignature = {\n type: \"content_block_delta\",\n index: contentIndex,\n delta: {\n type: \"signature_delta\",\n signature: choice.delta.thinking.signature,\n },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_delta\\ndata: ${JSON.stringify(\n thinkingSignature\n )}\\n\\n`\n )\n );\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: contentIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n contentIndex++;\n } else if (choice.delta.thinking.content) {\n const thinkingChunk = {\n type: \"content_block_delta\",\n index: contentIndex,\n delta: {\n type: \"thinking_delta\",\n thinking: choice.delta.thinking.content || \"\",\n },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_delta\\ndata: ${JSON.stringify(\n thinkingChunk\n )}\\n\\n`\n )\n );\n }\n }\n\n if (choice?.delta?.content && !isClosed && !hasFinished) {\n contentChunks++;\n\n // Close any previous content block if open and it's not a text content block\n if (currentContentBlockIndex >= 0) {\n // Check if current content block is text type\n const isCurrentTextBlock = hasTextContentStarted;\n if (!isCurrentTextBlock) {\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: currentContentBlockIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n }\n }\n\n if (!hasTextContentStarted && !hasFinished) {\n hasTextContentStarted = true;\n const contentBlockStart = {\n type: \"content_block_start\",\n index: contentIndex,\n content_block: {\n type: \"text\",\n text: \"\",\n },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_start\\ndata: ${JSON.stringify(\n contentBlockStart\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = contentIndex;\n }\n\n if (!isClosed && !hasFinished) {\n const anthropicChunk = {\n type: \"content_block_delta\",\n index: currentContentBlockIndex, // Use current content block index\n delta: {\n type: \"text_delta\",\n text: choice.delta.content,\n },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_delta\\ndata: ${JSON.stringify(\n anthropicChunk\n )}\\n\\n`\n )\n );\n }\n }\n\n if (\n choice?.delta?.annotations?.length &&\n !isClosed &&\n !hasFinished\n ) {\n // Close text content block if open\n if (currentContentBlockIndex >= 0 && hasTextContentStarted) {\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: currentContentBlockIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n hasTextContentStarted = false;\n }\n\n choice?.delta?.annotations.forEach((annotation: any) => {\n contentIndex++;\n const contentBlockStart = {\n type: \"content_block_start\",\n index: contentIndex,\n content_block: {\n type: \"web_search_tool_result\",\n tool_use_id: `srvtoolu_${uuidv4()}`,\n content: [\n {\n type: \"web_search_result\",\n title: annotation.url_citation.title,\n url: annotation.url_citation.url,\n },\n ],\n },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_start\\ndata: ${JSON.stringify(\n contentBlockStart\n )}\\n\\n`\n )\n );\n\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: contentIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n });\n }\n\n if (choice?.delta?.tool_calls && !isClosed && !hasFinished) {\n toolCallChunks++;\n const processedInThisChunk = new Set();\n\n for (const toolCall of choice.delta.tool_calls) {\n if (isClosed) break;\n const toolCallIndex = toolCall.index ?? 0;\n if (processedInThisChunk.has(toolCallIndex)) {\n continue;\n }\n processedInThisChunk.add(toolCallIndex);\n const isUnknownIndex =\n !toolCallIndexToContentBlockIndex.has(toolCallIndex);\n\n if (isUnknownIndex) {\n // Close any previous content block if open\n if (currentContentBlockIndex >= 0) {\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: currentContentBlockIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n }\n\n const newContentBlockIndex = contentIndex;\n toolCallIndexToContentBlockIndex.set(\n toolCallIndex,\n newContentBlockIndex\n );\n contentIndex++; // Increment contentIndex after setting the mapping\n const toolCallId =\n toolCall.id || `call_${Date.now()}_${toolCallIndex}`;\n const toolCallName =\n toolCall.function?.name || `tool_${toolCallIndex}`;\n const contentBlockStart = {\n type: \"content_block_start\",\n index: newContentBlockIndex,\n content_block: {\n type: \"tool_use\",\n id: toolCallId,\n name: toolCallName,\n input: {},\n },\n };\n\n safeEnqueue(\n encoder.encode(\n `event: content_block_start\\ndata: ${JSON.stringify(\n contentBlockStart\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = newContentBlockIndex;\n\n const toolCallInfo = {\n id: toolCallId,\n name: toolCallName,\n arguments: \"\",\n contentBlockIndex: newContentBlockIndex,\n };\n toolCalls.set(toolCallIndex, toolCallInfo);\n } else if (toolCall.id && toolCall.function?.name) {\n const existingToolCall = toolCalls.get(toolCallIndex)!;\n const wasTemporary =\n existingToolCall.id.startsWith(\"call_\") &&\n existingToolCall.name.startsWith(\"tool_\");\n\n if (wasTemporary) {\n existingToolCall.id = toolCall.id;\n existingToolCall.name = toolCall.function.name;\n }\n }\n\n if (\n toolCall.function?.arguments &&\n !isClosed &&\n !hasFinished\n ) {\n const blockIndex =\n toolCallIndexToContentBlockIndex.get(toolCallIndex);\n if (blockIndex === undefined) {\n continue;\n }\n const currentToolCall = toolCalls.get(toolCallIndex);\n if (currentToolCall) {\n currentToolCall.arguments +=\n toolCall.function.arguments;\n }\n\n try {\n const anthropicChunk = {\n type: \"content_block_delta\",\n index: blockIndex, // Use the correct content block index\n delta: {\n type: \"input_json_delta\",\n partial_json: toolCall.function.arguments,\n },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_delta\\ndata: ${JSON.stringify(\n anthropicChunk\n )}\\n\\n`\n )\n );\n } catch (error) {\n try {\n const fixedArgument = toolCall.function.arguments\n .replace(/[\\x00-\\x1F\\x7F-\\x9F]/g, \"\")\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"');\n\n const fixedChunk = {\n type: \"content_block_delta\",\n index: blockIndex, // Use the correct content block index\n delta: {\n type: \"input_json_delta\",\n partial_json: fixedArgument,\n },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_delta\\ndata: ${JSON.stringify(\n fixedChunk\n )}\\n\\n`\n )\n );\n } catch (fixError) {\n console.error(fixError);\n }\n }\n }\n }\n }\n\n if (choice?.finish_reason && !isClosed && !hasFinished) {\n if (contentChunks === 0 && toolCallChunks === 0) {\n console.error(\n \"Warning: No content in the stream response!\"\n );\n }\n\n // Close any remaining open content block\n if (currentContentBlockIndex >= 0) {\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: currentContentBlockIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n }\n\n if (!isClosed) {\n const stopReasonMapping: Record = {\n stop: \"end_turn\",\n length: \"max_tokens\",\n tool_calls: \"tool_use\",\n content_filter: \"stop_sequence\",\n };\n\n const anthropicStopReason =\n stopReasonMapping[choice.finish_reason] || \"end_turn\";\n\n stopReasonMessageDelta = {\n type: \"message_delta\",\n delta: {\n stop_reason: anthropicStopReason,\n stop_sequence: null,\n },\n usage: {\n input_tokens: chunk.usage?.prompt_tokens || 0,\n output_tokens: chunk.usage?.completion_tokens || 0,\n cache_read_input_tokens:\n chunk.usage?.cache_read_input_tokens || 0,\n },\n };\n }\n\n break;\n }\n } catch (parseError: any) {\n this.logger?.error(\n `parseError: ${parseError.name} message: ${parseError.message} stack: ${parseError.stack} data: ${data}`\n );\n }\n }\n }\n safeClose();\n } catch (error) {\n if (!isClosed) {\n try {\n controller.error(error);\n } catch (controllerError) {\n console.error(controllerError);\n }\n }\n } finally {\n if (reader) {\n try {\n reader.releaseLock();\n } catch (releaseError) {\n console.error(releaseError);\n }\n }\n }\n },\n cancel: (reason) => {\n this.logger.debug(`cancle stream: ${reason}`);\n },\n });\n\n return readable;\n }\n\n private convertOpenAIResponseToAnthropic(\n openaiResponse: ChatCompletion\n ): any {\n this.logger.debug({ response: openaiResponse }, `Original OpenAI response`);\n try {\n const choice = openaiResponse.choices[0];\n if (!choice) {\n throw new Error(\"No choices found in OpenAI response\");\n }\n const content: any[] = [];\n if (choice.message.annotations) {\n const id = `srvtoolu_${uuidv4()}`;\n content.push({\n type: \"server_tool_use\",\n id,\n name: \"web_search\",\n input: {\n query: \"\",\n },\n });\n content.push({\n type: \"web_search_tool_result\",\n tool_use_id: id,\n content: choice.message.annotations.map((item) => {\n return {\n type: \"web_search_result\",\n url: item.url_citation.url,\n title: item.url_citation.title,\n };\n }),\n });\n }\n if (choice.message.content) {\n content.push({\n type: \"text\",\n text: choice.message.content,\n });\n }\n if (choice.message.tool_calls && choice.message.tool_calls.length > 0) {\n choice.message.tool_calls.forEach((toolCall, index) => {\n let parsedInput = {};\n try {\n const argumentsStr = toolCall.function.arguments || \"{}\";\n\n if (typeof argumentsStr === \"object\") {\n parsedInput = argumentsStr;\n } else if (typeof argumentsStr === \"string\") {\n parsedInput = JSON.parse(argumentsStr);\n }\n } catch (parseError) {\n parsedInput = { text: toolCall.function.arguments || \"\" };\n }\n\n content.push({\n type: \"tool_use\",\n id: toolCall.id,\n name: toolCall.function.name,\n input: parsedInput,\n });\n });\n }\n\n const result = {\n id: openaiResponse.id,\n type: \"message\",\n role: \"assistant\",\n model: openaiResponse.model,\n content: content,\n stop_reason:\n choice.finish_reason === \"stop\"\n ? \"end_turn\"\n : choice.finish_reason === \"length\"\n ? \"max_tokens\"\n : choice.finish_reason === \"tool_calls\"\n ? \"tool_use\"\n : choice.finish_reason === \"content_filter\"\n ? \"stop_sequence\"\n : \"end_turn\",\n stop_sequence: null,\n usage: {\n input_tokens: openaiResponse.usage?.prompt_tokens || 0,\n output_tokens: openaiResponse.usage?.completion_tokens || 0,\n },\n };\n this.logger.debug(\n { result },\n `Conversion complete, final Anthropic response`\n );\n return result;\n } catch (e) {\n throw createApiError(\n `Provider error: ${JSON.stringify(openaiResponse)}`,\n 500,\n \"provider_error\"\n );\n }\n }\n}\n", "import { UnifiedChatRequest, UnifiedMessage } from \"../types/llm\";\nimport { Content, ContentListUnion, Part, ToolListUnion } from \"@google/genai\";\n\nexport function cleanupParameters(obj: any, keyName?: string): void {\n if (!obj || typeof obj !== \"object\") {\n return;\n }\n\n if (Array.isArray(obj)) {\n obj.forEach((item) => {\n cleanupParameters(item);\n });\n return;\n }\n\n const validFields = new Set([\n \"type\",\n \"format\",\n \"title\",\n \"description\",\n \"nullable\",\n \"enum\",\n \"maxItems\",\n \"minItems\",\n \"properties\",\n \"required\",\n \"minProperties\",\n \"maxProperties\",\n \"minLength\",\n \"maxLength\",\n \"pattern\",\n \"example\",\n \"anyOf\",\n \"propertyOrdering\",\n \"default\",\n \"items\",\n \"minimum\",\n \"maximum\",\n ]);\n\n if (keyName !== \"properties\") {\n Object.keys(obj).forEach((key) => {\n if (!validFields.has(key)) {\n delete obj[key];\n }\n });\n }\n\n if (obj.enum && obj.type !== \"string\") {\n delete obj.enum;\n }\n\n if (\n obj.type === \"string\" &&\n obj.format &&\n ![\"enum\", \"date-time\"].includes(obj.format)\n ) {\n delete obj.format;\n }\n\n Object.keys(obj).forEach((key) => {\n cleanupParameters(obj[key], key);\n });\n}\n\n// Type enum equivalent in JavaScript\nconst Type = {\n TYPE_UNSPECIFIED: \"TYPE_UNSPECIFIED\",\n STRING: \"STRING\",\n NUMBER: \"NUMBER\",\n INTEGER: \"INTEGER\",\n BOOLEAN: \"BOOLEAN\",\n ARRAY: \"ARRAY\",\n OBJECT: \"OBJECT\",\n NULL: \"NULL\",\n};\n\n/**\n * Transform the type field from an array of types to an array of anyOf fields.\n * @param {string[]} typeList - List of types\n * @param {Object} resultingSchema - The schema object to modify\n */\nfunction flattenTypeArrayToAnyOf(typeList: Array, resultingSchema: any): void {\n if (typeList.includes(\"null\")) {\n resultingSchema[\"nullable\"] = true;\n }\n const listWithoutNull = typeList.filter((type) => type !== \"null\");\n\n if (listWithoutNull.length === 1) {\n const upperCaseType = listWithoutNull[0].toUpperCase();\n resultingSchema[\"type\"] = Object.values(Type).includes(upperCaseType)\n ? upperCaseType\n : Type.TYPE_UNSPECIFIED;\n } else {\n resultingSchema[\"anyOf\"] = [];\n for (const i of listWithoutNull) {\n const upperCaseType = i.toUpperCase();\n resultingSchema[\"anyOf\"].push({\n type: Object.values(Type).includes(upperCaseType)\n ? upperCaseType\n : Type.TYPE_UNSPECIFIED,\n });\n }\n }\n}\n\n/**\n * Process a JSON schema to make it compatible with the GenAI API\n * @param {Object} _jsonSchema - The JSON schema to process\n * @returns {Object} - The processed schema\n */\nfunction processJsonSchema(_jsonSchema: any): any {\n const genAISchema = {};\n const schemaFieldNames = [\"items\"];\n const listSchemaFieldNames = [\"anyOf\"];\n const dictSchemaFieldNames = [\"properties\"];\n\n if (_jsonSchema[\"type\"] && _jsonSchema[\"anyOf\"]) {\n throw new Error(\"type and anyOf cannot be both populated.\");\n }\n\n /*\n This is to handle the nullable array or object. The _jsonSchema will\n be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The\n logic is to check if anyOf has 2 elements and one of the element is null,\n if so, the anyOf field is unnecessary, so we need to get rid of the anyOf\n field and make the schema nullable. Then use the other element as the new\n _jsonSchema for processing. This is because the backend doesn't have a null\n type.\n */\n const incomingAnyOf = _jsonSchema[\"anyOf\"];\n if (\n incomingAnyOf != null &&\n Array.isArray(incomingAnyOf) &&\n incomingAnyOf.length == 2\n ) {\n if (incomingAnyOf[0] && incomingAnyOf[0][\"type\"] === \"null\") {\n genAISchema[\"nullable\"] = true;\n _jsonSchema = incomingAnyOf[1];\n } else if (incomingAnyOf[1] && incomingAnyOf[1][\"type\"] === \"null\") {\n genAISchema[\"nullable\"] = true;\n _jsonSchema = incomingAnyOf[0];\n }\n }\n\n if (_jsonSchema[\"type\"] && Array.isArray(_jsonSchema[\"type\"])) {\n flattenTypeArrayToAnyOf(_jsonSchema[\"type\"], genAISchema);\n }\n\n for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) {\n // Skip if the fieldValue is undefined or null.\n if (fieldValue == null) {\n continue;\n }\n\n if (fieldName == \"type\") {\n if (fieldValue === \"null\") {\n throw new Error(\n \"type: null can not be the only possible type for the field.\"\n );\n }\n if (Array.isArray(fieldValue)) {\n // we have already handled the type field with array of types in the\n // beginning of this function.\n continue;\n }\n const upperCaseValue = fieldValue.toUpperCase();\n genAISchema[\"type\"] = Object.values(Type).includes(upperCaseValue)\n ? upperCaseValue\n : Type.TYPE_UNSPECIFIED;\n } else if (schemaFieldNames.includes(fieldName)) {\n genAISchema[fieldName] = processJsonSchema(fieldValue);\n } else if (listSchemaFieldNames.includes(fieldName)) {\n const listSchemaFieldValue = [];\n for (const item of fieldValue) {\n if (item[\"type\"] == \"null\") {\n genAISchema[\"nullable\"] = true;\n continue;\n }\n listSchemaFieldValue.push(processJsonSchema(item));\n }\n genAISchema[fieldName] = listSchemaFieldValue;\n } else if (dictSchemaFieldNames.includes(fieldName)) {\n const dictSchemaFieldValue = {};\n for (const [key, value] of Object.entries(fieldValue)) {\n dictSchemaFieldValue[key] = processJsonSchema(value);\n }\n genAISchema[fieldName] = dictSchemaFieldValue;\n } else {\n // additionalProperties is not included in JSONSchema, skipping it.\n if (fieldName === \"additionalProperties\") {\n continue;\n }\n genAISchema[fieldName] = fieldValue;\n }\n }\n return genAISchema;\n}\n\n/**\n * Transform a tool object\n * @param {Object} tool - The tool object to transform\n * @returns {Object} - The transformed tool object\n */\nexport function tTool(tool: any): any {\n if (tool.functionDeclarations) {\n for (const functionDeclaration of tool.functionDeclarations) {\n if (functionDeclaration.parameters) {\n if (!Object.keys(functionDeclaration.parameters).includes(\"$schema\")) {\n functionDeclaration.parameters = processJsonSchema(\n functionDeclaration.parameters\n );\n } else {\n if (!functionDeclaration.parametersJsonSchema) {\n functionDeclaration.parametersJsonSchema =\n functionDeclaration.parameters;\n delete functionDeclaration.parameters;\n }\n }\n }\n if (functionDeclaration.response) {\n if (!Object.keys(functionDeclaration.response).includes(\"$schema\")) {\n functionDeclaration.response = processJsonSchema(\n functionDeclaration.response\n );\n } else {\n if (!functionDeclaration.responseJsonSchema) {\n functionDeclaration.responseJsonSchema =\n functionDeclaration.response;\n delete functionDeclaration.response;\n }\n }\n }\n }\n }\n return tool;\n}\n\nexport function buildRequestBody(\n request: UnifiedChatRequest\n): Record {\n const tools = [];\n const functionDeclarations = request.tools\n ?.filter((tool) => tool.function.name !== \"web_search\")\n ?.map((tool) => {\n return {\n name: tool.function.name,\n description: tool.function.description,\n parametersJsonSchema: tool.function.parameters,\n };\n });\n if (functionDeclarations?.length) {\n tools.push(\n tTool({\n functionDeclarations,\n })\n );\n }\n const webSearch = request.tools?.find(\n (tool) => tool.function.name === \"web_search\"\n );\n if (webSearch) {\n tools.push({\n googleSearch: {},\n });\n }\n\n const contents = request.messages.map((message: UnifiedMessage) => {\n let role: \"user\" | \"model\";\n if (message.role === \"assistant\") {\n role = \"model\";\n } else if ([\"user\", \"system\", \"tool\"].includes(message.role)) {\n role = \"user\";\n } else {\n role = \"user\"; // Default to user if role is not recognized\n }\n const parts = [];\n if (typeof message.content === \"string\") {\n parts.push({\n text: message.content,\n });\n } else if (Array.isArray(message.content)) {\n parts.push(\n ...message.content.map((content) => {\n if (content.type === \"text\") {\n return {\n text: content.text || \"\",\n };\n }\n if (content.type === \"image_url\") {\n if (content.image_url.url.startsWith(\"http\")) {\n return {\n file_data: {\n mime_type: content.media_type,\n file_uri: content.image_url.url,\n },\n };\n } else {\n return {\n inlineData: {\n mime_type: content.media_type,\n data: content.image_url.url,\n },\n };\n }\n }\n })\n );\n }\n\n if (Array.isArray(message.tool_calls)) {\n parts.push(\n ...message.tool_calls.map((toolCall) => {\n return {\n functionCall: {\n id:\n toolCall.id ||\n `tool_${Math.random().toString(36).substring(2, 15)}`,\n name: toolCall.function.name,\n args: JSON.parse(toolCall.function.arguments || \"{}\"),\n },\n };\n })\n );\n }\n return {\n role,\n parts,\n };\n });\n\n const body = {\n contents,\n tools: tools.length ? tools : undefined,\n };\n\n if (request.tool_choice) {\n const toolConfig = {\n functionCallingConfig: {},\n };\n if (request.tool_choice === \"auto\") {\n toolConfig.functionCallingConfig.mode = \"auto\";\n } else if (request.tool_choice === \"none\") {\n toolConfig.functionCallingConfig.mode = \"none\";\n } else if (request.tool_choice === \"required\") {\n toolConfig.functionCallingConfig.mode = \"any\";\n } else if (request.tool_choice?.function?.name) {\n toolConfig.functionCallingConfig.mode = \"any\";\n toolConfig.functionCallingConfig.allowedFunctionNames = [\n request.tool_choice?.function?.name,\n ];\n }\n body.toolConfig = toolConfig;\n }\n\n return body;\n}\n\nexport function transformRequestOut(\n request: Record\n): UnifiedChatRequest {\n const contents: ContentListUnion = request.contents;\n const tools: ToolListUnion = request.tools;\n const model: string = request.model;\n const max_tokens: number | undefined = request.max_tokens;\n const temperature: number | undefined = request.temperature;\n const stream: boolean | undefined = request.stream;\n const tool_choice: \"auto\" | \"none\" | string | undefined = request.tool_choice;\n\n const unifiedChatRequest: UnifiedChatRequest = {\n messages: [],\n model,\n max_tokens,\n temperature,\n stream,\n tool_choice,\n };\n\n if (Array.isArray(contents)) {\n contents.forEach((content) => {\n if (typeof content === \"string\") {\n unifiedChatRequest.messages.push({\n role: \"user\",\n content,\n });\n } else if (typeof (content as Part).text === \"string\") {\n unifiedChatRequest.messages.push({\n role: \"user\",\n content: (content as Part).text || null,\n });\n } else if ((content as Content).role === \"user\") {\n unifiedChatRequest.messages.push({\n role: \"user\",\n content:\n (content as Content)?.parts?.map((part: Part) => ({\n type: \"text\",\n text: part.text || \"\",\n })) || [],\n });\n } else if ((content as Content).role === \"model\") {\n unifiedChatRequest.messages.push({\n role: \"assistant\",\n content:\n (content as Content)?.parts?.map((part: Part) => ({\n type: \"text\",\n text: part.text || \"\",\n })) || [],\n });\n }\n });\n }\n\n if (Array.isArray(tools)) {\n unifiedChatRequest.tools = [];\n tools.forEach((tool) => {\n if (Array.isArray(tool.functionDeclarations)) {\n tool.functionDeclarations.forEach((tool) => {\n unifiedChatRequest.tools!.push({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n },\n });\n });\n }\n });\n }\n\n return unifiedChatRequest;\n}\n\nexport async function transformResponseOut(\n response: Response,\n providerName: string,\n logger?: any\n): Promise {\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse: any = await response.json();\n const tool_calls =\n jsonResponse.candidates[0].content?.parts\n ?.filter((part: Part) => part.functionCall)\n ?.map((part: Part) => ({\n id:\n part.functionCall?.id ||\n `tool_${Math.random().toString(36).substring(2, 15)}`,\n type: \"function\",\n function: {\n name: part.functionCall?.name,\n arguments: JSON.stringify(part.functionCall?.args || {}),\n },\n })) || [];\n const res = {\n id: jsonResponse.responseId,\n choices: [\n {\n finish_reason:\n (\n jsonResponse.candidates[0].finishReason as string\n )?.toLowerCase() || null,\n index: 0,\n message: {\n content:\n jsonResponse.candidates[0].content?.parts\n ?.filter((part: Part) => part.text)\n ?.map((part: Part) => part.text)\n ?.join(\"\\n\") || \"\",\n role: \"assistant\",\n tool_calls: tool_calls.length > 0 ? tool_calls : undefined,\n },\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n model: jsonResponse.modelVersion,\n object: \"chat.completion\",\n usage: {\n completion_tokens: jsonResponse.usageMetadata.candidatesTokenCount,\n prompt_tokens: jsonResponse.usageMetadata.promptTokenCount,\n cached_content_token_count:\n jsonResponse.usageMetadata.cachedContentTokenCount || null,\n total_tokens: jsonResponse.usageMetadata.totalTokenCount,\n },\n };\n return new Response(JSON.stringify(res), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n\n const processLine = (\n line: string,\n controller: ReadableStreamDefaultController\n ) => {\n if (line.startsWith(\"data: \")) {\n const chunkStr = line.slice(6).trim();\n if (chunkStr) {\n logger?.debug({ chunkStr }, `${providerName} chunk:`);\n try {\n const chunk = JSON.parse(chunkStr);\n\n // Check if chunk has valid structure\n if (!chunk.candidates || !chunk.candidates[0]) {\n log(`Invalid chunk structure:`, chunkStr);\n return;\n }\n\n const candidate = chunk.candidates[0];\n const parts = candidate.content?.parts || [];\n\n const tool_calls = parts\n .filter((part: Part) => part.functionCall)\n .map((part: Part) => ({\n id:\n part.functionCall?.id ||\n `tool_${Math.random().toString(36).substring(2, 15)}`,\n type: \"function\",\n function: {\n name: part.functionCall?.name,\n arguments: JSON.stringify(part.functionCall?.args || {}),\n },\n }));\n\n const textContent = parts\n .filter((part: Part) => part.text)\n .map((part: Part) => part.text)\n .join(\"\\n\");\n\n const res = {\n choices: [\n {\n delta: {\n role: \"assistant\",\n content: textContent || \"\",\n tool_calls: tool_calls.length > 0 ? tool_calls : undefined,\n },\n finish_reason: candidate.finishReason?.toLowerCase() || null,\n index: candidate.index || (tool_calls.length > 0 ? 1 : 0),\n logprobs: null,\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n id: chunk.responseId || \"\",\n model: chunk.modelVersion || \"\",\n object: \"chat.completion.chunk\",\n system_fingerprint: \"fp_a49d71b8a1\",\n usage: {\n completion_tokens:\n chunk.usageMetadata?.candidatesTokenCount || 0,\n prompt_tokens: chunk.usageMetadata?.promptTokenCount || 0,\n cached_content_token_count:\n chunk.usageMetadata?.cachedContentTokenCount || null,\n total_tokens: chunk.usageMetadata?.totalTokenCount || 0,\n },\n };\n if (candidate?.groundingMetadata?.groundingChunks?.length) {\n res.choices[0].delta.annotations =\n candidate.groundingMetadata.groundingChunks.map(\n (groundingChunk, index) => {\n const support =\n candidate?.groundingMetadata?.groundingSupports?.filter(\n (item) => item.groundingChunkIndices?.includes(index)\n );\n return {\n type: \"url_citation\",\n url_citation: {\n url: groundingChunk?.web?.uri || \"\",\n title: groundingChunk?.web?.title || \"\",\n content: support?.[0]?.segment?.text || \"\",\n start_index: support?.[0]?.segment?.startIndex || 0,\n end_index: support?.[0]?.segment?.endIndex || 0,\n },\n };\n }\n );\n }\n controller.enqueue(\n encoder.encode(`data: ${JSON.stringify(res)}\\n\\n`)\n );\n } catch (error: any) {\n logger?.error(\n `Error parsing ${providerName} stream chunk`,\n chunkStr,\n error.message\n );\n }\n }\n }\n };\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n let buffer = \"\";\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n if (buffer) {\n processLine(buffer, controller);\n }\n break;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n processLine(line, controller);\n }\n }\n } catch (error) {\n controller.error(error);\n } finally {\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n }\n return response;\n}\n", "import { LLMProvider, UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer } from \"../types/transformer\";\nimport {\n buildRequestBody,\n transformRequestOut,\n transformResponseOut,\n} from \"../utils/gemini.util\";\n\nexport class GeminiTransformer implements Transformer {\n name = \"gemini\";\n\n endPoint = \"/v1beta/models/:modelAndAction\";\n\n async transformRequestIn(\n request: UnifiedChatRequest,\n provider: LLMProvider\n ): Promise> {\n return {\n body: buildRequestBody(request),\n config: {\n url: new URL(\n `./${request.model}:${\n request.stream ? \"streamGenerateContent?alt=sse\" : \"generateContent\"\n }`,\n provider.baseUrl\n ),\n headers: {\n \"x-goog-api-key\": provider.apiKey,\n Authorization: undefined,\n },\n },\n };\n }\n\n transformRequestOut = transformRequestOut;\n\n async transformResponseOut(response: Response): Promise {\n return transformResponseOut(response, this.name, this.logger);\n }\n}\n", "import { LLMProvider, UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer } from \"../types/transformer\";\nimport {\n buildRequestBody,\n transformRequestOut,\n transformResponseOut,\n} from \"../utils/gemini.util\";\n\nasync function getAccessToken(): Promise {\n try {\n const { GoogleAuth } = await import('google-auth-library');\n\n const auth = new GoogleAuth({\n scopes: ['https://www.googleapis.com/auth/cloud-platform']\n });\n\n const client = await auth.getClient();\n const accessToken = await client.getAccessToken();\n return accessToken.token || '';\n } catch (error) {\n console.error('Error getting access token:', error);\n throw new Error('Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:\\n' +\n '1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file\\n' +\n '2. Run \"gcloud auth application-default login\"\\n' +\n '3. Use Google Cloud environment with default service account');\n }\n}\n\nexport class VertexGeminiTransformer implements Transformer {\n name = \"vertex-gemini\";\n\n async transformRequestIn(\n request: UnifiedChatRequest,\n provider: LLMProvider\n ): Promise> {\n let projectId = process.env.GOOGLE_CLOUD_PROJECT;\n const location = process.env.GOOGLE_CLOUD_LOCATION || 'us-central1';\n\n if (!projectId && process.env.GOOGLE_APPLICATION_CREDENTIALS) {\n try {\n const fs = await import('fs');\n const keyContent = fs.readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS, 'utf8');\n const credentials = JSON.parse(keyContent);\n if (credentials && credentials.project_id) {\n projectId = credentials.project_id;\n }\n } catch (error) {\n console.error('Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:', error);\n }\n }\n\n if (!projectId) {\n throw new Error('Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.');\n }\n\n const accessToken = await getAccessToken();\n return {\n body: buildRequestBody(request),\n config: {\n url: new URL(\n `./v1beta1/projects/${projectId}/locations/${location}/publishers/google/models/${request.model}:${request.stream ? \"streamGenerateContent\" : \"generateContent\"}`,\n provider.baseUrl.endsWith('/') ? provider.baseUrl : provider.baseUrl + '/' || `https://${location}-aiplatform.googleapis.com`\n ),\n headers: {\n \"Authorization\": `Bearer ${accessToken}`,\n \"x-goog-api-key\": undefined,\n },\n },\n };\n }\n\n transformRequestOut = transformRequestOut;\n\n async transformResponseOut(response: Response): Promise {\n return transformResponseOut(response, this.name);\n }\n}\n", "import { UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer } from \"../types/transformer\";\n\nexport class DeepseekTransformer implements Transformer {\n name = \"deepseek\";\n\n async transformRequestIn(request: UnifiedChatRequest): Promise {\n if (request.max_tokens && request.max_tokens > 8192) {\n request.max_tokens = 8192; // DeepSeek has a max token limit of 8192\n }\n return request;\n }\n\n async transformResponseOut(response: Response): Promise {\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse = await response.json();\n // Handle non-streaming response if needed\n return new Response(JSON.stringify(jsonResponse), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n let reasoningContent = \"\";\n let isReasoningComplete = false;\n let buffer = \"\"; // \u7528\u4E8E\u7F13\u51B2\u4E0D\u5B8C\u6574\u7684\u6570\u636E\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n const processBuffer = (\n buffer: string,\n controller: ReadableStreamDefaultController,\n encoder: typeof TextEncoder\n ) => {\n const lines = buffer.split(\"\\n\");\n for (const line of lines) {\n if (line.trim()) {\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n };\n\n const processLine = (\n line: string,\n context: {\n controller: ReadableStreamDefaultController;\n encoder: typeof TextEncoder;\n reasoningContent: () => string;\n appendReasoningContent: (content: string) => void;\n isReasoningComplete: () => boolean;\n setReasoningComplete: (val: boolean) => void;\n }\n ) => {\n const { controller, encoder } = context;\n\n if (\n line.startsWith(\"data: \") &&\n line.trim() !== \"data: [DONE]\"\n ) {\n try {\n const data = JSON.parse(line.slice(6));\n\n // Extract reasoning_content from delta\n if (data.choices?.[0]?.delta?.reasoning_content) {\n context.appendReasoningContent(\n data.choices[0].delta.reasoning_content\n );\n const thinkingChunk = {\n ...data,\n choices: [\n {\n ...data.choices[0],\n delta: {\n ...data.choices[0].delta,\n thinking: {\n content: data.choices[0].delta.reasoning_content,\n },\n },\n },\n ],\n };\n delete thinkingChunk.choices[0].delta.reasoning_content;\n const thinkingLine = `data: ${JSON.stringify(\n thinkingChunk\n )}\\n\\n`;\n controller.enqueue(encoder.encode(thinkingLine));\n return;\n }\n\n // Check if reasoning is complete (when delta has content but no reasoning_content)\n if (\n data.choices?.[0]?.delta?.content &&\n context.reasoningContent() &&\n !context.isReasoningComplete()\n ) {\n context.setReasoningComplete(true);\n const signature = Date.now().toString();\n\n // Create a new chunk with thinking block\n const thinkingChunk = {\n ...data,\n choices: [\n {\n ...data.choices[0],\n delta: {\n ...data.choices[0].delta,\n content: null,\n thinking: {\n content: context.reasoningContent(),\n signature: signature,\n },\n },\n },\n ],\n };\n delete thinkingChunk.choices[0].delta.reasoning_content;\n // Send the thinking chunk\n const thinkingLine = `data: ${JSON.stringify(\n thinkingChunk\n )}\\n\\n`;\n controller.enqueue(encoder.encode(thinkingLine));\n }\n\n if (data.choices[0]?.delta?.reasoning_content) {\n delete data.choices[0].delta.reasoning_content;\n }\n\n // Send the modified chunk\n if (\n data.choices?.[0]?.delta &&\n Object.keys(data.choices[0].delta).length > 0\n ) {\n if (context.isReasoningComplete()) {\n data.choices[0].index++;\n }\n const modifiedLine = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n }\n } catch (e) {\n // If JSON parsing fails, pass through the original line\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n } else {\n // Pass through non-data lines (like [DONE])\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5269\u4F59\u7684\u6570\u636E\n if (buffer.trim()) {\n processBuffer(buffer, controller, encoder);\n }\n break;\n }\n\n const chunk = decoder.decode(value, { stream: true });\n buffer += chunk;\n\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5B8C\u6574\u7684\u6570\u636E\u884C\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\"; // \u6700\u540E\u4E00\u884C\u53EF\u80FD\u4E0D\u5B8C\u6574\uFF0C\u4FDD\u7559\u5728\u7F13\u51B2\u533A\n\n for (const line of lines) {\n if (!line.trim()) continue;\n\n try {\n processLine(line, {\n controller,\n encoder,\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) =>\n (reasoningContent += content),\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) => (isReasoningComplete = val),\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n } catch (error) {\n console.error(\"Stream error:\", error);\n controller.error(error);\n } finally {\n try {\n reader.releaseLock();\n } catch (e) {\n console.error(\"Error releasing reader lock:\", e);\n }\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: {\n \"Content-Type\": response.headers.get(\"Content-Type\") || \"text/plain\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n }\n\n return response;\n }\n}\n", "import { UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer } from \"../types/transformer\";\n\nexport class TooluseTransformer implements Transformer {\n name = \"tooluse\";\n\n transformRequestIn(request: UnifiedChatRequest): UnifiedChatRequest {\n request.messages.push({\n role: \"system\",\n content: `Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the \\`ExitTool\\` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.`,\n });\n if (request.tools?.length) {\n request.tool_choice = \"required\";\n request.tools.push({\n type: \"function\",\n function: {\n name: \"ExitTool\",\n description: `Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.\nIMPORTANT: Before using this tool, ensure that none of the available tools are applicable to the current task. You must evaluate all available options \u2014 only if no suitable tool can help you complete the task should you use ExitTool to terminate tool mode.\nExamples:\n1. Task: \"Use a tool to summarize this document\" \u2014 Do not use ExitTool if a summarization tool is available.\n2. Task: \"What\u2019s the weather today?\" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,\n parameters: {\n type: \"object\",\n properties: {\n response: {\n type: \"string\",\n description:\n \"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way.\",\n },\n },\n required: [\"response\"],\n },\n },\n });\n }\n return request;\n }\n\n async transformResponseOut(response: Response): Promise {\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse = await response.json();\n if (\n jsonResponse?.choices?.[0]?.message.tool_calls?.length &&\n jsonResponse?.choices?.[0]?.message.tool_calls[0]?.function?.name ===\n \"ExitTool\"\n ) {\n const toolCall = jsonResponse?.choices[0]?.message.tool_calls[0];\n const toolArguments = JSON.parse(toolCall.function.arguments || \"{}\");\n jsonResponse.choices[0].message.content = toolArguments.response || \"\";\n delete jsonResponse.choices[0].message.tool_calls;\n }\n\n // Handle non-streaming response if needed\n return new Response(JSON.stringify(jsonResponse), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n let exitToolIndex = -1;\n let exitToolResponse = \"\";\n let buffer = \"\"; // \u7528\u4E8E\u7F13\u51B2\u4E0D\u5B8C\u6574\u7684\u6570\u636E\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n\n const processBuffer = (\n buffer: string,\n controller: ReadableStreamDefaultController,\n encoder: TextEncoder\n ) => {\n const lines = buffer.split(\"\\n\");\n for (const line of lines) {\n if (line.trim()) {\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n };\n\n const processLine = (\n line: string,\n context: {\n controller: ReadableStreamDefaultController;\n encoder: TextEncoder;\n exitToolIndex: () => number;\n setExitToolIndex: (val: number) => void;\n exitToolResponse: () => string;\n appendExitToolResponse: (content: string) => void;\n }\n ) => {\n const {\n controller,\n encoder,\n exitToolIndex,\n setExitToolIndex,\n appendExitToolResponse,\n } = context;\n\n if (\n line.startsWith(\"data: \") &&\n line.trim() !== \"data: [DONE]\"\n ) {\n try {\n const data = JSON.parse(line.slice(6));\n\n if (data.choices[0]?.delta?.tool_calls?.length) {\n const toolCall = data.choices[0].delta.tool_calls[0];\n\n if (toolCall.function?.name === \"ExitTool\") {\n setExitToolIndex(toolCall.index);\n return;\n } else if (\n exitToolIndex() > -1 &&\n toolCall.index === exitToolIndex() &&\n toolCall.function.arguments\n ) {\n appendExitToolResponse(toolCall.function.arguments);\n try {\n const response = JSON.parse(context.exitToolResponse());\n data.choices = [\n {\n delta: {\n role: \"assistant\",\n content: response.response || \"\",\n },\n },\n ];\n const modifiedLine = `data: ${JSON.stringify(\n data\n )}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n } catch (e) {}\n return;\n }\n }\n\n if (\n data.choices?.[0]?.delta &&\n Object.keys(data.choices[0].delta).length > 0\n ) {\n const modifiedLine = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n }\n } catch (e) {\n // If JSON parsing fails, pass through the original line\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n } else {\n // Pass through non-data lines (like [DONE])\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n if (buffer.trim()) {\n processBuffer(buffer, controller, encoder);\n }\n break;\n }\n const chunk = decoder.decode(value, { stream: true });\n buffer += chunk;\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n for (const line of lines) {\n if (!line.trim()) continue;\n try {\n processLine(line, {\n controller,\n encoder,\n exitToolIndex: () => exitToolIndex,\n setExitToolIndex: (val) => (exitToolIndex = val),\n exitToolResponse: () => exitToolResponse,\n appendExitToolResponse: (content) =>\n (exitToolResponse += content),\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n } catch (error) {\n console.error(\"Stream error:\", error);\n controller.error(error);\n } finally {\n try {\n reader.releaseLock();\n } catch (e) {\n console.error(\"Error releasing reader lock:\", e);\n }\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n }\n\n return response;\n }\n}\n", "import { UnifiedChatRequest } from \"@/types/llm\";\nimport { Transformer, TransformerOptions } from \"../types/transformer\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nexport class OpenrouterTransformer implements Transformer {\n static TransformerName = \"openrouter\";\n\n constructor(private readonly options?: TransformerOptions) {}\n\n async transformRequestIn(\n request: UnifiedChatRequest\n ): Promise {\n if (!request.model.includes(\"claude\")) {\n request.messages.forEach((msg) => {\n if (Array.isArray(msg.content)) {\n msg.content.forEach((item: any) => {\n if (item.cache_control) {\n delete item.cache_control;\n }\n if (item.type === \"image_url\") {\n if (!item.image_url.url.startsWith(\"http\")) {\n item.image_url.url = `data:${item.media_type};base64,${item.image_url.url}`;\n }\n delete item.media_type;\n }\n });\n } else if (msg.cache_control) {\n delete msg.cache_control;\n }\n });\n } else {\n request.messages.forEach((msg) => {\n if (Array.isArray(msg.content)) {\n msg.content.forEach((item: any) => {\n if (item.type === \"image_url\") {\n if (!item.image_url.url.startsWith(\"http\")) {\n item.image_url.url = `data:${item.media_type};base64,${item.image_url.url}`;\n }\n delete item.media_type;\n }\n });\n }\n });\n }\n Object.assign(request, this.options || {});\n return request;\n }\n\n async transformResponseOut(response: Response): Promise {\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse = await response.json();\n return new Response(JSON.stringify(jsonResponse), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n\n let hasTextContent = false;\n let reasoningContent = \"\";\n let isReasoningComplete = false;\n let hasToolCall = false;\n let buffer = \"\"; // \u7528\u4E8E\u7F13\u51B2\u4E0D\u5B8C\u6574\u7684\u6570\u636E\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n const processBuffer = (\n buffer: string,\n controller: ReadableStreamDefaultController,\n encoder: TextEncoder\n ) => {\n const lines = buffer.split(\"\\n\");\n for (const line of lines) {\n if (line.trim()) {\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n };\n\n const processLine = (\n line: string,\n context: {\n controller: ReadableStreamDefaultController;\n encoder: TextEncoder;\n hasTextContent: () => boolean;\n setHasTextContent: (val: boolean) => void;\n reasoningContent: () => string;\n appendReasoningContent: (content: string) => void;\n isReasoningComplete: () => boolean;\n setReasoningComplete: (val: boolean) => void;\n }\n ) => {\n const { controller, encoder } = context;\n\n if (line.startsWith(\"data: \") && line.trim() !== \"data: [DONE]\") {\n const jsonStr = line.slice(6);\n try {\n const data = JSON.parse(jsonStr);\n if (data.usage) {\n this.logger?.debug(\n { usage: data.usage, hasToolCall },\n \"usage\"\n );\n data.choices[0].finish_reason = hasToolCall\n ? \"tool_calls\"\n : \"stop\";\n }\n\n if (data.choices?.[0]?.finish_reason === \"error\") {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({\n error: data.choices?.[0].error,\n })}\\n\\n`\n )\n );\n }\n\n if (\n data.choices?.[0]?.delta?.content &&\n !context.hasTextContent()\n ) {\n context.setHasTextContent(true);\n }\n\n // Extract reasoning_content from delta\n if (data.choices?.[0]?.delta?.reasoning) {\n context.appendReasoningContent(\n data.choices[0].delta.reasoning\n );\n const thinkingChunk = {\n ...data,\n choices: [\n {\n ...data.choices?.[0],\n delta: {\n ...data.choices[0].delta,\n thinking: {\n content: data.choices[0].delta.reasoning,\n },\n },\n },\n ],\n };\n if (thinkingChunk.choices?.[0]?.delta) {\n delete thinkingChunk.choices[0].delta.reasoning;\n }\n const thinkingLine = `data: ${JSON.stringify(\n thinkingChunk\n )}\\n\\n`;\n controller.enqueue(encoder.encode(thinkingLine));\n return;\n }\n\n // Check if reasoning is complete\n if (\n data.choices?.[0]?.delta?.content &&\n context.reasoningContent() &&\n !context.isReasoningComplete()\n ) {\n context.setReasoningComplete(true);\n const signature = Date.now().toString();\n\n const thinkingChunk = {\n ...data,\n choices: [\n {\n ...data.choices?.[0],\n delta: {\n ...data.choices[0].delta,\n content: null,\n thinking: {\n content: context.reasoningContent(),\n signature: signature,\n },\n },\n },\n ],\n };\n if (thinkingChunk.choices?.[0]?.delta) {\n delete thinkingChunk.choices[0].delta.reasoning;\n }\n const thinkingLine = `data: ${JSON.stringify(\n thinkingChunk\n )}\\n\\n`;\n controller.enqueue(encoder.encode(thinkingLine));\n }\n\n if (data.choices?.[0]?.delta?.reasoning) {\n delete data.choices[0].delta.reasoning;\n }\n if (\n data.choices?.[0]?.delta?.tool_calls?.length &&\n !Number.isNaN(\n parseInt(data.choices?.[0]?.delta?.tool_calls[0].id, 10)\n )\n ) {\n data.choices?.[0]?.delta?.tool_calls.forEach((tool: any) => {\n tool.id = `call_${uuidv4()}`;\n });\n }\n\n if (\n data.choices?.[0]?.delta?.tool_calls?.length &&\n !hasToolCall\n ) {\n hasToolCall = true;\n }\n\n if (\n data.choices?.[0]?.delta?.tool_calls?.length &&\n context.hasTextContent()\n ) {\n if (typeof data.choices[0].index === \"number\") {\n data.choices[0].index += 1;\n } else {\n data.choices[0].index = 1;\n }\n }\n\n const modifiedLine = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n } catch (e) {\n // \u5982\u679CJSON\u89E3\u6790\u5931\u8D25\uFF0C\u53EF\u80FD\u662F\u6570\u636E\u4E0D\u5B8C\u6574\uFF0C\u5C06\u539F\u59CB\u884C\u4F20\u9012\u4E0B\u53BB\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n } else {\n // Pass through non-data lines (like [DONE])\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5269\u4F59\u7684\u6570\u636E\n if (buffer.trim()) {\n processBuffer(buffer, controller, encoder);\n }\n break;\n }\n\n // \u68C0\u67E5value\u662F\u5426\u6709\u6548\n if (!value || value.length === 0) {\n continue;\n }\n\n let chunk;\n try {\n chunk = decoder.decode(value, { stream: true });\n } catch (decodeError) {\n console.warn(\"Failed to decode chunk\", decodeError);\n continue;\n }\n\n if (chunk.length === 0) {\n continue;\n }\n\n buffer += chunk;\n\n // \u5982\u679C\u7F13\u51B2\u533A\u8FC7\u5927\uFF0C\u8FDB\u884C\u5904\u7406\u907F\u514D\u5185\u5B58\u6CC4\u6F0F\n if (buffer.length > 1000000) {\n // 1MB \u9650\u5236\n console.warn(\n \"Buffer size exceeds limit, processing partial data\"\n );\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.trim()) {\n try {\n processLine(line, {\n controller,\n encoder,\n hasTextContent: () => hasTextContent,\n setHasTextContent: (val) => (hasTextContent = val),\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) =>\n (reasoningContent += content),\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) =>\n (isReasoningComplete = val),\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n continue;\n }\n\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5B8C\u6574\u7684\u6570\u636E\u884C\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\"; // \u6700\u540E\u4E00\u884C\u53EF\u80FD\u4E0D\u5B8C\u6574\uFF0C\u4FDD\u7559\u5728\u7F13\u51B2\u533A\n\n for (const line of lines) {\n if (!line.trim()) continue;\n\n try {\n processLine(line, {\n controller,\n encoder,\n hasTextContent: () => hasTextContent,\n setHasTextContent: (val) => (hasTextContent = val),\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) =>\n (reasoningContent += content),\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) => (isReasoningComplete = val),\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n } catch (error) {\n console.error(\"Stream error:\", error);\n controller.error(error);\n } finally {\n try {\n reader.releaseLock();\n } catch (e) {\n console.error(\"Error releasing reader lock:\", e);\n }\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n }\n\n return response;\n }\n}\n", "import { UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer, TransformerOptions } from \"../types/transformer\";\n\nexport class MaxTokenTransformer implements Transformer {\n static TransformerName = \"maxtoken\";\n max_tokens: number;\n\n constructor(private readonly options?: TransformerOptions) {\n this.max_tokens = this.options?.max_tokens;\n }\n\n async transformRequestIn(request: UnifiedChatRequest): Promise {\n if (request.max_tokens && request.max_tokens > this.max_tokens) {\n request.max_tokens = this.max_tokens;\n }\n return request;\n }\n}\n", "import { MessageContent, TextContent, UnifiedChatRequest } from \"@/types/llm\";\nimport { Transformer } from \"../types/transformer\";\nimport { v4 as uuidv4 } from \"uuid\"\n\nexport class GroqTransformer implements Transformer {\n name = \"groq\";\n\n async transformRequestIn(request: UnifiedChatRequest): Promise {\n request.messages.forEach(msg => {\n if (Array.isArray(msg.content)) {\n (msg.content as MessageContent[]).forEach((item) => {\n if ((item as TextContent).cache_control) {\n delete (item as TextContent).cache_control;\n }\n });\n } else if (msg.cache_control) {\n delete msg.cache_control;\n }\n })\n if (Array.isArray(request.tools)) {\n request.tools.forEach(tool => {\n delete tool.function.parameters.$schema;\n })\n }\n return request\n }\n\n async transformResponseOut(response: Response): Promise {\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse = await response.json();\n return new Response(JSON.stringify(jsonResponse), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n\n let hasTextContent = false;\n let reasoningContent = \"\";\n let isReasoningComplete = false;\n let buffer = \"\"; // \u7528\u4E8E\u7F13\u51B2\u4E0D\u5B8C\u6574\u7684\u6570\u636E\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n const processBuffer = (buffer: string, controller: ReadableStreamDefaultController, encoder: InstanceType) => {\n const lines = buffer.split(\"\\n\");\n for (const line of lines) {\n if (line.trim()) {\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n };\n\n const processLine = (line: string, context: {\n controller: ReadableStreamDefaultController;\n encoder: typeof TextEncoder;\n hasTextContent: () => boolean;\n setHasTextContent: (val: boolean) => void;\n reasoningContent: () => string;\n appendReasoningContent: (content: string) => void;\n isReasoningComplete: () => boolean;\n setReasoningComplete: (val: boolean) => void;\n }) => {\n const { controller, encoder } = context;\n\n if (line.startsWith(\"data: \") && line.trim() !== \"data: [DONE]\") {\n const jsonStr = line.slice(6);\n try {\n const data = JSON.parse(jsonStr);\n if (data.error) {\n throw new Error(JSON.stringify(data));\n }\n\n if (data.choices?.[0]?.delta?.content && !context.hasTextContent()) {\n context.setHasTextContent(true);\n }\n\n if (\n data.choices?.[0]?.delta?.tool_calls?.length\n ) {\n data.choices?.[0]?.delta?.tool_calls.forEach((tool: any) => {\n tool.id = `call_${uuidv4()}`;\n })\n }\n\n if (\n data.choices?.[0]?.delta?.tool_calls?.length &&\n context.hasTextContent()\n ) {\n if (typeof data.choices[0].index === 'number') {\n data.choices[0].index += 1;\n } else {\n data.choices[0].index = 1;\n }\n }\n\n const modifiedLine = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n } catch (e) {\n // \u5982\u679CJSON\u89E3\u6790\u5931\u8D25\uFF0C\u53EF\u80FD\u662F\u6570\u636E\u4E0D\u5B8C\u6574\uFF0C\u5C06\u539F\u59CB\u884C\u4F20\u9012\u4E0B\u53BB\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n } else {\n // Pass through non-data lines (like [DONE])\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5269\u4F59\u7684\u6570\u636E\n if (buffer.trim()) {\n processBuffer(buffer, controller, encoder);\n }\n break;\n }\n\n // \u68C0\u67E5value\u662F\u5426\u6709\u6548\n if (!value || value.length === 0) {\n continue;\n }\n\n let chunk;\n try {\n chunk = decoder.decode(value, { stream: true });\n } catch (decodeError) {\n console.warn(\"Failed to decode chunk\", decodeError);\n continue;\n }\n\n if (chunk.length === 0) {\n continue;\n }\n\n buffer += chunk;\n\n // \u5982\u679C\u7F13\u51B2\u533A\u8FC7\u5927\uFF0C\u8FDB\u884C\u5904\u7406\u907F\u514D\u5185\u5B58\u6CC4\u6F0F\n if (buffer.length > 1000000) { // 1MB \u9650\u5236\n console.warn(\"Buffer size exceeds limit, processing partial data\");\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.trim()) {\n try {\n processLine(line, {\n controller,\n encoder,\n hasTextContent: () => hasTextContent,\n setHasTextContent: (val) => hasTextContent = val,\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) => reasoningContent += content,\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) => isReasoningComplete = val\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n continue;\n }\n\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5B8C\u6574\u7684\u6570\u636E\u884C\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\"; // \u6700\u540E\u4E00\u884C\u53EF\u80FD\u4E0D\u5B8C\u6574\uFF0C\u4FDD\u7559\u5728\u7F13\u51B2\u533A\n\n for (const line of lines) {\n if (!line.trim()) continue;\n\n try {\n processLine(line, {\n controller,\n encoder,\n hasTextContent: () => hasTextContent,\n setHasTextContent: (val) => hasTextContent = val,\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) => reasoningContent += content,\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) => isReasoningComplete = val\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n } catch (error) {\n console.error(\"Stream error:\", error);\n controller.error(error);\n } finally {\n try {\n reader.releaseLock();\n } catch (e) {\n console.error(\"Error releasing reader lock:\", e);\n }\n controller.close();\n }\n },\n\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n }\n\n return response;\n }\n}", "import { MessageContent, TextContent, UnifiedChatRequest } from \"@/types/llm\";\nimport { Transformer } from \"../types/transformer\";\n\nexport class CleancacheTransformer implements Transformer {\n name = \"cleancache\";\n\n async transformRequestIn(request: UnifiedChatRequest): Promise {\n if (Array.isArray(request.messages)) {\n request.messages.forEach((msg) => {\n if (Array.isArray(msg.content)) {\n (msg.content as MessageContent[]).forEach((item) => {\n if ((item as TextContent).cache_control) {\n delete (item as TextContent).cache_control;\n }\n });\n } else if (msg.cache_control) {\n delete msg.cache_control;\n }\n });\n }\n return request;\n }\n}\n", "import JSON5 from \"json5\";\nimport { jsonrepair } from \"jsonrepair\";\n\n/**\n * \u89E3\u6790\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u7684\u51FD\u6570\n * Parse tool call arguments function\n * \u5148\u5C1D\u8BD5\u6807\u51C6JSON\u89E3\u6790\uFF0C\u7136\u540EJSON5\u89E3\u6790\uFF0C\u6700\u540E\u4F7F\u7528jsonrepair\u8FDB\u884C\u5B89\u5168\u4FEE\u590D\n * First try standard JSON parsing, then JSON5 parsing, finally use jsonrepair for safe repair\n * \n * @param argsString - \u9700\u8981\u89E3\u6790\u7684\u53C2\u6570\u5B57\u7B26\u4E32 / Parameter string to parse\n * @returns \u89E3\u6790\u540E\u7684\u53C2\u6570\u5BF9\u8C61\u6216\u5B89\u5168\u7684\u7A7A\u5BF9\u8C61 / Parsed parameter object or safe empty object\n */\nexport function parseToolArguments(argsString: string, logger?: any): string {\n // Handle empty or null input\n if (!argsString || argsString.trim() === \"\" || argsString === \"{}\") {\n return \"{}\";\n }\n\n try {\n // First attempt: Standard JSON parsing\n JSON.parse(argsString);\n logger?.debug(`\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u6807\u51C6JSON\u89E3\u6790\u6210\u529F / Tool arguments standard JSON parsing successful`);\n return argsString;\n } catch (jsonError: any) {\n try {\n // Second attempt: JSON5 parsing for relaxed syntax\n const args = JSON5.parse(argsString);\n logger?.debug(`\u5DE5\u5177\u8C03\u7528\u53C2\u6570JSON5\u89E3\u6790\u6210\u529F / Tool arguments JSON5 parsing successful`);\n return JSON.stringify(args);\n } catch (json5Error: any) {\n try {\n // Third attempt: Safe JSON repair without code execution\n const repairedJson = jsonrepair(argsString);\n logger?.debug(`\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u5B89\u5168\u4FEE\u590D\u6210\u529F / Tool arguments safely repaired`);\n return repairedJson;\n } catch (repairError: any) {\n // All parsing attempts failed - log errors and return safe fallback\n logger?.error(\n `JSON\u89E3\u6790\u5931\u8D25 / JSON parsing failed: ${jsonError.message}. ` +\n `JSON5\u89E3\u6790\u5931\u8D25 / JSON5 parsing failed: ${json5Error.message}. ` +\n `JSON\u4FEE\u590D\u5931\u8D25 / JSON repair failed: ${repairError.message}. ` +\n `\u8F93\u5165\u6570\u636E / Input data: ${JSON.stringify(argsString)}`\n );\n \n // Return safe empty object as fallback instead of potentially malformed input\n logger?.debug(`\u8FD4\u56DE\u5B89\u5168\u7684\u7A7A\u5BF9\u8C61\u4F5C\u4E3A\u540E\u5907\u65B9\u6848 / Returning safe empty object as fallback`);\n return \"{}\";\n }\n }\n }\n}", "export class JSONRepairError extends Error {\n position: number\n\n constructor(message: string, position: number) {\n super(`${message} at position ${position}`)\n\n this.position = position\n }\n}\n", "const codeSpace = 0x20 // \" \"\nconst codeNewline = 0xa // \"\\n\"\nconst codeTab = 0x9 // \"\\t\"\nconst codeReturn = 0xd // \"\\r\"\nconst codeNonBreakingSpace = 0xa0\nconst codeEnQuad = 0x2000\nconst codeHairSpace = 0x200a\nconst codeNarrowNoBreakSpace = 0x202f\nconst codeMediumMathematicalSpace = 0x205f\nconst codeIdeographicSpace = 0x3000\n\nexport function isHex(char: string): boolean {\n return /^[0-9A-Fa-f]$/.test(char)\n}\n\nexport function isDigit(char: string): boolean {\n return char >= '0' && char <= '9'\n}\n\nexport function isValidStringCharacter(char: string): boolean {\n // note that the valid range is between \\u{0020} and \\u{10ffff},\n // but in JavaScript it is not possible to create a code point larger than\n // \\u{10ffff}, so there is no need to test for that here.\n return char >= '\\u0020'\n}\n\nexport function isDelimiter(char: string): boolean {\n return ',:[]/{}()\\n+'.includes(char)\n}\n\nexport function isFunctionNameCharStart(char: string) {\n return (\n (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || char === '_' || char === '$'\n )\n}\n\nexport function isFunctionNameChar(char: string) {\n return (\n (char >= 'a' && char <= 'z') ||\n (char >= 'A' && char <= 'Z') ||\n char === '_' ||\n char === '$' ||\n (char >= '0' && char <= '9')\n )\n}\n\n// matches \"https://\" and other schemas\nexport const regexUrlStart = /^(http|https|ftp|mailto|file|data|irc):\\/\\/$/\n\n// matches all valid URL characters EXCEPT \"[\", \"]\", and \",\", since that are important JSON delimiters\nexport const regexUrlChar = /^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/\n\nexport function isUnquotedStringDelimiter(char: string): boolean {\n return ',[]/{}\\n+'.includes(char)\n}\n\nexport function isStartOfValue(char: string): boolean {\n return isQuote(char) || regexStartOfValue.test(char)\n}\n\n// alpha, number, minus, or opening bracket or brace\nconst regexStartOfValue = /^[[{\\w-]$/\n\nexport function isControlCharacter(char: string) {\n return char === '\\n' || char === '\\r' || char === '\\t' || char === '\\b' || char === '\\f'\n}\n\nexport interface Text {\n charCodeAt: (index: number) => number\n}\n\n/**\n * Check if the given character is a whitespace character like space, tab, or\n * newline\n */\nexport function isWhitespace(text: Text, index: number): boolean {\n const code = text.charCodeAt(index)\n\n return code === codeSpace || code === codeNewline || code === codeTab || code === codeReturn\n}\n\n/**\n * Check if the given character is a whitespace character like space or tab,\n * but NOT a newline\n */\nexport function isWhitespaceExceptNewline(text: Text, index: number): boolean {\n const code = text.charCodeAt(index)\n\n return code === codeSpace || code === codeTab || code === codeReturn\n}\n\n/**\n * Check if the given character is a special whitespace character, some\n * unicode variant\n */\nexport function isSpecialWhitespace(text: Text, index: number): boolean {\n const code = text.charCodeAt(index)\n\n return (\n code === codeNonBreakingSpace ||\n (code >= codeEnQuad && code <= codeHairSpace) ||\n code === codeNarrowNoBreakSpace ||\n code === codeMediumMathematicalSpace ||\n code === codeIdeographicSpace\n )\n}\n\n/**\n * Test whether the given character is a quote or double quote character.\n * Also tests for special variants of quotes.\n */\nexport function isQuote(char: string): boolean {\n // the first check double quotes, since that occurs most often\n return isDoubleQuoteLike(char) || isSingleQuoteLike(char)\n}\n\n/**\n * Test whether the given character is a double quote character.\n * Also tests for special variants of double quotes.\n */\nexport function isDoubleQuoteLike(char: string): boolean {\n return char === '\"' || char === '\\u201c' || char === '\\u201d'\n}\n\n/**\n * Test whether the given character is a double quote character.\n * Does NOT test for special variants of double quotes.\n */\nexport function isDoubleQuote(char: string): boolean {\n return char === '\"'\n}\n\n/**\n * Test whether the given character is a single quote character.\n * Also tests for special variants of single quotes.\n */\nexport function isSingleQuoteLike(char: string): boolean {\n return (\n char === \"'\" || char === '\\u2018' || char === '\\u2019' || char === '\\u0060' || char === '\\u00b4'\n )\n}\n\n/**\n * Test whether the given character is a single quote character.\n * Does NOT test for special variants of single quotes.\n */\nexport function isSingleQuote(char: string): boolean {\n return char === \"'\"\n}\n\n/**\n * Strip last occurrence of textToStrip from text\n */\nexport function stripLastOccurrence(\n text: string,\n textToStrip: string,\n stripRemainingText = false\n): string {\n const index = text.lastIndexOf(textToStrip)\n return index !== -1\n ? text.substring(0, index) + (stripRemainingText ? '' : text.substring(index + 1))\n : text\n}\n\nexport function insertBeforeLastWhitespace(text: string, textToInsert: string): string {\n let index = text.length\n\n if (!isWhitespace(text, index - 1)) {\n // no trailing whitespaces\n return text + textToInsert\n }\n\n while (isWhitespace(text, index - 1)) {\n index--\n }\n\n return text.substring(0, index) + textToInsert + text.substring(index)\n}\n\nexport function removeAtIndex(text: string, start: number, count: number) {\n return text.substring(0, start) + text.substring(start + count)\n}\n\n/**\n * Test whether a string ends with a newline or comma character and optional whitespace\n */\nexport function endsWithCommaOrNewline(text: string): boolean {\n return /[,\\n][ \\t\\r]*$/.test(text)\n}\n", "import { JSONRepairError } from '../utils/JSONRepairError.js'\nimport {\n endsWithCommaOrNewline,\n insertBeforeLastWhitespace,\n isControlCharacter,\n isDelimiter,\n isDigit,\n isDoubleQuote,\n isDoubleQuoteLike,\n isFunctionNameChar,\n isFunctionNameCharStart,\n isHex,\n isQuote,\n isSingleQuote,\n isSingleQuoteLike,\n isSpecialWhitespace,\n isStartOfValue,\n isUnquotedStringDelimiter,\n isValidStringCharacter,\n isWhitespace,\n isWhitespaceExceptNewline,\n regexUrlChar,\n regexUrlStart,\n removeAtIndex,\n stripLastOccurrence\n} from '../utils/stringUtils.js'\n\nconst controlCharacters: { [key: string]: string } = {\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t'\n}\n\n// map with all escape characters\nconst escapeCharacters: { [key: string]: string } = {\n '\"': '\"',\n '\\\\': '\\\\',\n '/': '/',\n b: '\\b',\n f: '\\f',\n n: '\\n',\n r: '\\r',\n t: '\\t'\n // note that \\u is handled separately in parseString()\n}\n\n/**\n * Repair a string containing an invalid JSON document.\n * For example changes JavaScript notation into JSON notation.\n *\n * Example:\n *\n * try {\n * const json = \"{name: 'John'}\"\n * const repaired = jsonrepair(json)\n * console.log(repaired)\n * // '{\"name\": \"John\"}'\n * } catch (err) {\n * console.error(err)\n * }\n *\n */\nexport function jsonrepair(text: string): string {\n let i = 0 // current index in text\n let output = '' // generated output\n\n parseMarkdownCodeBlock(['```', '[```', '{```'])\n\n const processed = parseValue()\n if (!processed) {\n throwUnexpectedEnd()\n }\n\n parseMarkdownCodeBlock(['```', '```]', '```}'])\n\n const processedComma = parseCharacter(',')\n if (processedComma) {\n parseWhitespaceAndSkipComments()\n }\n\n if (isStartOfValue(text[i]) && endsWithCommaOrNewline(output)) {\n // start of a new value after end of the root level object: looks like\n // newline delimited JSON -> turn into a root level array\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n\n parseNewlineDelimitedJSON()\n } else if (processedComma) {\n // repair: remove trailing comma\n output = stripLastOccurrence(output, ',')\n }\n\n // repair redundant end quotes\n while (text[i] === '}' || text[i] === ']') {\n i++\n parseWhitespaceAndSkipComments()\n }\n\n if (i >= text.length) {\n // reached the end of the document properly\n return output\n }\n\n throwUnexpectedCharacter()\n\n function parseValue(): boolean {\n parseWhitespaceAndSkipComments()\n const processed =\n parseObject() ||\n parseArray() ||\n parseString() ||\n parseNumber() ||\n parseKeywords() ||\n parseUnquotedString(false) ||\n parseRegex()\n parseWhitespaceAndSkipComments()\n\n return processed\n }\n\n function parseWhitespaceAndSkipComments(skipNewline = true): boolean {\n const start = i\n\n let changed = parseWhitespace(skipNewline)\n do {\n changed = parseComment()\n if (changed) {\n changed = parseWhitespace(skipNewline)\n }\n } while (changed)\n\n return i > start\n }\n\n function parseWhitespace(skipNewline: boolean): boolean {\n const _isWhiteSpace = skipNewline ? isWhitespace : isWhitespaceExceptNewline\n let whitespace = ''\n\n while (true) {\n if (_isWhiteSpace(text, i)) {\n whitespace += text[i]\n i++\n } else if (isSpecialWhitespace(text, i)) {\n // repair special whitespace\n whitespace += ' '\n i++\n } else {\n break\n }\n }\n\n if (whitespace.length > 0) {\n output += whitespace\n return true\n }\n\n return false\n }\n\n function parseComment(): boolean {\n // find a block comment '/* ... */'\n if (text[i] === '/' && text[i + 1] === '*') {\n // repair block comment by skipping it\n while (i < text.length && !atEndOfBlockComment(text, i)) {\n i++\n }\n i += 2\n\n return true\n }\n\n // find a line comment '// ...'\n if (text[i] === '/' && text[i + 1] === '/') {\n // repair line comment by skipping it\n while (i < text.length && text[i] !== '\\n') {\n i++\n }\n\n return true\n }\n\n return false\n }\n\n function parseMarkdownCodeBlock(blocks: string[]): boolean {\n // find and skip over a Markdown fenced code block:\n // ``` ... ```\n // or\n // ```json ... ```\n if (skipMarkdownCodeBlock(blocks)) {\n if (isFunctionNameCharStart(text[i])) {\n // strip the optional language specifier like \"json\"\n while (i < text.length && isFunctionNameChar(text[i])) {\n i++\n }\n }\n\n parseWhitespaceAndSkipComments()\n\n return true\n }\n\n return false\n }\n\n function skipMarkdownCodeBlock(blocks: string[]): boolean {\n for (const block of blocks) {\n const end = i + block.length\n if (text.slice(i, end) === block) {\n i = end\n return true\n }\n }\n\n return false\n }\n\n function parseCharacter(char: string): boolean {\n if (text[i] === char) {\n output += text[i]\n i++\n return true\n }\n\n return false\n }\n\n function skipCharacter(char: string): boolean {\n if (text[i] === char) {\n i++\n return true\n }\n\n return false\n }\n\n function skipEscapeCharacter(): boolean {\n return skipCharacter('\\\\')\n }\n\n /**\n * Skip ellipsis like \"[1,2,3,...]\" or \"[1,2,3,...,9]\" or \"[...,7,8,9]\"\n * or a similar construct in objects.\n */\n function skipEllipsis(): boolean {\n parseWhitespaceAndSkipComments()\n\n if (text[i] === '.' && text[i + 1] === '.' && text[i + 2] === '.') {\n // repair: remove the ellipsis (three dots) and optionally a comma\n i += 3\n parseWhitespaceAndSkipComments()\n skipCharacter(',')\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse an object like '{\"key\": \"value\"}'\n */\n function parseObject(): boolean {\n if (text[i] === '{') {\n output += '{'\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: skip leading comma like in {, message: \"hi\"}\n if (skipCharacter(',')) {\n parseWhitespaceAndSkipComments()\n }\n\n let initial = true\n while (i < text.length && text[i] !== '}') {\n let processedComma: boolean\n if (!initial) {\n processedComma = parseCharacter(',')\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n parseWhitespaceAndSkipComments()\n } else {\n processedComma = true\n initial = false\n }\n\n skipEllipsis()\n\n const processedKey = parseString() || parseUnquotedString(true)\n if (!processedKey) {\n if (\n text[i] === '}' ||\n text[i] === '{' ||\n text[i] === ']' ||\n text[i] === '[' ||\n text[i] === undefined\n ) {\n // repair trailing comma\n output = stripLastOccurrence(output, ',')\n } else {\n throwObjectKeyExpected()\n }\n break\n }\n\n parseWhitespaceAndSkipComments()\n const processedColon = parseCharacter(':')\n const truncatedText = i >= text.length\n if (!processedColon) {\n if (isStartOfValue(text[i]) || truncatedText) {\n // repair missing colon\n output = insertBeforeLastWhitespace(output, ':')\n } else {\n throwColonExpected()\n }\n }\n const processedValue = parseValue()\n if (!processedValue) {\n if (processedColon || truncatedText) {\n // repair missing object value\n output += 'null'\n } else {\n throwColonExpected()\n }\n }\n }\n\n if (text[i] === '}') {\n output += '}'\n i++\n } else {\n // repair missing end bracket\n output = insertBeforeLastWhitespace(output, '}')\n }\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse an array like '[\"item1\", \"item2\", ...]'\n */\n function parseArray(): boolean {\n if (text[i] === '[') {\n output += '['\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: skip leading comma like in [,1,2,3]\n if (skipCharacter(',')) {\n parseWhitespaceAndSkipComments()\n }\n\n let initial = true\n while (i < text.length && text[i] !== ']') {\n if (!initial) {\n const processedComma = parseCharacter(',')\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n } else {\n initial = false\n }\n\n skipEllipsis()\n\n const processedValue = parseValue()\n if (!processedValue) {\n // repair trailing comma\n output = stripLastOccurrence(output, ',')\n break\n }\n }\n\n if (text[i] === ']') {\n output += ']'\n i++\n } else {\n // repair missing closing array bracket\n output = insertBeforeLastWhitespace(output, ']')\n }\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse and repair Newline Delimited JSON (NDJSON):\n * multiple JSON objects separated by a newline character\n */\n function parseNewlineDelimitedJSON() {\n // repair NDJSON\n let initial = true\n let processedValue = true\n while (processedValue) {\n if (!initial) {\n // parse optional comma, insert when missing\n const processedComma = parseCharacter(',')\n if (!processedComma) {\n // repair: add missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n } else {\n initial = false\n }\n\n processedValue = parseValue()\n }\n\n if (!processedValue) {\n // repair: remove trailing comma\n output = stripLastOccurrence(output, ',')\n }\n\n // repair: wrap the output inside array brackets\n output = `[\\n${output}\\n]`\n }\n\n /**\n * Parse a string enclosed by double quotes \"...\". Can contain escaped quotes\n * Repair strings enclosed in single quotes or special quotes\n * Repair an escaped string\n *\n * The function can run in two stages:\n * - First, it assumes the string has a valid end quote\n * - If it turns out that the string does not have a valid end quote followed\n * by a delimiter (which should be the case), the function runs again in a\n * more conservative way, stopping the string at the first next delimiter\n * and fixing the string by inserting a quote there, or stopping at a\n * stop index detected in the first iteration.\n */\n function parseString(stopAtDelimiter = false, stopAtIndex = -1): boolean {\n let skipEscapeChars = text[i] === '\\\\'\n if (skipEscapeChars) {\n // repair: remove the first escape character\n i++\n skipEscapeChars = true\n }\n\n if (isQuote(text[i])) {\n // double quotes are correct JSON,\n // single quotes come from JavaScript for example, we assume it will have a correct single end quote too\n // otherwise, we will match any double-quote-like start with a double-quote-like end,\n // or any single-quote-like start with a single-quote-like end\n const isEndQuote = isDoubleQuote(text[i])\n ? isDoubleQuote\n : isSingleQuote(text[i])\n ? isSingleQuote\n : isSingleQuoteLike(text[i])\n ? isSingleQuoteLike\n : isDoubleQuoteLike\n\n const iBefore = i\n const oBefore = output.length\n\n let str = '\"'\n i++\n\n while (true) {\n if (i >= text.length) {\n // end of text, we are missing an end quote\n\n const iPrev = prevNonWhitespaceIndex(i - 1)\n if (!stopAtDelimiter && isDelimiter(text.charAt(iPrev))) {\n // if the text ends with a delimiter, like [\"hello],\n // so the missing end quote should be inserted before this delimiter\n // retry parsing the string, stopping at the first next delimiter\n i = iBefore\n output = output.substring(0, oBefore)\n\n return parseString(true)\n }\n\n // repair missing quote\n str = insertBeforeLastWhitespace(str, '\"')\n output += str\n\n return true\n }\n\n if (i === stopAtIndex) {\n // use the stop index detected in the first iteration, and repair end quote\n str = insertBeforeLastWhitespace(str, '\"')\n output += str\n\n return true\n }\n\n if (isEndQuote(text[i])) {\n // end quote\n // let us check what is before and after the quote to verify whether this is a legit end quote\n const iQuote = i\n const oQuote = str.length\n str += '\"'\n i++\n output += str\n\n parseWhitespaceAndSkipComments(false)\n\n if (\n stopAtDelimiter ||\n i >= text.length ||\n isDelimiter(text[i]) ||\n isQuote(text[i]) ||\n isDigit(text[i])\n ) {\n // The quote is followed by the end of the text, a delimiter,\n // or a next value. So the quote is indeed the end of the string.\n parseConcatenatedString()\n\n return true\n }\n\n const iPrevChar = prevNonWhitespaceIndex(iQuote - 1)\n const prevChar = text.charAt(iPrevChar)\n\n if (prevChar === ',') {\n // A comma followed by a quote, like '{\"a\":\"b,c,\"d\":\"e\"}'.\n // We assume that the quote is a start quote, and that the end quote\n // should have been located right before the comma but is missing.\n i = iBefore\n output = output.substring(0, oBefore)\n\n return parseString(false, iPrevChar)\n }\n\n if (isDelimiter(prevChar)) {\n // This is not the right end quote: it is preceded by a delimiter,\n // and NOT followed by a delimiter. So, there is an end quote missing\n // parse the string again and then stop at the first next delimiter\n i = iBefore\n output = output.substring(0, oBefore)\n\n return parseString(true)\n }\n\n // revert to right after the quote but before any whitespace, and continue parsing the string\n output = output.substring(0, oBefore)\n i = iQuote + 1\n\n // repair unescaped quote\n str = `${str.substring(0, oQuote)}\\\\${str.substring(oQuote)}`\n } else if (stopAtDelimiter && isUnquotedStringDelimiter(text[i])) {\n // we're in the mode to stop the string at the first delimiter\n // because there is an end quote missing\n\n // test start of an url like \"https://...\" (this would be parsed as a comment)\n if (text[i - 1] === ':' && regexUrlStart.test(text.substring(iBefore + 1, i + 2))) {\n while (i < text.length && regexUrlChar.test(text[i])) {\n str += text[i]\n i++\n }\n }\n\n // repair missing quote\n str = insertBeforeLastWhitespace(str, '\"')\n output += str\n\n parseConcatenatedString()\n\n return true\n } else if (text[i] === '\\\\') {\n // handle escaped content like \\n or \\u2605\n const char = text.charAt(i + 1)\n const escapeChar = escapeCharacters[char]\n if (escapeChar !== undefined) {\n str += text.slice(i, i + 2)\n i += 2\n } else if (char === 'u') {\n let j = 2\n while (j < 6 && isHex(text[i + j])) {\n j++\n }\n\n if (j === 6) {\n str += text.slice(i, i + 6)\n i += 6\n } else if (i + j >= text.length) {\n // repair invalid or truncated unicode char at the end of the text\n // by removing the unicode char and ending the string here\n i = text.length\n } else {\n throwInvalidUnicodeCharacter()\n }\n } else {\n // repair invalid escape character: remove it\n str += char\n i += 2\n }\n } else {\n // handle regular characters\n const char = text.charAt(i)\n\n if (char === '\"' && text[i - 1] !== '\\\\') {\n // repair unescaped double quote\n str += `\\\\${char}`\n i++\n } else if (isControlCharacter(char)) {\n // unescaped control character\n str += controlCharacters[char]\n i++\n } else {\n if (!isValidStringCharacter(char)) {\n throwInvalidCharacter(char)\n }\n str += char\n i++\n }\n }\n\n if (skipEscapeChars) {\n // repair: skipped escape character (nothing to do)\n skipEscapeCharacter()\n }\n }\n }\n\n return false\n }\n\n /**\n * Repair concatenated strings like \"hello\" + \"world\", change this into \"helloworld\"\n */\n function parseConcatenatedString(): boolean {\n let processed = false\n\n parseWhitespaceAndSkipComments()\n while (text[i] === '+') {\n processed = true\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: remove the end quote of the first string\n output = stripLastOccurrence(output, '\"', true)\n const start = output.length\n const parsedStr = parseString()\n if (parsedStr) {\n // repair: remove the start quote of the second string\n output = removeAtIndex(output, start, 1)\n } else {\n // repair: remove the + because it is not followed by a string\n output = insertBeforeLastWhitespace(output, '\"')\n }\n }\n\n return processed\n }\n\n /**\n * Parse a number like 2.4 or 2.4e6\n */\n function parseNumber(): boolean {\n const start = i\n if (text[i] === '-') {\n i++\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return true\n }\n if (!isDigit(text[i])) {\n i = start\n return false\n }\n }\n\n // Note that in JSON leading zeros like \"00789\" are not allowed.\n // We will allow all leading zeros here though and at the end of parseNumber\n // check against trailing zeros and repair that if needed.\n // Leading zeros can have meaning, so we should not clear them.\n while (isDigit(text[i])) {\n i++\n }\n\n if (text[i] === '.') {\n i++\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return true\n }\n if (!isDigit(text[i])) {\n i = start\n return false\n }\n while (isDigit(text[i])) {\n i++\n }\n }\n\n if (text[i] === 'e' || text[i] === 'E') {\n i++\n if (text[i] === '-' || text[i] === '+') {\n i++\n }\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return true\n }\n if (!isDigit(text[i])) {\n i = start\n return false\n }\n while (isDigit(text[i])) {\n i++\n }\n }\n\n // if we're not at the end of the number by this point, allow this to be parsed as another type\n if (!atEndOfNumber()) {\n i = start\n return false\n }\n\n if (i > start) {\n // repair a number with leading zeros like \"00789\"\n const num = text.slice(start, i)\n const hasInvalidLeadingZero = /^0\\d/.test(num)\n\n output += hasInvalidLeadingZero ? `\"${num}\"` : num\n return true\n }\n\n return false\n }\n\n /**\n * Parse keywords true, false, null\n * Repair Python keywords True, False, None\n */\n function parseKeywords(): boolean {\n return (\n parseKeyword('true', 'true') ||\n parseKeyword('false', 'false') ||\n parseKeyword('null', 'null') ||\n // repair Python keywords True, False, None\n parseKeyword('True', 'true') ||\n parseKeyword('False', 'false') ||\n parseKeyword('None', 'null')\n )\n }\n\n function parseKeyword(name: string, value: string): boolean {\n if (text.slice(i, i + name.length) === name) {\n output += value\n i += name.length\n return true\n }\n\n return false\n }\n\n /**\n * Repair an unquoted string by adding quotes around it\n * Repair a MongoDB function call like NumberLong(\"2\")\n * Repair a JSONP function call like callback({...});\n */\n function parseUnquotedString(isKey: boolean) {\n // note that the symbol can end with whitespaces: we stop at the next delimiter\n // also, note that we allow strings to contain a slash / in order to support repairing regular expressions\n const start = i\n\n if (isFunctionNameCharStart(text[i])) {\n while (i < text.length && isFunctionNameChar(text[i])) {\n i++\n }\n\n let j = i\n while (isWhitespace(text, j)) {\n j++\n }\n\n if (text[j] === '(') {\n // repair a MongoDB function call like NumberLong(\"2\")\n // repair a JSONP function call like callback({...});\n i = j + 1\n\n parseValue()\n\n if (text[i] === ')') {\n // repair: skip close bracket of function call\n i++\n if (text[i] === ';') {\n // repair: skip semicolon after JSONP call\n i++\n }\n }\n\n return true\n }\n }\n\n while (\n i < text.length &&\n !isUnquotedStringDelimiter(text[i]) &&\n !isQuote(text[i]) &&\n (!isKey || text[i] !== ':')\n ) {\n i++\n }\n\n // test start of an url like \"https://...\" (this would be parsed as a comment)\n if (text[i - 1] === ':' && regexUrlStart.test(text.substring(start, i + 2))) {\n while (i < text.length && regexUrlChar.test(text[i])) {\n i++\n }\n }\n\n if (i > start) {\n // repair unquoted string\n // also, repair undefined into null\n\n // first, go back to prevent getting trailing whitespaces in the string\n while (isWhitespace(text, i - 1) && i > 0) {\n i--\n }\n\n const symbol = text.slice(start, i)\n output += symbol === 'undefined' ? 'null' : JSON.stringify(symbol)\n\n if (text[i] === '\"') {\n // we had a missing start quote, but now we encountered the end quote, so we can skip that one\n i++\n }\n\n return true\n }\n }\n\n function parseRegex() {\n if (text[i] === '/') {\n const start = i\n i++\n\n while (i < text.length && (text[i] !== '/' || text[i - 1] === '\\\\')) {\n i++\n }\n i++\n\n output += `\"${text.substring(start, i)}\"`\n\n return true\n }\n }\n\n function prevNonWhitespaceIndex(start: number): number {\n let prev = start\n\n while (prev > 0 && isWhitespace(text, prev)) {\n prev--\n }\n\n return prev\n }\n\n function atEndOfNumber() {\n return i >= text.length || isDelimiter(text[i]) || isWhitespace(text, i)\n }\n\n function repairNumberEndingWithNumericSymbol(start: number) {\n // repair numbers cut off at the end\n // this will only be called when we end after a '.', '-', or 'e' and does not\n // change the number more than it needs to make it valid JSON\n output += `${text.slice(start, i)}0`\n }\n\n function throwInvalidCharacter(char: string) {\n throw new JSONRepairError(`Invalid character ${JSON.stringify(char)}`, i)\n }\n\n function throwUnexpectedCharacter() {\n throw new JSONRepairError(`Unexpected character ${JSON.stringify(text[i])}`, i)\n }\n\n function throwUnexpectedEnd() {\n throw new JSONRepairError('Unexpected end of json string', text.length)\n }\n\n function throwObjectKeyExpected() {\n throw new JSONRepairError('Object key expected', i)\n }\n\n function throwColonExpected() {\n throw new JSONRepairError('Colon expected', i)\n }\n\n function throwInvalidUnicodeCharacter() {\n const chars = text.slice(i, i + 6)\n throw new JSONRepairError(`Invalid unicode character \"${chars}\"`, i)\n }\n}\n\nfunction atEndOfBlockComment(text: string, i: number) {\n return text[i] === '*' && text[i + 1] === '/'\n}\n", "import { Transformer } from \"@/types/transformer\";\nimport { parseToolArguments } from \"@/utils/toolArgumentsParser\";\n\nexport class EnhanceToolTransformer implements Transformer {\n name = \"enhancetool\";\n\n async transformResponseOut(response: Response): Promise {\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse = await response.json();\n if (jsonResponse?.choices?.[0]?.message?.tool_calls?.length) {\n // \u5904\u7406\u975E\u6D41\u5F0F\u7684\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\n for (const toolCall of jsonResponse.choices[0].message.tool_calls) {\n if (toolCall.function?.arguments) {\n toolCall.function.arguments = parseToolArguments(\n toolCall.function.arguments,\n this.logger\n );\n }\n }\n }\n return new Response(JSON.stringify(jsonResponse), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n\n // Define interface for tool call tracking\n interface ToolCall {\n index?: number;\n name?: string;\n id?: string;\n arguments?: string;\n }\n\n let currentToolCall: ToolCall = {};\n\n let hasTextContent = false;\n let reasoningContent = \"\";\n let isReasoningComplete = false;\n let hasToolCall = false;\n let buffer = \"\"; // \u7528\u4E8E\u7F13\u51B2\u4E0D\u5B8C\u6574\u7684\u6570\u636E\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n const processBuffer = (\n buffer: string,\n controller: ReadableStreamDefaultController,\n encoder: TextEncoder\n ) => {\n const lines = buffer.split(\"\\n\");\n for (const line of lines) {\n if (line.trim()) {\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n };\n\n // Helper function to process completed tool calls\n const processCompletedToolCall = (\n data: any,\n controller: ReadableStreamDefaultController,\n encoder: TextEncoder\n ) => {\n let finalArgs = \"\";\n try {\n finalArgs = parseToolArguments(currentToolCall.arguments || \"\", this.logger);\n } catch (e: any) {\n console.error(\n `${e.message} ${\n e.stack\n } \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(\n currentToolCall\n )}`\n );\n // Use original arguments if parsing fails\n finalArgs = currentToolCall.arguments || \"\";\n }\n\n const delta = {\n role: \"assistant\",\n tool_calls: [\n {\n function: {\n name: currentToolCall.name,\n arguments: finalArgs,\n },\n id: currentToolCall.id,\n index: currentToolCall.index,\n type: \"function\",\n },\n ],\n };\n\n // Remove content field entirely to prevent extra null values\n const modifiedData = {\n ...data,\n choices: [\n {\n ...data.choices[0],\n delta,\n },\n ],\n };\n // Remove content field if it exists\n if (modifiedData.choices[0].delta.content !== undefined) {\n delete modifiedData.choices[0].delta.content;\n }\n\n const modifiedLine = `data: ${JSON.stringify(modifiedData)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n };\n\n const processLine = (\n line: string,\n context: {\n controller: ReadableStreamDefaultController;\n encoder: TextEncoder;\n hasTextContent: () => boolean;\n setHasTextContent: (val: boolean) => void;\n reasoningContent: () => string;\n appendReasoningContent: (content: string) => void;\n isReasoningComplete: () => boolean;\n setReasoningComplete: (val: boolean) => void;\n }\n ) => {\n const { controller, encoder } = context;\n\n if (line.startsWith(\"data: \") && line.trim() !== \"data: [DONE]\") {\n const jsonStr = line.slice(6);\n try {\n const data = JSON.parse(jsonStr);\n\n // Handle tool calls in streaming mode\n if (data.choices?.[0]?.delta?.tool_calls?.length) {\n const toolCallDelta = data.choices[0].delta.tool_calls[0];\n\n // Initialize currentToolCall if this is the first chunk for this tool call\n if (typeof currentToolCall.index === \"undefined\") {\n currentToolCall = {\n index: toolCallDelta.index,\n name: toolCallDelta.function?.name || \"\",\n id: toolCallDelta.id || \"\",\n arguments: toolCallDelta.function?.arguments || \"\"\n };\n if (toolCallDelta.function?.arguments) {\n toolCallDelta.function.arguments = ''\n }\n // Send the first chunk as-is\n const modifiedLine = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n return;\n }\n // Accumulate arguments if this is a continuation of the current tool call\n else if (currentToolCall.index === toolCallDelta.index) {\n if (toolCallDelta.function?.arguments) {\n currentToolCall.arguments += toolCallDelta.function.arguments;\n }\n // Don't send intermediate chunks that only contain arguments\n return;\n }\n // If we have a different tool call index, process the previous one and start a new one\n else {\n // Process the completed tool call using helper function\n processCompletedToolCall(data, controller, encoder);\n\n // Start tracking the new tool call\n currentToolCall = {\n index: toolCallDelta.index,\n name: toolCallDelta.function?.name || \"\",\n id: toolCallDelta.id || \"\",\n arguments: toolCallDelta.function?.arguments || \"\"\n };\n return;\n }\n }\n\n // Handle finish_reason for tool_calls\n if (data.choices?.[0]?.finish_reason === \"tool_calls\" && currentToolCall.index !== undefined) {\n // Process the final tool call using helper function\n processCompletedToolCall(data, controller, encoder);\n currentToolCall = {};\n return;\n }\n\n // Handle text content alongside tool calls\n if (\n data.choices?.[0]?.delta?.tool_calls?.length &&\n context.hasTextContent()\n ) {\n if (typeof data.choices[0].index === \"number\") {\n data.choices[0].index += 1;\n } else {\n data.choices[0].index = 1;\n }\n }\n\n const modifiedLine = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n } catch (e) {\n // \u5982\u679CJSON\u89E3\u6790\u5931\u8D25\uFF0C\u53EF\u80FD\u662F\u6570\u636E\u4E0D\u5B8C\u6574\uFF0C\u5C06\u539F\u59CB\u884C\u4F20\u9012\u4E0B\u53BB\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n } else {\n // Pass through non-data lines (like [DONE])\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5269\u4F59\u7684\u6570\u636E\n if (buffer.trim()) {\n processBuffer(buffer, controller, encoder);\n }\n break;\n }\n\n // \u68C0\u67E5value\u662F\u5426\u6709\u6548\n if (!value || value.length === 0) {\n continue;\n }\n\n let chunk;\n try {\n chunk = decoder.decode(value, { stream: true });\n } catch (decodeError) {\n console.warn(\"Failed to decode chunk\", decodeError);\n continue;\n }\n\n if (chunk.length === 0) {\n continue;\n }\n\n buffer += chunk;\n\n // \u5982\u679C\u7F13\u51B2\u533A\u8FC7\u5927\uFF0C\u8FDB\u884C\u5904\u7406\u907F\u514D\u5185\u5B58\u6CC4\u6F0F\n if (buffer.length > 1000000) {\n // 1MB \u9650\u5236\n console.warn(\n \"Buffer size exceeds limit, processing partial data\"\n );\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.trim()) {\n try {\n processLine(line, {\n controller,\n encoder,\n hasTextContent: () => hasTextContent,\n setHasTextContent: (val) => (hasTextContent = val),\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) =>\n (reasoningContent += content),\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) =>\n (isReasoningComplete = val),\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n continue;\n }\n\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5B8C\u6574\u7684\u6570\u636E\u884C\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\"; // \u6700\u540E\u4E00\u884C\u53EF\u80FD\u4E0D\u5B8C\u6574\uFF0C\u4FDD\u7559\u5728\u7F13\u51B2\u533A\n\n for (const line of lines) {\n if (!line.trim()) continue;\n\n try {\n processLine(line, {\n controller,\n encoder,\n hasTextContent: () => hasTextContent,\n setHasTextContent: (val) => (hasTextContent = val),\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) =>\n (reasoningContent += content),\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) => (isReasoningComplete = val),\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n } catch (error) {\n console.error(\"Stream error:\", error);\n controller.error(error);\n } finally {\n try {\n reader.releaseLock();\n } catch (e) {\n console.error(\"Error releasing reader lock:\", e);\n }\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n }\n\n return response;\n }\n}\n", "import { UnifiedChatRequest } from \"@/types/llm\";\nimport { Transformer, TransformerOptions } from \"../types/transformer\";\n\nexport class ReasoningTransformer implements Transformer {\n static TransformerName = \"reasoning\";\n enable: any;\n\n constructor(private readonly options?: TransformerOptions) {\n this.enable = this.options?.enable ?? true;\n }\n\n async transformRequestIn(\n request: UnifiedChatRequest\n ): Promise {\n if (!this.enable) {\n request.thinking = {\n type: \"disabled\",\n budget_tokens: -1,\n };\n request.enable_thinking = false;\n return request;\n }\n if (request.reasoning) {\n request.thinking = {\n type: \"enabled\",\n budget_tokens: request.reasoning.max_tokens,\n };\n request.enable_thinking = true;\n }\n return request;\n }\n\n async transformResponseOut(response: Response): Promise {\n if (!this.enable) return response;\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse = await response.json();\n // Handle non-streaming response if needed\n return new Response(JSON.stringify(jsonResponse), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n let reasoningContent = \"\";\n let isReasoningComplete = false;\n let buffer = \"\"; // Buffer for incomplete data\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n\n // Process buffer function\n const processBuffer = (\n buffer: string,\n controller: ReadableStreamDefaultController,\n encoder: TextEncoder\n ) => {\n const lines = buffer.split(\"\\n\");\n for (const line of lines) {\n if (line.trim()) {\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n };\n\n // Process line function\n const processLine = (\n line: string,\n context: {\n controller: ReadableStreamDefaultController;\n encoder: typeof TextEncoder;\n reasoningContent: () => string;\n appendReasoningContent: (content: string) => void;\n isReasoningComplete: () => boolean;\n setReasoningComplete: (val: boolean) => void;\n }\n ) => {\n const { controller, encoder } = context;\n\n this.logger?.debug({ line }, `Processing reason line`);\n\n if (line.startsWith(\"data: \") && line.trim() !== \"data: [DONE]\") {\n try {\n const data = JSON.parse(line.slice(6));\n\n // Extract reasoning_content from delta\n if (data.choices?.[0]?.delta?.reasoning_content) {\n context.appendReasoningContent(\n data.choices[0].delta.reasoning_content\n );\n const thinkingChunk = {\n ...data,\n choices: [\n {\n ...data.choices[0],\n delta: {\n ...data.choices[0].delta,\n thinking: {\n content: data.choices[0].delta.reasoning_content,\n },\n },\n },\n ],\n };\n delete thinkingChunk.choices[0].delta.reasoning_content;\n const thinkingLine = `data: ${JSON.stringify(\n thinkingChunk\n )}\\n\\n`;\n controller.enqueue(encoder.encode(thinkingLine));\n return;\n }\n\n // Check if reasoning is complete (when delta has content but no reasoning_content)\n if (\n (data.choices?.[0]?.delta?.content ||\n data.choices?.[0]?.delta?.tool_calls) &&\n context.reasoningContent() &&\n !context.isReasoningComplete()\n ) {\n context.setReasoningComplete(true);\n const signature = Date.now().toString();\n\n // Create a new chunk with thinking block\n const thinkingChunk = {\n ...data,\n choices: [\n {\n ...data.choices[0],\n delta: {\n ...data.choices[0].delta,\n content: null,\n thinking: {\n content: context.reasoningContent(),\n signature: signature,\n },\n },\n },\n ],\n };\n delete thinkingChunk.choices[0].delta.reasoning_content;\n // Send the thinking chunk\n const thinkingLine = `data: ${JSON.stringify(\n thinkingChunk\n )}\\n\\n`;\n controller.enqueue(encoder.encode(thinkingLine));\n }\n\n if (data.choices?.[0]?.delta?.reasoning_content) {\n delete data.choices[0].delta.reasoning_content;\n }\n\n // Send the modified chunk\n if (\n data.choices?.[0]?.delta &&\n Object.keys(data.choices[0].delta).length > 0\n ) {\n if (context.isReasoningComplete()) {\n data.choices[0].index++;\n }\n const modifiedLine = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n }\n } catch (e) {\n // If JSON parsing fails, pass through the original line\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n } else {\n // Pass through non-data lines (like [DONE])\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n // Process remaining data in buffer\n if (buffer.trim()) {\n processBuffer(buffer, controller, encoder);\n }\n break;\n }\n\n const chunk = decoder.decode(value, { stream: true });\n buffer += chunk;\n\n // Process complete lines from buffer\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\"; // Keep incomplete line in buffer\n\n for (const line of lines) {\n if (!line.trim()) continue;\n\n try {\n processLine(line, {\n controller,\n encoder: encoder,\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) =>\n (reasoningContent += content),\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) => (isReasoningComplete = val),\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // Pass through original line if parsing fails\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n } catch (error) {\n console.error(\"Stream error:\", error);\n controller.error(error);\n } finally {\n try {\n reader.releaseLock();\n } catch (e) {\n console.error(\"Error releasing reader lock:\", e);\n }\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n }\n\n return response;\n }\n}\n", "import { UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer, TransformerOptions } from \"../types/transformer\";\n\nexport class SamplingTransformer implements Transformer {\n name = \"sampling\";\n\n max_tokens: number;\n temperature: number;\n top_p: number;\n top_k: number;\n repetition_penalty: number;\n\n constructor(private readonly options?: TransformerOptions) {\n this.max_tokens = this.options?.max_tokens;\n this.temperature = this.options?.temperature;\n this.top_p = this.options?.top_p;\n this.top_k = this.options?.top_k;\n this.repetition_penalty = this.options?.repetition_penalty;\n }\n\n async transformRequestIn(\n request: UnifiedChatRequest\n ): Promise {\n if (request.max_tokens && request.max_tokens > this.max_tokens) {\n request.max_tokens = this.max_tokens;\n }\n if (typeof this.temperature !== \"undefined\") {\n request.temperature = this.temperature;\n }\n if (typeof this.top_p !== \"undefined\") {\n request.top_p = this.top_p;\n }\n if (typeof this.top_k !== \"undefined\") {\n request.top_k = this.top_k;\n }\n if (typeof this.repetition_penalty !== \"undefined\") {\n request.repetition_penalty = this.repetition_penalty;\n }\n return request;\n }\n}\n", "import { UnifiedChatRequest } from \"../types/llm\";\r\nimport { Transformer } from \"../types/transformer\";\r\n\r\nexport class MaxCompletionTokens implements Transformer {\r\n static TransformerName = \"maxcompletiontokens\";\r\n\r\n async transformRequestIn(\r\n request: UnifiedChatRequest\r\n ): Promise {\r\n if (request.max_tokens) {\r\n request.max_completion_tokens = request.max_tokens;\r\n delete request.max_tokens;\r\n }\r\n return request;\r\n }\r\n}\r\n", "import { UnifiedChatRequest, UnifiedMessage, UnifiedTool } from \"../types/llm\";\n\n// Vertex Claude\u6D88\u606F\u63A5\u53E3\ninterface ClaudeMessage {\n role: \"user\" | \"assistant\";\n content: Array<{\n type: \"text\" | \"image\";\n text?: string;\n source?: {\n type: \"base64\";\n media_type: string;\n data: string;\n };\n }>;\n}\n\n// Vertex Claude\u5DE5\u5177\u63A5\u53E3\ninterface ClaudeTool {\n name: string;\n description: string;\n input_schema: {\n type: string;\n properties: Record;\n required?: string[];\n additionalProperties?: boolean;\n $schema?: string;\n };\n}\n\n// Vertex Claude\u8BF7\u6C42\u63A5\u53E3\ninterface VertexClaudeRequest {\n anthropic_version: \"vertex-2023-10-16\";\n messages: ClaudeMessage[];\n max_tokens: number;\n stream?: boolean;\n temperature?: number;\n top_p?: number;\n top_k?: number;\n tools?: ClaudeTool[];\n tool_choice?: \"auto\" | \"none\" | { type: \"tool\"; name: string };\n}\n\n// Vertex Claude\u54CD\u5E94\u63A5\u53E3\ninterface VertexClaudeResponse {\n content: Array<{\n type: \"text\";\n text: string;\n }>;\n id: string;\n model: string;\n role: \"assistant\";\n stop_reason: string;\n stop_sequence: null;\n type: \"message\";\n usage: {\n input_tokens: number;\n output_tokens: number;\n };\n tool_use?: Array<{\n id: string;\n name: string;\n input: Record;\n }>;\n}\n\nexport function buildRequestBody(\n request: UnifiedChatRequest\n): VertexClaudeRequest {\n const messages: ClaudeMessage[] = [];\n\n for (let i = 0; i < request.messages.length; i++) {\n const message = request.messages[i];\n const isLastMessage = i === request.messages.length - 1;\n const isAssistantMessage = message.role === \"assistant\";\n\n const content: ClaudeMessage[\"content\"] = [];\n\n if (typeof message.content === \"string\") {\n // \u4FDD\u7559\u6240\u6709\u5B57\u7B26\u4E32\u5185\u5BB9\uFF0C\u5373\u4F7F\u662F\u7A7A\u5B57\u7B26\u4E32\uFF0C\u56E0\u4E3A\u53EF\u80FD\u5305\u542B\u91CD\u8981\u4FE1\u606F\n content.push({\n type: \"text\",\n text: message.content,\n });\n } else if (Array.isArray(message.content)) {\n message.content.forEach((item) => {\n if (item.type === \"text\") {\n // \u4FDD\u7559\u6240\u6709\u6587\u672C\u5185\u5BB9\uFF0C\u5373\u4F7F\u662F\u7A7A\u5B57\u7B26\u4E32\n content.push({\n type: \"text\",\n text: item.text || \"\",\n });\n } else if (item.type === \"image_url\") {\n // \u5904\u7406\u56FE\u7247\u5185\u5BB9\n content.push({\n type: \"image\",\n source: {\n type: \"base64\",\n media_type: item.media_type || \"image/jpeg\",\n data: item.image_url.url,\n },\n });\n }\n });\n }\n\n // \u53EA\u8DF3\u8FC7\u5B8C\u5168\u7A7A\u7684\u975E\u6700\u540E\u4E00\u6761\u6D88\u606F\uFF08\u6CA1\u6709\u5185\u5BB9\u548C\u5DE5\u5177\u8C03\u7528\uFF09\n if (\n !isLastMessage &&\n content.length === 0 &&\n !message.tool_calls &&\n !message.content\n ) {\n continue;\n }\n\n // \u5BF9\u4E8E\u6700\u540E\u4E00\u6761 assistant \u6D88\u606F\uFF0C\u5982\u679C\u6CA1\u6709\u5185\u5BB9\u4F46\u6709\u5DE5\u5177\u8C03\u7528\uFF0C\u5219\u6DFB\u52A0\u7A7A\u5185\u5BB9\n if (\n isLastMessage &&\n isAssistantMessage &&\n content.length === 0 &&\n message.tool_calls\n ) {\n content.push({\n type: \"text\",\n text: \"\",\n });\n }\n\n messages.push({\n role: message.role === \"assistant\" ? \"assistant\" : \"user\",\n content,\n });\n }\n\n const requestBody: VertexClaudeRequest = {\n anthropic_version: \"vertex-2023-10-16\",\n messages,\n max_tokens: request.max_tokens || 1000,\n stream: request.stream || false,\n ...(request.temperature && { temperature: request.temperature }),\n };\n\n // \u5904\u7406\u5DE5\u5177\u5B9A\u4E49\n if (request.tools && request.tools.length > 0) {\n requestBody.tools = request.tools.map((tool: UnifiedTool) => ({\n name: tool.function.name,\n description: tool.function.description,\n input_schema: tool.function.parameters,\n }));\n }\n\n // \u5904\u7406\u5DE5\u5177\u9009\u62E9\n if (request.tool_choice) {\n if (request.tool_choice === \"auto\" || request.tool_choice === \"none\") {\n requestBody.tool_choice = request.tool_choice;\n } else if (typeof request.tool_choice === \"string\") {\n // \u5982\u679C tool_choice \u662F\u5B57\u7B26\u4E32\uFF0C\u5047\u8BBE\u662F\u5DE5\u5177\u540D\u79F0\n requestBody.tool_choice = {\n type: \"tool\",\n name: request.tool_choice,\n };\n }\n }\n\n return requestBody;\n}\n\nexport function transformRequestOut(\n request: Record\n): UnifiedChatRequest {\n const vertexRequest = request as VertexClaudeRequest;\n\n const messages: UnifiedMessage[] = vertexRequest.messages.map((msg) => {\n const content = msg.content.map((item) => {\n if (item.type === \"text\") {\n return {\n type: \"text\" as const,\n text: item.text || \"\",\n };\n } else if (item.type === \"image\" && item.source) {\n return {\n type: \"image_url\" as const,\n image_url: {\n url: item.source.data,\n },\n media_type: item.source.media_type,\n };\n }\n return {\n type: \"text\" as const,\n text: \"\",\n };\n });\n\n return {\n role: msg.role,\n content,\n };\n });\n\n const result: UnifiedChatRequest = {\n messages,\n model: request.model || \"claude-sonnet-4@20250514\",\n max_tokens: vertexRequest.max_tokens,\n temperature: vertexRequest.temperature,\n stream: vertexRequest.stream,\n };\n\n // \u5904\u7406\u5DE5\u5177\u5B9A\u4E49\n if (vertexRequest.tools && vertexRequest.tools.length > 0) {\n result.tools = vertexRequest.tools.map((tool) => ({\n type: \"function\" as const,\n function: {\n name: tool.name,\n description: tool.description,\n parameters: {\n type: \"object\" as const,\n properties: tool.input_schema.properties,\n required: tool.input_schema.required,\n additionalProperties: tool.input_schema.additionalProperties,\n $schema: tool.input_schema.$schema,\n },\n },\n }));\n }\n\n // \u5904\u7406\u5DE5\u5177\u9009\u62E9\n if (vertexRequest.tool_choice) {\n if (typeof vertexRequest.tool_choice === \"string\") {\n result.tool_choice = vertexRequest.tool_choice;\n } else if (vertexRequest.tool_choice.type === \"tool\") {\n result.tool_choice = vertexRequest.tool_choice.name;\n }\n }\n\n return result;\n}\n\nexport async function transformResponseOut(\n response: Response,\n providerName: string,\n logger?: any\n): Promise {\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse = (await response.json()) as VertexClaudeResponse;\n\n // \u5904\u7406\u5DE5\u5177\u8C03\u7528\n let tool_calls = undefined;\n if (jsonResponse.tool_use && jsonResponse.tool_use.length > 0) {\n tool_calls = jsonResponse.tool_use.map((tool) => ({\n id: tool.id,\n type: \"function\" as const,\n function: {\n name: tool.name,\n arguments: JSON.stringify(tool.input),\n },\n }));\n }\n\n // \u8F6C\u6362\u4E3AOpenAI\u683C\u5F0F\u7684\u54CD\u5E94\n const res = {\n id: jsonResponse.id,\n choices: [\n {\n finish_reason: jsonResponse.stop_reason || null,\n index: 0,\n message: {\n content: jsonResponse.content[0]?.text || \"\",\n role: \"assistant\",\n ...(tool_calls && { tool_calls }),\n },\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n model: jsonResponse.model,\n object: \"chat.completion\",\n usage: {\n completion_tokens: jsonResponse.usage.output_tokens,\n prompt_tokens: jsonResponse.usage.input_tokens,\n total_tokens:\n jsonResponse.usage.input_tokens + jsonResponse.usage.output_tokens,\n },\n };\n\n return new Response(JSON.stringify(res), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n // \u5904\u7406\u6D41\u5F0F\u54CD\u5E94\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n\n const processLine = (\n line: string,\n controller: ReadableStreamDefaultController\n ) => {\n if (line.startsWith(\"data: \")) {\n const chunkStr = line.slice(6).trim();\n if (chunkStr) {\n logger?.debug({ chunkStr }, `${providerName} chunk:`);\n try {\n const chunk = JSON.parse(chunkStr);\n\n // \u5904\u7406 Anthropic \u539F\u751F\u683C\u5F0F\u7684\u6D41\u5F0F\u54CD\u5E94\n if (\n chunk.type === \"content_block_delta\" &&\n chunk.delta?.type === \"text_delta\"\n ) {\n // \u8FD9\u662F Anthropic \u539F\u751F\u683C\u5F0F\uFF0C\u9700\u8981\u8F6C\u6362\u4E3A OpenAI \u683C\u5F0F\n const res = {\n choices: [\n {\n delta: {\n role: \"assistant\",\n content: chunk.delta.text || \"\",\n },\n finish_reason: null,\n index: 0,\n logprobs: null,\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n id: chunk.id || \"\",\n model: chunk.model || \"\",\n object: \"chat.completion.chunk\",\n system_fingerprint: \"fp_a49d71b8a1\",\n usage: {\n completion_tokens: chunk.usage?.output_tokens || 0,\n prompt_tokens: chunk.usage?.input_tokens || 0,\n total_tokens:\n (chunk.usage?.input_tokens || 0) +\n (chunk.usage?.output_tokens || 0),\n },\n };\n controller.enqueue(\n encoder.encode(`data: ${JSON.stringify(res)}\\n\\n`)\n );\n } else if (\n chunk.type === \"content_block_delta\" &&\n chunk.delta?.type === \"input_json_delta\"\n ) {\n // \u5904\u7406\u5DE5\u5177\u8C03\u7528\u7684\u53C2\u6570\u589E\u91CF\n const res = {\n choices: [\n {\n delta: {\n tool_calls: [\n {\n index: chunk.index || 0,\n function: {\n arguments: chunk.delta.partial_json || \"\",\n },\n },\n ],\n },\n finish_reason: null,\n index: 0,\n logprobs: null,\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n id: chunk.id || \"\",\n model: chunk.model || \"\",\n object: \"chat.completion.chunk\",\n system_fingerprint: \"fp_a49d71b8a1\",\n usage: {\n completion_tokens: chunk.usage?.output_tokens || 0,\n prompt_tokens: chunk.usage?.input_tokens || 0,\n total_tokens:\n (chunk.usage?.input_tokens || 0) +\n (chunk.usage?.output_tokens || 0),\n },\n };\n controller.enqueue(\n encoder.encode(`data: ${JSON.stringify(res)}\\n\\n`)\n );\n } else if (\n chunk.type === \"content_block_start\" &&\n chunk.content_block?.type === \"tool_use\"\n ) {\n // \u5904\u7406\u5DE5\u5177\u8C03\u7528\u5F00\u59CB\n const res = {\n choices: [\n {\n delta: {\n tool_calls: [\n {\n index: chunk.index || 0,\n id: chunk.content_block.id,\n type: \"function\",\n function: {\n name: chunk.content_block.name,\n arguments: \"\",\n },\n },\n ],\n },\n finish_reason: null,\n index: 0,\n logprobs: null,\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n id: chunk.id || \"\",\n model: chunk.model || \"\",\n object: \"chat.completion.chunk\",\n system_fingerprint: \"fp_a49d71b8a1\",\n usage: {\n completion_tokens: chunk.usage?.output_tokens || 0,\n prompt_tokens: chunk.usage?.input_tokens || 0,\n total_tokens:\n (chunk.usage?.input_tokens || 0) +\n (chunk.usage?.output_tokens || 0),\n },\n };\n controller.enqueue(\n encoder.encode(`data: ${JSON.stringify(res)}\\n\\n`)\n );\n } else if (chunk.type === \"message_delta\") {\n // \u5904\u7406\u6D88\u606F\u7ED3\u675F\n const res = {\n choices: [\n {\n delta: {},\n finish_reason:\n chunk.delta?.stop_reason === \"tool_use\"\n ? \"tool_calls\"\n : chunk.delta?.stop_reason === \"max_tokens\"\n ? \"length\"\n : chunk.delta?.stop_reason === \"stop_sequence\"\n ? \"content_filter\"\n : \"stop\",\n index: 0,\n logprobs: null,\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n id: chunk.id || \"\",\n model: chunk.model || \"\",\n object: \"chat.completion.chunk\",\n system_fingerprint: \"fp_a49d71b8a1\",\n usage: {\n completion_tokens: chunk.usage?.output_tokens || 0,\n prompt_tokens: chunk.usage?.input_tokens || 0,\n total_tokens:\n (chunk.usage?.input_tokens || 0) +\n (chunk.usage?.output_tokens || 0),\n },\n };\n controller.enqueue(\n encoder.encode(`data: ${JSON.stringify(res)}\\n\\n`)\n );\n } else if (chunk.type === \"message_stop\") {\n // \u53D1\u9001\u7ED3\u675F\u6807\u8BB0\n controller.enqueue(encoder.encode(`data: [DONE]\\n\\n`));\n } else {\n // \u5904\u7406\u5176\u4ED6\u683C\u5F0F\u7684\u54CD\u5E94\uFF08\u4FDD\u6301\u539F\u6709\u903B\u8F91\u4F5C\u4E3A\u540E\u5907\uFF09\n const res = {\n choices: [\n {\n delta: {\n role: \"assistant\",\n content: chunk.content?.[0]?.text || \"\",\n },\n finish_reason: chunk.stop_reason?.toLowerCase() || null,\n index: 0,\n logprobs: null,\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n id: chunk.id || \"\",\n model: chunk.model || \"\",\n object: \"chat.completion.chunk\",\n system_fingerprint: \"fp_a49d71b8a1\",\n usage: {\n completion_tokens: chunk.usage?.output_tokens || 0,\n prompt_tokens: chunk.usage?.input_tokens || 0,\n total_tokens:\n (chunk.usage?.input_tokens || 0) +\n (chunk.usage?.output_tokens || 0),\n },\n };\n controller.enqueue(\n encoder.encode(`data: ${JSON.stringify(res)}\\n\\n`)\n );\n }\n } catch (error: any) {\n logger?.error(\n `Error parsing ${providerName} stream chunk`,\n chunkStr,\n error.message\n );\n }\n }\n }\n };\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n let buffer = \"\";\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n if (buffer) {\n processLine(buffer, controller);\n }\n break;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n processLine(line, controller);\n }\n }\n } catch (error) {\n controller.error(error);\n } finally {\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n }\n return response;\n}\n", "import { LLMProvider, UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer } from \"../types/transformer\";\nimport {\n buildRequestBody,\n transformRequestOut,\n transformResponseOut,\n} from \"../utils/vertex-claude.util\";\n\nasync function getAccessToken(): Promise {\n try {\n const { GoogleAuth } = await import('google-auth-library');\n\n const auth = new GoogleAuth({\n scopes: ['https://www.googleapis.com/auth/cloud-platform']\n });\n\n const client = await auth.getClient();\n const accessToken = await client.getAccessToken();\n return accessToken.token || '';\n } catch (error) {\n console.error('Error getting access token:', error);\n throw new Error('Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:\\n' +\n '1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file\\n' +\n '2. Run \"gcloud auth application-default login\"\\n' +\n '3. Use Google Cloud environment with default service account');\n }\n}\n\n\n\nexport class VertexClaudeTransformer implements Transformer {\n name = \"vertex-claude\";\n\n async transformRequestIn(\n request: UnifiedChatRequest,\n provider: LLMProvider\n ): Promise> {\n let projectId = process.env.GOOGLE_CLOUD_PROJECT;\n const location = process.env.GOOGLE_CLOUD_LOCATION || 'us-east5';\n\n if (!projectId && process.env.GOOGLE_APPLICATION_CREDENTIALS) {\n try {\n const fs = await import('fs');\n const keyContent = fs.readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS, 'utf8');\n const credentials = JSON.parse(keyContent);\n if (credentials && credentials.project_id) {\n projectId = credentials.project_id;\n }\n } catch (error) {\n console.error('Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:', error);\n }\n }\n\n if (!projectId) {\n throw new Error('Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.');\n }\n\n const accessToken = await getAccessToken();\n return {\n body: buildRequestBody(request),\n config: {\n url: new URL(\n `/v1/projects/${projectId}/locations/${location}/publishers/anthropic/models/${request.model}:${request.stream ? \"streamRawPredict\" : \"rawPredict\"}`,\n `https://${location}-aiplatform.googleapis.com`\n ).toString(),\n headers: {\n \"Authorization\": `Bearer ${accessToken}`,\n \"Content-Type\": \"application/json\",\n },\n },\n };\n }\n\n async transformRequestOut(request: Record): Promise {\n return transformRequestOut(request);\n }\n\n async transformResponseOut(response: Response): Promise {\n return transformResponseOut(response, this.name, this.logger);\n }\n}\n", "import { LLMProvider, UnifiedChatRequest, UnifiedMessage } from \"@/types/llm\";\nimport { Transformer } from \"@/types/transformer\";\n\n/**\n * Converts content from Claude Code format (array of objects) to plain string\n * @param content - The content to convert\n * @returns The converted string content\n */\nfunction convertContentToString(content: unknown): string {\n if (typeof content === 'string') {\n return content;\n }\n \n if (Array.isArray(content)) {\n return content\n .map(item => {\n if (typeof item === 'string') {\n return item;\n }\n if (typeof item === 'object' && item !== null && \n 'type' in item && item.type === 'text' && \n 'text' in item && typeof item.text === 'string') {\n return item.text;\n }\n return '';\n })\n .join('');\n }\n \n return '';\n}\n\n/**\n * Transformer class for Cerebras\n */\nexport class CerebrasTransformer implements Transformer {\n name = \"cerebras\";\n\n /**\n * Transform the request from Claude Code format to Cerebras format\n * @param request - The incoming request\n * @param provider - The LLM provider information\n * @returns The transformed request\n */\n async transformRequestIn(\n request: UnifiedChatRequest,\n provider: LLMProvider\n ): Promise> {\n // Deep clone the request to avoid modifying the original\n const transformedRequest = JSON.parse(JSON.stringify(request));\n \n // IMPORTANT: Cerebras API requires a model field in the request body\n // If model is not present in the request, use the first model from provider config\n if (!transformedRequest.model && provider.models && provider.models.length > 0) {\n transformedRequest.model = provider.models[0];\n }\n \n // Handle system field at the top level - convert to system message\n if (transformedRequest.system !== undefined) {\n const systemContent = convertContentToString(transformedRequest.system);\n // Add system message at the beginning of messages array\n if (!transformedRequest.messages) {\n transformedRequest.messages = [];\n }\n transformedRequest.messages.unshift({\n role: 'system',\n content: systemContent\n });\n // Remove the top-level system field as it's now in messages\n delete transformedRequest.system;\n }\n \n // Transform messages - IMPORTANT: This must convert ALL message content to strings\n if (transformedRequest.messages && Array.isArray(transformedRequest.messages)) {\n transformedRequest.messages = transformedRequest.messages.map((message: UnifiedMessage) => {\n const transformedMessage = { ...message };\n \n // Convert content to string format for ALL messages\n if (transformedMessage.content !== undefined) {\n transformedMessage.content = convertContentToString(transformedMessage.content);\n }\n \n return transformedMessage;\n });\n }\n \n return {\n body: transformedRequest,\n config: {\n headers: {\n 'Authorization': `Bearer ${provider.apiKey}`,\n 'Content-Type': 'application/json'\n }\n }\n };\n }\n\n /**\n * Transform the response\n * @param response - The response from Cerebras\n * @returns The transformed response\n */\n async transformResponseOut(response: Response): Promise {\n // Cerebras responses should be compatible with Claude Code\n // No transformation needed\n return response;\n }\n}", "import { UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer, TransformerOptions } from \"../types/transformer\";\n\nexport class StreamOptionsTransformer implements Transformer {\n name = \"streamoptions\";\n\n async transformRequestIn(\n request: UnifiedChatRequest\n ): Promise {\n if (!request.stream) return request;\n request.stream_options = {\n include_usage: true,\n };\n return request;\n }\n}\n", "import { AnthropicTransformer } from \"./anthropic.transformer\";\nimport { GeminiTransformer } from \"./gemini.transformer\";\nimport { VertexGeminiTransformer } from \"./vertex-gemini.transformer\";\nimport { DeepseekTransformer } from \"./deepseek.transformer\";\nimport { TooluseTransformer } from \"./tooluse.transformer\";\nimport { OpenrouterTransformer } from \"./openrouter.transformer\";\nimport { MaxTokenTransformer } from \"./maxtoken.transformer\";\nimport { GroqTransformer } from \"./groq.transformer\";\nimport { CleancacheTransformer } from \"./cleancache.transformer\";\nimport { EnhanceToolTransformer } from \"./enhancetool.transformer\";\nimport { ReasoningTransformer } from \"./reasoning.transformer\";\nimport { SamplingTransformer } from \"./sampling.transformer\";\nimport { MaxCompletionTokens } from \"./maxcompletiontokens.transformer\";\nimport { VertexClaudeTransformer } from \"./vertex-claude.transformer\";\nimport { CerebrasTransformer } from \"./cerebras.transformer\";\nimport { StreamOptionsTransformer } from \"./streamoptions.transformer\";\n\nexport default {\n AnthropicTransformer,\n GeminiTransformer,\n VertexGeminiTransformer,\n VertexClaudeTransformer,\n DeepseekTransformer,\n TooluseTransformer,\n OpenrouterTransformer,\n MaxTokenTransformer,\n GroqTransformer,\n CleancacheTransformer,\n EnhanceToolTransformer,\n ReasoningTransformer,\n SamplingTransformer,\n MaxCompletionTokens,\n CerebrasTransformer,\n StreamOptionsTransformer\n};\n", "import { Transformer, TransformerConstructor } from \"@/types/transformer\";\nimport { ConfigService } from \"./config\";\nimport Transformers from \"@/transformer\";\nimport Module from \"node:module\";\n\ninterface TransformerConfig {\n transformers: Array<{\n name: string;\n type: \"class\" | \"module\";\n path?: string;\n options?: any;\n }>;\n}\n\nexport class TransformerService {\n private transformers: Map =\n new Map();\n\n constructor(\n private readonly configService: ConfigService,\n private readonly logger: any\n ) {}\n\n registerTransformer(name: string, transformer: Transformer): void {\n this.transformers.set(name, transformer);\n this.logger.info(\n `register transformer: ${name}${\n transformer.endPoint\n ? ` (endpoint: ${transformer.endPoint})`\n : \" (no endpoint)\"\n }`\n );\n }\n\n getTransformer(\n name: string\n ): Transformer | TransformerConstructor | undefined {\n return this.transformers.get(name);\n }\n\n getAllTransformers(): Map {\n return new Map(this.transformers);\n }\n\n getTransformersWithEndpoint(): { name: string; transformer: Transformer }[] {\n const result: { name: string; transformer: Transformer }[] = [];\n\n this.transformers.forEach((transformer, name) => {\n if (transformer.endPoint) {\n result.push({ name, transformer });\n }\n });\n\n return result;\n }\n\n getTransformersWithoutEndpoint(): {\n name: string;\n transformer: Transformer;\n }[] {\n const result: { name: string; transformer: Transformer }[] = [];\n\n this.transformers.forEach((transformer, name) => {\n if (!transformer.endPoint) {\n result.push({ name, transformer });\n }\n });\n\n return result;\n }\n\n removeTransformer(name: string): boolean {\n return this.transformers.delete(name);\n }\n\n hasTransformer(name: string): boolean {\n return this.transformers.has(name);\n }\n\n async registerTransformerFromConfig(config: {\n path?: string;\n options?: any;\n }): Promise {\n try {\n if (config.path) {\n const module = require(require.resolve(config.path));\n if (module) {\n const instance = new module(config.options);\n // Set logger for transformer instance\n if (instance && typeof instance === \"object\") {\n (instance as any).logger = this.logger;\n }\n if (!instance.name) {\n throw new Error(\n `Transformer instance from ${config.path} does not have a name property.`\n );\n }\n this.registerTransformer(instance.name, instance);\n return true;\n }\n }\n return false;\n } catch (error: any) {\n this.logger.error(\n `load transformer (${config.path}) \\nerror: ${error.message}\\nstack: ${error.stack}`\n );\n return false;\n }\n }\n\n async initialize(): Promise {\n try {\n await this.registerDefaultTransformersInternal();\n await this.loadFromConfig();\n } catch (error: any) {\n this.logger.error(\n `TransformerService init error: ${error.message}\\nStack: ${error.stack}`\n );\n }\n }\n\n private async registerDefaultTransformersInternal(): Promise {\n try {\n Object.values(Transformers).forEach(\n (TransformerStatic: TransformerConstructor) => {\n if (\n \"TransformerName\" in TransformerStatic &&\n typeof TransformerStatic.TransformerName === \"string\"\n ) {\n this.registerTransformer(\n TransformerStatic.TransformerName,\n TransformerStatic\n );\n } else {\n const transformerInstance = new TransformerStatic();\n // Set logger for transformer instance\n if (\n transformerInstance &&\n typeof transformerInstance === \"object\"\n ) {\n (transformerInstance as any).logger = this.logger;\n }\n this.registerTransformer(\n transformerInstance.name!,\n transformerInstance\n );\n }\n }\n );\n } catch (error) {\n this.logger.error({ error }, \"transformer regist error:\");\n }\n }\n\n private async loadFromConfig(): Promise {\n const transformers = this.configService.get<\n TransformerConfig[\"transformers\"]\n >(\"transformers\", []);\n for (const transformer of transformers) {\n await this.registerTransformerFromConfig(transformer);\n }\n }\n}\n"], + "mappings": "6qBAAA,IAAAA,GAAAC,E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,EAC7C,QAAQ,GAAG,UAAW,IAAMA,EAAS,SAAS,CAAC,CACjD,OAASE,EAAO,CACd,KAAK,IAAI,IAAI,MAAM,0BAA0BA,CAAK,EAAE,EACpD,QAAQ,KAAK,CAAC,CAChB,CACF,CACF,EAGOC,GAAQtB", + "names": ["require_unicode", "__commonJSMin", "exports", "module", "require_util", "__commonJSMin", "exports", "module", "unicode", "c", "require_parse", "__commonJSMin", "exports", "module", "util", "source", "parseState", "stack", "pos", "line", "column", "token", "key", "root", "text", "reviver", "lex", "parseStates", "internalize", "holder", "name", "value", "i", "replacement", "lexState", "buffer", "doubleQuote", "sign", "c", "peek", "lexStates", "read", "newToken", "invalidChar", "literal", "u", "unicodeEscape", "invalidIdentifier", "escape", "separatorChar", "type", "s", "hexEscape", "count", "invalidEOF", "push", "pop", "parent", "current", "syntaxError", "formatChar", "replacements", "hexString", "message", "err", "require_stringify", "__commonJSMin", "exports", "module", "util", "value", "replacer", "space", "stack", "indent", "propertyList", "replacerFunc", "gap", "quote", "v", "item", "serializeProperty", "key", "holder", "quoteString", "serializeArray", "serializeObject", "quotes", "replacements", "product", "i", "c", "hexString", "quoteChar", "a", "b", "stepback", "keys", "partial", "propertyString", "member", "serializeKey", "final", "properties", "separator", "firstChar", "require_lib", "__commonJSMin", "exports", "module", "parse", "stringify", "JSON5", "require_extend", "__commonJSMin", "exports", "module", "hasOwn", "toStr", "defineProperty", "gOPD", "isArray", "arr", "isPlainObject", "obj", "hasOwnConstructor", "hasIsPrototypeOf", "key", "setProperty", "target", "options", "getProperty", "name", "extend", "src", "copy", "copyIsArray", "clone", "i", "length", "deep", "require_package", "__commonJSMin", "exports", "module", "pkg", "module", "exports", "defaultErrorRedactor", "extend_1", "__importDefault", "util_cjs_1", "pkg", "GaxiosError", "_GaxiosError", "instance", "message", "config", "response", "cause", "translateData", "res", "defaultErrorMessage", "status", "code", "errorMessages", "e", "responseType", "data", "REDACT", "redactHeaders", "headers", "_", "key", "redactString", "obj", "text", "redactObject", "exports", "getRetryConfig", "err", "config", "getConfig", "retryRanges", "shouldRetryRequest", "delay", "getNextRetryDelay", "backoff", "resolve", "isInRange", "min", "max", "status", "calculatedDelay", "maxAllowableDelay", "GaxiosInterceptorManager", "exports", "require_ms", "__commonJSMin", "exports", "module", "s", "m", "h", "d", "w", "y", "val", "options", "type", "parse", "fmtLong", "fmtShort", "str", "match", "n", "ms", "msAbs", "plural", "name", "isPlural", "require_common", "__commonJSMin", "exports", "module", "setup", "env", "createDebug", "coerce", "disable", "enable", "enabled", "destroy", "key", "selectColor", "namespace", "hash", "i", "prevTime", "enableOverride", "namespacesCache", "enabledCache", "debug", "args", "self", "curr", "ms", "index", "match", "format", "formatter", "val", "extend", "v", "delimiter", "newDebug", "namespaces", "split", "ns", "matchesTemplate", "search", "template", "searchIndex", "templateIndex", "starIndex", "matchIndex", "name", "skip", "require_browser", "__commonJSMin", "exports", "module", "formatArgs", "save", "load", "useColors", "localstorage", "warned", "m", "args", "c", "index", "lastC", "match", "namespaces", "formatters", "v", "error", "require_has_flag", "__commonJSMin", "exports", "module", "flag", "argv", "prefix", "pos", "terminatorPos", "require_supports_color", "__commonJSMin", "exports", "module", "os", "hasFlag", "env", "forceColor", "translateLevel", "level", "supportsColor", "stream", "min", "osRelease", "sign", "version", "getSupportLevel", "require_node", "__commonJSMin", "exports", "module", "tty", "util", "init", "log", "formatArgs", "save", "load", "useColors", "supportsColor", "key", "obj", "prop", "_", "k", "val", "args", "name", "c", "colorCode", "prefix", "getDate", "namespaces", "debug", "keys", "i", "formatters", "v", "str", "require_src", "__commonJSMin", "exports", "module", "http", "__importStar", "https", "toBuffer", "stream", "length", "chunks", "chunk", "exports", "json", "str", "_err", "err", "req", "url", "opts", "promise", "resolve", "reject", "net", "__importStar", "http", "https_1", "__exportStar", "exports", "INTERNAL", "Agent", "opts", "options", "stack", "l", "name", "fakeSocket", "socket", "sockets", "index", "req", "cb", "connectOpts", "err", "v", "debug_1", "__importDefault", "debug", "parseProxyResponse", "socket", "resolve", "reject", "buffersLength", "buffers", "read", "b", "ondata", "cleanup", "onend", "onerror", "err", "buffered", "endOfHeaders", "headerParts", "firstLine", "firstLineParts", "statusCode", "statusText", "headers", "header", "firstColon", "key", "value", "current", "exports", "net", "__importStar", "tls", "assert_1", "__importDefault", "debug_1", "agent_base_1", "url_1", "parse_proxy_response_1", "debug", "setServernameFromNonIpHost", "options", "HttpsProxyAgent", "proxy", "opts", "host", "port", "omit", "req", "socket", "headers", "payload", "auth", "name", "proxyResponsePromise", "connect", "buffered", "resume", "fakeSocket", "s", "exports", "obj", "keys", "ret", "key", "dataUriToBuffer", "uri", "firstComma", "meta", "charset", "base64", "type", "typeFull", "i", "encoding", "data", "buffer", "dist_default", "init_dist", "__esmMin", "noop", "typeIsObject", "x", "rethrowAssertionErrorRejection", "setFunctionName", "fn", "name", "originalPromise", "originalPromiseThen", "originalPromiseReject", "newPromise", "executor", "promiseResolvedWith", "value", "resolve", "promiseRejectedWith", "reason", "PerformPromiseThen", "promise", "onFulfilled", "onRejected", "uponPromise", "uponFulfillment", "uponRejection", "transformPromiseWith", "fulfillmentHandler", "rejectionHandler", "setPromiseIsHandledToTrue", "_queueMicrotask", "callback", "resolvedPromise", "cb", "reflectCall", "F", "V", "args", "promiseCall", "QUEUE_MAX_ARRAY_SIZE", "SimpleQueue", "element", "oldBack", "newBack", "oldFront", "newFront", "oldCursor", "newCursor", "elements", "i", "node", "front", "cursor", "AbortSteps", "ErrorSteps", "CancelSteps", "PullSteps", "ReleaseSteps", "ReadableStreamReaderGenericInitialize", "reader", "stream", "defaultReaderClosedPromiseInitialize", "defaultReaderClosedPromiseInitializeAsResolved", "defaultReaderClosedPromiseInitializeAsRejected", "ReadableStreamReaderGenericCancel", "ReadableStreamCancel", "ReadableStreamReaderGenericRelease", "defaultReaderClosedPromiseReject", "defaultReaderClosedPromiseResetToRejected", "readerLockException", "reject", "defaultReaderClosedPromiseResolve", "NumberIsFinite", "MathTrunc", "v", "isDictionary", "assertDictionary", "obj", "context", "assertFunction", "isObject", "assertObject", "assertRequiredArgument", "position", "assertRequiredField", "field", "convertUnrestrictedDouble", "censorNegativeZero", "integerPart", "convertUnsignedLongLongWithEnforceRange", "upperBound", "assertReadableStream", "IsReadableStream", "AcquireReadableStreamDefaultReader", "ReadableStreamDefaultReader", "ReadableStreamAddReadRequest", "readRequest", "ReadableStreamFulfillReadRequest", "chunk", "done", "ReadableStreamGetNumReadRequests", "ReadableStreamHasDefaultReader", "IsReadableStreamDefaultReader", "IsReadableStreamLocked", "defaultReaderBrandCheckException", "resolvePromise", "rejectPromise", "ReadableStreamDefaultReaderRead", "e", "ReadableStreamDefaultReaderRelease", "ReadableStreamDefaultReaderErrorReadRequests", "readRequests", "AsyncIteratorPrototype", "ReadableStreamAsyncIteratorImpl", "preventCancel", "nextSteps", "returnSteps", "queueMicrotask", "result", "ReadableStreamAsyncIteratorPrototype", "IsReadableStreamAsyncIterator", "streamAsyncIteratorBrandCheckException", "AcquireReadableStreamAsyncIterator", "impl", "iterator", "NumberIsNaN", "CreateArrayFromList", "CopyDataBlockBytes", "dest", "destOffset", "src", "srcOffset", "n", "TransferArrayBuffer", "O", "buffer", "IsDetachedBuffer", "ArrayBufferSlice", "begin", "end", "length", "slice", "GetMethod", "receiver", "prop", "func", "CreateAsyncFromSyncIterator", "syncIteratorRecord", "syncIterable", "asyncIterator", "nextMethod", "SymbolAsyncIterator", "_c", "_a", "_b", "GetIterator", "hint", "method", "syncMethod", "IteratorNext", "iteratorRecord", "IteratorComplete", "iterResult", "IteratorValue", "IsNonNegativeNumber", "CloneAsUint8Array", "DequeueValue", "container", "pair", "EnqueueValueWithSize", "size", "PeekQueueValue", "ResetQueue", "isDataViewConstructor", "ctor", "isDataView", "view", "arrayBufferViewElementSize", "ReadableStreamBYOBRequest", "IsReadableStreamBYOBRequest", "byobRequestBrandCheckException", "bytesWritten", "ReadableByteStreamControllerRespond", "ReadableByteStreamControllerRespondWithNewView", "ReadableByteStreamController", "IsReadableByteStreamController", "byteStreamControllerBrandCheckException", "ReadableByteStreamControllerGetBYOBRequest", "ReadableByteStreamControllerGetDesiredSize", "state", "ReadableByteStreamControllerClose", "ReadableByteStreamControllerEnqueue", "ReadableByteStreamControllerError", "ReadableByteStreamControllerClearPendingPullIntos", "ReadableByteStreamControllerClearAlgorithms", "ReadableByteStreamControllerFillReadRequestFromQueue", "autoAllocateChunkSize", "bufferE", "pullIntoDescriptor", "ReadableByteStreamControllerCallPullIfNeeded", "firstPullInto", "controller", "ReadableByteStreamControllerShouldCallPull", "pullPromise", "ReadableByteStreamControllerInvalidateBYOBRequest", "ReadableByteStreamControllerCommitPullIntoDescriptor", "filledView", "ReadableByteStreamControllerConvertPullIntoDescriptor", "ReadableStreamFulfillReadIntoRequest", "bytesFilled", "elementSize", "ReadableByteStreamControllerEnqueueChunkToQueue", "byteOffset", "byteLength", "ReadableByteStreamControllerEnqueueClonedChunkToQueue", "clonedChunk", "cloneE", "ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue", "firstDescriptor", "ReadableByteStreamControllerShiftPendingPullInto", "ReadableByteStreamControllerFillPullIntoDescriptorFromQueue", "maxBytesToCopy", "maxBytesFilled", "totalBytesToCopyRemaining", "ready", "remainderBytes", "maxAlignedBytes", "queue", "headOfQueue", "bytesToCopy", "destStart", "ReadableByteStreamControllerFillHeadPullIntoDescriptor", "ReadableByteStreamControllerHandleQueueDrain", "ReadableStreamClose", "ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue", "ReadableByteStreamControllerProcessReadRequestsUsingQueue", "ReadableByteStreamControllerPullInto", "min", "readIntoRequest", "minimumFill", "ReadableStreamAddReadIntoRequest", "emptyView", "ReadableByteStreamControllerRespondInClosedState", "ReadableStreamHasBYOBReader", "ReadableStreamGetNumReadIntoRequests", "ReadableByteStreamControllerRespondInReadableState", "remainderSize", "ReadableByteStreamControllerRespondInternal", "firstPendingPullInto", "transferredBuffer", "transferredView", "ReadableStreamError", "entry", "byobRequest", "SetUpReadableStreamBYOBRequest", "viewByteLength", "SetUpReadableByteStreamController", "startAlgorithm", "pullAlgorithm", "cancelAlgorithm", "highWaterMark", "startResult", "r", "SetUpReadableByteStreamControllerFromUnderlyingSource", "underlyingByteSource", "request", "convertReaderOptions", "options", "mode", "convertReadableStreamReaderMode", "convertByobReadOptions", "AcquireReadableStreamBYOBReader", "ReadableStreamBYOBReader", "IsReadableStreamBYOBReader", "byobReaderBrandCheckException", "rawOptions", "ReadableStreamBYOBReaderRead", "ReadableStreamBYOBReaderRelease", "ReadableStreamBYOBReaderErrorReadIntoRequests", "readIntoRequests", "ExtractHighWaterMark", "strategy", "defaultHWM", "ExtractSizeAlgorithm", "convertQueuingStrategy", "init", "convertQueuingStrategySize", "convertUnderlyingSink", "original", "abort", "close", "start", "type", "write", "convertUnderlyingSinkAbortCallback", "convertUnderlyingSinkCloseCallback", "convertUnderlyingSinkStartCallback", "convertUnderlyingSinkWriteCallback", "assertWritableStream", "IsWritableStream", "isAbortSignal", "supportsAbortController", "createAbortController", "WritableStream", "rawUnderlyingSink", "rawStrategy", "underlyingSink", "InitializeWritableStream", "sizeAlgorithm", "SetUpWritableStreamDefaultControllerFromUnderlyingSink", "streamBrandCheckException", "IsWritableStreamLocked", "WritableStreamAbort", "WritableStreamCloseQueuedOrInFlight", "WritableStreamClose", "AcquireWritableStreamDefaultWriter", "WritableStreamDefaultWriter", "CreateWritableStream", "writeAlgorithm", "closeAlgorithm", "abortAlgorithm", "WritableStreamDefaultController", "SetUpWritableStreamDefaultController", "wasAlreadyErroring", "WritableStreamStartErroring", "closeRequest", "writer", "defaultWriterReadyPromiseResolve", "WritableStreamDefaultControllerClose", "WritableStreamAddWriteRequest", "writeRequest", "WritableStreamDealWithRejection", "error", "WritableStreamFinishErroring", "WritableStreamDefaultWriterEnsureReadyPromiseRejected", "WritableStreamHasOperationMarkedInFlight", "storedError", "WritableStreamRejectCloseAndClosedPromiseIfNeeded", "abortRequest", "WritableStreamFinishInFlightWrite", "WritableStreamFinishInFlightWriteWithError", "WritableStreamFinishInFlightClose", "defaultWriterClosedPromiseResolve", "WritableStreamFinishInFlightCloseWithError", "WritableStreamMarkCloseRequestInFlight", "WritableStreamMarkFirstWriteRequestInFlight", "defaultWriterClosedPromiseReject", "WritableStreamUpdateBackpressure", "backpressure", "defaultWriterReadyPromiseReset", "defaultWriterReadyPromiseInitialize", "defaultWriterReadyPromiseInitializeAsResolved", "defaultWriterClosedPromiseInitialize", "defaultWriterReadyPromiseInitializeAsRejected", "defaultWriterClosedPromiseInitializeAsResolved", "defaultWriterClosedPromiseInitializeAsRejected", "IsWritableStreamDefaultWriter", "defaultWriterBrandCheckException", "defaultWriterLockException", "WritableStreamDefaultWriterGetDesiredSize", "WritableStreamDefaultWriterAbort", "WritableStreamDefaultWriterClose", "WritableStreamDefaultWriterRelease", "WritableStreamDefaultWriterWrite", "WritableStreamDefaultWriterCloseWithErrorPropagation", "WritableStreamDefaultWriterEnsureClosedPromiseRejected", "defaultWriterClosedPromiseResetToRejected", "defaultWriterReadyPromiseReject", "defaultWriterReadyPromiseResetToRejected", "WritableStreamDefaultControllerGetDesiredSize", "releasedError", "chunkSize", "WritableStreamDefaultControllerGetChunkSize", "WritableStreamDefaultControllerWrite", "closeSentinel", "IsWritableStreamDefaultController", "defaultControllerBrandCheckException", "WritableStreamDefaultControllerError", "WritableStreamDefaultControllerClearAlgorithms", "WritableStreamDefaultControllerGetBackpressure", "startPromise", "WritableStreamDefaultControllerAdvanceQueueIfNeeded", "chunkSizeE", "WritableStreamDefaultControllerErrorIfNeeded", "enqueueE", "WritableStreamDefaultControllerProcessClose", "WritableStreamDefaultControllerProcessWrite", "sinkClosePromise", "sinkWritePromise", "getGlobals", "globals", "isDOMExceptionConstructor", "getFromGlobal", "createPolyfill", "message", "DOMException", "ReadableStreamPipeTo", "source", "preventClose", "preventAbort", "signal", "shuttingDown", "currentWrite", "actions", "shutdownWithAction", "action", "pipeLoop", "resolveLoop", "rejectLoop", "next", "pipeStep", "resolveRead", "rejectRead", "isOrBecomesErrored", "shutdown", "isOrBecomesClosed", "destClosed", "waitForWritesToFinish", "oldCurrentWrite", "originalIsError", "originalError", "doTheRest", "finalize", "newError", "isError", "ReadableStreamDefaultController", "IsReadableStreamDefaultController", "ReadableStreamDefaultControllerGetDesiredSize", "ReadableStreamDefaultControllerCanCloseOrEnqueue", "ReadableStreamDefaultControllerClose", "ReadableStreamDefaultControllerEnqueue", "ReadableStreamDefaultControllerError", "ReadableStreamDefaultControllerClearAlgorithms", "ReadableStreamDefaultControllerCallPullIfNeeded", "ReadableStreamDefaultControllerShouldCallPull", "ReadableStreamDefaultControllerHasBackpressure", "SetUpReadableStreamDefaultController", "SetUpReadableStreamDefaultControllerFromUnderlyingSource", "underlyingSource", "ReadableStreamTee", "cloneForBranch2", "ReadableByteStreamTee", "ReadableStreamDefaultTee", "reading", "readAgain", "canceled1", "canceled2", "reason1", "reason2", "branch1", "branch2", "resolveCancelPromise", "cancelPromise", "chunk1", "chunk2", "cancel1Algorithm", "compositeReason", "cancelResult", "cancel2Algorithm", "CreateReadableStream", "readAgainForBranch1", "readAgainForBranch2", "forwardReaderError", "thisReader", "pullWithDefaultReader", "pull1Algorithm", "pull2Algorithm", "pullWithBYOBReader", "forBranch2", "byobBranch", "otherBranch", "byobCanceled", "otherCanceled", "CreateReadableByteStream", "isReadableStreamLike", "ReadableStreamFrom", "ReadableStreamFromDefaultReader", "ReadableStreamFromIterable", "asyncIterable", "nextResult", "nextPromise", "returnMethod", "returnResult", "returnPromise", "readPromise", "readResult", "convertUnderlyingDefaultOrByteSource", "cancel", "pull", "convertUnderlyingSourceCancelCallback", "convertUnderlyingSourcePullCallback", "convertUnderlyingSourceStartCallback", "convertReadableStreamType", "convertIteratorOptions", "convertPipeOptions", "assertAbortSignal", "convertReadableWritablePair", "readable", "writable", "ReadableStream", "rawUnderlyingSource", "InitializeReadableStream", "rawTransform", "transform", "destination", "branches", "sourceCancelPromise", "convertQueuingStrategyInit", "byteLengthSizeFunction", "ByteLengthQueuingStrategy", "IsByteLengthQueuingStrategy", "byteLengthBrandCheckException", "countSizeFunction", "CountQueuingStrategy", "IsCountQueuingStrategy", "countBrandCheckException", "convertTransformer", "flush", "readableType", "writableType", "convertTransformerCancelCallback", "convertTransformerFlushCallback", "convertTransformerStartCallback", "convertTransformerTransformCallback", "TransformStream", "rawTransformer", "rawWritableStrategy", "rawReadableStrategy", "writableStrategy", "readableStrategy", "transformer", "readableHighWaterMark", "readableSizeAlgorithm", "writableHighWaterMark", "writableSizeAlgorithm", "startPromise_resolve", "InitializeTransformStream", "SetUpTransformStreamDefaultControllerFromTransformer", "IsTransformStream", "TransformStreamDefaultSinkWriteAlgorithm", "TransformStreamDefaultSinkAbortAlgorithm", "TransformStreamDefaultSinkCloseAlgorithm", "TransformStreamDefaultSourcePullAlgorithm", "TransformStreamDefaultSourceCancelAlgorithm", "TransformStreamSetBackpressure", "TransformStreamError", "TransformStreamErrorWritableAndUnblockWrite", "TransformStreamDefaultControllerClearAlgorithms", "TransformStreamUnblockWrite", "TransformStreamDefaultController", "IsTransformStreamDefaultController", "readableController", "TransformStreamDefaultControllerEnqueue", "TransformStreamDefaultControllerError", "TransformStreamDefaultControllerTerminate", "SetUpTransformStreamDefaultController", "transformAlgorithm", "flushAlgorithm", "transformResultE", "TransformStreamDefaultControllerPerformTransform", "transformPromise", "backpressureChangePromise", "defaultControllerFinishPromiseReject", "defaultControllerFinishPromiseResolve", "flushPromise", "require_streams", "__commonJSMin", "process", "emitWarning", "error", "Blob", "params", "position", "blob", "ctrl", "buffer", "toIterator", "parts", "clone", "part", "position", "end", "size", "POOL_SIZE", "chunk", "b", "buffer", "import_streams", "_Blob", "Blob", "fetch_blob_default", "init_fetch_blob", "__esmMin", "#parts", "#type", "#size", "#endings", "blobParts", "options", "encoder", "element", "type", "decoder", "str", "data", "offset", "it", "ctrl", "start", "relativeStart", "relativeEnd", "span", "added", "blob", "object", "_File", "File", "file_default", "init_file", "__esmMin", "init_fetch_blob", "fetch_blob_default", "#lastModified", "#name", "fileBits", "fileName", "options", "lastModified", "object", "formDataToBlob", "F", "B", "fetch_blob_default", "b", "r", "c", "p", "v", "n", "e", "t", "i", "h", "m", "f", "x", "FormData", "init_esm_min", "__esmMin", "init_fetch_blob", "init_file", "a", "file_default", "#d", "o", "l", "d", "FetchBaseError", "init_base", "__esmMin", "message", "type", "FetchError", "init_fetch_error", "__esmMin", "init_base", "FetchBaseError", "message", "type", "systemError", "NAME", "isURLSearchParameters", "isBlob", "isAbortSignal", "isDomainOrSubdomain", "isSameProtocol", "init_is", "__esmMin", "object", "destination", "original", "orig", "dest", "require_node_domexception", "__commonJSMin", "exports", "module", "MessageChannel", "port", "ab", "err", "import_node_fs", "import_node_path", "import_node_domexception", "stat", "blobFromSync", "blobFrom", "fileFrom", "fileFromSync", "fromBlob", "fromFile", "BlobDataItem", "init_from", "__esmMin", "init_file", "init_fetch_blob", "fs", "path", "type", "fetch_blob_default", "file_default", "_BlobDataItem", "#path", "#start", "options", "start", "end", "mtimeMs", "DOMException", "multipart_parser_exports", "__export", "toFormData", "_fileName", "headerValue", "m", "match", "filename", "code", "Body", "ct", "parser", "MultipartParser", "headerField", "entryValue", "entryName", "contentType", "entryChunks", "formData", "FormData", "onPartData", "ui8a", "decoder", "appendToFile", "appendFileToFormData", "file", "file_default", "appendEntryToFormData", "chunk", "s", "S", "f", "F", "LF", "CR", "SPACE", "HYPHEN", "COLON", "A", "Z", "lower", "noop", "init_multipart_parser", "__esmMin", "init_from", "init_esm_min", "c", "boundary", "i", "data", "length_", "previousIndex", "lookbehind", "boundaryChars", "index", "state", "flags", "boundaryLength", "boundaryEnd", "bufferLength", "cl", "mark", "name", "clear", "callback", "callbackSymbol", "start", "end", "dataCallback", "markSymbol", "_lookbehind", "consumeBody", "data", "INTERNALS", "body", "Stream", "accum", "accumBytes", "chunk", "error", "FetchError", "FetchBaseError", "c", "import_node_stream", "import_node_util", "import_node_buffer", "pipeline", "Body", "clone", "getNonSpecFormDataBoundary", "extractContentType", "getTotalBytes", "writeToStream", "init_body", "__esmMin", "init_fetch_blob", "init_esm_min", "init_fetch_error", "init_base", "init_is", "size", "boundary", "isURLSearchParameters", "isBlob", "FormData", "formDataToBlob", "stream", "error_", "buffer", "byteOffset", "byteLength", "ct", "formData", "parameters", "name", "value", "toFormData", "buf", "fetch_blob_default", "text", "instance", "highWaterMark", "p1", "p2", "request", "dest", "fromRawHeaders", "headers", "Headers", "result", "value", "index", "array", "name", "validateHeaderName", "validateHeaderValue", "import_node_util", "import_node_http", "init_headers", "__esmMin", "http", "error", "_Headers", "init", "raw", "values", "method", "pair", "target", "p", "receiver", "callback", "thisArg", "key", "property", "redirectStatus", "isRedirect", "init_is_redirect", "__esmMin", "code", "INTERNALS", "Response", "init_response", "__esmMin", "init_headers", "init_body", "init_is_redirect", "_Response", "Body", "body", "options", "status", "headers", "Headers", "contentType", "extractContentType", "clone", "url", "isRedirect", "response", "data", "init", "getSearch", "init_get_search", "__esmMin", "parsedURL", "lastOffset", "hash", "stripURLForUseAsAReferrer", "url", "originOnly", "validateReferrerPolicy", "referrerPolicy", "ReferrerPolicy", "isOriginPotentiallyTrustworthy", "hostIp", "hostIPVersion", "isUrlPotentiallyTrustworthy", "determineRequestsReferrer", "request", "referrerURLCallback", "referrerOriginCallback", "policy", "referrerSource", "referrerURL", "referrerOrigin", "currentURL", "parseReferrerPolicyFromHeader", "headers", "policyTokens", "token", "import_node_net", "DEFAULT_REFERRER_POLICY", "init_referrer", "__esmMin", "import_node_url", "import_node_util", "INTERNALS", "isRequest", "doBadDataWarn", "Request", "getNodeRequestOptions", "init_request", "__esmMin", "init_headers", "init_body", "init_is", "init_get_search", "init_referrer", "object", "_Request", "Body", "input", "init", "parsedURL", "method", "inputBody", "clone", "headers", "Headers", "contentType", "extractContentType", "signal", "isAbortSignal", "referrer", "parsedReferrer", "formatUrl", "referrerPolicy", "validateReferrerPolicy", "request", "contentLengthValue", "totalBytes", "getTotalBytes", "DEFAULT_REFERRER_POLICY", "determineRequestsReferrer", "agent", "search", "getSearch", "options", "AbortError", "init_abort_error", "__esmMin", "init_base", "FetchBaseError", "message", "type", "src_exports", "__export", "AbortError", "fetch_blob_default", "FetchError", "file_default", "FormData", "Headers", "Request", "Response", "blobFrom", "blobFromSync", "fetch", "fileFrom", "fileFromSync", "isRedirect", "url", "options_", "resolve", "reject", "request", "parsedURL", "options", "getNodeRequestOptions", "supportedSchemas", "data", "dist_default", "response", "send", "https", "http", "signal", "abort", "error", "Stream", "abortAndFinalize", "finalize", "request_", "fixResponseChunkedTransferBadEnding", "s", "endedWithEventsCount", "hadError", "response_", "headers", "fromRawHeaders", "location", "locationURL", "requestOptions", "clone", "isDomainOrSubdomain", "isSameProtocol", "name", "responseReferrerPolicy", "parseReferrerPolicyFromHeader", "body", "pump", "responseOptions", "codings", "zlibOptions", "zlib", "raw", "chunk", "writeToStream", "errorCallback", "LAST_CHUNK", "isChunkedTransfer", "properLastChunkReceived", "previousChunk", "socket", "onSocketClose", "onData", "buf", "import_node_http", "import_node_https", "import_node_zlib", "import_node_stream", "import_node_buffer", "init_src", "__esmMin", "init_dist", "init_body", "init_response", "init_headers", "init_request", "init_fetch_error", "init_abort_error", "init_is_redirect", "init_esm_min", "init_is", "init_referrer", "init_from", "extend_1", "__importDefault", "https_1", "common_js_1", "retry_js_1", "stream_1", "interceptor_js_1", "randomUUID", "Gaxios", "defaults", "args", "input", "init", "url", "headers", "_a", "opts", "prepared", "#prepareRequest", "#applyRequestInterceptors", "#applyResponseInterceptors", "config", "fetchImpl", "#getFetch", "preparedOpts", "res", "data", "translatedResponse", "response", "chunk", "errorInfo", "e", "err", "shouldRetry", "#appendTimeoutToSignal", "#urlMayUseProxy", "noProxy", "candidate", "noProxyList", "noProxyEnvList", "rule", "cleanedRule", "options", "promiseChain", "interceptor", "preparedHeaders", "additionalQueryParams", "prefix", "key", "value", "shouldDirectlyPassData", "boundary", "proxy", "HttpsProxyAgent", "#getProxyAgent", "timeoutSignal", "status", "contentType", "multipartOptions", "finale", "currentPart", "partContentType", "#proxyAgent", "#fetch", "hasWindow", "base", "append", "exports", "exports", "request", "gaxios_js_1", "common_js_1", "__exportStar", "opts", "require_bignumber", "__commonJSMin", "exports", "module", "globalObject", "BigNumber", "isNumeric", "mathceil", "mathfloor", "bignumberError", "tooManyDigits", "BASE", "LOG_BASE", "MAX_SAFE_INTEGER", "POWS_TEN", "SQRT_BASE", "MAX", "clone", "configObject", "div", "convertBase", "parseNumeric", "P", "ONE", "DECIMAL_PLACES", "ROUNDING_MODE", "TO_EXP_NEG", "TO_EXP_POS", "MIN_EXP", "MAX_EXP", "CRYPTO", "MODULO_MODE", "POW_PRECISION", "FORMAT", "ALPHABET", "alphabetHasNormalDecimalDigits", "v", "b", "alphabet", "c", "caseChanged", "e", "i", "isNum", "len", "str", "x", "intCheck", "round", "obj", "p", "n", "s", "out", "maxOrMin", "pow2_53", "random53bitInt", "dp", "a", "k", "rand", "args", "sum", "decimal", "toBaseOut", "baseIn", "baseOut", "j", "arr", "arrL", "sign", "callerIsToString", "d", "r", "xc", "y", "rm", "toFixedPoint", "coeffToString", "multiply", "base", "m", "temp", "xlo", "xhi", "carry", "klo", "khi", "compare", "aL", "bL", "cmp", "subtract", "more", "prod", "prodL", "q", "qc", "rem", "remL", "rem0", "xi", "xL", "yc0", "yL", "yz", "yc", "bitFloor", "format", "id", "c0", "ne", "toExponential", "normalise", "basePrefix", "dotAfter", "dotBefore", "isInfinityOrNaN", "whitespaceOrPlus", "p1", "p2", "sd", "ni", "rd", "pows10", "valueOf", "half", "isModExp", "nIsBig", "nIsNeg", "nIsOdd", "isOdd", "t", "xLTy", "xe", "ye", "xcL", "ycL", "ylo", "yhi", "zc", "sqrtBase", "rep", "g1", "g2", "groupSeparator", "intPart", "fractionPart", "isNeg", "intDigits", "md", "d0", "d1", "d2", "exp", "n0", "n1", "z", "l", "min", "max", "name", "zs", "require_stringify", "__commonJSMin", "exports", "module", "BigNumber", "JSON", "f", "n", "cx", "escapable", "gap", "indent", "meta", "rep", "quote", "string", "a", "c", "str", "key", "holder", "i", "k", "v", "length", "mind", "partial", "value", "isBigNumber", "replacer", "space", "require_parse", "__commonJSMin", "exports", "module", "BigNumber", "suspectProtoRx", "suspectConstructorRx", "json_parse", "options", "_options", "at", "ch", "escapee", "text", "error", "m", "next", "c", "number", "string", "hex", "i", "uffff", "startAt", "white", "word", "value", "array", "object", "key", "source", "reviver", "result", "walk", "holder", "k", "v", "require_json_bigint", "__commonJSMin", "exports", "module", "json_stringify", "json_parse", "options", "exports", "isGoogleCloudServerless", "isGoogleComputeEngineLinux", "isGoogleComputeEngineMACAddress", "isGoogleComputeEngine", "detectGCPResidency", "fs_1", "os_1", "GCE_MAC_ADDRESS_REGEX", "biosVendor", "interfaces", "item", "mac", "Colours", "_Colours", "stream", "exports", "exports", "getNodeBackend", "getDebugBackend", "getStructuredBackend", "setBackend", "log", "events_1", "process", "__importStar", "util", "colours_1", "LogSeverity", "AdhocDebugLogger", "namespace", "upstream", "event", "listener", "args", "fields", "severity", "DebugLogBackendBase", "nodeFlag", "_a", "logger", "e", "NodeBackend", "nscolour", "pid", "level", "msg", "filteredFields", "fieldsJson", "fieldsColour", "regexp", "DebugBackend", "pkg", "debugLogger", "existingFilters", "debugPkg", "StructuredBackend", "json", "jsonString", "loggerCache", "cachedBackend", "backend", "parent", "existing", "previousBackend", "__exportStar", "exports", "exports", "instance", "project", "universe", "bulk", "isAvailable", "resetIsAvailableCache", "getGCPResidency", "setGCPResidency", "requestTimeout", "gaxios_1", "jsonBigint", "gcp_residency_1", "logger", "__importStar", "log", "getBaseUrl", "baseUrl", "validate", "options", "key", "metadataAccessor", "type", "noResponseRetries", "fastFail", "headers", "metadataKey", "params", "value", "requestMethod", "fastFailMetadataRequest", "req", "res", "metadataFlavor", "secondaryOptions", "r1", "r2", "properties", "r", "item", "detectGCPAvailableRetries", "cachedIsAvailableResponse", "e", "err", "code", "__exportStar", "require_base64_js", "__commonJSMin", "exports", "byteLength", "toByteArray", "fromByteArray", "lookup", "revLookup", "Arr", "code", "i", "len", "getLens", "b64", "validLen", "placeHoldersLen", "lens", "_byteLength", "tmp", "arr", "curByte", "tripletToBase64", "num", "encodeChunk", "uint8", "start", "end", "output", "extraBytes", "parts", "maxChunkLength", "len2", "require_shared", "__commonJSMin", "exports", "fromArrayBufferToHex", "arrayBuffer", "byte", "require_crypto", "__commonJSMin", "exports", "base64js", "shared_1", "BrowserCrypto", "_BrowserCrypto", "str", "inputBuffer", "outputBuffer", "count", "array", "base64", "pubkey", "data", "signature", "algo", "dataArray", "signatureArray", "cryptoKey", "privateKey", "result", "uint8array", "text", "key", "msg", "rawKey", "enc", "require_crypto", "__commonJSMin", "exports", "crypto", "NodeCrypto", "str", "count", "pubkey", "data", "signature", "verifier", "privateKey", "signer", "base64", "text", "key", "msg", "cryptoKey", "toBuffer", "toArrayBuffer", "buffer", "arrayBuffer", "require_crypto", "__commonJSMin", "exports", "__createBinding", "o", "m", "k", "k2", "desc", "__exportStar", "p", "createCrypto", "hasBrowserCrypto", "crypto_1", "crypto_2", "require_safe_buffer", "__commonJSMin", "exports", "module", "buffer", "Buffer", "copyProps", "src", "dst", "key", "SafeBuffer", "arg", "encodingOrOffset", "length", "size", "fill", "encoding", "buf", "require_param_bytes_for_alg", "__commonJSMin", "exports", "module", "getParamSize", "keySize", "result", "paramBytesForAlg", "getParamBytesForAlg", "alg", "paramBytes", "require_ecdsa_sig_formatter", "__commonJSMin", "exports", "module", "Buffer", "getParamBytesForAlg", "MAX_OCTET", "CLASS_UNIVERSAL", "PRIMITIVE_BIT", "TAG_SEQ", "TAG_INT", "ENCODED_TAG_SEQ", "ENCODED_TAG_INT", "base64Url", "base64", "signatureAsBuffer", "signature", "derToJose", "alg", "paramBytes", "maxEncodedParamLength", "inputLength", "offset", "seqLength", "rLength", "rOffset", "sLength", "sOffset", "rPadding", "sPadding", "dst", "o", "countPadding", "buf", "start", "stop", "padding", "needsSign", "joseToDer", "signatureBytes", "rsBytes", "shortLength", "require_util", "__commonJSMin", "exports", "snakeToCamel", "originalOrCamelOptions", "removeUndefinedValuesInObject", "isValidFile", "getWellKnownCertificateConfigFileLocation", "fs", "os", "path", "WELL_KNOWN_CERTIFICATE_CONFIG_FILE", "CLOUDSDK_CONFIG_DIRECTORY", "str", "match", "obj", "get", "key", "o", "LRUCache", "#cache", "options", "#moveToEnd", "value", "#evict", "item", "cutoffDate", "oldestItem", "object", "filePath", "configDir", "_isWindows", "require_package", "__commonJSMin", "exports", "module", "require_shared", "__commonJSMin", "exports", "pkg", "PRODUCT_NAME", "USER_AGENT", "require_authclient", "__commonJSMin", "exports", "events_1", "gaxios_1", "util_1", "google_logging_utils_1", "shared_cjs_1", "AuthClient", "_AuthClient", "opts", "options", "args", "input", "init", "url", "headers", "credentials", "target", "source", "xGoogUserProject", "authorizationHeader", "config", "nodeVersion", "userAgent", "symbols", "methodName", "logId", "logObject", "response", "error", "require_loginticket", "__commonJSMin", "exports", "LoginTicket", "env", "pay", "payload", "require_oauth2client", "__commonJSMin", "exports", "gaxios_1", "querystring", "stream", "formatEcdsa", "util_1", "crypto_1", "authclient_1", "loginticket_1", "CodeChallengeMethod", "CertificateFormat", "ClientAuthentication", "OAuth2Client", "_OAuth2Client", "options", "clientSecret", "redirectUri", "opts", "crypto", "codeVerifier", "codeChallenge", "codeOrOptions", "callback", "r", "e", "url", "headers", "values", "basic", "res", "tokens", "refreshToken", "p", "data", "refreshedAccessToken", "thisCreds", "err", "credentials", "token", "reAuthRetried", "statusCode", "mayRequireRefresh", "mayRequireRefreshWithNoRefreshToken", "isReadableStream", "isAuthErr", "response", "accessToken", "info", "nowTime", "format", "cacheControl", "cacheAge", "maxAge", "certificates", "key", "now", "jwt", "certs", "requiredAudience", "issuers", "maxExpiry", "segments", "signed", "signature", "envelope", "payload", "cert", "iat", "exp", "earliest", "latest", "aud", "audVerified", "accessTokenResponse", "expiryDate", "require_computeclient", "__commonJSMin", "exports", "gaxios_1", "gcpMetadata", "oauth2client_1", "Compute", "options", "tokenPath", "data", "instanceOptions", "e", "tokens", "targetAudience", "idTokenPath", "idToken", "res", "require_idtokenclient", "__commonJSMin", "exports", "oauth2client_1", "IdTokenClient", "options", "idToken", "payloadB64", "require_envDetect", "__commonJSMin", "exports", "clear", "getEnv", "gcpMetadata", "GCPEnv", "envPromise", "getEnvMemoized", "env", "isAppEngine", "isCloudFunction", "isComputeEngine", "isKubernetesEngine", "isCloudRun", "require_data_stream", "__commonJSMin", "exports", "module", "Buffer", "Stream", "util", "DataStream", "data", "require_buffer_equal_constant_time", "__commonJSMin", "exports", "module", "Buffer", "SlowBuffer", "bufferEq", "a", "b", "c", "i", "that", "origBufEqual", "origSlowBufEqual", "require_jwa", "__commonJSMin", "exports", "module", "Buffer", "crypto", "formatEcdsa", "util", "MSG_INVALID_ALGORITHM", "MSG_INVALID_SECRET", "MSG_INVALID_VERIFIER_KEY", "MSG_INVALID_SIGNER_KEY", "supportsKeyObjects", "checkIsPublicKey", "key", "typeError", "checkIsPrivateKey", "checkIsSecretKey", "fromBase64", "base64", "toBase64", "base64url", "padding", "i", "template", "args", "errMsg", "bufferOrString", "obj", "normalizeInput", "thing", "createHmacSigner", "bits", "secret", "hmac", "sig", "bufferEqual", "timingSafeEqual", "a", "b", "createHmacVerifier", "signature", "computedSig", "createKeySigner", "privateKey", "signer", "createKeyVerifier", "publicKey", "verifier", "createPSSKeySigner", "createPSSKeyVerifier", "createECDSASigner", "inner", "createECDSAVerifer", "result", "createNoneSigner", "createNoneVerifier", "algorithm", "signerFactories", "verifierFactories", "match", "algo", "require_tostring", "__commonJSMin", "exports", "module", "Buffer", "obj", "require_sign_stream", "__commonJSMin", "exports", "module", "Buffer", "DataStream", "jwa", "Stream", "toString", "util", "base64url", "string", "encoding", "jwsSecuredInput", "header", "payload", "encodedHeader", "encodedPayload", "jwsSign", "opts", "secretOrKey", "algo", "securedInput", "signature", "SignStream", "secret", "secretStream", "e", "require_verify_stream", "__commonJSMin", "exports", "module", "Buffer", "DataStream", "jwa", "Stream", "toString", "util", "JWS_REGEX", "isObject", "thing", "safeJsonParse", "headerFromJWS", "jwsSig", "encodedHeader", "securedInputFromJWS", "signatureFromJWS", "payloadFromJWS", "encoding", "payload", "isValidJws", "string", "jwsVerify", "algorithm", "secretOrKey", "err", "signature", "securedInput", "algo", "jwsDecode", "opts", "header", "VerifyStream", "secretStream", "valid", "obj", "e", "require_jws", "__commonJSMin", "exports", "SignStream", "VerifyStream", "ALGORITHMS", "opts", "require_src", "__commonJSMin", "exports", "fs", "_interopRequireWildcard", "_gaxios", "jws", "path", "_util", "e", "t", "r", "o", "i", "f", "_typeof", "_t3", "_classPrivateMethodInitSpec", "a", "_checkPrivateRedeclaration", "_classPrivateFieldInitSpec", "_classPrivateFieldSet", "s", "_assertClassBrand", "_classPrivateFieldGet", "n", "_defineProperties", "_toPropertyKey", "_createClass", "_classCallCheck", "_callSuper", "_getPrototypeOf", "_possibleConstructorReturn", "_isNativeReflectConstruct", "_assertThisInitialized", "_inherits", "_setPrototypeOf", "_wrapNativeSuper", "_isNativeFunction", "Wrapper", "_construct", "p", "_defineProperty", "_toPrimitive", "_regenerator", "c", "Generator", "u", "_regeneratorDefine2", "y", "G", "d", "l", "GeneratorFunction", "GeneratorFunctionPrototype", "asyncGeneratorStep", "_asyncToGenerator", "_next", "_throw", "readFile", "_callee", "_context", "ErrorWithCode", "GOOGLE_TOKEN_URL", "GOOGLE_REVOKE_TOKEN_URL", "_Error", "message", "code", "_this", "_inFlightRequest", "_GoogleToken_brand", "GoogleToken", "_options", "opts", "_configure", "now", "_this$eagerRefreshThr", "eagerRefreshThresholdMillis", "callback", "cb", "_getTokenAsync", "_getCredentials", "_callee2", "keyFile", "ext", "key", "body", "privateKey", "clientEmail", "_privateKey", "_t", "_context2", "getCredentials", "_x", "_revokeTokenAsync", "_x2", "_getTokenAsync2", "_callee3", "_context3", "_getTokenAsyncInner", "_x3", "_getTokenAsyncInner2", "_callee4", "creds", "_context4", "_ensureEmail", "_requestToken", "_revokeTokenAsync2", "_callee5", "url", "_context5", "options", "_requestToken2", "_callee6", "iat", "additionalClaims", "payload", "signedJWT", "_response", "_response2", "desc", "_t2", "_context6", "require_jwtaccess", "__commonJSMin", "exports", "jws", "util_1", "DEFAULT_HEADER", "JWTAccess", "_JWTAccess", "email", "key", "keyId", "eagerRefreshThresholdMillis", "url", "scopes", "cacheKey", "additionalClaims", "cachedToken", "now", "iat", "exp", "defaultClaims", "claim", "header", "payload", "signedJWT", "headers", "json", "inputStream", "callback", "resolve", "reject", "s", "chunk", "data", "err", "require_jwtclient", "__commonJSMin", "exports", "gtoken_1", "jwtaccess_1", "oauth2client_1", "authclient_1", "JWT", "_JWT", "options", "scopes", "jwt", "url", "useSelfSignedJWT", "tokens", "useScopes", "headers", "targetAudience", "gtoken", "callback", "r", "result", "json", "inputStream", "resolve", "reject", "s", "chunk", "data", "e", "apiKey", "creds", "require_refreshclient", "__commonJSMin", "exports", "oauth2client_1", "authclient_1", "UserRefreshClient", "_UserRefreshClient", "optionsOrClientId", "clientSecret", "refreshToken", "eagerRefreshThresholdMillis", "forceRefreshOnFailure", "opts", "targetAudience", "json", "inputStream", "callback", "resolve", "reject", "s", "chunk", "data", "err", "client", "require_impersonated", "__commonJSMin", "exports", "oauth2client_1", "gaxios_1", "util_1", "Impersonated", "_Impersonated", "options", "blobToSign", "name", "u", "body", "res", "tokenResponse", "error", "status", "message", "targetAudience", "require_oauth2common", "__commonJSMin", "exports", "getErrorFromOAuthErrorResponse", "gaxios_1", "crypto_1", "METHODS_SUPPORTING_REQUEST_BODY", "OAuthClientAuthHandler", "#crypto", "#clientAuthentication", "options", "opts", "bearerToken", "clientId", "clientSecret", "base64EncodedCreds", "method", "contentType", "data", "resp", "err", "errorCode", "errorDescription", "errorUri", "message", "newError", "keys", "key", "require_stscredentials", "__commonJSMin", "exports", "gaxios_1", "authclient_1", "oauth2common_1", "util_1", "StsCredentials", "_StsCredentials", "#tokenExchangeEndpoint", "options", "clientAuthentication", "stsCredentialsOptions", "headers", "values", "opts", "response", "stsSuccessfulResponse", "error", "require_baseexternalclient", "__commonJSMin", "exports", "gaxios_1", "stream", "authclient_1", "sts", "util_1", "shared_cjs_1", "STS_GRANT_TYPE", "STS_REQUEST_TOKEN_TYPE", "DEFAULT_OAUTH_SCOPE", "DEFAULT_TOKEN_LIFESPAN", "WORKFORCE_AUDIENCE_PATTERN", "DEFAULT_TOKEN_URL", "BaseExternalAccountClient", "_BaseExternalAccountClient", "#pendingAccessToken", "options", "opts", "type", "clientId", "clientSecret", "subjectTokenType", "workforcePoolUserProject", "serviceAccountImpersonationUrl", "serviceAccountImpersonation", "serviceAccountImpersonationLifetime", "workforceAudiencePattern", "credentials", "accessTokenResponse", "headers", "callback", "r", "e", "projectNumber", "response", "reAuthRetried", "requestHeaders", "res", "statusCode", "isReadableStream", "#internalRefreshAccessTokenAsync", "subjectToken", "stsCredentialsOptions", "additionalOptions", "additionalHeaders", "stsResponse", "audience", "match", "token", "successResponse", "accessToken", "now", "nodeVersion", "saImpersonation", "credentialSourceType", "require_filesubjecttokensupplier", "__commonJSMin", "exports", "util_1", "fs", "readFile", "realpath", "lstat", "FileSubjectTokenSupplier", "opts", "parsedFilePath", "err", "subjectToken", "rawText", "require_urlsubjecttokensupplier", "__commonJSMin", "exports", "authclient_1", "UrlSubjectTokenSupplier", "opts", "context", "subjectToken", "require_certificatesubjecttokensupplier", "__commonJSMin", "exports", "util_1", "fs", "crypto_1", "https", "CertificateSourceUnavailableError", "message", "InvalidConfigurationError", "CertificateSubjectTokenSupplier", "opts", "#resolveCertificateConfigFilePath", "certPath", "keyPath", "#getCertAndKeyPaths", "#getKeyAndCert", "#processChainFromPaths", "overridePath", "envPath", "wellKnownPath", "configPath", "fileContents", "config", "e", "cert", "key", "err", "leafCertBuffer", "leafCert", "chainCerts", "pem", "index", "leafIndex", "chainCert", "finalChain", "require_identitypoolclient", "__commonJSMin", "exports", "baseexternalclient_1", "util_1", "filesubjecttokensupplier_1", "urlsubjecttokensupplier_1", "certificatesubjecttokensupplier_1", "stscredentials_1", "gaxios_1", "IdentityPoolClient", "_IdentityPoolClient", "options", "opts", "credentialSource", "subjectTokenSupplier", "credentialSourceOpts", "formatOpts", "formatType", "formatSubjectTokenFieldName", "file", "url", "certificate", "headers", "certificateSubjecttokensupplier", "subjectToken", "mtlsAgent", "require_awsrequestsigner", "__commonJSMin", "exports", "gaxios_1", "crypto_1", "AWS_ALGORITHM", "AWS_REQUEST_TYPE", "AwsRequestSigner", "getCredentials", "region", "amzOptions", "requestPayloadData", "url", "method", "requestPayload", "additionalAmzHeaders", "awsSecurityCredentials", "uri", "headerMap", "generateAuthenticationHeaderMap", "headers", "awsSignedReq", "sign", "crypto", "key", "msg", "getSigningKey", "dateStamp", "serviceName", "kDate", "kRegion", "kService", "options", "now", "amzDate", "amzHeaders", "canonicalHeaders", "signedHeadersList", "signedHeaders", "payloadHash", "canonicalRequest", "credentialScope", "stringToSign", "signingKey", "signature", "authorizationHeader", "require_defaultawssecuritycredentialssupplier", "__commonJSMin", "exports", "authclient_1", "DefaultAwsSecurityCredentialsSupplier", "opts", "context", "#regionFromEnv", "metadataHeaders", "#getImdsV2SessionToken", "response", "#securityCredentialsFromEnv", "roleName", "#getAwsRoleName", "awsCreds", "#retrieveAwsSecurityCredentials", "transporter", "headers", "require_awsclient", "__commonJSMin", "exports", "awsrequestsigner_1", "baseexternalclient_1", "defaultawssecuritycredentialssupplier_1", "util_1", "gaxios_1", "AwsClient", "_AwsClient", "#DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL", "options", "opts", "credentialSource", "awsSecurityCredentialsSupplier", "credentialSourceOpts", "regionUrl", "securityCredentialsUrl", "imdsV2SessionTokenUrl", "match", "reformattedHeader", "value", "key", "require_executable_response", "__commonJSMin", "exports", "SAML_SUBJECT_TOKEN_TYPE", "OIDC_SUBJECT_TOKEN_TYPE1", "OIDC_SUBJECT_TOKEN_TYPE2", "ExecutableResponse", "responseJson", "InvalidVersionFieldError", "InvalidSuccessFieldError", "InvalidTokenTypeFieldError", "InvalidSubjectTokenError", "InvalidCodeFieldError", "InvalidMessageFieldError", "ExecutableResponseError", "message", "InvalidExpirationTimeFieldError", "require_pluggable_auth_handler", "__commonJSMin", "exports", "executable_response_1", "childProcess", "fs", "ExecutableError", "message", "code", "PluggableAuthHandler", "_PluggableAuthHandler", "options", "envMap", "resolve", "reject", "child", "output", "data", "err", "timeout", "responseJson", "response", "error", "filePath", "responseString", "command", "components", "i", "require_pluggable_auth_client", "__commonJSMin", "exports", "baseexternalclient_1", "executable_response_1", "pluggable_auth_handler_1", "pluggable_auth_handler_2", "DEFAULT_EXECUTABLE_TIMEOUT_MILLIS", "MINIMUM_EXECUTABLE_TIMEOUT_MILLIS", "MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS", "GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "MAXIMUM_EXECUTABLE_VERSION", "PluggableAuthClient", "options", "executableResponse", "envMap", "serviceAccountEmail", "require_externalclient", "__commonJSMin", "exports", "baseexternalclient_1", "identitypoolclient_1", "awsclient_1", "pluggable_auth_client_1", "ExternalAccountClient", "options", "require_externalAccountAuthorizedUserClient", "__commonJSMin", "exports", "authclient_1", "oauth2common_1", "gaxios_1", "stream", "baseexternalclient_1", "DEFAULT_TOKEN_URL", "ExternalAccountAuthorizedUserHandler", "_ExternalAccountAuthorizedUserHandler", "#tokenRefreshEndpoint", "options", "refreshToken", "headers", "opts", "response", "tokenRefreshResponse", "error", "ExternalAccountAuthorizedUserClient", "clientAuthentication", "accessTokenResponse", "callback", "r", "e", "reAuthRetried", "requestHeaders", "res", "statusCode", "isReadableStream", "refreshResponse", "credentials", "now", "require_googleauth", "__commonJSMin", "exports", "child_process_1", "fs", "gaxios_1", "gcpMetadata", "os", "path", "crypto_1", "computeclient_1", "idtokenclient_1", "envDetect_1", "jwtclient_1", "refreshclient_1", "impersonated_1", "externalclient_1", "baseexternalclient_1", "authclient_1", "externalAccountAuthorizedUserClient_1", "util_1", "GoogleAuth", "#pendingAuthClient", "opts", "client", "callback", "r", "projectId", "universeDomain", "e", "optionsOrCallback", "options", "#prepareAndCacheClient", "credential", "quotaProjectIdOverride", "credentialsPath", "location", "home", "filePath", "err", "readStream", "json", "sourceClient", "targetPrincipal", "targetScopes", "preferredUniverseDomain", "inputStream", "resolve", "reject", "chunks", "chunk", "data", "apiKey", "sys", "stdout", "creds", "serviceAccountEmail", "client_email", "universe_domain", "#determineClient", "stream", "targetAudience", "url", "headers", "args", "endpoint", "universe", "crypto", "emailOrUniqueId", "require_iam", "__commonJSMin", "exports", "IAMAuth", "selector", "token", "require_downscopedclient", "__commonJSMin", "exports", "gaxios_1", "stream", "authclient_1", "sts", "STS_GRANT_TYPE", "STS_REQUEST_TOKEN_TYPE", "STS_SUBJECT_TOKEN_TYPE", "DownscopedClient", "options", "credentialAccessBoundary", "rule", "credentials", "accessTokenResponse", "headers", "opts", "callback", "r", "e", "reAuthRetried", "response", "requestHeaders", "res", "statusCode", "isReadableStream", "subjectToken", "stsCredentialsOptions", "stsResponse", "sourceCredExpireDate", "expiryDate", "downscopedAccessToken", "now", "require_passthrough", "__commonJSMin", "exports", "authclient_1", "PassThroughClient", "opts", "require_src", "__commonJSMin", "exports", "googleauth_1", "authclient_1", "computeclient_1", "envDetect_1", "iam_1", "idtokenclient_1", "jwtaccess_1", "jwtclient_1", "impersonated_1", "oauth2client_1", "loginticket_1", "refreshclient_1", "awsclient_1", "awsrequestsigner_1", "identitypoolclient_1", "externalclient_1", "baseexternalclient_1", "downscopedclient_1", "pluggable_auth_client_1", "passthrough_1", "auth", "server_exports", "__export", "server_default", "__toCommonJS", "import_fastify", "import_cors", "import_fs", "import_path", "import_dotenv", "import_json5", "ConfigService", "options", "jsonPath", "jsonContent", "jsonConfig", "JSON5", "error", "envPath", "result", "envConfig", "env", "parsed", "path", "key", "defaultValue", "value", "summary", "createApiError", "message", "statusCode", "code", "type", "error", "errorHandler", "request", "reply", "response", "import_undici", "sendUnifiedRequest", "url", "request", "config", "logger", "headers", "key", "value", "combinedSignal", "timeoutSignal", "controller", "abortHandler", "fetchOptions", "version", "handleTransformerEndpoint", "req", "reply", "fastify", "transformer", "body", "providerName", "provider", "createApiError", "requestBody", "config", "bypass", "processRequestTransformers", "response", "sendRequestToProvider", "finalResponse", "processResponseTransformers", "formatResponse", "headers", "shouldBypassTransformers", "transformOut", "providerTransformer", "transformIn", "modelTransformer", "url", "auth", "sendUnifiedRequest", "errorText", "registerApiRoutes", "version", "transformersWithEndpoint", "request", "name", "baseUrl", "apiKey", "models", "isValidUrl", "LLMService", "providerService", "request", "id", "updates", "enabled", "modelName", "route", "provider", "model", "ProviderService", "configService", "transformerService", "logger", "providersConfig", "providerConfig", "transformer", "key", "Constructor", "transformerInstance", "error", "request", "provider", "model", "fullModel", "route", "name", "id", "updates", "updatedProvider", "enabled", "modelName", "modelNames", "transformerConfig", "acc", "item", "config", "models", "byteToHex", "i", "unsafeStringify", "arr", "offset", "import_crypto", "rnds8Pool", "poolPtr", "rng", "import_crypto", "native_default", "v4", "options", "buf", "offset", "native_default", "rnds", "rng", "i", "unsafeStringify", "v4_default", "getThinkLevel", "thinking_budget", "AnthropicTransformer", "request", "provider", "messages", "textParts", "item", "msg", "index", "toolParts", "c", "tool", "toolIndex", "toolMessage", "textAndMediaParts", "part", "assistantMessage", "text", "toolCallParts", "result", "getThinkLevel", "response", "context", "convertedStream", "data", "anthropicResponse", "tools", "openaiStream", "controller", "encoder", "messageId", "stopReasonMessageDelta", "model", "hasStarted", "hasTextContentStarted", "hasFinished", "toolCalls", "toolCallIndexToContentBlockIndex", "totalChunks", "contentChunks", "toolCallChunks", "isClosed", "isThinkingStarted", "contentIndex", "currentContentBlockIndex", "safeEnqueue", "dataStr", "error", "safeClose", "contentBlockStop", "messageStop", "reader", "decoder", "buffer", "done", "value", "lines", "line", "chunk", "errorMessage", "messageStart", "choice", "contentBlockStart", "thinkingSignature", "thinkingChunk", "anthropicChunk", "annotation", "v4_default", "processedInThisChunk", "toolCall", "toolCallIndex", "newContentBlockIndex", "toolCallId", "toolCallName", "toolCallInfo", "existingToolCall", "blockIndex", "currentToolCall", "fixedArgument", "fixedChunk", "fixError", "parseError", "controllerError", "releaseError", "reason", "openaiResponse", "content", "id", "parsedInput", "argumentsStr", "createApiError", "Type", "flattenTypeArrayToAnyOf", "typeList", "resultingSchema", "listWithoutNull", "type", "upperCaseType", "i", "processJsonSchema", "_jsonSchema", "genAISchema", "schemaFieldNames", "listSchemaFieldNames", "dictSchemaFieldNames", "incomingAnyOf", "fieldName", "fieldValue", "upperCaseValue", "listSchemaFieldValue", "item", "dictSchemaFieldValue", "key", "value", "tTool", "tool", "functionDeclaration", "buildRequestBody", "request", "tools", "functionDeclarations", "body", "message", "role", "parts", "content", "toolCall", "toolConfig", "transformRequestOut", "contents", "model", "max_tokens", "temperature", "stream", "tool_choice", "unifiedChatRequest", "part", "transformResponseOut", "response", "providerName", "logger", "jsonResponse", "tool_calls", "res", "decoder", "encoder", "processLine", "line", "controller", "chunkStr", "chunk", "candidate", "groundingChunk", "index", "support", "error", "reader", "buffer", "done", "lines", "GeminiTransformer", "request", "provider", "buildRequestBody", "transformRequestOut", "response", "transformResponseOut", "getAccessToken", "GoogleAuth", "error", "VertexGeminiTransformer", "request", "provider", "projectId", "location", "keyContent", "credentials", "accessToken", "buildRequestBody", "transformRequestOut", "response", "transformResponseOut", "DeepseekTransformer", "request", "response", "jsonResponse", "decoder", "encoder", "reasoningContent", "isReasoningComplete", "buffer", "stream", "controller", "reader", "processBuffer", "lines", "line", "processLine", "context", "data", "thinkingChunk", "thinkingLine", "signature", "modifiedLine", "done", "value", "chunk", "content", "val", "error", "e", "TooluseTransformer", "request", "response", "jsonResponse", "toolCall", "toolArguments", "decoder", "encoder", "exitToolIndex", "exitToolResponse", "buffer", "stream", "controller", "reader", "processBuffer", "lines", "line", "processLine", "context", "setExitToolIndex", "appendExitToolResponse", "data", "modifiedLine", "done", "value", "chunk", "val", "content", "error", "e", "OpenrouterTransformer", "options", "request", "msg", "item", "response", "jsonResponse", "decoder", "encoder", "hasTextContent", "reasoningContent", "isReasoningComplete", "hasToolCall", "buffer", "stream", "controller", "reader", "processBuffer", "lines", "line", "processLine", "context", "jsonStr", "data", "thinkingChunk", "thinkingLine", "signature", "tool", "v4_default", "modifiedLine", "done", "value", "chunk", "decodeError", "val", "content", "error", "e", "MaxTokenTransformer", "options", "request", "GroqTransformer", "request", "msg", "item", "tool", "response", "jsonResponse", "decoder", "encoder", "hasTextContent", "reasoningContent", "isReasoningComplete", "buffer", "stream", "controller", "reader", "processBuffer", "lines", "line", "processLine", "context", "jsonStr", "data", "v4_default", "modifiedLine", "done", "value", "chunk", "decodeError", "val", "content", "error", "e", "CleancacheTransformer", "request", "msg", "item", "import_json5", "JSONRepairError", "Error", "constructor", "message", "position", "isHex", "char", "test", "isDigit", "isValidStringCharacter", "isDelimiter", "includes", "isFunctionNameCharStart", "isFunctionNameChar", "regexUrlStart", "regexUrlChar", "isUnquotedStringDelimiter", "isStartOfValue", "isQuote", "regexStartOfValue", "isControlCharacter", "isWhitespace", "text", "index", "code", "charCodeAt", "codeSpace", "codeNewline", "codeTab", "codeReturn", "isWhitespaceExceptNewline", "isSpecialWhitespace", "codeNonBreakingSpace", "codeEnQuad", "codeHairSpace", "codeNarrowNoBreakSpace", "codeMediumMathematicalSpace", "codeIdeographicSpace", "isDoubleQuoteLike", "isSingleQuoteLike", "isDoubleQuote", "isSingleQuote", "stripLastOccurrence", "textToStrip", "stripRemainingText", "arguments", "length", "undefined", "lastIndexOf", "substring", "insertBeforeLastWhitespace", "textToInsert", "removeAtIndex", "start", "count", "endsWithCommaOrNewline", "controlCharacters", "escapeCharacters", "b", "f", "n", "r", "t", "jsonrepair", "text", "i", "output", "parseMarkdownCodeBlock", "parseValue", "throwUnexpectedEnd", "processedComma", "parseCharacter", "parseWhitespaceAndSkipComments", "isStartOfValue", "endsWithCommaOrNewline", "insertBeforeLastWhitespace", "parseNewlineDelimitedJSON", "stripLastOccurrence", "length", "throwUnexpectedCharacter", "processed", "parseObject", "parseArray", "parseString", "parseNumber", "parseKeywords", "parseUnquotedString", "parseRegex", "skipNewline", "arguments", "undefined", "start", "changed", "parseWhitespace", "parseComment", "_isWhiteSpace", "isWhitespace", "isWhitespaceExceptNewline", "whitespace", "isSpecialWhitespace", "atEndOfBlockComment", "blocks", "skipMarkdownCodeBlock", "isFunctionNameCharStart", "isFunctionNameChar", "block", "end", "slice", "char", "skipCharacter", "skipEscapeCharacter", "skipEllipsis", "initial", "throwObjectKeyExpected", "processedColon", "truncatedText", "throwColonExpected", "processedValue", "stopAtDelimiter", "stopAtIndex", "skipEscapeChars", "isQuote", "isEndQuote", "isDoubleQuote", "isSingleQuote", "isSingleQuoteLike", "isDoubleQuoteLike", "iBefore", "oBefore", "str", "iPrev", "prevNonWhitespaceIndex", "isDelimiter", "charAt", "substring", "iQuote", "oQuote", "isDigit", "parseConcatenatedString", "iPrevChar", "prevChar", "isUnquotedStringDelimiter", "regexUrlStart", "test", "regexUrlChar", "j", "isHex", "throwInvalidUnicodeCharacter", "isControlCharacter", "isValidStringCharacter", "throwInvalidCharacter", "removeAtIndex", "atEndOfNumber", "repairNumberEndingWithNumericSymbol", "num", "hasInvalidLeadingZero", "parseKeyword", "name", "value", "isKey", "symbol", "JSON", "stringify", "prev", "JSONRepairError", "chars", "parseToolArguments", "argsString", "logger", "jsonError", "args", "JSON5", "json5Error", "repairedJson", "jsonrepair", "repairError", "EnhanceToolTransformer", "response", "jsonResponse", "toolCall", "parseToolArguments", "decoder", "encoder", "currentToolCall", "hasTextContent", "reasoningContent", "isReasoningComplete", "hasToolCall", "buffer", "stream", "controller", "reader", "processBuffer", "lines", "line", "processCompletedToolCall", "data", "finalArgs", "e", "delta", "modifiedData", "modifiedLine", "processLine", "context", "jsonStr", "toolCallDelta", "done", "value", "chunk", "decodeError", "val", "content", "error", "ReasoningTransformer", "options", "request", "response", "jsonResponse", "decoder", "encoder", "reasoningContent", "isReasoningComplete", "buffer", "stream", "controller", "reader", "processBuffer", "lines", "line", "processLine", "context", "data", "thinkingChunk", "thinkingLine", "signature", "modifiedLine", "done", "value", "chunk", "content", "val", "error", "e", "SamplingTransformer", "options", "request", "MaxCompletionTokens", "request", "buildRequestBody", "request", "messages", "i", "message", "isLastMessage", "isAssistantMessage", "content", "item", "requestBody", "tool", "transformRequestOut", "vertexRequest", "result", "msg", "transformResponseOut", "response", "providerName", "logger", "jsonResponse", "tool_calls", "res", "decoder", "encoder", "processLine", "line", "controller", "chunkStr", "chunk", "error", "stream", "reader", "buffer", "done", "value", "lines", "getAccessToken", "GoogleAuth", "error", "VertexClaudeTransformer", "request", "provider", "projectId", "location", "keyContent", "credentials", "accessToken", "buildRequestBody", "transformRequestOut", "response", "transformResponseOut", "convertContentToString", "content", "item", "CerebrasTransformer", "request", "provider", "transformedRequest", "systemContent", "message", "transformedMessage", "response", "StreamOptionsTransformer", "request", "transformer_default", "AnthropicTransformer", "GeminiTransformer", "VertexGeminiTransformer", "VertexClaudeTransformer", "DeepseekTransformer", "TooluseTransformer", "OpenrouterTransformer", "MaxTokenTransformer", "GroqTransformer", "CleancacheTransformer", "EnhanceToolTransformer", "ReasoningTransformer", "SamplingTransformer", "MaxCompletionTokens", "CerebrasTransformer", "StreamOptionsTransformer", "TransformerService", "configService", "logger", "name", "transformer", "result", "config", "module", "instance", "error", "transformer_default", "TransformerStatic", "transformerInstance", "transformers", "createApp", "logger", "fastify", "Fastify", "errorHandler", "cors", "Server", "options", "ConfigService", "TransformerService", "ProviderService", "LLMService", "plugin", "hookName", "hookFunction", "request", "reply", "done", "req", "body", "provider", "model", "err", "registerApiRoutes", "address", "shutdown", "signal", "error", "server_default"] +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/thread-stream-worker.cjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/thread-stream-worker.cjs new file mode 100644 index 0000000000000000000000000000000000000000..a1b515875a9df24377f4ddbc5a0e534ccbfdf39f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/thread-stream-worker.cjs @@ -0,0 +1,2 @@ +"use strict";var I=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var w=I((b,R)=>{var g=new Function("modulePath","return import(modulePath)");function X(e){return typeof __non_webpack__require__=="function"?__non_webpack__require__(e):require(e)}R.exports={realImport:g,realRequire:X}});var T=I((B,D)=>{"use strict";D.exports={WRITE_INDEX:4,READ_INDEX:8}});var h=I((j,M)=>{"use strict";function q(e,t,c,_,r){let A=Date.now()+_,s=Atomics.load(e,t);if(s===c){r(null,"ok");return}let u=s,l=E=>{Date.now()>A?r(null,"timed-out"):setTimeout(()=>{u=s,s=Atomics.load(e,t),s===u?l(E>=1e3?1e3:E*2):s===c?r(null,"ok"):r(null,"not-equal")},E)};l(1)}function U(e,t,c,_,r){let A=Date.now()+_,s=Atomics.load(e,t);if(s!==c){r(null,"ok");return}let u=l=>{Date.now()>A?r(null,"timed-out"):setTimeout(()=>{s=Atomics.load(e,t),s!==c?r(null,"ok"):u(l>=1e3?1e3:l*2)},l)};u(1)}M.exports={wait:q,waitDiff:U}});var{realImport:x,realRequire:f}=w(),{workerData:O,parentPort:p}=require("worker_threads"),{WRITE_INDEX:m,READ_INDEX:n}=T(),{waitDiff:y}=h(),{dataBuf:k,filename:a,stateBuf:W}=O,i,o=new Int32Array(W),N=Buffer.from(k);async function S(){let e;try{a.endsWith(".ts")||a.endsWith(".cts")?(process[Symbol.for("ts-node.register.instance")]?process.env.TS_NODE_DEV&&f("ts-node-dev"):f("ts-node/register"),e=f(decodeURIComponent(a.replace(process.platform==="win32"?"file:///":"file://","")))):e=await x(a)}catch(t){if((t.code==="ENOTDIR"||t.code==="ERR_MODULE_NOT_FOUND")&&a.startsWith("file://"))e=f(decodeURIComponent(a.replace("file://","")));else if(t.code===void 0||t.code==="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING")try{e=f(decodeURIComponent(a.replace(process.platform==="win32"?"file:///":"file://","")))}catch{throw t}else throw t}typeof e=="object"&&(e=e.default),typeof e=="object"&&(e=e.default),i=await e(O.workerData),i.on("error",function(t){Atomics.store(o,m,-2),Atomics.notify(o,m),Atomics.store(o,n,-2),Atomics.notify(o,n),p.postMessage({code:"ERROR",err:t})}),i.on("close",function(){let t=Atomics.load(o,m);Atomics.store(o,n,t),Atomics.notify(o,n),setImmediate(()=>{process.exit(0)})})}S().then(function(){p.postMessage({code:"READY"}),process.nextTick(d)});function d(){let e=Atomics.load(o,n),t=Atomics.load(o,m);if(t===e){t===N.length?y(o,n,t,1/0,d):y(o,m,t,1/0,d);return}if(t===-1){i.end();return}let c=N.toString("utf8",e,t);i.write(c)?(Atomics.store(o,n,t),Atomics.notify(o,n),setImmediate(d)):i.once("drain",function(){Atomics.store(o,n,t),Atomics.notify(o,n),d()})}process.on("unhandledRejection",function(e){p.postMessage({code:"ERROR",err:e}),process.exit(1)});process.on("uncaughtException",function(e){p.postMessage({code:"ERROR",err:e}),process.exit(1)});process.once("exit",e=>{if(e!==0){process.exit(e);return}i?.writableNeedDrain&&!i?.writableEnded&&p.postMessage({code:"WARNING",err:new Error("ThreadStream: process exited before destination stream was drained. this may indicate that the destination stream try to write to a another missing stream")}),process.exit(0)}); +//# sourceMappingURL=thread-stream-worker.cjs.map diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/thread-stream-worker.cjs.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/thread-stream-worker.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..7d36fd1f3a2e760117ce061339e01957745aab9c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/cjs/thread-stream-worker.cjs.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/.pnpm/real-require@0.2.0/node_modules/real-require/src/index.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/indexes.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/wait.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/worker.js"], + "sourcesContent": ["/* eslint-disable no-new-func, camelcase */\n/* globals __non_webpack__require__ */\n\nconst realImport = new Function('modulePath', 'return import(modulePath)')\n\nfunction realRequire(modulePath) {\n if (typeof __non_webpack__require__ === 'function') {\n return __non_webpack__require__(modulePath)\n }\n\n return require(modulePath)\n}\n\nmodule.exports = { realImport, realRequire }\n", "'use strict'\n\nconst WRITE_INDEX = 4\nconst READ_INDEX = 8\n\nmodule.exports = {\n WRITE_INDEX,\n READ_INDEX\n}\n", "'use strict'\n\nconst MAX_TIMEOUT = 1000\n\nfunction wait (state, index, expected, timeout, done) {\n const max = Date.now() + timeout\n let current = Atomics.load(state, index)\n if (current === expected) {\n done(null, 'ok')\n return\n }\n let prior = current\n const check = (backoff) => {\n if (Date.now() > max) {\n done(null, 'timed-out')\n } else {\n setTimeout(() => {\n prior = current\n current = Atomics.load(state, index)\n if (current === prior) {\n check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)\n } else {\n if (current === expected) done(null, 'ok')\n else done(null, 'not-equal')\n }\n }, backoff)\n }\n }\n check(1)\n}\n\n// let waitDiffCount = 0\nfunction waitDiff (state, index, expected, timeout, done) {\n // const id = waitDiffCount++\n // process._rawDebug(`>>> waitDiff ${id}`)\n const max = Date.now() + timeout\n let current = Atomics.load(state, index)\n if (current !== expected) {\n done(null, 'ok')\n return\n }\n const check = (backoff) => {\n // process._rawDebug(`${id} ${index} current ${current} expected ${expected}`)\n // process._rawDebug('' + backoff)\n if (Date.now() > max) {\n done(null, 'timed-out')\n } else {\n setTimeout(() => {\n current = Atomics.load(state, index)\n if (current !== expected) {\n done(null, 'ok')\n } else {\n check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)\n }\n }, backoff)\n }\n }\n check(1)\n}\n\nmodule.exports = { wait, waitDiff }\n", "'use strict'\n\nconst { realImport, realRequire } = require('real-require')\nconst { workerData, parentPort } = require('worker_threads')\nconst { WRITE_INDEX, READ_INDEX } = require('./indexes')\nconst { waitDiff } = require('./wait')\n\nconst {\n dataBuf,\n filename,\n stateBuf\n} = workerData\n\nlet destination\n\nconst state = new Int32Array(stateBuf)\nconst data = Buffer.from(dataBuf)\n\nasync function start () {\n let worker\n try {\n if (filename.endsWith('.ts') || filename.endsWith('.cts')) {\n // TODO: add support for the TSM modules loader ( https://github.com/lukeed/tsm ).\n if (!process[Symbol.for('ts-node.register.instance')]) {\n realRequire('ts-node/register')\n } else if (process.env.TS_NODE_DEV) {\n realRequire('ts-node-dev')\n }\n // TODO: Support ES imports once tsc, tap & ts-node provide better compatibility guarantees.\n // Remove extra forwardslash on Windows\n worker = realRequire(decodeURIComponent(filename.replace(process.platform === 'win32' ? 'file:///' : 'file://', '')))\n } else {\n worker = (await realImport(filename))\n }\n } catch (error) {\n // A yarn user that tries to start a ThreadStream for an external module\n // provides a filename pointing to a zip file.\n // eg. require.resolve('pino-elasticsearch') // returns /foo/pino-elasticsearch-npm-6.1.0-0c03079478-6915435172.zip/bar.js\n // The `import` will fail to try to load it.\n // This catch block executes the `require` fallback to load the module correctly.\n // In fact, yarn modifies the `require` function to manage the zipped path.\n // More details at https://github.com/pinojs/pino/pull/1113\n // The error codes may change based on the node.js version (ENOTDIR > 12, ERR_MODULE_NOT_FOUND <= 12 )\n if ((error.code === 'ENOTDIR' || error.code === 'ERR_MODULE_NOT_FOUND') &&\n filename.startsWith('file://')) {\n worker = realRequire(decodeURIComponent(filename.replace('file://', '')))\n } else if (error.code === undefined || error.code === 'ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING') {\n // When bundled with pkg, an undefined error is thrown when called with realImport\n // When bundled with pkg and using node v20, an ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING error is thrown when called with realImport\n // More info at: https://github.com/pinojs/thread-stream/issues/143\n try {\n worker = realRequire(decodeURIComponent(filename.replace(process.platform === 'win32' ? 'file:///' : 'file://', '')))\n } catch {\n throw error\n }\n } else {\n throw error\n }\n }\n\n // Depending on how the default export is performed, and on how the code is\n // transpiled, we may find cases of two nested \"default\" objects.\n // See https://github.com/pinojs/pino/issues/1243#issuecomment-982774762\n if (typeof worker === 'object') worker = worker.default\n if (typeof worker === 'object') worker = worker.default\n\n destination = await worker(workerData.workerData)\n\n destination.on('error', function (err) {\n Atomics.store(state, WRITE_INDEX, -2)\n Atomics.notify(state, WRITE_INDEX)\n\n Atomics.store(state, READ_INDEX, -2)\n Atomics.notify(state, READ_INDEX)\n\n parentPort.postMessage({\n code: 'ERROR',\n err\n })\n })\n\n destination.on('close', function () {\n // process._rawDebug('worker close emitted')\n const end = Atomics.load(state, WRITE_INDEX)\n Atomics.store(state, READ_INDEX, end)\n Atomics.notify(state, READ_INDEX)\n setImmediate(() => {\n process.exit(0)\n })\n })\n}\n\n// No .catch() handler,\n// in case there is an error it goes\n// to unhandledRejection\nstart().then(function () {\n parentPort.postMessage({\n code: 'READY'\n })\n\n process.nextTick(run)\n})\n\nfunction run () {\n const current = Atomics.load(state, READ_INDEX)\n const end = Atomics.load(state, WRITE_INDEX)\n\n // process._rawDebug(`pre state ${current} ${end}`)\n\n if (end === current) {\n if (end === data.length) {\n waitDiff(state, READ_INDEX, end, Infinity, run)\n } else {\n waitDiff(state, WRITE_INDEX, end, Infinity, run)\n }\n return\n }\n\n // process._rawDebug(`post state ${current} ${end}`)\n\n if (end === -1) {\n // process._rawDebug('end')\n destination.end()\n return\n }\n\n const toWrite = data.toString('utf8', current, end)\n // process._rawDebug('worker writing: ' + toWrite)\n\n const res = destination.write(toWrite)\n\n if (res) {\n Atomics.store(state, READ_INDEX, end)\n Atomics.notify(state, READ_INDEX)\n setImmediate(run)\n } else {\n destination.once('drain', function () {\n Atomics.store(state, READ_INDEX, end)\n Atomics.notify(state, READ_INDEX)\n run()\n })\n }\n}\n\nprocess.on('unhandledRejection', function (err) {\n parentPort.postMessage({\n code: 'ERROR',\n err\n })\n process.exit(1)\n})\n\nprocess.on('uncaughtException', function (err) {\n parentPort.postMessage({\n code: 'ERROR',\n err\n })\n process.exit(1)\n})\n\nprocess.once('exit', exitCode => {\n if (exitCode !== 0) {\n process.exit(exitCode)\n return\n }\n if (destination?.writableNeedDrain && !destination?.writableEnded) {\n parentPort.postMessage({\n code: 'WARNING',\n err: new Error('ThreadStream: process exited before destination stream was drained. this may indicate that the destination stream try to write to a another missing stream')\n })\n }\n\n process.exit(0)\n})\n"], + "mappings": "2EAAA,IAAAA,EAAAC,EAAA,CAAAC,EAAAC,IAAA,CAGA,IAAMC,EAAa,IAAI,SAAS,aAAc,2BAA2B,EAEzE,SAASC,EAAYC,EAAY,CAC/B,OAAI,OAAO,0BAA6B,WAC/B,yBAAyBA,CAAU,EAGrC,QAAQA,CAAU,CAC3B,CAEAH,EAAO,QAAU,CAAE,WAAAC,EAAY,YAAAC,CAAY,ICb3C,IAAAE,EAAAC,EAAA,CAAAC,EAAAC,IAAA,cAKAA,EAAO,QAAU,CACf,cACA,YACF,ICRA,IAAAC,EAAAC,EAAA,CAAAC,EAAAC,IAAA,cAIA,SAASC,EAAMC,EAAOC,EAAOC,EAAUC,EAASC,EAAM,CACpD,IAAMC,EAAM,KAAK,IAAI,EAAIF,EACrBG,EAAU,QAAQ,KAAKN,EAAOC,CAAK,EACvC,GAAIK,IAAYJ,EAAU,CACxBE,EAAK,KAAM,IAAI,EACf,MACF,CACA,IAAIG,EAAQD,EACNE,EAASC,GAAY,CACrB,KAAK,IAAI,EAAIJ,EACfD,EAAK,KAAM,WAAW,EAEtB,WAAW,IAAM,CACfG,EAAQD,EACRA,EAAU,QAAQ,KAAKN,EAAOC,CAAK,EAC/BK,IAAYC,EACdC,EAAMC,GAAW,IAAc,IAAcA,EAAU,CAAC,EA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,EAAS,CACfF,IAAQL,EAAK,OACfN,EAASK,EAAON,EAAYY,EAAK,IAAUC,CAAG,EAE9CZ,EAASK,EAAOP,EAAaa,EAAK,IAAUC,CAAG,EAEjD,MACF,CAIA,GAAID,IAAQ,GAAI,CAEdP,EAAY,IAAI,EAChB,MACF,CAEA,IAAMU,EAAUR,EAAK,SAAS,OAAQO,EAASF,CAAG,EAGtCP,EAAY,MAAMU,CAAO,GAGnC,QAAQ,MAAMT,EAAON,EAAYY,CAAG,EACpC,QAAQ,OAAON,EAAON,CAAU,EAChC,aAAaa,CAAG,GAEhBR,EAAY,KAAK,QAAS,UAAY,CACpC,QAAQ,MAAMC,EAAON,EAAYY,CAAG,EACpC,QAAQ,OAAON,EAAON,CAAU,EAChCa,EAAI,CACN,CAAC,CAEL,CAEA,QAAQ,GAAG,qBAAsB,SAAUF,EAAK,CAC9Cb,EAAW,YAAY,CACrB,KAAM,QACN,IAAAa,CACF,CAAC,EACD,QAAQ,KAAK,CAAC,CAChB,CAAC,EAED,QAAQ,GAAG,oBAAqB,SAAUA,EAAK,CAC7Cb,EAAW,YAAY,CACrB,KAAM,QACN,IAAAa,CACF,CAAC,EACD,QAAQ,KAAK,CAAC,CAChB,CAAC,EAED,QAAQ,KAAK,OAAQK,GAAY,CAC/B,GAAIA,IAAa,EAAG,CAClB,QAAQ,KAAKA,CAAQ,EACrB,MACF,CACIX,GAAa,mBAAqB,CAACA,GAAa,eAClDP,EAAW,YAAY,CACrB,KAAM,UACN,IAAK,IAAI,MAAM,4JAA4J,CAC7K,CAAC,EAGH,QAAQ,KAAK,CAAC,CAChB,CAAC", + "names": ["require_src", "__commonJSMin", "exports", "module", "realImport", "realRequire", "modulePath", "require_indexes", "__commonJSMin", "exports", "module", "require_wait", "__commonJSMin", "exports", "module", "wait", "state", "index", "expected", "timeout", "done", "max", "current", "prior", "check", "backoff", "waitDiff", "realImport", "realRequire", "workerData", "parentPort", "WRITE_INDEX", "READ_INDEX", "waitDiff", "dataBuf", "filename", "stateBuf", "destination", "state", "data", "start", "worker", "error", "err", "end", "run", "current", "toWrite", "exitCode"] +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-file.mjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-file.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f6558adde591be2fd4f35fce208e45adae447860 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-file.mjs @@ -0,0 +1,103 @@ +var T=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var O=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ee=O((Bf,St)=>{"use strict";var Q=e=>e&&typeof e.message=="string",_e=e=>{if(!e)return;let t=e.cause;if(typeof t=="function"){let r=e.cause();return Q(r)?r:void 0}else return Q(t)?t:void 0},bt=(e,t)=>{if(!Q(e))return"";let r=e.stack||"";if(t.has(e))return r+` +causes have become circular...`;let n=_e(e);return n?(t.add(e),r+` +caused by: `+bt(n,t)):r},Bn=e=>bt(e,new Set),wt=(e,t,r)=>{if(!Q(e))return"";let n=r?"":e.message||"";if(t.has(e))return n+": ...";let i=_e(e);if(i){t.add(e);let o=typeof e.cause=="function";return n+(o?"":": ")+wt(i,t,o)}else return n},In=e=>wt(e,new Set);St.exports={isErrorLike:Q,getErrorCause:_e,stackWithCauses:Bn,messageWithCauses:In}});var Oe=O((If,Et)=>{"use strict";var qn=Symbol("circular-ref-tag"),re=Symbol("pino-raw-err-ref"),_t=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[re]},set:function(e){this[re]=e}}});Object.defineProperty(_t,re,{writable:!0,value:{}});Et.exports={pinoErrProto:_t,pinoErrorSymbols:{seen:qn,rawSymbol:re}}});var vt=O((qf,xt)=>{"use strict";xt.exports=ve;var{messageWithCauses:Cn,stackWithCauses:Nn,isErrorLike:Ot}=Ee(),{pinoErrProto:Dn,pinoErrorSymbols:Pn}=Oe(),{seen:xe}=Pn,{toString:zn}=Object.prototype;function ve(e){if(!Ot(e))return e;e[xe]=void 0;let t=Object.create(Dn);t.type=zn.call(e.constructor)==="[object Function]"?e.constructor.name:e.name,t.message=Cn(e),t.stack=Nn(e),Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(r=>ve(r)));for(let r in e)if(t[r]===void 0){let n=e[r];Ot(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,xe)&&(t[r]=ve(n)):t[r]=n}return delete e[xe],t.raw=e,t}});var $t=O((Cf,Lt)=>{"use strict";Lt.exports=ie;var{isErrorLike:Le}=Ee(),{pinoErrProto:Wn,pinoErrorSymbols:Mn}=Oe(),{seen:ne}=Mn,{toString:Fn}=Object.prototype;function ie(e){if(!Le(e))return e;e[ne]=void 0;let t=Object.create(Wn);t.type=Fn.call(e.constructor)==="[object Function]"?e.constructor.name:e.name,t.message=e.message,t.stack=e.stack,Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(r=>ie(r))),Le(e.cause)&&!Object.prototype.hasOwnProperty.call(e.cause,ne)&&(t.cause=ie(e.cause));for(let r in e)if(t[r]===void 0){let n=e[r];Le(n)?Object.prototype.hasOwnProperty.call(n,ne)||(t[r]=ie(n)):t[r]=n}return delete e[ne],t.raw=e,t}});var kt=O((Nf,Tt)=>{"use strict";Tt.exports={mapHttpRequest:Vn,reqSerializer:jt};var $e=Symbol("pino-raw-req-ref"),At=Object.create({},{id:{enumerable:!0,writable:!0,value:""},method:{enumerable:!0,writable:!0,value:""},url:{enumerable:!0,writable:!0,value:""},query:{enumerable:!0,writable:!0,value:""},params:{enumerable:!0,writable:!0,value:""},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:""},remotePort:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[$e]},set:function(e){this[$e]=e}}});Object.defineProperty(At,$e,{writable:!0,value:{}});function jt(e){let t=e.info||e.socket,r=Object.create(At);if(r.id=typeof e.id=="function"?e.id():e.id||(e.info?e.info.id:void 0),r.method=e.method,e.originalUrl)r.url=e.originalUrl;else{let n=e.path;r.url=typeof n=="string"?n:e.url?e.url.path||e.url:void 0}return e.query&&(r.query=e.query),e.params&&(r.params=e.params),r.headers=e.headers,r.remoteAddress=t&&t.remoteAddress,r.remotePort=t&&t.remotePort,r.raw=e.raw||e,r}function Vn(e){return{req:jt(e)}}});var qt=O((Df,It)=>{"use strict";It.exports={mapHttpResponse:Kn,resSerializer:Bt};var Ae=Symbol("pino-raw-res-ref"),Rt=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Ae]},set:function(e){this[Ae]=e}}});Object.defineProperty(Rt,Ae,{writable:!0,value:{}});function Bt(e){let t=Object.create(Rt);return t.statusCode=e.headersSent?e.statusCode:null,t.headers=e.getHeaders?e.getHeaders():e._headers,t.raw=e,t}function Kn(e){return{res:Bt(e)}}});var Te=O((Pf,Ct)=>{"use strict";var je=vt(),Jn=$t(),se=kt(),oe=qt();Ct.exports={err:je,errWithCause:Jn,mapHttpRequest:se.mapHttpRequest,mapHttpResponse:oe.mapHttpResponse,req:se.reqSerializer,res:oe.resSerializer,wrapErrorSerializer:function(t){return t===je?t:function(n){return t(je(n))}},wrapRequestSerializer:function(t){return t===se.reqSerializer?t:function(n){return t(se.reqSerializer(n))}},wrapResponseSerializer:function(t){return t===oe.resSerializer?t:function(n){return t(oe.resSerializer(n))}}}});var ke=O((zf,Nt)=>{"use strict";function Un(e,t){return t}Nt.exports=function(){let t=Error.prepareStackTrace;Error.prepareStackTrace=Un;let r=new Error().stack;if(Error.prepareStackTrace=t,!Array.isArray(r))return;let n=r.slice(2),i=[];for(let o of n)o&&i.push(o.getFileName());return i}});var Pt=O((Wf,Dt)=>{"use strict";Dt.exports=Gn;function Gn(e={}){let{ERR_PATHS_MUST_BE_STRINGS:t=()=>"fast-redact - Paths must be (non-empty) strings",ERR_INVALID_PATH:r=n=>`fast-redact \u2013 Invalid path (${n})`}=e;return function({paths:i}){i.forEach(o=>{if(typeof o!="string")throw Error(t());try{if(/〇/.test(o))throw Error();let f=(o[0]==="["?"":".")+o.replace(/^\*/,"\u3007").replace(/\.\*/g,".\u3007").replace(/\[\*\]/g,"[\u3007]");if(/\n|\r|;/.test(f)||/\/\*/.test(f))throw Error();Function(` + 'use strict' + const o = new Proxy({}, { get: () => o, set: () => { throw Error() } }); + const \u3007 = null; + o${f} + if ([o${f}].length !== 1) throw Error()`)()}catch{throw Error(r(o))}})}}});var le=O((Mf,zt)=>{"use strict";zt.exports=/[^.[\]]+|\[((?:.)*?)\]/g});var Mt=O((Ff,Wt)=>{"use strict";var Hn=le();Wt.exports=Xn;function Xn({paths:e}){let t=[];var r=0;let n=e.reduce(function(i,o,f){var u=o.match(Hn).map(h=>h.replace(/'|"|`/g,""));let d=o[0]==="[";u=u.map(h=>h[0]==="["?h.substr(1,h.length-2):h);let y=u.indexOf("*");if(y>-1){let h=u.slice(0,y),l=h.join("."),p=u.slice(y+1,u.length),c=p.length>0;r++,t.push({before:h,beforeStr:l,after:p,nested:c})}else i[o]={path:u,val:void 0,precensored:!1,circle:"",escPath:JSON.stringify(o),leadingBracket:d};return i},{});return{wildcards:t,wcLen:r,secret:n}}});var Vt=O((Vf,Ft)=>{"use strict";var Yn=le();Ft.exports=Qn;function Qn({secret:e,serialize:t,wcLen:r,strict:n,isCensorFct:i,censorFctTakesPath:o},f){let u=Function("o",` + if (typeof o !== 'object' || o == null) { + ${ri(n,t)} + } + const { censor, secret } = this + const originalSecret = {} + const secretKeys = Object.keys(secret) + for (var i = 0; i < secretKeys.length; i++) { + originalSecret[secretKeys[i]] = secret[secretKeys[i]] + } + + ${Zn(e,i,o)} + this.compileRestore() + ${ei(r>0,i,o)} + this.secret = originalSecret + ${ti(t)} + `).bind(f);return u.state=f,t===!1&&(u.restore=d=>f.restore(d)),u}function Zn(e,t,r){return Object.keys(e).map(n=>{let{escPath:i,leadingBracket:o,path:f}=e[n],u=o?1:0,d=o?"":".",y=[];for(var h;(h=Yn.exec(n))!==null;){let[,s]=h,{index:g,input:m}=h;g>u&&y.push(m.substring(0,g-(s?0:1)))}var l=y.map(s=>`o${d}${s}`).join(" && ");l.length===0?l+=`o${d}${n} != null`:l+=` && o${d}${n} != null`;let p=` + switch (true) { + ${y.reverse().map(s=>` + case o${d}${s} === censor: + secret[${i}].circle = ${JSON.stringify(s)} + break + `).join(` +`)} + } + `,c=r?`val, ${JSON.stringify(f)}`:"val";return` + if (${l}) { + const val = o${d}${n} + if (val === censor) { + secret[${i}].precensored = true + } else { + secret[${i}].val = val + o${d}${n} = ${t?`censor(${c})`:"censor"} + ${p} + } + } + `}).join(` +`)}function ei(e,t,r){return e===!0?` + { + const { wildcards, wcLen, groupRedact, nestedRedact } = this + for (var i = 0; i < wcLen; i++) { + const { before, beforeStr, after, nested } = wildcards[i] + if (nested === true) { + secret[beforeStr] = secret[beforeStr] || [] + nestedRedact(secret[beforeStr], o, before, after, censor, ${t}, ${r}) + } else secret[beforeStr] = groupRedact(o, before, censor, ${t}, ${r}) + } + } + `:""}function ti(e){return e===!1?"return o":` + var s = this.serialize(o) + this.restore(o) + return s + `}function ri(e,t){return e===!0?"throw Error('fast-redact: primitives cannot be redacted')":t===!1?"return o":"return this.serialize(o)"}});var Be=O((Kf,Ut)=>{"use strict";Ut.exports={groupRedact:ii,groupRestore:ni,nestedRedact:oi,nestedRestore:si};function ni({keys:e,values:t,target:r}){if(r==null||typeof r=="string")return;let n=e.length;for(var i=0;i0;f--)o=o[n[f]];o[n[0]]=i}}function oi(e,t,r,n,i,o,f){let u=Kt(t,r);if(u==null)return;let d=Object.keys(u),y=d.length;for(var h=0;h{"use strict";var{groupRestore:ui,nestedRestore:ci}=Be();Gt.exports=ai;function ai(){return function(){if(this.restore){this.restore.state.secret=this.secret;return}let{secret:t,wcLen:r}=this,n=Object.keys(t),i=hi(t,n),o=r>0,f=o?{secret:t,groupRestore:ui,nestedRestore:ci}:{secret:t};this.restore=Function("o",di(i,n,o)).bind(f),this.restore.state=f}}function hi(e,t){return t.map(r=>{let{circle:n,escPath:i,leadingBracket:o}=e[r],u=n?`o.${n} = secret[${i}].val`:`o${o?"":"."}${r} = secret[${i}].val`,d=`secret[${i}].val = undefined`;return` + if (secret[${i}].val !== undefined) { + try { ${u} } catch (e) {} + ${d} + } + `}).join("")}function di(e,t,r){return` + const secret = this.secret + ${r===!0?` + const keys = Object.keys(secret) + const len = keys.length + for (var i = len - 1; i >= ${t.length}; i--) { + const k = keys[i] + const o = secret[k] + if (o) { + if (o.flat === true) this.groupRestore(o) + else this.nestedRestore(o) + secret[k] = null + } + } + `:""} + ${e} + return o + `}});var Yt=O((Uf,Xt)=>{"use strict";Xt.exports=yi;function yi(e){let{secret:t,censor:r,compileRestore:n,serialize:i,groupRedact:o,nestedRedact:f,wildcards:u,wcLen:d}=e,y=[{secret:t,censor:r,compileRestore:n}];return i!==!1&&y.push({serialize:i}),d>0&&y.push({groupRedact:o,nestedRedact:f,wildcards:u,wcLen:d}),Object.assign(...y)}});var er=O((Gf,Zt)=>{"use strict";var Qt=Pt(),mi=Mt(),gi=Vt(),pi=Ht(),{groupRedact:bi,nestedRedact:wi}=Be(),Si=Yt(),_i=le(),Ei=Qt(),Ie=e=>e;Ie.restore=Ie;var Oi="[REDACTED]";qe.rx=_i;qe.validator=Qt;Zt.exports=qe;function qe(e={}){let t=Array.from(new Set(e.paths||[])),r="serialize"in e&&(e.serialize===!1||typeof e.serialize=="function")?e.serialize:JSON.stringify,n=e.remove;if(n===!0&&r!==JSON.stringify)throw Error("fast-redact \u2013 remove option may only be set when serializer is JSON.stringify");let i=n===!0?void 0:"censor"in e?e.censor:Oi,o=typeof i=="function",f=o&&i.length>1;if(t.length===0)return r||Ie;Ei({paths:t,serialize:r,censor:i});let{wildcards:u,wcLen:d,secret:y}=mi({paths:t,censor:i}),h=pi(),l="strict"in e?e.strict:!0;return gi({secret:y,wcLen:d,serialize:r,strict:l,isCensorFct:o,censorFctTakesPath:f},Si({secret:y,censor:i,compileRestore:h,serialize:r,groupRedact:bi,nestedRedact:wi,wildcards:u,wcLen:d}))}});var H=O((Hf,tr)=>{"use strict";var xi=Symbol("pino.setLevel"),vi=Symbol("pino.getLevel"),Li=Symbol("pino.levelVal"),$i=Symbol("pino.levelComp"),Ai=Symbol("pino.useLevelLabels"),ji=Symbol("pino.useOnlyCustomLevels"),Ti=Symbol("pino.mixin"),ki=Symbol("pino.lsCache"),Ri=Symbol("pino.chindings"),Bi=Symbol("pino.asJson"),Ii=Symbol("pino.write"),qi=Symbol("pino.redactFmt"),Ci=Symbol("pino.time"),Ni=Symbol("pino.timeSliceIndex"),Di=Symbol("pino.stream"),Pi=Symbol("pino.stringify"),zi=Symbol("pino.stringifySafe"),Wi=Symbol("pino.stringifiers"),Mi=Symbol("pino.end"),Fi=Symbol("pino.formatOpts"),Vi=Symbol("pino.messageKey"),Ki=Symbol("pino.errorKey"),Ji=Symbol("pino.nestedKey"),Ui=Symbol("pino.nestedKeyStr"),Gi=Symbol("pino.mixinMergeStrategy"),Hi=Symbol("pino.msgPrefix"),Xi=Symbol("pino.wildcardFirst"),Yi=Symbol.for("pino.serializers"),Qi=Symbol.for("pino.formatters"),Zi=Symbol.for("pino.hooks"),es=Symbol.for("pino.metadata");tr.exports={setLevelSym:xi,getLevelSym:vi,levelValSym:Li,levelCompSym:$i,useLevelLabelsSym:Ai,mixinSym:Ti,lsCacheSym:ki,chindingsSym:Ri,asJsonSym:Bi,writeSym:Ii,serializersSym:Yi,redactFmtSym:qi,timeSym:Ci,timeSliceIndexSym:Ni,streamSym:Di,stringifySym:Pi,stringifySafeSym:zi,stringifiersSym:Wi,endSym:Mi,formatOptsSym:Fi,messageKeySym:Vi,errorKeySym:Ki,nestedKeySym:Ji,wildcardFirstSym:Xi,needsMetadataGsym:es,useOnlyCustomLevelsSym:ji,formattersSym:Qi,hooksSym:Zi,nestedKeyStrSym:Ui,mixinMergeStrategySym:Gi,msgPrefixSym:Hi}});var De=O((Xf,sr)=>{"use strict";var Ne=er(),{redactFmtSym:ts,wildcardFirstSym:fe}=H(),{rx:Ce,validator:rs}=Ne,rr=rs({ERR_PATHS_MUST_BE_STRINGS:()=>"pino \u2013 redacted paths must be strings",ERR_INVALID_PATH:e=>`pino \u2013 redact paths array contains an invalid path (${e})`}),nr="[Redacted]",ir=!1;function ns(e,t){let{paths:r,censor:n}=is(e),i=r.reduce((u,d)=>{Ce.lastIndex=0;let y=Ce.exec(d),h=Ce.exec(d),l=y[1]!==void 0?y[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):y[0];if(l==="*"&&(l=fe),h===null)return u[l]=null,u;if(u[l]===null)return u;let{index:p}=h,c=`${d.substr(p,d.length-1)}`;return u[l]=u[l]||[],l!==fe&&u[l].length===0&&u[l].push(...u[fe]||[]),l===fe&&Object.keys(u).forEach(function(s){u[s]&&u[s].push(c)}),u[l].push(c),u},{}),o={[ts]:Ne({paths:r,censor:n,serialize:t,strict:ir})},f=(...u)=>t(typeof n=="function"?n(...u):n);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((u,d)=>{if(i[d]===null)u[d]=y=>f(y,[d]);else{let y=typeof n=="function"?(h,l)=>n(h,[d,...l]):n;u[d]=Ne({paths:i[d],censor:y,serialize:t,strict:ir})}return u},o)}function is(e){if(Array.isArray(e))return e={paths:e,censor:nr},rr(e),e;let{paths:t,censor:r=nr,remove:n}=e;if(Array.isArray(t)===!1)throw Error("pino \u2013 redact must contain an array of strings");return n===!0&&(r=void 0),rr({paths:t,censor:r}),{paths:t,censor:r}}sr.exports=ns});var lr=O((Yf,or)=>{"use strict";var ss=()=>"",os=()=>`,"time":${Date.now()}`,ls=()=>`,"time":${Math.round(Date.now()/1e3)}`,fs=()=>`,"time":"${new Date(Date.now()).toISOString()}"`;or.exports={nullTime:ss,epochTime:os,unixTime:ls,isoTime:fs}});var ur=O((Qf,fr)=>{"use strict";function us(e){try{return JSON.stringify(e)}catch{return'"[Circular]"'}}fr.exports=cs;function cs(e,t,r){var n=r&&r.stringify||us,i=1;if(typeof e=="object"&&e!==null){var o=t.length+i;if(o===1)return e;var f=new Array(o);f[0]=n(e);for(var u=1;u-1?l:0,e.charCodeAt(c+1)){case 100:case 102:if(h>=d||t[h]==null)break;l=d||t[h]==null)break;l=d||t[h]===void 0)break;l",l=c+2,c++;break}y+=n(t[h]),l=c+2,c++;break;case 115:if(h>=d)break;l{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let t=function(r){if((r>0&&r<1/0)===!1)throw typeof r!="number"&&typeof r!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(e,0,0,Number(r))},e=new Int32Array(new SharedArrayBuffer(4));Pe.exports=t}else{let e=function(t){if((t>0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let n=Date.now()+Number(t);for(;n>Date.now(););};Pe.exports=e}});var pr=O((eu,gr)=>{"use strict";var j=T("fs"),as=T("events"),hs=T("util").inherits,cr=T("path"),Me=ze(),ds=T("assert"),ue=100,ce=Buffer.allocUnsafe(0),ys=16*1024,ar="buffer",hr="utf8",[ms,gs]=(process.versions.node||"0.0").split(".").map(Number),ps=ms>=22&&gs>=7;function dr(e,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function r(o,f){if(o){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount("error")>0&&t.emit("error",o)}):t.emit("error",o);return}let u=t._reopening;t.fd=f,t.file=e,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit("ready")):t.emit("ready"),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():u&&process.nextTick(()=>t.emit("drain")))}let n=t.append?"a":"w",i=t.mode;if(t.sync)try{t.mkdir&&j.mkdirSync(cr.dirname(e),{recursive:!0});let o=j.openSync(e,n,i);r(null,o)}catch(o){throw r(o),o}else t.mkdir?j.mkdir(cr.dirname(e),{recursive:!0},o=>{if(o)return r(o);j.open(e,n,i,r)}):j.open(e,n,i,r)}function N(e){if(!(this instanceof N))return new N(e);let{fd:t,dest:r,minLength:n,maxLength:i,maxWrite:o,periodicFlush:f,sync:u,append:d=!0,mkdir:y,retryEAGAIN:h,fsync:l,contentMode:p,mode:c}=e||{};t=t||r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(n||0,16387),this.file=null,this.destroyed=!1,this.minLength=n||0,this.maxLength=i||0,this.maxWrite=o||ys,this._periodicFlush=f||0,this._periodicFlushTimer=void 0,this.sync=u||!1,this.writable=!0,this._fsync=l||!1,this.append=d||!1,this.mode=c,this.retryEAGAIN=h||(()=>!0),this.mkdir=y||!1;let s,g;if(p===ar)this._writingBuf=ce,this.write=Ss,this.flush=Es,this.flushSync=xs,this._actualWrite=Ls,s=()=>j.writeSync(this.fd,this._writingBuf),g=()=>j.write(this.fd,this._writingBuf,this.release);else if(p===void 0||p===hr)this._writingBuf="",this.write=ws,this.flush=_s,this.flushSync=Os,this._actualWrite=vs,s=()=>j.writeSync(this.fd,this._writingBuf,"utf8"),g=()=>j.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${hr}" and "${ar}", but passed ${p}`);if(typeof t=="number")this.fd=t,process.nextTick(()=>this.emit("ready"));else if(typeof t=="string")dr(t,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(m,S)=>{if(m){if((m.code==="EAGAIN"||m.code==="EBUSY")&&this.retryEAGAIN(m,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{Me(ue),this.release(void 0,0)}catch(_){this.release(_)}else setTimeout(g,ue);else this._writing=!1,this.emit("error",m);return}this.emit("write",S);let b=We(this._writingBuf,this._len,S);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){g();return}try{do{let _=s(),x=We(this._writingBuf,this._len,_);this._len=x.len,this._writingBuf=x.writingBuf}while(this._writingBuf.length)}catch(_){this.release(_);return}}this._fsync&&j.fsyncSync(this.fd);let w=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):w>this.minLength?this._actualWrite():this._ending?w>0?this._actualWrite():(this._writing=!1,ae(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(bs,this)):this.emit("drain"))},this.on("newListener",function(m){m==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function We(e,t,r){return typeof e=="string"&&Buffer.byteLength(e)!==r&&(r=Buffer.from(e).subarray(0,r).toString().length),t=Math.max(t-r,0),e=e.slice(r),{writingBuf:e,len:t}}function bs(e){e.listenerCount("drain")>0&&(e._asyncDrainScheduled=!1,e.emit("drain"))}hs(N,as);function yr(e,t){return e.length===0?ce:e.length===1?e[0]:Buffer.concat(e,t)}function ws(e){if(this.destroyed)throw new Error("SonicBoom destroyed");let t=this._len+e.length,r=this._bufs;return this.maxLength&&t>this.maxLength?(this.emit("drop",e),this._lenthis.maxWrite?r.push(""+e):r[r.length-1]+=e,this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._lenthis.maxLength?(this.emit("drop",e),this._lenthis.maxWrite?(r.push([e]),n.push(e.length)):(r[r.length-1].push(e),n[n.length-1]+=e.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len{if(this._fsync)this._flushPending=!1,e();else try{j.fsync(this.fd,n=>{this._flushPending=!1,e(n)})}catch(n){e(n)}this.off("error",r)},r=n=>{this._flushPending=!1,e(n),this.off("drain",t)};this.once("drain",t),this.once("error",r)}function _s(e){if(e!=null&&typeof e!="function")throw new Error("flush cb must be a function");if(this.destroyed){let t=new Error("SonicBoom destroyed");if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&mr.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function Es(e){if(e!=null&&typeof e!="function")throw new Error("flush cb must be a function");if(this.destroyed){let t=new Error("SonicBoom destroyed");if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&mr.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}N.prototype.reopen=function(e){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(e&&(this.file=e),this._reopening=!0,this._writing)return;let t=this.fd;this.once("ready",()=>{t!==this.fd&&j.close(t,r=>{if(r)return this.emit("error",r)})}),dr(this.file,this)};N.prototype.end=function(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():ae(this)))};function Os(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let e="";for(;this._bufs.length||e;){e.length<=0&&(e=this._bufs[0]);try{let t=j.writeSync(this.fd,e,"utf8"),r=We(e,this._len,t);e=r.writingBuf,this._len=r.len,e.length<=0&&this._bufs.shift()}catch(t){if((t.code==="EAGAIN"||t.code==="EBUSY")&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;Me(ue)}}try{j.fsyncSync(this.fd)}catch{}}function xs(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=ce);let e=ce;for(;this._bufs.length||e.length;){e.length<=0&&(e=yr(this._bufs[0],this._lens[0]));try{let t=j.writeSync(this.fd,e);e=e.subarray(t),this._len=Math.max(this._len-t,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code==="EAGAIN"||t.code==="EBUSY")&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;Me(ue)}}}N.prototype.destroy=function(){this.destroyed||ae(this)};function vs(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf||this._bufs.shift()||"",this.sync)try{let t=j.writeSync(this.fd,this._writingBuf,"utf8");e(null,t)}catch(t){e(t)}else j.write(this.fd,this._writingBuf,"utf8",e)}function Ls(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:yr(this._bufs.shift(),this._lens.shift()),this.sync)try{let t=j.writeSync(this.fd,this._writingBuf);e(null,t)}catch(t){e(t)}else ps&&(this._writingBuf=Buffer.from(this._writingBuf)),j.write(this.fd,this._writingBuf,e)}function ae(e){if(e.fd===-1){e.once("ready",ae.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],ds(typeof e.fd=="number",`sonic.fd must be a number, got ${typeof e.fd}`);try{j.fsync(e.fd,t)}catch{}function t(){e.fd!==1&&e.fd!==2?j.close(e.fd,r):r()}function r(n){if(n){e.emit("error",n);return}e._ending&&!e._writing&&e.emit("finish"),e.emit("close")}}N.SonicBoom=N;N.default=N;gr.exports=N});var Fe=O((tu,Er)=>{"use strict";var D={exit:[],beforeExit:[]},br={exit:js,beforeExit:Ts},X;function $s(){X===void 0&&(X=new FinalizationRegistry(ks))}function As(e){D[e].length>0||process.on(e,br[e])}function wr(e){D[e].length>0||(process.removeListener(e,br[e]),D.exit.length===0&&D.beforeExit.length===0&&(X=void 0))}function js(){Sr("exit")}function Ts(){Sr("beforeExit")}function Sr(e){for(let t of D[e]){let r=t.deref(),n=t.fn;r!==void 0&&n(r,e)}D[e]=[]}function ks(e){for(let t of["exit","beforeExit"]){let r=D[t].indexOf(e);D[t].splice(r,r+1),wr(t)}}function _r(e,t,r){if(t===void 0)throw new Error("the object can't be undefined");As(e);let n=new WeakRef(t);n.fn=r,$s(),X.register(t,n),D[e].push(n)}function Rs(e,t){_r("exit",e,t)}function Bs(e,t){_r("beforeExit",e,t)}function Is(e){if(X!==void 0){X.unregister(e);for(let t of["exit","beforeExit"])D[t]=D[t].filter(r=>{let n=r.deref();return n&&n!==e}),wr(t)}}Er.exports={register:Rs,registerBeforeExit:Bs,unregister:Is}});var Or=O((ru,qs)=>{qs.exports={name:"thread-stream",version:"3.1.0",description:"A streaming way to send data to a Node.js Worker Thread",main:"index.js",types:"index.d.ts",dependencies:{"real-require":"^0.2.0"},devDependencies:{"@types/node":"^20.1.0","@types/tap":"^15.0.0","@yao-pkg/pkg":"^5.11.5",desm:"^1.3.0",fastbench:"^1.0.1",husky:"^9.0.6","pino-elasticsearch":"^8.0.0","sonic-boom":"^4.0.1",standard:"^17.0.0",tap:"^16.2.0","ts-node":"^10.8.0",typescript:"^5.3.2","why-is-node-running":"^2.2.2"},scripts:{build:"tsc --noEmit",test:'standard && npm run build && npm run transpile && tap "test/**/*.test.*js" && tap --ts test/*.test.*ts',"test:ci":"standard && npm run transpile && npm run test:ci:js && npm run test:ci:ts","test:ci:js":'tap --no-check-coverage --timeout=120 --coverage-report=lcovonly "test/**/*.test.*js"',"test:ci:ts":'tap --ts --no-check-coverage --coverage-report=lcovonly "test/**/*.test.*ts"',"test:yarn":'npm run transpile && tap "test/**/*.test.js" --no-check-coverage',transpile:"sh ./test/ts/transpile.sh",prepare:"husky install"},standard:{ignore:["test/ts/**/*","test/syntax-error.mjs"]},repository:{type:"git",url:"git+https://github.com/mcollina/thread-stream.git"},keywords:["worker","thread","threads","stream"],author:"Matteo Collina ",license:"MIT",bugs:{url:"https://github.com/mcollina/thread-stream/issues"},homepage:"https://github.com/mcollina/thread-stream#readme"}});var vr=O((nu,xr)=>{"use strict";function Cs(e,t,r,n,i){let o=Date.now()+n,f=Atomics.load(e,t);if(f===r){i(null,"ok");return}let u=f,d=y=>{Date.now()>o?i(null,"timed-out"):setTimeout(()=>{u=f,f=Atomics.load(e,t),f===u?d(y>=1e3?1e3:y*2):f===r?i(null,"ok"):i(null,"not-equal")},y)};d(1)}function Ns(e,t,r,n,i){let o=Date.now()+n,f=Atomics.load(e,t);if(f!==r){i(null,"ok");return}let u=d=>{Date.now()>o?i(null,"timed-out"):setTimeout(()=>{f=Atomics.load(e,t),f!==r?i(null,"ok"):u(d>=1e3?1e3:d*2)},d)};u(1)}xr.exports={wait:Cs,waitDiff:Ns}});var $r=O((iu,Lr)=>{"use strict";Lr.exports={WRITE_INDEX:4,READ_INDEX:8}});var Rr=O((su,kr)=>{"use strict";var{version:Ds}=Or(),{EventEmitter:Ps}=T("events"),{Worker:zs}=T("worker_threads"),{join:Ws}=T("path"),{pathToFileURL:Ms}=T("url"),{wait:Fs}=vr(),{WRITE_INDEX:B,READ_INDEX:P}=$r(),Vs=T("buffer"),Ks=T("assert"),a=Symbol("kImpl"),Js=Vs.constants.MAX_STRING_LENGTH,ee=class{constructor(t){this._value=t}deref(){return this._value}},de=class{register(){}unregister(){}},Us=process.env.NODE_V8_COVERAGE?de:global.FinalizationRegistry||de,Gs=process.env.NODE_V8_COVERAGE?ee:global.WeakRef||ee,Ar=new Us(e=>{e.exited||e.terminate()});function Hs(e,t){let{filename:r,workerData:n}=t,o=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||Ws(__dirname,"lib","worker.js"),f=new zs(o,{...t.workerOpts,trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:Ms(r).href,dataBuf:e[a].dataBuf,stateBuf:e[a].stateBuf,workerData:{$context:{threadStreamVersion:Ds},...n}}});return f.stream=new ee(e),f.on("message",Xs),f.on("exit",Tr),Ar.register(e,f),f}function jr(e){Ks(!e[a].sync),e[a].needDrain&&(e[a].needDrain=!1,e.emit("drain"))}function he(e){let t=Atomics.load(e[a].state,B),r=e[a].data.length-t;if(r>0){if(e[a].buf.length===0){e[a].flushing=!1,e[a].ending?Ge(e):e[a].needDrain&&process.nextTick(jr,e);return}let n=e[a].buf.slice(0,r),i=Buffer.byteLength(n);i<=r?(e[a].buf=e[a].buf.slice(r),ye(e,n,he.bind(null,e))):e.flush(()=>{if(!e.destroyed){for(Atomics.store(e[a].state,P,0),Atomics.store(e[a].state,B,0);i>e[a].data.length;)r=r/2,n=e[a].buf.slice(0,r),i=Buffer.byteLength(n);e[a].buf=e[a].buf.slice(r),ye(e,n,he.bind(null,e))}})}else if(r===0){if(t===0&&e[a].buf.length===0)return;e.flush(()=>{Atomics.store(e[a].state,P,0),Atomics.store(e[a].state,B,0),he(e)})}else z(e,new Error("overwritten"))}function Xs(e){let t=this.stream.deref();if(t===void 0){this.exited=!0,this.terminate();return}switch(e.code){case"READY":this.stream=new Gs(t),t.flush(()=>{t[a].ready=!0,t.emit("ready")});break;case"ERROR":z(t,e.err);break;case"EVENT":Array.isArray(e.args)?t.emit(e.name,...e.args):t.emit(e.name,e.args);break;case"WARNING":process.emitWarning(e.err);break;default:z(t,new Error("this should not happen: "+e.code))}}function Tr(e){let t=this.stream.deref();t!==void 0&&(Ar.unregister(t),t.worker.exited=!0,t.worker.off("exit",Tr),z(t,e!==0?new Error("the worker thread exited"):null))}var Ke=class extends Ps{constructor(t={}){if(super(),t.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[a]={},this[a].stateBuf=new SharedArrayBuffer(128),this[a].state=new Int32Array(this[a].stateBuf),this[a].dataBuf=new SharedArrayBuffer(t.bufferSize||4*1024*1024),this[a].data=Buffer.from(this[a].dataBuf),this[a].sync=t.sync||!1,this[a].ending=!1,this[a].ended=!1,this[a].needDrain=!1,this[a].destroyed=!1,this[a].flushing=!1,this[a].ready=!1,this[a].finished=!1,this[a].errored=null,this[a].closed=!1,this[a].buf="",this.worker=Hs(this,t),this.on("message",(r,n)=>{this.worker.postMessage(r,n)})}write(t){if(this[a].destroyed)return Je(this,new Error("the worker has exited")),!1;if(this[a].ending)return Je(this,new Error("the worker is ending")),!1;if(this[a].flushing&&this[a].buf.length+t.length>=Js)try{Ve(this),this[a].flushing=!0}catch(r){return z(this,r),!1}if(this[a].buf+=t,this[a].sync)try{return Ve(this),!0}catch(r){return z(this,r),!1}return this[a].flushing||(this[a].flushing=!0,setImmediate(he,this)),this[a].needDrain=this[a].data.length-this[a].buf.length-Atomics.load(this[a].state,B)<=0,!this[a].needDrain}end(){this[a].destroyed||(this[a].ending=!0,Ge(this))}flush(t){if(this[a].destroyed){typeof t=="function"&&process.nextTick(t,new Error("the worker has exited"));return}let r=Atomics.load(this[a].state,B);Fs(this[a].state,P,r,1/0,(n,i)=>{if(n){z(this,n),process.nextTick(t,n);return}if(i==="not-equal"){this.flush(t);return}process.nextTick(t)})}flushSync(){this[a].destroyed||(Ve(this),Ue(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[a].ready}get destroyed(){return this[a].destroyed}get closed(){return this[a].closed}get writable(){return!this[a].destroyed&&!this[a].ending}get writableEnded(){return this[a].ending}get writableFinished(){return this[a].finished}get writableNeedDrain(){return this[a].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[a].errored}};function Je(e,t){setImmediate(()=>{e.emit("error",t)})}function z(e,t){e[a].destroyed||(e[a].destroyed=!0,t&&(e[a].errored=t,Je(e,t)),e.worker.exited?setImmediate(()=>{e[a].closed=!0,e.emit("close")}):e.worker.terminate().catch(()=>{}).then(()=>{e[a].closed=!0,e.emit("close")}))}function ye(e,t,r){let n=Atomics.load(e[a].state,B),i=Buffer.byteLength(t);return e[a].data.write(t,n),Atomics.store(e[a].state,B,n+i),Atomics.notify(e[a].state,B),r(),!0}function Ge(e){if(!(e[a].ended||!e[a].ending||e[a].flushing)){e[a].ended=!0;try{e.flushSync();let t=Atomics.load(e[a].state,P);Atomics.store(e[a].state,B,-1),Atomics.notify(e[a].state,B);let r=0;for(;t!==-1;){if(Atomics.wait(e[a].state,P,t,1e3),t=Atomics.load(e[a].state,P),t===-2){z(e,new Error("end() failed"));return}if(++r===10){z(e,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{e[a].finished=!0,e.emit("finish")})}catch(t){z(e,t)}}}function Ve(e){let t=()=>{e[a].ending?Ge(e):e[a].needDrain&&process.nextTick(jr,e)};for(e[a].flushing=!1;e[a].buf.length!==0;){let r=Atomics.load(e[a].state,B),n=e[a].data.length-r;if(n===0){Ue(e),Atomics.store(e[a].state,P,0),Atomics.store(e[a].state,B,0);continue}else if(n<0)throw new Error("overwritten");let i=e[a].buf.slice(0,n),o=Buffer.byteLength(i);if(o<=n)e[a].buf=e[a].buf.slice(n),ye(e,i,t);else{for(Ue(e),Atomics.store(e[a].state,P,0),Atomics.store(e[a].state,B,0);o>e[a].buf.length;)n=n/2,i=e[a].buf.slice(0,n),o=Buffer.byteLength(i);e[a].buf=e[a].buf.slice(n),ye(e,i,t)}}}function Ue(e){if(e[a].flushing)throw new Error("unable to flush while flushing");let t=Atomics.load(e[a].state,B),r=0;for(;;){let n=Atomics.load(e[a].state,P);if(n===-2)throw Error("_flushSync failed");if(n!==t)Atomics.wait(e[a].state,P,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}kr.exports=Ke});var Ye=O((ou,Br)=>{"use strict";var{createRequire:Ys}=T("module"),Qs=ke(),{join:He,isAbsolute:Zs,sep:eo}=T("node:path"),to=ze(),Xe=Fe(),ro=Rr();function no(e){Xe.register(e,so),Xe.registerBeforeExit(e,oo),e.on("close",function(){Xe.unregister(e)})}function io(e,t,r,n){let i=new ro({filename:e,workerData:t,workerOpts:r,sync:n});i.on("ready",o),i.on("close",function(){process.removeListener("exit",f)}),process.on("exit",f);function o(){process.removeListener("exit",f),i.unref(),r.autoEnd!==!1&&no(i)}function f(){i.closed||(i.flushSync(),to(100),i.end())}return i}function so(e){e.ref(),e.flushSync(),e.end(),e.once("close",function(){e.unref()})}function oo(e){e.flushSync()}function lo(e){let{pipeline:t,targets:r,levels:n,dedupe:i,worker:o={},caller:f=Qs(),sync:u=!1}=e,d={...e.options},y=typeof f=="string"?[f]:f,h="__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{},l=e.target;if(l&&r)throw new Error("only one of target or targets can be specified");return r?(l=h["pino-worker"]||He(__dirname,"worker.js"),d.targets=r.filter(c=>c.target).map(c=>({...c,target:p(c.target)})),d.pipelines=r.filter(c=>c.pipeline).map(c=>c.pipeline.map(s=>({...s,level:c.level,target:p(s.target)})))):t&&(l=h["pino-worker"]||He(__dirname,"worker.js"),d.pipelines=[t.map(c=>({...c,target:p(c.target)}))]),n&&(d.levels=n),i&&(d.dedupe=i),d.pinoWillSendConfig=!0,io(p(l),d,o,u);function p(c){if(c=h[c]||c,Zs(c)||c.indexOf("file://")===0)return c;if(c==="pino/file")return He(__dirname,"..","file.js");let s;for(let g of y)try{let m=g==="node:repl"?process.cwd()+eo:g;s=Ys(m).resolve(c);break}catch{continue}if(!s)throw new Error(`unable to determine transport target for "${c}"`);return s}}Br.exports=lo});var pe=O((lu,Vr)=>{"use strict";var Ir=ur(),{mapHttpRequest:fo,mapHttpResponse:uo}=Te(),Ze=pr(),qr=Fe(),{lsCacheSym:co,chindingsSym:Dr,writeSym:Cr,serializersSym:Pr,formatOptsSym:Nr,endSym:ao,stringifiersSym:zr,stringifySym:Wr,stringifySafeSym:et,wildcardFirstSym:Mr,nestedKeySym:ho,formattersSym:Fr,messageKeySym:yo,errorKeySym:mo,nestedKeyStrSym:go,msgPrefixSym:me}=H(),{isMainThread:po}=T("worker_threads"),bo=Ye();function Y(){}function wo(e,t){if(!t)return r;return function(...i){t.call(this,i,r,e)};function r(n,...i){if(typeof n=="object"){let o=n;n!==null&&(n.method&&n.headers&&n.socket?n=fo(n):typeof n.setHeader=="function"&&(n=uo(n)));let f;o===null&&i.length===0?f=[null]:(o=i.shift(),f=i),typeof this[me]=="string"&&o!==void 0&&o!==null&&(o=this[me]+o),this[Cr](n,Ir(o,f,this[Nr]),e)}else{let o=n===void 0?i.shift():n;typeof this[me]=="string"&&o!==void 0&&o!==null&&(o=this[me]+o),this[Cr](null,Ir(o,i,this[Nr]),e)}}}function Qe(e){let t="",r=0,n=!1,i=255,o=e.length;if(o>100)return JSON.stringify(e);for(var f=0;f=32;f++)i=e.charCodeAt(f),(i===34||i===92)&&(t+=e.slice(r,f)+"\\",r=f,n=!0);return n?t+=e.slice(r):t=e,i<32?JSON.stringify(e):'"'+t+'"'}function So(e,t,r,n){let i=this[Wr],o=this[et],f=this[zr],u=this[ao],d=this[Dr],y=this[Pr],h=this[Fr],l=this[yo],p=this[mo],c=this[co][r]+n;c=c+d;let s;h.log&&(e=h.log(e));let g=f[Mr],m="";for(let b in e)if(s=e[b],Object.prototype.hasOwnProperty.call(e,b)&&s!==void 0){y[b]?s=y[b](s):b===p&&y.err&&(s=y.err(s));let w=f[b]||g;switch(typeof s){case"undefined":case"function":continue;case"number":Number.isFinite(s)===!1&&(s=null);case"boolean":w&&(s=w(s));break;case"string":s=(w||Qe)(s);break;default:s=(w||i)(s,o)}if(s===void 0)continue;let _=Qe(b);m+=","+_+":"+s}let S="";if(t!==void 0){s=y[l]?y[l](t):t;let b=f[l]||g;switch(typeof s){case"function":break;case"number":Number.isFinite(s)===!1&&(s=null);case"boolean":b&&(s=b(s)),S=',"'+l+'":'+s;break;case"string":s=(b||Qe)(s),S=',"'+l+'":'+s;break;default:s=(b||i)(s,o),S=',"'+l+'":'+s}}return this[ho]&&m?c+this[go]+m.slice(1)+"}"+S+u:c+m+S+u}function _o(e,t){let r,n=e[Dr],i=e[Wr],o=e[et],f=e[zr],u=f[Mr],d=e[Pr],y=e[Fr].bindings;t=y(t);for(let h in t)if(r=t[h],(h!=="level"&&h!=="serializers"&&h!=="formatters"&&h!=="customLevels"&&t.hasOwnProperty(h)&&r!==void 0)===!0){if(r=d[h]?d[h](r):r,r=(f[h]||u||i)(r,o),r===void 0)continue;n+=',"'+h+'":'+r}return n}function Eo(e){return e.write!==e.constructor.prototype.write}function ge(e){let t=new Ze(e);return t.on("error",r),!e.sync&&po&&(qr.register(t,Oo),t.on("close",function(){qr.unregister(t)})),t;function r(n){if(n.code==="EPIPE"){t.write=Y,t.end=Y,t.flushSync=Y,t.destroy=Y;return}t.removeListener("error",r),t.emit("error",n)}}function Oo(e,t){e.destroyed||(t==="beforeExit"?(e.flush(),e.on("drain",function(){e.end()})):e.flushSync())}function xo(e){return function(r,n,i={},o){if(typeof i=="string")o=ge({dest:i}),i={};else if(typeof o=="string"){if(i&&i.transport)throw Error("only one of option.transport or stream can be specified");o=ge({dest:o})}else if(i instanceof Ze||i.writable||i._writableState)o=i,i={};else if(i.transport){if(i.transport instanceof Ze||i.transport.writable||i.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(i.transport.targets&&i.transport.targets.length&&i.formatters&&typeof i.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let d;i.customLevels&&(d=i.useOnlyCustomLevels?i.customLevels:Object.assign({},i.levels,i.customLevels)),o=bo({caller:n,...i.transport,levels:d})}if(i=Object.assign({},e,i),i.serializers=Object.assign({},e.serializers,i.serializers),i.formatters=Object.assign({},e.formatters,i.formatters),i.prettyPrint)throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:f,onChild:u}=i;return f===!1&&(i.level="silent"),u||(i.onChild=Y),o||(Eo(process.stdout)?o=process.stdout:o=ge({fd:process.stdout.fd||1})),{opts:i,stream:o}}}function vo(e,t){try{return JSON.stringify(e)}catch{try{return(t||this[et])(e)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function Lo(e,t,r){return{level:e,bindings:t,log:r}}function $o(e){let t=Number(e);return typeof e=="string"&&Number.isFinite(t)?t:e===void 0?1:e}Vr.exports={noop:Y,buildSafeSonicBoom:ge,asChindings:_o,asJson:So,genLog:wo,createArgsNormalizer:xo,stringify:vo,buildFormatters:Lo,normalizeDestFileDescriptor:$o}});var be=O((fu,Kr)=>{var Ao={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},jo={ASC:"ASC",DESC:"DESC"};Kr.exports={DEFAULT_LEVELS:Ao,SORTING_ORDER:jo}});var nt=O((uu,Hr)=>{"use strict";var{lsCacheSym:To,levelValSym:tt,useOnlyCustomLevelsSym:ko,streamSym:Ro,formattersSym:Bo,hooksSym:Io,levelCompSym:Jr}=H(),{noop:qo,genLog:K}=pe(),{DEFAULT_LEVELS:W,SORTING_ORDER:Ur}=be(),Gr={fatal:e=>{let t=K(W.fatal,e);return function(...r){let n=this[Ro];if(t.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:e=>K(W.error,e),warn:e=>K(W.warn,e),info:e=>K(W.info,e),debug:e=>K(W.debug,e),trace:e=>K(W.trace,e)},rt=Object.keys(W).reduce((e,t)=>(e[W[t]]=t,e),{}),Co=Object.keys(rt).reduce((e,t)=>(e[t]='{"level":'+Number(t),e),{});function No(e){let t=e[Bo].level,{labels:r}=e.levels,n={};for(let i in r){let o=t(r[i],Number(i));n[i]=JSON.stringify(o).slice(0,-1)}return e[To]=n,e}function Do(e,t){if(t)return!1;switch(e){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function Po(e){let{labels:t,values:r}=this.levels;if(typeof e=="number"){if(t[e]===void 0)throw Error("unknown level value"+e);e=t[e]}if(r[e]===void 0)throw Error("unknown level "+e);let n=this[tt],i=this[tt]=r[e],o=this[ko],f=this[Jr],u=this[Io].logMethod;for(let d in r){if(f(r[d],i)===!1){this[d]=qo;continue}this[d]=Do(d,o)?Gr[d](u):K(r[d],u)}this.emit("level-change",e,i,t[n],n,this)}function zo(e){let{levels:t,levelVal:r}=this;return t&&t.labels?t.labels[r]:""}function Wo(e){let{values:t}=this.levels,r=t[e];return r!==void 0&&this[Jr](r,this[tt])}function Mo(e,t,r){return e===Ur.DESC?t<=r:t>=r}function Fo(e){return typeof e=="string"?Mo.bind(null,e):e}function Vo(e=null,t=!1){let r=e?Object.keys(e).reduce((o,f)=>(o[e[f]]=f,o),{}):null,n=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),t?null:rt,r),i=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:W,e);return{labels:n,values:i}}function Ko(e,t,r){if(typeof e=="number"){if(![].concat(Object.keys(t||{}).map(o=>t[o]),r?[]:Object.keys(rt).map(o=>+o),1/0).includes(e))throw Error(`default level:${e} must be included in custom levels`);return}let n=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),r?null:W,t);if(!(e in n))throw Error(`default level:${e} must be included in custom levels`)}function Jo(e,t){let{labels:r,values:n}=e;for(let i in t){if(i in n)throw Error("levels cannot be overridden");if(t[i]in r)throw Error("pre-existing level values cannot be used for new levels")}}function Uo(e){if(typeof e!="function"&&!(typeof e=="string"&&Object.values(Ur).includes(e)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}Hr.exports={initialLsCache:Co,genLsCache:No,levelMethods:Gr,getLevel:zo,setLevel:Po,isLevelEnabled:Wo,mappings:Vo,assertNoLevelCollisions:Jo,assertDefaultLevelFound:Ko,genLevelComparison:Fo,assertLevelComparison:Uo}});var it=O((cu,Xr)=>{"use strict";Xr.exports={version:"9.7.0"}});var fn=O((hu,ln)=>{"use strict";var{EventEmitter:Go}=T("node:events"),{lsCacheSym:Ho,levelValSym:Xo,setLevelSym:ot,getLevelSym:Yr,chindingsSym:lt,parsedChindingsSym:Yo,mixinSym:Qo,asJsonSym:rn,writeSym:Zo,mixinMergeStrategySym:el,timeSym:tl,timeSliceIndexSym:rl,streamSym:nn,serializersSym:J,formattersSym:st,errorKeySym:nl,messageKeySym:il,useOnlyCustomLevelsSym:sl,needsMetadataGsym:ol,redactFmtSym:ll,stringifySym:fl,formatOptsSym:ul,stringifiersSym:cl,msgPrefixSym:Qr,hooksSym:al}=H(),{getLevel:hl,setLevel:dl,isLevelEnabled:yl,mappings:ml,initialLsCache:gl,genLsCache:pl,assertNoLevelCollisions:bl}=nt(),{asChindings:sn,asJson:wl,buildFormatters:Zr,stringify:en}=pe(),{version:Sl}=it(),_l=De(),El=class{},on={constructor:El,child:Ol,bindings:xl,setBindings:vl,flush:jl,isLevelEnabled:yl,version:Sl,get level(){return this[Yr]()},set level(e){this[ot](e)},get levelVal(){return this[Xo]},set levelVal(e){throw Error("levelVal is read-only")},[Ho]:gl,[Zo]:$l,[rn]:wl,[Yr]:hl,[ot]:dl};Object.setPrototypeOf(on,Go.prototype);ln.exports=function(){return Object.create(on)};var tn=e=>e;function Ol(e,t){if(!e)throw Error("missing bindings for child Pino");t=t||{};let r=this[J],n=this[st],i=Object.create(this);if(t.hasOwnProperty("serializers")===!0){i[J]=Object.create(null);for(let h in r)i[J][h]=r[h];let d=Object.getOwnPropertySymbols(r);for(var o=0;o{"use strict";var{hasOwnProperty:te}=Object.prototype,G=ct();G.configure=ct;G.stringify=G;G.default=G;at.stringify=G;at.configure=ct;an.exports=G;var Tl=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function F(e){return e.length<5e3&&!Tl.test(e)?`"${e}"`:JSON.stringify(e)}function ft(e,t){if(e.length>200||t)return e.sort(t);for(let r=1;rn;)e[i]=e[i-1],i--;e[i]=n}return e}var kl=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function ut(e){return kl.call(e)!==void 0&&e.length!==0}function un(e,t,r){e.length= 1`)}return r===void 0?1/0:r}function U(e){return e===1?"1 item":`${e} items`}function ql(e){let t=new Set;for(let r of e)(typeof r=="string"||typeof r=="number")&&t.add(String(r));return t}function Cl(e){if(te.call(e,"strict")){let t=e.strict;if(typeof t!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(t)return r=>{let n=`Object can not safely be stringified. Received type ${typeof r}`;throw typeof r!="function"&&(n+=` (${r.toString()})`),new Error(n)}}}function ct(e){e={...e};let t=Cl(e);t&&(e.bigint===void 0&&(e.bigint=!1),"circularValue"in e||(e.circularValue=Error));let r=Rl(e),n=Il(e,"bigint"),i=Bl(e),o=typeof i=="function"?i:void 0,f=cn(e,"maximumDepth"),u=cn(e,"maximumBreadth");function d(c,s,g,m,S,b){let w=s[c];switch(typeof w=="object"&&w!==null&&typeof w.toJSON=="function"&&(w=w.toJSON(c)),w=m.call(s,c,w),typeof w){case"string":return F(w);case"object":{if(w===null)return"null";if(g.indexOf(w)!==-1)return r;let _="",x=",",v=b;if(Array.isArray(w)){if(w.length===0)return"[]";if(fu){let V=w.length-u-1;_+=`${x}"... ${U(V)} not stringified"`}return S!==""&&(_+=` +${v}`),g.pop(),`[${_}]`}let L=Object.keys(w),$=L.length;if($===0)return"{}";if(fu){let k=$-u;_+=`${A}"...":${E}"${U(k)} not stringified"`,A=x}return S!==""&&A.length>1&&(_=` +${b}${_} +${v}`),g.pop(),`{${_}}`}case"number":return isFinite(w)?String(w):t?t(w):"null";case"boolean":return w===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(w);default:return t?t(w):void 0}}function y(c,s,g,m,S,b){switch(typeof s=="object"&&s!==null&&typeof s.toJSON=="function"&&(s=s.toJSON(c)),typeof s){case"string":return F(s);case"object":{if(s===null)return"null";if(g.indexOf(s)!==-1)return r;let w=b,_="",x=",";if(Array.isArray(s)){if(s.length===0)return"[]";if(fu){let R=s.length-u-1;_+=`${x}"... ${U(R)} not stringified"`}return S!==""&&(_+=` +${w}`),g.pop(),`[${_}]`}g.push(s);let v="";S!==""&&(b+=S,x=`, +${b}`,v=" ");let L="";for(let $ of m){let E=y($,s[$],g,m,S,b);E!==void 0&&(_+=`${L}${F($)}:${v}${E}`,L=x)}return S!==""&&L.length>1&&(_=` +${b}${_} +${w}`),g.pop(),`{${_}}`}case"number":return isFinite(s)?String(s):t?t(s):"null";case"boolean":return s===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(s);default:return t?t(s):void 0}}function h(c,s,g,m,S){switch(typeof s){case"string":return F(s);case"object":{if(s===null)return"null";if(typeof s.toJSON=="function"){if(s=s.toJSON(c),typeof s!="object")return h(c,s,g,m,S);if(s===null)return"null"}if(g.indexOf(s)!==-1)return r;let b=S;if(Array.isArray(s)){if(s.length===0)return"[]";if(fu){let q=s.length-u-1;E+=`${A}"... ${U(q)} not stringified"`}return E+=` +${b}`,g.pop(),`[${E}]`}let w=Object.keys(s),_=w.length;if(_===0)return"{}";if(fu){let E=_-u;v+=`${L}"...": "${U(E)} not stringified"`,L=x}return L!==""&&(v=` +${S}${v} +${b}`),g.pop(),`{${v}}`}case"number":return isFinite(s)?String(s):t?t(s):"null";case"boolean":return s===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(s);default:return t?t(s):void 0}}function l(c,s,g){switch(typeof s){case"string":return F(s);case"object":{if(s===null)return"null";if(typeof s.toJSON=="function"){if(s=s.toJSON(c),typeof s!="object")return l(c,s,g);if(s===null)return"null"}if(g.indexOf(s)!==-1)return r;let m="",S=s.length!==void 0;if(S&&Array.isArray(s)){if(s.length===0)return"[]";if(fu){let E=s.length-u-1;m+=`,"... ${U(E)} not stringified"`}return g.pop(),`[${m}]`}let b=Object.keys(s),w=b.length;if(w===0)return"{}";if(fu){let v=w-u;m+=`${_}"...":"${U(v)} not stringified"`}return g.pop(),`{${m}}`}case"number":return isFinite(s)?String(s):t?t(s):"null";case"boolean":return s===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(s);default:return t?t(s):void 0}}function p(c,s,g){if(arguments.length>1){let m="";if(typeof g=="number"?m=" ".repeat(Math.min(g,10)):typeof g=="string"&&(m=g.slice(0,10)),s!=null){if(typeof s=="function")return d("",{"":c},[],s,m,"");if(Array.isArray(s))return y("",c,[],ql(s),m,"")}if(m.length!==0)return h("",c,[],m,"")}return l("",c,[])}return p}});var mn=O((du,yn)=>{"use strict";var ht=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:dn}=be(),Nl=dn.info;function Dl(e,t){let r=0;e=e||[],t=t||{dedupe:!1};let n=Object.create(dn);n.silent=1/0,t.levels&&typeof t.levels=="object"&&Object.keys(t.levels).forEach(l=>{n[l]=t.levels[l]});let i={write:o,add:d,emit:f,flushSync:u,end:y,minLevel:0,streams:[],clone:h,[ht]:!0,streamLevels:n};return Array.isArray(e)?e.forEach(d,i):d.call(i,e),e=null,i;function o(l){let p,c=this.lastLevel,{streams:s}=this,g=0,m;for(let S=zl(s.length,t.dedupe);Ml(S,s.length,t.dedupe);S=Wl(S,t.dedupe))if(p=s[S],p.level<=c){if(g!==0&&g!==p.level)break;if(m=p.stream,m[ht]){let{lastTime:b,lastMsg:w,lastObj:_,lastLogger:x}=this;m.lastLevel=c,m.lastTime=b,m.lastMsg=w,m.lastObj=_,m.lastLogger=x}m.write(l),t.dedupe&&(g=p.level)}else if(!t.dedupe)break}function f(...l){for(let{stream:p}of this.streams)typeof p.emit=="function"&&p.emit(...l)}function u(){for(let{stream:l}of this.streams)typeof l.flushSync=="function"&&l.flushSync()}function d(l){if(!l)return i;let p=typeof l.write=="function"||l.stream,c=l.write?l:l.stream;if(!p)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:s,streamLevels:g}=this,m;typeof l.levelVal=="number"?m=l.levelVal:typeof l.level=="string"?m=g[l.level]:typeof l.level=="number"?m=l.level:m=Nl;let S={stream:c,level:m,levelVal:void 0,id:r++};return s.unshift(S),s.sort(Pl),this.minLevel=s[0].level,i}function y(){for(let{stream:l}of this.streams)typeof l.flushSync=="function"&&l.flushSync(),l.end()}function h(l){let p=new Array(this.streams.length);for(let c=0;c=0:e{function we(e){try{return T("path").join(`${process.cwd()}${T("path").sep}dist/esm`.replace(/\\/g,"/"),e)}catch{return new Function("p","return new URL(p, import.meta.url).pathname")(e)}}globalThis.__bundlerPathsOverrides={...globalThis.__bundlerPathsOverrides||{},"thread-stream-worker":we("./thread-stream-worker.mjs"),"pino-worker":we("./pino-worker.mjs"),"pino/file":we("./pino-file.mjs"),"pino-roll":we("./pino-roll.mjs")};var Fl=T("node:os"),On=Te(),Vl=ke(),Kl=De(),xn=lr(),Jl=fn(),vn=H(),{configure:Ul}=hn(),{assertDefaultLevelFound:Gl,mappings:Ln,genLsCache:Hl,genLevelComparison:Xl,assertLevelComparison:Yl}=nt(),{DEFAULT_LEVELS:$n,SORTING_ORDER:Ql}=be(),{createArgsNormalizer:Zl,asChindings:ef,buildSafeSonicBoom:gn,buildFormatters:tf,stringify:dt,normalizeDestFileDescriptor:pn,noop:rf}=pe(),{version:nf}=it(),{chindingsSym:bn,redactFmtSym:sf,serializersSym:wn,timeSym:of,timeSliceIndexSym:lf,streamSym:ff,stringifySym:Sn,stringifySafeSym:yt,stringifiersSym:_n,setLevelSym:uf,endSym:cf,formatOptsSym:af,messageKeySym:hf,errorKeySym:df,nestedKeySym:yf,mixinSym:mf,levelCompSym:gf,useOnlyCustomLevelsSym:pf,formattersSym:En,hooksSym:bf,nestedKeyStrSym:wf,mixinMergeStrategySym:Sf,msgPrefixSym:_f}=vn,{epochTime:An,nullTime:Ef}=xn,{pid:Of}=process,xf=Fl.hostname(),vf=On.err,Lf={level:"info",levelComparison:Ql.ASC,levels:$n,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:Of,hostname:xf},serializers:Object.assign(Object.create(null),{err:vf}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:An,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},$f=Zl(Lf),Af=Object.assign(Object.create(null),On);function mt(...e){let t={},{opts:r,stream:n}=$f(t,Vl(),...e);r.level&&typeof r.level=="string"&&$n[r.level.toLowerCase()]!==void 0&&(r.level=r.level.toLowerCase());let{redact:i,crlf:o,serializers:f,timestamp:u,messageKey:d,errorKey:y,nestedKey:h,base:l,name:p,level:c,customLevels:s,levelComparison:g,mixin:m,mixinMergeStrategy:S,useOnlyCustomLevels:b,formatters:w,hooks:_,depthLimit:x,edgeLimit:v,onChild:L,msgPrefix:$}=r,E=Ul({maximumDepth:x,maximumBreadth:v}),A=tf(w.level,w.bindings,w.log),R=dt.bind({[yt]:E}),k=i?Kl(i,R):{},I=i?{stringify:k[sf]}:{stringify:R},q="}"+(o?`\r +`:` +`),V=ef.bind(null,{[bn]:"",[wn]:f,[_n]:k,[Sn]:dt,[yt]:E,[En]:A}),Se="";l!==null&&(p===void 0?Se=V(l):Se=V(Object.assign({},l,{name:p})));let gt=u instanceof Function?u:u?An:Ef,kn=gt().indexOf(":")+1;if(b&&!s)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(m&&typeof m!="function")throw Error(`Unknown mixin type "${typeof m}" - expected "function"`);if($&&typeof $!="string")throw Error(`Unknown msgPrefix type "${typeof $}" - expected "string"`);Gl(c,s,b);let pt=Ln(s,b);typeof n.emit=="function"&&n.emit("message",{code:"PINO_CONFIG",config:{levels:pt,messageKey:d,errorKey:y}}),Yl(g);let Rn=Xl(g);return Object.assign(t,{levels:pt,[gf]:Rn,[pf]:b,[ff]:n,[of]:gt,[lf]:kn,[Sn]:dt,[yt]:E,[_n]:k,[cf]:q,[af]:I,[hf]:d,[df]:y,[yf]:h,[wf]:h?`,${JSON.stringify(h)}:{`:"",[wn]:f,[mf]:m,[Sf]:S,[bn]:Se,[En]:A,[bf]:_,silent:rf,onChild:L,[_f]:$}),Object.setPrototypeOf(t,Jl()),Hl(t),t[uf](c),t}C.exports=mt;C.exports.destination=(e=process.stdout.fd)=>typeof e=="object"?(e.dest=pn(e.dest||process.stdout.fd),gn(e)):gn({dest:pn(e),minLength:0});C.exports.transport=Ye();C.exports.multistream=mn();C.exports.levels=Ln();C.exports.stdSerializers=Af;C.exports.stdTimeFunctions=Object.assign({},xn);C.exports.symbols=vn;C.exports.version=nf;C.exports.default=mt;C.exports.pino=mt});var kf=O((mu,Tn)=>{var jf=jn(),{once:Tf}=T("node:events");Tn.exports=async function(e={}){let t=Object.assign({},e,{dest:e.destination||1,sync:!1});delete t.destination;let r=jf.destination(t);return await Tf(r,"ready"),r}});export default kf(); +//# sourceMappingURL=pino-file.mjs.map diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-file.mjs.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-file.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..1aad850d10ed4b5db1215fbc28c331fddc1915eb --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-file.mjs.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err-helpers.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err-proto.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err-with-cause.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/req.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/res.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/caller.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/validator.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/rx.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/parse.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/redactor.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/modifiers.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/restorer.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/state.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/symbols.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/redaction.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/time.js", "../../node_modules/.pnpm/quick-format-unescaped@4.0.4/node_modules/quick-format-unescaped/index.js", "../../node_modules/.pnpm/atomic-sleep@1.0.0/node_modules/atomic-sleep/index.js", "../../node_modules/.pnpm/sonic-boom@4.2.0/node_modules/sonic-boom/index.js", "../../node_modules/.pnpm/on-exit-leak-free@2.1.2/node_modules/on-exit-leak-free/index.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/package.json", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/wait.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/indexes.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/transport.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/tools.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/constants.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/levels.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/meta.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/proto.js", "../../node_modules/.pnpm/safe-stable-stringify@2.5.0/node_modules/safe-stable-stringify/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/multistream.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/pino.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/file.js"], + "sourcesContent": ["'use strict'\n\n// **************************************************************\n// * Code initially copied/adapted from \"pony-cause\" npm module *\n// * Please upstream improvements there *\n// **************************************************************\n\nconst isErrorLike = (err) => {\n return err && typeof err.message === 'string'\n}\n\n/**\n * @param {Error|{ cause?: unknown|(()=>err)}} err\n * @returns {Error|Object|undefined}\n */\nconst getErrorCause = (err) => {\n if (!err) return\n\n /** @type {unknown} */\n // @ts-ignore\n const cause = err.cause\n\n // VError / NError style causes\n if (typeof cause === 'function') {\n // @ts-ignore\n const causeResult = err.cause()\n\n return isErrorLike(causeResult)\n ? causeResult\n : undefined\n } else {\n return isErrorLike(cause)\n ? cause\n : undefined\n }\n}\n\n/**\n * Internal method that keeps a track of which error we have already added, to avoid circular recursion\n *\n * @private\n * @param {Error} err\n * @param {Set} seen\n * @returns {string}\n */\nconst _stackWithCauses = (err, seen) => {\n if (!isErrorLike(err)) return ''\n\n const stack = err.stack || ''\n\n // Ensure we don't go circular or crazily deep\n if (seen.has(err)) {\n return stack + '\\ncauses have become circular...'\n }\n\n const cause = getErrorCause(err)\n\n if (cause) {\n seen.add(err)\n return (stack + '\\ncaused by: ' + _stackWithCauses(cause, seen))\n } else {\n return stack\n }\n}\n\n/**\n * @param {Error} err\n * @returns {string}\n */\nconst stackWithCauses = (err) => _stackWithCauses(err, new Set())\n\n/**\n * Internal method that keeps a track of which error we have already added, to avoid circular recursion\n *\n * @private\n * @param {Error} err\n * @param {Set} seen\n * @param {boolean} [skip]\n * @returns {string}\n */\nconst _messageWithCauses = (err, seen, skip) => {\n if (!isErrorLike(err)) return ''\n\n const message = skip ? '' : (err.message || '')\n\n // Ensure we don't go circular or crazily deep\n if (seen.has(err)) {\n return message + ': ...'\n }\n\n const cause = getErrorCause(err)\n\n if (cause) {\n seen.add(err)\n\n // @ts-ignore\n const skipIfVErrorStyleCause = typeof err.cause === 'function'\n\n return (message +\n (skipIfVErrorStyleCause ? '' : ': ') +\n _messageWithCauses(cause, seen, skipIfVErrorStyleCause))\n } else {\n return message\n }\n}\n\n/**\n * @param {Error} err\n * @returns {string}\n */\nconst messageWithCauses = (err) => _messageWithCauses(err, new Set())\n\nmodule.exports = {\n isErrorLike,\n getErrorCause,\n stackWithCauses,\n messageWithCauses\n}\n", "'use strict'\n\nconst seen = Symbol('circular-ref-tag')\nconst rawSymbol = Symbol('pino-raw-err-ref')\n\nconst pinoErrProto = Object.create({}, {\n type: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n message: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n stack: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n aggregateErrors: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoErrProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nmodule.exports = {\n pinoErrProto,\n pinoErrorSymbols: {\n seen,\n rawSymbol\n }\n}\n", "'use strict'\n\nmodule.exports = errSerializer\n\nconst { messageWithCauses, stackWithCauses, isErrorLike } = require('./err-helpers')\nconst { pinoErrProto, pinoErrorSymbols } = require('./err-proto')\nconst { seen } = pinoErrorSymbols\n\nconst { toString } = Object.prototype\n\nfunction errSerializer (err) {\n if (!isErrorLike(err)) {\n return err\n }\n\n err[seen] = undefined // tag to prevent re-looking at this\n const _err = Object.create(pinoErrProto)\n _err.type = toString.call(err.constructor) === '[object Function]'\n ? err.constructor.name\n : err.name\n _err.message = messageWithCauses(err)\n _err.stack = stackWithCauses(err)\n\n if (Array.isArray(err.errors)) {\n _err.aggregateErrors = err.errors.map(err => errSerializer(err))\n }\n\n for (const key in err) {\n if (_err[key] === undefined) {\n const val = err[key]\n if (isErrorLike(val)) {\n // We append cause messages and stacks to _err, therefore skipping causes here\n if (key !== 'cause' && !Object.prototype.hasOwnProperty.call(val, seen)) {\n _err[key] = errSerializer(val)\n }\n } else {\n _err[key] = val\n }\n }\n }\n\n delete err[seen] // clean up tag in case err is serialized again later\n _err.raw = err\n return _err\n}\n", "'use strict'\n\nmodule.exports = errWithCauseSerializer\n\nconst { isErrorLike } = require('./err-helpers')\nconst { pinoErrProto, pinoErrorSymbols } = require('./err-proto')\nconst { seen } = pinoErrorSymbols\n\nconst { toString } = Object.prototype\n\nfunction errWithCauseSerializer (err) {\n if (!isErrorLike(err)) {\n return err\n }\n\n err[seen] = undefined // tag to prevent re-looking at this\n const _err = Object.create(pinoErrProto)\n _err.type = toString.call(err.constructor) === '[object Function]'\n ? err.constructor.name\n : err.name\n _err.message = err.message\n _err.stack = err.stack\n\n if (Array.isArray(err.errors)) {\n _err.aggregateErrors = err.errors.map(err => errWithCauseSerializer(err))\n }\n\n if (isErrorLike(err.cause) && !Object.prototype.hasOwnProperty.call(err.cause, seen)) {\n _err.cause = errWithCauseSerializer(err.cause)\n }\n\n for (const key in err) {\n if (_err[key] === undefined) {\n const val = err[key]\n if (isErrorLike(val)) {\n if (!Object.prototype.hasOwnProperty.call(val, seen)) {\n _err[key] = errWithCauseSerializer(val)\n }\n } else {\n _err[key] = val\n }\n }\n }\n\n delete err[seen] // clean up tag in case err is serialized again later\n _err.raw = err\n return _err\n}\n", "'use strict'\n\nmodule.exports = {\n mapHttpRequest,\n reqSerializer\n}\n\nconst rawSymbol = Symbol('pino-raw-req-ref')\nconst pinoReqProto = Object.create({}, {\n id: {\n enumerable: true,\n writable: true,\n value: ''\n },\n method: {\n enumerable: true,\n writable: true,\n value: ''\n },\n url: {\n enumerable: true,\n writable: true,\n value: ''\n },\n query: {\n enumerable: true,\n writable: true,\n value: ''\n },\n params: {\n enumerable: true,\n writable: true,\n value: ''\n },\n headers: {\n enumerable: true,\n writable: true,\n value: {}\n },\n remoteAddress: {\n enumerable: true,\n writable: true,\n value: ''\n },\n remotePort: {\n enumerable: true,\n writable: true,\n value: ''\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoReqProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nfunction reqSerializer (req) {\n // req.info is for hapi compat.\n const connection = req.info || req.socket\n const _req = Object.create(pinoReqProto)\n _req.id = (typeof req.id === 'function' ? req.id() : (req.id || (req.info ? req.info.id : undefined)))\n _req.method = req.method\n // req.originalUrl is for expressjs compat.\n if (req.originalUrl) {\n _req.url = req.originalUrl\n } else {\n const path = req.path\n // path for safe hapi compat.\n _req.url = typeof path === 'string' ? path : (req.url ? req.url.path || req.url : undefined)\n }\n\n if (req.query) {\n _req.query = req.query\n }\n\n if (req.params) {\n _req.params = req.params\n }\n\n _req.headers = req.headers\n _req.remoteAddress = connection && connection.remoteAddress\n _req.remotePort = connection && connection.remotePort\n // req.raw is for hapi compat/equivalence\n _req.raw = req.raw || req\n return _req\n}\n\nfunction mapHttpRequest (req) {\n return {\n req: reqSerializer(req)\n }\n}\n", "'use strict'\n\nmodule.exports = {\n mapHttpResponse,\n resSerializer\n}\n\nconst rawSymbol = Symbol('pino-raw-res-ref')\nconst pinoResProto = Object.create({}, {\n statusCode: {\n enumerable: true,\n writable: true,\n value: 0\n },\n headers: {\n enumerable: true,\n writable: true,\n value: ''\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoResProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nfunction resSerializer (res) {\n const _res = Object.create(pinoResProto)\n _res.statusCode = res.headersSent ? res.statusCode : null\n _res.headers = res.getHeaders ? res.getHeaders() : res._headers\n _res.raw = res\n return _res\n}\n\nfunction mapHttpResponse (res) {\n return {\n res: resSerializer(res)\n }\n}\n", "'use strict'\n\nconst errSerializer = require('./lib/err')\nconst errWithCauseSerializer = require('./lib/err-with-cause')\nconst reqSerializers = require('./lib/req')\nconst resSerializers = require('./lib/res')\n\nmodule.exports = {\n err: errSerializer,\n errWithCause: errWithCauseSerializer,\n mapHttpRequest: reqSerializers.mapHttpRequest,\n mapHttpResponse: resSerializers.mapHttpResponse,\n req: reqSerializers.reqSerializer,\n res: resSerializers.resSerializer,\n\n wrapErrorSerializer: function wrapErrorSerializer (customSerializer) {\n if (customSerializer === errSerializer) return customSerializer\n return function wrapErrSerializer (err) {\n return customSerializer(errSerializer(err))\n }\n },\n\n wrapRequestSerializer: function wrapRequestSerializer (customSerializer) {\n if (customSerializer === reqSerializers.reqSerializer) return customSerializer\n return function wrappedReqSerializer (req) {\n return customSerializer(reqSerializers.reqSerializer(req))\n }\n },\n\n wrapResponseSerializer: function wrapResponseSerializer (customSerializer) {\n if (customSerializer === resSerializers.resSerializer) return customSerializer\n return function wrappedResSerializer (res) {\n return customSerializer(resSerializers.resSerializer(res))\n }\n }\n}\n", "'use strict'\n\nfunction noOpPrepareStackTrace (_, stack) {\n return stack\n}\n\nmodule.exports = function getCallers () {\n const originalPrepare = Error.prepareStackTrace\n Error.prepareStackTrace = noOpPrepareStackTrace\n const stack = new Error().stack\n Error.prepareStackTrace = originalPrepare\n\n if (!Array.isArray(stack)) {\n return undefined\n }\n\n const entries = stack.slice(2)\n\n const fileNames = []\n\n for (const entry of entries) {\n if (!entry) {\n continue\n }\n\n fileNames.push(entry.getFileName())\n }\n\n return fileNames\n}\n", "'use strict'\n\nmodule.exports = validator\n\nfunction validator (opts = {}) {\n const {\n ERR_PATHS_MUST_BE_STRINGS = () => 'fast-redact - Paths must be (non-empty) strings',\n ERR_INVALID_PATH = (s) => `fast-redact \u2013 Invalid path (${s})`\n } = opts\n\n return function validate ({ paths }) {\n paths.forEach((s) => {\n if (typeof s !== 'string') {\n throw Error(ERR_PATHS_MUST_BE_STRINGS())\n }\n try {\n if (/\u3007/.test(s)) throw Error()\n const expr = (s[0] === '[' ? '' : '.') + s.replace(/^\\*/, '\u3007').replace(/\\.\\*/g, '.\u3007').replace(/\\[\\*\\]/g, '[\u3007]')\n if (/\\n|\\r|;/.test(expr)) throw Error()\n if (/\\/\\*/.test(expr)) throw Error()\n /* eslint-disable-next-line */\n Function(`\n 'use strict'\n const o = new Proxy({}, { get: () => o, set: () => { throw Error() } });\n const \u3007 = null;\n o${expr}\n if ([o${expr}].length !== 1) throw Error()`)()\n } catch (e) {\n throw Error(ERR_INVALID_PATH(s))\n }\n })\n }\n}\n", "'use strict'\n\nmodule.exports = /[^.[\\]]+|\\[((?:.)*?)\\]/g\n\n/*\nRegular expression explanation:\n\nAlt 1: /[^.[\\]]+/ - Match one or more characters that are *not* a dot (.)\n opening square bracket ([) or closing square bracket (])\n\nAlt 2: /\\[((?:.)*?)\\]/ - If the char IS dot or square bracket, then create a capture\n group (which will be capture group $1) that matches anything\n within square brackets. Expansion is lazy so it will\n stop matching as soon as the first closing bracket is met `]`\n (rather than continuing to match until the final closing bracket).\n*/\n", "'use strict'\n\nconst rx = require('./rx')\n\nmodule.exports = parse\n\nfunction parse ({ paths }) {\n const wildcards = []\n var wcLen = 0\n const secret = paths.reduce(function (o, strPath, ix) {\n var path = strPath.match(rx).map((p) => p.replace(/'|\"|`/g, ''))\n const leadingBracket = strPath[0] === '['\n path = path.map((p) => {\n if (p[0] === '[') return p.substr(1, p.length - 2)\n else return p\n })\n const star = path.indexOf('*')\n if (star > -1) {\n const before = path.slice(0, star)\n const beforeStr = before.join('.')\n const after = path.slice(star + 1, path.length)\n const nested = after.length > 0\n wcLen++\n wildcards.push({\n before,\n beforeStr,\n after,\n nested\n })\n } else {\n o[strPath] = {\n path: path,\n val: undefined,\n precensored: false,\n circle: '',\n escPath: JSON.stringify(strPath),\n leadingBracket: leadingBracket\n }\n }\n return o\n }, {})\n\n return { wildcards, wcLen, secret }\n}\n", "'use strict'\n\nconst rx = require('./rx')\n\nmodule.exports = redactor\n\nfunction redactor ({ secret, serialize, wcLen, strict, isCensorFct, censorFctTakesPath }, state) {\n /* eslint-disable-next-line */\n const redact = Function('o', `\n if (typeof o !== 'object' || o == null) {\n ${strictImpl(strict, serialize)}\n }\n const { censor, secret } = this\n const originalSecret = {}\n const secretKeys = Object.keys(secret)\n for (var i = 0; i < secretKeys.length; i++) {\n originalSecret[secretKeys[i]] = secret[secretKeys[i]]\n }\n\n ${redactTmpl(secret, isCensorFct, censorFctTakesPath)}\n this.compileRestore()\n ${dynamicRedactTmpl(wcLen > 0, isCensorFct, censorFctTakesPath)}\n this.secret = originalSecret\n ${resultTmpl(serialize)}\n `).bind(state)\n\n redact.state = state\n\n if (serialize === false) {\n redact.restore = (o) => state.restore(o)\n }\n\n return redact\n}\n\nfunction redactTmpl (secret, isCensorFct, censorFctTakesPath) {\n return Object.keys(secret).map((path) => {\n const { escPath, leadingBracket, path: arrPath } = secret[path]\n const skip = leadingBracket ? 1 : 0\n const delim = leadingBracket ? '' : '.'\n const hops = []\n var match\n while ((match = rx.exec(path)) !== null) {\n const [ , ix ] = match\n const { index, input } = match\n if (index > skip) hops.push(input.substring(0, index - (ix ? 0 : 1)))\n }\n var existence = hops.map((p) => `o${delim}${p}`).join(' && ')\n if (existence.length === 0) existence += `o${delim}${path} != null`\n else existence += ` && o${delim}${path} != null`\n\n const circularDetection = `\n switch (true) {\n ${hops.reverse().map((p) => `\n case o${delim}${p} === censor:\n secret[${escPath}].circle = ${JSON.stringify(p)}\n break\n `).join('\\n')}\n }\n `\n\n const censorArgs = censorFctTakesPath\n ? `val, ${JSON.stringify(arrPath)}`\n : `val`\n\n return `\n if (${existence}) {\n const val = o${delim}${path}\n if (val === censor) {\n secret[${escPath}].precensored = true\n } else {\n secret[${escPath}].val = val\n o${delim}${path} = ${isCensorFct ? `censor(${censorArgs})` : 'censor'}\n ${circularDetection}\n }\n }\n `\n }).join('\\n')\n}\n\nfunction dynamicRedactTmpl (hasWildcards, isCensorFct, censorFctTakesPath) {\n return hasWildcards === true ? `\n {\n const { wildcards, wcLen, groupRedact, nestedRedact } = this\n for (var i = 0; i < wcLen; i++) {\n const { before, beforeStr, after, nested } = wildcards[i]\n if (nested === true) {\n secret[beforeStr] = secret[beforeStr] || []\n nestedRedact(secret[beforeStr], o, before, after, censor, ${isCensorFct}, ${censorFctTakesPath})\n } else secret[beforeStr] = groupRedact(o, before, censor, ${isCensorFct}, ${censorFctTakesPath})\n }\n }\n ` : ''\n}\n\nfunction resultTmpl (serialize) {\n return serialize === false ? `return o` : `\n var s = this.serialize(o)\n this.restore(o)\n return s\n `\n}\n\nfunction strictImpl (strict, serialize) {\n return strict === true\n ? `throw Error('fast-redact: primitives cannot be redacted')`\n : serialize === false ? `return o` : `return this.serialize(o)`\n}\n", "'use strict'\n\nmodule.exports = {\n groupRedact,\n groupRestore,\n nestedRedact,\n nestedRestore\n}\n\nfunction groupRestore ({ keys, values, target }) {\n if (target == null || typeof target === 'string') return\n const length = keys.length\n for (var i = 0; i < length; i++) {\n const k = keys[i]\n target[k] = values[i]\n }\n}\n\nfunction groupRedact (o, path, censor, isCensorFct, censorFctTakesPath) {\n const target = get(o, path)\n if (target == null || typeof target === 'string') return { keys: null, values: null, target, flat: true }\n const keys = Object.keys(target)\n const keysLength = keys.length\n const pathLength = path.length\n const pathWithKey = censorFctTakesPath ? [...path] : undefined\n const values = new Array(keysLength)\n\n for (var i = 0; i < keysLength; i++) {\n const key = keys[i]\n values[i] = target[key]\n\n if (censorFctTakesPath) {\n pathWithKey[pathLength] = key\n target[key] = censor(target[key], pathWithKey)\n } else if (isCensorFct) {\n target[key] = censor(target[key])\n } else {\n target[key] = censor\n }\n }\n return { keys, values, target, flat: true }\n}\n\n/**\n * @param {RestoreInstruction[]} instructions a set of instructions for restoring values to objects\n */\nfunction nestedRestore (instructions) {\n for (let i = 0; i < instructions.length; i++) {\n const { target, path, value } = instructions[i]\n let current = target\n for (let i = path.length - 1; i > 0; i--) {\n current = current[path[i]]\n }\n current[path[0]] = value\n }\n}\n\nfunction nestedRedact (store, o, path, ns, censor, isCensorFct, censorFctTakesPath) {\n const target = get(o, path)\n if (target == null) return\n const keys = Object.keys(target)\n const keysLength = keys.length\n for (var i = 0; i < keysLength; i++) {\n const key = keys[i]\n specialSet(store, target, key, path, ns, censor, isCensorFct, censorFctTakesPath)\n }\n return store\n}\n\nfunction has (obj, prop) {\n return obj !== undefined && obj !== null\n ? ('hasOwn' in Object ? Object.hasOwn(obj, prop) : Object.prototype.hasOwnProperty.call(obj, prop))\n : false\n}\n\nfunction specialSet (store, o, k, path, afterPath, censor, isCensorFct, censorFctTakesPath) {\n const afterPathLen = afterPath.length\n const lastPathIndex = afterPathLen - 1\n const originalKey = k\n var i = -1\n var n\n var nv\n var ov\n var oov = null\n var wc = null\n var kIsWc\n var wcov\n var consecutive = false\n var level = 0\n // need to track depth of the `redactPath` tree\n var depth = 0\n var redactPathCurrent = tree()\n ov = n = o[k]\n if (typeof n !== 'object') return\n while (n != null && ++i < afterPathLen) {\n depth += 1\n k = afterPath[i]\n oov = ov\n if (k !== '*' && !wc && !(typeof n === 'object' && k in n)) {\n break\n }\n if (k === '*') {\n if (wc === '*') {\n consecutive = true\n }\n wc = k\n if (i !== lastPathIndex) {\n continue\n }\n }\n if (wc) {\n const wcKeys = Object.keys(n)\n for (var j = 0; j < wcKeys.length; j++) {\n const wck = wcKeys[j]\n wcov = n[wck]\n kIsWc = k === '*'\n if (consecutive) {\n redactPathCurrent = node(redactPathCurrent, wck, depth)\n level = i\n ov = iterateNthLevel(wcov, level - 1, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, o[originalKey], depth + 1)\n } else {\n if (kIsWc || (typeof wcov === 'object' && wcov !== null && k in wcov)) {\n if (kIsWc) {\n ov = wcov\n } else {\n ov = wcov[k]\n }\n nv = (i !== lastPathIndex)\n ? ov\n : (isCensorFct\n ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))\n : censor)\n if (kIsWc) {\n const rv = restoreInstr(node(redactPathCurrent, wck, depth), ov, o[originalKey])\n store.push(rv)\n n[wck] = nv\n } else {\n if (wcov[k] === nv) {\n // pass\n } else if ((nv === undefined && censor !== undefined) || (has(wcov, k) && nv === ov)) {\n redactPathCurrent = node(redactPathCurrent, wck, depth)\n } else {\n redactPathCurrent = node(redactPathCurrent, wck, depth)\n const rv = restoreInstr(node(redactPathCurrent, k, depth + 1), ov, o[originalKey])\n store.push(rv)\n wcov[k] = nv\n }\n }\n }\n }\n }\n wc = null\n } else {\n ov = n[k]\n redactPathCurrent = node(redactPathCurrent, k, depth)\n nv = (i !== lastPathIndex)\n ? ov\n : (isCensorFct\n ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))\n : censor)\n if ((has(n, k) && nv === ov) || (nv === undefined && censor !== undefined)) {\n // pass\n } else {\n const rv = restoreInstr(redactPathCurrent, ov, o[originalKey])\n store.push(rv)\n n[k] = nv\n }\n n = n[k]\n }\n if (typeof n !== 'object') break\n // prevent circular structure, see https://github.com/pinojs/pino/issues/1513\n if (ov === oov || typeof ov === 'undefined') {\n // pass\n }\n }\n}\n\nfunction get (o, p) {\n var i = -1\n var l = p.length\n var n = o\n while (n != null && ++i < l) {\n n = n[p[i]]\n }\n return n\n}\n\nfunction iterateNthLevel (wcov, level, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, parent, depth) {\n if (level === 0) {\n if (kIsWc || (typeof wcov === 'object' && wcov !== null && k in wcov)) {\n if (kIsWc) {\n ov = wcov\n } else {\n ov = wcov[k]\n }\n nv = (i !== lastPathIndex)\n ? ov\n : (isCensorFct\n ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))\n : censor)\n if (kIsWc) {\n const rv = restoreInstr(redactPathCurrent, ov, parent)\n store.push(rv)\n n[wck] = nv\n } else {\n if (wcov[k] === nv) {\n // pass\n } else if ((nv === undefined && censor !== undefined) || (has(wcov, k) && nv === ov)) {\n // pass\n } else {\n const rv = restoreInstr(node(redactPathCurrent, k, depth + 1), ov, parent)\n store.push(rv)\n wcov[k] = nv\n }\n }\n }\n }\n for (const key in wcov) {\n if (typeof wcov[key] === 'object') {\n redactPathCurrent = node(redactPathCurrent, key, depth)\n iterateNthLevel(wcov[key], level - 1, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, parent, depth + 1)\n }\n }\n}\n\n/**\n * @typedef {object} TreeNode\n * @prop {TreeNode} [parent] reference to the parent of this node in the tree, or `null` if there is no parent\n * @prop {string} key the key that this node represents (key here being part of the path being redacted\n * @prop {TreeNode[]} children the child nodes of this node\n * @prop {number} depth the depth of this node in the tree\n */\n\n/**\n * instantiate a new, empty tree\n * @returns {TreeNode}\n */\nfunction tree () {\n return { parent: null, key: null, children: [], depth: 0 }\n}\n\n/**\n * creates a new node in the tree, attaching it as a child of the provided parent node\n * if the specified depth matches the parent depth, adds the new node as a _sibling_ of the parent instead\n * @param {TreeNode} parent the parent node to add a new node to (if the parent depth matches the provided `depth` value, will instead add as a sibling of this\n * @param {string} key the key that the new node represents (key here being part of the path being redacted)\n * @param {number} depth the depth of the new node in the tree - used to determing whether to add the new node as a child or sibling of the provided `parent` node\n * @returns {TreeNode} a reference to the newly created node in the tree\n */\nfunction node (parent, key, depth) {\n if (parent.depth === depth) {\n return node(parent.parent, key, depth)\n }\n\n var child = {\n parent,\n key,\n depth,\n children: []\n }\n\n parent.children.push(child)\n\n return child\n}\n\n/**\n * @typedef {object} RestoreInstruction\n * @prop {string[]} path a reverse-order path that can be used to find the correct insertion point to restore a `value` for the given `parent` object\n * @prop {*} value the value to restore\n * @prop {object} target the object to restore the `value` in\n */\n\n/**\n * create a restore instruction for the given redactPath node\n * generates a path in reverse order by walking up the redactPath tree\n * @param {TreeNode} node a tree node that should be at the bottom of the redact path (i.e. have no children) - this will be used to walk up the redact path tree to construct the path needed to restore\n * @param {*} value the value to restore\n * @param {object} target a reference to the parent object to apply the restore instruction to\n * @returns {RestoreInstruction} an instruction used to restore a nested value for a specific object\n */\nfunction restoreInstr (node, value, target) {\n let current = node\n const path = []\n do {\n path.push(current.key)\n current = current.parent\n } while (current.parent != null)\n\n return { path, value, target }\n}\n", "'use strict'\n\nconst { groupRestore, nestedRestore } = require('./modifiers')\n\nmodule.exports = restorer\n\nfunction restorer () {\n return function compileRestore () {\n if (this.restore) {\n this.restore.state.secret = this.secret\n return\n }\n const { secret, wcLen } = this\n const paths = Object.keys(secret)\n const resetters = resetTmpl(secret, paths)\n const hasWildcards = wcLen > 0\n const state = hasWildcards ? { secret, groupRestore, nestedRestore } : { secret }\n /* eslint-disable-next-line */\n this.restore = Function(\n 'o',\n restoreTmpl(resetters, paths, hasWildcards)\n ).bind(state)\n this.restore.state = state\n }\n}\n\n/**\n * Mutates the original object to be censored by restoring its original values\n * prior to censoring.\n *\n * @param {object} secret Compiled object describing which target fields should\n * be censored and the field states.\n * @param {string[]} paths The list of paths to censor as provided at\n * initialization time.\n *\n * @returns {string} String of JavaScript to be used by `Function()`. The\n * string compiles to the function that does the work in the description.\n */\nfunction resetTmpl (secret, paths) {\n return paths.map((path) => {\n const { circle, escPath, leadingBracket } = secret[path]\n const delim = leadingBracket ? '' : '.'\n const reset = circle\n ? `o.${circle} = secret[${escPath}].val`\n : `o${delim}${path} = secret[${escPath}].val`\n const clear = `secret[${escPath}].val = undefined`\n return `\n if (secret[${escPath}].val !== undefined) {\n try { ${reset} } catch (e) {}\n ${clear}\n }\n `\n }).join('')\n}\n\n/**\n * Creates the body of the restore function\n *\n * Restoration of the redacted object happens\n * backwards, in reverse order of redactions,\n * so that repeated redactions on the same object\n * property can be eventually rolled back to the\n * original value.\n *\n * This way dynamic redactions are restored first,\n * starting from the last one working backwards and\n * followed by the static ones.\n *\n * @returns {string} the body of the restore function\n */\nfunction restoreTmpl (resetters, paths, hasWildcards) {\n const dynamicReset = hasWildcards === true ? `\n const keys = Object.keys(secret)\n const len = keys.length\n for (var i = len - 1; i >= ${paths.length}; i--) {\n const k = keys[i]\n const o = secret[k]\n if (o) {\n if (o.flat === true) this.groupRestore(o)\n else this.nestedRestore(o)\n secret[k] = null\n }\n }\n ` : ''\n\n return `\n const secret = this.secret\n ${dynamicReset}\n ${resetters}\n return o\n `\n}\n", "'use strict'\n\nmodule.exports = state\n\nfunction state (o) {\n const {\n secret,\n censor,\n compileRestore,\n serialize,\n groupRedact,\n nestedRedact,\n wildcards,\n wcLen\n } = o\n const builder = [{ secret, censor, compileRestore }]\n if (serialize !== false) builder.push({ serialize })\n if (wcLen > 0) builder.push({ groupRedact, nestedRedact, wildcards, wcLen })\n return Object.assign(...builder)\n}\n", "'use strict'\n\nconst validator = require('./lib/validator')\nconst parse = require('./lib/parse')\nconst redactor = require('./lib/redactor')\nconst restorer = require('./lib/restorer')\nconst { groupRedact, nestedRedact } = require('./lib/modifiers')\nconst state = require('./lib/state')\nconst rx = require('./lib/rx')\nconst validate = validator()\nconst noop = (o) => o\nnoop.restore = noop\n\nconst DEFAULT_CENSOR = '[REDACTED]'\nfastRedact.rx = rx\nfastRedact.validator = validator\n\nmodule.exports = fastRedact\n\nfunction fastRedact (opts = {}) {\n const paths = Array.from(new Set(opts.paths || []))\n const serialize = 'serialize' in opts ? (\n opts.serialize === false ? opts.serialize\n : (typeof opts.serialize === 'function' ? opts.serialize : JSON.stringify)\n ) : JSON.stringify\n const remove = opts.remove\n if (remove === true && serialize !== JSON.stringify) {\n throw Error('fast-redact \u2013 remove option may only be set when serializer is JSON.stringify')\n }\n const censor = remove === true\n ? undefined\n : 'censor' in opts ? opts.censor : DEFAULT_CENSOR\n\n const isCensorFct = typeof censor === 'function'\n const censorFctTakesPath = isCensorFct && censor.length > 1\n\n if (paths.length === 0) return serialize || noop\n\n validate({ paths, serialize, censor })\n\n const { wildcards, wcLen, secret } = parse({ paths, censor })\n\n const compileRestore = restorer()\n const strict = 'strict' in opts ? opts.strict : true\n\n return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({\n secret,\n censor,\n compileRestore,\n serialize,\n groupRedact,\n nestedRedact,\n wildcards,\n wcLen\n }))\n}\n", "'use strict'\n\nconst setLevelSym = Symbol('pino.setLevel')\nconst getLevelSym = Symbol('pino.getLevel')\nconst levelValSym = Symbol('pino.levelVal')\nconst levelCompSym = Symbol('pino.levelComp')\nconst useLevelLabelsSym = Symbol('pino.useLevelLabels')\nconst useOnlyCustomLevelsSym = Symbol('pino.useOnlyCustomLevels')\nconst mixinSym = Symbol('pino.mixin')\n\nconst lsCacheSym = Symbol('pino.lsCache')\nconst chindingsSym = Symbol('pino.chindings')\n\nconst asJsonSym = Symbol('pino.asJson')\nconst writeSym = Symbol('pino.write')\nconst redactFmtSym = Symbol('pino.redactFmt')\n\nconst timeSym = Symbol('pino.time')\nconst timeSliceIndexSym = Symbol('pino.timeSliceIndex')\nconst streamSym = Symbol('pino.stream')\nconst stringifySym = Symbol('pino.stringify')\nconst stringifySafeSym = Symbol('pino.stringifySafe')\nconst stringifiersSym = Symbol('pino.stringifiers')\nconst endSym = Symbol('pino.end')\nconst formatOptsSym = Symbol('pino.formatOpts')\nconst messageKeySym = Symbol('pino.messageKey')\nconst errorKeySym = Symbol('pino.errorKey')\nconst nestedKeySym = Symbol('pino.nestedKey')\nconst nestedKeyStrSym = Symbol('pino.nestedKeyStr')\nconst mixinMergeStrategySym = Symbol('pino.mixinMergeStrategy')\nconst msgPrefixSym = Symbol('pino.msgPrefix')\n\nconst wildcardFirstSym = Symbol('pino.wildcardFirst')\n\n// public symbols, no need to use the same pino\n// version for these\nconst serializersSym = Symbol.for('pino.serializers')\nconst formattersSym = Symbol.for('pino.formatters')\nconst hooksSym = Symbol.for('pino.hooks')\nconst needsMetadataGsym = Symbol.for('pino.metadata')\n\nmodule.exports = {\n setLevelSym,\n getLevelSym,\n levelValSym,\n levelCompSym,\n useLevelLabelsSym,\n mixinSym,\n lsCacheSym,\n chindingsSym,\n asJsonSym,\n writeSym,\n serializersSym,\n redactFmtSym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n stringifySym,\n stringifySafeSym,\n stringifiersSym,\n endSym,\n formatOptsSym,\n messageKeySym,\n errorKeySym,\n nestedKeySym,\n wildcardFirstSym,\n needsMetadataGsym,\n useOnlyCustomLevelsSym,\n formattersSym,\n hooksSym,\n nestedKeyStrSym,\n mixinMergeStrategySym,\n msgPrefixSym\n}\n", "'use strict'\n\nconst fastRedact = require('fast-redact')\nconst { redactFmtSym, wildcardFirstSym } = require('./symbols')\nconst { rx, validator } = fastRedact\n\nconst validate = validator({\n ERR_PATHS_MUST_BE_STRINGS: () => 'pino \u2013 redacted paths must be strings',\n ERR_INVALID_PATH: (s) => `pino \u2013 redact paths array contains an invalid path (${s})`\n})\n\nconst CENSOR = '[Redacted]'\nconst strict = false // TODO should this be configurable?\n\nfunction redaction (opts, serialize) {\n const { paths, censor } = handle(opts)\n\n const shape = paths.reduce((o, str) => {\n rx.lastIndex = 0\n const first = rx.exec(str)\n const next = rx.exec(str)\n\n // ns is the top-level path segment, brackets + quoting removed.\n let ns = first[1] !== undefined\n ? first[1].replace(/^(?:\"|'|`)(.*)(?:\"|'|`)$/, '$1')\n : first[0]\n\n if (ns === '*') {\n ns = wildcardFirstSym\n }\n\n // top level key:\n if (next === null) {\n o[ns] = null\n return o\n }\n\n // path with at least two segments:\n // if ns is already redacted at the top level, ignore lower level redactions\n if (o[ns] === null) {\n return o\n }\n\n const { index } = next\n const nextPath = `${str.substr(index, str.length - 1)}`\n\n o[ns] = o[ns] || []\n\n // shape is a mix of paths beginning with literal values and wildcard\n // paths [ \"a.b.c\", \"*.b.z\" ] should reduce to a shape of\n // { \"a\": [ \"b.c\", \"b.z\" ], *: [ \"b.z\" ] }\n // note: \"b.z\" is in both \"a\" and * arrays because \"a\" matches the wildcard.\n // (* entry has wildcardFirstSym as key)\n if (ns !== wildcardFirstSym && o[ns].length === 0) {\n // first time ns's get all '*' redactions so far\n o[ns].push(...(o[wildcardFirstSym] || []))\n }\n\n if (ns === wildcardFirstSym) {\n // new * path gets added to all previously registered literal ns's.\n Object.keys(o).forEach(function (k) {\n if (o[k]) {\n o[k].push(nextPath)\n }\n })\n }\n\n o[ns].push(nextPath)\n return o\n }, {})\n\n // the redactor assigned to the format symbol key\n // provides top level redaction for instances where\n // an object is interpolated into the msg string\n const result = {\n [redactFmtSym]: fastRedact({ paths, censor, serialize, strict })\n }\n\n const topCensor = (...args) => {\n return typeof censor === 'function' ? serialize(censor(...args)) : serialize(censor)\n }\n\n return [...Object.keys(shape), ...Object.getOwnPropertySymbols(shape)].reduce((o, k) => {\n // top level key:\n if (shape[k] === null) {\n o[k] = (value) => topCensor(value, [k])\n } else {\n const wrappedCensor = typeof censor === 'function'\n ? (value, path) => {\n return censor(value, [k, ...path])\n }\n : censor\n o[k] = fastRedact({\n paths: shape[k],\n censor: wrappedCensor,\n serialize,\n strict\n })\n }\n return o\n }, result)\n}\n\nfunction handle (opts) {\n if (Array.isArray(opts)) {\n opts = { paths: opts, censor: CENSOR }\n validate(opts)\n return opts\n }\n let { paths, censor = CENSOR, remove } = opts\n if (Array.isArray(paths) === false) { throw Error('pino \u2013 redact must contain an array of strings') }\n if (remove === true) censor = undefined\n validate({ paths, censor })\n\n return { paths, censor }\n}\n\nmodule.exports = redaction\n", "'use strict'\n\nconst nullTime = () => ''\n\nconst epochTime = () => `,\"time\":${Date.now()}`\n\nconst unixTime = () => `,\"time\":${Math.round(Date.now() / 1000.0)}`\n\nconst isoTime = () => `,\"time\":\"${new Date(Date.now()).toISOString()}\"` // using Date.now() for testability\n\nmodule.exports = { nullTime, epochTime, unixTime, isoTime }\n", "'use strict'\nfunction tryStringify (o) {\n try { return JSON.stringify(o) } catch(e) { return '\"[Circular]\"' }\n}\n\nmodule.exports = format\n\nfunction format(f, args, opts) {\n var ss = (opts && opts.stringify) || tryStringify\n var offset = 1\n if (typeof f === 'object' && f !== null) {\n var len = args.length + offset\n if (len === 1) return f\n var objects = new Array(len)\n objects[0] = ss(f)\n for (var index = 1; index < len; index++) {\n objects[index] = ss(args[index])\n }\n return objects.join(' ')\n }\n if (typeof f !== 'string') {\n return f\n }\n var argLen = args.length\n if (argLen === 0) return f\n var str = ''\n var a = 1 - offset\n var lastPos = -1\n var flen = (f && f.length) || 0\n for (var i = 0; i < flen;) {\n if (f.charCodeAt(i) === 37 && i + 1 < flen) {\n lastPos = lastPos > -1 ? lastPos : 0\n switch (f.charCodeAt(i + 1)) {\n case 100: // 'd'\n case 102: // 'f'\n if (a >= argLen)\n break\n if (args[a] == null) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += Number(args[a])\n lastPos = i + 2\n i++\n break\n case 105: // 'i'\n if (a >= argLen)\n break\n if (args[a] == null) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += Math.floor(Number(args[a]))\n lastPos = i + 2\n i++\n break\n case 79: // 'O'\n case 111: // 'o'\n case 106: // 'j'\n if (a >= argLen)\n break\n if (args[a] === undefined) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n var type = typeof args[a]\n if (type === 'string') {\n str += '\\'' + args[a] + '\\''\n lastPos = i + 2\n i++\n break\n }\n if (type === 'function') {\n str += args[a].name || ''\n lastPos = i + 2\n i++\n break\n }\n str += ss(args[a])\n lastPos = i + 2\n i++\n break\n case 115: // 's'\n if (a >= argLen)\n break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += String(args[a])\n lastPos = i + 2\n i++\n break\n case 37: // '%'\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += '%'\n lastPos = i + 2\n i++\n a--\n break\n }\n ++a\n }\n ++i\n }\n if (lastPos === -1)\n return f\n else if (lastPos < flen) {\n str += f.slice(lastPos)\n }\n\n return str\n}\n", "'use strict'\n\n/* global SharedArrayBuffer, Atomics */\n\nif (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') {\n const nil = new Int32Array(new SharedArrayBuffer(4))\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n\n Atomics.wait(nil, 0, 0, Number(ms))\n }\n module.exports = sleep\n} else {\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n const target = Date.now() + Number(ms)\n while (target > Date.now()){}\n }\n\n module.exports = sleep\n\n}\n", "'use strict'\n\nconst fs = require('fs')\nconst EventEmitter = require('events')\nconst inherits = require('util').inherits\nconst path = require('path')\nconst sleep = require('atomic-sleep')\nconst assert = require('assert')\n\nconst BUSY_WRITE_TIMEOUT = 100\nconst kEmptyBuffer = Buffer.allocUnsafe(0)\n\n// 16 KB. Don't write more than docker buffer size.\n// https://github.com/moby/moby/blob/513ec73831269947d38a644c278ce3cac36783b2/daemon/logger/copier.go#L13\nconst MAX_WRITE = 16 * 1024\n\nconst kContentModeBuffer = 'buffer'\nconst kContentModeUtf8 = 'utf8'\n\nconst [major, minor] = (process.versions.node || '0.0').split('.').map(Number)\nconst kCopyBuffer = major >= 22 && minor >= 7\n\nfunction openFile (file, sonic) {\n sonic._opening = true\n sonic._writing = true\n sonic._asyncDrainScheduled = false\n\n // NOTE: 'error' and 'ready' events emitted below only relevant when sonic.sync===false\n // for sync mode, there is no way to add a listener that will receive these\n\n function fileOpened (err, fd) {\n if (err) {\n sonic._reopening = false\n sonic._writing = false\n sonic._opening = false\n\n if (sonic.sync) {\n process.nextTick(() => {\n if (sonic.listenerCount('error') > 0) {\n sonic.emit('error', err)\n }\n })\n } else {\n sonic.emit('error', err)\n }\n return\n }\n\n const reopening = sonic._reopening\n\n sonic.fd = fd\n sonic.file = file\n sonic._reopening = false\n sonic._opening = false\n sonic._writing = false\n\n if (sonic.sync) {\n process.nextTick(() => sonic.emit('ready'))\n } else {\n sonic.emit('ready')\n }\n\n if (sonic.destroyed) {\n return\n }\n\n // start\n if ((!sonic._writing && sonic._len > sonic.minLength) || sonic._flushPending) {\n sonic._actualWrite()\n } else if (reopening) {\n process.nextTick(() => sonic.emit('drain'))\n }\n }\n\n const flags = sonic.append ? 'a' : 'w'\n const mode = sonic.mode\n\n if (sonic.sync) {\n try {\n if (sonic.mkdir) fs.mkdirSync(path.dirname(file), { recursive: true })\n const fd = fs.openSync(file, flags, mode)\n fileOpened(null, fd)\n } catch (err) {\n fileOpened(err)\n throw err\n }\n } else if (sonic.mkdir) {\n fs.mkdir(path.dirname(file), { recursive: true }, (err) => {\n if (err) return fileOpened(err)\n fs.open(file, flags, mode, fileOpened)\n })\n } else {\n fs.open(file, flags, mode, fileOpened)\n }\n}\n\nfunction SonicBoom (opts) {\n if (!(this instanceof SonicBoom)) {\n return new SonicBoom(opts)\n }\n\n let { fd, dest, minLength, maxLength, maxWrite, periodicFlush, sync, append = true, mkdir, retryEAGAIN, fsync, contentMode, mode } = opts || {}\n\n fd = fd || dest\n\n this._len = 0\n this.fd = -1\n this._bufs = []\n this._lens = []\n this._writing = false\n this._ending = false\n this._reopening = false\n this._asyncDrainScheduled = false\n this._flushPending = false\n this._hwm = Math.max(minLength || 0, 16387)\n this.file = null\n this.destroyed = false\n this.minLength = minLength || 0\n this.maxLength = maxLength || 0\n this.maxWrite = maxWrite || MAX_WRITE\n this._periodicFlush = periodicFlush || 0\n this._periodicFlushTimer = undefined\n this.sync = sync || false\n this.writable = true\n this._fsync = fsync || false\n this.append = append || false\n this.mode = mode\n this.retryEAGAIN = retryEAGAIN || (() => true)\n this.mkdir = mkdir || false\n\n let fsWriteSync\n let fsWrite\n if (contentMode === kContentModeBuffer) {\n this._writingBuf = kEmptyBuffer\n this.write = writeBuffer\n this.flush = flushBuffer\n this.flushSync = flushBufferSync\n this._actualWrite = actualWriteBuffer\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf)\n fsWrite = () => fs.write(this.fd, this._writingBuf, this.release)\n } else if (contentMode === undefined || contentMode === kContentModeUtf8) {\n this._writingBuf = ''\n this.write = write\n this.flush = flush\n this.flushSync = flushSync\n this._actualWrite = actualWrite\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf, 'utf8')\n fsWrite = () => fs.write(this.fd, this._writingBuf, 'utf8', this.release)\n } else {\n throw new Error(`SonicBoom supports \"${kContentModeUtf8}\" and \"${kContentModeBuffer}\", but passed ${contentMode}`)\n }\n\n if (typeof fd === 'number') {\n this.fd = fd\n process.nextTick(() => this.emit('ready'))\n } else if (typeof fd === 'string') {\n openFile(fd, this)\n } else {\n throw new Error('SonicBoom supports only file descriptors and files')\n }\n if (this.minLength >= this.maxWrite) {\n throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`)\n }\n\n this.release = (err, n) => {\n if (err) {\n if ((err.code === 'EAGAIN' || err.code === 'EBUSY') && this.retryEAGAIN(err, this._writingBuf.length, this._len - this._writingBuf.length)) {\n if (this.sync) {\n // This error code should not happen in sync mode, because it is\n // not using the underlining operating system asynchronous functions.\n // However it happens, and so we handle it.\n // Ref: https://github.com/pinojs/pino/issues/783\n try {\n sleep(BUSY_WRITE_TIMEOUT)\n this.release(undefined, 0)\n } catch (err) {\n this.release(err)\n }\n } else {\n // Let's give the destination some time to process the chunk.\n setTimeout(fsWrite, BUSY_WRITE_TIMEOUT)\n }\n } else {\n this._writing = false\n\n this.emit('error', err)\n }\n return\n }\n\n this.emit('write', n)\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n\n if (this._writingBuf.length) {\n if (!this.sync) {\n fsWrite()\n return\n }\n\n try {\n do {\n const n = fsWriteSync()\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n } while (this._writingBuf.length)\n } catch (err) {\n this.release(err)\n return\n }\n }\n\n if (this._fsync) {\n fs.fsyncSync(this.fd)\n }\n\n const len = this._len\n if (this._reopening) {\n this._writing = false\n this._reopening = false\n this.reopen()\n } else if (len > this.minLength) {\n this._actualWrite()\n } else if (this._ending) {\n if (len > 0) {\n this._actualWrite()\n } else {\n this._writing = false\n actualClose(this)\n }\n } else {\n this._writing = false\n if (this.sync) {\n if (!this._asyncDrainScheduled) {\n this._asyncDrainScheduled = true\n process.nextTick(emitDrain, this)\n }\n } else {\n this.emit('drain')\n }\n }\n }\n\n this.on('newListener', function (name) {\n if (name === 'drain') {\n this._asyncDrainScheduled = false\n }\n })\n\n if (this._periodicFlush !== 0) {\n this._periodicFlushTimer = setInterval(() => this.flush(null), this._periodicFlush)\n this._periodicFlushTimer.unref()\n }\n}\n\n/**\n * Release the writingBuf after fs.write n bytes data\n * @param {string | Buffer} writingBuf - currently writing buffer, usually be instance._writingBuf.\n * @param {number} len - currently buffer length, usually be instance._len.\n * @param {number} n - number of bytes fs already written\n * @returns {{writingBuf: string | Buffer, len: number}} released writingBuf and length\n */\nfunction releaseWritingBuf (writingBuf, len, n) {\n // if Buffer.byteLength is equal to n, that means writingBuf contains no multi-byte character\n if (typeof writingBuf === 'string' && Buffer.byteLength(writingBuf) !== n) {\n // Since the fs.write callback parameter `n` means how many bytes the passed of string\n // We calculate the original string length for avoiding the multi-byte character issue\n n = Buffer.from(writingBuf).subarray(0, n).toString().length\n }\n len = Math.max(len - n, 0)\n writingBuf = writingBuf.slice(n)\n return { writingBuf, len }\n}\n\nfunction emitDrain (sonic) {\n const hasListeners = sonic.listenerCount('drain') > 0\n if (!hasListeners) return\n sonic._asyncDrainScheduled = false\n sonic.emit('drain')\n}\n\ninherits(SonicBoom, EventEmitter)\n\nfunction mergeBuf (bufs, len) {\n if (bufs.length === 0) {\n return kEmptyBuffer\n }\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return Buffer.concat(bufs, len)\n}\n\nfunction write (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n bufs[bufs.length - 1].length + data.length > this.maxWrite\n ) {\n bufs.push('' + data)\n } else {\n bufs[bufs.length - 1] += data\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction writeBuffer (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n const lens = this._lens\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n lens[lens.length - 1] + data.length > this.maxWrite\n ) {\n bufs.push([data])\n lens.push(data.length)\n } else {\n bufs[bufs.length - 1].push(data)\n lens[lens.length - 1] += data.length\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction callFlushCallbackOnDrain (cb) {\n this._flushPending = true\n const onDrain = () => {\n // only if _fsync is false to avoid double fsync\n if (!this._fsync) {\n try {\n fs.fsync(this.fd, (err) => {\n this._flushPending = false\n cb(err)\n })\n } catch (err) {\n cb(err)\n }\n } else {\n this._flushPending = false\n cb()\n }\n this.off('error', onError)\n }\n const onError = (err) => {\n this._flushPending = false\n cb(err)\n this.off('drain', onDrain)\n }\n\n this.once('drain', onDrain)\n this.once('error', onError)\n}\n\nfunction flush (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push('')\n }\n\n this._actualWrite()\n}\n\nfunction flushBuffer (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push([])\n this._lens.push(0)\n }\n\n this._actualWrite()\n}\n\nSonicBoom.prototype.reopen = function (file) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.reopen(file)\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n if (!this.file) {\n throw new Error('Unable to reopen a file descriptor, you must pass a file to SonicBoom')\n }\n\n if (file) {\n this.file = file\n }\n this._reopening = true\n\n if (this._writing) {\n return\n }\n\n const fd = this.fd\n this.once('ready', () => {\n if (fd !== this.fd) {\n fs.close(fd, (err) => {\n if (err) {\n return this.emit('error', err)\n }\n })\n }\n })\n\n openFile(this.file, this)\n}\n\nSonicBoom.prototype.end = function () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.end()\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n this._ending = true\n\n if (this._writing) {\n return\n }\n\n if (this._len > 0 && this.fd >= 0) {\n this._actualWrite()\n } else {\n actualClose(this)\n }\n}\n\nfunction flushSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift(this._writingBuf)\n this._writingBuf = ''\n }\n\n let buf = ''\n while (this._bufs.length || buf) {\n if (buf.length <= 0) {\n buf = this._bufs[0]\n }\n try {\n const n = fs.writeSync(this.fd, buf, 'utf8')\n const releasedBufObj = releaseWritingBuf(buf, this._len, n)\n buf = releasedBufObj.writingBuf\n this._len = releasedBufObj.len\n if (buf.length <= 0) {\n this._bufs.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n\n try {\n fs.fsyncSync(this.fd)\n } catch {\n // Skip the error. The fd might not support fsync.\n }\n}\n\nfunction flushBufferSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift([this._writingBuf])\n this._writingBuf = kEmptyBuffer\n }\n\n let buf = kEmptyBuffer\n while (this._bufs.length || buf.length) {\n if (buf.length <= 0) {\n buf = mergeBuf(this._bufs[0], this._lens[0])\n }\n try {\n const n = fs.writeSync(this.fd, buf)\n buf = buf.subarray(n)\n this._len = Math.max(this._len - n, 0)\n if (buf.length <= 0) {\n this._bufs.shift()\n this._lens.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n}\n\nSonicBoom.prototype.destroy = function () {\n if (this.destroyed) {\n return\n }\n actualClose(this)\n}\n\nfunction actualWrite () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf || this._bufs.shift() || ''\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf, 'utf8')\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n fs.write(this.fd, this._writingBuf, 'utf8', release)\n }\n}\n\nfunction actualWriteBuffer () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift())\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf)\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n // fs.write will need to copy string to buffer anyway so\n // we do it here to avoid the overhead of calculating the buffer size\n // in releaseWritingBuf.\n if (kCopyBuffer) {\n this._writingBuf = Buffer.from(this._writingBuf)\n }\n fs.write(this.fd, this._writingBuf, release)\n }\n}\n\nfunction actualClose (sonic) {\n if (sonic.fd === -1) {\n sonic.once('ready', actualClose.bind(null, sonic))\n return\n }\n\n if (sonic._periodicFlushTimer !== undefined) {\n clearInterval(sonic._periodicFlushTimer)\n }\n\n sonic.destroyed = true\n sonic._bufs = []\n sonic._lens = []\n\n assert(typeof sonic.fd === 'number', `sonic.fd must be a number, got ${typeof sonic.fd}`)\n try {\n fs.fsync(sonic.fd, closeWrapped)\n } catch {\n }\n\n function closeWrapped () {\n // We skip errors in fsync\n\n if (sonic.fd !== 1 && sonic.fd !== 2) {\n fs.close(sonic.fd, done)\n } else {\n done()\n }\n }\n\n function done (err) {\n if (err) {\n sonic.emit('error', err)\n return\n }\n\n if (sonic._ending && !sonic._writing) {\n sonic.emit('finish')\n }\n sonic.emit('close')\n }\n}\n\n/**\n * These export configurations enable JS and TS developers\n * to consumer SonicBoom in whatever way best suits their needs.\n * Some examples of supported import syntax includes:\n * - `const SonicBoom = require('SonicBoom')`\n * - `const { SonicBoom } = require('SonicBoom')`\n * - `import * as SonicBoom from 'SonicBoom'`\n * - `import { SonicBoom } from 'SonicBoom'`\n * - `import SonicBoom from 'SonicBoom'`\n */\nSonicBoom.SonicBoom = SonicBoom\nSonicBoom.default = SonicBoom\nmodule.exports = SonicBoom\n", "'use strict'\n\nconst refs = {\n exit: [],\n beforeExit: []\n}\nconst functions = {\n exit: onExit,\n beforeExit: onBeforeExit\n}\n\nlet registry\n\nfunction ensureRegistry () {\n if (registry === undefined) {\n registry = new FinalizationRegistry(clear)\n }\n}\n\nfunction install (event) {\n if (refs[event].length > 0) {\n return\n }\n\n process.on(event, functions[event])\n}\n\nfunction uninstall (event) {\n if (refs[event].length > 0) {\n return\n }\n process.removeListener(event, functions[event])\n if (refs.exit.length === 0 && refs.beforeExit.length === 0) {\n registry = undefined\n }\n}\n\nfunction onExit () {\n callRefs('exit')\n}\n\nfunction onBeforeExit () {\n callRefs('beforeExit')\n}\n\nfunction callRefs (event) {\n for (const ref of refs[event]) {\n const obj = ref.deref()\n const fn = ref.fn\n\n // This should always happen, however GC is\n // undeterministic so it might not happen.\n /* istanbul ignore else */\n if (obj !== undefined) {\n fn(obj, event)\n }\n }\n refs[event] = []\n}\n\nfunction clear (ref) {\n for (const event of ['exit', 'beforeExit']) {\n const index = refs[event].indexOf(ref)\n refs[event].splice(index, index + 1)\n uninstall(event)\n }\n}\n\nfunction _register (event, obj, fn) {\n if (obj === undefined) {\n throw new Error('the object can\\'t be undefined')\n }\n install(event)\n const ref = new WeakRef(obj)\n ref.fn = fn\n\n ensureRegistry()\n registry.register(obj, ref)\n refs[event].push(ref)\n}\n\nfunction register (obj, fn) {\n _register('exit', obj, fn)\n}\n\nfunction registerBeforeExit (obj, fn) {\n _register('beforeExit', obj, fn)\n}\n\nfunction unregister (obj) {\n if (registry === undefined) {\n return\n }\n registry.unregister(obj)\n for (const event of ['exit', 'beforeExit']) {\n refs[event] = refs[event].filter((ref) => {\n const _obj = ref.deref()\n return _obj && _obj !== obj\n })\n uninstall(event)\n }\n}\n\nmodule.exports = {\n register,\n registerBeforeExit,\n unregister\n}\n", "{\n \"name\": \"thread-stream\",\n \"version\": \"3.1.0\",\n \"description\": \"A streaming way to send data to a Node.js Worker Thread\",\n \"main\": \"index.js\",\n \"types\": \"index.d.ts\",\n \"dependencies\": {\n \"real-require\": \"^0.2.0\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^20.1.0\",\n \"@types/tap\": \"^15.0.0\",\n \"@yao-pkg/pkg\": \"^5.11.5\",\n \"desm\": \"^1.3.0\",\n \"fastbench\": \"^1.0.1\",\n \"husky\": \"^9.0.6\",\n \"pino-elasticsearch\": \"^8.0.0\",\n \"sonic-boom\": \"^4.0.1\",\n \"standard\": \"^17.0.0\",\n \"tap\": \"^16.2.0\",\n \"ts-node\": \"^10.8.0\",\n \"typescript\": \"^5.3.2\",\n \"why-is-node-running\": \"^2.2.2\"\n },\n \"scripts\": {\n \"build\": \"tsc --noEmit\",\n \"test\": \"standard && npm run build && npm run transpile && tap \\\"test/**/*.test.*js\\\" && tap --ts test/*.test.*ts\",\n \"test:ci\": \"standard && npm run transpile && npm run test:ci:js && npm run test:ci:ts\",\n \"test:ci:js\": \"tap --no-check-coverage --timeout=120 --coverage-report=lcovonly \\\"test/**/*.test.*js\\\"\",\n \"test:ci:ts\": \"tap --ts --no-check-coverage --coverage-report=lcovonly \\\"test/**/*.test.*ts\\\"\",\n \"test:yarn\": \"npm run transpile && tap \\\"test/**/*.test.js\\\" --no-check-coverage\",\n \"transpile\": \"sh ./test/ts/transpile.sh\",\n \"prepare\": \"husky install\"\n },\n \"standard\": {\n \"ignore\": [\n \"test/ts/**/*\",\n \"test/syntax-error.mjs\"\n ]\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/mcollina/thread-stream.git\"\n },\n \"keywords\": [\n \"worker\",\n \"thread\",\n \"threads\",\n \"stream\"\n ],\n \"author\": \"Matteo Collina \",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/mcollina/thread-stream/issues\"\n },\n \"homepage\": \"https://github.com/mcollina/thread-stream#readme\"\n}\n", "'use strict'\n\nconst MAX_TIMEOUT = 1000\n\nfunction wait (state, index, expected, timeout, done) {\n const max = Date.now() + timeout\n let current = Atomics.load(state, index)\n if (current === expected) {\n done(null, 'ok')\n return\n }\n let prior = current\n const check = (backoff) => {\n if (Date.now() > max) {\n done(null, 'timed-out')\n } else {\n setTimeout(() => {\n prior = current\n current = Atomics.load(state, index)\n if (current === prior) {\n check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)\n } else {\n if (current === expected) done(null, 'ok')\n else done(null, 'not-equal')\n }\n }, backoff)\n }\n }\n check(1)\n}\n\n// let waitDiffCount = 0\nfunction waitDiff (state, index, expected, timeout, done) {\n // const id = waitDiffCount++\n // process._rawDebug(`>>> waitDiff ${id}`)\n const max = Date.now() + timeout\n let current = Atomics.load(state, index)\n if (current !== expected) {\n done(null, 'ok')\n return\n }\n const check = (backoff) => {\n // process._rawDebug(`${id} ${index} current ${current} expected ${expected}`)\n // process._rawDebug('' + backoff)\n if (Date.now() > max) {\n done(null, 'timed-out')\n } else {\n setTimeout(() => {\n current = Atomics.load(state, index)\n if (current !== expected) {\n done(null, 'ok')\n } else {\n check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)\n }\n }, backoff)\n }\n }\n check(1)\n}\n\nmodule.exports = { wait, waitDiff }\n", "'use strict'\n\nconst WRITE_INDEX = 4\nconst READ_INDEX = 8\n\nmodule.exports = {\n WRITE_INDEX,\n READ_INDEX\n}\n", "'use strict'\n\nconst { version } = require('./package.json')\nconst { EventEmitter } = require('events')\nconst { Worker } = require('worker_threads')\nconst { join } = require('path')\nconst { pathToFileURL } = require('url')\nconst { wait } = require('./lib/wait')\nconst {\n WRITE_INDEX,\n READ_INDEX\n} = require('./lib/indexes')\nconst buffer = require('buffer')\nconst assert = require('assert')\n\nconst kImpl = Symbol('kImpl')\n\n// V8 limit for string size\nconst MAX_STRING = buffer.constants.MAX_STRING_LENGTH\n\nclass FakeWeakRef {\n constructor (value) {\n this._value = value\n }\n\n deref () {\n return this._value\n }\n}\n\nclass FakeFinalizationRegistry {\n register () {}\n\n unregister () {}\n}\n\n// Currently using FinalizationRegistry with code coverage breaks the world\n// Ref: https://github.com/nodejs/node/issues/49344\nconst FinalizationRegistry = process.env.NODE_V8_COVERAGE ? FakeFinalizationRegistry : global.FinalizationRegistry || FakeFinalizationRegistry\nconst WeakRef = process.env.NODE_V8_COVERAGE ? FakeWeakRef : global.WeakRef || FakeWeakRef\n\nconst registry = new FinalizationRegistry((worker) => {\n if (worker.exited) {\n return\n }\n worker.terminate()\n})\n\nfunction createWorker (stream, opts) {\n const { filename, workerData } = opts\n\n const bundlerOverrides = '__bundlerPathsOverrides' in globalThis ? globalThis.__bundlerPathsOverrides : {}\n const toExecute = bundlerOverrides['thread-stream-worker'] || join(__dirname, 'lib', 'worker.js')\n\n const worker = new Worker(toExecute, {\n ...opts.workerOpts,\n trackUnmanagedFds: false,\n workerData: {\n filename: filename.indexOf('file://') === 0\n ? filename\n : pathToFileURL(filename).href,\n dataBuf: stream[kImpl].dataBuf,\n stateBuf: stream[kImpl].stateBuf,\n workerData: {\n $context: {\n threadStreamVersion: version\n },\n ...workerData\n }\n }\n })\n\n // We keep a strong reference for now,\n // we need to start writing first\n worker.stream = new FakeWeakRef(stream)\n\n worker.on('message', onWorkerMessage)\n worker.on('exit', onWorkerExit)\n registry.register(stream, worker)\n\n return worker\n}\n\nfunction drain (stream) {\n assert(!stream[kImpl].sync)\n if (stream[kImpl].needDrain) {\n stream[kImpl].needDrain = false\n stream.emit('drain')\n }\n}\n\nfunction nextFlush (stream) {\n const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n let leftover = stream[kImpl].data.length - writeIndex\n\n if (leftover > 0) {\n if (stream[kImpl].buf.length === 0) {\n stream[kImpl].flushing = false\n\n if (stream[kImpl].ending) {\n end(stream)\n } else if (stream[kImpl].needDrain) {\n process.nextTick(drain, stream)\n }\n\n return\n }\n\n let toWrite = stream[kImpl].buf.slice(0, leftover)\n let toWriteBytes = Buffer.byteLength(toWrite)\n if (toWriteBytes <= leftover) {\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n // process._rawDebug('writing ' + toWrite.length)\n write(stream, toWrite, nextFlush.bind(null, stream))\n } else {\n // multi-byte utf-8\n stream.flush(() => {\n // err is already handled in flush()\n if (stream.destroyed) {\n return\n }\n\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n\n // Find a toWrite length that fits the buffer\n // it must exists as the buffer is at least 4 bytes length\n // and the max utf-8 length for a char is 4 bytes.\n while (toWriteBytes > stream[kImpl].data.length) {\n leftover = leftover / 2\n toWrite = stream[kImpl].buf.slice(0, leftover)\n toWriteBytes = Buffer.byteLength(toWrite)\n }\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n write(stream, toWrite, nextFlush.bind(null, stream))\n })\n }\n } else if (leftover === 0) {\n if (writeIndex === 0 && stream[kImpl].buf.length === 0) {\n // we had a flushSync in the meanwhile\n return\n }\n stream.flush(() => {\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n nextFlush(stream)\n })\n } else {\n // This should never happen\n destroy(stream, new Error('overwritten'))\n }\n}\n\nfunction onWorkerMessage (msg) {\n const stream = this.stream.deref()\n if (stream === undefined) {\n this.exited = true\n // Terminate the worker.\n this.terminate()\n return\n }\n\n switch (msg.code) {\n case 'READY':\n // Replace the FakeWeakRef with a\n // proper one.\n this.stream = new WeakRef(stream)\n\n stream.flush(() => {\n stream[kImpl].ready = true\n stream.emit('ready')\n })\n break\n case 'ERROR':\n destroy(stream, msg.err)\n break\n case 'EVENT':\n if (Array.isArray(msg.args)) {\n stream.emit(msg.name, ...msg.args)\n } else {\n stream.emit(msg.name, msg.args)\n }\n break\n case 'WARNING':\n process.emitWarning(msg.err)\n break\n default:\n destroy(stream, new Error('this should not happen: ' + msg.code))\n }\n}\n\nfunction onWorkerExit (code) {\n const stream = this.stream.deref()\n if (stream === undefined) {\n // Nothing to do, the worker already exit\n return\n }\n registry.unregister(stream)\n stream.worker.exited = true\n stream.worker.off('exit', onWorkerExit)\n destroy(stream, code !== 0 ? new Error('the worker thread exited') : null)\n}\n\nclass ThreadStream extends EventEmitter {\n constructor (opts = {}) {\n super()\n\n if (opts.bufferSize < 4) {\n throw new Error('bufferSize must at least fit a 4-byte utf-8 char')\n }\n\n this[kImpl] = {}\n this[kImpl].stateBuf = new SharedArrayBuffer(128)\n this[kImpl].state = new Int32Array(this[kImpl].stateBuf)\n this[kImpl].dataBuf = new SharedArrayBuffer(opts.bufferSize || 4 * 1024 * 1024)\n this[kImpl].data = Buffer.from(this[kImpl].dataBuf)\n this[kImpl].sync = opts.sync || false\n this[kImpl].ending = false\n this[kImpl].ended = false\n this[kImpl].needDrain = false\n this[kImpl].destroyed = false\n this[kImpl].flushing = false\n this[kImpl].ready = false\n this[kImpl].finished = false\n this[kImpl].errored = null\n this[kImpl].closed = false\n this[kImpl].buf = ''\n\n // TODO (fix): Make private?\n this.worker = createWorker(this, opts) // TODO (fix): make private\n this.on('message', (message, transferList) => {\n this.worker.postMessage(message, transferList)\n })\n }\n\n write (data) {\n if (this[kImpl].destroyed) {\n error(this, new Error('the worker has exited'))\n return false\n }\n\n if (this[kImpl].ending) {\n error(this, new Error('the worker is ending'))\n return false\n }\n\n if (this[kImpl].flushing && this[kImpl].buf.length + data.length >= MAX_STRING) {\n try {\n writeSync(this)\n this[kImpl].flushing = true\n } catch (err) {\n destroy(this, err)\n return false\n }\n }\n\n this[kImpl].buf += data\n\n if (this[kImpl].sync) {\n try {\n writeSync(this)\n return true\n } catch (err) {\n destroy(this, err)\n return false\n }\n }\n\n if (!this[kImpl].flushing) {\n this[kImpl].flushing = true\n setImmediate(nextFlush, this)\n }\n\n this[kImpl].needDrain = this[kImpl].data.length - this[kImpl].buf.length - Atomics.load(this[kImpl].state, WRITE_INDEX) <= 0\n return !this[kImpl].needDrain\n }\n\n end () {\n if (this[kImpl].destroyed) {\n return\n }\n\n this[kImpl].ending = true\n end(this)\n }\n\n flush (cb) {\n if (this[kImpl].destroyed) {\n if (typeof cb === 'function') {\n process.nextTick(cb, new Error('the worker has exited'))\n }\n return\n }\n\n // TODO write all .buf\n const writeIndex = Atomics.load(this[kImpl].state, WRITE_INDEX)\n // process._rawDebug(`(flush) readIndex (${Atomics.load(this.state, READ_INDEX)}) writeIndex (${Atomics.load(this.state, WRITE_INDEX)})`)\n wait(this[kImpl].state, READ_INDEX, writeIndex, Infinity, (err, res) => {\n if (err) {\n destroy(this, err)\n process.nextTick(cb, err)\n return\n }\n if (res === 'not-equal') {\n // TODO handle deadlock\n this.flush(cb)\n return\n }\n process.nextTick(cb)\n })\n }\n\n flushSync () {\n if (this[kImpl].destroyed) {\n return\n }\n\n writeSync(this)\n flushSync(this)\n }\n\n unref () {\n this.worker.unref()\n }\n\n ref () {\n this.worker.ref()\n }\n\n get ready () {\n return this[kImpl].ready\n }\n\n get destroyed () {\n return this[kImpl].destroyed\n }\n\n get closed () {\n return this[kImpl].closed\n }\n\n get writable () {\n return !this[kImpl].destroyed && !this[kImpl].ending\n }\n\n get writableEnded () {\n return this[kImpl].ending\n }\n\n get writableFinished () {\n return this[kImpl].finished\n }\n\n get writableNeedDrain () {\n return this[kImpl].needDrain\n }\n\n get writableObjectMode () {\n return false\n }\n\n get writableErrored () {\n return this[kImpl].errored\n }\n}\n\nfunction error (stream, err) {\n setImmediate(() => {\n stream.emit('error', err)\n })\n}\n\nfunction destroy (stream, err) {\n if (stream[kImpl].destroyed) {\n return\n }\n stream[kImpl].destroyed = true\n\n if (err) {\n stream[kImpl].errored = err\n error(stream, err)\n }\n\n if (!stream.worker.exited) {\n stream.worker.terminate()\n .catch(() => {})\n .then(() => {\n stream[kImpl].closed = true\n stream.emit('close')\n })\n } else {\n setImmediate(() => {\n stream[kImpl].closed = true\n stream.emit('close')\n })\n }\n}\n\nfunction write (stream, data, cb) {\n // data is smaller than the shared buffer length\n const current = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n const length = Buffer.byteLength(data)\n stream[kImpl].data.write(data, current)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, current + length)\n Atomics.notify(stream[kImpl].state, WRITE_INDEX)\n cb()\n return true\n}\n\nfunction end (stream) {\n if (stream[kImpl].ended || !stream[kImpl].ending || stream[kImpl].flushing) {\n return\n }\n stream[kImpl].ended = true\n\n try {\n stream.flushSync()\n\n let readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n // process._rawDebug('writing index')\n Atomics.store(stream[kImpl].state, WRITE_INDEX, -1)\n // process._rawDebug(`(end) readIndex (${Atomics.load(stream.state, READ_INDEX)}) writeIndex (${Atomics.load(stream.state, WRITE_INDEX)})`)\n Atomics.notify(stream[kImpl].state, WRITE_INDEX)\n\n // Wait for the process to complete\n let spins = 0\n while (readIndex !== -1) {\n // process._rawDebug(`read = ${read}`)\n Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000)\n readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n if (readIndex === -2) {\n destroy(stream, new Error('end() failed'))\n return\n }\n\n if (++spins === 10) {\n destroy(stream, new Error('end() took too long (10s)'))\n return\n }\n }\n\n process.nextTick(() => {\n stream[kImpl].finished = true\n stream.emit('finish')\n })\n } catch (err) {\n destroy(stream, err)\n }\n // process._rawDebug('end finished...')\n}\n\nfunction writeSync (stream) {\n const cb = () => {\n if (stream[kImpl].ending) {\n end(stream)\n } else if (stream[kImpl].needDrain) {\n process.nextTick(drain, stream)\n }\n }\n stream[kImpl].flushing = false\n\n while (stream[kImpl].buf.length !== 0) {\n const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n let leftover = stream[kImpl].data.length - writeIndex\n if (leftover === 0) {\n flushSync(stream)\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n continue\n } else if (leftover < 0) {\n // stream should never happen\n throw new Error('overwritten')\n }\n\n let toWrite = stream[kImpl].buf.slice(0, leftover)\n let toWriteBytes = Buffer.byteLength(toWrite)\n if (toWriteBytes <= leftover) {\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n // process._rawDebug('writing ' + toWrite.length)\n write(stream, toWrite, cb)\n } else {\n // multi-byte utf-8\n flushSync(stream)\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n\n // Find a toWrite length that fits the buffer\n // it must exists as the buffer is at least 4 bytes length\n // and the max utf-8 length for a char is 4 bytes.\n while (toWriteBytes > stream[kImpl].buf.length) {\n leftover = leftover / 2\n toWrite = stream[kImpl].buf.slice(0, leftover)\n toWriteBytes = Buffer.byteLength(toWrite)\n }\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n write(stream, toWrite, cb)\n }\n }\n}\n\nfunction flushSync (stream) {\n if (stream[kImpl].flushing) {\n throw new Error('unable to flush while flushing')\n }\n\n // process._rawDebug('flushSync started')\n\n const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n\n let spins = 0\n\n // TODO handle deadlock\n while (true) {\n const readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n if (readIndex === -2) {\n throw Error('_flushSync failed')\n }\n\n // process._rawDebug(`(flushSync) readIndex (${readIndex}) writeIndex (${writeIndex})`)\n if (readIndex !== writeIndex) {\n // TODO stream timeouts for some reason.\n Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000)\n } else {\n break\n }\n\n if (++spins === 10) {\n throw new Error('_flushSync took too long (10s)')\n }\n }\n // process._rawDebug('flushSync finished')\n}\n\nmodule.exports = ThreadStream\n", "'use strict'\n\nconst { createRequire } = require('module')\nconst getCallers = require('./caller')\nconst { join, isAbsolute, sep } = require('node:path')\nconst sleep = require('atomic-sleep')\nconst onExit = require('on-exit-leak-free')\nconst ThreadStream = require('thread-stream')\n\nfunction setupOnExit (stream) {\n // This is leak free, it does not leave event handlers\n onExit.register(stream, autoEnd)\n onExit.registerBeforeExit(stream, flush)\n\n stream.on('close', function () {\n onExit.unregister(stream)\n })\n}\n\nfunction buildStream (filename, workerData, workerOpts, sync) {\n const stream = new ThreadStream({\n filename,\n workerData,\n workerOpts,\n sync\n })\n\n stream.on('ready', onReady)\n stream.on('close', function () {\n process.removeListener('exit', onExit)\n })\n\n process.on('exit', onExit)\n\n function onReady () {\n process.removeListener('exit', onExit)\n stream.unref()\n\n if (workerOpts.autoEnd !== false) {\n setupOnExit(stream)\n }\n }\n\n function onExit () {\n /* istanbul ignore next */\n if (stream.closed) {\n return\n }\n stream.flushSync()\n // Apparently there is a very sporadic race condition\n // that in certain OS would prevent the messages to be flushed\n // because the thread might not have been created still.\n // Unfortunately we need to sleep(100) in this case.\n sleep(100)\n stream.end()\n }\n\n return stream\n}\n\nfunction autoEnd (stream) {\n stream.ref()\n stream.flushSync()\n stream.end()\n stream.once('close', function () {\n stream.unref()\n })\n}\n\nfunction flush (stream) {\n stream.flushSync()\n}\n\nfunction transport (fullOptions) {\n const { pipeline, targets, levels, dedupe, worker = {}, caller = getCallers(), sync = false } = fullOptions\n\n const options = {\n ...fullOptions.options\n }\n\n // Backwards compatibility\n const callers = typeof caller === 'string' ? [caller] : caller\n\n // This will be eventually modified by bundlers\n const bundlerOverrides = '__bundlerPathsOverrides' in globalThis ? globalThis.__bundlerPathsOverrides : {}\n\n let target = fullOptions.target\n\n if (target && targets) {\n throw new Error('only one of target or targets can be specified')\n }\n\n if (targets) {\n target = bundlerOverrides['pino-worker'] || join(__dirname, 'worker.js')\n options.targets = targets.filter(dest => dest.target).map((dest) => {\n return {\n ...dest,\n target: fixTarget(dest.target)\n }\n })\n options.pipelines = targets.filter(dest => dest.pipeline).map((dest) => {\n return dest.pipeline.map((t) => {\n return {\n ...t,\n level: dest.level, // duplicate the pipeline `level` property defined in the upper level\n target: fixTarget(t.target)\n }\n })\n })\n } else if (pipeline) {\n target = bundlerOverrides['pino-worker'] || join(__dirname, 'worker.js')\n options.pipelines = [pipeline.map((dest) => {\n return {\n ...dest,\n target: fixTarget(dest.target)\n }\n })]\n }\n\n if (levels) {\n options.levels = levels\n }\n\n if (dedupe) {\n options.dedupe = dedupe\n }\n\n options.pinoWillSendConfig = true\n\n return buildStream(fixTarget(target), options, worker, sync)\n\n function fixTarget (origin) {\n origin = bundlerOverrides[origin] || origin\n\n if (isAbsolute(origin) || origin.indexOf('file://') === 0) {\n return origin\n }\n\n if (origin === 'pino/file') {\n return join(__dirname, '..', 'file.js')\n }\n\n let fixTarget\n\n for (const filePath of callers) {\n try {\n const context = filePath === 'node:repl'\n ? process.cwd() + sep\n : filePath\n\n fixTarget = createRequire(context).resolve(origin)\n break\n } catch (err) {\n // Silent catch\n continue\n }\n }\n\n if (!fixTarget) {\n throw new Error(`unable to determine transport target for \"${origin}\"`)\n }\n\n return fixTarget\n }\n}\n\nmodule.exports = transport\n", "'use strict'\n\n/* eslint no-prototype-builtins: 0 */\n\nconst format = require('quick-format-unescaped')\nconst { mapHttpRequest, mapHttpResponse } = require('pino-std-serializers')\nconst SonicBoom = require('sonic-boom')\nconst onExit = require('on-exit-leak-free')\nconst {\n lsCacheSym,\n chindingsSym,\n writeSym,\n serializersSym,\n formatOptsSym,\n endSym,\n stringifiersSym,\n stringifySym,\n stringifySafeSym,\n wildcardFirstSym,\n nestedKeySym,\n formattersSym,\n messageKeySym,\n errorKeySym,\n nestedKeyStrSym,\n msgPrefixSym\n} = require('./symbols')\nconst { isMainThread } = require('worker_threads')\nconst transport = require('./transport')\n\nfunction noop () {\n}\n\nfunction genLog (level, hook) {\n if (!hook) return LOG\n\n return function hookWrappedLog (...args) {\n hook.call(this, args, LOG, level)\n }\n\n function LOG (o, ...n) {\n if (typeof o === 'object') {\n let msg = o\n if (o !== null) {\n if (o.method && o.headers && o.socket) {\n o = mapHttpRequest(o)\n } else if (typeof o.setHeader === 'function') {\n o = mapHttpResponse(o)\n }\n }\n let formatParams\n if (msg === null && n.length === 0) {\n formatParams = [null]\n } else {\n msg = n.shift()\n formatParams = n\n }\n // We do not use a coercive check for `msg` as it is\n // measurably slower than the explicit checks.\n if (typeof this[msgPrefixSym] === 'string' && msg !== undefined && msg !== null) {\n msg = this[msgPrefixSym] + msg\n }\n this[writeSym](o, format(msg, formatParams, this[formatOptsSym]), level)\n } else {\n let msg = o === undefined ? n.shift() : o\n\n // We do not use a coercive check for `msg` as it is\n // measurably slower than the explicit checks.\n if (typeof this[msgPrefixSym] === 'string' && msg !== undefined && msg !== null) {\n msg = this[msgPrefixSym] + msg\n }\n this[writeSym](null, format(msg, n, this[formatOptsSym]), level)\n }\n }\n}\n\n// magically escape strings for json\n// relying on their charCodeAt\n// everything below 32 needs JSON.stringify()\n// 34 and 92 happens all the time, so we\n// have a fast case for them\nfunction asString (str) {\n let result = ''\n let last = 0\n let found = false\n let point = 255\n const l = str.length\n if (l > 100) {\n return JSON.stringify(str)\n }\n for (var i = 0; i < l && point >= 32; i++) {\n point = str.charCodeAt(i)\n if (point === 34 || point === 92) {\n result += str.slice(last, i) + '\\\\'\n last = i\n found = true\n }\n }\n if (!found) {\n result = str\n } else {\n result += str.slice(last)\n }\n return point < 32 ? JSON.stringify(str) : '\"' + result + '\"'\n}\n\nfunction asJson (obj, msg, num, time) {\n const stringify = this[stringifySym]\n const stringifySafe = this[stringifySafeSym]\n const stringifiers = this[stringifiersSym]\n const end = this[endSym]\n const chindings = this[chindingsSym]\n const serializers = this[serializersSym]\n const formatters = this[formattersSym]\n const messageKey = this[messageKeySym]\n const errorKey = this[errorKeySym]\n let data = this[lsCacheSym][num] + time\n\n // we need the child bindings added to the output first so instance logged\n // objects can take precedence when JSON.parse-ing the resulting log line\n data = data + chindings\n\n let value\n if (formatters.log) {\n obj = formatters.log(obj)\n }\n const wildcardStringifier = stringifiers[wildcardFirstSym]\n let propStr = ''\n for (const key in obj) {\n value = obj[key]\n if (Object.prototype.hasOwnProperty.call(obj, key) && value !== undefined) {\n if (serializers[key]) {\n value = serializers[key](value)\n } else if (key === errorKey && serializers.err) {\n value = serializers.err(value)\n }\n\n const stringifier = stringifiers[key] || wildcardStringifier\n\n switch (typeof value) {\n case 'undefined':\n case 'function':\n continue\n case 'number':\n /* eslint no-fallthrough: \"off\" */\n if (Number.isFinite(value) === false) {\n value = null\n }\n // this case explicitly falls through to the next one\n case 'boolean':\n if (stringifier) value = stringifier(value)\n break\n case 'string':\n value = (stringifier || asString)(value)\n break\n default:\n value = (stringifier || stringify)(value, stringifySafe)\n }\n if (value === undefined) continue\n const strKey = asString(key)\n propStr += ',' + strKey + ':' + value\n }\n }\n\n let msgStr = ''\n if (msg !== undefined) {\n value = serializers[messageKey] ? serializers[messageKey](msg) : msg\n const stringifier = stringifiers[messageKey] || wildcardStringifier\n\n switch (typeof value) {\n case 'function':\n break\n case 'number':\n /* eslint no-fallthrough: \"off\" */\n if (Number.isFinite(value) === false) {\n value = null\n }\n // this case explicitly falls through to the next one\n case 'boolean':\n if (stringifier) value = stringifier(value)\n msgStr = ',\"' + messageKey + '\":' + value\n break\n case 'string':\n value = (stringifier || asString)(value)\n msgStr = ',\"' + messageKey + '\":' + value\n break\n default:\n value = (stringifier || stringify)(value, stringifySafe)\n msgStr = ',\"' + messageKey + '\":' + value\n }\n }\n\n if (this[nestedKeySym] && propStr) {\n // place all the obj properties under the specified key\n // the nested key is already formatted from the constructor\n return data + this[nestedKeyStrSym] + propStr.slice(1) + '}' + msgStr + end\n } else {\n return data + propStr + msgStr + end\n }\n}\n\nfunction asChindings (instance, bindings) {\n let value\n let data = instance[chindingsSym]\n const stringify = instance[stringifySym]\n const stringifySafe = instance[stringifySafeSym]\n const stringifiers = instance[stringifiersSym]\n const wildcardStringifier = stringifiers[wildcardFirstSym]\n const serializers = instance[serializersSym]\n const formatter = instance[formattersSym].bindings\n bindings = formatter(bindings)\n\n for (const key in bindings) {\n value = bindings[key]\n const valid = key !== 'level' &&\n key !== 'serializers' &&\n key !== 'formatters' &&\n key !== 'customLevels' &&\n bindings.hasOwnProperty(key) &&\n value !== undefined\n if (valid === true) {\n value = serializers[key] ? serializers[key](value) : value\n value = (stringifiers[key] || wildcardStringifier || stringify)(value, stringifySafe)\n if (value === undefined) continue\n data += ',\"' + key + '\":' + value\n }\n }\n return data\n}\n\nfunction hasBeenTampered (stream) {\n return stream.write !== stream.constructor.prototype.write\n}\n\nfunction buildSafeSonicBoom (opts) {\n const stream = new SonicBoom(opts)\n stream.on('error', filterBrokenPipe)\n // If we are sync: false, we must flush on exit\n if (!opts.sync && isMainThread) {\n onExit.register(stream, autoEnd)\n\n stream.on('close', function () {\n onExit.unregister(stream)\n })\n }\n return stream\n\n function filterBrokenPipe (err) {\n // Impossible to replicate across all operating systems\n /* istanbul ignore next */\n if (err.code === 'EPIPE') {\n // If we get EPIPE, we should stop logging here\n // however we have no control to the consumer of\n // SonicBoom, so we just overwrite the write method\n stream.write = noop\n stream.end = noop\n stream.flushSync = noop\n stream.destroy = noop\n return\n }\n stream.removeListener('error', filterBrokenPipe)\n stream.emit('error', err)\n }\n}\n\nfunction autoEnd (stream, eventName) {\n // This check is needed only on some platforms\n /* istanbul ignore next */\n if (stream.destroyed) {\n return\n }\n\n if (eventName === 'beforeExit') {\n // We still have an event loop, let's use it\n stream.flush()\n stream.on('drain', function () {\n stream.end()\n })\n } else {\n // For some reason istanbul is not detecting this, but it's there\n /* istanbul ignore next */\n // We do not have an event loop, so flush synchronously\n stream.flushSync()\n }\n}\n\nfunction createArgsNormalizer (defaultOptions) {\n return function normalizeArgs (instance, caller, opts = {}, stream) {\n // support stream as a string\n if (typeof opts === 'string') {\n stream = buildSafeSonicBoom({ dest: opts })\n opts = {}\n } else if (typeof stream === 'string') {\n if (opts && opts.transport) {\n throw Error('only one of option.transport or stream can be specified')\n }\n stream = buildSafeSonicBoom({ dest: stream })\n } else if (opts instanceof SonicBoom || opts.writable || opts._writableState) {\n stream = opts\n opts = {}\n } else if (opts.transport) {\n if (opts.transport instanceof SonicBoom || opts.transport.writable || opts.transport._writableState) {\n throw Error('option.transport do not allow stream, please pass to option directly. e.g. pino(transport)')\n }\n if (opts.transport.targets && opts.transport.targets.length && opts.formatters && typeof opts.formatters.level === 'function') {\n throw Error('option.transport.targets do not allow custom level formatters')\n }\n\n let customLevels\n if (opts.customLevels) {\n customLevels = opts.useOnlyCustomLevels ? opts.customLevels : Object.assign({}, opts.levels, opts.customLevels)\n }\n stream = transport({ caller, ...opts.transport, levels: customLevels })\n }\n opts = Object.assign({}, defaultOptions, opts)\n opts.serializers = Object.assign({}, defaultOptions.serializers, opts.serializers)\n opts.formatters = Object.assign({}, defaultOptions.formatters, opts.formatters)\n\n if (opts.prettyPrint) {\n throw new Error('prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)')\n }\n\n const { enabled, onChild } = opts\n if (enabled === false) opts.level = 'silent'\n if (!onChild) opts.onChild = noop\n if (!stream) {\n if (!hasBeenTampered(process.stdout)) {\n // If process.stdout.fd is undefined, it means that we are running\n // in a worker thread. Let's assume we are logging to file descriptor 1.\n stream = buildSafeSonicBoom({ fd: process.stdout.fd || 1 })\n } else {\n stream = process.stdout\n }\n }\n return { opts, stream }\n }\n}\n\nfunction stringify (obj, stringifySafeFn) {\n try {\n return JSON.stringify(obj)\n } catch (_) {\n try {\n const stringify = stringifySafeFn || this[stringifySafeSym]\n return stringify(obj)\n } catch (_) {\n return '\"[unable to serialize, circular reference is too complex to analyze]\"'\n }\n }\n}\n\nfunction buildFormatters (level, bindings, log) {\n return {\n level,\n bindings,\n log\n }\n}\n\n/**\n * Convert a string integer file descriptor to a proper native integer\n * file descriptor.\n *\n * @param {string} destination The file descriptor string to attempt to convert.\n *\n * @returns {Number}\n */\nfunction normalizeDestFileDescriptor (destination) {\n const fd = Number(destination)\n if (typeof destination === 'string' && Number.isFinite(fd)) {\n return fd\n }\n // destination could be undefined if we are in a worker\n if (destination === undefined) {\n // This is stdout in UNIX systems\n return 1\n }\n return destination\n}\n\nmodule.exports = {\n noop,\n buildSafeSonicBoom,\n asChindings,\n asJson,\n genLog,\n createArgsNormalizer,\n stringify,\n buildFormatters,\n normalizeDestFileDescriptor\n}\n", "/**\n * Represents default log level values\n *\n * @enum {number}\n */\nconst DEFAULT_LEVELS = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60\n}\n\n/**\n * Represents sort order direction: `ascending` or `descending`\n *\n * @enum {string}\n */\nconst SORTING_ORDER = {\n ASC: 'ASC',\n DESC: 'DESC'\n}\n\nmodule.exports = {\n DEFAULT_LEVELS,\n SORTING_ORDER\n}\n", "'use strict'\n/* eslint no-prototype-builtins: 0 */\nconst {\n lsCacheSym,\n levelValSym,\n useOnlyCustomLevelsSym,\n streamSym,\n formattersSym,\n hooksSym,\n levelCompSym\n} = require('./symbols')\nconst { noop, genLog } = require('./tools')\nconst { DEFAULT_LEVELS, SORTING_ORDER } = require('./constants')\n\nconst levelMethods = {\n fatal: (hook) => {\n const logFatal = genLog(DEFAULT_LEVELS.fatal, hook)\n return function (...args) {\n const stream = this[streamSym]\n logFatal.call(this, ...args)\n if (typeof stream.flushSync === 'function') {\n try {\n stream.flushSync()\n } catch (e) {\n // https://github.com/pinojs/pino/pull/740#discussion_r346788313\n }\n }\n }\n },\n error: (hook) => genLog(DEFAULT_LEVELS.error, hook),\n warn: (hook) => genLog(DEFAULT_LEVELS.warn, hook),\n info: (hook) => genLog(DEFAULT_LEVELS.info, hook),\n debug: (hook) => genLog(DEFAULT_LEVELS.debug, hook),\n trace: (hook) => genLog(DEFAULT_LEVELS.trace, hook)\n}\n\nconst nums = Object.keys(DEFAULT_LEVELS).reduce((o, k) => {\n o[DEFAULT_LEVELS[k]] = k\n return o\n}, {})\n\nconst initialLsCache = Object.keys(nums).reduce((o, k) => {\n o[k] = '{\"level\":' + Number(k)\n return o\n}, {})\n\nfunction genLsCache (instance) {\n const formatter = instance[formattersSym].level\n const { labels } = instance.levels\n const cache = {}\n for (const label in labels) {\n const level = formatter(labels[label], Number(label))\n cache[label] = JSON.stringify(level).slice(0, -1)\n }\n instance[lsCacheSym] = cache\n return instance\n}\n\nfunction isStandardLevel (level, useOnlyCustomLevels) {\n if (useOnlyCustomLevels) {\n return false\n }\n\n switch (level) {\n case 'fatal':\n case 'error':\n case 'warn':\n case 'info':\n case 'debug':\n case 'trace':\n return true\n default:\n return false\n }\n}\n\nfunction setLevel (level) {\n const { labels, values } = this.levels\n if (typeof level === 'number') {\n if (labels[level] === undefined) throw Error('unknown level value' + level)\n level = labels[level]\n }\n if (values[level] === undefined) throw Error('unknown level ' + level)\n const preLevelVal = this[levelValSym]\n const levelVal = this[levelValSym] = values[level]\n const useOnlyCustomLevelsVal = this[useOnlyCustomLevelsSym]\n const levelComparison = this[levelCompSym]\n const hook = this[hooksSym].logMethod\n\n for (const key in values) {\n if (levelComparison(values[key], levelVal) === false) {\n this[key] = noop\n continue\n }\n this[key] = isStandardLevel(key, useOnlyCustomLevelsVal) ? levelMethods[key](hook) : genLog(values[key], hook)\n }\n\n this.emit(\n 'level-change',\n level,\n levelVal,\n labels[preLevelVal],\n preLevelVal,\n this\n )\n}\n\nfunction getLevel (level) {\n const { levels, levelVal } = this\n // protection against potential loss of Pino scope from serializers (edge case with circular refs - https://github.com/pinojs/pino/issues/833)\n return (levels && levels.labels) ? levels.labels[levelVal] : ''\n}\n\nfunction isLevelEnabled (logLevel) {\n const { values } = this.levels\n const logLevelVal = values[logLevel]\n return logLevelVal !== undefined && this[levelCompSym](logLevelVal, this[levelValSym])\n}\n\n/**\n * Determine if the given `current` level is enabled by comparing it\n * against the current threshold (`expected`).\n *\n * @param {SORTING_ORDER} direction comparison direction \"ASC\" or \"DESC\"\n * @param {number} current current log level number representation\n * @param {number} expected threshold value to compare with\n * @returns {boolean}\n */\nfunction compareLevel (direction, current, expected) {\n if (direction === SORTING_ORDER.DESC) {\n return current <= expected\n }\n\n return current >= expected\n}\n\n/**\n * Create a level comparison function based on `levelComparison`\n * it could a default function which compares levels either in \"ascending\" or \"descending\" order or custom comparison function\n *\n * @param {SORTING_ORDER | Function} levelComparison sort levels order direction or custom comparison function\n * @returns Function\n */\nfunction genLevelComparison (levelComparison) {\n if (typeof levelComparison === 'string') {\n return compareLevel.bind(null, levelComparison)\n }\n\n return levelComparison\n}\n\nfunction mappings (customLevels = null, useOnlyCustomLevels = false) {\n const customNums = customLevels\n /* eslint-disable */\n ? Object.keys(customLevels).reduce((o, k) => {\n o[customLevels[k]] = k\n return o\n }, {})\n : null\n /* eslint-enable */\n\n const labels = Object.assign(\n Object.create(Object.prototype, { Infinity: { value: 'silent' } }),\n useOnlyCustomLevels ? null : nums,\n customNums\n )\n const values = Object.assign(\n Object.create(Object.prototype, { silent: { value: Infinity } }),\n useOnlyCustomLevels ? null : DEFAULT_LEVELS,\n customLevels\n )\n return { labels, values }\n}\n\nfunction assertDefaultLevelFound (defaultLevel, customLevels, useOnlyCustomLevels) {\n if (typeof defaultLevel === 'number') {\n const values = [].concat(\n Object.keys(customLevels || {}).map(key => customLevels[key]),\n useOnlyCustomLevels ? [] : Object.keys(nums).map(level => +level),\n Infinity\n )\n if (!values.includes(defaultLevel)) {\n throw Error(`default level:${defaultLevel} must be included in custom levels`)\n }\n return\n }\n\n const labels = Object.assign(\n Object.create(Object.prototype, { silent: { value: Infinity } }),\n useOnlyCustomLevels ? null : DEFAULT_LEVELS,\n customLevels\n )\n if (!(defaultLevel in labels)) {\n throw Error(`default level:${defaultLevel} must be included in custom levels`)\n }\n}\n\nfunction assertNoLevelCollisions (levels, customLevels) {\n const { labels, values } = levels\n for (const k in customLevels) {\n if (k in values) {\n throw Error('levels cannot be overridden')\n }\n if (customLevels[k] in labels) {\n throw Error('pre-existing level values cannot be used for new levels')\n }\n }\n}\n\n/**\n * Validates whether `levelComparison` is correct\n *\n * @throws Error\n * @param {SORTING_ORDER | Function} levelComparison - value to validate\n * @returns\n */\nfunction assertLevelComparison (levelComparison) {\n if (typeof levelComparison === 'function') {\n return\n }\n\n if (typeof levelComparison === 'string' && Object.values(SORTING_ORDER).includes(levelComparison)) {\n return\n }\n\n throw new Error('Levels comparison should be one of \"ASC\", \"DESC\" or \"function\" type')\n}\n\nmodule.exports = {\n initialLsCache,\n genLsCache,\n levelMethods,\n getLevel,\n setLevel,\n isLevelEnabled,\n mappings,\n assertNoLevelCollisions,\n assertDefaultLevelFound,\n genLevelComparison,\n assertLevelComparison\n}\n", "'use strict'\n\nmodule.exports = { version: '9.7.0' }\n", "'use strict'\n\n/* eslint no-prototype-builtins: 0 */\n\nconst { EventEmitter } = require('node:events')\nconst {\n lsCacheSym,\n levelValSym,\n setLevelSym,\n getLevelSym,\n chindingsSym,\n parsedChindingsSym,\n mixinSym,\n asJsonSym,\n writeSym,\n mixinMergeStrategySym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n serializersSym,\n formattersSym,\n errorKeySym,\n messageKeySym,\n useOnlyCustomLevelsSym,\n needsMetadataGsym,\n redactFmtSym,\n stringifySym,\n formatOptsSym,\n stringifiersSym,\n msgPrefixSym,\n hooksSym\n} = require('./symbols')\nconst {\n getLevel,\n setLevel,\n isLevelEnabled,\n mappings,\n initialLsCache,\n genLsCache,\n assertNoLevelCollisions\n} = require('./levels')\nconst {\n asChindings,\n asJson,\n buildFormatters,\n stringify\n} = require('./tools')\nconst {\n version\n} = require('./meta')\nconst redaction = require('./redaction')\n\n// note: use of class is satirical\n// https://github.com/pinojs/pino/pull/433#pullrequestreview-127703127\nconst constructor = class Pino {}\nconst prototype = {\n constructor,\n child,\n bindings,\n setBindings,\n flush,\n isLevelEnabled,\n version,\n get level () { return this[getLevelSym]() },\n set level (lvl) { this[setLevelSym](lvl) },\n get levelVal () { return this[levelValSym] },\n set levelVal (n) { throw Error('levelVal is read-only') },\n [lsCacheSym]: initialLsCache,\n [writeSym]: write,\n [asJsonSym]: asJson,\n [getLevelSym]: getLevel,\n [setLevelSym]: setLevel\n}\n\nObject.setPrototypeOf(prototype, EventEmitter.prototype)\n\n// exporting and consuming the prototype object using factory pattern fixes scoping issues with getters when serializing\nmodule.exports = function () {\n return Object.create(prototype)\n}\n\nconst resetChildingsFormatter = bindings => bindings\nfunction child (bindings, options) {\n if (!bindings) {\n throw Error('missing bindings for child Pino')\n }\n options = options || {} // default options to empty object\n const serializers = this[serializersSym]\n const formatters = this[formattersSym]\n const instance = Object.create(this)\n\n if (options.hasOwnProperty('serializers') === true) {\n instance[serializersSym] = Object.create(null)\n\n for (const k in serializers) {\n instance[serializersSym][k] = serializers[k]\n }\n const parentSymbols = Object.getOwnPropertySymbols(serializers)\n /* eslint no-var: off */\n for (var i = 0; i < parentSymbols.length; i++) {\n const ks = parentSymbols[i]\n instance[serializersSym][ks] = serializers[ks]\n }\n\n for (const bk in options.serializers) {\n instance[serializersSym][bk] = options.serializers[bk]\n }\n const bindingsSymbols = Object.getOwnPropertySymbols(options.serializers)\n for (var bi = 0; bi < bindingsSymbols.length; bi++) {\n const bks = bindingsSymbols[bi]\n instance[serializersSym][bks] = options.serializers[bks]\n }\n } else instance[serializersSym] = serializers\n if (options.hasOwnProperty('formatters')) {\n const { level, bindings: chindings, log } = options.formatters\n instance[formattersSym] = buildFormatters(\n level || formatters.level,\n chindings || resetChildingsFormatter,\n log || formatters.log\n )\n } else {\n instance[formattersSym] = buildFormatters(\n formatters.level,\n resetChildingsFormatter,\n formatters.log\n )\n }\n if (options.hasOwnProperty('customLevels') === true) {\n assertNoLevelCollisions(this.levels, options.customLevels)\n instance.levels = mappings(options.customLevels, instance[useOnlyCustomLevelsSym])\n genLsCache(instance)\n }\n\n // redact must place before asChindings and only replace if exist\n if ((typeof options.redact === 'object' && options.redact !== null) || Array.isArray(options.redact)) {\n instance.redact = options.redact // replace redact directly\n const stringifiers = redaction(instance.redact, stringify)\n const formatOpts = { stringify: stringifiers[redactFmtSym] }\n instance[stringifySym] = stringify\n instance[stringifiersSym] = stringifiers\n instance[formatOptsSym] = formatOpts\n }\n\n if (typeof options.msgPrefix === 'string') {\n instance[msgPrefixSym] = (this[msgPrefixSym] || '') + options.msgPrefix\n }\n\n instance[chindingsSym] = asChindings(instance, bindings)\n const childLevel = options.level || this.level\n instance[setLevelSym](childLevel)\n this.onChild(instance)\n return instance\n}\n\nfunction bindings () {\n const chindings = this[chindingsSym]\n const chindingsJson = `{${chindings.substr(1)}}` // at least contains ,\"pid\":7068,\"hostname\":\"myMac\"\n const bindingsFromJson = JSON.parse(chindingsJson)\n delete bindingsFromJson.pid\n delete bindingsFromJson.hostname\n return bindingsFromJson\n}\n\nfunction setBindings (newBindings) {\n const chindings = asChindings(this, newBindings)\n this[chindingsSym] = chindings\n delete this[parsedChindingsSym]\n}\n\n/**\n * Default strategy for creating `mergeObject` from arguments and the result from `mixin()`.\n * Fields from `mergeObject` have higher priority in this strategy.\n *\n * @param {Object} mergeObject The object a user has supplied to the logging function.\n * @param {Object} mixinObject The result of the `mixin` method.\n * @return {Object}\n */\nfunction defaultMixinMergeStrategy (mergeObject, mixinObject) {\n return Object.assign(mixinObject, mergeObject)\n}\n\nfunction write (_obj, msg, num) {\n const t = this[timeSym]()\n const mixin = this[mixinSym]\n const errorKey = this[errorKeySym]\n const messageKey = this[messageKeySym]\n const mixinMergeStrategy = this[mixinMergeStrategySym] || defaultMixinMergeStrategy\n let obj\n const streamWriteHook = this[hooksSym].streamWrite\n\n if (_obj === undefined || _obj === null) {\n obj = {}\n } else if (_obj instanceof Error) {\n obj = { [errorKey]: _obj }\n if (msg === undefined) {\n msg = _obj.message\n }\n } else {\n obj = _obj\n if (msg === undefined && _obj[messageKey] === undefined && _obj[errorKey]) {\n msg = _obj[errorKey].message\n }\n }\n\n if (mixin) {\n obj = mixinMergeStrategy(obj, mixin(obj, num, this))\n }\n\n const s = this[asJsonSym](obj, msg, num, t)\n\n const stream = this[streamSym]\n if (stream[needsMetadataGsym] === true) {\n stream.lastLevel = num\n stream.lastObj = obj\n stream.lastMsg = msg\n stream.lastTime = t.slice(this[timeSliceIndexSym])\n stream.lastLogger = this // for child loggers\n }\n stream.write(streamWriteHook ? streamWriteHook(s) : s)\n}\n\nfunction noop () {}\n\nfunction flush (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw Error('callback must be a function')\n }\n\n const stream = this[streamSym]\n\n if (typeof stream.flush === 'function') {\n stream.flush(cb || noop)\n } else if (cb) cb()\n}\n", "'use strict'\n\nconst { hasOwnProperty } = Object.prototype\n\nconst stringify = configure()\n\n// @ts-expect-error\nstringify.configure = configure\n// @ts-expect-error\nstringify.stringify = stringify\n\n// @ts-expect-error\nstringify.default = stringify\n\n// @ts-expect-error used for named export\nexports.stringify = stringify\n// @ts-expect-error used for named export\nexports.configure = configure\n\nmodule.exports = stringify\n\n// eslint-disable-next-line no-control-regex\nconst strEscapeSequencesRegExp = /[\\u0000-\\u001f\\u0022\\u005c\\ud800-\\udfff]/\n\n// Escape C0 control characters, double quotes, the backslash and every code\n// unit with a numeric value in the inclusive range 0xD800 to 0xDFFF.\nfunction strEscape (str) {\n // Some magic numbers that worked out fine while benchmarking with v8 8.0\n if (str.length < 5000 && !strEscapeSequencesRegExp.test(str)) {\n return `\"${str}\"`\n }\n return JSON.stringify(str)\n}\n\nfunction sort (array, comparator) {\n // Insertion sort is very efficient for small input sizes, but it has a bad\n // worst case complexity. Thus, use native array sort for bigger values.\n if (array.length > 2e2 || comparator) {\n return array.sort(comparator)\n }\n for (let i = 1; i < array.length; i++) {\n const currentValue = array[i]\n let position = i\n while (position !== 0 && array[position - 1] > currentValue) {\n array[position] = array[position - 1]\n position--\n }\n array[position] = currentValue\n }\n return array\n}\n\nconst typedArrayPrototypeGetSymbolToStringTag =\n Object.getOwnPropertyDescriptor(\n Object.getPrototypeOf(\n Object.getPrototypeOf(\n new Int8Array()\n )\n ),\n Symbol.toStringTag\n ).get\n\nfunction isTypedArrayWithEntries (value) {\n return typedArrayPrototypeGetSymbolToStringTag.call(value) !== undefined && value.length !== 0\n}\n\nfunction stringifyTypedArray (array, separator, maximumBreadth) {\n if (array.length < maximumBreadth) {\n maximumBreadth = array.length\n }\n const whitespace = separator === ',' ? '' : ' '\n let res = `\"0\":${whitespace}${array[0]}`\n for (let i = 1; i < maximumBreadth; i++) {\n res += `${separator}\"${i}\":${whitespace}${array[i]}`\n }\n return res\n}\n\nfunction getCircularValueOption (options) {\n if (hasOwnProperty.call(options, 'circularValue')) {\n const circularValue = options.circularValue\n if (typeof circularValue === 'string') {\n return `\"${circularValue}\"`\n }\n if (circularValue == null) {\n return circularValue\n }\n if (circularValue === Error || circularValue === TypeError) {\n return {\n toString () {\n throw new TypeError('Converting circular structure to JSON')\n }\n }\n }\n throw new TypeError('The \"circularValue\" argument must be of type string or the value null or undefined')\n }\n return '\"[Circular]\"'\n}\n\nfunction getDeterministicOption (options) {\n let value\n if (hasOwnProperty.call(options, 'deterministic')) {\n value = options.deterministic\n if (typeof value !== 'boolean' && typeof value !== 'function') {\n throw new TypeError('The \"deterministic\" argument must be of type boolean or comparator function')\n }\n }\n return value === undefined ? true : value\n}\n\nfunction getBooleanOption (options, key) {\n let value\n if (hasOwnProperty.call(options, key)) {\n value = options[key]\n if (typeof value !== 'boolean') {\n throw new TypeError(`The \"${key}\" argument must be of type boolean`)\n }\n }\n return value === undefined ? true : value\n}\n\nfunction getPositiveIntegerOption (options, key) {\n let value\n if (hasOwnProperty.call(options, key)) {\n value = options[key]\n if (typeof value !== 'number') {\n throw new TypeError(`The \"${key}\" argument must be of type number`)\n }\n if (!Number.isInteger(value)) {\n throw new TypeError(`The \"${key}\" argument must be an integer`)\n }\n if (value < 1) {\n throw new RangeError(`The \"${key}\" argument must be >= 1`)\n }\n }\n return value === undefined ? Infinity : value\n}\n\nfunction getItemCount (number) {\n if (number === 1) {\n return '1 item'\n }\n return `${number} items`\n}\n\nfunction getUniqueReplacerSet (replacerArray) {\n const replacerSet = new Set()\n for (const value of replacerArray) {\n if (typeof value === 'string' || typeof value === 'number') {\n replacerSet.add(String(value))\n }\n }\n return replacerSet\n}\n\nfunction getStrictOption (options) {\n if (hasOwnProperty.call(options, 'strict')) {\n const value = options.strict\n if (typeof value !== 'boolean') {\n throw new TypeError('The \"strict\" argument must be of type boolean')\n }\n if (value) {\n return (value) => {\n let message = `Object can not safely be stringified. Received type ${typeof value}`\n if (typeof value !== 'function') message += ` (${value.toString()})`\n throw new Error(message)\n }\n }\n }\n}\n\nfunction configure (options) {\n options = { ...options }\n const fail = getStrictOption(options)\n if (fail) {\n if (options.bigint === undefined) {\n options.bigint = false\n }\n if (!('circularValue' in options)) {\n options.circularValue = Error\n }\n }\n const circularValue = getCircularValueOption(options)\n const bigint = getBooleanOption(options, 'bigint')\n const deterministic = getDeterministicOption(options)\n const comparator = typeof deterministic === 'function' ? deterministic : undefined\n const maximumDepth = getPositiveIntegerOption(options, 'maximumDepth')\n const maximumBreadth = getPositiveIntegerOption(options, 'maximumBreadth')\n\n function stringifyFnReplacer (key, parent, stack, replacer, spacer, indentation) {\n let value = parent[key]\n\n if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n }\n value = replacer.call(parent, key, value)\n\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n\n let res = ''\n let join = ','\n const originalIndentation = indentation\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n if (spacer !== '') {\n indentation += spacer\n res += `\\n${indentation}`\n join = `,\\n${indentation}`\n }\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n res += join\n }\n const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n if (spacer !== '') {\n res += `\\n${originalIndentation}`\n }\n stack.pop()\n return `[${res}]`\n }\n\n let keys = Object.keys(value)\n const keyLength = keys.length\n if (keyLength === 0) {\n return '{}'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Object]\"'\n }\n let whitespace = ''\n let separator = ''\n if (spacer !== '') {\n indentation += spacer\n join = `,\\n${indentation}`\n whitespace = ' '\n }\n const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n if (deterministic && !isTypedArrayWithEntries(value)) {\n keys = sort(keys, comparator)\n }\n stack.push(value)\n for (let i = 0; i < maximumPropertiesToStringify; i++) {\n const key = keys[i]\n const tmp = stringifyFnReplacer(key, value, stack, replacer, spacer, indentation)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}:${whitespace}${tmp}`\n separator = join\n }\n }\n if (keyLength > maximumBreadth) {\n const removedKeys = keyLength - maximumBreadth\n res += `${separator}\"...\":${whitespace}\"${getItemCount(removedKeys)} not stringified\"`\n separator = join\n }\n if (spacer !== '' && separator.length > 1) {\n res = `\\n${indentation}${res}\\n${originalIndentation}`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringifyArrayReplacer (key, value, stack, replacer, spacer, indentation) {\n if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n }\n\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n\n const originalIndentation = indentation\n let res = ''\n let join = ','\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n if (spacer !== '') {\n indentation += spacer\n res += `\\n${indentation}`\n join = `,\\n${indentation}`\n }\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n res += join\n }\n const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n if (spacer !== '') {\n res += `\\n${originalIndentation}`\n }\n stack.pop()\n return `[${res}]`\n }\n stack.push(value)\n let whitespace = ''\n if (spacer !== '') {\n indentation += spacer\n join = `,\\n${indentation}`\n whitespace = ' '\n }\n let separator = ''\n for (const key of replacer) {\n const tmp = stringifyArrayReplacer(key, value[key], stack, replacer, spacer, indentation)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}:${whitespace}${tmp}`\n separator = join\n }\n }\n if (spacer !== '' && separator.length > 1) {\n res = `\\n${indentation}${res}\\n${originalIndentation}`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringifyIndent (key, value, stack, spacer, indentation) {\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n // Prevent calling `toJSON` again.\n if (typeof value !== 'object') {\n return stringifyIndent(key, value, stack, spacer, indentation)\n }\n if (value === null) {\n return 'null'\n }\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n const originalIndentation = indentation\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n indentation += spacer\n let res = `\\n${indentation}`\n const join = `,\\n${indentation}`\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n res += join\n }\n const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n res += `\\n${originalIndentation}`\n stack.pop()\n return `[${res}]`\n }\n\n let keys = Object.keys(value)\n const keyLength = keys.length\n if (keyLength === 0) {\n return '{}'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Object]\"'\n }\n indentation += spacer\n const join = `,\\n${indentation}`\n let res = ''\n let separator = ''\n let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n if (isTypedArrayWithEntries(value)) {\n res += stringifyTypedArray(value, join, maximumBreadth)\n keys = keys.slice(value.length)\n maximumPropertiesToStringify -= value.length\n separator = join\n }\n if (deterministic) {\n keys = sort(keys, comparator)\n }\n stack.push(value)\n for (let i = 0; i < maximumPropertiesToStringify; i++) {\n const key = keys[i]\n const tmp = stringifyIndent(key, value[key], stack, spacer, indentation)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}: ${tmp}`\n separator = join\n }\n }\n if (keyLength > maximumBreadth) {\n const removedKeys = keyLength - maximumBreadth\n res += `${separator}\"...\": \"${getItemCount(removedKeys)} not stringified\"`\n separator = join\n }\n if (separator !== '') {\n res = `\\n${indentation}${res}\\n${originalIndentation}`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringifySimple (key, value, stack) {\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n // Prevent calling `toJSON` again\n if (typeof value !== 'object') {\n return stringifySimple(key, value, stack)\n }\n if (value === null) {\n return 'null'\n }\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n\n let res = ''\n\n const hasLength = value.length !== undefined\n if (hasLength && Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifySimple(String(i), value[i], stack)\n res += tmp !== undefined ? tmp : 'null'\n res += ','\n }\n const tmp = stringifySimple(String(i), value[i], stack)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `,\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n stack.pop()\n return `[${res}]`\n }\n\n let keys = Object.keys(value)\n const keyLength = keys.length\n if (keyLength === 0) {\n return '{}'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Object]\"'\n }\n let separator = ''\n let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n if (hasLength && isTypedArrayWithEntries(value)) {\n res += stringifyTypedArray(value, ',', maximumBreadth)\n keys = keys.slice(value.length)\n maximumPropertiesToStringify -= value.length\n separator = ','\n }\n if (deterministic) {\n keys = sort(keys, comparator)\n }\n stack.push(value)\n for (let i = 0; i < maximumPropertiesToStringify; i++) {\n const key = keys[i]\n const tmp = stringifySimple(key, value[key], stack)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}:${tmp}`\n separator = ','\n }\n }\n if (keyLength > maximumBreadth) {\n const removedKeys = keyLength - maximumBreadth\n res += `${separator}\"...\":\"${getItemCount(removedKeys)} not stringified\"`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringify (value, replacer, space) {\n if (arguments.length > 1) {\n let spacer = ''\n if (typeof space === 'number') {\n spacer = ' '.repeat(Math.min(space, 10))\n } else if (typeof space === 'string') {\n spacer = space.slice(0, 10)\n }\n if (replacer != null) {\n if (typeof replacer === 'function') {\n return stringifyFnReplacer('', { '': value }, [], replacer, spacer, '')\n }\n if (Array.isArray(replacer)) {\n return stringifyArrayReplacer('', value, [], getUniqueReplacerSet(replacer), spacer, '')\n }\n }\n if (spacer.length !== 0) {\n return stringifyIndent('', value, [], spacer, '')\n }\n }\n return stringifySimple('', value, [])\n }\n\n return stringify\n}\n", "'use strict'\n\nconst metadata = Symbol.for('pino.metadata')\nconst { DEFAULT_LEVELS } = require('./constants')\n\nconst DEFAULT_INFO_LEVEL = DEFAULT_LEVELS.info\n\nfunction multistream (streamsArray, opts) {\n let counter = 0\n streamsArray = streamsArray || []\n opts = opts || { dedupe: false }\n\n const streamLevels = Object.create(DEFAULT_LEVELS)\n streamLevels.silent = Infinity\n if (opts.levels && typeof opts.levels === 'object') {\n Object.keys(opts.levels).forEach(i => {\n streamLevels[i] = opts.levels[i]\n })\n }\n\n const res = {\n write,\n add,\n emit,\n flushSync,\n end,\n minLevel: 0,\n streams: [],\n clone,\n [metadata]: true,\n streamLevels\n }\n\n if (Array.isArray(streamsArray)) {\n streamsArray.forEach(add, res)\n } else {\n add.call(res, streamsArray)\n }\n\n // clean this object up\n // or it will stay allocated forever\n // as it is closed on the following closures\n streamsArray = null\n\n return res\n\n // we can exit early because the streams are ordered by level\n function write (data) {\n let dest\n const level = this.lastLevel\n const { streams } = this\n // for handling situation when several streams has the same level\n let recordedLevel = 0\n let stream\n\n // if dedupe set to true we send logs to the stream with the highest level\n // therefore, we have to change sorting order\n for (let i = initLoopVar(streams.length, opts.dedupe); checkLoopVar(i, streams.length, opts.dedupe); i = adjustLoopVar(i, opts.dedupe)) {\n dest = streams[i]\n if (dest.level <= level) {\n if (recordedLevel !== 0 && recordedLevel !== dest.level) {\n break\n }\n stream = dest.stream\n if (stream[metadata]) {\n const { lastTime, lastMsg, lastObj, lastLogger } = this\n stream.lastLevel = level\n stream.lastTime = lastTime\n stream.lastMsg = lastMsg\n stream.lastObj = lastObj\n stream.lastLogger = lastLogger\n }\n stream.write(data)\n if (opts.dedupe) {\n recordedLevel = dest.level\n }\n } else if (!opts.dedupe) {\n break\n }\n }\n }\n\n function emit (...args) {\n for (const { stream } of this.streams) {\n if (typeof stream.emit === 'function') {\n stream.emit(...args)\n }\n }\n }\n\n function flushSync () {\n for (const { stream } of this.streams) {\n if (typeof stream.flushSync === 'function') {\n stream.flushSync()\n }\n }\n }\n\n function add (dest) {\n if (!dest) {\n return res\n }\n\n // Check that dest implements either StreamEntry or DestinationStream\n const isStream = typeof dest.write === 'function' || dest.stream\n const stream_ = dest.write ? dest : dest.stream\n // This is necessary to provide a meaningful error message, otherwise it throws somewhere inside write()\n if (!isStream) {\n throw Error('stream object needs to implement either StreamEntry or DestinationStream interface')\n }\n\n const { streams, streamLevels } = this\n\n let level\n if (typeof dest.levelVal === 'number') {\n level = dest.levelVal\n } else if (typeof dest.level === 'string') {\n level = streamLevels[dest.level]\n } else if (typeof dest.level === 'number') {\n level = dest.level\n } else {\n level = DEFAULT_INFO_LEVEL\n }\n\n const dest_ = {\n stream: stream_,\n level,\n levelVal: undefined,\n id: counter++\n }\n\n streams.unshift(dest_)\n streams.sort(compareByLevel)\n\n this.minLevel = streams[0].level\n\n return res\n }\n\n function end () {\n for (const { stream } of this.streams) {\n if (typeof stream.flushSync === 'function') {\n stream.flushSync()\n }\n stream.end()\n }\n }\n\n function clone (level) {\n const streams = new Array(this.streams.length)\n\n for (let i = 0; i < streams.length; i++) {\n streams[i] = {\n level,\n stream: this.streams[i].stream\n }\n }\n\n return {\n write,\n add,\n minLevel: level,\n streams,\n clone,\n emit,\n flushSync,\n [metadata]: true\n }\n }\n}\n\nfunction compareByLevel (a, b) {\n return a.level - b.level\n}\n\nfunction initLoopVar (length, dedupe) {\n return dedupe ? length - 1 : 0\n}\n\nfunction adjustLoopVar (i, dedupe) {\n return dedupe ? i - 1 : i + 1\n}\n\nfunction checkLoopVar (i, length, dedupe) {\n return dedupe ? i >= 0 : i < length\n}\n\nmodule.exports = multistream\n", "\n function pinoBundlerAbsolutePath(p) {\n try {\n return require('path').join(`${process.cwd()}${require('path').sep}dist/esm`.replace(/\\\\/g, '/'), p)\n } catch(e) {\n const f = new Function('p', 'return new URL(p, import.meta.url).pathname');\n return f(p)\n }\n }\n \n globalThis.__bundlerPathsOverrides = { ...(globalThis.__bundlerPathsOverrides || {}), 'thread-stream-worker': pinoBundlerAbsolutePath('./thread-stream-worker.mjs'),'pino-worker': pinoBundlerAbsolutePath('./pino-worker.mjs'),'pino/file': pinoBundlerAbsolutePath('./pino-file.mjs'),'pino-roll': pinoBundlerAbsolutePath('./pino-roll.mjs')}\n 'use strict'\n\nconst os = require('node:os')\nconst stdSerializers = require('pino-std-serializers')\nconst caller = require('./lib/caller')\nconst redaction = require('./lib/redaction')\nconst time = require('./lib/time')\nconst proto = require('./lib/proto')\nconst symbols = require('./lib/symbols')\nconst { configure } = require('safe-stable-stringify')\nconst { assertDefaultLevelFound, mappings, genLsCache, genLevelComparison, assertLevelComparison } = require('./lib/levels')\nconst { DEFAULT_LEVELS, SORTING_ORDER } = require('./lib/constants')\nconst {\n createArgsNormalizer,\n asChindings,\n buildSafeSonicBoom,\n buildFormatters,\n stringify,\n normalizeDestFileDescriptor,\n noop\n} = require('./lib/tools')\nconst { version } = require('./lib/meta')\nconst {\n chindingsSym,\n redactFmtSym,\n serializersSym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n stringifySym,\n stringifySafeSym,\n stringifiersSym,\n setLevelSym,\n endSym,\n formatOptsSym,\n messageKeySym,\n errorKeySym,\n nestedKeySym,\n mixinSym,\n levelCompSym,\n useOnlyCustomLevelsSym,\n formattersSym,\n hooksSym,\n nestedKeyStrSym,\n mixinMergeStrategySym,\n msgPrefixSym\n} = symbols\nconst { epochTime, nullTime } = time\nconst { pid } = process\nconst hostname = os.hostname()\nconst defaultErrorSerializer = stdSerializers.err\nconst defaultOptions = {\n level: 'info',\n levelComparison: SORTING_ORDER.ASC,\n levels: DEFAULT_LEVELS,\n messageKey: 'msg',\n errorKey: 'err',\n nestedKey: null,\n enabled: true,\n base: { pid, hostname },\n serializers: Object.assign(Object.create(null), {\n err: defaultErrorSerializer\n }),\n formatters: Object.assign(Object.create(null), {\n bindings (bindings) {\n return bindings\n },\n level (label, number) {\n return { level: number }\n }\n }),\n hooks: {\n logMethod: undefined,\n streamWrite: undefined\n },\n timestamp: epochTime,\n name: undefined,\n redact: null,\n customLevels: null,\n useOnlyCustomLevels: false,\n depthLimit: 5,\n edgeLimit: 100\n}\n\nconst normalize = createArgsNormalizer(defaultOptions)\n\nconst serializers = Object.assign(Object.create(null), stdSerializers)\n\nfunction pino (...args) {\n const instance = {}\n const { opts, stream } = normalize(instance, caller(), ...args)\n\n if (opts.level && typeof opts.level === 'string' && DEFAULT_LEVELS[opts.level.toLowerCase()] !== undefined) opts.level = opts.level.toLowerCase()\n\n const {\n redact,\n crlf,\n serializers,\n timestamp,\n messageKey,\n errorKey,\n nestedKey,\n base,\n name,\n level,\n customLevels,\n levelComparison,\n mixin,\n mixinMergeStrategy,\n useOnlyCustomLevels,\n formatters,\n hooks,\n depthLimit,\n edgeLimit,\n onChild,\n msgPrefix\n } = opts\n\n const stringifySafe = configure({\n maximumDepth: depthLimit,\n maximumBreadth: edgeLimit\n })\n\n const allFormatters = buildFormatters(\n formatters.level,\n formatters.bindings,\n formatters.log\n )\n\n const stringifyFn = stringify.bind({\n [stringifySafeSym]: stringifySafe\n })\n const stringifiers = redact ? redaction(redact, stringifyFn) : {}\n const formatOpts = redact\n ? { stringify: stringifiers[redactFmtSym] }\n : { stringify: stringifyFn }\n const end = '}' + (crlf ? '\\r\\n' : '\\n')\n const coreChindings = asChindings.bind(null, {\n [chindingsSym]: '',\n [serializersSym]: serializers,\n [stringifiersSym]: stringifiers,\n [stringifySym]: stringify,\n [stringifySafeSym]: stringifySafe,\n [formattersSym]: allFormatters\n })\n\n let chindings = ''\n if (base !== null) {\n if (name === undefined) {\n chindings = coreChindings(base)\n } else {\n chindings = coreChindings(Object.assign({}, base, { name }))\n }\n }\n\n const time = (timestamp instanceof Function)\n ? timestamp\n : (timestamp ? epochTime : nullTime)\n const timeSliceIndex = time().indexOf(':') + 1\n\n if (useOnlyCustomLevels && !customLevels) throw Error('customLevels is required if useOnlyCustomLevels is set true')\n if (mixin && typeof mixin !== 'function') throw Error(`Unknown mixin type \"${typeof mixin}\" - expected \"function\"`)\n if (msgPrefix && typeof msgPrefix !== 'string') throw Error(`Unknown msgPrefix type \"${typeof msgPrefix}\" - expected \"string\"`)\n\n assertDefaultLevelFound(level, customLevels, useOnlyCustomLevels)\n const levels = mappings(customLevels, useOnlyCustomLevels)\n\n if (typeof stream.emit === 'function') {\n stream.emit('message', { code: 'PINO_CONFIG', config: { levels, messageKey, errorKey } })\n }\n\n assertLevelComparison(levelComparison)\n const levelCompFunc = genLevelComparison(levelComparison)\n\n Object.assign(instance, {\n levels,\n [levelCompSym]: levelCompFunc,\n [useOnlyCustomLevelsSym]: useOnlyCustomLevels,\n [streamSym]: stream,\n [timeSym]: time,\n [timeSliceIndexSym]: timeSliceIndex,\n [stringifySym]: stringify,\n [stringifySafeSym]: stringifySafe,\n [stringifiersSym]: stringifiers,\n [endSym]: end,\n [formatOptsSym]: formatOpts,\n [messageKeySym]: messageKey,\n [errorKeySym]: errorKey,\n [nestedKeySym]: nestedKey,\n // protect against injection\n [nestedKeyStrSym]: nestedKey ? `,${JSON.stringify(nestedKey)}:{` : '',\n [serializersSym]: serializers,\n [mixinSym]: mixin,\n [mixinMergeStrategySym]: mixinMergeStrategy,\n [chindingsSym]: chindings,\n [formattersSym]: allFormatters,\n [hooksSym]: hooks,\n silent: noop,\n onChild,\n [msgPrefixSym]: msgPrefix\n })\n\n Object.setPrototypeOf(instance, proto())\n\n genLsCache(instance)\n\n instance[setLevelSym](level)\n\n return instance\n}\n\nmodule.exports = pino\n\nmodule.exports.destination = (dest = process.stdout.fd) => {\n if (typeof dest === 'object') {\n dest.dest = normalizeDestFileDescriptor(dest.dest || process.stdout.fd)\n return buildSafeSonicBoom(dest)\n } else {\n return buildSafeSonicBoom({ dest: normalizeDestFileDescriptor(dest), minLength: 0 })\n }\n}\n\nmodule.exports.transport = require('./lib/transport')\nmodule.exports.multistream = require('./lib/multistream')\n\nmodule.exports.levels = mappings()\nmodule.exports.stdSerializers = serializers\nmodule.exports.stdTimeFunctions = Object.assign({}, time)\nmodule.exports.symbols = symbols\nmodule.exports.version = version\n\n// Enables default and name export with TypeScript and Babel\nmodule.exports.default = pino\nmodule.exports.pino = pino\n", "'use strict'\n\nconst pino = require('./pino')\nconst { once } = require('node:events')\n\nmodule.exports = async function (opts = {}) {\n const destOpts = Object.assign({}, opts, { dest: opts.destination || 1, sync: false })\n delete destOpts.destination\n const destination = pino.destination(destOpts)\n await once(destination, 'ready')\n return destination\n}\n"], + "mappings": "uTAAA,IAAAA,GAAAC,EAAA,CAAAC,GAAAC,KAAA,cAOA,IAAMC,EAAeC,GACZA,GAAO,OAAOA,EAAI,SAAY,SAOjCC,GAAiBD,GAAQ,CAC7B,GAAI,CAACA,EAAK,OAI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AO,KACP,CAAE,KAAAC,EAAK,EAAI,EAAQ,aAAa,EAEtCF,GAAO,QAAU,eAAgBG,EAAO,CAAC,EAAG,CAC1C,IAAMC,EAAW,OAAO,OAAO,CAAC,EAAGD,EAAM,CAAE,KAAMA,EAAK,aAAe,EAAG,KAAM,EAAM,CAAC,EACrF,OAAOC,EAAS,YAChB,IAAMC,EAAcJ,GAAK,YAAYG,CAAQ,EAC7C,aAAMF,GAAKG,EAAa,OAAO,EACxBA,CACT", + "names": ["require_err_helpers", "__commonJSMin", "exports", "module", "isErrorLike", "err", "getErrorCause", "cause", "causeResult", "_stackWithCauses", "seen", "stack", "stackWithCauses", "_messageWithCauses", "skip", "message", "skipIfVErrorStyleCause", "messageWithCauses", "require_err_proto", "__commonJSMin", "exports", "module", "seen", "rawSymbol", "pinoErrProto", "val", "require_err", "__commonJSMin", "exports", "module", "errSerializer", "messageWithCauses", "stackWithCauses", "isErrorLike", "pinoErrProto", "pinoErrorSymbols", "seen", "toString", "err", "_err", "key", "val", "require_err_with_cause", "__commonJSMin", "exports", "module", "errWithCauseSerializer", "isErrorLike", "pinoErrProto", "pinoErrorSymbols", "seen", "toString", "err", "_err", "key", "val", "require_req", "__commonJSMin", "exports", "module", "mapHttpRequest", "reqSerializer", "rawSymbol", "pinoReqProto", "val", "req", "connection", "_req", "path", "require_res", "__commonJSMin", "exports", "module", "mapHttpResponse", "resSerializer", "rawSymbol", "pinoResProto", "val", "res", "_res", "require_pino_std_serializers", "__commonJSMin", "exports", "module", "errSerializer", "errWithCauseSerializer", "reqSerializers", "resSerializers", "customSerializer", "err", "req", "res", "require_caller", "__commonJSMin", "exports", "module", "noOpPrepareStackTrace", "_", "stack", "originalPrepare", "entries", "fileNames", "entry", "require_validator", "__commonJSMin", "exports", "module", "validator", "opts", "ERR_PATHS_MUST_BE_STRINGS", "ERR_INVALID_PATH", "s", "paths", "expr", "require_rx", "__commonJSMin", "exports", "module", "require_parse", "__commonJSMin", "exports", "module", "rx", "parse", "paths", "wildcards", "wcLen", "secret", "o", "strPath", "ix", "path", "p", "leadingBracket", "star", "before", "beforeStr", "after", "nested", "require_redactor", "__commonJSMin", "exports", "module", "rx", "redactor", "secret", "serialize", "wcLen", "strict", "isCensorFct", "censorFctTakesPath", "state", "redact", "strictImpl", "redactTmpl", "dynamicRedactTmpl", "resultTmpl", "o", "path", "escPath", "leadingBracket", "arrPath", "skip", "delim", "hops", "match", "ix", "index", "input", "existence", "p", "circularDetection", "censorArgs", "hasWildcards", "require_modifiers", "__commonJSMin", "exports", "module", "groupRedact", "groupRestore", "nestedRedact", "nestedRestore", "keys", "values", "target", "length", "k", "o", "path", "censor", "isCensorFct", "censorFctTakesPath", "get", "keysLength", "pathLength", "pathWithKey", "i", "key", "instructions", "value", "current", "store", "ns", "specialSet", "has", "obj", "prop", "afterPath", "afterPathLen", "lastPathIndex", "originalKey", "n", "nv", "ov", "oov", "wc", "kIsWc", "wcov", "consecutive", "level", "depth", "redactPathCurrent", "tree", "wcKeys", "j", "wck", "node", "iterateNthLevel", "rv", "restoreInstr", "p", "l", "parent", "child", "require_restorer", "__commonJSMin", "exports", "module", "groupRestore", "nestedRestore", "restorer", "secret", "wcLen", "paths", "resetters", "resetTmpl", "hasWildcards", "state", "restoreTmpl", "path", "circle", "escPath", "leadingBracket", "reset", "clear", "require_state", "__commonJSMin", "exports", "module", "state", "o", "secret", "censor", "compileRestore", "serialize", "groupRedact", "nestedRedact", "wildcards", "wcLen", "builder", "require_fast_redact", "__commonJSMin", "exports", "module", "validator", "parse", "redactor", "restorer", "groupRedact", "nestedRedact", "state", "rx", "validate", "noop", "o", "DEFAULT_CENSOR", "fastRedact", "opts", "paths", "serialize", "remove", "censor", "isCensorFct", "censorFctTakesPath", "wildcards", "wcLen", "secret", "compileRestore", "strict", "require_symbols", "__commonJSMin", "exports", "module", "setLevelSym", "getLevelSym", "levelValSym", "levelCompSym", "useLevelLabelsSym", "useOnlyCustomLevelsSym", "mixinSym", "lsCacheSym", "chindingsSym", "asJsonSym", "writeSym", "redactFmtSym", "timeSym", "timeSliceIndexSym", "streamSym", "stringifySym", "stringifySafeSym", "stringifiersSym", "endSym", "formatOptsSym", "messageKeySym", "errorKeySym", "nestedKeySym", "nestedKeyStrSym", "mixinMergeStrategySym", "msgPrefixSym", "wildcardFirstSym", "serializersSym", "formattersSym", "hooksSym", "needsMetadataGsym", "require_redaction", "__commonJSMin", "exports", "module", "fastRedact", "redactFmtSym", "wildcardFirstSym", "rx", "validator", "validate", "s", "CENSOR", "strict", "redaction", "opts", "serialize", "paths", "censor", "handle", "shape", "o", "str", "first", "next", "ns", "index", "nextPath", "k", "result", "topCensor", "args", "value", "wrappedCensor", "path", "remove", "require_time", "__commonJSMin", "exports", "module", "nullTime", "epochTime", "unixTime", "isoTime", "require_quick_format_unescaped", "__commonJSMin", "exports", "module", "tryStringify", "o", "format", "f", "args", "opts", "ss", "offset", "len", "objects", "index", "argLen", "str", "a", "lastPos", "flen", "i", "type", "require_atomic_sleep", "__commonJSMin", "exports", "module", "sleep", "ms", "nil", "target", "require_sonic_boom", "__commonJSMin", "exports", "module", "fs", "EventEmitter", "inherits", "path", "sleep", "assert", "BUSY_WRITE_TIMEOUT", "kEmptyBuffer", "MAX_WRITE", "kContentModeBuffer", "kContentModeUtf8", "major", "minor", "kCopyBuffer", "openFile", "file", "sonic", "fileOpened", "err", "fd", "reopening", "flags", "mode", "SonicBoom", "opts", "dest", "minLength", "maxLength", "maxWrite", "periodicFlush", "sync", "append", "mkdir", "retryEAGAIN", "fsync", "contentMode", "fsWriteSync", "fsWrite", "writeBuffer", "flushBuffer", "flushBufferSync", "actualWriteBuffer", "write", "flush", "flushSync", "actualWrite", "n", "releasedBufObj", "releaseWritingBuf", "len", "actualClose", "emitDrain", "name", "writingBuf", "mergeBuf", "bufs", "data", "lens", "callFlushCallbackOnDrain", "cb", "onDrain", "onError", "error", "buf", "release", "written", "closeWrapped", "done", "require_on_exit_leak_free", "__commonJSMin", "exports", "module", "refs", "functions", "onExit", "onBeforeExit", "registry", "ensureRegistry", "clear", "install", "event", "uninstall", "callRefs", "ref", "obj", "fn", "index", "_register", "register", "registerBeforeExit", "unregister", "_obj", "require_package", "__commonJSMin", "exports", "module", "require_wait", "__commonJSMin", "exports", "module", "wait", "state", "index", "expected", "timeout", "done", "max", "current", "prior", "check", "backoff", "waitDiff", "require_indexes", "__commonJSMin", "exports", "module", "require_thread_stream", "__commonJSMin", "exports", "module", "version", "EventEmitter", "Worker", "join", "pathToFileURL", "wait", "WRITE_INDEX", "READ_INDEX", "buffer", "assert", "kImpl", "MAX_STRING", "FakeWeakRef", "value", "FakeFinalizationRegistry", "FinalizationRegistry", "WeakRef", "registry", "worker", "createWorker", "stream", "opts", "filename", "workerData", "toExecute", "onWorkerMessage", "onWorkerExit", "drain", "nextFlush", "writeIndex", "leftover", "end", "toWrite", "toWriteBytes", "write", "destroy", "msg", "code", "ThreadStream", "message", "transferList", "data", "error", "writeSync", "err", "cb", "res", "flushSync", "current", "length", "readIndex", "spins", "require_transport", "__commonJSMin", "exports", "module", "createRequire", "getCallers", "join", "isAbsolute", "sep", "sleep", "onExit", "ThreadStream", "setupOnExit", "stream", "autoEnd", "flush", "buildStream", "filename", "workerData", "workerOpts", "sync", "onReady", "transport", "fullOptions", "pipeline", "targets", "levels", "dedupe", "worker", "caller", "options", "callers", "bundlerOverrides", "target", "dest", "fixTarget", "t", "origin", "filePath", "context", "require_tools", "__commonJSMin", "exports", "module", "format", "mapHttpRequest", "mapHttpResponse", "SonicBoom", "onExit", "lsCacheSym", "chindingsSym", "writeSym", "serializersSym", "formatOptsSym", "endSym", "stringifiersSym", "stringifySym", "stringifySafeSym", "wildcardFirstSym", "nestedKeySym", "formattersSym", "messageKeySym", "errorKeySym", "nestedKeyStrSym", "msgPrefixSym", "isMainThread", "transport", "noop", "genLog", "level", "hook", "LOG", "args", "o", "n", "msg", "formatParams", "asString", "str", "result", "last", "found", "point", "l", "i", "asJson", "obj", "num", "time", "stringify", "stringifySafe", "stringifiers", "end", "chindings", "serializers", "formatters", "messageKey", "errorKey", "data", "value", "wildcardStringifier", "propStr", "key", "stringifier", "strKey", "msgStr", "asChindings", "instance", "bindings", "formatter", "hasBeenTampered", "stream", "buildSafeSonicBoom", "opts", "filterBrokenPipe", "autoEnd", "err", "eventName", "createArgsNormalizer", "defaultOptions", "caller", "customLevels", "enabled", "onChild", "stringifySafeFn", "buildFormatters", "log", "normalizeDestFileDescriptor", "destination", "fd", "require_constants", "__commonJSMin", "exports", "module", "DEFAULT_LEVELS", "SORTING_ORDER", "require_levels", "__commonJSMin", "exports", "module", "lsCacheSym", "levelValSym", "useOnlyCustomLevelsSym", "streamSym", "formattersSym", "hooksSym", "levelCompSym", "noop", "genLog", "DEFAULT_LEVELS", "SORTING_ORDER", "levelMethods", "hook", "logFatal", "args", "stream", "nums", "o", "k", "initialLsCache", "genLsCache", "instance", "formatter", "labels", "cache", "label", "level", "isStandardLevel", "useOnlyCustomLevels", "setLevel", "values", "preLevelVal", "levelVal", "useOnlyCustomLevelsVal", "levelComparison", "key", "getLevel", "levels", "isLevelEnabled", "logLevel", "logLevelVal", "compareLevel", "direction", "current", "expected", "genLevelComparison", "mappings", "customLevels", "customNums", "assertDefaultLevelFound", "defaultLevel", "assertNoLevelCollisions", "assertLevelComparison", "require_meta", "__commonJSMin", "exports", "module", "require_proto", "__commonJSMin", "exports", "module", "EventEmitter", "lsCacheSym", "levelValSym", "setLevelSym", "getLevelSym", "chindingsSym", "parsedChindingsSym", "mixinSym", "asJsonSym", "writeSym", "mixinMergeStrategySym", "timeSym", "timeSliceIndexSym", "streamSym", "serializersSym", "formattersSym", "errorKeySym", "messageKeySym", "useOnlyCustomLevelsSym", "needsMetadataGsym", "redactFmtSym", "stringifySym", "formatOptsSym", "stringifiersSym", "msgPrefixSym", "hooksSym", "getLevel", "setLevel", "isLevelEnabled", "mappings", "initialLsCache", "genLsCache", "assertNoLevelCollisions", "asChindings", "asJson", "buildFormatters", "stringify", "version", "redaction", "constructor", "prototype", "child", "bindings", "setBindings", "flush", "lvl", "n", "write", "resetChildingsFormatter", "options", "serializers", "formatters", "instance", "k", "parentSymbols", "i", "ks", "bk", "bindingsSymbols", "bi", "bks", "level", "chindings", "log", "stringifiers", "formatOpts", "childLevel", "chindingsJson", "bindingsFromJson", "newBindings", "defaultMixinMergeStrategy", "mergeObject", "mixinObject", "_obj", "msg", "num", "t", "mixin", "errorKey", "messageKey", "mixinMergeStrategy", "obj", "streamWriteHook", "s", "stream", "noop", "cb", "require_safe_stable_stringify", "__commonJSMin", "exports", "module", "hasOwnProperty", "stringify", "configure", "strEscapeSequencesRegExp", "strEscape", "str", "sort", "array", "comparator", "i", "currentValue", "position", "typedArrayPrototypeGetSymbolToStringTag", "isTypedArrayWithEntries", "value", "stringifyTypedArray", "separator", "maximumBreadth", "whitespace", "res", "getCircularValueOption", "options", "circularValue", "getDeterministicOption", "getBooleanOption", "key", "getPositiveIntegerOption", "getItemCount", "number", "getUniqueReplacerSet", "replacerArray", "replacerSet", "getStrictOption", "message", "fail", "bigint", "deterministic", "maximumDepth", "stringifyFnReplacer", "parent", "stack", "replacer", "spacer", "indentation", "join", "originalIndentation", "maximumValuesToStringify", "tmp", "removedKeys", "keys", "keyLength", "maximumPropertiesToStringify", "stringifyArrayReplacer", "stringifyIndent", "stringifySimple", "hasLength", "space", "require_multistream", "__commonJSMin", "exports", "module", "metadata", "DEFAULT_LEVELS", "DEFAULT_INFO_LEVEL", "multistream", "streamsArray", "opts", "counter", "streamLevels", "i", "res", "write", "add", "emit", "flushSync", "end", "clone", "data", "dest", "level", "streams", "recordedLevel", "stream", "initLoopVar", "checkLoopVar", "adjustLoopVar", "lastTime", "lastMsg", "lastObj", "lastLogger", "args", "isStream", "stream_", "dest_", "compareByLevel", "a", "b", "length", "dedupe", "require_pino", "__commonJSMin", "exports", "module", "pinoBundlerAbsolutePath", "p", "os", "stdSerializers", "caller", "redaction", "time", "proto", "symbols", "configure", "assertDefaultLevelFound", "mappings", "genLsCache", "genLevelComparison", "assertLevelComparison", "DEFAULT_LEVELS", "SORTING_ORDER", "createArgsNormalizer", "asChindings", "buildSafeSonicBoom", "buildFormatters", "stringify", "normalizeDestFileDescriptor", "noop", "version", "chindingsSym", "redactFmtSym", "serializersSym", "timeSym", "timeSliceIndexSym", "streamSym", "stringifySym", "stringifySafeSym", "stringifiersSym", "setLevelSym", "endSym", "formatOptsSym", "messageKeySym", "errorKeySym", "nestedKeySym", "mixinSym", "levelCompSym", "useOnlyCustomLevelsSym", "formattersSym", "hooksSym", "nestedKeyStrSym", "mixinMergeStrategySym", "msgPrefixSym", "epochTime", "nullTime", "pid", "hostname", "defaultErrorSerializer", "defaultOptions", "bindings", "label", "number", "normalize", "serializers", "pino", "args", "instance", "opts", "stream", "redact", "crlf", "timestamp", "messageKey", "errorKey", "nestedKey", "base", "name", "level", "customLevels", "levelComparison", "mixin", "mixinMergeStrategy", "useOnlyCustomLevels", "formatters", "hooks", "depthLimit", "edgeLimit", "onChild", "msgPrefix", "stringifySafe", "allFormatters", "stringifyFn", "stringifiers", "formatOpts", "end", "coreChindings", "chindings", "timeSliceIndex", "levels", "levelCompFunc", "dest", "require_file", "__commonJSMin", "exports", "module", "pino", "once", "opts", "destOpts", "destination"] +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-roll.mjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-roll.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0c72a36dcd8fd47537058a0485dbe29d6995ee61 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-roll.mjs @@ -0,0 +1,2 @@ +var re=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var s=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports);var Xo=s((FW,Mr)=>{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let r=function(t){if((t>0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(e,0,0,Number(t))},e=new Int32Array(new SharedArrayBuffer(4));Mr.exports=r}else{let e=function(r){if((r>0&&r<1/0)===!1)throw typeof r!="number"&&typeof r!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let n=Date.now()+Number(r);for(;n>Date.now(););};Mr.exports=e}});var ec=s((NW,ko)=>{"use strict";var j=re("fs"),ev=re("events"),rv=re("util").inherits,Vo=re("path"),wr=Xo(),tv=re("assert"),Ae=100,$e=Buffer.allocUnsafe(0),nv=16*1024,Go="buffer",Uo="utf8",[iv,uv]=(process.versions.node||"0.0").split(".").map(Number),av=iv>=22&&uv>=7;function Jo(e,r){r._opening=!0,r._writing=!0,r._asyncDrainScheduled=!1;function t(a,o){if(a){r._reopening=!1,r._writing=!1,r._opening=!1,r.sync?process.nextTick(()=>{r.listenerCount("error")>0&&r.emit("error",a)}):r.emit("error",a);return}let c=r._reopening;r.fd=o,r.file=e,r._reopening=!1,r._opening=!1,r._writing=!1,r.sync?process.nextTick(()=>r.emit("ready")):r.emit("ready"),!r.destroyed&&(!r._writing&&r._len>r.minLength||r._flushPending?r._actualWrite():c&&process.nextTick(()=>r.emit("drain")))}let n=r.append?"a":"w",u=r.mode;if(r.sync)try{r.mkdir&&j.mkdirSync(Vo.dirname(e),{recursive:!0});let a=j.openSync(e,n,u);t(null,a)}catch(a){throw t(a),a}else r.mkdir?j.mkdir(Vo.dirname(e),{recursive:!0},a=>{if(a)return t(a);j.open(e,n,u,t)}):j.open(e,n,u,t)}function F(e){if(!(this instanceof F))return new F(e);let{fd:r,dest:t,minLength:n,maxLength:u,maxWrite:a,periodicFlush:o,sync:c,append:f=!0,mkdir:d,retryEAGAIN:h,fsync:_,contentMode:g,mode:p}=e||{};r=r||t,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(n||0,16387),this.file=null,this.destroyed=!1,this.minLength=n||0,this.maxLength=u||0,this.maxWrite=a||nv,this._periodicFlush=o||0,this._periodicFlushTimer=void 0,this.sync=c||!1,this.writable=!0,this._fsync=_||!1,this.append=f||!1,this.mode=p,this.retryEAGAIN=h||(()=>!0),this.mkdir=d||!1;let q,x;if(g===Go)this._writingBuf=$e,this.write=cv,this.flush=dv,this.flushSync=hv,this._actualWrite=mv,q=()=>j.writeSync(this.fd,this._writingBuf),x=()=>j.write(this.fd,this._writingBuf,this.release);else if(g===void 0||g===Uo)this._writingBuf="",this.write=ov,this.flush=fv,this.flushSync=lv,this._actualWrite=_v,q=()=>j.writeSync(this.fd,this._writingBuf,"utf8"),x=()=>j.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${Uo}" and "${Go}", but passed ${g}`);if(typeof r=="number")this.fd=r,process.nextTick(()=>this.emit("ready"));else if(typeof r=="string")Jo(r,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(m,D)=>{if(m){if((m.code==="EAGAIN"||m.code==="EBUSY")&&this.retryEAGAIN(m,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{wr(Ae),this.release(void 0,0)}catch(Q){this.release(Q)}else setTimeout(x,Ae);else this._writing=!1,this.emit("error",m);return}this.emit("write",D);let E=Dr(this._writingBuf,this._len,D);if(this._len=E.len,this._writingBuf=E.writingBuf,this._writingBuf.length){if(!this.sync){x();return}try{do{let Q=q(),be=Dr(this._writingBuf,this._len,Q);this._len=be.len,this._writingBuf=be.writingBuf}while(this._writingBuf.length)}catch(Q){this.release(Q);return}}this._fsync&&j.fsyncSync(this.fd);let B=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):B>this.minLength?this._actualWrite():this._ending?B>0?this._actualWrite():(this._writing=!1,Ze(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(sv,this)):this.emit("drain"))},this.on("newListener",function(m){m==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function Dr(e,r,t){return typeof e=="string"&&Buffer.byteLength(e)!==t&&(t=Buffer.from(e).subarray(0,t).toString().length),r=Math.max(r-t,0),e=e.slice(t),{writingBuf:e,len:r}}function sv(e){e.listenerCount("drain")>0&&(e._asyncDrainScheduled=!1,e.emit("drain"))}rv(F,ev);function Ko(e,r){return e.length===0?$e:e.length===1?e[0]:Buffer.concat(e,r)}function ov(e){if(this.destroyed)throw new Error("SonicBoom destroyed");let r=this._len+e.length,t=this._bufs;return this.maxLength&&r>this.maxLength?(this.emit("drop",e),this._lenthis.maxWrite?t.push(""+e):t[t.length-1]+=e,this._len=r,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._lenthis.maxLength?(this.emit("drop",e),this._lenthis.maxWrite?(t.push([e]),n.push(e.length)):(t[t.length-1].push(e),n[n.length-1]+=e.length),this._len=r,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len{if(this._fsync)this._flushPending=!1,e();else try{j.fsync(this.fd,n=>{this._flushPending=!1,e(n)})}catch(n){e(n)}this.off("error",t)},t=n=>{this._flushPending=!1,e(n),this.off("drain",r)};this.once("drain",r),this.once("error",t)}function fv(e){if(e!=null&&typeof e!="function")throw new Error("flush cb must be a function");if(this.destroyed){let r=new Error("SonicBoom destroyed");if(e){e(r);return}throw r}if(this.minLength<=0){e?.();return}e&&yo.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function dv(e){if(e!=null&&typeof e!="function")throw new Error("flush cb must be a function");if(this.destroyed){let r=new Error("SonicBoom destroyed");if(e){e(r);return}throw r}if(this.minLength<=0){e?.();return}e&&yo.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}F.prototype.reopen=function(e){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(e&&(this.file=e),this._reopening=!0,this._writing)return;let r=this.fd;this.once("ready",()=>{r!==this.fd&&j.close(r,t=>{if(t)return this.emit("error",t)})}),Jo(this.file,this)};F.prototype.end=function(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():Ze(this)))};function lv(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let e="";for(;this._bufs.length||e;){e.length<=0&&(e=this._bufs[0]);try{let r=j.writeSync(this.fd,e,"utf8"),t=Dr(e,this._len,r);e=t.writingBuf,this._len=t.len,e.length<=0&&this._bufs.shift()}catch(r){if((r.code==="EAGAIN"||r.code==="EBUSY")&&!this.retryEAGAIN(r,e.length,this._len-e.length))throw r;wr(Ae)}}try{j.fsyncSync(this.fd)}catch{}}function hv(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=$e);let e=$e;for(;this._bufs.length||e.length;){e.length<=0&&(e=Ko(this._bufs[0],this._lens[0]));try{let r=j.writeSync(this.fd,e);e=e.subarray(r),this._len=Math.max(this._len-r,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(r){if((r.code==="EAGAIN"||r.code==="EBUSY")&&!this.retryEAGAIN(r,e.length,this._len-e.length))throw r;wr(Ae)}}}F.prototype.destroy=function(){this.destroyed||Ze(this)};function _v(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf||this._bufs.shift()||"",this.sync)try{let r=j.writeSync(this.fd,this._writingBuf,"utf8");e(null,r)}catch(r){e(r)}else j.write(this.fd,this._writingBuf,"utf8",e)}function mv(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:Ko(this._bufs.shift(),this._lens.shift()),this.sync)try{let r=j.writeSync(this.fd,this._writingBuf);e(null,r)}catch(r){e(r)}else av&&(this._writingBuf=Buffer.from(this._writingBuf)),j.write(this.fd,this._writingBuf,e)}function Ze(e){if(e.fd===-1){e.once("ready",Ze.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],tv(typeof e.fd=="number",`sonic.fd must be a number, got ${typeof e.fd}`);try{j.fsync(e.fd,r)}catch{}function r(){e.fd!==1&&e.fd!==2?j.close(e.fd,t):t()}function t(n){if(n){e.emit("error",n);return}e._ending&&!e._writing&&e.emit("finish"),e.emit("close")}}F.SonicBoom=F;F.default=F;ko.exports=F});var O=s(v=>{"use strict";v.secondsInYear=v.secondsInWeek=v.secondsInQuarter=v.secondsInMonth=v.secondsInMinute=v.secondsInHour=v.secondsInDay=v.quartersInYear=v.monthsInYear=v.monthsInQuarter=v.minutesInYear=v.minutesInMonth=v.minutesInHour=v.minutesInDay=v.minTime=v.millisecondsInWeek=v.millisecondsInSecond=v.millisecondsInMinute=v.millisecondsInHour=v.millisecondsInDay=v.maxTime=v.daysInYear=v.daysInWeek=v.constructFromSymbol=void 0;var HW=v.daysInWeek=7,bv=v.daysInYear=365.2425,gv=v.maxTime=Math.pow(10,8)*24*60*60*1e3,LW=v.minTime=-gv,CW=v.millisecondsInWeek=6048e5,zW=v.millisecondsInDay=864e5,BW=v.millisecondsInMinute=6e4,QW=v.millisecondsInHour=36e5,RW=v.millisecondsInSecond=1e3,AW=v.minutesInYear=525600,$W=v.minutesInMonth=43200,ZW=v.minutesInDay=1440,XW=v.minutesInHour=60,VW=v.monthsInQuarter=3,GW=v.monthsInYear=12,UW=v.quartersInYear=4,vv=v.secondsInHour=3600,JW=v.secondsInMinute=60,rc=v.secondsInDay=vv*24,KW=v.secondsInWeek=rc*7,xv=v.secondsInYear=rc*bv,Ov=v.secondsInMonth=xv/12,yW=v.secondsInQuarter=Ov*3,kW=v.constructFromSymbol=Symbol.for("constructDateFrom")});var b=s(nc=>{"use strict";nc.constructFrom=qv;var tc=O();function qv(e,r){return typeof e=="function"?e(r):e&&typeof e=="object"&&tc.constructFromSymbol in e?e[tc.constructFromSymbol](r):e instanceof Date?new e.constructor(r):new Date(r)}});var l=s(ic=>{"use strict";ic.toDate=Mv;var pv=b();function Mv(e,r){return(0,pv.constructFrom)(r||e,e)}});var H=s(uc=>{"use strict";uc.addDays=Pv;var Dv=b(),wv=l();function Pv(e,r,t){let n=(0,wv.toDate)(e,t?.in);return isNaN(r)?(0,Dv.constructFrom)(t?.in||e,NaN):(r&&n.setDate(n.getDate()+r),n)}});var oe=s(sc=>{"use strict";sc.addMonths=Iv;var ac=b(),jv=l();function Iv(e,r,t){let n=(0,jv.toDate)(e,t?.in);if(isNaN(r))return(0,ac.constructFrom)(t?.in||e,NaN);if(!r)return n;let u=n.getDate(),a=(0,ac.constructFrom)(t?.in||e,n.getTime());a.setMonth(n.getMonth()+r+1,0);let o=a.getDate();return u>=o?a:(n.setFullYear(a.getFullYear(),a.getMonth(),u),n)}});var Pr=s(oc=>{"use strict";oc.add=Sv;var Tv=H(),Ev=oe(),Yv=b(),Wv=l();function Sv(e,r,t){let{years:n=0,months:u=0,weeks:a=0,days:o=0,hours:c=0,minutes:f=0,seconds:d=0}=r,h=(0,Wv.toDate)(e,t?.in),_=u||n?(0,Ev.addMonths)(h,u+n*12):h,g=o||a?(0,Tv.addDays)(_,o+a*7):_,p=f+c*60,x=(d+p*60)*1e3;return(0,Yv.constructFrom)(t?.in||e,+g+x)}});var jr=s(cc=>{"use strict";cc.isSaturday=Nv;var Fv=l();function Nv(e,r){return(0,Fv.toDate)(e,r?.in).getDay()===6}});var Ir=s(fc=>{"use strict";fc.isSunday=Lv;var Hv=l();function Lv(e,r){return(0,Hv.toDate)(e,r?.in).getDay()===0}});var ge=s(dc=>{"use strict";dc.isWeekend=zv;var Cv=l();function zv(e,r){let t=(0,Cv.toDate)(e,r?.in).getDay();return t===0||t===6}});var Er=s(lc=>{"use strict";lc.addBusinessDays=$v;var Bv=b(),Qv=jr(),Rv=Ir(),Tr=ge(),Av=l();function $v(e,r,t){let n=(0,Av.toDate)(e,t?.in),u=(0,Tr.isWeekend)(n,t);if(isNaN(r))return(0,Bv.constructFrom)(t?.in,NaN);let a=n.getHours(),o=r<0?-1:1,c=Math.trunc(r/5);n.setDate(n.getDate()+c*7);let f=Math.abs(r%5);for(;f>0;)n.setDate(n.getDate()+o),(0,Tr.isWeekend)(n,t)||(f-=1);return u&&(0,Tr.isWeekend)(n,t)&&r!==0&&((0,Qv.isSaturday)(n,t)&&n.setDate(n.getDate()+(o<0?2:-1)),(0,Rv.isSunday)(n,t)&&n.setDate(n.getDate()+(o<0?1:-2))),n.setHours(a),n}});var ve=s(hc=>{"use strict";hc.addMilliseconds=Vv;var Zv=b(),Xv=l();function Vv(e,r,t){return(0,Zv.constructFrom)(t?.in||e,+(0,Xv.toDate)(e)+r)}});var Yr=s(_c=>{"use strict";_c.addHours=Jv;var Gv=ve(),Uv=O();function Jv(e,r,t){return(0,Gv.addMilliseconds)(e,r*Uv.millisecondsInHour,t)}});var Y=s(Wr=>{"use strict";Wr.getDefaultOptions=Kv;Wr.setDefaultOptions=yv;var mc={};function Kv(){return mc}function yv(e){mc=e}});var N=s(bc=>{"use strict";bc.startOfWeek=rx;var kv=Y(),ex=l();function rx(e,r){let t=(0,kv.getDefaultOptions)(),n=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,u=(0,ex.toDate)(e,r?.in),a=u.getDay(),o=(a{"use strict";gc.startOfISOWeek=nx;var tx=N();function nx(e,r){return(0,tx.startOfWeek)(e,{...r,weekStartsOn:1})}});var U=s(Oc=>{"use strict";Oc.getISOWeekYear=ux;var vc=b(),xc=L(),ix=l();function ux(e,r){let t=(0,ix.toDate)(e,r?.in),n=t.getFullYear(),u=(0,vc.constructFrom)(t,0);u.setFullYear(n+1,0,4),u.setHours(0,0,0,0);let a=(0,xc.startOfISOWeek)(u),o=(0,vc.constructFrom)(t,0);o.setFullYear(n,0,4),o.setHours(0,0,0,0);let c=(0,xc.startOfISOWeek)(o);return t.getTime()>=a.getTime()?n+1:t.getTime()>=c.getTime()?n:n-1}});var R=s(qc=>{"use strict";qc.getTimezoneOffsetInMilliseconds=sx;var ax=l();function sx(e){let r=(0,ax.toDate)(e),t=new Date(Date.UTC(r.getFullYear(),r.getMonth(),r.getDate(),r.getHours(),r.getMinutes(),r.getSeconds(),r.getMilliseconds()));return t.setUTCFullYear(r.getFullYear()),+e-+t}});var P=s(pc=>{"use strict";pc.normalizeDates=cx;var ox=b();function cx(e,...r){let t=ox.constructFrom.bind(null,e||r.find(n=>typeof n=="object"));return r.map(t)}});var xe=s(Mc=>{"use strict";Mc.startOfDay=dx;var fx=l();function dx(e,r){let t=(0,fx.toDate)(e,r?.in);return t.setHours(0,0,0,0),t}});var A=s(Pc=>{"use strict";Pc.differenceInCalendarDays=_x;var Dc=R(),lx=P(),hx=O(),wc=xe();function _x(e,r,t){let[n,u]=(0,lx.normalizeDates)(t?.in,e,r),a=(0,wc.startOfDay)(n),o=(0,wc.startOfDay)(u),c=+a-(0,Dc.getTimezoneOffsetInMilliseconds)(a),f=+o-(0,Dc.getTimezoneOffsetInMilliseconds)(o);return Math.round((c-f)/hx.millisecondsInDay)}});var ce=s(jc=>{"use strict";jc.startOfISOWeekYear=vx;var mx=b(),bx=U(),gx=L();function vx(e,r){let t=(0,bx.getISOWeekYear)(e,r),n=(0,mx.constructFrom)(r?.in||e,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),(0,gx.startOfISOWeek)(n)}});var Sr=s(Tc=>{"use strict";Tc.setISOWeekYear=px;var xx=b(),Ox=A(),Ic=ce(),qx=l();function px(e,r,t){let n=(0,qx.toDate)(e,t?.in),u=(0,Ox.differenceInCalendarDays)(n,(0,Ic.startOfISOWeekYear)(n,t)),a=(0,xx.constructFrom)(t?.in||e,0);return a.setFullYear(r,0,4),a.setHours(0,0,0,0),n=(0,Ic.startOfISOWeekYear)(a),n.setDate(n.getDate()+u),n}});var Fr=s(Ec=>{"use strict";Ec.addISOWeekYears=wx;var Mx=U(),Dx=Sr();function wx(e,r,t){return(0,Dx.setISOWeekYear)(e,(0,Mx.getISOWeekYear)(e,t)+r,t)}});var Xe=s(Yc=>{"use strict";Yc.addMinutes=Ix;var Px=O(),jx=l();function Ix(e,r,t){let n=(0,jx.toDate)(e,t?.in);return n.setTime(n.getTime()+r*Px.millisecondsInMinute),n}});var Ve=s(Wc=>{"use strict";Wc.addQuarters=Ex;var Tx=oe();function Ex(e,r,t){return(0,Tx.addMonths)(e,r*3,t)}});var Nr=s(Sc=>{"use strict";Sc.addSeconds=Wx;var Yx=ve();function Wx(e,r,t){return(0,Yx.addMilliseconds)(e,r*1e3,t)}});var Oe=s(Fc=>{"use strict";Fc.addWeeks=Fx;var Sx=H();function Fx(e,r,t){return(0,Sx.addDays)(e,r*7,t)}});var Hr=s(Nc=>{"use strict";Nc.addYears=Hx;var Nx=oe();function Hx(e,r,t){return(0,Nx.addMonths)(e,r*12,t)}});var Lc=s(Hc=>{"use strict";Hc.areIntervalsOverlapping=Lx;var Ge=l();function Lx(e,r,t){let[n,u]=[+(0,Ge.toDate)(e.start,t?.in),+(0,Ge.toDate)(e.end,t?.in)].sort((c,f)=>c-f),[a,o]=[+(0,Ge.toDate)(r.start,t?.in),+(0,Ge.toDate)(r.end,t?.in)].sort((c,f)=>c-f);return t?.inclusive?n<=o&&a<=u:n{"use strict";zc.max=zx;var Cc=b(),Cx=l();function zx(e,r){let t,n=r?.in;return e.forEach(u=>{!n&&typeof u=="object"&&(n=Cc.constructFrom.bind(null,u));let a=(0,Cx.toDate)(u,n);(!t||t{"use strict";Qc.min=Qx;var Bc=b(),Bx=l();function Qx(e,r){let t,n=r?.in;return e.forEach(u=>{!n&&typeof u=="object"&&(n=Bc.constructFrom.bind(null,u));let a=(0,Bx.toDate)(u,n);(!t||t>a||isNaN(+a))&&(t=a)}),(0,Bc.constructFrom)(n,t||NaN)}});var Ac=s(Rc=>{"use strict";Rc.clamp=Zx;var Rx=P(),Ax=Lr(),$x=Cr();function Zx(e,r,t){let[n,u,a]=(0,Rx.normalizeDates)(t?.in,e,r.start,r.end);return(0,$x.min)([(0,Ax.max)([n,u],t),a],t)}});var zr=s(Zc=>{"use strict";Zc.closestIndexTo=Xx;var $c=l();function Xx(e,r){let t=+(0,$c.toDate)(e);if(isNaN(t))return NaN;let n,u;return r.forEach((a,o)=>{let c=(0,$c.toDate)(a);if(isNaN(+c)){n=NaN,u=NaN;return}let f=Math.abs(t-+c);(n==null||f{"use strict";Xc.closestTo=Jx;var Vx=P(),Gx=zr(),Ux=b();function Jx(e,r,t){let[n,...u]=(0,Vx.normalizeDates)(t?.in,e,...r),a=(0,Gx.closestIndexTo)(n,u);if(typeof a=="number"&&isNaN(a))return(0,Ux.constructFrom)(n,NaN);if(a!==void 0)return u[a]}});var te=s(Uc=>{"use strict";Uc.compareAsc=Kx;var Gc=l();function Kx(e,r){let t=+(0,Gc.toDate)(e)-+(0,Gc.toDate)(r);return t<0?-1:t>0?1:t}});var yc=s(Kc=>{"use strict";Kc.compareDesc=yx;var Jc=l();function yx(e,r){let t=+(0,Jc.toDate)(e)-+(0,Jc.toDate)(r);return t>0?-1:t<0?1:t}});var T=s(kc=>{"use strict";kc.constructNow=eO;var kx=b();function eO(e){return(0,kx.constructFrom)(e,Date.now())}});var rf=s(ef=>{"use strict";ef.daysToWeeks=tO;var rO=O();function tO(e){let r=Math.trunc(e/rO.daysInWeek);return r===0?0:r}});var fe=s(nf=>{"use strict";nf.isSameDay=iO;var nO=P(),tf=xe();function iO(e,r,t){let[n,u]=(0,nO.normalizeDates)(t?.in,e,r);return+(0,tf.startOfDay)(n)==+(0,tf.startOfDay)(u)}});var Br=s(uf=>{"use strict";uf.isDate=uO;function uO(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}});var $=s(af=>{"use strict";af.isValid=oO;var aO=Br(),sO=l();function oO(e){return!(!(0,aO.isDate)(e)&&typeof e!="number"||isNaN(+(0,sO.toDate)(e)))}});var ff=s(cf=>{"use strict";cf.differenceInBusinessDays=hO;var cO=P(),sf=H(),fO=A(),dO=fe(),of=$(),lO=ge();function hO(e,r,t){let[n,u]=(0,cO.normalizeDates)(t?.in,e,r);if(!(0,of.isValid)(n)||!(0,of.isValid)(u))return NaN;let a=(0,fO.differenceInCalendarDays)(n,u),o=a<0?-1:1,c=Math.trunc(a/7),f=c*5,d=(0,sf.addDays)(u,c*7);for(;!(0,dO.isSameDay)(n,d);)f+=(0,lO.isWeekend)(d,t)?0:o,d=(0,sf.addDays)(d,o);return f===0?0:f}});var Qr=s(lf=>{"use strict";lf.differenceInCalendarISOWeekYears=mO;var _O=P(),df=U();function mO(e,r,t){let[n,u]=(0,_O.normalizeDates)(t?.in,e,r);return(0,df.getISOWeekYear)(n,t)-(0,df.getISOWeekYear)(u,t)}});var bf=s(mf=>{"use strict";mf.differenceInCalendarISOWeeks=vO;var hf=R(),bO=P(),gO=O(),_f=L();function vO(e,r,t){let[n,u]=(0,bO.normalizeDates)(t?.in,e,r),a=(0,_f.startOfISOWeek)(n),o=(0,_f.startOfISOWeek)(u),c=+a-(0,hf.getTimezoneOffsetInMilliseconds)(a),f=+o-(0,hf.getTimezoneOffsetInMilliseconds)(o);return Math.round((c-f)/gO.millisecondsInWeek)}});var Ue=s(gf=>{"use strict";gf.differenceInCalendarMonths=OO;var xO=P();function OO(e,r,t){let[n,u]=(0,xO.normalizeDates)(t?.in,e,r),a=n.getFullYear()-u.getFullYear(),o=n.getMonth()-u.getMonth();return a*12+o}});var Rr=s(vf=>{"use strict";vf.getQuarter=pO;var qO=l();function pO(e,r){let t=(0,qO.toDate)(e,r?.in);return Math.trunc(t.getMonth()/3)+1}});var Ar=s(Of=>{"use strict";Of.differenceInCalendarQuarters=DO;var MO=P(),xf=Rr();function DO(e,r,t){let[n,u]=(0,MO.normalizeDates)(t?.in,e,r),a=n.getFullYear()-u.getFullYear(),o=(0,xf.getQuarter)(n)-(0,xf.getQuarter)(u);return a*4+o}});var Je=s(Mf=>{"use strict";Mf.differenceInCalendarWeeks=jO;var qf=R(),wO=P(),PO=O(),pf=N();function jO(e,r,t){let[n,u]=(0,wO.normalizeDates)(t?.in,e,r),a=(0,pf.startOfWeek)(n,t),o=(0,pf.startOfWeek)(u,t),c=+a-(0,qf.getTimezoneOffsetInMilliseconds)(a),f=+o-(0,qf.getTimezoneOffsetInMilliseconds)(o);return Math.round((c-f)/PO.millisecondsInWeek)}});var Ke=s(Df=>{"use strict";Df.differenceInCalendarYears=TO;var IO=P();function TO(e,r,t){let[n,u]=(0,IO.normalizeDates)(t?.in,e,r);return n.getFullYear()-u.getFullYear()}});var ye=s(Pf=>{"use strict";Pf.differenceInDays=WO;var EO=P(),YO=A();function WO(e,r,t){let[n,u]=(0,EO.normalizeDates)(t?.in,e,r),a=wf(n,u),o=Math.abs((0,YO.differenceInCalendarDays)(n,u));n.setDate(n.getDate()-a*o);let c=+(wf(n,u)===-a),f=a*(o-c);return f===0?0:f}function wf(e,r){let t=e.getFullYear()-r.getFullYear()||e.getMonth()-r.getMonth()||e.getDate()-r.getDate()||e.getHours()-r.getHours()||e.getMinutes()-r.getMinutes()||e.getSeconds()-r.getSeconds()||e.getMilliseconds()-r.getMilliseconds();return t<0?-1:t>0?1:t}});var Z=s(jf=>{"use strict";jf.getRoundingMethod=SO;function SO(e){return r=>{let n=(e?Math[e]:Math.trunc)(r);return n===0?0:n}}});var ke=s(If=>{"use strict";If.differenceInHours=LO;var FO=Z(),NO=P(),HO=O();function LO(e,r,t){let[n,u]=(0,NO.normalizeDates)(t?.in,e,r),a=(+n-+u)/HO.millisecondsInHour;return(0,FO.getRoundingMethod)(t?.roundingMethod)(a)}});var $r=s(Tf=>{"use strict";Tf.subISOWeekYears=zO;var CO=Fr();function zO(e,r,t){return(0,CO.addISOWeekYears)(e,-r,t)}});var Wf=s(Yf=>{"use strict";Yf.differenceInISOWeekYears=AO;var BO=P(),Ef=te(),QO=Qr(),RO=$r();function AO(e,r,t){let[n,u]=(0,BO.normalizeDates)(t?.in,e,r),a=(0,Ef.compareAsc)(n,u),o=Math.abs((0,QO.differenceInCalendarISOWeekYears)(n,u,t)),c=(0,RO.subISOWeekYears)(n,a*o,t),f=+((0,Ef.compareAsc)(c,u)===-a),d=a*(o-f);return d===0?0:d}});var er=s(Ff=>{"use strict";Ff.differenceInMilliseconds=$O;var Sf=l();function $O(e,r){return+(0,Sf.toDate)(e)-+(0,Sf.toDate)(r)}});var rr=s(Nf=>{"use strict";Nf.differenceInMinutes=GO;var ZO=Z(),XO=O(),VO=er();function GO(e,r,t){let n=(0,VO.differenceInMilliseconds)(e,r)/XO.millisecondsInMinute;return(0,ZO.getRoundingMethod)(t?.roundingMethod)(n)}});var tr=s(Hf=>{"use strict";Hf.endOfDay=JO;var UO=l();function JO(e,r){let t=(0,UO.toDate)(e,r?.in);return t.setHours(23,59,59,999),t}});var nr=s(Lf=>{"use strict";Lf.endOfMonth=yO;var KO=l();function yO(e,r){let t=(0,KO.toDate)(e,r?.in),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}});var Zr=s(Cf=>{"use strict";Cf.isLastDayOfMonth=tq;var kO=tr(),eq=nr(),rq=l();function tq(e,r){let t=(0,rq.toDate)(e,r?.in);return+(0,kO.endOfDay)(t,r)==+(0,eq.endOfMonth)(t,r)}});var qe=s(zf=>{"use strict";zf.differenceInMonths=aq;var nq=P(),Xr=te(),iq=Ue(),uq=Zr();function aq(e,r,t){let[n,u,a]=(0,nq.normalizeDates)(t?.in,e,e,r),o=(0,Xr.compareAsc)(u,a),c=Math.abs((0,iq.differenceInCalendarMonths)(u,a));if(c<1)return 0;u.getMonth()===1&&u.getDate()>27&&u.setDate(30),u.setMonth(u.getMonth()-o*c);let f=(0,Xr.compareAsc)(u,a)===-o;(0,uq.isLastDayOfMonth)(n)&&c===1&&(0,Xr.compareAsc)(n,a)===1&&(f=!1);let d=o*(c-+f);return d===0?0:d}});var Qf=s(Bf=>{"use strict";Bf.differenceInQuarters=cq;var sq=Z(),oq=qe();function cq(e,r,t){let n=(0,oq.differenceInMonths)(e,r,t)/3;return(0,sq.getRoundingMethod)(t?.roundingMethod)(n)}});var pe=s(Rf=>{"use strict";Rf.differenceInSeconds=lq;var fq=Z(),dq=er();function lq(e,r,t){let n=(0,dq.differenceInMilliseconds)(e,r)/1e3;return(0,fq.getRoundingMethod)(t?.roundingMethod)(n)}});var $f=s(Af=>{"use strict";Af.differenceInWeeks=mq;var hq=Z(),_q=ye();function mq(e,r,t){let n=(0,_q.differenceInDays)(e,r,t)/7;return(0,hq.getRoundingMethod)(t?.roundingMethod)(n)}});var Vr=s(Xf=>{"use strict";Xf.differenceInYears=vq;var bq=P(),Zf=te(),gq=Ke();function vq(e,r,t){let[n,u]=(0,bq.normalizeDates)(t?.in,e,r),a=(0,Zf.compareAsc)(n,u),o=Math.abs((0,gq.differenceInCalendarYears)(n,u));n.setFullYear(1584),u.setFullYear(1584);let c=(0,Zf.compareAsc)(n,u)===-a,f=a*(o-+c);return f===0?0:f}});var C=s(Vf=>{"use strict";Vf.normalizeInterval=Oq;var xq=P();function Oq(e,r){let[t,n]=(0,xq.normalizeDates)(e,r.start,r.end);return{start:t,end:n}}});var Gr=s(Gf=>{"use strict";Gf.eachDayOfInterval=Mq;var qq=C(),pq=b();function Mq(e,r){let{start:t,end:n}=(0,qq.normalizeInterval)(r?.in,e),u=+t>+n,a=u?+t:+n,o=u?n:t;o.setHours(0,0,0,0);let c=r?.step??1;if(!c)return[];c<0&&(c=-c,u=!u);let f=[];for(;+o<=a;)f.push((0,pq.constructFrom)(t,o)),o.setDate(o.getDate()+c),o.setHours(0,0,0,0);return u?f.reverse():f}});var Jf=s(Uf=>{"use strict";Uf.eachHourOfInterval=Pq;var Dq=C(),wq=b();function Pq(e,r){let{start:t,end:n}=(0,Dq.normalizeInterval)(r?.in,e),u=+t>+n,a=u?+t:+n,o=u?n:t;o.setMinutes(0,0,0);let c=r?.step??1;if(!c)return[];c<0&&(c=-c,u=!u);let f=[];for(;+o<=a;)f.push((0,wq.constructFrom)(t,o)),o.setHours(o.getHours()+c);return u?f.reverse():f}});var yf=s(Kf=>{"use strict";Kf.eachMinuteOfInterval=Eq;var jq=C(),Iq=Xe(),Tq=b();function Eq(e,r){let{start:t,end:n}=(0,jq.normalizeInterval)(r?.in,e);t.setSeconds(0,0);let u=+t>+n,a=u?+t:+n,o=u?n:t,c=r?.step??1;if(!c)return[];c<0&&(c=-c,u=!u);let f=[];for(;+o<=a;)f.push((0,Tq.constructFrom)(t,o)),o=(0,Iq.addMinutes)(o,c);return u?f.reverse():f}});var ed=s(kf=>{"use strict";kf.eachMonthOfInterval=Sq;var Yq=C(),Wq=b();function Sq(e,r){let{start:t,end:n}=(0,Yq.normalizeInterval)(r?.in,e),u=+t>+n,a=u?+t:+n,o=u?n:t;o.setHours(0,0,0,0),o.setDate(1);let c=r?.step??1;if(!c)return[];c<0&&(c=-c,u=!u);let f=[];for(;+o<=a;)f.push((0,Wq.constructFrom)(t,o)),o.setMonth(o.getMonth()+c);return u?f.reverse():f}});var ir=s(rd=>{"use strict";rd.startOfQuarter=Nq;var Fq=l();function Nq(e,r){let t=(0,Fq.toDate)(e,r?.in),n=t.getMonth(),u=n-n%3;return t.setMonth(u,1),t.setHours(0,0,0,0),t}});var nd=s(td=>{"use strict";td.eachQuarterOfInterval=zq;var Hq=C(),Lq=Ve(),Cq=b(),ur=ir();function zq(e,r){let{start:t,end:n}=(0,Hq.normalizeInterval)(r?.in,e),u=+t>+n,a=u?+(0,ur.startOfQuarter)(t):+(0,ur.startOfQuarter)(n),o=u?(0,ur.startOfQuarter)(n):(0,ur.startOfQuarter)(t),c=r?.step??1;if(!c)return[];c<0&&(c=-c,u=!u);let f=[];for(;+o<=a;)f.push((0,Cq.constructFrom)(t,o)),o=(0,Lq.addQuarters)(o,c);return u?f.reverse():f}});var ud=s(id=>{"use strict";id.eachWeekOfInterval=Aq;var Bq=C(),Qq=Oe(),Rq=b(),ar=N();function Aq(e,r){let{start:t,end:n}=(0,Bq.normalizeInterval)(r?.in,e),u=+t>+n,a=u?(0,ar.startOfWeek)(n,r):(0,ar.startOfWeek)(t,r),o=u?(0,ar.startOfWeek)(t,r):(0,ar.startOfWeek)(n,r);a.setHours(15),o.setHours(15);let c=+o.getTime(),f=a,d=r?.step??1;if(!d)return[];d<0&&(d=-d,u=!u);let h=[];for(;+f<=c;)f.setHours(0),h.push((0,Rq.constructFrom)(t,f)),f=(0,Qq.addWeeks)(f,d),f.setHours(15);return u?h.reverse():h}});var sr=s(ad=>{"use strict";ad.eachWeekendOfInterval=Gq;var $q=C(),Zq=b(),Xq=Gr(),Vq=ge();function Gq(e,r){let{start:t,end:n}=(0,$q.normalizeInterval)(r?.in,e),u=(0,Xq.eachDayOfInterval)({start:t,end:n},r),a=[],o=0;for(;o{"use strict";sd.startOfMonth=Jq;var Uq=l();function Jq(e,r){let t=(0,Uq.toDate)(e,r?.in);return t.setDate(1),t.setHours(0,0,0,0),t}});var cd=s(od=>{"use strict";od.eachWeekendOfMonth=ep;var Kq=sr(),yq=nr(),kq=Me();function ep(e,r){let t=(0,kq.startOfMonth)(e,r),n=(0,yq.endOfMonth)(e,r);return(0,Kq.eachWeekendOfInterval)({start:t,end:n},r)}});var Ur=s(fd=>{"use strict";fd.endOfYear=tp;var rp=l();function tp(e,r){let t=(0,rp.toDate)(e,r?.in),n=t.getFullYear();return t.setFullYear(n+1,0,0),t.setHours(23,59,59,999),t}});var or=s(dd=>{"use strict";dd.startOfYear=ip;var np=l();function ip(e,r){let t=(0,np.toDate)(e,r?.in);return t.setFullYear(t.getFullYear(),0,1),t.setHours(0,0,0,0),t}});var hd=s(ld=>{"use strict";ld.eachWeekendOfYear=op;var up=sr(),ap=Ur(),sp=or();function op(e,r){let t=(0,sp.startOfYear)(e,r),n=(0,ap.endOfYear)(e,r);return(0,up.eachWeekendOfInterval)({start:t,end:n},r)}});var md=s(_d=>{"use strict";_d.eachYearOfInterval=dp;var cp=C(),fp=b();function dp(e,r){let{start:t,end:n}=(0,cp.normalizeInterval)(r?.in,e),u=+t>+n,a=u?+t:+n,o=u?n:t;o.setHours(0,0,0,0),o.setMonth(0,1);let c=r?.step??1;if(!c)return[];c<0&&(c=-c,u=!u);let f=[];for(;+o<=a;)f.push((0,fp.constructFrom)(t,o)),o.setFullYear(o.getFullYear()+c);return u?f.reverse():f}});var gd=s(bd=>{"use strict";bd.endOfDecade=hp;var lp=l();function hp(e,r){let t=(0,lp.toDate)(e,r?.in),n=t.getFullYear(),u=9+Math.floor(n/10)*10;return t.setFullYear(u,11,31),t.setHours(23,59,59,999),t}});var xd=s(vd=>{"use strict";vd.endOfHour=mp;var _p=l();function mp(e,r){let t=(0,_p.toDate)(e,r?.in);return t.setMinutes(59,59,999),t}});var Jr=s(Od=>{"use strict";Od.endOfWeek=vp;var bp=Y(),gp=l();function vp(e,r){let t=(0,bp.getDefaultOptions)(),n=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,u=(0,gp.toDate)(e,r?.in),a=u.getDay(),o=(a{"use strict";qd.endOfISOWeek=Op;var xp=Jr();function Op(e,r){return(0,xp.endOfWeek)(e,{...r,weekStartsOn:1})}});var Dd=s(Md=>{"use strict";Md.endOfISOWeekYear=Dp;var qp=b(),pp=U(),Mp=L();function Dp(e,r){let t=(0,pp.getISOWeekYear)(e,r),n=(0,qp.constructFrom)(r?.in||e,0);n.setFullYear(t+1,0,4),n.setHours(0,0,0,0);let u=(0,Mp.startOfISOWeek)(n,r);return u.setMilliseconds(u.getMilliseconds()-1),u}});var Pd=s(wd=>{"use strict";wd.endOfMinute=Pp;var wp=l();function Pp(e,r){let t=(0,wp.toDate)(e,r?.in);return t.setSeconds(59,999),t}});var Id=s(jd=>{"use strict";jd.endOfQuarter=Ip;var jp=l();function Ip(e,r){let t=(0,jp.toDate)(e,r?.in),n=t.getMonth(),u=n-n%3+3;return t.setMonth(u,0),t.setHours(23,59,59,999),t}});var Ed=s(Td=>{"use strict";Td.endOfSecond=Ep;var Tp=l();function Ep(e,r){let t=(0,Tp.toDate)(e,r?.in);return t.setMilliseconds(999),t}});var Wd=s(Yd=>{"use strict";Yd.endOfToday=Wp;var Yp=tr();function Wp(e){return(0,Yp.endOfDay)(Date.now(),e)}});var Nd=s(Fd=>{"use strict";Fd.endOfTomorrow=Sp;var Sd=T();function Sp(e){let r=(0,Sd.constructNow)(e?.in),t=r.getFullYear(),n=r.getMonth(),u=r.getDate(),a=(0,Sd.constructNow)(e?.in);return a.setFullYear(t,n,u+1),a.setHours(23,59,59,999),e?.in?e.in(a):a}});var Ld=s(Hd=>{"use strict";Hd.endOfYesterday=Hp;var Fp=b(),Np=T();function Hp(e){let r=(0,Np.constructNow)(e?.in),t=(0,Fp.constructFrom)(e?.in,0);return t.setFullYear(r.getFullYear(),r.getMonth(),r.getDate()-1),t.setHours(23,59,59,999),t}});var Cd=s(Kr=>{"use strict";Kr.formatDistance=void 0;var Lp={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},Cp=(e,r,t)=>{let n,u=Lp[e];return typeof u=="string"?n=u:r===1?n=u.one:n=u.other.replace("{{count}}",r.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"in "+n:n+" ago":n};Kr.formatDistance=Cp});var Bd=s(zd=>{"use strict";zd.buildFormatLongFn=zp;function zp(e){return(r={})=>{let t=r.width?String(r.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}});var Qd=s(kr=>{"use strict";kr.formatLong=void 0;var yr=Bd(),Bp={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},Qp={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},Rp={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},CF=kr.formatLong={date:(0,yr.buildFormatLongFn)({formats:Bp,defaultWidth:"full"}),time:(0,yr.buildFormatLongFn)({formats:Qp,defaultWidth:"full"}),dateTime:(0,yr.buildFormatLongFn)({formats:Rp,defaultWidth:"full"})}});var Rd=s(et=>{"use strict";et.formatRelative=void 0;var Ap={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},$p=(e,r,t,n)=>Ap[e];et.formatRelative=$p});var $d=s(Ad=>{"use strict";Ad.buildLocalizeFn=Zp;function Zp(e){return(r,t)=>{let n=t?.context?String(t.context):"standalone",u;if(n==="formatting"&&e.formattingValues){let o=e.defaultFormattingWidth||e.defaultWidth,c=t?.width?String(t.width):o;u=e.formattingValues[c]||e.formattingValues[o]}else{let o=e.defaultWidth,c=t?.width?String(t.width):e.defaultWidth;u=e.values[c]||e.values[o]}let a=e.argumentCallback?e.argumentCallback(r):r;return u[a]}}});var Zd=s(rt=>{"use strict";rt.localize=void 0;var De=$d(),Xp={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},Vp={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},Gp={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},Up={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},Jp={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},Kp={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},yp=(e,r)=>{let t=Number(e),n=t%100;if(n>20||n<10)switch(n%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},RF=rt.localize={ordinalNumber:yp,era:(0,De.buildLocalizeFn)({values:Xp,defaultWidth:"wide"}),quarter:(0,De.buildLocalizeFn)({values:Vp,defaultWidth:"wide",argumentCallback:e=>e-1}),month:(0,De.buildLocalizeFn)({values:Gp,defaultWidth:"wide"}),day:(0,De.buildLocalizeFn)({values:Up,defaultWidth:"wide"}),dayPeriod:(0,De.buildLocalizeFn)({values:Jp,defaultWidth:"wide",formattingValues:Kp,defaultFormattingWidth:"wide"})}});var Vd=s(Xd=>{"use strict";Xd.buildMatchFn=kp;function kp(e){return(r,t={})=>{let n=t.width,u=n&&e.matchPatterns[n]||e.matchPatterns[e.defaultMatchWidth],a=r.match(u);if(!a)return null;let o=a[0],c=n&&e.parsePatterns[n]||e.parsePatterns[e.defaultParseWidth],f=Array.isArray(c)?rM(c,_=>_.test(o)):eM(c,_=>_.test(o)),d;d=e.valueCallback?e.valueCallback(f):f,d=t.valueCallback?t.valueCallback(d):d;let h=r.slice(o.length);return{value:d,rest:h}}}function eM(e,r){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&r(e[t]))return t}function rM(e,r){for(let t=0;t{"use strict";Gd.buildMatchPatternFn=tM;function tM(e){return(r,t={})=>{let n=r.match(e.matchPattern);if(!n)return null;let u=n[0],a=r.match(e.parsePattern);if(!a)return null;let o=e.valueCallback?e.valueCallback(a[0]):a[0];o=t.valueCallback?t.valueCallback(o):o;let c=r.slice(u.length);return{value:o,rest:c}}}});var Jd=s(tt=>{"use strict";tt.match=void 0;var we=Vd(),nM=Ud(),iM=/^(\d+)(th|st|nd|rd)?/i,uM=/\d+/i,aM={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},sM={any:[/^b/i,/^(a|c)/i]},oM={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},cM={any:[/1/i,/2/i,/3/i,/4/i]},fM={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},dM={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},lM={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},hM={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},_M={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},mM={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},XF=tt.match={ordinalNumber:(0,nM.buildMatchPatternFn)({matchPattern:iM,parsePattern:uM,valueCallback:e=>parseInt(e,10)}),era:(0,we.buildMatchFn)({matchPatterns:aM,defaultMatchWidth:"wide",parsePatterns:sM,defaultParseWidth:"any"}),quarter:(0,we.buildMatchFn)({matchPatterns:oM,defaultMatchWidth:"wide",parsePatterns:cM,defaultParseWidth:"any",valueCallback:e=>e+1}),month:(0,we.buildMatchFn)({matchPatterns:fM,defaultMatchWidth:"wide",parsePatterns:dM,defaultParseWidth:"any"}),day:(0,we.buildMatchFn)({matchPatterns:lM,defaultMatchWidth:"wide",parsePatterns:hM,defaultParseWidth:"any"}),dayPeriod:(0,we.buildMatchFn)({matchPatterns:_M,defaultMatchWidth:"any",parsePatterns:mM,defaultParseWidth:"any"})}});var Kd=s(nt=>{"use strict";nt.enUS=void 0;var bM=Cd(),gM=Qd(),vM=Rd(),xM=Zd(),OM=Jd(),GF=nt.enUS={code:"en-US",formatDistance:bM.formatDistance,formatLong:gM.formatLong,formatRelative:vM.formatRelative,localize:xM.localize,match:OM.match,options:{weekStartsOn:0,firstWeekContainsDate:1}}});var ne=s(yd=>{"use strict";Object.defineProperty(yd,"defaultLocale",{enumerable:!0,get:function(){return qM.enUS}});var qM=Kd()});var it=s(kd=>{"use strict";kd.getDayOfYear=wM;var pM=A(),MM=or(),DM=l();function wM(e,r){let t=(0,DM.toDate)(e,r?.in);return(0,pM.differenceInCalendarDays)(t,(0,MM.startOfYear)(t))+1}});var cr=s(el=>{"use strict";el.getISOWeek=EM;var PM=O(),jM=L(),IM=ce(),TM=l();function EM(e,r){let t=(0,TM.toDate)(e,r?.in),n=+(0,jM.startOfISOWeek)(t)-+(0,IM.startOfISOWeekYear)(t);return Math.round(n/PM.millisecondsInWeek)+1}});var Pe=s(nl=>{"use strict";nl.getWeekYear=SM;var YM=Y(),rl=b(),tl=N(),WM=l();function SM(e,r){let t=(0,WM.toDate)(e,r?.in),n=t.getFullYear(),u=(0,YM.getDefaultOptions)(),a=r?.firstWeekContainsDate??r?.locale?.options?.firstWeekContainsDate??u.firstWeekContainsDate??u.locale?.options?.firstWeekContainsDate??1,o=(0,rl.constructFrom)(r?.in||e,0);o.setFullYear(n+1,0,a),o.setHours(0,0,0,0);let c=(0,tl.startOfWeek)(o,r),f=(0,rl.constructFrom)(r?.in||e,0);f.setFullYear(n,0,a),f.setHours(0,0,0,0);let d=(0,tl.startOfWeek)(f,r);return+t>=+c?n+1:+t>=+d?n:n-1}});var fr=s(il=>{"use strict";il.startOfWeekYear=CM;var FM=Y(),NM=b(),HM=Pe(),LM=N();function CM(e,r){let t=(0,FM.getDefaultOptions)(),n=r?.firstWeekContainsDate??r?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,u=(0,HM.getWeekYear)(e,r),a=(0,NM.constructFrom)(r?.in||e,0);return a.setFullYear(u,0,n),a.setHours(0,0,0,0),(0,LM.startOfWeek)(a,r)}});var dr=s(ul=>{"use strict";ul.getWeek=AM;var zM=O(),BM=N(),QM=fr(),RM=l();function AM(e,r){let t=(0,RM.toDate)(e,r?.in),n=+(0,BM.startOfWeek)(t,r)-+(0,QM.startOfWeekYear)(t,r);return Math.round(n/zM.millisecondsInWeek)+1}});var ie=s(al=>{"use strict";al.addLeadingZeros=$M;function $M(e,r){let t=e<0?"-":"",n=Math.abs(e).toString().padStart(r,"0");return t+n}});var at=s(ut=>{"use strict";ut.lightFormatters=void 0;var J=ie(),nN=ut.lightFormatters={y(e,r){let t=e.getFullYear(),n=t>0?t:1-t;return(0,J.addLeadingZeros)(r==="yy"?n%100:n,r.length)},M(e,r){let t=e.getMonth();return r==="M"?String(t+1):(0,J.addLeadingZeros)(t+1,2)},d(e,r){return(0,J.addLeadingZeros)(e.getDate(),r.length)},a(e,r){let t=e.getHours()/12>=1?"pm":"am";switch(r){case"a":case"aa":return t.toUpperCase();case"aaa":return t;case"aaaaa":return t[0];case"aaaa":default:return t==="am"?"a.m.":"p.m."}},h(e,r){return(0,J.addLeadingZeros)(e.getHours()%12||12,r.length)},H(e,r){return(0,J.addLeadingZeros)(e.getHours(),r.length)},m(e,r){return(0,J.addLeadingZeros)(e.getMinutes(),r.length)},s(e,r){return(0,J.addLeadingZeros)(e.getSeconds(),r.length)},S(e,r){let t=r.length,n=e.getMilliseconds(),u=Math.trunc(n*Math.pow(10,t-3));return(0,J.addLeadingZeros)(u,r.length)}}});var cl=s(st=>{"use strict";st.formatters=void 0;var ZM=it(),XM=cr(),VM=U(),GM=dr(),UM=Pe(),I=ie(),K=at(),de={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},uN=st.formatters={G:function(e,r,t){let n=e.getFullYear()>0?1:0;switch(r){case"G":case"GG":case"GGG":return t.era(n,{width:"abbreviated"});case"GGGGG":return t.era(n,{width:"narrow"});case"GGGG":default:return t.era(n,{width:"wide"})}},y:function(e,r,t){if(r==="yo"){let n=e.getFullYear(),u=n>0?n:1-n;return t.ordinalNumber(u,{unit:"year"})}return K.lightFormatters.y(e,r)},Y:function(e,r,t,n){let u=(0,UM.getWeekYear)(e,n),a=u>0?u:1-u;if(r==="YY"){let o=a%100;return(0,I.addLeadingZeros)(o,2)}return r==="Yo"?t.ordinalNumber(a,{unit:"year"}):(0,I.addLeadingZeros)(a,r.length)},R:function(e,r){let t=(0,VM.getISOWeekYear)(e);return(0,I.addLeadingZeros)(t,r.length)},u:function(e,r){let t=e.getFullYear();return(0,I.addLeadingZeros)(t,r.length)},Q:function(e,r,t){let n=Math.ceil((e.getMonth()+1)/3);switch(r){case"Q":return String(n);case"QQ":return(0,I.addLeadingZeros)(n,2);case"Qo":return t.ordinalNumber(n,{unit:"quarter"});case"QQQ":return t.quarter(n,{width:"abbreviated",context:"formatting"});case"QQQQQ":return t.quarter(n,{width:"narrow",context:"formatting"});case"QQQQ":default:return t.quarter(n,{width:"wide",context:"formatting"})}},q:function(e,r,t){let n=Math.ceil((e.getMonth()+1)/3);switch(r){case"q":return String(n);case"qq":return(0,I.addLeadingZeros)(n,2);case"qo":return t.ordinalNumber(n,{unit:"quarter"});case"qqq":return t.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return t.quarter(n,{width:"wide",context:"standalone"})}},M:function(e,r,t){let n=e.getMonth();switch(r){case"M":case"MM":return K.lightFormatters.M(e,r);case"Mo":return t.ordinalNumber(n+1,{unit:"month"});case"MMM":return t.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return t.month(n,{width:"wide",context:"formatting"})}},L:function(e,r,t){let n=e.getMonth();switch(r){case"L":return String(n+1);case"LL":return(0,I.addLeadingZeros)(n+1,2);case"Lo":return t.ordinalNumber(n+1,{unit:"month"});case"LLL":return t.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return t.month(n,{width:"wide",context:"standalone"})}},w:function(e,r,t,n){let u=(0,GM.getWeek)(e,n);return r==="wo"?t.ordinalNumber(u,{unit:"week"}):(0,I.addLeadingZeros)(u,r.length)},I:function(e,r,t){let n=(0,XM.getISOWeek)(e);return r==="Io"?t.ordinalNumber(n,{unit:"week"}):(0,I.addLeadingZeros)(n,r.length)},d:function(e,r,t){return r==="do"?t.ordinalNumber(e.getDate(),{unit:"date"}):K.lightFormatters.d(e,r)},D:function(e,r,t){let n=(0,ZM.getDayOfYear)(e);return r==="Do"?t.ordinalNumber(n,{unit:"dayOfYear"}):(0,I.addLeadingZeros)(n,r.length)},E:function(e,r,t){let n=e.getDay();switch(r){case"E":case"EE":case"EEE":return t.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(n,{width:"short",context:"formatting"});case"EEEE":default:return t.day(n,{width:"wide",context:"formatting"})}},e:function(e,r,t,n){let u=e.getDay(),a=(u-n.weekStartsOn+8)%7||7;switch(r){case"e":return String(a);case"ee":return(0,I.addLeadingZeros)(a,2);case"eo":return t.ordinalNumber(a,{unit:"day"});case"eee":return t.day(u,{width:"abbreviated",context:"formatting"});case"eeeee":return t.day(u,{width:"narrow",context:"formatting"});case"eeeeee":return t.day(u,{width:"short",context:"formatting"});case"eeee":default:return t.day(u,{width:"wide",context:"formatting"})}},c:function(e,r,t,n){let u=e.getDay(),a=(u-n.weekStartsOn+8)%7||7;switch(r){case"c":return String(a);case"cc":return(0,I.addLeadingZeros)(a,r.length);case"co":return t.ordinalNumber(a,{unit:"day"});case"ccc":return t.day(u,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(u,{width:"narrow",context:"standalone"});case"cccccc":return t.day(u,{width:"short",context:"standalone"});case"cccc":default:return t.day(u,{width:"wide",context:"standalone"})}},i:function(e,r,t){let n=e.getDay(),u=n===0?7:n;switch(r){case"i":return String(u);case"ii":return(0,I.addLeadingZeros)(u,r.length);case"io":return t.ordinalNumber(u,{unit:"day"});case"iii":return t.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return t.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return t.day(n,{width:"short",context:"formatting"});case"iiii":default:return t.day(n,{width:"wide",context:"formatting"})}},a:function(e,r,t){let u=e.getHours()/12>=1?"pm":"am";switch(r){case"a":case"aa":return t.dayPeriod(u,{width:"abbreviated",context:"formatting"});case"aaa":return t.dayPeriod(u,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return t.dayPeriod(u,{width:"narrow",context:"formatting"});case"aaaa":default:return t.dayPeriod(u,{width:"wide",context:"formatting"})}},b:function(e,r,t){let n=e.getHours(),u;switch(n===12?u=de.noon:n===0?u=de.midnight:u=n/12>=1?"pm":"am",r){case"b":case"bb":return t.dayPeriod(u,{width:"abbreviated",context:"formatting"});case"bbb":return t.dayPeriod(u,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return t.dayPeriod(u,{width:"narrow",context:"formatting"});case"bbbb":default:return t.dayPeriod(u,{width:"wide",context:"formatting"})}},B:function(e,r,t){let n=e.getHours(),u;switch(n>=17?u=de.evening:n>=12?u=de.afternoon:n>=4?u=de.morning:u=de.night,r){case"B":case"BB":case"BBB":return t.dayPeriod(u,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(u,{width:"narrow",context:"formatting"});case"BBBB":default:return t.dayPeriod(u,{width:"wide",context:"formatting"})}},h:function(e,r,t){if(r==="ho"){let n=e.getHours()%12;return n===0&&(n=12),t.ordinalNumber(n,{unit:"hour"})}return K.lightFormatters.h(e,r)},H:function(e,r,t){return r==="Ho"?t.ordinalNumber(e.getHours(),{unit:"hour"}):K.lightFormatters.H(e,r)},K:function(e,r,t){let n=e.getHours()%12;return r==="Ko"?t.ordinalNumber(n,{unit:"hour"}):(0,I.addLeadingZeros)(n,r.length)},k:function(e,r,t){let n=e.getHours();return n===0&&(n=24),r==="ko"?t.ordinalNumber(n,{unit:"hour"}):(0,I.addLeadingZeros)(n,r.length)},m:function(e,r,t){return r==="mo"?t.ordinalNumber(e.getMinutes(),{unit:"minute"}):K.lightFormatters.m(e,r)},s:function(e,r,t){return r==="so"?t.ordinalNumber(e.getSeconds(),{unit:"second"}):K.lightFormatters.s(e,r)},S:function(e,r){return K.lightFormatters.S(e,r)},X:function(e,r,t){let n=e.getTimezoneOffset();if(n===0)return"Z";switch(r){case"X":return ol(n);case"XXXX":case"XX":return ue(n);case"XXXXX":case"XXX":default:return ue(n,":")}},x:function(e,r,t){let n=e.getTimezoneOffset();switch(r){case"x":return ol(n);case"xxxx":case"xx":return ue(n);case"xxxxx":case"xxx":default:return ue(n,":")}},O:function(e,r,t){let n=e.getTimezoneOffset();switch(r){case"O":case"OO":case"OOO":return"GMT"+sl(n,":");case"OOOO":default:return"GMT"+ue(n,":")}},z:function(e,r,t){let n=e.getTimezoneOffset();switch(r){case"z":case"zz":case"zzz":return"GMT"+sl(n,":");case"zzzz":default:return"GMT"+ue(n,":")}},t:function(e,r,t){let n=Math.trunc(+e/1e3);return(0,I.addLeadingZeros)(n,r.length)},T:function(e,r,t){return(0,I.addLeadingZeros)(+e,r.length)}};function sl(e,r=""){let t=e>0?"-":"+",n=Math.abs(e),u=Math.trunc(n/60),a=n%60;return a===0?t+String(u):t+String(u)+r+(0,I.addLeadingZeros)(a,2)}function ol(e,r){return e%60===0?(e>0?"-":"+")+(0,I.addLeadingZeros)(Math.abs(e)/60,2):ue(e,r)}function ue(e,r=""){let t=e>0?"-":"+",n=Math.abs(e),u=(0,I.addLeadingZeros)(Math.trunc(n/60),2),a=(0,I.addLeadingZeros)(n%60,2);return t+u+r+a}});var ct=s(ot=>{"use strict";ot.longFormatters=void 0;var fl=(e,r)=>{switch(e){case"P":return r.date({width:"short"});case"PP":return r.date({width:"medium"});case"PPP":return r.date({width:"long"});case"PPPP":default:return r.date({width:"full"})}},dl=(e,r)=>{switch(e){case"p":return r.time({width:"short"});case"pp":return r.time({width:"medium"});case"ppp":return r.time({width:"long"});case"pppp":default:return r.time({width:"full"})}},JM=(e,r)=>{let t=e.match(/(P+)(p+)?/)||[],n=t[1],u=t[2];if(!u)return fl(e,r);let a;switch(n){case"P":a=r.dateTime({width:"short"});break;case"PP":a=r.dateTime({width:"medium"});break;case"PPP":a=r.dateTime({width:"long"});break;case"PPPP":default:a=r.dateTime({width:"full"});break}return a.replace("{{date}}",fl(n,r)).replace("{{time}}",dl(u,r))},sN=ot.longFormatters={p:dl,P:JM}});var ft=s(lr=>{"use strict";lr.isProtectedDayOfYearToken=eD;lr.isProtectedWeekYearToken=rD;lr.warnOrThrowProtectedError=tD;var KM=/^D+$/,yM=/^Y+$/,kM=["D","DD","YY","YYYY"];function eD(e){return KM.test(e)}function rD(e){return yM.test(e)}function tD(e,r,t){let n=nD(e,r,t);if(console.warn(n),kM.includes(e))throw new RangeError(n)}function nD(e,r,t){let n=e[0]==="Y"?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${r}\`) for formatting ${n} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}});var ht=s(je=>{"use strict";je.format=je.formatDate=hD;Object.defineProperty(je,"formatters",{enumerable:!0,get:function(){return lt.formatters}});Object.defineProperty(je,"longFormatters",{enumerable:!0,get:function(){return ll.longFormatters}});var iD=ne(),uD=Y(),lt=cl(),ll=ct(),dt=ft(),aD=$(),sD=l(),oD=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,cD=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,fD=/^'([^]*?)'?$/,dD=/''/g,lD=/[a-zA-Z]/;function hD(e,r,t){let n=(0,uD.getDefaultOptions)(),u=t?.locale??n.locale??iD.defaultLocale,a=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,o=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??n.weekStartsOn??n.locale?.options?.weekStartsOn??0,c=(0,sD.toDate)(e,t?.in);if(!(0,aD.isValid)(c))throw new RangeError("Invalid time value");let f=r.match(cD).map(h=>{let _=h[0];if(_==="p"||_==="P"){let g=ll.longFormatters[_];return g(h,u.formatLong)}return h}).join("").match(oD).map(h=>{if(h==="''")return{isToken:!1,value:"'"};let _=h[0];if(_==="'")return{isToken:!1,value:_D(h)};if(lt.formatters[_])return{isToken:!0,value:h};if(_.match(lD))throw new RangeError("Format string contains an unescaped latin alphabet character `"+_+"`");return{isToken:!1,value:h}});u.localize.preprocessor&&(f=u.localize.preprocessor(c,f));let d={firstWeekContainsDate:a,weekStartsOn:o,locale:u};return f.map(h=>{if(!h.isToken)return h.value;let _=h.value;(!t?.useAdditionalWeekYearTokens&&(0,dt.isProtectedWeekYearToken)(_)||!t?.useAdditionalDayOfYearTokens&&(0,dt.isProtectedDayOfYearToken)(_))&&(0,dt.warnOrThrowProtectedError)(_,r,String(e));let g=lt.formatters[_[0]];return g(c,_,u.localize,d)}).join("")}function _D(e){let r=e.match(fD);return r?r[1].replace(dD,"'"):e}});var _t=s(_l=>{"use strict";_l.formatDistance=qD;var mD=ne(),bD=Y(),hl=R(),gD=P(),vD=te(),le=O(),xD=qe(),OD=pe();function qD(e,r,t){let n=(0,bD.getDefaultOptions)(),u=t?.locale??n.locale??mD.defaultLocale,a=2520,o=(0,vD.compareAsc)(e,r);if(isNaN(o))throw new RangeError("Invalid time value");let c=Object.assign({},t,{addSuffix:t?.addSuffix,comparison:o}),[f,d]=(0,gD.normalizeDates)(t?.in,...o>0?[r,e]:[e,r]),h=(0,OD.differenceInSeconds)(d,f),_=((0,hl.getTimezoneOffsetInMilliseconds)(d)-(0,hl.getTimezoneOffsetInMilliseconds)(f))/1e3,g=Math.round((h-_)/60),p;if(g<2)return t?.includeSeconds?h<5?u.formatDistance("lessThanXSeconds",5,c):h<10?u.formatDistance("lessThanXSeconds",10,c):h<20?u.formatDistance("lessThanXSeconds",20,c):h<40?u.formatDistance("halfAMinute",0,c):h<60?u.formatDistance("lessThanXMinutes",1,c):u.formatDistance("xMinutes",1,c):g===0?u.formatDistance("lessThanXMinutes",1,c):u.formatDistance("xMinutes",g,c);if(g<45)return u.formatDistance("xMinutes",g,c);if(g<90)return u.formatDistance("aboutXHours",1,c);if(g{"use strict";bl.formatDistanceStrict=jD;var pD=ne(),MD=Y(),DD=Z(),ml=R(),wD=P(),PD=te(),y=O();function jD(e,r,t){let n=(0,MD.getDefaultOptions)(),u=t?.locale??n.locale??pD.defaultLocale,a=(0,PD.compareAsc)(e,r);if(isNaN(a))throw new RangeError("Invalid time value");let o=Object.assign({},t,{addSuffix:t?.addSuffix,comparison:a}),[c,f]=(0,wD.normalizeDates)(t?.in,...a>0?[r,e]:[e,r]),d=(0,DD.getRoundingMethod)(t?.roundingMethod??"round"),h=f.getTime()-c.getTime(),_=h/y.millisecondsInMinute,g=(0,ml.getTimezoneOffsetInMilliseconds)(f)-(0,ml.getTimezoneOffsetInMilliseconds)(c),p=(h-g)/y.millisecondsInMinute,q=t?.unit,x;if(q?x=q:_<1?x="second":_<60?x="minute":_{"use strict";gl.formatDistanceToNow=ED;var ID=T(),TD=_t();function ED(e,r){return(0,TD.formatDistance)(e,(0,ID.constructNow)(e),r)}});var Ol=s(xl=>{"use strict";xl.formatDistanceToNowStrict=SD;var YD=T(),WD=mt();function SD(e,r){return(0,WD.formatDistanceStrict)(e,(0,YD.constructNow)(e),r)}});var pl=s(ql=>{"use strict";ql.formatDuration=LD;var FD=ne(),ND=Y(),HD=["years","months","weeks","days","hours","minutes","seconds"];function LD(e,r){let t=(0,ND.getDefaultOptions)(),n=r?.locale??t.locale??FD.defaultLocale,u=r?.format??HD,a=r?.zero??!1,o=r?.delimiter??" ";return n.formatDistance?u.reduce((f,d)=>{let h=`x${d.replace(/(^.)/,g=>g.toUpperCase())}`,_=e[d];return _!==void 0&&(a||e[d])?f.concat(n.formatDistance(h,_)):f},[]).join(o):""}});var Dl=s(Ml=>{"use strict";Ml.formatISO=zD;var k=ie(),CD=l();function zD(e,r){let t=(0,CD.toDate)(e,r?.in);if(isNaN(+t))throw new RangeError("Invalid time value");let n=r?.format??"extended",u=r?.representation??"complete",a="",o="",c=n==="extended"?"-":"",f=n==="extended"?":":"";if(u!=="time"){let d=(0,k.addLeadingZeros)(t.getDate(),2),h=(0,k.addLeadingZeros)(t.getMonth()+1,2);a=`${(0,k.addLeadingZeros)(t.getFullYear(),4)}${c}${h}${c}${d}`}if(u!=="date"){let d=t.getTimezoneOffset();if(d!==0){let x=Math.abs(d),m=(0,k.addLeadingZeros)(Math.trunc(x/60),2),D=(0,k.addLeadingZeros)(x%60,2);o=`${d<0?"+":"-"}${m}:${D}`}else o="Z";let h=(0,k.addLeadingZeros)(t.getHours(),2),_=(0,k.addLeadingZeros)(t.getMinutes(),2),g=(0,k.addLeadingZeros)(t.getSeconds(),2),p=a===""?"":"T",q=[h,_,g].join(f);a=`${a}${p}${q}${o}`}return a}});var Pl=s(wl=>{"use strict";wl.formatISO9075=RD;var he=ie(),BD=$(),QD=l();function RD(e,r){let t=(0,QD.toDate)(e,r?.in);if(!(0,BD.isValid)(t))throw new RangeError("Invalid time value");let n=r?.format??"extended",u=r?.representation??"complete",a="",o=n==="extended"?"-":"",c=n==="extended"?":":"";if(u!=="time"){let f=(0,he.addLeadingZeros)(t.getDate(),2),d=(0,he.addLeadingZeros)(t.getMonth()+1,2);a=`${(0,he.addLeadingZeros)(t.getFullYear(),4)}${o}${d}${o}${f}`}if(u!=="date"){let f=(0,he.addLeadingZeros)(t.getHours(),2),d=(0,he.addLeadingZeros)(t.getMinutes(),2),h=(0,he.addLeadingZeros)(t.getSeconds(),2);a=`${a}${a===""?"":" "}${f}${c}${d}${c}${h}`}return a}});var Il=s(jl=>{"use strict";jl.formatISODuration=AD;function AD(e){let{years:r=0,months:t=0,days:n=0,hours:u=0,minutes:a=0,seconds:o=0}=e;return`P${r}Y${t}M${n}DT${u}H${a}M${o}S`}});var El=s(Tl=>{"use strict";Tl.formatRFC3339=XD;var ee=ie(),$D=$(),ZD=l();function XD(e,r){let t=(0,ZD.toDate)(e,r?.in);if(!(0,$D.isValid)(t))throw new RangeError("Invalid time value");let n=r?.fractionDigits??0,u=(0,ee.addLeadingZeros)(t.getDate(),2),a=(0,ee.addLeadingZeros)(t.getMonth()+1,2),o=t.getFullYear(),c=(0,ee.addLeadingZeros)(t.getHours(),2),f=(0,ee.addLeadingZeros)(t.getMinutes(),2),d=(0,ee.addLeadingZeros)(t.getSeconds(),2),h="";if(n>0){let p=t.getMilliseconds(),q=Math.trunc(p*Math.pow(10,n-3));h="."+(0,ee.addLeadingZeros)(q,n)}let _="",g=t.getTimezoneOffset();if(g!==0){let p=Math.abs(g),q=(0,ee.addLeadingZeros)(Math.trunc(p/60),2),x=(0,ee.addLeadingZeros)(p%60,2);_=`${g<0?"+":"-"}${q}:${x}`}else _="Z";return`${o}-${a}-${u}T${c}:${f}:${d}${h}${_}`}});var Wl=s(Yl=>{"use strict";Yl.formatRFC7231=KD;var hr=ie(),VD=$(),GD=l(),UD=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],JD=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function KD(e){let r=(0,GD.toDate)(e);if(!(0,VD.isValid)(r))throw new RangeError("Invalid time value");let t=UD[r.getUTCDay()],n=(0,hr.addLeadingZeros)(r.getUTCDate(),2),u=JD[r.getUTCMonth()],a=r.getUTCFullYear(),o=(0,hr.addLeadingZeros)(r.getUTCHours(),2),c=(0,hr.addLeadingZeros)(r.getUTCMinutes(),2),f=(0,hr.addLeadingZeros)(r.getUTCSeconds(),2);return`${t}, ${n} ${u} ${a} ${o}:${c}:${f} GMT`}});var Fl=s(Sl=>{"use strict";Sl.formatRelative=nw;var yD=ne(),kD=Y(),ew=P(),rw=A(),tw=ht();function nw(e,r,t){let[n,u]=(0,ew.normalizeDates)(t?.in,e,r),a=(0,kD.getDefaultOptions)(),o=t?.locale??a.locale??yD.defaultLocale,c=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??a.weekStartsOn??a.locale?.options?.weekStartsOn??0,f=(0,rw.differenceInCalendarDays)(n,u);if(isNaN(f))throw new RangeError("Invalid time value");let d;f<-6?d="other":f<-1?d="lastWeek":f<0?d="yesterday":f<1?d="today":f<2?d="tomorrow":f<7?d="nextWeek":d="other";let h=o.formatRelative(d,n,u,{locale:o,weekStartsOn:c});return(0,tw.format)(n,h,{locale:o,weekStartsOn:c})}});var Hl=s(Nl=>{"use strict";Nl.fromUnixTime=uw;var iw=l();function uw(e,r){return(0,iw.toDate)(e*1e3,r?.in)}});var bt=s(Ll=>{"use strict";Ll.getDate=sw;var aw=l();function sw(e,r){return(0,aw.toDate)(e,r?.in).getDate()}});var Ie=s(Cl=>{"use strict";Cl.getDay=cw;var ow=l();function cw(e,r){return(0,ow.toDate)(e,r?.in).getDay()}});var gt=s(zl=>{"use strict";zl.getDaysInMonth=lw;var fw=b(),dw=l();function lw(e,r){let t=(0,dw.toDate)(e,r?.in),n=t.getFullYear(),u=t.getMonth(),a=(0,fw.constructFrom)(t,0);return a.setFullYear(n,u+1,0),a.setHours(0,0,0,0),a.getDate()}});var vt=s(Bl=>{"use strict";Bl.isLeapYear=_w;var hw=l();function _w(e,r){let n=(0,hw.toDate)(e,r?.in).getFullYear();return n%400===0||n%4===0&&n%100!==0}});var Rl=s(Ql=>{"use strict";Ql.getDaysInYear=gw;var mw=vt(),bw=l();function gw(e,r){let t=(0,bw.toDate)(e,r?.in);return Number.isNaN(+t)?NaN:(0,mw.isLeapYear)(t)?366:365}});var $l=s(Al=>{"use strict";Al.getDecade=xw;var vw=l();function xw(e,r){let n=(0,vw.toDate)(e,r?.in).getFullYear();return Math.floor(n/10)*10}});var xt=s(Zl=>{"use strict";Zl.getDefaultOptions=qw;var Ow=Y();function qw(){return Object.assign({},(0,Ow.getDefaultOptions)())}});var Vl=s(Xl=>{"use strict";Xl.getHours=Mw;var pw=l();function Mw(e,r){return(0,pw.toDate)(e,r?.in).getHours()}});var Ot=s(Gl=>{"use strict";Gl.getISODay=ww;var Dw=l();function ww(e,r){let t=(0,Dw.toDate)(e,r?.in).getDay();return t===0?7:t}});var Kl=s(Jl=>{"use strict";Jl.getISOWeeksInYear=Iw;var Pw=Oe(),jw=O(),Ul=ce();function Iw(e,r){let t=(0,Ul.startOfISOWeekYear)(e,r),u=+(0,Ul.startOfISOWeekYear)((0,Pw.addWeeks)(t,60))-+t;return Math.round(u/jw.millisecondsInWeek)}});var kl=s(yl=>{"use strict";yl.getMilliseconds=Ew;var Tw=l();function Ew(e){return(0,Tw.toDate)(e).getMilliseconds()}});var rh=s(eh=>{"use strict";eh.getMinutes=Ww;var Yw=l();function Ww(e,r){return(0,Yw.toDate)(e,r?.in).getMinutes()}});var nh=s(th=>{"use strict";th.getMonth=Fw;var Sw=l();function Fw(e,r){return(0,Sw.toDate)(e,r?.in).getMonth()}});var ah=s(uh=>{"use strict";uh.getOverlappingDaysInIntervals=Hw;var ih=R(),Nw=O(),_r=l();function Hw(e,r){let[t,n]=[+(0,_r.toDate)(e.start),+(0,_r.toDate)(e.end)].sort((_,g)=>_-g),[u,a]=[+(0,_r.toDate)(r.start),+(0,_r.toDate)(r.end)].sort((_,g)=>_-g);if(!(tn?n:a,h=d-(0,ih.getTimezoneOffsetInMilliseconds)(d);return Math.ceil((h-f)/Nw.millisecondsInDay)}});var oh=s(sh=>{"use strict";sh.getSeconds=Cw;var Lw=l();function Cw(e){return(0,Lw.toDate)(e).getSeconds()}});var fh=s(ch=>{"use strict";ch.getTime=Bw;var zw=l();function Bw(e){return+(0,zw.toDate)(e)}});var lh=s(dh=>{"use strict";dh.getUnixTime=Rw;var Qw=l();function Rw(e){return Math.trunc(+(0,Qw.toDate)(e)/1e3)}});var _h=s(hh=>{"use strict";hh.getWeekOfMonth=Gw;var Aw=Y(),$w=bt(),Zw=Ie(),Xw=Me(),Vw=l();function Gw(e,r){let t=(0,Aw.getDefaultOptions)(),n=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,u=(0,$w.getDate)((0,Vw.toDate)(e,r?.in));if(isNaN(u))return NaN;let a=(0,Zw.getDay)((0,Xw.startOfMonth)(e,r)),o=n-a;o<=0&&(o+=7);let c=u-o;return Math.ceil(c/7)+1}});var qt=s(bh=>{"use strict";bh.lastDayOfMonth=Uw;var mh=l();function Uw(e,r){let t=(0,mh.toDate)(e,r?.in),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(0,0,0,0),(0,mh.toDate)(t,r?.in)}});var vh=s(gh=>{"use strict";gh.getWeeksInMonth=eP;var Jw=Je(),Kw=qt(),yw=Me(),kw=l();function eP(e,r){let t=(0,kw.toDate)(e,r?.in);return(0,Jw.differenceInCalendarWeeks)((0,Kw.lastDayOfMonth)(t,r),(0,yw.startOfMonth)(t,r),r)+1}});var Oh=s(xh=>{"use strict";xh.getYear=tP;var rP=l();function tP(e,r){return(0,rP.toDate)(e,r?.in).getFullYear()}});var ph=s(qh=>{"use strict";qh.hoursToMilliseconds=iP;var nP=O();function iP(e){return Math.trunc(e*nP.millisecondsInHour)}});var Dh=s(Mh=>{"use strict";Mh.hoursToMinutes=aP;var uP=O();function aP(e){return Math.trunc(e*uP.minutesInHour)}});var Ph=s(wh=>{"use strict";wh.hoursToSeconds=oP;var sP=O();function oP(e){return Math.trunc(e*sP.secondsInHour)}});var Ih=s(jh=>{"use strict";jh.interval=fP;var cP=P();function fP(e,r,t){let[n,u]=(0,cP.normalizeDates)(t?.in,e,r);if(isNaN(+n))throw new TypeError("Start date is invalid");if(isNaN(+u))throw new TypeError("End date is invalid");if(t?.assertPositive&&+n>+u)throw new TypeError("End date must be after start date");return{start:n,end:u}}});var Eh=s(Th=>{"use strict";Th.intervalToDuration=vP;var dP=C(),Te=Pr(),lP=ye(),hP=ke(),_P=rr(),mP=qe(),bP=pe(),gP=Vr();function vP(e,r){let{start:t,end:n}=(0,dP.normalizeInterval)(r?.in,e),u={},a=(0,gP.differenceInYears)(n,t);a&&(u.years=a);let o=(0,Te.add)(t,{years:u.years}),c=(0,mP.differenceInMonths)(n,o);c&&(u.months=c);let f=(0,Te.add)(o,{months:u.months}),d=(0,lP.differenceInDays)(n,f);d&&(u.days=d);let h=(0,Te.add)(f,{days:u.days}),_=(0,hP.differenceInHours)(n,h);_&&(u.hours=_);let g=(0,Te.add)(h,{hours:u.hours}),p=(0,_P.differenceInMinutes)(n,g);p&&(u.minutes=p);let q=(0,Te.add)(g,{minutes:u.minutes}),x=(0,bP.differenceInSeconds)(n,q);return x&&(u.seconds=x),u}});var Wh=s(Yh=>{"use strict";Yh.intlFormat=OP;var xP=l();function OP(e,r,t){let n;return qP(r)?n=r:t=r,new Intl.DateTimeFormat(t?.locale,n).format((0,xP.toDate)(e))}function qP(e){return e!==void 0&&!("locale"in e)}});var Ch=s(Lh=>{"use strict";Lh.intlFormatDistance=MP;var pP=P(),ae=O(),pt=A(),Sh=Ue(),Mt=Ar(),Fh=Je(),Dt=Ke(),Nh=ke(),Hh=rr(),wt=pe();function MP(e,r,t){let n=0,u,[a,o]=(0,pP.normalizeDates)(t?.in,e,r);if(t?.unit)u=t?.unit,u==="second"?n=(0,wt.differenceInSeconds)(a,o):u==="minute"?n=(0,Hh.differenceInMinutes)(a,o):u==="hour"?n=(0,Nh.differenceInHours)(a,o):u==="day"?n=(0,pt.differenceInCalendarDays)(a,o):u==="week"?n=(0,Fh.differenceInCalendarWeeks)(a,o):u==="month"?n=(0,Sh.differenceInCalendarMonths)(a,o):u==="quarter"?n=(0,Mt.differenceInCalendarQuarters)(a,o):u==="year"&&(n=(0,Dt.differenceInCalendarYears)(a,o));else{let f=(0,wt.differenceInSeconds)(a,o);Math.abs(f){"use strict";Bh.isAfter=DP;var zh=l();function DP(e,r){return+(0,zh.toDate)(e)>+(0,zh.toDate)(r)}});var $h=s(Ah=>{"use strict";Ah.isBefore=wP;var Rh=l();function wP(e,r){return+(0,Rh.toDate)(e)<+(0,Rh.toDate)(r)}});var Vh=s(Xh=>{"use strict";Xh.isEqual=PP;var Zh=l();function PP(e,r){return+(0,Zh.toDate)(e)==+(0,Zh.toDate)(r)}});var Uh=s(Gh=>{"use strict";Gh.isExists=jP;function jP(e,r,t){let n=new Date(e,r,t);return n.getFullYear()===e&&n.getMonth()===r&&n.getDate()===t}});var Kh=s(Jh=>{"use strict";Jh.isFirstDayOfMonth=TP;var IP=l();function TP(e,r){return(0,IP.toDate)(e,r?.in).getDate()===1}});var kh=s(yh=>{"use strict";yh.isFriday=YP;var EP=l();function YP(e,r){return(0,EP.toDate)(e,r?.in).getDay()===5}});var r_=s(e_=>{"use strict";e_.isFuture=SP;var WP=l();function SP(e){return+(0,WP.toDate)(e)>Date.now()}});var Pt=s(t_=>{"use strict";t_.transpose=NP;var FP=b();function NP(e,r){let t=HP(r)?new r(0):(0,FP.constructFrom)(r,0);return t.setFullYear(e.getFullYear(),e.getMonth(),e.getDate()),t.setHours(e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()),t}function HP(e){return typeof e=="function"&&e.prototype?.constructor===e}});var Tt=s(se=>{"use strict";se.ValueSetter=se.Setter=se.DateTimezoneSetter=void 0;var n_=b(),LP=Pt(),CP=10,Ee=class{subPriority=0;validate(r,t){return!0}};se.Setter=Ee;var jt=class extends Ee{constructor(r,t,n,u,a){super(),this.value=r,this.validateValue=t,this.setValue=n,this.priority=u,a&&(this.subPriority=a)}validate(r,t){return this.validateValue(r,this.value,t)}set(r,t,n){return this.setValue(r,t,this.value,n)}};se.ValueSetter=jt;var It=class extends Ee{priority=CP;subPriority=-1;constructor(r,t){super(),this.context=r||(n=>(0,n_.constructFrom)(t,n))}set(r,t){return t.timestampIsSet?r:(0,n_.constructFrom)(r,(0,LP.transpose)(r,this.context))}};se.DateTimezoneSetter=It});var M=s(Yt=>{"use strict";Yt.Parser=void 0;var zP=Tt(),Et=class{run(r,t,n,u){let a=this.parse(r,t,n,u);return a?{setter:new zP.ValueSetter(a.value,this.validate,this.set,this.priority,this.subPriority),rest:a.rest}:null}validate(r,t,n){return!0}};Yt.Parser=Et});var i_=s(St=>{"use strict";St.EraParser=void 0;var BP=M(),Wt=class extends BP.Parser{priority=140;parse(r,t,n){switch(t){case"G":case"GG":case"GGG":return n.era(r,{width:"abbreviated"})||n.era(r,{width:"narrow"});case"GGGGG":return n.era(r,{width:"narrow"});case"GGGG":default:return n.era(r,{width:"wide"})||n.era(r,{width:"abbreviated"})||n.era(r,{width:"narrow"})}}set(r,t,n){return t.era=n,r.setFullYear(n,0,1),r.setHours(0,0,0,0),r}incompatibleTokens=["R","u","t","T"]};St.EraParser=Wt});var W=s(Ye=>{"use strict";Ye.timezonePatterns=Ye.numericPatterns=void 0;var o3=Ye.numericPatterns={month:/^(1[0-2]|0?\d)/,date:/^(3[0-1]|[0-2]?\d)/,dayOfYear:/^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,week:/^(5[0-3]|[0-4]?\d)/,hour23h:/^(2[0-3]|[0-1]?\d)/,hour24h:/^(2[0-4]|[0-1]?\d)/,hour11h:/^(1[0-1]|0?\d)/,hour12h:/^(1[0-2]|0?\d)/,minute:/^[0-5]?\d/,second:/^[0-5]?\d/,singleDigit:/^\d/,twoDigits:/^\d{1,2}/,threeDigits:/^\d{1,3}/,fourDigits:/^\d{1,4}/,anyDigitsSigned:/^-?\d+/,singleDigitSigned:/^-?\d/,twoDigitsSigned:/^-?\d{1,2}/,threeDigitsSigned:/^-?\d{1,3}/,fourDigitsSigned:/^-?\d{1,4}/},c3=Ye.timezonePatterns={basicOptionalMinutes:/^([+-])(\d{2})(\d{2})?|Z/,basic:/^([+-])(\d{2})(\d{2})|Z/,basicOptionalSeconds:/^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,extended:/^([+-])(\d{2}):(\d{2})|Z/,extendedOptionalSeconds:/^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/}});var w=s(z=>{"use strict";z.dayPeriodEnumToHours=XP;z.isLeapYearIndex=GP;z.mapValue=QP;z.normalizeTwoDigitYear=VP;z.parseAnyDigitsSigned=AP;z.parseNDigits=$P;z.parseNDigitsSigned=ZP;z.parseNumericPattern=S;z.parseTimezonePattern=RP;var Ft=O(),X=W();function QP(e,r){return e&&{value:r(e.value),rest:e.rest}}function S(e,r){let t=r.match(e);return t?{value:parseInt(t[0],10),rest:r.slice(t[0].length)}:null}function RP(e,r){let t=r.match(e);if(!t)return null;if(t[0]==="Z")return{value:0,rest:r.slice(1)};let n=t[1]==="+"?1:-1,u=t[2]?parseInt(t[2],10):0,a=t[3]?parseInt(t[3],10):0,o=t[5]?parseInt(t[5],10):0;return{value:n*(u*Ft.millisecondsInHour+a*Ft.millisecondsInMinute+o*Ft.millisecondsInSecond),rest:r.slice(t[0].length)}}function AP(e){return S(X.numericPatterns.anyDigitsSigned,e)}function $P(e,r){switch(e){case 1:return S(X.numericPatterns.singleDigit,r);case 2:return S(X.numericPatterns.twoDigits,r);case 3:return S(X.numericPatterns.threeDigits,r);case 4:return S(X.numericPatterns.fourDigits,r);default:return S(new RegExp("^\\d{1,"+e+"}"),r)}}function ZP(e,r){switch(e){case 1:return S(X.numericPatterns.singleDigitSigned,r);case 2:return S(X.numericPatterns.twoDigitsSigned,r);case 3:return S(X.numericPatterns.threeDigitsSigned,r);case 4:return S(X.numericPatterns.fourDigitsSigned,r);default:return S(new RegExp("^-?\\d{1,"+e+"}"),r)}}function XP(e){switch(e){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;case"am":case"midnight":case"night":default:return 0}}function VP(e,r){let t=r>0,n=t?r:1-r,u;if(n<=50)u=e||100;else{let a=n+50,o=Math.trunc(a/100)*100,c=e>=a%100;u=e+o-(c?100:0)}return t?u:1-u}function GP(e){return e%400===0||e%4===0&&e%100!==0}});var u_=s(Ht=>{"use strict";Ht.YearParser=void 0;var UP=M(),_e=w(),Nt=class extends UP.Parser{priority=130;incompatibleTokens=["Y","R","u","w","I","i","e","c","t","T"];parse(r,t,n){let u=a=>({year:a,isTwoDigitYear:t==="yy"});switch(t){case"y":return(0,_e.mapValue)((0,_e.parseNDigits)(4,r),u);case"yo":return(0,_e.mapValue)(n.ordinalNumber(r,{unit:"year"}),u);default:return(0,_e.mapValue)((0,_e.parseNDigits)(t.length,r),u)}}validate(r,t){return t.isTwoDigitYear||t.year>0}set(r,t,n){let u=r.getFullYear();if(n.isTwoDigitYear){let o=(0,_e.normalizeTwoDigitYear)(n.year,u);return r.setFullYear(o,0,1),r.setHours(0,0,0,0),r}let a=!("era"in t)||t.era===1?n.year:1-n.year;return r.setFullYear(a,0,1),r.setHours(0,0,0,0),r}};Ht.YearParser=Nt});var s_=s(Ct=>{"use strict";Ct.LocalWeekYearParser=void 0;var JP=Pe(),a_=N(),KP=M(),me=w(),Lt=class extends KP.Parser{priority=130;parse(r,t,n){let u=a=>({year:a,isTwoDigitYear:t==="YY"});switch(t){case"Y":return(0,me.mapValue)((0,me.parseNDigits)(4,r),u);case"Yo":return(0,me.mapValue)(n.ordinalNumber(r,{unit:"year"}),u);default:return(0,me.mapValue)((0,me.parseNDigits)(t.length,r),u)}}validate(r,t){return t.isTwoDigitYear||t.year>0}set(r,t,n,u){let a=(0,JP.getWeekYear)(r,u);if(n.isTwoDigitYear){let c=(0,me.normalizeTwoDigitYear)(n.year,a);return r.setFullYear(c,0,u.firstWeekContainsDate),r.setHours(0,0,0,0),(0,a_.startOfWeek)(r,u)}let o=!("era"in t)||t.era===1?n.year:1-n.year;return r.setFullYear(o,0,u.firstWeekContainsDate),r.setHours(0,0,0,0),(0,a_.startOfWeek)(r,u)}incompatibleTokens=["y","R","u","Q","q","M","L","I","d","D","i","t","T"]};Ct.LocalWeekYearParser=Lt});var c_=s(Bt=>{"use strict";Bt.ISOWeekYearParser=void 0;var yP=L(),kP=b(),e1=M(),o_=w(),zt=class extends e1.Parser{priority=130;parse(r,t){return t==="R"?(0,o_.parseNDigitsSigned)(4,r):(0,o_.parseNDigitsSigned)(t.length,r)}set(r,t,n){let u=(0,kP.constructFrom)(r,0);return u.setFullYear(n,0,4),u.setHours(0,0,0,0),(0,yP.startOfISOWeek)(u)}incompatibleTokens=["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"]};Bt.ISOWeekYearParser=zt});var d_=s(Rt=>{"use strict";Rt.ExtendedYearParser=void 0;var r1=M(),f_=w(),Qt=class extends r1.Parser{priority=130;parse(r,t){return t==="u"?(0,f_.parseNDigitsSigned)(4,r):(0,f_.parseNDigitsSigned)(t.length,r)}set(r,t,n){return r.setFullYear(n,0,1),r.setHours(0,0,0,0),r}incompatibleTokens=["G","y","Y","R","w","I","i","e","c","t","T"]};Rt.ExtendedYearParser=Qt});var l_=s($t=>{"use strict";$t.QuarterParser=void 0;var t1=M(),n1=w(),At=class extends t1.Parser{priority=120;parse(r,t,n){switch(t){case"Q":case"QQ":return(0,n1.parseNDigits)(t.length,r);case"Qo":return n.ordinalNumber(r,{unit:"quarter"});case"QQQ":return n.quarter(r,{width:"abbreviated",context:"formatting"})||n.quarter(r,{width:"narrow",context:"formatting"});case"QQQQQ":return n.quarter(r,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(r,{width:"wide",context:"formatting"})||n.quarter(r,{width:"abbreviated",context:"formatting"})||n.quarter(r,{width:"narrow",context:"formatting"})}}validate(r,t){return t>=1&&t<=4}set(r,t,n){return r.setMonth((n-1)*3,1),r.setHours(0,0,0,0),r}incompatibleTokens=["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"]};$t.QuarterParser=At});var h_=s(Xt=>{"use strict";Xt.StandAloneQuarterParser=void 0;var i1=M(),u1=w(),Zt=class extends i1.Parser{priority=120;parse(r,t,n){switch(t){case"q":case"qq":return(0,u1.parseNDigits)(t.length,r);case"qo":return n.ordinalNumber(r,{unit:"quarter"});case"qqq":return n.quarter(r,{width:"abbreviated",context:"standalone"})||n.quarter(r,{width:"narrow",context:"standalone"});case"qqqqq":return n.quarter(r,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(r,{width:"wide",context:"standalone"})||n.quarter(r,{width:"abbreviated",context:"standalone"})||n.quarter(r,{width:"narrow",context:"standalone"})}}validate(r,t){return t>=1&&t<=4}set(r,t,n){return r.setMonth((n-1)*3,1),r.setHours(0,0,0,0),r}incompatibleTokens=["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"]};Xt.StandAloneQuarterParser=Zt});var __=s(Gt=>{"use strict";Gt.MonthParser=void 0;var a1=W(),s1=M(),We=w(),Vt=class extends s1.Parser{incompatibleTokens=["Y","R","q","Q","L","w","I","D","i","e","c","t","T"];priority=110;parse(r,t,n){let u=a=>a-1;switch(t){case"M":return(0,We.mapValue)((0,We.parseNumericPattern)(a1.numericPatterns.month,r),u);case"MM":return(0,We.mapValue)((0,We.parseNDigits)(2,r),u);case"Mo":return(0,We.mapValue)(n.ordinalNumber(r,{unit:"month"}),u);case"MMM":return n.month(r,{width:"abbreviated",context:"formatting"})||n.month(r,{width:"narrow",context:"formatting"});case"MMMMM":return n.month(r,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(r,{width:"wide",context:"formatting"})||n.month(r,{width:"abbreviated",context:"formatting"})||n.month(r,{width:"narrow",context:"formatting"})}}validate(r,t){return t>=0&&t<=11}set(r,t,n){return r.setMonth(n,1),r.setHours(0,0,0,0),r}};Gt.MonthParser=Vt});var m_=s(Jt=>{"use strict";Jt.StandAloneMonthParser=void 0;var o1=W(),c1=M(),Se=w(),Ut=class extends c1.Parser{priority=110;parse(r,t,n){let u=a=>a-1;switch(t){case"L":return(0,Se.mapValue)((0,Se.parseNumericPattern)(o1.numericPatterns.month,r),u);case"LL":return(0,Se.mapValue)((0,Se.parseNDigits)(2,r),u);case"Lo":return(0,Se.mapValue)(n.ordinalNumber(r,{unit:"month"}),u);case"LLL":return n.month(r,{width:"abbreviated",context:"standalone"})||n.month(r,{width:"narrow",context:"standalone"});case"LLLLL":return n.month(r,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(r,{width:"wide",context:"standalone"})||n.month(r,{width:"abbreviated",context:"standalone"})||n.month(r,{width:"narrow",context:"standalone"})}}validate(r,t){return t>=0&&t<=11}set(r,t,n){return r.setMonth(n,1),r.setHours(0,0,0,0),r}incompatibleTokens=["Y","R","q","Q","M","w","I","D","i","e","c","t","T"]};Jt.StandAloneMonthParser=Ut});var Kt=s(g_=>{"use strict";g_.setWeek=d1;var f1=dr(),b_=l();function d1(e,r,t){let n=(0,b_.toDate)(e,t?.in),u=(0,f1.getWeek)(n,t)-r;return n.setDate(n.getDate()-u*7),(0,b_.toDate)(n,t?.in)}});var x_=s(kt=>{"use strict";kt.LocalWeekParser=void 0;var l1=Kt(),h1=N(),_1=W(),m1=M(),v_=w(),yt=class extends m1.Parser{priority=100;parse(r,t,n){switch(t){case"w":return(0,v_.parseNumericPattern)(_1.numericPatterns.week,r);case"wo":return n.ordinalNumber(r,{unit:"week"});default:return(0,v_.parseNDigits)(t.length,r)}}validate(r,t){return t>=1&&t<=53}set(r,t,n,u){return(0,h1.startOfWeek)((0,l1.setWeek)(r,n,u),u)}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","i","t","T"]};kt.LocalWeekParser=yt});var en=s(O_=>{"use strict";O_.setISOWeek=v1;var b1=cr(),g1=l();function v1(e,r,t){let n=(0,g1.toDate)(e,t?.in),u=(0,b1.getISOWeek)(n,t)-r;return n.setDate(n.getDate()-u*7),n}});var p_=s(tn=>{"use strict";tn.ISOWeekParser=void 0;var x1=en(),O1=L(),q1=W(),p1=M(),q_=w(),rn=class extends p1.Parser{priority=100;parse(r,t,n){switch(t){case"I":return(0,q_.parseNumericPattern)(q1.numericPatterns.week,r);case"Io":return n.ordinalNumber(r,{unit:"week"});default:return(0,q_.parseNDigits)(t.length,r)}}validate(r,t){return t>=1&&t<=53}set(r,t,n){return(0,O1.startOfISOWeek)((0,x1.setISOWeek)(r,n))}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"]};tn.ISOWeekParser=rn});var M_=s(an=>{"use strict";an.DateParser=void 0;var M1=W(),D1=M(),nn=w(),w1=[31,28,31,30,31,30,31,31,30,31,30,31],P1=[31,29,31,30,31,30,31,31,30,31,30,31],un=class extends D1.Parser{priority=90;subPriority=1;parse(r,t,n){switch(t){case"d":return(0,nn.parseNumericPattern)(M1.numericPatterns.date,r);case"do":return n.ordinalNumber(r,{unit:"date"});default:return(0,nn.parseNDigits)(t.length,r)}}validate(r,t){let n=r.getFullYear(),u=(0,nn.isLeapYearIndex)(n),a=r.getMonth();return u?t>=1&&t<=P1[a]:t>=1&&t<=w1[a]}set(r,t,n){return r.setDate(n),r.setHours(0,0,0,0),r}incompatibleTokens=["Y","R","q","Q","w","I","D","i","e","c","t","T"]};an.DateParser=un});var D_=s(cn=>{"use strict";cn.DayOfYearParser=void 0;var j1=W(),I1=M(),sn=w(),on=class extends I1.Parser{priority=90;subpriority=1;parse(r,t,n){switch(t){case"D":case"DD":return(0,sn.parseNumericPattern)(j1.numericPatterns.dayOfYear,r);case"Do":return n.ordinalNumber(r,{unit:"date"});default:return(0,sn.parseNDigits)(t.length,r)}}validate(r,t){let n=r.getFullYear();return(0,sn.isLeapYearIndex)(n)?t>=1&&t<=366:t>=1&&t<=365}set(r,t,n){return r.setMonth(0,n),r.setHours(0,0,0,0),r}incompatibleTokens=["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"]};cn.DayOfYearParser=on});var Fe=s(w_=>{"use strict";w_.setDay=W1;var T1=Y(),E1=H(),Y1=l();function W1(e,r,t){let n=(0,T1.getDefaultOptions)(),u=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??n.weekStartsOn??n.locale?.options?.weekStartsOn??0,a=(0,Y1.toDate)(e,t?.in),o=a.getDay(),f=(r%7+7)%7,d=7-u,h=r<0||r>6?r-(o+d)%7:(f+d)%7-(o+d)%7;return(0,E1.addDays)(a,h,t)}});var P_=s(dn=>{"use strict";dn.DayParser=void 0;var S1=Fe(),F1=M(),fn=class extends F1.Parser{priority=90;parse(r,t,n){switch(t){case"E":case"EE":case"EEE":return n.day(r,{width:"abbreviated",context:"formatting"})||n.day(r,{width:"short",context:"formatting"})||n.day(r,{width:"narrow",context:"formatting"});case"EEEEE":return n.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(r,{width:"short",context:"formatting"})||n.day(r,{width:"narrow",context:"formatting"});case"EEEE":default:return n.day(r,{width:"wide",context:"formatting"})||n.day(r,{width:"abbreviated",context:"formatting"})||n.day(r,{width:"short",context:"formatting"})||n.day(r,{width:"narrow",context:"formatting"})}}validate(r,t){return t>=0&&t<=6}set(r,t,n,u){return r=(0,S1.setDay)(r,n,u),r.setHours(0,0,0,0),r}incompatibleTokens=["D","i","e","c","t","T"]};dn.DayParser=fn});var j_=s(_n=>{"use strict";_n.LocalDayParser=void 0;var N1=Fe(),H1=M(),ln=w(),hn=class extends H1.Parser{priority=90;parse(r,t,n,u){let a=o=>{let c=Math.floor((o-1)/7)*7;return(o+u.weekStartsOn+6)%7+c};switch(t){case"e":case"ee":return(0,ln.mapValue)((0,ln.parseNDigits)(t.length,r),a);case"eo":return(0,ln.mapValue)(n.ordinalNumber(r,{unit:"day"}),a);case"eee":return n.day(r,{width:"abbreviated",context:"formatting"})||n.day(r,{width:"short",context:"formatting"})||n.day(r,{width:"narrow",context:"formatting"});case"eeeee":return n.day(r,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(r,{width:"short",context:"formatting"})||n.day(r,{width:"narrow",context:"formatting"});case"eeee":default:return n.day(r,{width:"wide",context:"formatting"})||n.day(r,{width:"abbreviated",context:"formatting"})||n.day(r,{width:"short",context:"formatting"})||n.day(r,{width:"narrow",context:"formatting"})}}validate(r,t){return t>=0&&t<=6}set(r,t,n,u){return r=(0,N1.setDay)(r,n,u),r.setHours(0,0,0,0),r}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"]};_n.LocalDayParser=hn});var I_=s(gn=>{"use strict";gn.StandAloneLocalDayParser=void 0;var L1=Fe(),C1=M(),mn=w(),bn=class extends C1.Parser{priority=90;parse(r,t,n,u){let a=o=>{let c=Math.floor((o-1)/7)*7;return(o+u.weekStartsOn+6)%7+c};switch(t){case"c":case"cc":return(0,mn.mapValue)((0,mn.parseNDigits)(t.length,r),a);case"co":return(0,mn.mapValue)(n.ordinalNumber(r,{unit:"day"}),a);case"ccc":return n.day(r,{width:"abbreviated",context:"standalone"})||n.day(r,{width:"short",context:"standalone"})||n.day(r,{width:"narrow",context:"standalone"});case"ccccc":return n.day(r,{width:"narrow",context:"standalone"});case"cccccc":return n.day(r,{width:"short",context:"standalone"})||n.day(r,{width:"narrow",context:"standalone"});case"cccc":default:return n.day(r,{width:"wide",context:"standalone"})||n.day(r,{width:"abbreviated",context:"standalone"})||n.day(r,{width:"short",context:"standalone"})||n.day(r,{width:"narrow",context:"standalone"})}}validate(r,t){return t>=0&&t<=6}set(r,t,n,u){return r=(0,L1.setDay)(r,n,u),r.setHours(0,0,0,0),r}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"]};gn.StandAloneLocalDayParser=bn});var vn=s(T_=>{"use strict";T_.setISODay=R1;var z1=H(),B1=Ot(),Q1=l();function R1(e,r,t){let n=(0,Q1.toDate)(e,t?.in),u=(0,B1.getISODay)(n,t),a=r-u;return(0,z1.addDays)(n,a,t)}});var E_=s(On=>{"use strict";On.ISODayParser=void 0;var A1=vn(),$1=M(),Ne=w(),xn=class extends $1.Parser{priority=90;parse(r,t,n){let u=a=>a===0?7:a;switch(t){case"i":case"ii":return(0,Ne.parseNDigits)(t.length,r);case"io":return n.ordinalNumber(r,{unit:"day"});case"iii":return(0,Ne.mapValue)(n.day(r,{width:"abbreviated",context:"formatting"})||n.day(r,{width:"short",context:"formatting"})||n.day(r,{width:"narrow",context:"formatting"}),u);case"iiiii":return(0,Ne.mapValue)(n.day(r,{width:"narrow",context:"formatting"}),u);case"iiiiii":return(0,Ne.mapValue)(n.day(r,{width:"short",context:"formatting"})||n.day(r,{width:"narrow",context:"formatting"}),u);case"iiii":default:return(0,Ne.mapValue)(n.day(r,{width:"wide",context:"formatting"})||n.day(r,{width:"abbreviated",context:"formatting"})||n.day(r,{width:"short",context:"formatting"})||n.day(r,{width:"narrow",context:"formatting"}),u)}}validate(r,t){return t>=1&&t<=7}set(r,t,n){return r=(0,A1.setISODay)(r,n),r.setHours(0,0,0,0),r}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"]};On.ISODayParser=xn});var Y_=s(pn=>{"use strict";pn.AMPMParser=void 0;var Z1=M(),X1=w(),qn=class extends Z1.Parser{priority=80;parse(r,t,n){switch(t){case"a":case"aa":case"aaa":return n.dayPeriod(r,{width:"abbreviated",context:"formatting"})||n.dayPeriod(r,{width:"narrow",context:"formatting"});case"aaaaa":return n.dayPeriod(r,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(r,{width:"wide",context:"formatting"})||n.dayPeriod(r,{width:"abbreviated",context:"formatting"})||n.dayPeriod(r,{width:"narrow",context:"formatting"})}}set(r,t,n){return r.setHours((0,X1.dayPeriodEnumToHours)(n),0,0,0),r}incompatibleTokens=["b","B","H","k","t","T"]};pn.AMPMParser=qn});var W_=s(Dn=>{"use strict";Dn.AMPMMidnightParser=void 0;var V1=M(),G1=w(),Mn=class extends V1.Parser{priority=80;parse(r,t,n){switch(t){case"b":case"bb":case"bbb":return n.dayPeriod(r,{width:"abbreviated",context:"formatting"})||n.dayPeriod(r,{width:"narrow",context:"formatting"});case"bbbbb":return n.dayPeriod(r,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(r,{width:"wide",context:"formatting"})||n.dayPeriod(r,{width:"abbreviated",context:"formatting"})||n.dayPeriod(r,{width:"narrow",context:"formatting"})}}set(r,t,n){return r.setHours((0,G1.dayPeriodEnumToHours)(n),0,0,0),r}incompatibleTokens=["a","B","H","k","t","T"]};Dn.AMPMMidnightParser=Mn});var S_=s(Pn=>{"use strict";Pn.DayPeriodParser=void 0;var U1=M(),J1=w(),wn=class extends U1.Parser{priority=80;parse(r,t,n){switch(t){case"B":case"BB":case"BBB":return n.dayPeriod(r,{width:"abbreviated",context:"formatting"})||n.dayPeriod(r,{width:"narrow",context:"formatting"});case"BBBBB":return n.dayPeriod(r,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(r,{width:"wide",context:"formatting"})||n.dayPeriod(r,{width:"abbreviated",context:"formatting"})||n.dayPeriod(r,{width:"narrow",context:"formatting"})}}set(r,t,n){return r.setHours((0,J1.dayPeriodEnumToHours)(n),0,0,0),r}incompatibleTokens=["a","b","t","T"]};Pn.DayPeriodParser=wn});var N_=s(In=>{"use strict";In.Hour1to12Parser=void 0;var K1=W(),y1=M(),F_=w(),jn=class extends y1.Parser{priority=70;parse(r,t,n){switch(t){case"h":return(0,F_.parseNumericPattern)(K1.numericPatterns.hour12h,r);case"ho":return n.ordinalNumber(r,{unit:"hour"});default:return(0,F_.parseNDigits)(t.length,r)}}validate(r,t){return t>=1&&t<=12}set(r,t,n){let u=r.getHours()>=12;return u&&n<12?r.setHours(n+12,0,0,0):!u&&n===12?r.setHours(0,0,0,0):r.setHours(n,0,0,0),r}incompatibleTokens=["H","K","k","t","T"]};In.Hour1to12Parser=jn});var L_=s(En=>{"use strict";En.Hour0to23Parser=void 0;var k1=W(),ej=M(),H_=w(),Tn=class extends ej.Parser{priority=70;parse(r,t,n){switch(t){case"H":return(0,H_.parseNumericPattern)(k1.numericPatterns.hour23h,r);case"Ho":return n.ordinalNumber(r,{unit:"hour"});default:return(0,H_.parseNDigits)(t.length,r)}}validate(r,t){return t>=0&&t<=23}set(r,t,n){return r.setHours(n,0,0,0),r}incompatibleTokens=["a","b","h","K","k","t","T"]};En.Hour0to23Parser=Tn});var z_=s(Wn=>{"use strict";Wn.Hour0To11Parser=void 0;var rj=W(),tj=M(),C_=w(),Yn=class extends tj.Parser{priority=70;parse(r,t,n){switch(t){case"K":return(0,C_.parseNumericPattern)(rj.numericPatterns.hour11h,r);case"Ko":return n.ordinalNumber(r,{unit:"hour"});default:return(0,C_.parseNDigits)(t.length,r)}}validate(r,t){return t>=0&&t<=11}set(r,t,n){return r.getHours()>=12&&n<12?r.setHours(n+12,0,0,0):r.setHours(n,0,0,0),r}incompatibleTokens=["h","H","k","t","T"]};Wn.Hour0To11Parser=Yn});var Q_=s(Fn=>{"use strict";Fn.Hour1To24Parser=void 0;var nj=W(),ij=M(),B_=w(),Sn=class extends ij.Parser{priority=70;parse(r,t,n){switch(t){case"k":return(0,B_.parseNumericPattern)(nj.numericPatterns.hour24h,r);case"ko":return n.ordinalNumber(r,{unit:"hour"});default:return(0,B_.parseNDigits)(t.length,r)}}validate(r,t){return t>=1&&t<=24}set(r,t,n){let u=n<=24?n%24:n;return r.setHours(u,0,0,0),r}incompatibleTokens=["a","b","h","H","K","t","T"]};Fn.Hour1To24Parser=Sn});var A_=s(Hn=>{"use strict";Hn.MinuteParser=void 0;var uj=W(),aj=M(),R_=w(),Nn=class extends aj.Parser{priority=60;parse(r,t,n){switch(t){case"m":return(0,R_.parseNumericPattern)(uj.numericPatterns.minute,r);case"mo":return n.ordinalNumber(r,{unit:"minute"});default:return(0,R_.parseNDigits)(t.length,r)}}validate(r,t){return t>=0&&t<=59}set(r,t,n){return r.setMinutes(n,0,0),r}incompatibleTokens=["t","T"]};Hn.MinuteParser=Nn});var Z_=s(Cn=>{"use strict";Cn.SecondParser=void 0;var sj=W(),oj=M(),$_=w(),Ln=class extends oj.Parser{priority=50;parse(r,t,n){switch(t){case"s":return(0,$_.parseNumericPattern)(sj.numericPatterns.second,r);case"so":return n.ordinalNumber(r,{unit:"second"});default:return(0,$_.parseNDigits)(t.length,r)}}validate(r,t){return t>=0&&t<=59}set(r,t,n){return r.setSeconds(n,0),r}incompatibleTokens=["t","T"]};Cn.SecondParser=Ln});var V_=s(Bn=>{"use strict";Bn.FractionOfSecondParser=void 0;var cj=M(),X_=w(),zn=class extends cj.Parser{priority=30;parse(r,t){let n=u=>Math.trunc(u*Math.pow(10,-t.length+3));return(0,X_.mapValue)((0,X_.parseNDigits)(t.length,r),n)}set(r,t,n){return r.setMilliseconds(n),r}incompatibleTokens=["t","T"]};Bn.FractionOfSecondParser=zn});var G_=s(Rn=>{"use strict";Rn.ISOTimezoneWithZParser=void 0;var fj=b(),dj=R(),He=W(),lj=M(),Le=w(),Qn=class extends lj.Parser{priority=10;parse(r,t){switch(t){case"X":return(0,Le.parseTimezonePattern)(He.timezonePatterns.basicOptionalMinutes,r);case"XX":return(0,Le.parseTimezonePattern)(He.timezonePatterns.basic,r);case"XXXX":return(0,Le.parseTimezonePattern)(He.timezonePatterns.basicOptionalSeconds,r);case"XXXXX":return(0,Le.parseTimezonePattern)(He.timezonePatterns.extendedOptionalSeconds,r);case"XXX":default:return(0,Le.parseTimezonePattern)(He.timezonePatterns.extended,r)}}set(r,t,n){return t.timestampIsSet?r:(0,fj.constructFrom)(r,r.getTime()-(0,dj.getTimezoneOffsetInMilliseconds)(r)-n)}incompatibleTokens=["t","T","x"]};Rn.ISOTimezoneWithZParser=Qn});var U_=s($n=>{"use strict";$n.ISOTimezoneParser=void 0;var hj=b(),_j=R(),Ce=W(),mj=M(),ze=w(),An=class extends mj.Parser{priority=10;parse(r,t){switch(t){case"x":return(0,ze.parseTimezonePattern)(Ce.timezonePatterns.basicOptionalMinutes,r);case"xx":return(0,ze.parseTimezonePattern)(Ce.timezonePatterns.basic,r);case"xxxx":return(0,ze.parseTimezonePattern)(Ce.timezonePatterns.basicOptionalSeconds,r);case"xxxxx":return(0,ze.parseTimezonePattern)(Ce.timezonePatterns.extendedOptionalSeconds,r);case"xxx":default:return(0,ze.parseTimezonePattern)(Ce.timezonePatterns.extended,r)}}set(r,t,n){return t.timestampIsSet?r:(0,hj.constructFrom)(r,r.getTime()-(0,_j.getTimezoneOffsetInMilliseconds)(r)-n)}incompatibleTokens=["t","T","X"]};$n.ISOTimezoneParser=An});var J_=s(Xn=>{"use strict";Xn.TimestampSecondsParser=void 0;var bj=b(),gj=M(),vj=w(),Zn=class extends gj.Parser{priority=40;parse(r){return(0,vj.parseAnyDigitsSigned)(r)}set(r,t,n){return[(0,bj.constructFrom)(r,n*1e3),{timestampIsSet:!0}]}incompatibleTokens="*"};Xn.TimestampSecondsParser=Zn});var K_=s(Gn=>{"use strict";Gn.TimestampMillisecondsParser=void 0;var xj=b(),Oj=M(),qj=w(),Vn=class extends Oj.Parser{priority=20;parse(r){return(0,qj.parseAnyDigitsSigned)(r)}set(r,t,n){return[(0,xj.constructFrom)(r,n),{timestampIsSet:!0}]}incompatibleTokens="*"};Gn.TimestampMillisecondsParser=Vn});var y_=s(Un=>{"use strict";Un.parsers=void 0;var pj=i_(),Mj=u_(),Dj=s_(),wj=c_(),Pj=d_(),jj=l_(),Ij=h_(),Tj=__(),Ej=m_(),Yj=x_(),Wj=p_(),Sj=M_(),Fj=D_(),Nj=P_(),Hj=j_(),Lj=I_(),Cj=E_(),zj=Y_(),Bj=W_(),Qj=S_(),Rj=N_(),Aj=L_(),$j=z_(),Zj=Q_(),Xj=A_(),Vj=Z_(),Gj=V_(),Uj=G_(),Jj=U_(),Kj=J_(),yj=K_(),X3=Un.parsers={G:new pj.EraParser,y:new Mj.YearParser,Y:new Dj.LocalWeekYearParser,R:new wj.ISOWeekYearParser,u:new Pj.ExtendedYearParser,Q:new jj.QuarterParser,q:new Ij.StandAloneQuarterParser,M:new Tj.MonthParser,L:new Ej.StandAloneMonthParser,w:new Yj.LocalWeekParser,I:new Wj.ISOWeekParser,d:new Sj.DateParser,D:new Fj.DayOfYearParser,E:new Nj.DayParser,e:new Hj.LocalDayParser,c:new Lj.StandAloneLocalDayParser,i:new Cj.ISODayParser,a:new zj.AMPMParser,b:new Bj.AMPMMidnightParser,B:new Qj.DayPeriodParser,h:new Rj.Hour1to12Parser,H:new Aj.Hour0to23Parser,K:new $j.Hour0To11Parser,k:new Zj.Hour1To24Parser,m:new Xj.MinuteParser,s:new Vj.SecondParser,S:new Gj.FractionOfSecondParser,X:new Uj.ISOTimezoneWithZParser,x:new Jj.ISOTimezoneParser,t:new Kj.TimestampSecondsParser,T:new yj.TimestampMillisecondsParser}});var Kn=s(br=>{"use strict";Object.defineProperty(br,"longFormatters",{enumerable:!0,get:function(){return Jn.longFormatters}});br.parse=cI;Object.defineProperty(br,"parsers",{enumerable:!0,get:function(){return em.parsers}});var kj=ne(),Jn=ct(),mr=ft(),eI=b(),rI=xt(),k_=l(),tI=Tt(),em=y_(),nI=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,iI=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,uI=/^'([^]*?)'?$/,aI=/''/g,sI=/\S/,oI=/[a-zA-Z]/;function cI(e,r,t,n){let u=()=>(0,eI.constructFrom)(n?.in||t,NaN),a=(0,rI.getDefaultOptions)(),o=n?.locale??a.locale??kj.defaultLocale,c=n?.firstWeekContainsDate??n?.locale?.options?.firstWeekContainsDate??a.firstWeekContainsDate??a.locale?.options?.firstWeekContainsDate??1,f=n?.weekStartsOn??n?.locale?.options?.weekStartsOn??a.weekStartsOn??a.locale?.options?.weekStartsOn??0;if(!r)return e?u():(0,k_.toDate)(t,n?.in);let d={firstWeekContainsDate:c,weekStartsOn:f,locale:o},h=[new tI.DateTimezoneSetter(n?.in,t)],_=r.match(iI).map(m=>{let D=m[0];if(D in Jn.longFormatters){let E=Jn.longFormatters[D];return E(m,o.formatLong)}return m}).join("").match(nI),g=[];for(let m of _){!n?.useAdditionalWeekYearTokens&&(0,mr.isProtectedWeekYearToken)(m)&&(0,mr.warnOrThrowProtectedError)(m,r,e),!n?.useAdditionalDayOfYearTokens&&(0,mr.isProtectedDayOfYearToken)(m)&&(0,mr.warnOrThrowProtectedError)(m,r,e);let D=m[0],E=em.parsers[D];if(E){let{incompatibleTokens:B}=E;if(Array.isArray(B)){let be=g.find(Zo=>B.includes(Zo.token)||Zo.token===D);if(be)throw new RangeError(`The format string mustn't contain \`${be.fullToken}\` and \`${m}\` at the same time`)}else if(E.incompatibleTokens==="*"&&g.length>0)throw new RangeError(`The format string mustn't contain \`${m}\` and any other token at the same time`);g.push({token:D,fullToken:m});let Q=E.run(e,m,o.match,d);if(!Q)return u();h.push(Q.setter),e=Q.rest}else{if(D.match(oI))throw new RangeError("Format string contains an unescaped latin alphabet character `"+D+"`");if(m==="''"?m="'":D==="'"&&(m=fI(m)),e.indexOf(m)===0)e=e.slice(m.length);else return u()}}if(e.length>0&&sI.test(e))return u();let p=h.map(m=>m.priority).sort((m,D)=>D-m).filter((m,D,E)=>E.indexOf(m)===D).map(m=>h.filter(D=>D.priority===m).sort((D,E)=>E.subPriority-D.subPriority)).map(m=>m[0]),q=(0,k_.toDate)(t,n?.in);if(isNaN(+q))return u();let x={};for(let m of p){if(!m.validate(q,d))return u();let D=m.set(q,x,d);Array.isArray(D)?(q=D[0],Object.assign(x,D[1])):q=D}return q}function fI(e){return e.match(uI)[1].replace(aI,"'")}});var tm=s(rm=>{"use strict";rm.isMatch=hI;var dI=$(),lI=Kn();function hI(e,r,t){return(0,dI.isValid)((0,lI.parse)(e,r,new Date,t))}});var im=s(nm=>{"use strict";nm.isMonday=mI;var _I=l();function mI(e,r){return(0,_I.toDate)(e,r?.in).getDay()===1}});var am=s(um=>{"use strict";um.isPast=gI;var bI=l();function gI(e){return+(0,bI.toDate)(e){"use strict";sm.startOfHour=xI;var vI=l();function xI(e,r){let t=(0,vI.toDate)(e,r?.in);return t.setMinutes(0,0,0),t}});var kn=s(cm=>{"use strict";cm.isSameHour=qI;var OI=P(),om=yn();function qI(e,r,t){let[n,u]=(0,OI.normalizeDates)(t?.in,e,r);return+(0,om.startOfHour)(n)==+(0,om.startOfHour)(u)}});var gr=s(dm=>{"use strict";dm.isSameWeek=MI;var pI=P(),fm=N();function MI(e,r,t){let[n,u]=(0,pI.normalizeDates)(t?.in,e,r);return+(0,fm.startOfWeek)(n,t)==+(0,fm.startOfWeek)(u,t)}});var ei=s(lm=>{"use strict";lm.isSameISOWeek=wI;var DI=gr();function wI(e,r,t){return(0,DI.isSameWeek)(e,r,{...t,weekStartsOn:1})}});var mm=s(_m=>{"use strict";_m.isSameISOWeekYear=jI;var hm=ce(),PI=P();function jI(e,r,t){let[n,u]=(0,PI.normalizeDates)(t?.in,e,r);return+(0,hm.startOfISOWeekYear)(n)==+(0,hm.startOfISOWeekYear)(u)}});var ri=s(bm=>{"use strict";bm.startOfMinute=TI;var II=l();function TI(e,r){let t=(0,II.toDate)(e,r?.in);return t.setSeconds(0,0),t}});var ti=s(vm=>{"use strict";vm.isSameMinute=EI;var gm=ri();function EI(e,r){return+(0,gm.startOfMinute)(e)==+(0,gm.startOfMinute)(r)}});var ni=s(xm=>{"use strict";xm.isSameMonth=WI;var YI=P();function WI(e,r,t){let[n,u]=(0,YI.normalizeDates)(t?.in,e,r);return n.getFullYear()===u.getFullYear()&&n.getMonth()===u.getMonth()}});var ii=s(qm=>{"use strict";qm.isSameQuarter=FI;var SI=P(),Om=ir();function FI(e,r,t){let[n,u]=(0,SI.normalizeDates)(t?.in,e,r);return+(0,Om.startOfQuarter)(n)==+(0,Om.startOfQuarter)(u)}});var ui=s(pm=>{"use strict";pm.startOfSecond=HI;var NI=l();function HI(e,r){let t=(0,NI.toDate)(e,r?.in);return t.setMilliseconds(0),t}});var ai=s(Dm=>{"use strict";Dm.isSameSecond=LI;var Mm=ui();function LI(e,r){return+(0,Mm.startOfSecond)(e)==+(0,Mm.startOfSecond)(r)}});var si=s(wm=>{"use strict";wm.isSameYear=zI;var CI=P();function zI(e,r,t){let[n,u]=(0,CI.normalizeDates)(t?.in,e,r);return n.getFullYear()===u.getFullYear()}});var jm=s(Pm=>{"use strict";Pm.isThisHour=AI;var BI=T(),QI=kn(),RI=l();function AI(e,r){return(0,QI.isSameHour)((0,RI.toDate)(e,r?.in),(0,BI.constructNow)(r?.in||e))}});var Tm=s(Im=>{"use strict";Im.isThisISOWeek=VI;var $I=b(),ZI=T(),XI=ei();function VI(e,r){return(0,XI.isSameISOWeek)((0,$I.constructFrom)(r?.in||e,e),(0,ZI.constructNow)(r?.in||e))}});var Ym=s(Em=>{"use strict";Em.isThisMinute=JI;var GI=T(),UI=ti();function JI(e){return(0,UI.isSameMinute)(e,(0,GI.constructNow)(e))}});var Sm=s(Wm=>{"use strict";Wm.isThisMonth=eT;var KI=b(),yI=T(),kI=ni();function eT(e,r){return(0,kI.isSameMonth)((0,KI.constructFrom)(r?.in||e,e),(0,yI.constructNow)(r?.in||e))}});var Nm=s(Fm=>{"use strict";Fm.isThisQuarter=iT;var rT=b(),tT=T(),nT=ii();function iT(e,r){return(0,nT.isSameQuarter)((0,rT.constructFrom)(r?.in||e,e),(0,tT.constructNow)(r?.in||e))}});var Lm=s(Hm=>{"use strict";Hm.isThisSecond=sT;var uT=T(),aT=ai();function sT(e){return(0,aT.isSameSecond)(e,(0,uT.constructNow)(e))}});var zm=s(Cm=>{"use strict";Cm.isThisWeek=dT;var oT=b(),cT=T(),fT=gr();function dT(e,r){return(0,fT.isSameWeek)((0,oT.constructFrom)(r?.in||e,e),(0,cT.constructNow)(r?.in||e),r)}});var Qm=s(Bm=>{"use strict";Bm.isThisYear=mT;var lT=b(),hT=T(),_T=si();function mT(e,r){return(0,_T.isSameYear)((0,lT.constructFrom)(r?.in||e,e),(0,hT.constructNow)(r?.in||e))}});var Am=s(Rm=>{"use strict";Rm.isThursday=gT;var bT=l();function gT(e,r){return(0,bT.toDate)(e,r?.in).getDay()===4}});var Zm=s($m=>{"use strict";$m.isToday=qT;var vT=b(),xT=T(),OT=fe();function qT(e,r){return(0,OT.isSameDay)((0,vT.constructFrom)(r?.in||e,e),(0,xT.constructNow)(r?.in||e))}});var Vm=s(Xm=>{"use strict";Xm.isTomorrow=wT;var pT=H(),MT=T(),DT=fe();function wT(e,r){return(0,DT.isSameDay)(e,(0,pT.addDays)((0,MT.constructNow)(r?.in||e),1),r)}});var Um=s(Gm=>{"use strict";Gm.isTuesday=jT;var PT=l();function jT(e,r){return(0,PT.toDate)(e,r?.in).getDay()===2}});var Km=s(Jm=>{"use strict";Jm.isWednesday=TT;var IT=l();function TT(e,r){return(0,IT.toDate)(e,r?.in).getDay()===3}});var km=s(ym=>{"use strict";ym.isWithinInterval=ET;var oi=l();function ET(e,r,t){let n=+(0,oi.toDate)(e,t?.in),[u,a]=[+(0,oi.toDate)(r.start,t?.in),+(0,oi.toDate)(r.end,t?.in)].sort((o,c)=>o-c);return n>=u&&n<=a}});var Be=s(e0=>{"use strict";e0.subDays=WT;var YT=H();function WT(e,r,t){return(0,YT.addDays)(e,-r,t)}});var t0=s(r0=>{"use strict";r0.isYesterday=LT;var ST=b(),FT=T(),NT=fe(),HT=Be();function LT(e,r){return(0,NT.isSameDay)((0,ST.constructFrom)(r?.in||e,e),(0,HT.subDays)((0,FT.constructNow)(r?.in||e),1))}});var u0=s(i0=>{"use strict";i0.lastDayOfDecade=CT;var n0=l();function CT(e,r){let t=(0,n0.toDate)(e,r?.in),n=t.getFullYear(),u=9+Math.floor(n/10)*10;return t.setFullYear(u+1,0,0),t.setHours(0,0,0,0),(0,n0.toDate)(t,r?.in)}});var ci=s(a0=>{"use strict";a0.lastDayOfWeek=QT;var zT=Y(),BT=l();function QT(e,r){let t=(0,zT.getDefaultOptions)(),n=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,u=(0,BT.toDate)(e,r?.in),a=u.getDay(),o=(a{"use strict";s0.lastDayOfISOWeek=AT;var RT=ci();function AT(e,r){return(0,RT.lastDayOfWeek)(e,{...r,weekStartsOn:1})}});var f0=s(c0=>{"use strict";c0.lastDayOfISOWeekYear=VT;var $T=b(),ZT=U(),XT=L();function VT(e,r){let t=(0,ZT.getISOWeekYear)(e,r),n=(0,$T.constructFrom)(r?.in||e,0);n.setFullYear(t+1,0,4),n.setHours(0,0,0,0);let u=(0,XT.startOfISOWeek)(n,r);return u.setDate(u.getDate()-1),u}});var l0=s(d0=>{"use strict";d0.lastDayOfQuarter=UT;var GT=l();function UT(e,r){let t=(0,GT.toDate)(e,r?.in),n=t.getMonth(),u=n-n%3+3;return t.setMonth(u,0),t.setHours(0,0,0,0),t}});var _0=s(h0=>{"use strict";h0.lastDayOfYear=KT;var JT=l();function KT(e,r){let t=(0,JT.toDate)(e,r?.in),n=t.getFullYear();return t.setFullYear(n+1,0,0),t.setHours(0,0,0,0),t}});var b0=s(fi=>{"use strict";fi.lightFormat=iE;Object.defineProperty(fi,"lightFormatters",{enumerable:!0,get:function(){return m0.lightFormatters}});var m0=at(),yT=$(),kT=l(),eE=/(\w)\1*|''|'(''|[^'])+('|$)|./g,rE=/^'([^]*?)'?$/,tE=/''/g,nE=/[a-zA-Z]/;function iE(e,r){let t=(0,kT.toDate)(e);if(!(0,yT.isValid)(t))throw new RangeError("Invalid time value");let n=r.match(eE);return n?n.map(a=>{if(a==="''")return"'";let o=a[0];if(o==="'")return uE(a);let c=m0.lightFormatters[o];if(c)return c(t,a);if(o.match(nE))throw new RangeError("Format string contains an unescaped latin alphabet character `"+o+"`");return a}).join(""):""}function uE(e){let r=e.match(rE);return r?r[1].replace(tE,"'"):e}});var x0=s(v0=>{"use strict";v0.milliseconds=aE;var g0=O();function aE({years:e,months:r,weeks:t,days:n,hours:u,minutes:a,seconds:o}){let c=0;e&&(c+=e*g0.daysInYear),r&&(c+=r*(g0.daysInYear/12)),t&&(c+=t*7),n&&(c+=n);let f=c*24*60*60;return u&&(f+=u*60*60),a&&(f+=a*60),o&&(f+=o),Math.trunc(f*1e3)}});var q0=s(O0=>{"use strict";O0.millisecondsToHours=oE;var sE=O();function oE(e){let r=e/sE.millisecondsInHour;return Math.trunc(r)}});var M0=s(p0=>{"use strict";p0.millisecondsToMinutes=fE;var cE=O();function fE(e){let r=e/cE.millisecondsInMinute;return Math.trunc(r)}});var w0=s(D0=>{"use strict";D0.millisecondsToSeconds=lE;var dE=O();function lE(e){let r=e/dE.millisecondsInSecond;return Math.trunc(r)}});var j0=s(P0=>{"use strict";P0.minutesToHours=_E;var hE=O();function _E(e){let r=e/hE.minutesInHour;return Math.trunc(r)}});var T0=s(I0=>{"use strict";I0.minutesToMilliseconds=bE;var mE=O();function bE(e){return Math.trunc(e*mE.millisecondsInMinute)}});var Y0=s(E0=>{"use strict";E0.minutesToSeconds=vE;var gE=O();function vE(e){return Math.trunc(e*gE.secondsInMinute)}});var S0=s(W0=>{"use strict";W0.monthsToQuarters=OE;var xE=O();function OE(e){let r=e/xE.monthsInQuarter;return Math.trunc(r)}});var N0=s(F0=>{"use strict";F0.monthsToYears=pE;var qE=O();function pE(e){let r=e/qE.monthsInYear;return Math.trunc(r)}});var V=s(H0=>{"use strict";H0.nextDay=wE;var ME=H(),DE=Ie();function wE(e,r,t){let n=r-(0,DE.getDay)(e,t);return n<=0&&(n+=7),(0,ME.addDays)(e,n,t)}});var C0=s(L0=>{"use strict";L0.nextFriday=jE;var PE=V();function jE(e,r){return(0,PE.nextDay)(e,5,r)}});var B0=s(z0=>{"use strict";z0.nextMonday=TE;var IE=V();function TE(e,r){return(0,IE.nextDay)(e,1,r)}});var R0=s(Q0=>{"use strict";Q0.nextSaturday=YE;var EE=V();function YE(e,r){return(0,EE.nextDay)(e,6,r)}});var $0=s(A0=>{"use strict";A0.nextSunday=SE;var WE=V();function SE(e,r){return(0,WE.nextDay)(e,0,r)}});var X0=s(Z0=>{"use strict";Z0.nextThursday=NE;var FE=V();function NE(e,r){return(0,FE.nextDay)(e,4,r)}});var G0=s(V0=>{"use strict";V0.nextTuesday=LE;var HE=V();function LE(e,r){return(0,HE.nextDay)(e,2,r)}});var J0=s(U0=>{"use strict";U0.nextWednesday=zE;var CE=V();function zE(e,r){return(0,CE.nextDay)(e,3,r)}});var eb=s(k0=>{"use strict";k0.parseISO=QE;var xr=O(),BE=b(),K0=l();function QE(e,r){let t=()=>(0,BE.constructFrom)(r?.in,NaN),n=r?.additionalDigits??2,u=ZE(e),a;if(u.date){let d=XE(u.date,n);a=VE(d.restDateString,d.year)}if(!a||isNaN(+a))return t();let o=+a,c=0,f;if(u.time&&(c=GE(u.time),isNaN(c)))return t();if(u.timezone){if(f=UE(u.timezone),isNaN(f))return t()}else{let d=new Date(o+c),h=(0,K0.toDate)(0,r?.in);return h.setFullYear(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()),h.setHours(d.getUTCHours(),d.getUTCMinutes(),d.getUTCSeconds(),d.getUTCMilliseconds()),h}return(0,K0.toDate)(o+c+f,r?.in)}var vr={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},RE=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,AE=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,$E=/^([+-])(\d{2})(?::?(\d{2}))?$/;function ZE(e){let r={},t=e.split(vr.dateTimeDelimiter),n;if(t.length>2)return r;if(/:/.test(t[0])?n=t[0]:(r.date=t[0],n=t[1],vr.timeZoneDelimiter.test(r.date)&&(r.date=e.split(vr.timeZoneDelimiter)[0],n=e.substr(r.date.length,e.length))),n){let u=vr.timezone.exec(n);u?(r.time=n.replace(u[1],""),r.timezone=u[1]):r.time=n}return r}function XE(e,r){let t=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+r)+"})|(\\d{2}|[+-]\\d{"+(2+r)+"})$)"),n=e.match(t);if(!n)return{year:NaN,restDateString:""};let u=n[1]?parseInt(n[1]):null,a=n[2]?parseInt(n[2]):null;return{year:a===null?u:a*100,restDateString:e.slice((n[1]||n[2]).length)}}function VE(e,r){if(r===null)return new Date(NaN);let t=e.match(RE);if(!t)return new Date(NaN);let n=!!t[4],u=Qe(t[1]),a=Qe(t[2])-1,o=Qe(t[3]),c=Qe(t[4]),f=Qe(t[5])-1;if(n)return e2(r,c,f)?JE(r,c,f):new Date(NaN);{let d=new Date(0);return!yE(r,a,o)||!kE(r,u)?new Date(NaN):(d.setUTCFullYear(r,a,Math.max(u,o)),d)}}function Qe(e){return e?parseInt(e):1}function GE(e){let r=e.match(AE);if(!r)return NaN;let t=di(r[1]),n=di(r[2]),u=di(r[3]);return r2(t,n,u)?t*xr.millisecondsInHour+n*xr.millisecondsInMinute+u*1e3:NaN}function di(e){return e&&parseFloat(e.replace(",","."))||0}function UE(e){if(e==="Z")return 0;let r=e.match($E);if(!r)return 0;let t=r[1]==="+"?-1:1,n=parseInt(r[2]),u=r[3]&&parseInt(r[3])||0;return t2(n,u)?t*(n*xr.millisecondsInHour+u*xr.millisecondsInMinute):NaN}function JE(e,r,t){let n=new Date(0);n.setUTCFullYear(e,0,4);let u=n.getUTCDay()||7,a=(r-1)*7+t+1-u;return n.setUTCDate(n.getUTCDate()+a),n}var KE=[31,null,31,30,31,30,31,31,30,31,30,31];function y0(e){return e%400===0||e%4===0&&e%100!==0}function yE(e,r,t){return r>=0&&r<=11&&t>=1&&t<=(KE[r]||(y0(e)?29:28))}function kE(e,r){return r>=1&&r<=(y0(e)?366:365)}function e2(e,r,t){return r>=1&&r<=53&&t>=0&&t<=6}function r2(e,r,t){return e===24?r===0&&t===0:t>=0&&t<60&&r>=0&&r<60&&e>=0&&e<25}function t2(e,r){return r>=0&&r<=59}});var nb=s(tb=>{"use strict";tb.parseJSON=n2;var rb=l();function n2(e,r){let t=e.match(/(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{0,7}))?(?:Z|(.)(\d{2}):?(\d{2})?)?/);return t?(0,rb.toDate)(Date.UTC(+t[1],+t[2]-1,+t[3],+t[4]-(+t[9]||0)*(t[8]=="-"?-1:1),+t[5]-(+t[10]||0)*(t[8]=="-"?-1:1),+t[6],+((t[7]||"0")+"00").substring(0,3)),r?.in):(0,rb.toDate)(NaN,r?.in)}});var G=s(ib=>{"use strict";ib.previousDay=a2;var i2=Ie(),u2=Be();function a2(e,r,t){let n=(0,i2.getDay)(e,t)-r;return n<=0&&(n+=7),(0,u2.subDays)(e,n,t)}});var ab=s(ub=>{"use strict";ub.previousFriday=o2;var s2=G();function o2(e,r){return(0,s2.previousDay)(e,5,r)}});var ob=s(sb=>{"use strict";sb.previousMonday=f2;var c2=G();function f2(e,r){return(0,c2.previousDay)(e,1,r)}});var fb=s(cb=>{"use strict";cb.previousSaturday=l2;var d2=G();function l2(e,r){return(0,d2.previousDay)(e,6,r)}});var lb=s(db=>{"use strict";db.previousSunday=_2;var h2=G();function _2(e,r){return(0,h2.previousDay)(e,0,r)}});var _b=s(hb=>{"use strict";hb.previousThursday=b2;var m2=G();function b2(e,r){return(0,m2.previousDay)(e,4,r)}});var bb=s(mb=>{"use strict";mb.previousTuesday=v2;var g2=G();function v2(e,r){return(0,g2.previousDay)(e,2,r)}});var vb=s(gb=>{"use strict";gb.previousWednesday=O2;var x2=G();function O2(e,r){return(0,x2.previousDay)(e,3,r)}});var Ob=s(xb=>{"use strict";xb.quartersToMonths=p2;var q2=O();function p2(e){return Math.trunc(e*q2.monthsInQuarter)}});var pb=s(qb=>{"use strict";qb.quartersToYears=D2;var M2=O();function D2(e){let r=e/M2.quartersInYear;return Math.trunc(r)}});var Db=s(Mb=>{"use strict";Mb.roundToNearestHours=I2;var w2=Z(),P2=b(),j2=l();function I2(e,r){let t=r?.nearestTo??1;if(t<1||t>12)return(0,P2.constructFrom)(r?.in||e,NaN);let n=(0,j2.toDate)(e,r?.in),u=n.getMinutes()/60,a=n.getSeconds()/60/60,o=n.getMilliseconds()/1e3/60/60,c=n.getHours()+u+a+o,f=r?.roundingMethod??"round",h=(0,w2.getRoundingMethod)(f)(c/t)*t;return n.setHours(h,0,0,0),n}});var Pb=s(wb=>{"use strict";wb.roundToNearestMinutes=W2;var T2=Z(),E2=b(),Y2=l();function W2(e,r){let t=r?.nearestTo??1;if(t<1||t>30)return(0,E2.constructFrom)(e,NaN);let n=(0,Y2.toDate)(e,r?.in),u=n.getSeconds()/60,a=n.getMilliseconds()/1e3/60,o=n.getMinutes()+u+a,c=r?.roundingMethod??"round",d=(0,T2.getRoundingMethod)(c)(o/t)*t;return n.setMinutes(d,0,0),n}});var Ib=s(jb=>{"use strict";jb.secondsToHours=F2;var S2=O();function F2(e){let r=e/S2.secondsInHour;return Math.trunc(r)}});var Eb=s(Tb=>{"use strict";Tb.secondsToMilliseconds=H2;var N2=O();function H2(e){return e*N2.millisecondsInSecond}});var Wb=s(Yb=>{"use strict";Yb.secondsToMinutes=C2;var L2=O();function C2(e){let r=e/L2.secondsInMinute;return Math.trunc(r)}});var Or=s(Sb=>{"use strict";Sb.setMonth=R2;var z2=b(),B2=gt(),Q2=l();function R2(e,r,t){let n=(0,Q2.toDate)(e,t?.in),u=n.getFullYear(),a=n.getDate(),o=(0,z2.constructFrom)(t?.in||e,0);o.setFullYear(u,r,15),o.setHours(0,0,0,0);let c=(0,B2.getDaysInMonth)(o);return n.setMonth(r,Math.min(a,c)),n}});var Nb=s(Fb=>{"use strict";Fb.set=X2;var A2=b(),$2=Or(),Z2=l();function X2(e,r,t){let n=(0,Z2.toDate)(e,t?.in);return isNaN(+n)?(0,A2.constructFrom)(t?.in||e,NaN):(r.year!=null&&n.setFullYear(r.year),r.month!=null&&(n=(0,$2.setMonth)(n,r.month)),r.date!=null&&n.setDate(r.date),r.hours!=null&&n.setHours(r.hours),r.minutes!=null&&n.setMinutes(r.minutes),r.seconds!=null&&n.setSeconds(r.seconds),r.milliseconds!=null&&n.setMilliseconds(r.milliseconds),n)}});var Lb=s(Hb=>{"use strict";Hb.setDate=G2;var V2=l();function G2(e,r,t){let n=(0,V2.toDate)(e,t?.in);return n.setDate(r),n}});var zb=s(Cb=>{"use strict";Cb.setDayOfYear=J2;var U2=l();function J2(e,r,t){let n=(0,U2.toDate)(e,t?.in);return n.setMonth(0),n.setDate(r),n}});var Rb=s(Qb=>{"use strict";Qb.setDefaultOptions=K2;var Bb=Y();function K2(e){let r={},t=(0,Bb.getDefaultOptions)();for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n]);for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]===void 0?delete r[n]:r[n]=e[n]);(0,Bb.setDefaultOptions)(r)}});var $b=s(Ab=>{"use strict";Ab.setHours=k2;var y2=l();function k2(e,r,t){let n=(0,y2.toDate)(e,t?.in);return n.setHours(r),n}});var Xb=s(Zb=>{"use strict";Zb.setMilliseconds=rY;var eY=l();function rY(e,r,t){let n=(0,eY.toDate)(e,t?.in);return n.setMilliseconds(r),n}});var Gb=s(Vb=>{"use strict";Vb.setMinutes=nY;var tY=l();function nY(e,r,t){let n=(0,tY.toDate)(e,t?.in);return n.setMinutes(r),n}});var Jb=s(Ub=>{"use strict";Ub.setQuarter=aY;var iY=Or(),uY=l();function aY(e,r,t){let n=(0,uY.toDate)(e,t?.in),u=Math.trunc(n.getMonth()/3)+1,a=r-u;return(0,iY.setMonth)(n,n.getMonth()+a*3)}});var yb=s(Kb=>{"use strict";Kb.setSeconds=oY;var sY=l();function oY(e,r,t){let n=(0,sY.toDate)(e,t?.in);return n.setSeconds(r),n}});var rg=s(eg=>{"use strict";eg.setWeekYear=hY;var cY=Y(),fY=b(),dY=A(),kb=fr(),lY=l();function hY(e,r,t){let n=(0,cY.getDefaultOptions)(),u=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,a=(0,dY.differenceInCalendarDays)((0,lY.toDate)(e,t?.in),(0,kb.startOfWeekYear)(e,t),t),o=(0,fY.constructFrom)(t?.in||e,0);o.setFullYear(r,0,u),o.setHours(0,0,0,0);let c=(0,kb.startOfWeekYear)(o,t);return c.setDate(c.getDate()+a),c}});var ng=s(tg=>{"use strict";tg.setYear=bY;var _Y=b(),mY=l();function bY(e,r,t){let n=(0,mY.toDate)(e,t?.in);return isNaN(+n)?(0,_Y.constructFrom)(t?.in||e,NaN):(n.setFullYear(r),n)}});var ug=s(ig=>{"use strict";ig.startOfDecade=vY;var gY=l();function vY(e,r){let t=(0,gY.toDate)(e,r?.in),n=t.getFullYear(),u=Math.floor(n/10)*10;return t.setFullYear(u,0,1),t.setHours(0,0,0,0),t}});var sg=s(ag=>{"use strict";ag.startOfToday=OY;var xY=xe();function OY(e){return(0,xY.startOfDay)(Date.now(),e)}});var cg=s(og=>{"use strict";og.startOfTomorrow=MY;var qY=b(),pY=T();function MY(e){let r=(0,pY.constructNow)(e?.in),t=r.getFullYear(),n=r.getMonth(),u=r.getDate(),a=(0,qY.constructFrom)(e?.in,0);return a.setFullYear(t,n,u+1),a.setHours(0,0,0,0),a}});var lg=s(dg=>{"use strict";dg.startOfYesterday=DY;var fg=T();function DY(e){let r=(0,fg.constructNow)(e?.in),t=r.getFullYear(),n=r.getMonth(),u=r.getDate(),a=(0,fg.constructNow)(e?.in);return a.setFullYear(t,n,u-1),a.setHours(0,0,0,0),a}});var li=s(hg=>{"use strict";hg.subMonths=PY;var wY=oe();function PY(e,r,t){return(0,wY.addMonths)(e,-r,t)}});var mg=s(_g=>{"use strict";_g.sub=EY;var jY=b(),IY=Be(),TY=li();function EY(e,r,t){let{years:n=0,months:u=0,weeks:a=0,days:o=0,hours:c=0,minutes:f=0,seconds:d=0}=r,h=(0,TY.subMonths)(e,u+n*12,t),_=(0,IY.subDays)(h,o+a*7,t),g=f+c*60,q=(d+g*60)*1e3;return(0,jY.constructFrom)(t?.in||e,+_-q)}});var gg=s(bg=>{"use strict";bg.subBusinessDays=WY;var YY=Er();function WY(e,r,t){return(0,YY.addBusinessDays)(e,-r,t)}});var xg=s(vg=>{"use strict";vg.subHours=FY;var SY=Yr();function FY(e,r,t){return(0,SY.addHours)(e,-r,t)}});var qg=s(Og=>{"use strict";Og.subMilliseconds=HY;var NY=ve();function HY(e,r,t){return(0,NY.addMilliseconds)(e,-r,t)}});var Mg=s(pg=>{"use strict";pg.subMinutes=CY;var LY=Xe();function CY(e,r,t){return(0,LY.addMinutes)(e,-r,t)}});var wg=s(Dg=>{"use strict";Dg.subQuarters=BY;var zY=Ve();function BY(e,r,t){return(0,zY.addQuarters)(e,-r,t)}});var jg=s(Pg=>{"use strict";Pg.subSeconds=RY;var QY=Nr();function RY(e,r,t){return(0,QY.addSeconds)(e,-r,t)}});var Tg=s(Ig=>{"use strict";Ig.subWeeks=$Y;var AY=Oe();function $Y(e,r,t){return(0,AY.addWeeks)(e,-r,t)}});var Yg=s(Eg=>{"use strict";Eg.subYears=XY;var ZY=Hr();function XY(e,r,t){return(0,ZY.addYears)(e,-r,t)}});var Sg=s(Wg=>{"use strict";Wg.weeksToDays=GY;var VY=O();function GY(e){return Math.trunc(e*VY.daysInWeek)}});var Ng=s(Fg=>{"use strict";Fg.yearsToDays=JY;var UY=O();function JY(e){return Math.trunc(e*UY.daysInYear)}});var Lg=s(Hg=>{"use strict";Hg.yearsToMonths=yY;var KY=O();function yY(e){return Math.trunc(e*KY.monthsInYear)}});var zg=s(Cg=>{"use strict";Cg.yearsToQuarters=eW;var kY=O();function eW(e){return Math.trunc(e*kY.quartersInYear)}});var Bg=s(i=>{"use strict";var hi=Pr();Object.keys(hi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===hi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return hi[e]}})});var _i=Er();Object.keys(_i).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===_i[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return _i[e]}})});var mi=H();Object.keys(mi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===mi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return mi[e]}})});var bi=Yr();Object.keys(bi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===bi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return bi[e]}})});var gi=Fr();Object.keys(gi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===gi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return gi[e]}})});var vi=ve();Object.keys(vi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===vi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return vi[e]}})});var xi=Xe();Object.keys(xi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===xi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return xi[e]}})});var Oi=oe();Object.keys(Oi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Oi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Oi[e]}})});var qi=Ve();Object.keys(qi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===qi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return qi[e]}})});var pi=Nr();Object.keys(pi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===pi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return pi[e]}})});var Mi=Oe();Object.keys(Mi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Mi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Mi[e]}})});var Di=Hr();Object.keys(Di).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Di[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Di[e]}})});var wi=Lc();Object.keys(wi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===wi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return wi[e]}})});var Pi=Ac();Object.keys(Pi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Pi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Pi[e]}})});var ji=zr();Object.keys(ji).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ji[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ji[e]}})});var Ii=Vc();Object.keys(Ii).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ii[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ii[e]}})});var Ti=te();Object.keys(Ti).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ti[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ti[e]}})});var Ei=yc();Object.keys(Ei).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ei[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ei[e]}})});var Yi=b();Object.keys(Yi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Yi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Yi[e]}})});var Wi=T();Object.keys(Wi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Wi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Wi[e]}})});var Si=rf();Object.keys(Si).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Si[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Si[e]}})});var Fi=ff();Object.keys(Fi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Fi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Fi[e]}})});var Ni=A();Object.keys(Ni).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ni[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ni[e]}})});var Hi=Qr();Object.keys(Hi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Hi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Hi[e]}})});var Li=bf();Object.keys(Li).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Li[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Li[e]}})});var Ci=Ue();Object.keys(Ci).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ci[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ci[e]}})});var zi=Ar();Object.keys(zi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===zi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return zi[e]}})});var Bi=Je();Object.keys(Bi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Bi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Bi[e]}})});var Qi=Ke();Object.keys(Qi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Qi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Qi[e]}})});var Ri=ye();Object.keys(Ri).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ri[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ri[e]}})});var Ai=ke();Object.keys(Ai).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ai[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ai[e]}})});var $i=Wf();Object.keys($i).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===$i[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return $i[e]}})});var Zi=er();Object.keys(Zi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Zi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Zi[e]}})});var Xi=rr();Object.keys(Xi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Xi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Xi[e]}})});var Vi=qe();Object.keys(Vi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Vi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Vi[e]}})});var Gi=Qf();Object.keys(Gi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Gi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Gi[e]}})});var Ui=pe();Object.keys(Ui).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ui[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ui[e]}})});var Ji=$f();Object.keys(Ji).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ji[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ji[e]}})});var Ki=Vr();Object.keys(Ki).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ki[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ki[e]}})});var yi=Gr();Object.keys(yi).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===yi[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return yi[e]}})});var ki=Jf();Object.keys(ki).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ki[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ki[e]}})});var eu=yf();Object.keys(eu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===eu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return eu[e]}})});var ru=ed();Object.keys(ru).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ru[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ru[e]}})});var tu=nd();Object.keys(tu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===tu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return tu[e]}})});var nu=ud();Object.keys(nu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===nu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return nu[e]}})});var iu=sr();Object.keys(iu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===iu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return iu[e]}})});var uu=cd();Object.keys(uu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===uu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return uu[e]}})});var au=hd();Object.keys(au).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===au[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return au[e]}})});var su=md();Object.keys(su).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===su[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return su[e]}})});var ou=tr();Object.keys(ou).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ou[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ou[e]}})});var cu=gd();Object.keys(cu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===cu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return cu[e]}})});var fu=xd();Object.keys(fu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===fu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return fu[e]}})});var du=pd();Object.keys(du).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===du[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return du[e]}})});var lu=Dd();Object.keys(lu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===lu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return lu[e]}})});var hu=Pd();Object.keys(hu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===hu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return hu[e]}})});var _u=nr();Object.keys(_u).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===_u[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return _u[e]}})});var mu=Id();Object.keys(mu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===mu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return mu[e]}})});var bu=Ed();Object.keys(bu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===bu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return bu[e]}})});var gu=Wd();Object.keys(gu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===gu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return gu[e]}})});var vu=Nd();Object.keys(vu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===vu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return vu[e]}})});var xu=Jr();Object.keys(xu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===xu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return xu[e]}})});var Ou=Ur();Object.keys(Ou).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ou[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ou[e]}})});var qu=Ld();Object.keys(qu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===qu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return qu[e]}})});var pu=ht();Object.keys(pu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===pu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return pu[e]}})});var Mu=_t();Object.keys(Mu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Mu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Mu[e]}})});var Du=mt();Object.keys(Du).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Du[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Du[e]}})});var wu=vl();Object.keys(wu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===wu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return wu[e]}})});var Pu=Ol();Object.keys(Pu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Pu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Pu[e]}})});var ju=pl();Object.keys(ju).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ju[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ju[e]}})});var Iu=Dl();Object.keys(Iu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Iu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Iu[e]}})});var Tu=Pl();Object.keys(Tu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Tu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Tu[e]}})});var Eu=Il();Object.keys(Eu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Eu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Eu[e]}})});var Yu=El();Object.keys(Yu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Yu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Yu[e]}})});var Wu=Wl();Object.keys(Wu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Wu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Wu[e]}})});var Su=Fl();Object.keys(Su).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Su[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Su[e]}})});var Fu=Hl();Object.keys(Fu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Fu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Fu[e]}})});var Nu=bt();Object.keys(Nu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Nu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Nu[e]}})});var Hu=Ie();Object.keys(Hu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Hu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Hu[e]}})});var Lu=it();Object.keys(Lu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Lu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Lu[e]}})});var Cu=gt();Object.keys(Cu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Cu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Cu[e]}})});var zu=Rl();Object.keys(zu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===zu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return zu[e]}})});var Bu=$l();Object.keys(Bu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Bu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Bu[e]}})});var Qu=xt();Object.keys(Qu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Qu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Qu[e]}})});var Ru=Vl();Object.keys(Ru).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ru[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ru[e]}})});var Au=Ot();Object.keys(Au).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Au[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Au[e]}})});var $u=cr();Object.keys($u).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===$u[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return $u[e]}})});var Zu=U();Object.keys(Zu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Zu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Zu[e]}})});var Xu=Kl();Object.keys(Xu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Xu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Xu[e]}})});var Vu=kl();Object.keys(Vu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Vu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Vu[e]}})});var Gu=rh();Object.keys(Gu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Gu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Gu[e]}})});var Uu=nh();Object.keys(Uu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Uu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Uu[e]}})});var Ju=ah();Object.keys(Ju).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ju[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ju[e]}})});var Ku=Rr();Object.keys(Ku).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ku[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ku[e]}})});var yu=oh();Object.keys(yu).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===yu[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return yu[e]}})});var ku=fh();Object.keys(ku).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ku[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ku[e]}})});var ea=lh();Object.keys(ea).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ea[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ea[e]}})});var ra=dr();Object.keys(ra).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ra[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ra[e]}})});var ta=_h();Object.keys(ta).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ta[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ta[e]}})});var na=Pe();Object.keys(na).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===na[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return na[e]}})});var ia=vh();Object.keys(ia).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ia[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ia[e]}})});var ua=Oh();Object.keys(ua).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ua[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ua[e]}})});var aa=ph();Object.keys(aa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===aa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return aa[e]}})});var sa=Dh();Object.keys(sa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===sa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return sa[e]}})});var oa=Ph();Object.keys(oa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===oa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return oa[e]}})});var ca=Ih();Object.keys(ca).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ca[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ca[e]}})});var fa=Eh();Object.keys(fa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===fa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return fa[e]}})});var da=Wh();Object.keys(da).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===da[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return da[e]}})});var la=Ch();Object.keys(la).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===la[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return la[e]}})});var ha=Qh();Object.keys(ha).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ha[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ha[e]}})});var _a=$h();Object.keys(_a).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===_a[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return _a[e]}})});var ma=Br();Object.keys(ma).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ma[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ma[e]}})});var ba=Vh();Object.keys(ba).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ba[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ba[e]}})});var ga=Uh();Object.keys(ga).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ga[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ga[e]}})});var va=Kh();Object.keys(va).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===va[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return va[e]}})});var xa=kh();Object.keys(xa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===xa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return xa[e]}})});var Oa=r_();Object.keys(Oa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Oa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Oa[e]}})});var qa=Zr();Object.keys(qa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===qa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return qa[e]}})});var pa=vt();Object.keys(pa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===pa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return pa[e]}})});var Ma=tm();Object.keys(Ma).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ma[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ma[e]}})});var Da=im();Object.keys(Da).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Da[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Da[e]}})});var wa=am();Object.keys(wa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===wa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return wa[e]}})});var Pa=fe();Object.keys(Pa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Pa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Pa[e]}})});var ja=kn();Object.keys(ja).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ja[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ja[e]}})});var Ia=ei();Object.keys(Ia).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ia[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ia[e]}})});var Ta=mm();Object.keys(Ta).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ta[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ta[e]}})});var Ea=ti();Object.keys(Ea).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ea[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ea[e]}})});var Ya=ni();Object.keys(Ya).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ya[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ya[e]}})});var Wa=ii();Object.keys(Wa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Wa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Wa[e]}})});var Sa=ai();Object.keys(Sa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Sa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Sa[e]}})});var Fa=gr();Object.keys(Fa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Fa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Fa[e]}})});var Na=si();Object.keys(Na).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Na[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Na[e]}})});var Ha=jr();Object.keys(Ha).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ha[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ha[e]}})});var La=Ir();Object.keys(La).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===La[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return La[e]}})});var Ca=jm();Object.keys(Ca).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ca[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ca[e]}})});var za=Tm();Object.keys(za).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===za[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return za[e]}})});var Ba=Ym();Object.keys(Ba).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ba[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ba[e]}})});var Qa=Sm();Object.keys(Qa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Qa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Qa[e]}})});var Ra=Nm();Object.keys(Ra).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ra[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ra[e]}})});var Aa=Lm();Object.keys(Aa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Aa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Aa[e]}})});var $a=zm();Object.keys($a).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===$a[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return $a[e]}})});var Za=Qm();Object.keys(Za).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Za[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Za[e]}})});var Xa=Am();Object.keys(Xa).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Xa[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Xa[e]}})});var Va=Zm();Object.keys(Va).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Va[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Va[e]}})});var Ga=Vm();Object.keys(Ga).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ga[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ga[e]}})});var Ua=Um();Object.keys(Ua).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ua[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ua[e]}})});var Ja=$();Object.keys(Ja).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ja[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ja[e]}})});var Ka=Km();Object.keys(Ka).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ka[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ka[e]}})});var ya=ge();Object.keys(ya).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ya[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ya[e]}})});var ka=km();Object.keys(ka).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ka[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ka[e]}})});var es=t0();Object.keys(es).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===es[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return es[e]}})});var rs=u0();Object.keys(rs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===rs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return rs[e]}})});var ts=o0();Object.keys(ts).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ts[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ts[e]}})});var ns=f0();Object.keys(ns).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ns[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ns[e]}})});var is=qt();Object.keys(is).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===is[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return is[e]}})});var us=l0();Object.keys(us).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===us[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return us[e]}})});var as=ci();Object.keys(as).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===as[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return as[e]}})});var ss=_0();Object.keys(ss).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ss[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ss[e]}})});var os=b0();Object.keys(os).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===os[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return os[e]}})});var cs=Lr();Object.keys(cs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===cs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return cs[e]}})});var fs=x0();Object.keys(fs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===fs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return fs[e]}})});var ds=q0();Object.keys(ds).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ds[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ds[e]}})});var ls=M0();Object.keys(ls).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ls[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ls[e]}})});var hs=w0();Object.keys(hs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===hs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return hs[e]}})});var _s=Cr();Object.keys(_s).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===_s[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return _s[e]}})});var ms=j0();Object.keys(ms).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ms[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ms[e]}})});var bs=T0();Object.keys(bs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===bs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return bs[e]}})});var gs=Y0();Object.keys(gs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===gs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return gs[e]}})});var vs=S0();Object.keys(vs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===vs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return vs[e]}})});var xs=N0();Object.keys(xs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===xs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return xs[e]}})});var Os=V();Object.keys(Os).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Os[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Os[e]}})});var qs=C0();Object.keys(qs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===qs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return qs[e]}})});var ps=B0();Object.keys(ps).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ps[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ps[e]}})});var Ms=R0();Object.keys(Ms).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ms[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ms[e]}})});var Ds=$0();Object.keys(Ds).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ds[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ds[e]}})});var ws=X0();Object.keys(ws).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ws[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ws[e]}})});var Ps=G0();Object.keys(Ps).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ps[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ps[e]}})});var js=J0();Object.keys(js).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===js[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return js[e]}})});var Is=Kn();Object.keys(Is).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Is[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Is[e]}})});var Ts=eb();Object.keys(Ts).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ts[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ts[e]}})});var Es=nb();Object.keys(Es).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Es[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Es[e]}})});var Ys=G();Object.keys(Ys).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ys[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ys[e]}})});var Ws=ab();Object.keys(Ws).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ws[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ws[e]}})});var Ss=ob();Object.keys(Ss).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ss[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ss[e]}})});var Fs=fb();Object.keys(Fs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Fs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Fs[e]}})});var Ns=lb();Object.keys(Ns).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ns[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ns[e]}})});var Hs=_b();Object.keys(Hs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Hs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Hs[e]}})});var Ls=bb();Object.keys(Ls).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ls[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ls[e]}})});var Cs=vb();Object.keys(Cs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Cs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Cs[e]}})});var zs=Ob();Object.keys(zs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===zs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return zs[e]}})});var Bs=pb();Object.keys(Bs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Bs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Bs[e]}})});var Qs=Db();Object.keys(Qs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Qs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Qs[e]}})});var Rs=Pb();Object.keys(Rs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Rs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Rs[e]}})});var As=Ib();Object.keys(As).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===As[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return As[e]}})});var $s=Eb();Object.keys($s).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===$s[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return $s[e]}})});var Zs=Wb();Object.keys(Zs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Zs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Zs[e]}})});var Xs=Nb();Object.keys(Xs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Xs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Xs[e]}})});var Vs=Lb();Object.keys(Vs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Vs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Vs[e]}})});var Gs=Fe();Object.keys(Gs).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Gs[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Gs[e]}})});var Us=zb();Object.keys(Us).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Us[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Us[e]}})});var Js=Rb();Object.keys(Js).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Js[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Js[e]}})});var Ks=$b();Object.keys(Ks).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ks[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ks[e]}})});var ys=vn();Object.keys(ys).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ys[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ys[e]}})});var ks=en();Object.keys(ks).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ks[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ks[e]}})});var eo=Sr();Object.keys(eo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===eo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return eo[e]}})});var ro=Xb();Object.keys(ro).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ro[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ro[e]}})});var to=Gb();Object.keys(to).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===to[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return to[e]}})});var no=Or();Object.keys(no).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===no[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return no[e]}})});var io=Jb();Object.keys(io).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===io[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return io[e]}})});var uo=yb();Object.keys(uo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===uo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return uo[e]}})});var ao=Kt();Object.keys(ao).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ao[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ao[e]}})});var so=rg();Object.keys(so).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===so[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return so[e]}})});var oo=ng();Object.keys(oo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===oo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return oo[e]}})});var co=xe();Object.keys(co).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===co[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return co[e]}})});var fo=ug();Object.keys(fo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===fo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return fo[e]}})});var lo=yn();Object.keys(lo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===lo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return lo[e]}})});var ho=L();Object.keys(ho).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===ho[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return ho[e]}})});var _o=ce();Object.keys(_o).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===_o[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return _o[e]}})});var mo=ri();Object.keys(mo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===mo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return mo[e]}})});var bo=Me();Object.keys(bo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===bo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return bo[e]}})});var go=ir();Object.keys(go).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===go[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return go[e]}})});var vo=ui();Object.keys(vo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===vo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return vo[e]}})});var xo=sg();Object.keys(xo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===xo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return xo[e]}})});var Oo=cg();Object.keys(Oo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Oo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Oo[e]}})});var qo=N();Object.keys(qo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===qo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return qo[e]}})});var po=fr();Object.keys(po).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===po[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return po[e]}})});var Mo=or();Object.keys(Mo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Mo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Mo[e]}})});var Do=lg();Object.keys(Do).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Do[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Do[e]}})});var wo=mg();Object.keys(wo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===wo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return wo[e]}})});var Po=gg();Object.keys(Po).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Po[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Po[e]}})});var jo=Be();Object.keys(jo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===jo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return jo[e]}})});var Io=xg();Object.keys(Io).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Io[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Io[e]}})});var To=$r();Object.keys(To).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===To[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return To[e]}})});var Eo=qg();Object.keys(Eo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Eo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Eo[e]}})});var Yo=Mg();Object.keys(Yo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Yo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Yo[e]}})});var Wo=li();Object.keys(Wo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Wo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Wo[e]}})});var So=wg();Object.keys(So).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===So[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return So[e]}})});var Fo=jg();Object.keys(Fo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Fo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Fo[e]}})});var No=Tg();Object.keys(No).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===No[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return No[e]}})});var Ho=Yg();Object.keys(Ho).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ho[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ho[e]}})});var Lo=l();Object.keys(Lo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Lo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Lo[e]}})});var Co=Pt();Object.keys(Co).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Co[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Co[e]}})});var zo=Sg();Object.keys(zo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===zo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return zo[e]}})});var Bo=Ng();Object.keys(Bo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Bo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Bo[e]}})});var Qo=Lg();Object.keys(Qo).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Qo[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Qo[e]}})});var Ro=zg();Object.keys(Ro).forEach(function(e){e==="default"||e==="__esModule"||e in i&&i[e]===Ro[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return Ro[e]}})})});var Jg=s(($L,Ug)=>{"use strict";var{readdir:Qg,stat:Rg,unlink:Ao,symlink:rW,lstat:tW,readlink:nW}=re("fs/promises"),{dirname:Ag,join:qr}=re("path"),{format:iW,addDays:uW,addHours:aW,parse:sW,isValid:oW}=Bg();function cW(e){let r=1048576;if(typeof e!="string"&&typeof e!="number")return null;if(typeof e=="string"){let t=e.match(/^([\d.]+)(\w?)$/);if(t){let n=t[2]?.toLowerCase();e=+t[1],r=n==="g"?1024**3:n==="k"?1024:n==="b"?1:1024**2}else throw new Error(`${e} is not a valid size in KB, MB or GB`)}return e*r}function fW(e){let r=new Date;if(e==="daily"){let t=r.setHours(0,0,0,0);return{frequency:e,start:t,next:$g(t)}}if(e==="hourly"){let t=r.setMinutes(0,0,0);return{frequency:e,start:t,next:Zg(t)}}if(typeof e=="number"){let t=r.getTime()-r.getTime()%e;return{frequency:e,start:t,next:Xg(e)}}if(e)throw new Error(`${e} is neither a supported frequency or a number of milliseconds`);return null}function dW(e){if(e){if(typeof e!="object")throw new Error("limit must be an object");if(typeof e.count!="number"||e.count<=0)throw new Error("limit.count must be a number greater than 0");if(typeof e.removeOtherLogFiles<"u"&&typeof e.removeOtherLogFiles!="boolean")throw new Error("limit.removeOtherLogFiles must be boolean")}}function $g(e){return uW(new Date(e),1).setHours(0,0,0,0)}function Zg(e){return aW(new Date(e),1).setMinutes(0,0,0)}function Xg(e){let r=Date.now();return r-r%e+e}function lW(e){return e==="daily"?$g(new Date().setHours(0,0,0,0)):e==="hourly"?Zg(new Date().setMinutes(0,0,0)):Xg(e)}function Re(e){if(!e)throw new Error("No file name provided");return typeof e=="function"?e():e}function hW(e,r,t=1,n){let u=r?`.${r}`:"",a=typeof n!="string"?"":n.startsWith(".")?n:`.${n}`;return`${Re(e)}${u}.${t}${a}`}function Vg(e,r,t,n){let u=Re(r);if(!e.startsWith(u))return!1;let a=e.slice(u.length+1).split("."),o=1;typeof t=="string"&&t.length>0&&o++,typeof n=="string"&&n.length>0&&o++;let c=typeof n!="string"?"":n.startsWith(".")?n.slice(1):n;if(a.length!==o)return!1;if(c.length>0){let _=a.pop();if(c!==_)return!1}let f=a.pop(),d=Number(f);if(!Number.isInteger(d))return!1;let h=0;if(typeof t=="string"&&t.length>0){let _=sW(a[0],t,new Date);if(!oW(_))return!1;h=_.getTime()}return{fileName:e,fileTime:h,fileNumber:d}}async function _W(e){try{return(await Rg(e)).size}catch{return 0}}async function mW(e,r=null){let t=Re(e);try{return(await bW(Ag(t),r)).sort((u,a)=>a-u)[0]}catch{return 1}}async function bW(e,r){let t=[1];for(let n of await Qg(e)){if(r&&!await vW(qr(e,n),r))continue;let u=gW(n);u&&t.push(u)}return t}function gW(e){let r=e.match(/(\d+)$/);return r?+r[1]:null}function pr(e){return e.split(/(\\|\/)/g).pop()}async function vW(e,r){let{birthtimeMs:t}=await Rg(e);return t>=r}async function xW({count:e,removeOtherLogFiles:r,baseFile:t,dateFormat:n,extension:u,createdFileNames:a,newFileName:o}){if(r){let c=[],f=Re(t).split(/(\\|\/)/g),d=f.pop();for(let h of await Qg(qr(...f))){let _=Vg(h,d,n,u);_&&c.push(_)}c=c.sort((h,_)=>h.fileTime===_.fileTime?h.fileNumber-_.fileNumber:h.fileTime-_.fileTime),c.length>e&&await Promise.allSettled(c.slice(0,c.length-e).map(h=>Ao(qr(...f,h.fileName))))}else if(a.push(o),a.length>e){let c=a.splice(0,a.length-1-e);await Promise.allSettled(c.map(f=>Ao(f)))}}async function Gg(e,r){if((await tW(r).then(n=>n,()=>null))?.isSymbolicLink()){let n=await nW(r);if(pr(n)===pr(e))return!1;await Ao(r)}return!0}async function OW(e){let r=qr(Ag(e),"current.log");return await Gg(e,r)&&await rW(pr(e),r),!1}function qW(e){if(/[/\\?%*:|"<>]/g.test(e))throw new Error(`${e} contains invalid characters`);return!0}function pW(e,r,t=!1){if(!(e&&r?.start&&r.next))return null;try{return iW(t?r.start:r.next,e)}catch{throw new Error(`${e} must be a valid date format`)}}Ug.exports={buildFileName:hW,identifyLogFile:Vg,removeOldFiles:xW,checkSymlink:Gg,createSymlink:OW,detectLastNumber:mW,extractFileName:pr,parseFrequency:fW,getNext:lW,parseSize:cW,getFileName:Re,getFileSize:_W,validateLimitOptions:dW,parseDate:pW,validateDateFormat:qW}});var WW=s((ZL,kg)=>{var MW=ec(),{buildFileName:$o,removeOldFiles:DW,createSymlink:Kg,detectLastNumber:wW,parseSize:PW,parseFrequency:jW,getNext:IW,getFileSize:TW,validateLimitOptions:EW,parseDate:yg,validateDateFormat:YW}=Jg();kg.exports=async function({file:e,size:r,frequency:t,extension:n,limit:u,symlink:a,dateFormat:o,...c}={}){EW(u),YW(o);let f=jW(t),d=yg(o,f,!0),h=await wW(e,f?.start,o),_=$o(e,d,h,n),g=[_],p=await TW(_),q=PW(r),x=new MW({...c,dest:_});a&&Kg(_);let m;f&&(x.once("close",()=>{clearTimeout(m)}),E()),q&&x.on("write",B=>{p+=B,_===x.file&&p>=q&&(p=0,_=$o(e,d,++h,n),x.once("drain",D))});function D(){x.reopen(_),a&&Kg(_),u&&DW({...u,baseFile:e,dateFormat:o,extension:n,createdFileNames:g,newFileName:_})}function E(){clearTimeout(m),m=setTimeout(()=>{let B=d;d=yg(o,f),o&&d&&d!==B&&(h=0),_=$o(e,d,++h,n),D(),f.next=IW(t),E()},f.next-Date.now())}return x}});export default WW(); +//# sourceMappingURL=pino-roll.mjs.map diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-roll.mjs.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-roll.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..702f301cc8cdc2b0cde32b69e781073d7443342a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-roll.mjs.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/.pnpm/atomic-sleep@1.0.0/node_modules/atomic-sleep/index.js", "../../node_modules/.pnpm/sonic-boom@4.2.0/node_modules/sonic-boom/index.js", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/constants.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/constructFrom.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/toDate.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addMonths.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/add.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSaturday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSunday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isWeekend.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addBusinessDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/defaultOptions.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfISOWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISOWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/getTimezoneOffsetInMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/normalizeDates.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfDay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfISOWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setISOWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addISOWeekYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addQuarters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addWeeks.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/addYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/areIntervalsOverlapping.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/max.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/min.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/clamp.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/closestIndexTo.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/closestTo.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/compareAsc.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/compareDesc.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/constructNow.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/daysToWeeks.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameDay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isDate.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isValid.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInBusinessDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarISOWeekYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarISOWeeks.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarMonths.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getQuarter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarQuarters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarWeeks.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInCalendarYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/getRoundingMethod.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subISOWeekYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInISOWeekYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfDay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isLastDayOfMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInMonths.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInQuarters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInWeeks.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/differenceInYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/normalizeInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachDayOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachHourOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachMinuteOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachMonthOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfQuarter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachQuarterOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachWeekOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachWeekendOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachWeekendOfMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachWeekendOfYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/eachYearOfInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfDecade.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfHour.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfISOWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfISOWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfMinute.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfQuarter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfSecond.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfToday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfTomorrow.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/endOfYesterday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/formatDistance.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildFormatLongFn.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/formatLong.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/formatRelative.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildLocalizeFn.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/localize.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildMatchFn.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/_lib/buildMatchPatternFn.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US/_lib/match.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/locale/en-US.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/defaultLocale.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDayOfYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISOWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/addLeadingZeros.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/format/lightFormatters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/format/formatters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/format/longFormatters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/_lib/protectedTokens.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/format.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistance.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistanceStrict.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistanceToNow.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDistanceToNowStrict.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatDuration.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatISO.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatISO9075.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatISODuration.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatRFC3339.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatRFC7231.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/formatRelative.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/fromUnixTime.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDate.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDaysInMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isLeapYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDaysInYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDecade.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getDefaultOptions.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISODay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getISOWeeksInYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getOverlappingDaysInIntervals.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getTime.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getUnixTime.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeekOfMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getWeeksInMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/getYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/hoursToMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/hoursToMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/hoursToSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/interval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/intervalToDuration.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/intlFormat.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/intlFormatDistance.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isAfter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isBefore.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isEqual.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isExists.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isFirstDayOfMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isFriday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isFuture.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/transpose.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/Setter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/Parser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/EraParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/constants.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/utils.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/YearParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/LocalWeekYearParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/ISOWeekYearParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/ExtendedYearParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/QuarterParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/StandAloneQuarterParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/MonthParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/StandAloneMonthParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/LocalWeekParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setISOWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/ISOWeekParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/DateParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/DayOfYearParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setDay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/DayParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/LocalDayParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/StandAloneLocalDayParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setISODay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/ISODayParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/AMPMParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/AMPMMidnightParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/DayPeriodParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/Hour1to12Parser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/Hour0to23Parser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/Hour0To11Parser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/Hour1To24Parser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/MinuteParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/SecondParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/FractionOfSecondParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/ISOTimezoneWithZParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/ISOTimezoneParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/TimestampSecondsParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers/TimestampMillisecondsParser.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse/_lib/parsers.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parse.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isMatch.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isMonday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isPast.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfHour.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameHour.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameISOWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameISOWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfMinute.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameMinute.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameQuarter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfSecond.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameSecond.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isSameYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisHour.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisISOWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisMinute.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisQuarter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisSecond.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThisYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isThursday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isToday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isTomorrow.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isTuesday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isWednesday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isWithinInterval.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/isYesterday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfDecade.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfISOWeek.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfISOWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfQuarter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lastDayOfYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/lightFormat.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/milliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/millisecondsToHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/millisecondsToMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/millisecondsToSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/minutesToHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/minutesToMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/minutesToSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/monthsToQuarters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/monthsToYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextDay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextFriday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextMonday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextSaturday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextSunday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextThursday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextTuesday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/nextWednesday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parseISO.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/parseJSON.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousDay.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousFriday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousMonday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousSaturday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousSunday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousThursday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousTuesday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/previousWednesday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/quartersToMonths.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/quartersToYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/roundToNearestHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/roundToNearestMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/secondsToHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/secondsToMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/secondsToMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setMonth.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/set.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setDate.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setDayOfYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setDefaultOptions.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setQuarter.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setWeekYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/setYear.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfDecade.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfToday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfTomorrow.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/startOfYesterday.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subMonths.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/sub.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subBusinessDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subHours.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subMilliseconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subMinutes.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subQuarters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subSeconds.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subWeeks.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/subYears.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/weeksToDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/yearsToDays.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/yearsToMonths.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/yearsToQuarters.cjs", "../../node_modules/.pnpm/date-fns@4.1.0/node_modules/date-fns/index.cjs", "../../node_modules/.pnpm/pino-roll@3.1.0/node_modules/pino-roll/lib/utils.js", "../../node_modules/.pnpm/pino-roll@3.1.0/node_modules/pino-roll/pino-roll.js"], + "sourcesContent": ["'use strict'\n\n/* global SharedArrayBuffer, Atomics */\n\nif (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') {\n const nil = new Int32Array(new SharedArrayBuffer(4))\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n\n Atomics.wait(nil, 0, 0, Number(ms))\n }\n module.exports = sleep\n} else {\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n const target = Date.now() + Number(ms)\n while (target > Date.now()){}\n }\n\n module.exports = sleep\n\n}\n", "'use strict'\n\nconst fs = require('fs')\nconst EventEmitter = require('events')\nconst inherits = require('util').inherits\nconst path = require('path')\nconst sleep = require('atomic-sleep')\nconst assert = require('assert')\n\nconst BUSY_WRITE_TIMEOUT = 100\nconst kEmptyBuffer = Buffer.allocUnsafe(0)\n\n// 16 KB. Don't write more than docker buffer size.\n// https://github.com/moby/moby/blob/513ec73831269947d38a644c278ce3cac36783b2/daemon/logger/copier.go#L13\nconst MAX_WRITE = 16 * 1024\n\nconst kContentModeBuffer = 'buffer'\nconst kContentModeUtf8 = 'utf8'\n\nconst [major, minor] = (process.versions.node || '0.0').split('.').map(Number)\nconst kCopyBuffer = major >= 22 && minor >= 7\n\nfunction openFile (file, sonic) {\n sonic._opening = true\n sonic._writing = true\n sonic._asyncDrainScheduled = false\n\n // NOTE: 'error' and 'ready' events emitted below only relevant when sonic.sync===false\n // for sync mode, there is no way to add a listener that will receive these\n\n function fileOpened (err, fd) {\n if (err) {\n sonic._reopening = false\n sonic._writing = false\n sonic._opening = false\n\n if (sonic.sync) {\n process.nextTick(() => {\n if (sonic.listenerCount('error') > 0) {\n sonic.emit('error', err)\n }\n })\n } else {\n sonic.emit('error', err)\n }\n return\n }\n\n const reopening = sonic._reopening\n\n sonic.fd = fd\n sonic.file = file\n sonic._reopening = false\n sonic._opening = false\n sonic._writing = false\n\n if (sonic.sync) {\n process.nextTick(() => sonic.emit('ready'))\n } else {\n sonic.emit('ready')\n }\n\n if (sonic.destroyed) {\n return\n }\n\n // start\n if ((!sonic._writing && sonic._len > sonic.minLength) || sonic._flushPending) {\n sonic._actualWrite()\n } else if (reopening) {\n process.nextTick(() => sonic.emit('drain'))\n }\n }\n\n const flags = sonic.append ? 'a' : 'w'\n const mode = sonic.mode\n\n if (sonic.sync) {\n try {\n if (sonic.mkdir) fs.mkdirSync(path.dirname(file), { recursive: true })\n const fd = fs.openSync(file, flags, mode)\n fileOpened(null, fd)\n } catch (err) {\n fileOpened(err)\n throw err\n }\n } else if (sonic.mkdir) {\n fs.mkdir(path.dirname(file), { recursive: true }, (err) => {\n if (err) return fileOpened(err)\n fs.open(file, flags, mode, fileOpened)\n })\n } else {\n fs.open(file, flags, mode, fileOpened)\n }\n}\n\nfunction SonicBoom (opts) {\n if (!(this instanceof SonicBoom)) {\n return new SonicBoom(opts)\n }\n\n let { fd, dest, minLength, maxLength, maxWrite, periodicFlush, sync, append = true, mkdir, retryEAGAIN, fsync, contentMode, mode } = opts || {}\n\n fd = fd || dest\n\n this._len = 0\n this.fd = -1\n this._bufs = []\n this._lens = []\n this._writing = false\n this._ending = false\n this._reopening = false\n this._asyncDrainScheduled = false\n this._flushPending = false\n this._hwm = Math.max(minLength || 0, 16387)\n this.file = null\n this.destroyed = false\n this.minLength = minLength || 0\n this.maxLength = maxLength || 0\n this.maxWrite = maxWrite || MAX_WRITE\n this._periodicFlush = periodicFlush || 0\n this._periodicFlushTimer = undefined\n this.sync = sync || false\n this.writable = true\n this._fsync = fsync || false\n this.append = append || false\n this.mode = mode\n this.retryEAGAIN = retryEAGAIN || (() => true)\n this.mkdir = mkdir || false\n\n let fsWriteSync\n let fsWrite\n if (contentMode === kContentModeBuffer) {\n this._writingBuf = kEmptyBuffer\n this.write = writeBuffer\n this.flush = flushBuffer\n this.flushSync = flushBufferSync\n this._actualWrite = actualWriteBuffer\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf)\n fsWrite = () => fs.write(this.fd, this._writingBuf, this.release)\n } else if (contentMode === undefined || contentMode === kContentModeUtf8) {\n this._writingBuf = ''\n this.write = write\n this.flush = flush\n this.flushSync = flushSync\n this._actualWrite = actualWrite\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf, 'utf8')\n fsWrite = () => fs.write(this.fd, this._writingBuf, 'utf8', this.release)\n } else {\n throw new Error(`SonicBoom supports \"${kContentModeUtf8}\" and \"${kContentModeBuffer}\", but passed ${contentMode}`)\n }\n\n if (typeof fd === 'number') {\n this.fd = fd\n process.nextTick(() => this.emit('ready'))\n } else if (typeof fd === 'string') {\n openFile(fd, this)\n } else {\n throw new Error('SonicBoom supports only file descriptors and files')\n }\n if (this.minLength >= this.maxWrite) {\n throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`)\n }\n\n this.release = (err, n) => {\n if (err) {\n if ((err.code === 'EAGAIN' || err.code === 'EBUSY') && this.retryEAGAIN(err, this._writingBuf.length, this._len - this._writingBuf.length)) {\n if (this.sync) {\n // This error code should not happen in sync mode, because it is\n // not using the underlining operating system asynchronous functions.\n // However it happens, and so we handle it.\n // Ref: https://github.com/pinojs/pino/issues/783\n try {\n sleep(BUSY_WRITE_TIMEOUT)\n this.release(undefined, 0)\n } catch (err) {\n this.release(err)\n }\n } else {\n // Let's give the destination some time to process the chunk.\n setTimeout(fsWrite, BUSY_WRITE_TIMEOUT)\n }\n } else {\n this._writing = false\n\n this.emit('error', err)\n }\n return\n }\n\n this.emit('write', n)\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n\n if (this._writingBuf.length) {\n if (!this.sync) {\n fsWrite()\n return\n }\n\n try {\n do {\n const n = fsWriteSync()\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n } while (this._writingBuf.length)\n } catch (err) {\n this.release(err)\n return\n }\n }\n\n if (this._fsync) {\n fs.fsyncSync(this.fd)\n }\n\n const len = this._len\n if (this._reopening) {\n this._writing = false\n this._reopening = false\n this.reopen()\n } else if (len > this.minLength) {\n this._actualWrite()\n } else if (this._ending) {\n if (len > 0) {\n this._actualWrite()\n } else {\n this._writing = false\n actualClose(this)\n }\n } else {\n this._writing = false\n if (this.sync) {\n if (!this._asyncDrainScheduled) {\n this._asyncDrainScheduled = true\n process.nextTick(emitDrain, this)\n }\n } else {\n this.emit('drain')\n }\n }\n }\n\n this.on('newListener', function (name) {\n if (name === 'drain') {\n this._asyncDrainScheduled = false\n }\n })\n\n if (this._periodicFlush !== 0) {\n this._periodicFlushTimer = setInterval(() => this.flush(null), this._periodicFlush)\n this._periodicFlushTimer.unref()\n }\n}\n\n/**\n * Release the writingBuf after fs.write n bytes data\n * @param {string | Buffer} writingBuf - currently writing buffer, usually be instance._writingBuf.\n * @param {number} len - currently buffer length, usually be instance._len.\n * @param {number} n - number of bytes fs already written\n * @returns {{writingBuf: string | Buffer, len: number}} released writingBuf and length\n */\nfunction releaseWritingBuf (writingBuf, len, n) {\n // if Buffer.byteLength is equal to n, that means writingBuf contains no multi-byte character\n if (typeof writingBuf === 'string' && Buffer.byteLength(writingBuf) !== n) {\n // Since the fs.write callback parameter `n` means how many bytes the passed of string\n // We calculate the original string length for avoiding the multi-byte character issue\n n = Buffer.from(writingBuf).subarray(0, n).toString().length\n }\n len = Math.max(len - n, 0)\n writingBuf = writingBuf.slice(n)\n return { writingBuf, len }\n}\n\nfunction emitDrain (sonic) {\n const hasListeners = sonic.listenerCount('drain') > 0\n if (!hasListeners) return\n sonic._asyncDrainScheduled = false\n sonic.emit('drain')\n}\n\ninherits(SonicBoom, EventEmitter)\n\nfunction mergeBuf (bufs, len) {\n if (bufs.length === 0) {\n return kEmptyBuffer\n }\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return Buffer.concat(bufs, len)\n}\n\nfunction write (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n bufs[bufs.length - 1].length + data.length > this.maxWrite\n ) {\n bufs.push('' + data)\n } else {\n bufs[bufs.length - 1] += data\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction writeBuffer (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n const lens = this._lens\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n lens[lens.length - 1] + data.length > this.maxWrite\n ) {\n bufs.push([data])\n lens.push(data.length)\n } else {\n bufs[bufs.length - 1].push(data)\n lens[lens.length - 1] += data.length\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction callFlushCallbackOnDrain (cb) {\n this._flushPending = true\n const onDrain = () => {\n // only if _fsync is false to avoid double fsync\n if (!this._fsync) {\n try {\n fs.fsync(this.fd, (err) => {\n this._flushPending = false\n cb(err)\n })\n } catch (err) {\n cb(err)\n }\n } else {\n this._flushPending = false\n cb()\n }\n this.off('error', onError)\n }\n const onError = (err) => {\n this._flushPending = false\n cb(err)\n this.off('drain', onDrain)\n }\n\n this.once('drain', onDrain)\n this.once('error', onError)\n}\n\nfunction flush (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push('')\n }\n\n this._actualWrite()\n}\n\nfunction flushBuffer (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push([])\n this._lens.push(0)\n }\n\n this._actualWrite()\n}\n\nSonicBoom.prototype.reopen = function (file) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.reopen(file)\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n if (!this.file) {\n throw new Error('Unable to reopen a file descriptor, you must pass a file to SonicBoom')\n }\n\n if (file) {\n this.file = file\n }\n this._reopening = true\n\n if (this._writing) {\n return\n }\n\n const fd = this.fd\n this.once('ready', () => {\n if (fd !== this.fd) {\n fs.close(fd, (err) => {\n if (err) {\n return this.emit('error', err)\n }\n })\n }\n })\n\n openFile(this.file, this)\n}\n\nSonicBoom.prototype.end = function () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.end()\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n this._ending = true\n\n if (this._writing) {\n return\n }\n\n if (this._len > 0 && this.fd >= 0) {\n this._actualWrite()\n } else {\n actualClose(this)\n }\n}\n\nfunction flushSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift(this._writingBuf)\n this._writingBuf = ''\n }\n\n let buf = ''\n while (this._bufs.length || buf) {\n if (buf.length <= 0) {\n buf = this._bufs[0]\n }\n try {\n const n = fs.writeSync(this.fd, buf, 'utf8')\n const releasedBufObj = releaseWritingBuf(buf, this._len, n)\n buf = releasedBufObj.writingBuf\n this._len = releasedBufObj.len\n if (buf.length <= 0) {\n this._bufs.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n\n try {\n fs.fsyncSync(this.fd)\n } catch {\n // Skip the error. The fd might not support fsync.\n }\n}\n\nfunction flushBufferSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift([this._writingBuf])\n this._writingBuf = kEmptyBuffer\n }\n\n let buf = kEmptyBuffer\n while (this._bufs.length || buf.length) {\n if (buf.length <= 0) {\n buf = mergeBuf(this._bufs[0], this._lens[0])\n }\n try {\n const n = fs.writeSync(this.fd, buf)\n buf = buf.subarray(n)\n this._len = Math.max(this._len - n, 0)\n if (buf.length <= 0) {\n this._bufs.shift()\n this._lens.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n}\n\nSonicBoom.prototype.destroy = function () {\n if (this.destroyed) {\n return\n }\n actualClose(this)\n}\n\nfunction actualWrite () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf || this._bufs.shift() || ''\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf, 'utf8')\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n fs.write(this.fd, this._writingBuf, 'utf8', release)\n }\n}\n\nfunction actualWriteBuffer () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift())\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf)\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n // fs.write will need to copy string to buffer anyway so\n // we do it here to avoid the overhead of calculating the buffer size\n // in releaseWritingBuf.\n if (kCopyBuffer) {\n this._writingBuf = Buffer.from(this._writingBuf)\n }\n fs.write(this.fd, this._writingBuf, release)\n }\n}\n\nfunction actualClose (sonic) {\n if (sonic.fd === -1) {\n sonic.once('ready', actualClose.bind(null, sonic))\n return\n }\n\n if (sonic._periodicFlushTimer !== undefined) {\n clearInterval(sonic._periodicFlushTimer)\n }\n\n sonic.destroyed = true\n sonic._bufs = []\n sonic._lens = []\n\n assert(typeof sonic.fd === 'number', `sonic.fd must be a number, got ${typeof sonic.fd}`)\n try {\n fs.fsync(sonic.fd, closeWrapped)\n } catch {\n }\n\n function closeWrapped () {\n // We skip errors in fsync\n\n if (sonic.fd !== 1 && sonic.fd !== 2) {\n fs.close(sonic.fd, done)\n } else {\n done()\n }\n }\n\n function done (err) {\n if (err) {\n sonic.emit('error', err)\n return\n }\n\n if (sonic._ending && !sonic._writing) {\n sonic.emit('finish')\n }\n sonic.emit('close')\n }\n}\n\n/**\n * These export configurations enable JS and TS developers\n * to consumer SonicBoom in whatever way best suits their needs.\n * Some examples of supported import syntax includes:\n * - `const SonicBoom = require('SonicBoom')`\n * - `const { SonicBoom } = require('SonicBoom')`\n * - `import * as SonicBoom from 'SonicBoom'`\n * - `import { SonicBoom } from 'SonicBoom'`\n * - `import SonicBoom from 'SonicBoom'`\n */\nSonicBoom.SonicBoom = SonicBoom\nSonicBoom.default = SonicBoom\nmodule.exports = SonicBoom\n", "\"use strict\";\nexports.secondsInYear =\n exports.secondsInWeek =\n exports.secondsInQuarter =\n exports.secondsInMonth =\n exports.secondsInMinute =\n exports.secondsInHour =\n exports.secondsInDay =\n exports.quartersInYear =\n exports.monthsInYear =\n exports.monthsInQuarter =\n exports.minutesInYear =\n exports.minutesInMonth =\n exports.minutesInHour =\n exports.minutesInDay =\n exports.minTime =\n exports.millisecondsInWeek =\n exports.millisecondsInSecond =\n exports.millisecondsInMinute =\n exports.millisecondsInHour =\n exports.millisecondsInDay =\n exports.maxTime =\n exports.daysInYear =\n exports.daysInWeek =\n exports.constructFromSymbol =\n void 0; /**\n * @module constants\n * @summary Useful constants\n * @description\n * Collection of useful date constants.\n *\n * The constants could be imported from `date-fns/constants`:\n *\n * ```ts\n * import { maxTime, minTime } from \"date-fns/constants\";\n *\n * function isAllowedTime(time) {\n * return time <= maxTime && time >= minTime;\n * }\n * ```\n */\n\n/**\n * @constant\n * @name daysInWeek\n * @summary Days in 1 week.\n */\nconst daysInWeek = (exports.daysInWeek = 7);\n\n/**\n * @constant\n * @name daysInYear\n * @summary Days in 1 year.\n *\n * @description\n * How many days in a year.\n *\n * One years equals 365.2425 days according to the formula:\n *\n * > Leap year occurs every 4 years, except for years that are divisible by 100 and not divisible by 400.\n * > 1 mean year = (365+1/4-1/100+1/400) days = 365.2425 days\n */\nconst daysInYear = (exports.daysInYear = 365.2425);\n\n/**\n * @constant\n * @name maxTime\n * @summary Maximum allowed time.\n *\n * @example\n * import { maxTime } from \"date-fns/constants\";\n *\n * const isValid = 8640000000000001 <= maxTime;\n * //=> false\n *\n * new Date(8640000000000001);\n * //=> Invalid Date\n */\nconst maxTime = (exports.maxTime = Math.pow(10, 8) * 24 * 60 * 60 * 1000);\n\n/**\n * @constant\n * @name minTime\n * @summary Minimum allowed time.\n *\n * @example\n * import { minTime } from \"date-fns/constants\";\n *\n * const isValid = -8640000000000001 >= minTime;\n * //=> false\n *\n * new Date(-8640000000000001)\n * //=> Invalid Date\n */\nconst minTime = (exports.minTime = -maxTime);\n\n/**\n * @constant\n * @name millisecondsInWeek\n * @summary Milliseconds in 1 week.\n */\nconst millisecondsInWeek = (exports.millisecondsInWeek = 604800000);\n\n/**\n * @constant\n * @name millisecondsInDay\n * @summary Milliseconds in 1 day.\n */\nconst millisecondsInDay = (exports.millisecondsInDay = 86400000);\n\n/**\n * @constant\n * @name millisecondsInMinute\n * @summary Milliseconds in 1 minute\n */\nconst millisecondsInMinute = (exports.millisecondsInMinute = 60000);\n\n/**\n * @constant\n * @name millisecondsInHour\n * @summary Milliseconds in 1 hour\n */\nconst millisecondsInHour = (exports.millisecondsInHour = 3600000);\n\n/**\n * @constant\n * @name millisecondsInSecond\n * @summary Milliseconds in 1 second\n */\nconst millisecondsInSecond = (exports.millisecondsInSecond = 1000);\n\n/**\n * @constant\n * @name minutesInYear\n * @summary Minutes in 1 year.\n */\nconst minutesInYear = (exports.minutesInYear = 525600);\n\n/**\n * @constant\n * @name minutesInMonth\n * @summary Minutes in 1 month.\n */\nconst minutesInMonth = (exports.minutesInMonth = 43200);\n\n/**\n * @constant\n * @name minutesInDay\n * @summary Minutes in 1 day.\n */\nconst minutesInDay = (exports.minutesInDay = 1440);\n\n/**\n * @constant\n * @name minutesInHour\n * @summary Minutes in 1 hour.\n */\nconst minutesInHour = (exports.minutesInHour = 60);\n\n/**\n * @constant\n * @name monthsInQuarter\n * @summary Months in 1 quarter.\n */\nconst monthsInQuarter = (exports.monthsInQuarter = 3);\n\n/**\n * @constant\n * @name monthsInYear\n * @summary Months in 1 year.\n */\nconst monthsInYear = (exports.monthsInYear = 12);\n\n/**\n * @constant\n * @name quartersInYear\n * @summary Quarters in 1 year\n */\nconst quartersInYear = (exports.quartersInYear = 4);\n\n/**\n * @constant\n * @name secondsInHour\n * @summary Seconds in 1 hour.\n */\nconst secondsInHour = (exports.secondsInHour = 3600);\n\n/**\n * @constant\n * @name secondsInMinute\n * @summary Seconds in 1 minute.\n */\nconst secondsInMinute = (exports.secondsInMinute = 60);\n\n/**\n * @constant\n * @name secondsInDay\n * @summary Seconds in 1 day.\n */\nconst secondsInDay = (exports.secondsInDay = secondsInHour * 24);\n\n/**\n * @constant\n * @name secondsInWeek\n * @summary Seconds in 1 week.\n */\nconst secondsInWeek = (exports.secondsInWeek = secondsInDay * 7);\n\n/**\n * @constant\n * @name secondsInYear\n * @summary Seconds in 1 year.\n */\nconst secondsInYear = (exports.secondsInYear = secondsInDay * daysInYear);\n\n/**\n * @constant\n * @name secondsInMonth\n * @summary Seconds in 1 month\n */\nconst secondsInMonth = (exports.secondsInMonth = secondsInYear / 12);\n\n/**\n * @constant\n * @name secondsInQuarter\n * @summary Seconds in 1 quarter.\n */\nconst secondsInQuarter = (exports.secondsInQuarter = secondsInMonth * 3);\n\n/**\n * @constant\n * @name constructFromSymbol\n * @summary Symbol enabling Date extensions to inherit properties from the reference date.\n *\n * The symbol is used to enable the `constructFrom` function to construct a date\n * using a reference date and a value. It allows to transfer extra properties\n * from the reference date to the new date. It's useful for extensions like\n * [`TZDate`](https://github.com/date-fns/tz) that accept a time zone as\n * a constructor argument.\n */\nconst constructFromSymbol = (exports.constructFromSymbol =\n Symbol.for(\"constructDateFrom\"));\n", "\"use strict\";\nexports.constructFrom = constructFrom;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name constructFrom\n * @category Generic Helpers\n * @summary Constructs a date using the reference date and the value\n *\n * @description\n * The function constructs a new date using the constructor from the reference\n * date and the given value. It helps to build generic functions that accept\n * date extensions.\n *\n * It defaults to `Date` if the passed reference date is a number or a string.\n *\n * Starting from v3.7.0, it allows to construct a date using `[Symbol.for(\"constructDateFrom\")]`\n * enabling to transfer extra properties from the reference date to the new date.\n * It's useful for extensions like [`TZDate`](https://github.com/date-fns/tz)\n * that accept a time zone as a constructor argument.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n *\n * @param date - The reference date to take constructor from\n * @param value - The value to create the date\n *\n * @returns Date initialized using the given date and value\n *\n * @example\n * import { constructFrom } from \"date-fns\";\n *\n * // A function that clones a date preserving the original type\n * function cloneDate(date: DateType): DateType {\n * return constructFrom(\n * date, // Use constructor from the given date\n * date.getTime() // Use the date value to create a new date\n * );\n * }\n */\nfunction constructFrom(date, value) {\n if (typeof date === \"function\") return date(value);\n\n if (date && typeof date === \"object\" && _index.constructFromSymbol in date)\n return date[_index.constructFromSymbol](value);\n\n if (date instanceof Date) return new date.constructor(value);\n\n return new Date(value);\n}\n", "\"use strict\";\nexports.toDate = toDate;\nvar _index = require(\"./constructFrom.cjs\");\n\n/**\n * @name toDate\n * @category Common Helpers\n * @summary Convert the given argument to an instance of Date.\n *\n * @description\n * Convert the given argument to an instance of Date.\n *\n * If the argument is an instance of Date, the function returns its clone.\n *\n * If the argument is a number, it is treated as a timestamp.\n *\n * If the argument is none of the above, the function returns Invalid Date.\n *\n * Starting from v3.7.0, it clones a date using `[Symbol.for(\"constructDateFrom\")]`\n * enabling to transfer extra properties from the reference date to the new date.\n * It's useful for extensions like [`TZDate`](https://github.com/date-fns/tz)\n * that accept a time zone as a constructor argument.\n *\n * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param argument - The value to convert\n *\n * @returns The parsed date in the local time zone\n *\n * @example\n * // Clone the date:\n * const result = toDate(new Date(2014, 1, 11, 11, 30, 30))\n * //=> Tue Feb 11 2014 11:30:30\n *\n * @example\n * // Convert the timestamp to date:\n * const result = toDate(1392098430000)\n * //=> Tue Feb 11 2014 11:30:30\n */\nfunction toDate(argument, context) {\n // [TODO] Get rid of `toDate` or `constructFrom`?\n return (0, _index.constructFrom)(context || argument, argument);\n}\n", "\"use strict\";\nexports.addDays = addDays;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link addDays} function options.\n */\n\n/**\n * @name addDays\n * @category Day Helpers\n * @summary Add the specified number of days to the given date.\n *\n * @description\n * Add the specified number of days to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of days to be added.\n * @param options - An object with options\n *\n * @returns The new date with the days added\n *\n * @example\n * // Add 10 days to 1 September 2014:\n * const result = addDays(new Date(2014, 8, 1), 10)\n * //=> Thu Sep 11 2014 00:00:00\n */\nfunction addDays(date, amount, options) {\n const _date = (0, _index2.toDate)(date, options?.in);\n if (isNaN(amount)) return (0, _index.constructFrom)(options?.in || date, NaN);\n\n // If 0 days, no-op to avoid changing times in the hour before end of DST\n if (!amount) return _date;\n\n _date.setDate(_date.getDate() + amount);\n return _date;\n}\n", "\"use strict\";\nexports.addMonths = addMonths;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link addMonths} function options.\n */\n\n/**\n * @name addMonths\n * @category Month Helpers\n * @summary Add the specified number of months to the given date.\n *\n * @description\n * Add the specified number of months to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of months to be added.\n * @param options - The options object\n *\n * @returns The new date with the months added\n *\n * @example\n * // Add 5 months to 1 September 2014:\n * const result = addMonths(new Date(2014, 8, 1), 5)\n * //=> Sun Feb 01 2015 00:00:00\n *\n * // Add one month to 30 January 2023:\n * const result = addMonths(new Date(2023, 0, 30), 1)\n * //=> Tue Feb 28 2023 00:00:00\n */\nfunction addMonths(date, amount, options) {\n const _date = (0, _index2.toDate)(date, options?.in);\n if (isNaN(amount)) return (0, _index.constructFrom)(options?.in || date, NaN);\n if (!amount) {\n // If 0 months, no-op to avoid changing times in the hour before end of DST\n return _date;\n }\n const dayOfMonth = _date.getDate();\n\n // The JS Date object supports date math by accepting out-of-bounds values for\n // month, day, etc. For example, new Date(2020, 0, 0) returns 31 Dec 2019 and\n // new Date(2020, 13, 1) returns 1 Feb 2021. This is *almost* the behavior we\n // want except that dates will wrap around the end of a month, meaning that\n // new Date(2020, 13, 31) will return 3 Mar 2021 not 28 Feb 2021 as desired. So\n // we'll default to the end of the desired month by adding 1 to the desired\n // month and using a date of 0 to back up one day to the end of the desired\n // month.\n const endOfDesiredMonth = (0, _index.constructFrom)(\n options?.in || date,\n _date.getTime(),\n );\n endOfDesiredMonth.setMonth(_date.getMonth() + amount + 1, 0);\n const daysInMonth = endOfDesiredMonth.getDate();\n if (dayOfMonth >= daysInMonth) {\n // If we're already at the end of the month, then this is the correct date\n // and we're done.\n return endOfDesiredMonth;\n } else {\n // Otherwise, we now know that setting the original day-of-month value won't\n // cause an overflow, so set the desired day-of-month. Note that we can't\n // just set the date of `endOfDesiredMonth` because that object may have had\n // its time changed in the unusual case where where a DST transition was on\n // the last day of the month and its local time was in the hour skipped or\n // repeated next to a DST transition. So we use `date` instead which is\n // guaranteed to still have the original time.\n _date.setFullYear(\n endOfDesiredMonth.getFullYear(),\n endOfDesiredMonth.getMonth(),\n dayOfMonth,\n );\n return _date;\n }\n}\n", "\"use strict\";\nexports.add = add;\nvar _index = require(\"./addDays.cjs\");\nvar _index2 = require(\"./addMonths.cjs\");\nvar _index3 = require(\"./constructFrom.cjs\");\nvar _index4 = require(\"./toDate.cjs\");\n\n/**\n * The {@link add} function options.\n */\n\n/**\n * @name add\n * @category Common Helpers\n * @summary Add the specified years, months, weeks, days, hours, minutes, and seconds to the given date.\n *\n * @description\n * Add the specified years, months, weeks, days, hours, minutes, and seconds to the given date.\n *\n * @typeParam DateType - The `Date` type the function operates on. Gets inferred from passed arguments. Allows using extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param duration - The object with years, months, weeks, days, hours, minutes, and seconds to be added.\n * @param options - An object with options\n *\n * @returns The new date with the seconds added\n *\n * @example\n * // Add the following duration to 1 September 2014, 10:19:50\n * const result = add(new Date(2014, 8, 1, 10, 19, 50), {\n * years: 2,\n * months: 9,\n * weeks: 1,\n * days: 7,\n * hours: 5,\n * minutes: 9,\n * seconds: 30,\n * })\n * //=> Thu Jun 15 2017 15:29:20\n */\nfunction add(date, duration, options) {\n const {\n years = 0,\n months = 0,\n weeks = 0,\n days = 0,\n hours = 0,\n minutes = 0,\n seconds = 0,\n } = duration;\n\n // Add years and months\n const _date = (0, _index4.toDate)(date, options?.in);\n const dateWithMonths =\n months || years\n ? (0, _index2.addMonths)(_date, months + years * 12)\n : _date;\n\n // Add weeks and days\n const dateWithDays =\n days || weeks\n ? (0, _index.addDays)(dateWithMonths, days + weeks * 7)\n : dateWithMonths;\n\n // Add days, hours, minutes, and seconds\n const minutesToAdd = minutes + hours * 60;\n const secondsToAdd = seconds + minutesToAdd * 60;\n const msToAdd = secondsToAdd * 1000;\n\n return (0, _index3.constructFrom)(\n options?.in || date,\n +dateWithDays + msToAdd,\n );\n}\n", "\"use strict\";\nexports.isSaturday = isSaturday;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isSaturday} function options.\n */\n\n/**\n * @name isSaturday\n * @category Weekday Helpers\n * @summary Is the given date Saturday?\n *\n * @description\n * Is the given date Saturday?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is Saturday\n *\n * @example\n * // Is 27 September 2014 Saturday?\n * const result = isSaturday(new Date(2014, 8, 27))\n * //=> true\n */\nfunction isSaturday(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay() === 6;\n}\n", "\"use strict\";\nexports.isSunday = isSunday;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isSunday} function options.\n */\n\n/**\n * @name isSunday\n * @category Weekday Helpers\n * @summary Is the given date Sunday?\n *\n * @description\n * Is the given date Sunday?\n *\n * @param date - The date to check\n * @param options - The options object\n *\n * @returns The date is Sunday\n *\n * @example\n * // Is 21 September 2014 Sunday?\n * const result = isSunday(new Date(2014, 8, 21))\n * //=> true\n */\nfunction isSunday(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay() === 0;\n}\n", "\"use strict\";\nexports.isWeekend = isWeekend;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isWeekend} function options.\n */\n\n/**\n * @name isWeekend\n * @category Weekday Helpers\n * @summary Does the given date fall on a weekend?\n *\n * @description\n * Does the given date fall on a weekend? A weekend is either Saturday (`6`) or Sunday (`0`).\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date falls on a weekend\n *\n * @example\n * // Does 5 October 2014 fall on a weekend?\n * const result = isWeekend(new Date(2014, 9, 5))\n * //=> true\n */\nfunction isWeekend(date, options) {\n const day = (0, _index.toDate)(date, options?.in).getDay();\n return day === 0 || day === 6;\n}\n", "\"use strict\";\nexports.addBusinessDays = addBusinessDays;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./isSaturday.cjs\");\nvar _index3 = require(\"./isSunday.cjs\");\nvar _index4 = require(\"./isWeekend.cjs\");\nvar _index5 = require(\"./toDate.cjs\");\n\n/**\n * The {@link addBusinessDays} function options.\n */\n\n/**\n * @name addBusinessDays\n * @category Day Helpers\n * @summary Add the specified number of business days (mon - fri) to the given date.\n *\n * @description\n * Add the specified number of business days (mon - fri) to the given date, ignoring weekends.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of business days to be added.\n * @param options - An object with options\n *\n * @returns The new date with the business days added\n *\n * @example\n * // Add 10 business days to 1 September 2014:\n * const result = addBusinessDays(new Date(2014, 8, 1), 10)\n * //=> Mon Sep 15 2014 00:00:00 (skipped weekend days)\n */\nfunction addBusinessDays(date, amount, options) {\n const _date = (0, _index5.toDate)(date, options?.in);\n const startedOnWeekend = (0, _index4.isWeekend)(_date, options);\n\n if (isNaN(amount)) return (0, _index.constructFrom)(options?.in, NaN);\n\n const hours = _date.getHours();\n const sign = amount < 0 ? -1 : 1;\n const fullWeeks = Math.trunc(amount / 5);\n\n _date.setDate(_date.getDate() + fullWeeks * 7);\n\n // Get remaining days not part of a full week\n let restDays = Math.abs(amount % 5);\n\n // Loops over remaining days\n while (restDays > 0) {\n _date.setDate(_date.getDate() + sign);\n if (!(0, _index4.isWeekend)(_date, options)) restDays -= 1;\n }\n\n // If the date is a weekend day and we reduce a dividable of\n // 5 from it, we land on a weekend date.\n // To counter this, we add days accordingly to land on the next business day\n if (\n startedOnWeekend &&\n (0, _index4.isWeekend)(_date, options) &&\n amount !== 0\n ) {\n // If we're reducing days, we want to add days until we land on a weekday\n // If we're adding days we want to reduce days until we land on a weekday\n if ((0, _index2.isSaturday)(_date, options))\n _date.setDate(_date.getDate() + (sign < 0 ? 2 : -1));\n if ((0, _index3.isSunday)(_date, options))\n _date.setDate(_date.getDate() + (sign < 0 ? 1 : -2));\n }\n\n // Restore hours to avoid DST lag\n _date.setHours(hours);\n\n return _date;\n}\n", "\"use strict\";\nexports.addMilliseconds = addMilliseconds;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link addMilliseconds} function options.\n */\n\n/**\n * @name addMilliseconds\n * @category Millisecond Helpers\n * @summary Add the specified number of milliseconds to the given date.\n *\n * @description\n * Add the specified number of milliseconds to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of milliseconds to be added.\n * @param options - The options object\n *\n * @returns The new date with the milliseconds added\n *\n * @example\n * // Add 750 milliseconds to 10 July 2014 12:45:30.000:\n * const result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)\n * //=> Thu Jul 10 2014 12:45:30.750\n */\nfunction addMilliseconds(date, amount, options) {\n return (0, _index.constructFrom)(\n options?.in || date,\n +(0, _index2.toDate)(date) + amount,\n );\n}\n", "\"use strict\";\nexports.addHours = addHours;\nvar _index = require(\"./addMilliseconds.cjs\");\nvar _index2 = require(\"./constants.cjs\");\n\n/**\n * The {@link addHours} function options.\n */\n\n/**\n * @name addHours\n * @category Hour Helpers\n * @summary Add the specified number of hours to the given date.\n *\n * @description\n * Add the specified number of hours to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of hours to be added\n * @param options - An object with options\n *\n * @returns The new date with the hours added\n *\n * @example\n * // Add 2 hours to 10 July 2014 23:00:00:\n * const result = addHours(new Date(2014, 6, 10, 23, 0), 2)\n * //=> Fri Jul 11 2014 01:00:00\n */\nfunction addHours(date, amount, options) {\n return (0, _index.addMilliseconds)(\n date,\n amount * _index2.millisecondsInHour,\n options,\n );\n}\n", "\"use strict\";\nexports.getDefaultOptions = getDefaultOptions;\nexports.setDefaultOptions = setDefaultOptions;\n\nlet defaultOptions = {};\n\nfunction getDefaultOptions() {\n return defaultOptions;\n}\n\nfunction setDefaultOptions(newOptions) {\n defaultOptions = newOptions;\n}\n", "\"use strict\";\nexports.startOfWeek = startOfWeek;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfWeek} function options.\n */\n\n/**\n * @name startOfWeek\n * @category Week Helpers\n * @summary Return the start of a week for the given date.\n *\n * @description\n * Return the start of a week for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of a week\n *\n * @example\n * // The start of a week for 2 September 2014 11:55:00:\n * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Sun Aug 31 2014 00:00:00\n *\n * @example\n * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00:\n * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })\n * //=> Mon Sep 01 2014 00:00:00\n */\nfunction startOfWeek(date, options) {\n const defaultOptions = (0, _index.getDefaultOptions)();\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const _date = (0, _index2.toDate)(date, options?.in);\n const day = _date.getDay();\n const diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;\n\n _date.setDate(_date.getDate() - diff);\n _date.setHours(0, 0, 0, 0);\n return _date;\n}\n", "\"use strict\";\nexports.startOfISOWeek = startOfISOWeek;\nvar _index = require(\"./startOfWeek.cjs\");\n\n/**\n * The {@link startOfISOWeek} function options.\n */\n\n/**\n * @name startOfISOWeek\n * @category ISO Week Helpers\n * @summary Return the start of an ISO week for the given date.\n *\n * @description\n * Return the start of an ISO week for the given date.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of an ISO week\n *\n * @example\n * // The start of an ISO week for 2 September 2014 11:55:00:\n * const result = startOfISOWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Mon Sep 01 2014 00:00:00\n */\nfunction startOfISOWeek(date, options) {\n return (0, _index.startOfWeek)(date, { ...options, weekStartsOn: 1 });\n}\n", "\"use strict\";\nexports.getISOWeekYear = getISOWeekYear;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./startOfISOWeek.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getISOWeekYear} function options.\n */\n\n/**\n * @name getISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Get the ISO week-numbering year of the given date.\n *\n * @description\n * Get the ISO week-numbering year of the given date,\n * which always starts 3 days before the year's first Thursday.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param date - The given date\n *\n * @returns The ISO week-numbering year\n *\n * @example\n * // Which ISO-week numbering year is 2 January 2005?\n * const result = getISOWeekYear(new Date(2005, 0, 2))\n * //=> 2004\n */\nfunction getISOWeekYear(date, options) {\n const _date = (0, _index3.toDate)(date, options?.in);\n const year = _date.getFullYear();\n\n const fourthOfJanuaryOfNextYear = (0, _index.constructFrom)(_date, 0);\n fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);\n fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);\n const startOfNextYear = (0, _index2.startOfISOWeek)(\n fourthOfJanuaryOfNextYear,\n );\n\n const fourthOfJanuaryOfThisYear = (0, _index.constructFrom)(_date, 0);\n fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4);\n fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0);\n const startOfThisYear = (0, _index2.startOfISOWeek)(\n fourthOfJanuaryOfThisYear,\n );\n\n if (_date.getTime() >= startOfNextYear.getTime()) {\n return year + 1;\n } else if (_date.getTime() >= startOfThisYear.getTime()) {\n return year;\n } else {\n return year - 1;\n }\n}\n", "\"use strict\";\nexports.getTimezoneOffsetInMilliseconds = getTimezoneOffsetInMilliseconds;\nvar _index = require(\"../toDate.cjs\");\n\n/**\n * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds.\n * They usually appear for dates that denote time before the timezones were introduced\n * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891\n * and GMT+01:00:00 after that date)\n *\n * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above,\n * which would lead to incorrect calculations.\n *\n * This function returns the timezone offset in milliseconds that takes seconds in account.\n */\nfunction getTimezoneOffsetInMilliseconds(date) {\n const _date = (0, _index.toDate)(date);\n const utcDate = new Date(\n Date.UTC(\n _date.getFullYear(),\n _date.getMonth(),\n _date.getDate(),\n _date.getHours(),\n _date.getMinutes(),\n _date.getSeconds(),\n _date.getMilliseconds(),\n ),\n );\n utcDate.setUTCFullYear(_date.getFullYear());\n return +date - +utcDate;\n}\n", "\"use strict\";\nexports.normalizeDates = normalizeDates;\nvar _index = require(\"../constructFrom.cjs\");\n\nfunction normalizeDates(context, ...dates) {\n const normalize = _index.constructFrom.bind(\n null,\n context || dates.find((date) => typeof date === \"object\"),\n );\n return dates.map(normalize);\n}\n", "\"use strict\";\nexports.startOfDay = startOfDay;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfDay} function options.\n */\n\n/**\n * @name startOfDay\n * @category Day Helpers\n * @summary Return the start of a day for the given date.\n *\n * @description\n * Return the start of a day for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The start of a day\n *\n * @example\n * // The start of a day for 2 September 2014 11:55:00:\n * const result = startOfDay(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 02 2014 00:00:00\n */\nfunction startOfDay(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setHours(0, 0, 0, 0);\n return _date;\n}\n", "\"use strict\";\nexports.differenceInCalendarDays = differenceInCalendarDays;\nvar _index = require(\"./_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _index2 = require(\"./_lib/normalizeDates.cjs\");\nvar _index3 = require(\"./constants.cjs\");\nvar _index4 = require(\"./startOfDay.cjs\");\n\n/**\n * The {@link differenceInCalendarDays} function options.\n */\n\n/**\n * @name differenceInCalendarDays\n * @category Day Helpers\n * @summary Get the number of calendar days between the given dates.\n *\n * @description\n * Get the number of calendar days between the given dates. This means that the times are removed\n * from the dates and then the difference in days is calculated.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - The options object\n *\n * @returns The number of calendar days\n *\n * @example\n * // How many calendar days are between\n * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?\n * const result = differenceInCalendarDays(\n * new Date(2012, 6, 2, 0, 0),\n * new Date(2011, 6, 2, 23, 0)\n * )\n * //=> 366\n * // How many calendar days are between\n * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?\n * const result = differenceInCalendarDays(\n * new Date(2011, 6, 3, 0, 1),\n * new Date(2011, 6, 2, 23, 59)\n * )\n * //=> 1\n */\nfunction differenceInCalendarDays(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index2.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const laterStartOfDay = (0, _index4.startOfDay)(laterDate_);\n const earlierStartOfDay = (0, _index4.startOfDay)(earlierDate_);\n\n const laterTimestamp =\n +laterStartOfDay -\n (0, _index.getTimezoneOffsetInMilliseconds)(laterStartOfDay);\n const earlierTimestamp =\n +earlierStartOfDay -\n (0, _index.getTimezoneOffsetInMilliseconds)(earlierStartOfDay);\n\n // Round the number of days to the nearest integer because the number of\n // milliseconds in a day is not constant (e.g. it's different in the week of\n // the daylight saving time clock shift).\n return Math.round(\n (laterTimestamp - earlierTimestamp) / _index3.millisecondsInDay,\n );\n}\n", "\"use strict\";\nexports.startOfISOWeekYear = startOfISOWeekYear;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./getISOWeekYear.cjs\");\nvar _index3 = require(\"./startOfISOWeek.cjs\");\n\n/**\n * The {@link startOfISOWeekYear} function options.\n */\n\n/**\n * @name startOfISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Return the start of an ISO week-numbering year for the given date.\n *\n * @description\n * Return the start of an ISO week-numbering year,\n * which always starts 3 days before the year's first Thursday.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of an ISO week-numbering year\n *\n * @example\n * // The start of an ISO week-numbering year for 2 July 2005:\n * const result = startOfISOWeekYear(new Date(2005, 6, 2))\n * //=> Mon Jan 03 2005 00:00:00\n */\nfunction startOfISOWeekYear(date, options) {\n const year = (0, _index2.getISOWeekYear)(date, options);\n const fourthOfJanuary = (0, _index.constructFrom)(options?.in || date, 0);\n fourthOfJanuary.setFullYear(year, 0, 4);\n fourthOfJanuary.setHours(0, 0, 0, 0);\n return (0, _index3.startOfISOWeek)(fourthOfJanuary);\n}\n", "\"use strict\";\nexports.setISOWeekYear = setISOWeekYear;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./differenceInCalendarDays.cjs\");\nvar _index3 = require(\"./startOfISOWeekYear.cjs\");\nvar _index4 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setISOWeekYear} function options.\n */\n\n/**\n * @name setISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Set the ISO week-numbering year to the given date.\n *\n * @description\n * Set the ISO week-numbering year to the given date,\n * saving the week number and the weekday number.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows using extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param weekYear - The ISO week-numbering year of the new date\n * @param options - An object with options\n *\n * @returns The new date with the ISO week-numbering year set\n *\n * @example\n * // Set ISO week-numbering year 2007 to 29 December 2008:\n * const result = setISOWeekYear(new Date(2008, 11, 29), 2007)\n * //=> Mon Jan 01 2007 00:00:00\n */\nfunction setISOWeekYear(date, weekYear, options) {\n let _date = (0, _index4.toDate)(date, options?.in);\n const diff = (0, _index2.differenceInCalendarDays)(\n _date,\n (0, _index3.startOfISOWeekYear)(_date, options),\n );\n const fourthOfJanuary = (0, _index.constructFrom)(options?.in || date, 0);\n fourthOfJanuary.setFullYear(weekYear, 0, 4);\n fourthOfJanuary.setHours(0, 0, 0, 0);\n _date = (0, _index3.startOfISOWeekYear)(fourthOfJanuary);\n _date.setDate(_date.getDate() + diff);\n return _date;\n}\n", "\"use strict\";\nexports.addISOWeekYears = addISOWeekYears;\nvar _index = require(\"./getISOWeekYear.cjs\");\nvar _index2 = require(\"./setISOWeekYear.cjs\");\n\n/**\n * The {@link addISOWeekYears} function options.\n */\n\n/**\n * @name addISOWeekYears\n * @category ISO Week-Numbering Year Helpers\n * @summary Add the specified number of ISO week-numbering years to the given date.\n *\n * @description\n * Add the specified number of ISO week-numbering years to the given date.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n *\n * @param date - The date to be changed\n * @param amount - The amount of ISO week-numbering years to be added.\n * @param options - An object with options\n *\n * @returns The new date with the ISO week-numbering years added\n *\n * @example\n * // Add 5 ISO week-numbering years to 2 July 2010:\n * const result = addISOWeekYears(new Date(2010, 6, 2), 5)\n * //=> Fri Jun 26 2015 00:00:00\n */\nfunction addISOWeekYears(date, amount, options) {\n return (0, _index2.setISOWeekYear)(\n date,\n (0, _index.getISOWeekYear)(date, options) + amount,\n options,\n );\n}\n", "\"use strict\";\nexports.addMinutes = addMinutes;\nvar _index = require(\"./constants.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link addMinutes} function options.\n */\n\n/**\n * @name addMinutes\n * @category Minute Helpers\n * @summary Add the specified number of minutes to the given date.\n *\n * @description\n * Add the specified number of minutes to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of minutes to be added.\n * @param options - An object with options\n *\n * @returns The new date with the minutes added\n *\n * @example\n * // Add 30 minutes to 10 July 2014 12:00:00:\n * const result = addMinutes(new Date(2014, 6, 10, 12, 0), 30)\n * //=> Thu Jul 10 2014 12:30:00\n */\nfunction addMinutes(date, amount, options) {\n const _date = (0, _index2.toDate)(date, options?.in);\n _date.setTime(_date.getTime() + amount * _index.millisecondsInMinute);\n return _date;\n}\n", "\"use strict\";\nexports.addQuarters = addQuarters;\nvar _index = require(\"./addMonths.cjs\");\n\n/**\n * The {@link addQuarters} function options.\n */\n\n/**\n * @name addQuarters\n * @category Quarter Helpers\n * @summary Add the specified number of year quarters to the given date.\n *\n * @description\n * Add the specified number of year quarters to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of quarters to be added.\n * @param options - An object with options\n *\n * @returns The new date with the quarters added\n *\n * @example\n * // Add 1 quarter to 1 September 2014:\n * const result = addQuarters(new Date(2014, 8, 1), 1)\n * //=; Mon Dec 01 2014 00:00:00\n */\nfunction addQuarters(date, amount, options) {\n return (0, _index.addMonths)(date, amount * 3, options);\n}\n", "\"use strict\";\nexports.addSeconds = addSeconds;\nvar _index = require(\"./addMilliseconds.cjs\");\n\n/**\n * The {@link addSeconds} function options.\n */\n\n/**\n * @name addSeconds\n * @category Second Helpers\n * @summary Add the specified number of seconds to the given date.\n *\n * @description\n * Add the specified number of seconds to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of seconds to be added.\n * @param options - An object with options\n *\n * @returns The new date with the seconds added\n *\n * @example\n * // Add 30 seconds to 10 July 2014 12:45:00:\n * const result = addSeconds(new Date(2014, 6, 10, 12, 45, 0), 30)\n * //=> Thu Jul 10 2014 12:45:30\n */\nfunction addSeconds(date, amount, options) {\n return (0, _index.addMilliseconds)(date, amount * 1000, options);\n}\n", "\"use strict\";\nexports.addWeeks = addWeeks;\nvar _index = require(\"./addDays.cjs\");\n\n/**\n * The {@link addWeeks} function options.\n */\n\n/**\n * @name addWeeks\n * @category Week Helpers\n * @summary Add the specified number of weeks to the given date.\n *\n * @description\n * Add the specified number of weeks to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of weeks to be added.\n * @param options - An object with options\n *\n * @returns The new date with the weeks added\n *\n * @example\n * // Add 4 weeks to 1 September 2014:\n * const result = addWeeks(new Date(2014, 8, 1), 4)\n * //=> Mon Sep 29 2014 00:00:00\n */\nfunction addWeeks(date, amount, options) {\n return (0, _index.addDays)(date, amount * 7, options);\n}\n", "\"use strict\";\nexports.addYears = addYears;\nvar _index = require(\"./addMonths.cjs\");\n\n/**\n * The {@link addYears} function options.\n */\n\n/**\n * @name addYears\n * @category Year Helpers\n * @summary Add the specified number of years to the given date.\n *\n * @description\n * Add the specified number of years to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type.\n *\n * @param date - The date to be changed\n * @param amount - The amount of years to be added.\n * @param options - The options\n *\n * @returns The new date with the years added\n *\n * @example\n * // Add 5 years to 1 September 2014:\n * const result = addYears(new Date(2014, 8, 1), 5)\n * //=> Sun Sep 01 2019 00:00:00\n */\nfunction addYears(date, amount, options) {\n return (0, _index.addMonths)(date, amount * 12, options);\n}\n", "\"use strict\";\nexports.areIntervalsOverlapping = areIntervalsOverlapping;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link areIntervalsOverlapping} function options.\n */\n\n/**\n * @name areIntervalsOverlapping\n * @category Interval Helpers\n * @summary Is the given time interval overlapping with another time interval?\n *\n * @description\n * Is the given time interval overlapping with another time interval? Adjacent intervals do not count as overlapping unless `inclusive` is set to `true`.\n *\n * @param intervalLeft - The first interval to compare.\n * @param intervalRight - The second interval to compare.\n * @param options - The object with options\n *\n * @returns Whether the time intervals are overlapping\n *\n * @example\n * // For overlapping time intervals:\n * areIntervalsOverlapping(\n * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },\n * { start: new Date(2014, 0, 17), end: new Date(2014, 0, 21) }\n * )\n * //=> true\n *\n * @example\n * // For non-overlapping time intervals:\n * areIntervalsOverlapping(\n * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },\n * { start: new Date(2014, 0, 21), end: new Date(2014, 0, 22) }\n * )\n * //=> false\n *\n * @example\n * // For adjacent time intervals:\n * areIntervalsOverlapping(\n * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },\n * { start: new Date(2014, 0, 20), end: new Date(2014, 0, 30) }\n * )\n * //=> false\n *\n * @example\n * // Using the inclusive option:\n * areIntervalsOverlapping(\n * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },\n * { start: new Date(2014, 0, 20), end: new Date(2014, 0, 24) },\n * { inclusive: true }\n * )\n * //=> true\n */\nfunction areIntervalsOverlapping(intervalLeft, intervalRight, options) {\n const [leftStartTime, leftEndTime] = [\n +(0, _index.toDate)(intervalLeft.start, options?.in),\n +(0, _index.toDate)(intervalLeft.end, options?.in),\n ].sort((a, b) => a - b);\n const [rightStartTime, rightEndTime] = [\n +(0, _index.toDate)(intervalRight.start, options?.in),\n +(0, _index.toDate)(intervalRight.end, options?.in),\n ].sort((a, b) => a - b);\n\n if (options?.inclusive)\n return leftStartTime <= rightEndTime && rightStartTime <= leftEndTime;\n\n return leftStartTime < rightEndTime && rightStartTime < leftEndTime;\n}\n", "\"use strict\";\nexports.max = max;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link max} function options.\n */\n\n/**\n * @name max\n * @category Common Helpers\n * @summary Return the latest of the given dates.\n *\n * @description\n * Return the latest of the given dates.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param dates - The dates to compare\n *\n * @returns The latest of the dates\n *\n * @example\n * // Which of these dates is the latest?\n * const result = max([\n * new Date(1989, 6, 10),\n * new Date(1987, 1, 11),\n * new Date(1995, 6, 2),\n * new Date(1990, 0, 1)\n * ])\n * //=> Sun Jul 02 1995 00:00:00\n */\nfunction max(dates, options) {\n let result;\n let context = options?.in;\n\n dates.forEach((date) => {\n // Use the first date object as the context function\n if (!context && typeof date === \"object\")\n context = _index.constructFrom.bind(null, date);\n\n const date_ = (0, _index2.toDate)(date, context);\n if (!result || result < date_ || isNaN(+date_)) result = date_;\n });\n\n return (0, _index.constructFrom)(context, result || NaN);\n}\n", "\"use strict\";\nexports.min = min;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link min} function options.\n */\n\n/**\n * @name min\n * @category Common Helpers\n * @summary Returns the earliest of the given dates.\n *\n * @description\n * Returns the earliest of the given dates.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param dates - The dates to compare\n *\n * @returns The earliest of the dates\n *\n * @example\n * // Which of these dates is the earliest?\n * const result = min([\n * new Date(1989, 6, 10),\n * new Date(1987, 1, 11),\n * new Date(1995, 6, 2),\n * new Date(1990, 0, 1)\n * ])\n * //=> Wed Feb 11 1987 00:00:00\n */\nfunction min(dates, options) {\n let result;\n let context = options?.in;\n\n dates.forEach((date) => {\n // Use the first date object as the context function\n if (!context && typeof date === \"object\")\n context = _index.constructFrom.bind(null, date);\n\n const date_ = (0, _index2.toDate)(date, context);\n if (!result || result > date_ || isNaN(+date_)) result = date_;\n });\n\n return (0, _index.constructFrom)(context, result || NaN);\n}\n", "\"use strict\";\nexports.clamp = clamp;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./max.cjs\");\nvar _index3 = require(\"./min.cjs\");\n\n/**\n * The {@link clamp} function options.\n */\n\n/**\n * The {@link clamp} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the date argument,\n * then the start interval date, and finally the end interval date. If\n * a context function is passed, it uses the context function return type.\n */\n\n/**\n * @name clamp\n * @category Interval Helpers\n * @summary Return a date bounded by the start and the end of the given interval.\n *\n * @description\n * Clamps a date to the lower bound with the start of the interval and the upper\n * bound with the end of the interval.\n *\n * - When the date is less than the start of the interval, the start is returned.\n * - When the date is greater than the end of the interval, the end is returned.\n * - Otherwise the date is returned.\n *\n * @typeParam DateType - Date argument type.\n * @typeParam IntervalType - Interval argument type.\n * @typeParam Options - Options type.\n *\n * @param date - The date to be bounded\n * @param interval - The interval to bound to\n * @param options - An object with options\n *\n * @returns The date bounded by the start and the end of the interval\n *\n * @example\n * // What is Mar 21, 2021 bounded to an interval starting at Mar 22, 2021 and ending at Apr 01, 2021\n * const result = clamp(new Date(2021, 2, 21), {\n * start: new Date(2021, 2, 22),\n * end: new Date(2021, 3, 1),\n * })\n * //=> Mon Mar 22 2021 00:00:00\n */\nfunction clamp(date, interval, options) {\n const [date_, start, end] = (0, _index.normalizeDates)(\n options?.in,\n date,\n interval.start,\n interval.end,\n );\n\n return (0, _index3.min)(\n [(0, _index2.max)([date_, start], options), end],\n options,\n );\n}\n", "\"use strict\";\nexports.closestIndexTo = closestIndexTo;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name closestIndexTo\n * @category Common Helpers\n * @summary Return an index of the closest date from the array comparing to the given date.\n *\n * @description\n * Return an index of the closest date from the array comparing to the given date.\n *\n * @param dateToCompare - The date to compare with\n * @param dates - The array to search\n *\n * @returns An index of the date closest to the given date or undefined if no valid value is given\n *\n * @example\n * // Which date is closer to 6 September 2015?\n * const dateToCompare = new Date(2015, 8, 6)\n * const datesArray = [\n * new Date(2015, 0, 1),\n * new Date(2016, 0, 1),\n * new Date(2017, 0, 1)\n * ]\n * const result = closestIndexTo(dateToCompare, datesArray)\n * //=> 1\n */\nfunction closestIndexTo(dateToCompare, dates) {\n // [TODO] It would be better to return -1 here rather than undefined, as this\n // is how JS behaves, but it would be a breaking change, so we need\n // to consider it for v4.\n const timeToCompare = +(0, _index.toDate)(dateToCompare);\n\n if (isNaN(timeToCompare)) return NaN;\n\n let result;\n let minDistance;\n dates.forEach((date, index) => {\n const date_ = (0, _index.toDate)(date);\n\n if (isNaN(+date_)) {\n result = NaN;\n minDistance = NaN;\n return;\n }\n\n const distance = Math.abs(timeToCompare - +date_);\n if (result == null || distance < minDistance) {\n result = index;\n minDistance = distance;\n }\n });\n\n return result;\n}\n", "\"use strict\";\nexports.closestTo = closestTo;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./closestIndexTo.cjs\");\nvar _index3 = require(\"./constructFrom.cjs\");\n\n/**\n * The {@link closestTo} function options.\n */\n\n/**\n * The {@link closestTo} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the date argument,\n * then the start interval date, and finally the end interval date. If\n * a context function is passed, it uses the context function return type.\n */\n\n/**\n * @name closestTo\n * @category Common Helpers\n * @summary Return a date from the array closest to the given date.\n *\n * @description\n * Return a date from the array closest to the given date.\n *\n * @typeParam DateToCompare - Date to compare argument type.\n * @typeParam DatesType - Dates array argument type.\n * @typeParam Options - Options type.\n *\n * @param dateToCompare - The date to compare with\n * @param dates - The array to search\n *\n * @returns The date from the array closest to the given date or undefined if no valid value is given\n *\n * @example\n * // Which date is closer to 6 September 2015: 1 January 2000 or 1 January 2030?\n * const dateToCompare = new Date(2015, 8, 6)\n * const result = closestTo(dateToCompare, [\n * new Date(2000, 0, 1),\n * new Date(2030, 0, 1)\n * ])\n * //=> Tue Jan 01 2030 00:00:00\n */\nfunction closestTo(dateToCompare, dates, options) {\n const [dateToCompare_, ...dates_] = (0, _index.normalizeDates)(\n options?.in,\n dateToCompare,\n ...dates,\n );\n\n const index = (0, _index2.closestIndexTo)(dateToCompare_, dates_);\n\n if (typeof index === \"number\" && isNaN(index))\n return (0, _index3.constructFrom)(dateToCompare_, NaN);\n\n if (index !== undefined) return dates_[index];\n}\n", "\"use strict\";\nexports.compareAsc = compareAsc;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name compareAsc\n * @category Common Helpers\n * @summary Compare the two dates and return -1, 0 or 1.\n *\n * @description\n * Compare the two dates and return 1 if the first date is after the second,\n * -1 if the first date is before the second or 0 if dates are equal.\n *\n * @param dateLeft - The first date to compare\n * @param dateRight - The second date to compare\n *\n * @returns The result of the comparison\n *\n * @example\n * // Compare 11 February 1987 and 10 July 1989:\n * const result = compareAsc(new Date(1987, 1, 11), new Date(1989, 6, 10))\n * //=> -1\n *\n * @example\n * // Sort the array of dates:\n * const result = [\n * new Date(1995, 6, 2),\n * new Date(1987, 1, 11),\n * new Date(1989, 6, 10)\n * ].sort(compareAsc)\n * //=> [\n * // Wed Feb 11 1987 00:00:00,\n * // Mon Jul 10 1989 00:00:00,\n * // Sun Jul 02 1995 00:00:00\n * // ]\n */\nfunction compareAsc(dateLeft, dateRight) {\n const diff = +(0, _index.toDate)(dateLeft) - +(0, _index.toDate)(dateRight);\n\n if (diff < 0) return -1;\n else if (diff > 0) return 1;\n\n // Return 0 if diff is 0; return NaN if diff is NaN\n return diff;\n}\n", "\"use strict\";\nexports.compareDesc = compareDesc;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name compareDesc\n * @category Common Helpers\n * @summary Compare the two dates reverse chronologically and return -1, 0 or 1.\n *\n * @description\n * Compare the two dates and return -1 if the first date is after the second,\n * 1 if the first date is before the second or 0 if dates are equal.\n *\n * @param dateLeft - The first date to compare\n * @param dateRight - The second date to compare\n *\n * @returns The result of the comparison\n *\n * @example\n * // Compare 11 February 1987 and 10 July 1989 reverse chronologically:\n * const result = compareDesc(new Date(1987, 1, 11), new Date(1989, 6, 10))\n * //=> 1\n *\n * @example\n * // Sort the array of dates in reverse chronological order:\n * const result = [\n * new Date(1995, 6, 2),\n * new Date(1987, 1, 11),\n * new Date(1989, 6, 10)\n * ].sort(compareDesc)\n * //=> [\n * // Sun Jul 02 1995 00:00:00,\n * // Mon Jul 10 1989 00:00:00,\n * // Wed Feb 11 1987 00:00:00\n * // ]\n */\nfunction compareDesc(dateLeft, dateRight) {\n const diff = +(0, _index.toDate)(dateLeft) - +(0, _index.toDate)(dateRight);\n\n if (diff > 0) return -1;\n else if (diff < 0) return 1;\n\n // Return 0 if diff is 0; return NaN if diff is NaN\n return diff;\n}\n", "\"use strict\";\nexports.constructNow = constructNow;\nvar _index = require(\"./constructFrom.cjs\");\n\n/**\n * @name constructNow\n * @category Generic Helpers\n * @summary Constructs a new current date using the passed value constructor.\n * @pure false\n *\n * @description\n * The function constructs a new current date using the constructor from\n * the reference date. It helps to build generic functions that accept date\n * extensions and use the current date.\n *\n * It defaults to `Date` if the passed reference date is a number or a string.\n *\n * @param date - The reference date to take constructor from\n *\n * @returns Current date initialized using the given date constructor\n *\n * @example\n * import { constructNow, isSameDay } from 'date-fns'\n *\n * function isToday(\n * date: DateArg,\n * ): boolean {\n * // If we were to use `new Date()` directly, the function would behave\n * // differently in different timezones and return false for the same date.\n * return isSameDay(date, constructNow(date));\n * }\n */\nfunction constructNow(date) {\n return (0, _index.constructFrom)(date, Date.now());\n}\n", "\"use strict\";\nexports.daysToWeeks = daysToWeeks;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name daysToWeeks\n * @category Conversion Helpers\n * @summary Convert days to weeks.\n *\n * @description\n * Convert a number of days to a full number of weeks.\n *\n * @param days - The number of days to be converted\n *\n * @returns The number of days converted in weeks\n *\n * @example\n * // Convert 14 days to weeks:\n * const result = daysToWeeks(14)\n * //=> 2\n *\n * @example\n * // It uses trunc rounding:\n * const result = daysToWeeks(13)\n * //=> 1\n */\nfunction daysToWeeks(days) {\n const result = Math.trunc(days / _index.daysInWeek);\n // Prevent negative zero\n return result === 0 ? 0 : result;\n}\n", "\"use strict\";\nexports.isSameDay = isSameDay;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./startOfDay.cjs\");\n\n/**\n * The {@link isSameDay} function options.\n */\n\n/**\n * @name isSameDay\n * @category Day Helpers\n * @summary Are the given dates in the same day (and year and month)?\n *\n * @description\n * Are the given dates in the same day (and year and month)?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same day (and year and month)\n *\n * @example\n * // Are 4 September 06:00:00 and 4 September 18:00:00 in the same day?\n * const result = isSameDay(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 4, 18, 0))\n * //=> true\n *\n * @example\n * // Are 4 September and 4 October in the same day?\n * const result = isSameDay(new Date(2014, 8, 4), new Date(2014, 9, 4))\n * //=> false\n *\n * @example\n * // Are 4 September, 2014 and 4 September, 2015 in the same day?\n * const result = isSameDay(new Date(2014, 8, 4), new Date(2015, 8, 4))\n * //=> false\n */\nfunction isSameDay(laterDate, earlierDate, options) {\n const [dateLeft_, dateRight_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return (\n +(0, _index2.startOfDay)(dateLeft_) === +(0, _index2.startOfDay)(dateRight_)\n );\n}\n", "\"use strict\";\nexports.isDate = isDate; /**\n * @name isDate\n * @category Common Helpers\n * @summary Is the given value a date?\n *\n * @description\n * Returns true if the given value is an instance of Date. The function works for dates transferred across iframes.\n *\n * @param value - The value to check\n *\n * @returns True if the given value is a date\n *\n * @example\n * // For a valid date:\n * const result = isDate(new Date())\n * //=> true\n *\n * @example\n * // For an invalid date:\n * const result = isDate(new Date(NaN))\n * //=> true\n *\n * @example\n * // For some value:\n * const result = isDate('2014-02-31')\n * //=> false\n *\n * @example\n * // For an object:\n * const result = isDate({})\n * //=> false\n */\nfunction isDate(value) {\n return (\n value instanceof Date ||\n (typeof value === \"object\" &&\n Object.prototype.toString.call(value) === \"[object Date]\")\n );\n}\n", "\"use strict\";\nexports.isValid = isValid;\nvar _index = require(\"./isDate.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * @name isValid\n * @category Common Helpers\n * @summary Is the given date valid?\n *\n * @description\n * Returns false if argument is Invalid Date and true otherwise.\n * Argument is converted to Date using `toDate`. See [toDate](https://date-fns.org/docs/toDate)\n * Invalid Date is a Date, whose time value is NaN.\n *\n * Time value of Date: http://es5.github.io/#x15.9.1.1\n *\n * @param date - The date to check\n *\n * @returns The date is valid\n *\n * @example\n * // For the valid date:\n * const result = isValid(new Date(2014, 1, 31))\n * //=> true\n *\n * @example\n * // For the value, convertible into a date:\n * const result = isValid(1393804800000)\n * //=> true\n *\n * @example\n * // For the invalid date:\n * const result = isValid(new Date(''))\n * //=> false\n */\nfunction isValid(date) {\n return !(\n (!(0, _index.isDate)(date) && typeof date !== \"number\") ||\n isNaN(+(0, _index2.toDate)(date))\n );\n}\n", "\"use strict\";\nexports.differenceInBusinessDays = differenceInBusinessDays;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./addDays.cjs\");\nvar _index3 = require(\"./differenceInCalendarDays.cjs\");\nvar _index4 = require(\"./isSameDay.cjs\");\nvar _index5 = require(\"./isValid.cjs\");\nvar _index6 = require(\"./isWeekend.cjs\");\n\n/**\n * The {@link differenceInBusinessDays} function options.\n */\n\n/**\n * @name differenceInBusinessDays\n * @category Day Helpers\n * @summary Get the number of business days between the given dates.\n *\n * @description\n * Get the number of business day periods between the given dates.\n * Business days being days that aren't in the weekend.\n * Like `differenceInCalendarDays`, the function removes the times from\n * the dates before calculating the difference.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of business days\n *\n * @example\n * // How many business days are between\n * // 10 January 2014 and 20 July 2014?\n * const result = differenceInBusinessDays(\n * new Date(2014, 6, 20),\n * new Date(2014, 0, 10)\n * )\n * //=> 136\n *\n * // How many business days are between\n * // 30 November 2021 and 1 November 2021?\n * const result = differenceInBusinessDays(\n * new Date(2021, 10, 30),\n * new Date(2021, 10, 1)\n * )\n * //=> 21\n *\n * // How many business days are between\n * // 1 November 2021 and 1 December 2021?\n * const result = differenceInBusinessDays(\n * new Date(2021, 10, 1),\n * new Date(2021, 11, 1)\n * )\n * //=> -22\n *\n * // How many business days are between\n * // 1 November 2021 and 1 November 2021 ?\n * const result = differenceInBusinessDays(\n * new Date(2021, 10, 1),\n * new Date(2021, 10, 1)\n * )\n * //=> 0\n */\nfunction differenceInBusinessDays(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n if (!(0, _index5.isValid)(laterDate_) || !(0, _index5.isValid)(earlierDate_))\n return NaN;\n\n const diff = (0, _index3.differenceInCalendarDays)(laterDate_, earlierDate_);\n const sign = diff < 0 ? -1 : 1;\n const weeks = Math.trunc(diff / 7);\n\n let result = weeks * 5;\n let movingDate = (0, _index2.addDays)(earlierDate_, weeks * 7);\n\n // the loop below will run at most 6 times to account for the remaining days that don't makeup a full week\n while (!(0, _index4.isSameDay)(laterDate_, movingDate)) {\n // sign is used to account for both negative and positive differences\n result += (0, _index6.isWeekend)(movingDate, options) ? 0 : sign;\n movingDate = (0, _index2.addDays)(movingDate, sign);\n }\n\n // Prevent negative zero\n return result === 0 ? 0 : result;\n}\n", "\"use strict\";\nexports.differenceInCalendarISOWeekYears = differenceInCalendarISOWeekYears;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./getISOWeekYear.cjs\");\n\n/**\n * The {@link differenceInCalendarISOWeekYears} function options.\n */\n\n/**\n * @name differenceInCalendarISOWeekYears\n * @category ISO Week-Numbering Year Helpers\n * @summary Get the number of calendar ISO week-numbering years between the given dates.\n *\n * @description\n * Get the number of calendar ISO week-numbering years between the given dates.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of calendar ISO week-numbering years\n *\n * @example\n * // How many calendar ISO week-numbering years are 1 January 2010 and 1 January 2012?\n * const result = differenceInCalendarISOWeekYears(\n * new Date(2012, 0, 1),\n * new Date(2010, 0, 1)\n * )\n * //=> 2\n */\nfunction differenceInCalendarISOWeekYears(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return (\n (0, _index2.getISOWeekYear)(laterDate_, options) -\n (0, _index2.getISOWeekYear)(earlierDate_, options)\n );\n}\n", "\"use strict\";\nexports.differenceInCalendarISOWeeks = differenceInCalendarISOWeeks;\nvar _index = require(\"./_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _index2 = require(\"./_lib/normalizeDates.cjs\");\nvar _index3 = require(\"./constants.cjs\");\nvar _index4 = require(\"./startOfISOWeek.cjs\");\n\n/**\n * The {@link differenceInCalendarISOWeeks} function options.\n */\n\n/**\n * @name differenceInCalendarISOWeeks\n * @category ISO Week Helpers\n * @summary Get the number of calendar ISO weeks between the given dates.\n *\n * @description\n * Get the number of calendar ISO weeks between the given dates.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of calendar ISO weeks\n *\n * @example\n * // How many calendar ISO weeks are between 6 July 2014 and 21 July 2014?\n * const result = differenceInCalendarISOWeeks(\n * new Date(2014, 6, 21),\n * new Date(2014, 6, 6),\n * );\n * //=> 3\n */\nfunction differenceInCalendarISOWeeks(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index2.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const startOfISOWeekLeft = (0, _index4.startOfISOWeek)(laterDate_);\n const startOfISOWeekRight = (0, _index4.startOfISOWeek)(earlierDate_);\n\n const timestampLeft =\n +startOfISOWeekLeft -\n (0, _index.getTimezoneOffsetInMilliseconds)(startOfISOWeekLeft);\n const timestampRight =\n +startOfISOWeekRight -\n (0, _index.getTimezoneOffsetInMilliseconds)(startOfISOWeekRight);\n\n // Round the number of weeks to the nearest integer because the number of\n // milliseconds in a week is not constant (e.g. it's different in the week of\n // the daylight saving time clock shift).\n return Math.round(\n (timestampLeft - timestampRight) / _index3.millisecondsInWeek,\n );\n}\n", "\"use strict\";\nexports.differenceInCalendarMonths = differenceInCalendarMonths;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\n\n/**\n * The {@link differenceInCalendarMonths} function options.\n */\n\n/**\n * @name differenceInCalendarMonths\n * @category Month Helpers\n * @summary Get the number of calendar months between the given dates.\n *\n * @description\n * Get the number of calendar months between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of calendar months\n *\n * @example\n * // How many calendar months are between 31 January 2014 and 1 September 2014?\n * const result = differenceInCalendarMonths(\n * new Date(2014, 8, 1),\n * new Date(2014, 0, 31)\n * )\n * //=> 8\n */\nfunction differenceInCalendarMonths(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const yearsDiff = laterDate_.getFullYear() - earlierDate_.getFullYear();\n const monthsDiff = laterDate_.getMonth() - earlierDate_.getMonth();\n\n return yearsDiff * 12 + monthsDiff;\n}\n", "\"use strict\";\nexports.getQuarter = getQuarter;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getQuarter} function options.\n */\n\n/**\n * @name getQuarter\n * @category Quarter Helpers\n * @summary Get the year quarter of the given date.\n *\n * @description\n * Get the year quarter of the given date.\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The quarter\n *\n * @example\n * // Which quarter is 2 July 2014?\n * const result = getQuarter(new Date(2014, 6, 2));\n * //=> 3\n */\nfunction getQuarter(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const quarter = Math.trunc(_date.getMonth() / 3) + 1;\n return quarter;\n}\n", "\"use strict\";\nexports.differenceInCalendarQuarters = differenceInCalendarQuarters;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./getQuarter.cjs\");\n\n/**\n * The {@link differenceInCalendarQuarters} function options.\n */\n\n/**\n * @name differenceInCalendarQuarters\n * @category Quarter Helpers\n * @summary Get the number of calendar quarters between the given dates.\n *\n * @description\n * Get the number of calendar quarters between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of calendar quarters\n *\n * @example\n * // How many calendar quarters are between 31 December 2013 and 2 July 2014?\n * const result = differenceInCalendarQuarters(\n * new Date(2014, 6, 2),\n * new Date(2013, 11, 31)\n * )\n * //=> 3\n */\nfunction differenceInCalendarQuarters(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const yearsDiff = laterDate_.getFullYear() - earlierDate_.getFullYear();\n const quartersDiff =\n (0, _index2.getQuarter)(laterDate_) - (0, _index2.getQuarter)(earlierDate_);\n\n return yearsDiff * 4 + quartersDiff;\n}\n", "\"use strict\";\nexports.differenceInCalendarWeeks = differenceInCalendarWeeks;\nvar _index = require(\"./_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _index2 = require(\"./_lib/normalizeDates.cjs\");\nvar _index3 = require(\"./constants.cjs\");\nvar _index4 = require(\"./startOfWeek.cjs\");\n\n/**\n * The {@link differenceInCalendarWeeks} function options.\n */\n\n/**\n * @name differenceInCalendarWeeks\n * @category Week Helpers\n * @summary Get the number of calendar weeks between the given dates.\n *\n * @description\n * Get the number of calendar weeks between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options.\n *\n * @returns The number of calendar weeks\n *\n * @example\n * // How many calendar weeks are between 5 July 2014 and 20 July 2014?\n * const result = differenceInCalendarWeeks(\n * new Date(2014, 6, 20),\n * new Date(2014, 6, 5)\n * )\n * //=> 3\n *\n * @example\n * // If the week starts on Monday,\n * // how many calendar weeks are between 5 July 2014 and 20 July 2014?\n * const result = differenceInCalendarWeeks(\n * new Date(2014, 6, 20),\n * new Date(2014, 6, 5),\n * { weekStartsOn: 1 }\n * )\n * //=> 2\n */\nfunction differenceInCalendarWeeks(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index2.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const laterStartOfWeek = (0, _index4.startOfWeek)(laterDate_, options);\n const earlierStartOfWeek = (0, _index4.startOfWeek)(earlierDate_, options);\n\n const laterTimestamp =\n +laterStartOfWeek -\n (0, _index.getTimezoneOffsetInMilliseconds)(laterStartOfWeek);\n const earlierTimestamp =\n +earlierStartOfWeek -\n (0, _index.getTimezoneOffsetInMilliseconds)(earlierStartOfWeek);\n\n return Math.round(\n (laterTimestamp - earlierTimestamp) / _index3.millisecondsInWeek,\n );\n}\n", "\"use strict\";\nexports.differenceInCalendarYears = differenceInCalendarYears;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\n\n/**\n * The {@link differenceInCalendarYears} function options.\n */\n\n/**\n * @name differenceInCalendarYears\n * @category Year Helpers\n * @summary Get the number of calendar years between the given dates.\n *\n * @description\n * Get the number of calendar years between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n\n * @returns The number of calendar years\n *\n * @example\n * // How many calendar years are between 31 December 2013 and 11 February 2015?\n * const result = differenceInCalendarYears(\n * new Date(2015, 1, 11),\n * new Date(2013, 11, 31)\n * );\n * //=> 2\n */\nfunction differenceInCalendarYears(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return laterDate_.getFullYear() - earlierDate_.getFullYear();\n}\n", "\"use strict\";\nexports.differenceInDays = differenceInDays;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./differenceInCalendarDays.cjs\");\n\n/**\n * The {@link differenceInDays} function options.\n */\n\n/**\n * @name differenceInDays\n * @category Day Helpers\n * @summary Get the number of full days between the given dates.\n *\n * @description\n * Get the number of full day periods between two dates. Fractional days are\n * truncated towards zero.\n *\n * One \"full day\" is the distance between a local time in one day to the same\n * local time on the next or previous day. A full day can sometimes be less than\n * or more than 24 hours if a daylight savings change happens between two dates.\n *\n * To ignore DST and only measure exact 24-hour periods, use this instead:\n * `Math.trunc(differenceInHours(dateLeft, dateRight)/24)|0`.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of full days according to the local timezone\n *\n * @example\n * // How many full days are between\n * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00?\n * const result = differenceInDays(\n * new Date(2012, 6, 2, 0, 0),\n * new Date(2011, 6, 2, 23, 0)\n * )\n * //=> 365\n *\n * @example\n * // How many full days are between\n * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00?\n * const result = differenceInDays(\n * new Date(2011, 6, 3, 0, 1),\n * new Date(2011, 6, 2, 23, 59)\n * )\n * //=> 0\n *\n * @example\n * // How many full days are between\n * // 1 March 2020 0:00 and 1 June 2020 0:00 ?\n * // Note: because local time is used, the\n * // result will always be 92 days, even in\n * // time zones where DST starts and the\n * // period has only 92*24-1 hours.\n * const result = differenceInDays(\n * new Date(2020, 5, 1),\n * new Date(2020, 2, 1)\n * )\n * //=> 92\n */\nfunction differenceInDays(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const sign = compareLocalAsc(laterDate_, earlierDate_);\n const difference = Math.abs(\n (0, _index2.differenceInCalendarDays)(laterDate_, earlierDate_),\n );\n\n laterDate_.setDate(laterDate_.getDate() - sign * difference);\n\n // Math.abs(diff in full days - diff in calendar days) === 1 if last calendar day is not full\n // If so, result must be decreased by 1 in absolute value\n const isLastDayNotFull = Number(\n compareLocalAsc(laterDate_, earlierDate_) === -sign,\n );\n\n const result = sign * (difference - isLastDayNotFull);\n // Prevent negative zero\n return result === 0 ? 0 : result;\n}\n\n// Like `compareAsc` but uses local time not UTC, which is needed\n// for accurate equality comparisons of UTC timestamps that end up\n// having the same representation in local time, e.g. one hour before\n// DST ends vs. the instant that DST ends.\nfunction compareLocalAsc(laterDate, earlierDate) {\n const diff =\n laterDate.getFullYear() - earlierDate.getFullYear() ||\n laterDate.getMonth() - earlierDate.getMonth() ||\n laterDate.getDate() - earlierDate.getDate() ||\n laterDate.getHours() - earlierDate.getHours() ||\n laterDate.getMinutes() - earlierDate.getMinutes() ||\n laterDate.getSeconds() - earlierDate.getSeconds() ||\n laterDate.getMilliseconds() - earlierDate.getMilliseconds();\n\n if (diff < 0) return -1;\n if (diff > 0) return 1;\n\n // Return 0 if diff is 0; return NaN if diff is NaN\n return diff;\n}\n", "\"use strict\";\nexports.getRoundingMethod = getRoundingMethod;\n\nfunction getRoundingMethod(method) {\n return (number) => {\n const round = method ? Math[method] : Math.trunc;\n const result = round(number);\n // Prevent negative zero\n return result === 0 ? 0 : result;\n };\n}\n", "\"use strict\";\nexports.differenceInHours = differenceInHours;\nvar _index = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index2 = require(\"./_lib/normalizeDates.cjs\");\nvar _index3 = require(\"./constants.cjs\");\n\n/**\n * The {@link differenceInHours} function options.\n */\n\n/**\n * @name differenceInHours\n * @category Hour Helpers\n * @summary Get the number of hours between the given dates.\n *\n * @description\n * Get the number of hours between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options.\n *\n * @returns The number of hours\n *\n * @example\n * // How many hours are between 2 July 2014 06:50:00 and 2 July 2014 19:00:00?\n * const result = differenceInHours(\n * new Date(2014, 6, 2, 19, 0),\n * new Date(2014, 6, 2, 6, 50)\n * )\n * //=> 12\n */\nfunction differenceInHours(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index2.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n const diff = (+laterDate_ - +earlierDate_) / _index3.millisecondsInHour;\n return (0, _index.getRoundingMethod)(options?.roundingMethod)(diff);\n}\n", "\"use strict\";\nexports.subISOWeekYears = subISOWeekYears;\nvar _index = require(\"./addISOWeekYears.cjs\");\n\n/**\n * The {@link subISOWeekYears} function options.\n */\n\n/**\n * @name subISOWeekYears\n * @category ISO Week-Numbering Year Helpers\n * @summary Subtract the specified number of ISO week-numbering years from the given date.\n *\n * @description\n * Subtract the specified number of ISO week-numbering years from the given date.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of ISO week-numbering years to be subtracted.\n * @param options - The options\n *\n * @returns The new date with the ISO week-numbering years subtracted\n *\n * @example\n * // Subtract 5 ISO week-numbering years from 1 September 2014:\n * const result = subISOWeekYears(new Date(2014, 8, 1), 5)\n * //=> Mon Aug 31 2009 00:00:00\n */\nfunction subISOWeekYears(date, amount, options) {\n return (0, _index.addISOWeekYears)(date, -amount, options);\n}\n", "\"use strict\";\nexports.differenceInISOWeekYears = differenceInISOWeekYears;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./compareAsc.cjs\");\nvar _index3 = require(\"./differenceInCalendarISOWeekYears.cjs\");\nvar _index4 = require(\"./subISOWeekYears.cjs\");\n\n/**\n * The {@link differenceInISOWeekYears} function options.\n */\n\n/**\n * @name differenceInISOWeekYears\n * @category ISO Week-Numbering Year Helpers\n * @summary Get the number of full ISO week-numbering years between the given dates.\n *\n * @description\n * Get the number of full ISO week-numbering years between the given dates.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - The options\n *\n * @returns The number of full ISO week-numbering years\n *\n * @example\n * // How many full ISO week-numbering years are between 1 January 2010 and 1 January 2012?\n * const result = differenceInISOWeekYears(\n * new Date(2012, 0, 1),\n * new Date(2010, 0, 1)\n * )\n * // => 1\n */\nfunction differenceInISOWeekYears(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n const sign = (0, _index2.compareAsc)(laterDate_, earlierDate_);\n const diff = Math.abs(\n (0, _index3.differenceInCalendarISOWeekYears)(\n laterDate_,\n earlierDate_,\n options,\n ),\n );\n\n const adjustedDate = (0, _index4.subISOWeekYears)(\n laterDate_,\n sign * diff,\n options,\n );\n\n const isLastISOWeekYearNotFull = Number(\n (0, _index2.compareAsc)(adjustedDate, earlierDate_) === -sign,\n );\n const result = sign * (diff - isLastISOWeekYearNotFull);\n\n // Prevent negative zero\n return result === 0 ? 0 : result;\n}\n", "\"use strict\";\nexports.differenceInMilliseconds = differenceInMilliseconds;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name differenceInMilliseconds\n * @category Millisecond Helpers\n * @summary Get the number of milliseconds between the given dates.\n *\n * @description\n * Get the number of milliseconds between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n *\n * @returns The number of milliseconds\n *\n * @example\n * // How many milliseconds are between\n * // 2 July 2014 12:30:20.600 and 2 July 2014 12:30:21.700?\n * const result = differenceInMilliseconds(\n * new Date(2014, 6, 2, 12, 30, 21, 700),\n * new Date(2014, 6, 2, 12, 30, 20, 600)\n * )\n * //=> 1100\n */\nfunction differenceInMilliseconds(laterDate, earlierDate) {\n return +(0, _index.toDate)(laterDate) - +(0, _index.toDate)(earlierDate);\n}\n", "\"use strict\";\nexports.differenceInMinutes = differenceInMinutes;\nvar _index = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index2 = require(\"./constants.cjs\");\nvar _index3 = require(\"./differenceInMilliseconds.cjs\");\n\n/**\n * The {@link differenceInMinutes} function options.\n */\n\n/**\n * @name differenceInMinutes\n * @category Minute Helpers\n * @summary Get the number of minutes between the given dates.\n *\n * @description\n * Get the signed number of full (rounded towards 0) minutes between the given dates.\n *\n * @param dateLeft - The later date\n * @param dateRight - The earlier date\n * @param options - An object with options.\n *\n * @returns The number of minutes\n *\n * @example\n * // How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00?\n * const result = differenceInMinutes(\n * new Date(2014, 6, 2, 12, 20, 0),\n * new Date(2014, 6, 2, 12, 7, 59)\n * )\n * //=> 12\n *\n * @example\n * // How many minutes are between 10:01:59 and 10:00:00\n * const result = differenceInMinutes(\n * new Date(2000, 0, 1, 10, 0, 0),\n * new Date(2000, 0, 1, 10, 1, 59)\n * )\n * //=> -1\n */\nfunction differenceInMinutes(dateLeft, dateRight, options) {\n const diff =\n (0, _index3.differenceInMilliseconds)(dateLeft, dateRight) /\n _index2.millisecondsInMinute;\n return (0, _index.getRoundingMethod)(options?.roundingMethod)(diff);\n}\n", "\"use strict\";\nexports.endOfDay = endOfDay;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfDay} function options.\n */\n\n/**\n * @name endOfDay\n * @category Day Helpers\n * @summary Return the end of a day for the given date.\n *\n * @description\n * Return the end of a day for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a day\n *\n * @example\n * // The end of a day for 2 September 2014 11:55:00:\n * const result = endOfDay(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 02 2014 23:59:59.999\n */\nfunction endOfDay(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setHours(23, 59, 59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.endOfMonth = endOfMonth;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfMonth} function options.\n */\n\n/**\n * @name endOfMonth\n * @category Month Helpers\n * @summary Return the end of a month for the given date.\n *\n * @description\n * Return the end of a month for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a month\n *\n * @example\n * // The end of a month for 2 September 2014 11:55:00:\n * const result = endOfMonth(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 30 2014 23:59:59.999\n */\nfunction endOfMonth(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const month = _date.getMonth();\n _date.setFullYear(_date.getFullYear(), month + 1, 0);\n _date.setHours(23, 59, 59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.isLastDayOfMonth = isLastDayOfMonth;\nvar _index = require(\"./endOfDay.cjs\");\nvar _index2 = require(\"./endOfMonth.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * @name isLastDayOfMonth\n * @category Month Helpers\n * @summary Is the given date the last day of a month?\n *\n * @description\n * Is the given date the last day of a month?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is the last day of a month\n *\n * @example\n * // Is 28 February 2014 the last day of a month?\n * const result = isLastDayOfMonth(new Date(2014, 1, 28))\n * //=> true\n */\nfunction isLastDayOfMonth(date, options) {\n const _date = (0, _index3.toDate)(date, options?.in);\n return (\n +(0, _index.endOfDay)(_date, options) ===\n +(0, _index2.endOfMonth)(_date, options)\n );\n}\n", "\"use strict\";\nexports.differenceInMonths = differenceInMonths;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./compareAsc.cjs\");\nvar _index3 = require(\"./differenceInCalendarMonths.cjs\");\nvar _index4 = require(\"./isLastDayOfMonth.cjs\");\n\n/**\n * The {@link differenceInMonths} function options.\n */\n\n/**\n * @name differenceInMonths\n * @category Month Helpers\n * @summary Get the number of full months between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of full months\n *\n * @example\n * // How many full months are between 31 January 2014 and 1 September 2014?\n * const result = differenceInMonths(new Date(2014, 8, 1), new Date(2014, 0, 31))\n * //=> 7\n */\nfunction differenceInMonths(laterDate, earlierDate, options) {\n const [laterDate_, workingLaterDate, earlierDate_] = (0,\n _index.normalizeDates)(options?.in, laterDate, laterDate, earlierDate);\n\n const sign = (0, _index2.compareAsc)(workingLaterDate, earlierDate_);\n const difference = Math.abs(\n (0, _index3.differenceInCalendarMonths)(workingLaterDate, earlierDate_),\n );\n\n if (difference < 1) return 0;\n\n if (workingLaterDate.getMonth() === 1 && workingLaterDate.getDate() > 27)\n workingLaterDate.setDate(30);\n\n workingLaterDate.setMonth(workingLaterDate.getMonth() - sign * difference);\n\n let isLastMonthNotFull =\n (0, _index2.compareAsc)(workingLaterDate, earlierDate_) === -sign;\n\n if (\n (0, _index4.isLastDayOfMonth)(laterDate_) &&\n difference === 1 &&\n (0, _index2.compareAsc)(laterDate_, earlierDate_) === 1\n ) {\n isLastMonthNotFull = false;\n }\n\n const result = sign * (difference - +isLastMonthNotFull);\n return result === 0 ? 0 : result;\n}\n", "\"use strict\";\nexports.differenceInQuarters = differenceInQuarters;\nvar _index = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index2 = require(\"./differenceInMonths.cjs\");\n\n/**\n * The {@link differenceInQuarters} function options.\n */\n\n/**\n * @name differenceInQuarters\n * @category Quarter Helpers\n * @summary Get the number of quarters between the given dates.\n *\n * @description\n * Get the number of quarters between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options.\n *\n * @returns The number of full quarters\n *\n * @example\n * // How many full quarters are between 31 December 2013 and 2 July 2014?\n * const result = differenceInQuarters(new Date(2014, 6, 2), new Date(2013, 11, 31))\n * //=> 2\n */\nfunction differenceInQuarters(laterDate, earlierDate, options) {\n const diff =\n (0, _index2.differenceInMonths)(laterDate, earlierDate, options) / 3;\n return (0, _index.getRoundingMethod)(options?.roundingMethod)(diff);\n}\n", "\"use strict\";\nexports.differenceInSeconds = differenceInSeconds;\nvar _index = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index2 = require(\"./differenceInMilliseconds.cjs\");\n\n/**\n * The {@link differenceInSeconds} function options.\n */\n\n/**\n * @name differenceInSeconds\n * @category Second Helpers\n * @summary Get the number of seconds between the given dates.\n *\n * @description\n * Get the number of seconds between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options.\n *\n * @returns The number of seconds\n *\n * @example\n * // How many seconds are between\n * // 2 July 2014 12:30:07.999 and 2 July 2014 12:30:20.000?\n * const result = differenceInSeconds(\n * new Date(2014, 6, 2, 12, 30, 20, 0),\n * new Date(2014, 6, 2, 12, 30, 7, 999)\n * )\n * //=> 12\n */\nfunction differenceInSeconds(laterDate, earlierDate, options) {\n const diff =\n (0, _index2.differenceInMilliseconds)(laterDate, earlierDate) / 1000;\n return (0, _index.getRoundingMethod)(options?.roundingMethod)(diff);\n}\n", "\"use strict\";\nexports.differenceInWeeks = differenceInWeeks;\nvar _index = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index2 = require(\"./differenceInDays.cjs\");\n\n/**\n * The {@link differenceInWeeks} function options.\n */\n\n/**\n * @name differenceInWeeks\n * @category Week Helpers\n * @summary Get the number of full weeks between the given dates.\n *\n * @description\n * Get the number of full weeks between two dates. Fractional weeks are\n * truncated towards zero by default.\n *\n * One \"full week\" is the distance between a local time in one day to the same\n * local time 7 days earlier or later. A full week can sometimes be less than\n * or more than 7*24 hours if a daylight savings change happens between two dates.\n *\n * To ignore DST and only measure exact 7*24-hour periods, use this instead:\n * `Math.trunc(differenceInHours(dateLeft, dateRight)/(7*24))|0`.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of full weeks\n *\n * @example\n * // How many full weeks are between 5 July 2014 and 20 July 2014?\n * const result = differenceInWeeks(new Date(2014, 6, 20), new Date(2014, 6, 5))\n * //=> 2\n *\n * @example\n * // How many full weeks are between\n * // 1 March 2020 0:00 and 6 June 2020 0:00 ?\n * // Note: because local time is used, the\n * // result will always be 8 weeks (54 days),\n * // even if DST starts and the period has\n * // only 54*24-1 hours.\n * const result = differenceInWeeks(\n * new Date(2020, 5, 1),\n * new Date(2020, 2, 6)\n * )\n * //=> 8\n */\nfunction differenceInWeeks(laterDate, earlierDate, options) {\n const diff =\n (0, _index2.differenceInDays)(laterDate, earlierDate, options) / 7;\n return (0, _index.getRoundingMethod)(options?.roundingMethod)(diff);\n}\n", "\"use strict\";\nexports.differenceInYears = differenceInYears;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./compareAsc.cjs\");\nvar _index3 = require(\"./differenceInCalendarYears.cjs\");\n\n/**\n * The {@link differenceInYears} function options.\n */\n\n/**\n * @name differenceInYears\n * @category Year Helpers\n * @summary Get the number of full years between the given dates.\n *\n * @description\n * Get the number of full years between the given dates.\n *\n * @param laterDate - The later date\n * @param earlierDate - The earlier date\n * @param options - An object with options\n *\n * @returns The number of full years\n *\n * @example\n * // How many full years are between 31 December 2013 and 11 February 2015?\n * const result = differenceInYears(new Date(2015, 1, 11), new Date(2013, 11, 31))\n * //=> 1\n */\nfunction differenceInYears(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n // -1 if the left date is earlier than the right date\n // 2023-12-31 - 2024-01-01 = -1\n const sign = (0, _index2.compareAsc)(laterDate_, earlierDate_);\n\n // First calculate the difference in calendar years\n // 2024-01-01 - 2023-12-31 = 1 year\n const diff = Math.abs(\n (0, _index3.differenceInCalendarYears)(laterDate_, earlierDate_),\n );\n\n // Now we need to calculate if the difference is full. To do that we set\n // both dates to the same year and check if the both date's month and day\n // form a full year.\n laterDate_.setFullYear(1584);\n earlierDate_.setFullYear(1584);\n\n // For it to be true, when the later date is indeed later than the earlier date\n // (2026-02-01 - 2023-12-10 = 3 years), the difference is full if\n // the normalized later date is also later than the normalized earlier date.\n // In our example, 1584-02-01 is earlier than 1584-12-10, so the difference\n // is partial, hence we need to subtract 1 from the difference 3 - 1 = 2.\n const partial = (0, _index2.compareAsc)(laterDate_, earlierDate_) === -sign;\n\n const result = sign * (diff - +partial);\n\n // Prevent negative zero\n return result === 0 ? 0 : result;\n}\n", "\"use strict\";\nexports.normalizeInterval = normalizeInterval;\nvar _index = require(\"./normalizeDates.cjs\");\n\nfunction normalizeInterval(context, interval) {\n const [start, end] = (0, _index.normalizeDates)(\n context,\n interval.start,\n interval.end,\n );\n return { start, end };\n}\n", "\"use strict\";\nexports.eachDayOfInterval = eachDayOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\n\n/**\n * The {@link eachDayOfInterval} function options.\n */\n\n/**\n * The {@link eachDayOfInterval} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the date argument,\n * then the start interval date, and finally the end interval date. If\n * a context function is passed, it uses the context function return type.\n */\n\n/**\n * @name eachDayOfInterval\n * @category Interval Helpers\n * @summary Return the array of dates within the specified time interval.\n *\n * @description\n * Return the array of dates within the specified time interval.\n *\n * @typeParam IntervalType - Interval type.\n * @typeParam Options - Options type.\n *\n * @param interval - The interval.\n * @param options - An object with options.\n *\n * @returns The array with starts of days from the day of the interval start to the day of the interval end\n *\n * @example\n * // Each day between 6 October 2014 and 10 October 2014:\n * const result = eachDayOfInterval({\n * start: new Date(2014, 9, 6),\n * end: new Date(2014, 9, 10)\n * })\n * //=> [\n * // Mon Oct 06 2014 00:00:00,\n * // Tue Oct 07 2014 00:00:00,\n * // Wed Oct 08 2014 00:00:00,\n * // Thu Oct 09 2014 00:00:00,\n * // Fri Oct 10 2014 00:00:00\n * // ]\n */\nfunction eachDayOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n\n let reversed = +start > +end;\n const endTime = reversed ? +start : +end;\n const date = reversed ? end : start;\n date.setHours(0, 0, 0, 0);\n\n let step = options?.step ?? 1;\n if (!step) return [];\n if (step < 0) {\n step = -step;\n reversed = !reversed;\n }\n\n const dates = [];\n\n while (+date <= endTime) {\n dates.push((0, _index2.constructFrom)(start, date));\n date.setDate(date.getDate() + step);\n date.setHours(0, 0, 0, 0);\n }\n\n return reversed ? dates.reverse() : dates;\n}\n", "\"use strict\";\nexports.eachHourOfInterval = eachHourOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\n\n/**\n * The {@link eachHourOfInterval} function options.\n */\n\n/**\n * The {@link eachHourOfInterval} function result type.\n * Resolves to the appropriate date type based on inputs.\n */\n\n/**\n * @name eachHourOfInterval\n * @category Interval Helpers\n * @summary Return the array of hours within the specified time interval.\n *\n * @description\n * Return the array of hours within the specified time interval.\n *\n * @typeParam IntervalType - Interval type.\n * @typeParam Options - Options type.\n *\n * @param interval - The interval.\n * @param options - An object with options.\n *\n * @returns The array with starts of hours from the hour of the interval start to the hour of the interval end\n *\n * @example\n * // Each hour between 6 October 2014, 12:00 and 6 October 2014, 15:00\n * const result = eachHourOfInterval({\n * start: new Date(2014, 9, 6, 12),\n * end: new Date(2014, 9, 6, 15)\n * });\n * //=> [\n * // Mon Oct 06 2014 12:00:00,\n * // Mon Oct 06 2014 13:00:00,\n * // Mon Oct 06 2014 14:00:00,\n * // Mon Oct 06 2014 15:00:00\n * // ]\n */\nfunction eachHourOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n\n let reversed = +start > +end;\n const endTime = reversed ? +start : +end;\n const date = reversed ? end : start;\n date.setMinutes(0, 0, 0);\n\n let step = options?.step ?? 1;\n if (!step) return [];\n if (step < 0) {\n step = -step;\n reversed = !reversed;\n }\n\n const dates = [];\n\n while (+date <= endTime) {\n dates.push((0, _index2.constructFrom)(start, date));\n date.setHours(date.getHours() + step);\n }\n\n return reversed ? dates.reverse() : dates;\n}\n", "\"use strict\";\nexports.eachMinuteOfInterval = eachMinuteOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./addMinutes.cjs\");\nvar _index3 = require(\"./constructFrom.cjs\");\n\n/**\n * The {@link eachMinuteOfInterval} function options.\n */\n\n/**\n * The {@link eachMinuteOfInterval} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the date argument,\n * then the start interval date, and finally the end interval date. If\n * a context function is passed, it uses the context function return type.\n */\n\n/**\n * @name eachMinuteOfInterval\n * @category Interval Helpers\n * @summary Return the array of minutes within the specified time interval.\n *\n * @description\n * Returns the array of minutes within the specified time interval.\n *\n * @typeParam IntervalType - Interval type.\n * @typeParam Options - Options type.\n *\n * @param interval - The interval.\n * @param options - An object with options.\n *\n * @returns The array with starts of minutes from the minute of the interval start to the minute of the interval end\n *\n * @example\n * // Each minute between 14 October 2020, 13:00 and 14 October 2020, 13:03\n * const result = eachMinuteOfInterval({\n * start: new Date(2014, 9, 14, 13),\n * end: new Date(2014, 9, 14, 13, 3)\n * })\n * //=> [\n * // Wed Oct 14 2014 13:00:00,\n * // Wed Oct 14 2014 13:01:00,\n * // Wed Oct 14 2014 13:02:00,\n * // Wed Oct 14 2014 13:03:00\n * // ]\n */\nfunction eachMinuteOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n // Set to the start of the minute\n start.setSeconds(0, 0);\n\n let reversed = +start > +end;\n const endTime = reversed ? +start : +end;\n let date = reversed ? end : start;\n\n let step = options?.step ?? 1;\n if (!step) return [];\n if (step < 0) {\n step = -step;\n reversed = !reversed;\n }\n\n const dates = [];\n\n while (+date <= endTime) {\n dates.push((0, _index3.constructFrom)(start, date));\n date = (0, _index2.addMinutes)(date, step);\n }\n\n return reversed ? dates.reverse() : dates;\n}\n", "\"use strict\";\nexports.eachMonthOfInterval = eachMonthOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\n\n/**\n * The {@link eachMonthOfInterval} function options.\n */\n\n/**\n * The {@link eachMonthOfInterval} function result type. It resolves the proper data type.\n */\n\n/**\n * @name eachMonthOfInterval\n * @category Interval Helpers\n * @summary Return the array of months within the specified time interval.\n *\n * @description\n * Return the array of months within the specified time interval.\n *\n * @typeParam IntervalType - Interval type.\n * @typeParam Options - Options type.\n *\n * @param interval - The interval.\n * @param options - An object with options.\n *\n * @returns The array with starts of months from the month of the interval start to the month of the interval end\n *\n * @example\n * // Each month between 6 February 2014 and 10 August 2014:\n * const result = eachMonthOfInterval({\n * start: new Date(2014, 1, 6),\n * end: new Date(2014, 7, 10)\n * })\n * //=> [\n * // Sat Feb 01 2014 00:00:00,\n * // Sat Mar 01 2014 00:00:00,\n * // Tue Apr 01 2014 00:00:00,\n * // Thu May 01 2014 00:00:00,\n * // Sun Jun 01 2014 00:00:00,\n * // Tue Jul 01 2014 00:00:00,\n * // Fri Aug 01 2014 00:00:00\n * // ]\n */\nfunction eachMonthOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n\n let reversed = +start > +end;\n const endTime = reversed ? +start : +end;\n const date = reversed ? end : start;\n date.setHours(0, 0, 0, 0);\n date.setDate(1);\n\n let step = options?.step ?? 1;\n if (!step) return [];\n if (step < 0) {\n step = -step;\n reversed = !reversed;\n }\n\n const dates = [];\n\n while (+date <= endTime) {\n dates.push((0, _index2.constructFrom)(start, date));\n date.setMonth(date.getMonth() + step);\n }\n\n return reversed ? dates.reverse() : dates;\n}\n", "\"use strict\";\nexports.startOfQuarter = startOfQuarter;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfQuarter} function options.\n */\n\n/**\n * @name startOfQuarter\n * @category Quarter Helpers\n * @summary Return the start of a year quarter for the given date.\n *\n * @description\n * Return the start of a year quarter for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The start of a quarter\n *\n * @example\n * // The start of a quarter for 2 September 2014 11:55:00:\n * const result = startOfQuarter(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Jul 01 2014 00:00:00\n */\nfunction startOfQuarter(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const currentMonth = _date.getMonth();\n const month = currentMonth - (currentMonth % 3);\n _date.setMonth(month, 1);\n _date.setHours(0, 0, 0, 0);\n return _date;\n}\n", "\"use strict\";\nexports.eachQuarterOfInterval = eachQuarterOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./addQuarters.cjs\");\nvar _index3 = require(\"./constructFrom.cjs\");\nvar _index4 = require(\"./startOfQuarter.cjs\");\n\n/**\n * The {@link eachQuarterOfInterval} function options.\n */\n\n/**\n * The {@link eachQuarterOfInterval} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the date argument,\n * then the start interval date, and finally the end interval date. If\n * a context function is passed, it uses the context function return type.\n */\n\n/**\n * @name eachQuarterOfInterval\n * @category Interval Helpers\n * @summary Return the array of quarters within the specified time interval.\n *\n * @description\n * Return the array of quarters within the specified time interval.\n *\n * @typeParam IntervalType - Interval type.\n * @typeParam Options - Options type.\n *\n * @param interval - The interval\n * @param options - An object with options\n *\n * @returns The array with starts of quarters from the quarter of the interval start to the quarter of the interval end\n *\n * @example\n * // Each quarter within interval 6 February 2014 - 10 August 2014:\n * const result = eachQuarterOfInterval({\n * start: new Date(2014, 1, 6),\n * end: new Date(2014, 7, 10),\n * })\n * //=> [\n * // Wed Jan 01 2014 00:00:00,\n * // Tue Apr 01 2014 00:00:00,\n * // Tue Jul 01 2014 00:00:00,\n * // ]\n */\nfunction eachQuarterOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n\n let reversed = +start > +end;\n const endTime = reversed\n ? +(0, _index4.startOfQuarter)(start)\n : +(0, _index4.startOfQuarter)(end);\n let date = reversed\n ? (0, _index4.startOfQuarter)(end)\n : (0, _index4.startOfQuarter)(start);\n\n let step = options?.step ?? 1;\n if (!step) return [];\n if (step < 0) {\n step = -step;\n reversed = !reversed;\n }\n\n const dates = [];\n\n while (+date <= endTime) {\n dates.push((0, _index3.constructFrom)(start, date));\n date = (0, _index2.addQuarters)(date, step);\n }\n\n return reversed ? dates.reverse() : dates;\n}\n", "\"use strict\";\nexports.eachWeekOfInterval = eachWeekOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./addWeeks.cjs\");\nvar _index3 = require(\"./constructFrom.cjs\");\nvar _index4 = require(\"./startOfWeek.cjs\");\n\n/**\n * The {@link eachWeekOfInterval} function options.\n */\n\n/**\n * The {@link eachWeekOfInterval} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the interval start date,\n * then the end interval date. If a context function is passed, it uses the context function return type.\n */\n\n/**\n * @name eachWeekOfInterval\n * @category Interval Helpers\n * @summary Return the array of weeks within the specified time interval.\n *\n * @description\n * Return the array of weeks within the specified time interval.\n *\n * @param interval - The interval.\n * @param options - An object with options.\n *\n * @returns The array with starts of weeks from the week of the interval start to the week of the interval end\n *\n * @example\n * // Each week within interval 6 October 2014 - 23 November 2014:\n * const result = eachWeekOfInterval({\n * start: new Date(2014, 9, 6),\n * end: new Date(2014, 10, 23)\n * })\n * //=> [\n * // Sun Oct 05 2014 00:00:00,\n * // Sun Oct 12 2014 00:00:00,\n * // Sun Oct 19 2014 00:00:00,\n * // Sun Oct 26 2014 00:00:00,\n * // Sun Nov 02 2014 00:00:00,\n * // Sun Nov 09 2014 00:00:00,\n * // Sun Nov 16 2014 00:00:00,\n * // Sun Nov 23 2014 00:00:00\n * // ]\n */\nfunction eachWeekOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n\n let reversed = +start > +end;\n const startDateWeek = reversed\n ? (0, _index4.startOfWeek)(end, options)\n : (0, _index4.startOfWeek)(start, options);\n const endDateWeek = reversed\n ? (0, _index4.startOfWeek)(start, options)\n : (0, _index4.startOfWeek)(end, options);\n\n startDateWeek.setHours(15);\n endDateWeek.setHours(15);\n\n const endTime = +endDateWeek.getTime();\n let currentDate = startDateWeek;\n\n let step = options?.step ?? 1;\n if (!step) return [];\n if (step < 0) {\n step = -step;\n reversed = !reversed;\n }\n\n const dates = [];\n\n while (+currentDate <= endTime) {\n currentDate.setHours(0);\n dates.push((0, _index3.constructFrom)(start, currentDate));\n currentDate = (0, _index2.addWeeks)(currentDate, step);\n currentDate.setHours(15);\n }\n\n return reversed ? dates.reverse() : dates;\n}\n", "\"use strict\";\nexports.eachWeekendOfInterval = eachWeekendOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\nvar _index3 = require(\"./eachDayOfInterval.cjs\");\nvar _index4 = require(\"./isWeekend.cjs\");\n\n/**\n * The {@link eachWeekendOfInterval} function options.\n */\n\n/**\n * The {@link eachWeekendOfInterval} function result type.\n */\n\n/**\n * @name eachWeekendOfInterval\n * @category Interval Helpers\n * @summary List all the Saturdays and Sundays in the given date interval.\n *\n * @description\n * Get all the Saturdays and Sundays in the given date interval.\n *\n * @typeParam IntervalType - Interval type.\n * @typeParam Options - Options type.\n *\n * @param interval - The given interval\n * @param options - An object with options\n *\n * @returns An array containing all the Saturdays and Sundays\n *\n * @example\n * // Lists all Saturdays and Sundays in the given date interval\n * const result = eachWeekendOfInterval({\n * start: new Date(2018, 8, 17),\n * end: new Date(2018, 8, 30)\n * })\n * //=> [\n * // Sat Sep 22 2018 00:00:00,\n * // Sun Sep 23 2018 00:00:00,\n * // Sat Sep 29 2018 00:00:00,\n * // Sun Sep 30 2018 00:00:00\n * // ]\n */\nfunction eachWeekendOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n const dateInterval = (0, _index3.eachDayOfInterval)({ start, end }, options);\n const weekends = [];\n let index = 0;\n while (index < dateInterval.length) {\n const date = dateInterval[index++];\n if ((0, _index4.isWeekend)(date))\n weekends.push((0, _index2.constructFrom)(start, date));\n }\n return weekends;\n}\n", "\"use strict\";\nexports.startOfMonth = startOfMonth;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfMonth} function options.\n */\n\n/**\n * @name startOfMonth\n * @category Month Helpers\n * @summary Return the start of a month for the given date.\n *\n * @description\n * Return the start of a month for the given date. The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments.\n * Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed,\n * or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of a month\n *\n * @example\n * // The start of a month for 2 September 2014 11:55:00:\n * const result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Mon Sep 01 2014 00:00:00\n */\nfunction startOfMonth(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setDate(1);\n _date.setHours(0, 0, 0, 0);\n return _date;\n}\n", "\"use strict\";\nexports.eachWeekendOfMonth = eachWeekendOfMonth;\nvar _index = require(\"./eachWeekendOfInterval.cjs\");\nvar _index2 = require(\"./endOfMonth.cjs\");\nvar _index3 = require(\"./startOfMonth.cjs\");\n\n/**\n * The {@link eachWeekendOfMonth} function options.\n */\n\n/**\n * @name eachWeekendOfMonth\n * @category Month Helpers\n * @summary List all the Saturdays and Sundays in the given month.\n *\n * @description\n * Get all the Saturdays and Sundays in the given month.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The given month\n * @param options - An object with options\n *\n * @returns An array containing all the Saturdays and Sundays\n *\n * @example\n * // Lists all Saturdays and Sundays in the given month\n * const result = eachWeekendOfMonth(new Date(2022, 1, 1))\n * //=> [\n * // Sat Feb 05 2022 00:00:00,\n * // Sun Feb 06 2022 00:00:00,\n * // Sat Feb 12 2022 00:00:00,\n * // Sun Feb 13 2022 00:00:00,\n * // Sat Feb 19 2022 00:00:00,\n * // Sun Feb 20 2022 00:00:00,\n * // Sat Feb 26 2022 00:00:00,\n * // Sun Feb 27 2022 00:00:00\n * // ]\n */\nfunction eachWeekendOfMonth(date, options) {\n const start = (0, _index3.startOfMonth)(date, options);\n const end = (0, _index2.endOfMonth)(date, options);\n return (0, _index.eachWeekendOfInterval)({ start, end }, options);\n}\n", "\"use strict\";\nexports.endOfYear = endOfYear;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfYear} function options.\n */\n\n/**\n * @name endOfYear\n * @category Year Helpers\n * @summary Return the end of a year for the given date.\n *\n * @description\n * Return the end of a year for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The end of a year\n *\n * @example\n * // The end of a year for 2 September 2014 11:55:00:\n * const result = endOfYear(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Wed Dec 31 2014 23:59:59.999\n */\nfunction endOfYear(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const year = _date.getFullYear();\n _date.setFullYear(year + 1, 0, 0);\n _date.setHours(23, 59, 59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.startOfYear = startOfYear;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfYear} function options.\n */\n\n/**\n * @name startOfYear\n * @category Year Helpers\n * @summary Return the start of a year for the given date.\n *\n * @description\n * Return the start of a year for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The start of a year\n *\n * @example\n * // The start of a year for 2 September 2014 11:55:00:\n * const result = startOfYear(new Date(2014, 8, 2, 11, 55, 00))\n * //=> Wed Jan 01 2014 00:00:00\n */\nfunction startOfYear(date, options) {\n const date_ = (0, _index.toDate)(date, options?.in);\n date_.setFullYear(date_.getFullYear(), 0, 1);\n date_.setHours(0, 0, 0, 0);\n return date_;\n}\n", "\"use strict\";\nexports.eachWeekendOfYear = eachWeekendOfYear;\nvar _index = require(\"./eachWeekendOfInterval.cjs\");\nvar _index2 = require(\"./endOfYear.cjs\");\nvar _index3 = require(\"./startOfYear.cjs\");\n\n/**\n * The {@link eachWeekendOfYear} function options.\n */\n\n/**\n * @name eachWeekendOfYear\n * @category Year Helpers\n * @summary List all the Saturdays and Sundays in the year.\n *\n * @description\n * Get all the Saturdays and Sundays in the year.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The given year\n * @param options - An object with options\n *\n * @returns An array containing all the Saturdays and Sundays\n *\n * @example\n * // Lists all Saturdays and Sundays in the year\n * const result = eachWeekendOfYear(new Date(2020, 1, 1))\n * //=> [\n * // Sat Jan 03 2020 00:00:00,\n * // Sun Jan 04 2020 00:00:00,\n * // ...\n * // Sun Dec 27 2020 00:00:00\n * // ]\n * ]\n */\nfunction eachWeekendOfYear(date, options) {\n const start = (0, _index3.startOfYear)(date, options);\n const end = (0, _index2.endOfYear)(date, options);\n return (0, _index.eachWeekendOfInterval)({ start, end }, options);\n}\n", "\"use strict\";\nexports.eachYearOfInterval = eachYearOfInterval;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\n\n/**\n * The {@link eachYearOfInterval} function options.\n */\n\n/**\n * The {@link eachYearOfInterval} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the date argument,\n * then the start interval date, and finally the end interval date. If\n * a context function is passed, it uses the context function return type.\n */\n\n/**\n * @name eachYearOfInterval\n * @category Interval Helpers\n * @summary Return the array of yearly timestamps within the specified time interval.\n *\n * @description\n * Return the array of yearly timestamps within the specified time interval.\n *\n * @typeParam IntervalType - Interval type.\n * @typeParam Options - Options type.\n *\n * @param interval - The interval.\n * @param options - An object with options.\n *\n * @returns The array with starts of yearly timestamps from the month of the interval start to the month of the interval end\n *\n * @example\n * // Each year between 6 February 2014 and 10 August 2017:\n * const result = eachYearOfInterval({\n * start: new Date(2014, 1, 6),\n * end: new Date(2017, 7, 10)\n * })\n * //=> [\n * // Wed Jan 01 2014 00:00:00,\n * // Thu Jan 01 2015 00:00:00,\n * // Fri Jan 01 2016 00:00:00,\n * // Sun Jan 01 2017 00:00:00\n * // ]\n */\nfunction eachYearOfInterval(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n\n let reversed = +start > +end;\n const endTime = reversed ? +start : +end;\n const date = reversed ? end : start;\n date.setHours(0, 0, 0, 0);\n date.setMonth(0, 1);\n\n let step = options?.step ?? 1;\n if (!step) return [];\n if (step < 0) {\n step = -step;\n reversed = !reversed;\n }\n\n const dates = [];\n\n while (+date <= endTime) {\n dates.push((0, _index2.constructFrom)(start, date));\n date.setFullYear(date.getFullYear() + step);\n }\n\n return reversed ? dates.reverse() : dates;\n}\n", "\"use strict\";\nexports.endOfDecade = endOfDecade;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfDecade} function options.\n */\n\n/**\n * @name endOfDecade\n * @category Decade Helpers\n * @summary Return the end of a decade for the given date.\n *\n * @description\n * Return the end of a decade for the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a decade\n *\n * @example\n * // The end of a decade for 12 May 1984 00:00:00:\n * const result = endOfDecade(new Date(1984, 4, 12, 00, 00, 00))\n * //=> Dec 31 1989 23:59:59.999\n */\nfunction endOfDecade(date, options) {\n // TODO: Switch to more technical definition in of decades that start with 1\n // end with 0. I.e. 2001-2010 instead of current 2000-2009. It's a breaking\n // change, so it can only be done in 4.0.\n const _date = (0, _index.toDate)(date, options?.in);\n const year = _date.getFullYear();\n const decade = 9 + Math.floor(year / 10) * 10;\n _date.setFullYear(decade, 11, 31);\n _date.setHours(23, 59, 59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.endOfHour = endOfHour;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfHour} function options.\n */\n\n/**\n * @name endOfHour\n * @category Hour Helpers\n * @summary Return the end of an hour for the given date.\n *\n * @description\n * Return the end of an hour for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of an hour\n *\n * @example\n * // The end of an hour for 2 September 2014 11:55:00:\n * const result = endOfHour(new Date(2014, 8, 2, 11, 55))\n * //=> Tue Sep 02 2014 11:59:59.999\n */\nfunction endOfHour(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setMinutes(59, 59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.endOfWeek = endOfWeek;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfWeek} function options.\n */\n\n/**\n * @name endOfWeek\n * @category Week Helpers\n * @summary Return the end of a week for the given date.\n *\n * @description\n * Return the end of a week for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a week\n *\n * @example\n * // The end of a week for 2 September 2014 11:55:00:\n * const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Sat Sep 06 2014 23:59:59.999\n *\n * @example\n * // If the week starts on Monday, the end of the week for 2 September 2014 11:55:00:\n * const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })\n * //=> Sun Sep 07 2014 23:59:59.999\n */\nfunction endOfWeek(date, options) {\n const defaultOptions = (0, _index.getDefaultOptions)();\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const _date = (0, _index2.toDate)(date, options?.in);\n const day = _date.getDay();\n const diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);\n\n _date.setDate(_date.getDate() + diff);\n _date.setHours(23, 59, 59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.endOfISOWeek = endOfISOWeek;\nvar _index = require(\"./endOfWeek.cjs\");\n\n/**\n * The {@link endOfISOWeek} function options.\n */\n\n/**\n * @name endOfISOWeek\n * @category ISO Week Helpers\n * @summary Return the end of an ISO week for the given date.\n *\n * @description\n * Return the end of an ISO week for the given date.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of an ISO week\n *\n * @example\n * // The end of an ISO week for 2 September 2014 11:55:00:\n * const result = endOfISOWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Sun Sep 07 2014 23:59:59.999\n */\nfunction endOfISOWeek(date, options) {\n return (0, _index.endOfWeek)(date, { ...options, weekStartsOn: 1 });\n}\n", "\"use strict\";\nexports.endOfISOWeekYear = endOfISOWeekYear;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./getISOWeekYear.cjs\");\nvar _index3 = require(\"./startOfISOWeek.cjs\");\n\n/**\n * The {@link endOfISOWeekYear} function options.\n */\n\n/**\n * @name endOfISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Return the end of an ISO week-numbering year for the given date.\n *\n * @description\n * Return the end of an ISO week-numbering year,\n * which always starts 3 days before the year's first Thursday.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ContextDate - The `Date` type of the context function.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The end of an ISO week-numbering year\n *\n * @example\n * // The end of an ISO week-numbering year for 2 July 2005:\n * const result = endOfISOWeekYear(new Date(2005, 6, 2))\n * //=> Sun Jan 01 2006 23:59:59.999\n */\nfunction endOfISOWeekYear(date, options) {\n const year = (0, _index2.getISOWeekYear)(date, options);\n const fourthOfJanuaryOfNextYear = (0, _index.constructFrom)(\n options?.in || date,\n 0,\n );\n fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);\n fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);\n const _date = (0, _index3.startOfISOWeek)(fourthOfJanuaryOfNextYear, options);\n _date.setMilliseconds(_date.getMilliseconds() - 1);\n return _date;\n}\n", "\"use strict\";\nexports.endOfMinute = endOfMinute;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfMinute} function options.\n */\n\n/**\n * @name endOfMinute\n * @category Minute Helpers\n * @summary Return the end of a minute for the given date.\n *\n * @description\n * Return the end of a minute for the given date.\n * The result will be in the local timezone or the provided context.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a minute\n *\n * @example\n * // The end of a minute for 1 December 2014 22:15:45.400:\n * const result = endOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400))\n * //=> Mon Dec 01 2014 22:15:59.999\n */\nfunction endOfMinute(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setSeconds(59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.endOfQuarter = endOfQuarter;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfQuarter} function options.\n */\n\n/**\n * @name endOfQuarter\n * @category Quarter Helpers\n * @summary Return the end of a year quarter for the given date.\n *\n * @description\n * Return the end of a year quarter for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a quarter\n *\n * @example\n * // The end of a quarter for 2 September 2014 11:55:00:\n * const result = endOfQuarter(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 30 2014 23:59:59.999\n */\nfunction endOfQuarter(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const currentMonth = _date.getMonth();\n const month = currentMonth - (currentMonth % 3) + 3;\n _date.setMonth(month, 0);\n _date.setHours(23, 59, 59, 999);\n return _date;\n}\n", "\"use strict\";\nexports.endOfSecond = endOfSecond;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link endOfSecond} function options.\n */\n\n/**\n * @name endOfSecond\n * @category Second Helpers\n * @summary Return the end of a second for the given date.\n *\n * @description\n * Return the end of a second for the given date.\n * The result will be in the local timezone if no `in` option is specified.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of a second\n *\n * @example\n * // The end of a second for 1 December 2014 22:15:45.400:\n * const result = endOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400))\n * //=> Mon Dec 01 2014 22:15:45.999\n */\nfunction endOfSecond(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setMilliseconds(999);\n return _date;\n}\n", "\"use strict\";\nexports.endOfToday = endOfToday;\nvar _index = require(\"./endOfDay.cjs\");\n\n/**\n * The {@link endOfToday} function options.\n */\n\n/**\n * @name endOfToday\n * @category Day Helpers\n * @summary Return the end of today.\n * @pure false\n *\n * @description\n * Return the end of today.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param options - The options\n *\n * @returns The end of today\n *\n * @example\n * // If today is 6 October 2014:\n * const result = endOfToday()\n * //=> Mon Oct 6 2014 23:59:59.999\n */\nfunction endOfToday(options) {\n return (0, _index.endOfDay)(Date.now(), options);\n}\n", "\"use strict\";\nexports.endOfTomorrow = endOfTomorrow;\nvar _index = require(\"./constructNow.cjs\");\n\n/**\n * The {@link endOfTomorrow} function options.\n */\n\n/**\n * @name endOfTomorrow\n * @category Day Helpers\n * @summary Return the end of tomorrow.\n * @pure false\n *\n * @description\n * Return the end of tomorrow.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param options - The options\n * @returns The end of tomorrow\n *\n * @example\n * // If today is 6 October 2014:\n * const result = endOfTomorrow()\n * //=> Tue Oct 7 2014 23:59:59.999\n */\nfunction endOfTomorrow(options) {\n const now = (0, _index.constructNow)(options?.in);\n const year = now.getFullYear();\n const month = now.getMonth();\n const day = now.getDate();\n\n const date = (0, _index.constructNow)(options?.in);\n date.setFullYear(year, month, day + 1);\n date.setHours(23, 59, 59, 999);\n return options?.in ? options.in(date) : date;\n}\n", "\"use strict\";\nexports.endOfYesterday = endOfYesterday;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\n\n/**\n * The {@link endOfYesterday} function options.\n */\n\n/**\n * @name endOfYesterday\n * @category Day Helpers\n * @summary Return the end of yesterday.\n * @pure false\n *\n * @description\n * Return the end of yesterday.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @returns The end of yesterday\n *\n * @example\n * // If today is 6 October 2014:\n * const result = endOfYesterday()\n * //=> Sun Oct 5 2014 23:59:59.999\n */\nfunction endOfYesterday(options) {\n const now = (0, _index2.constructNow)(options?.in);\n const date = (0, _index.constructFrom)(options?.in, 0);\n date.setFullYear(now.getFullYear(), now.getMonth(), now.getDate() - 1);\n date.setHours(23, 59, 59, 999);\n return date;\n}\n", "\"use strict\";\nexports.formatDistance = void 0;\n\nconst formatDistanceLocale = {\n lessThanXSeconds: {\n one: \"less than a second\",\n other: \"less than {{count}} seconds\",\n },\n\n xSeconds: {\n one: \"1 second\",\n other: \"{{count}} seconds\",\n },\n\n halfAMinute: \"half a minute\",\n\n lessThanXMinutes: {\n one: \"less than a minute\",\n other: \"less than {{count}} minutes\",\n },\n\n xMinutes: {\n one: \"1 minute\",\n other: \"{{count}} minutes\",\n },\n\n aboutXHours: {\n one: \"about 1 hour\",\n other: \"about {{count}} hours\",\n },\n\n xHours: {\n one: \"1 hour\",\n other: \"{{count}} hours\",\n },\n\n xDays: {\n one: \"1 day\",\n other: \"{{count}} days\",\n },\n\n aboutXWeeks: {\n one: \"about 1 week\",\n other: \"about {{count}} weeks\",\n },\n\n xWeeks: {\n one: \"1 week\",\n other: \"{{count}} weeks\",\n },\n\n aboutXMonths: {\n one: \"about 1 month\",\n other: \"about {{count}} months\",\n },\n\n xMonths: {\n one: \"1 month\",\n other: \"{{count}} months\",\n },\n\n aboutXYears: {\n one: \"about 1 year\",\n other: \"about {{count}} years\",\n },\n\n xYears: {\n one: \"1 year\",\n other: \"{{count}} years\",\n },\n\n overXYears: {\n one: \"over 1 year\",\n other: \"over {{count}} years\",\n },\n\n almostXYears: {\n one: \"almost 1 year\",\n other: \"almost {{count}} years\",\n },\n};\n\nconst formatDistance = (token, count, options) => {\n let result;\n\n const tokenValue = formatDistanceLocale[token];\n if (typeof tokenValue === \"string\") {\n result = tokenValue;\n } else if (count === 1) {\n result = tokenValue.one;\n } else {\n result = tokenValue.other.replace(\"{{count}}\", count.toString());\n }\n\n if (options?.addSuffix) {\n if (options.comparison && options.comparison > 0) {\n return \"in \" + result;\n } else {\n return result + \" ago\";\n }\n }\n\n return result;\n};\nexports.formatDistance = formatDistance;\n", "\"use strict\";\nexports.buildFormatLongFn = buildFormatLongFn;\n\nfunction buildFormatLongFn(args) {\n return (options = {}) => {\n // TODO: Remove String()\n const width = options.width ? String(options.width) : args.defaultWidth;\n const format = args.formats[width] || args.formats[args.defaultWidth];\n return format;\n };\n}\n", "\"use strict\";\nexports.formatLong = void 0;\nvar _index = require(\"../../_lib/buildFormatLongFn.cjs\");\n\nconst dateFormats = {\n full: \"EEEE, MMMM do, y\",\n long: \"MMMM do, y\",\n medium: \"MMM d, y\",\n short: \"MM/dd/yyyy\",\n};\n\nconst timeFormats = {\n full: \"h:mm:ss a zzzz\",\n long: \"h:mm:ss a z\",\n medium: \"h:mm:ss a\",\n short: \"h:mm a\",\n};\n\nconst dateTimeFormats = {\n full: \"{{date}} 'at' {{time}}\",\n long: \"{{date}} 'at' {{time}}\",\n medium: \"{{date}}, {{time}}\",\n short: \"{{date}}, {{time}}\",\n};\n\nconst formatLong = (exports.formatLong = {\n date: (0, _index.buildFormatLongFn)({\n formats: dateFormats,\n defaultWidth: \"full\",\n }),\n\n time: (0, _index.buildFormatLongFn)({\n formats: timeFormats,\n defaultWidth: \"full\",\n }),\n\n dateTime: (0, _index.buildFormatLongFn)({\n formats: dateTimeFormats,\n defaultWidth: \"full\",\n }),\n});\n", "\"use strict\";\nexports.formatRelative = void 0;\n\nconst formatRelativeLocale = {\n lastWeek: \"'last' eeee 'at' p\",\n yesterday: \"'yesterday at' p\",\n today: \"'today at' p\",\n tomorrow: \"'tomorrow at' p\",\n nextWeek: \"eeee 'at' p\",\n other: \"P\",\n};\n\nconst formatRelative = (token, _date, _baseDate, _options) =>\n formatRelativeLocale[token];\nexports.formatRelative = formatRelative;\n", "\"use strict\";\nexports.buildLocalizeFn = buildLocalizeFn;\n\n/**\n * The localize function argument callback which allows to convert raw value to\n * the actual type.\n *\n * @param value - The value to convert\n *\n * @returns The converted value\n */\n\n/**\n * The map of localized values for each width.\n */\n\n/**\n * The index type of the locale unit value. It types conversion of units of\n * values that don't start at 0 (i.e. quarters).\n */\n\n/**\n * Converts the unit value to the tuple of values.\n */\n\n/**\n * The tuple of localized era values. The first element represents BC,\n * the second element represents AD.\n */\n\n/**\n * The tuple of localized quarter values. The first element represents Q1.\n */\n\n/**\n * The tuple of localized day values. The first element represents Sunday.\n */\n\n/**\n * The tuple of localized month values. The first element represents January.\n */\n\nfunction buildLocalizeFn(args) {\n return (value, options) => {\n const context = options?.context ? String(options.context) : \"standalone\";\n\n let valuesArray;\n if (context === \"formatting\" && args.formattingValues) {\n const defaultWidth = args.defaultFormattingWidth || args.defaultWidth;\n const width = options?.width ? String(options.width) : defaultWidth;\n\n valuesArray =\n args.formattingValues[width] || args.formattingValues[defaultWidth];\n } else {\n const defaultWidth = args.defaultWidth;\n const width = options?.width ? String(options.width) : args.defaultWidth;\n\n valuesArray = args.values[width] || args.values[defaultWidth];\n }\n const index = args.argumentCallback ? args.argumentCallback(value) : value;\n\n // @ts-expect-error - For some reason TypeScript just don't want to match it, no matter how hard we try. I challenge you to try to remove it!\n return valuesArray[index];\n };\n}\n", "\"use strict\";\nexports.localize = void 0;\nvar _index = require(\"../../_lib/buildLocalizeFn.cjs\");\n\nconst eraValues = {\n narrow: [\"B\", \"A\"],\n abbreviated: [\"BC\", \"AD\"],\n wide: [\"Before Christ\", \"Anno Domini\"],\n};\n\nconst quarterValues = {\n narrow: [\"1\", \"2\", \"3\", \"4\"],\n abbreviated: [\"Q1\", \"Q2\", \"Q3\", \"Q4\"],\n wide: [\"1st quarter\", \"2nd quarter\", \"3rd quarter\", \"4th quarter\"],\n};\n\n// Note: in English, the names of days of the week and months are capitalized.\n// If you are making a new locale based on this one, check if the same is true for the language you're working on.\n// Generally, formatted dates should look like they are in the middle of a sentence,\n// e.g. in Spanish language the weekdays and months should be in the lowercase.\nconst monthValues = {\n narrow: [\"J\", \"F\", \"M\", \"A\", \"M\", \"J\", \"J\", \"A\", \"S\", \"O\", \"N\", \"D\"],\n abbreviated: [\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n ],\n\n wide: [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n ],\n};\n\nconst dayValues = {\n narrow: [\"S\", \"M\", \"T\", \"W\", \"T\", \"F\", \"S\"],\n short: [\"Su\", \"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\"],\n abbreviated: [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"],\n wide: [\n \"Sunday\",\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\",\n ],\n};\n\nconst dayPeriodValues = {\n narrow: {\n am: \"a\",\n pm: \"p\",\n midnight: \"mi\",\n noon: \"n\",\n morning: \"morning\",\n afternoon: \"afternoon\",\n evening: \"evening\",\n night: \"night\",\n },\n abbreviated: {\n am: \"AM\",\n pm: \"PM\",\n midnight: \"midnight\",\n noon: \"noon\",\n morning: \"morning\",\n afternoon: \"afternoon\",\n evening: \"evening\",\n night: \"night\",\n },\n wide: {\n am: \"a.m.\",\n pm: \"p.m.\",\n midnight: \"midnight\",\n noon: \"noon\",\n morning: \"morning\",\n afternoon: \"afternoon\",\n evening: \"evening\",\n night: \"night\",\n },\n};\n\nconst formattingDayPeriodValues = {\n narrow: {\n am: \"a\",\n pm: \"p\",\n midnight: \"mi\",\n noon: \"n\",\n morning: \"in the morning\",\n afternoon: \"in the afternoon\",\n evening: \"in the evening\",\n night: \"at night\",\n },\n abbreviated: {\n am: \"AM\",\n pm: \"PM\",\n midnight: \"midnight\",\n noon: \"noon\",\n morning: \"in the morning\",\n afternoon: \"in the afternoon\",\n evening: \"in the evening\",\n night: \"at night\",\n },\n wide: {\n am: \"a.m.\",\n pm: \"p.m.\",\n midnight: \"midnight\",\n noon: \"noon\",\n morning: \"in the morning\",\n afternoon: \"in the afternoon\",\n evening: \"in the evening\",\n night: \"at night\",\n },\n};\n\nconst ordinalNumber = (dirtyNumber, _options) => {\n const number = Number(dirtyNumber);\n\n // If ordinal numbers depend on context, for example,\n // if they are different for different grammatical genders,\n // use `options.unit`.\n //\n // `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear',\n // 'day', 'hour', 'minute', 'second'.\n\n const rem100 = number % 100;\n if (rem100 > 20 || rem100 < 10) {\n switch (rem100 % 10) {\n case 1:\n return number + \"st\";\n case 2:\n return number + \"nd\";\n case 3:\n return number + \"rd\";\n }\n }\n return number + \"th\";\n};\n\nconst localize = (exports.localize = {\n ordinalNumber,\n\n era: (0, _index.buildLocalizeFn)({\n values: eraValues,\n defaultWidth: \"wide\",\n }),\n\n quarter: (0, _index.buildLocalizeFn)({\n values: quarterValues,\n defaultWidth: \"wide\",\n argumentCallback: (quarter) => quarter - 1,\n }),\n\n month: (0, _index.buildLocalizeFn)({\n values: monthValues,\n defaultWidth: \"wide\",\n }),\n\n day: (0, _index.buildLocalizeFn)({\n values: dayValues,\n defaultWidth: \"wide\",\n }),\n\n dayPeriod: (0, _index.buildLocalizeFn)({\n values: dayPeriodValues,\n defaultWidth: \"wide\",\n formattingValues: formattingDayPeriodValues,\n defaultFormattingWidth: \"wide\",\n }),\n});\n", "\"use strict\";\nexports.buildMatchFn = buildMatchFn;\n\nfunction buildMatchFn(args) {\n return (string, options = {}) => {\n const width = options.width;\n\n const matchPattern =\n (width && args.matchPatterns[width]) ||\n args.matchPatterns[args.defaultMatchWidth];\n const matchResult = string.match(matchPattern);\n\n if (!matchResult) {\n return null;\n }\n const matchedString = matchResult[0];\n\n const parsePatterns =\n (width && args.parsePatterns[width]) ||\n args.parsePatterns[args.defaultParseWidth];\n\n const key = Array.isArray(parsePatterns)\n ? findIndex(parsePatterns, (pattern) => pattern.test(matchedString))\n : // [TODO] -- I challenge you to fix the type\n findKey(parsePatterns, (pattern) => pattern.test(matchedString));\n\n let value;\n\n value = args.valueCallback ? args.valueCallback(key) : key;\n value = options.valueCallback\n ? // [TODO] -- I challenge you to fix the type\n options.valueCallback(value)\n : value;\n\n const rest = string.slice(matchedString.length);\n\n return { value, rest };\n };\n}\n\nfunction findKey(object, predicate) {\n for (const key in object) {\n if (\n Object.prototype.hasOwnProperty.call(object, key) &&\n predicate(object[key])\n ) {\n return key;\n }\n }\n return undefined;\n}\n\nfunction findIndex(array, predicate) {\n for (let key = 0; key < array.length; key++) {\n if (predicate(array[key])) {\n return key;\n }\n }\n return undefined;\n}\n", "\"use strict\";\nexports.buildMatchPatternFn = buildMatchPatternFn;\n\nfunction buildMatchPatternFn(args) {\n return (string, options = {}) => {\n const matchResult = string.match(args.matchPattern);\n if (!matchResult) return null;\n const matchedString = matchResult[0];\n\n const parseResult = string.match(args.parsePattern);\n if (!parseResult) return null;\n let value = args.valueCallback\n ? args.valueCallback(parseResult[0])\n : parseResult[0];\n\n // [TODO] I challenge you to fix the type\n value = options.valueCallback ? options.valueCallback(value) : value;\n\n const rest = string.slice(matchedString.length);\n\n return { value, rest };\n };\n}\n", "\"use strict\";\nexports.match = void 0;\n\nvar _index = require(\"../../_lib/buildMatchFn.cjs\");\nvar _index2 = require(\"../../_lib/buildMatchPatternFn.cjs\");\n\nconst matchOrdinalNumberPattern = /^(\\d+)(th|st|nd|rd)?/i;\nconst parseOrdinalNumberPattern = /\\d+/i;\n\nconst matchEraPatterns = {\n narrow: /^(b|a)/i,\n abbreviated: /^(b\\.?\\s?c\\.?|b\\.?\\s?c\\.?\\s?e\\.?|a\\.?\\s?d\\.?|c\\.?\\s?e\\.?)/i,\n wide: /^(before christ|before common era|anno domini|common era)/i,\n};\nconst parseEraPatterns = {\n any: [/^b/i, /^(a|c)/i],\n};\n\nconst matchQuarterPatterns = {\n narrow: /^[1234]/i,\n abbreviated: /^q[1234]/i,\n wide: /^[1234](th|st|nd|rd)? quarter/i,\n};\nconst parseQuarterPatterns = {\n any: [/1/i, /2/i, /3/i, /4/i],\n};\n\nconst matchMonthPatterns = {\n narrow: /^[jfmasond]/i,\n abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,\n wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i,\n};\nconst parseMonthPatterns = {\n narrow: [\n /^j/i,\n /^f/i,\n /^m/i,\n /^a/i,\n /^m/i,\n /^j/i,\n /^j/i,\n /^a/i,\n /^s/i,\n /^o/i,\n /^n/i,\n /^d/i,\n ],\n\n any: [\n /^ja/i,\n /^f/i,\n /^mar/i,\n /^ap/i,\n /^may/i,\n /^jun/i,\n /^jul/i,\n /^au/i,\n /^s/i,\n /^o/i,\n /^n/i,\n /^d/i,\n ],\n};\n\nconst matchDayPatterns = {\n narrow: /^[smtwf]/i,\n short: /^(su|mo|tu|we|th|fr|sa)/i,\n abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,\n wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i,\n};\nconst parseDayPatterns = {\n narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],\n any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i],\n};\n\nconst matchDayPeriodPatterns = {\n narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,\n any: /^([ap]\\.?\\s?m\\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i,\n};\nconst parseDayPeriodPatterns = {\n any: {\n am: /^a/i,\n pm: /^p/i,\n midnight: /^mi/i,\n noon: /^no/i,\n morning: /morning/i,\n afternoon: /afternoon/i,\n evening: /evening/i,\n night: /night/i,\n },\n};\n\nconst match = (exports.match = {\n ordinalNumber: (0, _index2.buildMatchPatternFn)({\n matchPattern: matchOrdinalNumberPattern,\n parsePattern: parseOrdinalNumberPattern,\n valueCallback: (value) => parseInt(value, 10),\n }),\n\n era: (0, _index.buildMatchFn)({\n matchPatterns: matchEraPatterns,\n defaultMatchWidth: \"wide\",\n parsePatterns: parseEraPatterns,\n defaultParseWidth: \"any\",\n }),\n\n quarter: (0, _index.buildMatchFn)({\n matchPatterns: matchQuarterPatterns,\n defaultMatchWidth: \"wide\",\n parsePatterns: parseQuarterPatterns,\n defaultParseWidth: \"any\",\n valueCallback: (index) => index + 1,\n }),\n\n month: (0, _index.buildMatchFn)({\n matchPatterns: matchMonthPatterns,\n defaultMatchWidth: \"wide\",\n parsePatterns: parseMonthPatterns,\n defaultParseWidth: \"any\",\n }),\n\n day: (0, _index.buildMatchFn)({\n matchPatterns: matchDayPatterns,\n defaultMatchWidth: \"wide\",\n parsePatterns: parseDayPatterns,\n defaultParseWidth: \"any\",\n }),\n\n dayPeriod: (0, _index.buildMatchFn)({\n matchPatterns: matchDayPeriodPatterns,\n defaultMatchWidth: \"any\",\n parsePatterns: parseDayPeriodPatterns,\n defaultParseWidth: \"any\",\n }),\n});\n", "\"use strict\";\nexports.enUS = void 0;\nvar _index = require(\"./en-US/_lib/formatDistance.cjs\");\nvar _index2 = require(\"./en-US/_lib/formatLong.cjs\");\nvar _index3 = require(\"./en-US/_lib/formatRelative.cjs\");\nvar _index4 = require(\"./en-US/_lib/localize.cjs\");\nvar _index5 = require(\"./en-US/_lib/match.cjs\");\n\n/**\n * @category Locales\n * @summary English locale (United States).\n * @language English\n * @iso-639-2 eng\n * @author Sasha Koss [@kossnocorp](https://github.com/kossnocorp)\n * @author Lesha Koss [@leshakoss](https://github.com/leshakoss)\n */\nconst enUS = (exports.enUS = {\n code: \"en-US\",\n formatDistance: _index.formatDistance,\n formatLong: _index2.formatLong,\n formatRelative: _index3.formatRelative,\n localize: _index4.localize,\n match: _index5.match,\n options: {\n weekStartsOn: 0 /* Sunday */,\n firstWeekContainsDate: 1,\n },\n});\n", "\"use strict\";\nObject.defineProperty(exports, \"defaultLocale\", {\n enumerable: true,\n get: function () {\n return _index.enUS;\n },\n});\nvar _index = require(\"../locale/en-US.cjs\");\n", "\"use strict\";\nexports.getDayOfYear = getDayOfYear;\nvar _index = require(\"./differenceInCalendarDays.cjs\");\nvar _index2 = require(\"./startOfYear.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getDayOfYear} function options.\n */\n\n/**\n * @name getDayOfYear\n * @category Day Helpers\n * @summary Get the day of the year of the given date.\n *\n * @description\n * Get the day of the year of the given date.\n *\n * @param date - The given date\n * @param options - The options\n *\n * @returns The day of year\n *\n * @example\n * // Which day of the year is 2 July 2014?\n * const result = getDayOfYear(new Date(2014, 6, 2))\n * //=> 183\n */\nfunction getDayOfYear(date, options) {\n const _date = (0, _index3.toDate)(date, options?.in);\n const diff = (0, _index.differenceInCalendarDays)(\n _date,\n (0, _index2.startOfYear)(_date),\n );\n const dayOfYear = diff + 1;\n return dayOfYear;\n}\n", "\"use strict\";\nexports.getISOWeek = getISOWeek;\nvar _index = require(\"./constants.cjs\");\nvar _index2 = require(\"./startOfISOWeek.cjs\");\nvar _index3 = require(\"./startOfISOWeekYear.cjs\");\nvar _index4 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getISOWeek} function options.\n */\n\n/**\n * @name getISOWeek\n * @category ISO Week Helpers\n * @summary Get the ISO week of the given date.\n *\n * @description\n * Get the ISO week of the given date.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param date - The given date\n * @param options - The options\n *\n * @returns The ISO week\n *\n * @example\n * // Which week of the ISO-week numbering year is 2 January 2005?\n * const result = getISOWeek(new Date(2005, 0, 2))\n * //=> 53\n */\nfunction getISOWeek(date, options) {\n const _date = (0, _index4.toDate)(date, options?.in);\n const diff =\n +(0, _index2.startOfISOWeek)(_date) -\n +(0, _index3.startOfISOWeekYear)(_date);\n\n // Round the number of weeks to the nearest integer because the number of\n // milliseconds in a week is not constant (e.g. it's different in the week of\n // the daylight saving time clock shift).\n return Math.round(diff / _index.millisecondsInWeek) + 1;\n}\n", "\"use strict\";\nexports.getWeekYear = getWeekYear;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\nvar _index3 = require(\"./startOfWeek.cjs\");\nvar _index4 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getWeekYear} function options.\n */\n\n/**\n * @name getWeekYear\n * @category Week-Numbering Year Helpers\n * @summary Get the local week-numbering year of the given date.\n *\n * @description\n * Get the local week-numbering year of the given date.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system\n *\n * @param date - The given date\n * @param options - An object with options.\n *\n * @returns The local week-numbering year\n *\n * @example\n * // Which week numbering year is 26 December 2004 with the default settings?\n * const result = getWeekYear(new Date(2004, 11, 26))\n * //=> 2005\n *\n * @example\n * // Which week numbering year is 26 December 2004 if week starts on Saturday?\n * const result = getWeekYear(new Date(2004, 11, 26), { weekStartsOn: 6 })\n * //=> 2004\n *\n * @example\n * // Which week numbering year is 26 December 2004 if the first week contains 4 January?\n * const result = getWeekYear(new Date(2004, 11, 26), { firstWeekContainsDate: 4 })\n * //=> 2004\n */\nfunction getWeekYear(date, options) {\n const _date = (0, _index4.toDate)(date, options?.in);\n const year = _date.getFullYear();\n\n const defaultOptions = (0, _index.getDefaultOptions)();\n const firstWeekContainsDate =\n options?.firstWeekContainsDate ??\n options?.locale?.options?.firstWeekContainsDate ??\n defaultOptions.firstWeekContainsDate ??\n defaultOptions.locale?.options?.firstWeekContainsDate ??\n 1;\n\n const firstWeekOfNextYear = (0, _index2.constructFrom)(\n options?.in || date,\n 0,\n );\n firstWeekOfNextYear.setFullYear(year + 1, 0, firstWeekContainsDate);\n firstWeekOfNextYear.setHours(0, 0, 0, 0);\n const startOfNextYear = (0, _index3.startOfWeek)(\n firstWeekOfNextYear,\n options,\n );\n\n const firstWeekOfThisYear = (0, _index2.constructFrom)(\n options?.in || date,\n 0,\n );\n firstWeekOfThisYear.setFullYear(year, 0, firstWeekContainsDate);\n firstWeekOfThisYear.setHours(0, 0, 0, 0);\n const startOfThisYear = (0, _index3.startOfWeek)(\n firstWeekOfThisYear,\n options,\n );\n\n if (+_date >= +startOfNextYear) {\n return year + 1;\n } else if (+_date >= +startOfThisYear) {\n return year;\n } else {\n return year - 1;\n }\n}\n", "\"use strict\";\nexports.startOfWeekYear = startOfWeekYear;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\nvar _index3 = require(\"./getWeekYear.cjs\");\nvar _index4 = require(\"./startOfWeek.cjs\");\n\n/**\n * The {@link startOfWeekYear} function options.\n */\n\n/**\n * @name startOfWeekYear\n * @category Week-Numbering Year Helpers\n * @summary Return the start of a local week-numbering year for the given date.\n *\n * @description\n * Return the start of a local week-numbering year.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of a week-numbering year\n *\n * @example\n * // The start of an a week-numbering year for 2 July 2005 with default settings:\n * const result = startOfWeekYear(new Date(2005, 6, 2))\n * //=> Sun Dec 26 2004 00:00:00\n *\n * @example\n * // The start of a week-numbering year for 2 July 2005\n * // if Monday is the first day of week\n * // and 4 January is always in the first week of the year:\n * const result = startOfWeekYear(new Date(2005, 6, 2), {\n * weekStartsOn: 1,\n * firstWeekContainsDate: 4\n * })\n * //=> Mon Jan 03 2005 00:00:00\n */\nfunction startOfWeekYear(date, options) {\n const defaultOptions = (0, _index.getDefaultOptions)();\n const firstWeekContainsDate =\n options?.firstWeekContainsDate ??\n options?.locale?.options?.firstWeekContainsDate ??\n defaultOptions.firstWeekContainsDate ??\n defaultOptions.locale?.options?.firstWeekContainsDate ??\n 1;\n\n const year = (0, _index3.getWeekYear)(date, options);\n const firstWeek = (0, _index2.constructFrom)(options?.in || date, 0);\n firstWeek.setFullYear(year, 0, firstWeekContainsDate);\n firstWeek.setHours(0, 0, 0, 0);\n const _date = (0, _index4.startOfWeek)(firstWeek, options);\n return _date;\n}\n", "\"use strict\";\nexports.getWeek = getWeek;\nvar _index = require(\"./constants.cjs\");\nvar _index2 = require(\"./startOfWeek.cjs\");\nvar _index3 = require(\"./startOfWeekYear.cjs\");\nvar _index4 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getWeek} function options.\n */\n\n/**\n * @name getWeek\n * @category Week Helpers\n * @summary Get the local week index of the given date.\n *\n * @description\n * Get the local week index of the given date.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The week\n *\n * @example\n * // Which week of the local week numbering year is 2 January 2005 with default options?\n * const result = getWeek(new Date(2005, 0, 2))\n * //=> 2\n *\n * @example\n * // Which week of the local week numbering year is 2 January 2005,\n * // if Monday is the first day of the week,\n * // and the first week of the year always contains 4 January?\n * const result = getWeek(new Date(2005, 0, 2), {\n * weekStartsOn: 1,\n * firstWeekContainsDate: 4\n * })\n * //=> 53\n */\nfunction getWeek(date, options) {\n const _date = (0, _index4.toDate)(date, options?.in);\n const diff =\n +(0, _index2.startOfWeek)(_date, options) -\n +(0, _index3.startOfWeekYear)(_date, options);\n\n // Round the number of weeks to the nearest integer because the number of\n // milliseconds in a week is not constant (e.g. it's different in the week of\n // the daylight saving time clock shift).\n return Math.round(diff / _index.millisecondsInWeek) + 1;\n}\n", "\"use strict\";\nexports.addLeadingZeros = addLeadingZeros;\nfunction addLeadingZeros(number, targetLength) {\n const sign = number < 0 ? \"-\" : \"\";\n const output = Math.abs(number).toString().padStart(targetLength, \"0\");\n return sign + output;\n}\n", "\"use strict\";\nexports.lightFormatters = void 0;\nvar _index = require(\"../addLeadingZeros.cjs\");\n\n/*\n * | | Unit | | Unit |\n * |-----|--------------------------------|-----|--------------------------------|\n * | a | AM, PM | A* | |\n * | d | Day of month | D | |\n * | h | Hour [1-12] | H | Hour [0-23] |\n * | m | Minute | M | Month |\n * | s | Second | S | Fraction of second |\n * | y | Year (abs) | Y | |\n *\n * Letters marked by * are not implemented but reserved by Unicode standard.\n */\n\nconst lightFormatters = (exports.lightFormatters = {\n // Year\n y(date, token) {\n // From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_tokens\n // | Year | y | yy | yyy | yyyy | yyyyy |\n // |----------|-------|----|-------|-------|-------|\n // | AD 1 | 1 | 01 | 001 | 0001 | 00001 |\n // | AD 12 | 12 | 12 | 012 | 0012 | 00012 |\n // | AD 123 | 123 | 23 | 123 | 0123 | 00123 |\n // | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 |\n // | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |\n\n const signedYear = date.getFullYear();\n // Returns 1 for 1 BC (which is year 0 in JavaScript)\n const year = signedYear > 0 ? signedYear : 1 - signedYear;\n return (0, _index.addLeadingZeros)(\n token === \"yy\" ? year % 100 : year,\n token.length,\n );\n },\n\n // Month\n M(date, token) {\n const month = date.getMonth();\n return token === \"M\"\n ? String(month + 1)\n : (0, _index.addLeadingZeros)(month + 1, 2);\n },\n\n // Day of the month\n d(date, token) {\n return (0, _index.addLeadingZeros)(date.getDate(), token.length);\n },\n\n // AM or PM\n a(date, token) {\n const dayPeriodEnumValue = date.getHours() / 12 >= 1 ? \"pm\" : \"am\";\n\n switch (token) {\n case \"a\":\n case \"aa\":\n return dayPeriodEnumValue.toUpperCase();\n case \"aaa\":\n return dayPeriodEnumValue;\n case \"aaaaa\":\n return dayPeriodEnumValue[0];\n case \"aaaa\":\n default:\n return dayPeriodEnumValue === \"am\" ? \"a.m.\" : \"p.m.\";\n }\n },\n\n // Hour [1-12]\n h(date, token) {\n return (0, _index.addLeadingZeros)(\n date.getHours() % 12 || 12,\n token.length,\n );\n },\n\n // Hour [0-23]\n H(date, token) {\n return (0, _index.addLeadingZeros)(date.getHours(), token.length);\n },\n\n // Minute\n m(date, token) {\n return (0, _index.addLeadingZeros)(date.getMinutes(), token.length);\n },\n\n // Second\n s(date, token) {\n return (0, _index.addLeadingZeros)(date.getSeconds(), token.length);\n },\n\n // Fraction of second\n S(date, token) {\n const numberOfDigits = token.length;\n const milliseconds = date.getMilliseconds();\n const fractionalSeconds = Math.trunc(\n milliseconds * Math.pow(10, numberOfDigits - 3),\n );\n return (0, _index.addLeadingZeros)(fractionalSeconds, token.length);\n },\n});\n", "\"use strict\";\nexports.formatters = void 0;\nvar _index = require(\"../../getDayOfYear.cjs\");\nvar _index2 = require(\"../../getISOWeek.cjs\");\nvar _index3 = require(\"../../getISOWeekYear.cjs\");\nvar _index4 = require(\"../../getWeek.cjs\");\nvar _index5 = require(\"../../getWeekYear.cjs\");\n\nvar _index6 = require(\"../addLeadingZeros.cjs\");\nvar _index7 = require(\"./lightFormatters.cjs\");\n\nconst dayPeriodEnum = {\n am: \"am\",\n pm: \"pm\",\n midnight: \"midnight\",\n noon: \"noon\",\n morning: \"morning\",\n afternoon: \"afternoon\",\n evening: \"evening\",\n night: \"night\",\n};\n\n/*\n * | | Unit | | Unit |\n * |-----|--------------------------------|-----|--------------------------------|\n * | a | AM, PM | A* | Milliseconds in day |\n * | b | AM, PM, noon, midnight | B | Flexible day period |\n * | c | Stand-alone local day of week | C* | Localized hour w/ day period |\n * | d | Day of month | D | Day of year |\n * | e | Local day of week | E | Day of week |\n * | f | | F* | Day of week in month |\n * | g* | Modified Julian day | G | Era |\n * | h | Hour [1-12] | H | Hour [0-23] |\n * | i! | ISO day of week | I! | ISO week of year |\n * | j* | Localized hour w/ day period | J* | Localized hour w/o day period |\n * | k | Hour [1-24] | K | Hour [0-11] |\n * | l* | (deprecated) | L | Stand-alone month |\n * | m | Minute | M | Month |\n * | n | | N | |\n * | o! | Ordinal number modifier | O | Timezone (GMT) |\n * | p! | Long localized time | P! | Long localized date |\n * | q | Stand-alone quarter | Q | Quarter |\n * | r* | Related Gregorian year | R! | ISO week-numbering year |\n * | s | Second | S | Fraction of second |\n * | t! | Seconds timestamp | T! | Milliseconds timestamp |\n * | u | Extended year | U* | Cyclic year |\n * | v* | Timezone (generic non-locat.) | V* | Timezone (location) |\n * | w | Local week of year | W* | Week of month |\n * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) |\n * | y | Year (abs) | Y | Local week-numbering year |\n * | z | Timezone (specific non-locat.) | Z* | Timezone (aliases) |\n *\n * Letters marked by * are not implemented but reserved by Unicode standard.\n *\n * Letters marked by ! are non-standard, but implemented by date-fns:\n * - `o` modifies the previous token to turn it into an ordinal (see `format` docs)\n * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,\n * i.e. 7 for Sunday, 1 for Monday, etc.\n * - `I` is ISO week of year, as opposed to `w` which is local week of year.\n * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.\n * `R` is supposed to be used in conjunction with `I` and `i`\n * for universal ISO week-numbering date, whereas\n * `Y` is supposed to be used in conjunction with `w` and `e`\n * for week-numbering date specific to the locale.\n * - `P` is long localized date format\n * - `p` is long localized time format\n */\n\nconst formatters = (exports.formatters = {\n // Era\n G: function (date, token, localize) {\n const era = date.getFullYear() > 0 ? 1 : 0;\n switch (token) {\n // AD, BC\n case \"G\":\n case \"GG\":\n case \"GGG\":\n return localize.era(era, { width: \"abbreviated\" });\n // A, B\n case \"GGGGG\":\n return localize.era(era, { width: \"narrow\" });\n // Anno Domini, Before Christ\n case \"GGGG\":\n default:\n return localize.era(era, { width: \"wide\" });\n }\n },\n\n // Year\n y: function (date, token, localize) {\n // Ordinal number\n if (token === \"yo\") {\n const signedYear = date.getFullYear();\n // Returns 1 for 1 BC (which is year 0 in JavaScript)\n const year = signedYear > 0 ? signedYear : 1 - signedYear;\n return localize.ordinalNumber(year, { unit: \"year\" });\n }\n\n return _index7.lightFormatters.y(date, token);\n },\n\n // Local week-numbering year\n Y: function (date, token, localize, options) {\n const signedWeekYear = (0, _index5.getWeekYear)(date, options);\n // Returns 1 for 1 BC (which is year 0 in JavaScript)\n const weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear;\n\n // Two digit year\n if (token === \"YY\") {\n const twoDigitYear = weekYear % 100;\n return (0, _index6.addLeadingZeros)(twoDigitYear, 2);\n }\n\n // Ordinal number\n if (token === \"Yo\") {\n return localize.ordinalNumber(weekYear, { unit: \"year\" });\n }\n\n // Padding\n return (0, _index6.addLeadingZeros)(weekYear, token.length);\n },\n\n // ISO week-numbering year\n R: function (date, token) {\n const isoWeekYear = (0, _index3.getISOWeekYear)(date);\n\n // Padding\n return (0, _index6.addLeadingZeros)(isoWeekYear, token.length);\n },\n\n // Extended year. This is a single number designating the year of this calendar system.\n // The main difference between `y` and `u` localizers are B.C. years:\n // | Year | `y` | `u` |\n // |------|-----|-----|\n // | AC 1 | 1 | 1 |\n // | BC 1 | 1 | 0 |\n // | BC 2 | 2 | -1 |\n // Also `yy` always returns the last two digits of a year,\n // while `uu` pads single digit years to 2 characters and returns other years unchanged.\n u: function (date, token) {\n const year = date.getFullYear();\n return (0, _index6.addLeadingZeros)(year, token.length);\n },\n\n // Quarter\n Q: function (date, token, localize) {\n const quarter = Math.ceil((date.getMonth() + 1) / 3);\n switch (token) {\n // 1, 2, 3, 4\n case \"Q\":\n return String(quarter);\n // 01, 02, 03, 04\n case \"QQ\":\n return (0, _index6.addLeadingZeros)(quarter, 2);\n // 1st, 2nd, 3rd, 4th\n case \"Qo\":\n return localize.ordinalNumber(quarter, { unit: \"quarter\" });\n // Q1, Q2, Q3, Q4\n case \"QQQ\":\n return localize.quarter(quarter, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n // 1, 2, 3, 4 (narrow quarter; could be not numerical)\n case \"QQQQQ\":\n return localize.quarter(quarter, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // 1st quarter, 2nd quarter, ...\n case \"QQQQ\":\n default:\n return localize.quarter(quarter, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // Stand-alone quarter\n q: function (date, token, localize) {\n const quarter = Math.ceil((date.getMonth() + 1) / 3);\n switch (token) {\n // 1, 2, 3, 4\n case \"q\":\n return String(quarter);\n // 01, 02, 03, 04\n case \"qq\":\n return (0, _index6.addLeadingZeros)(quarter, 2);\n // 1st, 2nd, 3rd, 4th\n case \"qo\":\n return localize.ordinalNumber(quarter, { unit: \"quarter\" });\n // Q1, Q2, Q3, Q4\n case \"qqq\":\n return localize.quarter(quarter, {\n width: \"abbreviated\",\n context: \"standalone\",\n });\n // 1, 2, 3, 4 (narrow quarter; could be not numerical)\n case \"qqqqq\":\n return localize.quarter(quarter, {\n width: \"narrow\",\n context: \"standalone\",\n });\n // 1st quarter, 2nd quarter, ...\n case \"qqqq\":\n default:\n return localize.quarter(quarter, {\n width: \"wide\",\n context: \"standalone\",\n });\n }\n },\n\n // Month\n M: function (date, token, localize) {\n const month = date.getMonth();\n switch (token) {\n case \"M\":\n case \"MM\":\n return _index7.lightFormatters.M(date, token);\n // 1st, 2nd, ..., 12th\n case \"Mo\":\n return localize.ordinalNumber(month + 1, { unit: \"month\" });\n // Jan, Feb, ..., Dec\n case \"MMM\":\n return localize.month(month, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n // J, F, ..., D\n case \"MMMMM\":\n return localize.month(month, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // January, February, ..., December\n case \"MMMM\":\n default:\n return localize.month(month, { width: \"wide\", context: \"formatting\" });\n }\n },\n\n // Stand-alone month\n L: function (date, token, localize) {\n const month = date.getMonth();\n switch (token) {\n // 1, 2, ..., 12\n case \"L\":\n return String(month + 1);\n // 01, 02, ..., 12\n case \"LL\":\n return (0, _index6.addLeadingZeros)(month + 1, 2);\n // 1st, 2nd, ..., 12th\n case \"Lo\":\n return localize.ordinalNumber(month + 1, { unit: \"month\" });\n // Jan, Feb, ..., Dec\n case \"LLL\":\n return localize.month(month, {\n width: \"abbreviated\",\n context: \"standalone\",\n });\n // J, F, ..., D\n case \"LLLLL\":\n return localize.month(month, {\n width: \"narrow\",\n context: \"standalone\",\n });\n // January, February, ..., December\n case \"LLLL\":\n default:\n return localize.month(month, { width: \"wide\", context: \"standalone\" });\n }\n },\n\n // Local week of year\n w: function (date, token, localize, options) {\n const week = (0, _index4.getWeek)(date, options);\n\n if (token === \"wo\") {\n return localize.ordinalNumber(week, { unit: \"week\" });\n }\n\n return (0, _index6.addLeadingZeros)(week, token.length);\n },\n\n // ISO week of year\n I: function (date, token, localize) {\n const isoWeek = (0, _index2.getISOWeek)(date);\n\n if (token === \"Io\") {\n return localize.ordinalNumber(isoWeek, { unit: \"week\" });\n }\n\n return (0, _index6.addLeadingZeros)(isoWeek, token.length);\n },\n\n // Day of the month\n d: function (date, token, localize) {\n if (token === \"do\") {\n return localize.ordinalNumber(date.getDate(), { unit: \"date\" });\n }\n\n return _index7.lightFormatters.d(date, token);\n },\n\n // Day of year\n D: function (date, token, localize) {\n const dayOfYear = (0, _index.getDayOfYear)(date);\n\n if (token === \"Do\") {\n return localize.ordinalNumber(dayOfYear, { unit: \"dayOfYear\" });\n }\n\n return (0, _index6.addLeadingZeros)(dayOfYear, token.length);\n },\n\n // Day of week\n E: function (date, token, localize) {\n const dayOfWeek = date.getDay();\n switch (token) {\n // Tue\n case \"E\":\n case \"EE\":\n case \"EEE\":\n return localize.day(dayOfWeek, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n // T\n case \"EEEEE\":\n return localize.day(dayOfWeek, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // Tu\n case \"EEEEEE\":\n return localize.day(dayOfWeek, {\n width: \"short\",\n context: \"formatting\",\n });\n // Tuesday\n case \"EEEE\":\n default:\n return localize.day(dayOfWeek, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // Local day of week\n e: function (date, token, localize, options) {\n const dayOfWeek = date.getDay();\n const localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;\n switch (token) {\n // Numerical value (Nth day of week with current locale or weekStartsOn)\n case \"e\":\n return String(localDayOfWeek);\n // Padded numerical value\n case \"ee\":\n return (0, _index6.addLeadingZeros)(localDayOfWeek, 2);\n // 1st, 2nd, ..., 7th\n case \"eo\":\n return localize.ordinalNumber(localDayOfWeek, { unit: \"day\" });\n case \"eee\":\n return localize.day(dayOfWeek, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n // T\n case \"eeeee\":\n return localize.day(dayOfWeek, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // Tu\n case \"eeeeee\":\n return localize.day(dayOfWeek, {\n width: \"short\",\n context: \"formatting\",\n });\n // Tuesday\n case \"eeee\":\n default:\n return localize.day(dayOfWeek, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // Stand-alone local day of week\n c: function (date, token, localize, options) {\n const dayOfWeek = date.getDay();\n const localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;\n switch (token) {\n // Numerical value (same as in `e`)\n case \"c\":\n return String(localDayOfWeek);\n // Padded numerical value\n case \"cc\":\n return (0, _index6.addLeadingZeros)(localDayOfWeek, token.length);\n // 1st, 2nd, ..., 7th\n case \"co\":\n return localize.ordinalNumber(localDayOfWeek, { unit: \"day\" });\n case \"ccc\":\n return localize.day(dayOfWeek, {\n width: \"abbreviated\",\n context: \"standalone\",\n });\n // T\n case \"ccccc\":\n return localize.day(dayOfWeek, {\n width: \"narrow\",\n context: \"standalone\",\n });\n // Tu\n case \"cccccc\":\n return localize.day(dayOfWeek, {\n width: \"short\",\n context: \"standalone\",\n });\n // Tuesday\n case \"cccc\":\n default:\n return localize.day(dayOfWeek, {\n width: \"wide\",\n context: \"standalone\",\n });\n }\n },\n\n // ISO day of week\n i: function (date, token, localize) {\n const dayOfWeek = date.getDay();\n const isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;\n switch (token) {\n // 2\n case \"i\":\n return String(isoDayOfWeek);\n // 02\n case \"ii\":\n return (0, _index6.addLeadingZeros)(isoDayOfWeek, token.length);\n // 2nd\n case \"io\":\n return localize.ordinalNumber(isoDayOfWeek, { unit: \"day\" });\n // Tue\n case \"iii\":\n return localize.day(dayOfWeek, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n // T\n case \"iiiii\":\n return localize.day(dayOfWeek, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // Tu\n case \"iiiiii\":\n return localize.day(dayOfWeek, {\n width: \"short\",\n context: \"formatting\",\n });\n // Tuesday\n case \"iiii\":\n default:\n return localize.day(dayOfWeek, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // AM or PM\n a: function (date, token, localize) {\n const hours = date.getHours();\n const dayPeriodEnumValue = hours / 12 >= 1 ? \"pm\" : \"am\";\n\n switch (token) {\n case \"a\":\n case \"aa\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n case \"aaa\":\n return localize\n .dayPeriod(dayPeriodEnumValue, {\n width: \"abbreviated\",\n context: \"formatting\",\n })\n .toLowerCase();\n case \"aaaaa\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"narrow\",\n context: \"formatting\",\n });\n case \"aaaa\":\n default:\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // AM, PM, midnight, noon\n b: function (date, token, localize) {\n const hours = date.getHours();\n let dayPeriodEnumValue;\n if (hours === 12) {\n dayPeriodEnumValue = dayPeriodEnum.noon;\n } else if (hours === 0) {\n dayPeriodEnumValue = dayPeriodEnum.midnight;\n } else {\n dayPeriodEnumValue = hours / 12 >= 1 ? \"pm\" : \"am\";\n }\n\n switch (token) {\n case \"b\":\n case \"bb\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n case \"bbb\":\n return localize\n .dayPeriod(dayPeriodEnumValue, {\n width: \"abbreviated\",\n context: \"formatting\",\n })\n .toLowerCase();\n case \"bbbbb\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"narrow\",\n context: \"formatting\",\n });\n case \"bbbb\":\n default:\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // in the morning, in the afternoon, in the evening, at night\n B: function (date, token, localize) {\n const hours = date.getHours();\n let dayPeriodEnumValue;\n if (hours >= 17) {\n dayPeriodEnumValue = dayPeriodEnum.evening;\n } else if (hours >= 12) {\n dayPeriodEnumValue = dayPeriodEnum.afternoon;\n } else if (hours >= 4) {\n dayPeriodEnumValue = dayPeriodEnum.morning;\n } else {\n dayPeriodEnumValue = dayPeriodEnum.night;\n }\n\n switch (token) {\n case \"B\":\n case \"BB\":\n case \"BBB\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"abbreviated\",\n context: \"formatting\",\n });\n case \"BBBBB\":\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"narrow\",\n context: \"formatting\",\n });\n case \"BBBB\":\n default:\n return localize.dayPeriod(dayPeriodEnumValue, {\n width: \"wide\",\n context: \"formatting\",\n });\n }\n },\n\n // Hour [1-12]\n h: function (date, token, localize) {\n if (token === \"ho\") {\n let hours = date.getHours() % 12;\n if (hours === 0) hours = 12;\n return localize.ordinalNumber(hours, { unit: \"hour\" });\n }\n\n return _index7.lightFormatters.h(date, token);\n },\n\n // Hour [0-23]\n H: function (date, token, localize) {\n if (token === \"Ho\") {\n return localize.ordinalNumber(date.getHours(), { unit: \"hour\" });\n }\n\n return _index7.lightFormatters.H(date, token);\n },\n\n // Hour [0-11]\n K: function (date, token, localize) {\n const hours = date.getHours() % 12;\n\n if (token === \"Ko\") {\n return localize.ordinalNumber(hours, { unit: \"hour\" });\n }\n\n return (0, _index6.addLeadingZeros)(hours, token.length);\n },\n\n // Hour [1-24]\n k: function (date, token, localize) {\n let hours = date.getHours();\n if (hours === 0) hours = 24;\n\n if (token === \"ko\") {\n return localize.ordinalNumber(hours, { unit: \"hour\" });\n }\n\n return (0, _index6.addLeadingZeros)(hours, token.length);\n },\n\n // Minute\n m: function (date, token, localize) {\n if (token === \"mo\") {\n return localize.ordinalNumber(date.getMinutes(), { unit: \"minute\" });\n }\n\n return _index7.lightFormatters.m(date, token);\n },\n\n // Second\n s: function (date, token, localize) {\n if (token === \"so\") {\n return localize.ordinalNumber(date.getSeconds(), { unit: \"second\" });\n }\n\n return _index7.lightFormatters.s(date, token);\n },\n\n // Fraction of second\n S: function (date, token) {\n return _index7.lightFormatters.S(date, token);\n },\n\n // Timezone (ISO-8601. If offset is 0, output is always `'Z'`)\n X: function (date, token, _localize) {\n const timezoneOffset = date.getTimezoneOffset();\n\n if (timezoneOffset === 0) {\n return \"Z\";\n }\n\n switch (token) {\n // Hours and optional minutes\n case \"X\":\n return formatTimezoneWithOptionalMinutes(timezoneOffset);\n\n // Hours, minutes and optional seconds without `:` delimiter\n // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n // so this token always has the same output as `XX`\n case \"XXXX\":\n case \"XX\": // Hours and minutes without `:` delimiter\n return formatTimezone(timezoneOffset);\n\n // Hours, minutes and optional seconds with `:` delimiter\n // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n // so this token always has the same output as `XXX`\n case \"XXXXX\":\n case \"XXX\": // Hours and minutes with `:` delimiter\n default:\n return formatTimezone(timezoneOffset, \":\");\n }\n },\n\n // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)\n x: function (date, token, _localize) {\n const timezoneOffset = date.getTimezoneOffset();\n\n switch (token) {\n // Hours and optional minutes\n case \"x\":\n return formatTimezoneWithOptionalMinutes(timezoneOffset);\n\n // Hours, minutes and optional seconds without `:` delimiter\n // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n // so this token always has the same output as `xx`\n case \"xxxx\":\n case \"xx\": // Hours and minutes without `:` delimiter\n return formatTimezone(timezoneOffset);\n\n // Hours, minutes and optional seconds with `:` delimiter\n // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets\n // so this token always has the same output as `xxx`\n case \"xxxxx\":\n case \"xxx\": // Hours and minutes with `:` delimiter\n default:\n return formatTimezone(timezoneOffset, \":\");\n }\n },\n\n // Timezone (GMT)\n O: function (date, token, _localize) {\n const timezoneOffset = date.getTimezoneOffset();\n\n switch (token) {\n // Short\n case \"O\":\n case \"OO\":\n case \"OOO\":\n return \"GMT\" + formatTimezoneShort(timezoneOffset, \":\");\n // Long\n case \"OOOO\":\n default:\n return \"GMT\" + formatTimezone(timezoneOffset, \":\");\n }\n },\n\n // Timezone (specific non-location)\n z: function (date, token, _localize) {\n const timezoneOffset = date.getTimezoneOffset();\n\n switch (token) {\n // Short\n case \"z\":\n case \"zz\":\n case \"zzz\":\n return \"GMT\" + formatTimezoneShort(timezoneOffset, \":\");\n // Long\n case \"zzzz\":\n default:\n return \"GMT\" + formatTimezone(timezoneOffset, \":\");\n }\n },\n\n // Seconds timestamp\n t: function (date, token, _localize) {\n const timestamp = Math.trunc(+date / 1000);\n return (0, _index6.addLeadingZeros)(timestamp, token.length);\n },\n\n // Milliseconds timestamp\n T: function (date, token, _localize) {\n return (0, _index6.addLeadingZeros)(+date, token.length);\n },\n});\n\nfunction formatTimezoneShort(offset, delimiter = \"\") {\n const sign = offset > 0 ? \"-\" : \"+\";\n const absOffset = Math.abs(offset);\n const hours = Math.trunc(absOffset / 60);\n const minutes = absOffset % 60;\n if (minutes === 0) {\n return sign + String(hours);\n }\n return (\n sign + String(hours) + delimiter + (0, _index6.addLeadingZeros)(minutes, 2)\n );\n}\n\nfunction formatTimezoneWithOptionalMinutes(offset, delimiter) {\n if (offset % 60 === 0) {\n const sign = offset > 0 ? \"-\" : \"+\";\n return sign + (0, _index6.addLeadingZeros)(Math.abs(offset) / 60, 2);\n }\n return formatTimezone(offset, delimiter);\n}\n\nfunction formatTimezone(offset, delimiter = \"\") {\n const sign = offset > 0 ? \"-\" : \"+\";\n const absOffset = Math.abs(offset);\n const hours = (0, _index6.addLeadingZeros)(Math.trunc(absOffset / 60), 2);\n const minutes = (0, _index6.addLeadingZeros)(absOffset % 60, 2);\n return sign + hours + delimiter + minutes;\n}\n", "\"use strict\";\nexports.longFormatters = void 0;\n\nconst dateLongFormatter = (pattern, formatLong) => {\n switch (pattern) {\n case \"P\":\n return formatLong.date({ width: \"short\" });\n case \"PP\":\n return formatLong.date({ width: \"medium\" });\n case \"PPP\":\n return formatLong.date({ width: \"long\" });\n case \"PPPP\":\n default:\n return formatLong.date({ width: \"full\" });\n }\n};\n\nconst timeLongFormatter = (pattern, formatLong) => {\n switch (pattern) {\n case \"p\":\n return formatLong.time({ width: \"short\" });\n case \"pp\":\n return formatLong.time({ width: \"medium\" });\n case \"ppp\":\n return formatLong.time({ width: \"long\" });\n case \"pppp\":\n default:\n return formatLong.time({ width: \"full\" });\n }\n};\n\nconst dateTimeLongFormatter = (pattern, formatLong) => {\n const matchResult = pattern.match(/(P+)(p+)?/) || [];\n const datePattern = matchResult[1];\n const timePattern = matchResult[2];\n\n if (!timePattern) {\n return dateLongFormatter(pattern, formatLong);\n }\n\n let dateTimeFormat;\n\n switch (datePattern) {\n case \"P\":\n dateTimeFormat = formatLong.dateTime({ width: \"short\" });\n break;\n case \"PP\":\n dateTimeFormat = formatLong.dateTime({ width: \"medium\" });\n break;\n case \"PPP\":\n dateTimeFormat = formatLong.dateTime({ width: \"long\" });\n break;\n case \"PPPP\":\n default:\n dateTimeFormat = formatLong.dateTime({ width: \"full\" });\n break;\n }\n\n return dateTimeFormat\n .replace(\"{{date}}\", dateLongFormatter(datePattern, formatLong))\n .replace(\"{{time}}\", timeLongFormatter(timePattern, formatLong));\n};\n\nconst longFormatters = (exports.longFormatters = {\n p: timeLongFormatter,\n P: dateTimeLongFormatter,\n});\n", "\"use strict\";\nexports.isProtectedDayOfYearToken = isProtectedDayOfYearToken;\nexports.isProtectedWeekYearToken = isProtectedWeekYearToken;\nexports.warnOrThrowProtectedError = warnOrThrowProtectedError;\nconst dayOfYearTokenRE = /^D+$/;\nconst weekYearTokenRE = /^Y+$/;\n\nconst throwTokens = [\"D\", \"DD\", \"YY\", \"YYYY\"];\n\nfunction isProtectedDayOfYearToken(token) {\n return dayOfYearTokenRE.test(token);\n}\n\nfunction isProtectedWeekYearToken(token) {\n return weekYearTokenRE.test(token);\n}\n\nfunction warnOrThrowProtectedError(token, format, input) {\n const _message = message(token, format, input);\n console.warn(_message);\n if (throwTokens.includes(token)) throw new RangeError(_message);\n}\n\nfunction message(token, format, input) {\n const subject = token[0] === \"Y\" ? \"years\" : \"days of the month\";\n return `Use \\`${token.toLowerCase()}\\` instead of \\`${token}\\` (in \\`${format}\\`) for formatting ${subject} to the input \\`${input}\\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`;\n}\n", "\"use strict\";\nexports.format = exports.formatDate = format;\nObject.defineProperty(exports, \"formatters\", {\n enumerable: true,\n get: function () {\n return _index3.formatters;\n },\n});\nObject.defineProperty(exports, \"longFormatters\", {\n enumerable: true,\n get: function () {\n return _index4.longFormatters;\n },\n});\nvar _index = require(\"./_lib/defaultLocale.cjs\");\nvar _index2 = require(\"./_lib/defaultOptions.cjs\");\nvar _index3 = require(\"./_lib/format/formatters.cjs\");\nvar _index4 = require(\"./_lib/format/longFormatters.cjs\");\nvar _index5 = require(\"./_lib/protectedTokens.cjs\");\n\nvar _index6 = require(\"./isValid.cjs\");\nvar _index7 = require(\"./toDate.cjs\");\n\n// Rexports of internal for libraries to use.\n// See: https://github.com/date-fns/date-fns/issues/3638#issuecomment-1877082874\n\n// This RegExp consists of three parts separated by `|`:\n// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token\n// (one of the certain letters followed by `o`)\n// - (\\w)\\1* matches any sequences of the same letter\n// - '' matches two quote characters in a row\n// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),\n// except a single quote symbol, which ends the sequence.\n// Two quote characters do not end the sequence.\n// If there is no matching single quote\n// then the sequence will continue until the end of the string.\n// - . matches any single character unmatched by previous parts of the RegExps\nconst formattingTokensRegExp =\n /[yYQqMLwIdDecihHKkms]o|(\\w)\\1*|''|'(''|[^'])+('|$)|./g;\n\n// This RegExp catches symbols escaped by quotes, and also\n// sequences of symbols P, p, and the combinations like `PPPPPPPppppp`\nconst longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;\n\nconst escapedStringRegExp = /^'([^]*?)'?$/;\nconst doubleQuoteRegExp = /''/g;\nconst unescapedLatinCharacterRegExp = /[a-zA-Z]/;\n\n/**\n * The {@link format} function options.\n */\n\n/**\n * @name format\n * @alias formatDate\n * @category Common Helpers\n * @summary Format the date.\n *\n * @description\n * Return the formatted date string in the given format. The result may vary by locale.\n *\n * > \u26A0\uFE0F Please note that the `format` tokens differ from Moment.js and other libraries.\n * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * The characters wrapped between two single quotes characters (') are escaped.\n * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.\n * (see the last example)\n *\n * Format of the string is based on Unicode Technical Standard #35:\n * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n * with a few additions (see note 7 below the table).\n *\n * Accepted patterns:\n * | Unit | Pattern | Result examples | Notes |\n * |---------------------------------|---------|-----------------------------------|-------|\n * | Era | G..GGG | AD, BC | |\n * | | GGGG | Anno Domini, Before Christ | 2 |\n * | | GGGGG | A, B | |\n * | Calendar year | y | 44, 1, 1900, 2017 | 5 |\n * | | yo | 44th, 1st, 0th, 17th | 5,7 |\n * | | yy | 44, 01, 00, 17 | 5 |\n * | | yyy | 044, 001, 1900, 2017 | 5 |\n * | | yyyy | 0044, 0001, 1900, 2017 | 5 |\n * | | yyyyy | ... | 3,5 |\n * | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 |\n * | | Yo | 44th, 1st, 1900th, 2017th | 5,7 |\n * | | YY | 44, 01, 00, 17 | 5,8 |\n * | | YYY | 044, 001, 1900, 2017 | 5 |\n * | | YYYY | 0044, 0001, 1900, 2017 | 5,8 |\n * | | YYYYY | ... | 3,5 |\n * | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 |\n * | | RR | -43, 00, 01, 1900, 2017 | 5,7 |\n * | | RRR | -043, 000, 001, 1900, 2017 | 5,7 |\n * | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 |\n * | | RRRRR | ... | 3,5,7 |\n * | Extended year | u | -43, 0, 1, 1900, 2017 | 5 |\n * | | uu | -43, 01, 1900, 2017 | 5 |\n * | | uuu | -043, 001, 1900, 2017 | 5 |\n * | | uuuu | -0043, 0001, 1900, 2017 | 5 |\n * | | uuuuu | ... | 3,5 |\n * | Quarter (formatting) | Q | 1, 2, 3, 4 | |\n * | | Qo | 1st, 2nd, 3rd, 4th | 7 |\n * | | QQ | 01, 02, 03, 04 | |\n * | | QQQ | Q1, Q2, Q3, Q4 | |\n * | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |\n * | | QQQQQ | 1, 2, 3, 4 | 4 |\n * | Quarter (stand-alone) | q | 1, 2, 3, 4 | |\n * | | qo | 1st, 2nd, 3rd, 4th | 7 |\n * | | qq | 01, 02, 03, 04 | |\n * | | qqq | Q1, Q2, Q3, Q4 | |\n * | | qqqq | 1st quarter, 2nd quarter, ... | 2 |\n * | | qqqqq | 1, 2, 3, 4 | 4 |\n * | Month (formatting) | M | 1, 2, ..., 12 | |\n * | | Mo | 1st, 2nd, ..., 12th | 7 |\n * | | MM | 01, 02, ..., 12 | |\n * | | MMM | Jan, Feb, ..., Dec | |\n * | | MMMM | January, February, ..., December | 2 |\n * | | MMMMM | J, F, ..., D | |\n * | Month (stand-alone) | L | 1, 2, ..., 12 | |\n * | | Lo | 1st, 2nd, ..., 12th | 7 |\n * | | LL | 01, 02, ..., 12 | |\n * | | LLL | Jan, Feb, ..., Dec | |\n * | | LLLL | January, February, ..., December | 2 |\n * | | LLLLL | J, F, ..., D | |\n * | Local week of year | w | 1, 2, ..., 53 | |\n * | | wo | 1st, 2nd, ..., 53th | 7 |\n * | | ww | 01, 02, ..., 53 | |\n * | ISO week of year | I | 1, 2, ..., 53 | 7 |\n * | | Io | 1st, 2nd, ..., 53th | 7 |\n * | | II | 01, 02, ..., 53 | 7 |\n * | Day of month | d | 1, 2, ..., 31 | |\n * | | do | 1st, 2nd, ..., 31st | 7 |\n * | | dd | 01, 02, ..., 31 | |\n * | Day of year | D | 1, 2, ..., 365, 366 | 9 |\n * | | Do | 1st, 2nd, ..., 365th, 366th | 7 |\n * | | DD | 01, 02, ..., 365, 366 | 9 |\n * | | DDD | 001, 002, ..., 365, 366 | |\n * | | DDDD | ... | 3 |\n * | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Sun | |\n * | | EEEE | Monday, Tuesday, ..., Sunday | 2 |\n * | | EEEEE | M, T, W, T, F, S, S | |\n * | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 |\n * | | io | 1st, 2nd, ..., 7th | 7 |\n * | | ii | 01, 02, ..., 07 | 7 |\n * | | iii | Mon, Tue, Wed, ..., Sun | 7 |\n * | | iiii | Monday, Tuesday, ..., Sunday | 2,7 |\n * | | iiiii | M, T, W, T, F, S, S | 7 |\n * | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 7 |\n * | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | |\n * | | eo | 2nd, 3rd, ..., 1st | 7 |\n * | | ee | 02, 03, ..., 01 | |\n * | | eee | Mon, Tue, Wed, ..., Sun | |\n * | | eeee | Monday, Tuesday, ..., Sunday | 2 |\n * | | eeeee | M, T, W, T, F, S, S | |\n * | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | |\n * | | co | 2nd, 3rd, ..., 1st | 7 |\n * | | cc | 02, 03, ..., 01 | |\n * | | ccc | Mon, Tue, Wed, ..., Sun | |\n * | | cccc | Monday, Tuesday, ..., Sunday | 2 |\n * | | ccccc | M, T, W, T, F, S, S | |\n * | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | AM, PM | a..aa | AM, PM | |\n * | | aaa | am, pm | |\n * | | aaaa | a.m., p.m. | 2 |\n * | | aaaaa | a, p | |\n * | AM, PM, noon, midnight | b..bb | AM, PM, noon, midnight | |\n * | | bbb | am, pm, noon, midnight | |\n * | | bbbb | a.m., p.m., noon, midnight | 2 |\n * | | bbbbb | a, p, n, mi | |\n * | Flexible day period | B..BBB | at night, in the morning, ... | |\n * | | BBBB | at night, in the morning, ... | 2 |\n * | | BBBBB | at night, in the morning, ... | |\n * | Hour [1-12] | h | 1, 2, ..., 11, 12 | |\n * | | ho | 1st, 2nd, ..., 11th, 12th | 7 |\n * | | hh | 01, 02, ..., 11, 12 | |\n * | Hour [0-23] | H | 0, 1, 2, ..., 23 | |\n * | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 |\n * | | HH | 00, 01, 02, ..., 23 | |\n * | Hour [0-11] | K | 1, 2, ..., 11, 0 | |\n * | | Ko | 1st, 2nd, ..., 11th, 0th | 7 |\n * | | KK | 01, 02, ..., 11, 00 | |\n * | Hour [1-24] | k | 24, 1, 2, ..., 23 | |\n * | | ko | 24th, 1st, 2nd, ..., 23rd | 7 |\n * | | kk | 24, 01, 02, ..., 23 | |\n * | Minute | m | 0, 1, ..., 59 | |\n * | | mo | 0th, 1st, ..., 59th | 7 |\n * | | mm | 00, 01, ..., 59 | |\n * | Second | s | 0, 1, ..., 59 | |\n * | | so | 0th, 1st, ..., 59th | 7 |\n * | | ss | 00, 01, ..., 59 | |\n * | Fraction of second | S | 0, 1, ..., 9 | |\n * | | SS | 00, 01, ..., 99 | |\n * | | SSS | 000, 001, ..., 999 | |\n * | | SSSS | ... | 3 |\n * | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | |\n * | | XX | -0800, +0530, Z | |\n * | | XXX | -08:00, +05:30, Z | |\n * | | XXXX | -0800, +0530, Z, +123456 | 2 |\n * | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |\n * | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | |\n * | | xx | -0800, +0530, +0000 | |\n * | | xxx | -08:00, +05:30, +00:00 | 2 |\n * | | xxxx | -0800, +0530, +0000, +123456 | |\n * | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |\n * | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | |\n * | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 |\n * | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 |\n * | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 |\n * | Seconds timestamp | t | 512969520 | 7 |\n * | | tt | ... | 3,7 |\n * | Milliseconds timestamp | T | 512969520900 | 7 |\n * | | TT | ... | 3,7 |\n * | Long localized date | P | 04/29/1453 | 7 |\n * | | PP | Apr 29, 1453 | 7 |\n * | | PPP | April 29th, 1453 | 7 |\n * | | PPPP | Friday, April 29th, 1453 | 2,7 |\n * | Long localized time | p | 12:00 AM | 7 |\n * | | pp | 12:00:00 AM | 7 |\n * | | ppp | 12:00:00 AM GMT+2 | 7 |\n * | | pppp | 12:00:00 AM GMT+02:00 | 2,7 |\n * | Combination of date and time | Pp | 04/29/1453, 12:00 AM | 7 |\n * | | PPpp | Apr 29, 1453, 12:00:00 AM | 7 |\n * | | PPPppp | April 29th, 1453 at ... | 7 |\n * | | PPPPpppp| Friday, April 29th, 1453 at ... | 2,7 |\n * Notes:\n * 1. \"Formatting\" units (e.g. formatting quarter) in the default en-US locale\n * are the same as \"stand-alone\" units, but are different in some languages.\n * \"Formatting\" units are declined according to the rules of the language\n * in the context of a date. \"Stand-alone\" units are always nominative singular:\n *\n * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`\n *\n * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`\n *\n * 2. Any sequence of the identical letters is a pattern, unless it is escaped by\n * the single quote characters (see below).\n * If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`)\n * the output will be the same as default pattern for this unit, usually\n * the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units\n * are marked with \"2\" in the last column of the table.\n *\n * `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'`\n *\n * `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'`\n *\n * `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'`\n *\n * `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'`\n *\n * `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'`\n *\n * 3. Some patterns could be unlimited length (such as `yyyyyyyy`).\n * The output will be padded with zeros to match the length of the pattern.\n *\n * `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'`\n *\n * 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.\n * These tokens represent the shortest form of the quarter.\n *\n * 5. The main difference between `y` and `u` patterns are B.C. years:\n *\n * | Year | `y` | `u` |\n * |------|-----|-----|\n * | AC 1 | 1 | 1 |\n * | BC 1 | 1 | 0 |\n * | BC 2 | 2 | -1 |\n *\n * Also `yy` always returns the last two digits of a year,\n * while `uu` pads single digit years to 2 characters and returns other years unchanged:\n *\n * | Year | `yy` | `uu` |\n * |------|------|------|\n * | 1 | 01 | 01 |\n * | 14 | 14 | 14 |\n * | 376 | 76 | 376 |\n * | 1453 | 53 | 1453 |\n *\n * The same difference is true for local and ISO week-numbering years (`Y` and `R`),\n * except local week-numbering years are dependent on `options.weekStartsOn`\n * and `options.firstWeekContainsDate` (compare [getISOWeekYear](https://date-fns.org/docs/getISOWeekYear)\n * and [getWeekYear](https://date-fns.org/docs/getWeekYear)).\n *\n * 6. Specific non-location timezones are currently unavailable in `date-fns`,\n * so right now these tokens fall back to GMT timezones.\n *\n * 7. These patterns are not in the Unicode Technical Standard #35:\n * - `i`: ISO day of week\n * - `I`: ISO week of year\n * - `R`: ISO week-numbering year\n * - `t`: seconds timestamp\n * - `T`: milliseconds timestamp\n * - `o`: ordinal number modifier\n * - `P`: long localized date\n * - `p`: long localized time\n *\n * 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.\n * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * 9. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.\n * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * @param date - The original date\n * @param format - The string of tokens\n * @param options - An object with options\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n * @throws `options.locale` must contain `localize` property\n * @throws `options.locale` must contain `formatLong` property\n * @throws use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws format string contains an unescaped latin alphabet character\n *\n * @example\n * // Represent 11 February 2014 in middle-endian format:\n * const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy')\n * //=> '02/11/2014'\n *\n * @example\n * // Represent 2 July 2014 in Esperanto:\n * import { eoLocale } from 'date-fns/locale/eo'\n * const result = format(new Date(2014, 6, 2), \"do 'de' MMMM yyyy\", {\n * locale: eoLocale\n * })\n * //=> '2-a de julio 2014'\n *\n * @example\n * // Escape string by single quote characters:\n * const result = format(new Date(2014, 6, 2, 15), \"h 'o''clock'\")\n * //=> \"3 o'clock\"\n */\nfunction format(date, formatStr, options) {\n const defaultOptions = (0, _index2.getDefaultOptions)();\n const locale =\n options?.locale ?? defaultOptions.locale ?? _index.defaultLocale;\n\n const firstWeekContainsDate =\n options?.firstWeekContainsDate ??\n options?.locale?.options?.firstWeekContainsDate ??\n defaultOptions.firstWeekContainsDate ??\n defaultOptions.locale?.options?.firstWeekContainsDate ??\n 1;\n\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const originalDate = (0, _index7.toDate)(date, options?.in);\n\n if (!(0, _index6.isValid)(originalDate)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n let parts = formatStr\n .match(longFormattingTokensRegExp)\n .map((substring) => {\n const firstCharacter = substring[0];\n if (firstCharacter === \"p\" || firstCharacter === \"P\") {\n const longFormatter = _index4.longFormatters[firstCharacter];\n return longFormatter(substring, locale.formatLong);\n }\n return substring;\n })\n .join(\"\")\n .match(formattingTokensRegExp)\n .map((substring) => {\n // Replace two single quote characters with one single quote character\n if (substring === \"''\") {\n return { isToken: false, value: \"'\" };\n }\n\n const firstCharacter = substring[0];\n if (firstCharacter === \"'\") {\n return { isToken: false, value: cleanEscapedString(substring) };\n }\n\n if (_index3.formatters[firstCharacter]) {\n return { isToken: true, value: substring };\n }\n\n if (firstCharacter.match(unescapedLatinCharacterRegExp)) {\n throw new RangeError(\n \"Format string contains an unescaped latin alphabet character `\" +\n firstCharacter +\n \"`\",\n );\n }\n\n return { isToken: false, value: substring };\n });\n\n // invoke localize preprocessor (only for french locales at the moment)\n if (locale.localize.preprocessor) {\n parts = locale.localize.preprocessor(originalDate, parts);\n }\n\n const formatterOptions = {\n firstWeekContainsDate,\n weekStartsOn,\n locale,\n };\n\n return parts\n .map((part) => {\n if (!part.isToken) return part.value;\n\n const token = part.value;\n\n if (\n (!options?.useAdditionalWeekYearTokens &&\n (0, _index5.isProtectedWeekYearToken)(token)) ||\n (!options?.useAdditionalDayOfYearTokens &&\n (0, _index5.isProtectedDayOfYearToken)(token))\n ) {\n (0, _index5.warnOrThrowProtectedError)(token, formatStr, String(date));\n }\n\n const formatter = _index3.formatters[token[0]];\n return formatter(originalDate, token, locale.localize, formatterOptions);\n })\n .join(\"\");\n}\n\nfunction cleanEscapedString(input) {\n const matched = input.match(escapedStringRegExp);\n\n if (!matched) {\n return input;\n }\n\n return matched[1].replace(doubleQuoteRegExp, \"'\");\n}\n", "\"use strict\";\nexports.formatDistance = formatDistance;\nvar _index = require(\"./_lib/defaultLocale.cjs\");\nvar _index2 = require(\"./_lib/defaultOptions.cjs\");\nvar _index3 = require(\"./_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _index4 = require(\"./_lib/normalizeDates.cjs\");\nvar _index5 = require(\"./compareAsc.cjs\");\nvar _index6 = require(\"./constants.cjs\");\nvar _index7 = require(\"./differenceInMonths.cjs\");\nvar _index8 = require(\"./differenceInSeconds.cjs\");\n\n/**\n * The {@link formatDistance} function options.\n */\n\n/**\n * @name formatDistance\n * @category Common Helpers\n * @summary Return the distance between the given dates in words.\n *\n * @description\n * Return the distance between the given dates in words.\n *\n * | Distance between dates | Result |\n * |-------------------------------------------------------------------|---------------------|\n * | 0 ... 30 secs | less than a minute |\n * | 30 secs ... 1 min 30 secs | 1 minute |\n * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes |\n * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour |\n * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours |\n * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day |\n * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days |\n * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month |\n * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months |\n * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months |\n * | 1 yr ... 1 yr 3 months | about 1 year |\n * | 1 yr 3 months ... 1 yr 9 month s | over 1 year |\n * | 1 yr 9 months ... 2 yrs | almost 2 years |\n * | N yrs ... N yrs 3 months | about N years |\n * | N yrs 3 months ... N yrs 9 months | over N years |\n * | N yrs 9 months ... N+1 yrs | almost N+1 years |\n *\n * With `options.includeSeconds == true`:\n * | Distance between dates | Result |\n * |------------------------|----------------------|\n * | 0 secs ... 5 secs | less than 5 seconds |\n * | 5 secs ... 10 secs | less than 10 seconds |\n * | 10 secs ... 20 secs | less than 20 seconds |\n * | 20 secs ... 40 secs | half a minute |\n * | 40 secs ... 60 secs | less than a minute |\n * | 60 secs ... 90 secs | 1 minute |\n *\n * @param laterDate - The date\n * @param earlierDate - The date to compare with\n * @param options - An object with options\n *\n * @returns The distance in words\n *\n * @throws `date` must not be Invalid Date\n * @throws `baseDate` must not be Invalid Date\n * @throws `options.locale` must contain `formatDistance` property\n *\n * @example\n * // What is the distance between 2 July 2014 and 1 January 2015?\n * const result = formatDistance(new Date(2014, 6, 2), new Date(2015, 0, 1))\n * //=> '6 months'\n *\n * @example\n * // What is the distance between 1 January 2015 00:00:15\n * // and 1 January 2015 00:00:00, including seconds?\n * const result = formatDistance(\n * new Date(2015, 0, 1, 0, 0, 15),\n * new Date(2015, 0, 1, 0, 0, 0),\n * { includeSeconds: true }\n * )\n * //=> 'less than 20 seconds'\n *\n * @example\n * // What is the distance from 1 January 2016\n * // to 1 January 2015, with a suffix?\n * const result = formatDistance(new Date(2015, 0, 1), new Date(2016, 0, 1), {\n * addSuffix: true\n * })\n * //=> 'about 1 year ago'\n *\n * @example\n * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto?\n * import { eoLocale } from 'date-fns/locale/eo'\n * const result = formatDistance(new Date(2016, 7, 1), new Date(2015, 0, 1), {\n * locale: eoLocale\n * })\n * //=> 'pli ol 1 jaro'\n */\nfunction formatDistance(laterDate, earlierDate, options) {\n const defaultOptions = (0, _index2.getDefaultOptions)();\n const locale =\n options?.locale ?? defaultOptions.locale ?? _index.defaultLocale;\n const minutesInAlmostTwoDays = 2520;\n\n const comparison = (0, _index5.compareAsc)(laterDate, earlierDate);\n\n if (isNaN(comparison)) throw new RangeError(\"Invalid time value\");\n\n const localizeOptions = Object.assign({}, options, {\n addSuffix: options?.addSuffix,\n comparison: comparison,\n });\n\n const [laterDate_, earlierDate_] = (0, _index4.normalizeDates)(\n options?.in,\n ...(comparison > 0 ? [earlierDate, laterDate] : [laterDate, earlierDate]),\n );\n\n const seconds = (0, _index8.differenceInSeconds)(earlierDate_, laterDate_);\n const offsetInSeconds =\n ((0, _index3.getTimezoneOffsetInMilliseconds)(earlierDate_) -\n (0, _index3.getTimezoneOffsetInMilliseconds)(laterDate_)) /\n 1000;\n const minutes = Math.round((seconds - offsetInSeconds) / 60);\n let months;\n\n // 0 up to 2 mins\n if (minutes < 2) {\n if (options?.includeSeconds) {\n if (seconds < 5) {\n return locale.formatDistance(\"lessThanXSeconds\", 5, localizeOptions);\n } else if (seconds < 10) {\n return locale.formatDistance(\"lessThanXSeconds\", 10, localizeOptions);\n } else if (seconds < 20) {\n return locale.formatDistance(\"lessThanXSeconds\", 20, localizeOptions);\n } else if (seconds < 40) {\n return locale.formatDistance(\"halfAMinute\", 0, localizeOptions);\n } else if (seconds < 60) {\n return locale.formatDistance(\"lessThanXMinutes\", 1, localizeOptions);\n } else {\n return locale.formatDistance(\"xMinutes\", 1, localizeOptions);\n }\n } else {\n if (minutes === 0) {\n return locale.formatDistance(\"lessThanXMinutes\", 1, localizeOptions);\n } else {\n return locale.formatDistance(\"xMinutes\", minutes, localizeOptions);\n }\n }\n\n // 2 mins up to 0.75 hrs\n } else if (minutes < 45) {\n return locale.formatDistance(\"xMinutes\", minutes, localizeOptions);\n\n // 0.75 hrs up to 1.5 hrs\n } else if (minutes < 90) {\n return locale.formatDistance(\"aboutXHours\", 1, localizeOptions);\n\n // 1.5 hrs up to 24 hrs\n } else if (minutes < _index6.minutesInDay) {\n const hours = Math.round(minutes / 60);\n return locale.formatDistance(\"aboutXHours\", hours, localizeOptions);\n\n // 1 day up to 1.75 days\n } else if (minutes < minutesInAlmostTwoDays) {\n return locale.formatDistance(\"xDays\", 1, localizeOptions);\n\n // 1.75 days up to 30 days\n } else if (minutes < _index6.minutesInMonth) {\n const days = Math.round(minutes / _index6.minutesInDay);\n return locale.formatDistance(\"xDays\", days, localizeOptions);\n\n // 1 month up to 2 months\n } else if (minutes < _index6.minutesInMonth * 2) {\n months = Math.round(minutes / _index6.minutesInMonth);\n return locale.formatDistance(\"aboutXMonths\", months, localizeOptions);\n }\n\n months = (0, _index7.differenceInMonths)(earlierDate_, laterDate_);\n\n // 2 months up to 12 months\n if (months < 12) {\n const nearestMonth = Math.round(minutes / _index6.minutesInMonth);\n return locale.formatDistance(\"xMonths\", nearestMonth, localizeOptions);\n\n // 1 year up to max Date\n } else {\n const monthsSinceStartOfYear = months % 12;\n const years = Math.trunc(months / 12);\n\n // N years up to 1 years 3 months\n if (monthsSinceStartOfYear < 3) {\n return locale.formatDistance(\"aboutXYears\", years, localizeOptions);\n\n // N years 3 months up to N years 9 months\n } else if (monthsSinceStartOfYear < 9) {\n return locale.formatDistance(\"overXYears\", years, localizeOptions);\n\n // N years 9 months up to N year 12 months\n } else {\n return locale.formatDistance(\"almostXYears\", years + 1, localizeOptions);\n }\n }\n}\n", "\"use strict\";\nexports.formatDistanceStrict = formatDistanceStrict;\nvar _index = require(\"./_lib/defaultLocale.cjs\");\nvar _index2 = require(\"./_lib/defaultOptions.cjs\");\nvar _index3 = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index4 = require(\"./_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _index5 = require(\"./_lib/normalizeDates.cjs\");\nvar _index6 = require(\"./compareAsc.cjs\");\nvar _index7 = require(\"./constants.cjs\");\n\n/**\n * The {@link formatDistanceStrict} function options.\n */\n\n/**\n * The unit used to format the distance in {@link formatDistanceStrict}.\n */\n\n/**\n * @name formatDistanceStrict\n * @category Common Helpers\n * @summary Return the distance between the given dates in words.\n *\n * @description\n * Return the distance between the given dates in words, using strict units.\n * This is like `formatDistance`, but does not use helpers like 'almost', 'over',\n * 'less than' and the like.\n *\n * | Distance between dates | Result |\n * |------------------------|---------------------|\n * | 0 ... 59 secs | [0..59] seconds |\n * | 1 ... 59 mins | [1..59] minutes |\n * | 1 ... 23 hrs | [1..23] hours |\n * | 1 ... 29 days | [1..29] days |\n * | 1 ... 11 months | [1..11] months |\n * | 1 ... N years | [1..N] years |\n *\n * @param laterDate - The date\n * @param earlierDate - The date to compare with\n * @param options - An object with options\n *\n * @returns The distance in words\n *\n * @throws `date` must not be Invalid Date\n * @throws `baseDate` must not be Invalid Date\n * @throws `options.unit` must be 'second', 'minute', 'hour', 'day', 'month' or 'year'\n * @throws `options.locale` must contain `formatDistance` property\n *\n * @example\n * // What is the distance between 2 July 2014 and 1 January 2015?\n * const result = formatDistanceStrict(new Date(2014, 6, 2), new Date(2015, 0, 2))\n * //=> '6 months'\n *\n * @example\n * // What is the distance between 1 January 2015 00:00:15\n * // and 1 January 2015 00:00:00?\n * const result = formatDistanceStrict(\n * new Date(2015, 0, 1, 0, 0, 15),\n * new Date(2015, 0, 1, 0, 0, 0)\n * )\n * //=> '15 seconds'\n *\n * @example\n * // What is the distance from 1 January 2016\n * // to 1 January 2015, with a suffix?\n * const result = formatDistanceStrict(new Date(2015, 0, 1), new Date(2016, 0, 1), {\n * addSuffix: true\n * })\n * //=> '1 year ago'\n *\n * @example\n * // What is the distance from 1 January 2016\n * // to 1 January 2015, in minutes?\n * const result = formatDistanceStrict(new Date(2016, 0, 1), new Date(2015, 0, 1), {\n * unit: 'minute'\n * })\n * //=> '525600 minutes'\n *\n * @example\n * // What is the distance from 1 January 2015\n * // to 28 January 2015, in months, rounded up?\n * const result = formatDistanceStrict(new Date(2015, 0, 28), new Date(2015, 0, 1), {\n * unit: 'month',\n * roundingMethod: 'ceil'\n * })\n * //=> '1 month'\n *\n * @example\n * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto?\n * import { eoLocale } from 'date-fns/locale/eo'\n * const result = formatDistanceStrict(new Date(2016, 7, 1), new Date(2015, 0, 1), {\n * locale: eoLocale\n * })\n * //=> '1 jaro'\n */\n\nfunction formatDistanceStrict(laterDate, earlierDate, options) {\n const defaultOptions = (0, _index2.getDefaultOptions)();\n const locale =\n options?.locale ?? defaultOptions.locale ?? _index.defaultLocale;\n\n const comparison = (0, _index6.compareAsc)(laterDate, earlierDate);\n\n if (isNaN(comparison)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n const localizeOptions = Object.assign({}, options, {\n addSuffix: options?.addSuffix,\n comparison: comparison,\n });\n\n const [laterDate_, earlierDate_] = (0, _index5.normalizeDates)(\n options?.in,\n ...(comparison > 0 ? [earlierDate, laterDate] : [laterDate, earlierDate]),\n );\n\n const roundingMethod = (0, _index3.getRoundingMethod)(\n options?.roundingMethod ?? \"round\",\n );\n\n const milliseconds = earlierDate_.getTime() - laterDate_.getTime();\n const minutes = milliseconds / _index7.millisecondsInMinute;\n\n const timezoneOffset =\n (0, _index4.getTimezoneOffsetInMilliseconds)(earlierDate_) -\n (0, _index4.getTimezoneOffsetInMilliseconds)(laterDate_);\n\n // Use DST-normalized difference in minutes for years, months and days;\n // use regular difference in minutes for hours, minutes and seconds.\n const dstNormalizedMinutes =\n (milliseconds - timezoneOffset) / _index7.millisecondsInMinute;\n\n const defaultUnit = options?.unit;\n let unit;\n if (!defaultUnit) {\n if (minutes < 1) {\n unit = \"second\";\n } else if (minutes < 60) {\n unit = \"minute\";\n } else if (minutes < _index7.minutesInDay) {\n unit = \"hour\";\n } else if (dstNormalizedMinutes < _index7.minutesInMonth) {\n unit = \"day\";\n } else if (dstNormalizedMinutes < _index7.minutesInYear) {\n unit = \"month\";\n } else {\n unit = \"year\";\n }\n } else {\n unit = defaultUnit;\n }\n\n // 0 up to 60 seconds\n if (unit === \"second\") {\n const seconds = roundingMethod(milliseconds / 1000);\n return locale.formatDistance(\"xSeconds\", seconds, localizeOptions);\n\n // 1 up to 60 mins\n } else if (unit === \"minute\") {\n const roundedMinutes = roundingMethod(minutes);\n return locale.formatDistance(\"xMinutes\", roundedMinutes, localizeOptions);\n\n // 1 up to 24 hours\n } else if (unit === \"hour\") {\n const hours = roundingMethod(minutes / 60);\n return locale.formatDistance(\"xHours\", hours, localizeOptions);\n\n // 1 up to 30 days\n } else if (unit === \"day\") {\n const days = roundingMethod(dstNormalizedMinutes / _index7.minutesInDay);\n return locale.formatDistance(\"xDays\", days, localizeOptions);\n\n // 1 up to 12 months\n } else if (unit === \"month\") {\n const months = roundingMethod(\n dstNormalizedMinutes / _index7.minutesInMonth,\n );\n return months === 12 && defaultUnit !== \"month\"\n ? locale.formatDistance(\"xYears\", 1, localizeOptions)\n : locale.formatDistance(\"xMonths\", months, localizeOptions);\n\n // 1 year up to max Date\n } else {\n const years = roundingMethod(dstNormalizedMinutes / _index7.minutesInYear);\n return locale.formatDistance(\"xYears\", years, localizeOptions);\n }\n}\n", "\"use strict\";\nexports.formatDistanceToNow = formatDistanceToNow;\nvar _index = require(\"./constructNow.cjs\");\n\nvar _index2 = require(\"./formatDistance.cjs\");\n\n/**\n * The {@link formatDistanceToNow} function options.\n */\n\n/**\n * @name formatDistanceToNow\n * @category Common Helpers\n * @summary Return the distance between the given date and now in words.\n * @pure false\n *\n * @description\n * Return the distance between the given date and now in words.\n *\n * | Distance to now | Result |\n * |-------------------------------------------------------------------|---------------------|\n * | 0 ... 30 secs | less than a minute |\n * | 30 secs ... 1 min 30 secs | 1 minute |\n * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes |\n * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour |\n * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours |\n * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day |\n * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days |\n * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month |\n * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months |\n * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months |\n * | 1 yr ... 1 yr 3 months | about 1 year |\n * | 1 yr 3 months ... 1 yr 9 month s | over 1 year |\n * | 1 yr 9 months ... 2 yrs | almost 2 years |\n * | N yrs ... N yrs 3 months | about N years |\n * | N yrs 3 months ... N yrs 9 months | over N years |\n * | N yrs 9 months ... N+1 yrs | almost N+1 years |\n *\n * With `options.includeSeconds == true`:\n * | Distance to now | Result |\n * |---------------------|----------------------|\n * | 0 secs ... 5 secs | less than 5 seconds |\n * | 5 secs ... 10 secs | less than 10 seconds |\n * | 10 secs ... 20 secs | less than 20 seconds |\n * | 20 secs ... 40 secs | half a minute |\n * | 40 secs ... 60 secs | less than a minute |\n * | 60 secs ... 90 secs | 1 minute |\n *\n * @param date - The given date\n * @param options - The object with options\n *\n * @returns The distance in words\n *\n * @throws `date` must not be Invalid Date\n * @throws `options.locale` must contain `formatDistance` property\n *\n * @example\n * // If today is 1 January 2015, what is the distance to 2 July 2014?\n * const result = formatDistanceToNow(\n * new Date(2014, 6, 2)\n * )\n * //=> '6 months'\n *\n * @example\n * // If now is 1 January 2015 00:00:00,\n * // what is the distance to 1 January 2015 00:00:15, including seconds?\n * const result = formatDistanceToNow(\n * new Date(2015, 0, 1, 0, 0, 15),\n * {includeSeconds: true}\n * )\n * //=> 'less than 20 seconds'\n *\n * @example\n * // If today is 1 January 2015,\n * // what is the distance to 1 January 2016, with a suffix?\n * const result = formatDistanceToNow(\n * new Date(2016, 0, 1),\n * {addSuffix: true}\n * )\n * //=> 'in about 1 year'\n *\n * @example\n * // If today is 1 January 2015,\n * // what is the distance to 1 August 2016 in Esperanto?\n * const eoLocale = require('date-fns/locale/eo')\n * const result = formatDistanceToNow(\n * new Date(2016, 7, 1),\n * {locale: eoLocale}\n * )\n * //=> 'pli ol 1 jaro'\n */\nfunction formatDistanceToNow(date, options) {\n return (0, _index2.formatDistance)(\n date,\n (0, _index.constructNow)(date),\n options,\n );\n}\n", "\"use strict\";\nexports.formatDistanceToNowStrict = formatDistanceToNowStrict;\nvar _index = require(\"./constructNow.cjs\");\n\nvar _index2 = require(\"./formatDistanceStrict.cjs\");\n\n/**\n * The {@link formatDistanceToNowStrict} function options.\n */\n\n/**\n * @name formatDistanceToNowStrict\n * @category Common Helpers\n * @summary Return the distance between the given date and now in words.\n * @pure false\n *\n * @description\n * Return the distance between the given dates in words, using strict units.\n * This is like `formatDistance`, but does not use helpers like 'almost', 'over',\n * 'less than' and the like.\n *\n * | Distance between dates | Result |\n * |------------------------|---------------------|\n * | 0 ... 59 secs | [0..59] seconds |\n * | 1 ... 59 mins | [1..59] minutes |\n * | 1 ... 23 hrs | [1..23] hours |\n * | 1 ... 29 days | [1..29] days |\n * | 1 ... 11 months | [1..11] months |\n * | 1 ... N years | [1..N] years |\n *\n * @param date - The given date\n * @param options - An object with options.\n *\n * @returns The distance in words\n *\n * @throws `date` must not be Invalid Date\n * @throws `options.locale` must contain `formatDistance` property\n *\n * @example\n * // If today is 1 January 2015, what is the distance to 2 July 2014?\n * const result = formatDistanceToNowStrict(\n * new Date(2014, 6, 2)\n * )\n * //=> '6 months'\n *\n * @example\n * // If now is 1 January 2015 00:00:00,\n * // what is the distance to 1 January 2015 00:00:15, including seconds?\n * const result = formatDistanceToNowStrict(\n * new Date(2015, 0, 1, 0, 0, 15)\n * )\n * //=> '15 seconds'\n *\n * @example\n * // If today is 1 January 2015,\n * // what is the distance to 1 January 2016, with a suffix?\n * const result = formatDistanceToNowStrict(\n * new Date(2016, 0, 1),\n * {addSuffix: true}\n * )\n * //=> 'in 1 year'\n *\n * @example\n * // If today is 28 January 2015,\n * // what is the distance to 1 January 2015, in months, rounded up??\n * const result = formatDistanceToNowStrict(new Date(2015, 0, 1), {\n * unit: 'month',\n * roundingMethod: 'ceil'\n * })\n * //=> '1 month'\n *\n * @example\n * // If today is 1 January 2015,\n * // what is the distance to 1 January 2016 in Esperanto?\n * const eoLocale = require('date-fns/locale/eo')\n * const result = formatDistanceToNowStrict(\n * new Date(2016, 0, 1),\n * {locale: eoLocale}\n * )\n * //=> '1 jaro'\n */\nfunction formatDistanceToNowStrict(date, options) {\n return (0, _index2.formatDistanceStrict)(\n date,\n (0, _index.constructNow)(date),\n options,\n );\n}\n", "\"use strict\";\nexports.formatDuration = formatDuration;\n\nvar _index = require(\"./_lib/defaultLocale.cjs\");\nvar _index2 = require(\"./_lib/defaultOptions.cjs\");\n\n/**\n * The {@link formatDuration} function options.\n */\n\nconst defaultFormat = [\n \"years\",\n \"months\",\n \"weeks\",\n \"days\",\n \"hours\",\n \"minutes\",\n \"seconds\",\n];\n\n/**\n * @name formatDuration\n * @category Common Helpers\n * @summary Formats a duration in human-readable format\n *\n * @description\n * Return human-readable duration string i.e. \"9 months 2 days\"\n *\n * @param duration - The duration to format\n * @param options - An object with options.\n *\n * @returns The formatted date string\n *\n * @example\n * // Format full duration\n * formatDuration({\n * years: 2,\n * months: 9,\n * weeks: 1,\n * days: 7,\n * hours: 5,\n * minutes: 9,\n * seconds: 30\n * })\n * //=> '2 years 9 months 1 week 7 days 5 hours 9 minutes 30 seconds'\n *\n * @example\n * // Format partial duration\n * formatDuration({ months: 9, days: 2 })\n * //=> '9 months 2 days'\n *\n * @example\n * // Customize the format\n * formatDuration(\n * {\n * years: 2,\n * months: 9,\n * weeks: 1,\n * days: 7,\n * hours: 5,\n * minutes: 9,\n * seconds: 30\n * },\n * { format: ['months', 'weeks'] }\n * ) === '9 months 1 week'\n *\n * @example\n * // Customize the zeros presence\n * formatDuration({ years: 0, months: 9 })\n * //=> '9 months'\n * formatDuration({ years: 0, months: 9 }, { zero: true })\n * //=> '0 years 9 months'\n *\n * @example\n * // Customize the delimiter\n * formatDuration({ years: 2, months: 9, weeks: 3 }, { delimiter: ', ' })\n * //=> '2 years, 9 months, 3 weeks'\n */\nfunction formatDuration(duration, options) {\n const defaultOptions = (0, _index2.getDefaultOptions)();\n const locale =\n options?.locale ?? defaultOptions.locale ?? _index.defaultLocale;\n const format = options?.format ?? defaultFormat;\n const zero = options?.zero ?? false;\n const delimiter = options?.delimiter ?? \" \";\n\n if (!locale.formatDistance) {\n return \"\";\n }\n\n const result = format\n .reduce((acc, unit) => {\n const token = `x${unit.replace(/(^.)/, (m) => m.toUpperCase())}`;\n const value = duration[unit];\n if (value !== undefined && (zero || duration[unit])) {\n return acc.concat(locale.formatDistance(token, value));\n }\n return acc;\n }, [])\n .join(delimiter);\n\n return result;\n}\n", "\"use strict\";\nexports.formatISO = formatISO;\nvar _index = require(\"./_lib/addLeadingZeros.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link formatISO} function options.\n */\n\n/**\n * @name formatISO\n * @category Common Helpers\n * @summary Format the date according to the ISO 8601 standard (https://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a003169814.htm).\n *\n * @description\n * Return the formatted date string in ISO 8601 format. Options may be passed to control the parts and notations of the date.\n *\n * @param date - The original date\n * @param options - An object with options.\n *\n * @returns The formatted date string (in local time zone)\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 18 September 2019 in ISO 8601 format (local time zone is UTC):\n * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52))\n * //=> '2019-09-18T19:00:52Z'\n *\n * @example\n * // Represent 18 September 2019 in ISO 8601, short format (local time zone is UTC):\n * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52), { format: 'basic' })\n * //=> '20190918T190052'\n *\n * @example\n * // Represent 18 September 2019 in ISO 8601 format, date only:\n * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52), { representation: 'date' })\n * //=> '2019-09-18'\n *\n * @example\n * // Represent 18 September 2019 in ISO 8601 format, time only (local time zone is UTC):\n * const result = formatISO(new Date(2019, 8, 18, 19, 0, 52), { representation: 'time' })\n * //=> '19:00:52Z'\n */\nfunction formatISO(date, options) {\n const date_ = (0, _index2.toDate)(date, options?.in);\n\n if (isNaN(+date_)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n const format = options?.format ?? \"extended\";\n const representation = options?.representation ?? \"complete\";\n\n let result = \"\";\n let tzOffset = \"\";\n\n const dateDelimiter = format === \"extended\" ? \"-\" : \"\";\n const timeDelimiter = format === \"extended\" ? \":\" : \"\";\n\n // Representation is either 'date' or 'complete'\n if (representation !== \"time\") {\n const day = (0, _index.addLeadingZeros)(date_.getDate(), 2);\n const month = (0, _index.addLeadingZeros)(date_.getMonth() + 1, 2);\n const year = (0, _index.addLeadingZeros)(date_.getFullYear(), 4);\n\n // yyyyMMdd or yyyy-MM-dd.\n result = `${year}${dateDelimiter}${month}${dateDelimiter}${day}`;\n }\n\n // Representation is either 'time' or 'complete'\n if (representation !== \"date\") {\n // Add the timezone.\n const offset = date_.getTimezoneOffset();\n\n if (offset !== 0) {\n const absoluteOffset = Math.abs(offset);\n const hourOffset = (0, _index.addLeadingZeros)(\n Math.trunc(absoluteOffset / 60),\n 2,\n );\n const minuteOffset = (0, _index.addLeadingZeros)(absoluteOffset % 60, 2);\n // If less than 0, the sign is +, because it is ahead of time.\n const sign = offset < 0 ? \"+\" : \"-\";\n\n tzOffset = `${sign}${hourOffset}:${minuteOffset}`;\n } else {\n tzOffset = \"Z\";\n }\n\n const hour = (0, _index.addLeadingZeros)(date_.getHours(), 2);\n const minute = (0, _index.addLeadingZeros)(date_.getMinutes(), 2);\n const second = (0, _index.addLeadingZeros)(date_.getSeconds(), 2);\n\n // If there's also date, separate it with time with 'T'\n const separator = result === \"\" ? \"\" : \"T\";\n\n // Creates a time string consisting of hour, minute, and second, separated by delimiters, if defined.\n const time = [hour, minute, second].join(timeDelimiter);\n\n // HHmmss or HH:mm:ss.\n result = `${result}${separator}${time}${tzOffset}`;\n }\n\n return result;\n}\n", "\"use strict\";\nexports.formatISO9075 = formatISO9075;\nvar _index = require(\"./_lib/addLeadingZeros.cjs\");\nvar _index2 = require(\"./isValid.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link formatISO9075} function options.\n */\n\n/**\n * @name formatISO9075\n * @category Common Helpers\n * @summary Format the date according to the ISO 9075 standard (https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_get-format).\n *\n * @description\n * Return the formatted date string in ISO 9075 format. Options may be passed to control the parts and notations of the date.\n *\n * @param date - The original date\n * @param options - An object with options.\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 18 September 2019 in ISO 9075 format:\n * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52))\n * //=> '2019-09-18 19:00:52'\n *\n * @example\n * // Represent 18 September 2019 in ISO 9075, short format:\n * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { format: 'basic' })\n * //=> '20190918 190052'\n *\n * @example\n * // Represent 18 September 2019 in ISO 9075 format, date only:\n * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { representation: 'date' })\n * //=> '2019-09-18'\n *\n * @example\n * // Represent 18 September 2019 in ISO 9075 format, time only:\n * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { representation: 'time' })\n * //=> '19:00:52'\n */\nfunction formatISO9075(date, options) {\n const date_ = (0, _index3.toDate)(date, options?.in);\n\n if (!(0, _index2.isValid)(date_)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n const format = options?.format ?? \"extended\";\n const representation = options?.representation ?? \"complete\";\n\n let result = \"\";\n\n const dateDelimiter = format === \"extended\" ? \"-\" : \"\";\n const timeDelimiter = format === \"extended\" ? \":\" : \"\";\n\n // Representation is either 'date' or 'complete'\n if (representation !== \"time\") {\n const day = (0, _index.addLeadingZeros)(date_.getDate(), 2);\n const month = (0, _index.addLeadingZeros)(date_.getMonth() + 1, 2);\n const year = (0, _index.addLeadingZeros)(date_.getFullYear(), 4);\n\n // yyyyMMdd or yyyy-MM-dd.\n result = `${year}${dateDelimiter}${month}${dateDelimiter}${day}`;\n }\n\n // Representation is either 'time' or 'complete'\n if (representation !== \"date\") {\n const hour = (0, _index.addLeadingZeros)(date_.getHours(), 2);\n const minute = (0, _index.addLeadingZeros)(date_.getMinutes(), 2);\n const second = (0, _index.addLeadingZeros)(date_.getSeconds(), 2);\n\n // If there's also date, separate it with time with a space\n const separator = result === \"\" ? \"\" : \" \";\n\n // HHmmss or HH:mm:ss.\n result = `${result}${separator}${hour}${timeDelimiter}${minute}${timeDelimiter}${second}`;\n }\n\n return result;\n}\n", "\"use strict\";\nexports.formatISODuration = formatISODuration;\n\n/**\n * @name formatISODuration\n * @category Common Helpers\n * @summary Format a duration object according as ISO 8601 duration string\n *\n * @description\n * Format a duration object according to the ISO 8601 duration standard (https://www.digi.com/resources/documentation/digidocs//90001488-13/reference/r_iso_8601_duration_format.htm)\n *\n * @param duration - The duration to format\n *\n * @returns The ISO 8601 duration string\n *\n * @example\n * // Format the given duration as ISO 8601 string\n * const result = formatISODuration({\n * years: 39,\n * months: 2,\n * days: 20,\n * hours: 7,\n * minutes: 5,\n * seconds: 0\n * })\n * //=> 'P39Y2M20DT0H0M0S'\n */\nfunction formatISODuration(duration) {\n const {\n years = 0,\n months = 0,\n days = 0,\n hours = 0,\n minutes = 0,\n seconds = 0,\n } = duration;\n\n return `P${years}Y${months}M${days}DT${hours}H${minutes}M${seconds}S`;\n}\n", "\"use strict\";\nexports.formatRFC3339 = formatRFC3339;\nvar _index = require(\"./_lib/addLeadingZeros.cjs\");\nvar _index2 = require(\"./isValid.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link formatRFC3339} function options.\n */\n\n/**\n * @name formatRFC3339\n * @category Common Helpers\n * @summary Format the date according to the RFC 3339 standard (https://tools.ietf.org/html/rfc3339#section-5.6).\n *\n * @description\n * Return the formatted date string in RFC 3339 format. Options may be passed to control the parts and notations of the date.\n *\n * @param date - The original date\n * @param options - An object with options.\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 18 September 2019 in RFC 3339 format:\n * formatRFC3339(new Date(2019, 8, 18, 19, 0, 52))\n * //=> '2019-09-18T19:00:52Z'\n *\n * @example\n * // Represent 18 September 2019 in RFC 3339 format, 3 digits of second fraction\n * formatRFC3339(new Date(2019, 8, 18, 19, 0, 52, 234), {\n * fractionDigits: 3\n * })\n * //=> '2019-09-18T19:00:52.234Z'\n */\nfunction formatRFC3339(date, options) {\n const date_ = (0, _index3.toDate)(date, options?.in);\n\n if (!(0, _index2.isValid)(date_)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n const fractionDigits = options?.fractionDigits ?? 0;\n\n const day = (0, _index.addLeadingZeros)(date_.getDate(), 2);\n const month = (0, _index.addLeadingZeros)(date_.getMonth() + 1, 2);\n const year = date_.getFullYear();\n\n const hour = (0, _index.addLeadingZeros)(date_.getHours(), 2);\n const minute = (0, _index.addLeadingZeros)(date_.getMinutes(), 2);\n const second = (0, _index.addLeadingZeros)(date_.getSeconds(), 2);\n\n let fractionalSecond = \"\";\n if (fractionDigits > 0) {\n const milliseconds = date_.getMilliseconds();\n const fractionalSeconds = Math.trunc(\n milliseconds * Math.pow(10, fractionDigits - 3),\n );\n fractionalSecond =\n \".\" + (0, _index.addLeadingZeros)(fractionalSeconds, fractionDigits);\n }\n\n let offset = \"\";\n const tzOffset = date_.getTimezoneOffset();\n\n if (tzOffset !== 0) {\n const absoluteOffset = Math.abs(tzOffset);\n const hourOffset = (0, _index.addLeadingZeros)(\n Math.trunc(absoluteOffset / 60),\n 2,\n );\n const minuteOffset = (0, _index.addLeadingZeros)(absoluteOffset % 60, 2);\n // If less than 0, the sign is +, because it is ahead of time.\n const sign = tzOffset < 0 ? \"+\" : \"-\";\n\n offset = `${sign}${hourOffset}:${minuteOffset}`;\n } else {\n offset = \"Z\";\n }\n\n return `${year}-${month}-${day}T${hour}:${minute}:${second}${fractionalSecond}${offset}`;\n}\n", "\"use strict\";\nexports.formatRFC7231 = formatRFC7231;\nvar _index = require(\"./_lib/addLeadingZeros.cjs\");\nvar _index2 = require(\"./isValid.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\nconst days = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n\nconst months = [\n \"Jan\",\n \"Feb\",\n \"Mar\",\n \"Apr\",\n \"May\",\n \"Jun\",\n \"Jul\",\n \"Aug\",\n \"Sep\",\n \"Oct\",\n \"Nov\",\n \"Dec\",\n];\n\n/**\n * @name formatRFC7231\n * @category Common Helpers\n * @summary Format the date according to the RFC 7231 standard (https://tools.ietf.org/html/rfc7231#section-7.1.1.1).\n *\n * @description\n * Return the formatted date string in RFC 7231 format.\n * The result will always be in UTC timezone.\n *\n * @param date - The original date\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 18 September 2019 in RFC 7231 format:\n * const result = formatRFC7231(new Date(2019, 8, 18, 19, 0, 52))\n * //=> 'Wed, 18 Sep 2019 19:00:52 GMT'\n */\nfunction formatRFC7231(date) {\n const _date = (0, _index3.toDate)(date);\n\n if (!(0, _index2.isValid)(_date)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n const dayName = days[_date.getUTCDay()];\n const dayOfMonth = (0, _index.addLeadingZeros)(_date.getUTCDate(), 2);\n const monthName = months[_date.getUTCMonth()];\n const year = _date.getUTCFullYear();\n\n const hour = (0, _index.addLeadingZeros)(_date.getUTCHours(), 2);\n const minute = (0, _index.addLeadingZeros)(_date.getUTCMinutes(), 2);\n const second = (0, _index.addLeadingZeros)(_date.getUTCSeconds(), 2);\n\n // Result variables.\n return `${dayName}, ${dayOfMonth} ${monthName} ${year} ${hour}:${minute}:${second} GMT`;\n}\n", "\"use strict\";\nexports.formatRelative = formatRelative;\nvar _index = require(\"./_lib/defaultLocale.cjs\");\nvar _index2 = require(\"./_lib/defaultOptions.cjs\");\nvar _index3 = require(\"./_lib/normalizeDates.cjs\");\nvar _index4 = require(\"./differenceInCalendarDays.cjs\");\nvar _index5 = require(\"./format.cjs\");\n\n/**\n * The {@link formatRelative} function options.\n */\n\n/**\n * @name formatRelative\n * @category Common Helpers\n * @summary Represent the date in words relative to the given base date.\n *\n * @description\n * Represent the date in words relative to the given base date.\n *\n * | Distance to the base date | Result |\n * |---------------------------|---------------------------|\n * | Previous 6 days | last Sunday at 04:30 AM |\n * | Last day | yesterday at 04:30 AM |\n * | Same day | today at 04:30 AM |\n * | Next day | tomorrow at 04:30 AM |\n * | Next 6 days | Sunday at 04:30 AM |\n * | Other | 12/31/2017 |\n *\n * @param date - The date to format\n * @param baseDate - The date to compare with\n * @param options - An object with options\n *\n * @returns The date in words\n *\n * @throws `date` must not be Invalid Date\n * @throws `baseDate` must not be Invalid Date\n * @throws `options.locale` must contain `localize` property\n * @throws `options.locale` must contain `formatLong` property\n * @throws `options.locale` must contain `formatRelative` property\n *\n * @example\n * // Represent the date of 6 days ago in words relative to the given base date. In this example, today is Wednesday\n * const result = formatRelative(subDays(new Date(), 6), new Date())\n * //=> \"last Thursday at 12:45 AM\"\n */\nfunction formatRelative(date, baseDate, options) {\n const [date_, baseDate_] = (0, _index3.normalizeDates)(\n options?.in,\n date,\n baseDate,\n );\n\n const defaultOptions = (0, _index2.getDefaultOptions)();\n const locale =\n options?.locale ?? defaultOptions.locale ?? _index.defaultLocale;\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const diff = (0, _index4.differenceInCalendarDays)(date_, baseDate_);\n\n if (isNaN(diff)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n let token;\n if (diff < -6) {\n token = \"other\";\n } else if (diff < -1) {\n token = \"lastWeek\";\n } else if (diff < 0) {\n token = \"yesterday\";\n } else if (diff < 1) {\n token = \"today\";\n } else if (diff < 2) {\n token = \"tomorrow\";\n } else if (diff < 7) {\n token = \"nextWeek\";\n } else {\n token = \"other\";\n }\n\n const formatStr = locale.formatRelative(token, date_, baseDate_, {\n locale,\n weekStartsOn,\n });\n return (0, _index5.format)(date_, formatStr, { locale, weekStartsOn });\n}\n", "\"use strict\";\nexports.fromUnixTime = fromUnixTime;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link fromUnixTime} function options.\n */\n\n/**\n * @name fromUnixTime\n * @category Timestamp Helpers\n * @summary Create a date from a Unix timestamp.\n *\n * @description\n * Create a date from a Unix timestamp (in seconds). Decimal values will be discarded.\n *\n * @param unixTime - The given Unix timestamp (in seconds)\n * @param options - An object with options. Allows to pass a context.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n *\n * @returns The date\n *\n * @example\n * // Create the date 29 February 2012 11:45:05:\n * const result = fromUnixTime(1330515905)\n * //=> Wed Feb 29 2012 11:45:05\n */\nfunction fromUnixTime(unixTime, options) {\n return (0, _index.toDate)(unixTime * 1000, options?.in);\n}\n", "\"use strict\";\nexports.getDate = getDate;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getDate} function options.\n */\n\n/**\n * @name getDate\n * @category Day Helpers\n * @summary Get the day of the month of the given date.\n *\n * @description\n * Get the day of the month of the given date.\n *\n * @param date - The given date\n * @param options - An object with options.\n *\n * @returns The day of month\n *\n * @example\n * // Which day of the month is 29 February 2012?\n * const result = getDate(new Date(2012, 1, 29))\n * //=> 29\n */\nfunction getDate(date, options) {\n return (0, _index.toDate)(date, options?.in).getDate();\n}\n", "\"use strict\";\nexports.getDay = getDay;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getDay} function options.\n */\n\n/**\n * @name getDay\n * @category Weekday Helpers\n * @summary Get the day of the week of the given date.\n *\n * @description\n * Get the day of the week of the given date.\n *\n * @param date - The given date\n * @param options - The options\n *\n * @returns The day of week, 0 represents Sunday\n *\n * @example\n * // Which day of the week is 29 February 2012?\n * const result = getDay(new Date(2012, 1, 29))\n * //=> 3\n */\nfunction getDay(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay();\n}\n", "\"use strict\";\nexports.getDaysInMonth = getDaysInMonth;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getDaysInMonth} function options.\n */\n\n/**\n * @name getDaysInMonth\n * @category Month Helpers\n * @summary Get the number of days in a month of the given date.\n *\n * @description\n * Get the number of days in a month of the given date, considering the context if provided.\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The number of days in a month\n *\n * @example\n * // How many days are in February 2000?\n * const result = getDaysInMonth(new Date(2000, 1))\n * //=> 29\n */\nfunction getDaysInMonth(date, options) {\n const _date = (0, _index2.toDate)(date, options?.in);\n const year = _date.getFullYear();\n const monthIndex = _date.getMonth();\n const lastDayOfMonth = (0, _index.constructFrom)(_date, 0);\n lastDayOfMonth.setFullYear(year, monthIndex + 1, 0);\n lastDayOfMonth.setHours(0, 0, 0, 0);\n return lastDayOfMonth.getDate();\n}\n", "\"use strict\";\nexports.isLeapYear = isLeapYear;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name isLeapYear\n * @category Year Helpers\n * @summary Is the given date in the leap year?\n *\n * @description\n * Is the given date in the leap year?\n *\n * @param date - The date to check\n * @param options - The options object\n *\n * @returns The date is in the leap year\n *\n * @example\n * // Is 1 September 2012 in the leap year?\n * const result = isLeapYear(new Date(2012, 8, 1))\n * //=> true\n */\nfunction isLeapYear(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const year = _date.getFullYear();\n return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);\n}\n", "\"use strict\";\nexports.getDaysInYear = getDaysInYear;\nvar _index = require(\"./isLeapYear.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getDaysInYear} function options.\n */\n\n/**\n * @name getDaysInYear\n * @category Year Helpers\n * @summary Get the number of days in a year of the given date.\n *\n * @description\n * Get the number of days in a year of the given date.\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The number of days in a year\n *\n * @example\n * // How many days are in 2012?\n * const result = getDaysInYear(new Date(2012, 0, 1))\n * //=> 366\n */\nfunction getDaysInYear(date, options) {\n const _date = (0, _index2.toDate)(date, options?.in);\n if (Number.isNaN(+_date)) return NaN;\n return (0, _index.isLeapYear)(_date) ? 366 : 365;\n}\n", "\"use strict\";\nexports.getDecade = getDecade;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getDecade} function options.\n */\n\n/**\n * @name getDecade\n * @category Decade Helpers\n * @summary Get the decade of the given date.\n *\n * @description\n * Get the decade of the given date.\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The year of decade\n *\n * @example\n * // Which decade belongs 27 November 1942?\n * const result = getDecade(new Date(1942, 10, 27))\n * //=> 1940\n */\nfunction getDecade(date, options) {\n // TODO: Switch to more technical definition in of decades that start with 1\n // end with 0. I.e. 2001-2010 instead of current 2000-2009. It's a breaking\n // change, so it can only be done in 4.0.\n const _date = (0, _index.toDate)(date, options?.in);\n const year = _date.getFullYear();\n const decade = Math.floor(year / 10) * 10;\n return decade;\n}\n", "\"use strict\";\nexports.getDefaultOptions = getDefaultOptions;\n\nvar _index = require(\"./_lib/defaultOptions.cjs\");\n\n/**\n * @name getDefaultOptions\n * @category Common Helpers\n * @summary Get default options.\n * @pure false\n *\n * @description\n * Returns an object that contains defaults for\n * `options.locale`, `options.weekStartsOn` and `options.firstWeekContainsDate`\n * arguments for all functions.\n *\n * You can change these with [setDefaultOptions](https://date-fns.org/docs/setDefaultOptions).\n *\n * @returns The default options\n *\n * @example\n * const result = getDefaultOptions()\n * //=> {}\n *\n * @example\n * setDefaultOptions({ weekStarsOn: 1, firstWeekContainsDate: 4 })\n * const result = getDefaultOptions()\n * //=> { weekStarsOn: 1, firstWeekContainsDate: 4 }\n */\nfunction getDefaultOptions() {\n return Object.assign({}, (0, _index.getDefaultOptions)());\n}\n", "\"use strict\";\nexports.getHours = getHours;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getHours} function options.\n */\n\n/**\n * @name getHours\n * @category Hour Helpers\n * @summary Get the hours of the given date.\n *\n * @description\n * Get the hours of the given date.\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The hours\n *\n * @example\n * // Get the hours of 29 February 2012 11:45:00:\n * const result = getHours(new Date(2012, 1, 29, 11, 45))\n * //=> 11\n */\nfunction getHours(date, options) {\n return (0, _index.toDate)(date, options?.in).getHours();\n}\n", "\"use strict\";\nexports.getISODay = getISODay;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getISODay} function options.\n */\n\n/**\n * @name getISODay\n * @category Weekday Helpers\n * @summary Get the day of the ISO week of the given date.\n *\n * @description\n * Get the day of the ISO week of the given date,\n * which is 7 for Sunday, 1 for Monday etc.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The day of ISO week\n *\n * @example\n * // Which day of the ISO week is 26 February 2012?\n * const result = getISODay(new Date(2012, 1, 26))\n * //=> 7\n */\nfunction getISODay(date, options) {\n const day = (0, _index.toDate)(date, options?.in).getDay();\n return day === 0 ? 7 : day;\n}\n", "\"use strict\";\nexports.getISOWeeksInYear = getISOWeeksInYear;\nvar _index = require(\"./addWeeks.cjs\");\nvar _index2 = require(\"./constants.cjs\");\nvar _index3 = require(\"./startOfISOWeekYear.cjs\");\n\n/**\n * The {@link getISOWeeksInYear} function options.\n */\n\n/**\n * @name getISOWeeksInYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Get the number of weeks in an ISO week-numbering year of the given date.\n *\n * @description\n * Get the number of weeks in an ISO week-numbering year of the given date.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The number of ISO weeks in a year\n *\n * @example\n * // How many weeks are in ISO week-numbering year 2015?\n * const result = getISOWeeksInYear(new Date(2015, 1, 11))\n * //=> 53\n */\nfunction getISOWeeksInYear(date, options) {\n const thisYear = (0, _index3.startOfISOWeekYear)(date, options);\n const nextYear = (0, _index3.startOfISOWeekYear)(\n (0, _index.addWeeks)(thisYear, 60),\n );\n const diff = +nextYear - +thisYear;\n\n // Round the number of weeks to the nearest integer because the number of\n // milliseconds in a week is not constant (e.g. it's different in the week of\n // the daylight saving time clock shift).\n return Math.round(diff / _index2.millisecondsInWeek);\n}\n", "\"use strict\";\nexports.getMilliseconds = getMilliseconds;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name getMilliseconds\n * @category Millisecond Helpers\n * @summary Get the milliseconds of the given date.\n *\n * @description\n * Get the milliseconds of the given date.\n *\n * @param date - The given date\n *\n * @returns The milliseconds\n *\n * @example\n * // Get the milliseconds of 29 February 2012 11:45:05.123:\n * const result = getMilliseconds(new Date(2012, 1, 29, 11, 45, 5, 123))\n * //=> 123\n */\nfunction getMilliseconds(date) {\n return (0, _index.toDate)(date).getMilliseconds();\n}\n", "\"use strict\";\nexports.getMinutes = getMinutes;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getMinutes} function options.\n */\n\n/**\n * @name getMinutes\n * @category Minute Helpers\n * @summary Get the minutes of the given date.\n *\n * @description\n * Get the minutes of the given date.\n *\n * @param date - The given date\n * @param options - The options\n *\n * @returns The minutes\n *\n * @example\n * // Get the minutes of 29 February 2012 11:45:05:\n * const result = getMinutes(new Date(2012, 1, 29, 11, 45, 5))\n * //=> 45\n */\nfunction getMinutes(date, options) {\n return (0, _index.toDate)(date, options?.in).getMinutes();\n}\n", "\"use strict\";\nexports.getMonth = getMonth;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getMonth} function options.\n */\n\n/**\n * @name getMonth\n * @category Month Helpers\n * @summary Get the month of the given date.\n *\n * @description\n * Get the month of the given date.\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The month index (0-11)\n *\n * @example\n * // Which month is 29 February 2012?\n * const result = getMonth(new Date(2012, 1, 29))\n * //=> 1\n */\nfunction getMonth(date, options) {\n return (0, _index.toDate)(date, options?.in).getMonth();\n}\n", "\"use strict\";\nexports.getOverlappingDaysInIntervals = getOverlappingDaysInIntervals;\nvar _index = require(\"./_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _index2 = require(\"./constants.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * @name getOverlappingDaysInIntervals\n * @category Interval Helpers\n * @summary Get the number of days that overlap in two time intervals\n *\n * @description\n * Get the number of days that overlap in two time intervals. It uses the time\n * between dates to calculate the number of days, rounding it up to include\n * partial days.\n *\n * Two equal 0-length intervals will result in 0. Two equal 1ms intervals will\n * result in 1.\n *\n * @param intervalLeft - The first interval to compare.\n * @param intervalRight - The second interval to compare.\n * @param options - An object with options\n *\n * @returns The number of days that overlap in two time intervals\n *\n * @example\n * // For overlapping time intervals adds 1 for each started overlapping day:\n * getOverlappingDaysInIntervals(\n * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },\n * { start: new Date(2014, 0, 17), end: new Date(2014, 0, 21) }\n * )\n * //=> 3\n *\n * @example\n * // For non-overlapping time intervals returns 0:\n * getOverlappingDaysInIntervals(\n * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },\n * { start: new Date(2014, 0, 21), end: new Date(2014, 0, 22) }\n * )\n * //=> 0\n */\n\nfunction getOverlappingDaysInIntervals(intervalLeft, intervalRight) {\n const [leftStart, leftEnd] = [\n +(0, _index3.toDate)(intervalLeft.start),\n +(0, _index3.toDate)(intervalLeft.end),\n ].sort((a, b) => a - b);\n const [rightStart, rightEnd] = [\n +(0, _index3.toDate)(intervalRight.start),\n +(0, _index3.toDate)(intervalRight.end),\n ].sort((a, b) => a - b);\n\n // Prevent NaN result if intervals don't overlap at all.\n const isOverlapping = leftStart < rightEnd && rightStart < leftEnd;\n if (!isOverlapping) return 0;\n\n // Remove the timezone offset to negate the DST effect on calculations.\n const overlapLeft = rightStart < leftStart ? leftStart : rightStart;\n const left =\n overlapLeft - (0, _index.getTimezoneOffsetInMilliseconds)(overlapLeft);\n const overlapRight = rightEnd > leftEnd ? leftEnd : rightEnd;\n const right =\n overlapRight - (0, _index.getTimezoneOffsetInMilliseconds)(overlapRight);\n\n // Ceil the number to include partial days too.\n return Math.ceil((right - left) / _index2.millisecondsInDay);\n}\n", "\"use strict\";\nexports.getSeconds = getSeconds;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name getSeconds\n * @category Second Helpers\n * @summary Get the seconds of the given date.\n *\n * @description\n * Get the seconds of the given date.\n *\n * @param date - The given date\n *\n * @returns The seconds\n *\n * @example\n * // Get the seconds of 29 February 2012 11:45:05.123:\n * const result = getSeconds(new Date(2012, 1, 29, 11, 45, 5, 123))\n * //=> 5\n */\nfunction getSeconds(date) {\n return (0, _index.toDate)(date).getSeconds();\n}\n", "\"use strict\";\nexports.getTime = getTime;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name getTime\n * @category Timestamp Helpers\n * @summary Get the milliseconds timestamp of the given date.\n *\n * @description\n * Get the milliseconds timestamp of the given date.\n *\n * @param date - The given date\n *\n * @returns The timestamp\n *\n * @example\n * // Get the timestamp of 29 February 2012 11:45:05.123:\n * const result = getTime(new Date(2012, 1, 29, 11, 45, 5, 123))\n * //=> 1330515905123\n */\nfunction getTime(date) {\n return +(0, _index.toDate)(date);\n}\n", "\"use strict\";\nexports.getUnixTime = getUnixTime;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name getUnixTime\n * @category Timestamp Helpers\n * @summary Get the seconds timestamp of the given date.\n *\n * @description\n * Get the seconds timestamp of the given date.\n *\n * @param date - The given date\n *\n * @returns The timestamp\n *\n * @example\n * // Get the timestamp of 29 February 2012 11:45:05 CET:\n * const result = getUnixTime(new Date(2012, 1, 29, 11, 45, 5))\n * //=> 1330512305\n */\nfunction getUnixTime(date) {\n return Math.trunc(+(0, _index.toDate)(date) / 1000);\n}\n", "\"use strict\";\nexports.getWeekOfMonth = getWeekOfMonth;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./getDate.cjs\");\nvar _index3 = require(\"./getDay.cjs\");\nvar _index4 = require(\"./startOfMonth.cjs\");\nvar _index5 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getWeekOfMonth} function options.\n */\n\n/**\n * @name getWeekOfMonth\n * @category Week Helpers\n * @summary Get the week of the month of the given date.\n *\n * @description\n * Get the week of the month of the given date.\n *\n * @param date - The given date\n * @param options - An object with options.\n *\n * @returns The week of month\n *\n * @example\n * // Which week of the month is 9 November 2017?\n * const result = getWeekOfMonth(new Date(2017, 10, 9))\n * //=> 2\n */\nfunction getWeekOfMonth(date, options) {\n const defaultOptions = (0, _index.getDefaultOptions)();\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const currentDayOfMonth = (0, _index2.getDate)(\n (0, _index5.toDate)(date, options?.in),\n );\n if (isNaN(currentDayOfMonth)) return NaN;\n\n const startWeekDay = (0, _index3.getDay)(\n (0, _index4.startOfMonth)(date, options),\n );\n\n let lastDayOfFirstWeek = weekStartsOn - startWeekDay;\n if (lastDayOfFirstWeek <= 0) lastDayOfFirstWeek += 7;\n\n const remainingDaysAfterFirstWeek = currentDayOfMonth - lastDayOfFirstWeek;\n return Math.ceil(remainingDaysAfterFirstWeek / 7) + 1;\n}\n", "\"use strict\";\nexports.lastDayOfMonth = lastDayOfMonth;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link lastDayOfMonth} function options.\n */\n\n/**\n * @name lastDayOfMonth\n * @category Month Helpers\n * @summary Return the last day of a month for the given date.\n *\n * @description\n * Return the last day of a month for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The last day of a month\n *\n * @example\n * // The last day of a month for 2 September 2014 11:55:00:\n * const result = lastDayOfMonth(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 30 2014 00:00:00\n */\nfunction lastDayOfMonth(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const month = _date.getMonth();\n _date.setFullYear(_date.getFullYear(), month + 1, 0);\n _date.setHours(0, 0, 0, 0);\n return (0, _index.toDate)(_date, options?.in);\n}\n", "\"use strict\";\nexports.getWeeksInMonth = getWeeksInMonth;\nvar _index = require(\"./differenceInCalendarWeeks.cjs\");\nvar _index2 = require(\"./lastDayOfMonth.cjs\");\nvar _index3 = require(\"./startOfMonth.cjs\");\nvar _index4 = require(\"./toDate.cjs\");\n\n/**\n * The {@link getWeeksInMonth} function options.\n */\n\n/**\n * @name getWeeksInMonth\n * @category Week Helpers\n * @summary Get the number of calendar weeks a month spans.\n *\n * @description\n * Get the number of calendar weeks the month in the given date spans.\n *\n * @param date - The given date\n * @param options - An object with options.\n *\n * @returns The number of calendar weeks\n *\n * @example\n * // How many calendar weeks does February 2015 span?\n * const result = getWeeksInMonth(new Date(2015, 1, 8))\n * //=> 4\n *\n * @example\n * // If the week starts on Monday,\n * // how many calendar weeks does July 2017 span?\n * const result = getWeeksInMonth(new Date(2017, 6, 5), { weekStartsOn: 1 })\n * //=> 6\n */\nfunction getWeeksInMonth(date, options) {\n const contextDate = (0, _index4.toDate)(date, options?.in);\n return (\n (0, _index.differenceInCalendarWeeks)(\n (0, _index2.lastDayOfMonth)(contextDate, options),\n (0, _index3.startOfMonth)(contextDate, options),\n options,\n ) + 1\n );\n}\n", "\"use strict\";\nexports.getYear = getYear;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link getYear} function options.\n */\n\n/**\n * @name getYear\n * @category Year Helpers\n * @summary Get the year of the given date.\n *\n * @description\n * Get the year of the given date.\n *\n * @param date - The given date\n * @param options - An object with options\n *\n * @returns The year\n *\n * @example\n * // Which year is 2 July 2014?\n * const result = getYear(new Date(2014, 6, 2))\n * //=> 2014\n */\nfunction getYear(date, options) {\n return (0, _index.toDate)(date, options?.in).getFullYear();\n}\n", "\"use strict\";\nexports.hoursToMilliseconds = hoursToMilliseconds;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name hoursToMilliseconds\n * @category Conversion Helpers\n * @summary Convert hours to milliseconds.\n *\n * @description\n * Convert a number of hours to a full number of milliseconds.\n *\n * @param hours - number of hours to be converted\n *\n * @returns The number of hours converted to milliseconds\n *\n * @example\n * // Convert 2 hours to milliseconds:\n * const result = hoursToMilliseconds(2)\n * //=> 7200000\n */\nfunction hoursToMilliseconds(hours) {\n return Math.trunc(hours * _index.millisecondsInHour);\n}\n", "\"use strict\";\nexports.hoursToMinutes = hoursToMinutes;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name hoursToMinutes\n * @category Conversion Helpers\n * @summary Convert hours to minutes.\n *\n * @description\n * Convert a number of hours to a full number of minutes.\n *\n * @param hours - number of hours to be converted\n *\n * @returns The number of hours converted in minutes\n *\n * @example\n * // Convert 2 hours to minutes:\n * const result = hoursToMinutes(2)\n * //=> 120\n */\nfunction hoursToMinutes(hours) {\n return Math.trunc(hours * _index.minutesInHour);\n}\n", "\"use strict\";\nexports.hoursToSeconds = hoursToSeconds;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name hoursToSeconds\n * @category Conversion Helpers\n * @summary Convert hours to seconds.\n *\n * @description\n * Convert a number of hours to a full number of seconds.\n *\n * @param hours - The number of hours to be converted\n *\n * @returns The number of hours converted in seconds\n *\n * @example\n * // Convert 2 hours to seconds:\n * const result = hoursToSeconds(2)\n * //=> 7200\n */\nfunction hoursToSeconds(hours) {\n return Math.trunc(hours * _index.secondsInHour);\n}\n", "\"use strict\";\nexports.interval = interval;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\n\n/**\n * The {@link interval} function options.\n */\n\n/**\n * The {@link interval} function result type. It resolves the proper data type.\n * It uses the first argument date object type, starting from the start argument,\n * then the end interval date. If a context function is passed, it uses the context\n * function return type.\n */\n\n/**\n * @name interval\n * @category Interval Helpers\n * @summary Creates an interval object and validates its values.\n *\n * @description\n * Creates a normalized interval object and validates its values. If the interval is invalid, an exception is thrown.\n *\n * @typeParam StartDate - Start date type.\n * @typeParam EndDate - End date type.\n * @typeParam Options - Options type.\n *\n * @param start - The start of the interval.\n * @param end - The end of the interval.\n * @param options - The options object.\n *\n * @throws `Start date is invalid` when `start` is invalid.\n * @throws `End date is invalid` when `end` is invalid.\n * @throws `End date must be after start date` when end is before `start` and `options.assertPositive` is true.\n *\n * @returns The normalized and validated interval object.\n */\nfunction interval(start, end, options) {\n const [_start, _end] = (0, _index.normalizeDates)(options?.in, start, end);\n\n if (isNaN(+_start)) throw new TypeError(\"Start date is invalid\");\n if (isNaN(+_end)) throw new TypeError(\"End date is invalid\");\n\n if (options?.assertPositive && +_start > +_end)\n throw new TypeError(\"End date must be after start date\");\n\n return { start: _start, end: _end };\n}\n", "\"use strict\";\nexports.intervalToDuration = intervalToDuration;\nvar _index = require(\"./_lib/normalizeInterval.cjs\");\nvar _index2 = require(\"./add.cjs\");\nvar _index3 = require(\"./differenceInDays.cjs\");\nvar _index4 = require(\"./differenceInHours.cjs\");\nvar _index5 = require(\"./differenceInMinutes.cjs\");\nvar _index6 = require(\"./differenceInMonths.cjs\");\nvar _index7 = require(\"./differenceInSeconds.cjs\");\nvar _index8 = require(\"./differenceInYears.cjs\");\n\n/**\n * The {@link intervalToDuration} function options.\n */\n\n/**\n * @name intervalToDuration\n * @category Common Helpers\n * @summary Convert interval to duration\n *\n * @description\n * Convert an interval object to a duration object.\n *\n * @param interval - The interval to convert to duration\n * @param options - The context options\n *\n * @returns The duration object\n *\n * @example\n * // Get the duration between January 15, 1929 and April 4, 1968.\n * intervalToDuration({\n * start: new Date(1929, 0, 15, 12, 0, 0),\n * end: new Date(1968, 3, 4, 19, 5, 0)\n * });\n * //=> { years: 39, months: 2, days: 20, hours: 7, minutes: 5, seconds: 0 }\n */\nfunction intervalToDuration(interval, options) {\n const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);\n const duration = {};\n\n const years = (0, _index8.differenceInYears)(end, start);\n if (years) duration.years = years;\n\n const remainingMonths = (0, _index2.add)(start, { years: duration.years });\n const months = (0, _index6.differenceInMonths)(end, remainingMonths);\n if (months) duration.months = months;\n\n const remainingDays = (0, _index2.add)(remainingMonths, {\n months: duration.months,\n });\n const days = (0, _index3.differenceInDays)(end, remainingDays);\n if (days) duration.days = days;\n\n const remainingHours = (0, _index2.add)(remainingDays, {\n days: duration.days,\n });\n const hours = (0, _index4.differenceInHours)(end, remainingHours);\n if (hours) duration.hours = hours;\n\n const remainingMinutes = (0, _index2.add)(remainingHours, {\n hours: duration.hours,\n });\n const minutes = (0, _index5.differenceInMinutes)(end, remainingMinutes);\n if (minutes) duration.minutes = minutes;\n\n const remainingSeconds = (0, _index2.add)(remainingMinutes, {\n minutes: duration.minutes,\n });\n const seconds = (0, _index7.differenceInSeconds)(end, remainingSeconds);\n if (seconds) duration.seconds = seconds;\n\n return duration;\n}\n", "\"use strict\";\nexports.intlFormat = intlFormat;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The locale string (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).\n * @deprecated\n *\n * [TODO] Remove in v4\n */\n\n/**\n * The format options (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options)\n */\n\n/**\n * The locale options.\n */\n\n/**\n * @name intlFormat\n * @category Common Helpers\n * @summary Format the date with Intl.DateTimeFormat (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat).\n *\n * @description\n * Return the formatted date string in the given format.\n * The method uses [`Intl.DateTimeFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) inside.\n * formatOptions are the same as [`Intl.DateTimeFormat` options](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat#using_options)\n *\n * > \u26A0\uFE0F Please note that before Node version 13.0.0, only the locale data for en-US is available by default.\n *\n * @param date - The date to format\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 4 October 2019 in middle-endian format:\n * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456))\n * //=> 10/4/2019\n */\n\n/**\n * @param date - The date to format\n * @param localeOptions - An object with locale\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 4 October 2019 in Korean.\n * // Convert the date with locale's options.\n * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456), {\n * locale: 'ko-KR',\n * })\n * //=> 2019. 10. 4.\n */\n\n/**\n * @param date - The date to format\n * @param formatOptions - The format options\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 4 October 2019.\n * // Convert the date with format's options.\n * const result = intlFormat.default(new Date(2019, 9, 4, 12, 30, 13, 456), {\n * year: 'numeric',\n * month: 'numeric',\n * day: 'numeric',\n * hour: 'numeric',\n * })\n * //=> 10/4/2019, 12 PM\n */\n\n/**\n * @param date - The date to format\n * @param formatOptions - The format options\n * @param localeOptions - An object with locale\n *\n * @returns The formatted date string\n *\n * @throws `date` must not be Invalid Date\n *\n * @example\n * // Represent 4 October 2019 in German.\n * // Convert the date with format's options and locale's options.\n * const result = intlFormat(new Date(2019, 9, 4, 12, 30, 13, 456), {\n * weekday: 'long',\n * year: 'numeric',\n * month: 'long',\n * day: 'numeric',\n * }, {\n * locale: 'de-DE',\n * })\n * //=> Freitag, 4. Oktober 2019\n */\n\nfunction intlFormat(date, formatOrLocale, localeOptions) {\n let formatOptions;\n\n if (isFormatOptions(formatOrLocale)) {\n formatOptions = formatOrLocale;\n } else {\n localeOptions = formatOrLocale;\n }\n\n return new Intl.DateTimeFormat(localeOptions?.locale, formatOptions).format(\n (0, _index.toDate)(date),\n );\n}\n\nfunction isFormatOptions(opts) {\n return opts !== undefined && !(\"locale\" in opts);\n}\n", "\"use strict\";\nexports.intlFormatDistance = intlFormatDistance;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./constants.cjs\");\n\nvar _index3 = require(\"./differenceInCalendarDays.cjs\");\nvar _index4 = require(\"./differenceInCalendarMonths.cjs\");\nvar _index5 = require(\"./differenceInCalendarQuarters.cjs\");\nvar _index6 = require(\"./differenceInCalendarWeeks.cjs\");\nvar _index7 = require(\"./differenceInCalendarYears.cjs\");\nvar _index8 = require(\"./differenceInHours.cjs\");\nvar _index9 = require(\"./differenceInMinutes.cjs\");\nvar _index10 = require(\"./differenceInSeconds.cjs\");\n\n/**\n * The {@link intlFormatDistance} function options.\n */\n\n/**\n * The unit used to format the distance in {@link intlFormatDistance}.\n */\n\n/**\n * @name intlFormatDistance\n * @category Common Helpers\n * @summary Formats distance between two dates in a human-readable format\n * @description\n * The function calculates the difference between two dates and formats it as a human-readable string.\n *\n * The function will pick the most appropriate unit depending on the distance between dates. For example, if the distance is a few hours, it might return `x hours`. If the distance is a few months, it might return `x months`.\n *\n * You can also specify a unit to force using it regardless of the distance to get a result like `123456 hours`.\n *\n * See the table below for the unit picking logic:\n *\n * | Distance between dates | Result (past) | Result (future) |\n * | ---------------------- | -------------- | --------------- |\n * | 0 seconds | now | now |\n * | 1-59 seconds | X seconds ago | in X seconds |\n * | 1-59 minutes | X minutes ago | in X minutes |\n * | 1-23 hours | X hours ago | in X hours |\n * | 1 day | yesterday | tomorrow |\n * | 2-6 days | X days ago | in X days |\n * | 7 days | last week | next week |\n * | 8 days-1 month | X weeks ago | in X weeks |\n * | 1 month | last month | next month |\n * | 2-3 months | X months ago | in X months |\n * | 1 quarter | last quarter | next quarter |\n * | 2-3 quarters | X quarters ago | in X quarters |\n * | 1 year | last year | next year |\n * | 2+ years | X years ago | in X years |\n *\n * @param laterDate - The date\n * @param earlierDate - The date to compare with.\n * @param options - An object with options.\n * See MDN for details [Locale identification and negotiation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation)\n * The narrow one could be similar to the short one for some locales.\n *\n * @returns The distance in words according to language-sensitive relative time formatting.\n *\n * @throws `date` must not be Invalid Date\n * @throws `baseDate` must not be Invalid Date\n * @throws `options.unit` must not be invalid Unit\n * @throws `options.locale` must not be invalid locale\n * @throws `options.localeMatcher` must not be invalid localeMatcher\n * @throws `options.numeric` must not be invalid numeric\n * @throws `options.style` must not be invalid style\n *\n * @example\n * // What is the distance between the dates when the fist date is after the second?\n * intlFormatDistance(\n * new Date(1986, 3, 4, 11, 30, 0),\n * new Date(1986, 3, 4, 10, 30, 0)\n * )\n * //=> 'in 1 hour'\n *\n * // What is the distance between the dates when the fist date is before the second?\n * intlFormatDistance(\n * new Date(1986, 3, 4, 10, 30, 0),\n * new Date(1986, 3, 4, 11, 30, 0)\n * )\n * //=> '1 hour ago'\n *\n * @example\n * // Use the unit option to force the function to output the result in quarters. Without setting it, the example would return \"next year\"\n * intlFormatDistance(\n * new Date(1987, 6, 4, 10, 30, 0),\n * new Date(1986, 3, 4, 10, 30, 0),\n * { unit: 'quarter' }\n * )\n * //=> 'in 5 quarters'\n *\n * @example\n * // Use the locale option to get the result in Spanish. Without setting it, the example would return \"in 1 hour\".\n * intlFormatDistance(\n * new Date(1986, 3, 4, 11, 30, 0),\n * new Date(1986, 3, 4, 10, 30, 0),\n * { locale: 'es' }\n * )\n * //=> 'dentro de 1 hora'\n *\n * @example\n * // Use the numeric option to force the function to use numeric values. Without setting it, the example would return \"tomorrow\".\n * intlFormatDistance(\n * new Date(1986, 3, 5, 11, 30, 0),\n * new Date(1986, 3, 4, 11, 30, 0),\n * { numeric: 'always' }\n * )\n * //=> 'in 1 day'\n *\n * @example\n * // Use the style option to force the function to use short values. Without setting it, the example would return \"in 2 years\".\n * intlFormatDistance(\n * new Date(1988, 3, 4, 11, 30, 0),\n * new Date(1986, 3, 4, 11, 30, 0),\n * { style: 'short' }\n * )\n * //=> 'in 2 yr'\n */\nfunction intlFormatDistance(laterDate, earlierDate, options) {\n let value = 0;\n let unit;\n\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n\n if (!options?.unit) {\n // Get the unit based on diffInSeconds calculations if no unit is specified\n const diffInSeconds = (0, _index10.differenceInSeconds)(\n laterDate_,\n earlierDate_,\n ); // The smallest unit\n\n if (Math.abs(diffInSeconds) < _index2.secondsInMinute) {\n value = (0, _index10.differenceInSeconds)(laterDate_, earlierDate_);\n unit = \"second\";\n } else if (Math.abs(diffInSeconds) < _index2.secondsInHour) {\n value = (0, _index9.differenceInMinutes)(laterDate_, earlierDate_);\n unit = \"minute\";\n } else if (\n Math.abs(diffInSeconds) < _index2.secondsInDay &&\n Math.abs(\n (0, _index3.differenceInCalendarDays)(laterDate_, earlierDate_),\n ) < 1\n ) {\n value = (0, _index8.differenceInHours)(laterDate_, earlierDate_);\n unit = \"hour\";\n } else if (\n Math.abs(diffInSeconds) < _index2.secondsInWeek &&\n (value = (0, _index3.differenceInCalendarDays)(\n laterDate_,\n earlierDate_,\n )) &&\n Math.abs(value) < 7\n ) {\n unit = \"day\";\n } else if (Math.abs(diffInSeconds) < _index2.secondsInMonth) {\n value = (0, _index6.differenceInCalendarWeeks)(laterDate_, earlierDate_);\n unit = \"week\";\n } else if (Math.abs(diffInSeconds) < _index2.secondsInQuarter) {\n value = (0, _index4.differenceInCalendarMonths)(laterDate_, earlierDate_);\n unit = \"month\";\n } else if (Math.abs(diffInSeconds) < _index2.secondsInYear) {\n if (\n (0, _index5.differenceInCalendarQuarters)(laterDate_, earlierDate_) < 4\n ) {\n // To filter out cases that are less than a year but match 4 quarters\n value = (0, _index5.differenceInCalendarQuarters)(\n laterDate_,\n earlierDate_,\n );\n unit = \"quarter\";\n } else {\n value = (0, _index7.differenceInCalendarYears)(\n laterDate_,\n earlierDate_,\n );\n unit = \"year\";\n }\n } else {\n value = (0, _index7.differenceInCalendarYears)(laterDate_, earlierDate_);\n unit = \"year\";\n }\n } else {\n // Get the value if unit is specified\n unit = options?.unit;\n if (unit === \"second\") {\n value = (0, _index10.differenceInSeconds)(laterDate_, earlierDate_);\n } else if (unit === \"minute\") {\n value = (0, _index9.differenceInMinutes)(laterDate_, earlierDate_);\n } else if (unit === \"hour\") {\n value = (0, _index8.differenceInHours)(laterDate_, earlierDate_);\n } else if (unit === \"day\") {\n value = (0, _index3.differenceInCalendarDays)(laterDate_, earlierDate_);\n } else if (unit === \"week\") {\n value = (0, _index6.differenceInCalendarWeeks)(laterDate_, earlierDate_);\n } else if (unit === \"month\") {\n value = (0, _index4.differenceInCalendarMonths)(laterDate_, earlierDate_);\n } else if (unit === \"quarter\") {\n value = (0, _index5.differenceInCalendarQuarters)(\n laterDate_,\n earlierDate_,\n );\n } else if (unit === \"year\") {\n value = (0, _index7.differenceInCalendarYears)(laterDate_, earlierDate_);\n }\n }\n\n const rtf = new Intl.RelativeTimeFormat(options?.locale, {\n numeric: \"auto\",\n ...options,\n });\n\n return rtf.format(value, unit);\n}\n", "\"use strict\";\nexports.isAfter = isAfter;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name isAfter\n * @category Common Helpers\n * @summary Is the first date after the second one?\n *\n * @description\n * Is the first date after the second one?\n *\n * @param date - The date that should be after the other one to return true\n * @param dateToCompare - The date to compare with\n *\n * @returns The first date is after the second date\n *\n * @example\n * // Is 10 July 1989 after 11 February 1987?\n * const result = isAfter(new Date(1989, 6, 10), new Date(1987, 1, 11))\n * //=> true\n */\nfunction isAfter(date, dateToCompare) {\n return +(0, _index.toDate)(date) > +(0, _index.toDate)(dateToCompare);\n}\n", "\"use strict\";\nexports.isBefore = isBefore;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name isBefore\n * @category Common Helpers\n * @summary Is the first date before the second one?\n *\n * @description\n * Is the first date before the second one?\n *\n * @param date - The date that should be before the other one to return true\n * @param dateToCompare - The date to compare with\n *\n * @returns The first date is before the second date\n *\n * @example\n * // Is 10 July 1989 before 11 February 1987?\n * const result = isBefore(new Date(1989, 6, 10), new Date(1987, 1, 11))\n * //=> false\n */\nfunction isBefore(date, dateToCompare) {\n return +(0, _index.toDate)(date) < +(0, _index.toDate)(dateToCompare);\n}\n", "\"use strict\";\nexports.isEqual = isEqual;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name isEqual\n * @category Common Helpers\n * @summary Are the given dates equal?\n *\n * @description\n * Are the given dates equal?\n *\n * @param dateLeft - The first date to compare\n * @param dateRight - The second date to compare\n *\n * @returns The dates are equal\n *\n * @example\n * // Are 2 July 2014 06:30:45.000 and 2 July 2014 06:30:45.500 equal?\n * const result = isEqual(\n * new Date(2014, 6, 2, 6, 30, 45, 0),\n * new Date(2014, 6, 2, 6, 30, 45, 500)\n * )\n * //=> false\n */\nfunction isEqual(leftDate, rightDate) {\n return +(0, _index.toDate)(leftDate) === +(0, _index.toDate)(rightDate);\n}\n", "\"use strict\";\nexports.isExists = isExists; /**\n * @name isExists\n * @category Common Helpers\n * @summary Is the given date exists?\n *\n * @description\n * Checks if the given arguments convert to an existing date.\n *\n * @param year - The year of the date to check\n * @param month - The month of the date to check\n * @param day - The day of the date to check\n *\n * @returns `true` if the date exists\n *\n * @example\n * // For the valid date:\n * const result = isExists(2018, 0, 31)\n * //=> true\n *\n * @example\n * // For the invalid date:\n * const result = isExists(2018, 1, 31)\n * //=> false\n */\nfunction isExists(year, month, day) {\n const date = new Date(year, month, day);\n return (\n date.getFullYear() === year &&\n date.getMonth() === month &&\n date.getDate() === day\n );\n}\n", "\"use strict\";\nexports.isFirstDayOfMonth = isFirstDayOfMonth;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isFirstDayOfMonth} function options.\n */\n\n/**\n * @name isFirstDayOfMonth\n * @category Month Helpers\n * @summary Is the given date the first day of a month?\n *\n * @description\n * Is the given date the first day of a month?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is the first day of a month\n *\n * @example\n * // Is 1 September 2014 the first day of a month?\n * const result = isFirstDayOfMonth(new Date(2014, 8, 1))\n * //=> true\n */\nfunction isFirstDayOfMonth(date, options) {\n return (0, _index.toDate)(date, options?.in).getDate() === 1;\n}\n", "\"use strict\";\nexports.isFriday = isFriday;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isFriday} function options.\n */\n\n/**\n * @name isFriday\n * @category Weekday Helpers\n * @summary Is the given date Friday?\n *\n * @description\n * Is the given date Friday?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is Friday\n *\n * @example\n * // Is 26 September 2014 Friday?\n * const result = isFriday(new Date(2014, 8, 26))\n * //=> true\n */\nfunction isFriday(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay() === 5;\n}\n", "\"use strict\";\nexports.isFuture = isFuture;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name isFuture\n * @category Common Helpers\n * @summary Is the given date in the future?\n * @pure false\n *\n * @description\n * Is the given date in the future?\n *\n * @param date - The date to check\n *\n * @returns The date is in the future\n *\n * @example\n * // If today is 6 October 2014, is 31 December 2014 in the future?\n * const result = isFuture(new Date(2014, 11, 31))\n * //=> true\n */\nfunction isFuture(date) {\n return +(0, _index.toDate)(date) > Date.now();\n}\n", "\"use strict\";\nexports.transpose = transpose;\nvar _index = require(\"./constructFrom.cjs\");\n\n/**\n * @name transpose\n * @category Generic Helpers\n * @summary Transpose the date to the given constructor.\n *\n * @description\n * The function transposes the date to the given constructor. It helps you\n * to transpose the date in the system time zone to say `UTCDate` or any other\n * date extension.\n *\n * @typeParam InputDate - The input `Date` type derived from the passed argument.\n * @typeParam ResultDate - The result `Date` type derived from the passed constructor.\n *\n * @param date - The date to use values from\n * @param constructor - The date constructor to use\n *\n * @returns Date transposed to the given constructor\n *\n * @example\n * // Create July 10, 2022 00:00 in locale time zone\n * const date = new Date(2022, 6, 10)\n * //=> 'Sun Jul 10 2022 00:00:00 GMT+0800 (Singapore Standard Time)'\n *\n * @example\n * // Transpose the date to July 10, 2022 00:00 in UTC\n * transpose(date, UTCDate)\n * //=> 'Sun Jul 10 2022 00:00:00 GMT+0000 (Coordinated Universal Time)'\n */\nfunction transpose(date, constructor) {\n const date_ = isConstructor(constructor)\n ? new constructor(0)\n : (0, _index.constructFrom)(constructor, 0);\n date_.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());\n date_.setHours(\n date.getHours(),\n date.getMinutes(),\n date.getSeconds(),\n date.getMilliseconds(),\n );\n return date_;\n}\n\nfunction isConstructor(constructor) {\n return (\n typeof constructor === \"function\" &&\n constructor.prototype?.constructor === constructor\n );\n}\n", "\"use strict\";\nexports.ValueSetter = exports.Setter = exports.DateTimezoneSetter = void 0;\nvar _index = require(\"../../constructFrom.cjs\");\nvar _index2 = require(\"../../transpose.cjs\");\n\nconst TIMEZONE_UNIT_PRIORITY = 10;\n\nclass Setter {\n subPriority = 0;\n\n validate(_utcDate, _options) {\n return true;\n }\n}\nexports.Setter = Setter;\n\nclass ValueSetter extends Setter {\n constructor(\n value,\n\n validateValue,\n\n setValue,\n\n priority,\n subPriority,\n ) {\n super();\n this.value = value;\n this.validateValue = validateValue;\n this.setValue = setValue;\n this.priority = priority;\n if (subPriority) {\n this.subPriority = subPriority;\n }\n }\n\n validate(date, options) {\n return this.validateValue(date, this.value, options);\n }\n\n set(date, flags, options) {\n return this.setValue(date, flags, this.value, options);\n }\n}\nexports.ValueSetter = ValueSetter;\n\nclass DateTimezoneSetter extends Setter {\n priority = TIMEZONE_UNIT_PRIORITY;\n subPriority = -1;\n\n constructor(context, reference) {\n super();\n this.context =\n context || ((date) => (0, _index.constructFrom)(reference, date));\n }\n\n set(date, flags) {\n if (flags.timestampIsSet) return date;\n return (0, _index.constructFrom)(\n date,\n (0, _index2.transpose)(date, this.context),\n );\n }\n}\nexports.DateTimezoneSetter = DateTimezoneSetter;\n", "\"use strict\";\nexports.Parser = void 0;\nvar _Setter = require(\"./Setter.cjs\");\n\nclass Parser {\n run(dateString, token, match, options) {\n const result = this.parse(dateString, token, match, options);\n if (!result) {\n return null;\n }\n\n return {\n setter: new _Setter.ValueSetter(\n result.value,\n this.validate,\n this.set,\n this.priority,\n this.subPriority,\n ),\n rest: result.rest,\n };\n }\n\n validate(_utcDate, _value, _options) {\n return true;\n }\n}\nexports.Parser = Parser;\n", "\"use strict\";\nexports.EraParser = void 0;\n\nvar _Parser = require(\"../Parser.cjs\");\n\nclass EraParser extends _Parser.Parser {\n priority = 140;\n\n parse(dateString, token, match) {\n switch (token) {\n // AD, BC\n case \"G\":\n case \"GG\":\n case \"GGG\":\n return (\n match.era(dateString, { width: \"abbreviated\" }) ||\n match.era(dateString, { width: \"narrow\" })\n );\n\n // A, B\n case \"GGGGG\":\n return match.era(dateString, { width: \"narrow\" });\n // Anno Domini, Before Christ\n case \"GGGG\":\n default:\n return (\n match.era(dateString, { width: \"wide\" }) ||\n match.era(dateString, { width: \"abbreviated\" }) ||\n match.era(dateString, { width: \"narrow\" })\n );\n }\n }\n\n set(date, flags, value) {\n flags.era = value;\n date.setFullYear(value, 0, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"R\", \"u\", \"t\", \"T\"];\n}\nexports.EraParser = EraParser;\n", "\"use strict\";\nexports.timezonePatterns = exports.numericPatterns = void 0;\nconst numericPatterns = (exports.numericPatterns = {\n month: /^(1[0-2]|0?\\d)/, // 0 to 12\n date: /^(3[0-1]|[0-2]?\\d)/, // 0 to 31\n dayOfYear: /^(36[0-6]|3[0-5]\\d|[0-2]?\\d?\\d)/, // 0 to 366\n week: /^(5[0-3]|[0-4]?\\d)/, // 0 to 53\n hour23h: /^(2[0-3]|[0-1]?\\d)/, // 0 to 23\n hour24h: /^(2[0-4]|[0-1]?\\d)/, // 0 to 24\n hour11h: /^(1[0-1]|0?\\d)/, // 0 to 11\n hour12h: /^(1[0-2]|0?\\d)/, // 0 to 12\n minute: /^[0-5]?\\d/, // 0 to 59\n second: /^[0-5]?\\d/, // 0 to 59\n\n singleDigit: /^\\d/, // 0 to 9\n twoDigits: /^\\d{1,2}/, // 0 to 99\n threeDigits: /^\\d{1,3}/, // 0 to 999\n fourDigits: /^\\d{1,4}/, // 0 to 9999\n\n anyDigitsSigned: /^-?\\d+/,\n singleDigitSigned: /^-?\\d/, // 0 to 9, -0 to -9\n twoDigitsSigned: /^-?\\d{1,2}/, // 0 to 99, -0 to -99\n threeDigitsSigned: /^-?\\d{1,3}/, // 0 to 999, -0 to -999\n fourDigitsSigned: /^-?\\d{1,4}/, // 0 to 9999, -0 to -9999\n});\n\nconst timezonePatterns = (exports.timezonePatterns = {\n basicOptionalMinutes: /^([+-])(\\d{2})(\\d{2})?|Z/,\n basic: /^([+-])(\\d{2})(\\d{2})|Z/,\n basicOptionalSeconds: /^([+-])(\\d{2})(\\d{2})((\\d{2}))?|Z/,\n extended: /^([+-])(\\d{2}):(\\d{2})|Z/,\n extendedOptionalSeconds: /^([+-])(\\d{2}):(\\d{2})(:(\\d{2}))?|Z/,\n});\n", "\"use strict\";\nexports.dayPeriodEnumToHours = dayPeriodEnumToHours;\nexports.isLeapYearIndex = isLeapYearIndex;\nexports.mapValue = mapValue;\nexports.normalizeTwoDigitYear = normalizeTwoDigitYear;\nexports.parseAnyDigitsSigned = parseAnyDigitsSigned;\nexports.parseNDigits = parseNDigits;\nexports.parseNDigitsSigned = parseNDigitsSigned;\nexports.parseNumericPattern = parseNumericPattern;\nexports.parseTimezonePattern = parseTimezonePattern;\nvar _index = require(\"../../constants.cjs\");\n\nvar _constants = require(\"./constants.cjs\");\n\nfunction mapValue(parseFnResult, mapFn) {\n if (!parseFnResult) {\n return parseFnResult;\n }\n\n return {\n value: mapFn(parseFnResult.value),\n rest: parseFnResult.rest,\n };\n}\n\nfunction parseNumericPattern(pattern, dateString) {\n const matchResult = dateString.match(pattern);\n\n if (!matchResult) {\n return null;\n }\n\n return {\n value: parseInt(matchResult[0], 10),\n rest: dateString.slice(matchResult[0].length),\n };\n}\n\nfunction parseTimezonePattern(pattern, dateString) {\n const matchResult = dateString.match(pattern);\n\n if (!matchResult) {\n return null;\n }\n\n // Input is 'Z'\n if (matchResult[0] === \"Z\") {\n return {\n value: 0,\n rest: dateString.slice(1),\n };\n }\n\n const sign = matchResult[1] === \"+\" ? 1 : -1;\n const hours = matchResult[2] ? parseInt(matchResult[2], 10) : 0;\n const minutes = matchResult[3] ? parseInt(matchResult[3], 10) : 0;\n const seconds = matchResult[5] ? parseInt(matchResult[5], 10) : 0;\n\n return {\n value:\n sign *\n (hours * _index.millisecondsInHour +\n minutes * _index.millisecondsInMinute +\n seconds * _index.millisecondsInSecond),\n rest: dateString.slice(matchResult[0].length),\n };\n}\n\nfunction parseAnyDigitsSigned(dateString) {\n return parseNumericPattern(\n _constants.numericPatterns.anyDigitsSigned,\n dateString,\n );\n}\n\nfunction parseNDigits(n, dateString) {\n switch (n) {\n case 1:\n return parseNumericPattern(\n _constants.numericPatterns.singleDigit,\n dateString,\n );\n case 2:\n return parseNumericPattern(\n _constants.numericPatterns.twoDigits,\n dateString,\n );\n case 3:\n return parseNumericPattern(\n _constants.numericPatterns.threeDigits,\n dateString,\n );\n case 4:\n return parseNumericPattern(\n _constants.numericPatterns.fourDigits,\n dateString,\n );\n default:\n return parseNumericPattern(new RegExp(\"^\\\\d{1,\" + n + \"}\"), dateString);\n }\n}\n\nfunction parseNDigitsSigned(n, dateString) {\n switch (n) {\n case 1:\n return parseNumericPattern(\n _constants.numericPatterns.singleDigitSigned,\n dateString,\n );\n case 2:\n return parseNumericPattern(\n _constants.numericPatterns.twoDigitsSigned,\n dateString,\n );\n case 3:\n return parseNumericPattern(\n _constants.numericPatterns.threeDigitsSigned,\n dateString,\n );\n case 4:\n return parseNumericPattern(\n _constants.numericPatterns.fourDigitsSigned,\n dateString,\n );\n default:\n return parseNumericPattern(new RegExp(\"^-?\\\\d{1,\" + n + \"}\"), dateString);\n }\n}\n\nfunction dayPeriodEnumToHours(dayPeriod) {\n switch (dayPeriod) {\n case \"morning\":\n return 4;\n case \"evening\":\n return 17;\n case \"pm\":\n case \"noon\":\n case \"afternoon\":\n return 12;\n case \"am\":\n case \"midnight\":\n case \"night\":\n default:\n return 0;\n }\n}\n\nfunction normalizeTwoDigitYear(twoDigitYear, currentYear) {\n const isCommonEra = currentYear > 0;\n // Absolute number of the current year:\n // 1 -> 1 AC\n // 0 -> 1 BC\n // -1 -> 2 BC\n const absCurrentYear = isCommonEra ? currentYear : 1 - currentYear;\n\n let result;\n if (absCurrentYear <= 50) {\n result = twoDigitYear || 100;\n } else {\n const rangeEnd = absCurrentYear + 50;\n const rangeEndCentury = Math.trunc(rangeEnd / 100) * 100;\n const isPreviousCentury = twoDigitYear >= rangeEnd % 100;\n result = twoDigitYear + rangeEndCentury - (isPreviousCentury ? 100 : 0);\n }\n\n return isCommonEra ? result : 1 - result;\n}\n\nfunction isLeapYearIndex(year) {\n return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);\n}\n", "\"use strict\";\nexports.YearParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns\n// | Year | y | yy | yyy | yyyy | yyyyy |\n// |----------|-------|----|-------|-------|-------|\n// | AD 1 | 1 | 01 | 001 | 0001 | 00001 |\n// | AD 12 | 12 | 12 | 012 | 0012 | 00012 |\n// | AD 123 | 123 | 23 | 123 | 0123 | 00123 |\n// | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 |\n// | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |\nclass YearParser extends _Parser.Parser {\n priority = 130;\n incompatibleTokens = [\"Y\", \"R\", \"u\", \"w\", \"I\", \"i\", \"e\", \"c\", \"t\", \"T\"];\n\n parse(dateString, token, match) {\n const valueCallback = (year) => ({\n year,\n isTwoDigitYear: token === \"yy\",\n });\n\n switch (token) {\n case \"y\":\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(4, dateString),\n valueCallback,\n );\n case \"yo\":\n return (0, _utils.mapValue)(\n match.ordinalNumber(dateString, {\n unit: \"year\",\n }),\n valueCallback,\n );\n default:\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(token.length, dateString),\n valueCallback,\n );\n }\n }\n\n validate(_date, value) {\n return value.isTwoDigitYear || value.year > 0;\n }\n\n set(date, flags, value) {\n const currentYear = date.getFullYear();\n\n if (value.isTwoDigitYear) {\n const normalizedTwoDigitYear = (0, _utils.normalizeTwoDigitYear)(\n value.year,\n currentYear,\n );\n date.setFullYear(normalizedTwoDigitYear, 0, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n const year =\n !(\"era\" in flags) || flags.era === 1 ? value.year : 1 - value.year;\n date.setFullYear(year, 0, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n}\nexports.YearParser = YearParser;\n", "\"use strict\";\nexports.LocalWeekYearParser = void 0;\nvar _index = require(\"../../../getWeekYear.cjs\");\n\nvar _index2 = require(\"../../../startOfWeek.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// Local week-numbering year\nclass LocalWeekYearParser extends _Parser.Parser {\n priority = 130;\n\n parse(dateString, token, match) {\n const valueCallback = (year) => ({\n year,\n isTwoDigitYear: token === \"YY\",\n });\n\n switch (token) {\n case \"Y\":\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(4, dateString),\n valueCallback,\n );\n case \"Yo\":\n return (0, _utils.mapValue)(\n match.ordinalNumber(dateString, {\n unit: \"year\",\n }),\n valueCallback,\n );\n default:\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(token.length, dateString),\n valueCallback,\n );\n }\n }\n\n validate(_date, value) {\n return value.isTwoDigitYear || value.year > 0;\n }\n\n set(date, flags, value, options) {\n const currentYear = (0, _index.getWeekYear)(date, options);\n\n if (value.isTwoDigitYear) {\n const normalizedTwoDigitYear = (0, _utils.normalizeTwoDigitYear)(\n value.year,\n currentYear,\n );\n date.setFullYear(\n normalizedTwoDigitYear,\n 0,\n options.firstWeekContainsDate,\n );\n date.setHours(0, 0, 0, 0);\n return (0, _index2.startOfWeek)(date, options);\n }\n\n const year =\n !(\"era\" in flags) || flags.era === 1 ? value.year : 1 - value.year;\n date.setFullYear(year, 0, options.firstWeekContainsDate);\n date.setHours(0, 0, 0, 0);\n return (0, _index2.startOfWeek)(date, options);\n }\n\n incompatibleTokens = [\n \"y\",\n \"R\",\n \"u\",\n \"Q\",\n \"q\",\n \"M\",\n \"L\",\n \"I\",\n \"d\",\n \"D\",\n \"i\",\n \"t\",\n \"T\",\n ];\n}\nexports.LocalWeekYearParser = LocalWeekYearParser;\n", "\"use strict\";\nexports.ISOWeekYearParser = void 0;\nvar _index = require(\"../../../startOfISOWeek.cjs\");\nvar _index2 = require(\"../../../constructFrom.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// ISO week-numbering year\nclass ISOWeekYearParser extends _Parser.Parser {\n priority = 130;\n\n parse(dateString, token) {\n if (token === \"R\") {\n return (0, _utils.parseNDigitsSigned)(4, dateString);\n }\n\n return (0, _utils.parseNDigitsSigned)(token.length, dateString);\n }\n\n set(date, _flags, value) {\n const firstWeekOfYear = (0, _index2.constructFrom)(date, 0);\n firstWeekOfYear.setFullYear(value, 0, 4);\n firstWeekOfYear.setHours(0, 0, 0, 0);\n return (0, _index.startOfISOWeek)(firstWeekOfYear);\n }\n\n incompatibleTokens = [\n \"G\",\n \"y\",\n \"Y\",\n \"u\",\n \"Q\",\n \"q\",\n \"M\",\n \"L\",\n \"w\",\n \"d\",\n \"D\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.ISOWeekYearParser = ISOWeekYearParser;\n", "\"use strict\";\nexports.ExtendedYearParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass ExtendedYearParser extends _Parser.Parser {\n priority = 130;\n\n parse(dateString, token) {\n if (token === \"u\") {\n return (0, _utils.parseNDigitsSigned)(4, dateString);\n }\n\n return (0, _utils.parseNDigitsSigned)(token.length, dateString);\n }\n\n set(date, _flags, value) {\n date.setFullYear(value, 0, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"G\", \"y\", \"Y\", \"R\", \"w\", \"I\", \"i\", \"e\", \"c\", \"t\", \"T\"];\n}\nexports.ExtendedYearParser = ExtendedYearParser;\n", "\"use strict\";\nexports.QuarterParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass QuarterParser extends _Parser.Parser {\n priority = 120;\n\n parse(dateString, token, match) {\n switch (token) {\n // 1, 2, 3, 4\n case \"Q\":\n case \"QQ\": // 01, 02, 03, 04\n return (0, _utils.parseNDigits)(token.length, dateString);\n // 1st, 2nd, 3rd, 4th\n case \"Qo\":\n return match.ordinalNumber(dateString, { unit: \"quarter\" });\n // Q1, Q2, Q3, Q4\n case \"QQQ\":\n return (\n match.quarter(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.quarter(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n\n // 1, 2, 3, 4 (narrow quarter; could be not numerical)\n case \"QQQQQ\":\n return match.quarter(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // 1st quarter, 2nd quarter, ...\n case \"QQQQ\":\n default:\n return (\n match.quarter(dateString, {\n width: \"wide\",\n context: \"formatting\",\n }) ||\n match.quarter(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.quarter(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n }\n }\n\n validate(_date, value) {\n return value >= 1 && value <= 4;\n }\n\n set(date, _flags, value) {\n date.setMonth((value - 1) * 3, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"Y\",\n \"R\",\n \"q\",\n \"M\",\n \"L\",\n \"w\",\n \"I\",\n \"d\",\n \"D\",\n \"i\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.QuarterParser = QuarterParser;\n", "\"use strict\";\nexports.StandAloneQuarterParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass StandAloneQuarterParser extends _Parser.Parser {\n priority = 120;\n\n parse(dateString, token, match) {\n switch (token) {\n // 1, 2, 3, 4\n case \"q\":\n case \"qq\": // 01, 02, 03, 04\n return (0, _utils.parseNDigits)(token.length, dateString);\n // 1st, 2nd, 3rd, 4th\n case \"qo\":\n return match.ordinalNumber(dateString, { unit: \"quarter\" });\n // Q1, Q2, Q3, Q4\n case \"qqq\":\n return (\n match.quarter(dateString, {\n width: \"abbreviated\",\n context: \"standalone\",\n }) ||\n match.quarter(dateString, {\n width: \"narrow\",\n context: \"standalone\",\n })\n );\n\n // 1, 2, 3, 4 (narrow quarter; could be not numerical)\n case \"qqqqq\":\n return match.quarter(dateString, {\n width: \"narrow\",\n context: \"standalone\",\n });\n // 1st quarter, 2nd quarter, ...\n case \"qqqq\":\n default:\n return (\n match.quarter(dateString, {\n width: \"wide\",\n context: \"standalone\",\n }) ||\n match.quarter(dateString, {\n width: \"abbreviated\",\n context: \"standalone\",\n }) ||\n match.quarter(dateString, {\n width: \"narrow\",\n context: \"standalone\",\n })\n );\n }\n }\n\n validate(_date, value) {\n return value >= 1 && value <= 4;\n }\n\n set(date, _flags, value) {\n date.setMonth((value - 1) * 3, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"Y\",\n \"R\",\n \"Q\",\n \"M\",\n \"L\",\n \"w\",\n \"I\",\n \"d\",\n \"D\",\n \"i\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.StandAloneQuarterParser = StandAloneQuarterParser;\n", "\"use strict\";\nexports.MonthParser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass MonthParser extends _Parser.Parser {\n incompatibleTokens = [\n \"Y\",\n \"R\",\n \"q\",\n \"Q\",\n \"L\",\n \"w\",\n \"I\",\n \"D\",\n \"i\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n\n priority = 110;\n\n parse(dateString, token, match) {\n const valueCallback = (value) => value - 1;\n\n switch (token) {\n // 1, 2, ..., 12\n case \"M\":\n return (0, _utils.mapValue)(\n (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.month,\n dateString,\n ),\n valueCallback,\n );\n // 01, 02, ..., 12\n case \"MM\":\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(2, dateString),\n valueCallback,\n );\n // 1st, 2nd, ..., 12th\n case \"Mo\":\n return (0, _utils.mapValue)(\n match.ordinalNumber(dateString, {\n unit: \"month\",\n }),\n valueCallback,\n );\n // Jan, Feb, ..., Dec\n case \"MMM\":\n return (\n match.month(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.month(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n\n // J, F, ..., D\n case \"MMMMM\":\n return match.month(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // January, February, ..., December\n case \"MMMM\":\n default:\n return (\n match.month(dateString, { width: \"wide\", context: \"formatting\" }) ||\n match.month(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.month(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 11;\n }\n\n set(date, _flags, value) {\n date.setMonth(value, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n}\nexports.MonthParser = MonthParser;\n", "\"use strict\";\nexports.StandAloneMonthParser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass StandAloneMonthParser extends _Parser.Parser {\n priority = 110;\n\n parse(dateString, token, match) {\n const valueCallback = (value) => value - 1;\n\n switch (token) {\n // 1, 2, ..., 12\n case \"L\":\n return (0, _utils.mapValue)(\n (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.month,\n dateString,\n ),\n valueCallback,\n );\n // 01, 02, ..., 12\n case \"LL\":\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(2, dateString),\n valueCallback,\n );\n // 1st, 2nd, ..., 12th\n case \"Lo\":\n return (0, _utils.mapValue)(\n match.ordinalNumber(dateString, {\n unit: \"month\",\n }),\n valueCallback,\n );\n // Jan, Feb, ..., Dec\n case \"LLL\":\n return (\n match.month(dateString, {\n width: \"abbreviated\",\n context: \"standalone\",\n }) ||\n match.month(dateString, { width: \"narrow\", context: \"standalone\" })\n );\n\n // J, F, ..., D\n case \"LLLLL\":\n return match.month(dateString, {\n width: \"narrow\",\n context: \"standalone\",\n });\n // January, February, ..., December\n case \"LLLL\":\n default:\n return (\n match.month(dateString, { width: \"wide\", context: \"standalone\" }) ||\n match.month(dateString, {\n width: \"abbreviated\",\n context: \"standalone\",\n }) ||\n match.month(dateString, { width: \"narrow\", context: \"standalone\" })\n );\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 11;\n }\n\n set(date, _flags, value) {\n date.setMonth(value, 1);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"Y\",\n \"R\",\n \"q\",\n \"Q\",\n \"M\",\n \"w\",\n \"I\",\n \"D\",\n \"i\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.StandAloneMonthParser = StandAloneMonthParser;\n", "\"use strict\";\nexports.setWeek = setWeek;\nvar _index = require(\"./getWeek.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setWeek} function options.\n */\n\n/**\n * @name setWeek\n * @category Week Helpers\n * @summary Set the local week to the given date.\n *\n * @description\n * Set the local week to the given date, saving the weekday number.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param week - The week of the new date\n * @param options - An object with options\n *\n * @returns The new date with the local week set\n *\n * @example\n * // Set the 1st week to 2 January 2005 with default options:\n * const result = setWeek(new Date(2005, 0, 2), 1)\n * //=> Sun Dec 26 2004 00:00:00\n *\n * @example\n * // Set the 1st week to 2 January 2005,\n * // if Monday is the first day of the week,\n * // and the first week of the year always contains 4 January:\n * const result = setWeek(new Date(2005, 0, 2), 1, {\n * weekStartsOn: 1,\n * firstWeekContainsDate: 4\n * })\n * //=> Sun Jan 4 2004 00:00:00\n */\nfunction setWeek(date, week, options) {\n const date_ = (0, _index2.toDate)(date, options?.in);\n const diff = (0, _index.getWeek)(date_, options) - week;\n date_.setDate(date_.getDate() - diff * 7);\n return (0, _index2.toDate)(date_, options?.in);\n}\n", "\"use strict\";\nexports.LocalWeekParser = void 0;\nvar _index = require(\"../../../setWeek.cjs\");\nvar _index2 = require(\"../../../startOfWeek.cjs\");\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// Local week of year\nclass LocalWeekParser extends _Parser.Parser {\n priority = 100;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"w\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.week,\n dateString,\n );\n case \"wo\":\n return match.ordinalNumber(dateString, { unit: \"week\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 1 && value <= 53;\n }\n\n set(date, _flags, value, options) {\n return (0, _index2.startOfWeek)(\n (0, _index.setWeek)(date, value, options),\n options,\n );\n }\n\n incompatibleTokens = [\n \"y\",\n \"R\",\n \"u\",\n \"q\",\n \"Q\",\n \"M\",\n \"L\",\n \"I\",\n \"d\",\n \"D\",\n \"i\",\n \"t\",\n \"T\",\n ];\n}\nexports.LocalWeekParser = LocalWeekParser;\n", "\"use strict\";\nexports.setISOWeek = setISOWeek;\nvar _index = require(\"./getISOWeek.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setISOWeek} function options.\n */\n\n/**\n * @name setISOWeek\n * @category ISO Week Helpers\n * @summary Set the ISO week to the given date.\n *\n * @description\n * Set the ISO week to the given date, saving the weekday number.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The `Date` type of the context function.\n *\n * @param date - The date to be changed\n * @param week - The ISO week of the new date\n * @param options - An object with options\n *\n * @returns The new date with the ISO week set\n *\n * @example\n * // Set the 53rd ISO week to 7 August 2004:\n * const result = setISOWeek(new Date(2004, 7, 7), 53)\n * //=> Sat Jan 01 2005 00:00:00\n */\nfunction setISOWeek(date, week, options) {\n const _date = (0, _index2.toDate)(date, options?.in);\n const diff = (0, _index.getISOWeek)(_date, options) - week;\n _date.setDate(_date.getDate() - diff * 7);\n return _date;\n}\n", "\"use strict\";\nexports.ISOWeekParser = void 0;\nvar _index = require(\"../../../setISOWeek.cjs\");\nvar _index2 = require(\"../../../startOfISOWeek.cjs\");\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// ISO week of year\nclass ISOWeekParser extends _Parser.Parser {\n priority = 100;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"I\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.week,\n dateString,\n );\n case \"Io\":\n return match.ordinalNumber(dateString, { unit: \"week\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 1 && value <= 53;\n }\n\n set(date, _flags, value) {\n return (0, _index2.startOfISOWeek)((0, _index.setISOWeek)(date, value));\n }\n\n incompatibleTokens = [\n \"y\",\n \"Y\",\n \"u\",\n \"q\",\n \"Q\",\n \"M\",\n \"L\",\n \"w\",\n \"d\",\n \"D\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.ISOWeekParser = ISOWeekParser;\n", "\"use strict\";\nexports.DateParser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nconst DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\nconst DAYS_IN_MONTH_LEAP_YEAR = [\n 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,\n];\n\n// Day of the month\nclass DateParser extends _Parser.Parser {\n priority = 90;\n subPriority = 1;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"d\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.date,\n dateString,\n );\n case \"do\":\n return match.ordinalNumber(dateString, { unit: \"date\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(date, value) {\n const year = date.getFullYear();\n const isLeapYear = (0, _utils.isLeapYearIndex)(year);\n const month = date.getMonth();\n if (isLeapYear) {\n return value >= 1 && value <= DAYS_IN_MONTH_LEAP_YEAR[month];\n } else {\n return value >= 1 && value <= DAYS_IN_MONTH[month];\n }\n }\n\n set(date, _flags, value) {\n date.setDate(value);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"Y\",\n \"R\",\n \"q\",\n \"Q\",\n \"w\",\n \"I\",\n \"D\",\n \"i\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.DateParser = DateParser;\n", "\"use strict\";\nexports.DayOfYearParser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass DayOfYearParser extends _Parser.Parser {\n priority = 90;\n\n subpriority = 1;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"D\":\n case \"DD\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.dayOfYear,\n dateString,\n );\n case \"Do\":\n return match.ordinalNumber(dateString, { unit: \"date\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(date, value) {\n const year = date.getFullYear();\n const isLeapYear = (0, _utils.isLeapYearIndex)(year);\n if (isLeapYear) {\n return value >= 1 && value <= 366;\n } else {\n return value >= 1 && value <= 365;\n }\n }\n\n set(date, _flags, value) {\n date.setMonth(0, value);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"Y\",\n \"R\",\n \"q\",\n \"Q\",\n \"M\",\n \"L\",\n \"w\",\n \"I\",\n \"d\",\n \"E\",\n \"i\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.DayOfYearParser = DayOfYearParser;\n", "\"use strict\";\nexports.setDay = setDay;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./addDays.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setDay} function options.\n */\n\n/**\n * @name setDay\n * @category Weekday Helpers\n * @summary Set the day of the week to the given date.\n *\n * @description\n * Set the day of the week to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param day - The day of the week of the new date\n * @param options - An object with options.\n *\n * @returns The new date with the day of the week set\n *\n * @example\n * // Set week day to Sunday, with the default weekStartsOn of Sunday:\n * const result = setDay(new Date(2014, 8, 1), 0)\n * //=> Sun Aug 31 2014 00:00:00\n *\n * @example\n * // Set week day to Sunday, with a weekStartsOn of Monday:\n * const result = setDay(new Date(2014, 8, 1), 0, { weekStartsOn: 1 })\n * //=> Sun Sep 07 2014 00:00:00\n */\nfunction setDay(date, day, options) {\n const defaultOptions = (0, _index.getDefaultOptions)();\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const date_ = (0, _index3.toDate)(date, options?.in);\n const currentDay = date_.getDay();\n\n const remainder = day % 7;\n const dayIndex = (remainder + 7) % 7;\n\n const delta = 7 - weekStartsOn;\n const diff =\n day < 0 || day > 6\n ? day - ((currentDay + delta) % 7)\n : ((dayIndex + delta) % 7) - ((currentDay + delta) % 7);\n return (0, _index2.addDays)(date_, diff, options);\n}\n", "\"use strict\";\nexports.DayParser = void 0;\nvar _index = require(\"../../../setDay.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\n// Day of week\nclass DayParser extends _Parser.Parser {\n priority = 90;\n\n parse(dateString, token, match) {\n switch (token) {\n // Tue\n case \"E\":\n case \"EE\":\n case \"EEE\":\n return (\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.day(dateString, { width: \"short\", context: \"formatting\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n\n // T\n case \"EEEEE\":\n return match.day(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // Tu\n case \"EEEEEE\":\n return (\n match.day(dateString, { width: \"short\", context: \"formatting\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n\n // Tuesday\n case \"EEEE\":\n default:\n return (\n match.day(dateString, { width: \"wide\", context: \"formatting\" }) ||\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.day(dateString, { width: \"short\", context: \"formatting\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 6;\n }\n\n set(date, _flags, value, options) {\n date = (0, _index.setDay)(date, value, options);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"D\", \"i\", \"e\", \"c\", \"t\", \"T\"];\n}\nexports.DayParser = DayParser;\n", "\"use strict\";\nexports.LocalDayParser = void 0;\nvar _index = require(\"../../../setDay.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// Local day of week\nclass LocalDayParser extends _Parser.Parser {\n priority = 90;\n parse(dateString, token, match, options) {\n const valueCallback = (value) => {\n // We want here floor instead of trunc, so we get -7 for value 0 instead of 0\n const wholeWeekDays = Math.floor((value - 1) / 7) * 7;\n return ((value + options.weekStartsOn + 6) % 7) + wholeWeekDays;\n };\n\n switch (token) {\n // 3\n case \"e\":\n case \"ee\": // 03\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(token.length, dateString),\n valueCallback,\n );\n // 3rd\n case \"eo\":\n return (0, _utils.mapValue)(\n match.ordinalNumber(dateString, {\n unit: \"day\",\n }),\n valueCallback,\n );\n // Tue\n case \"eee\":\n return (\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.day(dateString, { width: \"short\", context: \"formatting\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n\n // T\n case \"eeeee\":\n return match.day(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n });\n // Tu\n case \"eeeeee\":\n return (\n match.day(dateString, { width: \"short\", context: \"formatting\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n\n // Tuesday\n case \"eeee\":\n default:\n return (\n match.day(dateString, { width: \"wide\", context: \"formatting\" }) ||\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.day(dateString, { width: \"short\", context: \"formatting\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"formatting\" })\n );\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 6;\n }\n\n set(date, _flags, value, options) {\n date = (0, _index.setDay)(date, value, options);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"y\",\n \"R\",\n \"u\",\n \"q\",\n \"Q\",\n \"M\",\n \"L\",\n \"I\",\n \"d\",\n \"D\",\n \"E\",\n \"i\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.LocalDayParser = LocalDayParser;\n", "\"use strict\";\nexports.StandAloneLocalDayParser = void 0;\nvar _index = require(\"../../../setDay.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// Stand-alone local day of week\nclass StandAloneLocalDayParser extends _Parser.Parser {\n priority = 90;\n\n parse(dateString, token, match, options) {\n const valueCallback = (value) => {\n // We want here floor instead of trunc, so we get -7 for value 0 instead of 0\n const wholeWeekDays = Math.floor((value - 1) / 7) * 7;\n return ((value + options.weekStartsOn + 6) % 7) + wholeWeekDays;\n };\n\n switch (token) {\n // 3\n case \"c\":\n case \"cc\": // 03\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(token.length, dateString),\n valueCallback,\n );\n // 3rd\n case \"co\":\n return (0, _utils.mapValue)(\n match.ordinalNumber(dateString, {\n unit: \"day\",\n }),\n valueCallback,\n );\n // Tue\n case \"ccc\":\n return (\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"standalone\",\n }) ||\n match.day(dateString, { width: \"short\", context: \"standalone\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"standalone\" })\n );\n\n // T\n case \"ccccc\":\n return match.day(dateString, {\n width: \"narrow\",\n context: \"standalone\",\n });\n // Tu\n case \"cccccc\":\n return (\n match.day(dateString, { width: \"short\", context: \"standalone\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"standalone\" })\n );\n\n // Tuesday\n case \"cccc\":\n default:\n return (\n match.day(dateString, { width: \"wide\", context: \"standalone\" }) ||\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"standalone\",\n }) ||\n match.day(dateString, { width: \"short\", context: \"standalone\" }) ||\n match.day(dateString, { width: \"narrow\", context: \"standalone\" })\n );\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 6;\n }\n\n set(date, _flags, value, options) {\n date = (0, _index.setDay)(date, value, options);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"y\",\n \"R\",\n \"u\",\n \"q\",\n \"Q\",\n \"M\",\n \"L\",\n \"I\",\n \"d\",\n \"D\",\n \"E\",\n \"i\",\n \"e\",\n \"t\",\n \"T\",\n ];\n}\nexports.StandAloneLocalDayParser = StandAloneLocalDayParser;\n", "\"use strict\";\nexports.setISODay = setISODay;\nvar _index = require(\"./addDays.cjs\");\nvar _index2 = require(\"./getISODay.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setISODay} function options.\n */\n\n/**\n * @name setISODay\n * @category Weekday Helpers\n * @summary Set the day of the ISO week to the given date.\n *\n * @description\n * Set the day of the ISO week to the given date.\n * ISO week starts with Monday.\n * 7 is the index of Sunday, 1 is the index of Monday, etc.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param day - The day of the ISO week of the new date\n * @param options - An object with options\n *\n * @returns The new date with the day of the ISO week set\n *\n * @example\n * // Set Sunday to 1 September 2014:\n * const result = setISODay(new Date(2014, 8, 1), 7)\n * //=> Sun Sep 07 2014 00:00:00\n */\nfunction setISODay(date, day, options) {\n const date_ = (0, _index3.toDate)(date, options?.in);\n const currentDay = (0, _index2.getISODay)(date_, options);\n const diff = day - currentDay;\n return (0, _index.addDays)(date_, diff, options);\n}\n", "\"use strict\";\nexports.ISODayParser = void 0;\nvar _index = require(\"../../../setISODay.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// ISO day of week\nclass ISODayParser extends _Parser.Parser {\n priority = 90;\n\n parse(dateString, token, match) {\n const valueCallback = (value) => {\n if (value === 0) {\n return 7;\n }\n return value;\n };\n\n switch (token) {\n // 2\n case \"i\":\n case \"ii\": // 02\n return (0, _utils.parseNDigits)(token.length, dateString);\n // 2nd\n case \"io\":\n return match.ordinalNumber(dateString, { unit: \"day\" });\n // Tue\n case \"iii\":\n return (0, _utils.mapValue)(\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.day(dateString, {\n width: \"short\",\n context: \"formatting\",\n }) ||\n match.day(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n }),\n valueCallback,\n );\n // T\n case \"iiiii\":\n return (0, _utils.mapValue)(\n match.day(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n }),\n valueCallback,\n );\n // Tu\n case \"iiiiii\":\n return (0, _utils.mapValue)(\n match.day(dateString, {\n width: \"short\",\n context: \"formatting\",\n }) ||\n match.day(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n }),\n valueCallback,\n );\n // Tuesday\n case \"iiii\":\n default:\n return (0, _utils.mapValue)(\n match.day(dateString, {\n width: \"wide\",\n context: \"formatting\",\n }) ||\n match.day(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.day(dateString, {\n width: \"short\",\n context: \"formatting\",\n }) ||\n match.day(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n }),\n valueCallback,\n );\n }\n }\n\n validate(_date, value) {\n return value >= 1 && value <= 7;\n }\n\n set(date, _flags, value) {\n date = (0, _index.setISODay)(date, value);\n date.setHours(0, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\n \"y\",\n \"Y\",\n \"u\",\n \"q\",\n \"Q\",\n \"M\",\n \"L\",\n \"w\",\n \"d\",\n \"D\",\n \"E\",\n \"e\",\n \"c\",\n \"t\",\n \"T\",\n ];\n}\nexports.ISODayParser = ISODayParser;\n", "\"use strict\";\nexports.AMPMParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass AMPMParser extends _Parser.Parser {\n priority = 80;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"a\":\n case \"aa\":\n case \"aaa\":\n return (\n match.dayPeriod(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n\n case \"aaaaa\":\n return match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n });\n case \"aaaa\":\n default:\n return (\n match.dayPeriod(dateString, {\n width: \"wide\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n }\n }\n\n set(date, _flags, value) {\n date.setHours((0, _utils.dayPeriodEnumToHours)(value), 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"b\", \"B\", \"H\", \"k\", \"t\", \"T\"];\n}\nexports.AMPMParser = AMPMParser;\n", "\"use strict\";\nexports.AMPMMidnightParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass AMPMMidnightParser extends _Parser.Parser {\n priority = 80;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"b\":\n case \"bb\":\n case \"bbb\":\n return (\n match.dayPeriod(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n\n case \"bbbbb\":\n return match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n });\n case \"bbbb\":\n default:\n return (\n match.dayPeriod(dateString, {\n width: \"wide\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n }\n }\n\n set(date, _flags, value) {\n date.setHours((0, _utils.dayPeriodEnumToHours)(value), 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"a\", \"B\", \"H\", \"k\", \"t\", \"T\"];\n}\nexports.AMPMMidnightParser = AMPMMidnightParser;\n", "\"use strict\";\nexports.DayPeriodParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// in the morning, in the afternoon, in the evening, at night\nclass DayPeriodParser extends _Parser.Parser {\n priority = 80;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"B\":\n case \"BB\":\n case \"BBB\":\n return (\n match.dayPeriod(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n\n case \"BBBBB\":\n return match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n });\n case \"BBBB\":\n default:\n return (\n match.dayPeriod(dateString, {\n width: \"wide\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"abbreviated\",\n context: \"formatting\",\n }) ||\n match.dayPeriod(dateString, {\n width: \"narrow\",\n context: \"formatting\",\n })\n );\n }\n }\n\n set(date, _flags, value) {\n date.setHours((0, _utils.dayPeriodEnumToHours)(value), 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"a\", \"b\", \"t\", \"T\"];\n}\nexports.DayPeriodParser = DayPeriodParser;\n", "\"use strict\";\nexports.Hour1to12Parser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass Hour1to12Parser extends _Parser.Parser {\n priority = 70;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"h\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.hour12h,\n dateString,\n );\n case \"ho\":\n return match.ordinalNumber(dateString, { unit: \"hour\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 1 && value <= 12;\n }\n\n set(date, _flags, value) {\n const isPM = date.getHours() >= 12;\n if (isPM && value < 12) {\n date.setHours(value + 12, 0, 0, 0);\n } else if (!isPM && value === 12) {\n date.setHours(0, 0, 0, 0);\n } else {\n date.setHours(value, 0, 0, 0);\n }\n return date;\n }\n\n incompatibleTokens = [\"H\", \"K\", \"k\", \"t\", \"T\"];\n}\nexports.Hour1to12Parser = Hour1to12Parser;\n", "\"use strict\";\nexports.Hour0to23Parser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass Hour0to23Parser extends _Parser.Parser {\n priority = 70;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"H\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.hour23h,\n dateString,\n );\n case \"Ho\":\n return match.ordinalNumber(dateString, { unit: \"hour\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 23;\n }\n\n set(date, _flags, value) {\n date.setHours(value, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"a\", \"b\", \"h\", \"K\", \"k\", \"t\", \"T\"];\n}\nexports.Hour0to23Parser = Hour0to23Parser;\n", "\"use strict\";\nexports.Hour0To11Parser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass Hour0To11Parser extends _Parser.Parser {\n priority = 70;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"K\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.hour11h,\n dateString,\n );\n case \"Ko\":\n return match.ordinalNumber(dateString, { unit: \"hour\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 11;\n }\n\n set(date, _flags, value) {\n const isPM = date.getHours() >= 12;\n if (isPM && value < 12) {\n date.setHours(value + 12, 0, 0, 0);\n } else {\n date.setHours(value, 0, 0, 0);\n }\n return date;\n }\n\n incompatibleTokens = [\"h\", \"H\", \"k\", \"t\", \"T\"];\n}\nexports.Hour0To11Parser = Hour0To11Parser;\n", "\"use strict\";\nexports.Hour1To24Parser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass Hour1To24Parser extends _Parser.Parser {\n priority = 70;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"k\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.hour24h,\n dateString,\n );\n case \"ko\":\n return match.ordinalNumber(dateString, { unit: \"hour\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 1 && value <= 24;\n }\n\n set(date, _flags, value) {\n const hours = value <= 24 ? value % 24 : value;\n date.setHours(hours, 0, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"a\", \"b\", \"h\", \"H\", \"K\", \"t\", \"T\"];\n}\nexports.Hour1To24Parser = Hour1To24Parser;\n", "\"use strict\";\nexports.MinuteParser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass MinuteParser extends _Parser.Parser {\n priority = 60;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"m\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.minute,\n dateString,\n );\n case \"mo\":\n return match.ordinalNumber(dateString, { unit: \"minute\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 59;\n }\n\n set(date, _flags, value) {\n date.setMinutes(value, 0, 0);\n return date;\n }\n\n incompatibleTokens = [\"t\", \"T\"];\n}\nexports.MinuteParser = MinuteParser;\n", "\"use strict\";\nexports.SecondParser = void 0;\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass SecondParser extends _Parser.Parser {\n priority = 50;\n\n parse(dateString, token, match) {\n switch (token) {\n case \"s\":\n return (0, _utils.parseNumericPattern)(\n _constants.numericPatterns.second,\n dateString,\n );\n case \"so\":\n return match.ordinalNumber(dateString, { unit: \"second\" });\n default:\n return (0, _utils.parseNDigits)(token.length, dateString);\n }\n }\n\n validate(_date, value) {\n return value >= 0 && value <= 59;\n }\n\n set(date, _flags, value) {\n date.setSeconds(value, 0);\n return date;\n }\n\n incompatibleTokens = [\"t\", \"T\"];\n}\nexports.SecondParser = SecondParser;\n", "\"use strict\";\nexports.FractionOfSecondParser = void 0;\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass FractionOfSecondParser extends _Parser.Parser {\n priority = 30;\n\n parse(dateString, token) {\n const valueCallback = (value) =>\n Math.trunc(value * Math.pow(10, -token.length + 3));\n return (0, _utils.mapValue)(\n (0, _utils.parseNDigits)(token.length, dateString),\n valueCallback,\n );\n }\n\n set(date, _flags, value) {\n date.setMilliseconds(value);\n return date;\n }\n\n incompatibleTokens = [\"t\", \"T\"];\n}\nexports.FractionOfSecondParser = FractionOfSecondParser;\n", "\"use strict\";\nexports.ISOTimezoneWithZParser = void 0;\nvar _index = require(\"../../../constructFrom.cjs\");\nvar _index2 = require(\"../../../_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// Timezone (ISO-8601. +00:00 is `'Z'`)\nclass ISOTimezoneWithZParser extends _Parser.Parser {\n priority = 10;\n\n parse(dateString, token) {\n switch (token) {\n case \"X\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.basicOptionalMinutes,\n dateString,\n );\n case \"XX\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.basic,\n dateString,\n );\n case \"XXXX\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.basicOptionalSeconds,\n dateString,\n );\n case \"XXXXX\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.extendedOptionalSeconds,\n dateString,\n );\n case \"XXX\":\n default:\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.extended,\n dateString,\n );\n }\n }\n\n set(date, flags, value) {\n if (flags.timestampIsSet) return date;\n return (0, _index.constructFrom)(\n date,\n date.getTime() -\n (0, _index2.getTimezoneOffsetInMilliseconds)(date) -\n value,\n );\n }\n\n incompatibleTokens = [\"t\", \"T\", \"x\"];\n}\nexports.ISOTimezoneWithZParser = ISOTimezoneWithZParser;\n", "\"use strict\";\nexports.ISOTimezoneParser = void 0;\nvar _index = require(\"../../../constructFrom.cjs\");\nvar _index2 = require(\"../../../_lib/getTimezoneOffsetInMilliseconds.cjs\");\nvar _constants = require(\"../constants.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\n// Timezone (ISO-8601)\nclass ISOTimezoneParser extends _Parser.Parser {\n priority = 10;\n\n parse(dateString, token) {\n switch (token) {\n case \"x\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.basicOptionalMinutes,\n dateString,\n );\n case \"xx\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.basic,\n dateString,\n );\n case \"xxxx\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.basicOptionalSeconds,\n dateString,\n );\n case \"xxxxx\":\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.extendedOptionalSeconds,\n dateString,\n );\n case \"xxx\":\n default:\n return (0, _utils.parseTimezonePattern)(\n _constants.timezonePatterns.extended,\n dateString,\n );\n }\n }\n\n set(date, flags, value) {\n if (flags.timestampIsSet) return date;\n return (0, _index.constructFrom)(\n date,\n date.getTime() -\n (0, _index2.getTimezoneOffsetInMilliseconds)(date) -\n value,\n );\n }\n\n incompatibleTokens = [\"t\", \"T\", \"X\"];\n}\nexports.ISOTimezoneParser = ISOTimezoneParser;\n", "\"use strict\";\nexports.TimestampSecondsParser = void 0;\nvar _index = require(\"../../../constructFrom.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass TimestampSecondsParser extends _Parser.Parser {\n priority = 40;\n\n parse(dateString) {\n return (0, _utils.parseAnyDigitsSigned)(dateString);\n }\n\n set(date, _flags, value) {\n return [\n (0, _index.constructFrom)(date, value * 1000),\n { timestampIsSet: true },\n ];\n }\n\n incompatibleTokens = \"*\";\n}\nexports.TimestampSecondsParser = TimestampSecondsParser;\n", "\"use strict\";\nexports.TimestampMillisecondsParser = void 0;\nvar _index = require(\"../../../constructFrom.cjs\");\nvar _Parser = require(\"../Parser.cjs\");\n\nvar _utils = require(\"../utils.cjs\");\n\nclass TimestampMillisecondsParser extends _Parser.Parser {\n priority = 20;\n\n parse(dateString) {\n return (0, _utils.parseAnyDigitsSigned)(dateString);\n }\n\n set(date, _flags, value) {\n return [(0, _index.constructFrom)(date, value), { timestampIsSet: true }];\n }\n\n incompatibleTokens = \"*\";\n}\nexports.TimestampMillisecondsParser = TimestampMillisecondsParser;\n", "\"use strict\";\nexports.parsers = void 0;\nvar _EraParser = require(\"./parsers/EraParser.cjs\");\nvar _YearParser = require(\"./parsers/YearParser.cjs\");\nvar _LocalWeekYearParser = require(\"./parsers/LocalWeekYearParser.cjs\");\nvar _ISOWeekYearParser = require(\"./parsers/ISOWeekYearParser.cjs\");\nvar _ExtendedYearParser = require(\"./parsers/ExtendedYearParser.cjs\");\nvar _QuarterParser = require(\"./parsers/QuarterParser.cjs\");\nvar _StandAloneQuarterParser = require(\"./parsers/StandAloneQuarterParser.cjs\");\nvar _MonthParser = require(\"./parsers/MonthParser.cjs\");\nvar _StandAloneMonthParser = require(\"./parsers/StandAloneMonthParser.cjs\");\nvar _LocalWeekParser = require(\"./parsers/LocalWeekParser.cjs\");\nvar _ISOWeekParser = require(\"./parsers/ISOWeekParser.cjs\");\nvar _DateParser = require(\"./parsers/DateParser.cjs\");\nvar _DayOfYearParser = require(\"./parsers/DayOfYearParser.cjs\");\nvar _DayParser = require(\"./parsers/DayParser.cjs\");\nvar _LocalDayParser = require(\"./parsers/LocalDayParser.cjs\");\nvar _StandAloneLocalDayParser = require(\"./parsers/StandAloneLocalDayParser.cjs\");\nvar _ISODayParser = require(\"./parsers/ISODayParser.cjs\");\nvar _AMPMParser = require(\"./parsers/AMPMParser.cjs\");\nvar _AMPMMidnightParser = require(\"./parsers/AMPMMidnightParser.cjs\");\nvar _DayPeriodParser = require(\"./parsers/DayPeriodParser.cjs\");\nvar _Hour1to12Parser = require(\"./parsers/Hour1to12Parser.cjs\");\nvar _Hour0to23Parser = require(\"./parsers/Hour0to23Parser.cjs\");\nvar _Hour0To11Parser = require(\"./parsers/Hour0To11Parser.cjs\");\nvar _Hour1To24Parser = require(\"./parsers/Hour1To24Parser.cjs\");\nvar _MinuteParser = require(\"./parsers/MinuteParser.cjs\");\nvar _SecondParser = require(\"./parsers/SecondParser.cjs\");\nvar _FractionOfSecondParser = require(\"./parsers/FractionOfSecondParser.cjs\");\nvar _ISOTimezoneWithZParser = require(\"./parsers/ISOTimezoneWithZParser.cjs\");\nvar _ISOTimezoneParser = require(\"./parsers/ISOTimezoneParser.cjs\");\nvar _TimestampSecondsParser = require(\"./parsers/TimestampSecondsParser.cjs\");\nvar _TimestampMillisecondsParser = require(\"./parsers/TimestampMillisecondsParser.cjs\");\n\n/*\n * | | Unit | | Unit |\n * |-----|--------------------------------|-----|--------------------------------|\n * | a | AM, PM | A* | Milliseconds in day |\n * | b | AM, PM, noon, midnight | B | Flexible day period |\n * | c | Stand-alone local day of week | C* | Localized hour w/ day period |\n * | d | Day of month | D | Day of year |\n * | e | Local day of week | E | Day of week |\n * | f | | F* | Day of week in month |\n * | g* | Modified Julian day | G | Era |\n * | h | Hour [1-12] | H | Hour [0-23] |\n * | i! | ISO day of week | I! | ISO week of year |\n * | j* | Localized hour w/ day period | J* | Localized hour w/o day period |\n * | k | Hour [1-24] | K | Hour [0-11] |\n * | l* | (deprecated) | L | Stand-alone month |\n * | m | Minute | M | Month |\n * | n | | N | |\n * | o! | Ordinal number modifier | O* | Timezone (GMT) |\n * | p | | P | |\n * | q | Stand-alone quarter | Q | Quarter |\n * | r* | Related Gregorian year | R! | ISO week-numbering year |\n * | s | Second | S | Fraction of second |\n * | t! | Seconds timestamp | T! | Milliseconds timestamp |\n * | u | Extended year | U* | Cyclic year |\n * | v* | Timezone (generic non-locat.) | V* | Timezone (location) |\n * | w | Local week of year | W* | Week of month |\n * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) |\n * | y | Year (abs) | Y | Local week-numbering year |\n * | z* | Timezone (specific non-locat.) | Z* | Timezone (aliases) |\n *\n * Letters marked by * are not implemented but reserved by Unicode standard.\n *\n * Letters marked by ! are non-standard, but implemented by date-fns:\n * - `o` modifies the previous token to turn it into an ordinal (see `parse` docs)\n * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,\n * i.e. 7 for Sunday, 1 for Monday, etc.\n * - `I` is ISO week of year, as opposed to `w` which is local week of year.\n * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.\n * `R` is supposed to be used in conjunction with `I` and `i`\n * for universal ISO week-numbering date, whereas\n * `Y` is supposed to be used in conjunction with `w` and `e`\n * for week-numbering date specific to the locale.\n */\nconst parsers = (exports.parsers = {\n G: new _EraParser.EraParser(),\n y: new _YearParser.YearParser(),\n Y: new _LocalWeekYearParser.LocalWeekYearParser(),\n R: new _ISOWeekYearParser.ISOWeekYearParser(),\n u: new _ExtendedYearParser.ExtendedYearParser(),\n Q: new _QuarterParser.QuarterParser(),\n q: new _StandAloneQuarterParser.StandAloneQuarterParser(),\n M: new _MonthParser.MonthParser(),\n L: new _StandAloneMonthParser.StandAloneMonthParser(),\n w: new _LocalWeekParser.LocalWeekParser(),\n I: new _ISOWeekParser.ISOWeekParser(),\n d: new _DateParser.DateParser(),\n D: new _DayOfYearParser.DayOfYearParser(),\n E: new _DayParser.DayParser(),\n e: new _LocalDayParser.LocalDayParser(),\n c: new _StandAloneLocalDayParser.StandAloneLocalDayParser(),\n i: new _ISODayParser.ISODayParser(),\n a: new _AMPMParser.AMPMParser(),\n b: new _AMPMMidnightParser.AMPMMidnightParser(),\n B: new _DayPeriodParser.DayPeriodParser(),\n h: new _Hour1to12Parser.Hour1to12Parser(),\n H: new _Hour0to23Parser.Hour0to23Parser(),\n K: new _Hour0To11Parser.Hour0To11Parser(),\n k: new _Hour1To24Parser.Hour1To24Parser(),\n m: new _MinuteParser.MinuteParser(),\n s: new _SecondParser.SecondParser(),\n S: new _FractionOfSecondParser.FractionOfSecondParser(),\n X: new _ISOTimezoneWithZParser.ISOTimezoneWithZParser(),\n x: new _ISOTimezoneParser.ISOTimezoneParser(),\n t: new _TimestampSecondsParser.TimestampSecondsParser(),\n T: new _TimestampMillisecondsParser.TimestampMillisecondsParser(),\n});\n", "\"use strict\";\nObject.defineProperty(exports, \"longFormatters\", {\n enumerable: true,\n get: function () {\n return _index2.longFormatters;\n },\n});\nexports.parse = parse;\nObject.defineProperty(exports, \"parsers\", {\n enumerable: true,\n get: function () {\n return _index7.parsers;\n },\n});\nvar _index = require(\"./_lib/defaultLocale.cjs\");\nvar _index2 = require(\"./_lib/format/longFormatters.cjs\");\nvar _index3 = require(\"./_lib/protectedTokens.cjs\");\n\nvar _index4 = require(\"./constructFrom.cjs\");\nvar _index5 = require(\"./getDefaultOptions.cjs\");\nvar _index6 = require(\"./toDate.cjs\");\n\nvar _Setter = require(\"./parse/_lib/Setter.cjs\");\nvar _index7 = require(\"./parse/_lib/parsers.cjs\");\n\n// Rexports of internal for libraries to use.\n// See: https://github.com/date-fns/date-fns/issues/3638#issuecomment-1877082874\n\n/**\n * The {@link parse} function options.\n */\n\n// This RegExp consists of three parts separated by `|`:\n// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token\n// (one of the certain letters followed by `o`)\n// - (\\w)\\1* matches any sequences of the same letter\n// - '' matches two quote characters in a row\n// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),\n// except a single quote symbol, which ends the sequence.\n// Two quote characters do not end the sequence.\n// If there is no matching single quote\n// then the sequence will continue until the end of the string.\n// - . matches any single character unmatched by previous parts of the RegExps\nconst formattingTokensRegExp =\n /[yYQqMLwIdDecihHKkms]o|(\\w)\\1*|''|'(''|[^'])+('|$)|./g;\n\n// This RegExp catches symbols escaped by quotes, and also\n// sequences of symbols P, p, and the combinations like `PPPPPPPppppp`\nconst longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;\n\nconst escapedStringRegExp = /^'([^]*?)'?$/;\nconst doubleQuoteRegExp = /''/g;\n\nconst notWhitespaceRegExp = /\\S/;\nconst unescapedLatinCharacterRegExp = /[a-zA-Z]/;\n\n/**\n * @name parse\n * @category Common Helpers\n * @summary Parse the date.\n *\n * @description\n * Return the date parsed from string using the given format string.\n *\n * > \u26A0\uFE0F Please note that the `format` tokens differ from Moment.js and other libraries.\n * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * The characters in the format string wrapped between two single quotes characters (') are escaped.\n * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.\n *\n * Format of the format string is based on Unicode Technical Standard #35:\n * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n * with a few additions (see note 5 below the table).\n *\n * Not all tokens are compatible. Combinations that don't make sense or could lead to bugs are prohibited\n * and will throw `RangeError`. For example usage of 24-hour format token with AM/PM token will throw an exception:\n *\n * ```javascript\n * parse('23 AM', 'HH a', new Date())\n * //=> RangeError: The format string mustn't contain `HH` and `a` at the same time\n * ```\n *\n * See the compatibility table: https://docs.google.com/spreadsheets/d/e/2PACX-1vQOPU3xUhplll6dyoMmVUXHKl_8CRDs6_ueLmex3SoqwhuolkuN3O05l4rqx5h1dKX8eb46Ul-CCSrq/pubhtml?gid=0&single=true\n *\n * Accepted format string patterns:\n * | Unit |Prior| Pattern | Result examples | Notes |\n * |---------------------------------|-----|---------|-----------------------------------|-------|\n * | Era | 140 | G..GGG | AD, BC | |\n * | | | GGGG | Anno Domini, Before Christ | 2 |\n * | | | GGGGG | A, B | |\n * | Calendar year | 130 | y | 44, 1, 1900, 2017, 9999 | 4 |\n * | | | yo | 44th, 1st, 1900th, 9999999th | 4,5 |\n * | | | yy | 44, 01, 00, 17 | 4 |\n * | | | yyy | 044, 001, 123, 999 | 4 |\n * | | | yyyy | 0044, 0001, 1900, 2017 | 4 |\n * | | | yyyyy | ... | 2,4 |\n * | Local week-numbering year | 130 | Y | 44, 1, 1900, 2017, 9000 | 4 |\n * | | | Yo | 44th, 1st, 1900th, 9999999th | 4,5 |\n * | | | YY | 44, 01, 00, 17 | 4,6 |\n * | | | YYY | 044, 001, 123, 999 | 4 |\n * | | | YYYY | 0044, 0001, 1900, 2017 | 4,6 |\n * | | | YYYYY | ... | 2,4 |\n * | ISO week-numbering year | 130 | R | -43, 1, 1900, 2017, 9999, -9999 | 4,5 |\n * | | | RR | -43, 01, 00, 17 | 4,5 |\n * | | | RRR | -043, 001, 123, 999, -999 | 4,5 |\n * | | | RRRR | -0043, 0001, 2017, 9999, -9999 | 4,5 |\n * | | | RRRRR | ... | 2,4,5 |\n * | Extended year | 130 | u | -43, 1, 1900, 2017, 9999, -999 | 4 |\n * | | | uu | -43, 01, 99, -99 | 4 |\n * | | | uuu | -043, 001, 123, 999, -999 | 4 |\n * | | | uuuu | -0043, 0001, 2017, 9999, -9999 | 4 |\n * | | | uuuuu | ... | 2,4 |\n * | Quarter (formatting) | 120 | Q | 1, 2, 3, 4 | |\n * | | | Qo | 1st, 2nd, 3rd, 4th | 5 |\n * | | | QQ | 01, 02, 03, 04 | |\n * | | | QQQ | Q1, Q2, Q3, Q4 | |\n * | | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |\n * | | | QQQQQ | 1, 2, 3, 4 | 4 |\n * | Quarter (stand-alone) | 120 | q | 1, 2, 3, 4 | |\n * | | | qo | 1st, 2nd, 3rd, 4th | 5 |\n * | | | qq | 01, 02, 03, 04 | |\n * | | | qqq | Q1, Q2, Q3, Q4 | |\n * | | | qqqq | 1st quarter, 2nd quarter, ... | 2 |\n * | | | qqqqq | 1, 2, 3, 4 | 3 |\n * | Month (formatting) | 110 | M | 1, 2, ..., 12 | |\n * | | | Mo | 1st, 2nd, ..., 12th | 5 |\n * | | | MM | 01, 02, ..., 12 | |\n * | | | MMM | Jan, Feb, ..., Dec | |\n * | | | MMMM | January, February, ..., December | 2 |\n * | | | MMMMM | J, F, ..., D | |\n * | Month (stand-alone) | 110 | L | 1, 2, ..., 12 | |\n * | | | Lo | 1st, 2nd, ..., 12th | 5 |\n * | | | LL | 01, 02, ..., 12 | |\n * | | | LLL | Jan, Feb, ..., Dec | |\n * | | | LLLL | January, February, ..., December | 2 |\n * | | | LLLLL | J, F, ..., D | |\n * | Local week of year | 100 | w | 1, 2, ..., 53 | |\n * | | | wo | 1st, 2nd, ..., 53th | 5 |\n * | | | ww | 01, 02, ..., 53 | |\n * | ISO week of year | 100 | I | 1, 2, ..., 53 | 5 |\n * | | | Io | 1st, 2nd, ..., 53th | 5 |\n * | | | II | 01, 02, ..., 53 | 5 |\n * | Day of month | 90 | d | 1, 2, ..., 31 | |\n * | | | do | 1st, 2nd, ..., 31st | 5 |\n * | | | dd | 01, 02, ..., 31 | |\n * | Day of year | 90 | D | 1, 2, ..., 365, 366 | 7 |\n * | | | Do | 1st, 2nd, ..., 365th, 366th | 5 |\n * | | | DD | 01, 02, ..., 365, 366 | 7 |\n * | | | DDD | 001, 002, ..., 365, 366 | |\n * | | | DDDD | ... | 2 |\n * | Day of week (formatting) | 90 | E..EEE | Mon, Tue, Wed, ..., Sun | |\n * | | | EEEE | Monday, Tuesday, ..., Sunday | 2 |\n * | | | EEEEE | M, T, W, T, F, S, S | |\n * | | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | ISO day of week (formatting) | 90 | i | 1, 2, 3, ..., 7 | 5 |\n * | | | io | 1st, 2nd, ..., 7th | 5 |\n * | | | ii | 01, 02, ..., 07 | 5 |\n * | | | iii | Mon, Tue, Wed, ..., Sun | 5 |\n * | | | iiii | Monday, Tuesday, ..., Sunday | 2,5 |\n * | | | iiiii | M, T, W, T, F, S, S | 5 |\n * | | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 5 |\n * | Local day of week (formatting) | 90 | e | 2, 3, 4, ..., 1 | |\n * | | | eo | 2nd, 3rd, ..., 1st | 5 |\n * | | | ee | 02, 03, ..., 01 | |\n * | | | eee | Mon, Tue, Wed, ..., Sun | |\n * | | | eeee | Monday, Tuesday, ..., Sunday | 2 |\n * | | | eeeee | M, T, W, T, F, S, S | |\n * | | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | Local day of week (stand-alone) | 90 | c | 2, 3, 4, ..., 1 | |\n * | | | co | 2nd, 3rd, ..., 1st | 5 |\n * | | | cc | 02, 03, ..., 01 | |\n * | | | ccc | Mon, Tue, Wed, ..., Sun | |\n * | | | cccc | Monday, Tuesday, ..., Sunday | 2 |\n * | | | ccccc | M, T, W, T, F, S, S | |\n * | | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | AM, PM | 80 | a..aaa | AM, PM | |\n * | | | aaaa | a.m., p.m. | 2 |\n * | | | aaaaa | a, p | |\n * | AM, PM, noon, midnight | 80 | b..bbb | AM, PM, noon, midnight | |\n * | | | bbbb | a.m., p.m., noon, midnight | 2 |\n * | | | bbbbb | a, p, n, mi | |\n * | Flexible day period | 80 | B..BBB | at night, in the morning, ... | |\n * | | | BBBB | at night, in the morning, ... | 2 |\n * | | | BBBBB | at night, in the morning, ... | |\n * | Hour [1-12] | 70 | h | 1, 2, ..., 11, 12 | |\n * | | | ho | 1st, 2nd, ..., 11th, 12th | 5 |\n * | | | hh | 01, 02, ..., 11, 12 | |\n * | Hour [0-23] | 70 | H | 0, 1, 2, ..., 23 | |\n * | | | Ho | 0th, 1st, 2nd, ..., 23rd | 5 |\n * | | | HH | 00, 01, 02, ..., 23 | |\n * | Hour [0-11] | 70 | K | 1, 2, ..., 11, 0 | |\n * | | | Ko | 1st, 2nd, ..., 11th, 0th | 5 |\n * | | | KK | 01, 02, ..., 11, 00 | |\n * | Hour [1-24] | 70 | k | 24, 1, 2, ..., 23 | |\n * | | | ko | 24th, 1st, 2nd, ..., 23rd | 5 |\n * | | | kk | 24, 01, 02, ..., 23 | |\n * | Minute | 60 | m | 0, 1, ..., 59 | |\n * | | | mo | 0th, 1st, ..., 59th | 5 |\n * | | | mm | 00, 01, ..., 59 | |\n * | Second | 50 | s | 0, 1, ..., 59 | |\n * | | | so | 0th, 1st, ..., 59th | 5 |\n * | | | ss | 00, 01, ..., 59 | |\n * | Seconds timestamp | 40 | t | 512969520 | |\n * | | | tt | ... | 2 |\n * | Fraction of second | 30 | S | 0, 1, ..., 9 | |\n * | | | SS | 00, 01, ..., 99 | |\n * | | | SSS | 000, 001, ..., 999 | |\n * | | | SSSS | ... | 2 |\n * | Milliseconds timestamp | 20 | T | 512969520900 | |\n * | | | TT | ... | 2 |\n * | Timezone (ISO-8601 w/ Z) | 10 | X | -08, +0530, Z | |\n * | | | XX | -0800, +0530, Z | |\n * | | | XXX | -08:00, +05:30, Z | |\n * | | | XXXX | -0800, +0530, Z, +123456 | 2 |\n * | | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |\n * | Timezone (ISO-8601 w/o Z) | 10 | x | -08, +0530, +00 | |\n * | | | xx | -0800, +0530, +0000 | |\n * | | | xxx | -08:00, +05:30, +00:00 | 2 |\n * | | | xxxx | -0800, +0530, +0000, +123456 | |\n * | | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |\n * | Long localized date | NA | P | 05/29/1453 | 5,8 |\n * | | | PP | May 29, 1453 | |\n * | | | PPP | May 29th, 1453 | |\n * | | | PPPP | Sunday, May 29th, 1453 | 2,5,8 |\n * | Long localized time | NA | p | 12:00 AM | 5,8 |\n * | | | pp | 12:00:00 AM | |\n * | Combination of date and time | NA | Pp | 05/29/1453, 12:00 AM | |\n * | | | PPpp | May 29, 1453, 12:00:00 AM | |\n * | | | PPPpp | May 29th, 1453 at ... | |\n * | | | PPPPpp | Sunday, May 29th, 1453 at ... | 2,5,8 |\n * Notes:\n * 1. \"Formatting\" units (e.g. formatting quarter) in the default en-US locale\n * are the same as \"stand-alone\" units, but are different in some languages.\n * \"Formatting\" units are declined according to the rules of the language\n * in the context of a date. \"Stand-alone\" units are always nominative singular.\n * In `format` function, they will produce different result:\n *\n * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`\n *\n * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`\n *\n * `parse` will try to match both formatting and stand-alone units interchangeably.\n *\n * 2. Any sequence of the identical letters is a pattern, unless it is escaped by\n * the single quote characters (see below).\n * If the sequence is longer than listed in table:\n * - for numerical units (`yyyyyyyy`) `parse` will try to match a number\n * as wide as the sequence\n * - for text units (`MMMMMMMM`) `parse` will try to match the widest variation of the unit.\n * These variations are marked with \"2\" in the last column of the table.\n *\n * 3. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.\n * These tokens represent the shortest form of the quarter.\n *\n * 4. The main difference between `y` and `u` patterns are B.C. years:\n *\n * | Year | `y` | `u` |\n * |------|-----|-----|\n * | AC 1 | 1 | 1 |\n * | BC 1 | 1 | 0 |\n * | BC 2 | 2 | -1 |\n *\n * Also `yy` will try to guess the century of two digit year by proximity with `referenceDate`:\n *\n * `parse('50', 'yy', new Date(2018, 0, 1)) //=> Sat Jan 01 2050 00:00:00`\n *\n * `parse('75', 'yy', new Date(2018, 0, 1)) //=> Wed Jan 01 1975 00:00:00`\n *\n * while `uu` will just assign the year as is:\n *\n * `parse('50', 'uu', new Date(2018, 0, 1)) //=> Sat Jan 01 0050 00:00:00`\n *\n * `parse('75', 'uu', new Date(2018, 0, 1)) //=> Tue Jan 01 0075 00:00:00`\n *\n * The same difference is true for local and ISO week-numbering years (`Y` and `R`),\n * except local week-numbering years are dependent on `options.weekStartsOn`\n * and `options.firstWeekContainsDate` (compare [setISOWeekYear](https://date-fns.org/docs/setISOWeekYear)\n * and [setWeekYear](https://date-fns.org/docs/setWeekYear)).\n *\n * 5. These patterns are not in the Unicode Technical Standard #35:\n * - `i`: ISO day of week\n * - `I`: ISO week of year\n * - `R`: ISO week-numbering year\n * - `o`: ordinal number modifier\n * - `P`: long localized date\n * - `p`: long localized time\n *\n * 6. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.\n * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * 7. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.\n * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * 8. `P+` tokens do not have a defined priority since they are merely aliases to other tokens based\n * on the given locale.\n *\n * using `en-US` locale: `P` => `MM/dd/yyyy`\n * using `en-US` locale: `p` => `hh:mm a`\n * using `pt-BR` locale: `P` => `dd/MM/yyyy`\n * using `pt-BR` locale: `p` => `HH:mm`\n *\n * Values will be assigned to the date in the descending order of its unit's priority.\n * Units of an equal priority overwrite each other in the order of appearance.\n *\n * If no values of higher priority are parsed (e.g. when parsing string 'January 1st' without a year),\n * the values will be taken from 3rd argument `referenceDate` which works as a context of parsing.\n *\n * `referenceDate` must be passed for correct work of the function.\n * If you're not sure which `referenceDate` to supply, create a new instance of Date:\n * `parse('02/11/2014', 'MM/dd/yyyy', new Date())`\n * In this case parsing will be done in the context of the current date.\n * If `referenceDate` is `Invalid Date` or a value not convertible to valid `Date`,\n * then `Invalid Date` will be returned.\n *\n * The result may vary by locale.\n *\n * If `formatString` matches with `dateString` but does not provides tokens, `referenceDate` will be returned.\n *\n * If parsing failed, `Invalid Date` will be returned.\n * Invalid Date is a Date, whose time value is NaN.\n * Time value of Date: http://es5.github.io/#x15.9.1.1\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param dateStr - The string to parse\n * @param formatStr - The string of tokens\n * @param referenceDate - defines values missing from the parsed dateString\n * @param options - An object with options.\n * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * @returns The parsed date\n *\n * @throws `options.locale` must contain `match` property\n * @throws use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws format string contains an unescaped latin alphabet character\n *\n * @example\n * // Parse 11 February 2014 from middle-endian format:\n * var result = parse('02/11/2014', 'MM/dd/yyyy', new Date())\n * //=> Tue Feb 11 2014 00:00:00\n *\n * @example\n * // Parse 28th of February in Esperanto locale in the context of 2010 year:\n * import eo from 'date-fns/locale/eo'\n * var result = parse('28-a de februaro', \"do 'de' MMMM\", new Date(2010, 0, 1), {\n * locale: eo\n * })\n * //=> Sun Feb 28 2010 00:00:00\n */\nfunction parse(dateStr, formatStr, referenceDate, options) {\n const invalidDate = () =>\n (0, _index4.constructFrom)(options?.in || referenceDate, NaN);\n const defaultOptions = (0, _index5.getDefaultOptions)();\n const locale =\n options?.locale ?? defaultOptions.locale ?? _index.defaultLocale;\n\n const firstWeekContainsDate =\n options?.firstWeekContainsDate ??\n options?.locale?.options?.firstWeekContainsDate ??\n defaultOptions.firstWeekContainsDate ??\n defaultOptions.locale?.options?.firstWeekContainsDate ??\n 1;\n\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n if (!formatStr)\n return dateStr\n ? invalidDate()\n : (0, _index6.toDate)(referenceDate, options?.in);\n\n const subFnOptions = {\n firstWeekContainsDate,\n weekStartsOn,\n locale,\n };\n\n // If timezone isn't specified, it will try to use the context or\n // the reference date and fallback to the system time zone.\n const setters = [new _Setter.DateTimezoneSetter(options?.in, referenceDate)];\n\n const tokens = formatStr\n .match(longFormattingTokensRegExp)\n .map((substring) => {\n const firstCharacter = substring[0];\n if (firstCharacter in _index2.longFormatters) {\n const longFormatter = _index2.longFormatters[firstCharacter];\n return longFormatter(substring, locale.formatLong);\n }\n return substring;\n })\n .join(\"\")\n .match(formattingTokensRegExp);\n\n const usedTokens = [];\n\n for (let token of tokens) {\n if (\n !options?.useAdditionalWeekYearTokens &&\n (0, _index3.isProtectedWeekYearToken)(token)\n ) {\n (0, _index3.warnOrThrowProtectedError)(token, formatStr, dateStr);\n }\n if (\n !options?.useAdditionalDayOfYearTokens &&\n (0, _index3.isProtectedDayOfYearToken)(token)\n ) {\n (0, _index3.warnOrThrowProtectedError)(token, formatStr, dateStr);\n }\n\n const firstCharacter = token[0];\n const parser = _index7.parsers[firstCharacter];\n if (parser) {\n const { incompatibleTokens } = parser;\n if (Array.isArray(incompatibleTokens)) {\n const incompatibleToken = usedTokens.find(\n (usedToken) =>\n incompatibleTokens.includes(usedToken.token) ||\n usedToken.token === firstCharacter,\n );\n if (incompatibleToken) {\n throw new RangeError(\n `The format string mustn't contain \\`${incompatibleToken.fullToken}\\` and \\`${token}\\` at the same time`,\n );\n }\n } else if (parser.incompatibleTokens === \"*\" && usedTokens.length > 0) {\n throw new RangeError(\n `The format string mustn't contain \\`${token}\\` and any other token at the same time`,\n );\n }\n\n usedTokens.push({ token: firstCharacter, fullToken: token });\n\n const parseResult = parser.run(\n dateStr,\n token,\n locale.match,\n subFnOptions,\n );\n\n if (!parseResult) {\n return invalidDate();\n }\n\n setters.push(parseResult.setter);\n\n dateStr = parseResult.rest;\n } else {\n if (firstCharacter.match(unescapedLatinCharacterRegExp)) {\n throw new RangeError(\n \"Format string contains an unescaped latin alphabet character `\" +\n firstCharacter +\n \"`\",\n );\n }\n\n // Replace two single quote characters with one single quote character\n if (token === \"''\") {\n token = \"'\";\n } else if (firstCharacter === \"'\") {\n token = cleanEscapedString(token);\n }\n\n // Cut token from string, or, if string doesn't match the token, return Invalid Date\n if (dateStr.indexOf(token) === 0) {\n dateStr = dateStr.slice(token.length);\n } else {\n return invalidDate();\n }\n }\n }\n\n // Check if the remaining input contains something other than whitespace\n if (dateStr.length > 0 && notWhitespaceRegExp.test(dateStr)) {\n return invalidDate();\n }\n\n const uniquePrioritySetters = setters\n .map((setter) => setter.priority)\n .sort((a, b) => b - a)\n .filter((priority, index, array) => array.indexOf(priority) === index)\n .map((priority) =>\n setters\n .filter((setter) => setter.priority === priority)\n .sort((a, b) => b.subPriority - a.subPriority),\n )\n .map((setterArray) => setterArray[0]);\n\n let date = (0, _index6.toDate)(referenceDate, options?.in);\n\n if (isNaN(+date)) return invalidDate();\n\n const flags = {};\n for (const setter of uniquePrioritySetters) {\n if (!setter.validate(date, subFnOptions)) {\n return invalidDate();\n }\n\n const result = setter.set(date, flags, subFnOptions);\n // Result is tuple (date, flags)\n if (Array.isArray(result)) {\n date = result[0];\n Object.assign(flags, result[1]);\n // Result is date\n } else {\n date = result;\n }\n }\n\n return date;\n}\n\nfunction cleanEscapedString(input) {\n return input.match(escapedStringRegExp)[1].replace(doubleQuoteRegExp, \"'\");\n}\n", "\"use strict\";\nexports.isMatch = isMatch;\nvar _index = require(\"./isValid.cjs\");\nvar _index2 = require(\"./parse.cjs\");\n\n/**\n * The {@link isMatch} function options.\n */\n\n/**\n * @name isMatch\n * @category Common Helpers\n * @summary validates the date string against given formats\n *\n * @description\n * Return the true if given date is string correct against the given format else\n * will return false.\n *\n * > \u26A0\uFE0F Please note that the `format` tokens differ from Moment.js and other libraries.\n * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * The characters in the format string wrapped between two single quotes characters (') are escaped.\n * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.\n *\n * Format of the format string is based on Unicode Technical Standard #35:\n * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n * with a few additions (see note 5 below the table).\n *\n * Not all tokens are compatible. Combinations that don't make sense or could lead to bugs are prohibited\n * and will throw `RangeError`. For example usage of 24-hour format token with AM/PM token will throw an exception:\n *\n * ```javascript\n * isMatch('23 AM', 'HH a')\n * //=> RangeError: The format string mustn't contain `HH` and `a` at the same time\n * ```\n *\n * See the compatibility table: https://docs.google.com/spreadsheets/d/e/2PACX-1vQOPU3xUhplll6dyoMmVUXHKl_8CRDs6_ueLmex3SoqwhuolkuN3O05l4rqx5h1dKX8eb46Ul-CCSrq/pubhtml?gid=0&single=true\n *\n * Accepted format string patterns:\n * | Unit |Prior| Pattern | Result examples | Notes |\n * |---------------------------------|-----|---------|-----------------------------------|-------|\n * | Era | 140 | G..GGG | AD, BC | |\n * | | | GGGG | Anno Domini, Before Christ | 2 |\n * | | | GGGGG | A, B | |\n * | Calendar year | 130 | y | 44, 1, 1900, 2017, 9999 | 4 |\n * | | | yo | 44th, 1st, 1900th, 9999999th | 4,5 |\n * | | | yy | 44, 01, 00, 17 | 4 |\n * | | | yyy | 044, 001, 123, 999 | 4 |\n * | | | yyyy | 0044, 0001, 1900, 2017 | 4 |\n * | | | yyyyy | ... | 2,4 |\n * | Local week-numbering year | 130 | Y | 44, 1, 1900, 2017, 9000 | 4 |\n * | | | Yo | 44th, 1st, 1900th, 9999999th | 4,5 |\n * | | | YY | 44, 01, 00, 17 | 4,6 |\n * | | | YYY | 044, 001, 123, 999 | 4 |\n * | | | YYYY | 0044, 0001, 1900, 2017 | 4,6 |\n * | | | YYYYY | ... | 2,4 |\n * | ISO week-numbering year | 130 | R | -43, 1, 1900, 2017, 9999, -9999 | 4,5 |\n * | | | RR | -43, 01, 00, 17 | 4,5 |\n * | | | RRR | -043, 001, 123, 999, -999 | 4,5 |\n * | | | RRRR | -0043, 0001, 2017, 9999, -9999 | 4,5 |\n * | | | RRRRR | ... | 2,4,5 |\n * | Extended year | 130 | u | -43, 1, 1900, 2017, 9999, -999 | 4 |\n * | | | uu | -43, 01, 99, -99 | 4 |\n * | | | uuu | -043, 001, 123, 999, -999 | 4 |\n * | | | uuuu | -0043, 0001, 2017, 9999, -9999 | 4 |\n * | | | uuuuu | ... | 2,4 |\n * | Quarter (formatting) | 120 | Q | 1, 2, 3, 4 | |\n * | | | Qo | 1st, 2nd, 3rd, 4th | 5 |\n * | | | QQ | 01, 02, 03, 04 | |\n * | | | QQQ | Q1, Q2, Q3, Q4 | |\n * | | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |\n * | | | QQQQQ | 1, 2, 3, 4 | 4 |\n * | Quarter (stand-alone) | 120 | q | 1, 2, 3, 4 | |\n * | | | qo | 1st, 2nd, 3rd, 4th | 5 |\n * | | | qq | 01, 02, 03, 04 | |\n * | | | qqq | Q1, Q2, Q3, Q4 | |\n * | | | qqqq | 1st quarter, 2nd quarter, ... | 2 |\n * | | | qqqqq | 1, 2, 3, 4 | 3 |\n * | Month (formatting) | 110 | M | 1, 2, ..., 12 | |\n * | | | Mo | 1st, 2nd, ..., 12th | 5 |\n * | | | MM | 01, 02, ..., 12 | |\n * | | | MMM | Jan, Feb, ..., Dec | |\n * | | | MMMM | January, February, ..., December | 2 |\n * | | | MMMMM | J, F, ..., D | |\n * | Month (stand-alone) | 110 | L | 1, 2, ..., 12 | |\n * | | | Lo | 1st, 2nd, ..., 12th | 5 |\n * | | | LL | 01, 02, ..., 12 | |\n * | | | LLL | Jan, Feb, ..., Dec | |\n * | | | LLLL | January, February, ..., December | 2 |\n * | | | LLLLL | J, F, ..., D | |\n * | Local week of year | 100 | w | 1, 2, ..., 53 | |\n * | | | wo | 1st, 2nd, ..., 53th | 5 |\n * | | | ww | 01, 02, ..., 53 | |\n * | ISO week of year | 100 | I | 1, 2, ..., 53 | 5 |\n * | | | Io | 1st, 2nd, ..., 53th | 5 |\n * | | | II | 01, 02, ..., 53 | 5 |\n * | Day of month | 90 | d | 1, 2, ..., 31 | |\n * | | | do | 1st, 2nd, ..., 31st | 5 |\n * | | | dd | 01, 02, ..., 31 | |\n * | Day of year | 90 | D | 1, 2, ..., 365, 366 | 7 |\n * | | | Do | 1st, 2nd, ..., 365th, 366th | 5 |\n * | | | DD | 01, 02, ..., 365, 366 | 7 |\n * | | | DDD | 001, 002, ..., 365, 366 | |\n * | | | DDDD | ... | 2 |\n * | Day of week (formatting) | 90 | E..EEE | Mon, Tue, Wed, ..., Su | |\n * | | | EEEE | Monday, Tuesday, ..., Sunday | 2 |\n * | | | EEEEE | M, T, W, T, F, S, S | |\n * | | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | ISO day of week (formatting) | 90 | i | 1, 2, 3, ..., 7 | 5 |\n * | | | io | 1st, 2nd, ..., 7th | 5 |\n * | | | ii | 01, 02, ..., 07 | 5 |\n * | | | iii | Mon, Tue, Wed, ..., Su | 5 |\n * | | | iiii | Monday, Tuesday, ..., Sunday | 2,5 |\n * | | | iiiii | M, T, W, T, F, S, S | 5 |\n * | | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 5 |\n * | Local day of week (formatting) | 90 | e | 2, 3, 4, ..., 1 | |\n * | | | eo | 2nd, 3rd, ..., 1st | 5 |\n * | | | ee | 02, 03, ..., 01 | |\n * | | | eee | Mon, Tue, Wed, ..., Su | |\n * | | | eeee | Monday, Tuesday, ..., Sunday | 2 |\n * | | | eeeee | M, T, W, T, F, S, S | |\n * | | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | Local day of week (stand-alone) | 90 | c | 2, 3, 4, ..., 1 | |\n * | | | co | 2nd, 3rd, ..., 1st | 5 |\n * | | | cc | 02, 03, ..., 01 | |\n * | | | ccc | Mon, Tue, Wed, ..., Su | |\n * | | | cccc | Monday, Tuesday, ..., Sunday | 2 |\n * | | | ccccc | M, T, W, T, F, S, S | |\n * | | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |\n * | AM, PM | 80 | a..aaa | AM, PM | |\n * | | | aaaa | a.m., p.m. | 2 |\n * | | | aaaaa | a, p | |\n * | AM, PM, noon, midnight | 80 | b..bbb | AM, PM, noon, midnight | |\n * | | | bbbb | a.m., p.m., noon, midnight | 2 |\n * | | | bbbbb | a, p, n, mi | |\n * | Flexible day period | 80 | B..BBB | at night, in the morning, ... | |\n * | | | BBBB | at night, in the morning, ... | 2 |\n * | | | BBBBB | at night, in the morning, ... | |\n * | Hour [1-12] | 70 | h | 1, 2, ..., 11, 12 | |\n * | | | ho | 1st, 2nd, ..., 11th, 12th | 5 |\n * | | | hh | 01, 02, ..., 11, 12 | |\n * | Hour [0-23] | 70 | H | 0, 1, 2, ..., 23 | |\n * | | | Ho | 0th, 1st, 2nd, ..., 23rd | 5 |\n * | | | HH | 00, 01, 02, ..., 23 | |\n * | Hour [0-11] | 70 | K | 1, 2, ..., 11, 0 | |\n * | | | Ko | 1st, 2nd, ..., 11th, 0th | 5 |\n * | | | KK | 01, 02, ..., 11, 00 | |\n * | Hour [1-24] | 70 | k | 24, 1, 2, ..., 23 | |\n * | | | ko | 24th, 1st, 2nd, ..., 23rd | 5 |\n * | | | kk | 24, 01, 02, ..., 23 | |\n * | Minute | 60 | m | 0, 1, ..., 59 | |\n * | | | mo | 0th, 1st, ..., 59th | 5 |\n * | | | mm | 00, 01, ..., 59 | |\n * | Second | 50 | s | 0, 1, ..., 59 | |\n * | | | so | 0th, 1st, ..., 59th | 5 |\n * | | | ss | 00, 01, ..., 59 | |\n * | Seconds timestamp | 40 | t | 512969520 | |\n * | | | tt | ... | 2 |\n * | Fraction of second | 30 | S | 0, 1, ..., 9 | |\n * | | | SS | 00, 01, ..., 99 | |\n * | | | SSS | 000, 001, ..., 999 | |\n * | | | SSSS | ... | 2 |\n * | Milliseconds timestamp | 20 | T | 512969520900 | |\n * | | | TT | ... | 2 |\n * | Timezone (ISO-8601 w/ Z) | 10 | X | -08, +0530, Z | |\n * | | | XX | -0800, +0530, Z | |\n * | | | XXX | -08:00, +05:30, Z | |\n * | | | XXXX | -0800, +0530, Z, +123456 | 2 |\n * | | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |\n * | Timezone (ISO-8601 w/o Z) | 10 | x | -08, +0530, +00 | |\n * | | | xx | -0800, +0530, +0000 | |\n * | | | xxx | -08:00, +05:30, +00:00 | 2 |\n * | | | xxxx | -0800, +0530, +0000, +123456 | |\n * | | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |\n * | Long localized date | NA | P | 05/29/1453 | 5,8 |\n * | | | PP | May 29, 1453 | |\n * | | | PPP | May 29th, 1453 | |\n * | | | PPPP | Sunday, May 29th, 1453 | 2,5,8 |\n * | Long localized time | NA | p | 12:00 AM | 5,8 |\n * | | | pp | 12:00:00 AM | |\n * | Combination of date and time | NA | Pp | 05/29/1453, 12:00 AM | |\n * | | | PPpp | May 29, 1453, 12:00:00 AM | |\n * | | | PPPpp | May 29th, 1453 at ... | |\n * | | | PPPPpp | Sunday, May 29th, 1453 at ... | 2,5,8 |\n * Notes:\n * 1. \"Formatting\" units (e.g. formatting quarter) in the default en-US locale\n * are the same as \"stand-alone\" units, but are different in some languages.\n * \"Formatting\" units are declined according to the rules of the language\n * in the context of a date. \"Stand-alone\" units are always nominative singular.\n * In `format` function, they will produce different result:\n *\n * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`\n *\n * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`\n *\n * `isMatch` will try to match both formatting and stand-alone units interchangeably.\n *\n * 2. Any sequence of the identical letters is a pattern, unless it is escaped by\n * the single quote characters (see below).\n * If the sequence is longer than listed in table:\n * - for numerical units (`yyyyyyyy`) `isMatch` will try to match a number\n * as wide as the sequence\n * - for text units (`MMMMMMMM`) `isMatch` will try to match the widest variation of the unit.\n * These variations are marked with \"2\" in the last column of the table.\n *\n * 3. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.\n * These tokens represent the shortest form of the quarter.\n *\n * 4. The main difference between `y` and `u` patterns are B.C. years:\n *\n * | Year | `y` | `u` |\n * |------|-----|-----|\n * | AC 1 | 1 | 1 |\n * | BC 1 | 1 | 0 |\n * | BC 2 | 2 | -1 |\n *\n * Also `yy` will try to guess the century of two digit year by proximity with `referenceDate`:\n *\n * `isMatch('50', 'yy') //=> true`\n *\n * `isMatch('75', 'yy') //=> true`\n *\n * while `uu` will use the year as is:\n *\n * `isMatch('50', 'uu') //=> true`\n *\n * `isMatch('75', 'uu') //=> true`\n *\n * The same difference is true for local and ISO week-numbering years (`Y` and `R`),\n * except local week-numbering years are dependent on `options.weekStartsOn`\n * and `options.firstWeekContainsDate` (compare [setISOWeekYear](https://date-fns.org/docs/setISOWeekYear)\n * and [setWeekYear](https://date-fns.org/docs/setWeekYear)).\n *\n * 5. These patterns are not in the Unicode Technical Standard #35:\n * - `i`: ISO day of week\n * - `I`: ISO week of year\n * - `R`: ISO week-numbering year\n * - `o`: ordinal number modifier\n * - `P`: long localized date\n * - `p`: long localized time\n *\n * 6. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.\n * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * 7. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.\n * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * 8. `P+` tokens do not have a defined priority since they are merely aliases to other tokens based\n * on the given locale.\n *\n * using `en-US` locale: `P` => `MM/dd/yyyy`\n * using `en-US` locale: `p` => `hh:mm a`\n * using `pt-BR` locale: `P` => `dd/MM/yyyy`\n * using `pt-BR` locale: `p` => `HH:mm`\n *\n * Values will be checked in the descending order of its unit's priority.\n * Units of an equal priority overwrite each other in the order of appearance.\n *\n * If no values of higher priority are matched (e.g. when matching string 'January 1st' without a year),\n * the values will be taken from today's using `new Date()` date which works as a context of parsing.\n *\n * The result may vary by locale.\n *\n * If `formatString` matches with `dateString` but does not provides tokens, `referenceDate` will be returned.\n *\n * @param dateStr - The date string to verify\n * @param format - The string of tokens\n * @param options - An object with options.\n * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * @returns Is format string a match for date string?\n *\n * @throws `options.locale` must contain `match` property\n * @throws use `yyyy` instead of `YYYY` for formatting years; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `yy` instead of `YY` for formatting years; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `d` instead of `D` for formatting days of the month; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws use `dd` instead of `DD` for formatting days of the month; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n * @throws format string contains an unescaped latin alphabet character\n *\n * @example\n * // Match 11 February 2014 from middle-endian format:\n * const result = isMatch('02/11/2014', 'MM/dd/yyyy')\n * //=> true\n *\n * @example\n * // Match 28th of February in Esperanto locale in the context of 2010 year:\n * import eo from 'date-fns/locale/eo'\n * const result = isMatch('28-a de februaro', \"do 'de' MMMM\", {\n * locale: eo\n * })\n * //=> true\n */\nfunction isMatch(dateStr, formatStr, options) {\n return (0, _index.isValid)(\n (0, _index2.parse)(dateStr, formatStr, new Date(), options),\n );\n}\n", "\"use strict\";\nexports.isMonday = isMonday;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isMonday} function options.\n */\n\n/**\n * @name isMonday\n * @category Weekday Helpers\n * @summary Is the given date Monday?\n *\n * @description\n * Is the given date Monday?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is Monday\n *\n * @example\n * // Is 22 September 2014 Monday?\n * const result = isMonday(new Date(2014, 8, 22))\n * //=> true\n */\nfunction isMonday(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay() === 1;\n}\n", "\"use strict\";\nexports.isPast = isPast;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * @name isPast\n * @category Common Helpers\n * @summary Is the given date in the past?\n * @pure false\n *\n * @description\n * Is the given date in the past?\n *\n * @param date - The date to check\n *\n * @returns The date is in the past\n *\n * @example\n * // If today is 6 October 2014, is 2 July 2014 in the past?\n * const result = isPast(new Date(2014, 6, 2))\n * //=> true\n */\nfunction isPast(date) {\n return +(0, _index.toDate)(date) < Date.now();\n}\n", "\"use strict\";\nexports.startOfHour = startOfHour;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfHour} function options.\n */\n\n/**\n * @name startOfHour\n * @category Hour Helpers\n * @summary Return the start of an hour for the given date.\n *\n * @description\n * Return the start of an hour for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of an hour\n *\n * @example\n * // The start of an hour for 2 September 2014 11:55:00:\n * const result = startOfHour(new Date(2014, 8, 2, 11, 55))\n * //=> Tue Sep 02 2014 11:00:00\n */\nfunction startOfHour(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setMinutes(0, 0, 0);\n return _date;\n}\n", "\"use strict\";\nexports.isSameHour = isSameHour;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./startOfHour.cjs\");\n\n/**\n * The {@link isSameHour} function options.\n */\n\n/**\n * @name isSameHour\n * @category Hour Helpers\n * @summary Are the given dates in the same hour (and same day)?\n *\n * @description\n * Are the given dates in the same hour (and same day)?\n *\n * @param dateLeft - The first date to check\n * @param dateRight - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same hour (and same day)\n *\n * @example\n * // Are 4 September 2014 06:00:00 and 4 September 06:30:00 in the same hour?\n * const result = isSameHour(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 4, 6, 30))\n * //=> true\n *\n * @example\n * // Are 4 September 2014 06:00:00 and 5 September 06:00:00 in the same hour?\n * const result = isSameHour(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 5, 6, 0))\n * //=> false\n */\nfunction isSameHour(dateLeft, dateRight, options) {\n const [dateLeft_, dateRight_] = (0, _index.normalizeDates)(\n options?.in,\n dateLeft,\n dateRight,\n );\n return (\n +(0, _index2.startOfHour)(dateLeft_) ===\n +(0, _index2.startOfHour)(dateRight_)\n );\n}\n", "\"use strict\";\nexports.isSameWeek = isSameWeek;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./startOfWeek.cjs\");\n\n/**\n * The {@link isSameWeek} function options.\n */\n\n/**\n * @name isSameWeek\n * @category Week Helpers\n * @summary Are the given dates in the same week (and month and year)?\n *\n * @description\n * Are the given dates in the same week (and month and year)?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same week (and month and year)\n *\n * @example\n * // Are 31 August 2014 and 4 September 2014 in the same week?\n * const result = isSameWeek(new Date(2014, 7, 31), new Date(2014, 8, 4))\n * //=> true\n *\n * @example\n * // If week starts with Monday,\n * // are 31 August 2014 and 4 September 2014 in the same week?\n * const result = isSameWeek(new Date(2014, 7, 31), new Date(2014, 8, 4), {\n * weekStartsOn: 1\n * })\n * //=> false\n *\n * @example\n * // Are 1 January 2014 and 1 January 2015 in the same week?\n * const result = isSameWeek(new Date(2014, 0, 1), new Date(2015, 0, 1))\n * //=> false\n */\nfunction isSameWeek(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return (\n +(0, _index2.startOfWeek)(laterDate_, options) ===\n +(0, _index2.startOfWeek)(earlierDate_, options)\n );\n}\n", "\"use strict\";\nexports.isSameISOWeek = isSameISOWeek;\nvar _index = require(\"./isSameWeek.cjs\");\n\n/**\n * The {@link isSameISOWeek} function options.\n */\n\n/**\n * @name isSameISOWeek\n * @category ISO Week Helpers\n * @summary Are the given dates in the same ISO week (and year)?\n *\n * @description\n * Are the given dates in the same ISO week (and year)?\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same ISO week (and year)\n *\n * @example\n * // Are 1 September 2014 and 7 September 2014 in the same ISO week?\n * const result = isSameISOWeek(new Date(2014, 8, 1), new Date(2014, 8, 7))\n * //=> true\n *\n * @example\n * // Are 1 September 2014 and 1 September 2015 in the same ISO week?\n * const result = isSameISOWeek(new Date(2014, 8, 1), new Date(2015, 8, 1))\n * //=> false\n */\nfunction isSameISOWeek(laterDate, earlierDate, options) {\n return (0, _index.isSameWeek)(laterDate, earlierDate, {\n ...options,\n weekStartsOn: 1,\n });\n}\n", "\"use strict\";\nexports.isSameISOWeekYear = isSameISOWeekYear;\nvar _index = require(\"./startOfISOWeekYear.cjs\");\n\nvar _index2 = require(\"./_lib/normalizeDates.cjs\");\n\n/**\n * The {@link isSameISOWeekYear} function options.\n */\n\n/**\n * @name isSameISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Are the given dates in the same ISO week-numbering year?\n *\n * @description\n * Are the given dates in the same ISO week-numbering year?\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same ISO week-numbering year\n *\n * @example\n * // Are 29 December 2003 and 2 January 2005 in the same ISO week-numbering year?\n * const result = isSameISOWeekYear(new Date(2003, 11, 29), new Date(2005, 0, 2))\n * //=> true\n */\nfunction isSameISOWeekYear(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index2.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return (\n +(0, _index.startOfISOWeekYear)(laterDate_) ===\n +(0, _index.startOfISOWeekYear)(earlierDate_)\n );\n}\n", "\"use strict\";\nexports.startOfMinute = startOfMinute;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfMinute} function options.\n */\n\n/**\n * @name startOfMinute\n * @category Minute Helpers\n * @summary Return the start of a minute for the given date.\n *\n * @description\n * Return the start of a minute for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of a minute\n *\n * @example\n * // The start of a minute for 1 December 2014 22:15:45.400:\n * const result = startOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400))\n * //=> Mon Dec 01 2014 22:15:00\n */\nfunction startOfMinute(date, options) {\n const date_ = (0, _index.toDate)(date, options?.in);\n date_.setSeconds(0, 0);\n return date_;\n}\n", "\"use strict\";\nexports.isSameMinute = isSameMinute;\nvar _index = require(\"./startOfMinute.cjs\");\n\n/**\n * @name isSameMinute\n * @category Minute Helpers\n * @summary Are the given dates in the same minute (and hour and day)?\n *\n * @description\n * Are the given dates in the same minute (and hour and day)?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n *\n * @returns The dates are in the same minute (and hour and day)\n *\n * @example\n * // Are 4 September 2014 06:30:00 and 4 September 2014 06:30:15 in the same minute?\n * const result = isSameMinute(\n * new Date(2014, 8, 4, 6, 30),\n * new Date(2014, 8, 4, 6, 30, 15)\n * )\n * //=> true\n *\n * @example\n * // Are 4 September 2014 06:30:00 and 5 September 2014 06:30:00 in the same minute?\n * const result = isSameMinute(\n * new Date(2014, 8, 4, 6, 30),\n * new Date(2014, 8, 5, 6, 30)\n * )\n * //=> false\n */\nfunction isSameMinute(laterDate, earlierDate) {\n return (\n +(0, _index.startOfMinute)(laterDate) ===\n +(0, _index.startOfMinute)(earlierDate)\n );\n}\n", "\"use strict\";\nexports.isSameMonth = isSameMonth;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\n\n/**\n * The {@link isSameMonth} function options.\n */\n\n/**\n * @name isSameMonth\n * @category Month Helpers\n * @summary Are the given dates in the same month (and year)?\n *\n * @description\n * Are the given dates in the same month (and year)?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same month (and year)\n *\n * @example\n * // Are 2 September 2014 and 25 September 2014 in the same month?\n * const result = isSameMonth(new Date(2014, 8, 2), new Date(2014, 8, 25))\n * //=> true\n *\n * @example\n * // Are 2 September 2014 and 25 September 2015 in the same month?\n * const result = isSameMonth(new Date(2014, 8, 2), new Date(2015, 8, 25))\n * //=> false\n */\nfunction isSameMonth(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return (\n laterDate_.getFullYear() === earlierDate_.getFullYear() &&\n laterDate_.getMonth() === earlierDate_.getMonth()\n );\n}\n", "\"use strict\";\nexports.isSameQuarter = isSameQuarter;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\nvar _index2 = require(\"./startOfQuarter.cjs\");\n\n/**\n * The {@link isSameQuarter} function options.\n */\n\n/**\n * @name isSameQuarter\n * @category Quarter Helpers\n * @summary Are the given dates in the same quarter (and year)?\n *\n * @description\n * Are the given dates in the same quarter (and year)?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same quarter (and year)\n *\n * @example\n * // Are 1 January 2014 and 8 March 2014 in the same quarter?\n * const result = isSameQuarter(new Date(2014, 0, 1), new Date(2014, 2, 8))\n * //=> true\n *\n * @example\n * // Are 1 January 2014 and 1 January 2015 in the same quarter?\n * const result = isSameQuarter(new Date(2014, 0, 1), new Date(2015, 0, 1))\n * //=> false\n */\nfunction isSameQuarter(laterDate, earlierDate, options) {\n const [dateLeft_, dateRight_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return (\n +(0, _index2.startOfQuarter)(dateLeft_) ===\n +(0, _index2.startOfQuarter)(dateRight_)\n );\n}\n", "\"use strict\";\nexports.startOfSecond = startOfSecond;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfSecond} function options.\n */\n\n/**\n * @name startOfSecond\n * @category Second Helpers\n * @summary Return the start of a second for the given date.\n *\n * @description\n * Return the start of a second for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The start of a second\n *\n * @example\n * // The start of a second for 1 December 2014 22:15:45.400:\n * const result = startOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400))\n * //=> Mon Dec 01 2014 22:15:45.000\n */\nfunction startOfSecond(date, options) {\n const date_ = (0, _index.toDate)(date, options?.in);\n date_.setMilliseconds(0);\n return date_;\n}\n", "\"use strict\";\nexports.isSameSecond = isSameSecond;\nvar _index = require(\"./startOfSecond.cjs\");\n\n/**\n * @name isSameSecond\n * @category Second Helpers\n * @summary Are the given dates in the same second (and hour and day)?\n *\n * @description\n * Are the given dates in the same second (and hour and day)?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n *\n * @returns The dates are in the same second (and hour and day)\n *\n * @example\n * // Are 4 September 2014 06:30:15.000 and 4 September 2014 06:30.15.500 in the same second?\n * const result = isSameSecond(\n * new Date(2014, 8, 4, 6, 30, 15),\n * new Date(2014, 8, 4, 6, 30, 15, 500)\n * )\n * //=> true\n *\n * @example\n * // Are 4 September 2014 06:00:15.000 and 4 September 2014 06:01.15.000 in the same second?\n * const result = isSameSecond(\n * new Date(2014, 8, 4, 6, 0, 15),\n * new Date(2014, 8, 4, 6, 1, 15)\n * )\n * //=> false\n *\n * @example\n * // Are 4 September 2014 06:00:15.000 and 5 September 2014 06:00.15.000 in the same second?\n * const result = isSameSecond(\n * new Date(2014, 8, 4, 6, 0, 15),\n * new Date(2014, 8, 5, 6, 0, 15)\n * )\n * //=> false\n */\nfunction isSameSecond(laterDate, earlierDate) {\n return (\n +(0, _index.startOfSecond)(laterDate) ===\n +(0, _index.startOfSecond)(earlierDate)\n );\n}\n", "\"use strict\";\nexports.isSameYear = isSameYear;\nvar _index = require(\"./_lib/normalizeDates.cjs\");\n\n/**\n * The {@link isSameYear} function options.\n */\n\n/**\n * @name isSameYear\n * @category Year Helpers\n * @summary Are the given dates in the same year?\n *\n * @description\n * Are the given dates in the same year?\n *\n * @param laterDate - The first date to check\n * @param earlierDate - The second date to check\n * @param options - An object with options\n *\n * @returns The dates are in the same year\n *\n * @example\n * // Are 2 September 2014 and 25 September 2014 in the same year?\n * const result = isSameYear(new Date(2014, 8, 2), new Date(2014, 8, 25))\n * //=> true\n */\nfunction isSameYear(laterDate, earlierDate, options) {\n const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(\n options?.in,\n laterDate,\n earlierDate,\n );\n return laterDate_.getFullYear() === earlierDate_.getFullYear();\n}\n", "\"use strict\";\nexports.isThisHour = isThisHour;\nvar _index = require(\"./constructNow.cjs\");\nvar _index2 = require(\"./isSameHour.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link isThisHour} function options.\n */\n\n/**\n * @name isThisHour\n * @category Hour Helpers\n * @summary Is the given date in the same hour as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same hour as the current date?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is in this hour\n *\n * @example\n * // If now is 25 September 2014 18:30:15.500,\n * // is 25 September 2014 18:00:00 in this hour?\n * const result = isThisHour(new Date(2014, 8, 25, 18))\n * //=> true\n */\nfunction isThisHour(date, options) {\n return (0, _index2.isSameHour)(\n (0, _index3.toDate)(date, options?.in),\n (0, _index.constructNow)(options?.in || date),\n );\n}\n", "\"use strict\";\nexports.isThisISOWeek = isThisISOWeek;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameISOWeek.cjs\");\n\n/**\n * The {@link isThisISOWeek} function options.\n */\n\n/**\n * @name isThisISOWeek\n * @category ISO Week Helpers\n * @summary Is the given date in the same ISO week as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same ISO week as the current date?\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is in this ISO week\n *\n * @example\n * // If today is 25 September 2014, is 22 September 2014 in this ISO week?\n * const result = isThisISOWeek(new Date(2014, 8, 22))\n * //=> true\n */\nfunction isThisISOWeek(date, options) {\n return (0, _index3.isSameISOWeek)(\n (0, _index.constructFrom)(options?.in || date, date),\n (0, _index2.constructNow)(options?.in || date),\n );\n}\n", "\"use strict\";\nexports.isThisMinute = isThisMinute;\nvar _index = require(\"./constructNow.cjs\");\nvar _index2 = require(\"./isSameMinute.cjs\");\n\n/**\n * @name isThisMinute\n * @category Minute Helpers\n * @summary Is the given date in the same minute as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same minute as the current date?\n *\n * @param date - The date to check\n *\n * @returns The date is in this minute\n *\n * @example\n * // If now is 25 September 2014 18:30:15.500,\n * // is 25 September 2014 18:30:00 in this minute?\n * const result = isThisMinute(new Date(2014, 8, 25, 18, 30))\n * //=> true\n */\n\nfunction isThisMinute(date) {\n return (0, _index2.isSameMinute)(date, (0, _index.constructNow)(date));\n}\n", "\"use strict\";\nexports.isThisMonth = isThisMonth;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameMonth.cjs\");\n\n/**\n * The {@link isThisMonth} function options.\n */\n\n/**\n * @name isThisMonth\n * @category Month Helpers\n * @summary Is the given date in the same month as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same month as the current date?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is in this month\n *\n * @example\n * // If today is 25 September 2014, is 15 September 2014 in this month?\n * const result = isThisMonth(new Date(2014, 8, 15))\n * //=> true\n */\nfunction isThisMonth(date, options) {\n return (0, _index3.isSameMonth)(\n (0, _index.constructFrom)(options?.in || date, date),\n (0, _index2.constructNow)(options?.in || date),\n );\n}\n", "\"use strict\";\nexports.isThisQuarter = isThisQuarter;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameQuarter.cjs\");\n\n/**\n * The {@link isThisQuarter} function options.\n */\n\n/**\n * @name isThisQuarter\n * @category Quarter Helpers\n * @summary Is the given date in the same quarter as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same quarter as the current date?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is in this quarter\n *\n * @example\n * // If today is 25 September 2014, is 2 July 2014 in this quarter?\n * const result = isThisQuarter(new Date(2014, 6, 2))\n * //=> true\n */\nfunction isThisQuarter(date, options) {\n return (0, _index3.isSameQuarter)(\n (0, _index.constructFrom)(options?.in || date, date),\n (0, _index2.constructNow)(options?.in || date),\n );\n}\n", "\"use strict\";\nexports.isThisSecond = isThisSecond;\nvar _index = require(\"./constructNow.cjs\");\nvar _index2 = require(\"./isSameSecond.cjs\");\n\n/**\n * @name isThisSecond\n * @category Second Helpers\n * @summary Is the given date in the same second as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same second as the current date?\n *\n * @param date - The date to check\n *\n * @returns The date is in this second\n *\n * @example\n * // If now is 25 September 2014 18:30:15.500,\n * // is 25 September 2014 18:30:15.000 in this second?\n * const result = isThisSecond(new Date(2014, 8, 25, 18, 30, 15))\n * //=> true\n */\nfunction isThisSecond(date) {\n return (0, _index2.isSameSecond)(date, (0, _index.constructNow)(date));\n}\n", "\"use strict\";\nexports.isThisWeek = isThisWeek;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameWeek.cjs\");\n\n/**\n * The {@link isThisWeek} function options.\n */\n\n/**\n * @name isThisWeek\n * @category Week Helpers\n * @summary Is the given date in the same week as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same week as the current date?\n *\n * @param date - The date to check\n * @param options - The object with options\n *\n * @returns The date is in this week\n *\n * @example\n * // If today is 25 September 2014, is 21 September 2014 in this week?\n * const result = isThisWeek(new Date(2014, 8, 21))\n * //=> true\n *\n * @example\n * // If today is 25 September 2014 and week starts with Monday\n * // is 21 September 2014 in this week?\n * const result = isThisWeek(new Date(2014, 8, 21), { weekStartsOn: 1 })\n * //=> false\n */\nfunction isThisWeek(date, options) {\n return (0, _index3.isSameWeek)(\n (0, _index.constructFrom)(options?.in || date, date),\n (0, _index2.constructNow)(options?.in || date),\n options,\n );\n}\n", "\"use strict\";\nexports.isThisYear = isThisYear;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameYear.cjs\");\n\n/**\n * The {@link isThisYear} function options.\n */\n\n/**\n * @name isThisYear\n * @category Year Helpers\n * @summary Is the given date in the same year as the current date?\n * @pure false\n *\n * @description\n * Is the given date in the same year as the current date?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is in this year\n *\n * @example\n * // If today is 25 September 2014, is 2 July 2014 in this year?\n * const result = isThisYear(new Date(2014, 6, 2))\n * //=> true\n */\nfunction isThisYear(date, options) {\n return (0, _index3.isSameYear)(\n (0, _index.constructFrom)(options?.in || date, date),\n (0, _index2.constructNow)(options?.in || date),\n );\n}\n", "\"use strict\";\nexports.isThursday = isThursday;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isThursday} function options.\n */\n\n/**\n * @name isThursday\n * @category Weekday Helpers\n * @summary Is the given date Thursday?\n *\n * @description\n * Is the given date Thursday?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is Thursday\n *\n * @example\n * // Is 25 September 2014 Thursday?\n * const result = isThursday(new Date(2014, 8, 25))\n * //=> true\n */\nfunction isThursday(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay() === 4;\n}\n", "\"use strict\";\nexports.isToday = isToday;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameDay.cjs\");\n\n/**\n * The {@link isToday} function options.\n */\n\n/**\n * @name isToday\n * @category Day Helpers\n * @summary Is the given date today?\n * @pure false\n *\n * @description\n * Is the given date today?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is today\n *\n * @example\n * // If today is 6 October 2014, is 6 October 14:00:00 today?\n * const result = isToday(new Date(2014, 9, 6, 14, 0))\n * //=> true\n */\nfunction isToday(date, options) {\n return (0, _index3.isSameDay)(\n (0, _index.constructFrom)(options?.in || date, date),\n (0, _index2.constructNow)(options?.in || date),\n );\n}\n", "\"use strict\";\nexports.isTomorrow = isTomorrow;\nvar _index = require(\"./addDays.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameDay.cjs\");\n\n/**\n * The {@link isTomorrow} function options.\n */\n\n/**\n * @name isTomorrow\n * @category Day Helpers\n * @summary Is the given date tomorrow?\n * @pure false\n *\n * @description\n * Is the given date tomorrow?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is tomorrow\n *\n * @example\n * // If today is 6 October 2014, is 7 October 14:00:00 tomorrow?\n * const result = isTomorrow(new Date(2014, 9, 7, 14, 0))\n * //=> true\n */\nfunction isTomorrow(date, options) {\n return (0, _index3.isSameDay)(\n date,\n (0, _index.addDays)((0, _index2.constructNow)(options?.in || date), 1),\n options,\n );\n}\n", "\"use strict\";\nexports.isTuesday = isTuesday;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isTuesday} function options.\n */\n\n/**\n * @name isTuesday\n * @category Weekday Helpers\n * @summary Is the given date Tuesday?\n *\n * @description\n * Is the given date Tuesday?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is Tuesday\n *\n * @example\n * // Is 23 September 2014 Tuesday?\n * const result = isTuesday(new Date(2014, 8, 23))\n * //=> true\n */\nfunction isTuesday(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay() === 2;\n}\n", "\"use strict\";\nexports.isWednesday = isWednesday;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isWednesday} function options.\n */\n\n/**\n * @name isWednesday\n * @category Weekday Helpers\n * @summary Is the given date Wednesday?\n *\n * @description\n * Is the given date Wednesday?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is Wednesday\n *\n * @example\n * // Is 24 September 2014 Wednesday?\n * const result = isWednesday(new Date(2014, 8, 24))\n * //=> true\n */\nfunction isWednesday(date, options) {\n return (0, _index.toDate)(date, options?.in).getDay() === 3;\n}\n", "\"use strict\";\nexports.isWithinInterval = isWithinInterval;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link isWithinInterval} function options.\n */\n\n/**\n * @name isWithinInterval\n * @category Interval Helpers\n * @summary Is the given date within the interval?\n *\n * @description\n * Is the given date within the interval? (Including start and end.)\n *\n * @param date - The date to check\n * @param interval - The interval to check\n * @param options - An object with options\n *\n * @returns The date is within the interval\n *\n * @example\n * // For the date within the interval:\n * isWithinInterval(new Date(2014, 0, 3), {\n * start: new Date(2014, 0, 1),\n * end: new Date(2014, 0, 7)\n * })\n * // => true\n *\n * @example\n * // For the date outside of the interval:\n * isWithinInterval(new Date(2014, 0, 10), {\n * start: new Date(2014, 0, 1),\n * end: new Date(2014, 0, 7)\n * })\n * // => false\n *\n * @example\n * // For date equal to the interval start:\n * isWithinInterval(date, { start, end: date })\n * // => true\n *\n * @example\n * // For date equal to the interval end:\n * isWithinInterval(date, { start: date, end })\n * // => true\n */\nfunction isWithinInterval(date, interval, options) {\n const time = +(0, _index.toDate)(date, options?.in);\n const [startTime, endTime] = [\n +(0, _index.toDate)(interval.start, options?.in),\n +(0, _index.toDate)(interval.end, options?.in),\n ].sort((a, b) => a - b);\n\n return time >= startTime && time <= endTime;\n}\n", "\"use strict\";\nexports.subDays = subDays;\nvar _index = require(\"./addDays.cjs\");\n\n/**\n * The {@link subDays} function options.\n */\n\n/**\n * @name subDays\n * @category Day Helpers\n * @summary Subtract the specified number of days from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of days to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the days subtracted\n *\n * @example\n * // Subtract 10 days from 1 September 2014:\n * const result = subDays(new Date(2014, 8, 1), 10)\n * //=> Fri Aug 22 2014 00:00:00\n */\nfunction subDays(date, amount, options) {\n return (0, _index.addDays)(date, -amount, options);\n}\n", "\"use strict\";\nexports.isYesterday = isYesterday;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\nvar _index3 = require(\"./isSameDay.cjs\");\nvar _index4 = require(\"./subDays.cjs\");\n\n/**\n * The {@link isYesterday} function options.\n */\n\n/**\n * @name isYesterday\n * @category Day Helpers\n * @summary Is the given date yesterday?\n * @pure false\n *\n * @description\n * Is the given date yesterday?\n *\n * @param date - The date to check\n * @param options - An object with options\n *\n * @returns The date is yesterday\n *\n * @example\n * // If today is 6 October 2014, is 5 October 14:00:00 yesterday?\n * const result = isYesterday(new Date(2014, 9, 5, 14, 0))\n * //=> true\n */\nfunction isYesterday(date, options) {\n return (0, _index3.isSameDay)(\n (0, _index.constructFrom)(options?.in || date, date),\n (0, _index4.subDays)((0, _index2.constructNow)(options?.in || date), 1),\n );\n}\n", "\"use strict\";\nexports.lastDayOfDecade = lastDayOfDecade;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link lastDayOfDecade} function options.\n */\n\n/**\n * @name lastDayOfDecade\n * @category Decade Helpers\n * @summary Return the last day of a decade for the given date.\n *\n * @description\n * Return the last day of a decade for the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows using extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type; inferred from arguments or specified by context.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The last day of a decade\n *\n * @example\n * // The last day of a decade for 21 December 2012 21:12:00:\n * const result = lastDayOfDecade(new Date(2012, 11, 21, 21, 12, 00))\n * //=> Wed Dec 31 2019 00:00:00\n */\nfunction lastDayOfDecade(date, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n const year = _date.getFullYear();\n const decade = 9 + Math.floor(year / 10) * 10;\n _date.setFullYear(decade + 1, 0, 0);\n _date.setHours(0, 0, 0, 0);\n return (0, _index.toDate)(_date, options?.in);\n}\n", "\"use strict\";\nexports.lastDayOfWeek = lastDayOfWeek;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link lastDayOfWeek} function options.\n */\n\n/**\n * @name lastDayOfWeek\n * @category Week Helpers\n * @summary Return the last day of a week for the given date.\n *\n * @description\n * Return the last day of a week for the given date.\n * The result will be in the local timezone unless a context is specified.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The last day of a week\n */\nfunction lastDayOfWeek(date, options) {\n const defaultOptions = (0, _index.getDefaultOptions)();\n const weekStartsOn =\n options?.weekStartsOn ??\n options?.locale?.options?.weekStartsOn ??\n defaultOptions.weekStartsOn ??\n defaultOptions.locale?.options?.weekStartsOn ??\n 0;\n\n const _date = (0, _index2.toDate)(date, options?.in);\n const day = _date.getDay();\n const diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);\n\n _date.setHours(0, 0, 0, 0);\n _date.setDate(_date.getDate() + diff);\n\n return _date;\n}\n", "\"use strict\";\nexports.lastDayOfISOWeek = lastDayOfISOWeek;\nvar _index = require(\"./lastDayOfWeek.cjs\");\n\n/**\n * The {@link lastDayOfISOWeek} function options.\n */\n\n/**\n * @name lastDayOfISOWeek\n * @category ISO Week Helpers\n * @summary Return the last day of an ISO week for the given date.\n *\n * @description\n * Return the last day of an ISO week for the given date.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The Date type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [UTCDate](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The last day of an ISO week\n *\n * @example\n * // The last day of an ISO week for 2 September 2014 11:55:00:\n * const result = lastDayOfISOWeek(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Sun Sep 07 2014 00:00:00\n */\nfunction lastDayOfISOWeek(date, options) {\n return (0, _index.lastDayOfWeek)(date, { ...options, weekStartsOn: 1 });\n}\n", "\"use strict\";\nexports.lastDayOfISOWeekYear = lastDayOfISOWeekYear;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./getISOWeekYear.cjs\");\nvar _index3 = require(\"./startOfISOWeek.cjs\");\n\n/**\n * The {@link lastDayOfISOWeekYear} function options.\n */\n\n/**\n * @name lastDayOfISOWeekYear\n * @category ISO Week-Numbering Year Helpers\n * @summary Return the last day of an ISO week-numbering year for the given date.\n *\n * @description\n * Return the last day of an ISO week-numbering year,\n * which always starts 3 days before the year's first Thursday.\n * The result will be in the local timezone.\n *\n * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The end of an ISO week-numbering year\n *\n * @example\n * // The last day of an ISO week-numbering year for 2 July 2005:\n * const result = lastDayOfISOWeekYear(new Date(2005, 6, 2))\n * //=> Sun Jan 01 2006 00:00:00\n */\nfunction lastDayOfISOWeekYear(date, options) {\n const year = (0, _index2.getISOWeekYear)(date, options);\n const fourthOfJanuary = (0, _index.constructFrom)(options?.in || date, 0);\n fourthOfJanuary.setFullYear(year + 1, 0, 4);\n fourthOfJanuary.setHours(0, 0, 0, 0);\n\n const date_ = (0, _index3.startOfISOWeek)(fourthOfJanuary, options);\n date_.setDate(date_.getDate() - 1);\n return date_;\n}\n", "\"use strict\";\nexports.lastDayOfQuarter = lastDayOfQuarter;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link lastDayOfQuarter} function options.\n */\n\n/**\n * @name lastDayOfQuarter\n * @category Quarter Helpers\n * @summary Return the last day of a year quarter for the given date.\n *\n * @description\n * Return the last day of a year quarter for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - The options\n *\n * @returns The last day of a quarter\n *\n * @example\n * // The last day of a quarter for 2 September 2014 11:55:00:\n * const result = lastDayOfQuarter(new Date(2014, 8, 2, 11, 55, 0))\n * //=> Tue Sep 30 2014 00:00:00\n */\nfunction lastDayOfQuarter(date, options) {\n const date_ = (0, _index.toDate)(date, options?.in);\n const currentMonth = date_.getMonth();\n const month = currentMonth - (currentMonth % 3) + 3;\n date_.setMonth(month, 0);\n date_.setHours(0, 0, 0, 0);\n return date_;\n}\n", "\"use strict\";\nexports.lastDayOfYear = lastDayOfYear;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link lastDayOfYear} function options.\n */\n\n/**\n * @name lastDayOfYear\n * @category Year Helpers\n * @summary Return the last day of a year for the given date.\n *\n * @description\n * Return the last day of a year for the given date.\n * The result will be in the local timezone.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The last day of a year\n *\n * @example\n * // The last day of a year for 2 September 2014 11:55:00:\n * const result = lastDayOfYear(new Date(2014, 8, 2, 11, 55, 00))\n * //=> Wed Dec 31 2014 00:00:00\n */\nfunction lastDayOfYear(date, options) {\n const date_ = (0, _index.toDate)(date, options?.in);\n const year = date_.getFullYear();\n date_.setFullYear(year + 1, 0, 0);\n date_.setHours(0, 0, 0, 0);\n return date_;\n}\n", "\"use strict\";\nexports.lightFormat = lightFormat;\nObject.defineProperty(exports, \"lightFormatters\", {\n enumerable: true,\n get: function () {\n return _index.lightFormatters;\n },\n});\nvar _index = require(\"./_lib/format/lightFormatters.cjs\");\nvar _index2 = require(\"./isValid.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n// Rexports of internal for libraries to use.\n// See: https://github.com/date-fns/date-fns/issues/3638#issuecomment-1877082874\n\n// This RegExp consists of three parts separated by `|`:\n// - (\\w)\\1* matches any sequences of the same letter\n// - '' matches two quote characters in a row\n// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),\n// except a single quote symbol, which ends the sequence.\n// Two quote characters do not end the sequence.\n// If there is no matching single quote\n// then the sequence will continue until the end of the string.\n// - . matches any single character unmatched by previous parts of the RegExps\nconst formattingTokensRegExp = /(\\w)\\1*|''|'(''|[^'])+('|$)|./g;\n\nconst escapedStringRegExp = /^'([^]*?)'?$/;\nconst doubleQuoteRegExp = /''/g;\nconst unescapedLatinCharacterRegExp = /[a-zA-Z]/;\n\n/**\n * @private\n */\n\n/**\n * @name lightFormat\n * @category Common Helpers\n * @summary Format the date.\n *\n * @description\n * Return the formatted date string in the given format. Unlike `format`,\n * `lightFormat` doesn't use locales and outputs date using the most popular tokens.\n *\n * > \u26A0\uFE0F Please note that the `lightFormat` tokens differ from Moment.js and other libraries.\n * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md\n *\n * The characters wrapped between two single quotes characters (') are escaped.\n * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.\n *\n * Format of the string is based on Unicode Technical Standard #35:\n * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n *\n * Accepted patterns:\n * | Unit | Pattern | Result examples |\n * |---------------------------------|---------|-----------------------------------|\n * | AM, PM | a..aaa | AM, PM |\n * | | aaaa | a.m., p.m. |\n * | | aaaaa | a, p |\n * | Calendar year | y | 44, 1, 1900, 2017 |\n * | | yy | 44, 01, 00, 17 |\n * | | yyy | 044, 001, 000, 017 |\n * | | yyyy | 0044, 0001, 1900, 2017 |\n * | Month (formatting) | M | 1, 2, ..., 12 |\n * | | MM | 01, 02, ..., 12 |\n * | Day of month | d | 1, 2, ..., 31 |\n * | | dd | 01, 02, ..., 31 |\n * | Hour [1-12] | h | 1, 2, ..., 11, 12 |\n * | | hh | 01, 02, ..., 11, 12 |\n * | Hour [0-23] | H | 0, 1, 2, ..., 23 |\n * | | HH | 00, 01, 02, ..., 23 |\n * | Minute | m | 0, 1, ..., 59 |\n * | | mm | 00, 01, ..., 59 |\n * | Second | s | 0, 1, ..., 59 |\n * | | ss | 00, 01, ..., 59 |\n * | Fraction of second | S | 0, 1, ..., 9 |\n * | | SS | 00, 01, ..., 99 |\n * | | SSS | 000, 001, ..., 999 |\n * | | SSSS | ... |\n *\n * @param date - The original date\n * @param format - The string of tokens\n *\n * @returns The formatted date string\n *\n * @throws `Invalid time value` if the date is invalid\n * @throws format string contains an unescaped latin alphabet character\n *\n * @example\n * const result = lightFormat(new Date(2014, 1, 11), 'yyyy-MM-dd')\n * //=> '2014-02-11'\n */\nfunction lightFormat(date, formatStr) {\n const date_ = (0, _index3.toDate)(date);\n\n if (!(0, _index2.isValid)(date_)) {\n throw new RangeError(\"Invalid time value\");\n }\n\n const tokens = formatStr.match(formattingTokensRegExp);\n\n // The only case when formattingTokensRegExp doesn't match the string is when it's empty\n if (!tokens) return \"\";\n\n const result = tokens\n .map((substring) => {\n // Replace two single quote characters with one single quote character\n if (substring === \"''\") {\n return \"'\";\n }\n\n const firstCharacter = substring[0];\n if (firstCharacter === \"'\") {\n return cleanEscapedString(substring);\n }\n\n const formatter = _index.lightFormatters[firstCharacter];\n if (formatter) {\n return formatter(date_, substring);\n }\n\n if (firstCharacter.match(unescapedLatinCharacterRegExp)) {\n throw new RangeError(\n \"Format string contains an unescaped latin alphabet character `\" +\n firstCharacter +\n \"`\",\n );\n }\n\n return substring;\n })\n .join(\"\");\n\n return result;\n}\n\nfunction cleanEscapedString(input) {\n const matches = input.match(escapedStringRegExp);\n if (!matches) return input;\n return matches[1].replace(doubleQuoteRegExp, \"'\");\n}\n", "\"use strict\";\nexports.milliseconds = milliseconds;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name milliseconds\n * @category Millisecond Helpers\n * @summary\n * Returns the number of milliseconds in the specified, years, months, weeks, days, hours, minutes and seconds.\n *\n * @description\n * Returns the number of milliseconds in the specified, years, months, weeks, days, hours, minutes and seconds.\n *\n * One years equals 365.2425 days according to the formula:\n *\n * > Leap year occurs every 4 years, except for years that are divisible by 100 and not divisible by 400.\n * > 1 mean year = (365+1/4-1/100+1/400) days = 365.2425 days\n *\n * One month is a year divided by 12.\n *\n * @param duration - The object with years, months, weeks, days, hours, minutes and seconds to be added.\n *\n * @returns The milliseconds\n *\n * @example\n * // 1 year in milliseconds\n * milliseconds({ years: 1 })\n * //=> 31556952000\n *\n * // 3 months in milliseconds\n * milliseconds({ months: 3 })\n * //=> 7889238000\n */\nfunction milliseconds({ years, months, weeks, days, hours, minutes, seconds }) {\n let totalDays = 0;\n\n if (years) totalDays += years * _index.daysInYear;\n if (months) totalDays += months * (_index.daysInYear / 12);\n if (weeks) totalDays += weeks * 7;\n if (days) totalDays += days;\n\n let totalSeconds = totalDays * 24 * 60 * 60;\n\n if (hours) totalSeconds += hours * 60 * 60;\n if (minutes) totalSeconds += minutes * 60;\n if (seconds) totalSeconds += seconds;\n\n return Math.trunc(totalSeconds * 1000);\n}\n", "\"use strict\";\nexports.millisecondsToHours = millisecondsToHours;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name millisecondsToHours\n * @category Conversion Helpers\n * @summary Convert milliseconds to hours.\n *\n * @description\n * Convert a number of milliseconds to a full number of hours.\n *\n * @param milliseconds - The number of milliseconds to be converted\n *\n * @returns The number of milliseconds converted in hours\n *\n * @example\n * // Convert 7200000 milliseconds to hours:\n * const result = millisecondsToHours(7200000)\n * //=> 2\n *\n * @example\n * // It uses floor rounding:\n * const result = millisecondsToHours(7199999)\n * //=> 1\n */\nfunction millisecondsToHours(milliseconds) {\n const hours = milliseconds / _index.millisecondsInHour;\n return Math.trunc(hours);\n}\n", "\"use strict\";\nexports.millisecondsToMinutes = millisecondsToMinutes;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name millisecondsToMinutes\n * @category Conversion Helpers\n * @summary Convert milliseconds to minutes.\n *\n * @description\n * Convert a number of milliseconds to a full number of minutes.\n *\n * @param milliseconds - The number of milliseconds to be converted\n *\n * @returns The number of milliseconds converted in minutes\n *\n * @example\n * // Convert 60000 milliseconds to minutes:\n * const result = millisecondsToMinutes(60000)\n * //=> 1\n *\n * @example\n * // It uses floor rounding:\n * const result = millisecondsToMinutes(119999)\n * //=> 1\n */\nfunction millisecondsToMinutes(milliseconds) {\n const minutes = milliseconds / _index.millisecondsInMinute;\n return Math.trunc(minutes);\n}\n", "\"use strict\";\nexports.millisecondsToSeconds = millisecondsToSeconds;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name millisecondsToSeconds\n * @category Conversion Helpers\n * @summary Convert milliseconds to seconds.\n *\n * @description\n * Convert a number of milliseconds to a full number of seconds.\n *\n * @param milliseconds - The number of milliseconds to be converted\n *\n * @returns The number of milliseconds converted in seconds\n *\n * @example\n * // Convert 1000 milliseconds to seconds:\n * const result = millisecondsToSeconds(1000)\n * //=> 1\n *\n * @example\n * // It uses floor rounding:\n * const result = millisecondsToSeconds(1999)\n * //=> 1\n */\nfunction millisecondsToSeconds(milliseconds) {\n const seconds = milliseconds / _index.millisecondsInSecond;\n return Math.trunc(seconds);\n}\n", "\"use strict\";\nexports.minutesToHours = minutesToHours;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name minutesToHours\n * @category Conversion Helpers\n * @summary Convert minutes to hours.\n *\n * @description\n * Convert a number of minutes to a full number of hours.\n *\n * @param minutes - The number of minutes to be converted\n *\n * @returns The number of minutes converted in hours\n *\n * @example\n * // Convert 140 minutes to hours:\n * const result = minutesToHours(120)\n * //=> 2\n *\n * @example\n * // It uses floor rounding:\n * const result = minutesToHours(179)\n * //=> 2\n */\nfunction minutesToHours(minutes) {\n const hours = minutes / _index.minutesInHour;\n return Math.trunc(hours);\n}\n", "\"use strict\";\nexports.minutesToMilliseconds = minutesToMilliseconds;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name minutesToMilliseconds\n * @category Conversion Helpers\n * @summary Convert minutes to milliseconds.\n *\n * @description\n * Convert a number of minutes to a full number of milliseconds.\n *\n * @param minutes - The number of minutes to be converted\n *\n * @returns The number of minutes converted in milliseconds\n *\n * @example\n * // Convert 2 minutes to milliseconds\n * const result = minutesToMilliseconds(2)\n * //=> 120000\n */\nfunction minutesToMilliseconds(minutes) {\n return Math.trunc(minutes * _index.millisecondsInMinute);\n}\n", "\"use strict\";\nexports.minutesToSeconds = minutesToSeconds;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name minutesToSeconds\n * @category Conversion Helpers\n * @summary Convert minutes to seconds.\n *\n * @description\n * Convert a number of minutes to a full number of seconds.\n *\n * @param minutes - The number of minutes to be converted\n *\n * @returns The number of minutes converted in seconds\n *\n * @example\n * // Convert 2 minutes to seconds\n * const result = minutesToSeconds(2)\n * //=> 120\n */\nfunction minutesToSeconds(minutes) {\n return Math.trunc(minutes * _index.secondsInMinute);\n}\n", "\"use strict\";\nexports.monthsToQuarters = monthsToQuarters;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name monthsToQuarters\n * @category Conversion Helpers\n * @summary Convert number of months to quarters.\n *\n * @description\n * Convert a number of months to a full number of quarters.\n *\n * @param months - The number of months to be converted.\n *\n * @returns The number of months converted in quarters\n *\n * @example\n * // Convert 6 months to quarters:\n * const result = monthsToQuarters(6)\n * //=> 2\n *\n * @example\n * // It uses floor rounding:\n * const result = monthsToQuarters(7)\n * //=> 2\n */\nfunction monthsToQuarters(months) {\n const quarters = months / _index.monthsInQuarter;\n return Math.trunc(quarters);\n}\n", "\"use strict\";\nexports.monthsToYears = monthsToYears;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name monthsToYears\n * @category Conversion Helpers\n * @summary Convert number of months to years.\n *\n * @description\n * Convert a number of months to a full number of years.\n *\n * @param months - The number of months to be converted\n *\n * @returns The number of months converted in years\n *\n * @example\n * // Convert 36 months to years:\n * const result = monthsToYears(36)\n * //=> 3\n *\n * // It uses floor rounding:\n * const result = monthsToYears(40)\n * //=> 3\n */\nfunction monthsToYears(months) {\n const years = months / _index.monthsInYear;\n return Math.trunc(years);\n}\n", "\"use strict\";\nexports.nextDay = nextDay;\nvar _index = require(\"./addDays.cjs\");\nvar _index2 = require(\"./getDay.cjs\");\n\n/**\n * The {@link nextDay} function options.\n */\n\n/**\n * @name nextDay\n * @category Weekday Helpers\n * @summary When is the next day of the week? 0-6 the day of the week, 0 represents Sunday.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to check\n * @param day - Day of the week\n * @param options - An object with options\n *\n * @returns The date is the next day of the week\n *\n * @example\n * // When is the next Monday after Mar, 20, 2020?\n * const result = nextDay(new Date(2020, 2, 20), 1)\n * //=> Mon Mar 23 2020 00:00:00\n *\n * @example\n * // When is the next Tuesday after Mar, 21, 2020?\n * const result = nextDay(new Date(2020, 2, 21), 2)\n * //=> Tue Mar 24 2020 00:00:00\n */\nfunction nextDay(date, day, options) {\n let delta = day - (0, _index2.getDay)(date, options);\n if (delta <= 0) delta += 7;\n\n return (0, _index.addDays)(date, delta, options);\n}\n", "\"use strict\";\nexports.nextFriday = nextFriday;\nvar _index = require(\"./nextDay.cjs\");\n\n/**\n * The {@link nextFriday} function options.\n */\n\n/**\n * @name nextFriday\n * @category Weekday Helpers\n * @summary When is the next Friday?\n *\n * @description\n * When is the next Friday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The next Friday\n *\n * @example\n * // When is the next Friday after Mar, 22, 2020?\n * const result = nextFriday(new Date(2020, 2, 22))\n * //=> Fri Mar 27 2020 00:00:00\n */\nfunction nextFriday(date, options) {\n return (0, _index.nextDay)(date, 5, options);\n}\n", "\"use strict\";\nexports.nextMonday = nextMonday;\nvar _index = require(\"./nextDay.cjs\");\n\n/**\n * The {@link nextMonday} function options.\n */\n\n/**\n * @name nextMonday\n * @category Weekday Helpers\n * @summary When is the next Monday?\n *\n * @description\n * When is the next Monday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, returned from the context function if passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The next Monday\n *\n * @example\n * // When is the next Monday after Mar, 22, 2020?\n * const result = nextMonday(new Date(2020, 2, 22))\n * //=> Mon Mar 23 2020 00:00:00\n */\nfunction nextMonday(date, options) {\n return (0, _index.nextDay)(date, 1, options);\n}\n", "\"use strict\";\nexports.nextSaturday = nextSaturday;\nvar _index = require(\"./nextDay.cjs\");\n\n/**\n * The {@link nextSaturday} function options.\n */\n\n/**\n * @name nextSaturday\n * @category Weekday Helpers\n * @summary When is the next Saturday?\n *\n * @description\n * When is the next Saturday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The next Saturday\n *\n * @example\n * // When is the next Saturday after Mar, 22, 2020?\n * const result = nextSaturday(new Date(2020, 2, 22))\n * //=> Sat Mar 28 2020 00:00:00\n */\nfunction nextSaturday(date, options) {\n return (0, _index.nextDay)(date, 6, options);\n}\n", "\"use strict\";\nexports.nextSunday = nextSunday;\nvar _index = require(\"./nextDay.cjs\");\n\n/**\n * The {@link nextSunday} function options.\n */\n\n/**\n * @name nextSunday\n * @category Weekday Helpers\n * @summary When is the next Sunday?\n *\n * @description\n * When is the next Sunday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned if a context is provided.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The next Sunday\n *\n * @example\n * // When is the next Sunday after March 22, 2020?\n * const result = nextSunday(new Date(2020, 2, 22))\n * //=> Sun Mar 29 2020 00:00:00\n */\nfunction nextSunday(date, options) {\n return (0, _index.nextDay)(date, 0, options);\n}\n", "\"use strict\";\nexports.nextThursday = nextThursday;\nvar _index = require(\"./nextDay.cjs\");\n\n/**\n * The {@link nextThursday} function options.\n */\n\n/**\n * @name nextThursday\n * @category Weekday Helpers\n * @summary When is the next Thursday?\n *\n * @description\n * When is the next Thursday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The next Thursday\n *\n * @example\n * // When is the next Thursday after Mar, 22, 2020?\n * const result = nextThursday(new Date(2020, 2, 22))\n * //=> Thur Mar 26 2020 00:00:00\n */\nfunction nextThursday(date, options) {\n return (0, _index.nextDay)(date, 4, options);\n}\n", "\"use strict\";\nexports.nextTuesday = nextTuesday;\nvar _index = require(\"./nextDay.cjs\");\n\n/**\n * The {@link nextTuesday} function options.\n */\n\n/**\n * @name nextTuesday\n * @category Weekday Helpers\n * @summary When is the next Tuesday?\n *\n * @description\n * When is the next Tuesday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The next Tuesday\n *\n * @example\n * // When is the next Tuesday after Mar, 22, 2020?\n * const result = nextTuesday(new Date(2020, 2, 22))\n * //=> Tue Mar 24 2020 00:00:00\n */\nfunction nextTuesday(date, options) {\n return (0, _index.nextDay)(date, 2, options);\n}\n", "\"use strict\";\nexports.nextWednesday = nextWednesday;\nvar _index = require(\"./nextDay.cjs\");\n\n/**\n * The {@link nextWednesday} function options.\n */\n\n/**\n * @name nextWednesday\n * @category Weekday Helpers\n * @summary When is the next Wednesday?\n *\n * @description\n * When is the next Wednesday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The next Wednesday\n *\n * @example\n * // When is the next Wednesday after Mar, 22, 2020?\n * const result = nextWednesday(new Date(2020, 2, 22))\n * //=> Wed Mar 25 2020 00:00:00\n */\nfunction nextWednesday(date, options) {\n return (0, _index.nextDay)(date, 3, options);\n}\n", "\"use strict\";\nexports.parseISO = parseISO;\nvar _index = require(\"./constants.cjs\");\n\nvar _index2 = require(\"./constructFrom.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link parseISO} function options.\n */\n\n/**\n * @name parseISO\n * @category Common Helpers\n * @summary Parse ISO string\n *\n * @description\n * Parse the given string in ISO 8601 format and return an instance of Date.\n *\n * Function accepts complete ISO 8601 formats as well as partial implementations.\n * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601\n *\n * If the argument isn't a string, the function cannot parse the string or\n * the values are invalid, it returns Invalid Date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param argument - The value to convert\n * @param options - An object with options\n *\n * @returns The parsed date in the local time zone\n *\n * @example\n * // Convert string '2014-02-11T11:30:30' to date:\n * const result = parseISO('2014-02-11T11:30:30')\n * //=> Tue Feb 11 2014 11:30:30\n *\n * @example\n * // Convert string '+02014101' to date,\n * // if the additional number of digits in the extended year format is 1:\n * const result = parseISO('+02014101', { additionalDigits: 1 })\n * //=> Fri Apr 11 2014 00:00:00\n */\nfunction parseISO(argument, options) {\n const invalidDate = () => (0, _index2.constructFrom)(options?.in, NaN);\n\n const additionalDigits = options?.additionalDigits ?? 2;\n const dateStrings = splitDateString(argument);\n\n let date;\n if (dateStrings.date) {\n const parseYearResult = parseYear(dateStrings.date, additionalDigits);\n date = parseDate(parseYearResult.restDateString, parseYearResult.year);\n }\n\n if (!date || isNaN(+date)) return invalidDate();\n\n const timestamp = +date;\n let time = 0;\n let offset;\n\n if (dateStrings.time) {\n time = parseTime(dateStrings.time);\n if (isNaN(time)) return invalidDate();\n }\n\n if (dateStrings.timezone) {\n offset = parseTimezone(dateStrings.timezone);\n if (isNaN(offset)) return invalidDate();\n } else {\n const tmpDate = new Date(timestamp + time);\n const result = (0, _index3.toDate)(0, options?.in);\n result.setFullYear(\n tmpDate.getUTCFullYear(),\n tmpDate.getUTCMonth(),\n tmpDate.getUTCDate(),\n );\n result.setHours(\n tmpDate.getUTCHours(),\n tmpDate.getUTCMinutes(),\n tmpDate.getUTCSeconds(),\n tmpDate.getUTCMilliseconds(),\n );\n return result;\n }\n\n return (0, _index3.toDate)(timestamp + time + offset, options?.in);\n}\n\nconst patterns = {\n dateTimeDelimiter: /[T ]/,\n timeZoneDelimiter: /[Z ]/i,\n timezone: /([Z+-].*)$/,\n};\n\nconst dateRegex =\n /^-?(?:(\\d{3})|(\\d{2})(?:-?(\\d{2}))?|W(\\d{2})(?:-?(\\d{1}))?|)$/;\nconst timeRegex =\n /^(\\d{2}(?:[.,]\\d*)?)(?::?(\\d{2}(?:[.,]\\d*)?))?(?::?(\\d{2}(?:[.,]\\d*)?))?$/;\nconst timezoneRegex = /^([+-])(\\d{2})(?::?(\\d{2}))?$/;\n\nfunction splitDateString(dateString) {\n const dateStrings = {};\n const array = dateString.split(patterns.dateTimeDelimiter);\n let timeString;\n\n // The regex match should only return at maximum two array elements.\n // [date], [time], or [date, time].\n if (array.length > 2) {\n return dateStrings;\n }\n\n if (/:/.test(array[0])) {\n timeString = array[0];\n } else {\n dateStrings.date = array[0];\n timeString = array[1];\n if (patterns.timeZoneDelimiter.test(dateStrings.date)) {\n dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0];\n timeString = dateString.substr(\n dateStrings.date.length,\n dateString.length,\n );\n }\n }\n\n if (timeString) {\n const token = patterns.timezone.exec(timeString);\n if (token) {\n dateStrings.time = timeString.replace(token[1], \"\");\n dateStrings.timezone = token[1];\n } else {\n dateStrings.time = timeString;\n }\n }\n\n return dateStrings;\n}\n\nfunction parseYear(dateString, additionalDigits) {\n const regex = new RegExp(\n \"^(?:(\\\\d{4}|[+-]\\\\d{\" +\n (4 + additionalDigits) +\n \"})|(\\\\d{2}|[+-]\\\\d{\" +\n (2 + additionalDigits) +\n \"})$)\",\n );\n\n const captures = dateString.match(regex);\n // Invalid ISO-formatted year\n if (!captures) return { year: NaN, restDateString: \"\" };\n\n const year = captures[1] ? parseInt(captures[1]) : null;\n const century = captures[2] ? parseInt(captures[2]) : null;\n\n // either year or century is null, not both\n return {\n year: century === null ? year : century * 100,\n restDateString: dateString.slice((captures[1] || captures[2]).length),\n };\n}\n\nfunction parseDate(dateString, year) {\n // Invalid ISO-formatted year\n if (year === null) return new Date(NaN);\n\n const captures = dateString.match(dateRegex);\n // Invalid ISO-formatted string\n if (!captures) return new Date(NaN);\n\n const isWeekDate = !!captures[4];\n const dayOfYear = parseDateUnit(captures[1]);\n const month = parseDateUnit(captures[2]) - 1;\n const day = parseDateUnit(captures[3]);\n const week = parseDateUnit(captures[4]);\n const dayOfWeek = parseDateUnit(captures[5]) - 1;\n\n if (isWeekDate) {\n if (!validateWeekDate(year, week, dayOfWeek)) {\n return new Date(NaN);\n }\n return dayOfISOWeekYear(year, week, dayOfWeek);\n } else {\n const date = new Date(0);\n if (\n !validateDate(year, month, day) ||\n !validateDayOfYearDate(year, dayOfYear)\n ) {\n return new Date(NaN);\n }\n date.setUTCFullYear(year, month, Math.max(dayOfYear, day));\n return date;\n }\n}\n\nfunction parseDateUnit(value) {\n return value ? parseInt(value) : 1;\n}\n\nfunction parseTime(timeString) {\n const captures = timeString.match(timeRegex);\n if (!captures) return NaN; // Invalid ISO-formatted time\n\n const hours = parseTimeUnit(captures[1]);\n const minutes = parseTimeUnit(captures[2]);\n const seconds = parseTimeUnit(captures[3]);\n\n if (!validateTime(hours, minutes, seconds)) {\n return NaN;\n }\n\n return (\n hours * _index.millisecondsInHour +\n minutes * _index.millisecondsInMinute +\n seconds * 1000\n );\n}\n\nfunction parseTimeUnit(value) {\n return (value && parseFloat(value.replace(\",\", \".\"))) || 0;\n}\n\nfunction parseTimezone(timezoneString) {\n if (timezoneString === \"Z\") return 0;\n\n const captures = timezoneString.match(timezoneRegex);\n if (!captures) return 0;\n\n const sign = captures[1] === \"+\" ? -1 : 1;\n const hours = parseInt(captures[2]);\n const minutes = (captures[3] && parseInt(captures[3])) || 0;\n\n if (!validateTimezone(hours, minutes)) {\n return NaN;\n }\n\n return (\n sign *\n (hours * _index.millisecondsInHour + minutes * _index.millisecondsInMinute)\n );\n}\n\nfunction dayOfISOWeekYear(isoWeekYear, week, day) {\n const date = new Date(0);\n date.setUTCFullYear(isoWeekYear, 0, 4);\n const fourthOfJanuaryDay = date.getUTCDay() || 7;\n const diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay;\n date.setUTCDate(date.getUTCDate() + diff);\n return date;\n}\n\n// Validation functions\n\n// February is null to handle the leap year (using ||)\nconst daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\nfunction isLeapYearIndex(year) {\n return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0);\n}\n\nfunction validateDate(year, month, date) {\n return (\n month >= 0 &&\n month <= 11 &&\n date >= 1 &&\n date <= (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28))\n );\n}\n\nfunction validateDayOfYearDate(year, dayOfYear) {\n return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex(year) ? 366 : 365);\n}\n\nfunction validateWeekDate(_year, week, day) {\n return week >= 1 && week <= 53 && day >= 0 && day <= 6;\n}\n\nfunction validateTime(hours, minutes, seconds) {\n if (hours === 24) {\n return minutes === 0 && seconds === 0;\n }\n\n return (\n seconds >= 0 &&\n seconds < 60 &&\n minutes >= 0 &&\n minutes < 60 &&\n hours >= 0 &&\n hours < 25\n );\n}\n\nfunction validateTimezone(_hours, minutes) {\n return minutes >= 0 && minutes <= 59;\n}\n", "\"use strict\";\nexports.parseJSON = parseJSON;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link parseJSON} function options.\n */\n\n/**\n * Converts a complete ISO date string in UTC time, the typical format for transmitting\n * a date in JSON, to a JavaScript `Date` instance.\n *\n * This is a minimal implementation for converting dates retrieved from a JSON API to\n * a `Date` instance which can be used with other functions in the `date-fns` library.\n * The following formats are supported:\n *\n * - `2000-03-15T05:20:10.123Z`: The output of `.toISOString()` and `JSON.stringify(new Date())`\n * - `2000-03-15T05:20:10Z`: Without milliseconds\n * - `2000-03-15T05:20:10+00:00`: With a zero offset, the default JSON encoded format in some other languages\n * - `2000-03-15T05:20:10+05:45`: With a positive or negative offset, the default JSON encoded format in some other languages\n * - `2000-03-15T05:20:10+0000`: With a zero offset without a colon\n * - `2000-03-15T05:20:10`: Without a trailing 'Z' symbol\n * - `2000-03-15T05:20:10.1234567`: Up to 7 digits in milliseconds field. Only first 3 are taken into account since JS does not allow fractional milliseconds\n * - `2000-03-15 05:20:10`: With a space instead of a 'T' separator for APIs returning a SQL date without reformatting\n *\n * For convenience and ease of use these other input types are also supported\n * via [toDate](https://date-fns.org/docs/toDate):\n *\n * - A `Date` instance will be cloned\n * - A `number` will be treated as a timestamp\n *\n * Any other input type or invalid date strings will return an `Invalid Date`.\n *\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param dateStr - A fully formed ISO8601 date string to convert\n * @param options - An object with options\n *\n * @returns The parsed date in the local time zone\n */\nfunction parseJSON(dateStr, options) {\n const parts = dateStr.match(\n /(\\d{4})-(\\d{2})-(\\d{2})[T ](\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{0,7}))?(?:Z|(.)(\\d{2}):?(\\d{2})?)?/,\n );\n\n if (!parts) return (0, _index.toDate)(NaN, options?.in);\n\n return (0, _index.toDate)(\n Date.UTC(\n +parts[1],\n +parts[2] - 1,\n +parts[3],\n +parts[4] - (+parts[9] || 0) * (parts[8] == \"-\" ? -1 : 1),\n +parts[5] - (+parts[10] || 0) * (parts[8] == \"-\" ? -1 : 1),\n +parts[6],\n +((parts[7] || \"0\") + \"00\").substring(0, 3),\n ),\n options?.in,\n );\n}\n", "\"use strict\";\nexports.previousDay = previousDay;\nvar _index = require(\"./getDay.cjs\");\nvar _index2 = require(\"./subDays.cjs\");\n\n/**\n * The {@link previousDay} function options.\n */\n\n/**\n * @name previousDay\n * @category Weekday Helpers\n * @summary When is the previous day of the week?\n *\n * @description\n * When is the previous day of the week? 0-6 the day of the week, 0 represents Sunday.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to check\n * @param day - The day of the week\n * @param options - An object with options\n *\n * @returns The date is the previous day of week\n *\n * @example\n * // When is the previous Monday before Mar, 20, 2020?\n * const result = previousDay(new Date(2020, 2, 20), 1)\n * //=> Mon Mar 16 2020 00:00:00\n *\n * @example\n * // When is the previous Tuesday before Mar, 21, 2020?\n * const result = previousDay(new Date(2020, 2, 21), 2)\n * //=> Tue Mar 17 2020 00:00:00\n */\nfunction previousDay(date, day, options) {\n let delta = (0, _index.getDay)(date, options) - day;\n if (delta <= 0) delta += 7;\n\n return (0, _index2.subDays)(date, delta, options);\n}\n", "\"use strict\";\nexports.previousFriday = previousFriday;\nvar _index = require(\"./previousDay.cjs\");\n\n/**\n * The {@link previousFriday} function options.\n */\n\n/**\n * @name previousFriday\n * @category Weekday Helpers\n * @summary When is the previous Friday?\n *\n * @description\n * When is the previous Friday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [UTCDate](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - The options\n *\n * @returns The previous Friday\n *\n * @example\n * // When is the previous Friday before Jun, 19, 2021?\n * const result = previousFriday(new Date(2021, 5, 19))\n * //=> Fri June 18 2021 00:00:00\n */\nfunction previousFriday(date, options) {\n return (0, _index.previousDay)(date, 5, options);\n}\n", "\"use strict\";\nexports.previousMonday = previousMonday;\nvar _index = require(\"./previousDay.cjs\");\n\n/**\n * The {@link previousMonday} function options.\n */\n\n/**\n * @name previousMonday\n * @category Weekday Helpers\n * @summary When is the previous Monday?\n *\n * @description\n * When is the previous Monday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The previous Monday\n *\n * @example\n * // When is the previous Monday before Jun, 18, 2021?\n * const result = previousMonday(new Date(2021, 5, 18))\n * //=> Mon June 14 2021 00:00:00\n */\nfunction previousMonday(date, options) {\n return (0, _index.previousDay)(date, 1, options);\n}\n", "\"use strict\";\nexports.previousSaturday = previousSaturday;\nvar _index = require(\"./previousDay.cjs\");\n\n/**\n * The {@link previousSaturday} function options.\n */\n\n/**\n * @name previousSaturday\n * @category Weekday Helpers\n * @summary When is the previous Saturday?\n *\n * @description\n * When is the previous Saturday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - The options\n *\n * @returns The previous Saturday\n *\n * @example\n * // When is the previous Saturday before Jun, 20, 2021?\n * const result = previousSaturday(new Date(2021, 5, 20))\n * //=> Sat June 19 2021 00:00:00\n */\nfunction previousSaturday(date, options) {\n return (0, _index.previousDay)(date, 6, options);\n}\n", "\"use strict\";\nexports.previousSunday = previousSunday;\nvar _index = require(\"./previousDay.cjs\");\n\n/**\n * The {@link previousSunday} function options.\n */\n\n/**\n * @name previousSunday\n * @category Weekday Helpers\n * @summary When is the previous Sunday?\n *\n * @description\n * When is the previous Sunday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - The options\n *\n * @returns The previous Sunday\n *\n * @example\n * // When is the previous Sunday before Jun, 21, 2021?\n * const result = previousSunday(new Date(2021, 5, 21))\n * //=> Sun June 20 2021 00:00:00\n */\nfunction previousSunday(date, options) {\n return (0, _index.previousDay)(date, 0, options);\n}\n", "\"use strict\";\nexports.previousThursday = previousThursday;\nvar _index = require(\"./previousDay.cjs\");\n\n/**\n * The {@link previousThursday} function options.\n */\n\n/**\n * @name previousThursday\n * @category Weekday Helpers\n * @summary When is the previous Thursday?\n *\n * @description\n * When is the previous Thursday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The previous Thursday\n *\n * @example\n * // When is the previous Thursday before Jun, 18, 2021?\n * const result = previousThursday(new Date(2021, 5, 18))\n * //=> Thu June 17 2021 00:00:00\n */\nfunction previousThursday(date, options) {\n return (0, _index.previousDay)(date, 4, options);\n}\n", "\"use strict\";\nexports.previousTuesday = previousTuesday;\nvar _index = require(\"./previousDay.cjs\");\n\n/**\n * The {@link previousTuesday} function options.\n */\n\n/**\n * @name previousTuesday\n * @category Weekday Helpers\n * @summary When is the previous Tuesday?\n *\n * @description\n * When is the previous Tuesday?\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The previous Tuesday\n *\n * @example\n * // When is the previous Tuesday before Jun, 18, 2021?\n * const result = previousTuesday(new Date(2021, 5, 18))\n * //=> Tue June 15 2021 00:00:00\n */\nfunction previousTuesday(date, options) {\n return (0, _index.previousDay)(date, 2, options);\n}\n", "\"use strict\";\nexports.previousWednesday = previousWednesday;\nvar _index = require(\"./previousDay.cjs\");\n\n/**\n * The {@link previousWednesday} function options.\n */\n\n/**\n * @name previousWednesday\n * @category Weekday Helpers\n * @summary When is the previous Wednesday?\n *\n * @description\n * When is the previous Wednesday?\n *\n * @typeParam DateType - The Date type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [UTCDate](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to start counting from\n * @param options - An object with options\n *\n * @returns The previous Wednesday\n *\n * @example\n * // When is the previous Wednesday before Jun, 18, 2021?\n * const result = previousWednesday(new Date(2021, 5, 18))\n * //=> Wed June 16 2021 00:00:00\n */\nfunction previousWednesday(date, options) {\n return (0, _index.previousDay)(date, 3, options);\n}\n", "\"use strict\";\nexports.quartersToMonths = quartersToMonths;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name quartersToMonths\n * @category Conversion Helpers\n * @summary Convert number of quarters to months.\n *\n * @description\n * Convert a number of quarters to a full number of months.\n *\n * @param quarters - The number of quarters to be converted\n *\n * @returns The number of quarters converted in months\n *\n * @example\n * // Convert 2 quarters to months\n * const result = quartersToMonths(2)\n * //=> 6\n */\nfunction quartersToMonths(quarters) {\n return Math.trunc(quarters * _index.monthsInQuarter);\n}\n", "\"use strict\";\nexports.quartersToYears = quartersToYears;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name quartersToYears\n * @category Conversion Helpers\n * @summary Convert number of quarters to years.\n *\n * @description\n * Convert a number of quarters to a full number of years.\n *\n * @param quarters - The number of quarters to be converted\n *\n * @returns The number of quarters converted in years\n *\n * @example\n * // Convert 8 quarters to years\n * const result = quartersToYears(8)\n * //=> 2\n *\n * @example\n * // It uses floor rounding:\n * const result = quartersToYears(11)\n * //=> 2\n */\nfunction quartersToYears(quarters) {\n const years = quarters / _index.quartersInYear;\n return Math.trunc(years);\n}\n", "\"use strict\";\nexports.roundToNearestHours = roundToNearestHours;\nvar _index = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link roundToNearestHours} function options.\n */\n\n/**\n * @name roundToNearestHours\n * @category Hour Helpers\n * @summary Rounds the given date to the nearest hour\n *\n * @description\n * Rounds the given date to the nearest hour (or number of hours).\n * Rounds up when the given date is exactly between the nearest round hours.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to round\n * @param options - An object with options.\n *\n * @returns The new date rounded to the closest hour\n *\n * @example\n * // Round 10 July 2014 12:34:56 to nearest hour:\n * const result = roundToNearestHours(new Date(2014, 6, 10, 12, 34, 56))\n * //=> Thu Jul 10 2014 13:00:00\n *\n * @example\n * // Round 10 July 2014 12:34:56 to nearest half hour:\n * const result = roundToNearestHours(new Date(2014, 6, 10, 12, 34, 56), { nearestTo: 6 })\n * //=> Thu Jul 10 2014 12:00:00\n *\n * @example\n * // Round 10 July 2014 12:34:56 to nearest half hour:\n * const result = roundToNearestHours(new Date(2014, 6, 10, 12, 34, 56), { nearestTo: 8 })\n * //=> Thu Jul 10 2014 16:00:00\n *\n * @example\n * // Floor (rounds down) 10 July 2014 12:34:56 to nearest hour:\n * const result = roundToNearestHours(new Date(2014, 6, 10, 1, 23, 45), { roundingMethod: 'ceil' })\n * //=> Thu Jul 10 2014 02:00:00\n *\n * @example\n * // Ceil (rounds up) 10 July 2014 12:34:56 to nearest quarter hour:\n * const result = roundToNearestHours(new Date(2014, 6, 10, 12, 34, 56), { roundingMethod: 'floor', nearestTo: 8 })\n * //=> Thu Jul 10 2014 08:00:00\n */\nfunction roundToNearestHours(date, options) {\n const nearestTo = options?.nearestTo ?? 1;\n\n if (nearestTo < 1 || nearestTo > 12)\n return (0, _index2.constructFrom)(options?.in || date, NaN);\n\n const date_ = (0, _index3.toDate)(date, options?.in);\n const fractionalMinutes = date_.getMinutes() / 60;\n const fractionalSeconds = date_.getSeconds() / 60 / 60;\n const fractionalMilliseconds = date_.getMilliseconds() / 1000 / 60 / 60;\n const hours =\n date_.getHours() +\n fractionalMinutes +\n fractionalSeconds +\n fractionalMilliseconds;\n\n const method = options?.roundingMethod ?? \"round\";\n const roundingMethod = (0, _index.getRoundingMethod)(method);\n\n const roundedHours = roundingMethod(hours / nearestTo) * nearestTo;\n\n date_.setHours(roundedHours, 0, 0, 0);\n return date_;\n}\n", "\"use strict\";\nexports.roundToNearestMinutes = roundToNearestMinutes;\nvar _index = require(\"./_lib/getRoundingMethod.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link roundToNearestMinutes} function options.\n */\n\n/**\n * @name roundToNearestMinutes\n * @category Minute Helpers\n * @summary Rounds the given date to the nearest minute\n *\n * @description\n * Rounds the given date to the nearest minute (or number of minutes).\n * Rounds up when the given date is exactly between the nearest round minutes.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to round\n * @param options - An object with options.\n *\n * @returns The new date rounded to the closest minute\n *\n * @example\n * // Round 10 July 2014 12:12:34 to nearest minute:\n * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34))\n * //=> Thu Jul 10 2014 12:13:00\n *\n * @example\n * // Round 10 July 2014 12:12:34 to nearest quarter hour:\n * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34), { nearestTo: 15 })\n * //=> Thu Jul 10 2014 12:15:00\n *\n * @example\n * // Floor (rounds down) 10 July 2014 12:12:34 to nearest minute:\n * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34), { roundingMethod: 'floor' })\n * //=> Thu Jul 10 2014 12:12:00\n *\n * @example\n * // Ceil (rounds up) 10 July 2014 12:12:34 to nearest half hour:\n * const result = roundToNearestMinutes(new Date(2014, 6, 10, 12, 12, 34), { roundingMethod: 'ceil', nearestTo: 30 })\n * //=> Thu Jul 10 2014 12:30:00\n */\nfunction roundToNearestMinutes(date, options) {\n const nearestTo = options?.nearestTo ?? 1;\n\n if (nearestTo < 1 || nearestTo > 30)\n return (0, _index2.constructFrom)(date, NaN);\n\n const date_ = (0, _index3.toDate)(date, options?.in);\n const fractionalSeconds = date_.getSeconds() / 60;\n const fractionalMilliseconds = date_.getMilliseconds() / 1000 / 60;\n const minutes =\n date_.getMinutes() + fractionalSeconds + fractionalMilliseconds;\n\n const method = options?.roundingMethod ?? \"round\";\n const roundingMethod = (0, _index.getRoundingMethod)(method);\n\n const roundedMinutes = roundingMethod(minutes / nearestTo) * nearestTo;\n\n date_.setMinutes(roundedMinutes, 0, 0);\n return date_;\n}\n", "\"use strict\";\nexports.secondsToHours = secondsToHours;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name secondsToHours\n * @category Conversion Helpers\n * @summary Convert seconds to hours.\n *\n * @description\n * Convert a number of seconds to a full number of hours.\n *\n * @param seconds - The number of seconds to be converted\n *\n * @returns The number of seconds converted in hours\n *\n * @example\n * // Convert 7200 seconds into hours\n * const result = secondsToHours(7200)\n * //=> 2\n *\n * @example\n * // It uses floor rounding:\n * const result = secondsToHours(7199)\n * //=> 1\n */\nfunction secondsToHours(seconds) {\n const hours = seconds / _index.secondsInHour;\n return Math.trunc(hours);\n}\n", "\"use strict\";\nexports.secondsToMilliseconds = secondsToMilliseconds;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name secondsToMilliseconds\n * @category Conversion Helpers\n * @summary Convert seconds to milliseconds.\n *\n * @description\n * Convert a number of seconds to a full number of milliseconds.\n *\n * @param seconds - The number of seconds to be converted\n *\n * @returns The number of seconds converted in milliseconds\n *\n * @example\n * // Convert 2 seconds into milliseconds\n * const result = secondsToMilliseconds(2)\n * //=> 2000\n */\nfunction secondsToMilliseconds(seconds) {\n return seconds * _index.millisecondsInSecond;\n}\n", "\"use strict\";\nexports.secondsToMinutes = secondsToMinutes;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name secondsToMinutes\n * @category Conversion Helpers\n * @summary Convert seconds to minutes.\n *\n * @description\n * Convert a number of seconds to a full number of minutes.\n *\n * @param seconds - The number of seconds to be converted\n *\n * @returns The number of seconds converted in minutes\n *\n * @example\n * // Convert 120 seconds into minutes\n * const result = secondsToMinutes(120)\n * //=> 2\n *\n * @example\n * // It uses floor rounding:\n * const result = secondsToMinutes(119)\n * //=> 1\n */\nfunction secondsToMinutes(seconds) {\n const minutes = seconds / _index.secondsInMinute;\n return Math.trunc(minutes);\n}\n", "\"use strict\";\nexports.setMonth = setMonth;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./getDaysInMonth.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setMonth} function options.\n */\n\n/**\n * @name setMonth\n * @category Month Helpers\n * @summary Set the month to the given date.\n *\n * @description\n * Set the month to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param month - The month index to set (0-11)\n * @param options - The options\n *\n * @returns The new date with the month set\n *\n * @example\n * // Set February to 1 September 2014:\n * const result = setMonth(new Date(2014, 8, 1), 1)\n * //=> Sat Feb 01 2014 00:00:00\n */\nfunction setMonth(date, month, options) {\n const _date = (0, _index3.toDate)(date, options?.in);\n const year = _date.getFullYear();\n const day = _date.getDate();\n\n const midMonth = (0, _index.constructFrom)(options?.in || date, 0);\n midMonth.setFullYear(year, month, 15);\n midMonth.setHours(0, 0, 0, 0);\n const daysInMonth = (0, _index2.getDaysInMonth)(midMonth);\n\n // Set the earlier date, allows to wrap Jan 31 to Feb 28\n _date.setMonth(month, Math.min(day, daysInMonth));\n return _date;\n}\n", "\"use strict\";\nexports.set = set;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./setMonth.cjs\");\nvar _index3 = require(\"./toDate.cjs\");\n\n/**\n * The {@link set} function options.\n */\n\n/**\n * @name set\n * @category Common Helpers\n * @summary Set date values to a given date.\n *\n * @description\n * Set date values to a given date.\n *\n * Sets time values to date from object `values`.\n * A value is not set if it is undefined or null or doesn't exist in `values`.\n *\n * Note about bundle size: `set` does not internally use `setX` functions from date-fns but instead opts\n * to use native `Date#setX` methods. If you use this function, you may not want to include the\n * other `setX` functions that date-fns provides if you are concerned about the bundle size.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param values - The date values to be set\n * @param options - The options\n *\n * @returns The new date with options set\n *\n * @example\n * // Transform 1 September 2014 into 20 October 2015 in a single line:\n * const result = set(new Date(2014, 8, 20), { year: 2015, month: 9, date: 20 })\n * //=> Tue Oct 20 2015 00:00:00\n *\n * @example\n * // Set 12 PM to 1 September 2014 01:23:45 to 1 September 2014 12:00:00:\n * const result = set(new Date(2014, 8, 1, 1, 23, 45), { hours: 12 })\n * //=> Mon Sep 01 2014 12:23:45\n */\nfunction set(date, values, options) {\n let _date = (0, _index3.toDate)(date, options?.in);\n\n // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date\n if (isNaN(+_date)) return (0, _index.constructFrom)(options?.in || date, NaN);\n\n if (values.year != null) _date.setFullYear(values.year);\n if (values.month != null) _date = (0, _index2.setMonth)(_date, values.month);\n if (values.date != null) _date.setDate(values.date);\n if (values.hours != null) _date.setHours(values.hours);\n if (values.minutes != null) _date.setMinutes(values.minutes);\n if (values.seconds != null) _date.setSeconds(values.seconds);\n if (values.milliseconds != null) _date.setMilliseconds(values.milliseconds);\n\n return _date;\n}\n", "\"use strict\";\nexports.setDate = setDate;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link setDate} function options.\n */\n\n/**\n * @name setDate\n * @category Day Helpers\n * @summary Set the day of the month to the given date.\n *\n * @description\n * Set the day of the month to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows using extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param dayOfMonth - The day of the month of the new date\n * @param options - The options\n *\n * @returns The new date with the day of the month set\n *\n * @example\n * // Set the 30th day of the month to 1 September 2014:\n * const result = setDate(new Date(2014, 8, 1), 30)\n * //=> Tue Sep 30 2014 00:00:00\n */\nfunction setDate(date, dayOfMonth, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setDate(dayOfMonth);\n return _date;\n}\n", "\"use strict\";\nexports.setDayOfYear = setDayOfYear;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link setDayOfYear} function options.\n */\n\n/**\n * @name setDayOfYear\n * @category Day Helpers\n * @summary Set the day of the year to the given date.\n *\n * @description\n * Set the day of the year to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param dayOfYear - The day of the year of the new date\n * @param options - An object with options\n *\n * @returns The new date with the day of the year set\n *\n * @example\n * // Set the 2nd day of the year to 2 July 2014:\n * const result = setDayOfYear(new Date(2014, 6, 2), 2)\n * //=> Thu Jan 02 2014 00:00:00\n */\nfunction setDayOfYear(date, dayOfYear, options) {\n const date_ = (0, _index.toDate)(date, options?.in);\n date_.setMonth(0);\n date_.setDate(dayOfYear);\n return date_;\n}\n", "\"use strict\";\nexports.setDefaultOptions = setDefaultOptions;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\n\n/**\n * @name setDefaultOptions\n * @category Common Helpers\n * @summary Set default options including locale.\n * @pure false\n *\n * @description\n * Sets the defaults for\n * `options.locale`, `options.weekStartsOn` and `options.firstWeekContainsDate`\n * arguments for all functions.\n *\n * @param options - An object with options\n *\n * @example\n * // Set global locale:\n * import { es } from 'date-fns/locale'\n * setDefaultOptions({ locale: es })\n * const result = format(new Date(2014, 8, 2), 'PPPP')\n * //=> 'martes, 2 de septiembre de 2014'\n *\n * @example\n * // Start of the week for 2 September 2014:\n * const result = startOfWeek(new Date(2014, 8, 2))\n * //=> Sun Aug 31 2014 00:00:00\n *\n * @example\n * // Start of the week for 2 September 2014,\n * // when we set that week starts on Monday by default:\n * setDefaultOptions({ weekStartsOn: 1 })\n * const result = startOfWeek(new Date(2014, 8, 2))\n * //=> Mon Sep 01 2014 00:00:00\n *\n * @example\n * // Manually set options take priority over default options:\n * setDefaultOptions({ weekStartsOn: 1 })\n * const result = startOfWeek(new Date(2014, 8, 2), { weekStartsOn: 0 })\n * //=> Sun Aug 31 2014 00:00:00\n *\n * @example\n * // Remove the option by setting it to `undefined`:\n * setDefaultOptions({ weekStartsOn: 1 })\n * setDefaultOptions({ weekStartsOn: undefined })\n * const result = startOfWeek(new Date(2014, 8, 2))\n * //=> Sun Aug 31 2014 00:00:00\n */\nfunction setDefaultOptions(options) {\n const result = {};\n const defaultOptions = (0, _index.getDefaultOptions)();\n\n for (const property in defaultOptions) {\n if (Object.prototype.hasOwnProperty.call(defaultOptions, property)) {\n // [TODO] I challenge you to fix the type\n result[property] = defaultOptions[property];\n }\n }\n\n for (const property in options) {\n if (Object.prototype.hasOwnProperty.call(options, property)) {\n if (options[property] === undefined) {\n // [TODO] I challenge you to fix the type\n delete result[property];\n } else {\n // [TODO] I challenge you to fix the type\n result[property] = options[property];\n }\n }\n }\n\n (0, _index.setDefaultOptions)(result);\n}\n", "\"use strict\";\nexports.setHours = setHours;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link setHours} function options.\n */\n\n/**\n * @name setHours\n * @category Hour Helpers\n * @summary Set the hours to the given date.\n *\n * @description\n * Set the hours to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param hours - The hours of the new date\n * @param options - An object with options\n *\n * @returns The new date with the hours set\n *\n * @example\n * // Set 4 hours to 1 September 2014 11:30:00:\n * const result = setHours(new Date(2014, 8, 1, 11, 30), 4)\n * //=> Mon Sep 01 2014 04:30:00\n */\nfunction setHours(date, hours, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setHours(hours);\n return _date;\n}\n", "\"use strict\";\nexports.setMilliseconds = setMilliseconds;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link setMilliseconds} function options.\n */\n\n/**\n * @name setMilliseconds\n * @category Millisecond Helpers\n * @summary Set the milliseconds to the given date.\n *\n * @description\n * Set the milliseconds to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param milliseconds - The milliseconds of the new date\n * @param options - The options\n *\n * @returns The new date with the milliseconds set\n *\n * @example\n * // Set 300 milliseconds to 1 September 2014 11:30:40.500:\n * const result = setMilliseconds(new Date(2014, 8, 1, 11, 30, 40, 500), 300)\n * //=> Mon Sep 01 2014 11:30:40.300\n */\nfunction setMilliseconds(date, milliseconds, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setMilliseconds(milliseconds);\n return _date;\n}\n", "\"use strict\";\nexports.setMinutes = setMinutes;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link setMinutes} function options.\n */\n\n/**\n * @name setMinutes\n * @category Minute Helpers\n * @summary Set the minutes to the given date.\n *\n * @description\n * Set the minutes to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows using extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, returned from the context function, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param minutes - The minutes of the new date\n * @param options - An object with options\n *\n * @returns The new date with the minutes set\n *\n * @example\n * // Set 45 minutes to 1 September 2014 11:30:40:\n * const result = setMinutes(new Date(2014, 8, 1, 11, 30, 40), 45)\n * //=> Mon Sep 01 2014 11:45:40\n */\nfunction setMinutes(date, minutes, options) {\n const date_ = (0, _index.toDate)(date, options?.in);\n date_.setMinutes(minutes);\n return date_;\n}\n", "\"use strict\";\nexports.setQuarter = setQuarter;\nvar _index = require(\"./setMonth.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setQuarter} function options.\n */\n\n/**\n * @name setQuarter\n * @category Quarter Helpers\n * @summary Set the year quarter to the given date.\n *\n * @description\n * Set the year quarter to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param quarter - The quarter of the new date\n * @param options - The options\n *\n * @returns The new date with the quarter set\n *\n * @example\n * // Set the 2nd quarter to 2 July 2014:\n * const result = setQuarter(new Date(2014, 6, 2), 2)\n * //=> Wed Apr 02 2014 00:00:00\n */\nfunction setQuarter(date, quarter, options) {\n const date_ = (0, _index2.toDate)(date, options?.in);\n const oldQuarter = Math.trunc(date_.getMonth() / 3) + 1;\n const diff = quarter - oldQuarter;\n return (0, _index.setMonth)(date_, date_.getMonth() + diff * 3);\n}\n", "\"use strict\";\nexports.setSeconds = setSeconds;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link setSeconds} function options.\n */\n\n/**\n * @name setSeconds\n * @category Second Helpers\n * @summary Set the seconds to the given date, with context support.\n *\n * @description\n * Set the seconds to the given date, with an optional context for time zone specification.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param seconds - The seconds of the new date\n * @param options - An object with options\n *\n * @returns The new date with the seconds set\n *\n * @example\n * // Set 45 seconds to 1 September 2014 11:30:40:\n * const result = setSeconds(new Date(2014, 8, 1, 11, 30, 40), 45)\n * //=> Mon Sep 01 2014 11:30:45\n */\nfunction setSeconds(date, seconds, options) {\n const _date = (0, _index.toDate)(date, options?.in);\n _date.setSeconds(seconds);\n return _date;\n}\n", "\"use strict\";\nexports.setWeekYear = setWeekYear;\nvar _index = require(\"./_lib/defaultOptions.cjs\");\nvar _index2 = require(\"./constructFrom.cjs\");\nvar _index3 = require(\"./differenceInCalendarDays.cjs\");\nvar _index4 = require(\"./startOfWeekYear.cjs\");\nvar _index5 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setWeekYear} function options.\n */\n\n/**\n * @name setWeekYear\n * @category Week-Numbering Year Helpers\n * @summary Set the local week-numbering year to the given date.\n *\n * @description\n * Set the local week-numbering year to the given date,\n * saving the week number and the weekday number.\n * The exact calculation depends on the values of\n * `options.weekStartsOn` (which is the index of the first day of the week)\n * and `options.firstWeekContainsDate` (which is the day of January, which is always in\n * the first week of the week-numbering year)\n *\n * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param weekYear - The local week-numbering year of the new date\n * @param options - An object with options\n *\n * @returns The new date with the local week-numbering year set\n *\n * @example\n * // Set the local week-numbering year 2004 to 2 January 2010 with default options:\n * const result = setWeekYear(new Date(2010, 0, 2), 2004)\n * //=> Sat Jan 03 2004 00:00:00\n *\n * @example\n * // Set the local week-numbering year 2004 to 2 January 2010,\n * // if Monday is the first day of week\n * // and 4 January is always in the first week of the year:\n * const result = setWeekYear(new Date(2010, 0, 2), 2004, {\n * weekStartsOn: 1,\n * firstWeekContainsDate: 4\n * })\n * //=> Sat Jan 01 2005 00:00:00\n */\nfunction setWeekYear(date, weekYear, options) {\n const defaultOptions = (0, _index.getDefaultOptions)();\n const firstWeekContainsDate =\n options?.firstWeekContainsDate ??\n options?.locale?.options?.firstWeekContainsDate ??\n defaultOptions.firstWeekContainsDate ??\n defaultOptions.locale?.options?.firstWeekContainsDate ??\n 1;\n\n const diff = (0, _index3.differenceInCalendarDays)(\n (0, _index5.toDate)(date, options?.in),\n (0, _index4.startOfWeekYear)(date, options),\n options,\n );\n\n const firstWeek = (0, _index2.constructFrom)(options?.in || date, 0);\n firstWeek.setFullYear(weekYear, 0, firstWeekContainsDate);\n firstWeek.setHours(0, 0, 0, 0);\n\n const date_ = (0, _index4.startOfWeekYear)(firstWeek, options);\n date_.setDate(date_.getDate() + diff);\n return date_;\n}\n", "\"use strict\";\nexports.setYear = setYear;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./toDate.cjs\");\n\n/**\n * The {@link setYear} function options.\n */\n\n/**\n * @name setYear\n * @category Year Helpers\n * @summary Set the year to the given date.\n *\n * @description\n * Set the year to the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param year - The year of the new date\n * @param options - An object with options.\n *\n * @returns The new date with the year set\n *\n * @example\n * // Set year 2013 to 1 September 2014:\n * const result = setYear(new Date(2014, 8, 1), 2013)\n * //=> Sun Sep 01 2013 00:00:00\n */\nfunction setYear(date, year, options) {\n const date_ = (0, _index2.toDate)(date, options?.in);\n\n // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date\n if (isNaN(+date_)) return (0, _index.constructFrom)(options?.in || date, NaN);\n\n date_.setFullYear(year);\n return date_;\n}\n", "\"use strict\";\nexports.startOfDecade = startOfDecade;\nvar _index = require(\"./toDate.cjs\");\n\n/**\n * The {@link startOfDecade} options.\n */\n\n/**\n * @name startOfDecade\n * @category Decade Helpers\n * @summary Return the start of a decade for the given date.\n *\n * @description\n * Return the start of a decade for the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The original date\n * @param options - An object with options\n *\n * @returns The start of a decade\n *\n * @example\n * // The start of a decade for 21 October 2015 00:00:00:\n * const result = startOfDecade(new Date(2015, 9, 21, 00, 00, 00))\n * //=> Jan 01 2010 00:00:00\n */\nfunction startOfDecade(date, options) {\n // TODO: Switch to more technical definition in of decades that start with 1\n // end with 0. I.e. 2001-2010 instead of current 2000-2009. It's a breaking\n // change, so it can only be done in 4.0.\n const _date = (0, _index.toDate)(date, options?.in);\n const year = _date.getFullYear();\n const decade = Math.floor(year / 10) * 10;\n _date.setFullYear(decade, 0, 1);\n _date.setHours(0, 0, 0, 0);\n return _date;\n}\n", "\"use strict\";\nexports.startOfToday = startOfToday;\nvar _index = require(\"./startOfDay.cjs\");\n\n/**\n * The {@link startOfToday} function options.\n */\n\n/**\n * @name startOfToday\n * @category Day Helpers\n * @summary Return the start of today.\n * @pure false\n *\n * @description\n * Return the start of today.\n *\n * @typeParam ContextDate - The `Date` type of the context function.\n *\n * @param options - An object with options\n *\n * @returns The start of today\n *\n * @example\n * // If today is 6 October 2014:\n * const result = startOfToday()\n * //=> Mon Oct 6 2014 00:00:00\n */\nfunction startOfToday(options) {\n return (0, _index.startOfDay)(Date.now(), options);\n}\n", "\"use strict\";\nexports.startOfTomorrow = startOfTomorrow;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./constructNow.cjs\");\n\n/**\n * The {@link startOfTomorrow} function options.\n */\n\n/**\n * @name startOfTomorrow\n * @category Day Helpers\n * @summary Return the start of tomorrow.\n * @pure false\n *\n * @typeParam ContextDate - The `Date` type of the context function.\n *\n * @param options - An object with options\n *\n * @returns The start of tomorrow\n *\n * @description\n * Return the start of tomorrow.\n *\n * @example\n * // If today is 6 October 2014:\n * const result = startOfTomorrow()\n * //=> Tue Oct 7 2014 00:00:00\n */\nfunction startOfTomorrow(options) {\n const now = (0, _index2.constructNow)(options?.in);\n const year = now.getFullYear();\n const month = now.getMonth();\n const day = now.getDate();\n\n const date = (0, _index.constructFrom)(options?.in, 0);\n date.setFullYear(year, month, day + 1);\n date.setHours(0, 0, 0, 0);\n return date;\n}\n", "\"use strict\";\nexports.startOfYesterday = startOfYesterday;\nvar _index = require(\"./constructNow.cjs\");\n\n/**\n * The {@link startOfYesterday} function options.\n */\n\n/**\n * @name startOfYesterday\n * @category Day Helpers\n * @summary Return the start of yesterday.\n * @pure false\n *\n * @typeParam ContextDate - The `Date` type of the context function.\n *\n * @param options - An object with options\n *\n * @description\n * Return the start of yesterday.\n *\n * @returns The start of yesterday\n *\n * @example\n * // If today is 6 October 2014:\n * const result = startOfYesterday()\n * //=> Sun Oct 5 2014 00:00:00\n */\nfunction startOfYesterday(options) {\n const now = (0, _index.constructNow)(options?.in);\n const year = now.getFullYear();\n const month = now.getMonth();\n const day = now.getDate();\n\n const date = (0, _index.constructNow)(options?.in);\n date.setFullYear(year, month, day - 1);\n date.setHours(0, 0, 0, 0);\n return date;\n}\n", "\"use strict\";\nexports.subMonths = subMonths;\nvar _index = require(\"./addMonths.cjs\");\n\n/**\n * The subMonths function options.\n */\n\n/**\n * @name subMonths\n * @category Month Helpers\n * @summary Subtract the specified number of months from the given date.\n *\n * @description\n * Subtract the specified number of months from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of months to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the months subtracted\n *\n * @example\n * // Subtract 5 months from 1 February 2015:\n * const result = subMonths(new Date(2015, 1, 1), 5)\n * //=> Mon Sep 01 2014 00:00:00\n */\nfunction subMonths(date, amount, options) {\n return (0, _index.addMonths)(date, -amount, options);\n}\n", "\"use strict\";\nexports.sub = sub;\nvar _index = require(\"./constructFrom.cjs\");\nvar _index2 = require(\"./subDays.cjs\");\nvar _index3 = require(\"./subMonths.cjs\");\n\n/**\n * The {@link sub} function options.\n */\n\n/**\n * @name sub\n * @category Common Helpers\n * @summary Subtract the specified years, months, weeks, days, hours, minutes and seconds from the given date.\n *\n * @description\n * Subtract the specified years, months, weeks, days, hours, minutes and seconds from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param duration - The object with years, months, weeks, days, hours, minutes and seconds to be subtracted\n * @param options - An object with options\n *\n * | Key | Description |\n * |---------|------------------------------------|\n * | years | Amount of years to be subtracted |\n * | months | Amount of months to be subtracted |\n * | weeks | Amount of weeks to be subtracted |\n * | days | Amount of days to be subtracted |\n * | hours | Amount of hours to be subtracted |\n * | minutes | Amount of minutes to be subtracted |\n * | seconds | Amount of seconds to be subtracted |\n *\n * All values default to 0\n *\n * @returns The new date with the seconds subtracted\n *\n * @example\n * // Subtract the following duration from 15 June 2017 15:29:20\n * const result = sub(new Date(2017, 5, 15, 15, 29, 20), {\n * years: 2,\n * months: 9,\n * weeks: 1,\n * days: 7,\n * hours: 5,\n * minutes: 9,\n * seconds: 30\n * })\n * //=> Mon Sep 1 2014 10:19:50\n */\nfunction sub(date, duration, options) {\n const {\n years = 0,\n months = 0,\n weeks = 0,\n days = 0,\n hours = 0,\n minutes = 0,\n seconds = 0,\n } = duration;\n\n const withoutMonths = (0, _index3.subMonths)(\n date,\n months + years * 12,\n options,\n );\n const withoutDays = (0, _index2.subDays)(\n withoutMonths,\n days + weeks * 7,\n options,\n );\n\n const minutesToSub = minutes + hours * 60;\n const secondsToSub = seconds + minutesToSub * 60;\n const msToSub = secondsToSub * 1000;\n\n return (0, _index.constructFrom)(options?.in || date, +withoutDays - msToSub);\n}\n", "\"use strict\";\nexports.subBusinessDays = subBusinessDays;\nvar _index = require(\"./addBusinessDays.cjs\");\n\n/**\n * The {@link subBusinessDays} function options.\n */\n\n/**\n * @name subBusinessDays\n * @category Day Helpers\n * @summary Subtract the specified number of business days (mon - fri) from the given date.\n *\n * @description\n * Subtract the specified number of business days (mon - fri) from the given date, ignoring weekends.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of business days to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the business days subtracted\n *\n * @example\n * // Subtract 10 business days from 1 September 2014:\n * const result = subBusinessDays(new Date(2014, 8, 1), 10)\n * //=> Mon Aug 18 2014 00:00:00 (skipped weekend days)\n */\nfunction subBusinessDays(date, amount, options) {\n return (0, _index.addBusinessDays)(date, -amount, options);\n}\n", "\"use strict\";\nexports.subHours = subHours;\nvar _index = require(\"./addHours.cjs\");\n\n/**\n * The {@link subHours} function options.\n */\n\n/**\n * @name subHours\n * @category Hour Helpers\n * @summary Subtract the specified number of hours from the given date.\n *\n * @description\n * Subtract the specified number of hours from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of hours to be subtracted.\n * @param options - The options\n *\n * @returns The new date with the hours subtracted\n *\n * @example\n * // Subtract 2 hours from 11 July 2014 01:00:00:\n * const result = subHours(new Date(2014, 6, 11, 1, 0), 2)\n * //=> Thu Jul 10 2014 23:00:00\n */\nfunction subHours(date, amount, options) {\n return (0, _index.addHours)(date, -amount, options);\n}\n", "\"use strict\";\nexports.subMilliseconds = subMilliseconds;\nvar _index = require(\"./addMilliseconds.cjs\");\n\n/**\n * The {@link subMilliseconds} function options.\n */\n\n/**\n * Subtract the specified number of milliseconds from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of milliseconds to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the milliseconds subtracted\n */\nfunction subMilliseconds(date, amount, options) {\n return (0, _index.addMilliseconds)(date, -amount, options);\n}\n", "\"use strict\";\nexports.subMinutes = subMinutes;\nvar _index = require(\"./addMinutes.cjs\");\n\n/**\n * The {@link subMinutes} function options.\n */\n\n/**\n * @name subMinutes\n * @category Minute Helpers\n * @summary Subtract the specified number of minutes from the given date.\n *\n * @description\n * Subtract the specified number of minutes from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of minutes to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the minutes subtracted\n *\n * @example\n * // Subtract 30 minutes from 10 July 2014 12:00:00:\n * const result = subMinutes(new Date(2014, 6, 10, 12, 0), 30)\n * //=> Thu Jul 10 2014 11:30:00\n */\nfunction subMinutes(date, amount, options) {\n return (0, _index.addMinutes)(date, -amount, options);\n}\n", "\"use strict\";\nexports.subQuarters = subQuarters;\nvar _index = require(\"./addQuarters.cjs\");\n\n/**\n * The {@link subQuarters} function options.\n */\n\n/**\n * @name subQuarters\n * @category Quarter Helpers\n * @summary Subtract the specified number of year quarters from the given date.\n *\n * @description\n * Subtract the specified number of year quarters from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of quarters to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the quarters subtracted\n *\n * @example\n * // Subtract 3 quarters from 1 September 2014:\n * const result = subQuarters(new Date(2014, 8, 1), 3)\n * //=> Sun Dec 01 2013 00:00:00\n */\nfunction subQuarters(date, amount, options) {\n return (0, _index.addQuarters)(date, -amount, options);\n}\n", "\"use strict\";\nexports.subSeconds = subSeconds;\nvar _index = require(\"./addSeconds.cjs\");\n\n/**\n * The {@link subSeconds} function options.\n */\n\n/**\n * Subtract the specified number of seconds from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of seconds to be subtracted.\n * @param options - The options\n *\n * @returns The new date with the seconds subtracted\n *\n * @example\n * // Subtract 30 seconds from 10 July 2014 12:45:00:\n * const result = subSeconds(new Date(2014, 6, 10, 12, 45, 0), 30)\n * //=> Thu Jul 10 2014 12:44:30\n */\nfunction subSeconds(date, amount, options) {\n return (0, _index.addSeconds)(date, -amount, options);\n}\n", "\"use strict\";\nexports.subWeeks = subWeeks;\nvar _index = require(\"./addWeeks.cjs\");\n\n/**\n * The {@link subWeeks} function options.\n */\n\n/**\n * @name subWeeks\n * @category Week Helpers\n * @summary Subtract the specified number of weeks from the given date.\n *\n * @description\n * Subtract the specified number of weeks from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of weeks to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the weeks subtracted\n *\n * @example\n * // Subtract 4 weeks from 1 September 2014:\n * const result = subWeeks(new Date(2014, 8, 1), 4)\n * //=> Mon Aug 04 2014 00:00:00\n */\nfunction subWeeks(date, amount, options) {\n return (0, _index.addWeeks)(date, -amount, options);\n}\n", "\"use strict\";\nexports.subYears = subYears;\nvar _index = require(\"./addYears.cjs\");\n\n/**\n * The {@link subYears} function options.\n */\n\n/**\n * @name subYears\n * @category Year Helpers\n * @summary Subtract the specified number of years from the given date.\n *\n * @description\n * Subtract the specified number of years from the given date.\n *\n * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).\n * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.\n *\n * @param date - The date to be changed\n * @param amount - The amount of years to be subtracted.\n * @param options - An object with options\n *\n * @returns The new date with the years subtracted\n *\n * @example\n * // Subtract 5 years from 1 September 2014:\n * const result = subYears(new Date(2014, 8, 1), 5)\n * //=> Tue Sep 01 2009 00:00:00\n */\nfunction subYears(date, amount, options) {\n return (0, _index.addYears)(date, -amount, options);\n}\n", "\"use strict\";\nexports.weeksToDays = weeksToDays;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name weeksToDays\n * @category Conversion Helpers\n * @summary Convert weeks to days.\n *\n * @description\n * Convert a number of weeks to a full number of days.\n *\n * @param weeks - The number of weeks to be converted\n *\n * @returns The number of weeks converted in days\n *\n * @example\n * // Convert 2 weeks into days\n * const result = weeksToDays(2)\n * //=> 14\n */\nfunction weeksToDays(weeks) {\n return Math.trunc(weeks * _index.daysInWeek);\n}\n", "\"use strict\";\nexports.yearsToDays = yearsToDays;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name yearsToDays\n * @category Conversion Helpers\n * @summary Convert years to days.\n *\n * @description\n * Convert a number of years to a full number of days.\n *\n * @param years - The number of years to be converted\n *\n * @returns The number of years converted in days\n *\n * @example\n * // Convert 2 years into days\n * const result = yearsToDays(2)\n * //=> 730\n */\nfunction yearsToDays(years) {\n return Math.trunc(years * _index.daysInYear);\n}\n", "\"use strict\";\nexports.yearsToMonths = yearsToMonths;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name yearsToMonths\n * @category Conversion Helpers\n * @summary Convert years to months.\n *\n * @description\n * Convert a number of years to a full number of months.\n *\n * @param years - The number of years to be converted\n *\n * @returns The number of years converted in months\n *\n * @example\n * // Convert 2 years into months\n * const result = yearsToMonths(2)\n * //=> 24\n */\nfunction yearsToMonths(years) {\n return Math.trunc(years * _index.monthsInYear);\n}\n", "\"use strict\";\nexports.yearsToQuarters = yearsToQuarters;\nvar _index = require(\"./constants.cjs\");\n\n/**\n * @name yearsToQuarters\n * @category Conversion Helpers\n * @summary Convert years to quarters.\n *\n * @description\n * Convert a number of years to a full number of quarters.\n *\n * @param years - The number of years to be converted\n *\n * @returns The number of years converted in quarters\n *\n * @example\n * // Convert 2 years to quarters\n * const result = yearsToQuarters(2)\n * //=> 8\n */\nfunction yearsToQuarters(years) {\n return Math.trunc(years * _index.quartersInYear);\n}\n", "\"use strict\";\n\nvar _index = require(\"./add.cjs\");\nObject.keys(_index).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index[key];\n },\n });\n});\nvar _index2 = require(\"./addBusinessDays.cjs\");\nObject.keys(_index2).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index2[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index2[key];\n },\n });\n});\nvar _index3 = require(\"./addDays.cjs\");\nObject.keys(_index3).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index3[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index3[key];\n },\n });\n});\nvar _index4 = require(\"./addHours.cjs\");\nObject.keys(_index4).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index4[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index4[key];\n },\n });\n});\nvar _index5 = require(\"./addISOWeekYears.cjs\");\nObject.keys(_index5).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index5[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index5[key];\n },\n });\n});\nvar _index6 = require(\"./addMilliseconds.cjs\");\nObject.keys(_index6).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index6[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index6[key];\n },\n });\n});\nvar _index7 = require(\"./addMinutes.cjs\");\nObject.keys(_index7).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index7[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index7[key];\n },\n });\n});\nvar _index8 = require(\"./addMonths.cjs\");\nObject.keys(_index8).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index8[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index8[key];\n },\n });\n});\nvar _index9 = require(\"./addQuarters.cjs\");\nObject.keys(_index9).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index9[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index9[key];\n },\n });\n});\nvar _index10 = require(\"./addSeconds.cjs\");\nObject.keys(_index10).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index10[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index10[key];\n },\n });\n});\nvar _index11 = require(\"./addWeeks.cjs\");\nObject.keys(_index11).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index11[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index11[key];\n },\n });\n});\nvar _index12 = require(\"./addYears.cjs\");\nObject.keys(_index12).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index12[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index12[key];\n },\n });\n});\nvar _index13 = require(\"./areIntervalsOverlapping.cjs\");\nObject.keys(_index13).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index13[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index13[key];\n },\n });\n});\nvar _index14 = require(\"./clamp.cjs\");\nObject.keys(_index14).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index14[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index14[key];\n },\n });\n});\nvar _index15 = require(\"./closestIndexTo.cjs\");\nObject.keys(_index15).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index15[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index15[key];\n },\n });\n});\nvar _index16 = require(\"./closestTo.cjs\");\nObject.keys(_index16).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index16[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index16[key];\n },\n });\n});\nvar _index17 = require(\"./compareAsc.cjs\");\nObject.keys(_index17).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index17[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index17[key];\n },\n });\n});\nvar _index18 = require(\"./compareDesc.cjs\");\nObject.keys(_index18).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index18[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index18[key];\n },\n });\n});\nvar _index19 = require(\"./constructFrom.cjs\");\nObject.keys(_index19).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index19[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index19[key];\n },\n });\n});\nvar _index20 = require(\"./constructNow.cjs\");\nObject.keys(_index20).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index20[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index20[key];\n },\n });\n});\nvar _index21 = require(\"./daysToWeeks.cjs\");\nObject.keys(_index21).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index21[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index21[key];\n },\n });\n});\nvar _index22 = require(\"./differenceInBusinessDays.cjs\");\nObject.keys(_index22).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index22[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index22[key];\n },\n });\n});\nvar _index23 = require(\"./differenceInCalendarDays.cjs\");\nObject.keys(_index23).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index23[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index23[key];\n },\n });\n});\nvar _index24 = require(\"./differenceInCalendarISOWeekYears.cjs\");\nObject.keys(_index24).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index24[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index24[key];\n },\n });\n});\nvar _index25 = require(\"./differenceInCalendarISOWeeks.cjs\");\nObject.keys(_index25).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index25[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index25[key];\n },\n });\n});\nvar _index26 = require(\"./differenceInCalendarMonths.cjs\");\nObject.keys(_index26).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index26[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index26[key];\n },\n });\n});\nvar _index27 = require(\"./differenceInCalendarQuarters.cjs\");\nObject.keys(_index27).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index27[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index27[key];\n },\n });\n});\nvar _index28 = require(\"./differenceInCalendarWeeks.cjs\");\nObject.keys(_index28).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index28[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index28[key];\n },\n });\n});\nvar _index29 = require(\"./differenceInCalendarYears.cjs\");\nObject.keys(_index29).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index29[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index29[key];\n },\n });\n});\nvar _index30 = require(\"./differenceInDays.cjs\");\nObject.keys(_index30).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index30[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index30[key];\n },\n });\n});\nvar _index31 = require(\"./differenceInHours.cjs\");\nObject.keys(_index31).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index31[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index31[key];\n },\n });\n});\nvar _index32 = require(\"./differenceInISOWeekYears.cjs\");\nObject.keys(_index32).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index32[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index32[key];\n },\n });\n});\nvar _index33 = require(\"./differenceInMilliseconds.cjs\");\nObject.keys(_index33).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index33[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index33[key];\n },\n });\n});\nvar _index34 = require(\"./differenceInMinutes.cjs\");\nObject.keys(_index34).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index34[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index34[key];\n },\n });\n});\nvar _index35 = require(\"./differenceInMonths.cjs\");\nObject.keys(_index35).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index35[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index35[key];\n },\n });\n});\nvar _index36 = require(\"./differenceInQuarters.cjs\");\nObject.keys(_index36).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index36[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index36[key];\n },\n });\n});\nvar _index37 = require(\"./differenceInSeconds.cjs\");\nObject.keys(_index37).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index37[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index37[key];\n },\n });\n});\nvar _index38 = require(\"./differenceInWeeks.cjs\");\nObject.keys(_index38).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index38[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index38[key];\n },\n });\n});\nvar _index39 = require(\"./differenceInYears.cjs\");\nObject.keys(_index39).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index39[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index39[key];\n },\n });\n});\nvar _index40 = require(\"./eachDayOfInterval.cjs\");\nObject.keys(_index40).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index40[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index40[key];\n },\n });\n});\nvar _index41 = require(\"./eachHourOfInterval.cjs\");\nObject.keys(_index41).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index41[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index41[key];\n },\n });\n});\nvar _index42 = require(\"./eachMinuteOfInterval.cjs\");\nObject.keys(_index42).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index42[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index42[key];\n },\n });\n});\nvar _index43 = require(\"./eachMonthOfInterval.cjs\");\nObject.keys(_index43).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index43[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index43[key];\n },\n });\n});\nvar _index44 = require(\"./eachQuarterOfInterval.cjs\");\nObject.keys(_index44).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index44[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index44[key];\n },\n });\n});\nvar _index45 = require(\"./eachWeekOfInterval.cjs\");\nObject.keys(_index45).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index45[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index45[key];\n },\n });\n});\nvar _index46 = require(\"./eachWeekendOfInterval.cjs\");\nObject.keys(_index46).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index46[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index46[key];\n },\n });\n});\nvar _index47 = require(\"./eachWeekendOfMonth.cjs\");\nObject.keys(_index47).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index47[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index47[key];\n },\n });\n});\nvar _index48 = require(\"./eachWeekendOfYear.cjs\");\nObject.keys(_index48).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index48[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index48[key];\n },\n });\n});\nvar _index49 = require(\"./eachYearOfInterval.cjs\");\nObject.keys(_index49).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index49[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index49[key];\n },\n });\n});\nvar _index50 = require(\"./endOfDay.cjs\");\nObject.keys(_index50).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index50[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index50[key];\n },\n });\n});\nvar _index51 = require(\"./endOfDecade.cjs\");\nObject.keys(_index51).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index51[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index51[key];\n },\n });\n});\nvar _index52 = require(\"./endOfHour.cjs\");\nObject.keys(_index52).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index52[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index52[key];\n },\n });\n});\nvar _index53 = require(\"./endOfISOWeek.cjs\");\nObject.keys(_index53).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index53[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index53[key];\n },\n });\n});\nvar _index54 = require(\"./endOfISOWeekYear.cjs\");\nObject.keys(_index54).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index54[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index54[key];\n },\n });\n});\nvar _index55 = require(\"./endOfMinute.cjs\");\nObject.keys(_index55).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index55[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index55[key];\n },\n });\n});\nvar _index56 = require(\"./endOfMonth.cjs\");\nObject.keys(_index56).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index56[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index56[key];\n },\n });\n});\nvar _index57 = require(\"./endOfQuarter.cjs\");\nObject.keys(_index57).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index57[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index57[key];\n },\n });\n});\nvar _index58 = require(\"./endOfSecond.cjs\");\nObject.keys(_index58).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index58[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index58[key];\n },\n });\n});\nvar _index59 = require(\"./endOfToday.cjs\");\nObject.keys(_index59).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index59[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index59[key];\n },\n });\n});\nvar _index60 = require(\"./endOfTomorrow.cjs\");\nObject.keys(_index60).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index60[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index60[key];\n },\n });\n});\nvar _index61 = require(\"./endOfWeek.cjs\");\nObject.keys(_index61).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index61[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index61[key];\n },\n });\n});\nvar _index62 = require(\"./endOfYear.cjs\");\nObject.keys(_index62).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index62[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index62[key];\n },\n });\n});\nvar _index63 = require(\"./endOfYesterday.cjs\");\nObject.keys(_index63).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index63[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index63[key];\n },\n });\n});\nvar _index64 = require(\"./format.cjs\");\nObject.keys(_index64).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index64[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index64[key];\n },\n });\n});\nvar _index65 = require(\"./formatDistance.cjs\");\nObject.keys(_index65).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index65[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index65[key];\n },\n });\n});\nvar _index66 = require(\"./formatDistanceStrict.cjs\");\nObject.keys(_index66).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index66[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index66[key];\n },\n });\n});\nvar _index67 = require(\"./formatDistanceToNow.cjs\");\nObject.keys(_index67).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index67[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index67[key];\n },\n });\n});\nvar _index68 = require(\"./formatDistanceToNowStrict.cjs\");\nObject.keys(_index68).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index68[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index68[key];\n },\n });\n});\nvar _index69 = require(\"./formatDuration.cjs\");\nObject.keys(_index69).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index69[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index69[key];\n },\n });\n});\nvar _index70 = require(\"./formatISO.cjs\");\nObject.keys(_index70).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index70[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index70[key];\n },\n });\n});\nvar _index71 = require(\"./formatISO9075.cjs\");\nObject.keys(_index71).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index71[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index71[key];\n },\n });\n});\nvar _index72 = require(\"./formatISODuration.cjs\");\nObject.keys(_index72).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index72[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index72[key];\n },\n });\n});\nvar _index73 = require(\"./formatRFC3339.cjs\");\nObject.keys(_index73).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index73[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index73[key];\n },\n });\n});\nvar _index74 = require(\"./formatRFC7231.cjs\");\nObject.keys(_index74).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index74[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index74[key];\n },\n });\n});\nvar _index75 = require(\"./formatRelative.cjs\");\nObject.keys(_index75).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index75[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index75[key];\n },\n });\n});\nvar _index76 = require(\"./fromUnixTime.cjs\");\nObject.keys(_index76).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index76[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index76[key];\n },\n });\n});\nvar _index77 = require(\"./getDate.cjs\");\nObject.keys(_index77).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index77[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index77[key];\n },\n });\n});\nvar _index78 = require(\"./getDay.cjs\");\nObject.keys(_index78).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index78[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index78[key];\n },\n });\n});\nvar _index79 = require(\"./getDayOfYear.cjs\");\nObject.keys(_index79).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index79[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index79[key];\n },\n });\n});\nvar _index80 = require(\"./getDaysInMonth.cjs\");\nObject.keys(_index80).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index80[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index80[key];\n },\n });\n});\nvar _index81 = require(\"./getDaysInYear.cjs\");\nObject.keys(_index81).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index81[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index81[key];\n },\n });\n});\nvar _index82 = require(\"./getDecade.cjs\");\nObject.keys(_index82).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index82[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index82[key];\n },\n });\n});\nvar _index83 = require(\"./getDefaultOptions.cjs\");\nObject.keys(_index83).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index83[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index83[key];\n },\n });\n});\nvar _index84 = require(\"./getHours.cjs\");\nObject.keys(_index84).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index84[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index84[key];\n },\n });\n});\nvar _index85 = require(\"./getISODay.cjs\");\nObject.keys(_index85).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index85[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index85[key];\n },\n });\n});\nvar _index86 = require(\"./getISOWeek.cjs\");\nObject.keys(_index86).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index86[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index86[key];\n },\n });\n});\nvar _index87 = require(\"./getISOWeekYear.cjs\");\nObject.keys(_index87).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index87[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index87[key];\n },\n });\n});\nvar _index88 = require(\"./getISOWeeksInYear.cjs\");\nObject.keys(_index88).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index88[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index88[key];\n },\n });\n});\nvar _index89 = require(\"./getMilliseconds.cjs\");\nObject.keys(_index89).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index89[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index89[key];\n },\n });\n});\nvar _index90 = require(\"./getMinutes.cjs\");\nObject.keys(_index90).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index90[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index90[key];\n },\n });\n});\nvar _index91 = require(\"./getMonth.cjs\");\nObject.keys(_index91).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index91[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index91[key];\n },\n });\n});\nvar _index92 = require(\"./getOverlappingDaysInIntervals.cjs\");\nObject.keys(_index92).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index92[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index92[key];\n },\n });\n});\nvar _index93 = require(\"./getQuarter.cjs\");\nObject.keys(_index93).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index93[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index93[key];\n },\n });\n});\nvar _index94 = require(\"./getSeconds.cjs\");\nObject.keys(_index94).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index94[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index94[key];\n },\n });\n});\nvar _index95 = require(\"./getTime.cjs\");\nObject.keys(_index95).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index95[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index95[key];\n },\n });\n});\nvar _index96 = require(\"./getUnixTime.cjs\");\nObject.keys(_index96).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index96[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index96[key];\n },\n });\n});\nvar _index97 = require(\"./getWeek.cjs\");\nObject.keys(_index97).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index97[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index97[key];\n },\n });\n});\nvar _index98 = require(\"./getWeekOfMonth.cjs\");\nObject.keys(_index98).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index98[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index98[key];\n },\n });\n});\nvar _index99 = require(\"./getWeekYear.cjs\");\nObject.keys(_index99).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index99[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index99[key];\n },\n });\n});\nvar _index100 = require(\"./getWeeksInMonth.cjs\");\nObject.keys(_index100).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index100[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index100[key];\n },\n });\n});\nvar _index101 = require(\"./getYear.cjs\");\nObject.keys(_index101).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index101[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index101[key];\n },\n });\n});\nvar _index102 = require(\"./hoursToMilliseconds.cjs\");\nObject.keys(_index102).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index102[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index102[key];\n },\n });\n});\nvar _index103 = require(\"./hoursToMinutes.cjs\");\nObject.keys(_index103).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index103[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index103[key];\n },\n });\n});\nvar _index104 = require(\"./hoursToSeconds.cjs\");\nObject.keys(_index104).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index104[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index104[key];\n },\n });\n});\nvar _index105 = require(\"./interval.cjs\");\nObject.keys(_index105).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index105[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index105[key];\n },\n });\n});\nvar _index106 = require(\"./intervalToDuration.cjs\");\nObject.keys(_index106).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index106[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index106[key];\n },\n });\n});\nvar _index107 = require(\"./intlFormat.cjs\");\nObject.keys(_index107).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index107[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index107[key];\n },\n });\n});\nvar _index108 = require(\"./intlFormatDistance.cjs\");\nObject.keys(_index108).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index108[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index108[key];\n },\n });\n});\nvar _index109 = require(\"./isAfter.cjs\");\nObject.keys(_index109).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index109[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index109[key];\n },\n });\n});\nvar _index110 = require(\"./isBefore.cjs\");\nObject.keys(_index110).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index110[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index110[key];\n },\n });\n});\nvar _index111 = require(\"./isDate.cjs\");\nObject.keys(_index111).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index111[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index111[key];\n },\n });\n});\nvar _index112 = require(\"./isEqual.cjs\");\nObject.keys(_index112).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index112[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index112[key];\n },\n });\n});\nvar _index113 = require(\"./isExists.cjs\");\nObject.keys(_index113).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index113[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index113[key];\n },\n });\n});\nvar _index114 = require(\"./isFirstDayOfMonth.cjs\");\nObject.keys(_index114).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index114[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index114[key];\n },\n });\n});\nvar _index115 = require(\"./isFriday.cjs\");\nObject.keys(_index115).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index115[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index115[key];\n },\n });\n});\nvar _index116 = require(\"./isFuture.cjs\");\nObject.keys(_index116).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index116[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index116[key];\n },\n });\n});\nvar _index117 = require(\"./isLastDayOfMonth.cjs\");\nObject.keys(_index117).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index117[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index117[key];\n },\n });\n});\nvar _index118 = require(\"./isLeapYear.cjs\");\nObject.keys(_index118).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index118[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index118[key];\n },\n });\n});\nvar _index119 = require(\"./isMatch.cjs\");\nObject.keys(_index119).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index119[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index119[key];\n },\n });\n});\nvar _index120 = require(\"./isMonday.cjs\");\nObject.keys(_index120).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index120[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index120[key];\n },\n });\n});\nvar _index121 = require(\"./isPast.cjs\");\nObject.keys(_index121).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index121[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index121[key];\n },\n });\n});\nvar _index122 = require(\"./isSameDay.cjs\");\nObject.keys(_index122).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index122[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index122[key];\n },\n });\n});\nvar _index123 = require(\"./isSameHour.cjs\");\nObject.keys(_index123).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index123[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index123[key];\n },\n });\n});\nvar _index124 = require(\"./isSameISOWeek.cjs\");\nObject.keys(_index124).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index124[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index124[key];\n },\n });\n});\nvar _index125 = require(\"./isSameISOWeekYear.cjs\");\nObject.keys(_index125).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index125[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index125[key];\n },\n });\n});\nvar _index126 = require(\"./isSameMinute.cjs\");\nObject.keys(_index126).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index126[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index126[key];\n },\n });\n});\nvar _index127 = require(\"./isSameMonth.cjs\");\nObject.keys(_index127).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index127[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index127[key];\n },\n });\n});\nvar _index128 = require(\"./isSameQuarter.cjs\");\nObject.keys(_index128).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index128[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index128[key];\n },\n });\n});\nvar _index129 = require(\"./isSameSecond.cjs\");\nObject.keys(_index129).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index129[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index129[key];\n },\n });\n});\nvar _index130 = require(\"./isSameWeek.cjs\");\nObject.keys(_index130).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index130[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index130[key];\n },\n });\n});\nvar _index131 = require(\"./isSameYear.cjs\");\nObject.keys(_index131).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index131[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index131[key];\n },\n });\n});\nvar _index132 = require(\"./isSaturday.cjs\");\nObject.keys(_index132).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index132[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index132[key];\n },\n });\n});\nvar _index133 = require(\"./isSunday.cjs\");\nObject.keys(_index133).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index133[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index133[key];\n },\n });\n});\nvar _index134 = require(\"./isThisHour.cjs\");\nObject.keys(_index134).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index134[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index134[key];\n },\n });\n});\nvar _index135 = require(\"./isThisISOWeek.cjs\");\nObject.keys(_index135).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index135[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index135[key];\n },\n });\n});\nvar _index136 = require(\"./isThisMinute.cjs\");\nObject.keys(_index136).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index136[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index136[key];\n },\n });\n});\nvar _index137 = require(\"./isThisMonth.cjs\");\nObject.keys(_index137).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index137[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index137[key];\n },\n });\n});\nvar _index138 = require(\"./isThisQuarter.cjs\");\nObject.keys(_index138).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index138[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index138[key];\n },\n });\n});\nvar _index139 = require(\"./isThisSecond.cjs\");\nObject.keys(_index139).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index139[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index139[key];\n },\n });\n});\nvar _index140 = require(\"./isThisWeek.cjs\");\nObject.keys(_index140).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index140[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index140[key];\n },\n });\n});\nvar _index141 = require(\"./isThisYear.cjs\");\nObject.keys(_index141).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index141[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index141[key];\n },\n });\n});\nvar _index142 = require(\"./isThursday.cjs\");\nObject.keys(_index142).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index142[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index142[key];\n },\n });\n});\nvar _index143 = require(\"./isToday.cjs\");\nObject.keys(_index143).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index143[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index143[key];\n },\n });\n});\nvar _index144 = require(\"./isTomorrow.cjs\");\nObject.keys(_index144).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index144[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index144[key];\n },\n });\n});\nvar _index145 = require(\"./isTuesday.cjs\");\nObject.keys(_index145).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index145[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index145[key];\n },\n });\n});\nvar _index146 = require(\"./isValid.cjs\");\nObject.keys(_index146).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index146[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index146[key];\n },\n });\n});\nvar _index147 = require(\"./isWednesday.cjs\");\nObject.keys(_index147).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index147[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index147[key];\n },\n });\n});\nvar _index148 = require(\"./isWeekend.cjs\");\nObject.keys(_index148).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index148[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index148[key];\n },\n });\n});\nvar _index149 = require(\"./isWithinInterval.cjs\");\nObject.keys(_index149).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index149[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index149[key];\n },\n });\n});\nvar _index150 = require(\"./isYesterday.cjs\");\nObject.keys(_index150).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index150[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index150[key];\n },\n });\n});\nvar _index151 = require(\"./lastDayOfDecade.cjs\");\nObject.keys(_index151).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index151[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index151[key];\n },\n });\n});\nvar _index152 = require(\"./lastDayOfISOWeek.cjs\");\nObject.keys(_index152).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index152[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index152[key];\n },\n });\n});\nvar _index153 = require(\"./lastDayOfISOWeekYear.cjs\");\nObject.keys(_index153).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index153[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index153[key];\n },\n });\n});\nvar _index154 = require(\"./lastDayOfMonth.cjs\");\nObject.keys(_index154).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index154[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index154[key];\n },\n });\n});\nvar _index155 = require(\"./lastDayOfQuarter.cjs\");\nObject.keys(_index155).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index155[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index155[key];\n },\n });\n});\nvar _index156 = require(\"./lastDayOfWeek.cjs\");\nObject.keys(_index156).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index156[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index156[key];\n },\n });\n});\nvar _index157 = require(\"./lastDayOfYear.cjs\");\nObject.keys(_index157).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index157[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index157[key];\n },\n });\n});\nvar _index158 = require(\"./lightFormat.cjs\");\nObject.keys(_index158).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index158[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index158[key];\n },\n });\n});\nvar _index159 = require(\"./max.cjs\");\nObject.keys(_index159).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index159[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index159[key];\n },\n });\n});\nvar _index160 = require(\"./milliseconds.cjs\");\nObject.keys(_index160).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index160[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index160[key];\n },\n });\n});\nvar _index161 = require(\"./millisecondsToHours.cjs\");\nObject.keys(_index161).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index161[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index161[key];\n },\n });\n});\nvar _index162 = require(\"./millisecondsToMinutes.cjs\");\nObject.keys(_index162).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index162[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index162[key];\n },\n });\n});\nvar _index163 = require(\"./millisecondsToSeconds.cjs\");\nObject.keys(_index163).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index163[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index163[key];\n },\n });\n});\nvar _index164 = require(\"./min.cjs\");\nObject.keys(_index164).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index164[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index164[key];\n },\n });\n});\nvar _index165 = require(\"./minutesToHours.cjs\");\nObject.keys(_index165).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index165[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index165[key];\n },\n });\n});\nvar _index166 = require(\"./minutesToMilliseconds.cjs\");\nObject.keys(_index166).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index166[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index166[key];\n },\n });\n});\nvar _index167 = require(\"./minutesToSeconds.cjs\");\nObject.keys(_index167).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index167[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index167[key];\n },\n });\n});\nvar _index168 = require(\"./monthsToQuarters.cjs\");\nObject.keys(_index168).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index168[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index168[key];\n },\n });\n});\nvar _index169 = require(\"./monthsToYears.cjs\");\nObject.keys(_index169).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index169[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index169[key];\n },\n });\n});\nvar _index170 = require(\"./nextDay.cjs\");\nObject.keys(_index170).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index170[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index170[key];\n },\n });\n});\nvar _index171 = require(\"./nextFriday.cjs\");\nObject.keys(_index171).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index171[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index171[key];\n },\n });\n});\nvar _index172 = require(\"./nextMonday.cjs\");\nObject.keys(_index172).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index172[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index172[key];\n },\n });\n});\nvar _index173 = require(\"./nextSaturday.cjs\");\nObject.keys(_index173).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index173[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index173[key];\n },\n });\n});\nvar _index174 = require(\"./nextSunday.cjs\");\nObject.keys(_index174).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index174[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index174[key];\n },\n });\n});\nvar _index175 = require(\"./nextThursday.cjs\");\nObject.keys(_index175).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index175[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index175[key];\n },\n });\n});\nvar _index176 = require(\"./nextTuesday.cjs\");\nObject.keys(_index176).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index176[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index176[key];\n },\n });\n});\nvar _index177 = require(\"./nextWednesday.cjs\");\nObject.keys(_index177).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index177[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index177[key];\n },\n });\n});\nvar _index178 = require(\"./parse.cjs\");\nObject.keys(_index178).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index178[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index178[key];\n },\n });\n});\nvar _index179 = require(\"./parseISO.cjs\");\nObject.keys(_index179).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index179[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index179[key];\n },\n });\n});\nvar _index180 = require(\"./parseJSON.cjs\");\nObject.keys(_index180).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index180[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index180[key];\n },\n });\n});\nvar _index181 = require(\"./previousDay.cjs\");\nObject.keys(_index181).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index181[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index181[key];\n },\n });\n});\nvar _index182 = require(\"./previousFriday.cjs\");\nObject.keys(_index182).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index182[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index182[key];\n },\n });\n});\nvar _index183 = require(\"./previousMonday.cjs\");\nObject.keys(_index183).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index183[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index183[key];\n },\n });\n});\nvar _index184 = require(\"./previousSaturday.cjs\");\nObject.keys(_index184).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index184[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index184[key];\n },\n });\n});\nvar _index185 = require(\"./previousSunday.cjs\");\nObject.keys(_index185).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index185[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index185[key];\n },\n });\n});\nvar _index186 = require(\"./previousThursday.cjs\");\nObject.keys(_index186).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index186[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index186[key];\n },\n });\n});\nvar _index187 = require(\"./previousTuesday.cjs\");\nObject.keys(_index187).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index187[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index187[key];\n },\n });\n});\nvar _index188 = require(\"./previousWednesday.cjs\");\nObject.keys(_index188).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index188[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index188[key];\n },\n });\n});\nvar _index189 = require(\"./quartersToMonths.cjs\");\nObject.keys(_index189).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index189[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index189[key];\n },\n });\n});\nvar _index190 = require(\"./quartersToYears.cjs\");\nObject.keys(_index190).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index190[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index190[key];\n },\n });\n});\nvar _index191 = require(\"./roundToNearestHours.cjs\");\nObject.keys(_index191).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index191[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index191[key];\n },\n });\n});\nvar _index192 = require(\"./roundToNearestMinutes.cjs\");\nObject.keys(_index192).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index192[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index192[key];\n },\n });\n});\nvar _index193 = require(\"./secondsToHours.cjs\");\nObject.keys(_index193).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index193[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index193[key];\n },\n });\n});\nvar _index194 = require(\"./secondsToMilliseconds.cjs\");\nObject.keys(_index194).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index194[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index194[key];\n },\n });\n});\nvar _index195 = require(\"./secondsToMinutes.cjs\");\nObject.keys(_index195).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index195[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index195[key];\n },\n });\n});\nvar _index196 = require(\"./set.cjs\");\nObject.keys(_index196).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index196[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index196[key];\n },\n });\n});\nvar _index197 = require(\"./setDate.cjs\");\nObject.keys(_index197).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index197[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index197[key];\n },\n });\n});\nvar _index198 = require(\"./setDay.cjs\");\nObject.keys(_index198).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index198[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index198[key];\n },\n });\n});\nvar _index199 = require(\"./setDayOfYear.cjs\");\nObject.keys(_index199).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index199[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index199[key];\n },\n });\n});\nvar _index200 = require(\"./setDefaultOptions.cjs\");\nObject.keys(_index200).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index200[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index200[key];\n },\n });\n});\nvar _index201 = require(\"./setHours.cjs\");\nObject.keys(_index201).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index201[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index201[key];\n },\n });\n});\nvar _index202 = require(\"./setISODay.cjs\");\nObject.keys(_index202).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index202[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index202[key];\n },\n });\n});\nvar _index203 = require(\"./setISOWeek.cjs\");\nObject.keys(_index203).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index203[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index203[key];\n },\n });\n});\nvar _index204 = require(\"./setISOWeekYear.cjs\");\nObject.keys(_index204).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index204[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index204[key];\n },\n });\n});\nvar _index205 = require(\"./setMilliseconds.cjs\");\nObject.keys(_index205).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index205[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index205[key];\n },\n });\n});\nvar _index206 = require(\"./setMinutes.cjs\");\nObject.keys(_index206).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index206[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index206[key];\n },\n });\n});\nvar _index207 = require(\"./setMonth.cjs\");\nObject.keys(_index207).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index207[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index207[key];\n },\n });\n});\nvar _index208 = require(\"./setQuarter.cjs\");\nObject.keys(_index208).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index208[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index208[key];\n },\n });\n});\nvar _index209 = require(\"./setSeconds.cjs\");\nObject.keys(_index209).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index209[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index209[key];\n },\n });\n});\nvar _index210 = require(\"./setWeek.cjs\");\nObject.keys(_index210).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index210[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index210[key];\n },\n });\n});\nvar _index211 = require(\"./setWeekYear.cjs\");\nObject.keys(_index211).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index211[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index211[key];\n },\n });\n});\nvar _index212 = require(\"./setYear.cjs\");\nObject.keys(_index212).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index212[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index212[key];\n },\n });\n});\nvar _index213 = require(\"./startOfDay.cjs\");\nObject.keys(_index213).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index213[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index213[key];\n },\n });\n});\nvar _index214 = require(\"./startOfDecade.cjs\");\nObject.keys(_index214).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index214[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index214[key];\n },\n });\n});\nvar _index215 = require(\"./startOfHour.cjs\");\nObject.keys(_index215).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index215[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index215[key];\n },\n });\n});\nvar _index216 = require(\"./startOfISOWeek.cjs\");\nObject.keys(_index216).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index216[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index216[key];\n },\n });\n});\nvar _index217 = require(\"./startOfISOWeekYear.cjs\");\nObject.keys(_index217).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index217[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index217[key];\n },\n });\n});\nvar _index218 = require(\"./startOfMinute.cjs\");\nObject.keys(_index218).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index218[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index218[key];\n },\n });\n});\nvar _index219 = require(\"./startOfMonth.cjs\");\nObject.keys(_index219).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index219[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index219[key];\n },\n });\n});\nvar _index220 = require(\"./startOfQuarter.cjs\");\nObject.keys(_index220).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index220[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index220[key];\n },\n });\n});\nvar _index221 = require(\"./startOfSecond.cjs\");\nObject.keys(_index221).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index221[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index221[key];\n },\n });\n});\nvar _index222 = require(\"./startOfToday.cjs\");\nObject.keys(_index222).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index222[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index222[key];\n },\n });\n});\nvar _index223 = require(\"./startOfTomorrow.cjs\");\nObject.keys(_index223).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index223[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index223[key];\n },\n });\n});\nvar _index224 = require(\"./startOfWeek.cjs\");\nObject.keys(_index224).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index224[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index224[key];\n },\n });\n});\nvar _index225 = require(\"./startOfWeekYear.cjs\");\nObject.keys(_index225).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index225[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index225[key];\n },\n });\n});\nvar _index226 = require(\"./startOfYear.cjs\");\nObject.keys(_index226).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index226[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index226[key];\n },\n });\n});\nvar _index227 = require(\"./startOfYesterday.cjs\");\nObject.keys(_index227).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index227[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index227[key];\n },\n });\n});\nvar _index228 = require(\"./sub.cjs\");\nObject.keys(_index228).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index228[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index228[key];\n },\n });\n});\nvar _index229 = require(\"./subBusinessDays.cjs\");\nObject.keys(_index229).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index229[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index229[key];\n },\n });\n});\nvar _index230 = require(\"./subDays.cjs\");\nObject.keys(_index230).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index230[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index230[key];\n },\n });\n});\nvar _index231 = require(\"./subHours.cjs\");\nObject.keys(_index231).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index231[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index231[key];\n },\n });\n});\nvar _index232 = require(\"./subISOWeekYears.cjs\");\nObject.keys(_index232).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index232[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index232[key];\n },\n });\n});\nvar _index233 = require(\"./subMilliseconds.cjs\");\nObject.keys(_index233).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index233[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index233[key];\n },\n });\n});\nvar _index234 = require(\"./subMinutes.cjs\");\nObject.keys(_index234).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index234[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index234[key];\n },\n });\n});\nvar _index235 = require(\"./subMonths.cjs\");\nObject.keys(_index235).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index235[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index235[key];\n },\n });\n});\nvar _index236 = require(\"./subQuarters.cjs\");\nObject.keys(_index236).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index236[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index236[key];\n },\n });\n});\nvar _index237 = require(\"./subSeconds.cjs\");\nObject.keys(_index237).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index237[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index237[key];\n },\n });\n});\nvar _index238 = require(\"./subWeeks.cjs\");\nObject.keys(_index238).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index238[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index238[key];\n },\n });\n});\nvar _index239 = require(\"./subYears.cjs\");\nObject.keys(_index239).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index239[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index239[key];\n },\n });\n});\nvar _index240 = require(\"./toDate.cjs\");\nObject.keys(_index240).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index240[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index240[key];\n },\n });\n});\nvar _index241 = require(\"./transpose.cjs\");\nObject.keys(_index241).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index241[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index241[key];\n },\n });\n});\nvar _index242 = require(\"./weeksToDays.cjs\");\nObject.keys(_index242).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index242[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index242[key];\n },\n });\n});\nvar _index243 = require(\"./yearsToDays.cjs\");\nObject.keys(_index243).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index243[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index243[key];\n },\n });\n});\nvar _index244 = require(\"./yearsToMonths.cjs\");\nObject.keys(_index244).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index244[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index244[key];\n },\n });\n});\nvar _index245 = require(\"./yearsToQuarters.cjs\");\nObject.keys(_index245).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _index245[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return _index245[key];\n },\n });\n});\n", "'use strict'\n\nconst { readdir, stat, unlink, symlink, lstat, readlink } = require('fs/promises')\nconst { dirname, join } = require('path')\nconst { format, addDays, addHours, parse, isValid } = require('date-fns')\n\nfunction parseSize (size) {\n let multiplier = 1024 ** 2\n if (typeof size !== 'string' && typeof size !== 'number') {\n return null\n }\n if (typeof size === 'string') {\n const match = size.match(/^([\\d.]+)(\\w?)$/)\n if (match) {\n const unit = match[2]?.toLowerCase()\n size = +match[1]\n multiplier = unit === 'g' ? 1024 ** 3 : unit === 'k' ? 1024 : unit === 'b' ? 1 : 1024 ** 2\n } else {\n throw new Error(`${size} is not a valid size in KB, MB or GB`)\n }\n }\n return size * multiplier\n}\n\nfunction parseFrequency (frequency) {\n const today = new Date()\n if (frequency === 'daily') {\n const start = today.setHours(0, 0, 0, 0)\n return { frequency, start, next: getNextDay(start) }\n }\n if (frequency === 'hourly') {\n const start = today.setMinutes(0, 0, 0)\n return { frequency, start, next: getNextHour(start) }\n }\n if (typeof frequency === 'number') {\n const start = today.getTime() - today.getTime() % frequency\n return { frequency, start, next: getNextCustom(frequency) }\n }\n if (frequency) {\n throw new Error(`${frequency} is neither a supported frequency or a number of milliseconds`)\n }\n return null\n}\n\nfunction validateLimitOptions (limit) {\n if (limit) {\n if (typeof limit !== 'object') {\n throw new Error('limit must be an object')\n }\n if (typeof limit.count !== 'number' || limit.count <= 0) {\n throw new Error('limit.count must be a number greater than 0')\n }\n if (typeof limit.removeOtherLogFiles !== 'undefined' && typeof limit.removeOtherLogFiles !== 'boolean') {\n throw new Error('limit.removeOtherLogFiles must be boolean')\n }\n }\n}\n\nfunction getNextDay (start) {\n return addDays(new Date(start), 1).setHours(0, 0, 0, 0)\n}\n\nfunction getNextHour (start) {\n return addHours(new Date(start), 1).setMinutes(0, 0, 0)\n}\n\nfunction getNextCustom (frequency) {\n const time = Date.now()\n return time - time % frequency + frequency\n}\n\nfunction getNext (frequency) {\n if (frequency === 'daily') {\n return getNextDay(new Date().setHours(0, 0, 0, 0))\n }\n if (frequency === 'hourly') {\n return getNextHour(new Date().setMinutes(0, 0, 0))\n }\n return getNextCustom(frequency)\n}\n\nfunction getFileName (fileVal) {\n if (!fileVal) {\n throw new Error('No file name provided')\n }\n return typeof fileVal === 'function' ? fileVal() : fileVal\n}\n\nfunction buildFileName (fileVal, date, lastNumber = 1, extension) {\n const dateStr = date ? `.${date}` : ''\n const extensionStr = typeof extension !== 'string' ? '' : extension.startsWith('.') ? extension : `.${extension}`\n return `${getFileName(fileVal)}${dateStr}.${lastNumber}${extensionStr}`\n}\n\nfunction identifyLogFile (checkedFileName, fileVal, dateFormat, extension) {\n const baseFileNameStr = getFileName(fileVal)\n if (!checkedFileName.startsWith(baseFileNameStr)) return false\n const checkFileNameSegments = checkedFileName\n .slice(baseFileNameStr.length + 1)\n .split('.')\n let expectedSegmentCount = 1\n if (typeof dateFormat === 'string' && dateFormat.length > 0) expectedSegmentCount++\n if (typeof extension === 'string' && extension.length > 0) expectedSegmentCount++\n const extensionStr = typeof extension !== 'string' ? '' : extension.startsWith('.') ? extension.slice(1) : extension\n if (checkFileNameSegments.length !== expectedSegmentCount) return false\n if (extensionStr.length > 0) {\n const chkExtension = checkFileNameSegments.pop()\n if (extensionStr !== chkExtension) return false\n }\n const chkFileNumber = checkFileNameSegments.pop()\n const fileNumber = Number(chkFileNumber)\n if (!Number.isInteger(fileNumber)) {\n return false\n }\n let fileTime = 0\n if (typeof dateFormat === 'string' && dateFormat.length > 0) {\n const d = parse(checkFileNameSegments[0], dateFormat, new Date())\n if (!isValid(d)) return false\n fileTime = d.getTime()\n }\n return { fileName: checkedFileName, fileTime, fileNumber }\n}\n\nasync function getFileSize (filePath) {\n try {\n const fileStats = await stat(filePath)\n return fileStats.size\n } catch {\n return 0\n }\n}\n\nasync function detectLastNumber (fileVal, time = null) {\n const fileName = getFileName(fileVal)\n try {\n const numbers = await readFileTrailingNumbers(dirname(fileName), time)\n return numbers.sort((a, b) => b - a)[0]\n } catch {\n return 1\n }\n}\n\nasync function readFileTrailingNumbers (folder, time) {\n const numbers = [1]\n for (const file of await readdir(folder)) {\n if (time && !(await isMatchingTime(join(folder, file), time))) {\n continue\n }\n const number = extractTrailingNumber(file)\n if (number) {\n numbers.push(number)\n }\n }\n return numbers\n}\n\nfunction extractTrailingNumber (fileName) {\n const match = fileName.match(/(\\d+)$/)\n return match ? +match[1] : null\n}\n\nfunction extractFileName (fileName) {\n return fileName.split(/(\\\\|\\/)/g).pop()\n}\n\nasync function isMatchingTime (filePath, time) {\n const { birthtimeMs } = await stat(filePath)\n return birthtimeMs >= time\n}\n\nasync function removeOldFiles ({ count, removeOtherLogFiles, baseFile, dateFormat, extension, createdFileNames, newFileName }) {\n if (!removeOtherLogFiles) {\n createdFileNames.push(newFileName)\n if (createdFileNames.length > count) {\n const filesToRemove = createdFileNames.splice(0, createdFileNames.length - 1 - count)\n await Promise.allSettled(filesToRemove.map(file => unlink(file)))\n }\n } else {\n let files = []\n const pathSegments = getFileName(baseFile).split(/(\\\\|\\/)/g)\n const baseFileNameStr = pathSegments.pop()\n for (const fileEntry of await readdir(join(...pathSegments))) {\n const f = identifyLogFile(fileEntry, baseFileNameStr, dateFormat, extension)\n if (f) {\n files.push(f)\n }\n }\n files = files.sort((i, j) => {\n if (i.fileTime === j.fileTime) {\n return i.fileNumber - j.fileNumber\n }\n return i.fileTime - j.fileTime\n })\n if (files.length > count) {\n await Promise.allSettled(\n files\n .slice(0, files.length - count)\n .map(file => unlink(join(...pathSegments, file.fileName)))\n )\n }\n }\n}\n\nasync function checkSymlink (fileName, linkPath) {\n const stats = await lstat(linkPath).then(stats => stats, () => null)\n if (stats?.isSymbolicLink()) {\n const existingTarget = await readlink(linkPath)\n if (extractFileName(existingTarget) === extractFileName(fileName)) {\n return false\n }\n await unlink(linkPath)\n }\n return true\n}\n\nasync function createSymlink (fileVal) {\n const linkPath = join(dirname(fileVal), 'current.log')\n const shouldCreateSymlink = await checkSymlink(fileVal, linkPath)\n if (shouldCreateSymlink) {\n await symlink(extractFileName(fileVal), linkPath)\n }\n return false\n}\n\nfunction validateDateFormat (formatStr) {\n const invalidChars = /[/\\\\?%*:|\"<>]/g\n if (invalidChars.test(formatStr)) {\n throw new Error(`${formatStr} contains invalid characters`)\n }\n return true\n}\n\nfunction parseDate (formatStr, frequencySpec, parseStart = false) {\n if (!(formatStr && frequencySpec?.start && frequencySpec.next)) return null\n\n try {\n return format(parseStart ? frequencySpec.start : frequencySpec.next, formatStr)\n } catch (error) {\n throw new Error(`${formatStr} must be a valid date format`)\n }\n}\n\nmodule.exports = {\n buildFileName,\n identifyLogFile,\n removeOldFiles,\n checkSymlink,\n createSymlink,\n detectLastNumber,\n extractFileName,\n parseFrequency,\n getNext,\n parseSize,\n getFileName,\n getFileSize,\n validateLimitOptions,\n parseDate,\n validateDateFormat\n}\n", "'use strict'\n\nconst SonicBoom = require('sonic-boom')\nconst {\n buildFileName,\n removeOldFiles,\n createSymlink,\n detectLastNumber,\n parseSize,\n parseFrequency,\n getNext,\n getFileSize,\n validateLimitOptions,\n parseDate,\n validateDateFormat\n} = require('./lib/utils')\n\n/**\n * A function that returns a string path to the base file name\n *\n * @typedef {function} LogFilePath\n * @returns {string}\n */\n\n/**\n * @typedef {object} Options\n *\n * @property {string|LogFilePath} file - Absolute or relative path to the log file.\n * Your application needs the write right on the parent folder.\n * Number will be appended to this file name.\n * When the parent folder already contains numbered files, numbering will continue based on the highest number.\n * If this path does not exist, the logger with throw an error unless you set `mkdir` to `true`.\n *\n * @property {string|number} size? - When specified, the maximum size of a given log file.\n * Can be combined with frequency.\n * Use 'k', 'm' and 'g' to express values in KB, MB or GB.\n * Numerical values will be considered as MB.\n *\n * @property {string|number} frequency? - When specified, the amount of time a given log file is used.\n * Can be combined with size.\n * Use 'daily' or 'hourly' to rotate file every day (or every hour).\n * Existing file within the current day (or hour) will be re-used.\n * Numerical values will be considered as a number of milliseconds.\n * Using a numerical value will always create a new file upon startup.\n *\n * @property {string} extension? - When specified, appends a file extension after the file number.\n *\n * @property {boolean} symlink? - When specified, creates a symlink to the current log file.\n *\n * @property {LimitOptions} limit? - strategy used to remove oldest files when rotating them.\n *\n * @property {string} dateFormat? - When specified, appends the current date/time to the file name in the provided format.\n * Supports date formats from `date-fns` (see: https://date-fns.org/v4.1.0/docs/format), such as 'yyyy-MM-dd' and 'yyyy-MM-dd-hh'.\n */\n\n/**\n * @typedef {object} LimitOptions\n *\n * @property {number} count? -number of log files, **in addition to the currently used file**.\n * @property {boolean} removeOtherLogFiles? - when true, older file matching the log file format will also be removed.\n */\n\n/**\n * @typedef {Options & import('sonic-boom').SonicBoomOpts} PinoRollOptions\n */\n\n/**\n * Creates a Pino transport (a Sonic-boom stream) to writing into files.\n * Automatically rolls your files based on a given frequency, size, or both.\n *\n * @param {PinoRollOptions} options - to configure file destionation, and rolling rules.\n * @returns {SonicBoom} the Sonic boom steam, usabled as Pino transport.\n */\nmodule.exports = async function ({\n file,\n size,\n frequency,\n extension,\n limit,\n symlink,\n dateFormat,\n ...opts\n} = {}) {\n validateLimitOptions(limit)\n validateDateFormat(dateFormat)\n const frequencySpec = parseFrequency(frequency)\n\n let date = parseDate(dateFormat, frequencySpec, true)\n let number = await detectLastNumber(file, frequencySpec?.start, dateFormat)\n\n let fileName = buildFileName(file, date, number, extension)\n const createdFileNames = [fileName]\n let currentSize = await getFileSize(fileName)\n const maxSize = parseSize(size)\n\n const destination = new SonicBoom({ ...opts, dest: fileName })\n\n if (symlink) {\n createSymlink(fileName)\n }\n\n let rollTimeout\n if (frequencySpec) {\n destination.once('close', () => {\n clearTimeout(rollTimeout)\n })\n scheduleRoll()\n }\n\n if (maxSize) {\n destination.on('write', writtenSize => {\n currentSize += writtenSize\n if (fileName === destination.file && currentSize >= maxSize) {\n currentSize = 0\n fileName = buildFileName(file, date, ++number, extension)\n // delay to let the destination finish its write\n destination.once('drain', roll)\n }\n })\n }\n\n function roll () {\n destination.reopen(fileName)\n if (symlink) {\n createSymlink(fileName)\n }\n if (limit) {\n removeOldFiles({ ...limit, baseFile: file, dateFormat, extension, createdFileNames, newFileName: fileName })\n }\n }\n\n function scheduleRoll () {\n clearTimeout(rollTimeout)\n rollTimeout = setTimeout(() => {\n const prevDate = date\n date = parseDate(dateFormat, frequencySpec)\n if (dateFormat && date && date !== prevDate) number = 0\n fileName = buildFileName(file, date, ++number, extension)\n roll()\n frequencySpec.next = getNext(frequency)\n scheduleRoll()\n }, frequencySpec.next - Date.now())\n }\n\n return destination\n}\n"], + "mappings": "wTAAA,IAAAA,GAAAC,EAAA,CAAAC,GAAAC,KAAA,cAIA,GAAI,OAAO,kBAAsB,KAAe,OAAO,QAAY,IAAa,CAG9E,IAASC,EAAT,SAAgBC,EAAI,CAGlB,IADcA,EAAK,GAAKA,EAAK,OACf,GACZ,MAAI,OAAOA,GAAO,UAAY,OAAOA,GAAO,SACpC,UAAU,4BAA4B,EAExC,WAAW,0EAA0E,EAG7F,QAAQ,KAAKC,EAA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AAUQ,EAAYE,CAAa,EACtCF,GAAcG,GAAQA,IAASW,IAAUV,EAAS,GACtDC,EAAWtB,GAAcW,EAAMS,EAAM,EAAEC,EAAQP,CAAS,EACxDgB,EAAK,EACLX,EAAc,KAAOb,GAAQO,CAAS,EACtCe,EAAa,CACf,EAAGT,EAAc,KAAO,KAAK,IAAI,CAAC,CACpC,CAEA,OAAOO,CACT", + "names": ["require_atomic_sleep", "__commonJSMin", "exports", "module", "sleep", "ms", "nil", "target", "require_sonic_boom", "__commonJSMin", "exports", "module", "fs", "EventEmitter", "inherits", "path", "sleep", "assert", "BUSY_WRITE_TIMEOUT", "kEmptyBuffer", "MAX_WRITE", "kContentModeBuffer", "kContentModeUtf8", "major", "minor", "kCopyBuffer", "openFile", "file", "sonic", "fileOpened", "err", "fd", "reopening", "flags", "mode", "SonicBoom", "opts", "dest", "minLength", "maxLength", "maxWrite", "periodicFlush", "sync", "append", "mkdir", "retryEAGAIN", "fsync", "contentMode", "fsWriteSync", "fsWrite", "writeBuffer", "flushBuffer", "flushBufferSync", "actualWriteBuffer", "write", "flush", "flushSync", "actualWrite", "n", "releasedBufObj", "releaseWritingBuf", "len", "actualClose", "emitDrain", "name", "writingBuf", "mergeBuf", "bufs", "data", "lens", "callFlushCallbackOnDrain", "cb", "onDrain", "onError", "error", "buf", "release", "written", "closeWrapped", "done", "require_constants", "__commonJSMin", "exports", "daysInWeek", "daysInYear", "maxTime", "minTime", "millisecondsInWeek", "millisecondsInDay", "millisecondsInMinute", "millisecondsInHour", "millisecondsInSecond", "minutesInYear", "minutesInMonth", "minutesInDay", "minutesInHour", "monthsInQuarter", "monthsInYear", "quartersInYear", "secondsInHour", "secondsInMinute", "secondsInDay", "secondsInWeek", "secondsInYear", "secondsInMonth", "secondsInQuarter", "constructFromSymbol", "require_constructFrom", "__commonJSMin", "exports", "constructFrom", "_index", "date", "value", "require_toDate", "__commonJSMin", "exports", "toDate", "_index", "argument", "context", "require_addDays", "__commonJSMin", "exports", "addDays", "_index", "_index2", "date", "amount", "options", "_date", "require_addMonths", "__commonJSMin", "exports", "addMonths", "_index", "_index2", "date", "amount", "options", "_date", "dayOfMonth", "endOfDesiredMonth", "daysInMonth", "require_add", "__commonJSMin", "exports", "add", "_index", "_index2", "_index3", "_index4", "date", "duration", "options", "years", "months", "weeks", "days", "hours", "minutes", "seconds", "_date", "dateWithMonths", "dateWithDays", "minutesToAdd", "msToAdd", "require_isSaturday", "__commonJSMin", "exports", "isSaturday", "_index", "date", "options", "require_isSunday", "__commonJSMin", "exports", "isSunday", "_index", "date", "options", "require_isWeekend", "__commonJSMin", "exports", "isWeekend", "_index", "date", "options", "day", "require_addBusinessDays", "__commonJSMin", "exports", "addBusinessDays", "_index", "_index2", "_index3", "_index4", "_index5", "date", "amount", "options", "_date", "startedOnWeekend", "hours", "sign", "fullWeeks", "restDays", "require_addMilliseconds", "__commonJSMin", "exports", "addMilliseconds", "_index", "_index2", "date", "amount", "options", "require_addHours", "__commonJSMin", "exports", "addHours", "_index", "_index2", "date", "amount", "options", "require_defaultOptions", "__commonJSMin", "exports", "getDefaultOptions", "setDefaultOptions", "defaultOptions", "newOptions", "require_startOfWeek", "__commonJSMin", "exports", "startOfWeek", "_index", "_index2", "date", "options", "defaultOptions", "weekStartsOn", "_date", "day", "diff", "require_startOfISOWeek", "__commonJSMin", "exports", "startOfISOWeek", "_index", "date", "options", "require_getISOWeekYear", "__commonJSMin", "exports", "getISOWeekYear", "_index", "_index2", "_index3", "date", "options", "_date", "year", "fourthOfJanuaryOfNextYear", "startOfNextYear", "fourthOfJanuaryOfThisYear", "startOfThisYear", "require_getTimezoneOffsetInMilliseconds", "__commonJSMin", "exports", "getTimezoneOffsetInMilliseconds", "_index", "date", "_date", "utcDate", "require_normalizeDates", "__commonJSMin", "exports", "normalizeDates", "_index", "context", "dates", "normalize", "date", "require_startOfDay", "__commonJSMin", "exports", "startOfDay", "_index", "date", "options", "_date", "require_differenceInCalendarDays", "__commonJSMin", "exports", "differenceInCalendarDays", "_index", "_index2", "_index3", "_index4", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "laterStartOfDay", "earlierStartOfDay", "laterTimestamp", "earlierTimestamp", "require_startOfISOWeekYear", "__commonJSMin", "exports", "startOfISOWeekYear", "_index", "_index2", "_index3", "date", "options", "year", "fourthOfJanuary", "require_setISOWeekYear", "__commonJSMin", "exports", "setISOWeekYear", "_index", "_index2", "_index3", "_index4", "date", "weekYear", "options", "_date", "diff", "fourthOfJanuary", "require_addISOWeekYears", "__commonJSMin", "exports", "addISOWeekYears", "_index", "_index2", "date", "amount", "options", "require_addMinutes", "__commonJSMin", "exports", "addMinutes", "_index", "_index2", "date", "amount", "options", "_date", "require_addQuarters", "__commonJSMin", "exports", "addQuarters", "_index", "date", "amount", "options", "require_addSeconds", "__commonJSMin", "exports", "addSeconds", "_index", "date", "amount", "options", "require_addWeeks", "__commonJSMin", "exports", "addWeeks", "_index", "date", "amount", "options", "require_addYears", "__commonJSMin", "exports", "addYears", "_index", "date", "amount", "options", "require_areIntervalsOverlapping", "__commonJSMin", "exports", "areIntervalsOverlapping", "_index", "intervalLeft", "intervalRight", "options", "leftStartTime", "leftEndTime", "a", "b", "rightStartTime", "rightEndTime", "require_max", "__commonJSMin", "exports", "max", "_index", "_index2", "dates", "options", "result", "context", "date", "date_", "require_min", "__commonJSMin", "exports", "min", "_index", "_index2", "dates", "options", "result", "context", "date", "date_", "require_clamp", "__commonJSMin", "exports", "clamp", "_index", "_index2", "_index3", "date", "interval", "options", "date_", "start", "end", "require_closestIndexTo", "__commonJSMin", "exports", "closestIndexTo", "_index", "dateToCompare", "dates", "timeToCompare", "result", "minDistance", "date", "index", "date_", "distance", "require_closestTo", "__commonJSMin", "exports", "closestTo", "_index", "_index2", "_index3", "dateToCompare", "dates", "options", "dateToCompare_", "dates_", "index", "require_compareAsc", "__commonJSMin", "exports", "compareAsc", "_index", "dateLeft", "dateRight", "diff", "require_compareDesc", "__commonJSMin", "exports", "compareDesc", "_index", "dateLeft", "dateRight", "diff", "require_constructNow", "__commonJSMin", "exports", "constructNow", "_index", "date", "require_daysToWeeks", "__commonJSMin", "exports", "daysToWeeks", "_index", "days", "result", "require_isSameDay", "__commonJSMin", "exports", "isSameDay", "_index", "_index2", "laterDate", "earlierDate", "options", "dateLeft_", "dateRight_", "require_isDate", "__commonJSMin", "exports", "isDate", "value", "require_isValid", "__commonJSMin", "exports", "isValid", "_index", "_index2", "date", "require_differenceInBusinessDays", "__commonJSMin", "exports", "differenceInBusinessDays", "_index", "_index2", "_index3", "_index4", "_index5", "_index6", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "diff", "sign", "weeks", "result", "movingDate", "require_differenceInCalendarISOWeekYears", "__commonJSMin", "exports", "differenceInCalendarISOWeekYears", "_index", "_index2", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "require_differenceInCalendarISOWeeks", "__commonJSMin", "exports", "differenceInCalendarISOWeeks", "_index", "_index2", "_index3", "_index4", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "startOfISOWeekLeft", "startOfISOWeekRight", "timestampLeft", "timestampRight", "require_differenceInCalendarMonths", "__commonJSMin", "exports", "differenceInCalendarMonths", "_index", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "yearsDiff", "monthsDiff", "require_getQuarter", "__commonJSMin", "exports", "getQuarter", "_index", "date", "options", "_date", "require_differenceInCalendarQuarters", "__commonJSMin", "exports", "differenceInCalendarQuarters", "_index", "_index2", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "yearsDiff", "quartersDiff", "require_differenceInCalendarWeeks", "__commonJSMin", "exports", "differenceInCalendarWeeks", "_index", "_index2", "_index3", "_index4", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "laterStartOfWeek", "earlierStartOfWeek", "laterTimestamp", "earlierTimestamp", "require_differenceInCalendarYears", "__commonJSMin", "exports", "differenceInCalendarYears", "_index", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "require_differenceInDays", "__commonJSMin", "exports", "differenceInDays", "_index", "_index2", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "sign", "compareLocalAsc", "difference", "isLastDayNotFull", "result", "diff", "require_getRoundingMethod", "__commonJSMin", "exports", "getRoundingMethod", "method", "number", "result", "require_differenceInHours", "__commonJSMin", "exports", "differenceInHours", "_index", "_index2", "_index3", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "diff", "require_subISOWeekYears", "__commonJSMin", "exports", "subISOWeekYears", "_index", "date", "amount", "options", "require_differenceInISOWeekYears", "__commonJSMin", "exports", "differenceInISOWeekYears", "_index", "_index2", "_index3", "_index4", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "sign", "diff", "adjustedDate", "isLastISOWeekYearNotFull", "result", "require_differenceInMilliseconds", "__commonJSMin", "exports", "differenceInMilliseconds", "_index", "laterDate", "earlierDate", "require_differenceInMinutes", "__commonJSMin", "exports", "differenceInMinutes", "_index", "_index2", "_index3", "dateLeft", "dateRight", "options", "diff", "require_endOfDay", "__commonJSMin", "exports", "endOfDay", "_index", "date", "options", "_date", "require_endOfMonth", "__commonJSMin", "exports", "endOfMonth", "_index", "date", "options", "_date", "month", "require_isLastDayOfMonth", "__commonJSMin", "exports", "isLastDayOfMonth", "_index", "_index2", "_index3", "date", "options", "_date", "require_differenceInMonths", "__commonJSMin", "exports", "differenceInMonths", "_index", "_index2", "_index3", "_index4", "laterDate", "earlierDate", "options", "laterDate_", "workingLaterDate", "earlierDate_", "sign", "difference", "isLastMonthNotFull", "result", "require_differenceInQuarters", "__commonJSMin", "exports", "differenceInQuarters", "_index", "_index2", "laterDate", "earlierDate", "options", "diff", "require_differenceInSeconds", "__commonJSMin", "exports", "differenceInSeconds", "_index", "_index2", "laterDate", "earlierDate", "options", "diff", "require_differenceInWeeks", "__commonJSMin", "exports", "differenceInWeeks", "_index", "_index2", "laterDate", "earlierDate", "options", "diff", "require_differenceInYears", "__commonJSMin", "exports", "differenceInYears", "_index", "_index2", "_index3", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "sign", "diff", "partial", "result", "require_normalizeInterval", "__commonJSMin", "exports", "normalizeInterval", "_index", "context", "interval", "start", "end", "require_eachDayOfInterval", "__commonJSMin", "exports", "eachDayOfInterval", "_index", "_index2", "interval", "options", "start", "end", "reversed", "endTime", "date", "step", "dates", "require_eachHourOfInterval", "__commonJSMin", "exports", "eachHourOfInterval", "_index", "_index2", "interval", "options", "start", "end", "reversed", "endTime", "date", "step", "dates", "require_eachMinuteOfInterval", "__commonJSMin", "exports", "eachMinuteOfInterval", "_index", "_index2", "_index3", "interval", "options", "start", "end", "reversed", "endTime", "date", "step", "dates", "require_eachMonthOfInterval", "__commonJSMin", "exports", "eachMonthOfInterval", "_index", "_index2", "interval", "options", "start", "end", "reversed", "endTime", "date", "step", "dates", "require_startOfQuarter", "__commonJSMin", "exports", "startOfQuarter", "_index", "date", "options", "_date", "currentMonth", "month", "require_eachQuarterOfInterval", "__commonJSMin", "exports", "eachQuarterOfInterval", "_index", "_index2", "_index3", "_index4", "interval", "options", "start", "end", "reversed", "endTime", "date", "step", "dates", "require_eachWeekOfInterval", "__commonJSMin", "exports", "eachWeekOfInterval", "_index", "_index2", "_index3", "_index4", "interval", "options", "start", "end", "reversed", "startDateWeek", "endDateWeek", "endTime", "currentDate", "step", "dates", "require_eachWeekendOfInterval", "__commonJSMin", "exports", "eachWeekendOfInterval", "_index", "_index2", "_index3", "_index4", "interval", "options", "start", "end", "dateInterval", "weekends", "index", "date", "require_startOfMonth", "__commonJSMin", "exports", "startOfMonth", "_index", "date", "options", "_date", "require_eachWeekendOfMonth", "__commonJSMin", "exports", "eachWeekendOfMonth", "_index", "_index2", "_index3", "date", "options", "start", "end", "require_endOfYear", "__commonJSMin", "exports", "endOfYear", "_index", "date", "options", "_date", "year", "require_startOfYear", "__commonJSMin", "exports", "startOfYear", "_index", "date", "options", "date_", "require_eachWeekendOfYear", "__commonJSMin", "exports", "eachWeekendOfYear", "_index", "_index2", "_index3", "date", "options", "start", "end", "require_eachYearOfInterval", "__commonJSMin", "exports", "eachYearOfInterval", "_index", "_index2", "interval", "options", "start", "end", "reversed", "endTime", "date", "step", "dates", "require_endOfDecade", "__commonJSMin", "exports", "endOfDecade", "_index", "date", "options", "_date", "year", "decade", "require_endOfHour", "__commonJSMin", "exports", "endOfHour", "_index", "date", "options", "_date", "require_endOfWeek", "__commonJSMin", "exports", "endOfWeek", "_index", "_index2", "date", "options", "defaultOptions", "weekStartsOn", "_date", "day", "diff", "require_endOfISOWeek", "__commonJSMin", "exports", "endOfISOWeek", "_index", "date", "options", "require_endOfISOWeekYear", "__commonJSMin", "exports", "endOfISOWeekYear", "_index", "_index2", "_index3", "date", "options", "year", "fourthOfJanuaryOfNextYear", "_date", "require_endOfMinute", "__commonJSMin", "exports", "endOfMinute", "_index", "date", "options", "_date", "require_endOfQuarter", "__commonJSMin", "exports", "endOfQuarter", "_index", "date", "options", "_date", "currentMonth", "month", "require_endOfSecond", "__commonJSMin", "exports", "endOfSecond", "_index", "date", "options", "_date", "require_endOfToday", "__commonJSMin", "exports", "endOfToday", "_index", "options", "require_endOfTomorrow", "__commonJSMin", "exports", "endOfTomorrow", "_index", "options", "now", "year", "month", "day", "date", "require_endOfYesterday", "__commonJSMin", "exports", "endOfYesterday", "_index", "_index2", "options", "now", "date", "require_formatDistance", "__commonJSMin", "exports", "formatDistanceLocale", "formatDistance", "token", "count", "options", "result", "tokenValue", "require_buildFormatLongFn", "__commonJSMin", "exports", "buildFormatLongFn", "args", "options", "width", "require_formatLong", "__commonJSMin", "exports", "_index", "dateFormats", "timeFormats", "dateTimeFormats", "formatLong", "require_formatRelative", "__commonJSMin", "exports", "formatRelativeLocale", "formatRelative", "token", "_date", "_baseDate", "_options", "require_buildLocalizeFn", "__commonJSMin", "exports", "buildLocalizeFn", "args", "value", "options", "context", "valuesArray", "defaultWidth", "width", "index", "require_localize", "__commonJSMin", "exports", "_index", "eraValues", "quarterValues", "monthValues", "dayValues", "dayPeriodValues", "formattingDayPeriodValues", "ordinalNumber", "dirtyNumber", "_options", "number", "rem100", "localize", "quarter", "require_buildMatchFn", "__commonJSMin", "exports", "buildMatchFn", "args", "string", "options", "width", "matchPattern", "matchResult", "matchedString", "parsePatterns", "key", "findIndex", "pattern", "findKey", "value", "rest", "object", "predicate", "array", "require_buildMatchPatternFn", "__commonJSMin", "exports", "buildMatchPatternFn", "args", "string", "options", "matchResult", "matchedString", "parseResult", "value", "rest", "require_match", "__commonJSMin", "exports", "_index", "_index2", "matchOrdinalNumberPattern", "parseOrdinalNumberPattern", "matchEraPatterns", "parseEraPatterns", "matchQuarterPatterns", "parseQuarterPatterns", "matchMonthPatterns", "parseMonthPatterns", "matchDayPatterns", "parseDayPatterns", "matchDayPeriodPatterns", "parseDayPeriodPatterns", "match", "value", "index", "require_en_US", "__commonJSMin", "exports", "_index", "_index2", "_index3", "_index4", "_index5", "enUS", "require_defaultLocale", "__commonJSMin", "exports", "_index", "require_getDayOfYear", "__commonJSMin", "exports", "getDayOfYear", "_index", "_index2", "_index3", "date", "options", "_date", "require_getISOWeek", "__commonJSMin", "exports", "getISOWeek", "_index", "_index2", "_index3", "_index4", "date", "options", "_date", "diff", "require_getWeekYear", "__commonJSMin", "exports", "getWeekYear", "_index", "_index2", "_index3", "_index4", "date", "options", "_date", "year", "defaultOptions", "firstWeekContainsDate", "firstWeekOfNextYear", "startOfNextYear", "firstWeekOfThisYear", "startOfThisYear", "require_startOfWeekYear", "__commonJSMin", "exports", "startOfWeekYear", "_index", "_index2", "_index3", "_index4", "date", "options", "defaultOptions", "firstWeekContainsDate", "year", "firstWeek", "require_getWeek", "__commonJSMin", "exports", "getWeek", "_index", "_index2", "_index3", "_index4", "date", "options", "_date", "diff", "require_addLeadingZeros", "__commonJSMin", "exports", "addLeadingZeros", "number", "targetLength", "sign", "output", "require_lightFormatters", "__commonJSMin", "exports", "_index", "lightFormatters", "date", "token", "signedYear", "year", "month", "dayPeriodEnumValue", "numberOfDigits", "milliseconds", "fractionalSeconds", "require_formatters", "__commonJSMin", "exports", "_index", "_index2", "_index3", "_index4", "_index5", "_index6", "_index7", "dayPeriodEnum", "formatters", "date", "token", "localize", "era", "signedYear", "year", "options", "signedWeekYear", "weekYear", "twoDigitYear", "isoWeekYear", "quarter", "month", "week", "isoWeek", "dayOfYear", "dayOfWeek", "localDayOfWeek", "isoDayOfWeek", "dayPeriodEnumValue", "hours", "_localize", "timezoneOffset", "formatTimezoneWithOptionalMinutes", "formatTimezone", "formatTimezoneShort", "timestamp", "offset", "delimiter", "sign", "absOffset", "minutes", "require_longFormatters", "__commonJSMin", "exports", "dateLongFormatter", "pattern", "formatLong", "timeLongFormatter", "dateTimeLongFormatter", "matchResult", "datePattern", "timePattern", "dateTimeFormat", "longFormatters", "require_protectedTokens", "__commonJSMin", "exports", "isProtectedDayOfYearToken", "isProtectedWeekYearToken", "warnOrThrowProtectedError", "dayOfYearTokenRE", "weekYearTokenRE", "throwTokens", "token", "format", "input", "_message", "message", "subject", "require_format", "__commonJSMin", "exports", "format", "_index3", "_index4", "_index", "_index2", "_index5", "_index6", "_index7", "formattingTokensRegExp", "longFormattingTokensRegExp", "escapedStringRegExp", "doubleQuoteRegExp", "unescapedLatinCharacterRegExp", "date", "formatStr", "options", "defaultOptions", "locale", "firstWeekContainsDate", "weekStartsOn", "originalDate", "parts", "substring", "firstCharacter", "longFormatter", "cleanEscapedString", "formatterOptions", "part", "token", "formatter", "input", "matched", "require_formatDistance", "__commonJSMin", "exports", "formatDistance", "_index", "_index2", "_index3", "_index4", "_index5", "_index6", "_index7", "_index8", "laterDate", "earlierDate", "options", "defaultOptions", "locale", "minutesInAlmostTwoDays", "comparison", "localizeOptions", "laterDate_", "earlierDate_", "seconds", "offsetInSeconds", "minutes", "months", "hours", "days", "nearestMonth", "monthsSinceStartOfYear", "years", "require_formatDistanceStrict", "__commonJSMin", "exports", "formatDistanceStrict", "_index", "_index2", "_index3", "_index4", "_index5", "_index6", "_index7", "laterDate", "earlierDate", "options", "defaultOptions", "locale", "comparison", "localizeOptions", "laterDate_", "earlierDate_", "roundingMethod", "milliseconds", "minutes", "timezoneOffset", "dstNormalizedMinutes", "defaultUnit", "unit", "seconds", "roundedMinutes", "hours", "days", "months", "years", "require_formatDistanceToNow", "__commonJSMin", "exports", "formatDistanceToNow", "_index", "_index2", "date", "options", "require_formatDistanceToNowStrict", "__commonJSMin", "exports", "formatDistanceToNowStrict", "_index", "_index2", "date", "options", "require_formatDuration", "__commonJSMin", "exports", "formatDuration", "_index", "_index2", "defaultFormat", "duration", "options", "defaultOptions", "locale", "format", "zero", "delimiter", "acc", "unit", "token", "m", "value", "require_formatISO", "__commonJSMin", "exports", "formatISO", "_index", "_index2", "date", "options", "date_", "format", "representation", "result", "tzOffset", "dateDelimiter", "timeDelimiter", "day", "month", "offset", "absoluteOffset", "hourOffset", "minuteOffset", "hour", "minute", "second", "separator", "time", "require_formatISO9075", "__commonJSMin", "exports", "formatISO9075", "_index", "_index2", "_index3", "date", "options", "date_", "format", "representation", "result", "dateDelimiter", "timeDelimiter", "day", "month", "hour", "minute", "second", "require_formatISODuration", "__commonJSMin", "exports", "formatISODuration", "duration", "years", "months", "days", "hours", "minutes", "seconds", "require_formatRFC3339", "__commonJSMin", "exports", "formatRFC3339", "_index", "_index2", "_index3", "date", "options", "date_", "fractionDigits", "day", "month", "year", "hour", "minute", "second", "fractionalSecond", "milliseconds", "fractionalSeconds", "offset", "tzOffset", "absoluteOffset", "hourOffset", "minuteOffset", "require_formatRFC7231", "__commonJSMin", "exports", "formatRFC7231", "_index", "_index2", "_index3", "days", "months", "date", "_date", "dayName", "dayOfMonth", "monthName", "year", "hour", "minute", "second", "require_formatRelative", "__commonJSMin", "exports", "formatRelative", "_index", "_index2", "_index3", "_index4", "_index5", "date", "baseDate", "options", "date_", "baseDate_", "defaultOptions", "locale", "weekStartsOn", "diff", "token", "formatStr", "require_fromUnixTime", "__commonJSMin", "exports", "fromUnixTime", "_index", "unixTime", "options", "require_getDate", "__commonJSMin", "exports", "getDate", "_index", "date", "options", "require_getDay", "__commonJSMin", "exports", "getDay", "_index", "date", "options", "require_getDaysInMonth", "__commonJSMin", "exports", "getDaysInMonth", "_index", "_index2", "date", "options", "_date", "year", "monthIndex", "lastDayOfMonth", "require_isLeapYear", "__commonJSMin", "exports", "isLeapYear", "_index", "date", "options", "year", "require_getDaysInYear", "__commonJSMin", "exports", "getDaysInYear", "_index", "_index2", "date", "options", "_date", "require_getDecade", "__commonJSMin", "exports", "getDecade", "_index", "date", "options", "year", "require_getDefaultOptions", "__commonJSMin", "exports", "getDefaultOptions", "_index", "require_getHours", "__commonJSMin", "exports", "getHours", "_index", "date", "options", "require_getISODay", "__commonJSMin", "exports", "getISODay", "_index", "date", "options", "day", "require_getISOWeeksInYear", "__commonJSMin", "exports", "getISOWeeksInYear", "_index", "_index2", "_index3", "date", "options", "thisYear", "diff", "require_getMilliseconds", "__commonJSMin", "exports", "getMilliseconds", "_index", "date", "require_getMinutes", "__commonJSMin", "exports", "getMinutes", "_index", "date", "options", "require_getMonth", "__commonJSMin", "exports", "getMonth", "_index", "date", "options", "require_getOverlappingDaysInIntervals", "__commonJSMin", "exports", "getOverlappingDaysInIntervals", "_index", "_index2", "_index3", "intervalLeft", "intervalRight", "leftStart", "leftEnd", "a", "b", "rightStart", "rightEnd", "overlapLeft", "left", "overlapRight", "right", "require_getSeconds", "__commonJSMin", "exports", "getSeconds", "_index", "date", "require_getTime", "__commonJSMin", "exports", "getTime", "_index", "date", "require_getUnixTime", "__commonJSMin", "exports", "getUnixTime", "_index", "date", "require_getWeekOfMonth", "__commonJSMin", "exports", "getWeekOfMonth", "_index", "_index2", "_index3", "_index4", "_index5", "date", "options", "defaultOptions", "weekStartsOn", "currentDayOfMonth", "startWeekDay", "lastDayOfFirstWeek", "remainingDaysAfterFirstWeek", "require_lastDayOfMonth", "__commonJSMin", "exports", "lastDayOfMonth", "_index", "date", "options", "_date", "month", "require_getWeeksInMonth", "__commonJSMin", "exports", "getWeeksInMonth", "_index", "_index2", "_index3", "_index4", "date", "options", "contextDate", "require_getYear", "__commonJSMin", "exports", "getYear", "_index", "date", "options", "require_hoursToMilliseconds", "__commonJSMin", "exports", "hoursToMilliseconds", "_index", "hours", "require_hoursToMinutes", "__commonJSMin", "exports", "hoursToMinutes", "_index", "hours", "require_hoursToSeconds", "__commonJSMin", "exports", "hoursToSeconds", "_index", "hours", "require_interval", "__commonJSMin", "exports", "interval", "_index", "start", "end", "options", "_start", "_end", "require_intervalToDuration", "__commonJSMin", "exports", "intervalToDuration", "_index", "_index2", "_index3", "_index4", "_index5", "_index6", "_index7", "_index8", "interval", "options", "start", "end", "duration", "years", "remainingMonths", "months", "remainingDays", "days", "remainingHours", "hours", "remainingMinutes", "minutes", "remainingSeconds", "seconds", "require_intlFormat", "__commonJSMin", "exports", "intlFormat", "_index", "date", "formatOrLocale", "localeOptions", "formatOptions", "isFormatOptions", "opts", "require_intlFormatDistance", "__commonJSMin", "exports", "intlFormatDistance", "_index", "_index2", "_index3", "_index4", "_index5", "_index6", "_index7", "_index8", "_index9", "_index10", "laterDate", "earlierDate", "options", "value", "unit", "laterDate_", "earlierDate_", "diffInSeconds", "require_isAfter", "__commonJSMin", "exports", "isAfter", "_index", "date", "dateToCompare", "require_isBefore", "__commonJSMin", "exports", "isBefore", "_index", "date", "dateToCompare", "require_isEqual", "__commonJSMin", "exports", "isEqual", "_index", "leftDate", "rightDate", "require_isExists", "__commonJSMin", "exports", "isExists", "year", "month", "day", "date", "require_isFirstDayOfMonth", "__commonJSMin", "exports", "isFirstDayOfMonth", "_index", "date", "options", "require_isFriday", "__commonJSMin", "exports", "isFriday", "_index", "date", "options", "require_isFuture", "__commonJSMin", "exports", "isFuture", "_index", "date", "require_transpose", "__commonJSMin", "exports", "transpose", "_index", "date", "constructor", "date_", "isConstructor", "require_Setter", "__commonJSMin", "exports", "_index", "_index2", "TIMEZONE_UNIT_PRIORITY", "Setter", "_utcDate", "_options", "ValueSetter", "value", "validateValue", "setValue", "priority", "subPriority", "date", "options", "flags", "DateTimezoneSetter", "context", "reference", "require_Parser", "__commonJSMin", "exports", "_Setter", "Parser", "dateString", "token", "match", "options", "result", "_utcDate", "_value", "_options", "require_EraParser", "__commonJSMin", "exports", "_Parser", "EraParser", "dateString", "token", "match", "date", "flags", "value", "require_constants", "__commonJSMin", "exports", "numericPatterns", "timezonePatterns", "require_utils", "__commonJSMin", "exports", "dayPeriodEnumToHours", "isLeapYearIndex", "mapValue", "normalizeTwoDigitYear", "parseAnyDigitsSigned", "parseNDigits", "parseNDigitsSigned", "parseNumericPattern", "parseTimezonePattern", "_index", "_constants", "parseFnResult", "mapFn", "pattern", "dateString", "matchResult", "sign", "hours", "minutes", "seconds", "n", "dayPeriod", "twoDigitYear", "currentYear", "isCommonEra", "absCurrentYear", "result", "rangeEnd", "rangeEndCentury", "isPreviousCentury", "year", "require_YearParser", "__commonJSMin", "exports", "_Parser", "_utils", "YearParser", "dateString", "token", "match", "valueCallback", "year", "_date", "value", "date", "flags", "currentYear", "normalizedTwoDigitYear", "require_LocalWeekYearParser", "__commonJSMin", "exports", "_index", "_index2", "_Parser", "_utils", "LocalWeekYearParser", "dateString", "token", "match", "valueCallback", "year", "_date", "value", "date", "flags", "options", "currentYear", "normalizedTwoDigitYear", "require_ISOWeekYearParser", "__commonJSMin", "exports", "_index", "_index2", "_Parser", "_utils", "ISOWeekYearParser", "dateString", "token", "date", "_flags", "value", "firstWeekOfYear", "require_ExtendedYearParser", "__commonJSMin", "exports", "_Parser", "_utils", "ExtendedYearParser", "dateString", "token", "date", "_flags", "value", "require_QuarterParser", "__commonJSMin", "exports", "_Parser", "_utils", "QuarterParser", "dateString", "token", "match", "_date", "value", "date", "_flags", "require_StandAloneQuarterParser", "__commonJSMin", "exports", "_Parser", "_utils", "StandAloneQuarterParser", "dateString", "token", "match", "_date", "value", "date", "_flags", "require_MonthParser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "MonthParser", "dateString", "token", "match", "valueCallback", "value", "_date", "date", "_flags", "require_StandAloneMonthParser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "StandAloneMonthParser", "dateString", "token", "match", "valueCallback", "value", "_date", "date", "_flags", "require_setWeek", "__commonJSMin", "exports", "setWeek", "_index", "_index2", "date", "week", "options", "date_", "diff", "require_LocalWeekParser", "__commonJSMin", "exports", "_index", "_index2", "_constants", "_Parser", "_utils", "LocalWeekParser", "dateString", "token", "match", "_date", "value", "date", "_flags", "options", "require_setISOWeek", "__commonJSMin", "exports", "setISOWeek", "_index", "_index2", "date", "week", "options", "_date", "diff", "require_ISOWeekParser", "__commonJSMin", "exports", "_index", "_index2", "_constants", "_Parser", "_utils", "ISOWeekParser", "dateString", "token", "match", "_date", "value", "date", "_flags", "require_DateParser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "DAYS_IN_MONTH", "DAYS_IN_MONTH_LEAP_YEAR", "DateParser", "dateString", "token", "match", "date", "value", "year", "isLeapYear", "month", "_flags", "require_DayOfYearParser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "DayOfYearParser", "dateString", "token", "match", "date", "value", "year", "_flags", "require_setDay", "__commonJSMin", "exports", "setDay", "_index", "_index2", "_index3", "date", "day", "options", "defaultOptions", "weekStartsOn", "date_", "currentDay", "dayIndex", "delta", "diff", "require_DayParser", "__commonJSMin", "exports", "_index", "_Parser", "DayParser", "dateString", "token", "match", "_date", "value", "date", "_flags", "options", "require_LocalDayParser", "__commonJSMin", "exports", "_index", "_Parser", "_utils", "LocalDayParser", "dateString", "token", "match", "options", "valueCallback", "value", "wholeWeekDays", "_date", "date", "_flags", "require_StandAloneLocalDayParser", "__commonJSMin", "exports", "_index", "_Parser", "_utils", "StandAloneLocalDayParser", "dateString", "token", "match", "options", "valueCallback", "value", "wholeWeekDays", "_date", "date", "_flags", "require_setISODay", "__commonJSMin", "exports", "setISODay", "_index", "_index2", "_index3", "date", "day", "options", "date_", "currentDay", "diff", "require_ISODayParser", "__commonJSMin", "exports", "_index", "_Parser", "_utils", "ISODayParser", "dateString", "token", "match", "valueCallback", "value", "_date", "date", "_flags", "require_AMPMParser", "__commonJSMin", "exports", "_Parser", "_utils", "AMPMParser", "dateString", "token", "match", "date", "_flags", "value", "require_AMPMMidnightParser", "__commonJSMin", "exports", "_Parser", "_utils", "AMPMMidnightParser", "dateString", "token", "match", "date", "_flags", "value", "require_DayPeriodParser", "__commonJSMin", "exports", "_Parser", "_utils", "DayPeriodParser", "dateString", "token", "match", "date", "_flags", "value", "require_Hour1to12Parser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "Hour1to12Parser", "dateString", "token", "match", "_date", "value", "date", "_flags", "isPM", "require_Hour0to23Parser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "Hour0to23Parser", "dateString", "token", "match", "_date", "value", "date", "_flags", "require_Hour0To11Parser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "Hour0To11Parser", "dateString", "token", "match", "_date", "value", "date", "_flags", "require_Hour1To24Parser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "Hour1To24Parser", "dateString", "token", "match", "_date", "value", "date", "_flags", "hours", "require_MinuteParser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "MinuteParser", "dateString", "token", "match", "_date", "value", "date", "_flags", "require_SecondParser", "__commonJSMin", "exports", "_constants", "_Parser", "_utils", "SecondParser", "dateString", "token", "match", "_date", "value", "date", "_flags", "require_FractionOfSecondParser", "__commonJSMin", "exports", "_Parser", "_utils", "FractionOfSecondParser", "dateString", "token", "valueCallback", "value", "date", "_flags", "require_ISOTimezoneWithZParser", "__commonJSMin", "exports", "_index", "_index2", "_constants", "_Parser", "_utils", "ISOTimezoneWithZParser", "dateString", "token", "date", "flags", "value", "require_ISOTimezoneParser", "__commonJSMin", "exports", "_index", "_index2", "_constants", "_Parser", "_utils", "ISOTimezoneParser", "dateString", "token", "date", "flags", "value", "require_TimestampSecondsParser", "__commonJSMin", "exports", "_index", "_Parser", "_utils", "TimestampSecondsParser", "dateString", "date", "_flags", "value", "require_TimestampMillisecondsParser", "__commonJSMin", "exports", "_index", "_Parser", "_utils", "TimestampMillisecondsParser", "dateString", "date", "_flags", "value", "require_parsers", "__commonJSMin", "exports", "_EraParser", "_YearParser", "_LocalWeekYearParser", "_ISOWeekYearParser", "_ExtendedYearParser", "_QuarterParser", "_StandAloneQuarterParser", "_MonthParser", "_StandAloneMonthParser", "_LocalWeekParser", "_ISOWeekParser", "_DateParser", "_DayOfYearParser", "_DayParser", "_LocalDayParser", "_StandAloneLocalDayParser", "_ISODayParser", "_AMPMParser", "_AMPMMidnightParser", "_DayPeriodParser", "_Hour1to12Parser", "_Hour0to23Parser", "_Hour0To11Parser", "_Hour1To24Parser", "_MinuteParser", "_SecondParser", "_FractionOfSecondParser", "_ISOTimezoneWithZParser", "_ISOTimezoneParser", "_TimestampSecondsParser", "_TimestampMillisecondsParser", "parsers", "require_parse", "__commonJSMin", "exports", "_index2", "parse", "_index7", "_index", "_index3", "_index4", "_index5", "_index6", "_Setter", "formattingTokensRegExp", "longFormattingTokensRegExp", "escapedStringRegExp", "doubleQuoteRegExp", "notWhitespaceRegExp", "unescapedLatinCharacterRegExp", "dateStr", "formatStr", "referenceDate", "options", "invalidDate", "defaultOptions", "locale", "firstWeekContainsDate", "weekStartsOn", "subFnOptions", "setters", "tokens", "substring", "firstCharacter", "longFormatter", "usedTokens", "token", "parser", "incompatibleTokens", "incompatibleToken", "usedToken", "parseResult", "cleanEscapedString", "uniquePrioritySetters", "setter", "a", "b", "priority", "index", "array", "setterArray", "date", "flags", "result", "input", "require_isMatch", "__commonJSMin", "exports", "isMatch", "_index", "_index2", "dateStr", "formatStr", "options", "require_isMonday", "__commonJSMin", "exports", "isMonday", "_index", "date", "options", "require_isPast", "__commonJSMin", "exports", "isPast", "_index", "date", "require_startOfHour", "__commonJSMin", "exports", "startOfHour", "_index", "date", "options", "_date", "require_isSameHour", "__commonJSMin", "exports", "isSameHour", "_index", "_index2", "dateLeft", "dateRight", "options", "dateLeft_", "dateRight_", "require_isSameWeek", "__commonJSMin", "exports", "isSameWeek", "_index", "_index2", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "require_isSameISOWeek", "__commonJSMin", "exports", "isSameISOWeek", "_index", "laterDate", "earlierDate", "options", "require_isSameISOWeekYear", "__commonJSMin", "exports", "isSameISOWeekYear", "_index", "_index2", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "require_startOfMinute", "__commonJSMin", "exports", "startOfMinute", "_index", "date", "options", "date_", "require_isSameMinute", "__commonJSMin", "exports", "isSameMinute", "_index", "laterDate", "earlierDate", "require_isSameMonth", "__commonJSMin", "exports", "isSameMonth", "_index", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "require_isSameQuarter", "__commonJSMin", "exports", "isSameQuarter", "_index", "_index2", "laterDate", "earlierDate", "options", "dateLeft_", "dateRight_", "require_startOfSecond", "__commonJSMin", "exports", "startOfSecond", "_index", "date", "options", "date_", "require_isSameSecond", "__commonJSMin", "exports", "isSameSecond", "_index", "laterDate", "earlierDate", "require_isSameYear", "__commonJSMin", "exports", "isSameYear", "_index", "laterDate", "earlierDate", "options", "laterDate_", "earlierDate_", "require_isThisHour", "__commonJSMin", "exports", "isThisHour", "_index", "_index2", "_index3", "date", "options", "require_isThisISOWeek", "__commonJSMin", "exports", "isThisISOWeek", "_index", "_index2", "_index3", "date", "options", "require_isThisMinute", "__commonJSMin", "exports", "isThisMinute", "_index", "_index2", "date", "require_isThisMonth", "__commonJSMin", "exports", "isThisMonth", "_index", "_index2", "_index3", "date", "options", "require_isThisQuarter", "__commonJSMin", "exports", "isThisQuarter", "_index", "_index2", "_index3", "date", "options", "require_isThisSecond", "__commonJSMin", "exports", "isThisSecond", "_index", "_index2", "date", "require_isThisWeek", "__commonJSMin", "exports", "isThisWeek", "_index", "_index2", "_index3", "date", "options", "require_isThisYear", "__commonJSMin", "exports", "isThisYear", "_index", "_index2", "_index3", "date", "options", "require_isThursday", "__commonJSMin", "exports", "isThursday", "_index", "date", "options", "require_isToday", "__commonJSMin", "exports", "isToday", "_index", "_index2", "_index3", "date", "options", "require_isTomorrow", "__commonJSMin", "exports", "isTomorrow", "_index", "_index2", "_index3", "date", "options", "require_isTuesday", "__commonJSMin", "exports", "isTuesday", "_index", "date", "options", "require_isWednesday", "__commonJSMin", "exports", "isWednesday", "_index", "date", "options", "require_isWithinInterval", "__commonJSMin", "exports", "isWithinInterval", "_index", "date", "interval", "options", "time", "startTime", "endTime", "a", "b", "require_subDays", "__commonJSMin", "exports", "subDays", "_index", "date", "amount", "options", "require_isYesterday", "__commonJSMin", "exports", "isYesterday", "_index", "_index2", "_index3", "_index4", "date", "options", "require_lastDayOfDecade", "__commonJSMin", "exports", "lastDayOfDecade", "_index", "date", "options", "_date", "year", "decade", "require_lastDayOfWeek", "__commonJSMin", "exports", "lastDayOfWeek", "_index", "_index2", "date", "options", "defaultOptions", "weekStartsOn", "_date", "day", "diff", "require_lastDayOfISOWeek", "__commonJSMin", "exports", "lastDayOfISOWeek", "_index", "date", "options", "require_lastDayOfISOWeekYear", "__commonJSMin", "exports", "lastDayOfISOWeekYear", "_index", "_index2", "_index3", "date", "options", "year", "fourthOfJanuary", "date_", "require_lastDayOfQuarter", "__commonJSMin", "exports", "lastDayOfQuarter", "_index", "date", "options", "date_", "currentMonth", "month", "require_lastDayOfYear", "__commonJSMin", "exports", "lastDayOfYear", "_index", "date", "options", "date_", "year", "require_lightFormat", "__commonJSMin", "exports", "lightFormat", "_index", "_index2", "_index3", "formattingTokensRegExp", "escapedStringRegExp", "doubleQuoteRegExp", "unescapedLatinCharacterRegExp", "date", "formatStr", "date_", "tokens", "substring", "firstCharacter", "cleanEscapedString", "formatter", "input", "matches", "require_milliseconds", "__commonJSMin", "exports", "milliseconds", "_index", "years", "months", "weeks", "days", "hours", "minutes", "seconds", "totalDays", "totalSeconds", "require_millisecondsToHours", "__commonJSMin", "exports", "millisecondsToHours", "_index", "milliseconds", "hours", "require_millisecondsToMinutes", "__commonJSMin", "exports", "millisecondsToMinutes", "_index", "milliseconds", "minutes", "require_millisecondsToSeconds", "__commonJSMin", "exports", "millisecondsToSeconds", "_index", "milliseconds", "seconds", "require_minutesToHours", "__commonJSMin", "exports", "minutesToHours", "_index", "minutes", "hours", "require_minutesToMilliseconds", "__commonJSMin", "exports", "minutesToMilliseconds", "_index", "minutes", "require_minutesToSeconds", "__commonJSMin", "exports", "minutesToSeconds", "_index", "minutes", "require_monthsToQuarters", "__commonJSMin", "exports", "monthsToQuarters", "_index", "months", "quarters", "require_monthsToYears", "__commonJSMin", "exports", "monthsToYears", "_index", "months", "years", "require_nextDay", "__commonJSMin", "exports", "nextDay", "_index", "_index2", "date", "day", "options", "delta", "require_nextFriday", "__commonJSMin", "exports", "nextFriday", "_index", "date", "options", "require_nextMonday", "__commonJSMin", "exports", "nextMonday", "_index", "date", "options", "require_nextSaturday", "__commonJSMin", "exports", "nextSaturday", "_index", "date", "options", "require_nextSunday", "__commonJSMin", "exports", "nextSunday", "_index", "date", "options", "require_nextThursday", "__commonJSMin", "exports", "nextThursday", "_index", "date", "options", "require_nextTuesday", "__commonJSMin", "exports", "nextTuesday", "_index", "date", "options", "require_nextWednesday", "__commonJSMin", "exports", "nextWednesday", "_index", "date", "options", "require_parseISO", "__commonJSMin", "exports", "parseISO", "_index", "_index2", "_index3", "argument", "options", "invalidDate", "additionalDigits", "dateStrings", "splitDateString", "date", "parseYearResult", "parseYear", "parseDate", "timestamp", "time", "offset", "parseTime", "parseTimezone", "tmpDate", "result", "patterns", "dateRegex", "timeRegex", "timezoneRegex", "dateString", "array", "timeString", "token", "regex", "captures", "year", "century", "isWeekDate", "dayOfYear", "parseDateUnit", "month", "day", "week", "dayOfWeek", "validateWeekDate", "dayOfISOWeekYear", "validateDate", "validateDayOfYearDate", "value", "hours", "parseTimeUnit", "minutes", "seconds", "validateTime", "timezoneString", "sign", "validateTimezone", "isoWeekYear", "fourthOfJanuaryDay", "diff", "daysInMonths", "isLeapYearIndex", "_year", "_hours", "require_parseJSON", "__commonJSMin", "exports", "parseJSON", "_index", "dateStr", "options", "parts", "require_previousDay", "__commonJSMin", "exports", "previousDay", "_index", "_index2", "date", "day", "options", "delta", "require_previousFriday", "__commonJSMin", "exports", "previousFriday", "_index", "date", "options", "require_previousMonday", "__commonJSMin", "exports", "previousMonday", "_index", "date", "options", "require_previousSaturday", "__commonJSMin", "exports", "previousSaturday", "_index", "date", "options", "require_previousSunday", "__commonJSMin", "exports", "previousSunday", "_index", "date", "options", "require_previousThursday", "__commonJSMin", "exports", "previousThursday", "_index", "date", "options", "require_previousTuesday", "__commonJSMin", "exports", "previousTuesday", "_index", "date", "options", "require_previousWednesday", "__commonJSMin", "exports", "previousWednesday", "_index", "date", "options", "require_quartersToMonths", "__commonJSMin", "exports", "quartersToMonths", "_index", "quarters", "require_quartersToYears", "__commonJSMin", "exports", "quartersToYears", "_index", "quarters", "years", "require_roundToNearestHours", "__commonJSMin", "exports", "roundToNearestHours", "_index", "_index2", "_index3", "date", "options", "nearestTo", "date_", "fractionalMinutes", "fractionalSeconds", "fractionalMilliseconds", "hours", "method", "roundedHours", "require_roundToNearestMinutes", "__commonJSMin", "exports", "roundToNearestMinutes", "_index", "_index2", "_index3", "date", "options", "nearestTo", "date_", "fractionalSeconds", "fractionalMilliseconds", "minutes", "method", "roundedMinutes", "require_secondsToHours", "__commonJSMin", "exports", "secondsToHours", "_index", "seconds", "hours", "require_secondsToMilliseconds", "__commonJSMin", "exports", "secondsToMilliseconds", "_index", "seconds", "require_secondsToMinutes", "__commonJSMin", "exports", "secondsToMinutes", "_index", "seconds", "minutes", "require_setMonth", "__commonJSMin", "exports", "setMonth", "_index", "_index2", "_index3", "date", "month", "options", "_date", "year", "day", "midMonth", "daysInMonth", "require_set", "__commonJSMin", "exports", "set", "_index", "_index2", "_index3", "date", "values", "options", "_date", "require_setDate", "__commonJSMin", "exports", "setDate", "_index", "date", "dayOfMonth", "options", "_date", "require_setDayOfYear", "__commonJSMin", "exports", "setDayOfYear", "_index", "date", "dayOfYear", "options", "date_", "require_setDefaultOptions", "__commonJSMin", "exports", "setDefaultOptions", "_index", "options", "result", "defaultOptions", "property", "require_setHours", "__commonJSMin", "exports", "setHours", "_index", "date", "hours", "options", "_date", "require_setMilliseconds", "__commonJSMin", "exports", "setMilliseconds", "_index", "date", "milliseconds", "options", "_date", "require_setMinutes", "__commonJSMin", "exports", "setMinutes", "_index", "date", "minutes", "options", "date_", "require_setQuarter", "__commonJSMin", "exports", "setQuarter", "_index", "_index2", "date", "quarter", "options", "date_", "oldQuarter", "diff", "require_setSeconds", "__commonJSMin", "exports", "setSeconds", "_index", "date", "seconds", "options", "_date", "require_setWeekYear", "__commonJSMin", "exports", "setWeekYear", "_index", "_index2", "_index3", "_index4", "_index5", "date", "weekYear", "options", "defaultOptions", "firstWeekContainsDate", "diff", "firstWeek", "date_", "require_setYear", "__commonJSMin", "exports", "setYear", "_index", "_index2", "date", "year", "options", "date_", "require_startOfDecade", "__commonJSMin", "exports", "startOfDecade", "_index", "date", "options", "_date", "year", "decade", "require_startOfToday", "__commonJSMin", "exports", "startOfToday", "_index", "options", "require_startOfTomorrow", "__commonJSMin", "exports", "startOfTomorrow", "_index", "_index2", "options", "now", "year", "month", "day", "date", "require_startOfYesterday", "__commonJSMin", "exports", "startOfYesterday", "_index", "options", "now", "year", "month", "day", "date", "require_subMonths", "__commonJSMin", "exports", "subMonths", "_index", "date", "amount", "options", "require_sub", "__commonJSMin", "exports", "sub", "_index", "_index2", "_index3", "date", "duration", "options", "years", "months", "weeks", "days", "hours", "minutes", "seconds", "withoutMonths", "withoutDays", "minutesToSub", "msToSub", "require_subBusinessDays", "__commonJSMin", "exports", "subBusinessDays", "_index", "date", "amount", "options", "require_subHours", "__commonJSMin", "exports", "subHours", "_index", "date", "amount", "options", "require_subMilliseconds", "__commonJSMin", "exports", "subMilliseconds", "_index", "date", "amount", "options", "require_subMinutes", "__commonJSMin", "exports", "subMinutes", "_index", "date", "amount", "options", "require_subQuarters", "__commonJSMin", "exports", "subQuarters", "_index", "date", "amount", "options", "require_subSeconds", "__commonJSMin", "exports", "subSeconds", "_index", "date", "amount", "options", "require_subWeeks", "__commonJSMin", "exports", "subWeeks", "_index", "date", "amount", "options", "require_subYears", "__commonJSMin", "exports", "subYears", "_index", "date", "amount", "options", "require_weeksToDays", "__commonJSMin", "exports", "weeksToDays", "_index", "weeks", "require_yearsToDays", "__commonJSMin", "exports", "yearsToDays", "_index", "years", "require_yearsToMonths", "__commonJSMin", "exports", "yearsToMonths", "_index", "years", "require_yearsToQuarters", "__commonJSMin", "exports", "yearsToQuarters", "_index", "years", "require_date_fns", "__commonJSMin", "exports", "_index", "key", "_index2", "_index3", "_index4", "_index5", "_index6", "_index7", "_index8", "_index9", "_index10", "_index11", "_index12", "_index13", "_index14", "_index15", "_index16", "_index17", "_index18", "_index19", "_index20", "_index21", "_index22", "_index23", "_index24", "_index25", "_index26", "_index27", "_index28", "_index29", "_index30", "_index31", "_index32", "_index33", "_index34", "_index35", "_index36", "_index37", "_index38", "_index39", "_index40", "_index41", "_index42", "_index43", "_index44", "_index45", "_index46", "_index47", "_index48", "_index49", "_index50", "_index51", "_index52", "_index53", "_index54", "_index55", "_index56", "_index57", "_index58", "_index59", "_index60", "_index61", "_index62", "_index63", "_index64", "_index65", "_index66", "_index67", "_index68", "_index69", "_index70", "_index71", "_index72", "_index73", "_index74", "_index75", "_index76", "_index77", "_index78", "_index79", "_index80", "_index81", "_index82", "_index83", "_index84", "_index85", "_index86", "_index87", "_index88", "_index89", "_index90", "_index91", "_index92", "_index93", "_index94", "_index95", "_index96", "_index97", "_index98", "_index99", "_index100", "_index101", "_index102", "_index103", "_index104", "_index105", "_index106", "_index107", "_index108", "_index109", "_index110", "_index111", "_index112", "_index113", "_index114", "_index115", "_index116", "_index117", "_index118", "_index119", "_index120", "_index121", "_index122", "_index123", "_index124", "_index125", "_index126", "_index127", "_index128", "_index129", "_index130", "_index131", "_index132", "_index133", "_index134", "_index135", "_index136", "_index137", "_index138", "_index139", "_index140", "_index141", "_index142", "_index143", "_index144", "_index145", "_index146", "_index147", "_index148", "_index149", "_index150", "_index151", "_index152", "_index153", "_index154", "_index155", "_index156", "_index157", "_index158", "_index159", "_index160", "_index161", "_index162", "_index163", "_index164", "_index165", "_index166", "_index167", "_index168", "_index169", "_index170", "_index171", "_index172", "_index173", "_index174", "_index175", "_index176", "_index177", "_index178", "_index179", "_index180", "_index181", "_index182", "_index183", "_index184", "_index185", "_index186", "_index187", "_index188", "_index189", "_index190", "_index191", "_index192", "_index193", "_index194", "_index195", "_index196", "_index197", "_index198", "_index199", "_index200", "_index201", "_index202", "_index203", "_index204", "_index205", "_index206", "_index207", "_index208", "_index209", "_index210", "_index211", "_index212", "_index213", "_index214", "_index215", "_index216", "_index217", "_index218", "_index219", "_index220", "_index221", "_index222", "_index223", "_index224", "_index225", "_index226", "_index227", "_index228", "_index229", "_index230", "_index231", "_index232", "_index233", "_index234", "_index235", "_index236", "_index237", "_index238", "_index239", "_index240", "_index241", "_index242", "_index243", "_index244", "_index245", "require_utils", "__commonJSMin", "exports", "module", "readdir", "stat", "unlink", "symlink", "lstat", "readlink", "dirname", "join", "format", "addDays", "addHours", "parse", "isValid", "parseSize", "size", "multiplier", "match", "unit", "parseFrequency", "frequency", "today", "start", "getNextDay", "getNextHour", "getNextCustom", "validateLimitOptions", "limit", "time", "getNext", "getFileName", "fileVal", "buildFileName", "date", "lastNumber", "extension", "dateStr", "extensionStr", "identifyLogFile", "checkedFileName", "dateFormat", "baseFileNameStr", "checkFileNameSegments", "expectedSegmentCount", "chkExtension", "chkFileNumber", "fileNumber", "fileTime", "d", "getFileSize", "filePath", "detectLastNumber", "fileName", "readFileTrailingNumbers", "a", "b", "folder", "numbers", "file", "isMatchingTime", "number", "extractTrailingNumber", "extractFileName", "birthtimeMs", "removeOldFiles", "count", "removeOtherLogFiles", "baseFile", "createdFileNames", "newFileName", "files", "pathSegments", "fileEntry", "f", "i", "j", "filesToRemove", "checkSymlink", "linkPath", "stats", "existingTarget", "createSymlink", "validateDateFormat", "formatStr", "parseDate", "frequencySpec", "parseStart", "require_pino_roll", "__commonJSMin", "exports", "module", "SonicBoom", "buildFileName", "removeOldFiles", "createSymlink", "detectLastNumber", "parseSize", "parseFrequency", "getNext", "getFileSize", "validateLimitOptions", "parseDate", "validateDateFormat", "file", "size", "frequency", "extension", "limit", "symlink", "dateFormat", "opts", "frequencySpec", "date", "number", "fileName", "createdFileNames", "currentSize", "maxSize", "destination", "rollTimeout", "scheduleRoll", "writtenSize", "roll", "prevDate"] +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-worker.mjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-worker.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e0aa0af7ef5bd14d0d9c582cabe2b0b8f7c04f94 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-worker.mjs @@ -0,0 +1,104 @@ +var j=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var v=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var xe=v((hu,vt)=>{"use strict";var Z=e=>e&&typeof e.message=="string",Oe=e=>{if(!e)return;let t=e.cause;if(typeof t=="function"){let r=e.cause();return Z(r)?r:void 0}else return Z(t)?t:void 0},_t=(e,t)=>{if(!Z(e))return"";let r=e.stack||"";if(t.has(e))return r+` +causes have become circular...`;let n=Oe(e);return n?(t.add(e),r+` +caused by: `+_t(n,t)):r},Xn=e=>_t(e,new Set),Et=(e,t,r)=>{if(!Z(e))return"";let n=r?"":e.message||"";if(t.has(e))return n+": ...";let i=Oe(e);if(i){t.add(e);let o=typeof e.cause=="function";return n+(o?"":": ")+Et(i,t,o)}else return n},Yn=e=>Et(e,new Set);vt.exports={isErrorLike:Z,getErrorCause:Oe,stackWithCauses:Xn,messageWithCauses:Yn}});var Le=v((du,xt)=>{"use strict";var Qn=Symbol("circular-ref-tag"),ie=Symbol("pino-raw-err-ref"),Ot=Object.create({},{type:{enumerable:!0,writable:!0,value:void 0},message:{enumerable:!0,writable:!0,value:void 0},stack:{enumerable:!0,writable:!0,value:void 0},aggregateErrors:{enumerable:!0,writable:!0,value:void 0},raw:{enumerable:!1,get:function(){return this[ie]},set:function(e){this[ie]=e}}});Object.defineProperty(Ot,ie,{writable:!0,value:{}});xt.exports={pinoErrProto:Ot,pinoErrorSymbols:{seen:Qn,rawSymbol:ie}}});var jt=v((yu,$t)=>{"use strict";$t.exports=je;var{messageWithCauses:Zn,stackWithCauses:ei,isErrorLike:Lt}=xe(),{pinoErrProto:ti,pinoErrorSymbols:ri}=Le(),{seen:$e}=ri,{toString:ni}=Object.prototype;function je(e){if(!Lt(e))return e;e[$e]=void 0;let t=Object.create(ti);t.type=ni.call(e.constructor)==="[object Function]"?e.constructor.name:e.name,t.message=Zn(e),t.stack=ei(e),Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(r=>je(r)));for(let r in e)if(t[r]===void 0){let n=e[r];Lt(n)?r!=="cause"&&!Object.prototype.hasOwnProperty.call(n,$e)&&(t[r]=je(n)):t[r]=n}return delete e[$e],t.raw=e,t}});var Tt=v((mu,At)=>{"use strict";At.exports=oe;var{isErrorLike:Ae}=xe(),{pinoErrProto:ii,pinoErrorSymbols:si}=Le(),{seen:se}=si,{toString:oi}=Object.prototype;function oe(e){if(!Ae(e))return e;e[se]=void 0;let t=Object.create(ii);t.type=oi.call(e.constructor)==="[object Function]"?e.constructor.name:e.name,t.message=e.message,t.stack=e.stack,Array.isArray(e.errors)&&(t.aggregateErrors=e.errors.map(r=>oe(r))),Ae(e.cause)&&!Object.prototype.hasOwnProperty.call(e.cause,se)&&(t.cause=oe(e.cause));for(let r in e)if(t[r]===void 0){let n=e[r];Ae(n)?Object.prototype.hasOwnProperty.call(n,se)||(t[r]=oe(n)):t[r]=n}return delete e[se],t.raw=e,t}});var qt=v((gu,Bt)=>{"use strict";Bt.exports={mapHttpRequest:li,reqSerializer:Rt};var Te=Symbol("pino-raw-req-ref"),kt=Object.create({},{id:{enumerable:!0,writable:!0,value:""},method:{enumerable:!0,writable:!0,value:""},url:{enumerable:!0,writable:!0,value:""},query:{enumerable:!0,writable:!0,value:""},params:{enumerable:!0,writable:!0,value:""},headers:{enumerable:!0,writable:!0,value:{}},remoteAddress:{enumerable:!0,writable:!0,value:""},remotePort:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[Te]},set:function(e){this[Te]=e}}});Object.defineProperty(kt,Te,{writable:!0,value:{}});function Rt(e){let t=e.info||e.socket,r=Object.create(kt);if(r.id=typeof e.id=="function"?e.id():e.id||(e.info?e.info.id:void 0),r.method=e.method,e.originalUrl)r.url=e.originalUrl;else{let n=e.path;r.url=typeof n=="string"?n:e.url?e.url.path||e.url:void 0}return e.query&&(r.query=e.query),e.params&&(r.params=e.params),r.headers=e.headers,r.remoteAddress=t&&t.remoteAddress,r.remotePort=t&&t.remotePort,r.raw=e.raw||e,r}function li(e){return{req:Rt(e)}}});var Nt=v((pu,Dt)=>{"use strict";Dt.exports={mapHttpResponse:fi,resSerializer:It};var ke=Symbol("pino-raw-res-ref"),Ct=Object.create({},{statusCode:{enumerable:!0,writable:!0,value:0},headers:{enumerable:!0,writable:!0,value:""},raw:{enumerable:!1,get:function(){return this[ke]},set:function(e){this[ke]=e}}});Object.defineProperty(Ct,ke,{writable:!0,value:{}});function It(e){let t=Object.create(Ct);return t.statusCode=e.headersSent?e.statusCode:null,t.headers=e.getHeaders?e.getHeaders():e._headers,t.raw=e,t}function fi(e){return{res:It(e)}}});var Be=v((bu,Pt)=>{"use strict";var Re=jt(),ui=Tt(),le=qt(),fe=Nt();Pt.exports={err:Re,errWithCause:ui,mapHttpRequest:le.mapHttpRequest,mapHttpResponse:fe.mapHttpResponse,req:le.reqSerializer,res:fe.resSerializer,wrapErrorSerializer:function(t){return t===Re?t:function(n){return t(Re(n))}},wrapRequestSerializer:function(t){return t===le.reqSerializer?t:function(n){return t(le.reqSerializer(n))}},wrapResponseSerializer:function(t){return t===fe.resSerializer?t:function(n){return t(fe.resSerializer(n))}}}});var qe=v((wu,Mt)=>{"use strict";function ci(e,t){return t}Mt.exports=function(){let t=Error.prepareStackTrace;Error.prepareStackTrace=ci;let r=new Error().stack;if(Error.prepareStackTrace=t,!Array.isArray(r))return;let n=r.slice(2),i=[];for(let o of n)o&&i.push(o.getFileName());return i}});var zt=v((Su,Wt)=>{"use strict";Wt.exports=ai;function ai(e={}){let{ERR_PATHS_MUST_BE_STRINGS:t=()=>"fast-redact - Paths must be (non-empty) strings",ERR_INVALID_PATH:r=n=>`fast-redact \u2013 Invalid path (${n})`}=e;return function({paths:i}){i.forEach(o=>{if(typeof o!="string")throw Error(t());try{if(/〇/.test(o))throw Error();let a=(o[0]==="["?"":".")+o.replace(/^\*/,"\u3007").replace(/\.\*/g,".\u3007").replace(/\[\*\]/g,"[\u3007]");if(/\n|\r|;/.test(a)||/\/\*/.test(a))throw Error();Function(` + 'use strict' + const o = new Proxy({}, { get: () => o, set: () => { throw Error() } }); + const \u3007 = null; + o${a} + if ([o${a}].length !== 1) throw Error()`)()}catch{throw Error(r(o))}})}}});var ue=v((_u,Ft)=>{"use strict";Ft.exports=/[^.[\]]+|\[((?:.)*?)\]/g});var Vt=v((Eu,Kt)=>{"use strict";var hi=ue();Kt.exports=di;function di({paths:e}){let t=[];var r=0;let n=e.reduce(function(i,o,a){var f=o.match(hi).map(u=>u.replace(/'|"|`/g,""));let c=o[0]==="[";f=f.map(u=>u[0]==="["?u.substr(1,u.length-2):u);let h=f.indexOf("*");if(h>-1){let u=f.slice(0,h),l=u.join("."),p=f.slice(h+1,f.length),d=p.length>0;r++,t.push({before:u,beforeStr:l,after:p,nested:d})}else i[o]={path:f,val:void 0,precensored:!1,circle:"",escPath:JSON.stringify(o),leadingBracket:c};return i},{});return{wildcards:t,wcLen:r,secret:n}}});var Jt=v((vu,Ut)=>{"use strict";var yi=ue();Ut.exports=mi;function mi({secret:e,serialize:t,wcLen:r,strict:n,isCensorFct:i,censorFctTakesPath:o},a){let f=Function("o",` + if (typeof o !== 'object' || o == null) { + ${wi(n,t)} + } + const { censor, secret } = this + const originalSecret = {} + const secretKeys = Object.keys(secret) + for (var i = 0; i < secretKeys.length; i++) { + originalSecret[secretKeys[i]] = secret[secretKeys[i]] + } + + ${gi(e,i,o)} + this.compileRestore() + ${pi(r>0,i,o)} + this.secret = originalSecret + ${bi(t)} + `).bind(a);return f.state=a,t===!1&&(f.restore=c=>a.restore(c)),f}function gi(e,t,r){return Object.keys(e).map(n=>{let{escPath:i,leadingBracket:o,path:a}=e[n],f=o?1:0,c=o?"":".",h=[];for(var u;(u=yi.exec(n))!==null;){let[,s]=u,{index:g,input:m}=u;g>f&&h.push(m.substring(0,g-(s?0:1)))}var l=h.map(s=>`o${c}${s}`).join(" && ");l.length===0?l+=`o${c}${n} != null`:l+=` && o${c}${n} != null`;let p=` + switch (true) { + ${h.reverse().map(s=>` + case o${c}${s} === censor: + secret[${i}].circle = ${JSON.stringify(s)} + break + `).join(` +`)} + } + `,d=r?`val, ${JSON.stringify(a)}`:"val";return` + if (${l}) { + const val = o${c}${n} + if (val === censor) { + secret[${i}].precensored = true + } else { + secret[${i}].val = val + o${c}${n} = ${t?`censor(${d})`:"censor"} + ${p} + } + } + `}).join(` +`)}function pi(e,t,r){return e===!0?` + { + const { wildcards, wcLen, groupRedact, nestedRedact } = this + for (var i = 0; i < wcLen; i++) { + const { before, beforeStr, after, nested } = wildcards[i] + if (nested === true) { + secret[beforeStr] = secret[beforeStr] || [] + nestedRedact(secret[beforeStr], o, before, after, censor, ${t}, ${r}) + } else secret[beforeStr] = groupRedact(o, before, censor, ${t}, ${r}) + } + } + `:""}function bi(e){return e===!1?"return o":` + var s = this.serialize(o) + this.restore(o) + return s + `}function wi(e,t){return e===!0?"throw Error('fast-redact: primitives cannot be redacted')":t===!1?"return o":"return this.serialize(o)"}});var Ie=v((Ou,Xt)=>{"use strict";Xt.exports={groupRedact:_i,groupRestore:Si,nestedRedact:vi,nestedRestore:Ei};function Si({keys:e,values:t,target:r}){if(r==null||typeof r=="string")return;let n=e.length;for(var i=0;i0;a--)o=o[n[a]];o[n[0]]=i}}function vi(e,t,r,n,i,o,a){let f=Gt(t,r);if(f==null)return;let c=Object.keys(f),h=c.length;for(var u=0;u{"use strict";var{groupRestore:Li,nestedRestore:$i}=Ie();Yt.exports=ji;function ji(){return function(){if(this.restore){this.restore.state.secret=this.secret;return}let{secret:t,wcLen:r}=this,n=Object.keys(t),i=Ai(t,n),o=r>0,a=o?{secret:t,groupRestore:Li,nestedRestore:$i}:{secret:t};this.restore=Function("o",Ti(i,n,o)).bind(a),this.restore.state=a}}function Ai(e,t){return t.map(r=>{let{circle:n,escPath:i,leadingBracket:o}=e[r],f=n?`o.${n} = secret[${i}].val`:`o${o?"":"."}${r} = secret[${i}].val`,c=`secret[${i}].val = undefined`;return` + if (secret[${i}].val !== undefined) { + try { ${f} } catch (e) {} + ${c} + } + `}).join("")}function Ti(e,t,r){return` + const secret = this.secret + ${r===!0?` + const keys = Object.keys(secret) + const len = keys.length + for (var i = len - 1; i >= ${t.length}; i--) { + const k = keys[i] + const o = secret[k] + if (o) { + if (o.flat === true) this.groupRestore(o) + else this.nestedRestore(o) + secret[k] = null + } + } + `:""} + ${e} + return o + `}});var er=v((Lu,Zt)=>{"use strict";Zt.exports=ki;function ki(e){let{secret:t,censor:r,compileRestore:n,serialize:i,groupRedact:o,nestedRedact:a,wildcards:f,wcLen:c}=e,h=[{secret:t,censor:r,compileRestore:n}];return i!==!1&&h.push({serialize:i}),c>0&&h.push({groupRedact:o,nestedRedact:a,wildcards:f,wcLen:c}),Object.assign(...h)}});var nr=v(($u,rr)=>{"use strict";var tr=zt(),Ri=Vt(),Bi=Jt(),qi=Qt(),{groupRedact:Ci,nestedRedact:Ii}=Ie(),Di=er(),Ni=ue(),Pi=tr(),De=e=>e;De.restore=De;var Mi="[REDACTED]";Ne.rx=Ni;Ne.validator=tr;rr.exports=Ne;function Ne(e={}){let t=Array.from(new Set(e.paths||[])),r="serialize"in e&&(e.serialize===!1||typeof e.serialize=="function")?e.serialize:JSON.stringify,n=e.remove;if(n===!0&&r!==JSON.stringify)throw Error("fast-redact \u2013 remove option may only be set when serializer is JSON.stringify");let i=n===!0?void 0:"censor"in e?e.censor:Mi,o=typeof i=="function",a=o&&i.length>1;if(t.length===0)return r||De;Pi({paths:t,serialize:r,censor:i});let{wildcards:f,wcLen:c,secret:h}=Ri({paths:t,censor:i}),u=qi(),l="strict"in e?e.strict:!0;return Bi({secret:h,wcLen:c,serialize:r,strict:l,isCensorFct:o,censorFctTakesPath:a},Di({secret:h,censor:i,compileRestore:u,serialize:r,groupRedact:Ci,nestedRedact:Ii,wildcards:f,wcLen:c}))}});var X=v((ju,ir)=>{"use strict";var Wi=Symbol("pino.setLevel"),zi=Symbol("pino.getLevel"),Fi=Symbol("pino.levelVal"),Ki=Symbol("pino.levelComp"),Vi=Symbol("pino.useLevelLabels"),Ui=Symbol("pino.useOnlyCustomLevels"),Ji=Symbol("pino.mixin"),Gi=Symbol("pino.lsCache"),Hi=Symbol("pino.chindings"),Xi=Symbol("pino.asJson"),Yi=Symbol("pino.write"),Qi=Symbol("pino.redactFmt"),Zi=Symbol("pino.time"),es=Symbol("pino.timeSliceIndex"),ts=Symbol("pino.stream"),rs=Symbol("pino.stringify"),ns=Symbol("pino.stringifySafe"),is=Symbol("pino.stringifiers"),ss=Symbol("pino.end"),os=Symbol("pino.formatOpts"),ls=Symbol("pino.messageKey"),fs=Symbol("pino.errorKey"),us=Symbol("pino.nestedKey"),cs=Symbol("pino.nestedKeyStr"),as=Symbol("pino.mixinMergeStrategy"),hs=Symbol("pino.msgPrefix"),ds=Symbol("pino.wildcardFirst"),ys=Symbol.for("pino.serializers"),ms=Symbol.for("pino.formatters"),gs=Symbol.for("pino.hooks"),ps=Symbol.for("pino.metadata");ir.exports={setLevelSym:Wi,getLevelSym:zi,levelValSym:Fi,levelCompSym:Ki,useLevelLabelsSym:Vi,mixinSym:Ji,lsCacheSym:Gi,chindingsSym:Hi,asJsonSym:Xi,writeSym:Yi,serializersSym:ys,redactFmtSym:Qi,timeSym:Zi,timeSliceIndexSym:es,streamSym:ts,stringifySym:rs,stringifySafeSym:ns,stringifiersSym:is,endSym:ss,formatOptsSym:os,messageKeySym:ls,errorKeySym:fs,nestedKeySym:us,wildcardFirstSym:ds,needsMetadataGsym:ps,useOnlyCustomLevelsSym:Ui,formattersSym:ms,hooksSym:gs,nestedKeyStrSym:cs,mixinMergeStrategySym:as,msgPrefixSym:hs}});var We=v((Au,fr)=>{"use strict";var Me=nr(),{redactFmtSym:bs,wildcardFirstSym:ce}=X(),{rx:Pe,validator:ws}=Me,sr=ws({ERR_PATHS_MUST_BE_STRINGS:()=>"pino \u2013 redacted paths must be strings",ERR_INVALID_PATH:e=>`pino \u2013 redact paths array contains an invalid path (${e})`}),or="[Redacted]",lr=!1;function Ss(e,t){let{paths:r,censor:n}=_s(e),i=r.reduce((f,c)=>{Pe.lastIndex=0;let h=Pe.exec(c),u=Pe.exec(c),l=h[1]!==void 0?h[1].replace(/^(?:"|'|`)(.*)(?:"|'|`)$/,"$1"):h[0];if(l==="*"&&(l=ce),u===null)return f[l]=null,f;if(f[l]===null)return f;let{index:p}=u,d=`${c.substr(p,c.length-1)}`;return f[l]=f[l]||[],l!==ce&&f[l].length===0&&f[l].push(...f[ce]||[]),l===ce&&Object.keys(f).forEach(function(s){f[s]&&f[s].push(d)}),f[l].push(d),f},{}),o={[bs]:Me({paths:r,censor:n,serialize:t,strict:lr})},a=(...f)=>t(typeof n=="function"?n(...f):n);return[...Object.keys(i),...Object.getOwnPropertySymbols(i)].reduce((f,c)=>{if(i[c]===null)f[c]=h=>a(h,[c]);else{let h=typeof n=="function"?(u,l)=>n(u,[c,...l]):n;f[c]=Me({paths:i[c],censor:h,serialize:t,strict:lr})}return f},o)}function _s(e){if(Array.isArray(e))return e={paths:e,censor:or},sr(e),e;let{paths:t,censor:r=or,remove:n}=e;if(Array.isArray(t)===!1)throw Error("pino \u2013 redact must contain an array of strings");return n===!0&&(r=void 0),sr({paths:t,censor:r}),{paths:t,censor:r}}fr.exports=Ss});var cr=v((Tu,ur)=>{"use strict";var Es=()=>"",vs=()=>`,"time":${Date.now()}`,Os=()=>`,"time":${Math.round(Date.now()/1e3)}`,xs=()=>`,"time":"${new Date(Date.now()).toISOString()}"`;ur.exports={nullTime:Es,epochTime:vs,unixTime:Os,isoTime:xs}});var hr=v((ku,ar)=>{"use strict";function Ls(e){try{return JSON.stringify(e)}catch{return'"[Circular]"'}}ar.exports=$s;function $s(e,t,r){var n=r&&r.stringify||Ls,i=1;if(typeof e=="object"&&e!==null){var o=t.length+i;if(o===1)return e;var a=new Array(o);a[0]=n(e);for(var f=1;f-1?l:0,e.charCodeAt(d+1)){case 100:case 102:if(u>=c||t[u]==null)break;l=c||t[u]==null)break;l=c||t[u]===void 0)break;l",l=d+2,d++;break}h+=n(t[u]),l=d+2,d++;break;case 115:if(u>=c)break;l{"use strict";if(typeof SharedArrayBuffer<"u"&&typeof Atomics<"u"){let t=function(r){if((r>0&&r<1/0)===!1)throw typeof r!="number"&&typeof r!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");Atomics.wait(e,0,0,Number(r))},e=new Int32Array(new SharedArrayBuffer(4));ze.exports=t}else{let e=function(t){if((t>0&&t<1/0)===!1)throw typeof t!="number"&&typeof t!="bigint"?TypeError("sleep: ms must be a number"):RangeError("sleep: ms must be a number that is greater than 0 but less than Infinity");let n=Date.now()+Number(t);for(;n>Date.now(););};ze.exports=e}});var Sr=v((Bu,wr)=>{"use strict";var T=j("fs"),js=j("events"),As=j("util").inherits,dr=j("path"),Ve=Fe(),Ts=j("assert"),ae=100,he=Buffer.allocUnsafe(0),ks=16*1024,yr="buffer",mr="utf8",[Rs,Bs]=(process.versions.node||"0.0").split(".").map(Number),qs=Rs>=22&&Bs>=7;function gr(e,t){t._opening=!0,t._writing=!0,t._asyncDrainScheduled=!1;function r(o,a){if(o){t._reopening=!1,t._writing=!1,t._opening=!1,t.sync?process.nextTick(()=>{t.listenerCount("error")>0&&t.emit("error",o)}):t.emit("error",o);return}let f=t._reopening;t.fd=a,t.file=e,t._reopening=!1,t._opening=!1,t._writing=!1,t.sync?process.nextTick(()=>t.emit("ready")):t.emit("ready"),!t.destroyed&&(!t._writing&&t._len>t.minLength||t._flushPending?t._actualWrite():f&&process.nextTick(()=>t.emit("drain")))}let n=t.append?"a":"w",i=t.mode;if(t.sync)try{t.mkdir&&T.mkdirSync(dr.dirname(e),{recursive:!0});let o=T.openSync(e,n,i);r(null,o)}catch(o){throw r(o),o}else t.mkdir?T.mkdir(dr.dirname(e),{recursive:!0},o=>{if(o)return r(o);T.open(e,n,i,r)}):T.open(e,n,i,r)}function D(e){if(!(this instanceof D))return new D(e);let{fd:t,dest:r,minLength:n,maxLength:i,maxWrite:o,periodicFlush:a,sync:f,append:c=!0,mkdir:h,retryEAGAIN:u,fsync:l,contentMode:p,mode:d}=e||{};t=t||r,this._len=0,this.fd=-1,this._bufs=[],this._lens=[],this._writing=!1,this._ending=!1,this._reopening=!1,this._asyncDrainScheduled=!1,this._flushPending=!1,this._hwm=Math.max(n||0,16387),this.file=null,this.destroyed=!1,this.minLength=n||0,this.maxLength=i||0,this.maxWrite=o||ks,this._periodicFlush=a||0,this._periodicFlushTimer=void 0,this.sync=f||!1,this.writable=!0,this._fsync=l||!1,this.append=c||!1,this.mode=d,this.retryEAGAIN=u||(()=>!0),this.mkdir=h||!1;let s,g;if(p===yr)this._writingBuf=he,this.write=Ds,this.flush=Ps,this.flushSync=Ws,this._actualWrite=Fs,s=()=>T.writeSync(this.fd,this._writingBuf),g=()=>T.write(this.fd,this._writingBuf,this.release);else if(p===void 0||p===mr)this._writingBuf="",this.write=Is,this.flush=Ns,this.flushSync=Ms,this._actualWrite=zs,s=()=>T.writeSync(this.fd,this._writingBuf,"utf8"),g=()=>T.write(this.fd,this._writingBuf,"utf8",this.release);else throw new Error(`SonicBoom supports "${mr}" and "${yr}", but passed ${p}`);if(typeof t=="number")this.fd=t,process.nextTick(()=>this.emit("ready"));else if(typeof t=="string")gr(t,this);else throw new Error("SonicBoom supports only file descriptors and files");if(this.minLength>=this.maxWrite)throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`);this.release=(m,S)=>{if(m){if((m.code==="EAGAIN"||m.code==="EBUSY")&&this.retryEAGAIN(m,this._writingBuf.length,this._len-this._writingBuf.length))if(this.sync)try{Ve(ae),this.release(void 0,0)}catch(_){this.release(_)}else setTimeout(g,ae);else this._writing=!1,this.emit("error",m);return}this.emit("write",S);let b=Ke(this._writingBuf,this._len,S);if(this._len=b.len,this._writingBuf=b.writingBuf,this._writingBuf.length){if(!this.sync){g();return}try{do{let _=s(),O=Ke(this._writingBuf,this._len,_);this._len=O.len,this._writingBuf=O.writingBuf}while(this._writingBuf.length)}catch(_){this.release(_);return}}this._fsync&&T.fsyncSync(this.fd);let w=this._len;this._reopening?(this._writing=!1,this._reopening=!1,this.reopen()):w>this.minLength?this._actualWrite():this._ending?w>0?this._actualWrite():(this._writing=!1,de(this)):(this._writing=!1,this.sync?this._asyncDrainScheduled||(this._asyncDrainScheduled=!0,process.nextTick(Cs,this)):this.emit("drain"))},this.on("newListener",function(m){m==="drain"&&(this._asyncDrainScheduled=!1)}),this._periodicFlush!==0&&(this._periodicFlushTimer=setInterval(()=>this.flush(null),this._periodicFlush),this._periodicFlushTimer.unref())}function Ke(e,t,r){return typeof e=="string"&&Buffer.byteLength(e)!==r&&(r=Buffer.from(e).subarray(0,r).toString().length),t=Math.max(t-r,0),e=e.slice(r),{writingBuf:e,len:t}}function Cs(e){e.listenerCount("drain")>0&&(e._asyncDrainScheduled=!1,e.emit("drain"))}As(D,js);function pr(e,t){return e.length===0?he:e.length===1?e[0]:Buffer.concat(e,t)}function Is(e){if(this.destroyed)throw new Error("SonicBoom destroyed");let t=this._len+e.length,r=this._bufs;return this.maxLength&&t>this.maxLength?(this.emit("drop",e),this._lenthis.maxWrite?r.push(""+e):r[r.length-1]+=e,this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._lenthis.maxLength?(this.emit("drop",e),this._lenthis.maxWrite?(r.push([e]),n.push(e.length)):(r[r.length-1].push(e),n[n.length-1]+=e.length),this._len=t,!this._writing&&this._len>=this.minLength&&this._actualWrite(),this._len{if(this._fsync)this._flushPending=!1,e();else try{T.fsync(this.fd,n=>{this._flushPending=!1,e(n)})}catch(n){e(n)}this.off("error",r)},r=n=>{this._flushPending=!1,e(n),this.off("drain",t)};this.once("drain",t),this.once("error",r)}function Ns(e){if(e!=null&&typeof e!="function")throw new Error("flush cb must be a function");if(this.destroyed){let t=new Error("SonicBoom destroyed");if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&br.call(this,e),!this._writing&&(this._bufs.length===0&&this._bufs.push(""),this._actualWrite())}function Ps(e){if(e!=null&&typeof e!="function")throw new Error("flush cb must be a function");if(this.destroyed){let t=new Error("SonicBoom destroyed");if(e){e(t);return}throw t}if(this.minLength<=0){e?.();return}e&&br.call(this,e),!this._writing&&(this._bufs.length===0&&(this._bufs.push([]),this._lens.push(0)),this._actualWrite())}D.prototype.reopen=function(e){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.reopen(e)});return}if(this._ending)return;if(!this.file)throw new Error("Unable to reopen a file descriptor, you must pass a file to SonicBoom");if(e&&(this.file=e),this._reopening=!0,this._writing)return;let t=this.fd;this.once("ready",()=>{t!==this.fd&&T.close(t,r=>{if(r)return this.emit("error",r)})}),gr(this.file,this)};D.prototype.end=function(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this._opening){this.once("ready",()=>{this.end()});return}this._ending||(this._ending=!0,!this._writing&&(this._len>0&&this.fd>=0?this._actualWrite():de(this)))};function Ms(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift(this._writingBuf),this._writingBuf="");let e="";for(;this._bufs.length||e;){e.length<=0&&(e=this._bufs[0]);try{let t=T.writeSync(this.fd,e,"utf8"),r=Ke(e,this._len,t);e=r.writingBuf,this._len=r.len,e.length<=0&&this._bufs.shift()}catch(t){if((t.code==="EAGAIN"||t.code==="EBUSY")&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;Ve(ae)}}try{T.fsyncSync(this.fd)}catch{}}function Ws(){if(this.destroyed)throw new Error("SonicBoom destroyed");if(this.fd<0)throw new Error("sonic boom is not ready yet");!this._writing&&this._writingBuf.length>0&&(this._bufs.unshift([this._writingBuf]),this._writingBuf=he);let e=he;for(;this._bufs.length||e.length;){e.length<=0&&(e=pr(this._bufs[0],this._lens[0]));try{let t=T.writeSync(this.fd,e);e=e.subarray(t),this._len=Math.max(this._len-t,0),e.length<=0&&(this._bufs.shift(),this._lens.shift())}catch(t){if((t.code==="EAGAIN"||t.code==="EBUSY")&&!this.retryEAGAIN(t,e.length,this._len-e.length))throw t;Ve(ae)}}}D.prototype.destroy=function(){this.destroyed||de(this)};function zs(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf||this._bufs.shift()||"",this.sync)try{let t=T.writeSync(this.fd,this._writingBuf,"utf8");e(null,t)}catch(t){e(t)}else T.write(this.fd,this._writingBuf,"utf8",e)}function Fs(){let e=this.release;if(this._writing=!0,this._writingBuf=this._writingBuf.length?this._writingBuf:pr(this._bufs.shift(),this._lens.shift()),this.sync)try{let t=T.writeSync(this.fd,this._writingBuf);e(null,t)}catch(t){e(t)}else qs&&(this._writingBuf=Buffer.from(this._writingBuf)),T.write(this.fd,this._writingBuf,e)}function de(e){if(e.fd===-1){e.once("ready",de.bind(null,e));return}e._periodicFlushTimer!==void 0&&clearInterval(e._periodicFlushTimer),e.destroyed=!0,e._bufs=[],e._lens=[],Ts(typeof e.fd=="number",`sonic.fd must be a number, got ${typeof e.fd}`);try{T.fsync(e.fd,t)}catch{}function t(){e.fd!==1&&e.fd!==2?T.close(e.fd,r):r()}function r(n){if(n){e.emit("error",n);return}e._ending&&!e._writing&&e.emit("finish"),e.emit("close")}}D.SonicBoom=D;D.default=D;wr.exports=D});var Ue=v((qu,xr)=>{"use strict";var N={exit:[],beforeExit:[]},_r={exit:Us,beforeExit:Js},Y;function Ks(){Y===void 0&&(Y=new FinalizationRegistry(Gs))}function Vs(e){N[e].length>0||process.on(e,_r[e])}function Er(e){N[e].length>0||(process.removeListener(e,_r[e]),N.exit.length===0&&N.beforeExit.length===0&&(Y=void 0))}function Us(){vr("exit")}function Js(){vr("beforeExit")}function vr(e){for(let t of N[e]){let r=t.deref(),n=t.fn;r!==void 0&&n(r,e)}N[e]=[]}function Gs(e){for(let t of["exit","beforeExit"]){let r=N[t].indexOf(e);N[t].splice(r,r+1),Er(t)}}function Or(e,t,r){if(t===void 0)throw new Error("the object can't be undefined");Vs(e);let n=new WeakRef(t);n.fn=r,Ks(),Y.register(t,n),N[e].push(n)}function Hs(e,t){Or("exit",e,t)}function Xs(e,t){Or("beforeExit",e,t)}function Ys(e){if(Y!==void 0){Y.unregister(e);for(let t of["exit","beforeExit"])N[t]=N[t].filter(r=>{let n=r.deref();return n&&n!==e}),Er(t)}}xr.exports={register:Hs,registerBeforeExit:Xs,unregister:Ys}});var Lr=v((Cu,Qs)=>{Qs.exports={name:"thread-stream",version:"3.1.0",description:"A streaming way to send data to a Node.js Worker Thread",main:"index.js",types:"index.d.ts",dependencies:{"real-require":"^0.2.0"},devDependencies:{"@types/node":"^20.1.0","@types/tap":"^15.0.0","@yao-pkg/pkg":"^5.11.5",desm:"^1.3.0",fastbench:"^1.0.1",husky:"^9.0.6","pino-elasticsearch":"^8.0.0","sonic-boom":"^4.0.1",standard:"^17.0.0",tap:"^16.2.0","ts-node":"^10.8.0",typescript:"^5.3.2","why-is-node-running":"^2.2.2"},scripts:{build:"tsc --noEmit",test:'standard && npm run build && npm run transpile && tap "test/**/*.test.*js" && tap --ts test/*.test.*ts',"test:ci":"standard && npm run transpile && npm run test:ci:js && npm run test:ci:ts","test:ci:js":'tap --no-check-coverage --timeout=120 --coverage-report=lcovonly "test/**/*.test.*js"',"test:ci:ts":'tap --ts --no-check-coverage --coverage-report=lcovonly "test/**/*.test.*ts"',"test:yarn":'npm run transpile && tap "test/**/*.test.js" --no-check-coverage',transpile:"sh ./test/ts/transpile.sh",prepare:"husky install"},standard:{ignore:["test/ts/**/*","test/syntax-error.mjs"]},repository:{type:"git",url:"git+https://github.com/mcollina/thread-stream.git"},keywords:["worker","thread","threads","stream"],author:"Matteo Collina ",license:"MIT",bugs:{url:"https://github.com/mcollina/thread-stream/issues"},homepage:"https://github.com/mcollina/thread-stream#readme"}});var jr=v((Iu,$r)=>{"use strict";function Zs(e,t,r,n,i){let o=Date.now()+n,a=Atomics.load(e,t);if(a===r){i(null,"ok");return}let f=a,c=h=>{Date.now()>o?i(null,"timed-out"):setTimeout(()=>{f=a,a=Atomics.load(e,t),a===f?c(h>=1e3?1e3:h*2):a===r?i(null,"ok"):i(null,"not-equal")},h)};c(1)}function eo(e,t,r,n,i){let o=Date.now()+n,a=Atomics.load(e,t);if(a!==r){i(null,"ok");return}let f=c=>{Date.now()>o?i(null,"timed-out"):setTimeout(()=>{a=Atomics.load(e,t),a!==r?i(null,"ok"):f(c>=1e3?1e3:c*2)},c)};f(1)}$r.exports={wait:Zs,waitDiff:eo}});var Tr=v((Du,Ar)=>{"use strict";Ar.exports={WRITE_INDEX:4,READ_INDEX:8}});var Cr=v((Nu,qr)=>{"use strict";var{version:to}=Lr(),{EventEmitter:ro}=j("events"),{Worker:no}=j("worker_threads"),{join:io}=j("path"),{pathToFileURL:so}=j("url"),{wait:oo}=jr(),{WRITE_INDEX:B,READ_INDEX:P}=Tr(),lo=j("buffer"),fo=j("assert"),y=Symbol("kImpl"),uo=lo.constants.MAX_STRING_LENGTH,te=class{constructor(t){this._value=t}deref(){return this._value}},me=class{register(){}unregister(){}},co=process.env.NODE_V8_COVERAGE?me:global.FinalizationRegistry||me,ao=process.env.NODE_V8_COVERAGE?te:global.WeakRef||te,kr=new co(e=>{e.exited||e.terminate()});function ho(e,t){let{filename:r,workerData:n}=t,o=("__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{})["thread-stream-worker"]||io(__dirname,"lib","worker.js"),a=new no(o,{...t.workerOpts,trackUnmanagedFds:!1,workerData:{filename:r.indexOf("file://")===0?r:so(r).href,dataBuf:e[y].dataBuf,stateBuf:e[y].stateBuf,workerData:{$context:{threadStreamVersion:to},...n}}});return a.stream=new te(e),a.on("message",yo),a.on("exit",Br),kr.register(e,a),a}function Rr(e){fo(!e[y].sync),e[y].needDrain&&(e[y].needDrain=!1,e.emit("drain"))}function ye(e){let t=Atomics.load(e[y].state,B),r=e[y].data.length-t;if(r>0){if(e[y].buf.length===0){e[y].flushing=!1,e[y].ending?Ye(e):e[y].needDrain&&process.nextTick(Rr,e);return}let n=e[y].buf.slice(0,r),i=Buffer.byteLength(n);i<=r?(e[y].buf=e[y].buf.slice(r),ge(e,n,ye.bind(null,e))):e.flush(()=>{if(!e.destroyed){for(Atomics.store(e[y].state,P,0),Atomics.store(e[y].state,B,0);i>e[y].data.length;)r=r/2,n=e[y].buf.slice(0,r),i=Buffer.byteLength(n);e[y].buf=e[y].buf.slice(r),ge(e,n,ye.bind(null,e))}})}else if(r===0){if(t===0&&e[y].buf.length===0)return;e.flush(()=>{Atomics.store(e[y].state,P,0),Atomics.store(e[y].state,B,0),ye(e)})}else M(e,new Error("overwritten"))}function yo(e){let t=this.stream.deref();if(t===void 0){this.exited=!0,this.terminate();return}switch(e.code){case"READY":this.stream=new ao(t),t.flush(()=>{t[y].ready=!0,t.emit("ready")});break;case"ERROR":M(t,e.err);break;case"EVENT":Array.isArray(e.args)?t.emit(e.name,...e.args):t.emit(e.name,e.args);break;case"WARNING":process.emitWarning(e.err);break;default:M(t,new Error("this should not happen: "+e.code))}}function Br(e){let t=this.stream.deref();t!==void 0&&(kr.unregister(t),t.worker.exited=!0,t.worker.off("exit",Br),M(t,e!==0?new Error("the worker thread exited"):null))}var Ge=class extends ro{constructor(t={}){if(super(),t.bufferSize<4)throw new Error("bufferSize must at least fit a 4-byte utf-8 char");this[y]={},this[y].stateBuf=new SharedArrayBuffer(128),this[y].state=new Int32Array(this[y].stateBuf),this[y].dataBuf=new SharedArrayBuffer(t.bufferSize||4*1024*1024),this[y].data=Buffer.from(this[y].dataBuf),this[y].sync=t.sync||!1,this[y].ending=!1,this[y].ended=!1,this[y].needDrain=!1,this[y].destroyed=!1,this[y].flushing=!1,this[y].ready=!1,this[y].finished=!1,this[y].errored=null,this[y].closed=!1,this[y].buf="",this.worker=ho(this,t),this.on("message",(r,n)=>{this.worker.postMessage(r,n)})}write(t){if(this[y].destroyed)return He(this,new Error("the worker has exited")),!1;if(this[y].ending)return He(this,new Error("the worker is ending")),!1;if(this[y].flushing&&this[y].buf.length+t.length>=uo)try{Je(this),this[y].flushing=!0}catch(r){return M(this,r),!1}if(this[y].buf+=t,this[y].sync)try{return Je(this),!0}catch(r){return M(this,r),!1}return this[y].flushing||(this[y].flushing=!0,setImmediate(ye,this)),this[y].needDrain=this[y].data.length-this[y].buf.length-Atomics.load(this[y].state,B)<=0,!this[y].needDrain}end(){this[y].destroyed||(this[y].ending=!0,Ye(this))}flush(t){if(this[y].destroyed){typeof t=="function"&&process.nextTick(t,new Error("the worker has exited"));return}let r=Atomics.load(this[y].state,B);oo(this[y].state,P,r,1/0,(n,i)=>{if(n){M(this,n),process.nextTick(t,n);return}if(i==="not-equal"){this.flush(t);return}process.nextTick(t)})}flushSync(){this[y].destroyed||(Je(this),Xe(this))}unref(){this.worker.unref()}ref(){this.worker.ref()}get ready(){return this[y].ready}get destroyed(){return this[y].destroyed}get closed(){return this[y].closed}get writable(){return!this[y].destroyed&&!this[y].ending}get writableEnded(){return this[y].ending}get writableFinished(){return this[y].finished}get writableNeedDrain(){return this[y].needDrain}get writableObjectMode(){return!1}get writableErrored(){return this[y].errored}};function He(e,t){setImmediate(()=>{e.emit("error",t)})}function M(e,t){e[y].destroyed||(e[y].destroyed=!0,t&&(e[y].errored=t,He(e,t)),e.worker.exited?setImmediate(()=>{e[y].closed=!0,e.emit("close")}):e.worker.terminate().catch(()=>{}).then(()=>{e[y].closed=!0,e.emit("close")}))}function ge(e,t,r){let n=Atomics.load(e[y].state,B),i=Buffer.byteLength(t);return e[y].data.write(t,n),Atomics.store(e[y].state,B,n+i),Atomics.notify(e[y].state,B),r(),!0}function Ye(e){if(!(e[y].ended||!e[y].ending||e[y].flushing)){e[y].ended=!0;try{e.flushSync();let t=Atomics.load(e[y].state,P);Atomics.store(e[y].state,B,-1),Atomics.notify(e[y].state,B);let r=0;for(;t!==-1;){if(Atomics.wait(e[y].state,P,t,1e3),t=Atomics.load(e[y].state,P),t===-2){M(e,new Error("end() failed"));return}if(++r===10){M(e,new Error("end() took too long (10s)"));return}}process.nextTick(()=>{e[y].finished=!0,e.emit("finish")})}catch(t){M(e,t)}}}function Je(e){let t=()=>{e[y].ending?Ye(e):e[y].needDrain&&process.nextTick(Rr,e)};for(e[y].flushing=!1;e[y].buf.length!==0;){let r=Atomics.load(e[y].state,B),n=e[y].data.length-r;if(n===0){Xe(e),Atomics.store(e[y].state,P,0),Atomics.store(e[y].state,B,0);continue}else if(n<0)throw new Error("overwritten");let i=e[y].buf.slice(0,n),o=Buffer.byteLength(i);if(o<=n)e[y].buf=e[y].buf.slice(n),ge(e,i,t);else{for(Xe(e),Atomics.store(e[y].state,P,0),Atomics.store(e[y].state,B,0);o>e[y].buf.length;)n=n/2,i=e[y].buf.slice(0,n),o=Buffer.byteLength(i);e[y].buf=e[y].buf.slice(n),ge(e,i,t)}}}function Xe(e){if(e[y].flushing)throw new Error("unable to flush while flushing");let t=Atomics.load(e[y].state,B),r=0;for(;;){let n=Atomics.load(e[y].state,P);if(n===-2)throw Error("_flushSync failed");if(n!==t)Atomics.wait(e[y].state,P,n,1e3);else break;if(++r===10)throw new Error("_flushSync took too long (10s)")}}qr.exports=Ge});var et=v((Pu,Ir)=>{"use strict";var{createRequire:mo}=j("module"),go=qe(),{join:Qe,isAbsolute:po,sep:bo}=j("node:path"),wo=Fe(),Ze=Ue(),So=Cr();function _o(e){Ze.register(e,vo),Ze.registerBeforeExit(e,Oo),e.on("close",function(){Ze.unregister(e)})}function Eo(e,t,r,n){let i=new So({filename:e,workerData:t,workerOpts:r,sync:n});i.on("ready",o),i.on("close",function(){process.removeListener("exit",a)}),process.on("exit",a);function o(){process.removeListener("exit",a),i.unref(),r.autoEnd!==!1&&_o(i)}function a(){i.closed||(i.flushSync(),wo(100),i.end())}return i}function vo(e){e.ref(),e.flushSync(),e.end(),e.once("close",function(){e.unref()})}function Oo(e){e.flushSync()}function xo(e){let{pipeline:t,targets:r,levels:n,dedupe:i,worker:o={},caller:a=go(),sync:f=!1}=e,c={...e.options},h=typeof a=="string"?[a]:a,u="__bundlerPathsOverrides"in globalThis?globalThis.__bundlerPathsOverrides:{},l=e.target;if(l&&r)throw new Error("only one of target or targets can be specified");return r?(l=u["pino-worker"]||Qe(__dirname,"worker.js"),c.targets=r.filter(d=>d.target).map(d=>({...d,target:p(d.target)})),c.pipelines=r.filter(d=>d.pipeline).map(d=>d.pipeline.map(s=>({...s,level:d.level,target:p(s.target)})))):t&&(l=u["pino-worker"]||Qe(__dirname,"worker.js"),c.pipelines=[t.map(d=>({...d,target:p(d.target)}))]),n&&(c.levels=n),i&&(c.dedupe=i),c.pinoWillSendConfig=!0,Eo(p(l),c,o,f);function p(d){if(d=u[d]||d,po(d)||d.indexOf("file://")===0)return d;if(d==="pino/file")return Qe(__dirname,"..","file.js");let s;for(let g of h)try{let m=g==="node:repl"?process.cwd()+bo:g;s=mo(m).resolve(d);break}catch{continue}if(!s)throw new Error(`unable to determine transport target for "${d}"`);return s}}Ir.exports=xo});var we=v((Mu,Jr)=>{"use strict";var Dr=hr(),{mapHttpRequest:Lo,mapHttpResponse:$o}=Be(),rt=Sr(),Nr=Ue(),{lsCacheSym:jo,chindingsSym:Wr,writeSym:Pr,serializersSym:zr,formatOptsSym:Mr,endSym:Ao,stringifiersSym:Fr,stringifySym:Kr,stringifySafeSym:nt,wildcardFirstSym:Vr,nestedKeySym:To,formattersSym:Ur,messageKeySym:ko,errorKeySym:Ro,nestedKeyStrSym:Bo,msgPrefixSym:pe}=X(),{isMainThread:qo}=j("worker_threads"),Co=et();function Q(){}function Io(e,t){if(!t)return r;return function(...i){t.call(this,i,r,e)};function r(n,...i){if(typeof n=="object"){let o=n;n!==null&&(n.method&&n.headers&&n.socket?n=Lo(n):typeof n.setHeader=="function"&&(n=$o(n)));let a;o===null&&i.length===0?a=[null]:(o=i.shift(),a=i),typeof this[pe]=="string"&&o!==void 0&&o!==null&&(o=this[pe]+o),this[Pr](n,Dr(o,a,this[Mr]),e)}else{let o=n===void 0?i.shift():n;typeof this[pe]=="string"&&o!==void 0&&o!==null&&(o=this[pe]+o),this[Pr](null,Dr(o,i,this[Mr]),e)}}}function tt(e){let t="",r=0,n=!1,i=255,o=e.length;if(o>100)return JSON.stringify(e);for(var a=0;a=32;a++)i=e.charCodeAt(a),(i===34||i===92)&&(t+=e.slice(r,a)+"\\",r=a,n=!0);return n?t+=e.slice(r):t=e,i<32?JSON.stringify(e):'"'+t+'"'}function Do(e,t,r,n){let i=this[Kr],o=this[nt],a=this[Fr],f=this[Ao],c=this[Wr],h=this[zr],u=this[Ur],l=this[ko],p=this[Ro],d=this[jo][r]+n;d=d+c;let s;u.log&&(e=u.log(e));let g=a[Vr],m="";for(let b in e)if(s=e[b],Object.prototype.hasOwnProperty.call(e,b)&&s!==void 0){h[b]?s=h[b](s):b===p&&h.err&&(s=h.err(s));let w=a[b]||g;switch(typeof s){case"undefined":case"function":continue;case"number":Number.isFinite(s)===!1&&(s=null);case"boolean":w&&(s=w(s));break;case"string":s=(w||tt)(s);break;default:s=(w||i)(s,o)}if(s===void 0)continue;let _=tt(b);m+=","+_+":"+s}let S="";if(t!==void 0){s=h[l]?h[l](t):t;let b=a[l]||g;switch(typeof s){case"function":break;case"number":Number.isFinite(s)===!1&&(s=null);case"boolean":b&&(s=b(s)),S=',"'+l+'":'+s;break;case"string":s=(b||tt)(s),S=',"'+l+'":'+s;break;default:s=(b||i)(s,o),S=',"'+l+'":'+s}}return this[To]&&m?d+this[Bo]+m.slice(1)+"}"+S+f:d+m+S+f}function No(e,t){let r,n=e[Wr],i=e[Kr],o=e[nt],a=e[Fr],f=a[Vr],c=e[zr],h=e[Ur].bindings;t=h(t);for(let u in t)if(r=t[u],(u!=="level"&&u!=="serializers"&&u!=="formatters"&&u!=="customLevels"&&t.hasOwnProperty(u)&&r!==void 0)===!0){if(r=c[u]?c[u](r):r,r=(a[u]||f||i)(r,o),r===void 0)continue;n+=',"'+u+'":'+r}return n}function Po(e){return e.write!==e.constructor.prototype.write}function be(e){let t=new rt(e);return t.on("error",r),!e.sync&&qo&&(Nr.register(t,Mo),t.on("close",function(){Nr.unregister(t)})),t;function r(n){if(n.code==="EPIPE"){t.write=Q,t.end=Q,t.flushSync=Q,t.destroy=Q;return}t.removeListener("error",r),t.emit("error",n)}}function Mo(e,t){e.destroyed||(t==="beforeExit"?(e.flush(),e.on("drain",function(){e.end()})):e.flushSync())}function Wo(e){return function(r,n,i={},o){if(typeof i=="string")o=be({dest:i}),i={};else if(typeof o=="string"){if(i&&i.transport)throw Error("only one of option.transport or stream can be specified");o=be({dest:o})}else if(i instanceof rt||i.writable||i._writableState)o=i,i={};else if(i.transport){if(i.transport instanceof rt||i.transport.writable||i.transport._writableState)throw Error("option.transport do not allow stream, please pass to option directly. e.g. pino(transport)");if(i.transport.targets&&i.transport.targets.length&&i.formatters&&typeof i.formatters.level=="function")throw Error("option.transport.targets do not allow custom level formatters");let c;i.customLevels&&(c=i.useOnlyCustomLevels?i.customLevels:Object.assign({},i.levels,i.customLevels)),o=Co({caller:n,...i.transport,levels:c})}if(i=Object.assign({},e,i),i.serializers=Object.assign({},e.serializers,i.serializers),i.formatters=Object.assign({},e.formatters,i.formatters),i.prettyPrint)throw new Error("prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)");let{enabled:a,onChild:f}=i;return a===!1&&(i.level="silent"),f||(i.onChild=Q),o||(Po(process.stdout)?o=process.stdout:o=be({fd:process.stdout.fd||1})),{opts:i,stream:o}}}function zo(e,t){try{return JSON.stringify(e)}catch{try{return(t||this[nt])(e)}catch{return'"[unable to serialize, circular reference is too complex to analyze]"'}}}function Fo(e,t,r){return{level:e,bindings:t,log:r}}function Ko(e){let t=Number(e);return typeof e=="string"&&Number.isFinite(t)?t:e===void 0?1:e}Jr.exports={noop:Q,buildSafeSonicBoom:be,asChindings:No,asJson:Do,genLog:Io,createArgsNormalizer:Wo,stringify:zo,buildFormatters:Fo,normalizeDestFileDescriptor:Ko}});var Se=v((Wu,Gr)=>{var Vo={trace:10,debug:20,info:30,warn:40,error:50,fatal:60},Uo={ASC:"ASC",DESC:"DESC"};Gr.exports={DEFAULT_LEVELS:Vo,SORTING_ORDER:Uo}});var ot=v((zu,Qr)=>{"use strict";var{lsCacheSym:Jo,levelValSym:it,useOnlyCustomLevelsSym:Go,streamSym:Ho,formattersSym:Xo,hooksSym:Yo,levelCompSym:Hr}=X(),{noop:Qo,genLog:U}=we(),{DEFAULT_LEVELS:W,SORTING_ORDER:Xr}=Se(),Yr={fatal:e=>{let t=U(W.fatal,e);return function(...r){let n=this[Ho];if(t.call(this,...r),typeof n.flushSync=="function")try{n.flushSync()}catch{}}},error:e=>U(W.error,e),warn:e=>U(W.warn,e),info:e=>U(W.info,e),debug:e=>U(W.debug,e),trace:e=>U(W.trace,e)},st=Object.keys(W).reduce((e,t)=>(e[W[t]]=t,e),{}),Zo=Object.keys(st).reduce((e,t)=>(e[t]='{"level":'+Number(t),e),{});function el(e){let t=e[Xo].level,{labels:r}=e.levels,n={};for(let i in r){let o=t(r[i],Number(i));n[i]=JSON.stringify(o).slice(0,-1)}return e[Jo]=n,e}function tl(e,t){if(t)return!1;switch(e){case"fatal":case"error":case"warn":case"info":case"debug":case"trace":return!0;default:return!1}}function rl(e){let{labels:t,values:r}=this.levels;if(typeof e=="number"){if(t[e]===void 0)throw Error("unknown level value"+e);e=t[e]}if(r[e]===void 0)throw Error("unknown level "+e);let n=this[it],i=this[it]=r[e],o=this[Go],a=this[Hr],f=this[Yo].logMethod;for(let c in r){if(a(r[c],i)===!1){this[c]=Qo;continue}this[c]=tl(c,o)?Yr[c](f):U(r[c],f)}this.emit("level-change",e,i,t[n],n,this)}function nl(e){let{levels:t,levelVal:r}=this;return t&&t.labels?t.labels[r]:""}function il(e){let{values:t}=this.levels,r=t[e];return r!==void 0&&this[Hr](r,this[it])}function sl(e,t,r){return e===Xr.DESC?t<=r:t>=r}function ol(e){return typeof e=="string"?sl.bind(null,e):e}function ll(e=null,t=!1){let r=e?Object.keys(e).reduce((o,a)=>(o[e[a]]=a,o),{}):null,n=Object.assign(Object.create(Object.prototype,{Infinity:{value:"silent"}}),t?null:st,r),i=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),t?null:W,e);return{labels:n,values:i}}function fl(e,t,r){if(typeof e=="number"){if(![].concat(Object.keys(t||{}).map(o=>t[o]),r?[]:Object.keys(st).map(o=>+o),1/0).includes(e))throw Error(`default level:${e} must be included in custom levels`);return}let n=Object.assign(Object.create(Object.prototype,{silent:{value:1/0}}),r?null:W,t);if(!(e in n))throw Error(`default level:${e} must be included in custom levels`)}function ul(e,t){let{labels:r,values:n}=e;for(let i in t){if(i in n)throw Error("levels cannot be overridden");if(t[i]in r)throw Error("pre-existing level values cannot be used for new levels")}}function cl(e){if(typeof e!="function"&&!(typeof e=="string"&&Object.values(Xr).includes(e)))throw new Error('Levels comparison should be one of "ASC", "DESC" or "function" type')}Qr.exports={initialLsCache:Zo,genLsCache:el,levelMethods:Yr,getLevel:nl,setLevel:rl,isLevelEnabled:il,mappings:ll,assertNoLevelCollisions:ul,assertDefaultLevelFound:fl,genLevelComparison:ol,assertLevelComparison:cl}});var lt=v((Fu,Zr)=>{"use strict";Zr.exports={version:"9.7.0"}});var an=v((Vu,cn)=>{"use strict";var{EventEmitter:al}=j("node:events"),{lsCacheSym:hl,levelValSym:dl,setLevelSym:ut,getLevelSym:en,chindingsSym:ct,parsedChindingsSym:yl,mixinSym:ml,asJsonSym:on,writeSym:gl,mixinMergeStrategySym:pl,timeSym:bl,timeSliceIndexSym:wl,streamSym:ln,serializersSym:J,formattersSym:ft,errorKeySym:Sl,messageKeySym:_l,useOnlyCustomLevelsSym:El,needsMetadataGsym:vl,redactFmtSym:Ol,stringifySym:xl,formatOptsSym:Ll,stringifiersSym:$l,msgPrefixSym:tn,hooksSym:jl}=X(),{getLevel:Al,setLevel:Tl,isLevelEnabled:kl,mappings:Rl,initialLsCache:Bl,genLsCache:ql,assertNoLevelCollisions:Cl}=ot(),{asChindings:fn,asJson:Il,buildFormatters:rn,stringify:nn}=we(),{version:Dl}=lt(),Nl=We(),Pl=class{},un={constructor:Pl,child:Ml,bindings:Wl,setBindings:zl,flush:Ul,isLevelEnabled:kl,version:Dl,get level(){return this[en]()},set level(e){this[ut](e)},get levelVal(){return this[dl]},set levelVal(e){throw Error("levelVal is read-only")},[hl]:Bl,[gl]:Kl,[on]:Il,[en]:Al,[ut]:Tl};Object.setPrototypeOf(un,al.prototype);cn.exports=function(){return Object.create(un)};var sn=e=>e;function Ml(e,t){if(!e)throw Error("missing bindings for child Pino");t=t||{};let r=this[J],n=this[ft],i=Object.create(this);if(t.hasOwnProperty("serializers")===!0){i[J]=Object.create(null);for(let u in r)i[J][u]=r[u];let c=Object.getOwnPropertySymbols(r);for(var o=0;o{"use strict";var{hasOwnProperty:re}=Object.prototype,H=dt();H.configure=dt;H.stringify=H;H.default=H;yt.stringify=H;yt.configure=dt;yn.exports=H;var Jl=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function F(e){return e.length<5e3&&!Jl.test(e)?`"${e}"`:JSON.stringify(e)}function at(e,t){if(e.length>200||t)return e.sort(t);for(let r=1;rn;)e[i]=e[i-1],i--;e[i]=n}return e}var Gl=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function ht(e){return Gl.call(e)!==void 0&&e.length!==0}function hn(e,t,r){e.length= 1`)}return r===void 0?1/0:r}function G(e){return e===1?"1 item":`${e} items`}function Ql(e){let t=new Set;for(let r of e)(typeof r=="string"||typeof r=="number")&&t.add(String(r));return t}function Zl(e){if(re.call(e,"strict")){let t=e.strict;if(typeof t!="boolean")throw new TypeError('The "strict" argument must be of type boolean');if(t)return r=>{let n=`Object can not safely be stringified. Received type ${typeof r}`;throw typeof r!="function"&&(n+=` (${r.toString()})`),new Error(n)}}}function dt(e){e={...e};let t=Zl(e);t&&(e.bigint===void 0&&(e.bigint=!1),"circularValue"in e||(e.circularValue=Error));let r=Hl(e),n=Yl(e,"bigint"),i=Xl(e),o=typeof i=="function"?i:void 0,a=dn(e,"maximumDepth"),f=dn(e,"maximumBreadth");function c(d,s,g,m,S,b){let w=s[d];switch(typeof w=="object"&&w!==null&&typeof w.toJSON=="function"&&(w=w.toJSON(d)),w=m.call(s,d,w),typeof w){case"string":return F(w);case"object":{if(w===null)return"null";if(g.indexOf(w)!==-1)return r;let _="",O=",",x=b;if(Array.isArray(w)){if(w.length===0)return"[]";if(af){let V=w.length-f-1;_+=`${O}"... ${G(V)} not stringified"`}return S!==""&&(_+=` +${x}`),g.pop(),`[${_}]`}let L=Object.keys(w),$=L.length;if($===0)return"{}";if(af){let k=$-f;_+=`${A}"...":${E}"${G(k)} not stringified"`,A=O}return S!==""&&A.length>1&&(_=` +${b}${_} +${x}`),g.pop(),`{${_}}`}case"number":return isFinite(w)?String(w):t?t(w):"null";case"boolean":return w===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(w);default:return t?t(w):void 0}}function h(d,s,g,m,S,b){switch(typeof s=="object"&&s!==null&&typeof s.toJSON=="function"&&(s=s.toJSON(d)),typeof s){case"string":return F(s);case"object":{if(s===null)return"null";if(g.indexOf(s)!==-1)return r;let w=b,_="",O=",";if(Array.isArray(s)){if(s.length===0)return"[]";if(af){let R=s.length-f-1;_+=`${O}"... ${G(R)} not stringified"`}return S!==""&&(_+=` +${w}`),g.pop(),`[${_}]`}g.push(s);let x="";S!==""&&(b+=S,O=`, +${b}`,x=" ");let L="";for(let $ of m){let E=h($,s[$],g,m,S,b);E!==void 0&&(_+=`${L}${F($)}:${x}${E}`,L=O)}return S!==""&&L.length>1&&(_=` +${b}${_} +${w}`),g.pop(),`{${_}}`}case"number":return isFinite(s)?String(s):t?t(s):"null";case"boolean":return s===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(s);default:return t?t(s):void 0}}function u(d,s,g,m,S){switch(typeof s){case"string":return F(s);case"object":{if(s===null)return"null";if(typeof s.toJSON=="function"){if(s=s.toJSON(d),typeof s!="object")return u(d,s,g,m,S);if(s===null)return"null"}if(g.indexOf(s)!==-1)return r;let b=S;if(Array.isArray(s)){if(s.length===0)return"[]";if(af){let C=s.length-f-1;E+=`${A}"... ${G(C)} not stringified"`}return E+=` +${b}`,g.pop(),`[${E}]`}let w=Object.keys(s),_=w.length;if(_===0)return"{}";if(af){let E=_-f;x+=`${L}"...": "${G(E)} not stringified"`,L=O}return L!==""&&(x=` +${S}${x} +${b}`),g.pop(),`{${x}}`}case"number":return isFinite(s)?String(s):t?t(s):"null";case"boolean":return s===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(s);default:return t?t(s):void 0}}function l(d,s,g){switch(typeof s){case"string":return F(s);case"object":{if(s===null)return"null";if(typeof s.toJSON=="function"){if(s=s.toJSON(d),typeof s!="object")return l(d,s,g);if(s===null)return"null"}if(g.indexOf(s)!==-1)return r;let m="",S=s.length!==void 0;if(S&&Array.isArray(s)){if(s.length===0)return"[]";if(af){let E=s.length-f-1;m+=`,"... ${G(E)} not stringified"`}return g.pop(),`[${m}]`}let b=Object.keys(s),w=b.length;if(w===0)return"{}";if(af){let x=w-f;m+=`${_}"...":"${G(x)} not stringified"`}return g.pop(),`{${m}}`}case"number":return isFinite(s)?String(s):t?t(s):"null";case"boolean":return s===!0?"true":"false";case"undefined":return;case"bigint":if(n)return String(s);default:return t?t(s):void 0}}function p(d,s,g){if(arguments.length>1){let m="";if(typeof g=="number"?m=" ".repeat(Math.min(g,10)):typeof g=="string"&&(m=g.slice(0,10)),s!=null){if(typeof s=="function")return c("",{"":d},[],s,m,"");if(Array.isArray(s))return h("",d,[],Ql(s),m,"")}if(m.length!==0)return u("",d,[],m,"")}return l("",d,[])}return p}});var bn=v((Uu,pn)=>{"use strict";var mt=Symbol.for("pino.metadata"),{DEFAULT_LEVELS:gn}=Se(),ef=gn.info;function tf(e,t){let r=0;e=e||[],t=t||{dedupe:!1};let n=Object.create(gn);n.silent=1/0,t.levels&&typeof t.levels=="object"&&Object.keys(t.levels).forEach(l=>{n[l]=t.levels[l]});let i={write:o,add:c,emit:a,flushSync:f,end:h,minLevel:0,streams:[],clone:u,[mt]:!0,streamLevels:n};return Array.isArray(e)?e.forEach(c,i):c.call(i,e),e=null,i;function o(l){let p,d=this.lastLevel,{streams:s}=this,g=0,m;for(let S=nf(s.length,t.dedupe);of(S,s.length,t.dedupe);S=sf(S,t.dedupe))if(p=s[S],p.level<=d){if(g!==0&&g!==p.level)break;if(m=p.stream,m[mt]){let{lastTime:b,lastMsg:w,lastObj:_,lastLogger:O}=this;m.lastLevel=d,m.lastTime=b,m.lastMsg=w,m.lastObj=_,m.lastLogger=O}m.write(l),t.dedupe&&(g=p.level)}else if(!t.dedupe)break}function a(...l){for(let{stream:p}of this.streams)typeof p.emit=="function"&&p.emit(...l)}function f(){for(let{stream:l}of this.streams)typeof l.flushSync=="function"&&l.flushSync()}function c(l){if(!l)return i;let p=typeof l.write=="function"||l.stream,d=l.write?l:l.stream;if(!p)throw Error("stream object needs to implement either StreamEntry or DestinationStream interface");let{streams:s,streamLevels:g}=this,m;typeof l.levelVal=="number"?m=l.levelVal:typeof l.level=="string"?m=g[l.level]:typeof l.level=="number"?m=l.level:m=ef;let S={stream:d,level:m,levelVal:void 0,id:r++};return s.unshift(S),s.sort(rf),this.minLevel=s[0].level,i}function h(){for(let{stream:l}of this.streams)typeof l.flushSync=="function"&&l.flushSync(),l.end()}function u(l){let p=new Array(this.streams.length);for(let d=0;d=0:e{function _e(e){try{return j("path").join(`${process.cwd()}${j("path").sep}dist/esm`.replace(/\\/g,"/"),e)}catch{return new Function("p","return new URL(p, import.meta.url).pathname")(e)}}globalThis.__bundlerPathsOverrides={...globalThis.__bundlerPathsOverrides||{},"thread-stream-worker":_e("./thread-stream-worker.mjs"),"pino-worker":_e("./pino-worker.mjs"),"pino/file":_e("./pino-file.mjs"),"pino-roll":_e("./pino-roll.mjs")};var lf=j("node:os"),Ln=Be(),ff=qe(),uf=We(),$n=cr(),cf=an(),jn=X(),{configure:af}=mn(),{assertDefaultLevelFound:hf,mappings:An,genLsCache:df,genLevelComparison:yf,assertLevelComparison:mf}=ot(),{DEFAULT_LEVELS:Tn,SORTING_ORDER:gf}=Se(),{createArgsNormalizer:pf,asChindings:bf,buildSafeSonicBoom:wn,buildFormatters:wf,stringify:gt,normalizeDestFileDescriptor:Sn,noop:Sf}=we(),{version:_f}=lt(),{chindingsSym:_n,redactFmtSym:Ef,serializersSym:En,timeSym:vf,timeSliceIndexSym:Of,streamSym:xf,stringifySym:vn,stringifySafeSym:pt,stringifiersSym:On,setLevelSym:Lf,endSym:$f,formatOptsSym:jf,messageKeySym:Af,errorKeySym:Tf,nestedKeySym:kf,mixinSym:Rf,levelCompSym:Bf,useOnlyCustomLevelsSym:qf,formattersSym:xn,hooksSym:Cf,nestedKeyStrSym:If,mixinMergeStrategySym:Df,msgPrefixSym:Nf}=jn,{epochTime:kn,nullTime:Pf}=$n,{pid:Mf}=process,Wf=lf.hostname(),zf=Ln.err,Ff={level:"info",levelComparison:gf.ASC,levels:Tn,messageKey:"msg",errorKey:"err",nestedKey:null,enabled:!0,base:{pid:Mf,hostname:Wf},serializers:Object.assign(Object.create(null),{err:zf}),formatters:Object.assign(Object.create(null),{bindings(e){return e},level(e,t){return{level:t}}}),hooks:{logMethod:void 0,streamWrite:void 0},timestamp:kn,name:void 0,redact:null,customLevels:null,useOnlyCustomLevels:!1,depthLimit:5,edgeLimit:100},Kf=pf(Ff),Vf=Object.assign(Object.create(null),Ln);function bt(...e){let t={},{opts:r,stream:n}=Kf(t,ff(),...e);r.level&&typeof r.level=="string"&&Tn[r.level.toLowerCase()]!==void 0&&(r.level=r.level.toLowerCase());let{redact:i,crlf:o,serializers:a,timestamp:f,messageKey:c,errorKey:h,nestedKey:u,base:l,name:p,level:d,customLevels:s,levelComparison:g,mixin:m,mixinMergeStrategy:S,useOnlyCustomLevels:b,formatters:w,hooks:_,depthLimit:O,edgeLimit:x,onChild:L,msgPrefix:$}=r,E=af({maximumDepth:O,maximumBreadth:x}),A=wf(w.level,w.bindings,w.log),R=gt.bind({[pt]:E}),k=i?uf(i,R):{},q=i?{stringify:k[Ef]}:{stringify:R},C="}"+(o?`\r +`:` +`),V=bf.bind(null,{[_n]:"",[En]:a,[On]:k,[vn]:gt,[pt]:E,[xn]:A}),ve="";l!==null&&(p===void 0?ve=V(l):ve=V(Object.assign({},l,{name:p})));let wt=f instanceof Function?f:f?kn:Pf,Gn=wt().indexOf(":")+1;if(b&&!s)throw Error("customLevels is required if useOnlyCustomLevels is set true");if(m&&typeof m!="function")throw Error(`Unknown mixin type "${typeof m}" - expected "function"`);if($&&typeof $!="string")throw Error(`Unknown msgPrefix type "${typeof $}" - expected "string"`);hf(d,s,b);let St=An(s,b);typeof n.emit=="function"&&n.emit("message",{code:"PINO_CONFIG",config:{levels:St,messageKey:c,errorKey:h}}),mf(g);let Hn=yf(g);return Object.assign(t,{levels:St,[Bf]:Hn,[qf]:b,[xf]:n,[vf]:wt,[Of]:Gn,[vn]:gt,[pt]:E,[On]:k,[$f]:C,[jf]:q,[Af]:c,[Tf]:h,[kf]:u,[If]:u?`,${JSON.stringify(u)}:{`:"",[En]:a,[Rf]:m,[Df]:S,[_n]:ve,[xn]:A,[Cf]:_,silent:Sf,onChild:L,[Nf]:$}),Object.setPrototypeOf(t,cf()),df(t),t[Lf](d),t}I.exports=bt;I.exports.destination=(e=process.stdout.fd)=>typeof e=="object"?(e.dest=Sn(e.dest||process.stdout.fd),wn(e)):wn({dest:Sn(e),minLength:0});I.exports.transport=et();I.exports.multistream=bn();I.exports.levels=An();I.exports.stdSerializers=Vf;I.exports.stdTimeFunctions=Object.assign({},$n);I.exports.symbols=jn;I.exports.version=_f;I.exports.default=bt;I.exports.pino=bt});var In=v((Gu,Cn)=>{"use strict";var{Transform:Uf}=j("stream"),{StringDecoder:Jf}=j("string_decoder"),K=Symbol("last"),Ee=Symbol("decoder");function Gf(e,t,r){let n;if(this.overflow){if(n=this[Ee].write(e).split(this.matcher),n.length===1)return r();n.shift(),this.overflow=!1}else this[K]+=this[Ee].write(e),n=this[K].split(this.matcher);this[K]=n.pop();for(let i=0;ithis.maxLength,this.overflow&&!this.skipOverflow){r(new Error("maximum buffer reached"));return}r()}function Hf(e){if(this[K]+=this[Ee].end(),this[K])try{qn(this,this.mapper(this[K]))}catch(t){return e(t)}e()}function qn(e,t){t!==void 0&&e.push(t)}function Bn(e){return e}function Xf(e,t,r){switch(e=e||/\r?\n/,t=t||Bn,r=r||{},arguments.length){case 1:typeof e=="function"?(t=e,e=/\r?\n/):typeof e=="object"&&!(e instanceof RegExp)&&!e[Symbol.split]&&(r=e,e=/\r?\n/);break;case 2:typeof e=="function"?(r=t,t=e,e=/\r?\n/):typeof t=="object"&&(r=t,t=Bn)}r=Object.assign({},r),r.autoDestroy=!0,r.transform=Gf,r.flush=Hf,r.readableObjectMode=!0;let n=new Uf(r);return n[K]="",n[Ee]=new Jf("utf8"),n.matcher=e,n.mapper=t,n.maxLength=r.maxLength,n.skipOverflow=r.skipOverflow||!1,n.overflow=!1,n._destroy=function(i,o){this._writableState.errorEmitted=!1,o(i)},n}Cn.exports=Xf});var Wn=v((Hu,Mn)=>{"use strict";var Dn=Symbol.for("pino.metadata"),Yf=In(),{Duplex:Qf}=j("stream"),{parentPort:Nn,workerData:Pn}=j("worker_threads");function Zf(){let e,t,r=new Promise((n,i)=>{e=n,t=i});return r.resolve=e,r.reject=t,r}Mn.exports=function(t,r={}){let n=r.expectPinoConfig===!0&&Pn?.workerData?.pinoWillSendConfig===!0,i=r.parse==="lines",o=typeof r.parseLine=="function"?r.parseLine:JSON.parse,a=r.close||eu,f=Yf(function(h){let u;try{u=o(h)}catch(l){this.emit("unknown",h,l);return}if(u===null){this.emit("unknown",h,"Null value ignored");return}return typeof u!="object"&&(u={data:u,time:Date.now()}),f[Dn]&&(f.lastTime=u.time,f.lastLevel=u.level,f.lastObj=u),i?h:u},{autoDestroy:!0});if(f._destroy=function(h,u){let l=a(h,u);l&&typeof l.then=="function"&&l.then(u,u)},r.expectPinoConfig===!0&&Pn?.workerData?.pinoWillSendConfig!==!0&&setImmediate(()=>{f.emit("error",new Error("This transport is not compatible with the current version of pino. Please upgrade pino to the latest version."))}),r.metadata!==!1&&(f[Dn]=!0,f.lastTime=0,f.lastLevel=0,f.lastObj=null),n){let h={},u=Zf();return Nn.on("message",function l(p){p.code==="PINO_CONFIG"&&(h=p.config,u.resolve(),Nn.off("message",l))}),Object.defineProperties(f,{levels:{get(){return h.levels}},messageKey:{get(){return h.messageKey}},errorKey:{get(){return h.errorKey}}}),u.then(c)}return c();function c(){let h=t(f);if(h&&typeof h.catch=="function")h.catch(u=>{f.destroy(u)}),h=null;else if(r.enablePipelining&&h)return Qf.from({writable:f,readable:h});return f}};function eu(e,t){process.nextTick(t,e)}});var Fn=v((Xu,zn)=>{var tu=new Function("modulePath","return import(modulePath)");function ru(e){return typeof __non_webpack__require__=="function"?__non_webpack__require__(e):j(e)}zn.exports={realImport:tu,realRequire:ru}});var Vn=v((Qu,Kn)=>{"use strict";var{realImport:nu,realRequire:ne}=Fn();Kn.exports=iu;async function iu(e){let t;try{let r=e.startsWith("file://")?e:"file://"+e;r.endsWith(".ts")||r.endsWith(".cts")?(process[Symbol.for("ts-node.register.instance")]?ne("ts-node/register"):process.env&&process.env.TS_NODE_DEV&&ne("ts-node-dev"),t=ne(decodeURIComponent(e))):t=await nu(r)}catch(r){if(r.code==="ENOTDIR"||r.code==="ERR_MODULE_NOT_FOUND")t=ne(e);else if(r.code===void 0||r.code==="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING")try{t=ne(decodeURIComponent(e))}catch{throw r}else throw r}if(typeof t=="object"&&(t=t.default),typeof t=="object"&&(t=t.default),typeof t!="function")throw Error("exported worker is not a function");return t}});var cu=v((Zu,Jn)=>{var su=j("node:events"),{pipeline:ou,PassThrough:lu}=j("node:stream"),fu=Rn(),uu=Wn(),Un=Vn();Jn.exports=async function({targets:e,pipelines:t,levels:r,dedupe:n}){let i=[];if(e&&e.length&&(e=await Promise.all(e.map(async f=>{let h=await(await Un(f.target))(f.options);return{level:f.level,stream:h}})),i.push(...e)),t&&t.length&&(t=await Promise.all(t.map(async f=>{let c,h=await Promise.all(f.map(async u=>(c=u.level,await(await Un(u.target))(u.options))));return{level:c,stream:a(h)}})),i.push(...t)),i.length===1)return i[0].stream;return uu(o,{parse:"lines",metadata:!0,close(f,c){let h=0;for(let l of i)h++,l.stream.on("close",u),l.stream.end();function u(){--h===0&&c(f)}}});function o(f){let c=fu.multistream(i,{levels:r,dedupe:n});f.on("data",function(h){let{lastTime:u,lastMsg:l,lastObj:p,lastLevel:d}=this;c.lastLevel=d,c.lastTime=u,c.lastMsg=l,c.lastObj=p,c.write(h+` +`)})}function a(f){let c=new su,h=new lu({autoDestroy:!0,destroy(u,l){c.on("error",l),c.on("closed",l)}});return ou(h,...f,function(u){if(u&&u.code!=="ERR_STREAM_PREMATURE_CLOSE"){c.emit("error",u);return}c.emit("closed")}),h}}});export default cu(); +//# sourceMappingURL=pino-worker.mjs.map diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-worker.mjs.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-worker.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..773ccbf03f49d7198d6e92d885ae92ec72907ddd --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/pino-worker.mjs.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err-helpers.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err-proto.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/err-with-cause.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/req.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/lib/res.js", "../../node_modules/.pnpm/pino-std-serializers@7.0.0/node_modules/pino-std-serializers/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/caller.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/validator.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/rx.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/parse.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/redactor.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/modifiers.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/restorer.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/lib/state.js", "../../node_modules/.pnpm/fast-redact@3.5.0/node_modules/fast-redact/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/symbols.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/redaction.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/time.js", "../../node_modules/.pnpm/quick-format-unescaped@4.0.4/node_modules/quick-format-unescaped/index.js", "../../node_modules/.pnpm/atomic-sleep@1.0.0/node_modules/atomic-sleep/index.js", "../../node_modules/.pnpm/sonic-boom@4.2.0/node_modules/sonic-boom/index.js", "../../node_modules/.pnpm/on-exit-leak-free@2.1.2/node_modules/on-exit-leak-free/index.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/package.json", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/wait.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/indexes.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/transport.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/tools.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/constants.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/levels.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/meta.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/proto.js", "../../node_modules/.pnpm/safe-stable-stringify@2.5.0/node_modules/safe-stable-stringify/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/multistream.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/pino.js", "../../node_modules/.pnpm/split2@4.2.0/node_modules/split2/index.js", "../../node_modules/.pnpm/pino-abstract-transport@2.0.0/node_modules/pino-abstract-transport/index.js", "../../node_modules/.pnpm/real-require@0.2.0/node_modules/real-require/src/index.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/transport-stream.js", "../../node_modules/.pnpm/pino@9.7.0/node_modules/pino/lib/worker.js"], + "sourcesContent": ["'use strict'\n\n// **************************************************************\n// * Code initially copied/adapted from \"pony-cause\" npm module *\n// * Please upstream improvements there *\n// **************************************************************\n\nconst isErrorLike = (err) => {\n return err && typeof err.message === 'string'\n}\n\n/**\n * @param {Error|{ cause?: unknown|(()=>err)}} err\n * @returns {Error|Object|undefined}\n */\nconst getErrorCause = (err) => {\n if (!err) return\n\n /** @type {unknown} */\n // @ts-ignore\n const cause = err.cause\n\n // VError / NError style causes\n if (typeof cause === 'function') {\n // @ts-ignore\n const causeResult = err.cause()\n\n return isErrorLike(causeResult)\n ? causeResult\n : undefined\n } else {\n return isErrorLike(cause)\n ? cause\n : undefined\n }\n}\n\n/**\n * Internal method that keeps a track of which error we have already added, to avoid circular recursion\n *\n * @private\n * @param {Error} err\n * @param {Set} seen\n * @returns {string}\n */\nconst _stackWithCauses = (err, seen) => {\n if (!isErrorLike(err)) return ''\n\n const stack = err.stack || ''\n\n // Ensure we don't go circular or crazily deep\n if (seen.has(err)) {\n return stack + '\\ncauses have become circular...'\n }\n\n const cause = getErrorCause(err)\n\n if (cause) {\n seen.add(err)\n return (stack + '\\ncaused by: ' + _stackWithCauses(cause, seen))\n } else {\n return stack\n }\n}\n\n/**\n * @param {Error} err\n * @returns {string}\n */\nconst stackWithCauses = (err) => _stackWithCauses(err, new Set())\n\n/**\n * Internal method that keeps a track of which error we have already added, to avoid circular recursion\n *\n * @private\n * @param {Error} err\n * @param {Set} seen\n * @param {boolean} [skip]\n * @returns {string}\n */\nconst _messageWithCauses = (err, seen, skip) => {\n if (!isErrorLike(err)) return ''\n\n const message = skip ? '' : (err.message || '')\n\n // Ensure we don't go circular or crazily deep\n if (seen.has(err)) {\n return message + ': ...'\n }\n\n const cause = getErrorCause(err)\n\n if (cause) {\n seen.add(err)\n\n // @ts-ignore\n const skipIfVErrorStyleCause = typeof err.cause === 'function'\n\n return (message +\n (skipIfVErrorStyleCause ? '' : ': ') +\n _messageWithCauses(cause, seen, skipIfVErrorStyleCause))\n } else {\n return message\n }\n}\n\n/**\n * @param {Error} err\n * @returns {string}\n */\nconst messageWithCauses = (err) => _messageWithCauses(err, new Set())\n\nmodule.exports = {\n isErrorLike,\n getErrorCause,\n stackWithCauses,\n messageWithCauses\n}\n", "'use strict'\n\nconst seen = Symbol('circular-ref-tag')\nconst rawSymbol = Symbol('pino-raw-err-ref')\n\nconst pinoErrProto = Object.create({}, {\n type: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n message: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n stack: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n aggregateErrors: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoErrProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nmodule.exports = {\n pinoErrProto,\n pinoErrorSymbols: {\n seen,\n rawSymbol\n }\n}\n", "'use strict'\n\nmodule.exports = errSerializer\n\nconst { messageWithCauses, stackWithCauses, isErrorLike } = require('./err-helpers')\nconst { pinoErrProto, pinoErrorSymbols } = require('./err-proto')\nconst { seen } = pinoErrorSymbols\n\nconst { toString } = Object.prototype\n\nfunction errSerializer (err) {\n if (!isErrorLike(err)) {\n return err\n }\n\n err[seen] = undefined // tag to prevent re-looking at this\n const _err = Object.create(pinoErrProto)\n _err.type = toString.call(err.constructor) === '[object Function]'\n ? err.constructor.name\n : err.name\n _err.message = messageWithCauses(err)\n _err.stack = stackWithCauses(err)\n\n if (Array.isArray(err.errors)) {\n _err.aggregateErrors = err.errors.map(err => errSerializer(err))\n }\n\n for (const key in err) {\n if (_err[key] === undefined) {\n const val = err[key]\n if (isErrorLike(val)) {\n // We append cause messages and stacks to _err, therefore skipping causes here\n if (key !== 'cause' && !Object.prototype.hasOwnProperty.call(val, seen)) {\n _err[key] = errSerializer(val)\n }\n } else {\n _err[key] = val\n }\n }\n }\n\n delete err[seen] // clean up tag in case err is serialized again later\n _err.raw = err\n return _err\n}\n", "'use strict'\n\nmodule.exports = errWithCauseSerializer\n\nconst { isErrorLike } = require('./err-helpers')\nconst { pinoErrProto, pinoErrorSymbols } = require('./err-proto')\nconst { seen } = pinoErrorSymbols\n\nconst { toString } = Object.prototype\n\nfunction errWithCauseSerializer (err) {\n if (!isErrorLike(err)) {\n return err\n }\n\n err[seen] = undefined // tag to prevent re-looking at this\n const _err = Object.create(pinoErrProto)\n _err.type = toString.call(err.constructor) === '[object Function]'\n ? err.constructor.name\n : err.name\n _err.message = err.message\n _err.stack = err.stack\n\n if (Array.isArray(err.errors)) {\n _err.aggregateErrors = err.errors.map(err => errWithCauseSerializer(err))\n }\n\n if (isErrorLike(err.cause) && !Object.prototype.hasOwnProperty.call(err.cause, seen)) {\n _err.cause = errWithCauseSerializer(err.cause)\n }\n\n for (const key in err) {\n if (_err[key] === undefined) {\n const val = err[key]\n if (isErrorLike(val)) {\n if (!Object.prototype.hasOwnProperty.call(val, seen)) {\n _err[key] = errWithCauseSerializer(val)\n }\n } else {\n _err[key] = val\n }\n }\n }\n\n delete err[seen] // clean up tag in case err is serialized again later\n _err.raw = err\n return _err\n}\n", "'use strict'\n\nmodule.exports = {\n mapHttpRequest,\n reqSerializer\n}\n\nconst rawSymbol = Symbol('pino-raw-req-ref')\nconst pinoReqProto = Object.create({}, {\n id: {\n enumerable: true,\n writable: true,\n value: ''\n },\n method: {\n enumerable: true,\n writable: true,\n value: ''\n },\n url: {\n enumerable: true,\n writable: true,\n value: ''\n },\n query: {\n enumerable: true,\n writable: true,\n value: ''\n },\n params: {\n enumerable: true,\n writable: true,\n value: ''\n },\n headers: {\n enumerable: true,\n writable: true,\n value: {}\n },\n remoteAddress: {\n enumerable: true,\n writable: true,\n value: ''\n },\n remotePort: {\n enumerable: true,\n writable: true,\n value: ''\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoReqProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nfunction reqSerializer (req) {\n // req.info is for hapi compat.\n const connection = req.info || req.socket\n const _req = Object.create(pinoReqProto)\n _req.id = (typeof req.id === 'function' ? req.id() : (req.id || (req.info ? req.info.id : undefined)))\n _req.method = req.method\n // req.originalUrl is for expressjs compat.\n if (req.originalUrl) {\n _req.url = req.originalUrl\n } else {\n const path = req.path\n // path for safe hapi compat.\n _req.url = typeof path === 'string' ? path : (req.url ? req.url.path || req.url : undefined)\n }\n\n if (req.query) {\n _req.query = req.query\n }\n\n if (req.params) {\n _req.params = req.params\n }\n\n _req.headers = req.headers\n _req.remoteAddress = connection && connection.remoteAddress\n _req.remotePort = connection && connection.remotePort\n // req.raw is for hapi compat/equivalence\n _req.raw = req.raw || req\n return _req\n}\n\nfunction mapHttpRequest (req) {\n return {\n req: reqSerializer(req)\n }\n}\n", "'use strict'\n\nmodule.exports = {\n mapHttpResponse,\n resSerializer\n}\n\nconst rawSymbol = Symbol('pino-raw-res-ref')\nconst pinoResProto = Object.create({}, {\n statusCode: {\n enumerable: true,\n writable: true,\n value: 0\n },\n headers: {\n enumerable: true,\n writable: true,\n value: ''\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoResProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nfunction resSerializer (res) {\n const _res = Object.create(pinoResProto)\n _res.statusCode = res.headersSent ? res.statusCode : null\n _res.headers = res.getHeaders ? res.getHeaders() : res._headers\n _res.raw = res\n return _res\n}\n\nfunction mapHttpResponse (res) {\n return {\n res: resSerializer(res)\n }\n}\n", "'use strict'\n\nconst errSerializer = require('./lib/err')\nconst errWithCauseSerializer = require('./lib/err-with-cause')\nconst reqSerializers = require('./lib/req')\nconst resSerializers = require('./lib/res')\n\nmodule.exports = {\n err: errSerializer,\n errWithCause: errWithCauseSerializer,\n mapHttpRequest: reqSerializers.mapHttpRequest,\n mapHttpResponse: resSerializers.mapHttpResponse,\n req: reqSerializers.reqSerializer,\n res: resSerializers.resSerializer,\n\n wrapErrorSerializer: function wrapErrorSerializer (customSerializer) {\n if (customSerializer === errSerializer) return customSerializer\n return function wrapErrSerializer (err) {\n return customSerializer(errSerializer(err))\n }\n },\n\n wrapRequestSerializer: function wrapRequestSerializer (customSerializer) {\n if (customSerializer === reqSerializers.reqSerializer) return customSerializer\n return function wrappedReqSerializer (req) {\n return customSerializer(reqSerializers.reqSerializer(req))\n }\n },\n\n wrapResponseSerializer: function wrapResponseSerializer (customSerializer) {\n if (customSerializer === resSerializers.resSerializer) return customSerializer\n return function wrappedResSerializer (res) {\n return customSerializer(resSerializers.resSerializer(res))\n }\n }\n}\n", "'use strict'\n\nfunction noOpPrepareStackTrace (_, stack) {\n return stack\n}\n\nmodule.exports = function getCallers () {\n const originalPrepare = Error.prepareStackTrace\n Error.prepareStackTrace = noOpPrepareStackTrace\n const stack = new Error().stack\n Error.prepareStackTrace = originalPrepare\n\n if (!Array.isArray(stack)) {\n return undefined\n }\n\n const entries = stack.slice(2)\n\n const fileNames = []\n\n for (const entry of entries) {\n if (!entry) {\n continue\n }\n\n fileNames.push(entry.getFileName())\n }\n\n return fileNames\n}\n", "'use strict'\n\nmodule.exports = validator\n\nfunction validator (opts = {}) {\n const {\n ERR_PATHS_MUST_BE_STRINGS = () => 'fast-redact - Paths must be (non-empty) strings',\n ERR_INVALID_PATH = (s) => `fast-redact \u2013 Invalid path (${s})`\n } = opts\n\n return function validate ({ paths }) {\n paths.forEach((s) => {\n if (typeof s !== 'string') {\n throw Error(ERR_PATHS_MUST_BE_STRINGS())\n }\n try {\n if (/\u3007/.test(s)) throw Error()\n const expr = (s[0] === '[' ? '' : '.') + s.replace(/^\\*/, '\u3007').replace(/\\.\\*/g, '.\u3007').replace(/\\[\\*\\]/g, '[\u3007]')\n if (/\\n|\\r|;/.test(expr)) throw Error()\n if (/\\/\\*/.test(expr)) throw Error()\n /* eslint-disable-next-line */\n Function(`\n 'use strict'\n const o = new Proxy({}, { get: () => o, set: () => { throw Error() } });\n const \u3007 = null;\n o${expr}\n if ([o${expr}].length !== 1) throw Error()`)()\n } catch (e) {\n throw Error(ERR_INVALID_PATH(s))\n }\n })\n }\n}\n", "'use strict'\n\nmodule.exports = /[^.[\\]]+|\\[((?:.)*?)\\]/g\n\n/*\nRegular expression explanation:\n\nAlt 1: /[^.[\\]]+/ - Match one or more characters that are *not* a dot (.)\n opening square bracket ([) or closing square bracket (])\n\nAlt 2: /\\[((?:.)*?)\\]/ - If the char IS dot or square bracket, then create a capture\n group (which will be capture group $1) that matches anything\n within square brackets. Expansion is lazy so it will\n stop matching as soon as the first closing bracket is met `]`\n (rather than continuing to match until the final closing bracket).\n*/\n", "'use strict'\n\nconst rx = require('./rx')\n\nmodule.exports = parse\n\nfunction parse ({ paths }) {\n const wildcards = []\n var wcLen = 0\n const secret = paths.reduce(function (o, strPath, ix) {\n var path = strPath.match(rx).map((p) => p.replace(/'|\"|`/g, ''))\n const leadingBracket = strPath[0] === '['\n path = path.map((p) => {\n if (p[0] === '[') return p.substr(1, p.length - 2)\n else return p\n })\n const star = path.indexOf('*')\n if (star > -1) {\n const before = path.slice(0, star)\n const beforeStr = before.join('.')\n const after = path.slice(star + 1, path.length)\n const nested = after.length > 0\n wcLen++\n wildcards.push({\n before,\n beforeStr,\n after,\n nested\n })\n } else {\n o[strPath] = {\n path: path,\n val: undefined,\n precensored: false,\n circle: '',\n escPath: JSON.stringify(strPath),\n leadingBracket: leadingBracket\n }\n }\n return o\n }, {})\n\n return { wildcards, wcLen, secret }\n}\n", "'use strict'\n\nconst rx = require('./rx')\n\nmodule.exports = redactor\n\nfunction redactor ({ secret, serialize, wcLen, strict, isCensorFct, censorFctTakesPath }, state) {\n /* eslint-disable-next-line */\n const redact = Function('o', `\n if (typeof o !== 'object' || o == null) {\n ${strictImpl(strict, serialize)}\n }\n const { censor, secret } = this\n const originalSecret = {}\n const secretKeys = Object.keys(secret)\n for (var i = 0; i < secretKeys.length; i++) {\n originalSecret[secretKeys[i]] = secret[secretKeys[i]]\n }\n\n ${redactTmpl(secret, isCensorFct, censorFctTakesPath)}\n this.compileRestore()\n ${dynamicRedactTmpl(wcLen > 0, isCensorFct, censorFctTakesPath)}\n this.secret = originalSecret\n ${resultTmpl(serialize)}\n `).bind(state)\n\n redact.state = state\n\n if (serialize === false) {\n redact.restore = (o) => state.restore(o)\n }\n\n return redact\n}\n\nfunction redactTmpl (secret, isCensorFct, censorFctTakesPath) {\n return Object.keys(secret).map((path) => {\n const { escPath, leadingBracket, path: arrPath } = secret[path]\n const skip = leadingBracket ? 1 : 0\n const delim = leadingBracket ? '' : '.'\n const hops = []\n var match\n while ((match = rx.exec(path)) !== null) {\n const [ , ix ] = match\n const { index, input } = match\n if (index > skip) hops.push(input.substring(0, index - (ix ? 0 : 1)))\n }\n var existence = hops.map((p) => `o${delim}${p}`).join(' && ')\n if (existence.length === 0) existence += `o${delim}${path} != null`\n else existence += ` && o${delim}${path} != null`\n\n const circularDetection = `\n switch (true) {\n ${hops.reverse().map((p) => `\n case o${delim}${p} === censor:\n secret[${escPath}].circle = ${JSON.stringify(p)}\n break\n `).join('\\n')}\n }\n `\n\n const censorArgs = censorFctTakesPath\n ? `val, ${JSON.stringify(arrPath)}`\n : `val`\n\n return `\n if (${existence}) {\n const val = o${delim}${path}\n if (val === censor) {\n secret[${escPath}].precensored = true\n } else {\n secret[${escPath}].val = val\n o${delim}${path} = ${isCensorFct ? `censor(${censorArgs})` : 'censor'}\n ${circularDetection}\n }\n }\n `\n }).join('\\n')\n}\n\nfunction dynamicRedactTmpl (hasWildcards, isCensorFct, censorFctTakesPath) {\n return hasWildcards === true ? `\n {\n const { wildcards, wcLen, groupRedact, nestedRedact } = this\n for (var i = 0; i < wcLen; i++) {\n const { before, beforeStr, after, nested } = wildcards[i]\n if (nested === true) {\n secret[beforeStr] = secret[beforeStr] || []\n nestedRedact(secret[beforeStr], o, before, after, censor, ${isCensorFct}, ${censorFctTakesPath})\n } else secret[beforeStr] = groupRedact(o, before, censor, ${isCensorFct}, ${censorFctTakesPath})\n }\n }\n ` : ''\n}\n\nfunction resultTmpl (serialize) {\n return serialize === false ? `return o` : `\n var s = this.serialize(o)\n this.restore(o)\n return s\n `\n}\n\nfunction strictImpl (strict, serialize) {\n return strict === true\n ? `throw Error('fast-redact: primitives cannot be redacted')`\n : serialize === false ? `return o` : `return this.serialize(o)`\n}\n", "'use strict'\n\nmodule.exports = {\n groupRedact,\n groupRestore,\n nestedRedact,\n nestedRestore\n}\n\nfunction groupRestore ({ keys, values, target }) {\n if (target == null || typeof target === 'string') return\n const length = keys.length\n for (var i = 0; i < length; i++) {\n const k = keys[i]\n target[k] = values[i]\n }\n}\n\nfunction groupRedact (o, path, censor, isCensorFct, censorFctTakesPath) {\n const target = get(o, path)\n if (target == null || typeof target === 'string') return { keys: null, values: null, target, flat: true }\n const keys = Object.keys(target)\n const keysLength = keys.length\n const pathLength = path.length\n const pathWithKey = censorFctTakesPath ? [...path] : undefined\n const values = new Array(keysLength)\n\n for (var i = 0; i < keysLength; i++) {\n const key = keys[i]\n values[i] = target[key]\n\n if (censorFctTakesPath) {\n pathWithKey[pathLength] = key\n target[key] = censor(target[key], pathWithKey)\n } else if (isCensorFct) {\n target[key] = censor(target[key])\n } else {\n target[key] = censor\n }\n }\n return { keys, values, target, flat: true }\n}\n\n/**\n * @param {RestoreInstruction[]} instructions a set of instructions for restoring values to objects\n */\nfunction nestedRestore (instructions) {\n for (let i = 0; i < instructions.length; i++) {\n const { target, path, value } = instructions[i]\n let current = target\n for (let i = path.length - 1; i > 0; i--) {\n current = current[path[i]]\n }\n current[path[0]] = value\n }\n}\n\nfunction nestedRedact (store, o, path, ns, censor, isCensorFct, censorFctTakesPath) {\n const target = get(o, path)\n if (target == null) return\n const keys = Object.keys(target)\n const keysLength = keys.length\n for (var i = 0; i < keysLength; i++) {\n const key = keys[i]\n specialSet(store, target, key, path, ns, censor, isCensorFct, censorFctTakesPath)\n }\n return store\n}\n\nfunction has (obj, prop) {\n return obj !== undefined && obj !== null\n ? ('hasOwn' in Object ? Object.hasOwn(obj, prop) : Object.prototype.hasOwnProperty.call(obj, prop))\n : false\n}\n\nfunction specialSet (store, o, k, path, afterPath, censor, isCensorFct, censorFctTakesPath) {\n const afterPathLen = afterPath.length\n const lastPathIndex = afterPathLen - 1\n const originalKey = k\n var i = -1\n var n\n var nv\n var ov\n var oov = null\n var wc = null\n var kIsWc\n var wcov\n var consecutive = false\n var level = 0\n // need to track depth of the `redactPath` tree\n var depth = 0\n var redactPathCurrent = tree()\n ov = n = o[k]\n if (typeof n !== 'object') return\n while (n != null && ++i < afterPathLen) {\n depth += 1\n k = afterPath[i]\n oov = ov\n if (k !== '*' && !wc && !(typeof n === 'object' && k in n)) {\n break\n }\n if (k === '*') {\n if (wc === '*') {\n consecutive = true\n }\n wc = k\n if (i !== lastPathIndex) {\n continue\n }\n }\n if (wc) {\n const wcKeys = Object.keys(n)\n for (var j = 0; j < wcKeys.length; j++) {\n const wck = wcKeys[j]\n wcov = n[wck]\n kIsWc = k === '*'\n if (consecutive) {\n redactPathCurrent = node(redactPathCurrent, wck, depth)\n level = i\n ov = iterateNthLevel(wcov, level - 1, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, o[originalKey], depth + 1)\n } else {\n if (kIsWc || (typeof wcov === 'object' && wcov !== null && k in wcov)) {\n if (kIsWc) {\n ov = wcov\n } else {\n ov = wcov[k]\n }\n nv = (i !== lastPathIndex)\n ? ov\n : (isCensorFct\n ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))\n : censor)\n if (kIsWc) {\n const rv = restoreInstr(node(redactPathCurrent, wck, depth), ov, o[originalKey])\n store.push(rv)\n n[wck] = nv\n } else {\n if (wcov[k] === nv) {\n // pass\n } else if ((nv === undefined && censor !== undefined) || (has(wcov, k) && nv === ov)) {\n redactPathCurrent = node(redactPathCurrent, wck, depth)\n } else {\n redactPathCurrent = node(redactPathCurrent, wck, depth)\n const rv = restoreInstr(node(redactPathCurrent, k, depth + 1), ov, o[originalKey])\n store.push(rv)\n wcov[k] = nv\n }\n }\n }\n }\n }\n wc = null\n } else {\n ov = n[k]\n redactPathCurrent = node(redactPathCurrent, k, depth)\n nv = (i !== lastPathIndex)\n ? ov\n : (isCensorFct\n ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))\n : censor)\n if ((has(n, k) && nv === ov) || (nv === undefined && censor !== undefined)) {\n // pass\n } else {\n const rv = restoreInstr(redactPathCurrent, ov, o[originalKey])\n store.push(rv)\n n[k] = nv\n }\n n = n[k]\n }\n if (typeof n !== 'object') break\n // prevent circular structure, see https://github.com/pinojs/pino/issues/1513\n if (ov === oov || typeof ov === 'undefined') {\n // pass\n }\n }\n}\n\nfunction get (o, p) {\n var i = -1\n var l = p.length\n var n = o\n while (n != null && ++i < l) {\n n = n[p[i]]\n }\n return n\n}\n\nfunction iterateNthLevel (wcov, level, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, parent, depth) {\n if (level === 0) {\n if (kIsWc || (typeof wcov === 'object' && wcov !== null && k in wcov)) {\n if (kIsWc) {\n ov = wcov\n } else {\n ov = wcov[k]\n }\n nv = (i !== lastPathIndex)\n ? ov\n : (isCensorFct\n ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))\n : censor)\n if (kIsWc) {\n const rv = restoreInstr(redactPathCurrent, ov, parent)\n store.push(rv)\n n[wck] = nv\n } else {\n if (wcov[k] === nv) {\n // pass\n } else if ((nv === undefined && censor !== undefined) || (has(wcov, k) && nv === ov)) {\n // pass\n } else {\n const rv = restoreInstr(node(redactPathCurrent, k, depth + 1), ov, parent)\n store.push(rv)\n wcov[k] = nv\n }\n }\n }\n }\n for (const key in wcov) {\n if (typeof wcov[key] === 'object') {\n redactPathCurrent = node(redactPathCurrent, key, depth)\n iterateNthLevel(wcov[key], level - 1, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, parent, depth + 1)\n }\n }\n}\n\n/**\n * @typedef {object} TreeNode\n * @prop {TreeNode} [parent] reference to the parent of this node in the tree, or `null` if there is no parent\n * @prop {string} key the key that this node represents (key here being part of the path being redacted\n * @prop {TreeNode[]} children the child nodes of this node\n * @prop {number} depth the depth of this node in the tree\n */\n\n/**\n * instantiate a new, empty tree\n * @returns {TreeNode}\n */\nfunction tree () {\n return { parent: null, key: null, children: [], depth: 0 }\n}\n\n/**\n * creates a new node in the tree, attaching it as a child of the provided parent node\n * if the specified depth matches the parent depth, adds the new node as a _sibling_ of the parent instead\n * @param {TreeNode} parent the parent node to add a new node to (if the parent depth matches the provided `depth` value, will instead add as a sibling of this\n * @param {string} key the key that the new node represents (key here being part of the path being redacted)\n * @param {number} depth the depth of the new node in the tree - used to determing whether to add the new node as a child or sibling of the provided `parent` node\n * @returns {TreeNode} a reference to the newly created node in the tree\n */\nfunction node (parent, key, depth) {\n if (parent.depth === depth) {\n return node(parent.parent, key, depth)\n }\n\n var child = {\n parent,\n key,\n depth,\n children: []\n }\n\n parent.children.push(child)\n\n return child\n}\n\n/**\n * @typedef {object} RestoreInstruction\n * @prop {string[]} path a reverse-order path that can be used to find the correct insertion point to restore a `value` for the given `parent` object\n * @prop {*} value the value to restore\n * @prop {object} target the object to restore the `value` in\n */\n\n/**\n * create a restore instruction for the given redactPath node\n * generates a path in reverse order by walking up the redactPath tree\n * @param {TreeNode} node a tree node that should be at the bottom of the redact path (i.e. have no children) - this will be used to walk up the redact path tree to construct the path needed to restore\n * @param {*} value the value to restore\n * @param {object} target a reference to the parent object to apply the restore instruction to\n * @returns {RestoreInstruction} an instruction used to restore a nested value for a specific object\n */\nfunction restoreInstr (node, value, target) {\n let current = node\n const path = []\n do {\n path.push(current.key)\n current = current.parent\n } while (current.parent != null)\n\n return { path, value, target }\n}\n", "'use strict'\n\nconst { groupRestore, nestedRestore } = require('./modifiers')\n\nmodule.exports = restorer\n\nfunction restorer () {\n return function compileRestore () {\n if (this.restore) {\n this.restore.state.secret = this.secret\n return\n }\n const { secret, wcLen } = this\n const paths = Object.keys(secret)\n const resetters = resetTmpl(secret, paths)\n const hasWildcards = wcLen > 0\n const state = hasWildcards ? { secret, groupRestore, nestedRestore } : { secret }\n /* eslint-disable-next-line */\n this.restore = Function(\n 'o',\n restoreTmpl(resetters, paths, hasWildcards)\n ).bind(state)\n this.restore.state = state\n }\n}\n\n/**\n * Mutates the original object to be censored by restoring its original values\n * prior to censoring.\n *\n * @param {object} secret Compiled object describing which target fields should\n * be censored and the field states.\n * @param {string[]} paths The list of paths to censor as provided at\n * initialization time.\n *\n * @returns {string} String of JavaScript to be used by `Function()`. The\n * string compiles to the function that does the work in the description.\n */\nfunction resetTmpl (secret, paths) {\n return paths.map((path) => {\n const { circle, escPath, leadingBracket } = secret[path]\n const delim = leadingBracket ? '' : '.'\n const reset = circle\n ? `o.${circle} = secret[${escPath}].val`\n : `o${delim}${path} = secret[${escPath}].val`\n const clear = `secret[${escPath}].val = undefined`\n return `\n if (secret[${escPath}].val !== undefined) {\n try { ${reset} } catch (e) {}\n ${clear}\n }\n `\n }).join('')\n}\n\n/**\n * Creates the body of the restore function\n *\n * Restoration of the redacted object happens\n * backwards, in reverse order of redactions,\n * so that repeated redactions on the same object\n * property can be eventually rolled back to the\n * original value.\n *\n * This way dynamic redactions are restored first,\n * starting from the last one working backwards and\n * followed by the static ones.\n *\n * @returns {string} the body of the restore function\n */\nfunction restoreTmpl (resetters, paths, hasWildcards) {\n const dynamicReset = hasWildcards === true ? `\n const keys = Object.keys(secret)\n const len = keys.length\n for (var i = len - 1; i >= ${paths.length}; i--) {\n const k = keys[i]\n const o = secret[k]\n if (o) {\n if (o.flat === true) this.groupRestore(o)\n else this.nestedRestore(o)\n secret[k] = null\n }\n }\n ` : ''\n\n return `\n const secret = this.secret\n ${dynamicReset}\n ${resetters}\n return o\n `\n}\n", "'use strict'\n\nmodule.exports = state\n\nfunction state (o) {\n const {\n secret,\n censor,\n compileRestore,\n serialize,\n groupRedact,\n nestedRedact,\n wildcards,\n wcLen\n } = o\n const builder = [{ secret, censor, compileRestore }]\n if (serialize !== false) builder.push({ serialize })\n if (wcLen > 0) builder.push({ groupRedact, nestedRedact, wildcards, wcLen })\n return Object.assign(...builder)\n}\n", "'use strict'\n\nconst validator = require('./lib/validator')\nconst parse = require('./lib/parse')\nconst redactor = require('./lib/redactor')\nconst restorer = require('./lib/restorer')\nconst { groupRedact, nestedRedact } = require('./lib/modifiers')\nconst state = require('./lib/state')\nconst rx = require('./lib/rx')\nconst validate = validator()\nconst noop = (o) => o\nnoop.restore = noop\n\nconst DEFAULT_CENSOR = '[REDACTED]'\nfastRedact.rx = rx\nfastRedact.validator = validator\n\nmodule.exports = fastRedact\n\nfunction fastRedact (opts = {}) {\n const paths = Array.from(new Set(opts.paths || []))\n const serialize = 'serialize' in opts ? (\n opts.serialize === false ? opts.serialize\n : (typeof opts.serialize === 'function' ? opts.serialize : JSON.stringify)\n ) : JSON.stringify\n const remove = opts.remove\n if (remove === true && serialize !== JSON.stringify) {\n throw Error('fast-redact \u2013 remove option may only be set when serializer is JSON.stringify')\n }\n const censor = remove === true\n ? undefined\n : 'censor' in opts ? opts.censor : DEFAULT_CENSOR\n\n const isCensorFct = typeof censor === 'function'\n const censorFctTakesPath = isCensorFct && censor.length > 1\n\n if (paths.length === 0) return serialize || noop\n\n validate({ paths, serialize, censor })\n\n const { wildcards, wcLen, secret } = parse({ paths, censor })\n\n const compileRestore = restorer()\n const strict = 'strict' in opts ? opts.strict : true\n\n return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({\n secret,\n censor,\n compileRestore,\n serialize,\n groupRedact,\n nestedRedact,\n wildcards,\n wcLen\n }))\n}\n", "'use strict'\n\nconst setLevelSym = Symbol('pino.setLevel')\nconst getLevelSym = Symbol('pino.getLevel')\nconst levelValSym = Symbol('pino.levelVal')\nconst levelCompSym = Symbol('pino.levelComp')\nconst useLevelLabelsSym = Symbol('pino.useLevelLabels')\nconst useOnlyCustomLevelsSym = Symbol('pino.useOnlyCustomLevels')\nconst mixinSym = Symbol('pino.mixin')\n\nconst lsCacheSym = Symbol('pino.lsCache')\nconst chindingsSym = Symbol('pino.chindings')\n\nconst asJsonSym = Symbol('pino.asJson')\nconst writeSym = Symbol('pino.write')\nconst redactFmtSym = Symbol('pino.redactFmt')\n\nconst timeSym = Symbol('pino.time')\nconst timeSliceIndexSym = Symbol('pino.timeSliceIndex')\nconst streamSym = Symbol('pino.stream')\nconst stringifySym = Symbol('pino.stringify')\nconst stringifySafeSym = Symbol('pino.stringifySafe')\nconst stringifiersSym = Symbol('pino.stringifiers')\nconst endSym = Symbol('pino.end')\nconst formatOptsSym = Symbol('pino.formatOpts')\nconst messageKeySym = Symbol('pino.messageKey')\nconst errorKeySym = Symbol('pino.errorKey')\nconst nestedKeySym = Symbol('pino.nestedKey')\nconst nestedKeyStrSym = Symbol('pino.nestedKeyStr')\nconst mixinMergeStrategySym = Symbol('pino.mixinMergeStrategy')\nconst msgPrefixSym = Symbol('pino.msgPrefix')\n\nconst wildcardFirstSym = Symbol('pino.wildcardFirst')\n\n// public symbols, no need to use the same pino\n// version for these\nconst serializersSym = Symbol.for('pino.serializers')\nconst formattersSym = Symbol.for('pino.formatters')\nconst hooksSym = Symbol.for('pino.hooks')\nconst needsMetadataGsym = Symbol.for('pino.metadata')\n\nmodule.exports = {\n setLevelSym,\n getLevelSym,\n levelValSym,\n levelCompSym,\n useLevelLabelsSym,\n mixinSym,\n lsCacheSym,\n chindingsSym,\n asJsonSym,\n writeSym,\n serializersSym,\n redactFmtSym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n stringifySym,\n stringifySafeSym,\n stringifiersSym,\n endSym,\n formatOptsSym,\n messageKeySym,\n errorKeySym,\n nestedKeySym,\n wildcardFirstSym,\n needsMetadataGsym,\n useOnlyCustomLevelsSym,\n formattersSym,\n hooksSym,\n nestedKeyStrSym,\n mixinMergeStrategySym,\n msgPrefixSym\n}\n", "'use strict'\n\nconst fastRedact = require('fast-redact')\nconst { redactFmtSym, wildcardFirstSym } = require('./symbols')\nconst { rx, validator } = fastRedact\n\nconst validate = validator({\n ERR_PATHS_MUST_BE_STRINGS: () => 'pino \u2013 redacted paths must be strings',\n ERR_INVALID_PATH: (s) => `pino \u2013 redact paths array contains an invalid path (${s})`\n})\n\nconst CENSOR = '[Redacted]'\nconst strict = false // TODO should this be configurable?\n\nfunction redaction (opts, serialize) {\n const { paths, censor } = handle(opts)\n\n const shape = paths.reduce((o, str) => {\n rx.lastIndex = 0\n const first = rx.exec(str)\n const next = rx.exec(str)\n\n // ns is the top-level path segment, brackets + quoting removed.\n let ns = first[1] !== undefined\n ? first[1].replace(/^(?:\"|'|`)(.*)(?:\"|'|`)$/, '$1')\n : first[0]\n\n if (ns === '*') {\n ns = wildcardFirstSym\n }\n\n // top level key:\n if (next === null) {\n o[ns] = null\n return o\n }\n\n // path with at least two segments:\n // if ns is already redacted at the top level, ignore lower level redactions\n if (o[ns] === null) {\n return o\n }\n\n const { index } = next\n const nextPath = `${str.substr(index, str.length - 1)}`\n\n o[ns] = o[ns] || []\n\n // shape is a mix of paths beginning with literal values and wildcard\n // paths [ \"a.b.c\", \"*.b.z\" ] should reduce to a shape of\n // { \"a\": [ \"b.c\", \"b.z\" ], *: [ \"b.z\" ] }\n // note: \"b.z\" is in both \"a\" and * arrays because \"a\" matches the wildcard.\n // (* entry has wildcardFirstSym as key)\n if (ns !== wildcardFirstSym && o[ns].length === 0) {\n // first time ns's get all '*' redactions so far\n o[ns].push(...(o[wildcardFirstSym] || []))\n }\n\n if (ns === wildcardFirstSym) {\n // new * path gets added to all previously registered literal ns's.\n Object.keys(o).forEach(function (k) {\n if (o[k]) {\n o[k].push(nextPath)\n }\n })\n }\n\n o[ns].push(nextPath)\n return o\n }, {})\n\n // the redactor assigned to the format symbol key\n // provides top level redaction for instances where\n // an object is interpolated into the msg string\n const result = {\n [redactFmtSym]: fastRedact({ paths, censor, serialize, strict })\n }\n\n const topCensor = (...args) => {\n return typeof censor === 'function' ? serialize(censor(...args)) : serialize(censor)\n }\n\n return [...Object.keys(shape), ...Object.getOwnPropertySymbols(shape)].reduce((o, k) => {\n // top level key:\n if (shape[k] === null) {\n o[k] = (value) => topCensor(value, [k])\n } else {\n const wrappedCensor = typeof censor === 'function'\n ? (value, path) => {\n return censor(value, [k, ...path])\n }\n : censor\n o[k] = fastRedact({\n paths: shape[k],\n censor: wrappedCensor,\n serialize,\n strict\n })\n }\n return o\n }, result)\n}\n\nfunction handle (opts) {\n if (Array.isArray(opts)) {\n opts = { paths: opts, censor: CENSOR }\n validate(opts)\n return opts\n }\n let { paths, censor = CENSOR, remove } = opts\n if (Array.isArray(paths) === false) { throw Error('pino \u2013 redact must contain an array of strings') }\n if (remove === true) censor = undefined\n validate({ paths, censor })\n\n return { paths, censor }\n}\n\nmodule.exports = redaction\n", "'use strict'\n\nconst nullTime = () => ''\n\nconst epochTime = () => `,\"time\":${Date.now()}`\n\nconst unixTime = () => `,\"time\":${Math.round(Date.now() / 1000.0)}`\n\nconst isoTime = () => `,\"time\":\"${new Date(Date.now()).toISOString()}\"` // using Date.now() for testability\n\nmodule.exports = { nullTime, epochTime, unixTime, isoTime }\n", "'use strict'\nfunction tryStringify (o) {\n try { return JSON.stringify(o) } catch(e) { return '\"[Circular]\"' }\n}\n\nmodule.exports = format\n\nfunction format(f, args, opts) {\n var ss = (opts && opts.stringify) || tryStringify\n var offset = 1\n if (typeof f === 'object' && f !== null) {\n var len = args.length + offset\n if (len === 1) return f\n var objects = new Array(len)\n objects[0] = ss(f)\n for (var index = 1; index < len; index++) {\n objects[index] = ss(args[index])\n }\n return objects.join(' ')\n }\n if (typeof f !== 'string') {\n return f\n }\n var argLen = args.length\n if (argLen === 0) return f\n var str = ''\n var a = 1 - offset\n var lastPos = -1\n var flen = (f && f.length) || 0\n for (var i = 0; i < flen;) {\n if (f.charCodeAt(i) === 37 && i + 1 < flen) {\n lastPos = lastPos > -1 ? lastPos : 0\n switch (f.charCodeAt(i + 1)) {\n case 100: // 'd'\n case 102: // 'f'\n if (a >= argLen)\n break\n if (args[a] == null) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += Number(args[a])\n lastPos = i + 2\n i++\n break\n case 105: // 'i'\n if (a >= argLen)\n break\n if (args[a] == null) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += Math.floor(Number(args[a]))\n lastPos = i + 2\n i++\n break\n case 79: // 'O'\n case 111: // 'o'\n case 106: // 'j'\n if (a >= argLen)\n break\n if (args[a] === undefined) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n var type = typeof args[a]\n if (type === 'string') {\n str += '\\'' + args[a] + '\\''\n lastPos = i + 2\n i++\n break\n }\n if (type === 'function') {\n str += args[a].name || ''\n lastPos = i + 2\n i++\n break\n }\n str += ss(args[a])\n lastPos = i + 2\n i++\n break\n case 115: // 's'\n if (a >= argLen)\n break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += String(args[a])\n lastPos = i + 2\n i++\n break\n case 37: // '%'\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += '%'\n lastPos = i + 2\n i++\n a--\n break\n }\n ++a\n }\n ++i\n }\n if (lastPos === -1)\n return f\n else if (lastPos < flen) {\n str += f.slice(lastPos)\n }\n\n return str\n}\n", "'use strict'\n\n/* global SharedArrayBuffer, Atomics */\n\nif (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') {\n const nil = new Int32Array(new SharedArrayBuffer(4))\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n\n Atomics.wait(nil, 0, 0, Number(ms))\n }\n module.exports = sleep\n} else {\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n const target = Date.now() + Number(ms)\n while (target > Date.now()){}\n }\n\n module.exports = sleep\n\n}\n", "'use strict'\n\nconst fs = require('fs')\nconst EventEmitter = require('events')\nconst inherits = require('util').inherits\nconst path = require('path')\nconst sleep = require('atomic-sleep')\nconst assert = require('assert')\n\nconst BUSY_WRITE_TIMEOUT = 100\nconst kEmptyBuffer = Buffer.allocUnsafe(0)\n\n// 16 KB. Don't write more than docker buffer size.\n// https://github.com/moby/moby/blob/513ec73831269947d38a644c278ce3cac36783b2/daemon/logger/copier.go#L13\nconst MAX_WRITE = 16 * 1024\n\nconst kContentModeBuffer = 'buffer'\nconst kContentModeUtf8 = 'utf8'\n\nconst [major, minor] = (process.versions.node || '0.0').split('.').map(Number)\nconst kCopyBuffer = major >= 22 && minor >= 7\n\nfunction openFile (file, sonic) {\n sonic._opening = true\n sonic._writing = true\n sonic._asyncDrainScheduled = false\n\n // NOTE: 'error' and 'ready' events emitted below only relevant when sonic.sync===false\n // for sync mode, there is no way to add a listener that will receive these\n\n function fileOpened (err, fd) {\n if (err) {\n sonic._reopening = false\n sonic._writing = false\n sonic._opening = false\n\n if (sonic.sync) {\n process.nextTick(() => {\n if (sonic.listenerCount('error') > 0) {\n sonic.emit('error', err)\n }\n })\n } else {\n sonic.emit('error', err)\n }\n return\n }\n\n const reopening = sonic._reopening\n\n sonic.fd = fd\n sonic.file = file\n sonic._reopening = false\n sonic._opening = false\n sonic._writing = false\n\n if (sonic.sync) {\n process.nextTick(() => sonic.emit('ready'))\n } else {\n sonic.emit('ready')\n }\n\n if (sonic.destroyed) {\n return\n }\n\n // start\n if ((!sonic._writing && sonic._len > sonic.minLength) || sonic._flushPending) {\n sonic._actualWrite()\n } else if (reopening) {\n process.nextTick(() => sonic.emit('drain'))\n }\n }\n\n const flags = sonic.append ? 'a' : 'w'\n const mode = sonic.mode\n\n if (sonic.sync) {\n try {\n if (sonic.mkdir) fs.mkdirSync(path.dirname(file), { recursive: true })\n const fd = fs.openSync(file, flags, mode)\n fileOpened(null, fd)\n } catch (err) {\n fileOpened(err)\n throw err\n }\n } else if (sonic.mkdir) {\n fs.mkdir(path.dirname(file), { recursive: true }, (err) => {\n if (err) return fileOpened(err)\n fs.open(file, flags, mode, fileOpened)\n })\n } else {\n fs.open(file, flags, mode, fileOpened)\n }\n}\n\nfunction SonicBoom (opts) {\n if (!(this instanceof SonicBoom)) {\n return new SonicBoom(opts)\n }\n\n let { fd, dest, minLength, maxLength, maxWrite, periodicFlush, sync, append = true, mkdir, retryEAGAIN, fsync, contentMode, mode } = opts || {}\n\n fd = fd || dest\n\n this._len = 0\n this.fd = -1\n this._bufs = []\n this._lens = []\n this._writing = false\n this._ending = false\n this._reopening = false\n this._asyncDrainScheduled = false\n this._flushPending = false\n this._hwm = Math.max(minLength || 0, 16387)\n this.file = null\n this.destroyed = false\n this.minLength = minLength || 0\n this.maxLength = maxLength || 0\n this.maxWrite = maxWrite || MAX_WRITE\n this._periodicFlush = periodicFlush || 0\n this._periodicFlushTimer = undefined\n this.sync = sync || false\n this.writable = true\n this._fsync = fsync || false\n this.append = append || false\n this.mode = mode\n this.retryEAGAIN = retryEAGAIN || (() => true)\n this.mkdir = mkdir || false\n\n let fsWriteSync\n let fsWrite\n if (contentMode === kContentModeBuffer) {\n this._writingBuf = kEmptyBuffer\n this.write = writeBuffer\n this.flush = flushBuffer\n this.flushSync = flushBufferSync\n this._actualWrite = actualWriteBuffer\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf)\n fsWrite = () => fs.write(this.fd, this._writingBuf, this.release)\n } else if (contentMode === undefined || contentMode === kContentModeUtf8) {\n this._writingBuf = ''\n this.write = write\n this.flush = flush\n this.flushSync = flushSync\n this._actualWrite = actualWrite\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf, 'utf8')\n fsWrite = () => fs.write(this.fd, this._writingBuf, 'utf8', this.release)\n } else {\n throw new Error(`SonicBoom supports \"${kContentModeUtf8}\" and \"${kContentModeBuffer}\", but passed ${contentMode}`)\n }\n\n if (typeof fd === 'number') {\n this.fd = fd\n process.nextTick(() => this.emit('ready'))\n } else if (typeof fd === 'string') {\n openFile(fd, this)\n } else {\n throw new Error('SonicBoom supports only file descriptors and files')\n }\n if (this.minLength >= this.maxWrite) {\n throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`)\n }\n\n this.release = (err, n) => {\n if (err) {\n if ((err.code === 'EAGAIN' || err.code === 'EBUSY') && this.retryEAGAIN(err, this._writingBuf.length, this._len - this._writingBuf.length)) {\n if (this.sync) {\n // This error code should not happen in sync mode, because it is\n // not using the underlining operating system asynchronous functions.\n // However it happens, and so we handle it.\n // Ref: https://github.com/pinojs/pino/issues/783\n try {\n sleep(BUSY_WRITE_TIMEOUT)\n this.release(undefined, 0)\n } catch (err) {\n this.release(err)\n }\n } else {\n // Let's give the destination some time to process the chunk.\n setTimeout(fsWrite, BUSY_WRITE_TIMEOUT)\n }\n } else {\n this._writing = false\n\n this.emit('error', err)\n }\n return\n }\n\n this.emit('write', n)\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n\n if (this._writingBuf.length) {\n if (!this.sync) {\n fsWrite()\n return\n }\n\n try {\n do {\n const n = fsWriteSync()\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n } while (this._writingBuf.length)\n } catch (err) {\n this.release(err)\n return\n }\n }\n\n if (this._fsync) {\n fs.fsyncSync(this.fd)\n }\n\n const len = this._len\n if (this._reopening) {\n this._writing = false\n this._reopening = false\n this.reopen()\n } else if (len > this.minLength) {\n this._actualWrite()\n } else if (this._ending) {\n if (len > 0) {\n this._actualWrite()\n } else {\n this._writing = false\n actualClose(this)\n }\n } else {\n this._writing = false\n if (this.sync) {\n if (!this._asyncDrainScheduled) {\n this._asyncDrainScheduled = true\n process.nextTick(emitDrain, this)\n }\n } else {\n this.emit('drain')\n }\n }\n }\n\n this.on('newListener', function (name) {\n if (name === 'drain') {\n this._asyncDrainScheduled = false\n }\n })\n\n if (this._periodicFlush !== 0) {\n this._periodicFlushTimer = setInterval(() => this.flush(null), this._periodicFlush)\n this._periodicFlushTimer.unref()\n }\n}\n\n/**\n * Release the writingBuf after fs.write n bytes data\n * @param {string | Buffer} writingBuf - currently writing buffer, usually be instance._writingBuf.\n * @param {number} len - currently buffer length, usually be instance._len.\n * @param {number} n - number of bytes fs already written\n * @returns {{writingBuf: string | Buffer, len: number}} released writingBuf and length\n */\nfunction releaseWritingBuf (writingBuf, len, n) {\n // if Buffer.byteLength is equal to n, that means writingBuf contains no multi-byte character\n if (typeof writingBuf === 'string' && Buffer.byteLength(writingBuf) !== n) {\n // Since the fs.write callback parameter `n` means how many bytes the passed of string\n // We calculate the original string length for avoiding the multi-byte character issue\n n = Buffer.from(writingBuf).subarray(0, n).toString().length\n }\n len = Math.max(len - n, 0)\n writingBuf = writingBuf.slice(n)\n return { writingBuf, len }\n}\n\nfunction emitDrain (sonic) {\n const hasListeners = sonic.listenerCount('drain') > 0\n if (!hasListeners) return\n sonic._asyncDrainScheduled = false\n sonic.emit('drain')\n}\n\ninherits(SonicBoom, EventEmitter)\n\nfunction mergeBuf (bufs, len) {\n if (bufs.length === 0) {\n return kEmptyBuffer\n }\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return Buffer.concat(bufs, len)\n}\n\nfunction write (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n bufs[bufs.length - 1].length + data.length > this.maxWrite\n ) {\n bufs.push('' + data)\n } else {\n bufs[bufs.length - 1] += data\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction writeBuffer (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n const lens = this._lens\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n lens[lens.length - 1] + data.length > this.maxWrite\n ) {\n bufs.push([data])\n lens.push(data.length)\n } else {\n bufs[bufs.length - 1].push(data)\n lens[lens.length - 1] += data.length\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction callFlushCallbackOnDrain (cb) {\n this._flushPending = true\n const onDrain = () => {\n // only if _fsync is false to avoid double fsync\n if (!this._fsync) {\n try {\n fs.fsync(this.fd, (err) => {\n this._flushPending = false\n cb(err)\n })\n } catch (err) {\n cb(err)\n }\n } else {\n this._flushPending = false\n cb()\n }\n this.off('error', onError)\n }\n const onError = (err) => {\n this._flushPending = false\n cb(err)\n this.off('drain', onDrain)\n }\n\n this.once('drain', onDrain)\n this.once('error', onError)\n}\n\nfunction flush (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push('')\n }\n\n this._actualWrite()\n}\n\nfunction flushBuffer (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push([])\n this._lens.push(0)\n }\n\n this._actualWrite()\n}\n\nSonicBoom.prototype.reopen = function (file) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.reopen(file)\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n if (!this.file) {\n throw new Error('Unable to reopen a file descriptor, you must pass a file to SonicBoom')\n }\n\n if (file) {\n this.file = file\n }\n this._reopening = true\n\n if (this._writing) {\n return\n }\n\n const fd = this.fd\n this.once('ready', () => {\n if (fd !== this.fd) {\n fs.close(fd, (err) => {\n if (err) {\n return this.emit('error', err)\n }\n })\n }\n })\n\n openFile(this.file, this)\n}\n\nSonicBoom.prototype.end = function () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.end()\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n this._ending = true\n\n if (this._writing) {\n return\n }\n\n if (this._len > 0 && this.fd >= 0) {\n this._actualWrite()\n } else {\n actualClose(this)\n }\n}\n\nfunction flushSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift(this._writingBuf)\n this._writingBuf = ''\n }\n\n let buf = ''\n while (this._bufs.length || buf) {\n if (buf.length <= 0) {\n buf = this._bufs[0]\n }\n try {\n const n = fs.writeSync(this.fd, buf, 'utf8')\n const releasedBufObj = releaseWritingBuf(buf, this._len, n)\n buf = releasedBufObj.writingBuf\n this._len = releasedBufObj.len\n if (buf.length <= 0) {\n this._bufs.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n\n try {\n fs.fsyncSync(this.fd)\n } catch {\n // Skip the error. The fd might not support fsync.\n }\n}\n\nfunction flushBufferSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift([this._writingBuf])\n this._writingBuf = kEmptyBuffer\n }\n\n let buf = kEmptyBuffer\n while (this._bufs.length || buf.length) {\n if (buf.length <= 0) {\n buf = mergeBuf(this._bufs[0], this._lens[0])\n }\n try {\n const n = fs.writeSync(this.fd, buf)\n buf = buf.subarray(n)\n this._len = Math.max(this._len - n, 0)\n if (buf.length <= 0) {\n this._bufs.shift()\n this._lens.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n}\n\nSonicBoom.prototype.destroy = function () {\n if (this.destroyed) {\n return\n }\n actualClose(this)\n}\n\nfunction actualWrite () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf || this._bufs.shift() || ''\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf, 'utf8')\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n fs.write(this.fd, this._writingBuf, 'utf8', release)\n }\n}\n\nfunction actualWriteBuffer () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift())\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf)\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n // fs.write will need to copy string to buffer anyway so\n // we do it here to avoid the overhead of calculating the buffer size\n // in releaseWritingBuf.\n if (kCopyBuffer) {\n this._writingBuf = Buffer.from(this._writingBuf)\n }\n fs.write(this.fd, this._writingBuf, release)\n }\n}\n\nfunction actualClose (sonic) {\n if (sonic.fd === -1) {\n sonic.once('ready', actualClose.bind(null, sonic))\n return\n }\n\n if (sonic._periodicFlushTimer !== undefined) {\n clearInterval(sonic._periodicFlushTimer)\n }\n\n sonic.destroyed = true\n sonic._bufs = []\n sonic._lens = []\n\n assert(typeof sonic.fd === 'number', `sonic.fd must be a number, got ${typeof sonic.fd}`)\n try {\n fs.fsync(sonic.fd, closeWrapped)\n } catch {\n }\n\n function closeWrapped () {\n // We skip errors in fsync\n\n if (sonic.fd !== 1 && sonic.fd !== 2) {\n fs.close(sonic.fd, done)\n } else {\n done()\n }\n }\n\n function done (err) {\n if (err) {\n sonic.emit('error', err)\n return\n }\n\n if (sonic._ending && !sonic._writing) {\n sonic.emit('finish')\n }\n sonic.emit('close')\n }\n}\n\n/**\n * These export configurations enable JS and TS developers\n * to consumer SonicBoom in whatever way best suits their needs.\n * Some examples of supported import syntax includes:\n * - `const SonicBoom = require('SonicBoom')`\n * - `const { SonicBoom } = require('SonicBoom')`\n * - `import * as SonicBoom from 'SonicBoom'`\n * - `import { SonicBoom } from 'SonicBoom'`\n * - `import SonicBoom from 'SonicBoom'`\n */\nSonicBoom.SonicBoom = SonicBoom\nSonicBoom.default = SonicBoom\nmodule.exports = SonicBoom\n", "'use strict'\n\nconst refs = {\n exit: [],\n beforeExit: []\n}\nconst functions = {\n exit: onExit,\n beforeExit: onBeforeExit\n}\n\nlet registry\n\nfunction ensureRegistry () {\n if (registry === undefined) {\n registry = new FinalizationRegistry(clear)\n }\n}\n\nfunction install (event) {\n if (refs[event].length > 0) {\n return\n }\n\n process.on(event, functions[event])\n}\n\nfunction uninstall (event) {\n if (refs[event].length > 0) {\n return\n }\n process.removeListener(event, functions[event])\n if (refs.exit.length === 0 && refs.beforeExit.length === 0) {\n registry = undefined\n }\n}\n\nfunction onExit () {\n callRefs('exit')\n}\n\nfunction onBeforeExit () {\n callRefs('beforeExit')\n}\n\nfunction callRefs (event) {\n for (const ref of refs[event]) {\n const obj = ref.deref()\n const fn = ref.fn\n\n // This should always happen, however GC is\n // undeterministic so it might not happen.\n /* istanbul ignore else */\n if (obj !== undefined) {\n fn(obj, event)\n }\n }\n refs[event] = []\n}\n\nfunction clear (ref) {\n for (const event of ['exit', 'beforeExit']) {\n const index = refs[event].indexOf(ref)\n refs[event].splice(index, index + 1)\n uninstall(event)\n }\n}\n\nfunction _register (event, obj, fn) {\n if (obj === undefined) {\n throw new Error('the object can\\'t be undefined')\n }\n install(event)\n const ref = new WeakRef(obj)\n ref.fn = fn\n\n ensureRegistry()\n registry.register(obj, ref)\n refs[event].push(ref)\n}\n\nfunction register (obj, fn) {\n _register('exit', obj, fn)\n}\n\nfunction registerBeforeExit (obj, fn) {\n _register('beforeExit', obj, fn)\n}\n\nfunction unregister (obj) {\n if (registry === undefined) {\n return\n }\n registry.unregister(obj)\n for (const event of ['exit', 'beforeExit']) {\n refs[event] = refs[event].filter((ref) => {\n const _obj = ref.deref()\n return _obj && _obj !== obj\n })\n uninstall(event)\n }\n}\n\nmodule.exports = {\n register,\n registerBeforeExit,\n unregister\n}\n", "{\n \"name\": \"thread-stream\",\n \"version\": \"3.1.0\",\n \"description\": \"A streaming way to send data to a Node.js Worker Thread\",\n \"main\": \"index.js\",\n \"types\": \"index.d.ts\",\n \"dependencies\": {\n \"real-require\": \"^0.2.0\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^20.1.0\",\n \"@types/tap\": \"^15.0.0\",\n \"@yao-pkg/pkg\": \"^5.11.5\",\n \"desm\": \"^1.3.0\",\n \"fastbench\": \"^1.0.1\",\n \"husky\": \"^9.0.6\",\n \"pino-elasticsearch\": \"^8.0.0\",\n \"sonic-boom\": \"^4.0.1\",\n \"standard\": \"^17.0.0\",\n \"tap\": \"^16.2.0\",\n \"ts-node\": \"^10.8.0\",\n \"typescript\": \"^5.3.2\",\n \"why-is-node-running\": \"^2.2.2\"\n },\n \"scripts\": {\n \"build\": \"tsc --noEmit\",\n \"test\": \"standard && npm run build && npm run transpile && tap \\\"test/**/*.test.*js\\\" && tap --ts test/*.test.*ts\",\n \"test:ci\": \"standard && npm run transpile && npm run test:ci:js && npm run test:ci:ts\",\n \"test:ci:js\": \"tap --no-check-coverage --timeout=120 --coverage-report=lcovonly \\\"test/**/*.test.*js\\\"\",\n \"test:ci:ts\": \"tap --ts --no-check-coverage --coverage-report=lcovonly \\\"test/**/*.test.*ts\\\"\",\n \"test:yarn\": \"npm run transpile && tap \\\"test/**/*.test.js\\\" --no-check-coverage\",\n \"transpile\": \"sh ./test/ts/transpile.sh\",\n \"prepare\": \"husky install\"\n },\n \"standard\": {\n \"ignore\": [\n \"test/ts/**/*\",\n \"test/syntax-error.mjs\"\n ]\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/mcollina/thread-stream.git\"\n },\n \"keywords\": [\n \"worker\",\n \"thread\",\n \"threads\",\n \"stream\"\n ],\n \"author\": \"Matteo Collina \",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/mcollina/thread-stream/issues\"\n },\n \"homepage\": \"https://github.com/mcollina/thread-stream#readme\"\n}\n", "'use strict'\n\nconst MAX_TIMEOUT = 1000\n\nfunction wait (state, index, expected, timeout, done) {\n const max = Date.now() + timeout\n let current = Atomics.load(state, index)\n if (current === expected) {\n done(null, 'ok')\n return\n }\n let prior = current\n const check = (backoff) => {\n if (Date.now() > max) {\n done(null, 'timed-out')\n } else {\n setTimeout(() => {\n prior = current\n current = Atomics.load(state, index)\n if (current === prior) {\n check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)\n } else {\n if (current === expected) done(null, 'ok')\n else done(null, 'not-equal')\n }\n }, backoff)\n }\n }\n check(1)\n}\n\n// let waitDiffCount = 0\nfunction waitDiff (state, index, expected, timeout, done) {\n // const id = waitDiffCount++\n // process._rawDebug(`>>> waitDiff ${id}`)\n const max = Date.now() + timeout\n let current = Atomics.load(state, index)\n if (current !== expected) {\n done(null, 'ok')\n return\n }\n const check = (backoff) => {\n // process._rawDebug(`${id} ${index} current ${current} expected ${expected}`)\n // process._rawDebug('' + backoff)\n if (Date.now() > max) {\n done(null, 'timed-out')\n } else {\n setTimeout(() => {\n current = Atomics.load(state, index)\n if (current !== expected) {\n done(null, 'ok')\n } else {\n check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)\n }\n }, backoff)\n }\n }\n check(1)\n}\n\nmodule.exports = { wait, waitDiff }\n", "'use strict'\n\nconst WRITE_INDEX = 4\nconst READ_INDEX = 8\n\nmodule.exports = {\n WRITE_INDEX,\n READ_INDEX\n}\n", "'use strict'\n\nconst { version } = require('./package.json')\nconst { EventEmitter } = require('events')\nconst { Worker } = require('worker_threads')\nconst { join } = require('path')\nconst { pathToFileURL } = require('url')\nconst { wait } = require('./lib/wait')\nconst {\n WRITE_INDEX,\n READ_INDEX\n} = require('./lib/indexes')\nconst buffer = require('buffer')\nconst assert = require('assert')\n\nconst kImpl = Symbol('kImpl')\n\n// V8 limit for string size\nconst MAX_STRING = buffer.constants.MAX_STRING_LENGTH\n\nclass FakeWeakRef {\n constructor (value) {\n this._value = value\n }\n\n deref () {\n return this._value\n }\n}\n\nclass FakeFinalizationRegistry {\n register () {}\n\n unregister () {}\n}\n\n// Currently using FinalizationRegistry with code coverage breaks the world\n// Ref: https://github.com/nodejs/node/issues/49344\nconst FinalizationRegistry = process.env.NODE_V8_COVERAGE ? FakeFinalizationRegistry : global.FinalizationRegistry || FakeFinalizationRegistry\nconst WeakRef = process.env.NODE_V8_COVERAGE ? FakeWeakRef : global.WeakRef || FakeWeakRef\n\nconst registry = new FinalizationRegistry((worker) => {\n if (worker.exited) {\n return\n }\n worker.terminate()\n})\n\nfunction createWorker (stream, opts) {\n const { filename, workerData } = opts\n\n const bundlerOverrides = '__bundlerPathsOverrides' in globalThis ? globalThis.__bundlerPathsOverrides : {}\n const toExecute = bundlerOverrides['thread-stream-worker'] || join(__dirname, 'lib', 'worker.js')\n\n const worker = new Worker(toExecute, {\n ...opts.workerOpts,\n trackUnmanagedFds: false,\n workerData: {\n filename: filename.indexOf('file://') === 0\n ? filename\n : pathToFileURL(filename).href,\n dataBuf: stream[kImpl].dataBuf,\n stateBuf: stream[kImpl].stateBuf,\n workerData: {\n $context: {\n threadStreamVersion: version\n },\n ...workerData\n }\n }\n })\n\n // We keep a strong reference for now,\n // we need to start writing first\n worker.stream = new FakeWeakRef(stream)\n\n worker.on('message', onWorkerMessage)\n worker.on('exit', onWorkerExit)\n registry.register(stream, worker)\n\n return worker\n}\n\nfunction drain (stream) {\n assert(!stream[kImpl].sync)\n if (stream[kImpl].needDrain) {\n stream[kImpl].needDrain = false\n stream.emit('drain')\n }\n}\n\nfunction nextFlush (stream) {\n const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n let leftover = stream[kImpl].data.length - writeIndex\n\n if (leftover > 0) {\n if (stream[kImpl].buf.length === 0) {\n stream[kImpl].flushing = false\n\n if (stream[kImpl].ending) {\n end(stream)\n } else if (stream[kImpl].needDrain) {\n process.nextTick(drain, stream)\n }\n\n return\n }\n\n let toWrite = stream[kImpl].buf.slice(0, leftover)\n let toWriteBytes = Buffer.byteLength(toWrite)\n if (toWriteBytes <= leftover) {\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n // process._rawDebug('writing ' + toWrite.length)\n write(stream, toWrite, nextFlush.bind(null, stream))\n } else {\n // multi-byte utf-8\n stream.flush(() => {\n // err is already handled in flush()\n if (stream.destroyed) {\n return\n }\n\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n\n // Find a toWrite length that fits the buffer\n // it must exists as the buffer is at least 4 bytes length\n // and the max utf-8 length for a char is 4 bytes.\n while (toWriteBytes > stream[kImpl].data.length) {\n leftover = leftover / 2\n toWrite = stream[kImpl].buf.slice(0, leftover)\n toWriteBytes = Buffer.byteLength(toWrite)\n }\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n write(stream, toWrite, nextFlush.bind(null, stream))\n })\n }\n } else if (leftover === 0) {\n if (writeIndex === 0 && stream[kImpl].buf.length === 0) {\n // we had a flushSync in the meanwhile\n return\n }\n stream.flush(() => {\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n nextFlush(stream)\n })\n } else {\n // This should never happen\n destroy(stream, new Error('overwritten'))\n }\n}\n\nfunction onWorkerMessage (msg) {\n const stream = this.stream.deref()\n if (stream === undefined) {\n this.exited = true\n // Terminate the worker.\n this.terminate()\n return\n }\n\n switch (msg.code) {\n case 'READY':\n // Replace the FakeWeakRef with a\n // proper one.\n this.stream = new WeakRef(stream)\n\n stream.flush(() => {\n stream[kImpl].ready = true\n stream.emit('ready')\n })\n break\n case 'ERROR':\n destroy(stream, msg.err)\n break\n case 'EVENT':\n if (Array.isArray(msg.args)) {\n stream.emit(msg.name, ...msg.args)\n } else {\n stream.emit(msg.name, msg.args)\n }\n break\n case 'WARNING':\n process.emitWarning(msg.err)\n break\n default:\n destroy(stream, new Error('this should not happen: ' + msg.code))\n }\n}\n\nfunction onWorkerExit (code) {\n const stream = this.stream.deref()\n if (stream === undefined) {\n // Nothing to do, the worker already exit\n return\n }\n registry.unregister(stream)\n stream.worker.exited = true\n stream.worker.off('exit', onWorkerExit)\n destroy(stream, code !== 0 ? new Error('the worker thread exited') : null)\n}\n\nclass ThreadStream extends EventEmitter {\n constructor (opts = {}) {\n super()\n\n if (opts.bufferSize < 4) {\n throw new Error('bufferSize must at least fit a 4-byte utf-8 char')\n }\n\n this[kImpl] = {}\n this[kImpl].stateBuf = new SharedArrayBuffer(128)\n this[kImpl].state = new Int32Array(this[kImpl].stateBuf)\n this[kImpl].dataBuf = new SharedArrayBuffer(opts.bufferSize || 4 * 1024 * 1024)\n this[kImpl].data = Buffer.from(this[kImpl].dataBuf)\n this[kImpl].sync = opts.sync || false\n this[kImpl].ending = false\n this[kImpl].ended = false\n this[kImpl].needDrain = false\n this[kImpl].destroyed = false\n this[kImpl].flushing = false\n this[kImpl].ready = false\n this[kImpl].finished = false\n this[kImpl].errored = null\n this[kImpl].closed = false\n this[kImpl].buf = ''\n\n // TODO (fix): Make private?\n this.worker = createWorker(this, opts) // TODO (fix): make private\n this.on('message', (message, transferList) => {\n this.worker.postMessage(message, transferList)\n })\n }\n\n write (data) {\n if (this[kImpl].destroyed) {\n error(this, new Error('the worker has exited'))\n return false\n }\n\n if (this[kImpl].ending) {\n error(this, new Error('the worker is ending'))\n return false\n }\n\n if (this[kImpl].flushing && this[kImpl].buf.length + data.length >= MAX_STRING) {\n try {\n writeSync(this)\n this[kImpl].flushing = true\n } catch (err) {\n destroy(this, err)\n return false\n }\n }\n\n this[kImpl].buf += data\n\n if (this[kImpl].sync) {\n try {\n writeSync(this)\n return true\n } catch (err) {\n destroy(this, err)\n return false\n }\n }\n\n if (!this[kImpl].flushing) {\n this[kImpl].flushing = true\n setImmediate(nextFlush, this)\n }\n\n this[kImpl].needDrain = this[kImpl].data.length - this[kImpl].buf.length - Atomics.load(this[kImpl].state, WRITE_INDEX) <= 0\n return !this[kImpl].needDrain\n }\n\n end () {\n if (this[kImpl].destroyed) {\n return\n }\n\n this[kImpl].ending = true\n end(this)\n }\n\n flush (cb) {\n if (this[kImpl].destroyed) {\n if (typeof cb === 'function') {\n process.nextTick(cb, new Error('the worker has exited'))\n }\n return\n }\n\n // TODO write all .buf\n const writeIndex = Atomics.load(this[kImpl].state, WRITE_INDEX)\n // process._rawDebug(`(flush) readIndex (${Atomics.load(this.state, READ_INDEX)}) writeIndex (${Atomics.load(this.state, WRITE_INDEX)})`)\n wait(this[kImpl].state, READ_INDEX, writeIndex, Infinity, (err, res) => {\n if (err) {\n destroy(this, err)\n process.nextTick(cb, err)\n return\n }\n if (res === 'not-equal') {\n // TODO handle deadlock\n this.flush(cb)\n return\n }\n process.nextTick(cb)\n })\n }\n\n flushSync () {\n if (this[kImpl].destroyed) {\n return\n }\n\n writeSync(this)\n flushSync(this)\n }\n\n unref () {\n this.worker.unref()\n }\n\n ref () {\n this.worker.ref()\n }\n\n get ready () {\n return this[kImpl].ready\n }\n\n get destroyed () {\n return this[kImpl].destroyed\n }\n\n get closed () {\n return this[kImpl].closed\n }\n\n get writable () {\n return !this[kImpl].destroyed && !this[kImpl].ending\n }\n\n get writableEnded () {\n return this[kImpl].ending\n }\n\n get writableFinished () {\n return this[kImpl].finished\n }\n\n get writableNeedDrain () {\n return this[kImpl].needDrain\n }\n\n get writableObjectMode () {\n return false\n }\n\n get writableErrored () {\n return this[kImpl].errored\n }\n}\n\nfunction error (stream, err) {\n setImmediate(() => {\n stream.emit('error', err)\n })\n}\n\nfunction destroy (stream, err) {\n if (stream[kImpl].destroyed) {\n return\n }\n stream[kImpl].destroyed = true\n\n if (err) {\n stream[kImpl].errored = err\n error(stream, err)\n }\n\n if (!stream.worker.exited) {\n stream.worker.terminate()\n .catch(() => {})\n .then(() => {\n stream[kImpl].closed = true\n stream.emit('close')\n })\n } else {\n setImmediate(() => {\n stream[kImpl].closed = true\n stream.emit('close')\n })\n }\n}\n\nfunction write (stream, data, cb) {\n // data is smaller than the shared buffer length\n const current = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n const length = Buffer.byteLength(data)\n stream[kImpl].data.write(data, current)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, current + length)\n Atomics.notify(stream[kImpl].state, WRITE_INDEX)\n cb()\n return true\n}\n\nfunction end (stream) {\n if (stream[kImpl].ended || !stream[kImpl].ending || stream[kImpl].flushing) {\n return\n }\n stream[kImpl].ended = true\n\n try {\n stream.flushSync()\n\n let readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n // process._rawDebug('writing index')\n Atomics.store(stream[kImpl].state, WRITE_INDEX, -1)\n // process._rawDebug(`(end) readIndex (${Atomics.load(stream.state, READ_INDEX)}) writeIndex (${Atomics.load(stream.state, WRITE_INDEX)})`)\n Atomics.notify(stream[kImpl].state, WRITE_INDEX)\n\n // Wait for the process to complete\n let spins = 0\n while (readIndex !== -1) {\n // process._rawDebug(`read = ${read}`)\n Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000)\n readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n if (readIndex === -2) {\n destroy(stream, new Error('end() failed'))\n return\n }\n\n if (++spins === 10) {\n destroy(stream, new Error('end() took too long (10s)'))\n return\n }\n }\n\n process.nextTick(() => {\n stream[kImpl].finished = true\n stream.emit('finish')\n })\n } catch (err) {\n destroy(stream, err)\n }\n // process._rawDebug('end finished...')\n}\n\nfunction writeSync (stream) {\n const cb = () => {\n if (stream[kImpl].ending) {\n end(stream)\n } else if (stream[kImpl].needDrain) {\n process.nextTick(drain, stream)\n }\n }\n stream[kImpl].flushing = false\n\n while (stream[kImpl].buf.length !== 0) {\n const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n let leftover = stream[kImpl].data.length - writeIndex\n if (leftover === 0) {\n flushSync(stream)\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n continue\n } else if (leftover < 0) {\n // stream should never happen\n throw new Error('overwritten')\n }\n\n let toWrite = stream[kImpl].buf.slice(0, leftover)\n let toWriteBytes = Buffer.byteLength(toWrite)\n if (toWriteBytes <= leftover) {\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n // process._rawDebug('writing ' + toWrite.length)\n write(stream, toWrite, cb)\n } else {\n // multi-byte utf-8\n flushSync(stream)\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n\n // Find a toWrite length that fits the buffer\n // it must exists as the buffer is at least 4 bytes length\n // and the max utf-8 length for a char is 4 bytes.\n while (toWriteBytes > stream[kImpl].buf.length) {\n leftover = leftover / 2\n toWrite = stream[kImpl].buf.slice(0, leftover)\n toWriteBytes = Buffer.byteLength(toWrite)\n }\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n write(stream, toWrite, cb)\n }\n }\n}\n\nfunction flushSync (stream) {\n if (stream[kImpl].flushing) {\n throw new Error('unable to flush while flushing')\n }\n\n // process._rawDebug('flushSync started')\n\n const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n\n let spins = 0\n\n // TODO handle deadlock\n while (true) {\n const readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n if (readIndex === -2) {\n throw Error('_flushSync failed')\n }\n\n // process._rawDebug(`(flushSync) readIndex (${readIndex}) writeIndex (${writeIndex})`)\n if (readIndex !== writeIndex) {\n // TODO stream timeouts for some reason.\n Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000)\n } else {\n break\n }\n\n if (++spins === 10) {\n throw new Error('_flushSync took too long (10s)')\n }\n }\n // process._rawDebug('flushSync finished')\n}\n\nmodule.exports = ThreadStream\n", "'use strict'\n\nconst { createRequire } = require('module')\nconst getCallers = require('./caller')\nconst { join, isAbsolute, sep } = require('node:path')\nconst sleep = require('atomic-sleep')\nconst onExit = require('on-exit-leak-free')\nconst ThreadStream = require('thread-stream')\n\nfunction setupOnExit (stream) {\n // This is leak free, it does not leave event handlers\n onExit.register(stream, autoEnd)\n onExit.registerBeforeExit(stream, flush)\n\n stream.on('close', function () {\n onExit.unregister(stream)\n })\n}\n\nfunction buildStream (filename, workerData, workerOpts, sync) {\n const stream = new ThreadStream({\n filename,\n workerData,\n workerOpts,\n sync\n })\n\n stream.on('ready', onReady)\n stream.on('close', function () {\n process.removeListener('exit', onExit)\n })\n\n process.on('exit', onExit)\n\n function onReady () {\n process.removeListener('exit', onExit)\n stream.unref()\n\n if (workerOpts.autoEnd !== false) {\n setupOnExit(stream)\n }\n }\n\n function onExit () {\n /* istanbul ignore next */\n if (stream.closed) {\n return\n }\n stream.flushSync()\n // Apparently there is a very sporadic race condition\n // that in certain OS would prevent the messages to be flushed\n // because the thread might not have been created still.\n // Unfortunately we need to sleep(100) in this case.\n sleep(100)\n stream.end()\n }\n\n return stream\n}\n\nfunction autoEnd (stream) {\n stream.ref()\n stream.flushSync()\n stream.end()\n stream.once('close', function () {\n stream.unref()\n })\n}\n\nfunction flush (stream) {\n stream.flushSync()\n}\n\nfunction transport (fullOptions) {\n const { pipeline, targets, levels, dedupe, worker = {}, caller = getCallers(), sync = false } = fullOptions\n\n const options = {\n ...fullOptions.options\n }\n\n // Backwards compatibility\n const callers = typeof caller === 'string' ? [caller] : caller\n\n // This will be eventually modified by bundlers\n const bundlerOverrides = '__bundlerPathsOverrides' in globalThis ? globalThis.__bundlerPathsOverrides : {}\n\n let target = fullOptions.target\n\n if (target && targets) {\n throw new Error('only one of target or targets can be specified')\n }\n\n if (targets) {\n target = bundlerOverrides['pino-worker'] || join(__dirname, 'worker.js')\n options.targets = targets.filter(dest => dest.target).map((dest) => {\n return {\n ...dest,\n target: fixTarget(dest.target)\n }\n })\n options.pipelines = targets.filter(dest => dest.pipeline).map((dest) => {\n return dest.pipeline.map((t) => {\n return {\n ...t,\n level: dest.level, // duplicate the pipeline `level` property defined in the upper level\n target: fixTarget(t.target)\n }\n })\n })\n } else if (pipeline) {\n target = bundlerOverrides['pino-worker'] || join(__dirname, 'worker.js')\n options.pipelines = [pipeline.map((dest) => {\n return {\n ...dest,\n target: fixTarget(dest.target)\n }\n })]\n }\n\n if (levels) {\n options.levels = levels\n }\n\n if (dedupe) {\n options.dedupe = dedupe\n }\n\n options.pinoWillSendConfig = true\n\n return buildStream(fixTarget(target), options, worker, sync)\n\n function fixTarget (origin) {\n origin = bundlerOverrides[origin] || origin\n\n if (isAbsolute(origin) || origin.indexOf('file://') === 0) {\n return origin\n }\n\n if (origin === 'pino/file') {\n return join(__dirname, '..', 'file.js')\n }\n\n let fixTarget\n\n for (const filePath of callers) {\n try {\n const context = filePath === 'node:repl'\n ? process.cwd() + sep\n : filePath\n\n fixTarget = createRequire(context).resolve(origin)\n break\n } catch (err) {\n // Silent catch\n continue\n }\n }\n\n if (!fixTarget) {\n throw new Error(`unable to determine transport target for \"${origin}\"`)\n }\n\n return fixTarget\n }\n}\n\nmodule.exports = transport\n", "'use strict'\n\n/* eslint no-prototype-builtins: 0 */\n\nconst format = require('quick-format-unescaped')\nconst { mapHttpRequest, mapHttpResponse } = require('pino-std-serializers')\nconst SonicBoom = require('sonic-boom')\nconst onExit = require('on-exit-leak-free')\nconst {\n lsCacheSym,\n chindingsSym,\n writeSym,\n serializersSym,\n formatOptsSym,\n endSym,\n stringifiersSym,\n stringifySym,\n stringifySafeSym,\n wildcardFirstSym,\n nestedKeySym,\n formattersSym,\n messageKeySym,\n errorKeySym,\n nestedKeyStrSym,\n msgPrefixSym\n} = require('./symbols')\nconst { isMainThread } = require('worker_threads')\nconst transport = require('./transport')\n\nfunction noop () {\n}\n\nfunction genLog (level, hook) {\n if (!hook) return LOG\n\n return function hookWrappedLog (...args) {\n hook.call(this, args, LOG, level)\n }\n\n function LOG (o, ...n) {\n if (typeof o === 'object') {\n let msg = o\n if (o !== null) {\n if (o.method && o.headers && o.socket) {\n o = mapHttpRequest(o)\n } else if (typeof o.setHeader === 'function') {\n o = mapHttpResponse(o)\n }\n }\n let formatParams\n if (msg === null && n.length === 0) {\n formatParams = [null]\n } else {\n msg = n.shift()\n formatParams = n\n }\n // We do not use a coercive check for `msg` as it is\n // measurably slower than the explicit checks.\n if (typeof this[msgPrefixSym] === 'string' && msg !== undefined && msg !== null) {\n msg = this[msgPrefixSym] + msg\n }\n this[writeSym](o, format(msg, formatParams, this[formatOptsSym]), level)\n } else {\n let msg = o === undefined ? n.shift() : o\n\n // We do not use a coercive check for `msg` as it is\n // measurably slower than the explicit checks.\n if (typeof this[msgPrefixSym] === 'string' && msg !== undefined && msg !== null) {\n msg = this[msgPrefixSym] + msg\n }\n this[writeSym](null, format(msg, n, this[formatOptsSym]), level)\n }\n }\n}\n\n// magically escape strings for json\n// relying on their charCodeAt\n// everything below 32 needs JSON.stringify()\n// 34 and 92 happens all the time, so we\n// have a fast case for them\nfunction asString (str) {\n let result = ''\n let last = 0\n let found = false\n let point = 255\n const l = str.length\n if (l > 100) {\n return JSON.stringify(str)\n }\n for (var i = 0; i < l && point >= 32; i++) {\n point = str.charCodeAt(i)\n if (point === 34 || point === 92) {\n result += str.slice(last, i) + '\\\\'\n last = i\n found = true\n }\n }\n if (!found) {\n result = str\n } else {\n result += str.slice(last)\n }\n return point < 32 ? JSON.stringify(str) : '\"' + result + '\"'\n}\n\nfunction asJson (obj, msg, num, time) {\n const stringify = this[stringifySym]\n const stringifySafe = this[stringifySafeSym]\n const stringifiers = this[stringifiersSym]\n const end = this[endSym]\n const chindings = this[chindingsSym]\n const serializers = this[serializersSym]\n const formatters = this[formattersSym]\n const messageKey = this[messageKeySym]\n const errorKey = this[errorKeySym]\n let data = this[lsCacheSym][num] + time\n\n // we need the child bindings added to the output first so instance logged\n // objects can take precedence when JSON.parse-ing the resulting log line\n data = data + chindings\n\n let value\n if (formatters.log) {\n obj = formatters.log(obj)\n }\n const wildcardStringifier = stringifiers[wildcardFirstSym]\n let propStr = ''\n for (const key in obj) {\n value = obj[key]\n if (Object.prototype.hasOwnProperty.call(obj, key) && value !== undefined) {\n if (serializers[key]) {\n value = serializers[key](value)\n } else if (key === errorKey && serializers.err) {\n value = serializers.err(value)\n }\n\n const stringifier = stringifiers[key] || wildcardStringifier\n\n switch (typeof value) {\n case 'undefined':\n case 'function':\n continue\n case 'number':\n /* eslint no-fallthrough: \"off\" */\n if (Number.isFinite(value) === false) {\n value = null\n }\n // this case explicitly falls through to the next one\n case 'boolean':\n if (stringifier) value = stringifier(value)\n break\n case 'string':\n value = (stringifier || asString)(value)\n break\n default:\n value = (stringifier || stringify)(value, stringifySafe)\n }\n if (value === undefined) continue\n const strKey = asString(key)\n propStr += ',' + strKey + ':' + value\n }\n }\n\n let msgStr = ''\n if (msg !== undefined) {\n value = serializers[messageKey] ? serializers[messageKey](msg) : msg\n const stringifier = stringifiers[messageKey] || wildcardStringifier\n\n switch (typeof value) {\n case 'function':\n break\n case 'number':\n /* eslint no-fallthrough: \"off\" */\n if (Number.isFinite(value) === false) {\n value = null\n }\n // this case explicitly falls through to the next one\n case 'boolean':\n if (stringifier) value = stringifier(value)\n msgStr = ',\"' + messageKey + '\":' + value\n break\n case 'string':\n value = (stringifier || asString)(value)\n msgStr = ',\"' + messageKey + '\":' + value\n break\n default:\n value = (stringifier || stringify)(value, stringifySafe)\n msgStr = ',\"' + messageKey + '\":' + value\n }\n }\n\n if (this[nestedKeySym] && propStr) {\n // place all the obj properties under the specified key\n // the nested key is already formatted from the constructor\n return data + this[nestedKeyStrSym] + propStr.slice(1) + '}' + msgStr + end\n } else {\n return data + propStr + msgStr + end\n }\n}\n\nfunction asChindings (instance, bindings) {\n let value\n let data = instance[chindingsSym]\n const stringify = instance[stringifySym]\n const stringifySafe = instance[stringifySafeSym]\n const stringifiers = instance[stringifiersSym]\n const wildcardStringifier = stringifiers[wildcardFirstSym]\n const serializers = instance[serializersSym]\n const formatter = instance[formattersSym].bindings\n bindings = formatter(bindings)\n\n for (const key in bindings) {\n value = bindings[key]\n const valid = key !== 'level' &&\n key !== 'serializers' &&\n key !== 'formatters' &&\n key !== 'customLevels' &&\n bindings.hasOwnProperty(key) &&\n value !== undefined\n if (valid === true) {\n value = serializers[key] ? serializers[key](value) : value\n value = (stringifiers[key] || wildcardStringifier || stringify)(value, stringifySafe)\n if (value === undefined) continue\n data += ',\"' + key + '\":' + value\n }\n }\n return data\n}\n\nfunction hasBeenTampered (stream) {\n return stream.write !== stream.constructor.prototype.write\n}\n\nfunction buildSafeSonicBoom (opts) {\n const stream = new SonicBoom(opts)\n stream.on('error', filterBrokenPipe)\n // If we are sync: false, we must flush on exit\n if (!opts.sync && isMainThread) {\n onExit.register(stream, autoEnd)\n\n stream.on('close', function () {\n onExit.unregister(stream)\n })\n }\n return stream\n\n function filterBrokenPipe (err) {\n // Impossible to replicate across all operating systems\n /* istanbul ignore next */\n if (err.code === 'EPIPE') {\n // If we get EPIPE, we should stop logging here\n // however we have no control to the consumer of\n // SonicBoom, so we just overwrite the write method\n stream.write = noop\n stream.end = noop\n stream.flushSync = noop\n stream.destroy = noop\n return\n }\n stream.removeListener('error', filterBrokenPipe)\n stream.emit('error', err)\n }\n}\n\nfunction autoEnd (stream, eventName) {\n // This check is needed only on some platforms\n /* istanbul ignore next */\n if (stream.destroyed) {\n return\n }\n\n if (eventName === 'beforeExit') {\n // We still have an event loop, let's use it\n stream.flush()\n stream.on('drain', function () {\n stream.end()\n })\n } else {\n // For some reason istanbul is not detecting this, but it's there\n /* istanbul ignore next */\n // We do not have an event loop, so flush synchronously\n stream.flushSync()\n }\n}\n\nfunction createArgsNormalizer (defaultOptions) {\n return function normalizeArgs (instance, caller, opts = {}, stream) {\n // support stream as a string\n if (typeof opts === 'string') {\n stream = buildSafeSonicBoom({ dest: opts })\n opts = {}\n } else if (typeof stream === 'string') {\n if (opts && opts.transport) {\n throw Error('only one of option.transport or stream can be specified')\n }\n stream = buildSafeSonicBoom({ dest: stream })\n } else if (opts instanceof SonicBoom || opts.writable || opts._writableState) {\n stream = opts\n opts = {}\n } else if (opts.transport) {\n if (opts.transport instanceof SonicBoom || opts.transport.writable || opts.transport._writableState) {\n throw Error('option.transport do not allow stream, please pass to option directly. e.g. pino(transport)')\n }\n if (opts.transport.targets && opts.transport.targets.length && opts.formatters && typeof opts.formatters.level === 'function') {\n throw Error('option.transport.targets do not allow custom level formatters')\n }\n\n let customLevels\n if (opts.customLevels) {\n customLevels = opts.useOnlyCustomLevels ? opts.customLevels : Object.assign({}, opts.levels, opts.customLevels)\n }\n stream = transport({ caller, ...opts.transport, levels: customLevels })\n }\n opts = Object.assign({}, defaultOptions, opts)\n opts.serializers = Object.assign({}, defaultOptions.serializers, opts.serializers)\n opts.formatters = Object.assign({}, defaultOptions.formatters, opts.formatters)\n\n if (opts.prettyPrint) {\n throw new Error('prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)')\n }\n\n const { enabled, onChild } = opts\n if (enabled === false) opts.level = 'silent'\n if (!onChild) opts.onChild = noop\n if (!stream) {\n if (!hasBeenTampered(process.stdout)) {\n // If process.stdout.fd is undefined, it means that we are running\n // in a worker thread. Let's assume we are logging to file descriptor 1.\n stream = buildSafeSonicBoom({ fd: process.stdout.fd || 1 })\n } else {\n stream = process.stdout\n }\n }\n return { opts, stream }\n }\n}\n\nfunction stringify (obj, stringifySafeFn) {\n try {\n return JSON.stringify(obj)\n } catch (_) {\n try {\n const stringify = stringifySafeFn || this[stringifySafeSym]\n return stringify(obj)\n } catch (_) {\n return '\"[unable to serialize, circular reference is too complex to analyze]\"'\n }\n }\n}\n\nfunction buildFormatters (level, bindings, log) {\n return {\n level,\n bindings,\n log\n }\n}\n\n/**\n * Convert a string integer file descriptor to a proper native integer\n * file descriptor.\n *\n * @param {string} destination The file descriptor string to attempt to convert.\n *\n * @returns {Number}\n */\nfunction normalizeDestFileDescriptor (destination) {\n const fd = Number(destination)\n if (typeof destination === 'string' && Number.isFinite(fd)) {\n return fd\n }\n // destination could be undefined if we are in a worker\n if (destination === undefined) {\n // This is stdout in UNIX systems\n return 1\n }\n return destination\n}\n\nmodule.exports = {\n noop,\n buildSafeSonicBoom,\n asChindings,\n asJson,\n genLog,\n createArgsNormalizer,\n stringify,\n buildFormatters,\n normalizeDestFileDescriptor\n}\n", "/**\n * Represents default log level values\n *\n * @enum {number}\n */\nconst DEFAULT_LEVELS = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60\n}\n\n/**\n * Represents sort order direction: `ascending` or `descending`\n *\n * @enum {string}\n */\nconst SORTING_ORDER = {\n ASC: 'ASC',\n DESC: 'DESC'\n}\n\nmodule.exports = {\n DEFAULT_LEVELS,\n SORTING_ORDER\n}\n", "'use strict'\n/* eslint no-prototype-builtins: 0 */\nconst {\n lsCacheSym,\n levelValSym,\n useOnlyCustomLevelsSym,\n streamSym,\n formattersSym,\n hooksSym,\n levelCompSym\n} = require('./symbols')\nconst { noop, genLog } = require('./tools')\nconst { DEFAULT_LEVELS, SORTING_ORDER } = require('./constants')\n\nconst levelMethods = {\n fatal: (hook) => {\n const logFatal = genLog(DEFAULT_LEVELS.fatal, hook)\n return function (...args) {\n const stream = this[streamSym]\n logFatal.call(this, ...args)\n if (typeof stream.flushSync === 'function') {\n try {\n stream.flushSync()\n } catch (e) {\n // https://github.com/pinojs/pino/pull/740#discussion_r346788313\n }\n }\n }\n },\n error: (hook) => genLog(DEFAULT_LEVELS.error, hook),\n warn: (hook) => genLog(DEFAULT_LEVELS.warn, hook),\n info: (hook) => genLog(DEFAULT_LEVELS.info, hook),\n debug: (hook) => genLog(DEFAULT_LEVELS.debug, hook),\n trace: (hook) => genLog(DEFAULT_LEVELS.trace, hook)\n}\n\nconst nums = Object.keys(DEFAULT_LEVELS).reduce((o, k) => {\n o[DEFAULT_LEVELS[k]] = k\n return o\n}, {})\n\nconst initialLsCache = Object.keys(nums).reduce((o, k) => {\n o[k] = '{\"level\":' + Number(k)\n return o\n}, {})\n\nfunction genLsCache (instance) {\n const formatter = instance[formattersSym].level\n const { labels } = instance.levels\n const cache = {}\n for (const label in labels) {\n const level = formatter(labels[label], Number(label))\n cache[label] = JSON.stringify(level).slice(0, -1)\n }\n instance[lsCacheSym] = cache\n return instance\n}\n\nfunction isStandardLevel (level, useOnlyCustomLevels) {\n if (useOnlyCustomLevels) {\n return false\n }\n\n switch (level) {\n case 'fatal':\n case 'error':\n case 'warn':\n case 'info':\n case 'debug':\n case 'trace':\n return true\n default:\n return false\n }\n}\n\nfunction setLevel (level) {\n const { labels, values } = this.levels\n if (typeof level === 'number') {\n if (labels[level] === undefined) throw Error('unknown level value' + level)\n level = labels[level]\n }\n if (values[level] === undefined) throw Error('unknown level ' + level)\n const preLevelVal = this[levelValSym]\n const levelVal = this[levelValSym] = values[level]\n const useOnlyCustomLevelsVal = this[useOnlyCustomLevelsSym]\n const levelComparison = this[levelCompSym]\n const hook = this[hooksSym].logMethod\n\n for (const key in values) {\n if (levelComparison(values[key], levelVal) === false) {\n this[key] = noop\n continue\n }\n this[key] = isStandardLevel(key, useOnlyCustomLevelsVal) ? levelMethods[key](hook) : genLog(values[key], hook)\n }\n\n this.emit(\n 'level-change',\n level,\n levelVal,\n labels[preLevelVal],\n preLevelVal,\n this\n )\n}\n\nfunction getLevel (level) {\n const { levels, levelVal } = this\n // protection against potential loss of Pino scope from serializers (edge case with circular refs - https://github.com/pinojs/pino/issues/833)\n return (levels && levels.labels) ? levels.labels[levelVal] : ''\n}\n\nfunction isLevelEnabled (logLevel) {\n const { values } = this.levels\n const logLevelVal = values[logLevel]\n return logLevelVal !== undefined && this[levelCompSym](logLevelVal, this[levelValSym])\n}\n\n/**\n * Determine if the given `current` level is enabled by comparing it\n * against the current threshold (`expected`).\n *\n * @param {SORTING_ORDER} direction comparison direction \"ASC\" or \"DESC\"\n * @param {number} current current log level number representation\n * @param {number} expected threshold value to compare with\n * @returns {boolean}\n */\nfunction compareLevel (direction, current, expected) {\n if (direction === SORTING_ORDER.DESC) {\n return current <= expected\n }\n\n return current >= expected\n}\n\n/**\n * Create a level comparison function based on `levelComparison`\n * it could a default function which compares levels either in \"ascending\" or \"descending\" order or custom comparison function\n *\n * @param {SORTING_ORDER | Function} levelComparison sort levels order direction or custom comparison function\n * @returns Function\n */\nfunction genLevelComparison (levelComparison) {\n if (typeof levelComparison === 'string') {\n return compareLevel.bind(null, levelComparison)\n }\n\n return levelComparison\n}\n\nfunction mappings (customLevels = null, useOnlyCustomLevels = false) {\n const customNums = customLevels\n /* eslint-disable */\n ? Object.keys(customLevels).reduce((o, k) => {\n o[customLevels[k]] = k\n return o\n }, {})\n : null\n /* eslint-enable */\n\n const labels = Object.assign(\n Object.create(Object.prototype, { Infinity: { value: 'silent' } }),\n useOnlyCustomLevels ? null : nums,\n customNums\n )\n const values = Object.assign(\n Object.create(Object.prototype, { silent: { value: Infinity } }),\n useOnlyCustomLevels ? null : DEFAULT_LEVELS,\n customLevels\n )\n return { labels, values }\n}\n\nfunction assertDefaultLevelFound (defaultLevel, customLevels, useOnlyCustomLevels) {\n if (typeof defaultLevel === 'number') {\n const values = [].concat(\n Object.keys(customLevels || {}).map(key => customLevels[key]),\n useOnlyCustomLevels ? [] : Object.keys(nums).map(level => +level),\n Infinity\n )\n if (!values.includes(defaultLevel)) {\n throw Error(`default level:${defaultLevel} must be included in custom levels`)\n }\n return\n }\n\n const labels = Object.assign(\n Object.create(Object.prototype, { silent: { value: Infinity } }),\n useOnlyCustomLevels ? null : DEFAULT_LEVELS,\n customLevels\n )\n if (!(defaultLevel in labels)) {\n throw Error(`default level:${defaultLevel} must be included in custom levels`)\n }\n}\n\nfunction assertNoLevelCollisions (levels, customLevels) {\n const { labels, values } = levels\n for (const k in customLevels) {\n if (k in values) {\n throw Error('levels cannot be overridden')\n }\n if (customLevels[k] in labels) {\n throw Error('pre-existing level values cannot be used for new levels')\n }\n }\n}\n\n/**\n * Validates whether `levelComparison` is correct\n *\n * @throws Error\n * @param {SORTING_ORDER | Function} levelComparison - value to validate\n * @returns\n */\nfunction assertLevelComparison (levelComparison) {\n if (typeof levelComparison === 'function') {\n return\n }\n\n if (typeof levelComparison === 'string' && Object.values(SORTING_ORDER).includes(levelComparison)) {\n return\n }\n\n throw new Error('Levels comparison should be one of \"ASC\", \"DESC\" or \"function\" type')\n}\n\nmodule.exports = {\n initialLsCache,\n genLsCache,\n levelMethods,\n getLevel,\n setLevel,\n isLevelEnabled,\n mappings,\n assertNoLevelCollisions,\n assertDefaultLevelFound,\n genLevelComparison,\n assertLevelComparison\n}\n", "'use strict'\n\nmodule.exports = { version: '9.7.0' }\n", "'use strict'\n\n/* eslint no-prototype-builtins: 0 */\n\nconst { EventEmitter } = require('node:events')\nconst {\n lsCacheSym,\n levelValSym,\n setLevelSym,\n getLevelSym,\n chindingsSym,\n parsedChindingsSym,\n mixinSym,\n asJsonSym,\n writeSym,\n mixinMergeStrategySym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n serializersSym,\n formattersSym,\n errorKeySym,\n messageKeySym,\n useOnlyCustomLevelsSym,\n needsMetadataGsym,\n redactFmtSym,\n stringifySym,\n formatOptsSym,\n stringifiersSym,\n msgPrefixSym,\n hooksSym\n} = require('./symbols')\nconst {\n getLevel,\n setLevel,\n isLevelEnabled,\n mappings,\n initialLsCache,\n genLsCache,\n assertNoLevelCollisions\n} = require('./levels')\nconst {\n asChindings,\n asJson,\n buildFormatters,\n stringify\n} = require('./tools')\nconst {\n version\n} = require('./meta')\nconst redaction = require('./redaction')\n\n// note: use of class is satirical\n// https://github.com/pinojs/pino/pull/433#pullrequestreview-127703127\nconst constructor = class Pino {}\nconst prototype = {\n constructor,\n child,\n bindings,\n setBindings,\n flush,\n isLevelEnabled,\n version,\n get level () { return this[getLevelSym]() },\n set level (lvl) { this[setLevelSym](lvl) },\n get levelVal () { return this[levelValSym] },\n set levelVal (n) { throw Error('levelVal is read-only') },\n [lsCacheSym]: initialLsCache,\n [writeSym]: write,\n [asJsonSym]: asJson,\n [getLevelSym]: getLevel,\n [setLevelSym]: setLevel\n}\n\nObject.setPrototypeOf(prototype, EventEmitter.prototype)\n\n// exporting and consuming the prototype object using factory pattern fixes scoping issues with getters when serializing\nmodule.exports = function () {\n return Object.create(prototype)\n}\n\nconst resetChildingsFormatter = bindings => bindings\nfunction child (bindings, options) {\n if (!bindings) {\n throw Error('missing bindings for child Pino')\n }\n options = options || {} // default options to empty object\n const serializers = this[serializersSym]\n const formatters = this[formattersSym]\n const instance = Object.create(this)\n\n if (options.hasOwnProperty('serializers') === true) {\n instance[serializersSym] = Object.create(null)\n\n for (const k in serializers) {\n instance[serializersSym][k] = serializers[k]\n }\n const parentSymbols = Object.getOwnPropertySymbols(serializers)\n /* eslint no-var: off */\n for (var i = 0; i < parentSymbols.length; i++) {\n const ks = parentSymbols[i]\n instance[serializersSym][ks] = serializers[ks]\n }\n\n for (const bk in options.serializers) {\n instance[serializersSym][bk] = options.serializers[bk]\n }\n const bindingsSymbols = Object.getOwnPropertySymbols(options.serializers)\n for (var bi = 0; bi < bindingsSymbols.length; bi++) {\n const bks = bindingsSymbols[bi]\n instance[serializersSym][bks] = options.serializers[bks]\n }\n } else instance[serializersSym] = serializers\n if (options.hasOwnProperty('formatters')) {\n const { level, bindings: chindings, log } = options.formatters\n instance[formattersSym] = buildFormatters(\n level || formatters.level,\n chindings || resetChildingsFormatter,\n log || formatters.log\n )\n } else {\n instance[formattersSym] = buildFormatters(\n formatters.level,\n resetChildingsFormatter,\n formatters.log\n )\n }\n if (options.hasOwnProperty('customLevels') === true) {\n assertNoLevelCollisions(this.levels, options.customLevels)\n instance.levels = mappings(options.customLevels, instance[useOnlyCustomLevelsSym])\n genLsCache(instance)\n }\n\n // redact must place before asChindings and only replace if exist\n if ((typeof options.redact === 'object' && options.redact !== null) || Array.isArray(options.redact)) {\n instance.redact = options.redact // replace redact directly\n const stringifiers = redaction(instance.redact, stringify)\n const formatOpts = { stringify: stringifiers[redactFmtSym] }\n instance[stringifySym] = stringify\n instance[stringifiersSym] = stringifiers\n instance[formatOptsSym] = formatOpts\n }\n\n if (typeof options.msgPrefix === 'string') {\n instance[msgPrefixSym] = (this[msgPrefixSym] || '') + options.msgPrefix\n }\n\n instance[chindingsSym] = asChindings(instance, bindings)\n const childLevel = options.level || this.level\n instance[setLevelSym](childLevel)\n this.onChild(instance)\n return instance\n}\n\nfunction bindings () {\n const chindings = this[chindingsSym]\n const chindingsJson = `{${chindings.substr(1)}}` // at least contains ,\"pid\":7068,\"hostname\":\"myMac\"\n const bindingsFromJson = JSON.parse(chindingsJson)\n delete bindingsFromJson.pid\n delete bindingsFromJson.hostname\n return bindingsFromJson\n}\n\nfunction setBindings (newBindings) {\n const chindings = asChindings(this, newBindings)\n this[chindingsSym] = chindings\n delete this[parsedChindingsSym]\n}\n\n/**\n * Default strategy for creating `mergeObject` from arguments and the result from `mixin()`.\n * Fields from `mergeObject` have higher priority in this strategy.\n *\n * @param {Object} mergeObject The object a user has supplied to the logging function.\n * @param {Object} mixinObject The result of the `mixin` method.\n * @return {Object}\n */\nfunction defaultMixinMergeStrategy (mergeObject, mixinObject) {\n return Object.assign(mixinObject, mergeObject)\n}\n\nfunction write (_obj, msg, num) {\n const t = this[timeSym]()\n const mixin = this[mixinSym]\n const errorKey = this[errorKeySym]\n const messageKey = this[messageKeySym]\n const mixinMergeStrategy = this[mixinMergeStrategySym] || defaultMixinMergeStrategy\n let obj\n const streamWriteHook = this[hooksSym].streamWrite\n\n if (_obj === undefined || _obj === null) {\n obj = {}\n } else if (_obj instanceof Error) {\n obj = { [errorKey]: _obj }\n if (msg === undefined) {\n msg = _obj.message\n }\n } else {\n obj = _obj\n if (msg === undefined && _obj[messageKey] === undefined && _obj[errorKey]) {\n msg = _obj[errorKey].message\n }\n }\n\n if (mixin) {\n obj = mixinMergeStrategy(obj, mixin(obj, num, this))\n }\n\n const s = this[asJsonSym](obj, msg, num, t)\n\n const stream = this[streamSym]\n if (stream[needsMetadataGsym] === true) {\n stream.lastLevel = num\n stream.lastObj = obj\n stream.lastMsg = msg\n stream.lastTime = t.slice(this[timeSliceIndexSym])\n stream.lastLogger = this // for child loggers\n }\n stream.write(streamWriteHook ? streamWriteHook(s) : s)\n}\n\nfunction noop () {}\n\nfunction flush (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw Error('callback must be a function')\n }\n\n const stream = this[streamSym]\n\n if (typeof stream.flush === 'function') {\n stream.flush(cb || noop)\n } else if (cb) cb()\n}\n", "'use strict'\n\nconst { hasOwnProperty } = Object.prototype\n\nconst stringify = configure()\n\n// @ts-expect-error\nstringify.configure = configure\n// @ts-expect-error\nstringify.stringify = stringify\n\n// @ts-expect-error\nstringify.default = stringify\n\n// @ts-expect-error used for named export\nexports.stringify = stringify\n// @ts-expect-error used for named export\nexports.configure = configure\n\nmodule.exports = stringify\n\n// eslint-disable-next-line no-control-regex\nconst strEscapeSequencesRegExp = /[\\u0000-\\u001f\\u0022\\u005c\\ud800-\\udfff]/\n\n// Escape C0 control characters, double quotes, the backslash and every code\n// unit with a numeric value in the inclusive range 0xD800 to 0xDFFF.\nfunction strEscape (str) {\n // Some magic numbers that worked out fine while benchmarking with v8 8.0\n if (str.length < 5000 && !strEscapeSequencesRegExp.test(str)) {\n return `\"${str}\"`\n }\n return JSON.stringify(str)\n}\n\nfunction sort (array, comparator) {\n // Insertion sort is very efficient for small input sizes, but it has a bad\n // worst case complexity. Thus, use native array sort for bigger values.\n if (array.length > 2e2 || comparator) {\n return array.sort(comparator)\n }\n for (let i = 1; i < array.length; i++) {\n const currentValue = array[i]\n let position = i\n while (position !== 0 && array[position - 1] > currentValue) {\n array[position] = array[position - 1]\n position--\n }\n array[position] = currentValue\n }\n return array\n}\n\nconst typedArrayPrototypeGetSymbolToStringTag =\n Object.getOwnPropertyDescriptor(\n Object.getPrototypeOf(\n Object.getPrototypeOf(\n new Int8Array()\n )\n ),\n Symbol.toStringTag\n ).get\n\nfunction isTypedArrayWithEntries (value) {\n return typedArrayPrototypeGetSymbolToStringTag.call(value) !== undefined && value.length !== 0\n}\n\nfunction stringifyTypedArray (array, separator, maximumBreadth) {\n if (array.length < maximumBreadth) {\n maximumBreadth = array.length\n }\n const whitespace = separator === ',' ? '' : ' '\n let res = `\"0\":${whitespace}${array[0]}`\n for (let i = 1; i < maximumBreadth; i++) {\n res += `${separator}\"${i}\":${whitespace}${array[i]}`\n }\n return res\n}\n\nfunction getCircularValueOption (options) {\n if (hasOwnProperty.call(options, 'circularValue')) {\n const circularValue = options.circularValue\n if (typeof circularValue === 'string') {\n return `\"${circularValue}\"`\n }\n if (circularValue == null) {\n return circularValue\n }\n if (circularValue === Error || circularValue === TypeError) {\n return {\n toString () {\n throw new TypeError('Converting circular structure to JSON')\n }\n }\n }\n throw new TypeError('The \"circularValue\" argument must be of type string or the value null or undefined')\n }\n return '\"[Circular]\"'\n}\n\nfunction getDeterministicOption (options) {\n let value\n if (hasOwnProperty.call(options, 'deterministic')) {\n value = options.deterministic\n if (typeof value !== 'boolean' && typeof value !== 'function') {\n throw new TypeError('The \"deterministic\" argument must be of type boolean or comparator function')\n }\n }\n return value === undefined ? true : value\n}\n\nfunction getBooleanOption (options, key) {\n let value\n if (hasOwnProperty.call(options, key)) {\n value = options[key]\n if (typeof value !== 'boolean') {\n throw new TypeError(`The \"${key}\" argument must be of type boolean`)\n }\n }\n return value === undefined ? true : value\n}\n\nfunction getPositiveIntegerOption (options, key) {\n let value\n if (hasOwnProperty.call(options, key)) {\n value = options[key]\n if (typeof value !== 'number') {\n throw new TypeError(`The \"${key}\" argument must be of type number`)\n }\n if (!Number.isInteger(value)) {\n throw new TypeError(`The \"${key}\" argument must be an integer`)\n }\n if (value < 1) {\n throw new RangeError(`The \"${key}\" argument must be >= 1`)\n }\n }\n return value === undefined ? Infinity : value\n}\n\nfunction getItemCount (number) {\n if (number === 1) {\n return '1 item'\n }\n return `${number} items`\n}\n\nfunction getUniqueReplacerSet (replacerArray) {\n const replacerSet = new Set()\n for (const value of replacerArray) {\n if (typeof value === 'string' || typeof value === 'number') {\n replacerSet.add(String(value))\n }\n }\n return replacerSet\n}\n\nfunction getStrictOption (options) {\n if (hasOwnProperty.call(options, 'strict')) {\n const value = options.strict\n if (typeof value !== 'boolean') {\n throw new TypeError('The \"strict\" argument must be of type boolean')\n }\n if (value) {\n return (value) => {\n let message = `Object can not safely be stringified. Received type ${typeof value}`\n if (typeof value !== 'function') message += ` (${value.toString()})`\n throw new Error(message)\n }\n }\n }\n}\n\nfunction configure (options) {\n options = { ...options }\n const fail = getStrictOption(options)\n if (fail) {\n if (options.bigint === undefined) {\n options.bigint = false\n }\n if (!('circularValue' in options)) {\n options.circularValue = Error\n }\n }\n const circularValue = getCircularValueOption(options)\n const bigint = getBooleanOption(options, 'bigint')\n const deterministic = getDeterministicOption(options)\n const comparator = typeof deterministic === 'function' ? deterministic : undefined\n const maximumDepth = getPositiveIntegerOption(options, 'maximumDepth')\n const maximumBreadth = getPositiveIntegerOption(options, 'maximumBreadth')\n\n function stringifyFnReplacer (key, parent, stack, replacer, spacer, indentation) {\n let value = parent[key]\n\n if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n }\n value = replacer.call(parent, key, value)\n\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n\n let res = ''\n let join = ','\n const originalIndentation = indentation\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n if (spacer !== '') {\n indentation += spacer\n res += `\\n${indentation}`\n join = `,\\n${indentation}`\n }\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n res += join\n }\n const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n if (spacer !== '') {\n res += `\\n${originalIndentation}`\n }\n stack.pop()\n return `[${res}]`\n }\n\n let keys = Object.keys(value)\n const keyLength = keys.length\n if (keyLength === 0) {\n return '{}'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Object]\"'\n }\n let whitespace = ''\n let separator = ''\n if (spacer !== '') {\n indentation += spacer\n join = `,\\n${indentation}`\n whitespace = ' '\n }\n const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n if (deterministic && !isTypedArrayWithEntries(value)) {\n keys = sort(keys, comparator)\n }\n stack.push(value)\n for (let i = 0; i < maximumPropertiesToStringify; i++) {\n const key = keys[i]\n const tmp = stringifyFnReplacer(key, value, stack, replacer, spacer, indentation)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}:${whitespace}${tmp}`\n separator = join\n }\n }\n if (keyLength > maximumBreadth) {\n const removedKeys = keyLength - maximumBreadth\n res += `${separator}\"...\":${whitespace}\"${getItemCount(removedKeys)} not stringified\"`\n separator = join\n }\n if (spacer !== '' && separator.length > 1) {\n res = `\\n${indentation}${res}\\n${originalIndentation}`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringifyArrayReplacer (key, value, stack, replacer, spacer, indentation) {\n if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n }\n\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n\n const originalIndentation = indentation\n let res = ''\n let join = ','\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n if (spacer !== '') {\n indentation += spacer\n res += `\\n${indentation}`\n join = `,\\n${indentation}`\n }\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n res += join\n }\n const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n if (spacer !== '') {\n res += `\\n${originalIndentation}`\n }\n stack.pop()\n return `[${res}]`\n }\n stack.push(value)\n let whitespace = ''\n if (spacer !== '') {\n indentation += spacer\n join = `,\\n${indentation}`\n whitespace = ' '\n }\n let separator = ''\n for (const key of replacer) {\n const tmp = stringifyArrayReplacer(key, value[key], stack, replacer, spacer, indentation)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}:${whitespace}${tmp}`\n separator = join\n }\n }\n if (spacer !== '' && separator.length > 1) {\n res = `\\n${indentation}${res}\\n${originalIndentation}`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringifyIndent (key, value, stack, spacer, indentation) {\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n // Prevent calling `toJSON` again.\n if (typeof value !== 'object') {\n return stringifyIndent(key, value, stack, spacer, indentation)\n }\n if (value === null) {\n return 'null'\n }\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n const originalIndentation = indentation\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n indentation += spacer\n let res = `\\n${indentation}`\n const join = `,\\n${indentation}`\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n res += join\n }\n const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n res += `\\n${originalIndentation}`\n stack.pop()\n return `[${res}]`\n }\n\n let keys = Object.keys(value)\n const keyLength = keys.length\n if (keyLength === 0) {\n return '{}'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Object]\"'\n }\n indentation += spacer\n const join = `,\\n${indentation}`\n let res = ''\n let separator = ''\n let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n if (isTypedArrayWithEntries(value)) {\n res += stringifyTypedArray(value, join, maximumBreadth)\n keys = keys.slice(value.length)\n maximumPropertiesToStringify -= value.length\n separator = join\n }\n if (deterministic) {\n keys = sort(keys, comparator)\n }\n stack.push(value)\n for (let i = 0; i < maximumPropertiesToStringify; i++) {\n const key = keys[i]\n const tmp = stringifyIndent(key, value[key], stack, spacer, indentation)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}: ${tmp}`\n separator = join\n }\n }\n if (keyLength > maximumBreadth) {\n const removedKeys = keyLength - maximumBreadth\n res += `${separator}\"...\": \"${getItemCount(removedKeys)} not stringified\"`\n separator = join\n }\n if (separator !== '') {\n res = `\\n${indentation}${res}\\n${originalIndentation}`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringifySimple (key, value, stack) {\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n // Prevent calling `toJSON` again\n if (typeof value !== 'object') {\n return stringifySimple(key, value, stack)\n }\n if (value === null) {\n return 'null'\n }\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n\n let res = ''\n\n const hasLength = value.length !== undefined\n if (hasLength && Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifySimple(String(i), value[i], stack)\n res += tmp !== undefined ? tmp : 'null'\n res += ','\n }\n const tmp = stringifySimple(String(i), value[i], stack)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `,\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n stack.pop()\n return `[${res}]`\n }\n\n let keys = Object.keys(value)\n const keyLength = keys.length\n if (keyLength === 0) {\n return '{}'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Object]\"'\n }\n let separator = ''\n let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n if (hasLength && isTypedArrayWithEntries(value)) {\n res += stringifyTypedArray(value, ',', maximumBreadth)\n keys = keys.slice(value.length)\n maximumPropertiesToStringify -= value.length\n separator = ','\n }\n if (deterministic) {\n keys = sort(keys, comparator)\n }\n stack.push(value)\n for (let i = 0; i < maximumPropertiesToStringify; i++) {\n const key = keys[i]\n const tmp = stringifySimple(key, value[key], stack)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}:${tmp}`\n separator = ','\n }\n }\n if (keyLength > maximumBreadth) {\n const removedKeys = keyLength - maximumBreadth\n res += `${separator}\"...\":\"${getItemCount(removedKeys)} not stringified\"`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringify (value, replacer, space) {\n if (arguments.length > 1) {\n let spacer = ''\n if (typeof space === 'number') {\n spacer = ' '.repeat(Math.min(space, 10))\n } else if (typeof space === 'string') {\n spacer = space.slice(0, 10)\n }\n if (replacer != null) {\n if (typeof replacer === 'function') {\n return stringifyFnReplacer('', { '': value }, [], replacer, spacer, '')\n }\n if (Array.isArray(replacer)) {\n return stringifyArrayReplacer('', value, [], getUniqueReplacerSet(replacer), spacer, '')\n }\n }\n if (spacer.length !== 0) {\n return stringifyIndent('', value, [], spacer, '')\n }\n }\n return stringifySimple('', value, [])\n }\n\n return stringify\n}\n", "'use strict'\n\nconst metadata = Symbol.for('pino.metadata')\nconst { DEFAULT_LEVELS } = require('./constants')\n\nconst DEFAULT_INFO_LEVEL = DEFAULT_LEVELS.info\n\nfunction multistream (streamsArray, opts) {\n let counter = 0\n streamsArray = streamsArray || []\n opts = opts || { dedupe: false }\n\n const streamLevels = Object.create(DEFAULT_LEVELS)\n streamLevels.silent = Infinity\n if (opts.levels && typeof opts.levels === 'object') {\n Object.keys(opts.levels).forEach(i => {\n streamLevels[i] = opts.levels[i]\n })\n }\n\n const res = {\n write,\n add,\n emit,\n flushSync,\n end,\n minLevel: 0,\n streams: [],\n clone,\n [metadata]: true,\n streamLevels\n }\n\n if (Array.isArray(streamsArray)) {\n streamsArray.forEach(add, res)\n } else {\n add.call(res, streamsArray)\n }\n\n // clean this object up\n // or it will stay allocated forever\n // as it is closed on the following closures\n streamsArray = null\n\n return res\n\n // we can exit early because the streams are ordered by level\n function write (data) {\n let dest\n const level = this.lastLevel\n const { streams } = this\n // for handling situation when several streams has the same level\n let recordedLevel = 0\n let stream\n\n // if dedupe set to true we send logs to the stream with the highest level\n // therefore, we have to change sorting order\n for (let i = initLoopVar(streams.length, opts.dedupe); checkLoopVar(i, streams.length, opts.dedupe); i = adjustLoopVar(i, opts.dedupe)) {\n dest = streams[i]\n if (dest.level <= level) {\n if (recordedLevel !== 0 && recordedLevel !== dest.level) {\n break\n }\n stream = dest.stream\n if (stream[metadata]) {\n const { lastTime, lastMsg, lastObj, lastLogger } = this\n stream.lastLevel = level\n stream.lastTime = lastTime\n stream.lastMsg = lastMsg\n stream.lastObj = lastObj\n stream.lastLogger = lastLogger\n }\n stream.write(data)\n if (opts.dedupe) {\n recordedLevel = dest.level\n }\n } else if (!opts.dedupe) {\n break\n }\n }\n }\n\n function emit (...args) {\n for (const { stream } of this.streams) {\n if (typeof stream.emit === 'function') {\n stream.emit(...args)\n }\n }\n }\n\n function flushSync () {\n for (const { stream } of this.streams) {\n if (typeof stream.flushSync === 'function') {\n stream.flushSync()\n }\n }\n }\n\n function add (dest) {\n if (!dest) {\n return res\n }\n\n // Check that dest implements either StreamEntry or DestinationStream\n const isStream = typeof dest.write === 'function' || dest.stream\n const stream_ = dest.write ? dest : dest.stream\n // This is necessary to provide a meaningful error message, otherwise it throws somewhere inside write()\n if (!isStream) {\n throw Error('stream object needs to implement either StreamEntry or DestinationStream interface')\n }\n\n const { streams, streamLevels } = this\n\n let level\n if (typeof dest.levelVal === 'number') {\n level = dest.levelVal\n } else if (typeof dest.level === 'string') {\n level = streamLevels[dest.level]\n } else if (typeof dest.level === 'number') {\n level = dest.level\n } else {\n level = DEFAULT_INFO_LEVEL\n }\n\n const dest_ = {\n stream: stream_,\n level,\n levelVal: undefined,\n id: counter++\n }\n\n streams.unshift(dest_)\n streams.sort(compareByLevel)\n\n this.minLevel = streams[0].level\n\n return res\n }\n\n function end () {\n for (const { stream } of this.streams) {\n if (typeof stream.flushSync === 'function') {\n stream.flushSync()\n }\n stream.end()\n }\n }\n\n function clone (level) {\n const streams = new Array(this.streams.length)\n\n for (let i = 0; i < streams.length; i++) {\n streams[i] = {\n level,\n stream: this.streams[i].stream\n }\n }\n\n return {\n write,\n add,\n minLevel: level,\n streams,\n clone,\n emit,\n flushSync,\n [metadata]: true\n }\n }\n}\n\nfunction compareByLevel (a, b) {\n return a.level - b.level\n}\n\nfunction initLoopVar (length, dedupe) {\n return dedupe ? length - 1 : 0\n}\n\nfunction adjustLoopVar (i, dedupe) {\n return dedupe ? i - 1 : i + 1\n}\n\nfunction checkLoopVar (i, length, dedupe) {\n return dedupe ? i >= 0 : i < length\n}\n\nmodule.exports = multistream\n", "\n function pinoBundlerAbsolutePath(p) {\n try {\n return require('path').join(`${process.cwd()}${require('path').sep}dist/esm`.replace(/\\\\/g, '/'), p)\n } catch(e) {\n const f = new Function('p', 'return new URL(p, import.meta.url).pathname');\n return f(p)\n }\n }\n \n globalThis.__bundlerPathsOverrides = { ...(globalThis.__bundlerPathsOverrides || {}), 'thread-stream-worker': pinoBundlerAbsolutePath('./thread-stream-worker.mjs'),'pino-worker': pinoBundlerAbsolutePath('./pino-worker.mjs'),'pino/file': pinoBundlerAbsolutePath('./pino-file.mjs'),'pino-roll': pinoBundlerAbsolutePath('./pino-roll.mjs')}\n 'use strict'\n\nconst os = require('node:os')\nconst stdSerializers = require('pino-std-serializers')\nconst caller = require('./lib/caller')\nconst redaction = require('./lib/redaction')\nconst time = require('./lib/time')\nconst proto = require('./lib/proto')\nconst symbols = require('./lib/symbols')\nconst { configure } = require('safe-stable-stringify')\nconst { assertDefaultLevelFound, mappings, genLsCache, genLevelComparison, assertLevelComparison } = require('./lib/levels')\nconst { DEFAULT_LEVELS, SORTING_ORDER } = require('./lib/constants')\nconst {\n createArgsNormalizer,\n asChindings,\n buildSafeSonicBoom,\n buildFormatters,\n stringify,\n normalizeDestFileDescriptor,\n noop\n} = require('./lib/tools')\nconst { version } = require('./lib/meta')\nconst {\n chindingsSym,\n redactFmtSym,\n serializersSym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n stringifySym,\n stringifySafeSym,\n stringifiersSym,\n setLevelSym,\n endSym,\n formatOptsSym,\n messageKeySym,\n errorKeySym,\n nestedKeySym,\n mixinSym,\n levelCompSym,\n useOnlyCustomLevelsSym,\n formattersSym,\n hooksSym,\n nestedKeyStrSym,\n mixinMergeStrategySym,\n msgPrefixSym\n} = symbols\nconst { epochTime, nullTime } = time\nconst { pid } = process\nconst hostname = os.hostname()\nconst defaultErrorSerializer = stdSerializers.err\nconst defaultOptions = {\n level: 'info',\n levelComparison: SORTING_ORDER.ASC,\n levels: DEFAULT_LEVELS,\n messageKey: 'msg',\n errorKey: 'err',\n nestedKey: null,\n enabled: true,\n base: { pid, hostname },\n serializers: Object.assign(Object.create(null), {\n err: defaultErrorSerializer\n }),\n formatters: Object.assign(Object.create(null), {\n bindings (bindings) {\n return bindings\n },\n level (label, number) {\n return { level: number }\n }\n }),\n hooks: {\n logMethod: undefined,\n streamWrite: undefined\n },\n timestamp: epochTime,\n name: undefined,\n redact: null,\n customLevels: null,\n useOnlyCustomLevels: false,\n depthLimit: 5,\n edgeLimit: 100\n}\n\nconst normalize = createArgsNormalizer(defaultOptions)\n\nconst serializers = Object.assign(Object.create(null), stdSerializers)\n\nfunction pino (...args) {\n const instance = {}\n const { opts, stream } = normalize(instance, caller(), ...args)\n\n if (opts.level && typeof opts.level === 'string' && DEFAULT_LEVELS[opts.level.toLowerCase()] !== undefined) opts.level = opts.level.toLowerCase()\n\n const {\n redact,\n crlf,\n serializers,\n timestamp,\n messageKey,\n errorKey,\n nestedKey,\n base,\n name,\n level,\n customLevels,\n levelComparison,\n mixin,\n mixinMergeStrategy,\n useOnlyCustomLevels,\n formatters,\n hooks,\n depthLimit,\n edgeLimit,\n onChild,\n msgPrefix\n } = opts\n\n const stringifySafe = configure({\n maximumDepth: depthLimit,\n maximumBreadth: edgeLimit\n })\n\n const allFormatters = buildFormatters(\n formatters.level,\n formatters.bindings,\n formatters.log\n )\n\n const stringifyFn = stringify.bind({\n [stringifySafeSym]: stringifySafe\n })\n const stringifiers = redact ? redaction(redact, stringifyFn) : {}\n const formatOpts = redact\n ? { stringify: stringifiers[redactFmtSym] }\n : { stringify: stringifyFn }\n const end = '}' + (crlf ? '\\r\\n' : '\\n')\n const coreChindings = asChindings.bind(null, {\n [chindingsSym]: '',\n [serializersSym]: serializers,\n [stringifiersSym]: stringifiers,\n [stringifySym]: stringify,\n [stringifySafeSym]: stringifySafe,\n [formattersSym]: allFormatters\n })\n\n let chindings = ''\n if (base !== null) {\n if (name === undefined) {\n chindings = coreChindings(base)\n } else {\n chindings = coreChindings(Object.assign({}, base, { name }))\n }\n }\n\n const time = (timestamp instanceof Function)\n ? timestamp\n : (timestamp ? epochTime : nullTime)\n const timeSliceIndex = time().indexOf(':') + 1\n\n if (useOnlyCustomLevels && !customLevels) throw Error('customLevels is required if useOnlyCustomLevels is set true')\n if (mixin && typeof mixin !== 'function') throw Error(`Unknown mixin type \"${typeof mixin}\" - expected \"function\"`)\n if (msgPrefix && typeof msgPrefix !== 'string') throw Error(`Unknown msgPrefix type \"${typeof msgPrefix}\" - expected \"string\"`)\n\n assertDefaultLevelFound(level, customLevels, useOnlyCustomLevels)\n const levels = mappings(customLevels, useOnlyCustomLevels)\n\n if (typeof stream.emit === 'function') {\n stream.emit('message', { code: 'PINO_CONFIG', config: { levels, messageKey, errorKey } })\n }\n\n assertLevelComparison(levelComparison)\n const levelCompFunc = genLevelComparison(levelComparison)\n\n Object.assign(instance, {\n levels,\n [levelCompSym]: levelCompFunc,\n [useOnlyCustomLevelsSym]: useOnlyCustomLevels,\n [streamSym]: stream,\n [timeSym]: time,\n [timeSliceIndexSym]: timeSliceIndex,\n [stringifySym]: stringify,\n [stringifySafeSym]: stringifySafe,\n [stringifiersSym]: stringifiers,\n [endSym]: end,\n [formatOptsSym]: formatOpts,\n [messageKeySym]: messageKey,\n [errorKeySym]: errorKey,\n [nestedKeySym]: nestedKey,\n // protect against injection\n [nestedKeyStrSym]: nestedKey ? `,${JSON.stringify(nestedKey)}:{` : '',\n [serializersSym]: serializers,\n [mixinSym]: mixin,\n [mixinMergeStrategySym]: mixinMergeStrategy,\n [chindingsSym]: chindings,\n [formattersSym]: allFormatters,\n [hooksSym]: hooks,\n silent: noop,\n onChild,\n [msgPrefixSym]: msgPrefix\n })\n\n Object.setPrototypeOf(instance, proto())\n\n genLsCache(instance)\n\n instance[setLevelSym](level)\n\n return instance\n}\n\nmodule.exports = pino\n\nmodule.exports.destination = (dest = process.stdout.fd) => {\n if (typeof dest === 'object') {\n dest.dest = normalizeDestFileDescriptor(dest.dest || process.stdout.fd)\n return buildSafeSonicBoom(dest)\n } else {\n return buildSafeSonicBoom({ dest: normalizeDestFileDescriptor(dest), minLength: 0 })\n }\n}\n\nmodule.exports.transport = require('./lib/transport')\nmodule.exports.multistream = require('./lib/multistream')\n\nmodule.exports.levels = mappings()\nmodule.exports.stdSerializers = serializers\nmodule.exports.stdTimeFunctions = Object.assign({}, time)\nmodule.exports.symbols = symbols\nmodule.exports.version = version\n\n// Enables default and name export with TypeScript and Babel\nmodule.exports.default = pino\nmodule.exports.pino = pino\n", "/*\nCopyright (c) 2014-2021, Matteo Collina \n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted, provided that the above\ncopyright notice and this permission notice appear in all copies.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\nWITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\nANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR\nIN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*/\n\n'use strict'\n\nconst { Transform } = require('stream')\nconst { StringDecoder } = require('string_decoder')\nconst kLast = Symbol('last')\nconst kDecoder = Symbol('decoder')\n\nfunction transform (chunk, enc, cb) {\n let list\n if (this.overflow) { // Line buffer is full. Skip to start of next line.\n const buf = this[kDecoder].write(chunk)\n list = buf.split(this.matcher)\n\n if (list.length === 1) return cb() // Line ending not found. Discard entire chunk.\n\n // Line ending found. Discard trailing fragment of previous line and reset overflow state.\n list.shift()\n this.overflow = false\n } else {\n this[kLast] += this[kDecoder].write(chunk)\n list = this[kLast].split(this.matcher)\n }\n\n this[kLast] = list.pop()\n\n for (let i = 0; i < list.length; i++) {\n try {\n push(this, this.mapper(list[i]))\n } catch (error) {\n return cb(error)\n }\n }\n\n this.overflow = this[kLast].length > this.maxLength\n if (this.overflow && !this.skipOverflow) {\n cb(new Error('maximum buffer reached'))\n return\n }\n\n cb()\n}\n\nfunction flush (cb) {\n // forward any gibberish left in there\n this[kLast] += this[kDecoder].end()\n\n if (this[kLast]) {\n try {\n push(this, this.mapper(this[kLast]))\n } catch (error) {\n return cb(error)\n }\n }\n\n cb()\n}\n\nfunction push (self, val) {\n if (val !== undefined) {\n self.push(val)\n }\n}\n\nfunction noop (incoming) {\n return incoming\n}\n\nfunction split (matcher, mapper, options) {\n // Set defaults for any arguments not supplied.\n matcher = matcher || /\\r?\\n/\n mapper = mapper || noop\n options = options || {}\n\n // Test arguments explicitly.\n switch (arguments.length) {\n case 1:\n // If mapper is only argument.\n if (typeof matcher === 'function') {\n mapper = matcher\n matcher = /\\r?\\n/\n // If options is only argument.\n } else if (typeof matcher === 'object' && !(matcher instanceof RegExp) && !matcher[Symbol.split]) {\n options = matcher\n matcher = /\\r?\\n/\n }\n break\n\n case 2:\n // If mapper and options are arguments.\n if (typeof matcher === 'function') {\n options = mapper\n mapper = matcher\n matcher = /\\r?\\n/\n // If matcher and options are arguments.\n } else if (typeof mapper === 'object') {\n options = mapper\n mapper = noop\n }\n }\n\n options = Object.assign({}, options)\n options.autoDestroy = true\n options.transform = transform\n options.flush = flush\n options.readableObjectMode = true\n\n const stream = new Transform(options)\n\n stream[kLast] = ''\n stream[kDecoder] = new StringDecoder('utf8')\n stream.matcher = matcher\n stream.mapper = mapper\n stream.maxLength = options.maxLength\n stream.skipOverflow = options.skipOverflow || false\n stream.overflow = false\n stream._destroy = function (err, cb) {\n // Weird Node v12 bug that we need to work around\n this._writableState.errorEmitted = false\n cb(err)\n }\n\n return stream\n}\n\nmodule.exports = split\n", "'use strict'\n\nconst metadata = Symbol.for('pino.metadata')\nconst split = require('split2')\nconst { Duplex } = require('stream')\nconst { parentPort, workerData } = require('worker_threads')\n\nfunction createDeferred () {\n let resolve\n let reject\n const promise = new Promise((_resolve, _reject) => {\n resolve = _resolve\n reject = _reject\n })\n promise.resolve = resolve\n promise.reject = reject\n return promise\n}\n\nmodule.exports = function build (fn, opts = {}) {\n const waitForConfig = opts.expectPinoConfig === true && workerData?.workerData?.pinoWillSendConfig === true\n const parseLines = opts.parse === 'lines'\n const parseLine = typeof opts.parseLine === 'function' ? opts.parseLine : JSON.parse\n const close = opts.close || defaultClose\n const stream = split(function (line) {\n let value\n\n try {\n value = parseLine(line)\n } catch (error) {\n this.emit('unknown', line, error)\n return\n }\n\n if (value === null) {\n this.emit('unknown', line, 'Null value ignored')\n return\n }\n\n if (typeof value !== 'object') {\n value = {\n data: value,\n time: Date.now()\n }\n }\n\n if (stream[metadata]) {\n stream.lastTime = value.time\n stream.lastLevel = value.level\n stream.lastObj = value\n }\n\n if (parseLines) {\n return line\n }\n\n return value\n }, { autoDestroy: true })\n\n stream._destroy = function (err, cb) {\n const promise = close(err, cb)\n if (promise && typeof promise.then === 'function') {\n promise.then(cb, cb)\n }\n }\n\n if (opts.expectPinoConfig === true && workerData?.workerData?.pinoWillSendConfig !== true) {\n setImmediate(() => {\n stream.emit('error', new Error('This transport is not compatible with the current version of pino. Please upgrade pino to the latest version.'))\n })\n }\n\n if (opts.metadata !== false) {\n stream[metadata] = true\n stream.lastTime = 0\n stream.lastLevel = 0\n stream.lastObj = null\n }\n\n if (waitForConfig) {\n let pinoConfig = {}\n const configReceived = createDeferred()\n parentPort.on('message', function handleMessage (message) {\n if (message.code === 'PINO_CONFIG') {\n pinoConfig = message.config\n configReceived.resolve()\n parentPort.off('message', handleMessage)\n }\n })\n\n Object.defineProperties(stream, {\n levels: {\n get () { return pinoConfig.levels }\n },\n messageKey: {\n get () { return pinoConfig.messageKey }\n },\n errorKey: {\n get () { return pinoConfig.errorKey }\n }\n })\n\n return configReceived.then(finish)\n }\n\n return finish()\n\n function finish () {\n let res = fn(stream)\n\n if (res && typeof res.catch === 'function') {\n res.catch((err) => {\n stream.destroy(err)\n })\n\n // set it to null to not retain a reference to the promise\n res = null\n } else if (opts.enablePipelining && res) {\n return Duplex.from({ writable: stream, readable: res })\n }\n\n return stream\n }\n}\n\nfunction defaultClose (err, cb) {\n process.nextTick(cb, err)\n}\n", "/* eslint-disable no-new-func, camelcase */\n/* globals __non_webpack__require__ */\n\nconst realImport = new Function('modulePath', 'return import(modulePath)')\n\nfunction realRequire(modulePath) {\n if (typeof __non_webpack__require__ === 'function') {\n return __non_webpack__require__(modulePath)\n }\n\n return require(modulePath)\n}\n\nmodule.exports = { realImport, realRequire }\n", "'use strict'\n\nconst { realImport, realRequire } = require('real-require')\n\nmodule.exports = loadTransportStreamBuilder\n\n/**\n * Loads & returns a function to build transport streams\n * @param {string} target\n * @returns {Promise>}\n * @throws {Error} In case the target module does not export a function\n */\nasync function loadTransportStreamBuilder (target) {\n let fn\n try {\n const toLoad = target.startsWith('file://') ? target : 'file://' + target\n\n if (toLoad.endsWith('.ts') || toLoad.endsWith('.cts')) {\n // TODO: add support for the TSM modules loader ( https://github.com/lukeed/tsm ).\n if (process[Symbol.for('ts-node.register.instance')]) {\n realRequire('ts-node/register')\n } else if (process.env && process.env.TS_NODE_DEV) {\n realRequire('ts-node-dev')\n }\n // TODO: Support ES imports once tsc, tap & ts-node provide better compatibility guarantees.\n fn = realRequire(decodeURIComponent(target))\n } else {\n fn = (await realImport(toLoad))\n }\n } catch (error) {\n // See this PR for details: https://github.com/pinojs/thread-stream/pull/34\n if ((error.code === 'ENOTDIR' || error.code === 'ERR_MODULE_NOT_FOUND')) {\n fn = realRequire(target)\n } else if (error.code === undefined || error.code === 'ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING') {\n // When bundled with pkg, an undefined error is thrown when called with realImport\n // When bundled with pkg and using node v20, an ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING error is thrown when called with realImport\n // More info at: https://github.com/pinojs/thread-stream/issues/143\n try {\n fn = realRequire(decodeURIComponent(target))\n } catch {\n throw error\n }\n } else {\n throw error\n }\n }\n\n // Depending on how the default export is performed, and on how the code is\n // transpiled, we may find cases of two nested \"default\" objects.\n // See https://github.com/pinojs/pino/issues/1243#issuecomment-982774762\n if (typeof fn === 'object') fn = fn.default\n if (typeof fn === 'object') fn = fn.default\n if (typeof fn !== 'function') throw Error('exported worker is not a function')\n\n return fn\n}\n", "'use strict'\n\nconst EE = require('node:events')\nconst { pipeline, PassThrough } = require('node:stream')\nconst pino = require('../pino.js')\nconst build = require('pino-abstract-transport')\nconst loadTransportStreamBuilder = require('./transport-stream')\n\n// This file is not checked by the code coverage tool,\n// as it is not reliable.\n\n/* istanbul ignore file */\n\n/*\n * > Multiple targets & pipelines\n *\n *\n * \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u250C\u2500\u2500\u2500\u2500\u2500\u2510\n * \u2502 \u2502 \u2502 p \u2502\n * \u2502 \u2502 \u2502 i \u2502\n * \u2502 target \u2502 \u2502 n \u2502\n * \u2502 \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2524 o \u2502\n * \u2502 targets \u2502 target \u2502 \u2502 . \u2502\n * \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25BA \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2524 m \u2502 source\n * \u2502 \u2502 target \u2502 \u2502 u \u2502 \u2502\n * \u2502 \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2524 l \u2502 \u2502write\n * \u2502 \u2502 \u2502 \u2502 t \u2502 \u25BC\n * \u2502 \u2502 pipeline \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502 \u2502 i \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n * \u2502 \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25BA \u2502 PassThrough \u251C\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2524 s \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502\n * \u2502 \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502 \u2502 t \u2502 write\u2502 Thread \u2502\n * \u2502 \u2502 \u2502 \u2502 r \u2502\u25C4\u2500\u2500\u2500\u2500\u2500\u2524 Stream \u2502\n * \u2502 \u2502 pipeline \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502 \u2502 e \u2502 \u2502 \u2502\n * \u2502 \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25BA \u2502 PassThrough \u251C\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2524 a \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n * \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502 \u2502 m \u2502\n * \u2502 \u2502 \u2502 \u2502\n * \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2514\u2500\u2500\u2500\u2500\u2500\u2518\n *\n *\n *\n * > One single pipeline or target\n *\n *\n * source\n * \u2502\n * \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502write\n * \u2502 \u2502 \u25BC\n * \u2502 \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n * \u2502 targets \u2502 target \u2502 \u2502 \u2502\n * \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25BA \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502 \u2502\n * \u2502 \u2502 \u2502 \u2502 \u2502\n * \u2502 \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502\n * \u2502 \u2502 \u2502 \u2502\n * \u2502 \u2502 \u2502 \u2502\n * \u2502 OR \u2502 \u2502 \u2502\n * \u2502 \u2502 \u2502 \u2502\n * \u2502 \u2502 \u2502 \u2502\n * \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502 \u2502 \u2502\n * \u2502 targets \u2502 pipeline \u2502 \u2502 \u2502 \u2502 Thread \u2502\n * \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25BA \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25BA\u2502 PassThrough \u251C\u2500\u2524 \u2502 Stream \u2502\n * \u2502 \u2502 \u2502 \u2502 \u2502 \u2502 \u2502\n * \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502 \u2502 \u2502\n * \u2502 \u2502 \u2502 \u2502\n * \u2502 OR \u2502 write\u2502 \u2502\n * \u2502 \u2502\u25C4\u2500\u2500\u2500\u2500\u2500\u2524 \u2502\n * \u2502 \u2502 \u2502 \u2502\n * \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 \u2502 \u2502 \u2502\n * \u2502 pipeline \u2502 \u2502 \u2502 \u2502 \u2502\n * \u2502 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u25BA\u2502 PassThrough \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 \u2502 \u2502\n * \u2502 \u2502 \u2502 \u2502 \u2502 \u2502\n * \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518 \u2502 \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n * \u2502 \u2502\n * \u2502 \u2502\n * \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n */\n\nmodule.exports = async function ({ targets, pipelines, levels, dedupe }) {\n const targetStreams = []\n\n // Process targets\n if (targets && targets.length) {\n targets = await Promise.all(targets.map(async (t) => {\n const fn = await loadTransportStreamBuilder(t.target)\n const stream = await fn(t.options)\n return {\n level: t.level,\n stream\n }\n }))\n\n targetStreams.push(...targets)\n }\n\n // Process pipelines\n if (pipelines && pipelines.length) {\n pipelines = await Promise.all(\n pipelines.map(async (p) => {\n let level\n const pipeDests = await Promise.all(\n p.map(async (t) => {\n // level assigned to pipeline is duplicated over all its targets, just store it\n level = t.level\n const fn = await loadTransportStreamBuilder(t.target)\n const stream = await fn(t.options)\n return stream\n }\n ))\n\n return {\n level,\n stream: createPipeline(pipeDests)\n }\n })\n )\n targetStreams.push(...pipelines)\n }\n\n // Skip building the multistream step if either one single pipeline or target is defined and\n // return directly the stream instance back to TreadStream.\n // This is equivalent to define either:\n //\n // pino.transport({ target: ... })\n //\n // OR\n //\n // pino.transport({ pipeline: ... })\n if (targetStreams.length === 1) {\n return targetStreams[0].stream\n } else {\n return build(process, {\n parse: 'lines',\n metadata: true,\n close (err, cb) {\n let expected = 0\n for (const transport of targetStreams) {\n expected++\n transport.stream.on('close', closeCb)\n transport.stream.end()\n }\n\n function closeCb () {\n if (--expected === 0) {\n cb(err)\n }\n }\n }\n })\n }\n\n // TODO: Why split2 was not used for pipelines?\n function process (stream) {\n const multi = pino.multistream(targetStreams, { levels, dedupe })\n // TODO manage backpressure\n stream.on('data', function (chunk) {\n const { lastTime, lastMsg, lastObj, lastLevel } = this\n multi.lastLevel = lastLevel\n multi.lastTime = lastTime\n multi.lastMsg = lastMsg\n multi.lastObj = lastObj\n\n // TODO handle backpressure\n multi.write(chunk + '\\n')\n })\n }\n\n /**\n * Creates a pipeline using the provided streams and return an instance of `PassThrough` stream\n * as a source for the pipeline.\n *\n * @param {(TransformStream|WritableStream)[]} streams An array of streams.\n * All intermediate streams in the array *MUST* be `Transform` streams and only the last one `Writable`.\n * @returns A `PassThrough` stream instance representing the source stream of the pipeline\n */\n function createPipeline (streams) {\n const ee = new EE()\n const stream = new PassThrough({\n autoDestroy: true,\n destroy (_, cb) {\n ee.on('error', cb)\n ee.on('closed', cb)\n }\n })\n\n pipeline(stream, ...streams, function (err) {\n if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n ee.emit('error', err)\n return\n }\n\n ee.emit('closed')\n })\n\n return stream\n }\n}\n"], + "mappings": "uTAAA,IAAAA,GAAAC,EAAA,CAAAC,GAAAC,KAAA,cAOA,IAAMC,EAAeC,GACZA,GAAO,OAAOA,EAAI,SAAY,SAOjCC,GAAiBD,GAAQ,CAC7B,GAAI,CAACA,EAAK,OAI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AAGiB,EAAS,SAAUX,EAAK,CAC1C,GAAIA,GAAOA,EAAI,OAAS,6BAA8B,CACpDY,EAAG,KAAK,QAASZ,CAAG,EACpB,MACF,CAEAY,EAAG,KAAK,QAAQ,CAClB,CAAC,EAEMlB,CACT,CACF", + "names": ["require_err_helpers", "__commonJSMin", "exports", "module", "isErrorLike", "err", "getErrorCause", "cause", "causeResult", "_stackWithCauses", "seen", "stack", "stackWithCauses", "_messageWithCauses", "skip", "message", "skipIfVErrorStyleCause", "messageWithCauses", "require_err_proto", "__commonJSMin", "exports", "module", "seen", "rawSymbol", "pinoErrProto", "val", "require_err", "__commonJSMin", "exports", "module", "errSerializer", "messageWithCauses", "stackWithCauses", "isErrorLike", "pinoErrProto", "pinoErrorSymbols", "seen", "toString", "err", "_err", "key", "val", "require_err_with_cause", "__commonJSMin", "exports", "module", "errWithCauseSerializer", "isErrorLike", "pinoErrProto", "pinoErrorSymbols", "seen", "toString", "err", "_err", "key", "val", "require_req", "__commonJSMin", "exports", "module", "mapHttpRequest", "reqSerializer", "rawSymbol", "pinoReqProto", "val", "req", "connection", "_req", "path", "require_res", "__commonJSMin", "exports", "module", "mapHttpResponse", "resSerializer", "rawSymbol", "pinoResProto", "val", "res", "_res", "require_pino_std_serializers", "__commonJSMin", "exports", "module", "errSerializer", "errWithCauseSerializer", "reqSerializers", "resSerializers", "customSerializer", "err", "req", "res", "require_caller", "__commonJSMin", "exports", "module", "noOpPrepareStackTrace", "_", "stack", "originalPrepare", "entries", "fileNames", "entry", "require_validator", "__commonJSMin", "exports", "module", "validator", "opts", "ERR_PATHS_MUST_BE_STRINGS", "ERR_INVALID_PATH", "s", "paths", "expr", "require_rx", "__commonJSMin", "exports", "module", "require_parse", "__commonJSMin", "exports", "module", "rx", "parse", "paths", "wildcards", "wcLen", "secret", "o", "strPath", "ix", "path", "p", "leadingBracket", "star", "before", "beforeStr", "after", "nested", "require_redactor", "__commonJSMin", "exports", "module", "rx", "redactor", "secret", "serialize", "wcLen", "strict", "isCensorFct", "censorFctTakesPath", "state", "redact", "strictImpl", "redactTmpl", "dynamicRedactTmpl", "resultTmpl", "o", "path", "escPath", "leadingBracket", "arrPath", "skip", "delim", "hops", "match", "ix", "index", "input", "existence", "p", "circularDetection", "censorArgs", "hasWildcards", "require_modifiers", "__commonJSMin", "exports", "module", "groupRedact", "groupRestore", "nestedRedact", "nestedRestore", "keys", "values", "target", "length", "k", "o", "path", "censor", "isCensorFct", "censorFctTakesPath", "get", "keysLength", "pathLength", "pathWithKey", "i", "key", "instructions", "value", "current", "store", "ns", "specialSet", "has", "obj", "prop", "afterPath", "afterPathLen", "lastPathIndex", "originalKey", "n", "nv", "ov", "oov", "wc", "kIsWc", "wcov", "consecutive", "level", "depth", "redactPathCurrent", "tree", "wcKeys", "j", "wck", "node", "iterateNthLevel", "rv", "restoreInstr", "p", "l", "parent", "child", "require_restorer", "__commonJSMin", "exports", "module", "groupRestore", "nestedRestore", "restorer", "secret", "wcLen", "paths", "resetters", "resetTmpl", "hasWildcards", "state", "restoreTmpl", "path", "circle", "escPath", "leadingBracket", "reset", "clear", "require_state", "__commonJSMin", "exports", "module", "state", "o", "secret", "censor", "compileRestore", "serialize", "groupRedact", "nestedRedact", "wildcards", "wcLen", "builder", "require_fast_redact", "__commonJSMin", "exports", "module", "validator", "parse", "redactor", "restorer", "groupRedact", "nestedRedact", "state", "rx", "validate", "noop", "o", "DEFAULT_CENSOR", "fastRedact", "opts", "paths", "serialize", "remove", "censor", "isCensorFct", "censorFctTakesPath", "wildcards", "wcLen", "secret", "compileRestore", "strict", "require_symbols", "__commonJSMin", "exports", "module", "setLevelSym", "getLevelSym", "levelValSym", "levelCompSym", "useLevelLabelsSym", "useOnlyCustomLevelsSym", "mixinSym", "lsCacheSym", "chindingsSym", "asJsonSym", "writeSym", "redactFmtSym", "timeSym", "timeSliceIndexSym", "streamSym", "stringifySym", "stringifySafeSym", "stringifiersSym", "endSym", "formatOptsSym", "messageKeySym", "errorKeySym", "nestedKeySym", "nestedKeyStrSym", "mixinMergeStrategySym", "msgPrefixSym", "wildcardFirstSym", "serializersSym", "formattersSym", "hooksSym", "needsMetadataGsym", "require_redaction", "__commonJSMin", "exports", "module", "fastRedact", "redactFmtSym", "wildcardFirstSym", "rx", "validator", "validate", "s", "CENSOR", "strict", "redaction", "opts", "serialize", "paths", "censor", "handle", "shape", "o", "str", "first", "next", "ns", "index", "nextPath", "k", "result", "topCensor", "args", "value", "wrappedCensor", "path", "remove", "require_time", "__commonJSMin", "exports", "module", "nullTime", "epochTime", "unixTime", "isoTime", "require_quick_format_unescaped", "__commonJSMin", "exports", "module", "tryStringify", "o", "format", "f", "args", "opts", "ss", "offset", "len", "objects", "index", "argLen", "str", "a", "lastPos", "flen", "i", "type", "require_atomic_sleep", "__commonJSMin", "exports", "module", "sleep", "ms", "nil", "target", "require_sonic_boom", "__commonJSMin", "exports", "module", "fs", "EventEmitter", "inherits", "path", "sleep", "assert", "BUSY_WRITE_TIMEOUT", "kEmptyBuffer", "MAX_WRITE", "kContentModeBuffer", "kContentModeUtf8", "major", "minor", "kCopyBuffer", "openFile", "file", "sonic", "fileOpened", "err", "fd", "reopening", "flags", "mode", "SonicBoom", "opts", "dest", "minLength", "maxLength", "maxWrite", "periodicFlush", "sync", "append", "mkdir", "retryEAGAIN", "fsync", "contentMode", "fsWriteSync", "fsWrite", "writeBuffer", "flushBuffer", "flushBufferSync", "actualWriteBuffer", "write", "flush", "flushSync", "actualWrite", "n", "releasedBufObj", "releaseWritingBuf", "len", "actualClose", "emitDrain", "name", "writingBuf", "mergeBuf", "bufs", "data", "lens", "callFlushCallbackOnDrain", "cb", "onDrain", "onError", "error", "buf", "release", "written", "closeWrapped", "done", "require_on_exit_leak_free", "__commonJSMin", "exports", "module", "refs", "functions", "onExit", "onBeforeExit", "registry", "ensureRegistry", "clear", "install", "event", "uninstall", "callRefs", "ref", "obj", "fn", "index", "_register", "register", "registerBeforeExit", "unregister", "_obj", "require_package", "__commonJSMin", "exports", "module", "require_wait", "__commonJSMin", "exports", "module", "wait", "state", "index", "expected", "timeout", "done", "max", "current", "prior", "check", "backoff", "waitDiff", "require_indexes", "__commonJSMin", "exports", "module", "require_thread_stream", "__commonJSMin", "exports", "module", "version", "EventEmitter", "Worker", "join", "pathToFileURL", "wait", "WRITE_INDEX", "READ_INDEX", "buffer", "assert", "kImpl", "MAX_STRING", "FakeWeakRef", "value", "FakeFinalizationRegistry", "FinalizationRegistry", "WeakRef", "registry", "worker", "createWorker", "stream", "opts", "filename", "workerData", "toExecute", "onWorkerMessage", "onWorkerExit", "drain", "nextFlush", "writeIndex", "leftover", "end", "toWrite", "toWriteBytes", "write", "destroy", "msg", "code", "ThreadStream", "message", "transferList", "data", "error", "writeSync", "err", "cb", "res", "flushSync", "current", "length", "readIndex", "spins", "require_transport", "__commonJSMin", "exports", "module", "createRequire", "getCallers", "join", "isAbsolute", "sep", "sleep", "onExit", "ThreadStream", "setupOnExit", "stream", "autoEnd", "flush", "buildStream", "filename", "workerData", "workerOpts", "sync", "onReady", "transport", "fullOptions", "pipeline", "targets", "levels", "dedupe", "worker", "caller", "options", "callers", "bundlerOverrides", "target", "dest", "fixTarget", "t", "origin", "filePath", "context", "require_tools", "__commonJSMin", "exports", "module", "format", "mapHttpRequest", "mapHttpResponse", "SonicBoom", "onExit", "lsCacheSym", "chindingsSym", "writeSym", "serializersSym", "formatOptsSym", "endSym", "stringifiersSym", "stringifySym", "stringifySafeSym", "wildcardFirstSym", "nestedKeySym", "formattersSym", "messageKeySym", "errorKeySym", "nestedKeyStrSym", "msgPrefixSym", "isMainThread", "transport", "noop", "genLog", "level", "hook", "LOG", "args", "o", "n", "msg", "formatParams", "asString", "str", "result", "last", "found", "point", "l", "i", "asJson", "obj", "num", "time", "stringify", "stringifySafe", "stringifiers", "end", "chindings", "serializers", "formatters", "messageKey", "errorKey", "data", "value", "wildcardStringifier", "propStr", "key", "stringifier", "strKey", "msgStr", "asChindings", "instance", "bindings", "formatter", "hasBeenTampered", "stream", "buildSafeSonicBoom", "opts", "filterBrokenPipe", "autoEnd", "err", "eventName", "createArgsNormalizer", "defaultOptions", "caller", "customLevels", "enabled", "onChild", "stringifySafeFn", "buildFormatters", "log", "normalizeDestFileDescriptor", "destination", "fd", "require_constants", "__commonJSMin", "exports", "module", "DEFAULT_LEVELS", "SORTING_ORDER", "require_levels", "__commonJSMin", "exports", "module", "lsCacheSym", "levelValSym", "useOnlyCustomLevelsSym", "streamSym", "formattersSym", "hooksSym", "levelCompSym", "noop", "genLog", "DEFAULT_LEVELS", "SORTING_ORDER", "levelMethods", "hook", "logFatal", "args", "stream", "nums", "o", "k", "initialLsCache", "genLsCache", "instance", "formatter", "labels", "cache", "label", "level", "isStandardLevel", "useOnlyCustomLevels", "setLevel", "values", "preLevelVal", "levelVal", "useOnlyCustomLevelsVal", "levelComparison", "key", "getLevel", "levels", "isLevelEnabled", "logLevel", "logLevelVal", "compareLevel", "direction", "current", "expected", "genLevelComparison", "mappings", "customLevels", "customNums", "assertDefaultLevelFound", "defaultLevel", "assertNoLevelCollisions", "assertLevelComparison", "require_meta", "__commonJSMin", "exports", "module", "require_proto", "__commonJSMin", "exports", "module", "EventEmitter", "lsCacheSym", "levelValSym", "setLevelSym", "getLevelSym", "chindingsSym", "parsedChindingsSym", "mixinSym", "asJsonSym", "writeSym", "mixinMergeStrategySym", "timeSym", "timeSliceIndexSym", "streamSym", "serializersSym", "formattersSym", "errorKeySym", "messageKeySym", "useOnlyCustomLevelsSym", "needsMetadataGsym", "redactFmtSym", "stringifySym", "formatOptsSym", "stringifiersSym", "msgPrefixSym", "hooksSym", "getLevel", "setLevel", "isLevelEnabled", "mappings", "initialLsCache", "genLsCache", "assertNoLevelCollisions", "asChindings", "asJson", "buildFormatters", "stringify", "version", "redaction", "constructor", "prototype", "child", "bindings", "setBindings", "flush", "lvl", "n", "write", "resetChildingsFormatter", "options", "serializers", "formatters", "instance", "k", "parentSymbols", "i", "ks", "bk", "bindingsSymbols", "bi", "bks", "level", "chindings", "log", "stringifiers", "formatOpts", "childLevel", "chindingsJson", "bindingsFromJson", "newBindings", "defaultMixinMergeStrategy", "mergeObject", "mixinObject", "_obj", "msg", "num", "t", "mixin", "errorKey", "messageKey", "mixinMergeStrategy", "obj", "streamWriteHook", "s", "stream", "noop", "cb", "require_safe_stable_stringify", "__commonJSMin", "exports", "module", "hasOwnProperty", "stringify", "configure", "strEscapeSequencesRegExp", "strEscape", "str", "sort", "array", "comparator", "i", "currentValue", "position", "typedArrayPrototypeGetSymbolToStringTag", "isTypedArrayWithEntries", "value", "stringifyTypedArray", "separator", "maximumBreadth", "whitespace", "res", "getCircularValueOption", "options", "circularValue", "getDeterministicOption", "getBooleanOption", "key", "getPositiveIntegerOption", "getItemCount", "number", "getUniqueReplacerSet", "replacerArray", "replacerSet", "getStrictOption", "message", "fail", "bigint", "deterministic", "maximumDepth", "stringifyFnReplacer", "parent", "stack", "replacer", "spacer", "indentation", "join", "originalIndentation", "maximumValuesToStringify", "tmp", "removedKeys", "keys", "keyLength", "maximumPropertiesToStringify", "stringifyArrayReplacer", "stringifyIndent", "stringifySimple", "hasLength", "space", "require_multistream", "__commonJSMin", "exports", "module", "metadata", "DEFAULT_LEVELS", "DEFAULT_INFO_LEVEL", "multistream", "streamsArray", "opts", "counter", "streamLevels", "i", "res", "write", "add", "emit", "flushSync", "end", "clone", "data", "dest", "level", "streams", "recordedLevel", "stream", "initLoopVar", "checkLoopVar", "adjustLoopVar", "lastTime", "lastMsg", "lastObj", "lastLogger", "args", "isStream", "stream_", "dest_", "compareByLevel", "a", "b", "length", "dedupe", "require_pino", "__commonJSMin", "exports", "module", "pinoBundlerAbsolutePath", "p", "os", "stdSerializers", "caller", "redaction", "time", "proto", "symbols", "configure", "assertDefaultLevelFound", "mappings", "genLsCache", "genLevelComparison", "assertLevelComparison", "DEFAULT_LEVELS", "SORTING_ORDER", "createArgsNormalizer", "asChindings", "buildSafeSonicBoom", "buildFormatters", "stringify", "normalizeDestFileDescriptor", "noop", "version", "chindingsSym", "redactFmtSym", "serializersSym", "timeSym", "timeSliceIndexSym", "streamSym", "stringifySym", "stringifySafeSym", "stringifiersSym", "setLevelSym", "endSym", "formatOptsSym", "messageKeySym", "errorKeySym", "nestedKeySym", "mixinSym", "levelCompSym", "useOnlyCustomLevelsSym", "formattersSym", "hooksSym", "nestedKeyStrSym", "mixinMergeStrategySym", "msgPrefixSym", "epochTime", "nullTime", "pid", "hostname", "defaultErrorSerializer", "defaultOptions", "bindings", "label", "number", "normalize", "serializers", "pino", "args", "instance", "opts", "stream", "redact", "crlf", "timestamp", "messageKey", "errorKey", "nestedKey", "base", "name", "level", "customLevels", "levelComparison", "mixin", "mixinMergeStrategy", "useOnlyCustomLevels", "formatters", "hooks", "depthLimit", "edgeLimit", "onChild", "msgPrefix", "stringifySafe", "allFormatters", "stringifyFn", "stringifiers", "formatOpts", "end", "coreChindings", "chindings", "timeSliceIndex", "levels", "levelCompFunc", "dest", "require_split2", "__commonJSMin", "exports", "module", "Transform", "StringDecoder", "kLast", "kDecoder", "transform", "chunk", "enc", "cb", "list", "push", "error", "flush", "self", "val", "noop", "incoming", "split", "matcher", "mapper", "options", "stream", "err", "require_pino_abstract_transport", "__commonJSMin", "exports", "module", "metadata", "split", "Duplex", "parentPort", "workerData", "createDeferred", "resolve", "reject", "promise", "_resolve", "_reject", "fn", "opts", "waitForConfig", "parseLines", "parseLine", "close", "defaultClose", "stream", "line", "value", "error", "err", "cb", "pinoConfig", "configReceived", "handleMessage", "message", "finish", "res", "require_src", "__commonJSMin", "exports", "module", "realImport", "realRequire", "modulePath", "__require", "require_transport_stream", "__commonJSMin", "exports", "module", "realImport", "realRequire", "loadTransportStreamBuilder", "target", "fn", "toLoad", "error", "require_worker", "__commonJSMin", "exports", "module", "EE", "pipeline", "PassThrough", "pino", "build", "loadTransportStreamBuilder", "targets", "pipelines", "levels", "dedupe", "targetStreams", "t", "stream", "p", "level", "pipeDests", "createPipeline", "process", "err", "cb", "expected", "transport", "closeCb", "multi", "chunk", "lastTime", "lastMsg", "lastObj", "lastLevel", "streams", "ee", "_"] +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/server.mjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/server.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0a8e3baa8b9ea9754bdd19aa8ebb235fc5d0073c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/server.mjs @@ -0,0 +1,274 @@ +var My=Object.create;var Pa=Object.defineProperty;var $y=Object.getOwnPropertyDescriptor;var Hy=Object.getOwnPropertyNames;var Gy=Object.getPrototypeOf,Wy=Object.prototype.hasOwnProperty;var X=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var Me=(r,e)=>()=>(r&&(e=r(r=0)),e);var z=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Af=(r,e)=>{for(var t in e)Pa(r,t,{get:e[t],enumerable:!0})},zy=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Hy(e))!Wy.call(r,o)&&o!==t&&Pa(r,o,{get:()=>e[o],enumerable:!(n=$y(e,o))||n.enumerable});return r};var zr=(r,e,t)=>(t=r!=null?My(Gy(r)):{},zy(e||!r||!r.__esModule?Pa(t,"default",{value:r,enumerable:!0}):t,r));var Df=z((sA,lo)=>{lo.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;lo.exports.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\u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9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;lo.exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8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\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uF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D34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\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DE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/});var Ba=z((oA,Sf)=>{var xa=Df();Sf.exports={isSpaceSeparator(r){return typeof r=="string"&&xa.Space_Separator.test(r)},isIdStartChar(r){return typeof r=="string"&&(r>="a"&&r<="z"||r>="A"&&r<="Z"||r==="$"||r==="_"||xa.ID_Start.test(r))},isIdContinueChar(r){return typeof r=="string"&&(r>="a"&&r<="z"||r>="A"&&r<="Z"||r>="0"&&r<="9"||r==="$"||r==="_"||r==="\u200C"||r==="\u200D"||xa.ID_Continue.test(r))},isDigit(r){return typeof r=="string"&&/[0-9]/.test(r)},isHexDigit(r){return typeof r=="string"&&/[0-9A-Fa-f]/.test(r)}}});var Ff=z((iA,kf)=>{var $e=Ba(),Na,Ze,cr,ho,vr,Pt,He,La,os;kf.exports=function(e,t){Na=String(e),Ze="start",cr=[],ho=0,vr=1,Pt=0,He=void 0,La=void 0,os=void 0;do He=Jy(),Yy[Ze]();while(He.type!=="eof");return typeof t=="function"?qa({"":os},"",t):os};function qa(r,e,t){let n=r[e];if(n!=null&&typeof n=="object")if(Array.isArray(n))for(let o=0;o0;){let t=lr();if(!$e.isHexDigit(t))throw Pe($());r+=$()}return String.fromCodePoint(parseInt(r,16))}var Yy={start(){if(He.type==="eof")throw Vr();Ia()},beforePropertyName(){switch(He.type){case"identifier":case"string":La=He.value,Ze="afterPropertyName";return;case"punctuator":fo();return;case"eof":throw Vr()}},afterPropertyName(){if(He.type==="eof")throw Vr();Ze="beforePropertyValue"},beforePropertyValue(){if(He.type==="eof")throw Vr();Ia()},beforeArrayValue(){if(He.type==="eof")throw Vr();if(He.type==="punctuator"&&He.value==="]"){fo();return}Ia()},afterPropertyValue(){if(He.type==="eof")throw Vr();switch(He.value){case",":Ze="beforePropertyName";return;case"}":fo()}},afterArrayValue(){if(He.type==="eof")throw Vr();switch(He.value){case",":Ze="beforeArrayValue";return;case"]":fo()}},end(){}};function Ia(){let r;switch(He.type){case"punctuator":switch(He.value){case"{":r={};break;case"[":r=[];break}break;case"null":case"boolean":case"numeric":case"string":r=He.value;break}if(os===void 0)os=r;else{let e=cr[cr.length-1];Array.isArray(e)?e.push(r):Object.defineProperty(e,La,{value:r,writable:!0,enumerable:!0,configurable:!0})}if(r!==null&&typeof r=="object")cr.push(r),Array.isArray(r)?Ze="beforeArrayValue":Ze="beforePropertyName";else{let e=cr[cr.length-1];e==null?Ze="end":Array.isArray(e)?Ze="afterArrayValue":Ze="afterPropertyValue"}}function fo(){cr.pop();let r=cr[cr.length-1];r==null?Ze="end":Array.isArray(r)?Ze="afterArrayValue":Ze="afterPropertyValue"}function Pe(r){return po(r===void 0?`JSON5: invalid end of input at ${vr}:${Pt}`:`JSON5: invalid character '${Rf(r)}' at ${vr}:${Pt}`)}function Vr(){return po(`JSON5: invalid end of input at ${vr}:${Pt}`)}function vf(){return Pt-=5,po(`JSON5: invalid identifier character at ${vr}:${Pt}`)}function Xy(r){console.warn(`JSON5: '${Rf(r)}' in strings is not valid ECMAScript; consider escaping`)}function Rf(r){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[r])return e[r];if(r<" "){let t=r.charCodeAt(0).toString(16);return"\\x"+("00"+t).substring(t.length)}return r}function po(r){let e=new SyntaxError(r);return e.lineNumber=vr,e.columnNumber=Pt,e}});var Pf=z((aA,Of)=>{var Ua=Ba();Of.exports=function(e,t,n){let o=[],a="",u,l,f="",h;if(t!=null&&typeof t=="object"&&!Array.isArray(t)&&(n=t.space,h=t.quote,t=t.replacer),typeof t=="function")l=t;else if(Array.isArray(t)){u=[];for(let w of t){let g;typeof w=="string"?g=w:(typeof w=="number"||w instanceof String||w instanceof Number)&&(g=String(w)),g!==void 0&&u.indexOf(g)<0&&u.push(g)}}return n instanceof Number?n=Number(n):n instanceof String&&(n=String(n)),typeof n=="number"?n>0&&(n=Math.min(10,Math.floor(n)),f=" ".substr(0,n)):typeof n=="string"&&(f=n.substr(0,10)),d("",{"":e});function d(w,g){let C=g[w];switch(C!=null&&(typeof C.toJSON5=="function"?C=C.toJSON5(w):typeof C.toJSON=="function"&&(C=C.toJSON(w))),l&&(C=l.call(g,w,C)),C instanceof Number?C=Number(C):C instanceof String?C=String(C):C instanceof Boolean&&(C=C.valueOf()),C){case null:return"null";case!0:return"true";case!1:return"false"}if(typeof C=="string")return _(C,!1);if(typeof C=="number")return String(C);if(typeof C=="object")return Array.isArray(C)?v(C):E(C)}function _(w){let g={"'":.1,'"':.2},C={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},R="";for(let N=0;Ng[N]=0)throw TypeError("Converting circular structure to JSON5");o.push(w);let g=a;a=a+f;let C=u||Object.keys(w),R=[];for(let N of C){let j=d(N,w);if(j!==void 0){let L=P(N)+":";f!==""&&(L+=" "),L+=j,R.push(L)}}let S;if(R.length===0)S="{}";else{let N;if(f==="")N=R.join(","),S="{"+N+"}";else{let j=`, +`+a;N=R.join(j),S=`{ +`+a+N+`, +`+g+"}"}}return o.pop(),a=g,S}function P(w){if(w.length===0)return _(w,!0);let g=String.fromCodePoint(w.codePointAt(0));if(!Ua.isIdStartChar(g))return _(w,!0);for(let C=g.length;C=0)throw TypeError("Converting circular structure to JSON5");o.push(w);let g=a;a=a+f;let C=[];for(let S=0;S{var Qy=Ff(),Zy=Pf(),e0={parse:Qy,stringify:Zy};xf.exports=e0});var Ga=z(($A,Yf)=>{"use strict";var So=Object.prototype.hasOwnProperty,Kf=Object.prototype.toString,Hf=Object.defineProperty,Gf=Object.getOwnPropertyDescriptor,Wf=function(e){return typeof Array.isArray=="function"?Array.isArray(e):Kf.call(e)==="[object Array]"},zf=function(e){if(!e||Kf.call(e)!=="[object Object]")return!1;var t=So.call(e,"constructor"),n=e.constructor&&e.constructor.prototype&&So.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!t&&!n)return!1;var o;for(o in e);return typeof o>"u"||So.call(e,o)},Jf=function(e,t){Hf&&t.name==="__proto__"?Hf(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},Vf=function(e,t){if(t==="__proto__")if(So.call(e,t)){if(Gf)return Gf(e,t).value}else return;return e[t]};Yf.exports=function r(){var e,t,n,o,a,u,l=arguments[0],f=1,h=arguments.length,d=!1;for(typeof l=="boolean"&&(d=l,l=arguments[1]||{},f=2),(l==null||typeof l!="object"&&typeof l!="function")&&(l={});f{y0.exports={name:"gaxios",version:"7.1.1",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:"googleapis/gaxios",keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","@types/tmp":"0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.0.0",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^4.0.0","jsdoc-region-tag":"^3.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.0-beta.13","null-loader":"^4.0.0","pack-n-play":"^3.0.0",puppeteer:"^24.0.0",sinon:"^20.0.0","stream-browserify":"^3.0.0",tmp:"0.2.3","ts-loader":"^9.5.2",typescript:"^5.8.3",webpack:"^5.35.0","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"}}});var Zf=z((GA,Qf)=>{"use strict";var _0=Xf();Qf.exports={pkg:_0}});var Ja=z(Et=>{"use strict";var td=Et&&Et.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Et,"__esModule",{value:!0});Et.GaxiosError=Et.GAXIOS_ERROR_SYMBOL=void 0;Et.defaultErrorRedactor=rd;var ed=td(Ga()),C0=td(Zf()),Wa=C0.default.pkg;Et.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Wa.name}-gaxios-error`);var za=class r extends Error{config;response;code;status;error;[Et.GAXIOS_ERROR_SYMBOL]=Wa.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&Et.GAXIOS_ERROR_SYMBOL in e&&e[Et.GAXIOS_ERROR_SYMBOL]===Wa.version?!0:Function.prototype[Symbol.hasInstance].call(r,e)}constructor(e,t,n,o){if(super(e,{cause:o}),this.config=t,this.response=n,this.error=o instanceof Error?o:void 0,this.config=(0,ed.default)(!0,{},t),this.response&&(this.response.config=(0,ed.default)(!0,{},this.response.config)),this.response){try{this.response.data=b0(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.code)}static extractAPIErrorFromResponse(e,t="The request failed"){let n=t;if(typeof e.data=="string"&&(n=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){n="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:n;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,a="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let u=[];for(let l of e.data.error.errors)typeof l=="object"&&"message"in l&&typeof l.message=="string"&&u.push(l.message);return Object.assign({message:u.join(` +`)||n,code:a,status:o},e.data.error)}return Object.assign({message:n,code:a,status:o},e.data.error)}}return{message:n,code:e.status,status:e.statusText}}};Et.GaxiosError=za;function b0(r,e){switch(r){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function rd(r){let e="< - See `errorRedactor` option in `gaxios` for configuration>.";function t(a){a&&a.forEach((u,l)=>{(/^authentication$/i.test(l)||/^authorization$/i.test(l)||/secret/i.test(l))&&a.set(l,e)})}function n(a,u){if(typeof a=="object"&&a!==null&&typeof a[u]=="string"){let l=a[u];(/grant_type=/i.test(l)||/assertion=/i.test(l)||/secret/i.test(l))&&(a[u]=e)}}function o(a){!a||typeof a!="object"||(a instanceof FormData||a instanceof URLSearchParams||"forEach"in a&&"set"in a?a.forEach((u,l)=>{(["grant_type","assertion"].includes(l)||/secret/.test(l))&&a.set(l,e)}):("grant_type"in a&&(a.grant_type=e),"assertion"in a&&(a.assertion=e),"client_secret"in a&&(a.client_secret=e)))}return r.config&&(t(r.config.headers),n(r.config,"data"),o(r.config.data),n(r.config,"body"),o(r.config.body),r.config.url.searchParams.has("token")&&r.config.url.searchParams.set("token",e),r.config.url.searchParams.has("client_secret")&&r.config.url.searchParams.set("client_secret",e)),r.response&&(rd({config:r.response.config}),t(r.response.headers),r.response.bodyUsed&&(n(r.response,"data"),o(r.response.data))),r}});var sd=z(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.getRetryConfig=E0;async function E0(r){let e=nd(r);if(!r||!r.config||!e&&!r.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let t=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||t,r.config.retryConfig=e,!await(e.shouldRetry||w0)(r))return{shouldRetry:!1,config:r.config};let o=A0(e);r.config.retryConfig.currentRetryAttempt+=1;let a=e.retryBackoff?e.retryBackoff(r,o):new Promise(u=>{setTimeout(u,o)});return e.onRetryAttempt&&await e.onRetryAttempt(r),await a,{shouldRetry:!0,config:r.config}}function w0(r){let e=nd(r);if(r.config.signal?.aborted&&r.code!=="TimeoutError"||r.code==="AbortError"||!e||e.retry===0||!r.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(r.config.method?.toUpperCase()||"GET"))return!1;if(r.response&&r.response.status){let t=!1;for(let[n,o]of e.statusCodesToRetry){let a=r.response.status;if(a>=n&&a<=o){t=!0;break}}if(!t)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function nd(r){if(r&&r.config&&r.config.retryConfig)return r.config.retryConfig}function A0(r){let t=(r.currentRetryAttempt?0:r.retryDelay??100)+(Math.pow(r.retryDelayMultiplier,r.currentRetryAttempt)-1)/2*1e3,n=r.totalTimeout-(Date.now()-r.timeOfFirstRequest);return Math.min(t,n,r.maxRetryDelay)}});var Ya=z(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});vo.GaxiosInterceptorManager=void 0;var Ka=class extends Set{};vo.GaxiosInterceptorManager=Ka});var id=z((VA,od)=>{var bn=1e3,En=bn*60,wn=En*60,Kr=wn*24,D0=Kr*7,S0=Kr*365.25;od.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return v0(r);if(t==="number"&&isFinite(r))return e.long?R0(r):T0(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function v0(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*S0;case"weeks":case"week":case"w":return t*D0;case"days":case"day":case"d":return t*Kr;case"hours":case"hour":case"hrs":case"hr":case"h":return t*wn;case"minutes":case"minute":case"mins":case"min":case"m":return t*En;case"seconds":case"second":case"secs":case"sec":case"s":return t*bn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function T0(r){var e=Math.abs(r);return e>=Kr?Math.round(r/Kr)+"d":e>=wn?Math.round(r/wn)+"h":e>=En?Math.round(r/En)+"m":e>=bn?Math.round(r/bn)+"s":r+"ms"}function R0(r){var e=Math.abs(r);return e>=Kr?To(r,e,Kr,"day"):e>=wn?To(r,e,wn,"hour"):e>=En?To(r,e,En,"minute"):e>=bn?To(r,e,bn,"second"):r+" ms"}function To(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var Xa=z((KA,ad)=>{function k0(r){t.debug=t,t.default=t,t.coerce=f,t.disable=u,t.enable=o,t.enabled=l,t.humanize=id(),t.destroy=h,Object.keys(r).forEach(d=>{t[d]=r[d]}),t.names=[],t.skips=[],t.formatters={};function e(d){let _=0;for(let E=0;E{if(L==="%%")return"%";N++;let K=t.formatters[H];if(typeof K=="function"){let W=g[N];L=K.call(C,W),g.splice(N,1),N--}return L}),t.formatArgs.call(C,g),(C.log||t.log).apply(C,g)}return w.namespace=d,w.useColors=t.useColors(),w.color=t.selectColor(d),w.extend=n,w.destroy=t.destroy,Object.defineProperty(w,"enabled",{enumerable:!0,configurable:!1,get:()=>E!==null?E:(P!==t.namespaces&&(P=t.namespaces,v=t.enabled(d)),v),set:g=>{E=g}}),typeof t.init=="function"&&t.init(w),w}function n(d,_){let E=t(this.namespace+(typeof _>"u"?":":_)+d);return E.log=this.log,E}function o(d){t.save(d),t.namespaces=d,t.names=[],t.skips=[];let _=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let E of _)E[0]==="-"?t.skips.push(E.slice(1)):t.names.push(E)}function a(d,_){let E=0,P=0,v=-1,w=0;for(;E"-"+_)].join(",");return t.enable(""),d}function l(d){for(let _ of t.skips)if(a(d,_))return!1;for(let _ of t.names)if(a(d,_))return!0;return!1}function f(d){return d instanceof Error?d.stack||d.message:d}function h(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}ad.exports=k0});var ud=z((st,Ro)=>{st.formatArgs=O0;st.save=P0;st.load=x0;st.useColors=F0;st.storage=B0();st.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();st.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function F0(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function O0(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ro.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}st.log=console.debug||console.log||(()=>{});function P0(r){try{r?st.storage.setItem("debug",r):st.storage.removeItem("debug")}catch{}}function x0(){let r;try{r=st.storage.getItem("debug")||st.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function B0(){try{return localStorage}catch{}}Ro.exports=Xa()(st);var{formatters:I0}=Ro.exports;I0.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var ld=z((YA,cd)=>{"use strict";cd.exports=(r,e)=>{e=e||process.argv;let t=r.startsWith("-")?"":r.length===1?"-":"--",n=e.indexOf(t+r),o=e.indexOf("--");return n!==-1&&(o===-1?!0:n{"use strict";var N0=X("os"),xt=ld(),Ye=process.env,An;xt("no-color")||xt("no-colors")||xt("color=false")?An=!1:(xt("color")||xt("colors")||xt("color=true")||xt("color=always"))&&(An=!0);"FORCE_COLOR"in Ye&&(An=Ye.FORCE_COLOR.length===0||parseInt(Ye.FORCE_COLOR,10)!==0);function q0(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function j0(r){if(An===!1)return 0;if(xt("color=16m")||xt("color=full")||xt("color=truecolor"))return 3;if(xt("color=256"))return 2;if(r&&!r.isTTY&&An!==!0)return 0;let e=An?1:0;if(process.platform==="win32"){let t=N0.release().split(".");return Number(process.versions.node.split(".")[0])>=8&&Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("CI"in Ye)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some(t=>t in Ye)||Ye.CI_NAME==="codeship"?1:e;if("TEAMCITY_VERSION"in Ye)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Ye.TEAMCITY_VERSION)?1:0;if(Ye.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in Ye){let t=parseInt((Ye.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Ye.TERM_PROGRAM){case"iTerm.app":return t>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Ye.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Ye.TERM)||"COLORTERM"in Ye?1:(Ye.TERM==="dumb",e)}function Qa(r){let e=j0(r);return q0(e)}fd.exports={supportsColor:Qa,stdout:Qa(process.stdout),stderr:Qa(process.stderr)}});var pd=z((Ge,Fo)=>{var L0=X("tty"),ko=X("util");Ge.init=z0;Ge.log=H0;Ge.formatArgs=M0;Ge.save=G0;Ge.load=W0;Ge.useColors=U0;Ge.destroy=ko.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Ge.colors=[6,2,3,4,5,1];try{let r=dd();r&&(r.stderr||r).level>=2&&(Ge.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}Ge.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(o,a)=>a.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),r[t]=n,r},{});function U0(){return"colors"in Ge.inspectOpts?!!Ge.inspectOpts.colors:L0.isatty(process.stderr.fd)}function M0(r){let{namespace:e,useColors:t}=this;if(t){let n=this.color,o="\x1B[3"+(n<8?n:"8;5;"+n),a=` ${o};1m${e} \x1B[0m`;r[0]=a+r[0].split(` +`).join(` +`+a),r.push(o+"m+"+Fo.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=$0()+e+" "+r[0]}function $0(){return Ge.inspectOpts.hideDate?"":new Date().toISOString()+" "}function H0(...r){return process.stderr.write(ko.formatWithOptions(Ge.inspectOpts,...r)+` +`)}function G0(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function W0(){return process.env.DEBUG}function z0(r){r.inspectOpts={};let e=Object.keys(Ge.inspectOpts);for(let t=0;te.trim()).join(" ")};hd.O=function(r){return this.inspectOpts.colors=this.useColors,ko.inspect(r,this.inspectOpts)}});var eu=z((QA,Za)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Za.exports=ud():Za.exports=pd()});var yd=z(ot=>{"use strict";var J0=ot&&ot.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),V0=ot&&ot.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),md=ot&&ot.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&J0(e,r,t);return V0(e,r),e};Object.defineProperty(ot,"__esModule",{value:!0});ot.req=ot.json=ot.toBuffer=void 0;var K0=md(X("http")),Y0=md(X("https"));async function gd(r){let e=0,t=[];for await(let n of r)e+=n.length,t.push(n);return Buffer.concat(t,e)}ot.toBuffer=gd;async function X0(r){let t=(await gd(r)).toString("utf8");try{return JSON.parse(t)}catch(n){let o=n;throw o.message+=` (input: ${t})`,o}}ot.json=X0;function Q0(r,e={}){let n=((typeof r=="string"?r:r.href).startsWith("https:")?Y0:K0).request(r,e),o=new Promise((a,u)=>{n.once("response",a).once("error",u).end()});return n.then=o.then.bind(o),n}ot.req=Q0});var Ed=z(lt=>{"use strict";var Cd=lt&<.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),Z0=lt&<.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),bd=lt&<.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&Cd(e,r,t);return Z0(e,r),e},e_=lt&<.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Cd(e,r,t)};Object.defineProperty(lt,"__esModule",{value:!0});lt.Agent=void 0;var t_=bd(X("net")),_d=bd(X("http")),r_=X("https");e_(yd(),lt);var Gt=Symbol("AgentBaseInternalState"),tu=class extends _d.Agent{constructor(e){super(e),this[Gt]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:t}=new Error;return typeof t!="string"?!1:t.split(` +`).some(n=>n.indexOf("(https.js:")!==-1||n.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let t=new t_.Socket({writable:!1});return this.sockets[e].push(t),this.totalSocketCount++,t}decrementSockets(e,t){if(!this.sockets[e]||t===null)return;let n=this.sockets[e],o=n.indexOf(t);o!==-1&&(n.splice(o,1),this.totalSocketCount--,n.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?r_.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,t,n){let o={...t,secureEndpoint:this.isSecureEndpoint(t)},a=this.getName(o),u=this.incrementSockets(a);Promise.resolve().then(()=>this.connect(e,o)).then(l=>{if(this.decrementSockets(a,u),l instanceof _d.Agent)try{return l.addRequest(e,o)}catch(f){return n(f)}this[Gt].currentSocket=l,super.createSocket(e,t,n)},l=>{this.decrementSockets(a,u),n(l)})}createConnection(){let e=this[Gt].currentSocket;if(this[Gt].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[Gt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[Gt]&&(this[Gt].defaultPort=e)}get protocol(){return this[Gt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[Gt]&&(this[Gt].protocol=e)}};lt.Agent=tu});var wd=z(Dn=>{"use strict";var n_=Dn&&Dn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Dn,"__esModule",{value:!0});Dn.parseProxyResponse=void 0;var s_=n_(eu()),Oo=(0,s_.default)("https-proxy-agent:parse-proxy-response");function o_(r){return new Promise((e,t)=>{let n=0,o=[];function a(){let d=r.read();d?h(d):r.once("readable",a)}function u(){r.removeListener("end",l),r.removeListener("error",f),r.removeListener("readable",a)}function l(){u(),Oo("onend"),t(new Error("Proxy connection ended before receiving CONNECT response"))}function f(d){u(),Oo("onerror %o",d),t(d)}function h(d){o.push(d),n+=d.length;let _=Buffer.concat(o,n),E=_.indexOf(`\r +\r +`);if(E===-1){Oo("have not received end of HTTP headers yet..."),a();return}let P=_.slice(0,E).toString("ascii").split(`\r +`),v=P.shift();if(!v)return r.destroy(),t(new Error("No header received from proxy CONNECT response"));let w=v.split(" "),g=+w[1],C=w.slice(2).join(" "),R={};for(let S of P){if(!S)continue;let N=S.indexOf(":");if(N===-1)return r.destroy(),t(new Error(`Invalid header from proxy CONNECT response: "${S}"`));let j=S.slice(0,N).toLowerCase(),L=S.slice(N+1).trimStart(),H=R[j];typeof H=="string"?R[j]=[H,L]:Array.isArray(H)?H.push(L):R[j]=L}Oo("got proxy server response: %o %o",v,R),u(),e({connect:{statusCode:g,statusText:C,headers:R},buffered:_})}r.on("error",f),r.on("end",l),a()})}Dn.parseProxyResponse=o_});var Rd=z(wt=>{"use strict";var i_=wt&&wt.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),a_=wt&&wt.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),vd=wt&&wt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&i_(e,r,t);return a_(e,r),e},Td=wt&&wt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(wt,"__esModule",{value:!0});wt.HttpsProxyAgent=void 0;var Po=vd(X("net")),Ad=vd(X("tls")),u_=Td(X("assert")),c_=Td(eu()),l_=Ed(),f_=X("url"),d_=wd(),as=(0,c_.default)("https-proxy-agent"),Dd=r=>r.servername===void 0&&r.host&&!Po.isIP(r.host)?{...r,servername:r.host}:r,xo=class extends l_.Agent{constructor(e,t){super(t),this.options={path:void 0},this.proxy=typeof e=="string"?new f_.URL(e):e,this.proxyHeaders=t?.headers??{},as("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let n=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),o=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...t?Sd(t,"headers"):null,host:n,port:o}}async connect(e,t){let{proxy:n}=this;if(!t.host)throw new TypeError('No "host" provided');let o;n.protocol==="https:"?(as("Creating `tls.Socket`: %o",this.connectOpts),o=Ad.connect(Dd(this.connectOpts))):(as("Creating `net.Socket`: %o",this.connectOpts),o=Po.connect(this.connectOpts));let a=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},u=Po.isIPv6(t.host)?`[${t.host}]`:t.host,l=`CONNECT ${u}:${t.port} HTTP/1.1\r +`;if(n.username||n.password){let E=`${decodeURIComponent(n.username)}:${decodeURIComponent(n.password)}`;a["Proxy-Authorization"]=`Basic ${Buffer.from(E).toString("base64")}`}a.Host=`${u}:${t.port}`,a["Proxy-Connection"]||(a["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let E of Object.keys(a))l+=`${E}: ${a[E]}\r +`;let f=(0,d_.parseProxyResponse)(o);o.write(`${l}\r +`);let{connect:h,buffered:d}=await f;if(e.emit("proxyConnect",h),this.emit("proxyConnect",h,e),h.statusCode===200)return e.once("socket",h_),t.secureEndpoint?(as("Upgrading socket connection to TLS"),Ad.connect({...Sd(Dd(t),"host","path","port"),socket:o})):o;o.destroy();let _=new Po.Socket({writable:!1});return _.readable=!0,e.once("socket",E=>{as("Replaying proxy buffer for failed request"),(0,u_.default)(E.listenerCount("data")>0),E.push(d),E.push(null)}),_}};xo.protocols=["http","https"];wt.HttpsProxyAgent=xo;function h_(r){r.resume()}function Sd(r,...e){let t={},n;for(n in r)e.includes(n)||(t[n]=r[n]);return t}});function p_(r){if(!/^data:/i.test(r))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');r=r.replace(/\r?\n/g,"");let e=r.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");let t=r.substring(5,e).split(";"),n="",o=!1,a=t[0]||"text/plain",u=a;for(let d=1;d{kd=p_});var Pd=z((Bo,Od)=>{(function(r,e){typeof Bo=="object"&&typeof Od<"u"?e(Bo):typeof define=="function"&&define.amd?define(["exports"],e):(r=typeof globalThis<"u"?globalThis:r||self,e(r.WebStreamsPolyfill={}))})(Bo,function(r){"use strict";function e(){}function t(s){return typeof s=="object"&&s!==null||typeof s=="function"}let n=e;function o(s,i){try{Object.defineProperty(s,"name",{value:i,configurable:!0})}catch{}}let a=Promise,u=Promise.prototype.then,l=Promise.reject.bind(a);function f(s){return new a(s)}function h(s){return f(i=>i(s))}function d(s){return l(s)}function _(s,i,c){return u.call(s,i,c)}function E(s,i,c){_(_(s,i,c),void 0,n)}function P(s,i){E(s,i)}function v(s,i){E(s,void 0,i)}function w(s,i,c){return _(s,i,c)}function g(s){_(s,void 0,n)}let C=s=>{if(typeof queueMicrotask=="function")C=queueMicrotask;else{let i=h(void 0);C=c=>_(i,c)}return C(s)};function R(s,i,c){if(typeof s!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(s,i,c)}function S(s,i,c){try{return h(R(s,i,c))}catch(m){return d(m)}}let N=16384;class j{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(i){let c=this._back,m=c;c._elements.length===N-1&&(m={_elements:[],_next:void 0}),c._elements.push(i),m!==c&&(this._back=m,c._next=m),++this._size}shift(){let i=this._front,c=i,m=this._cursor,A=m+1,I=i._elements,U=I[m];return A===N&&(c=i._next,A=0),--this._size,this._cursor=A,i!==c&&(this._front=c),I[m]=void 0,U}forEach(i){let c=this._cursor,m=this._front,A=m._elements;for(;(c!==A.length||m._next!==void 0)&&!(c===A.length&&(m=m._next,A=m._elements,c=0,A.length===0));)i(A[c]),++c}peek(){let i=this._front,c=this._cursor;return i._elements[c]}}let L=Symbol("[[AbortSteps]]"),H=Symbol("[[ErrorSteps]]"),K=Symbol("[[CancelSteps]]"),W=Symbol("[[PullSteps]]"),Ae=Symbol("[[ReleaseSteps]]");function he(s,i){s._ownerReadableStream=i,i._reader=s,i._state==="readable"?de(s):i._state==="closed"?ue(s):Z(s,i._storedError)}function fe(s,i){let c=s._ownerReadableStream;return Ft(c,i)}function ye(s){let i=s._ownerReadableStream;i._state==="readable"?J(s,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):se(s,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),i._readableStreamController[Ae](),i._reader=void 0,s._ownerReadableStream=void 0}function re(s){return new TypeError("Cannot "+s+" a stream using a released reader")}function de(s){s._closedPromise=f((i,c)=>{s._closedPromise_resolve=i,s._closedPromise_reject=c})}function Z(s,i){de(s),J(s,i)}function ue(s){de(s),oe(s)}function J(s,i){s._closedPromise_reject!==void 0&&(g(s._closedPromise),s._closedPromise_reject(i),s._closedPromise_resolve=void 0,s._closedPromise_reject=void 0)}function se(s,i){Z(s,i)}function oe(s){s._closedPromise_resolve!==void 0&&(s._closedPromise_resolve(void 0),s._closedPromise_resolve=void 0,s._closedPromise_reject=void 0)}let Ie=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},je=Math.trunc||function(s){return s<0?Math.ceil(s):Math.floor(s)};function G(s){return typeof s=="object"||typeof s=="function"}function pe(s,i){if(s!==void 0&&!G(s))throw new TypeError(`${i} is not an object.`)}function Ee(s,i){if(typeof s!="function")throw new TypeError(`${i} is not a function.`)}function er(s){return typeof s=="object"&&s!==null||typeof s=="function"}function xe(s,i){if(!er(s))throw new TypeError(`${i} is not an object.`)}function Ne(s,i,c){if(s===void 0)throw new TypeError(`Parameter ${i} is required in '${c}'.`)}function p(s,i,c){if(s===void 0)throw new TypeError(`${i} is required in '${c}'.`)}function y(s){return Number(s)}function b(s){return s===0?0:s}function x(s){return b(je(s))}function T(s,i){let m=Number.MAX_SAFE_INTEGER,A=Number(s);if(A=b(A),!Ie(A))throw new TypeError(`${i} is not a finite number`);if(A=x(A),A<0||A>m)throw new TypeError(`${i} is outside the accepted range of 0 to ${m}, inclusive`);return!Ie(A)||A===0?0:A}function F(s,i){if(!wr(s))throw new TypeError(`${i} is not a ReadableStream.`)}function q(s){return new M(s)}function D(s,i){s._reader._readRequests.push(i)}function k(s,i,c){let A=s._reader._readRequests.shift();c?A._closeSteps():A._chunkSteps(i)}function B(s){return s._reader._readRequests.length}function O(s){let i=s._reader;return!(i===void 0||!Y(i))}class M{constructor(i){if(Ne(i,1,"ReadableStreamDefaultReader"),F(i,"First parameter"),Ar(i))throw new TypeError("This stream has already been locked for exclusive reading by another reader");he(this,i),this._readRequests=new j}get closed(){return Y(this)?this._closedPromise:d(Be("closed"))}cancel(i=void 0){return Y(this)?this._ownerReadableStream===void 0?d(re("cancel")):fe(this,i):d(Be("cancel"))}read(){if(!Y(this))return d(Be("read"));if(this._ownerReadableStream===void 0)return d(re("read from"));let i,c,m=f((I,U)=>{i=I,c=U});return Q(this,{_chunkSteps:I=>i({value:I,done:!1}),_closeSteps:()=>i({value:void 0,done:!0}),_errorSteps:I=>c(I)}),m}releaseLock(){if(!Y(this))throw Be("releaseLock");this._ownerReadableStream!==void 0&&we(this)}}Object.defineProperties(M.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(M.prototype.cancel,"cancel"),o(M.prototype.read,"read"),o(M.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(M.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function Y(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_readRequests")?!1:s instanceof M}function Q(s,i){let c=s._ownerReadableStream;c._disturbed=!0,c._state==="closed"?i._closeSteps():c._state==="errored"?i._errorSteps(c._storedError):c._readableStreamController[W](i)}function we(s){ye(s);let i=new TypeError("Reader was released");Fe(s,i)}function Fe(s,i){let c=s._readRequests;s._readRequests=new j,c.forEach(m=>{m._errorSteps(i)})}function Be(s){return new TypeError(`ReadableStreamDefaultReader.prototype.${s} can only be used on a ReadableStreamDefaultReader`)}let be=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype);class De{constructor(i,c){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=i,this._preventCancel=c}next(){let i=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?w(this._ongoingPromise,i,i):i(),this._ongoingPromise}return(i){let c=()=>this._returnSteps(i);return this._ongoingPromise?w(this._ongoingPromise,c,c):c()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let i=this._reader,c,m,A=f((U,V)=>{c=U,m=V});return Q(i,{_chunkSteps:U=>{this._ongoingPromise=void 0,C(()=>c({value:U,done:!1}))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,ye(i),c({value:void 0,done:!0})},_errorSteps:U=>{this._ongoingPromise=void 0,this._isFinished=!0,ye(i),m(U)}}),A}_returnSteps(i){if(this._isFinished)return Promise.resolve({value:i,done:!0});this._isFinished=!0;let c=this._reader;if(!this._preventCancel){let m=fe(c,i);return ye(c),w(m,()=>({value:i,done:!0}))}return ye(c),h({value:i,done:!0})}}let Le={next(){return on(this)?this._asyncIteratorImpl.next():d(an("next"))},return(s){return on(this)?this._asyncIteratorImpl.return(s):d(an("return"))}};Object.setPrototypeOf(Le,be);function sn(s,i){let c=q(s),m=new De(c,i),A=Object.create(Le);return A._asyncIteratorImpl=m,A}function on(s){if(!t(s)||!Object.prototype.hasOwnProperty.call(s,"_asyncIteratorImpl"))return!1;try{return s._asyncIteratorImpl instanceof De}catch{return!1}}function an(s){return new TypeError(`ReadableStreamAsyncIterator.${s} can only be used on a ReadableSteamAsyncIterator`)}let ut=Number.isNaN||function(s){return s!==s};var tr,Ve,Ue;function Se(s){return s.slice()}function bl(s,i,c,m,A){new Uint8Array(s).set(new Uint8Array(c,m,A),i)}let rr=s=>(typeof s.transfer=="function"?rr=i=>i.transfer():typeof structuredClone=="function"?rr=i=>structuredClone(i,{transfer:[i]}):rr=i=>i,rr(s)),_r=s=>(typeof s.detached=="boolean"?_r=i=>i.detached:_r=i=>i.byteLength===0,_r(s));function El(s,i,c){if(s.slice)return s.slice(i,c);let m=c-i,A=new ArrayBuffer(m);return bl(A,0,s,i,m),A}function qs(s,i){let c=s[i];if(c!=null){if(typeof c!="function")throw new TypeError(`${String(i)} is not a function`);return c}}function ig(s){let i={[Symbol.iterator]:()=>s.iterator},c=async function*(){return yield*i}(),m=c.next;return{iterator:c,nextMethod:m,done:!1}}let oa=(Ue=(tr=Symbol.asyncIterator)!==null&&tr!==void 0?tr:(Ve=Symbol.for)===null||Ve===void 0?void 0:Ve.call(Symbol,"Symbol.asyncIterator"))!==null&&Ue!==void 0?Ue:"@@asyncIterator";function wl(s,i="sync",c){if(c===void 0)if(i==="async"){if(c=qs(s,oa),c===void 0){let I=qs(s,Symbol.iterator),U=wl(s,"sync",I);return ig(U)}}else c=qs(s,Symbol.iterator);if(c===void 0)throw new TypeError("The object is not iterable");let m=R(c,s,[]);if(!t(m))throw new TypeError("The iterator method must return an object");let A=m.next;return{iterator:m,nextMethod:A,done:!1}}function ag(s){let i=R(s.nextMethod,s.iterator,[]);if(!t(i))throw new TypeError("The iterator.next() method must return an object");return i}function ug(s){return!!s.done}function cg(s){return s.value}function lg(s){return!(typeof s!="number"||ut(s)||s<0)}function Al(s){let i=El(s.buffer,s.byteOffset,s.byteOffset+s.byteLength);return new Uint8Array(i)}function ia(s){let i=s._queue.shift();return s._queueTotalSize-=i.size,s._queueTotalSize<0&&(s._queueTotalSize=0),i.value}function aa(s,i,c){if(!lg(c)||c===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");s._queue.push({value:i,size:c}),s._queueTotalSize+=c}function fg(s){return s._queue.peek().value}function Cr(s){s._queue=new j,s._queueTotalSize=0}function Dl(s){return s===DataView}function dg(s){return Dl(s.constructor)}function hg(s){return Dl(s)?1:s.BYTES_PER_ELEMENT}class jr{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!ua(this))throw ha("view");return this._view}respond(i){if(!ua(this))throw ha("respond");if(Ne(i,1,"respond"),i=T(i,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(_r(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");Ms(this._associatedReadableByteStreamController,i)}respondWithNewView(i){if(!ua(this))throw ha("respondWithNewView");if(Ne(i,1,"respondWithNewView"),!ArrayBuffer.isView(i))throw new TypeError("You can only respond with array buffer views");if(this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(_r(i.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");$s(this._associatedReadableByteStreamController,i)}}Object.defineProperties(jr.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),o(jr.prototype.respond,"respond"),o(jr.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(jr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class nr{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Lr(this))throw Xn("byobRequest");return da(this)}get desiredSize(){if(!Lr(this))throw Xn("desiredSize");return Bl(this)}close(){if(!Lr(this))throw Xn("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let i=this._controlledReadableByteStream._state;if(i!=="readable")throw new TypeError(`The stream (in ${i} state) is not in the readable state and cannot be closed`);Yn(this)}enqueue(i){if(!Lr(this))throw Xn("enqueue");if(Ne(i,1,"enqueue"),!ArrayBuffer.isView(i))throw new TypeError("chunk must be an array buffer view");if(i.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(i.buffer.byteLength===0)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");let c=this._controlledReadableByteStream._state;if(c!=="readable")throw new TypeError(`The stream (in ${c} state) is not in the readable state and cannot be enqueued to`);Us(this,i)}error(i=void 0){if(!Lr(this))throw Xn("error");Ct(this,i)}[K](i){Sl(this),Cr(this);let c=this._cancelAlgorithm(i);return Ls(this),c}[W](i){let c=this._controlledReadableByteStream;if(this._queueTotalSize>0){xl(this,i);return}let m=this._autoAllocateChunkSize;if(m!==void 0){let A;try{A=new ArrayBuffer(m)}catch(U){i._errorSteps(U);return}let I={buffer:A,bufferByteLength:m,byteOffset:0,byteLength:m,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(I)}D(c,i),Ur(this)}[Ae](){if(this._pendingPullIntos.length>0){let i=this._pendingPullIntos.peek();i.readerType="none",this._pendingPullIntos=new j,this._pendingPullIntos.push(i)}}}Object.defineProperties(nr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),o(nr.prototype.close,"close"),o(nr.prototype.enqueue,"enqueue"),o(nr.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(nr.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function Lr(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_controlledReadableByteStream")?!1:s instanceof nr}function ua(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_associatedReadableByteStreamController")?!1:s instanceof jr}function Ur(s){if(!_g(s))return;if(s._pulling){s._pullAgain=!0;return}s._pulling=!0;let c=s._pullAlgorithm();E(c,()=>(s._pulling=!1,s._pullAgain&&(s._pullAgain=!1,Ur(s)),null),m=>(Ct(s,m),null))}function Sl(s){la(s),s._pendingPullIntos=new j}function ca(s,i){let c=!1;s._state==="closed"&&(c=!0);let m=vl(i);i.readerType==="default"?k(s,m,c):Dg(s,m,c)}function vl(s){let i=s.bytesFilled,c=s.elementSize;return new s.viewConstructor(s.buffer,s.byteOffset,i/c)}function js(s,i,c,m){s._queue.push({buffer:i,byteOffset:c,byteLength:m}),s._queueTotalSize+=m}function Tl(s,i,c,m){let A;try{A=El(i,c,c+m)}catch(I){throw Ct(s,I),I}js(s,A,0,m)}function Rl(s,i){i.bytesFilled>0&&Tl(s,i.buffer,i.byteOffset,i.bytesFilled),un(s)}function kl(s,i){let c=Math.min(s._queueTotalSize,i.byteLength-i.bytesFilled),m=i.bytesFilled+c,A=c,I=!1,U=m%i.elementSize,V=m-U;V>=i.minimumFill&&(A=V-i.bytesFilled,I=!0);let ae=s._queue;for(;A>0;){let te=ae.peek(),ce=Math.min(A,te.byteLength),ge=i.byteOffset+i.bytesFilled;bl(i.buffer,ge,te.buffer,te.byteOffset,ce),te.byteLength===ce?ae.shift():(te.byteOffset+=ce,te.byteLength-=ce),s._queueTotalSize-=ce,Fl(s,ce,i),A-=ce}return I}function Fl(s,i,c){c.bytesFilled+=i}function Ol(s){s._queueTotalSize===0&&s._closeRequested?(Ls(s),ns(s._controlledReadableByteStream)):Ur(s)}function la(s){s._byobRequest!==null&&(s._byobRequest._associatedReadableByteStreamController=void 0,s._byobRequest._view=null,s._byobRequest=null)}function fa(s){for(;s._pendingPullIntos.length>0;){if(s._queueTotalSize===0)return;let i=s._pendingPullIntos.peek();kl(s,i)&&(un(s),ca(s._controlledReadableByteStream,i))}}function pg(s){let i=s._controlledReadableByteStream._reader;for(;i._readRequests.length>0;){if(s._queueTotalSize===0)return;let c=i._readRequests.shift();xl(s,c)}}function mg(s,i,c,m){let A=s._controlledReadableByteStream,I=i.constructor,U=hg(I),{byteOffset:V,byteLength:ae}=i,te=c*U,ce;try{ce=rr(i.buffer)}catch(Te){m._errorSteps(Te);return}let ge={buffer:ce,bufferByteLength:ce.byteLength,byteOffset:V,byteLength:ae,bytesFilled:0,minimumFill:te,elementSize:U,viewConstructor:I,readerType:"byob"};if(s._pendingPullIntos.length>0){s._pendingPullIntos.push(ge),ql(A,m);return}if(A._state==="closed"){let Te=new I(ge.buffer,ge.byteOffset,0);m._closeSteps(Te);return}if(s._queueTotalSize>0){if(kl(s,ge)){let Te=vl(ge);Ol(s),m._chunkSteps(Te);return}if(s._closeRequested){let Te=new TypeError("Insufficient bytes to fill elements in the given buffer");Ct(s,Te),m._errorSteps(Te);return}}s._pendingPullIntos.push(ge),ql(A,m),Ur(s)}function gg(s,i){i.readerType==="none"&&un(s);let c=s._controlledReadableByteStream;if(pa(c))for(;jl(c)>0;){let m=un(s);ca(c,m)}}function yg(s,i,c){if(Fl(s,i,c),c.readerType==="none"){Rl(s,c),fa(s);return}if(c.bytesFilled0){let A=c.byteOffset+c.bytesFilled;Tl(s,c.buffer,A-m,m)}c.bytesFilled-=m,ca(s._controlledReadableByteStream,c),fa(s)}function Pl(s,i){let c=s._pendingPullIntos.peek();la(s),s._controlledReadableByteStream._state==="closed"?gg(s,c):yg(s,i,c),Ur(s)}function un(s){return s._pendingPullIntos.shift()}function _g(s){let i=s._controlledReadableByteStream;return i._state!=="readable"||s._closeRequested||!s._started?!1:!!(O(i)&&B(i)>0||pa(i)&&jl(i)>0||Bl(s)>0)}function Ls(s){s._pullAlgorithm=void 0,s._cancelAlgorithm=void 0}function Yn(s){let i=s._controlledReadableByteStream;if(!(s._closeRequested||i._state!=="readable")){if(s._queueTotalSize>0){s._closeRequested=!0;return}if(s._pendingPullIntos.length>0){let c=s._pendingPullIntos.peek();if(c.bytesFilled%c.elementSize!==0){let m=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Ct(s,m),m}}Ls(s),ns(i)}}function Us(s,i){let c=s._controlledReadableByteStream;if(s._closeRequested||c._state!=="readable")return;let{buffer:m,byteOffset:A,byteLength:I}=i;if(_r(m))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let U=rr(m);if(s._pendingPullIntos.length>0){let V=s._pendingPullIntos.peek();if(_r(V.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");la(s),V.buffer=rr(V.buffer),V.readerType==="none"&&Rl(s,V)}if(O(c))if(pg(s),B(c)===0)js(s,U,A,I);else{s._pendingPullIntos.length>0&&un(s);let V=new Uint8Array(U,A,I);k(c,V,!1)}else pa(c)?(js(s,U,A,I),fa(s)):js(s,U,A,I);Ur(s)}function Ct(s,i){let c=s._controlledReadableByteStream;c._state==="readable"&&(Sl(s),Cr(s),Ls(s),cf(c,i))}function xl(s,i){let c=s._queue.shift();s._queueTotalSize-=c.byteLength,Ol(s);let m=new Uint8Array(c.buffer,c.byteOffset,c.byteLength);i._chunkSteps(m)}function da(s){if(s._byobRequest===null&&s._pendingPullIntos.length>0){let i=s._pendingPullIntos.peek(),c=new Uint8Array(i.buffer,i.byteOffset+i.bytesFilled,i.byteLength-i.bytesFilled),m=Object.create(jr.prototype);bg(m,s,c),s._byobRequest=m}return s._byobRequest}function Bl(s){let i=s._controlledReadableByteStream._state;return i==="errored"?null:i==="closed"?0:s._strategyHWM-s._queueTotalSize}function Ms(s,i){let c=s._pendingPullIntos.peek();if(s._controlledReadableByteStream._state==="closed"){if(i!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(i===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(c.bytesFilled+i>c.byteLength)throw new RangeError("bytesWritten out of range")}c.buffer=rr(c.buffer),Pl(s,i)}function $s(s,i){let c=s._pendingPullIntos.peek();if(s._controlledReadableByteStream._state==="closed"){if(i.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(i.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(c.byteOffset+c.bytesFilled!==i.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(c.bufferByteLength!==i.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(c.bytesFilled+i.byteLength>c.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let A=i.byteLength;c.buffer=rr(i.buffer),Pl(s,A)}function Il(s,i,c,m,A,I,U){i._controlledReadableByteStream=s,i._pullAgain=!1,i._pulling=!1,i._byobRequest=null,i._queue=i._queueTotalSize=void 0,Cr(i),i._closeRequested=!1,i._started=!1,i._strategyHWM=I,i._pullAlgorithm=m,i._cancelAlgorithm=A,i._autoAllocateChunkSize=U,i._pendingPullIntos=new j,s._readableStreamController=i;let V=c();E(h(V),()=>(i._started=!0,Ur(i),null),ae=>(Ct(i,ae),null))}function Cg(s,i,c){let m=Object.create(nr.prototype),A,I,U;i.start!==void 0?A=()=>i.start(m):A=()=>{},i.pull!==void 0?I=()=>i.pull(m):I=()=>h(void 0),i.cancel!==void 0?U=ae=>i.cancel(ae):U=()=>h(void 0);let V=i.autoAllocateChunkSize;if(V===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");Il(s,m,A,I,U,c,V)}function bg(s,i,c){s._associatedReadableByteStreamController=i,s._view=c}function ha(s){return new TypeError(`ReadableStreamBYOBRequest.prototype.${s} can only be used on a ReadableStreamBYOBRequest`)}function Xn(s){return new TypeError(`ReadableByteStreamController.prototype.${s} can only be used on a ReadableByteStreamController`)}function Eg(s,i){pe(s,i);let c=s?.mode;return{mode:c===void 0?void 0:wg(c,`${i} has member 'mode' that`)}}function wg(s,i){if(s=`${s}`,s!=="byob")throw new TypeError(`${i} '${s}' is not a valid enumeration value for ReadableStreamReaderMode`);return s}function Ag(s,i){var c;pe(s,i);let m=(c=s?.min)!==null&&c!==void 0?c:1;return{min:T(m,`${i} has member 'min' that`)}}function Nl(s){return new br(s)}function ql(s,i){s._reader._readIntoRequests.push(i)}function Dg(s,i,c){let A=s._reader._readIntoRequests.shift();c?A._closeSteps(i):A._chunkSteps(i)}function jl(s){return s._reader._readIntoRequests.length}function pa(s){let i=s._reader;return!(i===void 0||!Mr(i))}class br{constructor(i){if(Ne(i,1,"ReadableStreamBYOBReader"),F(i,"First parameter"),Ar(i))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Lr(i._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");he(this,i),this._readIntoRequests=new j}get closed(){return Mr(this)?this._closedPromise:d(Hs("closed"))}cancel(i=void 0){return Mr(this)?this._ownerReadableStream===void 0?d(re("cancel")):fe(this,i):d(Hs("cancel"))}read(i,c={}){if(!Mr(this))return d(Hs("read"));if(!ArrayBuffer.isView(i))return d(new TypeError("view must be an array buffer view"));if(i.byteLength===0)return d(new TypeError("view must have non-zero byteLength"));if(i.buffer.byteLength===0)return d(new TypeError("view's buffer must have non-zero byteLength"));if(_r(i.buffer))return d(new TypeError("view's buffer has been detached"));let m;try{m=Ag(c,"options")}catch(te){return d(te)}let A=m.min;if(A===0)return d(new TypeError("options.min must be greater than 0"));if(dg(i)){if(A>i.byteLength)return d(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(A>i.length)return d(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return d(re("read from"));let I,U,V=f((te,ce)=>{I=te,U=ce});return Ll(this,i,A,{_chunkSteps:te=>I({value:te,done:!1}),_closeSteps:te=>I({value:te,done:!0}),_errorSteps:te=>U(te)}),V}releaseLock(){if(!Mr(this))throw Hs("releaseLock");this._ownerReadableStream!==void 0&&Sg(this)}}Object.defineProperties(br.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),o(br.prototype.cancel,"cancel"),o(br.prototype.read,"read"),o(br.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(br.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function Mr(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_readIntoRequests")?!1:s instanceof br}function Ll(s,i,c,m){let A=s._ownerReadableStream;A._disturbed=!0,A._state==="errored"?m._errorSteps(A._storedError):mg(A._readableStreamController,i,c,m)}function Sg(s){ye(s);let i=new TypeError("Reader was released");Ul(s,i)}function Ul(s,i){let c=s._readIntoRequests;s._readIntoRequests=new j,c.forEach(m=>{m._errorSteps(i)})}function Hs(s){return new TypeError(`ReadableStreamBYOBReader.prototype.${s} can only be used on a ReadableStreamBYOBReader`)}function Qn(s,i){let{highWaterMark:c}=s;if(c===void 0)return i;if(ut(c)||c<0)throw new RangeError("Invalid highWaterMark");return c}function Gs(s){let{size:i}=s;return i||(()=>1)}function Ws(s,i){pe(s,i);let c=s?.highWaterMark,m=s?.size;return{highWaterMark:c===void 0?void 0:y(c),size:m===void 0?void 0:vg(m,`${i} has member 'size' that`)}}function vg(s,i){return Ee(s,i),c=>y(s(c))}function Tg(s,i){pe(s,i);let c=s?.abort,m=s?.close,A=s?.start,I=s?.type,U=s?.write;return{abort:c===void 0?void 0:Rg(c,s,`${i} has member 'abort' that`),close:m===void 0?void 0:kg(m,s,`${i} has member 'close' that`),start:A===void 0?void 0:Fg(A,s,`${i} has member 'start' that`),write:U===void 0?void 0:Og(U,s,`${i} has member 'write' that`),type:I}}function Rg(s,i,c){return Ee(s,c),m=>S(s,i,[m])}function kg(s,i,c){return Ee(s,c),()=>S(s,i,[])}function Fg(s,i,c){return Ee(s,c),m=>R(s,i,[m])}function Og(s,i,c){return Ee(s,c),(m,A)=>S(s,i,[m,A])}function Ml(s,i){if(!cn(s))throw new TypeError(`${i} is not a WritableStream.`)}function Pg(s){if(typeof s!="object"||s===null)return!1;try{return typeof s.aborted=="boolean"}catch{return!1}}let xg=typeof AbortController=="function";function Bg(){if(xg)return new AbortController}class Er{constructor(i={},c={}){i===void 0?i=null:xe(i,"First parameter");let m=Ws(c,"Second parameter"),A=Tg(i,"First parameter");if(Hl(this),A.type!==void 0)throw new RangeError("Invalid type is specified");let U=Gs(m),V=Qn(m,1);Vg(this,A,V,U)}get locked(){if(!cn(this))throw Ys("locked");return ln(this)}abort(i=void 0){return cn(this)?ln(this)?d(new TypeError("Cannot abort a stream that already has a writer")):zs(this,i):d(Ys("abort"))}close(){return cn(this)?ln(this)?d(new TypeError("Cannot close a stream that already has a writer")):Ht(this)?d(new TypeError("Cannot close an already-closing stream")):Gl(this):d(Ys("close"))}getWriter(){if(!cn(this))throw Ys("getWriter");return $l(this)}}Object.defineProperties(Er.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),o(Er.prototype.abort,"abort"),o(Er.prototype.close,"close"),o(Er.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Er.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function $l(s){return new sr(s)}function Ig(s,i,c,m,A=1,I=()=>1){let U=Object.create(Er.prototype);Hl(U);let V=Object.create(fn.prototype);return Yl(U,V,s,i,c,m,A,I),U}function Hl(s){s._state="writable",s._storedError=void 0,s._writer=void 0,s._writableStreamController=void 0,s._writeRequests=new j,s._inFlightWriteRequest=void 0,s._closeRequest=void 0,s._inFlightCloseRequest=void 0,s._pendingAbortRequest=void 0,s._backpressure=!1}function cn(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_writableStreamController")?!1:s instanceof Er}function ln(s){return s._writer!==void 0}function zs(s,i){var c;if(s._state==="closed"||s._state==="errored")return h(void 0);s._writableStreamController._abortReason=i,(c=s._writableStreamController._abortController)===null||c===void 0||c.abort(i);let m=s._state;if(m==="closed"||m==="errored")return h(void 0);if(s._pendingAbortRequest!==void 0)return s._pendingAbortRequest._promise;let A=!1;m==="erroring"&&(A=!0,i=void 0);let I=f((U,V)=>{s._pendingAbortRequest={_promise:void 0,_resolve:U,_reject:V,_reason:i,_wasAlreadyErroring:A}});return s._pendingAbortRequest._promise=I,A||ga(s,i),I}function Gl(s){let i=s._state;if(i==="closed"||i==="errored")return d(new TypeError(`The stream (in ${i} state) is not in the writable state and cannot be closed`));let c=f((A,I)=>{let U={_resolve:A,_reject:I};s._closeRequest=U}),m=s._writer;return m!==void 0&&s._backpressure&&i==="writable"&&Da(m),Kg(s._writableStreamController),c}function Ng(s){return f((c,m)=>{let A={_resolve:c,_reject:m};s._writeRequests.push(A)})}function ma(s,i){if(s._state==="writable"){ga(s,i);return}ya(s)}function ga(s,i){let c=s._writableStreamController;s._state="erroring",s._storedError=i;let m=s._writer;m!==void 0&&zl(m,i),!Mg(s)&&c._started&&ya(s)}function ya(s){s._state="errored",s._writableStreamController[H]();let i=s._storedError;if(s._writeRequests.forEach(A=>{A._reject(i)}),s._writeRequests=new j,s._pendingAbortRequest===void 0){Js(s);return}let c=s._pendingAbortRequest;if(s._pendingAbortRequest=void 0,c._wasAlreadyErroring){c._reject(i),Js(s);return}let m=s._writableStreamController[L](c._reason);E(m,()=>(c._resolve(),Js(s),null),A=>(c._reject(A),Js(s),null))}function qg(s){s._inFlightWriteRequest._resolve(void 0),s._inFlightWriteRequest=void 0}function jg(s,i){s._inFlightWriteRequest._reject(i),s._inFlightWriteRequest=void 0,ma(s,i)}function Lg(s){s._inFlightCloseRequest._resolve(void 0),s._inFlightCloseRequest=void 0,s._state==="erroring"&&(s._storedError=void 0,s._pendingAbortRequest!==void 0&&(s._pendingAbortRequest._resolve(),s._pendingAbortRequest=void 0)),s._state="closed";let c=s._writer;c!==void 0&&ef(c)}function Ug(s,i){s._inFlightCloseRequest._reject(i),s._inFlightCloseRequest=void 0,s._pendingAbortRequest!==void 0&&(s._pendingAbortRequest._reject(i),s._pendingAbortRequest=void 0),ma(s,i)}function Ht(s){return!(s._closeRequest===void 0&&s._inFlightCloseRequest===void 0)}function Mg(s){return!(s._inFlightWriteRequest===void 0&&s._inFlightCloseRequest===void 0)}function $g(s){s._inFlightCloseRequest=s._closeRequest,s._closeRequest=void 0}function Hg(s){s._inFlightWriteRequest=s._writeRequests.shift()}function Js(s){s._closeRequest!==void 0&&(s._closeRequest._reject(s._storedError),s._closeRequest=void 0);let i=s._writer;i!==void 0&&wa(i,s._storedError)}function _a(s,i){let c=s._writer;c!==void 0&&i!==s._backpressure&&(i?ry(c):Da(c)),s._backpressure=i}class sr{constructor(i){if(Ne(i,1,"WritableStreamDefaultWriter"),Ml(i,"First parameter"),ln(i))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=i,i._writer=this;let c=i._state;if(c==="writable")!Ht(i)&&i._backpressure?Qs(this):tf(this),Xs(this);else if(c==="erroring")Aa(this,i._storedError),Xs(this);else if(c==="closed")tf(this),ey(this);else{let m=i._storedError;Aa(this,m),Zl(this,m)}}get closed(){return $r(this)?this._closedPromise:d(Hr("closed"))}get desiredSize(){if(!$r(this))throw Hr("desiredSize");if(this._ownerWritableStream===void 0)throw es("desiredSize");return Jg(this)}get ready(){return $r(this)?this._readyPromise:d(Hr("ready"))}abort(i=void 0){return $r(this)?this._ownerWritableStream===void 0?d(es("abort")):Gg(this,i):d(Hr("abort"))}close(){if(!$r(this))return d(Hr("close"));let i=this._ownerWritableStream;return i===void 0?d(es("close")):Ht(i)?d(new TypeError("Cannot close an already-closing stream")):Wl(this)}releaseLock(){if(!$r(this))throw Hr("releaseLock");this._ownerWritableStream!==void 0&&Jl(this)}write(i=void 0){return $r(this)?this._ownerWritableStream===void 0?d(es("write to")):Vl(this,i):d(Hr("write"))}}Object.defineProperties(sr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),o(sr.prototype.abort,"abort"),o(sr.prototype.close,"close"),o(sr.prototype.releaseLock,"releaseLock"),o(sr.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(sr.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function $r(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_ownerWritableStream")?!1:s instanceof sr}function Gg(s,i){let c=s._ownerWritableStream;return zs(c,i)}function Wl(s){let i=s._ownerWritableStream;return Gl(i)}function Wg(s){let i=s._ownerWritableStream,c=i._state;return Ht(i)||c==="closed"?h(void 0):c==="errored"?d(i._storedError):Wl(s)}function zg(s,i){s._closedPromiseState==="pending"?wa(s,i):ty(s,i)}function zl(s,i){s._readyPromiseState==="pending"?rf(s,i):ny(s,i)}function Jg(s){let i=s._ownerWritableStream,c=i._state;return c==="errored"||c==="erroring"?null:c==="closed"?0:Xl(i._writableStreamController)}function Jl(s){let i=s._ownerWritableStream,c=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");zl(s,c),zg(s,c),i._writer=void 0,s._ownerWritableStream=void 0}function Vl(s,i){let c=s._ownerWritableStream,m=c._writableStreamController,A=Yg(m,i);if(c!==s._ownerWritableStream)return d(es("write to"));let I=c._state;if(I==="errored")return d(c._storedError);if(Ht(c)||I==="closed")return d(new TypeError("The stream is closing or closed and cannot be written to"));if(I==="erroring")return d(c._storedError);let U=Ng(c);return Xg(m,i,A),U}let Kl={};class fn{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!Ca(this))throw Ea("abortReason");return this._abortReason}get signal(){if(!Ca(this))throw Ea("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(i=void 0){if(!Ca(this))throw Ea("error");this._controlledWritableStream._state==="writable"&&Ql(this,i)}[L](i){let c=this._abortAlgorithm(i);return Vs(this),c}[H](){Cr(this)}}Object.defineProperties(fn.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(fn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function Ca(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_controlledWritableStream")?!1:s instanceof fn}function Yl(s,i,c,m,A,I,U,V){i._controlledWritableStream=s,s._writableStreamController=i,i._queue=void 0,i._queueTotalSize=void 0,Cr(i),i._abortReason=void 0,i._abortController=Bg(),i._started=!1,i._strategySizeAlgorithm=V,i._strategyHWM=U,i._writeAlgorithm=m,i._closeAlgorithm=A,i._abortAlgorithm=I;let ae=ba(i);_a(s,ae);let te=c(),ce=h(te);E(ce,()=>(i._started=!0,Ks(i),null),ge=>(i._started=!0,ma(s,ge),null))}function Vg(s,i,c,m){let A=Object.create(fn.prototype),I,U,V,ae;i.start!==void 0?I=()=>i.start(A):I=()=>{},i.write!==void 0?U=te=>i.write(te,A):U=()=>h(void 0),i.close!==void 0?V=()=>i.close():V=()=>h(void 0),i.abort!==void 0?ae=te=>i.abort(te):ae=()=>h(void 0),Yl(s,A,I,U,V,ae,c,m)}function Vs(s){s._writeAlgorithm=void 0,s._closeAlgorithm=void 0,s._abortAlgorithm=void 0,s._strategySizeAlgorithm=void 0}function Kg(s){aa(s,Kl,0),Ks(s)}function Yg(s,i){try{return s._strategySizeAlgorithm(i)}catch(c){return Zn(s,c),1}}function Xl(s){return s._strategyHWM-s._queueTotalSize}function Xg(s,i,c){try{aa(s,i,c)}catch(A){Zn(s,A);return}let m=s._controlledWritableStream;if(!Ht(m)&&m._state==="writable"){let A=ba(s);_a(m,A)}Ks(s)}function Ks(s){let i=s._controlledWritableStream;if(!s._started||i._inFlightWriteRequest!==void 0)return;if(i._state==="erroring"){ya(i);return}if(s._queue.length===0)return;let m=fg(s);m===Kl?Qg(s):Zg(s,m)}function Zn(s,i){s._controlledWritableStream._state==="writable"&&Ql(s,i)}function Qg(s){let i=s._controlledWritableStream;$g(i),ia(s);let c=s._closeAlgorithm();Vs(s),E(c,()=>(Lg(i),null),m=>(Ug(i,m),null))}function Zg(s,i){let c=s._controlledWritableStream;Hg(c);let m=s._writeAlgorithm(i);E(m,()=>{qg(c);let A=c._state;if(ia(s),!Ht(c)&&A==="writable"){let I=ba(s);_a(c,I)}return Ks(s),null},A=>(c._state==="writable"&&Vs(s),jg(c,A),null))}function ba(s){return Xl(s)<=0}function Ql(s,i){let c=s._controlledWritableStream;Vs(s),ga(c,i)}function Ys(s){return new TypeError(`WritableStream.prototype.${s} can only be used on a WritableStream`)}function Ea(s){return new TypeError(`WritableStreamDefaultController.prototype.${s} can only be used on a WritableStreamDefaultController`)}function Hr(s){return new TypeError(`WritableStreamDefaultWriter.prototype.${s} can only be used on a WritableStreamDefaultWriter`)}function es(s){return new TypeError("Cannot "+s+" a stream using a released writer")}function Xs(s){s._closedPromise=f((i,c)=>{s._closedPromise_resolve=i,s._closedPromise_reject=c,s._closedPromiseState="pending"})}function Zl(s,i){Xs(s),wa(s,i)}function ey(s){Xs(s),ef(s)}function wa(s,i){s._closedPromise_reject!==void 0&&(g(s._closedPromise),s._closedPromise_reject(i),s._closedPromise_resolve=void 0,s._closedPromise_reject=void 0,s._closedPromiseState="rejected")}function ty(s,i){Zl(s,i)}function ef(s){s._closedPromise_resolve!==void 0&&(s._closedPromise_resolve(void 0),s._closedPromise_resolve=void 0,s._closedPromise_reject=void 0,s._closedPromiseState="resolved")}function Qs(s){s._readyPromise=f((i,c)=>{s._readyPromise_resolve=i,s._readyPromise_reject=c}),s._readyPromiseState="pending"}function Aa(s,i){Qs(s),rf(s,i)}function tf(s){Qs(s),Da(s)}function rf(s,i){s._readyPromise_reject!==void 0&&(g(s._readyPromise),s._readyPromise_reject(i),s._readyPromise_resolve=void 0,s._readyPromise_reject=void 0,s._readyPromiseState="rejected")}function ry(s){Qs(s)}function ny(s,i){Aa(s,i)}function Da(s){s._readyPromise_resolve!==void 0&&(s._readyPromise_resolve(void 0),s._readyPromise_resolve=void 0,s._readyPromise_reject=void 0,s._readyPromiseState="fulfilled")}function sy(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof global<"u")return global}let Sa=sy();function oy(s){if(!(typeof s=="function"||typeof s=="object")||s.name!=="DOMException")return!1;try{return new s,!0}catch{return!1}}function iy(){let s=Sa?.DOMException;return oy(s)?s:void 0}function ay(){let s=function(c,m){this.message=c||"",this.name=m||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return o(s,"DOMException"),s.prototype=Object.create(Error.prototype),Object.defineProperty(s.prototype,"constructor",{value:s,writable:!0,configurable:!0}),s}let uy=iy()||ay();function nf(s,i,c,m,A,I){let U=q(s),V=$l(i);s._disturbed=!0;let ae=!1,te=h(void 0);return f((ce,ge)=>{let Te;if(I!==void 0){if(Te=()=>{let ne=I.reason!==void 0?I.reason:new uy("Aborted","AbortError"),_e=[];m||_e.push(()=>i._state==="writable"?zs(i,ne):h(void 0)),A||_e.push(()=>s._state==="readable"?Ft(s,ne):h(void 0)),rt(()=>Promise.all(_e.map(Re=>Re())),!0,ne)},I.aborted){Te();return}I.addEventListener("abort",Te)}function Ot(){return f((ne,_e)=>{function Re(ct){ct?ne():_(mn(),Re,_e)}Re(!1)})}function mn(){return ae?h(!0):_(V._readyPromise,()=>f((ne,_e)=>{Q(U,{_chunkSteps:Re=>{te=_(Vl(V,Re),void 0,e),ne(!1)},_closeSteps:()=>ne(!0),_errorSteps:_e})}))}if(ir(s,U._closedPromise,ne=>(m?bt(!0,ne):rt(()=>zs(i,ne),!0,ne),null)),ir(i,V._closedPromise,ne=>(A?bt(!0,ne):rt(()=>Ft(s,ne),!0,ne),null)),Qe(s,U._closedPromise,()=>(c?bt():rt(()=>Wg(V)),null)),Ht(i)||i._state==="closed"){let ne=new TypeError("the destination writable stream closed before all data could be piped to it");A?bt(!0,ne):rt(()=>Ft(s,ne),!0,ne)}g(Ot());function Sr(){let ne=te;return _(te,()=>ne!==te?Sr():void 0)}function ir(ne,_e,Re){ne._state==="errored"?Re(ne._storedError):v(_e,Re)}function Qe(ne,_e,Re){ne._state==="closed"?Re():P(_e,Re)}function rt(ne,_e,Re){if(ae)return;ae=!0,i._state==="writable"&&!Ht(i)?P(Sr(),ct):ct();function ct(){return E(ne(),()=>ar(_e,Re),gn=>ar(!0,gn)),null}}function bt(ne,_e){ae||(ae=!0,i._state==="writable"&&!Ht(i)?P(Sr(),()=>ar(ne,_e)):ar(ne,_e))}function ar(ne,_e){return Jl(V),ye(U),I!==void 0&&I.removeEventListener("abort",Te),ne?ge(_e):ce(void 0),null}})}class or{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Zs(this))throw to("desiredSize");return va(this)}close(){if(!Zs(this))throw to("close");if(!hn(this))throw new TypeError("The stream is not in a state that permits close");Gr(this)}enqueue(i=void 0){if(!Zs(this))throw to("enqueue");if(!hn(this))throw new TypeError("The stream is not in a state that permits enqueue");return dn(this,i)}error(i=void 0){if(!Zs(this))throw to("error");kt(this,i)}[K](i){Cr(this);let c=this._cancelAlgorithm(i);return eo(this),c}[W](i){let c=this._controlledReadableStream;if(this._queue.length>0){let m=ia(this);this._closeRequested&&this._queue.length===0?(eo(this),ns(c)):ts(this),i._chunkSteps(m)}else D(c,i),ts(this)}[Ae](){}}Object.defineProperties(or.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),o(or.prototype.close,"close"),o(or.prototype.enqueue,"enqueue"),o(or.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(or.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function Zs(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_controlledReadableStream")?!1:s instanceof or}function ts(s){if(!sf(s))return;if(s._pulling){s._pullAgain=!0;return}s._pulling=!0;let c=s._pullAlgorithm();E(c,()=>(s._pulling=!1,s._pullAgain&&(s._pullAgain=!1,ts(s)),null),m=>(kt(s,m),null))}function sf(s){let i=s._controlledReadableStream;return!hn(s)||!s._started?!1:!!(Ar(i)&&B(i)>0||va(s)>0)}function eo(s){s._pullAlgorithm=void 0,s._cancelAlgorithm=void 0,s._strategySizeAlgorithm=void 0}function Gr(s){if(!hn(s))return;let i=s._controlledReadableStream;s._closeRequested=!0,s._queue.length===0&&(eo(s),ns(i))}function dn(s,i){if(!hn(s))return;let c=s._controlledReadableStream;if(Ar(c)&&B(c)>0)k(c,i,!1);else{let m;try{m=s._strategySizeAlgorithm(i)}catch(A){throw kt(s,A),A}try{aa(s,i,m)}catch(A){throw kt(s,A),A}}ts(s)}function kt(s,i){let c=s._controlledReadableStream;c._state==="readable"&&(Cr(s),eo(s),cf(c,i))}function va(s){let i=s._controlledReadableStream._state;return i==="errored"?null:i==="closed"?0:s._strategyHWM-s._queueTotalSize}function cy(s){return!sf(s)}function hn(s){let i=s._controlledReadableStream._state;return!s._closeRequested&&i==="readable"}function of(s,i,c,m,A,I,U){i._controlledReadableStream=s,i._queue=void 0,i._queueTotalSize=void 0,Cr(i),i._started=!1,i._closeRequested=!1,i._pullAgain=!1,i._pulling=!1,i._strategySizeAlgorithm=U,i._strategyHWM=I,i._pullAlgorithm=m,i._cancelAlgorithm=A,s._readableStreamController=i;let V=c();E(h(V),()=>(i._started=!0,ts(i),null),ae=>(kt(i,ae),null))}function ly(s,i,c,m){let A=Object.create(or.prototype),I,U,V;i.start!==void 0?I=()=>i.start(A):I=()=>{},i.pull!==void 0?U=()=>i.pull(A):U=()=>h(void 0),i.cancel!==void 0?V=ae=>i.cancel(ae):V=()=>h(void 0),of(s,A,I,U,V,c,m)}function to(s){return new TypeError(`ReadableStreamDefaultController.prototype.${s} can only be used on a ReadableStreamDefaultController`)}function fy(s,i){return Lr(s._readableStreamController)?hy(s):dy(s)}function dy(s,i){let c=q(s),m=!1,A=!1,I=!1,U=!1,V,ae,te,ce,ge,Te=f(Qe=>{ge=Qe});function Ot(){return m?(A=!0,h(void 0)):(m=!0,Q(c,{_chunkSteps:rt=>{C(()=>{A=!1;let bt=rt,ar=rt;I||dn(te._readableStreamController,bt),U||dn(ce._readableStreamController,ar),m=!1,A&&Ot()})},_closeSteps:()=>{m=!1,I||Gr(te._readableStreamController),U||Gr(ce._readableStreamController),(!I||!U)&&ge(void 0)},_errorSteps:()=>{m=!1}}),h(void 0))}function mn(Qe){if(I=!0,V=Qe,U){let rt=Se([V,ae]),bt=Ft(s,rt);ge(bt)}return Te}function Sr(Qe){if(U=!0,ae=Qe,I){let rt=Se([V,ae]),bt=Ft(s,rt);ge(bt)}return Te}function ir(){}return te=rs(ir,Ot,mn),ce=rs(ir,Ot,Sr),v(c._closedPromise,Qe=>(kt(te._readableStreamController,Qe),kt(ce._readableStreamController,Qe),(!I||!U)&&ge(void 0),null)),[te,ce]}function hy(s){let i=q(s),c=!1,m=!1,A=!1,I=!1,U=!1,V,ae,te,ce,ge,Te=f(ne=>{ge=ne});function Ot(ne){v(ne._closedPromise,_e=>(ne!==i||(Ct(te._readableStreamController,_e),Ct(ce._readableStreamController,_e),(!I||!U)&&ge(void 0)),null))}function mn(){Mr(i)&&(ye(i),i=q(s),Ot(i)),Q(i,{_chunkSteps:_e=>{C(()=>{m=!1,A=!1;let Re=_e,ct=_e;if(!I&&!U)try{ct=Al(_e)}catch(gn){Ct(te._readableStreamController,gn),Ct(ce._readableStreamController,gn),ge(Ft(s,gn));return}I||Us(te._readableStreamController,Re),U||Us(ce._readableStreamController,ct),c=!1,m?ir():A&&Qe()})},_closeSteps:()=>{c=!1,I||Yn(te._readableStreamController),U||Yn(ce._readableStreamController),te._readableStreamController._pendingPullIntos.length>0&&Ms(te._readableStreamController,0),ce._readableStreamController._pendingPullIntos.length>0&&Ms(ce._readableStreamController,0),(!I||!U)&&ge(void 0)},_errorSteps:()=>{c=!1}})}function Sr(ne,_e){Y(i)&&(ye(i),i=Nl(s),Ot(i));let Re=_e?ce:te,ct=_e?te:ce;Ll(i,ne,1,{_chunkSteps:yn=>{C(()=>{m=!1,A=!1;let _n=_e?U:I;if(_e?I:U)_n||$s(Re._readableStreamController,yn);else{let wf;try{wf=Al(yn)}catch(Oa){Ct(Re._readableStreamController,Oa),Ct(ct._readableStreamController,Oa),ge(Ft(s,Oa));return}_n||$s(Re._readableStreamController,yn),Us(ct._readableStreamController,wf)}c=!1,m?ir():A&&Qe()})},_closeSteps:yn=>{c=!1;let _n=_e?U:I,co=_e?I:U;_n||Yn(Re._readableStreamController),co||Yn(ct._readableStreamController),yn!==void 0&&(_n||$s(Re._readableStreamController,yn),!co&&ct._readableStreamController._pendingPullIntos.length>0&&Ms(ct._readableStreamController,0)),(!_n||!co)&&ge(void 0)},_errorSteps:()=>{c=!1}})}function ir(){if(c)return m=!0,h(void 0);c=!0;let ne=da(te._readableStreamController);return ne===null?mn():Sr(ne._view,!1),h(void 0)}function Qe(){if(c)return A=!0,h(void 0);c=!0;let ne=da(ce._readableStreamController);return ne===null?mn():Sr(ne._view,!0),h(void 0)}function rt(ne){if(I=!0,V=ne,U){let _e=Se([V,ae]),Re=Ft(s,_e);ge(Re)}return Te}function bt(ne){if(U=!0,ae=ne,I){let _e=Se([V,ae]),Re=Ft(s,_e);ge(Re)}return Te}function ar(){}return te=uf(ar,ir,rt),ce=uf(ar,Qe,bt),Ot(i),[te,ce]}function py(s){return t(s)&&typeof s.getReader<"u"}function my(s){return py(s)?yy(s.getReader()):gy(s)}function gy(s){let i,c=wl(s,"async"),m=e;function A(){let U;try{U=ag(c)}catch(ae){return d(ae)}let V=h(U);return w(V,ae=>{if(!t(ae))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(ug(ae))Gr(i._readableStreamController);else{let ce=cg(ae);dn(i._readableStreamController,ce)}})}function I(U){let V=c.iterator,ae;try{ae=qs(V,"return")}catch(ge){return d(ge)}if(ae===void 0)return h(void 0);let te;try{te=R(ae,V,[U])}catch(ge){return d(ge)}let ce=h(te);return w(ce,ge=>{if(!t(ge))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return i=rs(m,A,I,0),i}function yy(s){let i,c=e;function m(){let I;try{I=s.read()}catch(U){return d(U)}return w(I,U=>{if(!t(U))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(U.done)Gr(i._readableStreamController);else{let V=U.value;dn(i._readableStreamController,V)}})}function A(I){try{return h(s.cancel(I))}catch(U){return d(U)}}return i=rs(c,m,A,0),i}function _y(s,i){pe(s,i);let c=s,m=c?.autoAllocateChunkSize,A=c?.cancel,I=c?.pull,U=c?.start,V=c?.type;return{autoAllocateChunkSize:m===void 0?void 0:T(m,`${i} has member 'autoAllocateChunkSize' that`),cancel:A===void 0?void 0:Cy(A,c,`${i} has member 'cancel' that`),pull:I===void 0?void 0:by(I,c,`${i} has member 'pull' that`),start:U===void 0?void 0:Ey(U,c,`${i} has member 'start' that`),type:V===void 0?void 0:wy(V,`${i} has member 'type' that`)}}function Cy(s,i,c){return Ee(s,c),m=>S(s,i,[m])}function by(s,i,c){return Ee(s,c),m=>S(s,i,[m])}function Ey(s,i,c){return Ee(s,c),m=>R(s,i,[m])}function wy(s,i){if(s=`${s}`,s!=="bytes")throw new TypeError(`${i} '${s}' is not a valid enumeration value for ReadableStreamType`);return s}function Ay(s,i){return pe(s,i),{preventCancel:!!s?.preventCancel}}function af(s,i){pe(s,i);let c=s?.preventAbort,m=s?.preventCancel,A=s?.preventClose,I=s?.signal;return I!==void 0&&Dy(I,`${i} has member 'signal' that`),{preventAbort:!!c,preventCancel:!!m,preventClose:!!A,signal:I}}function Dy(s,i){if(!Pg(s))throw new TypeError(`${i} is not an AbortSignal.`)}function Sy(s,i){pe(s,i);let c=s?.readable;p(c,"readable","ReadableWritablePair"),F(c,`${i} has member 'readable' that`);let m=s?.writable;return p(m,"writable","ReadableWritablePair"),Ml(m,`${i} has member 'writable' that`),{readable:c,writable:m}}class Ke{constructor(i={},c={}){i===void 0?i=null:xe(i,"First parameter");let m=Ws(c,"Second parameter"),A=_y(i,"First parameter");if(Ta(this),A.type==="bytes"){if(m.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let I=Qn(m,0);Cg(this,A,I)}else{let I=Gs(m),U=Qn(m,1);ly(this,A,U,I)}}get locked(){if(!wr(this))throw Wr("locked");return Ar(this)}cancel(i=void 0){return wr(this)?Ar(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):Ft(this,i):d(Wr("cancel"))}getReader(i=void 0){if(!wr(this))throw Wr("getReader");return Eg(i,"First parameter").mode===void 0?q(this):Nl(this)}pipeThrough(i,c={}){if(!wr(this))throw Wr("pipeThrough");Ne(i,1,"pipeThrough");let m=Sy(i,"First parameter"),A=af(c,"Second parameter");if(Ar(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(ln(m.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let I=nf(this,m.writable,A.preventClose,A.preventAbort,A.preventCancel,A.signal);return g(I),m.readable}pipeTo(i,c={}){if(!wr(this))return d(Wr("pipeTo"));if(i===void 0)return d("Parameter 1 is required in 'pipeTo'.");if(!cn(i))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let m;try{m=af(c,"Second parameter")}catch(A){return d(A)}return Ar(this)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):ln(i)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):nf(this,i,m.preventClose,m.preventAbort,m.preventCancel,m.signal)}tee(){if(!wr(this))throw Wr("tee");let i=fy(this);return Se(i)}values(i=void 0){if(!wr(this))throw Wr("values");let c=Ay(i,"First parameter");return sn(this,c.preventCancel)}[oa](i){return this.values(i)}static from(i){return my(i)}}Object.defineProperties(Ke,{from:{enumerable:!0}}),Object.defineProperties(Ke.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),o(Ke.from,"from"),o(Ke.prototype.cancel,"cancel"),o(Ke.prototype.getReader,"getReader"),o(Ke.prototype.pipeThrough,"pipeThrough"),o(Ke.prototype.pipeTo,"pipeTo"),o(Ke.prototype.tee,"tee"),o(Ke.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ke.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(Ke.prototype,oa,{value:Ke.prototype.values,writable:!0,configurable:!0});function rs(s,i,c,m=1,A=()=>1){let I=Object.create(Ke.prototype);Ta(I);let U=Object.create(or.prototype);return of(I,U,s,i,c,m,A),I}function uf(s,i,c){let m=Object.create(Ke.prototype);Ta(m);let A=Object.create(nr.prototype);return Il(m,A,s,i,c,0,void 0),m}function Ta(s){s._state="readable",s._reader=void 0,s._storedError=void 0,s._disturbed=!1}function wr(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_readableStreamController")?!1:s instanceof Ke}function Ar(s){return s._reader!==void 0}function Ft(s,i){if(s._disturbed=!0,s._state==="closed")return h(void 0);if(s._state==="errored")return d(s._storedError);ns(s);let c=s._reader;if(c!==void 0&&Mr(c)){let A=c._readIntoRequests;c._readIntoRequests=new j,A.forEach(I=>{I._closeSteps(void 0)})}let m=s._readableStreamController[K](i);return w(m,e)}function ns(s){s._state="closed";let i=s._reader;if(i!==void 0&&(oe(i),Y(i))){let c=i._readRequests;i._readRequests=new j,c.forEach(m=>{m._closeSteps()})}}function cf(s,i){s._state="errored",s._storedError=i;let c=s._reader;c!==void 0&&(J(c,i),Y(c)?Fe(c,i):Ul(c,i))}function Wr(s){return new TypeError(`ReadableStream.prototype.${s} can only be used on a ReadableStream`)}function lf(s,i){pe(s,i);let c=s?.highWaterMark;return p(c,"highWaterMark","QueuingStrategyInit"),{highWaterMark:y(c)}}let ff=s=>s.byteLength;o(ff,"size");class ro{constructor(i){Ne(i,1,"ByteLengthQueuingStrategy"),i=lf(i,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=i.highWaterMark}get highWaterMark(){if(!hf(this))throw df("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!hf(this))throw df("size");return ff}}Object.defineProperties(ro.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ro.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function df(s){return new TypeError(`ByteLengthQueuingStrategy.prototype.${s} can only be used on a ByteLengthQueuingStrategy`)}function hf(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_byteLengthQueuingStrategyHighWaterMark")?!1:s instanceof ro}let pf=()=>1;o(pf,"size");class no{constructor(i){Ne(i,1,"CountQueuingStrategy"),i=lf(i,"First parameter"),this._countQueuingStrategyHighWaterMark=i.highWaterMark}get highWaterMark(){if(!gf(this))throw mf("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!gf(this))throw mf("size");return pf}}Object.defineProperties(no.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(no.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function mf(s){return new TypeError(`CountQueuingStrategy.prototype.${s} can only be used on a CountQueuingStrategy`)}function gf(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_countQueuingStrategyHighWaterMark")?!1:s instanceof no}function vy(s,i){pe(s,i);let c=s?.cancel,m=s?.flush,A=s?.readableType,I=s?.start,U=s?.transform,V=s?.writableType;return{cancel:c===void 0?void 0:Fy(c,s,`${i} has member 'cancel' that`),flush:m===void 0?void 0:Ty(m,s,`${i} has member 'flush' that`),readableType:A,start:I===void 0?void 0:Ry(I,s,`${i} has member 'start' that`),transform:U===void 0?void 0:ky(U,s,`${i} has member 'transform' that`),writableType:V}}function Ty(s,i,c){return Ee(s,c),m=>S(s,i,[m])}function Ry(s,i,c){return Ee(s,c),m=>R(s,i,[m])}function ky(s,i,c){return Ee(s,c),(m,A)=>S(s,i,[m,A])}function Fy(s,i,c){return Ee(s,c),m=>S(s,i,[m])}class so{constructor(i={},c={},m={}){i===void 0&&(i=null);let A=Ws(c,"Second parameter"),I=Ws(m,"Third parameter"),U=vy(i,"First parameter");if(U.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(U.writableType!==void 0)throw new RangeError("Invalid writableType specified");let V=Qn(I,0),ae=Gs(I),te=Qn(A,1),ce=Gs(A),ge,Te=f(Ot=>{ge=Ot});Oy(this,Te,te,ce,V,ae),xy(this,U),U.start!==void 0?ge(U.start(this._transformStreamController)):ge(void 0)}get readable(){if(!yf(this))throw Ef("readable");return this._readable}get writable(){if(!yf(this))throw Ef("writable");return this._writable}}Object.defineProperties(so.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(so.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function Oy(s,i,c,m,A,I){function U(){return i}function V(Te){return Ny(s,Te)}function ae(Te){return qy(s,Te)}function te(){return jy(s)}s._writable=Ig(U,V,te,ae,c,m);function ce(){return Ly(s)}function ge(Te){return Uy(s,Te)}s._readable=rs(U,ce,ge,A,I),s._backpressure=void 0,s._backpressureChangePromise=void 0,s._backpressureChangePromise_resolve=void 0,oo(s,!0),s._transformStreamController=void 0}function yf(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_transformStreamController")?!1:s instanceof so}function _f(s,i){kt(s._readable._readableStreamController,i),Ra(s,i)}function Ra(s,i){ao(s._transformStreamController),Zn(s._writable._writableStreamController,i),ka(s)}function ka(s){s._backpressure&&oo(s,!1)}function oo(s,i){s._backpressureChangePromise!==void 0&&s._backpressureChangePromise_resolve(),s._backpressureChangePromise=f(c=>{s._backpressureChangePromise_resolve=c}),s._backpressure=i}class Dr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!io(this))throw uo("desiredSize");let i=this._controlledTransformStream._readable._readableStreamController;return va(i)}enqueue(i=void 0){if(!io(this))throw uo("enqueue");Cf(this,i)}error(i=void 0){if(!io(this))throw uo("error");By(this,i)}terminate(){if(!io(this))throw uo("terminate");Iy(this)}}Object.defineProperties(Dr.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),o(Dr.prototype.enqueue,"enqueue"),o(Dr.prototype.error,"error"),o(Dr.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Dr.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function io(s){return!t(s)||!Object.prototype.hasOwnProperty.call(s,"_controlledTransformStream")?!1:s instanceof Dr}function Py(s,i,c,m,A){i._controlledTransformStream=s,s._transformStreamController=i,i._transformAlgorithm=c,i._flushAlgorithm=m,i._cancelAlgorithm=A,i._finishPromise=void 0,i._finishPromise_resolve=void 0,i._finishPromise_reject=void 0}function xy(s,i){let c=Object.create(Dr.prototype),m,A,I;i.transform!==void 0?m=U=>i.transform(U,c):m=U=>{try{return Cf(c,U),h(void 0)}catch(V){return d(V)}},i.flush!==void 0?A=()=>i.flush(c):A=()=>h(void 0),i.cancel!==void 0?I=U=>i.cancel(U):I=()=>h(void 0),Py(s,c,m,A,I)}function ao(s){s._transformAlgorithm=void 0,s._flushAlgorithm=void 0,s._cancelAlgorithm=void 0}function Cf(s,i){let c=s._controlledTransformStream,m=c._readable._readableStreamController;if(!hn(m))throw new TypeError("Readable side is not in a state that permits enqueue");try{dn(m,i)}catch(I){throw Ra(c,I),c._readable._storedError}cy(m)!==c._backpressure&&oo(c,!0)}function By(s,i){_f(s._controlledTransformStream,i)}function bf(s,i){let c=s._transformAlgorithm(i);return w(c,void 0,m=>{throw _f(s._controlledTransformStream,m),m})}function Iy(s){let i=s._controlledTransformStream,c=i._readable._readableStreamController;Gr(c);let m=new TypeError("TransformStream terminated");Ra(i,m)}function Ny(s,i){let c=s._transformStreamController;if(s._backpressure){let m=s._backpressureChangePromise;return w(m,()=>{let A=s._writable;if(A._state==="erroring")throw A._storedError;return bf(c,i)})}return bf(c,i)}function qy(s,i){let c=s._transformStreamController;if(c._finishPromise!==void 0)return c._finishPromise;let m=s._readable;c._finishPromise=f((I,U)=>{c._finishPromise_resolve=I,c._finishPromise_reject=U});let A=c._cancelAlgorithm(i);return ao(c),E(A,()=>(m._state==="errored"?pn(c,m._storedError):(kt(m._readableStreamController,i),Fa(c)),null),I=>(kt(m._readableStreamController,I),pn(c,I),null)),c._finishPromise}function jy(s){let i=s._transformStreamController;if(i._finishPromise!==void 0)return i._finishPromise;let c=s._readable;i._finishPromise=f((A,I)=>{i._finishPromise_resolve=A,i._finishPromise_reject=I});let m=i._flushAlgorithm();return ao(i),E(m,()=>(c._state==="errored"?pn(i,c._storedError):(Gr(c._readableStreamController),Fa(i)),null),A=>(kt(c._readableStreamController,A),pn(i,A),null)),i._finishPromise}function Ly(s){return oo(s,!1),s._backpressureChangePromise}function Uy(s,i){let c=s._transformStreamController;if(c._finishPromise!==void 0)return c._finishPromise;let m=s._writable;c._finishPromise=f((I,U)=>{c._finishPromise_resolve=I,c._finishPromise_reject=U});let A=c._cancelAlgorithm(i);return ao(c),E(A,()=>(m._state==="errored"?pn(c,m._storedError):(Zn(m._writableStreamController,i),ka(s),Fa(c)),null),I=>(Zn(m._writableStreamController,I),ka(s),pn(c,I),null)),c._finishPromise}function uo(s){return new TypeError(`TransformStreamDefaultController.prototype.${s} can only be used on a TransformStreamDefaultController`)}function Fa(s){s._finishPromise_resolve!==void 0&&(s._finishPromise_resolve(),s._finishPromise_resolve=void 0,s._finishPromise_reject=void 0)}function pn(s,i){s._finishPromise_reject!==void 0&&(g(s._finishPromise),s._finishPromise_reject(i),s._finishPromise_resolve=void 0,s._finishPromise_reject=void 0)}function Ef(s){return new TypeError(`TransformStream.prototype.${s} can only be used on a TransformStream`)}r.ByteLengthQueuingStrategy=ro,r.CountQueuingStrategy=no,r.ReadableByteStreamController=nr,r.ReadableStream=Ke,r.ReadableStreamBYOBReader=br,r.ReadableStreamBYOBRequest=jr,r.ReadableStreamDefaultController=or,r.ReadableStreamDefaultReader=M,r.TransformStream=so,r.TransformStreamDefaultController=Dr,r.WritableStream=Er,r.WritableStreamDefaultController=fn,r.WritableStreamDefaultWriter=sr})});var xd=z(()=>{if(!globalThis.ReadableStream)try{let r=X("node:process"),{emitWarning:e}=r;try{r.emitWarning=()=>{},Object.assign(globalThis,X("node:stream/web")),r.emitWarning=e}catch(t){throw r.emitWarning=e,t}}catch{Object.assign(globalThis,Pd())}try{let{Blob:r}=X("buffer");r&&!r.prototype.stream&&(r.prototype.stream=function(t){let n=0,o=this;return new ReadableStream({type:"bytes",async pull(a){let l=await o.slice(n,Math.min(o.size,n+65536)).arrayBuffer();n+=l.byteLength,a.enqueue(new Uint8Array(l)),n===o.size&&a.close()}})})}catch{}});async function*ru(r,e=!0){for(let t of r)if("stream"in t)yield*t.stream();else if(ArrayBuffer.isView(t))if(e){let n=t.byteOffset,o=t.byteOffset+t.byteLength;for(;n!==o;){let a=Math.min(o-n,Bd),u=t.buffer.slice(n,n+a);n+=u.byteLength,yield new Uint8Array(u)}}else yield t;else{let n=0,o=t;for(;n!==o.size;){let u=await o.slice(n,Math.min(o.size,n+Bd)).arrayBuffer();n+=u.byteLength,yield new Uint8Array(u)}}}var iD,Bd,Id,m_,Bt,us=Me(()=>{iD=zr(xd(),1);Bd=65536;Id=class nu{#e=[];#t="";#r=0;#n="transparent";constructor(e=[],t={}){if(typeof e!="object"||e===null)throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if(typeof e[Symbol.iterator]!="function")throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if(typeof t!="object"&&typeof t!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");t===null&&(t={});let n=new TextEncoder;for(let a of e){let u;ArrayBuffer.isView(a)?u=new Uint8Array(a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength)):a instanceof ArrayBuffer?u=new Uint8Array(a.slice(0)):a instanceof nu?u=a:u=n.encode(`${a}`),this.#r+=ArrayBuffer.isView(u)?u.byteLength:u.size,this.#e.push(u)}this.#n=`${t.endings===void 0?"transparent":t.endings}`;let o=t.type===void 0?"":String(t.type);this.#t=/^[\x20-\x7E]*$/.test(o)?o:""}get size(){return this.#r}get type(){return this.#t}async text(){let e=new TextDecoder,t="";for await(let n of ru(this.#e,!1))t+=e.decode(n,{stream:!0});return t+=e.decode(),t}async arrayBuffer(){let e=new Uint8Array(this.size),t=0;for await(let n of ru(this.#e,!1))e.set(n,t),t+=n.length;return e.buffer}stream(){let e=ru(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(t){let n=await e.next();n.done?t.close():t.enqueue(n.value)},async cancel(){await e.return()}})}slice(e=0,t=this.size,n=""){let{size:o}=this,a=e<0?Math.max(o+e,0):Math.min(e,o),u=t<0?Math.max(o+t,0):Math.min(t,o),l=Math.max(u-a,0),f=this.#e,h=[],d=0;for(let E of f){if(d>=l)break;let P=ArrayBuffer.isView(E)?E.byteLength:E.size;if(a&&P<=a)a-=P,u-=P;else{let v;ArrayBuffer.isView(E)?(v=E.subarray(a,Math.min(P,u)),d+=v.byteLength):(v=E.slice(a,Math.min(P,u)),d+=v.size),u-=P,h.push(v),a=0}}let _=new nu([],{type:String(n).toLowerCase()});return _.#r=l,_.#e=h,_}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](e){return e&&typeof e=="object"&&typeof e.constructor=="function"&&(typeof e.stream=="function"||typeof e.arrayBuffer=="function")&&/^(Blob|File)$/.test(e[Symbol.toStringTag])}};Object.defineProperties(Id.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});m_=Id,Bt=m_});var g_,y_,Rr,su=Me(()=>{us();g_=class extends Bt{#e=0;#t="";constructor(e,t,n={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,n),n===null&&(n={});let o=n.lastModified===void 0?Date.now():Number(n.lastModified);Number.isNaN(o)||(this.#e=o),this.#t=String(t)}get name(){return this.#t}get lastModified(){return this.#e}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](e){return!!e&&e instanceof Bt&&/^(File)$/.test(e[Symbol.toStringTag])}},y_=g_,Rr=y_});function jd(r,e=Bt){var t=`${Nd()}${Nd()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),n=[],o=`--${t}\r +Content-Disposition: form-data; name="`;return r.forEach((a,u)=>typeof a=="string"?n.push(o+ou(u)+`"\r +\r +${a.replace(/\r(?!\n)|(?{us();su();({toStringTag:cs,iterator:__,hasInstance:C_}=Symbol),Nd=Math.random,b_="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),qd=(r,e,t)=>(r+="",/^(Blob|File)$/.test(e&&e[cs])?[(t=t!==void 0?t+"":e[cs]=="File"?e.name:"blob",r),e.name!==t||e[cs]=="blob"?new Rr([e],t,e):e]:[r,e+""]),ou=(r,e)=>(e?r:r.replace(/\r?\n|\r/g,`\r +`)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),Yr=(r,e,t)=>{if(e.lengthtypeof e[t]!="function")}append(...e){Yr("append",arguments,2),this.#e.push(qd(...e))}delete(e){Yr("delete",arguments,1),e+="",this.#e=this.#e.filter(([t])=>t!==e)}get(e){Yr("get",arguments,1),e+="";for(var t=this.#e,n=t.length,o=0;on[0]===e&&t.push(n[1])),t}has(e){return Yr("has",arguments,1),e+="",this.#e.some(t=>t[0]===e)}forEach(e,t){Yr("forEach",arguments,1);for(var[n,o]of this)e.call(t,o,n,this)}set(...e){Yr("set",arguments,2);var t=[],n=!0;e=qd(...e),this.#e.forEach(o=>{o[0]===e[0]?n&&(n=!t.push(e)):t.push(o)}),n&&t.push(e),this.#e=t}*entries(){yield*this.#e}*keys(){for(var[e]of this)yield e}*values(){for(var[,e]of this)yield e}}});var fr,No=Me(()=>{fr=class extends Error{constructor(e,t){super(e),Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}});var et,iu=Me(()=>{No();et=class extends fr{constructor(e,t,n){super(e,t),n&&(this.code=this.errno=n.code,this.erroredSysCall=n.syscall)}}});var qo,au,ls,Ld,Ud,Md,jo=Me(()=>{qo=Symbol.toStringTag,au=r=>typeof r=="object"&&typeof r.append=="function"&&typeof r.delete=="function"&&typeof r.get=="function"&&typeof r.getAll=="function"&&typeof r.has=="function"&&typeof r.set=="function"&&typeof r.sort=="function"&&r[qo]==="URLSearchParams",ls=r=>r&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&typeof r.constructor=="function"&&/^(Blob|File)$/.test(r[qo]),Ld=r=>typeof r=="object"&&(r[qo]==="AbortSignal"||r[qo]==="EventTarget"),Ud=(r,e)=>{let t=new URL(e).hostname,n=new URL(r).hostname;return t===n||t.endsWith(`.${n}`)},Md=(r,e)=>{let t=new URL(e).protocol,n=new URL(r).protocol;return t===n}});var Hd=z((CD,$d)=>{if(!globalThis.DOMException)try{let{MessageChannel:r}=X("worker_threads"),e=new r().port1,t=new ArrayBuffer;e.postMessage(t,[t,t])}catch(r){r.constructor.name==="DOMException"&&(globalThis.DOMException=r.constructor)}$d.exports=globalThis.DOMException});import{statSync as Gd,createReadStream as E_,promises as w_}from"node:fs";import{basename as A_}from"node:path";var Wd,uu,zd,Jd,Vd,Kd,Yd,Xd,Lo,cu=Me(()=>{Wd=zr(Hd(),1);su();us();({stat:uu}=w_),zd=(r,e)=>Yd(Gd(r),r,e),Jd=(r,e)=>uu(r).then(t=>Yd(t,r,e)),Vd=(r,e)=>uu(r).then(t=>Xd(t,r,e)),Kd=(r,e)=>Xd(Gd(r),r,e),Yd=(r,e,t="")=>new Bt([new Lo({path:e,size:r.size,lastModified:r.mtimeMs,start:0})],{type:t}),Xd=(r,e,t="")=>new Rr([new Lo({path:e,size:r.size,lastModified:r.mtimeMs,start:0})],A_(e),{type:t,lastModified:r.mtimeMs}),Lo=class r{#e;#t;constructor(e){this.#e=e.path,this.#t=e.start,this.size=e.size,this.lastModified=e.lastModified}slice(e,t){return new r({path:this.#e,lastModified:this.lastModified,size:t-e,start:this.#t+e})}async*stream(){let{mtimeMs:e}=await uu(this.#e);if(e>this.lastModified)throw new Wd.default("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.","NotReadableError");yield*E_(this.#e,{start:this.#t,end:this.#t+this.size-1})}get[Symbol.toStringTag](){return"Blob"}}});var Zd={};Af(Zd,{toFormData:()=>F_});function k_(r){let e=r.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let t=e[2]||e[3]||"",n=t.slice(t.lastIndexOf("\\")+1);return n=n.replace(/%22/g,'"'),n=n.replace(/&#(\d{4});/g,(o,a)=>String.fromCharCode(a)),n}async function F_(r,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let t=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!t)throw new TypeError("no or bad content-type header, no multipart boundary");let n=new lu(t[1]||t[2]),o,a,u,l,f,h,d=[],_=new kr,E=C=>{u+=g.decode(C,{stream:!0})},P=C=>{d.push(C)},v=()=>{let C=new Rr(d,h,{type:f});_.append(l,C)},w=()=>{_.append(l,u)},g=new TextDecoder("utf-8");g.decode(),n.onPartBegin=function(){n.onPartData=E,n.onPartEnd=w,o="",a="",u="",l="",f="",h=null,d.length=0},n.onHeaderField=function(C){o+=g.decode(C,{stream:!0})},n.onHeaderValue=function(C){a+=g.decode(C,{stream:!0})},n.onHeaderEnd=function(){if(a+=g.decode(),o=o.toLowerCase(),o==="content-disposition"){let C=a.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);C&&(l=C[2]||C[3]||""),h=k_(a),h&&(n.onPartData=P,n.onPartEnd=v)}else o==="content-type"&&(f=a);a="",o=""};for await(let C of r)n.write(C);return n.end(),_}var Wt,ke,Qd,Fr,Uo,Mo,D_,fs,S_,v_,T_,R_,Xr,lu,eh=Me(()=>{cu();Io();Wt=0,ke={START_BOUNDARY:Wt++,HEADER_FIELD_START:Wt++,HEADER_FIELD:Wt++,HEADER_VALUE_START:Wt++,HEADER_VALUE:Wt++,HEADER_VALUE_ALMOST_DONE:Wt++,HEADERS_ALMOST_DONE:Wt++,PART_DATA_START:Wt++,PART_DATA:Wt++,END:Wt++},Qd=1,Fr={PART_BOUNDARY:Qd,LAST_BOUNDARY:Qd*=2},Uo=10,Mo=13,D_=32,fs=45,S_=58,v_=97,T_=122,R_=r=>r|32,Xr=()=>{},lu=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=Xr,this.onHeaderField=Xr,this.onHeadersEnd=Xr,this.onHeaderValue=Xr,this.onPartBegin=Xr,this.onPartData=Xr,this.onPartEnd=Xr,this.boundaryChars={},e=`\r +--`+e;let t=new Uint8Array(e.length);for(let n=0;n{this[N+"Mark"]=t},C=N=>{delete this[N+"Mark"]},R=(N,j,L,H)=>{(j===void 0||j!==L)&&this[N](H&&H.subarray(j,L))},S=(N,j)=>{let L=N+"Mark";L in this&&(j?(R(N,this[L],t,e),delete this[L]):(R(N,this[L],e.length,e),this[L]=0))};for(t=0;tT_)return;break;case ke.HEADER_VALUE_START:if(v===D_)break;g("onHeaderValue"),h=ke.HEADER_VALUE;case ke.HEADER_VALUE:v===Mo&&(S("onHeaderValue",!0),R("onHeaderEnd"),h=ke.HEADER_VALUE_ALMOST_DONE);break;case ke.HEADER_VALUE_ALMOST_DONE:if(v!==Uo)return;h=ke.HEADER_FIELD_START;break;case ke.HEADERS_ALMOST_DONE:if(v!==Uo)return;R("onHeadersEnd"),h=ke.PART_DATA_START;break;case ke.PART_DATA_START:h=ke.PART_DATA,g("onPartData");case ke.PART_DATA:if(o=f,f===0){for(t+=E;t0)a[f-1]=v;else if(o>0){let N=new Uint8Array(a.buffer,a.byteOffset,a.byteLength);R("onPartData",0,o,N),o=0,g("onPartData"),t--}break;case ke.END:break;default:throw new Error(`Unexpected state entered: ${h}`)}S("onHeaderField"),S("onHeaderValue"),S("onPartData"),this.index=f,this.state=h,this.flags=d}end(){if(this.state===ke.HEADER_FIELD_START&&this.index===0||this.state===ke.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==ke.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}});import Or,{PassThrough as th}from"node:stream";import{types as rh,deprecate as du,promisify as O_}from"node:util";import{Buffer as At}from"node:buffer";async function fu(r){if(r[it].disturbed)throw new TypeError(`body used already for: ${r.url}`);if(r[it].disturbed=!0,r[it].error)throw r[it].error;let{body:e}=r;if(e===null)return At.alloc(0);if(!(e instanceof Or))return At.alloc(0);let t=[],n=0;try{for await(let o of e){if(r.size>0&&n+o.length>r.size){let a=new et(`content size at ${r.url} over limit: ${r.size}`,"max-size");throw e.destroy(a),a}n+=o.length,t.push(o)}}catch(o){throw o instanceof fr?o:new et(`Invalid response body while trying to fetch ${r.url}: ${o.message}`,"system",o)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return t.every(o=>typeof o=="string")?At.from(t.join("")):At.concat(t,n)}catch(o){throw new et(`Could not create Buffer from response body for ${r.url}: ${o.message}`,"system",o)}else throw new et(`Premature close of server response while trying to fetch ${r.url}`)}var P_,it,zt,Sn,x_,$o,nh,sh,Ho=Me(()=>{us();Io();iu();No();jo();P_=O_(Or.pipeline),it=Symbol("Body internals"),zt=class{constructor(e,{size:t=0}={}){let n=null;e===null?e=null:au(e)?e=At.from(e.toString()):ls(e)||At.isBuffer(e)||(rh.isAnyArrayBuffer(e)?e=At.from(e):ArrayBuffer.isView(e)?e=At.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Or||(e instanceof kr?(e=jd(e),n=e.type.split("=")[1]):e=At.from(String(e))));let o=e;At.isBuffer(e)?o=Or.Readable.from(e):ls(e)&&(o=Or.Readable.from(e.stream())),this[it]={body:e,stream:o,boundary:n,disturbed:!1,error:null},this.size=t,e instanceof Or&&e.on("error",a=>{let u=a instanceof fr?a:new et(`Invalid response body while trying to fetch ${this.url}: ${a.message}`,"system",a);this[it].error=u})}get body(){return this[it].stream}get bodyUsed(){return this[it].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:t,byteLength:n}=await fu(this);return e.slice(t,t+n)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let n=new kr,o=new URLSearchParams(await this.text());for(let[a,u]of o)n.append(a,u);return n}let{toFormData:t}=await Promise.resolve().then(()=>(eh(),Zd));return t(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[it].body&&this[it].body.type||"",t=await this.arrayBuffer();return new Bt([t],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await fu(this);return new TextDecoder().decode(e)}buffer(){return fu(this)}};zt.prototype.buffer=du(zt.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer");Object.defineProperties(zt.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:du(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});Sn=(r,e)=>{let t,n,{body:o}=r[it];if(r.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof Or&&typeof o.getBoundary!="function"&&(t=new th({highWaterMark:e}),n=new th({highWaterMark:e}),o.pipe(t),o.pipe(n),r[it].stream=t,o=n),o},x_=du(r=>r.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),$o=(r,e)=>r===null?null:typeof r=="string"?"text/plain;charset=UTF-8":au(r)?"application/x-www-form-urlencoded;charset=UTF-8":ls(r)?r.type||null:At.isBuffer(r)||rh.isAnyArrayBuffer(r)||ArrayBuffer.isView(r)?null:r instanceof kr?`multipart/form-data; boundary=${e[it].boundary}`:r&&typeof r.getBoundary=="function"?`multipart/form-data;boundary=${x_(r)}`:r instanceof Or?null:"text/plain;charset=UTF-8",nh=r=>{let{body:e}=r[it];return e===null?0:ls(e)?e.size:At.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},sh=async(r,{body:e})=>{e===null?r.end():await P_(e,r)}});import{types as oh}from"node:util";import Wo from"node:http";function ih(r=[]){return new at(r.reduce((e,t,n,o)=>(n%2===0&&e.push(o.slice(n,n+2)),e),[]).filter(([e,t])=>{try{return Go(e),hu(e,String(t)),!0}catch{return!1}}))}var Go,hu,at,zo=Me(()=>{Go=typeof Wo.validateHeaderName=="function"?Wo.validateHeaderName:r=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(r)){let e=new TypeError(`Header name must be a valid HTTP token [${r}]`);throw Object.defineProperty(e,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),e}},hu=typeof Wo.validateHeaderValue=="function"?Wo.validateHeaderValue:(r,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let t=new TypeError(`Invalid character in header content ["${r}"]`);throw Object.defineProperty(t,"code",{value:"ERR_INVALID_CHAR"}),t}},at=class r extends URLSearchParams{constructor(e){let t=[];if(e instanceof r){let n=e.raw();for(let[o,a]of Object.entries(n))t.push(...a.map(u=>[o,u]))}else if(e!=null)if(typeof e=="object"&&!oh.isBoxedPrimitive(e)){let n=e[Symbol.iterator];if(n==null)t.push(...Object.entries(e));else{if(typeof n!="function")throw new TypeError("Header pairs must be iterable");t=[...e].map(o=>{if(typeof o!="object"||oh.isBoxedPrimitive(o))throw new TypeError("Each header pair must be an iterable object");return[...o]}).map(o=>{if(o.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return[...o]})}}else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence> or record)");return t=t.length>0?t.map(([n,o])=>(Go(n),hu(n,String(o)),[String(n).toLowerCase(),String(o)])):void 0,super(t),new Proxy(this,{get(n,o,a){switch(o){case"append":case"set":return(u,l)=>(Go(u),hu(u,String(l)),URLSearchParams.prototype[o].call(n,String(u).toLowerCase(),String(l)));case"delete":case"has":case"getAll":return u=>(Go(u),URLSearchParams.prototype[o].call(n,String(u).toLowerCase()));case"keys":return()=>(n.sort(),new Set(URLSearchParams.prototype.keys.call(n)).keys());default:return Reflect.get(n,o,a)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let t=this.getAll(e);if(t.length===0)return null;let n=t.join(", ");return/^content-encoding$/i.test(e)&&(n=n.toLowerCase()),n}forEach(e,t=void 0){for(let n of this.keys())Reflect.apply(e,t,[this.get(n),n,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,t)=>(e[t]=this.getAll(t),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,t)=>{let n=this.getAll(t);return t==="host"?e[t]=n[0]:e[t]=n.length>1?n:n[0],e},{})}};Object.defineProperties(at.prototype,["get","entries","forEach","values"].reduce((r,e)=>(r[e]={enumerable:!0},r),{}))});var B_,ds,pu=Me(()=>{B_=new Set([301,302,303,307,308]),ds=r=>B_.has(r)});var It,ft,ah=Me(()=>{zo();Ho();pu();It=Symbol("Response internals"),ft=class r extends zt{constructor(e=null,t={}){super(e,t);let n=t.status!=null?t.status:200,o=new at(t.headers);if(e!==null&&!o.has("Content-Type")){let a=$o(e,this);a&&o.append("Content-Type",a)}this[It]={type:"default",url:t.url,status:n,statusText:t.statusText||"",headers:o,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[It].type}get url(){return this[It].url||""}get status(){return this[It].status}get ok(){return this[It].status>=200&&this[It].status<300}get redirected(){return this[It].counter>0}get statusText(){return this[It].statusText}get headers(){return this[It].headers}get highWaterMark(){return this[It].highWaterMark}clone(){return new r(Sn(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,t=302){if(!ds(t))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new r(null,{headers:{location:new URL(e).toString()},status:t})}static error(){let e=new r(null,{status:0,statusText:""});return e[It].type="error",e}static json(e=void 0,t={}){let n=JSON.stringify(e);if(n===void 0)throw new TypeError("data is not JSON serializable");let o=new at(t&&t.headers);return o.has("content-type")||o.set("content-type","application/json"),new r(n,{...t,headers:o})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(ft.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}})});var uh,ch=Me(()=>{uh=r=>{if(r.search)return r.search;let e=r.href.length-1,t=r.hash||(r.href[e]==="#"?"#":"");return r.href[e-t.length]==="?"?"?":""}});import{isIP as I_}from"node:net";function lh(r,e=!1){return r==null||(r=new URL(r),/^(about|blob|data):$/.test(r.protocol))?"no-referrer":(r.username="",r.password="",r.hash="",e&&(r.pathname="",r.search=""),r)}function hh(r){if(!fh.has(r))throw new TypeError(`Invalid referrerPolicy: ${r}`);return r}function N_(r){if(/^(http|ws)s:$/.test(r.protocol))return!0;let e=r.host.replace(/(^\[)|(]$)/g,""),t=I_(e);return t===4&&/^127\./.test(e)||t===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:r.host==="localhost"||r.host.endsWith(".localhost")?!1:r.protocol==="file:"}function vn(r){return/^about:(blank|srcdoc)$/.test(r)||r.protocol==="data:"||/^(blob|filesystem):$/.test(r.protocol)?!0:N_(r)}function ph(r,{referrerURLCallback:e,referrerOriginCallback:t}={}){if(r.referrer==="no-referrer"||r.referrerPolicy==="")return null;let n=r.referrerPolicy;if(r.referrer==="about:client")return"no-referrer";let o=r.referrer,a=lh(o),u=lh(o,!0);a.toString().length>4096&&(a=u),e&&(a=e(a)),t&&(u=t(u));let l=new URL(r.url);switch(n){case"no-referrer":return"no-referrer";case"origin":return u;case"unsafe-url":return a;case"strict-origin":return vn(a)&&!vn(l)?"no-referrer":u.toString();case"strict-origin-when-cross-origin":return a.origin===l.origin?a:vn(a)&&!vn(l)?"no-referrer":u;case"same-origin":return a.origin===l.origin?a:"no-referrer";case"origin-when-cross-origin":return a.origin===l.origin?a:u;case"no-referrer-when-downgrade":return vn(a)&&!vn(l)?"no-referrer":a;default:throw new TypeError(`Invalid referrerPolicy: ${n}`)}}function mh(r){let e=(r.get("referrer-policy")||"").split(/[,\s]+/),t="";for(let n of e)n&&fh.has(n)&&(t=n);return t}var fh,dh,mu=Me(()=>{fh=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),dh="strict-origin-when-cross-origin"});import{format as q_}from"node:url";import{deprecate as j_}from"node:util";var We,hs,L_,Pr,gh,yh=Me(()=>{zo();Ho();jo();ch();mu();We=Symbol("Request internals"),hs=r=>typeof r=="object"&&typeof r[We]=="object",L_=j_(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),Pr=class r extends zt{constructor(e,t={}){let n;if(hs(e)?n=new URL(e.url):(n=new URL(e),e={}),n.username!==""||n.password!=="")throw new TypeError(`${n} is an url with embedded credentials.`);let o=t.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),!hs(t)&&"data"in t&&L_(),(t.body!=null||hs(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let a=t.body?t.body:hs(e)&&e.body!==null?Sn(e):null;super(a,{size:t.size||e.size||0});let u=new at(t.headers||e.headers||{});if(a!==null&&!u.has("Content-Type")){let h=$o(a,this);h&&u.set("Content-Type",h)}let l=hs(e)?e.signal:null;if("signal"in t&&(l=t.signal),l!=null&&!Ld(l))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let f=t.referrer==null?e.referrer:t.referrer;if(f==="")f="no-referrer";else if(f){let h=new URL(f);f=/^about:(\/\/)?client$/.test(h)?"client":h}else f=void 0;this[We]={method:o,redirect:t.redirect||e.redirect||"follow",headers:u,parsedURL:n,signal:l,referrer:f},this.follow=t.follow===void 0?e.follow===void 0?20:e.follow:t.follow,this.compress=t.compress===void 0?e.compress===void 0?!0:e.compress:t.compress,this.counter=t.counter||e.counter||0,this.agent=t.agent||e.agent,this.highWaterMark=t.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=t.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=t.referrerPolicy||e.referrerPolicy||""}get method(){return this[We].method}get url(){return q_(this[We].parsedURL)}get headers(){return this[We].headers}get redirect(){return this[We].redirect}get signal(){return this[We].signal}get referrer(){if(this[We].referrer==="no-referrer")return"";if(this[We].referrer==="client")return"about:client";if(this[We].referrer)return this[We].referrer.toString()}get referrerPolicy(){return this[We].referrerPolicy}set referrerPolicy(e){this[We].referrerPolicy=hh(e)}clone(){return new r(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(Pr.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});gh=r=>{let{parsedURL:e}=r[We],t=new at(r[We].headers);t.has("Accept")||t.set("Accept","*/*");let n=null;if(r.body===null&&/^(post|put)$/i.test(r.method)&&(n="0"),r.body!==null){let l=nh(r);typeof l=="number"&&!Number.isNaN(l)&&(n=String(l))}n&&t.set("Content-Length",n),r.referrerPolicy===""&&(r.referrerPolicy=dh),r.referrer&&r.referrer!=="no-referrer"?r[We].referrer=ph(r):r[We].referrer="no-referrer",r[We].referrer instanceof URL&&t.set("Referer",r.referrer),t.has("User-Agent")||t.set("User-Agent","node-fetch"),r.compress&&!t.has("Accept-Encoding")&&t.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=r;typeof o=="function"&&(o=o(e));let a=uh(e),u={path:e.pathname+a,method:r.method,headers:t[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:r.insecureHTTPParser,agent:o};return{parsedURL:e,options:u}}});var ps,_h=Me(()=>{No();ps=class extends fr{constructor(e,t="aborted"){super(e,t)}}});var Eh={};Af(Eh,{AbortError:()=>ps,Blob:()=>Bt,FetchError:()=>et,File:()=>Rr,FormData:()=>kr,Headers:()=>at,Request:()=>Pr,Response:()=>ft,blobFrom:()=>Jd,blobFromSync:()=>zd,default:()=>gu,fileFrom:()=>Vd,fileFromSync:()=>Kd,isRedirect:()=>ds});import U_ from"node:http";import M_ from"node:https";import Tn from"node:zlib";import Ch,{PassThrough as bh,pipeline as Rn}from"node:stream";import{Buffer as Jo}from"node:buffer";async function gu(r,e){return new Promise((t,n)=>{let o=new Pr(r,e),{parsedURL:a,options:u}=gh(o);if(!$_.has(a.protocol))throw new TypeError(`node-fetch cannot load ${r}. URL scheme "${a.protocol.replace(/:$/,"")}" is not supported.`);if(a.protocol==="data:"){let v=kd(o.url),w=new ft(v,{headers:{"Content-Type":v.typeFull}});t(w);return}let l=(a.protocol==="https:"?M_:U_).request,{signal:f}=o,h=null,d=()=>{let v=new ps("The operation was aborted.");n(v),o.body&&o.body instanceof Ch.Readable&&o.body.destroy(v),!(!h||!h.body)&&h.body.emit("error",v)};if(f&&f.aborted){d();return}let _=()=>{d(),P()},E=l(a.toString(),u);f&&f.addEventListener("abort",_);let P=()=>{E.abort(),f&&f.removeEventListener("abort",_)};E.on("error",v=>{n(new et(`request to ${o.url} failed, reason: ${v.message}`,"system",v)),P()}),H_(E,v=>{h&&h.body&&h.body.destroy(v)}),process.version<"v14"&&E.on("socket",v=>{let w;v.prependListener("end",()=>{w=v._eventsCount}),v.prependListener("close",g=>{if(h&&w{E.setTimeout(0);let w=ih(v.rawHeaders);if(ds(v.statusCode)){let N=w.get("Location"),j=null;try{j=N===null?null:new URL(N,o.url)}catch{if(o.redirect!=="manual"){n(new et(`uri requested responds with an invalid redirect URL: ${N}`,"invalid-redirect")),P();return}}switch(o.redirect){case"error":n(new et(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),P();return;case"manual":break;case"follow":{if(j===null)break;if(o.counter>=o.follow){n(new et(`maximum redirect reached at: ${o.url}`,"max-redirect")),P();return}let L={headers:new at(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:Sn(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!Ud(o.url,j)||!Md(o.url,j))for(let K of["authorization","www-authenticate","cookie","cookie2"])L.headers.delete(K);if(v.statusCode!==303&&o.body&&e.body instanceof Ch.Readable){n(new et("Cannot follow redirect with body being a readable stream","unsupported-redirect")),P();return}(v.statusCode===303||(v.statusCode===301||v.statusCode===302)&&o.method==="POST")&&(L.method="GET",L.body=void 0,L.headers.delete("content-length"));let H=mh(w);H&&(L.referrerPolicy=H),t(gu(new Pr(j,L))),P();return}default:return n(new TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}f&&v.once("end",()=>{f.removeEventListener("abort",_)});let g=Rn(v,new bh,N=>{N&&n(N)});process.version<"v12.10"&&v.on("aborted",_);let C={url:o.url,status:v.statusCode,statusText:v.statusMessage,headers:w,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},R=w.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||R===null||v.statusCode===204||v.statusCode===304){h=new ft(g,C),t(h);return}let S={flush:Tn.Z_SYNC_FLUSH,finishFlush:Tn.Z_SYNC_FLUSH};if(R==="gzip"||R==="x-gzip"){g=Rn(g,Tn.createGunzip(S),N=>{N&&n(N)}),h=new ft(g,C),t(h);return}if(R==="deflate"||R==="x-deflate"){let N=Rn(v,new bh,j=>{j&&n(j)});N.once("data",j=>{(j[0]&15)===8?g=Rn(g,Tn.createInflate(),L=>{L&&n(L)}):g=Rn(g,Tn.createInflateRaw(),L=>{L&&n(L)}),h=new ft(g,C),t(h)}),N.once("end",()=>{h||(h=new ft(g,C),t(h))});return}if(R==="br"){g=Rn(g,Tn.createBrotliDecompress(),N=>{N&&n(N)}),h=new ft(g,C),t(h);return}h=new ft(g,C),t(h)}),sh(E,o).catch(n)})}function H_(r,e){let t=Jo.from(`0\r +\r +`),n=!1,o=!1,a;r.on("response",u=>{let{headers:l}=u;n=l["transfer-encoding"]==="chunked"&&!l["content-length"]}),r.on("socket",u=>{let l=()=>{if(n&&!o){let h=new Error("Premature close");h.code="ERR_STREAM_PREMATURE_CLOSE",e(h)}},f=h=>{o=Jo.compare(h.slice(-5),t)===0,!o&&a&&(o=Jo.compare(a.slice(-3),t.slice(0,3))===0&&Jo.compare(h.slice(-2),t.slice(3))===0),a=h};u.prependListener("close",l),u.on("data",f),r.on("close",()=>{u.removeListener("close",l),u.removeListener("data",f)})})}var $_,wh=Me(()=>{Fd();Ho();ah();zo();yh();iu();_h();pu();Io();jo();mu();cu();$_=new Set(["data:","http:","https:"])});var Sh=z(Fn=>{"use strict";var G_=Fn&&Fn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},kn;Object.defineProperty(Fn,"__esModule",{value:!0});Fn.Gaxios=void 0;var W_=G_(Ga()),z_=X("https"),Qr=Ja(),J_=sd(),Ah=X("stream"),Dh=Ya(),V_=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),Vo=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new Dh.GaxiosInterceptorManager,response:new Dh.GaxiosInterceptorManager}}fetch(...e){let t=e[0],n=e[1],o,a=new Headers;return typeof t=="string"?o=new URL(t):t instanceof URL?o=t:t&&t.url&&(o=new URL(t.url)),t&&typeof t=="object"&&"headers"in t&&kn.mergeHeaders(a,t.headers),n&&kn.mergeHeaders(a,new Headers(n.headers)),typeof t=="object"&&!(t instanceof URL)?this.request({...n,...t,headers:a,url:o}):this.request({...n,headers:a,url:o})}async request(e={}){let t=await this.#n(e);return t=await this.#t(t),this.#r(this._request(t))}async _defaultAdapter(e){let t=e.fetchImplementation||this.defaults.fetchImplementation||await kn.#u(),n={...e};delete n.data;let o=await t(e.url,n),a=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:a}}),Object.assign(o,{config:e,data:a})}async _request(e){try{let t;if(e.adapter?t=await e.adapter(e,this._defaultAdapter.bind(this)):t=await this._defaultAdapter(e),!e.validateStatus(t.status)){if(e.responseType==="stream"){let o=[];for await(let a of e.data??[])o.push(a);t.data=o}let n=Qr.GaxiosError.extractAPIErrorFromResponse(t,`Request failed with status code ${t.status}`);throw new Qr.GaxiosError(n?.message,e,t,n)}return t}catch(t){let n;t instanceof Qr.GaxiosError?n=t:t instanceof Error?n=new Qr.GaxiosError(t.message,e,void 0,t):n=new Qr.GaxiosError("Unexpected Gaxios Error",e,void 0,t);let{shouldRetry:o,config:a}=await(0,J_.getRetryConfig)(n);if(o&&a)return n.config.retryConfig.currentRetryAttempt=a.retryConfig.currentRetryAttempt,e.retryConfig=n.config?.retryConfig,this.#s(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(n),n}}async getResponseData(e,t){if(e.maxContentLength&&t.headers.has("content-length")&&e.maxContentLength=200&&e<300}async getResponseDataFromContentType(e){let t=e.headers.get("Content-Type");if(t===null)return e.text();if(t=t.toLowerCase(),t.includes("application/json")){let n=await e.text();try{n=JSON.parse(n)}catch{}return n}else return t.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,t){let n=`--${t}--`;for(let o of e){let a=o.headers.get("Content-Type")||"application/octet-stream";yield`--${t}\r +Content-Type: ${a}\r +\r +`,typeof o.content=="string"?yield o.content:yield*o.content,yield`\r +`}yield n}static#o;static#i;static async#a(){return this.#o||=(await Promise.resolve().then(()=>zr(Rd()))).HttpsProxyAgent,this.#o}static async#u(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(wh(),Eh))).default,this.#i}static mergeHeaders(e,...t){e=e instanceof Headers?e:new Headers(e);for(let n of t)(n instanceof Headers?n:new Headers(n)).forEach((a,u)=>{u==="set-cookie"?e.append(u,a):e.set(u,a)});return e}};Fn.Gaxios=Vo;kn=Vo});var Je=z(tt=>{"use strict";var K_=tt&&tt.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),Y_=tt&&tt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&K_(e,r,t)};Object.defineProperty(tt,"__esModule",{value:!0});tt.instance=tt.Gaxios=tt.GaxiosError=void 0;tt.request=Q_;var vh=Sh();Object.defineProperty(tt,"Gaxios",{enumerable:!0,get:function(){return vh.Gaxios}});var X_=Ja();Object.defineProperty(tt,"GaxiosError",{enumerable:!0,get:function(){return X_.GaxiosError}});Y_(Ya(),tt);tt.instance=new vh.Gaxios;async function Q_(r){return tt.instance.request(r)}});var yu=z((Th,Ko)=>{(function(r){"use strict";var e,t=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,n=Math.ceil,o=Math.floor,a="[BigNumber Error] ",u=a+"Number primitive has more than 15 significant digits: ",l=1e14,f=14,h=9007199254740991,d=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],_=1e7,E=1e9;function P(j){var L,H,K,W=G.prototype={constructor:G,toString:null,valueOf:null},Ae=new G(1),he=20,fe=4,ye=-7,re=21,de=-1e7,Z=1e7,ue=!1,J=1,se=0,oe={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},Ie="0123456789abcdefghijklmnopqrstuvwxyz",je=!0;function G(p,y){var b,x,T,F,q,D,k,B,O=this;if(!(O instanceof G))return new G(p,y);if(y==null){if(p&&p._isBigNumber===!0){O.s=p.s,!p.c||p.e>Z?O.c=O.e=null:p.e=10;q/=10,F++);F>Z?O.c=O.e=null:(O.e=F,O.c=[p]);return}B=String(p)}else{if(!t.test(B=String(p)))return K(O,B,D);O.s=B.charCodeAt(0)==45?(B=B.slice(1),-1):1}(F=B.indexOf("."))>-1&&(B=B.replace(".","")),(q=B.search(/e/i))>0?(F<0&&(F=q),F+=+B.slice(q+1),B=B.substring(0,q)):F<0&&(F=B.length)}else{if(C(y,2,Ie.length,"Base"),y==10&&je)return O=new G(p),xe(O,he+O.e+1,fe);if(B=String(p),D=typeof p=="number"){if(p*0!=0)return K(O,B,D,y);if(O.s=1/p<0?(B=B.slice(1),-1):1,G.DEBUG&&B.replace(/^0\.0*|\./,"").length>15)throw Error(u+p)}else O.s=B.charCodeAt(0)===45?(B=B.slice(1),-1):1;for(b=Ie.slice(0,y),F=q=0,k=B.length;qF){F=k;continue}}else if(!T&&(B==B.toUpperCase()&&(B=B.toLowerCase())||B==B.toLowerCase()&&(B=B.toUpperCase()))){T=!0,q=-1,F=0;continue}return K(O,String(p),D,y)}D=!1,B=H(B,y,10,O.s),(F=B.indexOf("."))>-1?B=B.replace(".",""):F=B.length}for(q=0;B.charCodeAt(q)===48;q++);for(k=B.length;B.charCodeAt(--k)===48;);if(B=B.slice(q,++k)){if(k-=q,D&&G.DEBUG&&k>15&&(p>h||p!==o(p)))throw Error(u+O.s*p);if((F=F-q-1)>Z)O.c=O.e=null;else if(F=-E&&T<=E&&T===o(T)){if(x[0]===0){if(T===0&&x.length===1)return!0;break e}if(y=(T+1)%f,y<1&&(y+=f),String(x[0]).length==y){for(y=0;y=l||b!==o(b))break e;if(b!==0)return!0}}}else if(x===null&&T===null&&(F===null||F===1||F===-1))return!0;throw Error(a+"Invalid BigNumber: "+p)},G.maximum=G.max=function(){return Ee(arguments,-1)},G.minimum=G.min=function(){return Ee(arguments,1)},G.random=function(){var p=9007199254740992,y=Math.random()*p&2097151?function(){return o(Math.random()*p)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(b){var x,T,F,q,D,k=0,B=[],O=new G(Ae);if(b==null?b=he:C(b,0,E),q=n(b/f),ue)if(crypto.getRandomValues){for(x=crypto.getRandomValues(new Uint32Array(q*=2));k>>11),D>=9e15?(T=crypto.getRandomValues(new Uint32Array(2)),x[k]=T[0],x[k+1]=T[1]):(B.push(D%1e14),k+=2);k=q/2}else if(crypto.randomBytes){for(x=crypto.randomBytes(q*=7);k=9e15?crypto.randomBytes(7).copy(x,k):(B.push(D%1e14),k+=7);k=q/7}else throw ue=!1,Error(a+"crypto unavailable");if(!ue)for(;k=10;D/=10,k++);kT-1&&(D[q+1]==null&&(D[q+1]=0),D[q+1]+=D[q]/T|0,D[q]%=T)}return D.reverse()}return function(b,x,T,F,q){var D,k,B,O,M,Y,Q,we,Fe=b.indexOf("."),Be=he,be=fe;for(Fe>=0&&(O=se,se=0,b=b.replace(".",""),we=new G(x),Y=we.pow(b.length-Fe),se=O,we.c=y(N(w(Y.c),Y.e,"0"),10,T,p),we.e=we.c.length),Q=y(b,x,T,q?(D=Ie,p):(D=p,Ie)),B=O=Q.length;Q[--O]==0;Q.pop());if(!Q[0])return D.charAt(0);if(Fe<0?--B:(Y.c=Q,Y.e=B,Y.s=F,Y=L(Y,we,Be,be,T),Q=Y.c,M=Y.r,B=Y.e),k=B+Be+1,Fe=Q[k],O=T/2,M=M||k<0||Q[k+1]!=null,M=be<4?(Fe!=null||M)&&(be==0||be==(Y.s<0?3:2)):Fe>O||Fe==O&&(be==4||M||be==6&&Q[k-1]&1||be==(Y.s<0?8:7)),k<1||!Q[0])b=M?N(D.charAt(1),-Be,D.charAt(0)):D.charAt(0);else{if(Q.length=k,M)for(--T;++Q[--k]>T;)Q[k]=0,k||(++B,Q=[1].concat(Q));for(O=Q.length;!Q[--O];);for(Fe=0,b="";Fe<=O;b+=D.charAt(Q[Fe++]));b=N(b,B,D.charAt(0))}return b}}(),L=function(){function p(x,T,F){var q,D,k,B,O=0,M=x.length,Y=T%_,Q=T/_|0;for(x=x.slice();M--;)k=x[M]%_,B=x[M]/_|0,q=Q*k+B*Y,D=Y*k+q%_*_+O,O=(D/F|0)+(q/_|0)+Q*B,x[M]=D%F;return O&&(x=[O].concat(x)),x}function y(x,T,F,q){var D,k;if(F!=q)k=F>q?1:-1;else for(D=k=0;DT[D]?1:-1;break}return k}function b(x,T,F,q){for(var D=0;F--;)x[F]-=D,D=x[F]1;x.splice(0,1));}return function(x,T,F,q,D){var k,B,O,M,Y,Q,we,Fe,Be,be,De,Le,sn,on,an,ut,tr,Ve=x.s==T.s?1:-1,Ue=x.c,Se=T.c;if(!Ue||!Ue[0]||!Se||!Se[0])return new G(!x.s||!T.s||(Ue?Se&&Ue[0]==Se[0]:!Se)?NaN:Ue&&Ue[0]==0||!Se?Ve*0:Ve/0);for(Fe=new G(Ve),Be=Fe.c=[],B=x.e-T.e,Ve=F+B+1,D||(D=l,B=v(x.e/f)-v(T.e/f),Ve=Ve/f|0),O=0;Se[O]==(Ue[O]||0);O++);if(Se[O]>(Ue[O]||0)&&B--,Ve<0)Be.push(1),M=!0;else{for(on=Ue.length,ut=Se.length,O=0,Ve+=2,Y=o(D/(Se[0]+1)),Y>1&&(Se=p(Se,Y,D),Ue=p(Ue,Y,D),ut=Se.length,on=Ue.length),sn=ut,be=Ue.slice(0,ut),De=be.length;De=D/2&&an++;do{if(Y=0,k=y(Se,be,ut,De),k<0){if(Le=be[0],ut!=De&&(Le=Le*D+(be[1]||0)),Y=o(Le/an),Y>1)for(Y>=D&&(Y=D-1),Q=p(Se,Y,D),we=Q.length,De=be.length;y(Q,be,we,De)==1;)Y--,b(Q,ut=10;Ve/=10,O++);xe(Fe,F+(Fe.e=O+B*f-1)+1,q,M)}else Fe.e=B,Fe.r=+M;return Fe}}();function pe(p,y,b,x){var T,F,q,D,k;if(b==null?b=fe:C(b,0,8),!p.c)return p.toString();if(T=p.c[0],q=p.e,y==null)k=w(p.c),k=x==1||x==2&&(q<=ye||q>=re)?S(k,q):N(k,q,"0");else if(p=xe(new G(p),y,b),F=p.e,k=w(p.c),D=k.length,x==1||x==2&&(y<=F||F<=ye)){for(;Dq),k=N(k,F,"0"),F+1>D){if(--y>0)for(k+=".";y--;k+="0");}else if(y+=F-D,y>0)for(F+1==D&&(k+=".");y--;k+="0");return p.s<0&&T?"-"+k:k}function Ee(p,y){for(var b,x,T=1,F=new G(p[0]);T=10;T/=10,x++);return(b=x+b*f-1)>Z?p.c=p.e=null:b=10;D/=10,T++);if(F=y-T,F<0)F+=f,q=y,k=M[B=0],O=o(k/Y[T-q-1]%10);else if(B=n((F+1)/f),B>=M.length)if(x){for(;M.length<=B;M.push(0));k=O=0,T=1,F%=f,q=F-f+1}else break e;else{for(k=D=M[B],T=1;D>=10;D/=10,T++);F%=f,q=F-f+T,O=q<0?0:o(k/Y[T-q-1]%10)}if(x=x||y<0||M[B+1]!=null||(q<0?k:k%Y[T-q-1]),x=b<4?(O||x)&&(b==0||b==(p.s<0?3:2)):O>5||O==5&&(b==4||x||b==6&&(F>0?q>0?k/Y[T-q]:0:M[B-1])%10&1||b==(p.s<0?8:7)),y<1||!M[0])return M.length=0,x?(y-=p.e+1,M[0]=Y[(f-y%f)%f],p.e=-y||0):M[0]=p.e=0,p;if(F==0?(M.length=B,D=1,B--):(M.length=B+1,D=Y[f-F],M[B]=q>0?o(k/Y[T-q]%Y[q])*D:0),x)for(;;)if(B==0){for(F=1,q=M[0];q>=10;q/=10,F++);for(q=M[0]+=D,D=1;q>=10;q/=10,D++);F!=D&&(p.e++,M[0]==l&&(M[0]=1));break}else{if(M[B]+=D,M[B]!=l)break;M[B--]=0,D=1}for(F=M.length;M[--F]===0;M.pop());}p.e>Z?p.c=p.e=null:p.e=re?S(y,b):N(y,b,"0"),p.s<0?"-"+y:y)}return W.absoluteValue=W.abs=function(){var p=new G(this);return p.s<0&&(p.s=1),p},W.comparedTo=function(p,y){return g(this,new G(p,y))},W.decimalPlaces=W.dp=function(p,y){var b,x,T,F=this;if(p!=null)return C(p,0,E),y==null?y=fe:C(y,0,8),xe(new G(F),p+F.e+1,y);if(!(b=F.c))return null;if(x=((T=b.length-1)-v(this.e/f))*f,T=b[T])for(;T%10==0;T/=10,x--);return x<0&&(x=0),x},W.dividedBy=W.div=function(p,y){return L(this,new G(p,y),he,fe)},W.dividedToIntegerBy=W.idiv=function(p,y){return L(this,new G(p,y),0,1)},W.exponentiatedBy=W.pow=function(p,y){var b,x,T,F,q,D,k,B,O,M=this;if(p=new G(p),p.c&&!p.isInteger())throw Error(a+"Exponent not an integer: "+Ne(p));if(y!=null&&(y=new G(y)),D=p.e>14,!M.c||!M.c[0]||M.c[0]==1&&!M.e&&M.c.length==1||!p.c||!p.c[0])return O=new G(Math.pow(+Ne(M),D?p.s*(2-R(p)):+Ne(p))),y?O.mod(y):O;if(k=p.s<0,y){if(y.c?!y.c[0]:!y.s)return new G(NaN);x=!k&&M.isInteger()&&y.isInteger(),x&&(M=M.mod(y))}else{if(p.e>9&&(M.e>0||M.e<-1||(M.e==0?M.c[0]>1||D&&M.c[1]>=24e7:M.c[0]<8e13||D&&M.c[0]<=9999975e7)))return F=M.s<0&&R(p)?-0:0,M.e>-1&&(F=1/F),new G(k?1/F:F);se&&(F=n(se/f+2))}for(D?(b=new G(.5),k&&(p.s=1),B=R(p)):(T=Math.abs(+Ne(p)),B=T%2),O=new G(Ae);;){if(B){if(O=O.times(M),!O.c)break;F?O.c.length>F&&(O.c.length=F):x&&(O=O.mod(y))}if(T){if(T=o(T/2),T===0)break;B=T%2}else if(p=p.times(b),xe(p,p.e+1,1),p.e>14)B=R(p);else{if(T=+Ne(p),T===0)break;B=T%2}M=M.times(M),F?M.c&&M.c.length>F&&(M.c.length=F):x&&(M=M.mod(y))}return x?O:(k&&(O=Ae.div(O)),y?O.mod(y):F?xe(O,se,fe,q):O)},W.integerValue=function(p){var y=new G(this);return p==null?p=fe:C(p,0,8),xe(y,y.e+1,p)},W.isEqualTo=W.eq=function(p,y){return g(this,new G(p,y))===0},W.isFinite=function(){return!!this.c},W.isGreaterThan=W.gt=function(p,y){return g(this,new G(p,y))>0},W.isGreaterThanOrEqualTo=W.gte=function(p,y){return(y=g(this,new G(p,y)))===1||y===0},W.isInteger=function(){return!!this.c&&v(this.e/f)>this.c.length-2},W.isLessThan=W.lt=function(p,y){return g(this,new G(p,y))<0},W.isLessThanOrEqualTo=W.lte=function(p,y){return(y=g(this,new G(p,y)))===-1||y===0},W.isNaN=function(){return!this.s},W.isNegative=function(){return this.s<0},W.isPositive=function(){return this.s>0},W.isZero=function(){return!!this.c&&this.c[0]==0},W.minus=function(p,y){var b,x,T,F,q=this,D=q.s;if(p=new G(p,y),y=p.s,!D||!y)return new G(NaN);if(D!=y)return p.s=-y,q.plus(p);var k=q.e/f,B=p.e/f,O=q.c,M=p.c;if(!k||!B){if(!O||!M)return O?(p.s=-y,p):new G(M?q:NaN);if(!O[0]||!M[0])return M[0]?(p.s=-y,p):new G(O[0]?q:fe==3?-0:0)}if(k=v(k),B=v(B),O=O.slice(),D=k-B){for((F=D<0)?(D=-D,T=O):(B=k,T=M),T.reverse(),y=D;y--;T.push(0));T.reverse()}else for(x=(F=(D=O.length)<(y=M.length))?D:y,D=y=0;y0)for(;y--;O[b++]=0);for(y=l-1;x>D;){if(O[--x]=0;){for(b=0,Y=Le[T]%Be,Q=Le[T]/Be|0,q=k,F=T+q;F>T;)B=De[--q]%Be,O=De[q]/Be|0,D=Q*B+O*Y,B=Y*B+D%Be*Be+we[F]+b,b=(B/Fe|0)+(D/Be|0)+Q*O,we[F--]=B%Fe;we[F]=b}return b?++x:we.splice(0,1),er(p,we,x)},W.negated=function(){var p=new G(this);return p.s=-p.s||null,p},W.plus=function(p,y){var b,x=this,T=x.s;if(p=new G(p,y),y=p.s,!T||!y)return new G(NaN);if(T!=y)return p.s=-y,x.minus(p);var F=x.e/f,q=p.e/f,D=x.c,k=p.c;if(!F||!q){if(!D||!k)return new G(T/0);if(!D[0]||!k[0])return k[0]?p:new G(D[0]?x:T*0)}if(F=v(F),q=v(q),D=D.slice(),T=F-q){for(T>0?(q=F,b=k):(T=-T,b=D),b.reverse();T--;b.push(0));b.reverse()}for(T=D.length,y=k.length,T-y<0&&(b=k,k=D,D=b,y=T),T=0;y;)T=(D[--y]=D[y]+k[y]+T)/l|0,D[y]=l===D[y]?0:D[y]%l;return T&&(D=[T].concat(D),++q),er(p,D,q)},W.precision=W.sd=function(p,y){var b,x,T,F=this;if(p!=null&&p!==!!p)return C(p,1,E),y==null?y=fe:C(y,0,8),xe(new G(F),p,y);if(!(b=F.c))return null;if(T=b.length-1,x=T*f+1,T=b[T]){for(;T%10==0;T/=10,x--);for(T=b[0];T>=10;T/=10,x++);}return p&&F.e+1>x&&(x=F.e+1),x},W.shiftedBy=function(p){return C(p,-h,h),this.times("1e"+p)},W.squareRoot=W.sqrt=function(){var p,y,b,x,T,F=this,q=F.c,D=F.s,k=F.e,B=he+4,O=new G("0.5");if(D!==1||!q||!q[0])return new G(!D||D<0&&(!q||q[0])?NaN:q?F:1/0);if(D=Math.sqrt(+Ne(F)),D==0||D==1/0?(y=w(q),(y.length+k)%2==0&&(y+="0"),D=Math.sqrt(+y),k=v((k+1)/2)-(k<0||k%2),D==1/0?y="5e"+k:(y=D.toExponential(),y=y.slice(0,y.indexOf("e")+1)+k),b=new G(y)):b=new G(D+""),b.c[0]){for(k=b.e,D=k+B,D<3&&(D=0);;)if(T=b,b=O.times(T.plus(L(F,T,B,1))),w(T.c).slice(0,D)===(y=w(b.c)).slice(0,D))if(b.e0&&we>0){for(F=we%D||D,O=Q.substr(0,F);F0&&(O+=B+Q.slice(F)),Y&&(O="-"+O)}x=M?O+(b.decimalSeparator||"")+((k=+b.fractionGroupSize)?M.replace(new RegExp("\\d{"+k+"}\\B","g"),"$&"+(b.fractionGroupSeparator||"")):M):O}return(b.prefix||"")+x+(b.suffix||"")},W.toFraction=function(p){var y,b,x,T,F,q,D,k,B,O,M,Y,Q=this,we=Q.c;if(p!=null&&(D=new G(p),!D.isInteger()&&(D.c||D.s!==1)||D.lt(Ae)))throw Error(a+"Argument "+(D.isInteger()?"out of range: ":"not an integer: ")+Ne(D));if(!we)return new G(Q);for(y=new G(Ae),B=b=new G(Ae),x=k=new G(Ae),Y=w(we),F=y.e=Y.length-Q.e-1,y.c[0]=d[(q=F%f)<0?f+q:q],p=!p||D.comparedTo(y)>0?F>0?y:B:D,q=Z,Z=1/0,D=new G(Y),k.c[0]=0;O=L(D,y,0,1),T=b.plus(O.times(x)),T.comparedTo(p)!=1;)b=x,x=T,B=k.plus(O.times(T=B)),k=T,y=D.minus(O.times(T=y)),D=T;return T=L(p.minus(b),x,0,1),k=k.plus(T.times(B)),b=b.plus(T.times(x)),k.s=B.s=Q.s,F=F*2,M=L(B,x,F,fe).minus(Q).abs().comparedTo(L(k,b,F,fe).minus(Q).abs())<1?[B,x]:[k,b],Z=q,M},W.toNumber=function(){return+Ne(this)},W.toPrecision=function(p,y){return p!=null&&C(p,1,E),pe(this,p,y,2)},W.toString=function(p){var y,b=this,x=b.s,T=b.e;return T===null?x?(y="Infinity",x<0&&(y="-"+y)):y="NaN":(p==null?y=T<=ye||T>=re?S(w(b.c),T):N(w(b.c),T,"0"):p===10&&je?(b=xe(new G(b),he+T+1,fe),y=N(w(b.c),b.e,"0")):(C(p,2,Ie.length,"Base"),y=H(N(w(b.c),T,"0"),10,p,x,!0)),x<0&&b.c[0]&&(y="-"+y)),y},W.valueOf=W.toJSON=function(){return Ne(this)},W._isBigNumber=!0,j!=null&&G.set(j),G}function v(j){var L=j|0;return j>0||j===L?L:L-1}function w(j){for(var L,H,K=1,W=j.length,Ae=j[0]+"";Kre^H?1:-1;for(fe=(ye=W.length)<(re=Ae.length)?ye:re,he=0;heAe[he]^H?1:-1;return ye==re?0:ye>re^H?1:-1}function C(j,L,H,K){if(jH||j!==o(j))throw Error(a+(K||"Argument")+(typeof j=="number"?jH?" out of range: ":" not an integer: ":" not a primitive number: ")+String(j))}function R(j){var L=j.c.length-1;return v(j.e/f)==L&&j.c[L]%2!=0}function S(j,L){return(j.length>1?j.charAt(0)+"."+j.slice(1):j)+(L<0?"e":"e+")+L}function N(j,L,H){var K,W;if(L<0){for(W=H+".";++L;W+=H);j=W+j}else if(K=j.length,++L>K){for(W=H,L-=K;--L;W+=H);j+=W}else L{var Rh=yu(),kh=Fh.exports;(function(){"use strict";function r(h){return h<10?"0"+h:h}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,t=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n,o,a={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},u;function l(h){return t.lastIndex=0,t.test(h)?'"'+h.replace(t,function(d){var _=a[d];return typeof _=="string"?_:"\\u"+("0000"+d.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+h+'"'}function f(h,d){var _,E,P,v,w=n,g,C=d[h],R=C!=null&&(C instanceof Rh||Rh.isBigNumber(C));switch(C&&typeof C=="object"&&typeof C.toJSON=="function"&&(C=C.toJSON(h)),typeof u=="function"&&(C=u.call(d,h,C)),typeof C){case"string":return R?C:l(C);case"number":return isFinite(C)?String(C):"null";case"boolean":case"null":case"bigint":return String(C);case"object":if(!C)return"null";if(n+=o,g=[],Object.prototype.toString.apply(C)==="[object Array]"){for(v=C.length,_=0;_{var Yo=null,Z_=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,eC=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/,tC=function(r){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(r!=null){if(r.strict===!0&&(e.strict=!0),r.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=r.alwaysParseAsBig===!0?r.alwaysParseAsBig:!1,e.useNativeBigInt=r.useNativeBigInt===!0?r.useNativeBigInt:!1,typeof r.constructorAction<"u")if(r.constructorAction==="error"||r.constructorAction==="ignore"||r.constructorAction==="preserve")e.constructorAction=r.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${r.constructorAction}`);if(typeof r.protoAction<"u")if(r.protoAction==="error"||r.protoAction==="ignore"||r.protoAction==="preserve")e.protoAction=r.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${r.protoAction}`)}var t,n,o={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:` +`,r:"\r",t:" "},a,u=function(w){throw{name:"SyntaxError",message:w,at:t,text:a}},l=function(w){return w&&w!==n&&u("Expected '"+w+"' instead of '"+n+"'"),n=a.charAt(t),t+=1,n},f=function(){var w,g="";for(n==="-"&&(g="-",l("-"));n>="0"&&n<="9";)g+=n,l();if(n===".")for(g+=".";l()&&n>="0"&&n<="9";)g+=n;if(n==="e"||n==="E")for(g+=n,l(),(n==="-"||n==="+")&&(g+=n,l());n>="0"&&n<="9";)g+=n,l();if(w=+g,!isFinite(w))u("Bad number");else return Yo==null&&(Yo=yu()),g.length>15?e.storeAsString?g:e.useNativeBigInt?BigInt(g):new Yo(g):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(w):new Yo(w):w},h=function(){var w,g,C="",R;if(n==='"')for(var S=t;l();){if(n==='"')return t-1>S&&(C+=a.substring(S,t-1)),l(),C;if(n==="\\"){if(t-1>S&&(C+=a.substring(S,t-1)),l(),n==="u"){for(R=0,g=0;g<4&&(w=parseInt(l(),16),!!isFinite(w));g+=1)R=R*16+w;C+=String.fromCharCode(R)}else if(typeof o[n]=="string")C+=o[n];else break;S=t}}u("Bad string")},d=function(){for(;n&&n<=" ";)l()},_=function(){switch(n){case"t":return l("t"),l("r"),l("u"),l("e"),!0;case"f":return l("f"),l("a"),l("l"),l("s"),l("e"),!1;case"n":return l("n"),l("u"),l("l"),l("l"),null}u("Unexpected '"+n+"'")},E,P=function(){var w=[];if(n==="["){if(l("["),d(),n==="]")return l("]"),w;for(;n;){if(w.push(E()),d(),n==="]")return l("]"),w;l(","),d()}}u("Bad array")},v=function(){var w,g=Object.create(null);if(n==="{"){if(l("{"),d(),n==="}")return l("}"),g;for(;n;){if(w=h(),d(),l(":"),e.strict===!0&&Object.hasOwnProperty.call(g,w)&&u('Duplicate key "'+w+'"'),Z_.test(w)===!0?e.protoAction==="error"?u("Object contains forbidden prototype property"):e.protoAction==="ignore"?E():g[w]=E():eC.test(w)===!0?e.constructorAction==="error"?u("Object contains forbidden constructor property"):e.constructorAction==="ignore"?E():g[w]=E():g[w]=E(),d(),n==="}")return l("}"),g;l(","),d()}}u("Bad object")};return E=function(){switch(d(),n){case"{":return v();case"[":return P();case'"':return h();case"-":return f();default:return n>="0"&&n<="9"?f():_()}},function(w,g){var C;return a=w+"",t=0,n=" ",C=E(),d(),n&&u("Syntax error"),typeof g=="function"?function R(S,N){var j,L,H=S[N];return H&&typeof H=="object"&&Object.keys(H).forEach(function(K){L=R(H,K),L!==void 0?H[K]=L:delete H[K]}),g.call(S,N,H)}({"":C},""):C}};Ph.exports=tC});var Nh=z((DS,Xo)=>{var Bh=Oh().stringify,Ih=xh();Xo.exports=function(r){return{parse:Ih(r),stringify:Bh}};Xo.exports.parse=Ih();Xo.exports.stringify=Bh});var _u=z(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.GCE_LINUX_BIOS_PATHS=void 0;Nt.isGoogleCloudServerless=Lh;Nt.isGoogleComputeEngineLinux=Uh;Nt.isGoogleComputeEngineMACAddress=Mh;Nt.isGoogleComputeEngine=$h;Nt.detectGCPResidency=nC;var qh=X("fs"),jh=X("os");Nt.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var rC=/^42:01/;function Lh(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function Uh(){if((0,jh.platform)()!=="linux")return!1;try{(0,qh.statSync)(Nt.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let r=(0,qh.readFileSync)(Nt.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(r)}catch{return!1}}function Mh(){let r=(0,jh.networkInterfaces)();for(let e of Object.values(r))if(e){for(let{mac:t}of e)if(rC.test(t))return!0}return!1}function $h(){return Uh()||Mh()}function nC(){return Lh()||$h()}});var Hh=z(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.Colours=void 0;var Xe=class r{static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth=="function"?e.getColorDepth()>2:!0)}static refresh(){r.enabled=r.isEnabled(process==null?void 0:process.stderr),this.enabled?(r.reset="\x1B[0m",r.bright="\x1B[1m",r.dim="\x1B[2m",r.red="\x1B[31m",r.green="\x1B[32m",r.yellow="\x1B[33m",r.blue="\x1B[34m",r.magenta="\x1B[35m",r.cyan="\x1B[36m",r.white="\x1B[37m",r.grey="\x1B[90m"):(r.reset="",r.bright="",r.dim="",r.red="",r.green="",r.yellow="",r.blue="",r.magenta="",r.cyan="",r.white="",r.grey="")}};Qo.Colours=Xe;Xe.enabled=!1;Xe.reset="";Xe.bright="";Xe.dim="";Xe.red="";Xe.green="";Xe.yellow="";Xe.blue="";Xe.magenta="";Xe.cyan="";Xe.white="";Xe.grey="";Xe.refresh()});var Jh=z(ve=>{"use strict";var sC=ve&&ve.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),oC=ve&&ve.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),Gh=ve&&ve.__importStar||function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(n[n.length]=o);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),o=0;othis.on(n,o)}),this.func.debug=(...n)=>this.invokeSeverity(qt.DEBUG,...n),this.func.info=(...n)=>this.invokeSeverity(qt.INFO,...n),this.func.warn=(...n)=>this.invokeSeverity(qt.WARNING,...n),this.func.error=(...n)=>this.invokeSeverity(qt.ERROR,...n),this.func.sublog=n=>zh(n,this.func)}invoke(e,...t){if(this.upstream)try{this.upstream(e,...t)}catch{}try{this.emit("log",e,t)}catch{}}invokeSeverity(e,...t){this.invoke({severity:e},...t)}};ve.AdhocDebugLogger=gs;ve.placeholder=new gs("",()=>{}).func;var On=class{constructor(){var e;this.cached=new Map,this.filters=[],this.filtersSet=!1;let t=(e=ms.env[ve.env.nodeEnables])!==null&&e!==void 0?e:"*";t==="all"&&(t="*"),this.filters=t.split(",")}log(e,t,...n){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let o=this.cached.get(e);o||(o=this.makeLogger(e),this.cached.set(e,o)),o(t,...n)}catch(o){console.error(o)}}};ve.DebugLogBackendBase=On;var Cu=class extends On{constructor(){super(...arguments),this.enabledRegexp=/.*/g}isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(t,...n)=>{var o;let a=`${dt.Colours.green}${e}${dt.Colours.reset}`,u=`${dt.Colours.yellow}${ms.pid}${dt.Colours.reset}`,l;switch(t.severity){case qt.ERROR:l=`${dt.Colours.red}${t.severity}${dt.Colours.reset}`;break;case qt.INFO:l=`${dt.Colours.magenta}${t.severity}${dt.Colours.reset}`;break;case qt.WARNING:l=`${dt.Colours.yellow}${t.severity}${dt.Colours.reset}`;break;default:l=(o=t.severity)!==null&&o!==void 0?o:qt.DEFAULT;break}let f=Wh.formatWithOptions({colors:dt.Colours.enabled},...n),h=Object.assign({},t);delete h.severity;let d=Object.getOwnPropertyNames(h).length?JSON.stringify(h):"",_=d?`${dt.Colours.grey}${d}${dt.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",u,a,l,f,d?` ${_}`:"")}:()=>{}}setFilters(){let t=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${t}$`,"i")}};function bu(){return new Cu}var Eu=class extends On{constructor(e){super(),this.debugPkg=e}makeLogger(e){let t=this.debugPkg(e);return(n,...o)=>{t(o[0],...o.slice(1))}}setFilters(){var e;let t=(e=ms.env.NODE_DEBUG)!==null&&e!==void 0?e:"";ms.env.NODE_DEBUG=`${t}${t?",":""}${this.filters.join(",")}`}};function aC(r){return new Eu(r)}var wu=class extends On{constructor(e){var t;super(),this.upstream=(t=e)!==null&&t!==void 0?t:void 0}makeLogger(e){var t;let n=(t=this.upstream)===null||t===void 0?void 0:t.makeLogger(e);return(o,...a)=>{var u;let l=(u=o.severity)!==null&&u!==void 0?u:qt.INFO,f=Object.assign({severity:l,message:Wh.format(...a)},o),h=JSON.stringify(f);n?n(o,h):console.log("%s",h)}}setFilters(){var e;(e=this.upstream)===null||e===void 0||e.setFilters()}};function uC(r){return new wu(r)}ve.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var Au=new Map,ht;function cC(r){ht=r,Au.clear()}function zh(r,e){if(!ht&&!ms.env[ve.env.nodeEnables]||!r)return ve.placeholder;e&&(r=`${e.instance.namespace}:${r}`);let t=Au.get(r);if(t)return t.func;if(ht===null)return ve.placeholder;ht===void 0&&(ht=bu());let n=(()=>{let o;return new gs(r,(u,...l)=>{if(o!==ht){if(ht===null)return;ht===void 0&&(ht=bu()),o=ht}ht?.log(r,u,...l)})})();return Au.set(r,n),n.func}});var Du=z(Zr=>{"use strict";var lC=Zr&&Zr.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),fC=Zr&&Zr.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&lC(e,r,t)};Object.defineProperty(Zr,"__esModule",{value:!0});fC(Jh(),Zr)});var _s=z(ie=>{"use strict";var Kh=ie&&ie.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),dC=ie&&ie.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),hC=ie&&ie.__importStar||function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(n[n.length]=o);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),o=0;o{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}})}async function ys(r,e={},t=3,n=!1){let o=new Headers(ie.HEADERS),a="",u={};if(typeof r=="object"){let _=r;new Headers(_.headers).forEach((E,P)=>o.set(P,E)),a=_.metadataKey,u=_.params||u,t=_.noResponseRetries||t,n=_.fastFail||n}else a=r;typeof e=="string"?a+=`/${e}`:(_C(e),e.property&&(a+=`/${e.property}`),new Headers(e.headers).forEach((_,E)=>o.set(E,_)),u=e.params||u);let l=n?CC:Su.request,f={url:`${vu()}/${a}`,headers:o,retryConfig:{noResponseRetries:t},params:u,responseType:"text",timeout:Xh()};Vh.info("instance request %j",f);let h=await l(f);Vh.info("instance metadata is %s",h.data);let d=h.headers.get(ie.HEADER_NAME);if(d!==ie.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${ie.HEADER_NAME} header. Expected '${ie.HEADER_VALUE}', got ${d?`'${d}'`:"no header"}`);if(typeof h.data=="string")try{return mC.parse(h.data)}catch{}return h.data}async function CC(r){let e={...r,url:r.url?.toString().replace(vu(),vu(ie.SECONDARY_HOST_ADDRESS))},t=(0,Su.request)(r),n=(0,Su.request)(e);return Promise.any([t,n])}function bC(r){return ys("instance",r)}function EC(r){return ys("project",r)}function wC(r){return ys("universe",r)}async function AC(r){let e={};return await Promise.all(r.map(t=>(async()=>{let n=await ys(t),o=t.metadataKey;e[o]=n})())),e}function DC(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var Zo;async function SC(){if(process.env.METADATA_SERVER_DETECTION){let r=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(r in ie.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${r}\`, but it should be \`${Object.keys(ie.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(r){case"assume-present":return!0;case"none":return!1;case"bios-only":return Tu();case"ping-only":}}try{return Zo===void 0&&(Zo=ys("instance",void 0,DC(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST))),await Zo,!0}catch(r){let e=r;if(process.env.DEBUG_AUTH&&console.info(e),e.type==="request-timeout"||e.response&&e.response.status===404)return!1;if(!(e.response&&e.response.status===404)&&(!e.code||!["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(e.code.toString()))){let t="UNKNOWN";e.code&&(t=e.code.toString()),process.emitWarning(`received unexpected error = ${e.message} code = ${t}`,"MetadataLookupWarning")}return!1}}function vC(){Zo=void 0}ie.gcpResidencyCache=null;function Tu(){return ie.gcpResidencyCache===null&&Yh(),ie.gcpResidencyCache}function Yh(r=null){ie.gcpResidencyCache=r!==null?r:(0,gC.detectGCPResidency)()}function Xh(){return Tu()?0:3e3}pC(_u(),ie)});var ep=z(ei=>{"use strict";ei.byteLength=RC;ei.toByteArray=FC;ei.fromByteArray=xC;var Jt=[],Dt=[],TC=typeof Uint8Array<"u"?Uint8Array:Array,Ru="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(en=0,Qh=Ru.length;en0)throw new Error("Invalid string. Length must be a multiple of 4");var t=r.indexOf("=");t===-1&&(t=e);var n=t===e?0:4-t%4;return[t,n]}function RC(r){var e=Zh(r),t=e[0],n=e[1];return(t+n)*3/4-n}function kC(r,e,t){return(e+t)*3/4-t}function FC(r){var e,t=Zh(r),n=t[0],o=t[1],a=new TC(kC(r,n,o)),u=0,l=o>0?n-4:n,f;for(f=0;f>16&255,a[u++]=e>>8&255,a[u++]=e&255;return o===2&&(e=Dt[r.charCodeAt(f)]<<2|Dt[r.charCodeAt(f+1)]>>4,a[u++]=e&255),o===1&&(e=Dt[r.charCodeAt(f)]<<10|Dt[r.charCodeAt(f+1)]<<4|Dt[r.charCodeAt(f+2)]>>2,a[u++]=e>>8&255,a[u++]=e&255),a}function OC(r){return Jt[r>>18&63]+Jt[r>>12&63]+Jt[r>>6&63]+Jt[r&63]}function PC(r,e,t){for(var n,o=[],a=e;al?l:u+a));return n===1?(e=r[t-1],o.push(Jt[e>>2]+Jt[e<<4&63]+"==")):n===2&&(e=(r[t-2]<<8)+r[t-1],o.push(Jt[e>>10]+Jt[e>>4&63]+Jt[e<<2&63]+"=")),o.join("")}});var Fu=z(ku=>{"use strict";Object.defineProperty(ku,"__esModule",{value:!0});ku.fromArrayBufferToHex=BC;function BC(r){return Array.from(new Uint8Array(r)).map(t=>t.toString(16).padStart(2,"0")).join("")}});var tp=z(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.BrowserCrypto=void 0;var Pn=ep(),IC=Fu(),Ou=class r{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let t=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",t);return Pn.fromByteArray(new Uint8Array(n))}randomBytesBase64(e){let t=new Uint8Array(e);return window.crypto.getRandomValues(t),Pn.fromByteArray(t)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,t,n){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},a=new TextEncoder().encode(t),u=Pn.toByteArray(r.padBase64(n)),l=await window.crypto.subtle.importKey("jwk",e,o,!0,["verify"]);return await window.crypto.subtle.verify(o,l,u,a)}async sign(e,t){let n={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(t),a=await window.crypto.subtle.importKey("jwk",e,n,!0,["sign"]),u=await window.crypto.subtle.sign(n,a,o);return Pn.fromByteArray(new Uint8Array(u))}decodeBase64StringUtf8(e){let t=Pn.toByteArray(r.padBase64(e));return new TextDecoder().decode(t)}encodeBase64StringUtf8(e){let t=new TextEncoder().encode(e);return Pn.fromByteArray(t)}async sha256DigestHex(e){let t=new TextEncoder().encode(e),n=await window.crypto.subtle.digest("SHA-256",t);return(0,IC.fromArrayBufferToHex)(n)}async signWithHmacSha256(e,t){let n=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),o=new TextEncoder,a=await window.crypto.subtle.importKey("raw",o.encode(n),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",a,o.encode(t))}};ti.BrowserCrypto=Ou});var rp=z(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});ri.NodeCrypto=void 0;var xn=X("crypto"),Pu=class{async sha256DigestBase64(e){return xn.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return xn.randomBytes(e).toString("base64")}async verify(e,t,n){let o=xn.createVerify("RSA-SHA256");return o.update(t),o.end(),o.verify(e,n,"base64")}async sign(e,t){let n=xn.createSign("RSA-SHA256");return n.update(t),n.end(),n.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return xn.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,t){let n=typeof e=="string"?e:qC(e);return NC(xn.createHmac("sha256",n).update(t).digest())}};ri.NodeCrypto=Pu;function NC(r){return r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)}function qC(r){return Buffer.from(r)}});var Cs=z(dr=>{"use strict";var jC=dr&&dr.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var o=Object.getOwnPropertyDescriptor(e,t);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,o)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),LC=dr&&dr.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&jC(e,r,t)};Object.defineProperty(dr,"__esModule",{value:!0});dr.createCrypto=$C;dr.hasBrowserCrypto=np;var UC=tp(),MC=rp();LC(Fu(),dr);function $C(){return np()?new UC.BrowserCrypto:new MC.NodeCrypto}function np(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Bn=z((xu,op)=>{var ni=X("buffer"),Vt=ni.Buffer;function sp(r,e){for(var t in r)e[t]=r[t]}Vt.from&&Vt.alloc&&Vt.allocUnsafe&&Vt.allocUnsafeSlow?op.exports=ni:(sp(ni,xu),xu.Buffer=tn);function tn(r,e,t){return Vt(r,e,t)}tn.prototype=Object.create(Vt.prototype);sp(Vt,tn);tn.from=function(r,e,t){if(typeof r=="number")throw new TypeError("Argument must not be a number");return Vt(r,e,t)};tn.alloc=function(r,e,t){if(typeof r!="number")throw new TypeError("Argument must be a number");var n=Vt(r);return e!==void 0?typeof t=="string"?n.fill(e,t):n.fill(e):n.fill(0),n};tn.allocUnsafe=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return Vt(r)};tn.allocUnsafeSlow=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return ni.SlowBuffer(r)}});var ap=z((IS,ip)=>{"use strict";function Bu(r){var e=(r/8|0)+(r%8===0?0:1);return e}var HC={ES256:Bu(256),ES384:Bu(384),ES512:Bu(521)};function GC(r){var e=HC[r];if(e)return e;throw new Error('Unknown algorithm "'+r+'"')}ip.exports=GC});var Iu=z((NS,hp)=>{"use strict";var si=Bn().Buffer,cp=ap(),oi=128,lp=0,WC=32,zC=16,JC=2,fp=zC|WC|lp<<6,ii=JC|lp<<6;function VC(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function dp(r){if(si.isBuffer(r))return r;if(typeof r=="string")return si.from(r,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function KC(r,e){r=dp(r);var t=cp(e),n=t+1,o=r.length,a=0;if(r[a++]!==fp)throw new Error('Could not find expected "seq"');var u=r[a++];if(u===(oi|1)&&(u=r[a++]),o-a=oi;return o&&--n,n}function YC(r,e){r=dp(r);var t=cp(e),n=r.length;if(n!==t*2)throw new TypeError('"'+e+'" signatures must be "'+t*2+'" bytes, saw "'+n+'"');var o=up(r,0,t),a=up(r,t,r.length),u=t-o,l=t-a,f=2+u+1+1+l,h=f{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.LRUCache=void 0;hr.snakeToCamel=mp;hr.originalOrCamelOptions=eb;hr.removeUndefinedValuesInObject=tb;hr.isValidFile=rb;hr.getWellKnownCertificateConfigFileLocation=nb;var XC=X("fs"),QC=X("os"),Nu=X("path"),ZC="certificate_config.json",pp="gcloud";function mp(r){return r.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function eb(r){function e(t){let n=r||{};return n[t]??n[mp(t)]}return{get:e}}var qu=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,t){this.#e.delete(e),this.#e.set(e,{value:t,lastAccessed:Date.now()})}set(e,t){this.#t(e,t),this.#r()}get(e){let t=this.#e.get(e);if(t)return this.#t(e,t.value),this.#r(),t.value}#r(){let e=this.maxAge?Date.now()-this.maxAge:0,t=this.#e.entries().next();for(;!t.done&&(this.#e.size>this.capacity||t.value[1].lastAccessed{(t===void 0||t==="undefined")&&delete r[e]}),r}async function rb(r){try{return(await XC.promises.lstat(r)).isFile()}catch{return!1}}function nb(){let r=process.env.CLOUDSDK_CONFIG||(sb()?Nu.join(process.env.APPDATA||"",pp):Nu.join(process.env.HOME||"",".config",pp));return Nu.join(r,ZC)}function sb(){return QC.platform().startsWith("win")}});var gp=z((jS,ob)=>{ob.exports={name:"google-auth-library",version:"10.2.0",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:"googleapis/google-auth-library-nodejs.git",keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.0.0","gcp-metadata":"^7.0.0","google-logging-utils":"^1.0.0",gtoken:"^8.0.0",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","assert-rejects":"^1.0.0",c8:"^10.0.0",codecov:"^3.0.2",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^4.0.0","jsdoc-region-tag":"^3.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",linkinator:"^6.1.2",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.1","null-loader":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","ts-loader":"^8.0.0",typescript:"^5.1.6",webpack:"^5.21.2","webpack-cli":"^4.0.0"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start","docs-test":"linkinator docs","predocs-test":"npm run docs",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0"}});var ju=z(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.USER_AGENT=xr.PRODUCT_NAME=xr.pkg=void 0;var yp=gp();xr.pkg=yp;var _p="google-api-nodejs-client";xr.PRODUCT_NAME=_p;var ib=`${_p}/${yp.version}`;xr.USER_AGENT=ib});var pt=z(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.AuthClient=Lt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=Lt.DEFAULT_UNIVERSE=void 0;var ab=X("events"),Lu=Je(),ub=jt(),cb=Du(),Uu=ju();Lt.DEFAULT_UNIVERSE="googleapis.com";Lt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=5*60*1e3;var Mu=class r extends ab.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=Lt.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=Lt.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let t=(0,ub.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=t.get("project_id")??null,this.quotaProjectId=t.get("quota_project_id"),this.credentials=t.get("credentials")??{},this.universeDomain=t.get("universe_domain")??Lt.DEFAULT_UNIVERSE,this.transporter=e.transporter??new Lu.Gaxios(e.transporterOptions),t.get("useAuthRequestParameters")!==!1&&(this.transporter.interceptors.request.add(r.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(r.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let t=e[0],n=e[1],o,a=new Headers;return typeof t=="string"?o=new URL(t):t instanceof URL?o=t:t&&t.url&&(o=new URL(t.url)),t&&typeof t=="object"&&"headers"in t&&Lu.Gaxios.mergeHeaders(a,t.headers),n&&Lu.Gaxios.mergeHeaders(a,new Headers(n.headers)),typeof t=="object"&&!(t instanceof URL)?this.request({...n,...t,headers:a,url:o}):this.request({...n,headers:a,url:o})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,t){let n=t.get("x-goog-user-project"),o=t.get("authorization");return n&&e.set("x-goog-user-project",n),o&&e.set("authorization",o),e}static log=(0,cb.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let n=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${n}`)}let t=e.headers.get("User-Agent");t?t.includes(`${Uu.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${t} ${Uu.USER_AGENT}`):e.headers.set("User-Agent",Uu.USER_AGENT);try{let n=e,o=n[r.RequestMethodNameSymbol],a=`${Math.floor(Math.random()*1e3)}`;n[r.RequestLogIdSymbol]=a;let u={url:e.url,headers:e.headers};o?r.log.info("%s [%s] request %j",o,a,u):r.log.info("[%s] request %j",a,u)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let t=e.config,n=t[r.RequestMethodNameSymbol],o=t[r.RequestLogIdSymbol];n?r.log.info("%s [%s] response %j",n,o,e.data):r.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let t=e.config,n=t[r.RequestMethodNameSymbol],o=t[r.RequestLogIdSymbol];n?r.log.info("%s [%s] error %j",n,o,e.response?.data):r.log.error("[%s] error %j",o,e.response?.data)}catch{}throw e}};static setMethodName(e,t){try{let n=e;n[r.RequestMethodNameSymbol]=t}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};Lt.AuthClient=Mu});var Hu=z(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});ai.LoginTicket=void 0;var $u=class{envelope;payload;constructor(e,t){this.envelope=e,this.payload=t}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}};ai.LoginTicket=$u});var rn=z(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.OAuth2Client=Kt.ClientAuthentication=Kt.CertificateFormat=Kt.CodeChallengeMethod=void 0;var Cp=Je(),lb=X("querystring"),fb=X("stream"),db=Iu(),bp=jt(),Gu=Cs(),In=pt(),hb=Hu(),Ep;(function(r){r.Plain="plain",r.S256="S256"})(Ep||(Kt.CodeChallengeMethod=Ep={}));var pr;(function(r){r.PEM="PEM",r.JWK="JWK"})(pr||(Kt.CertificateFormat=pr={}));var bs;(function(r){r.ClientSecretPost="ClientSecretPost",r.ClientSecretBasic="ClientSecretBasic",r.None="None"})(bs||(Kt.ClientAuthentication=bs={}));var Wu=class r extends In.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=pr.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},t,n){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:t,redirectUri:n}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints},this.clientAuthentication=e.clientAuthentication||bs.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");return e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" ")),this.endpoints.oauth2AuthBaseUrl.toString()+"?"+lb.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,Gu.createCrypto)(),n=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),a=(await e.sha256DigestBase64(n)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:n,codeChallenge:a}}getToken(e,t){let n=typeof e=="string"?{code:e}:e;if(t)this.getTokenAsync(n).then(o=>t(null,o.tokens,o.res),o=>t(o,null,o.response));else return this.getTokenAsync(n)}async getTokenAsync(e){let t=this.endpoints.oauth2TokenUrl.toString(),n=new Headers,o={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===bs.ClientSecretBasic){let f=Buffer.from(`${this._clientId}:${this._clientSecret}`);n.set("authorization",`Basic ${f.toString("base64")}`)}this.clientAuthentication===bs.ClientSecretPost&&(o.client_secret=this._clientSecret);let a={...r.RETRY_CONFIG,method:"POST",url:t,data:new URLSearchParams((0,bp.removeUndefinedValuesInObject)(o)),headers:n};In.AuthClient.setMethodName(a,"getTokenAsync");let u=await this.transporter.request(a),l=u.data;return u.data&&u.data.expires_in&&(l.expiry_date=new Date().getTime()+u.data.expires_in*1e3,delete l.expires_in),this.emit("tokens",l),{tokens:l,res:u}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let t=this.refreshTokenNoCache(e).then(n=>(this.refreshTokenPromises.delete(e),n),n=>{throw this.refreshTokenPromises.delete(e),n});return this.refreshTokenPromises.set(e,t),t}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let t=this.endpoints.oauth2TokenUrl.toString(),n={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},o;try{let u={...r.RETRY_CONFIG,method:"POST",url:t,data:new URLSearchParams((0,bp.removeUndefinedValuesInObject)(n))};In.AuthClient.setMethodName(u,"refreshTokenNoCache"),o=await this.transporter.request(u)}catch(u){throw u instanceof Cp.GaxiosError&&u.message==="invalid_grant"&&u.response?.data&&/ReAuth/i.test(u.response.data.error_description)&&(u.message=JSON.stringify(u.response.data)),u}let a=o.data;return o.data&&o.data.expires_in&&(a.expiry_date=new Date().getTime()+o.data.expires_in*1e3,delete a.expires_in),this.emit("tokens",a),{tokens:a,res:o}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(t=>e(null,t.credentials,t.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),t=e.tokens;return t.refresh_token=this.credentials.refresh_token,this.credentials=t,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(t=>e(null,t.token,t.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let n=await this.processAndValidateRefreshHandler();if(n?.access_token)return this.setCredentials(n),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let t=await this.refreshAccessTokenAsync();if(!t.credentials||t.credentials&&!t.credentials.access_token)throw new Error("Could not refresh access token.");return{token:t.credentials.access_token,res:t.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let t=this.credentials;if(!t.access_token&&!t.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(t.access_token&&!this.isTokenExpiring()){t.token_type=t.token_type||"Bearer";let l=new Headers({authorization:t.token_type+" "+t.access_token});return{headers:this.addSharedMetadataHeaders(l)}}if(this.refreshHandler){let l=await this.processAndValidateRefreshHandler();if(l?.access_token){this.setCredentials(l);let f=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(f)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let n=null,o=null;try{n=await this.refreshToken(t.refresh_token),o=n.tokens}catch(l){let f=l;throw f.response&&(f.response.status===403||f.response.status===404)&&(f.message=`Could not refresh access token: ${f.message}`),f}let a=this.credentials;a.token_type=a.token_type||"Bearer",o.refresh_token=a.refresh_token,this.credentials=o;let u=new Headers({authorization:a.token_type+" "+o.access_token});return{headers:this.addSharedMetadataHeaders(u),res:n.res}}static getRevokeTokenUrl(e){return new r().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let t=new URL(this.endpoints.oauth2RevokeUrl);return t.searchParams.append("token",e),t}revokeToken(e,t){let n={...r.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(In.AuthClient.setMethodName(n,"revokeToken"),t)this.transporter.request(n).then(o=>t(null,o),t);else return this.transporter.request(n)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(t=>e(null,t),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw new Error("No access token to revoke.")}request(e,t){if(t)this.requestAsync(e).then(n=>t(null,n),n=>t(n,n.response));else return this.requestAsync(e)}async requestAsync(e,t=!1){try{let n=await this.getRequestMetadataAsync();return e.headers=Cp.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,n.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(n){let o=n.response;if(o){let a=o.status,u=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),l=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,f=o.config.data instanceof fb.Readable,h=a===401||a===403;if(!t&&h&&!f&&u)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!t&&h&&!f&&l){let d=await this.processAndValidateRefreshHandler();return d?.access_token&&this.setCredentials(d),this.requestAsync(e,!0)}}throw n}}verifyIdToken(e,t){if(t&&typeof t!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(t)this.verifyIdTokenAsync(e).then(n=>t(null,n),t);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let t=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,t.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:t}=await this.transporter.request({...r.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),n=Object.assign({expiry_date:new Date().getTime()+t.expires_in*1e3,scopes:t.scope.split(" ")},t);return delete n.expires_in,delete n.scope,n}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(t=>e(null,t.certs,t.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),t=(0,Gu.hasBrowserCrypto)()?pr.JWK:pr.PEM;if(this.certificateExpiry&&e[0-9]+)/.exec(a)?.groups?.maxAge;h&&(u=Number(h)*1e3)}let l={};switch(t){case pr.PEM:l=n.data;break;case pr.JWK:for(let h of n.data.keys)l[h.kid]=h;break;default:throw new Error(`Unsupported certificate format ${t}`)}let f=new Date;return this.certificateExpiry=u===-1?null:new Date(f.getTime()+u),this.certificateCache=l,this.certificateCacheFormat=t,{certs:l,format:t,res:n}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(t=>e(null,t.pubkeys,t.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,t=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let n={...r.RETRY_CONFIG,url:t};In.AuthClient.setMethodName(n,"getIapPublicKeysAsync"),e=await this.transporter.request(n)}catch(n){throw n instanceof Error&&(n.message=`Failed to retrieve verification certificates: ${n.message}`),n}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,t,n,o,a){let u=(0,Gu.createCrypto)();a||(a=r.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let l=e.split(".");if(l.length!==3)throw new Error("Wrong number of segments in token: "+e);let f=l[0]+"."+l[1],h=l[2],d,_;try{d=JSON.parse(u.decodeBase64StringUtf8(l[0]))}catch(S){throw S instanceof Error&&(S.message=`Can't parse token envelope: ${l[0]}': ${S.message}`),S}if(!d)throw new Error("Can't parse token envelope: "+l[0]);try{_=JSON.parse(u.decodeBase64StringUtf8(l[1]))}catch(S){throw S instanceof Error&&(S.message=`Can't parse token payload '${l[0]}`),S}if(!_)throw new Error("Can't parse token payload: "+l[1]);if(!Object.prototype.hasOwnProperty.call(t,d.kid))throw new Error("No pem found for envelope: "+JSON.stringify(d));let E=t[d.kid];if(d.alg==="ES256"&&(h=db.joseToDer(h,"ES256").toString("base64")),!await u.verify(E,f,h))throw new Error("Invalid token signature: "+e);if(!_.iat)throw new Error("No issue time in token: "+JSON.stringify(_));if(!_.exp)throw new Error("No expiration time in token: "+JSON.stringify(_));let v=Number(_.iat);if(isNaN(v))throw new Error("iat field using invalid format");let w=Number(_.exp);if(isNaN(w))throw new Error("exp field using invalid format");let g=new Date().getTime()/1e3;if(w>=g+a)throw new Error("Expiration time too far in future: "+JSON.stringify(_));let C=v-r.CLOCK_SKEW_SECS_,R=w+r.CLOCK_SKEW_SECS_;if(gR)throw new Error("Token used too late, "+g+" > "+R+": "+JSON.stringify(_));if(o&&o.indexOf(_.iss)<0)throw new Error("Invalid issuer, expected one of ["+o+"], but got "+_.iss);if(typeof n<"u"&&n!==null){let S=_.aud,N=!1;if(n.constructor===Array?N=n.indexOf(S)>-1:N=S===n,!N)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new hb.LoginTicket(d,_)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};Kt.OAuth2Client=Wu});var Ju=z(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.Compute=void 0;var pb=Je(),wp=_s(),mb=rn(),zu=class extends mb.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e=`service-accounts/${this.serviceAccountEmail}/token`,t;try{let o={property:e};this.scopes.length>0&&(o.params={scopes:this.scopes.join(",")}),t=await wp.instance(o)}catch(o){throw o instanceof pb.GaxiosError&&(o.message=`Could not refresh access token: ${o.message}`,this.wrapError(o)),o}let n=t;return t&&t.expires_in&&(n.expiry_date=new Date().getTime()+t.expires_in*1e3,delete n.expires_in),this.emit("tokens",n),{tokens:n,res:null}}async fetchIdToken(e){let t=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,n;try{let o={property:t};n=await wp.instance(o)}catch(o){throw o instanceof Error&&(o.message=`Could not fetch ID token: ${o.message}`),o}return n}wrapError(e){let t=e.response;t&&t.status&&(e.status=t.status,t.status===403?e.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+e.message:t.status===404&&(e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message))}};ui.Compute=zu});var Ku=z(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.IdTokenClient=void 0;var gb=rn(),Vu=class extends gb.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let t=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:t,expiry_date:this.getIdTokenExpiryDate(t)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let t=e.split(".")[1];if(t)return JSON.parse(Buffer.from(t,"base64").toString("ascii")).exp*1e3}};ci.IdTokenClient=Vu});var Yu=z(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.GCPEnv=void 0;Nn.clear=yb;Nn.getEnv=_b;var Ap=_s(),mr;(function(r){r.APP_ENGINE="APP_ENGINE",r.KUBERNETES_ENGINE="KUBERNETES_ENGINE",r.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",r.COMPUTE_ENGINE="COMPUTE_ENGINE",r.CLOUD_RUN="CLOUD_RUN",r.NONE="NONE"})(mr||(Nn.GCPEnv=mr={}));var Es;function yb(){Es=void 0}async function _b(){return Es||(Es=Cb(),Es)}async function Cb(){let r=mr.NONE;return bb()?r=mr.APP_ENGINE:Eb()?r=mr.CLOUD_FUNCTIONS:await Db()?await Ab()?r=mr.KUBERNETES_ENGINE:wb()?r=mr.CLOUD_RUN:r=mr.COMPUTE_ENGINE:r=mr.NONE,r}function bb(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function Eb(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function wb(){return!!process.env.K_CONFIGURATION}async function Ab(){try{return await Ap.instance("attributes/cluster-name"),!0}catch{return!1}}async function Db(){return Ap.isAvailable()}});var Xu=z((zS,Dp)=>{var li=Bn().Buffer,Sb=X("stream"),vb=X("util");function fi(r){if(this.buffer=null,this.writable=!0,this.readable=!0,!r)return this.buffer=li.alloc(0),this;if(typeof r.pipe=="function")return this.buffer=li.alloc(0),r.pipe(this),this;if(r.length||typeof r=="object")return this.buffer=r,this.writable=!1,process.nextTick(function(){this.emit("end",r),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof r+")")}vb.inherits(fi,Sb);fi.prototype.write=function(e){this.buffer=li.concat([this.buffer,li.from(e)]),this.emit("data",e)};fi.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};Dp.exports=fi});var vp=z((JS,Sp)=>{"use strict";var ws=X("buffer").Buffer,Qu=X("buffer").SlowBuffer;Sp.exports=di;function di(r,e){if(!ws.isBuffer(r)||!ws.isBuffer(e)||r.length!==e.length)return!1;for(var t=0,n=0;n{var jn=Bn().Buffer,St=X("crypto"),Rp=Iu(),Tp=X("util"),kb=`"%s" is not a valid algorithm. + Supported algorithms are: + "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,As="secret must be a string or buffer",qn="key must be a string or a buffer",Fb="key must be a string, a buffer or an object",ec=typeof St.createPublicKey=="function";ec&&(qn+=" or a KeyObject",As+="or a KeyObject");function kp(r){if(!jn.isBuffer(r)&&typeof r!="string"&&(!ec||typeof r!="object"||typeof r.type!="string"||typeof r.asymmetricKeyType!="string"||typeof r.export!="function"))throw Ut(qn)}function Fp(r){if(!jn.isBuffer(r)&&typeof r!="string"&&typeof r!="object")throw Ut(Fb)}function Ob(r){if(!jn.isBuffer(r)){if(typeof r=="string")return r;if(!ec||typeof r!="object"||r.type!=="secret"||typeof r.export!="function")throw Ut(As)}}function tc(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Op(r){r=r.toString();var e=4-r.length%4;if(e!==4)for(var t=0;t{var Mb=X("buffer").Buffer;Np.exports=function(e){return typeof e=="string"?e:typeof e=="number"||Mb.isBuffer(e)?e.toString():JSON.stringify(e)}});var $p=z((YS,Mp)=>{var $b=Bn().Buffer,qp=Xu(),Hb=rc(),Gb=X("stream"),jp=nc(),sc=X("util");function Lp(r,e){return $b.from(r,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Wb(r,e,t){t=t||"utf8";var n=Lp(jp(r),"binary"),o=Lp(jp(e),t);return sc.format("%s.%s",n,o)}function Up(r){var e=r.header,t=r.payload,n=r.secret||r.privateKey,o=r.encoding,a=Hb(e.alg),u=Wb(e,t,o),l=a.sign(u,n);return sc.format("%s.%s",u,l)}function hi(r){var e=r.secret||r.privateKey||r.key,t=new qp(e);this.readable=!0,this.header=r.header,this.encoding=r.encoding,this.secret=this.privateKey=this.key=t,this.payload=new qp(r.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}sc.inherits(hi,Gb);hi.prototype.sign=function(){try{var e=Up({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(t){this.readable=!1,this.emit("error",t),this.emit("close")}};hi.sign=Up;Mp.exports=hi});var Qp=z((XS,Xp)=>{var Gp=Bn().Buffer,Hp=Xu(),zb=rc(),Jb=X("stream"),Wp=nc(),Vb=X("util"),Kb=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function Yb(r){return Object.prototype.toString.call(r)==="[object Object]"}function Xb(r){if(Yb(r))return r;try{return JSON.parse(r)}catch{return}}function zp(r){var e=r.split(".",1)[0];return Xb(Gp.from(e,"base64").toString("binary"))}function Qb(r){return r.split(".",2).join(".")}function Jp(r){return r.split(".")[2]}function Zb(r,e){e=e||"utf8";var t=r.split(".")[1];return Gp.from(t,"base64").toString(e)}function Vp(r){return Kb.test(r)&&!!zp(r)}function Kp(r,e,t){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}r=Wp(r);var o=Jp(r),a=Qb(r),u=zb(e);return u.verify(a,o,t)}function Yp(r,e){if(e=e||{},r=Wp(r),!Vp(r))return null;var t=zp(r);if(!t)return null;var n=Zb(r);return(t.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:t,payload:n,signature:Jp(r)}}function Ln(r){r=r||{};var e=r.secret||r.publicKey||r.key,t=new Hp(e);this.readable=!0,this.algorithm=r.algorithm,this.encoding=r.encoding,this.secret=this.publicKey=this.key=t,this.signature=new Hp(r.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}Vb.inherits(Ln,Jb);Ln.prototype.verify=function(){try{var e=Kp(this.signature.buffer,this.algorithm,this.key.buffer),t=Yp(this.signature.buffer,this.encoding);return this.emit("done",e,t),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};Ln.decode=Yp;Ln.isValid=Vp;Ln.verify=Kp;Xp.exports=Ln});var oc=z(Br=>{var Zp=$p(),pi=Qp(),eE=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Br.ALGORITHMS=eE;Br.sign=Zp.sign;Br.verify=pi.verify;Br.decode=pi.decode;Br.isValid=pi.isValid;Br.createSign=function(e){return new Zp(e)};Br.createVerify=function(e){return new pi(e)}});var pm=z(gi=>{"use strict";Object.defineProperty(gi,"__esModule",{value:!0});gi.GoogleToken=void 0;var em=mi(X("fs")),tE=Je(),rE=mi(oc()),nE=mi(X("path")),sE=X("util");function mi(r,e){if(typeof WeakMap=="function")var t=new WeakMap,n=new WeakMap;return(mi=function(a,u){if(!u&&a&&a.__esModule)return a;var l,f,h={__proto__:null,default:a};if(a===null||gr(a)!="object"&&typeof a!="function")return h;if(l=u?n:t){if(l.has(a))return l.get(a);l.set(a,h)}for(var d in a)d!=="default"&&{}.hasOwnProperty.call(a,d)&&((f=(l=Object.defineProperty)&&Object.getOwnPropertyDescriptor(a,d))&&(f.get||f.set)?l(h,d,f):h[d]=a[d]);return h})(r,e)}function gr(r){"@babel/helpers - typeof";return gr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},gr(r)}function oE(r,e){cm(r,e),e.add(r)}function iE(r,e,t){cm(r,e),e.set(r,t)}function cm(r,e){if(e.has(r))throw new TypeError("Cannot initialize the same private elements twice on an object")}function tm(r,e,t){return r.set(Mt(r,e),t),t}function rm(r,e){return r.get(Mt(r,e))}function Mt(r,e,t){if(typeof r=="function"?r===e:r.has(e))return arguments.length<3?e:t;throw new TypeError("Private element is not present on this object")}function nm(r,e){for(var t=0;t3?(Z=se===de)&&(K=ue[(H=ue[4])?5:(H=3,3)],ue[4]=ue[5]=r):ue[0]<=J&&((Z=re<2&&Jde||de>se)&&(ue[4]=re,ue[5]=de,fe.n=se,H=0))}if(Z||re>1)return u;throw he=!0,de}return function(re,de,Z){if(W>1)throw TypeError("Generator is already running");for(he&&de===1&&ye(de,Z),H=de,K=Z;(e=H<2?r:K)||!he;){L||(H?H<3?(H>1&&(fe.n=-1),ye(H,K)):fe.n=K:fe.v=K);try{if(W=2,L){if(H||(re="next"),e=L[re]){if(!(e=e.call(L,K)))throw TypeError("iterator result is not an object");if(!e.done)return e;K=e.value,H<2&&(H=0)}else H===1&&(e=L.return)&&e.call(L),H<2&&(K=TypeError("The iterator does not provide a '"+re+"' method"),H=1);L=r}else if((e=(he=fe.n<0)?K:S.call(N,fe))!==u)break}catch(ue){L=r,H=1,K=ue}finally{W=1}}return{value:e,done:he}}}(P,w,g),!0),R}var u={};function l(){}function f(){}function h(){}e=Object.getPrototypeOf;var d=[][n]?e(e([][n]())):(gt(e={},n,function(){return this}),e),_=h.prototype=l.prototype=Object.create(d);function E(P){return Object.setPrototypeOf?Object.setPrototypeOf(P,h):(P.__proto__=h,gt(P,o,"GeneratorFunction")),P.prototype=Object.create(_),P}return f.prototype=h,gt(_,"constructor",h),gt(h,"constructor",f),f.displayName="GeneratorFunction",gt(h,o,"GeneratorFunction"),gt(_),gt(_,o,"Generator"),gt(_,n,function(){return this}),gt(_,"toString",function(){return"[object Generator]"}),(yt=function(){return{w:a,m:E}})()}function gt(r,e,t,n){var o=Object.defineProperty;try{o({},"",{})}catch{o=0}gt=function(u,l,f,h){if(l)o?o(u,l,{value:f,enumerable:!h,configurable:!h,writable:!h}):u[l]=f;else{var d=function(E,P){gt(u,E,function(v){return this._invoke(E,P,v)})};d("next",0),d("throw",1),d("return",2)}},gt(r,e,t,n)}function sm(r,e,t,n,o,a,u){try{var l=r[a](u),f=l.value}catch(h){return void t(h)}l.done?e(f):Promise.resolve(f).then(n,o)}function Un(r){return function(){var e=this,t=arguments;return new Promise(function(n,o){var a=r.apply(e,t);function u(f){sm(a,n,o,u,l,"next",f)}function l(f){sm(a,n,o,u,l,"throw",f)}u(void 0)})}}var om=em.readFile?(0,sE.promisify)(em.readFile):Un(yt().m(function r(){return yt().w(function(e){for(;;)switch(e.n){case 0:throw new vs("use key rather than keyFile.","MISSING_CREDENTIALS");case 1:return e.a(2)}},r)})),im="https://oauth2.googleapis.com/token",pE="https://oauth2.googleapis.com/revoke?token=",vs=function(r){function e(t,n){var o;return fm(this,e),o=aE(this,e,[t]),mt(o,"code",void 0),o.code=n,o}return lE(e,r),lm(e)}(ic(Error)),Ss=new WeakMap,Yt=new WeakSet,ZS=gi.GoogleToken=function(){function r(e){fm(this,r),oE(this,Yt),mt(this,"expiresAt",void 0),mt(this,"key",void 0),mt(this,"keyFile",void 0),mt(this,"iss",void 0),mt(this,"sub",void 0),mt(this,"scope",void 0),mt(this,"rawToken",void 0),mt(this,"tokenExpires",void 0),mt(this,"email",void 0),mt(this,"additionalClaims",void 0),mt(this,"eagerRefreshThresholdMillis",void 0),mt(this,"transporter",{request:function(n){return(0,tE.request)(n)}}),iE(this,Ss,void 0),Mt(Yt,this,hm).call(this,e)}return lm(r,[{key:"accessToken",get:function(){return this.rawToken?this.rawToken.access_token:void 0}},{key:"idToken",get:function(){return this.rawToken?this.rawToken.id_token:void 0}},{key:"tokenType",get:function(){return this.rawToken?this.rawToken.token_type:void 0}},{key:"refreshToken",get:function(){return this.rawToken?this.rawToken.refresh_token:void 0}},{key:"hasExpired",value:function(){var t=new Date().getTime();return this.rawToken&&this.expiresAt?t>=this.expiresAt:!0}},{key:"isTokenExpiring",value:function(){var t,n=new Date().getTime(),o=(t=this.eagerRefreshThresholdMillis)!==null&&t!==void 0?t:0;return this.rawToken&&this.expiresAt?this.expiresAt<=n+o:!0}},{key:"getToken",value:function(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(gr(t)==="object"&&(n=t,t=void 0),n=Object.assign({forceRefresh:!1},n),t){var o=t;Mt(Yt,this,am).call(this,n).then(function(a){return o(null,a)},t);return}return Mt(Yt,this,am).call(this,n)}},{key:"getCredentials",value:function(){var e=Un(yt().m(function n(o){var a,u,l,f,h,d,_;return yt().w(function(E){for(;;)switch(E.n){case 0:a=nE.extname(o),_=a,E.n=_===".json"?1:_===".der"||_===".crt"||_===".pem"?4:_===".p12"||_===".pfx"?6:7;break;case 1:return E.n=2,om(o,"utf8");case 2:if(u=E.v,l=JSON.parse(u),f=l.private_key,h=l.client_email,!(!f||!h)){E.n=3;break}throw new vs("private_key and client_email are required.","MISSING_CREDENTIALS");case 3:return E.a(2,{privateKey:f,clientEmail:h});case 4:return E.n=5,om(o,"utf8");case 5:return d=E.v,E.a(2,{privateKey:d});case 6:throw new vs("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.","UNKNOWN_CERTIFICATE_TYPE");case 7:throw new vs("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE");case 8:return E.a(2)}},n)}));function t(n){return e.apply(this,arguments)}return t}()},{key:"revokeToken",value:function(t){if(t){Mt(Yt,this,um).call(this).then(function(){return t()},t);return}return Mt(Yt,this,um).call(this)}}])}();function am(r){return ac.apply(this,arguments)}function ac(){return ac=Un(yt().m(function r(e){return yt().w(function(t){for(;;)switch(t.n){case 0:if(!(rm(Ss,this)&&!e.forceRefresh)){t.n=1;break}return t.a(2,rm(Ss,this));case 1:return t.p=1,t.n=2,tm(Ss,this,Mt(Yt,this,mE).call(this,e));case 2:return t.a(2,t.v);case 3:return t.p=3,tm(Ss,this,void 0),t.f(3);case 4:return t.a(2)}},r,this,[[1,,3,4]])})),ac.apply(this,arguments)}function mE(r){return uc.apply(this,arguments)}function uc(){return uc=Un(yt().m(function r(e){var t;return yt().w(function(n){for(;;)switch(n.n){case 0:if(!(this.isTokenExpiring()===!1&&e.forceRefresh===!1)){n.n=1;break}return n.a(2,Promise.resolve(this.rawToken));case 1:if(!(!this.key&&!this.keyFile)){n.n=2;break}throw new Error("No key or keyFile set.");case 2:if(!(!this.key&&this.keyFile)){n.n=4;break}return n.n=3,this.getCredentials(this.keyFile);case 3:t=n.v,this.key=t.privateKey,this.iss=t.clientEmail||this.iss,t.clientEmail||Mt(Yt,this,gE).call(this);case 4:return n.a(2,Mt(Yt,this,yE).call(this))}},r,this)})),uc.apply(this,arguments)}function gE(){if(!this.iss)throw new vs("email is required.","MISSING_CREDENTIALS")}function um(){return cc.apply(this,arguments)}function cc(){return cc=Un(yt().m(function r(){var e;return yt().w(function(t){for(;;)switch(t.n){case 0:if(this.accessToken){t.n=1;break}throw new Error("No token to revoke.");case 1:return e=pE+this.accessToken,t.n=2,this.transporter.request({url:e,retry:!0});case 2:Mt(Yt,this,hm).call(this,{email:this.iss,sub:this.sub,key:this.key,keyFile:this.keyFile,scope:this.scope,additionalClaims:this.additionalClaims});case 3:return t.a(2)}},r,this)})),cc.apply(this,arguments)}function hm(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.keyFile=r.keyFile,this.key=r.key,this.rawToken=void 0,this.iss=r.email||r.iss,this.sub=r.sub,this.additionalClaims=r.additionalClaims,gr(r.scope)==="object"?this.scope=r.scope.join(" "):this.scope=r.scope,this.eagerRefreshThresholdMillis=r.eagerRefreshThresholdMillis,r.transporter&&(this.transporter=r.transporter)}function yE(){return lc.apply(this,arguments)}function lc(){return lc=Un(yt().m(function r(){var e,t,n,o,a,u,l,f,h,d;return yt().w(function(_){for(;;)switch(_.n){case 0:return e=Math.floor(new Date().getTime()/1e3),t=this.additionalClaims||{},n=Object.assign({iss:this.iss,scope:this.scope,aud:im,exp:e+3600,iat:e,sub:this.sub},t),o=rE.sign({header:{alg:"RS256"},payload:n,secret:this.key}),_.p=1,_.n=2,this.transporter.request({method:"POST",url:im,data:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:o}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});case 2:return a=_.v,this.rawToken=a.data,this.expiresAt=a.data.expires_in===null||a.data.expires_in===void 0?void 0:(e+a.data.expires_in)*1e3,_.a(2,this.rawToken);case 3:throw _.p=3,d=_.v,this.rawToken=void 0,this.tokenExpires=void 0,f=d.response&&(u=d.response)!==null&&u!==void 0&&u.data?(l=d.response)===null||l===void 0?void 0:l.data:{},f.error&&(h=f.error_description?": ".concat(f.error_description):"",d.message="".concat(f.error).concat(h)),d;case 4:return _.a(2)}},r,this,[[1,3]])})),lc.apply(this,arguments)}});var hc=z(yi=>{"use strict";Object.defineProperty(yi,"__esModule",{value:!0});yi.JWTAccess=void 0;var _E=oc(),CE=jt(),mm={alg:"RS256",typ:"JWT"},dc=class r{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new CE.LRUCache({capacity:500,maxAge:60*60*1e3});constructor(e,t,n,o){this.email=e,this.key=t,this.keyId=n,this.eagerRefreshThresholdMillis=o??5*60*1e3}getCachedKey(e,t){let n=e;if(t&&Array.isArray(t)&&t.length?n=e?`${e}_${t.join("_")}`:`${t.join("_")}`:typeof t=="string"&&(n=e?`${e}_${t}`:t),!n)throw Error("Scopes or url must be provided");return n}getRequestHeaders(e,t,n){let o=this.getCachedKey(e,n),a=this.cache.get(o),u=Date.now();if(a&&a.expiration-u>this.eagerRefreshThresholdMillis)return new Headers(a.headers);let l=Math.floor(Date.now()/1e3),f=r.getExpirationTime(l),h;if(Array.isArray(n)&&(n=n.join(" ")),n?h={iss:this.email,sub:this.email,scope:n,exp:f,iat:l}:h={iss:this.email,sub:this.email,aud:e,exp:f,iat:l},t){for(let v in h)if(t[v])throw new Error(`The '${v}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let d=this.keyId?{...mm,kid:this.keyId}:mm,_=Object.assign(h,t),E=_E.sign({header:d,payload:_,secret:this.key}),P=new Headers({authorization:`Bearer ${E}`});return this.cache.set(o,{expiration:f*1e3,headers:P}),P}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,t){if(t)this.fromStreamAsync(e).then(()=>t(),t);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((t,n)=>{e||n(new Error("Must pass in a stream containing the service account auth settings."));let o="";e.setEncoding("utf8").on("data",a=>o+=a).on("error",n).on("end",()=>{try{let a=JSON.parse(o);this.fromJSON(a),t()}catch(a){n(a)}})})}};yi.JWTAccess=dc});var mc=z(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});Ci.JWT=void 0;var gm=pm(),bE=hc(),EE=rn(),_i=pt(),pc=class r extends EE.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let t=new r(this);return t.scopes=e,t}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let t=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==_i.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==_i.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${_i.DEFAULT_UNIVERSE}`);if(!this.apiKey&&t)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:n}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${n.id_token}`}))}}else{this.access||(this.access=new bE.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let n;this.hasUserScopes()?n=this.scopes:e||(n=this.defaultScopes);let o=this.useJWTAccessWithScope||this.universeDomain!==_i.DEFAULT_UNIVERSE,a=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?n:void 0);return{headers:this.addSharedMetadataHeaders(a)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let t=new gm.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await t.getToken({forceRefresh:!0}),!t.idToken)throw new Error("Unknown error: Failed to fetch ID token");return t.idToken}hasUserScopes(){return this.scopes?this.scopes.length>0:!1}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0||this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(e)this.authorizeAsync().then(t=>e(null,t),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw new Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.key,this.email=this.gtoken.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),n={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};return this.emit("tokens",n),{res:null,tokens:n}}createGToken(){return this.gtoken||(this.gtoken=new gm.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,t){if(t)this.fromStreamAsync(e).then(()=>t(),t);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((t,n)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let o="";e.setEncoding("utf8").on("error",n).on("data",a=>o+=a).on("end",()=>{try{let a=JSON.parse(o);this.fromJSON(a),t()}catch(a){n(a)}})})}fromAPIKey(e){if(typeof e!="string")throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let t=await this.createGToken().getCredentials(this.keyFile);return{private_key:t.privateKey,client_email:t.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};Ci.JWT=pc});var yc=z(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.UserRefreshClient=Mn.USER_REFRESH_ACCOUNT_TYPE=void 0;var wE=rn(),AE=pt();Mn.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var gc=class r extends wE.OAuth2Client{_refreshToken;constructor(e,t,n,o,a){let u=e&&typeof e=="object"?e:{clientId:e,clientSecret:t,refreshToken:n,eagerRefreshThresholdMillis:o,forceRefreshOnFailure:a};super(u),this._refreshToken=u.refreshToken,this.credentials.refresh_token=u.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let t={...r.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e})};return AE.AuthClient.setMethodName(t,"fetchIdToken"),(await this.transporter.request(t)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,t){if(t)this.fromStreamAsync(e).then(()=>t(),t);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((t,n)=>{if(!e)return n(new Error("Must pass in a stream containing the user refresh token."));let o="";e.setEncoding("utf8").on("error",n).on("data",a=>o+=a).on("end",()=>{try{let a=JSON.parse(o);return this.fromJSON(a),t()}catch(a){return n(a)}})})}static fromJSON(e){let t=new r;return t.fromJSON(e),t}};Mn.UserRefreshClient=gc});var Cc=z($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.Impersonated=$n.IMPERSONATED_ACCOUNT_TYPE=void 0;var ym=rn(),DE=Je(),SE=jt();$n.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var _c=class r extends ym.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){if(super(e),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new ym.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,SE.originalOrCamelOptions)(e).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let t=`projects/-/serviceAccounts/${this.targetPrincipal}`,n=`${this.endpoint}/v1/${t}:signBlob`,o={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...r.RETRY_CONFIG,url:n,data:o,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,t=`${this.endpoint}/v1/${e}:generateAccessToken`,n={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},o=await this.sourceClient.request({...r.RETRY_CONFIG,url:t,data:n,method:"POST"}),a=o.data;return this.credentials.access_token=a.accessToken,this.credentials.expiry_date=Date.parse(a.expireTime),{tokens:this.credentials,res:o}}catch(e){if(!(e instanceof Error))throw e;let t=0,n="";throw e instanceof DE.GaxiosError&&(t=e?.response?.data?.error?.status,n=e?.response?.data?.error?.message),t&&n?(e.message=`${t}: unable to impersonate: ${n}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,t){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,o=`${this.endpoint}/v1/${n}:generateIdToken`,a={delegates:this.delegates,audience:e,includeEmail:t?.includeEmail??!0,useEmailAzp:t?.includeEmail??!0};return(await this.sourceClient.request({...r.RETRY_CONFIG,url:o,data:a,method:"POST"})).data.token}};$n.Impersonated=_c});var Ec=z(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.OAuthClientAuthHandler=void 0;ks.getErrorFromOAuthErrorResponse=RE;var Hn=Je(),vE=Cs(),TE=["PUT","POST","PATCH"],bc=class{#e=(0,vE.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new Hn.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new Hn.Gaxios)}applyClientAuthenticationOptions(e,t){e.headers=Hn.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,t),t||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,t){if(t)e.headers=Hn.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${t}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=Hn.Gaxios.mergeHeaders(e.headers);let n=this.#t.clientId,o=this.#t.clientSecret||"",a=this.#e.encodeBase64StringUtf8(`${n}:${o}`);Hn.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${a}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let t=(e.method||"GET").toUpperCase();if(!TE.includes(t))throw new Error(`${t} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let o=new Headers(e.headers).get("content-type");if(o?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let a=new URLSearchParams(e.data??"");a.append("client_id",this.#t.clientId),a.append("client_secret",this.#t.clientSecret||""),e.data=a}else if(o?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw new Error(`${o} content-types are not supported with ${this.#t.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};ks.OAuthClientAuthHandler=bc;function RE(r,e){let t=r.error,n=r.error_description,o=r.error_uri,a=`Error code ${t}`;typeof n<"u"&&(a+=`: ${n}`),typeof o<"u"&&(a+=` - ${o}`);let u=new Error(a);if(e){let l=Object.keys(e);e.stack&&l.push("stack"),l.forEach(f=>{f!=="message"&&Object.defineProperty(u,f,{value:e[f],writable:!1,enumerable:!0})})}return u}});var Ei=z(bi=>{"use strict";Object.defineProperty(bi,"__esModule",{value:!0});bi.StsCredentials=void 0;var kE=Je(),FE=pt(),_m=Ec(),OE=jt(),wc=class r extends _m.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},t){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:t}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,t,n){let o={grant_type:e.grantType,resource:e.resource,audience:e.audience,scope:e.scope?.join(" "),requested_token_type:e.requestedTokenType,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,actor_token:e.actingParty?.actorToken,actor_token_type:e.actingParty?.actorTokenType,options:n&&JSON.stringify(n)},a={...r.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:t,data:new URLSearchParams((0,OE.removeUndefinedValuesInObject)(o))};FE.AuthClient.setMethodName(a,"exchangeToken"),this.applyClientAuthenticationOptions(a);try{let u=await this.transporter.request(a),l=u.data;return l.res=u,l}catch(u){throw u instanceof kE.GaxiosError&&u.response?(0,_m.getErrorFromOAuthErrorResponse)(u.response.data,u):u}}};bi.StsCredentials=wc});var Ir=z(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.BaseExternalAccountClient=vt.CLOUD_RESOURCE_MANAGER=vt.EXTERNAL_ACCOUNT_TYPE=vt.EXPIRATION_TIME_OFFSET=void 0;var PE=Je(),xE=X("stream"),Ac=pt(),BE=Ei(),Cm=jt(),IE=ju(),NE="urn:ietf:params:oauth:grant-type:token-exchange",qE="urn:ietf:params:oauth:token-type:access_token",Dc="https://www.googleapis.com/auth/cloud-platform",jE=3600;vt.EXPIRATION_TIME_OFFSET=5*60*1e3;vt.EXTERNAL_ACCOUNT_TYPE="external_account";vt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var LE="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",UE="https://sts.{universeDomain}/v1/token",Sc=class r extends Ac.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let t=(0,Cm.originalOrCamelOptions)(e),n=t.get("type");if(n&&n!==vt.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${vt.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=t.get("client_id"),a=t.get("client_secret");this.tokenUrl=t.get("token_url")??UE.replace("{universeDomain}",this.universeDomain);let u=t.get("subject_token_type"),l=t.get("workforce_pool_user_project"),f=t.get("service_account_impersonation_url"),h=t.get("service_account_impersonation"),d=(0,Cm.originalOrCamelOptions)(h).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(t.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),o&&(this.clientAuth={confidentialClientType:"basic",clientId:o,clientSecret:a}),this.stsCredential=new BE.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=t.get("scopes")||[Dc],this.cachedAccessToken=null,this.audience=t.get("audience"),this.subjectTokenType=u,this.workforcePoolUserProject=l;let _=new RegExp(LE);if(this.workforcePoolUserProject&&!this.audience.match(_))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=f,this.serviceAccountImpersonationLifetime=d,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=jE),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(t)this.requestAsync(e).then(n=>t(null,n),n=>t(n,n.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let t=await this.getRequestHeaders(),n={...r.RETRY_CONFIG,headers:t,url:`${this.cloudResourceManagerURL.toString()}${e}`};Ac.AuthClient.setMethodName(n,"getProjectId");let o=await this.transporter.request(n);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,t=!1){let n;try{let o=await this.getRequestHeaders();e.headers=PE.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let a=o.response;if(a){let u=a.status,l=a.config.data instanceof xE.Readable;if(!t&&(u===401||u===403)&&!l&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),t={grantType:NE,audience:this.audience,requestedTokenType:qE,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[Dc]:this.getScopesArray()},n=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),a=await this.stsCredential.exchangeToken(t,o,n);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(a.access_token):a.expires_in?this.cachedAccessToken={access_token:a.access_token,expiry_date:new Date().getTime()+a.expires_in*1e3,res:a.res}:this.cachedAccessToken={access_token:a.access_token,res:a.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let t=e.match(/\/projects\/([^/]+)/);return t?t[1]:null}async getImpersonatedAccessToken(e){let t={...r.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"}};Ac.AuthClient.setMethodName(t,"getImpersonatedAccessToken");let n=await this.transporter.request(t),o=n.data;return{access_token:o.accessToken,expiry_date:new Date(o.expireTime).getTime(),res:n}}isExpired(e){let t=new Date().getTime();return e.expiry_date?t>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[Dc]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),t=this.serviceAccountImpersonationUrl!==void 0,n=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${IE.pkg.version} google-byoid-sdk source/${n} sa-impersonation/${t} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};vt.BaseExternalAccountClient=Sc});var bm=z(wi=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});wi.FileSubjectTokenSupplier=void 0;var Tc=X("util"),Rc=X("fs"),ME=(0,Tc.promisify)(Rc.readFile??(()=>{})),$E=(0,Tc.promisify)(Rc.realpath??(()=>{})),HE=(0,Tc.promisify)(Rc.lstat??(()=>{})),vc=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{if(e=await $E(e),!(await HE(e)).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let t,n=await ME(e,{encoding:"utf8"});if(this.formatType==="text"?t=n:this.formatType==="json"&&this.subjectTokenFieldName&&(t=JSON.parse(n)[this.subjectTokenFieldName]),!t)throw new Error("Unable to parse the subject_token from the credential_source file");return t}};wi.FileSubjectTokenSupplier=vc});var Em=z(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});Ai.UrlSubjectTokenSupplier=void 0;var GE=pt(),kc=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let t={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers};GE.AuthClient.setMethodName(t,"getSubjectToken");let n;if(this.formatType==="text"?n=(await e.transporter.request(t)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(n=(await e.transporter.request(t)).data[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source URL");return n}};Ai.UrlSubjectTokenSupplier=kc});var wm=z(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.CertificateSubjectTokenSupplier=_t.InvalidConfigurationError=_t.CertificateSourceUnavailableError=_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var Di=jt(),Si=X("fs"),vi=X("crypto"),WE=X("https");_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var Xt=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};_t.CertificateSourceUnavailableError=Xt;var Tt=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};_t.InvalidConfigurationError=Tt;var Fc=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Tt("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Tt("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Tt("Cannot create mTLS Agent with missing certificate or key");return new WE.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:t}=await this.#t();return{cert:this.cert,key:this.key}=await this.#r(e,t),await this.#n(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,Di.isValidFile)(e))return e;throw new Xt(`Provided certificate config path is invalid: ${e}`)}let t=process.env[_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(t){if(await(0,Di.isValidFile)(t))return t;throw new Xt(`Path from environment variable "${_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${t}`)}let n=(0,Di.getWellKnownCertificateConfigFileLocation)();if(await(0,Di.isValidFile)(n))return n;throw new Xt(`Could not find certificate configuration file. Searched override path, the "${_t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${n}).`)}async#t(){let e=this.certificateConfigPath,t;try{t=await Si.promises.readFile(e,"utf8")}catch{throw new Xt(`Failed to read certificate config file at: ${e}`)}try{let n=JSON.parse(t),o=n?.cert_configs?.workload?.cert_path,a=n?.cert_configs?.workload?.key_path;if(!o||!a)throw new Tt(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:a}}catch(n){throw n instanceof Tt?n:new Tt(`Failed to parse certificate config from ${e}: ${n.message}`)}}async#r(e,t){let n,o;try{n=await Si.promises.readFile(e),new vi.X509Certificate(n)}catch(a){let u=a instanceof Error?a.message:String(a);throw new Xt(`Failed to read certificate file at ${e}: ${u}`)}try{o=await Si.promises.readFile(t),(0,vi.createPrivateKey)(o)}catch(a){let u=a instanceof Error?a.message:String(a);throw new Xt(`Failed to read private key file at ${t}: ${u}`)}return{cert:n,key:o}}async#n(e){let t=new vi.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([t.raw.toString("base64")]);try{let a=((await Si.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((f,h)=>{try{return new vi.X509Certificate(f)}catch(d){let _=d instanceof Error?d.message:String(d);throw new Tt(`Failed to parse certificate at index ${h} in trust chain file ${this.trustChainPath}: ${_}`)}}),u=a.findIndex(f=>t.raw.equals(f.raw)),l;if(u===-1)l=[t,...a];else if(u===0)l=a;else throw new Tt(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${u}).`);return JSON.stringify(l.map(f=>f.raw.toString("base64")))}catch(n){if(n instanceof Tt)throw n;let o=n instanceof Error?n.message:String(n);throw new Xt(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};_t.CertificateSubjectTokenSupplier=Fc});var xc=z(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.IdentityPoolClient=void 0;var zE=Ir(),Oc=jt(),JE=bm(),VE=Em(),Am=wm(),KE=Ei(),Dm=Je(),Pc=class r extends zE.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let t=(0,Oc.originalOrCamelOptions)(e),n=t.get("credential_source"),o=t.get("subject_token_supplier");if(!n&&!o)throw new Error("A credential source or subject token supplier must be specified.");if(n&&o)throw new Error("Only one of credential source or subject token supplier can be specified.");if(o)this.subjectTokenSupplier=o,this.credentialSourceType="programmatic";else{let a=(0,Oc.originalOrCamelOptions)(n),u=(0,Oc.originalOrCamelOptions)(a.get("format")),l=u.get("type")||"text",f=u.get("subject_token_field_name");if(l!=="json"&&l!=="text")throw new Error(`Invalid credential_source format "${l}"`);if(l==="json"&&!f)throw new Error("Missing subject_token_field_name for JSON credential_source format");let h=a.get("file"),d=a.get("url"),_=a.get("certificate"),E=a.get("headers");if(h&&d||d&&_||h&&_)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(h)this.credentialSourceType="file",this.subjectTokenSupplier=new JE.FileSubjectTokenSupplier({filePath:h,formatType:l,subjectTokenFieldName:f});else if(d)this.credentialSourceType="url",this.subjectTokenSupplier=new VE.UrlSubjectTokenSupplier({url:d,formatType:l,subjectTokenFieldName:f,headers:E,additionalGaxiosOptions:r.RETRY_CONFIG});else if(_){this.credentialSourceType="certificate";let P=new Am.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:_.use_default_certificate_config,certificateConfigLocation:_.certificate_config_location,trustChainPath:_.trust_chain_path});this.subjectTokenSupplier=P}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof Am.CertificateSubjectTokenSupplier){let t=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new KE.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new Dm.Gaxios({agent:t})}),this.transporter=new Dm.Gaxios({...this.transporter.defaults||{},agent:t})}return e}};Ti.IdentityPoolClient=Pc});var Ic=z(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});ki.AwsRequestSigner=void 0;var Ri=Je(),vm=Cs(),Sm="AWS4-HMAC-SHA256",YE="aws4_request",Bc=class{getCredentials;region;crypto;constructor(e,t){this.getCredentials=e,this.region=t,this.crypto=(0,vm.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let t=typeof e.data=="object"?JSON.stringify(e.data):e.data,n=e.url,o=e.method||"GET",a=e.body||t,u=e.headers,l=await this.getCredentials(),f=new URL(n);if(typeof a!="string"&&a!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${a}`);let h=await QE({crypto:this.crypto,host:f.host,canonicalUri:f.pathname,canonicalQuerystring:f.search.slice(1),method:o,region:this.region,securityCredentials:l,requestPayload:a,additionalAmzHeaders:u}),d=Ri.Gaxios.mergeHeaders(h.amzDate?{"x-amz-date":h.amzDate}:{},{authorization:h.authorizationHeader,host:f.host},u||{});l.token&&Ri.Gaxios.mergeHeaders(d,{"x-amz-security-token":l.token});let _={url:n,method:o,headers:d};return a!==void 0&&(_.body=a),_}};ki.AwsRequestSigner=Bc;async function Fs(r,e,t){return await r.signWithHmacSha256(e,t)}async function XE(r,e,t,n,o){let a=await Fs(r,`AWS4${e}`,t),u=await Fs(r,a,n),l=await Fs(r,u,o);return await Fs(r,l,"aws4_request")}async function QE(r){let e=Ri.Gaxios.mergeHeaders(r.additionalAmzHeaders),t=r.requestPayload||"",n=r.host.split(".")[0],o=new Date,a=o.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),u=o.toISOString().replace(/[-]/g,"").replace(/T.*/,"");r.securityCredentials.token&&e.set("x-amz-security-token",r.securityCredentials.token);let l=Ri.Gaxios.mergeHeaders({host:r.host},e.has("date")?{}:{"x-amz-date":a},e),f="",h=[...l.keys()].sort();h.forEach(R=>{f+=`${R}:${l.get(R)} +`});let d=h.join(";"),_=await r.crypto.sha256DigestHex(t),E=`${r.method.toUpperCase()} +${r.canonicalUri} +${r.canonicalQuerystring} +${f} +${d} +${_}`,P=`${u}/${r.region}/${n}/${YE}`,v=`${Sm} +${a} +${P} +`+await r.crypto.sha256DigestHex(E),w=await XE(r.crypto,r.securityCredentials.secretAccessKey,u,r.region,n),g=await Fs(r.crypto,w,v),C=`${Sm} Credential=${r.securityCredentials.accessKeyId}/${P}, SignedHeaders=${d}, Signature=${(0,vm.fromArrayBufferToHex)(g)}`;return{amzDate:e.has("date")?void 0:a,authorizationHeader:C,canonicalQuerystring:r.canonicalQuerystring}}});var Tm=z(Oi=>{"use strict";Object.defineProperty(Oi,"__esModule",{value:!0});Oi.DefaultAwsSecurityCredentialsSupplier=void 0;var Fi=pt(),Nc=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#n)return this.#n;let t=new Headers;if(!this.#n&&this.imdsV2SessionTokenUrl&&t.set("x-aws-ec2-metadata-token",await this.#e(e.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let n={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",headers:t};Fi.AuthClient.setMethodName(n,"getAwsRegion");let o=await e.transporter.request(n);return o.data.substr(0,o.data.length-1)}async getAwsSecurityCredentials(e){if(this.#s)return this.#s;let t=new Headers;this.imdsV2SessionTokenUrl&&t.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let n=await this.#t(t,e.transporter),o=await this.#r(n,t,e.transporter);return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,token:o.Token}}async#e(e){let t={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return Fi.AuthClient.setMethodName(t,"#getImdsV2SessionToken"),(await e.request(t)).data}async#t(e,t){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let n={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",headers:e};return Fi.AuthClient.setMethodName(n,"#getAwsRoleName"),(await t.request(n)).data}async#r(e,t,n){let o={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:t};return Fi.AuthClient.setMethodName(o,"#retrieveAwsSecurityCredentials"),(await n.request(o)).data}get#n(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#s(){return process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY?{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN}:null}};Oi.DefaultAwsSecurityCredentialsSupplier=Nc});var jc=z(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});Pi.AwsClient=void 0;var ZE=Ic(),ew=Ir(),tw=Tm(),Rm=jt(),rw=Je(),qc=class r extends ew.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);let t=(0,Rm.originalOrCamelOptions)(e),n=t.get("credential_source"),o=t.get("aws_security_credentials_supplier");if(!n&&!o)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(n&&o)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(o)this.awsSecurityCredentialsSupplier=o,this.regionalCredVerificationUrl=r.#e,this.credentialSourceType="programmatic";else{let a=(0,Rm.originalOrCamelOptions)(n);this.environmentId=a.get("environment_id");let u=a.get("region_url"),l=a.get("url"),f=a.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new tw.DefaultAwsSecurityCredentialsSupplier({regionUrl:u,securityCredentialsUrl:l,imdsV2SessionTokenUrl:f}),this.regionalCredVerificationUrl=a.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(parseInt(e[2],10)!==1)throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new ZE.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let e=await this.awsRequestSigner.getRequestOptions({...r.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),t=[];return rw.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,a)=>t.push({key:a,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:t}))}};Pi.AwsClient=qc});var Hc=z(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.InvalidSubjectTokenError=qe.InvalidMessageFieldError=qe.InvalidCodeFieldError=qe.InvalidTokenTypeFieldError=qe.InvalidExpirationTimeFieldError=qe.InvalidSuccessFieldError=qe.InvalidVersionFieldError=qe.ExecutableResponseError=qe.ExecutableResponse=void 0;var xi="urn:ietf:params:oauth:token-type:saml2",Lc="urn:ietf:params:oauth:token-type:id_token",Uc="urn:ietf:params:oauth:token-type:jwt",Mc=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new Bi("Executable response must contain a 'version' field.");if(e.success===void 0)throw new Ii("Executable response must contain a 'success' field.");if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==xi&&this.tokenType!==Lc&&this.tokenType!==Uc)throw new Ni(`Executable response must contain a 'token_type' field when successful and it must be one of ${Lc}, ${Uc}, or ${xi}.`);if(this.tokenType===xi){if(!e.saml_response)throw new Os(`Executable response must contain a 'saml_response' field when token_type=${xi}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Os(`Executable response must contain a 'id_token' field when token_type=${Lc} or ${Uc}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new qi("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new ji("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.PluggableAuthHandler=Gn.ExecutableError=void 0;var nn=Hc(),nw=X("child_process"),Gc=X("fs"),Li=class extends Error{code;constructor(e,t){super(`The executable failed with exit code: ${t} and error message: ${e}.`),this.code=t,Object.setPrototypeOf(this,new.target.prototype)}};Gn.ExecutableError=Li;var Wc=class r{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw new Error("No command provided.");if(this.commandComponents=r.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((t,n)=>{let o=nw.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),a="";o.stdout.on("data",l=>{a+=l}),o.stderr.on("data",l=>{a+=l});let u=setTimeout(()=>(o.removeAllListeners(),o.kill(),n(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);o.on("close",l=>{if(clearTimeout(u),l===0)try{let f=JSON.parse(a),h=new nn.ExecutableResponse(f);return t(h)}catch(f){return f instanceof nn.ExecutableResponseError?n(f):n(new nn.ExecutableResponseError(`The executable returned an invalid response: ${a}`))}else return n(new Li(a,l.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Gc.promises.realpath(this.outputFile)}catch{return}if(!(await Gc.promises.lstat(e)).isFile())return;let t=await Gc.promises.readFile(e,{encoding:"utf8"});if(t!=="")try{let n=JSON.parse(t);return new nn.ExecutableResponse(n).isValid()?new nn.ExecutableResponse(n):void 0}catch(n){throw n instanceof nn.ExecutableResponseError?n:new nn.ExecutableResponseError(`The output file contained an invalid response: ${t}`)}}static parseCommand(e){let t=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!t)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let n=0;n{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.PluggableAuthClient=Wn.ExecutableError=void 0;var sw=Ir(),ow=Hc(),km=zc(),iw=zc();Object.defineProperty(Wn,"ExecutableError",{enumerable:!0,get:function(){return iw.ExecutableError}});var aw=30*1e3,Fm=5*1e3,Om=120*1e3,uw="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",Pm=1,Jc=class extends sw.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=aw;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillisOm)throw new Error(`Timeout must be between ${Fm} and ${Om} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new km.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[uw]!=="1")throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let t=new Map;t.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),t.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),t.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&t.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let n=this.getServiceAccountEmail();n&&t.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",n),e=await this.handler.retrieveResponseFromExecutable(t)}if(e.version>Pm)throw new Error(`Version of executable is not currently supported, maximum supported version is ${Pm}.`);if(!e.success)throw new km.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new ow.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw new Error("Executable response is expired.");return e.subjectToken}};Wn.PluggableAuthClient=Jc});var Yc=z(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.ExternalAccountClient=void 0;var cw=Ir(),lw=xc(),fw=jc(),dw=Vc(),Kc=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return e&&e.type===cw.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new fw.AwsClient(e):e.credential_source?.executable?new dw.PluggableAuthClient(e):new lw.IdentityPoolClient(e):null}};Ui.ExternalAccountClient=Kc});var Nm=z(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.ExternalAccountAuthorizedUserClient=zn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var Bm=pt(),xm=Ec(),Im=Je(),hw=X("stream"),pw=Ir();zn.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var mw="https://sts.{universeDomain}/v1/oauthtoken",Xc=class r extends xm.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,t){let n={...r.RETRY_CONFIG,url:this.#e,method:"POST",headers:t,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e})};Bm.AuthClient.setMethodName(n,"refreshToken"),this.applyClientAuthenticationOptions(n);try{let o=await this.transporter.request(n),a=o.data;return a.res=o,a}catch(o){throw o instanceof Im.GaxiosError&&o.response?(0,xm.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},Qc=class extends Bm.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let t={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new Xc({tokenRefreshEndpoint:e.token_url??mw.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:t}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=pw.EXPIRATION_TIME_OFFSET:this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(t)this.requestAsync(e).then(n=>t(null,n),n=>t(n,n.response));else return this.requestAsync(e)}async requestAsync(e,t=!1){let n;try{let o=await this.getRequestHeaders();e.headers=Im.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let a=o.response;if(a){let u=a.status,l=a.config.data instanceof hw.Readable;if(!t&&(u===401||u===403)&&!l&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1e3,res:e.res},e.refresh_token!==void 0&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let t=new Date().getTime();return e.expiry_date?t>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};zn.ExternalAccountAuthorizedUserClient=Qc});var Um=z($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.GoogleAuth=$t.GoogleAuthExceptionMessages=void 0;var gw=X("child_process"),Ps=X("fs"),yw=Je(),xs=_s(),_w=X("os"),Zc=X("path"),Cw=Cs(),bw=Ju(),Ew=Ku(),ww=Yu(),Jn=mc(),qm=yc(),Vn=Cc(),Aw=Yc(),Bs=Ir(),el=pt(),jm=Nm(),Lm=jt();$t.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment. +To learn more about authentication and Google APIs, visit: +https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment. +To learn more about authentication and Google APIs, visit: +https://cloud.google.com/docs/authentication/getting-started`,NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:`Unable to detect a Universe Domain in the current environment. +To learn more about Universe Domain retrieval, visit: +https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var tl=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError($t.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);e.universeDomain&&(this.clientOptions.universeDomain=e.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then(t=>e(null,t),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===$t.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId(),e)return this._cachedProjectId=e,e;throw new Error($t.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await xs.universe("universe-domain"),e||=el.DEFAULT_UNIVERSE}catch(t){if(t&&t?.response?.status===404)e=el.DEFAULT_UNIVERSE;else throw t}return e}async getUniverseDomain(){let e=(0,Lm.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=el.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},t){let n;if(typeof e=="function"?t=e:n=e,t)this.getApplicationDefaultAsync(n).then(o=>t(null,o.credential,o.projectId),t);else return this.getApplicationDefaultAsync(n)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let t;if(t=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),t)return t instanceof Jn.JWT?t.scopes=this.scopes:t instanceof Bs.BaseExternalAccountClient&&(t.scopes=this.getAnyScopes()),await this.#t(t);if(t=await this._tryGetApplicationCredentialsFromWellKnownFile(e),t)return t instanceof Jn.JWT?t.scopes=this.scopes:t instanceof Bs.BaseExternalAccountClient&&(t.scopes=this.getAnyScopes()),await this.#t(t);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new bw.Compute(e));throw new Error($t.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,t=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let n=await this.getProjectIdOptional();return t&&(e.quotaProjectId=t),this.cachedCredential=e,{credential:e,projectId:n}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=xs.getGCPResidency()||await xs.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let t=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!t||t.length===0)return null;try{return this._getApplicationCredentialsFromFilePath(t,e)}catch(n){throw n instanceof Error&&(n.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${n.message}`),n}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let t=null;if(this._isWindows())t=process.env.APPDATA;else{let o=process.env.HOME;o&&(t=Zc.join(o,".config"))}return t&&(t=Zc.join(t,"gcloud","application_default_credentials.json"),Ps.existsSync(t)||(t=null)),t?await this._getApplicationCredentialsFromFilePath(t,e):null}async _getApplicationCredentialsFromFilePath(e,t={}){if(!e||e.length===0)throw new Error("The file path is invalid.");try{if(e=Ps.realpathSync(e),!Ps.lstatSync(e).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let n=Ps.createReadStream(e);return this.fromStream(n,t)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==Vn.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Vn.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");let t=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let n=/(?[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!n)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let o=this.getAnyScopes()??[];return new Vn.Impersonated({...e,sourceClient:t,targetPrincipal:n,targetScopes:Array.isArray(o)?o:[o]})}fromJSON(e,t={}){let n,o=(0,Lm.originalOrCamelOptions)(t).get("universe_domain");return e.type===qm.USER_REFRESH_ACCOUNT_TYPE?(n=new qm.UserRefreshClient(t),n.fromJSON(e)):e.type===Vn.IMPERSONATED_ACCOUNT_TYPE?n=this.fromImpersonatedJSON(e):e.type===Bs.EXTERNAL_ACCOUNT_TYPE?(n=Aw.ExternalAccountClient.fromJSON({...e,...t}),n.scopes=this.getAnyScopes()):e.type===jm.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?n=new jm.ExternalAccountAuthorizedUserClient({...e,...t}):(t.scopes=this.scopes,n=new Jn.JWT(t),this.setGapicJWTValues(n),n.fromJSON(e)),o&&(n.universeDomain=o),n}_cacheClientFromJSON(e,t){let n=this.fromJSON(e,t);return this.jsonContent=e,this.cachedCredential=n,n}fromStream(e,t={},n){let o={};if(typeof t=="function"?n=t:o=t,n)this.fromStreamAsync(e,o).then(a=>n(null,a),n);else return this.fromStreamAsync(e,o)}fromStreamAsync(e,t){return new Promise((n,o)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");let a=[];e.setEncoding("utf8").on("error",o).on("data",u=>a.push(u)).on("end",()=>{try{try{let u=JSON.parse(a.join("")),l=this._cacheClientFromJSON(u,t);return n(l)}catch(u){if(!this.keyFilename)throw u;let l=new Jn.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=l,this.setGapicJWTValues(l),n(l)}}catch(u){return o(u)}})})}fromAPIKey(e,t={}){return new Jn.JWT({...t,apiKey:e})}_isWindows(){let e=_w.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,gw.exec)("gcloud config config-helper --format json",(t,n)=>{if(!t&&n)try{let o=JSON.parse(n).configuration.properties.core.project;e(o);return}catch{}e(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let t=await this.getClient();if(t&&t.projectId)return t.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==Bs.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await xs.project("project-id")}catch{return null}}getCredentials(e){if(e)this.getCredentialsAsync().then(t=>e(null,t),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof Vn.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof Bs.BaseExternalAccountClient){let t=e.getServiceAccountEmail();if(t)return{client_email:t,universe_domain:e.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[t,n]=await Promise.all([xs.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:t,universe_domain:n}}throw new Error($t.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#r();try{return await this.#e}finally{this.#e=null}}async#r(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=Zc.resolve(this.keyFilename),t=Ps.createReadStream(e);return await this.fromStreamAsync(t,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:t}=await this.#t(e);return t}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let t=await this.getClient();if(!("fetchIdToken"in t))throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new Ew.IdTokenClient({targetAudience:e,idTokenProvider:t})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let t=e.url,o=await(await this.getClient()).getRequestHeaders(t);return e.headers=yw.Gaxios.mergeHeaders(e.headers,o),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,ww.getEnv)()}async sign(e,t){let n=await this.getClient(),o=await this.getUniverseDomain();if(t=t||`https://iamcredentials.${o}/v1/projects/-/serviceAccounts/`,n instanceof Vn.Impersonated)return(await n.sign(e)).signedBlob;let a=(0,Cw.createCrypto)();if(n instanceof Jn.JWT&&n.key)return await a.sign(n.key,e);let u=await this.getCredentials();if(!u.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(a,u.client_email,e,t)}async signBlob(e,t,n,o){let a=new URL(o+`${t}:signBlob`);return(await this.request({method:"POST",url:a.href,data:{payload:e.encodeBase64StringUtf8(n)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};$t.GoogleAuth=tl});var Mm=z(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});Mi.IAMAuth=void 0;var rl=class{selector;token;constructor(e,t){this.selector=e,this.token=t,this.selector=e,this.token=t}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};Mi.IAMAuth=rl});var $m=z(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.DownscopedClient=Zt.EXPIRATION_TIME_OFFSET=Zt.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var Dw=Je(),Sw=X("stream"),nl=pt(),vw=Ei(),Tw="urn:ietf:params:oauth:grant-type:token-exchange",Rw="urn:ietf:params:oauth:token-type:access_token",kw="urn:ietf:params:oauth:token-type:access_token";Zt.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;Zt.EXPIRATION_TIME_OFFSET=5*60*1e3;var sl=class extends nl.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,t={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof nl.AuthClient?{}:e),e instanceof nl.AuthClient?(this.authClient=e,this.credentialAccessBoundary=t):(this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>Zt.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${Zt.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let n of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(n.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new vw.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),t=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(t)}request(e,t){if(t)this.requestAsync(e).then(n=>t(null,n),n=>t(n,n.response));else return this.requestAsync(e)}async requestAsync(e,t=!1){let n;try{let o=await this.getRequestHeaders();e.headers=Dw.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),n=await this.transporter.request(e)}catch(o){let a=o.response;if(a){let u=a.status,l=a.config.data instanceof Sw.Readable;if(!t&&(u===401||u===403)&&!l&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return n}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,t={grantType:Tw,requestedTokenType:Rw,subjectToken:e,subjectTokenType:kw},n=await this.stsCredential.exchangeToken(t,void 0,this.credentialAccessBoundary),o=this.authClient.credentials?.expiry_date||null,a=n.expires_in?new Date().getTime()+n.expires_in*1e3:o;return this.cachedDownscopedAccessToken={access_token:n.access_token,expiry_date:a,res:n.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){let t=new Date().getTime();return e.expiry_date?t>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};Zt.DownscopedClient=sl});var Hm=z($i=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});$i.PassThroughClient=void 0;var Fw=pt(),ol=class extends Fw.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};$i.PassThroughClient=ol});var al=z(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.GoogleAuth=ee.auth=ee.PassThroughClient=ee.ExecutableError=ee.PluggableAuthClient=ee.DownscopedClient=ee.BaseExternalAccountClient=ee.ExternalAccountClient=ee.IdentityPoolClient=ee.AwsRequestSigner=ee.AwsClient=ee.UserRefreshClient=ee.LoginTicket=ee.ClientAuthentication=ee.OAuth2Client=ee.CodeChallengeMethod=ee.Impersonated=ee.JWT=ee.JWTAccess=ee.IdTokenClient=ee.IAMAuth=ee.GCPEnv=ee.Compute=ee.DEFAULT_UNIVERSE=ee.AuthClient=ee.gaxios=ee.gcpMetadata=void 0;var Gm=Um();Object.defineProperty(ee,"GoogleAuth",{enumerable:!0,get:function(){return Gm.GoogleAuth}});ee.gcpMetadata=_s();ee.gaxios=Je();var Wm=pt();Object.defineProperty(ee,"AuthClient",{enumerable:!0,get:function(){return Wm.AuthClient}});Object.defineProperty(ee,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return Wm.DEFAULT_UNIVERSE}});var Ow=Ju();Object.defineProperty(ee,"Compute",{enumerable:!0,get:function(){return Ow.Compute}});var Pw=Yu();Object.defineProperty(ee,"GCPEnv",{enumerable:!0,get:function(){return Pw.GCPEnv}});var xw=Mm();Object.defineProperty(ee,"IAMAuth",{enumerable:!0,get:function(){return xw.IAMAuth}});var Bw=Ku();Object.defineProperty(ee,"IdTokenClient",{enumerable:!0,get:function(){return Bw.IdTokenClient}});var Iw=hc();Object.defineProperty(ee,"JWTAccess",{enumerable:!0,get:function(){return Iw.JWTAccess}});var Nw=mc();Object.defineProperty(ee,"JWT",{enumerable:!0,get:function(){return Nw.JWT}});var qw=Cc();Object.defineProperty(ee,"Impersonated",{enumerable:!0,get:function(){return qw.Impersonated}});var il=rn();Object.defineProperty(ee,"CodeChallengeMethod",{enumerable:!0,get:function(){return il.CodeChallengeMethod}});Object.defineProperty(ee,"OAuth2Client",{enumerable:!0,get:function(){return il.OAuth2Client}});Object.defineProperty(ee,"ClientAuthentication",{enumerable:!0,get:function(){return il.ClientAuthentication}});var jw=Hu();Object.defineProperty(ee,"LoginTicket",{enumerable:!0,get:function(){return jw.LoginTicket}});var Lw=yc();Object.defineProperty(ee,"UserRefreshClient",{enumerable:!0,get:function(){return Lw.UserRefreshClient}});var Uw=jc();Object.defineProperty(ee,"AwsClient",{enumerable:!0,get:function(){return Uw.AwsClient}});var Mw=Ic();Object.defineProperty(ee,"AwsRequestSigner",{enumerable:!0,get:function(){return Mw.AwsRequestSigner}});var $w=xc();Object.defineProperty(ee,"IdentityPoolClient",{enumerable:!0,get:function(){return $w.IdentityPoolClient}});var Hw=Yc();Object.defineProperty(ee,"ExternalAccountClient",{enumerable:!0,get:function(){return Hw.ExternalAccountClient}});var Gw=Ir();Object.defineProperty(ee,"BaseExternalAccountClient",{enumerable:!0,get:function(){return Gw.BaseExternalAccountClient}});var Ww=$m();Object.defineProperty(ee,"DownscopedClient",{enumerable:!0,get:function(){return Ww.DownscopedClient}});var zm=Vc();Object.defineProperty(ee,"PluggableAuthClient",{enumerable:!0,get:function(){return zm.PluggableAuthClient}});Object.defineProperty(ee,"ExecutableError",{enumerable:!0,get:function(){return zm.ExecutableError}});var zw=Hm();Object.defineProperty(ee,"PassThroughClient",{enumerable:!0,get:function(){return zw.PassThroughClient}});var Jw=new Gm.GoogleAuth;ee.auth=Jw});import eA from"fastify";import tA from"@fastify/cors";var Nf=zr(Ma(),1);import{readFileSync as t0,existsSync as Bf}from"fs";import{join as If}from"path";import{config as r0}from"dotenv";var mo=class{config={};options;constructor(e={jsonPath:"./config.json"}){this.options={envPath:e.envPath||".env",jsonPath:e.jsonPath,useEnvFile:!1,useJsonFile:e.useJsonFile!==!1,useEnvironmentVariables:e.useEnvironmentVariables!==!1,...e},this.loadConfig()}loadConfig(){this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),this.options.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useEnvFile&&this.loadEnvConfig(),this.config.LOG_FILE&&(process.env.LOG_FILE=this.config.LOG_FILE),this.config.LOG&&(process.env.LOG=this.config.LOG)}loadJsonConfig(){if(!this.options.jsonPath)return;let e=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:If(process.cwd(),this.options.jsonPath);if(Bf(e))try{let t=t0(e,"utf-8"),n=Nf.default.parse(t);this.config={...this.config,...n},console.log(`Loaded JSON config from: ${e}`)}catch(t){console.warn(`Failed to load JSON config from ${e}:`,t)}else console.warn(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:If(process.cwd(),this.options.envPath);if(Bf(e))try{let t=r0({path:e});t.parsed&&(this.config={...this.config,...this.parseEnvConfig(t.parsed)})}catch(t){console.warn(`Failed to load .env config from ${e}:`,t)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let t={};return Object.assign(t,e),t}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,t){let n=this.config[e];return n!==void 0?n:t}getAll(){return{...this.config}}getHttpsProxy(){return this.get("HTTPS_PROXY")||this.get("https_proxy")||this.get("httpsProxy")||this.get("PROXY_URL")}has(e){return this.config[e]!==void 0}set(e,t){this.config[e]=t}reload(){this.config={},this.loadConfig()}getConfigSummary(){let e=[];return this.options.initialConfig&&e.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&e.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&e.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&e.push("Environment Variables"),`Config sources: ${e.join(", ")}`}};function nt(r,e=500,t="internal_error",n="api_error"){let o=new Error(r);return o.statusCode=e,o.code=t,o.type=n,o}async function qf(r,e,t){e.log.error(r);let n=r.statusCode||500,o={error:{message:r.message+r.stack||"Internal Server Error",type:r.type||"api_error",code:r.code||"internal_error"}};return t.code(n).send(o)}import{ProxyAgent as n0}from"undici";function jf(r,e,t,n){let o=new Headers({"Content-Type":"application/json"});t.headers&&Object.entries(t.headers).forEach(([f,h])=>{h&&o.set(f,h)});let a,u=AbortSignal.timeout(t.TIMEOUT??60*1e3*60);if(t.signal){let f=new AbortController,h=()=>f.abort();t.signal.addEventListener("abort",h),u.addEventListener("abort",h),a=f.signal}else a=u;let l={method:"POST",headers:o,body:JSON.stringify(e),signal:a};return t.httpsProxy&&(l.dispatcher=new n0(new URL(t.httpsProxy).toString())),n?.debug({request:l,headers:Object.fromEntries(o.entries()),requestUrl:typeof r=="string"?r:r.toString(),useProxy:t.httpsProxy},"final request"),fetch(typeof r=="string"?r:r.toString(),l)}var Lf="1.0.28";async function o0(r,e,t,n){let o=r.body,a=r.provider,u=t._server.providerService.getProvider(a);if(!u)throw nt(`Provider '${a}' not found`,404,"provider_not_found");let{requestBody:l,config:f,bypass:h}=await i0(o,u,n,r.headers),d=await u0(l,f,u,t,h,n),_=await c0(l,d,u,n,h);return l0(_,e,o)}async function i0(r,e,t,n){let o=r,a={},u=!1;if(u=a0(e,t,r),u&&(n instanceof Headers?n.delete("content-length"):delete n["content-length"],a.headers=n),!u&&typeof t.transformRequestOut=="function"){let l=await t.transformRequestOut(o);l.body?(o=l.body,a=l.config||{}):o=l}if(!u&&e.transformer?.use?.length)for(let l of e.transformer.use){if(!l||typeof l.transformRequestIn!="function")continue;let f=await l.transformRequestIn(o,e);f.body?(o=f.body,a={...a,...f.config}):o=f}if(!u&&e.transformer?.[r.model]?.use?.length)for(let l of e.transformer[r.model].use)!l||typeof l.transformRequestIn!="function"||(o=await l.transformRequestIn(o,e));return{requestBody:o,config:a,bypass:u}}function a0(r,e,t){return r.transformer?.use?.length===1&&r.transformer.use[0].name===e.name&&(!r.transformer?.[t.model]?.use.length||r.transformer?.[t.model]?.use.length===1&&r.transformer?.[t.model]?.use[0].name===e.name)}async function u0(r,e,t,n,o,a){let u=e.url||new URL(t.baseUrl);if(o&&typeof a.auth=="function"){let f=await a.auth(r,t);if(f.body){r=f.body;let h=e.headers||{};f.config?.headers&&(h={...h,...f.config.headers},delete h.host,delete f.config.headers),e={...e,...f.config,headers:h}}else r=f}let l=await jf(u,r,{httpsProxy:n._server.configService.getHttpsProxy(),...e,headers:{Authorization:`Bearer ${t.apiKey}`,...e?.headers||{}}},n.log);if(!l.ok){let f=await l.text();throw nt(`Error from provider(${t.name},${r.model}: ${l.status}): ${f}`,l.status,"provider_response_error")}return l}async function c0(r,e,t,n,o){let a=e;if(!o&&t.transformer?.use?.length)for(let u of Array.from(t.transformer.use).reverse())!u||typeof u.transformResponseOut!="function"||(a=await u.transformResponseOut(a));if(!o&&t.transformer?.[r.model]?.use?.length)for(let u of Array.from(t.transformer[r.model].use).reverse())!u||typeof u.transformResponseOut!="function"||(a=await u.transformResponseOut(a));return!o&&n.transformResponseIn&&(a=await n.transformResponseIn(a)),a}function l0(r,e,t){return r.ok||e.code(r.status),t.stream===!0?(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),e.send(r.body)):r.json()}var Uf=async r=>{r.get("/",async()=>({message:"LLMs API",version:Lf})),r.get("/health",async()=>({status:"ok",timestamp:new Date().toISOString()}));let e=r._server.transformerService.getTransformersWithEndpoint();for(let{transformer:t}of e)t.endPoint&&r.post(t.endPoint,async(n,o)=>o0(n,o,r,t));r.post("/providers",{schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(t,n)=>{let{name:o,baseUrl:a,apiKey:u,models:l}=t.body;if(!o?.trim())throw nt("Provider name is required",400,"invalid_request");if(!a||!f0(a))throw nt("Valid base URL is required",400,"invalid_request");if(!u?.trim())throw nt("API key is required",400,"invalid_request");if(!l||!Array.isArray(l)||l.length===0)throw nt("At least one model is required",400,"invalid_request");if(r._server.providerService.getProvider(t.body.name))throw nt(`Provider with name '${t.body.name}' already exists`,400,"provider_exists");return r._server.providerService.registerProvider(t.body)}),r.get("/providers",async()=>r._server.providerService.getProviders()),r.get("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{let n=r._server.providerService.getProvider(t.params.id);if(!n)throw nt("Provider not found",404,"provider_not_found");return n}),r.put("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},enabled:{type:"boolean"}}}}},async(t,n)=>{let o=r._server.providerService.updateProvider(t.params.id,t.body);if(!o)throw nt("Provider not found",404,"provider_not_found");return o}),r.delete("/providers/:id",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async t=>{if(!r._server.providerService.deleteProvider(t.params.id))throw nt("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),r.patch("/providers/:id/toggle",{schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(t,n)=>{if(!r._server.providerService.toggleProvider(t.params.id,t.body.enabled))throw nt("Provider not found",404,"provider_not_found");return{message:`Provider ${t.body.enabled?"enabled":"disabled"} successfully`}})};function f0(r){try{return new URL(r),!0}catch{return!1}}var go=class{constructor(e){this.providerService=e}registerProvider(e){return this.providerService.registerProvider(e)}getProviders(){return this.providerService.getProviders()}getProvider(e){return this.providerService.getProvider(e)}updateProvider(e,t){return this.providerService.updateProvider(e,t)}deleteProvider(e){return this.providerService.deleteProvider(e)}toggleProvider(e,t){return this.providerService.toggleProvider(e,t)}resolveRoute(e){let t=this.providerService.resolveModelRoute(e);if(!t)throw new Error(`Model ${e} not found. Available models: ${this.getAvailableModelNames().join(", ")}`);return t}async getAvailableModels(){return{object:"list",data:this.providerService.getAvailableModels().flatMap(t=>t.models.map(n=>({id:n,object:"model",provider:t.provider,created:Math.floor(Date.now()/1e3),owned_by:t.provider})))}}getAvailableModelNames(){return this.providerService.getModelRoutes().map(e=>e.fullModel)}getModelRoutes(){return this.providerService.getModelRoutes()}};var yo=class{constructor(e,t,n){this.configService=e;this.transformerService=t;this.logger=n;this.initializeCustomProviders()}providers=new Map;modelRoutes=new Map;initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(t=>{try{if(!t.name||!t.api_base_url||!t.api_key)return;let n={};t.transformer&&Object.keys(t.transformer).forEach(o=>{o==="use"?Array.isArray(t.transformer.use)&&(n.use=t.transformer.use.map(a=>{if(Array.isArray(a)&&typeof a[0]=="string"){let u=this.transformerService.getTransformer(a[0]);if(u)return new u(a[1])}if(typeof a=="string"){let u=this.transformerService.getTransformer(a);return typeof u=="function"?new u:u}}).filter(a=>typeof a<"u")):Array.isArray(t.transformer[o]?.use)&&(n[o]={use:t.transformer[o].use.map(a=>{if(Array.isArray(a)&&typeof a[0]=="string"){let u=this.transformerService.getTransformer(a[0]);if(u)return new u(a[1])}if(typeof a=="string"){let u=this.transformerService.getTransformer(a);return typeof u=="function"?new u:u}}).filter(a=>typeof a<"u")})}),this.registerProvider({name:t.name,baseUrl:t.api_base_url,apiKey:t.api_key,models:t.models||[],transformer:t.transformer?n:void 0}),this.logger.info(`${t.name} provider registered`)}catch(n){this.logger.error(`${t.name} provider registered error: ${n}`)}})}registerProvider(e){let t={...e};return this.providers.set(t.name,t),e.models.forEach(n=>{let o=`${t.name},${n}`,a={provider:t.name,model:n,fullModel:o};this.modelRoutes.set(o,a),this.modelRoutes.has(n)||this.modelRoutes.set(n,a)}),t}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,t){let n=this.providers.get(e);if(!n)return null;let o={...n,...t,updatedAt:new Date};return this.providers.set(e,o),t.models&&(n.models.forEach(a=>{let u=`${n.id},${a}`;this.modelRoutes.delete(u),this.modelRoutes.delete(a)}),t.models.forEach(a=>{let u=`${n.name},${a}`,l={provider:n.name,model:a,fullModel:u};this.modelRoutes.set(u,l),this.modelRoutes.has(a)||this.modelRoutes.set(a,l)})),o}deleteProvider(e){let t=this.providers.get(e);return t?(t.models.forEach(n=>{let o=`${t.name},${n}`;this.modelRoutes.delete(o),this.modelRoutes.delete(n)}),this.providers.delete(e),!0):!1}toggleProvider(e,t){return!!this.providers.get(e)}resolveModelRoute(e){let t=this.modelRoutes.get(e);if(!t)return null;let n=this.providers.get(t.provider);return n?{provider:n,originalModel:e,targetModel:t.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(t=>{t.models.forEach(n=>{e.push(n),e.push(`${t.name},${n}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((t,n)=>{if(Array.isArray(n)){let[o,a={}]=n;t[o]=a}else t[n]={};return t},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(t=>{t.models.forEach(n=>{e.push({id:n,object:"model",owned_by:t.name,provider:t.name}),e.push({id:`${t.name},${n}`,object:"model",owned_by:t.name,provider:t.name})})}),{object:"list",data:e}}};var ze=[];for(let r=0;r<256;++r)ze.push((r+256).toString(16).slice(1));function Mf(r,e=0){return(ze[r[e+0]]+ze[r[e+1]]+ze[r[e+2]]+ze[r[e+3]]+"-"+ze[r[e+4]]+ze[r[e+5]]+"-"+ze[r[e+6]]+ze[r[e+7]]+"-"+ze[r[e+8]]+ze[r[e+9]]+"-"+ze[r[e+10]]+ze[r[e+11]]+ze[r[e+12]]+ze[r[e+13]]+ze[r[e+14]]+ze[r[e+15]]).toLowerCase()}import{randomFillSync as d0}from"crypto";var Co=new Uint8Array(256),_o=Co.length;function $a(){return _o>Co.length-16&&(d0(Co),_o=0),Co.slice(_o,_o+=16)}import{randomUUID as h0}from"crypto";var Ha={randomUUID:h0};function p0(r,e,t){if(Ha.randomUUID&&!e&&!r)return Ha.randomUUID();r=r||{};let n=r.random??r.rng?.()??$a();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(t=t||0,t<0||t+16>e.length)throw new RangeError(`UUID byte range ${t}:${t+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[t+o]=n[o];return e}return Mf(n)}var Tr=p0;var $f=r=>r<=0?"none":r<=1024?"low":r<=8192?"medium":"high";var bo=class{name="Anthropic";endPoint="/v1/messages";async auth(e,t){return{body:e,config:{headers:{"x-api-key":t.apiKey,authorization:void 0}}}}async transformRequestOut(e){let t=[];if(e.system){if(typeof e.system=="string")t.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let a=e.system.filter(u=>u.type==="text"&&u.text).map(u=>({type:"text",text:u.text,cache_control:u.cache_control}));t.push({role:"system",content:a})}}JSON.parse(JSON.stringify(e.messages||[]))?.forEach((a,u)=>{if(a.role==="user"||a.role==="assistant"){if(typeof a.content=="string"){t.push({role:a.role,content:a.content});return}if(Array.isArray(a.content)){if(a.role==="user"){let l=a.content.filter(h=>h.type==="tool_result"&&h.tool_use_id);l.length&&l.forEach((h,d)=>{let _={role:"tool",content:typeof h.content=="string"?h.content:JSON.stringify(h.content),tool_call_id:h.tool_use_id,cache_control:h.cache_control};t.push(_)});let f=a.content.filter(h=>h.type==="text"&&h.text||h.type==="image"&&h.source);f.length&&t.push({role:"user",content:f.map(h=>h?.type==="image"?{type:"image_url",image_url:{url:h.source?.type==="base64"?h.source.data:h.source.url},media_type:h.source.media_type}:h)})}else if(a.role==="assistant"){let l={role:"assistant",content:null},f=a.content.filter(d=>d.type==="text"&&d.text);f.length&&(l.content=f.map(d=>d.text).join(` +`));let h=a.content.filter(d=>d.type==="tool_use"&&d.id);h.length&&(l.tool_calls=h.map(d=>({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.input||{})}}))),t.push(l)}return}}});let o={messages:t,model:e.model,max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream,tools:e.tools?.length?this.convertAnthropicToolsToUnified(e.tools):void 0,tool_choice:e.tool_choice};return e.thinking&&(o.reasoning={effort:$f(e.thinking.budget_tokens),enabled:e.thinking.type==="enabled"}),e.tool_choice&&(e.tool_choice.type==="tool"?o.tool_choice={type:"function",function:{name:e.tool_choice.name}}:o.tool_choice=e.tool_choice.type),o}async transformResponseIn(e,t){if(e.headers.get("Content-Type")?.includes("text/event-stream")){if(!e.body)throw new Error("Stream response body is null");let o=await this.convertOpenAIStreamToAnthropic(e.body);return new Response(o,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let o=await e.json(),a=this.convertOpenAIResponseToAnthropic(o);return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}}convertAnthropicToolsToUnified(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description||"",parameters:t.input_schema}}))}async convertOpenAIStreamToAnthropic(e){return new ReadableStream({start:async n=>{let o=new TextEncoder,a=`msg_${Date.now()}`,u=null,l="unknown",f=!1,h=!1,d=!1,_=new Map,E=new Map,P=0,v=0,w=0,g=!1,C=!1,R=0,S=-1,N=H=>{if(!g)try{n.enqueue(H);let K=new TextDecoder().decode(H);this.logger.debug({dataStr:K},"send data")}catch(K){if(K instanceof TypeError&&K.message.includes("Controller is already closed"))g=!0;else throw this.logger.debug(`send data error: ${K.message}`),K}},j=()=>{if(!g)try{if(S>=0){let K={type:"content_block_stop",index:S};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(K)} + +`)),S=-1}u?(N(o.encode(`event: message_delta +data: ${JSON.stringify(u)} + +`)),u=null):N(o.encode(`event: message_delta +data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:0,output_tokens:0,cache_read_input_tokens:0}})} + +`));let H={type:"message_stop"};N(o.encode(`event: message_stop +data: ${JSON.stringify(H)} + +`)),n.close(),g=!0}catch(H){if(H instanceof TypeError&&H.message.includes("Controller is already closed"))g=!0;else throw H}},L=null;try{L=e.getReader();let H=new TextDecoder,K="";for(;!g;){let{done:W,value:Ae}=await L.read();if(W)break;K+=H.decode(Ae,{stream:!0});let he=K.split(` +`);K=he.pop()||"";for(let fe of he){if(g||d)break;if(!fe.startsWith("data:"))continue;let ye=fe.slice(5).trim();if(this.logger.debug(`recieved data: ${ye}`),ye!=="[DONE]")try{let re=JSON.parse(ye);if(P++,this.logger.debug({response:re},"Original Response"),re.error){let Z={type:"error",message:{type:"api_error",message:JSON.stringify(re.error)}};N(o.encode(`event: error +data: ${JSON.stringify(Z)} + +`));continue}if(l=re.model||l,!f&&!g&&!d){f=!0;let Z={type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:l,stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}};N(o.encode(`event: message_start +data: ${JSON.stringify(Z)} + +`))}let de=re.choices?.[0];if(re.usage&&(u?u.usage={input_tokens:re.usage?.prompt_tokens||0,output_tokens:re.usage?.completion_tokens||0,cache_read_input_tokens:re.usage?.cache_read_input_tokens||0}:u={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:re.usage?.prompt_tokens||0,output_tokens:re.usage?.completion_tokens||0,cache_read_input_tokens:re.usage?.cache_read_input_tokens||0}}),!de)continue;if(de?.delta?.thinking&&!g&&!d){if(S>=0){let Z={type:"content_block_stop",index:S};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(Z)} + +`)),S=-1}if(!C){let Z={type:"content_block_start",index:R,content_block:{type:"thinking",thinking:""}};N(o.encode(`event: content_block_start +data: ${JSON.stringify(Z)} + +`)),S=R,C=!0}if(de.delta.thinking.signature){let Z={type:"content_block_delta",index:R,delta:{type:"signature_delta",signature:de.delta.thinking.signature}};N(o.encode(`event: content_block_delta +data: ${JSON.stringify(Z)} + +`));let ue={type:"content_block_stop",index:R};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(ue)} + +`)),S=-1,R++}else if(de.delta.thinking.content){let Z={type:"content_block_delta",index:R,delta:{type:"thinking_delta",thinking:de.delta.thinking.content||""}};N(o.encode(`event: content_block_delta +data: ${JSON.stringify(Z)} + +`))}}if(de?.delta?.content&&!g&&!d){if(v++,S>=0&&!h){let ue={type:"content_block_stop",index:S};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(ue)} + +`)),S=-1}if(!h&&!d){h=!0;let Z={type:"content_block_start",index:R,content_block:{type:"text",text:""}};N(o.encode(`event: content_block_start +data: ${JSON.stringify(Z)} + +`)),S=R}if(!g&&!d){let Z={type:"content_block_delta",index:S,delta:{type:"text_delta",text:de.delta.content}};N(o.encode(`event: content_block_delta +data: ${JSON.stringify(Z)} + +`))}}if(de?.delta?.annotations?.length&&!g&&!d){if(S>=0&&h){let Z={type:"content_block_stop",index:S};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(Z)} + +`)),S=-1,h=!1}de?.delta?.annotations.forEach(Z=>{R++;let ue={type:"content_block_start",index:R,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${Tr()}`,content:[{type:"web_search_result",title:Z.url_citation.title,url:Z.url_citation.url}]}};N(o.encode(`event: content_block_start +data: ${JSON.stringify(ue)} + +`));let J={type:"content_block_stop",index:R};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(J)} + +`)),S=-1})}if(de?.delta?.tool_calls&&!g&&!d){w++;let Z=new Set;for(let ue of de.delta.tool_calls){if(g)break;let J=ue.index??0;if(Z.has(J))continue;if(Z.add(J),!E.has(J)){if(S>=0){let Ee={type:"content_block_stop",index:S};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(Ee)} + +`)),S=-1}let oe=R;E.set(J,oe),R++;let Ie=ue.id||`call_${Date.now()}_${J}`,je=ue.function?.name||`tool_${J}`,G={type:"content_block_start",index:oe,content_block:{type:"tool_use",id:Ie,name:je,input:{}}};N(o.encode(`event: content_block_start +data: ${JSON.stringify(G)} + +`)),S=oe;let pe={id:Ie,name:je,arguments:"",contentBlockIndex:oe};_.set(J,pe)}else if(ue.id&&ue.function?.name){let oe=_.get(J);oe.id.startsWith("call_")&&oe.name.startsWith("tool_")&&(oe.id=ue.id,oe.name=ue.function.name)}if(ue.function?.arguments&&!g&&!d){let oe=E.get(J);if(oe===void 0)continue;let Ie=_.get(J);Ie&&(Ie.arguments+=ue.function.arguments);try{let je={type:"content_block_delta",index:oe,delta:{type:"input_json_delta",partial_json:ue.function.arguments}};N(o.encode(`event: content_block_delta +data: ${JSON.stringify(je)} + +`))}catch{try{let G=ue.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g,"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),pe={type:"content_block_delta",index:oe,delta:{type:"input_json_delta",partial_json:G}};N(o.encode(`event: content_block_delta +data: ${JSON.stringify(pe)} + +`))}catch(G){console.error(G)}}}}}if(de?.finish_reason&&!g&&!d){if(v===0&&w===0&&console.error("Warning: No content in the stream response!"),S>=0){let Z={type:"content_block_stop",index:S};N(o.encode(`event: content_block_stop +data: ${JSON.stringify(Z)} + +`)),S=-1}g||(u={type:"message_delta",delta:{stop_reason:{stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence"}[de.finish_reason]||"end_turn",stop_sequence:null},usage:{input_tokens:re.usage?.prompt_tokens||0,output_tokens:re.usage?.completion_tokens||0,cache_read_input_tokens:re.usage?.cache_read_input_tokens||0}});break}}catch(re){this.logger?.error(`parseError: ${re.name} message: ${re.message} stack: ${re.stack} data: ${ye}`)}}}j()}catch(H){if(!g)try{n.error(H)}catch(K){console.error(K)}}finally{if(L)try{L.releaseLock()}catch(H){console.error(H)}}},cancel:n=>{this.logger.debug(`cancle stream: ${n}`)}})}convertOpenAIResponseToAnthropic(e){this.logger.debug({response:e},"Original OpenAI response");try{let t=e.choices[0];if(!t)throw new Error("No choices found in OpenAI response");let n=[];if(t.message.annotations){let a=`srvtoolu_${Tr()}`;n.push({type:"server_tool_use",id:a,name:"web_search",input:{query:""}}),n.push({type:"web_search_tool_result",tool_use_id:a,content:t.message.annotations.map(u=>({type:"web_search_result",url:u.url_citation.url,title:u.url_citation.title}))})}t.message.content&&n.push({type:"text",text:t.message.content}),t.message.tool_calls&&t.message.tool_calls.length>0&&t.message.tool_calls.forEach((a,u)=>{let l={};try{let f=a.function.arguments||"{}";typeof f=="object"?l=f:typeof f=="string"&&(l=JSON.parse(f))}catch{l={text:a.function.arguments||""}}n.push({type:"tool_use",id:a.id,name:a.function.name,input:l})});let o={id:e.id,type:"message",role:"assistant",model:e.model,content:n,stop_reason:t.finish_reason==="stop"?"end_turn":t.finish_reason==="length"?"max_tokens":t.finish_reason==="tool_calls"?"tool_use":t.finish_reason==="content_filter"?"stop_sequence":"end_turn",stop_sequence:null,usage:{input_tokens:e.usage?.prompt_tokens||0,output_tokens:e.usage?.completion_tokens||0}};return this.logger.debug({result:o},"Conversion complete, final Anthropic response"),o}catch{throw nt(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}};var Cn={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function m0(r,e){r.includes("null")&&(e.nullable=!0);let t=r.filter(n=>n!=="null");if(t.length===1){let n=t[0].toUpperCase();e.type=Object.values(Cn).includes(n)?n:Cn.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let n of t){let o=n.toUpperCase();e.anyOf.push({type:Object.values(Cn).includes(o)?o:Cn.TYPE_UNSPECIFIED})}}}function is(r){let e={},t=["items"],n=["anyOf"],o=["properties"];if(r.type&&r.anyOf)throw new Error("type and anyOf cannot be both populated.");let a=r.anyOf;a!=null&&Array.isArray(a)&&a.length==2&&(a[0]&&a[0].type==="null"?(e.nullable=!0,r=a[1]):a[1]&&a[1].type==="null"&&(e.nullable=!0,r=a[0])),r.type&&Array.isArray(r.type)&&m0(r.type,e);for(let[u,l]of Object.entries(r))if(l!=null)if(u=="type"){if(l==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(l))continue;let f=l.toUpperCase();e.type=Object.values(Cn).includes(f)?f:Cn.TYPE_UNSPECIFIED}else if(t.includes(u))e[u]=is(l);else if(n.includes(u)){let f=[];for(let h of l){if(h.type=="null"){e.nullable=!0;continue}f.push(is(h))}e[u]=f}else if(o.includes(u)){let f={};for(let[h,d]of Object.entries(l))f[h]=is(d);e[u]=f}else{if(u==="additionalProperties")continue;e[u]=l}return e}function g0(r){if(r.functionDeclarations)for(let e of r.functionDeclarations)e.parameters&&(Object.keys(e.parameters).includes("$schema")?e.parametersJsonSchema||(e.parametersJsonSchema=e.parameters,delete e.parameters):e.parameters=is(e.parameters)),e.response&&(Object.keys(e.response).includes("$schema")?e.responseJsonSchema||(e.responseJsonSchema=e.response,delete e.response):e.response=is(e.response));return r}function Eo(r){let e=[],t=r.tools?.filter(u=>u.function.name!=="web_search")?.map(u=>({name:u.function.name,description:u.function.description,parametersJsonSchema:u.function.parameters}));t?.length&&e.push(g0({functionDeclarations:t})),r.tools?.find(u=>u.function.name==="web_search")&&e.push({googleSearch:{}});let a={contents:r.messages.map(u=>{let l;u.role==="assistant"?l="model":(["user","system","tool"].includes(u.role),l="user");let f=[];return typeof u.content=="string"?f.push({text:u.content}):Array.isArray(u.content)&&f.push(...u.content.map(h=>{if(h.type==="text")return{text:h.text||""};if(h.type==="image_url")return h.image_url.url.startsWith("http")?{file_data:{mime_type:h.media_type,file_uri:h.image_url.url}}:{inlineData:{mime_type:h.media_type,data:h.image_url.url}}})),Array.isArray(u.tool_calls)&&f.push(...u.tool_calls.map(h=>({functionCall:{id:h.id||`tool_${Math.random().toString(36).substring(2,15)}`,name:h.function.name,args:JSON.parse(h.function.arguments||"{}")}}))),{role:l,parts:f}}),tools:e.length?e:void 0};if(r.tool_choice){let u={functionCallingConfig:{}};r.tool_choice==="auto"?u.functionCallingConfig.mode="auto":r.tool_choice==="none"?u.functionCallingConfig.mode="none":r.tool_choice==="required"?u.functionCallingConfig.mode="any":r.tool_choice?.function?.name&&(u.functionCallingConfig.mode="any",u.functionCallingConfig.allowedFunctionNames=[r.tool_choice?.function?.name]),a.toolConfig=u}return a}function wo(r){let e=r.contents,t=r.tools,n=r.model,o=r.max_tokens,a=r.temperature,u=r.stream,l=r.tool_choice,f={messages:[],model:n,max_tokens:o,temperature:a,stream:u,tool_choice:l};return Array.isArray(e)&&e.forEach(h=>{typeof h=="string"?f.messages.push({role:"user",content:h}):typeof h.text=="string"?f.messages.push({role:"user",content:h.text||null}):h.role==="user"?f.messages.push({role:"user",content:h?.parts?.map(d=>({type:"text",text:d.text||""}))||[]}):h.role==="model"&&f.messages.push({role:"assistant",content:h?.parts?.map(d=>({type:"text",text:d.text||""}))||[]})}),Array.isArray(t)&&(f.tools=[],t.forEach(h=>{Array.isArray(h.functionDeclarations)&&h.functionDeclarations.forEach(d=>{f.tools.push({type:"function",function:{name:d.name,description:d.description,parameters:d.parameters}})})})),f}async function Ao(r,e,t){if(r.headers.get("Content-Type")?.includes("application/json")){let n=await r.json(),o=n.candidates[0].content?.parts?.filter(u=>u.functionCall)?.map(u=>({id:u.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:u.functionCall?.name,arguments:JSON.stringify(u.functionCall?.args||{})}}))||[],a={id:n.responseId,choices:[{finish_reason:n.candidates[0].finishReason?.toLowerCase()||null,index:0,message:{content:n.candidates[0].content?.parts?.filter(u=>u.text)?.map(u=>u.text)?.join(` +`)||"",role:"assistant",tool_calls:o.length>0?o:void 0}}],created:parseInt(new Date().getTime()/1e3+"",10),model:n.modelVersion,object:"chat.completion",usage:{completion_tokens:n.usageMetadata.candidatesTokenCount,prompt_tokens:n.usageMetadata.promptTokenCount,cached_content_token_count:n.usageMetadata.cachedContentTokenCount||null,total_tokens:n.usageMetadata.totalTokenCount}};return new Response(JSON.stringify(a),{status:r.status,statusText:r.statusText,headers:r.headers})}else if(r.headers.get("Content-Type")?.includes("stream")){if(!r.body)return r;let n=new TextDecoder,o=new TextEncoder,a=(l,f)=>{if(l.startsWith("data: ")){let h=l.slice(6).trim();if(h){t?.debug({chunkStr:h},`${e} chunk:`);try{let d=JSON.parse(h);if(!d.candidates||!d.candidates[0]){log("Invalid chunk structure:",h);return}let _=d.candidates[0],E=_.content?.parts||[],P=E.filter(g=>g.functionCall).map(g=>({id:g.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:g.functionCall?.name,arguments:JSON.stringify(g.functionCall?.args||{})}})),w={choices:[{delta:{role:"assistant",content:E.filter(g=>g.text).map(g=>g.text).join(` +`)||"",tool_calls:P.length>0?P:void 0},finish_reason:_.finishReason?.toLowerCase()||null,index:_.index||(P.length>0?1:0),logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.responseId||"",model:d.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usageMetadata?.candidatesTokenCount||0,prompt_tokens:d.usageMetadata?.promptTokenCount||0,cached_content_token_count:d.usageMetadata?.cachedContentTokenCount||null,total_tokens:d.usageMetadata?.totalTokenCount||0}};_?.groundingMetadata?.groundingChunks?.length&&(w.choices[0].delta.annotations=_.groundingMetadata.groundingChunks.map((g,C)=>{let R=_?.groundingMetadata?.groundingSupports?.filter(S=>S.groundingChunkIndices?.includes(C));return{type:"url_citation",url_citation:{url:g?.web?.uri||"",title:g?.web?.title||"",content:R?.[0]?.segment?.text||"",start_index:R?.[0]?.segment?.startIndex||0,end_index:R?.[0]?.segment?.endIndex||0}}})),f.enqueue(o.encode(`data: ${JSON.stringify(w)} + +`))}catch(d){t?.error(`Error parsing ${e} stream chunk`,h,d.message)}}}},u=new ReadableStream({async start(l){let f=r.body.getReader(),h="";try{for(;;){let{done:d,value:_}=await f.read();if(d){h&&a(h,l);break}h+=n.decode(_,{stream:!0});let E=h.split(` +`);h=E.pop()||"";for(let P of E)a(P,l)}}catch(d){l.error(d)}finally{l.close()}}});return new Response(u,{status:r.status,statusText:r.statusText,headers:r.headers})}return r}var Do=class{name="gemini";endPoint="/v1beta/models/:modelAndAction";async transformRequestIn(e,t){return{body:Eo(e),config:{url:new URL(`./${e.model}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,t.baseUrl),headers:{"x-goog-api-key":t.apiKey,Authorization:void 0}}}}transformRequestOut=wo;async transformResponseOut(e){return Ao(e,this.name,this.logger)}};async function Vw(){try{let{GoogleAuth:r}=await Promise.resolve().then(()=>zr(al(),1));return(await(await new r({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(r){throw console.error("Error getting access token:",r),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods: +1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file +2. Run "gcloud auth application-default login" +3. Use Google Cloud environment with default service account`)}}var Hi=class{name="vertex-gemini";async transformRequestIn(e,t){let n=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!n&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let l=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),f=JSON.parse(l);f&&f.project_id&&(n=f.project_id)}catch(u){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",u)}if(!n)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let a=await Vw();return{body:Eo(e),config:{url:new URL(`./v1beta1/projects/${n}/locations/${o}/publishers/google/models/${e.model}:${e.stream?"streamGenerateContent":"generateContent"}`,t.baseUrl.endsWith("/")?t.baseUrl:t.baseUrl+"/"||`https://${o}-aiplatform.googleapis.com`),headers:{Authorization:`Bearer ${a}`,"x-goog-api-key":void 0}}}}transformRequestOut=wo;async transformResponseOut(e){return Ao(e,this.name)}};var Gi=class{name="deepseek";async transformRequestIn(e){return e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,n=new TextEncoder,o="",a=!1,u="",l=new ReadableStream({async start(f){let h=e.body.getReader(),d=(E,P,v)=>{let w=E.split(` +`);for(let g of w)g.trim()&&P.enqueue(v.encode(g+` +`))},_=(E,P)=>{let{controller:v,encoder:w}=P;if(E.startsWith("data: ")&&E.trim()!=="data: [DONE]")try{let g=JSON.parse(E.slice(6));if(g.choices?.[0]?.delta?.reasoning_content){P.appendReasoningContent(g.choices[0].delta.reasoning_content);let C={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete C.choices[0].delta.reasoning_content;let R=`data: ${JSON.stringify(C)} + +`;v.enqueue(w.encode(R));return}if(g.choices?.[0]?.delta?.content&&P.reasoningContent()&&!P.isReasoningComplete()){P.setReasoningComplete(!0);let C=Date.now().toString(),R={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:P.reasoningContent(),signature:C}}}]};delete R.choices[0].delta.reasoning_content;let S=`data: ${JSON.stringify(R)} + +`;v.enqueue(w.encode(S))}if(g.choices[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0){P.isReasoningComplete()&&g.choices[0].index++;let C=`data: ${JSON.stringify(g)} + +`;v.enqueue(w.encode(C))}}catch{v.enqueue(w.encode(E+` +`))}else v.enqueue(w.encode(E+` +`))};try{for(;;){let{done:E,value:P}=await h.read();if(E){u.trim()&&d(u,f,n);break}let v=t.decode(P,{stream:!0});u+=v;let w=u.split(` +`);u=w.pop()||"";for(let g of w)if(g.trim())try{_(g,{controller:f,encoder:n,reasoningContent:()=>o,appendReasoningContent:C=>o+=C,isReasoningComplete:()=>a,setReasoningComplete:C=>a=C})}catch(C){console.error("Error processing line:",g,C),f.enqueue(n.encode(g+` +`))}}}catch(E){console.error("Stream error:",E),f.error(E)}finally{try{h.releaseLock()}catch(E){console.error("Error releasing reader lock:",E)}f.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Wi=class{name="tooluse";transformRequestIn(e){return e.messages.push({role:"system",content:"Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate."}),e.tools?.length&&(e.tool_choice="required",e.tools.push({type:"function",function:{name:"ExitTool",description:`Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode. +IMPORTANT: Before using this tool, ensure that none of the available tools are applicable to the current task. You must evaluate all available options \u2014 only if no suitable tool can help you complete the task should you use ExitTool to terminate tool mode. +Examples: +1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available. +2. Task: "What\u2019s the weather today?" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,parameters:{type:"object",properties:{response:{type:"string",description:"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way."}},required:["response"]}}})),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();if(t?.choices?.[0]?.message.tool_calls?.length&&t?.choices?.[0]?.message.tool_calls[0]?.function?.name==="ExitTool"){let n=t?.choices[0]?.message.tool_calls[0],o=JSON.parse(n.function.arguments||"{}");t.choices[0].message.content=o.response||"",delete t.choices[0].message.tool_calls}return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,n=new TextEncoder,o=-1,a="",u="",l=new ReadableStream({async start(f){let h=e.body.getReader(),d=(E,P,v)=>{let w=E.split(` +`);for(let g of w)g.trim()&&P.enqueue(v.encode(g+` +`))},_=(E,P)=>{let{controller:v,encoder:w,exitToolIndex:g,setExitToolIndex:C,appendExitToolResponse:R}=P;if(E.startsWith("data: ")&&E.trim()!=="data: [DONE]")try{let S=JSON.parse(E.slice(6));if(S.choices[0]?.delta?.tool_calls?.length){let N=S.choices[0].delta.tool_calls[0];if(N.function?.name==="ExitTool"){C(N.index);return}else if(g()>-1&&N.index===g()&&N.function.arguments){R(N.function.arguments);try{let j=JSON.parse(P.exitToolResponse());S.choices=[{delta:{role:"assistant",content:j.response||""}}];let L=`data: ${JSON.stringify(S)} + +`;v.enqueue(w.encode(L))}catch{}return}}if(S.choices?.[0]?.delta&&Object.keys(S.choices[0].delta).length>0){let N=`data: ${JSON.stringify(S)} + +`;v.enqueue(w.encode(N))}}catch{v.enqueue(w.encode(E+` +`))}else v.enqueue(w.encode(E+` +`))};try{for(;;){let{done:E,value:P}=await h.read();if(E){u.trim()&&d(u,f,n);break}let v=t.decode(P,{stream:!0});u+=v;let w=u.split(` +`);u=w.pop()||"";for(let g of w)if(g.trim())try{_(g,{controller:f,encoder:n,exitToolIndex:()=>o,setExitToolIndex:C=>o=C,exitToolResponse:()=>a,appendExitToolResponse:C=>a+=C})}catch(C){console.error("Error processing line:",g,C),f.enqueue(n.encode(g+` +`))}}}catch(E){console.error("Stream error:",E),f.error(E)}finally{try{h.releaseLock()}catch(E){console.error("Error releasing reader lock:",E)}f.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var zi=class{constructor(e){this.options=e}static TransformerName="openrouter";async transformRequestIn(e){return e.model.includes("claude")?e.messages.forEach(t=>{Array.isArray(t.content)&&t.content.forEach(n=>{n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`data:${n.media_type};base64,${n.image_url.url}`),delete n.media_type)})}):e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(n=>{n.cache_control&&delete n.cache_control,n.type==="image_url"&&(n.image_url.url.startsWith("http")||(n.image_url.url=`data:${n.media_type};base64,${n.image_url.url}`),delete n.media_type)}):t.cache_control&&delete t.cache_control}),Object.assign(e,this.options||{}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,n=new TextEncoder,o=!1,a="",u=!1,l=!1,f="",h=new ReadableStream({async start(d){let _=e.body.getReader(),E=(v,w,g)=>{let C=v.split(` +`);for(let R of C)R.trim()&&w.enqueue(g.encode(R+` +`))},P=(v,w)=>{let{controller:g,encoder:C}=w;if(v.startsWith("data: ")&&v.trim()!=="data: [DONE]"){let R=v.slice(6);try{let S=JSON.parse(R);if(S.usage&&(this.logger?.debug({usage:S.usage,hasToolCall:l},"usage"),S.choices[0].finish_reason=l?"tool_calls":"stop"),S.choices?.[0]?.finish_reason==="error"&&g.enqueue(C.encode(`data: ${JSON.stringify({error:S.choices?.[0].error})} + +`)),S.choices?.[0]?.delta?.content&&!w.hasTextContent()&&w.setHasTextContent(!0),S.choices?.[0]?.delta?.reasoning){w.appendReasoningContent(S.choices[0].delta.reasoning);let j={...S,choices:[{...S.choices?.[0],delta:{...S.choices[0].delta,thinking:{content:S.choices[0].delta.reasoning}}}]};j.choices?.[0]?.delta&&delete j.choices[0].delta.reasoning;let L=`data: ${JSON.stringify(j)} + +`;g.enqueue(C.encode(L));return}if(S.choices?.[0]?.delta?.content&&w.reasoningContent()&&!w.isReasoningComplete()){w.setReasoningComplete(!0);let j=Date.now().toString(),L={...S,choices:[{...S.choices?.[0],delta:{...S.choices[0].delta,content:null,thinking:{content:w.reasoningContent(),signature:j}}}]};L.choices?.[0]?.delta&&delete L.choices[0].delta.reasoning;let H=`data: ${JSON.stringify(L)} + +`;g.enqueue(C.encode(H))}S.choices?.[0]?.delta?.reasoning&&delete S.choices[0].delta.reasoning,S.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(S.choices?.[0]?.delta?.tool_calls[0].id,10))&&S.choices?.[0]?.delta?.tool_calls.forEach(j=>{j.id=`call_${Tr()}`}),S.choices?.[0]?.delta?.tool_calls?.length&&!l&&(l=!0),S.choices?.[0]?.delta?.tool_calls?.length&&w.hasTextContent()&&(typeof S.choices[0].index=="number"?S.choices[0].index+=1:S.choices[0].index=1);let N=`data: ${JSON.stringify(S)} + +`;g.enqueue(C.encode(N))}catch{g.enqueue(C.encode(v+` +`))}}else g.enqueue(C.encode(v+` +`))};try{for(;;){let{done:v,value:w}=await _.read();if(v){f.trim()&&E(f,d,n);break}if(!w||w.length===0)continue;let g;try{g=t.decode(w,{stream:!0})}catch(R){console.warn("Failed to decode chunk",R);continue}if(g.length===0)continue;if(f+=g,f.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let R=f.split(` +`);f=R.pop()||"";for(let S of R)if(S.trim())try{P(S,{controller:d,encoder:n,hasTextContent:()=>o,setHasTextContent:N=>o=N,reasoningContent:()=>a,appendReasoningContent:N=>a+=N,isReasoningComplete:()=>u,setReasoningComplete:N=>u=N})}catch(N){console.error("Error processing line:",S,N),d.enqueue(n.encode(S+` +`))}continue}let C=f.split(` +`);f=C.pop()||"";for(let R of C)if(R.trim())try{P(R,{controller:d,encoder:n,hasTextContent:()=>o,setHasTextContent:S=>o=S,reasoningContent:()=>a,appendReasoningContent:S=>a+=S,isReasoningComplete:()=>u,setReasoningComplete:S=>u=S})}catch(S){console.error("Error processing line:",R,S),d.enqueue(n.encode(R+` +`))}}}catch(v){console.error("Stream error:",v),d.error(v)}finally{try{_.releaseLock()}catch(v){console.error("Error releasing reader lock:",v)}d.close()}}});return new Response(h,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Ji=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens}static TransformerName="maxtoken";max_tokens;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),e}};var Vi=class{name="groq";async transformRequestIn(e){return e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(n=>{n.cache_control&&delete n.cache_control}):t.cache_control&&delete t.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(t=>{delete t.function.parameters.$schema}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,n=new TextEncoder,o=!1,a="",u=!1,l="",f=new ReadableStream({async start(h){let d=e.body.getReader(),_=(P,v,w)=>{let g=P.split(` +`);for(let C of g)C.trim()&&v.enqueue(w.encode(C+` +`))},E=(P,v)=>{let{controller:w,encoder:g}=v;if(P.startsWith("data: ")&&P.trim()!=="data: [DONE]"){let C=P.slice(6);try{let R=JSON.parse(C);if(R.error)throw new Error(JSON.stringify(R));R.choices?.[0]?.delta?.content&&!v.hasTextContent()&&v.setHasTextContent(!0),R.choices?.[0]?.delta?.tool_calls?.length&&R.choices?.[0]?.delta?.tool_calls.forEach(N=>{N.id=`call_${Tr()}`}),R.choices?.[0]?.delta?.tool_calls?.length&&v.hasTextContent()&&(typeof R.choices[0].index=="number"?R.choices[0].index+=1:R.choices[0].index=1);let S=`data: ${JSON.stringify(R)} + +`;w.enqueue(g.encode(S))}catch{w.enqueue(g.encode(P+` +`))}}else w.enqueue(g.encode(P+` +`))};try{for(;;){let{done:P,value:v}=await d.read();if(P){l.trim()&&_(l,h,n);break}if(!v||v.length===0)continue;let w;try{w=t.decode(v,{stream:!0})}catch(C){console.warn("Failed to decode chunk",C);continue}if(w.length===0)continue;if(l+=w,l.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let C=l.split(` +`);l=C.pop()||"";for(let R of C)if(R.trim())try{E(R,{controller:h,encoder:n,hasTextContent:()=>o,setHasTextContent:S=>o=S,reasoningContent:()=>a,appendReasoningContent:S=>a+=S,isReasoningComplete:()=>u,setReasoningComplete:S=>u=S})}catch(S){console.error("Error processing line:",R,S),h.enqueue(n.encode(R+` +`))}continue}let g=l.split(` +`);l=g.pop()||"";for(let C of g)if(C.trim())try{E(C,{controller:h,encoder:n,hasTextContent:()=>o,setHasTextContent:R=>o=R,reasoningContent:()=>a,appendReasoningContent:R=>a+=R,isReasoningComplete:()=>u,setReasoningComplete:R=>u=R})}catch(R){console.error("Error processing line:",C,R),h.enqueue(n.encode(C+` +`))}}}catch(P){console.error("Stream error:",P),h.error(P)}finally{try{d.releaseLock()}catch(P){console.error("Error releasing reader lock:",P)}h.close()}}});return new Response(f,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Ki=class{name="cleancache";async transformRequestIn(e){return Array.isArray(e.messages)&&e.messages.forEach(t=>{Array.isArray(t.content)?t.content.forEach(n=>{n.cache_control&&delete n.cache_control}):t.cache_control&&delete t.cache_control}),e}};var eg=zr(Ma(),1);var yr=class extends Error{constructor(e,t){super(`${e} at position ${t}`),this.position=t}};function Jm(r){return/^[0-9A-Fa-f]$/.test(r)}function qr(r){return r>="0"&&r<="9"}function Vm(r){return r>=" "}function Is(r){return`,:[]/{}() ++`.includes(r)}function ul(r){return r>="a"&&r<="z"||r>="A"&&r<="Z"||r==="_"||r==="$"}function cl(r){return r>="a"&&r<="z"||r>="A"&&r<="Z"||r==="_"||r==="$"||r>="0"&&r<="9"}var ll=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,fl=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function dl(r){return`,[]/{} ++`.includes(r)}function hl(r){return Ns(r)||Kw.test(r)}var Kw=/^[[{\w-]$/;function Km(r){return r===` +`||r==="\r"||r===" "||r==="\b"||r==="\f"}function Nr(r,e){let t=r.charCodeAt(e);return t===32||t===10||t===9||t===13}function Ym(r,e){let t=r.charCodeAt(e);return t===32||t===9||t===13}function Xm(r,e){let t=r.charCodeAt(e);return t===160||t>=8192&&t<=8202||t===8239||t===8287||t===12288}function Ns(r){return pl(r)||Yi(r)}function pl(r){return r==='"'||r==="\u201C"||r==="\u201D"}function ml(r){return r==='"'}function Yi(r){return r==="'"||r==="\u2018"||r==="\u2019"||r==="`"||r==="\xB4"}function gl(r){return r==="'"}function Kn(r,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=r.lastIndexOf(e);return n!==-1?r.substring(0,n)+(t?"":r.substring(n+1)):r}function Rt(r,e){let t=r.length;if(!Nr(r,t-1))return r+e;for(;Nr(r,t-1);)t--;return r.substring(0,t)+e+r.substring(t)}function Qm(r,e,t){return r.substring(0,e)+r.substring(e+t)}function Zm(r){return/[,\n][ \t\r]*$/.test(r)}var Yw={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},Xw={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:` +`,r:"\r",t:" "};function yl(r){let e=0,t="";h(["```","[```","{```"]),a()||re(),h(["```","```]","```}"]);let o=_(",");for(o&&u(),hl(r[e])&&Zm(t)?(o||(t=Rt(t,",")),C()):o&&(t=Kn(t,","));r[e]==="}"||r[e]==="]";)e++,u();if(e>=r.length)return t;ye();function a(){u();let J=w()||g()||R()||N()||j()||H(!1)||K();return u(),J}function u(){let J=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,se=e,oe=l(J);do oe=f(),oe&&(oe=l(J));while(oe);return e>se}function l(J){let se=J?Nr:Ym,oe="";for(;;)if(se(r,e))oe+=r[e],e++;else if(Xm(r,e))oe+=" ",e++;else break;return oe.length>0?(t+=oe,!0):!1}function f(){if(r[e]==="/"&&r[e+1]==="*"){for(;e=r.length;Ie||(hl(r[e])||je?t=Rt(t,":"):Z()),a()||(Ie||je?t+="null":Z())}return r[e]==="}"?(t+="}",e++):t=Rt(t,"}"),!0}return!1}function g(){if(r[e]==="["){t+="[",e++,u(),E(",")&&u();let J=!0;for(;e0&&arguments[0]!==void 0?arguments[0]:!1,se=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,oe=r[e]==="\\";if(oe&&(e++,oe=!0),Ns(r[e])){let Ie=ml(r[e])?ml:gl(r[e])?gl:Yi(r[e])?Yi:pl,je=e,G=t.length,pe='"';for(e++;;){if(e>=r.length){let Ee=W(e-1);return!J&&Is(r.charAt(Ee))?(e=je,t=t.substring(0,G),R(!0)):(pe=Rt(pe,'"'),t+=pe,!0)}if(e===se)return pe=Rt(pe,'"'),t+=pe,!0;if(Ie(r[e])){let Ee=e,er=pe.length;if(pe+='"',e++,t+=pe,u(!1),J||e>=r.length||Is(r[e])||Ns(r[e])||qr(r[e]))return S(),!0;let xe=W(Ee-1),Ne=r.charAt(xe);if(Ne===",")return e=je,t=t.substring(0,G),R(!1,xe);if(Is(Ne))return e=je,t=t.substring(0,G),R(!0);t=t.substring(0,G),e=Ee+1,pe=`${pe.substring(0,er)}\\${pe.substring(er)}`}else if(J&&dl(r[e])){if(r[e-1]===":"&&ll.test(r.substring(je+1,e+2)))for(;e=r.length?e=r.length:ue()}else pe+=Ee,e+=2}else{let Ee=r.charAt(e);Ee==='"'&&r[e-1]!=="\\"?(pe+=`\\${Ee}`,e++):Km(Ee)?(pe+=Yw[Ee],e++):(Vm(Ee)||fe(Ee),pe+=Ee,e++)}oe&&P()}}return!1}function S(){let J=!1;for(u();r[e]==="+";){J=!0,e++,u(),t=Kn(t,'"',!0);let se=t.length;R()?t=Qm(t,se,1):t=Rt(t,'"')}return J}function N(){let J=e;if(r[e]==="-"){if(e++,Ae())return he(J),!0;if(!qr(r[e]))return e=J,!1}for(;qr(r[e]);)e++;if(r[e]==="."){if(e++,Ae())return he(J),!0;if(!qr(r[e]))return e=J,!1;for(;qr(r[e]);)e++}if(r[e]==="e"||r[e]==="E"){if(e++,(r[e]==="-"||r[e]==="+")&&e++,Ae())return he(J),!0;if(!qr(r[e]))return e=J,!1;for(;qr(r[e]);)e++}if(!Ae())return e=J,!1;if(e>J){let se=r.slice(J,e),oe=/^0\d/.test(se);return t+=oe?`"${se}"`:se,!0}return!1}function j(){return L("true","true")||L("false","false")||L("null","null")||L("True","true")||L("False","false")||L("None","null")}function L(J,se){return r.slice(e,e+J.length)===J?(t+=se,e+=J.length,!0):!1}function H(J){let se=e;if(ul(r[e])){for(;ese){for(;Nr(r,e-1)&&e>0;)e--;let oe=r.slice(se,e);return t+=oe==="undefined"?"null":JSON.stringify(oe),r[e]==='"'&&e++,!0}}function K(){if(r[e]==="/"){let J=e;for(e++;e0&&Nr(r,se);)se--;return se}function Ae(){return e>=r.length||Is(r[e])||Nr(r,e)}function he(J){t+=`${r.slice(J,e)}0`}function fe(J){throw new yr(`Invalid character ${JSON.stringify(J)}`,e)}function ye(){throw new yr(`Unexpected character ${JSON.stringify(r[e])}`,e)}function re(){throw new yr("Unexpected end of json string",r.length)}function de(){throw new yr("Object key expected",e)}function Z(){throw new yr("Colon expected",e)}function ue(){let J=r.slice(e,e+6);throw new yr(`Invalid unicode character "${J}"`,e)}}function Qw(r,e){return r[e]==="*"&&r[e+1]==="/"}function _l(r,e){if(!r||r.trim()===""||r==="{}")return"{}";try{return JSON.parse(r),e?.debug("\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u6807\u51C6JSON\u89E3\u6790\u6210\u529F / Tool arguments standard JSON parsing successful"),r}catch(t){try{let n=eg.default.parse(r);return e?.debug("\u5DE5\u5177\u8C03\u7528\u53C2\u6570JSON5\u89E3\u6790\u6210\u529F / Tool arguments JSON5 parsing successful"),JSON.stringify(n)}catch(n){try{let o=yl(r);return e?.debug("\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u5B89\u5168\u4FEE\u590D\u6210\u529F / Tool arguments safely repaired"),o}catch(o){return e?.error(`JSON\u89E3\u6790\u5931\u8D25 / JSON parsing failed: ${t.message}. JSON5\u89E3\u6790\u5931\u8D25 / JSON5 parsing failed: ${n.message}. JSON\u4FEE\u590D\u5931\u8D25 / JSON repair failed: ${o.message}. \u8F93\u5165\u6570\u636E / Input data: ${JSON.stringify(r)}`),e?.debug("\u8FD4\u56DE\u5B89\u5168\u7684\u7A7A\u5BF9\u8C61\u4F5C\u4E3A\u540E\u5907\u65B9\u6848 / Returning safe empty object as fallback"),"{}"}}}}var Xi=class{name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();if(t?.choices?.[0]?.message?.tool_calls?.length)for(let n of t.choices[0].message.tool_calls)n.function?.arguments&&(n.function.arguments=_l(n.function.arguments,this.logger));return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,n=new TextEncoder,o={},a=!1,u="",l=!1,f=!1,h="",d=new ReadableStream({async start(_){let E=e.body.getReader(),P=(g,C,R)=>{let S=g.split(` +`);for(let N of S)N.trim()&&C.enqueue(R.encode(N+` +`))},v=(g,C,R)=>{let S="";try{S=_l(o.arguments||"",this.logger)}catch(H){console.error(`${H.message} ${H.stack} \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(o)}`),S=o.arguments||""}let N={role:"assistant",tool_calls:[{function:{name:o.name,arguments:S},id:o.id,index:o.index,type:"function"}]},j={...g,choices:[{...g.choices[0],delta:N}]};j.choices[0].delta.content!==void 0&&delete j.choices[0].delta.content;let L=`data: ${JSON.stringify(j)} + +`;C.enqueue(R.encode(L))},w=(g,C)=>{let{controller:R,encoder:S}=C;if(g.startsWith("data: ")&&g.trim()!=="data: [DONE]"){let N=g.slice(6);try{let j=JSON.parse(N);if(j.choices?.[0]?.delta?.tool_calls?.length){let H=j.choices[0].delta.tool_calls[0];if(typeof o.index>"u"){o={index:H.index,name:H.function?.name||"",id:H.id||"",arguments:H.function?.arguments||""},H.function?.arguments&&(H.function.arguments="");let K=`data: ${JSON.stringify(j)} + +`;R.enqueue(S.encode(K));return}else if(o.index===H.index){H.function?.arguments&&(o.arguments+=H.function.arguments);return}else{v(j,R,S),o={index:H.index,name:H.function?.name||"",id:H.id||"",arguments:H.function?.arguments||""};return}}if(j.choices?.[0]?.finish_reason==="tool_calls"&&o.index!==void 0){v(j,R,S),o={};return}j.choices?.[0]?.delta?.tool_calls?.length&&C.hasTextContent()&&(typeof j.choices[0].index=="number"?j.choices[0].index+=1:j.choices[0].index=1);let L=`data: ${JSON.stringify(j)} + +`;R.enqueue(S.encode(L))}catch{R.enqueue(S.encode(g+` +`))}}else R.enqueue(S.encode(g+` +`))};try{for(;;){let{done:g,value:C}=await E.read();if(g){h.trim()&&P(h,_,n);break}if(!C||C.length===0)continue;let R;try{R=t.decode(C,{stream:!0})}catch(N){console.warn("Failed to decode chunk",N);continue}if(R.length===0)continue;if(h+=R,h.length>1e6){console.warn("Buffer size exceeds limit, processing partial data");let N=h.split(` +`);h=N.pop()||"";for(let j of N)if(j.trim())try{w(j,{controller:_,encoder:n,hasTextContent:()=>a,setHasTextContent:L=>a=L,reasoningContent:()=>u,appendReasoningContent:L=>u+=L,isReasoningComplete:()=>l,setReasoningComplete:L=>l=L})}catch(L){console.error("Error processing line:",j,L),_.enqueue(n.encode(j+` +`))}continue}let S=h.split(` +`);h=S.pop()||"";for(let N of S)if(N.trim())try{w(N,{controller:_,encoder:n,hasTextContent:()=>a,setHasTextContent:j=>a=j,reasoningContent:()=>u,appendReasoningContent:j=>u+=j,isReasoningComplete:()=>l,setReasoningComplete:j=>l=j})}catch(j){console.error("Error processing line:",N,j),_.enqueue(n.encode(N+` +`))}}}catch(g){console.error("Stream error:",g),_.error(g)}finally{try{E.releaseLock()}catch(g){console.error("Error releasing reader lock:",g)}_.close()}}});return new Response(d,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Qi=class{constructor(e){this.options=e;this.enable=this.options?.enable??!0}static TransformerName="reasoning";enable;async transformRequestIn(e){return this.enable?(e.reasoning&&(e.thinking={type:"enabled",budget_tokens:e.reasoning.max_tokens},e.enable_thinking=!0),e):(e.thinking={type:"disabled",budget_tokens:-1},e.enable_thinking=!1,e)}async transformResponseOut(e){if(!this.enable)return e;if(e.headers.get("Content-Type")?.includes("application/json")){let t=await e.json();return new Response(JSON.stringify(t),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let t=new TextDecoder,n=new TextEncoder,o="",a=!1,u="",l=new ReadableStream({async start(f){let h=e.body.getReader(),d=(E,P,v)=>{let w=E.split(` +`);for(let g of w)g.trim()&&P.enqueue(v.encode(g+` +`))},_=(E,P)=>{let{controller:v,encoder:w}=P;if(this.logger?.debug({line:E},"Processing reason line"),E.startsWith("data: ")&&E.trim()!=="data: [DONE]")try{let g=JSON.parse(E.slice(6));if(g.choices?.[0]?.delta?.reasoning_content){P.appendReasoningContent(g.choices[0].delta.reasoning_content);let C={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,thinking:{content:g.choices[0].delta.reasoning_content}}}]};delete C.choices[0].delta.reasoning_content;let R=`data: ${JSON.stringify(C)} + +`;v.enqueue(w.encode(R));return}if((g.choices?.[0]?.delta?.content||g.choices?.[0]?.delta?.tool_calls)&&P.reasoningContent()&&!P.isReasoningComplete()){P.setReasoningComplete(!0);let C=Date.now().toString(),R={...g,choices:[{...g.choices[0],delta:{...g.choices[0].delta,content:null,thinking:{content:P.reasoningContent(),signature:C}}}]};delete R.choices[0].delta.reasoning_content;let S=`data: ${JSON.stringify(R)} + +`;v.enqueue(w.encode(S))}if(g.choices?.[0]?.delta?.reasoning_content&&delete g.choices[0].delta.reasoning_content,g.choices?.[0]?.delta&&Object.keys(g.choices[0].delta).length>0){P.isReasoningComplete()&&g.choices[0].index++;let C=`data: ${JSON.stringify(g)} + +`;v.enqueue(w.encode(C))}}catch{v.enqueue(w.encode(E+` +`))}else v.enqueue(w.encode(E+` +`))};try{for(;;){let{done:E,value:P}=await h.read();if(E){u.trim()&&d(u,f,n);break}let v=t.decode(P,{stream:!0});u+=v;let w=u.split(` +`);u=w.pop()||"";for(let g of w)if(g.trim())try{_(g,{controller:f,encoder:n,reasoningContent:()=>o,appendReasoningContent:C=>o+=C,isReasoningComplete:()=>a,setReasoningComplete:C=>a=C})}catch(C){console.error("Error processing line:",g,C),f.enqueue(n.encode(g+` +`))}}}catch(E){console.error("Stream error:",E),f.error(E)}finally{try{h.releaseLock()}catch(E){console.error("Error releasing reader lock:",E)}f.close()}}});return new Response(l,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Zi=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens,this.temperature=this.options?.temperature,this.top_p=this.options?.top_p,this.top_k=this.options?.top_k,this.repetition_penalty=this.options?.repetition_penalty}name="sampling";max_tokens;temperature;top_p;top_k;repetition_penalty;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),typeof this.temperature<"u"&&(e.temperature=this.temperature),typeof this.top_p<"u"&&(e.top_p=this.top_p),typeof this.top_k<"u"&&(e.top_k=this.top_k),typeof this.repetition_penalty<"u"&&(e.repetition_penalty=this.repetition_penalty),e}};var ea=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}};function tg(r){let e=[];for(let n=0;n{f.type==="text"?l.push({type:"text",text:f.text||""}):f.type==="image_url"&&l.push({type:"image",source:{type:"base64",media_type:f.media_type||"image/jpeg",data:f.image_url.url}})}),!(!a&&l.length===0&&!o.tool_calls&&!o.content)&&(a&&u&&l.length===0&&o.tool_calls&&l.push({type:"text",text:""}),e.push({role:o.role==="assistant"?"assistant":"user",content:l}))}let t={anthropic_version:"vertex-2023-10-16",messages:e,max_tokens:r.max_tokens||1e3,stream:r.stream||!1,...r.temperature&&{temperature:r.temperature}};return r.tools&&r.tools.length>0&&(t.tools=r.tools.map(n=>({name:n.function.name,description:n.function.description,input_schema:n.function.parameters}))),r.tool_choice&&(r.tool_choice==="auto"||r.tool_choice==="none"?t.tool_choice=r.tool_choice:typeof r.tool_choice=="string"&&(t.tool_choice={type:"tool",name:r.tool_choice})),t}function rg(r){let e=r,n={messages:e.messages.map(o=>{let a=o.content.map(u=>u.type==="text"?{type:"text",text:u.text||""}:u.type==="image"&&u.source?{type:"image_url",image_url:{url:u.source.data},media_type:u.source.media_type}:{type:"text",text:""});return{role:o.role,content:a}}),model:r.model||"claude-sonnet-4@20250514",max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream};return e.tools&&e.tools.length>0&&(n.tools=e.tools.map(o=>({type:"function",function:{name:o.name,description:o.description,parameters:{type:"object",properties:o.input_schema.properties,required:o.input_schema.required,additionalProperties:o.input_schema.additionalProperties,$schema:o.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?n.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(n.tool_choice=e.tool_choice.name)),n}async function ng(r,e,t){if(r.headers.get("Content-Type")?.includes("application/json")){let n=await r.json(),o;n.tool_use&&n.tool_use.length>0&&(o=n.tool_use.map(u=>({id:u.id,type:"function",function:{name:u.name,arguments:JSON.stringify(u.input)}})));let a={id:n.id,choices:[{finish_reason:n.stop_reason||null,index:0,message:{content:n.content[0]?.text||"",role:"assistant",...o&&{tool_calls:o}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:n.model,object:"chat.completion",usage:{completion_tokens:n.usage.output_tokens,prompt_tokens:n.usage.input_tokens,total_tokens:n.usage.input_tokens+n.usage.output_tokens}};return new Response(JSON.stringify(a),{status:r.status,statusText:r.statusText,headers:r.headers})}else if(r.headers.get("Content-Type")?.includes("stream")){if(!r.body)return r;let n=new TextDecoder,o=new TextEncoder,a=(l,f)=>{if(l.startsWith("data: ")){let h=l.slice(6).trim();if(h){t?.debug({chunkStr:h},`${e} chunk:`);try{let d=JSON.parse(h);if(d.type==="content_block_delta"&&d.delta?.type==="text_delta"){let _={choices:[{delta:{role:"assistant",content:d.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};f.enqueue(o.encode(`data: ${JSON.stringify(_)} + +`))}else if(d.type==="content_block_delta"&&d.delta?.type==="input_json_delta"){let _={choices:[{delta:{tool_calls:[{index:d.index||0,function:{arguments:d.delta.partial_json||""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};f.enqueue(o.encode(`data: ${JSON.stringify(_)} + +`))}else if(d.type==="content_block_start"&&d.content_block?.type==="tool_use"){let _={choices:[{delta:{tool_calls:[{index:d.index||0,id:d.content_block.id,type:"function",function:{name:d.content_block.name,arguments:""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};f.enqueue(o.encode(`data: ${JSON.stringify(_)} + +`))}else if(d.type==="message_delta"){let _={choices:[{delta:{},finish_reason:d.delta?.stop_reason==="tool_use"?"tool_calls":d.delta?.stop_reason==="max_tokens"?"length":d.delta?.stop_reason==="stop_sequence"?"content_filter":"stop",index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};f.enqueue(o.encode(`data: ${JSON.stringify(_)} + +`))}else if(d.type==="message_stop")f.enqueue(o.encode(`data: [DONE] + +`));else{let _={choices:[{delta:{role:"assistant",content:d.content?.[0]?.text||""},finish_reason:d.stop_reason?.toLowerCase()||null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:d.id||"",model:d.model||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:{completion_tokens:d.usage?.output_tokens||0,prompt_tokens:d.usage?.input_tokens||0,total_tokens:(d.usage?.input_tokens||0)+(d.usage?.output_tokens||0)}};f.enqueue(o.encode(`data: ${JSON.stringify(_)} + +`))}}catch(d){t?.error(`Error parsing ${e} stream chunk`,h,d.message)}}}},u=new ReadableStream({async start(l){let f=r.body.getReader(),h="";try{for(;;){let{done:d,value:_}=await f.read();if(d){h&&a(h,l);break}h+=n.decode(_,{stream:!0});let E=h.split(` +`);h=E.pop()||"";for(let P of E)a(P,l)}}catch(d){l.error(d)}finally{l.close()}}});return new Response(u,{status:r.status,statusText:r.statusText,headers:r.headers})}return r}async function Zw(){try{let{GoogleAuth:r}=await Promise.resolve().then(()=>zr(al(),1));return(await(await new r({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(r){throw console.error("Error getting access token:",r),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods: +1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file +2. Run "gcloud auth application-default login" +3. Use Google Cloud environment with default service account`)}}var ta=class{name="vertex-claude";async transformRequestIn(e,t){let n=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!n&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let l=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),f=JSON.parse(l);f&&f.project_id&&(n=f.project_id)}catch(u){console.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",u)}if(!n)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let a=await Zw();return{body:tg(e),config:{url:new URL(`/v1/projects/${n}/locations/${o}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${o}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return rg(e)}async transformResponseOut(e){return ng(e,this.name,this.logger)}};function sg(r){return typeof r=="string"?r:Array.isArray(r)?r.map(e=>typeof e=="string"?e:typeof e=="object"&&e!==null&&"type"in e&&e.type==="text"&&"text"in e&&typeof e.text=="string"?e.text:"").join(""):""}var ra=class{name="cerebras";async transformRequestIn(e,t){let n=JSON.parse(JSON.stringify(e));if(!n.model&&t.models&&t.models.length>0&&(n.model=t.models[0]),n.system!==void 0){let o=sg(n.system);n.messages||(n.messages=[]),n.messages.unshift({role:"system",content:o}),delete n.system}return n.messages&&Array.isArray(n.messages)&&(n.messages=n.messages.map(o=>{let a={...o};return a.content!==void 0&&(a.content=sg(a.content)),a})),{body:n,config:{headers:{Authorization:`Bearer ${t.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}};var na=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var og={AnthropicTransformer:bo,GeminiTransformer:Do,VertexGeminiTransformer:Hi,VertexClaudeTransformer:ta,DeepseekTransformer:Gi,TooluseTransformer:Wi,OpenrouterTransformer:zi,MaxTokenTransformer:Ji,GroqTransformer:Vi,CleancacheTransformer:Ki,EnhanceToolTransformer:Xi,ReasoningTransformer:Qi,SamplingTransformer:Zi,MaxCompletionTokens:ea,CerebrasTransformer:ra,StreamOptionsTransformer:na};var sa=class{constructor(e,t){this.configService=e;this.logger=t}transformers=new Map;registerTransformer(e,t){this.transformers.set(e,t),this.logger.info(`register transformer: ${e}${t.endPoint?` (endpoint: ${t.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[];return this.transformers.forEach((t,n)=>{t.endPoint&&e.push({name:n,transformer:t})}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((t,n)=>{t.endPoint||e.push({name:n,transformer:t})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let t=X(X.resolve(e.path));if(t){let n=new t(e.options);if(n&&typeof n=="object"&&(n.logger=this.logger),!n.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(n.name,n),!0}}return!1}catch(t){return this.logger.error(`load transformer (${e.path}) +error: ${t.message} +stack: ${t.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message} +Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(og).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let t=new e;t&&typeof t=="object"&&(t.logger=this.logger),this.registerTransformer(t.name,t)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let t of e)await this.registerTransformerFromConfig(t)}};function rA(r){let e=eA({bodyLimit:52428800,logger:r});return e.setErrorHandler(qf),e.register(tA),e}var Cl=class{app;configService;llmService;providerService;transformerService;constructor(e={}){this.app=rA(e.logger??!0),this.configService=new mo(e),this.transformerService=new sa(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new yo(this.configService,this.transformerService,this.app.log),this.llmService=new go(this.providerService)})}async register(e,t){await this.app.register(e,t)}addHook(e,t){this.app.addHook(e,t)}async start(){try{this.app._server=this,this.app.addHook("preHandler",(n,o,a)=>{n.url.startsWith("/v1/messages")&&n.body&&(n.log.info({body:n.body},"request body"),n.body.stream,n.body.stream||(n.body.stream=!1)),a()}),this.app.addHook("preHandler",async(n,o)=>{if(!(n.url.startsWith("/api")||n.method!=="POST"))try{let a=n.body;if(!a||!a.model)return o.code(400).send({error:"Missing model in request body"});let[u,l]=a.model.split(",");a.model=l,n.provider=u;return}catch(a){return n.log.error("Error in modelProviderMiddleware:",a),o.code(500).send({error:"Internal server error"})}}),this.app.register(Uf);let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);let t=async n=>{this.app.log.info(`Received ${n}, shutting down gracefully...`),await this.app.close(),process.exit(0)};process.on("SIGINT",()=>t("SIGINT")),process.on("SIGTERM",()=>t("SIGTERM"))}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},QT=Cl;export{QT as default}; +/*! Bundled license information: + +web-streams-polyfill/dist/ponyfill.es2018.js: + (** + * @license + * web-streams-polyfill v3.3.3 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + *) + +fetch-blob/index.js: + (*! fetch-blob. MIT License. Jimmy Wärting *) + +formdata-polyfill/esm.min.js: + (*! formdata-polyfill. MIT License. Jimmy Wärting *) + +node-domexception/index.js: + (*! node-domexception. MIT License. Jimmy Wärting *) + +safe-buffer/index.js: + (*! safe-buffer. MIT License. Feross Aboukhadijeh *) + +gtoken/build/cjs/src/index.cjs: + (*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE *) +*/ +//# sourceMappingURL=server.mjs.map diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/server.mjs.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/server.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..6ffe5fa61dc38990b88fbe0ee937abcf43368dfe --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/server.mjs.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/.pnpm/json5@2.2.3/node_modules/json5/lib/unicode.js", "../../node_modules/.pnpm/json5@2.2.3/node_modules/json5/lib/util.js", "../../node_modules/.pnpm/json5@2.2.3/node_modules/json5/lib/parse.js", "../../node_modules/.pnpm/json5@2.2.3/node_modules/json5/lib/stringify.js", "../../node_modules/.pnpm/json5@2.2.3/node_modules/json5/lib/index.js", "../../node_modules/.pnpm/extend@3.0.2/node_modules/extend/index.js", "../../node_modules/.pnpm/gaxios@7.1.1/node_modules/gaxios/package.json", "../../node_modules/.pnpm/gaxios@7.1.1/node_modules/gaxios/src/util.cts", "../../node_modules/.pnpm/gaxios@7.1.1/node_modules/gaxios/src/common.ts", "../../node_modules/.pnpm/gaxios@7.1.1/node_modules/gaxios/src/retry.ts", "../../node_modules/.pnpm/gaxios@7.1.1/node_modules/gaxios/src/interceptor.ts", "../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js", "../../node_modules/.pnpm/debug@4.4.1_supports-color@5.5.0/node_modules/debug/src/common.js", "../../node_modules/.pnpm/debug@4.4.1_supports-color@5.5.0/node_modules/debug/src/browser.js", "../../node_modules/.pnpm/has-flag@3.0.0/node_modules/has-flag/index.js", "../../node_modules/.pnpm/supports-color@5.5.0/node_modules/supports-color/index.js", "../../node_modules/.pnpm/debug@4.4.1_supports-color@5.5.0/node_modules/debug/src/node.js", "../../node_modules/.pnpm/debug@4.4.1_supports-color@5.5.0/node_modules/debug/src/index.js", "../../node_modules/.pnpm/agent-base@7.1.4/node_modules/agent-base/src/helpers.ts", "../../node_modules/.pnpm/agent-base@7.1.4/node_modules/agent-base/src/index.ts", "../../node_modules/.pnpm/https-proxy-agent@7.0.6/node_modules/https-proxy-agent/src/parse-proxy-response.ts", "../../node_modules/.pnpm/https-proxy-agent@7.0.6/node_modules/https-proxy-agent/src/index.ts", "../../node_modules/.pnpm/data-uri-to-buffer@4.0.1/node_modules/data-uri-to-buffer/src/index.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/utils.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/helpers/miscellaneous.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/helpers/webidl.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/simple-queue.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/abstract-ops/internal-methods.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/generic-reader.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/stub/number-isfinite.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/stub/math-trunc.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/basic.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/readable-stream.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/default-reader.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/target/es2018/stub/async-iterator-prototype.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/async-iterator.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/stub/number-isnan.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/abstract-ops/ecmascript.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/abstract-ops/miscellaneous.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/abstract-ops/queue-with-sizes.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/helpers/array-buffer-view.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/byte-stream-controller.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/reader-options.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/byob-reader.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/abstract-ops/queuing-strategy.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/queuing-strategy.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/underlying-sink.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/writable-stream.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/abort-signal.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/writable-stream.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/globals.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/stub/dom-exception.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/pipe.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/default-controller.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/tee.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/readable-stream-like.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream/from.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/underlying-source.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/iterator-options.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/pipe-options.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/readable-writable-pair.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/readable-stream.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/queuing-strategy-init.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/byte-length-queuing-strategy.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/count-queuing-strategy.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/validators/transformer.ts", "../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/src/lib/transform-stream.ts", "../../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/streams.cjs", "../../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/index.js", "../../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/file.js", "../../node_modules/.pnpm/formdata-polyfill@4.0.10/node_modules/formdata-polyfill/esm.min.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/base.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/fetch-error.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is.js", "../../node_modules/.pnpm/node-domexception@1.0.0/node_modules/node-domexception/index.js", "../../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/from.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/multipart-parser.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/body.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is-redirect.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/response.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/get-search.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/referrer.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/request.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/abort-error.js", "../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/index.js", "../../node_modules/.pnpm/gaxios@7.1.1/node_modules/gaxios/src/gaxios.ts", "../../node_modules/.pnpm/gaxios@7.1.1/node_modules/gaxios/src/index.ts", "../../node_modules/.pnpm/bignumber.js@9.3.1/node_modules/bignumber.js/bignumber.js", "../../node_modules/.pnpm/json-bigint@1.0.0/node_modules/json-bigint/lib/stringify.js", "../../node_modules/.pnpm/json-bigint@1.0.0/node_modules/json-bigint/lib/parse.js", "../../node_modules/.pnpm/json-bigint@1.0.0/node_modules/json-bigint/index.js", "../../node_modules/.pnpm/gcp-metadata@7.0.1/node_modules/gcp-metadata/src/gcp-residency.ts", "../../node_modules/.pnpm/google-logging-utils@1.1.1/node_modules/google-logging-utils/src/colours.ts", "../../node_modules/.pnpm/google-logging-utils@1.1.1/node_modules/google-logging-utils/src/logging-utils.ts", "../../node_modules/.pnpm/google-logging-utils@1.1.1/node_modules/google-logging-utils/src/index.ts", "../../node_modules/.pnpm/gcp-metadata@7.0.1/node_modules/gcp-metadata/src/index.ts", "../../node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/crypto/shared.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/crypto/browser/crypto.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/crypto/node/crypto.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/crypto/crypto.js", "../../node_modules/.pnpm/safe-buffer@5.2.1/node_modules/safe-buffer/index.js", "../../node_modules/.pnpm/ecdsa-sig-formatter@1.0.11/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js", "../../node_modules/.pnpm/ecdsa-sig-formatter@1.0.11/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/util.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/package.json", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/shared.cjs", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/authclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/loginticket.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/oauth2client.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/computeclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/idtokenclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/envDetect.js", "../../node_modules/.pnpm/jws@4.0.0/node_modules/jws/lib/data-stream.js", "../../node_modules/.pnpm/buffer-equal-constant-time@1.0.1/node_modules/buffer-equal-constant-time/index.js", "../../node_modules/.pnpm/jwa@2.0.1/node_modules/jwa/index.js", "../../node_modules/.pnpm/jws@4.0.0/node_modules/jws/lib/tostring.js", "../../node_modules/.pnpm/jws@4.0.0/node_modules/jws/lib/sign-stream.js", "../../node_modules/.pnpm/jws@4.0.0/node_modules/jws/lib/verify-stream.js", "../../node_modules/.pnpm/jws@4.0.0/node_modules/jws/index.js", "../../node_modules/.pnpm/gtoken@8.0.0/node_modules/gtoken/build/cjs/src/index.cjs", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/jwtaccess.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/jwtclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/refreshclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/impersonated.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/oauth2common.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/stscredentials.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/baseexternalclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/identitypoolclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/awsclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/executable-response.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/externalclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/googleauth.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/iam.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/downscopedclient.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/auth/passthrough.js", "../../node_modules/.pnpm/google-auth-library@10.2.0/node_modules/google-auth-library/build/src/index.js", "../../src/server.ts", "../../src/services/config.ts", "../../src/api/middleware.ts", "../../src/utils/request.ts", "../../package.json", "../../src/api/routes.ts", "../../src/services/llm.ts", "../../src/services/provider.ts", "../../node_modules/.pnpm/uuid@11.1.0/node_modules/uuid/dist/esm/stringify.js", "../../node_modules/.pnpm/uuid@11.1.0/node_modules/uuid/dist/esm/rng.js", "../../node_modules/.pnpm/uuid@11.1.0/node_modules/uuid/dist/esm/native.js", "../../node_modules/.pnpm/uuid@11.1.0/node_modules/uuid/dist/esm/v4.js", "../../src/utils/thinking.ts", "../../src/transformer/anthropic.transformer.ts", "../../src/utils/gemini.util.ts", "../../src/transformer/gemini.transformer.ts", "../../src/transformer/vertex-gemini.transformer.ts", "../../src/transformer/deepseek.transformer.ts", "../../src/transformer/tooluse.transformer.ts", "../../src/transformer/openrouter.transformer.ts", "../../src/transformer/maxtoken.transformer.ts", "../../src/transformer/groq.transformer.ts", "../../src/transformer/cleancache.transformer.ts", "../../src/utils/toolArgumentsParser.ts", "../../node_modules/.pnpm/jsonrepair@3.13.0/node_modules/jsonrepair/src/utils/JSONRepairError.ts", "../../node_modules/.pnpm/jsonrepair@3.13.0/node_modules/jsonrepair/src/utils/stringUtils.ts", "../../node_modules/.pnpm/jsonrepair@3.13.0/node_modules/jsonrepair/src/regular/jsonrepair.ts", "../../src/transformer/enhancetool.transformer.ts", "../../src/transformer/reasoning.transformer.ts", "../../src/transformer/sampling.transformer.ts", "../../src/transformer/maxcompletiontokens.transformer.ts", "../../src/utils/vertex-claude.util.ts", "../../src/transformer/vertex-claude.transformer.ts", "../../src/transformer/cerebras.transformer.ts", "../../src/transformer/streamoptions.transformer.ts", "../../src/transformer/index.ts", "../../src/services/transformer.ts"], + "sourcesContent": ["// This is a generated file. Do not edit.\nmodule.exports.Space_Separator = /[\\u1680\\u2000-\\u200A\\u202F\\u205F\\u3000]/\nmodule.exports.ID_Start = /[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086A\\u08A0-\\u08B4\\u08B6-\\u08BD\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u09FC\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\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40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u1884\\u1887-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1C80-\\u1C88\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312E\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FEA\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7AE\\uA7B0-\\uA7B7\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA8FD\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\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46]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC00-\\uDC6E\\uDC80-\\uDD43]|[\\uD80C\\uD81C-\\uD820\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872\\uD874-\\uD879][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2E]|\\uD811[\\uDC00-\\uDE46]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\uDED0-\\uDEED\\uDF00-\\uDF2F\\uDF40-\\uDF43\\uDF63-\\uDF77\\uDF7D-\\uDF8F]|\\uD81B[\\uDF00-\\uDF44\\uDF50\\uDF93-\\uDF9F\\uDFE0\\uDFE1]|\\uD821[\\uDC00-\\uDFEC]|\\uD822[\\uDC00-\\uDEF2]|\\uD82C[\\uDC00-\\uDD1E\\uDD70-\\uDEFB]|\\uD82F[\\uDC00-\\uDC6A\\uDC70-\\uDC7C\\uDC80-\\uDC88\\uDC90-\\uDC99]|\\uD835[\\uDC00-\\uDC54\\uDC56-\\uDC9C\\uDC9E\\uDC9F\\uDCA2\\uDCA5\\uDCA6\\uDCA9-\\uDCAC\\uDCAE-\\uDCB9\\uDCBB\\uDCBD-\\uDCC3\\uDCC5-\\uDD05\\uDD07-\\uDD0A\\uDD0D-\\uDD14\\uDD16-\\uDD1C\\uDD1E-\\uDD39\\uDD3B-\\uDD3E\\uDD40-\\uDD44\\uDD46\\uDD4A-\\uDD50\\uDD52-\\uDEA5\\uDEA8-\\uDEC0\\uDEC2-\\uDEDA\\uDEDC-\\uDEFA\\uDEFC-\\uDF14\\uDF16-\\uDF34\\uDF36-\\uDF4E\\uDF50-\\uDF6E\\uDF70-\\uDF88\\uDF8A-\\uDFA8\\uDFAA-\\uDFC2\\uDFC4-\\uDFCB]|\\uD83A[\\uDC00-\\uDCC4\\uDD00-\\uDD43]|\\uD83B[\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD869[\\uDC00-\\uDED6\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF34\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20-\\uDFFF]|\\uD873[\\uDC00-\\uDEA1\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0]|\\uD87E[\\uDC00-\\uDE1D]/\nmodule.exports.ID_Continue = /[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0300-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u0483-\\u0487\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0610-\\u061A\\u0620-\\u0669\\u066E-\\u06D3\\u06D5-\\u06DC\\u06DF-\\u06E8\\u06EA-\\u06FC\\u06FF\\u0710-\\u074A\\u074D-\\u07B1\\u07C0-\\u07F5\\u07FA\\u0800-\\u082D\\u0840-\\u085B\\u0860-\\u086A\\u08A0-\\u08B4\\u08B6-\\u08BD\\u08D4-\\u08E1\\u08E3-\\u0963\\u0966-\\u096F\\u0971-\\u0983\\u0985-\\u098C\\u098F\\u0990\\u0993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260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u135D-\\u135F\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1714\\u1720-\\u1734\\u1740-\\u1753\\u1760-\\u176C\\u176E-\\u1770\\u1772\\u1773\\u1780-\\u17D3\\u17D7\\u17DC\\u17DD\\u17E0-\\u17E9\\u180B-\\u180D\\u1810-\\u1819\\u1820-\\u1877\\u1880-\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1920-\\u192B\\u1930-\\u193B\\u1946-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u19D0-\\u19D9\\u1A00-\\u1A1B\\u1A20-\\u1A5E\\u1A60-\\u1A7C\\u1A7F-\\u1A89\\u1A90-\\u1A99\\u1AA7\\u1AB0-\\u1ABD\\u1B00-\\u1B4B\\u1B50-\\u1B59\\u1B6B-\\u1B73\\u1B80-\\u1BF3\\u1C00-\\u1C37\\u1C40-\\u1C49\\u1C4D-\\u1C7D\\u1C80-\\u1C88\\u1CD0-\\u1CD2\\u1CD4-\\u1CF9\\u1D00-\\u1DF9\\u1DFB-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u203F\\u2040\\u2054\\u2071\\u207F\\u2090-\\u209C\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D7F-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2DE0-\\u2DFF\\u2E2F\\u3005-\\u3007\\u3021-\\u302F\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u3099\\u309A\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312E\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FEA\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA62B\\uA640-\\uA66F\\uA674-\\uA67D\\uA67F-\\uA6F1\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7AE\\uA7B0-\\uA7B7\\uA7F7-\\uA827\\uA840-\\uA873\\uA880-\\uA8C5\\uA8D0-\\uA8D9\\uA8E0-\\uA8F7\\uA8FB\\uA8FD\\uA900-\\uA92D\\uA930-\\uA953\\uA960-\\uA97C\\uA980-\\uA9C0\\uA9CF-\\uA9D9\\uA9E0-\\uA9FE\\uAA00-\\uAA36\\uAA40-\\uAA4D\\uAA50-\\uAA59\\uAA60-\\uAA76\\uAA7A-\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEF\\uAAF2-\\uAAF6\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-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19\\uDF1D-\\uDF2B\\uDF30-\\uDF39]|\\uD806[\\uDCA0-\\uDCE9\\uDCFF\\uDE00-\\uDE3E\\uDE47\\uDE50-\\uDE83\\uDE86-\\uDE99\\uDEC0-\\uDEF8]|\\uD807[\\uDC00-\\uDC08\\uDC0A-\\uDC36\\uDC38-\\uDC40\\uDC50-\\uDC59\\uDC72-\\uDC8F\\uDC92-\\uDCA7\\uDCA9-\\uDCB6\\uDD00-\\uDD06\\uDD08\\uDD09\\uDD0B-\\uDD36\\uDD3A\\uDD3C\\uDD3D\\uDD3F-\\uDD47\\uDD50-\\uDD59]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC00-\\uDC6E\\uDC80-\\uDD43]|[\\uD80C\\uD81C-\\uD820\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872\\uD874-\\uD879][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2E]|\\uD811[\\uDC00-\\uDE46]|\\uD81A[\\uDC00-\\uDE38\\uDE40-\\uDE5E\\uDE60-\\uDE69\\uDED0-\\uDEED\\uDEF0-\\uDEF4\\uDF00-\\uDF36\\uDF40-\\uDF43\\uDF50-\\uDF59\\uDF63-\\uDF77\\uDF7D-\\uDF8F]|\\uD81B[\\uDF00-\\uDF44\\uDF50-\\uDF7E\\uDF8F-\\uDF9F\\uDFE0\\uDFE1]|\\uD821[\\uDC00-\\uDFEC]|\\uD822[\\uDC00-\\uDEF2]|\\uD82C[\\uDC00-\\uDD1E\\uDD70-\\uDEFB]|\\uD82F[\\uDC00-\\uDC6A\\uDC70-\\uDC7C\\uDC80-\\uDC88\\uDC90-\\uDC99\\uDC9D\\uDC9E]|\\uD834[\\uDD65-\\uDD69\\uDD6D-\\uDD72\\uDD7B-\\uDD82\\uDD85-\\uDD8B\\uDDAA-\\uDDAD\\uDE42-\\uDE44]|\\uD835[\\uDC00-\\uDC54\\uDC56-\\uDC9C\\uDC9E\\uDC9F\\uDCA2\\uDCA5\\uDCA6\\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|\\uD873[\\uDC00-\\uDEA1\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0]|\\uD87E[\\uDC00-\\uDE1D]|\\uDB40[\\uDD00-\\uDDEF]/\n", "const unicode = require('../lib/unicode')\n\nmodule.exports = {\n isSpaceSeparator (c) {\n return typeof c === 'string' && unicode.Space_Separator.test(c)\n },\n\n isIdStartChar (c) {\n return typeof c === 'string' && (\n (c >= 'a' && c <= 'z') ||\n (c >= 'A' && c <= 'Z') ||\n (c === '$') || (c === '_') ||\n unicode.ID_Start.test(c)\n )\n },\n\n isIdContinueChar (c) {\n return typeof c === 'string' && (\n (c >= 'a' && c <= 'z') ||\n (c >= 'A' && c <= 'Z') ||\n (c >= '0' && c <= '9') ||\n (c === '$') || (c === '_') ||\n (c === '\\u200C') || (c === '\\u200D') ||\n unicode.ID_Continue.test(c)\n )\n },\n\n isDigit (c) {\n return typeof c === 'string' && /[0-9]/.test(c)\n },\n\n isHexDigit (c) {\n return typeof c === 'string' && /[0-9A-Fa-f]/.test(c)\n },\n}\n", "const util = require('./util')\n\nlet source\nlet parseState\nlet stack\nlet pos\nlet line\nlet column\nlet token\nlet key\nlet root\n\nmodule.exports = function parse (text, reviver) {\n source = String(text)\n parseState = 'start'\n stack = []\n pos = 0\n line = 1\n column = 0\n token = undefined\n key = undefined\n root = undefined\n\n do {\n token = lex()\n\n // This code is unreachable.\n // if (!parseStates[parseState]) {\n // throw invalidParseState()\n // }\n\n parseStates[parseState]()\n } while (token.type !== 'eof')\n\n if (typeof reviver === 'function') {\n return internalize({'': root}, '', reviver)\n }\n\n return root\n}\n\nfunction internalize (holder, name, reviver) {\n const value = holder[name]\n if (value != null && typeof value === 'object') {\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n const key = String(i)\n const replacement = internalize(value, key, reviver)\n if (replacement === undefined) {\n delete value[key]\n } else {\n Object.defineProperty(value, key, {\n value: replacement,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n }\n }\n } else {\n for (const key in value) {\n const replacement = internalize(value, key, reviver)\n if (replacement === undefined) {\n delete value[key]\n } else {\n Object.defineProperty(value, key, {\n value: replacement,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n }\n }\n }\n }\n\n return reviver.call(holder, name, value)\n}\n\nlet lexState\nlet buffer\nlet doubleQuote\nlet sign\nlet c\n\nfunction lex () {\n lexState = 'default'\n buffer = ''\n doubleQuote = false\n sign = 1\n\n for (;;) {\n c = peek()\n\n // This code is unreachable.\n // if (!lexStates[lexState]) {\n // throw invalidLexState(lexState)\n // }\n\n const token = lexStates[lexState]()\n if (token) {\n return token\n }\n }\n}\n\nfunction peek () {\n if (source[pos]) {\n return String.fromCodePoint(source.codePointAt(pos))\n }\n}\n\nfunction read () {\n const c = peek()\n\n if (c === '\\n') {\n line++\n column = 0\n } else if (c) {\n column += c.length\n } else {\n column++\n }\n\n if (c) {\n pos += c.length\n }\n\n return c\n}\n\nconst lexStates = {\n default () {\n switch (c) {\n case '\\t':\n case '\\v':\n case '\\f':\n case ' ':\n case '\\u00A0':\n case '\\uFEFF':\n case '\\n':\n case '\\r':\n case '\\u2028':\n case '\\u2029':\n read()\n return\n\n case '/':\n read()\n lexState = 'comment'\n return\n\n case undefined:\n read()\n return newToken('eof')\n }\n\n if (util.isSpaceSeparator(c)) {\n read()\n return\n }\n\n // This code is unreachable.\n // if (!lexStates[parseState]) {\n // throw invalidLexState(parseState)\n // }\n\n return lexStates[parseState]()\n },\n\n comment () {\n switch (c) {\n case '*':\n read()\n lexState = 'multiLineComment'\n return\n\n case '/':\n read()\n lexState = 'singleLineComment'\n return\n }\n\n throw invalidChar(read())\n },\n\n multiLineComment () {\n switch (c) {\n case '*':\n read()\n lexState = 'multiLineCommentAsterisk'\n return\n\n case undefined:\n throw invalidChar(read())\n }\n\n read()\n },\n\n multiLineCommentAsterisk () {\n switch (c) {\n case '*':\n read()\n return\n\n case '/':\n read()\n lexState = 'default'\n return\n\n case undefined:\n throw invalidChar(read())\n }\n\n read()\n lexState = 'multiLineComment'\n },\n\n singleLineComment () {\n switch (c) {\n case '\\n':\n case '\\r':\n case '\\u2028':\n case '\\u2029':\n read()\n lexState = 'default'\n return\n\n case undefined:\n read()\n return newToken('eof')\n }\n\n read()\n },\n\n value () {\n switch (c) {\n case '{':\n case '[':\n return newToken('punctuator', read())\n\n case 'n':\n read()\n literal('ull')\n return newToken('null', null)\n\n case 't':\n read()\n literal('rue')\n return newToken('boolean', true)\n\n case 'f':\n read()\n literal('alse')\n return newToken('boolean', false)\n\n case '-':\n case '+':\n if (read() === '-') {\n sign = -1\n }\n\n lexState = 'sign'\n return\n\n case '.':\n buffer = read()\n lexState = 'decimalPointLeading'\n return\n\n case '0':\n buffer = read()\n lexState = 'zero'\n return\n\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n buffer = read()\n lexState = 'decimalInteger'\n return\n\n case 'I':\n read()\n literal('nfinity')\n return newToken('numeric', Infinity)\n\n case 'N':\n read()\n literal('aN')\n return newToken('numeric', NaN)\n\n case '\"':\n case \"'\":\n doubleQuote = (read() === '\"')\n buffer = ''\n lexState = 'string'\n return\n }\n\n throw invalidChar(read())\n },\n\n identifierNameStartEscape () {\n if (c !== 'u') {\n throw invalidChar(read())\n }\n\n read()\n const u = unicodeEscape()\n switch (u) {\n case '$':\n case '_':\n break\n\n default:\n if (!util.isIdStartChar(u)) {\n throw invalidIdentifier()\n }\n\n break\n }\n\n buffer += u\n lexState = 'identifierName'\n },\n\n identifierName () {\n switch (c) {\n case '$':\n case '_':\n case '\\u200C':\n case '\\u200D':\n buffer += read()\n return\n\n case '\\\\':\n read()\n lexState = 'identifierNameEscape'\n return\n }\n\n if (util.isIdContinueChar(c)) {\n buffer += read()\n return\n }\n\n return newToken('identifier', buffer)\n },\n\n identifierNameEscape () {\n if (c !== 'u') {\n throw invalidChar(read())\n }\n\n read()\n const u = unicodeEscape()\n switch (u) {\n case '$':\n case '_':\n case '\\u200C':\n case '\\u200D':\n break\n\n default:\n if (!util.isIdContinueChar(u)) {\n throw invalidIdentifier()\n }\n\n break\n }\n\n buffer += u\n lexState = 'identifierName'\n },\n\n sign () {\n switch (c) {\n case '.':\n buffer = read()\n lexState = 'decimalPointLeading'\n return\n\n case '0':\n buffer = read()\n lexState = 'zero'\n return\n\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n buffer = read()\n lexState = 'decimalInteger'\n return\n\n case 'I':\n read()\n literal('nfinity')\n return newToken('numeric', sign * Infinity)\n\n case 'N':\n read()\n literal('aN')\n return newToken('numeric', NaN)\n }\n\n throw invalidChar(read())\n },\n\n zero () {\n switch (c) {\n case '.':\n buffer += read()\n lexState = 'decimalPoint'\n return\n\n case 'e':\n case 'E':\n buffer += read()\n lexState = 'decimalExponent'\n return\n\n case 'x':\n case 'X':\n buffer += read()\n lexState = 'hexadecimal'\n return\n }\n\n return newToken('numeric', sign * 0)\n },\n\n decimalInteger () {\n switch (c) {\n case '.':\n buffer += read()\n lexState = 'decimalPoint'\n return\n\n case 'e':\n case 'E':\n buffer += read()\n lexState = 'decimalExponent'\n return\n }\n\n if (util.isDigit(c)) {\n buffer += read()\n return\n }\n\n return newToken('numeric', sign * Number(buffer))\n },\n\n decimalPointLeading () {\n if (util.isDigit(c)) {\n buffer += read()\n lexState = 'decimalFraction'\n return\n }\n\n throw invalidChar(read())\n },\n\n decimalPoint () {\n switch (c) {\n case 'e':\n case 'E':\n buffer += read()\n lexState = 'decimalExponent'\n return\n }\n\n if (util.isDigit(c)) {\n buffer += read()\n lexState = 'decimalFraction'\n return\n }\n\n return newToken('numeric', sign * Number(buffer))\n },\n\n decimalFraction () {\n switch (c) {\n case 'e':\n case 'E':\n buffer += read()\n lexState = 'decimalExponent'\n return\n }\n\n if (util.isDigit(c)) {\n buffer += read()\n return\n }\n\n return newToken('numeric', sign * Number(buffer))\n },\n\n decimalExponent () {\n switch (c) {\n case '+':\n case '-':\n buffer += read()\n lexState = 'decimalExponentSign'\n return\n }\n\n if (util.isDigit(c)) {\n buffer += read()\n lexState = 'decimalExponentInteger'\n return\n }\n\n throw invalidChar(read())\n },\n\n decimalExponentSign () {\n if (util.isDigit(c)) {\n buffer += read()\n lexState = 'decimalExponentInteger'\n return\n }\n\n throw invalidChar(read())\n },\n\n decimalExponentInteger () {\n if (util.isDigit(c)) {\n buffer += read()\n return\n }\n\n return newToken('numeric', sign * Number(buffer))\n },\n\n hexadecimal () {\n if (util.isHexDigit(c)) {\n buffer += read()\n lexState = 'hexadecimalInteger'\n return\n }\n\n throw invalidChar(read())\n },\n\n hexadecimalInteger () {\n if (util.isHexDigit(c)) {\n buffer += read()\n return\n }\n\n return newToken('numeric', sign * Number(buffer))\n },\n\n string () {\n switch (c) {\n case '\\\\':\n read()\n buffer += escape()\n return\n\n case '\"':\n if (doubleQuote) {\n read()\n return newToken('string', buffer)\n }\n\n buffer += read()\n return\n\n case \"'\":\n if (!doubleQuote) {\n read()\n return newToken('string', buffer)\n }\n\n buffer += read()\n return\n\n case '\\n':\n case '\\r':\n throw invalidChar(read())\n\n case '\\u2028':\n case '\\u2029':\n separatorChar(c)\n break\n\n case undefined:\n throw invalidChar(read())\n }\n\n buffer += read()\n },\n\n start () {\n switch (c) {\n case '{':\n case '[':\n return newToken('punctuator', read())\n\n // This code is unreachable since the default lexState handles eof.\n // case undefined:\n // return newToken('eof')\n }\n\n lexState = 'value'\n },\n\n beforePropertyName () {\n switch (c) {\n case '$':\n case '_':\n buffer = read()\n lexState = 'identifierName'\n return\n\n case '\\\\':\n read()\n lexState = 'identifierNameStartEscape'\n return\n\n case '}':\n return newToken('punctuator', read())\n\n case '\"':\n case \"'\":\n doubleQuote = (read() === '\"')\n lexState = 'string'\n return\n }\n\n if (util.isIdStartChar(c)) {\n buffer += read()\n lexState = 'identifierName'\n return\n }\n\n throw invalidChar(read())\n },\n\n afterPropertyName () {\n if (c === ':') {\n return newToken('punctuator', read())\n }\n\n throw invalidChar(read())\n },\n\n beforePropertyValue () {\n lexState = 'value'\n },\n\n afterPropertyValue () {\n switch (c) {\n case ',':\n case '}':\n return newToken('punctuator', read())\n }\n\n throw invalidChar(read())\n },\n\n beforeArrayValue () {\n if (c === ']') {\n return newToken('punctuator', read())\n }\n\n lexState = 'value'\n },\n\n afterArrayValue () {\n switch (c) {\n case ',':\n case ']':\n return newToken('punctuator', read())\n }\n\n throw invalidChar(read())\n },\n\n end () {\n // This code is unreachable since it's handled by the default lexState.\n // if (c === undefined) {\n // read()\n // return newToken('eof')\n // }\n\n throw invalidChar(read())\n },\n}\n\nfunction newToken (type, value) {\n return {\n type,\n value,\n line,\n column,\n }\n}\n\nfunction literal (s) {\n for (const c of s) {\n const p = peek()\n\n if (p !== c) {\n throw invalidChar(read())\n }\n\n read()\n }\n}\n\nfunction escape () {\n const c = peek()\n switch (c) {\n case 'b':\n read()\n return '\\b'\n\n case 'f':\n read()\n return '\\f'\n\n case 'n':\n read()\n return '\\n'\n\n case 'r':\n read()\n return '\\r'\n\n case 't':\n read()\n return '\\t'\n\n case 'v':\n read()\n return '\\v'\n\n case '0':\n read()\n if (util.isDigit(peek())) {\n throw invalidChar(read())\n }\n\n return '\\0'\n\n case 'x':\n read()\n return hexEscape()\n\n case 'u':\n read()\n return unicodeEscape()\n\n case '\\n':\n case '\\u2028':\n case '\\u2029':\n read()\n return ''\n\n case '\\r':\n read()\n if (peek() === '\\n') {\n read()\n }\n\n return ''\n\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n throw invalidChar(read())\n\n case undefined:\n throw invalidChar(read())\n }\n\n return read()\n}\n\nfunction hexEscape () {\n let buffer = ''\n let c = peek()\n\n if (!util.isHexDigit(c)) {\n throw invalidChar(read())\n }\n\n buffer += read()\n\n c = peek()\n if (!util.isHexDigit(c)) {\n throw invalidChar(read())\n }\n\n buffer += read()\n\n return String.fromCodePoint(parseInt(buffer, 16))\n}\n\nfunction unicodeEscape () {\n let buffer = ''\n let count = 4\n\n while (count-- > 0) {\n const c = peek()\n if (!util.isHexDigit(c)) {\n throw invalidChar(read())\n }\n\n buffer += read()\n }\n\n return String.fromCodePoint(parseInt(buffer, 16))\n}\n\nconst parseStates = {\n start () {\n if (token.type === 'eof') {\n throw invalidEOF()\n }\n\n push()\n },\n\n beforePropertyName () {\n switch (token.type) {\n case 'identifier':\n case 'string':\n key = token.value\n parseState = 'afterPropertyName'\n return\n\n case 'punctuator':\n // This code is unreachable since it's handled by the lexState.\n // if (token.value !== '}') {\n // throw invalidToken()\n // }\n\n pop()\n return\n\n case 'eof':\n throw invalidEOF()\n }\n\n // This code is unreachable since it's handled by the lexState.\n // throw invalidToken()\n },\n\n afterPropertyName () {\n // This code is unreachable since it's handled by the lexState.\n // if (token.type !== 'punctuator' || token.value !== ':') {\n // throw invalidToken()\n // }\n\n if (token.type === 'eof') {\n throw invalidEOF()\n }\n\n parseState = 'beforePropertyValue'\n },\n\n beforePropertyValue () {\n if (token.type === 'eof') {\n throw invalidEOF()\n }\n\n push()\n },\n\n beforeArrayValue () {\n if (token.type === 'eof') {\n throw invalidEOF()\n }\n\n if (token.type === 'punctuator' && token.value === ']') {\n pop()\n return\n }\n\n push()\n },\n\n afterPropertyValue () {\n // This code is unreachable since it's handled by the lexState.\n // if (token.type !== 'punctuator') {\n // throw invalidToken()\n // }\n\n if (token.type === 'eof') {\n throw invalidEOF()\n }\n\n switch (token.value) {\n case ',':\n parseState = 'beforePropertyName'\n return\n\n case '}':\n pop()\n }\n\n // This code is unreachable since it's handled by the lexState.\n // throw invalidToken()\n },\n\n afterArrayValue () {\n // This code is unreachable since it's handled by the lexState.\n // if (token.type !== 'punctuator') {\n // throw invalidToken()\n // }\n\n if (token.type === 'eof') {\n throw invalidEOF()\n }\n\n switch (token.value) {\n case ',':\n parseState = 'beforeArrayValue'\n return\n\n case ']':\n pop()\n }\n\n // This code is unreachable since it's handled by the lexState.\n // throw invalidToken()\n },\n\n end () {\n // This code is unreachable since it's handled by the lexState.\n // if (token.type !== 'eof') {\n // throw invalidToken()\n // }\n },\n}\n\nfunction push () {\n let value\n\n switch (token.type) {\n case 'punctuator':\n switch (token.value) {\n case '{':\n value = {}\n break\n\n case '[':\n value = []\n break\n }\n\n break\n\n case 'null':\n case 'boolean':\n case 'numeric':\n case 'string':\n value = token.value\n break\n\n // This code is unreachable.\n // default:\n // throw invalidToken()\n }\n\n if (root === undefined) {\n root = value\n } else {\n const parent = stack[stack.length - 1]\n if (Array.isArray(parent)) {\n parent.push(value)\n } else {\n Object.defineProperty(parent, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n }\n }\n\n if (value !== null && typeof value === 'object') {\n stack.push(value)\n\n if (Array.isArray(value)) {\n parseState = 'beforeArrayValue'\n } else {\n parseState = 'beforePropertyName'\n }\n } else {\n const current = stack[stack.length - 1]\n if (current == null) {\n parseState = 'end'\n } else if (Array.isArray(current)) {\n parseState = 'afterArrayValue'\n } else {\n parseState = 'afterPropertyValue'\n }\n }\n}\n\nfunction pop () {\n stack.pop()\n\n const current = stack[stack.length - 1]\n if (current == null) {\n parseState = 'end'\n } else if (Array.isArray(current)) {\n parseState = 'afterArrayValue'\n } else {\n parseState = 'afterPropertyValue'\n }\n}\n\n// This code is unreachable.\n// function invalidParseState () {\n// return new Error(`JSON5: invalid parse state '${parseState}'`)\n// }\n\n// This code is unreachable.\n// function invalidLexState (state) {\n// return new Error(`JSON5: invalid lex state '${state}'`)\n// }\n\nfunction invalidChar (c) {\n if (c === undefined) {\n return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)\n }\n\n return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)\n}\n\nfunction invalidEOF () {\n return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)\n}\n\n// This code is unreachable.\n// function invalidToken () {\n// if (token.type === 'eof') {\n// return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)\n// }\n\n// const c = String.fromCodePoint(token.value.codePointAt(0))\n// return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)\n// }\n\nfunction invalidIdentifier () {\n column -= 5\n return syntaxError(`JSON5: invalid identifier character at ${line}:${column}`)\n}\n\nfunction separatorChar (c) {\n console.warn(`JSON5: '${formatChar(c)}' in strings is not valid ECMAScript; consider escaping`)\n}\n\nfunction formatChar (c) {\n const replacements = {\n \"'\": \"\\\\'\",\n '\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n '\\v': '\\\\v',\n '\\0': '\\\\0',\n '\\u2028': '\\\\u2028',\n '\\u2029': '\\\\u2029',\n }\n\n if (replacements[c]) {\n return replacements[c]\n }\n\n if (c < ' ') {\n const hexString = c.charCodeAt(0).toString(16)\n return '\\\\x' + ('00' + hexString).substring(hexString.length)\n }\n\n return c\n}\n\nfunction syntaxError (message) {\n const err = new SyntaxError(message)\n err.lineNumber = line\n err.columnNumber = column\n return err\n}\n", "const util = require('./util')\n\nmodule.exports = function stringify (value, replacer, space) {\n const stack = []\n let indent = ''\n let propertyList\n let replacerFunc\n let gap = ''\n let quote\n\n if (\n replacer != null &&\n typeof replacer === 'object' &&\n !Array.isArray(replacer)\n ) {\n space = replacer.space\n quote = replacer.quote\n replacer = replacer.replacer\n }\n\n if (typeof replacer === 'function') {\n replacerFunc = replacer\n } else if (Array.isArray(replacer)) {\n propertyList = []\n for (const v of replacer) {\n let item\n\n if (typeof v === 'string') {\n item = v\n } else if (\n typeof v === 'number' ||\n v instanceof String ||\n v instanceof Number\n ) {\n item = String(v)\n }\n\n if (item !== undefined && propertyList.indexOf(item) < 0) {\n propertyList.push(item)\n }\n }\n }\n\n if (space instanceof Number) {\n space = Number(space)\n } else if (space instanceof String) {\n space = String(space)\n }\n\n if (typeof space === 'number') {\n if (space > 0) {\n space = Math.min(10, Math.floor(space))\n gap = ' '.substr(0, space)\n }\n } else if (typeof space === 'string') {\n gap = space.substr(0, 10)\n }\n\n return serializeProperty('', {'': value})\n\n function serializeProperty (key, holder) {\n let value = holder[key]\n if (value != null) {\n if (typeof value.toJSON5 === 'function') {\n value = value.toJSON5(key)\n } else if (typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n }\n }\n\n if (replacerFunc) {\n value = replacerFunc.call(holder, key, value)\n }\n\n if (value instanceof Number) {\n value = Number(value)\n } else if (value instanceof String) {\n value = String(value)\n } else if (value instanceof Boolean) {\n value = value.valueOf()\n }\n\n switch (value) {\n case null: return 'null'\n case true: return 'true'\n case false: return 'false'\n }\n\n if (typeof value === 'string') {\n return quoteString(value, false)\n }\n\n if (typeof value === 'number') {\n return String(value)\n }\n\n if (typeof value === 'object') {\n return Array.isArray(value) ? serializeArray(value) : serializeObject(value)\n }\n\n return undefined\n }\n\n function quoteString (value) {\n const quotes = {\n \"'\": 0.1,\n '\"': 0.2,\n }\n\n const replacements = {\n \"'\": \"\\\\'\",\n '\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n '\\v': '\\\\v',\n '\\0': '\\\\0',\n '\\u2028': '\\\\u2028',\n '\\u2029': '\\\\u2029',\n }\n\n let product = ''\n\n for (let i = 0; i < value.length; i++) {\n const c = value[i]\n switch (c) {\n case \"'\":\n case '\"':\n quotes[c]++\n product += c\n continue\n\n case '\\0':\n if (util.isDigit(value[i + 1])) {\n product += '\\\\x00'\n continue\n }\n }\n\n if (replacements[c]) {\n product += replacements[c]\n continue\n }\n\n if (c < ' ') {\n let hexString = c.charCodeAt(0).toString(16)\n product += '\\\\x' + ('00' + hexString).substring(hexString.length)\n continue\n }\n\n product += c\n }\n\n const quoteChar = quote || Object.keys(quotes).reduce((a, b) => (quotes[a] < quotes[b]) ? a : b)\n\n product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar])\n\n return quoteChar + product + quoteChar\n }\n\n function serializeObject (value) {\n if (stack.indexOf(value) >= 0) {\n throw TypeError('Converting circular structure to JSON5')\n }\n\n stack.push(value)\n\n let stepback = indent\n indent = indent + gap\n\n let keys = propertyList || Object.keys(value)\n let partial = []\n for (const key of keys) {\n const propertyString = serializeProperty(key, value)\n if (propertyString !== undefined) {\n let member = serializeKey(key) + ':'\n if (gap !== '') {\n member += ' '\n }\n member += propertyString\n partial.push(member)\n }\n }\n\n let final\n if (partial.length === 0) {\n final = '{}'\n } else {\n let properties\n if (gap === '') {\n properties = partial.join(',')\n final = '{' + properties + '}'\n } else {\n let separator = ',\\n' + indent\n properties = partial.join(separator)\n final = '{\\n' + indent + properties + ',\\n' + stepback + '}'\n }\n }\n\n stack.pop()\n indent = stepback\n return final\n }\n\n function serializeKey (key) {\n if (key.length === 0) {\n return quoteString(key, true)\n }\n\n const firstChar = String.fromCodePoint(key.codePointAt(0))\n if (!util.isIdStartChar(firstChar)) {\n return quoteString(key, true)\n }\n\n for (let i = firstChar.length; i < key.length; i++) {\n if (!util.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) {\n return quoteString(key, true)\n }\n }\n\n return key\n }\n\n function serializeArray (value) {\n if (stack.indexOf(value) >= 0) {\n throw TypeError('Converting circular structure to JSON5')\n }\n\n stack.push(value)\n\n let stepback = indent\n indent = indent + gap\n\n let partial = []\n for (let i = 0; i < value.length; i++) {\n const propertyString = serializeProperty(String(i), value)\n partial.push((propertyString !== undefined) ? propertyString : 'null')\n }\n\n let final\n if (partial.length === 0) {\n final = '[]'\n } else {\n if (gap === '') {\n let properties = partial.join(',')\n final = '[' + properties + ']'\n } else {\n let separator = ',\\n' + indent\n let properties = partial.join(separator)\n final = '[\\n' + indent + properties + ',\\n' + stepback + ']'\n }\n }\n\n stack.pop()\n indent = stepback\n return final\n }\n}\n", "const parse = require('./parse')\nconst stringify = require('./stringify')\n\nconst JSON5 = {\n parse,\n stringify,\n}\n\nmodule.exports = JSON5\n", "'use strict';\n\nvar hasOwn = Object.prototype.hasOwnProperty;\nvar toStr = Object.prototype.toString;\nvar defineProperty = Object.defineProperty;\nvar gOPD = Object.getOwnPropertyDescriptor;\n\nvar isArray = function isArray(arr) {\n\tif (typeof Array.isArray === 'function') {\n\t\treturn Array.isArray(arr);\n\t}\n\n\treturn toStr.call(arr) === '[object Array]';\n};\n\nvar isPlainObject = function isPlainObject(obj) {\n\tif (!obj || toStr.call(obj) !== '[object Object]') {\n\t\treturn false;\n\t}\n\n\tvar hasOwnConstructor = hasOwn.call(obj, 'constructor');\n\tvar hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');\n\t// Not own constructor property must be Object\n\tif (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {\n\t\treturn false;\n\t}\n\n\t// Own properties are enumerated firstly, so to speed up,\n\t// if last one is own, then all properties are own.\n\tvar key;\n\tfor (key in obj) { /**/ }\n\n\treturn typeof key === 'undefined' || hasOwn.call(obj, key);\n};\n\n// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target\nvar setProperty = function setProperty(target, options) {\n\tif (defineProperty && options.name === '__proto__') {\n\t\tdefineProperty(target, options.name, {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\tvalue: options.newValue,\n\t\t\twritable: true\n\t\t});\n\t} else {\n\t\ttarget[options.name] = options.newValue;\n\t}\n};\n\n// Return undefined instead of __proto__ if '__proto__' is not an own property\nvar getProperty = function getProperty(obj, name) {\n\tif (name === '__proto__') {\n\t\tif (!hasOwn.call(obj, name)) {\n\t\t\treturn void 0;\n\t\t} else if (gOPD) {\n\t\t\t// In early versions of node, obj['__proto__'] is buggy when obj has\n\t\t\t// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.\n\t\t\treturn gOPD(obj, name).value;\n\t\t}\n\t}\n\n\treturn obj[name];\n};\n\nmodule.exports = function extend() {\n\tvar options, name, src, copy, copyIsArray, clone;\n\tvar target = arguments[0];\n\tvar i = 1;\n\tvar length = arguments.length;\n\tvar deep = false;\n\n\t// Handle a deep copy situation\n\tif (typeof target === 'boolean') {\n\t\tdeep = target;\n\t\ttarget = arguments[1] || {};\n\t\t// skip the boolean and the target\n\t\ti = 2;\n\t}\n\tif (target == null || (typeof target !== 'object' && typeof target !== 'function')) {\n\t\ttarget = {};\n\t}\n\n\tfor (; i < length; ++i) {\n\t\toptions = arguments[i];\n\t\t// Only deal with non-null/undefined values\n\t\tif (options != null) {\n\t\t\t// Extend the base object\n\t\t\tfor (name in options) {\n\t\t\t\tsrc = getProperty(target, name);\n\t\t\t\tcopy = getProperty(options, name);\n\n\t\t\t\t// Prevent never-ending loop\n\t\t\t\tif (target !== copy) {\n\t\t\t\t\t// Recurse if we're merging plain objects or arrays\n\t\t\t\t\tif (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {\n\t\t\t\t\t\tif (copyIsArray) {\n\t\t\t\t\t\t\tcopyIsArray = false;\n\t\t\t\t\t\t\tclone = src && isArray(src) ? src : [];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tclone = src && isPlainObject(src) ? src : {};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Never move original objects, clone them\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: extend(deep, clone, copy) });\n\n\t\t\t\t\t// Don't bring in undefined values\n\t\t\t\t\t} else if (typeof copy !== 'undefined') {\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: copy });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return the modified object\n\treturn target;\n};\n", "{\n \"name\": \"gaxios\",\n \"version\": \"7.1.1\",\n \"description\": \"A simple common HTTP client specifically for Google APIs and services.\",\n \"main\": \"build/cjs/src/index.js\",\n \"types\": \"build/cjs/src/index.d.ts\",\n \"files\": [\n \"build/\"\n ],\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./build/esm/src/index.d.ts\",\n \"default\": \"./build/esm/src/index.js\"\n },\n \"require\": {\n \"types\": \"./build/cjs/src/index.d.ts\",\n \"default\": \"./build/cjs/src/index.js\"\n }\n }\n },\n \"scripts\": {\n \"lint\": \"gts check --no-inline-config\",\n \"test\": \"c8 mocha build/esm/test\",\n \"presystem-test\": \"npm run compile\",\n \"system-test\": \"mocha build/esm/system-test --timeout 80000\",\n \"compile\": \"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs\",\n \"fix\": \"gts fix\",\n \"prepare\": \"npm run compile\",\n \"pretest\": \"npm run compile\",\n \"webpack\": \"webpack\",\n \"prebrowser-test\": \"npm run compile\",\n \"browser-test\": \"node build/browser-test/browser-test-runner.js\",\n \"docs\": \"jsdoc -c .jsdoc.js\",\n \"docs-test\": \"linkinator docs\",\n \"predocs-test\": \"npm run docs\",\n \"samples-test\": \"cd samples/ && npm link ../ && npm test && cd ../\",\n \"prelint\": \"cd samples; npm link ../; npm install\",\n \"clean\": \"gts clean\"\n },\n \"repository\": \"googleapis/gaxios\",\n \"keywords\": [\n \"google\"\n ],\n \"engines\": {\n \"node\": \">=18\"\n },\n \"author\": \"Google, LLC\",\n \"license\": \"Apache-2.0\",\n \"devDependencies\": {\n \"@babel/plugin-proposal-private-methods\": \"^7.18.6\",\n \"@types/cors\": \"^2.8.6\",\n \"@types/express\": \"^5.0.0\",\n \"@types/extend\": \"^3.0.1\",\n \"@types/mocha\": \"^10.0.10\",\n \"@types/multiparty\": \"4.2.1\",\n \"@types/mv\": \"^2.1.0\",\n \"@types/ncp\": \"^2.0.1\",\n \"@types/node\": \"^22.0.0\",\n \"@types/sinon\": \"^17.0.0\",\n \"@types/tmp\": \"0.2.6\",\n \"assert\": \"^2.0.0\",\n \"browserify\": \"^17.0.0\",\n \"c8\": \"^10.0.0\",\n \"cors\": \"^2.8.5\",\n \"express\": \"^5.0.0\",\n \"gts\": \"^6.0.0\",\n \"is-docker\": \"^3.0.0\",\n \"jsdoc\": \"^4.0.0\",\n \"jsdoc-fresh\": \"^4.0.0\",\n \"jsdoc-region-tag\": \"^3.0.0\",\n \"karma\": \"^6.0.0\",\n \"karma-chrome-launcher\": \"^3.0.0\",\n \"karma-coverage\": \"^2.0.0\",\n \"karma-firefox-launcher\": \"^2.0.0\",\n \"karma-mocha\": \"^2.0.0\",\n \"karma-remap-coverage\": \"^0.1.5\",\n \"karma-sourcemap-loader\": \"^0.4.0\",\n \"karma-webpack\": \"^5.0.1\",\n \"linkinator\": \"^6.1.2\",\n \"mocha\": \"^11.1.0\",\n \"multiparty\": \"^4.2.1\",\n \"mv\": \"^2.1.1\",\n \"ncp\": \"^2.0.0\",\n \"nock\": \"^14.0.0-beta.13\",\n \"null-loader\": \"^4.0.0\",\n \"pack-n-play\": \"^3.0.0\",\n \"puppeteer\": \"^24.0.0\",\n \"sinon\": \"^20.0.0\",\n \"stream-browserify\": \"^3.0.0\",\n \"tmp\": \"0.2.3\",\n \"ts-loader\": \"^9.5.2\",\n \"typescript\": \"^5.8.3\",\n \"webpack\": \"^5.35.0\",\n \"webpack-cli\": \"^6.0.1\"\n },\n \"dependencies\": {\n \"extend\": \"^3.0.2\",\n \"https-proxy-agent\": \"^7.0.1\",\n \"node-fetch\": \"^3.3.2\"\n }\n}\n", null, null, null, null, "/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n", "\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(/\\s+/g, ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n", "/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n", "'use strict';\nmodule.exports = (flag, argv) => {\n\targv = argv || process.argv;\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst pos = argv.indexOf(prefix + flag);\n\tconst terminatorPos = argv.indexOf('--');\n\treturn pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);\n};\n", "'use strict';\nconst os = require('os');\nconst hasFlag = require('has-flag');\n\nconst env = process.env;\n\nlet forceColor;\nif (hasFlag('no-color') ||\n\thasFlag('no-colors') ||\n\thasFlag('color=false')) {\n\tforceColor = false;\n} else if (hasFlag('color') ||\n\thasFlag('colors') ||\n\thasFlag('color=true') ||\n\thasFlag('color=always')) {\n\tforceColor = true;\n}\nif ('FORCE_COLOR' in env) {\n\tforceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3\n\t};\n}\n\nfunction supportsColor(stream) {\n\tif (forceColor === false) {\n\t\treturn 0;\n\t}\n\n\tif (hasFlag('color=16m') ||\n\t\thasFlag('color=full') ||\n\t\thasFlag('color=truecolor')) {\n\t\treturn 3;\n\t}\n\n\tif (hasFlag('color=256')) {\n\t\treturn 2;\n\t}\n\n\tif (stream && !stream.isTTY && forceColor !== true) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor ? 1 : 0;\n\n\tif (process.platform === 'win32') {\n\t\t// Node.js 7.5.0 is the first version of Node.js to include a patch to\n\t\t// libuv that enables 256 color output on Windows. Anything earlier and it\n\t\t// won't work. However, here we target Node.js 8 at minimum as it is an LTS\n\t\t// release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows\n\t\t// release that supports 256 colors. Windows 10 build 14931 is the first release\n\t\t// that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(process.versions.node.split('.')[0]) >= 8 &&\n\t\t\tNumber(osRelease[0]) >= 10 &&\n\t\t\tNumber(osRelease[2]) >= 10586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app':\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\tcase 'Apple_Terminal':\n\t\t\t\treturn 2;\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\treturn min;\n}\n\nfunction getSupportLevel(stream) {\n\tconst level = supportsColor(stream);\n\treturn translateLevel(level);\n}\n\nmodule.exports = {\n\tsupportsColor: getSupportLevel,\n\tstdout: getSupportLevel(process.stdout),\n\tstderr: getSupportLevel(process.stderr)\n};\n", "/**\n * Module dependencies.\n */\n\nconst tty = require('tty');\nconst util = require('util');\n\n/**\n * This is the Node.js implementation of `debug()`.\n */\n\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.destroy = util.deprecate(\n\t() => {},\n\t'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'\n);\n\n/**\n * Colors.\n */\n\nexports.colors = [6, 2, 3, 4, 5, 1];\n\ntry {\n\t// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)\n\t// eslint-disable-next-line import/no-extraneous-dependencies\n\tconst supportsColor = require('supports-color');\n\n\tif (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {\n\t\texports.colors = [\n\t\t\t20,\n\t\t\t21,\n\t\t\t26,\n\t\t\t27,\n\t\t\t32,\n\t\t\t33,\n\t\t\t38,\n\t\t\t39,\n\t\t\t40,\n\t\t\t41,\n\t\t\t42,\n\t\t\t43,\n\t\t\t44,\n\t\t\t45,\n\t\t\t56,\n\t\t\t57,\n\t\t\t62,\n\t\t\t63,\n\t\t\t68,\n\t\t\t69,\n\t\t\t74,\n\t\t\t75,\n\t\t\t76,\n\t\t\t77,\n\t\t\t78,\n\t\t\t79,\n\t\t\t80,\n\t\t\t81,\n\t\t\t92,\n\t\t\t93,\n\t\t\t98,\n\t\t\t99,\n\t\t\t112,\n\t\t\t113,\n\t\t\t128,\n\t\t\t129,\n\t\t\t134,\n\t\t\t135,\n\t\t\t148,\n\t\t\t149,\n\t\t\t160,\n\t\t\t161,\n\t\t\t162,\n\t\t\t163,\n\t\t\t164,\n\t\t\t165,\n\t\t\t166,\n\t\t\t167,\n\t\t\t168,\n\t\t\t169,\n\t\t\t170,\n\t\t\t171,\n\t\t\t172,\n\t\t\t173,\n\t\t\t178,\n\t\t\t179,\n\t\t\t184,\n\t\t\t185,\n\t\t\t196,\n\t\t\t197,\n\t\t\t198,\n\t\t\t199,\n\t\t\t200,\n\t\t\t201,\n\t\t\t202,\n\t\t\t203,\n\t\t\t204,\n\t\t\t205,\n\t\t\t206,\n\t\t\t207,\n\t\t\t208,\n\t\t\t209,\n\t\t\t214,\n\t\t\t215,\n\t\t\t220,\n\t\t\t221\n\t\t];\n\t}\n} catch (error) {\n\t// Swallow - we only care if `supports-color` is available; it doesn't have to be.\n}\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(key => {\n\treturn /^debug_/i.test(key);\n}).reduce((obj, key) => {\n\t// Camel-case\n\tconst prop = key\n\t\t.substring(6)\n\t\t.toLowerCase()\n\t\t.replace(/_([a-z])/g, (_, k) => {\n\t\t\treturn k.toUpperCase();\n\t\t});\n\n\t// Coerce string value into JS value\n\tlet val = process.env[key];\n\tif (/^(yes|on|true|enabled)$/i.test(val)) {\n\t\tval = true;\n\t} else if (/^(no|off|false|disabled)$/i.test(val)) {\n\t\tval = false;\n\t} else if (val === 'null') {\n\t\tval = null;\n\t} else {\n\t\tval = Number(val);\n\t}\n\n\tobj[prop] = val;\n\treturn obj;\n}, {});\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n\treturn 'colors' in exports.inspectOpts ?\n\t\tBoolean(exports.inspectOpts.colors) :\n\t\ttty.isatty(process.stderr.fd);\n}\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\tconst {namespace: name, useColors} = this;\n\n\tif (useColors) {\n\t\tconst c = this.color;\n\t\tconst colorCode = '\\u001B[3' + (c < 8 ? c : '8;5;' + c);\n\t\tconst prefix = ` ${colorCode};1m${name} \\u001B[0m`;\n\n\t\targs[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n\t\targs.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\\u001B[0m');\n\t} else {\n\t\targs[0] = getDate() + name + ' ' + args[0];\n\t}\n}\n\nfunction getDate() {\n\tif (exports.inspectOpts.hideDate) {\n\t\treturn '';\n\t}\n\treturn new Date().toISOString() + ' ';\n}\n\n/**\n * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr.\n */\n\nfunction log(...args) {\n\treturn process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\tif (namespaces) {\n\t\tprocess.env.DEBUG = namespaces;\n\t} else {\n\t\t// If you set a process.env field to null or undefined, it gets cast to the\n\t\t// string 'null' or 'undefined'. Just delete instead.\n\t\tdelete process.env.DEBUG;\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n\treturn process.env.DEBUG;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init(debug) {\n\tdebug.inspectOpts = {};\n\n\tconst keys = Object.keys(exports.inspectOpts);\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tdebug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nformatters.o = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts)\n\t\t.split('\\n')\n\t\t.map(str => str.trim())\n\t\t.join(' ');\n};\n\n/**\n * Map %O to `util.inspect()`, allowing multiple lines if needed.\n */\n\nformatters.O = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts);\n};\n", "/**\n * Detect Electron renderer / nwjs process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {\n\tmodule.exports = require('./browser.js');\n} else {\n\tmodule.exports = require('./node.js');\n}\n", null, null, null, null, "export interface MimeBuffer extends Buffer {\n\ttype: string;\n\ttypeFull: string;\n\tcharset: string;\n}\n\n/**\n * Returns a `Buffer` instance from the given data URI `uri`.\n *\n * @param {String} uri Data URI to turn into a Buffer instance\n * @returns {Buffer} Buffer instance from Data URI\n * @api public\n */\nexport function dataUriToBuffer(uri: string): MimeBuffer {\n\tif (!/^data:/i.test(uri)) {\n\t\tthrow new TypeError(\n\t\t\t'`uri` does not appear to be a Data URI (must begin with \"data:\")'\n\t\t);\n\t}\n\n\t// strip newlines\n\turi = uri.replace(/\\r?\\n/g, '');\n\n\t// split the URI up into the \"metadata\" and the \"data\" portions\n\tconst firstComma = uri.indexOf(',');\n\tif (firstComma === -1 || firstComma <= 4) {\n\t\tthrow new TypeError('malformed data: URI');\n\t}\n\n\t// remove the \"data:\" scheme and parse the metadata\n\tconst meta = uri.substring(5, firstComma).split(';');\n\n\tlet charset = '';\n\tlet base64 = false;\n\tconst type = meta[0] || 'text/plain';\n\tlet typeFull = type;\n\tfor (let i = 1; i < meta.length; i++) {\n\t\tif (meta[i] === 'base64') {\n\t\t\tbase64 = true;\n\t\t} else if(meta[i]) {\n\t\t\ttypeFull += `;${ meta[i]}`;\n\t\t\tif (meta[i].indexOf('charset=') === 0) {\n\t\t\t\tcharset = meta[i].substring(8);\n\t\t\t}\n\t\t}\n\t}\n\t// defaults to US-ASCII only if type is not provided\n\tif (!meta[0] && !charset.length) {\n\t\ttypeFull += ';charset=US-ASCII';\n\t\tcharset = 'US-ASCII';\n\t}\n\n\t// get the encoded data portion and decode URI-encoded chars\n\tconst encoding = base64 ? 'base64' : 'ascii';\n\tconst data = unescape(uri.substring(firstComma + 1));\n\tconst buffer = Buffer.from(data, encoding) as MimeBuffer;\n\n\t// set `.type` and `.typeFull` properties to MIME type\n\tbuffer.type = type;\n\tbuffer.typeFull = typeFull;\n\n\t// set the `.charset` property\n\tbuffer.charset = charset;\n\n\treturn buffer;\n}\n\nexport default dataUriToBuffer;\n", "export function noop(): undefined {\n return undefined;\n}\n", "import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n", "import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n", "import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n", "export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n", "import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n", "/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n", "/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n", "import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n", "import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n", "import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n", "/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n", "/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterableIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nObject.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n", "/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n", "import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\n// Aligns with core-js/modules/es.symbol.async-iterator.js\nexport const SymbolAsyncIterator: (typeof Symbol)['asyncIterator'] =\n Symbol.asyncIterator ??\n Symbol.for?.('Symbol.asyncIterator') ??\n '@@asyncIterator';\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, SymbolAsyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n", "import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n", "import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n", "export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n", "import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n", "import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n", "import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n", "import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n", "import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n", "import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n", "import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n", "/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n", "import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n", "/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n", "/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n", "import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n", "import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n", "import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n", "import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n", "import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n", "import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n", "import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n", "import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n", "import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n", "import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList, SymbolAsyncIterator } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream implements AsyncIterable {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n\n [SymbolAsyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator {\n // Stub implementation, overridden below\n return this.values(options);\n }\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nObject.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n});\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n", "import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n", "import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n", "import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n", "import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n", "import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n", "/* c8 ignore start */\n// 64 KiB (same size chrome slice theirs blob into Uint8array's)\nconst POOL_SIZE = 65536\n\nif (!globalThis.ReadableStream) {\n // `node:stream/web` got introduced in v16.5.0 as experimental\n // and it's preferred over the polyfilled version. So we also\n // suppress the warning that gets emitted by NodeJS for using it.\n try {\n const process = require('node:process')\n const { emitWarning } = process\n try {\n process.emitWarning = () => {}\n Object.assign(globalThis, require('node:stream/web'))\n process.emitWarning = emitWarning\n } catch (error) {\n process.emitWarning = emitWarning\n throw error\n }\n } catch (error) {\n // fallback to polyfill implementation\n Object.assign(globalThis, require('web-streams-polyfill/dist/ponyfill.es2018.js'))\n }\n}\n\ntry {\n // Don't use node: prefix for this, require+node: is not supported until node v14.14\n // Only `import()` can use prefix in 12.20 and later\n const { Blob } = require('buffer')\n if (Blob && !Blob.prototype.stream) {\n Blob.prototype.stream = function name (params) {\n let position = 0\n const blob = this\n\n return new ReadableStream({\n type: 'bytes',\n async pull (ctrl) {\n const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE))\n const buffer = await chunk.arrayBuffer()\n position += buffer.byteLength\n ctrl.enqueue(new Uint8Array(buffer))\n\n if (position === blob.size) {\n ctrl.close()\n }\n }\n })\n }\n }\n} catch (error) {}\n/* c8 ignore end */\n", "/*! fetch-blob. MIT License. Jimmy W\u00E4rting */\n\n// TODO (jimmywarting): in the feature use conditional loading with top level await (requires 14.x)\n// Node has recently added whatwg stream into core\n\nimport './streams.cjs'\n\n// 64 KiB (same size chrome slice theirs blob into Uint8array's)\nconst POOL_SIZE = 65536\n\n/** @param {(Blob | Uint8Array)[]} parts */\nasync function * toIterator (parts, clone = true) {\n for (const part of parts) {\n if ('stream' in part) {\n yield * (/** @type {AsyncIterableIterator} */ (part.stream()))\n } else if (ArrayBuffer.isView(part)) {\n if (clone) {\n let position = part.byteOffset\n const end = part.byteOffset + part.byteLength\n while (position !== end) {\n const size = Math.min(end - position, POOL_SIZE)\n const chunk = part.buffer.slice(position, position + size)\n position += chunk.byteLength\n yield new Uint8Array(chunk)\n }\n } else {\n yield part\n }\n /* c8 ignore next 10 */\n } else {\n // For blobs that have arrayBuffer but no stream method (nodes buffer.Blob)\n let position = 0, b = (/** @type {Blob} */ (part))\n while (position !== b.size) {\n const chunk = b.slice(position, Math.min(b.size, position + POOL_SIZE))\n const buffer = await chunk.arrayBuffer()\n position += buffer.byteLength\n yield new Uint8Array(buffer)\n }\n }\n }\n}\n\nconst _Blob = class Blob {\n /** @type {Array.<(Blob|Uint8Array)>} */\n #parts = []\n #type = ''\n #size = 0\n #endings = 'transparent'\n\n /**\n * The Blob() constructor returns a new Blob object. The content\n * of the blob consists of the concatenation of the values given\n * in the parameter array.\n *\n * @param {*} blobParts\n * @param {{ type?: string, endings?: string }} [options]\n */\n constructor (blobParts = [], options = {}) {\n if (typeof blobParts !== 'object' || blobParts === null) {\n throw new TypeError('Failed to construct \\'Blob\\': The provided value cannot be converted to a sequence.')\n }\n\n if (typeof blobParts[Symbol.iterator] !== 'function') {\n throw new TypeError('Failed to construct \\'Blob\\': The object must have a callable @@iterator property.')\n }\n\n if (typeof options !== 'object' && typeof options !== 'function') {\n throw new TypeError('Failed to construct \\'Blob\\': parameter 2 cannot convert to dictionary.')\n }\n\n if (options === null) options = {}\n\n const encoder = new TextEncoder()\n for (const element of blobParts) {\n let part\n if (ArrayBuffer.isView(element)) {\n part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength))\n } else if (element instanceof ArrayBuffer) {\n part = new Uint8Array(element.slice(0))\n } else if (element instanceof Blob) {\n part = element\n } else {\n part = encoder.encode(`${element}`)\n }\n\n this.#size += ArrayBuffer.isView(part) ? part.byteLength : part.size\n this.#parts.push(part)\n }\n\n this.#endings = `${options.endings === undefined ? 'transparent' : options.endings}`\n const type = options.type === undefined ? '' : String(options.type)\n this.#type = /^[\\x20-\\x7E]*$/.test(type) ? type : ''\n }\n\n /**\n * The Blob interface's size property returns the\n * size of the Blob in bytes.\n */\n get size () {\n return this.#size\n }\n\n /**\n * The type property of a Blob object returns the MIME type of the file.\n */\n get type () {\n return this.#type\n }\n\n /**\n * The text() method in the Blob interface returns a Promise\n * that resolves with a string containing the contents of\n * the blob, interpreted as UTF-8.\n *\n * @return {Promise}\n */\n async text () {\n // More optimized than using this.arrayBuffer()\n // that requires twice as much ram\n const decoder = new TextDecoder()\n let str = ''\n for await (const part of toIterator(this.#parts, false)) {\n str += decoder.decode(part, { stream: true })\n }\n // Remaining\n str += decoder.decode()\n return str\n }\n\n /**\n * The arrayBuffer() method in the Blob interface returns a\n * Promise that resolves with the contents of the blob as\n * binary data contained in an ArrayBuffer.\n *\n * @return {Promise}\n */\n async arrayBuffer () {\n // Easier way... Just a unnecessary overhead\n // const view = new Uint8Array(this.size);\n // await this.stream().getReader({mode: 'byob'}).read(view);\n // return view.buffer;\n\n const data = new Uint8Array(this.size)\n let offset = 0\n for await (const chunk of toIterator(this.#parts, false)) {\n data.set(chunk, offset)\n offset += chunk.length\n }\n\n return data.buffer\n }\n\n stream () {\n const it = toIterator(this.#parts, true)\n\n return new globalThis.ReadableStream({\n // @ts-ignore\n type: 'bytes',\n async pull (ctrl) {\n const chunk = await it.next()\n chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value)\n },\n\n async cancel () {\n await it.return()\n }\n })\n }\n\n /**\n * The Blob interface's slice() method creates and returns a\n * new Blob object which contains data from a subset of the\n * blob on which it's called.\n *\n * @param {number} [start]\n * @param {number} [end]\n * @param {string} [type]\n */\n slice (start = 0, end = this.size, type = '') {\n const { size } = this\n\n let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size)\n let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size)\n\n const span = Math.max(relativeEnd - relativeStart, 0)\n const parts = this.#parts\n const blobParts = []\n let added = 0\n\n for (const part of parts) {\n // don't add the overflow to new blobParts\n if (added >= span) {\n break\n }\n\n const size = ArrayBuffer.isView(part) ? part.byteLength : part.size\n if (relativeStart && size <= relativeStart) {\n // Skip the beginning and change the relative\n // start & end position as we skip the unwanted parts\n relativeStart -= size\n relativeEnd -= size\n } else {\n let chunk\n if (ArrayBuffer.isView(part)) {\n chunk = part.subarray(relativeStart, Math.min(size, relativeEnd))\n added += chunk.byteLength\n } else {\n chunk = part.slice(relativeStart, Math.min(size, relativeEnd))\n added += chunk.size\n }\n relativeEnd -= size\n blobParts.push(chunk)\n relativeStart = 0 // All next sequential parts should start at 0\n }\n }\n\n const blob = new Blob([], { type: String(type).toLowerCase() })\n blob.#size = span\n blob.#parts = blobParts\n\n return blob\n }\n\n get [Symbol.toStringTag] () {\n return 'Blob'\n }\n\n static [Symbol.hasInstance] (object) {\n return (\n object &&\n typeof object === 'object' &&\n typeof object.constructor === 'function' &&\n (\n typeof object.stream === 'function' ||\n typeof object.arrayBuffer === 'function'\n ) &&\n /^(Blob|File)$/.test(object[Symbol.toStringTag])\n )\n }\n}\n\nObject.defineProperties(_Blob.prototype, {\n size: { enumerable: true },\n type: { enumerable: true },\n slice: { enumerable: true }\n})\n\n/** @type {typeof globalThis.Blob} */\nexport const Blob = _Blob\nexport default Blob\n", "import Blob from './index.js'\n\nconst _File = class File extends Blob {\n #lastModified = 0\n #name = ''\n\n /**\n * @param {*[]} fileBits\n * @param {string} fileName\n * @param {{lastModified?: number, type?: string}} options\n */// @ts-ignore\n constructor (fileBits, fileName, options = {}) {\n if (arguments.length < 2) {\n throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`)\n }\n super(fileBits, options)\n\n if (options === null) options = {}\n\n // Simulate WebIDL type casting for NaN value in lastModified option.\n const lastModified = options.lastModified === undefined ? Date.now() : Number(options.lastModified)\n if (!Number.isNaN(lastModified)) {\n this.#lastModified = lastModified\n }\n\n this.#name = String(fileName)\n }\n\n get name () {\n return this.#name\n }\n\n get lastModified () {\n return this.#lastModified\n }\n\n get [Symbol.toStringTag] () {\n return 'File'\n }\n\n static [Symbol.hasInstance] (object) {\n return !!object && object instanceof Blob &&\n /^(File)$/.test(object[Symbol.toStringTag])\n }\n}\n\n/** @type {typeof globalThis.File} */// @ts-ignore\nexport const File = _File\nexport default File\n", "/*! formdata-polyfill. MIT License. Jimmy W\u00E4rting */\n\nimport C from 'fetch-blob'\nimport F from 'fetch-blob/file.js'\n\nvar {toStringTag:t,iterator:i,hasInstance:h}=Symbol,\nr=Math.random,\nm='append,set,get,getAll,delete,keys,values,entries,forEach,constructor'.split(','),\nf=(a,b,c)=>(a+='',/^(Blob|File)$/.test(b && b[t])?[(c=c!==void 0?c+'':b[t]=='File'?b.name:'blob',a),b.name!==c||b[t]=='blob'?new F([b],c,b):b]:[a,b+'']),\ne=(c,f)=>(f?c:c.replace(/\\r?\\n|\\r/g,'\\r\\n')).replace(/\\n/g,'%0A').replace(/\\r/g,'%0D').replace(/\"/g,'%22'),\nx=(n, a, e)=>{if(a.lengthtypeof o[m]!='function')}\nappend(...a){x('append',arguments,2);this.#d.push(f(...a))}\ndelete(a){x('delete',arguments,1);a+='';this.#d=this.#d.filter(([b])=>b!==a)}\nget(a){x('get',arguments,1);a+='';for(var b=this.#d,l=b.length,c=0;cc[0]===a&&b.push(c[1]));return b}\nhas(a){x('has',arguments,1);a+='';return this.#d.some(b=>b[0]===a)}\nforEach(a,b){x('forEach',arguments,1);for(var [c,d]of this)a.call(b,d,c,this)}\nset(...a){x('set',arguments,2);var b=[],c=!0;a=f(...a);this.#d.forEach(d=>{d[0]===a[0]?c&&(c=!b.push(a)):b.push(d)});c&&b.push(a);this.#d=b}\n*entries(){yield*this.#d}\n*keys(){for(var[a]of this)yield a}\n*values(){for(var[,a]of this)yield a}}\n\n/** @param {FormData} F */\nexport function formDataToBlob (F,B=C){\nvar b=`${r()}${r()}`.replace(/\\./g, '').slice(-28).padStart(32, '-'),c=[],p=`--${b}\\r\\nContent-Disposition: form-data; name=\"`\nF.forEach((v,n)=>typeof v=='string'\n?c.push(p+e(n)+`\"\\r\\n\\r\\n${v.replace(/\\r(?!\\n)|(? {\n\treturn (\n\t\ttypeof object === 'object' &&\n\t\ttypeof object.append === 'function' &&\n\t\ttypeof object.delete === 'function' &&\n\t\ttypeof object.get === 'function' &&\n\t\ttypeof object.getAll === 'function' &&\n\t\ttypeof object.has === 'function' &&\n\t\ttypeof object.set === 'function' &&\n\t\ttypeof object.sort === 'function' &&\n\t\tobject[NAME] === 'URLSearchParams'\n\t);\n};\n\n/**\n * Check if `object` is a W3C `Blob` object (which `File` inherits from)\n * @param {*} object - Object to check for\n * @return {boolean}\n */\nexport const isBlob = object => {\n\treturn (\n\t\tobject &&\n\t\ttypeof object === 'object' &&\n\t\ttypeof object.arrayBuffer === 'function' &&\n\t\ttypeof object.type === 'string' &&\n\t\ttypeof object.stream === 'function' &&\n\t\ttypeof object.constructor === 'function' &&\n\t\t/^(Blob|File)$/.test(object[NAME])\n\t);\n};\n\n/**\n * Check if `obj` is an instance of AbortSignal.\n * @param {*} object - Object to check for\n * @return {boolean}\n */\nexport const isAbortSignal = object => {\n\treturn (\n\t\ttypeof object === 'object' && (\n\t\t\tobject[NAME] === 'AbortSignal' ||\n\t\t\tobject[NAME] === 'EventTarget'\n\t\t)\n\t);\n};\n\n/**\n * isDomainOrSubdomain reports whether sub is a subdomain (or exact match) of\n * the parent domain.\n *\n * Both domains must already be in canonical form.\n * @param {string|URL} original\n * @param {string|URL} destination\n */\nexport const isDomainOrSubdomain = (destination, original) => {\n\tconst orig = new URL(original).hostname;\n\tconst dest = new URL(destination).hostname;\n\n\treturn orig === dest || orig.endsWith(`.${dest}`);\n};\n\n/**\n * isSameProtocol reports whether the two provided URLs use the same protocol.\n *\n * Both domains must already be in canonical form.\n * @param {string|URL} original\n * @param {string|URL} destination\n */\nexport const isSameProtocol = (destination, original) => {\n\tconst orig = new URL(original).protocol;\n\tconst dest = new URL(destination).protocol;\n\n\treturn orig === dest;\n};\n", "/*! node-domexception. MIT License. Jimmy W\u00E4rting */\n\nif (!globalThis.DOMException) {\n try {\n const { MessageChannel } = require('worker_threads'),\n port = new MessageChannel().port1,\n ab = new ArrayBuffer()\n port.postMessage(ab, [ab, ab])\n } catch (err) {\n err.constructor.name === 'DOMException' && (\n globalThis.DOMException = err.constructor\n )\n }\n}\n\nmodule.exports = globalThis.DOMException\n", "import { statSync, createReadStream, promises as fs } from 'node:fs'\nimport { basename } from 'node:path'\nimport DOMException from 'node-domexception'\n\nimport File from './file.js'\nimport Blob from './index.js'\n\nconst { stat } = fs\n\n/**\n * @param {string} path filepath on the disk\n * @param {string} [type] mimetype to use\n */\nconst blobFromSync = (path, type) => fromBlob(statSync(path), path, type)\n\n/**\n * @param {string} path filepath on the disk\n * @param {string} [type] mimetype to use\n * @returns {Promise}\n */\nconst blobFrom = (path, type) => stat(path).then(stat => fromBlob(stat, path, type))\n\n/**\n * @param {string} path filepath on the disk\n * @param {string} [type] mimetype to use\n * @returns {Promise}\n */\nconst fileFrom = (path, type) => stat(path).then(stat => fromFile(stat, path, type))\n\n/**\n * @param {string} path filepath on the disk\n * @param {string} [type] mimetype to use\n */\nconst fileFromSync = (path, type) => fromFile(statSync(path), path, type)\n\n// @ts-ignore\nconst fromBlob = (stat, path, type = '') => new Blob([new BlobDataItem({\n path,\n size: stat.size,\n lastModified: stat.mtimeMs,\n start: 0\n})], { type })\n\n// @ts-ignore\nconst fromFile = (stat, path, type = '') => new File([new BlobDataItem({\n path,\n size: stat.size,\n lastModified: stat.mtimeMs,\n start: 0\n})], basename(path), { type, lastModified: stat.mtimeMs })\n\n/**\n * This is a blob backed up by a file on the disk\n * with minium requirement. Its wrapped around a Blob as a blobPart\n * so you have no direct access to this.\n *\n * @private\n */\nclass BlobDataItem {\n #path\n #start\n\n constructor (options) {\n this.#path = options.path\n this.#start = options.start\n this.size = options.size\n this.lastModified = options.lastModified\n }\n\n /**\n * Slicing arguments is first validated and formatted\n * to not be out of range by Blob.prototype.slice\n */\n slice (start, end) {\n return new BlobDataItem({\n path: this.#path,\n lastModified: this.lastModified,\n size: end - start,\n start: this.#start + start\n })\n }\n\n async * stream () {\n const { mtimeMs } = await stat(this.#path)\n if (mtimeMs > this.lastModified) {\n throw new DOMException('The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.', 'NotReadableError')\n }\n yield * createReadStream(this.#path, {\n start: this.#start,\n end: this.#start + this.size - 1\n })\n }\n\n get [Symbol.toStringTag] () {\n return 'Blob'\n }\n}\n\nexport default blobFromSync\nexport { File, Blob, blobFrom, blobFromSync, fileFrom, fileFromSync }\n", "import {File} from 'fetch-blob/from.js';\nimport {FormData} from 'formdata-polyfill/esm.min.js';\n\nlet s = 0;\nconst S = {\n\tSTART_BOUNDARY: s++,\n\tHEADER_FIELD_START: s++,\n\tHEADER_FIELD: s++,\n\tHEADER_VALUE_START: s++,\n\tHEADER_VALUE: s++,\n\tHEADER_VALUE_ALMOST_DONE: s++,\n\tHEADERS_ALMOST_DONE: s++,\n\tPART_DATA_START: s++,\n\tPART_DATA: s++,\n\tEND: s++\n};\n\nlet f = 1;\nconst F = {\n\tPART_BOUNDARY: f,\n\tLAST_BOUNDARY: f *= 2\n};\n\nconst LF = 10;\nconst CR = 13;\nconst SPACE = 32;\nconst HYPHEN = 45;\nconst COLON = 58;\nconst A = 97;\nconst Z = 122;\n\nconst lower = c => c | 0x20;\n\nconst noop = () => {};\n\nclass MultipartParser {\n\t/**\n\t * @param {string} boundary\n\t */\n\tconstructor(boundary) {\n\t\tthis.index = 0;\n\t\tthis.flags = 0;\n\n\t\tthis.onHeaderEnd = noop;\n\t\tthis.onHeaderField = noop;\n\t\tthis.onHeadersEnd = noop;\n\t\tthis.onHeaderValue = noop;\n\t\tthis.onPartBegin = noop;\n\t\tthis.onPartData = noop;\n\t\tthis.onPartEnd = noop;\n\n\t\tthis.boundaryChars = {};\n\n\t\tboundary = '\\r\\n--' + boundary;\n\t\tconst ui8a = new Uint8Array(boundary.length);\n\t\tfor (let i = 0; i < boundary.length; i++) {\n\t\t\tui8a[i] = boundary.charCodeAt(i);\n\t\t\tthis.boundaryChars[ui8a[i]] = true;\n\t\t}\n\n\t\tthis.boundary = ui8a;\n\t\tthis.lookbehind = new Uint8Array(this.boundary.length + 8);\n\t\tthis.state = S.START_BOUNDARY;\n\t}\n\n\t/**\n\t * @param {Uint8Array} data\n\t */\n\twrite(data) {\n\t\tlet i = 0;\n\t\tconst length_ = data.length;\n\t\tlet previousIndex = this.index;\n\t\tlet {lookbehind, boundary, boundaryChars, index, state, flags} = this;\n\t\tconst boundaryLength = this.boundary.length;\n\t\tconst boundaryEnd = boundaryLength - 1;\n\t\tconst bufferLength = data.length;\n\t\tlet c;\n\t\tlet cl;\n\n\t\tconst mark = name => {\n\t\t\tthis[name + 'Mark'] = i;\n\t\t};\n\n\t\tconst clear = name => {\n\t\t\tdelete this[name + 'Mark'];\n\t\t};\n\n\t\tconst callback = (callbackSymbol, start, end, ui8a) => {\n\t\t\tif (start === undefined || start !== end) {\n\t\t\t\tthis[callbackSymbol](ui8a && ui8a.subarray(start, end));\n\t\t\t}\n\t\t};\n\n\t\tconst dataCallback = (name, clear) => {\n\t\t\tconst markSymbol = name + 'Mark';\n\t\t\tif (!(markSymbol in this)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (clear) {\n\t\t\t\tcallback(name, this[markSymbol], i, data);\n\t\t\t\tdelete this[markSymbol];\n\t\t\t} else {\n\t\t\t\tcallback(name, this[markSymbol], data.length, data);\n\t\t\t\tthis[markSymbol] = 0;\n\t\t\t}\n\t\t};\n\n\t\tfor (i = 0; i < length_; i++) {\n\t\t\tc = data[i];\n\n\t\t\tswitch (state) {\n\t\t\t\tcase S.START_BOUNDARY:\n\t\t\t\t\tif (index === boundary.length - 2) {\n\t\t\t\t\t\tif (c === HYPHEN) {\n\t\t\t\t\t\t\tflags |= F.LAST_BOUNDARY;\n\t\t\t\t\t\t} else if (c !== CR) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else if (index - 1 === boundary.length - 2) {\n\t\t\t\t\t\tif (flags & F.LAST_BOUNDARY && c === HYPHEN) {\n\t\t\t\t\t\t\tstate = S.END;\n\t\t\t\t\t\t\tflags = 0;\n\t\t\t\t\t\t} else if (!(flags & F.LAST_BOUNDARY) && c === LF) {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t\tcallback('onPartBegin');\n\t\t\t\t\t\t\tstate = S.HEADER_FIELD_START;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c !== boundary[index + 2]) {\n\t\t\t\t\t\tindex = -2;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c === boundary[index + 2]) {\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADER_FIELD_START:\n\t\t\t\t\tstate = S.HEADER_FIELD;\n\t\t\t\t\tmark('onHeaderField');\n\t\t\t\t\tindex = 0;\n\t\t\t\t\t// falls through\n\t\t\t\tcase S.HEADER_FIELD:\n\t\t\t\t\tif (c === CR) {\n\t\t\t\t\t\tclear('onHeaderField');\n\t\t\t\t\t\tstate = S.HEADERS_ALMOST_DONE;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tindex++;\n\t\t\t\t\tif (c === HYPHEN) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c === COLON) {\n\t\t\t\t\t\tif (index === 1) {\n\t\t\t\t\t\t\t// empty header field\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdataCallback('onHeaderField', true);\n\t\t\t\t\t\tstate = S.HEADER_VALUE_START;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcl = lower(c);\n\t\t\t\t\tif (cl < A || cl > Z) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADER_VALUE_START:\n\t\t\t\t\tif (c === SPACE) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tmark('onHeaderValue');\n\t\t\t\t\tstate = S.HEADER_VALUE;\n\t\t\t\t\t// falls through\n\t\t\t\tcase S.HEADER_VALUE:\n\t\t\t\t\tif (c === CR) {\n\t\t\t\t\t\tdataCallback('onHeaderValue', true);\n\t\t\t\t\t\tcallback('onHeaderEnd');\n\t\t\t\t\t\tstate = S.HEADER_VALUE_ALMOST_DONE;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADER_VALUE_ALMOST_DONE:\n\t\t\t\t\tif (c !== LF) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tstate = S.HEADER_FIELD_START;\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.HEADERS_ALMOST_DONE:\n\t\t\t\t\tif (c !== LF) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tcallback('onHeadersEnd');\n\t\t\t\t\tstate = S.PART_DATA_START;\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.PART_DATA_START:\n\t\t\t\t\tstate = S.PART_DATA;\n\t\t\t\t\tmark('onPartData');\n\t\t\t\t\t// falls through\n\t\t\t\tcase S.PART_DATA:\n\t\t\t\t\tpreviousIndex = index;\n\n\t\t\t\t\tif (index === 0) {\n\t\t\t\t\t\t// boyer-moore derrived algorithm to safely skip non-boundary data\n\t\t\t\t\t\ti += boundaryEnd;\n\t\t\t\t\t\twhile (i < bufferLength && !(data[i] in boundaryChars)) {\n\t\t\t\t\t\t\ti += boundaryLength;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ti -= boundaryEnd;\n\t\t\t\t\t\tc = data[i];\n\t\t\t\t\t}\n\n\t\t\t\t\tif (index < boundary.length) {\n\t\t\t\t\t\tif (boundary[index] === c) {\n\t\t\t\t\t\t\tif (index === 0) {\n\t\t\t\t\t\t\t\tdataCallback('onPartData', true);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tindex++;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (index === boundary.length) {\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t\tif (c === CR) {\n\t\t\t\t\t\t\t// CR = part boundary\n\t\t\t\t\t\t\tflags |= F.PART_BOUNDARY;\n\t\t\t\t\t\t} else if (c === HYPHEN) {\n\t\t\t\t\t\t\t// HYPHEN = end boundary\n\t\t\t\t\t\t\tflags |= F.LAST_BOUNDARY;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (index - 1 === boundary.length) {\n\t\t\t\t\t\tif (flags & F.PART_BOUNDARY) {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t\tif (c === LF) {\n\t\t\t\t\t\t\t\t// unset the PART_BOUNDARY flag\n\t\t\t\t\t\t\t\tflags &= ~F.PART_BOUNDARY;\n\t\t\t\t\t\t\t\tcallback('onPartEnd');\n\t\t\t\t\t\t\t\tcallback('onPartBegin');\n\t\t\t\t\t\t\t\tstate = S.HEADER_FIELD_START;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (flags & F.LAST_BOUNDARY) {\n\t\t\t\t\t\t\tif (c === HYPHEN) {\n\t\t\t\t\t\t\t\tcallback('onPartEnd');\n\t\t\t\t\t\t\t\tstate = S.END;\n\t\t\t\t\t\t\t\tflags = 0;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (index > 0) {\n\t\t\t\t\t\t// when matching a possible boundary, keep a lookbehind reference\n\t\t\t\t\t\t// in case it turns out to be a false lead\n\t\t\t\t\t\tlookbehind[index - 1] = c;\n\t\t\t\t\t} else if (previousIndex > 0) {\n\t\t\t\t\t\t// if our boundary turned out to be rubbish, the captured lookbehind\n\t\t\t\t\t\t// belongs to partData\n\t\t\t\t\t\tconst _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength);\n\t\t\t\t\t\tcallback('onPartData', 0, previousIndex, _lookbehind);\n\t\t\t\t\t\tpreviousIndex = 0;\n\t\t\t\t\t\tmark('onPartData');\n\n\t\t\t\t\t\t// reconsider the current character even so it interrupted the sequence\n\t\t\t\t\t\t// it could be the beginning of a new sequence\n\t\t\t\t\t\ti--;\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase S.END:\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Error(`Unexpected state entered: ${state}`);\n\t\t\t}\n\t\t}\n\n\t\tdataCallback('onHeaderField');\n\t\tdataCallback('onHeaderValue');\n\t\tdataCallback('onPartData');\n\n\t\t// Update properties for the next call\n\t\tthis.index = index;\n\t\tthis.state = state;\n\t\tthis.flags = flags;\n\t}\n\n\tend() {\n\t\tif ((this.state === S.HEADER_FIELD_START && this.index === 0) ||\n\t\t\t(this.state === S.PART_DATA && this.index === this.boundary.length)) {\n\t\t\tthis.onPartEnd();\n\t\t} else if (this.state !== S.END) {\n\t\t\tthrow new Error('MultipartParser.end(): stream ended unexpectedly');\n\t\t}\n\t}\n}\n\nfunction _fileName(headerValue) {\n\t// matches either a quoted-string or a token (RFC 2616 section 19.5.1)\n\tconst m = headerValue.match(/\\bfilename=(\"(.*?)\"|([^()<>@,;:\\\\\"/[\\]?={}\\s\\t]+))($|;\\s)/i);\n\tif (!m) {\n\t\treturn;\n\t}\n\n\tconst match = m[2] || m[3] || '';\n\tlet filename = match.slice(match.lastIndexOf('\\\\') + 1);\n\tfilename = filename.replace(/%22/g, '\"');\n\tfilename = filename.replace(/&#(\\d{4});/g, (m, code) => {\n\t\treturn String.fromCharCode(code);\n\t});\n\treturn filename;\n}\n\nexport async function toFormData(Body, ct) {\n\tif (!/multipart/i.test(ct)) {\n\t\tthrow new TypeError('Failed to fetch');\n\t}\n\n\tconst m = ct.match(/boundary=(?:\"([^\"]+)\"|([^;]+))/i);\n\n\tif (!m) {\n\t\tthrow new TypeError('no or bad content-type header, no multipart boundary');\n\t}\n\n\tconst parser = new MultipartParser(m[1] || m[2]);\n\n\tlet headerField;\n\tlet headerValue;\n\tlet entryValue;\n\tlet entryName;\n\tlet contentType;\n\tlet filename;\n\tconst entryChunks = [];\n\tconst formData = new FormData();\n\n\tconst onPartData = ui8a => {\n\t\tentryValue += decoder.decode(ui8a, {stream: true});\n\t};\n\n\tconst appendToFile = ui8a => {\n\t\tentryChunks.push(ui8a);\n\t};\n\n\tconst appendFileToFormData = () => {\n\t\tconst file = new File(entryChunks, filename, {type: contentType});\n\t\tformData.append(entryName, file);\n\t};\n\n\tconst appendEntryToFormData = () => {\n\t\tformData.append(entryName, entryValue);\n\t};\n\n\tconst decoder = new TextDecoder('utf-8');\n\tdecoder.decode();\n\n\tparser.onPartBegin = function () {\n\t\tparser.onPartData = onPartData;\n\t\tparser.onPartEnd = appendEntryToFormData;\n\n\t\theaderField = '';\n\t\theaderValue = '';\n\t\tentryValue = '';\n\t\tentryName = '';\n\t\tcontentType = '';\n\t\tfilename = null;\n\t\tentryChunks.length = 0;\n\t};\n\n\tparser.onHeaderField = function (ui8a) {\n\t\theaderField += decoder.decode(ui8a, {stream: true});\n\t};\n\n\tparser.onHeaderValue = function (ui8a) {\n\t\theaderValue += decoder.decode(ui8a, {stream: true});\n\t};\n\n\tparser.onHeaderEnd = function () {\n\t\theaderValue += decoder.decode();\n\t\theaderField = headerField.toLowerCase();\n\n\t\tif (headerField === 'content-disposition') {\n\t\t\t// matches either a quoted-string or a token (RFC 2616 section 19.5.1)\n\t\t\tconst m = headerValue.match(/\\bname=(\"([^\"]*)\"|([^()<>@,;:\\\\\"/[\\]?={}\\s\\t]+))/i);\n\n\t\t\tif (m) {\n\t\t\t\tentryName = m[2] || m[3] || '';\n\t\t\t}\n\n\t\t\tfilename = _fileName(headerValue);\n\n\t\t\tif (filename) {\n\t\t\t\tparser.onPartData = appendToFile;\n\t\t\t\tparser.onPartEnd = appendFileToFormData;\n\t\t\t}\n\t\t} else if (headerField === 'content-type') {\n\t\t\tcontentType = headerValue;\n\t\t}\n\n\t\theaderValue = '';\n\t\theaderField = '';\n\t};\n\n\tfor await (const chunk of Body) {\n\t\tparser.write(chunk);\n\t}\n\n\tparser.end();\n\n\treturn formData;\n}\n", "\n/**\n * Body.js\n *\n * Body interface provides common methods for Request and Response\n */\n\nimport Stream, {PassThrough} from 'node:stream';\nimport {types, deprecate, promisify} from 'node:util';\nimport {Buffer} from 'node:buffer';\n\nimport Blob from 'fetch-blob';\nimport {FormData, formDataToBlob} from 'formdata-polyfill/esm.min.js';\n\nimport {FetchError} from './errors/fetch-error.js';\nimport {FetchBaseError} from './errors/base.js';\nimport {isBlob, isURLSearchParameters} from './utils/is.js';\n\nconst pipeline = promisify(Stream.pipeline);\nconst INTERNALS = Symbol('Body internals');\n\n/**\n * Body mixin\n *\n * Ref: https://fetch.spec.whatwg.org/#body\n *\n * @param Stream body Readable stream\n * @param Object opts Response options\n * @return Void\n */\nexport default class Body {\n\tconstructor(body, {\n\t\tsize = 0\n\t} = {}) {\n\t\tlet boundary = null;\n\n\t\tif (body === null) {\n\t\t\t// Body is undefined or null\n\t\t\tbody = null;\n\t\t} else if (isURLSearchParameters(body)) {\n\t\t\t// Body is a URLSearchParams\n\t\t\tbody = Buffer.from(body.toString());\n\t\t} else if (isBlob(body)) {\n\t\t\t// Body is blob\n\t\t} else if (Buffer.isBuffer(body)) {\n\t\t\t// Body is Buffer\n\t\t} else if (types.isAnyArrayBuffer(body)) {\n\t\t\t// Body is ArrayBuffer\n\t\t\tbody = Buffer.from(body);\n\t\t} else if (ArrayBuffer.isView(body)) {\n\t\t\t// Body is ArrayBufferView\n\t\t\tbody = Buffer.from(body.buffer, body.byteOffset, body.byteLength);\n\t\t} else if (body instanceof Stream) {\n\t\t\t// Body is stream\n\t\t} else if (body instanceof FormData) {\n\t\t\t// Body is FormData\n\t\t\tbody = formDataToBlob(body);\n\t\t\tboundary = body.type.split('=')[1];\n\t\t} else {\n\t\t\t// None of the above\n\t\t\t// coerce to string then buffer\n\t\t\tbody = Buffer.from(String(body));\n\t\t}\n\n\t\tlet stream = body;\n\n\t\tif (Buffer.isBuffer(body)) {\n\t\t\tstream = Stream.Readable.from(body);\n\t\t} else if (isBlob(body)) {\n\t\t\tstream = Stream.Readable.from(body.stream());\n\t\t}\n\n\t\tthis[INTERNALS] = {\n\t\t\tbody,\n\t\t\tstream,\n\t\t\tboundary,\n\t\t\tdisturbed: false,\n\t\t\terror: null\n\t\t};\n\t\tthis.size = size;\n\n\t\tif (body instanceof Stream) {\n\t\t\tbody.on('error', error_ => {\n\t\t\t\tconst error = error_ instanceof FetchBaseError ?\n\t\t\t\t\terror_ :\n\t\t\t\t\tnew FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, 'system', error_);\n\t\t\t\tthis[INTERNALS].error = error;\n\t\t\t});\n\t\t}\n\t}\n\n\tget body() {\n\t\treturn this[INTERNALS].stream;\n\t}\n\n\tget bodyUsed() {\n\t\treturn this[INTERNALS].disturbed;\n\t}\n\n\t/**\n\t * Decode response as ArrayBuffer\n\t *\n\t * @return Promise\n\t */\n\tasync arrayBuffer() {\n\t\tconst {buffer, byteOffset, byteLength} = await consumeBody(this);\n\t\treturn buffer.slice(byteOffset, byteOffset + byteLength);\n\t}\n\n\tasync formData() {\n\t\tconst ct = this.headers.get('content-type');\n\n\t\tif (ct.startsWith('application/x-www-form-urlencoded')) {\n\t\t\tconst formData = new FormData();\n\t\t\tconst parameters = new URLSearchParams(await this.text());\n\n\t\t\tfor (const [name, value] of parameters) {\n\t\t\t\tformData.append(name, value);\n\t\t\t}\n\n\t\t\treturn formData;\n\t\t}\n\n\t\tconst {toFormData} = await import('./utils/multipart-parser.js');\n\t\treturn toFormData(this.body, ct);\n\t}\n\n\t/**\n\t * Return raw response as Blob\n\t *\n\t * @return Promise\n\t */\n\tasync blob() {\n\t\tconst ct = (this.headers && this.headers.get('content-type')) || (this[INTERNALS].body && this[INTERNALS].body.type) || '';\n\t\tconst buf = await this.arrayBuffer();\n\n\t\treturn new Blob([buf], {\n\t\t\ttype: ct\n\t\t});\n\t}\n\n\t/**\n\t * Decode response as json\n\t *\n\t * @return Promise\n\t */\n\tasync json() {\n\t\tconst text = await this.text();\n\t\treturn JSON.parse(text);\n\t}\n\n\t/**\n\t * Decode response as text\n\t *\n\t * @return Promise\n\t */\n\tasync text() {\n\t\tconst buffer = await consumeBody(this);\n\t\treturn new TextDecoder().decode(buffer);\n\t}\n\n\t/**\n\t * Decode response as buffer (non-spec api)\n\t *\n\t * @return Promise\n\t */\n\tbuffer() {\n\t\treturn consumeBody(this);\n\t}\n}\n\nBody.prototype.buffer = deprecate(Body.prototype.buffer, 'Please use \\'response.arrayBuffer()\\' instead of \\'response.buffer()\\'', 'node-fetch#buffer');\n\n// In browsers, all properties are enumerable.\nObject.defineProperties(Body.prototype, {\n\tbody: {enumerable: true},\n\tbodyUsed: {enumerable: true},\n\tarrayBuffer: {enumerable: true},\n\tblob: {enumerable: true},\n\tjson: {enumerable: true},\n\ttext: {enumerable: true},\n\tdata: {get: deprecate(() => {},\n\t\t'data doesn\\'t exist, use json(), text(), arrayBuffer(), or body instead',\n\t\t'https://github.com/node-fetch/node-fetch/issues/1000 (response)')}\n});\n\n/**\n * Consume and convert an entire Body to a Buffer.\n *\n * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body\n *\n * @return Promise\n */\nasync function consumeBody(data) {\n\tif (data[INTERNALS].disturbed) {\n\t\tthrow new TypeError(`body used already for: ${data.url}`);\n\t}\n\n\tdata[INTERNALS].disturbed = true;\n\n\tif (data[INTERNALS].error) {\n\t\tthrow data[INTERNALS].error;\n\t}\n\n\tconst {body} = data;\n\n\t// Body is null\n\tif (body === null) {\n\t\treturn Buffer.alloc(0);\n\t}\n\n\t/* c8 ignore next 3 */\n\tif (!(body instanceof Stream)) {\n\t\treturn Buffer.alloc(0);\n\t}\n\n\t// Body is stream\n\t// get ready to actually consume the body\n\tconst accum = [];\n\tlet accumBytes = 0;\n\n\ttry {\n\t\tfor await (const chunk of body) {\n\t\t\tif (data.size > 0 && accumBytes + chunk.length > data.size) {\n\t\t\t\tconst error = new FetchError(`content size at ${data.url} over limit: ${data.size}`, 'max-size');\n\t\t\t\tbody.destroy(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\taccumBytes += chunk.length;\n\t\t\taccum.push(chunk);\n\t\t}\n\t} catch (error) {\n\t\tconst error_ = error instanceof FetchBaseError ? error : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error.message}`, 'system', error);\n\t\tthrow error_;\n\t}\n\n\tif (body.readableEnded === true || body._readableState.ended === true) {\n\t\ttry {\n\t\t\tif (accum.every(c => typeof c === 'string')) {\n\t\t\t\treturn Buffer.from(accum.join(''));\n\t\t\t}\n\n\t\t\treturn Buffer.concat(accum, accumBytes);\n\t\t} catch (error) {\n\t\t\tthrow new FetchError(`Could not create Buffer from response body for ${data.url}: ${error.message}`, 'system', error);\n\t\t}\n\t} else {\n\t\tthrow new FetchError(`Premature close of server response while trying to fetch ${data.url}`);\n\t}\n}\n\n/**\n * Clone body given Res/Req instance\n *\n * @param Mixed instance Response or Request instance\n * @param String highWaterMark highWaterMark for both PassThrough body streams\n * @return Mixed\n */\nexport const clone = (instance, highWaterMark) => {\n\tlet p1;\n\tlet p2;\n\tlet {body} = instance[INTERNALS];\n\n\t// Don't allow cloning a used body\n\tif (instance.bodyUsed) {\n\t\tthrow new Error('cannot clone body after it is used');\n\t}\n\n\t// Check that body is a stream and not form-data object\n\t// note: we can't clone the form-data object without having it as a dependency\n\tif ((body instanceof Stream) && (typeof body.getBoundary !== 'function')) {\n\t\t// Tee instance body\n\t\tp1 = new PassThrough({highWaterMark});\n\t\tp2 = new PassThrough({highWaterMark});\n\t\tbody.pipe(p1);\n\t\tbody.pipe(p2);\n\t\t// Set instance body to teed body and return the other teed body\n\t\tinstance[INTERNALS].stream = p1;\n\t\tbody = p2;\n\t}\n\n\treturn body;\n};\n\nconst getNonSpecFormDataBoundary = deprecate(\n\tbody => body.getBoundary(),\n\t'form-data doesn\\'t follow the spec and requires special treatment. Use alternative package',\n\t'https://github.com/node-fetch/node-fetch/issues/1167'\n);\n\n/**\n * Performs the operation \"extract a `Content-Type` value from |object|\" as\n * specified in the specification:\n * https://fetch.spec.whatwg.org/#concept-bodyinit-extract\n *\n * This function assumes that instance.body is present.\n *\n * @param {any} body Any options.body input\n * @returns {string | null}\n */\nexport const extractContentType = (body, request) => {\n\t// Body is null or undefined\n\tif (body === null) {\n\t\treturn null;\n\t}\n\n\t// Body is string\n\tif (typeof body === 'string') {\n\t\treturn 'text/plain;charset=UTF-8';\n\t}\n\n\t// Body is a URLSearchParams\n\tif (isURLSearchParameters(body)) {\n\t\treturn 'application/x-www-form-urlencoded;charset=UTF-8';\n\t}\n\n\t// Body is blob\n\tif (isBlob(body)) {\n\t\treturn body.type || null;\n\t}\n\n\t// Body is a Buffer (Buffer, ArrayBuffer or ArrayBufferView)\n\tif (Buffer.isBuffer(body) || types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) {\n\t\treturn null;\n\t}\n\n\tif (body instanceof FormData) {\n\t\treturn `multipart/form-data; boundary=${request[INTERNALS].boundary}`;\n\t}\n\n\t// Detect form data input from form-data module\n\tif (body && typeof body.getBoundary === 'function') {\n\t\treturn `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`;\n\t}\n\n\t// Body is stream - can't really do much about this\n\tif (body instanceof Stream) {\n\t\treturn null;\n\t}\n\n\t// Body constructor defaults other things to string\n\treturn 'text/plain;charset=UTF-8';\n};\n\n/**\n * The Fetch Standard treats this as if \"total bytes\" is a property on the body.\n * For us, we have to explicitly get it with a function.\n *\n * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes\n *\n * @param {any} obj.body Body object from the Body instance.\n * @returns {number | null}\n */\nexport const getTotalBytes = request => {\n\tconst {body} = request[INTERNALS];\n\n\t// Body is null or undefined\n\tif (body === null) {\n\t\treturn 0;\n\t}\n\n\t// Body is Blob\n\tif (isBlob(body)) {\n\t\treturn body.size;\n\t}\n\n\t// Body is Buffer\n\tif (Buffer.isBuffer(body)) {\n\t\treturn body.length;\n\t}\n\n\t// Detect form data input from form-data module\n\tif (body && typeof body.getLengthSync === 'function') {\n\t\treturn body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null;\n\t}\n\n\t// Body is stream\n\treturn null;\n};\n\n/**\n * Write a Body to a Node.js WritableStream (e.g. http.Request) object.\n *\n * @param {Stream.Writable} dest The stream to write to.\n * @param obj.body Body object from the Body instance.\n * @returns {Promise}\n */\nexport const writeToStream = async (dest, {body}) => {\n\tif (body === null) {\n\t\t// Body is null\n\t\tdest.end();\n\t} else {\n\t\t// Body is stream\n\t\tawait pipeline(body, dest);\n\t}\n};\n", "/**\n * Headers.js\n *\n * Headers class offers convenient helpers\n */\n\nimport {types} from 'node:util';\nimport http from 'node:http';\n\n/* c8 ignore next 9 */\nconst validateHeaderName = typeof http.validateHeaderName === 'function' ?\n\thttp.validateHeaderName :\n\tname => {\n\t\tif (!/^[\\^`\\-\\w!#$%&'*+.|~]+$/.test(name)) {\n\t\t\tconst error = new TypeError(`Header name must be a valid HTTP token [${name}]`);\n\t\t\tObject.defineProperty(error, 'code', {value: 'ERR_INVALID_HTTP_TOKEN'});\n\t\t\tthrow error;\n\t\t}\n\t};\n\n/* c8 ignore next 9 */\nconst validateHeaderValue = typeof http.validateHeaderValue === 'function' ?\n\thttp.validateHeaderValue :\n\t(name, value) => {\n\t\tif (/[^\\t\\u0020-\\u007E\\u0080-\\u00FF]/.test(value)) {\n\t\t\tconst error = new TypeError(`Invalid character in header content [\"${name}\"]`);\n\t\t\tObject.defineProperty(error, 'code', {value: 'ERR_INVALID_CHAR'});\n\t\t\tthrow error;\n\t\t}\n\t};\n\n/**\n * @typedef {Headers | Record | Iterable | Iterable>} HeadersInit\n */\n\n/**\n * This Fetch API interface allows you to perform various actions on HTTP request and response headers.\n * These actions include retrieving, setting, adding to, and removing.\n * A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs.\n * You can add to this using methods like append() (see Examples.)\n * In all methods of this interface, header names are matched by case-insensitive byte sequence.\n *\n */\nexport default class Headers extends URLSearchParams {\n\t/**\n\t * Headers class\n\t *\n\t * @constructor\n\t * @param {HeadersInit} [init] - Response headers\n\t */\n\tconstructor(init) {\n\t\t// Validate and normalize init object in [name, value(s)][]\n\t\t/** @type {string[][]} */\n\t\tlet result = [];\n\t\tif (init instanceof Headers) {\n\t\t\tconst raw = init.raw();\n\t\t\tfor (const [name, values] of Object.entries(raw)) {\n\t\t\t\tresult.push(...values.map(value => [name, value]));\n\t\t\t}\n\t\t} else if (init == null) { // eslint-disable-line no-eq-null, eqeqeq\n\t\t\t// No op\n\t\t} else if (typeof init === 'object' && !types.isBoxedPrimitive(init)) {\n\t\t\tconst method = init[Symbol.iterator];\n\t\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\t\tif (method == null) {\n\t\t\t\t// Record\n\t\t\t\tresult.push(...Object.entries(init));\n\t\t\t} else {\n\t\t\t\tif (typeof method !== 'function') {\n\t\t\t\t\tthrow new TypeError('Header pairs must be iterable');\n\t\t\t\t}\n\n\t\t\t\t// Sequence>\n\t\t\t\t// Note: per spec we have to first exhaust the lists then process them\n\t\t\t\tresult = [...init]\n\t\t\t\t\t.map(pair => {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\ttypeof pair !== 'object' || types.isBoxedPrimitive(pair)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthrow new TypeError('Each header pair must be an iterable object');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn [...pair];\n\t\t\t\t\t}).map(pair => {\n\t\t\t\t\t\tif (pair.length !== 2) {\n\t\t\t\t\t\t\tthrow new TypeError('Each header pair must be a name/value tuple');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn [...pair];\n\t\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new TypeError('Failed to construct \\'Headers\\': The provided value is not of type \\'(sequence> or record)');\n\t\t}\n\n\t\t// Validate and lowercase\n\t\tresult =\n\t\t\tresult.length > 0 ?\n\t\t\t\tresult.map(([name, value]) => {\n\t\t\t\t\tvalidateHeaderName(name);\n\t\t\t\t\tvalidateHeaderValue(name, String(value));\n\t\t\t\t\treturn [String(name).toLowerCase(), String(value)];\n\t\t\t\t}) :\n\t\t\t\tundefined;\n\n\t\tsuper(result);\n\n\t\t// Returning a Proxy that will lowercase key names, validate parameters and sort keys\n\t\t// eslint-disable-next-line no-constructor-return\n\t\treturn new Proxy(this, {\n\t\t\tget(target, p, receiver) {\n\t\t\t\tswitch (p) {\n\t\t\t\t\tcase 'append':\n\t\t\t\t\tcase 'set':\n\t\t\t\t\t\treturn (name, value) => {\n\t\t\t\t\t\t\tvalidateHeaderName(name);\n\t\t\t\t\t\t\tvalidateHeaderValue(name, String(value));\n\t\t\t\t\t\t\treturn URLSearchParams.prototype[p].call(\n\t\t\t\t\t\t\t\ttarget,\n\t\t\t\t\t\t\t\tString(name).toLowerCase(),\n\t\t\t\t\t\t\t\tString(value)\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t};\n\n\t\t\t\t\tcase 'delete':\n\t\t\t\t\tcase 'has':\n\t\t\t\t\tcase 'getAll':\n\t\t\t\t\t\treturn name => {\n\t\t\t\t\t\t\tvalidateHeaderName(name);\n\t\t\t\t\t\t\treturn URLSearchParams.prototype[p].call(\n\t\t\t\t\t\t\t\ttarget,\n\t\t\t\t\t\t\t\tString(name).toLowerCase()\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t};\n\n\t\t\t\t\tcase 'keys':\n\t\t\t\t\t\treturn () => {\n\t\t\t\t\t\t\ttarget.sort();\n\t\t\t\t\t\t\treturn new Set(URLSearchParams.prototype.keys.call(target)).keys();\n\t\t\t\t\t\t};\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn Reflect.get(target, p, receiver);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t/* c8 ignore next */\n\t}\n\n\tget [Symbol.toStringTag]() {\n\t\treturn this.constructor.name;\n\t}\n\n\ttoString() {\n\t\treturn Object.prototype.toString.call(this);\n\t}\n\n\tget(name) {\n\t\tconst values = this.getAll(name);\n\t\tif (values.length === 0) {\n\t\t\treturn null;\n\t\t}\n\n\t\tlet value = values.join(', ');\n\t\tif (/^content-encoding$/i.test(name)) {\n\t\t\tvalue = value.toLowerCase();\n\t\t}\n\n\t\treturn value;\n\t}\n\n\tforEach(callback, thisArg = undefined) {\n\t\tfor (const name of this.keys()) {\n\t\t\tReflect.apply(callback, thisArg, [this.get(name), name, this]);\n\t\t}\n\t}\n\n\t* values() {\n\t\tfor (const name of this.keys()) {\n\t\t\tyield this.get(name);\n\t\t}\n\t}\n\n\t/**\n\t * @type {() => IterableIterator<[string, string]>}\n\t */\n\t* entries() {\n\t\tfor (const name of this.keys()) {\n\t\t\tyield [name, this.get(name)];\n\t\t}\n\t}\n\n\t[Symbol.iterator]() {\n\t\treturn this.entries();\n\t}\n\n\t/**\n\t * Node-fetch non-spec method\n\t * returning all headers and their values as array\n\t * @returns {Record}\n\t */\n\traw() {\n\t\treturn [...this.keys()].reduce((result, key) => {\n\t\t\tresult[key] = this.getAll(key);\n\t\t\treturn result;\n\t\t}, {});\n\t}\n\n\t/**\n\t * For better console.log(headers) and also to convert Headers into Node.js Request compatible format\n\t */\n\t[Symbol.for('nodejs.util.inspect.custom')]() {\n\t\treturn [...this.keys()].reduce((result, key) => {\n\t\t\tconst values = this.getAll(key);\n\t\t\t// Http.request() only supports string as Host header.\n\t\t\t// This hack makes specifying custom Host header possible.\n\t\t\tif (key === 'host') {\n\t\t\t\tresult[key] = values[0];\n\t\t\t} else {\n\t\t\t\tresult[key] = values.length > 1 ? values : values[0];\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}, {});\n\t}\n}\n\n/**\n * Re-shaping object for Web IDL tests\n * Only need to do it for overridden methods\n */\nObject.defineProperties(\n\tHeaders.prototype,\n\t['get', 'entries', 'forEach', 'values'].reduce((result, property) => {\n\t\tresult[property] = {enumerable: true};\n\t\treturn result;\n\t}, {})\n);\n\n/**\n * Create a Headers object from an http.IncomingMessage.rawHeaders, ignoring those that do\n * not conform to HTTP grammar productions.\n * @param {import('http').IncomingMessage['rawHeaders']} headers\n */\nexport function fromRawHeaders(headers = []) {\n\treturn new Headers(\n\t\theaders\n\t\t\t// Split into pairs\n\t\t\t.reduce((result, value, index, array) => {\n\t\t\t\tif (index % 2 === 0) {\n\t\t\t\t\tresult.push(array.slice(index, index + 2));\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t}, [])\n\t\t\t.filter(([name, value]) => {\n\t\t\t\ttry {\n\t\t\t\t\tvalidateHeaderName(name);\n\t\t\t\t\tvalidateHeaderValue(name, String(value));\n\t\t\t\t\treturn true;\n\t\t\t\t} catch {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t})\n\n\t);\n}\n", "const redirectStatus = new Set([301, 302, 303, 307, 308]);\n\n/**\n * Redirect code matching\n *\n * @param {number} code - Status code\n * @return {boolean}\n */\nexport const isRedirect = code => {\n\treturn redirectStatus.has(code);\n};\n", "/**\n * Response.js\n *\n * Response class provides content decoding\n */\n\nimport Headers from './headers.js';\nimport Body, {clone, extractContentType} from './body.js';\nimport {isRedirect} from './utils/is-redirect.js';\n\nconst INTERNALS = Symbol('Response internals');\n\n/**\n * Response class\n *\n * Ref: https://fetch.spec.whatwg.org/#response-class\n *\n * @param Stream body Readable stream\n * @param Object opts Response options\n * @return Void\n */\nexport default class Response extends Body {\n\tconstructor(body = null, options = {}) {\n\t\tsuper(body, options);\n\n\t\t// eslint-disable-next-line no-eq-null, eqeqeq, no-negated-condition\n\t\tconst status = options.status != null ? options.status : 200;\n\n\t\tconst headers = new Headers(options.headers);\n\n\t\tif (body !== null && !headers.has('Content-Type')) {\n\t\t\tconst contentType = extractContentType(body, this);\n\t\t\tif (contentType) {\n\t\t\t\theaders.append('Content-Type', contentType);\n\t\t\t}\n\t\t}\n\n\t\tthis[INTERNALS] = {\n\t\t\ttype: 'default',\n\t\t\turl: options.url,\n\t\t\tstatus,\n\t\t\tstatusText: options.statusText || '',\n\t\t\theaders,\n\t\t\tcounter: options.counter,\n\t\t\thighWaterMark: options.highWaterMark\n\t\t};\n\t}\n\n\tget type() {\n\t\treturn this[INTERNALS].type;\n\t}\n\n\tget url() {\n\t\treturn this[INTERNALS].url || '';\n\t}\n\n\tget status() {\n\t\treturn this[INTERNALS].status;\n\t}\n\n\t/**\n\t * Convenience property representing if the request ended normally\n\t */\n\tget ok() {\n\t\treturn this[INTERNALS].status >= 200 && this[INTERNALS].status < 300;\n\t}\n\n\tget redirected() {\n\t\treturn this[INTERNALS].counter > 0;\n\t}\n\n\tget statusText() {\n\t\treturn this[INTERNALS].statusText;\n\t}\n\n\tget headers() {\n\t\treturn this[INTERNALS].headers;\n\t}\n\n\tget highWaterMark() {\n\t\treturn this[INTERNALS].highWaterMark;\n\t}\n\n\t/**\n\t * Clone this response\n\t *\n\t * @return Response\n\t */\n\tclone() {\n\t\treturn new Response(clone(this, this.highWaterMark), {\n\t\t\ttype: this.type,\n\t\t\turl: this.url,\n\t\t\tstatus: this.status,\n\t\t\tstatusText: this.statusText,\n\t\t\theaders: this.headers,\n\t\t\tok: this.ok,\n\t\t\tredirected: this.redirected,\n\t\t\tsize: this.size,\n\t\t\thighWaterMark: this.highWaterMark\n\t\t});\n\t}\n\n\t/**\n\t * @param {string} url The URL that the new response is to originate from.\n\t * @param {number} status An optional status code for the response (e.g., 302.)\n\t * @returns {Response} A Response object.\n\t */\n\tstatic redirect(url, status = 302) {\n\t\tif (!isRedirect(status)) {\n\t\t\tthrow new RangeError('Failed to execute \"redirect\" on \"response\": Invalid status code');\n\t\t}\n\n\t\treturn new Response(null, {\n\t\t\theaders: {\n\t\t\t\tlocation: new URL(url).toString()\n\t\t\t},\n\t\t\tstatus\n\t\t});\n\t}\n\n\tstatic error() {\n\t\tconst response = new Response(null, {status: 0, statusText: ''});\n\t\tresponse[INTERNALS].type = 'error';\n\t\treturn response;\n\t}\n\n\tstatic json(data = undefined, init = {}) {\n\t\tconst body = JSON.stringify(data);\n\n\t\tif (body === undefined) {\n\t\t\tthrow new TypeError('data is not JSON serializable');\n\t\t}\n\n\t\tconst headers = new Headers(init && init.headers);\n\n\t\tif (!headers.has('content-type')) {\n\t\t\theaders.set('content-type', 'application/json');\n\t\t}\n\n\t\treturn new Response(body, {\n\t\t\t...init,\n\t\t\theaders\n\t\t});\n\t}\n\n\tget [Symbol.toStringTag]() {\n\t\treturn 'Response';\n\t}\n}\n\nObject.defineProperties(Response.prototype, {\n\ttype: {enumerable: true},\n\turl: {enumerable: true},\n\tstatus: {enumerable: true},\n\tok: {enumerable: true},\n\tredirected: {enumerable: true},\n\tstatusText: {enumerable: true},\n\theaders: {enumerable: true},\n\tclone: {enumerable: true}\n});\n", "export const getSearch = parsedURL => {\n\tif (parsedURL.search) {\n\t\treturn parsedURL.search;\n\t}\n\n\tconst lastOffset = parsedURL.href.length - 1;\n\tconst hash = parsedURL.hash || (parsedURL.href[lastOffset] === '#' ? '#' : '');\n\treturn parsedURL.href[lastOffset - hash.length] === '?' ? '?' : '';\n};\n", "import {isIP} from 'node:net';\n\n/**\n * @external URL\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/URL|URL}\n */\n\n/**\n * @module utils/referrer\n * @private\n */\n\n/**\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#strip-url|Referrer Policy \u00A78.4. Strip url for use as a referrer}\n * @param {string} URL\n * @param {boolean} [originOnly=false]\n */\nexport function stripURLForUseAsAReferrer(url, originOnly = false) {\n\t// 1. If url is null, return no referrer.\n\tif (url == null) { // eslint-disable-line no-eq-null, eqeqeq\n\t\treturn 'no-referrer';\n\t}\n\n\turl = new URL(url);\n\n\t// 2. If url's scheme is a local scheme, then return no referrer.\n\tif (/^(about|blob|data):$/.test(url.protocol)) {\n\t\treturn 'no-referrer';\n\t}\n\n\t// 3. Set url's username to the empty string.\n\turl.username = '';\n\n\t// 4. Set url's password to null.\n\t// Note: `null` appears to be a mistake as this actually results in the password being `\"null\"`.\n\turl.password = '';\n\n\t// 5. Set url's fragment to null.\n\t// Note: `null` appears to be a mistake as this actually results in the fragment being `\"#null\"`.\n\turl.hash = '';\n\n\t// 6. If the origin-only flag is true, then:\n\tif (originOnly) {\n\t\t// 6.1. Set url's path to null.\n\t\t// Note: `null` appears to be a mistake as this actually results in the path being `\"/null\"`.\n\t\turl.pathname = '';\n\n\t\t// 6.2. Set url's query to null.\n\t\t// Note: `null` appears to be a mistake as this actually results in the query being `\"?null\"`.\n\t\turl.search = '';\n\t}\n\n\t// 7. Return url.\n\treturn url;\n}\n\n/**\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#enumdef-referrerpolicy|enum ReferrerPolicy}\n */\nexport const ReferrerPolicy = new Set([\n\t'',\n\t'no-referrer',\n\t'no-referrer-when-downgrade',\n\t'same-origin',\n\t'origin',\n\t'strict-origin',\n\t'origin-when-cross-origin',\n\t'strict-origin-when-cross-origin',\n\t'unsafe-url'\n]);\n\n/**\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#default-referrer-policy|default referrer policy}\n */\nexport const DEFAULT_REFERRER_POLICY = 'strict-origin-when-cross-origin';\n\n/**\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#referrer-policies|Referrer Policy \u00A73. Referrer Policies}\n * @param {string} referrerPolicy\n * @returns {string} referrerPolicy\n */\nexport function validateReferrerPolicy(referrerPolicy) {\n\tif (!ReferrerPolicy.has(referrerPolicy)) {\n\t\tthrow new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);\n\t}\n\n\treturn referrerPolicy;\n}\n\n/**\n * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-origin-trustworthy|Referrer Policy \u00A73.2. Is origin potentially trustworthy?}\n * @param {external:URL} url\n * @returns `true`: \"Potentially Trustworthy\", `false`: \"Not Trustworthy\"\n */\nexport function isOriginPotentiallyTrustworthy(url) {\n\t// 1. If origin is an opaque origin, return \"Not Trustworthy\".\n\t// Not applicable\n\n\t// 2. Assert: origin is a tuple origin.\n\t// Not for implementations\n\n\t// 3. If origin's scheme is either \"https\" or \"wss\", return \"Potentially Trustworthy\".\n\tif (/^(http|ws)s:$/.test(url.protocol)) {\n\t\treturn true;\n\t}\n\n\t// 4. If origin's host component matches one of the CIDR notations 127.0.0.0/8 or ::1/128 [RFC4632], return \"Potentially Trustworthy\".\n\tconst hostIp = url.host.replace(/(^\\[)|(]$)/g, '');\n\tconst hostIPVersion = isIP(hostIp);\n\n\tif (hostIPVersion === 4 && /^127\\./.test(hostIp)) {\n\t\treturn true;\n\t}\n\n\tif (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) {\n\t\treturn true;\n\t}\n\n\t// 5. If origin's host component is \"localhost\" or falls within \".localhost\", and the user agent conforms to the name resolution rules in [let-localhost-be-localhost], return \"Potentially Trustworthy\".\n\t// We are returning FALSE here because we cannot ensure conformance to\n\t// let-localhost-be-loalhost (https://tools.ietf.org/html/draft-west-let-localhost-be-localhost)\n\tif (url.host === 'localhost' || url.host.endsWith('.localhost')) {\n\t\treturn false;\n\t}\n\n\t// 6. If origin's scheme component is file, return \"Potentially Trustworthy\".\n\tif (url.protocol === 'file:') {\n\t\treturn true;\n\t}\n\n\t// 7. If origin's scheme component is one which the user agent considers to be authenticated, return \"Potentially Trustworthy\".\n\t// Not supported\n\n\t// 8. If origin has been configured as a trustworthy origin, return \"Potentially Trustworthy\".\n\t// Not supported\n\n\t// 9. Return \"Not Trustworthy\".\n\treturn false;\n}\n\n/**\n * @see {@link https://w3c.github.io/webappsec-secure-contexts/#is-url-trustworthy|Referrer Policy \u00A73.3. Is url potentially trustworthy?}\n * @param {external:URL} url\n * @returns `true`: \"Potentially Trustworthy\", `false`: \"Not Trustworthy\"\n */\nexport function isUrlPotentiallyTrustworthy(url) {\n\t// 1. If url is \"about:blank\" or \"about:srcdoc\", return \"Potentially Trustworthy\".\n\tif (/^about:(blank|srcdoc)$/.test(url)) {\n\t\treturn true;\n\t}\n\n\t// 2. If url's scheme is \"data\", return \"Potentially Trustworthy\".\n\tif (url.protocol === 'data:') {\n\t\treturn true;\n\t}\n\n\t// Note: The origin of blob: and filesystem: URLs is the origin of the context in which they were\n\t// created. Therefore, blobs created in a trustworthy origin will themselves be potentially\n\t// trustworthy.\n\tif (/^(blob|filesystem):$/.test(url.protocol)) {\n\t\treturn true;\n\t}\n\n\t// 3. Return the result of executing \u00A73.2 Is origin potentially trustworthy? on url's origin.\n\treturn isOriginPotentiallyTrustworthy(url);\n}\n\n/**\n * Modifies the referrerURL to enforce any extra security policy considerations.\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy \u00A78.3. Determine request's Referrer}, step 7\n * @callback module:utils/referrer~referrerURLCallback\n * @param {external:URL} referrerURL\n * @returns {external:URL} modified referrerURL\n */\n\n/**\n * Modifies the referrerOrigin to enforce any extra security policy considerations.\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy \u00A78.3. Determine request's Referrer}, step 7\n * @callback module:utils/referrer~referrerOriginCallback\n * @param {external:URL} referrerOrigin\n * @returns {external:URL} modified referrerOrigin\n */\n\n/**\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer|Referrer Policy \u00A78.3. Determine request's Referrer}\n * @param {Request} request\n * @param {object} o\n * @param {module:utils/referrer~referrerURLCallback} o.referrerURLCallback\n * @param {module:utils/referrer~referrerOriginCallback} o.referrerOriginCallback\n * @returns {external:URL} Request's referrer\n */\nexport function determineRequestsReferrer(request, {referrerURLCallback, referrerOriginCallback} = {}) {\n\t// There are 2 notes in the specification about invalid pre-conditions. We return null, here, for\n\t// these cases:\n\t// > Note: If request's referrer is \"no-referrer\", Fetch will not call into this algorithm.\n\t// > Note: If request's referrer policy is the empty string, Fetch will not call into this\n\t// > algorithm.\n\tif (request.referrer === 'no-referrer' || request.referrerPolicy === '') {\n\t\treturn null;\n\t}\n\n\t// 1. Let policy be request's associated referrer policy.\n\tconst policy = request.referrerPolicy;\n\n\t// 2. Let environment be request's client.\n\t// not applicable to node.js\n\n\t// 3. Switch on request's referrer:\n\tif (request.referrer === 'about:client') {\n\t\treturn 'no-referrer';\n\t}\n\n\t// \"a URL\": Let referrerSource be request's referrer.\n\tconst referrerSource = request.referrer;\n\n\t// 4. Let request's referrerURL be the result of stripping referrerSource for use as a referrer.\n\tlet referrerURL = stripURLForUseAsAReferrer(referrerSource);\n\n\t// 5. Let referrerOrigin be the result of stripping referrerSource for use as a referrer, with the\n\t// origin-only flag set to true.\n\tlet referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true);\n\n\t// 6. If the result of serializing referrerURL is a string whose length is greater than 4096, set\n\t// referrerURL to referrerOrigin.\n\tif (referrerURL.toString().length > 4096) {\n\t\treferrerURL = referrerOrigin;\n\t}\n\n\t// 7. The user agent MAY alter referrerURL or referrerOrigin at this point to enforce arbitrary\n\t// policy considerations in the interests of minimizing data leakage. For example, the user\n\t// agent could strip the URL down to an origin, modify its host, replace it with an empty\n\t// string, etc.\n\tif (referrerURLCallback) {\n\t\treferrerURL = referrerURLCallback(referrerURL);\n\t}\n\n\tif (referrerOriginCallback) {\n\t\treferrerOrigin = referrerOriginCallback(referrerOrigin);\n\t}\n\n\t// 8.Execute the statements corresponding to the value of policy:\n\tconst currentURL = new URL(request.url);\n\n\tswitch (policy) {\n\t\tcase 'no-referrer':\n\t\t\treturn 'no-referrer';\n\n\t\tcase 'origin':\n\t\t\treturn referrerOrigin;\n\n\t\tcase 'unsafe-url':\n\t\t\treturn referrerURL;\n\n\t\tcase 'strict-origin':\n\t\t\t// 1. If referrerURL is a potentially trustworthy URL and request's current URL is not a\n\t\t\t// potentially trustworthy URL, then return no referrer.\n\t\t\tif (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {\n\t\t\t\treturn 'no-referrer';\n\t\t\t}\n\n\t\t\t// 2. Return referrerOrigin.\n\t\t\treturn referrerOrigin.toString();\n\n\t\tcase 'strict-origin-when-cross-origin':\n\t\t\t// 1. If the origin of referrerURL and the origin of request's current URL are the same, then\n\t\t\t// return referrerURL.\n\t\t\tif (referrerURL.origin === currentURL.origin) {\n\t\t\t\treturn referrerURL;\n\t\t\t}\n\n\t\t\t// 2. If referrerURL is a potentially trustworthy URL and request's current URL is not a\n\t\t\t// potentially trustworthy URL, then return no referrer.\n\t\t\tif (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {\n\t\t\t\treturn 'no-referrer';\n\t\t\t}\n\n\t\t\t// 3. Return referrerOrigin.\n\t\t\treturn referrerOrigin;\n\n\t\tcase 'same-origin':\n\t\t\t// 1. If the origin of referrerURL and the origin of request's current URL are the same, then\n\t\t\t// return referrerURL.\n\t\t\tif (referrerURL.origin === currentURL.origin) {\n\t\t\t\treturn referrerURL;\n\t\t\t}\n\n\t\t\t// 2. Return no referrer.\n\t\t\treturn 'no-referrer';\n\n\t\tcase 'origin-when-cross-origin':\n\t\t\t// 1. If the origin of referrerURL and the origin of request's current URL are the same, then\n\t\t\t// return referrerURL.\n\t\t\tif (referrerURL.origin === currentURL.origin) {\n\t\t\t\treturn referrerURL;\n\t\t\t}\n\n\t\t\t// Return referrerOrigin.\n\t\t\treturn referrerOrigin;\n\n\t\tcase 'no-referrer-when-downgrade':\n\t\t\t// 1. If referrerURL is a potentially trustworthy URL and request's current URL is not a\n\t\t\t// potentially trustworthy URL, then return no referrer.\n\t\t\tif (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {\n\t\t\t\treturn 'no-referrer';\n\t\t\t}\n\n\t\t\t// 2. Return referrerURL.\n\t\t\treturn referrerURL;\n\n\t\tdefault:\n\t\t\tthrow new TypeError(`Invalid referrerPolicy: ${policy}`);\n\t}\n}\n\n/**\n * @see {@link https://w3c.github.io/webappsec-referrer-policy/#parse-referrer-policy-from-header|Referrer Policy \u00A78.1. Parse a referrer policy from a Referrer-Policy header}\n * @param {Headers} headers Response headers\n * @returns {string} policy\n */\nexport function parseReferrerPolicyFromHeader(headers) {\n\t// 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy`\n\t// and response\u2019s header list.\n\tconst policyTokens = (headers.get('referrer-policy') || '').split(/[,\\s]+/);\n\n\t// 2. Let policy be the empty string.\n\tlet policy = '';\n\n\t// 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty\n\t// string, then set policy to token.\n\t// Note: This algorithm loops over multiple policy values to allow deployment of new policy\n\t// values with fallbacks for older user agents, as described in \u00A7 11.1 Unknown Policy Values.\n\tfor (const token of policyTokens) {\n\t\tif (token && ReferrerPolicy.has(token)) {\n\t\t\tpolicy = token;\n\t\t}\n\t}\n\n\t// 4. Return policy.\n\treturn policy;\n}\n", "/**\n * Request.js\n *\n * Request class contains server only options\n *\n * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/.\n */\n\nimport {format as formatUrl} from 'node:url';\nimport {deprecate} from 'node:util';\nimport Headers from './headers.js';\nimport Body, {clone, extractContentType, getTotalBytes} from './body.js';\nimport {isAbortSignal} from './utils/is.js';\nimport {getSearch} from './utils/get-search.js';\nimport {\n\tvalidateReferrerPolicy, determineRequestsReferrer, DEFAULT_REFERRER_POLICY\n} from './utils/referrer.js';\n\nconst INTERNALS = Symbol('Request internals');\n\n/**\n * Check if `obj` is an instance of Request.\n *\n * @param {*} object\n * @return {boolean}\n */\nconst isRequest = object => {\n\treturn (\n\t\ttypeof object === 'object' &&\n\t\ttypeof object[INTERNALS] === 'object'\n\t);\n};\n\nconst doBadDataWarn = deprecate(() => {},\n\t'.data is not a valid RequestInit property, use .body instead',\n\t'https://github.com/node-fetch/node-fetch/issues/1000 (request)');\n\n/**\n * Request class\n *\n * Ref: https://fetch.spec.whatwg.org/#request-class\n *\n * @param Mixed input Url or Request instance\n * @param Object init Custom options\n * @return Void\n */\nexport default class Request extends Body {\n\tconstructor(input, init = {}) {\n\t\tlet parsedURL;\n\n\t\t// Normalize input and force URL to be encoded as UTF-8 (https://github.com/node-fetch/node-fetch/issues/245)\n\t\tif (isRequest(input)) {\n\t\t\tparsedURL = new URL(input.url);\n\t\t} else {\n\t\t\tparsedURL = new URL(input);\n\t\t\tinput = {};\n\t\t}\n\n\t\tif (parsedURL.username !== '' || parsedURL.password !== '') {\n\t\t\tthrow new TypeError(`${parsedURL} is an url with embedded credentials.`);\n\t\t}\n\n\t\tlet method = init.method || input.method || 'GET';\n\t\tif (/^(delete|get|head|options|post|put)$/i.test(method)) {\n\t\t\tmethod = method.toUpperCase();\n\t\t}\n\n\t\tif (!isRequest(init) && 'data' in init) {\n\t\t\tdoBadDataWarn();\n\t\t}\n\n\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\tif ((init.body != null || (isRequest(input) && input.body !== null)) &&\n\t\t\t(method === 'GET' || method === 'HEAD')) {\n\t\t\tthrow new TypeError('Request with GET/HEAD method cannot have body');\n\t\t}\n\n\t\tconst inputBody = init.body ?\n\t\t\tinit.body :\n\t\t\t(isRequest(input) && input.body !== null ?\n\t\t\t\tclone(input) :\n\t\t\t\tnull);\n\n\t\tsuper(inputBody, {\n\t\t\tsize: init.size || input.size || 0\n\t\t});\n\n\t\tconst headers = new Headers(init.headers || input.headers || {});\n\n\t\tif (inputBody !== null && !headers.has('Content-Type')) {\n\t\t\tconst contentType = extractContentType(inputBody, this);\n\t\t\tif (contentType) {\n\t\t\t\theaders.set('Content-Type', contentType);\n\t\t\t}\n\t\t}\n\n\t\tlet signal = isRequest(input) ?\n\t\t\tinput.signal :\n\t\t\tnull;\n\t\tif ('signal' in init) {\n\t\t\tsignal = init.signal;\n\t\t}\n\n\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\tif (signal != null && !isAbortSignal(signal)) {\n\t\t\tthrow new TypeError('Expected signal to be an instanceof AbortSignal or EventTarget');\n\t\t}\n\n\t\t// \u00A75.4, Request constructor steps, step 15.1\n\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\tlet referrer = init.referrer == null ? input.referrer : init.referrer;\n\t\tif (referrer === '') {\n\t\t\t// \u00A75.4, Request constructor steps, step 15.2\n\t\t\treferrer = 'no-referrer';\n\t\t} else if (referrer) {\n\t\t\t// \u00A75.4, Request constructor steps, step 15.3.1, 15.3.2\n\t\t\tconst parsedReferrer = new URL(referrer);\n\t\t\t// \u00A75.4, Request constructor steps, step 15.3.3, 15.3.4\n\t\t\treferrer = /^about:(\\/\\/)?client$/.test(parsedReferrer) ? 'client' : parsedReferrer;\n\t\t} else {\n\t\t\treferrer = undefined;\n\t\t}\n\n\t\tthis[INTERNALS] = {\n\t\t\tmethod,\n\t\t\tredirect: init.redirect || input.redirect || 'follow',\n\t\t\theaders,\n\t\t\tparsedURL,\n\t\t\tsignal,\n\t\t\treferrer\n\t\t};\n\n\t\t// Node-fetch-only options\n\t\tthis.follow = init.follow === undefined ? (input.follow === undefined ? 20 : input.follow) : init.follow;\n\t\tthis.compress = init.compress === undefined ? (input.compress === undefined ? true : input.compress) : init.compress;\n\t\tthis.counter = init.counter || input.counter || 0;\n\t\tthis.agent = init.agent || input.agent;\n\t\tthis.highWaterMark = init.highWaterMark || input.highWaterMark || 16384;\n\t\tthis.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false;\n\n\t\t// \u00A75.4, Request constructor steps, step 16.\n\t\t// Default is empty string per https://fetch.spec.whatwg.org/#concept-request-referrer-policy\n\t\tthis.referrerPolicy = init.referrerPolicy || input.referrerPolicy || '';\n\t}\n\n\t/** @returns {string} */\n\tget method() {\n\t\treturn this[INTERNALS].method;\n\t}\n\n\t/** @returns {string} */\n\tget url() {\n\t\treturn formatUrl(this[INTERNALS].parsedURL);\n\t}\n\n\t/** @returns {Headers} */\n\tget headers() {\n\t\treturn this[INTERNALS].headers;\n\t}\n\n\tget redirect() {\n\t\treturn this[INTERNALS].redirect;\n\t}\n\n\t/** @returns {AbortSignal} */\n\tget signal() {\n\t\treturn this[INTERNALS].signal;\n\t}\n\n\t// https://fetch.spec.whatwg.org/#dom-request-referrer\n\tget referrer() {\n\t\tif (this[INTERNALS].referrer === 'no-referrer') {\n\t\t\treturn '';\n\t\t}\n\n\t\tif (this[INTERNALS].referrer === 'client') {\n\t\t\treturn 'about:client';\n\t\t}\n\n\t\tif (this[INTERNALS].referrer) {\n\t\t\treturn this[INTERNALS].referrer.toString();\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tget referrerPolicy() {\n\t\treturn this[INTERNALS].referrerPolicy;\n\t}\n\n\tset referrerPolicy(referrerPolicy) {\n\t\tthis[INTERNALS].referrerPolicy = validateReferrerPolicy(referrerPolicy);\n\t}\n\n\t/**\n\t * Clone this request\n\t *\n\t * @return Request\n\t */\n\tclone() {\n\t\treturn new Request(this);\n\t}\n\n\tget [Symbol.toStringTag]() {\n\t\treturn 'Request';\n\t}\n}\n\nObject.defineProperties(Request.prototype, {\n\tmethod: {enumerable: true},\n\turl: {enumerable: true},\n\theaders: {enumerable: true},\n\tredirect: {enumerable: true},\n\tclone: {enumerable: true},\n\tsignal: {enumerable: true},\n\treferrer: {enumerable: true},\n\treferrerPolicy: {enumerable: true}\n});\n\n/**\n * Convert a Request to Node.js http request options.\n *\n * @param {Request} request - A Request instance\n * @return The options object to be passed to http.request\n */\nexport const getNodeRequestOptions = request => {\n\tconst {parsedURL} = request[INTERNALS];\n\tconst headers = new Headers(request[INTERNALS].headers);\n\n\t// Fetch step 1.3\n\tif (!headers.has('Accept')) {\n\t\theaders.set('Accept', '*/*');\n\t}\n\n\t// HTTP-network-or-cache fetch steps 2.4-2.7\n\tlet contentLengthValue = null;\n\tif (request.body === null && /^(post|put)$/i.test(request.method)) {\n\t\tcontentLengthValue = '0';\n\t}\n\n\tif (request.body !== null) {\n\t\tconst totalBytes = getTotalBytes(request);\n\t\t// Set Content-Length if totalBytes is a number (that is not NaN)\n\t\tif (typeof totalBytes === 'number' && !Number.isNaN(totalBytes)) {\n\t\t\tcontentLengthValue = String(totalBytes);\n\t\t}\n\t}\n\n\tif (contentLengthValue) {\n\t\theaders.set('Content-Length', contentLengthValue);\n\t}\n\n\t// 4.1. Main fetch, step 2.6\n\t// > If request's referrer policy is the empty string, then set request's referrer policy to the\n\t// > default referrer policy.\n\tif (request.referrerPolicy === '') {\n\t\trequest.referrerPolicy = DEFAULT_REFERRER_POLICY;\n\t}\n\n\t// 4.1. Main fetch, step 2.7\n\t// > If request's referrer is not \"no-referrer\", set request's referrer to the result of invoking\n\t// > determine request's referrer.\n\tif (request.referrer && request.referrer !== 'no-referrer') {\n\t\trequest[INTERNALS].referrer = determineRequestsReferrer(request);\n\t} else {\n\t\trequest[INTERNALS].referrer = 'no-referrer';\n\t}\n\n\t// 4.5. HTTP-network-or-cache fetch, step 6.9\n\t// > If httpRequest's referrer is a URL, then append `Referer`/httpRequest's referrer, serialized\n\t// > and isomorphic encoded, to httpRequest's header list.\n\tif (request[INTERNALS].referrer instanceof URL) {\n\t\theaders.set('Referer', request.referrer);\n\t}\n\n\t// HTTP-network-or-cache fetch step 2.11\n\tif (!headers.has('User-Agent')) {\n\t\theaders.set('User-Agent', 'node-fetch');\n\t}\n\n\t// HTTP-network-or-cache fetch step 2.15\n\tif (request.compress && !headers.has('Accept-Encoding')) {\n\t\theaders.set('Accept-Encoding', 'gzip, deflate, br');\n\t}\n\n\tlet {agent} = request;\n\tif (typeof agent === 'function') {\n\t\tagent = agent(parsedURL);\n\t}\n\n\t// HTTP-network fetch step 4.2\n\t// chunked encoding is handled by Node.js\n\n\tconst search = getSearch(parsedURL);\n\n\t// Pass the full URL directly to request(), but overwrite the following\n\t// options:\n\tconst options = {\n\t\t// Overwrite search to retain trailing ? (issue #776)\n\t\tpath: parsedURL.pathname + search,\n\t\t// The following options are not expressed in the URL\n\t\tmethod: request.method,\n\t\theaders: headers[Symbol.for('nodejs.util.inspect.custom')](),\n\t\tinsecureHTTPParser: request.insecureHTTPParser,\n\t\tagent\n\t};\n\n\treturn {\n\t\t/** @type {URL} */\n\t\tparsedURL,\n\t\toptions\n\t};\n};\n", "import {FetchBaseError} from './base.js';\n\n/**\n * AbortError interface for cancelled requests\n */\nexport class AbortError extends FetchBaseError {\n\tconstructor(message, type = 'aborted') {\n\t\tsuper(message, type);\n\t}\n}\n", "/**\n * Index.js\n *\n * a request API compatible with window.fetch\n *\n * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/.\n */\n\nimport http from 'node:http';\nimport https from 'node:https';\nimport zlib from 'node:zlib';\nimport Stream, {PassThrough, pipeline as pump} from 'node:stream';\nimport {Buffer} from 'node:buffer';\n\nimport dataUriToBuffer from 'data-uri-to-buffer';\n\nimport {writeToStream, clone} from './body.js';\nimport Response from './response.js';\nimport Headers, {fromRawHeaders} from './headers.js';\nimport Request, {getNodeRequestOptions} from './request.js';\nimport {FetchError} from './errors/fetch-error.js';\nimport {AbortError} from './errors/abort-error.js';\nimport {isRedirect} from './utils/is-redirect.js';\nimport {FormData} from 'formdata-polyfill/esm.min.js';\nimport {isDomainOrSubdomain, isSameProtocol} from './utils/is.js';\nimport {parseReferrerPolicyFromHeader} from './utils/referrer.js';\nimport {\n\tBlob,\n\tFile,\n\tfileFromSync,\n\tfileFrom,\n\tblobFromSync,\n\tblobFrom\n} from 'fetch-blob/from.js';\n\nexport {FormData, Headers, Request, Response, FetchError, AbortError, isRedirect};\nexport {Blob, File, fileFromSync, fileFrom, blobFromSync, blobFrom};\n\nconst supportedSchemas = new Set(['data:', 'http:', 'https:']);\n\n/**\n * Fetch function\n *\n * @param {string | URL | import('./request').default} url - Absolute url or Request instance\n * @param {*} [options_] - Fetch options\n * @return {Promise}\n */\nexport default async function fetch(url, options_) {\n\treturn new Promise((resolve, reject) => {\n\t\t// Build request object\n\t\tconst request = new Request(url, options_);\n\t\tconst {parsedURL, options} = getNodeRequestOptions(request);\n\t\tif (!supportedSchemas.has(parsedURL.protocol)) {\n\t\t\tthrow new TypeError(`node-fetch cannot load ${url}. URL scheme \"${parsedURL.protocol.replace(/:$/, '')}\" is not supported.`);\n\t\t}\n\n\t\tif (parsedURL.protocol === 'data:') {\n\t\t\tconst data = dataUriToBuffer(request.url);\n\t\t\tconst response = new Response(data, {headers: {'Content-Type': data.typeFull}});\n\t\t\tresolve(response);\n\t\t\treturn;\n\t\t}\n\n\t\t// Wrap http.request into fetch\n\t\tconst send = (parsedURL.protocol === 'https:' ? https : http).request;\n\t\tconst {signal} = request;\n\t\tlet response = null;\n\n\t\tconst abort = () => {\n\t\t\tconst error = new AbortError('The operation was aborted.');\n\t\t\treject(error);\n\t\t\tif (request.body && request.body instanceof Stream.Readable) {\n\t\t\t\trequest.body.destroy(error);\n\t\t\t}\n\n\t\t\tif (!response || !response.body) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tresponse.body.emit('error', error);\n\t\t};\n\n\t\tif (signal && signal.aborted) {\n\t\t\tabort();\n\t\t\treturn;\n\t\t}\n\n\t\tconst abortAndFinalize = () => {\n\t\t\tabort();\n\t\t\tfinalize();\n\t\t};\n\n\t\t// Send request\n\t\tconst request_ = send(parsedURL.toString(), options);\n\n\t\tif (signal) {\n\t\t\tsignal.addEventListener('abort', abortAndFinalize);\n\t\t}\n\n\t\tconst finalize = () => {\n\t\t\trequest_.abort();\n\t\t\tif (signal) {\n\t\t\t\tsignal.removeEventListener('abort', abortAndFinalize);\n\t\t\t}\n\t\t};\n\n\t\trequest_.on('error', error => {\n\t\t\treject(new FetchError(`request to ${request.url} failed, reason: ${error.message}`, 'system', error));\n\t\t\tfinalize();\n\t\t});\n\n\t\tfixResponseChunkedTransferBadEnding(request_, error => {\n\t\t\tif (response && response.body) {\n\t\t\t\tresponse.body.destroy(error);\n\t\t\t}\n\t\t});\n\n\t\t/* c8 ignore next 18 */\n\t\tif (process.version < 'v14') {\n\t\t\t// Before Node.js 14, pipeline() does not fully support async iterators and does not always\n\t\t\t// properly handle when the socket close/end events are out of order.\n\t\t\trequest_.on('socket', s => {\n\t\t\t\tlet endedWithEventsCount;\n\t\t\t\ts.prependListener('end', () => {\n\t\t\t\t\tendedWithEventsCount = s._eventsCount;\n\t\t\t\t});\n\t\t\t\ts.prependListener('close', hadError => {\n\t\t\t\t\t// if end happened before close but the socket didn't emit an error, do it now\n\t\t\t\t\tif (response && endedWithEventsCount < s._eventsCount && !hadError) {\n\t\t\t\t\t\tconst error = new Error('Premature close');\n\t\t\t\t\t\terror.code = 'ERR_STREAM_PREMATURE_CLOSE';\n\t\t\t\t\t\tresponse.body.emit('error', error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\trequest_.on('response', response_ => {\n\t\t\trequest_.setTimeout(0);\n\t\t\tconst headers = fromRawHeaders(response_.rawHeaders);\n\n\t\t\t// HTTP fetch step 5\n\t\t\tif (isRedirect(response_.statusCode)) {\n\t\t\t\t// HTTP fetch step 5.2\n\t\t\t\tconst location = headers.get('Location');\n\n\t\t\t\t// HTTP fetch step 5.3\n\t\t\t\tlet locationURL = null;\n\t\t\t\ttry {\n\t\t\t\t\tlocationURL = location === null ? null : new URL(location, request.url);\n\t\t\t\t} catch {\n\t\t\t\t\t// error here can only be invalid URL in Location: header\n\t\t\t\t\t// do not throw when options.redirect == manual\n\t\t\t\t\t// let the user extract the errorneous redirect URL\n\t\t\t\t\tif (request.redirect !== 'manual') {\n\t\t\t\t\t\treject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'));\n\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// HTTP fetch step 5.5\n\t\t\t\tswitch (request.redirect) {\n\t\t\t\t\tcase 'error':\n\t\t\t\t\t\treject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));\n\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\treturn;\n\t\t\t\t\tcase 'manual':\n\t\t\t\t\t\t// Nothing to do\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'follow': {\n\t\t\t\t\t\t// HTTP-redirect fetch step 2\n\t\t\t\t\t\tif (locationURL === null) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 5\n\t\t\t\t\t\tif (request.counter >= request.follow) {\n\t\t\t\t\t\t\treject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));\n\t\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 6 (counter increment)\n\t\t\t\t\t\t// Create a new Request object.\n\t\t\t\t\t\tconst requestOptions = {\n\t\t\t\t\t\t\theaders: new Headers(request.headers),\n\t\t\t\t\t\t\tfollow: request.follow,\n\t\t\t\t\t\t\tcounter: request.counter + 1,\n\t\t\t\t\t\t\tagent: request.agent,\n\t\t\t\t\t\t\tcompress: request.compress,\n\t\t\t\t\t\t\tmethod: request.method,\n\t\t\t\t\t\t\tbody: clone(request),\n\t\t\t\t\t\t\tsignal: request.signal,\n\t\t\t\t\t\t\tsize: request.size,\n\t\t\t\t\t\t\treferrer: request.referrer,\n\t\t\t\t\t\t\treferrerPolicy: request.referrerPolicy\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t// when forwarding sensitive headers like \"Authorization\",\n\t\t\t\t\t\t// \"WWW-Authenticate\", and \"Cookie\" to untrusted targets,\n\t\t\t\t\t\t// headers will be ignored when following a redirect to a domain\n\t\t\t\t\t\t// that is not a subdomain match or exact match of the initial domain.\n\t\t\t\t\t\t// For example, a redirect from \"foo.com\" to either \"foo.com\" or \"sub.foo.com\"\n\t\t\t\t\t\t// will forward the sensitive headers, but a redirect to \"bar.com\" will not.\n\t\t\t\t\t\t// headers will also be ignored when following a redirect to a domain using\n\t\t\t\t\t\t// a different protocol. For example, a redirect from \"https://foo.com\" to \"http://foo.com\"\n\t\t\t\t\t\t// will not forward the sensitive headers\n\t\t\t\t\t\tif (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) {\n\t\t\t\t\t\t\tfor (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) {\n\t\t\t\t\t\t\t\trequestOptions.headers.delete(name);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 9\n\t\t\t\t\t\tif (response_.statusCode !== 303 && request.body && options_.body instanceof Stream.Readable) {\n\t\t\t\t\t\t\treject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));\n\t\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 11\n\t\t\t\t\t\tif (response_.statusCode === 303 || ((response_.statusCode === 301 || response_.statusCode === 302) && request.method === 'POST')) {\n\t\t\t\t\t\t\trequestOptions.method = 'GET';\n\t\t\t\t\t\t\trequestOptions.body = undefined;\n\t\t\t\t\t\t\trequestOptions.headers.delete('content-length');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 14\n\t\t\t\t\t\tconst responseReferrerPolicy = parseReferrerPolicyFromHeader(headers);\n\t\t\t\t\t\tif (responseReferrerPolicy) {\n\t\t\t\t\t\t\trequestOptions.referrerPolicy = responseReferrerPolicy;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// HTTP-redirect fetch step 15\n\t\t\t\t\t\tresolve(fetch(new Request(locationURL, requestOptions)));\n\t\t\t\t\t\tfinalize();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn reject(new TypeError(`Redirect option '${request.redirect}' is not a valid value of RequestRedirect`));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Prepare response\n\t\t\tif (signal) {\n\t\t\t\tresponse_.once('end', () => {\n\t\t\t\t\tsignal.removeEventListener('abort', abortAndFinalize);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tlet body = pump(response_, new PassThrough(), error => {\n\t\t\t\tif (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\t\t\t});\n\t\t\t// see https://github.com/nodejs/node/pull/29376\n\t\t\t/* c8 ignore next 3 */\n\t\t\tif (process.version < 'v12.10') {\n\t\t\t\tresponse_.on('aborted', abortAndFinalize);\n\t\t\t}\n\n\t\t\tconst responseOptions = {\n\t\t\t\turl: request.url,\n\t\t\t\tstatus: response_.statusCode,\n\t\t\t\tstatusText: response_.statusMessage,\n\t\t\t\theaders,\n\t\t\t\tsize: request.size,\n\t\t\t\tcounter: request.counter,\n\t\t\t\thighWaterMark: request.highWaterMark\n\t\t\t};\n\n\t\t\t// HTTP-network fetch step 12.1.1.3\n\t\t\tconst codings = headers.get('Content-Encoding');\n\n\t\t\t// HTTP-network fetch step 12.1.1.4: handle content codings\n\n\t\t\t// in following scenarios we ignore compression support\n\t\t\t// 1. compression support is disabled\n\t\t\t// 2. HEAD request\n\t\t\t// 3. no Content-Encoding header\n\t\t\t// 4. no content response (204)\n\t\t\t// 5. content not modified response (304)\n\t\t\tif (!request.compress || request.method === 'HEAD' || codings === null || response_.statusCode === 204 || response_.statusCode === 304) {\n\t\t\t\tresponse = new Response(body, responseOptions);\n\t\t\t\tresolve(response);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// For Node v6+\n\t\t\t// Be less strict when decoding compressed responses, since sometimes\n\t\t\t// servers send slightly invalid responses that are still accepted\n\t\t\t// by common browsers.\n\t\t\t// Always using Z_SYNC_FLUSH is what cURL does.\n\t\t\tconst zlibOptions = {\n\t\t\t\tflush: zlib.Z_SYNC_FLUSH,\n\t\t\t\tfinishFlush: zlib.Z_SYNC_FLUSH\n\t\t\t};\n\n\t\t\t// For gzip\n\t\t\tif (codings === 'gzip' || codings === 'x-gzip') {\n\t\t\t\tbody = pump(body, zlib.createGunzip(zlibOptions), error => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tresponse = new Response(body, responseOptions);\n\t\t\t\tresolve(response);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// For deflate\n\t\t\tif (codings === 'deflate' || codings === 'x-deflate') {\n\t\t\t\t// Handle the infamous raw deflate response from old servers\n\t\t\t\t// a hack for old IIS and Apache servers\n\t\t\t\tconst raw = pump(response_, new PassThrough(), error => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\traw.once('data', chunk => {\n\t\t\t\t\t// See http://stackoverflow.com/questions/37519828\n\t\t\t\t\tif ((chunk[0] & 0x0F) === 0x08) {\n\t\t\t\t\t\tbody = pump(body, zlib.createInflate(), error => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbody = pump(body, zlib.createInflateRaw(), error => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tresponse = new Response(body, responseOptions);\n\t\t\t\t\tresolve(response);\n\t\t\t\t});\n\t\t\t\traw.once('end', () => {\n\t\t\t\t\t// Some old IIS servers return zero-length OK deflate responses, so\n\t\t\t\t\t// 'data' is never emitted. See https://github.com/node-fetch/node-fetch/pull/903\n\t\t\t\t\tif (!response) {\n\t\t\t\t\t\tresponse = new Response(body, responseOptions);\n\t\t\t\t\t\tresolve(response);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// For br\n\t\t\tif (codings === 'br') {\n\t\t\t\tbody = pump(body, zlib.createBrotliDecompress(), error => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tresponse = new Response(body, responseOptions);\n\t\t\t\tresolve(response);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Otherwise, use response as-is\n\t\t\tresponse = new Response(body, responseOptions);\n\t\t\tresolve(response);\n\t\t});\n\n\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\twriteToStream(request_, request).catch(reject);\n\t});\n}\n\nfunction fixResponseChunkedTransferBadEnding(request, errorCallback) {\n\tconst LAST_CHUNK = Buffer.from('0\\r\\n\\r\\n');\n\n\tlet isChunkedTransfer = false;\n\tlet properLastChunkReceived = false;\n\tlet previousChunk;\n\n\trequest.on('response', response => {\n\t\tconst {headers} = response;\n\t\tisChunkedTransfer = headers['transfer-encoding'] === 'chunked' && !headers['content-length'];\n\t});\n\n\trequest.on('socket', socket => {\n\t\tconst onSocketClose = () => {\n\t\t\tif (isChunkedTransfer && !properLastChunkReceived) {\n\t\t\t\tconst error = new Error('Premature close');\n\t\t\t\terror.code = 'ERR_STREAM_PREMATURE_CLOSE';\n\t\t\t\terrorCallback(error);\n\t\t\t}\n\t\t};\n\n\t\tconst onData = buf => {\n\t\t\tproperLastChunkReceived = Buffer.compare(buf.slice(-5), LAST_CHUNK) === 0;\n\n\t\t\t// Sometimes final 0-length chunk and end of message code are in separate packets\n\t\t\tif (!properLastChunkReceived && previousChunk) {\n\t\t\t\tproperLastChunkReceived = (\n\t\t\t\t\tBuffer.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 &&\n\t\t\t\t\tBuffer.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tpreviousChunk = buf;\n\t\t};\n\n\t\tsocket.prependListener('close', onSocketClose);\n\t\tsocket.on('data', onData);\n\n\t\trequest.on('close', () => {\n\t\t\tsocket.removeListener('close', onSocketClose);\n\t\t\tsocket.removeListener('data', onData);\n\t\t});\n\t});\n}\n", null, null, ";(function (globalObject) {\r\n 'use strict';\r\n\r\n/*\r\n * bignumber.js v9.3.1\r\n * A JavaScript library for arbitrary-precision arithmetic.\r\n * https://github.com/MikeMcl/bignumber.js\r\n * Copyright (c) 2025 Michael Mclaughlin \r\n * MIT Licensed.\r\n *\r\n * BigNumber.prototype methods | BigNumber methods\r\n * |\r\n * absoluteValue abs | clone\r\n * comparedTo | config set\r\n * decimalPlaces dp | DECIMAL_PLACES\r\n * dividedBy div | ROUNDING_MODE\r\n * dividedToIntegerBy idiv | EXPONENTIAL_AT\r\n * exponentiatedBy pow | RANGE\r\n * integerValue | CRYPTO\r\n * isEqualTo eq | MODULO_MODE\r\n * isFinite | POW_PRECISION\r\n * isGreaterThan gt | FORMAT\r\n * isGreaterThanOrEqualTo gte | ALPHABET\r\n * isInteger | isBigNumber\r\n * isLessThan lt | maximum max\r\n * isLessThanOrEqualTo lte | minimum min\r\n * isNaN | random\r\n * isNegative | sum\r\n * isPositive |\r\n * isZero |\r\n * minus |\r\n * modulo mod |\r\n * multipliedBy times |\r\n * negated |\r\n * plus |\r\n * precision sd |\r\n * shiftedBy |\r\n * squareRoot sqrt |\r\n * toExponential |\r\n * toFixed |\r\n * toFormat |\r\n * toFraction |\r\n * toJSON |\r\n * toNumber |\r\n * toPrecision |\r\n * toString |\r\n * valueOf |\r\n *\r\n */\r\n\r\n\r\n var BigNumber,\r\n isNumeric = /^-?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i,\r\n mathceil = Math.ceil,\r\n mathfloor = Math.floor,\r\n\r\n bignumberError = '[BigNumber Error] ',\r\n tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ',\r\n\r\n BASE = 1e14,\r\n LOG_BASE = 14,\r\n MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1\r\n // MAX_INT32 = 0x7fffffff, // 2^31 - 1\r\n POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],\r\n SQRT_BASE = 1e7,\r\n\r\n // EDITABLE\r\n // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and\r\n // the arguments to toExponential, toFixed, toFormat, and toPrecision.\r\n MAX = 1E9; // 0 to MAX_INT32\r\n\r\n\r\n /*\r\n * Create and return a BigNumber constructor.\r\n */\r\n function clone(configObject) {\r\n var div, convertBase, parseNumeric,\r\n P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null },\r\n ONE = new BigNumber(1),\r\n\r\n\r\n //----------------------------- EDITABLE CONFIG DEFAULTS -------------------------------\r\n\r\n\r\n // The default values below must be integers within the inclusive ranges stated.\r\n // The values can also be changed at run-time using BigNumber.set.\r\n\r\n // The maximum number of decimal places for operations involving division.\r\n DECIMAL_PLACES = 20, // 0 to MAX\r\n\r\n // The rounding mode used when rounding to the above decimal places, and when using\r\n // toExponential, toFixed, toFormat and toPrecision, and round (default value).\r\n // UP 0 Away from zero.\r\n // DOWN 1 Towards zero.\r\n // CEIL 2 Towards +Infinity.\r\n // FLOOR 3 Towards -Infinity.\r\n // HALF_UP 4 Towards nearest neighbour. If equidistant, up.\r\n // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.\r\n // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.\r\n // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.\r\n // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.\r\n ROUNDING_MODE = 4, // 0 to 8\r\n\r\n // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]\r\n\r\n // The exponent value at and beneath which toString returns exponential notation.\r\n // Number type: -7\r\n TO_EXP_NEG = -7, // 0 to -MAX\r\n\r\n // The exponent value at and above which toString returns exponential notation.\r\n // Number type: 21\r\n TO_EXP_POS = 21, // 0 to MAX\r\n\r\n // RANGE : [MIN_EXP, MAX_EXP]\r\n\r\n // The minimum exponent value, beneath which underflow to zero occurs.\r\n // Number type: -324 (5e-324)\r\n MIN_EXP = -1e7, // -1 to -MAX\r\n\r\n // The maximum exponent value, above which overflow to Infinity occurs.\r\n // Number type: 308 (1.7976931348623157e+308)\r\n // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.\r\n MAX_EXP = 1e7, // 1 to MAX\r\n\r\n // Whether to use cryptographically-secure random number generation, if available.\r\n CRYPTO = false, // true or false\r\n\r\n // The modulo mode used when calculating the modulus: a mod n.\r\n // The quotient (q = a / n) is calculated according to the corresponding rounding mode.\r\n // The remainder (r) is calculated as: r = a - n * q.\r\n //\r\n // UP 0 The remainder is positive if the dividend is negative, else is negative.\r\n // DOWN 1 The remainder has the same sign as the dividend.\r\n // This modulo mode is commonly known as 'truncated division' and is\r\n // equivalent to (a % n) in JavaScript.\r\n // FLOOR 3 The remainder has the same sign as the divisor (Python %).\r\n // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.\r\n // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).\r\n // The remainder is always positive.\r\n //\r\n // The truncated division, floored division, Euclidian division and IEEE 754 remainder\r\n // modes are commonly used for the modulus operation.\r\n // Although the other rounding modes can also be used, they may not give useful results.\r\n MODULO_MODE = 1, // 0 to 9\r\n\r\n // The maximum number of significant digits of the result of the exponentiatedBy operation.\r\n // If POW_PRECISION is 0, there will be unlimited significant digits.\r\n POW_PRECISION = 0, // 0 to MAX\r\n\r\n // The format specification used by the BigNumber.prototype.toFormat method.\r\n FORMAT = {\r\n prefix: '',\r\n groupSize: 3,\r\n secondaryGroupSize: 0,\r\n groupSeparator: ',',\r\n decimalSeparator: '.',\r\n fractionGroupSize: 0,\r\n fractionGroupSeparator: '\\xA0', // non-breaking space\r\n suffix: ''\r\n },\r\n\r\n // The alphabet used for base conversion. It must be at least 2 characters long, with no '+',\r\n // '-', '.', whitespace, or repeated character.\r\n // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'\r\n ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz',\r\n alphabetHasNormalDecimalDigits = true;\r\n\r\n\r\n //------------------------------------------------------------------------------------------\r\n\r\n\r\n // CONSTRUCTOR\r\n\r\n\r\n /*\r\n * The BigNumber constructor and exported function.\r\n * Create and return a new instance of a BigNumber object.\r\n *\r\n * v {number|string|BigNumber} A numeric value.\r\n * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive.\r\n */\r\n function BigNumber(v, b) {\r\n var alphabet, c, caseChanged, e, i, isNum, len, str,\r\n x = this;\r\n\r\n // Enable constructor call without `new`.\r\n if (!(x instanceof BigNumber)) return new BigNumber(v, b);\r\n\r\n if (b == null) {\r\n\r\n if (v && v._isBigNumber === true) {\r\n x.s = v.s;\r\n\r\n if (!v.c || v.e > MAX_EXP) {\r\n x.c = x.e = null;\r\n } else if (v.e < MIN_EXP) {\r\n x.c = [x.e = 0];\r\n } else {\r\n x.e = v.e;\r\n x.c = v.c.slice();\r\n }\r\n\r\n return;\r\n }\r\n\r\n if ((isNum = typeof v == 'number') && v * 0 == 0) {\r\n\r\n // Use `1 / n` to handle minus zero also.\r\n x.s = 1 / v < 0 ? (v = -v, -1) : 1;\r\n\r\n // Fast path for integers, where n < 2147483648 (2**31).\r\n if (v === ~~v) {\r\n for (e = 0, i = v; i >= 10; i /= 10, e++);\r\n\r\n if (e > MAX_EXP) {\r\n x.c = x.e = null;\r\n } else {\r\n x.e = e;\r\n x.c = [v];\r\n }\r\n\r\n return;\r\n }\r\n\r\n str = String(v);\r\n } else {\r\n\r\n if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum);\r\n\r\n x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1;\r\n }\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n\r\n // Exponential form?\r\n if ((i = str.search(/e/i)) > 0) {\r\n\r\n // Determine exponent.\r\n if (e < 0) e = i;\r\n e += +str.slice(i + 1);\r\n str = str.substring(0, i);\r\n } else if (e < 0) {\r\n\r\n // Integer.\r\n e = str.length;\r\n }\r\n\r\n } else {\r\n\r\n // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'\r\n intCheck(b, 2, ALPHABET.length, 'Base');\r\n\r\n // Allow exponential notation to be used with base 10 argument, while\r\n // also rounding to DECIMAL_PLACES as with other bases.\r\n if (b == 10 && alphabetHasNormalDecimalDigits) {\r\n x = new BigNumber(v);\r\n return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE);\r\n }\r\n\r\n str = String(v);\r\n\r\n if (isNum = typeof v == 'number') {\r\n\r\n // Avoid potential interpretation of Infinity and NaN as base 44+ values.\r\n if (v * 0 != 0) return parseNumeric(x, str, isNum, b);\r\n\r\n x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1;\r\n\r\n // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'\r\n if (BigNumber.DEBUG && str.replace(/^0\\.0*|\\./, '').length > 15) {\r\n throw Error\r\n (tooManyDigits + v);\r\n }\r\n } else {\r\n x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1;\r\n }\r\n\r\n alphabet = ALPHABET.slice(0, b);\r\n e = i = 0;\r\n\r\n // Check that str is a valid base b number.\r\n // Don't use RegExp, so alphabet can contain special characters.\r\n for (len = str.length; i < len; i++) {\r\n if (alphabet.indexOf(c = str.charAt(i)) < 0) {\r\n if (c == '.') {\r\n\r\n // If '.' is not the first character and it has not be found before.\r\n if (i > e) {\r\n e = len;\r\n continue;\r\n }\r\n } else if (!caseChanged) {\r\n\r\n // Allow e.g. hexadecimal 'FF' as well as 'ff'.\r\n if (str == str.toUpperCase() && (str = str.toLowerCase()) ||\r\n str == str.toLowerCase() && (str = str.toUpperCase())) {\r\n caseChanged = true;\r\n i = -1;\r\n e = 0;\r\n continue;\r\n }\r\n }\r\n\r\n return parseNumeric(x, String(v), isNum, b);\r\n }\r\n }\r\n\r\n // Prevent later check for length on converted number.\r\n isNum = false;\r\n str = convertBase(str, b, 10, x.s);\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n else e = str.length;\r\n }\r\n\r\n // Determine leading zeros.\r\n for (i = 0; str.charCodeAt(i) === 48; i++);\r\n\r\n // Determine trailing zeros.\r\n for (len = str.length; str.charCodeAt(--len) === 48;);\r\n\r\n if (str = str.slice(i, ++len)) {\r\n len -= i;\r\n\r\n // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'\r\n if (isNum && BigNumber.DEBUG &&\r\n len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) {\r\n throw Error\r\n (tooManyDigits + (x.s * v));\r\n }\r\n\r\n // Overflow?\r\n if ((e = e - i - 1) > MAX_EXP) {\r\n\r\n // Infinity.\r\n x.c = x.e = null;\r\n\r\n // Underflow?\r\n } else if (e < MIN_EXP) {\r\n\r\n // Zero.\r\n x.c = [x.e = 0];\r\n } else {\r\n x.e = e;\r\n x.c = [];\r\n\r\n // Transform base\r\n\r\n // e is the base 10 exponent.\r\n // i is where to slice str to get the first element of the coefficient array.\r\n i = (e + 1) % LOG_BASE;\r\n if (e < 0) i += LOG_BASE; // i < 1\r\n\r\n if (i < len) {\r\n if (i) x.c.push(+str.slice(0, i));\r\n\r\n for (len -= LOG_BASE; i < len;) {\r\n x.c.push(+str.slice(i, i += LOG_BASE));\r\n }\r\n\r\n i = LOG_BASE - (str = str.slice(i)).length;\r\n } else {\r\n i -= len;\r\n }\r\n\r\n for (; i--; str += '0');\r\n x.c.push(+str);\r\n }\r\n } else {\r\n\r\n // Zero.\r\n x.c = [x.e = 0];\r\n }\r\n }\r\n\r\n\r\n // CONSTRUCTOR PROPERTIES\r\n\r\n\r\n BigNumber.clone = clone;\r\n\r\n BigNumber.ROUND_UP = 0;\r\n BigNumber.ROUND_DOWN = 1;\r\n BigNumber.ROUND_CEIL = 2;\r\n BigNumber.ROUND_FLOOR = 3;\r\n BigNumber.ROUND_HALF_UP = 4;\r\n BigNumber.ROUND_HALF_DOWN = 5;\r\n BigNumber.ROUND_HALF_EVEN = 6;\r\n BigNumber.ROUND_HALF_CEIL = 7;\r\n BigNumber.ROUND_HALF_FLOOR = 8;\r\n BigNumber.EUCLID = 9;\r\n\r\n\r\n /*\r\n * Configure infrequently-changing library-wide settings.\r\n *\r\n * Accept an object with the following optional properties (if the value of a property is\r\n * a number, it must be an integer within the inclusive range stated):\r\n *\r\n * DECIMAL_PLACES {number} 0 to MAX\r\n * ROUNDING_MODE {number} 0 to 8\r\n * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX]\r\n * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX]\r\n * CRYPTO {boolean} true or false\r\n * MODULO_MODE {number} 0 to 9\r\n * POW_PRECISION {number} 0 to MAX\r\n * ALPHABET {string} A string of two or more unique characters which does\r\n * not contain '.'.\r\n * FORMAT {object} An object with some of the following properties:\r\n * prefix {string}\r\n * groupSize {number}\r\n * secondaryGroupSize {number}\r\n * groupSeparator {string}\r\n * decimalSeparator {string}\r\n * fractionGroupSize {number}\r\n * fractionGroupSeparator {string}\r\n * suffix {string}\r\n *\r\n * (The values assigned to the above FORMAT object properties are not checked for validity.)\r\n *\r\n * E.g.\r\n * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })\r\n *\r\n * Ignore properties/parameters set to null or undefined, except for ALPHABET.\r\n *\r\n * Return an object with the properties current values.\r\n */\r\n BigNumber.config = BigNumber.set = function (obj) {\r\n var p, v;\r\n\r\n if (obj != null) {\r\n\r\n if (typeof obj == 'object') {\r\n\r\n // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.\r\n // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) {\r\n v = obj[p];\r\n intCheck(v, 0, MAX, p);\r\n DECIMAL_PLACES = v;\r\n }\r\n\r\n // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.\r\n // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) {\r\n v = obj[p];\r\n intCheck(v, 0, 8, p);\r\n ROUNDING_MODE = v;\r\n }\r\n\r\n // EXPONENTIAL_AT {number|number[]}\r\n // Integer, -MAX to MAX inclusive or\r\n // [integer -MAX to 0 inclusive, 0 to MAX inclusive].\r\n // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) {\r\n v = obj[p];\r\n if (v && v.pop) {\r\n intCheck(v[0], -MAX, 0, p);\r\n intCheck(v[1], 0, MAX, p);\r\n TO_EXP_NEG = v[0];\r\n TO_EXP_POS = v[1];\r\n } else {\r\n intCheck(v, -MAX, MAX, p);\r\n TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v);\r\n }\r\n }\r\n\r\n // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or\r\n // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].\r\n // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}'\r\n if (obj.hasOwnProperty(p = 'RANGE')) {\r\n v = obj[p];\r\n if (v && v.pop) {\r\n intCheck(v[0], -MAX, -1, p);\r\n intCheck(v[1], 1, MAX, p);\r\n MIN_EXP = v[0];\r\n MAX_EXP = v[1];\r\n } else {\r\n intCheck(v, -MAX, MAX, p);\r\n if (v) {\r\n MIN_EXP = -(MAX_EXP = v < 0 ? -v : v);\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' cannot be zero: ' + v);\r\n }\r\n }\r\n }\r\n\r\n // CRYPTO {boolean} true or false.\r\n // '[BigNumber Error] CRYPTO not true or false: {v}'\r\n // '[BigNumber Error] crypto unavailable'\r\n if (obj.hasOwnProperty(p = 'CRYPTO')) {\r\n v = obj[p];\r\n if (v === !!v) {\r\n if (v) {\r\n if (typeof crypto != 'undefined' && crypto &&\r\n (crypto.getRandomValues || crypto.randomBytes)) {\r\n CRYPTO = v;\r\n } else {\r\n CRYPTO = !v;\r\n throw Error\r\n (bignumberError + 'crypto unavailable');\r\n }\r\n } else {\r\n CRYPTO = v;\r\n }\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' not true or false: ' + v);\r\n }\r\n }\r\n\r\n // MODULO_MODE {number} Integer, 0 to 9 inclusive.\r\n // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'MODULO_MODE')) {\r\n v = obj[p];\r\n intCheck(v, 0, 9, p);\r\n MODULO_MODE = v;\r\n }\r\n\r\n // POW_PRECISION {number} Integer, 0 to MAX inclusive.\r\n // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'POW_PRECISION')) {\r\n v = obj[p];\r\n intCheck(v, 0, MAX, p);\r\n POW_PRECISION = v;\r\n }\r\n\r\n // FORMAT {object}\r\n // '[BigNumber Error] FORMAT not an object: {v}'\r\n if (obj.hasOwnProperty(p = 'FORMAT')) {\r\n v = obj[p];\r\n if (typeof v == 'object') FORMAT = v;\r\n else throw Error\r\n (bignumberError + p + ' not an object: ' + v);\r\n }\r\n\r\n // ALPHABET {string}\r\n // '[BigNumber Error] ALPHABET invalid: {v}'\r\n if (obj.hasOwnProperty(p = 'ALPHABET')) {\r\n v = obj[p];\r\n\r\n // Disallow if less than two characters,\r\n // or if it contains '+', '-', '.', whitespace, or a repeated character.\r\n if (typeof v == 'string' && !/^.?$|[+\\-.\\s]|(.).*\\1/.test(v)) {\r\n alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789';\r\n ALPHABET = v;\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' invalid: ' + v);\r\n }\r\n }\r\n\r\n } else {\r\n\r\n // '[BigNumber Error] Object expected: {v}'\r\n throw Error\r\n (bignumberError + 'Object expected: ' + obj);\r\n }\r\n }\r\n\r\n return {\r\n DECIMAL_PLACES: DECIMAL_PLACES,\r\n ROUNDING_MODE: ROUNDING_MODE,\r\n EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS],\r\n RANGE: [MIN_EXP, MAX_EXP],\r\n CRYPTO: CRYPTO,\r\n MODULO_MODE: MODULO_MODE,\r\n POW_PRECISION: POW_PRECISION,\r\n FORMAT: FORMAT,\r\n ALPHABET: ALPHABET\r\n };\r\n };\r\n\r\n\r\n /*\r\n * Return true if v is a BigNumber instance, otherwise return false.\r\n *\r\n * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed.\r\n *\r\n * v {any}\r\n *\r\n * '[BigNumber Error] Invalid BigNumber: {v}'\r\n */\r\n BigNumber.isBigNumber = function (v) {\r\n if (!v || v._isBigNumber !== true) return false;\r\n if (!BigNumber.DEBUG) return true;\r\n\r\n var i, n,\r\n c = v.c,\r\n e = v.e,\r\n s = v.s;\r\n\r\n out: if ({}.toString.call(c) == '[object Array]') {\r\n\r\n if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) {\r\n\r\n // If the first element is zero, the BigNumber value must be zero.\r\n if (c[0] === 0) {\r\n if (e === 0 && c.length === 1) return true;\r\n break out;\r\n }\r\n\r\n // Calculate number of digits that c[0] should have, based on the exponent.\r\n i = (e + 1) % LOG_BASE;\r\n if (i < 1) i += LOG_BASE;\r\n\r\n // Calculate number of digits of c[0].\r\n //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) {\r\n if (String(c[0]).length == i) {\r\n\r\n for (i = 0; i < c.length; i++) {\r\n n = c[i];\r\n if (n < 0 || n >= BASE || n !== mathfloor(n)) break out;\r\n }\r\n\r\n // Last element cannot be zero, unless it is the only element.\r\n if (n !== 0) return true;\r\n }\r\n }\r\n\r\n // Infinity/NaN\r\n } else if (c === null && e === null && (s === null || s === 1 || s === -1)) {\r\n return true;\r\n }\r\n\r\n throw Error\r\n (bignumberError + 'Invalid BigNumber: ' + v);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the maximum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.maximum = BigNumber.max = function () {\r\n return maxOrMin(arguments, -1);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the minimum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.minimum = BigNumber.min = function () {\r\n return maxOrMin(arguments, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,\r\n * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing\r\n * zeros are produced).\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}'\r\n * '[BigNumber Error] crypto unavailable'\r\n */\r\n BigNumber.random = (function () {\r\n var pow2_53 = 0x20000000000000;\r\n\r\n // Return a 53 bit integer n, where 0 <= n < 9007199254740992.\r\n // Check if Math.random() produces more than 32 bits of randomness.\r\n // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.\r\n // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.\r\n var random53bitInt = (Math.random() * pow2_53) & 0x1fffff\r\n ? function () { return mathfloor(Math.random() * pow2_53); }\r\n : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +\r\n (Math.random() * 0x800000 | 0); };\r\n\r\n return function (dp) {\r\n var a, b, e, k, v,\r\n i = 0,\r\n c = [],\r\n rand = new BigNumber(ONE);\r\n\r\n if (dp == null) dp = DECIMAL_PLACES;\r\n else intCheck(dp, 0, MAX);\r\n\r\n k = mathceil(dp / LOG_BASE);\r\n\r\n if (CRYPTO) {\r\n\r\n // Browsers supporting crypto.getRandomValues.\r\n if (crypto.getRandomValues) {\r\n\r\n a = crypto.getRandomValues(new Uint32Array(k *= 2));\r\n\r\n for (; i < k;) {\r\n\r\n // 53 bits:\r\n // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)\r\n // 11111 11111111 11111111 11111111 11100000 00000000 00000000\r\n // ((Math.pow(2, 32) - 1) >>> 11).toString(2)\r\n // 11111 11111111 11111111\r\n // 0x20000 is 2^21.\r\n v = a[i] * 0x20000 + (a[i + 1] >>> 11);\r\n\r\n // Rejection sampling:\r\n // 0 <= v < 9007199254740992\r\n // Probability that v >= 9e15, is\r\n // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251\r\n if (v >= 9e15) {\r\n b = crypto.getRandomValues(new Uint32Array(2));\r\n a[i] = b[0];\r\n a[i + 1] = b[1];\r\n } else {\r\n\r\n // 0 <= v <= 8999999999999999\r\n // 0 <= (v % 1e14) <= 99999999999999\r\n c.push(v % 1e14);\r\n i += 2;\r\n }\r\n }\r\n i = k / 2;\r\n\r\n // Node.js supporting crypto.randomBytes.\r\n } else if (crypto.randomBytes) {\r\n\r\n // buffer\r\n a = crypto.randomBytes(k *= 7);\r\n\r\n for (; i < k;) {\r\n\r\n // 0x1000000000000 is 2^48, 0x10000000000 is 2^40\r\n // 0x100000000 is 2^32, 0x1000000 is 2^24\r\n // 11111 11111111 11111111 11111111 11111111 11111111 11111111\r\n // 0 <= v < 9007199254740992\r\n v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) +\r\n (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) +\r\n (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6];\r\n\r\n if (v >= 9e15) {\r\n crypto.randomBytes(7).copy(a, i);\r\n } else {\r\n\r\n // 0 <= (v % 1e14) <= 99999999999999\r\n c.push(v % 1e14);\r\n i += 7;\r\n }\r\n }\r\n i = k / 7;\r\n } else {\r\n CRYPTO = false;\r\n throw Error\r\n (bignumberError + 'crypto unavailable');\r\n }\r\n }\r\n\r\n // Use Math.random.\r\n if (!CRYPTO) {\r\n\r\n for (; i < k;) {\r\n v = random53bitInt();\r\n if (v < 9e15) c[i++] = v % 1e14;\r\n }\r\n }\r\n\r\n k = c[--i];\r\n dp %= LOG_BASE;\r\n\r\n // Convert trailing digits to zeros according to dp.\r\n if (k && dp) {\r\n v = POWS_TEN[LOG_BASE - dp];\r\n c[i] = mathfloor(k / v) * v;\r\n }\r\n\r\n // Remove trailing elements which are zero.\r\n for (; c[i] === 0; c.pop(), i--);\r\n\r\n // Zero?\r\n if (i < 0) {\r\n c = [e = 0];\r\n } else {\r\n\r\n // Remove leading elements which are zero and adjust exponent accordingly.\r\n for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);\r\n\r\n // Count the digits of the first element of c to determine leading zeros, and...\r\n for (i = 1, v = c[0]; v >= 10; v /= 10, i++);\r\n\r\n // adjust the exponent accordingly.\r\n if (i < LOG_BASE) e -= LOG_BASE - i;\r\n }\r\n\r\n rand.e = e;\r\n rand.c = c;\r\n return rand;\r\n };\r\n })();\r\n\r\n\r\n /*\r\n * Return a BigNumber whose value is the sum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.sum = function () {\r\n var i = 1,\r\n args = arguments,\r\n sum = new BigNumber(args[0]);\r\n for (; i < args.length;) sum = sum.plus(args[i++]);\r\n return sum;\r\n };\r\n\r\n\r\n // PRIVATE FUNCTIONS\r\n\r\n\r\n // Called by BigNumber and BigNumber.prototype.toString.\r\n convertBase = (function () {\r\n var decimal = '0123456789';\r\n\r\n /*\r\n * Convert string of baseIn to an array of numbers of baseOut.\r\n * Eg. toBaseOut('255', 10, 16) returns [15, 15].\r\n * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5].\r\n */\r\n function toBaseOut(str, baseIn, baseOut, alphabet) {\r\n var j,\r\n arr = [0],\r\n arrL,\r\n i = 0,\r\n len = str.length;\r\n\r\n for (; i < len;) {\r\n for (arrL = arr.length; arrL--; arr[arrL] *= baseIn);\r\n\r\n arr[0] += alphabet.indexOf(str.charAt(i++));\r\n\r\n for (j = 0; j < arr.length; j++) {\r\n\r\n if (arr[j] > baseOut - 1) {\r\n if (arr[j + 1] == null) arr[j + 1] = 0;\r\n arr[j + 1] += arr[j] / baseOut | 0;\r\n arr[j] %= baseOut;\r\n }\r\n }\r\n }\r\n\r\n return arr.reverse();\r\n }\r\n\r\n // Convert a numeric string of baseIn to a numeric string of baseOut.\r\n // If the caller is toString, we are converting from base 10 to baseOut.\r\n // If the caller is BigNumber, we are converting from baseIn to base 10.\r\n return function (str, baseIn, baseOut, sign, callerIsToString) {\r\n var alphabet, d, e, k, r, x, xc, y,\r\n i = str.indexOf('.'),\r\n dp = DECIMAL_PLACES,\r\n rm = ROUNDING_MODE;\r\n\r\n // Non-integer.\r\n if (i >= 0) {\r\n k = POW_PRECISION;\r\n\r\n // Unlimited precision.\r\n POW_PRECISION = 0;\r\n str = str.replace('.', '');\r\n y = new BigNumber(baseIn);\r\n x = y.pow(str.length - i);\r\n POW_PRECISION = k;\r\n\r\n // Convert str as if an integer, then restore the fraction part by dividing the\r\n // result by its base raised to a power.\r\n\r\n y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'),\r\n 10, baseOut, decimal);\r\n y.e = y.c.length;\r\n }\r\n\r\n // Convert the number as integer.\r\n\r\n xc = toBaseOut(str, baseIn, baseOut, callerIsToString\r\n ? (alphabet = ALPHABET, decimal)\r\n : (alphabet = decimal, ALPHABET));\r\n\r\n // xc now represents str as an integer and converted to baseOut. e is the exponent.\r\n e = k = xc.length;\r\n\r\n // Remove trailing zeros.\r\n for (; xc[--k] == 0; xc.pop());\r\n\r\n // Zero?\r\n if (!xc[0]) return alphabet.charAt(0);\r\n\r\n // Does str represent an integer? If so, no need for the division.\r\n if (i < 0) {\r\n --e;\r\n } else {\r\n x.c = xc;\r\n x.e = e;\r\n\r\n // The sign is needed for correct rounding.\r\n x.s = sign;\r\n x = div(x, y, dp, rm, baseOut);\r\n xc = x.c;\r\n r = x.r;\r\n e = x.e;\r\n }\r\n\r\n // xc now represents str converted to baseOut.\r\n\r\n // The index of the rounding digit.\r\n d = e + dp + 1;\r\n\r\n // The rounding digit: the digit to the right of the digit that may be rounded up.\r\n i = xc[d];\r\n\r\n // Look at the rounding digits and mode to determine whether to round up.\r\n\r\n k = baseOut / 2;\r\n r = r || d < 0 || xc[d + 1] != null;\r\n\r\n r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n\r\n // If the index of the rounding digit is not greater than zero, or xc represents\r\n // zero, then the result of the base conversion is zero or, if rounding up, a value\r\n // such as 0.00001.\r\n if (d < 1 || !xc[0]) {\r\n\r\n // 1^-dp or 0\r\n str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0);\r\n } else {\r\n\r\n // Truncate xc to the required number of decimal places.\r\n xc.length = d;\r\n\r\n // Round up?\r\n if (r) {\r\n\r\n // Rounding up may mean the previous digit has to be rounded up and so on.\r\n for (--baseOut; ++xc[--d] > baseOut;) {\r\n xc[d] = 0;\r\n\r\n if (!d) {\r\n ++e;\r\n xc = [1].concat(xc);\r\n }\r\n }\r\n }\r\n\r\n // Determine trailing zeros.\r\n for (k = xc.length; !xc[--k];);\r\n\r\n // E.g. [4, 11, 15] becomes 4bf.\r\n for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++]));\r\n\r\n // Add leading zeros, decimal point and trailing zeros as required.\r\n str = toFixedPoint(str, e, alphabet.charAt(0));\r\n }\r\n\r\n // The caller will add the sign.\r\n return str;\r\n };\r\n })();\r\n\r\n\r\n // Perform division in the specified base. Called by div and convertBase.\r\n div = (function () {\r\n\r\n // Assume non-zero x and k.\r\n function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }\r\n\r\n function compare(a, b, aL, bL) {\r\n var i, cmp;\r\n\r\n if (aL != bL) {\r\n cmp = aL > bL ? 1 : -1;\r\n } else {\r\n\r\n for (i = cmp = 0; i < aL; i++) {\r\n\r\n if (a[i] != b[i]) {\r\n cmp = a[i] > b[i] ? 1 : -1;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n return cmp;\r\n }\r\n\r\n function subtract(a, b, aL, base) {\r\n var i = 0;\r\n\r\n // Subtract b from a.\r\n for (; aL--;) {\r\n a[aL] -= i;\r\n i = a[aL] < b[aL] ? 1 : 0;\r\n a[aL] = i * base + a[aL] - b[aL];\r\n }\r\n\r\n // Remove leading zeros.\r\n for (; !a[0] && a.length > 1; a.splice(0, 1));\r\n }\r\n\r\n // x: dividend, y: divisor.\r\n return function (x, y, dp, rm, base) {\r\n var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,\r\n yL, yz,\r\n s = x.s == y.s ? 1 : -1,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n // Either NaN, Infinity or 0?\r\n if (!xc || !xc[0] || !yc || !yc[0]) {\r\n\r\n return new BigNumber(\r\n\r\n // Return NaN if either NaN, or both Infinity or 0.\r\n !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN :\r\n\r\n // Return \u00B10 if x is \u00B10 or y is \u00B1Infinity, or return \u00B1Infinity as y is \u00B10.\r\n xc && xc[0] == 0 || !yc ? s * 0 : s / 0\r\n );\r\n }\r\n\r\n q = new BigNumber(s);\r\n qc = q.c = [];\r\n e = x.e - y.e;\r\n s = dp + e + 1;\r\n\r\n if (!base) {\r\n base = BASE;\r\n e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE);\r\n s = s / LOG_BASE | 0;\r\n }\r\n\r\n // Result exponent may be one less then the current value of e.\r\n // The coefficients of the BigNumbers from convertBase may have trailing zeros.\r\n for (i = 0; yc[i] == (xc[i] || 0); i++);\r\n\r\n if (yc[i] > (xc[i] || 0)) e--;\r\n\r\n if (s < 0) {\r\n qc.push(1);\r\n more = true;\r\n } else {\r\n xL = xc.length;\r\n yL = yc.length;\r\n i = 0;\r\n s += 2;\r\n\r\n // Normalise xc and yc so highest order digit of yc is >= base / 2.\r\n\r\n n = mathfloor(base / (yc[0] + 1));\r\n\r\n // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1.\r\n // if (n > 1 || n++ == 1 && yc[0] < base / 2) {\r\n if (n > 1) {\r\n yc = multiply(yc, n, base);\r\n xc = multiply(xc, n, base);\r\n yL = yc.length;\r\n xL = xc.length;\r\n }\r\n\r\n xi = yL;\r\n rem = xc.slice(0, yL);\r\n remL = rem.length;\r\n\r\n // Add zeros to make remainder as long as divisor.\r\n for (; remL < yL; rem[remL++] = 0);\r\n yz = yc.slice();\r\n yz = [0].concat(yz);\r\n yc0 = yc[0];\r\n if (yc[1] >= base / 2) yc0++;\r\n // Not necessary, but to prevent trial digit n > base, when using base 3.\r\n // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15;\r\n\r\n do {\r\n n = 0;\r\n\r\n // Compare divisor and remainder.\r\n cmp = compare(yc, rem, yL, remL);\r\n\r\n // If divisor < remainder.\r\n if (cmp < 0) {\r\n\r\n // Calculate trial digit, n.\r\n\r\n rem0 = rem[0];\r\n if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);\r\n\r\n // n is how many times the divisor goes into the current remainder.\r\n n = mathfloor(rem0 / yc0);\r\n\r\n // Algorithm:\r\n // product = divisor multiplied by trial digit (n).\r\n // Compare product and remainder.\r\n // If product is greater than remainder:\r\n // Subtract divisor from product, decrement trial digit.\r\n // Subtract product from remainder.\r\n // If product was less than remainder at the last compare:\r\n // Compare new remainder and divisor.\r\n // If remainder is greater than divisor:\r\n // Subtract divisor from remainder, increment trial digit.\r\n\r\n if (n > 1) {\r\n\r\n // n may be > base only when base is 3.\r\n if (n >= base) n = base - 1;\r\n\r\n // product = divisor * trial digit.\r\n prod = multiply(yc, n, base);\r\n prodL = prod.length;\r\n remL = rem.length;\r\n\r\n // Compare product and remainder.\r\n // If product > remainder then trial digit n too high.\r\n // n is 1 too high about 5% of the time, and is not known to have\r\n // ever been more than 1 too high.\r\n while (compare(prod, rem, prodL, remL) == 1) {\r\n n--;\r\n\r\n // Subtract divisor from product.\r\n subtract(prod, yL < prodL ? yz : yc, prodL, base);\r\n prodL = prod.length;\r\n cmp = 1;\r\n }\r\n } else {\r\n\r\n // n is 0 or 1, cmp is -1.\r\n // If n is 0, there is no need to compare yc and rem again below,\r\n // so change cmp to 1 to avoid it.\r\n // If n is 1, leave cmp as -1, so yc and rem are compared again.\r\n if (n == 0) {\r\n\r\n // divisor < remainder, so n must be at least 1.\r\n cmp = n = 1;\r\n }\r\n\r\n // product = divisor\r\n prod = yc.slice();\r\n prodL = prod.length;\r\n }\r\n\r\n if (prodL < remL) prod = [0].concat(prod);\r\n\r\n // Subtract product from remainder.\r\n subtract(rem, prod, remL, base);\r\n remL = rem.length;\r\n\r\n // If product was < remainder.\r\n if (cmp == -1) {\r\n\r\n // Compare divisor and new remainder.\r\n // If divisor < new remainder, subtract divisor from remainder.\r\n // Trial digit n too low.\r\n // n is 1 too low about 5% of the time, and very rarely 2 too low.\r\n while (compare(yc, rem, yL, remL) < 1) {\r\n n++;\r\n\r\n // Subtract divisor from remainder.\r\n subtract(rem, yL < remL ? yz : yc, remL, base);\r\n remL = rem.length;\r\n }\r\n }\r\n } else if (cmp === 0) {\r\n n++;\r\n rem = [0];\r\n } // else cmp === 1 and n will be 0\r\n\r\n // Add the next digit, n, to the result array.\r\n qc[i++] = n;\r\n\r\n // Update the remainder.\r\n if (rem[0]) {\r\n rem[remL++] = xc[xi] || 0;\r\n } else {\r\n rem = [xc[xi]];\r\n remL = 1;\r\n }\r\n } while ((xi++ < xL || rem[0] != null) && s--);\r\n\r\n more = rem[0] != null;\r\n\r\n // Leading zero?\r\n if (!qc[0]) qc.splice(0, 1);\r\n }\r\n\r\n if (base == BASE) {\r\n\r\n // To calculate q.e, first get the number of digits of qc[0].\r\n for (i = 1, s = qc[0]; s >= 10; s /= 10, i++);\r\n\r\n round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more);\r\n\r\n // Caller is convertBase.\r\n } else {\r\n q.e = e;\r\n q.r = +more;\r\n }\r\n\r\n return q;\r\n };\r\n })();\r\n\r\n\r\n /*\r\n * Return a string representing the value of BigNumber n in fixed-point or exponential\r\n * notation rounded to the specified decimal places or significant digits.\r\n *\r\n * n: a BigNumber.\r\n * i: the index of the last digit required (i.e. the digit that may be rounded up).\r\n * rm: the rounding mode.\r\n * id: 1 (toExponential) or 2 (toPrecision).\r\n */\r\n function format(n, i, rm, id) {\r\n var c0, e, ne, len, str;\r\n\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n if (!n.c) return n.toString();\r\n\r\n c0 = n.c[0];\r\n ne = n.e;\r\n\r\n if (i == null) {\r\n str = coeffToString(n.c);\r\n str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS)\r\n ? toExponential(str, ne)\r\n : toFixedPoint(str, ne, '0');\r\n } else {\r\n n = round(new BigNumber(n), i, rm);\r\n\r\n // n.e may have changed if the value was rounded up.\r\n e = n.e;\r\n\r\n str = coeffToString(n.c);\r\n len = str.length;\r\n\r\n // toPrecision returns exponential notation if the number of significant digits\r\n // specified is less than the number of digits necessary to represent the integer\r\n // part of the value in fixed-point notation.\r\n\r\n // Exponential notation.\r\n if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) {\r\n\r\n // Append zeros?\r\n for (; len < i; str += '0', len++);\r\n str = toExponential(str, e);\r\n\r\n // Fixed-point notation.\r\n } else {\r\n i -= ne + (id === 2 && e > ne);\r\n str = toFixedPoint(str, e, '0');\r\n\r\n // Append zeros?\r\n if (e + 1 > len) {\r\n if (--i > 0) for (str += '.'; i--; str += '0');\r\n } else {\r\n i += e - len;\r\n if (i > 0) {\r\n if (e + 1 == len) str += '.';\r\n for (; i--; str += '0');\r\n }\r\n }\r\n }\r\n }\r\n\r\n return n.s < 0 && c0 ? '-' + str : str;\r\n }\r\n\r\n\r\n // Handle BigNumber.max and BigNumber.min.\r\n // If any number is NaN, return NaN.\r\n function maxOrMin(args, n) {\r\n var k, y,\r\n i = 1,\r\n x = new BigNumber(args[0]);\r\n\r\n for (; i < args.length; i++) {\r\n y = new BigNumber(args[i]);\r\n if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) {\r\n x = y;\r\n }\r\n }\r\n\r\n return x;\r\n }\r\n\r\n\r\n /*\r\n * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.\r\n * Called by minus, plus and times.\r\n */\r\n function normalise(n, c, e) {\r\n var i = 1,\r\n j = c.length;\r\n\r\n // Remove trailing zeros.\r\n for (; !c[--j]; c.pop());\r\n\r\n // Calculate the base 10 exponent. First get the number of digits of c[0].\r\n for (j = c[0]; j >= 10; j /= 10, i++);\r\n\r\n // Overflow?\r\n if ((e = i + e * LOG_BASE - 1) > MAX_EXP) {\r\n\r\n // Infinity.\r\n n.c = n.e = null;\r\n\r\n // Underflow?\r\n } else if (e < MIN_EXP) {\r\n\r\n // Zero.\r\n n.c = [n.e = 0];\r\n } else {\r\n n.e = e;\r\n n.c = c;\r\n }\r\n\r\n return n;\r\n }\r\n\r\n\r\n // Handle values that fail the validity test in BigNumber.\r\n parseNumeric = (function () {\r\n var basePrefix = /^(-?)0([xbo])(?=\\w[\\w.]*$)/i,\r\n dotAfter = /^([^.]+)\\.$/,\r\n dotBefore = /^\\.([^.]+)$/,\r\n isInfinityOrNaN = /^-?(Infinity|NaN)$/,\r\n whitespaceOrPlus = /^\\s*\\+(?=[\\w.])|^\\s+|\\s+$/g;\r\n\r\n return function (x, str, isNum, b) {\r\n var base,\r\n s = isNum ? str : str.replace(whitespaceOrPlus, '');\r\n\r\n // No exception on \u00B1Infinity or NaN.\r\n if (isInfinityOrNaN.test(s)) {\r\n x.s = isNaN(s) ? null : s < 0 ? -1 : 1;\r\n } else {\r\n if (!isNum) {\r\n\r\n // basePrefix = /^(-?)0([xbo])(?=\\w[\\w.]*$)/i\r\n s = s.replace(basePrefix, function (m, p1, p2) {\r\n base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8;\r\n return !b || b == base ? p1 : m;\r\n });\r\n\r\n if (b) {\r\n base = b;\r\n\r\n // E.g. '1.' to '1', '.1' to '0.1'\r\n s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1');\r\n }\r\n\r\n if (str != s) return new BigNumber(s, base);\r\n }\r\n\r\n // '[BigNumber Error] Not a number: {n}'\r\n // '[BigNumber Error] Not a base {b} number: {n}'\r\n if (BigNumber.DEBUG) {\r\n throw Error\r\n (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str);\r\n }\r\n\r\n // NaN\r\n x.s = null;\r\n }\r\n\r\n x.c = x.e = null;\r\n }\r\n })();\r\n\r\n\r\n /*\r\n * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.\r\n * If r is truthy, it is known that there are more digits after the rounding digit.\r\n */\r\n function round(x, sd, rm, r) {\r\n var d, i, j, k, n, ni, rd,\r\n xc = x.c,\r\n pows10 = POWS_TEN;\r\n\r\n // if x is not Infinity or NaN...\r\n if (xc) {\r\n\r\n // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.\r\n // n is a base 1e14 number, the value of the element of array x.c containing rd.\r\n // ni is the index of n within x.c.\r\n // d is the number of digits of n.\r\n // i is the index of rd within n including leading zeros.\r\n // j is the actual index of rd within n (if < 0, rd is a leading zero).\r\n out: {\r\n\r\n // Get the number of digits of the first element of xc.\r\n for (d = 1, k = xc[0]; k >= 10; k /= 10, d++);\r\n i = sd - d;\r\n\r\n // If the rounding digit is in the first element of xc...\r\n if (i < 0) {\r\n i += LOG_BASE;\r\n j = sd;\r\n n = xc[ni = 0];\r\n\r\n // Get the rounding digit at index j of n.\r\n rd = mathfloor(n / pows10[d - j - 1] % 10);\r\n } else {\r\n ni = mathceil((i + 1) / LOG_BASE);\r\n\r\n if (ni >= xc.length) {\r\n\r\n if (r) {\r\n\r\n // Needed by sqrt.\r\n for (; xc.length <= ni; xc.push(0));\r\n n = rd = 0;\r\n d = 1;\r\n i %= LOG_BASE;\r\n j = i - LOG_BASE + 1;\r\n } else {\r\n break out;\r\n }\r\n } else {\r\n n = k = xc[ni];\r\n\r\n // Get the number of digits of n.\r\n for (d = 1; k >= 10; k /= 10, d++);\r\n\r\n // Get the index of rd within n.\r\n i %= LOG_BASE;\r\n\r\n // Get the index of rd within n, adjusted for leading zeros.\r\n // The number of leading zeros of n is given by LOG_BASE - d.\r\n j = i - LOG_BASE + d;\r\n\r\n // Get the rounding digit at index j of n.\r\n rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10);\r\n }\r\n }\r\n\r\n r = r || sd < 0 ||\r\n\r\n // Are there any non-zero digits after the rounding digit?\r\n // The expression n % pows10[d - j - 1] returns all digits of n to the right\r\n // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.\r\n xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]);\r\n\r\n r = rm < 4\r\n ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 &&\r\n\r\n // Check whether the digit to the left of the rounding digit is odd.\r\n ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n\r\n if (sd < 1 || !xc[0]) {\r\n xc.length = 0;\r\n\r\n if (r) {\r\n\r\n // Convert sd to decimal places.\r\n sd -= x.e + 1;\r\n\r\n // 1, 0.1, 0.01, 0.001, 0.0001 etc.\r\n xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE];\r\n x.e = -sd || 0;\r\n } else {\r\n\r\n // Zero.\r\n xc[0] = x.e = 0;\r\n }\r\n\r\n return x;\r\n }\r\n\r\n // Remove excess digits.\r\n if (i == 0) {\r\n xc.length = ni;\r\n k = 1;\r\n ni--;\r\n } else {\r\n xc.length = ni + 1;\r\n k = pows10[LOG_BASE - i];\r\n\r\n // E.g. 56700 becomes 56000 if 7 is the rounding digit.\r\n // j > 0 means i > number of leading zeros of n.\r\n xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0;\r\n }\r\n\r\n // Round up?\r\n if (r) {\r\n\r\n for (; ;) {\r\n\r\n // If the digit to be rounded up is in the first element of xc...\r\n if (ni == 0) {\r\n\r\n // i will be the length of xc[0] before k is added.\r\n for (i = 1, j = xc[0]; j >= 10; j /= 10, i++);\r\n j = xc[0] += k;\r\n for (k = 1; j >= 10; j /= 10, k++);\r\n\r\n // if i != k the length has increased.\r\n if (i != k) {\r\n x.e++;\r\n if (xc[0] == BASE) xc[0] = 1;\r\n }\r\n\r\n break;\r\n } else {\r\n xc[ni] += k;\r\n if (xc[ni] != BASE) break;\r\n xc[ni--] = 0;\r\n k = 1;\r\n }\r\n }\r\n }\r\n\r\n // Remove trailing zeros.\r\n for (i = xc.length; xc[--i] === 0; xc.pop());\r\n }\r\n\r\n // Overflow? Infinity.\r\n if (x.e > MAX_EXP) {\r\n x.c = x.e = null;\r\n\r\n // Underflow? Zero.\r\n } else if (x.e < MIN_EXP) {\r\n x.c = [x.e = 0];\r\n }\r\n }\r\n\r\n return x;\r\n }\r\n\r\n\r\n function valueOf(n) {\r\n var str,\r\n e = n.e;\r\n\r\n if (e === null) return n.toString();\r\n\r\n str = coeffToString(n.c);\r\n\r\n str = e <= TO_EXP_NEG || e >= TO_EXP_POS\r\n ? toExponential(str, e)\r\n : toFixedPoint(str, e, '0');\r\n\r\n return n.s < 0 ? '-' + str : str;\r\n }\r\n\r\n\r\n // PROTOTYPE/INSTANCE METHODS\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the absolute value of this BigNumber.\r\n */\r\n P.absoluteValue = P.abs = function () {\r\n var x = new BigNumber(this);\r\n if (x.s < 0) x.s = 1;\r\n return x;\r\n };\r\n\r\n\r\n /*\r\n * Return\r\n * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),\r\n * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),\r\n * 0 if they have the same value,\r\n * or null if the value of either is NaN.\r\n */\r\n P.comparedTo = function (y, b) {\r\n return compare(this, new BigNumber(y, b));\r\n };\r\n\r\n\r\n /*\r\n * If dp is undefined or null or true or false, return the number of decimal places of the\r\n * value of this BigNumber, or null if the value of this BigNumber is \u00B1Infinity or NaN.\r\n *\r\n * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this\r\n * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or\r\n * ROUNDING_MODE if rm is omitted.\r\n *\r\n * [dp] {number} Decimal places: integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.decimalPlaces = P.dp = function (dp, rm) {\r\n var c, n, v,\r\n x = this;\r\n\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n return round(new BigNumber(x), dp + x.e + 1, rm);\r\n }\r\n\r\n if (!(c = x.c)) return null;\r\n n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE;\r\n\r\n // Subtract the number of trailing zeros of the last number.\r\n if (v = c[v]) for (; v % 10 == 0; v /= 10, n--);\r\n if (n < 0) n = 0;\r\n\r\n return n;\r\n };\r\n\r\n\r\n /*\r\n * n / 0 = I\r\n * n / N = N\r\n * n / I = 0\r\n * 0 / n = 0\r\n * 0 / 0 = N\r\n * 0 / N = N\r\n * 0 / I = 0\r\n * N / n = N\r\n * N / 0 = N\r\n * N / N = N\r\n * N / I = N\r\n * I / n = I\r\n * I / 0 = I\r\n * I / N = N\r\n * I / I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber divided by the value of\r\n * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.\r\n */\r\n P.dividedBy = P.div = function (y, b) {\r\n return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the integer part of dividing the value of this\r\n * BigNumber by the value of BigNumber(y, b).\r\n */\r\n P.dividedToIntegerBy = P.idiv = function (y, b) {\r\n return div(this, new BigNumber(y, b), 0, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a BigNumber whose value is the value of this BigNumber exponentiated by n.\r\n *\r\n * If m is present, return the result modulo m.\r\n * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.\r\n * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE.\r\n *\r\n * The modular power operation works efficiently when x, n, and m are integers, otherwise it\r\n * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0.\r\n *\r\n * n {number|string|BigNumber} The exponent. An integer.\r\n * [m] {number|string|BigNumber} The modulus.\r\n *\r\n * '[BigNumber Error] Exponent not an integer: {n}'\r\n */\r\n P.exponentiatedBy = P.pow = function (n, m) {\r\n var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y,\r\n x = this;\r\n\r\n n = new BigNumber(n);\r\n\r\n // Allow NaN and \u00B1Infinity, but not other non-integers.\r\n if (n.c && !n.isInteger()) {\r\n throw Error\r\n (bignumberError + 'Exponent not an integer: ' + valueOf(n));\r\n }\r\n\r\n if (m != null) m = new BigNumber(m);\r\n\r\n // Exponent of MAX_SAFE_INTEGER is 15.\r\n nIsBig = n.e > 14;\r\n\r\n // If x is NaN, \u00B1Infinity, \u00B10 or \u00B11, or n is \u00B1Infinity, NaN or \u00B10.\r\n if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) {\r\n\r\n // The sign of the result of pow when x is negative depends on the evenness of n.\r\n // If +n overflows to \u00B1Infinity, the evenness of n would be not be known.\r\n y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n)));\r\n return m ? y.mod(m) : y;\r\n }\r\n\r\n nIsNeg = n.s < 0;\r\n\r\n if (m) {\r\n\r\n // x % m returns NaN if abs(m) is zero, or m is NaN.\r\n if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN);\r\n\r\n isModExp = !nIsNeg && x.isInteger() && m.isInteger();\r\n\r\n if (isModExp) x = x.mod(m);\r\n\r\n // Overflow to \u00B1Infinity: >=2**1e10 or >=1.0000024**1e15.\r\n // Underflow to \u00B10: <=0.79**1e10 or <=0.9999975**1e15.\r\n } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0\r\n // [1, 240000000]\r\n ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7\r\n // [80000000000000] [99999750000000]\r\n : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) {\r\n\r\n // If x is negative and n is odd, k = -0, else k = 0.\r\n k = x.s < 0 && isOdd(n) ? -0 : 0;\r\n\r\n // If x >= 1, k = \u00B1Infinity.\r\n if (x.e > -1) k = 1 / k;\r\n\r\n // If n is negative return \u00B10, else return \u00B1Infinity.\r\n return new BigNumber(nIsNeg ? 1 / k : k);\r\n\r\n } else if (POW_PRECISION) {\r\n\r\n // Truncating each coefficient array to a length of k after each multiplication\r\n // equates to truncating significant digits to POW_PRECISION + [28, 41],\r\n // i.e. there will be a minimum of 28 guard digits retained.\r\n k = mathceil(POW_PRECISION / LOG_BASE + 2);\r\n }\r\n\r\n if (nIsBig) {\r\n half = new BigNumber(0.5);\r\n if (nIsNeg) n.s = 1;\r\n nIsOdd = isOdd(n);\r\n } else {\r\n i = Math.abs(+valueOf(n));\r\n nIsOdd = i % 2;\r\n }\r\n\r\n y = new BigNumber(ONE);\r\n\r\n // Performs 54 loop iterations for n of 9007199254740991.\r\n for (; ;) {\r\n\r\n if (nIsOdd) {\r\n y = y.times(x);\r\n if (!y.c) break;\r\n\r\n if (k) {\r\n if (y.c.length > k) y.c.length = k;\r\n } else if (isModExp) {\r\n y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m));\r\n }\r\n }\r\n\r\n if (i) {\r\n i = mathfloor(i / 2);\r\n if (i === 0) break;\r\n nIsOdd = i % 2;\r\n } else {\r\n n = n.times(half);\r\n round(n, n.e + 1, 1);\r\n\r\n if (n.e > 14) {\r\n nIsOdd = isOdd(n);\r\n } else {\r\n i = +valueOf(n);\r\n if (i === 0) break;\r\n nIsOdd = i % 2;\r\n }\r\n }\r\n\r\n x = x.times(x);\r\n\r\n if (k) {\r\n if (x.c && x.c.length > k) x.c.length = k;\r\n } else if (isModExp) {\r\n x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m));\r\n }\r\n }\r\n\r\n if (isModExp) return y;\r\n if (nIsNeg) y = ONE.div(y);\r\n\r\n return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y;\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer\r\n * using rounding mode rm, or ROUNDING_MODE if rm is omitted.\r\n *\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}'\r\n */\r\n P.integerValue = function (rm) {\r\n var n = new BigNumber(this);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n return round(n, n.e + 1, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isEqualTo = P.eq = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is a finite number, otherwise return false.\r\n */\r\n P.isFinite = function () {\r\n return !!this.c;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isGreaterThan = P.gt = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is greater than or equal to the value of\r\n * BigNumber(y, b), otherwise return false.\r\n */\r\n P.isGreaterThanOrEqualTo = P.gte = function (y, b) {\r\n return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0;\r\n\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is an integer, otherwise return false.\r\n */\r\n P.isInteger = function () {\r\n return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isLessThan = P.lt = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is less than or equal to the value of\r\n * BigNumber(y, b), otherwise return false.\r\n */\r\n P.isLessThanOrEqualTo = P.lte = function (y, b) {\r\n return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is NaN, otherwise return false.\r\n */\r\n P.isNaN = function () {\r\n return !this.s;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is negative, otherwise return false.\r\n */\r\n P.isNegative = function () {\r\n return this.s < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is positive, otherwise return false.\r\n */\r\n P.isPositive = function () {\r\n return this.s > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is 0 or -0, otherwise return false.\r\n */\r\n P.isZero = function () {\r\n return !!this.c && this.c[0] == 0;\r\n };\r\n\r\n\r\n /*\r\n * n - 0 = n\r\n * n - N = N\r\n * n - I = -I\r\n * 0 - n = -n\r\n * 0 - 0 = 0\r\n * 0 - N = N\r\n * 0 - I = -I\r\n * N - n = N\r\n * N - 0 = N\r\n * N - N = N\r\n * N - I = N\r\n * I - n = I\r\n * I - 0 = I\r\n * I - N = N\r\n * I - I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber minus the value of\r\n * BigNumber(y, b).\r\n */\r\n P.minus = function (y, b) {\r\n var i, j, t, xLTy,\r\n x = this,\r\n a = x.s;\r\n\r\n y = new BigNumber(y, b);\r\n b = y.s;\r\n\r\n // Either NaN?\r\n if (!a || !b) return new BigNumber(NaN);\r\n\r\n // Signs differ?\r\n if (a != b) {\r\n y.s = -b;\r\n return x.plus(y);\r\n }\r\n\r\n var xe = x.e / LOG_BASE,\r\n ye = y.e / LOG_BASE,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n if (!xe || !ye) {\r\n\r\n // Either Infinity?\r\n if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN);\r\n\r\n // Either zero?\r\n if (!xc[0] || !yc[0]) {\r\n\r\n // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.\r\n return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x :\r\n\r\n // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity\r\n ROUNDING_MODE == 3 ? -0 : 0);\r\n }\r\n }\r\n\r\n xe = bitFloor(xe);\r\n ye = bitFloor(ye);\r\n xc = xc.slice();\r\n\r\n // Determine which is the bigger number.\r\n if (a = xe - ye) {\r\n\r\n if (xLTy = a < 0) {\r\n a = -a;\r\n t = xc;\r\n } else {\r\n ye = xe;\r\n t = yc;\r\n }\r\n\r\n t.reverse();\r\n\r\n // Prepend zeros to equalise exponents.\r\n for (b = a; b--; t.push(0));\r\n t.reverse();\r\n } else {\r\n\r\n // Exponents equal. Check digit by digit.\r\n j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b;\r\n\r\n for (a = b = 0; b < j; b++) {\r\n\r\n if (xc[b] != yc[b]) {\r\n xLTy = xc[b] < yc[b];\r\n break;\r\n }\r\n }\r\n }\r\n\r\n // x < y? Point xc to the array of the bigger number.\r\n if (xLTy) {\r\n t = xc;\r\n xc = yc;\r\n yc = t;\r\n y.s = -y.s;\r\n }\r\n\r\n b = (j = yc.length) - (i = xc.length);\r\n\r\n // Append zeros to xc if shorter.\r\n // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.\r\n if (b > 0) for (; b--; xc[i++] = 0);\r\n b = BASE - 1;\r\n\r\n // Subtract yc from xc.\r\n for (; j > a;) {\r\n\r\n if (xc[--j] < yc[j]) {\r\n for (i = j; i && !xc[--i]; xc[i] = b);\r\n --xc[i];\r\n xc[j] += BASE;\r\n }\r\n\r\n xc[j] -= yc[j];\r\n }\r\n\r\n // Remove leading zeros and adjust exponent accordingly.\r\n for (; xc[0] == 0; xc.splice(0, 1), --ye);\r\n\r\n // Zero?\r\n if (!xc[0]) {\r\n\r\n // Following IEEE 754 (2008) 6.3,\r\n // n - n = +0 but n - n = -0 when rounding towards -Infinity.\r\n y.s = ROUNDING_MODE == 3 ? -1 : 1;\r\n y.c = [y.e = 0];\r\n return y;\r\n }\r\n\r\n // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity\r\n // for finite x and y.\r\n return normalise(y, xc, ye);\r\n };\r\n\r\n\r\n /*\r\n * n % 0 = N\r\n * n % N = N\r\n * n % I = n\r\n * 0 % n = 0\r\n * -0 % n = -0\r\n * 0 % 0 = N\r\n * 0 % N = N\r\n * 0 % I = 0\r\n * N % n = N\r\n * N % 0 = N\r\n * N % N = N\r\n * N % I = N\r\n * I % n = N\r\n * I % 0 = N\r\n * I % N = N\r\n * I % I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber modulo the value of\r\n * BigNumber(y, b). The result depends on the value of MODULO_MODE.\r\n */\r\n P.modulo = P.mod = function (y, b) {\r\n var q, s,\r\n x = this;\r\n\r\n y = new BigNumber(y, b);\r\n\r\n // Return NaN if x is Infinity or NaN, or y is NaN or zero.\r\n if (!x.c || !y.s || y.c && !y.c[0]) {\r\n return new BigNumber(NaN);\r\n\r\n // Return x if y is Infinity or x is zero.\r\n } else if (!y.c || x.c && !x.c[0]) {\r\n return new BigNumber(x);\r\n }\r\n\r\n if (MODULO_MODE == 9) {\r\n\r\n // Euclidian division: q = sign(y) * floor(x / abs(y))\r\n // r = x - qy where 0 <= r < abs(y)\r\n s = y.s;\r\n y.s = 1;\r\n q = div(x, y, 0, 3);\r\n y.s = s;\r\n q.s *= s;\r\n } else {\r\n q = div(x, y, 0, MODULO_MODE);\r\n }\r\n\r\n y = x.minus(q.times(y));\r\n\r\n // To match JavaScript %, ensure sign of zero is sign of dividend.\r\n if (!y.c[0] && MODULO_MODE == 1) y.s = x.s;\r\n\r\n return y;\r\n };\r\n\r\n\r\n /*\r\n * n * 0 = 0\r\n * n * N = N\r\n * n * I = I\r\n * 0 * n = 0\r\n * 0 * 0 = 0\r\n * 0 * N = N\r\n * 0 * I = N\r\n * N * n = N\r\n * N * 0 = N\r\n * N * N = N\r\n * N * I = N\r\n * I * n = I\r\n * I * 0 = N\r\n * I * N = N\r\n * I * I = I\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value\r\n * of BigNumber(y, b).\r\n */\r\n P.multipliedBy = P.times = function (y, b) {\r\n var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,\r\n base, sqrtBase,\r\n x = this,\r\n xc = x.c,\r\n yc = (y = new BigNumber(y, b)).c;\r\n\r\n // Either NaN, \u00B1Infinity or \u00B10?\r\n if (!xc || !yc || !xc[0] || !yc[0]) {\r\n\r\n // Return NaN if either is NaN, or one is 0 and the other is Infinity.\r\n if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) {\r\n y.c = y.e = y.s = null;\r\n } else {\r\n y.s *= x.s;\r\n\r\n // Return \u00B1Infinity if either is \u00B1Infinity.\r\n if (!xc || !yc) {\r\n y.c = y.e = null;\r\n\r\n // Return \u00B10 if either is \u00B10.\r\n } else {\r\n y.c = [0];\r\n y.e = 0;\r\n }\r\n }\r\n\r\n return y;\r\n }\r\n\r\n e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE);\r\n y.s *= x.s;\r\n xcL = xc.length;\r\n ycL = yc.length;\r\n\r\n // Ensure xc points to longer array and xcL to its length.\r\n if (xcL < ycL) {\r\n zc = xc;\r\n xc = yc;\r\n yc = zc;\r\n i = xcL;\r\n xcL = ycL;\r\n ycL = i;\r\n }\r\n\r\n // Initialise the result array with zeros.\r\n for (i = xcL + ycL, zc = []; i--; zc.push(0));\r\n\r\n base = BASE;\r\n sqrtBase = SQRT_BASE;\r\n\r\n for (i = ycL; --i >= 0;) {\r\n c = 0;\r\n ylo = yc[i] % sqrtBase;\r\n yhi = yc[i] / sqrtBase | 0;\r\n\r\n for (k = xcL, j = i + k; j > i;) {\r\n xlo = xc[--k] % sqrtBase;\r\n xhi = xc[k] / sqrtBase | 0;\r\n m = yhi * xlo + xhi * ylo;\r\n xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c;\r\n c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi;\r\n zc[j--] = xlo % base;\r\n }\r\n\r\n zc[j] = c;\r\n }\r\n\r\n if (c) {\r\n ++e;\r\n } else {\r\n zc.splice(0, 1);\r\n }\r\n\r\n return normalise(y, zc, e);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber negated,\r\n * i.e. multiplied by -1.\r\n */\r\n P.negated = function () {\r\n var x = new BigNumber(this);\r\n x.s = -x.s || null;\r\n return x;\r\n };\r\n\r\n\r\n /*\r\n * n + 0 = n\r\n * n + N = N\r\n * n + I = I\r\n * 0 + n = n\r\n * 0 + 0 = 0\r\n * 0 + N = N\r\n * 0 + I = I\r\n * N + n = N\r\n * N + 0 = N\r\n * N + N = N\r\n * N + I = N\r\n * I + n = I\r\n * I + 0 = I\r\n * I + N = N\r\n * I + I = I\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber plus the value of\r\n * BigNumber(y, b).\r\n */\r\n P.plus = function (y, b) {\r\n var t,\r\n x = this,\r\n a = x.s;\r\n\r\n y = new BigNumber(y, b);\r\n b = y.s;\r\n\r\n // Either NaN?\r\n if (!a || !b) return new BigNumber(NaN);\r\n\r\n // Signs differ?\r\n if (a != b) {\r\n y.s = -b;\r\n return x.minus(y);\r\n }\r\n\r\n var xe = x.e / LOG_BASE,\r\n ye = y.e / LOG_BASE,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n if (!xe || !ye) {\r\n\r\n // Return \u00B1Infinity if either \u00B1Infinity.\r\n if (!xc || !yc) return new BigNumber(a / 0);\r\n\r\n // Either zero?\r\n // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.\r\n if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0);\r\n }\r\n\r\n xe = bitFloor(xe);\r\n ye = bitFloor(ye);\r\n xc = xc.slice();\r\n\r\n // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.\r\n if (a = xe - ye) {\r\n if (a > 0) {\r\n ye = xe;\r\n t = yc;\r\n } else {\r\n a = -a;\r\n t = xc;\r\n }\r\n\r\n t.reverse();\r\n for (; a--; t.push(0));\r\n t.reverse();\r\n }\r\n\r\n a = xc.length;\r\n b = yc.length;\r\n\r\n // Point xc to the longer array, and b to the shorter length.\r\n if (a - b < 0) {\r\n t = yc;\r\n yc = xc;\r\n xc = t;\r\n b = a;\r\n }\r\n\r\n // Only start adding at yc.length - 1 as the further digits of xc can be ignored.\r\n for (a = 0; b;) {\r\n a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0;\r\n xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;\r\n }\r\n\r\n if (a) {\r\n xc = [a].concat(xc);\r\n ++ye;\r\n }\r\n\r\n // No need to check for zero, as +x + +y != 0 && -x + -y != 0\r\n // ye = MAX_EXP + 1 possible\r\n return normalise(y, xc, ye);\r\n };\r\n\r\n\r\n /*\r\n * If sd is undefined or null or true or false, return the number of significant digits of\r\n * the value of this BigNumber, or null if the value of this BigNumber is \u00B1Infinity or NaN.\r\n * If sd is true include integer-part trailing zeros in the count.\r\n *\r\n * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this\r\n * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or\r\n * ROUNDING_MODE if rm is omitted.\r\n *\r\n * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive.\r\n * boolean: whether to count integer-part trailing zeros: true or false.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'\r\n */\r\n P.precision = P.sd = function (sd, rm) {\r\n var c, n, v,\r\n x = this;\r\n\r\n if (sd != null && sd !== !!sd) {\r\n intCheck(sd, 1, MAX);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n return round(new BigNumber(x), sd, rm);\r\n }\r\n\r\n if (!(c = x.c)) return null;\r\n v = c.length - 1;\r\n n = v * LOG_BASE + 1;\r\n\r\n if (v = c[v]) {\r\n\r\n // Subtract the number of trailing zeros of the last element.\r\n for (; v % 10 == 0; v /= 10, n--);\r\n\r\n // Add the number of digits of the first element.\r\n for (v = c[0]; v >= 10; v /= 10, n++);\r\n }\r\n\r\n if (sd && x.e + 1 > n) n = x.e + 1;\r\n\r\n return n;\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber shifted by k places\r\n * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.\r\n *\r\n * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}'\r\n */\r\n P.shiftedBy = function (k) {\r\n intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);\r\n return this.times('1e' + k);\r\n };\r\n\r\n\r\n /*\r\n * sqrt(-n) = N\r\n * sqrt(N) = N\r\n * sqrt(-I) = N\r\n * sqrt(I) = I\r\n * sqrt(0) = 0\r\n * sqrt(-0) = -0\r\n *\r\n * Return a new BigNumber whose value is the square root of the value of this BigNumber,\r\n * rounded according to DECIMAL_PLACES and ROUNDING_MODE.\r\n */\r\n P.squareRoot = P.sqrt = function () {\r\n var m, n, r, rep, t,\r\n x = this,\r\n c = x.c,\r\n s = x.s,\r\n e = x.e,\r\n dp = DECIMAL_PLACES + 4,\r\n half = new BigNumber('0.5');\r\n\r\n // Negative/NaN/Infinity/zero?\r\n if (s !== 1 || !c || !c[0]) {\r\n return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0);\r\n }\r\n\r\n // Initial estimate.\r\n s = Math.sqrt(+valueOf(x));\r\n\r\n // Math.sqrt underflow/overflow?\r\n // Pass x to Math.sqrt as integer, then adjust the exponent of the result.\r\n if (s == 0 || s == 1 / 0) {\r\n n = coeffToString(c);\r\n if ((n.length + e) % 2 == 0) n += '0';\r\n s = Math.sqrt(+n);\r\n e = bitFloor((e + 1) / 2) - (e < 0 || e % 2);\r\n\r\n if (s == 1 / 0) {\r\n n = '5e' + e;\r\n } else {\r\n n = s.toExponential();\r\n n = n.slice(0, n.indexOf('e') + 1) + e;\r\n }\r\n\r\n r = new BigNumber(n);\r\n } else {\r\n r = new BigNumber(s + '');\r\n }\r\n\r\n // Check for zero.\r\n // r could be zero if MIN_EXP is changed after the this value was created.\r\n // This would cause a division by zero (x/t) and hence Infinity below, which would cause\r\n // coeffToString to throw.\r\n if (r.c[0]) {\r\n e = r.e;\r\n s = e + dp;\r\n if (s < 3) s = 0;\r\n\r\n // Newton-Raphson iteration.\r\n for (; ;) {\r\n t = r;\r\n r = half.times(t.plus(div(x, t, dp, 1)));\r\n\r\n if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) {\r\n\r\n // The exponent of r may here be one less than the final result exponent,\r\n // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits\r\n // are indexed correctly.\r\n if (r.e < e) --s;\r\n n = n.slice(s - 3, s + 1);\r\n\r\n // The 4th rounding digit may be in error by -1 so if the 4 rounding digits\r\n // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the\r\n // iteration.\r\n if (n == '9999' || !rep && n == '4999') {\r\n\r\n // On the first iteration only, check to see if rounding up gives the\r\n // exact result as the nines may infinitely repeat.\r\n if (!rep) {\r\n round(t, t.e + DECIMAL_PLACES + 2, 0);\r\n\r\n if (t.times(t).eq(x)) {\r\n r = t;\r\n break;\r\n }\r\n }\r\n\r\n dp += 4;\r\n s += 4;\r\n rep = 1;\r\n } else {\r\n\r\n // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact\r\n // result. If not, then there are further digits and m will be truthy.\r\n if (!+n || !+n.slice(1) && n.charAt(0) == '5') {\r\n\r\n // Truncate to the first rounding digit.\r\n round(r, r.e + DECIMAL_PLACES + 2, 1);\r\n m = !r.times(r).eq(x);\r\n }\r\n\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in exponential notation and\r\n * rounded using ROUNDING_MODE to dp fixed decimal places.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.toExponential = function (dp, rm) {\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n dp++;\r\n }\r\n return format(this, dp, rm, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in fixed-point notation rounding\r\n * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.\r\n *\r\n * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',\r\n * but e.g. (-0.00001).toFixed(0) is '-0'.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.toFixed = function (dp, rm) {\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n dp = dp + this.e + 1;\r\n }\r\n return format(this, dp, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in fixed-point notation rounded\r\n * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties\r\n * of the format or FORMAT object (see BigNumber.set).\r\n *\r\n * The formatting object may contain some or all of the properties shown below.\r\n *\r\n * FORMAT = {\r\n * prefix: '',\r\n * groupSize: 3,\r\n * secondaryGroupSize: 0,\r\n * groupSeparator: ',',\r\n * decimalSeparator: '.',\r\n * fractionGroupSize: 0,\r\n * fractionGroupSeparator: '\\xA0', // non-breaking space\r\n * suffix: ''\r\n * };\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n * [format] {object} Formatting options. See FORMAT pbject above.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n * '[BigNumber Error] Argument not an object: {format}'\r\n */\r\n P.toFormat = function (dp, rm, format) {\r\n var str,\r\n x = this;\r\n\r\n if (format == null) {\r\n if (dp != null && rm && typeof rm == 'object') {\r\n format = rm;\r\n rm = null;\r\n } else if (dp && typeof dp == 'object') {\r\n format = dp;\r\n dp = rm = null;\r\n } else {\r\n format = FORMAT;\r\n }\r\n } else if (typeof format != 'object') {\r\n throw Error\r\n (bignumberError + 'Argument not an object: ' + format);\r\n }\r\n\r\n str = x.toFixed(dp, rm);\r\n\r\n if (x.c) {\r\n var i,\r\n arr = str.split('.'),\r\n g1 = +format.groupSize,\r\n g2 = +format.secondaryGroupSize,\r\n groupSeparator = format.groupSeparator || '',\r\n intPart = arr[0],\r\n fractionPart = arr[1],\r\n isNeg = x.s < 0,\r\n intDigits = isNeg ? intPart.slice(1) : intPart,\r\n len = intDigits.length;\r\n\r\n if (g2) {\r\n i = g1;\r\n g1 = g2;\r\n g2 = i;\r\n len -= i;\r\n }\r\n\r\n if (g1 > 0 && len > 0) {\r\n i = len % g1 || g1;\r\n intPart = intDigits.substr(0, i);\r\n for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1);\r\n if (g2 > 0) intPart += groupSeparator + intDigits.slice(i);\r\n if (isNeg) intPart = '-' + intPart;\r\n }\r\n\r\n str = fractionPart\r\n ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize)\r\n ? fractionPart.replace(new RegExp('\\\\d{' + g2 + '}\\\\B', 'g'),\r\n '$&' + (format.fractionGroupSeparator || ''))\r\n : fractionPart)\r\n : intPart;\r\n }\r\n\r\n return (format.prefix || '') + str + (format.suffix || '');\r\n };\r\n\r\n\r\n /*\r\n * Return an array of two BigNumbers representing the value of this BigNumber as a simple\r\n * fraction with an integer numerator and an integer denominator.\r\n * The denominator will be a positive non-zero value less than or equal to the specified\r\n * maximum denominator. If a maximum denominator is not specified, the denominator will be\r\n * the lowest value necessary to represent the number exactly.\r\n *\r\n * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator.\r\n *\r\n * '[BigNumber Error] Argument {not an integer|out of range} : {md}'\r\n */\r\n P.toFraction = function (md) {\r\n var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s,\r\n x = this,\r\n xc = x.c;\r\n\r\n if (md != null) {\r\n n = new BigNumber(md);\r\n\r\n // Throw if md is less than one or is not an integer, unless it is Infinity.\r\n if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) {\r\n throw Error\r\n (bignumberError + 'Argument ' +\r\n (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n));\r\n }\r\n }\r\n\r\n if (!xc) return new BigNumber(x);\r\n\r\n d = new BigNumber(ONE);\r\n n1 = d0 = new BigNumber(ONE);\r\n d1 = n0 = new BigNumber(ONE);\r\n s = coeffToString(xc);\r\n\r\n // Determine initial denominator.\r\n // d is a power of 10 and the minimum max denominator that specifies the value exactly.\r\n e = d.e = s.length - x.e - 1;\r\n d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp];\r\n md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n;\r\n\r\n exp = MAX_EXP;\r\n MAX_EXP = 1 / 0;\r\n n = new BigNumber(s);\r\n\r\n // n0 = d1 = 0\r\n n0.c[0] = 0;\r\n\r\n for (; ;) {\r\n q = div(n, d, 0, 1);\r\n d2 = d0.plus(q.times(d1));\r\n if (d2.comparedTo(md) == 1) break;\r\n d0 = d1;\r\n d1 = d2;\r\n n1 = n0.plus(q.times(d2 = n1));\r\n n0 = d2;\r\n d = n.minus(q.times(d2 = d));\r\n n = d2;\r\n }\r\n\r\n d2 = div(md.minus(d0), d1, 0, 1);\r\n n0 = n0.plus(d2.times(n1));\r\n d0 = d0.plus(d2.times(d1));\r\n n0.s = n1.s = x.s;\r\n e = e * 2;\r\n\r\n // Determine which fraction is closer to x, n0/d0 or n1/d1\r\n r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo(\r\n div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0];\r\n\r\n MAX_EXP = exp;\r\n\r\n return r;\r\n };\r\n\r\n\r\n /*\r\n * Return the value of this BigNumber converted to a number primitive.\r\n */\r\n P.toNumber = function () {\r\n return +valueOf(this);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber rounded to sd significant digits\r\n * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits\r\n * necessary to represent the integer part of the value in fixed-point notation, then use\r\n * exponential notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'\r\n */\r\n P.toPrecision = function (sd, rm) {\r\n if (sd != null) intCheck(sd, 1, MAX);\r\n return format(this, sd, rm, 2);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in base b, or base 10 if b is\r\n * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and\r\n * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent\r\n * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than\r\n * TO_EXP_NEG, return exponential notation.\r\n *\r\n * [b] {number} Integer, 2 to ALPHABET.length inclusive.\r\n *\r\n * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'\r\n */\r\n P.toString = function (b) {\r\n var str,\r\n n = this,\r\n s = n.s,\r\n e = n.e;\r\n\r\n // Infinity or NaN?\r\n if (e === null) {\r\n if (s) {\r\n str = 'Infinity';\r\n if (s < 0) str = '-' + str;\r\n } else {\r\n str = 'NaN';\r\n }\r\n } else {\r\n if (b == null) {\r\n str = e <= TO_EXP_NEG || e >= TO_EXP_POS\r\n ? toExponential(coeffToString(n.c), e)\r\n : toFixedPoint(coeffToString(n.c), e, '0');\r\n } else if (b === 10 && alphabetHasNormalDecimalDigits) {\r\n n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE);\r\n str = toFixedPoint(coeffToString(n.c), n.e, '0');\r\n } else {\r\n intCheck(b, 2, ALPHABET.length, 'Base');\r\n str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true);\r\n }\r\n\r\n if (s < 0 && n.c[0]) str = '-' + str;\r\n }\r\n\r\n return str;\r\n };\r\n\r\n\r\n /*\r\n * Return as toString, but do not accept a base argument, and include the minus sign for\r\n * negative zero.\r\n */\r\n P.valueOf = P.toJSON = function () {\r\n return valueOf(this);\r\n };\r\n\r\n\r\n P._isBigNumber = true;\r\n\r\n if (configObject != null) BigNumber.set(configObject);\r\n\r\n return BigNumber;\r\n }\r\n\r\n\r\n // PRIVATE HELPER FUNCTIONS\r\n\r\n // These functions don't need access to variables,\r\n // e.g. DECIMAL_PLACES, in the scope of the `clone` function above.\r\n\r\n\r\n function bitFloor(n) {\r\n var i = n | 0;\r\n return n > 0 || n === i ? i : i - 1;\r\n }\r\n\r\n\r\n // Return a coefficient array as a string of base 10 digits.\r\n function coeffToString(a) {\r\n var s, z,\r\n i = 1,\r\n j = a.length,\r\n r = a[0] + '';\r\n\r\n for (; i < j;) {\r\n s = a[i++] + '';\r\n z = LOG_BASE - s.length;\r\n for (; z--; s = '0' + s);\r\n r += s;\r\n }\r\n\r\n // Determine trailing zeros.\r\n for (j = r.length; r.charCodeAt(--j) === 48;);\r\n\r\n return r.slice(0, j + 1 || 1);\r\n }\r\n\r\n\r\n // Compare the value of BigNumbers x and y.\r\n function compare(x, y) {\r\n var a, b,\r\n xc = x.c,\r\n yc = y.c,\r\n i = x.s,\r\n j = y.s,\r\n k = x.e,\r\n l = y.e;\r\n\r\n // Either NaN?\r\n if (!i || !j) return null;\r\n\r\n a = xc && !xc[0];\r\n b = yc && !yc[0];\r\n\r\n // Either zero?\r\n if (a || b) return a ? b ? 0 : -j : i;\r\n\r\n // Signs differ?\r\n if (i != j) return i;\r\n\r\n a = i < 0;\r\n b = k == l;\r\n\r\n // Either Infinity?\r\n if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1;\r\n\r\n // Compare exponents.\r\n if (!b) return k > l ^ a ? 1 : -1;\r\n\r\n j = (k = xc.length) < (l = yc.length) ? k : l;\r\n\r\n // Compare digit by digit.\r\n for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1;\r\n\r\n // Compare lengths.\r\n return k == l ? 0 : k > l ^ a ? 1 : -1;\r\n }\r\n\r\n\r\n /*\r\n * Check that n is a primitive number, an integer, and in range, otherwise throw.\r\n */\r\n function intCheck(n, min, max, name) {\r\n if (n < min || n > max || n !== mathfloor(n)) {\r\n throw Error\r\n (bignumberError + (name || 'Argument') + (typeof n == 'number'\r\n ? n < min || n > max ? ' out of range: ' : ' not an integer: '\r\n : ' not a primitive number: ') + String(n));\r\n }\r\n }\r\n\r\n\r\n // Assumes finite n.\r\n function isOdd(n) {\r\n var k = n.c.length - 1;\r\n return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0;\r\n }\r\n\r\n\r\n function toExponential(str, e) {\r\n return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) +\r\n (e < 0 ? 'e' : 'e+') + e;\r\n }\r\n\r\n\r\n function toFixedPoint(str, e, z) {\r\n var len, zs;\r\n\r\n // Negative exponent?\r\n if (e < 0) {\r\n\r\n // Prepend zeros.\r\n for (zs = z + '.'; ++e; zs += z);\r\n str = zs + str;\r\n\r\n // Positive exponent\r\n } else {\r\n len = str.length;\r\n\r\n // Append zeros.\r\n if (++e > len) {\r\n for (zs = z, e -= len; --e; zs += z);\r\n str += zs;\r\n } else if (e < len) {\r\n str = str.slice(0, e) + '.' + str.slice(e);\r\n }\r\n }\r\n\r\n return str;\r\n }\r\n\r\n\r\n // EXPORT\r\n\r\n\r\n BigNumber = clone();\r\n BigNumber['default'] = BigNumber.BigNumber = BigNumber;\r\n\r\n // AMD.\r\n if (typeof define == 'function' && define.amd) {\r\n define(function () { return BigNumber; });\r\n\r\n // Node.js and other environments that support module.exports.\r\n } else if (typeof module != 'undefined' && module.exports) {\r\n module.exports = BigNumber;\r\n\r\n // Browser.\r\n } else {\r\n if (!globalObject) {\r\n globalObject = typeof self != 'undefined' && self ? self : window;\r\n }\r\n\r\n globalObject.BigNumber = BigNumber;\r\n }\r\n})(this);\r\n", "var BigNumber = require('bignumber.js');\n\n/*\n json2.js\n 2013-05-26\n\n Public Domain.\n\n NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.\n\n See http://www.JSON.org/js.html\n\n\n This code should be minified before deployment.\n See http://javascript.crockford.com/jsmin.html\n\n USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO\n NOT CONTROL.\n\n\n This file creates a global JSON object containing two methods: stringify\n and parse.\n\n JSON.stringify(value, replacer, space)\n value any JavaScript value, usually an object or array.\n\n replacer an optional parameter that determines how object\n values are stringified for objects. It can be a\n function or an array of strings.\n\n space an optional parameter that specifies the indentation\n of nested structures. If it is omitted, the text will\n be packed without extra whitespace. If it is a number,\n it will specify the number of spaces to indent at each\n level. If it is a string (such as '\\t' or ' '),\n it contains the characters used to indent at each level.\n\n This method produces a JSON text from a JavaScript value.\n\n When an object value is found, if the object contains a toJSON\n method, its toJSON method will be called and the result will be\n stringified. A toJSON method does not serialize: it returns the\n value represented by the name/value pair that should be serialized,\n or undefined if nothing should be serialized. The toJSON method\n will be passed the key associated with the value, and this will be\n bound to the value\n\n For example, this would serialize Dates as ISO strings.\n\n Date.prototype.toJSON = function (key) {\n function f(n) {\n // Format integers to have at least two digits.\n return n < 10 ? '0' + n : n;\n }\n\n return this.getUTCFullYear() + '-' +\n f(this.getUTCMonth() + 1) + '-' +\n f(this.getUTCDate()) + 'T' +\n f(this.getUTCHours()) + ':' +\n f(this.getUTCMinutes()) + ':' +\n f(this.getUTCSeconds()) + 'Z';\n };\n\n You can provide an optional replacer method. It will be passed the\n key and value of each member, with this bound to the containing\n object. The value that is returned from your method will be\n serialized. If your method returns undefined, then the member will\n be excluded from the serialization.\n\n If the replacer parameter is an array of strings, then it will be\n used to select the members to be serialized. It filters the results\n such that only members with keys listed in the replacer array are\n stringified.\n\n Values that do not have JSON representations, such as undefined or\n functions, will not be serialized. Such values in objects will be\n dropped; in arrays they will be replaced with null. You can use\n a replacer function to replace those with JSON values.\n JSON.stringify(undefined) returns undefined.\n\n The optional space parameter produces a stringification of the\n value that is filled with line breaks and indentation to make it\n easier to read.\n\n If the space parameter is a non-empty string, then that string will\n be used for indentation. If the space parameter is a number, then\n the indentation will be that many spaces.\n\n Example:\n\n text = JSON.stringify(['e', {pluribus: 'unum'}]);\n // text is '[\"e\",{\"pluribus\":\"unum\"}]'\n\n\n text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\\t');\n // text is '[\\n\\t\"e\",\\n\\t{\\n\\t\\t\"pluribus\": \"unum\"\\n\\t}\\n]'\n\n text = JSON.stringify([new Date()], function (key, value) {\n return this[key] instanceof Date ?\n 'Date(' + this[key] + ')' : value;\n });\n // text is '[\"Date(---current time---)\"]'\n\n\n JSON.parse(text, reviver)\n This method parses a JSON text to produce an object or array.\n It can throw a SyntaxError exception.\n\n The optional reviver parameter is a function that can filter and\n transform the results. It receives each of the keys and values,\n and its return value is used instead of the original value.\n If it returns what it received, then the structure is not modified.\n If it returns undefined then the member is deleted.\n\n Example:\n\n // Parse the text. Values that look like ISO date strings will\n // be converted to Date objects.\n\n myData = JSON.parse(text, function (key, value) {\n var a;\n if (typeof value === 'string') {\n a =\n/^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}(?:\\.\\d*)?)Z$/.exec(value);\n if (a) {\n return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],\n +a[5], +a[6]));\n }\n }\n return value;\n });\n\n myData = JSON.parse('[\"Date(09/09/2001)\"]', function (key, value) {\n var d;\n if (typeof value === 'string' &&\n value.slice(0, 5) === 'Date(' &&\n value.slice(-1) === ')') {\n d = new Date(value.slice(5, -1));\n if (d) {\n return d;\n }\n }\n return value;\n });\n\n\n This is a reference implementation. You are free to copy, modify, or\n redistribute.\n*/\n\n/*jslint evil: true, regexp: true */\n\n/*members \"\", \"\\b\", \"\\t\", \"\\n\", \"\\f\", \"\\r\", \"\\\"\", JSON, \"\\\\\", apply,\n call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,\n getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,\n lastIndex, length, parse, prototype, push, replace, slice, stringify,\n test, toJSON, toString, valueOf\n*/\n\n\n// Create a JSON object only if one does not already exist. We create the\n// methods in a closure to avoid creating global variables.\n\nvar JSON = module.exports;\n\n(function () {\n 'use strict';\n\n function f(n) {\n // Format integers to have at least two digits.\n return n < 10 ? '0' + n : n;\n }\n\n var cx = /[\\u0000\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]/g,\n escapable = /[\\\\\\\"\\x00-\\x1f\\x7f-\\x9f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]/g,\n gap,\n indent,\n meta = { // table of character substitutions\n '\\b': '\\\\b',\n '\\t': '\\\\t',\n '\\n': '\\\\n',\n '\\f': '\\\\f',\n '\\r': '\\\\r',\n '\"' : '\\\\\"',\n '\\\\': '\\\\\\\\'\n },\n rep;\n\n\n function quote(string) {\n\n// If the string contains no control characters, no quote characters, and no\n// backslash characters, then we can safely slap some quotes around it.\n// Otherwise we must also replace the offending characters with safe escape\n// sequences.\n\n escapable.lastIndex = 0;\n return escapable.test(string) ? '\"' + string.replace(escapable, function (a) {\n var c = meta[a];\n return typeof c === 'string'\n ? c\n : '\\\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);\n }) + '\"' : '\"' + string + '\"';\n }\n\n\n function str(key, holder) {\n\n// Produce a string from holder[key].\n\n var i, // The loop counter.\n k, // The member key.\n v, // The member value.\n length,\n mind = gap,\n partial,\n value = holder[key],\n isBigNumber = value != null && (value instanceof BigNumber || BigNumber.isBigNumber(value));\n\n// If the value has a toJSON method, call it to obtain a replacement value.\n\n if (value && typeof value === 'object' &&\n typeof value.toJSON === 'function') {\n value = value.toJSON(key);\n }\n\n// If we were called with a replacer function, then call the replacer to\n// obtain a replacement value.\n\n if (typeof rep === 'function') {\n value = rep.call(holder, key, value);\n }\n\n// What happens next depends on the value's type.\n\n switch (typeof value) {\n case 'string':\n if (isBigNumber) {\n return value;\n } else {\n return quote(value);\n }\n\n case 'number':\n\n// JSON numbers must be finite. Encode non-finite numbers as null.\n\n return isFinite(value) ? String(value) : 'null';\n\n case 'boolean':\n case 'null':\n case 'bigint':\n\n// If the value is a boolean or null, convert it to a string. Note:\n// typeof null does not produce 'null'. The case is included here in\n// the remote chance that this gets fixed someday.\n\n return String(value);\n\n// If the type is 'object', we might be dealing with an object or an array or\n// null.\n\n case 'object':\n\n// Due to a specification blunder in ECMAScript, typeof null is 'object',\n// so watch out for that case.\n\n if (!value) {\n return 'null';\n }\n\n// Make an array to hold the partial results of stringifying this object value.\n\n gap += indent;\n partial = [];\n\n// Is the value an array?\n\n if (Object.prototype.toString.apply(value) === '[object Array]') {\n\n// The value is an array. Stringify every element. Use null as a placeholder\n// for non-JSON values.\n\n length = value.length;\n for (i = 0; i < length; i += 1) {\n partial[i] = str(i, value) || 'null';\n }\n\n// Join all of the elements together, separated with commas, and wrap them in\n// brackets.\n\n v = partial.length === 0\n ? '[]'\n : gap\n ? '[\\n' + gap + partial.join(',\\n' + gap) + '\\n' + mind + ']'\n : '[' + partial.join(',') + ']';\n gap = mind;\n return v;\n }\n\n// If the replacer is an array, use it to select the members to be stringified.\n\n if (rep && typeof rep === 'object') {\n length = rep.length;\n for (i = 0; i < length; i += 1) {\n if (typeof rep[i] === 'string') {\n k = rep[i];\n v = str(k, value);\n if (v) {\n partial.push(quote(k) + (gap ? ': ' : ':') + v);\n }\n }\n }\n } else {\n\n// Otherwise, iterate through all of the keys in the object.\n\n Object.keys(value).forEach(function(k) {\n var v = str(k, value);\n if (v) {\n partial.push(quote(k) + (gap ? ': ' : ':') + v);\n }\n });\n }\n\n// Join all of the member texts together, separated with commas,\n// and wrap them in braces.\n\n v = partial.length === 0\n ? '{}'\n : gap\n ? '{\\n' + gap + partial.join(',\\n' + gap) + '\\n' + mind + '}'\n : '{' + partial.join(',') + '}';\n gap = mind;\n return v;\n }\n }\n\n// If the JSON object does not yet have a stringify method, give it one.\n\n if (typeof JSON.stringify !== 'function') {\n JSON.stringify = function (value, replacer, space) {\n\n// The stringify method takes a value and an optional replacer, and an optional\n// space parameter, and returns a JSON text. The replacer can be a function\n// that can replace values, or an array of strings that will select the keys.\n// A default replacer method can be provided. Use of the space parameter can\n// produce text that is more easily readable.\n\n var i;\n gap = '';\n indent = '';\n\n// If the space parameter is a number, make an indent string containing that\n// many spaces.\n\n if (typeof space === 'number') {\n for (i = 0; i < space; i += 1) {\n indent += ' ';\n }\n\n// If the space parameter is a string, it will be used as the indent string.\n\n } else if (typeof space === 'string') {\n indent = space;\n }\n\n// If there is a replacer, it must be a function or an array.\n// Otherwise, throw an error.\n\n rep = replacer;\n if (replacer && typeof replacer !== 'function' &&\n (typeof replacer !== 'object' ||\n typeof replacer.length !== 'number')) {\n throw new Error('JSON.stringify');\n }\n\n// Make a fake root object containing our value under the key of ''.\n// Return the result of stringifying the value.\n\n return str('', {'': value});\n };\n }\n}());\n", "var BigNumber = null;\n\n// regexpxs extracted from\n// (c) BSD-3-Clause\n// https://github.com/fastify/secure-json-parse/graphs/contributors and https://github.com/hapijs/bourne/graphs/contributors\n\nconst suspectProtoRx = /(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])(?:p|\\\\u0070)(?:r|\\\\u0072)(?:o|\\\\u006[Ff])(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])/;\nconst suspectConstructorRx = /(?:c|\\\\u0063)(?:o|\\\\u006[Ff])(?:n|\\\\u006[Ee])(?:s|\\\\u0073)(?:t|\\\\u0074)(?:r|\\\\u0072)(?:u|\\\\u0075)(?:c|\\\\u0063)(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:r|\\\\u0072)/;\n\n/*\n json_parse.js\n 2012-06-20\n\n Public Domain.\n\n NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.\n\n This file creates a json_parse function.\n During create you can (optionally) specify some behavioural switches\n\n require('json-bigint')(options)\n\n The optional options parameter holds switches that drive certain\n aspects of the parsing process:\n * options.strict = true will warn about duplicate-key usage in the json.\n The default (strict = false) will silently ignore those and overwrite\n values for keys that are in duplicate use.\n\n The resulting function follows this signature:\n json_parse(text, reviver)\n This method parses a JSON text to produce an object or array.\n It can throw a SyntaxError exception.\n\n The optional reviver parameter is a function that can filter and\n transform the results. It receives each of the keys and values,\n and its return value is used instead of the original value.\n If it returns what it received, then the structure is not modified.\n If it returns undefined then the member is deleted.\n\n Example:\n\n // Parse the text. Values that look like ISO date strings will\n // be converted to Date objects.\n\n myData = json_parse(text, function (key, value) {\n var a;\n if (typeof value === 'string') {\n a =\n/^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}(?:\\.\\d*)?)Z$/.exec(value);\n if (a) {\n return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],\n +a[5], +a[6]));\n }\n }\n return value;\n });\n\n This is a reference implementation. You are free to copy, modify, or\n redistribute.\n\n This code should be minified before deployment.\n See http://javascript.crockford.com/jsmin.html\n\n USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO\n NOT CONTROL.\n*/\n\n/*members \"\", \"\\\"\", \"\\/\", \"\\\\\", at, b, call, charAt, f, fromCharCode,\n hasOwnProperty, message, n, name, prototype, push, r, t, text\n*/\n\nvar json_parse = function (options) {\n 'use strict';\n\n // This is a function that can parse a JSON text, producing a JavaScript\n // data structure. It is a simple, recursive descent parser. It does not use\n // eval or regular expressions, so it can be used as a model for implementing\n // a JSON parser in other languages.\n\n // We are defining the function inside of another function to avoid creating\n // global variables.\n\n // Default options one can override by passing options to the parse()\n var _options = {\n strict: false, // not being strict means do not generate syntax errors for \"duplicate key\"\n storeAsString: false, // toggles whether the values should be stored as BigNumber (default) or a string\n alwaysParseAsBig: false, // toggles whether all numbers should be Big\n useNativeBigInt: false, // toggles whether to use native BigInt instead of bignumber.js\n protoAction: 'error',\n constructorAction: 'error',\n };\n\n // If there are options, then use them to override the default _options\n if (options !== undefined && options !== null) {\n if (options.strict === true) {\n _options.strict = true;\n }\n if (options.storeAsString === true) {\n _options.storeAsString = true;\n }\n _options.alwaysParseAsBig =\n options.alwaysParseAsBig === true ? options.alwaysParseAsBig : false;\n _options.useNativeBigInt =\n options.useNativeBigInt === true ? options.useNativeBigInt : false;\n\n if (typeof options.constructorAction !== 'undefined') {\n if (\n options.constructorAction === 'error' ||\n options.constructorAction === 'ignore' ||\n options.constructorAction === 'preserve'\n ) {\n _options.constructorAction = options.constructorAction;\n } else {\n throw new Error(\n `Incorrect value for constructorAction option, must be \"error\", \"ignore\" or undefined but passed ${options.constructorAction}`\n );\n }\n }\n\n if (typeof options.protoAction !== 'undefined') {\n if (\n options.protoAction === 'error' ||\n options.protoAction === 'ignore' ||\n options.protoAction === 'preserve'\n ) {\n _options.protoAction = options.protoAction;\n } else {\n throw new Error(\n `Incorrect value for protoAction option, must be \"error\", \"ignore\" or undefined but passed ${options.protoAction}`\n );\n }\n }\n }\n\n var at, // The index of the current character\n ch, // The current character\n escapee = {\n '\"': '\"',\n '\\\\': '\\\\',\n '/': '/',\n b: '\\b',\n f: '\\f',\n n: '\\n',\n r: '\\r',\n t: '\\t',\n },\n text,\n error = function (m) {\n // Call error when something is wrong.\n\n throw {\n name: 'SyntaxError',\n message: m,\n at: at,\n text: text,\n };\n },\n next = function (c) {\n // If a c parameter is provided, verify that it matches the current character.\n\n if (c && c !== ch) {\n error(\"Expected '\" + c + \"' instead of '\" + ch + \"'\");\n }\n\n // Get the next character. When there are no more characters,\n // return the empty string.\n\n ch = text.charAt(at);\n at += 1;\n return ch;\n },\n number = function () {\n // Parse a number value.\n\n var number,\n string = '';\n\n if (ch === '-') {\n string = '-';\n next('-');\n }\n while (ch >= '0' && ch <= '9') {\n string += ch;\n next();\n }\n if (ch === '.') {\n string += '.';\n while (next() && ch >= '0' && ch <= '9') {\n string += ch;\n }\n }\n if (ch === 'e' || ch === 'E') {\n string += ch;\n next();\n if (ch === '-' || ch === '+') {\n string += ch;\n next();\n }\n while (ch >= '0' && ch <= '9') {\n string += ch;\n next();\n }\n }\n number = +string;\n if (!isFinite(number)) {\n error('Bad number');\n } else {\n if (BigNumber == null) BigNumber = require('bignumber.js');\n //if (number > 9007199254740992 || number < -9007199254740992)\n // Bignumber has stricter check: everything with length > 15 digits disallowed\n if (string.length > 15)\n return _options.storeAsString\n ? string\n : _options.useNativeBigInt\n ? BigInt(string)\n : new BigNumber(string);\n else\n return !_options.alwaysParseAsBig\n ? number\n : _options.useNativeBigInt\n ? BigInt(number)\n : new BigNumber(number);\n }\n },\n string = function () {\n // Parse a string value.\n\n var hex,\n i,\n string = '',\n uffff;\n\n // When parsing for string values, we must look for \" and \\ characters.\n\n if (ch === '\"') {\n var startAt = at;\n while (next()) {\n if (ch === '\"') {\n if (at - 1 > startAt) string += text.substring(startAt, at - 1);\n next();\n return string;\n }\n if (ch === '\\\\') {\n if (at - 1 > startAt) string += text.substring(startAt, at - 1);\n next();\n if (ch === 'u') {\n uffff = 0;\n for (i = 0; i < 4; i += 1) {\n hex = parseInt(next(), 16);\n if (!isFinite(hex)) {\n break;\n }\n uffff = uffff * 16 + hex;\n }\n string += String.fromCharCode(uffff);\n } else if (typeof escapee[ch] === 'string') {\n string += escapee[ch];\n } else {\n break;\n }\n startAt = at;\n }\n }\n }\n error('Bad string');\n },\n white = function () {\n // Skip whitespace.\n\n while (ch && ch <= ' ') {\n next();\n }\n },\n word = function () {\n // true, false, or null.\n\n switch (ch) {\n case 't':\n next('t');\n next('r');\n next('u');\n next('e');\n return true;\n case 'f':\n next('f');\n next('a');\n next('l');\n next('s');\n next('e');\n return false;\n case 'n':\n next('n');\n next('u');\n next('l');\n next('l');\n return null;\n }\n error(\"Unexpected '\" + ch + \"'\");\n },\n value, // Place holder for the value function.\n array = function () {\n // Parse an array value.\n\n var array = [];\n\n if (ch === '[') {\n next('[');\n white();\n if (ch === ']') {\n next(']');\n return array; // empty array\n }\n while (ch) {\n array.push(value());\n white();\n if (ch === ']') {\n next(']');\n return array;\n }\n next(',');\n white();\n }\n }\n error('Bad array');\n },\n object = function () {\n // Parse an object value.\n\n var key,\n object = Object.create(null);\n\n if (ch === '{') {\n next('{');\n white();\n if (ch === '}') {\n next('}');\n return object; // empty object\n }\n while (ch) {\n key = string();\n white();\n next(':');\n if (\n _options.strict === true &&\n Object.hasOwnProperty.call(object, key)\n ) {\n error('Duplicate key \"' + key + '\"');\n }\n\n if (suspectProtoRx.test(key) === true) {\n if (_options.protoAction === 'error') {\n error('Object contains forbidden prototype property');\n } else if (_options.protoAction === 'ignore') {\n value();\n } else {\n object[key] = value();\n }\n } else if (suspectConstructorRx.test(key) === true) {\n if (_options.constructorAction === 'error') {\n error('Object contains forbidden constructor property');\n } else if (_options.constructorAction === 'ignore') {\n value();\n } else {\n object[key] = value();\n }\n } else {\n object[key] = value();\n }\n\n white();\n if (ch === '}') {\n next('}');\n return object;\n }\n next(',');\n white();\n }\n }\n error('Bad object');\n };\n\n value = function () {\n // Parse a JSON value. It could be an object, an array, a string, a number,\n // or a word.\n\n white();\n switch (ch) {\n case '{':\n return object();\n case '[':\n return array();\n case '\"':\n return string();\n case '-':\n return number();\n default:\n return ch >= '0' && ch <= '9' ? number() : word();\n }\n };\n\n // Return the json_parse function. It will have access to all of the above\n // functions and variables.\n\n return function (source, reviver) {\n var result;\n\n text = source + '';\n at = 0;\n ch = ' ';\n result = value();\n white();\n if (ch) {\n error('Syntax error');\n }\n\n // If there is a reviver function, we recursively walk the new structure,\n // passing each name/value pair to the reviver function for possible\n // transformation, starting with a temporary root object that holds the result\n // in an empty key. If there is not a reviver function, we simply return the\n // result.\n\n return typeof reviver === 'function'\n ? (function walk(holder, key) {\n var k,\n v,\n value = holder[key];\n if (value && typeof value === 'object') {\n Object.keys(value).forEach(function (k) {\n v = walk(value, k);\n if (v !== undefined) {\n value[k] = v;\n } else {\n delete value[k];\n }\n });\n }\n return reviver.call(holder, key, value);\n })({ '': result }, '')\n : result;\n };\n};\n\nmodule.exports = json_parse;\n", "var json_stringify = require('./lib/stringify.js').stringify;\nvar json_parse = require('./lib/parse.js');\n\nmodule.exports = function(options) {\n return {\n parse: json_parse(options),\n stringify: json_stringify\n }\n};\n//create the default method members with no options applied for backwards compatibility\nmodule.exports.parse = json_parse();\nmodule.exports.stringify = json_stringify;\n", null, null, null, null, null, "'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n", "\"use strict\";\n// Copyright 2025 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.fromArrayBufferToHex = fromArrayBufferToHex;\n/**\n * Converts an ArrayBuffer to a hexadecimal string.\n * @param arrayBuffer The ArrayBuffer to convert to hexadecimal string.\n * @return The hexadecimal encoding of the ArrayBuffer.\n */\nfunction fromArrayBufferToHex(arrayBuffer) {\n // Convert buffer to byte array.\n const byteArray = Array.from(new Uint8Array(arrayBuffer));\n // Convert bytes to hex string.\n return byteArray\n .map(byte => {\n return byte.toString(16).padStart(2, '0');\n })\n .join('');\n}\n//# sourceMappingURL=shared.js.map", "\"use strict\";\n// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/* global window */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BrowserCrypto = void 0;\n// This file implements crypto functions we need using in-browser\n// SubtleCrypto interface `window.crypto.subtle`.\nconst base64js = require(\"base64-js\");\nconst shared_1 = require(\"../shared\");\nclass BrowserCrypto {\n constructor() {\n if (typeof window === 'undefined' ||\n window.crypto === undefined ||\n window.crypto.subtle === undefined) {\n throw new Error(\"SubtleCrypto not found. Make sure it's an https:// website.\");\n }\n }\n async sha256DigestBase64(str) {\n // SubtleCrypto digest() method is async, so we must make\n // this method async as well.\n // To calculate SHA256 digest using SubtleCrypto, we first\n // need to convert an input string to an ArrayBuffer:\n const inputBuffer = new TextEncoder().encode(str);\n // Result is ArrayBuffer as well.\n const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer);\n return base64js.fromByteArray(new Uint8Array(outputBuffer));\n }\n randomBytesBase64(count) {\n const array = new Uint8Array(count);\n window.crypto.getRandomValues(array);\n return base64js.fromByteArray(array);\n }\n static padBase64(base64) {\n // base64js requires padding, so let's add some '='\n while (base64.length % 4 !== 0) {\n base64 += '=';\n }\n return base64;\n }\n async verify(pubkey, data, signature) {\n const algo = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' },\n };\n const dataArray = new TextEncoder().encode(data);\n const signatureArray = base64js.toByteArray(BrowserCrypto.padBase64(signature));\n const cryptoKey = await window.crypto.subtle.importKey('jwk', pubkey, algo, true, ['verify']);\n // SubtleCrypto's verify method is async so we must make\n // this method async as well.\n const result = await window.crypto.subtle.verify(algo, cryptoKey, signatureArray, dataArray);\n return result;\n }\n async sign(privateKey, data) {\n const algo = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' },\n };\n const dataArray = new TextEncoder().encode(data);\n const cryptoKey = await window.crypto.subtle.importKey('jwk', privateKey, algo, true, ['sign']);\n // SubtleCrypto's sign method is async so we must make\n // this method async as well.\n const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray);\n return base64js.fromByteArray(new Uint8Array(result));\n }\n decodeBase64StringUtf8(base64) {\n const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base64));\n const result = new TextDecoder().decode(uint8array);\n return result;\n }\n encodeBase64StringUtf8(text) {\n const uint8array = new TextEncoder().encode(text);\n const result = base64js.fromByteArray(uint8array);\n return result;\n }\n /**\n * Computes the SHA-256 hash of the provided string.\n * @param str The plain text string to hash.\n * @return A promise that resolves with the SHA-256 hash of the provided\n * string in hexadecimal encoding.\n */\n async sha256DigestHex(str) {\n // SubtleCrypto digest() method is async, so we must make\n // this method async as well.\n // To calculate SHA256 digest using SubtleCrypto, we first\n // need to convert an input string to an ArrayBuffer:\n const inputBuffer = new TextEncoder().encode(str);\n // Result is ArrayBuffer as well.\n const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer);\n return (0, shared_1.fromArrayBufferToHex)(outputBuffer);\n }\n /**\n * Computes the HMAC hash of a message using the provided crypto key and the\n * SHA-256 algorithm.\n * @param key The secret crypto key in utf-8 or ArrayBuffer format.\n * @param msg The plain text message.\n * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer\n * format.\n */\n async signWithHmacSha256(key, msg) {\n // Convert key, if provided in ArrayBuffer format, to string.\n const rawKey = typeof key === 'string'\n ? key\n : String.fromCharCode(...new Uint16Array(key));\n const enc = new TextEncoder();\n const cryptoKey = await window.crypto.subtle.importKey('raw', enc.encode(rawKey), {\n name: 'HMAC',\n hash: {\n name: 'SHA-256',\n },\n }, false, ['sign']);\n return window.crypto.subtle.sign('HMAC', cryptoKey, enc.encode(msg));\n }\n}\nexports.BrowserCrypto = BrowserCrypto;\n//# sourceMappingURL=crypto.js.map", "\"use strict\";\n// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.NodeCrypto = void 0;\nconst crypto = require(\"crypto\");\nclass NodeCrypto {\n async sha256DigestBase64(str) {\n return crypto.createHash('sha256').update(str).digest('base64');\n }\n randomBytesBase64(count) {\n return crypto.randomBytes(count).toString('base64');\n }\n async verify(pubkey, data, signature) {\n const verifier = crypto.createVerify('RSA-SHA256');\n verifier.update(data);\n verifier.end();\n return verifier.verify(pubkey, signature, 'base64');\n }\n async sign(privateKey, data) {\n const signer = crypto.createSign('RSA-SHA256');\n signer.update(data);\n signer.end();\n return signer.sign(privateKey, 'base64');\n }\n decodeBase64StringUtf8(base64) {\n return Buffer.from(base64, 'base64').toString('utf-8');\n }\n encodeBase64StringUtf8(text) {\n return Buffer.from(text, 'utf-8').toString('base64');\n }\n /**\n * Computes the SHA-256 hash of the provided string.\n * @param str The plain text string to hash.\n * @return A promise that resolves with the SHA-256 hash of the provided\n * string in hexadecimal encoding.\n */\n async sha256DigestHex(str) {\n return crypto.createHash('sha256').update(str).digest('hex');\n }\n /**\n * Computes the HMAC hash of a message using the provided crypto key and the\n * SHA-256 algorithm.\n * @param key The secret crypto key in utf-8 or ArrayBuffer format.\n * @param msg The plain text message.\n * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer\n * format.\n */\n async signWithHmacSha256(key, msg) {\n const cryptoKey = typeof key === 'string' ? key : toBuffer(key);\n return toArrayBuffer(crypto.createHmac('sha256', cryptoKey).update(msg).digest());\n }\n}\nexports.NodeCrypto = NodeCrypto;\n/**\n * Converts a Node.js Buffer to an ArrayBuffer.\n * https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer\n * @param buffer The Buffer input to covert.\n * @return The ArrayBuffer representation of the input.\n */\nfunction toArrayBuffer(buffer) {\n return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);\n}\n/**\n * Converts an ArrayBuffer to a Node.js Buffer.\n * @param arrayBuffer The ArrayBuffer input to covert.\n * @return The Buffer representation of the input.\n */\nfunction toBuffer(arrayBuffer) {\n return Buffer.from(arrayBuffer);\n}\n//# sourceMappingURL=crypto.js.map", "\"use strict\";\n// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/* global window */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createCrypto = createCrypto;\nexports.hasBrowserCrypto = hasBrowserCrypto;\nconst crypto_1 = require(\"./browser/crypto\");\nconst crypto_2 = require(\"./node/crypto\");\n__exportStar(require(\"./shared\"), exports);\n// Crypto interface will provide required crypto functions.\n// Use `createCrypto()` factory function to create an instance\n// of Crypto. It will either use Node.js `crypto` module, or\n// use browser's SubtleCrypto interface. Since most of the\n// SubtleCrypto methods return promises, we must make those\n// methods return promises here as well, even though in Node.js\n// they are synchronous.\nfunction createCrypto() {\n if (hasBrowserCrypto()) {\n return new crypto_1.BrowserCrypto();\n }\n return new crypto_2.NodeCrypto();\n}\nfunction hasBrowserCrypto() {\n return (typeof window !== 'undefined' &&\n typeof window.crypto !== 'undefined' &&\n typeof window.crypto.subtle !== 'undefined');\n}\n//# sourceMappingURL=crypto.js.map", "/*! safe-buffer. MIT License. Feross Aboukhadijeh */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n", "'use strict';\n\nfunction getParamSize(keySize) {\n\tvar result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1);\n\treturn result;\n}\n\nvar paramBytesForAlg = {\n\tES256: getParamSize(256),\n\tES384: getParamSize(384),\n\tES512: getParamSize(521)\n};\n\nfunction getParamBytesForAlg(alg) {\n\tvar paramBytes = paramBytesForAlg[alg];\n\tif (paramBytes) {\n\t\treturn paramBytes;\n\t}\n\n\tthrow new Error('Unknown algorithm \"' + alg + '\"');\n}\n\nmodule.exports = getParamBytesForAlg;\n", "'use strict';\n\nvar Buffer = require('safe-buffer').Buffer;\n\nvar getParamBytesForAlg = require('./param-bytes-for-alg');\n\nvar MAX_OCTET = 0x80,\n\tCLASS_UNIVERSAL = 0,\n\tPRIMITIVE_BIT = 0x20,\n\tTAG_SEQ = 0x10,\n\tTAG_INT = 0x02,\n\tENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6),\n\tENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6);\n\nfunction base64Url(base64) {\n\treturn base64\n\t\t.replace(/=/g, '')\n\t\t.replace(/\\+/g, '-')\n\t\t.replace(/\\//g, '_');\n}\n\nfunction signatureAsBuffer(signature) {\n\tif (Buffer.isBuffer(signature)) {\n\t\treturn signature;\n\t} else if ('string' === typeof signature) {\n\t\treturn Buffer.from(signature, 'base64');\n\t}\n\n\tthrow new TypeError('ECDSA signature must be a Base64 string or a Buffer');\n}\n\nfunction derToJose(signature, alg) {\n\tsignature = signatureAsBuffer(signature);\n\tvar paramBytes = getParamBytesForAlg(alg);\n\n\t// the DER encoded param should at most be the param size, plus a padding\n\t// zero, since due to being a signed integer\n\tvar maxEncodedParamLength = paramBytes + 1;\n\n\tvar inputLength = signature.length;\n\n\tvar offset = 0;\n\tif (signature[offset++] !== ENCODED_TAG_SEQ) {\n\t\tthrow new Error('Could not find expected \"seq\"');\n\t}\n\n\tvar seqLength = signature[offset++];\n\tif (seqLength === (MAX_OCTET | 1)) {\n\t\tseqLength = signature[offset++];\n\t}\n\n\tif (inputLength - offset < seqLength) {\n\t\tthrow new Error('\"seq\" specified length of \"' + seqLength + '\", only \"' + (inputLength - offset) + '\" remaining');\n\t}\n\n\tif (signature[offset++] !== ENCODED_TAG_INT) {\n\t\tthrow new Error('Could not find expected \"int\" for \"r\"');\n\t}\n\n\tvar rLength = signature[offset++];\n\n\tif (inputLength - offset - 2 < rLength) {\n\t\tthrow new Error('\"r\" specified length of \"' + rLength + '\", only \"' + (inputLength - offset - 2) + '\" available');\n\t}\n\n\tif (maxEncodedParamLength < rLength) {\n\t\tthrow new Error('\"r\" specified length of \"' + rLength + '\", max of \"' + maxEncodedParamLength + '\" is acceptable');\n\t}\n\n\tvar rOffset = offset;\n\toffset += rLength;\n\n\tif (signature[offset++] !== ENCODED_TAG_INT) {\n\t\tthrow new Error('Could not find expected \"int\" for \"s\"');\n\t}\n\n\tvar sLength = signature[offset++];\n\n\tif (inputLength - offset !== sLength) {\n\t\tthrow new Error('\"s\" specified length of \"' + sLength + '\", expected \"' + (inputLength - offset) + '\"');\n\t}\n\n\tif (maxEncodedParamLength < sLength) {\n\t\tthrow new Error('\"s\" specified length of \"' + sLength + '\", max of \"' + maxEncodedParamLength + '\" is acceptable');\n\t}\n\n\tvar sOffset = offset;\n\toffset += sLength;\n\n\tif (offset !== inputLength) {\n\t\tthrow new Error('Expected to consume entire buffer, but \"' + (inputLength - offset) + '\" bytes remain');\n\t}\n\n\tvar rPadding = paramBytes - rLength,\n\t\tsPadding = paramBytes - sLength;\n\n\tvar dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength);\n\n\tfor (offset = 0; offset < rPadding; ++offset) {\n\t\tdst[offset] = 0;\n\t}\n\tsignature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength);\n\n\toffset = paramBytes;\n\n\tfor (var o = offset; offset < o + sPadding; ++offset) {\n\t\tdst[offset] = 0;\n\t}\n\tsignature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength);\n\n\tdst = dst.toString('base64');\n\tdst = base64Url(dst);\n\n\treturn dst;\n}\n\nfunction countPadding(buf, start, stop) {\n\tvar padding = 0;\n\twhile (start + padding < stop && buf[start + padding] === 0) {\n\t\t++padding;\n\t}\n\n\tvar needsSign = buf[start + padding] >= MAX_OCTET;\n\tif (needsSign) {\n\t\t--padding;\n\t}\n\n\treturn padding;\n}\n\nfunction joseToDer(signature, alg) {\n\tsignature = signatureAsBuffer(signature);\n\tvar paramBytes = getParamBytesForAlg(alg);\n\n\tvar signatureBytes = signature.length;\n\tif (signatureBytes !== paramBytes * 2) {\n\t\tthrow new TypeError('\"' + alg + '\" signatures must be \"' + paramBytes * 2 + '\" bytes, saw \"' + signatureBytes + '\"');\n\t}\n\n\tvar rPadding = countPadding(signature, 0, paramBytes);\n\tvar sPadding = countPadding(signature, paramBytes, signature.length);\n\tvar rLength = paramBytes - rPadding;\n\tvar sLength = paramBytes - sPadding;\n\n\tvar rsBytes = 1 + 1 + rLength + 1 + 1 + sLength;\n\n\tvar shortLength = rsBytes < MAX_OCTET;\n\n\tvar dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes);\n\n\tvar offset = 0;\n\tdst[offset++] = ENCODED_TAG_SEQ;\n\tif (shortLength) {\n\t\t// Bit 8 has value \"0\"\n\t\t// bits 7-1 give the length.\n\t\tdst[offset++] = rsBytes;\n\t} else {\n\t\t// Bit 8 of first octet has value \"1\"\n\t\t// bits 7-1 give the number of additional length octets.\n\t\tdst[offset++] = MAX_OCTET\t| 1;\n\t\t// length, base 256\n\t\tdst[offset++] = rsBytes & 0xff;\n\t}\n\tdst[offset++] = ENCODED_TAG_INT;\n\tdst[offset++] = rLength;\n\tif (rPadding < 0) {\n\t\tdst[offset++] = 0;\n\t\toffset += signature.copy(dst, offset, 0, paramBytes);\n\t} else {\n\t\toffset += signature.copy(dst, offset, rPadding, paramBytes);\n\t}\n\tdst[offset++] = ENCODED_TAG_INT;\n\tdst[offset++] = sLength;\n\tif (sPadding < 0) {\n\t\tdst[offset++] = 0;\n\t\tsignature.copy(dst, offset, paramBytes);\n\t} else {\n\t\tsignature.copy(dst, offset, paramBytes + sPadding);\n\t}\n\n\treturn dst;\n}\n\nmodule.exports = {\n\tderToJose: derToJose,\n\tjoseToDer: joseToDer\n};\n", "\"use strict\";\n// Copyright 2023 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LRUCache = void 0;\nexports.snakeToCamel = snakeToCamel;\nexports.originalOrCamelOptions = originalOrCamelOptions;\nexports.removeUndefinedValuesInObject = removeUndefinedValuesInObject;\nexports.isValidFile = isValidFile;\nexports.getWellKnownCertificateConfigFileLocation = getWellKnownCertificateConfigFileLocation;\nconst fs = require(\"fs\");\nconst os = require(\"os\");\nconst path = require(\"path\");\nconst WELL_KNOWN_CERTIFICATE_CONFIG_FILE = 'certificate_config.json';\nconst CLOUDSDK_CONFIG_DIRECTORY = 'gcloud';\n/**\n * Returns the camel case of a provided string.\n *\n * @remarks\n *\n * Match any `_` and not `_` pair, then return the uppercase of the not `_`\n * character.\n *\n * @param str the string to convert\n * @returns the camelCase'd string\n */\nfunction snakeToCamel(str) {\n return str.replace(/([_][^_])/g, match => match.slice(1).toUpperCase());\n}\n/**\n * Get the value of `obj[key]` or `obj[camelCaseKey]`, with a preference\n * for original, non-camelCase key.\n *\n * @param obj object to lookup a value in\n * @returns a `get` function for getting `obj[key || snakeKey]`, if available\n */\nfunction originalOrCamelOptions(obj) {\n /**\n *\n * @param key an index of object, preferably snake_case\n * @returns the value `obj[key || snakeKey]`, if available\n */\n function get(key) {\n const o = (obj || {});\n return o[key] ?? o[snakeToCamel(key)];\n }\n return { get };\n}\n/**\n * A simple LRU cache utility.\n * Not meant for external usage.\n *\n * @experimental\n */\nclass LRUCache {\n capacity;\n /**\n * Maps are in order. Thus, the older item is the first item.\n *\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map}\n */\n #cache = new Map();\n maxAge;\n constructor(options) {\n this.capacity = options.capacity;\n this.maxAge = options.maxAge;\n }\n /**\n * Moves the key to the end of the cache.\n *\n * @param key the key to move\n * @param value the value of the key\n */\n #moveToEnd(key, value) {\n this.#cache.delete(key);\n this.#cache.set(key, {\n value,\n lastAccessed: Date.now(),\n });\n }\n /**\n * Add an item to the cache.\n *\n * @param key the key to upsert\n * @param value the value of the key\n */\n set(key, value) {\n this.#moveToEnd(key, value);\n this.#evict();\n }\n /**\n * Get an item from the cache.\n *\n * @param key the key to retrieve\n */\n get(key) {\n const item = this.#cache.get(key);\n if (!item)\n return;\n this.#moveToEnd(key, item.value);\n this.#evict();\n return item.value;\n }\n /**\n * Maintain the cache based on capacity and TTL.\n */\n #evict() {\n const cutoffDate = this.maxAge ? Date.now() - this.maxAge : 0;\n /**\n * Because we know Maps are in order, this item is both the\n * last item in the list (capacity) and oldest (maxAge).\n */\n let oldestItem = this.#cache.entries().next();\n while (!oldestItem.done &&\n (this.#cache.size > this.capacity || // too many\n oldestItem.value[1].lastAccessed < cutoffDate) // too old\n ) {\n this.#cache.delete(oldestItem.value[0]);\n oldestItem = this.#cache.entries().next();\n }\n }\n}\nexports.LRUCache = LRUCache;\n// Given and object remove fields where value is undefined.\nfunction removeUndefinedValuesInObject(object) {\n Object.entries(object).forEach(([key, value]) => {\n if (value === undefined || value === 'undefined') {\n delete object[key];\n }\n });\n return object;\n}\n/**\n * Helper to check if a path points to a valid file.\n */\nasync function isValidFile(filePath) {\n try {\n const stats = await fs.promises.lstat(filePath);\n return stats.isFile();\n }\n catch (e) {\n return false;\n }\n}\n/**\n * Determines the well-known gcloud location for the certificate config file.\n * @returns The platform-specific path to the configuration file.\n * @internal\n */\nfunction getWellKnownCertificateConfigFileLocation() {\n const configDir = process.env.CLOUDSDK_CONFIG ||\n (_isWindows()\n ? path.join(process.env.APPDATA || '', CLOUDSDK_CONFIG_DIRECTORY)\n : path.join(process.env.HOME || '', '.config', CLOUDSDK_CONFIG_DIRECTORY));\n return path.join(configDir, WELL_KNOWN_CERTIFICATE_CONFIG_FILE);\n}\n/**\n * Checks if the current operating system is Windows.\n * @returns True if the OS is Windows, false otherwise.\n * @internal\n */\nfunction _isWindows() {\n return os.platform().startsWith('win');\n}\n//# sourceMappingURL=util.js.map", "{\n \"name\": \"google-auth-library\",\n \"version\": \"10.2.0\",\n \"author\": \"Google Inc.\",\n \"description\": \"Google APIs Authentication Client Library for Node.js\",\n \"engines\": {\n \"node\": \">=18\"\n },\n \"main\": \"./build/src/index.js\",\n \"types\": \"./build/src/index.d.ts\",\n \"repository\": \"googleapis/google-auth-library-nodejs.git\",\n \"keywords\": [\n \"google\",\n \"api\",\n \"google apis\",\n \"client\",\n \"client library\"\n ],\n \"dependencies\": {\n \"base64-js\": \"^1.3.0\",\n \"ecdsa-sig-formatter\": \"^1.0.11\",\n \"gaxios\": \"^7.0.0\",\n \"gcp-metadata\": \"^7.0.0\",\n \"google-logging-utils\": \"^1.0.0\",\n \"gtoken\": \"^8.0.0\",\n \"jws\": \"^4.0.0\"\n },\n \"devDependencies\": {\n \"@types/base64-js\": \"^1.2.5\",\n \"@types/jws\": \"^3.1.0\",\n \"@types/mocha\": \"^10.0.10\",\n \"@types/mv\": \"^2.1.0\",\n \"@types/ncp\": \"^2.0.1\",\n \"@types/node\": \"^22.0.0\",\n \"@types/sinon\": \"^17.0.0\",\n \"assert-rejects\": \"^1.0.0\",\n \"c8\": \"^10.0.0\",\n \"codecov\": \"^3.0.2\",\n \"gts\": \"^6.0.0\",\n \"is-docker\": \"^3.0.0\",\n \"jsdoc\": \"^4.0.0\",\n \"jsdoc-fresh\": \"^4.0.0\",\n \"jsdoc-region-tag\": \"^3.0.0\",\n \"karma\": \"^6.0.0\",\n \"karma-chrome-launcher\": \"^3.0.0\",\n \"karma-coverage\": \"^2.0.0\",\n \"karma-firefox-launcher\": \"^2.0.0\",\n \"karma-mocha\": \"^2.0.0\",\n \"karma-sourcemap-loader\": \"^0.4.0\",\n \"karma-webpack\": \"^5.0.1\",\n \"keypair\": \"^1.0.4\",\n \"linkinator\": \"^6.1.2\",\n \"mocha\": \"^11.1.0\",\n \"mv\": \"^2.1.1\",\n \"ncp\": \"^2.0.0\",\n \"nock\": \"^14.0.1\",\n \"null-loader\": \"^4.0.0\",\n \"puppeteer\": \"^24.0.0\",\n \"sinon\": \"^21.0.0\",\n \"ts-loader\": \"^8.0.0\",\n \"typescript\": \"^5.1.6\",\n \"webpack\": \"^5.21.2\",\n \"webpack-cli\": \"^4.0.0\"\n },\n \"files\": [\n \"build/src\",\n \"!build/src/**/*.map\"\n ],\n \"scripts\": {\n \"test\": \"c8 mocha build/test\",\n \"clean\": \"gts clean\",\n \"prepare\": \"npm run compile\",\n \"lint\": \"gts check --no-inline-config\",\n \"compile\": \"tsc -p .\",\n \"fix\": \"gts fix\",\n \"pretest\": \"npm run compile -- --sourceMap\",\n \"docs\": \"jsdoc -c .jsdoc.js\",\n \"samples-setup\": \"cd samples/ && npm link ../ && npm run setup && cd ../\",\n \"samples-test\": \"cd samples/ && npm link ../ && npm test && cd ../\",\n \"system-test\": \"mocha build/system-test --timeout 60000\",\n \"presystem-test\": \"npm run compile -- --sourceMap\",\n \"webpack\": \"webpack\",\n \"browser-test\": \"karma start\",\n \"docs-test\": \"linkinator docs\",\n \"predocs-test\": \"npm run docs\",\n \"prelint\": \"cd samples; npm link ../; npm install\"\n },\n \"license\": \"Apache-2.0\"\n}\n", "\"use strict\";\n// Copyright 2023 Google LLC\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.USER_AGENT = exports.PRODUCT_NAME = exports.pkg = void 0;\nconst pkg = require('../../package.json');\nexports.pkg = pkg;\nconst PRODUCT_NAME = 'google-api-nodejs-client';\nexports.PRODUCT_NAME = PRODUCT_NAME;\nconst USER_AGENT = `${PRODUCT_NAME}/${pkg.version}`;\nexports.USER_AGENT = USER_AGENT;\n//# sourceMappingURL=shared.cjs.map", "\"use strict\";\n// Copyright 2012 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AuthClient = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = exports.DEFAULT_UNIVERSE = void 0;\nconst events_1 = require(\"events\");\nconst gaxios_1 = require(\"gaxios\");\nconst util_1 = require(\"../util\");\nconst google_logging_utils_1 = require(\"google-logging-utils\");\nconst shared_cjs_1 = require(\"../shared.cjs\");\n/**\n * The default cloud universe\n *\n * @see {@link AuthJSONOptions.universe_domain}\n */\nexports.DEFAULT_UNIVERSE = 'googleapis.com';\n/**\n * The default {@link AuthClientOptions.eagerRefreshThresholdMillis}\n */\nexports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = 5 * 60 * 1000;\n/**\n * The base of all Auth Clients.\n */\nclass AuthClient extends events_1.EventEmitter {\n apiKey;\n projectId;\n /**\n * The quota project ID. The quota project can be used by client libraries for the billing purpose.\n * See {@link https://cloud.google.com/docs/quota Working with quotas}\n */\n quotaProjectId;\n /**\n * The {@link Gaxios `Gaxios`} instance used for making requests.\n */\n transporter;\n credentials = {};\n eagerRefreshThresholdMillis = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;\n forceRefreshOnFailure = false;\n universeDomain = exports.DEFAULT_UNIVERSE;\n /**\n * Symbols that can be added to GaxiosOptions to specify the method name that is\n * making an RPC call, for logging purposes, as well as a string ID that can be\n * used to correlate calls and responses.\n */\n static RequestMethodNameSymbol = Symbol('request method name');\n static RequestLogIdSymbol = Symbol('request log id');\n constructor(opts = {}) {\n super();\n const options = (0, util_1.originalOrCamelOptions)(opts);\n // Shared auth options\n this.apiKey = opts.apiKey;\n this.projectId = options.get('project_id') ?? null;\n this.quotaProjectId = options.get('quota_project_id');\n this.credentials = options.get('credentials') ?? {};\n this.universeDomain = options.get('universe_domain') ?? exports.DEFAULT_UNIVERSE;\n // Shared client options\n this.transporter = opts.transporter ?? new gaxios_1.Gaxios(opts.transporterOptions);\n if (options.get('useAuthRequestParameters') !== false) {\n this.transporter.interceptors.request.add(AuthClient.DEFAULT_REQUEST_INTERCEPTOR);\n this.transporter.interceptors.response.add(AuthClient.DEFAULT_RESPONSE_INTERCEPTOR);\n }\n if (opts.eagerRefreshThresholdMillis) {\n this.eagerRefreshThresholdMillis = opts.eagerRefreshThresholdMillis;\n }\n this.forceRefreshOnFailure = opts.forceRefreshOnFailure ?? false;\n }\n /**\n * A {@link fetch `fetch`} compliant API for {@link AuthClient}.\n *\n * @see {@link AuthClient.request} for the classic method.\n *\n * @remarks\n *\n * This is useful as a drop-in replacement for `fetch` API usage.\n *\n * @example\n *\n * ```ts\n * const authClient = new AuthClient();\n * const fetchWithAuthClient: typeof fetch = (...args) => authClient.fetch(...args);\n * await fetchWithAuthClient('https://example.com');\n * ```\n *\n * @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters\n * @returns the {@link GaxiosResponse} with Gaxios-added properties\n */\n fetch(...args) {\n // Up to 2 parameters in either overload\n const input = args[0];\n const init = args[1];\n let url = undefined;\n const headers = new Headers();\n // prepare URL\n if (typeof input === 'string') {\n url = new URL(input);\n }\n else if (input instanceof URL) {\n url = input;\n }\n else if (input && input.url) {\n url = new URL(input.url);\n }\n // prepare headers\n if (input && typeof input === 'object' && 'headers' in input) {\n gaxios_1.Gaxios.mergeHeaders(headers, input.headers);\n }\n if (init) {\n gaxios_1.Gaxios.mergeHeaders(headers, new Headers(init.headers));\n }\n // prepare request\n if (typeof input === 'object' && !(input instanceof URL)) {\n // input must have been a non-URL object\n return this.request({ ...init, ...input, headers, url });\n }\n else {\n // input must have been a string or URL\n return this.request({ ...init, headers, url });\n }\n }\n /**\n * Sets the auth credentials.\n */\n setCredentials(credentials) {\n this.credentials = credentials;\n }\n /**\n * Append additional headers, e.g., x-goog-user-project, shared across the\n * classes inheriting AuthClient. This method should be used by any method\n * that overrides getRequestMetadataAsync(), which is a shared helper for\n * setting request information in both gRPC and HTTP API calls.\n *\n * @param headers object to append additional headers to.\n */\n addSharedMetadataHeaders(headers) {\n // quota_project_id, stored in application_default_credentials.json, is set in\n // the x-goog-user-project header, to indicate an alternate account for\n // billing and quota:\n if (!headers.has('x-goog-user-project') && // don't override a value the user sets.\n this.quotaProjectId) {\n headers.set('x-goog-user-project', this.quotaProjectId);\n }\n return headers;\n }\n /**\n * Adds the `x-goog-user-project` and `authorization` headers to the target Headers\n * object, if they exist on the source.\n *\n * @param target the headers to target\n * @param source the headers to source from\n * @returns the target headers\n */\n addUserProjectAndAuthHeaders(target, source) {\n const xGoogUserProject = source.get('x-goog-user-project');\n const authorizationHeader = source.get('authorization');\n if (xGoogUserProject) {\n target.set('x-goog-user-project', xGoogUserProject);\n }\n if (authorizationHeader) {\n target.set('authorization', authorizationHeader);\n }\n return target;\n }\n static log = (0, google_logging_utils_1.log)('auth');\n static DEFAULT_REQUEST_INTERCEPTOR = {\n resolved: async (config) => {\n // Set `x-goog-api-client`, if not already set\n if (!config.headers.has('x-goog-api-client')) {\n const nodeVersion = process.version.replace(/^v/, '');\n config.headers.set('x-goog-api-client', `gl-node/${nodeVersion}`);\n }\n // Set `User-Agent`\n const userAgent = config.headers.get('User-Agent');\n if (!userAgent) {\n config.headers.set('User-Agent', shared_cjs_1.USER_AGENT);\n }\n else if (!userAgent.includes(`${shared_cjs_1.PRODUCT_NAME}/`)) {\n config.headers.set('User-Agent', `${userAgent} ${shared_cjs_1.USER_AGENT}`);\n }\n try {\n const symbols = config;\n const methodName = symbols[AuthClient.RequestMethodNameSymbol];\n // This doesn't need to be very unique or interesting, it's just an aid for\n // matching requests to responses.\n const logId = `${Math.floor(Math.random() * 1000)}`;\n symbols[AuthClient.RequestLogIdSymbol] = logId;\n // Boil down the object we're printing out.\n const logObject = {\n url: config.url,\n headers: config.headers,\n };\n if (methodName) {\n AuthClient.log.info('%s [%s] request %j', methodName, logId, logObject);\n }\n else {\n AuthClient.log.info('[%s] request %j', logId, logObject);\n }\n }\n catch (e) {\n // Logging must not create new errors; swallow them all.\n }\n return config;\n },\n };\n static DEFAULT_RESPONSE_INTERCEPTOR = {\n resolved: async (response) => {\n try {\n const symbols = response.config;\n const methodName = symbols[AuthClient.RequestMethodNameSymbol];\n const logId = symbols[AuthClient.RequestLogIdSymbol];\n if (methodName) {\n AuthClient.log.info('%s [%s] response %j', methodName, logId, response.data);\n }\n else {\n AuthClient.log.info('[%s] response %j', logId, response.data);\n }\n }\n catch (e) {\n // Logging must not create new errors; swallow them all.\n }\n return response;\n },\n rejected: async (error) => {\n try {\n const symbols = error.config;\n const methodName = symbols[AuthClient.RequestMethodNameSymbol];\n const logId = symbols[AuthClient.RequestLogIdSymbol];\n if (methodName) {\n AuthClient.log.info('%s [%s] error %j', methodName, logId, error.response?.data);\n }\n else {\n AuthClient.log.error('[%s] error %j', logId, error.response?.data);\n }\n }\n catch (e) {\n // Logging must not create new errors; swallow them all.\n }\n // Re-throw the error.\n throw error;\n },\n };\n /**\n * Sets the method name that is making a Gaxios request, so that logging may tag\n * log lines with the operation.\n * @param config A Gaxios request config\n * @param methodName The method name making the call\n */\n static setMethodName(config, methodName) {\n try {\n const symbols = config;\n symbols[AuthClient.RequestMethodNameSymbol] = methodName;\n }\n catch (e) {\n // Logging must not create new errors; swallow them all.\n }\n }\n /**\n * Retry config for Auth-related requests.\n *\n * @remarks\n *\n * This is not a part of the default {@link AuthClient.transporter transporter/gaxios}\n * config as some downstream APIs would prefer if customers explicitly enable retries,\n * such as GCS.\n */\n static get RETRY_CONFIG() {\n return {\n retry: true,\n retryConfig: {\n httpMethodsToRetry: ['GET', 'PUT', 'POST', 'HEAD', 'OPTIONS', 'DELETE'],\n },\n };\n }\n}\nexports.AuthClient = AuthClient;\n//# sourceMappingURL=authclient.js.map", "\"use strict\";\n// Copyright 2014 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LoginTicket = void 0;\nclass LoginTicket {\n envelope;\n payload;\n /**\n * Create a simple class to extract user ID from an ID Token\n *\n * @param {string} env Envelope of the jwt\n * @param {TokenPayload} pay Payload of the jwt\n * @constructor\n */\n constructor(env, pay) {\n this.envelope = env;\n this.payload = pay;\n }\n getEnvelope() {\n return this.envelope;\n }\n getPayload() {\n return this.payload;\n }\n /**\n * Create a simple class to extract user ID from an ID Token\n *\n * @return The user ID\n */\n getUserId() {\n const payload = this.getPayload();\n if (payload && payload.sub) {\n return payload.sub;\n }\n return null;\n }\n /**\n * Returns attributes from the login ticket. This can contain\n * various information about the user session.\n *\n * @return The envelope and payload\n */\n getAttributes() {\n return { envelope: this.getEnvelope(), payload: this.getPayload() };\n }\n}\nexports.LoginTicket = LoginTicket;\n//# sourceMappingURL=loginticket.js.map", "\"use strict\";\n// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.OAuth2Client = exports.ClientAuthentication = exports.CertificateFormat = exports.CodeChallengeMethod = void 0;\nconst gaxios_1 = require(\"gaxios\");\nconst querystring = require(\"querystring\");\nconst stream = require(\"stream\");\nconst formatEcdsa = require(\"ecdsa-sig-formatter\");\nconst util_1 = require(\"../util\");\nconst crypto_1 = require(\"../crypto/crypto\");\nconst authclient_1 = require(\"./authclient\");\nconst loginticket_1 = require(\"./loginticket\");\nvar CodeChallengeMethod;\n(function (CodeChallengeMethod) {\n CodeChallengeMethod[\"Plain\"] = \"plain\";\n CodeChallengeMethod[\"S256\"] = \"S256\";\n})(CodeChallengeMethod || (exports.CodeChallengeMethod = CodeChallengeMethod = {}));\nvar CertificateFormat;\n(function (CertificateFormat) {\n CertificateFormat[\"PEM\"] = \"PEM\";\n CertificateFormat[\"JWK\"] = \"JWK\";\n})(CertificateFormat || (exports.CertificateFormat = CertificateFormat = {}));\n/**\n * The client authentication type. Supported values are basic, post, and none.\n * https://datatracker.ietf.org/doc/html/rfc7591#section-2\n */\nvar ClientAuthentication;\n(function (ClientAuthentication) {\n ClientAuthentication[\"ClientSecretPost\"] = \"ClientSecretPost\";\n ClientAuthentication[\"ClientSecretBasic\"] = \"ClientSecretBasic\";\n ClientAuthentication[\"None\"] = \"None\";\n})(ClientAuthentication || (exports.ClientAuthentication = ClientAuthentication = {}));\nclass OAuth2Client extends authclient_1.AuthClient {\n redirectUri;\n certificateCache = {};\n certificateExpiry = null;\n certificateCacheFormat = CertificateFormat.PEM;\n refreshTokenPromises = new Map();\n endpoints;\n issuers;\n clientAuthentication;\n // TODO: refactor tests to make this private\n _clientId;\n // TODO: refactor tests to make this private\n _clientSecret;\n refreshHandler;\n /**\n * An OAuth2 Client for Google APIs.\n *\n * @param options The OAuth2 Client Options. Passing an `clientId` directly is **@DEPRECATED**.\n * @param clientSecret **@DEPRECATED**. Provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead.\n * @param redirectUri **@DEPRECATED**. Provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead.\n */\n constructor(options = {}, \n /**\n * @deprecated - provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead\n */\n clientSecret, \n /**\n * @deprecated - provide a {@link OAuth2ClientOptions `OAuth2ClientOptions`} object in the first parameter instead\n */\n redirectUri) {\n super(typeof options === 'object' ? options : {});\n if (typeof options !== 'object') {\n options = {\n clientId: options,\n clientSecret,\n redirectUri,\n };\n }\n this._clientId = options.clientId || options.client_id;\n this._clientSecret = options.clientSecret || options.client_secret;\n this.redirectUri = options.redirectUri || options.redirect_uris?.[0];\n this.endpoints = {\n tokenInfoUrl: 'https://oauth2.googleapis.com/tokeninfo',\n oauth2AuthBaseUrl: 'https://accounts.google.com/o/oauth2/v2/auth',\n oauth2TokenUrl: 'https://oauth2.googleapis.com/token',\n oauth2RevokeUrl: 'https://oauth2.googleapis.com/revoke',\n oauth2FederatedSignonPemCertsUrl: 'https://www.googleapis.com/oauth2/v1/certs',\n oauth2FederatedSignonJwkCertsUrl: 'https://www.googleapis.com/oauth2/v3/certs',\n oauth2IapPublicKeyUrl: 'https://www.gstatic.com/iap/verify/public_key',\n ...options.endpoints,\n };\n this.clientAuthentication =\n options.clientAuthentication || ClientAuthentication.ClientSecretPost;\n this.issuers = options.issuers || [\n 'accounts.google.com',\n 'https://accounts.google.com',\n this.universeDomain,\n ];\n }\n /**\n * @deprecated use instance's {@link OAuth2Client.endpoints}\n */\n static GOOGLE_TOKEN_INFO_URL = 'https://oauth2.googleapis.com/tokeninfo';\n /**\n * Clock skew - five minutes in seconds\n */\n static CLOCK_SKEW_SECS_ = 300;\n /**\n * The default max Token Lifetime is one day in seconds\n */\n static DEFAULT_MAX_TOKEN_LIFETIME_SECS_ = 86400;\n /**\n * Generates URL for consent page landing.\n * @param opts Options.\n * @return URL to consent page.\n */\n generateAuthUrl(opts = {}) {\n if (opts.code_challenge_method && !opts.code_challenge) {\n throw new Error('If a code_challenge_method is provided, code_challenge must be included.');\n }\n opts.response_type = opts.response_type || 'code';\n opts.client_id = opts.client_id || this._clientId;\n opts.redirect_uri = opts.redirect_uri || this.redirectUri;\n // Allow scopes to be passed either as array or a string\n if (Array.isArray(opts.scope)) {\n opts.scope = opts.scope.join(' ');\n }\n const rootUrl = this.endpoints.oauth2AuthBaseUrl.toString();\n return (rootUrl +\n '?' +\n querystring.stringify(opts));\n }\n generateCodeVerifier() {\n // To make the code compatible with browser SubtleCrypto we need to make\n // this method async.\n throw new Error('generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.');\n }\n /**\n * Convenience method to automatically generate a code_verifier, and its\n * resulting SHA256. If used, this must be paired with a S256\n * code_challenge_method.\n *\n * For a full example see:\n * https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js\n */\n async generateCodeVerifierAsync() {\n // base64 encoding uses 6 bits per character, and we want to generate128\n // characters. 6*128/8 = 96.\n const crypto = (0, crypto_1.createCrypto)();\n const randomString = crypto.randomBytesBase64(96);\n // The valid characters in the code_verifier are [A-Z]/[a-z]/[0-9]/\n // \"-\"/\".\"/\"_\"/\"~\". Base64 encoded strings are pretty close, so we're just\n // swapping out a few chars.\n const codeVerifier = randomString\n .replace(/\\+/g, '~')\n .replace(/=/g, '_')\n .replace(/\\//g, '-');\n // Generate the base64 encoded SHA256\n const unencodedCodeChallenge = await crypto.sha256DigestBase64(codeVerifier);\n // We need to use base64UrlEncoding instead of standard base64\n const codeChallenge = unencodedCodeChallenge\n .split('=')[0]\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n return { codeVerifier, codeChallenge };\n }\n getToken(codeOrOptions, callback) {\n const options = typeof codeOrOptions === 'string' ? { code: codeOrOptions } : codeOrOptions;\n if (callback) {\n this.getTokenAsync(options).then(r => callback(null, r.tokens, r.res), e => callback(e, null, e.response));\n }\n else {\n return this.getTokenAsync(options);\n }\n }\n async getTokenAsync(options) {\n const url = this.endpoints.oauth2TokenUrl.toString();\n const headers = new Headers();\n const values = {\n client_id: options.client_id || this._clientId,\n code_verifier: options.codeVerifier,\n code: options.code,\n grant_type: 'authorization_code',\n redirect_uri: options.redirect_uri || this.redirectUri,\n };\n if (this.clientAuthentication === ClientAuthentication.ClientSecretBasic) {\n const basic = Buffer.from(`${this._clientId}:${this._clientSecret}`);\n headers.set('authorization', `Basic ${basic.toString('base64')}`);\n }\n if (this.clientAuthentication === ClientAuthentication.ClientSecretPost) {\n values.client_secret = this._clientSecret;\n }\n const opts = {\n ...OAuth2Client.RETRY_CONFIG,\n method: 'POST',\n url,\n data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(values)),\n headers,\n };\n authclient_1.AuthClient.setMethodName(opts, 'getTokenAsync');\n const res = await this.transporter.request(opts);\n const tokens = res.data;\n if (res.data && res.data.expires_in) {\n tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000;\n delete tokens.expires_in;\n }\n this.emit('tokens', tokens);\n return { tokens, res };\n }\n /**\n * Refreshes the access token.\n * @param refresh_token Existing refresh token.\n * @private\n */\n async refreshToken(refreshToken) {\n if (!refreshToken) {\n return this.refreshTokenNoCache(refreshToken);\n }\n // If a request to refresh using the same token has started,\n // return the same promise.\n if (this.refreshTokenPromises.has(refreshToken)) {\n return this.refreshTokenPromises.get(refreshToken);\n }\n const p = this.refreshTokenNoCache(refreshToken).then(r => {\n this.refreshTokenPromises.delete(refreshToken);\n return r;\n }, e => {\n this.refreshTokenPromises.delete(refreshToken);\n throw e;\n });\n this.refreshTokenPromises.set(refreshToken, p);\n return p;\n }\n async refreshTokenNoCache(refreshToken) {\n if (!refreshToken) {\n throw new Error('No refresh token is set.');\n }\n const url = this.endpoints.oauth2TokenUrl.toString();\n const data = {\n refresh_token: refreshToken,\n client_id: this._clientId,\n client_secret: this._clientSecret,\n grant_type: 'refresh_token',\n };\n let res;\n try {\n const opts = {\n ...OAuth2Client.RETRY_CONFIG,\n method: 'POST',\n url,\n data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(data)),\n };\n authclient_1.AuthClient.setMethodName(opts, 'refreshTokenNoCache');\n // request for new token\n res = await this.transporter.request(opts);\n }\n catch (e) {\n if (e instanceof gaxios_1.GaxiosError &&\n e.message === 'invalid_grant' &&\n e.response?.data &&\n /ReAuth/i.test(e.response.data.error_description)) {\n e.message = JSON.stringify(e.response.data);\n }\n throw e;\n }\n const tokens = res.data;\n // TODO: de-duplicate this code from a few spots\n if (res.data && res.data.expires_in) {\n tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000;\n delete tokens.expires_in;\n }\n this.emit('tokens', tokens);\n return { tokens, res };\n }\n refreshAccessToken(callback) {\n if (callback) {\n this.refreshAccessTokenAsync().then(r => callback(null, r.credentials, r.res), callback);\n }\n else {\n return this.refreshAccessTokenAsync();\n }\n }\n async refreshAccessTokenAsync() {\n const r = await this.refreshToken(this.credentials.refresh_token);\n const tokens = r.tokens;\n tokens.refresh_token = this.credentials.refresh_token;\n this.credentials = tokens;\n return { credentials: this.credentials, res: r.res };\n }\n getAccessToken(callback) {\n if (callback) {\n this.getAccessTokenAsync().then(r => callback(null, r.token, r.res), callback);\n }\n else {\n return this.getAccessTokenAsync();\n }\n }\n async getAccessTokenAsync() {\n const shouldRefresh = !this.credentials.access_token || this.isTokenExpiring();\n if (shouldRefresh) {\n if (!this.credentials.refresh_token) {\n if (this.refreshHandler) {\n const refreshedAccessToken = await this.processAndValidateRefreshHandler();\n if (refreshedAccessToken?.access_token) {\n this.setCredentials(refreshedAccessToken);\n return { token: this.credentials.access_token };\n }\n }\n else {\n throw new Error('No refresh token or refresh handler callback is set.');\n }\n }\n const r = await this.refreshAccessTokenAsync();\n if (!r.credentials || (r.credentials && !r.credentials.access_token)) {\n throw new Error('Could not refresh access token.');\n }\n return { token: r.credentials.access_token, res: r.res };\n }\n else {\n return { token: this.credentials.access_token };\n }\n }\n /**\n * The main authentication interface. It takes an optional url which when\n * present is the endpoint being accessed, and returns a Promise which\n * resolves with authorization header fields.\n *\n * In OAuth2Client, the result has the form:\n * { authorization: 'Bearer ' }\n */\n async getRequestHeaders(url) {\n const headers = (await this.getRequestMetadataAsync(url)).headers;\n return headers;\n }\n async getRequestMetadataAsync(url) {\n url;\n const thisCreds = this.credentials;\n if (!thisCreds.access_token &&\n !thisCreds.refresh_token &&\n !this.apiKey &&\n !this.refreshHandler) {\n throw new Error('No access, refresh token, API key or refresh handler callback is set.');\n }\n if (thisCreds.access_token && !this.isTokenExpiring()) {\n thisCreds.token_type = thisCreds.token_type || 'Bearer';\n const headers = new Headers({\n authorization: thisCreds.token_type + ' ' + thisCreds.access_token,\n });\n return { headers: this.addSharedMetadataHeaders(headers) };\n }\n // If refreshHandler exists, call processAndValidateRefreshHandler().\n if (this.refreshHandler) {\n const refreshedAccessToken = await this.processAndValidateRefreshHandler();\n if (refreshedAccessToken?.access_token) {\n this.setCredentials(refreshedAccessToken);\n const headers = new Headers({\n authorization: 'Bearer ' + this.credentials.access_token,\n });\n return { headers: this.addSharedMetadataHeaders(headers) };\n }\n }\n if (this.apiKey) {\n return { headers: new Headers({ 'X-Goog-Api-Key': this.apiKey }) };\n }\n let r = null;\n let tokens = null;\n try {\n r = await this.refreshToken(thisCreds.refresh_token);\n tokens = r.tokens;\n }\n catch (err) {\n const e = err;\n if (e.response &&\n (e.response.status === 403 || e.response.status === 404)) {\n e.message = `Could not refresh access token: ${e.message}`;\n }\n throw e;\n }\n const credentials = this.credentials;\n credentials.token_type = credentials.token_type || 'Bearer';\n tokens.refresh_token = credentials.refresh_token;\n this.credentials = tokens;\n const headers = new Headers({\n authorization: credentials.token_type + ' ' + tokens.access_token,\n });\n return { headers: this.addSharedMetadataHeaders(headers), res: r.res };\n }\n /**\n * Generates an URL to revoke the given token.\n * @param token The existing token to be revoked.\n *\n * @deprecated use instance method {@link OAuth2Client.getRevokeTokenURL}\n */\n static getRevokeTokenUrl(token) {\n return new OAuth2Client().getRevokeTokenURL(token).toString();\n }\n /**\n * Generates a URL to revoke the given token.\n *\n * @param token The existing token to be revoked.\n */\n getRevokeTokenURL(token) {\n const url = new URL(this.endpoints.oauth2RevokeUrl);\n url.searchParams.append('token', token);\n return url;\n }\n revokeToken(token, callback) {\n const opts = {\n ...OAuth2Client.RETRY_CONFIG,\n url: this.getRevokeTokenURL(token).toString(),\n method: 'POST',\n };\n authclient_1.AuthClient.setMethodName(opts, 'revokeToken');\n if (callback) {\n this.transporter\n .request(opts)\n .then(r => callback(null, r), callback);\n }\n else {\n return this.transporter.request(opts);\n }\n }\n revokeCredentials(callback) {\n if (callback) {\n this.revokeCredentialsAsync().then(res => callback(null, res), callback);\n }\n else {\n return this.revokeCredentialsAsync();\n }\n }\n async revokeCredentialsAsync() {\n const token = this.credentials.access_token;\n this.credentials = {};\n if (token) {\n return this.revokeToken(token);\n }\n else {\n throw new Error('No access token to revoke.');\n }\n }\n request(opts, callback) {\n if (callback) {\n this.requestAsync(opts).then(r => callback(null, r), e => {\n return callback(e, e.response);\n });\n }\n else {\n return this.requestAsync(opts);\n }\n }\n async requestAsync(opts, reAuthRetried = false) {\n try {\n const r = await this.getRequestMetadataAsync();\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);\n this.addUserProjectAndAuthHeaders(opts.headers, r.headers);\n if (this.apiKey) {\n opts.headers.set('X-Goog-Api-Key', this.apiKey);\n }\n return await this.transporter.request(opts);\n }\n catch (e) {\n const res = e.response;\n if (res) {\n const statusCode = res.status;\n // Retry the request for metadata if the following criteria are true:\n // - We haven't already retried. It only makes sense to retry once.\n // - The response was a 401 or a 403\n // - The request didn't send a readableStream\n // - An access_token and refresh_token were available, but either no\n // expiry_date was available or the forceRefreshOnFailure flag is set.\n // The absent expiry_date case can happen when developers stash the\n // access_token and refresh_token for later use, but the access_token\n // fails on the first try because it's expired. Some developers may\n // choose to enable forceRefreshOnFailure to mitigate time-related\n // errors.\n // Or the following criteria are true:\n // - We haven't already retried. It only makes sense to retry once.\n // - The response was a 401 or a 403\n // - The request didn't send a readableStream\n // - No refresh_token was available\n // - An access_token and a refreshHandler callback were available, but\n // either no expiry_date was available or the forceRefreshOnFailure\n // flag is set. The access_token fails on the first try because it's\n // expired. Some developers may choose to enable forceRefreshOnFailure\n // to mitigate time-related errors.\n const mayRequireRefresh = this.credentials &&\n this.credentials.access_token &&\n this.credentials.refresh_token &&\n (!this.credentials.expiry_date || this.forceRefreshOnFailure);\n const mayRequireRefreshWithNoRefreshToken = this.credentials &&\n this.credentials.access_token &&\n !this.credentials.refresh_token &&\n (!this.credentials.expiry_date || this.forceRefreshOnFailure) &&\n this.refreshHandler;\n const isReadableStream = res.config.data instanceof stream.Readable;\n const isAuthErr = statusCode === 401 || statusCode === 403;\n if (!reAuthRetried &&\n isAuthErr &&\n !isReadableStream &&\n mayRequireRefresh) {\n await this.refreshAccessTokenAsync();\n return this.requestAsync(opts, true);\n }\n else if (!reAuthRetried &&\n isAuthErr &&\n !isReadableStream &&\n mayRequireRefreshWithNoRefreshToken) {\n const refreshedAccessToken = await this.processAndValidateRefreshHandler();\n if (refreshedAccessToken?.access_token) {\n this.setCredentials(refreshedAccessToken);\n }\n return this.requestAsync(opts, true);\n }\n }\n throw e;\n }\n }\n verifyIdToken(options, callback) {\n // This function used to accept two arguments instead of an options object.\n // Check the types to help users upgrade with less pain.\n // This check can be removed after a 2.0 release.\n if (callback && typeof callback !== 'function') {\n throw new Error('This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.');\n }\n if (callback) {\n this.verifyIdTokenAsync(options).then(r => callback(null, r), callback);\n }\n else {\n return this.verifyIdTokenAsync(options);\n }\n }\n async verifyIdTokenAsync(options) {\n if (!options.idToken) {\n throw new Error('The verifyIdToken method requires an ID Token');\n }\n const response = await this.getFederatedSignonCertsAsync();\n const login = await this.verifySignedJwtWithCertsAsync(options.idToken, response.certs, options.audience, this.issuers, options.maxExpiry);\n return login;\n }\n /**\n * Obtains information about the provisioned access token. Especially useful\n * if you want to check the scopes that were provisioned to a given token.\n *\n * @param accessToken Required. The Access Token for which you want to get\n * user info.\n */\n async getTokenInfo(accessToken) {\n const { data } = await this.transporter.request({\n ...OAuth2Client.RETRY_CONFIG,\n method: 'POST',\n headers: {\n 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',\n authorization: `Bearer ${accessToken}`,\n },\n url: this.endpoints.tokenInfoUrl.toString(),\n });\n const info = Object.assign({\n expiry_date: new Date().getTime() + data.expires_in * 1000,\n scopes: data.scope.split(' '),\n }, data);\n delete info.expires_in;\n delete info.scope;\n return info;\n }\n getFederatedSignonCerts(callback) {\n if (callback) {\n this.getFederatedSignonCertsAsync().then(r => callback(null, r.certs, r.res), callback);\n }\n else {\n return this.getFederatedSignonCertsAsync();\n }\n }\n async getFederatedSignonCertsAsync() {\n const nowTime = new Date().getTime();\n const format = (0, crypto_1.hasBrowserCrypto)()\n ? CertificateFormat.JWK\n : CertificateFormat.PEM;\n if (this.certificateExpiry &&\n nowTime < this.certificateExpiry.getTime() &&\n this.certificateCacheFormat === format) {\n return { certs: this.certificateCache, format };\n }\n let res;\n let url;\n switch (format) {\n case CertificateFormat.PEM:\n url = this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();\n break;\n case CertificateFormat.JWK:\n url = this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();\n break;\n default:\n throw new Error(`Unsupported certificate format ${format}`);\n }\n try {\n const opts = {\n ...OAuth2Client.RETRY_CONFIG,\n url,\n };\n authclient_1.AuthClient.setMethodName(opts, 'getFederatedSignonCertsAsync');\n res = await this.transporter.request(opts);\n }\n catch (e) {\n if (e instanceof Error) {\n e.message = `Failed to retrieve verification certificates: ${e.message}`;\n }\n throw e;\n }\n const cacheControl = res?.headers.get('cache-control');\n let cacheAge = -1;\n if (cacheControl) {\n const maxAge = /max-age=(?[0-9]+)/.exec(cacheControl)?.groups\n ?.maxAge;\n if (maxAge) {\n // Cache results with max-age (in seconds)\n cacheAge = Number(maxAge) * 1000; // milliseconds\n }\n }\n let certificates = {};\n switch (format) {\n case CertificateFormat.PEM:\n certificates = res.data;\n break;\n case CertificateFormat.JWK:\n for (const key of res.data.keys) {\n certificates[key.kid] = key;\n }\n break;\n default:\n throw new Error(`Unsupported certificate format ${format}`);\n }\n const now = new Date();\n this.certificateExpiry =\n cacheAge === -1 ? null : new Date(now.getTime() + cacheAge);\n this.certificateCache = certificates;\n this.certificateCacheFormat = format;\n return { certs: certificates, format, res };\n }\n getIapPublicKeys(callback) {\n if (callback) {\n this.getIapPublicKeysAsync().then(r => callback(null, r.pubkeys, r.res), callback);\n }\n else {\n return this.getIapPublicKeysAsync();\n }\n }\n async getIapPublicKeysAsync() {\n let res;\n const url = this.endpoints.oauth2IapPublicKeyUrl.toString();\n try {\n const opts = {\n ...OAuth2Client.RETRY_CONFIG,\n url,\n };\n authclient_1.AuthClient.setMethodName(opts, 'getIapPublicKeysAsync');\n res = await this.transporter.request(opts);\n }\n catch (e) {\n if (e instanceof Error) {\n e.message = `Failed to retrieve verification certificates: ${e.message}`;\n }\n throw e;\n }\n return { pubkeys: res.data, res };\n }\n verifySignedJwtWithCerts() {\n // To make the code compatible with browser SubtleCrypto we need to make\n // this method async.\n throw new Error('verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.');\n }\n /**\n * Verify the id token is signed with the correct certificate\n * and is from the correct audience.\n * @param jwt The jwt to verify (The ID Token in this case).\n * @param certs The array of certs to test the jwt against.\n * @param requiredAudience The audience to test the jwt against.\n * @param issuers The allowed issuers of the jwt (Optional).\n * @param maxExpiry The max expiry the certificate can be (Optional).\n * @return Returns a promise resolving to LoginTicket on verification.\n */\n async verifySignedJwtWithCertsAsync(jwt, certs, requiredAudience, issuers, maxExpiry) {\n const crypto = (0, crypto_1.createCrypto)();\n if (!maxExpiry) {\n maxExpiry = OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_;\n }\n const segments = jwt.split('.');\n if (segments.length !== 3) {\n throw new Error('Wrong number of segments in token: ' + jwt);\n }\n const signed = segments[0] + '.' + segments[1];\n let signature = segments[2];\n let envelope;\n let payload;\n try {\n envelope = JSON.parse(crypto.decodeBase64StringUtf8(segments[0]));\n }\n catch (err) {\n if (err instanceof Error) {\n err.message = `Can't parse token envelope: ${segments[0]}': ${err.message}`;\n }\n throw err;\n }\n if (!envelope) {\n throw new Error(\"Can't parse token envelope: \" + segments[0]);\n }\n try {\n payload = JSON.parse(crypto.decodeBase64StringUtf8(segments[1]));\n }\n catch (err) {\n if (err instanceof Error) {\n err.message = `Can't parse token payload '${segments[0]}`;\n }\n throw err;\n }\n if (!payload) {\n throw new Error(\"Can't parse token payload: \" + segments[1]);\n }\n if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) {\n // If this is not present, then there's no reason to attempt verification\n throw new Error('No pem found for envelope: ' + JSON.stringify(envelope));\n }\n const cert = certs[envelope.kid];\n if (envelope.alg === 'ES256') {\n signature = formatEcdsa.joseToDer(signature, 'ES256').toString('base64');\n }\n const verified = await crypto.verify(cert, signed, signature);\n if (!verified) {\n throw new Error('Invalid token signature: ' + jwt);\n }\n if (!payload.iat) {\n throw new Error('No issue time in token: ' + JSON.stringify(payload));\n }\n if (!payload.exp) {\n throw new Error('No expiration time in token: ' + JSON.stringify(payload));\n }\n const iat = Number(payload.iat);\n if (isNaN(iat))\n throw new Error('iat field using invalid format');\n const exp = Number(payload.exp);\n if (isNaN(exp))\n throw new Error('exp field using invalid format');\n const now = new Date().getTime() / 1000;\n if (exp >= now + maxExpiry) {\n throw new Error('Expiration time too far in future: ' + JSON.stringify(payload));\n }\n const earliest = iat - OAuth2Client.CLOCK_SKEW_SECS_;\n const latest = exp + OAuth2Client.CLOCK_SKEW_SECS_;\n if (now < earliest) {\n throw new Error('Token used too early, ' +\n now +\n ' < ' +\n earliest +\n ': ' +\n JSON.stringify(payload));\n }\n if (now > latest) {\n throw new Error('Token used too late, ' +\n now +\n ' > ' +\n latest +\n ': ' +\n JSON.stringify(payload));\n }\n if (issuers && issuers.indexOf(payload.iss) < 0) {\n throw new Error('Invalid issuer, expected one of [' +\n issuers +\n '], but got ' +\n payload.iss);\n }\n // Check the audience matches if we have one\n if (typeof requiredAudience !== 'undefined' && requiredAudience !== null) {\n const aud = payload.aud;\n let audVerified = false;\n // If the requiredAudience is an array, check if it contains token\n // audience\n if (requiredAudience.constructor === Array) {\n audVerified = requiredAudience.indexOf(aud) > -1;\n }\n else {\n audVerified = aud === requiredAudience;\n }\n if (!audVerified) {\n throw new Error('Wrong recipient, payload audience != requiredAudience');\n }\n }\n return new loginticket_1.LoginTicket(envelope, payload);\n }\n /**\n * Returns a promise that resolves with AccessTokenResponse type if\n * refreshHandler is defined.\n * If not, nothing is returned.\n */\n async processAndValidateRefreshHandler() {\n if (this.refreshHandler) {\n const accessTokenResponse = await this.refreshHandler();\n if (!accessTokenResponse.access_token) {\n throw new Error('No access token is returned by the refreshHandler callback.');\n }\n return accessTokenResponse;\n }\n return;\n }\n /**\n * Returns true if a token is expired or will expire within\n * eagerRefreshThresholdMillismilliseconds.\n * If there is no expiry time, assumes the token is not expired or expiring.\n */\n isTokenExpiring() {\n const expiryDate = this.credentials.expiry_date;\n return expiryDate\n ? expiryDate <= new Date().getTime() + this.eagerRefreshThresholdMillis\n : false;\n }\n}\nexports.OAuth2Client = OAuth2Client;\n//# sourceMappingURL=oauth2client.js.map", "\"use strict\";\n// Copyright 2013 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Compute = void 0;\nconst gaxios_1 = require(\"gaxios\");\nconst gcpMetadata = require(\"gcp-metadata\");\nconst oauth2client_1 = require(\"./oauth2client\");\nclass Compute extends oauth2client_1.OAuth2Client {\n serviceAccountEmail;\n scopes;\n /**\n * Google Compute Engine service account credentials.\n *\n * Retrieve access token from the metadata server.\n * See: https://cloud.google.com/compute/docs/access/authenticate-workloads#applications\n */\n constructor(options = {}) {\n super(options);\n // Start with an expired refresh token, which will automatically be\n // refreshed before the first API call is made.\n this.credentials = { expiry_date: 1, refresh_token: 'compute-placeholder' };\n this.serviceAccountEmail = options.serviceAccountEmail || 'default';\n this.scopes = Array.isArray(options.scopes)\n ? options.scopes\n : options.scopes\n ? [options.scopes]\n : [];\n }\n /**\n * Refreshes the access token.\n * @param refreshToken Unused parameter\n */\n async refreshTokenNoCache() {\n const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`;\n let data;\n try {\n const instanceOptions = {\n property: tokenPath,\n };\n if (this.scopes.length > 0) {\n instanceOptions.params = {\n scopes: this.scopes.join(','),\n };\n }\n data = await gcpMetadata.instance(instanceOptions);\n }\n catch (e) {\n if (e instanceof gaxios_1.GaxiosError) {\n e.message = `Could not refresh access token: ${e.message}`;\n this.wrapError(e);\n }\n throw e;\n }\n const tokens = data;\n if (data && data.expires_in) {\n tokens.expiry_date = new Date().getTime() + data.expires_in * 1000;\n delete tokens.expires_in;\n }\n this.emit('tokens', tokens);\n return { tokens, res: null };\n }\n /**\n * Fetches an ID token.\n * @param targetAudience the audience for the fetched ID token.\n */\n async fetchIdToken(targetAudience) {\n const idTokenPath = `service-accounts/${this.serviceAccountEmail}/identity` +\n `?format=full&audience=${targetAudience}`;\n let idToken;\n try {\n const instanceOptions = {\n property: idTokenPath,\n };\n idToken = await gcpMetadata.instance(instanceOptions);\n }\n catch (e) {\n if (e instanceof Error) {\n e.message = `Could not fetch ID token: ${e.message}`;\n }\n throw e;\n }\n return idToken;\n }\n wrapError(e) {\n const res = e.response;\n if (res && res.status) {\n e.status = res.status;\n if (res.status === 403) {\n e.message =\n 'A Forbidden error was returned while attempting to retrieve an access ' +\n 'token for the Compute Engine built-in service account. This may be because the Compute ' +\n 'Engine instance does not have the correct permission scopes specified: ' +\n e.message;\n }\n else if (res.status === 404) {\n e.message =\n 'A Not Found error was returned while attempting to retrieve an access' +\n 'token for the Compute Engine built-in service account. This may be because the Compute ' +\n 'Engine instance does not have any permission scopes specified: ' +\n e.message;\n }\n }\n }\n}\nexports.Compute = Compute;\n//# sourceMappingURL=computeclient.js.map", "\"use strict\";\n// Copyright 2020 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.IdTokenClient = void 0;\nconst oauth2client_1 = require(\"./oauth2client\");\nclass IdTokenClient extends oauth2client_1.OAuth2Client {\n targetAudience;\n idTokenProvider;\n /**\n * Google ID Token client\n *\n * Retrieve ID token from the metadata server.\n * See: https://cloud.google.com/docs/authentication/get-id-token#metadata-server\n */\n constructor(options) {\n super(options);\n this.targetAudience = options.targetAudience;\n this.idTokenProvider = options.idTokenProvider;\n }\n async getRequestMetadataAsync() {\n if (!this.credentials.id_token ||\n !this.credentials.expiry_date ||\n this.isTokenExpiring()) {\n const idToken = await this.idTokenProvider.fetchIdToken(this.targetAudience);\n this.credentials = {\n id_token: idToken,\n expiry_date: this.getIdTokenExpiryDate(idToken),\n };\n }\n const headers = new Headers({\n authorization: 'Bearer ' + this.credentials.id_token,\n });\n return { headers };\n }\n getIdTokenExpiryDate(idToken) {\n const payloadB64 = idToken.split('.')[1];\n if (payloadB64) {\n const payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('ascii'));\n return payload.exp * 1000;\n }\n }\n}\nexports.IdTokenClient = IdTokenClient;\n//# sourceMappingURL=idtokenclient.js.map", "\"use strict\";\n// Copyright 2018 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.GCPEnv = void 0;\nexports.clear = clear;\nexports.getEnv = getEnv;\nconst gcpMetadata = require(\"gcp-metadata\");\nvar GCPEnv;\n(function (GCPEnv) {\n GCPEnv[\"APP_ENGINE\"] = \"APP_ENGINE\";\n GCPEnv[\"KUBERNETES_ENGINE\"] = \"KUBERNETES_ENGINE\";\n GCPEnv[\"CLOUD_FUNCTIONS\"] = \"CLOUD_FUNCTIONS\";\n GCPEnv[\"COMPUTE_ENGINE\"] = \"COMPUTE_ENGINE\";\n GCPEnv[\"CLOUD_RUN\"] = \"CLOUD_RUN\";\n GCPEnv[\"NONE\"] = \"NONE\";\n})(GCPEnv || (exports.GCPEnv = GCPEnv = {}));\nlet envPromise;\nfunction clear() {\n envPromise = undefined;\n}\nasync function getEnv() {\n if (envPromise) {\n return envPromise;\n }\n envPromise = getEnvMemoized();\n return envPromise;\n}\nasync function getEnvMemoized() {\n let env = GCPEnv.NONE;\n if (isAppEngine()) {\n env = GCPEnv.APP_ENGINE;\n }\n else if (isCloudFunction()) {\n env = GCPEnv.CLOUD_FUNCTIONS;\n }\n else if (await isComputeEngine()) {\n if (await isKubernetesEngine()) {\n env = GCPEnv.KUBERNETES_ENGINE;\n }\n else if (isCloudRun()) {\n env = GCPEnv.CLOUD_RUN;\n }\n else {\n env = GCPEnv.COMPUTE_ENGINE;\n }\n }\n else {\n env = GCPEnv.NONE;\n }\n return env;\n}\nfunction isAppEngine() {\n return !!(process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME);\n}\nfunction isCloudFunction() {\n return !!(process.env.FUNCTION_NAME || process.env.FUNCTION_TARGET);\n}\n/**\n * This check only verifies that the environment is running knative.\n * This must be run *after* checking for Kubernetes, otherwise it will\n * return a false positive.\n */\nfunction isCloudRun() {\n return !!process.env.K_CONFIGURATION;\n}\nasync function isKubernetesEngine() {\n try {\n await gcpMetadata.instance('attributes/cluster-name');\n return true;\n }\n catch (e) {\n return false;\n }\n}\nasync function isComputeEngine() {\n return gcpMetadata.isAvailable();\n}\n//# sourceMappingURL=envDetect.js.map", "/*global module, process*/\nvar Buffer = require('safe-buffer').Buffer;\nvar Stream = require('stream');\nvar util = require('util');\n\nfunction DataStream(data) {\n this.buffer = null;\n this.writable = true;\n this.readable = true;\n\n // No input\n if (!data) {\n this.buffer = Buffer.alloc(0);\n return this;\n }\n\n // Stream\n if (typeof data.pipe === 'function') {\n this.buffer = Buffer.alloc(0);\n data.pipe(this);\n return this;\n }\n\n // Buffer or String\n // or Object (assumedly a passworded key)\n if (data.length || typeof data === 'object') {\n this.buffer = data;\n this.writable = false;\n process.nextTick(function () {\n this.emit('end', data);\n this.readable = false;\n this.emit('close');\n }.bind(this));\n return this;\n }\n\n throw new TypeError('Unexpected data type ('+ typeof data + ')');\n}\nutil.inherits(DataStream, Stream);\n\nDataStream.prototype.write = function write(data) {\n this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]);\n this.emit('data', data);\n};\n\nDataStream.prototype.end = function end(data) {\n if (data)\n this.write(data);\n this.emit('end', data);\n this.emit('close');\n this.writable = false;\n this.readable = false;\n};\n\nmodule.exports = DataStream;\n", "/*jshint node:true */\n'use strict';\nvar Buffer = require('buffer').Buffer; // browserify\nvar SlowBuffer = require('buffer').SlowBuffer;\n\nmodule.exports = bufferEq;\n\nfunction bufferEq(a, b) {\n\n // shortcutting on type is necessary for correctness\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n return false;\n }\n\n // buffer sizes should be well-known information, so despite this\n // shortcutting, it doesn't leak any information about the *contents* of the\n // buffers.\n if (a.length !== b.length) {\n return false;\n }\n\n var c = 0;\n for (var i = 0; i < a.length; i++) {\n /*jshint bitwise:false */\n c |= a[i] ^ b[i]; // XOR\n }\n return c === 0;\n}\n\nbufferEq.install = function() {\n Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) {\n return bufferEq(this, that);\n };\n};\n\nvar origBufEqual = Buffer.prototype.equal;\nvar origSlowBufEqual = SlowBuffer.prototype.equal;\nbufferEq.restore = function() {\n Buffer.prototype.equal = origBufEqual;\n SlowBuffer.prototype.equal = origSlowBufEqual;\n};\n", "var Buffer = require('safe-buffer').Buffer;\nvar crypto = require('crypto');\nvar formatEcdsa = require('ecdsa-sig-formatter');\nvar util = require('util');\n\nvar MSG_INVALID_ALGORITHM = '\"%s\" is not a valid algorithm.\\n Supported algorithms are:\\n \"HS256\", \"HS384\", \"HS512\", \"RS256\", \"RS384\", \"RS512\", \"PS256\", \"PS384\", \"PS512\", \"ES256\", \"ES384\", \"ES512\" and \"none\".'\nvar MSG_INVALID_SECRET = 'secret must be a string or buffer';\nvar MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer';\nvar MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object';\n\nvar supportsKeyObjects = typeof crypto.createPublicKey === 'function';\nif (supportsKeyObjects) {\n MSG_INVALID_VERIFIER_KEY += ' or a KeyObject';\n MSG_INVALID_SECRET += 'or a KeyObject';\n}\n\nfunction checkIsPublicKey(key) {\n if (Buffer.isBuffer(key)) {\n return;\n }\n\n if (typeof key === 'string') {\n return;\n }\n\n if (!supportsKeyObjects) {\n throw typeError(MSG_INVALID_VERIFIER_KEY);\n }\n\n if (typeof key !== 'object') {\n throw typeError(MSG_INVALID_VERIFIER_KEY);\n }\n\n if (typeof key.type !== 'string') {\n throw typeError(MSG_INVALID_VERIFIER_KEY);\n }\n\n if (typeof key.asymmetricKeyType !== 'string') {\n throw typeError(MSG_INVALID_VERIFIER_KEY);\n }\n\n if (typeof key.export !== 'function') {\n throw typeError(MSG_INVALID_VERIFIER_KEY);\n }\n};\n\nfunction checkIsPrivateKey(key) {\n if (Buffer.isBuffer(key)) {\n return;\n }\n\n if (typeof key === 'string') {\n return;\n }\n\n if (typeof key === 'object') {\n return;\n }\n\n throw typeError(MSG_INVALID_SIGNER_KEY);\n};\n\nfunction checkIsSecretKey(key) {\n if (Buffer.isBuffer(key)) {\n return;\n }\n\n if (typeof key === 'string') {\n return key;\n }\n\n if (!supportsKeyObjects) {\n throw typeError(MSG_INVALID_SECRET);\n }\n\n if (typeof key !== 'object') {\n throw typeError(MSG_INVALID_SECRET);\n }\n\n if (key.type !== 'secret') {\n throw typeError(MSG_INVALID_SECRET);\n }\n\n if (typeof key.export !== 'function') {\n throw typeError(MSG_INVALID_SECRET);\n }\n}\n\nfunction fromBase64(base64) {\n return base64\n .replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n}\n\nfunction toBase64(base64url) {\n base64url = base64url.toString();\n\n var padding = 4 - base64url.length % 4;\n if (padding !== 4) {\n for (var i = 0; i < padding; ++i) {\n base64url += '=';\n }\n }\n\n return base64url\n .replace(/\\-/g, '+')\n .replace(/_/g, '/');\n}\n\nfunction typeError(template) {\n var args = [].slice.call(arguments, 1);\n var errMsg = util.format.bind(util, template).apply(null, args);\n return new TypeError(errMsg);\n}\n\nfunction bufferOrString(obj) {\n return Buffer.isBuffer(obj) || typeof obj === 'string';\n}\n\nfunction normalizeInput(thing) {\n if (!bufferOrString(thing))\n thing = JSON.stringify(thing);\n return thing;\n}\n\nfunction createHmacSigner(bits) {\n return function sign(thing, secret) {\n checkIsSecretKey(secret);\n thing = normalizeInput(thing);\n var hmac = crypto.createHmac('sha' + bits, secret);\n var sig = (hmac.update(thing), hmac.digest('base64'))\n return fromBase64(sig);\n }\n}\n\nvar bufferEqual;\nvar timingSafeEqual = 'timingSafeEqual' in crypto ? function timingSafeEqual(a, b) {\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n\n return crypto.timingSafeEqual(a, b)\n} : function timingSafeEqual(a, b) {\n if (!bufferEqual) {\n bufferEqual = require('buffer-equal-constant-time');\n }\n\n return bufferEqual(a, b)\n}\n\nfunction createHmacVerifier(bits) {\n return function verify(thing, signature, secret) {\n var computedSig = createHmacSigner(bits)(thing, secret);\n return timingSafeEqual(Buffer.from(signature), Buffer.from(computedSig));\n }\n}\n\nfunction createKeySigner(bits) {\n return function sign(thing, privateKey) {\n checkIsPrivateKey(privateKey);\n thing = normalizeInput(thing);\n // Even though we are specifying \"RSA\" here, this works with ECDSA\n // keys as well.\n var signer = crypto.createSign('RSA-SHA' + bits);\n var sig = (signer.update(thing), signer.sign(privateKey, 'base64'));\n return fromBase64(sig);\n }\n}\n\nfunction createKeyVerifier(bits) {\n return function verify(thing, signature, publicKey) {\n checkIsPublicKey(publicKey);\n thing = normalizeInput(thing);\n signature = toBase64(signature);\n var verifier = crypto.createVerify('RSA-SHA' + bits);\n verifier.update(thing);\n return verifier.verify(publicKey, signature, 'base64');\n }\n}\n\nfunction createPSSKeySigner(bits) {\n return function sign(thing, privateKey) {\n checkIsPrivateKey(privateKey);\n thing = normalizeInput(thing);\n var signer = crypto.createSign('RSA-SHA' + bits);\n var sig = (signer.update(thing), signer.sign({\n key: privateKey,\n padding: crypto.constants.RSA_PKCS1_PSS_PADDING,\n saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST\n }, 'base64'));\n return fromBase64(sig);\n }\n}\n\nfunction createPSSKeyVerifier(bits) {\n return function verify(thing, signature, publicKey) {\n checkIsPublicKey(publicKey);\n thing = normalizeInput(thing);\n signature = toBase64(signature);\n var verifier = crypto.createVerify('RSA-SHA' + bits);\n verifier.update(thing);\n return verifier.verify({\n key: publicKey,\n padding: crypto.constants.RSA_PKCS1_PSS_PADDING,\n saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST\n }, signature, 'base64');\n }\n}\n\nfunction createECDSASigner(bits) {\n var inner = createKeySigner(bits);\n return function sign() {\n var signature = inner.apply(null, arguments);\n signature = formatEcdsa.derToJose(signature, 'ES' + bits);\n return signature;\n };\n}\n\nfunction createECDSAVerifer(bits) {\n var inner = createKeyVerifier(bits);\n return function verify(thing, signature, publicKey) {\n signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64');\n var result = inner(thing, signature, publicKey);\n return result;\n };\n}\n\nfunction createNoneSigner() {\n return function sign() {\n return '';\n }\n}\n\nfunction createNoneVerifier() {\n return function verify(thing, signature) {\n return signature === '';\n }\n}\n\nmodule.exports = function jwa(algorithm) {\n var signerFactories = {\n hs: createHmacSigner,\n rs: createKeySigner,\n ps: createPSSKeySigner,\n es: createECDSASigner,\n none: createNoneSigner,\n }\n var verifierFactories = {\n hs: createHmacVerifier,\n rs: createKeyVerifier,\n ps: createPSSKeyVerifier,\n es: createECDSAVerifer,\n none: createNoneVerifier,\n }\n var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);\n if (!match)\n throw typeError(MSG_INVALID_ALGORITHM, algorithm);\n var algo = (match[1] || match[3]).toLowerCase();\n var bits = match[2];\n\n return {\n sign: signerFactories[algo](bits),\n verify: verifierFactories[algo](bits),\n }\n};\n", "/*global module*/\nvar Buffer = require('buffer').Buffer;\n\nmodule.exports = function toString(obj) {\n if (typeof obj === 'string')\n return obj;\n if (typeof obj === 'number' || Buffer.isBuffer(obj))\n return obj.toString();\n return JSON.stringify(obj);\n};\n", "/*global module*/\nvar Buffer = require('safe-buffer').Buffer;\nvar DataStream = require('./data-stream');\nvar jwa = require('jwa');\nvar Stream = require('stream');\nvar toString = require('./tostring');\nvar util = require('util');\n\nfunction base64url(string, encoding) {\n return Buffer\n .from(string, encoding)\n .toString('base64')\n .replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n}\n\nfunction jwsSecuredInput(header, payload, encoding) {\n encoding = encoding || 'utf8';\n var encodedHeader = base64url(toString(header), 'binary');\n var encodedPayload = base64url(toString(payload), encoding);\n return util.format('%s.%s', encodedHeader, encodedPayload);\n}\n\nfunction jwsSign(opts) {\n var header = opts.header;\n var payload = opts.payload;\n var secretOrKey = opts.secret || opts.privateKey;\n var encoding = opts.encoding;\n var algo = jwa(header.alg);\n var securedInput = jwsSecuredInput(header, payload, encoding);\n var signature = algo.sign(securedInput, secretOrKey);\n return util.format('%s.%s', securedInput, signature);\n}\n\nfunction SignStream(opts) {\n var secret = opts.secret||opts.privateKey||opts.key;\n var secretStream = new DataStream(secret);\n this.readable = true;\n this.header = opts.header;\n this.encoding = opts.encoding;\n this.secret = this.privateKey = this.key = secretStream;\n this.payload = new DataStream(opts.payload);\n this.secret.once('close', function () {\n if (!this.payload.writable && this.readable)\n this.sign();\n }.bind(this));\n\n this.payload.once('close', function () {\n if (!this.secret.writable && this.readable)\n this.sign();\n }.bind(this));\n}\nutil.inherits(SignStream, Stream);\n\nSignStream.prototype.sign = function sign() {\n try {\n var signature = jwsSign({\n header: this.header,\n payload: this.payload.buffer,\n secret: this.secret.buffer,\n encoding: this.encoding\n });\n this.emit('done', signature);\n this.emit('data', signature);\n this.emit('end');\n this.readable = false;\n return signature;\n } catch (e) {\n this.readable = false;\n this.emit('error', e);\n this.emit('close');\n }\n};\n\nSignStream.sign = jwsSign;\n\nmodule.exports = SignStream;\n", "/*global module*/\nvar Buffer = require('safe-buffer').Buffer;\nvar DataStream = require('./data-stream');\nvar jwa = require('jwa');\nvar Stream = require('stream');\nvar toString = require('./tostring');\nvar util = require('util');\nvar JWS_REGEX = /^[a-zA-Z0-9\\-_]+?\\.[a-zA-Z0-9\\-_]+?\\.([a-zA-Z0-9\\-_]+)?$/;\n\nfunction isObject(thing) {\n return Object.prototype.toString.call(thing) === '[object Object]';\n}\n\nfunction safeJsonParse(thing) {\n if (isObject(thing))\n return thing;\n try { return JSON.parse(thing); }\n catch (e) { return undefined; }\n}\n\nfunction headerFromJWS(jwsSig) {\n var encodedHeader = jwsSig.split('.', 1)[0];\n return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary'));\n}\n\nfunction securedInputFromJWS(jwsSig) {\n return jwsSig.split('.', 2).join('.');\n}\n\nfunction signatureFromJWS(jwsSig) {\n return jwsSig.split('.')[2];\n}\n\nfunction payloadFromJWS(jwsSig, encoding) {\n encoding = encoding || 'utf8';\n var payload = jwsSig.split('.')[1];\n return Buffer.from(payload, 'base64').toString(encoding);\n}\n\nfunction isValidJws(string) {\n return JWS_REGEX.test(string) && !!headerFromJWS(string);\n}\n\nfunction jwsVerify(jwsSig, algorithm, secretOrKey) {\n if (!algorithm) {\n var err = new Error(\"Missing algorithm parameter for jws.verify\");\n err.code = \"MISSING_ALGORITHM\";\n throw err;\n }\n jwsSig = toString(jwsSig);\n var signature = signatureFromJWS(jwsSig);\n var securedInput = securedInputFromJWS(jwsSig);\n var algo = jwa(algorithm);\n return algo.verify(securedInput, signature, secretOrKey);\n}\n\nfunction jwsDecode(jwsSig, opts) {\n opts = opts || {};\n jwsSig = toString(jwsSig);\n\n if (!isValidJws(jwsSig))\n return null;\n\n var header = headerFromJWS(jwsSig);\n\n if (!header)\n return null;\n\n var payload = payloadFromJWS(jwsSig);\n if (header.typ === 'JWT' || opts.json)\n payload = JSON.parse(payload, opts.encoding);\n\n return {\n header: header,\n payload: payload,\n signature: signatureFromJWS(jwsSig)\n };\n}\n\nfunction VerifyStream(opts) {\n opts = opts || {};\n var secretOrKey = opts.secret||opts.publicKey||opts.key;\n var secretStream = new DataStream(secretOrKey);\n this.readable = true;\n this.algorithm = opts.algorithm;\n this.encoding = opts.encoding;\n this.secret = this.publicKey = this.key = secretStream;\n this.signature = new DataStream(opts.signature);\n this.secret.once('close', function () {\n if (!this.signature.writable && this.readable)\n this.verify();\n }.bind(this));\n\n this.signature.once('close', function () {\n if (!this.secret.writable && this.readable)\n this.verify();\n }.bind(this));\n}\nutil.inherits(VerifyStream, Stream);\nVerifyStream.prototype.verify = function verify() {\n try {\n var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer);\n var obj = jwsDecode(this.signature.buffer, this.encoding);\n this.emit('done', valid, obj);\n this.emit('data', valid);\n this.emit('end');\n this.readable = false;\n return valid;\n } catch (e) {\n this.readable = false;\n this.emit('error', e);\n this.emit('close');\n }\n};\n\nVerifyStream.decode = jwsDecode;\nVerifyStream.isValid = isValidJws;\nVerifyStream.verify = jwsVerify;\n\nmodule.exports = VerifyStream;\n", "/*global exports*/\nvar SignStream = require('./lib/sign-stream');\nvar VerifyStream = require('./lib/verify-stream');\n\nvar ALGORITHMS = [\n 'HS256', 'HS384', 'HS512',\n 'RS256', 'RS384', 'RS512',\n 'PS256', 'PS384', 'PS512',\n 'ES256', 'ES384', 'ES512'\n];\n\nexports.ALGORITHMS = ALGORITHMS;\nexports.sign = SignStream.sign;\nexports.verify = VerifyStream.verify;\nexports.decode = VerifyStream.decode;\nexports.isValid = VerifyStream.isValid;\nexports.createSign = function createSign(opts) {\n return new SignStream(opts);\n};\nexports.createVerify = function createVerify(opts) {\n return new VerifyStream(opts);\n};\n", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.GoogleToken = void 0;\nvar fs = _interopRequireWildcard(require(\"fs\"));\nvar _gaxios = require(\"gaxios\");\nvar jws = _interopRequireWildcard(require(\"jws\"));\nvar path = _interopRequireWildcard(require(\"path\"));\nvar _util = require(\"util\");\nfunction _interopRequireWildcard(e, t) { if (\"function\" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, \"default\": e }; if (null === e || \"object\" != _typeof(e) && \"function\" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t3 in e) \"default\" !== _t3 && {}.hasOwnProperty.call(e, _t3) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t3)) && (i.get || i.set) ? o(f, _t3, i) : f[_t3] = e[_t3]); return f; })(e, t); }\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _classPrivateMethodInitSpec(e, a) { _checkPrivateRedeclaration(e, a), a.add(e); }\nfunction _classPrivateFieldInitSpec(e, t, a) { _checkPrivateRedeclaration(e, t), t.set(e, a); }\nfunction _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError(\"Cannot initialize the same private elements twice on an object\"); }\nfunction _classPrivateFieldSet(s, a, r) { return s.set(_assertClassBrand(s, a), r), r; }\nfunction _classPrivateFieldGet(s, a) { return s.get(_assertClassBrand(s, a)); }\nfunction _assertClassBrand(e, t, n) { if (\"function\" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError(\"Private element is not present on this object\"); }\nfunction _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, \"value\" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }\nfunction _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, \"prototype\", { writable: !1 }), e; }\nfunction _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError(\"Cannot call a class as a function\"); }\nfunction _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }\nfunction _possibleConstructorReturn(t, e) { if (e && (\"object\" == _typeof(e) || \"function\" == typeof e)) return e; if (void 0 !== e) throw new TypeError(\"Derived constructors may only return object or undefined\"); return _assertThisInitialized(t); }\nfunction _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); return e; }\nfunction _inherits(t, e) { if (\"function\" != typeof e && null !== e) throw new TypeError(\"Super expression must either be null or a function\"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, \"prototype\", { writable: !1 }), e && _setPrototypeOf(t, e); }\nfunction _wrapNativeSuper(t) { var r = \"function\" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if (\"function\" != typeof t) throw new TypeError(\"Super expression must either be null or a function\"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); }\nfunction _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; }\nfunction _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }\nfunction _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf(\"[native code]\"); } catch (n) { return \"function\" == typeof t; } }\nfunction _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }\nfunction _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = \"function\" == typeof Symbol ? Symbol : {}, n = r.iterator || \"@@iterator\", o = r.toStringTag || \"@@toStringTag\"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, \"_invoke\", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError(\"Generator is already running\"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = \"next\"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError(\"iterator result is not an object\"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i[\"return\"]) && t.call(i), c < 2 && (u = TypeError(\"The iterator does not provide a '\" + o + \"' method\"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, \"GeneratorFunction\")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, \"constructor\", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, \"constructor\", GeneratorFunction), GeneratorFunction.displayName = \"GeneratorFunction\", _regeneratorDefine2(GeneratorFunctionPrototype, o, \"GeneratorFunction\"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, \"Generator\"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, \"toString\", function () { return \"[object Generator]\"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }\nfunction _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, \"\", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { if (r) i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n;else { var o = function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); }; o(\"next\", 0), o(\"throw\", 1), o(\"return\", 2); } }, _regeneratorDefine2(e, r, n, t); }\nfunction asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }\nfunction _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, \"next\", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, \"throw\", n); } _next(void 0); }); }; } /**\n * Copyright 2018 Google LLC\n *\n * Distributed under MIT license.\n * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT\n */\nvar readFile = fs.readFile ? (0, _util.promisify)(fs.readFile) : /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {\n return _regenerator().w(function (_context) {\n while (1) switch (_context.n) {\n case 0:\n throw new ErrorWithCode('use key rather than keyFile.', 'MISSING_CREDENTIALS');\n case 1:\n return _context.a(2);\n }\n }, _callee);\n}));\nvar GOOGLE_TOKEN_URL = 'https://oauth2.googleapis.com/token';\nvar GOOGLE_REVOKE_TOKEN_URL = 'https://oauth2.googleapis.com/revoke?token=';\nvar ErrorWithCode = /*#__PURE__*/function (_Error) {\n function ErrorWithCode(message, code) {\n var _this;\n _classCallCheck(this, ErrorWithCode);\n _this = _callSuper(this, ErrorWithCode, [message]);\n _defineProperty(_this, \"code\", void 0);\n _this.code = code;\n return _this;\n }\n _inherits(ErrorWithCode, _Error);\n return _createClass(ErrorWithCode);\n}(/*#__PURE__*/_wrapNativeSuper(Error));\nvar _inFlightRequest = /*#__PURE__*/new WeakMap();\nvar _GoogleToken_brand = /*#__PURE__*/new WeakSet();\nvar GoogleToken = exports.GoogleToken = /*#__PURE__*/function () {\n /**\n * Create a GoogleToken.\n *\n * @param options Configuration object.\n */\n function GoogleToken(_options) {\n _classCallCheck(this, GoogleToken);\n _classPrivateMethodInitSpec(this, _GoogleToken_brand);\n _defineProperty(this, \"expiresAt\", void 0);\n _defineProperty(this, \"key\", void 0);\n _defineProperty(this, \"keyFile\", void 0);\n _defineProperty(this, \"iss\", void 0);\n _defineProperty(this, \"sub\", void 0);\n _defineProperty(this, \"scope\", void 0);\n _defineProperty(this, \"rawToken\", void 0);\n _defineProperty(this, \"tokenExpires\", void 0);\n _defineProperty(this, \"email\", void 0);\n _defineProperty(this, \"additionalClaims\", void 0);\n _defineProperty(this, \"eagerRefreshThresholdMillis\", void 0);\n _defineProperty(this, \"transporter\", {\n request: function request(opts) {\n return (0, _gaxios.request)(opts);\n }\n });\n _classPrivateFieldInitSpec(this, _inFlightRequest, void 0);\n _assertClassBrand(_GoogleToken_brand, this, _configure).call(this, _options);\n }\n\n /**\n * Returns whether the token has expired.\n *\n * @return true if the token has expired, false otherwise.\n */\n return _createClass(GoogleToken, [{\n key: \"accessToken\",\n get: function get() {\n return this.rawToken ? this.rawToken.access_token : undefined;\n }\n }, {\n key: \"idToken\",\n get: function get() {\n return this.rawToken ? this.rawToken.id_token : undefined;\n }\n }, {\n key: \"tokenType\",\n get: function get() {\n return this.rawToken ? this.rawToken.token_type : undefined;\n }\n }, {\n key: \"refreshToken\",\n get: function get() {\n return this.rawToken ? this.rawToken.refresh_token : undefined;\n }\n }, {\n key: \"hasExpired\",\n value: function hasExpired() {\n var now = new Date().getTime();\n if (this.rawToken && this.expiresAt) {\n return now >= this.expiresAt;\n } else {\n return true;\n }\n }\n\n /**\n * Returns whether the token will expire within eagerRefreshThresholdMillis\n *\n * @return true if the token will be expired within eagerRefreshThresholdMillis, false otherwise.\n */\n }, {\n key: \"isTokenExpiring\",\n value: function isTokenExpiring() {\n var _this$eagerRefreshThr;\n var now = new Date().getTime();\n var eagerRefreshThresholdMillis = (_this$eagerRefreshThr = this.eagerRefreshThresholdMillis) !== null && _this$eagerRefreshThr !== void 0 ? _this$eagerRefreshThr : 0;\n if (this.rawToken && this.expiresAt) {\n return this.expiresAt <= now + eagerRefreshThresholdMillis;\n } else {\n return true;\n }\n }\n\n /**\n * Returns a cached token or retrieves a new one from Google.\n *\n * @param callback The callback function.\n */\n }, {\n key: \"getToken\",\n value: function getToken(callback) {\n var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n if (_typeof(callback) === 'object') {\n opts = callback;\n callback = undefined;\n }\n opts = Object.assign({\n forceRefresh: false\n }, opts);\n if (callback) {\n var cb = callback;\n _assertClassBrand(_GoogleToken_brand, this, _getTokenAsync).call(this, opts).then(function (t) {\n return cb(null, t);\n }, callback);\n return;\n }\n return _assertClassBrand(_GoogleToken_brand, this, _getTokenAsync).call(this, opts);\n }\n\n /**\n * Given a keyFile, extract the key and client email if available\n * @param keyFile Path to a json, pem, or p12 file that contains the key.\n * @returns an object with privateKey and clientEmail properties\n */\n }, {\n key: \"getCredentials\",\n value: (function () {\n var _getCredentials = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(keyFile) {\n var ext, key, body, privateKey, clientEmail, _privateKey, _t;\n return _regenerator().w(function (_context2) {\n while (1) switch (_context2.n) {\n case 0:\n ext = path.extname(keyFile);\n _t = ext;\n _context2.n = _t === '.json' ? 1 : _t === '.der' ? 4 : _t === '.crt' ? 4 : _t === '.pem' ? 4 : _t === '.p12' ? 6 : _t === '.pfx' ? 6 : 7;\n break;\n case 1:\n _context2.n = 2;\n return readFile(keyFile, 'utf8');\n case 2:\n key = _context2.v;\n body = JSON.parse(key);\n privateKey = body.private_key;\n clientEmail = body.client_email;\n if (!(!privateKey || !clientEmail)) {\n _context2.n = 3;\n break;\n }\n throw new ErrorWithCode('private_key and client_email are required.', 'MISSING_CREDENTIALS');\n case 3:\n return _context2.a(2, {\n privateKey: privateKey,\n clientEmail: clientEmail\n });\n case 4:\n _context2.n = 5;\n return readFile(keyFile, 'utf8');\n case 5:\n _privateKey = _context2.v;\n return _context2.a(2, {\n privateKey: _privateKey\n });\n case 6:\n throw new ErrorWithCode('*.p12 certificates are not supported after v6.1.2. ' + 'Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.', 'UNKNOWN_CERTIFICATE_TYPE');\n case 7:\n throw new ErrorWithCode('Unknown certificate type. Type is determined based on file extension. ' + 'Current supported extensions are *.json, and *.pem.', 'UNKNOWN_CERTIFICATE_TYPE');\n case 8:\n return _context2.a(2);\n }\n }, _callee2);\n }));\n function getCredentials(_x) {\n return _getCredentials.apply(this, arguments);\n }\n return getCredentials;\n }())\n }, {\n key: \"revokeToken\",\n value: function revokeToken(callback) {\n if (callback) {\n _assertClassBrand(_GoogleToken_brand, this, _revokeTokenAsync).call(this).then(function () {\n return callback();\n }, callback);\n return;\n }\n return _assertClassBrand(_GoogleToken_brand, this, _revokeTokenAsync).call(this);\n }\n }]);\n}();\nfunction _getTokenAsync(_x2) {\n return _getTokenAsync2.apply(this, arguments);\n}\nfunction _getTokenAsync2() {\n _getTokenAsync2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(opts) {\n return _regenerator().w(function (_context3) {\n while (1) switch (_context3.n) {\n case 0:\n if (!(_classPrivateFieldGet(_inFlightRequest, this) && !opts.forceRefresh)) {\n _context3.n = 1;\n break;\n }\n return _context3.a(2, _classPrivateFieldGet(_inFlightRequest, this));\n case 1:\n _context3.p = 1;\n _context3.n = 2;\n return _classPrivateFieldSet(_inFlightRequest, this, _assertClassBrand(_GoogleToken_brand, this, _getTokenAsyncInner).call(this, opts));\n case 2:\n return _context3.a(2, _context3.v);\n case 3:\n _context3.p = 3;\n _classPrivateFieldSet(_inFlightRequest, this, undefined);\n return _context3.f(3);\n case 4:\n return _context3.a(2);\n }\n }, _callee3, this, [[1,, 3, 4]]);\n }));\n return _getTokenAsync2.apply(this, arguments);\n}\nfunction _getTokenAsyncInner(_x3) {\n return _getTokenAsyncInner2.apply(this, arguments);\n}\nfunction _getTokenAsyncInner2() {\n _getTokenAsyncInner2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(opts) {\n var creds;\n return _regenerator().w(function (_context4) {\n while (1) switch (_context4.n) {\n case 0:\n if (!(this.isTokenExpiring() === false && opts.forceRefresh === false)) {\n _context4.n = 1;\n break;\n }\n return _context4.a(2, Promise.resolve(this.rawToken));\n case 1:\n if (!(!this.key && !this.keyFile)) {\n _context4.n = 2;\n break;\n }\n throw new Error('No key or keyFile set.');\n case 2:\n if (!(!this.key && this.keyFile)) {\n _context4.n = 4;\n break;\n }\n _context4.n = 3;\n return this.getCredentials(this.keyFile);\n case 3:\n creds = _context4.v;\n this.key = creds.privateKey;\n this.iss = creds.clientEmail || this.iss;\n if (!creds.clientEmail) {\n _assertClassBrand(_GoogleToken_brand, this, _ensureEmail).call(this);\n }\n case 4:\n return _context4.a(2, _assertClassBrand(_GoogleToken_brand, this, _requestToken).call(this));\n }\n }, _callee4, this);\n }));\n return _getTokenAsyncInner2.apply(this, arguments);\n}\nfunction _ensureEmail() {\n if (!this.iss) {\n throw new ErrorWithCode('email is required.', 'MISSING_CREDENTIALS');\n }\n}\nfunction _revokeTokenAsync() {\n return _revokeTokenAsync2.apply(this, arguments);\n}\nfunction _revokeTokenAsync2() {\n _revokeTokenAsync2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5() {\n var url;\n return _regenerator().w(function (_context5) {\n while (1) switch (_context5.n) {\n case 0:\n if (this.accessToken) {\n _context5.n = 1;\n break;\n }\n throw new Error('No token to revoke.');\n case 1:\n url = GOOGLE_REVOKE_TOKEN_URL + this.accessToken;\n _context5.n = 2;\n return this.transporter.request({\n url: url,\n retry: true\n });\n case 2:\n _assertClassBrand(_GoogleToken_brand, this, _configure).call(this, {\n email: this.iss,\n sub: this.sub,\n key: this.key,\n keyFile: this.keyFile,\n scope: this.scope,\n additionalClaims: this.additionalClaims\n });\n case 3:\n return _context5.a(2);\n }\n }, _callee5, this);\n }));\n return _revokeTokenAsync2.apply(this, arguments);\n}\n/**\n * Configure the GoogleToken for re-use.\n * @param {object} options Configuration object.\n */\nfunction _configure() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n this.keyFile = options.keyFile;\n this.key = options.key;\n this.rawToken = undefined;\n this.iss = options.email || options.iss;\n this.sub = options.sub;\n this.additionalClaims = options.additionalClaims;\n if (_typeof(options.scope) === 'object') {\n this.scope = options.scope.join(' ');\n } else {\n this.scope = options.scope;\n }\n this.eagerRefreshThresholdMillis = options.eagerRefreshThresholdMillis;\n if (options.transporter) {\n this.transporter = options.transporter;\n }\n}\n/**\n * Request the token from Google.\n */\nfunction _requestToken() {\n return _requestToken2.apply(this, arguments);\n}\nfunction _requestToken2() {\n _requestToken2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6() {\n var iat, additionalClaims, payload, signedJWT, r, _response, _response2, body, desc, _t2;\n return _regenerator().w(function (_context6) {\n while (1) switch (_context6.n) {\n case 0:\n iat = Math.floor(new Date().getTime() / 1000);\n additionalClaims = this.additionalClaims || {};\n payload = Object.assign({\n iss: this.iss,\n scope: this.scope,\n aud: GOOGLE_TOKEN_URL,\n exp: iat + 3600,\n iat: iat,\n sub: this.sub\n }, additionalClaims);\n signedJWT = jws.sign({\n header: {\n alg: 'RS256'\n },\n payload: payload,\n secret: this.key\n });\n _context6.p = 1;\n _context6.n = 2;\n return this.transporter.request({\n method: 'POST',\n url: GOOGLE_TOKEN_URL,\n data: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',\n assertion: signedJWT\n }),\n responseType: 'json',\n retryConfig: {\n httpMethodsToRetry: ['POST']\n }\n });\n case 2:\n r = _context6.v;\n this.rawToken = r.data;\n this.expiresAt = r.data.expires_in === null || r.data.expires_in === undefined ? undefined : (iat + r.data.expires_in) * 1000;\n return _context6.a(2, this.rawToken);\n case 3:\n _context6.p = 3;\n _t2 = _context6.v;\n this.rawToken = undefined;\n this.tokenExpires = undefined;\n body = _t2.response && (_response = _t2.response) !== null && _response !== void 0 && _response.data ? (_response2 = _t2.response) === null || _response2 === void 0 ? void 0 : _response2.data : {};\n if (body.error) {\n desc = body.error_description ? \": \".concat(body.error_description) : '';\n _t2.message = \"\".concat(body.error).concat(desc);\n }\n throw _t2;\n case 4:\n return _context6.a(2);\n }\n }, _callee6, this, [[1, 3]]);\n }));\n return _requestToken2.apply(this, arguments);\n}", "\"use strict\";\n// Copyright 2015 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.JWTAccess = void 0;\nconst jws = require(\"jws\");\nconst util_1 = require(\"../util\");\nconst DEFAULT_HEADER = {\n alg: 'RS256',\n typ: 'JWT',\n};\nclass JWTAccess {\n email;\n key;\n keyId;\n projectId;\n eagerRefreshThresholdMillis;\n cache = new util_1.LRUCache({\n capacity: 500,\n maxAge: 60 * 60 * 1000,\n });\n /**\n * JWTAccess service account credentials.\n *\n * Create a new access token by using the credential to create a new JWT token\n * that's recognized as the access token.\n *\n * @param email the service account email address.\n * @param key the private key that will be used to sign the token.\n * @param keyId the ID of the private key used to sign the token.\n */\n constructor(email, key, keyId, eagerRefreshThresholdMillis) {\n this.email = email;\n this.key = key;\n this.keyId = keyId;\n this.eagerRefreshThresholdMillis =\n eagerRefreshThresholdMillis ?? 5 * 60 * 1000;\n }\n /**\n * Ensures that we're caching a key appropriately, giving precedence to scopes vs. url\n *\n * @param url The URI being authorized.\n * @param scopes The scope or scopes being authorized\n * @returns A string that returns the cached key.\n */\n getCachedKey(url, scopes) {\n let cacheKey = url;\n if (scopes && Array.isArray(scopes) && scopes.length) {\n cacheKey = url ? `${url}_${scopes.join('_')}` : `${scopes.join('_')}`;\n }\n else if (typeof scopes === 'string') {\n cacheKey = url ? `${url}_${scopes}` : scopes;\n }\n if (!cacheKey) {\n throw Error('Scopes or url must be provided');\n }\n return cacheKey;\n }\n /**\n * Get a non-expired access token, after refreshing if necessary.\n *\n * @param url The URI being authorized.\n * @param additionalClaims An object with a set of additional claims to\n * include in the payload.\n * @returns An object that includes the authorization header.\n */\n getRequestHeaders(url, additionalClaims, scopes) {\n // Return cached authorization headers, unless we are within\n // eagerRefreshThresholdMillis ms of them expiring:\n const key = this.getCachedKey(url, scopes);\n const cachedToken = this.cache.get(key);\n const now = Date.now();\n if (cachedToken &&\n cachedToken.expiration - now > this.eagerRefreshThresholdMillis) {\n // Copying headers into a new `Headers` object to avoid potential leakage -\n // as this is a cache it is possible for multiple requests to reference this\n // same value.\n return new Headers(cachedToken.headers);\n }\n const iat = Math.floor(Date.now() / 1000);\n const exp = JWTAccess.getExpirationTime(iat);\n let defaultClaims;\n // Turn scopes into space-separated string\n if (Array.isArray(scopes)) {\n scopes = scopes.join(' ');\n }\n // If scopes are specified, sign with scopes\n if (scopes) {\n defaultClaims = {\n iss: this.email,\n sub: this.email,\n scope: scopes,\n exp,\n iat,\n };\n }\n else {\n defaultClaims = {\n iss: this.email,\n sub: this.email,\n aud: url,\n exp,\n iat,\n };\n }\n // if additionalClaims are provided, ensure they do not collide with\n // other required claims.\n if (additionalClaims) {\n for (const claim in defaultClaims) {\n if (additionalClaims[claim]) {\n throw new Error(`The '${claim}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`);\n }\n }\n }\n const header = this.keyId\n ? { ...DEFAULT_HEADER, kid: this.keyId }\n : DEFAULT_HEADER;\n const payload = Object.assign(defaultClaims, additionalClaims);\n // Sign the jwt and add it to the cache\n const signedJWT = jws.sign({ header, payload, secret: this.key });\n const headers = new Headers({ authorization: `Bearer ${signedJWT}` });\n this.cache.set(key, {\n expiration: exp * 1000,\n headers,\n });\n return headers;\n }\n /**\n * Returns an expiration time for the JWT token.\n *\n * @param iat The issued at time for the JWT.\n * @returns An expiration time for the JWT.\n */\n static getExpirationTime(iat) {\n const exp = iat + 3600; // 3600 seconds = 1 hour\n return exp;\n }\n /**\n * Create a JWTAccess credentials instance using the given input options.\n * @param json The input object.\n */\n fromJSON(json) {\n if (!json) {\n throw new Error('Must pass in a JSON object containing the service account auth settings.');\n }\n if (!json.client_email) {\n throw new Error('The incoming JSON object does not contain a client_email field');\n }\n if (!json.private_key) {\n throw new Error('The incoming JSON object does not contain a private_key field');\n }\n // Extract the relevant information from the json key file.\n this.email = json.client_email;\n this.key = json.private_key;\n this.keyId = json.private_key_id;\n this.projectId = json.project_id;\n }\n fromStream(inputStream, callback) {\n if (callback) {\n this.fromStreamAsync(inputStream).then(() => callback(), callback);\n }\n else {\n return this.fromStreamAsync(inputStream);\n }\n }\n fromStreamAsync(inputStream) {\n return new Promise((resolve, reject) => {\n if (!inputStream) {\n reject(new Error('Must pass in a stream containing the service account auth settings.'));\n }\n let s = '';\n inputStream\n .setEncoding('utf8')\n .on('data', chunk => (s += chunk))\n .on('error', reject)\n .on('end', () => {\n try {\n const data = JSON.parse(s);\n this.fromJSON(data);\n resolve();\n }\n catch (err) {\n reject(err);\n }\n });\n });\n }\n}\nexports.JWTAccess = JWTAccess;\n//# sourceMappingURL=jwtaccess.js.map", "\"use strict\";\n// Copyright 2013 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.JWT = void 0;\nconst gtoken_1 = require(\"gtoken\");\nconst jwtaccess_1 = require(\"./jwtaccess\");\nconst oauth2client_1 = require(\"./oauth2client\");\nconst authclient_1 = require(\"./authclient\");\nclass JWT extends oauth2client_1.OAuth2Client {\n email;\n keyFile;\n key;\n keyId;\n defaultScopes;\n scopes;\n scope;\n subject;\n gtoken;\n additionalClaims;\n useJWTAccessWithScope;\n defaultServicePath;\n access;\n /**\n * JWT service account credentials.\n *\n * Retrieve access token using gtoken.\n *\n * @param options the\n */\n constructor(options = {}) {\n super(options);\n this.email = options.email;\n this.keyFile = options.keyFile;\n this.key = options.key;\n this.keyId = options.keyId;\n this.scopes = options.scopes;\n this.subject = options.subject;\n this.additionalClaims = options.additionalClaims;\n // Start with an expired refresh token, which will automatically be\n // refreshed before the first API call is made.\n this.credentials = { refresh_token: 'jwt-placeholder', expiry_date: 1 };\n }\n /**\n * Creates a copy of the credential with the specified scopes.\n * @param scopes List of requested scopes or a single scope.\n * @return The cloned instance.\n */\n createScoped(scopes) {\n const jwt = new JWT(this);\n jwt.scopes = scopes;\n return jwt;\n }\n /**\n * Obtains the metadata to be sent with the request.\n *\n * @param url the URI being authorized.\n */\n async getRequestMetadataAsync(url) {\n url = this.defaultServicePath ? `https://${this.defaultServicePath}/` : url;\n const useSelfSignedJWT = (!this.hasUserScopes() && url) ||\n (this.useJWTAccessWithScope && this.hasAnyScopes()) ||\n this.universeDomain !== authclient_1.DEFAULT_UNIVERSE;\n if (this.subject && this.universeDomain !== authclient_1.DEFAULT_UNIVERSE) {\n throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${authclient_1.DEFAULT_UNIVERSE}`);\n }\n if (!this.apiKey && useSelfSignedJWT) {\n if (this.additionalClaims &&\n this.additionalClaims.target_audience) {\n const { tokens } = await this.refreshToken();\n return {\n headers: this.addSharedMetadataHeaders(new Headers({\n authorization: `Bearer ${tokens.id_token}`,\n })),\n };\n }\n else {\n // no scopes have been set, but a uri has been provided. Use JWTAccess\n // credentials.\n if (!this.access) {\n this.access = new jwtaccess_1.JWTAccess(this.email, this.key, this.keyId, this.eagerRefreshThresholdMillis);\n }\n let scopes;\n if (this.hasUserScopes()) {\n scopes = this.scopes;\n }\n else if (!url) {\n scopes = this.defaultScopes;\n }\n const useScopes = this.useJWTAccessWithScope ||\n this.universeDomain !== authclient_1.DEFAULT_UNIVERSE;\n const headers = await this.access.getRequestHeaders(url ?? undefined, this.additionalClaims, \n // Scopes take precedent over audience for signing,\n // so we only provide them if `useJWTAccessWithScope` is on or\n // if we are in a non-default universe\n useScopes ? scopes : undefined);\n return { headers: this.addSharedMetadataHeaders(headers) };\n }\n }\n else if (this.hasAnyScopes() || this.apiKey) {\n return super.getRequestMetadataAsync(url);\n }\n else {\n // If no audience, apiKey, or scopes are provided, we should not attempt\n // to populate any headers:\n return { headers: new Headers() };\n }\n }\n /**\n * Fetches an ID token.\n * @param targetAudience the audience for the fetched ID token.\n */\n async fetchIdToken(targetAudience) {\n // Create a new gToken for fetching an ID token\n const gtoken = new gtoken_1.GoogleToken({\n iss: this.email,\n sub: this.subject,\n scope: this.scopes || this.defaultScopes,\n keyFile: this.keyFile,\n key: this.key,\n additionalClaims: { target_audience: targetAudience },\n transporter: this.transporter,\n });\n await gtoken.getToken({\n forceRefresh: true,\n });\n if (!gtoken.idToken) {\n throw new Error('Unknown error: Failed to fetch ID token');\n }\n return gtoken.idToken;\n }\n /**\n * Determine if there are currently scopes available.\n */\n hasUserScopes() {\n if (!this.scopes) {\n return false;\n }\n return this.scopes.length > 0;\n }\n /**\n * Are there any default or user scopes defined.\n */\n hasAnyScopes() {\n if (this.scopes && this.scopes.length > 0)\n return true;\n if (this.defaultScopes && this.defaultScopes.length > 0)\n return true;\n return false;\n }\n authorize(callback) {\n if (callback) {\n this.authorizeAsync().then(r => callback(null, r), callback);\n }\n else {\n return this.authorizeAsync();\n }\n }\n async authorizeAsync() {\n const result = await this.refreshToken();\n if (!result) {\n throw new Error('No result returned');\n }\n this.credentials = result.tokens;\n this.credentials.refresh_token = 'jwt-placeholder';\n this.key = this.gtoken.key;\n this.email = this.gtoken.iss;\n return result.tokens;\n }\n /**\n * Refreshes the access token.\n * @param refreshToken ignored\n * @private\n */\n async refreshTokenNoCache() {\n const gtoken = this.createGToken();\n const token = await gtoken.getToken({\n forceRefresh: this.isTokenExpiring(),\n });\n const tokens = {\n access_token: token.access_token,\n token_type: 'Bearer',\n expiry_date: gtoken.expiresAt,\n id_token: gtoken.idToken,\n };\n this.emit('tokens', tokens);\n return { res: null, tokens };\n }\n /**\n * Create a gToken if it doesn't already exist.\n */\n createGToken() {\n if (!this.gtoken) {\n this.gtoken = new gtoken_1.GoogleToken({\n iss: this.email,\n sub: this.subject,\n scope: this.scopes || this.defaultScopes,\n keyFile: this.keyFile,\n key: this.key,\n additionalClaims: this.additionalClaims,\n transporter: this.transporter,\n });\n }\n return this.gtoken;\n }\n /**\n * Create a JWT credentials instance using the given input options.\n * @param json The input object.\n *\n * @remarks\n *\n * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}.\n */\n fromJSON(json) {\n if (!json) {\n throw new Error('Must pass in a JSON object containing the service account auth settings.');\n }\n if (!json.client_email) {\n throw new Error('The incoming JSON object does not contain a client_email field');\n }\n if (!json.private_key) {\n throw new Error('The incoming JSON object does not contain a private_key field');\n }\n // Extract the relevant information from the json key file.\n this.email = json.client_email;\n this.key = json.private_key;\n this.keyId = json.private_key_id;\n this.projectId = json.project_id;\n this.quotaProjectId = json.quota_project_id;\n this.universeDomain = json.universe_domain || this.universeDomain;\n }\n fromStream(inputStream, callback) {\n if (callback) {\n this.fromStreamAsync(inputStream).then(() => callback(), callback);\n }\n else {\n return this.fromStreamAsync(inputStream);\n }\n }\n fromStreamAsync(inputStream) {\n return new Promise((resolve, reject) => {\n if (!inputStream) {\n throw new Error('Must pass in a stream containing the service account auth settings.');\n }\n let s = '';\n inputStream\n .setEncoding('utf8')\n .on('error', reject)\n .on('data', chunk => (s += chunk))\n .on('end', () => {\n try {\n const data = JSON.parse(s);\n this.fromJSON(data);\n resolve();\n }\n catch (e) {\n reject(e);\n }\n });\n });\n }\n /**\n * Creates a JWT credentials instance using an API Key for authentication.\n * @param apiKey The API Key in string form.\n */\n fromAPIKey(apiKey) {\n if (typeof apiKey !== 'string') {\n throw new Error('Must provide an API Key string.');\n }\n this.apiKey = apiKey;\n }\n /**\n * Using the key or keyFile on the JWT client, obtain an object that contains\n * the key and the client email.\n */\n async getCredentials() {\n if (this.key) {\n return { private_key: this.key, client_email: this.email };\n }\n else if (this.keyFile) {\n const gtoken = this.createGToken();\n const creds = await gtoken.getCredentials(this.keyFile);\n return { private_key: creds.privateKey, client_email: creds.clientEmail };\n }\n throw new Error('A key or a keyFile must be provided to getCredentials.');\n }\n}\nexports.JWT = JWT;\n//# sourceMappingURL=jwtclient.js.map", "\"use strict\";\n// Copyright 2015 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.UserRefreshClient = exports.USER_REFRESH_ACCOUNT_TYPE = void 0;\nconst oauth2client_1 = require(\"./oauth2client\");\nconst authclient_1 = require(\"./authclient\");\nexports.USER_REFRESH_ACCOUNT_TYPE = 'authorized_user';\nclass UserRefreshClient extends oauth2client_1.OAuth2Client {\n // TODO: refactor tests to make this private\n // In a future gts release, the _propertyName rule will be lifted.\n // This is also a hard one because `this.refreshToken` is a function.\n _refreshToken;\n /**\n * The User Refresh Token client.\n *\n * @param optionsOrClientId The User Refresh Token client options. Passing an `clientId` directly is **@DEPRECATED**.\n * @param clientSecret **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.\n * @param refreshToken **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.\n * @param eagerRefreshThresholdMillis **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.\n * @param forceRefreshOnFailure **@DEPRECATED**. Provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead.\n */\n constructor(optionsOrClientId, \n /**\n * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead\n */\n clientSecret, \n /**\n * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead\n */\n refreshToken, \n /**\n * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead\n */\n eagerRefreshThresholdMillis, \n /**\n * @deprecated - provide a {@link UserRefreshClientOptions `UserRefreshClientOptions`} object in the first parameter instead\n */\n forceRefreshOnFailure) {\n const opts = optionsOrClientId && typeof optionsOrClientId === 'object'\n ? optionsOrClientId\n : {\n clientId: optionsOrClientId,\n clientSecret,\n refreshToken,\n eagerRefreshThresholdMillis,\n forceRefreshOnFailure,\n };\n super(opts);\n this._refreshToken = opts.refreshToken;\n this.credentials.refresh_token = opts.refreshToken;\n }\n /**\n * Refreshes the access token.\n * @param refreshToken An ignored refreshToken..\n * @param callback Optional callback.\n */\n async refreshTokenNoCache() {\n return super.refreshTokenNoCache(this._refreshToken);\n }\n async fetchIdToken(targetAudience) {\n const opts = {\n ...UserRefreshClient.RETRY_CONFIG,\n url: this.endpoints.oauth2TokenUrl,\n method: 'POST',\n data: new URLSearchParams({\n client_id: this._clientId,\n client_secret: this._clientSecret,\n grant_type: 'refresh_token',\n refresh_token: this._refreshToken,\n target_audience: targetAudience,\n }),\n };\n authclient_1.AuthClient.setMethodName(opts, 'fetchIdToken');\n const res = await this.transporter.request(opts);\n return res.data.id_token;\n }\n /**\n * Create a UserRefreshClient credentials instance using the given input\n * options.\n * @param json The input object.\n */\n fromJSON(json) {\n if (!json) {\n throw new Error('Must pass in a JSON object containing the user refresh token');\n }\n if (json.type !== 'authorized_user') {\n throw new Error('The incoming JSON object does not have the \"authorized_user\" type');\n }\n if (!json.client_id) {\n throw new Error('The incoming JSON object does not contain a client_id field');\n }\n if (!json.client_secret) {\n throw new Error('The incoming JSON object does not contain a client_secret field');\n }\n if (!json.refresh_token) {\n throw new Error('The incoming JSON object does not contain a refresh_token field');\n }\n this._clientId = json.client_id;\n this._clientSecret = json.client_secret;\n this._refreshToken = json.refresh_token;\n this.credentials.refresh_token = json.refresh_token;\n this.quotaProjectId = json.quota_project_id;\n this.universeDomain = json.universe_domain || this.universeDomain;\n }\n fromStream(inputStream, callback) {\n if (callback) {\n this.fromStreamAsync(inputStream).then(() => callback(), callback);\n }\n else {\n return this.fromStreamAsync(inputStream);\n }\n }\n async fromStreamAsync(inputStream) {\n return new Promise((resolve, reject) => {\n if (!inputStream) {\n return reject(new Error('Must pass in a stream containing the user refresh token.'));\n }\n let s = '';\n inputStream\n .setEncoding('utf8')\n .on('error', reject)\n .on('data', chunk => (s += chunk))\n .on('end', () => {\n try {\n const data = JSON.parse(s);\n this.fromJSON(data);\n return resolve();\n }\n catch (err) {\n return reject(err);\n }\n });\n });\n }\n /**\n * Create a UserRefreshClient credentials instance using the given input\n * options.\n * @param json The input object.\n */\n static fromJSON(json) {\n const client = new UserRefreshClient();\n client.fromJSON(json);\n return client;\n }\n}\nexports.UserRefreshClient = UserRefreshClient;\n//# sourceMappingURL=refreshclient.js.map", "\"use strict\";\n/**\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Impersonated = exports.IMPERSONATED_ACCOUNT_TYPE = void 0;\nconst oauth2client_1 = require(\"./oauth2client\");\nconst gaxios_1 = require(\"gaxios\");\nconst util_1 = require(\"../util\");\nexports.IMPERSONATED_ACCOUNT_TYPE = 'impersonated_service_account';\nclass Impersonated extends oauth2client_1.OAuth2Client {\n sourceClient;\n targetPrincipal;\n targetScopes;\n delegates;\n lifetime;\n endpoint;\n /**\n * Impersonated service account credentials.\n *\n * Create a new access token by impersonating another service account.\n *\n * Impersonated Credentials allowing credentials issued to a user or\n * service account to impersonate another. The source project using\n * Impersonated Credentials must enable the \"IAMCredentials\" API.\n * Also, the target service account must grant the orginating principal\n * the \"Service Account Token Creator\" IAM role.\n *\n * @param {object} options - The configuration object.\n * @param {object} [options.sourceClient] the source credential used as to\n * acquire the impersonated credentials.\n * @param {string} [options.targetPrincipal] the service account to\n * impersonate.\n * @param {string[]} [options.delegates] the chained list of delegates\n * required to grant the final access_token. If set, the sequence of\n * identities must have \"Service Account Token Creator\" capability granted to\n * the preceding identity. For example, if set to [serviceAccountB,\n * serviceAccountC], the sourceCredential must have the Token Creator role on\n * serviceAccountB. serviceAccountB must have the Token Creator on\n * serviceAccountC. Finally, C must have Token Creator on target_principal.\n * If left unset, sourceCredential must have that role on targetPrincipal.\n * @param {string[]} [options.targetScopes] scopes to request during the\n * authorization grant.\n * @param {number} [options.lifetime] number of seconds the delegated\n * credential should be valid for up to 3600 seconds by default, or 43,200\n * seconds by extending the token's lifetime, see:\n * https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth\n * @param {string} [options.endpoint] api endpoint override.\n */\n constructor(options = {}) {\n super(options);\n // Start with an expired refresh token, which will automatically be\n // refreshed before the first API call is made.\n this.credentials = {\n expiry_date: 1,\n refresh_token: 'impersonated-placeholder',\n };\n this.sourceClient = options.sourceClient ?? new oauth2client_1.OAuth2Client();\n this.targetPrincipal = options.targetPrincipal ?? '';\n this.delegates = options.delegates ?? [];\n this.targetScopes = options.targetScopes ?? [];\n this.lifetime = options.lifetime ?? 3600;\n const usingExplicitUniverseDomain = !!(0, util_1.originalOrCamelOptions)(options).get('universe_domain');\n if (!usingExplicitUniverseDomain) {\n // override the default universe with the source's universe\n this.universeDomain = this.sourceClient.universeDomain;\n }\n else if (this.sourceClient.universeDomain !== this.universeDomain) {\n // non-default universe and is not matching the source - this could be a credential leak\n throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);\n }\n this.endpoint =\n options.endpoint ?? `https://iamcredentials.${this.universeDomain}`;\n }\n /**\n * Signs some bytes.\n *\n * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob Reference Documentation}\n * @param blobToSign String to sign.\n *\n * @returns A {@link SignBlobResponse} denoting the keyID and signedBlob in base64 string\n */\n async sign(blobToSign) {\n await this.sourceClient.getAccessToken();\n const name = `projects/-/serviceAccounts/${this.targetPrincipal}`;\n const u = `${this.endpoint}/v1/${name}:signBlob`;\n const body = {\n delegates: this.delegates,\n payload: Buffer.from(blobToSign).toString('base64'),\n };\n const res = await this.sourceClient.request({\n ...Impersonated.RETRY_CONFIG,\n url: u,\n data: body,\n method: 'POST',\n });\n return res.data;\n }\n /** The service account email to be impersonated. */\n getTargetPrincipal() {\n return this.targetPrincipal;\n }\n /**\n * Refreshes the access token.\n */\n async refreshToken() {\n try {\n await this.sourceClient.getAccessToken();\n const name = 'projects/-/serviceAccounts/' + this.targetPrincipal;\n const u = `${this.endpoint}/v1/${name}:generateAccessToken`;\n const body = {\n delegates: this.delegates,\n scope: this.targetScopes,\n lifetime: this.lifetime + 's',\n };\n const res = await this.sourceClient.request({\n ...Impersonated.RETRY_CONFIG,\n url: u,\n data: body,\n method: 'POST',\n });\n const tokenResponse = res.data;\n this.credentials.access_token = tokenResponse.accessToken;\n this.credentials.expiry_date = Date.parse(tokenResponse.expireTime);\n return {\n tokens: this.credentials,\n res,\n };\n }\n catch (error) {\n if (!(error instanceof Error))\n throw error;\n let status = 0;\n let message = '';\n if (error instanceof gaxios_1.GaxiosError) {\n status = error?.response?.data?.error?.status;\n message = error?.response?.data?.error?.message;\n }\n if (status && message) {\n error.message = `${status}: unable to impersonate: ${message}`;\n throw error;\n }\n else {\n error.message = `unable to impersonate: ${error}`;\n throw error;\n }\n }\n }\n /**\n * Generates an OpenID Connect ID token for a service account.\n *\n * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateIdToken Reference Documentation}\n *\n * @param targetAudience the audience for the fetched ID token.\n * @param options the for the request\n * @return an OpenID Connect ID token\n */\n async fetchIdToken(targetAudience, options) {\n await this.sourceClient.getAccessToken();\n const name = `projects/-/serviceAccounts/${this.targetPrincipal}`;\n const u = `${this.endpoint}/v1/${name}:generateIdToken`;\n const body = {\n delegates: this.delegates,\n audience: targetAudience,\n includeEmail: options?.includeEmail ?? true,\n useEmailAzp: options?.includeEmail ?? true,\n };\n const res = await this.sourceClient.request({\n ...Impersonated.RETRY_CONFIG,\n url: u,\n data: body,\n method: 'POST',\n });\n return res.data.token;\n }\n}\nexports.Impersonated = Impersonated;\n//# sourceMappingURL=impersonated.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.OAuthClientAuthHandler = void 0;\nexports.getErrorFromOAuthErrorResponse = getErrorFromOAuthErrorResponse;\nconst gaxios_1 = require(\"gaxios\");\nconst crypto_1 = require(\"../crypto/crypto\");\n/** List of HTTP methods that accept request bodies. */\nconst METHODS_SUPPORTING_REQUEST_BODY = ['PUT', 'POST', 'PATCH'];\n/**\n * Abstract class for handling client authentication in OAuth-based\n * operations.\n * When request-body client authentication is used, only application/json and\n * application/x-www-form-urlencoded content types for HTTP methods that support\n * request bodies are supported.\n */\nclass OAuthClientAuthHandler {\n #crypto = (0, crypto_1.createCrypto)();\n #clientAuthentication;\n transporter;\n /**\n * Instantiates an OAuth client authentication handler.\n * @param options The OAuth Client Auth Handler instance options. Passing an `ClientAuthentication` directly is **@DEPRECATED**.\n */\n constructor(options) {\n if (options && 'clientId' in options) {\n this.#clientAuthentication = options;\n this.transporter = new gaxios_1.Gaxios();\n }\n else {\n this.#clientAuthentication = options?.clientAuthentication;\n this.transporter = options?.transporter || new gaxios_1.Gaxios();\n }\n }\n /**\n * Applies client authentication on the OAuth request's headers or POST\n * body but does not process the request.\n * @param opts The GaxiosOptions whose headers or data are to be modified\n * depending on the client authentication mechanism to be used.\n * @param bearerToken The optional bearer token to use for authentication.\n * When this is used, no client authentication credentials are needed.\n */\n applyClientAuthenticationOptions(opts, bearerToken) {\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);\n // Inject authenticated header.\n this.injectAuthenticatedHeaders(opts, bearerToken);\n // Inject authenticated request body.\n if (!bearerToken) {\n this.injectAuthenticatedRequestBody(opts);\n }\n }\n /**\n * Applies client authentication on the request's header if either\n * basic authentication or bearer token authentication is selected.\n *\n * @param opts The GaxiosOptions whose headers or data are to be modified\n * depending on the client authentication mechanism to be used.\n * @param bearerToken The optional bearer token to use for authentication.\n * When this is used, no client authentication credentials are needed.\n */\n injectAuthenticatedHeaders(opts, bearerToken) {\n // Bearer token prioritized higher than basic Auth.\n if (bearerToken) {\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers, {\n authorization: `Bearer ${bearerToken}`,\n });\n }\n else if (this.#clientAuthentication?.confidentialClientType === 'basic') {\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);\n const clientId = this.#clientAuthentication.clientId;\n const clientSecret = this.#clientAuthentication.clientSecret || '';\n const base64EncodedCreds = this.#crypto.encodeBase64StringUtf8(`${clientId}:${clientSecret}`);\n gaxios_1.Gaxios.mergeHeaders(opts.headers, {\n authorization: `Basic ${base64EncodedCreds}`,\n });\n }\n }\n /**\n * Applies client authentication on the request's body if request-body\n * client authentication is selected.\n *\n * @param opts The GaxiosOptions whose headers or data are to be modified\n * depending on the client authentication mechanism to be used.\n */\n injectAuthenticatedRequestBody(opts) {\n if (this.#clientAuthentication?.confidentialClientType === 'request-body') {\n const method = (opts.method || 'GET').toUpperCase();\n if (!METHODS_SUPPORTING_REQUEST_BODY.includes(method)) {\n throw new Error(`${method} HTTP method does not support ` +\n `${this.#clientAuthentication.confidentialClientType} ` +\n 'client authentication');\n }\n // Get content-type\n const headers = new Headers(opts.headers);\n const contentType = headers.get('content-type');\n // Inject authenticated request body\n if (contentType?.startsWith('application/x-www-form-urlencoded') ||\n opts.data instanceof URLSearchParams) {\n const data = new URLSearchParams(opts.data ?? '');\n data.append('client_id', this.#clientAuthentication.clientId);\n data.append('client_secret', this.#clientAuthentication.clientSecret || '');\n opts.data = data;\n }\n else if (contentType?.startsWith('application/json')) {\n opts.data = opts.data || {};\n Object.assign(opts.data, {\n client_id: this.#clientAuthentication.clientId,\n client_secret: this.#clientAuthentication.clientSecret || '',\n });\n }\n else {\n throw new Error(`${contentType} content-types are not supported with ` +\n `${this.#clientAuthentication.confidentialClientType} ` +\n 'client authentication');\n }\n }\n }\n /**\n * Retry config for Auth-related requests.\n *\n * @remarks\n *\n * This is not a part of the default {@link AuthClient.transporter transporter/gaxios}\n * config as some downstream APIs would prefer if customers explicitly enable retries,\n * such as GCS.\n */\n static get RETRY_CONFIG() {\n return {\n retry: true,\n retryConfig: {\n httpMethodsToRetry: ['GET', 'PUT', 'POST', 'HEAD', 'OPTIONS', 'DELETE'],\n },\n };\n }\n}\nexports.OAuthClientAuthHandler = OAuthClientAuthHandler;\n/**\n * Converts an OAuth error response to a native JavaScript Error.\n * @param resp The OAuth error response to convert to a native Error object.\n * @param err The optional original error. If provided, the error properties\n * will be copied to the new error.\n * @return The converted native Error object.\n */\nfunction getErrorFromOAuthErrorResponse(resp, err) {\n // Error response.\n const errorCode = resp.error;\n const errorDescription = resp.error_description;\n const errorUri = resp.error_uri;\n let message = `Error code ${errorCode}`;\n if (typeof errorDescription !== 'undefined') {\n message += `: ${errorDescription}`;\n }\n if (typeof errorUri !== 'undefined') {\n message += ` - ${errorUri}`;\n }\n const newError = new Error(message);\n // Copy properties from original error to newly generated error.\n if (err) {\n const keys = Object.keys(err);\n if (err.stack) {\n // Copy error.stack if available.\n keys.push('stack');\n }\n keys.forEach(key => {\n // Do not overwrite the message field.\n if (key !== 'message') {\n Object.defineProperty(newError, key, {\n value: err[key],\n writable: false,\n enumerable: true,\n });\n }\n });\n }\n return newError;\n}\n//# sourceMappingURL=oauth2common.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.StsCredentials = void 0;\nconst gaxios_1 = require(\"gaxios\");\nconst authclient_1 = require(\"./authclient\");\nconst oauth2common_1 = require(\"./oauth2common\");\nconst util_1 = require(\"../util\");\n/**\n * Implements the OAuth 2.0 token exchange based on\n * https://tools.ietf.org/html/rfc8693\n */\nclass StsCredentials extends oauth2common_1.OAuthClientAuthHandler {\n #tokenExchangeEndpoint;\n /**\n * Initializes an STS credentials instance.\n *\n * @param options The STS credentials instance options. Passing an `tokenExchangeEndpoint` directly is **@DEPRECATED**.\n * @param clientAuthentication **@DEPRECATED**. Provide a {@link StsCredentialsConstructionOptions `StsCredentialsConstructionOptions`} object in the first parameter instead.\n */\n constructor(options = {\n tokenExchangeEndpoint: '',\n }, \n /**\n * @deprecated - provide a {@link StsCredentialsConstructionOptions `StsCredentialsConstructionOptions`} object in the first parameter instead\n */\n clientAuthentication) {\n if (typeof options !== 'object' || options instanceof URL) {\n options = {\n tokenExchangeEndpoint: options,\n clientAuthentication,\n };\n }\n super(options);\n this.#tokenExchangeEndpoint = options.tokenExchangeEndpoint;\n }\n /**\n * Exchanges the provided token for another type of token based on the\n * rfc8693 spec.\n * @param stsCredentialsOptions The token exchange options used to populate\n * the token exchange request.\n * @param additionalHeaders Optional additional headers to pass along the\n * request.\n * @param options Optional additional GCP-specific non-spec defined options\n * to send with the request.\n * Example: `&options=${encodeUriComponent(JSON.stringified(options))}`\n * @return A promise that resolves with the token exchange response containing\n * the requested token and its expiration time.\n */\n async exchangeToken(stsCredentialsOptions, headers, options) {\n const values = {\n grant_type: stsCredentialsOptions.grantType,\n resource: stsCredentialsOptions.resource,\n audience: stsCredentialsOptions.audience,\n scope: stsCredentialsOptions.scope?.join(' '),\n requested_token_type: stsCredentialsOptions.requestedTokenType,\n subject_token: stsCredentialsOptions.subjectToken,\n subject_token_type: stsCredentialsOptions.subjectTokenType,\n actor_token: stsCredentialsOptions.actingParty?.actorToken,\n actor_token_type: stsCredentialsOptions.actingParty?.actorTokenType,\n // Non-standard GCP-specific options.\n options: options && JSON.stringify(options),\n };\n const opts = {\n ...StsCredentials.RETRY_CONFIG,\n url: this.#tokenExchangeEndpoint.toString(),\n method: 'POST',\n headers,\n data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(values)),\n };\n authclient_1.AuthClient.setMethodName(opts, 'exchangeToken');\n // Apply OAuth client authentication.\n this.applyClientAuthenticationOptions(opts);\n try {\n const response = await this.transporter.request(opts);\n // Successful response.\n const stsSuccessfulResponse = response.data;\n stsSuccessfulResponse.res = response;\n return stsSuccessfulResponse;\n }\n catch (error) {\n // Translate error to OAuthError.\n if (error instanceof gaxios_1.GaxiosError && error.response) {\n throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, \n // Preserve other fields from the original error.\n error);\n }\n // Request could fail before the server responds.\n throw error;\n }\n }\n}\nexports.StsCredentials = StsCredentials;\n//# sourceMappingURL=stscredentials.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BaseExternalAccountClient = exports.CLOUD_RESOURCE_MANAGER = exports.EXTERNAL_ACCOUNT_TYPE = exports.EXPIRATION_TIME_OFFSET = void 0;\nconst gaxios_1 = require(\"gaxios\");\nconst stream = require(\"stream\");\nconst authclient_1 = require(\"./authclient\");\nconst sts = require(\"./stscredentials\");\nconst util_1 = require(\"../util\");\nconst shared_cjs_1 = require(\"../shared.cjs\");\n/**\n * The required token exchange grant_type: rfc8693#section-2.1\n */\nconst STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange';\n/**\n * The requested token exchange requested_token_type: rfc8693#section-2.1\n */\nconst STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';\n/** The default OAuth scope to request when none is provided. */\nconst DEFAULT_OAUTH_SCOPE = 'https://www.googleapis.com/auth/cloud-platform';\n/** Default impersonated token lifespan in seconds.*/\nconst DEFAULT_TOKEN_LIFESPAN = 3600;\n/**\n * Offset to take into account network delays and server clock skews.\n */\nexports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000;\n/**\n * The credentials JSON file type for external account clients.\n * There are 3 types of JSON configs:\n * 1. authorized_user => Google end user credential\n * 2. service_account => Google service account credential\n * 3. external_Account => non-GCP service (eg. AWS, Azure, K8s)\n */\nexports.EXTERNAL_ACCOUNT_TYPE = 'external_account';\n/**\n * Cloud resource manager URL used to retrieve project information.\n *\n * @deprecated use {@link BaseExternalAccountClient.cloudResourceManagerURL} instead\n **/\nexports.CLOUD_RESOURCE_MANAGER = 'https://cloudresourcemanager.googleapis.com/v1/projects/';\n/** The workforce audience pattern. */\nconst WORKFORCE_AUDIENCE_PATTERN = '//iam\\\\.googleapis\\\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+';\nconst DEFAULT_TOKEN_URL = 'https://sts.{universeDomain}/v1/token';\n/**\n * Base external account client. This is used to instantiate AuthClients for\n * exchanging external account credentials for GCP access token and authorizing\n * requests to GCP APIs.\n * The base class implements common logic for exchanging various type of\n * external credentials for GCP access token. The logic of determining and\n * retrieving the external credential based on the environment and\n * credential_source will be left for the subclasses.\n */\nclass BaseExternalAccountClient extends authclient_1.AuthClient {\n /**\n * OAuth scopes for the GCP access token to use. When not provided,\n * the default https://www.googleapis.com/auth/cloud-platform is\n * used.\n */\n scopes;\n projectNumber;\n audience;\n subjectTokenType;\n stsCredential;\n clientAuth;\n credentialSourceType;\n cachedAccessToken;\n serviceAccountImpersonationUrl;\n serviceAccountImpersonationLifetime;\n workforcePoolUserProject;\n configLifetimeRequested;\n tokenUrl;\n /**\n * @example\n * ```ts\n * new URL('https://cloudresourcemanager.googleapis.com/v1/projects/');\n * ```\n */\n cloudResourceManagerURL;\n supplierContext;\n /**\n * A pending access token request. Used for concurrent calls.\n */\n #pendingAccessToken = null;\n /**\n * Instantiate a BaseExternalAccountClient instance using the provided JSON\n * object loaded from an external account credentials file.\n * @param options The external account options object typically loaded\n * from the external account JSON credential file. The camelCased options\n * are aliases for the snake_cased options.\n */\n constructor(options) {\n super(options);\n const opts = (0, util_1.originalOrCamelOptions)(options);\n const type = opts.get('type');\n if (type && type !== exports.EXTERNAL_ACCOUNT_TYPE) {\n throw new Error(`Expected \"${exports.EXTERNAL_ACCOUNT_TYPE}\" type but ` +\n `received \"${options.type}\"`);\n }\n const clientId = opts.get('client_id');\n const clientSecret = opts.get('client_secret');\n this.tokenUrl =\n opts.get('token_url') ??\n DEFAULT_TOKEN_URL.replace('{universeDomain}', this.universeDomain);\n const subjectTokenType = opts.get('subject_token_type');\n const workforcePoolUserProject = opts.get('workforce_pool_user_project');\n const serviceAccountImpersonationUrl = opts.get('service_account_impersonation_url');\n const serviceAccountImpersonation = opts.get('service_account_impersonation');\n const serviceAccountImpersonationLifetime = (0, util_1.originalOrCamelOptions)(serviceAccountImpersonation).get('token_lifetime_seconds');\n this.cloudResourceManagerURL = new URL(opts.get('cloud_resource_manager_url') ||\n `https://cloudresourcemanager.${this.universeDomain}/v1/projects/`);\n if (clientId) {\n this.clientAuth = {\n confidentialClientType: 'basic',\n clientId,\n clientSecret,\n };\n }\n this.stsCredential = new sts.StsCredentials({\n tokenExchangeEndpoint: this.tokenUrl,\n clientAuthentication: this.clientAuth,\n });\n this.scopes = opts.get('scopes') || [DEFAULT_OAUTH_SCOPE];\n this.cachedAccessToken = null;\n this.audience = opts.get('audience');\n this.subjectTokenType = subjectTokenType;\n this.workforcePoolUserProject = workforcePoolUserProject;\n const workforceAudiencePattern = new RegExp(WORKFORCE_AUDIENCE_PATTERN);\n if (this.workforcePoolUserProject &&\n !this.audience.match(workforceAudiencePattern)) {\n throw new Error('workforcePoolUserProject should not be set for non-workforce pool ' +\n 'credentials.');\n }\n this.serviceAccountImpersonationUrl = serviceAccountImpersonationUrl;\n this.serviceAccountImpersonationLifetime =\n serviceAccountImpersonationLifetime;\n if (this.serviceAccountImpersonationLifetime) {\n this.configLifetimeRequested = true;\n }\n else {\n this.configLifetimeRequested = false;\n this.serviceAccountImpersonationLifetime = DEFAULT_TOKEN_LIFESPAN;\n }\n this.projectNumber = this.getProjectNumber(this.audience);\n this.supplierContext = {\n audience: this.audience,\n subjectTokenType: this.subjectTokenType,\n transporter: this.transporter,\n };\n }\n /** The service account email to be impersonated, if available. */\n getServiceAccountEmail() {\n if (this.serviceAccountImpersonationUrl) {\n if (this.serviceAccountImpersonationUrl.length > 256) {\n /**\n * Prevents DOS attacks.\n * @see {@link https://github.com/googleapis/google-auth-library-nodejs/security/code-scanning/84}\n **/\n throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);\n }\n // Parse email from URL. The formal looks as follows:\n // https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/name@project-id.iam.gserviceaccount.com:generateAccessToken\n const re = /serviceAccounts\\/(?[^:]+):generateAccessToken$/;\n const result = re.exec(this.serviceAccountImpersonationUrl);\n return result?.groups?.email || null;\n }\n return null;\n }\n /**\n * Provides a mechanism to inject GCP access tokens directly.\n * When the provided credential expires, a new credential, using the\n * external account options, is retrieved.\n * @param credentials The Credentials object to set on the current client.\n */\n setCredentials(credentials) {\n super.setCredentials(credentials);\n this.cachedAccessToken = credentials;\n }\n /**\n * @return A promise that resolves with the current GCP access token\n * response. If the current credential is expired, a new one is retrieved.\n */\n async getAccessToken() {\n // If cached access token is unavailable or expired, force refresh.\n if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) {\n await this.refreshAccessTokenAsync();\n }\n // Return GCP access token in GetAccessTokenResponse format.\n return {\n token: this.cachedAccessToken.access_token,\n res: this.cachedAccessToken.res,\n };\n }\n /**\n * The main authentication interface. It takes an optional url which when\n * present is the endpoint being accessed, and returns a Promise which\n * resolves with authorization header fields.\n *\n * The result has the form:\n * { authorization: 'Bearer ' }\n */\n async getRequestHeaders() {\n const accessTokenResponse = await this.getAccessToken();\n const headers = new Headers({\n authorization: `Bearer ${accessTokenResponse.token}`,\n });\n return this.addSharedMetadataHeaders(headers);\n }\n request(opts, callback) {\n if (callback) {\n this.requestAsync(opts).then(r => callback(null, r), e => {\n return callback(e, e.response);\n });\n }\n else {\n return this.requestAsync(opts);\n }\n }\n /**\n * @return A promise that resolves with the project ID corresponding to the\n * current workload identity pool or current workforce pool if\n * determinable. For workforce pool credential, it returns the project ID\n * corresponding to the workforcePoolUserProject.\n * This is introduced to match the current pattern of using the Auth\n * library:\n * const projectId = await auth.getProjectId();\n * const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;\n * const res = await client.request({ url });\n * The resource may not have permission\n * (resourcemanager.projects.get) to call this API or the required\n * scopes may not be selected:\n * https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes\n */\n async getProjectId() {\n const projectNumber = this.projectNumber || this.workforcePoolUserProject;\n if (this.projectId) {\n // Return previously determined project ID.\n return this.projectId;\n }\n else if (projectNumber) {\n // Preferable not to use request() to avoid retrial policies.\n const headers = await this.getRequestHeaders();\n const opts = {\n ...BaseExternalAccountClient.RETRY_CONFIG,\n headers,\n url: `${this.cloudResourceManagerURL.toString()}${projectNumber}`,\n };\n authclient_1.AuthClient.setMethodName(opts, 'getProjectId');\n const response = await this.transporter.request(opts);\n this.projectId = response.data.projectId;\n return this.projectId;\n }\n return null;\n }\n /**\n * Authenticates the provided HTTP request, processes it and resolves with the\n * returned response.\n * @param opts The HTTP request options.\n * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure.\n * @return A promise that resolves with the successful response.\n */\n async requestAsync(opts, reAuthRetried = false) {\n let response;\n try {\n const requestHeaders = await this.getRequestHeaders();\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);\n this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders);\n response = await this.transporter.request(opts);\n }\n catch (e) {\n const res = e.response;\n if (res) {\n const statusCode = res.status;\n // Retry the request for metadata if the following criteria are true:\n // - We haven't already retried. It only makes sense to retry once.\n // - The response was a 401 or a 403\n // - The request didn't send a readableStream\n // - forceRefreshOnFailure is true\n const isReadableStream = res.config.data instanceof stream.Readable;\n const isAuthErr = statusCode === 401 || statusCode === 403;\n if (!reAuthRetried &&\n isAuthErr &&\n !isReadableStream &&\n this.forceRefreshOnFailure) {\n await this.refreshAccessTokenAsync();\n return await this.requestAsync(opts, true);\n }\n }\n throw e;\n }\n return response;\n }\n /**\n * Forces token refresh, even if unexpired tokens are currently cached.\n * External credentials are exchanged for GCP access tokens via the token\n * exchange endpoint and other settings provided in the client options\n * object.\n * If the service_account_impersonation_url is provided, an additional\n * step to exchange the external account GCP access token for a service\n * account impersonated token is performed.\n * @return A promise that resolves with the fresh GCP access tokens.\n */\n async refreshAccessTokenAsync() {\n // Use an existing access token request, or cache a new one\n this.#pendingAccessToken =\n this.#pendingAccessToken || this.#internalRefreshAccessTokenAsync();\n try {\n return await this.#pendingAccessToken;\n }\n finally {\n // clear pending access token for future requests\n this.#pendingAccessToken = null;\n }\n }\n async #internalRefreshAccessTokenAsync() {\n // Retrieve the external credential.\n const subjectToken = await this.retrieveSubjectToken();\n // Construct the STS credentials options.\n const stsCredentialsOptions = {\n grantType: STS_GRANT_TYPE,\n audience: this.audience,\n requestedTokenType: STS_REQUEST_TOKEN_TYPE,\n subjectToken,\n subjectTokenType: this.subjectTokenType,\n // generateAccessToken requires the provided access token to have\n // scopes:\n // https://www.googleapis.com/auth/iam or\n // https://www.googleapis.com/auth/cloud-platform\n // The new service account access token scopes will match the user\n // provided ones.\n scope: this.serviceAccountImpersonationUrl\n ? [DEFAULT_OAUTH_SCOPE]\n : this.getScopesArray(),\n };\n // Exchange the external credentials for a GCP access token.\n // Client auth is prioritized over passing the workforcePoolUserProject\n // parameter for STS token exchange.\n const additionalOptions = !this.clientAuth && this.workforcePoolUserProject\n ? { userProject: this.workforcePoolUserProject }\n : undefined;\n const additionalHeaders = new Headers({\n 'x-goog-api-client': this.getMetricsHeaderValue(),\n });\n const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, additionalHeaders, additionalOptions);\n if (this.serviceAccountImpersonationUrl) {\n this.cachedAccessToken = await this.getImpersonatedAccessToken(stsResponse.access_token);\n }\n else if (stsResponse.expires_in) {\n // Save response in cached access token.\n this.cachedAccessToken = {\n access_token: stsResponse.access_token,\n expiry_date: new Date().getTime() + stsResponse.expires_in * 1000,\n res: stsResponse.res,\n };\n }\n else {\n // Save response in cached access token.\n this.cachedAccessToken = {\n access_token: stsResponse.access_token,\n res: stsResponse.res,\n };\n }\n // Save credentials.\n this.credentials = {};\n Object.assign(this.credentials, this.cachedAccessToken);\n delete this.credentials.res;\n // Trigger tokens event to notify external listeners.\n this.emit('tokens', {\n refresh_token: null,\n expiry_date: this.cachedAccessToken.expiry_date,\n access_token: this.cachedAccessToken.access_token,\n token_type: 'Bearer',\n id_token: null,\n });\n // Return the cached access token.\n return this.cachedAccessToken;\n }\n /**\n * Returns the workload identity pool project number if it is determinable\n * from the audience resource name.\n * @param audience The STS audience used to determine the project number.\n * @return The project number associated with the workload identity pool, if\n * this can be determined from the STS audience field. Otherwise, null is\n * returned.\n */\n getProjectNumber(audience) {\n // STS audience pattern:\n // //iam.googleapis.com/projects/$PROJECT_NUMBER/locations/...\n const match = audience.match(/\\/projects\\/([^/]+)/);\n if (!match) {\n return null;\n }\n return match[1];\n }\n /**\n * Exchanges an external account GCP access token for a service\n * account impersonated access token using iamcredentials\n * GenerateAccessToken API.\n * @param token The access token to exchange for a service account access\n * token.\n * @return A promise that resolves with the service account impersonated\n * credentials response.\n */\n async getImpersonatedAccessToken(token) {\n const opts = {\n ...BaseExternalAccountClient.RETRY_CONFIG,\n url: this.serviceAccountImpersonationUrl,\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${token}`,\n },\n data: {\n scope: this.getScopesArray(),\n lifetime: this.serviceAccountImpersonationLifetime + 's',\n },\n };\n authclient_1.AuthClient.setMethodName(opts, 'getImpersonatedAccessToken');\n const response = await this.transporter.request(opts);\n const successResponse = response.data;\n return {\n access_token: successResponse.accessToken,\n // Convert from ISO format to timestamp.\n expiry_date: new Date(successResponse.expireTime).getTime(),\n res: response,\n };\n }\n /**\n * Returns whether the provided credentials are expired or not.\n * If there is no expiry time, assumes the token is not expired or expiring.\n * @param accessToken The credentials to check for expiration.\n * @return Whether the credentials are expired or not.\n */\n isExpired(accessToken) {\n const now = new Date().getTime();\n return accessToken.expiry_date\n ? now >= accessToken.expiry_date - this.eagerRefreshThresholdMillis\n : false;\n }\n /**\n * @return The list of scopes for the requested GCP access token.\n */\n getScopesArray() {\n // Since scopes can be provided as string or array, the type should\n // be normalized.\n if (typeof this.scopes === 'string') {\n return [this.scopes];\n }\n return this.scopes || [DEFAULT_OAUTH_SCOPE];\n }\n getMetricsHeaderValue() {\n const nodeVersion = process.version.replace(/^v/, '');\n const saImpersonation = this.serviceAccountImpersonationUrl !== undefined;\n const credentialSourceType = this.credentialSourceType\n ? this.credentialSourceType\n : 'unknown';\n return `gl-node/${nodeVersion} auth/${shared_cjs_1.pkg.version} google-byoid-sdk source/${credentialSourceType} sa-impersonation/${saImpersonation} config-lifetime/${this.configLifetimeRequested}`;\n }\n getTokenUrl() {\n return this.tokenUrl;\n }\n}\nexports.BaseExternalAccountClient = BaseExternalAccountClient;\n//# sourceMappingURL=baseexternalclient.js.map", "\"use strict\";\n// Copyright 2024 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.FileSubjectTokenSupplier = void 0;\nconst util_1 = require(\"util\");\nconst fs = require(\"fs\");\n// fs.readfile is undefined in browser karma tests causing\n// `npm run browser-test` to fail as test.oauth2.ts imports this file via\n// src/index.ts.\n// Fallback to void function to avoid promisify throwing a TypeError.\nconst readFile = (0, util_1.promisify)(fs.readFile ?? (() => { }));\nconst realpath = (0, util_1.promisify)(fs.realpath ?? (() => { }));\nconst lstat = (0, util_1.promisify)(fs.lstat ?? (() => { }));\n/**\n * Internal subject token supplier implementation used when a file location\n * is configured in the credential configuration used to build an {@link IdentityPoolClient}\n */\nclass FileSubjectTokenSupplier {\n filePath;\n formatType;\n subjectTokenFieldName;\n /**\n * Instantiates a new file based subject token supplier.\n * @param opts The file subject token supplier options to build the supplier\n * with.\n */\n constructor(opts) {\n this.filePath = opts.filePath;\n this.formatType = opts.formatType;\n this.subjectTokenFieldName = opts.subjectTokenFieldName;\n }\n /**\n * Returns the subject token stored at the file specified in the constructor.\n * @param context {@link ExternalAccountSupplierContext} from the calling\n * {@link IdentityPoolClient}, contains the requested audience and subject\n * token type for the external account identity. Not used.\n */\n async getSubjectToken() {\n // Make sure there is a file at the path. lstatSync will throw if there is\n // nothing there.\n let parsedFilePath = this.filePath;\n try {\n // Resolve path to actual file in case of symlink. Expect a thrown error\n // if not resolvable.\n parsedFilePath = await realpath(parsedFilePath);\n if (!(await lstat(parsedFilePath)).isFile()) {\n throw new Error();\n }\n }\n catch (err) {\n if (err instanceof Error) {\n err.message = `The file at ${parsedFilePath} does not exist, or it is not a file. ${err.message}`;\n }\n throw err;\n }\n let subjectToken;\n const rawText = await readFile(parsedFilePath, { encoding: 'utf8' });\n if (this.formatType === 'text') {\n subjectToken = rawText;\n }\n else if (this.formatType === 'json' && this.subjectTokenFieldName) {\n const json = JSON.parse(rawText);\n subjectToken = json[this.subjectTokenFieldName];\n }\n if (!subjectToken) {\n throw new Error('Unable to parse the subject_token from the credential_source file');\n }\n return subjectToken;\n }\n}\nexports.FileSubjectTokenSupplier = FileSubjectTokenSupplier;\n//# sourceMappingURL=filesubjecttokensupplier.js.map", "\"use strict\";\n// Copyright 2024 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.UrlSubjectTokenSupplier = void 0;\nconst authclient_1 = require(\"./authclient\");\n/**\n * Internal subject token supplier implementation used when a URL\n * is configured in the credential configuration used to build an {@link IdentityPoolClient}\n */\nclass UrlSubjectTokenSupplier {\n url;\n headers;\n formatType;\n subjectTokenFieldName;\n additionalGaxiosOptions;\n /**\n * Instantiates a URL subject token supplier.\n * @param opts The URL subject token supplier options to build the supplier with.\n */\n constructor(opts) {\n this.url = opts.url;\n this.formatType = opts.formatType;\n this.subjectTokenFieldName = opts.subjectTokenFieldName;\n this.headers = opts.headers;\n this.additionalGaxiosOptions = opts.additionalGaxiosOptions;\n }\n /**\n * Sends a GET request to the URL provided in the constructor and resolves\n * with the returned external subject token.\n * @param context {@link ExternalAccountSupplierContext} from the calling\n * {@link IdentityPoolClient}, contains the requested audience and subject\n * token type for the external account identity. Not used.\n */\n async getSubjectToken(context) {\n const opts = {\n ...this.additionalGaxiosOptions,\n url: this.url,\n method: 'GET',\n headers: this.headers,\n };\n authclient_1.AuthClient.setMethodName(opts, 'getSubjectToken');\n let subjectToken;\n if (this.formatType === 'text') {\n const response = await context.transporter.request(opts);\n subjectToken = response.data;\n }\n else if (this.formatType === 'json' && this.subjectTokenFieldName) {\n const response = await context.transporter.request(opts);\n subjectToken = response.data[this.subjectTokenFieldName];\n }\n if (!subjectToken) {\n throw new Error('Unable to parse the subject_token from the credential_source URL');\n }\n return subjectToken;\n }\n}\nexports.UrlSubjectTokenSupplier = UrlSubjectTokenSupplier;\n//# sourceMappingURL=urlsubjecttokensupplier.js.map", "\"use strict\";\n// Copyright 2025 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CertificateSubjectTokenSupplier = exports.InvalidConfigurationError = exports.CertificateSourceUnavailableError = exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = void 0;\nconst util_1 = require(\"../util\");\nconst fs = require(\"fs\");\nconst crypto_1 = require(\"crypto\");\nconst https = require(\"https\");\nexports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = 'GOOGLE_API_CERTIFICATE_CONFIG';\n/**\n * Thrown when the certificate source cannot be located or accessed.\n */\nclass CertificateSourceUnavailableError extends Error {\n constructor(message) {\n super(message);\n this.name = 'CertificateSourceUnavailableError';\n }\n}\nexports.CertificateSourceUnavailableError = CertificateSourceUnavailableError;\n/**\n * Thrown for invalid configuration that is not related to file availability.\n */\nclass InvalidConfigurationError extends Error {\n constructor(message) {\n super(message);\n this.name = 'InvalidConfigurationError';\n }\n}\nexports.InvalidConfigurationError = InvalidConfigurationError;\n/**\n * A subject token supplier that uses a client certificate for authentication.\n * It provides the certificate chain as the subject token for identity federation.\n */\nclass CertificateSubjectTokenSupplier {\n certificateConfigPath;\n trustChainPath;\n cert;\n key;\n /**\n * Initializes a new instance of the CertificateSubjectTokenSupplier.\n * @param opts The configuration options for the supplier.\n */\n constructor(opts) {\n if (!opts.useDefaultCertificateConfig && !opts.certificateConfigLocation) {\n throw new InvalidConfigurationError('Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.');\n }\n if (opts.useDefaultCertificateConfig && opts.certificateConfigLocation) {\n throw new InvalidConfigurationError('Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.');\n }\n this.trustChainPath = opts.trustChainPath;\n this.certificateConfigPath = opts.certificateConfigLocation ?? '';\n }\n /**\n * Creates an HTTPS agent configured with the client certificate and private key for mTLS.\n * @returns An mTLS-configured https.Agent.\n */\n async createMtlsHttpsAgent() {\n if (!this.key || !this.cert) {\n throw new InvalidConfigurationError('Cannot create mTLS Agent with missing certificate or key');\n }\n return new https.Agent({ key: this.key, cert: this.cert });\n }\n /**\n * Constructs the subject token, which is the base64-encoded certificate chain.\n * @returns A promise that resolves with the subject token.\n */\n async getSubjectToken() {\n // The \"subject token\" in this context is the processed certificate chain.\n this.certificateConfigPath = await this.#resolveCertificateConfigFilePath();\n const { certPath, keyPath } = await this.#getCertAndKeyPaths();\n ({ cert: this.cert, key: this.key } = await this.#getKeyAndCert(certPath, keyPath));\n return await this.#processChainFromPaths(this.cert);\n }\n /**\n * Resolves the absolute path to the certificate configuration file\n * by checking the \"certificate_config_location\" provided in the ADC file,\n * or the \"GOOGLE_API_CERTIFICATE_CONFIG\" environment variable\n * or in the default gcloud path.\n * @param overridePath An optional path to check first.\n * @returns The resolved file path.\n */\n async #resolveCertificateConfigFilePath() {\n // 1. Check for the override path from constructor options.\n const overridePath = this.certificateConfigPath;\n if (overridePath) {\n if (await (0, util_1.isValidFile)(overridePath)) {\n return overridePath;\n }\n throw new CertificateSourceUnavailableError(`Provided certificate config path is invalid: ${overridePath}`);\n }\n // 2. Check the standard environment variable.\n const envPath = process.env[exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];\n if (envPath) {\n if (await (0, util_1.isValidFile)(envPath)) {\n return envPath;\n }\n throw new CertificateSourceUnavailableError(`Path from environment variable \"${exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}\" is invalid: ${envPath}`);\n }\n // 3. Check the well-known gcloud config location.\n const wellKnownPath = (0, util_1.getWellKnownCertificateConfigFileLocation)();\n if (await (0, util_1.isValidFile)(wellKnownPath)) {\n return wellKnownPath;\n }\n // 4. If none are found, throw an error.\n throw new CertificateSourceUnavailableError('Could not find certificate configuration file. Searched override path, ' +\n `the \"${exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}\" env var, and the gcloud path (${wellKnownPath}).`);\n }\n /**\n * Reads and parses the certificate config JSON file to extract the certificate and key paths.\n * @returns An object containing the certificate and key paths.\n */\n async #getCertAndKeyPaths() {\n const configPath = this.certificateConfigPath;\n let fileContents;\n try {\n fileContents = await fs.promises.readFile(configPath, 'utf8');\n }\n catch (err) {\n throw new CertificateSourceUnavailableError(`Failed to read certificate config file at: ${configPath}`);\n }\n try {\n const config = JSON.parse(fileContents);\n const certPath = config?.cert_configs?.workload?.cert_path;\n const keyPath = config?.cert_configs?.workload?.key_path;\n if (!certPath || !keyPath) {\n throw new InvalidConfigurationError(`Certificate config file (${configPath}) is missing required \"cert_path\" or \"key_path\" in the workload config.`);\n }\n return { certPath, keyPath };\n }\n catch (e) {\n if (e instanceof InvalidConfigurationError)\n throw e;\n throw new InvalidConfigurationError(`Failed to parse certificate config from ${configPath}: ${e.message}`);\n }\n }\n /**\n * Reads and parses the cert and key files get their content and check valid format.\n * @returns An object containing the cert content and key content in buffer format.\n */\n async #getKeyAndCert(certPath, keyPath) {\n let cert, key;\n try {\n cert = await fs.promises.readFile(certPath);\n new crypto_1.X509Certificate(cert);\n }\n catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new CertificateSourceUnavailableError(`Failed to read certificate file at ${certPath}: ${message}`);\n }\n try {\n key = await fs.promises.readFile(keyPath);\n (0, crypto_1.createPrivateKey)(key);\n }\n catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new CertificateSourceUnavailableError(`Failed to read private key file at ${keyPath}: ${message}`);\n }\n return { cert, key };\n }\n /**\n * Reads the leaf certificate and trust chain, combines them,\n * and returns a JSON array of base64-encoded certificates.\n * @returns A stringified JSON array of the certificate chain.\n */\n async #processChainFromPaths(leafCertBuffer) {\n const leafCert = new crypto_1.X509Certificate(leafCertBuffer);\n // If no trust chain is provided, just use the successfully parsed leaf certificate.\n if (!this.trustChainPath) {\n return JSON.stringify([leafCert.raw.toString('base64')]);\n }\n // Handle the trust chain logic.\n try {\n const chainPems = await fs.promises.readFile(this.trustChainPath, 'utf8');\n const pemBlocks = chainPems.match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g) ?? [];\n const chainCerts = pemBlocks.map((pem, index) => {\n try {\n return new crypto_1.X509Certificate(pem);\n }\n catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n // Throw a more precise error if a single certificate in the chain is invalid.\n throw new InvalidConfigurationError(`Failed to parse certificate at index ${index} in trust chain file ${this.trustChainPath}: ${message}`);\n }\n });\n const leafIndex = chainCerts.findIndex(chainCert => leafCert.raw.equals(chainCert.raw));\n let finalChain;\n if (leafIndex === -1) {\n // Leaf not found, so prepend it to the chain.\n finalChain = [leafCert, ...chainCerts];\n }\n else if (leafIndex === 0) {\n // Leaf is already the first element, so the chain is correctly ordered.\n finalChain = chainCerts;\n }\n else {\n // Leaf is in the chain but not at the top, which is invalid.\n throw new InvalidConfigurationError(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${leafIndex}).`);\n }\n return JSON.stringify(finalChain.map(cert => cert.raw.toString('base64')));\n }\n catch (err) {\n // Re-throw our specific configuration errors.\n if (err instanceof InvalidConfigurationError)\n throw err;\n const message = err instanceof Error ? err.message : String(err);\n throw new CertificateSourceUnavailableError(`Failed to process certificate chain from ${this.trustChainPath}: ${message}`);\n }\n }\n}\nexports.CertificateSubjectTokenSupplier = CertificateSubjectTokenSupplier;\n//# sourceMappingURL=certificatesubjecttokensupplier.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.IdentityPoolClient = void 0;\nconst baseexternalclient_1 = require(\"./baseexternalclient\");\nconst util_1 = require(\"../util\");\nconst filesubjecttokensupplier_1 = require(\"./filesubjecttokensupplier\");\nconst urlsubjecttokensupplier_1 = require(\"./urlsubjecttokensupplier\");\nconst certificatesubjecttokensupplier_1 = require(\"./certificatesubjecttokensupplier\");\nconst stscredentials_1 = require(\"./stscredentials\");\nconst gaxios_1 = require(\"gaxios\");\n/**\n * Defines the Url-sourced and file-sourced external account clients mainly\n * used for K8s and Azure workloads.\n */\nclass IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient {\n subjectTokenSupplier;\n /**\n * Instantiate an IdentityPoolClient instance using the provided JSON\n * object loaded from an external account credentials file.\n * An error is thrown if the credential is not a valid file-sourced or\n * url-sourced credential or a workforce pool user project is provided\n * with a non workforce audience.\n * @param options The external account options object typically loaded\n * from the external account JSON credential file. The camelCased options\n * are aliases for the snake_cased options.\n */\n constructor(options) {\n super(options);\n const opts = (0, util_1.originalOrCamelOptions)(options);\n const credentialSource = opts.get('credential_source');\n const subjectTokenSupplier = opts.get('subject_token_supplier');\n // Validate credential sourcing configuration.\n if (!credentialSource && !subjectTokenSupplier) {\n throw new Error('A credential source or subject token supplier must be specified.');\n }\n if (credentialSource && subjectTokenSupplier) {\n throw new Error('Only one of credential source or subject token supplier can be specified.');\n }\n if (subjectTokenSupplier) {\n this.subjectTokenSupplier = subjectTokenSupplier;\n this.credentialSourceType = 'programmatic';\n }\n else {\n const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource);\n const formatOpts = (0, util_1.originalOrCamelOptions)(credentialSourceOpts.get('format'));\n // Text is the default format type.\n const formatType = formatOpts.get('type') || 'text';\n const formatSubjectTokenFieldName = formatOpts.get('subject_token_field_name');\n if (formatType !== 'json' && formatType !== 'text') {\n throw new Error(`Invalid credential_source format \"${formatType}\"`);\n }\n if (formatType === 'json' && !formatSubjectTokenFieldName) {\n throw new Error('Missing subject_token_field_name for JSON credential_source format');\n }\n const file = credentialSourceOpts.get('file');\n const url = credentialSourceOpts.get('url');\n const certificate = credentialSourceOpts.get('certificate');\n const headers = credentialSourceOpts.get('headers');\n if ((file && url) || (url && certificate) || (file && certificate)) {\n throw new Error('No valid Identity Pool \"credential_source\" provided, must be either file, url, or certificate.');\n }\n else if (file) {\n this.credentialSourceType = 'file';\n this.subjectTokenSupplier = new filesubjecttokensupplier_1.FileSubjectTokenSupplier({\n filePath: file,\n formatType: formatType,\n subjectTokenFieldName: formatSubjectTokenFieldName,\n });\n }\n else if (url) {\n this.credentialSourceType = 'url';\n this.subjectTokenSupplier = new urlsubjecttokensupplier_1.UrlSubjectTokenSupplier({\n url: url,\n formatType: formatType,\n subjectTokenFieldName: formatSubjectTokenFieldName,\n headers: headers,\n additionalGaxiosOptions: IdentityPoolClient.RETRY_CONFIG,\n });\n }\n else if (certificate) {\n this.credentialSourceType = 'certificate';\n const certificateSubjecttokensupplier = new certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier({\n useDefaultCertificateConfig: certificate.use_default_certificate_config,\n certificateConfigLocation: certificate.certificate_config_location,\n trustChainPath: certificate.trust_chain_path,\n });\n this.subjectTokenSupplier = certificateSubjecttokensupplier;\n }\n else {\n throw new Error('No valid Identity Pool \"credential_source\" provided, must be either file, url, or certificate.');\n }\n }\n }\n /**\n * Triggered when a external subject token is needed to be exchanged for a GCP\n * access token via GCP STS endpoint. Gets a subject token by calling\n * the configured {@link SubjectTokenSupplier}\n * @return A promise that resolves with the external subject token.\n */\n async retrieveSubjectToken() {\n const subjectToken = await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);\n if (this.subjectTokenSupplier instanceof certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier) {\n const mtlsAgent = await this.subjectTokenSupplier.createMtlsHttpsAgent();\n this.stsCredential = new stscredentials_1.StsCredentials({\n tokenExchangeEndpoint: this.getTokenUrl(),\n clientAuthentication: this.clientAuth,\n transporter: new gaxios_1.Gaxios({ agent: mtlsAgent }),\n });\n this.transporter = new gaxios_1.Gaxios({\n ...(this.transporter.defaults || {}),\n agent: mtlsAgent,\n });\n }\n return subjectToken;\n }\n}\nexports.IdentityPoolClient = IdentityPoolClient;\n//# sourceMappingURL=identitypoolclient.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AwsRequestSigner = void 0;\nconst gaxios_1 = require(\"gaxios\");\nconst crypto_1 = require(\"../crypto/crypto\");\n/** AWS Signature Version 4 signing algorithm identifier. */\nconst AWS_ALGORITHM = 'AWS4-HMAC-SHA256';\n/**\n * The termination string for the AWS credential scope value as defined in\n * https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html\n */\nconst AWS_REQUEST_TYPE = 'aws4_request';\n/**\n * Implements an AWS API request signer based on the AWS Signature Version 4\n * signing process.\n * https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html\n */\nclass AwsRequestSigner {\n getCredentials;\n region;\n crypto;\n /**\n * Instantiates an AWS API request signer used to send authenticated signed\n * requests to AWS APIs based on the AWS Signature Version 4 signing process.\n * This also provides a mechanism to generate the signed request without\n * sending it.\n * @param getCredentials A mechanism to retrieve AWS security credentials\n * when needed.\n * @param region The AWS region to use.\n */\n constructor(getCredentials, region) {\n this.getCredentials = getCredentials;\n this.region = region;\n this.crypto = (0, crypto_1.createCrypto)();\n }\n /**\n * Generates the signed request for the provided HTTP request for calling\n * an AWS API. This follows the steps described at:\n * https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html\n * @param amzOptions The AWS request options that need to be signed.\n * @return A promise that resolves with the GaxiosOptions containing the\n * signed HTTP request parameters.\n */\n async getRequestOptions(amzOptions) {\n if (!amzOptions.url) {\n throw new RangeError('\"url\" is required in \"amzOptions\"');\n }\n // Stringify JSON requests. This will be set in the request body of the\n // generated signed request.\n const requestPayloadData = typeof amzOptions.data === 'object'\n ? JSON.stringify(amzOptions.data)\n : amzOptions.data;\n const url = amzOptions.url;\n const method = amzOptions.method || 'GET';\n const requestPayload = amzOptions.body || requestPayloadData;\n const additionalAmzHeaders = amzOptions.headers;\n const awsSecurityCredentials = await this.getCredentials();\n const uri = new URL(url);\n if (typeof requestPayload !== 'string' && requestPayload !== undefined) {\n throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${requestPayload}`);\n }\n const headerMap = await generateAuthenticationHeaderMap({\n crypto: this.crypto,\n host: uri.host,\n canonicalUri: uri.pathname,\n canonicalQuerystring: uri.search.slice(1),\n method,\n region: this.region,\n securityCredentials: awsSecurityCredentials,\n requestPayload,\n additionalAmzHeaders,\n });\n // Append additional optional headers, eg. X-Amz-Target, Content-Type, etc.\n const headers = gaxios_1.Gaxios.mergeHeaders(\n // Add x-amz-date if available.\n headerMap.amzDate ? { 'x-amz-date': headerMap.amzDate } : {}, {\n authorization: headerMap.authorizationHeader,\n host: uri.host,\n }, additionalAmzHeaders || {});\n if (awsSecurityCredentials.token) {\n gaxios_1.Gaxios.mergeHeaders(headers, {\n 'x-amz-security-token': awsSecurityCredentials.token,\n });\n }\n const awsSignedReq = {\n url,\n method: method,\n headers,\n };\n if (requestPayload !== undefined) {\n awsSignedReq.body = requestPayload;\n }\n return awsSignedReq;\n }\n}\nexports.AwsRequestSigner = AwsRequestSigner;\n/**\n * Creates the HMAC-SHA256 hash of the provided message using the\n * provided key.\n *\n * @param crypto The crypto instance used to facilitate cryptographic\n * operations.\n * @param key The HMAC-SHA256 key to use.\n * @param msg The message to hash.\n * @return The computed hash bytes.\n */\nasync function sign(crypto, key, msg) {\n return await crypto.signWithHmacSha256(key, msg);\n}\n/**\n * Calculates the signing key used to calculate the signature for\n * AWS Signature Version 4 based on:\n * https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html\n *\n * @param crypto The crypto instance used to facilitate cryptographic\n * operations.\n * @param key The AWS secret access key.\n * @param dateStamp The '%Y%m%d' date format.\n * @param region The AWS region.\n * @param serviceName The AWS service name, eg. sts.\n * @return The signing key bytes.\n */\nasync function getSigningKey(crypto, key, dateStamp, region, serviceName) {\n const kDate = await sign(crypto, `AWS4${key}`, dateStamp);\n const kRegion = await sign(crypto, kDate, region);\n const kService = await sign(crypto, kRegion, serviceName);\n const kSigning = await sign(crypto, kService, 'aws4_request');\n return kSigning;\n}\n/**\n * Generates the authentication header map needed for generating the AWS\n * Signature Version 4 signed request.\n *\n * @param option The options needed to compute the authentication header map.\n * @return The AWS authentication header map which constitutes of the following\n * components: amz-date, authorization header and canonical query string.\n */\nasync function generateAuthenticationHeaderMap(options) {\n const additionalAmzHeaders = gaxios_1.Gaxios.mergeHeaders(options.additionalAmzHeaders);\n const requestPayload = options.requestPayload || '';\n // iam.amazonaws.com host => iam service.\n // sts.us-east-2.amazonaws.com => sts service.\n const serviceName = options.host.split('.')[0];\n const now = new Date();\n // Format: '%Y%m%dT%H%M%SZ'.\n const amzDate = now\n .toISOString()\n .replace(/[-:]/g, '')\n .replace(/\\.[0-9]+/, '');\n // Format: '%Y%m%d'.\n const dateStamp = now.toISOString().replace(/[-]/g, '').replace(/T.*/, '');\n // Add AWS token if available.\n if (options.securityCredentials.token) {\n additionalAmzHeaders.set('x-amz-security-token', options.securityCredentials.token);\n }\n // Header keys need to be sorted alphabetically.\n const amzHeaders = gaxios_1.Gaxios.mergeHeaders({\n host: options.host,\n }, \n // Previously the date was not fixed with x-amz- and could be provided manually.\n // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.req\n additionalAmzHeaders.has('date') ? {} : { 'x-amz-date': amzDate }, additionalAmzHeaders);\n let canonicalHeaders = '';\n // TypeScript is missing `Headers#keys` at the time of writing\n const signedHeadersList = [\n ...amzHeaders.keys(),\n ].sort();\n signedHeadersList.forEach(key => {\n canonicalHeaders += `${key}:${amzHeaders.get(key)}\\n`;\n });\n const signedHeaders = signedHeadersList.join(';');\n const payloadHash = await options.crypto.sha256DigestHex(requestPayload);\n // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html\n const canonicalRequest = `${options.method.toUpperCase()}\\n` +\n `${options.canonicalUri}\\n` +\n `${options.canonicalQuerystring}\\n` +\n `${canonicalHeaders}\\n` +\n `${signedHeaders}\\n` +\n `${payloadHash}`;\n const credentialScope = `${dateStamp}/${options.region}/${serviceName}/${AWS_REQUEST_TYPE}`;\n // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html\n const stringToSign = `${AWS_ALGORITHM}\\n` +\n `${amzDate}\\n` +\n `${credentialScope}\\n` +\n (await options.crypto.sha256DigestHex(canonicalRequest));\n // https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html\n const signingKey = await getSigningKey(options.crypto, options.securityCredentials.secretAccessKey, dateStamp, options.region, serviceName);\n const signature = await sign(options.crypto, signingKey, stringToSign);\n // https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html\n const authorizationHeader = `${AWS_ALGORITHM} Credential=${options.securityCredentials.accessKeyId}/` +\n `${credentialScope}, SignedHeaders=${signedHeaders}, ` +\n `Signature=${(0, crypto_1.fromArrayBufferToHex)(signature)}`;\n return {\n // Do not return x-amz-date if date is available.\n amzDate: additionalAmzHeaders.has('date') ? undefined : amzDate,\n authorizationHeader,\n canonicalQuerystring: options.canonicalQuerystring,\n };\n}\n//# sourceMappingURL=awsrequestsigner.js.map", "\"use strict\";\n// Copyright 2024 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DefaultAwsSecurityCredentialsSupplier = void 0;\nconst authclient_1 = require(\"./authclient\");\n/**\n * Internal AWS security credentials supplier implementation used by {@link AwsClient}\n * when a credential source is provided instead of a user defined supplier.\n * The logic is summarized as:\n * 1. If imdsv2_session_token_url is provided in the credential source, then\n * fetch the aws session token and include it in the headers of the\n * metadata requests. This is a requirement for IDMSv2 but optional\n * for IDMSv1.\n * 2. Retrieve AWS region from availability-zone.\n * 3a. Check AWS credentials in environment variables. If not found, get\n * from security-credentials endpoint.\n * 3b. Get AWS credentials from security-credentials endpoint. In order\n * to retrieve this, the AWS role needs to be determined by calling\n * security-credentials endpoint without any argument. Then the\n * credentials can be retrieved via: security-credentials/role_name\n * 4. Generate the signed request to AWS STS GetCallerIdentity action.\n * 5. Inject x-goog-cloud-target-resource into header and serialize the\n * signed request. This will be the subject-token to pass to GCP STS.\n */\nclass DefaultAwsSecurityCredentialsSupplier {\n regionUrl;\n securityCredentialsUrl;\n imdsV2SessionTokenUrl;\n additionalGaxiosOptions;\n /**\n * Instantiates a new DefaultAwsSecurityCredentialsSupplier using information\n * from the credential_source stored in the ADC file.\n * @param opts The default aws security credentials supplier options object to\n * build the supplier with.\n */\n constructor(opts) {\n this.regionUrl = opts.regionUrl;\n this.securityCredentialsUrl = opts.securityCredentialsUrl;\n this.imdsV2SessionTokenUrl = opts.imdsV2SessionTokenUrl;\n this.additionalGaxiosOptions = opts.additionalGaxiosOptions;\n }\n /**\n * Returns the active AWS region. This first checks to see if the region\n * is available as an environment variable. If it is not, then the supplier\n * will call the region URL.\n * @param context {@link ExternalAccountSupplierContext} from the calling\n * {@link AwsClient}, contains the requested audience and subject token type\n * for the external account identity.\n * @return A promise that resolves with the AWS region string.\n */\n async getAwsRegion(context) {\n // Priority order for region determination:\n // AWS_REGION > AWS_DEFAULT_REGION > metadata server.\n if (this.#regionFromEnv) {\n return this.#regionFromEnv;\n }\n const metadataHeaders = new Headers();\n if (!this.#regionFromEnv && this.imdsV2SessionTokenUrl) {\n metadataHeaders.set('x-aws-ec2-metadata-token', await this.#getImdsV2SessionToken(context.transporter));\n }\n if (!this.regionUrl) {\n throw new RangeError('Unable to determine AWS region due to missing ' +\n '\"options.credential_source.region_url\"');\n }\n const opts = {\n ...this.additionalGaxiosOptions,\n url: this.regionUrl,\n method: 'GET',\n headers: metadataHeaders,\n };\n authclient_1.AuthClient.setMethodName(opts, 'getAwsRegion');\n const response = await context.transporter.request(opts);\n // Remove last character. For example, if us-east-2b is returned,\n // the region would be us-east-2.\n return response.data.substr(0, response.data.length - 1);\n }\n /**\n * Returns AWS security credentials. This first checks to see if the credentials\n * is available as environment variables. If it is not, then the supplier\n * will call the security credentials URL.\n * @param context {@link ExternalAccountSupplierContext} from the calling\n * {@link AwsClient}, contains the requested audience and subject token type\n * for the external account identity.\n * @return A promise that resolves with the AWS security credentials.\n */\n async getAwsSecurityCredentials(context) {\n // Check environment variables for permanent credentials first.\n // https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html\n if (this.#securityCredentialsFromEnv) {\n return this.#securityCredentialsFromEnv;\n }\n const metadataHeaders = new Headers();\n if (this.imdsV2SessionTokenUrl) {\n metadataHeaders.set('x-aws-ec2-metadata-token', await this.#getImdsV2SessionToken(context.transporter));\n }\n // Since the role on a VM can change, we don't need to cache it.\n const roleName = await this.#getAwsRoleName(metadataHeaders, context.transporter);\n // Temporary credentials typically last for several hours.\n // Expiration is returned in response.\n // Consider future optimization of this logic to cache AWS tokens\n // until their natural expiration.\n const awsCreds = await this.#retrieveAwsSecurityCredentials(roleName, metadataHeaders, context.transporter);\n return {\n accessKeyId: awsCreds.AccessKeyId,\n secretAccessKey: awsCreds.SecretAccessKey,\n token: awsCreds.Token,\n };\n }\n /**\n * @param transporter The transporter to use for requests.\n * @return A promise that resolves with the IMDSv2 Session Token.\n */\n async #getImdsV2SessionToken(transporter) {\n const opts = {\n ...this.additionalGaxiosOptions,\n url: this.imdsV2SessionTokenUrl,\n method: 'PUT',\n headers: { 'x-aws-ec2-metadata-token-ttl-seconds': '300' },\n };\n authclient_1.AuthClient.setMethodName(opts, '#getImdsV2SessionToken');\n const response = await transporter.request(opts);\n return response.data;\n }\n /**\n * @param headers The headers to be used in the metadata request.\n * @param transporter The transporter to use for requests.\n * @return A promise that resolves with the assigned role to the current\n * AWS VM. This is needed for calling the security-credentials endpoint.\n */\n async #getAwsRoleName(headers, transporter) {\n if (!this.securityCredentialsUrl) {\n throw new Error('Unable to determine AWS role name due to missing ' +\n '\"options.credential_source.url\"');\n }\n const opts = {\n ...this.additionalGaxiosOptions,\n url: this.securityCredentialsUrl,\n method: 'GET',\n headers: headers,\n };\n authclient_1.AuthClient.setMethodName(opts, '#getAwsRoleName');\n const response = await transporter.request(opts);\n return response.data;\n }\n /**\n * Retrieves the temporary AWS credentials by calling the security-credentials\n * endpoint as specified in the `credential_source` object.\n * @param roleName The role attached to the current VM.\n * @param headers The headers to be used in the metadata request.\n * @param transporter The transporter to use for requests.\n * @return A promise that resolves with the temporary AWS credentials\n * needed for creating the GetCallerIdentity signed request.\n */\n async #retrieveAwsSecurityCredentials(roleName, headers, transporter) {\n const opts = {\n ...this.additionalGaxiosOptions,\n url: `${this.securityCredentialsUrl}/${roleName}`,\n headers: headers,\n };\n authclient_1.AuthClient.setMethodName(opts, '#retrieveAwsSecurityCredentials');\n const response = await transporter.request(opts);\n return response.data;\n }\n get #regionFromEnv() {\n // The AWS region can be provided through AWS_REGION or AWS_DEFAULT_REGION.\n // Only one is required.\n return (process.env['AWS_REGION'] || process.env['AWS_DEFAULT_REGION'] || null);\n }\n get #securityCredentialsFromEnv() {\n // Both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are required.\n if (process.env['AWS_ACCESS_KEY_ID'] &&\n process.env['AWS_SECRET_ACCESS_KEY']) {\n return {\n accessKeyId: process.env['AWS_ACCESS_KEY_ID'],\n secretAccessKey: process.env['AWS_SECRET_ACCESS_KEY'],\n token: process.env['AWS_SESSION_TOKEN'],\n };\n }\n return null;\n }\n}\nexports.DefaultAwsSecurityCredentialsSupplier = DefaultAwsSecurityCredentialsSupplier;\n//# sourceMappingURL=defaultawssecuritycredentialssupplier.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AwsClient = void 0;\nconst awsrequestsigner_1 = require(\"./awsrequestsigner\");\nconst baseexternalclient_1 = require(\"./baseexternalclient\");\nconst defaultawssecuritycredentialssupplier_1 = require(\"./defaultawssecuritycredentialssupplier\");\nconst util_1 = require(\"../util\");\nconst gaxios_1 = require(\"gaxios\");\n/**\n * AWS external account client. This is used for AWS workloads, where\n * AWS STS GetCallerIdentity serialized signed requests are exchanged for\n * GCP access token.\n */\nclass AwsClient extends baseexternalclient_1.BaseExternalAccountClient {\n environmentId;\n awsSecurityCredentialsSupplier;\n regionalCredVerificationUrl;\n awsRequestSigner;\n region;\n static #DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL = 'https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15';\n /**\n * @deprecated AWS client no validates the EC2 metadata address.\n **/\n static AWS_EC2_METADATA_IPV4_ADDRESS = '169.254.169.254';\n /**\n * @deprecated AWS client no validates the EC2 metadata address.\n **/\n static AWS_EC2_METADATA_IPV6_ADDRESS = 'fd00:ec2::254';\n /**\n * Instantiates an AwsClient instance using the provided JSON\n * object loaded from an external account credentials file.\n * An error is thrown if the credential is not a valid AWS credential.\n * @param options The external account options object typically loaded\n * from the external account JSON credential file.\n */\n constructor(options) {\n super(options);\n const opts = (0, util_1.originalOrCamelOptions)(options);\n const credentialSource = opts.get('credential_source');\n const awsSecurityCredentialsSupplier = opts.get('aws_security_credentials_supplier');\n // Validate credential sourcing configuration.\n if (!credentialSource && !awsSecurityCredentialsSupplier) {\n throw new Error('A credential source or AWS security credentials supplier must be specified.');\n }\n if (credentialSource && awsSecurityCredentialsSupplier) {\n throw new Error('Only one of credential source or AWS security credentials supplier can be specified.');\n }\n if (awsSecurityCredentialsSupplier) {\n this.awsSecurityCredentialsSupplier = awsSecurityCredentialsSupplier;\n this.regionalCredVerificationUrl =\n AwsClient.#DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL;\n this.credentialSourceType = 'programmatic';\n }\n else {\n const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource);\n this.environmentId = credentialSourceOpts.get('environment_id');\n // This is only required if the AWS region is not available in the\n // AWS_REGION or AWS_DEFAULT_REGION environment variables.\n const regionUrl = credentialSourceOpts.get('region_url');\n // This is only required if AWS security credentials are not available in\n // environment variables.\n const securityCredentialsUrl = credentialSourceOpts.get('url');\n const imdsV2SessionTokenUrl = credentialSourceOpts.get('imdsv2_session_token_url');\n this.awsSecurityCredentialsSupplier =\n new defaultawssecuritycredentialssupplier_1.DefaultAwsSecurityCredentialsSupplier({\n regionUrl: regionUrl,\n securityCredentialsUrl: securityCredentialsUrl,\n imdsV2SessionTokenUrl: imdsV2SessionTokenUrl,\n });\n this.regionalCredVerificationUrl = credentialSourceOpts.get('regional_cred_verification_url');\n this.credentialSourceType = 'aws';\n // Data validators.\n this.validateEnvironmentId();\n }\n this.awsRequestSigner = null;\n this.region = '';\n }\n validateEnvironmentId() {\n const match = this.environmentId?.match(/^(aws)(\\d+)$/);\n if (!match || !this.regionalCredVerificationUrl) {\n throw new Error('No valid AWS \"credential_source\" provided');\n }\n else if (parseInt(match[2], 10) !== 1) {\n throw new Error(`aws version \"${match[2]}\" is not supported in the current build.`);\n }\n }\n /**\n * Triggered when an external subject token is needed to be exchanged for a\n * GCP access token via GCP STS endpoint. This will call the\n * {@link AwsSecurityCredentialsSupplier} to retrieve an AWS region and AWS\n * Security Credentials, then use them to create a signed AWS STS request that\n * can be exchanged for a GCP access token.\n * @return A promise that resolves with the external subject token.\n */\n async retrieveSubjectToken() {\n // Initialize AWS request signer if not already initialized.\n if (!this.awsRequestSigner) {\n this.region = await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext);\n this.awsRequestSigner = new awsrequestsigner_1.AwsRequestSigner(async () => {\n return this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext);\n }, this.region);\n }\n // Generate signed request to AWS STS GetCallerIdentity API.\n // Use the required regional endpoint. Otherwise, the request will fail.\n const options = await this.awsRequestSigner.getRequestOptions({\n ...AwsClient.RETRY_CONFIG,\n url: this.regionalCredVerificationUrl.replace('{region}', this.region),\n method: 'POST',\n });\n // The GCP STS endpoint expects the headers to be formatted as:\n // [\n // {key: 'x-amz-date', value: '...'},\n // {key: 'authorization', value: '...'},\n // ...\n // ]\n // And then serialized as:\n // encodeURIComponent(JSON.stringify({\n // url: '...',\n // method: 'POST',\n // headers: [{key: 'x-amz-date', value: '...'}, ...]\n // }))\n const reformattedHeader = [];\n const extendedHeaders = gaxios_1.Gaxios.mergeHeaders({\n // The full, canonical resource name of the workload identity pool\n // provider, with or without the HTTPS prefix.\n // Including this header as part of the signature is recommended to\n // ensure data integrity.\n 'x-goog-cloud-target-resource': this.audience,\n }, options.headers);\n // Reformat header to GCP STS expected format.\n extendedHeaders.forEach((value, key) => reformattedHeader.push({ key, value }));\n // Serialize the reformatted signed request.\n return encodeURIComponent(JSON.stringify({\n url: options.url,\n method: options.method,\n headers: reformattedHeader,\n }));\n }\n}\nexports.AwsClient = AwsClient;\n//# sourceMappingURL=awsclient.js.map", "\"use strict\";\n// Copyright 2022 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.InvalidSubjectTokenError = exports.InvalidMessageFieldError = exports.InvalidCodeFieldError = exports.InvalidTokenTypeFieldError = exports.InvalidExpirationTimeFieldError = exports.InvalidSuccessFieldError = exports.InvalidVersionFieldError = exports.ExecutableResponseError = exports.ExecutableResponse = void 0;\nconst SAML_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:saml2';\nconst OIDC_SUBJECT_TOKEN_TYPE1 = 'urn:ietf:params:oauth:token-type:id_token';\nconst OIDC_SUBJECT_TOKEN_TYPE2 = 'urn:ietf:params:oauth:token-type:jwt';\n/**\n * Defines the response of a 3rd party executable run by the pluggable auth client.\n */\nclass ExecutableResponse {\n /**\n * The version of the Executable response. Only version 1 is currently supported.\n */\n version;\n /**\n * Whether the executable ran successfully.\n */\n success;\n /**\n * The epoch time for expiration of the token in seconds.\n */\n expirationTime;\n /**\n * The type of subject token in the response, currently supported values are:\n * urn:ietf:params:oauth:token-type:saml2\n * urn:ietf:params:oauth:token-type:id_token\n * urn:ietf:params:oauth:token-type:jwt\n */\n tokenType;\n /**\n * The error code from the executable.\n */\n errorCode;\n /**\n * The error message from the executable.\n */\n errorMessage;\n /**\n * The subject token from the executable, format depends on tokenType.\n */\n subjectToken;\n /**\n * Instantiates an ExecutableResponse instance using the provided JSON object\n * from the output of the executable.\n * @param responseJson Response from a 3rd party executable, loaded from a\n * run of the executable or a cached output file.\n */\n constructor(responseJson) {\n // Check that the required fields exist in the json response.\n if (!responseJson.version) {\n throw new InvalidVersionFieldError(\"Executable response must contain a 'version' field.\");\n }\n if (responseJson.success === undefined) {\n throw new InvalidSuccessFieldError(\"Executable response must contain a 'success' field.\");\n }\n this.version = responseJson.version;\n this.success = responseJson.success;\n // Validate required fields for a successful response.\n if (this.success) {\n this.expirationTime = responseJson.expiration_time;\n this.tokenType = responseJson.token_type;\n // Validate token type field.\n if (this.tokenType !== SAML_SUBJECT_TOKEN_TYPE &&\n this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE1 &&\n this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE2) {\n throw new InvalidTokenTypeFieldError(\"Executable response must contain a 'token_type' field when successful \" +\n `and it must be one of ${OIDC_SUBJECT_TOKEN_TYPE1}, ${OIDC_SUBJECT_TOKEN_TYPE2}, or ${SAML_SUBJECT_TOKEN_TYPE}.`);\n }\n // Validate subject token.\n if (this.tokenType === SAML_SUBJECT_TOKEN_TYPE) {\n if (!responseJson.saml_response) {\n throw new InvalidSubjectTokenError(`Executable response must contain a 'saml_response' field when token_type=${SAML_SUBJECT_TOKEN_TYPE}.`);\n }\n this.subjectToken = responseJson.saml_response;\n }\n else {\n if (!responseJson.id_token) {\n throw new InvalidSubjectTokenError(\"Executable response must contain a 'id_token' field when \" +\n `token_type=${OIDC_SUBJECT_TOKEN_TYPE1} or ${OIDC_SUBJECT_TOKEN_TYPE2}.`);\n }\n this.subjectToken = responseJson.id_token;\n }\n }\n else {\n // Both code and message must be provided for unsuccessful responses.\n if (!responseJson.code) {\n throw new InvalidCodeFieldError(\"Executable response must contain a 'code' field when unsuccessful.\");\n }\n if (!responseJson.message) {\n throw new InvalidMessageFieldError(\"Executable response must contain a 'message' field when unsuccessful.\");\n }\n this.errorCode = responseJson.code;\n this.errorMessage = responseJson.message;\n }\n }\n /**\n * @return A boolean representing if the response has a valid token. Returns\n * true when the response was successful and the token is not expired.\n */\n isValid() {\n return !this.isExpired() && this.success;\n }\n /**\n * @return A boolean representing if the response is expired. Returns true if the\n * provided timeout has passed.\n */\n isExpired() {\n return (this.expirationTime !== undefined &&\n this.expirationTime < Math.round(Date.now() / 1000));\n }\n}\nexports.ExecutableResponse = ExecutableResponse;\n/**\n * An error thrown by the ExecutableResponse class.\n */\nclass ExecutableResponseError extends Error {\n constructor(message) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\nexports.ExecutableResponseError = ExecutableResponseError;\n/**\n * An error thrown when the 'version' field in an executable response is missing or invalid.\n */\nclass InvalidVersionFieldError extends ExecutableResponseError {\n}\nexports.InvalidVersionFieldError = InvalidVersionFieldError;\n/**\n * An error thrown when the 'success' field in an executable response is missing or invalid.\n */\nclass InvalidSuccessFieldError extends ExecutableResponseError {\n}\nexports.InvalidSuccessFieldError = InvalidSuccessFieldError;\n/**\n * An error thrown when the 'expiration_time' field in an executable response is missing or invalid.\n */\nclass InvalidExpirationTimeFieldError extends ExecutableResponseError {\n}\nexports.InvalidExpirationTimeFieldError = InvalidExpirationTimeFieldError;\n/**\n * An error thrown when the 'token_type' field in an executable response is missing or invalid.\n */\nclass InvalidTokenTypeFieldError extends ExecutableResponseError {\n}\nexports.InvalidTokenTypeFieldError = InvalidTokenTypeFieldError;\n/**\n * An error thrown when the 'code' field in an executable response is missing or invalid.\n */\nclass InvalidCodeFieldError extends ExecutableResponseError {\n}\nexports.InvalidCodeFieldError = InvalidCodeFieldError;\n/**\n * An error thrown when the 'message' field in an executable response is missing or invalid.\n */\nclass InvalidMessageFieldError extends ExecutableResponseError {\n}\nexports.InvalidMessageFieldError = InvalidMessageFieldError;\n/**\n * An error thrown when the subject token in an executable response is missing or invalid.\n */\nclass InvalidSubjectTokenError extends ExecutableResponseError {\n}\nexports.InvalidSubjectTokenError = InvalidSubjectTokenError;\n//# sourceMappingURL=executable-response.js.map", "\"use strict\";\n// Copyright 2022 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PluggableAuthHandler = exports.ExecutableError = void 0;\nconst executable_response_1 = require(\"./executable-response\");\nconst childProcess = require(\"child_process\");\nconst fs = require(\"fs\");\n/**\n * Error thrown from the executable run by PluggableAuthClient.\n */\nclass ExecutableError extends Error {\n /**\n * The exit code returned by the executable.\n */\n code;\n constructor(message, code) {\n super(`The executable failed with exit code: ${code} and error message: ${message}.`);\n this.code = code;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\nexports.ExecutableError = ExecutableError;\n/**\n * A handler used to retrieve 3rd party token responses from user defined\n * executables and cached file output for the PluggableAuthClient class.\n */\nclass PluggableAuthHandler {\n commandComponents;\n timeoutMillis;\n outputFile;\n /**\n * Instantiates a PluggableAuthHandler instance using the provided\n * PluggableAuthHandlerOptions object.\n */\n constructor(options) {\n if (!options.command) {\n throw new Error('No command provided.');\n }\n this.commandComponents = PluggableAuthHandler.parseCommand(options.command);\n this.timeoutMillis = options.timeoutMillis;\n if (!this.timeoutMillis) {\n throw new Error('No timeoutMillis provided.');\n }\n this.outputFile = options.outputFile;\n }\n /**\n * Calls user provided executable to get a 3rd party subject token and\n * returns the response.\n * @param envMap a Map of additional Environment Variables required for\n * the executable.\n * @return A promise that resolves with the executable response.\n */\n retrieveResponseFromExecutable(envMap) {\n return new Promise((resolve, reject) => {\n // Spawn process to run executable using added environment variables.\n const child = childProcess.spawn(this.commandComponents[0], this.commandComponents.slice(1), {\n env: { ...process.env, ...Object.fromEntries(envMap) },\n });\n let output = '';\n // Append stdout to output as executable runs.\n child.stdout.on('data', (data) => {\n output += data;\n });\n // Append stderr as executable runs.\n child.stderr.on('data', (err) => {\n output += err;\n });\n // Set up a timeout to end the child process and throw an error.\n const timeout = setTimeout(() => {\n // Kill child process and remove listeners so 'close' event doesn't get\n // read after child process is killed.\n child.removeAllListeners();\n child.kill();\n return reject(new Error('The executable failed to finish within the timeout specified.'));\n }, this.timeoutMillis);\n child.on('close', (code) => {\n // Cancel timeout if executable closes before timeout is reached.\n clearTimeout(timeout);\n if (code === 0) {\n // If the executable completed successfully, try to return the parsed response.\n try {\n const responseJson = JSON.parse(output);\n const response = new executable_response_1.ExecutableResponse(responseJson);\n return resolve(response);\n }\n catch (error) {\n if (error instanceof executable_response_1.ExecutableResponseError) {\n return reject(error);\n }\n return reject(new executable_response_1.ExecutableResponseError(`The executable returned an invalid response: ${output}`));\n }\n }\n else {\n return reject(new ExecutableError(output, code.toString()));\n }\n });\n });\n }\n /**\n * Checks user provided output file for response from previous run of\n * executable and return the response if it exists, is formatted correctly, and is not expired.\n */\n async retrieveCachedResponse() {\n if (!this.outputFile || this.outputFile.length === 0) {\n return undefined;\n }\n let filePath;\n try {\n filePath = await fs.promises.realpath(this.outputFile);\n }\n catch {\n // If file path cannot be resolved, return undefined.\n return undefined;\n }\n if (!(await fs.promises.lstat(filePath)).isFile()) {\n // If path does not lead to file, return undefined.\n return undefined;\n }\n const responseString = await fs.promises.readFile(filePath, {\n encoding: 'utf8',\n });\n if (responseString === '') {\n return undefined;\n }\n try {\n const responseJson = JSON.parse(responseString);\n const response = new executable_response_1.ExecutableResponse(responseJson);\n // Check if response is successful and unexpired.\n if (response.isValid()) {\n return new executable_response_1.ExecutableResponse(responseJson);\n }\n return undefined;\n }\n catch (error) {\n if (error instanceof executable_response_1.ExecutableResponseError) {\n throw error;\n }\n throw new executable_response_1.ExecutableResponseError(`The output file contained an invalid response: ${responseString}`);\n }\n }\n /**\n * Parses given command string into component array, splitting on spaces unless\n * spaces are between quotation marks.\n */\n static parseCommand(command) {\n // Split the command into components by splitting on spaces,\n // unless spaces are contained in quotation marks.\n const components = command.match(/(?:[^\\s\"]+|\"[^\"]*\")+/g);\n if (!components) {\n throw new Error(`Provided command: \"${command}\" could not be parsed.`);\n }\n // Remove quotation marks from the beginning and end of each component if they are present.\n for (let i = 0; i < components.length; i++) {\n if (components[i][0] === '\"' && components[i].slice(-1) === '\"') {\n components[i] = components[i].slice(1, -1);\n }\n }\n return components;\n }\n}\nexports.PluggableAuthHandler = PluggableAuthHandler;\n//# sourceMappingURL=pluggable-auth-handler.js.map", "\"use strict\";\n// Copyright 2022 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PluggableAuthClient = exports.ExecutableError = void 0;\nconst baseexternalclient_1 = require(\"./baseexternalclient\");\nconst executable_response_1 = require(\"./executable-response\");\nconst pluggable_auth_handler_1 = require(\"./pluggable-auth-handler\");\nvar pluggable_auth_handler_2 = require(\"./pluggable-auth-handler\");\nObject.defineProperty(exports, \"ExecutableError\", { enumerable: true, get: function () { return pluggable_auth_handler_2.ExecutableError; } });\n/**\n * The default executable timeout when none is provided, in milliseconds.\n */\nconst DEFAULT_EXECUTABLE_TIMEOUT_MILLIS = 30 * 1000;\n/**\n * The minimum allowed executable timeout in milliseconds.\n */\nconst MINIMUM_EXECUTABLE_TIMEOUT_MILLIS = 5 * 1000;\n/**\n * The maximum allowed executable timeout in milliseconds.\n */\nconst MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS = 120 * 1000;\n/**\n * The environment variable to check to see if executable can be run.\n * Value must be set to '1' for the executable to run.\n */\nconst GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES = 'GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES';\n/**\n * The maximum currently supported executable version.\n */\nconst MAXIMUM_EXECUTABLE_VERSION = 1;\n/**\n * PluggableAuthClient enables the exchange of workload identity pool external credentials for\n * Google access tokens by retrieving 3rd party tokens through a user supplied executable. These\n * scripts/executables are completely independent of the Google Cloud Auth libraries. These\n * credentials plug into ADC and will call the specified executable to retrieve the 3rd party token\n * to be exchanged for a Google access token.\n *\n *

To use these credentials, the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable\n * must be set to '1'. This is for security reasons.\n *\n *

Both OIDC and SAML are supported. The executable must adhere to a specific response format\n * defined below.\n *\n *

The executable must print out the 3rd party token to STDOUT in JSON format. When an\n * output_file is specified in the credential configuration, the executable must also handle writing the\n * JSON response to this file.\n *\n *

\n * OIDC response sample:\n * {\n *   \"version\": 1,\n *   \"success\": true,\n *   \"token_type\": \"urn:ietf:params:oauth:token-type:id_token\",\n *   \"id_token\": \"HEADER.PAYLOAD.SIGNATURE\",\n *   \"expiration_time\": 1620433341\n * }\n *\n * SAML2 response sample:\n * {\n *   \"version\": 1,\n *   \"success\": true,\n *   \"token_type\": \"urn:ietf:params:oauth:token-type:saml2\",\n *   \"saml_response\": \"...\",\n *   \"expiration_time\": 1620433341\n * }\n *\n * Error response sample:\n * {\n *   \"version\": 1,\n *   \"success\": false,\n *   \"code\": \"401\",\n *   \"message\": \"Error message.\"\n * }\n * 
\n *\n *

The \"expiration_time\" field in the JSON response is only required for successful\n * responses when an output file was specified in the credential configuration\n *\n *

The auth libraries will populate certain environment variables that will be accessible by the\n * executable, such as: GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE, GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE,\n * GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE, GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL, and\n * GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE.\n *\n *

Please see this repositories README for a complete executable request/response specification.\n */\nclass PluggableAuthClient extends baseexternalclient_1.BaseExternalAccountClient {\n /**\n * The command used to retrieve the third party token.\n */\n command;\n /**\n * The timeout in milliseconds for running executable,\n * set to default if none provided.\n */\n timeoutMillis;\n /**\n * The path to file to check for cached executable response.\n */\n outputFile;\n /**\n * Executable and output file handler.\n */\n handler;\n /**\n * Instantiates a PluggableAuthClient instance using the provided JSON\n * object loaded from an external account credentials file.\n * An error is thrown if the credential is not a valid pluggable auth credential.\n * @param options The external account options object typically loaded from\n * the external account JSON credential file.\n */\n constructor(options) {\n super(options);\n if (!options.credential_source.executable) {\n throw new Error('No valid Pluggable Auth \"credential_source\" provided.');\n }\n this.command = options.credential_source.executable.command;\n if (!this.command) {\n throw new Error('No valid Pluggable Auth \"credential_source\" provided.');\n }\n // Check if the provided timeout exists and if it is valid.\n if (options.credential_source.executable.timeout_millis === undefined) {\n this.timeoutMillis = DEFAULT_EXECUTABLE_TIMEOUT_MILLIS;\n }\n else {\n this.timeoutMillis = options.credential_source.executable.timeout_millis;\n if (this.timeoutMillis < MINIMUM_EXECUTABLE_TIMEOUT_MILLIS ||\n this.timeoutMillis > MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS) {\n throw new Error(`Timeout must be between ${MINIMUM_EXECUTABLE_TIMEOUT_MILLIS} and ` +\n `${MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS} milliseconds.`);\n }\n }\n this.outputFile = options.credential_source.executable.output_file;\n this.handler = new pluggable_auth_handler_1.PluggableAuthHandler({\n command: this.command,\n timeoutMillis: this.timeoutMillis,\n outputFile: this.outputFile,\n });\n this.credentialSourceType = 'executable';\n }\n /**\n * Triggered when an external subject token is needed to be exchanged for a\n * GCP access token via GCP STS endpoint.\n * This uses the `options.credential_source` object to figure out how\n * to retrieve the token using the current environment. In this case,\n * this calls a user provided executable which returns the subject token.\n * The logic is summarized as:\n * 1. Validated that the executable is allowed to run. The\n * GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment must be set to\n * 1 for security reasons.\n * 2. If an output file is specified by the user, check the file location\n * for a response. If the file exists and contains a valid response,\n * return the subject token from the file.\n * 3. Call the provided executable and return response.\n * @return A promise that resolves with the external subject token.\n */\n async retrieveSubjectToken() {\n // Check if the executable is allowed to run.\n if (process.env[GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES] !== '1') {\n throw new Error('Pluggable Auth executables need to be explicitly allowed to run by ' +\n 'setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment ' +\n 'Variable to 1.');\n }\n let executableResponse = undefined;\n // Try to get cached executable response from output file.\n if (this.outputFile) {\n executableResponse = await this.handler.retrieveCachedResponse();\n }\n // If no response from output file, call the executable.\n if (!executableResponse) {\n // Set up environment map with required values for the executable.\n const envMap = new Map();\n envMap.set('GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE', this.audience);\n envMap.set('GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE', this.subjectTokenType);\n // Always set to 0 because interactive mode is not supported.\n envMap.set('GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE', '0');\n if (this.outputFile) {\n envMap.set('GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE', this.outputFile);\n }\n const serviceAccountEmail = this.getServiceAccountEmail();\n if (serviceAccountEmail) {\n envMap.set('GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL', serviceAccountEmail);\n }\n executableResponse =\n await this.handler.retrieveResponseFromExecutable(envMap);\n }\n if (executableResponse.version > MAXIMUM_EXECUTABLE_VERSION) {\n throw new Error(`Version of executable is not currently supported, maximum supported version is ${MAXIMUM_EXECUTABLE_VERSION}.`);\n }\n // Check that response was successful.\n if (!executableResponse.success) {\n throw new pluggable_auth_handler_1.ExecutableError(executableResponse.errorMessage, executableResponse.errorCode);\n }\n // Check that response contains expiration time if output file was specified.\n if (this.outputFile) {\n if (!executableResponse.expirationTime) {\n throw new executable_response_1.InvalidExpirationTimeFieldError('The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.');\n }\n }\n // Check that response is not expired.\n if (executableResponse.isExpired()) {\n throw new Error('Executable response is expired.');\n }\n // Return subject token from response.\n return executableResponse.subjectToken;\n }\n}\nexports.PluggableAuthClient = PluggableAuthClient;\n//# sourceMappingURL=pluggable-auth-client.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ExternalAccountClient = void 0;\nconst baseexternalclient_1 = require(\"./baseexternalclient\");\nconst identitypoolclient_1 = require(\"./identitypoolclient\");\nconst awsclient_1 = require(\"./awsclient\");\nconst pluggable_auth_client_1 = require(\"./pluggable-auth-client\");\n/**\n * Dummy class with no constructor. Developers are expected to use fromJSON.\n */\nclass ExternalAccountClient {\n constructor() {\n throw new Error('ExternalAccountClients should be initialized via: ' +\n 'ExternalAccountClient.fromJSON(), ' +\n 'directly via explicit constructors, eg. ' +\n 'new AwsClient(options), new IdentityPoolClient(options), new' +\n 'PluggableAuthClientOptions, or via ' +\n 'new GoogleAuth(options).getClient()');\n }\n /**\n * This static method will instantiate the\n * corresponding type of external account credential depending on the\n * underlying credential source.\n * @param options The external account options object typically loaded\n * from the external account JSON credential file.\n * @return A BaseExternalAccountClient instance or null if the options\n * provided do not correspond to an external account credential.\n */\n static fromJSON(options) {\n if (options && options.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {\n if (options.credential_source?.environment_id) {\n return new awsclient_1.AwsClient(options);\n }\n else if (options.credential_source?.executable) {\n return new pluggable_auth_client_1.PluggableAuthClient(options);\n }\n else {\n return new identitypoolclient_1.IdentityPoolClient(options);\n }\n }\n else {\n return null;\n }\n }\n}\nexports.ExternalAccountClient = ExternalAccountClient;\n//# sourceMappingURL=externalclient.js.map", "\"use strict\";\n// Copyright 2023 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ExternalAccountAuthorizedUserClient = exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = void 0;\nconst authclient_1 = require(\"./authclient\");\nconst oauth2common_1 = require(\"./oauth2common\");\nconst gaxios_1 = require(\"gaxios\");\nconst stream = require(\"stream\");\nconst baseexternalclient_1 = require(\"./baseexternalclient\");\n/**\n * The credentials JSON file type for external account authorized user clients.\n */\nexports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = 'external_account_authorized_user';\nconst DEFAULT_TOKEN_URL = 'https://sts.{universeDomain}/v1/oauthtoken';\n/**\n * Handler for token refresh requests sent to the token_url endpoint for external\n * authorized user credentials.\n */\nclass ExternalAccountAuthorizedUserHandler extends oauth2common_1.OAuthClientAuthHandler {\n #tokenRefreshEndpoint;\n /**\n * Initializes an ExternalAccountAuthorizedUserHandler instance.\n * @param url The URL of the token refresh endpoint.\n * @param transporter The transporter to use for the refresh request.\n * @param clientAuthentication The client authentication credentials to use\n * for the refresh request.\n */\n constructor(options) {\n super(options);\n this.#tokenRefreshEndpoint = options.tokenRefreshEndpoint;\n }\n /**\n * Requests a new access token from the token_url endpoint using the provided\n * refresh token.\n * @param refreshToken The refresh token to use to generate a new access token.\n * @param additionalHeaders Optional additional headers to pass along the\n * request.\n * @return A promise that resolves with the token refresh response containing\n * the requested access token and its expiration time.\n */\n async refreshToken(refreshToken, headers) {\n const opts = {\n ...ExternalAccountAuthorizedUserHandler.RETRY_CONFIG,\n url: this.#tokenRefreshEndpoint,\n method: 'POST',\n headers,\n data: new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n }),\n };\n authclient_1.AuthClient.setMethodName(opts, 'refreshToken');\n // Apply OAuth client authentication.\n this.applyClientAuthenticationOptions(opts);\n try {\n const response = await this.transporter.request(opts);\n // Successful response.\n const tokenRefreshResponse = response.data;\n tokenRefreshResponse.res = response;\n return tokenRefreshResponse;\n }\n catch (error) {\n // Translate error to OAuthError.\n if (error instanceof gaxios_1.GaxiosError && error.response) {\n throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, \n // Preserve other fields from the original error.\n error);\n }\n // Request could fail before the server responds.\n throw error;\n }\n }\n}\n/**\n * External Account Authorized User Client. This is used for OAuth2 credentials\n * sourced using external identities through Workforce Identity Federation.\n * Obtaining the initial access and refresh token can be done through the\n * Google Cloud CLI.\n */\nclass ExternalAccountAuthorizedUserClient extends authclient_1.AuthClient {\n cachedAccessToken;\n externalAccountAuthorizedUserHandler;\n refreshToken;\n /**\n * Instantiates an ExternalAccountAuthorizedUserClient instances using the\n * provided JSON object loaded from a credentials files.\n * An error is throws if the credential is not valid.\n * @param options The external account authorized user option object typically\n * from the external accoutn authorized user JSON credential file.\n */\n constructor(options) {\n super(options);\n if (options.universe_domain) {\n this.universeDomain = options.universe_domain;\n }\n this.refreshToken = options.refresh_token;\n const clientAuthentication = {\n confidentialClientType: 'basic',\n clientId: options.client_id,\n clientSecret: options.client_secret,\n };\n this.externalAccountAuthorizedUserHandler =\n new ExternalAccountAuthorizedUserHandler({\n tokenRefreshEndpoint: options.token_url ??\n DEFAULT_TOKEN_URL.replace('{universeDomain}', this.universeDomain),\n transporter: this.transporter,\n clientAuthentication,\n });\n this.cachedAccessToken = null;\n this.quotaProjectId = options.quota_project_id;\n // As threshold could be zero,\n // eagerRefreshThresholdMillis || EXPIRATION_TIME_OFFSET will override the\n // zero value.\n if (typeof options?.eagerRefreshThresholdMillis !== 'number') {\n this.eagerRefreshThresholdMillis = baseexternalclient_1.EXPIRATION_TIME_OFFSET;\n }\n else {\n this.eagerRefreshThresholdMillis = options\n .eagerRefreshThresholdMillis;\n }\n this.forceRefreshOnFailure = !!options?.forceRefreshOnFailure;\n }\n async getAccessToken() {\n // If cached access token is unavailable or expired, force refresh.\n if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) {\n await this.refreshAccessTokenAsync();\n }\n // Return GCP access token in GetAccessTokenResponse format.\n return {\n token: this.cachedAccessToken.access_token,\n res: this.cachedAccessToken.res,\n };\n }\n async getRequestHeaders() {\n const accessTokenResponse = await this.getAccessToken();\n const headers = new Headers({\n authorization: `Bearer ${accessTokenResponse.token}`,\n });\n return this.addSharedMetadataHeaders(headers);\n }\n request(opts, callback) {\n if (callback) {\n this.requestAsync(opts).then(r => callback(null, r), e => {\n return callback(e, e.response);\n });\n }\n else {\n return this.requestAsync(opts);\n }\n }\n /**\n * Authenticates the provided HTTP request, processes it and resolves with the\n * returned response.\n * @param opts The HTTP request options.\n * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure.\n * @return A promise that resolves with the successful response.\n */\n async requestAsync(opts, reAuthRetried = false) {\n let response;\n try {\n const requestHeaders = await this.getRequestHeaders();\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);\n this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders);\n response = await this.transporter.request(opts);\n }\n catch (e) {\n const res = e.response;\n if (res) {\n const statusCode = res.status;\n // Retry the request for metadata if the following criteria are true:\n // - We haven't already retried. It only makes sense to retry once.\n // - The response was a 401 or a 403\n // - The request didn't send a readableStream\n // - forceRefreshOnFailure is true\n const isReadableStream = res.config.data instanceof stream.Readable;\n const isAuthErr = statusCode === 401 || statusCode === 403;\n if (!reAuthRetried &&\n isAuthErr &&\n !isReadableStream &&\n this.forceRefreshOnFailure) {\n await this.refreshAccessTokenAsync();\n return await this.requestAsync(opts, true);\n }\n }\n throw e;\n }\n return response;\n }\n /**\n * Forces token refresh, even if unexpired tokens are currently cached.\n * @return A promise that resolves with the refreshed credential.\n */\n async refreshAccessTokenAsync() {\n // Refresh the access token using the refresh token.\n const refreshResponse = await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);\n this.cachedAccessToken = {\n access_token: refreshResponse.access_token,\n expiry_date: new Date().getTime() + refreshResponse.expires_in * 1000,\n res: refreshResponse.res,\n };\n if (refreshResponse.refresh_token !== undefined) {\n this.refreshToken = refreshResponse.refresh_token;\n }\n return this.cachedAccessToken;\n }\n /**\n * Returns whether the provided credentials are expired or not.\n * If there is no expiry time, assumes the token is not expired or expiring.\n * @param credentials The credentials to check for expiration.\n * @return Whether the credentials are expired or not.\n */\n isExpired(credentials) {\n const now = new Date().getTime();\n return credentials.expiry_date\n ? now >= credentials.expiry_date - this.eagerRefreshThresholdMillis\n : false;\n }\n}\nexports.ExternalAccountAuthorizedUserClient = ExternalAccountAuthorizedUserClient;\n//# sourceMappingURL=externalAccountAuthorizedUserClient.js.map", "\"use strict\";\n// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.GoogleAuth = exports.GoogleAuthExceptionMessages = void 0;\nconst child_process_1 = require(\"child_process\");\nconst fs = require(\"fs\");\nconst gaxios_1 = require(\"gaxios\");\nconst gcpMetadata = require(\"gcp-metadata\");\nconst os = require(\"os\");\nconst path = require(\"path\");\nconst crypto_1 = require(\"../crypto/crypto\");\nconst computeclient_1 = require(\"./computeclient\");\nconst idtokenclient_1 = require(\"./idtokenclient\");\nconst envDetect_1 = require(\"./envDetect\");\nconst jwtclient_1 = require(\"./jwtclient\");\nconst refreshclient_1 = require(\"./refreshclient\");\nconst impersonated_1 = require(\"./impersonated\");\nconst externalclient_1 = require(\"./externalclient\");\nconst baseexternalclient_1 = require(\"./baseexternalclient\");\nconst authclient_1 = require(\"./authclient\");\nconst externalAccountAuthorizedUserClient_1 = require(\"./externalAccountAuthorizedUserClient\");\nconst util_1 = require(\"../util\");\nexports.GoogleAuthExceptionMessages = {\n API_KEY_WITH_CREDENTIALS: 'API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.',\n NO_PROJECT_ID_FOUND: 'Unable to detect a Project Id in the current environment. \\n' +\n 'To learn more about authentication and Google APIs, visit: \\n' +\n 'https://cloud.google.com/docs/authentication/getting-started',\n NO_CREDENTIALS_FOUND: 'Unable to find credentials in current environment. \\n' +\n 'To learn more about authentication and Google APIs, visit: \\n' +\n 'https://cloud.google.com/docs/authentication/getting-started',\n NO_ADC_FOUND: 'Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.',\n NO_UNIVERSE_DOMAIN_FOUND: 'Unable to detect a Universe Domain in the current environment.\\n' +\n 'To learn more about Universe Domain retrieval, visit: \\n' +\n 'https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys',\n};\nclass GoogleAuth {\n /**\n * Caches a value indicating whether the auth layer is running on Google\n * Compute Engine.\n * @private\n */\n checkIsGCE = undefined;\n useJWTAccessWithScope;\n defaultServicePath;\n // Note: this properly is only public to satisfy unit tests.\n // https://github.com/Microsoft/TypeScript/issues/5228\n get isGCE() {\n return this.checkIsGCE;\n }\n _findProjectIdPromise;\n _cachedProjectId;\n // To save the contents of the JSON credential file\n jsonContent = null;\n apiKey;\n cachedCredential = null;\n /**\n * A pending {@link AuthClient}. Used for concurrent {@link GoogleAuth.getClient} calls.\n */\n #pendingAuthClient = null;\n /**\n * Scopes populated by the client library by default. We differentiate between\n * these and user defined scopes when deciding whether to use a self-signed JWT.\n */\n defaultScopes;\n keyFilename;\n scopes;\n clientOptions = {};\n /**\n * Configuration is resolved in the following order of precedence:\n * - {@link GoogleAuthOptions.credentials `credentials`}\n * - {@link GoogleAuthOptions.keyFilename `keyFilename`}\n * - {@link GoogleAuthOptions.keyFile `keyFile`}\n *\n * {@link GoogleAuthOptions.clientOptions `clientOptions`} are passed to the\n * {@link AuthClient `AuthClient`s}.\n *\n * @param opts\n */\n constructor(opts = {}) {\n this._cachedProjectId = opts.projectId || null;\n this.cachedCredential = opts.authClient || null;\n this.keyFilename = opts.keyFilename || opts.keyFile;\n this.scopes = opts.scopes;\n this.clientOptions = opts.clientOptions || {};\n this.jsonContent = opts.credentials || null;\n this.apiKey = opts.apiKey || this.clientOptions.apiKey || null;\n // Cannot use both API Key + Credentials\n if (this.apiKey && (this.jsonContent || this.clientOptions.credentials)) {\n throw new RangeError(exports.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);\n }\n if (opts.universeDomain) {\n this.clientOptions.universeDomain = opts.universeDomain;\n }\n }\n // GAPIC client libraries should always use self-signed JWTs. The following\n // variables are set on the JWT client in order to indicate the type of library,\n // and sign the JWT with the correct audience and scopes (if not supplied).\n setGapicJWTValues(client) {\n client.defaultServicePath = this.defaultServicePath;\n client.useJWTAccessWithScope = this.useJWTAccessWithScope;\n client.defaultScopes = this.defaultScopes;\n }\n getProjectId(callback) {\n if (callback) {\n this.getProjectIdAsync().then(r => callback(null, r), callback);\n }\n else {\n return this.getProjectIdAsync();\n }\n }\n /**\n * A temporary method for internal `getProjectId` usages where `null` is\n * acceptable. In a future major release, `getProjectId` should return `null`\n * (as the `Promise` base signature describes) and this private\n * method should be removed.\n *\n * @returns Promise that resolves with project id (or `null`)\n */\n async getProjectIdOptional() {\n try {\n return await this.getProjectId();\n }\n catch (e) {\n if (e instanceof Error &&\n e.message === exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND) {\n return null;\n }\n else {\n throw e;\n }\n }\n }\n /**\n * A private method for finding and caching a projectId.\n *\n * Supports environments in order of precedence:\n * - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable\n * - GOOGLE_APPLICATION_CREDENTIALS JSON file\n * - Cloud SDK: `gcloud config config-helper --format json`\n * - GCE project ID from metadata server\n *\n * @returns projectId\n */\n async findAndCacheProjectId() {\n let projectId = null;\n projectId ||= await this.getProductionProjectId();\n projectId ||= await this.getFileProjectId();\n projectId ||= await this.getDefaultServiceProjectId();\n projectId ||= await this.getGCEProjectId();\n projectId ||= await this.getExternalAccountClientProjectId();\n if (projectId) {\n this._cachedProjectId = projectId;\n return projectId;\n }\n else {\n throw new Error(exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND);\n }\n }\n async getProjectIdAsync() {\n if (this._cachedProjectId) {\n return this._cachedProjectId;\n }\n if (!this._findProjectIdPromise) {\n this._findProjectIdPromise = this.findAndCacheProjectId();\n }\n return this._findProjectIdPromise;\n }\n /**\n * Retrieves a universe domain from the metadata server via\n * {@link gcpMetadata.universe}.\n *\n * @returns a universe domain\n */\n async getUniverseDomainFromMetadataServer() {\n let universeDomain;\n try {\n universeDomain = await gcpMetadata.universe('universe-domain');\n universeDomain ||= authclient_1.DEFAULT_UNIVERSE;\n }\n catch (e) {\n if (e && e?.response?.status === 404) {\n universeDomain = authclient_1.DEFAULT_UNIVERSE;\n }\n else {\n throw e;\n }\n }\n return universeDomain;\n }\n /**\n * Retrieves, caches, and returns the universe domain in the following order\n * of precedence:\n * - The universe domain in {@link GoogleAuth.clientOptions}\n * - An existing or ADC {@link AuthClient}'s universe domain\n * - {@link gcpMetadata.universe}, if {@link Compute} client\n *\n * @returns The universe domain\n */\n async getUniverseDomain() {\n let universeDomain = (0, util_1.originalOrCamelOptions)(this.clientOptions).get('universe_domain');\n try {\n universeDomain ??= (await this.getClient()).universeDomain;\n }\n catch {\n // client or ADC is not available\n universeDomain ??= authclient_1.DEFAULT_UNIVERSE;\n }\n return universeDomain;\n }\n /**\n * @returns Any scopes (user-specified or default scopes specified by the\n * client library) that need to be set on the current Auth client.\n */\n getAnyScopes() {\n return this.scopes || this.defaultScopes;\n }\n getApplicationDefault(optionsOrCallback = {}, callback) {\n let options;\n if (typeof optionsOrCallback === 'function') {\n callback = optionsOrCallback;\n }\n else {\n options = optionsOrCallback;\n }\n if (callback) {\n this.getApplicationDefaultAsync(options).then(r => callback(null, r.credential, r.projectId), callback);\n }\n else {\n return this.getApplicationDefaultAsync(options);\n }\n }\n async getApplicationDefaultAsync(options = {}) {\n // If we've already got a cached credential, return it.\n // This will also preserve one's configured quota project, in case they\n // set one directly on the credential previously.\n if (this.cachedCredential) {\n // cache, while preserving existing quota project preferences\n return await this.#prepareAndCacheClient(this.cachedCredential, null);\n }\n let credential;\n // Check for the existence of a local environment variable pointing to the\n // location of the credential file. This is typically used in local\n // developer scenarios.\n credential =\n await this._tryGetApplicationCredentialsFromEnvironmentVariable(options);\n if (credential) {\n if (credential instanceof jwtclient_1.JWT) {\n credential.scopes = this.scopes;\n }\n else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) {\n credential.scopes = this.getAnyScopes();\n }\n return await this.#prepareAndCacheClient(credential);\n }\n // Look in the well-known credential file location.\n credential =\n await this._tryGetApplicationCredentialsFromWellKnownFile(options);\n if (credential) {\n if (credential instanceof jwtclient_1.JWT) {\n credential.scopes = this.scopes;\n }\n else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) {\n credential.scopes = this.getAnyScopes();\n }\n return await this.#prepareAndCacheClient(credential);\n }\n // Determine if we're running on GCE.\n if (await this._checkIsGCE()) {\n options.scopes = this.getAnyScopes();\n return await this.#prepareAndCacheClient(new computeclient_1.Compute(options));\n }\n throw new Error(exports.GoogleAuthExceptionMessages.NO_ADC_FOUND);\n }\n async #prepareAndCacheClient(credential, quotaProjectIdOverride = process.env['GOOGLE_CLOUD_QUOTA_PROJECT'] || null) {\n const projectId = await this.getProjectIdOptional();\n if (quotaProjectIdOverride) {\n credential.quotaProjectId = quotaProjectIdOverride;\n }\n this.cachedCredential = credential;\n return { credential, projectId };\n }\n /**\n * Determines whether the auth layer is running on Google Compute Engine.\n * Checks for GCP Residency, then fallback to checking if metadata server\n * is available.\n *\n * @returns A promise that resolves with the boolean.\n * @api private\n */\n async _checkIsGCE() {\n if (this.checkIsGCE === undefined) {\n this.checkIsGCE =\n gcpMetadata.getGCPResidency() || (await gcpMetadata.isAvailable());\n }\n return this.checkIsGCE;\n }\n /**\n * Attempts to load default credentials from the environment variable path..\n * @returns Promise that resolves with the OAuth2Client or null.\n * @api private\n */\n async _tryGetApplicationCredentialsFromEnvironmentVariable(options) {\n const credentialsPath = process.env['GOOGLE_APPLICATION_CREDENTIALS'] ||\n process.env['google_application_credentials'];\n if (!credentialsPath || credentialsPath.length === 0) {\n return null;\n }\n try {\n return this._getApplicationCredentialsFromFilePath(credentialsPath, options);\n }\n catch (e) {\n if (e instanceof Error) {\n e.message = `Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e.message}`;\n }\n throw e;\n }\n }\n /**\n * Attempts to load default credentials from a well-known file location\n * @return Promise that resolves with the OAuth2Client or null.\n * @api private\n */\n async _tryGetApplicationCredentialsFromWellKnownFile(options) {\n // First, figure out the location of the file, depending upon the OS type.\n let location = null;\n if (this._isWindows()) {\n // Windows\n location = process.env['APPDATA'];\n }\n else {\n // Linux or Mac\n const home = process.env['HOME'];\n if (home) {\n location = path.join(home, '.config');\n }\n }\n // If we found the root path, expand it.\n if (location) {\n location = path.join(location, 'gcloud', 'application_default_credentials.json');\n if (!fs.existsSync(location)) {\n location = null;\n }\n }\n // The file does not exist.\n if (!location) {\n return null;\n }\n // The file seems to exist. Try to use it.\n const client = await this._getApplicationCredentialsFromFilePath(location, options);\n return client;\n }\n /**\n * Attempts to load default credentials from a file at the given path..\n * @param filePath The path to the file to read.\n * @returns Promise that resolves with the OAuth2Client\n * @api private\n */\n async _getApplicationCredentialsFromFilePath(filePath, options = {}) {\n // Make sure the path looks like a string.\n if (!filePath || filePath.length === 0) {\n throw new Error('The file path is invalid.');\n }\n // Make sure there is a file at the path. lstatSync will throw if there is\n // nothing there.\n try {\n // Resolve path to actual file in case of symlink. Expect a thrown error\n // if not resolvable.\n filePath = fs.realpathSync(filePath);\n if (!fs.lstatSync(filePath).isFile()) {\n throw new Error();\n }\n }\n catch (err) {\n if (err instanceof Error) {\n err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`;\n }\n throw err;\n }\n // Now open a read stream on the file, and parse it.\n const readStream = fs.createReadStream(filePath);\n return this.fromStream(readStream, options);\n }\n /**\n * Create a credentials instance using a given impersonated input options.\n * @param json The impersonated input object.\n * @returns JWT or UserRefresh Client with data\n */\n fromImpersonatedJSON(json) {\n if (!json) {\n throw new Error('Must pass in a JSON object containing an impersonated refresh token');\n }\n if (json.type !== impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {\n throw new Error(`The incoming JSON object does not have the \"${impersonated_1.IMPERSONATED_ACCOUNT_TYPE}\" type`);\n }\n if (!json.source_credentials) {\n throw new Error('The incoming JSON object does not contain a source_credentials field');\n }\n if (!json.service_account_impersonation_url) {\n throw new Error('The incoming JSON object does not contain a service_account_impersonation_url field');\n }\n const sourceClient = this.fromJSON(json.source_credentials);\n if (json.service_account_impersonation_url?.length > 256) {\n /**\n * Prevents DOS attacks.\n * @see {@link https://github.com/googleapis/google-auth-library-nodejs/security/code-scanning/85}\n **/\n throw new RangeError(`Target principal is too long: ${json.service_account_impersonation_url}`);\n }\n // Extract service account from service_account_impersonation_url\n const targetPrincipal = /(?[^/]+):(generateAccessToken|generateIdToken)$/.exec(json.service_account_impersonation_url)?.groups?.target;\n if (!targetPrincipal) {\n throw new RangeError(`Cannot extract target principal from ${json.service_account_impersonation_url}`);\n }\n const targetScopes = this.getAnyScopes() ?? [];\n return new impersonated_1.Impersonated({\n ...json,\n sourceClient,\n targetPrincipal,\n targetScopes: Array.isArray(targetScopes) ? targetScopes : [targetScopes],\n });\n }\n /**\n * Create a credentials instance using the given input options.\n * This client is not cached.\n *\n * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}.\n *\n * @param json The input object.\n * @param options The JWT or UserRefresh options for the client\n * @returns JWT or UserRefresh Client with data\n */\n fromJSON(json, options = {}) {\n let client;\n // user's preferred universe domain\n const preferredUniverseDomain = (0, util_1.originalOrCamelOptions)(options).get('universe_domain');\n if (json.type === refreshclient_1.USER_REFRESH_ACCOUNT_TYPE) {\n client = new refreshclient_1.UserRefreshClient(options);\n client.fromJSON(json);\n }\n else if (json.type === impersonated_1.IMPERSONATED_ACCOUNT_TYPE) {\n client = this.fromImpersonatedJSON(json);\n }\n else if (json.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {\n client = externalclient_1.ExternalAccountClient.fromJSON({\n ...json,\n ...options,\n });\n client.scopes = this.getAnyScopes();\n }\n else if (json.type === externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE) {\n client = new externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient({\n ...json,\n ...options,\n });\n }\n else {\n options.scopes = this.scopes;\n client = new jwtclient_1.JWT(options);\n this.setGapicJWTValues(client);\n client.fromJSON(json);\n }\n if (preferredUniverseDomain) {\n client.universeDomain = preferredUniverseDomain;\n }\n return client;\n }\n /**\n * Return a JWT or UserRefreshClient from JavaScript object, caching both the\n * object used to instantiate and the client.\n * @param json The input object.\n * @param options The JWT or UserRefresh options for the client\n * @returns JWT or UserRefresh Client with data\n */\n _cacheClientFromJSON(json, options) {\n const client = this.fromJSON(json, options);\n // cache both raw data used to instantiate client and client itself.\n this.jsonContent = json;\n this.cachedCredential = client;\n return client;\n }\n fromStream(inputStream, optionsOrCallback = {}, callback) {\n let options = {};\n if (typeof optionsOrCallback === 'function') {\n callback = optionsOrCallback;\n }\n else {\n options = optionsOrCallback;\n }\n if (callback) {\n this.fromStreamAsync(inputStream, options).then(r => callback(null, r), callback);\n }\n else {\n return this.fromStreamAsync(inputStream, options);\n }\n }\n fromStreamAsync(inputStream, options) {\n return new Promise((resolve, reject) => {\n if (!inputStream) {\n throw new Error('Must pass in a stream containing the Google auth settings.');\n }\n const chunks = [];\n inputStream\n .setEncoding('utf8')\n .on('error', reject)\n .on('data', chunk => chunks.push(chunk))\n .on('end', () => {\n try {\n try {\n const data = JSON.parse(chunks.join(''));\n const r = this._cacheClientFromJSON(data, options);\n return resolve(r);\n }\n catch (err) {\n // If we failed parsing this.keyFileName, assume that it\n // is a PEM or p12 certificate:\n if (!this.keyFilename)\n throw err;\n const client = new jwtclient_1.JWT({\n ...this.clientOptions,\n keyFile: this.keyFilename,\n });\n this.cachedCredential = client;\n this.setGapicJWTValues(client);\n return resolve(client);\n }\n }\n catch (err) {\n return reject(err);\n }\n });\n });\n }\n /**\n * Create a credentials instance using the given API key string.\n * The created client is not cached. In order to create and cache it use the {@link GoogleAuth.getClient `getClient`} method after first providing an {@link GoogleAuth.apiKey `apiKey`}.\n *\n * @param apiKey The API key string\n * @param options An optional options object.\n * @returns A JWT loaded from the key\n */\n fromAPIKey(apiKey, options = {}) {\n return new jwtclient_1.JWT({ ...options, apiKey });\n }\n /**\n * Determines whether the current operating system is Windows.\n * @api private\n */\n _isWindows() {\n const sys = os.platform();\n if (sys && sys.length >= 3) {\n if (sys.substring(0, 3).toLowerCase() === 'win') {\n return true;\n }\n }\n return false;\n }\n /**\n * Run the Google Cloud SDK command that prints the default project ID\n */\n async getDefaultServiceProjectId() {\n return new Promise(resolve => {\n (0, child_process_1.exec)('gcloud config config-helper --format json', (err, stdout) => {\n if (!err && stdout) {\n try {\n const projectId = JSON.parse(stdout).configuration.properties.core.project;\n resolve(projectId);\n return;\n }\n catch (e) {\n // ignore errors\n }\n }\n resolve(null);\n });\n });\n }\n /**\n * Loads the project id from environment variables.\n * @api private\n */\n getProductionProjectId() {\n return (process.env['GCLOUD_PROJECT'] ||\n process.env['GOOGLE_CLOUD_PROJECT'] ||\n process.env['gcloud_project'] ||\n process.env['google_cloud_project']);\n }\n /**\n * Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file.\n * @api private\n */\n async getFileProjectId() {\n if (this.cachedCredential) {\n // Try to read the project ID from the cached credentials file\n return this.cachedCredential.projectId;\n }\n // Ensure the projectId is loaded from the keyFile if available.\n if (this.keyFilename) {\n const creds = await this.getClient();\n if (creds && creds.projectId) {\n return creds.projectId;\n }\n }\n // Try to load a credentials file and read its project ID\n const r = await this._tryGetApplicationCredentialsFromEnvironmentVariable();\n if (r) {\n return r.projectId;\n }\n else {\n return null;\n }\n }\n /**\n * Gets the project ID from external account client if available.\n */\n async getExternalAccountClientProjectId() {\n if (!this.jsonContent || this.jsonContent.type !== baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) {\n return null;\n }\n const creds = await this.getClient();\n // Do not suppress the underlying error, as the error could contain helpful\n // information for debugging and fixing. This is especially true for\n // external account creds as in order to get the project ID, the following\n // operations have to succeed:\n // 1. Valid credentials file should be supplied.\n // 2. Ability to retrieve access tokens from STS token exchange API.\n // 3. Ability to exchange for service account impersonated credentials (if\n // enabled).\n // 4. Ability to get project info using the access token from step 2 or 3.\n // Without surfacing the error, it is harder for developers to determine\n // which step went wrong.\n return await creds.getProjectId();\n }\n /**\n * Gets the Compute Engine project ID if it can be inferred.\n */\n async getGCEProjectId() {\n try {\n const r = await gcpMetadata.project('project-id');\n return r;\n }\n catch (e) {\n // Ignore any errors\n return null;\n }\n }\n getCredentials(callback) {\n if (callback) {\n this.getCredentialsAsync().then(r => callback(null, r), callback);\n }\n else {\n return this.getCredentialsAsync();\n }\n }\n async getCredentialsAsync() {\n const client = await this.getClient();\n if (client instanceof impersonated_1.Impersonated) {\n return { client_email: client.getTargetPrincipal() };\n }\n if (client instanceof baseexternalclient_1.BaseExternalAccountClient) {\n const serviceAccountEmail = client.getServiceAccountEmail();\n if (serviceAccountEmail) {\n return {\n client_email: serviceAccountEmail,\n universe_domain: client.universeDomain,\n };\n }\n }\n if (this.jsonContent) {\n return {\n client_email: this.jsonContent.client_email,\n private_key: this.jsonContent.private_key,\n universe_domain: this.jsonContent.universe_domain,\n };\n }\n if (await this._checkIsGCE()) {\n const [client_email, universe_domain] = await Promise.all([\n gcpMetadata.instance('service-accounts/default/email'),\n this.getUniverseDomain(),\n ]);\n return { client_email, universe_domain };\n }\n throw new Error(exports.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND);\n }\n /**\n * Automatically obtain an {@link AuthClient `AuthClient`} based on the\n * provided configuration. If no options were passed, use Application\n * Default Credentials.\n */\n async getClient() {\n if (this.cachedCredential) {\n return this.cachedCredential;\n }\n // Use an existing auth client request, or cache a new one\n this.#pendingAuthClient =\n this.#pendingAuthClient || this.#determineClient();\n try {\n return await this.#pendingAuthClient;\n }\n finally {\n // reset the pending auth client in case it is changed later\n this.#pendingAuthClient = null;\n }\n }\n async #determineClient() {\n if (this.jsonContent) {\n return this._cacheClientFromJSON(this.jsonContent, this.clientOptions);\n }\n else if (this.keyFilename) {\n const filePath = path.resolve(this.keyFilename);\n const stream = fs.createReadStream(filePath);\n return await this.fromStreamAsync(stream, this.clientOptions);\n }\n else if (this.apiKey) {\n const client = await this.fromAPIKey(this.apiKey, this.clientOptions);\n client.scopes = this.scopes;\n const { credential } = await this.#prepareAndCacheClient(client);\n return credential;\n }\n else {\n const { credential } = await this.getApplicationDefaultAsync(this.clientOptions);\n return credential;\n }\n }\n /**\n * Creates a client which will fetch an ID token for authorization.\n * @param targetAudience the audience for the fetched ID token.\n * @returns IdTokenClient for making HTTP calls authenticated with ID tokens.\n */\n async getIdTokenClient(targetAudience) {\n const client = await this.getClient();\n if (!('fetchIdToken' in client)) {\n throw new Error('Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.');\n }\n return new idtokenclient_1.IdTokenClient({ targetAudience, idTokenProvider: client });\n }\n /**\n * Automatically obtain application default credentials, and return\n * an access token for making requests.\n */\n async getAccessToken() {\n const client = await this.getClient();\n return (await client.getAccessToken()).token;\n }\n /**\n * Obtain the HTTP headers that will provide authorization for a given\n * request.\n */\n async getRequestHeaders(url) {\n const client = await this.getClient();\n return client.getRequestHeaders(url);\n }\n /**\n * Obtain credentials for a request, then attach the appropriate headers to\n * the request options.\n * @param opts Axios or Request options on which to attach the headers\n */\n async authorizeRequest(opts = {}) {\n const url = opts.url;\n const client = await this.getClient();\n const headers = await client.getRequestHeaders(url);\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers, headers);\n return opts;\n }\n /**\n * A {@link fetch `fetch`} compliant API for {@link GoogleAuth}.\n *\n * @see {@link GoogleAuth.request} for the classic method.\n *\n * @remarks\n *\n * This is useful as a drop-in replacement for `fetch` API usage.\n *\n * @example\n *\n * ```ts\n * const auth = new GoogleAuth();\n * const fetchWithAuth: typeof fetch = (...args) => auth.fetch(...args);\n * await fetchWithAuth('https://example.com');\n * ```\n *\n * @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters\n * @returns the {@link GaxiosResponse} with Gaxios-added properties\n */\n async fetch(...args) {\n const client = await this.getClient();\n return client.fetch(...args);\n }\n /**\n * Automatically obtain application default credentials, and make an\n * HTTP request using the given options.\n *\n * @see {@link GoogleAuth.fetch} for the modern method.\n *\n * @param opts Axios request options for the HTTP request.\n */\n async request(opts) {\n const client = await this.getClient();\n return client.request(opts);\n }\n /**\n * Determine the compute environment in which the code is running.\n */\n getEnv() {\n return (0, envDetect_1.getEnv)();\n }\n /**\n * Sign the given data with the current private key, or go out\n * to the IAM API to sign it.\n * @param data The data to be signed.\n * @param endpoint A custom endpoint to use.\n *\n * @example\n * ```\n * sign('data', 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/');\n * ```\n */\n async sign(data, endpoint) {\n const client = await this.getClient();\n const universe = await this.getUniverseDomain();\n endpoint =\n endpoint ||\n `https://iamcredentials.${universe}/v1/projects/-/serviceAccounts/`;\n if (client instanceof impersonated_1.Impersonated) {\n const signed = await client.sign(data);\n return signed.signedBlob;\n }\n const crypto = (0, crypto_1.createCrypto)();\n if (client instanceof jwtclient_1.JWT && client.key) {\n const sign = await crypto.sign(client.key, data);\n return sign;\n }\n const creds = await this.getCredentials();\n if (!creds.client_email) {\n throw new Error('Cannot sign data without `client_email`.');\n }\n return this.signBlob(crypto, creds.client_email, data, endpoint);\n }\n async signBlob(crypto, emailOrUniqueId, data, endpoint) {\n const url = new URL(endpoint + `${emailOrUniqueId}:signBlob`);\n const res = await this.request({\n method: 'POST',\n url: url.href,\n data: {\n payload: crypto.encodeBase64StringUtf8(data),\n },\n retry: true,\n retryConfig: {\n httpMethodsToRetry: ['POST'],\n },\n });\n return res.data.signedBlob;\n }\n}\nexports.GoogleAuth = GoogleAuth;\n//# sourceMappingURL=googleauth.js.map", "\"use strict\";\n// Copyright 2014 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.IAMAuth = void 0;\nclass IAMAuth {\n selector;\n token;\n /**\n * IAM credentials.\n *\n * @param selector the iam authority selector\n * @param token the token\n * @constructor\n */\n constructor(selector, token) {\n this.selector = selector;\n this.token = token;\n this.selector = selector;\n this.token = token;\n }\n /**\n * Acquire the HTTP headers required to make an authenticated request.\n */\n getRequestHeaders() {\n return {\n 'x-goog-iam-authority-selector': this.selector,\n 'x-goog-iam-authorization-token': this.token,\n };\n }\n}\nexports.IAMAuth = IAMAuth;\n//# sourceMappingURL=iam.js.map", "\"use strict\";\n// Copyright 2021 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DownscopedClient = exports.EXPIRATION_TIME_OFFSET = exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = void 0;\nconst gaxios_1 = require(\"gaxios\");\nconst stream = require(\"stream\");\nconst authclient_1 = require(\"./authclient\");\nconst sts = require(\"./stscredentials\");\n/**\n * The required token exchange grant_type: rfc8693#section-2.1\n */\nconst STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange';\n/**\n * The requested token exchange requested_token_type: rfc8693#section-2.1\n */\nconst STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';\n/**\n * The requested token exchange subject_token_type: rfc8693#section-2.1\n */\nconst STS_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';\n/**\n * The maximum number of access boundary rules a Credential Access Boundary\n * can contain.\n */\nexports.MAX_ACCESS_BOUNDARY_RULES_COUNT = 10;\n/**\n * Offset to take into account network delays and server clock skews.\n */\nexports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000;\n/**\n * Defines a set of Google credentials that are downscoped from an existing set\n * of Google OAuth2 credentials. This is useful to restrict the Identity and\n * Access Management (IAM) permissions that a short-lived credential can use.\n * The common pattern of usage is to have a token broker with elevated access\n * generate these downscoped credentials from higher access source credentials\n * and pass the downscoped short-lived access tokens to a token consumer via\n * some secure authenticated channel for limited access to Google Cloud Storage\n * resources.\n */\nclass DownscopedClient extends authclient_1.AuthClient {\n authClient;\n credentialAccessBoundary;\n cachedDownscopedAccessToken;\n stsCredential;\n /**\n * Instantiates a downscoped client object using the provided source\n * AuthClient and credential access boundary rules.\n * To downscope permissions of a source AuthClient, a Credential Access\n * Boundary that specifies which resources the new credential can access, as\n * well as an upper bound on the permissions that are available on each\n * resource, has to be defined. A downscoped client can then be instantiated\n * using the source AuthClient and the Credential Access Boundary.\n * @param options the {@link DownscopedClientOptions `DownscopedClientOptions`} to use. Passing an `AuthClient` directly is **@DEPRECATED**.\n * @param credentialAccessBoundary **@DEPRECATED**. Provide a {@link DownscopedClientOptions `DownscopedClientOptions`} object in the first parameter instead.\n */\n constructor(\n /**\n * AuthClient is for backwards-compatibility.\n */\n options, \n /**\n * @deprecated - provide a {@link DownscopedClientOptions `DownscopedClientOptions`} object in the first parameter instead\n */\n credentialAccessBoundary = {\n accessBoundary: {\n accessBoundaryRules: [],\n },\n }) {\n super(options instanceof authclient_1.AuthClient ? {} : options);\n if (options instanceof authclient_1.AuthClient) {\n this.authClient = options;\n this.credentialAccessBoundary = credentialAccessBoundary;\n }\n else {\n this.authClient = options.authClient;\n this.credentialAccessBoundary = options.credentialAccessBoundary;\n }\n // Check 1-10 Access Boundary Rules are defined within Credential Access\n // Boundary.\n if (this.credentialAccessBoundary.accessBoundary.accessBoundaryRules\n .length === 0) {\n throw new Error('At least one access boundary rule needs to be defined.');\n }\n else if (this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length >\n exports.MAX_ACCESS_BOUNDARY_RULES_COUNT) {\n throw new Error('The provided access boundary has more than ' +\n `${exports.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);\n }\n // Check at least one permission should be defined in each Access Boundary\n // Rule.\n for (const rule of this.credentialAccessBoundary.accessBoundary\n .accessBoundaryRules) {\n if (rule.availablePermissions.length === 0) {\n throw new Error('At least one permission should be defined in access boundary rules.');\n }\n }\n this.stsCredential = new sts.StsCredentials({\n tokenExchangeEndpoint: `https://sts.${this.universeDomain}/v1/token`,\n });\n this.cachedDownscopedAccessToken = null;\n }\n /**\n * Provides a mechanism to inject Downscoped access tokens directly.\n * The expiry_date field is required to facilitate determination of the token\n * expiration which would make it easier for the token consumer to handle.\n * @param credentials The Credentials object to set on the current client.\n */\n setCredentials(credentials) {\n if (!credentials.expiry_date) {\n throw new Error('The access token expiry_date field is missing in the provided ' +\n 'credentials.');\n }\n super.setCredentials(credentials);\n this.cachedDownscopedAccessToken = credentials;\n }\n async getAccessToken() {\n // If the cached access token is unavailable or expired, force refresh.\n // The Downscoped access token will be returned in\n // DownscopedAccessTokenResponse format.\n if (!this.cachedDownscopedAccessToken ||\n this.isExpired(this.cachedDownscopedAccessToken)) {\n await this.refreshAccessTokenAsync();\n }\n // Return Downscoped access token in DownscopedAccessTokenResponse format.\n return {\n token: this.cachedDownscopedAccessToken.access_token,\n expirationTime: this.cachedDownscopedAccessToken.expiry_date,\n res: this.cachedDownscopedAccessToken.res,\n };\n }\n /**\n * The main authentication interface. It takes an optional url which when\n * present is the endpoint being accessed, and returns a Promise which\n * resolves with authorization header fields.\n *\n * The result has the form:\n * { authorization: 'Bearer ' }\n */\n async getRequestHeaders() {\n const accessTokenResponse = await this.getAccessToken();\n const headers = new Headers({\n authorization: `Bearer ${accessTokenResponse.token}`,\n });\n return this.addSharedMetadataHeaders(headers);\n }\n request(opts, callback) {\n if (callback) {\n this.requestAsync(opts).then(r => callback(null, r), e => {\n return callback(e, e.response);\n });\n }\n else {\n return this.requestAsync(opts);\n }\n }\n /**\n * Authenticates the provided HTTP request, processes it and resolves with the\n * returned response.\n * @param opts The HTTP request options.\n * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure\n * @return A promise that resolves with the successful response.\n */\n async requestAsync(opts, reAuthRetried = false) {\n let response;\n try {\n const requestHeaders = await this.getRequestHeaders();\n opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers);\n this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders);\n response = await this.transporter.request(opts);\n }\n catch (e) {\n const res = e.response;\n if (res) {\n const statusCode = res.status;\n // Retry the request for metadata if the following criteria are true:\n // - We haven't already retried. It only makes sense to retry once.\n // - The response was a 401 or a 403\n // - The request didn't send a readableStream\n // - forceRefreshOnFailure is true\n const isReadableStream = res.config.data instanceof stream.Readable;\n const isAuthErr = statusCode === 401 || statusCode === 403;\n if (!reAuthRetried &&\n isAuthErr &&\n !isReadableStream &&\n this.forceRefreshOnFailure) {\n await this.refreshAccessTokenAsync();\n return await this.requestAsync(opts, true);\n }\n }\n throw e;\n }\n return response;\n }\n /**\n * Forces token refresh, even if unexpired tokens are currently cached.\n * GCP access tokens are retrieved from authclient object/source credential.\n * Then GCP access tokens are exchanged for downscoped access tokens via the\n * token exchange endpoint.\n * @return A promise that resolves with the fresh downscoped access token.\n */\n async refreshAccessTokenAsync() {\n // Retrieve GCP access token from source credential.\n const subjectToken = (await this.authClient.getAccessToken()).token;\n // Construct the STS credentials options.\n const stsCredentialsOptions = {\n grantType: STS_GRANT_TYPE,\n requestedTokenType: STS_REQUEST_TOKEN_TYPE,\n subjectToken: subjectToken,\n subjectTokenType: STS_SUBJECT_TOKEN_TYPE,\n };\n // Exchange the source AuthClient access token for a Downscoped access\n // token.\n const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, undefined, this.credentialAccessBoundary);\n /**\n * The STS endpoint will only return the expiration time for the downscoped\n * access token if the original access token represents a service account.\n * The downscoped token's expiration time will always match the source\n * credential expiration. When no expires_in is returned, we can copy the\n * source credential's expiration time.\n */\n const sourceCredExpireDate = this.authClient.credentials?.expiry_date || null;\n const expiryDate = stsResponse.expires_in\n ? new Date().getTime() + stsResponse.expires_in * 1000\n : sourceCredExpireDate;\n // Save response in cached access token.\n this.cachedDownscopedAccessToken = {\n access_token: stsResponse.access_token,\n expiry_date: expiryDate,\n res: stsResponse.res,\n };\n // Save credentials.\n this.credentials = {};\n Object.assign(this.credentials, this.cachedDownscopedAccessToken);\n delete this.credentials.res;\n // Trigger tokens event to notify external listeners.\n this.emit('tokens', {\n refresh_token: null,\n expiry_date: this.cachedDownscopedAccessToken.expiry_date,\n access_token: this.cachedDownscopedAccessToken.access_token,\n token_type: 'Bearer',\n id_token: null,\n });\n // Return the cached access token.\n return this.cachedDownscopedAccessToken;\n }\n /**\n * Returns whether the provided credentials are expired or not.\n * If there is no expiry time, assumes the token is not expired or expiring.\n * @param downscopedAccessToken The credentials to check for expiration.\n * @return Whether the credentials are expired or not.\n */\n isExpired(downscopedAccessToken) {\n const now = new Date().getTime();\n return downscopedAccessToken.expiry_date\n ? now >=\n downscopedAccessToken.expiry_date - this.eagerRefreshThresholdMillis\n : false;\n }\n}\nexports.DownscopedClient = DownscopedClient;\n//# sourceMappingURL=downscopedclient.js.map", "\"use strict\";\n// Copyright 2024 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PassThroughClient = void 0;\nconst authclient_1 = require(\"./authclient\");\n/**\n * An AuthClient without any Authentication information. Useful for:\n * - Anonymous access\n * - Local Emulators\n * - Testing Environments\n *\n */\nclass PassThroughClient extends authclient_1.AuthClient {\n /**\n * Creates a request without any authentication headers or checks.\n *\n * @remarks\n *\n * In testing environments it may be useful to change the provided\n * {@link AuthClient.transporter} for any desired request overrides/handling.\n *\n * @param opts\n * @returns The response of the request.\n */\n async request(opts) {\n return this.transporter.request(opts);\n }\n /**\n * A required method of the base class.\n * Always will return an empty object.\n *\n * @returns {}\n */\n async getAccessToken() {\n return {};\n }\n /**\n * A required method of the base class.\n * Always will return an empty object.\n *\n * @returns {}\n */\n async getRequestHeaders() {\n return new Headers();\n }\n}\nexports.PassThroughClient = PassThroughClient;\n//# sourceMappingURL=passthrough.js.map", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.GoogleAuth = exports.auth = exports.PassThroughClient = exports.ExecutableError = exports.PluggableAuthClient = exports.DownscopedClient = exports.BaseExternalAccountClient = exports.ExternalAccountClient = exports.IdentityPoolClient = exports.AwsRequestSigner = exports.AwsClient = exports.UserRefreshClient = exports.LoginTicket = exports.ClientAuthentication = exports.OAuth2Client = exports.CodeChallengeMethod = exports.Impersonated = exports.JWT = exports.JWTAccess = exports.IdTokenClient = exports.IAMAuth = exports.GCPEnv = exports.Compute = exports.DEFAULT_UNIVERSE = exports.AuthClient = exports.gaxios = exports.gcpMetadata = void 0;\n// Copyright 2017 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nconst googleauth_1 = require(\"./auth/googleauth\");\nObject.defineProperty(exports, \"GoogleAuth\", { enumerable: true, get: function () { return googleauth_1.GoogleAuth; } });\n// Export common deps to ensure types/instances are the exact match. Useful\n// for consistently configuring the library across versions.\nexports.gcpMetadata = require(\"gcp-metadata\");\nexports.gaxios = require(\"gaxios\");\nvar authclient_1 = require(\"./auth/authclient\");\nObject.defineProperty(exports, \"AuthClient\", { enumerable: true, get: function () { return authclient_1.AuthClient; } });\nObject.defineProperty(exports, \"DEFAULT_UNIVERSE\", { enumerable: true, get: function () { return authclient_1.DEFAULT_UNIVERSE; } });\nvar computeclient_1 = require(\"./auth/computeclient\");\nObject.defineProperty(exports, \"Compute\", { enumerable: true, get: function () { return computeclient_1.Compute; } });\nvar envDetect_1 = require(\"./auth/envDetect\");\nObject.defineProperty(exports, \"GCPEnv\", { enumerable: true, get: function () { return envDetect_1.GCPEnv; } });\nvar iam_1 = require(\"./auth/iam\");\nObject.defineProperty(exports, \"IAMAuth\", { enumerable: true, get: function () { return iam_1.IAMAuth; } });\nvar idtokenclient_1 = require(\"./auth/idtokenclient\");\nObject.defineProperty(exports, \"IdTokenClient\", { enumerable: true, get: function () { return idtokenclient_1.IdTokenClient; } });\nvar jwtaccess_1 = require(\"./auth/jwtaccess\");\nObject.defineProperty(exports, \"JWTAccess\", { enumerable: true, get: function () { return jwtaccess_1.JWTAccess; } });\nvar jwtclient_1 = require(\"./auth/jwtclient\");\nObject.defineProperty(exports, \"JWT\", { enumerable: true, get: function () { return jwtclient_1.JWT; } });\nvar impersonated_1 = require(\"./auth/impersonated\");\nObject.defineProperty(exports, \"Impersonated\", { enumerable: true, get: function () { return impersonated_1.Impersonated; } });\nvar oauth2client_1 = require(\"./auth/oauth2client\");\nObject.defineProperty(exports, \"CodeChallengeMethod\", { enumerable: true, get: function () { return oauth2client_1.CodeChallengeMethod; } });\nObject.defineProperty(exports, \"OAuth2Client\", { enumerable: true, get: function () { return oauth2client_1.OAuth2Client; } });\nObject.defineProperty(exports, \"ClientAuthentication\", { enumerable: true, get: function () { return oauth2client_1.ClientAuthentication; } });\nvar loginticket_1 = require(\"./auth/loginticket\");\nObject.defineProperty(exports, \"LoginTicket\", { enumerable: true, get: function () { return loginticket_1.LoginTicket; } });\nvar refreshclient_1 = require(\"./auth/refreshclient\");\nObject.defineProperty(exports, \"UserRefreshClient\", { enumerable: true, get: function () { return refreshclient_1.UserRefreshClient; } });\nvar awsclient_1 = require(\"./auth/awsclient\");\nObject.defineProperty(exports, \"AwsClient\", { enumerable: true, get: function () { return awsclient_1.AwsClient; } });\nvar awsrequestsigner_1 = require(\"./auth/awsrequestsigner\");\nObject.defineProperty(exports, \"AwsRequestSigner\", { enumerable: true, get: function () { return awsrequestsigner_1.AwsRequestSigner; } });\nvar identitypoolclient_1 = require(\"./auth/identitypoolclient\");\nObject.defineProperty(exports, \"IdentityPoolClient\", { enumerable: true, get: function () { return identitypoolclient_1.IdentityPoolClient; } });\nvar externalclient_1 = require(\"./auth/externalclient\");\nObject.defineProperty(exports, \"ExternalAccountClient\", { enumerable: true, get: function () { return externalclient_1.ExternalAccountClient; } });\nvar baseexternalclient_1 = require(\"./auth/baseexternalclient\");\nObject.defineProperty(exports, \"BaseExternalAccountClient\", { enumerable: true, get: function () { return baseexternalclient_1.BaseExternalAccountClient; } });\nvar downscopedclient_1 = require(\"./auth/downscopedclient\");\nObject.defineProperty(exports, \"DownscopedClient\", { enumerable: true, get: function () { return downscopedclient_1.DownscopedClient; } });\nvar pluggable_auth_client_1 = require(\"./auth/pluggable-auth-client\");\nObject.defineProperty(exports, \"PluggableAuthClient\", { enumerable: true, get: function () { return pluggable_auth_client_1.PluggableAuthClient; } });\nObject.defineProperty(exports, \"ExecutableError\", { enumerable: true, get: function () { return pluggable_auth_client_1.ExecutableError; } });\nvar passthrough_1 = require(\"./auth/passthrough\");\nObject.defineProperty(exports, \"PassThroughClient\", { enumerable: true, get: function () { return passthrough_1.PassThroughClient; } });\nconst auth = new googleauth_1.GoogleAuth();\nexports.auth = auth;\n//# sourceMappingURL=index.js.map", "import Fastify, {\n FastifyInstance,\n FastifyReply,\n FastifyRequest,\n FastifyPluginAsync,\n FastifyPluginCallback,\n FastifyPluginOptions,\n FastifyRegisterOptions,\n preHandlerHookHandler,\n onRequestHookHandler,\n preParsingHookHandler,\n preValidationHookHandler,\n preSerializationHookHandler,\n onSendHookHandler,\n onResponseHookHandler,\n onTimeoutHookHandler,\n onErrorHookHandler,\n onRouteHookHandler,\n onRegisterHookHandler,\n onReadyHookHandler,\n onListenHookHandler,\n onCloseHookHandler,\n FastifyBaseLogger,\n FastifyLoggerOptions,\n} from \"fastify\";\nimport cors from \"@fastify/cors\";\nimport { ConfigService, AppConfig } from \"./services/config\";\nimport { errorHandler } from \"./api/middleware\";\nimport { registerApiRoutes } from \"./api/routes\";\nimport { LLMService } from \"./services/llm\";\nimport { ProviderService } from \"./services/provider\";\nimport { TransformerService } from \"./services/transformer\";\nimport { PinoLoggerOptions } from \"fastify/types/logger\";\n\n// Extend FastifyRequest to include custom properties\ndeclare module \"fastify\" {\n interface FastifyRequest {\n provider?: string;\n }\n interface FastifyInstance {\n _server?: Server;\n }\n}\n\ninterface ServerOptions {\n initialConfig?: AppConfig;\n logger?: boolean | PinoLoggerOptions;\n}\n\n// Application factory\nfunction createApp(logger: boolean | PinoLoggerOptions): FastifyInstance {\n const fastify = Fastify({\n bodyLimit: 50 * 1024 * 1024,\n logger,\n });\n\n // Register error handler\n fastify.setErrorHandler(errorHandler);\n\n // Register CORS\n fastify.register(cors);\n return fastify;\n}\n\n// Server class\nclass Server {\n private app: FastifyInstance;\n configService: ConfigService;\n llmService: LLMService;\n providerService: ProviderService;\n transformerService: TransformerService;\n\n constructor(options: ServerOptions = {}) {\n this.app = createApp(options.logger ?? true);\n this.configService = new ConfigService(options);\n this.transformerService = new TransformerService(\n this.configService,\n this.app.log\n );\n this.transformerService.initialize().finally(() => {\n this.providerService = new ProviderService(\n this.configService,\n this.transformerService,\n this.app.log\n );\n this.llmService = new LLMService(this.providerService);\n });\n }\n\n // Type-safe register method using Fastify native types\n async register(\n plugin: FastifyPluginAsync | FastifyPluginCallback,\n options?: FastifyRegisterOptions\n ): Promise {\n await (this.app as any).register(plugin, options);\n }\n\n // Type-safe addHook method with Fastify native types\n addHook(hookName: \"onRequest\", hookFunction: onRequestHookHandler): void;\n addHook(hookName: \"preParsing\", hookFunction: preParsingHookHandler): void;\n addHook(\n hookName: \"preValidation\",\n hookFunction: preValidationHookHandler\n ): void;\n addHook(hookName: \"preHandler\", hookFunction: preHandlerHookHandler): void;\n addHook(\n hookName: \"preSerialization\",\n hookFunction: preSerializationHookHandler\n ): void;\n addHook(hookName: \"onSend\", hookFunction: onSendHookHandler): void;\n addHook(hookName: \"onResponse\", hookFunction: onResponseHookHandler): void;\n addHook(hookName: \"onTimeout\", hookFunction: onTimeoutHookHandler): void;\n addHook(hookName: \"onError\", hookFunction: onErrorHookHandler): void;\n addHook(hookName: \"onRoute\", hookFunction: onRouteHookHandler): void;\n addHook(hookName: \"onRegister\", hookFunction: onRegisterHookHandler): void;\n addHook(hookName: \"onReady\", hookFunction: onReadyHookHandler): void;\n addHook(hookName: \"onListen\", hookFunction: onListenHookHandler): void;\n addHook(hookName: \"onClose\", hookFunction: onCloseHookHandler): void;\n public addHook(hookName: string, hookFunction: any): void {\n this.app.addHook(hookName as any, hookFunction);\n }\n\n async start(): Promise {\n try {\n this.app._server = this;\n\n this.app.addHook(\"preHandler\", (request, reply, done) => {\n if (request.url.startsWith('/v1/messages') && request.body) {\n request.log.info({ body: request.body }, \"request body\");\n request.body.stream === true\n if(!request.body.stream) {\n request.body.stream = false; // Ensure stream is false if not set\n }\n }\n done();\n });\n\n this.app.addHook(\n \"preHandler\",\n async (req: FastifyRequest, reply: FastifyReply) => {\n if (req.url.startsWith(\"/api\") || req.method !== \"POST\") return;\n try {\n const body = req.body as any;\n if (!body || !body.model) {\n return reply\n .code(400)\n .send({ error: \"Missing model in request body\" });\n }\n const [provider, model] = body.model.split(\",\");\n body.model = model;\n req.provider = provider;\n return;\n } catch (err) {\n req.log.error(\"Error in modelProviderMiddleware:\", err);\n return reply.code(500).send({ error: \"Internal server error\" });\n }\n }\n );\n\n this.app.register(registerApiRoutes);\n\n const address = await this.app.listen({\n port: parseInt(this.configService.get(\"PORT\") || \"3000\", 10),\n host: this.configService.get(\"HOST\") || \"127.0.0.1\",\n });\n\n this.app.log.info(`\uD83D\uDE80 LLMs API server listening on ${address}`);\n\n const shutdown = async (signal: string) => {\n this.app.log.info(`Received ${signal}, shutting down gracefully...`);\n await this.app.close();\n process.exit(0);\n };\n\n process.on(\"SIGINT\", () => shutdown(\"SIGINT\"));\n process.on(\"SIGTERM\", () => shutdown(\"SIGTERM\"));\n } catch (error) {\n this.app.log.error(`Error starting server: ${error}`);\n process.exit(1);\n }\n }\n}\n\n// Export for external use\nexport default Server;\n", "import { readFileSync, existsSync } from \"fs\";\nimport { join } from \"path\";\nimport { config } from \"dotenv\";\nimport JSON5 from 'json5';\n\nexport interface ConfigOptions {\n envPath?: string;\n jsonPath?: string;\n useEnvFile?: boolean;\n useJsonFile?: boolean;\n useEnvironmentVariables?: boolean;\n initialConfig?: AppConfig;\n}\n\nexport interface AppConfig {\n [key: string]: any;\n}\n\nexport class ConfigService {\n private config: AppConfig = {};\n private options: ConfigOptions;\n\n constructor(\n options: ConfigOptions = {\n jsonPath: \"./config.json\",\n }\n ) {\n this.options = {\n envPath: options.envPath || \".env\",\n jsonPath: options.jsonPath,\n useEnvFile: false,\n useJsonFile: options.useJsonFile !== false,\n useEnvironmentVariables: options.useEnvironmentVariables !== false,\n ...options,\n };\n\n this.loadConfig();\n }\n\n private loadConfig(): void {\n if (this.options.useJsonFile && this.options.jsonPath) {\n this.loadJsonConfig();\n }\n\n if (this.options.initialConfig) {\n this.config = { ...this.config, ...this.options.initialConfig };\n }\n\n if (this.options.useEnvFile) {\n this.loadEnvConfig();\n }\n\n // if (this.options.useEnvironmentVariables) {\n // this.loadEnvironmentVariables();\n // }\n\n if (this.config.LOG_FILE) {\n process.env.LOG_FILE = this.config.LOG_FILE;\n }\n if (this.config.LOG) {\n process.env.LOG = this.config.LOG;\n }\n }\n\n private loadJsonConfig(): void {\n if (!this.options.jsonPath) return;\n\n const jsonPath = this.isAbsolutePath(this.options.jsonPath)\n ? this.options.jsonPath\n : join(process.cwd(), this.options.jsonPath);\n\n if (existsSync(jsonPath)) {\n try {\n const jsonContent = readFileSync(jsonPath, \"utf-8\");\n const jsonConfig = JSON5.parse(jsonContent);\n this.config = { ...this.config, ...jsonConfig };\n console.log(`Loaded JSON config from: ${jsonPath}`);\n } catch (error) {\n console.warn(`Failed to load JSON config from ${jsonPath}:`, error);\n }\n } else {\n console.warn(`JSON config file not found: ${jsonPath}`);\n }\n }\n\n private loadEnvConfig(): void {\n const envPath = this.isAbsolutePath(this.options.envPath!)\n ? this.options.envPath!\n : join(process.cwd(), this.options.envPath!);\n\n if (existsSync(envPath)) {\n try {\n const result = config({ path: envPath });\n if (result.parsed) {\n this.config = {\n ...this.config,\n ...this.parseEnvConfig(result.parsed),\n };\n }\n } catch (error) {\n console.warn(`Failed to load .env config from ${envPath}:`, error);\n }\n }\n }\n\n private loadEnvironmentVariables(): void {\n const envConfig = this.parseEnvConfig(process.env);\n this.config = { ...this.config, ...envConfig };\n }\n\n private parseEnvConfig(\n env: Record\n ): Partial {\n const parsed: Partial = {};\n\n Object.assign(parsed, env);\n\n return parsed;\n }\n\n private isAbsolutePath(path: string): boolean {\n return path.startsWith(\"/\") || path.includes(\":\");\n }\n\n public get(key: keyof AppConfig): T | undefined;\n public get(key: keyof AppConfig, defaultValue: T): T;\n public get(key: keyof AppConfig, defaultValue?: T): T | undefined {\n const value = this.config[key];\n return value !== undefined ? (value as T) : defaultValue;\n }\n\n public getAll(): AppConfig {\n return { ...this.config };\n }\n\n public getHttpsProxy(): string | undefined {\n return (\n this.get(\"HTTPS_PROXY\") ||\n this.get(\"https_proxy\") ||\n this.get(\"httpsProxy\") ||\n this.get(\"PROXY_URL\")\n );\n }\n\n public has(key: keyof AppConfig): boolean {\n return this.config[key] !== undefined;\n }\n\n public set(key: keyof AppConfig, value: any): void {\n this.config[key] = value;\n }\n\n public reload(): void {\n this.config = {};\n this.loadConfig();\n }\n\n public getConfigSummary(): string {\n const summary: string[] = [];\n\n if (this.options.initialConfig) {\n summary.push(\"Initial Config\");\n }\n\n if (this.options.useJsonFile && this.options.jsonPath) {\n summary.push(`JSON: ${this.options.jsonPath}`);\n }\n\n if (this.options.useEnvFile) {\n summary.push(`ENV: ${this.options.envPath}`);\n }\n\n if (this.options.useEnvironmentVariables) {\n summary.push(\"Environment Variables\");\n }\n\n return `Config sources: ${summary.join(\", \")}`;\n }\n}\n", "import { FastifyRequest, FastifyReply } from \"fastify\";\n\nexport interface ApiError extends Error {\n statusCode?: number;\n code?: string;\n type?: string;\n}\n\nexport function createApiError(\n message: string,\n statusCode: number = 500,\n code: string = \"internal_error\",\n type: string = \"api_error\"\n): ApiError {\n const error = new Error(message) as ApiError;\n error.statusCode = statusCode;\n error.code = code;\n error.type = type;\n return error;\n}\n\nexport async function errorHandler(\n error: ApiError,\n request: FastifyRequest,\n reply: FastifyReply\n) {\n request.log.error(error);\n\n const statusCode = error.statusCode || 500;\n const response = {\n error: {\n message: error.message + error.stack || \"Internal Server Error\",\n type: error.type || \"api_error\",\n code: error.code || \"internal_error\",\n },\n };\n\n return reply.code(statusCode).send(response);\n}\n", "import { ProxyAgent } from \"undici\";\nimport { UnifiedChatRequest } from \"../types/llm\";\n\nexport function sendUnifiedRequest(\n url: URL | string,\n request: UnifiedChatRequest,\n config: any,\n logger?: any\n): Promise {\n const headers = new Headers({\n \"Content-Type\": \"application/json\",\n });\n if (config.headers) {\n Object.entries(config.headers).forEach(([key, value]) => {\n if (value) {\n headers.set(key, value as string);\n }\n });\n }\n let combinedSignal: AbortSignal;\n const timeoutSignal = AbortSignal.timeout(config.TIMEOUT ?? 60 * 1000 * 60);\n\n if (config.signal) {\n const controller = new AbortController();\n const abortHandler = () => controller.abort();\n config.signal.addEventListener(\"abort\", abortHandler);\n timeoutSignal.addEventListener(\"abort\", abortHandler);\n combinedSignal = controller.signal;\n } else {\n combinedSignal = timeoutSignal;\n }\n\n const fetchOptions: RequestInit = {\n method: \"POST\",\n headers: headers,\n body: JSON.stringify(request),\n signal: combinedSignal,\n };\n\n if (config.httpsProxy) {\n (fetchOptions as any).dispatcher = new ProxyAgent(\n new URL(config.httpsProxy).toString()\n );\n }\n logger?.debug(\n {\n request: fetchOptions,\n headers: Object.fromEntries(headers.entries()),\n requestUrl: typeof url === \"string\" ? url : url.toString(),\n useProxy: config.httpsProxy,\n },\n \"final request\"\n );\n return fetch(typeof url === \"string\" ? url : url.toString(), fetchOptions);\n}\n", "{\n \"name\": \"@musistudio/llms\",\n \"version\": \"1.0.28\",\n \"description\": \"A universal LLM API transformation server\",\n \"main\": \"dist/cjs/server.cjs\",\n \"module\": \"dist/esm/server.mjs\",\n \"type\": \"module\",\n \"exports\": {\n \".\": {\n \"import\": \"./dist/esm/server.mjs\",\n \"require\": \"./dist/cjs/server.cjs\"\n }\n },\n \"scripts\": {\n \"tsx\": \"tsx\",\n \"build\": \"tsx scripts/build.ts\",\n \"build:watch\": \"tsx scripts/build.ts --watch\",\n \"dev\": \"nodemon\",\n \"start\": \"node dist/cjs/server.cjs\",\n \"start:esm\": \"node dist/esm/server.mjs\",\n \"lint\": \"eslint src --ext .ts,.tsx\"\n },\n \"keywords\": [],\n \"author\": \"\",\n \"license\": \"MIT\",\n \"dependencies\": {\n \"@anthropic-ai/sdk\": \"^0.54.0\",\n \"@fastify/cors\": \"^11.0.1\",\n \"@google/genai\": \"^1.7.0\",\n \"dotenv\": \"^16.5.0\",\n \"fastify\": \"^5.4.0\",\n \"google-auth-library\": \"^10.1.0\",\n \"json5\": \"^2.2.3\",\n \"jsonrepair\": \"^3.13.0\",\n \"openai\": \"^5.6.0\",\n \"undici\": \"^7.10.0\",\n \"uuid\": \"^11.1.0\"\n },\n \"devDependencies\": {\n \"@types/chai\": \"^5.2.2\",\n \"@types/mocha\": \"^10.0.10\",\n \"@types/node\": \"^24.0.3\",\n \"@types/sinon\": \"^17.0.4\",\n \"@typescript-eslint/eslint-plugin\": \"^8.35.0\",\n \"@typescript-eslint/parser\": \"^8.35.0\",\n \"chai\": \"^5.2.0\",\n \"esbuild\": \"^0.25.5\",\n \"eslint\": \"^9.30.0\",\n \"nodemon\": \"^3.1.10\",\n \"sinon\": \"^21.0.0\",\n \"tsx\": \"^4.20.3\",\n \"typescript\": \"^5.8.3\",\n \"typescript-eslint\": \"^8.35.0\"\n }\n}\n", "import {\n FastifyInstance,\n FastifyPluginAsync,\n FastifyRequest,\n FastifyReply,\n} from \"fastify\";\nimport { RegisterProviderRequest, LLMProvider } from \"@/types/llm\";\nimport { sendUnifiedRequest } from \"@/utils/request\";\nimport { createApiError } from \"./middleware\";\nimport { version } from \"../../package.json\";\n\n/**\n * \u5904\u7406transformer\u7AEF\u70B9\u7684\u4E3B\u51FD\u6570\n * \u534F\u8C03\u6574\u4E2A\u8BF7\u6C42\u5904\u7406\u6D41\u7A0B\uFF1A\u9A8C\u8BC1\u63D0\u4F9B\u8005\u3001\u5904\u7406\u8BF7\u6C42\u8F6C\u6362\u5668\u3001\u53D1\u9001\u8BF7\u6C42\u3001\u5904\u7406\u54CD\u5E94\u8F6C\u6362\u5668\u3001\u683C\u5F0F\u5316\u54CD\u5E94\n */\nasync function handleTransformerEndpoint(\n req: FastifyRequest,\n reply: FastifyReply,\n fastify: FastifyInstance,\n transformer: any\n) {\n const body = req.body as any;\n const providerName = req.provider!;\n const provider = fastify._server!.providerService.getProvider(providerName);\n\n // \u9A8C\u8BC1\u63D0\u4F9B\u8005\u662F\u5426\u5B58\u5728\n if (!provider) {\n throw createApiError(\n `Provider '${providerName}' not found`,\n 404,\n \"provider_not_found\"\n );\n }\n\n // \u5904\u7406\u8BF7\u6C42\u8F6C\u6362\u5668\u94FE\n const { requestBody, config, bypass } = await processRequestTransformers(\n body,\n provider,\n transformer,\n req.headers\n );\n\n // \u53D1\u9001\u8BF7\u6C42\u5230LLM\u63D0\u4F9B\u8005\n const response = await sendRequestToProvider(\n requestBody,\n config,\n provider,\n fastify,\n bypass,\n transformer\n );\n\n // \u5904\u7406\u54CD\u5E94\u8F6C\u6362\u5668\u94FE\n const finalResponse = await processResponseTransformers(\n requestBody,\n response,\n provider,\n transformer,\n bypass\n );\n\n // \u683C\u5F0F\u5316\u5E76\u8FD4\u56DE\u54CD\u5E94\n return formatResponse(finalResponse, reply, body);\n}\n\n/**\n * \u5904\u7406\u8BF7\u6C42\u8F6C\u6362\u5668\u94FE\n * \u4F9D\u6B21\u6267\u884CtransformRequestOut\u3001provider transformers\u3001model-specific transformers\n * \u8FD4\u56DE\u5904\u7406\u540E\u7684\u8BF7\u6C42\u4F53\u3001\u914D\u7F6E\u548C\u662F\u5426\u8DF3\u8FC7\u8F6C\u6362\u5668\u7684\u6807\u5FD7\n */\nasync function processRequestTransformers(\n body: any,\n provider: any,\n transformer: any,\n headers: any\n) {\n let requestBody = body;\n let config = {};\n let bypass = false;\n\n // \u68C0\u67E5\u662F\u5426\u5E94\u8BE5\u8DF3\u8FC7\u8F6C\u6362\u5668\uFF08\u900F\u4F20\u53C2\u6570\uFF09\n bypass = shouldBypassTransformers(provider, transformer, body);\n\n if (bypass) {\n if (headers instanceof Headers) {\n headers.delete(\"content-length\");\n } else {\n delete headers[\"content-length\"];\n }\n config.headers = headers;\n }\n\n // \u6267\u884Ctransformer\u7684transformRequestOut\u65B9\u6CD5\n if (!bypass && typeof transformer.transformRequestOut === \"function\") {\n const transformOut = await transformer.transformRequestOut(requestBody);\n if (transformOut.body) {\n requestBody = transformOut.body;\n config = transformOut.config || {};\n } else {\n requestBody = transformOut;\n }\n }\n\n // \u6267\u884Cprovider\u7EA7\u522B\u7684\u8F6C\u6362\u5668\n if (!bypass && provider.transformer?.use?.length) {\n for (const providerTransformer of provider.transformer.use) {\n if (\n !providerTransformer ||\n typeof providerTransformer.transformRequestIn !== \"function\"\n ) {\n continue;\n }\n const transformIn = await providerTransformer.transformRequestIn(\n requestBody,\n provider\n );\n if (transformIn.body) {\n requestBody = transformIn.body;\n config = { ...config, ...transformIn.config };\n } else {\n requestBody = transformIn;\n }\n }\n }\n\n // \u6267\u884C\u6A21\u578B\u7279\u5B9A\u7684\u8F6C\u6362\u5668\n if (!bypass && provider.transformer?.[body.model]?.use?.length) {\n for (const modelTransformer of provider.transformer[body.model].use) {\n if (\n !modelTransformer ||\n typeof modelTransformer.transformRequestIn !== \"function\"\n ) {\n continue;\n }\n requestBody = await modelTransformer.transformRequestIn(\n requestBody,\n provider\n );\n }\n }\n\n return { requestBody, config, bypass };\n}\n\n/**\n * \u5224\u65AD\u662F\u5426\u5E94\u8BE5\u8DF3\u8FC7\u8F6C\u6362\u5668\uFF08\u900F\u4F20\u53C2\u6570\uFF09\n * \u5F53provider\u53EA\u4F7F\u7528\u4E00\u4E2Atransformer\u4E14\u8BE5transformer\u4E0E\u5F53\u524Dtransformer\u76F8\u540C\u65F6\uFF0C\u8DF3\u8FC7\u5176\u4ED6\u8F6C\u6362\u5668\n */\nfunction shouldBypassTransformers(\n provider: any,\n transformer: any,\n body: any\n): boolean {\n return (\n provider.transformer?.use?.length === 1 &&\n provider.transformer.use[0].name === transformer.name &&\n (!provider.transformer?.[body.model]?.use.length ||\n (provider.transformer?.[body.model]?.use.length === 1 &&\n provider.transformer?.[body.model]?.use[0].name === transformer.name))\n );\n}\n\n/**\n * \u53D1\u9001\u8BF7\u6C42\u5230LLM\u63D0\u4F9B\u8005\n * \u5904\u7406\u8BA4\u8BC1\u3001\u6784\u5EFA\u8BF7\u6C42\u914D\u7F6E\u3001\u53D1\u9001\u8BF7\u6C42\u5E76\u5904\u7406\u9519\u8BEF\n */\nasync function sendRequestToProvider(\n requestBody: any,\n config: any,\n provider: any,\n fastify: FastifyInstance,\n bypass: boolean,\n transformer: any\n) {\n const url = config.url || new URL(provider.baseUrl);\n\n // \u5728\u900F\u4F20\u53C2\u6570\u4E0B\u5904\u7406\u8BA4\u8BC1\n if (bypass && typeof transformer.auth === \"function\") {\n const auth = await transformer.auth(requestBody, provider);\n if (auth.body) {\n requestBody = auth.body;\n let headers = config.headers || {};\n if (auth.config?.headers) {\n headers = {\n ...headers,\n ...auth.config.headers,\n };\n delete headers.host;\n delete auth.config.headers;\n }\n config = {\n ...config,\n ...auth.config,\n headers,\n };\n } else {\n requestBody = auth;\n }\n }\n\n // \u53D1\u9001HTTP\u8BF7\u6C42\n const response = await sendUnifiedRequest(\n url,\n requestBody,\n {\n httpsProxy: fastify._server!.configService.getHttpsProxy(),\n ...config,\n headers: {\n Authorization: `Bearer ${provider.apiKey}`,\n ...(config?.headers || {}),\n },\n },\n fastify.log\n );\n\n // \u5904\u7406\u8BF7\u6C42\u9519\u8BEF\n if (!response.ok) {\n const errorText = await response.text();\n throw createApiError(\n `Error from provider(${provider.name},${requestBody.model}: ${response.status}): ${errorText}`,\n response.status,\n \"provider_response_error\"\n );\n }\n\n return response;\n}\n\n/**\n * \u5904\u7406\u54CD\u5E94\u8F6C\u6362\u5668\u94FE\n * \u4F9D\u6B21\u6267\u884Cprovider transformers\u3001model-specific transformers\u3001transformer\u7684transformResponseIn\n */\nasync function processResponseTransformers(\n requestBody: any,\n response: any,\n provider: any,\n transformer: any,\n bypass: boolean\n) {\n let finalResponse = response;\n\n // \u6267\u884Cprovider\u7EA7\u522B\u7684\u54CD\u5E94\u8F6C\u6362\u5668\n if (!bypass && provider.transformer?.use?.length) {\n for (const providerTransformer of Array.from(\n provider.transformer.use\n ).reverse()) {\n if (\n !providerTransformer ||\n typeof providerTransformer.transformResponseOut !== \"function\"\n ) {\n continue;\n }\n finalResponse = await providerTransformer.transformResponseOut(\n finalResponse\n );\n }\n }\n\n // \u6267\u884C\u6A21\u578B\u7279\u5B9A\u7684\u54CD\u5E94\u8F6C\u6362\u5668\n if (!bypass && provider.transformer?.[requestBody.model]?.use?.length) {\n for (const modelTransformer of Array.from(\n provider.transformer[requestBody.model].use\n ).reverse()) {\n if (\n !modelTransformer ||\n typeof modelTransformer.transformResponseOut !== \"function\"\n ) {\n continue;\n }\n finalResponse = await modelTransformer.transformResponseOut(\n finalResponse\n );\n }\n }\n\n // \u6267\u884Ctransformer\u7684transformResponseIn\u65B9\u6CD5\n if (!bypass && transformer.transformResponseIn) {\n finalResponse = await transformer.transformResponseIn(finalResponse);\n }\n\n return finalResponse;\n}\n\n/**\n * \u683C\u5F0F\u5316\u5E76\u8FD4\u56DE\u54CD\u5E94\n * \u5904\u7406HTTP\u72B6\u6001\u7801\u3001\u6D41\u5F0F\u54CD\u5E94\u548C\u666E\u901A\u54CD\u5E94\u7684\u683C\u5F0F\u5316\n */\nfunction formatResponse(response: any, reply: FastifyReply, body: any) {\n // \u8BBE\u7F6EHTTP\u72B6\u6001\u7801\n if (!response.ok) {\n reply.code(response.status);\n }\n\n // \u5904\u7406\u6D41\u5F0F\u54CD\u5E94\n const isStream = body.stream === true;\n if (isStream) {\n reply.header(\"Content-Type\", \"text/event-stream\");\n reply.header(\"Cache-Control\", \"no-cache\");\n reply.header(\"Connection\", \"keep-alive\");\n return reply.send(response.body);\n } else {\n // \u5904\u7406\u666E\u901AJSON\u54CD\u5E94\n return response.json();\n }\n}\n\nexport const registerApiRoutes: FastifyPluginAsync = async (\n fastify: FastifyInstance\n) => {\n // Health and info endpoints\n fastify.get(\"/\", async () => {\n return { message: \"LLMs API\", version };\n });\n\n fastify.get(\"/health\", async () => {\n return { status: \"ok\", timestamp: new Date().toISOString() };\n });\n\n const transformersWithEndpoint =\n fastify._server!.transformerService.getTransformersWithEndpoint();\n\n for (const { transformer } of transformersWithEndpoint) {\n if (transformer.endPoint) {\n fastify.post(\n transformer.endPoint,\n async (req: FastifyRequest, reply: FastifyReply) => {\n return handleTransformerEndpoint(req, reply, fastify, transformer);\n }\n );\n }\n }\n\n fastify.post(\n \"/providers\",\n {\n schema: {\n body: {\n type: \"object\",\n properties: {\n id: { type: \"string\" },\n name: { type: \"string\" },\n type: { type: \"string\", enum: [\"openai\", \"anthropic\"] },\n baseUrl: { type: \"string\" },\n apiKey: { type: \"string\" },\n models: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"id\", \"name\", \"type\", \"baseUrl\", \"apiKey\", \"models\"],\n },\n },\n },\n async (\n request: FastifyRequest<{ Body: RegisterProviderRequest }>,\n reply: FastifyReply\n ) => {\n // Validation\n const { name, baseUrl, apiKey, models } = request.body;\n\n if (!name?.trim()) {\n throw createApiError(\n \"Provider name is required\",\n 400,\n \"invalid_request\"\n );\n }\n\n if (!baseUrl || !isValidUrl(baseUrl)) {\n throw createApiError(\n \"Valid base URL is required\",\n 400,\n \"invalid_request\"\n );\n }\n\n if (!apiKey?.trim()) {\n throw createApiError(\"API key is required\", 400, \"invalid_request\");\n }\n\n if (!models || !Array.isArray(models) || models.length === 0) {\n throw createApiError(\n \"At least one model is required\",\n 400,\n \"invalid_request\"\n );\n }\n\n // Check if provider already exists\n if (fastify._server!.providerService.getProvider(request.body.name)) {\n throw createApiError(\n `Provider with name '${request.body.name}' already exists`,\n 400,\n \"provider_exists\"\n );\n }\n\n return fastify._server!.providerService.registerProvider(request.body);\n }\n );\n\n fastify.get(\"/providers\", async () => {\n return fastify._server!.providerService.getProviders();\n });\n\n fastify.get(\n \"/providers/:id\",\n {\n schema: {\n params: {\n type: \"object\",\n properties: { id: { type: \"string\" } },\n required: [\"id\"],\n },\n },\n },\n async (request: FastifyRequest<{ Params: { id: string } }>) => {\n const provider = fastify._server!.providerService.getProvider(\n request.params.id\n );\n if (!provider) {\n throw createApiError(\"Provider not found\", 404, \"provider_not_found\");\n }\n return provider;\n }\n );\n\n fastify.put(\n \"/providers/:id\",\n {\n schema: {\n params: {\n type: \"object\",\n properties: { id: { type: \"string\" } },\n required: [\"id\"],\n },\n body: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n type: { type: \"string\", enum: [\"openai\", \"anthropic\"] },\n baseUrl: { type: \"string\" },\n apiKey: { type: \"string\" },\n models: { type: \"array\", items: { type: \"string\" } },\n enabled: { type: \"boolean\" },\n },\n },\n },\n },\n async (\n request: FastifyRequest<{\n Params: { id: string };\n Body: Partial;\n }>,\n reply\n ) => {\n const provider = fastify._server!.providerService.updateProvider(\n request.params.id,\n request.body\n );\n if (!provider) {\n throw createApiError(\"Provider not found\", 404, \"provider_not_found\");\n }\n return provider;\n }\n );\n\n fastify.delete(\n \"/providers/:id\",\n {\n schema: {\n params: {\n type: \"object\",\n properties: { id: { type: \"string\" } },\n required: [\"id\"],\n },\n },\n },\n async (request: FastifyRequest<{ Params: { id: string } }>) => {\n const success = fastify._server!.providerService.deleteProvider(\n request.params.id\n );\n if (!success) {\n throw createApiError(\"Provider not found\", 404, \"provider_not_found\");\n }\n return { message: \"Provider deleted successfully\" };\n }\n );\n\n fastify.patch(\n \"/providers/:id/toggle\",\n {\n schema: {\n params: {\n type: \"object\",\n properties: { id: { type: \"string\" } },\n required: [\"id\"],\n },\n body: {\n type: \"object\",\n properties: { enabled: { type: \"boolean\" } },\n required: [\"enabled\"],\n },\n },\n },\n async (\n request: FastifyRequest<{\n Params: { id: string };\n Body: { enabled: boolean };\n }>,\n reply\n ) => {\n const success = fastify._server!.providerService.toggleProvider(\n request.params.id,\n request.body.enabled\n );\n if (!success) {\n throw createApiError(\"Provider not found\", 404, \"provider_not_found\");\n }\n return {\n message: `Provider ${\n request.body.enabled ? \"enabled\" : \"disabled\"\n } successfully`,\n };\n }\n );\n};\n\n// Helper function\nfunction isValidUrl(url: string): boolean {\n try {\n new URL(url);\n return true;\n } catch {\n return false;\n }\n}\n", "import { ProviderService } from \"./provider\";\nimport {\n LLMProvider,\n RegisterProviderRequest,\n RequestRouteInfo,\n} from \"../types/llm\";\n\nexport class LLMService {\n constructor(private readonly providerService: ProviderService) {\n }\n\n registerProvider(request: RegisterProviderRequest): LLMProvider {\n return this.providerService.registerProvider(request);\n }\n\n getProviders(): LLMProvider[] {\n return this.providerService.getProviders();\n }\n\n getProvider(id: string): LLMProvider | undefined {\n return this.providerService.getProvider(id);\n }\n\n updateProvider(\n id: string,\n updates: Partial\n ): LLMProvider | null {\n const result = this.providerService.updateProvider(id, updates);\n return result;\n }\n\n deleteProvider(id: string): boolean {\n const result = this.providerService.deleteProvider(id);\n return result;\n }\n\n toggleProvider(id: string, enabled: boolean): boolean {\n return this.providerService.toggleProvider(id, enabled);\n }\n\n private resolveRoute(modelName: string): RequestRouteInfo {\n const route = this.providerService.resolveModelRoute(modelName);\n if (!route) {\n throw new Error(\n `Model ${modelName} not found. Available models: ${this.getAvailableModelNames().join(\n \", \"\n )}`\n );\n }\n return route;\n }\n\n async getAvailableModels(): Promise {\n const providers = this.providerService.getAvailableModels();\n\n return {\n object: \"list\",\n data: providers.flatMap((provider) =>\n provider.models.map((model) => ({\n id: model,\n object: \"model\",\n provider: provider.provider,\n created: Math.floor(Date.now() / 1000),\n owned_by: provider.provider,\n }))\n ),\n };\n }\n\n private getAvailableModelNames(): string[] {\n return this.providerService\n .getModelRoutes()\n .map((route) => route.fullModel);\n }\n\n getModelRoutes() {\n return this.providerService.getModelRoutes();\n }\n}\n", "import { TransformerConstructor } from \"@/types/transformer\";\nimport {\n LLMProvider,\n RegisterProviderRequest,\n ModelRoute,\n RequestRouteInfo,\n ConfigProvider,\n} from \"../types/llm\";\nimport { ConfigService } from \"./config\";\nimport { TransformerService } from \"./transformer\";\n\nexport class ProviderService {\n private providers: Map = new Map();\n private modelRoutes: Map = new Map();\n\n constructor(private readonly configService: ConfigService, private readonly transformerService: TransformerService, private readonly logger: any) {\n this.initializeCustomProviders();\n }\n\n private initializeCustomProviders() {\n const providersConfig =\n this.configService.get(\"providers\");\n if (providersConfig && Array.isArray(providersConfig)) {\n this.initializeFromProvidersArray(providersConfig);\n return;\n }\n }\n\n private initializeFromProvidersArray(providersConfig: ConfigProvider[]) {\n providersConfig.forEach((providerConfig: ConfigProvider) => {\n try {\n if (\n !providerConfig.name ||\n !providerConfig.api_base_url ||\n !providerConfig.api_key\n ) {\n return;\n }\n\n const transformer: LLMProvider[\"transformer\"] = {}\n\n if (providerConfig.transformer) {\n Object.keys(providerConfig.transformer).forEach(key => {\n if (key === 'use') {\n if (Array.isArray(providerConfig.transformer.use)) {\n transformer.use = providerConfig.transformer.use.map((transformer) => {\n if (Array.isArray(transformer) && typeof transformer[0] === 'string') {\n const Constructor = this.transformerService.getTransformer(transformer[0]);\n if (Constructor) {\n return new (Constructor as TransformerConstructor)(transformer[1]);\n }\n }\n if (typeof transformer === 'string') {\n const transformerInstance = this.transformerService.getTransformer(transformer);\n if (typeof transformerInstance === 'function') {\n return new transformerInstance();\n }\n return transformerInstance;\n }\n }).filter((transformer) => typeof transformer !== 'undefined');\n }\n } else {\n if (Array.isArray(providerConfig.transformer[key]?.use)) {\n transformer[key] = {\n use: providerConfig.transformer[key].use.map((transformer) => {\n if (Array.isArray(transformer) && typeof transformer[0] === 'string') {\n const Constructor = this.transformerService.getTransformer(transformer[0]);\n if (Constructor) {\n return new (Constructor as TransformerConstructor)(transformer[1]);\n }\n }\n if (typeof transformer === 'string') {\n const transformerInstance = this.transformerService.getTransformer(transformer);\n if (typeof transformerInstance === 'function') {\n return new transformerInstance();\n }\n return transformerInstance;\n }\n }).filter((transformer) => typeof transformer !== 'undefined')\n }\n }\n }\n })\n }\n\n this.registerProvider({\n name: providerConfig.name,\n baseUrl: providerConfig.api_base_url,\n apiKey: providerConfig.api_key,\n models: providerConfig.models || [],\n transformer: providerConfig.transformer ? transformer : undefined,\n });\n\n this.logger.info(`${providerConfig.name} provider registered`);\n } catch (error) {\n this.logger.error(`${providerConfig.name} provider registered error: ${error}`);\n }\n });\n }\n\n registerProvider(request: RegisterProviderRequest): LLMProvider {\n const provider: LLMProvider = {\n ...request,\n };\n\n this.providers.set(provider.name, provider);\n\n request.models.forEach((model) => {\n const fullModel = `${provider.name},${model}`;\n const route: ModelRoute = {\n provider: provider.name,\n model,\n fullModel,\n };\n this.modelRoutes.set(fullModel, route);\n if (!this.modelRoutes.has(model)) {\n this.modelRoutes.set(model, route);\n }\n });\n\n return provider;\n }\n\n getProviders(): LLMProvider[] {\n return Array.from(this.providers.values());\n }\n\n getProvider(name: string): LLMProvider | undefined {\n return this.providers.get(name);\n }\n\n updateProvider(\n id: string,\n updates: Partial\n ): LLMProvider | null {\n const provider = this.providers.get(id);\n if (!provider) {\n return null;\n }\n\n const updatedProvider = {\n ...provider,\n ...updates,\n updatedAt: new Date(),\n };\n\n this.providers.set(id, updatedProvider);\n\n if (updates.models) {\n provider.models.forEach((model) => {\n const fullModel = `${provider.id},${model}`;\n this.modelRoutes.delete(fullModel);\n this.modelRoutes.delete(model);\n });\n\n updates.models.forEach((model) => {\n const fullModel = `${provider.name},${model}`;\n const route: ModelRoute = {\n provider: provider.name,\n model,\n fullModel,\n };\n this.modelRoutes.set(fullModel, route);\n if (!this.modelRoutes.has(model)) {\n this.modelRoutes.set(model, route);\n }\n });\n }\n\n return updatedProvider;\n }\n\n deleteProvider(id: string): boolean {\n const provider = this.providers.get(id);\n if (!provider) {\n return false;\n }\n\n provider.models.forEach((model) => {\n const fullModel = `${provider.name},${model}`;\n this.modelRoutes.delete(fullModel);\n this.modelRoutes.delete(model);\n });\n\n this.providers.delete(id);\n return true;\n }\n\n toggleProvider(name: string, enabled: boolean): boolean {\n const provider = this.providers.get(name);\n if (!provider) {\n return false;\n }\n return true;\n }\n\n resolveModelRoute(modelName: string): RequestRouteInfo | null {\n const route = this.modelRoutes.get(modelName);\n if (!route) {\n return null;\n }\n\n const provider = this.providers.get(route.provider);\n if (!provider) {\n return null;\n }\n\n return {\n provider,\n originalModel: modelName,\n targetModel: route.model,\n };\n }\n\n getAvailableModelNames(): string[] {\n const modelNames: string[] = [];\n this.providers.forEach((provider) => {\n provider.models.forEach((model) => {\n modelNames.push(model);\n modelNames.push(`${provider.name},${model}`);\n });\n });\n return modelNames;\n }\n\n getModelRoutes(): ModelRoute[] {\n return Array.from(this.modelRoutes.values());\n }\n\n private parseTransformerConfig(transformerConfig: any): any {\n if (!transformerConfig) return {};\n\n if (Array.isArray(transformerConfig)) {\n return transformerConfig.reduce((acc, item) => {\n if (Array.isArray(item)) {\n const [name, config = {}] = item;\n acc[name] = config;\n } else {\n acc[item] = {};\n }\n return acc;\n }, {});\n }\n\n return transformerConfig;\n }\n\n async getAvailableModels(): Promise<{\n object: string;\n data: Array<{\n id: string;\n object: string;\n owned_by: string;\n provider: string;\n }>;\n }> {\n const models: Array<{\n id: string;\n object: string;\n owned_by: string;\n provider: string;\n }> = [];\n\n this.providers.forEach((provider) => {\n provider.models.forEach((model) => {\n models.push({\n id: model,\n object: \"model\",\n owned_by: provider.name,\n provider: provider.name,\n });\n\n models.push({\n id: `${provider.name},${model}`,\n object: \"model\",\n owned_by: provider.name,\n provider: provider.name,\n });\n });\n });\n\n return {\n object: \"list\",\n data: models,\n };\n }\n}\n", "import validate from './validate.js';\nconst byteToHex = [];\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nexport function unsafeStringify(arr, offset = 0) {\n return (byteToHex[arr[offset + 0]] +\n byteToHex[arr[offset + 1]] +\n byteToHex[arr[offset + 2]] +\n byteToHex[arr[offset + 3]] +\n '-' +\n byteToHex[arr[offset + 4]] +\n byteToHex[arr[offset + 5]] +\n '-' +\n byteToHex[arr[offset + 6]] +\n byteToHex[arr[offset + 7]] +\n '-' +\n byteToHex[arr[offset + 8]] +\n byteToHex[arr[offset + 9]] +\n '-' +\n byteToHex[arr[offset + 10]] +\n byteToHex[arr[offset + 11]] +\n byteToHex[arr[offset + 12]] +\n byteToHex[arr[offset + 13]] +\n byteToHex[arr[offset + 14]] +\n byteToHex[arr[offset + 15]]).toLowerCase();\n}\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset);\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n return uuid;\n}\nexport default stringify;\n", "import { randomFillSync } from 'crypto';\nconst rnds8Pool = new Uint8Array(256);\nlet poolPtr = rnds8Pool.length;\nexport default function rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n return rnds8Pool.slice(poolPtr, (poolPtr += 16));\n}\n", "import { randomUUID } from 'crypto';\nexport default { randomUUID };\n", "import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n options = options || {};\n const rnds = options.random ?? options.rng?.() ?? rng();\n if (rnds.length < 16) {\n throw new Error('Random bytes length must be >= 16');\n }\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n if (buf) {\n offset = offset || 0;\n if (offset < 0 || offset + 16 > buf.length) {\n throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);\n }\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n return buf;\n }\n return unsafeStringify(rnds);\n}\nexport default v4;\n", "import { ThinkLevel } from \"@/types/llm\";\n\nexport const getThinkLevel = (thinking_budget: number): ThinkLevel => {\n if (thinking_budget <= 0) return \"none\";\n if (thinking_budget <= 1024) return \"low\";\n if (thinking_budget <= 8192) return \"medium\";\n return \"high\";\n};\n", "import { ChatCompletion } from \"openai/resources\";\nimport {\n LLMProvider,\n UnifiedChatRequest,\n UnifiedMessage,\n UnifiedTool,\n} from \"@/types/llm\";\nimport { Transformer, TransformerContext } from \"@/types/transformer\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { getThinkLevel } from \"@/utils/thinking\";\nimport { createApiError } from \"@/api/middleware\";\n\nexport class AnthropicTransformer implements Transformer {\n name = \"Anthropic\";\n endPoint = \"/v1/messages\";\n\n async auth(request: any, provider: LLMProvider): Promise {\n return {\n body: request,\n config: {\n headers: {\n \"x-api-key\": provider.apiKey,\n authorization: undefined,\n },\n },\n };\n }\n\n async transformRequestOut(\n request: Record\n ): Promise {\n const messages: UnifiedMessage[] = [];\n\n if (request.system) {\n if (typeof request.system === \"string\") {\n messages.push({\n role: \"system\",\n content: request.system,\n });\n } else if (Array.isArray(request.system) && request.system.length) {\n const textParts = request.system\n .filter((item: any) => item.type === \"text\" && item.text)\n .map((item: any) => ({\n type: \"text\" as const,\n text: item.text,\n cache_control: item.cache_control,\n }));\n messages.push({\n role: \"system\",\n content: textParts,\n });\n }\n }\n\n const requestMessages = JSON.parse(JSON.stringify(request.messages || []));\n\n requestMessages?.forEach((msg: any, index: number) => {\n if (msg.role === \"user\" || msg.role === \"assistant\") {\n if (typeof msg.content === \"string\") {\n messages.push({\n role: msg.role,\n content: msg.content,\n });\n return;\n }\n\n if (Array.isArray(msg.content)) {\n if (msg.role === \"user\") {\n const toolParts = msg.content.filter(\n (c: any) => c.type === \"tool_result\" && c.tool_use_id\n );\n if (toolParts.length) {\n toolParts.forEach((tool: any, toolIndex: number) => {\n const toolMessage: UnifiedMessage = {\n role: \"tool\",\n content:\n typeof tool.content === \"string\"\n ? tool.content\n : JSON.stringify(tool.content),\n tool_call_id: tool.tool_use_id,\n cache_control: tool.cache_control,\n };\n messages.push(toolMessage);\n });\n }\n\n const textAndMediaParts = msg.content.filter(\n (c: any) =>\n (c.type === \"text\" && c.text) ||\n (c.type === \"image\" && c.source)\n );\n if (textAndMediaParts.length) {\n messages.push({\n role: \"user\",\n content: textAndMediaParts.map((part: any) => {\n if (part?.type === \"image\") {\n return {\n type: \"image_url\",\n image_url: {\n url:\n part.source?.type === \"base64\"\n ? part.source.data\n : part.source.url,\n },\n media_type: part.source.media_type,\n };\n }\n return part;\n }),\n });\n }\n } else if (msg.role === \"assistant\") {\n const assistantMessage: UnifiedMessage = {\n role: \"assistant\",\n content: null,\n };\n const textParts = msg.content.filter(\n (c: any) => c.type === \"text\" && c.text\n );\n if (textParts.length) {\n assistantMessage.content = textParts\n .map((text: any) => text.text)\n .join(\"\\n\");\n }\n\n const toolCallParts = msg.content.filter(\n (c: any) => c.type === \"tool_use\" && c.id\n );\n if (toolCallParts.length) {\n assistantMessage.tool_calls = toolCallParts.map((tool: any) => {\n return {\n id: tool.id,\n type: \"function\" as const,\n function: {\n name: tool.name,\n arguments: JSON.stringify(tool.input || {}),\n },\n };\n });\n }\n messages.push(assistantMessage);\n }\n return;\n }\n }\n });\n\n const result: UnifiedChatRequest = {\n messages,\n model: request.model,\n max_tokens: request.max_tokens,\n temperature: request.temperature,\n stream: request.stream,\n tools: request.tools?.length\n ? this.convertAnthropicToolsToUnified(request.tools)\n : undefined,\n tool_choice: request.tool_choice,\n };\n if (request.thinking) {\n result.reasoning = {\n effort: getThinkLevel(request.thinking.budget_tokens),\n // max_tokens: request.thinking.budget_tokens,\n enabled: request.thinking.type === \"enabled\",\n };\n }\n if (request.tool_choice) {\n if (request.tool_choice.type === \"tool\") {\n result.tool_choice = {\n type: \"function\",\n function: { name: request.tool_choice.name },\n };\n } else {\n result.tool_choice = request.tool_choice.type;\n }\n }\n return result;\n }\n\n async transformResponseIn(\n response: Response,\n context?: TransformerContext\n ): Promise {\n const isStream = response.headers\n .get(\"Content-Type\")\n ?.includes(\"text/event-stream\");\n if (isStream) {\n if (!response.body) {\n throw new Error(\"Stream response body is null\");\n }\n const convertedStream = await this.convertOpenAIStreamToAnthropic(\n response.body\n );\n return new Response(convertedStream, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n } else {\n const data = await response.json();\n const anthropicResponse = this.convertOpenAIResponseToAnthropic(data);\n return new Response(JSON.stringify(anthropicResponse), {\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n }\n\n private convertAnthropicToolsToUnified(tools: any[]): UnifiedTool[] {\n return tools.map((tool) => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description || \"\",\n parameters: tool.input_schema,\n },\n }));\n }\n\n private async convertOpenAIStreamToAnthropic(\n openaiStream: ReadableStream\n ): Promise {\n const readable = new ReadableStream({\n start: async (controller) => {\n const encoder = new TextEncoder();\n const messageId = `msg_${Date.now()}`;\n let stopReasonMessageDelta: null | Record = null;\n let model = \"unknown\";\n let hasStarted = false;\n let hasTextContentStarted = false;\n let hasFinished = false;\n const toolCalls = new Map();\n const toolCallIndexToContentBlockIndex = new Map();\n let totalChunks = 0;\n let contentChunks = 0;\n let toolCallChunks = 0;\n let isClosed = false;\n let isThinkingStarted = false;\n let contentIndex = 0;\n let currentContentBlockIndex = -1; // Track the current content block index\n\n const safeEnqueue = (data: Uint8Array) => {\n if (!isClosed) {\n try {\n controller.enqueue(data);\n const dataStr = new TextDecoder().decode(data);\n this.logger.debug({ dataStr }, `send data`);\n } catch (error) {\n if (\n error instanceof TypeError &&\n error.message.includes(\"Controller is already closed\")\n ) {\n isClosed = true;\n } else {\n this.logger.debug(`send data error: ${error.message}`);\n throw error;\n }\n }\n }\n };\n\n const safeClose = () => {\n if (!isClosed) {\n try {\n // Close any remaining open content block\n if (currentContentBlockIndex >= 0) {\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: currentContentBlockIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n }\n\n if (stopReasonMessageDelta) {\n safeEnqueue(\n encoder.encode(\n `event: message_delta\\ndata: ${JSON.stringify(\n stopReasonMessageDelta\n )}\\n\\n`\n )\n );\n stopReasonMessageDelta = null;\n } else {\n safeEnqueue(\n encoder.encode(\n `event: message_delta\\ndata: ${JSON.stringify({\n type: \"message_delta\",\n delta: {\n stop_reason: \"end_turn\",\n stop_sequence: null,\n },\n usage: {\n input_tokens: 0,\n output_tokens: 0,\n cache_read_input_tokens: 0,\n },\n })}\\n\\n`\n )\n );\n }\n const messageStop = {\n type: \"message_stop\",\n };\n safeEnqueue(\n encoder.encode(\n `event: message_stop\\ndata: ${JSON.stringify(\n messageStop\n )}\\n\\n`\n )\n );\n controller.close();\n isClosed = true;\n } catch (error) {\n if (\n error instanceof TypeError &&\n error.message.includes(\"Controller is already closed\")\n ) {\n isClosed = true;\n } else {\n throw error;\n }\n }\n }\n };\n\n let reader: ReadableStreamDefaultReader | null = null;\n\n try {\n reader = openaiStream.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n while (true) {\n if (isClosed) {\n break;\n }\n\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (isClosed || hasFinished) break;\n\n if (!line.startsWith(\"data:\")) continue;\n const data = line.slice(5).trim();\n this.logger.debug(`recieved data: ${data}`);\n\n if (data === \"[DONE]\") {\n continue;\n }\n\n try {\n const chunk = JSON.parse(data);\n totalChunks++;\n this.logger.debug({ response: chunk }, `Original Response`);\n if (chunk.error) {\n const errorMessage = {\n type: \"error\",\n message: {\n type: \"api_error\",\n message: JSON.stringify(chunk.error),\n },\n };\n\n safeEnqueue(\n encoder.encode(\n `event: error\\ndata: ${JSON.stringify(errorMessage)}\\n\\n`\n )\n );\n continue;\n }\n\n model = chunk.model || model;\n\n if (!hasStarted && !isClosed && !hasFinished) {\n hasStarted = true;\n\n const messageStart = {\n type: \"message_start\",\n message: {\n id: messageId,\n type: \"message\",\n role: \"assistant\",\n content: [],\n model: model,\n stop_reason: null,\n stop_sequence: null,\n usage: {\n input_tokens: 0,\n output_tokens: 0,\n },\n },\n };\n\n safeEnqueue(\n encoder.encode(\n `event: message_start\\ndata: ${JSON.stringify(\n messageStart\n )}\\n\\n`\n )\n );\n }\n\n const choice = chunk.choices?.[0];\n if (chunk.usage) {\n if (!stopReasonMessageDelta) {\n stopReasonMessageDelta = {\n type: \"message_delta\",\n delta: {\n stop_reason: \"end_turn\",\n stop_sequence: null,\n },\n usage: {\n input_tokens: chunk.usage?.prompt_tokens || 0,\n output_tokens: chunk.usage?.completion_tokens || 0,\n cache_read_input_tokens:\n chunk.usage?.cache_read_input_tokens || 0,\n },\n };\n } else {\n stopReasonMessageDelta.usage = {\n input_tokens: chunk.usage?.prompt_tokens || 0,\n output_tokens: chunk.usage?.completion_tokens || 0,\n cache_read_input_tokens:\n chunk.usage?.cache_read_input_tokens || 0,\n };\n }\n }\n if (!choice) {\n continue;\n }\n\n if (choice?.delta?.thinking && !isClosed && !hasFinished) {\n // Close any previous content block if open\n if (currentContentBlockIndex >= 0) {\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: currentContentBlockIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n }\n\n if (!isThinkingStarted) {\n const contentBlockStart = {\n type: \"content_block_start\",\n index: contentIndex,\n content_block: { type: \"thinking\", thinking: \"\" },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_start\\ndata: ${JSON.stringify(\n contentBlockStart\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = contentIndex;\n isThinkingStarted = true;\n }\n if (choice.delta.thinking.signature) {\n const thinkingSignature = {\n type: \"content_block_delta\",\n index: contentIndex,\n delta: {\n type: \"signature_delta\",\n signature: choice.delta.thinking.signature,\n },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_delta\\ndata: ${JSON.stringify(\n thinkingSignature\n )}\\n\\n`\n )\n );\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: contentIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n contentIndex++;\n } else if (choice.delta.thinking.content) {\n const thinkingChunk = {\n type: \"content_block_delta\",\n index: contentIndex,\n delta: {\n type: \"thinking_delta\",\n thinking: choice.delta.thinking.content || \"\",\n },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_delta\\ndata: ${JSON.stringify(\n thinkingChunk\n )}\\n\\n`\n )\n );\n }\n }\n\n if (choice?.delta?.content && !isClosed && !hasFinished) {\n contentChunks++;\n\n // Close any previous content block if open and it's not a text content block\n if (currentContentBlockIndex >= 0) {\n // Check if current content block is text type\n const isCurrentTextBlock = hasTextContentStarted;\n if (!isCurrentTextBlock) {\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: currentContentBlockIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n }\n }\n\n if (!hasTextContentStarted && !hasFinished) {\n hasTextContentStarted = true;\n const contentBlockStart = {\n type: \"content_block_start\",\n index: contentIndex,\n content_block: {\n type: \"text\",\n text: \"\",\n },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_start\\ndata: ${JSON.stringify(\n contentBlockStart\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = contentIndex;\n }\n\n if (!isClosed && !hasFinished) {\n const anthropicChunk = {\n type: \"content_block_delta\",\n index: currentContentBlockIndex, // Use current content block index\n delta: {\n type: \"text_delta\",\n text: choice.delta.content,\n },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_delta\\ndata: ${JSON.stringify(\n anthropicChunk\n )}\\n\\n`\n )\n );\n }\n }\n\n if (\n choice?.delta?.annotations?.length &&\n !isClosed &&\n !hasFinished\n ) {\n // Close text content block if open\n if (currentContentBlockIndex >= 0 && hasTextContentStarted) {\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: currentContentBlockIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n hasTextContentStarted = false;\n }\n\n choice?.delta?.annotations.forEach((annotation: any) => {\n contentIndex++;\n const contentBlockStart = {\n type: \"content_block_start\",\n index: contentIndex,\n content_block: {\n type: \"web_search_tool_result\",\n tool_use_id: `srvtoolu_${uuidv4()}`,\n content: [\n {\n type: \"web_search_result\",\n title: annotation.url_citation.title,\n url: annotation.url_citation.url,\n },\n ],\n },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_start\\ndata: ${JSON.stringify(\n contentBlockStart\n )}\\n\\n`\n )\n );\n\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: contentIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n });\n }\n\n if (choice?.delta?.tool_calls && !isClosed && !hasFinished) {\n toolCallChunks++;\n const processedInThisChunk = new Set();\n\n for (const toolCall of choice.delta.tool_calls) {\n if (isClosed) break;\n const toolCallIndex = toolCall.index ?? 0;\n if (processedInThisChunk.has(toolCallIndex)) {\n continue;\n }\n processedInThisChunk.add(toolCallIndex);\n const isUnknownIndex =\n !toolCallIndexToContentBlockIndex.has(toolCallIndex);\n\n if (isUnknownIndex) {\n // Close any previous content block if open\n if (currentContentBlockIndex >= 0) {\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: currentContentBlockIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n }\n\n const newContentBlockIndex = contentIndex;\n toolCallIndexToContentBlockIndex.set(\n toolCallIndex,\n newContentBlockIndex\n );\n contentIndex++; // Increment contentIndex after setting the mapping\n const toolCallId =\n toolCall.id || `call_${Date.now()}_${toolCallIndex}`;\n const toolCallName =\n toolCall.function?.name || `tool_${toolCallIndex}`;\n const contentBlockStart = {\n type: \"content_block_start\",\n index: newContentBlockIndex,\n content_block: {\n type: \"tool_use\",\n id: toolCallId,\n name: toolCallName,\n input: {},\n },\n };\n\n safeEnqueue(\n encoder.encode(\n `event: content_block_start\\ndata: ${JSON.stringify(\n contentBlockStart\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = newContentBlockIndex;\n\n const toolCallInfo = {\n id: toolCallId,\n name: toolCallName,\n arguments: \"\",\n contentBlockIndex: newContentBlockIndex,\n };\n toolCalls.set(toolCallIndex, toolCallInfo);\n } else if (toolCall.id && toolCall.function?.name) {\n const existingToolCall = toolCalls.get(toolCallIndex)!;\n const wasTemporary =\n existingToolCall.id.startsWith(\"call_\") &&\n existingToolCall.name.startsWith(\"tool_\");\n\n if (wasTemporary) {\n existingToolCall.id = toolCall.id;\n existingToolCall.name = toolCall.function.name;\n }\n }\n\n if (\n toolCall.function?.arguments &&\n !isClosed &&\n !hasFinished\n ) {\n const blockIndex =\n toolCallIndexToContentBlockIndex.get(toolCallIndex);\n if (blockIndex === undefined) {\n continue;\n }\n const currentToolCall = toolCalls.get(toolCallIndex);\n if (currentToolCall) {\n currentToolCall.arguments +=\n toolCall.function.arguments;\n }\n\n try {\n const anthropicChunk = {\n type: \"content_block_delta\",\n index: blockIndex, // Use the correct content block index\n delta: {\n type: \"input_json_delta\",\n partial_json: toolCall.function.arguments,\n },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_delta\\ndata: ${JSON.stringify(\n anthropicChunk\n )}\\n\\n`\n )\n );\n } catch (error) {\n try {\n const fixedArgument = toolCall.function.arguments\n .replace(/[\\x00-\\x1F\\x7F-\\x9F]/g, \"\")\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"');\n\n const fixedChunk = {\n type: \"content_block_delta\",\n index: blockIndex, // Use the correct content block index\n delta: {\n type: \"input_json_delta\",\n partial_json: fixedArgument,\n },\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_delta\\ndata: ${JSON.stringify(\n fixedChunk\n )}\\n\\n`\n )\n );\n } catch (fixError) {\n console.error(fixError);\n }\n }\n }\n }\n }\n\n if (choice?.finish_reason && !isClosed && !hasFinished) {\n if (contentChunks === 0 && toolCallChunks === 0) {\n console.error(\n \"Warning: No content in the stream response!\"\n );\n }\n\n // Close any remaining open content block\n if (currentContentBlockIndex >= 0) {\n const contentBlockStop = {\n type: \"content_block_stop\",\n index: currentContentBlockIndex,\n };\n safeEnqueue(\n encoder.encode(\n `event: content_block_stop\\ndata: ${JSON.stringify(\n contentBlockStop\n )}\\n\\n`\n )\n );\n currentContentBlockIndex = -1;\n }\n\n if (!isClosed) {\n const stopReasonMapping: Record = {\n stop: \"end_turn\",\n length: \"max_tokens\",\n tool_calls: \"tool_use\",\n content_filter: \"stop_sequence\",\n };\n\n const anthropicStopReason =\n stopReasonMapping[choice.finish_reason] || \"end_turn\";\n\n stopReasonMessageDelta = {\n type: \"message_delta\",\n delta: {\n stop_reason: anthropicStopReason,\n stop_sequence: null,\n },\n usage: {\n input_tokens: chunk.usage?.prompt_tokens || 0,\n output_tokens: chunk.usage?.completion_tokens || 0,\n cache_read_input_tokens:\n chunk.usage?.cache_read_input_tokens || 0,\n },\n };\n }\n\n break;\n }\n } catch (parseError: any) {\n this.logger?.error(\n `parseError: ${parseError.name} message: ${parseError.message} stack: ${parseError.stack} data: ${data}`\n );\n }\n }\n }\n safeClose();\n } catch (error) {\n if (!isClosed) {\n try {\n controller.error(error);\n } catch (controllerError) {\n console.error(controllerError);\n }\n }\n } finally {\n if (reader) {\n try {\n reader.releaseLock();\n } catch (releaseError) {\n console.error(releaseError);\n }\n }\n }\n },\n cancel: (reason) => {\n this.logger.debug(`cancle stream: ${reason}`);\n },\n });\n\n return readable;\n }\n\n private convertOpenAIResponseToAnthropic(\n openaiResponse: ChatCompletion\n ): any {\n this.logger.debug({ response: openaiResponse }, `Original OpenAI response`);\n try {\n const choice = openaiResponse.choices[0];\n if (!choice) {\n throw new Error(\"No choices found in OpenAI response\");\n }\n const content: any[] = [];\n if (choice.message.annotations) {\n const id = `srvtoolu_${uuidv4()}`;\n content.push({\n type: \"server_tool_use\",\n id,\n name: \"web_search\",\n input: {\n query: \"\",\n },\n });\n content.push({\n type: \"web_search_tool_result\",\n tool_use_id: id,\n content: choice.message.annotations.map((item) => {\n return {\n type: \"web_search_result\",\n url: item.url_citation.url,\n title: item.url_citation.title,\n };\n }),\n });\n }\n if (choice.message.content) {\n content.push({\n type: \"text\",\n text: choice.message.content,\n });\n }\n if (choice.message.tool_calls && choice.message.tool_calls.length > 0) {\n choice.message.tool_calls.forEach((toolCall, index) => {\n let parsedInput = {};\n try {\n const argumentsStr = toolCall.function.arguments || \"{}\";\n\n if (typeof argumentsStr === \"object\") {\n parsedInput = argumentsStr;\n } else if (typeof argumentsStr === \"string\") {\n parsedInput = JSON.parse(argumentsStr);\n }\n } catch (parseError) {\n parsedInput = { text: toolCall.function.arguments || \"\" };\n }\n\n content.push({\n type: \"tool_use\",\n id: toolCall.id,\n name: toolCall.function.name,\n input: parsedInput,\n });\n });\n }\n\n const result = {\n id: openaiResponse.id,\n type: \"message\",\n role: \"assistant\",\n model: openaiResponse.model,\n content: content,\n stop_reason:\n choice.finish_reason === \"stop\"\n ? \"end_turn\"\n : choice.finish_reason === \"length\"\n ? \"max_tokens\"\n : choice.finish_reason === \"tool_calls\"\n ? \"tool_use\"\n : choice.finish_reason === \"content_filter\"\n ? \"stop_sequence\"\n : \"end_turn\",\n stop_sequence: null,\n usage: {\n input_tokens: openaiResponse.usage?.prompt_tokens || 0,\n output_tokens: openaiResponse.usage?.completion_tokens || 0,\n },\n };\n this.logger.debug(\n { result },\n `Conversion complete, final Anthropic response`\n );\n return result;\n } catch (e) {\n throw createApiError(\n `Provider error: ${JSON.stringify(openaiResponse)}`,\n 500,\n \"provider_error\"\n );\n }\n }\n}\n", "import { UnifiedChatRequest, UnifiedMessage } from \"../types/llm\";\nimport { Content, ContentListUnion, Part, ToolListUnion } from \"@google/genai\";\n\nexport function cleanupParameters(obj: any, keyName?: string): void {\n if (!obj || typeof obj !== \"object\") {\n return;\n }\n\n if (Array.isArray(obj)) {\n obj.forEach((item) => {\n cleanupParameters(item);\n });\n return;\n }\n\n const validFields = new Set([\n \"type\",\n \"format\",\n \"title\",\n \"description\",\n \"nullable\",\n \"enum\",\n \"maxItems\",\n \"minItems\",\n \"properties\",\n \"required\",\n \"minProperties\",\n \"maxProperties\",\n \"minLength\",\n \"maxLength\",\n \"pattern\",\n \"example\",\n \"anyOf\",\n \"propertyOrdering\",\n \"default\",\n \"items\",\n \"minimum\",\n \"maximum\",\n ]);\n\n if (keyName !== \"properties\") {\n Object.keys(obj).forEach((key) => {\n if (!validFields.has(key)) {\n delete obj[key];\n }\n });\n }\n\n if (obj.enum && obj.type !== \"string\") {\n delete obj.enum;\n }\n\n if (\n obj.type === \"string\" &&\n obj.format &&\n ![\"enum\", \"date-time\"].includes(obj.format)\n ) {\n delete obj.format;\n }\n\n Object.keys(obj).forEach((key) => {\n cleanupParameters(obj[key], key);\n });\n}\n\n// Type enum equivalent in JavaScript\nconst Type = {\n TYPE_UNSPECIFIED: \"TYPE_UNSPECIFIED\",\n STRING: \"STRING\",\n NUMBER: \"NUMBER\",\n INTEGER: \"INTEGER\",\n BOOLEAN: \"BOOLEAN\",\n ARRAY: \"ARRAY\",\n OBJECT: \"OBJECT\",\n NULL: \"NULL\",\n};\n\n/**\n * Transform the type field from an array of types to an array of anyOf fields.\n * @param {string[]} typeList - List of types\n * @param {Object} resultingSchema - The schema object to modify\n */\nfunction flattenTypeArrayToAnyOf(typeList: Array, resultingSchema: any): void {\n if (typeList.includes(\"null\")) {\n resultingSchema[\"nullable\"] = true;\n }\n const listWithoutNull = typeList.filter((type) => type !== \"null\");\n\n if (listWithoutNull.length === 1) {\n const upperCaseType = listWithoutNull[0].toUpperCase();\n resultingSchema[\"type\"] = Object.values(Type).includes(upperCaseType)\n ? upperCaseType\n : Type.TYPE_UNSPECIFIED;\n } else {\n resultingSchema[\"anyOf\"] = [];\n for (const i of listWithoutNull) {\n const upperCaseType = i.toUpperCase();\n resultingSchema[\"anyOf\"].push({\n type: Object.values(Type).includes(upperCaseType)\n ? upperCaseType\n : Type.TYPE_UNSPECIFIED,\n });\n }\n }\n}\n\n/**\n * Process a JSON schema to make it compatible with the GenAI API\n * @param {Object} _jsonSchema - The JSON schema to process\n * @returns {Object} - The processed schema\n */\nfunction processJsonSchema(_jsonSchema: any): any {\n const genAISchema = {};\n const schemaFieldNames = [\"items\"];\n const listSchemaFieldNames = [\"anyOf\"];\n const dictSchemaFieldNames = [\"properties\"];\n\n if (_jsonSchema[\"type\"] && _jsonSchema[\"anyOf\"]) {\n throw new Error(\"type and anyOf cannot be both populated.\");\n }\n\n /*\n This is to handle the nullable array or object. The _jsonSchema will\n be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The\n logic is to check if anyOf has 2 elements and one of the element is null,\n if so, the anyOf field is unnecessary, so we need to get rid of the anyOf\n field and make the schema nullable. Then use the other element as the new\n _jsonSchema for processing. This is because the backend doesn't have a null\n type.\n */\n const incomingAnyOf = _jsonSchema[\"anyOf\"];\n if (\n incomingAnyOf != null &&\n Array.isArray(incomingAnyOf) &&\n incomingAnyOf.length == 2\n ) {\n if (incomingAnyOf[0] && incomingAnyOf[0][\"type\"] === \"null\") {\n genAISchema[\"nullable\"] = true;\n _jsonSchema = incomingAnyOf[1];\n } else if (incomingAnyOf[1] && incomingAnyOf[1][\"type\"] === \"null\") {\n genAISchema[\"nullable\"] = true;\n _jsonSchema = incomingAnyOf[0];\n }\n }\n\n if (_jsonSchema[\"type\"] && Array.isArray(_jsonSchema[\"type\"])) {\n flattenTypeArrayToAnyOf(_jsonSchema[\"type\"], genAISchema);\n }\n\n for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) {\n // Skip if the fieldValue is undefined or null.\n if (fieldValue == null) {\n continue;\n }\n\n if (fieldName == \"type\") {\n if (fieldValue === \"null\") {\n throw new Error(\n \"type: null can not be the only possible type for the field.\"\n );\n }\n if (Array.isArray(fieldValue)) {\n // we have already handled the type field with array of types in the\n // beginning of this function.\n continue;\n }\n const upperCaseValue = fieldValue.toUpperCase();\n genAISchema[\"type\"] = Object.values(Type).includes(upperCaseValue)\n ? upperCaseValue\n : Type.TYPE_UNSPECIFIED;\n } else if (schemaFieldNames.includes(fieldName)) {\n genAISchema[fieldName] = processJsonSchema(fieldValue);\n } else if (listSchemaFieldNames.includes(fieldName)) {\n const listSchemaFieldValue = [];\n for (const item of fieldValue) {\n if (item[\"type\"] == \"null\") {\n genAISchema[\"nullable\"] = true;\n continue;\n }\n listSchemaFieldValue.push(processJsonSchema(item));\n }\n genAISchema[fieldName] = listSchemaFieldValue;\n } else if (dictSchemaFieldNames.includes(fieldName)) {\n const dictSchemaFieldValue = {};\n for (const [key, value] of Object.entries(fieldValue)) {\n dictSchemaFieldValue[key] = processJsonSchema(value);\n }\n genAISchema[fieldName] = dictSchemaFieldValue;\n } else {\n // additionalProperties is not included in JSONSchema, skipping it.\n if (fieldName === \"additionalProperties\") {\n continue;\n }\n genAISchema[fieldName] = fieldValue;\n }\n }\n return genAISchema;\n}\n\n/**\n * Transform a tool object\n * @param {Object} tool - The tool object to transform\n * @returns {Object} - The transformed tool object\n */\nexport function tTool(tool: any): any {\n if (tool.functionDeclarations) {\n for (const functionDeclaration of tool.functionDeclarations) {\n if (functionDeclaration.parameters) {\n if (!Object.keys(functionDeclaration.parameters).includes(\"$schema\")) {\n functionDeclaration.parameters = processJsonSchema(\n functionDeclaration.parameters\n );\n } else {\n if (!functionDeclaration.parametersJsonSchema) {\n functionDeclaration.parametersJsonSchema =\n functionDeclaration.parameters;\n delete functionDeclaration.parameters;\n }\n }\n }\n if (functionDeclaration.response) {\n if (!Object.keys(functionDeclaration.response).includes(\"$schema\")) {\n functionDeclaration.response = processJsonSchema(\n functionDeclaration.response\n );\n } else {\n if (!functionDeclaration.responseJsonSchema) {\n functionDeclaration.responseJsonSchema =\n functionDeclaration.response;\n delete functionDeclaration.response;\n }\n }\n }\n }\n }\n return tool;\n}\n\nexport function buildRequestBody(\n request: UnifiedChatRequest\n): Record {\n const tools = [];\n const functionDeclarations = request.tools\n ?.filter((tool) => tool.function.name !== \"web_search\")\n ?.map((tool) => {\n return {\n name: tool.function.name,\n description: tool.function.description,\n parametersJsonSchema: tool.function.parameters,\n };\n });\n if (functionDeclarations?.length) {\n tools.push(\n tTool({\n functionDeclarations,\n })\n );\n }\n const webSearch = request.tools?.find(\n (tool) => tool.function.name === \"web_search\"\n );\n if (webSearch) {\n tools.push({\n googleSearch: {},\n });\n }\n\n const contents = request.messages.map((message: UnifiedMessage) => {\n let role: \"user\" | \"model\";\n if (message.role === \"assistant\") {\n role = \"model\";\n } else if ([\"user\", \"system\", \"tool\"].includes(message.role)) {\n role = \"user\";\n } else {\n role = \"user\"; // Default to user if role is not recognized\n }\n const parts = [];\n if (typeof message.content === \"string\") {\n parts.push({\n text: message.content,\n });\n } else if (Array.isArray(message.content)) {\n parts.push(\n ...message.content.map((content) => {\n if (content.type === \"text\") {\n return {\n text: content.text || \"\",\n };\n }\n if (content.type === \"image_url\") {\n if (content.image_url.url.startsWith(\"http\")) {\n return {\n file_data: {\n mime_type: content.media_type,\n file_uri: content.image_url.url,\n },\n };\n } else {\n return {\n inlineData: {\n mime_type: content.media_type,\n data: content.image_url.url,\n },\n };\n }\n }\n })\n );\n }\n\n if (Array.isArray(message.tool_calls)) {\n parts.push(\n ...message.tool_calls.map((toolCall) => {\n return {\n functionCall: {\n id:\n toolCall.id ||\n `tool_${Math.random().toString(36).substring(2, 15)}`,\n name: toolCall.function.name,\n args: JSON.parse(toolCall.function.arguments || \"{}\"),\n },\n };\n })\n );\n }\n return {\n role,\n parts,\n };\n });\n\n const body = {\n contents,\n tools: tools.length ? tools : undefined,\n };\n\n if (request.tool_choice) {\n const toolConfig = {\n functionCallingConfig: {},\n };\n if (request.tool_choice === \"auto\") {\n toolConfig.functionCallingConfig.mode = \"auto\";\n } else if (request.tool_choice === \"none\") {\n toolConfig.functionCallingConfig.mode = \"none\";\n } else if (request.tool_choice === \"required\") {\n toolConfig.functionCallingConfig.mode = \"any\";\n } else if (request.tool_choice?.function?.name) {\n toolConfig.functionCallingConfig.mode = \"any\";\n toolConfig.functionCallingConfig.allowedFunctionNames = [\n request.tool_choice?.function?.name,\n ];\n }\n body.toolConfig = toolConfig;\n }\n\n return body;\n}\n\nexport function transformRequestOut(\n request: Record\n): UnifiedChatRequest {\n const contents: ContentListUnion = request.contents;\n const tools: ToolListUnion = request.tools;\n const model: string = request.model;\n const max_tokens: number | undefined = request.max_tokens;\n const temperature: number | undefined = request.temperature;\n const stream: boolean | undefined = request.stream;\n const tool_choice: \"auto\" | \"none\" | string | undefined = request.tool_choice;\n\n const unifiedChatRequest: UnifiedChatRequest = {\n messages: [],\n model,\n max_tokens,\n temperature,\n stream,\n tool_choice,\n };\n\n if (Array.isArray(contents)) {\n contents.forEach((content) => {\n if (typeof content === \"string\") {\n unifiedChatRequest.messages.push({\n role: \"user\",\n content,\n });\n } else if (typeof (content as Part).text === \"string\") {\n unifiedChatRequest.messages.push({\n role: \"user\",\n content: (content as Part).text || null,\n });\n } else if ((content as Content).role === \"user\") {\n unifiedChatRequest.messages.push({\n role: \"user\",\n content:\n (content as Content)?.parts?.map((part: Part) => ({\n type: \"text\",\n text: part.text || \"\",\n })) || [],\n });\n } else if ((content as Content).role === \"model\") {\n unifiedChatRequest.messages.push({\n role: \"assistant\",\n content:\n (content as Content)?.parts?.map((part: Part) => ({\n type: \"text\",\n text: part.text || \"\",\n })) || [],\n });\n }\n });\n }\n\n if (Array.isArray(tools)) {\n unifiedChatRequest.tools = [];\n tools.forEach((tool) => {\n if (Array.isArray(tool.functionDeclarations)) {\n tool.functionDeclarations.forEach((tool) => {\n unifiedChatRequest.tools!.push({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n },\n });\n });\n }\n });\n }\n\n return unifiedChatRequest;\n}\n\nexport async function transformResponseOut(\n response: Response,\n providerName: string,\n logger?: any\n): Promise {\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse: any = await response.json();\n const tool_calls =\n jsonResponse.candidates[0].content?.parts\n ?.filter((part: Part) => part.functionCall)\n ?.map((part: Part) => ({\n id:\n part.functionCall?.id ||\n `tool_${Math.random().toString(36).substring(2, 15)}`,\n type: \"function\",\n function: {\n name: part.functionCall?.name,\n arguments: JSON.stringify(part.functionCall?.args || {}),\n },\n })) || [];\n const res = {\n id: jsonResponse.responseId,\n choices: [\n {\n finish_reason:\n (\n jsonResponse.candidates[0].finishReason as string\n )?.toLowerCase() || null,\n index: 0,\n message: {\n content:\n jsonResponse.candidates[0].content?.parts\n ?.filter((part: Part) => part.text)\n ?.map((part: Part) => part.text)\n ?.join(\"\\n\") || \"\",\n role: \"assistant\",\n tool_calls: tool_calls.length > 0 ? tool_calls : undefined,\n },\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n model: jsonResponse.modelVersion,\n object: \"chat.completion\",\n usage: {\n completion_tokens: jsonResponse.usageMetadata.candidatesTokenCount,\n prompt_tokens: jsonResponse.usageMetadata.promptTokenCount,\n cached_content_token_count:\n jsonResponse.usageMetadata.cachedContentTokenCount || null,\n total_tokens: jsonResponse.usageMetadata.totalTokenCount,\n },\n };\n return new Response(JSON.stringify(res), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n\n const processLine = (\n line: string,\n controller: ReadableStreamDefaultController\n ) => {\n if (line.startsWith(\"data: \")) {\n const chunkStr = line.slice(6).trim();\n if (chunkStr) {\n logger?.debug({ chunkStr }, `${providerName} chunk:`);\n try {\n const chunk = JSON.parse(chunkStr);\n\n // Check if chunk has valid structure\n if (!chunk.candidates || !chunk.candidates[0]) {\n log(`Invalid chunk structure:`, chunkStr);\n return;\n }\n\n const candidate = chunk.candidates[0];\n const parts = candidate.content?.parts || [];\n\n const tool_calls = parts\n .filter((part: Part) => part.functionCall)\n .map((part: Part) => ({\n id:\n part.functionCall?.id ||\n `tool_${Math.random().toString(36).substring(2, 15)}`,\n type: \"function\",\n function: {\n name: part.functionCall?.name,\n arguments: JSON.stringify(part.functionCall?.args || {}),\n },\n }));\n\n const textContent = parts\n .filter((part: Part) => part.text)\n .map((part: Part) => part.text)\n .join(\"\\n\");\n\n const res = {\n choices: [\n {\n delta: {\n role: \"assistant\",\n content: textContent || \"\",\n tool_calls: tool_calls.length > 0 ? tool_calls : undefined,\n },\n finish_reason: candidate.finishReason?.toLowerCase() || null,\n index: candidate.index || (tool_calls.length > 0 ? 1 : 0),\n logprobs: null,\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n id: chunk.responseId || \"\",\n model: chunk.modelVersion || \"\",\n object: \"chat.completion.chunk\",\n system_fingerprint: \"fp_a49d71b8a1\",\n usage: {\n completion_tokens:\n chunk.usageMetadata?.candidatesTokenCount || 0,\n prompt_tokens: chunk.usageMetadata?.promptTokenCount || 0,\n cached_content_token_count:\n chunk.usageMetadata?.cachedContentTokenCount || null,\n total_tokens: chunk.usageMetadata?.totalTokenCount || 0,\n },\n };\n if (candidate?.groundingMetadata?.groundingChunks?.length) {\n res.choices[0].delta.annotations =\n candidate.groundingMetadata.groundingChunks.map(\n (groundingChunk, index) => {\n const support =\n candidate?.groundingMetadata?.groundingSupports?.filter(\n (item) => item.groundingChunkIndices?.includes(index)\n );\n return {\n type: \"url_citation\",\n url_citation: {\n url: groundingChunk?.web?.uri || \"\",\n title: groundingChunk?.web?.title || \"\",\n content: support?.[0]?.segment?.text || \"\",\n start_index: support?.[0]?.segment?.startIndex || 0,\n end_index: support?.[0]?.segment?.endIndex || 0,\n },\n };\n }\n );\n }\n controller.enqueue(\n encoder.encode(`data: ${JSON.stringify(res)}\\n\\n`)\n );\n } catch (error: any) {\n logger?.error(\n `Error parsing ${providerName} stream chunk`,\n chunkStr,\n error.message\n );\n }\n }\n }\n };\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n let buffer = \"\";\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n if (buffer) {\n processLine(buffer, controller);\n }\n break;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n processLine(line, controller);\n }\n }\n } catch (error) {\n controller.error(error);\n } finally {\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n }\n return response;\n}\n", "import { LLMProvider, UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer } from \"../types/transformer\";\nimport {\n buildRequestBody,\n transformRequestOut,\n transformResponseOut,\n} from \"../utils/gemini.util\";\n\nexport class GeminiTransformer implements Transformer {\n name = \"gemini\";\n\n endPoint = \"/v1beta/models/:modelAndAction\";\n\n async transformRequestIn(\n request: UnifiedChatRequest,\n provider: LLMProvider\n ): Promise> {\n return {\n body: buildRequestBody(request),\n config: {\n url: new URL(\n `./${request.model}:${\n request.stream ? \"streamGenerateContent?alt=sse\" : \"generateContent\"\n }`,\n provider.baseUrl\n ),\n headers: {\n \"x-goog-api-key\": provider.apiKey,\n Authorization: undefined,\n },\n },\n };\n }\n\n transformRequestOut = transformRequestOut;\n\n async transformResponseOut(response: Response): Promise {\n return transformResponseOut(response, this.name, this.logger);\n }\n}\n", "import { LLMProvider, UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer } from \"../types/transformer\";\nimport {\n buildRequestBody,\n transformRequestOut,\n transformResponseOut,\n} from \"../utils/gemini.util\";\n\nasync function getAccessToken(): Promise {\n try {\n const { GoogleAuth } = await import('google-auth-library');\n\n const auth = new GoogleAuth({\n scopes: ['https://www.googleapis.com/auth/cloud-platform']\n });\n\n const client = await auth.getClient();\n const accessToken = await client.getAccessToken();\n return accessToken.token || '';\n } catch (error) {\n console.error('Error getting access token:', error);\n throw new Error('Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:\\n' +\n '1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file\\n' +\n '2. Run \"gcloud auth application-default login\"\\n' +\n '3. Use Google Cloud environment with default service account');\n }\n}\n\nexport class VertexGeminiTransformer implements Transformer {\n name = \"vertex-gemini\";\n\n async transformRequestIn(\n request: UnifiedChatRequest,\n provider: LLMProvider\n ): Promise> {\n let projectId = process.env.GOOGLE_CLOUD_PROJECT;\n const location = process.env.GOOGLE_CLOUD_LOCATION || 'us-central1';\n\n if (!projectId && process.env.GOOGLE_APPLICATION_CREDENTIALS) {\n try {\n const fs = await import('fs');\n const keyContent = fs.readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS, 'utf8');\n const credentials = JSON.parse(keyContent);\n if (credentials && credentials.project_id) {\n projectId = credentials.project_id;\n }\n } catch (error) {\n console.error('Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:', error);\n }\n }\n\n if (!projectId) {\n throw new Error('Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.');\n }\n\n const accessToken = await getAccessToken();\n return {\n body: buildRequestBody(request),\n config: {\n url: new URL(\n `./v1beta1/projects/${projectId}/locations/${location}/publishers/google/models/${request.model}:${request.stream ? \"streamGenerateContent\" : \"generateContent\"}`,\n provider.baseUrl.endsWith('/') ? provider.baseUrl : provider.baseUrl + '/' || `https://${location}-aiplatform.googleapis.com`\n ),\n headers: {\n \"Authorization\": `Bearer ${accessToken}`,\n \"x-goog-api-key\": undefined,\n },\n },\n };\n }\n\n transformRequestOut = transformRequestOut;\n\n async transformResponseOut(response: Response): Promise {\n return transformResponseOut(response, this.name);\n }\n}\n", "import { UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer } from \"../types/transformer\";\n\nexport class DeepseekTransformer implements Transformer {\n name = \"deepseek\";\n\n async transformRequestIn(request: UnifiedChatRequest): Promise {\n if (request.max_tokens && request.max_tokens > 8192) {\n request.max_tokens = 8192; // DeepSeek has a max token limit of 8192\n }\n return request;\n }\n\n async transformResponseOut(response: Response): Promise {\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse = await response.json();\n // Handle non-streaming response if needed\n return new Response(JSON.stringify(jsonResponse), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n let reasoningContent = \"\";\n let isReasoningComplete = false;\n let buffer = \"\"; // \u7528\u4E8E\u7F13\u51B2\u4E0D\u5B8C\u6574\u7684\u6570\u636E\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n const processBuffer = (\n buffer: string,\n controller: ReadableStreamDefaultController,\n encoder: typeof TextEncoder\n ) => {\n const lines = buffer.split(\"\\n\");\n for (const line of lines) {\n if (line.trim()) {\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n };\n\n const processLine = (\n line: string,\n context: {\n controller: ReadableStreamDefaultController;\n encoder: typeof TextEncoder;\n reasoningContent: () => string;\n appendReasoningContent: (content: string) => void;\n isReasoningComplete: () => boolean;\n setReasoningComplete: (val: boolean) => void;\n }\n ) => {\n const { controller, encoder } = context;\n\n if (\n line.startsWith(\"data: \") &&\n line.trim() !== \"data: [DONE]\"\n ) {\n try {\n const data = JSON.parse(line.slice(6));\n\n // Extract reasoning_content from delta\n if (data.choices?.[0]?.delta?.reasoning_content) {\n context.appendReasoningContent(\n data.choices[0].delta.reasoning_content\n );\n const thinkingChunk = {\n ...data,\n choices: [\n {\n ...data.choices[0],\n delta: {\n ...data.choices[0].delta,\n thinking: {\n content: data.choices[0].delta.reasoning_content,\n },\n },\n },\n ],\n };\n delete thinkingChunk.choices[0].delta.reasoning_content;\n const thinkingLine = `data: ${JSON.stringify(\n thinkingChunk\n )}\\n\\n`;\n controller.enqueue(encoder.encode(thinkingLine));\n return;\n }\n\n // Check if reasoning is complete (when delta has content but no reasoning_content)\n if (\n data.choices?.[0]?.delta?.content &&\n context.reasoningContent() &&\n !context.isReasoningComplete()\n ) {\n context.setReasoningComplete(true);\n const signature = Date.now().toString();\n\n // Create a new chunk with thinking block\n const thinkingChunk = {\n ...data,\n choices: [\n {\n ...data.choices[0],\n delta: {\n ...data.choices[0].delta,\n content: null,\n thinking: {\n content: context.reasoningContent(),\n signature: signature,\n },\n },\n },\n ],\n };\n delete thinkingChunk.choices[0].delta.reasoning_content;\n // Send the thinking chunk\n const thinkingLine = `data: ${JSON.stringify(\n thinkingChunk\n )}\\n\\n`;\n controller.enqueue(encoder.encode(thinkingLine));\n }\n\n if (data.choices[0]?.delta?.reasoning_content) {\n delete data.choices[0].delta.reasoning_content;\n }\n\n // Send the modified chunk\n if (\n data.choices?.[0]?.delta &&\n Object.keys(data.choices[0].delta).length > 0\n ) {\n if (context.isReasoningComplete()) {\n data.choices[0].index++;\n }\n const modifiedLine = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n }\n } catch (e) {\n // If JSON parsing fails, pass through the original line\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n } else {\n // Pass through non-data lines (like [DONE])\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5269\u4F59\u7684\u6570\u636E\n if (buffer.trim()) {\n processBuffer(buffer, controller, encoder);\n }\n break;\n }\n\n const chunk = decoder.decode(value, { stream: true });\n buffer += chunk;\n\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5B8C\u6574\u7684\u6570\u636E\u884C\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\"; // \u6700\u540E\u4E00\u884C\u53EF\u80FD\u4E0D\u5B8C\u6574\uFF0C\u4FDD\u7559\u5728\u7F13\u51B2\u533A\n\n for (const line of lines) {\n if (!line.trim()) continue;\n\n try {\n processLine(line, {\n controller,\n encoder,\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) =>\n (reasoningContent += content),\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) => (isReasoningComplete = val),\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n } catch (error) {\n console.error(\"Stream error:\", error);\n controller.error(error);\n } finally {\n try {\n reader.releaseLock();\n } catch (e) {\n console.error(\"Error releasing reader lock:\", e);\n }\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: {\n \"Content-Type\": response.headers.get(\"Content-Type\") || \"text/plain\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n }\n\n return response;\n }\n}\n", "import { UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer } from \"../types/transformer\";\n\nexport class TooluseTransformer implements Transformer {\n name = \"tooluse\";\n\n transformRequestIn(request: UnifiedChatRequest): UnifiedChatRequest {\n request.messages.push({\n role: \"system\",\n content: `Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the \\`ExitTool\\` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.`,\n });\n if (request.tools?.length) {\n request.tool_choice = \"required\";\n request.tools.push({\n type: \"function\",\n function: {\n name: \"ExitTool\",\n description: `Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.\nIMPORTANT: Before using this tool, ensure that none of the available tools are applicable to the current task. You must evaluate all available options \u2014 only if no suitable tool can help you complete the task should you use ExitTool to terminate tool mode.\nExamples:\n1. Task: \"Use a tool to summarize this document\" \u2014 Do not use ExitTool if a summarization tool is available.\n2. Task: \"What\u2019s the weather today?\" \u2014 If no tool is available to answer, use ExitTool after reasoning that none can fulfill the task.`,\n parameters: {\n type: \"object\",\n properties: {\n response: {\n type: \"string\",\n description:\n \"Your response will be forwarded to the user exactly as returned \u2014 the tool will not modify or post-process it in any way.\",\n },\n },\n required: [\"response\"],\n },\n },\n });\n }\n return request;\n }\n\n async transformResponseOut(response: Response): Promise {\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse = await response.json();\n if (\n jsonResponse?.choices?.[0]?.message.tool_calls?.length &&\n jsonResponse?.choices?.[0]?.message.tool_calls[0]?.function?.name ===\n \"ExitTool\"\n ) {\n const toolCall = jsonResponse?.choices[0]?.message.tool_calls[0];\n const toolArguments = JSON.parse(toolCall.function.arguments || \"{}\");\n jsonResponse.choices[0].message.content = toolArguments.response || \"\";\n delete jsonResponse.choices[0].message.tool_calls;\n }\n\n // Handle non-streaming response if needed\n return new Response(JSON.stringify(jsonResponse), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n let exitToolIndex = -1;\n let exitToolResponse = \"\";\n let buffer = \"\"; // \u7528\u4E8E\u7F13\u51B2\u4E0D\u5B8C\u6574\u7684\u6570\u636E\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n\n const processBuffer = (\n buffer: string,\n controller: ReadableStreamDefaultController,\n encoder: TextEncoder\n ) => {\n const lines = buffer.split(\"\\n\");\n for (const line of lines) {\n if (line.trim()) {\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n };\n\n const processLine = (\n line: string,\n context: {\n controller: ReadableStreamDefaultController;\n encoder: TextEncoder;\n exitToolIndex: () => number;\n setExitToolIndex: (val: number) => void;\n exitToolResponse: () => string;\n appendExitToolResponse: (content: string) => void;\n }\n ) => {\n const {\n controller,\n encoder,\n exitToolIndex,\n setExitToolIndex,\n appendExitToolResponse,\n } = context;\n\n if (\n line.startsWith(\"data: \") &&\n line.trim() !== \"data: [DONE]\"\n ) {\n try {\n const data = JSON.parse(line.slice(6));\n\n if (data.choices[0]?.delta?.tool_calls?.length) {\n const toolCall = data.choices[0].delta.tool_calls[0];\n\n if (toolCall.function?.name === \"ExitTool\") {\n setExitToolIndex(toolCall.index);\n return;\n } else if (\n exitToolIndex() > -1 &&\n toolCall.index === exitToolIndex() &&\n toolCall.function.arguments\n ) {\n appendExitToolResponse(toolCall.function.arguments);\n try {\n const response = JSON.parse(context.exitToolResponse());\n data.choices = [\n {\n delta: {\n role: \"assistant\",\n content: response.response || \"\",\n },\n },\n ];\n const modifiedLine = `data: ${JSON.stringify(\n data\n )}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n } catch (e) {}\n return;\n }\n }\n\n if (\n data.choices?.[0]?.delta &&\n Object.keys(data.choices[0].delta).length > 0\n ) {\n const modifiedLine = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n }\n } catch (e) {\n // If JSON parsing fails, pass through the original line\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n } else {\n // Pass through non-data lines (like [DONE])\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n if (buffer.trim()) {\n processBuffer(buffer, controller, encoder);\n }\n break;\n }\n const chunk = decoder.decode(value, { stream: true });\n buffer += chunk;\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n for (const line of lines) {\n if (!line.trim()) continue;\n try {\n processLine(line, {\n controller,\n encoder,\n exitToolIndex: () => exitToolIndex,\n setExitToolIndex: (val) => (exitToolIndex = val),\n exitToolResponse: () => exitToolResponse,\n appendExitToolResponse: (content) =>\n (exitToolResponse += content),\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n } catch (error) {\n console.error(\"Stream error:\", error);\n controller.error(error);\n } finally {\n try {\n reader.releaseLock();\n } catch (e) {\n console.error(\"Error releasing reader lock:\", e);\n }\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n }\n\n return response;\n }\n}\n", "import { UnifiedChatRequest } from \"@/types/llm\";\nimport { Transformer, TransformerOptions } from \"../types/transformer\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nexport class OpenrouterTransformer implements Transformer {\n static TransformerName = \"openrouter\";\n\n constructor(private readonly options?: TransformerOptions) {}\n\n async transformRequestIn(\n request: UnifiedChatRequest\n ): Promise {\n if (!request.model.includes(\"claude\")) {\n request.messages.forEach((msg) => {\n if (Array.isArray(msg.content)) {\n msg.content.forEach((item: any) => {\n if (item.cache_control) {\n delete item.cache_control;\n }\n if (item.type === \"image_url\") {\n if (!item.image_url.url.startsWith(\"http\")) {\n item.image_url.url = `data:${item.media_type};base64,${item.image_url.url}`;\n }\n delete item.media_type;\n }\n });\n } else if (msg.cache_control) {\n delete msg.cache_control;\n }\n });\n } else {\n request.messages.forEach((msg) => {\n if (Array.isArray(msg.content)) {\n msg.content.forEach((item: any) => {\n if (item.type === \"image_url\") {\n if (!item.image_url.url.startsWith(\"http\")) {\n item.image_url.url = `data:${item.media_type};base64,${item.image_url.url}`;\n }\n delete item.media_type;\n }\n });\n }\n });\n }\n Object.assign(request, this.options || {});\n return request;\n }\n\n async transformResponseOut(response: Response): Promise {\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse = await response.json();\n return new Response(JSON.stringify(jsonResponse), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n\n let hasTextContent = false;\n let reasoningContent = \"\";\n let isReasoningComplete = false;\n let hasToolCall = false;\n let buffer = \"\"; // \u7528\u4E8E\u7F13\u51B2\u4E0D\u5B8C\u6574\u7684\u6570\u636E\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n const processBuffer = (\n buffer: string,\n controller: ReadableStreamDefaultController,\n encoder: TextEncoder\n ) => {\n const lines = buffer.split(\"\\n\");\n for (const line of lines) {\n if (line.trim()) {\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n };\n\n const processLine = (\n line: string,\n context: {\n controller: ReadableStreamDefaultController;\n encoder: TextEncoder;\n hasTextContent: () => boolean;\n setHasTextContent: (val: boolean) => void;\n reasoningContent: () => string;\n appendReasoningContent: (content: string) => void;\n isReasoningComplete: () => boolean;\n setReasoningComplete: (val: boolean) => void;\n }\n ) => {\n const { controller, encoder } = context;\n\n if (line.startsWith(\"data: \") && line.trim() !== \"data: [DONE]\") {\n const jsonStr = line.slice(6);\n try {\n const data = JSON.parse(jsonStr);\n if (data.usage) {\n this.logger?.debug(\n { usage: data.usage, hasToolCall },\n \"usage\"\n );\n data.choices[0].finish_reason = hasToolCall\n ? \"tool_calls\"\n : \"stop\";\n }\n\n if (data.choices?.[0]?.finish_reason === \"error\") {\n controller.enqueue(\n encoder.encode(\n `data: ${JSON.stringify({\n error: data.choices?.[0].error,\n })}\\n\\n`\n )\n );\n }\n\n if (\n data.choices?.[0]?.delta?.content &&\n !context.hasTextContent()\n ) {\n context.setHasTextContent(true);\n }\n\n // Extract reasoning_content from delta\n if (data.choices?.[0]?.delta?.reasoning) {\n context.appendReasoningContent(\n data.choices[0].delta.reasoning\n );\n const thinkingChunk = {\n ...data,\n choices: [\n {\n ...data.choices?.[0],\n delta: {\n ...data.choices[0].delta,\n thinking: {\n content: data.choices[0].delta.reasoning,\n },\n },\n },\n ],\n };\n if (thinkingChunk.choices?.[0]?.delta) {\n delete thinkingChunk.choices[0].delta.reasoning;\n }\n const thinkingLine = `data: ${JSON.stringify(\n thinkingChunk\n )}\\n\\n`;\n controller.enqueue(encoder.encode(thinkingLine));\n return;\n }\n\n // Check if reasoning is complete\n if (\n data.choices?.[0]?.delta?.content &&\n context.reasoningContent() &&\n !context.isReasoningComplete()\n ) {\n context.setReasoningComplete(true);\n const signature = Date.now().toString();\n\n const thinkingChunk = {\n ...data,\n choices: [\n {\n ...data.choices?.[0],\n delta: {\n ...data.choices[0].delta,\n content: null,\n thinking: {\n content: context.reasoningContent(),\n signature: signature,\n },\n },\n },\n ],\n };\n if (thinkingChunk.choices?.[0]?.delta) {\n delete thinkingChunk.choices[0].delta.reasoning;\n }\n const thinkingLine = `data: ${JSON.stringify(\n thinkingChunk\n )}\\n\\n`;\n controller.enqueue(encoder.encode(thinkingLine));\n }\n\n if (data.choices?.[0]?.delta?.reasoning) {\n delete data.choices[0].delta.reasoning;\n }\n if (\n data.choices?.[0]?.delta?.tool_calls?.length &&\n !Number.isNaN(\n parseInt(data.choices?.[0]?.delta?.tool_calls[0].id, 10)\n )\n ) {\n data.choices?.[0]?.delta?.tool_calls.forEach((tool: any) => {\n tool.id = `call_${uuidv4()}`;\n });\n }\n\n if (\n data.choices?.[0]?.delta?.tool_calls?.length &&\n !hasToolCall\n ) {\n hasToolCall = true;\n }\n\n if (\n data.choices?.[0]?.delta?.tool_calls?.length &&\n context.hasTextContent()\n ) {\n if (typeof data.choices[0].index === \"number\") {\n data.choices[0].index += 1;\n } else {\n data.choices[0].index = 1;\n }\n }\n\n const modifiedLine = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n } catch (e) {\n // \u5982\u679CJSON\u89E3\u6790\u5931\u8D25\uFF0C\u53EF\u80FD\u662F\u6570\u636E\u4E0D\u5B8C\u6574\uFF0C\u5C06\u539F\u59CB\u884C\u4F20\u9012\u4E0B\u53BB\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n } else {\n // Pass through non-data lines (like [DONE])\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5269\u4F59\u7684\u6570\u636E\n if (buffer.trim()) {\n processBuffer(buffer, controller, encoder);\n }\n break;\n }\n\n // \u68C0\u67E5value\u662F\u5426\u6709\u6548\n if (!value || value.length === 0) {\n continue;\n }\n\n let chunk;\n try {\n chunk = decoder.decode(value, { stream: true });\n } catch (decodeError) {\n console.warn(\"Failed to decode chunk\", decodeError);\n continue;\n }\n\n if (chunk.length === 0) {\n continue;\n }\n\n buffer += chunk;\n\n // \u5982\u679C\u7F13\u51B2\u533A\u8FC7\u5927\uFF0C\u8FDB\u884C\u5904\u7406\u907F\u514D\u5185\u5B58\u6CC4\u6F0F\n if (buffer.length > 1000000) {\n // 1MB \u9650\u5236\n console.warn(\n \"Buffer size exceeds limit, processing partial data\"\n );\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.trim()) {\n try {\n processLine(line, {\n controller,\n encoder,\n hasTextContent: () => hasTextContent,\n setHasTextContent: (val) => (hasTextContent = val),\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) =>\n (reasoningContent += content),\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) =>\n (isReasoningComplete = val),\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n continue;\n }\n\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5B8C\u6574\u7684\u6570\u636E\u884C\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\"; // \u6700\u540E\u4E00\u884C\u53EF\u80FD\u4E0D\u5B8C\u6574\uFF0C\u4FDD\u7559\u5728\u7F13\u51B2\u533A\n\n for (const line of lines) {\n if (!line.trim()) continue;\n\n try {\n processLine(line, {\n controller,\n encoder,\n hasTextContent: () => hasTextContent,\n setHasTextContent: (val) => (hasTextContent = val),\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) =>\n (reasoningContent += content),\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) => (isReasoningComplete = val),\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n } catch (error) {\n console.error(\"Stream error:\", error);\n controller.error(error);\n } finally {\n try {\n reader.releaseLock();\n } catch (e) {\n console.error(\"Error releasing reader lock:\", e);\n }\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n }\n\n return response;\n }\n}\n", "import { UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer, TransformerOptions } from \"../types/transformer\";\n\nexport class MaxTokenTransformer implements Transformer {\n static TransformerName = \"maxtoken\";\n max_tokens: number;\n\n constructor(private readonly options?: TransformerOptions) {\n this.max_tokens = this.options?.max_tokens;\n }\n\n async transformRequestIn(request: UnifiedChatRequest): Promise {\n if (request.max_tokens && request.max_tokens > this.max_tokens) {\n request.max_tokens = this.max_tokens;\n }\n return request;\n }\n}\n", "import { MessageContent, TextContent, UnifiedChatRequest } from \"@/types/llm\";\nimport { Transformer } from \"../types/transformer\";\nimport { v4 as uuidv4 } from \"uuid\"\n\nexport class GroqTransformer implements Transformer {\n name = \"groq\";\n\n async transformRequestIn(request: UnifiedChatRequest): Promise {\n request.messages.forEach(msg => {\n if (Array.isArray(msg.content)) {\n (msg.content as MessageContent[]).forEach((item) => {\n if ((item as TextContent).cache_control) {\n delete (item as TextContent).cache_control;\n }\n });\n } else if (msg.cache_control) {\n delete msg.cache_control;\n }\n })\n if (Array.isArray(request.tools)) {\n request.tools.forEach(tool => {\n delete tool.function.parameters.$schema;\n })\n }\n return request\n }\n\n async transformResponseOut(response: Response): Promise {\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse = await response.json();\n return new Response(JSON.stringify(jsonResponse), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n\n let hasTextContent = false;\n let reasoningContent = \"\";\n let isReasoningComplete = false;\n let buffer = \"\"; // \u7528\u4E8E\u7F13\u51B2\u4E0D\u5B8C\u6574\u7684\u6570\u636E\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n const processBuffer = (buffer: string, controller: ReadableStreamDefaultController, encoder: InstanceType) => {\n const lines = buffer.split(\"\\n\");\n for (const line of lines) {\n if (line.trim()) {\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n };\n\n const processLine = (line: string, context: {\n controller: ReadableStreamDefaultController;\n encoder: typeof TextEncoder;\n hasTextContent: () => boolean;\n setHasTextContent: (val: boolean) => void;\n reasoningContent: () => string;\n appendReasoningContent: (content: string) => void;\n isReasoningComplete: () => boolean;\n setReasoningComplete: (val: boolean) => void;\n }) => {\n const { controller, encoder } = context;\n\n if (line.startsWith(\"data: \") && line.trim() !== \"data: [DONE]\") {\n const jsonStr = line.slice(6);\n try {\n const data = JSON.parse(jsonStr);\n if (data.error) {\n throw new Error(JSON.stringify(data));\n }\n\n if (data.choices?.[0]?.delta?.content && !context.hasTextContent()) {\n context.setHasTextContent(true);\n }\n\n if (\n data.choices?.[0]?.delta?.tool_calls?.length\n ) {\n data.choices?.[0]?.delta?.tool_calls.forEach((tool: any) => {\n tool.id = `call_${uuidv4()}`;\n })\n }\n\n if (\n data.choices?.[0]?.delta?.tool_calls?.length &&\n context.hasTextContent()\n ) {\n if (typeof data.choices[0].index === 'number') {\n data.choices[0].index += 1;\n } else {\n data.choices[0].index = 1;\n }\n }\n\n const modifiedLine = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n } catch (e) {\n // \u5982\u679CJSON\u89E3\u6790\u5931\u8D25\uFF0C\u53EF\u80FD\u662F\u6570\u636E\u4E0D\u5B8C\u6574\uFF0C\u5C06\u539F\u59CB\u884C\u4F20\u9012\u4E0B\u53BB\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n } else {\n // Pass through non-data lines (like [DONE])\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5269\u4F59\u7684\u6570\u636E\n if (buffer.trim()) {\n processBuffer(buffer, controller, encoder);\n }\n break;\n }\n\n // \u68C0\u67E5value\u662F\u5426\u6709\u6548\n if (!value || value.length === 0) {\n continue;\n }\n\n let chunk;\n try {\n chunk = decoder.decode(value, { stream: true });\n } catch (decodeError) {\n console.warn(\"Failed to decode chunk\", decodeError);\n continue;\n }\n\n if (chunk.length === 0) {\n continue;\n }\n\n buffer += chunk;\n\n // \u5982\u679C\u7F13\u51B2\u533A\u8FC7\u5927\uFF0C\u8FDB\u884C\u5904\u7406\u907F\u514D\u5185\u5B58\u6CC4\u6F0F\n if (buffer.length > 1000000) { // 1MB \u9650\u5236\n console.warn(\"Buffer size exceeds limit, processing partial data\");\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.trim()) {\n try {\n processLine(line, {\n controller,\n encoder,\n hasTextContent: () => hasTextContent,\n setHasTextContent: (val) => hasTextContent = val,\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) => reasoningContent += content,\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) => isReasoningComplete = val\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n continue;\n }\n\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5B8C\u6574\u7684\u6570\u636E\u884C\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\"; // \u6700\u540E\u4E00\u884C\u53EF\u80FD\u4E0D\u5B8C\u6574\uFF0C\u4FDD\u7559\u5728\u7F13\u51B2\u533A\n\n for (const line of lines) {\n if (!line.trim()) continue;\n\n try {\n processLine(line, {\n controller,\n encoder,\n hasTextContent: () => hasTextContent,\n setHasTextContent: (val) => hasTextContent = val,\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) => reasoningContent += content,\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) => isReasoningComplete = val\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n } catch (error) {\n console.error(\"Stream error:\", error);\n controller.error(error);\n } finally {\n try {\n reader.releaseLock();\n } catch (e) {\n console.error(\"Error releasing reader lock:\", e);\n }\n controller.close();\n }\n },\n\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n }\n\n return response;\n }\n}", "import { MessageContent, TextContent, UnifiedChatRequest } from \"@/types/llm\";\nimport { Transformer } from \"../types/transformer\";\n\nexport class CleancacheTransformer implements Transformer {\n name = \"cleancache\";\n\n async transformRequestIn(request: UnifiedChatRequest): Promise {\n if (Array.isArray(request.messages)) {\n request.messages.forEach((msg) => {\n if (Array.isArray(msg.content)) {\n (msg.content as MessageContent[]).forEach((item) => {\n if ((item as TextContent).cache_control) {\n delete (item as TextContent).cache_control;\n }\n });\n } else if (msg.cache_control) {\n delete msg.cache_control;\n }\n });\n }\n return request;\n }\n}\n", "import JSON5 from \"json5\";\nimport { jsonrepair } from \"jsonrepair\";\n\n/**\n * \u89E3\u6790\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u7684\u51FD\u6570\n * Parse tool call arguments function\n * \u5148\u5C1D\u8BD5\u6807\u51C6JSON\u89E3\u6790\uFF0C\u7136\u540EJSON5\u89E3\u6790\uFF0C\u6700\u540E\u4F7F\u7528jsonrepair\u8FDB\u884C\u5B89\u5168\u4FEE\u590D\n * First try standard JSON parsing, then JSON5 parsing, finally use jsonrepair for safe repair\n * \n * @param argsString - \u9700\u8981\u89E3\u6790\u7684\u53C2\u6570\u5B57\u7B26\u4E32 / Parameter string to parse\n * @returns \u89E3\u6790\u540E\u7684\u53C2\u6570\u5BF9\u8C61\u6216\u5B89\u5168\u7684\u7A7A\u5BF9\u8C61 / Parsed parameter object or safe empty object\n */\nexport function parseToolArguments(argsString: string, logger?: any): string {\n // Handle empty or null input\n if (!argsString || argsString.trim() === \"\" || argsString === \"{}\") {\n return \"{}\";\n }\n\n try {\n // First attempt: Standard JSON parsing\n JSON.parse(argsString);\n logger?.debug(`\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u6807\u51C6JSON\u89E3\u6790\u6210\u529F / Tool arguments standard JSON parsing successful`);\n return argsString;\n } catch (jsonError: any) {\n try {\n // Second attempt: JSON5 parsing for relaxed syntax\n const args = JSON5.parse(argsString);\n logger?.debug(`\u5DE5\u5177\u8C03\u7528\u53C2\u6570JSON5\u89E3\u6790\u6210\u529F / Tool arguments JSON5 parsing successful`);\n return JSON.stringify(args);\n } catch (json5Error: any) {\n try {\n // Third attempt: Safe JSON repair without code execution\n const repairedJson = jsonrepair(argsString);\n logger?.debug(`\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u5B89\u5168\u4FEE\u590D\u6210\u529F / Tool arguments safely repaired`);\n return repairedJson;\n } catch (repairError: any) {\n // All parsing attempts failed - log errors and return safe fallback\n logger?.error(\n `JSON\u89E3\u6790\u5931\u8D25 / JSON parsing failed: ${jsonError.message}. ` +\n `JSON5\u89E3\u6790\u5931\u8D25 / JSON5 parsing failed: ${json5Error.message}. ` +\n `JSON\u4FEE\u590D\u5931\u8D25 / JSON repair failed: ${repairError.message}. ` +\n `\u8F93\u5165\u6570\u636E / Input data: ${JSON.stringify(argsString)}`\n );\n \n // Return safe empty object as fallback instead of potentially malformed input\n logger?.debug(`\u8FD4\u56DE\u5B89\u5168\u7684\u7A7A\u5BF9\u8C61\u4F5C\u4E3A\u540E\u5907\u65B9\u6848 / Returning safe empty object as fallback`);\n return \"{}\";\n }\n }\n }\n}", "export class JSONRepairError extends Error {\n position: number\n\n constructor(message: string, position: number) {\n super(`${message} at position ${position}`)\n\n this.position = position\n }\n}\n", "const codeSpace = 0x20 // \" \"\nconst codeNewline = 0xa // \"\\n\"\nconst codeTab = 0x9 // \"\\t\"\nconst codeReturn = 0xd // \"\\r\"\nconst codeNonBreakingSpace = 0xa0\nconst codeEnQuad = 0x2000\nconst codeHairSpace = 0x200a\nconst codeNarrowNoBreakSpace = 0x202f\nconst codeMediumMathematicalSpace = 0x205f\nconst codeIdeographicSpace = 0x3000\n\nexport function isHex(char: string): boolean {\n return /^[0-9A-Fa-f]$/.test(char)\n}\n\nexport function isDigit(char: string): boolean {\n return char >= '0' && char <= '9'\n}\n\nexport function isValidStringCharacter(char: string): boolean {\n // note that the valid range is between \\u{0020} and \\u{10ffff},\n // but in JavaScript it is not possible to create a code point larger than\n // \\u{10ffff}, so there is no need to test for that here.\n return char >= '\\u0020'\n}\n\nexport function isDelimiter(char: string): boolean {\n return ',:[]/{}()\\n+'.includes(char)\n}\n\nexport function isFunctionNameCharStart(char: string) {\n return (\n (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || char === '_' || char === '$'\n )\n}\n\nexport function isFunctionNameChar(char: string) {\n return (\n (char >= 'a' && char <= 'z') ||\n (char >= 'A' && char <= 'Z') ||\n char === '_' ||\n char === '$' ||\n (char >= '0' && char <= '9')\n )\n}\n\n// matches \"https://\" and other schemas\nexport const regexUrlStart = /^(http|https|ftp|mailto|file|data|irc):\\/\\/$/\n\n// matches all valid URL characters EXCEPT \"[\", \"]\", and \",\", since that are important JSON delimiters\nexport const regexUrlChar = /^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/\n\nexport function isUnquotedStringDelimiter(char: string): boolean {\n return ',[]/{}\\n+'.includes(char)\n}\n\nexport function isStartOfValue(char: string): boolean {\n return isQuote(char) || regexStartOfValue.test(char)\n}\n\n// alpha, number, minus, or opening bracket or brace\nconst regexStartOfValue = /^[[{\\w-]$/\n\nexport function isControlCharacter(char: string) {\n return char === '\\n' || char === '\\r' || char === '\\t' || char === '\\b' || char === '\\f'\n}\n\nexport interface Text {\n charCodeAt: (index: number) => number\n}\n\n/**\n * Check if the given character is a whitespace character like space, tab, or\n * newline\n */\nexport function isWhitespace(text: Text, index: number): boolean {\n const code = text.charCodeAt(index)\n\n return code === codeSpace || code === codeNewline || code === codeTab || code === codeReturn\n}\n\n/**\n * Check if the given character is a whitespace character like space or tab,\n * but NOT a newline\n */\nexport function isWhitespaceExceptNewline(text: Text, index: number): boolean {\n const code = text.charCodeAt(index)\n\n return code === codeSpace || code === codeTab || code === codeReturn\n}\n\n/**\n * Check if the given character is a special whitespace character, some\n * unicode variant\n */\nexport function isSpecialWhitespace(text: Text, index: number): boolean {\n const code = text.charCodeAt(index)\n\n return (\n code === codeNonBreakingSpace ||\n (code >= codeEnQuad && code <= codeHairSpace) ||\n code === codeNarrowNoBreakSpace ||\n code === codeMediumMathematicalSpace ||\n code === codeIdeographicSpace\n )\n}\n\n/**\n * Test whether the given character is a quote or double quote character.\n * Also tests for special variants of quotes.\n */\nexport function isQuote(char: string): boolean {\n // the first check double quotes, since that occurs most often\n return isDoubleQuoteLike(char) || isSingleQuoteLike(char)\n}\n\n/**\n * Test whether the given character is a double quote character.\n * Also tests for special variants of double quotes.\n */\nexport function isDoubleQuoteLike(char: string): boolean {\n return char === '\"' || char === '\\u201c' || char === '\\u201d'\n}\n\n/**\n * Test whether the given character is a double quote character.\n * Does NOT test for special variants of double quotes.\n */\nexport function isDoubleQuote(char: string): boolean {\n return char === '\"'\n}\n\n/**\n * Test whether the given character is a single quote character.\n * Also tests for special variants of single quotes.\n */\nexport function isSingleQuoteLike(char: string): boolean {\n return (\n char === \"'\" || char === '\\u2018' || char === '\\u2019' || char === '\\u0060' || char === '\\u00b4'\n )\n}\n\n/**\n * Test whether the given character is a single quote character.\n * Does NOT test for special variants of single quotes.\n */\nexport function isSingleQuote(char: string): boolean {\n return char === \"'\"\n}\n\n/**\n * Strip last occurrence of textToStrip from text\n */\nexport function stripLastOccurrence(\n text: string,\n textToStrip: string,\n stripRemainingText = false\n): string {\n const index = text.lastIndexOf(textToStrip)\n return index !== -1\n ? text.substring(0, index) + (stripRemainingText ? '' : text.substring(index + 1))\n : text\n}\n\nexport function insertBeforeLastWhitespace(text: string, textToInsert: string): string {\n let index = text.length\n\n if (!isWhitespace(text, index - 1)) {\n // no trailing whitespaces\n return text + textToInsert\n }\n\n while (isWhitespace(text, index - 1)) {\n index--\n }\n\n return text.substring(0, index) + textToInsert + text.substring(index)\n}\n\nexport function removeAtIndex(text: string, start: number, count: number) {\n return text.substring(0, start) + text.substring(start + count)\n}\n\n/**\n * Test whether a string ends with a newline or comma character and optional whitespace\n */\nexport function endsWithCommaOrNewline(text: string): boolean {\n return /[,\\n][ \\t\\r]*$/.test(text)\n}\n", "import { JSONRepairError } from '../utils/JSONRepairError.js'\nimport {\n endsWithCommaOrNewline,\n insertBeforeLastWhitespace,\n isControlCharacter,\n isDelimiter,\n isDigit,\n isDoubleQuote,\n isDoubleQuoteLike,\n isFunctionNameChar,\n isFunctionNameCharStart,\n isHex,\n isQuote,\n isSingleQuote,\n isSingleQuoteLike,\n isSpecialWhitespace,\n isStartOfValue,\n isUnquotedStringDelimiter,\n isValidStringCharacter,\n isWhitespace,\n isWhitespaceExceptNewline,\n regexUrlChar,\n regexUrlStart,\n removeAtIndex,\n stripLastOccurrence\n} from '../utils/stringUtils.js'\n\nconst controlCharacters: { [key: string]: string } = {\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t'\n}\n\n// map with all escape characters\nconst escapeCharacters: { [key: string]: string } = {\n '\"': '\"',\n '\\\\': '\\\\',\n '/': '/',\n b: '\\b',\n f: '\\f',\n n: '\\n',\n r: '\\r',\n t: '\\t'\n // note that \\u is handled separately in parseString()\n}\n\n/**\n * Repair a string containing an invalid JSON document.\n * For example changes JavaScript notation into JSON notation.\n *\n * Example:\n *\n * try {\n * const json = \"{name: 'John'}\"\n * const repaired = jsonrepair(json)\n * console.log(repaired)\n * // '{\"name\": \"John\"}'\n * } catch (err) {\n * console.error(err)\n * }\n *\n */\nexport function jsonrepair(text: string): string {\n let i = 0 // current index in text\n let output = '' // generated output\n\n parseMarkdownCodeBlock(['```', '[```', '{```'])\n\n const processed = parseValue()\n if (!processed) {\n throwUnexpectedEnd()\n }\n\n parseMarkdownCodeBlock(['```', '```]', '```}'])\n\n const processedComma = parseCharacter(',')\n if (processedComma) {\n parseWhitespaceAndSkipComments()\n }\n\n if (isStartOfValue(text[i]) && endsWithCommaOrNewline(output)) {\n // start of a new value after end of the root level object: looks like\n // newline delimited JSON -> turn into a root level array\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n\n parseNewlineDelimitedJSON()\n } else if (processedComma) {\n // repair: remove trailing comma\n output = stripLastOccurrence(output, ',')\n }\n\n // repair redundant end quotes\n while (text[i] === '}' || text[i] === ']') {\n i++\n parseWhitespaceAndSkipComments()\n }\n\n if (i >= text.length) {\n // reached the end of the document properly\n return output\n }\n\n throwUnexpectedCharacter()\n\n function parseValue(): boolean {\n parseWhitespaceAndSkipComments()\n const processed =\n parseObject() ||\n parseArray() ||\n parseString() ||\n parseNumber() ||\n parseKeywords() ||\n parseUnquotedString(false) ||\n parseRegex()\n parseWhitespaceAndSkipComments()\n\n return processed\n }\n\n function parseWhitespaceAndSkipComments(skipNewline = true): boolean {\n const start = i\n\n let changed = parseWhitespace(skipNewline)\n do {\n changed = parseComment()\n if (changed) {\n changed = parseWhitespace(skipNewline)\n }\n } while (changed)\n\n return i > start\n }\n\n function parseWhitespace(skipNewline: boolean): boolean {\n const _isWhiteSpace = skipNewline ? isWhitespace : isWhitespaceExceptNewline\n let whitespace = ''\n\n while (true) {\n if (_isWhiteSpace(text, i)) {\n whitespace += text[i]\n i++\n } else if (isSpecialWhitespace(text, i)) {\n // repair special whitespace\n whitespace += ' '\n i++\n } else {\n break\n }\n }\n\n if (whitespace.length > 0) {\n output += whitespace\n return true\n }\n\n return false\n }\n\n function parseComment(): boolean {\n // find a block comment '/* ... */'\n if (text[i] === '/' && text[i + 1] === '*') {\n // repair block comment by skipping it\n while (i < text.length && !atEndOfBlockComment(text, i)) {\n i++\n }\n i += 2\n\n return true\n }\n\n // find a line comment '// ...'\n if (text[i] === '/' && text[i + 1] === '/') {\n // repair line comment by skipping it\n while (i < text.length && text[i] !== '\\n') {\n i++\n }\n\n return true\n }\n\n return false\n }\n\n function parseMarkdownCodeBlock(blocks: string[]): boolean {\n // find and skip over a Markdown fenced code block:\n // ``` ... ```\n // or\n // ```json ... ```\n if (skipMarkdownCodeBlock(blocks)) {\n if (isFunctionNameCharStart(text[i])) {\n // strip the optional language specifier like \"json\"\n while (i < text.length && isFunctionNameChar(text[i])) {\n i++\n }\n }\n\n parseWhitespaceAndSkipComments()\n\n return true\n }\n\n return false\n }\n\n function skipMarkdownCodeBlock(blocks: string[]): boolean {\n for (const block of blocks) {\n const end = i + block.length\n if (text.slice(i, end) === block) {\n i = end\n return true\n }\n }\n\n return false\n }\n\n function parseCharacter(char: string): boolean {\n if (text[i] === char) {\n output += text[i]\n i++\n return true\n }\n\n return false\n }\n\n function skipCharacter(char: string): boolean {\n if (text[i] === char) {\n i++\n return true\n }\n\n return false\n }\n\n function skipEscapeCharacter(): boolean {\n return skipCharacter('\\\\')\n }\n\n /**\n * Skip ellipsis like \"[1,2,3,...]\" or \"[1,2,3,...,9]\" or \"[...,7,8,9]\"\n * or a similar construct in objects.\n */\n function skipEllipsis(): boolean {\n parseWhitespaceAndSkipComments()\n\n if (text[i] === '.' && text[i + 1] === '.' && text[i + 2] === '.') {\n // repair: remove the ellipsis (three dots) and optionally a comma\n i += 3\n parseWhitespaceAndSkipComments()\n skipCharacter(',')\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse an object like '{\"key\": \"value\"}'\n */\n function parseObject(): boolean {\n if (text[i] === '{') {\n output += '{'\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: skip leading comma like in {, message: \"hi\"}\n if (skipCharacter(',')) {\n parseWhitespaceAndSkipComments()\n }\n\n let initial = true\n while (i < text.length && text[i] !== '}') {\n let processedComma: boolean\n if (!initial) {\n processedComma = parseCharacter(',')\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n parseWhitespaceAndSkipComments()\n } else {\n processedComma = true\n initial = false\n }\n\n skipEllipsis()\n\n const processedKey = parseString() || parseUnquotedString(true)\n if (!processedKey) {\n if (\n text[i] === '}' ||\n text[i] === '{' ||\n text[i] === ']' ||\n text[i] === '[' ||\n text[i] === undefined\n ) {\n // repair trailing comma\n output = stripLastOccurrence(output, ',')\n } else {\n throwObjectKeyExpected()\n }\n break\n }\n\n parseWhitespaceAndSkipComments()\n const processedColon = parseCharacter(':')\n const truncatedText = i >= text.length\n if (!processedColon) {\n if (isStartOfValue(text[i]) || truncatedText) {\n // repair missing colon\n output = insertBeforeLastWhitespace(output, ':')\n } else {\n throwColonExpected()\n }\n }\n const processedValue = parseValue()\n if (!processedValue) {\n if (processedColon || truncatedText) {\n // repair missing object value\n output += 'null'\n } else {\n throwColonExpected()\n }\n }\n }\n\n if (text[i] === '}') {\n output += '}'\n i++\n } else {\n // repair missing end bracket\n output = insertBeforeLastWhitespace(output, '}')\n }\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse an array like '[\"item1\", \"item2\", ...]'\n */\n function parseArray(): boolean {\n if (text[i] === '[') {\n output += '['\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: skip leading comma like in [,1,2,3]\n if (skipCharacter(',')) {\n parseWhitespaceAndSkipComments()\n }\n\n let initial = true\n while (i < text.length && text[i] !== ']') {\n if (!initial) {\n const processedComma = parseCharacter(',')\n if (!processedComma) {\n // repair missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n } else {\n initial = false\n }\n\n skipEllipsis()\n\n const processedValue = parseValue()\n if (!processedValue) {\n // repair trailing comma\n output = stripLastOccurrence(output, ',')\n break\n }\n }\n\n if (text[i] === ']') {\n output += ']'\n i++\n } else {\n // repair missing closing array bracket\n output = insertBeforeLastWhitespace(output, ']')\n }\n\n return true\n }\n\n return false\n }\n\n /**\n * Parse and repair Newline Delimited JSON (NDJSON):\n * multiple JSON objects separated by a newline character\n */\n function parseNewlineDelimitedJSON() {\n // repair NDJSON\n let initial = true\n let processedValue = true\n while (processedValue) {\n if (!initial) {\n // parse optional comma, insert when missing\n const processedComma = parseCharacter(',')\n if (!processedComma) {\n // repair: add missing comma\n output = insertBeforeLastWhitespace(output, ',')\n }\n } else {\n initial = false\n }\n\n processedValue = parseValue()\n }\n\n if (!processedValue) {\n // repair: remove trailing comma\n output = stripLastOccurrence(output, ',')\n }\n\n // repair: wrap the output inside array brackets\n output = `[\\n${output}\\n]`\n }\n\n /**\n * Parse a string enclosed by double quotes \"...\". Can contain escaped quotes\n * Repair strings enclosed in single quotes or special quotes\n * Repair an escaped string\n *\n * The function can run in two stages:\n * - First, it assumes the string has a valid end quote\n * - If it turns out that the string does not have a valid end quote followed\n * by a delimiter (which should be the case), the function runs again in a\n * more conservative way, stopping the string at the first next delimiter\n * and fixing the string by inserting a quote there, or stopping at a\n * stop index detected in the first iteration.\n */\n function parseString(stopAtDelimiter = false, stopAtIndex = -1): boolean {\n let skipEscapeChars = text[i] === '\\\\'\n if (skipEscapeChars) {\n // repair: remove the first escape character\n i++\n skipEscapeChars = true\n }\n\n if (isQuote(text[i])) {\n // double quotes are correct JSON,\n // single quotes come from JavaScript for example, we assume it will have a correct single end quote too\n // otherwise, we will match any double-quote-like start with a double-quote-like end,\n // or any single-quote-like start with a single-quote-like end\n const isEndQuote = isDoubleQuote(text[i])\n ? isDoubleQuote\n : isSingleQuote(text[i])\n ? isSingleQuote\n : isSingleQuoteLike(text[i])\n ? isSingleQuoteLike\n : isDoubleQuoteLike\n\n const iBefore = i\n const oBefore = output.length\n\n let str = '\"'\n i++\n\n while (true) {\n if (i >= text.length) {\n // end of text, we are missing an end quote\n\n const iPrev = prevNonWhitespaceIndex(i - 1)\n if (!stopAtDelimiter && isDelimiter(text.charAt(iPrev))) {\n // if the text ends with a delimiter, like [\"hello],\n // so the missing end quote should be inserted before this delimiter\n // retry parsing the string, stopping at the first next delimiter\n i = iBefore\n output = output.substring(0, oBefore)\n\n return parseString(true)\n }\n\n // repair missing quote\n str = insertBeforeLastWhitespace(str, '\"')\n output += str\n\n return true\n }\n\n if (i === stopAtIndex) {\n // use the stop index detected in the first iteration, and repair end quote\n str = insertBeforeLastWhitespace(str, '\"')\n output += str\n\n return true\n }\n\n if (isEndQuote(text[i])) {\n // end quote\n // let us check what is before and after the quote to verify whether this is a legit end quote\n const iQuote = i\n const oQuote = str.length\n str += '\"'\n i++\n output += str\n\n parseWhitespaceAndSkipComments(false)\n\n if (\n stopAtDelimiter ||\n i >= text.length ||\n isDelimiter(text[i]) ||\n isQuote(text[i]) ||\n isDigit(text[i])\n ) {\n // The quote is followed by the end of the text, a delimiter,\n // or a next value. So the quote is indeed the end of the string.\n parseConcatenatedString()\n\n return true\n }\n\n const iPrevChar = prevNonWhitespaceIndex(iQuote - 1)\n const prevChar = text.charAt(iPrevChar)\n\n if (prevChar === ',') {\n // A comma followed by a quote, like '{\"a\":\"b,c,\"d\":\"e\"}'.\n // We assume that the quote is a start quote, and that the end quote\n // should have been located right before the comma but is missing.\n i = iBefore\n output = output.substring(0, oBefore)\n\n return parseString(false, iPrevChar)\n }\n\n if (isDelimiter(prevChar)) {\n // This is not the right end quote: it is preceded by a delimiter,\n // and NOT followed by a delimiter. So, there is an end quote missing\n // parse the string again and then stop at the first next delimiter\n i = iBefore\n output = output.substring(0, oBefore)\n\n return parseString(true)\n }\n\n // revert to right after the quote but before any whitespace, and continue parsing the string\n output = output.substring(0, oBefore)\n i = iQuote + 1\n\n // repair unescaped quote\n str = `${str.substring(0, oQuote)}\\\\${str.substring(oQuote)}`\n } else if (stopAtDelimiter && isUnquotedStringDelimiter(text[i])) {\n // we're in the mode to stop the string at the first delimiter\n // because there is an end quote missing\n\n // test start of an url like \"https://...\" (this would be parsed as a comment)\n if (text[i - 1] === ':' && regexUrlStart.test(text.substring(iBefore + 1, i + 2))) {\n while (i < text.length && regexUrlChar.test(text[i])) {\n str += text[i]\n i++\n }\n }\n\n // repair missing quote\n str = insertBeforeLastWhitespace(str, '\"')\n output += str\n\n parseConcatenatedString()\n\n return true\n } else if (text[i] === '\\\\') {\n // handle escaped content like \\n or \\u2605\n const char = text.charAt(i + 1)\n const escapeChar = escapeCharacters[char]\n if (escapeChar !== undefined) {\n str += text.slice(i, i + 2)\n i += 2\n } else if (char === 'u') {\n let j = 2\n while (j < 6 && isHex(text[i + j])) {\n j++\n }\n\n if (j === 6) {\n str += text.slice(i, i + 6)\n i += 6\n } else if (i + j >= text.length) {\n // repair invalid or truncated unicode char at the end of the text\n // by removing the unicode char and ending the string here\n i = text.length\n } else {\n throwInvalidUnicodeCharacter()\n }\n } else {\n // repair invalid escape character: remove it\n str += char\n i += 2\n }\n } else {\n // handle regular characters\n const char = text.charAt(i)\n\n if (char === '\"' && text[i - 1] !== '\\\\') {\n // repair unescaped double quote\n str += `\\\\${char}`\n i++\n } else if (isControlCharacter(char)) {\n // unescaped control character\n str += controlCharacters[char]\n i++\n } else {\n if (!isValidStringCharacter(char)) {\n throwInvalidCharacter(char)\n }\n str += char\n i++\n }\n }\n\n if (skipEscapeChars) {\n // repair: skipped escape character (nothing to do)\n skipEscapeCharacter()\n }\n }\n }\n\n return false\n }\n\n /**\n * Repair concatenated strings like \"hello\" + \"world\", change this into \"helloworld\"\n */\n function parseConcatenatedString(): boolean {\n let processed = false\n\n parseWhitespaceAndSkipComments()\n while (text[i] === '+') {\n processed = true\n i++\n parseWhitespaceAndSkipComments()\n\n // repair: remove the end quote of the first string\n output = stripLastOccurrence(output, '\"', true)\n const start = output.length\n const parsedStr = parseString()\n if (parsedStr) {\n // repair: remove the start quote of the second string\n output = removeAtIndex(output, start, 1)\n } else {\n // repair: remove the + because it is not followed by a string\n output = insertBeforeLastWhitespace(output, '\"')\n }\n }\n\n return processed\n }\n\n /**\n * Parse a number like 2.4 or 2.4e6\n */\n function parseNumber(): boolean {\n const start = i\n if (text[i] === '-') {\n i++\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return true\n }\n if (!isDigit(text[i])) {\n i = start\n return false\n }\n }\n\n // Note that in JSON leading zeros like \"00789\" are not allowed.\n // We will allow all leading zeros here though and at the end of parseNumber\n // check against trailing zeros and repair that if needed.\n // Leading zeros can have meaning, so we should not clear them.\n while (isDigit(text[i])) {\n i++\n }\n\n if (text[i] === '.') {\n i++\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return true\n }\n if (!isDigit(text[i])) {\n i = start\n return false\n }\n while (isDigit(text[i])) {\n i++\n }\n }\n\n if (text[i] === 'e' || text[i] === 'E') {\n i++\n if (text[i] === '-' || text[i] === '+') {\n i++\n }\n if (atEndOfNumber()) {\n repairNumberEndingWithNumericSymbol(start)\n return true\n }\n if (!isDigit(text[i])) {\n i = start\n return false\n }\n while (isDigit(text[i])) {\n i++\n }\n }\n\n // if we're not at the end of the number by this point, allow this to be parsed as another type\n if (!atEndOfNumber()) {\n i = start\n return false\n }\n\n if (i > start) {\n // repair a number with leading zeros like \"00789\"\n const num = text.slice(start, i)\n const hasInvalidLeadingZero = /^0\\d/.test(num)\n\n output += hasInvalidLeadingZero ? `\"${num}\"` : num\n return true\n }\n\n return false\n }\n\n /**\n * Parse keywords true, false, null\n * Repair Python keywords True, False, None\n */\n function parseKeywords(): boolean {\n return (\n parseKeyword('true', 'true') ||\n parseKeyword('false', 'false') ||\n parseKeyword('null', 'null') ||\n // repair Python keywords True, False, None\n parseKeyword('True', 'true') ||\n parseKeyword('False', 'false') ||\n parseKeyword('None', 'null')\n )\n }\n\n function parseKeyword(name: string, value: string): boolean {\n if (text.slice(i, i + name.length) === name) {\n output += value\n i += name.length\n return true\n }\n\n return false\n }\n\n /**\n * Repair an unquoted string by adding quotes around it\n * Repair a MongoDB function call like NumberLong(\"2\")\n * Repair a JSONP function call like callback({...});\n */\n function parseUnquotedString(isKey: boolean) {\n // note that the symbol can end with whitespaces: we stop at the next delimiter\n // also, note that we allow strings to contain a slash / in order to support repairing regular expressions\n const start = i\n\n if (isFunctionNameCharStart(text[i])) {\n while (i < text.length && isFunctionNameChar(text[i])) {\n i++\n }\n\n let j = i\n while (isWhitespace(text, j)) {\n j++\n }\n\n if (text[j] === '(') {\n // repair a MongoDB function call like NumberLong(\"2\")\n // repair a JSONP function call like callback({...});\n i = j + 1\n\n parseValue()\n\n if (text[i] === ')') {\n // repair: skip close bracket of function call\n i++\n if (text[i] === ';') {\n // repair: skip semicolon after JSONP call\n i++\n }\n }\n\n return true\n }\n }\n\n while (\n i < text.length &&\n !isUnquotedStringDelimiter(text[i]) &&\n !isQuote(text[i]) &&\n (!isKey || text[i] !== ':')\n ) {\n i++\n }\n\n // test start of an url like \"https://...\" (this would be parsed as a comment)\n if (text[i - 1] === ':' && regexUrlStart.test(text.substring(start, i + 2))) {\n while (i < text.length && regexUrlChar.test(text[i])) {\n i++\n }\n }\n\n if (i > start) {\n // repair unquoted string\n // also, repair undefined into null\n\n // first, go back to prevent getting trailing whitespaces in the string\n while (isWhitespace(text, i - 1) && i > 0) {\n i--\n }\n\n const symbol = text.slice(start, i)\n output += symbol === 'undefined' ? 'null' : JSON.stringify(symbol)\n\n if (text[i] === '\"') {\n // we had a missing start quote, but now we encountered the end quote, so we can skip that one\n i++\n }\n\n return true\n }\n }\n\n function parseRegex() {\n if (text[i] === '/') {\n const start = i\n i++\n\n while (i < text.length && (text[i] !== '/' || text[i - 1] === '\\\\')) {\n i++\n }\n i++\n\n output += `\"${text.substring(start, i)}\"`\n\n return true\n }\n }\n\n function prevNonWhitespaceIndex(start: number): number {\n let prev = start\n\n while (prev > 0 && isWhitespace(text, prev)) {\n prev--\n }\n\n return prev\n }\n\n function atEndOfNumber() {\n return i >= text.length || isDelimiter(text[i]) || isWhitespace(text, i)\n }\n\n function repairNumberEndingWithNumericSymbol(start: number) {\n // repair numbers cut off at the end\n // this will only be called when we end after a '.', '-', or 'e' and does not\n // change the number more than it needs to make it valid JSON\n output += `${text.slice(start, i)}0`\n }\n\n function throwInvalidCharacter(char: string) {\n throw new JSONRepairError(`Invalid character ${JSON.stringify(char)}`, i)\n }\n\n function throwUnexpectedCharacter() {\n throw new JSONRepairError(`Unexpected character ${JSON.stringify(text[i])}`, i)\n }\n\n function throwUnexpectedEnd() {\n throw new JSONRepairError('Unexpected end of json string', text.length)\n }\n\n function throwObjectKeyExpected() {\n throw new JSONRepairError('Object key expected', i)\n }\n\n function throwColonExpected() {\n throw new JSONRepairError('Colon expected', i)\n }\n\n function throwInvalidUnicodeCharacter() {\n const chars = text.slice(i, i + 6)\n throw new JSONRepairError(`Invalid unicode character \"${chars}\"`, i)\n }\n}\n\nfunction atEndOfBlockComment(text: string, i: number) {\n return text[i] === '*' && text[i + 1] === '/'\n}\n", "import { Transformer } from \"@/types/transformer\";\nimport { parseToolArguments } from \"@/utils/toolArgumentsParser\";\n\nexport class EnhanceToolTransformer implements Transformer {\n name = \"enhancetool\";\n\n async transformResponseOut(response: Response): Promise {\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse = await response.json();\n if (jsonResponse?.choices?.[0]?.message?.tool_calls?.length) {\n // \u5904\u7406\u975E\u6D41\u5F0F\u7684\u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\n for (const toolCall of jsonResponse.choices[0].message.tool_calls) {\n if (toolCall.function?.arguments) {\n toolCall.function.arguments = parseToolArguments(\n toolCall.function.arguments,\n this.logger\n );\n }\n }\n }\n return new Response(JSON.stringify(jsonResponse), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n\n // Define interface for tool call tracking\n interface ToolCall {\n index?: number;\n name?: string;\n id?: string;\n arguments?: string;\n }\n\n let currentToolCall: ToolCall = {};\n\n let hasTextContent = false;\n let reasoningContent = \"\";\n let isReasoningComplete = false;\n let hasToolCall = false;\n let buffer = \"\"; // \u7528\u4E8E\u7F13\u51B2\u4E0D\u5B8C\u6574\u7684\u6570\u636E\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n const processBuffer = (\n buffer: string,\n controller: ReadableStreamDefaultController,\n encoder: TextEncoder\n ) => {\n const lines = buffer.split(\"\\n\");\n for (const line of lines) {\n if (line.trim()) {\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n };\n\n // Helper function to process completed tool calls\n const processCompletedToolCall = (\n data: any,\n controller: ReadableStreamDefaultController,\n encoder: TextEncoder\n ) => {\n let finalArgs = \"\";\n try {\n finalArgs = parseToolArguments(currentToolCall.arguments || \"\", this.logger);\n } catch (e: any) {\n console.error(\n `${e.message} ${\n e.stack\n } \u5DE5\u5177\u8C03\u7528\u53C2\u6570\u89E3\u6790\u5931\u8D25: ${JSON.stringify(\n currentToolCall\n )}`\n );\n // Use original arguments if parsing fails\n finalArgs = currentToolCall.arguments || \"\";\n }\n\n const delta = {\n role: \"assistant\",\n tool_calls: [\n {\n function: {\n name: currentToolCall.name,\n arguments: finalArgs,\n },\n id: currentToolCall.id,\n index: currentToolCall.index,\n type: \"function\",\n },\n ],\n };\n\n // Remove content field entirely to prevent extra null values\n const modifiedData = {\n ...data,\n choices: [\n {\n ...data.choices[0],\n delta,\n },\n ],\n };\n // Remove content field if it exists\n if (modifiedData.choices[0].delta.content !== undefined) {\n delete modifiedData.choices[0].delta.content;\n }\n\n const modifiedLine = `data: ${JSON.stringify(modifiedData)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n };\n\n const processLine = (\n line: string,\n context: {\n controller: ReadableStreamDefaultController;\n encoder: TextEncoder;\n hasTextContent: () => boolean;\n setHasTextContent: (val: boolean) => void;\n reasoningContent: () => string;\n appendReasoningContent: (content: string) => void;\n isReasoningComplete: () => boolean;\n setReasoningComplete: (val: boolean) => void;\n }\n ) => {\n const { controller, encoder } = context;\n\n if (line.startsWith(\"data: \") && line.trim() !== \"data: [DONE]\") {\n const jsonStr = line.slice(6);\n try {\n const data = JSON.parse(jsonStr);\n\n // Handle tool calls in streaming mode\n if (data.choices?.[0]?.delta?.tool_calls?.length) {\n const toolCallDelta = data.choices[0].delta.tool_calls[0];\n\n // Initialize currentToolCall if this is the first chunk for this tool call\n if (typeof currentToolCall.index === \"undefined\") {\n currentToolCall = {\n index: toolCallDelta.index,\n name: toolCallDelta.function?.name || \"\",\n id: toolCallDelta.id || \"\",\n arguments: toolCallDelta.function?.arguments || \"\"\n };\n if (toolCallDelta.function?.arguments) {\n toolCallDelta.function.arguments = ''\n }\n // Send the first chunk as-is\n const modifiedLine = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n return;\n }\n // Accumulate arguments if this is a continuation of the current tool call\n else if (currentToolCall.index === toolCallDelta.index) {\n if (toolCallDelta.function?.arguments) {\n currentToolCall.arguments += toolCallDelta.function.arguments;\n }\n // Don't send intermediate chunks that only contain arguments\n return;\n }\n // If we have a different tool call index, process the previous one and start a new one\n else {\n // Process the completed tool call using helper function\n processCompletedToolCall(data, controller, encoder);\n\n // Start tracking the new tool call\n currentToolCall = {\n index: toolCallDelta.index,\n name: toolCallDelta.function?.name || \"\",\n id: toolCallDelta.id || \"\",\n arguments: toolCallDelta.function?.arguments || \"\"\n };\n return;\n }\n }\n\n // Handle finish_reason for tool_calls\n if (data.choices?.[0]?.finish_reason === \"tool_calls\" && currentToolCall.index !== undefined) {\n // Process the final tool call using helper function\n processCompletedToolCall(data, controller, encoder);\n currentToolCall = {};\n return;\n }\n\n // Handle text content alongside tool calls\n if (\n data.choices?.[0]?.delta?.tool_calls?.length &&\n context.hasTextContent()\n ) {\n if (typeof data.choices[0].index === \"number\") {\n data.choices[0].index += 1;\n } else {\n data.choices[0].index = 1;\n }\n }\n\n const modifiedLine = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n } catch (e) {\n // \u5982\u679CJSON\u89E3\u6790\u5931\u8D25\uFF0C\u53EF\u80FD\u662F\u6570\u636E\u4E0D\u5B8C\u6574\uFF0C\u5C06\u539F\u59CB\u884C\u4F20\u9012\u4E0B\u53BB\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n } else {\n // Pass through non-data lines (like [DONE])\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5269\u4F59\u7684\u6570\u636E\n if (buffer.trim()) {\n processBuffer(buffer, controller, encoder);\n }\n break;\n }\n\n // \u68C0\u67E5value\u662F\u5426\u6709\u6548\n if (!value || value.length === 0) {\n continue;\n }\n\n let chunk;\n try {\n chunk = decoder.decode(value, { stream: true });\n } catch (decodeError) {\n console.warn(\"Failed to decode chunk\", decodeError);\n continue;\n }\n\n if (chunk.length === 0) {\n continue;\n }\n\n buffer += chunk;\n\n // \u5982\u679C\u7F13\u51B2\u533A\u8FC7\u5927\uFF0C\u8FDB\u884C\u5904\u7406\u907F\u514D\u5185\u5B58\u6CC4\u6F0F\n if (buffer.length > 1000000) {\n // 1MB \u9650\u5236\n console.warn(\n \"Buffer size exceeds limit, processing partial data\"\n );\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.trim()) {\n try {\n processLine(line, {\n controller,\n encoder,\n hasTextContent: () => hasTextContent,\n setHasTextContent: (val) => (hasTextContent = val),\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) =>\n (reasoningContent += content),\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) =>\n (isReasoningComplete = val),\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n continue;\n }\n\n // \u5904\u7406\u7F13\u51B2\u533A\u4E2D\u5B8C\u6574\u7684\u6570\u636E\u884C\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\"; // \u6700\u540E\u4E00\u884C\u53EF\u80FD\u4E0D\u5B8C\u6574\uFF0C\u4FDD\u7559\u5728\u7F13\u51B2\u533A\n\n for (const line of lines) {\n if (!line.trim()) continue;\n\n try {\n processLine(line, {\n controller,\n encoder,\n hasTextContent: () => hasTextContent,\n setHasTextContent: (val) => (hasTextContent = val),\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) =>\n (reasoningContent += content),\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) => (isReasoningComplete = val),\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // \u5982\u679C\u89E3\u6790\u5931\u8D25\uFF0C\u76F4\u63A5\u4F20\u9012\u539F\u59CB\u884C\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n } catch (error) {\n console.error(\"Stream error:\", error);\n controller.error(error);\n } finally {\n try {\n reader.releaseLock();\n } catch (e) {\n console.error(\"Error releasing reader lock:\", e);\n }\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n }\n\n return response;\n }\n}\n", "import { UnifiedChatRequest } from \"@/types/llm\";\nimport { Transformer, TransformerOptions } from \"../types/transformer\";\n\nexport class ReasoningTransformer implements Transformer {\n static TransformerName = \"reasoning\";\n enable: any;\n\n constructor(private readonly options?: TransformerOptions) {\n this.enable = this.options?.enable ?? true;\n }\n\n async transformRequestIn(\n request: UnifiedChatRequest\n ): Promise {\n if (!this.enable) {\n request.thinking = {\n type: \"disabled\",\n budget_tokens: -1,\n };\n request.enable_thinking = false;\n return request;\n }\n if (request.reasoning) {\n request.thinking = {\n type: \"enabled\",\n budget_tokens: request.reasoning.max_tokens,\n };\n request.enable_thinking = true;\n }\n return request;\n }\n\n async transformResponseOut(response: Response): Promise {\n if (!this.enable) return response;\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse = await response.json();\n // Handle non-streaming response if needed\n return new Response(JSON.stringify(jsonResponse), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n let reasoningContent = \"\";\n let isReasoningComplete = false;\n let buffer = \"\"; // Buffer for incomplete data\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n\n // Process buffer function\n const processBuffer = (\n buffer: string,\n controller: ReadableStreamDefaultController,\n encoder: TextEncoder\n ) => {\n const lines = buffer.split(\"\\n\");\n for (const line of lines) {\n if (line.trim()) {\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n };\n\n // Process line function\n const processLine = (\n line: string,\n context: {\n controller: ReadableStreamDefaultController;\n encoder: typeof TextEncoder;\n reasoningContent: () => string;\n appendReasoningContent: (content: string) => void;\n isReasoningComplete: () => boolean;\n setReasoningComplete: (val: boolean) => void;\n }\n ) => {\n const { controller, encoder } = context;\n\n this.logger?.debug({ line }, `Processing reason line`);\n\n if (line.startsWith(\"data: \") && line.trim() !== \"data: [DONE]\") {\n try {\n const data = JSON.parse(line.slice(6));\n\n // Extract reasoning_content from delta\n if (data.choices?.[0]?.delta?.reasoning_content) {\n context.appendReasoningContent(\n data.choices[0].delta.reasoning_content\n );\n const thinkingChunk = {\n ...data,\n choices: [\n {\n ...data.choices[0],\n delta: {\n ...data.choices[0].delta,\n thinking: {\n content: data.choices[0].delta.reasoning_content,\n },\n },\n },\n ],\n };\n delete thinkingChunk.choices[0].delta.reasoning_content;\n const thinkingLine = `data: ${JSON.stringify(\n thinkingChunk\n )}\\n\\n`;\n controller.enqueue(encoder.encode(thinkingLine));\n return;\n }\n\n // Check if reasoning is complete (when delta has content but no reasoning_content)\n if (\n (data.choices?.[0]?.delta?.content ||\n data.choices?.[0]?.delta?.tool_calls) &&\n context.reasoningContent() &&\n !context.isReasoningComplete()\n ) {\n context.setReasoningComplete(true);\n const signature = Date.now().toString();\n\n // Create a new chunk with thinking block\n const thinkingChunk = {\n ...data,\n choices: [\n {\n ...data.choices[0],\n delta: {\n ...data.choices[0].delta,\n content: null,\n thinking: {\n content: context.reasoningContent(),\n signature: signature,\n },\n },\n },\n ],\n };\n delete thinkingChunk.choices[0].delta.reasoning_content;\n // Send the thinking chunk\n const thinkingLine = `data: ${JSON.stringify(\n thinkingChunk\n )}\\n\\n`;\n controller.enqueue(encoder.encode(thinkingLine));\n }\n\n if (data.choices?.[0]?.delta?.reasoning_content) {\n delete data.choices[0].delta.reasoning_content;\n }\n\n // Send the modified chunk\n if (\n data.choices?.[0]?.delta &&\n Object.keys(data.choices[0].delta).length > 0\n ) {\n if (context.isReasoningComplete()) {\n data.choices[0].index++;\n }\n const modifiedLine = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(encoder.encode(modifiedLine));\n }\n } catch (e) {\n // If JSON parsing fails, pass through the original line\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n } else {\n // Pass through non-data lines (like [DONE])\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n };\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n // Process remaining data in buffer\n if (buffer.trim()) {\n processBuffer(buffer, controller, encoder);\n }\n break;\n }\n\n const chunk = decoder.decode(value, { stream: true });\n buffer += chunk;\n\n // Process complete lines from buffer\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\"; // Keep incomplete line in buffer\n\n for (const line of lines) {\n if (!line.trim()) continue;\n\n try {\n processLine(line, {\n controller,\n encoder: encoder,\n reasoningContent: () => reasoningContent,\n appendReasoningContent: (content) =>\n (reasoningContent += content),\n isReasoningComplete: () => isReasoningComplete,\n setReasoningComplete: (val) => (isReasoningComplete = val),\n });\n } catch (error) {\n console.error(\"Error processing line:\", line, error);\n // Pass through original line if parsing fails\n controller.enqueue(encoder.encode(line + \"\\n\"));\n }\n }\n }\n } catch (error) {\n console.error(\"Stream error:\", error);\n controller.error(error);\n } finally {\n try {\n reader.releaseLock();\n } catch (e) {\n console.error(\"Error releasing reader lock:\", e);\n }\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n }\n\n return response;\n }\n}\n", "import { UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer, TransformerOptions } from \"../types/transformer\";\n\nexport class SamplingTransformer implements Transformer {\n name = \"sampling\";\n\n max_tokens: number;\n temperature: number;\n top_p: number;\n top_k: number;\n repetition_penalty: number;\n\n constructor(private readonly options?: TransformerOptions) {\n this.max_tokens = this.options?.max_tokens;\n this.temperature = this.options?.temperature;\n this.top_p = this.options?.top_p;\n this.top_k = this.options?.top_k;\n this.repetition_penalty = this.options?.repetition_penalty;\n }\n\n async transformRequestIn(\n request: UnifiedChatRequest\n ): Promise {\n if (request.max_tokens && request.max_tokens > this.max_tokens) {\n request.max_tokens = this.max_tokens;\n }\n if (typeof this.temperature !== \"undefined\") {\n request.temperature = this.temperature;\n }\n if (typeof this.top_p !== \"undefined\") {\n request.top_p = this.top_p;\n }\n if (typeof this.top_k !== \"undefined\") {\n request.top_k = this.top_k;\n }\n if (typeof this.repetition_penalty !== \"undefined\") {\n request.repetition_penalty = this.repetition_penalty;\n }\n return request;\n }\n}\n", "import { UnifiedChatRequest } from \"../types/llm\";\r\nimport { Transformer } from \"../types/transformer\";\r\n\r\nexport class MaxCompletionTokens implements Transformer {\r\n static TransformerName = \"maxcompletiontokens\";\r\n\r\n async transformRequestIn(\r\n request: UnifiedChatRequest\r\n ): Promise {\r\n if (request.max_tokens) {\r\n request.max_completion_tokens = request.max_tokens;\r\n delete request.max_tokens;\r\n }\r\n return request;\r\n }\r\n}\r\n", "import { UnifiedChatRequest, UnifiedMessage, UnifiedTool } from \"../types/llm\";\n\n// Vertex Claude\u6D88\u606F\u63A5\u53E3\ninterface ClaudeMessage {\n role: \"user\" | \"assistant\";\n content: Array<{\n type: \"text\" | \"image\";\n text?: string;\n source?: {\n type: \"base64\";\n media_type: string;\n data: string;\n };\n }>;\n}\n\n// Vertex Claude\u5DE5\u5177\u63A5\u53E3\ninterface ClaudeTool {\n name: string;\n description: string;\n input_schema: {\n type: string;\n properties: Record;\n required?: string[];\n additionalProperties?: boolean;\n $schema?: string;\n };\n}\n\n// Vertex Claude\u8BF7\u6C42\u63A5\u53E3\ninterface VertexClaudeRequest {\n anthropic_version: \"vertex-2023-10-16\";\n messages: ClaudeMessage[];\n max_tokens: number;\n stream?: boolean;\n temperature?: number;\n top_p?: number;\n top_k?: number;\n tools?: ClaudeTool[];\n tool_choice?: \"auto\" | \"none\" | { type: \"tool\"; name: string };\n}\n\n// Vertex Claude\u54CD\u5E94\u63A5\u53E3\ninterface VertexClaudeResponse {\n content: Array<{\n type: \"text\";\n text: string;\n }>;\n id: string;\n model: string;\n role: \"assistant\";\n stop_reason: string;\n stop_sequence: null;\n type: \"message\";\n usage: {\n input_tokens: number;\n output_tokens: number;\n };\n tool_use?: Array<{\n id: string;\n name: string;\n input: Record;\n }>;\n}\n\nexport function buildRequestBody(\n request: UnifiedChatRequest\n): VertexClaudeRequest {\n const messages: ClaudeMessage[] = [];\n\n for (let i = 0; i < request.messages.length; i++) {\n const message = request.messages[i];\n const isLastMessage = i === request.messages.length - 1;\n const isAssistantMessage = message.role === \"assistant\";\n\n const content: ClaudeMessage[\"content\"] = [];\n\n if (typeof message.content === \"string\") {\n // \u4FDD\u7559\u6240\u6709\u5B57\u7B26\u4E32\u5185\u5BB9\uFF0C\u5373\u4F7F\u662F\u7A7A\u5B57\u7B26\u4E32\uFF0C\u56E0\u4E3A\u53EF\u80FD\u5305\u542B\u91CD\u8981\u4FE1\u606F\n content.push({\n type: \"text\",\n text: message.content,\n });\n } else if (Array.isArray(message.content)) {\n message.content.forEach((item) => {\n if (item.type === \"text\") {\n // \u4FDD\u7559\u6240\u6709\u6587\u672C\u5185\u5BB9\uFF0C\u5373\u4F7F\u662F\u7A7A\u5B57\u7B26\u4E32\n content.push({\n type: \"text\",\n text: item.text || \"\",\n });\n } else if (item.type === \"image_url\") {\n // \u5904\u7406\u56FE\u7247\u5185\u5BB9\n content.push({\n type: \"image\",\n source: {\n type: \"base64\",\n media_type: item.media_type || \"image/jpeg\",\n data: item.image_url.url,\n },\n });\n }\n });\n }\n\n // \u53EA\u8DF3\u8FC7\u5B8C\u5168\u7A7A\u7684\u975E\u6700\u540E\u4E00\u6761\u6D88\u606F\uFF08\u6CA1\u6709\u5185\u5BB9\u548C\u5DE5\u5177\u8C03\u7528\uFF09\n if (\n !isLastMessage &&\n content.length === 0 &&\n !message.tool_calls &&\n !message.content\n ) {\n continue;\n }\n\n // \u5BF9\u4E8E\u6700\u540E\u4E00\u6761 assistant \u6D88\u606F\uFF0C\u5982\u679C\u6CA1\u6709\u5185\u5BB9\u4F46\u6709\u5DE5\u5177\u8C03\u7528\uFF0C\u5219\u6DFB\u52A0\u7A7A\u5185\u5BB9\n if (\n isLastMessage &&\n isAssistantMessage &&\n content.length === 0 &&\n message.tool_calls\n ) {\n content.push({\n type: \"text\",\n text: \"\",\n });\n }\n\n messages.push({\n role: message.role === \"assistant\" ? \"assistant\" : \"user\",\n content,\n });\n }\n\n const requestBody: VertexClaudeRequest = {\n anthropic_version: \"vertex-2023-10-16\",\n messages,\n max_tokens: request.max_tokens || 1000,\n stream: request.stream || false,\n ...(request.temperature && { temperature: request.temperature }),\n };\n\n // \u5904\u7406\u5DE5\u5177\u5B9A\u4E49\n if (request.tools && request.tools.length > 0) {\n requestBody.tools = request.tools.map((tool: UnifiedTool) => ({\n name: tool.function.name,\n description: tool.function.description,\n input_schema: tool.function.parameters,\n }));\n }\n\n // \u5904\u7406\u5DE5\u5177\u9009\u62E9\n if (request.tool_choice) {\n if (request.tool_choice === \"auto\" || request.tool_choice === \"none\") {\n requestBody.tool_choice = request.tool_choice;\n } else if (typeof request.tool_choice === \"string\") {\n // \u5982\u679C tool_choice \u662F\u5B57\u7B26\u4E32\uFF0C\u5047\u8BBE\u662F\u5DE5\u5177\u540D\u79F0\n requestBody.tool_choice = {\n type: \"tool\",\n name: request.tool_choice,\n };\n }\n }\n\n return requestBody;\n}\n\nexport function transformRequestOut(\n request: Record\n): UnifiedChatRequest {\n const vertexRequest = request as VertexClaudeRequest;\n\n const messages: UnifiedMessage[] = vertexRequest.messages.map((msg) => {\n const content = msg.content.map((item) => {\n if (item.type === \"text\") {\n return {\n type: \"text\" as const,\n text: item.text || \"\",\n };\n } else if (item.type === \"image\" && item.source) {\n return {\n type: \"image_url\" as const,\n image_url: {\n url: item.source.data,\n },\n media_type: item.source.media_type,\n };\n }\n return {\n type: \"text\" as const,\n text: \"\",\n };\n });\n\n return {\n role: msg.role,\n content,\n };\n });\n\n const result: UnifiedChatRequest = {\n messages,\n model: request.model || \"claude-sonnet-4@20250514\",\n max_tokens: vertexRequest.max_tokens,\n temperature: vertexRequest.temperature,\n stream: vertexRequest.stream,\n };\n\n // \u5904\u7406\u5DE5\u5177\u5B9A\u4E49\n if (vertexRequest.tools && vertexRequest.tools.length > 0) {\n result.tools = vertexRequest.tools.map((tool) => ({\n type: \"function\" as const,\n function: {\n name: tool.name,\n description: tool.description,\n parameters: {\n type: \"object\" as const,\n properties: tool.input_schema.properties,\n required: tool.input_schema.required,\n additionalProperties: tool.input_schema.additionalProperties,\n $schema: tool.input_schema.$schema,\n },\n },\n }));\n }\n\n // \u5904\u7406\u5DE5\u5177\u9009\u62E9\n if (vertexRequest.tool_choice) {\n if (typeof vertexRequest.tool_choice === \"string\") {\n result.tool_choice = vertexRequest.tool_choice;\n } else if (vertexRequest.tool_choice.type === \"tool\") {\n result.tool_choice = vertexRequest.tool_choice.name;\n }\n }\n\n return result;\n}\n\nexport async function transformResponseOut(\n response: Response,\n providerName: string,\n logger?: any\n): Promise {\n if (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n const jsonResponse = (await response.json()) as VertexClaudeResponse;\n\n // \u5904\u7406\u5DE5\u5177\u8C03\u7528\n let tool_calls = undefined;\n if (jsonResponse.tool_use && jsonResponse.tool_use.length > 0) {\n tool_calls = jsonResponse.tool_use.map((tool) => ({\n id: tool.id,\n type: \"function\" as const,\n function: {\n name: tool.name,\n arguments: JSON.stringify(tool.input),\n },\n }));\n }\n\n // \u8F6C\u6362\u4E3AOpenAI\u683C\u5F0F\u7684\u54CD\u5E94\n const res = {\n id: jsonResponse.id,\n choices: [\n {\n finish_reason: jsonResponse.stop_reason || null,\n index: 0,\n message: {\n content: jsonResponse.content[0]?.text || \"\",\n role: \"assistant\",\n ...(tool_calls && { tool_calls }),\n },\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n model: jsonResponse.model,\n object: \"chat.completion\",\n usage: {\n completion_tokens: jsonResponse.usage.output_tokens,\n prompt_tokens: jsonResponse.usage.input_tokens,\n total_tokens:\n jsonResponse.usage.input_tokens + jsonResponse.usage.output_tokens,\n },\n };\n\n return new Response(JSON.stringify(res), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } else if (response.headers.get(\"Content-Type\")?.includes(\"stream\")) {\n // \u5904\u7406\u6D41\u5F0F\u54CD\u5E94\n if (!response.body) {\n return response;\n }\n\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n\n const processLine = (\n line: string,\n controller: ReadableStreamDefaultController\n ) => {\n if (line.startsWith(\"data: \")) {\n const chunkStr = line.slice(6).trim();\n if (chunkStr) {\n logger?.debug({ chunkStr }, `${providerName} chunk:`);\n try {\n const chunk = JSON.parse(chunkStr);\n\n // \u5904\u7406 Anthropic \u539F\u751F\u683C\u5F0F\u7684\u6D41\u5F0F\u54CD\u5E94\n if (\n chunk.type === \"content_block_delta\" &&\n chunk.delta?.type === \"text_delta\"\n ) {\n // \u8FD9\u662F Anthropic \u539F\u751F\u683C\u5F0F\uFF0C\u9700\u8981\u8F6C\u6362\u4E3A OpenAI \u683C\u5F0F\n const res = {\n choices: [\n {\n delta: {\n role: \"assistant\",\n content: chunk.delta.text || \"\",\n },\n finish_reason: null,\n index: 0,\n logprobs: null,\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n id: chunk.id || \"\",\n model: chunk.model || \"\",\n object: \"chat.completion.chunk\",\n system_fingerprint: \"fp_a49d71b8a1\",\n usage: {\n completion_tokens: chunk.usage?.output_tokens || 0,\n prompt_tokens: chunk.usage?.input_tokens || 0,\n total_tokens:\n (chunk.usage?.input_tokens || 0) +\n (chunk.usage?.output_tokens || 0),\n },\n };\n controller.enqueue(\n encoder.encode(`data: ${JSON.stringify(res)}\\n\\n`)\n );\n } else if (\n chunk.type === \"content_block_delta\" &&\n chunk.delta?.type === \"input_json_delta\"\n ) {\n // \u5904\u7406\u5DE5\u5177\u8C03\u7528\u7684\u53C2\u6570\u589E\u91CF\n const res = {\n choices: [\n {\n delta: {\n tool_calls: [\n {\n index: chunk.index || 0,\n function: {\n arguments: chunk.delta.partial_json || \"\",\n },\n },\n ],\n },\n finish_reason: null,\n index: 0,\n logprobs: null,\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n id: chunk.id || \"\",\n model: chunk.model || \"\",\n object: \"chat.completion.chunk\",\n system_fingerprint: \"fp_a49d71b8a1\",\n usage: {\n completion_tokens: chunk.usage?.output_tokens || 0,\n prompt_tokens: chunk.usage?.input_tokens || 0,\n total_tokens:\n (chunk.usage?.input_tokens || 0) +\n (chunk.usage?.output_tokens || 0),\n },\n };\n controller.enqueue(\n encoder.encode(`data: ${JSON.stringify(res)}\\n\\n`)\n );\n } else if (\n chunk.type === \"content_block_start\" &&\n chunk.content_block?.type === \"tool_use\"\n ) {\n // \u5904\u7406\u5DE5\u5177\u8C03\u7528\u5F00\u59CB\n const res = {\n choices: [\n {\n delta: {\n tool_calls: [\n {\n index: chunk.index || 0,\n id: chunk.content_block.id,\n type: \"function\",\n function: {\n name: chunk.content_block.name,\n arguments: \"\",\n },\n },\n ],\n },\n finish_reason: null,\n index: 0,\n logprobs: null,\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n id: chunk.id || \"\",\n model: chunk.model || \"\",\n object: \"chat.completion.chunk\",\n system_fingerprint: \"fp_a49d71b8a1\",\n usage: {\n completion_tokens: chunk.usage?.output_tokens || 0,\n prompt_tokens: chunk.usage?.input_tokens || 0,\n total_tokens:\n (chunk.usage?.input_tokens || 0) +\n (chunk.usage?.output_tokens || 0),\n },\n };\n controller.enqueue(\n encoder.encode(`data: ${JSON.stringify(res)}\\n\\n`)\n );\n } else if (chunk.type === \"message_delta\") {\n // \u5904\u7406\u6D88\u606F\u7ED3\u675F\n const res = {\n choices: [\n {\n delta: {},\n finish_reason:\n chunk.delta?.stop_reason === \"tool_use\"\n ? \"tool_calls\"\n : chunk.delta?.stop_reason === \"max_tokens\"\n ? \"length\"\n : chunk.delta?.stop_reason === \"stop_sequence\"\n ? \"content_filter\"\n : \"stop\",\n index: 0,\n logprobs: null,\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n id: chunk.id || \"\",\n model: chunk.model || \"\",\n object: \"chat.completion.chunk\",\n system_fingerprint: \"fp_a49d71b8a1\",\n usage: {\n completion_tokens: chunk.usage?.output_tokens || 0,\n prompt_tokens: chunk.usage?.input_tokens || 0,\n total_tokens:\n (chunk.usage?.input_tokens || 0) +\n (chunk.usage?.output_tokens || 0),\n },\n };\n controller.enqueue(\n encoder.encode(`data: ${JSON.stringify(res)}\\n\\n`)\n );\n } else if (chunk.type === \"message_stop\") {\n // \u53D1\u9001\u7ED3\u675F\u6807\u8BB0\n controller.enqueue(encoder.encode(`data: [DONE]\\n\\n`));\n } else {\n // \u5904\u7406\u5176\u4ED6\u683C\u5F0F\u7684\u54CD\u5E94\uFF08\u4FDD\u6301\u539F\u6709\u903B\u8F91\u4F5C\u4E3A\u540E\u5907\uFF09\n const res = {\n choices: [\n {\n delta: {\n role: \"assistant\",\n content: chunk.content?.[0]?.text || \"\",\n },\n finish_reason: chunk.stop_reason?.toLowerCase() || null,\n index: 0,\n logprobs: null,\n },\n ],\n created: parseInt(new Date().getTime() / 1000 + \"\", 10),\n id: chunk.id || \"\",\n model: chunk.model || \"\",\n object: \"chat.completion.chunk\",\n system_fingerprint: \"fp_a49d71b8a1\",\n usage: {\n completion_tokens: chunk.usage?.output_tokens || 0,\n prompt_tokens: chunk.usage?.input_tokens || 0,\n total_tokens:\n (chunk.usage?.input_tokens || 0) +\n (chunk.usage?.output_tokens || 0),\n },\n };\n controller.enqueue(\n encoder.encode(`data: ${JSON.stringify(res)}\\n\\n`)\n );\n }\n } catch (error: any) {\n logger?.error(\n `Error parsing ${providerName} stream chunk`,\n chunkStr,\n error.message\n );\n }\n }\n }\n };\n\n const stream = new ReadableStream({\n async start(controller) {\n const reader = response.body!.getReader();\n let buffer = \"\";\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n if (buffer) {\n processLine(buffer, controller);\n }\n break;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n processLine(line, controller);\n }\n }\n } catch (error) {\n controller.error(error);\n } finally {\n controller.close();\n }\n },\n });\n\n return new Response(stream, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n }\n return response;\n}\n", "import { LLMProvider, UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer } from \"../types/transformer\";\nimport {\n buildRequestBody,\n transformRequestOut,\n transformResponseOut,\n} from \"../utils/vertex-claude.util\";\n\nasync function getAccessToken(): Promise {\n try {\n const { GoogleAuth } = await import('google-auth-library');\n\n const auth = new GoogleAuth({\n scopes: ['https://www.googleapis.com/auth/cloud-platform']\n });\n\n const client = await auth.getClient();\n const accessToken = await client.getAccessToken();\n return accessToken.token || '';\n } catch (error) {\n console.error('Error getting access token:', error);\n throw new Error('Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:\\n' +\n '1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file\\n' +\n '2. Run \"gcloud auth application-default login\"\\n' +\n '3. Use Google Cloud environment with default service account');\n }\n}\n\n\n\nexport class VertexClaudeTransformer implements Transformer {\n name = \"vertex-claude\";\n\n async transformRequestIn(\n request: UnifiedChatRequest,\n provider: LLMProvider\n ): Promise> {\n let projectId = process.env.GOOGLE_CLOUD_PROJECT;\n const location = process.env.GOOGLE_CLOUD_LOCATION || 'us-east5';\n\n if (!projectId && process.env.GOOGLE_APPLICATION_CREDENTIALS) {\n try {\n const fs = await import('fs');\n const keyContent = fs.readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS, 'utf8');\n const credentials = JSON.parse(keyContent);\n if (credentials && credentials.project_id) {\n projectId = credentials.project_id;\n }\n } catch (error) {\n console.error('Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:', error);\n }\n }\n\n if (!projectId) {\n throw new Error('Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.');\n }\n\n const accessToken = await getAccessToken();\n return {\n body: buildRequestBody(request),\n config: {\n url: new URL(\n `/v1/projects/${projectId}/locations/${location}/publishers/anthropic/models/${request.model}:${request.stream ? \"streamRawPredict\" : \"rawPredict\"}`,\n `https://${location}-aiplatform.googleapis.com`\n ).toString(),\n headers: {\n \"Authorization\": `Bearer ${accessToken}`,\n \"Content-Type\": \"application/json\",\n },\n },\n };\n }\n\n async transformRequestOut(request: Record): Promise {\n return transformRequestOut(request);\n }\n\n async transformResponseOut(response: Response): Promise {\n return transformResponseOut(response, this.name, this.logger);\n }\n}\n", "import { LLMProvider, UnifiedChatRequest, UnifiedMessage } from \"@/types/llm\";\nimport { Transformer } from \"@/types/transformer\";\n\n/**\n * Converts content from Claude Code format (array of objects) to plain string\n * @param content - The content to convert\n * @returns The converted string content\n */\nfunction convertContentToString(content: unknown): string {\n if (typeof content === 'string') {\n return content;\n }\n \n if (Array.isArray(content)) {\n return content\n .map(item => {\n if (typeof item === 'string') {\n return item;\n }\n if (typeof item === 'object' && item !== null && \n 'type' in item && item.type === 'text' && \n 'text' in item && typeof item.text === 'string') {\n return item.text;\n }\n return '';\n })\n .join('');\n }\n \n return '';\n}\n\n/**\n * Transformer class for Cerebras\n */\nexport class CerebrasTransformer implements Transformer {\n name = \"cerebras\";\n\n /**\n * Transform the request from Claude Code format to Cerebras format\n * @param request - The incoming request\n * @param provider - The LLM provider information\n * @returns The transformed request\n */\n async transformRequestIn(\n request: UnifiedChatRequest,\n provider: LLMProvider\n ): Promise> {\n // Deep clone the request to avoid modifying the original\n const transformedRequest = JSON.parse(JSON.stringify(request));\n \n // IMPORTANT: Cerebras API requires a model field in the request body\n // If model is not present in the request, use the first model from provider config\n if (!transformedRequest.model && provider.models && provider.models.length > 0) {\n transformedRequest.model = provider.models[0];\n }\n \n // Handle system field at the top level - convert to system message\n if (transformedRequest.system !== undefined) {\n const systemContent = convertContentToString(transformedRequest.system);\n // Add system message at the beginning of messages array\n if (!transformedRequest.messages) {\n transformedRequest.messages = [];\n }\n transformedRequest.messages.unshift({\n role: 'system',\n content: systemContent\n });\n // Remove the top-level system field as it's now in messages\n delete transformedRequest.system;\n }\n \n // Transform messages - IMPORTANT: This must convert ALL message content to strings\n if (transformedRequest.messages && Array.isArray(transformedRequest.messages)) {\n transformedRequest.messages = transformedRequest.messages.map((message: UnifiedMessage) => {\n const transformedMessage = { ...message };\n \n // Convert content to string format for ALL messages\n if (transformedMessage.content !== undefined) {\n transformedMessage.content = convertContentToString(transformedMessage.content);\n }\n \n return transformedMessage;\n });\n }\n \n return {\n body: transformedRequest,\n config: {\n headers: {\n 'Authorization': `Bearer ${provider.apiKey}`,\n 'Content-Type': 'application/json'\n }\n }\n };\n }\n\n /**\n * Transform the response\n * @param response - The response from Cerebras\n * @returns The transformed response\n */\n async transformResponseOut(response: Response): Promise {\n // Cerebras responses should be compatible with Claude Code\n // No transformation needed\n return response;\n }\n}", "import { UnifiedChatRequest } from \"../types/llm\";\nimport { Transformer, TransformerOptions } from \"../types/transformer\";\n\nexport class StreamOptionsTransformer implements Transformer {\n name = \"streamoptions\";\n\n async transformRequestIn(\n request: UnifiedChatRequest\n ): Promise {\n if (!request.stream) return request;\n request.stream_options = {\n include_usage: true,\n };\n return request;\n }\n}\n", "import { AnthropicTransformer } from \"./anthropic.transformer\";\nimport { GeminiTransformer } from \"./gemini.transformer\";\nimport { VertexGeminiTransformer } from \"./vertex-gemini.transformer\";\nimport { DeepseekTransformer } from \"./deepseek.transformer\";\nimport { TooluseTransformer } from \"./tooluse.transformer\";\nimport { OpenrouterTransformer } from \"./openrouter.transformer\";\nimport { MaxTokenTransformer } from \"./maxtoken.transformer\";\nimport { GroqTransformer } from \"./groq.transformer\";\nimport { CleancacheTransformer } from \"./cleancache.transformer\";\nimport { EnhanceToolTransformer } from \"./enhancetool.transformer\";\nimport { ReasoningTransformer } from \"./reasoning.transformer\";\nimport { SamplingTransformer } from \"./sampling.transformer\";\nimport { MaxCompletionTokens } from \"./maxcompletiontokens.transformer\";\nimport { VertexClaudeTransformer } from \"./vertex-claude.transformer\";\nimport { CerebrasTransformer } from \"./cerebras.transformer\";\nimport { StreamOptionsTransformer } from \"./streamoptions.transformer\";\n\nexport default {\n AnthropicTransformer,\n GeminiTransformer,\n VertexGeminiTransformer,\n VertexClaudeTransformer,\n DeepseekTransformer,\n TooluseTransformer,\n OpenrouterTransformer,\n MaxTokenTransformer,\n GroqTransformer,\n CleancacheTransformer,\n EnhanceToolTransformer,\n ReasoningTransformer,\n SamplingTransformer,\n MaxCompletionTokens,\n CerebrasTransformer,\n StreamOptionsTransformer\n};\n", "import { Transformer, TransformerConstructor } from \"@/types/transformer\";\nimport { ConfigService } from \"./config\";\nimport Transformers from \"@/transformer\";\nimport Module from \"node:module\";\n\ninterface TransformerConfig {\n transformers: Array<{\n name: string;\n type: \"class\" | \"module\";\n path?: string;\n options?: any;\n }>;\n}\n\nexport class TransformerService {\n private transformers: Map =\n new Map();\n\n constructor(\n private readonly configService: ConfigService,\n private readonly logger: any\n ) {}\n\n registerTransformer(name: string, transformer: Transformer): void {\n this.transformers.set(name, transformer);\n this.logger.info(\n `register transformer: ${name}${\n transformer.endPoint\n ? ` (endpoint: ${transformer.endPoint})`\n : \" (no endpoint)\"\n }`\n );\n }\n\n getTransformer(\n name: string\n ): Transformer | TransformerConstructor | undefined {\n return this.transformers.get(name);\n }\n\n getAllTransformers(): Map {\n return new Map(this.transformers);\n }\n\n getTransformersWithEndpoint(): { name: string; transformer: Transformer }[] {\n const result: { name: string; transformer: Transformer }[] = [];\n\n this.transformers.forEach((transformer, name) => {\n if (transformer.endPoint) {\n result.push({ name, transformer });\n }\n });\n\n return result;\n }\n\n getTransformersWithoutEndpoint(): {\n name: string;\n transformer: Transformer;\n }[] {\n const result: { name: string; transformer: Transformer }[] = [];\n\n this.transformers.forEach((transformer, name) => {\n if (!transformer.endPoint) {\n result.push({ name, transformer });\n }\n });\n\n return result;\n }\n\n removeTransformer(name: string): boolean {\n return this.transformers.delete(name);\n }\n\n hasTransformer(name: string): boolean {\n return this.transformers.has(name);\n }\n\n async registerTransformerFromConfig(config: {\n path?: string;\n options?: any;\n }): Promise {\n try {\n if (config.path) {\n const module = require(require.resolve(config.path));\n if (module) {\n const instance = new module(config.options);\n // Set logger for transformer instance\n if (instance && typeof instance === \"object\") {\n (instance as any).logger = this.logger;\n }\n if (!instance.name) {\n throw new Error(\n `Transformer instance from ${config.path} does not have a name property.`\n );\n }\n this.registerTransformer(instance.name, instance);\n return true;\n }\n }\n return false;\n } catch (error: any) {\n this.logger.error(\n `load transformer (${config.path}) \\nerror: ${error.message}\\nstack: ${error.stack}`\n );\n return false;\n }\n }\n\n async initialize(): Promise {\n try {\n await this.registerDefaultTransformersInternal();\n await this.loadFromConfig();\n } catch (error: any) {\n this.logger.error(\n `TransformerService init error: ${error.message}\\nStack: ${error.stack}`\n );\n }\n }\n\n private async registerDefaultTransformersInternal(): Promise {\n try {\n Object.values(Transformers).forEach(\n (TransformerStatic: TransformerConstructor) => {\n if (\n \"TransformerName\" in TransformerStatic &&\n typeof TransformerStatic.TransformerName === \"string\"\n ) {\n this.registerTransformer(\n TransformerStatic.TransformerName,\n TransformerStatic\n );\n } else {\n const transformerInstance = new TransformerStatic();\n // Set logger for transformer instance\n if (\n transformerInstance &&\n typeof transformerInstance === \"object\"\n ) {\n (transformerInstance as any).logger = this.logger;\n }\n this.registerTransformer(\n transformerInstance.name!,\n transformerInstance\n );\n }\n }\n );\n } catch (error) {\n this.logger.error({ error }, \"transformer regist error:\");\n }\n }\n\n private async loadFromConfig(): Promise {\n const transformers = this.configService.get<\n TransformerConfig[\"transformers\"]\n >(\"transformers\", []);\n for (const transformer of transformers) {\n await this.registerTransformerFromConfig(transformer);\n }\n }\n}\n"], + "mappings": "82BAAA,IAAAA,GAAAC,EAAA,CAAAC,GAAAC,KAAA,CACAA,GAAO,QAAQ,gBAAkB,0CACjCA,GAAO,QAAQ,SAAW,s7NAC1BA,GAAO,QAAQ,YAAc,u2QCH7B,IAAAC,GAAAC,EAAA,CAAAC,GAAAC,KAAA,KAAMC,GAAU,KAEhBD,GAAO,QAAU,CACb,iBAAkBE,EAAG,CACjB,OAAO,OAAOA,GAAM,UAAYD,GAAQ,gBAAgB,KAAKC,CAAC,CAClE,EAEA,cAAeA,EAAG,CACd,OAAO,OAAOA,GAAM,WACfA,GAAK,KAAOA,GAAK,KACrBA,GAAK,KAAOA,GAAK,KACjBA,IAAM,KAASA,IAAM,KACtBD,GAAQ,SAAS,KAAKC,CAAC,EAE3B,EAEA,iBAAkBA,EAAG,CACjB,OAAO,OAAOA,GAAM,WACfA,GAAK,KAAOA,GAAK,KACrBA,GAAK,KAAOA,GAAK,KACjBA,GAAK,KAAOA,GAAK,KACjBA,IAAM,KAASA,IAAM,KACrBA,IAAM,UAAcA,IAAM,UAC3BD,GAAQ,YAAY,KAAKC,CAAC,EAE9B,EAEA,QAASA,EAAG,CACR,OAAO,OAAOA,GAAM,UAAY,QAAQ,KAAKA,CAAC,CAClD,EAEA,WAAYA,EAAG,CACX,OAAO,OAAOA,GAAM,UA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/CN,EAAM,KAAK,GAAG,EAAE,KAAK,CAAE,MAAO,uBAAwB,CAAC,CAChE,CACF,CACF,EAEA,KAAK,IAAI,SAASO,EAAiB,EAEnC,IAAMC,EAAU,MAAM,KAAK,IAAI,OAAO,CACpC,KAAM,SAAS,KAAK,cAAc,IAAI,MAAM,GAAK,OAAQ,EAAE,EAC3D,KAAM,KAAK,cAAc,IAAI,MAAM,GAAK,WAC1C,CAAC,EAED,KAAK,IAAI,IAAI,KAAK,0CAAmCA,CAAO,EAAE,EAE9D,IAAMC,EAAW,MAAOC,GAAmB,CACzC,KAAK,IAAI,IAAI,KAAK,YAAYA,CAAM,+BAA+B,EACnE,MAAM,KAAK,IAAI,MAAM,EACrB,QAAQ,KAAK,CAAC,CAChB,EAEA,QAAQ,GAAG,SAAU,IAAMD,EAAS,QAAQ,CAAC,EAC7C,QAAQ,GAAG,UAAW,IAAMA,EAAS,SAAS,CAAC,CACjD,OAASE,EAAO,CACd,KAAK,IAAI,IAAI,MAAM,0BAA0BA,CAAK,EAAE,EACpD,QAAQ,KAAK,CAAC,CAChB,CACF,CACF,EAGOC,GAAQtB", + "names": ["require_unicode", "__commonJSMin", "exports", "module", "require_util", "__commonJSMin", "exports", "module", "unicode", "c", "require_parse", "__commonJSMin", "exports", "module", "util", "source", "parseState", "stack", "pos", "line", "column", "token", "key", "root", "text", "reviver", "lex", "parseStates", "internalize", "holder", "name", "value", "i", "replacement", "lexState", "buffer", "doubleQuote", "sign", "c", "peek", "lexStates", "read", "newToken", "invalidChar", "literal", "u", "unicodeEscape", "invalidIdentifier", "escape", "separatorChar", "type", "s", "hexEscape", "count", "invalidEOF", "push", "pop", "parent", "current", "syntaxError", "formatChar", "replacements", "hexString", "message", "err", "require_stringify", "__commonJSMin", "exports", "module", "util", "value", "replacer", "space", "stack", "indent", "propertyList", "replacerFunc", "gap", "quote", "v", "item", "serializeProperty", "key", "holder", "quoteString", "serializeArray", "serializeObject", "quotes", "replacements", "product", "i", "c", "hexString", "quoteChar", "a", "b", "stepback", "keys", "partial", "propertyString", "member", "serializeKey", "final", "properties", "separator", "firstChar", "require_lib", "__commonJSMin", "exports", "module", "parse", "stringify", "JSON5", "require_extend", "__commonJSMin", "exports", "module", "hasOwn", "toStr", "defineProperty", "gOPD", "isArray", "arr", "isPlainObject", "obj", "hasOwnConstructor", "hasIsPrototypeOf", "key", "setProperty", "target", "options", "getProperty", "name", "extend", "src", "copy", "copyIsArray", "clone", "i", "length", "deep", "require_package", "__commonJSMin", "exports", "module", "pkg", "module", "exports", "defaultErrorRedactor", "extend_1", "__importDefault", "util_cjs_1", "pkg", "GaxiosError", "_GaxiosError", "instance", "message", "config", "response", "cause", "translateData", "res", "defaultErrorMessage", "status", "code", "errorMessages", "e", "responseType", "data", "REDACT", "redactHeaders", "headers", "_", "key", "redactString", "obj", "text", "redactObject", "exports", "getRetryConfig", "err", "config", "getConfig", "retryRanges", "shouldRetryRequest", "delay", "getNextRetryDelay", "backoff", "resolve", "isInRange", "min", "max", "status", "calculatedDelay", "maxAllowableDelay", "GaxiosInterceptorManager", "exports", "require_ms", "__commonJSMin", "exports", "module", "s", "m", "h", "d", "w", "y", "val", "options", "type", "parse", "fmtLong", "fmtShort", "str", "match", "n", "ms", "msAbs", "plural", "name", "isPlural", "require_common", "__commonJSMin", "exports", "module", "setup", "env", "createDebug", "coerce", "disable", "enable", "enabled", "destroy", "key", "selectColor", "namespace", "hash", "i", "prevTime", "enableOverride", "namespacesCache", "enabledCache", "debug", "args", "self", "curr", "ms", "index", "match", "format", "formatter", "val", "extend", "v", "delimiter", "newDebug", "namespaces", "split", "ns", "matchesTemplate", "search", "template", "searchIndex", "templateIndex", "starIndex", "matchIndex", "name", "skip", "require_browser", "__commonJSMin", "exports", "module", "formatArgs", "save", "load", "useColors", "localstorage", "warned", "m", "args", "c", "index", "lastC", "match", "namespaces", "formatters", "v", "error", "require_has_flag", "__commonJSMin", "exports", "module", "flag", "argv", "prefix", "pos", "terminatorPos", "require_supports_color", "__commonJSMin", "exports", "module", "os", "hasFlag", "env", "forceColor", "translateLevel", "level", "supportsColor", "stream", "min", "osRelease", "sign", "version", "getSupportLevel", "require_node", "__commonJSMin", "exports", "module", "tty", "util", "init", "log", "formatArgs", "save", "load", "useColors", "supportsColor", "key", "obj", "prop", "_", "k", "val", "args", "name", "c", "colorCode", "prefix", "getDate", "namespaces", "debug", "keys", "i", "formatters", "v", "str", "require_src", "__commonJSMin", "exports", "module", "http", "__importStar", "https", "toBuffer", "stream", "length", "chunks", "chunk", "exports", "json", "str", "_err", "err", "req", "url", "opts", "promise", "resolve", "reject", "net", "__importStar", "http", "https_1", "__exportStar", "exports", "INTERNAL", "Agent", "opts", "options", "stack", "l", "name", "fakeSocket", "socket", "sockets", "index", "req", "cb", "connectOpts", "err", "v", "debug_1", "__importDefault", "debug", "parseProxyResponse", "socket", "resolve", "reject", "buffersLength", "buffers", "read", "b", "ondata", "cleanup", "onend", "onerror", "err", "buffered", "endOfHeaders", "headerParts", "firstLine", "firstLineParts", "statusCode", "statusText", "headers", "header", "firstColon", "key", "value", "current", "exports", "net", "__importStar", "tls", "assert_1", "__importDefault", "debug_1", "agent_base_1", "url_1", "parse_proxy_response_1", "debug", "setServernameFromNonIpHost", "options", "HttpsProxyAgent", "proxy", "opts", "host", "port", "omit", "req", "socket", "headers", "payload", "auth", "name", "proxyResponsePromise", "connect", "buffered", "resume", "fakeSocket", "s", "exports", "obj", "keys", "ret", "key", "dataUriToBuffer", "uri", "firstComma", "meta", "charset", "base64", "type", "typeFull", "i", "encoding", "data", "buffer", "dist_default", "init_dist", "__esmMin", "noop", "typeIsObject", "x", "rethrowAssertionErrorRejection", "setFunctionName", "fn", "name", "originalPromise", "originalPromiseThen", "originalPromiseReject", "newPromise", "executor", "promiseResolvedWith", "value", "resolve", "promiseRejectedWith", "reason", "PerformPromiseThen", "promise", "onFulfilled", "onRejected", "uponPromise", "uponFulfillment", "uponRejection", "transformPromiseWith", "fulfillmentHandler", "rejectionHandler", "setPromiseIsHandledToTrue", "_queueMicrotask", "callback", "resolvedPromise", "cb", "reflectCall", "F", "V", "args", "promiseCall", "QUEUE_MAX_ARRAY_SIZE", "SimpleQueue", "element", "oldBack", "newBack", "oldFront", "newFront", "oldCursor", "newCursor", "elements", "i", "node", "front", "cursor", "AbortSteps", "ErrorSteps", "CancelSteps", "PullSteps", "ReleaseSteps", "ReadableStreamReaderGenericInitialize", "reader", "stream", "defaultReaderClosedPromiseInitialize", "defaultReaderClosedPromiseInitializeAsResolved", "defaultReaderClosedPromiseInitializeAsRejected", "ReadableStreamReaderGenericCancel", "ReadableStreamCancel", "ReadableStreamReaderGenericRelease", "defaultReaderClosedPromiseReject", "defaultReaderClosedPromiseResetToRejected", "readerLockException", "reject", "defaultReaderClosedPromiseResolve", "NumberIsFinite", "MathTrunc", "v", "isDictionary", "assertDictionary", "obj", "context", "assertFunction", "isObject", "assertObject", "assertRequiredArgument", "position", "assertRequiredField", "field", "convertUnrestrictedDouble", "censorNegativeZero", "integerPart", "convertUnsignedLongLongWithEnforceRange", "upperBound", "assertReadableStream", "IsReadableStream", "AcquireReadableStreamDefaultReader", "ReadableStreamDefaultReader", "ReadableStreamAddReadRequest", "readRequest", "ReadableStreamFulfillReadRequest", "chunk", "done", "ReadableStreamGetNumReadRequests", "ReadableStreamHasDefaultReader", "IsReadableStreamDefaultReader", "IsReadableStreamLocked", "defaultReaderBrandCheckException", "resolvePromise", "rejectPromise", "ReadableStreamDefaultReaderRead", "e", "ReadableStreamDefaultReaderRelease", "ReadableStreamDefaultReaderErrorReadRequests", "readRequests", "AsyncIteratorPrototype", "ReadableStreamAsyncIteratorImpl", "preventCancel", "nextSteps", "returnSteps", "queueMicrotask", "result", "ReadableStreamAsyncIteratorPrototype", "IsReadableStreamAsyncIterator", "streamAsyncIteratorBrandCheckException", "AcquireReadableStreamAsyncIterator", "impl", "iterator", "NumberIsNaN", "CreateArrayFromList", "CopyDataBlockBytes", "dest", "destOffset", "src", "srcOffset", "n", "TransferArrayBuffer", "O", "buffer", "IsDetachedBuffer", "ArrayBufferSlice", "begin", "end", "length", "slice", "GetMethod", "receiver", "prop", "func", "CreateAsyncFromSyncIterator", "syncIteratorRecord", "syncIterable", "asyncIterator", "nextMethod", "SymbolAsyncIterator", "_c", "_a", "_b", "GetIterator", "hint", "method", "syncMethod", "IteratorNext", "iteratorRecord", "IteratorComplete", "iterResult", "IteratorValue", "IsNonNegativeNumber", "CloneAsUint8Array", "DequeueValue", "container", "pair", "EnqueueValueWithSize", "size", "PeekQueueValue", "ResetQueue", "isDataViewConstructor", "ctor", "isDataView", "view", "arrayBufferViewElementSize", "ReadableStreamBYOBRequest", "IsReadableStreamBYOBRequest", "byobRequestBrandCheckException", "bytesWritten", "ReadableByteStreamControllerRespond", "ReadableByteStreamControllerRespondWithNewView", "ReadableByteStreamController", "IsReadableByteStreamController", "byteStreamControllerBrandCheckException", "ReadableByteStreamControllerGetBYOBRequest", "ReadableByteStreamControllerGetDesiredSize", "state", "ReadableByteStreamControllerClose", "ReadableByteStreamControllerEnqueue", "ReadableByteStreamControllerError", "ReadableByteStreamControllerClearPendingPullIntos", "ReadableByteStreamControllerClearAlgorithms", "ReadableByteStreamControllerFillReadRequestFromQueue", "autoAllocateChunkSize", "bufferE", "pullIntoDescriptor", "ReadableByteStreamControllerCallPullIfNeeded", "firstPullInto", "controller", "ReadableByteStreamControllerShouldCallPull", "pullPromise", "ReadableByteStreamControllerInvalidateBYOBRequest", "ReadableByteStreamControllerCommitPullIntoDescriptor", "filledView", "ReadableByteStreamControllerConvertPullIntoDescriptor", "ReadableStreamFulfillReadIntoRequest", "bytesFilled", "elementSize", "ReadableByteStreamControllerEnqueueChunkToQueue", "byteOffset", "byteLength", "ReadableByteStreamControllerEnqueueClonedChunkToQueue", "clonedChunk", "cloneE", "ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue", "firstDescriptor", "ReadableByteStreamControllerShiftPendingPullInto", "ReadableByteStreamControllerFillPullIntoDescriptorFromQueue", "maxBytesToCopy", "maxBytesFilled", "totalBytesToCopyRemaining", "ready", "remainderBytes", "maxAlignedBytes", "queue", "headOfQueue", "bytesToCopy", "destStart", "ReadableByteStreamControllerFillHeadPullIntoDescriptor", "ReadableByteStreamControllerHandleQueueDrain", "ReadableStreamClose", "ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue", "ReadableByteStreamControllerProcessReadRequestsUsingQueue", "ReadableByteStreamControllerPullInto", "min", "readIntoRequest", "minimumFill", "ReadableStreamAddReadIntoRequest", "emptyView", "ReadableByteStreamControllerRespondInClosedState", "ReadableStreamHasBYOBReader", "ReadableStreamGetNumReadIntoRequests", "ReadableByteStreamControllerRespondInReadableState", "remainderSize", "ReadableByteStreamControllerRespondInternal", "firstPendingPullInto", "transferredBuffer", "transferredView", "ReadableStreamError", "entry", "byobRequest", "SetUpReadableStreamBYOBRequest", "viewByteLength", "SetUpReadableByteStreamController", "startAlgorithm", "pullAlgorithm", "cancelAlgorithm", "highWaterMark", "startResult", "r", "SetUpReadableByteStreamControllerFromUnderlyingSource", "underlyingByteSource", "request", "convertReaderOptions", "options", "mode", "convertReadableStreamReaderMode", "convertByobReadOptions", "AcquireReadableStreamBYOBReader", "ReadableStreamBYOBReader", "IsReadableStreamBYOBReader", "byobReaderBrandCheckException", "rawOptions", "ReadableStreamBYOBReaderRead", "ReadableStreamBYOBReaderRelease", "ReadableStreamBYOBReaderErrorReadIntoRequests", "readIntoRequests", "ExtractHighWaterMark", "strategy", "defaultHWM", "ExtractSizeAlgorithm", "convertQueuingStrategy", "init", "convertQueuingStrategySize", "convertUnderlyingSink", "original", "abort", "close", "start", "type", "write", "convertUnderlyingSinkAbortCallback", "convertUnderlyingSinkCloseCallback", "convertUnderlyingSinkStartCallback", "convertUnderlyingSinkWriteCallback", "assertWritableStream", "IsWritableStream", "isAbortSignal", "supportsAbortController", "createAbortController", "WritableStream", "rawUnderlyingSink", "rawStrategy", "underlyingSink", "InitializeWritableStream", "sizeAlgorithm", "SetUpWritableStreamDefaultControllerFromUnderlyingSink", "streamBrandCheckException", "IsWritableStreamLocked", "WritableStreamAbort", "WritableStreamCloseQueuedOrInFlight", "WritableStreamClose", "AcquireWritableStreamDefaultWriter", "WritableStreamDefaultWriter", "CreateWritableStream", "writeAlgorithm", "closeAlgorithm", "abortAlgorithm", "WritableStreamDefaultController", "SetUpWritableStreamDefaultController", "wasAlreadyErroring", "WritableStreamStartErroring", "closeRequest", "writer", "defaultWriterReadyPromiseResolve", "WritableStreamDefaultControllerClose", "WritableStreamAddWriteRequest", "writeRequest", "WritableStreamDealWithRejection", "error", "WritableStreamFinishErroring", "WritableStreamDefaultWriterEnsureReadyPromiseRejected", "WritableStreamHasOperationMarkedInFlight", "storedError", "WritableStreamRejectCloseAndClosedPromiseIfNeeded", "abortRequest", "WritableStreamFinishInFlightWrite", "WritableStreamFinishInFlightWriteWithError", "WritableStreamFinishInFlightClose", "defaultWriterClosedPromiseResolve", "WritableStreamFinishInFlightCloseWithError", "WritableStreamMarkCloseRequestInFlight", "WritableStreamMarkFirstWriteRequestInFlight", "defaultWriterClosedPromiseReject", "WritableStreamUpdateBackpressure", "backpressure", "defaultWriterReadyPromiseReset", "defaultWriterReadyPromiseInitialize", "defaultWriterReadyPromiseInitializeAsResolved", "defaultWriterClosedPromiseInitialize", "defaultWriterReadyPromiseInitializeAsRejected", "defaultWriterClosedPromiseInitializeAsResolved", "defaultWriterClosedPromiseInitializeAsRejected", "IsWritableStreamDefaultWriter", "defaultWriterBrandCheckException", "defaultWriterLockException", "WritableStreamDefaultWriterGetDesiredSize", "WritableStreamDefaultWriterAbort", "WritableStreamDefaultWriterClose", "WritableStreamDefaultWriterRelease", "WritableStreamDefaultWriterWrite", "WritableStreamDefaultWriterCloseWithErrorPropagation", "WritableStreamDefaultWriterEnsureClosedPromiseRejected", "defaultWriterClosedPromiseResetToRejected", "defaultWriterReadyPromiseReject", "defaultWriterReadyPromiseResetToRejected", "WritableStreamDefaultControllerGetDesiredSize", "releasedError", "chunkSize", "WritableStreamDefaultControllerGetChunkSize", "WritableStreamDefaultControllerWrite", "closeSentinel", "IsWritableStreamDefaultController", "defaultControllerBrandCheckException", "WritableStreamDefaultControllerError", "WritableStreamDefaultControllerClearAlgorithms", "WritableStreamDefaultControllerGetBackpressure", "startPromise", "WritableStreamDefaultControllerAdvanceQueueIfNeeded", "chunkSizeE", "WritableStreamDefaultControllerErrorIfNeeded", "enqueueE", "WritableStreamDefaultControllerProcessClose", "WritableStreamDefaultControllerProcessWrite", "sinkClosePromise", "sinkWritePromise", "getGlobals", "globals", "isDOMExceptionConstructor", "getFromGlobal", "createPolyfill", "message", "DOMException", "ReadableStreamPipeTo", "source", "preventClose", "preventAbort", "signal", "shuttingDown", "currentWrite", "actions", "shutdownWithAction", "action", "pipeLoop", "resolveLoop", "rejectLoop", "next", "pipeStep", "resolveRead", "rejectRead", "isOrBecomesErrored", "shutdown", "isOrBecomesClosed", "destClosed", "waitForWritesToFinish", "oldCurrentWrite", "originalIsError", "originalError", "doTheRest", "finalize", "newError", "isError", "ReadableStreamDefaultController", "IsReadableStreamDefaultController", "ReadableStreamDefaultControllerGetDesiredSize", "ReadableStreamDefaultControllerCanCloseOrEnqueue", "ReadableStreamDefaultControllerClose", "ReadableStreamDefaultControllerEnqueue", "ReadableStreamDefaultControllerError", "ReadableStreamDefaultControllerClearAlgorithms", "ReadableStreamDefaultControllerCallPullIfNeeded", "ReadableStreamDefaultControllerShouldCallPull", "ReadableStreamDefaultControllerHasBackpressure", "SetUpReadableStreamDefaultController", "SetUpReadableStreamDefaultControllerFromUnderlyingSource", "underlyingSource", "ReadableStreamTee", "cloneForBranch2", "ReadableByteStreamTee", "ReadableStreamDefaultTee", "reading", "readAgain", "canceled1", "canceled2", "reason1", "reason2", "branch1", "branch2", "resolveCancelPromise", "cancelPromise", "chunk1", "chunk2", "cancel1Algorithm", "compositeReason", "cancelResult", "cancel2Algorithm", "CreateReadableStream", "readAgainForBranch1", "readAgainForBranch2", "forwardReaderError", "thisReader", "pullWithDefaultReader", "pull1Algorithm", "pull2Algorithm", "pullWithBYOBReader", "forBranch2", "byobBranch", "otherBranch", "byobCanceled", "otherCanceled", "CreateReadableByteStream", "isReadableStreamLike", "ReadableStreamFrom", "ReadableStreamFromDefaultReader", "ReadableStreamFromIterable", "asyncIterable", "nextResult", "nextPromise", "returnMethod", "returnResult", "returnPromise", "readPromise", "readResult", "convertUnderlyingDefaultOrByteSource", "cancel", "pull", "convertUnderlyingSourceCancelCallback", "convertUnderlyingSourcePullCallback", "convertUnderlyingSourceStartCallback", "convertReadableStreamType", "convertIteratorOptions", "convertPipeOptions", "assertAbortSignal", "convertReadableWritablePair", "readable", "writable", "ReadableStream", "rawUnderlyingSource", "InitializeReadableStream", "rawTransform", "transform", "destination", "branches", "sourceCancelPromise", "convertQueuingStrategyInit", "byteLengthSizeFunction", "ByteLengthQueuingStrategy", "IsByteLengthQueuingStrategy", "byteLengthBrandCheckException", "countSizeFunction", "CountQueuingStrategy", "IsCountQueuingStrategy", "countBrandCheckException", "convertTransformer", "flush", "readableType", "writableType", "convertTransformerCancelCallback", "convertTransformerFlushCallback", "convertTransformerStartCallback", "convertTransformerTransformCallback", "TransformStream", "rawTransformer", "rawWritableStrategy", "rawReadableStrategy", "writableStrategy", "readableStrategy", "transformer", "readableHighWaterMark", "readableSizeAlgorithm", "writableHighWaterMark", "writableSizeAlgorithm", "startPromise_resolve", "InitializeTransformStream", "SetUpTransformStreamDefaultControllerFromTransformer", "IsTransformStream", "TransformStreamDefaultSinkWriteAlgorithm", "TransformStreamDefaultSinkAbortAlgorithm", "TransformStreamDefaultSinkCloseAlgorithm", "TransformStreamDefaultSourcePullAlgorithm", "TransformStreamDefaultSourceCancelAlgorithm", "TransformStreamSetBackpressure", "TransformStreamError", "TransformStreamErrorWritableAndUnblockWrite", "TransformStreamDefaultControllerClearAlgorithms", "TransformStreamUnblockWrite", "TransformStreamDefaultController", "IsTransformStreamDefaultController", "readableController", "TransformStreamDefaultControllerEnqueue", "TransformStreamDefaultControllerError", "TransformStreamDefaultControllerTerminate", "SetUpTransformStreamDefaultController", "transformAlgorithm", "flushAlgorithm", "transformResultE", "TransformStreamDefaultControllerPerformTransform", "transformPromise", "backpressureChangePromise", "defaultControllerFinishPromiseReject", "defaultControllerFinishPromiseResolve", "flushPromise", "require_streams", "__commonJSMin", "process", "emitWarning", "error", "Blob", "params", "position", "blob", "ctrl", "buffer", "toIterator", "parts", "clone", "part", "position", "end", "size", "POOL_SIZE", "chunk", "b", "buffer", "import_streams", "_Blob", "Blob", "fetch_blob_default", "init_fetch_blob", "__esmMin", "#parts", "#type", "#size", "#endings", "blobParts", "options", "encoder", "element", "type", "decoder", "str", "data", "offset", "it", "ctrl", "start", "relativeStart", "relativeEnd", "span", "added", "blob", "object", "_File", "File", "file_default", "init_file", "__esmMin", "init_fetch_blob", "fetch_blob_default", "#lastModified", "#name", "fileBits", "fileName", "options", "lastModified", "object", "formDataToBlob", "F", "B", "fetch_blob_default", "b", "r", "c", "p", "v", "n", "e", "t", "i", "h", "m", "f", "x", "FormData", "init_esm_min", "__esmMin", "init_fetch_blob", "init_file", "a", "file_default", "#d", "o", "l", "d", "FetchBaseError", "init_base", "__esmMin", "message", "type", "FetchError", "init_fetch_error", "__esmMin", "init_base", "FetchBaseError", "message", "type", "systemError", "NAME", "isURLSearchParameters", "isBlob", "isAbortSignal", "isDomainOrSubdomain", "isSameProtocol", "init_is", "__esmMin", "object", "destination", "original", "orig", "dest", "require_node_domexception", "__commonJSMin", "exports", "module", "MessageChannel", "port", "ab", "err", "statSync", "createReadStream", "fs", "basename", "import_node_domexception", "stat", "blobFromSync", "blobFrom", "fileFrom", "fileFromSync", "fromBlob", "fromFile", "BlobDataItem", "init_from", "__esmMin", "init_file", "init_fetch_blob", "path", "type", "fetch_blob_default", "file_default", "_BlobDataItem", "#path", "#start", "options", "start", "end", "mtimeMs", "DOMException", "multipart_parser_exports", "__export", "toFormData", "_fileName", "headerValue", "m", "match", "filename", "code", "Body", "ct", "parser", "MultipartParser", "headerField", "entryValue", "entryName", "contentType", "entryChunks", "formData", "FormData", "onPartData", "ui8a", "decoder", "appendToFile", "appendFileToFormData", "file", "file_default", "appendEntryToFormData", "chunk", "s", "S", "f", "F", "LF", "CR", "SPACE", "HYPHEN", "COLON", "A", "Z", "lower", "noop", "init_multipart_parser", "__esmMin", "init_from", "init_esm_min", "c", "boundary", "i", "data", "length_", "previousIndex", "lookbehind", "boundaryChars", "index", "state", "flags", "boundaryLength", "boundaryEnd", "bufferLength", "cl", "mark", "name", "clear", "callback", "callbackSymbol", "start", "end", "dataCallback", "markSymbol", "_lookbehind", "Stream", "PassThrough", "types", "deprecate", "promisify", "Buffer", "consumeBody", "data", "INTERNALS", "body", "accum", "accumBytes", "chunk", "error", "FetchError", "FetchBaseError", "c", "pipeline", "Body", "clone", "getNonSpecFormDataBoundary", "extractContentType", "getTotalBytes", "writeToStream", "init_body", "__esmMin", "init_fetch_blob", "init_esm_min", "init_fetch_error", "init_base", "init_is", "size", "boundary", "isURLSearchParameters", "isBlob", "FormData", "formDataToBlob", "stream", "error_", "buffer", "byteOffset", "byteLength", "ct", "formData", "parameters", "name", "value", "toFormData", "buf", "fetch_blob_default", "text", "instance", "highWaterMark", "p1", "p2", "request", "dest", "types", "http", "fromRawHeaders", "headers", "Headers", "result", "value", "index", "array", "name", "validateHeaderName", "validateHeaderValue", "init_headers", "__esmMin", "error", "_Headers", "init", "raw", "values", "method", "pair", "target", "p", "receiver", "callback", "thisArg", "key", "property", "redirectStatus", "isRedirect", "init_is_redirect", "__esmMin", "code", "INTERNALS", "Response", "init_response", "__esmMin", "init_headers", "init_body", "init_is_redirect", "_Response", "Body", "body", "options", "status", "headers", "Headers", "contentType", "extractContentType", "clone", "url", "isRedirect", "response", "data", "init", "getSearch", "init_get_search", "__esmMin", "parsedURL", "lastOffset", "hash", "isIP", "stripURLForUseAsAReferrer", "url", "originOnly", "validateReferrerPolicy", "referrerPolicy", "ReferrerPolicy", "isOriginPotentiallyTrustworthy", "hostIp", "hostIPVersion", "isUrlPotentiallyTrustworthy", "determineRequestsReferrer", "request", "referrerURLCallback", "referrerOriginCallback", "policy", "referrerSource", "referrerURL", "referrerOrigin", "currentURL", "parseReferrerPolicyFromHeader", "headers", "policyTokens", "token", "DEFAULT_REFERRER_POLICY", "init_referrer", "__esmMin", "formatUrl", "deprecate", "INTERNALS", "isRequest", "doBadDataWarn", "Request", "getNodeRequestOptions", "init_request", "__esmMin", "init_headers", "init_body", "init_is", "init_get_search", "init_referrer", "object", "_Request", "Body", "input", "init", "parsedURL", "method", "inputBody", "clone", "headers", "Headers", "contentType", "extractContentType", "signal", "isAbortSignal", "referrer", "parsedReferrer", "referrerPolicy", "validateReferrerPolicy", "request", "contentLengthValue", "totalBytes", "getTotalBytes", "DEFAULT_REFERRER_POLICY", "determineRequestsReferrer", "agent", "search", "getSearch", "options", "AbortError", "init_abort_error", "__esmMin", "init_base", "FetchBaseError", "message", "type", "src_exports", "__export", "AbortError", "fetch_blob_default", "FetchError", "file_default", "FormData", "Headers", "Request", "Response", "blobFrom", "blobFromSync", "fetch", "fileFrom", "fileFromSync", "isRedirect", "http", "https", "zlib", "Stream", "PassThrough", "pump", "Buffer", "url", "options_", "resolve", "reject", "request", "parsedURL", "options", "getNodeRequestOptions", "supportedSchemas", "data", "dist_default", "response", "send", "signal", "abort", "error", "abortAndFinalize", "finalize", "request_", "fixResponseChunkedTransferBadEnding", "s", "endedWithEventsCount", "hadError", "response_", "headers", "fromRawHeaders", "location", "locationURL", "requestOptions", "clone", "isDomainOrSubdomain", "isSameProtocol", "name", "responseReferrerPolicy", "parseReferrerPolicyFromHeader", "body", "responseOptions", "codings", "zlibOptions", "raw", "chunk", "writeToStream", "errorCallback", "LAST_CHUNK", "isChunkedTransfer", "properLastChunkReceived", "previousChunk", "socket", "onSocketClose", "onData", "buf", "init_src", "__esmMin", "init_dist", "init_body", "init_response", "init_headers", "init_request", "init_fetch_error", "init_abort_error", "init_is_redirect", "init_esm_min", "init_is", "init_referrer", "init_from", "extend_1", "__importDefault", "https_1", "common_js_1", "retry_js_1", "stream_1", "interceptor_js_1", "randomUUID", "Gaxios", "defaults", "args", "input", "init", "url", "headers", "_a", "opts", "prepared", "#prepareRequest", "#applyRequestInterceptors", "#applyResponseInterceptors", "config", "fetchImpl", "#getFetch", "preparedOpts", "res", "data", "translatedResponse", "response", "chunk", "errorInfo", "e", "err", "shouldRetry", "#appendTimeoutToSignal", "#urlMayUseProxy", "noProxy", "candidate", "noProxyList", "noProxyEnvList", "rule", "cleanedRule", "options", "promiseChain", "interceptor", "preparedHeaders", "additionalQueryParams", "prefix", "key", "value", "shouldDirectlyPassData", "boundary", "proxy", "HttpsProxyAgent", "#getProxyAgent", "timeoutSignal", "status", "contentType", "multipartOptions", "finale", "currentPart", "partContentType", "#proxyAgent", "#fetch", "hasWindow", "base", "append", "exports", "exports", "request", "gaxios_js_1", "common_js_1", "__exportStar", "opts", "require_bignumber", "__commonJSMin", "exports", "module", "globalObject", "BigNumber", "isNumeric", "mathceil", "mathfloor", "bignumberError", "tooManyDigits", "BASE", "LOG_BASE", "MAX_SAFE_INTEGER", "POWS_TEN", "SQRT_BASE", "MAX", "clone", "configObject", "div", "convertBase", "parseNumeric", "P", "ONE", "DECIMAL_PLACES", "ROUNDING_MODE", "TO_EXP_NEG", "TO_EXP_POS", "MIN_EXP", "MAX_EXP", "CRYPTO", "MODULO_MODE", "POW_PRECISION", "FORMAT", "ALPHABET", "alphabetHasNormalDecimalDigits", "v", "b", "alphabet", "c", "caseChanged", "e", "i", "isNum", "len", "str", "x", "intCheck", "round", "obj", "p", "n", "s", "out", "maxOrMin", "pow2_53", "random53bitInt", "dp", "a", "k", "rand", "args", "sum", "decimal", "toBaseOut", "baseIn", "baseOut", "j", "arr", "arrL", "sign", "callerIsToString", "d", "r", "xc", "y", "rm", "toFixedPoint", "coeffToString", "multiply", "base", "m", "temp", "xlo", "xhi", "carry", "klo", "khi", "compare", "aL", "bL", "cmp", "subtract", "more", "prod", "prodL", "q", "qc", "rem", "remL", "rem0", "xi", "xL", "yc0", "yL", "yz", "yc", "bitFloor", "format", "id", "c0", "ne", "toExponential", "normalise", "basePrefix", "dotAfter", "dotBefore", "isInfinityOrNaN", "whitespaceOrPlus", "p1", "p2", "sd", "ni", "rd", "pows10", "valueOf", "half", "isModExp", "nIsBig", "nIsNeg", "nIsOdd", "isOdd", "t", "xLTy", "xe", "ye", "xcL", "ycL", "ylo", "yhi", "zc", "sqrtBase", "rep", "g1", "g2", "groupSeparator", "intPart", "fractionPart", "isNeg", "intDigits", "md", "d0", "d1", "d2", "exp", "n0", "n1", "z", "l", "min", "max", "name", "zs", "require_stringify", "__commonJSMin", "exports", "module", "BigNumber", "JSON", "f", "n", "cx", "escapable", "gap", "indent", "meta", "rep", "quote", "string", "a", "c", "str", "key", "holder", "i", "k", "v", "length", "mind", "partial", "value", "isBigNumber", "replacer", "space", "require_parse", "__commonJSMin", "exports", "module", "BigNumber", "suspectProtoRx", "suspectConstructorRx", "json_parse", "options", "_options", "at", "ch", "escapee", "text", "error", "m", "next", "c", "number", "string", "hex", "i", "uffff", "startAt", "white", "word", "value", "array", "object", "key", "source", "reviver", "result", "walk", "holder", "k", "v", "require_json_bigint", "__commonJSMin", "exports", "module", "json_stringify", "json_parse", "options", "exports", "isGoogleCloudServerless", "isGoogleComputeEngineLinux", "isGoogleComputeEngineMACAddress", "isGoogleComputeEngine", "detectGCPResidency", "fs_1", "os_1", "GCE_MAC_ADDRESS_REGEX", "biosVendor", "interfaces", "item", "mac", "Colours", "_Colours", "stream", "exports", "exports", "getNodeBackend", "getDebugBackend", "getStructuredBackend", "setBackend", "log", "events_1", "process", "__importStar", "util", "colours_1", "LogSeverity", "AdhocDebugLogger", "namespace", "upstream", "event", "listener", "args", "fields", "severity", "DebugLogBackendBase", "nodeFlag", "_a", "logger", "e", "NodeBackend", "nscolour", "pid", "level", "msg", "filteredFields", "fieldsJson", "fieldsColour", "regexp", "DebugBackend", "pkg", "debugLogger", "existingFilters", "debugPkg", "StructuredBackend", "json", "jsonString", "loggerCache", "cachedBackend", "backend", "parent", "existing", "previousBackend", "__exportStar", "exports", "exports", "instance", "project", "universe", "bulk", "isAvailable", "resetIsAvailableCache", "getGCPResidency", "setGCPResidency", "requestTimeout", "gaxios_1", "jsonBigint", "gcp_residency_1", "logger", "__importStar", "log", "getBaseUrl", "baseUrl", "validate", "options", "key", "metadataAccessor", "type", "noResponseRetries", "fastFail", "headers", "metadataKey", "params", "value", "requestMethod", "fastFailMetadataRequest", "req", "res", "metadataFlavor", "secondaryOptions", "r1", "r2", "properties", "r", "item", "detectGCPAvailableRetries", "cachedIsAvailableResponse", "e", "err", "code", "__exportStar", "require_base64_js", "__commonJSMin", "exports", "byteLength", "toByteArray", "fromByteArray", "lookup", "revLookup", "Arr", "code", "i", "len", "getLens", "b64", "validLen", "placeHoldersLen", "lens", "_byteLength", "tmp", "arr", "curByte", "tripletToBase64", "num", "encodeChunk", "uint8", "start", "end", "output", "extraBytes", "parts", "maxChunkLength", "len2", "require_shared", "__commonJSMin", "exports", "fromArrayBufferToHex", "arrayBuffer", "byte", "require_crypto", "__commonJSMin", "exports", "base64js", "shared_1", "BrowserCrypto", "_BrowserCrypto", "str", "inputBuffer", "outputBuffer", "count", "array", "base64", "pubkey", "data", "signature", "algo", "dataArray", "signatureArray", "cryptoKey", "privateKey", "result", "uint8array", "text", "key", "msg", "rawKey", "enc", "require_crypto", "__commonJSMin", "exports", "crypto", "NodeCrypto", "str", "count", "pubkey", "data", "signature", "verifier", "privateKey", "signer", "base64", "text", "key", "msg", "cryptoKey", "toBuffer", "toArrayBuffer", "buffer", "arrayBuffer", "require_crypto", "__commonJSMin", "exports", "__createBinding", "o", "m", "k", "k2", "desc", "__exportStar", "p", "createCrypto", "hasBrowserCrypto", "crypto_1", "crypto_2", "require_safe_buffer", "__commonJSMin", "exports", "module", "buffer", "Buffer", "copyProps", "src", "dst", "key", "SafeBuffer", "arg", "encodingOrOffset", "length", "size", "fill", "encoding", "buf", "require_param_bytes_for_alg", "__commonJSMin", "exports", "module", "getParamSize", "keySize", "result", "paramBytesForAlg", "getParamBytesForAlg", "alg", "paramBytes", "require_ecdsa_sig_formatter", "__commonJSMin", "exports", "module", "Buffer", "getParamBytesForAlg", "MAX_OCTET", "CLASS_UNIVERSAL", "PRIMITIVE_BIT", "TAG_SEQ", "TAG_INT", "ENCODED_TAG_SEQ", "ENCODED_TAG_INT", "base64Url", "base64", "signatureAsBuffer", "signature", "derToJose", "alg", "paramBytes", "maxEncodedParamLength", "inputLength", "offset", "seqLength", "rLength", "rOffset", "sLength", "sOffset", "rPadding", "sPadding", "dst", "o", "countPadding", "buf", "start", "stop", "padding", "needsSign", "joseToDer", "signatureBytes", "rsBytes", "shortLength", "require_util", "__commonJSMin", "exports", "snakeToCamel", "originalOrCamelOptions", "removeUndefinedValuesInObject", "isValidFile", "getWellKnownCertificateConfigFileLocation", "fs", "os", "path", "WELL_KNOWN_CERTIFICATE_CONFIG_FILE", "CLOUDSDK_CONFIG_DIRECTORY", "str", "match", "obj", "get", "key", "o", "LRUCache", "#cache", "options", "#moveToEnd", "value", "#evict", "item", "cutoffDate", "oldestItem", "object", "filePath", "configDir", "_isWindows", "require_package", "__commonJSMin", "exports", "module", "require_shared", "__commonJSMin", "exports", "pkg", "PRODUCT_NAME", "USER_AGENT", "require_authclient", "__commonJSMin", "exports", "events_1", "gaxios_1", "util_1", "google_logging_utils_1", "shared_cjs_1", "AuthClient", "_AuthClient", "opts", "options", "args", "input", "init", "url", "headers", "credentials", "target", "source", "xGoogUserProject", "authorizationHeader", "config", "nodeVersion", "userAgent", "symbols", "methodName", "logId", "logObject", "response", "error", "require_loginticket", "__commonJSMin", "exports", "LoginTicket", "env", "pay", "payload", "require_oauth2client", "__commonJSMin", "exports", "gaxios_1", "querystring", "stream", "formatEcdsa", "util_1", "crypto_1", "authclient_1", "loginticket_1", "CodeChallengeMethod", "CertificateFormat", "ClientAuthentication", "OAuth2Client", "_OAuth2Client", "options", "clientSecret", "redirectUri", "opts", "crypto", "codeVerifier", "codeChallenge", "codeOrOptions", "callback", "r", "e", "url", "headers", "values", "basic", "res", "tokens", "refreshToken", "p", "data", "refreshedAccessToken", "thisCreds", "err", "credentials", "token", "reAuthRetried", "statusCode", "mayRequireRefresh", "mayRequireRefreshWithNoRefreshToken", "isReadableStream", "isAuthErr", "response", "accessToken", "info", "nowTime", "format", "cacheControl", "cacheAge", "maxAge", "certificates", "key", "now", "jwt", "certs", "requiredAudience", "issuers", "maxExpiry", "segments", "signed", "signature", "envelope", "payload", "cert", "iat", "exp", "earliest", "latest", "aud", "audVerified", "accessTokenResponse", "expiryDate", "require_computeclient", "__commonJSMin", "exports", "gaxios_1", "gcpMetadata", "oauth2client_1", "Compute", "options", "tokenPath", "data", "instanceOptions", "e", "tokens", "targetAudience", "idTokenPath", "idToken", "res", "require_idtokenclient", "__commonJSMin", "exports", "oauth2client_1", "IdTokenClient", "options", "idToken", "payloadB64", "require_envDetect", "__commonJSMin", "exports", "clear", "getEnv", "gcpMetadata", "GCPEnv", "envPromise", "getEnvMemoized", "env", "isAppEngine", "isCloudFunction", "isComputeEngine", "isKubernetesEngine", "isCloudRun", "require_data_stream", "__commonJSMin", "exports", "module", "Buffer", "Stream", "util", "DataStream", "data", "require_buffer_equal_constant_time", "__commonJSMin", "exports", "module", "Buffer", "SlowBuffer", "bufferEq", "a", "b", "c", "i", "that", "origBufEqual", "origSlowBufEqual", "require_jwa", "__commonJSMin", "exports", "module", "Buffer", "crypto", "formatEcdsa", "util", "MSG_INVALID_ALGORITHM", "MSG_INVALID_SECRET", "MSG_INVALID_VERIFIER_KEY", "MSG_INVALID_SIGNER_KEY", "supportsKeyObjects", "checkIsPublicKey", "key", "typeError", "checkIsPrivateKey", "checkIsSecretKey", "fromBase64", "base64", "toBase64", "base64url", "padding", "i", "template", "args", "errMsg", "bufferOrString", "obj", "normalizeInput", "thing", "createHmacSigner", "bits", "secret", "hmac", "sig", "bufferEqual", "timingSafeEqual", "a", "b", "createHmacVerifier", "signature", "computedSig", "createKeySigner", "privateKey", "signer", "createKeyVerifier", "publicKey", "verifier", "createPSSKeySigner", "createPSSKeyVerifier", "createECDSASigner", "inner", "createECDSAVerifer", "result", "createNoneSigner", "createNoneVerifier", "algorithm", "signerFactories", "verifierFactories", "match", "algo", "require_tostring", "__commonJSMin", "exports", "module", "Buffer", "obj", "require_sign_stream", "__commonJSMin", "exports", "module", "Buffer", "DataStream", "jwa", "Stream", "toString", "util", "base64url", "string", "encoding", "jwsSecuredInput", "header", "payload", "encodedHeader", "encodedPayload", "jwsSign", "opts", "secretOrKey", "algo", "securedInput", "signature", "SignStream", "secret", "secretStream", "e", "require_verify_stream", "__commonJSMin", "exports", "module", "Buffer", "DataStream", "jwa", "Stream", "toString", "util", "JWS_REGEX", "isObject", "thing", "safeJsonParse", "headerFromJWS", "jwsSig", "encodedHeader", "securedInputFromJWS", "signatureFromJWS", "payloadFromJWS", "encoding", "payload", "isValidJws", "string", "jwsVerify", "algorithm", "secretOrKey", "err", "signature", "securedInput", "algo", "jwsDecode", "opts", "header", "VerifyStream", "secretStream", "valid", "obj", "e", "require_jws", "__commonJSMin", "exports", "SignStream", "VerifyStream", "ALGORITHMS", "opts", "require_src", "__commonJSMin", "exports", "fs", "_interopRequireWildcard", "_gaxios", "jws", "path", "_util", "e", "t", "r", "o", "i", "f", "_typeof", "_t3", "_classPrivateMethodInitSpec", "a", "_checkPrivateRedeclaration", "_classPrivateFieldInitSpec", "_classPrivateFieldSet", "s", "_assertClassBrand", "_classPrivateFieldGet", "n", "_defineProperties", "_toPropertyKey", "_createClass", "_classCallCheck", "_callSuper", "_getPrototypeOf", "_possibleConstructorReturn", "_isNativeReflectConstruct", "_assertThisInitialized", "_inherits", "_setPrototypeOf", "_wrapNativeSuper", "_isNativeFunction", "Wrapper", "_construct", "p", "_defineProperty", "_toPrimitive", "_regenerator", "c", "Generator", "u", "_regeneratorDefine2", "y", "G", "d", "l", "GeneratorFunction", "GeneratorFunctionPrototype", "asyncGeneratorStep", "_asyncToGenerator", "_next", "_throw", "readFile", "_callee", "_context", "ErrorWithCode", "GOOGLE_TOKEN_URL", "GOOGLE_REVOKE_TOKEN_URL", "_Error", "message", "code", "_this", "_inFlightRequest", "_GoogleToken_brand", "GoogleToken", "_options", "opts", "_configure", "now", "_this$eagerRefreshThr", "eagerRefreshThresholdMillis", "callback", "cb", "_getTokenAsync", "_getCredentials", "_callee2", "keyFile", "ext", "key", "body", "privateKey", "clientEmail", "_privateKey", "_t", "_context2", "getCredentials", "_x", "_revokeTokenAsync", "_x2", "_getTokenAsync2", "_callee3", "_context3", "_getTokenAsyncInner", "_x3", "_getTokenAsyncInner2", "_callee4", "creds", "_context4", "_ensureEmail", "_requestToken", "_revokeTokenAsync2", "_callee5", "url", "_context5", "options", "_requestToken2", "_callee6", "iat", "additionalClaims", "payload", "signedJWT", "_response", "_response2", "desc", "_t2", "_context6", "require_jwtaccess", "__commonJSMin", "exports", "jws", "util_1", "DEFAULT_HEADER", "JWTAccess", "_JWTAccess", "email", "key", "keyId", "eagerRefreshThresholdMillis", "url", "scopes", "cacheKey", "additionalClaims", "cachedToken", "now", "iat", "exp", "defaultClaims", "claim", "header", "payload", "signedJWT", "headers", "json", "inputStream", "callback", "resolve", "reject", "s", "chunk", "data", "err", "require_jwtclient", "__commonJSMin", "exports", "gtoken_1", "jwtaccess_1", "oauth2client_1", "authclient_1", "JWT", "_JWT", "options", "scopes", "jwt", "url", "useSelfSignedJWT", "tokens", "useScopes", "headers", "targetAudience", "gtoken", "callback", "r", "result", "json", "inputStream", "resolve", "reject", "s", "chunk", "data", "e", "apiKey", "creds", "require_refreshclient", "__commonJSMin", "exports", "oauth2client_1", "authclient_1", "UserRefreshClient", "_UserRefreshClient", "optionsOrClientId", "clientSecret", "refreshToken", "eagerRefreshThresholdMillis", "forceRefreshOnFailure", "opts", "targetAudience", "json", "inputStream", "callback", "resolve", "reject", "s", "chunk", "data", "err", "client", "require_impersonated", "__commonJSMin", "exports", "oauth2client_1", "gaxios_1", "util_1", "Impersonated", "_Impersonated", "options", "blobToSign", "name", "u", "body", "res", "tokenResponse", "error", "status", "message", "targetAudience", "require_oauth2common", "__commonJSMin", "exports", "getErrorFromOAuthErrorResponse", "gaxios_1", "crypto_1", "METHODS_SUPPORTING_REQUEST_BODY", "OAuthClientAuthHandler", "#crypto", "#clientAuthentication", "options", "opts", "bearerToken", "clientId", "clientSecret", "base64EncodedCreds", "method", "contentType", "data", "resp", "err", "errorCode", "errorDescription", "errorUri", "message", "newError", "keys", "key", "require_stscredentials", "__commonJSMin", "exports", "gaxios_1", "authclient_1", "oauth2common_1", "util_1", "StsCredentials", "_StsCredentials", "#tokenExchangeEndpoint", "options", "clientAuthentication", "stsCredentialsOptions", "headers", "values", "opts", "response", "stsSuccessfulResponse", "error", "require_baseexternalclient", "__commonJSMin", "exports", "gaxios_1", "stream", "authclient_1", "sts", "util_1", "shared_cjs_1", "STS_GRANT_TYPE", "STS_REQUEST_TOKEN_TYPE", "DEFAULT_OAUTH_SCOPE", "DEFAULT_TOKEN_LIFESPAN", "WORKFORCE_AUDIENCE_PATTERN", "DEFAULT_TOKEN_URL", "BaseExternalAccountClient", "_BaseExternalAccountClient", "#pendingAccessToken", "options", "opts", "type", "clientId", "clientSecret", "subjectTokenType", "workforcePoolUserProject", "serviceAccountImpersonationUrl", "serviceAccountImpersonation", "serviceAccountImpersonationLifetime", "workforceAudiencePattern", "credentials", "accessTokenResponse", "headers", "callback", "r", "e", "projectNumber", "response", "reAuthRetried", "requestHeaders", "res", "statusCode", "isReadableStream", "#internalRefreshAccessTokenAsync", "subjectToken", "stsCredentialsOptions", "additionalOptions", "additionalHeaders", "stsResponse", "audience", "match", "token", "successResponse", "accessToken", "now", "nodeVersion", "saImpersonation", "credentialSourceType", "require_filesubjecttokensupplier", "__commonJSMin", "exports", "util_1", "fs", "readFile", "realpath", "lstat", "FileSubjectTokenSupplier", "opts", "parsedFilePath", "err", "subjectToken", "rawText", "require_urlsubjecttokensupplier", "__commonJSMin", "exports", "authclient_1", "UrlSubjectTokenSupplier", "opts", "context", "subjectToken", "require_certificatesubjecttokensupplier", "__commonJSMin", "exports", "util_1", "fs", "crypto_1", "https", "CertificateSourceUnavailableError", "message", "InvalidConfigurationError", "CertificateSubjectTokenSupplier", "opts", "#resolveCertificateConfigFilePath", "certPath", "keyPath", "#getCertAndKeyPaths", "#getKeyAndCert", "#processChainFromPaths", "overridePath", "envPath", "wellKnownPath", "configPath", "fileContents", "config", "e", "cert", "key", "err", "leafCertBuffer", "leafCert", "chainCerts", "pem", "index", "leafIndex", "chainCert", "finalChain", "require_identitypoolclient", "__commonJSMin", "exports", "baseexternalclient_1", "util_1", "filesubjecttokensupplier_1", "urlsubjecttokensupplier_1", "certificatesubjecttokensupplier_1", "stscredentials_1", "gaxios_1", "IdentityPoolClient", "_IdentityPoolClient", "options", "opts", "credentialSource", "subjectTokenSupplier", "credentialSourceOpts", "formatOpts", "formatType", "formatSubjectTokenFieldName", "file", "url", "certificate", "headers", "certificateSubjecttokensupplier", "subjectToken", "mtlsAgent", "require_awsrequestsigner", "__commonJSMin", "exports", "gaxios_1", "crypto_1", "AWS_ALGORITHM", "AWS_REQUEST_TYPE", "AwsRequestSigner", "getCredentials", "region", "amzOptions", "requestPayloadData", "url", "method", "requestPayload", "additionalAmzHeaders", "awsSecurityCredentials", "uri", "headerMap", "generateAuthenticationHeaderMap", "headers", "awsSignedReq", "sign", "crypto", "key", "msg", "getSigningKey", "dateStamp", "serviceName", "kDate", "kRegion", "kService", "options", "now", "amzDate", "amzHeaders", "canonicalHeaders", "signedHeadersList", "signedHeaders", "payloadHash", "canonicalRequest", "credentialScope", "stringToSign", "signingKey", "signature", "authorizationHeader", "require_defaultawssecuritycredentialssupplier", "__commonJSMin", "exports", "authclient_1", "DefaultAwsSecurityCredentialsSupplier", "opts", "context", "#regionFromEnv", "metadataHeaders", "#getImdsV2SessionToken", "response", "#securityCredentialsFromEnv", "roleName", "#getAwsRoleName", "awsCreds", "#retrieveAwsSecurityCredentials", "transporter", "headers", "require_awsclient", "__commonJSMin", "exports", "awsrequestsigner_1", "baseexternalclient_1", "defaultawssecuritycredentialssupplier_1", "util_1", "gaxios_1", "AwsClient", "_AwsClient", "#DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL", "options", "opts", "credentialSource", "awsSecurityCredentialsSupplier", "credentialSourceOpts", "regionUrl", "securityCredentialsUrl", "imdsV2SessionTokenUrl", "match", "reformattedHeader", "value", "key", "require_executable_response", "__commonJSMin", "exports", "SAML_SUBJECT_TOKEN_TYPE", "OIDC_SUBJECT_TOKEN_TYPE1", "OIDC_SUBJECT_TOKEN_TYPE2", "ExecutableResponse", "responseJson", "InvalidVersionFieldError", "InvalidSuccessFieldError", "InvalidTokenTypeFieldError", "InvalidSubjectTokenError", "InvalidCodeFieldError", "InvalidMessageFieldError", "ExecutableResponseError", "message", "InvalidExpirationTimeFieldError", "require_pluggable_auth_handler", "__commonJSMin", "exports", "executable_response_1", "childProcess", "fs", "ExecutableError", "message", "code", "PluggableAuthHandler", "_PluggableAuthHandler", "options", "envMap", "resolve", "reject", "child", "output", "data", "err", "timeout", "responseJson", "response", "error", "filePath", "responseString", "command", "components", "i", "require_pluggable_auth_client", "__commonJSMin", "exports", "baseexternalclient_1", "executable_response_1", "pluggable_auth_handler_1", "pluggable_auth_handler_2", "DEFAULT_EXECUTABLE_TIMEOUT_MILLIS", "MINIMUM_EXECUTABLE_TIMEOUT_MILLIS", "MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS", "GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES", "MAXIMUM_EXECUTABLE_VERSION", "PluggableAuthClient", "options", "executableResponse", "envMap", "serviceAccountEmail", "require_externalclient", "__commonJSMin", "exports", "baseexternalclient_1", "identitypoolclient_1", "awsclient_1", "pluggable_auth_client_1", "ExternalAccountClient", "options", "require_externalAccountAuthorizedUserClient", "__commonJSMin", "exports", "authclient_1", "oauth2common_1", "gaxios_1", "stream", "baseexternalclient_1", "DEFAULT_TOKEN_URL", "ExternalAccountAuthorizedUserHandler", "_ExternalAccountAuthorizedUserHandler", "#tokenRefreshEndpoint", "options", "refreshToken", "headers", "opts", "response", "tokenRefreshResponse", "error", "ExternalAccountAuthorizedUserClient", "clientAuthentication", "accessTokenResponse", "callback", "r", "e", "reAuthRetried", "requestHeaders", "res", "statusCode", "isReadableStream", "refreshResponse", "credentials", "now", "require_googleauth", "__commonJSMin", "exports", "child_process_1", "fs", "gaxios_1", "gcpMetadata", "os", "path", "crypto_1", "computeclient_1", "idtokenclient_1", "envDetect_1", "jwtclient_1", "refreshclient_1", "impersonated_1", "externalclient_1", "baseexternalclient_1", "authclient_1", "externalAccountAuthorizedUserClient_1", "util_1", "GoogleAuth", "#pendingAuthClient", "opts", "client", "callback", "r", "projectId", "universeDomain", "e", "optionsOrCallback", "options", "#prepareAndCacheClient", "credential", "quotaProjectIdOverride", "credentialsPath", "location", "home", "filePath", "err", "readStream", "json", "sourceClient", "targetPrincipal", "targetScopes", "preferredUniverseDomain", "inputStream", "resolve", "reject", "chunks", "chunk", "data", "apiKey", "sys", "stdout", "creds", "serviceAccountEmail", "client_email", "universe_domain", "#determineClient", "stream", "targetAudience", "url", "headers", "args", "endpoint", "universe", "crypto", "emailOrUniqueId", "require_iam", "__commonJSMin", "exports", "IAMAuth", "selector", "token", "require_downscopedclient", "__commonJSMin", "exports", "gaxios_1", "stream", "authclient_1", "sts", "STS_GRANT_TYPE", "STS_REQUEST_TOKEN_TYPE", "STS_SUBJECT_TOKEN_TYPE", "DownscopedClient", "options", "credentialAccessBoundary", "rule", "credentials", "accessTokenResponse", "headers", "opts", "callback", "r", "e", "reAuthRetried", "response", "requestHeaders", "res", "statusCode", "isReadableStream", "subjectToken", "stsCredentialsOptions", "stsResponse", "sourceCredExpireDate", "expiryDate", "downscopedAccessToken", "now", "require_passthrough", "__commonJSMin", "exports", "authclient_1", "PassThroughClient", "opts", "require_src", "__commonJSMin", "exports", "googleauth_1", "authclient_1", "computeclient_1", "envDetect_1", "iam_1", "idtokenclient_1", "jwtaccess_1", "jwtclient_1", "impersonated_1", "oauth2client_1", "loginticket_1", "refreshclient_1", "awsclient_1", "awsrequestsigner_1", "identitypoolclient_1", "externalclient_1", "baseexternalclient_1", "downscopedclient_1", "pluggable_auth_client_1", "passthrough_1", "auth", "Fastify", "cors", "import_json5", "readFileSync", "existsSync", "join", "config", "ConfigService", "options", "jsonPath", "jsonContent", "jsonConfig", "JSON5", "error", "envPath", "result", "envConfig", "env", "parsed", "path", "key", "defaultValue", "value", "summary", "createApiError", "message", "statusCode", "code", "type", "error", "errorHandler", "request", "reply", "response", "ProxyAgent", "sendUnifiedRequest", "url", "request", "config", "logger", "headers", "key", "value", "combinedSignal", "timeoutSignal", "controller", "abortHandler", "fetchOptions", "version", "handleTransformerEndpoint", "req", "reply", "fastify", "transformer", "body", "providerName", "provider", "createApiError", "requestBody", "config", "bypass", "processRequestTransformers", "response", "sendRequestToProvider", "finalResponse", "processResponseTransformers", "formatResponse", "headers", "shouldBypassTransformers", "transformOut", "providerTransformer", "transformIn", "modelTransformer", "url", "auth", "sendUnifiedRequest", "errorText", "registerApiRoutes", "version", "transformersWithEndpoint", "request", "name", "baseUrl", "apiKey", "models", "isValidUrl", "LLMService", "providerService", "request", "id", "updates", "enabled", "modelName", "route", "provider", "model", "ProviderService", "configService", "transformerService", "logger", "providersConfig", "providerConfig", "transformer", "key", "Constructor", "transformerInstance", "error", "request", "provider", "model", "fullModel", "route", "name", "id", "updates", "updatedProvider", "enabled", "modelName", "modelNames", "transformerConfig", "acc", "item", "config", "models", "byteToHex", "i", "unsafeStringify", "arr", "offset", "randomFillSync", "rnds8Pool", "poolPtr", "rng", "randomUUID", "native_default", "v4", "options", "buf", "offset", "native_default", "rnds", "rng", "i", "unsafeStringify", "v4_default", "getThinkLevel", "thinking_budget", "AnthropicTransformer", "request", "provider", "messages", "textParts", "item", "msg", "index", "toolParts", "c", "tool", "toolIndex", "toolMessage", "textAndMediaParts", "part", "assistantMessage", "text", "toolCallParts", "result", "getThinkLevel", "response", "context", "convertedStream", "data", "anthropicResponse", "tools", "openaiStream", "controller", "encoder", "messageId", "stopReasonMessageDelta", "model", "hasStarted", "hasTextContentStarted", "hasFinished", "toolCalls", "toolCallIndexToContentBlockIndex", "totalChunks", "contentChunks", "toolCallChunks", "isClosed", "isThinkingStarted", "contentIndex", "currentContentBlockIndex", "safeEnqueue", "dataStr", "error", "safeClose", "contentBlockStop", "messageStop", "reader", "decoder", "buffer", "done", "value", "lines", "line", "chunk", "errorMessage", "messageStart", "choice", "contentBlockStart", "thinkingSignature", "thinkingChunk", "anthropicChunk", "annotation", "v4_default", "processedInThisChunk", "toolCall", "toolCallIndex", "newContentBlockIndex", "toolCallId", "toolCallName", "toolCallInfo", "existingToolCall", "blockIndex", "currentToolCall", "fixedArgument", "fixedChunk", "fixError", "parseError", "controllerError", "releaseError", "reason", "openaiResponse", "content", "id", "parsedInput", "argumentsStr", "createApiError", "Type", "flattenTypeArrayToAnyOf", "typeList", "resultingSchema", "listWithoutNull", "type", "upperCaseType", "i", "processJsonSchema", "_jsonSchema", "genAISchema", "schemaFieldNames", "listSchemaFieldNames", "dictSchemaFieldNames", "incomingAnyOf", "fieldName", "fieldValue", "upperCaseValue", "listSchemaFieldValue", "item", "dictSchemaFieldValue", "key", "value", "tTool", "tool", "functionDeclaration", "buildRequestBody", "request", "tools", "functionDeclarations", "body", "message", "role", "parts", "content", "toolCall", "toolConfig", "transformRequestOut", "contents", "model", "max_tokens", "temperature", "stream", "tool_choice", "unifiedChatRequest", "part", "transformResponseOut", "response", "providerName", "logger", "jsonResponse", "tool_calls", "res", "decoder", "encoder", "processLine", "line", "controller", "chunkStr", "chunk", "candidate", "groundingChunk", "index", "support", "error", "reader", "buffer", "done", "lines", "GeminiTransformer", "request", "provider", "buildRequestBody", "transformRequestOut", "response", "transformResponseOut", "getAccessToken", "GoogleAuth", "error", "VertexGeminiTransformer", "request", "provider", "projectId", "location", "keyContent", "credentials", "accessToken", "buildRequestBody", "transformRequestOut", "response", "transformResponseOut", "DeepseekTransformer", "request", "response", "jsonResponse", "decoder", "encoder", "reasoningContent", "isReasoningComplete", "buffer", "stream", "controller", "reader", "processBuffer", "lines", "line", "processLine", "context", "data", "thinkingChunk", "thinkingLine", "signature", "modifiedLine", "done", "value", "chunk", "content", "val", "error", "e", "TooluseTransformer", "request", "response", "jsonResponse", "toolCall", "toolArguments", "decoder", "encoder", "exitToolIndex", "exitToolResponse", "buffer", "stream", "controller", "reader", "processBuffer", "lines", "line", "processLine", "context", "setExitToolIndex", "appendExitToolResponse", "data", "modifiedLine", "done", "value", "chunk", "val", "content", "error", "e", "OpenrouterTransformer", "options", "request", "msg", "item", "response", "jsonResponse", "decoder", "encoder", "hasTextContent", "reasoningContent", "isReasoningComplete", "hasToolCall", "buffer", "stream", "controller", "reader", "processBuffer", "lines", "line", "processLine", "context", "jsonStr", "data", "thinkingChunk", "thinkingLine", "signature", "tool", "v4_default", "modifiedLine", "done", "value", "chunk", "decodeError", "val", "content", "error", "e", "MaxTokenTransformer", "options", "request", "GroqTransformer", "request", "msg", "item", "tool", "response", "jsonResponse", "decoder", "encoder", "hasTextContent", "reasoningContent", "isReasoningComplete", "buffer", "stream", "controller", "reader", "processBuffer", "lines", "line", "processLine", "context", "jsonStr", "data", "v4_default", "modifiedLine", "done", "value", "chunk", "decodeError", "val", "content", "error", "e", "CleancacheTransformer", "request", "msg", "item", "import_json5", "JSONRepairError", "Error", "constructor", "message", "position", "isHex", "char", "test", "isDigit", "isValidStringCharacter", "isDelimiter", "includes", "isFunctionNameCharStart", "isFunctionNameChar", "regexUrlStart", "regexUrlChar", "isUnquotedStringDelimiter", "isStartOfValue", "isQuote", "regexStartOfValue", "isControlCharacter", "isWhitespace", "text", "index", "code", "charCodeAt", "codeSpace", "codeNewline", "codeTab", "codeReturn", "isWhitespaceExceptNewline", "isSpecialWhitespace", "codeNonBreakingSpace", "codeEnQuad", "codeHairSpace", "codeNarrowNoBreakSpace", "codeMediumMathematicalSpace", "codeIdeographicSpace", "isDoubleQuoteLike", "isSingleQuoteLike", "isDoubleQuote", "isSingleQuote", "stripLastOccurrence", "textToStrip", "stripRemainingText", "arguments", "length", "undefined", "lastIndexOf", "substring", "insertBeforeLastWhitespace", "textToInsert", "removeAtIndex", "start", "count", "endsWithCommaOrNewline", "controlCharacters", "escapeCharacters", "b", "f", "n", "r", "t", "jsonrepair", "text", "i", "output", "parseMarkdownCodeBlock", "parseValue", "throwUnexpectedEnd", "processedComma", "parseCharacter", "parseWhitespaceAndSkipComments", "isStartOfValue", "endsWithCommaOrNewline", "insertBeforeLastWhitespace", "parseNewlineDelimitedJSON", "stripLastOccurrence", "length", "throwUnexpectedCharacter", "processed", "parseObject", "parseArray", "parseString", "parseNumber", "parseKeywords", "parseUnquotedString", "parseRegex", "skipNewline", "arguments", "undefined", "start", "changed", "parseWhitespace", "parseComment", "_isWhiteSpace", "isWhitespace", "isWhitespaceExceptNewline", "whitespace", "isSpecialWhitespace", "atEndOfBlockComment", "blocks", "skipMarkdownCodeBlock", "isFunctionNameCharStart", "isFunctionNameChar", "block", "end", "slice", "char", "skipCharacter", "skipEscapeCharacter", "skipEllipsis", "initial", "throwObjectKeyExpected", "processedColon", "truncatedText", "throwColonExpected", "processedValue", "stopAtDelimiter", "stopAtIndex", "skipEscapeChars", "isQuote", "isEndQuote", "isDoubleQuote", "isSingleQuote", "isSingleQuoteLike", "isDoubleQuoteLike", "iBefore", "oBefore", "str", "iPrev", "prevNonWhitespaceIndex", "isDelimiter", "charAt", "substring", "iQuote", "oQuote", "isDigit", "parseConcatenatedString", "iPrevChar", "prevChar", "isUnquotedStringDelimiter", "regexUrlStart", "test", "regexUrlChar", "j", "isHex", "throwInvalidUnicodeCharacter", "isControlCharacter", "isValidStringCharacter", "throwInvalidCharacter", "removeAtIndex", "atEndOfNumber", "repairNumberEndingWithNumericSymbol", "num", "hasInvalidLeadingZero", "parseKeyword", "name", "value", "isKey", "symbol", "JSON", "stringify", "prev", "JSONRepairError", "chars", "parseToolArguments", "argsString", "logger", "jsonError", "args", "JSON5", "json5Error", "repairedJson", "jsonrepair", "repairError", "EnhanceToolTransformer", "response", "jsonResponse", "toolCall", "parseToolArguments", "decoder", "encoder", "currentToolCall", "hasTextContent", "reasoningContent", "isReasoningComplete", "hasToolCall", "buffer", "stream", "controller", "reader", "processBuffer", "lines", "line", "processCompletedToolCall", "data", "finalArgs", "e", "delta", "modifiedData", "modifiedLine", "processLine", "context", "jsonStr", "toolCallDelta", "done", "value", "chunk", "decodeError", "val", "content", "error", "ReasoningTransformer", "options", "request", "response", "jsonResponse", "decoder", "encoder", "reasoningContent", "isReasoningComplete", "buffer", "stream", "controller", "reader", "processBuffer", "lines", "line", "processLine", "context", "data", "thinkingChunk", "thinkingLine", "signature", "modifiedLine", "done", "value", "chunk", "content", "val", "error", "e", "SamplingTransformer", "options", "request", "MaxCompletionTokens", "request", "buildRequestBody", "request", "messages", "i", "message", "isLastMessage", "isAssistantMessage", "content", "item", "requestBody", "tool", "transformRequestOut", "vertexRequest", "result", "msg", "transformResponseOut", "response", "providerName", "logger", "jsonResponse", "tool_calls", "res", "decoder", "encoder", "processLine", "line", "controller", "chunkStr", "chunk", "error", "stream", "reader", "buffer", "done", "value", "lines", "getAccessToken", "GoogleAuth", "error", "VertexClaudeTransformer", "request", "provider", "projectId", "location", "keyContent", "credentials", "accessToken", "buildRequestBody", "transformRequestOut", "response", "transformResponseOut", "convertContentToString", "content", "item", "CerebrasTransformer", "request", "provider", "transformedRequest", "systemContent", "message", "transformedMessage", "response", "StreamOptionsTransformer", "request", "transformer_default", "AnthropicTransformer", "GeminiTransformer", "VertexGeminiTransformer", "VertexClaudeTransformer", "DeepseekTransformer", "TooluseTransformer", "OpenrouterTransformer", "MaxTokenTransformer", "GroqTransformer", "CleancacheTransformer", "EnhanceToolTransformer", "ReasoningTransformer", "SamplingTransformer", "MaxCompletionTokens", "CerebrasTransformer", "StreamOptionsTransformer", "TransformerService", "configService", "logger", "name", "transformer", "result", "config", "module", "__require", "instance", "error", "transformer_default", "TransformerStatic", "transformerInstance", "transformers", "createApp", "logger", "fastify", "Fastify", "errorHandler", "cors", "Server", "options", "ConfigService", "TransformerService", "ProviderService", "LLMService", "plugin", "hookName", "hookFunction", "request", "reply", "done", "req", "body", "provider", "model", "err", "registerApiRoutes", "address", "shutdown", "signal", "error", "server_default"] +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/thread-stream-worker.mjs b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/thread-stream-worker.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d64e3d2adc43d6aefce4486d49557ee861b753b5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/thread-stream-worker.mjs @@ -0,0 +1,2 @@ +var I=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var R=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var D=R((B,w)=>{var X=new Function("modulePath","return import(modulePath)");function q(e){return typeof __non_webpack__require__=="function"?__non_webpack__require__(e):I(e)}w.exports={realImport:X,realRequire:q}});var M=R((L,T)=>{"use strict";T.exports={WRITE_INDEX:4,READ_INDEX:8}});var y=R((P,h)=>{"use strict";function U(e,t,r,_,i){let A=Date.now()+_,s=Atomics.load(e,t);if(s===r){i(null,"ok");return}let u=s,l=E=>{Date.now()>A?i(null,"timed-out"):setTimeout(()=>{u=s,s=Atomics.load(e,t),s===u?l(E>=1e3?1e3:E*2):s===r?i(null,"ok"):i(null,"not-equal")},E)};l(1)}function x(e,t,r,_,i){let A=Date.now()+_,s=Atomics.load(e,t);if(s!==r){i(null,"ok");return}let u=l=>{Date.now()>A?i(null,"timed-out"):setTimeout(()=>{s=Atomics.load(e,t),s!==r?i(null,"ok"):u(l>=1e3?1e3:l*2)},l)};u(1)}h.exports={wait:U,waitDiff:x}});var{realImport:k,realRequire:f}=D(),{workerData:g,parentPort:p}=I("worker_threads"),{WRITE_INDEX:m,READ_INDEX:n}=M(),{waitDiff:N}=y(),{dataBuf:W,filename:a,stateBuf:S}=g,c,o=new Int32Array(S),O=Buffer.from(W);async function C(){let e;try{a.endsWith(".ts")||a.endsWith(".cts")?(process[Symbol.for("ts-node.register.instance")]?process.env.TS_NODE_DEV&&f("ts-node-dev"):f("ts-node/register"),e=f(decodeURIComponent(a.replace(process.platform==="win32"?"file:///":"file://","")))):e=await k(a)}catch(t){if((t.code==="ENOTDIR"||t.code==="ERR_MODULE_NOT_FOUND")&&a.startsWith("file://"))e=f(decodeURIComponent(a.replace("file://","")));else if(t.code===void 0||t.code==="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING")try{e=f(decodeURIComponent(a.replace(process.platform==="win32"?"file:///":"file://","")))}catch{throw t}else throw t}typeof e=="object"&&(e=e.default),typeof e=="object"&&(e=e.default),c=await e(g.workerData),c.on("error",function(t){Atomics.store(o,m,-2),Atomics.notify(o,m),Atomics.store(o,n,-2),Atomics.notify(o,n),p.postMessage({code:"ERROR",err:t})}),c.on("close",function(){let t=Atomics.load(o,m);Atomics.store(o,n,t),Atomics.notify(o,n),setImmediate(()=>{process.exit(0)})})}C().then(function(){p.postMessage({code:"READY"}),process.nextTick(d)});function d(){let e=Atomics.load(o,n),t=Atomics.load(o,m);if(t===e){t===O.length?N(o,n,t,1/0,d):N(o,m,t,1/0,d);return}if(t===-1){c.end();return}let r=O.toString("utf8",e,t);c.write(r)?(Atomics.store(o,n,t),Atomics.notify(o,n),setImmediate(d)):c.once("drain",function(){Atomics.store(o,n,t),Atomics.notify(o,n),d()})}process.on("unhandledRejection",function(e){p.postMessage({code:"ERROR",err:e}),process.exit(1)});process.on("uncaughtException",function(e){p.postMessage({code:"ERROR",err:e}),process.exit(1)});process.once("exit",e=>{if(e!==0){process.exit(e);return}c?.writableNeedDrain&&!c?.writableEnded&&p.postMessage({code:"WARNING",err:new Error("ThreadStream: process exited before destination stream was drained. this may indicate that the destination stream try to write to a another missing stream")}),process.exit(0)}); +//# sourceMappingURL=thread-stream-worker.mjs.map diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/thread-stream-worker.mjs.map b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/thread-stream-worker.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..7efae79baa4d2dcc75a8b2adccfa61903655fccc --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/dist/esm/thread-stream-worker.mjs.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../node_modules/.pnpm/real-require@0.2.0/node_modules/real-require/src/index.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/indexes.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/wait.js", "../../node_modules/.pnpm/thread-stream@3.1.0/node_modules/thread-stream/lib/worker.js"], + "sourcesContent": ["/* eslint-disable no-new-func, camelcase */\n/* globals __non_webpack__require__ */\n\nconst realImport = new Function('modulePath', 'return import(modulePath)')\n\nfunction realRequire(modulePath) {\n if (typeof __non_webpack__require__ === 'function') {\n return __non_webpack__require__(modulePath)\n }\n\n return require(modulePath)\n}\n\nmodule.exports = { realImport, realRequire }\n", "'use strict'\n\nconst WRITE_INDEX = 4\nconst READ_INDEX = 8\n\nmodule.exports = {\n WRITE_INDEX,\n READ_INDEX\n}\n", "'use strict'\n\nconst MAX_TIMEOUT = 1000\n\nfunction wait (state, index, expected, timeout, done) {\n const max = Date.now() + timeout\n let current = Atomics.load(state, index)\n if (current === expected) {\n done(null, 'ok')\n return\n }\n let prior = current\n const check = (backoff) => {\n if (Date.now() > max) {\n done(null, 'timed-out')\n } else {\n setTimeout(() => {\n prior = current\n current = Atomics.load(state, index)\n if (current === prior) {\n check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)\n } else {\n if (current === expected) done(null, 'ok')\n else done(null, 'not-equal')\n }\n }, backoff)\n }\n }\n check(1)\n}\n\n// let waitDiffCount = 0\nfunction waitDiff (state, index, expected, timeout, done) {\n // const id = waitDiffCount++\n // process._rawDebug(`>>> waitDiff ${id}`)\n const max = Date.now() + timeout\n let current = Atomics.load(state, index)\n if (current !== expected) {\n done(null, 'ok')\n return\n }\n const check = (backoff) => {\n // process._rawDebug(`${id} ${index} current ${current} expected ${expected}`)\n // process._rawDebug('' + backoff)\n if (Date.now() > max) {\n done(null, 'timed-out')\n } else {\n setTimeout(() => {\n current = Atomics.load(state, index)\n if (current !== expected) {\n done(null, 'ok')\n } else {\n check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)\n }\n }, backoff)\n }\n }\n check(1)\n}\n\nmodule.exports = { wait, waitDiff }\n", "'use strict'\n\nconst { realImport, realRequire } = require('real-require')\nconst { workerData, parentPort } = require('worker_threads')\nconst { WRITE_INDEX, READ_INDEX } = require('./indexes')\nconst { waitDiff } = require('./wait')\n\nconst {\n dataBuf,\n filename,\n stateBuf\n} = workerData\n\nlet destination\n\nconst state = new Int32Array(stateBuf)\nconst data = Buffer.from(dataBuf)\n\nasync function start () {\n let worker\n try {\n if (filename.endsWith('.ts') || filename.endsWith('.cts')) {\n // TODO: add support for the TSM modules loader ( https://github.com/lukeed/tsm ).\n if (!process[Symbol.for('ts-node.register.instance')]) {\n realRequire('ts-node/register')\n } else if (process.env.TS_NODE_DEV) {\n realRequire('ts-node-dev')\n }\n // TODO: Support ES imports once tsc, tap & ts-node provide better compatibility guarantees.\n // Remove extra forwardslash on Windows\n worker = realRequire(decodeURIComponent(filename.replace(process.platform === 'win32' ? 'file:///' : 'file://', '')))\n } else {\n worker = (await realImport(filename))\n }\n } catch (error) {\n // A yarn user that tries to start a ThreadStream for an external module\n // provides a filename pointing to a zip file.\n // eg. require.resolve('pino-elasticsearch') // returns /foo/pino-elasticsearch-npm-6.1.0-0c03079478-6915435172.zip/bar.js\n // The `import` will fail to try to load it.\n // This catch block executes the `require` fallback to load the module correctly.\n // In fact, yarn modifies the `require` function to manage the zipped path.\n // More details at https://github.com/pinojs/pino/pull/1113\n // The error codes may change based on the node.js version (ENOTDIR > 12, ERR_MODULE_NOT_FOUND <= 12 )\n if ((error.code === 'ENOTDIR' || error.code === 'ERR_MODULE_NOT_FOUND') &&\n filename.startsWith('file://')) {\n worker = realRequire(decodeURIComponent(filename.replace('file://', '')))\n } else if (error.code === undefined || error.code === 'ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING') {\n // When bundled with pkg, an undefined error is thrown when called with realImport\n // When bundled with pkg and using node v20, an ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING error is thrown when called with realImport\n // More info at: https://github.com/pinojs/thread-stream/issues/143\n try {\n worker = realRequire(decodeURIComponent(filename.replace(process.platform === 'win32' ? 'file:///' : 'file://', '')))\n } catch {\n throw error\n }\n } else {\n throw error\n }\n }\n\n // Depending on how the default export is performed, and on how the code is\n // transpiled, we may find cases of two nested \"default\" objects.\n // See https://github.com/pinojs/pino/issues/1243#issuecomment-982774762\n if (typeof worker === 'object') worker = worker.default\n if (typeof worker === 'object') worker = worker.default\n\n destination = await worker(workerData.workerData)\n\n destination.on('error', function (err) {\n Atomics.store(state, WRITE_INDEX, -2)\n Atomics.notify(state, WRITE_INDEX)\n\n Atomics.store(state, READ_INDEX, -2)\n Atomics.notify(state, READ_INDEX)\n\n parentPort.postMessage({\n code: 'ERROR',\n err\n })\n })\n\n destination.on('close', function () {\n // process._rawDebug('worker close emitted')\n const end = Atomics.load(state, WRITE_INDEX)\n Atomics.store(state, READ_INDEX, end)\n Atomics.notify(state, READ_INDEX)\n setImmediate(() => {\n process.exit(0)\n })\n })\n}\n\n// No .catch() handler,\n// in case there is an error it goes\n// to unhandledRejection\nstart().then(function () {\n parentPort.postMessage({\n code: 'READY'\n })\n\n process.nextTick(run)\n})\n\nfunction run () {\n const current = Atomics.load(state, READ_INDEX)\n const end = Atomics.load(state, WRITE_INDEX)\n\n // process._rawDebug(`pre state ${current} ${end}`)\n\n if (end === current) {\n if (end === data.length) {\n waitDiff(state, READ_INDEX, end, Infinity, run)\n } else {\n waitDiff(state, WRITE_INDEX, end, Infinity, run)\n }\n return\n }\n\n // process._rawDebug(`post state ${current} ${end}`)\n\n if (end === -1) {\n // process._rawDebug('end')\n destination.end()\n return\n }\n\n const toWrite = data.toString('utf8', current, end)\n // process._rawDebug('worker writing: ' + toWrite)\n\n const res = destination.write(toWrite)\n\n if (res) {\n Atomics.store(state, READ_INDEX, end)\n Atomics.notify(state, READ_INDEX)\n setImmediate(run)\n } else {\n destination.once('drain', function () {\n Atomics.store(state, READ_INDEX, end)\n Atomics.notify(state, READ_INDEX)\n run()\n })\n }\n}\n\nprocess.on('unhandledRejection', function (err) {\n parentPort.postMessage({\n code: 'ERROR',\n err\n })\n process.exit(1)\n})\n\nprocess.on('uncaughtException', function (err) {\n parentPort.postMessage({\n code: 'ERROR',\n err\n })\n process.exit(1)\n})\n\nprocess.once('exit', exitCode => {\n if (exitCode !== 0) {\n process.exit(exitCode)\n return\n }\n if (destination?.writableNeedDrain && !destination?.writableEnded) {\n parentPort.postMessage({\n code: 'WARNING',\n err: new Error('ThreadStream: process exited before destination stream was drained. this may indicate that the destination stream try to write to a another missing stream')\n })\n }\n\n process.exit(0)\n})\n"], + "mappings": "uTAAA,IAAAA,EAAAC,EAAA,CAAAC,EAAAC,IAAA,CAGA,IAAMC,EAAa,IAAI,SAAS,aAAc,2BAA2B,EAEzE,SAASC,EAAYC,EAAY,CAC/B,OAAI,OAAO,0BAA6B,WAC/B,yBAAyBA,CAAU,EAGrCC,EAAQD,CAAU,CAC3B,CAEAH,EAAO,QAAU,C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AUA,EAAK,CAC7Cb,EAAW,YAAY,CACrB,KAAM,QACN,IAAAa,CACF,CAAC,EACD,QAAQ,KAAK,CAAC,CAChB,CAAC,EAED,QAAQ,KAAK,OAAQK,GAAY,CAC/B,GAAIA,IAAa,EAAG,CAClB,QAAQ,KAAKA,CAAQ,EACrB,MACF,CACIX,GAAa,mBAAqB,CAACA,GAAa,eAClDP,EAAW,YAAY,CACrB,KAAM,UACN,IAAK,IAAI,MAAM,4JAA4J,CAC7K,CAAC,EAGH,QAAQ,KAAK,CAAC,CAChB,CAAC", + "names": ["require_src", "__commonJSMin", "exports", "module", "realImport", "realRequire", "modulePath", "__require", "require_indexes", "__commonJSMin", "exports", "module", "require_wait", "__commonJSMin", "exports", "module", "wait", "state", "index", "expected", "timeout", "done", "max", "current", "prior", "check", "backoff", "waitDiff", "realImport", "realRequire", "workerData", "parentPort", "WRITE_INDEX", "READ_INDEX", "waitDiff", "dataBuf", "filename", "stateBuf", "destination", "state", "data", "start", "worker", "error", "err", "end", "run", "current", "toWrite", "exitCode"] +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/nodemon.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/nodemon.json new file mode 100644 index 0000000000000000000000000000000000000000..e106886a8974a0fa4f5b28ebd3025e02a43ca3ef --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/nodemon.json @@ -0,0 +1,6 @@ +{ + "watch": ["src"], + "ext": ".ts,.js", + "ignore": [], + "exec": "tsx src/server.ts" +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2270359a5b5619d95b25b340b16a862c30be47b7 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@musistudio/llms/package.json @@ -0,0 +1,55 @@ +{ + "name": "@musistudio/llms", + "version": "1.0.28", + "description": "A universal LLM API transformation server", + "main": "dist/cjs/server.cjs", + "module": "dist/esm/server.mjs", + "type": "module", + "exports": { + ".": { + "import": "./dist/esm/server.mjs", + "require": "./dist/cjs/server.cjs" + } + }, + "scripts": { + "tsx": "tsx", + "build": "tsx scripts/build.ts", + "build:watch": "tsx scripts/build.ts --watch", + "dev": "nodemon", + "start": "node dist/cjs/server.cjs", + "start:esm": "node dist/esm/server.mjs", + "lint": "eslint src --ext .ts,.tsx" + }, + "keywords": [], + "author": "", + "license": "MIT", + "dependencies": { + "@anthropic-ai/sdk": "^0.54.0", + "@fastify/cors": "^11.0.1", + "@google/genai": "^1.7.0", + "dotenv": "^16.5.0", + "fastify": "^5.4.0", + "google-auth-library": "^10.1.0", + "json5": "^2.2.3", + "jsonrepair": "^3.13.0", + "openai": "^5.6.0", + "undici": "^7.10.0", + "uuid": "^11.1.0" + }, + "devDependencies": { + "@types/chai": "^5.2.2", + "@types/mocha": "^10.0.10", + "@types/node": "^24.0.3", + "@types/sinon": "^17.0.4", + "@typescript-eslint/eslint-plugin": "^8.35.0", + "@typescript-eslint/parser": "^8.35.0", + "chai": "^5.2.0", + "esbuild": "^0.25.5", + "eslint": "^9.30.0", + "nodemon": "^3.1.10", + "sinon": "^21.0.0", + "tsx": "^4.20.3", + "typescript": "^5.8.3", + "typescript-eslint": "^8.35.0" + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/LICENSE b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..65a999460170355f6383b8f122da09e66e485165 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Denis Malinochkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/README.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e0b218b9f090cbf38b4a75f1f6b83b46bf8e4476 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/README.md @@ -0,0 +1,171 @@ +# @nodelib/fs.scandir + +> List files and directories inside the specified directory. + +## :bulb: Highlights + +The package is aimed at obtaining information about entries in the directory. + +* :moneybag: Returns useful information: `name`, `path`, `dirent` and `stats` (optional). +* :gear: On Node.js 10.10+ uses the mechanism without additional calls to determine the entry type. See [`old` and `modern` mode](#old-and-modern-mode). +* :link: Can safely work with broken symbolic links. + +## Install + +```console +npm install @nodelib/fs.scandir +``` + +## Usage + +```ts +import * as fsScandir from '@nodelib/fs.scandir'; + +fsScandir.scandir('path', (error, stats) => { /* … */ }); +``` + +## API + +### .scandir(path, [optionsOrSettings], callback) + +Returns an array of plain objects ([`Entry`](#entry)) with information about entry for provided path with standard callback-style. + +```ts +fsScandir.scandir('path', (error, entries) => { /* … */ }); +fsScandir.scandir('path', {}, (error, entries) => { /* … */ }); +fsScandir.scandir('path', new fsScandir.Settings(), (error, entries) => { /* … */ }); +``` + +### .scandirSync(path, [optionsOrSettings]) + +Returns an array of plain objects ([`Entry`](#entry)) with information about entry for provided path. + +```ts +const entries = fsScandir.scandirSync('path'); +const entries = fsScandir.scandirSync('path', {}); +const entries = fsScandir.scandirSync(('path', new fsScandir.Settings()); +``` + +#### path + +* Required: `true` +* Type: `string | Buffer | URL` + +A path to a file. If a URL is provided, it must use the `file:` protocol. + +#### optionsOrSettings + +* Required: `false` +* Type: `Options | Settings` +* Default: An instance of `Settings` class + +An [`Options`](#options) object or an instance of [`Settings`](#settingsoptions) class. + +> :book: When you pass a plain object, an instance of the `Settings` class will be created automatically. If you plan to call the method frequently, use a pre-created instance of the `Settings` class. + +### Settings([options]) + +A class of full settings of the package. + +```ts +const settings = new fsScandir.Settings({ followSymbolicLinks: false }); + +const entries = fsScandir.scandirSync('path', settings); +``` + +## Entry + +* `name` — The name of the entry (`unknown.txt`). +* `path` — The path of the entry relative to call directory (`root/unknown.txt`). +* `dirent` — An instance of [`fs.Dirent`](./src/types/index.ts) class. On Node.js below 10.10 will be emulated by [`DirentFromStats`](./src/utils/fs.ts) class. +* `stats` (optional) — An instance of `fs.Stats` class. + +For example, the `scandir` call for `tools` directory with one directory inside: + +```ts +{ + dirent: Dirent { name: 'typedoc', /* … */ }, + name: 'typedoc', + path: 'tools/typedoc' +} +``` + +## Options + +### stats + +* Type: `boolean` +* Default: `false` + +Adds an instance of `fs.Stats` class to the [`Entry`](#entry). + +> :book: Always use `fs.readdir` without the `withFileTypes` option. ??TODO?? + +### followSymbolicLinks + +* Type: `boolean` +* Default: `false` + +Follow symbolic links or not. Call `fs.stat` on symbolic link if `true`. + +### `throwErrorOnBrokenSymbolicLink` + +* Type: `boolean` +* Default: `true` + +Throw an error when symbolic link is broken if `true` or safely use `lstat` call if `false`. + +### `pathSegmentSeparator` + +* Type: `string` +* Default: `path.sep` + +By default, this package uses the correct path separator for your OS (`\` on Windows, `/` on Unix-like systems). But you can set this option to any separator character(s) that you want to use instead. + +### `fs` + +* Type: [`FileSystemAdapter`](./src/adapters/fs.ts) +* Default: A default FS methods + +By default, the built-in Node.js module (`fs`) is used to work with the file system. You can replace any method with your own. + +```ts +interface FileSystemAdapter { + lstat?: typeof fs.lstat; + stat?: typeof fs.stat; + lstatSync?: typeof fs.lstatSync; + statSync?: typeof fs.statSync; + readdir?: typeof fs.readdir; + readdirSync?: typeof fs.readdirSync; +} + +const settings = new fsScandir.Settings({ + fs: { lstat: fakeLstat } +}); +``` + +## `old` and `modern` mode + +This package has two modes that are used depending on the environment and parameters of use. + +### old + +* Node.js below `10.10` or when the `stats` option is enabled + +When working in the old mode, the directory is read first (`fs.readdir`), then the type of entries is determined (`fs.lstat` and/or `fs.stat` for symbolic links). + +### modern + +* Node.js 10.10+ and the `stats` option is disabled + +In the modern mode, reading the directory (`fs.readdir` with the `withFileTypes` option) is combined with obtaining information about its entries. An additional call for symbolic links (`fs.stat`) is still present. + +This mode makes fewer calls to the file system. It's faster. + +## Changelog + +See the [Releases section of our GitHub project](https://github.com/nodelib/nodelib/releases) for changelog for each release version. + +## License + +This software is released under the terms of the MIT license. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/adapters/fs.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/adapters/fs.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..827f1db09aac5d9f6b2e63d56a509ae67faaf0e6 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/adapters/fs.d.ts @@ -0,0 +1,20 @@ +import type * as fsStat from '@nodelib/fs.stat'; +import type { Dirent, ErrnoException } from '../types'; +export interface ReaddirAsynchronousMethod { + (filepath: string, options: { + withFileTypes: true; + }, callback: (error: ErrnoException | null, files: Dirent[]) => void): void; + (filepath: string, callback: (error: ErrnoException | null, files: string[]) => void): void; +} +export interface ReaddirSynchronousMethod { + (filepath: string, options: { + withFileTypes: true; + }): Dirent[]; + (filepath: string): string[]; +} +export declare type FileSystemAdapter = fsStat.FileSystemAdapter & { + readdir: ReaddirAsynchronousMethod; + readdirSync: ReaddirSynchronousMethod; +}; +export declare const FILE_SYSTEM_ADAPTER: FileSystemAdapter; +export declare function createFileSystemAdapter(fsMethods?: Partial): FileSystemAdapter; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/adapters/fs.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/adapters/fs.js new file mode 100644 index 0000000000000000000000000000000000000000..f0fe022023e6dfd5b56c33f2bac6d2d3b180e1c5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/adapters/fs.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; +const fs = require("fs"); +exports.FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + stat: fs.stat, + lstatSync: fs.lstatSync, + statSync: fs.statSync, + readdir: fs.readdir, + readdirSync: fs.readdirSync +}; +function createFileSystemAdapter(fsMethods) { + if (fsMethods === undefined) { + return exports.FILE_SYSTEM_ADAPTER; + } + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); +} +exports.createFileSystemAdapter = createFileSystemAdapter; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/constants.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..33f17497d43b391287e2c9fc65d1c7cb4668ea50 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/constants.d.ts @@ -0,0 +1,4 @@ +/** + * IS `true` for Node.js 10.10 and greater. + */ +export declare const IS_SUPPORT_READDIR_WITH_FILE_TYPES: boolean; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/constants.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..7e3d4411f751e190be8794b687e9fa60ef5fae06 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/constants.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0; +const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.'); +if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) { + throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`); +} +const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); +const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); +const SUPPORTED_MAJOR_VERSION = 10; +const SUPPORTED_MINOR_VERSION = 10; +const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION; +const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION; +/** + * IS `true` for Node.js 10.10 and greater. + */ +exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b9da83ed172315106269d96bb9043c922af68cc5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/index.d.ts @@ -0,0 +1,12 @@ +import type { FileSystemAdapter, ReaddirAsynchronousMethod, ReaddirSynchronousMethod } from './adapters/fs'; +import * as async from './providers/async'; +import Settings, { Options } from './settings'; +import type { Dirent, Entry } from './types'; +declare type AsyncCallback = async.AsyncCallback; +declare function scandir(path: string, callback: AsyncCallback): void; +declare function scandir(path: string, optionsOrSettings: Options | Settings, callback: AsyncCallback): void; +declare namespace scandir { + function __promisify__(path: string, optionsOrSettings?: Options | Settings): Promise; +} +declare function scandirSync(path: string, optionsOrSettings?: Options | Settings): Entry[]; +export { scandir, scandirSync, Settings, AsyncCallback, Dirent, Entry, FileSystemAdapter, ReaddirAsynchronousMethod, ReaddirSynchronousMethod, Options }; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/index.js new file mode 100644 index 0000000000000000000000000000000000000000..99c70d3d635f73d2704b02695933770401b14d37 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/index.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Settings = exports.scandirSync = exports.scandir = void 0; +const async = require("./providers/async"); +const sync = require("./providers/sync"); +const settings_1 = require("./settings"); +exports.Settings = settings_1.default; +function scandir(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + async.read(path, getSettings(), optionsOrSettingsOrCallback); + return; + } + async.read(path, getSettings(optionsOrSettingsOrCallback), callback); +} +exports.scandir = scandir; +function scandirSync(path, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + return sync.read(path, settings); +} +exports.scandirSync = scandirSync; +function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1.default) { + return settingsOrOptions; + } + return new settings_1.default(settingsOrOptions); +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/async.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/async.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5829676df7e302e14b87edf2d99c04b58384d0af --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/async.d.ts @@ -0,0 +1,7 @@ +/// +import type Settings from '../settings'; +import type { Entry } from '../types'; +export declare type AsyncCallback = (error: NodeJS.ErrnoException, entries: Entry[]) => void; +export declare function read(directory: string, settings: Settings, callback: AsyncCallback): void; +export declare function readdirWithFileTypes(directory: string, settings: Settings, callback: AsyncCallback): void; +export declare function readdir(directory: string, settings: Settings, callback: AsyncCallback): void; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/async.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/async.js new file mode 100644 index 0000000000000000000000000000000000000000..e8e2f0a9cba94ed06b7762f2846ab88330aaa44e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/async.js @@ -0,0 +1,104 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.readdir = exports.readdirWithFileTypes = exports.read = void 0; +const fsStat = require("@nodelib/fs.stat"); +const rpl = require("run-parallel"); +const constants_1 = require("../constants"); +const utils = require("../utils"); +const common = require("./common"); +function read(directory, settings, callback) { + if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + readdirWithFileTypes(directory, settings, callback); + return; + } + readdir(directory, settings, callback); +} +exports.read = read; +function readdirWithFileTypes(directory, settings, callback) { + settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => { + if (readdirError !== null) { + callFailureCallback(callback, readdirError); + return; + } + const entries = dirents.map((dirent) => ({ + dirent, + name: dirent.name, + path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) + })); + if (!settings.followSymbolicLinks) { + callSuccessCallback(callback, entries); + return; + } + const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); + rpl(tasks, (rplError, rplEntries) => { + if (rplError !== null) { + callFailureCallback(callback, rplError); + return; + } + callSuccessCallback(callback, rplEntries); + }); + }); +} +exports.readdirWithFileTypes = readdirWithFileTypes; +function makeRplTaskEntry(entry, settings) { + return (done) => { + if (!entry.dirent.isSymbolicLink()) { + done(null, entry); + return; + } + settings.fs.stat(entry.path, (statError, stats) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + done(statError); + return; + } + done(null, entry); + return; + } + entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); + done(null, entry); + }); + }; +} +function readdir(directory, settings, callback) { + settings.fs.readdir(directory, (readdirError, names) => { + if (readdirError !== null) { + callFailureCallback(callback, readdirError); + return; + } + const tasks = names.map((name) => { + const path = common.joinPathSegments(directory, name, settings.pathSegmentSeparator); + return (done) => { + fsStat.stat(path, settings.fsStatSettings, (error, stats) => { + if (error !== null) { + done(error); + return; + } + const entry = { + name, + path, + dirent: utils.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; + } + done(null, entry); + }); + }; + }); + rpl(tasks, (rplError, entries) => { + if (rplError !== null) { + callFailureCallback(callback, rplError); + return; + } + callSuccessCallback(callback, entries); + }); + }); +} +exports.readdir = readdir; +function callFailureCallback(callback, error) { + callback(error); +} +function callSuccessCallback(callback, result) { + callback(null, result); +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/common.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/common.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2b4d08b57a0de23a030b494abbb236239638b122 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/common.d.ts @@ -0,0 +1 @@ +export declare function joinPathSegments(a: string, b: string, separator: string): string; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/common.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/common.js new file mode 100644 index 0000000000000000000000000000000000000000..8724cb59afe97cdfebdf6b50bdf36534537e781c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/common.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.joinPathSegments = void 0; +function joinPathSegments(a, b, separator) { + /** + * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). + */ + if (a.endsWith(separator)) { + return a + b; + } + return a + separator + b; +} +exports.joinPathSegments = joinPathSegments; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/sync.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/sync.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e05c8f072cb5766844c31f6d8424c692f0caacac --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/sync.d.ts @@ -0,0 +1,5 @@ +import type Settings from '../settings'; +import type { Entry } from '../types'; +export declare function read(directory: string, settings: Settings): Entry[]; +export declare function readdirWithFileTypes(directory: string, settings: Settings): Entry[]; +export declare function readdir(directory: string, settings: Settings): Entry[]; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/sync.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/sync.js new file mode 100644 index 0000000000000000000000000000000000000000..146db3434f42252e4071db1624074a666fe21b4a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/providers/sync.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.readdir = exports.readdirWithFileTypes = exports.read = void 0; +const fsStat = require("@nodelib/fs.stat"); +const constants_1 = require("../constants"); +const utils = require("../utils"); +const common = require("./common"); +function read(directory, settings) { + if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + return readdirWithFileTypes(directory, settings); + } + return readdir(directory, settings); +} +exports.read = read; +function readdirWithFileTypes(directory, settings) { + const dirents = settings.fs.readdirSync(directory, { withFileTypes: true }); + return dirents.map((dirent) => { + const entry = { + dirent, + name: dirent.name, + path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) + }; + if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { + try { + const stats = settings.fs.statSync(entry.path); + entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); + } + catch (error) { + if (settings.throwErrorOnBrokenSymbolicLink) { + throw error; + } + } + } + return entry; + }); +} +exports.readdirWithFileTypes = readdirWithFileTypes; +function readdir(directory, settings) { + const names = settings.fs.readdirSync(directory); + return names.map((name) => { + const entryPath = common.joinPathSegments(directory, name, settings.pathSegmentSeparator); + const stats = fsStat.statSync(entryPath, settings.fsStatSettings); + const entry = { + name, + path: entryPath, + dirent: utils.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; + } + return entry; + }); +} +exports.readdir = readdir; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/settings.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/settings.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a0db11559914a553d8e2da52b612bf48f2d5dd74 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/settings.d.ts @@ -0,0 +1,20 @@ +import * as fsStat from '@nodelib/fs.stat'; +import * as fs from './adapters/fs'; +export interface Options { + followSymbolicLinks?: boolean; + fs?: Partial; + pathSegmentSeparator?: string; + stats?: boolean; + throwErrorOnBrokenSymbolicLink?: boolean; +} +export default class Settings { + private readonly _options; + readonly followSymbolicLinks: boolean; + readonly fs: fs.FileSystemAdapter; + readonly pathSegmentSeparator: string; + readonly stats: boolean; + readonly throwErrorOnBrokenSymbolicLink: boolean; + readonly fsStatSettings: fsStat.Settings; + constructor(_options?: Options); + private _getValue; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/settings.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/settings.js new file mode 100644 index 0000000000000000000000000000000000000000..15a3e8cde7704afdc4d66723ac440c2acb7e3519 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/settings.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const path = require("path"); +const fsStat = require("@nodelib/fs.stat"); +const fs = require("./adapters/fs"); +class Settings { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); + this.fs = fs.createFileSystemAdapter(this._options.fs); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep); + this.stats = this._getValue(this._options.stats, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + this.fsStatSettings = new fsStat.Settings({ + followSymbolicLink: this.followSymbolicLinks, + fs: this.fs, + throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink + }); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } +} +exports.default = Settings; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/types/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f326c5e5e41f3288779c97c777e782e5642aed1f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/types/index.d.ts @@ -0,0 +1,20 @@ +/// +import type * as fs from 'fs'; +export interface Entry { + dirent: Dirent; + name: string; + path: string; + stats?: Stats; +} +export declare type Stats = fs.Stats; +export declare type ErrnoException = NodeJS.ErrnoException; +export interface Dirent { + isBlockDevice: () => boolean; + isCharacterDevice: () => boolean; + isDirectory: () => boolean; + isFIFO: () => boolean; + isFile: () => boolean; + isSocket: () => boolean; + isSymbolicLink: () => boolean; + name: string; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/types/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/types/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/types/index.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/utils/fs.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/utils/fs.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bb863f1573e99fe2fe287dcdd8d22c075dd014e1 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/utils/fs.d.ts @@ -0,0 +1,2 @@ +import type { Dirent, Stats } from '../types'; +export declare function createDirentFromStats(name: string, stats: Stats): Dirent; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/utils/fs.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/utils/fs.js new file mode 100644 index 0000000000000000000000000000000000000000..ace7c74d63f6da763b2711a4119d6005f5c3b187 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/utils/fs.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createDirentFromStats = void 0; +class DirentFromStats { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } +} +function createDirentFromStats(name, stats) { + return new DirentFromStats(name, stats); +} +exports.createDirentFromStats = createDirentFromStats; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/utils/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/utils/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1b41954e79d847e0f085ce4235b8ee62fddb1977 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/utils/index.d.ts @@ -0,0 +1,2 @@ +import * as fs from './fs'; +export { fs }; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/utils/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/utils/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f5de129f47b80353304d3219c96f73f59a390397 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/out/utils/index.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fs = void 0; +const fs = require("./fs"); +exports.fs = fs; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d3a89241b3c1891339651dfdeb9495813587e289 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.scandir/package.json @@ -0,0 +1,44 @@ +{ + "name": "@nodelib/fs.scandir", + "version": "2.1.5", + "description": "List files and directories inside the specified directory", + "license": "MIT", + "repository": "https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.scandir", + "keywords": [ + "NodeLib", + "fs", + "FileSystem", + "file system", + "scandir", + "readdir", + "dirent" + ], + "engines": { + "node": ">= 8" + }, + "files": [ + "out/**", + "!out/**/*.map", + "!out/**/*.spec.*" + ], + "main": "out/index.js", + "typings": "out/index.d.ts", + "scripts": { + "clean": "rimraf {tsconfig.tsbuildinfo,out}", + "lint": "eslint \"src/**/*.ts\" --cache", + "compile": "tsc -b .", + "compile:watch": "tsc -p . --watch --sourceMap", + "test": "mocha \"out/**/*.spec.js\" -s 0", + "build": "npm run clean && npm run compile && npm run lint && npm test", + "watch": "npm run clean && npm run compile:watch" + }, + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "devDependencies": { + "@nodelib/fs.macchiato": "1.0.4", + "@types/run-parallel": "^1.1.0" + }, + "gitHead": "d6a7960d5281d3dd5f8e2efba49bb552d090f562" +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/LICENSE b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..65a999460170355f6383b8f122da09e66e485165 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Denis Malinochkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/README.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/README.md new file mode 100644 index 0000000000000000000000000000000000000000..686f0471d40f2f522e53db44f5a5b7a73a65e9df --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/README.md @@ -0,0 +1,126 @@ +# @nodelib/fs.stat + +> Get the status of a file with some features. + +## :bulb: Highlights + +Wrapper around standard method `fs.lstat` and `fs.stat` with some features. + +* :beginner: Normally follows symbolic link. +* :gear: Can safely work with broken symbolic link. + +## Install + +```console +npm install @nodelib/fs.stat +``` + +## Usage + +```ts +import * as fsStat from '@nodelib/fs.stat'; + +fsStat.stat('path', (error, stats) => { /* … */ }); +``` + +## API + +### .stat(path, [optionsOrSettings], callback) + +Returns an instance of `fs.Stats` class for provided path with standard callback-style. + +```ts +fsStat.stat('path', (error, stats) => { /* … */ }); +fsStat.stat('path', {}, (error, stats) => { /* … */ }); +fsStat.stat('path', new fsStat.Settings(), (error, stats) => { /* … */ }); +``` + +### .statSync(path, [optionsOrSettings]) + +Returns an instance of `fs.Stats` class for provided path. + +```ts +const stats = fsStat.stat('path'); +const stats = fsStat.stat('path', {}); +const stats = fsStat.stat('path', new fsStat.Settings()); +``` + +#### path + +* Required: `true` +* Type: `string | Buffer | URL` + +A path to a file. If a URL is provided, it must use the `file:` protocol. + +#### optionsOrSettings + +* Required: `false` +* Type: `Options | Settings` +* Default: An instance of `Settings` class + +An [`Options`](#options) object or an instance of [`Settings`](#settings) class. + +> :book: When you pass a plain object, an instance of the `Settings` class will be created automatically. If you plan to call the method frequently, use a pre-created instance of the `Settings` class. + +### Settings([options]) + +A class of full settings of the package. + +```ts +const settings = new fsStat.Settings({ followSymbolicLink: false }); + +const stats = fsStat.stat('path', settings); +``` + +## Options + +### `followSymbolicLink` + +* Type: `boolean` +* Default: `true` + +Follow symbolic link or not. Call `fs.stat` on symbolic link if `true`. + +### `markSymbolicLink` + +* Type: `boolean` +* Default: `false` + +Mark symbolic link by setting the return value of `isSymbolicLink` function to always `true` (even after `fs.stat`). + +> :book: Can be used if you want to know what is hidden behind a symbolic link, but still continue to know that it is a symbolic link. + +### `throwErrorOnBrokenSymbolicLink` + +* Type: `boolean` +* Default: `true` + +Throw an error when symbolic link is broken if `true` or safely return `lstat` call if `false`. + +### `fs` + +* Type: [`FileSystemAdapter`](./src/adapters/fs.ts) +* Default: A default FS methods + +By default, the built-in Node.js module (`fs`) is used to work with the file system. You can replace any method with your own. + +```ts +interface FileSystemAdapter { + lstat?: typeof fs.lstat; + stat?: typeof fs.stat; + lstatSync?: typeof fs.lstatSync; + statSync?: typeof fs.statSync; +} + +const settings = new fsStat.Settings({ + fs: { lstat: fakeLstat } +}); +``` + +## Changelog + +See the [Releases section of our GitHub project](https://github.com/nodelib/nodelib/releases) for changelog for each release version. + +## License + +This software is released under the terms of the MIT license. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/adapters/fs.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/adapters/fs.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3af759c95fb85c927bc8204a49c5eaca37d691d2 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/adapters/fs.d.ts @@ -0,0 +1,13 @@ +/// +import * as fs from 'fs'; +import type { ErrnoException } from '../types'; +export declare type StatAsynchronousMethod = (path: string, callback: (error: ErrnoException | null, stats: fs.Stats) => void) => void; +export declare type StatSynchronousMethod = (path: string) => fs.Stats; +export interface FileSystemAdapter { + lstat: StatAsynchronousMethod; + stat: StatAsynchronousMethod; + lstatSync: StatSynchronousMethod; + statSync: StatSynchronousMethod; +} +export declare const FILE_SYSTEM_ADAPTER: FileSystemAdapter; +export declare function createFileSystemAdapter(fsMethods?: Partial): FileSystemAdapter; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/adapters/fs.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/adapters/fs.js new file mode 100644 index 0000000000000000000000000000000000000000..8dc08c8ca1f1c72aa9622352ca5d55f65198767d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/adapters/fs.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; +const fs = require("fs"); +exports.FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + stat: fs.stat, + lstatSync: fs.lstatSync, + statSync: fs.statSync +}; +function createFileSystemAdapter(fsMethods) { + if (fsMethods === undefined) { + return exports.FILE_SYSTEM_ADAPTER; + } + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); +} +exports.createFileSystemAdapter = createFileSystemAdapter; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f95db995c7f8fd07939359f4885835eebcd9e0fc --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/index.d.ts @@ -0,0 +1,12 @@ +import type { FileSystemAdapter, StatAsynchronousMethod, StatSynchronousMethod } from './adapters/fs'; +import * as async from './providers/async'; +import Settings, { Options } from './settings'; +import type { Stats } from './types'; +declare type AsyncCallback = async.AsyncCallback; +declare function stat(path: string, callback: AsyncCallback): void; +declare function stat(path: string, optionsOrSettings: Options | Settings, callback: AsyncCallback): void; +declare namespace stat { + function __promisify__(path: string, optionsOrSettings?: Options | Settings): Promise; +} +declare function statSync(path: string, optionsOrSettings?: Options | Settings): Stats; +export { Settings, stat, statSync, AsyncCallback, FileSystemAdapter, StatAsynchronousMethod, StatSynchronousMethod, Options, Stats }; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b23f7510d050fe830d40765ad49fe72b21ebef5b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/index.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.statSync = exports.stat = exports.Settings = void 0; +const async = require("./providers/async"); +const sync = require("./providers/sync"); +const settings_1 = require("./settings"); +exports.Settings = settings_1.default; +function stat(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + async.read(path, getSettings(), optionsOrSettingsOrCallback); + return; + } + async.read(path, getSettings(optionsOrSettingsOrCallback), callback); +} +exports.stat = stat; +function statSync(path, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + return sync.read(path, settings); +} +exports.statSync = statSync; +function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1.default) { + return settingsOrOptions; + } + return new settings_1.default(settingsOrOptions); +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/providers/async.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/providers/async.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..85423ce11e2efb74a86e9477405e1976fec6b7c5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/providers/async.d.ts @@ -0,0 +1,4 @@ +import type Settings from '../settings'; +import type { ErrnoException, Stats } from '../types'; +export declare type AsyncCallback = (error: ErrnoException, stats: Stats) => void; +export declare function read(path: string, settings: Settings, callback: AsyncCallback): void; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/providers/async.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/providers/async.js new file mode 100644 index 0000000000000000000000000000000000000000..983ff0e6cb79f6e4442be70c43e79c6b406dd9bb --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/providers/async.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.read = void 0; +function read(path, settings, callback) { + settings.fs.lstat(path, (lstatError, lstat) => { + if (lstatError !== null) { + callFailureCallback(callback, lstatError); + return; + } + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + callSuccessCallback(callback, lstat); + return; + } + settings.fs.stat(path, (statError, stat) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + callFailureCallback(callback, statError); + return; + } + callSuccessCallback(callback, lstat); + return; + } + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + callSuccessCallback(callback, stat); + }); + }); +} +exports.read = read; +function callFailureCallback(callback, error) { + callback(error); +} +function callSuccessCallback(callback, result) { + callback(null, result); +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/providers/sync.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/providers/sync.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..428c3d792b385664fe3fe4770c46e558d7ca5285 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/providers/sync.d.ts @@ -0,0 +1,3 @@ +import type Settings from '../settings'; +import type { Stats } from '../types'; +export declare function read(path: string, settings: Settings): Stats; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/providers/sync.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/providers/sync.js new file mode 100644 index 0000000000000000000000000000000000000000..1521c3616eaee4439c5cd1a855c97d029d4dab38 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/providers/sync.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.read = void 0; +function read(path, settings) { + const lstat = settings.fs.lstatSync(path); + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + return lstat; + } + try { + const stat = settings.fs.statSync(path); + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + return stat; + } + catch (error) { + if (!settings.throwErrorOnBrokenSymbolicLink) { + return lstat; + } + throw error; + } +} +exports.read = read; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/settings.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/settings.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f4b3d444302ff6b5715a79341156f61350bd0a1b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/settings.d.ts @@ -0,0 +1,16 @@ +import * as fs from './adapters/fs'; +export interface Options { + followSymbolicLink?: boolean; + fs?: Partial; + markSymbolicLink?: boolean; + throwErrorOnBrokenSymbolicLink?: boolean; +} +export default class Settings { + private readonly _options; + readonly followSymbolicLink: boolean; + readonly fs: fs.FileSystemAdapter; + readonly markSymbolicLink: boolean; + readonly throwErrorOnBrokenSymbolicLink: boolean; + constructor(_options?: Options); + private _getValue; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/settings.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/settings.js new file mode 100644 index 0000000000000000000000000000000000000000..111ec09ca6491ae6d8d9a9c9bdcb32c8408afcc4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/settings.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const fs = require("./adapters/fs"); +class Settings { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); + this.fs = fs.createFileSystemAdapter(this._options.fs); + this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } +} +exports.default = Settings; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/types/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..74c08ed2f7a1201d2e28453602b83241d83ade82 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/types/index.d.ts @@ -0,0 +1,4 @@ +/// +import type * as fs from 'fs'; +export declare type Stats = fs.Stats; +export declare type ErrnoException = NodeJS.ErrnoException; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/types/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/types/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/out/types/index.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f2540c2894ea9181f73274a493df0dc3789d6128 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.stat/package.json @@ -0,0 +1,37 @@ +{ + "name": "@nodelib/fs.stat", + "version": "2.0.5", + "description": "Get the status of a file with some features", + "license": "MIT", + "repository": "https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.stat", + "keywords": [ + "NodeLib", + "fs", + "FileSystem", + "file system", + "stat" + ], + "engines": { + "node": ">= 8" + }, + "files": [ + "out/**", + "!out/**/*.map", + "!out/**/*.spec.*" + ], + "main": "out/index.js", + "typings": "out/index.d.ts", + "scripts": { + "clean": "rimraf {tsconfig.tsbuildinfo,out}", + "lint": "eslint \"src/**/*.ts\" --cache", + "compile": "tsc -b .", + "compile:watch": "tsc -p . --watch --sourceMap", + "test": "mocha \"out/**/*.spec.js\" -s 0", + "build": "npm run clean && npm run compile && npm run lint && npm test", + "watch": "npm run clean && npm run compile:watch" + }, + "devDependencies": { + "@nodelib/fs.macchiato": "1.0.4" + }, + "gitHead": "d6a7960d5281d3dd5f8e2efba49bb552d090f562" +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/LICENSE b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..65a999460170355f6383b8f122da09e66e485165 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Denis Malinochkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/README.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6ccc08db4a10bca492f2db7b547b98a7f22a4e8c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/README.md @@ -0,0 +1,215 @@ +# @nodelib/fs.walk + +> A library for efficiently walking a directory recursively. + +## :bulb: Highlights + +* :moneybag: Returns useful information: `name`, `path`, `dirent` and `stats` (optional). +* :rocket: On Node.js 10.10+ uses the mechanism without additional calls to determine the entry type for performance reasons. See [`old` and `modern` mode](https://github.com/nodelib/nodelib/blob/master/packages/fs/fs.scandir/README.md#old-and-modern-mode). +* :gear: Built-in directories/files and error filtering system. +* :link: Can safely work with broken symbolic links. + +## Install + +```console +npm install @nodelib/fs.walk +``` + +## Usage + +```ts +import * as fsWalk from '@nodelib/fs.walk'; + +fsWalk.walk('path', (error, entries) => { /* … */ }); +``` + +## API + +### .walk(path, [optionsOrSettings], callback) + +Reads the directory recursively and asynchronously. Requires a callback function. + +> :book: If you want to use the Promise API, use `util.promisify`. + +```ts +fsWalk.walk('path', (error, entries) => { /* … */ }); +fsWalk.walk('path', {}, (error, entries) => { /* … */ }); +fsWalk.walk('path', new fsWalk.Settings(), (error, entries) => { /* … */ }); +``` + +### .walkStream(path, [optionsOrSettings]) + +Reads the directory recursively and asynchronously. [Readable Stream](https://nodejs.org/dist/latest-v12.x/docs/api/stream.html#stream_readable_streams) is used as a provider. + +```ts +const stream = fsWalk.walkStream('path'); +const stream = fsWalk.walkStream('path', {}); +const stream = fsWalk.walkStream('path', new fsWalk.Settings()); +``` + +### .walkSync(path, [optionsOrSettings]) + +Reads the directory recursively and synchronously. Returns an array of entries. + +```ts +const entries = fsWalk.walkSync('path'); +const entries = fsWalk.walkSync('path', {}); +const entries = fsWalk.walkSync('path', new fsWalk.Settings()); +``` + +#### path + +* Required: `true` +* Type: `string | Buffer | URL` + +A path to a file. If a URL is provided, it must use the `file:` protocol. + +#### optionsOrSettings + +* Required: `false` +* Type: `Options | Settings` +* Default: An instance of `Settings` class + +An [`Options`](#options) object or an instance of [`Settings`](#settings) class. + +> :book: When you pass a plain object, an instance of the `Settings` class will be created automatically. If you plan to call the method frequently, use a pre-created instance of the `Settings` class. + +### Settings([options]) + +A class of full settings of the package. + +```ts +const settings = new fsWalk.Settings({ followSymbolicLinks: true }); + +const entries = fsWalk.walkSync('path', settings); +``` + +## Entry + +* `name` — The name of the entry (`unknown.txt`). +* `path` — The path of the entry relative to call directory (`root/unknown.txt`). +* `dirent` — An instance of [`fs.Dirent`](./src/types/index.ts) class. +* [`stats`] — An instance of `fs.Stats` class. + +## Options + +### basePath + +* Type: `string` +* Default: `undefined` + +By default, all paths are built relative to the root path. You can use this option to set custom root path. + +In the example below we read the files from the `root` directory, but in the results the root path will be `custom`. + +```ts +fsWalk.walkSync('root'); // → ['root/file.txt'] +fsWalk.walkSync('root', { basePath: 'custom' }); // → ['custom/file.txt'] +``` + +### concurrency + +* Type: `number` +* Default: `Infinity` + +The maximum number of concurrent calls to `fs.readdir`. + +> :book: The higher the number, the higher performance and the load on the File System. If you want to read in quiet mode, set the value to `4 * os.cpus().length` (4 is default size of [thread pool work scheduling](http://docs.libuv.org/en/v1.x/threadpool.html#thread-pool-work-scheduling)). + +### deepFilter + +* Type: [`DeepFilterFunction`](./src/settings.ts) +* Default: `undefined` + +A function that indicates whether the directory will be read deep or not. + +```ts +// Skip all directories that starts with `node_modules` +const filter: DeepFilterFunction = (entry) => !entry.path.startsWith('node_modules'); +``` + +### entryFilter + +* Type: [`EntryFilterFunction`](./src/settings.ts) +* Default: `undefined` + +A function that indicates whether the entry will be included to results or not. + +```ts +// Exclude all `.js` files from results +const filter: EntryFilterFunction = (entry) => !entry.name.endsWith('.js'); +``` + +### errorFilter + +* Type: [`ErrorFilterFunction`](./src/settings.ts) +* Default: `undefined` + +A function that allows you to skip errors that occur when reading directories. + +For example, you can skip `ENOENT` errors if required: + +```ts +// Skip all ENOENT errors +const filter: ErrorFilterFunction = (error) => error.code == 'ENOENT'; +``` + +### stats + +* Type: `boolean` +* Default: `false` + +Adds an instance of `fs.Stats` class to the [`Entry`](#entry). + +> :book: Always use `fs.readdir` with additional `fs.lstat/fs.stat` calls to determine the entry type. + +### followSymbolicLinks + +* Type: `boolean` +* Default: `false` + +Follow symbolic links or not. Call `fs.stat` on symbolic link if `true`. + +### `throwErrorOnBrokenSymbolicLink` + +* Type: `boolean` +* Default: `true` + +Throw an error when symbolic link is broken if `true` or safely return `lstat` call if `false`. + +### `pathSegmentSeparator` + +* Type: `string` +* Default: `path.sep` + +By default, this package uses the correct path separator for your OS (`\` on Windows, `/` on Unix-like systems). But you can set this option to any separator character(s) that you want to use instead. + +### `fs` + +* Type: `FileSystemAdapter` +* Default: A default FS methods + +By default, the built-in Node.js module (`fs`) is used to work with the file system. You can replace any method with your own. + +```ts +interface FileSystemAdapter { + lstat: typeof fs.lstat; + stat: typeof fs.stat; + lstatSync: typeof fs.lstatSync; + statSync: typeof fs.statSync; + readdir: typeof fs.readdir; + readdirSync: typeof fs.readdirSync; +} + +const settings = new fsWalk.Settings({ + fs: { lstat: fakeLstat } +}); +``` + +## Changelog + +See the [Releases section of our GitHub project](https://github.com/nodelib/nodelib/releases) for changelog for each release version. + +## License + +This software is released under the terms of the MIT license. diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8864c7bff5d8cb4a3db399a957f5eb49031d3248 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/index.d.ts @@ -0,0 +1,14 @@ +/// +import type { Readable } from 'stream'; +import type { Dirent, FileSystemAdapter } from '@nodelib/fs.scandir'; +import { AsyncCallback } from './providers/async'; +import Settings, { DeepFilterFunction, EntryFilterFunction, ErrorFilterFunction, Options } from './settings'; +import type { Entry } from './types'; +declare function walk(directory: string, callback: AsyncCallback): void; +declare function walk(directory: string, optionsOrSettings: Options | Settings, callback: AsyncCallback): void; +declare namespace walk { + function __promisify__(directory: string, optionsOrSettings?: Options | Settings): Promise; +} +declare function walkSync(directory: string, optionsOrSettings?: Options | Settings): Entry[]; +declare function walkStream(directory: string, optionsOrSettings?: Options | Settings): Readable; +export { walk, walkSync, walkStream, Settings, AsyncCallback, Dirent, Entry, FileSystemAdapter, Options, DeepFilterFunction, EntryFilterFunction, ErrorFilterFunction }; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/index.js new file mode 100644 index 0000000000000000000000000000000000000000..15207874afa1dadac7f7655545b4b1f75ee87a78 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/index.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Settings = exports.walkStream = exports.walkSync = exports.walk = void 0; +const async_1 = require("./providers/async"); +const stream_1 = require("./providers/stream"); +const sync_1 = require("./providers/sync"); +const settings_1 = require("./settings"); +exports.Settings = settings_1.default; +function walk(directory, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + new async_1.default(directory, getSettings()).read(optionsOrSettingsOrCallback); + return; + } + new async_1.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); +} +exports.walk = walk; +function walkSync(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new sync_1.default(directory, settings); + return provider.read(); +} +exports.walkSync = walkSync; +function walkStream(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new stream_1.default(directory, settings); + return provider.read(); +} +exports.walkStream = walkStream; +function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1.default) { + return settingsOrOptions; + } + return new settings_1.default(settingsOrOptions); +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/async.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/async.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0f6717d780f64fd49f31ba1cfccabb40eb5aafea --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/async.d.ts @@ -0,0 +1,12 @@ +import AsyncReader from '../readers/async'; +import type Settings from '../settings'; +import type { Entry, Errno } from '../types'; +export declare type AsyncCallback = (error: Errno, entries: Entry[]) => void; +export default class AsyncProvider { + private readonly _root; + private readonly _settings; + protected readonly _reader: AsyncReader; + private readonly _storage; + constructor(_root: string, _settings: Settings); + read(callback: AsyncCallback): void; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/async.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/async.js new file mode 100644 index 0000000000000000000000000000000000000000..51d3be51a85d46c5ab53f5b7d92675996d02887c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/async.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const async_1 = require("../readers/async"); +class AsyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async_1.default(this._root, this._settings); + this._storage = []; + } + read(callback) { + this._reader.onError((error) => { + callFailureCallback(callback, error); + }); + this._reader.onEntry((entry) => { + this._storage.push(entry); + }); + this._reader.onEnd(() => { + callSuccessCallback(callback, this._storage); + }); + this._reader.read(); + } +} +exports.default = AsyncProvider; +function callFailureCallback(callback, error) { + callback(error); +} +function callSuccessCallback(callback, entries) { + callback(null, entries); +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..874f60c5a10b2f8fdfca1725fc1e8ff335e7549c --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/index.d.ts @@ -0,0 +1,4 @@ +import AsyncProvider from './async'; +import StreamProvider from './stream'; +import SyncProvider from './sync'; +export { AsyncProvider, StreamProvider, SyncProvider }; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4c2529ce8a385a0215ddf188b8a46163b2e18842 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/index.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SyncProvider = exports.StreamProvider = exports.AsyncProvider = void 0; +const async_1 = require("./async"); +exports.AsyncProvider = async_1.default; +const stream_1 = require("./stream"); +exports.StreamProvider = stream_1.default; +const sync_1 = require("./sync"); +exports.SyncProvider = sync_1.default; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/stream.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/stream.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..294185f85dc59d2a40eec8b0fea2d87958e41cdf --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/stream.d.ts @@ -0,0 +1,12 @@ +/// +import { Readable } from 'stream'; +import AsyncReader from '../readers/async'; +import type Settings from '../settings'; +export default class StreamProvider { + private readonly _root; + private readonly _settings; + protected readonly _reader: AsyncReader; + protected readonly _stream: Readable; + constructor(_root: string, _settings: Settings); + read(): Readable; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/stream.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/stream.js new file mode 100644 index 0000000000000000000000000000000000000000..51298b0f58f14b0c9b9f36061cdd0c0b950ba2f3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/stream.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const stream_1 = require("stream"); +const async_1 = require("../readers/async"); +class StreamProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async_1.default(this._root, this._settings); + this._stream = new stream_1.Readable({ + objectMode: true, + read: () => { }, + destroy: () => { + if (!this._reader.isDestroyed) { + this._reader.destroy(); + } + } + }); + } + read() { + this._reader.onError((error) => { + this._stream.emit('error', error); + }); + this._reader.onEntry((entry) => { + this._stream.push(entry); + }); + this._reader.onEnd(() => { + this._stream.push(null); + }); + this._reader.read(); + return this._stream; + } +} +exports.default = StreamProvider; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/sync.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/sync.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..551c42e41293756691160855d122f365710ac007 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/sync.d.ts @@ -0,0 +1,10 @@ +import SyncReader from '../readers/sync'; +import type Settings from '../settings'; +import type { Entry } from '../types'; +export default class SyncProvider { + private readonly _root; + private readonly _settings; + protected readonly _reader: SyncReader; + constructor(_root: string, _settings: Settings); + read(): Entry[]; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/sync.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/sync.js new file mode 100644 index 0000000000000000000000000000000000000000..faab6ca2ad4262e2d9d5539b8c6ce0017090fd29 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/providers/sync.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const sync_1 = require("../readers/sync"); +class SyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new sync_1.default(this._root, this._settings); + } + read() { + return this._reader.read(); + } +} +exports.default = SyncProvider; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/async.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/async.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9acf4e6c25f383ab22f55ff79a7f2022f6238773 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/async.d.ts @@ -0,0 +1,30 @@ +/// +import { EventEmitter } from 'events'; +import * as fsScandir from '@nodelib/fs.scandir'; +import type Settings from '../settings'; +import type { Entry, Errno } from '../types'; +import Reader from './reader'; +declare type EntryEventCallback = (entry: Entry) => void; +declare type ErrorEventCallback = (error: Errno) => void; +declare type EndEventCallback = () => void; +export default class AsyncReader extends Reader { + protected readonly _settings: Settings; + protected readonly _scandir: typeof fsScandir.scandir; + protected readonly _emitter: EventEmitter; + private readonly _queue; + private _isFatalError; + private _isDestroyed; + constructor(_root: string, _settings: Settings); + read(): EventEmitter; + get isDestroyed(): boolean; + destroy(): void; + onEntry(callback: EntryEventCallback): void; + onError(callback: ErrorEventCallback): void; + onEnd(callback: EndEventCallback): void; + private _pushToQueue; + private _worker; + private _handleError; + private _handleEntry; + private _emitEntry; +} +export {}; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/async.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/async.js new file mode 100644 index 0000000000000000000000000000000000000000..ebe8dd5735858b58c0d6a38cdb925c85c7c03651 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/async.js @@ -0,0 +1,97 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const events_1 = require("events"); +const fsScandir = require("@nodelib/fs.scandir"); +const fastq = require("fastq"); +const common = require("./common"); +const reader_1 = require("./reader"); +class AsyncReader extends reader_1.default { + constructor(_root, _settings) { + super(_root, _settings); + this._settings = _settings; + this._scandir = fsScandir.scandir; + this._emitter = new events_1.EventEmitter(); + this._queue = fastq(this._worker.bind(this), this._settings.concurrency); + this._isFatalError = false; + this._isDestroyed = false; + this._queue.drain = () => { + if (!this._isFatalError) { + this._emitter.emit('end'); + } + }; + } + read() { + this._isFatalError = false; + this._isDestroyed = false; + setImmediate(() => { + this._pushToQueue(this._root, this._settings.basePath); + }); + return this._emitter; + } + get isDestroyed() { + return this._isDestroyed; + } + destroy() { + if (this._isDestroyed) { + throw new Error('The reader is already destroyed'); + } + this._isDestroyed = true; + this._queue.killAndDrain(); + } + onEntry(callback) { + this._emitter.on('entry', callback); + } + onError(callback) { + this._emitter.once('error', callback); + } + onEnd(callback) { + this._emitter.once('end', callback); + } + _pushToQueue(directory, base) { + const queueItem = { directory, base }; + this._queue.push(queueItem, (error) => { + if (error !== null) { + this._handleError(error); + } + }); + } + _worker(item, done) { + this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => { + if (error !== null) { + done(error, undefined); + return; + } + for (const entry of entries) { + this._handleEntry(entry, item.base); + } + done(null, undefined); + }); + } + _handleError(error) { + if (this._isDestroyed || !common.isFatalError(this._settings, error)) { + return; + } + this._isFatalError = true; + this._isDestroyed = true; + this._emitter.emit('error', error); + } + _handleEntry(entry, base) { + if (this._isDestroyed || this._isFatalError) { + return; + } + const fullpath = entry.path; + if (base !== undefined) { + entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + if (common.isAppliedFilter(this._settings.entryFilter, entry)) { + this._emitEntry(entry); + } + if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); + } + } + _emitEntry(entry) { + this._emitter.emit('entry', entry); + } +} +exports.default = AsyncReader; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/common.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/common.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5985f97c402e5a92edf987d791821650c9b66f3b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/common.d.ts @@ -0,0 +1,7 @@ +import type { FilterFunction } from '../settings'; +import type Settings from '../settings'; +import type { Errno } from '../types'; +export declare function isFatalError(settings: Settings, error: Errno): boolean; +export declare function isAppliedFilter(filter: FilterFunction | null, value: T): boolean; +export declare function replacePathSegmentSeparator(filepath: string, separator: string): string; +export declare function joinPathSegments(a: string, b: string, separator: string): string; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/common.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/common.js new file mode 100644 index 0000000000000000000000000000000000000000..a93572f48a79ecd394339f6b27768a3b49332912 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/common.js @@ -0,0 +1,31 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.joinPathSegments = exports.replacePathSegmentSeparator = exports.isAppliedFilter = exports.isFatalError = void 0; +function isFatalError(settings, error) { + if (settings.errorFilter === null) { + return true; + } + return !settings.errorFilter(error); +} +exports.isFatalError = isFatalError; +function isAppliedFilter(filter, value) { + return filter === null || filter(value); +} +exports.isAppliedFilter = isAppliedFilter; +function replacePathSegmentSeparator(filepath, separator) { + return filepath.split(/[/\\]/).join(separator); +} +exports.replacePathSegmentSeparator = replacePathSegmentSeparator; +function joinPathSegments(a, b, separator) { + if (a === '') { + return b; + } + /** + * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). + */ + if (a.endsWith(separator)) { + return a + b; + } + return a + separator + b; +} +exports.joinPathSegments = joinPathSegments; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/reader.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/reader.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e1f383b25192216249d67456b437f7ea0ae5db24 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/reader.d.ts @@ -0,0 +1,6 @@ +import type Settings from '../settings'; +export default class Reader { + protected readonly _root: string; + protected readonly _settings: Settings; + constructor(_root: string, _settings: Settings); +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/reader.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/reader.js new file mode 100644 index 0000000000000000000000000000000000000000..782f07cbfab62ff2469f26b2fc98050a38b21f27 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/reader.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const common = require("./common"); +class Reader { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); + } +} +exports.default = Reader; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/sync.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/sync.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..af410335363f14e3d0bdd44054917e08c6ba57ad --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/sync.d.ts @@ -0,0 +1,15 @@ +import * as fsScandir from '@nodelib/fs.scandir'; +import type { Entry } from '../types'; +import Reader from './reader'; +export default class SyncReader extends Reader { + protected readonly _scandir: typeof fsScandir.scandirSync; + private readonly _storage; + private readonly _queue; + read(): Entry[]; + private _pushToQueue; + private _handleQueue; + private _handleDirectory; + private _handleError; + private _handleEntry; + private _pushToStorage; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/sync.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/sync.js new file mode 100644 index 0000000000000000000000000000000000000000..9a8d5a6f1e18e826bc8930d03b5ef9e05b8738b3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/readers/sync.js @@ -0,0 +1,59 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const fsScandir = require("@nodelib/fs.scandir"); +const common = require("./common"); +const reader_1 = require("./reader"); +class SyncReader extends reader_1.default { + constructor() { + super(...arguments); + this._scandir = fsScandir.scandirSync; + this._storage = []; + this._queue = new Set(); + } + read() { + this._pushToQueue(this._root, this._settings.basePath); + this._handleQueue(); + return this._storage; + } + _pushToQueue(directory, base) { + this._queue.add({ directory, base }); + } + _handleQueue() { + for (const item of this._queue.values()) { + this._handleDirectory(item.directory, item.base); + } + } + _handleDirectory(directory, base) { + try { + const entries = this._scandir(directory, this._settings.fsScandirSettings); + for (const entry of entries) { + this._handleEntry(entry, base); + } + } + catch (error) { + this._handleError(error); + } + } + _handleError(error) { + if (!common.isFatalError(this._settings, error)) { + return; + } + throw error; + } + _handleEntry(entry, base) { + const fullpath = entry.path; + if (base !== undefined) { + entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + if (common.isAppliedFilter(this._settings.entryFilter, entry)) { + this._pushToStorage(entry); + } + if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); + } + } + _pushToStorage(entry) { + this._storage.push(entry); + } +} +exports.default = SyncReader; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/settings.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/settings.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d1c4b45f6b52bd167482312568a4ba7f4b9bba74 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/settings.d.ts @@ -0,0 +1,30 @@ +import * as fsScandir from '@nodelib/fs.scandir'; +import type { Entry, Errno } from './types'; +export declare type FilterFunction = (value: T) => boolean; +export declare type DeepFilterFunction = FilterFunction; +export declare type EntryFilterFunction = FilterFunction; +export declare type ErrorFilterFunction = FilterFunction; +export interface Options { + basePath?: string; + concurrency?: number; + deepFilter?: DeepFilterFunction; + entryFilter?: EntryFilterFunction; + errorFilter?: ErrorFilterFunction; + followSymbolicLinks?: boolean; + fs?: Partial; + pathSegmentSeparator?: string; + stats?: boolean; + throwErrorOnBrokenSymbolicLink?: boolean; +} +export default class Settings { + private readonly _options; + readonly basePath?: string; + readonly concurrency: number; + readonly deepFilter: DeepFilterFunction | null; + readonly entryFilter: EntryFilterFunction | null; + readonly errorFilter: ErrorFilterFunction | null; + readonly pathSegmentSeparator: string; + readonly fsScandirSettings: fsScandir.Settings; + constructor(_options?: Options); + private _getValue; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/settings.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/settings.js new file mode 100644 index 0000000000000000000000000000000000000000..d7a85c81eeecf8fd230e6fecedc9550bddb2ff93 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/settings.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const path = require("path"); +const fsScandir = require("@nodelib/fs.scandir"); +class Settings { + constructor(_options = {}) { + this._options = _options; + this.basePath = this._getValue(this._options.basePath, undefined); + this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY); + this.deepFilter = this._getValue(this._options.deepFilter, null); + this.entryFilter = this._getValue(this._options.entryFilter, null); + this.errorFilter = this._getValue(this._options.errorFilter, null); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep); + this.fsScandirSettings = new fsScandir.Settings({ + followSymbolicLinks: this._options.followSymbolicLinks, + fs: this._options.fs, + pathSegmentSeparator: this._options.pathSegmentSeparator, + stats: this._options.stats, + throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink + }); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } +} +exports.default = Settings; diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/types/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/types/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6ee9bd3f9bf81ccaf9abde0f329e38b075344056 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/types/index.d.ts @@ -0,0 +1,8 @@ +/// +import type * as scandir from '@nodelib/fs.scandir'; +export declare type Entry = scandir.Entry; +export declare type Errno = NodeJS.ErrnoException; +export interface QueueItem { + directory: string; + base?: string; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/types/index.js b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/types/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ad2e549bdc6801e0d1c80b0308d4b9bd4985ce --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/out/types/index.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/package.json new file mode 100644 index 0000000000000000000000000000000000000000..86bfce48b59e41fa4985ac837c5ba8a9dacabe37 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@nodelib/fs.walk/package.json @@ -0,0 +1,44 @@ +{ + "name": "@nodelib/fs.walk", + "version": "1.2.8", + "description": "A library for efficiently walking a directory recursively", + "license": "MIT", + "repository": "https://github.com/nodelib/nodelib/tree/master/packages/fs/fs.walk", + "keywords": [ + "NodeLib", + "fs", + "FileSystem", + "file system", + "walk", + "scanner", + "crawler" + ], + "engines": { + "node": ">= 8" + }, + "files": [ + "out/**", + "!out/**/*.map", + "!out/**/*.spec.*", + "!out/**/tests/**" + ], + "main": "out/index.js", + "typings": "out/index.d.ts", + "scripts": { + "clean": "rimraf {tsconfig.tsbuildinfo,out}", + "lint": "eslint \"src/**/*.ts\" --cache", + "compile": "tsc -b .", + "compile:watch": "tsc -p . --watch --sourceMap", + "test": "mocha \"out/**/*.spec.js\" -s 0", + "build": "npm run clean && npm run compile && npm run lint && npm test", + "watch": "npm run clean && npm run compile:watch" + }, + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "devDependencies": { + "@nodelib/fs.macchiato": "1.0.4" + }, + "gitHead": "1e5bad48565da2b06b8600e744324ea240bf49d8" +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/LICENSE b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/README.md b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1c799624668f9f1d22f685a8ac8113b090bbb7b4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for node (https://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node. + +### Additional Details + * Last updated: Fri, 15 Aug 2025 08:39:32 GMT + * Dependencies: [undici-types](https://npmjs.com/package/undici-types) + +# Credits +These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [Alberto Schiabel](https://github.com/jkomyno), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [David Junger](https://github.com/touffy), [Mohsen Azimi](https://github.com/mohsen1), [Nikita Galkin](https://github.com/galkin), [Sebastian Silbermann](https://github.com/eps1lon), [Wilco Bakker](https://github.com/WilcoBakker), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), [Dmitry Semigradsky](https://github.com/Semigradsky), [René](https://github.com/Renegade334), and [Yagiz Nizipli](https://github.com/anonrig). diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/assert.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/assert.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b79fc2197d3c2fdc473d7e0eab2e189b773b1133 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/assert.d.ts @@ -0,0 +1,1056 @@ +/** + * The `node:assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/assert.js) + */ +declare module "assert" { + /** + * An alias of {@link ok}. + * @since v0.5.9 + * @param value The input that is checked for being truthy. + */ + function assert(value: unknown, message?: string | Error): asserts value; + namespace assert { + /** + * Indicates the failure of an assertion. All errors thrown by the `node:assert` module will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + /** + * Set to the `actual` argument for methods such as {@link assert.strictEqual()}. + */ + actual: unknown; + /** + * Set to the `expected` argument for methods such as {@link assert.strictEqual()}. + */ + expected: unknown; + /** + * Set to the passed in operator value. + */ + operator: string; + /** + * Indicates if the message was auto-generated (`true`) or not. + */ + generatedMessage: boolean; + /** + * Value is always `ERR_ASSERTION` to show that the error is an assertion error. + */ + code: "ERR_ASSERTION"; + constructor(options?: { + /** If provided, the error message is set to this value. */ + message?: string | undefined; + /** The `actual` property on the error instance. */ + actual?: unknown | undefined; + /** The `expected` property on the error instance. */ + expected?: unknown | undefined; + /** The `operator` property on the error instance. */ + operator?: string | undefined; + /** If provided, the generated stack trace omits frames before this function. */ + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + stackStartFn?: Function | undefined; + }); + } + /** + * This feature is deprecated and will be removed in a future version. + * Please consider using alternatives such as the `mock` helper function. + * @since v14.2.0, v12.19.0 + * @deprecated Deprecated + */ + class CallTracker { + /** + * The wrapper function is expected to be called exactly `exact` times. If the + * function has not been called exactly `exact` times when `tracker.verify()` is called, then `tracker.verify()` will throw an + * error. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func); + * ``` + * @since v14.2.0, v12.19.0 + * @param [fn='A no-op function'] + * @param [exact=1] + * @return A function that wraps `fn`. + */ + calls(exact?: number): () => void; + calls(fn: undefined, exact?: number): () => void; + calls any>(fn: Func, exact?: number): Func; + calls any>(fn?: Func, exact?: number): Func | (() => void); + /** + * Example: + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * callsfunc(1, 2, 3); + * + * assert.deepStrictEqual(tracker.getCalls(callsfunc), + * [{ thisArg: undefined, arguments: [1, 2, 3] }]); + * ``` + * @since v18.8.0, v16.18.0 + * @return An array with all the calls to a tracked function. + */ + getCalls(fn: Function): CallTrackerCall[]; + /** + * The arrays contains information about the expected and actual number of calls of + * the functions that have not been called the expected number of times. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * // Returns an array containing information on callsfunc() + * console.log(tracker.report()); + * // [ + * // { + * // message: 'Expected the func function to be executed 2 time(s) but was + * // executed 0 time(s).', + * // actual: 0, + * // expected: 2, + * // operator: 'func', + * // stack: stack trace + * // } + * // ] + * ``` + * @since v14.2.0, v12.19.0 + * @return An array of objects containing information about the wrapper functions returned by {@link tracker.calls()}. + */ + report(): CallTrackerReportInformation[]; + /** + * Reset calls of the call tracker. If a tracked function is passed as an argument, the calls will be reset for it. + * If no arguments are passed, all tracked functions will be reset. + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * + * callsfunc(); + * // Tracker was called once + * assert.strictEqual(tracker.getCalls(callsfunc).length, 1); + * + * tracker.reset(callsfunc); + * assert.strictEqual(tracker.getCalls(callsfunc).length, 0); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn a tracked function to reset. + */ + reset(fn?: Function): void; + /** + * Iterates through the list of functions passed to {@link tracker.calls()} and will throw an error for functions that + * have not been called the expected number of times. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * callsfunc(); + * + * // Will throw an error since callsfunc() was only called once. + * tracker.verify(); + * ``` + * @since v14.2.0, v12.19.0 + */ + verify(): void; + } + interface CallTrackerCall { + thisArg: object; + arguments: unknown[]; + } + interface CallTrackerReportInformation { + message: string; + /** The actual number of times the function was called. */ + actual: number; + /** The number of times the function was expected to be called. */ + expected: number; + /** The name of the function that is wrapped. */ + operator: string; + /** A stack trace of the function. */ + stack: object; + } + type AssertPredicate = RegExp | (new() => object) | ((thrown: unknown) => boolean) | object | Error; + /** + * Throws an `AssertionError` with the provided error message or a default + * error message. If the `message` parameter is an instance of an `Error` then + * it will be thrown instead of the `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.fail(); + * // AssertionError [ERR_ASSERTION]: Failed + * + * assert.fail('boom'); + * // AssertionError [ERR_ASSERTION]: boom + * + * assert.fail(new TypeError('need array')); + * // TypeError: need array + * ``` + * + * Using `assert.fail()` with more than two arguments is possible but deprecated. + * See below for further details. + * @since v0.1.21 + * @param [message='Failed'] + */ + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail( + actual: unknown, + expected: unknown, + message?: string | Error, + operator?: string, + // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type + stackStartFn?: Function, + ): never; + /** + * Tests if `value` is truthy. It is equivalent to `assert.equal(!!value, true, message)`. + * + * If `value` is not truthy, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is `undefined`, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. + * + * Be aware that in the `repl` the error message will be different to the one + * thrown in a file! See below for further details. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ok(true); + * // OK + * assert.ok(1); + * // OK + * + * assert.ok(); + * // AssertionError: No value argument passed to `assert.ok()` + * + * assert.ok(false, 'it\'s false'); + * // AssertionError: it's false + * + * // In the repl: + * assert.ok(typeof 123 === 'string'); + * // AssertionError: false == true + * + * // In a file (e.g. test.js): + * assert.ok(typeof 123 === 'string'); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(typeof 123 === 'string') + * + * assert.ok(false); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(false) + * + * assert.ok(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(0) + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * // Using `assert()` works the same: + * assert(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert(0) + * ``` + * @since v0.1.21 + */ + function ok(value: unknown, message?: string | Error): asserts value; + /** + * **Strict assertion mode** + * + * An alias of {@link strictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link strictEqual} instead. + * + * Tests shallow, coercive equality between the `actual` and `expected` parameters + * using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled + * and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.equal(1, 1); + * // OK, 1 == 1 + * assert.equal(1, '1'); + * // OK, 1 == '1' + * assert.equal(NaN, NaN); + * // OK + * + * assert.equal(1, 2); + * // AssertionError: 1 == 2 + * assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); + * // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } + * ``` + * + * If the values are not equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v0.1.21 + */ + function equal(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. + * + * Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is + * specially handled and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.notEqual(1, 2); + * // OK + * + * assert.notEqual(1, 1); + * // AssertionError: 1 != 1 + * + * assert.notEqual(1, '1'); + * // AssertionError: 1 != '1' + * ``` + * + * If the values are equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default error + * message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v0.1.21 + */ + function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link deepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead. + * + * Tests for deep equality between the `actual` and `expected` parameters. Consider + * using {@link deepStrictEqual} instead. {@link deepEqual} can have + * surprising results. + * + * _Deep equality_ means that the enumerable "own" properties of child objects + * are also recursively evaluated by the following rules. + * @since v0.1.21 + */ + function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notDeepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead. + * + * Tests for any deep inequality. Opposite of {@link deepEqual}. + * + * ```js + * import assert from 'node:assert'; + * + * const obj1 = { + * a: { + * b: 1, + * }, + * }; + * const obj2 = { + * a: { + * b: 2, + * }, + * }; + * const obj3 = { + * a: { + * b: 1, + * }, + * }; + * const obj4 = { __proto__: obj1 }; + * + * assert.notDeepEqual(obj1, obj1); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj2); + * // OK + * + * assert.notDeepEqual(obj1, obj3); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj4); + * // OK + * ``` + * + * If the values are deeply equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests strict equality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.strictEqual(1, 2); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + * // 1 !== 2 + * + * assert.strictEqual(1, 1); + * // OK + * + * assert.strictEqual('Hello foobar', 'Hello World!'); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + actual - expected + * // + * // + 'Hello foobar' + * // - 'Hello World!' + * // ^ + * + * const apples = 1; + * const oranges = 2; + * assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); + * // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 + * + * assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); + * // TypeError: Inputs are not identical + * ``` + * + * If the values are not strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a + * default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function strictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests strict inequality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notStrictEqual(1, 2); + * // OK + * + * assert.notStrictEqual(1, 1); + * // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to: + * // + * // 1 + * + * assert.notStrictEqual(1, '1'); + * // OK + * ``` + * + * If the values are strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a + * default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests for deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. + * @since v1.2.0 + */ + function deepStrictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); + * // OK + * ``` + * + * If the values are deeply and strictly equal, an `AssertionError` is thrown + * with a `message` property set equal to the value of the `message` parameter. If + * the `message` parameter is undefined, a default error message is assigned. If + * the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v1.2.0 + */ + function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Expects the function `fn` to throw an error. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * a validation object where each property will be tested for strict deep equality, + * or an instance of error where each property will be tested for strict deep + * equality including the non-enumerable `message` and `name` properties. When + * using an object, it is also possible to use a regular expression, when + * validating against a string property. See below for examples. + * + * If specified, `message` will be appended to the message provided by the `AssertionError` if the `fn` call fails to throw or in case the error validation + * fails. + * + * Custom validation object/error instance: + * + * ```js + * import assert from 'node:assert/strict'; + * + * const err = new TypeError('Wrong value'); + * err.code = 404; + * err.foo = 'bar'; + * err.info = { + * nested: true, + * baz: 'text', + * }; + * err.reg = /abc/i; + * + * assert.throws( + * () => { + * throw err; + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * info: { + * nested: true, + * baz: 'text', + * }, + * // Only properties on the validation object will be tested for. + * // Using nested objects requires all properties to be present. Otherwise + * // the validation is going to fail. + * }, + * ); + * + * // Using regular expressions to validate error properties: + * assert.throws( + * () => { + * throw err; + * }, + * { + * // The `name` and `message` properties are strings and using regular + * // expressions on those will match against the string. If they fail, an + * // error is thrown. + * name: /^TypeError$/, + * message: /Wrong/, + * foo: 'bar', + * info: { + * nested: true, + * // It is not possible to use regular expressions for nested properties! + * baz: 'text', + * }, + * // The `reg` property contains a regular expression and only if the + * // validation object contains an identical regular expression, it is going + * // to pass. + * reg: /abc/i, + * }, + * ); + * + * // Fails due to the different `message` and `name` properties: + * assert.throws( + * () => { + * const otherErr = new Error('Not found'); + * // Copy all enumerable properties from `err` to `otherErr`. + * for (const [key, value] of Object.entries(err)) { + * otherErr[key] = value; + * } + * throw otherErr; + * }, + * // The error's `message` and `name` properties will also be checked when using + * // an error as validation object. + * err, + * ); + * ``` + * + * Validate instanceof using constructor: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * Error, + * ); + * ``` + * + * Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions): + * + * Using a regular expression runs `.toString` on the error object, and will + * therefore also include the error name. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * /^Error: Wrong value$/, + * ); + * ``` + * + * Custom error validation: + * + * The function must return `true` to indicate all internal validations passed. + * It will otherwise fail with an `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * (err) => { + * assert(err instanceof Error); + * assert(/value/.test(err)); + * // Avoid returning anything from validation functions besides `true`. + * // Otherwise, it's not clear what part of the validation failed. Instead, + * // throw an error about the specific validation that failed (as done in this + * // example) and add as much helpful debugging information to that error as + * // possible. + * return true; + * }, + * 'unexpected error', + * ); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Using the same + * message as the thrown error message is going to result in an `ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using + * a string as the second argument gets considered: + * + * ```js + * import assert from 'node:assert/strict'; + * + * function throwingFirst() { + * throw new Error('First'); + * } + * + * function throwingSecond() { + * throw new Error('Second'); + * } + * + * function notThrowing() {} + * + * // The second argument is a string and the input function threw an Error. + * // The first case will not throw as it does not match for the error message + * // thrown by the input function! + * assert.throws(throwingFirst, 'Second'); + * // In the next example the message has no benefit over the message from the + * // error and since it is not clear if the user intended to actually match + * // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. + * assert.throws(throwingSecond, 'Second'); + * // TypeError [ERR_AMBIGUOUS_ARGUMENT] + * + * // The string is only used (as message) in case the function does not throw: + * assert.throws(notThrowing, 'Second'); + * // AssertionError [ERR_ASSERTION]: Missing expected exception: Second + * + * // If it was intended to match for the error message do this instead: + * // It does not throw because the error messages match. + * assert.throws(throwingSecond, /Second$/); + * + * // If the error message does not match, an AssertionError is thrown. + * assert.throws(throwingFirst, /Second$/); + * // AssertionError [ERR_ASSERTION] + * ``` + * + * Due to the confusing error-prone notation, avoid a string as the second + * argument. + * @since v0.1.21 + */ + function throws(block: () => unknown, message?: string | Error): void; + function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Asserts that the function `fn` does not throw an error. + * + * Using `assert.doesNotThrow()` is actually not useful because there + * is no benefit in catching an error and then rethrowing it. Instead, consider + * adding a comment next to the specific code path that should not throw and keep + * error messages as expressive as possible. + * + * When `assert.doesNotThrow()` is called, it will immediately call the `fn` function. + * + * If an error is thrown and it is the same type as that specified by the `error` parameter, then an `AssertionError` is thrown. If the error is of a + * different type, or if the `error` parameter is undefined, the error is + * propagated back to the caller. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * The following, for instance, will throw the `TypeError` because there is no + * matching error type in the assertion: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * However, the following will result in an `AssertionError` with the message + * 'Got unwanted exception...': + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * TypeError, + * ); + * ``` + * + * If an `AssertionError` is thrown and a value is provided for the `message` parameter, the value of `message` will be appended to the `AssertionError` message: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * /Wrong value/, + * 'Whoops', + * ); + * // Throws: AssertionError: Got unwanted exception: Whoops + * ``` + * @since v0.1.21 + */ + function doesNotThrow(block: () => unknown, message?: string | Error): void; + function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Throws `value` if `value` is not `undefined` or `null`. This is useful when + * testing the `error` argument in callbacks. The stack trace contains all frames + * from the error passed to `ifError()` including the potential new frames for `ifError()` itself. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ifError(null); + * // OK + * assert.ifError(0); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 + * assert.ifError('error'); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' + * assert.ifError(new Error()); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error + * + * // Create some random error frames. + * let err; + * (function errorFrame() { + * err = new Error('test error'); + * })(); + * + * (function ifErrorFrame() { + * assert.ifError(err); + * })(); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error + * // at ifErrorFrame + * // at errorFrame + * ``` + * @since v0.1.97 + */ + function ifError(value: unknown): asserts value is null | undefined; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is rejected. + * + * If `asyncFn` is a function and it throws an error synchronously, `assert.rejects()` will return a rejected `Promise` with that error. If the + * function does not return a promise, `assert.rejects()` will return a rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v24.x/api/errors.html#err_invalid_return_value) + * error. In both cases the error handler is skipped. + * + * Besides the async nature to await the completion behaves identically to {@link throws}. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * an object where each property will be tested for, or an instance of error where + * each property will be tested for including the non-enumerable `message` and `name` properties. + * + * If specified, `message` will be the message provided by the `{@link AssertionError}` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * (err) => { + * assert.strictEqual(err.name, 'TypeError'); + * assert.strictEqual(err.message, 'Wrong value'); + * return true; + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.rejects( + * Promise.reject(new Error('Wrong value')), + * Error, + * ).then(() => { + * // ... + * }); + * ``` + * + * `error` cannot be a string. If a string is provided as the second argument, then `error` is assumed to + * be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Please read the + * example in {@link throws} carefully if using a string as the second argument gets considered. + * @since v10.0.0 + */ + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is not rejected. + * + * If `asyncFn` is a function and it throws an error synchronously, `assert.doesNotReject()` will return a rejected `Promise` with that error. If + * the function does not return a promise, `assert.doesNotReject()` will return a + * rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v24.x/api/errors.html#err_invalid_return_value) error. In both cases + * the error handler is skipped. + * + * Using `assert.doesNotReject()` is actually not useful because there is little + * benefit in catching a rejection and then rejecting it again. Instead, consider + * adding a comment next to the specific code path that should not reject and keep + * error messages as expressive as possible. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) + * .then(() => { + * // ... + * }); + * ``` + * @since v10.0.0 + */ + function doesNotReject( + block: (() => Promise) | Promise, + message?: string | Error, + ): Promise; + function doesNotReject( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Expects the `string` input to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.match('I will fail', /pass/); + * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... + * + * assert.match(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.match('I will pass', /pass/); + * // OK + * ``` + * + * If the values do not match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an [Error](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`. + * @since v13.6.0, v12.16.0 + */ + function match(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Expects the `string` input not to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotMatch('I will fail', /fail/); + * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... + * + * assert.doesNotMatch(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.doesNotMatch('I will pass', /different/); + * // OK + * ``` + * + * If the values do match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an [Error](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`. + * @since v13.6.0, v12.16.0 + */ + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Tests for partial deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. "Partial" equality means + * that only properties that exist on the `expected` parameter are going to be + * compared. + * + * This method always passes the same test cases as `assert.deepStrictEqual()`, + * behaving as a super set of it. + * @since v22.13.0 + */ + function partialDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * In strict assertion mode, non-strict methods behave like their corresponding strict methods. For example, + * {@link deepEqual} will behave like {@link deepStrictEqual}. + * + * In strict assertion mode, error messages for objects display a diff. In legacy assertion mode, error + * messages for objects display the objects, often truncated. + * + * To use strict assertion mode: + * + * ```js + * import { strict as assert } from 'node:assert'; + * import assert from 'node:assert/strict'; + * ``` + * + * Example error diff: + * + * ```js + * import { strict as assert } from 'node:assert'; + * + * assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]); + * // AssertionError: Expected inputs to be strictly deep-equal: + * // + actual - expected ... Lines skipped + * // + * // [ + * // [ + * // ... + * // 2, + * // + 3 + * // - '3' + * // ], + * // ... + * // 5 + * // ] + * ``` + * + * To deactivate the colors, use the `NO_COLOR` or `NODE_DISABLE_COLORS` environment variables. This will also + * deactivate the colors in the REPL. For more on color support in terminal environments, read the tty + * `getColorDepth()` documentation. + * + * @since v15.0.0, v13.9.0, v12.16.2, v9.9.0 + */ + namespace strict { + type AssertionError = assert.AssertionError; + type AssertPredicate = assert.AssertPredicate; + type CallTrackerCall = assert.CallTrackerCall; + type CallTrackerReportInformation = assert.CallTrackerReportInformation; + } + const strict: + & Omit< + typeof assert, + | "equal" + | "notEqual" + | "deepEqual" + | "notDeepEqual" + | "ok" + | "strictEqual" + | "deepStrictEqual" + | "ifError" + | "strict" + | "AssertionError" + > + & { + (value: unknown, message?: string | Error): asserts value; + equal: typeof strictEqual; + notEqual: typeof notStrictEqual; + deepEqual: typeof deepStrictEqual; + notDeepEqual: typeof notDeepStrictEqual; + // Mapped types and assertion functions are incompatible? + // TS2775: Assertions require every name in the call target + // to be declared with an explicit type annotation. + ok: typeof ok; + strictEqual: typeof strictEqual; + deepStrictEqual: typeof deepStrictEqual; + ifError: typeof ifError; + strict: typeof strict; + AssertionError: typeof AssertionError; + }; + } + export = assert; +} +declare module "node:assert" { + import assert = require("assert"); + export = assert; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/assert/strict.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/assert/strict.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f333913a4565f7067b05ddbc415490e585f2d1e1 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/assert/strict.d.ts @@ -0,0 +1,8 @@ +declare module "assert/strict" { + import { strict } from "node:assert"; + export = strict; +} +declare module "node:assert/strict" { + import { strict } from "node:assert"; + export = strict; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/async_hooks.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/async_hooks.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2377689f865bf238b24201284c843f21ccc321cf --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,623 @@ +/** + * We strongly discourage the use of the `async_hooks` API. + * Other APIs that can cover most of its use cases include: + * + * * [`AsyncLocalStorage`](https://nodejs.org/docs/latest-v24.x/api/async_context.html#class-asynclocalstorage) tracks async context + * * [`process.getActiveResourcesInfo()`](https://nodejs.org/docs/latest-v24.x/api/process.html#processgetactiveresourcesinfo) tracks active resources + * + * The `node:async_hooks` module provides an API to track asynchronous resources. + * It can be accessed using: + * + * ```js + * import async_hooks from 'node:async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/async_hooks.js) + */ +declare module "async_hooks" { + /** + * ```js + * import { executionAsyncId } from 'node:async_hooks'; + * import fs from 'node:fs'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * const path = '.'; + * fs.open(path, 'r', (err, fd) => { + * console.log(executionAsyncId()); // 6 - open() + * }); + * ``` + * + * The ID returned from `executionAsyncId()` is related to execution timing, not + * causality (which is covered by `triggerAsyncId()`): + * + * ```js + * const server = net.createServer((conn) => { + * // Returns the ID of the server, not of the new connection, because the + * // callback runs in the execution scope of the server's MakeCallback(). + * async_hooks.executionAsyncId(); + * + * }).listen(port, () => { + * // Returns the ID of a TickObject (process.nextTick()) because all + * // callbacks passed to .listen() are wrapped in a nextTick(). + * async_hooks.executionAsyncId(); + * }); + * ``` + * + * Promise contexts may not get precise `executionAsyncIds` by default. + * See the section on [promise execution tracking](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html#promise-execution-tracking). + * @since v8.1.0 + * @return The `asyncId` of the current execution context. Useful to track when something calls. + */ + function executionAsyncId(): number; + /** + * Resource objects returned by `executionAsyncResource()` are most often internal + * Node.js handle objects with undocumented APIs. Using any functions or properties + * on the object is likely to crash your application and should be avoided. + * + * Using `executionAsyncResource()` in the top-level execution context will + * return an empty object as there is no handle or request object to use, + * but having an object representing the top-level can be helpful. + * + * ```js + * import { open } from 'node:fs'; + * import { executionAsyncId, executionAsyncResource } from 'node:async_hooks'; + * + * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} + * open(new URL(import.meta.url), 'r', (err, fd) => { + * console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap + * }); + * ``` + * + * This can be used to implement continuation local storage without the + * use of a tracking `Map` to store the metadata: + * + * ```js + * import { createServer } from 'node:http'; + * import { + * executionAsyncId, + * executionAsyncResource, + * createHook, + * } from 'node:async_hooks'; + * const sym = Symbol('state'); // Private symbol to avoid pollution + * + * createHook({ + * init(asyncId, type, triggerAsyncId, resource) { + * const cr = executionAsyncResource(); + * if (cr) { + * resource[sym] = cr[sym]; + * } + * }, + * }).enable(); + * + * const server = createServer((req, res) => { + * executionAsyncResource()[sym] = { state: req.url }; + * setTimeout(function() { + * res.end(JSON.stringify(executionAsyncResource()[sym])); + * }, 100); + * }).listen(3000); + * ``` + * @since v13.9.0, v12.17.0 + * @return The resource representing the current execution. Useful to store data within the resource. + */ + function executionAsyncResource(): object; + /** + * ```js + * const server = net.createServer((conn) => { + * // The resource that caused (or triggered) this callback to be called + * // was that of the new connection. Thus the return value of triggerAsyncId() + * // is the asyncId of "conn". + * async_hooks.triggerAsyncId(); + * + * }).listen(port, () => { + * // Even though all callbacks passed to .listen() are wrapped in a nextTick() + * // the callback itself exists because the call to the server's .listen() + * // was made. So the return value would be the ID of the server. + * async_hooks.triggerAsyncId(); + * }); + * ``` + * + * Promise contexts may not get valid `triggerAsyncId`s by default. See + * the section on [promise execution tracking](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html#promise-execution-tracking). + * @return The ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId A unique ID for the async resource + * @param type The type of the async resource + * @param triggerAsyncId The unique ID of the async resource in whose execution context this async resource was created + * @param resource Reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + /** + * Called immediately after the callback specified in `before` is completed. + * + * If an uncaught exception occurs during execution of the callback, then `after` will run after the `'uncaughtException'` event is emitted or a `domain`'s handler runs. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + /** + * Registers functions to be called for different lifetime events of each async + * operation. + * + * The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the + * respective asynchronous event during a resource's lifetime. + * + * All callbacks are optional. For example, if only resource cleanup needs to + * be tracked, then only the `destroy` callback needs to be passed. The + * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. + * + * ```js + * import { createHook } from 'node:async_hooks'; + * + * const asyncHook = createHook({ + * init(asyncId, type, triggerAsyncId, resource) { }, + * destroy(asyncId) { }, + * }); + * ``` + * + * The callbacks will be inherited via the prototype chain: + * + * ```js + * class MyAsyncCallbacks { + * init(asyncId, type, triggerAsyncId, resource) { } + * destroy(asyncId) {} + * } + * + * class MyAddedCallbacks extends MyAsyncCallbacks { + * before(asyncId) { } + * after(asyncId) { } + * } + * + * const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); + * ``` + * + * Because promises are asynchronous resources whose lifecycle is tracked + * via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises. + * @since v8.1.0 + * @param callbacks The `Hook Callbacks` to register + * @return Instance used for disabling and enabling hooks + */ + function createHook(callbacks: HookCallbacks): AsyncHook; + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * @default executionAsyncId() + */ + triggerAsyncId?: number | undefined; + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * @default false + */ + requireManualDestroy?: boolean | undefined; + } + /** + * The class `AsyncResource` is designed to be extended by the embedder's async + * resources. Using this, users can easily trigger the lifetime events of their + * own resources. + * + * The `init` hook will trigger when an `AsyncResource` is instantiated. + * + * The following is an overview of the `AsyncResource` API. + * + * ```js + * import { AsyncResource, executionAsyncId } from 'node:async_hooks'; + * + * // AsyncResource() is meant to be extended. Instantiating a + * // new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * // async_hook.executionAsyncId() is used. + * const asyncResource = new AsyncResource( + * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }, + * ); + * + * // Run a function in the execution context of the resource. This will + * // * establish the context of the resource + * // * trigger the AsyncHooks before callbacks + * // * call the provided function `fn` with the supplied arguments + * // * trigger the AsyncHooks after callbacks + * // * restore the original execution context + * asyncResource.runInAsyncScope(fn, thisArg, ...args); + * + * // Call AsyncHooks destroy callbacks. + * asyncResource.emitDestroy(); + * + * // Return the unique ID assigned to the AsyncResource instance. + * asyncResource.asyncId(); + * + * // Return the trigger ID for the AsyncResource instance. + * asyncResource.triggerAsyncId(); + * ``` + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since v9.3.0) + */ + constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); + /** + * Binds the given function to the current execution context. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current execution context. + * @param type An optional name to associate with the underlying `AsyncResource`. + */ + static bind any, ThisArg>( + fn: Func, + type?: string, + thisArg?: ThisArg, + ): Func; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>(fn: Func): Func; + /** + * Call the provided function with the provided arguments in the execution context + * of the async resource. This will establish the context, trigger the AsyncHooks + * before callbacks, call the function, trigger the AsyncHooks after callbacks, and + * then restore the original execution context. + * @since v9.6.0 + * @param fn The function to call in the execution context of this async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope( + fn: (this: This, ...args: any[]) => Result, + thisArg?: This, + ...args: any[] + ): Result; + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + * @return A reference to `asyncResource`. + */ + emitDestroy(): this; + /** + * @return The unique `asyncId` assigned to the resource. + */ + asyncId(): number; + /** + * @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. + */ + triggerAsyncId(): number; + } + interface AsyncLocalStorageOptions { + /** + * The default value to be used when no store is provided. + */ + defaultValue?: any; + /** + * A name for the `AsyncLocalStorage` value. + */ + name?: string | undefined; + } + /** + * This class creates stores that stay coherent through asynchronous operations. + * + * While you can create your own implementation on top of the `node:async_hooks` module, `AsyncLocalStorage` should be preferred as it is a performant and memory + * safe implementation that involves significant optimizations that are non-obvious + * to implement. + * + * The following example uses `AsyncLocalStorage` to build a simple logger + * that assigns IDs to incoming HTTP requests and includes them in messages + * logged within each request. + * + * ```js + * import http from 'node:http'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const asyncLocalStorage = new AsyncLocalStorage(); + * + * function logWithId(msg) { + * const id = asyncLocalStorage.getStore(); + * console.log(`${id !== undefined ? id : '-'}:`, msg); + * } + * + * let idSeq = 0; + * http.createServer((req, res) => { + * asyncLocalStorage.run(idSeq++, () => { + * logWithId('start'); + * // Imagine any chain of async operations here + * setImmediate(() => { + * logWithId('finish'); + * res.end(); + * }); + * }); + * }).listen(8080); + * + * http.get('http://localhost:8080'); + * http.get('http://localhost:8080'); + * // Prints: + * // 0: start + * // 0: finish + * // 1: start + * // 1: finish + * ``` + * + * Each instance of `AsyncLocalStorage` maintains an independent storage context. + * Multiple instances can safely exist simultaneously without risk of interfering + * with each other's data. + * @since v13.10.0, v12.17.0 + */ + class AsyncLocalStorage { + /** + * Creates a new instance of `AsyncLocalStorage`. Store is only provided within a + * `run()` call or after an `enterWith()` call. + */ + constructor(options?: AsyncLocalStorageOptions); + /** + * Binds the given function to the current execution context. + * @since v19.8.0 + * @param fn The function to bind to the current execution context. + * @return A new function that calls `fn` within the captured execution context. + */ + static bind any>(fn: Func): Func; + /** + * Captures the current execution context and returns a function that accepts a + * function as an argument. Whenever the returned function is called, it + * calls the function passed to it within the captured context. + * + * ```js + * const asyncLocalStorage = new AsyncLocalStorage(); + * const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot()); + * const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); + * console.log(result); // returns 123 + * ``` + * + * AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple + * async context tracking purposes, for example: + * + * ```js + * class Foo { + * #runInAsyncScope = AsyncLocalStorage.snapshot(); + * + * get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); } + * } + * + * const foo = asyncLocalStorage.run(123, () => new Foo()); + * console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123 + * ``` + * @since v19.8.0 + * @return A new function with the signature `(fn: (...args) : R, ...args) : R`. + */ + static snapshot(): (fn: (...args: TArgs) => R, ...args: TArgs) => R; + /** + * Disables the instance of `AsyncLocalStorage`. All subsequent calls + * to `asyncLocalStorage.getStore()` will return `undefined` until `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. + * + * When calling `asyncLocalStorage.disable()`, all current contexts linked to the + * instance will be exited. + * + * Calling `asyncLocalStorage.disable()` is required before the `asyncLocalStorage` can be garbage collected. This does not apply to stores + * provided by the `asyncLocalStorage`, as those objects are garbage collected + * along with the corresponding async resources. + * + * Use this method when the `asyncLocalStorage` is not in use anymore + * in the current process. + * @since v13.10.0, v12.17.0 + * @experimental + */ + disable(): void; + /** + * Returns the current store. + * If called outside of an asynchronous context initialized by + * calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it + * returns `undefined`. + * @since v13.10.0, v12.17.0 + */ + getStore(): T | undefined; + /** + * The name of the `AsyncLocalStorage` instance if provided. + * @since v24.0.0 + */ + readonly name: string; + /** + * Runs a function synchronously within a context and returns its + * return value. The store is not accessible outside of the callback function. + * The store is accessible to any asynchronous operations created within the + * callback. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `run()` too. + * The stacktrace is not impacted by this call and the context is exited. + * + * Example: + * + * ```js + * const store = { id: 2 }; + * try { + * asyncLocalStorage.run(store, () => { + * asyncLocalStorage.getStore(); // Returns the store object + * setTimeout(() => { + * asyncLocalStorage.getStore(); // Returns the store object + * }, 200); + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns undefined + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + */ + run(store: T, callback: () => R): R; + run(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Runs a function synchronously outside of a context and returns its + * return value. The store is not accessible within the callback function or + * the asynchronous operations created within the callback. Any `getStore()` call done within the callback function will always return `undefined`. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `exit()` too. + * The stacktrace is not impacted by this call and the context is re-entered. + * + * Example: + * + * ```js + * // Within a call to run + * try { + * asyncLocalStorage.getStore(); // Returns the store object or value + * asyncLocalStorage.exit(() => { + * asyncLocalStorage.getStore(); // Returns undefined + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns the same object or value + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + * @experimental + */ + exit(callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Transitions into the context for the remainder of the current + * synchronous execution and then persists the store through any following + * asynchronous calls. + * + * Example: + * + * ```js + * const store = { id: 1 }; + * // Replaces previous store with the given store object + * asyncLocalStorage.enterWith(store); + * asyncLocalStorage.getStore(); // Returns the store object + * someAsyncOperation(() => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * ``` + * + * This transition will continue for the _entire_ synchronous execution. + * This means that if, for example, the context is entered within an event + * handler subsequent event handlers will also run within that context unless + * specifically bound to another context with an `AsyncResource`. That is why `run()` should be preferred over `enterWith()` unless there are strong reasons + * to use the latter method. + * + * ```js + * const store = { id: 1 }; + * + * emitter.on('my-event', () => { + * asyncLocalStorage.enterWith(store); + * }); + * emitter.on('my-event', () => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * + * asyncLocalStorage.getStore(); // Returns undefined + * emitter.emit('my-event'); + * asyncLocalStorage.getStore(); // Returns the same object + * ``` + * @since v13.11.0, v12.17.0 + * @experimental + */ + enterWith(store: T): void; + } + /** + * @since v17.2.0, v16.14.0 + * @return A map of provider types to the corresponding numeric id. + * This map contains all the event types that might be emitted by the `async_hooks.init()` event. + */ + namespace asyncWrapProviders { + const NONE: number; + const DIRHANDLE: number; + const DNSCHANNEL: number; + const ELDHISTOGRAM: number; + const FILEHANDLE: number; + const FILEHANDLECLOSEREQ: number; + const FIXEDSIZEBLOBCOPY: number; + const FSEVENTWRAP: number; + const FSREQCALLBACK: number; + const FSREQPROMISE: number; + const GETADDRINFOREQWRAP: number; + const GETNAMEINFOREQWRAP: number; + const HEAPSNAPSHOT: number; + const HTTP2SESSION: number; + const HTTP2STREAM: number; + const HTTP2PING: number; + const HTTP2SETTINGS: number; + const HTTPINCOMINGMESSAGE: number; + const HTTPCLIENTREQUEST: number; + const JSSTREAM: number; + const JSUDPWRAP: number; + const MESSAGEPORT: number; + const PIPECONNECTWRAP: number; + const PIPESERVERWRAP: number; + const PIPEWRAP: number; + const PROCESSWRAP: number; + const PROMISE: number; + const QUERYWRAP: number; + const SHUTDOWNWRAP: number; + const SIGNALWRAP: number; + const STATWATCHER: number; + const STREAMPIPE: number; + const TCPCONNECTWRAP: number; + const TCPSERVERWRAP: number; + const TCPWRAP: number; + const TTYWRAP: number; + const UDPSENDWRAP: number; + const UDPWRAP: number; + const SIGINTWATCHDOG: number; + const WORKER: number; + const WORKERHEAPSNAPSHOT: number; + const WRITEWRAP: number; + const ZLIB: number; + const CHECKPRIMEREQUEST: number; + const PBKDF2REQUEST: number; + const KEYPAIRGENREQUEST: number; + const KEYGENREQUEST: number; + const KEYEXPORTREQUEST: number; + const CIPHERREQUEST: number; + const DERIVEBITSREQUEST: number; + const HASHREQUEST: number; + const RANDOMBYTESREQUEST: number; + const RANDOMPRIMEREQUEST: number; + const SCRYPTREQUEST: number; + const SIGNREQUEST: number; + const TLSWRAP: number; + const VERIFYREQUEST: number; + } +} +declare module "node:async_hooks" { + export * from "async_hooks"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/buffer.buffer.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/buffer.buffer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b22f83a291507d2c30848803eb3257edf8c3c497 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/buffer.buffer.d.ts @@ -0,0 +1,463 @@ +declare module "buffer" { + type ImplicitArrayBuffer> = T extends + { valueOf(): infer V extends ArrayBufferLike } ? V : T; + global { + interface BufferConstructor { + // see buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: ArrayLike): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: TArrayBuffer): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * If `array` is an `Array`-like object (that is, one with a `length` property of + * type `number`), it is treated as if it is an array, unless it is a `Buffer` or + * a `Uint8Array`. This means all other `TypedArray` variants get treated as an + * `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use + * `Buffer.copyBytesFrom()`. + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal + * `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from(array: WithImplicitCoercion>): Buffer; + /** + * This creates a view of the `ArrayBuffer` without copying the underlying + * memory. For example, when passed a reference to the `.buffer` property of a + * `TypedArray` instance, the newly created `Buffer` will share the same + * allocated memory as the `TypedArray`'s underlying `ArrayBuffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arr = new Uint16Array(2); + * + * arr[0] = 5000; + * arr[1] = 4000; + * + * // Shares memory with `arr`. + * const buf = Buffer.from(arr.buffer); + * + * console.log(buf); + * // Prints: + * + * // Changing the original Uint16Array changes the Buffer also. + * arr[1] = 6000; + * + * console.log(buf); + * // Prints: + * ``` + * + * The optional `byteOffset` and `length` arguments specify a memory range within + * the `arrayBuffer` that will be shared by the `Buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const ab = new ArrayBuffer(10); + * const buf = Buffer.from(ab, 0, 2); + * + * console.log(buf.length); + * // Prints: 2 + * ``` + * + * A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer` or a + * `SharedArrayBuffer` or another type appropriate for `Buffer.from()` + * variants. + * + * It is important to remember that a backing `ArrayBuffer` can cover a range + * of memory that extends beyond the bounds of a `TypedArray` view. A new + * `Buffer` created using the `buffer` property of a `TypedArray` may extend + * beyond the range of the `TypedArray`: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements + * const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements + * console.log(arrA.buffer === arrB.buffer); // true + * + * const buf = Buffer.from(arrB.buffer); + * console.log(buf); + * // Prints: + * ``` + * @since v5.10.0 + * @param arrayBuffer An `ArrayBuffer`, `SharedArrayBuffer`, for example the + * `.buffer` property of a `TypedArray`. + * @param byteOffset Index of first byte to expose. **Default:** `0`. + * @param length Number of bytes to expose. **Default:** + * `arrayBuffer.byteLength - byteOffset`. + */ + from>( + arrayBuffer: TArrayBuffer, + byteOffset?: number, + length?: number, + ): Buffer>; + /** + * Creates a new `Buffer` containing `string`. The `encoding` parameter identifies + * the character encoding to be used when converting `string` into bytes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('this is a tést'); + * const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); + * + * console.log(buf1.toString()); + * // Prints: this is a tést + * console.log(buf2.toString()); + * // Prints: this is a tést + * console.log(buf1.toString('latin1')); + * // Prints: this is a tést + * ``` + * + * A `TypeError` will be thrown if `string` is not a string or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(string)` may also use the internal `Buffer` pool like + * `Buffer.allocUnsafe()` does. + * @since v5.10.0 + * @param string A string to encode. + * @param encoding The encoding of `string`. **Default:** `'utf8'`. + */ + from(string: WithImplicitCoercion, encoding?: BufferEncoding): Buffer; + from(arrayOrString: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. If the combined length of the `Buffer`s in `list` is + * less than `totalLength`, the remaining space is filled with zeros. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: readonly Uint8Array[], totalLength?: number): Buffer; + /** + * Copies the underlying memory of `view` into a new `Buffer`. + * + * ```js + * const u16 = new Uint16Array([0, 0xffff]); + * const buf = Buffer.copyBytesFrom(u16, 1, 1); + * u16[1] = 0; + * console.log(buf.length); // 2 + * console.log(buf[0]); // 255 + * console.log(buf[1]); // 255 + * ``` + * @since v19.8.0 + * @param view The {TypedArray} to copy. + * @param [offset=0] The starting offset within `view`. + * @param [length=view.length - offset] The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, + * and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if + * `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + } + interface Buffer extends Uint8Array { + // see buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @since v0.3.0 + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + } + type NonSharedBuffer = Buffer; + type AllowSharedBuffer = Buffer; + } + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + var SlowBuffer: { + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + new(size: number): Buffer; + prototype: Buffer; + }; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/buffer.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/buffer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cbdf207cd1234609fdfaa1715a00d1d27e415d1b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,1930 @@ +// If lib.dom.d.ts or lib.webworker.d.ts is loaded, then use the global types. +// Otherwise, use the types from node. +type _Blob = typeof globalThis extends { onmessage: any; Blob: any } ? {} : import("buffer").Blob; +type _File = typeof globalThis extends { onmessage: any; File: any } ? {} : import("buffer").File; + +/** + * `Buffer` objects are used to represent a fixed-length sequence of bytes. Many + * Node.js APIs support `Buffer`s. + * + * The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and + * extends it with methods that cover additional use cases. Node.js APIs accept + * plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) s wherever `Buffer`s are supported as well. + * + * While the `Buffer` class is available within the global scope, it is still + * recommended to explicitly reference it via an import or require statement. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a zero-filled Buffer of length 10. + * const buf1 = Buffer.alloc(10); + * + * // Creates a Buffer of length 10, + * // filled with bytes which all have the value `1`. + * const buf2 = Buffer.alloc(10, 1); + * + * // Creates an uninitialized buffer of length 10. + * // This is faster than calling Buffer.alloc() but the returned + * // Buffer instance might contain old data that needs to be + * // overwritten using fill(), write(), or other functions that fill the Buffer's + * // contents. + * const buf3 = Buffer.allocUnsafe(10); + * + * // Creates a Buffer containing the bytes [1, 2, 3]. + * const buf4 = Buffer.from([1, 2, 3]); + * + * // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries + * // are all truncated using `(value & 255)` to fit into the range 0–255. + * const buf5 = Buffer.from([257, 257.5, -255, '1']); + * + * // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést': + * // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation) + * // [116, 195, 169, 115, 116] (in decimal notation) + * const buf6 = Buffer.from('tést'); + * + * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. + * const buf7 = Buffer.from('tést', 'latin1'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/buffer.js) + */ +declare module "buffer" { + import { BinaryLike } from "node:crypto"; + import { ReadableStream as WebReadableStream } from "node:stream/web"; + /** + * This function returns `true` if `input` contains only valid UTF-8-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.4.0, v18.14.0 + * @param input The input to validate. + */ + export function isUtf8(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; + /** + * This function returns `true` if `input` contains only valid ASCII-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.6.0, v18.15.0 + * @param input The input to validate. + */ + export function isAscii(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; + export let INSPECT_MAX_BYTES: number; + export const kMaxLength: number; + export const kStringMaxLength: number; + export const constants: { + MAX_LENGTH: number; + MAX_STRING_LENGTH: number; + }; + export type TranscodeEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "latin1" + | "binary"; + /** + * Re-encodes the given `Buffer` or `Uint8Array` instance from one character + * encoding to another. Returns a new `Buffer` instance. + * + * Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if + * conversion from `fromEnc` to `toEnc` is not permitted. + * + * Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`, `'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. + * + * The transcoding process will use substitution characters if a given byte + * sequence cannot be adequately represented in the target encoding. For instance: + * + * ```js + * import { Buffer, transcode } from 'node:buffer'; + * + * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); + * console.log(newBuf.toString('ascii')); + * // Prints: '?' + * ``` + * + * Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced + * with `?` in the transcoded `Buffer`. + * @since v7.1.0 + * @param source A `Buffer` or `Uint8Array` instance. + * @param fromEnc The current encoding. + * @param toEnc To target encoding. + */ + export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; + /** + * Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using + * a prior call to `URL.createObjectURL()`. + * @since v16.7.0 + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + export function resolveObjectURL(id: string): Blob | undefined; + export { type AllowSharedBuffer, Buffer, type NonSharedBuffer }; + /** + * @experimental + */ + export interface BlobOptions { + /** + * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts + * will be converted to the platform native line-ending as specified by `import { EOL } from 'node:os'`. + */ + endings?: "transparent" | "native"; + /** + * The Blob content-type. The intent is for `type` to convey + * the MIME media type of the data, however no validation of the type format + * is performed. + */ + type?: string | undefined; + } + /** + * A [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) encapsulates immutable, raw data that can be safely shared across + * multiple worker threads. + * @since v15.7.0, v14.18.0 + */ + export class Blob { + /** + * The total size of the `Blob` in bytes. + * @since v15.7.0, v14.18.0 + */ + readonly size: number; + /** + * The content-type of the `Blob`. + * @since v15.7.0, v14.18.0 + */ + readonly type: string; + /** + * Creates a new `Blob` object containing a concatenation of the given sources. + * + * {ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into + * the 'Blob' and can therefore be safely modified after the 'Blob' is created. + * + * String sources are also copied into the `Blob`. + */ + constructor(sources: Array, options?: BlobOptions); + /** + * Returns a promise that fulfills with an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of + * the `Blob` data. + * @since v15.7.0, v14.18.0 + */ + arrayBuffer(): Promise; + /** + * The `blob.bytes()` method returns the byte of the `Blob` object as a `Promise`. + * + * ```js + * const blob = new Blob(['hello']); + * blob.bytes().then((bytes) => { + * console.log(bytes); // Outputs: Uint8Array(5) [ 104, 101, 108, 108, 111 ] + * }); + * ``` + */ + bytes(): Promise; + /** + * Creates and returns a new `Blob` containing a subset of this `Blob` objects + * data. The original `Blob` is not altered. + * @since v15.7.0, v14.18.0 + * @param start The starting index. + * @param end The ending index. + * @param type The content-type for the new `Blob` + */ + slice(start?: number, end?: number, type?: string): Blob; + /** + * Returns a promise that fulfills with the contents of the `Blob` decoded as a + * UTF-8 string. + * @since v15.7.0, v14.18.0 + */ + text(): Promise; + /** + * Returns a new `ReadableStream` that allows the content of the `Blob` to be read. + * @since v16.7.0 + */ + stream(): WebReadableStream; + } + export interface FileOptions { + /** + * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be + * converted to the platform native line-ending as specified by `import { EOL } from 'node:os'`. + */ + endings?: "native" | "transparent"; + /** The File content-type. */ + type?: string; + /** The last modified date of the file. `Default`: Date.now(). */ + lastModified?: number; + } + /** + * A [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) provides information about files. + * @since v19.2.0, v18.13.0 + */ + export class File extends Blob { + constructor(sources: Array, fileName: string, options?: FileOptions); + /** + * The name of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly name: string; + /** + * The last modified date of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly lastModified: number; + } + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + export type WithImplicitCoercion = + | T + | { valueOf(): T } + | (T extends string ? { [Symbol.toPrimitive](hint: "string"): T } : never); + global { + namespace NodeJS { + export { BufferEncoding }; + } + // Buffer class + type BufferEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex"; + /** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex' + */ + interface BufferConstructor { + // see buffer.buffer.d.ts for implementation specific to TypeScript 5.7 and later + // see ts5.6/buffer.buffer.d.ts for implementation specific to TypeScript 5.6 and earlier + + /** + * Returns `true` if `obj` is a `Buffer`, `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * Buffer.isBuffer(Buffer.alloc(10)); // true + * Buffer.isBuffer(Buffer.from('foo')); // true + * Buffer.isBuffer('a string'); // false + * Buffer.isBuffer([]); // false + * Buffer.isBuffer(new Uint8Array(1024)); // false + * ``` + * @since v0.1.101 + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns `true` if `encoding` is the name of a supported character encoding, + * or `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * console.log(Buffer.isEncoding('utf8')); + * // Prints: true + * + * console.log(Buffer.isEncoding('hex')); + * // Prints: true + * + * console.log(Buffer.isEncoding('utf/8')); + * // Prints: false + * + * console.log(Buffer.isEncoding('')); + * // Prints: false + * ``` + * @since v0.9.1 + * @param encoding A character encoding name to check. + */ + isEncoding(encoding: string): encoding is BufferEncoding; + /** + * Returns the byte length of a string when encoded using `encoding`. + * This is not the same as [`String.prototype.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), which does not account + * for the encoding that is used to convert the string into bytes. + * + * For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input. + * For strings that contain non-base64/hex-encoded data (e.g. whitespace), the + * return value might be greater than the length of a `Buffer` created from the + * string. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const str = '\u00bd + \u00bc = \u00be'; + * + * console.log(`${str}: ${str.length} characters, ` + + * `${Buffer.byteLength(str, 'utf8')} bytes`); + * // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes + * ``` + * + * When `string` is a + * `Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/- + * Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop- + * er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned. + * @since v0.1.90 + * @param string A value to calculate the length of. + * @param [encoding='utf8'] If `string` is a string, this is its encoding. + * @return The number of bytes contained within `string`. + */ + byteLength( + string: string | Buffer | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, + encoding?: BufferEncoding, + ): number; + /** + * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of `Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('1234'); + * const buf2 = Buffer.from('0123'); + * const arr = [buf1, buf2]; + * + * console.log(arr.sort(Buffer.compare)); + * // Prints: [ , ] + * // (This result is equal to: [buf2, buf1].) + * ``` + * @since v0.11.13 + * @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details. + */ + compare(buf1: Uint8Array, buf2: Uint8Array): -1 | 0 | 1; + /** + * This is the size (in bytes) of pre-allocated internal `Buffer` instances used + * for pooling. This value may be modified. + * @since v0.11.3 + */ + poolSize: number; + } + interface Buffer { + // see buffer.buffer.d.ts for implementation specific to TypeScript 5.7 and later + // see ts5.6/buffer.buffer.d.ts for implementation specific to TypeScript 5.6 and earlier + + /** + * Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did + * not contain enough space to fit the entire string, only part of `string` will be + * written. However, partially encoded characters will not be written. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(256); + * + * const len = buf.write('\u00bd + \u00bc = \u00be', 0); + * + * console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); + * // Prints: 12 bytes: ½ + ¼ = ¾ + * + * const buffer = Buffer.alloc(10); + * + * const length = buffer.write('abcd', 8); + * + * console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); + * // Prints: 2 bytes : ab + * ``` + * @since v0.1.90 + * @param string String to write to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write `string`. + * @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). + * @param [encoding='utf8'] The character encoding of `string`. + * @return Number of bytes written. + */ + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + /** + * Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`. + * + * If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8, + * then each invalid byte is replaced with the replacement character `U+FFFD`. + * + * The maximum length of a string instance (in UTF-16 code units) is available + * as {@link constants.MAX_STRING_LENGTH}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * console.log(buf1.toString('utf8')); + * // Prints: abcdefghijklmnopqrstuvwxyz + * console.log(buf1.toString('utf8', 0, 5)); + * // Prints: abcde + * + * const buf2 = Buffer.from('tést'); + * + * console.log(buf2.toString('hex')); + * // Prints: 74c3a97374 + * console.log(buf2.toString('utf8', 0, 3)); + * // Prints: té + * console.log(buf2.toString(undefined, 0, 3)); + * // Prints: té + * ``` + * @since v0.1.90 + * @param [encoding='utf8'] The character encoding to use. + * @param [start=0] The byte offset to start decoding at. + * @param [end=buf.length] The byte offset to stop decoding at (not inclusive). + */ + toString(encoding?: BufferEncoding, start?: number, end?: number): string; + /** + * Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls + * this function when stringifying a `Buffer` instance. + * + * `Buffer.from()` accepts objects in the format returned from this method. + * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); + * const json = JSON.stringify(buf); + * + * console.log(json); + * // Prints: {"type":"Buffer","data":[1,2,3,4,5]} + * + * const copy = JSON.parse(json, (key, value) => { + * return value && value.type === 'Buffer' ? + * Buffer.from(value) : + * value; + * }); + * + * console.log(copy); + * // Prints: + * ``` + * @since v0.9.2 + */ + toJSON(): { + type: "Buffer"; + data: number[]; + }; + /** + * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('414243', 'hex'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.equals(buf2)); + * // Prints: true + * console.log(buf1.equals(buf3)); + * // Prints: false + * ``` + * @since v0.11.13 + * @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`. + */ + equals(otherBuffer: Uint8Array): boolean; + /** + * Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order. + * Comparison is based on the actual sequence of bytes in each `Buffer`. + * + * * `0` is returned if `target` is the same as `buf` + * * `1` is returned if `target` should come _before_`buf` when sorted. + * * `-1` is returned if `target` should come _after_`buf` when sorted. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('BCD'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.compare(buf1)); + * // Prints: 0 + * console.log(buf1.compare(buf2)); + * // Prints: -1 + * console.log(buf1.compare(buf3)); + * // Prints: -1 + * console.log(buf2.compare(buf1)); + * // Prints: 1 + * console.log(buf2.compare(buf3)); + * // Prints: 1 + * console.log([buf1, buf2, buf3].sort(Buffer.compare)); + * // Prints: [ , , ] + * // (This result is equal to: [buf1, buf3, buf2].) + * ``` + * + * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd` arguments can be used to limit the comparison to specific ranges within `target` and `buf` respectively. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); + * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + * + * console.log(buf1.compare(buf2, 5, 9, 0, 4)); + * // Prints: 0 + * console.log(buf1.compare(buf2, 0, 6, 4)); + * // Prints: -1 + * console.log(buf1.compare(buf2, 5, 6, 5)); + * // Prints: 1 + * ``` + * + * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`, `targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. + * @since v0.11.13 + * @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`. + * @param [targetStart=0] The offset within `target` at which to begin comparison. + * @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive). + * @param [sourceStart=0] The offset within `buf` at which to begin comparison. + * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). + */ + compare( + target: Uint8Array, + targetStart?: number, + targetEnd?: number, + sourceStart?: number, + sourceEnd?: number, + ): -1 | 0 | 1; + /** + * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. + * + * [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available + * for all TypedArrays, including Node.js `Buffer`s, although it takes + * different function arguments. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create two `Buffer` instances. + * const buf1 = Buffer.allocUnsafe(26); + * const buf2 = Buffer.allocUnsafe(26).fill('!'); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. + * buf1.copy(buf2, 8, 16, 20); + * // This is equivalent to: + * // buf2.set(buf1.subarray(16, 20), 8); + * + * console.log(buf2.toString('ascii', 0, 25)); + * // Prints: !!!!!!!!qrst!!!!!!!!!!!!! + * ``` + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` and copy data from one region to an overlapping region + * // within the same `Buffer`. + * + * const buf = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf[i] = i + 97; + * } + * + * buf.copy(buf, 0, 4, 10); + * + * console.log(buf.toString()); + * // Prints: efghijghijklmnopqrstuvwxyz + * ``` + * @since v0.1.90 + * @param target A `Buffer` or {@link Uint8Array} to copy into. + * @param [targetStart=0] The offset within `target` at which to begin writing. + * @param [sourceStart=0] The offset within `buf` from which to begin copying. + * @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive). + * @return The number of bytes copied. + */ + copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64BE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64LE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64LE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * This function is also available under the `writeBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64BE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64BE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64LE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * + * This function is also available under the `writeBigUint64LE` alias. + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64LE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64LE(value: bigint, offset?: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntLE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntLE + * @since v14.9.0, v12.19.0 + */ + writeUintLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntBE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntBE + * @since v14.9.0, v12.19.0 + */ + writeUintBE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than a signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when`value` is anything other than a + * signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntBE(value: number, offset: number, byteLength: number): number; + /** + * Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64BE(0)); + * // Prints: 4294967295n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64BE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + readBigUint64BE(offset?: number): bigint; + /** + * Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64LE(0)); + * // Prints: 18446744069414584320n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64LE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + readBigUint64LE(offset?: number): bigint; + /** + * Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64BE(offset?: number): bigint; + /** + * Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64LE(offset?: number): bigint; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an unsigned, little-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntLE(0, 6).toString(16)); + * // Prints: ab9078563412 + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntLE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntLE + * @since v14.9.0, v12.19.0 + */ + readUintLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an unsigned big-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readUIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntBE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntBE + * @since v14.9.0, v12.19.0 + */ + readUintBE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a little-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntLE(0, 6).toString(16)); + * // Prints: -546f87a9cbee + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a big-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * console.log(buf.readIntBE(1, 0).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntBE(offset: number, byteLength: number): number; + /** + * Reads an unsigned 8-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, -2]); + * + * console.log(buf.readUInt8(0)); + * // Prints: 1 + * console.log(buf.readUInt8(1)); + * // Prints: 254 + * console.log(buf.readUInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readUInt8(offset?: number): number; + /** + * @alias Buffer.readUInt8 + * @since v14.9.0, v12.19.0 + */ + readUint8(offset?: number): number; + /** + * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16LE(0).toString(16)); + * // Prints: 3412 + * console.log(buf.readUInt16LE(1).toString(16)); + * // Prints: 5634 + * console.log(buf.readUInt16LE(2).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16LE(offset?: number): number; + /** + * @alias Buffer.readUInt16LE + * @since v14.9.0, v12.19.0 + */ + readUint16LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16BE(0).toString(16)); + * // Prints: 1234 + * console.log(buf.readUInt16BE(1).toString(16)); + * // Prints: 3456 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16BE(offset?: number): number; + /** + * @alias Buffer.readUInt16BE + * @since v14.9.0, v12.19.0 + */ + readUint16BE(offset?: number): number; + /** + * Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32LE(0).toString(16)); + * // Prints: 78563412 + * console.log(buf.readUInt32LE(1).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32LE(offset?: number): number; + /** + * @alias Buffer.readUInt32LE + * @since v14.9.0, v12.19.0 + */ + readUint32LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32BE(0).toString(16)); + * // Prints: 12345678 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32BE(offset?: number): number; + /** + * @alias Buffer.readUInt32BE + * @since v14.9.0, v12.19.0 + */ + readUint32BE(offset?: number): number; + /** + * Reads a signed 8-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([-1, 5]); + * + * console.log(buf.readInt8(0)); + * // Prints: -1 + * console.log(buf.readInt8(1)); + * // Prints: 5 + * console.log(buf.readInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readInt8(offset?: number): number; + /** + * Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16LE(0)); + * // Prints: 1280 + * console.log(buf.readInt16LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16LE(offset?: number): number; + /** + * Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16BE(offset?: number): number; + /** + * Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32LE(0)); + * // Prints: 83886080 + * console.log(buf.readInt32LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32LE(offset?: number): number; + /** + * Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32BE(offset?: number): number; + /** + * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatLE(0)); + * // Prints: 1.539989614439558e-36 + * console.log(buf.readFloatLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatLE(offset?: number): number; + /** + * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatBE(0)); + * // Prints: 2.387939260590663e-38 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatBE(offset?: number): number; + /** + * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleLE(0)); + * // Prints: 5.447603722011605e-270 + * console.log(buf.readDoubleLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleLE(offset?: number): number; + /** + * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleBE(0)); + * // Prints: 8.20788039913184e-304 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleBE(offset?: number): number; + reverse(): this; + /** + * Interprets `buf` as an array of unsigned 16-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap16(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap16(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * + * One convenient use of `buf.swap16()` is to perform a fast in-place conversion + * between UTF-16 little-endian and UTF-16 big-endian: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); + * buf.swap16(); // Convert to big-endian UTF-16 text. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap16(): this; + /** + * Interprets `buf` as an array of unsigned 32-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap32(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap32(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap32(): this; + /** + * Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. + * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap64(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap64(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v6.3.0 + * @return A reference to `buf`. + */ + swap64(): this; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a + * valid unsigned 8-bit integer. Behavior is undefined when `value` is anything + * other than an unsigned 8-bit integer. + * + * This function is also available under the `writeUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt8(0x3, 0); + * buf.writeUInt8(0x4, 1); + * buf.writeUInt8(0x23, 2); + * buf.writeUInt8(0x42, 3); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeUInt8(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt8 + * @since v14.9.0, v12.19.0 + */ + writeUint8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 16-bit integer. + * + * This function is also available under the `writeUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16LE(0xdead, 0); + * buf.writeUInt16LE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16LE + * @since v14.9.0, v12.19.0 + */ + writeUint16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 16-bit integer. + * + * This function is also available under the `writeUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16BE(0xdead, 0); + * buf.writeUInt16BE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16BE + * @since v14.9.0, v12.19.0 + */ + writeUint16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 32-bit integer. + * + * This function is also available under the `writeUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32LE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32LE + * @since v14.9.0, v12.19.0 + */ + writeUint32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 32-bit integer. + * + * This function is also available under the `writeUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32BE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32BE + * @since v14.9.0, v12.19.0 + */ + writeUint32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a valid + * signed 8-bit integer. Behavior is undefined when `value` is anything other than + * a signed 8-bit integer. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt8(2, 0); + * buf.writeInt8(-2, 1); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeInt8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16LE(0x0304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16BE(0x0102, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32LE(0x05060708, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32BE(0x01020304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatLE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatBE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatBE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleLE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleBE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleBE(value: number, offset?: number): number; + /** + * Fills `buf` with the specified `value`. If the `offset` and `end` are not given, + * the entire `buf` will be filled: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * + * // Fill a buffer with empty string + * const c = Buffer.allocUnsafe(5).fill(''); + * + * console.log(c.fill('')); + * // Prints: + * ``` + * + * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or + * integer. If the resulting integer is greater than `255` (decimal), `buf` will be + * filled with `value & 255`. + * + * If the final write of a `fill()` operation falls on a multi-byte character, + * then only the bytes of that character that fit into `buf` are written: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with character that takes up two bytes in UTF-8. + * + * console.log(Buffer.allocUnsafe(5).fill('\u0222')); + * // Prints: + * ``` + * + * If `value` contains invalid characters, it is truncated; if no valid + * fill data remains, an exception is thrown: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(5); + * + * console.log(buf.fill('a')); + * // Prints: + * console.log(buf.fill('aazz', 'hex')); + * // Prints: + * console.log(buf.fill('zz', 'hex')); + * // Throws an exception. + * ``` + * @since v0.5.0 + * @param value The value with which to fill `buf`. Empty value (string, Uint8Array, Buffer) is coerced to `0`. + * @param [offset=0] Number of bytes to skip before starting to fill `buf`. + * @param [end=buf.length] Where to stop filling `buf` (not inclusive). + * @param [encoding='utf8'] The encoding for `value` if `value` is a string. + * @return A reference to `buf`. + */ + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + fill(value: string | Uint8Array | number, offset: number, encoding: BufferEncoding): this; + fill(value: string | Uint8Array | number, encoding: BufferEncoding): this; + /** + * If `value` is: + * + * * a string, `value` is interpreted according to the character encoding in `encoding`. + * * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. + * To compare a partial `Buffer`, use `buf.subarray`. + * * a number, `value` will be interpreted as an unsigned 8-bit integer + * value between `0` and `255`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.indexOf('this')); + * // Prints: 0 + * console.log(buf.indexOf('is')); + * // Prints: 2 + * console.log(buf.indexOf(Buffer.from('a buffer'))); + * // Prints: 8 + * console.log(buf.indexOf(97)); + * // Prints: 8 (97 is the decimal ASCII value for 'a') + * console.log(buf.indexOf(Buffer.from('a buffer example'))); + * // Prints: -1 + * console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: 8 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); + * // Prints: 4 + * console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); + * // Prints: 6 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a `TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. If the result + * of coercion is `NaN` or `0`, then the entire buffer will be searched. This + * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.indexOf(99.9)); + * console.log(b.indexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN or 0. + * // Prints: 1, searching the whole buffer. + * console.log(b.indexOf('b', undefined)); + * console.log(b.indexOf('b', {})); + * console.log(b.indexOf('b', null)); + * console.log(b.indexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer` and `byteOffset` is less + * than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned. + * @since v1.5.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + indexOf(value: string | number | Uint8Array, encoding: BufferEncoding): number; + /** + * Identical to `buf.indexOf()`, except the last occurrence of `value` is found + * rather than the first occurrence. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this buffer is a buffer'); + * + * console.log(buf.lastIndexOf('this')); + * // Prints: 0 + * console.log(buf.lastIndexOf('buffer')); + * // Prints: 17 + * console.log(buf.lastIndexOf(Buffer.from('buffer'))); + * // Prints: 17 + * console.log(buf.lastIndexOf(97)); + * // Prints: 15 (97 is the decimal ASCII value for 'a') + * console.log(buf.lastIndexOf(Buffer.from('yolo'))); + * // Prints: -1 + * console.log(buf.lastIndexOf('buffer', 5)); + * // Prints: 5 + * console.log(buf.lastIndexOf('buffer', 4)); + * // Prints: -1 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')); + * // Prints: 6 + * console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); + * // Prints: 4 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a `TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. Any arguments + * that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. + * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.lastIndexOf(99.9)); + * console.log(b.lastIndexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN. + * // Prints: 1, searching the whole buffer. + * console.log(b.lastIndexOf('b', undefined)); + * console.log(b.lastIndexOf('b', {})); + * + * // Passing a byteOffset that coerces to 0. + * // Prints: -1, equivalent to passing 0. + * console.log(b.lastIndexOf('b', null)); + * console.log(b.lastIndexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. + * @since v6.0.0 + * @param value What to search for. + * @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + lastIndexOf(value: string | number | Uint8Array, encoding: BufferEncoding): number; + /** + * Equivalent to `buf.indexOf() !== -1`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.includes('this')); + * // Prints: true + * console.log(buf.includes('is')); + * // Prints: true + * console.log(buf.includes(Buffer.from('a buffer'))); + * // Prints: true + * console.log(buf.includes(97)); + * // Prints: true (97 is the decimal ASCII value for 'a') + * console.log(buf.includes(Buffer.from('a buffer example'))); + * // Prints: false + * console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: true + * console.log(buf.includes('this', 4)); + * // Prints: false + * ``` + * @since v5.3.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is its encoding. + * @return `true` if `value` was found in `buf`, `false` otherwise. + */ + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + includes(value: string | number | Buffer, encoding: BufferEncoding): boolean; + } + var Buffer: BufferConstructor; + /** + * Decodes a string of Base64-encoded data into bytes, and encodes those bytes + * into a string using Latin-1 (ISO-8859-1). + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @legacy Use `Buffer.from(data, 'base64')` instead. + * @param data The Base64-encoded input string. + */ + function atob(data: string): string; + /** + * Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes + * into a string using Base64. + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @legacy Use `buf.toString('base64')` instead. + * @param data An ASCII (Latin1) string. + */ + function btoa(data: string): string; + interface Blob extends _Blob {} + /** + * `Blob` class is a global reference for `import { Blob } from 'node:buffer'` + * https://nodejs.org/api/buffer.html#class-blob + * @since v18.0.0 + */ + var Blob: typeof globalThis extends { onmessage: any; Blob: infer T } ? T + : typeof import("buffer").Blob; + interface File extends _File {} + /** + * `File` class is a global reference for `import { File } from 'node:buffer'` + * https://nodejs.org/api/buffer.html#class-file + * @since v20.0.0 + */ + var File: typeof globalThis extends { onmessage: any; File: infer T } ? T + : typeof import("buffer").File; + } +} +declare module "node:buffer" { + export * from "buffer"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/child_process.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/child_process.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a12a8c82ded1fd486d3ef901e398a456aff33f4 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,1453 @@ +/** + * The `node:child_process` module provides the ability to spawn subprocesses in + * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability + * is primarily provided by the {@link spawn} function: + * + * ```js + * import { spawn } from 'node:child_process'; + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * By default, pipes for `stdin`, `stdout`, and `stderr` are established between + * the parent Node.js process and the spawned subprocess. These pipes have + * limited (and platform-specific) capacity. If the subprocess writes to + * stdout in excess of that limit without the output being captured, the + * subprocess blocks waiting for the pipe buffer to accept more data. This is + * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }` option if the output will not be consumed. + * + * The command lookup is performed using the `options.env.PATH` environment + * variable if `env` is in the `options` object. Otherwise, `process.env.PATH` is + * used. If `options.env` is set without `PATH`, lookup on Unix is performed + * on a default search path search of `/usr/bin:/bin` (see your operating system's + * manual for execvpe/execvp), on Windows the current processes environment + * variable `PATH` is used. + * + * On Windows, environment variables are case-insensitive. Node.js + * lexicographically sorts the `env` keys and uses the first one that + * case-insensitively matches. Only first (in lexicographic order) entry will be + * passed to the subprocess. This might lead to issues on Windows when passing + * objects to the `env` option that have multiple variants of the same key, such as `PATH` and `Path`. + * + * The {@link spawn} method spawns the child process asynchronously, + * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks + * the event loop until the spawned process either exits or is terminated. + * + * For convenience, the `node:child_process` module provides a handful of + * synchronous and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on + * top of {@link spawn} or {@link spawnSync}. + * + * * {@link exec}: spawns a shell and runs a command within that + * shell, passing the `stdout` and `stderr` to a callback function when + * complete. + * * {@link execFile}: similar to {@link exec} except + * that it spawns the command directly without first spawning a shell by + * default. + * * {@link fork}: spawns a new Node.js process and invokes a + * specified module with an IPC communication channel established that allows + * sending messages between parent and child. + * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop. + * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop. + * + * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, + * the synchronous methods can have significant impact on performance due to + * stalling the event loop while spawned processes complete. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/child_process.js) + */ +declare module "child_process" { + import { Abortable, EventEmitter } from "node:events"; + import * as dgram from "node:dgram"; + import * as net from "node:net"; + import { Pipe, Readable, Stream, Writable } from "node:stream"; + import { URL } from "node:url"; + type Serializable = string | object | number | boolean | bigint; + type SendHandle = net.Socket | net.Server | dgram.Socket | undefined; + /** + * Instances of the `ChildProcess` represent spawned child processes. + * + * Instances of `ChildProcess` are not intended to be created directly. Rather, + * use the {@link spawn}, {@link exec},{@link execFile}, or {@link fork} methods to create + * instances of `ChildProcess`. + * @since v2.2.0 + */ + class ChildProcess extends EventEmitter { + /** + * A `Writable Stream` that represents the child process's `stdin`. + * + * If a child process waits to read all of its input, the child will not continue + * until this stream has been closed via `end()`. + * + * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will + * refer to the same value. + * + * The `subprocess.stdin` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdin: Writable | null; + /** + * A `Readable Stream` that represents the child process's `stdout`. + * + * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will + * refer to the same value. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdout: Readable | null; + /** + * A `Readable Stream` that represents the child process's `stderr`. + * + * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will + * refer to the same value. + * + * The `subprocess.stderr` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stderr: Readable | null; + /** + * The `subprocess.channel` property is a reference to the child's IPC channel. If + * no IPC channel exists, this property is `undefined`. + * @since v7.1.0 + */ + readonly channel?: Pipe | null | undefined; + /** + * A sparse array of pipes to the child process, corresponding with positions in + * the `stdio` option passed to {@link spawn} that have been set + * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and `subprocess.stdio[2]` are also available as `subprocess.stdin`, `subprocess.stdout`, and `subprocess.stderr`, + * respectively. + * + * In the following example, only the child's fd `1` (stdout) is configured as a + * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values + * in the array are `null`. + * + * ```js + * import assert from 'node:assert'; + * import fs from 'node:fs'; + * import child_process from 'node:child_process'; + * + * const subprocess = child_process.spawn('ls', { + * stdio: [ + * 0, // Use parent's stdin for child. + * 'pipe', // Pipe child's stdout to parent. + * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. + * ], + * }); + * + * assert.strictEqual(subprocess.stdio[0], null); + * assert.strictEqual(subprocess.stdio[0], subprocess.stdin); + * + * assert(subprocess.stdout); + * assert.strictEqual(subprocess.stdio[1], subprocess.stdout); + * + * assert.strictEqual(subprocess.stdio[2], null); + * assert.strictEqual(subprocess.stdio[2], subprocess.stderr); + * ``` + * + * The `subprocess.stdio` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.7.10 + */ + readonly stdio: [ + Writable | null, + // stdin + Readable | null, + // stdout + Readable | null, + // stderr + Readable | Writable | null | undefined, + // extra + Readable | Writable | null | undefined, // extra + ]; + /** + * The `subprocess.killed` property indicates whether the child process + * successfully received a signal from `subprocess.kill()`. The `killed` property + * does not indicate that the child process has been terminated. + * @since v0.5.10 + */ + readonly killed: boolean; + /** + * Returns the process identifier (PID) of the child process. If the child process + * fails to spawn due to errors, then the value is `undefined` and `error` is + * emitted. + * + * ```js + * import { spawn } from 'node:child_process'; + * const grep = spawn('grep', ['ssh']); + * + * console.log(`Spawned child pid: ${grep.pid}`); + * grep.stdin.end(); + * ``` + * @since v0.1.90 + */ + readonly pid?: number | undefined; + /** + * The `subprocess.connected` property indicates whether it is still possible to + * send and receive messages from a child process. When `subprocess.connected` is `false`, it is no longer possible to send or receive messages. + * @since v0.7.2 + */ + readonly connected: boolean; + /** + * The `subprocess.exitCode` property indicates the exit code of the child process. + * If the child process is still running, the field will be `null`. + */ + readonly exitCode: number | null; + /** + * The `subprocess.signalCode` property indicates the signal received by + * the child process if any, else `null`. + */ + readonly signalCode: NodeJS.Signals | null; + /** + * The `subprocess.spawnargs` property represents the full list of command-line + * arguments the child process was launched with. + */ + readonly spawnargs: string[]; + /** + * The `subprocess.spawnfile` property indicates the executable file name of + * the child process that is launched. + * + * For {@link fork}, its value will be equal to `process.execPath`. + * For {@link spawn}, its value will be the name of + * the executable file. + * For {@link exec}, its value will be the name of the shell + * in which the child process is launched. + */ + readonly spawnfile: string; + /** + * The `subprocess.kill()` method sends a signal to the child process. If no + * argument is given, the process will be sent the `'SIGTERM'` signal. See [`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function + * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. + * + * ```js + * import { spawn } from 'node:child_process'; + * const grep = spawn('grep', ['ssh']); + * + * grep.on('close', (code, signal) => { + * console.log( + * `child process terminated due to receipt of signal ${signal}`); + * }); + * + * // Send SIGHUP to process. + * grep.kill('SIGHUP'); + * ``` + * + * The `ChildProcess` object may emit an `'error'` event if the signal + * cannot be delivered. Sending a signal to a child process that has already exited + * is not an error but may have unforeseen consequences. Specifically, if the + * process identifier (PID) has been reassigned to another process, the signal will + * be delivered to that process instead which can have unexpected results. + * + * While the function is called `kill`, the signal delivered to the child process + * may not actually terminate the process. + * + * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. + * + * On Windows, where POSIX signals do not exist, the `signal` argument will be + * ignored, and the process will be killed forcefully and abruptly (similar to `'SIGKILL'`). + * See `Signal Events` for more details. + * + * On Linux, child processes of child processes will not be terminated + * when attempting to kill their parent. This is likely to happen when running a + * new process in a shell or with the use of the `shell` option of `ChildProcess`: + * + * ```js + * 'use strict'; + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn( + * 'sh', + * [ + * '-c', + * `node -e "setInterval(() => { + * console.log(process.pid, 'is alive') + * }, 500);"`, + * ], { + * stdio: ['inherit', 'inherit', 'inherit'], + * }, + * ); + * + * setTimeout(() => { + * subprocess.kill(); // Does not terminate the Node.js process in the shell. + * }, 2000); + * ``` + * @since v0.1.90 + */ + kill(signal?: NodeJS.Signals | number): boolean; + /** + * Calls {@link ChildProcess.kill} with `'SIGTERM'`. + * @since v20.5.0 + */ + [Symbol.dispose](): void; + /** + * When an IPC channel has been established between the parent and child ( + * i.e. when using {@link fork}), the `subprocess.send()` method can + * be used to send messages to the child process. When the child process is a + * Node.js instance, these messages can be received via the `'message'` event. + * + * The message goes through serialization and parsing. The resulting + * message might not be the same as what is originally sent. + * + * For example, in the parent script: + * + * ```js + * import cp from 'node:child_process'; + * const n = cp.fork(`${__dirname}/sub.js`); + * + * n.on('message', (m) => { + * console.log('PARENT got message:', m); + * }); + * + * // Causes the child to print: CHILD got message: { hello: 'world' } + * n.send({ hello: 'world' }); + * ``` + * + * And then the child script, `'sub.js'` might look like this: + * + * ```js + * process.on('message', (m) => { + * console.log('CHILD got message:', m); + * }); + * + * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } + * process.send({ foo: 'bar', baz: NaN }); + * ``` + * + * Child Node.js processes will have a `process.send()` method of their own + * that allows the child to send messages back to the parent. + * + * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages + * containing a `NODE_` prefix in the `cmd` property are reserved for use within + * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the `'internalMessage'` event and are consumed internally by Node.js. + * Applications should avoid using such messages or listening for `'internalMessage'` events as it is subject to change without notice. + * + * The optional `sendHandle` argument that may be passed to `subprocess.send()` is + * for passing a TCP server or socket object to the child process. The child will + * receive the object as the second argument passed to the callback function + * registered on the `'message'` event. Any data that is received and buffered in + * the socket will not be sent to the child. Sending IPC sockets is not supported on Windows. + * + * The optional `callback` is a function that is invoked after the message is + * sent but before the child may have received it. The function is called with a + * single argument: `null` on success, or an `Error` object on failure. + * + * If no `callback` function is provided and the message cannot be sent, an `'error'` event will be emitted by the `ChildProcess` object. This can + * happen, for instance, when the child process has already exited. + * + * `subprocess.send()` will return `false` if the channel has closed or when the + * backlog of unsent messages exceeds a threshold that makes it unwise to send + * more. Otherwise, the method returns `true`. The `callback` function can be + * used to implement flow control. + * + * #### Example: sending a server object + * + * The `sendHandle` argument can be used, for instance, to pass the handle of + * a TCP server object to the child process as illustrated in the example below: + * + * ```js + * import { createServer } from 'node:net'; + * import { fork } from 'node:child_process'; + * const subprocess = fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = createServer(); + * server.on('connection', (socket) => { + * socket.end('handled by parent'); + * }); + * server.listen(1337, () => { + * subprocess.send('server', server); + * }); + * ``` + * + * The child would then receive the server object as: + * + * ```js + * process.on('message', (m, server) => { + * if (m === 'server') { + * server.on('connection', (socket) => { + * socket.end('handled by child'); + * }); + * } + * }); + * ``` + * + * Once the server is now shared between the parent and child, some connections + * can be handled by the parent and some by the child. + * + * While the example above uses a server created using the `node:net` module, `node:dgram` module servers use exactly the same workflow with the exceptions of + * listening on a `'message'` event instead of `'connection'` and using `server.bind()` instead of `server.listen()`. This is, however, only + * supported on Unix platforms. + * + * #### Example: sending a socket object + * + * Similarly, the `sendHandler` argument can be used to pass the handle of a + * socket to the child process. The example below spawns two children that each + * handle connections with "normal" or "special" priority: + * + * ```js + * import { createServer } from 'node:net'; + * import { fork } from 'node:child_process'; + * const normal = fork('subprocess.js', ['normal']); + * const special = fork('subprocess.js', ['special']); + * + * // Open up the server and send sockets to child. Use pauseOnConnect to prevent + * // the sockets from being read before they are sent to the child process. + * const server = createServer({ pauseOnConnect: true }); + * server.on('connection', (socket) => { + * + * // If this is special priority... + * if (socket.remoteAddress === '74.125.127.100') { + * special.send('socket', socket); + * return; + * } + * // This is normal priority. + * normal.send('socket', socket); + * }); + * server.listen(1337); + * ``` + * + * The `subprocess.js` would receive the socket handle as the second argument + * passed to the event callback function: + * + * ```js + * process.on('message', (m, socket) => { + * if (m === 'socket') { + * if (socket) { + * // Check that the client socket exists. + * // It is possible for the socket to be closed between the time it is + * // sent and the time it is received in the child process. + * socket.end(`Request handled with ${process.argv[2]} priority`); + * } + * } + * }); + * ``` + * + * Do not use `.maxConnections` on a socket that has been passed to a subprocess. + * The parent cannot track when the socket is destroyed. + * + * Any `'message'` handlers in the subprocess should verify that `socket` exists, + * as the connection may have been closed during the time it takes to send the + * connection to the child. + * @since v0.5.9 + * @param sendHandle `undefined`, or a [`net.Socket`](https://nodejs.org/docs/latest-v24.x/api/net.html#class-netsocket), [`net.Server`](https://nodejs.org/docs/latest-v24.x/api/net.html#class-netserver), or [`dgram.Socket`](https://nodejs.org/docs/latest-v24.x/api/dgram.html#class-dgramsocket) object. + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: Serializable, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; + send( + message: Serializable, + sendHandle?: SendHandle, + options?: MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * Closes the IPC channel between parent and child, allowing the child to exit + * gracefully once there are no other connections keeping it alive. After calling + * this method the `subprocess.connected` and `process.connected` properties in + * both the parent and child (respectively) will be set to `false`, and it will be + * no longer possible to pass messages between the processes. + * + * The `'disconnect'` event will be emitted when there are no messages in the + * process of being received. This will most often be triggered immediately after + * calling `subprocess.disconnect()`. + * + * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked + * within the child process to close the IPC channel as well. + * @since v0.7.2 + */ + disconnect(): void; + /** + * By default, the parent will wait for the detached child to exit. To prevent the + * parent from waiting for a given `subprocess` to exit, use the `subprocess.unref()` method. Doing so will cause the parent's event loop to not + * include the child in its reference count, allowing the parent to exit + * independently of the child, unless there is an established IPC channel between + * the child and the parent. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * ``` + * @since v0.7.10 + */ + unref(): void; + /** + * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will + * restore the removed reference count for the child process, forcing the parent + * to wait for the child to exit before exiting itself. + * + * ```js + * import { spawn } from 'node:child_process'; + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * subprocess.ref(); + * ``` + * @since v0.7.10 + */ + ref(): void; + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + * 6. spawn + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + addListener(event: "spawn", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "exit", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "message", message: Serializable, sendHandle: SendHandle): boolean; + emit(event: "spawn", listener: () => void): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + on(event: "spawn", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + once(event: "spawn", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependListener(event: "spawn", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "close", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "exit", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependOnceListener(event: "spawn", listener: () => void): this; + } + // return this object when stdio option is undefined or not specified + interface ChildProcessWithoutNullStreams extends ChildProcess { + stdin: Writable; + stdout: Readable; + stderr: Readable; + readonly stdio: [ + Writable, + Readable, + Readable, + // stderr + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + // return this object when stdio option is a tuple of 3 + interface ChildProcessByStdio + extends ChildProcess + { + stdin: I; + stdout: O; + stderr: E; + readonly stdio: [ + I, + O, + E, + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + interface MessageOptions { + keepOpen?: boolean | undefined; + } + type IOType = "overlapped" | "pipe" | "ignore" | "inherit"; + type StdioOptions = IOType | Array; + type SerializationType = "json" | "advanced"; + interface MessagingOptions extends Abortable { + /** + * Specify the kind of serialization used for sending messages between processes. + * @default 'json' + */ + serialization?: SerializationType | undefined; + /** + * The signal value to be used when the spawned process will be killed by the abort signal. + * @default 'SIGTERM' + */ + killSignal?: NodeJS.Signals | number | undefined; + /** + * In milliseconds the maximum amount of time the process is allowed to run. + */ + timeout?: number | undefined; + } + interface ProcessEnvOptions { + uid?: number | undefined; + gid?: number | undefined; + cwd?: string | URL | undefined; + env?: NodeJS.ProcessEnv | undefined; + } + interface CommonOptions extends ProcessEnvOptions { + /** + * @default false + */ + windowsHide?: boolean | undefined; + /** + * @default 0 + */ + timeout?: number | undefined; + } + interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { + argv0?: string | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + shell?: boolean | string | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + interface SpawnOptions extends CommonSpawnOptions { + detached?: boolean | undefined; + } + interface SpawnOptionsWithoutStdio extends SpawnOptions { + stdio?: StdioPipeNamed | StdioPipe[] | undefined; + } + type StdioNull = "inherit" | "ignore" | Stream; + type StdioPipeNamed = "pipe" | "overlapped"; + type StdioPipe = undefined | null | StdioPipeNamed; + interface SpawnOptionsWithStdioTuple< + Stdin extends StdioNull | StdioPipe, + Stdout extends StdioNull | StdioPipe, + Stderr extends StdioNull | StdioPipe, + > extends SpawnOptions { + stdio: [Stdin, Stdout, Stderr]; + } + /** + * The `child_process.spawn()` method spawns a new process using the given `command`, with command-line arguments in `args`. If omitted, `args` defaults + * to an empty array. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * A third argument may be used to specify additional options, with these defaults: + * + * ```js + * const defaults = { + * cwd: undefined, + * env: process.env, + * }; + * ``` + * + * Use `cwd` to specify the working directory from which the process is spawned. + * If not given, the default is to inherit the current working directory. If given, + * but the path does not exist, the child process emits an `ENOENT` error + * and exits immediately. `ENOENT` is also emitted when the command + * does not exist. + * + * Use `env` to specify environment variables that will be visible to the new + * process, the default is `process.env`. + * + * `undefined` values in `env` will be ignored. + * + * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the + * exit code: + * + * ```js + * import { spawn } from 'node:child_process'; + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * Example: A very elaborate way to run `ps ax | grep ssh` + * + * ```js + * import { spawn } from 'node:child_process'; + * const ps = spawn('ps', ['ax']); + * const grep = spawn('grep', ['ssh']); + * + * ps.stdout.on('data', (data) => { + * grep.stdin.write(data); + * }); + * + * ps.stderr.on('data', (data) => { + * console.error(`ps stderr: ${data}`); + * }); + * + * ps.on('close', (code) => { + * if (code !== 0) { + * console.log(`ps process exited with code ${code}`); + * } + * grep.stdin.end(); + * }); + * + * grep.stdout.on('data', (data) => { + * console.log(data.toString()); + * }); + * + * grep.stderr.on('data', (data) => { + * console.error(`grep stderr: ${data}`); + * }); + * + * grep.on('close', (code) => { + * if (code !== 0) { + * console.log(`grep process exited with code ${code}`); + * } + * }); + * ``` + * + * Example of checking for failed `spawn`: + * + * ```js + * import { spawn } from 'node:child_process'; + * const subprocess = spawn('bad_command'); + * + * subprocess.on('error', (err) => { + * console.error('Failed to start subprocess.'); + * }); + * ``` + * + * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process + * title while others (Windows, SunOS) will use `command`. + * + * Node.js overwrites `argv[0]` with `process.execPath` on startup, so `process.argv[0]` in a Node.js child process will not match the `argv0` parameter passed to `spawn` from the parent. Retrieve + * it with the `process.argv0` property instead. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { spawn } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const grep = spawn('grep', ['ssh'], { signal }); + * grep.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * ``` + * @since v0.1.90 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptions): ChildProcess; + // overloads of spawn with 'args' + function spawn( + command: string, + args?: readonly string[], + options?: SpawnOptionsWithoutStdio, + ): ChildProcessWithoutNullStreams; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, args: readonly string[], options: SpawnOptions): ChildProcess; + interface ExecOptions extends CommonOptions { + shell?: string | undefined; + signal?: AbortSignal | undefined; + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + encoding?: string | null | undefined; + } + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding?: BufferEncoding | undefined; + } + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: "buffer" | null; // specify `null`. + } + interface ExecException extends Error { + cmd?: string | undefined; + killed?: boolean | undefined; + code?: number | undefined; + signal?: NodeJS.Signals | undefined; + stdout?: string; + stderr?: string; + } + /** + * Spawns a shell then executes the `command` within that shell, buffering any + * generated output. The `command` string passed to the exec function is processed + * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters)) + * need to be dealt with accordingly: + * + * ```js + * import { exec } from 'node:child_process'; + * + * exec('"/path/to/test file/test.sh" arg1 arg2'); + * // Double quotes are used so that the space in the path is not interpreted as + * // a delimiter of multiple arguments. + * + * exec('echo "The \\$HOME variable is $HOME"'); + * // The $HOME variable is escaped in the first instance, but not in the second. + * ``` + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * + * If a `callback` function is provided, it is called with the arguments `(error, stdout, stderr)`. On success, `error` will be `null`. On error, `error` will be an instance of `Error`. The + * `error.code` property will be + * the exit code of the process. By convention, any exit code other than `0` indicates an error. `error.signal` will be the signal that terminated the + * process. + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * ```js + * import { exec } from 'node:child_process'; + * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { + * if (error) { + * console.error(`exec error: ${error}`); + * return; + * } + * console.log(`stdout: ${stdout}`); + * console.error(`stderr: ${stderr}`); + * }); + * ``` + * + * If `timeout` is greater than `0`, the parent will send the signal + * identified by the `killSignal` property (the default is `'SIGTERM'`) if the + * child runs longer than `timeout` milliseconds. + * + * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace + * the existing process and uses a shell to execute the command. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * import util from 'node:util'; + * import child_process from 'node:child_process'; + * const exec = util.promisify(child_process.exec); + * + * async function lsExample() { + * const { stdout, stderr } = await exec('ls'); + * console.log('stdout:', stdout); + * console.error('stderr:', stderr); + * } + * lsExample(); + * ``` + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { exec } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.90 + * @param command The command to run, with space-separated arguments. + * @param callback called with the output when process terminates. + */ + function exec( + command: string, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec( + command: string, + options: ExecOptionsWithBufferEncoding, + callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + // `options` with well-known or absent `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: ExecOptionsWithStringEncoding, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: ExecOptions | undefined | null, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + interface PromiseWithChild extends Promise { + child: ChildProcess; + } + namespace exec { + function __promisify__(command: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + command: string, + options: ExecOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ExecFileOptions extends CommonOptions, Abortable { + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + windowsVerbatimArguments?: boolean | undefined; + shell?: boolean | string | undefined; + signal?: AbortSignal | undefined; + encoding?: string | null | undefined; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding?: BufferEncoding | undefined; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: "buffer" | null; + } + /** @deprecated Use `ExecFileOptions` instead. */ + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions {} + type ExecFileException = + & Omit + & Omit + & { code?: string | number | undefined | null }; + /** + * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified + * executable `file` is spawned directly as a new process making it slightly more + * efficient than {@link exec}. + * + * The same options as {@link exec} are supported. Since a shell is + * not spawned, behaviors such as I/O redirection and file globbing are not + * supported. + * + * ```js + * import { execFile } from 'node:child_process'; + * const child = execFile('node', ['--version'], (error, stdout, stderr) => { + * if (error) { + * throw error; + * } + * console.log(stdout); + * }); + * ``` + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * import util from 'node:util'; + * import child_process from 'node:child_process'; + * const execFile = util.promisify(child_process.execFile); + * async function getVersion() { + * const { stdout } = await execFile('node', ['--version']); + * console.log(stdout); + * } + * getVersion(); + * ``` + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * import { execFile } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.91 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @param callback Called with the output when process terminates. + */ + // no `options` definitely means stdout/stderr are `string`. + function execFile( + file: string, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile( + file: string, + options: ExecFileOptionsWithBufferEncoding, + callback?: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback?: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + // `options` with well-known or absent `encoding` means stdout/stderr are definitely `string`. + function execFile( + file: string, + options: ExecFileOptionsWithStringEncoding, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: ExecFileOptions | undefined | null, + callback: + | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) + | undefined + | null, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions | undefined | null, + callback: + | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) + | undefined + | null, + ): ChildProcess; + namespace execFile { + function __promisify__(file: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions | undefined | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { + execPath?: string | undefined; + execArgv?: string[] | undefined; + silent?: boolean | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + detached?: boolean | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + /** + * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes. + * Like {@link spawn}, a `ChildProcess` object is returned. The + * returned `ChildProcess` will have an additional communication channel + * built-in that allows messages to be passed back and forth between the parent and + * child. See `subprocess.send()` for details. + * + * Keep in mind that spawned Node.js child processes are + * independent of the parent with exception of the IPC communication channel + * that is established between the two. Each process has its own memory, with + * their own V8 instances. Because of the additional resource allocations + * required, spawning a large number of child Node.js processes is not + * recommended. + * + * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the `options` object allows for an alternative + * execution path to be used. + * + * Node.js processes launched with a custom `execPath` will communicate with the + * parent process using the file descriptor (fd) identified using the + * environment variable `NODE_CHANNEL_FD` on the child process. + * + * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the + * current process. + * + * The `shell` option available in {@link spawn} is not supported by `child_process.fork()` and will be ignored if set. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * if (process.argv[2] === 'child') { + * setTimeout(() => { + * console.log(`Hello from ${process.argv[2]}!`); + * }, 1_000); + * } else { + * import { fork } from 'node:child_process'; + * const controller = new AbortController(); + * const { signal } = controller; + * const child = fork(__filename, ['child'], { signal }); + * child.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * } + * ``` + * @since v0.5.0 + * @param modulePath The module to run in the child. + * @param args List of string arguments. + */ + function fork(modulePath: string | URL, options?: ForkOptions): ChildProcess; + function fork(modulePath: string | URL, args?: readonly string[], options?: ForkOptions): ChildProcess; + interface SpawnSyncOptions extends CommonSpawnOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding?: "buffer" | null | undefined; + } + interface SpawnSyncReturns { + pid: number; + output: Array; + stdout: T; + stderr: T; + status: number | null; + signal: NodeJS.Signals | null; + error?: Error | undefined; + } + /** + * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the process intercepts and handles the `SIGTERM` signal + * and doesn't exit, the parent process will wait until the child process has + * exited. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args: readonly string[]): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithStringEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithBufferEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args?: readonly string[], + options?: SpawnSyncOptions, + ): SpawnSyncReturns; + interface CommonExecOptions extends CommonOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + /** + * Can be set to 'pipe', 'inherit, or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + killSignal?: NodeJS.Signals | number | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface ExecSyncOptions extends CommonExecOptions { + shell?: string | undefined; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding?: "buffer" | null | undefined; + } + /** + * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the child process intercepts and handles the `SIGTERM` signal and doesn't exit, the parent process will wait until the child process + * has exited. + * + * If the process times out or has a non-zero exit code, this method will throw. + * The `Error` object will contain the entire result from {@link spawnSync}. + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @return The stdout from the command. + */ + function execSync(command: string): Buffer; + function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): Buffer; + function execSync(command: string, options?: ExecSyncOptions): string | Buffer; + interface ExecFileSyncOptions extends CommonExecOptions { + shell?: boolean | string | undefined; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding?: "buffer" | null; // specify `null`. + } + /** + * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not + * return until the child process has fully closed. When a timeout has been + * encountered and `killSignal` is sent, the method won't return until the process + * has completely exited. + * + * If the child process intercepts and handles the `SIGTERM` signal and + * does not exit, the parent process will still wait until the child process has + * exited. + * + * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @return The stdout from the command. + */ + function execFileSync(file: string): Buffer; + function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(file: string, options?: ExecFileSyncOptions): string | Buffer; + function execFileSync(file: string, args: readonly string[]): Buffer; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithStringEncoding, + ): string; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithBufferEncoding, + ): Buffer; + function execFileSync(file: string, args?: readonly string[], options?: ExecFileSyncOptions): string | Buffer; +} +declare module "node:child_process" { + export * from "child_process"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/cluster.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/cluster.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fa25fdaeb822126469f947b98fb0f34e6cb96a9e --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/cluster.d.ts @@ -0,0 +1,579 @@ +/** + * Clusters of Node.js processes can be used to run multiple instances of Node.js + * that can distribute workloads among their application threads. When process isolation + * is not needed, use the [`worker_threads`](https://nodejs.org/docs/latest-v24.x/api/worker_threads.html) + * module instead, which allows running multiple application threads within a single Node.js instance. + * + * The cluster module allows easy creation of child processes that all share + * server ports. + * + * ```js + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; + * + * const numCPUs = availableParallelism(); + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('exit', (worker, code, signal) => { + * console.log(`worker ${worker.process.pid} died`); + * }); + * } else { + * // Workers can share any TCP connection + * // In this case it is an HTTP server + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * + * console.log(`Worker ${process.pid} started`); + * } + * ``` + * + * Running Node.js will now share port 8000 between the workers: + * + * ```console + * $ node server.js + * Primary 3596 is running + * Worker 4324 started + * Worker 4520 started + * Worker 6056 started + * Worker 5644 started + * ``` + * + * On Windows, it is not yet possible to set up a named pipe server in a worker. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/cluster.js) + */ +declare module "cluster" { + import * as child from "node:child_process"; + import EventEmitter = require("node:events"); + import * as net from "node:net"; + type SerializationType = "json" | "advanced"; + export interface ClusterSettings { + /** + * List of string arguments passed to the Node.js executable. + * @default process.execArgv + */ + execArgv?: string[] | undefined; + /** + * File path to worker file. + * @default process.argv[1] + */ + exec?: string | undefined; + /** + * String arguments passed to worker. + * @default process.argv.slice(2) + */ + args?: string[] | undefined; + /** + * Whether or not to send output to parent's stdio. + * @default false + */ + silent?: boolean | undefined; + /** + * Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must + * contain an `'ipc'` entry. When this option is provided, it overrides `silent`. See [`child_prcess.spawn()`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#child_processspawncommand-args-options)'s + * [`stdio`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#optionsstdio). + */ + stdio?: any[] | undefined; + /** + * Sets the user identity of the process. (See [`setuid(2)`](https://man7.org/linux/man-pages/man2/setuid.2.html).) + */ + uid?: number | undefined; + /** + * Sets the group identity of the process. (See [`setgid(2)`](https://man7.org/linux/man-pages/man2/setgid.2.html).) + */ + gid?: number | undefined; + /** + * Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. + * By default each worker gets its own port, incremented from the primary's `process.debugPort`. + */ + inspectPort?: number | (() => number) | undefined; + /** + * Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. + * See [Advanced serialization for `child_process`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#advanced-serialization) for more details. + * @default false + */ + serialization?: SerializationType | undefined; + /** + * Current working directory of the worker process. + * @default undefined (inherits from parent process) + */ + cwd?: string | undefined; + /** + * Hide the forked processes console window that would normally be created on Windows systems. + * @default false + */ + windowsHide?: boolean | undefined; + } + export interface Address { + address: string; + port: number; + /** + * The `addressType` is one of: + * + * * `4` (TCPv4) + * * `6` (TCPv6) + * * `-1` (Unix domain socket) + * * `'udp4'` or `'udp6'` (UDPv4 or UDPv6) + */ + addressType: 4 | 6 | -1 | "udp4" | "udp6"; + } + /** + * A `Worker` object contains all public information and method about a worker. + * In the primary it can be obtained using `cluster.workers`. In a worker + * it can be obtained using `cluster.worker`. + * @since v0.7.0 + */ + export class Worker extends EventEmitter { + /** + * Each new worker is given its own unique id, this id is stored in the `id`. + * + * While a worker is alive, this is the key that indexes it in `cluster.workers`. + * @since v0.8.0 + */ + id: number; + /** + * All workers are created using [`child_process.fork()`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#child_processforkmodulepath-args-options), the returned object + * from this function is stored as `.process`. In a worker, the global `process` is stored. + * + * See: [Child Process module](https://nodejs.org/docs/latest-v24.x/api/child_process.html#child_processforkmodulepath-args-options). + * + * Workers will call `process.exit(0)` if the `'disconnect'` event occurs + * on `process` and `.exitedAfterDisconnect` is not `true`. This protects against + * accidental disconnection. + * @since v0.7.0 + */ + process: child.ChildProcess; + /** + * Send a message to a worker or primary, optionally with a handle. + * + * In the primary, this sends a message to a specific worker. It is identical to [`ChildProcess.send()`](https://nodejs.org/docs/latest-v24.x/api/child_process.html#subprocesssendmessage-sendhandle-options-callback). + * + * In a worker, this sends a message to the primary. It is identical to `process.send()`. + * + * This example will echo back all messages from the primary: + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * worker.send('hi there'); + * + * } else if (cluster.isWorker) { + * process.on('message', (msg) => { + * process.send(msg); + * }); + * } + * ``` + * @since v0.7.0 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. + */ + send(message: child.Serializable, callback?: (error: Error | null) => void): boolean; + send( + message: child.Serializable, + sendHandle: child.SendHandle, + callback?: (error: Error | null) => void, + ): boolean; + send( + message: child.Serializable, + sendHandle: child.SendHandle, + options?: child.MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * This function will kill the worker. In the primary worker, it does this by + * disconnecting the `worker.process`, and once disconnected, killing with `signal`. In the worker, it does it by killing the process with `signal`. + * + * The `kill()` function kills the worker process without waiting for a graceful + * disconnect, it has the same behavior as `worker.process.kill()`. + * + * This method is aliased as `worker.destroy()` for backwards compatibility. + * + * In a worker, `process.kill()` exists, but it is not this function; + * it is [`kill()`](https://nodejs.org/docs/latest-v24.x/api/process.html#processkillpid-signal). + * @since v0.9.12 + * @param [signal='SIGTERM'] Name of the kill signal to send to the worker process. + */ + kill(signal?: string): void; + destroy(signal?: string): void; + /** + * In a worker, this function will close all servers, wait for the `'close'` event + * on those servers, and then disconnect the IPC channel. + * + * In the primary, an internal message is sent to the worker causing it to call `.disconnect()` on itself. + * + * Causes `.exitedAfterDisconnect` to be set. + * + * After a server is closed, it will no longer accept new connections, + * but connections may be accepted by any other listening worker. Existing + * connections will be allowed to close as usual. When no more connections exist, + * see `server.close()`, the IPC channel to the worker will close allowing it + * to die gracefully. + * + * The above applies _only_ to server connections, client connections are not + * automatically closed by workers, and disconnect does not wait for them to close + * before exiting. + * + * In a worker, `process.disconnect` exists, but it is not this function; + * it is `disconnect()`. + * + * Because long living server connections may block workers from disconnecting, it + * may be useful to send a message, so application specific actions may be taken to + * close them. It also may be useful to implement a timeout, killing a worker if + * the `'disconnect'` event has not been emitted after some time. + * + * ```js + * import net from 'node:net'; + * + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * let timeout; + * + * worker.on('listening', (address) => { + * worker.send('shutdown'); + * worker.disconnect(); + * timeout = setTimeout(() => { + * worker.kill(); + * }, 2000); + * }); + * + * worker.on('disconnect', () => { + * clearTimeout(timeout); + * }); + * + * } else if (cluster.isWorker) { + * const server = net.createServer((socket) => { + * // Connections never end + * }); + * + * server.listen(8000); + * + * process.on('message', (msg) => { + * if (msg === 'shutdown') { + * // Initiate graceful close of any connections to server + * } + * }); + * } + * ``` + * @since v0.7.7 + * @return A reference to `worker`. + */ + disconnect(): this; + /** + * This function returns `true` if the worker is connected to its primary via its + * IPC channel, `false` otherwise. A worker is connected to its primary after it + * has been created. It is disconnected after the `'disconnect'` event is emitted. + * @since v0.11.14 + */ + isConnected(): boolean; + /** + * This function returns `true` if the worker's process has terminated (either + * because of exiting or being signaled). Otherwise, it returns `false`. + * + * ```js + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; + * + * const numCPUs = availableParallelism(); + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('fork', (worker) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * + * cluster.on('exit', (worker, code, signal) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * } else { + * // Workers can share any TCP connection. In this case, it is an HTTP server. + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end(`Current process\n ${process.pid}`); + * process.kill(process.pid); + * }).listen(8000); + * } + * ``` + * @since v0.11.14 + */ + isDead(): boolean; + /** + * This property is `true` if the worker exited due to `.disconnect()`. + * If the worker exited any other way, it is `false`. If the + * worker has not exited, it is `undefined`. + * + * The boolean `worker.exitedAfterDisconnect` allows distinguishing between + * voluntary and accidental exit, the primary may choose not to respawn a worker + * based on this value. + * + * ```js + * cluster.on('exit', (worker, code, signal) => { + * if (worker.exitedAfterDisconnect === true) { + * console.log('Oh, it was just voluntary – no need to worry'); + * } + * }); + * + * // kill worker + * worker.kill(); + * ``` + * @since v6.0.0 + */ + exitedAfterDisconnect: boolean; + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "exit", code: number, signal: string): boolean; + emit(event: "listening", address: Address): boolean; + emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; + } + export interface Cluster extends EventEmitter { + disconnect(callback?: () => void): void; + /** + * Spawn a new worker process. + * + * This can only be called from the primary process. + * @param env Key/value pairs to add to worker process environment. + * @since v0.6.0 + */ + fork(env?: any): Worker; + /** @deprecated since v16.0.0 - use isPrimary. */ + readonly isMaster: boolean; + /** + * True if the process is a primary. This is determined by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` + * is undefined, then `isPrimary` is `true`. + * @since v16.0.0 + */ + readonly isPrimary: boolean; + /** + * True if the process is not a primary (it is the negation of `cluster.isPrimary`). + * @since v0.6.0 + */ + readonly isWorker: boolean; + /** + * The scheduling policy, either `cluster.SCHED_RR` for round-robin or `cluster.SCHED_NONE` to leave it to the operating system. This is a + * global setting and effectively frozen once either the first worker is spawned, or [`.setupPrimary()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clustersetupprimarysettings) + * is called, whichever comes first. + * + * `SCHED_RR` is the default on all operating systems except Windows. Windows will change to `SCHED_RR` once libuv is able to effectively distribute + * IOCP handles without incurring a large performance hit. + * + * `cluster.schedulingPolicy` can also be set through the `NODE_CLUSTER_SCHED_POLICY` environment variable. Valid values are `'rr'` and `'none'`. + * @since v0.11.2 + */ + schedulingPolicy: number; + /** + * After calling [`.setupPrimary()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clustersetupprimarysettings) + * (or [`.fork()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clusterforkenv)) this settings object will contain + * the settings, including the default values. + * + * This object is not intended to be changed or set manually. + * @since v0.7.1 + */ + readonly settings: ClusterSettings; + /** @deprecated since v16.0.0 - use [`.setupPrimary()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clustersetupprimarysettings) instead. */ + setupMaster(settings?: ClusterSettings): void; + /** + * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in `cluster.settings`. + * + * Any settings changes only affect future calls to [`.fork()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clusterforkenv) + * and have no effect on workers that are already running. + * + * The only attribute of a worker that cannot be set via `.setupPrimary()` is the `env` passed to + * [`.fork()`](https://nodejs.org/docs/latest-v24.x/api/cluster.html#clusterforkenv). + * + * The defaults above apply to the first call only; the defaults for later calls are the current values at the time of + * `cluster.setupPrimary()` is called. + * + * ```js + * import cluster from 'node:cluster'; + * + * cluster.setupPrimary({ + * exec: 'worker.js', + * args: ['--use', 'https'], + * silent: true, + * }); + * cluster.fork(); // https worker + * cluster.setupPrimary({ + * exec: 'worker.js', + * args: ['--use', 'http'], + * }); + * cluster.fork(); // http worker + * ``` + * + * This can only be called from the primary process. + * @since v16.0.0 + */ + setupPrimary(settings?: ClusterSettings): void; + /** + * A reference to the current worker object. Not available in the primary process. + * + * ```js + * import cluster from 'node:cluster'; + * + * if (cluster.isPrimary) { + * console.log('I am primary'); + * cluster.fork(); + * cluster.fork(); + * } else if (cluster.isWorker) { + * console.log(`I am worker #${cluster.worker.id}`); + * } + * ``` + * @since v0.7.0 + */ + readonly worker?: Worker | undefined; + /** + * A hash that stores the active worker objects, keyed by `id` field. This makes it easy to loop through all the workers. It is only available in the primary process. + * + * A worker is removed from `cluster.workers` after the worker has disconnected _and_ exited. The order between these two events cannot be determined in advance. However, it + * is guaranteed that the removal from the `cluster.workers` list happens before the last `'disconnect'` or `'exit'` event is emitted. + * + * ```js + * import cluster from 'node:cluster'; + * + * for (const worker of Object.values(cluster.workers)) { + * worker.send('big announcement to all workers'); + * } + * ``` + * @since v0.7.0 + */ + readonly workers?: NodeJS.Dict | undefined; + readonly SCHED_NONE: number; + readonly SCHED_RR: number; + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener( + event: "message", + listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, + ): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect", worker: Worker): boolean; + emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + emit(event: "fork", worker: Worker): boolean; + emit(event: "listening", worker: Worker, address: Address): boolean; + emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online", worker: Worker): boolean; + emit(event: "setup", settings: ClusterSettings): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: ClusterSettings) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: ClusterSettings) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependListener( + event: "message", + listener: (worker: Worker, message: any, handle?: net.Socket | net.Server) => void, + ): this; + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener( + event: "message", + listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, + ): this; + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + } + const cluster: Cluster; + export default cluster; +} +declare module "node:cluster" { + export * from "cluster"; + export { default as default } from "cluster"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/compatibility/iterators.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/compatibility/iterators.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..156e7856360bf532de1d82080e425573e9b2d749 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/compatibility/iterators.d.ts @@ -0,0 +1,21 @@ +// Backwards-compatible iterator interfaces, augmented with iterator helper methods by lib.esnext.iterator in TypeScript 5.6. +// The IterableIterator interface does not contain these methods, which creates assignability issues in places where IteratorObjects +// are expected (eg. DOM-compatible APIs) if lib.esnext.iterator is loaded. +// Also ensures that iterators returned by the Node API, which inherit from Iterator.prototype, correctly expose the iterator helper methods +// if lib.esnext.iterator is loaded. +// TODO: remove once this package no longer supports TS 5.5, and replace NodeJS.BuiltinIteratorReturn with BuiltinIteratorReturn. + +// Placeholders for TS <5.6 +interface IteratorObject {} +interface AsyncIteratorObject {} + +declare namespace NodeJS { + // Populate iterator methods for TS <5.6 + interface Iterator extends globalThis.Iterator {} + interface AsyncIterator extends globalThis.AsyncIterator {} + + // Polyfill for TS 5.6's instrinsic BuiltinIteratorReturn type, required for DOM-compatible iterators + type BuiltinIteratorReturn = ReturnType extends + globalThis.Iterator ? TReturn + : any; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/console.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/console.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c923bd0acbc43d7e8b7fa656dd8e0b8b98d4123d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/console.d.ts @@ -0,0 +1,452 @@ +/** + * The `node:console` module provides a simple debugging console that is similar to + * the JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()`, and `console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and + * [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/console.js) + */ +declare module "console" { + import console = require("node:console"); + export = console; +} +declare module "node:console" { + import { InspectOptions } from "node:util"; + global { + // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build + interface Console { + Console: console.ConsoleConstructor; + /** + * `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only + * writes a message and does not otherwise affect execution. The output always + * starts with `"Assertion failed"`. If provided, `message` is formatted using + * [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args). + * + * If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens. + * + * ```js + * console.assert(true, 'does nothing'); + * + * console.assert(false, 'Whoops %s work', 'didn\'t'); + * // Assertion failed: Whoops didn't work + * + * console.assert(); + * // Assertion failed + * ``` + * @since v0.1.101 + * @param value The value tested for being truthy. + * @param message All arguments besides `value` are used as error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the + * TTY. When `stdout` is not a TTY, this method does nothing. + * + * The specific operation of `console.clear()` can vary across operating systems + * and terminal types. For most Linux operating systems, `console.clear()` operates similarly to the `clear` shell command. On Windows, `console.clear()` will clear only the output in the + * current terminal viewport for the Node.js + * binary. + * @since v8.3.0 + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the + * number of times `console.count()` has been called with the given `label`. + * + * ```js + * > console.count() + * default: 1 + * undefined + * > console.count('default') + * default: 2 + * undefined + * > console.count('abc') + * abc: 1 + * undefined + * > console.count('xyz') + * xyz: 1 + * undefined + * > console.count('abc') + * abc: 2 + * undefined + * > console.count() + * default: 3 + * undefined + * > + * ``` + * @since v8.3.0 + * @param [label='default'] The display label for the counter. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + * + * ```js + * > console.count('abc'); + * abc: 1 + * undefined + * > console.countReset('abc'); + * undefined + * > console.count('abc'); + * abc: 1 + * undefined + * > + * ``` + * @since v8.3.0 + * @param [label='default'] The display label for the counter. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link log}. + * @since v8.0.0 + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options) on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + * @since v0.1.101 + */ + dir(obj: any, options?: InspectOptions): void; + /** + * This method calls `console.log()` passing it the arguments received. + * This method does not produce any XML formatting. + * @since v8.0.0 + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) + * (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). + * + * ```js + * const code = 5; + * console.error('error #%d', code); + * // Prints: error #5, to stderr + * console.error('error', code); + * // Prints: error 5, to stderr + * ``` + * + * If formatting elements (e.g. `%d`) are not found in the first string then + * [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options) is called on each argument and the + * resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) + * for more information. + * @since v0.1.100 + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by spaces for `groupIndentation` length. + * + * If one or more `label`s are provided, those are printed first without the + * additional indentation. + * @since v8.5.0 + */ + group(...label: any[]): void; + /** + * An alias for {@link group}. + * @since v8.5.0 + */ + groupCollapsed(...label: any[]): void; + /** + * Decreases indentation of subsequent lines by spaces for `groupIndentation` length. + * @since v8.5.0 + */ + groupEnd(): void; + /** + * The `console.info()` function is an alias for {@link log}. + * @since v0.1.100 + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) + * (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). + * + * ```js + * const count = 5; + * console.log('count: %d', count); + * // Prints: count: 5, to stdout + * console.log('count:', count); + * // Prints: count: 5, to stdout + * ``` + * + * See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information. + * @since v0.1.100 + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * Try to construct a table with the columns of the properties of `tabularData` (or use `properties`) and rows of `tabularData` and log it. Falls back to just + * logging the argument if it can't be parsed as tabular. + * + * ```js + * // These can't be parsed as tabular data + * console.table(Symbol()); + * // Symbol() + * + * console.table(undefined); + * // undefined + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); + * // ┌─────────┬─────┬─────┐ + * // │ (index) │ a │ b │ + * // ├─────────┼─────┼─────┤ + * // │ 0 │ 1 │ 'Y' │ + * // │ 1 │ 'Z' │ 2 │ + * // └─────────┴─────┴─────┘ + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); + * // ┌─────────┬─────┐ + * // │ (index) │ a │ + * // ├─────────┼─────┤ + * // │ 0 │ 1 │ + * // │ 1 │ 'Z' │ + * // └─────────┴─────┘ + * ``` + * @since v10.0.0 + * @param properties Alternate properties for constructing the table. + */ + table(tabularData: any, properties?: readonly string[]): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers + * are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in + * suitable time units to `stdout`. For example, if the elapsed + * time is 3869ms, `console.timeEnd()` displays "3.869s". + * @since v0.1.104 + * @param [label='default'] + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link time} and + * prints the result to `stdout`: + * + * ```js + * console.time('bunch-of-stuff'); + * // Do a bunch of stuff. + * console.timeEnd('bunch-of-stuff'); + * // Prints: bunch-of-stuff: 225.438ms + * ``` + * @since v0.1.104 + * @param [label='default'] + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link time}, prints + * the elapsed time and other `data` arguments to `stdout`: + * + * ```js + * console.time('process'); + * const value = expensiveProcess1(); // Returns 42 + * console.timeLog('process', value); + * // Prints "process: 365.227ms 42". + * doExpensiveProcess2(value); + * console.timeEnd('process'); + * ``` + * @since v10.7.0 + * @param [label='default'] + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string `'Trace: '`, followed by the [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) + * formatted message and stack trace to the current position in the code. + * + * ```js + * console.trace('Show me'); + * // Prints: (stack trace will vary based on where trace is called) + * // Trace: Show me + * // at repl:2:9 + * // at REPLServer.defaultEval (repl.js:248:27) + * // at bound (domain.js:287:14) + * // at REPLServer.runBound [as eval] (domain.js:300:12) + * // at REPLServer. (repl.js:412:12) + * // at emitOne (events.js:82:20) + * // at REPLServer.emit (events.js:169:7) + * // at REPLServer.Interface._onLine (readline.js:210:10) + * // at REPLServer.Interface._line (readline.js:549:8) + * // at REPLServer.Interface._ttyWrite (readline.js:826:14) + * ``` + * @since v0.1.104 + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The `console.warn()` function is an alias for {@link error}. + * @since v0.1.100 + */ + warn(message?: any, ...optionalParams: any[]): void; + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. The `console.profile()` + * method starts a JavaScript CPU profile with an optional label until {@link profileEnd} + * is called. The profile is then added to the Profile panel of the inspector. + * + * ```js + * console.profile('MyLabel'); + * // Some code + * console.profileEnd('MyLabel'); + * // Adds the profile 'MyLabel' to the Profiles panel of the inspector. + * ``` + * @since v8.0.0 + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. Stops the current + * JavaScript CPU profiling session if one has been started and prints the report to the + * Profiles panel of the inspector. See {@link profile} for an example. + * + * If this method is called without a label, the most recently started profile is stopped. + * @since v8.0.0 + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. The `console.timeStamp()` + * method adds an event with the label `'label'` to the Timeline panel of the inspector. + * @since v8.0.0 + */ + timeStamp(label?: string): void; + } + /** + * The `console` module provides a simple debugging console that is similar to the + * JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and + * [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/console.js) + */ + namespace console { + interface ConsoleConstructorOptions { + stdout: NodeJS.WritableStream; + stderr?: NodeJS.WritableStream | undefined; + /** + * Ignore errors when writing to the underlying streams. + * @default true + */ + ignoreErrors?: boolean | undefined; + /** + * Set color support for this `Console` instance. Setting to true enables coloring while inspecting + * values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color + * support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the + * respective stream. This option can not be used, if `inspectOptions.colors` is set as well. + * @default auto + */ + colorMode?: boolean | "auto" | undefined; + /** + * Specifies options that are passed along to + * [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options). + */ + inspectOptions?: InspectOptions | undefined; + /** + * Set group indentation. + * @default 2 + */ + groupIndentation?: number | undefined; + } + interface ConsoleConstructor { + prototype: Console; + new(stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; + } + } + var console: Console; + } + export = globalThis.console; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/constants.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/constants.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5685a9dfe307be102639a9c61a8c02632b542c95 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/constants.d.ts @@ -0,0 +1,21 @@ +/** + * @deprecated The `node:constants` module is deprecated. When requiring access to constants + * relevant to specific Node.js builtin modules, developers should instead refer + * to the `constants` property exposed by the relevant module. For instance, + * `require('node:fs').constants` and `require('node:os').constants`. + */ +declare module "constants" { + const constants: + & typeof import("node:os").constants.dlopen + & typeof import("node:os").constants.errno + & typeof import("node:os").constants.priority + & typeof import("node:os").constants.signals + & typeof import("node:fs").constants + & typeof import("node:crypto").constants; + export = constants; +} + +declare module "node:constants" { + import constants = require("constants"); + export = constants; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/crypto.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/crypto.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e3c7d67174f00eac30e4b82994534ba25f7e7003 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,4532 @@ +/** + * The `node:crypto` module provides cryptographic functionality that includes a + * set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify + * functions. + * + * ```js + * const { createHmac } = await import('node:crypto'); + * + * const secret = 'abcdefg'; + * const hash = createHmac('sha256', secret) + * .update('I love cupcakes') + * .digest('hex'); + * console.log(hash); + * // Prints: + * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/crypto.js) + */ +declare module "crypto" { + import * as stream from "node:stream"; + import { PeerCertificate } from "node:tls"; + /** + * SPKAC is a Certificate Signing Request mechanism originally implemented by + * Netscape and was specified formally as part of HTML5's `keygen` element. + * + * `` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects + * should not use this element anymore. + * + * The `node:crypto` module provides the `Certificate` class for working with SPKAC + * data. The most common usage is handling output generated by the HTML5 `` element. Node.js uses [OpenSSL's SPKAC + * implementation](https://www.openssl.org/docs/man3.0/man1/openssl-spkac.html) internally. + * @since v0.11.8 + */ + class Certificate { + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const challenge = Certificate.exportChallenge(spkac); + * console.log(challenge.toString('utf8')); + * // Prints: the challenge as a UTF8 string + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The challenge component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportChallenge(spkac: BinaryLike): Buffer; + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const publicKey = Certificate.exportPublicKey(spkac); + * console.log(publicKey); + * // Prints: the public key as + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The public key component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * ```js + * import { Buffer } from 'node:buffer'; + * const { Certificate } = await import('node:crypto'); + * + * const spkac = getSpkacSomehow(); + * console.log(Certificate.verifySpkac(Buffer.from(spkac))); + * // Prints: true or false + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return `true` if the given `spkac` data structure is valid, `false` otherwise. + */ + static verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + /** + * @deprecated + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): Buffer; + /** + * @deprecated + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * @deprecated + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + } + namespace constants { + // https://nodejs.org/dist/latest-v24.x/docs/api/crypto.html#crypto-constants + const OPENSSL_VERSION_NUMBER: number; + /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ + const SSL_OP_ALL: number; + /** Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode for TLS v1.3 */ + const SSL_OP_ALLOW_NO_DHE_KEX: number; + /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + /** Instructs OpenSSL to use Cisco's version identifier of DTLS_BAD_VER. */ + const SSL_OP_CISCO_ANYCONNECT: number; + /** Instructs OpenSSL to turn on cookie exchange. */ + const SSL_OP_COOKIE_EXCHANGE: number; + /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + /** Instructs OpenSSL to disable encrypt-then-MAC. */ + const SSL_OP_NO_ENCRYPT_THEN_MAC: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to disable renegotiation. */ + const SSL_OP_NO_RENEGOTIATION: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + /** Instructs OpenSSL to turn off SSL v2 */ + const SSL_OP_NO_SSLv2: number; + /** Instructs OpenSSL to turn off SSL v3 */ + const SSL_OP_NO_SSLv3: number; + /** Instructs OpenSSL to disable use of RFC4507bis tickets. */ + const SSL_OP_NO_TICKET: number; + /** Instructs OpenSSL to turn off TLS v1 */ + const SSL_OP_NO_TLSv1: number; + /** Instructs OpenSSL to turn off TLS v1.1 */ + const SSL_OP_NO_TLSv1_1: number; + /** Instructs OpenSSL to turn off TLS v1.2 */ + const SSL_OP_NO_TLSv1_2: number; + /** Instructs OpenSSL to turn off TLS v1.3 */ + const SSL_OP_NO_TLSv1_3: number; + /** Instructs OpenSSL server to prioritize ChaCha20-Poly1305 when the client does. This option has no effect if `SSL_OP_CIPHER_SERVER_PREFERENCE` is not enabled. */ + const SSL_OP_PRIORITIZE_CHACHA: number; + /** Instructs OpenSSL to disable version rollback attack detection. */ + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_RSA: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_EC: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ + const RSA_PSS_SALTLEN_DIGEST: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ + const RSA_PSS_SALTLEN_MAX_SIGN: number; + /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ + const RSA_PSS_SALTLEN_AUTO: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ + const defaultCoreCipherList: string; + /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ + const defaultCipherList: string; + } + interface HashOptions extends stream.TransformOptions { + /** + * For XOF hash functions such as `shake256`, the + * outputLength option can be used to specify the desired output length in bytes. + */ + outputLength?: number | undefined; + } + /** @deprecated since v10.0.0 */ + const fips: boolean; + /** + * Creates and returns a `Hash` object that can be used to generate hash digests + * using the given `algorithm`. Optional `options` argument controls stream + * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option + * can be used to specify the desired output length in bytes. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * Example: generating the sha256 sum of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHash, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hash = createHash('sha256'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hash.update(data); + * else { + * console.log(`${hash.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.92 + * @param options `stream.transform` options + */ + function createHash(algorithm: string, options?: HashOptions): Hash; + /** + * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`. + * Optional `options` argument controls stream behavior. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is + * a `KeyObject`, its type must be `secret`. If it is a string, please consider `caveats when using strings as inputs to cryptographic APIs`. If it was + * obtained from a cryptographically secure source of entropy, such as {@link randomBytes} or {@link generateKey}, its length should not + * exceed the block size of `algorithm` (e.g., 512 bits for SHA-256). + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hmac.update(data); + * else { + * console.log(`${hmac.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; + // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings + type BinaryToTextEncoding = "base64" | "base64url" | "hex" | "binary"; + type CharacterEncoding = "utf8" | "utf-8" | "utf16le" | "utf-16le" | "latin1"; + type LegacyCharacterEncoding = "ascii" | "binary" | "ucs2" | "ucs-2"; + type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + /** + * The `Hash` class is a utility for creating hash digests of data. It can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed hash digest on the readable side, or + * * Using the `hash.update()` and `hash.digest()` methods to produce the + * computed hash. + * + * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hash` objects as streams: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hash.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * } + * }); + * + * hash.write('some data to hash'); + * hash.end(); + * ``` + * + * Example: Using `Hash` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { createHash } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * const input = createReadStream('test.js'); + * input.pipe(hash).setEncoding('hex').pipe(stdout); + * ``` + * + * Example: Using the `hash.update()` and `hash.digest()` methods: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('some data to hash'); + * console.log(hash.digest('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * ``` + * @since v0.1.92 + */ + class Hash extends stream.Transform { + private constructor(); + /** + * Creates a new `Hash` object that contains a deep copy of the internal state + * of the current `Hash` object. + * + * The optional `options` argument controls stream behavior. For XOF hash + * functions such as `'shake256'`, the `outputLength` option can be used to + * specify the desired output length in bytes. + * + * An error is thrown when an attempt is made to copy the `Hash` object after + * its `hash.digest()` method has been called. + * + * ```js + * // Calculate a rolling hash. + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('one'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('two'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('three'); + * console.log(hash.copy().digest('hex')); + * + * // Etc. + * ``` + * @since v13.1.0 + * @param options `stream.transform` options + */ + copy(options?: HashOptions): Hash; + /** + * Updates the hash content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hash; + update(data: string, inputEncoding: Encoding): Hash; + /** + * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method). + * If `encoding` is provided a string will be returned; otherwise + * a `Buffer` is returned. + * + * The `Hash` object can not be used again after `hash.digest()` method has been + * called. Multiple calls will cause an error to be thrown. + * @since v0.1.92 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + /** + * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can + * be used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed HMAC digest on the readable side, or + * * Using the `hmac.update()` and `hmac.digest()` methods to produce the + * computed HMAC digest. + * + * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hmac` objects as streams: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hmac.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * } + * }); + * + * hmac.write('some data to hash'); + * hmac.end(); + * ``` + * + * Example: Using `Hmac` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream('test.js'); + * input.pipe(hmac).pipe(stdout); + * ``` + * + * Example: Using the `hmac.update()` and `hmac.digest()` methods: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + * @since v0.1.94 + * @deprecated Since v20.13.0 Calling `Hmac` class directly with `Hmac()` or `new Hmac()` is deprecated due to being internals, not intended for public use. Please use the {@link createHmac} method to create Hmac instances. + */ + class Hmac extends stream.Transform { + private constructor(); + /** + * Updates the `Hmac` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hmac; + update(data: string, inputEncoding: Encoding): Hmac; + /** + * Calculates the HMAC digest of all of the data passed using `hmac.update()`. + * If `encoding` is + * provided a string is returned; otherwise a `Buffer` is returned; + * + * The `Hmac` object can not be used again after `hmac.digest()` has been + * called. Multiple calls to `hmac.digest()` will result in an error being thrown. + * @since v0.1.94 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + type KeyObjectType = "secret" | "public" | "private"; + interface KeyExportOptions { + type: "pkcs1" | "spki" | "pkcs8" | "sec1"; + format: T; + cipher?: string | undefined; + passphrase?: string | Buffer | undefined; + } + interface JwkKeyExportOptions { + format: "jwk"; + } + interface JsonWebKey { + crv?: string | undefined; + d?: string | undefined; + dp?: string | undefined; + dq?: string | undefined; + e?: string | undefined; + k?: string | undefined; + kty?: string | undefined; + n?: string | undefined; + p?: string | undefined; + q?: string | undefined; + qi?: string | undefined; + x?: string | undefined; + y?: string | undefined; + [key: string]: unknown; + } + interface AsymmetricKeyDetails { + /** + * Key size in bits (RSA, DSA). + */ + modulusLength?: number | undefined; + /** + * Public exponent (RSA). + */ + publicExponent?: bigint | undefined; + /** + * Name of the message digest (RSA-PSS). + */ + hashAlgorithm?: string | undefined; + /** + * Name of the message digest used by MGF1 (RSA-PSS). + */ + mgf1HashAlgorithm?: string | undefined; + /** + * Minimal salt length in bytes (RSA-PSS). + */ + saltLength?: number | undefined; + /** + * Size of q in bits (DSA). + */ + divisorLength?: number | undefined; + /** + * Name of the curve (EC). + */ + namedCurve?: string | undefined; + } + /** + * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key, + * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject` + * objects are not to be created directly using the `new`keyword. + * + * Most applications should consider using the new `KeyObject` API instead of + * passing keys as strings or `Buffer`s due to improved security features. + * + * `KeyObject` instances can be passed to other threads via `postMessage()`. + * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to + * be listed in the `transferList` argument. + * @since v11.6.0 + */ + class KeyObject { + private constructor(); + /** + * Example: Converting a `CryptoKey` instance to a `KeyObject`: + * + * ```js + * const { KeyObject } = await import('node:crypto'); + * const { subtle } = globalThis.crypto; + * + * const key = await subtle.generateKey({ + * name: 'HMAC', + * hash: 'SHA-256', + * length: 256, + * }, true, ['sign', 'verify']); + * + * const keyObject = KeyObject.from(key); + * console.log(keyObject.symmetricKeySize); + * // Prints: 32 (symmetric key size in bytes) + * ``` + * @since v15.0.0 + */ + static from(key: webcrypto.CryptoKey): KeyObject; + /** + * For asymmetric keys, this property represents the type of the key. Supported key + * types are: + * + * * `'rsa'` (OID 1.2.840.113549.1.1.1) + * * `'rsa-pss'` (OID 1.2.840.113549.1.1.10) + * * `'dsa'` (OID 1.2.840.10040.4.1) + * * `'ec'` (OID 1.2.840.10045.2.1) + * * `'x25519'` (OID 1.3.101.110) + * * `'x448'` (OID 1.3.101.111) + * * `'ed25519'` (OID 1.3.101.112) + * * `'ed448'` (OID 1.3.101.113) + * * `'dh'` (OID 1.2.840.113549.1.3.1) + * + * This property is `undefined` for unrecognized `KeyObject` types and symmetric + * keys. + * @since v11.6.0 + */ + asymmetricKeyType?: KeyType | undefined; + /** + * This property exists only on asymmetric keys. Depending on the type of the key, + * this object contains information about the key. None of the information obtained + * through this property can be used to uniquely identify a key or to compromise + * the security of the key. + * + * For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence, + * the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be + * set. + * + * Other key details might be exposed via this API using additional attributes. + * @since v15.7.0 + */ + asymmetricKeyDetails?: AsymmetricKeyDetails | undefined; + /** + * For symmetric keys, the following encoding options can be used: + * + * For public keys, the following encoding options can be used: + * + * For private keys, the following encoding options can be used: + * + * The result type depends on the selected encoding format, when PEM the + * result is a string, when DER it will be a buffer containing the data + * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. + * + * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are + * ignored. + * + * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of + * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be + * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for + * encrypted private keys. Since PKCS#8 defines its own + * encryption mechanism, PEM-level encryption is not supported when encrypting + * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for + * PKCS#1 and SEC1 encryption. + * @since v11.6.0 + */ + export(options: KeyExportOptions<"pem">): string | Buffer; + export(options?: KeyExportOptions<"der">): Buffer; + export(options?: JwkKeyExportOptions): JsonWebKey; + /** + * Returns `true` or `false` depending on whether the keys have exactly the same + * type, value, and parameters. This method is not [constant time](https://en.wikipedia.org/wiki/Timing_attack). + * @since v17.7.0, v16.15.0 + * @param otherKeyObject A `KeyObject` with which to compare `keyObject`. + */ + equals(otherKeyObject: KeyObject): boolean; + /** + * For secret keys, this property represents the size of the key in bytes. This + * property is `undefined` for asymmetric keys. + * @since v11.6.0 + */ + symmetricKeySize?: number | undefined; + /** + * Converts a `KeyObject` instance to a `CryptoKey`. + * @since 22.10.0 + */ + toCryptoKey( + algorithm: + | webcrypto.AlgorithmIdentifier + | webcrypto.RsaHashedImportParams + | webcrypto.EcKeyImportParams + | webcrypto.HmacImportParams, + extractable: boolean, + keyUsages: readonly webcrypto.KeyUsage[], + ): webcrypto.CryptoKey; + /** + * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys + * or `'private'` for private (asymmetric) keys. + * @since v11.6.0 + */ + type: KeyObjectType; + } + type CipherCCMTypes = "aes-128-ccm" | "aes-192-ccm" | "aes-256-ccm"; + type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm"; + type CipherOCBTypes = "aes-128-ocb" | "aes-192-ocb" | "aes-256-ocb"; + type CipherChaCha20Poly1305Types = "chacha20-poly1305"; + type BinaryLike = string | NodeJS.ArrayBufferView; + type CipherKey = BinaryLike | KeyObject; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number | undefined; + } + interface CipherOCBOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherChaCha20Poly1305Options extends stream.TransformOptions { + /** @default 16 */ + authTagLength?: number | undefined; + } + /** + * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and + * initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a + * given IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createCipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): CipherCCM; + function createCipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): CipherOCB; + function createCipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): CipherGCM; + function createCipheriv( + algorithm: CipherChaCha20Poly1305Types, + key: CipherKey, + iv: BinaryLike, + options?: CipherChaCha20Poly1305Options, + ): CipherChaCha20Poly1305; + function createCipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Cipheriv; + /** + * Instances of the `Cipheriv` class are used to encrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain unencrypted + * data is written to produce encrypted data on the readable side, or + * * Using the `cipher.update()` and `cipher.final()` methods to produce + * the encrypted data. + * + * The {@link createCipheriv} method is + * used to create `Cipheriv` instances. `Cipheriv` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Cipheriv` objects as streams: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * // Once we have the key and iv, we can create and use the cipher... + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = ''; + * cipher.setEncoding('hex'); + * + * cipher.on('data', (chunk) => encrypted += chunk); + * cipher.on('end', () => console.log(encrypted)); + * + * cipher.write('some clear text data'); + * cipher.end(); + * }); + * }); + * ``` + * + * Example: Using `Cipheriv` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * + * import { + * pipeline, + * } from 'node:stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.js'); + * const output = createWriteStream('test.enc'); + * + * pipeline(input, cipher, output, (err) => { + * if (err) throw err; + * }); + * }); + * }); + * ``` + * + * Example: Using the `cipher.update()` and `cipher.final()` methods: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); + * encrypted += cipher.final('hex'); + * console.log(encrypted); + * }); + * }); + * ``` + * @since v0.1.94 + */ + class Cipheriv extends stream.Transform { + private constructor(); + /** + * Updates the cipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or `DataView`. If `data` is a `Buffer`, + * `TypedArray`, or `DataView`, then `inputEncoding` is ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being + * thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the data. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: BinaryLike): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `cipher.final()` method has been called, the `Cipheriv` object can no + * longer be used to encrypt data. Attempts to call `cipher.final()` more than + * once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When using block encryption algorithms, the `Cipheriv` class will automatically + * add padding to the input data to the appropriate block size. To disable the + * default padding call `cipher.setAutoPadding(false)`. + * + * When `autoPadding` is `false`, the length of the entire input data must be a + * multiple of the cipher's block size or `cipher.final()` will throw an error. + * Disabling automatic padding is useful for non-standard padding, for instance + * using `0x0` instead of PKCS padding. + * + * The `cipher.setAutoPadding()` method must be called before `cipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(autoPadding?: boolean): this; + } + interface CipherCCM extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherGCM extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherOCB extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherChaCha20Poly1305 extends Cipheriv { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + /** + * Creates and returns a `Decipheriv` object that uses the given `algorithm`, `key` and initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the `authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength` option is not required but can be used to restrict accepted authentication tags + * to those with the specified length. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a given + * IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createDecipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): DecipherCCM; + function createDecipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): DecipherOCB; + function createDecipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): DecipherGCM; + function createDecipheriv( + algorithm: CipherChaCha20Poly1305Types, + key: CipherKey, + iv: BinaryLike, + options?: CipherChaCha20Poly1305Options, + ): DecipherChaCha20Poly1305; + function createDecipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Decipheriv; + /** + * Instances of the `Decipheriv` class are used to decrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain encrypted + * data is written to produce unencrypted data on the readable side, or + * * Using the `decipher.update()` and `decipher.final()` methods to + * produce the unencrypted data. + * + * The {@link createDecipheriv} method is + * used to create `Decipheriv` instances. `Decipheriv` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Decipheriv` objects as streams: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Key length is dependent on the algorithm. In this case for aes192, it is + * // 24 bytes (192 bits). + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * let decrypted = ''; + * decipher.on('readable', () => { + * let chunk; + * while (null !== (chunk = decipher.read())) { + * decrypted += chunk.toString('utf8'); + * } + * }); + * decipher.on('end', () => { + * console.log(decrypted); + * // Prints: some clear text data + * }); + * + * // Encrypted with same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * decipher.write(encrypted, 'hex'); + * decipher.end(); + * ``` + * + * Example: Using `Decipheriv` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.enc'); + * const output = createWriteStream('test.js'); + * + * input.pipe(decipher).pipe(output); + * ``` + * + * Example: Using the `decipher.update()` and `decipher.final()` methods: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * // Encrypted using same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * let decrypted = decipher.update(encrypted, 'hex', 'utf8'); + * decrypted += decipher.final('utf8'); + * console.log(decrypted); + * // Prints: some clear text data + * ``` + * @since v0.1.94 + */ + class Decipheriv extends stream.Transform { + private constructor(); + /** + * Updates the decipher with `data`. If the `inputEncoding` argument is given, + * the `data` argument is a string using the specified encoding. If the `inputEncoding` argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is + * ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding` is specified, a string using the specified encoding is returned. If no `outputEncoding` is provided, a `Buffer` is returned. + * + * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error + * being thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: NodeJS.ArrayBufferView): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `decipher.final()` method has been called, the `Decipheriv` object can + * no longer be used to decrypt data. Attempts to call `decipher.final()` more + * than once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When data has been encrypted without standard block padding, calling `decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and + * removing padding. + * + * Turning auto padding off will only work if the input data's length is a + * multiple of the ciphers block size. + * + * The `decipher.setAutoPadding()` method must be called before `decipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(auto_padding?: boolean): this; + } + interface DecipherCCM extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface DecipherGCM extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherOCB extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherChaCha20Poly1305 extends Decipheriv { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "pkcs8" | "sec1" | undefined; + passphrase?: string | Buffer | undefined; + encoding?: string | undefined; + } + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "spki" | undefined; + encoding?: string | undefined; + } + /** + * Asynchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKey, + * } = await import('node:crypto'); + * + * generateKey('hmac', { length: 512 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKey( + type: "hmac" | "aes", + options: { + length: number; + }, + callback: (err: Error | null, key: KeyObject) => void, + ): void; + /** + * Synchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKeySync, + * } = await import('node:crypto'); + * + * const key = generateKeySync('hmac', { length: 512 }); + * console.log(key.export().toString('hex')); // e89..........41e + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKeySync( + type: "hmac" | "aes", + options: { + length: number; + }, + ): KeyObject; + interface JsonWebKeyInput { + key: JsonWebKey; + format: "jwk"; + } + /** + * Creates and returns a new key object containing a private key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key` must be an object with the properties described above. + * + * If the private key is encrypted, a `passphrase` must be specified. The length + * of the passphrase is limited to 1024 bytes. + * @since v11.6.0 + */ + function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a public key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject` with type `'private'`, the public key is derived from the given private key; + * otherwise, `key` must be an object with the properties described above. + * + * If the format is `'pem'`, the `'key'` may also be an X.509 certificate. + * + * Because public keys can be derived from private keys, a private key may be + * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the + * returned `KeyObject` will be `'public'` and that the private key cannot be + * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type `'private'` is given, a new `KeyObject` with type `'public'` will be returned + * and it will be impossible to extract the private key from the returned object. + * @since v11.6.0 + */ + function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a secret key for symmetric + * encryption or `Hmac`. + * @since v11.6.0 + * @param encoding The string encoding when `key` is a string. + */ + function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject; + function createSecretKey(key: string, encoding: BufferEncoding): KeyObject; + /** + * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms. + * Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Sign` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createSign(algorithm: string, options?: stream.WritableOptions): Sign; + type DSAEncoding = "der" | "ieee-p1363"; + interface SigningOptions { + /** + * @see crypto.constants.RSA_PKCS1_PADDING + */ + padding?: number | undefined; + saltLength?: number | undefined; + dsaEncoding?: DSAEncoding | undefined; + } + interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} + interface SignKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface SignJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} + interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} + interface VerifyKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} + type KeyLike = string | Buffer | KeyObject; + /** + * The `Sign` class is a utility for generating signatures. It can be used in one + * of two ways: + * + * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or + * * Using the `sign.update()` and `sign.sign()` methods to produce the + * signature. + * + * The {@link createSign} method is used to create `Sign` instances. The + * argument is the string name of the hash function to use. `Sign` objects are not + * to be created directly using the `new` keyword. + * + * Example: Using `Sign` and `Verify` objects as streams: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('ec', { + * namedCurve: 'sect239k1', + * }); + * + * const sign = createSign('SHA256'); + * sign.write('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey, 'hex'); + * + * const verify = createVerify('SHA256'); + * verify.write('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature, 'hex')); + * // Prints: true + * ``` + * + * Example: Using the `sign.update()` and `verify.update()` methods: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('rsa', { + * modulusLength: 2048, + * }); + * + * const sign = createSign('SHA256'); + * sign.update('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey); + * + * const verify = createVerify('SHA256'); + * verify.update('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature)); + * // Prints: true + * ``` + * @since v0.1.92 + */ + class Sign extends stream.Writable { + private constructor(); + /** + * Updates the `Sign` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): this; + update(data: string, inputEncoding: Encoding): this; + /** + * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the following additional properties can be passed: + * + * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * The `Sign` object can not be again used after `sign.sign()` method has been + * called. Multiple calls to `sign.sign()` will result in an error being thrown. + * @since v0.1.92 + */ + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput): Buffer; + sign( + privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + outputFormat: BinaryToTextEncoding, + ): string; + } + /** + * Creates and returns a `Verify` object that uses the given algorithm. + * Use {@link getHashes} to obtain an array of names of the available + * signing algorithms. Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Verify` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; + /** + * The `Verify` class is a utility for verifying signatures. It can be used in one + * of two ways: + * + * * As a writable `stream` where written data is used to validate against the + * supplied signature, or + * * Using the `verify.update()` and `verify.verify()` methods to verify + * the signature. + * + * The {@link createVerify} method is used to create `Verify` instances. `Verify` objects are not to be created directly using the `new` keyword. + * + * See `Sign` for examples. + * @since v0.1.92 + */ + class Verify extends stream.Writable { + private constructor(); + /** + * Updates the `Verify` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `inputEncoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or `DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Verify; + update(data: string, inputEncoding: Encoding): Verify; + /** + * Verifies the provided data using the given `object` and `signature`. + * + * If `object` is not a `KeyObject`, this function behaves as if `object` had been passed to {@link createPublicKey}. If it is an + * object, the following additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the data, in + * the `signatureEncoding`. + * If a `signatureEncoding` is specified, the `signature` is expected to be a + * string; otherwise `signature` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * The `verify` object can not be used again after `verify.verify()` has been + * called. Multiple calls to `verify.verify()` will result in an error being + * thrown. + * + * Because public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.1.92 + */ + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: string, + signature_format?: BinaryToTextEncoding, + ): boolean; + } + /** + * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an + * optional specific `generator`. + * + * The `generator` argument can be a number, string, or `Buffer`. If `generator` is not specified, the value `2` is used. + * + * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise + * a `Buffer`, `TypedArray`, or `DataView` is expected. + * + * If `generatorEncoding` is specified, `generator` is expected to be a string; + * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected. + * @since v0.11.12 + * @param primeEncoding The `encoding` of the `prime` string. + * @param [generator=2] + * @param generatorEncoding The `encoding` of the `generator` string. + */ + function createDiffieHellman(primeLength: number, generator?: number): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + /** + * The `DiffieHellman` class is a utility for creating Diffie-Hellman key + * exchanges. + * + * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createDiffieHellman, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createDiffieHellman(2048); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * // OK + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * ``` + * @since v0.5.0 + */ + class DiffieHellman { + private constructor(); + /** + * Generates private and public Diffie-Hellman key values unless they have been + * generated or computed already, and returns + * the public key in the specified `encoding`. This key should be + * transferred to the other party. + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * This function is a thin wrapper around [`DH_generate_key()`](https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html). In particular, + * once a private key has been generated or set, calling this function only updates + * the public key but does not generate a new private key. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using the specified `inputEncoding`, and secret is + * encoded using specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned. + * @since v0.5.0 + * @param inputEncoding The `encoding` of an `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, inputEncoding?: null, outputEncoding?: null): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding?: null): Buffer; + computeSecret( + otherPublicKey: NodeJS.ArrayBufferView, + inputEncoding: null, + outputEncoding: BinaryToTextEncoding, + ): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * Returns the Diffie-Hellman prime in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrime(): Buffer; + getPrime(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman generator in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getGenerator(): Buffer; + getGenerator(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman public key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPublicKey(): Buffer; + getPublicKey(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman private key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * Sets the Diffie-Hellman public key. If the `encoding` argument is provided, `publicKey` is expected + * to be a string. If no `encoding` is provided, `publicKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `publicKey` string. + */ + setPublicKey(publicKey: NodeJS.ArrayBufferView): void; + setPublicKey(publicKey: string, encoding: BufferEncoding): void; + /** + * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected + * to be a string. If no `encoding` is provided, `privateKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * + * This function does not automatically compute the associated public key. Either `diffieHellman.setPublicKey()` or `diffieHellman.generateKeys()` can be + * used to manually provide the public key or to automatically derive it. + * @since v0.5.0 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BufferEncoding): void; + /** + * A bit field containing any warnings and/or errors resulting from a check + * performed during initialization of the `DiffieHellman` object. + * + * The following values are valid for this property (as defined in `node:constants` module): + * + * * `DH_CHECK_P_NOT_SAFE_PRIME` + * * `DH_CHECK_P_NOT_PRIME` + * * `DH_UNABLE_TO_CHECK_GENERATOR` + * * `DH_NOT_SUITABLE_GENERATOR` + * @since v0.11.12 + */ + verifyError: number; + } + /** + * The `DiffieHellmanGroup` class takes a well-known modp group as its argument. + * It works the same as `DiffieHellman`, except that it does not allow changing its keys after creation. + * In other words, it does not implement `setPublicKey()` or `setPrivateKey()` methods. + * + * ```js + * const { createDiffieHellmanGroup } = await import('node:crypto'); + * const dh = createDiffieHellmanGroup('modp1'); + * ``` + * The name (e.g. `'modp1'`) is taken from [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt) (modp1 and 2) and [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt): + * ```bash + * $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h + * modp1 # 768 bits + * modp2 # 1024 bits + * modp5 # 1536 bits + * modp14 # 2048 bits + * modp15 # etc. + * modp16 + * modp17 + * modp18 + * ``` + * @since v0.7.5 + */ + const DiffieHellmanGroup: DiffieHellmanGroupConstructor; + interface DiffieHellmanGroupConstructor { + new(name: string): DiffieHellmanGroup; + (name: string): DiffieHellmanGroup; + readonly prototype: DiffieHellmanGroup; + } + type DiffieHellmanGroup = Omit; + /** + * Creates a predefined `DiffieHellmanGroup` key exchange object. The + * supported groups are listed in the documentation for `DiffieHellmanGroup`. + * + * The returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * the keys (with `diffieHellman.setPublicKey()`, for example). The + * advantage of using this method is that the parties do not have to + * generate nor exchange a group modulus beforehand, saving both processor + * and communication time. + * + * Example (obtaining a shared secret): + * + * ```js + * const { + * getDiffieHellman, + * } = await import('node:crypto'); + * const alice = getDiffieHellman('modp14'); + * const bob = getDiffieHellman('modp14'); + * + * alice.generateKeys(); + * bob.generateKeys(); + * + * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); + * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); + * + * // aliceSecret and bobSecret should be the same + * console.log(aliceSecret === bobSecret); + * ``` + * @since v0.7.5 + */ + function getDiffieHellman(groupName: string): DiffieHellmanGroup; + /** + * An alias for {@link getDiffieHellman} + * @since v0.9.3 + */ + function createDiffieHellmanGroup(name: string): DiffieHellmanGroup; + /** + * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`. + * + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an error occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. By default, the successfully generated `derivedKey` will be passed to the callback as a `Buffer`. An error will be + * thrown if any of the input arguments specify invalid values or types. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2, + * } = await import('node:crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * @since v0.5.5 + */ + function pbkdf2( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + /** + * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`. + * + * If an error occurs an `Error` will be thrown, otherwise the derived key will be + * returned as a `Buffer`. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2Sync, + * } = await import('node:crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * @since v0.9.3 + */ + function pbkdf2Sync( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + ): Buffer; + /** + * Generates cryptographically strong pseudorandom data. The `size` argument + * is a number indicating the number of bytes to generate. + * + * If a `callback` function is provided, the bytes are generated asynchronously + * and the `callback` function is invoked with two arguments: `err` and `buf`. + * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The `buf` argument is a `Buffer` containing the generated bytes. + * + * ```js + * // Asynchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * randomBytes(256, (err, buf) => { + * if (err) throw err; + * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); + * }); + * ``` + * + * If the `callback` function is not provided, the random bytes are generated + * synchronously and returned as a `Buffer`. An error will be thrown if + * there is a problem generating the bytes. + * + * ```js + * // Synchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * const buf = randomBytes(256); + * console.log( + * `${buf.length} bytes of random data: ${buf.toString('hex')}`); + * ``` + * + * The `crypto.randomBytes()` method will not complete until there is + * sufficient entropy available. + * This should normally never take longer than a few milliseconds. The only time + * when generating the random bytes may conceivably block for a longer period of + * time is right after boot, when the whole system is still low on entropy. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomBytes()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomBytes` requests when doing so as part of fulfilling a client + * request. + * @since v0.5.8 + * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`. + * @return if the `callback` function is not provided. + */ + function randomBytes(size: number): Buffer; + function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + function pseudoRandomBytes(size: number): Buffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + /** + * Return a random integer `n` such that `min <= n < max`. This + * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). + * + * The range (`max - min`) must be less than 2**48. `min` and `max` must + * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + * + * If the `callback` function is not provided, the random integer is + * generated synchronously. + * + * ```js + * // Asynchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * randomInt(3, (err, n) => { + * if (err) throw err; + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * }); + * ``` + * + * ```js + * // Synchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(1, 7); + * console.log(`The dice rolled: ${n}`); + * ``` + * @since v14.10.0, v12.19.0 + * @param [min=0] Start of random range (inclusive). + * @param max End of random range (exclusive). + * @param callback `function(err, n) {}`. + */ + function randomInt(max: number): number; + function randomInt(min: number, max: number): number; + function randomInt(max: number, callback: (err: Error | null, value: number) => void): void; + function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void; + /** + * Synchronous version of {@link randomFill}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * console.log(randomFillSync(buf).toString('hex')); + * + * randomFillSync(buf, 5); + * console.log(buf.toString('hex')); + * + * // The above is equivalent to the following: + * randomFillSync(buf, 5, 5); + * console.log(buf.toString('hex')); + * ``` + * + * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * console.log(Buffer.from(randomFillSync(a).buffer, + * a.byteOffset, a.byteLength).toString('hex')); + * + * const b = new DataView(new ArrayBuffer(10)); + * console.log(Buffer.from(randomFillSync(b).buffer, + * b.byteOffset, b.byteLength).toString('hex')); + * + * const c = new ArrayBuffer(10); + * console.log(Buffer.from(randomFillSync(c)).toString('hex')); + * ``` + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @return The object passed as `buffer` argument. + */ + function randomFillSync(buffer: T, offset?: number, size?: number): T; + /** + * This function is similar to {@link randomBytes} but requires the first + * argument to be a `Buffer` that will be filled. It also + * requires that a callback is passed in. + * + * If the `callback` function is not provided, an error will be thrown. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * randomFill(buf, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * randomFill(buf, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * // The above is equivalent to the following: + * randomFill(buf, 5, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * ``` + * + * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as `buffer`. + * + * While this includes instances of `Float32Array` and `Float64Array`, this + * function should not be used to generate random floating-point numbers. The + * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array + * contains finite numbers only, they are not drawn from a uniform random + * distribution and have no meaningful lower or upper bounds. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * randomFill(a, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const b = new DataView(new ArrayBuffer(10)); + * randomFill(b, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const c = new ArrayBuffer(10); + * randomFill(c, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf).toString('hex')); + * }); + * ``` + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomFill()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomFill` requests when doing so as part of fulfilling a client + * request. + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @param callback `function(err, buf) {}`. + */ + function randomFill( + buffer: T, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + size: number, + callback: (err: Error | null, buf: T) => void, + ): void; + interface ScryptOptions { + cost?: number | undefined; + blockSize?: number | undefined; + parallelization?: number | undefined; + N?: number | undefined; + r?: number | undefined; + p?: number | undefined; + maxmem?: number | undefined; + } + /** + * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * The `callback` function is called with two arguments: `err` and `derivedKey`. `err` is an exception object when key derivation fails, otherwise `err` is `null`. `derivedKey` is passed to the + * callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scrypt, + * } = await import('node:crypto'); + * + * // Using the factory defaults. + * scrypt('password', 'salt', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * // Using a custom N parameter. Must be a power of two. + * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' + * }); + * ``` + * @since v10.5.0 + */ + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options: ScryptOptions, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + /** + * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scryptSync, + * } = await import('node:crypto'); + * // Using the factory defaults. + * + * const key1 = scryptSync('password', 'salt', 64); + * console.log(key1.toString('hex')); // '3745e48...08d59ae' + * // Using a custom N parameter. Must be a power of two. + * const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); + * console.log(key2.toString('hex')); // '3745e48...aa39b34' + * ``` + * @since v10.5.0 + */ + function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer; + interface RsaPublicKey { + key: KeyLike; + padding?: number | undefined; + } + interface RsaPrivateKey { + key: KeyLike; + passphrase?: string | undefined; + /** + * @default 'sha1' + */ + oaepHash?: string | undefined; + oaepLabel?: NodeJS.TypedArray | undefined; + padding?: number | undefined; + } + /** + * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using + * the corresponding private key, for example using {@link privateDecrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.11.14 + */ + function publicEncrypt( + key: RsaPublicKey | RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): Buffer; + /** + * Decrypts `buffer` with `key`.`buffer` was previously encrypted using + * the corresponding private key, for example using {@link privateEncrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v1.1.0 + */ + function publicDecrypt( + key: RsaPublicKey | RsaPrivateKey | KeyLike, + buffer: NodeJS.ArrayBufferView | string, + ): Buffer; + /** + * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using + * the corresponding public key, for example using {@link publicEncrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. + * @since v0.11.14 + */ + function privateDecrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView | string): Buffer; + /** + * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using + * the corresponding public key, for example using {@link publicDecrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. + * @since v1.1.0 + */ + function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView | string): Buffer; + /** + * ```js + * const { + * getCiphers, + * } = await import('node:crypto'); + * + * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] + * ``` + * @since v0.9.3 + * @return An array with the names of the supported cipher algorithms. + */ + function getCiphers(): string[]; + /** + * ```js + * const { + * getCurves, + * } = await import('node:crypto'); + * + * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] + * ``` + * @since v2.3.0 + * @return An array with the names of the supported elliptic curves. + */ + function getCurves(): string[]; + /** + * @since v10.0.0 + * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}. + */ + function getFips(): 1 | 0; + /** + * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. + * Throws an error if FIPS mode is not available. + * @since v10.0.0 + * @param bool `true` to enable FIPS mode. + */ + function setFips(bool: boolean): void; + /** + * ```js + * const { + * getHashes, + * } = await import('node:crypto'); + * + * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] + * ``` + * @since v0.9.3 + * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. + */ + function getHashes(): string[]; + /** + * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) + * key exchanges. + * + * Instances of the `ECDH` class can be created using the {@link createECDH} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createECDH, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createECDH('secp521r1'); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createECDH('secp521r1'); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * // OK + * ``` + * @since v0.11.14 + */ + class ECDH { + private constructor(); + /** + * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the + * format specified by `format`. The `format` argument specifies point encoding + * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is + * interpreted using the specified `inputEncoding`, and the returned key is encoded + * using the specified `outputEncoding`. + * + * Use {@link getCurves} to obtain a list of available curve names. + * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display + * the name and description of each available elliptic curve. + * + * If `format` is not specified the point will be returned in `'uncompressed'` format. + * + * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * Example (uncompressing a key): + * + * ```js + * const { + * createECDH, + * ECDH, + * } = await import('node:crypto'); + * + * const ecdh = createECDH('secp256k1'); + * ecdh.generateKeys(); + * + * const compressedKey = ecdh.getPublicKey('hex', 'compressed'); + * + * const uncompressedKey = ECDH.convertKey(compressedKey, + * 'secp256k1', + * 'hex', + * 'hex', + * 'uncompressed'); + * + * // The converted key and the uncompressed public key should be the same + * console.log(uncompressedKey === ecdh.getPublicKey('hex')); + * ``` + * @since v10.0.0 + * @param inputEncoding The `encoding` of the `key` string. + * @param outputEncoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + static convertKey( + key: BinaryLike, + curve: string, + inputEncoding?: BinaryToTextEncoding, + outputEncoding?: "latin1" | "hex" | "base64" | "base64url", + format?: "uncompressed" | "compressed" | "hybrid", + ): Buffer | string; + /** + * Generates private and public EC Diffie-Hellman key values, and returns + * the public key in the specified `format` and `encoding`. This key should be + * transferred to the other party. + * + * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. + * + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using specified `inputEncoding`, and the returned secret + * is encoded using the specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned. + * + * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey` lies outside of the elliptic curve. Since `otherPublicKey` is + * usually supplied from a remote user over an insecure network, + * be sure to handle this exception accordingly. + * @since v0.11.14 + * @param inputEncoding The `encoding` of the `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @return The EC Diffie-Hellman in the specified `encoding`. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. + * + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. + */ + getPublicKey(encoding?: null, format?: ECDHKeyFormat): Buffer; + getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Sets the EC Diffie-Hellman private key. + * If `encoding` is provided, `privateKey` is expected + * to be a string; otherwise `privateKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `privateKey` is not valid for the curve specified when the `ECDH` object was + * created, an error is thrown. Upon setting the private key, the associated + * public point (key) is also generated and set in the `ECDH` object. + * @since v0.11.14 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; + } + /** + * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a + * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent + * OpenSSL releases, `openssl ecparam -list_curves` will also display the name + * and description of each available elliptic curve. + * @since v0.11.14 + */ + function createECDH(curveName: string): ECDH; + /** + * This function compares the underlying bytes that represent the given `ArrayBuffer`, `TypedArray`, or `DataView` instances using a constant-time + * algorithm. + * + * This function does not leak timing information that + * would allow an attacker to guess one of the values. This is suitable for + * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/). + * + * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they + * must have the same byte length. An error is thrown if `a` and `b` have + * different byte lengths. + * + * If at least one of `a` and `b` is a `TypedArray` with more than one byte per + * entry, such as `Uint16Array`, the result will be computed using the platform + * byte order. + * + * **When both of the inputs are `Float32Array`s or `Float64Array`s, this function might return unexpected results due to IEEE 754** + * **encoding of floating-point numbers. In particular, neither `x === y` nor `Object.is(x, y)` implies that the byte representations of two floating-point** + * **numbers `x` and `y` are equal.** + * + * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code + * is timing-safe. Care should be taken to ensure that the surrounding code does + * not introduce timing vulnerabilities. + * @since v6.6.0 + */ + function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; + type KeyType = "rsa" | "rsa-pss" | "dsa" | "ec" | "ed25519" | "ed448" | "x25519" | "x448"; + type KeyFormat = "pem" | "der" | "jwk"; + interface BasePrivateKeyEncodingOptions { + format: T; + cipher?: string | undefined; + passphrase?: string | undefined; + } + interface KeyPairKeyObjectResult { + publicKey: KeyObject; + privateKey: KeyObject; + } + interface ED25519KeyPairKeyObjectOptions {} + interface ED448KeyPairKeyObjectOptions {} + interface X25519KeyPairKeyObjectOptions {} + interface X448KeyPairKeyObjectOptions {} + interface ECKeyPairKeyObjectOptions { + /** + * Name of the curve to use + */ + namedCurve: string; + /** + * Must be `'named'` or `'explicit'`. Default: `'named'`. + */ + paramEncoding?: "explicit" | "named" | undefined; + } + interface RSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + } + interface RSAPSSKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + } + interface DSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + } + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs1" | "pkcs8"; + }; + } + interface RSAPSSKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface ECKeyPairOptions extends ECKeyPairKeyObjectOptions { + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "sec1" | "pkcs8"; + }; + } + interface ED25519KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface ED448KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface X25519KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface X448KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * When encoding public keys, it is recommended to use `'spki'`. When encoding + * private keys, it is recommended to use `'pkcs8'` with a strong passphrase, + * and to keep the passphrase confidential. + * + * ```js + * const { + * generateKeyPairSync, + * } = await import('node:crypto'); + * + * const { + * publicKey, + * privateKey, + * } = generateKeyPairSync('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }); + * ``` + * + * The return value `{ publicKey, privateKey }` represents the generated key pair. + * When PEM encoding was selected, the respective key will be a string, otherwise + * it will be a buffer containing the data encoded as DER. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "rsa", options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "rsa-pss", options: RSAPSSKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "dsa", options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ec", options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ed25519", options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ed448", options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "x25519", options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "x448", options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * It is recommended to encode public keys as `'spki'` and private keys as `'pkcs8'` with encryption for long-term storage: + * + * ```js + * const { + * generateKeyPair, + * } = await import('node:crypto'); + * + * generateKeyPair('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }, (err, publicKey, privateKey) => { + * // Handle errors and use the generated key pair. + * }); + * ``` + * + * On completion, `callback` will be called with `err` set to `undefined` and `publicKey` / `privateKey` representing the generated key pair. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + namespace generateKeyPair { + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "rsa", options: RSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "dsa", options: DSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "ec", options: ECKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed25519", + options?: ED25519KeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "ed448", options?: ED448KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "x25519", + options?: X25519KeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "x448", options?: X448KeyPairKeyObjectOptions): Promise; + } + /** + * Calculates and returns the signature for `data` using the given private key and + * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is + * dependent upon the key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPrivateKey}. If it is an object, the following + * additional properties can be passed: + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + ): Buffer; + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + callback: (error: Error | null, data: Buffer) => void, + ): void; + /** + * Verifies the given signature for `data` using the given key and algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is dependent upon the + * key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPublicKey}. If it is an object, the following + * additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the `data`. + * + * Because public keys can be derived from private keys, a private key or a public + * key may be passed for `key`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + callback: (error: Error | null, result: boolean) => void, + ): void; + /** + * Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`. + * Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'` + * (for Diffie-Hellman), `'ec'`, `'x448'`, or `'x25519'` (for ECDH). + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v13.9.0, v12.17.0 + */ + function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer; + function diffieHellman( + options: { privateKey: KeyObject; publicKey: KeyObject }, + callback: (err: Error | null, secret: Buffer) => void, + ): void; + /** + * A utility for creating one-shot hash digests of data. It can be faster than the object-based `crypto.createHash()` when hashing a smaller amount of data + * (<= 5MB) that's readily available. If the data can be big or if it is streamed, it's still recommended to use `crypto.createHash()` instead. The `algorithm` + * is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. On recent releases + * of OpenSSL, `openssl list -digest-algorithms` will display the available digest algorithms. + * + * Example: + * + * ```js + * import crypto from 'node:crypto'; + * import { Buffer } from 'node:buffer'; + * + * // Hashing a string and return the result as a hex-encoded string. + * const string = 'Node.js'; + * // 10b3493287f831e81a438811a1ffba01f8cec4b7 + * console.log(crypto.hash('sha1', string)); + * + * // Encode a base64-encoded string into a Buffer, hash it and return + * // the result as a buffer. + * const base64 = 'Tm9kZS5qcw=='; + * // + * console.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer')); + * ``` + * @since v21.7.0, v20.12.0 + * @param data When `data` is a string, it will be encoded as UTF-8 before being hashed. If a different input encoding is desired for a string input, user + * could encode the string into a `TypedArray` using either `TextEncoder` or `Buffer.from()` and passing the encoded `TypedArray` into this API instead. + * @param [outputEncoding='hex'] [Encoding](https://nodejs.org/docs/latest-v24.x/api/buffer.html#buffers-and-character-encodings) used to encode the returned digest. + */ + function hash(algorithm: string, data: BinaryLike, outputEncoding?: BinaryToTextEncoding): string; + function hash(algorithm: string, data: BinaryLike, outputEncoding: "buffer"): Buffer; + function hash( + algorithm: string, + data: BinaryLike, + outputEncoding?: BinaryToTextEncoding | "buffer", + ): string | Buffer; + type CipherMode = "cbc" | "ccm" | "cfb" | "ctr" | "ecb" | "gcm" | "ocb" | "ofb" | "stream" | "wrap" | "xts"; + interface CipherInfoOptions { + /** + * A test key length. + */ + keyLength?: number | undefined; + /** + * A test IV length. + */ + ivLength?: number | undefined; + } + interface CipherInfo { + /** + * The name of the cipher. + */ + name: string; + /** + * The nid of the cipher. + */ + nid: number; + /** + * The block size of the cipher in bytes. + * This property is omitted when mode is 'stream'. + */ + blockSize?: number | undefined; + /** + * The expected or default initialization vector length in bytes. + * This property is omitted if the cipher does not use an initialization vector. + */ + ivLength?: number | undefined; + /** + * The expected or default key length in bytes. + */ + keyLength: number; + /** + * The cipher mode. + */ + mode: CipherMode; + } + /** + * Returns information about a given cipher. + * + * Some ciphers accept variable length keys and initialization vectors. By default, + * the `crypto.getCipherInfo()` method will return the default values for these + * ciphers. To test if a given key length or iv length is acceptable for given + * cipher, use the `keyLength` and `ivLength` options. If the given values are + * unacceptable, `undefined` will be returned. + * @since v15.0.0 + * @param nameOrNid The name or nid of the cipher to query. + */ + function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined; + /** + * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an errors occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. The successfully generated `derivedKey` will + * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any + * of the input arguments specify invalid values or types. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdf, + * } = await import('node:crypto'); + * + * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * }); + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdf( + digest: string, + irm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: ArrayBuffer) => void, + ): void; + /** + * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The + * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + * + * An error will be thrown if any of the input arguments specify invalid values or + * types, or if the derived key cannot be generated. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdfSync, + * } = await import('node:crypto'); + * + * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdfSync( + digest: string, + ikm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + ): ArrayBuffer; + interface SecureHeapUsage { + /** + * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag. + */ + total: number; + /** + * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag. + */ + min: number; + /** + * The total number of bytes currently allocated from the secure heap. + */ + used: number; + /** + * The calculated ratio of `used` to `total` allocated bytes. + */ + utilization: number; + } + /** + * @since v15.6.0 + */ + function secureHeapUsed(): SecureHeapUsage; + interface RandomUUIDOptions { + /** + * By default, to improve performance, + * Node.js will pre-emptively generate and persistently cache enough + * random data to generate up to 128 random UUIDs. To generate a UUID + * without using the cache, set `disableEntropyCache` to `true`. + * + * @default `false` + */ + disableEntropyCache?: boolean | undefined; + } + type UUID = `${string}-${string}-${string}-${string}-${string}`; + /** + * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a + * cryptographic pseudorandom number generator. + * @since v15.6.0, v14.17.0 + */ + function randomUUID(options?: RandomUUIDOptions): UUID; + interface X509CheckOptions { + /** + * @default 'always' + */ + subject?: "always" | "default" | "never"; + /** + * @default true + */ + wildcards?: boolean; + /** + * @default true + */ + partialWildcards?: boolean; + /** + * @default false + */ + multiLabelWildcards?: boolean; + /** + * @default false + */ + singleLabelSubdomains?: boolean; + } + /** + * Encapsulates an X509 certificate and provides read-only access to + * its information. + * + * ```js + * const { X509Certificate } = await import('node:crypto'); + * + * const x509 = new X509Certificate('{... pem encoded cert ...}'); + * + * console.log(x509.subject); + * ``` + * @since v15.6.0 + */ + class X509Certificate { + /** + * Will be \`true\` if this is a Certificate Authority (CA) certificate. + * @since v15.6.0 + */ + readonly ca: boolean; + /** + * The SHA-1 fingerprint of this certificate. + * + * Because SHA-1 is cryptographically broken and because the security of SHA-1 is + * significantly worse than that of algorithms that are commonly used to sign + * certificates, consider using `x509.fingerprint256` instead. + * @since v15.6.0 + */ + readonly fingerprint: string; + /** + * The SHA-256 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint256: string; + /** + * The SHA-512 fingerprint of this certificate. + * + * Because computing the SHA-256 fingerprint is usually faster and because it is + * only half the size of the SHA-512 fingerprint, `x509.fingerprint256` may be + * a better choice. While SHA-512 presumably provides a higher level of security in + * general, the security of SHA-256 matches that of most algorithms that are + * commonly used to sign certificates. + * @since v17.2.0, v16.14.0 + */ + readonly fingerprint512: string; + /** + * The complete subject of this certificate. + * @since v15.6.0 + */ + readonly subject: string; + /** + * The subject alternative name specified for this certificate. + * + * This is a comma-separated list of subject alternative names. Each entry begins + * with a string identifying the kind of the subject alternative name followed by + * a colon and the value associated with the entry. + * + * Earlier versions of Node.js incorrectly assumed that it is safe to split this + * property at the two-character sequence `', '` (see [CVE-2021-44532](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44532)). However, + * both malicious and legitimate certificates can contain subject alternative names + * that include this sequence when represented as a string. + * + * After the prefix denoting the type of the entry, the remainder of each entry + * might be enclosed in quotes to indicate that the value is a JSON string literal. + * For backward compatibility, Node.js only uses JSON string literals within this + * property when necessary to avoid ambiguity. Third-party code should be prepared + * to handle both possible entry formats. + * @since v15.6.0 + */ + readonly subjectAltName: string | undefined; + /** + * A textual representation of the certificate's authority information access + * extension. + * + * This is a line feed separated list of access descriptions. Each line begins with + * the access method and the kind of the access location, followed by a colon and + * the value associated with the access location. + * + * After the prefix denoting the access method and the kind of the access location, + * the remainder of each line might be enclosed in quotes to indicate that the + * value is a JSON string literal. For backward compatibility, Node.js only uses + * JSON string literals within this property when necessary to avoid ambiguity. + * Third-party code should be prepared to handle both possible entry formats. + * @since v15.6.0 + */ + readonly infoAccess: string | undefined; + /** + * An array detailing the key usages for this certificate. + * @since v15.6.0 + */ + readonly keyUsage: string[]; + /** + * The issuer identification included in this certificate. + * @since v15.6.0 + */ + readonly issuer: string; + /** + * The issuer certificate or `undefined` if the issuer certificate is not + * available. + * @since v15.9.0 + */ + readonly issuerCertificate?: X509Certificate | undefined; + /** + * The public key `KeyObject` for this certificate. + * @since v15.6.0 + */ + readonly publicKey: KeyObject; + /** + * A `Buffer` containing the DER encoding of this certificate. + * @since v15.6.0 + */ + readonly raw: Buffer; + /** + * The serial number of this certificate. + * + * Serial numbers are assigned by certificate authorities and do not uniquely + * identify certificates. Consider using `x509.fingerprint256` as a unique + * identifier instead. + * @since v15.6.0 + */ + readonly serialNumber: string; + /** + * The date/time from which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validFrom: string; + /** + * The date/time from which this certificate is valid, encapsulated in a `Date` object. + * @since v22.10.0 + */ + readonly validFromDate: Date; + /** + * The date/time until which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validTo: string; + /** + * The date/time until which this certificate is valid, encapsulated in a `Date` object. + * @since v22.10.0 + */ + readonly validToDate: Date; + constructor(buffer: BinaryLike); + /** + * Checks whether the certificate matches the given email address. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any email addresses. + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching email + * address, the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns `email` if the certificate matches, `undefined` if it does not. + */ + checkEmail(email: string, options?: Pick): string | undefined; + /** + * Checks whether the certificate matches the given host name. + * + * If the certificate matches the given host name, the matching subject name is + * returned. The returned name might be an exact match (e.g., `foo.example.com`) + * or it might contain wildcards (e.g., `*.example.com`). Because host name + * comparisons are case-insensitive, the returned subject name might also differ + * from the given `name` in capitalization. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any DNS names. This behavior is consistent with [RFC 2818](https://www.rfc-editor.org/rfc/rfc2818.txt) ("HTTP Over TLS"). + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching DNS name, + * the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns a subject name that matches `name`, or `undefined` if no subject name matches `name`. + */ + checkHost(name: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given IP address (IPv4 or IPv6). + * + * Only [RFC 5280](https://www.rfc-editor.org/rfc/rfc5280.txt) `iPAddress` subject alternative names are considered, and they + * must match the given `ip` address exactly. Other subject alternative names as + * well as the subject field of the certificate are ignored. + * @since v15.6.0 + * @return Returns `ip` if the certificate matches, `undefined` if it does not. + */ + checkIP(ip: string): string | undefined; + /** + * Checks whether this certificate was potentially issued by the given `otherCert` + * by comparing the certificate metadata. + * + * This is useful for pruning a list of possible issuer certificates which have been + * selected using a more rudimentary filtering routine, i.e. just based on subject + * and issuer names. + * + * Finally, to verify that this certificate's signature was produced by a private key + * corresponding to `otherCert`'s public key use `x509.verify(publicKey)` + * with `otherCert`'s public key represented as a `KeyObject` + * like so + * + * ```js + * if (!x509.verify(otherCert.publicKey)) { + * throw new Error('otherCert did not issue x509'); + * } + * ``` + * @since v15.6.0 + */ + checkIssued(otherCert: X509Certificate): boolean; + /** + * Checks whether the public key for this certificate is consistent with + * the given private key. + * @since v15.6.0 + * @param privateKey A private key. + */ + checkPrivateKey(privateKey: KeyObject): boolean; + /** + * There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded + * certificate. + * @since v15.6.0 + */ + toJSON(): string; + /** + * Returns information about this certificate using the legacy `certificate object` encoding. + * @since v15.6.0 + */ + toLegacyObject(): PeerCertificate; + /** + * Returns the PEM-encoded certificate. + * @since v15.6.0 + */ + toString(): string; + /** + * Verifies that this certificate was signed by the given public key. + * Does not perform any other validation checks on the certificate. + * @since v15.6.0 + * @param publicKey A public key. + */ + verify(publicKey: KeyObject): boolean; + } + type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint; + interface GeneratePrimeOptions { + add?: LargeNumberLike | undefined; + rem?: LargeNumberLike | undefined; + /** + * @default false + */ + safe?: boolean | undefined; + bigint?: boolean | undefined; + } + interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { + bigint: true; + } + interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { + bigint?: false | undefined; + } + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsBigInt, + callback: (err: Error | null, prime: bigint) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsArrayBuffer, + callback: (err: Error | null, prime: ArrayBuffer) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptions, + callback: (err: Error | null, prime: ArrayBuffer | bigint) => void, + ): void; + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrimeSync(size: number): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint; + interface CheckPrimeOptions { + /** + * The number of Miller-Rabin probabilistic primality iterations to perform. + * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most `2**-64` for random input. + * Care must be used when selecting a number of checks. + * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. + * + * @default 0 + */ + checks?: number | undefined; + } + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + */ + function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void; + function checkPrime( + value: LargeNumberLike, + options: CheckPrimeOptions, + callback: (err: Error | null, result: boolean) => void, + ): void; + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`. + */ + function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean; + /** + * Load and set the `engine` for some or all OpenSSL functions (selected by flags). + * + * `engine` could be either an id or a path to the engine's shared library. + * + * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags` is a bit field taking one of or a mix of the following flags (defined in `crypto.constants`): + * + * * `crypto.constants.ENGINE_METHOD_RSA` + * * `crypto.constants.ENGINE_METHOD_DSA` + * * `crypto.constants.ENGINE_METHOD_DH` + * * `crypto.constants.ENGINE_METHOD_RAND` + * * `crypto.constants.ENGINE_METHOD_EC` + * * `crypto.constants.ENGINE_METHOD_CIPHERS` + * * `crypto.constants.ENGINE_METHOD_DIGESTS` + * * `crypto.constants.ENGINE_METHOD_PKEY_METHS` + * * `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` + * * `crypto.constants.ENGINE_METHOD_ALL` + * * `crypto.constants.ENGINE_METHOD_NONE` + * @since v0.11.11 + * @param flags + */ + function setEngine(engine: string, flags?: number): void; + /** + * A convenient alias for {@link webcrypto.getRandomValues}. This + * implementation is not compliant with the Web Crypto spec, to write + * web-compatible code use {@link webcrypto.getRandomValues} instead. + * @since v17.4.0 + * @return Returns `typedArray`. + */ + function getRandomValues(typedArray: T): T; + /** + * A convenient alias for `crypto.webcrypto.subtle`. + * @since v17.4.0 + */ + const subtle: webcrypto.SubtleCrypto; + /** + * An implementation of the Web Crypto API standard. + * + * See the {@link https://nodejs.org/docs/latest/api/webcrypto.html Web Crypto API documentation} for details. + * @since v15.0.0 + */ + const webcrypto: webcrypto.Crypto; + namespace webcrypto { + type BufferSource = ArrayBufferView | ArrayBuffer; + type KeyFormat = "jwk" | "pkcs8" | "raw" | "spki"; + type KeyType = "private" | "public" | "secret"; + type KeyUsage = + | "decrypt" + | "deriveBits" + | "deriveKey" + | "encrypt" + | "sign" + | "unwrapKey" + | "verify" + | "wrapKey"; + type AlgorithmIdentifier = Algorithm | string; + type HashAlgorithmIdentifier = AlgorithmIdentifier; + type NamedCurve = string; + type BigInteger = Uint8Array; + interface AesCbcParams extends Algorithm { + iv: BufferSource; + } + interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; + } + interface AesDerivedKeyParams extends Algorithm { + length: number; + } + interface AesGcmParams extends Algorithm { + additionalData?: BufferSource; + iv: BufferSource; + tagLength?: number; + } + interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; + } + interface AesKeyGenParams extends Algorithm { + length: number; + } + interface Algorithm { + name: string; + } + interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: NamedCurve; + } + interface EcKeyGenParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcKeyImportParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; + } + interface EcdsaParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface Ed448Params extends Algorithm { + context?: BufferSource; + } + interface HkdfParams extends Algorithm { + hash: HashAlgorithmIdentifier; + info: BufferSource; + salt: BufferSource; + } + interface HmacImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; + } + interface HmacKeyGenParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; + } + interface KeyAlgorithm { + name: string; + } + interface Pbkdf2Params extends Algorithm { + hash: HashAlgorithmIdentifier; + iterations: number; + salt: BufferSource; + } + interface RsaHashedImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; + } + interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: HashAlgorithmIdentifier; + } + interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaOaepParams extends Algorithm { + label?: BufferSource; + } + interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; + } + interface RsaPssParams extends Algorithm { + saltLength: number; + } + /** + * Importing the `webcrypto` object (`import { webcrypto } from 'node:crypto'`) gives an instance of the `Crypto` class. + * `Crypto` is a singleton that provides access to the remainder of the crypto API. + * @since v15.0.0 + */ + interface Crypto { + /** + * Provides access to the `SubtleCrypto` API. + * @since v15.0.0 + */ + readonly subtle: SubtleCrypto; + /** + * Generates cryptographically strong random values. + * The given `typedArray` is filled with random values, and a reference to `typedArray` is returned. + * + * The given `typedArray` must be an integer-based instance of {@link NodeJS.TypedArray}, i.e. `Float32Array` and `Float64Array` are not accepted. + * + * An error will be thrown if the given `typedArray` is larger than 65,536 bytes. + * @since v15.0.0 + */ + getRandomValues>(typedArray: T): T; + /** + * Generates a random {@link https://www.rfc-editor.org/rfc/rfc4122.txt RFC 4122} version 4 UUID. + * The UUID is generated using a cryptographic pseudorandom number generator. + * @since v16.7.0 + */ + randomUUID(): UUID; + CryptoKey: CryptoKeyConstructor; + } + // This constructor throws ILLEGAL_CONSTRUCTOR so it should not be newable. + interface CryptoKeyConstructor { + /** Illegal constructor */ + (_: { readonly _: unique symbol }): never; // Allows instanceof to work but not be callable by the user. + readonly length: 0; + readonly name: "CryptoKey"; + readonly prototype: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface CryptoKey { + /** + * An object detailing the algorithm for which the key can be used along with additional algorithm-specific parameters. + * @since v15.0.0 + */ + readonly algorithm: KeyAlgorithm; + /** + * When `true`, the {@link CryptoKey} can be extracted using either `subtleCrypto.exportKey()` or `subtleCrypto.wrapKey()`. + * @since v15.0.0 + */ + readonly extractable: boolean; + /** + * A string identifying whether the key is a symmetric (`'secret'`) or asymmetric (`'private'` or `'public'`) key. + * @since v15.0.0 + */ + readonly type: KeyType; + /** + * An array of strings identifying the operations for which the key may be used. + * + * The possible usages are: + * - `'encrypt'` - The key may be used to encrypt data. + * - `'decrypt'` - The key may be used to decrypt data. + * - `'sign'` - The key may be used to generate digital signatures. + * - `'verify'` - The key may be used to verify digital signatures. + * - `'deriveKey'` - The key may be used to derive a new key. + * - `'deriveBits'` - The key may be used to derive bits. + * - `'wrapKey'` - The key may be used to wrap another key. + * - `'unwrapKey'` - The key may be used to unwrap another key. + * + * Valid key usages depend on the key algorithm (identified by `cryptokey.algorithm.name`). + * @since v15.0.0 + */ + readonly usages: KeyUsage[]; + } + /** + * The `CryptoKeyPair` is a simple dictionary object with `publicKey` and `privateKey` properties, representing an asymmetric key pair. + * @since v15.0.0 + */ + interface CryptoKeyPair { + /** + * A {@link CryptoKey} whose type will be `'private'`. + * @since v15.0.0 + */ + privateKey: CryptoKey; + /** + * A {@link CryptoKey} whose type will be `'public'`. + * @since v15.0.0 + */ + publicKey: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface SubtleCrypto { + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `key`, + * `subtle.decrypt()` attempts to decipher the provided `data`. If successful, + * the returned promise will be resolved with an `` containing the plaintext result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + decrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `baseKey`, + * `subtle.deriveBits()` attempts to generate `length` bits. + * The Node.js implementation requires that when `length` is a number it must be multiple of `8`. + * When `length` is `null` the maximum number of bits for a given algorithm is generated. This is allowed + * for the `'ECDH'`, `'X25519'`, and `'X448'` algorithms. + * If successful, the returned promise will be resolved with an `` containing the generated data. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @since v15.0.0 + */ + deriveBits( + algorithm: EcdhKeyDeriveParams, + baseKey: CryptoKey, + length?: number | null, + ): Promise; + deriveBits( + algorithm: EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + length: number, + ): Promise; + /** + * Using the method and parameters specified in `algorithm`, and the keying material provided by `baseKey`, + * `subtle.deriveKey()` attempts to generate a new ` based on the method and parameters in `derivedKeyAlgorithm`. + * + * Calling `subtle.deriveKey()` is equivalent to calling `subtle.deriveBits()` to generate raw keying material, + * then passing the result into the `subtle.importKey()` method using the `deriveKeyAlgorithm`, `extractable`, and `keyUsages` parameters as input. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + deriveKey( + algorithm: EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + derivedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams | AesDerivedKeyParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + /** + * Using the method identified by `algorithm`, `subtle.digest()` attempts to generate a digest of `data`. + * If successful, the returned promise is resolved with an `` containing the computed digest. + * + * If `algorithm` is provided as a ``, it must be one of: + * + * - `'SHA-1'` + * - `'SHA-256'` + * - `'SHA-384'` + * - `'SHA-512'` + * + * If `algorithm` is provided as an ``, it must have a `name` property whose value is one of the above. + * @since v15.0.0 + */ + digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise; + /** + * Using the method and parameters specified by `algorithm` and the keying material provided by `key`, + * `subtle.encrypt()` attempts to encipher `data`. If successful, + * the returned promise is resolved with an `` containing the encrypted result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + encrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * Exports the given key into the specified format, if supported. + * + * If the `` is not extractable, the returned promise will reject. + * + * When `format` is either `'pkcs8'` or `'spki'` and the export is successful, + * the returned promise will be resolved with an `` containing the exported key data. + * + * When `format` is `'jwk'` and the export is successful, the returned promise will be resolved with a + * JavaScript object conforming to the {@link https://tools.ietf.org/html/rfc7517 JSON Web Key} specification. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @returns `` containing ``. + * @since v15.0.0 + */ + exportKey(format: "jwk", key: CryptoKey): Promise; + exportKey(format: Exclude, key: CryptoKey): Promise; + /** + * Using the method and parameters provided in `algorithm`, + * `subtle.generateKey()` attempts to generate new keying material. + * Depending the method used, the method may generate either a single `` or a ``. + * + * The `` (public and private key) generating algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * The `` (secret key) generating algorithms supported include: + * + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + generateKey( + algorithm: RsaHashedKeyGenParams | EcKeyGenParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + generateKey( + algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + generateKey( + algorithm: AlgorithmIdentifier, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * The `subtle.importKey()` method attempts to interpret the provided `keyData` as the given `format` + * to create a `` instance using the provided `algorithm`, `extractable`, and `keyUsages` arguments. + * If the import is successful, the returned promise will be resolved with the created ``. + * + * If importing a `'PBKDF2'` key, `extractable` must be `false`. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + importKey( + format: "jwk", + keyData: JsonWebKey, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + importKey( + format: Exclude, + keyData: BufferSource, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters given by `algorithm` and the keying material provided by `key`, + * `subtle.sign()` attempts to generate a cryptographic signature of `data`. If successful, + * the returned promise is resolved with an `` containing the generated signature. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + sign( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.unwrapKey()` method attempts to decrypt a wrapped key and create a `` instance. + * It is equivalent to calling `subtle.decrypt()` first on the encrypted key data (using the `wrappedKey`, `unwrapAlgo`, and `unwrappingKey` arguments as input) + * then passing the results in to the `subtle.importKey()` method using the `unwrappedKeyAlgo`, `extractable`, and `keyUsages` arguments as inputs. + * If successful, the returned promise is resolved with a `` object. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * + * The unwrapped key algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + unwrapKey( + format: KeyFormat, + wrappedKey: BufferSource, + unwrappingKey: CryptoKey, + unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + unwrappedKeyAlgorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters given in `algorithm` and the keying material provided by `key`, + * `subtle.verify()` attempts to verify that `signature` is a valid cryptographic signature of `data`. + * The returned promise is resolved with either `true` or `false`. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + verify( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, + key: CryptoKey, + signature: BufferSource, + data: BufferSource, + ): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.wrapKey()` method exports the keying material into the format identified by `format`, + * then encrypts it using the method and parameters specified by `wrapAlgo` and the keying material provided by `wrappingKey`. + * It is the equivalent to calling `subtle.exportKey()` using `format` and `key` as the arguments, + * then passing the result to the `subtle.encrypt()` method using `wrappingKey` and `wrapAlgo` as inputs. + * If successful, the returned promise will be resolved with an `` containing the encrypted key data. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @since v15.0.0 + */ + wrapKey( + format: KeyFormat, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + ): Promise; + } + } + + global { + var crypto: typeof globalThis extends { + crypto: infer T; + onmessage: any; + } ? T + : webcrypto.Crypto; + } +} +declare module "node:crypto" { + export * from "crypto"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/dgram.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/dgram.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..35239f92cc6a49247b5415c0f5473b68f569ee5f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,599 @@ +/** + * The `node:dgram` module provides an implementation of UDP datagram sockets. + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/dgram.js) + */ +declare module "dgram" { + import { AddressInfo, BlockList } from "node:net"; + import * as dns from "node:dns"; + import { Abortable, EventEmitter } from "node:events"; + interface RemoteInfo { + address: string; + family: "IPv4" | "IPv6"; + port: number; + size: number; + } + interface BindOptions { + port?: number | undefined; + address?: string | undefined; + exclusive?: boolean | undefined; + fd?: number | undefined; + } + type SocketType = "udp4" | "udp6"; + interface SocketOptions extends Abortable { + type: SocketType; + reuseAddr?: boolean | undefined; + reusePort?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + recvBufferSize?: number | undefined; + sendBufferSize?: number | undefined; + lookup?: + | (( + hostname: string, + options: dns.LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ) => void) + | undefined; + receiveBlockList?: BlockList | undefined; + sendBlockList?: BlockList | undefined; + } + /** + * Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram + * messages. When `address` and `port` are not passed to `socket.bind()` the + * method will bind the socket to the "all interfaces" address on a random port + * (it does the right thing for both `udp4` and `udp6` sockets). The bound address + * and port can be retrieved using `socket.address().address` and `socket.address().port`. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.close()` on the socket: + * + * ```js + * const controller = new AbortController(); + * const { signal } = controller; + * const server = dgram.createSocket({ type: 'udp4', signal }); + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * // Later, when you want to close the server. + * controller.abort(); + * ``` + * @since v0.11.13 + * @param options Available options are: + * @param callback Attached as a listener for `'message'` events. Optional. + */ + function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + /** + * Encapsulates the datagram functionality. + * + * New instances of `dgram.Socket` are created using {@link createSocket}. + * The `new` keyword is not to be used to create `dgram.Socket` instances. + * @since v0.1.99 + */ + class Socket extends EventEmitter { + /** + * Tells the kernel to join a multicast group at the given `multicastAddress` and `multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the `multicastInterface` argument is not + * specified, the operating system will choose + * one interface and will add membership to it. To add membership to every + * available interface, call `addMembership` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * + * When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur: + * + * ```js + * import cluster from 'node:cluster'; + * import dgram from 'node:dgram'; + * + * if (cluster.isPrimary) { + * cluster.fork(); // Works ok. + * cluster.fork(); // Fails with EADDRINUSE. + * } else { + * const s = dgram.createSocket('udp4'); + * s.bind(1234, () => { + * s.addMembership('224.0.0.114'); + * }); + * } + * ``` + * @since v0.6.9 + */ + addMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * Returns an object containing the address information for a socket. + * For UDP sockets, this object will contain `address`, `family`, and `port` properties. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.99 + */ + address(): AddressInfo; + /** + * For UDP sockets, causes the `dgram.Socket` to listen for datagram + * messages on a named `port` and optional `address`. If `port` is not + * specified or is `0`, the operating system will attempt to bind to a + * random port. If `address` is not specified, the operating system will + * attempt to listen on all addresses. Once binding is complete, a `'listening'` event is emitted and the optional `callback` function is + * called. + * + * Specifying both a `'listening'` event listener and passing a `callback` to the `socket.bind()` method is not harmful but not very + * useful. + * + * A bound datagram socket keeps the Node.js process running to receive + * datagram messages. + * + * If binding fails, an `'error'` event is generated. In rare case (e.g. + * attempting to bind with a closed socket), an `Error` may be thrown. + * + * Example of a UDP server listening on port 41234: + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @since v0.1.99 + * @param callback with no parameters. Called when binding is complete. + */ + bind(port?: number, address?: string, callback?: () => void): this; + bind(port?: number, callback?: () => void): this; + bind(callback?: () => void): this; + bind(options: BindOptions, callback?: () => void): this; + /** + * Close the underlying socket and stop listening for data on it. If a callback is + * provided, it is added as a listener for the `'close'` event. + * @since v0.1.99 + * @param callback Called when the socket has been closed. + */ + close(callback?: () => void): this; + /** + * Associates the `dgram.Socket` to a remote address and port. Every + * message sent by this handle is automatically sent to that destination. Also, + * the socket will only receive messages from that remote peer. + * Trying to call `connect()` on an already connected socket will result + * in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not + * provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) + * will be used by default. Once the connection is complete, a `'connect'` event + * is emitted and the optional `callback` function is called. In case of failure, + * the `callback` is called or, failing this, an `'error'` event is emitted. + * @since v12.0.0 + * @param callback Called when the connection is completed or on error. + */ + connect(port: number, address?: string, callback?: () => void): void; + connect(port: number, callback: () => void): void; + /** + * A synchronous function that disassociates a connected `dgram.Socket` from + * its remote address. Trying to call `disconnect()` on an unbound or already + * disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception. + * @since v12.0.0 + */ + disconnect(): void; + /** + * Instructs the kernel to leave a multicast group at `multicastAddress` using the `IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the + * kernel when the socket is closed or the process terminates, so most apps will + * never have reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v0.6.9 + */ + dropMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_RCVBUF` socket receive buffer size in bytes. + */ + getRecvBufferSize(): number; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_SNDBUF` socket send buffer size in bytes. + */ + getSendBufferSize(): number; + /** + * @since v18.8.0, v16.19.0 + * @return Number of bytes queued for sending. + */ + getSendQueueSize(): number; + /** + * @since v18.8.0, v16.19.0 + * @return Number of send requests currently in the queue awaiting to be processed. + */ + getSendQueueCount(): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active. The `socket.ref()` method adds the socket back to the reference + * counting and restores the default behavior. + * + * Calling `socket.ref()` multiples times will have no additional effect. + * + * The `socket.ref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + ref(): this; + /** + * Returns an object containing the `address`, `family`, and `port` of the remote + * endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception + * if the socket is not connected. + * @since v12.0.0 + */ + remoteAddress(): AddressInfo; + /** + * Broadcasts a datagram on the socket. + * For connectionless sockets, the destination `port` and `address` must be + * specified. Connected sockets, on the other hand, will use their associated + * remote endpoint, so the `port` and `address` arguments must not be set. + * + * The `msg` argument contains the message to be sent. + * Depending on its type, different behavior can apply. If `msg` is a `Buffer`, + * any `TypedArray` or a `DataView`, + * the `offset` and `length` specify the offset within the `Buffer` where the + * message begins and the number of bytes in the message, respectively. + * If `msg` is a `String`, then it is automatically converted to a `Buffer` with `'utf8'` encoding. With messages that + * contain multi-byte characters, `offset` and `length` will be calculated with + * respect to `byte length` and not the character position. + * If `msg` is an array, `offset` and `length` must not be specified. + * + * The `address` argument is a string. If the value of `address` is a host name, + * DNS will be used to resolve the address of the host. If `address` is not + * provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) will be used by default. + * + * If the socket has not been previously bound with a call to `bind`, the socket + * is assigned a random port number and is bound to the "all interfaces" address + * (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) + * + * An optional `callback` function may be specified to as a way of reporting + * DNS errors or for determining when it is safe to reuse the `buf` object. + * DNS lookups delay the time to send for at least one tick of the + * Node.js event loop. + * + * The only way to know for sure that the datagram has been sent is by using a `callback`. If an error occurs and a `callback` is given, the error will be + * passed as the first argument to the `callback`. If a `callback` is not given, + * the error is emitted as an `'error'` event on the `socket` object. + * + * Offset and length are optional but both _must_ be set if either are used. + * They are supported only when the first argument is a `Buffer`, a `TypedArray`, + * or a `DataView`. + * + * This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket. + * + * Example of sending a UDP packet to a port on `localhost`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.send(message, 41234, 'localhost', (err) => { + * client.close(); + * }); + * ``` + * + * Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('Some '); + * const buf2 = Buffer.from('bytes'); + * const client = dgram.createSocket('udp4'); + * client.send([buf1, buf2], 41234, (err) => { + * client.close(); + * }); + * ``` + * + * Sending multiple buffers might be faster or slower depending on the + * application and operating system. Run benchmarks to + * determine the optimal strategy on a case-by-case basis. Generally speaking, + * however, sending multiple buffers is faster. + * + * Example of sending a UDP packet using a socket connected to a port on `localhost`: + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.connect(41234, 'localhost', (err) => { + * client.send(message, (err) => { + * client.close(); + * }); + * }); + * ``` + * @since v0.1.99 + * @param msg Message to be sent. + * @param offset Offset in the buffer where the message starts. + * @param length Number of bytes in the message. + * @param port Destination port. + * @param address Destination host name or IP address. + * @param callback Called when the message has been sent. + */ + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView | readonly any[], + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | NodeJS.ArrayBufferView, + offset: number, + length: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + /** + * Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP + * packets may be sent to a local interface's broadcast address. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.6.9 + */ + setBroadcast(flag: boolean): void; + /** + * _All references to scope in this section are referring to [IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC + * 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_ + * _with a scope index is written as `'IP%scope'` where scope is an interface name_ + * _or interface number._ + * + * Sets the default outgoing multicast interface of the socket to a chosen + * interface or back to system interface selection. The `multicastInterface` must + * be a valid string representation of an IP from the socket's family. + * + * For IPv4 sockets, this should be the IP configured for the desired physical + * interface. All packets sent to multicast on the socket will be sent on the + * interface determined by the most recent successful use of this call. + * + * For IPv6 sockets, `multicastInterface` should include a scope to indicate the + * interface as in the examples that follow. In IPv6, individual `send` calls can + * also use explicit scope in addresses, so only packets sent to a multicast + * address without specifying an explicit scope are affected by the most recent + * successful use of this call. + * + * This method throws `EBADF` if called on an unbound socket. + * + * #### Example: IPv6 outgoing multicast interface + * + * On most systems, where scope format uses the interface name: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%eth1'); + * }); + * ``` + * + * On Windows, where scope format uses an interface number: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%2'); + * }); + * ``` + * + * #### Example: IPv4 outgoing multicast interface + * + * All systems use an IP of the host on the desired physical interface: + * + * ```js + * const socket = dgram.createSocket('udp4'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('10.0.0.2'); + * }); + * ``` + * @since v8.6.0 + */ + setMulticastInterface(multicastInterface: string): void; + /** + * Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`, + * multicast packets will also be received on the local interface. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastLoopback(flag: boolean): boolean; + /** + * Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for + * "Time to Live", in this context it specifies the number of IP hops that a + * packet is allowed to travel through, specifically for multicast traffic. Each + * router or gateway that forwards a packet decrements the TTL. If the TTL is + * decremented to 0 by a router, it will not be forwarded. + * + * The `ttl` argument may be between 0 and 255\. The default on most systems is `1`. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastTTL(ttl: number): number; + /** + * Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setRecvBufferSize(size: number): void; + /** + * Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setSendBufferSize(size: number): void; + /** + * Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live", + * in this context it specifies the number of IP hops that a packet is allowed to + * travel through. Each router or gateway that forwards a packet decrements the + * TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. + * Changing TTL values is typically done for network probes or when multicasting. + * + * The `ttl` argument may be between 1 and 255\. The default on most systems + * is 64. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.101 + */ + setTTL(ttl: number): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active, allowing the process to exit even if the socket is still + * listening. + * + * Calling `socket.unref()` multiple times will have no additional effect. + * + * The `socket.unref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + unref(): this; + /** + * Tells the kernel to join a source-specific multicast channel at the given `sourceAddress` and `groupAddress`, using the `multicastInterface` with the `IP_ADD_SOURCE_MEMBERSHIP` socket + * option. If the `multicastInterface` argument + * is not specified, the operating system will choose one interface and will add + * membership to it. To add membership to every available interface, call `socket.addSourceSpecificMembership()` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * @since v13.1.0, v12.16.0 + */ + addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * Instructs the kernel to leave a source-specific multicast channel at the given `sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP` socket option. This method is + * automatically called by the kernel when the + * socket is closed or the process terminates, so most apps will never have + * reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v13.1.0, v12.16.0 + */ + dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. error + * 4. listening + * 5. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: Buffer, rinfo: RemoteInfo): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + /** + * Calls `socket.close()` and returns a promise that fulfills when the socket has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } +} +declare module "node:dgram" { + export * from "dgram"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/diagnostics_channel.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/diagnostics_channel.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fa5ed691b04d838aa063d42d5e72cb77dc762214 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/diagnostics_channel.d.ts @@ -0,0 +1,578 @@ +/** + * The `node:diagnostics_channel` module provides an API to create named channels + * to report arbitrary message data for diagnostics purposes. + * + * It can be accessed using: + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * ``` + * + * It is intended that a module writer wanting to report diagnostics messages + * will create one or many top-level channels to report messages through. + * Channels may also be acquired at runtime but it is not encouraged + * due to the additional overhead of doing so. Channels may be exported for + * convenience, but as long as the name is known it can be acquired anywhere. + * + * If you intend for your module to produce diagnostics data for others to + * consume it is recommended that you include documentation of what named + * channels are used along with the shape of the message data. Channel names + * should generally include the module name to avoid collisions with data from + * other modules. + * @since v15.1.0, v14.17.0 + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/diagnostics_channel.js) + */ +declare module "diagnostics_channel" { + import { AsyncLocalStorage } from "node:async_hooks"; + /** + * Check if there are active subscribers to the named channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * if (diagnostics_channel.hasSubscribers('my-channel')) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return If there are active subscribers + */ + function hasSubscribers(name: string | symbol): boolean; + /** + * This is the primary entry-point for anyone wanting to publish to a named + * channel. It produces a channel object which is optimized to reduce overhead at + * publish time as much as possible. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return The named channel object + */ + function channel(name: string | symbol): Channel; + type ChannelListener = (message: unknown, name: string | symbol) => void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * diagnostics_channel.subscribe('my-channel', (message, name) => { + * // Received data + * }); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The handler to receive channel messages + */ + function subscribe(name: string | symbol, onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with {@link subscribe}. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * function onMessage(message, name) { + * // Received data + * } + * + * diagnostics_channel.subscribe('my-channel', onMessage); + * + * diagnostics_channel.unsubscribe('my-channel', onMessage); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean; + /** + * Creates a `TracingChannel` wrapper for the given `TracingChannel Channels`. If a name is given, the corresponding tracing + * channels will be created in the form of `tracing:${name}:${eventType}` where `eventType` corresponds to the types of `TracingChannel Channels`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channelsByName = diagnostics_channel.tracingChannel('my-channel'); + * + * // or... + * + * const channelsByCollection = diagnostics_channel.tracingChannel({ + * start: diagnostics_channel.channel('tracing:my-channel:start'), + * end: diagnostics_channel.channel('tracing:my-channel:end'), + * asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'), + * asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'), + * error: diagnostics_channel.channel('tracing:my-channel:error'), + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param nameOrChannels Channel name or object containing all the `TracingChannel Channels` + * @return Collection of channels to trace with + */ + function tracingChannel< + StoreType = unknown, + ContextType extends object = StoreType extends object ? StoreType : object, + >( + nameOrChannels: string | TracingChannelCollection, + ): TracingChannel; + /** + * The class `Channel` represents an individual named channel within the data + * pipeline. It is used to track subscribers and to publish messages when there + * are subscribers present. It exists as a separate object to avoid channel + * lookups at publish time, enabling very fast publish speeds and allowing + * for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly + * with `new Channel(name)` is not supported. + * @since v15.1.0, v14.17.0 + */ + class Channel { + readonly name: string | symbol; + /** + * Check if there are active subscribers to this channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * if (channel.hasSubscribers) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + */ + readonly hasSubscribers: boolean; + private constructor(name: string | symbol); + /** + * Publish a message to any subscribers to the channel. This will trigger + * message handlers synchronously so they will execute within the same context. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.publish({ + * some: 'message', + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param message The message to send to the channel subscribers + */ + publish(message: unknown): void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link subscribe(name, onMessage)} + * @param onMessage The handler to receive channel messages + */ + subscribe(onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * function onMessage(message, name) { + * // Received data + * } + * + * channel.subscribe(onMessage); + * + * channel.unsubscribe(onMessage); + * ``` + * @since v15.1.0, v14.17.0 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link unsubscribe(name, onMessage)} + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + unsubscribe(onMessage: ChannelListener): void; + /** + * When `channel.runStores(context, ...)` is called, the given context data + * will be applied to any store bound to the channel. If the store has already been + * bound the previous `transform` function will be replaced with the new one. + * The `transform` function may be omitted to set the given context data as the + * context directly. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store, (data) => { + * return { data }; + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param store The store to which to bind the context data + * @param transform Transform context data before setting the store context + */ + bindStore(store: AsyncLocalStorage, transform?: (context: ContextType) => StoreType): void; + /** + * Remove a message handler previously registered to this channel with `channel.bindStore(store)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store); + * channel.unbindStore(store); + * ``` + * @since v19.9.0 + * @experimental + * @param store The store to unbind from the channel. + * @return `true` if the store was found, `false` otherwise. + */ + unbindStore(store: AsyncLocalStorage): boolean; + /** + * Applies the given data to any AsyncLocalStorage instances bound to the channel + * for the duration of the given function, then publishes to the channel within + * the scope of that data is applied to the stores. + * + * If a transform function was given to `channel.bindStore(store)` it will be + * applied to transform the message data before it becomes the context value for + * the store. The prior storage context is accessible from within the transform + * function in cases where context linking is required. + * + * The context applied to the store should be accessible in any async code which + * continues from execution which began during the given function, however + * there are some situations in which `context loss` may occur. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store, (message) => { + * const parent = store.getStore(); + * return new Span(message, parent); + * }); + * channel.runStores({ some: 'message' }, () => { + * store.getStore(); // Span({ some: 'message' }) + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param context Message to send to subscribers and bind to stores + * @param fn Handler to run within the entered storage context + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runStores( + context: ContextType, + fn: (this: ThisArg, ...args: Args) => Result, + thisArg?: ThisArg, + ...args: Args + ): Result; + } + interface TracingChannelSubscribers { + start: (message: ContextType) => void; + end: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + asyncStart: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + asyncEnd: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + error: ( + message: ContextType & { + error: unknown; + }, + ) => void; + } + interface TracingChannelCollection { + start: Channel; + end: Channel; + asyncStart: Channel; + asyncEnd: Channel; + error: Channel; + } + /** + * The class `TracingChannel` is a collection of `TracingChannel Channels` which + * together express a single traceable action. It is used to formalize and + * simplify the process of producing events for tracing application flow. {@link tracingChannel} is used to construct a `TracingChannel`. As with `Channel` it is recommended to create and reuse a + * single `TracingChannel` at the top-level of the file rather than creating them + * dynamically. + * @since v19.9.0 + * @experimental + */ + class TracingChannel implements TracingChannelCollection { + start: Channel; + end: Channel; + asyncStart: Channel; + asyncEnd: Channel; + error: Channel; + /** + * Helper to subscribe a collection of functions to the corresponding channels. + * This is the same as calling `channel.subscribe(onMessage)` on each channel + * individually. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.subscribe({ + * start(message) { + * // Handle start message + * }, + * end(message) { + * // Handle end message + * }, + * asyncStart(message) { + * // Handle asyncStart message + * }, + * asyncEnd(message) { + * // Handle asyncEnd message + * }, + * error(message) { + * // Handle error message + * }, + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param subscribers Set of `TracingChannel Channels` subscribers + */ + subscribe(subscribers: TracingChannelSubscribers): void; + /** + * Helper to unsubscribe a collection of functions from the corresponding channels. + * This is the same as calling `channel.unsubscribe(onMessage)` on each channel + * individually. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.unsubscribe({ + * start(message) { + * // Handle start message + * }, + * end(message) { + * // Handle end message + * }, + * asyncStart(message) { + * // Handle asyncStart message + * }, + * asyncEnd(message) { + * // Handle asyncEnd message + * }, + * error(message) { + * // Handle error message + * }, + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param subscribers Set of `TracingChannel Channels` subscribers + * @return `true` if all handlers were successfully unsubscribed, and `false` otherwise. + */ + unsubscribe(subscribers: TracingChannelSubscribers): void; + /** + * Trace a synchronous function call. This will always produce a `start event` and `end event` around the execution and may produce an `error event` if the given function throws an error. + * This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceSync(() => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn Function to wrap a trace around + * @param context Shared object to correlate events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return The return value of the given function + */ + traceSync( + fn: (this: ThisArg, ...args: Args) => Result, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Result; + /** + * Trace a promise-returning function call. This will always produce a `start event` and `end event` around the synchronous portion of the + * function execution, and will produce an `asyncStart event` and `asyncEnd event` when a promise continuation is reached. It may also + * produce an `error event` if the given function throws an error or the + * returned promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.tracePromise(async () => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn Promise-returning function to wrap a trace around + * @param context Shared object to correlate trace events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return Chained from promise returned by the given function + */ + tracePromise( + fn: (this: ThisArg, ...args: Args) => Promise, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Promise; + /** + * Trace a callback-receiving function call. This will always produce a `start event` and `end event` around the synchronous portion of the + * function execution, and will produce a `asyncStart event` and `asyncEnd event` around the callback execution. It may also produce an `error event` if the given function throws an error or + * the returned + * promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * The `position` will be -1 by default to indicate the final argument should + * be used as the callback. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceCallback((arg1, callback) => { + * // Do something + * callback(null, 'result'); + * }, 1, { + * some: 'thing', + * }, thisArg, arg1, callback); + * ``` + * + * The callback will also be run with `channel.runStores(context, ...)` which + * enables context loss recovery in some cases. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * const myStore = new AsyncLocalStorage(); + * + * // The start channel sets the initial store data to something + * // and stores that store data value on the trace context object + * channels.start.bindStore(myStore, (data) => { + * const span = new Span(data); + * data.span = span; + * return span; + * }); + * + * // Then asyncStart can restore from that data it stored previously + * channels.asyncStart.bindStore(myStore, (data) => { + * return data.span; + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn callback using function to wrap a trace around + * @param position Zero-indexed argument position of expected callback + * @param context Shared object to correlate trace events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return The return value of the given function + */ + traceCallback( + fn: (this: ThisArg, ...args: Args) => Result, + position?: number, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): Result; + /** + * `true` if any of the individual channels has a subscriber, `false` if not. + * + * This is a helper method available on a {@link TracingChannel} instance to check + * if any of the [TracingChannel Channels](https://nodejs.org/api/diagnostics_channel.html#tracingchannel-channels) have subscribers. + * A `true` is returned if any of them have at least one subscriber, a `false` is returned otherwise. + * + * ```js + * const diagnostics_channel = require('node:diagnostics_channel'); + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * if (channels.hasSubscribers) { + * // Do something + * } + * ``` + * @since v22.0.0, v20.13.0 + */ + readonly hasSubscribers: boolean; + } +} +declare module "node:diagnostics_channel" { + export * from "diagnostics_channel"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/dns.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/dns.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f7539fd349c9777f4fd4c1f8e53b47cf981d73ba --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/dns.d.ts @@ -0,0 +1,918 @@ +/** + * The `node:dns` module enables name resolution. For example, use it to look up IP + * addresses of host names. + * + * Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the + * DNS protocol for lookups. {@link lookup} uses the operating system + * facilities to perform name resolution. It may not need to perform any network + * communication. To perform name resolution the way other applications on the same + * system do, use {@link lookup}. + * + * ```js + * import dns from 'node:dns'; + * + * dns.lookup('example.org', (err, address, family) => { + * console.log('address: %j family: IPv%s', address, family); + * }); + * // address: "93.184.216.34" family: IPv4 + * ``` + * + * All other functions in the `node:dns` module connect to an actual DNS server to + * perform name resolution. They will always use the network to perform DNS + * queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform + * DNS queries, bypassing other name-resolution facilities. + * + * ```js + * import dns from 'node:dns'; + * + * dns.resolve4('archive.org', (err, addresses) => { + * if (err) throw err; + * + * console.log(`addresses: ${JSON.stringify(addresses)}`); + * + * addresses.forEach((a) => { + * dns.reverse(a, (err, hostnames) => { + * if (err) { + * throw err; + * } + * console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); + * }); + * }); + * }); + * ``` + * + * See the [Implementation considerations section](https://nodejs.org/docs/latest-v24.x/api/dns.html#implementation-considerations) for more information. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/dns.js) + */ +declare module "dns" { + import * as dnsPromises from "node:dns/promises"; + // Supported getaddrinfo flags. + /** + * Limits returned address types to the types of non-loopback addresses configured on the system. For example, IPv4 addresses are + * only returned if the current system has at least one IPv4 address configured. + */ + export const ADDRCONFIG: number; + /** + * If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses. It is not supported + * on some operating systems (e.g. FreeBSD 10.1). + */ + export const V4MAPPED: number; + /** + * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as + * well as IPv4 mapped IPv6 addresses. + */ + export const ALL: number; + export interface LookupOptions { + /** + * The record family. Must be `4`, `6`, or `0`. For backward compatibility reasons, `'IPv4'` and `'IPv6'` are interpreted + * as `4` and `6` respectively. The value 0 indicates that either an IPv4 or IPv6 address is returned. If the value `0` is used + * with `{ all: true } (see below)`, both IPv4 and IPv6 addresses are returned. + * @default 0 + */ + family?: number | "IPv4" | "IPv6" | undefined; + /** + * One or more [supported `getaddrinfo`](https://nodejs.org/docs/latest-v24.x/api/dns.html#supported-getaddrinfo-flags) flags. Multiple flags may be + * passed by bitwise `OR`ing their values. + */ + hints?: number | undefined; + /** + * When `true`, the callback returns all resolved addresses in an array. Otherwise, returns a single address. + * @default false + */ + all?: boolean | undefined; + /** + * When `verbatim`, the resolved addresses are return unsorted. When `ipv4first`, the resolved addresses are sorted + * by placing IPv4 addresses before IPv6 addresses. When `ipv6first`, the resolved addresses are sorted by placing IPv6 + * addresses before IPv4 addresses. Default value is configurable using + * {@link setDefaultResultOrder} or [`--dns-result-order`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--dns-result-orderorder). + * @default `verbatim` (addresses are not reordered) + * @since v22.1.0 + */ + order?: "ipv4first" | "ipv6first" | "verbatim" | undefined; + /** + * When `true`, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 + * addresses are placed before IPv6 addresses. This option will be deprecated in favor of `order`. When both are specified, + * `order` has higher precedence. New code should only use `order`. Default value is configurable using {@link setDefaultResultOrder} + * @default true (addresses are not reordered) + * @deprecated Please use `order` option + */ + verbatim?: boolean | undefined; + } + export interface LookupOneOptions extends LookupOptions { + all?: false | undefined; + } + export interface LookupAllOptions extends LookupOptions { + all: true; + } + export interface LookupAddress { + /** + * A string representation of an IPv4 or IPv6 address. + */ + address: string; + /** + * `4` or `6`, denoting the family of `address`, or `0` if the address is not an IPv4 or IPv6 address. `0` is a likely indicator of a + * bug in the name resolution service used by the operating system. + */ + family: number; + } + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is `0` or not provided, then + * IPv4 and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the arguments for `callback` change to `(err, addresses)`, with `addresses` being an array of objects with the + * properties `address` and `family`. + * + * On error, `err` is an `Error` object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dns.lookup()` does not necessarily have anything to do with the DNS protocol. + * The implementation uses an operating system facility that can associate names + * with addresses and vice versa. This implementation can have subtle but + * important consequences on the behavior of any Node.js program. Please take some + * time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v24.x/api/dns.html#implementation-considerations) + * before using `dns.lookup()`. + * + * Example usage: + * + * ```js + * import dns from 'node:dns'; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * dns.lookup('example.com', options, (err, address, family) => + * console.log('address: %j family: IPv%s', address, family)); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dns.lookup('example.com', options, (err, addresses) => + * console.log('addresses: %j', addresses)); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * ``` + * + * If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v24.x/api/util.html#utilpromisifyoriginal) ed + * version, and `all` is not set to `true`, it returns a `Promise` for an `Object` with `address` and `family` properties. + * @since v0.1.90 + */ + export function lookup( + hostname: string, + family: number, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export function lookup( + hostname: string, + options: LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export function lookup( + hostname: string, + options: LookupAllOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void, + ): void; + export function lookup( + hostname: string, + options: LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void, + ): void; + export function lookup( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise; + function __promisify__(hostname: string, options: LookupOptions): Promise; + } + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown. + * + * On an error, `err` is an [`Error`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) object, + * where `err.code` is the error code. + * + * ```js + * import dns from 'node:dns'; + * dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { + * console.log(hostname, service); + * // Prints: localhost ssh + * }); + * ``` + * + * If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v24.x/api/util.html#utilpromisifyoriginal) ed + * version, it returns a `Promise` for an `Object` with `hostname` and `service` properties. + * @since v0.11.14 + */ + export function lookupService( + address: string, + port: number, + callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void, + ): void; + export namespace lookupService { + function __promisify__( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + } + export interface ResolveOptions { + ttl: boolean; + } + export interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + export interface RecordWithTtl { + address: string; + ttl: number; + } + /** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */ + export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + export interface AnyARecord extends RecordWithTtl { + type: "A"; + } + export interface AnyAaaaRecord extends RecordWithTtl { + type: "AAAA"; + } + export interface CaaRecord { + critical: number; + issue?: string | undefined; + issuewild?: string | undefined; + iodef?: string | undefined; + contactemail?: string | undefined; + contactphone?: string | undefined; + } + export interface AnyCaaRecord extends CaaRecord { + type: "CAA"; + } + export interface MxRecord { + priority: number; + exchange: string; + } + export interface AnyMxRecord extends MxRecord { + type: "MX"; + } + export interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + export interface AnyNaptrRecord extends NaptrRecord { + type: "NAPTR"; + } + export interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + export interface AnySoaRecord extends SoaRecord { + type: "SOA"; + } + export interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + export interface AnySrvRecord extends SrvRecord { + type: "SRV"; + } + export interface TlsaRecord { + certUsage: number; + selector: number; + match: number; + data: ArrayBuffer; + } + export interface AnyTlsaRecord extends TlsaRecord { + type: "TLSA"; + } + export interface AnyTxtRecord { + type: "TXT"; + entries: string[]; + } + export interface AnyNsRecord { + type: "NS"; + value: string; + } + export interface AnyPtrRecord { + type: "PTR"; + value: string; + } + export interface AnyCnameRecord { + type: "CNAME"; + value: string; + } + export type AnyRecord = + | AnyARecord + | AnyAaaaRecord + | AnyCaaRecord + | AnyCnameRecord + | AnyMxRecord + | AnyNaptrRecord + | AnyNsRecord + | AnyPtrRecord + | AnySoaRecord + | AnySrvRecord + | AnyTlsaRecord + | AnyTxtRecord; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. The `callback` function has arguments `(err, records)`. When successful, `records` will be an array of resource + * records. The type and structure of individual results varies based on `rrtype`: + * + * + * + * On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) object, + * where `err.code` is one of the `DNS error codes`. + * @since v0.1.27 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + export function resolve( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "A" | "AAAA" | "CNAME" | "NS" | "PTR", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "ANY", + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "CAA", + callback: (err: NodeJS.ErrnoException | null, address: CaaRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "MX", + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "NAPTR", + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "SOA", + callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "SRV", + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "TLSA", + callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "TXT", + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: string, + callback: ( + err: NodeJS.ErrnoException | null, + addresses: + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord + | SrvRecord[] + | TlsaRecord[] + | string[][] + | AnyRecord[], + ) => void, + ): void; + export namespace resolve { + function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function __promisify__(hostname: string, rrtype: "ANY"): Promise; + function __promisify__(hostname: string, rrtype: "CAA"): Promise; + function __promisify__(hostname: string, rrtype: "MX"): Promise; + function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; + function __promisify__(hostname: string, rrtype: "SOA"): Promise; + function __promisify__(hostname: string, rrtype: "SRV"): Promise; + function __promisify__(hostname: string, rrtype: "TLSA"): Promise; + function __promisify__(hostname: string, rrtype: "TXT"): Promise; + function __promisify__( + hostname: string, + rrtype: string, + ): Promise< + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord + | SrvRecord[] + | TlsaRecord[] + | string[][] + | AnyRecord[] + >; + } + /** + * Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve4( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve4( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + export function resolve4( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + export namespace resolve4 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv6 addresses. + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve6( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve6( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + export function resolve6( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + export namespace resolve6 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of canonical name records available for the `hostname` (e.g. `['bar.example.com']`). + * @since v0.3.2 + */ + export function resolveCname( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolveCname { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of certification authority authorization records + * available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + export function resolveCaa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void, + ): void; + export namespace resolveCaa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of objects containing both a `priority` and `exchange` property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v0.1.27 + */ + export function resolveMx( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + export namespace resolveMx { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will contain an array of + * objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v0.9.12 + */ + export function resolveNaptr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + export namespace resolveNaptr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of name server records available for `hostname` (e.g. `['ns1.example.com', 'ns2.example.com']`). + * @since v0.1.90 + */ + export function resolveNs( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolveNs { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * be an array of strings containing the reply records. + * @since v6.0.0 + */ + export function resolvePtr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolvePtr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. The `address` argument passed to the `callback` function will + * be an object with the following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v0.11.10 + */ + export function resolveSoa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void, + ): void; + export namespace resolveSoa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * be an array of objects with the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v0.1.27 + */ + export function resolveSrv( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + export namespace resolveSrv { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve certificate associations (`TLSA` records) for + * the `hostname`. The `records` argument passed to the `callback` function is an + * array of objects with these properties: + * + * * `certUsage` + * * `selector` + * * `match` + * * `data` + * + * ```js + * { + * certUsage: 3, + * selector: 1, + * match: 1, + * data: [ArrayBuffer] + * } + * ``` + * @since v23.9.0, v22.15.0 + */ + export function resolveTlsa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void, + ): void; + export namespace resolveTlsa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. The `records` argument passed to the `callback` function is a + * two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v0.1.27 + */ + export function resolveTxt( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + export namespace resolveTxt { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * The `ret` argument passed to the `callback` function will be an array containing + * various types of records. Each object has a property `type` that indicates the + * type of the current record. And depending on the `type`, additional properties + * will be present on the object: + * + * + * + * Here is an example of the `ret` object passed to the callback: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * + * DNS server operators may choose not to respond to `ANY` queries. It may be better to call individual methods like {@link resolve4}, {@link resolveMx}, and so on. For more details, see + * [RFC 8482](https://tools.ietf.org/html/rfc8482). + */ + export function resolveAny( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + export namespace resolveAny { + function __promisify__(hostname: string): Promise; + } + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-error) object, where `err.code` is + * one of the [DNS error codes](https://nodejs.org/docs/latest-v24.x/api/dns.html#error-codes). + * @since v0.1.16 + */ + export function reverse( + ip: string, + callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void, + ): void; + /** + * Get the default value for `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v24.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: for `order` defaulting to `ipv4first`. + * * `ipv6first`: for `order` defaulting to `ipv6first`. + * * `verbatim`: for `order` defaulting to `verbatim`. + * @since v18.17.0 + */ + export function getDefaultResultOrder(): "ipv4first" | "ipv6first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dns.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dns.setServers()` method must not be called while a DNS query is in + * progress. + * + * The {@link setServers} method affects only {@link resolve}, `dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}). + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v0.11.3 + * @param servers array of [RFC 5952](https://datatracker.ietf.org/doc/html/rfc5952#section-6) formatted addresses + */ + export function setServers(servers: readonly string[]): void; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v0.11.3 + */ + export function getServers(): string[]; + /** + * Set the default value of `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v24.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: sets default `order` to `ipv4first`. + * * `ipv6first`: sets default `order` to `ipv6first`. + * * `verbatim`: sets default `order` to `verbatim`. + * + * The default is `verbatim` and {@link setDefaultResultOrder} have higher + * priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--dns-result-orderorder). When using + * [worker threads](https://nodejs.org/docs/latest-v24.x/api/worker_threads.html), {@link setDefaultResultOrder} from the main + * thread won't affect the default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`. + */ + export function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void; + // Error codes + export const NODATA: "ENODATA"; + export const FORMERR: "EFORMERR"; + export const SERVFAIL: "ESERVFAIL"; + export const NOTFOUND: "ENOTFOUND"; + export const NOTIMP: "ENOTIMP"; + export const REFUSED: "EREFUSED"; + export const BADQUERY: "EBADQUERY"; + export const BADNAME: "EBADNAME"; + export const BADFAMILY: "EBADFAMILY"; + export const BADRESP: "EBADRESP"; + export const CONNREFUSED: "ECONNREFUSED"; + export const TIMEOUT: "ETIMEOUT"; + export const EOF: "EOF"; + export const FILE: "EFILE"; + export const NOMEM: "ENOMEM"; + export const DESTRUCTION: "EDESTRUCTION"; + export const BADSTR: "EBADSTR"; + export const BADFLAGS: "EBADFLAGS"; + export const NONAME: "ENONAME"; + export const BADHINTS: "EBADHINTS"; + export const NOTINITIALIZED: "ENOTINITIALIZED"; + export const LOADIPHLPAPI: "ELOADIPHLPAPI"; + export const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS"; + export const CANCELLED: "ECANCELLED"; + export interface ResolverOptions { + /** + * Query timeout in milliseconds, or `-1` to use the default timeout. + */ + timeout?: number | undefined; + /** + * The number of tries the resolver will try contacting each name server before giving up. + * @default 4 + */ + tries?: number; + } + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v24.x/api/dns.html#dnssetserversservers) does not affect + * other resolvers: + * + * ```js + * import { Resolver } from 'node:dns'; + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org', (err, addresses) => { + * // ... + * }); + * ``` + * + * The following methods from the `node:dns` module are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v8.3.0 + */ + export class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTlsa: typeof resolveTlsa; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } + export { dnsPromises as promises }; +} +declare module "node:dns" { + export * from "dns"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/dns/promises.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/dns/promises.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..efb9fbfdf4258584324b30edf9250750b95d75fa --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/dns/promises.d.ts @@ -0,0 +1,503 @@ +/** + * The `dns.promises` API provides an alternative set of asynchronous DNS methods + * that return `Promise` objects rather than using callbacks. The API is accessible + * via `import { promises as dnsPromises } from 'node:dns'` or `import dnsPromises from 'node:dns/promises'`. + * @since v10.6.0 + */ +declare module "dns/promises" { + import { + AnyRecord, + CaaRecord, + LookupAddress, + LookupAllOptions, + LookupOneOptions, + LookupOptions, + MxRecord, + NaptrRecord, + RecordWithTtl, + ResolveOptions, + ResolverOptions, + ResolveWithTtlOptions, + SoaRecord, + SrvRecord, + TlsaRecord, + } from "node:dns"; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v10.6.0 + */ + function getServers(): string[]; + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the `Promise` is resolved with `addresses` being an array of objects with the properties `address` and `family`. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options) does not necessarily have anything to do with the DNS + * protocol. The implementation uses an operating system facility that can + * associate names with addresses and vice versa. This implementation can have + * subtle but important consequences on the behavior of any Node.js program. Please + * take some time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v20.x/api/dns.html#implementation-considerations) before + * using `dnsPromises.lookup()`. + * + * Example usage: + * + * ```js + * import dns from 'node:dns'; + * const dnsPromises = dns.promises; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('address: %j family: IPv%s', result.address, result.family); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * }); + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('addresses: %j', result); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * }); + * ``` + * @since v10.6.0 + */ + function lookup(hostname: string, family: number): Promise; + function lookup(hostname: string, options: LookupOneOptions): Promise; + function lookup(hostname: string, options: LookupAllOptions): Promise; + function lookup(hostname: string, options: LookupOptions): Promise; + function lookup(hostname: string): Promise; + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code. + * + * ```js + * import dnsPromises from 'node:dns'; + * dnsPromises.lookupService('127.0.0.1', 22).then((result) => { + * console.log(result.hostname, result.service); + * // Prints: localhost ssh + * }); + * ``` + * @since v10.6.0 + */ + function lookupService( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. When successful, the `Promise` is resolved with an + * array of resource records. The type and structure of individual results vary + * based on `rrtype`: + * + * + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes). + * @since v10.6.0 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + function resolve(hostname: string): Promise; + function resolve(hostname: string, rrtype: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function resolve(hostname: string, rrtype: "ANY"): Promise; + function resolve(hostname: string, rrtype: "CAA"): Promise; + function resolve(hostname: string, rrtype: "MX"): Promise; + function resolve(hostname: string, rrtype: "NAPTR"): Promise; + function resolve(hostname: string, rrtype: "SOA"): Promise; + function resolve(hostname: string, rrtype: "SRV"): Promise; + function resolve(hostname: string, rrtype: "TLSA"): Promise; + function resolve(hostname: string, rrtype: "TXT"): Promise; + function resolve(hostname: string, rrtype: string): Promise< + | string[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord + | SrvRecord[] + | TlsaRecord[] + | string[][] + | AnyRecord[] + >; + /** + * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv4 + * addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve4(hostname: string): Promise; + function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve4(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv6 + * addresses. + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve6(hostname: string): Promise; + function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve6(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * On success, the `Promise` is resolved with an array containing various types of + * records. Each object has a property `type` that indicates the type of the + * current record. And depending on the `type`, additional properties will be + * present on the object: + * + * + * + * Here is an example of the result object: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * @since v10.6.0 + */ + function resolveAny(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success, + * the `Promise` is resolved with an array of objects containing available + * certification authority authorization records available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + function resolveCaa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success, + * the `Promise` is resolved with an array of canonical name records available for + * the `hostname` (e.g. `['bar.example.com']`). + * @since v10.6.0 + */ + function resolveCname(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects + * containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v10.6.0 + */ + function resolveMx(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. On success, the `Promise` is resolved with an array + * of objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v10.6.0 + */ + function resolveNaptr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. On success, the `Promise` is resolved with an array of name server + * records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`). + * @since v10.6.0 + */ + function resolveNs(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. On success, the `Promise` is resolved with an array of strings + * containing the reply records. + * @since v10.6.0 + */ + function resolvePtr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. On success, the `Promise` is resolved with an object with the + * following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v10.6.0 + */ + function resolveSoa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects with + * the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v10.6.0 + */ + function resolveSrv(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve certificate associations (`TLSA` records) for + * the `hostname`. On success, the `Promise` is resolved with an array of objectsAdd commentMore actions + * with these properties: + * + * * `certUsage` + * * `selector` + * * `match` + * * `data` + * + * ```js + * { + * certUsage: 3, + * selector: 1, + * match: 1, + * data: [ArrayBuffer] + * } + * ``` + * @since v23.9.0, v22.15.0 + */ + function resolveTlsa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. On success, the `Promise` is resolved with a two-dimensional array + * of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v10.6.0 + */ + function resolveTxt(hostname: string): Promise; + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes). + * @since v10.6.0 + */ + function reverse(ip: string): Promise; + /** + * Get the default value for `verbatim` in {@link lookup} and [dnsPromises.lookup()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: for `verbatim` defaulting to `false`. + * * `verbatim`: for `verbatim` defaulting to `true`. + * @since v20.1.0 + */ + function getDefaultResultOrder(): "ipv4first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dnsPromises.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dnsPromises.setServers()` method must not be called while a DNS query is in + * progress. + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v10.6.0 + * @param servers array of `RFC 5952` formatted addresses + */ + function setServers(servers: readonly string[]): void; + /** + * Set the default value of `order` in `dns.lookup()` and `{@link lookup}`. The value could be: + * + * * `ipv4first`: sets default `order` to `ipv4first`. + * * `ipv6first`: sets default `order` to `ipv6first`. + * * `verbatim`: sets default `order` to `verbatim`. + * + * The default is `verbatim` and [dnsPromises.setDefaultResultOrder()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder) + * have higher priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder). + * When using [worker threads](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html), [`dnsPromises.setDefaultResultOrder()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder) + * from the main thread won't affect the default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`. + */ + function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void; + // Error codes + const NODATA: "ENODATA"; + const FORMERR: "EFORMERR"; + const SERVFAIL: "ESERVFAIL"; + const NOTFOUND: "ENOTFOUND"; + const NOTIMP: "ENOTIMP"; + const REFUSED: "EREFUSED"; + const BADQUERY: "EBADQUERY"; + const BADNAME: "EBADNAME"; + const BADFAMILY: "EBADFAMILY"; + const BADRESP: "EBADRESP"; + const CONNREFUSED: "ECONNREFUSED"; + const TIMEOUT: "ETIMEOUT"; + const EOF: "EOF"; + const FILE: "EFILE"; + const NOMEM: "ENOMEM"; + const DESTRUCTION: "EDESTRUCTION"; + const BADSTR: "EBADSTR"; + const BADFLAGS: "EBADFLAGS"; + const NONAME: "ENONAME"; + const BADHINTS: "EBADHINTS"; + const NOTINITIALIZED: "ENOTINITIALIZED"; + const LOADIPHLPAPI: "ELOADIPHLPAPI"; + const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS"; + const CANCELLED: "ECANCELLED"; + + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetserversservers) does not affect + * other resolvers: + * + * ```js + * import { promises } from 'node:dns'; + * const resolver = new promises.Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org').then((addresses) => { + * // ... + * }); + * + * // Alternatively, the same code can be written using async-await style. + * (async function() { + * const addresses = await resolver.resolve4('example.org'); + * })(); + * ``` + * + * The following methods from the `dnsPromises` API are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v10.6.0 + */ + class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTlsa: typeof resolveTlsa; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } +} +declare module "node:dns/promises" { + export * from "dns/promises"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/dom-events.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/dom-events.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cd6acde28196cf04b3cecd86b8642f83168c2dca --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/dom-events.d.ts @@ -0,0 +1,99 @@ +// Make this a module +export {}; + +// Conditional type aliases, which are later merged into the global scope. +// Will either be empty if the relevant web library is already present, or the @types/node definition otherwise. + +type __Event = typeof globalThis extends { onmessage: any } ? {} : Event; +interface Event { + readonly bubbles: boolean; + cancelBubble: boolean; + readonly cancelable: boolean; + readonly composed: boolean; + composedPath(): [EventTarget?]; + readonly currentTarget: EventTarget | null; + readonly defaultPrevented: boolean; + readonly eventPhase: 0 | 2; + initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; + readonly isTrusted: boolean; + preventDefault(): void; + readonly returnValue: boolean; + readonly srcElement: EventTarget | null; + stopImmediatePropagation(): void; + stopPropagation(): void; + readonly target: EventTarget | null; + readonly timeStamp: number; + readonly type: string; +} + +type __CustomEvent = typeof globalThis extends { onmessage: any } ? {} : CustomEvent; +interface CustomEvent extends Event { + readonly detail: T; +} + +type __EventTarget = typeof globalThis extends { onmessage: any } ? {} : EventTarget; +interface EventTarget { + addEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: AddEventListenerOptions | boolean, + ): void; + dispatchEvent(event: Event): boolean; + removeEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: EventListenerOptions | boolean, + ): void; +} + +interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} + +interface CustomEventInit extends EventInit { + detail?: T; +} + +interface EventListenerOptions { + capture?: boolean; +} + +interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean; + passive?: boolean; + signal?: AbortSignal; +} + +interface EventListener { + (evt: Event): void; +} + +interface EventListenerObject { + handleEvent(object: Event): void; +} + +// Merge conditional interfaces into global scope, and conditionally declare global constructors. +declare global { + interface Event extends __Event {} + var Event: typeof globalThis extends { onmessage: any; Event: infer T } ? T + : { + prototype: Event; + new(type: string, eventInitDict?: EventInit): Event; + }; + + interface CustomEvent extends __CustomEvent {} + var CustomEvent: typeof globalThis extends { onmessage: any; CustomEvent: infer T } ? T + : { + prototype: CustomEvent; + new(type: string, eventInitDict?: CustomEventInit): CustomEvent; + }; + + interface EventTarget extends __EventTarget {} + var EventTarget: typeof globalThis extends { onmessage: any; EventTarget: infer T } ? T + : { + prototype: EventTarget; + new(): EventTarget; + }; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/domain.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/domain.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c64115370b6cfe132d00c7b003e023f8509ca00 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/domain.d.ts @@ -0,0 +1,170 @@ +/** + * **This module is pending deprecation.** Once a replacement API has been + * finalized, this module will be fully deprecated. Most developers should + * **not** have cause to use this module. Users who absolutely must have + * the functionality that domains provide may rely on it for the time being + * but should expect to have to migrate to a different solution + * in the future. + * + * Domains provide a way to handle multiple different IO operations as a + * single group. If any of the event emitters or callbacks registered to a + * domain emit an `'error'` event, or throw an error, then the domain object + * will be notified, rather than losing the context of the error in the `process.on('uncaughtException')` handler, or causing the program to + * exit immediately with an error code. + * @deprecated Since v1.4.2 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/domain.js) + */ +declare module "domain" { + import EventEmitter = require("node:events"); + /** + * The `Domain` class encapsulates the functionality of routing errors and + * uncaught exceptions to the active `Domain` object. + * + * To handle the errors that it catches, listen to its `'error'` event. + */ + class Domain extends EventEmitter { + /** + * An array of timers and event emitters that have been explicitly added + * to the domain. + */ + members: Array; + /** + * The `enter()` method is plumbing used by the `run()`, `bind()`, and `intercept()` methods to set the active domain. It sets `domain.active` and `process.domain` to the domain, and implicitly + * pushes the domain onto the domain + * stack managed by the domain module (see {@link exit} for details on the + * domain stack). The call to `enter()` delimits the beginning of a chain of + * asynchronous calls and I/O operations bound to a domain. + * + * Calling `enter()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + enter(): void; + /** + * The `exit()` method exits the current domain, popping it off the domain stack. + * Any time execution is going to switch to the context of a different chain of + * asynchronous calls, it's important to ensure that the current domain is exited. + * The call to `exit()` delimits either the end of or an interruption to the chain + * of asynchronous calls and I/O operations bound to a domain. + * + * If there are multiple, nested domains bound to the current execution context, `exit()` will exit any domains nested within this domain. + * + * Calling `exit()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + exit(): void; + /** + * Run the supplied function in the context of the domain, implicitly + * binding all event emitters, timers, and low-level requests that are + * created in that context. Optionally, arguments can be passed to + * the function. + * + * This is the most basic way to use a domain. + * + * ```js + * import domain from 'node:domain'; + * import fs from 'node:fs'; + * const d = domain.create(); + * d.on('error', (er) => { + * console.error('Caught error!', er); + * }); + * d.run(() => { + * process.nextTick(() => { + * setTimeout(() => { // Simulating some various async stuff + * fs.open('non-existent file', 'r', (er, fd) => { + * if (er) throw er; + * // proceed... + * }); + * }, 100); + * }); + * }); + * ``` + * + * In this example, the `d.on('error')` handler will be triggered, rather + * than crashing the program. + */ + run(fn: (...args: any[]) => T, ...args: any[]): T; + /** + * Explicitly adds an emitter to the domain. If any event handlers called by + * the emitter throw an error, or if the emitter emits an `'error'` event, it + * will be routed to the domain's `'error'` event, just like with implicit + * binding. + * + * This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by + * the domain `'error'` handler. + * + * If the Timer or `EventEmitter` was already bound to a domain, it is removed + * from that one, and bound to this one instead. + * @param emitter emitter or timer to be added to the domain + */ + add(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The opposite of {@link add}. Removes domain handling from the + * specified emitter. + * @param emitter emitter or timer to be removed from the domain + */ + remove(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The returned function will be a wrapper around the supplied callback + * function. When the returned function is called, any errors that are + * thrown will be routed to the domain's `'error'` event. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.bind((er, data) => { + * // If this throws, it will also be passed to the domain. + * return cb(er, data ? JSON.parse(data) : null); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The bound function + */ + bind(callback: T): T; + /** + * This method is almost identical to {@link bind}. However, in + * addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function. + * + * In this way, the common `if (err) return callback(err);` pattern can be replaced + * with a single error handler in a single place. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.intercept((data) => { + * // Note, the first argument is never passed to the + * // callback since it is assumed to be the 'Error' argument + * // and thus intercepted by the domain. + * + * // If this throws, it will also be passed to the domain + * // so the error-handling logic can be moved to the 'error' + * // event on the domain instead of being repeated throughout + * // the program. + * return cb(null, JSON.parse(data)); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The intercepted function + */ + intercept(callback: T): T; + } + function create(): Domain; +} +declare module "node:domain" { + export * from "domain"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/events.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/events.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b79141f9409ac2d4956165280ffa6c42a7e45b7a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/events.d.ts @@ -0,0 +1,930 @@ +/** + * Much of the Node.js core API is built around an idiomatic asynchronous + * event-driven architecture in which certain kinds of objects (called "emitters") + * emit named events that cause `Function` objects ("listeners") to be called. + * + * For instance: a `net.Server` object emits an event each time a peer + * connects to it; a `fs.ReadStream` emits an event when the file is opened; + * a `stream` emits an event whenever data is available to be read. + * + * All objects that emit events are instances of the `EventEmitter` class. These + * objects expose an `eventEmitter.on()` function that allows one or more + * functions to be attached to named events emitted by the object. Typically, + * event names are camel-cased strings but any valid JavaScript property key + * can be used. + * + * When the `EventEmitter` object emits an event, all of the functions attached + * to that specific event are called _synchronously_. Any values returned by the + * called listeners are _ignored_ and discarded. + * + * The following example shows a simple `EventEmitter` instance with a single + * listener. The `eventEmitter.on()` method is used to register listeners, while + * the `eventEmitter.emit()` method is used to trigger the event. + * + * ```js + * import { EventEmitter } from 'node:events'; + * + * class MyEmitter extends EventEmitter {} + * + * const myEmitter = new MyEmitter(); + * myEmitter.on('event', () => { + * console.log('an event occurred!'); + * }); + * myEmitter.emit('event'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/events.js) + */ +declare module "events" { + import { AsyncResource, AsyncResourceOptions } from "node:async_hooks"; + // NOTE: This class is in the docs but is **not actually exported** by Node. + // If https://github.com/nodejs/node/issues/39903 gets resolved and Node + // actually starts exporting the class, uncomment below. + // import { EventListener, EventListenerObject } from '__dom-events'; + // /** The NodeEventTarget is a Node.js-specific extension to EventTarget that emulates a subset of the EventEmitter API. */ + // interface NodeEventTarget extends EventTarget { + // /** + // * Node.js-specific extension to the `EventTarget` class that emulates the equivalent `EventEmitter` API. + // * The only difference between `addListener()` and `addEventListener()` is that addListener() will return a reference to the EventTarget. + // */ + // addListener(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this; + // /** Node.js-specific extension to the `EventTarget` class that returns an array of event `type` names for which event listeners are registered. */ + // eventNames(): string[]; + // /** Node.js-specific extension to the `EventTarget` class that returns the number of event listeners registered for the `type`. */ + // listenerCount(type: string): number; + // /** Node.js-specific alias for `eventTarget.removeListener()`. */ + // off(type: string, listener: EventListener | EventListenerObject): this; + // /** Node.js-specific alias for `eventTarget.addListener()`. */ + // on(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this; + // /** Node.js-specific extension to the `EventTarget` class that adds a `once` listener for the given event `type`. This is equivalent to calling `on` with the `once` option set to `true`. */ + // once(type: string, listener: EventListener | EventListenerObject): this; + // /** + // * Node.js-specific extension to the `EventTarget` class. + // * If `type` is specified, removes all registered listeners for `type`, + // * otherwise removes all registered listeners. + // */ + // removeAllListeners(type: string): this; + // /** + // * Node.js-specific extension to the `EventTarget` class that removes the listener for the given `type`. + // * The only difference between `removeListener()` and `removeEventListener()` is that `removeListener()` will return a reference to the `EventTarget`. + // */ + // removeListener(type: string, listener: EventListener | EventListenerObject): this; + // } + interface EventEmitterOptions { + /** + * Enables automatic capturing of promise rejection. + */ + captureRejections?: boolean | undefined; + } + interface StaticEventEmitterOptions { + /** + * Can be used to cancel awaiting events. + */ + signal?: AbortSignal | undefined; + } + interface StaticEventEmitterIteratorOptions extends StaticEventEmitterOptions { + /** + * Names of events that will end the iteration. + */ + close?: string[] | undefined; + /** + * The high watermark. The emitter is paused every time the size of events being buffered is higher than it. + * Supported only on emitters implementing `pause()` and `resume()` methods. + * @default Number.MAX_SAFE_INTEGER + */ + highWaterMark?: number | undefined; + /** + * The low watermark. The emitter is resumed every time the size of events being buffered is lower than it. + * Supported only on emitters implementing `pause()` and `resume()` methods. + * @default 1 + */ + lowWaterMark?: number | undefined; + } + interface EventEmitter = DefaultEventMap> extends NodeJS.EventEmitter {} + type EventMap = Record | DefaultEventMap; + type DefaultEventMap = [never]; + type AnyRest = [...args: any[]]; + type Args = T extends DefaultEventMap ? AnyRest : ( + K extends keyof T ? T[K] : never + ); + type Key = T extends DefaultEventMap ? string | symbol : K | keyof T; + type Key2 = T extends DefaultEventMap ? string | symbol : K & keyof T; + type Listener = T extends DefaultEventMap ? F : ( + K extends keyof T ? ( + T[K] extends unknown[] ? (...args: T[K]) => void : never + ) + : never + ); + type Listener1 = Listener void>; + type Listener2 = Listener; + + /** + * The `EventEmitter` class is defined and exposed by the `node:events` module: + * + * ```js + * import { EventEmitter } from 'node:events'; + * ``` + * + * All `EventEmitter`s emit the event `'newListener'` when new listeners are + * added and `'removeListener'` when existing listeners are removed. + * + * It supports the following option: + * @since v0.1.26 + */ + class EventEmitter = DefaultEventMap> { + constructor(options?: EventEmitterOptions); + + [EventEmitter.captureRejectionSymbol]?(error: Error, event: Key, ...args: Args): void; + + /** + * Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given + * event or that is rejected if the `EventEmitter` emits `'error'` while waiting. + * The `Promise` will resolve with an array of all the arguments emitted to the + * given event. + * + * This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event + * semantics and does not listen to the `'error'` event. + * + * ```js + * import { once, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * process.nextTick(() => { + * ee.emit('myevent', 42); + * }); + * + * const [value] = await once(ee, 'myevent'); + * console.log(value); + * + * const err = new Error('kaboom'); + * process.nextTick(() => { + * ee.emit('error', err); + * }); + * + * try { + * await once(ee, 'myevent'); + * } catch (err) { + * console.error('error happened', err); + * } + * ``` + * + * The special handling of the `'error'` event is only used when `events.once()` is used to wait for another event. If `events.once()` is used to wait for the + * '`error'` event itself, then it is treated as any other kind of event without + * special handling: + * + * ```js + * import { EventEmitter, once } from 'node:events'; + * + * const ee = new EventEmitter(); + * + * once(ee, 'error') + * .then(([err]) => console.log('ok', err.message)) + * .catch((err) => console.error('error', err.message)); + * + * ee.emit('error', new Error('boom')); + * + * // Prints: ok boom + * ``` + * + * An `AbortSignal` can be used to cancel waiting for the event: + * + * ```js + * import { EventEmitter, once } from 'node:events'; + * + * const ee = new EventEmitter(); + * const ac = new AbortController(); + * + * async function foo(emitter, event, signal) { + * try { + * await once(emitter, event, { signal }); + * console.log('event emitted!'); + * } catch (error) { + * if (error.name === 'AbortError') { + * console.error('Waiting for the event was canceled!'); + * } else { + * console.error('There was an error', error.message); + * } + * } + * } + * + * foo(ee, 'foo', ac.signal); + * ac.abort(); // Abort waiting for the event + * ee.emit('foo'); // Prints: Waiting for the event was canceled! + * ``` + * @since v11.13.0, v10.16.0 + */ + static once( + emitter: NodeJS.EventEmitter, + eventName: string | symbol, + options?: StaticEventEmitterOptions, + ): Promise; + static once(emitter: EventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; + /** + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo')) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * ``` + * + * Returns an `AsyncIterator` that iterates `eventName` events. It will throw + * if the `EventEmitter` emits `'error'`. It removes all listeners when + * exiting the loop. The `value` returned by each iteration is an array + * composed of the emitted event arguments. + * + * An `AbortSignal` can be used to cancel waiting on events: + * + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ac = new AbortController(); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo', { signal: ac.signal })) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * + * process.nextTick(() => ac.abort()); + * ``` + * + * Use the `close` option to specify an array of event names that will end the iteration: + * + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * ee.emit('close'); + * }); + * + * for await (const event of on(ee, 'foo', { close: ['close'] })) { + * console.log(event); // prints ['bar'] [42] + * } + * // the loop will exit after 'close' is emitted + * console.log('done'); // prints 'done' + * ``` + * @since v13.6.0, v12.16.0 + * @return An `AsyncIterator` that iterates `eventName` events emitted by the `emitter` + */ + static on( + emitter: NodeJS.EventEmitter, + eventName: string | symbol, + options?: StaticEventEmitterIteratorOptions, + ): NodeJS.AsyncIterator; + static on( + emitter: EventTarget, + eventName: string, + options?: StaticEventEmitterIteratorOptions, + ): NodeJS.AsyncIterator; + /** + * A class method that returns the number of listeners for the given `eventName` registered on the given `emitter`. + * + * ```js + * import { EventEmitter, listenerCount } from 'node:events'; + * + * const myEmitter = new EventEmitter(); + * myEmitter.on('event', () => {}); + * myEmitter.on('event', () => {}); + * console.log(listenerCount(myEmitter, 'event')); + * // Prints: 2 + * ``` + * @since v0.9.12 + * @deprecated Since v3.2.0 - Use `listenerCount` instead. + * @param emitter The emitter to query + * @param eventName The event name + */ + static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * For `EventEmitter`s this behaves exactly the same as calling `.listeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the event listeners for the + * event target. This is useful for debugging and diagnostic purposes. + * + * ```js + * import { getEventListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * const listener = () => console.log('Events are fun'); + * ee.on('foo', listener); + * console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] + * } + * { + * const et = new EventTarget(); + * const listener = () => console.log('Events are fun'); + * et.addEventListener('foo', listener); + * console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] + * } + * ``` + * @since v15.2.0, v14.17.0 + */ + static getEventListeners(emitter: EventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; + /** + * Returns the currently set max amount of listeners. + * + * For `EventEmitter`s this behaves exactly the same as calling `.getMaxListeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the max event listeners for the + * event target. If the number of event handlers on a single EventTarget exceeds + * the max set, the EventTarget will print a warning. + * + * ```js + * import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * console.log(getMaxListeners(ee)); // 10 + * setMaxListeners(11, ee); + * console.log(getMaxListeners(ee)); // 11 + * } + * { + * const et = new EventTarget(); + * console.log(getMaxListeners(et)); // 10 + * setMaxListeners(11, et); + * console.log(getMaxListeners(et)); // 11 + * } + * ``` + * @since v19.9.0 + */ + static getMaxListeners(emitter: EventTarget | NodeJS.EventEmitter): number; + /** + * ```js + * import { setMaxListeners, EventEmitter } from 'node:events'; + * + * const target = new EventTarget(); + * const emitter = new EventEmitter(); + * + * setMaxListeners(5, target, emitter); + * ``` + * @since v15.4.0 + * @param n A non-negative number. The maximum number of listeners per `EventTarget` event. + * @param eventTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter} + * objects. + */ + static setMaxListeners(n?: number, ...eventTargets: Array): void; + /** + * Listens once to the `abort` event on the provided `signal`. + * + * Listening to the `abort` event on abort signals is unsafe and may + * lead to resource leaks since another third party with the signal can + * call `e.stopImmediatePropagation()`. Unfortunately Node.js cannot change + * this since it would violate the web standard. Additionally, the original + * API makes it easy to forget to remove listeners. + * + * This API allows safely using `AbortSignal`s in Node.js APIs by solving these + * two issues by listening to the event such that `stopImmediatePropagation` does + * not prevent the listener from running. + * + * Returns a disposable so that it may be unsubscribed from more easily. + * + * ```js + * import { addAbortListener } from 'node:events'; + * + * function example(signal) { + * let disposable; + * try { + * signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); + * disposable = addAbortListener(signal, (e) => { + * // Do something when signal is aborted. + * }); + * } finally { + * disposable?.[Symbol.dispose](); + * } + * } + * ``` + * @since v20.5.0 + * @return Disposable that removes the `abort` listener. + */ + static addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable; + /** + * This symbol shall be used to install a listener for only monitoring `'error'` events. Listeners installed using this symbol are called before the regular `'error'` listeners are called. + * + * Installing a listener using this symbol does not change the behavior once an `'error'` event is emitted. Therefore, the process will still crash if no + * regular `'error'` listener is installed. + * @since v13.6.0, v12.17.0 + */ + static readonly errorMonitor: unique symbol; + /** + * Value: `Symbol.for('nodejs.rejection')` + * + * See how to write a custom `rejection handler`. + * @since v13.4.0, v12.16.0 + */ + static readonly captureRejectionSymbol: unique symbol; + /** + * Value: [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) + * + * Change the default `captureRejections` option on all new `EventEmitter` objects. + * @since v13.4.0, v12.16.0 + */ + static captureRejections: boolean; + /** + * By default, a maximum of `10` listeners can be registered for any single + * event. This limit can be changed for individual `EventEmitter` instances + * using the `emitter.setMaxListeners(n)` method. To change the default + * for _all_`EventEmitter` instances, the `events.defaultMaxListeners` property + * can be used. If this value is not a positive number, a `RangeError` is thrown. + * + * Take caution when setting the `events.defaultMaxListeners` because the + * change affects _all_ `EventEmitter` instances, including those created before + * the change is made. However, calling `emitter.setMaxListeners(n)` still has + * precedence over `events.defaultMaxListeners`. + * + * This is not a hard limit. The `EventEmitter` instance will allow + * more listeners to be added but will output a trace warning to stderr indicating + * that a "possible EventEmitter memory leak" has been detected. For any single + * `EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()` methods can be used to + * temporarily avoid this warning: + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.setMaxListeners(emitter.getMaxListeners() + 1); + * emitter.once('event', () => { + * // do stuff + * emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); + * }); + * ``` + * + * The `--trace-warnings` command-line flag can be used to display the + * stack trace for such warnings. + * + * The emitted warning can be inspected with `process.on('warning')` and will + * have the additional `emitter`, `type`, and `count` properties, referring to + * the event emitter instance, the event's name and the number of attached + * listeners, respectively. + * Its `name` property is set to `'MaxListenersExceededWarning'`. + * @since v0.11.2 + */ + static defaultMaxListeners: number; + } + import internal = require("node:events"); + namespace EventEmitter { + // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4 + export { internal as EventEmitter }; + export interface Abortable { + /** + * When provided the corresponding `AbortController` can be used to cancel an asynchronous action. + */ + signal?: AbortSignal | undefined; + } + + export interface EventEmitterReferencingAsyncResource extends AsyncResource { + readonly eventEmitter: EventEmitterAsyncResource; + } + + export interface EventEmitterAsyncResourceOptions extends AsyncResourceOptions, EventEmitterOptions { + /** + * The type of async event, this is required when instantiating `EventEmitterAsyncResource` + * directly rather than as a child class. + * @default new.target.name if instantiated as a child class. + */ + name?: string; + } + + /** + * Integrates `EventEmitter` with `AsyncResource` for `EventEmitter`s that + * require manual async tracking. Specifically, all events emitted by instances + * of `events.EventEmitterAsyncResource` will run within its `async context`. + * + * ```js + * import { EventEmitterAsyncResource, EventEmitter } from 'node:events'; + * import { notStrictEqual, strictEqual } from 'node:assert'; + * import { executionAsyncId, triggerAsyncId } from 'node:async_hooks'; + * + * // Async tracking tooling will identify this as 'Q'. + * const ee1 = new EventEmitterAsyncResource({ name: 'Q' }); + * + * // 'foo' listeners will run in the EventEmitters async context. + * ee1.on('foo', () => { + * strictEqual(executionAsyncId(), ee1.asyncId); + * strictEqual(triggerAsyncId(), ee1.triggerAsyncId); + * }); + * + * const ee2 = new EventEmitter(); + * + * // 'foo' listeners on ordinary EventEmitters that do not track async + * // context, however, run in the same async context as the emit(). + * ee2.on('foo', () => { + * notStrictEqual(executionAsyncId(), ee2.asyncId); + * notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId); + * }); + * + * Promise.resolve().then(() => { + * ee1.emit('foo'); + * ee2.emit('foo'); + * }); + * ``` + * + * The `EventEmitterAsyncResource` class has the same methods and takes the + * same options as `EventEmitter` and `AsyncResource` themselves. + * @since v17.4.0, v16.14.0 + */ + export class EventEmitterAsyncResource extends EventEmitter { + /** + * @param options Only optional in child class. + */ + constructor(options?: EventEmitterAsyncResourceOptions); + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + */ + emitDestroy(): void; + /** + * The unique `asyncId` assigned to the resource. + */ + readonly asyncId: number; + /** + * The same triggerAsyncId that is passed to the AsyncResource constructor. + */ + readonly triggerAsyncId: number; + /** + * The returned `AsyncResource` object has an additional `eventEmitter` property + * that provides a reference to this `EventEmitterAsyncResource`. + */ + readonly asyncResource: EventEmitterReferencingAsyncResource; + } + } + global { + namespace NodeJS { + interface EventEmitter = DefaultEventMap> { + [EventEmitter.captureRejectionSymbol]?(error: Error, event: Key, ...args: Args): void; + /** + * Alias for `emitter.on(eventName, listener)`. + * @since v0.1.26 + */ + addListener(eventName: Key, listener: Listener1): this; + /** + * Adds the `listener` function to the end of the listeners array for the event + * named `eventName`. No checks are made to see if the `listener` has already + * been added. Multiple calls passing the same combination of `eventName` and + * `listener` will result in the `listener` being added, and called, multiple times. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The `emitter.prependListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEE = new EventEmitter(); + * myEE.on('foo', () => console.log('a')); + * myEE.prependListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.1.101 + * @param eventName The name of the event. + * @param listener The callback function + */ + on(eventName: Key, listener: Listener1): this; + /** + * Adds a **one-time** `listener` function for the event named `eventName`. The + * next time `eventName` is triggered, this listener is removed and then invoked. + * + * ```js + * server.once('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The `emitter.prependOnceListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEE = new EventEmitter(); + * myEE.once('foo', () => console.log('a')); + * myEE.prependOnceListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.3.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + once(eventName: Key, listener: Listener1): this; + /** + * Removes the specified `listener` from the listener array for the event named `eventName`. + * + * ```js + * const callback = (stream) => { + * console.log('someone connected!'); + * }; + * server.on('connection', callback); + * // ... + * server.removeListener('connection', callback); + * ``` + * + * `removeListener()` will remove, at most, one instance of a listener from the + * listener array. If any single listener has been added multiple times to the + * listener array for the specified `eventName`, then `removeListener()` must be + * called multiple times to remove each instance. + * + * Once an event is emitted, all listeners attached to it at the + * time of emitting are called in order. This implies that any `removeListener()` or `removeAllListeners()` calls _after_ emitting and _before_ the last listener finishes execution + * will not remove them from`emit()` in progress. Subsequent events behave as expected. + * + * ```js + * import { EventEmitter } from 'node:events'; + * class MyEmitter extends EventEmitter {} + * const myEmitter = new MyEmitter(); + * + * const callbackA = () => { + * console.log('A'); + * myEmitter.removeListener('event', callbackB); + * }; + * + * const callbackB = () => { + * console.log('B'); + * }; + * + * myEmitter.on('event', callbackA); + * + * myEmitter.on('event', callbackB); + * + * // callbackA removes listener callbackB but it will still be called. + * // Internal listener array at time of emit [callbackA, callbackB] + * myEmitter.emit('event'); + * // Prints: + * // A + * // B + * + * // callbackB is now removed. + * // Internal listener array [callbackA] + * myEmitter.emit('event'); + * // Prints: + * // A + * ``` + * + * Because listeners are managed using an internal array, calling this will + * change the position indices of any listener registered _after_ the listener + * being removed. This will not impact the order in which listeners are called, + * but it means that any copies of the listener array as returned by + * the `emitter.listeners()` method will need to be recreated. + * + * When a single function has been added as a handler multiple times for a single + * event (as in the example below), `removeListener()` will remove the most + * recently added instance. In the example the `once('ping')` listener is removed: + * + * ```js + * import { EventEmitter } from 'node:events'; + * const ee = new EventEmitter(); + * + * function pong() { + * console.log('pong'); + * } + * + * ee.on('ping', pong); + * ee.once('ping', pong); + * ee.removeListener('ping', pong); + * + * ee.emit('ping'); + * ee.emit('ping'); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeListener(eventName: Key, listener: Listener1): this; + /** + * Alias for `emitter.removeListener()`. + * @since v10.0.0 + */ + off(eventName: Key, listener: Listener1): this; + /** + * Removes all listeners, or those of the specified `eventName`. + * + * It is bad practice to remove listeners added elsewhere in the code, + * particularly when the `EventEmitter` instance was created by some other + * component or module (e.g. sockets or file streams). + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeAllListeners(eventName?: Key): this; + /** + * By default `EventEmitter`s will print a warning if more than `10` listeners are + * added for a particular event. This is a useful default that helps finding + * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be + * modified for this specific `EventEmitter` instance. The value can be set to `Infinity` (or `0`) to indicate an unlimited number of listeners. + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.3.5 + */ + setMaxListeners(n: number): this; + /** + * Returns the current max listener value for the `EventEmitter` which is either + * set by `emitter.setMaxListeners(n)` or defaults to {@link EventEmitter.defaultMaxListeners}. + * @since v1.0.0 + */ + getMaxListeners(): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * console.log(util.inspect(server.listeners('connection'))); + * // Prints: [ [Function] ] + * ``` + * @since v0.1.26 + */ + listeners(eventName: Key): Array>; + /** + * Returns a copy of the array of listeners for the event named `eventName`, + * including any wrappers (such as those created by `.once()`). + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.once('log', () => console.log('log once')); + * + * // Returns a new Array with a function `onceWrapper` which has a property + * // `listener` which contains the original listener bound above + * const listeners = emitter.rawListeners('log'); + * const logFnWrapper = listeners[0]; + * + * // Logs "log once" to the console and does not unbind the `once` event + * logFnWrapper.listener(); + * + * // Logs "log once" to the console and removes the listener + * logFnWrapper(); + * + * emitter.on('log', () => console.log('log persistently')); + * // Will return a new Array with a single function bound by `.on()` above + * const newListeners = emitter.rawListeners('log'); + * + * // Logs "log persistently" twice + * newListeners[0](); + * emitter.emit('log'); + * ``` + * @since v9.4.0 + */ + rawListeners(eventName: Key): Array>; + /** + * Synchronously calls each of the listeners registered for the event named `eventName`, in the order they were registered, passing the supplied arguments + * to each. + * + * Returns `true` if the event had listeners, `false` otherwise. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEmitter = new EventEmitter(); + * + * // First listener + * myEmitter.on('event', function firstListener() { + * console.log('Helloooo! first listener'); + * }); + * // Second listener + * myEmitter.on('event', function secondListener(arg1, arg2) { + * console.log(`event with parameters ${arg1}, ${arg2} in second listener`); + * }); + * // Third listener + * myEmitter.on('event', function thirdListener(...args) { + * const parameters = args.join(', '); + * console.log(`event with parameters ${parameters} in third listener`); + * }); + * + * console.log(myEmitter.listeners('event')); + * + * myEmitter.emit('event', 1, 2, 3, 4, 5); + * + * // Prints: + * // [ + * // [Function: firstListener], + * // [Function: secondListener], + * // [Function: thirdListener] + * // ] + * // Helloooo! first listener + * // event with parameters 1, 2 in second listener + * // event with parameters 1, 2, 3, 4, 5 in third listener + * ``` + * @since v0.1.26 + */ + emit(eventName: Key, ...args: Args): boolean; + /** + * Returns the number of listeners listening for the event named `eventName`. + * If `listener` is provided, it will return how many times the listener is found + * in the list of the listeners of the event. + * @since v3.2.0 + * @param eventName The name of the event being listened for + * @param listener The event handler function + */ + listenerCount(eventName: Key, listener?: Listener2): number; + /** + * Adds the `listener` function to the _beginning_ of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName` + * and `listener` will result in the `listener` being added, and called, multiple times. + * + * ```js + * server.prependListener('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependListener(eventName: Key, listener: Listener1): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName` to the _beginning_ of the listeners array. The next time `eventName` is triggered, this + * listener is removed, and then invoked. + * + * ```js + * server.prependOnceListener('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependOnceListener(eventName: Key, listener: Listener1): this; + /** + * Returns an array listing the events for which the emitter has registered + * listeners. The values in the array are strings or `Symbol`s. + * + * ```js + * import { EventEmitter } from 'node:events'; + * + * const myEE = new EventEmitter(); + * myEE.on('foo', () => {}); + * myEE.on('bar', () => {}); + * + * const sym = Symbol('symbol'); + * myEE.on(sym, () => {}); + * + * console.log(myEE.eventNames()); + * // Prints: [ 'foo', 'bar', Symbol(symbol) ] + * ``` + * @since v6.0.0 + */ + eventNames(): Array<(string | symbol) & Key2>; + } + } + } + export = EventEmitter; +} +declare module "node:events" { + import events = require("events"); + export = events; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/fs.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/fs.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5f3bd7ad42f5bf51a7f766b1c6940bd56cb3a123 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/fs.d.ts @@ -0,0 +1,4440 @@ +/** + * The `node:fs` module enables interacting with the file system in a + * way modeled on standard POSIX functions. + * + * To use the promise-based APIs: + * + * ```js + * import * as fs from 'node:fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from 'node:fs'; + * ``` + * + * All file system operations have synchronous, callback, and promise-based + * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/fs.js) + */ +declare module "fs" { + import * as stream from "node:stream"; + import { Abortable, EventEmitter } from "node:events"; + import { URL } from "node:url"; + import * as promises from "node:fs/promises"; + export { promises }; + /** + * Valid types for path values in "fs". + */ + export type PathLike = string | Buffer | URL; + export type PathOrFileDescriptor = PathLike | number; + export type TimeLike = string | number | Date; + export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; + export type BufferEncodingOption = + | "buffer" + | { + encoding: "buffer"; + }; + export interface ObjectEncodingOptions { + encoding?: BufferEncoding | null | undefined; + } + export type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null; + export type OpenMode = number | string; + export type Mode = number | string; + export interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + export interface Stats extends StatsBase {} + /** + * A `fs.Stats` object provides information about a file. + * + * Objects returned from {@link stat}, {@link lstat}, {@link fstat}, and + * their synchronous counterparts are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`, and the object will contain additional + * nanosecond-precision properties suffixed with `Ns`. `Stat` objects are not to be created directly using the `new` keyword. + * + * ```console + * Stats { + * dev: 2114, + * ino: 48064969, + * mode: 33188, + * nlink: 1, + * uid: 85, + * gid: 100, + * rdev: 0, + * size: 527, + * blksize: 4096, + * blocks: 8, + * atimeMs: 1318289051000.1, + * mtimeMs: 1318289051000.1, + * ctimeMs: 1318289051000.1, + * birthtimeMs: 1318289051000.1, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * + * `bigint` version: + * + * ```console + * BigIntStats { + * dev: 2114n, + * ino: 48064969n, + * mode: 33188n, + * nlink: 1n, + * uid: 85n, + * gid: 100n, + * rdev: 0n, + * size: 527n, + * blksize: 4096n, + * blocks: 8n, + * atimeMs: 1318289051000n, + * mtimeMs: 1318289051000n, + * ctimeMs: 1318289051000n, + * birthtimeMs: 1318289051000n, + * atimeNs: 1318289051000000000n, + * mtimeNs: 1318289051000000000n, + * ctimeNs: 1318289051000000000n, + * birthtimeNs: 1318289051000000000n, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * @since v0.1.21 + */ + export class Stats { + private constructor(); + } + export interface StatsFsBase { + /** Type of file system. */ + type: T; + /** Optimal transfer block size. */ + bsize: T; + /** Total data blocks in file system. */ + blocks: T; + /** Free blocks in file system. */ + bfree: T; + /** Available blocks for unprivileged users */ + bavail: T; + /** Total file nodes in file system. */ + files: T; + /** Free file nodes in file system. */ + ffree: T; + } + export interface StatsFs extends StatsFsBase {} + /** + * Provides information about a mounted file system. + * + * Objects returned from {@link statfs} and its synchronous counterpart are of + * this type. If `bigint` in the `options` passed to those methods is `true`, the + * numeric values will be `bigint` instead of `number`. + * + * ```console + * StatFs { + * type: 1397114950, + * bsize: 4096, + * blocks: 121938943, + * bfree: 61058895, + * bavail: 61058895, + * files: 999, + * ffree: 1000000 + * } + * ``` + * + * `bigint` version: + * + * ```console + * StatFs { + * type: 1397114950n, + * bsize: 4096n, + * blocks: 121938943n, + * bfree: 61058895n, + * bavail: 61058895n, + * files: 999n, + * ffree: 1000000n + * } + * ``` + * @since v19.6.0, v18.15.0 + */ + export class StatsFs {} + export interface BigIntStatsFs extends StatsFsBase {} + export interface StatFsOptions { + bigint?: boolean | undefined; + } + /** + * A representation of a directory entry, which can be a file or a subdirectory + * within the directory, as returned by reading from an `fs.Dir`. The + * directory entry is a combination of the file name and file type pairs. + * + * Additionally, when {@link readdir} or {@link readdirSync} is called with + * the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s. + * @since v10.10.0 + */ + export class Dirent { + /** + * Returns `true` if the `fs.Dirent` object describes a regular file. + * @since v10.10.0 + */ + isFile(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a file system + * directory. + * @since v10.10.0 + */ + isDirectory(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a block device. + * @since v10.10.0 + */ + isBlockDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a character device. + * @since v10.10.0 + */ + isCharacterDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a symbolic link. + * @since v10.10.0 + */ + isSymbolicLink(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a first-in-first-out + * (FIFO) pipe. + * @since v10.10.0 + */ + isFIFO(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a socket. + * @since v10.10.0 + */ + isSocket(): boolean; + /** + * The file name that this `fs.Dirent` object refers to. The type of this + * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}. + * @since v10.10.0 + */ + name: Name; + /** + * The path to the parent directory of the file this `fs.Dirent` object refers to. + * @since v20.12.0, v18.20.0 + */ + parentPath: string; + } + /** + * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + */ + export class Dir implements AsyncIterable { + /** + * The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or `fsPromises.opendir()`. + * @since v12.12.0 + */ + readonly path: string; + /** + * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. + */ + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * + * A promise is returned that will be fulfilled after the resource has been + * closed. + * @since v12.12.0 + */ + close(): Promise; + close(cb: NoParamCallback): void; + /** + * Synchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * @since v12.12.0 + */ + closeSync(): void; + /** + * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`. + * + * A promise is returned that will be fulfilled with an `fs.Dirent`, or `null` if there are no more directory entries to read. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + * @return containing {fs.Dirent|null} + */ + read(): Promise; + read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; + /** + * Synchronously read the next directory entry as an `fs.Dirent`. See the + * POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail. + * + * If there are no more directory entries to read, `null` will be returned. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + */ + readSync(): Dirent | null; + /** + * Calls `dir.close()` if the directory handle is open, and returns a promise that + * fulfills when disposal is complete. + * @since v24.1.0 + */ + [Symbol.asyncDispose](): Promise; + /** + * Calls `dir.closeSync()` if the directory handle is open, and returns + * `undefined`. + * @since v24.1.0 + */ + [Symbol.dispose](): void; + } + /** + * Class: fs.StatWatcher + * @since v14.3.0, v12.20.0 + * Extends `EventEmitter` + * A successful call to {@link watchFile} method will return a new fs.StatWatcher object. + */ + export interface StatWatcher extends EventEmitter { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.StatWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.StatWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.StatWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.StatWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + } + export interface FSWatcher extends EventEmitter { + /** + * Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the `fs.FSWatcher` object is no longer usable. + * @since v0.5.8 + */ + close(): void; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.FSWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.FSWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.FSWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.FSWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + /** + * events.EventEmitter + * 1. change + * 2. close + * 3. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + } + /** + * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function. + * @since v0.1.93 + */ + export class ReadStream extends stream.Readable { + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes that have been read so far. + * @since v6.4.0 + */ + bytesRead: number; + /** + * The path to the file the stream is reading from as specified in the first + * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `Buffer`, then`readStream.path` will be a + * `Buffer`. If `fd` is specified, then`readStream.path` will be `undefined`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0, v10.16.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: K, listener: ReadStreamEvents[K]): this; + on(event: K, listener: ReadStreamEvents[K]): this; + once(event: K, listener: ReadStreamEvents[K]): this; + prependListener(event: K, listener: ReadStreamEvents[K]): this; + prependOnceListener(event: K, listener: ReadStreamEvents[K]): this; + } + + /** + * The Keys are events of the ReadStream and the values are the functions that are called when the event is emitted. + */ + type ReadStreamEvents = { + close: () => void; + data: (chunk: Buffer | string) => void; + end: () => void; + error: (err: Error) => void; + open: (fd: number) => void; + pause: () => void; + readable: () => void; + ready: () => void; + resume: () => void; + } & CustomEvents; + + /** + * string & {} allows to allow any kind of strings for the event + * but still allows to have auto completion for the normal events. + */ + type CustomEvents = { [Key in string & {} | symbol]: (...args: any[]) => void }; + + /** + * The Keys are events of the WriteStream and the values are the functions that are called when the event is emitted. + */ + type WriteStreamEvents = { + close: () => void; + drain: () => void; + error: (err: Error) => void; + finish: () => void; + open: (fd: number) => void; + pipe: (src: stream.Readable) => void; + ready: () => void; + unpipe: (src: stream.Readable) => void; + } & CustomEvents; + /** + * * Extends `stream.Writable` + * + * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function. + * @since v0.1.93 + */ + export class WriteStream extends stream.Writable { + /** + * Closes `writeStream`. Optionally accepts a + * callback that will be executed once the `writeStream`is closed. + * @since v0.9.4 + */ + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes written so far. Does not include data that is still queued + * for writing. + * @since v0.4.7 + */ + bytesWritten: number; + /** + * The path to the file the stream is writing to as specified in the first + * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a + * `Buffer`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: K, listener: WriteStreamEvents[K]): this; + on(event: K, listener: WriteStreamEvents[K]): this; + once(event: K, listener: WriteStreamEvents[K]): this; + prependListener(event: K, listener: WriteStreamEvents[K]): this; + prependOnceListener(event: K, listener: WriteStreamEvents[K]): this; + } + /** + * Asynchronously rename file at `oldPath` to the pathname provided + * as `newPath`. In the case that `newPath` already exists, it will + * be overwritten. If there is a directory at `newPath`, an error will + * be raised instead. No arguments other than a possible exception are + * given to the completion callback. + * + * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). + * + * ```js + * import { rename } from 'node:fs'; + * + * rename('oldFile.txt', 'newFile.txt', (err) => { + * if (err) throw err; + * console.log('Rename complete!'); + * }); + * ``` + * @since v0.0.2 + */ + export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + /** + * Renames the file from `oldPath` to `newPath`. Returns `undefined`. + * + * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details. + * @since v0.1.21 + */ + export function renameSync(oldPath: PathLike, newPath: PathLike): void; + /** + * Truncates the file. No arguments other than a possible exception are + * given to the completion callback. A file descriptor can also be passed as the + * first argument. In this case, `fs.ftruncate()` is called. + * + * ```js + * import { truncate } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * truncate('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was truncated'); + * }); + * ``` + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * + * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details. + * @since v0.8.6 + * @param [len=0] + */ + export function truncate(path: PathLike, len: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function truncate(path: PathLike, callback: NoParamCallback): void; + export namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number): Promise; + } + /** + * Truncates the file. Returns `undefined`. A file descriptor can also be + * passed as the first argument. In this case, `fs.ftruncateSync()` is called. + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * @since v0.8.6 + * @param [len=0] + */ + export function truncateSync(path: PathLike, len?: number): void; + /** + * Truncates the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. + * + * If the file referred to by the file descriptor was larger than `len` bytes, only + * the first `len` bytes will be retained in the file. + * + * For example, the following program retains only the first four bytes of the + * file: + * + * ```js + * import { open, close, ftruncate } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('temp.txt', 'r+', (err, fd) => { + * if (err) throw err; + * + * try { + * ftruncate(fd, 4, (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * if (err) throw err; + * } + * }); + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncate(fd: number, len: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + export function ftruncate(fd: number, callback: NoParamCallback): void; + export namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number): Promise; + } + /** + * Truncates the file descriptor. Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link ftruncate}. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncateSync(fd: number, len?: number): void; + /** + * Asynchronously changes owner and group of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Synchronously changes owner and group of a file. Returns `undefined`. + * This is the synchronous version of {@link chown}. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chownSync(path: PathLike, uid: number, gid: number): void; + /** + * Sets the owner of the file. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; + export namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + /** + * Sets the owner of the file. Returns `undefined`. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function fchownSync(fd: number, uid: number, gid: number): void; + /** + * Set the owner of the symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail. + */ + export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Set the owner for the path. Returns `undefined`. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details. + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function lchownSync(path: PathLike, uid: number, gid: number): void; + /** + * Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic + * link, then the link is not dereferenced: instead, the timestamps of the + * symbolic link itself are changed. + * + * No arguments other than a possible exception are given to the completion + * callback. + * @since v14.5.0, v12.19.0 + */ + export function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace lutimes { + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, + * with the difference that if the path refers to a symbolic link, then the link is not + * dereferenced: instead, the timestamps of the symbolic link itself are changed. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Change the file system timestamps of the symbolic link referenced by `path`. + * Returns `undefined`, or throws an exception when parameters are incorrect or + * the operation fails. This is the synchronous version of {@link lutimes}. + * @since v14.5.0, v12.19.0 + */ + export function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Asynchronously changes the permissions of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * + * ```js + * import { chmod } from 'node:fs'; + * + * chmod('my_file.txt', 0o775, (err) => { + * if (err) throw err; + * console.log('The permissions for file "my_file.txt" have been changed!'); + * }); + * ``` + * @since v0.1.30 + */ + export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + export namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link chmod}. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * @since v0.6.7 + */ + export function chmodSync(path: PathLike, mode: Mode): void; + /** + * Sets the permissions on the file. No arguments other than a possible exception + * are given to the completion callback. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; + export namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: Mode): Promise; + } + /** + * Sets the permissions on the file. Returns `undefined`. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmodSync(fd: number, mode: Mode): void; + /** + * Changes the permissions on a symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + /** @deprecated */ + export namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * Changes the permissions on a symbolic link. Returns `undefined`. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmodSync(path: PathLike, mode: Mode): void; + /** + * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * + * {@link stat} follows symbolic links. Use {@link lstat} to look at the + * links themselves. + * + * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. + * Instead, user code should open/read/write the file directly and handle the + * error raised if the file is not available. + * + * To check if a file exists without manipulating it afterwards, {@link access} is recommended. + * + * For example, given the following directory structure: + * + * ```text + * - txtDir + * -- file.txt + * - app.js + * ``` + * + * The next program will check for the stats of the given paths: + * + * ```js + * import { stat } from 'node:fs'; + * + * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; + * + * for (let i = 0; i < pathsToCheck.length; i++) { + * stat(pathsToCheck[i], (err, stats) => { + * console.log(stats.isDirectory()); + * console.log(stats); + * }); + * } + * ``` + * + * The resulting output will resemble: + * + * ```console + * true + * Stats { + * dev: 16777220, + * mode: 16877, + * nlink: 3, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214262, + * size: 96, + * blocks: 0, + * atimeMs: 1561174653071.963, + * mtimeMs: 1561174614583.3518, + * ctimeMs: 1561174626623.5366, + * birthtimeMs: 1561174126937.2893, + * atime: 2019-06-22T03:37:33.072Z, + * mtime: 2019-06-22T03:36:54.583Z, + * ctime: 2019-06-22T03:37:06.624Z, + * birthtime: 2019-06-22T03:28:46.937Z + * } + * false + * Stats { + * dev: 16777220, + * mode: 33188, + * nlink: 1, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214074, + * size: 8, + * blocks: 8, + * atimeMs: 1561174616618.8555, + * mtimeMs: 1561174614584, + * ctimeMs: 1561174614583.8145, + * birthtimeMs: 1561174007710.7478, + * atime: 2019-06-22T03:36:56.619Z, + * mtime: 2019-06-22T03:36:54.584Z, + * ctime: 2019-06-22T03:36:54.584Z, + * birthtime: 2019-06-22T03:26:47.711Z + * } + * ``` + * @since v0.0.2 + */ + export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function stat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function stat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function stat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + export interface StatSyncFn extends Function { + (path: PathLike, options?: undefined): Stats; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + }, + ): Stats | undefined; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + throwIfNoEntry: false; + }, + ): BigIntStats | undefined; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + }, + ): Stats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + }, + ): BigIntStats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: boolean; + throwIfNoEntry?: false | undefined; + }, + ): Stats | BigIntStats; + (path: PathLike, options?: StatSyncOptions): Stats | BigIntStats | undefined; + } + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const statSync: StatSyncFn; + /** + * Invokes the callback with the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function fstat( + fd: number, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function fstat( + fd: number, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function fstat( + fd: number, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(fd: number, options?: StatOptions): Promise; + } + /** + * Retrieves the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstatSync( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Stats; + export function fstatSync( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): BigIntStats; + export function fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats; + /** + * Retrieves the `fs.Stats` for the symbolic link referred to by the path. + * The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic + * link, then the link itself is stat-ed, not the file that it refers to. + * + * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details. + * @since v0.1.30 + */ + export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function lstat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function lstat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function lstat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + /** + * Asynchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. The callback gets two arguments `(err, stats)` where `stats`is an `fs.StatFs` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfs(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void): void; + export function statfs( + path: PathLike, + options: + | (StatFsOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void, + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStatsFs) => void, + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs | BigIntStatsFs) => void, + ): void; + export namespace statfs { + /** + * Asynchronous statfs(2) - Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an object. + * @param path A path to an existing file or directory on the file system to be queried. + */ + function __promisify__( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatFsOptions): Promise; + } + /** + * Synchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfsSync( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): StatsFs; + export function statfsSync( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): BigIntStatsFs; + export function statfsSync(path: PathLike, options?: StatFsOptions): StatsFs | BigIntStatsFs; + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const lstatSync: StatSyncFn; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than + * a possible + * exception are given to the completion callback. + * @since v0.1.31 + */ + export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.31 + */ + export function linkSync(existingPath: PathLike, newPath: PathLike): void; + /** + * Creates the link called `path` pointing to `target`. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details. + * + * The `type` argument is only available on Windows and ignored on other platforms. + * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is + * not a string, Node.js will autodetect `target` type and use `'file'` or `'dir'`. + * If the `target` does not exist, `'file'` will be used. Windows junction points + * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. Junction + * points on NTFS volumes can only point to directories. + * + * Relative targets are relative to the link's parent directory. + * + * ```js + * import { symlink } from 'node:fs'; + * + * symlink('./mew', './mewtwo', callback); + * ``` + * + * The above example creates a symbolic link `mewtwo` which points to `mew` in the + * same directory: + * + * ```bash + * $ tree . + * . + * ├── mew + * └── mewtwo -> ./mew + * ``` + * @since v0.1.31 + * @param [type='null'] + */ + export function symlink( + target: PathLike, + path: PathLike, + type: symlink.Type | undefined | null, + callback: NoParamCallback, + ): void; + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; + export namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + type Type = "dir" | "file" | "junction"; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link symlink}. + * @since v0.1.31 + * @param [type='null'] + */ + export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + /** + * Reads the contents of the symbolic link referred to by `path`. The callback gets + * two arguments `(err, linkString)`. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path passed to the callback. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readlink( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + export namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + } + /** + * Returns the symbolic link's string value. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer; + /** + * Asynchronously computes the canonical pathname by resolving `.`, `..`, and + * symbolic links. + * + * A canonical pathname is not necessarily unique. Hard links and bind mounts can + * expose a file system entity through many pathnames. + * + * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: + * + * 1. No case conversion is performed on case-insensitive file systems. + * 2. The maximum number of symbolic links is platform-independent and generally + * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. + * + * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd` to resolve relative paths. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * If `path` resolves to a socket or a pipe, the function will return a system + * dependent name for that object. + * @since v0.1.31 + */ + export function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function realpath( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + export namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). + * + * The `callback` gets two arguments `(err, resolvedPath)`. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v9.2.0 + */ + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + function native( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void, + ): void; + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void, + ): void; + function native( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + } + /** + * Returns the resolved pathname. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link realpath}. + * @since v0.1.31 + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string | Buffer; + export namespace realpathSync { + function native(path: PathLike, options?: EncodingOption): string; + function native(path: PathLike, options: BufferEncodingOption): Buffer; + function native(path: PathLike, options?: EncodingOption): string | Buffer; + } + /** + * Asynchronously removes a file or symbolic link. No arguments other than a + * possible exception are given to the completion callback. + * + * ```js + * import { unlink } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * unlink('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was deleted'); + * }); + * ``` + * + * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a + * directory, use {@link rmdir}. + * + * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details. + * @since v0.0.2 + */ + export function unlink(path: PathLike, callback: NoParamCallback): void; + export namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. + * @since v0.1.21 + */ + export function unlinkSync(path: PathLike): void; + export interface RmDirOptions { + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * @deprecated since v14.14.0 In future versions of Node.js and will trigger a warning + * `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file. + * Use `fs.rm(path, { recursive: true, force: true })` instead. + * + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given + * to the completion callback. + * + * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on + * Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`. + * @since v0.0.2 + */ + export function rmdir(path: PathLike, callback: NoParamCallback): void; + export function rmdir(path: PathLike, options: RmDirOptions, callback: NoParamCallback): void; + export namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options?: RmDirOptions): Promise; + } + /** + * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. + * + * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error + * on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`. + * @since v0.1.21 + */ + export function rmdirSync(path: PathLike, options?: RmDirOptions): void; + export interface RmOptions { + /** + * When `true`, exceptions will be ignored if `path` does not exist. + * @default false + */ + force?: boolean | undefined; + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). No arguments other than a possible exception are given to the + * completion callback. + * @since v14.14.0 + */ + export function rm(path: PathLike, callback: NoParamCallback): void; + export function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void; + export namespace rm { + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + function __promisify__(path: PathLike, options?: RmOptions): Promise; + } + /** + * Synchronously removes files and directories (modeled on the standard POSIX `rm` utility). Returns `undefined`. + * @since v14.14.0 + */ + export function rmSync(path: PathLike, options?: RmOptions): void; + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean | undefined; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: Mode | undefined; + } + /** + * Asynchronously creates a directory. + * + * The callback is given a possible exception and, if `recursive` is `true`, the + * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was + * created (for instance, if it was previously created). + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fs.mkdir()` when `path` is a directory that + * exists results in an error only + * when `recursive` is false. If `recursive` is false and the directory exists, + * an `EEXIST` error occurs. + * + * ```js + * import { mkdir } from 'node:fs'; + * + * // Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist. + * mkdir('./tmp/a/apple', { recursive: true }, (err) => { + * if (err) throw err; + * }); + * ``` + * + * On Windows, using `fs.mkdir()` on the root directory even with recursion will + * result in an error: + * + * ```js + * import { mkdir } from 'node:fs'; + * + * mkdir('/', { recursive: true }, (err) => { + * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] + * }); + * ``` + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.8 + */ + export function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + | undefined, + callback: NoParamCallback, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: Mode | MakeDirectoryOptions | null | undefined, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function mkdir(path: PathLike, callback: NoParamCallback): void; + export namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: Mode | MakeDirectoryOptions | null, + ): Promise; + } + /** + * Synchronously creates a directory. Returns `undefined`, or if `recursive` is `true`, the first directory path created. + * This is the synchronous version of {@link mkdir}. + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.21 + */ + export function mkdirSync( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): string | undefined; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): void; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; + /** + * Creates a unique temporary directory. + * + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. Due to platform + * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, + * notably the BSDs, can return more than six random characters, and replace + * trailing `X` characters in `prefix` with random characters. + * + * The created directory path is passed as a string to the callback's second + * parameter. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 + * }); + * ``` + * + * The `fs.mkdtemp()` method will append the six randomly selected characters + * directly to the `prefix` string. For instance, given a directory `/tmp`, if the + * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator + * (`import { sep } from 'node:path'`). + * + * ```js + * import { tmpdir } from 'node:os'; + * import { mkdtemp } from 'node:fs'; + * + * // The parent directory for the new temporary directory + * const tmpDir = tmpdir(); + * + * // This method is *INCORRECT*: + * mkdtemp(tmpDir, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmpabc123`. + * // A new temporary directory is created at the file system root + * // rather than *within* the /tmp directory. + * }); + * + * // This method is *CORRECT*: + * import { sep } from 'node:path'; + * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmp/abc123`. + * // A new temporary directory is created within + * // the /tmp directory. + * }); + * ``` + * @since v5.10.0 + */ + export function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: + | "buffer" + | { + encoding: "buffer"; + }, + callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + export function mkdtemp( + prefix: string, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + export namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + } + /** + * Returns the created directory path. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link mkdtemp}. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v5.10.0 + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string | Buffer; + /** + * Reads the contents of a directory. The callback gets two arguments `(err, files)` where `files` is an array of the names of the files in the directory excluding `'.'` and `'..'`. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames passed to the callback. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects. + * @since v0.1.8 + */ + export function readdir( + path: PathLike, + options: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readdir( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + export function readdir( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, + ): void; + export namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options: + | "buffer" + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + function __promisify__( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise[]>; + } + /** + * Reads the contents of the directory. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames returned. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects. + * @since v0.1.21 + */ + export function readdirSync( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): string[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): string[] | Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdirSync( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + export function readdirSync( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; + /** + * Closes the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.0.2 + */ + export function close(fd: number, callback?: NoParamCallback): void; + export namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Closes the file descriptor. Returns `undefined`. + * + * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.1.21 + */ + export function closeSync(fd: number): void; + /** + * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. + * + * `mode` sets the file mode (permission and sticky bits), but only if the file was + * created. On Windows, only the write permission can be manipulated; see {@link chmod}. + * + * The callback gets two arguments `(err, fd)`. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * + * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc. + * @since v0.0.2 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] + */ + export function open( + path: PathLike, + flags: OpenMode | undefined, + mode: Mode | undefined | null, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param [flags='r'] See `support of file system `flags``. + */ + export function open( + path: PathLike, + flags: OpenMode | undefined, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + export namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; + } + /** + * Returns an integer representing the file descriptor. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link open}. + * @since v0.1.21 + * @param [flags='r'] + * @param [mode=0o666] + */ + export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time in seconds, `Date`s, or a numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. + * @since v0.4.2 + */ + export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link utimes}. + * @since v0.4.2 + */ + export function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Change the file system timestamps of the object referenced by the supplied file + * descriptor. See {@link utimes}. + * @since v0.4.2 + */ + export function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Synchronous version of {@link futimes}. Returns `undefined`. + * @since v0.4.2 + */ + export function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other + * than a possible exception are given to the completion callback. + * @since v0.1.96 + */ + export function fsync(fd: number, callback: NoParamCallback): void; + export namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.96 + */ + export function fsyncSync(fd: number): void; + export interface WriteOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `buffer.byteLength - offset` + */ + length?: number | undefined; + /** + * @default null + */ + position?: number | undefined | null; + } + /** + * Write `buffer` to the file specified by `fd`. + * + * `offset` determines the part of the buffer to be written, and `length` is + * an integer specifying the number of bytes to write. + * + * `position` refers to the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). + * + * The callback will be given three arguments `(err, bytesWritten, buffer)` where `bytesWritten` specifies how many _bytes_ were written from `buffer`. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesWritten` and `buffer` properties. + * + * It is unsafe to use `fs.write()` multiple times on the same file without waiting + * for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v0.0.2 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + export function write( + fd: number, + buffer: TBuffer, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param options An object with the following properties: + * * `offset` The part of the buffer to be written. If not supplied, defaults to `0`. + * * `length` The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * * `position` The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write( + fd: number, + buffer: TBuffer, + options: WriteOptions, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + encoding: BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + */ + export function write( + fd: number, + string: string, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + export namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param options An object with the following properties: + * * `offset` The part of the buffer to be written. If not supplied, defaults to `0`. + * * `length` The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * * `position` The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + options?: WriteOptions, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link write}. + * @since v0.1.21 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + * @return The number of bytes written. + */ + export function writeSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset?: number | null, + length?: number | null, + position?: number | null, + ): number; + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function writeSync( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): number; + export type ReadPosition = number | bigint; + export interface ReadSyncOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `length of buffer` + */ + length?: number | undefined; + /** + * @default null + */ + position?: ReadPosition | null | undefined; + } + export interface ReadAsyncOptions extends ReadSyncOptions { + buffer?: TBuffer; + } + /** + * Read data from the file specified by `fd`. + * + * The callback is given the three arguments, `(err, bytesRead, buffer)`. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffer` properties. + * @since v0.0.2 + * @param buffer The buffer that the data will be written to. + * @param offset The position in `buffer` to write the data to. + * @param length The number of bytes to read. + * @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If + * `position` is an integer, the file position will be unchanged. + */ + export function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + /** + * Similar to the above `fs.read` function, this version takes an optional `options` object. + * If not otherwise specified in an `options` object, + * `buffer` defaults to `Buffer.alloc(16384)`, + * `offset` defaults to `0`, + * `length` defaults to `buffer.byteLength`, `- offset` as of Node 17.6.0 + * `position` defaults to `null` + * @since v12.17.0, 13.11.0 + */ + export function read( + fd: number, + options: ReadAsyncOptions, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + buffer: TBuffer, + options: ReadSyncOptions, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + buffer: TBuffer, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NodeJS.ArrayBufferView) => void, + ): void; + export namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__( + fd: number, + options: ReadAsyncOptions, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__(fd: number): Promise<{ + bytesRead: number; + buffer: NodeJS.ArrayBufferView; + }>; + } + /** + * Returns the number of `bytesRead`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link read}. + * @since v0.1.21 + * @param [position='null'] + */ + export function readSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset: number, + length: number, + position: ReadPosition | null, + ): number; + /** + * Similar to the above `fs.readSync` function, this version takes an optional `options` object. + * If no `options` object is specified, it will default with the above values. + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; + /** + * Asynchronously reads the entire contents of a file. + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', (err, data) => { + * if (err) throw err; + * console.log(data); + * }); + * ``` + * + * The callback is passed two arguments `(err, data)`, where `data` is the + * contents of the file. + * + * If no encoding is specified, then the raw buffer is returned. + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', 'utf8', callback); + * ``` + * + * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an + * error will be returned. On FreeBSD, a representation of the directory's contents + * will be returned. + * + * ```js + * import { readFile } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFile('', (err, data) => { + * // => [Error: EISDIR: illegal operation on a directory, read ] + * }); + * + * // FreeBSD + * readFile('', (err, data) => { + * // => null, + * }); + * ``` + * + * It is possible to abort an ongoing request using an `AbortSignal`. If a + * request is aborted the callback is called with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs'; + * + * const controller = new AbortController(); + * const signal = controller.signal; + * readFile(fileInfo[0].name, { signal }, (err, buf) => { + * // ... + * }); + * // When you want to abort the request + * controller.abort(); + * ``` + * + * The `fs.readFile()` function buffers the entire file. To minimize memory costs, + * when possible prefer streaming via `fs.createReadStream()`. + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * @since v0.1.29 + * @param path filename or file descriptor + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding?: null | undefined; + flag?: string | undefined; + } & Abortable) + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding: BufferEncoding; + flag?: string | undefined; + } & Abortable) + | BufferEncoding, + callback: (err: NodeJS.ErrnoException | null, data: string) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | (ObjectEncodingOptions & { + flag?: string | undefined; + } & Abortable) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: string | NonSharedBuffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + export function readFile( + path: PathOrFileDescriptor, + callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void, + ): void; + export namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): Promise; + } + /** + * Returns the contents of the `path`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readFile}. + * + * If the `encoding` option is specified then this function returns a + * string. Otherwise it returns a buffer. + * + * Similar to {@link readFile}, when the path is a directory, the behavior of `fs.readFileSync()` is platform-specific. + * + * ```js + * import { readFileSync } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFileSync(''); + * // => [Error: EISDIR: illegal operation on a directory, read ] + * + * // FreeBSD + * readFileSync(''); // => + * ``` + * @since v0.1.8 + * @param path filename or file descriptor + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): NonSharedBuffer; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): string; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): string | NonSharedBuffer; + export type WriteFileOptions = + | ( + & ObjectEncodingOptions + & Abortable + & { + mode?: Mode | undefined; + flag?: string | undefined; + flush?: boolean | undefined; + } + ) + | BufferEncoding + | null; + /** + * When `file` is a filename, asynchronously writes data to the file, replacing the + * file if it already exists. `data` can be a string or a buffer. + * + * When `file` is a file descriptor, the behavior is similar to calling `fs.write()` directly (which is recommended). See the notes below on using + * a file descriptor. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, (err) => { + * if (err) throw err; + * console.log('The file has been saved!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { writeFile } from 'node:fs'; + * + * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); + * ``` + * + * It is unsafe to use `fs.writeFile()` multiple times on the same file without + * waiting for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that + * performs multiple `write` calls internally to write the buffer passed to it. + * For performance sensitive code consider using {@link createWriteStream}. + * + * It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, { signal }, (err) => { + * // When a request is aborted - the callback is called with an AbortError + * }); + * // When the request should be aborted + * controller.abort(); + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFile( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function writeFile( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + callback: NoParamCallback, + ): void; + export namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): Promise; + } + /** + * Returns `undefined`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writeFile}. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFileSync( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', (err) => { + * if (err) throw err; + * console.log('The "data to append" was appended to file!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', 'utf8', callback); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { open, close, appendFile } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('message.txt', 'a', (err, fd) => { + * if (err) throw err; + * + * try { + * appendFile(fd, 'data to append', 'utf8', (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * throw err; + * } + * }); + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFile( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void; + export namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__( + file: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): Promise; + } + /** + * Synchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * try { + * appendFileSync('message.txt', 'data to append'); + * console.log('The "data to append" was appended to file!'); + * } catch (err) { + * // Handle the error + * } + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * appendFileSync('message.txt', 'data to append', 'utf8'); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { openSync, closeSync, appendFileSync } from 'node:fs'; + * + * let fd; + * + * try { + * fd = openSync('message.txt', 'a'); + * appendFileSync(fd, 'data to append', 'utf8'); + * } catch (err) { + * // Handle the error + * } finally { + * if (fd !== undefined) + * closeSync(fd); + * } + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFileSync( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): void; + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'node:fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export interface WatchFileOptions { + bigint?: boolean | undefined; + persistent?: boolean | undefined; + interval?: number | undefined; + } + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'node:fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint?: false | undefined; + }) + | undefined, + listener: StatsListener, + ): StatWatcher; + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint: true; + }) + | undefined, + listener: BigIntStatsListener, + ): StatWatcher; + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watchFile(filename: PathLike, listener: StatsListener): StatWatcher; + /** + * Stop watching for changes on `filename`. If `listener` is specified, only that + * particular listener is removed. Otherwise, _all_ listeners are removed, + * effectively stopping watching of `filename`. + * + * Calling `fs.unwatchFile()` with a filename that is not being watched is a + * no-op, not an error. + * + * Using {@link watch} is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()` when possible. + * @since v0.1.31 + * @param listener Optional, a listener previously attached using `fs.watchFile()` + */ + export function unwatchFile(filename: PathLike, listener?: StatsListener): void; + export function unwatchFile(filename: PathLike, listener?: BigIntStatsListener): void; + export interface WatchOptions extends Abortable { + encoding?: BufferEncoding | "buffer" | undefined; + persistent?: boolean | undefined; + recursive?: boolean | undefined; + } + export interface WatchOptionsWithBufferEncoding extends WatchOptions { + encoding: "buffer"; + } + export interface WatchOptionsWithStringEncoding extends WatchOptions { + encoding?: BufferEncoding | undefined; + } + export type WatchEventType = "rename" | "change"; + export type WatchListener = (event: WatchEventType, filename: T | null) => void; + export type StatsListener = (curr: Stats, prev: Stats) => void; + export type BigIntStatsListener = (curr: BigIntStats, prev: BigIntStats) => void; + /** + * Watch for changes on `filename`, where `filename` is either a file or a + * directory. + * + * The second argument is optional. If `options` is provided as a string, it + * specifies the `encoding`. Otherwise `options` should be passed as an object. + * + * The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file + * which triggered the event. + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of `eventType`. + * + * If a `signal` is passed, aborting the corresponding AbortController will close + * the returned `fs.FSWatcher`. + * @since v0.5.10 + * @param listener + */ + export function watch( + filename: PathLike, + options?: WatchOptionsWithStringEncoding | BufferEncoding | null, + listener?: WatchListener, + ): FSWatcher; + export function watch( + filename: PathLike, + options: WatchOptionsWithBufferEncoding | "buffer", + listener: WatchListener, + ): FSWatcher; + export function watch( + filename: PathLike, + options: WatchOptions | BufferEncoding | "buffer" | null, + listener: WatchListener, + ): FSWatcher; + export function watch(filename: PathLike, listener: WatchListener): FSWatcher; + /** + * Test whether or not the given path exists by checking with the file system. + * Then call the `callback` argument with either true or false: + * + * ```js + * import { exists } from 'node:fs'; + * + * exists('/etc/passwd', (e) => { + * console.log(e ? 'it exists' : 'no passwd!'); + * }); + * ``` + * + * **The parameters for this callback are not consistent with other Node.js** + * **callbacks.** Normally, the first parameter to a Node.js callback is an `err` parameter, optionally followed by other parameters. The `fs.exists()` callback + * has only one boolean parameter. This is one reason `fs.access()` is recommended + * instead of `fs.exists()`. + * + * Using `fs.exists()` to check for the existence of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file does not exist. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { exists, open, close } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * console.error('myfile already exists'); + * } else { + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { open, close, exists } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } else { + * console.error('myfile does not exist'); + * } + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for existence and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the existence of a file only if the file won't be + * used directly, for example when its existence is a signal from another + * process. + * @since v0.0.2 + * @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead. + */ + export function exists(path: PathLike, callback: (exists: boolean) => void): void; + /** @deprecated */ + export namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Returns `true` if the path exists, `false` otherwise. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link exists}. + * + * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback` parameter to `fs.exists()` accepts parameters that are inconsistent with other + * Node.js callbacks. `fs.existsSync()` does not use a callback. + * + * ```js + * import { existsSync } from 'node:fs'; + * + * if (existsSync('/etc/passwd')) + * console.log('The path exists.'); + * ``` + * @since v0.1.21 + */ + export function existsSync(path: PathLike): boolean; + export namespace constants { + // File Access Constants + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + // File Copy Constants + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + // File Open Constants + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + // File Type Constants + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + // File Mode Constants + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + const UV_FS_O_FILEMAP: number; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * The final argument, `callback`, is a callback function that is invoked with + * a possible error argument. If any of the accessibility checks fail, the error + * argument will be an `Error` object. The following examples check if `package.json` exists, and if it is readable or writable. + * + * ```js + * import { access, constants } from 'node:fs'; + * + * const file = 'package.json'; + * + * // Check if the file exists in the current directory. + * access(file, constants.F_OK, (err) => { + * console.log(`${file} ${err ? 'does not exist' : 'exists'}`); + * }); + * + * // Check if the file is readable. + * access(file, constants.R_OK, (err) => { + * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); + * }); + * + * // Check if the file is writable. + * access(file, constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); + * }); + * + * // Check if the file is readable and writable. + * access(file, constants.R_OK | constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`); + * }); + * ``` + * + * Do not use `fs.access()` to check for the accessibility of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file is not accessible. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * + * access('myfile', (err) => { + * if (!err) { + * console.error('myfile already exists'); + * return; + * } + * + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * access('myfile', (err) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for accessibility and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the accessibility of a file only if the file will not be + * used directly, for example when its accessibility is a signal from another + * process. + * + * On Windows, access-control policies (ACLs) on a directory may limit access to + * a file or directory. The `fs.access()` function, however, does not check the + * ACL and therefore may report that a path is accessible even if the ACL restricts + * the user from reading or writing to it. + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function access(path: PathLike, callback: NoParamCallback): void; + export namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + /** + * Synchronously tests a user's permissions for the file or directory specified + * by `path`. The `mode` argument is an optional integer that specifies the + * accessibility checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and + * `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, + * the method will return `undefined`. + * + * ```js + * import { accessSync, constants } from 'node:fs'; + * + * try { + * accessSync('etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can read/write'); + * } catch (err) { + * console.error('no access!'); + * } + * ``` + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function accessSync(path: PathLike, mode?: number): void; + interface StreamOptions { + flags?: string | undefined; + encoding?: BufferEncoding | undefined; + fd?: number | promises.FileHandle | undefined; + mode?: number | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + signal?: AbortSignal | null | undefined; + highWaterMark?: number | undefined; + } + interface FSImplementation { + open?: (...args: any[]) => any; + close?: (...args: any[]) => any; + } + interface CreateReadStreamFSImplementation extends FSImplementation { + read: (...args: any[]) => any; + } + interface CreateWriteStreamFSImplementation extends FSImplementation { + write: (...args: any[]) => any; + writev?: (...args: any[]) => any; + } + interface ReadStreamOptions extends StreamOptions { + fs?: CreateReadStreamFSImplementation | null | undefined; + end?: number | undefined; + } + interface WriteStreamOptions extends StreamOptions { + fs?: CreateWriteStreamFSImplementation | null | undefined; + flush?: boolean | undefined; + } + /** + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is + * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the + * current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use + * the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. + * + * If `fd` points to a character device that only supports blocking reads + * (such as keyboard or sound card), read operations do not finish until data is + * available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option, it is possible to override the corresponding `fs` implementations for `open`, `read`, and `close`. When providing the `fs` option, + * an override for `read` is required. If no `fd` is provided, an override for `open` is also required. If `autoClose` is `true`, an override for `close` is + * also required. + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * // Create a stream from some character device. + * const stream = createReadStream('/dev/input/event0'); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * `mode` sets the file mode (permission and sticky bits), but only if the + * file was created. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * createReadStream('sample.txt', { start: 90, end: 99 }); + * ``` + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` option to be set to `r+` rather than the + * default `w`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option it is possible to override the corresponding `fs` implementations for `open`, `write`, `writev`, and `close`. Overriding `write()` without `writev()` can reduce + * performance as some optimizations (`_writev()`) + * will be disabled. When providing the `fs` option, overrides for at least one of `write` and `writev` are required. If no `fd` option is supplied, an override + * for `open` is also required. If `autoClose` is `true`, an override for `close` is also required. + * + * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the `path` argument and will use the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s + * should be passed to `net.Socket`. + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createWriteStream(path: PathLike, options?: BufferEncoding | WriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other + * than a possible + * exception are given to the completion callback. + * @since v0.1.96 + */ + export function fdatasync(fd: number, callback: NoParamCallback): void; + export namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`. + * @since v0.1.96 + */ + export function fdatasyncSync(fd: number): void; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. No arguments other than a possible exception are given to the + * callback function. Node.js makes no guarantees about the atomicity of the copy + * operation. If an error occurs after the destination file has been opened for + * writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFile, constants } from 'node:fs'; + * + * function callback(err) { + * if (err) throw err; + * console.log('source.txt was copied to destination.txt'); + * } + * + * // destination.txt will be created or overwritten by default. + * copyFile('source.txt', 'destination.txt', callback); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; + export function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void; + export namespace copyFile { + function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise; + } + /** + * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. Returns `undefined`. Node.js makes no guarantees about the + * atomicity of the copy operation. If an error occurs after the destination file + * has been opened for writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFileSync, constants } from 'node:fs'; + * + * // destination.txt will be created or overwritten by default. + * copyFileSync('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; + /** + * Write an array of `ArrayBufferView`s to the file specified by `fd` using `writev()`. + * + * `position` is the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. + * + * The callback will be given three arguments: `err`, `bytesWritten`, and `buffers`. `bytesWritten` is how many bytes were written from `buffers`. + * + * If this method is `util.promisify()` ed, it returns a promise for an `Object` with `bytesWritten` and `buffers` properties. + * + * It is unsafe to use `fs.writev()` multiple times on the same file without + * waiting for the callback. For this scenario, use {@link createWriteStream}. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] + */ + export function writev( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export function writev( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position: number | null, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export interface WriteVResult { + bytesWritten: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace writev { + function __promisify__( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position?: number, + ): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writev}. + * @since v12.9.0 + * @param [position='null'] + * @return The number of bytes written. + */ + export function writevSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + /** + * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s + * using `readv()`. + * + * `position` is the offset from the beginning of the file from where data + * should be read. If `typeof position !== 'number'`, the data will be read + * from the current position. + * + * The callback will be given three arguments: `err`, `bytesRead`, and `buffers`. `bytesRead` is how many bytes were read from the file. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffers` properties. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + */ + export function readv( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export function readv( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position: number | null, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export interface ReadVResult { + bytesRead: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace readv { + function __promisify__( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position?: number, + ): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readv}. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + * @return The number of bytes read. + */ + export function readvSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + + export interface OpenAsBlobOptions { + /** + * An optional mime type for the blob. + * + * @default 'undefined' + */ + type?: string | undefined; + } + + /** + * Returns a `Blob` whose data is backed by the given file. + * + * The file must not be modified after the `Blob` is created. Any modifications + * will cause reading the `Blob` data to fail with a `DOMException` error. + * Synchronous stat operations on the file when the `Blob` is created, and before + * each read in order to detect whether the file data has been modified on disk. + * + * ```js + * import { openAsBlob } from 'node:fs'; + * + * const blob = await openAsBlob('the.file.txt'); + * const ab = await blob.arrayBuffer(); + * blob.stream(); + * ``` + * @since v19.8.0 + */ + export function openAsBlob(path: PathLike, options?: OpenAsBlobOptions): Promise; + + export interface OpenDirOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * Number of directory entries that are buffered + * internally when reading from the directory. Higher values lead to better + * performance but higher memory usage. + * @default 32 + */ + bufferSize?: number | undefined; + /** + * @default false + */ + recursive?: boolean; + } + /** + * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendirSync(path: PathLike, options?: OpenDirOptions): Dir; + /** + * Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for + * more details. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendir(path: PathLike, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export function opendir( + path: PathLike, + options: OpenDirOptions, + cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void, + ): void; + export namespace opendir { + function __promisify__(path: PathLike, options?: OpenDirOptions): Promise; + } + export interface BigIntStats extends StatsBase { + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + birthtimeNs: bigint; + } + export interface BigIntOptions { + bigint: true; + } + export interface StatOptions { + bigint?: boolean | undefined; + } + export interface StatSyncOptions extends StatOptions { + throwIfNoEntry?: boolean | undefined; + } + interface CopyOptionsBase { + /** + * Dereference symlinks + * @default false + */ + dereference?: boolean; + /** + * When `force` is `false`, and the destination + * exists, throw an error. + * @default false + */ + errorOnExist?: boolean; + /** + * Overwrite existing file or directory. _The copy + * operation will ignore errors if you set this to false and the destination + * exists. Use the `errorOnExist` option to change this behavior. + * @default true + */ + force?: boolean; + /** + * Modifiers for copy operation. See `mode` flag of {@link copyFileSync()} + */ + mode?: number; + /** + * When `true` timestamps from `src` will + * be preserved. + * @default false + */ + preserveTimestamps?: boolean; + /** + * Copy directories recursively. + * @default false + */ + recursive?: boolean; + /** + * When true, path resolution for symlinks will be skipped + * @default false + */ + verbatimSymlinks?: boolean; + } + export interface CopyOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean | Promise; + } + export interface CopySyncOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean; + } + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cp( + source: string | URL, + destination: string | URL, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + export function cp( + source: string | URL, + destination: string | URL, + opts: CopyOptions, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + /** + * Synchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void; + + interface _GlobOptions { + /** + * Current working directory. + * @default process.cwd() + */ + cwd?: string | URL | undefined; + /** + * `true` if the glob should return paths as `Dirent`s, `false` otherwise. + * @default false + * @since v22.2.0 + */ + withFileTypes?: boolean | undefined; + /** + * Function to filter out files/directories or a + * list of glob patterns to be excluded. If a function is provided, return + * `true` to exclude the item, `false` to include it. + * @default undefined + */ + exclude?: ((fileName: T) => boolean) | readonly string[] | undefined; + } + export interface GlobOptions extends _GlobOptions {} + export interface GlobOptionsWithFileTypes extends _GlobOptions { + withFileTypes: true; + } + export interface GlobOptionsWithoutFileTypes extends _GlobOptions { + withFileTypes?: false | undefined; + } + + /** + * Retrieves the files matching the specified pattern. + * + * ```js + * import { glob } from 'node:fs'; + * + * glob('*.js', (err, matches) => { + * if (err) throw err; + * console.log(matches); + * }); + * ``` + * @since v22.0.0 + */ + export function glob( + pattern: string | readonly string[], + callback: (err: NodeJS.ErrnoException | null, matches: string[]) => void, + ): void; + export function glob( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + callback: ( + err: NodeJS.ErrnoException | null, + matches: Dirent[], + ) => void, + ): void; + export function glob( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + callback: ( + err: NodeJS.ErrnoException | null, + matches: string[], + ) => void, + ): void; + export function glob( + pattern: string | readonly string[], + options: GlobOptions, + callback: ( + err: NodeJS.ErrnoException | null, + matches: Dirent[] | string[], + ) => void, + ): void; + /** + * ```js + * import { globSync } from 'node:fs'; + * + * console.log(globSync('*.js')); + * ``` + * @since v22.0.0 + * @returns paths of files that match the pattern. + */ + export function globSync(pattern: string | readonly string[]): string[]; + export function globSync( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + ): Dirent[]; + export function globSync( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + ): string[]; + export function globSync( + pattern: string | readonly string[], + options: GlobOptions, + ): Dirent[] | string[]; +} +declare module "node:fs" { + export * from "fs"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/fs/promises.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/fs/promises.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d3386aa494cf4186a5e88577f5430604aeffefa2 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/fs/promises.d.ts @@ -0,0 +1,1277 @@ +/** + * The `fs/promises` API provides asynchronous file system methods that return + * promises. + * + * The promise APIs use the underlying Node.js threadpool to perform file + * system operations off the event loop thread. These operations are not + * synchronized or threadsafe. Care must be taken when performing multiple + * concurrent modifications on the same file or data corruption may occur. + * @since v10.0.0 + */ +declare module "fs/promises" { + import { Abortable } from "node:events"; + import { Stream } from "node:stream"; + import { ReadableStream } from "node:stream/web"; + import { + BigIntStats, + BigIntStatsFs, + BufferEncodingOption, + constants as fsConstants, + CopyOptions, + Dir, + Dirent, + GlobOptions, + GlobOptionsWithFileTypes, + GlobOptionsWithoutFileTypes, + MakeDirectoryOptions, + Mode, + ObjectEncodingOptions, + OpenDirOptions, + OpenMode, + PathLike, + ReadPosition, + ReadStream, + ReadVResult, + RmDirOptions, + RmOptions, + StatFsOptions, + StatOptions, + Stats, + StatsFs, + TimeLike, + WatchEventType, + WatchOptions as _WatchOptions, + WriteStream, + WriteVResult, + } from "node:fs"; + import { Interface as ReadlineInterface } from "node:readline"; + interface FileChangeInfo { + eventType: WatchEventType; + filename: T | null; + } + interface FlagAndOpenMode { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } + interface FileReadResult { + bytesRead: number; + buffer: T; + } + interface FileReadOptions { + /** + * @default `Buffer.alloc(0xffff)` + */ + buffer?: T; + /** + * @default 0 + */ + offset?: number | null; + /** + * @default `buffer.byteLength` + */ + length?: number | null; + position?: ReadPosition | null; + } + interface CreateReadStreamOptions extends Abortable { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + end?: number | undefined; + highWaterMark?: number | undefined; + } + interface CreateWriteStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + highWaterMark?: number | undefined; + flush?: boolean | undefined; + } + interface ReadableWebStreamOptions { + autoClose?: boolean | undefined; + } + // TODO: Add `EventEmitter` close + interface FileHandle { + /** + * The numeric file descriptor managed by the {FileHandle} object. + * @since v10.0.0 + */ + readonly fd: number; + /** + * Alias of `filehandle.writeFile()`. + * + * When operating on file handles, the mode cannot be changed from what it was set + * to with `fsPromises.open()`. Therefore, this is equivalent to `filehandle.writeFile()`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + appendFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Changes the ownership of the file. A wrapper for [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html). + * @since v10.0.0 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + * @return Fulfills with `undefined` upon success. + */ + chown(uid: number, gid: number): Promise; + /** + * Modifies the permissions on the file. See [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html). + * @since v10.0.0 + * @param mode the file mode bit mask. + * @return Fulfills with `undefined` upon success. + */ + chmod(mode: Mode): Promise; + /** + * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 KiB. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `start` is + * omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from + * the current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If the `FileHandle` points to a character device that only supports blocking + * reads (such as keyboard or sound card), read operations do not finish until data + * is available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('/dev/input/event0'); + * // Create a stream from some character device. + * const stream = fd.createReadStream(); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('sample.txt'); + * fd.createReadStream({ start: 90, end: 99 }); + * ``` + * @since v16.11.0 + */ + createReadStream(options?: CreateReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` `open` option to be set to `r+` rather than + * the default `r`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * @since v16.11.0 + */ + createWriteStream(options?: CreateWriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. + * + * Unlike `filehandle.sync` this method does not flush modified metadata. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + datasync(): Promise; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + sync(): Promise; + /** + * Reads data from the file and stores that in the given buffer. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * @since v10.0.0 + * @param buffer A buffer that will be filled with the file data read. + * @param offset The location in the buffer at which to start filling. + * @param length The number of bytes to read. + * @param position The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an + * integer, the current file position will remain unchanged. + * @return Fulfills upon success with an object with two properties: + */ + read( + buffer: T, + offset?: number | null, + length?: number | null, + position?: ReadPosition | null, + ): Promise>; + read( + buffer: T, + options?: FileReadOptions, + ): Promise>; + read(options?: FileReadOptions): Promise>; + /** + * Returns a byte-oriented `ReadableStream` that may be used to read the file's + * contents. + * + * An error will be thrown if this method is called more than once or is called + * after the `FileHandle` is closed or closing. + * + * ```js + * import { + * open, + * } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const chunk of file.readableWebStream()) + * console.log(chunk); + * + * await file.close(); + * ``` + * + * While the `ReadableStream` will read the file to completion, it will not + * close the `FileHandle` automatically. User code must still call the`fileHandle.close()` method. + * @since v17.0.0 + */ + readableWebStream(options?: ReadableWebStreamOptions): ReadableStream; + /** + * Asynchronously reads the entire contents of a file. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support reading. + * + * If one or more `filehandle.read()` calls are made on a file handle and then a `filehandle.readFile()` call is made, the data will be read from the current + * position till the end of the file. It doesn't always read from the beginning + * of the file. + * @since v10.0.0 + * @return Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the + * data will be a string. + */ + readFile( + options?: + | ({ encoding?: null | undefined } & Abortable) + | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + */ + readFile( + options: + | ({ encoding: BufferEncoding } & Abortable) + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + */ + readFile( + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Convenience method to create a `readline` interface and stream over the file. + * See `filehandle.createReadStream()` for the options. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const line of file.readLines()) { + * console.log(line); + * } + * ``` + * @since v18.11.0 + */ + readLines(options?: CreateReadStreamOptions): ReadlineInterface; + /** + * @since v10.0.0 + * @return Fulfills with an {fs.Stats} for the file. + */ + stat( + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + stat( + opts: StatOptions & { + bigint: true; + }, + ): Promise; + stat(opts?: StatOptions): Promise; + /** + * Truncates the file. + * + * If the file was larger than `len` bytes, only the first `len` bytes will be + * retained in the file. + * + * The following example retains only the first four bytes of the file: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle = null; + * try { + * filehandle = await open('temp.txt', 'r+'); + * await filehandle.truncate(4); + * } finally { + * await filehandle?.close(); + * } + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + truncate(len?: number): Promise; + /** + * Change the file system timestamps of the object referenced by the `FileHandle` then fulfills the promise with no arguments upon success. + * @since v10.0.0 + */ + utimes(atime: TimeLike, mtime: TimeLike): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * The promise is fulfilled with no arguments upon success. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support writing. + * + * It is unsafe to use `filehandle.writeFile()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). + * + * If one or more `filehandle.write()` calls are made on a file handle and then a`filehandle.writeFile()` call is made, the data will be written from the + * current position till the end of the file. It doesn't always write from the + * beginning of the file. + * @since v10.0.0 + */ + writeFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Write `buffer` to the file. + * + * The promise is fulfilled with an object containing two properties: + * + * It is unsafe to use `filehandle.write()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). For this + * scenario, use `filehandle.createWriteStream()`. + * + * On Linux, positional writes do not work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v10.0.0 + * @param offset The start position from within `buffer` where the data to write begins. + * @param [length=buffer.byteLength - offset] The number of bytes from `buffer` to write. + * @param [position='null'] The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current + * position. See the POSIX pwrite(2) documentation for more detail. + */ + write( + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + buffer: TBuffer, + options?: { offset?: number; length?: number; position?: number }, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + data: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + /** + * Write an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s to the file. + * + * The promise is fulfilled with an object containing a two properties: + * + * It is unsafe to call `writev()` multiple times on the same file without waiting + * for the promise to be fulfilled (or rejected). + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current + * position. + */ + writev(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise; + /** + * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s + * @since v13.13.0, v12.17.0 + * @param [position='null'] The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. + * @return Fulfills upon success an object containing two properties: + */ + readv(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise; + /** + * Closes the file handle after waiting for any pending operation on the handle to + * complete. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle; + * try { + * filehandle = await open('thefile.txt', 'r'); + * } finally { + * await filehandle?.close(); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + close(): Promise; + /** + * Calls `filehandle.close()` and returns a promise that fulfills when the + * filehandle is closed. + * @since v20.4.0, v18.8.0 + */ + [Symbol.asyncDispose](): Promise; + } + const constants: typeof fsConstants; + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If the accessibility check is successful, the promise is fulfilled with no + * value. If any of the accessibility checks fail, the promise is rejected + * with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and + * written by the current process. + * + * ```js + * import { access, constants } from 'node:fs/promises'; + * + * try { + * await access('/etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can access'); + * } catch { + * console.error('cannot access'); + * } + * ``` + * + * Using `fsPromises.access()` to check for the accessibility of a file before + * calling `fsPromises.open()` is not recommended. Doing so introduces a race + * condition, since other processes may change the file's state between the two + * calls. Instead, user code should open/read/write the file directly and handle + * the error raised if the file is not accessible. + * @since v10.0.0 + * @param [mode=fs.constants.F_OK] + * @return Fulfills with `undefined` upon success. + */ + function access(path: PathLike, mode?: number): Promise; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. + * + * No guarantees are made about the atomicity of the copy operation. If an + * error occurs after the destination file has been opened for writing, an attempt + * will be made to remove the destination. + * + * ```js + * import { copyFile, constants } from 'node:fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * try { + * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * ``` + * @since v10.0.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. + * `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`) + * @return Fulfills with `undefined` upon success. + */ + function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise; + /** + * Opens a `FileHandle`. + * + * Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * @since v10.0.0 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created. + * @return Fulfills with a {FileHandle} object. + */ + function open(path: PathLike, flags?: string | number, mode?: Mode): Promise; + /** + * Renames `oldPath` to `newPath`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + /** + * Truncates (shortens or extends the length) of the content at `path` to `len` bytes. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + function truncate(path: PathLike, len?: number): Promise; + /** + * Removes the directory identified by `path`. + * + * Using `fsPromises.rmdir()` on a file (not a directory) results in the + * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rmdir(path: PathLike, options?: RmDirOptions): Promise; + /** + * Removes files and directories (modeled on the standard POSIX `rm` utility). + * @since v14.14.0 + * @return Fulfills with `undefined` upon success. + */ + function rm(path: PathLike, options?: RmOptions): Promise; + /** + * Asynchronously creates a directory. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fsPromises.mkdir()` when `path` is a directory + * that exists results in a + * rejection only when `recursive` is false. + * + * ```js + * import { mkdir } from 'node:fs/promises'; + * + * try { + * const projectFolder = new URL('./test/project/', import.meta.url); + * const createDir = await mkdir(projectFolder, { recursive: true }); + * + * console.log(`created ${createDir}`); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * @since v10.0.0 + * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. + */ + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + /** + * Reads the contents of a directory. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames. If the `encoding` is set to `'buffer'`, the filenames returned + * will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the returned array will contain `fs.Dirent` objects. + * + * ```js + * import { readdir } from 'node:fs/promises'; + * + * try { + * const files = await readdir(path); + * for (const file of files) + * console.log(file); + * } catch (err) { + * console.error(err); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a directory. If a URL is provided, it must use the `file:` protocol. + * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`. + */ + function readdir( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise[]>; + /** + * Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is + * fulfilled with the`linkString` upon success. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, the link path + * returned will be passed as a `Buffer` object. + * @since v10.0.0 + * @return Fulfills with the `linkString` upon success. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | string | null): Promise; + /** + * Creates a symbolic link. + * + * The `type` argument is only used on Windows platforms and can be one of `'dir'`, `'file'`, or `'junction'`. If the `type` argument is not a string, Node.js will + * autodetect `target` type and use `'file'` or `'dir'`. If the `target` does not + * exist, `'file'` will be used. Windows junction points require the destination + * path to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. Junction points on NTFS volumes + * can only point to directories. + * @since v10.0.0 + * @param [type='null'] + * @return Fulfills with `undefined` upon success. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + /** + * Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link, + * in which case the link itself is stat-ed, not the file that it refers to. + * Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail. + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`. + */ + function lstat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function lstat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function lstat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given `path`. + */ + function stat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function stat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function stat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v19.6.0, v18.15.0 + * @return Fulfills with the {fs.StatFs} object for the given `path`. + */ + function statfs( + path: PathLike, + opts?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function statfs( + path: PathLike, + opts: StatFsOptions & { + bigint: true; + }, + ): Promise; + function statfs(path: PathLike, opts?: StatFsOptions): Promise; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + /** + * If `path` refers to a symbolic link, then the link is removed without affecting + * the file or directory to which that link refers. If the `path` refers to a file + * path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function unlink(path: PathLike): Promise; + /** + * Changes the permissions of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the permissions on a symbolic link. + * + * This method is only implemented on macOS. + * @deprecated Since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the ownership on a symbolic link. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a + * symbolic link, then the link is not dereferenced: instead, the timestamps of + * the symbolic link itself are changed. + * @since v14.5.0, v12.19.0 + * @return Fulfills with `undefined` upon success. + */ + function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Changes the ownership of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time, `Date`s, or a + * numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Determines the actual location of `path` using the same semantics as the `fs.realpath.native()` function. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path. If the `encoding` is set to `'buffer'`, the path returned will be + * passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v10.0.0 + * @return Fulfills with the resolved path upon success. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath( + path: PathLike, + options?: ObjectEncodingOptions | BufferEncoding | null, + ): Promise; + /** + * Creates a unique temporary directory. A unique directory name is generated by + * appending six random characters to the end of the provided `prefix`. Due to + * platform inconsistencies, avoid trailing `X` characters in `prefix`. Some + * platforms, notably the BSDs, can return more than six random characters, and + * replace trailing `X` characters in `prefix` with random characters. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs/promises'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * try { + * await mkdtemp(join(tmpdir(), 'foo-')); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * The `fsPromises.mkdtemp()` method will append the six randomly selected + * characters directly to the `prefix` string. For instance, given a directory `/tmp`, if the intention is to create a temporary directory _within_ `/tmp`, the `prefix` must end with a trailing + * platform-specific path separator + * (`import { sep } from 'node:path'`). + * @since v10.0.0 + * @return Fulfills with a string containing the file system path of the newly created temporary directory. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * If `options` is a string, then it specifies the encoding. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * Any specified `FileHandle` has to support writing. + * + * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file + * without waiting for the promise to be settled. + * + * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience + * method that performs multiple `write` calls internally to write the buffer + * passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`. + * + * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs/promises'; + * import { Buffer } from 'node:buffer'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * const promise = writeFile('message.txt', data, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v10.0.0 + * @param file filename or `FileHandle` + * @return Fulfills with `undefined` upon success. + */ + function writeFile( + file: PathLike | FileHandle, + data: + | string + | NodeJS.ArrayBufferView + | Iterable + | AsyncIterable + | Stream, + options?: + | (ObjectEncodingOptions & { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + /** + * If all data is successfully written to the file, and `flush` + * is `true`, `filehandle.sync()` is used to flush the data. + * @default false + */ + flush?: boolean | undefined; + } & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * The `path` may be specified as a `FileHandle` that has been opened + * for appending (using `fsPromises.open()`). + * @since v10.0.0 + * @param path filename or {FileHandle} + * @return Fulfills with `undefined` upon success. + */ + function appendFile( + path: PathLike | FileHandle, + data: string | Uint8Array, + options?: (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined }) | BufferEncoding | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * + * If no encoding is specified (using `options.encoding`), the data is returned + * as a `Buffer` object. Otherwise, the data will be a string. + * + * If `options` is a string, then it specifies the encoding. + * + * When the `path` is a directory, the behavior of `fsPromises.readFile()` is + * platform-specific. On macOS, Linux, and Windows, the promise will be rejected + * with an error. On FreeBSD, a representation of the directory's contents will be + * returned. + * + * An example of reading a `package.json` file located in the same directory of the + * running code: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * try { + * const filePath = new URL('./package.json', import.meta.url); + * const contents = await readFile(filePath, { encoding: 'utf8' }); + * console.log(contents); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * + * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a + * request is aborted the promise returned is rejected with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const promise = readFile(fileName, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * + * Any specified `FileHandle` has to support reading. + * @since v10.0.0 + * @param path filename or `FileHandle` + * @return Fulfills with the contents of the file. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ({ + encoding?: null | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options: + | ({ + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ( + & ObjectEncodingOptions + & Abortable + & { + flag?: OpenMode | undefined; + } + ) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * + * Example using async iteration: + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + * @return Fulfills with an {fs.Dir}. + */ + function opendir(path: PathLike, options?: OpenDirOptions): Promise; + interface WatchOptions extends _WatchOptions { + maxQueue?: number | undefined; + overflow?: "ignore" | "throw" | undefined; + } + interface WatchOptionsWithBufferEncoding extends WatchOptions { + encoding: "buffer"; + } + interface WatchOptionsWithStringEncoding extends WatchOptions { + encoding?: BufferEncoding | undefined; + } + /** + * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. + * + * ```js + * import { watch } from 'node:fs/promises'; + * + * const ac = new AbortController(); + * const { signal } = ac; + * setTimeout(() => ac.abort(), 10000); + * + * (async () => { + * try { + * const watcher = watch(__filename, { signal }); + * for await (const event of watcher) + * console.log(event); + * } catch (err) { + * if (err.name === 'AbortError') + * return; + * throw err; + * } + * })(); + * ``` + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`. + * @since v15.9.0, v14.18.0 + * @return of objects with the properties: + */ + function watch( + filename: PathLike, + options?: WatchOptionsWithStringEncoding | BufferEncoding, + ): NodeJS.AsyncIterator>; + function watch( + filename: PathLike, + options: WatchOptionsWithBufferEncoding | "buffer", + ): NodeJS.AsyncIterator>; + function watch( + filename: PathLike, + options: WatchOptions | BufferEncoding | "buffer", + ): NodeJS.AsyncIterator>; + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + * @return Fulfills with `undefined` upon success. + */ + function cp(source: string | URL, destination: string | URL, opts?: CopyOptions): Promise; + /** + * ```js + * import { glob } from 'node:fs/promises'; + * + * for await (const entry of glob('*.js')) + * console.log(entry); + * ``` + * @since v22.0.0 + * @returns An AsyncIterator that yields the paths of files + * that match the pattern. + */ + function glob(pattern: string | readonly string[]): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptionsWithFileTypes, + ): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptionsWithoutFileTypes, + ): NodeJS.AsyncIterator; + function glob( + pattern: string | readonly string[], + options: GlobOptions, + ): NodeJS.AsyncIterator; +} +declare module "node:fs/promises" { + export * from "fs/promises"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/globals.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/globals.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..143ba4ea0bee09220afae53a84301000c2ac4695 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/globals.d.ts @@ -0,0 +1,367 @@ +export {}; // Make this a module + +// #region Fetch and friends +// Conditional type aliases, used at the end of this file. +// Will either be empty if lib.dom (or lib.webworker) is included, or the undici version otherwise. +type _Request = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Request; +type _Response = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Response; +type _FormData = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").FormData; +type _Headers = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Headers; +type _MessageEvent = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").MessageEvent; +type _RequestInit = typeof globalThis extends { onmessage: any } ? {} + : import("undici-types").RequestInit; +type _ResponseInit = typeof globalThis extends { onmessage: any } ? {} + : import("undici-types").ResponseInit; +type _WebSocket = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").WebSocket; +type _EventSource = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").EventSource; +type _CloseEvent = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").CloseEvent; +// #endregion Fetch and friends + +// Conditional type definitions for webstorage interface, which conflicts with lib.dom otherwise. +type _Storage = typeof globalThis extends { onabort: any } ? {} : { + readonly length: number; + clear(): void; + getItem(key: string): string | null; + key(index: number): string | null; + removeItem(key: string): void; + setItem(key: string, value: string): void; + [key: string]: any; +}; + +// #region DOMException +type _DOMException = typeof globalThis extends { onmessage: any } ? {} : NodeDOMException; +interface NodeDOMException extends Error { + readonly code: number; + readonly message: string; + readonly name: string; + readonly INDEX_SIZE_ERR: 1; + readonly DOMSTRING_SIZE_ERR: 2; + readonly HIERARCHY_REQUEST_ERR: 3; + readonly WRONG_DOCUMENT_ERR: 4; + readonly INVALID_CHARACTER_ERR: 5; + readonly NO_DATA_ALLOWED_ERR: 6; + readonly NO_MODIFICATION_ALLOWED_ERR: 7; + readonly NOT_FOUND_ERR: 8; + readonly NOT_SUPPORTED_ERR: 9; + readonly INUSE_ATTRIBUTE_ERR: 10; + readonly INVALID_STATE_ERR: 11; + readonly SYNTAX_ERR: 12; + readonly INVALID_MODIFICATION_ERR: 13; + readonly NAMESPACE_ERR: 14; + readonly INVALID_ACCESS_ERR: 15; + readonly VALIDATION_ERR: 16; + readonly TYPE_MISMATCH_ERR: 17; + readonly SECURITY_ERR: 18; + readonly NETWORK_ERR: 19; + readonly ABORT_ERR: 20; + readonly URL_MISMATCH_ERR: 21; + readonly QUOTA_EXCEEDED_ERR: 22; + readonly TIMEOUT_ERR: 23; + readonly INVALID_NODE_TYPE_ERR: 24; + readonly DATA_CLONE_ERR: 25; +} +interface NodeDOMExceptionConstructor { + prototype: DOMException; + new(message?: string, nameOrOptions?: string | { name?: string; cause?: unknown }): DOMException; + readonly INDEX_SIZE_ERR: 1; + readonly DOMSTRING_SIZE_ERR: 2; + readonly HIERARCHY_REQUEST_ERR: 3; + readonly WRONG_DOCUMENT_ERR: 4; + readonly INVALID_CHARACTER_ERR: 5; + readonly NO_DATA_ALLOWED_ERR: 6; + readonly NO_MODIFICATION_ALLOWED_ERR: 7; + readonly NOT_FOUND_ERR: 8; + readonly NOT_SUPPORTED_ERR: 9; + readonly INUSE_ATTRIBUTE_ERR: 10; + readonly INVALID_STATE_ERR: 11; + readonly SYNTAX_ERR: 12; + readonly INVALID_MODIFICATION_ERR: 13; + readonly NAMESPACE_ERR: 14; + readonly INVALID_ACCESS_ERR: 15; + readonly VALIDATION_ERR: 16; + readonly TYPE_MISMATCH_ERR: 17; + readonly SECURITY_ERR: 18; + readonly NETWORK_ERR: 19; + readonly ABORT_ERR: 20; + readonly URL_MISMATCH_ERR: 21; + readonly QUOTA_EXCEEDED_ERR: 22; + readonly TIMEOUT_ERR: 23; + readonly INVALID_NODE_TYPE_ERR: 24; + readonly DATA_CLONE_ERR: 25; +} +// #endregion DOMException + +declare global { + var global: typeof globalThis; + + var process: NodeJS.Process; + var console: Console; + + interface ErrorConstructor { + /** + * Creates a `.stack` property on `targetObject`, which when accessed returns + * a string representing the location in the code at which + * `Error.captureStackTrace()` was called. + * + * ```js + * const myObject = {}; + * Error.captureStackTrace(myObject); + * myObject.stack; // Similar to `new Error().stack` + * ``` + * + * The first line of the trace will be prefixed with + * `${myObject.name}: ${myObject.message}`. + * + * The optional `constructorOpt` argument accepts a function. If given, all frames + * above `constructorOpt`, including `constructorOpt`, will be omitted from the + * generated stack trace. + * + * The `constructorOpt` argument is useful for hiding implementation + * details of error generation from the user. For instance: + * + * ```js + * function a() { + * b(); + * } + * + * function b() { + * c(); + * } + * + * function c() { + * // Create an error without stack trace to avoid calculating the stack trace twice. + * const { stackTraceLimit } = Error; + * Error.stackTraceLimit = 0; + * const error = new Error(); + * Error.stackTraceLimit = stackTraceLimit; + * + * // Capture the stack trace above function b + * Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace + * throw error; + * } + * + * a(); + * ``` + */ + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + /** + * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces + */ + prepareStackTrace(err: Error, stackTraces: NodeJS.CallSite[]): any; + /** + * The `Error.stackTraceLimit` property specifies the number of stack frames + * collected by a stack trace (whether generated by `new Error().stack` or + * `Error.captureStackTrace(obj)`). + * + * The default value is `10` but may be set to any valid JavaScript number. Changes + * will affect any stack trace captured _after_ the value has been changed. + * + * If set to a non-number value, or set to a negative number, stack traces will + * not capture any frames. + */ + stackTraceLimit: number; + } + + /** + * Enable this API with the `--expose-gc` CLI flag. + */ + var gc: NodeJS.GCFunction | undefined; + + namespace NodeJS { + interface CallSite { + getColumnNumber(): number | null; + getEnclosingColumnNumber(): number | null; + getEnclosingLineNumber(): number | null; + getEvalOrigin(): string | undefined; + getFileName(): string | null; + getFunction(): Function | undefined; + getFunctionName(): string | null; + getLineNumber(): number | null; + getMethodName(): string | null; + getPosition(): number; + getPromiseIndex(): number | null; + getScriptHash(): string; + getScriptNameOrSourceURL(): string | null; + getThis(): unknown; + getTypeName(): string | null; + isAsync(): boolean; + isConstructor(): boolean; + isEval(): boolean; + isNative(): boolean; + isPromiseAll(): boolean; + isToplevel(): boolean; + } + + interface ErrnoException extends Error { + errno?: number | undefined; + code?: string | undefined; + path?: string | undefined; + syscall?: string | undefined; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: BufferEncoding): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean | undefined }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): this; + end(data: string | Uint8Array, cb?: () => void): this; + end(str: string, encoding?: BufferEncoding, cb?: () => void): this; + } + + interface ReadWriteStream extends ReadableStream, WritableStream {} + + interface RefCounted { + ref(): this; + unref(): this; + } + + interface Dict { + [key: string]: T | undefined; + } + + interface ReadOnlyDict { + readonly [key: string]: T | undefined; + } + + interface GCFunction { + (minor?: boolean): void; + (options: NodeJS.GCOptions & { execution: "async" }): Promise; + (options: NodeJS.GCOptions): void; + } + + interface GCOptions { + execution?: "sync" | "async" | undefined; + flavor?: "regular" | "last-resort" | undefined; + type?: "major-snapshot" | "major" | "minor" | undefined; + filename?: string | undefined; + } + + /** An iterable iterator returned by the Node.js API. */ + interface Iterator extends IteratorObject { + [Symbol.iterator](): NodeJS.Iterator; + } + + /** An async iterable iterator returned by the Node.js API. */ + interface AsyncIterator extends AsyncIteratorObject { + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + } + } + + // Global DOM types + + interface DOMException extends _DOMException {} + var DOMException: typeof globalThis extends { onmessage: any; DOMException: infer T } ? T + : NodeDOMExceptionConstructor; + + // #region AbortController + interface AbortController { + readonly signal: AbortSignal; + abort(reason?: any): void; + } + var AbortController: typeof globalThis extends { onmessage: any; AbortController: infer T } ? T + : { + prototype: AbortController; + new(): AbortController; + }; + + interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: ((this: AbortSignal, ev: Event) => any) | null; + readonly reason: any; + throwIfAborted(): void; + } + var AbortSignal: typeof globalThis extends { onmessage: any; AbortSignal: infer T } ? T + : { + prototype: AbortSignal; + new(): AbortSignal; + abort(reason?: any): AbortSignal; + any(signals: AbortSignal[]): AbortSignal; + timeout(milliseconds: number): AbortSignal; + }; + // #endregion AbortController + + // #region Storage + interface Storage extends _Storage {} + // Conditional on `onabort` rather than `onmessage`, in order to exclude lib.webworker + var Storage: typeof globalThis extends { onabort: any; Storage: infer T } ? T + : { + prototype: Storage; + new(): Storage; + }; + + var localStorage: Storage; + var sessionStorage: Storage; + // #endregion Storage + + // #region fetch + interface RequestInit extends _RequestInit {} + + function fetch( + input: string | URL | globalThis.Request, + init?: RequestInit, + ): Promise; + + interface Request extends _Request {} + var Request: typeof globalThis extends { + onmessage: any; + Request: infer T; + } ? T + : typeof import("undici-types").Request; + + interface ResponseInit extends _ResponseInit {} + + interface Response extends _Response {} + var Response: typeof globalThis extends { + onmessage: any; + Response: infer T; + } ? T + : typeof import("undici-types").Response; + + interface FormData extends _FormData {} + var FormData: typeof globalThis extends { + onmessage: any; + FormData: infer T; + } ? T + : typeof import("undici-types").FormData; + + interface Headers extends _Headers {} + var Headers: typeof globalThis extends { + onmessage: any; + Headers: infer T; + } ? T + : typeof import("undici-types").Headers; + + interface MessageEvent extends _MessageEvent {} + var MessageEvent: typeof globalThis extends { + onmessage: any; + MessageEvent: infer T; + } ? T + : typeof import("undici-types").MessageEvent; + + interface WebSocket extends _WebSocket {} + var WebSocket: typeof globalThis extends { onmessage: any; WebSocket: infer T } ? T + : typeof import("undici-types").WebSocket; + + interface EventSource extends _EventSource {} + var EventSource: typeof globalThis extends { onmessage: any; EventSource: infer T } ? T + : typeof import("undici-types").EventSource; + + interface CloseEvent extends _CloseEvent {} + var CloseEvent: typeof globalThis extends { onmessage: any; CloseEvent: infer T } ? T + : typeof import("undici-types").CloseEvent; + // #endregion fetch +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/globals.typedarray.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/globals.typedarray.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6d5c9527e847a7b1d6335ed201818331a9273da3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/globals.typedarray.d.ts @@ -0,0 +1,22 @@ +export {}; // Make this a module + +declare global { + namespace NodeJS { + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float16Array + | Float32Array + | Float64Array; + type ArrayBufferView = + | TypedArray + | DataView; + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/http.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/http.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4df8fad912fdae09a8628792d79d83cb0c45a69b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/http.d.ts @@ -0,0 +1,2046 @@ +/** + * To use the HTTP server and client one must import the `node:http` module. + * + * The HTTP interfaces in Node.js are designed to support many features + * of the protocol which have been traditionally difficult to use. + * In particular, large, possibly chunk-encoded, messages. The interface is + * careful to never buffer entire requests or responses, so the + * user is able to stream data. + * + * HTTP message headers are represented by an object like this: + * + * ```json + * { "content-length": "123", + * "content-type": "text/plain", + * "connection": "keep-alive", + * "host": "example.com", + * "accept": "*" } + * ``` + * + * Keys are lowercased. Values are not modified. + * + * In order to support the full spectrum of possible HTTP applications, the Node.js + * HTTP API is very low-level. It deals with stream handling and message + * parsing only. It parses a message into headers and body but it does not + * parse the actual headers or the body. + * + * See `message.headers` for details on how duplicate headers are handled. + * + * The raw headers as they were received are retained in the `rawHeaders` property, which is an array of `[key, value, key2, value2, ...]`. For + * example, the previous message header object might have a `rawHeaders` list like the following: + * + * ```js + * [ 'ConTent-Length', '123456', + * 'content-LENGTH', '123', + * 'content-type', 'text/plain', + * 'CONNECTION', 'keep-alive', + * 'Host', 'example.com', + * 'accepT', '*' ] + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/http.js) + */ +declare module "http" { + import * as stream from "node:stream"; + import { URL } from "node:url"; + import { LookupOptions } from "node:dns"; + import { EventEmitter } from "node:events"; + import { LookupFunction, Server as NetServer, Socket, TcpSocketConnectOpts } from "node:net"; + // incoming headers will never contain number + interface IncomingHttpHeaders extends NodeJS.Dict { + accept?: string | undefined; + "accept-encoding"?: string | undefined; + "accept-language"?: string | undefined; + "accept-patch"?: string | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + "alt-svc"?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + connection?: string | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-type"?: string | undefined; + cookie?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + location?: string | undefined; + origin?: string | undefined; + pragma?: string | undefined; + "proxy-authenticate"?: string | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "retry-after"?: string | undefined; + "sec-fetch-site"?: string | undefined; + "sec-fetch-mode"?: string | undefined; + "sec-fetch-user"?: string | undefined; + "sec-fetch-dest"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | undefined; + "sec-websocket-version"?: string | undefined; + "set-cookie"?: string[] | undefined; + "strict-transport-security"?: string | undefined; + tk?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + upgrade?: string | undefined; + "user-agent"?: string | undefined; + vary?: string | undefined; + via?: string | undefined; + warning?: string | undefined; + "www-authenticate"?: string | undefined; + } + // outgoing headers allows numbers (as they are converted internally to strings) + type OutgoingHttpHeader = number | string | string[]; + interface OutgoingHttpHeaders extends NodeJS.Dict { + accept?: string | string[] | undefined; + "accept-charset"?: string | string[] | undefined; + "accept-encoding"?: string | string[] | undefined; + "accept-language"?: string | string[] | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + "cdn-cache-control"?: string | undefined; + connection?: string | string[] | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | number | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-security-policy"?: string | undefined; + "content-security-policy-report-only"?: string | undefined; + "content-type"?: string | undefined; + cookie?: string | string[] | undefined; + dav?: string | string[] | undefined; + dnt?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-range"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + link?: string | string[] | undefined; + location?: string | undefined; + "max-forwards"?: string | undefined; + origin?: string | undefined; + pragma?: string | string[] | undefined; + "proxy-authenticate"?: string | string[] | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + "public-key-pins-report-only"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "referrer-policy"?: string | undefined; + refresh?: string | undefined; + "retry-after"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | string[] | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | string[] | undefined; + "sec-websocket-version"?: string | undefined; + server?: string | undefined; + "set-cookie"?: string | string[] | undefined; + "strict-transport-security"?: string | undefined; + te?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + "user-agent"?: string | undefined; + upgrade?: string | undefined; + "upgrade-insecure-requests"?: string | undefined; + vary?: string | undefined; + via?: string | string[] | undefined; + warning?: string | undefined; + "www-authenticate"?: string | string[] | undefined; + "x-content-type-options"?: string | undefined; + "x-dns-prefetch-control"?: string | undefined; + "x-frame-options"?: string | undefined; + "x-xss-protection"?: string | undefined; + } + interface ClientRequestArgs { + _defaultAgent?: Agent | undefined; + agent?: Agent | boolean | undefined; + auth?: string | null | undefined; + createConnection?: + | (( + options: ClientRequestArgs, + oncreate: (err: Error | null, socket: stream.Duplex) => void, + ) => stream.Duplex | null | undefined) + | undefined; + defaultPort?: number | string | undefined; + family?: number | undefined; + headers?: OutgoingHttpHeaders | readonly string[] | undefined; + hints?: LookupOptions["hints"]; + host?: string | null | undefined; + hostname?: string | null | undefined; + insecureHTTPParser?: boolean | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + lookup?: LookupFunction | undefined; + /** + * @default 16384 + */ + maxHeaderSize?: number | undefined; + method?: string | undefined; + path?: string | null | undefined; + port?: number | string | null | undefined; + protocol?: string | null | undefined; + setDefaultHeaders?: boolean | undefined; + setHost?: boolean | undefined; + signal?: AbortSignal | undefined; + socketPath?: string | undefined; + timeout?: number | undefined; + uniqueHeaders?: Array | undefined; + joinDuplicateHeaders?: boolean; + } + interface ServerOptions< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > { + /** + * Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. + */ + IncomingMessage?: Request | undefined; + /** + * Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`. + */ + ServerResponse?: Response | undefined; + /** + * Sets the timeout value in milliseconds for receiving the entire request from the client. + * @see Server.requestTimeout for more information. + * @default 300000 + * @since v18.0.0 + */ + requestTimeout?: number | undefined; + /** + * It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates. + * @default false + * @since v18.14.0 + */ + joinDuplicateHeaders?: boolean; + /** + * The number of milliseconds of inactivity a server needs to wait for additional incoming data, + * after it has finished writing the last response, before a socket will be destroyed. + * @see Server.keepAliveTimeout for more information. + * @default 5000 + * @since v18.0.0 + */ + keepAliveTimeout?: number | undefined; + /** + * Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests. + * @default 30000 + */ + connectionsCheckingInterval?: number | undefined; + /** + * Sets the timeout value in milliseconds for receiving the complete HTTP headers from the client. + * See {@link Server.headersTimeout} for more information. + * @default 60000 + * @since 18.0.0 + */ + headersTimeout?: number | undefined; + /** + * Optionally overrides all `socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`. + * Default: @see stream.getDefaultHighWaterMark(). + * @since v20.1.0 + */ + highWaterMark?: number | undefined; + /** + * Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. + * Using the insecure parser should be avoided. + * See --insecure-http-parser for more information. + * @default false + */ + insecureHTTPParser?: boolean | undefined; + /** + * Optionally overrides the value of `--max-http-header-size` for requests received by + * this server, i.e. the maximum length of request headers in bytes. + * @default 16384 + * @since v13.3.0 + */ + maxHeaderSize?: number | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default true + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it forces the server to respond with a 400 (Bad Request) status code + * to any HTTP/1.1 request message that lacks a Host header (as mandated by the specification). + * @default true + * @since 20.0.0 + */ + requireHostHeader?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + /** + * A list of response headers that should be sent only once. + * If the header's value is an array, the items will be joined using `; `. + */ + uniqueHeaders?: Array | undefined; + /** + * If set to `true`, an error is thrown when writing to an HTTP response which does not have a body. + * @default false + * @since v18.17.0, v20.2.0 + */ + rejectNonStandardBodyWrites?: boolean | undefined; + } + type RequestListener< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > = (req: InstanceType, res: InstanceType & { req: InstanceType }) => void; + /** + * @since v0.1.17 + */ + class Server< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + > extends NetServer { + constructor(requestListener?: RequestListener); + constructor(options: ServerOptions, requestListener?: RequestListener); + /** + * Sets the timeout value for sockets, and emits a `'timeout'` event on + * the Server object, passing the socket as an argument, if a timeout + * occurs. + * + * If there is a `'timeout'` event listener on the Server object, then it + * will be called with the timed-out socket as an argument. + * + * By default, the Server does not timeout sockets. However, if a callback + * is assigned to the Server's `'timeout'` event, timeouts must be handled + * explicitly. + * @since v0.9.12 + * @param [msecs=0 (no timeout)] + */ + setTimeout(msecs?: number, callback?: (socket: Socket) => void): this; + setTimeout(callback: (socket: Socket) => void): this; + /** + * Limits maximum incoming headers count. If set to 0, no limit will be applied. + * @since v0.7.0 + */ + maxHeadersCount: number | null; + /** + * The maximum number of requests socket can handle + * before closing keep alive connection. + * + * A value of `0` will disable the limit. + * + * When the limit is reached it will set the `Connection` header value to `close`, + * but will not actually close the connection, subsequent requests sent + * after the limit is reached will get `503 Service Unavailable` as a response. + * @since v16.10.0 + */ + maxRequestsPerSocket: number | null; + /** + * The number of milliseconds of inactivity before a socket is presumed + * to have timed out. + * + * A value of `0` will disable the timeout behavior on incoming connections. + * + * The socket timeout logic is set up on connection, so changing this + * value only affects new connections to the server, not any existing connections. + * @since v0.9.12 + */ + timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP + * headers. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v11.3.0, v10.14.0 + */ + headersTimeout: number; + /** + * The number of milliseconds of inactivity a server needs to wait for additional + * incoming data, after it has finished writing the last response, before a socket + * will be destroyed. If the server receives new data before the keep-alive + * timeout has fired, it will reset the regular inactivity timeout, i.e., `server.timeout`. + * + * A value of `0` will disable the keep-alive timeout behavior on incoming + * connections. + * A value of `0` makes the http server behave similarly to Node.js versions prior + * to 8.0.0, which did not have a keep-alive timeout. + * + * The socket timeout logic is set up on connection, so changing this value only + * affects new connections to the server, not any existing connections. + * @since v8.0.0 + */ + keepAliveTimeout: number; + /** + * Sets the timeout value in milliseconds for receiving the entire request from + * the client. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v14.11.0 + */ + requestTimeout: number; + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request + * or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "checkContinue", listener: RequestListener): this; + addListener(event: "checkExpectation", listener: RequestListener): this; + addListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + addListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + addListener(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + addListener(event: "request", listener: RequestListener): this; + addListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit( + event: "checkContinue", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "clientError", err: Error, socket: stream.Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; + emit(event: "dropRequest", req: InstanceType, socket: stream.Duplex): boolean; + emit( + event: "request", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "upgrade", req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "checkContinue", listener: RequestListener): this; + on(event: "checkExpectation", listener: RequestListener): this; + on(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + on(event: "connect", listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + on(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + on(event: "request", listener: RequestListener): this; + on(event: "upgrade", listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "checkContinue", listener: RequestListener): this; + once(event: "checkExpectation", listener: RequestListener): this; + once(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + once( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + once(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + once(event: "request", listener: RequestListener): this; + once( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "checkContinue", listener: RequestListener): this; + prependListener(event: "checkExpectation", listener: RequestListener): this; + prependListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + prependListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependListener( + event: "dropRequest", + listener: (req: InstanceType, socket: stream.Duplex) => void, + ): this; + prependListener(event: "request", listener: RequestListener): this; + prependListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "checkContinue", listener: RequestListener): this; + prependOnceListener(event: "checkExpectation", listener: RequestListener): this; + prependOnceListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + prependOnceListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependOnceListener( + event: "dropRequest", + listener: (req: InstanceType, socket: stream.Duplex) => void, + ): this; + prependOnceListener(event: "request", listener: RequestListener): this; + prependOnceListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + } + /** + * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract outgoing message from + * the perspective of the participants of an HTTP transaction. + * @since v0.1.17 + */ + class OutgoingMessage extends stream.Writable { + readonly req: Request; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + /** + * @deprecated Use `writableEnded` instead. + */ + finished: boolean; + /** + * Read-only. `true` if the headers were sent, otherwise `false`. + * @since v0.9.3 + */ + readonly headersSent: boolean; + /** + * Alias of `outgoingMessage.socket`. + * @since v0.3.0 + * @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead. + */ + readonly connection: Socket | null; + /** + * Reference to the underlying socket. Usually, users will not want to access + * this property. + * + * After calling `outgoingMessage.end()`, this property will be nulled. + * @since v0.3.0 + */ + readonly socket: Socket | null; + constructor(); + /** + * Once a socket is associated with the message and is connected, `socket.setTimeout()` will be called with `msecs` as the first parameter. + * @since v0.9.12 + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * Sets a single header value. If the header already exists in the to-be-sent + * headers, its value will be replaced. Use an array of strings to send multiple + * headers with the same name. + * @since v0.4.0 + * @param name Header name + * @param value Header value + */ + setHeader(name: string, value: number | string | readonly string[]): this; + /** + * Sets multiple header values for implicit headers. headers must be an instance of + * `Headers` or `Map`, if a header already exists in the to-be-sent headers, its + * value will be replaced. + * + * ```js + * const headers = new Headers({ foo: 'bar' }); + * outgoingMessage.setHeaders(headers); + * ``` + * + * or + * + * ```js + * const headers = new Map([['foo', 'bar']]); + * outgoingMessage.setHeaders(headers); + * ``` + * + * When headers have been set with `outgoingMessage.setHeaders()`, they will be + * merged with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * const headers = new Headers({ 'Content-Type': 'text/html' }); + * res.setHeaders(headers); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * @since v19.6.0, v18.15.0 + * @param name Header name + * @param value Header value + */ + setHeaders(headers: Headers | Map): this; + /** + * Append a single header value to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple + * times. + * + * If there were no previous values for the header, this is equivalent to calling `outgoingMessage.setHeader(name, value)`. + * + * Depending of the value of `options.uniqueHeaders` when the client request or the + * server were created, this will end up in the header being sent multiple times or + * a single time with values joined using `; `. + * @since v18.3.0, v16.17.0 + * @param name Header name + * @param value Header value + */ + appendHeader(name: string, value: string | readonly string[]): this; + /** + * Gets the value of the HTTP header with the given name. If that header is not + * set, the returned value will be `undefined`. + * @since v0.4.0 + * @param name Name of header + */ + getHeader(name: string): number | string | string[] | undefined; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow + * copy is used, array values may be mutated without additional calls to + * various header-related HTTP module methods. The keys of the returned + * object are the header names and the values are the respective header + * values. All header names are lowercase. + * + * The object returned by the `outgoingMessage.getHeaders()` method does + * not prototypically inherit from the JavaScript `Object`. This means that + * typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, + * and others are not defined and will not work. + * + * ```js + * outgoingMessage.setHeader('Foo', 'bar'); + * outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = outgoingMessage.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v7.7.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All names are lowercase. + * @since v7.7.0 + */ + getHeaderNames(): string[]; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name is case-insensitive. + * + * ```js + * const hasContentType = outgoingMessage.hasHeader('content-type'); + * ``` + * @since v7.7.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that is queued for implicit sending. + * + * ```js + * outgoingMessage.removeHeader('Content-Encoding'); + * ``` + * @since v0.4.0 + * @param name Header name + */ + removeHeader(name: string): void; + /** + * Adds HTTP trailers (headers but at the end of the message) to the message. + * + * Trailers will **only** be emitted if the message is chunked encoded. If not, + * the trailers will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header field names in its value, e.g. + * + * ```js + * message.writeHead(200, { 'Content-Type': 'text/plain', + * 'Trailer': 'Content-MD5' }); + * message.write(fileData); + * message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); + * message.end(); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.3.0 + */ + addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; + /** + * Flushes the message headers. + * + * For efficiency reason, Node.js normally buffers the message headers + * until `outgoingMessage.end()` is called or the first chunk of message data + * is written. It then tries to pack the headers and data into a single TCP + * packet. + * + * It is usually desired (it saves a TCP round-trip), but not when the first + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()` bypasses the optimization and kickstarts the message. + * @since v1.6.0 + */ + flushHeaders(): void; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v0.1.17 + */ + class ServerResponse extends OutgoingMessage { + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v0.4.0 + */ + statusCode: number; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status message that will be sent to the client when + * the headers get flushed. If this is left as `undefined` then the standard + * message for the status code will be used. + * + * ```js + * response.statusMessage = 'Not found'; + * ``` + * + * After response header was sent to the client, this property indicates the + * status message which was sent out. + * @since v0.11.8 + */ + statusMessage: string; + /** + * If set to `true`, Node.js will check whether the `Content-Length` header value and the size of the body, in bytes, are equal. + * Mismatching the `Content-Length` header value will result + * in an `Error` being thrown, identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * @since v18.10.0, v16.18.0 + */ + strictContentLength: boolean; + constructor(req: Request); + assignSocket(socket: Socket): void; + detachSocket(socket: Socket): void; + /** + * Sends an HTTP/1.1 100 Continue message to the client, indicating that + * the request body should be sent. See the `'checkContinue'` event on `Server`. + * @since v0.3.0 + */ + writeContinue(callback?: () => void): void; + /** + * Sends an HTTP/1.1 103 Early Hints message to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. The optional `callback` argument will be called when + * the response message has been written. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * 'x-trace-id': 'id for diagnostics', + * }); + * + * const earlyHintsCallback = () => console.log('early hints message sent'); + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }, earlyHintsCallback); + * ``` + * @since v18.11.0 + * @param hints An object containing the values of headers + * @param callback Will be called when the response message has been written + */ + writeEarlyHints(hints: Record, callback?: () => void): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * Optionally one can give a human-readable `statusMessage` as the second + * argument. + * + * `headers` may be an `Array` where the keys and values are in the same list. + * It is _not_ a list of tuples. So, the even-numbered offsets are key values, + * and the odd-numbered offsets are the associated values. The array is in the same + * format as `request.rawHeaders`. + * + * Returns a reference to the `ServerResponse`, so that calls can be chained. + * + * ```js + * const body = 'hello world'; + * response + * .writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain', + * }) + * .end(body); + * ``` + * + * This method must only be called once on a message and it must + * be called before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * If this method is called and `response.setHeader()` has not been called, + * it will directly write the supplied header values onto the network channel + * without caching internally, and the `response.getHeader()` on the header + * will not yield the expected result. If progressive population of headers is + * desired with potential future retrieval and modification, use `response.setHeader()` instead. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * `Content-Length` is read in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * will check whether `Content-Length` and the length of the body which has + * been transmitted are equal or not. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a \[`Error`\]\[\] being thrown. + * @since v0.1.30 + */ + writeHead( + statusCode: number, + statusMessage?: string, + headers?: OutgoingHttpHeaders | OutgoingHttpHeader[], + ): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends a HTTP/1.1 102 Processing message to the client, indicating that + * the request body should be sent. + * @since v10.0.0 + */ + writeProcessing(callback?: () => void): void; + } + interface InformationEvent { + statusCode: number; + statusMessage: string; + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + } + /** + * This object is created internally and returned from {@link request}. It + * represents an _in-progress_ request whose header has already been queued. The + * header is still mutable using the `setHeader(name, value)`, `getHeader(name)`, `removeHeader(name)` API. The actual header will + * be sent along with the first data chunk or when calling `request.end()`. + * + * To get the response, add a listener for `'response'` to the request object. `'response'` will be emitted from the request object when the response + * headers have been received. The `'response'` event is executed with one + * argument which is an instance of {@link IncomingMessage}. + * + * During the `'response'` event, one can add listeners to the + * response object; particularly to listen for the `'data'` event. + * + * If no `'response'` handler is added, then the response will be + * entirely discarded. However, if a `'response'` event handler is added, + * then the data from the response object **must** be consumed, either by + * calling `response.read()` whenever there is a `'readable'` event, or + * by adding a `'data'` handler, or by calling the `.resume()` method. + * Until the data is consumed, the `'end'` event will not fire. Also, until + * the data is read it will consume memory that can eventually lead to a + * 'process out of memory' error. + * + * For backward compatibility, `res` will only emit `'error'` if there is an `'error'` listener registered. + * + * Set `Content-Length` header to limit the response body size. + * If `response.strictContentLength` is set to `true`, mismatching the `Content-Length` header value will result in an `Error` being thrown, + * identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * + * `Content-Length` value should be in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. + * @since v0.1.17 + */ + class ClientRequest extends OutgoingMessage { + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v0.11.14 + * @deprecated Since v17.0.0, v16.12.0 - Check `destroyed` instead. + */ + aborted: boolean; + /** + * The request host. + * @since v14.5.0, v12.19.0 + */ + host: string; + /** + * The request protocol. + * @since v14.5.0, v12.19.0 + */ + protocol: string; + /** + * When sending request through a keep-alive enabled agent, the underlying socket + * might be reused. But if server closes connection at unfortunate time, client + * may run into a 'ECONNRESET' error. + * + * ```js + * import http from 'node:http'; + * + * // Server has a 5 seconds keep-alive timeout by default + * http + * .createServer((req, res) => { + * res.write('hello\n'); + * res.end(); + * }) + * .listen(3000); + * + * setInterval(() => { + * // Adapting a keep-alive agent + * http.get('http://localhost:3000', { agent }, (res) => { + * res.on('data', (data) => { + * // Do nothing + * }); + * }); + * }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout + * ``` + * + * By marking a request whether it reused socket or not, we can do + * automatic error retry base on it. + * + * ```js + * import http from 'node:http'; + * const agent = new http.Agent({ keepAlive: true }); + * + * function retriableRequest() { + * const req = http + * .get('http://localhost:3000', { agent }, (res) => { + * // ... + * }) + * .on('error', (err) => { + * // Check if retry is needed + * if (req.reusedSocket && err.code === 'ECONNRESET') { + * retriableRequest(); + * } + * }); + * } + * + * retriableRequest(); + * ``` + * @since v13.0.0, v12.16.0 + */ + reusedSocket: boolean; + /** + * Limits maximum response headers count. If set to 0, no limit will be applied. + */ + maxHeadersCount: number; + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + /** + * The request method. + * @since v0.1.97 + */ + method: string; + /** + * The request path. + * @since v0.4.0 + */ + path: string; + /** + * Marks the request as aborting. Calling this will cause remaining data + * in the response to be dropped and the socket to be destroyed. + * @since v0.3.8 + * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. + */ + abort(): void; + onSocket(socket: Socket): void; + /** + * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. + * @since v0.5.9 + * @param timeout Milliseconds before a request times out. + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. + * @since v0.5.9 + */ + setNoDelay(noDelay?: boolean): void; + /** + * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. + * @since v0.5.9 + */ + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + /** + * Returns an array containing the unique names of the current outgoing raw + * headers. Header names are returned with their exact casing being set. + * + * ```js + * request.setHeader('Foo', 'bar'); + * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = request.getRawHeaderNames(); + * // headerNames === ['Foo', 'Set-Cookie'] + * ``` + * @since v15.13.0, v14.17.0 + */ + getRawHeaderNames(): string[]; + /** + * @deprecated + */ + addListener(event: "abort", listener: () => void): this; + addListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + addListener(event: "continue", listener: () => void): this; + addListener(event: "information", listener: (info: InformationEvent) => void): this; + addListener(event: "response", listener: (response: IncomingMessage) => void): this; + addListener(event: "socket", listener: (socket: Socket) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + on(event: "abort", listener: () => void): this; + on(event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: "continue", listener: () => void): this; + on(event: "information", listener: (info: InformationEvent) => void): this; + on(event: "response", listener: (response: IncomingMessage) => void): this; + on(event: "socket", listener: (socket: Socket) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + once(event: "abort", listener: () => void): this; + once(event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: "continue", listener: () => void): this; + once(event: "information", listener: (info: InformationEvent) => void): this; + once(event: "response", listener: (response: IncomingMessage) => void): this; + once(event: "socket", listener: (socket: Socket) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependListener(event: "abort", listener: () => void): this; + prependListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependListener(event: "continue", listener: () => void): this; + prependListener(event: "information", listener: (info: InformationEvent) => void): this; + prependListener(event: "response", listener: (response: IncomingMessage) => void): this; + prependListener(event: "socket", listener: (socket: Socket) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependOnceListener(event: "abort", listener: () => void): this; + prependOnceListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependOnceListener(event: "continue", listener: () => void): this; + prependOnceListener(event: "information", listener: (info: InformationEvent) => void): this; + prependOnceListener(event: "response", listener: (response: IncomingMessage) => void): this; + prependOnceListener(event: "socket", listener: (socket: Socket) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to + * access response + * status, headers, and data. + * + * Different from its `socket` value which is a subclass of `stream.Duplex`, the `IncomingMessage` itself extends `stream.Readable` and is created separately to + * parse and emit the incoming HTTP headers and payload, as the underlying socket + * may be reused multiple times in case of keep-alive. + * @since v0.1.17 + */ + class IncomingMessage extends stream.Readable { + constructor(socket: Socket); + /** + * The `message.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + * @deprecated Since v17.0.0,v16.12.0 - Check `message.destroyed` from stream.Readable. + */ + aborted: boolean; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. + * Probably either `'1.1'` or `'1.0'`. + * + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. + * @since v0.1.1 + */ + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + /** + * The `message.complete` property will be `true` if a complete HTTP message has + * been received and successfully parsed. + * + * This property is particularly useful as a means of determining if a client or + * server fully transmitted a message before a connection was terminated: + * + * ```js + * const req = http.request({ + * host: '127.0.0.1', + * port: 8080, + * method: 'POST', + * }, (res) => { + * res.resume(); + * res.on('end', () => { + * if (!res.complete) + * console.error( + * 'The connection was terminated while the message was still being sent'); + * }); + * }); + * ``` + * @since v0.3.0 + */ + complete: boolean; + /** + * Alias for `message.socket`. + * @since v0.1.90 + * @deprecated Since v16.0.0 - Use `socket`. + */ + connection: Socket; + /** + * The `net.Socket` object associated with the connection. + * + * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the + * client's authentication details. + * + * This property is guaranteed to be an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specified a socket + * type other than `net.Socket` or internally nulled. + * @since v0.3.0 + */ + socket: Socket; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * Duplicates in raw headers are handled in the following ways, depending on the + * header name: + * + * * Duplicates of `age`, `authorization`, `content-length`, `content-type`, `etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`, `last-modified`, `location`, + * `max-forwards`, `proxy-authorization`, `referer`, `retry-after`, `server`, or `user-agent` are discarded. + * To allow duplicate values of the headers listed above to be joined, + * use the option `joinDuplicateHeaders` in {@link request} and {@link createServer}. See RFC 9110 Section 5.3 for more + * information. + * * `set-cookie` is always an array. Duplicates are added to the array. + * * For duplicate `cookie` headers, the values are joined together with `; `. + * * For all other headers, the values are joined together with `, `. + * @since v0.1.5 + */ + headers: IncomingHttpHeaders; + /** + * Similar to `message.headers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': ['curl/7.22.0'], + * // host: ['127.0.0.1:8000'], + * // accept: ['*'] } + * console.log(request.headersDistinct); + * ``` + * @since v18.3.0, v16.17.0 + */ + headersDistinct: NodeJS.Dict; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v0.11.6 + */ + rawHeaders: string[]; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v0.3.0 + */ + trailers: NodeJS.Dict; + /** + * Similar to `message.trailers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * Only populated at the `'end'` event. + * @since v18.3.0, v16.17.0 + */ + trailersDistinct: NodeJS.Dict; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v0.11.6 + */ + rawTrailers: string[]; + /** + * Calls `message.socket.setTimeout(msecs, callback)`. + * @since v0.5.9 + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * **Only valid for request obtained from {@link Server}.** + * + * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. + * @since v0.1.1 + */ + method?: string | undefined; + /** + * **Only valid for request obtained from {@link Server}.** + * + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. Take the following request: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * To parse the URL into its parts: + * + * ```js + * new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and `process.env.HOST` is undefined: + * + * ```console + * $ node + * > new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); + * URL { + * href: 'http://localhost/status?name=ryan', + * origin: 'http://localhost', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost', + * hostname: 'localhost', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * + * Ensure that you set `process.env.HOST` to the server's host name, or consider replacing this part entirely. If using `req.headers.host`, ensure proper + * validation is used, as clients may specify a custom `Host` header. + * @since v0.1.90 + */ + url?: string | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The 3-digit HTTP response status code. E.G. `404`. + * @since v0.1.1 + */ + statusCode?: number | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. + * @since v0.11.10 + */ + statusMessage?: string | undefined; + /** + * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error` is provided, an `'error'` event is emitted on the socket and `error` is passed + * as an argument to any listeners on the event. + * @since v0.3.0 + */ + destroy(error?: Error): this; + } + interface AgentOptions extends Partial { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean | undefined; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number | undefined; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number | undefined; + /** + * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. + */ + maxTotalSockets?: number | undefined; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number | undefined; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number | undefined; + /** + * Scheduling strategy to apply when picking the next free socket to use. + * @default `lifo` + */ + scheduling?: "fifo" | "lifo" | undefined; + } + /** + * An `Agent` is responsible for managing connection persistence + * and reuse for HTTP clients. It maintains a queue of pending requests + * for a given host and port, reusing a single socket connection for each + * until the queue is empty, at which time the socket is either destroyed + * or put into a pool where it is kept to be used again for requests to the + * same host and port. Whether it is destroyed or pooled depends on the `keepAlive` `option`. + * + * Pooled connections have TCP Keep-Alive enabled for them, but servers may + * still close idle connections, in which case they will be removed from the + * pool and a new connection will be made when a new HTTP request is made for + * that host and port. Servers may also refuse to allow multiple requests + * over the same connection, in which case the connection will have to be + * remade for every request and cannot be pooled. The `Agent` will still make + * the requests to that server, but each one will occur over a new connection. + * + * When a connection is closed by the client or the server, it is removed + * from the pool. Any unused sockets in the pool will be unrefed so as not + * to keep the Node.js process running when there are no outstanding requests. + * (see `socket.unref()`). + * + * It is good practice, to `destroy()` an `Agent` instance when it is no + * longer in use, because unused sockets consume OS resources. + * + * Sockets are removed from an agent when the socket emits either + * a `'close'` event or an `'agentRemove'` event. When intending to keep one + * HTTP request open for a long time without keeping it in the agent, something + * like the following may be done: + * + * ```js + * http.get(options, (res) => { + * // Do stuff + * }).on('socket', (socket) => { + * socket.emit('agentRemove'); + * }); + * ``` + * + * An agent may also be used for an individual request. By providing `{agent: false}` as an option to the `http.get()` or `http.request()` functions, a one-time use `Agent` with default options + * will be used + * for the client connection. + * + * `agent:false`: + * + * ```js + * http.get({ + * hostname: 'localhost', + * port: 80, + * path: '/', + * agent: false, // Create a new agent just for this one request + * }, (res) => { + * // Do stuff with response + * }); + * ``` + * + * `options` in [`socket.connect()`](https://nodejs.org/docs/latest-v24.x/api/net.html#socketconnectoptions-connectlistener) are also supported. + * + * To configure any of them, a custom {@link Agent} instance must be created. + * + * ```js + * import http from 'node:http'; + * const keepAliveAgent = new http.Agent({ keepAlive: true }); + * options.agent = keepAliveAgent; + * http.request(options, onResponseCallback) + * ``` + * @since v0.3.4 + */ + class Agent extends EventEmitter { + /** + * By default set to 256. For agents with `keepAlive` enabled, this + * sets the maximum number of sockets that will be left open in the free + * state. + * @since v0.11.7 + */ + maxFreeSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open per origin. Origin is the returned value of `agent.getName()`. + * @since v0.3.6 + */ + maxSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open. Unlike `maxSockets`, this parameter applies across all origins. + * @since v14.5.0, v12.19.0 + */ + maxTotalSockets: number; + /** + * An object which contains arrays of sockets currently awaiting use by + * the agent when `keepAlive` is enabled. Do not modify. + * + * Sockets in the `freeSockets` list will be automatically destroyed and + * removed from the array on `'timeout'`. + * @since v0.11.4 + */ + readonly freeSockets: NodeJS.ReadOnlyDict; + /** + * An object which contains arrays of sockets currently in use by the + * agent. Do not modify. + * @since v0.3.6 + */ + readonly sockets: NodeJS.ReadOnlyDict; + /** + * An object which contains queues of requests that have not yet been assigned to + * sockets. Do not modify. + * @since v0.5.9 + */ + readonly requests: NodeJS.ReadOnlyDict; + constructor(opts?: AgentOptions); + /** + * Destroy any sockets that are currently in use by the agent. + * + * It is usually not necessary to do this. However, if using an + * agent with `keepAlive` enabled, then it is best to explicitly shut down + * the agent when it is no longer needed. Otherwise, + * sockets might stay open for quite a long time before the server + * terminates them. + * @since v0.11.4 + */ + destroy(): void; + /** + * Produces a socket/stream to be used for HTTP requests. + * + * By default, this function is the same as `net.createConnection()`. However, + * custom agents may override this method in case greater flexibility is desired. + * + * A socket/stream can be supplied in one of two ways: by returning the + * socket/stream from this function, or by passing the socket/stream to `callback`. + * + * This method is guaranteed to return an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specifies a socket + * type other than `net.Socket`. + * + * `callback` has a signature of `(err, stream)`. + * @since v0.11.4 + * @param options Options containing connection details. Check `createConnection` for the format of the options + * @param callback Callback function that receives the created socket + */ + createConnection( + options: ClientRequestArgs, + callback?: (err: Error | null, stream: stream.Duplex) => void, + ): stream.Duplex; + /** + * Called when `socket` is detached from a request and could be persisted by the`Agent`. Default behavior is to: + * + * ```js + * socket.setKeepAlive(true, this.keepAliveMsecs); + * socket.unref(); + * return true; + * ``` + * + * This method can be overridden by a particular `Agent` subclass. If this + * method returns a falsy value, the socket will be destroyed instead of persisting + * it for use with the next request. + * + * The `socket` argument can be an instance of `net.Socket`, a subclass of `stream.Duplex`. + * @since v8.1.0 + */ + keepSocketAlive(socket: stream.Duplex): void; + /** + * Called when `socket` is attached to `request` after being persisted because of + * the keep-alive options. Default behavior is to: + * + * ```js + * socket.ref(); + * ``` + * + * This method can be overridden by a particular `Agent` subclass. + * + * The `socket` argument can be an instance of `net.Socket`, a subclass of `stream.Duplex`. + * @since v8.1.0 + */ + reuseSocket(socket: stream.Duplex, request: ClientRequest): void; + /** + * Get a unique name for a set of request options, to determine whether a + * connection can be reused. For an HTTP agent, this returns`host:port:localAddress` or `host:port:localAddress:family`. For an HTTPS agent, + * the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options + * that determine socket reusability. + * @since v0.11.4 + * @param options A set of options providing information for name generation + */ + getName(options?: ClientRequestArgs): string; + } + const METHODS: string[]; + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + /** + * Returns a new instance of {@link Server}. + * + * The `requestListener` is a function which is automatically + * added to the `'request'` event. + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer(); + * + * // Listen to the request event + * server.on('request', (request, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.1.13 + */ + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + >(requestListener?: RequestListener): Server; + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse> = typeof ServerResponse, + >( + options: ServerOptions, + requestListener?: RequestListener, + ): Server; + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs {} + /** + * `options` in `socket.connect()` are also supported. + * + * Node.js maintains several connections per server to make HTTP requests. + * This function allows one to transparently issue requests. + * + * `url` can be a string or a `URL` object. If `url` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * If both `url` and `options` are specified, the objects are merged, with the `options` properties taking precedence. + * + * The optional `callback` parameter will be added as a one-time listener for + * the `'response'` event. + * + * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * import http from 'node:http'; + * import { Buffer } from 'node:buffer'; + * + * const postData = JSON.stringify({ + * 'msg': 'Hello World!', + * }); + * + * const options = { + * hostname: 'www.google.com', + * port: 80, + * path: '/upload', + * method: 'POST', + * headers: { + * 'Content-Type': 'application/json', + * 'Content-Length': Buffer.byteLength(postData), + * }, + * }; + * + * const req = http.request(options, (res) => { + * console.log(`STATUS: ${res.statusCode}`); + * console.log(`HEADERS: ${JSON.stringify(res.headers)}`); + * res.setEncoding('utf8'); + * res.on('data', (chunk) => { + * console.log(`BODY: ${chunk}`); + * }); + * res.on('end', () => { + * console.log('No more data in response.'); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(`problem with request: ${e.message}`); + * }); + * + * // Write data to request body + * req.write(postData); + * req.end(); + * ``` + * + * In the example `req.end()` was called. With `http.request()` one + * must always call `req.end()` to signify the end of the request - + * even if there is no data being written to the request body. + * + * If any error is encountered during the request (be that with DNS resolution, + * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted + * on the returned request object. As with all `'error'` events, if no listeners + * are registered the error will be thrown. + * + * There are a few special headers that should be noted. + * + * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to + * the server should be persisted until the next request. + * * Sending a 'Content-Length' header will disable the default chunked encoding. + * * Sending an 'Expect' header will immediately send the request headers. + * Usually, when sending 'Expect: 100-continue', both a timeout and a listener + * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more + * information. + * * Sending an Authorization header will override using the `auth` option + * to compute basic authentication. + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('http://abc:xyz@example.com'); + * + * const req = http.request(options, (res) => { + * // ... + * }); + * ``` + * + * In a successful request, the following events will be emitted in the following + * order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * (`'data'` will not be emitted at all if the response body is empty, for + * instance, in most redirects) + * * `'end'` on the `res` object + * * `'close'` + * + * In the case of a connection error, the following events will be emitted: + * + * * `'socket'` + * * `'error'` + * * `'close'` + * + * In the case of a premature connection close before the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` + * * `'close'` + * + * In the case of a premature connection close after the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (connection closed here) + * * `'aborted'` on the `res` object + * * `'close'` + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'` + * * `'close'` on the `res` object + * + * If `req.destroy()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.destroy()` called here) + * * `'aborted'` on the `res` object + * * `'close'` + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` on the `res` object + * + * If `req.abort()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.abort()` called here) + * * `'abort'` + * * `'close'` + * + * If `req.abort()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.abort()` called here) + * * `'abort'` + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` + * * `'close'` + * + * If `req.abort()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.abort()` called here) + * * `'abort'` + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * Setting the `timeout` option or using the `setTimeout()` function will + * not abort the request or do anything besides add a `'timeout'` event. + * + * Passing an `AbortSignal` and then calling `abort()` on the corresponding `AbortController` will behave the same way as calling `.destroy()` on the + * request. Specifically, the `'error'` event will be emitted with an error with + * the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'` and the `cause`, if one was provided. + * @since v0.3.6 + */ + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: IncomingMessage) => void, + ): ClientRequest; + /** + * Since most requests are GET requests without bodies, Node.js provides this + * convenience method. The only difference between this method and {@link request} is that it sets the method to GET by default and calls `req.end()` automatically. The callback must take care to + * consume the response + * data for reasons stated in {@link ClientRequest} section. + * + * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}. + * + * JSON fetching example: + * + * ```js + * http.get('http://localhost:8000/', (res) => { + * const { statusCode } = res; + * const contentType = res.headers['content-type']; + * + * let error; + * // Any 2xx status code signals a successful response but + * // here we're only checking for 200. + * if (statusCode !== 200) { + * error = new Error('Request Failed.\n' + + * `Status Code: ${statusCode}`); + * } else if (!/^application\/json/.test(contentType)) { + * error = new Error('Invalid content-type.\n' + + * `Expected application/json but received ${contentType}`); + * } + * if (error) { + * console.error(error.message); + * // Consume response data to free up memory + * res.resume(); + * return; + * } + * + * res.setEncoding('utf8'); + * let rawData = ''; + * res.on('data', (chunk) => { rawData += chunk; }); + * res.on('end', () => { + * try { + * const parsedData = JSON.parse(rawData); + * console.log(parsedData); + * } catch (e) { + * console.error(e.message); + * } + * }); + * }).on('error', (e) => { + * console.error(`Got error: ${e.message}`); + * }); + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the method set to GET by default. + */ + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + /** + * Performs the low-level validations on the provided `name` that are done when `res.setHeader(name, value)` is called. + * + * Passing illegal value as `name` will result in a `TypeError` being thrown, + * identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Example: + * + * ```js + * import { validateHeaderName } from 'node:http'; + * + * try { + * validateHeaderName(''); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN' + * console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' + * } + * ``` + * @since v14.3.0 + * @param [label='Header name'] Label for error message. + */ + function validateHeaderName(name: string): void; + /** + * Performs the low-level validations on the provided `value` that are done when `res.setHeader(name, value)` is called. + * + * Passing illegal value as `value` will result in a `TypeError` being thrown. + * + * * Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. + * * Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Examples: + * + * ```js + * import { validateHeaderValue } from 'node:http'; + * + * try { + * validateHeaderValue('x-my-header', undefined); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true + * console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' + * } + * + * try { + * validateHeaderValue('x-my-header', 'oʊmɪɡə'); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_INVALID_CHAR'); // --> true + * console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' + * } + * ``` + * @since v14.3.0 + * @param name Header name + * @param value Header value + */ + function validateHeaderValue(name: string, value: string): void; + /** + * Set the maximum number of idle HTTP parsers. + * @since v18.8.0, v16.18.0 + * @param [max=1000] + */ + function setMaxIdleHTTPParsers(max: number): void; + /** + * Global instance of `Agent` which is used as the default for all HTTP client + * requests. Diverges from a default `Agent` configuration by having `keepAlive` + * enabled and a `timeout` of 5 seconds. + * @since v0.5.9 + */ + let globalAgent: Agent; + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. + */ + const maxHeaderSize: number; + /** + * A browser-compatible implementation of [WebSocket](https://nodejs.org/docs/latest/api/http.html#websocket). + * @since v22.5.0 + */ + const WebSocket: import("undici-types").WebSocket; + /** + * @since v22.5.0 + */ + const CloseEvent: import("undici-types").CloseEvent; + /** + * @since v22.5.0 + */ + const MessageEvent: import("undici-types").MessageEvent; +} +declare module "node:http" { + export * from "http"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/http2.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/http2.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5e53de79f93eeb9ea256b7fd380c12e6846c3771 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/http2.d.ts @@ -0,0 +1,2630 @@ +/** + * The `node:http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. + * It can be accessed using: + * + * ```js + * import http2 from 'node:http2'; + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/http2.js) + */ +declare module "http2" { + import EventEmitter = require("node:events"); + import * as fs from "node:fs"; + import * as net from "node:net"; + import * as stream from "node:stream"; + import * as tls from "node:tls"; + import * as url from "node:url"; + import { + IncomingHttpHeaders as Http1IncomingHttpHeaders, + IncomingMessage, + OutgoingHttpHeaders, + ServerResponse, + } from "node:http"; + export { OutgoingHttpHeaders } from "node:http"; + export interface IncomingHttpStatusHeader { + ":status"?: number | undefined; + } + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ":path"?: string | undefined; + ":method"?: string | undefined; + ":authority"?: string | undefined; + ":scheme"?: string | undefined; + } + // Http2Stream + export interface StreamState { + localWindowSize?: number | undefined; + state?: number | undefined; + localClose?: number | undefined; + remoteClose?: number | undefined; + /** @deprecated */ + sumDependencyWeight?: number | undefined; + /** @deprecated */ + weight?: number | undefined; + } + export interface ServerStreamResponseOptions { + endStream?: boolean | undefined; + waitForTrailers?: boolean | undefined; + } + export interface StatOptions { + offset: number; + length: number; + } + export interface ServerStreamFileResponseOptions { + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + statCheck?(stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions): void | boolean; + waitForTrailers?: boolean | undefined; + offset?: number | undefined; + length?: number | undefined; + } + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?(err: NodeJS.ErrnoException): void; + } + export interface Http2Stream extends stream.Duplex { + /** + * Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, + * the `'aborted'` event will have been emitted. + * @since v8.4.0 + */ + readonly aborted: boolean; + /** + * This property shows the number of characters currently buffered to be written. + * See `net.Socket.bufferSize` for details. + * @since v11.2.0, v10.16.0 + */ + readonly bufferSize: number; + /** + * Set to `true` if the `Http2Stream` instance has been closed. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Set to `true` if the `Http2Stream` instance has been destroyed and is no longer + * usable. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Set to `true` if the `END_STREAM` flag was set in the request or response + * HEADERS frame received, indicating that no additional data should be received + * and the readable side of the `Http2Stream` will be closed. + * @since v10.11.0 + */ + readonly endAfterHeaders: boolean; + /** + * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined` if the stream identifier has not yet been assigned. + * @since v8.4.0 + */ + readonly id?: number | undefined; + /** + * Set to `true` if the `Http2Stream` instance has not yet been assigned a + * numeric stream identifier. + * @since v9.4.0 + */ + readonly pending: boolean; + /** + * Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is + * destroyed after either receiving an `RST_STREAM` frame from the connected peer, + * calling `http2stream.close()`, or `http2stream.destroy()`. Will be `undefined` if the `Http2Stream` has not been closed. + * @since v8.4.0 + */ + readonly rstCode: number; + /** + * An object containing the outbound headers sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentHeaders: OutgoingHttpHeaders; + /** + * An array of objects containing the outbound informational (additional) headers + * sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentInfoHeaders?: OutgoingHttpHeaders[] | undefined; + /** + * An object containing the outbound trailers sent for this `HttpStream`. + * @since v9.5.0 + */ + readonly sentTrailers?: OutgoingHttpHeaders | undefined; + /** + * A reference to the `Http2Session` instance that owns this `Http2Stream`. The + * value will be `undefined` after the `Http2Stream` instance is destroyed. + * @since v8.4.0 + */ + readonly session: Http2Session | undefined; + /** + * Provides miscellaneous information about the current state of the `Http2Stream`. + * + * A current state of this `Http2Stream`. + * @since v8.4.0 + */ + readonly state: StreamState; + /** + * Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the + * connected HTTP/2 peer. + * @since v8.4.0 + * @param [code=http2.constants.NGHTTP2_NO_ERROR] Unsigned 32-bit integer identifying the error code. + * @param callback An optional function registered to listen for the `'close'` event. + */ + close(code?: number, callback?: () => void): void; + /** + * @deprecated Priority signaling is no longer supported in Node.js. + */ + priority(options: unknown): void; + /** + * ```js + * import http2 from 'node:http2'; + * const client = http2.connect('http://example.org:8000'); + * const { NGHTTP2_CANCEL } = http2.constants; + * const req = client.request({ ':path': '/' }); + * + * // Cancel the stream if there's no activity after 5 seconds + * req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); + * ``` + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method + * will cause the `Http2Stream` to be immediately closed and must only be + * called after the `'wantTrailers'` event has been emitted. When sending a + * request or sending a response, the `options.waitForTrailers` option must be set + * in order to keep the `Http2Stream` open after the final `DATA` frame so that + * trailers can be sent. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond(undefined, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ xyz: 'abc' }); + * }); + * stream.end('Hello World'); + * }); + * ``` + * + * The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header + * fields (e.g. `':method'`, `':path'`, etc). + * @since v10.0.0 + */ + sendTrailers(headers: OutgoingHttpHeaders): void; + addListener(event: "aborted", listener: () => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: "streamClosed", listener: (code: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "wantTrailers", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted"): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "frameError", frameType: number, errorCode: number): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: "streamClosed", code: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "wantTrailers"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: () => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: "streamClosed", listener: (code: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "wantTrailers", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: () => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: "streamClosed", listener: (code: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "wantTrailers", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: () => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "streamClosed", listener: (code: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "wantTrailers", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: () => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "wantTrailers", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: "continue", listener: () => {}): this; + addListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "continue"): boolean; + emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "continue", listener: () => {}): this; + on( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "continue", listener: () => {}): this; + once( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "continue", listener: () => {}): this; + prependListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "continue", listener: () => {}): this; + prependOnceListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ServerHttp2Stream extends Http2Stream { + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote + * client's most recent `SETTINGS` frame. Will be `true` if the remote peer + * accepts push streams, `false` otherwise. Settings are the same for every `Http2Stream` in the same `Http2Session`. + * @since v8.4.0 + */ + readonly pushAllowed: boolean; + /** + * Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. + * @since v8.4.0 + */ + additionalHeaders(headers: OutgoingHttpHeaders): void; + /** + * Initiates a push stream. The callback is invoked with the new `Http2Stream` instance created for the push stream passed as the second argument, or an `Error` passed as the first argument. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { + * if (err) throw err; + * pushStream.respond({ ':status': 200 }); + * pushStream.end('some pushed data'); + * }); + * stream.end('some data'); + * }); + * ``` + * + * Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass + * a `weight` value to `http2stream.priority` with the `silent` option set to `true` to enable server-side bandwidth balancing between concurrent streams. + * + * Calling `http2stream.pushStream()` from within a pushed stream is not permitted + * and will throw an error. + * @since v8.4.0 + * @param callback Callback that is called once the push stream has been initiated. + */ + pushStream( + headers: OutgoingHttpHeaders, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + pushStream( + headers: OutgoingHttpHeaders, + options?: Pick, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + /** + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * Initiates a response. When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be used to send trailing header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either `http2stream.sendTrailers()` or `http2stream.close()` to close the `Http2Stream`. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * stream.end('some data'); + * }); + * ``` + * @since v8.4.0 + */ + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + /** + * Initiates a response whose data is read from the given file descriptor. No + * validation is performed on the given file descriptor. If an error occurs while + * attempting to read data using the file descriptor, the `Http2Stream` will be + * closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * ```js + * import http2 from 'node:http2'; + * import fs from 'node:fs'; + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers); + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given fd. If the `statCheck` function is provided, the `http2stream.respondWithFD()` method will + * perform an `fs.fstat()` call to collect details on the provided file descriptor. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The file descriptor or `FileHandle` is not closed when the stream is closed, + * so it will need to be closed manually once it is no longer needed. + * Using the same file descriptor concurrently for multiple streams + * is not supported and may result in data loss. Re-using a file descriptor + * after a stream has finished is supported. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code _must_ call either `http2stream.sendTrailers()` + * or `http2stream.close()` to close the `Http2Stream`. + * + * ```js + * import http2 from 'node:http2'; + * import fs from 'node:fs'; + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * @since v8.4.0 + * @param fd A readable file descriptor. + */ + respondWithFD( + fd: number | fs.promises.FileHandle, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptions, + ): void; + /** + * Sends a regular file as the response. The `path` must specify a regular file + * or an `'error'` event will be emitted on the `Http2Stream` object. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given file: + * + * If an error occurs while attempting to read the file data, the `Http2Stream` will be closed using an + * `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * If the `onError` callback is defined, then it will be called. Otherwise, the stream will be destroyed. + * + * Example using a file path: + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * headers['last-modified'] = stat.mtime.toUTCString(); + * } + * + * function onError(err) { + * // stream.respond() can throw if the stream has been destroyed by + * // the other side. + * try { + * if (err.code === 'ENOENT') { + * stream.respond({ ':status': 404 }); + * } else { + * stream.respond({ ':status': 500 }); + * } + * } catch (err) { + * // Perform actual error handling. + * console.error(err); + * } + * stream.end(); + * } + * + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck, onError }); + * }); + * ``` + * + * The `options.statCheck` function may also be used to cancel the send operation + * by returning `false`. For instance, a conditional request may check the stat + * results to determine if the file has been modified to return an appropriate `304` response: + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * // Check the stat here... + * stream.respond({ ':status': 304 }); + * return false; // Cancel the send operation + * } + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck }); + * }); + * ``` + * + * The `content-length` header field will be automatically set. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The `options.onError` function may also be used to handle all the errors + * that could happen before the delivery of the file is initiated. The + * default behavior is to destroy the stream. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * }); + * ``` + * @since v8.4.0 + */ + respondWithFile( + path: string, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptionsWithError, + ): void; + } + // Http2Session + export interface Settings { + headerTableSize?: number | undefined; + enablePush?: boolean | undefined; + initialWindowSize?: number | undefined; + maxFrameSize?: number | undefined; + maxConcurrentStreams?: number | undefined; + maxHeaderListSize?: number | undefined; + enableConnectProtocol?: boolean | undefined; + } + export interface ClientSessionRequestOptions { + endStream?: boolean | undefined; + exclusive?: boolean | undefined; + parent?: number | undefined; + waitForTrailers?: boolean | undefined; + signal?: AbortSignal | undefined; + } + export interface SessionState { + effectiveLocalWindowSize?: number | undefined; + effectiveRecvDataLength?: number | undefined; + nextStreamID?: number | undefined; + localWindowSize?: number | undefined; + lastProcStreamID?: number | undefined; + remoteWindowSize?: number | undefined; + outboundQueueSize?: number | undefined; + deflateDynamicTableSize?: number | undefined; + inflateDynamicTableSize?: number | undefined; + } + export interface Http2Session extends EventEmitter { + /** + * Value will be `undefined` if the `Http2Session` is not yet connected to a + * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or + * will return the value of the connected `TLSSocket`'s own `alpnProtocol` property. + * @since v9.4.0 + */ + readonly alpnProtocol?: string | undefined; + /** + * Will be `true` if this `Http2Session` instance has been closed, otherwise `false`. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Will be `true` if this `Http2Session` instance is still connecting, will be set + * to `false` before emitting `connect` event and/or calling the `http2.connect` callback. + * @since v10.0.0 + */ + readonly connecting: boolean; + /** + * Will be `true` if this `Http2Session` instance has been destroyed and must no + * longer be used, otherwise `false`. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Value is `undefined` if the `Http2Session` session socket has not yet been + * connected, `true` if the `Http2Session` is connected with a `TLSSocket`, + * and `false` if the `Http2Session` is connected to any other kind of socket + * or stream. + * @since v9.4.0 + */ + readonly encrypted?: boolean | undefined; + /** + * A prototype-less object describing the current local settings of this `Http2Session`. + * The local settings are local to _this_`Http2Session` instance. + * @since v8.4.0 + */ + readonly localSettings: Settings; + /** + * If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property + * will return an `Array` of origins for which the `Http2Session` may be + * considered authoritative. + * + * The `originSet` property is only available when using a secure TLS connection. + * @since v9.4.0 + */ + readonly originSet?: string[] | undefined; + /** + * Indicates whether the `Http2Session` is currently waiting for acknowledgment of + * a sent `SETTINGS` frame. Will be `true` after calling the `http2session.settings()` method. + * Will be `false` once all sent `SETTINGS` frames have been acknowledged. + * @since v8.4.0 + */ + readonly pendingSettingsAck: boolean; + /** + * A prototype-less object describing the current remote settings of this`Http2Session`. + * The remote settings are set by the _connected_ HTTP/2 peer. + * @since v8.4.0 + */ + readonly remoteSettings: Settings; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * limits available methods to ones safe to use with HTTP/2. + * + * `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw + * an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information. + * + * `setTimeout` method will be called on this `Http2Session`. + * + * All other interactions will be routed directly to the socket. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * Provides miscellaneous information about the current state of the`Http2Session`. + * + * An object describing the current status of this `Http2Session`. + * @since v8.4.0 + */ + readonly state: SessionState; + /** + * The `http2session.type` will be equal to `http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a + * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a + * client. + * @since v8.4.0 + */ + readonly type: number; + /** + * Gracefully closes the `Http2Session`, allowing any existing streams to + * complete on their own and preventing new `Http2Stream` instances from being + * created. Once closed, `http2session.destroy()`_might_ be called if there + * are no open `Http2Stream` instances. + * + * If specified, the `callback` function is registered as a handler for the`'close'` event. + * @since v9.4.0 + */ + close(callback?: () => void): void; + /** + * Immediately terminates the `Http2Session` and the associated `net.Socket` or `tls.TLSSocket`. + * + * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error` is not undefined, an `'error'` event will be emitted immediately before the `'close'` event. + * + * If there are any remaining open `Http2Streams` associated with the `Http2Session`, those will also be destroyed. + * @since v8.4.0 + * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. + * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. + */ + destroy(error?: Error, code?: number): void; + /** + * Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`. + * @since v9.4.0 + * @param code An HTTP/2 error code + * @param lastStreamID The numeric ID of the last processed `Http2Stream` + * @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. + */ + goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; + /** + * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must + * be provided. The method will return `true` if the `PING` was sent, `false` otherwise. + * + * The maximum number of outstanding (unacknowledged) pings is determined by the `maxOutstandingPings` configuration option. The default maximum is 10. + * + * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView` containing 8 bytes of data that will be transmitted with the `PING` and + * returned with the ping acknowledgment. + * + * The callback will be invoked with three arguments: an error argument that will + * be `null` if the `PING` was successfully acknowledged, a `duration` argument + * that reports the number of milliseconds elapsed since the ping was sent and the + * acknowledgment was received, and a `Buffer` containing the 8-byte `PING` payload. + * + * ```js + * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { + * if (!err) { + * console.log(`Ping acknowledged in ${duration} milliseconds`); + * console.log(`With payload '${payload.toString()}'`); + * } + * }); + * ``` + * + * If the `payload` argument is not specified, the default payload will be the + * 64-bit timestamp (little endian) marking the start of the `PING` duration. + * @since v8.9.3 + * @param payload Optional ping payload. + */ + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping( + payload: NodeJS.ArrayBufferView, + callback: (err: Error | null, duration: number, payload: Buffer) => void, + ): boolean; + /** + * Calls `ref()` on this `Http2Session` instance's underlying `net.Socket`. + * @since v9.4.0 + */ + ref(): void; + /** + * Sets the local endpoint's window size. + * The `windowSize` is the total window size to set, not + * the delta. + * + * ```js + * import http2 from 'node:http2'; + * + * const server = http2.createServer(); + * const expectedWindowSize = 2 ** 20; + * server.on('connect', (session) => { + * + * // Set local window size to be 2 ** 20 + * session.setLocalWindowSize(expectedWindowSize); + * }); + * ``` + * @since v15.3.0, v14.18.0 + */ + setLocalWindowSize(windowSize: number): void; + /** + * Used to set a callback function that is called when there is no activity on + * the `Http2Session` after `msecs` milliseconds. The given `callback` is + * registered as a listener on the `'timeout'` event. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Updates the current local settings for this `Http2Session` and sends a new `SETTINGS` frame to the connected HTTP/2 peer. + * + * Once called, the `http2session.pendingSettingsAck` property will be `true` while the session is waiting for the remote peer to acknowledge the new + * settings. + * + * The new settings will not become effective until the `SETTINGS` acknowledgment + * is received and the `'localSettings'` event is emitted. It is possible to send + * multiple `SETTINGS` frames while acknowledgment is still pending. + * @since v8.4.0 + * @param callback Callback that is called once the session is connected or right away if the session is already connected. + */ + settings( + settings: Settings, + callback?: (err: Error | null, settings: Settings, duration: number) => void, + ): void; + /** + * Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + unref(): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + addListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + addListener(event: "localSettings", listener: (settings: Settings) => void): this; + addListener(event: "ping", listener: () => void): this; + addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; + emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData?: Buffer): boolean; + emit(event: "localSettings", settings: Settings): boolean; + emit(event: "ping"): boolean; + emit(event: "remoteSettings", settings: Settings): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this; + on(event: "localSettings", listener: (settings: Settings) => void): this; + on(event: "ping", listener: () => void): this; + on(event: "remoteSettings", listener: (settings: Settings) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this; + once(event: "localSettings", listener: (settings: Settings) => void): this; + once(event: "ping", listener: () => void): this; + once(event: "remoteSettings", listener: (settings: Settings) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + prependListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + prependListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependListener(event: "ping", listener: () => void): this; + prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + prependOnceListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "ping", listener: () => void): this; + prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Session extends Http2Session { + /** + * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()` creates and returns an `Http2Stream` instance that can be used to send an + * HTTP/2 request to the connected server. + * + * When a `ClientHttp2Session` is first created, the socket may not yet be + * connected. if `clienthttp2session.request()` is called during this time, the + * actual request will be deferred until the socket is ready to go. + * If the `session` is closed before the actual request be executed, an `ERR_HTTP2_GOAWAY_SESSION` is thrown. + * + * This method is only available if `http2session.type` is equal to `http2.constants.NGHTTP2_SESSION_CLIENT`. + * + * ```js + * import http2 from 'node:http2'; + * const clientSession = http2.connect('https://localhost:1234'); + * const { + * HTTP2_HEADER_PATH, + * HTTP2_HEADER_STATUS, + * } = http2.constants; + * + * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); + * req.on('response', (headers) => { + * console.log(headers[HTTP2_HEADER_STATUS]); + * req.on('data', (chunk) => { // .. }); + * req.on('end', () => { // .. }); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * is emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be called to send trailing + * headers to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * When `options.signal` is set with an `AbortSignal` and then `abort` on the + * corresponding `AbortController` is called, the request will emit an `'error'`event with an `AbortError` error. + * + * The `:method` and `:path` pseudo-headers are not specified within `headers`, + * they respectively default to: + * + * * `:method` \= `'GET'` + * * `:path` \= `/` + * @since v8.4.0 + */ + request( + headers?: OutgoingHttpHeaders | readonly string[], + options?: ClientSessionRequestOptions, + ): ClientHttp2Stream; + addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: "origin", listener: (origins: string[]) => void): this; + addListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + addListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; + emit(event: "origin", origins: readonly string[]): boolean; + emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit( + event: "stream", + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + on(event: "origin", listener: (origins: string[]) => void): this; + on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + once(event: "origin", listener: (origins: string[]) => void): this; + once( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + once( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: "origin", listener: (origins: string[]) => void): this; + prependListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: "origin", listener: (origins: string[]) => void): this; + prependOnceListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependOnceListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + export interface ServerHttp2Session< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends Http2Session { + readonly server: + | Http2Server + | Http2SecureServer; + /** + * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. + * + * ```js + * import http2 from 'node:http2'; + * + * const server = http2.createServer(); + * server.on('session', (session) => { + * // Set altsvc for origin https://example.org:80 + * session.altsvc('h2=":8000"', 'https://example.org:80'); + * }); + * + * server.on('stream', (stream) => { + * // Set altsvc for a specific stream + * stream.session.altsvc('h2=":8000"', stream.id); + * }); + * ``` + * + * Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate + * service is associated with the origin of the given `Http2Stream`. + * + * The `alt` and origin string _must_ contain only ASCII bytes and are + * strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`may be passed to clear any previously set alternative service for a given + * domain. + * + * When a string is passed for the `originOrStream` argument, it will be parsed as + * a URL and the origin will be derived. For instance, the origin for the + * HTTP URL `'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as`originOrStream`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * @since v9.4.0 + * @param alt A description of the alternative service configuration as defined by `RFC 7838`. + * @param originOrStream Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the + * `http2stream.id` property. + */ + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + /** + * Submits an `ORIGIN` frame (as defined by [RFC 8336](https://tools.ietf.org/html/rfc8336)) to the connected client + * to advertise the set of origins for which the server is capable of providing + * authoritative responses. + * + * ```js + * import http2 from 'node:http2'; + * const options = getSecureOptionsSomehow(); + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * server.on('session', (session) => { + * session.origin('https://example.com', 'https://example.org'); + * }); + * ``` + * + * When a string is passed as an `origin`, it will be parsed as a URL and the + * origin will be derived. For instance, the origin for the HTTP URL `'https://example.org/foo/bar'` is the ASCII string` 'https://example.org'`. An error will be thrown if either the given + * string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as + * an `origin`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * + * Alternatively, the `origins` option may be used when creating a new HTTP/2 + * server using the `http2.createSecureServer()` method: + * + * ```js + * import http2 from 'node:http2'; + * const options = getSecureOptionsSomehow(); + * options.origins = ['https://example.com', 'https://example.org']; + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * ``` + * @since v10.12.0 + * @param origins One or more URL Strings passed as separate arguments. + */ + origin( + ...origins: Array< + | string + | url.URL + | { + origin: string; + } + > + ): void; + addListener( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit( + event: "connect", + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "connect", + listener: ( + session: ServerHttp2Session, + socket: net.Socket | tls.TLSSocket, + ) => void, + ): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + // Http2Server + export interface SessionOptions { + /** + * Sets the maximum dynamic table size for deflating header fields. + * @default 4Kib + */ + maxDeflateDynamicTableSize?: number | undefined; + /** + * Sets the maximum number of settings entries per `SETTINGS` frame. + * The minimum value allowed is `1`. + * @default 32 + */ + maxSettings?: number | undefined; + /** + * Sets the maximum memory that the `Http2Session` is permitted to use. + * The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. + * The minimum value allowed is `1`. + * This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, + * but new `Http2Stream` instances will be rejected while this limit is exceeded. + * The current number of `Http2Stream` sessions, the current memory use of the header compression tables, + * current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit. + * @default 10 + */ + maxSessionMemory?: number | undefined; + /** + * Sets the maximum number of header entries. + * This is similar to `server.maxHeadersCount` or `request.maxHeadersCount` in the `node:http` module. + * The minimum value is `1`. + * @default 128 + */ + maxHeaderListPairs?: number | undefined; + /** + * Sets the maximum number of outstanding, unacknowledged pings. + * @default 10 + */ + maxOutstandingPings?: number | undefined; + /** + * Sets the maximum allowed size for a serialized, compressed block of headers. + * Attempts to send headers that exceed this limit will result in + * a `'frameError'` event being emitted and the stream being closed and destroyed. + */ + maxSendHeaderBlockLength?: number | undefined; + /** + * Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames. + * @default http2.constants.PADDING_STRATEGY_NONE + */ + paddingStrategy?: number | undefined; + /** + * Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. + * Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. + * @default 100 + */ + peerMaxConcurrentStreams?: number | undefined; + /** + * The initial settings to send to the remote peer upon connection. + */ + settings?: Settings | undefined; + /** + * The array of integer values determines the settings types, + * which are included in the `CustomSettings`-property of the received remoteSettings. + * Please see the `CustomSettings`-property of the `Http2Settings` object for more information, on the allowed setting types. + */ + remoteCustomSettings?: number[] | undefined; + /** + * Specifies a timeout in milliseconds that + * a server should wait when an [`'unknownProtocol'`][] is emitted. If the + * socket has not been destroyed by that time the server will destroy it. + * @default 100000 + */ + unknownProtocolTimeout?: number | undefined; + /** + * If `true`, it turns on strict leading + * and trailing whitespace validation for HTTP/2 header field names and values + * as per [RFC-9113](https://www.rfc-editor.org/rfc/rfc9113.html#section-8.2.1). + * @since v24.2.0 + * @default true + */ + strictFieldWhitespaceValidation?: boolean | undefined; + } + export interface ClientSessionOptions extends SessionOptions { + /** + * Sets the maximum number of reserved push streams the client will accept at any given time. + * Once the current number of currently reserved push streams exceeds reaches this limit, + * new push streams sent by the server will be automatically rejected. + * The minimum allowed value is 0. The maximum allowed value is 232-1. + * A negative value sets this option to the maximum allowed value. + * @default 200 + */ + maxReservedRemoteStreams?: number | undefined; + /** + * An optional callback that receives the `URL` instance passed to `connect` and the `options` object, + * and returns any `Duplex` stream that is to be used as the connection for this session. + */ + createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; + /** + * The protocol to connect with, if not set in the `authority`. + * Value may be either `'http:'` or `'https:'`. + * @default 'https:' + */ + protocol?: "http:" | "https:" | undefined; + } + export interface ServerSessionOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends SessionOptions { + streamResetBurst?: number | undefined; + streamResetRate?: number | undefined; + Http1IncomingMessage?: Http1Request | undefined; + Http1ServerResponse?: Http1Response | undefined; + Http2ServerRequest?: Http2Request | undefined; + Http2ServerResponse?: Http2Response | undefined; + } + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} + export interface SecureServerSessionOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends ServerSessionOptions, tls.TlsOptions {} + export interface ServerOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends ServerSessionOptions {} + export interface SecureServerOptions< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends SecureServerSessionOptions { + allowHTTP1?: boolean | undefined; + origins?: string[] | undefined; + } + interface HTTP2ServerCommon { + setTimeout(msec?: number, callback?: () => void): this; + /** + * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values. + * Throws ERR_INVALID_ARG_TYPE for invalid settings argument. + */ + updateSettings(settings: Settings): void; + } + export interface Http2Server< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends net.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + addListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + addListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit( + event: "checkContinue", + request: InstanceType, + response: InstanceType, + ): boolean; + emit(event: "request", request: InstanceType, response: InstanceType): boolean; + emit( + event: "session", + session: ServerHttp2Session, + ): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + on( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + on( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + once( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + once( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependOnceListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface Http2SecureServer< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + > extends tls.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + addListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + addListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit( + event: "checkContinue", + request: InstanceType, + response: InstanceType, + ): boolean; + emit(event: "request", request: InstanceType, response: InstanceType): boolean; + emit( + event: "session", + session: ServerHttp2Session, + ): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + on( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + on( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + once( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + once( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: InstanceType, response: InstanceType) => void, + ): this; + prependOnceListener( + event: "session", + listener: (session: ServerHttp2Session) => void, + ): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * A `Http2ServerRequest` object is created by {@link Server} or {@link SecureServer} and passed as the first argument to the `'request'` event. It may be used to access a request status, + * headers, and + * data. + * @since v8.4.0 + */ + export class Http2ServerRequest extends stream.Readable { + constructor( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + options: stream.ReadableOptions, + rawHeaders: readonly string[], + ); + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ + readonly aborted: boolean; + /** + * The request authority pseudo header field. Because HTTP/2 allows requests + * to set either `:authority` or `host`, this value is derived from `req.headers[':authority']` if present. Otherwise, it is derived from `req.headers['host']`. + * @since v8.4.0 + */ + readonly authority: string; + /** + * See `request.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * The `request.complete` property will be `true` if the request has + * been completed, aborted, or destroyed. + * @since v12.10.0 + */ + readonly complete: boolean; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * See `HTTP/2 Headers Object`. + * + * In HTTP/2, the request path, host name, protocol, and method are represented as + * special headers prefixed with the `:` character (e.g. `':path'`). These special + * headers will be included in the `request.headers` object. Care must be taken not + * to inadvertently modify these special headers or errors may occur. For instance, + * removing all headers from the request will cause errors to occur: + * + * ```js + * removeAllHeaders(request.headers); + * assert(request.url); // Fails because the :path header has been removed + * ``` + * @since v8.4.0 + */ + readonly headers: IncomingHttpHeaders; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. Returns `'2.0'`. + * + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. + * @since v8.4.0 + */ + readonly httpVersion: string; + readonly httpVersionMinor: number; + readonly httpVersionMajor: number; + /** + * The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. + * @since v8.4.0 + */ + readonly method: string; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v8.4.0 + */ + readonly rawHeaders: string[]; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly rawTrailers: string[]; + /** + * The request scheme pseudo header field indicating the scheme + * portion of the target URL. + * @since v8.4.0 + */ + readonly scheme: string; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `request.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `request.stream`. + * + * `setTimeout` method will be called on `request.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. With TLS support, + * use `request.socket.getPeerCertificate()` to obtain the client's + * authentication details. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the request. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly trailers: IncomingHttpHeaders; + /** + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. If the request is: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * Then `request.url` will be: + * + * ```js + * '/status?name=ryan' + * ``` + * + * To parse the url into its parts, `new URL()` can be used: + * + * ```console + * $ node + * > new URL('/status?name=ryan', 'http://example.com') + * URL { + * href: 'http://example.com/status?name=ryan', + * origin: 'http://example.com', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'example.com', + * hostname: 'example.com', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v8.4.0 + */ + url: string; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream`s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + read(size?: number): Buffer | string | null; + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted", hadError: boolean, code: number): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v8.4.0 + */ + export class Http2ServerResponse extends stream.Writable { + constructor(stream: ServerHttp2Stream); + /** + * See `response.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * Append a single header value to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple times. + * + * If there were no previous values for the header, this is equivalent to calling {@link setHeader}. + * + * Attempting to set a header field name or value that contains invalid characters will result in a + * [TypeError](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-typeerror) being thrown. + * + * ```js + * // Returns headers including "set-cookie: a" and "set-cookie: b" + * const server = http2.createServer((req, res) => { + * res.setHeader('set-cookie', 'a'); + * res.appendHeader('set-cookie', 'b'); + * res.writeHead(200); + * res.end('ok'); + * }); + * ``` + * @since v20.12.0 + */ + appendHeader(name: string, value: string | string[]): void; + /** + * Boolean value that indicates whether the response has completed. Starts + * as `false`. After `response.end()` executes, the value will be `true`. + * @since v8.4.0 + * @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`. + */ + readonly finished: boolean; + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * A reference to the original HTTP2 `request` object. + * @since v15.7.0 + */ + readonly req: Request; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `response.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `response.stream`. + * + * `setTimeout` method will be called on `response.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. + * + * ```js + * import http2 from 'node:http2'; + * const server = http2.createServer((req, res) => { + * const ip = req.socket.remoteAddress; + * const port = req.socket.remotePort; + * res.end(`Your IP address is ${ip} and your source port is ${port}.`); + * }).listen(3000); + * ``` + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the response. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * When true, the Date header will be automatically generated and sent in + * the response if it is not already present in the headers. Defaults to true. + * + * This should only be disabled for testing; HTTP requires the Date header + * in responses. + * @since v8.4.0 + */ + sendDate: boolean; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v8.4.0 + */ + statusCode: number; + /** + * Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns + * an empty string. + * @since v8.4.0 + */ + statusMessage: ""; + /** + * This method adds HTTP trailing headers (a header but at the end of the + * message) to the response. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + addTrailers(trailers: OutgoingHttpHeaders): void; + /** + * This method signals to the server that all of the response headers and body + * have been sent; that server should consider this message complete. + * The method, `response.end()`, MUST be called on each response. + * + * If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`. + * + * If `callback` is specified, it will be called when the response stream + * is finished. + * @since v8.4.0 + */ + end(callback?: () => void): this; + end(data: string | Uint8Array, callback?: () => void): this; + end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): this; + /** + * Reads out a header that has already been queued but not sent to the client. + * The name is case-insensitive. + * + * ```js + * const contentType = response.getHeader('content-type'); + * ``` + * @since v8.4.0 + */ + getHeader(name: string): string; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All header names are lowercase. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = response.getHeaderNames(); + * // headerNames === ['foo', 'set-cookie'] + * ``` + * @since v8.4.0 + */ + getHeaderNames(): string[]; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow copy + * is used, array values may be mutated without additional calls to various + * header-related http module methods. The keys of the returned object are the + * header names and the values are the respective header values. All header names + * are lowercase. + * + * The object returned by the `response.getHeaders()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = response.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.4.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name matching is case-insensitive. + * + * ```js + * const hasContentType = response.hasHeader('content-type'); + * ``` + * @since v8.4.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that has been queued for implicit sending. + * + * ```js + * response.removeHeader('Content-Encoding'); + * ``` + * @since v8.4.0 + */ + removeHeader(name: string): void; + /** + * Sets a single header value for implicit headers. If this header already exists + * in the to-be-sent headers, its value will be replaced. Use an array of strings + * here to send multiple headers with the same name. + * + * ```js + * response.setHeader('Content-Type', 'text/html; charset=utf-8'); + * ``` + * + * or + * + * ```js + * response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * @since v8.4.0 + */ + setHeader(name: string, value: number | string | readonly string[]): void; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * If this method is called and `response.writeHead()` has not been called, + * it will switch to implicit header mode and flush the implicit headers. + * + * This sends a chunk of the response body. This method may + * be called multiple times to provide successive parts of the body. + * + * In the `node:http` module, the response body is omitted when the + * request is a HEAD request. Similarly, the `204` and `304` responses _must not_ include a message body. + * + * `chunk` can be a string or a buffer. If `chunk` is a string, + * the second parameter specifies how to encode it into a byte stream. + * By default the `encoding` is `'utf8'`. `callback` will be called when this chunk + * of data is flushed. + * + * This is the raw HTTP body and has nothing to do with higher-level multi-part + * body encodings that may be used. + * + * The first time `response.write()` is called, it will send the buffered + * header information and the first chunk of the body to the client. The second + * time `response.write()` is called, Node.js assumes data will be streamed, + * and sends the new data separately. That is, the response is buffered up to the + * first chunk of the body. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is free again. + * @since v8.4.0 + */ + write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; + write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; + /** + * Sends a status `100 Continue` to the client, indicating that the request body + * should be sent. See the `'checkContinue'` event on `Http2Server` and `Http2SecureServer`. + * @since v8.4.0 + */ + writeContinue(): void; + /** + * Sends a status `103 Early Hints` to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }); + * ``` + * @since v18.11.0 + */ + writeEarlyHints(hints: Record): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * + * Returns a reference to the `Http2ServerResponse`, so that calls can be chained. + * + * For compatibility with `HTTP/1`, a human-readable `statusMessage` may be + * passed as the second argument. However, because the `statusMessage` has no + * meaning within HTTP/2, the argument will have no effect and a process warning + * will be emitted. + * + * ```js + * const body = 'hello world'; + * response.writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain; charset=utf-8', + * }); + * ``` + * + * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be used to determine the number of bytes in a + * given encoding. On outbound messages, Node.js does not check if Content-Length + * and the length of the body being transmitted are equal or not. However, when + * receiving messages, Node.js will automatically reject messages when the `Content-Length` does not match the actual payload size. + * + * This method may be called at most one time on a message before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; + /** + * Call `http2stream.pushStream()` with the given headers, and wrap the + * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback + * parameter if successful. When `Http2ServerRequest` is closed, the callback is + * called with an error `ERR_HTTP2_INVALID_STREAM`. + * @since v8.4.0 + * @param headers An object describing the headers + * @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of + * `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method + */ + createPushResponse( + headers: OutgoingHttpHeaders, + callback: (err: Error | null, res: Http2ServerResponse) => void, + ): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + /** + * This symbol can be set as a property on the HTTP/2 headers object with + * an array value in order to provide a list of headers considered sensitive. + */ + export const sensitiveHeaders: symbol; + /** + * Returns an object containing the default settings for an `Http2Session` instance. This method returns a new object instance every time it is called + * so instances returned may be safely modified for use. + * @since v8.4.0 + */ + export function getDefaultSettings(): Settings; + /** + * Returns a `Buffer` instance containing serialized representation of the given + * HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended + * for use with the `HTTP2-Settings` header field. + * + * ```js + * import http2 from 'node:http2'; + * + * const packed = http2.getPackedSettings({ enablePush: false }); + * + * console.log(packed.toString('base64')); + * // Prints: AAIAAAAA + * ``` + * @since v8.4.0 + */ + export function getPackedSettings(settings: Settings): Buffer; + /** + * Returns a `HTTP/2 Settings Object` containing the deserialized settings from + * the given `Buffer` as generated by `http2.getPackedSettings()`. + * @since v8.4.0 + * @param buf The packed settings. + */ + export function getUnpackedSettings(buf: Uint8Array): Settings; + /** + * Returns a `net.Server` instance that creates and manages `Http2Session` instances. + * + * Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when + * communicating + * with browser clients. + * + * ```js + * import http2 from 'node:http2'; + * + * // Create an unencrypted HTTP/2 server. + * // Since there are no browsers known that support + * // unencrypted HTTP/2, the use of `http2.createSecureServer()` + * // is necessary when communicating with browser clients. + * const server = http2.createServer(); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8000); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + export function createServer< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + >( + options: ServerOptions, + onRequestHandler?: (request: InstanceType, response: InstanceType) => void, + ): Http2Server; + /** + * Returns a `tls.Server` instance that creates and manages `Http2Session` instances. + * + * ```js + * import http2 from 'node:http2'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * }; + * + * // Create a secure HTTP/2 server + * const server = http2.createSecureServer(options); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8443); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createSecureServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + export function createSecureServer< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + >( + options: SecureServerOptions, + onRequestHandler?: (request: InstanceType, response: InstanceType) => void, + ): Http2SecureServer; + /** + * Returns a `ClientHttp2Session` instance. + * + * ```js + * import http2 from 'node:http2'; + * const client = http2.connect('https://localhost:1234'); + * + * // Use the client + * + * client.close(); + * ``` + * @since v8.4.0 + * @param authority The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port + * is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. + * @param listener Will be registered as a one-time listener of the {@link 'connect'} event. + */ + export function connect( + authority: string | url.URL, + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + /** + * Create an HTTP/2 server session from an existing socket. + * @param socket A Duplex Stream + * @param options Any `{@link createServer}` options can be provided. + * @since v20.12.0 + */ + export function performServerHandshake< + Http1Request extends typeof IncomingMessage = typeof IncomingMessage, + Http1Response extends typeof ServerResponse> = typeof ServerResponse, + Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, + Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, + >( + socket: stream.Duplex, + options?: ServerOptions, + ): ServerHttp2Session; +} +declare module "node:http2" { + export * from "http2"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/https.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/https.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a40f06b289c767cb4aa15e55e6df188e042a19f8 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/https.d.ts @@ -0,0 +1,545 @@ +/** + * HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a + * separate module. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/https.js) + */ +declare module "https" { + import { Duplex } from "node:stream"; + import * as tls from "node:tls"; + import * as http from "node:http"; + import { URL } from "node:url"; + type ServerOptions< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; + type RequestOptions = + & http.RequestOptions + & tls.SecureContextOptions + & { + checkServerIdentity?: + | ((hostname: string, cert: tls.DetailedPeerCertificate) => Error | undefined) + | undefined; + rejectUnauthorized?: boolean | undefined; // Defaults to true + servername?: string | undefined; // SNI TLS Extension + }; + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + maxCachedSessions?: number | undefined; + } + /** + * An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information. + * @since v0.4.5 + */ + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + } + interface Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > extends http.Server {} + /** + * See `http.Server` for more information. + * @since v0.3.4 + */ + class Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + > extends tls.Server { + constructor(requestListener?: http.RequestListener); + constructor( + options: ServerOptions, + requestListener?: http.RequestListener, + ); + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Duplex) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "checkContinue", listener: http.RequestListener): this; + addListener(event: "checkExpectation", listener: http.RequestListener): this; + addListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + addListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + addListener(event: "request", listener: http.RequestListener): this; + addListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + emit(event: string, ...args: any[]): boolean; + emit(event: "keylog", line: Buffer, tlsSocket: tls.TLSSocket): boolean; + emit( + event: "newSession", + sessionId: Buffer, + sessionData: Buffer, + callback: (err: Error, resp: Buffer) => void, + ): boolean; + emit( + event: "OCSPRequest", + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ): boolean; + emit(event: "resumeSession", sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; + emit(event: "secureConnection", tlsSocket: tls.TLSSocket): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: tls.TLSSocket): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Duplex): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit( + event: "checkContinue", + req: InstanceType, + res: InstanceType, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType, + ): boolean; + emit(event: "clientError", err: Error, socket: Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: Duplex, head: Buffer): boolean; + emit( + event: "request", + req: InstanceType, + res: InstanceType, + ): boolean; + emit(event: "upgrade", req: InstanceType, socket: Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + on( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + on( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Duplex) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "checkContinue", listener: http.RequestListener): this; + on(event: "checkExpectation", listener: http.RequestListener): this; + on(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + on(event: "connect", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + on(event: "request", listener: http.RequestListener): this; + on(event: "upgrade", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Duplex) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "checkContinue", listener: http.RequestListener): this; + once(event: "checkExpectation", listener: http.RequestListener): this; + once(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + once(event: "connect", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + once(event: "request", listener: http.RequestListener): this; + once(event: "upgrade", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Duplex) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "checkContinue", listener: http.RequestListener): this; + prependListener(event: "checkExpectation", listener: http.RequestListener): this; + prependListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependListener(event: "request", listener: http.RequestListener): this; + prependListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Duplex) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "checkContinue", listener: http.RequestListener): this; + prependOnceListener(event: "checkExpectation", listener: http.RequestListener): this; + prependOnceListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependOnceListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: "request", listener: http.RequestListener): this; + prependOnceListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + } + /** + * ```js + * // curl -k https://localhost:8000/ + * import https from 'node:https'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * + * Or + * + * ```js + * import https from 'node:https'; + * import fs from 'node:fs'; + * + * const options = { + * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), + * passphrase: 'sample', + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * @since v0.3.4 + * @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`. + * @param requestListener A listener to be added to the `'request'` event. + */ + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + >(requestListener?: http.RequestListener): Server; + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse> = typeof http.ServerResponse, + >( + options: ServerOptions, + requestListener?: http.RequestListener, + ): Server; + /** + * Makes a request to a secure web server. + * + * The following additional `options` from `tls.connect()` are also accepted: `ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`, `honorCipherOrder`, `key`, `passphrase`, + * `pfx`, `rejectUnauthorized`, `secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`, `highWaterMark`. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * import https from 'node:https'; + * + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * }; + * + * const req = https.request(options, (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(e); + * }); + * req.end(); + * ``` + * + * Example using options from `tls.connect()`: + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * options.agent = new https.Agent(options); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Alternatively, opt out of connection pooling by not using an `Agent`. + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * agent: false, + * }; + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('https://abc:xyz@example.com'); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): + * + * ```js + * import tls from 'node:tls'; + * import https from 'node:https'; + * import crypto from 'node:crypto'; + * + * function sha256(s) { + * return crypto.createHash('sha256').update(s).digest('base64'); + * } + * const options = { + * hostname: 'github.com', + * port: 443, + * path: '/', + * method: 'GET', + * checkServerIdentity: function(host, cert) { + * // Make sure the certificate is issued to the host we are connected to + * const err = tls.checkServerIdentity(host, cert); + * if (err) { + * return err; + * } + * + * // Pin the public key, similar to HPKP pin-sha256 pinning + * const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; + * if (sha256(cert.pubkey) !== pubkey256) { + * const msg = 'Certificate verification error: ' + + * `The public key of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // Pin the exact certificate, rather than the pub key + * const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' + + * 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; + * if (cert.fingerprint256 !== cert256) { + * const msg = 'Certificate verification error: ' + + * `The certificate of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // This loop is informational only. + * // Print the certificate and public key fingerprints of all certs in the + * // chain. Its common to pin the public key of the issuer on the public + * // internet, while pinning the public key of the service in sensitive + * // environments. + * do { + * console.log('Subject Common Name:', cert.subject.CN); + * console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256); + * + * hash = crypto.createHash('sha256'); + * console.log(' Public key ping-sha256:', sha256(cert.pubkey)); + * + * lastprint256 = cert.fingerprint256; + * cert = cert.issuerCertificate; + * } while (cert.fingerprint256 !== lastprint256); + * + * }, + * }; + * + * options.agent = new https.Agent(options); + * const req = https.request(options, (res) => { + * console.log('All OK. Server matched our pinned cert or public key'); + * console.log('statusCode:', res.statusCode); + * // Print the HPKP values + * console.log('headers:', res.headers['public-key-pins']); + * + * res.on('data', (d) => {}); + * }); + * + * req.on('error', (e) => { + * console.error(e.message); + * }); + * req.end(); + * ``` + * + * Outputs for example: + * + * ```text + * Subject Common Name: github.com + * Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16 + * Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU= + * Subject Common Name: DigiCert SHA2 Extended Validation Server CA + * Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A + * Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho= + * Subject Common Name: DigiCert High Assurance EV Root CA + * Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF + * Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18= + * All OK. Server matched our pinned cert or public key + * statusCode: 200 + * headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; + * pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; + * pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains + * ``` + * @since v0.3.6 + * @param options Accepts all `options` from `request`, with some differences in default values: + */ + function request( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + /** + * Like `http.get()` but for HTTPS. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * ```js + * import https from 'node:https'; + * + * https.get('https://encrypted.google.com/', (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * + * }).on('error', (e) => { + * console.error(e); + * }); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. + */ + function get( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function get( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + let globalAgent: Agent; +} +declare module "node:https" { + export * from "https"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3b005c11450f068b131b79ca972b17e5fb44dc57 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/index.d.ts @@ -0,0 +1,94 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +// NOTE: These definitions support Node.js and TypeScript 5.8+. + +// Reference required TypeScript libraries: +/// +/// +/// + +// Iterator definitions required for compatibility with TypeScript <5.6: +/// + +// Definitions for Node.js modules specific to TypeScript 5.7+: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/inspector.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/inspector.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..06333e4956c4c110c66152da0479b2f4e8ae1550 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,4211 @@ +// These definitions are automatically generated by the generate-inspector script. +// Do not edit this file directly. +// See scripts/generate-inspector/README.md for information on how to update the protocol definitions. +// Changes to the module itself should be added to the generator template (scripts/generate-inspector/inspector.d.ts.template). + +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/inspector.js) + */ +declare module 'inspector' { + import EventEmitter = require('node:events'); + + interface InspectorNotification { + method: string; + params: T; + } + + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + /** + * Primitive value which cannot be JSON-stringified. + */ + type UnserializableValue = string; + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string | undefined; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId | undefined; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: ObjectPreview | undefined; + /** + * @experimental + */ + customPreview?: CustomPreview | undefined; + } + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId | undefined; + } + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: EntryPreview[] | undefined; + } + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string | undefined; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview | undefined; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + } + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview | undefined; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean | undefined; + /** + * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). + */ + get?: RemoteObject | undefined; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: RemoteObject | undefined; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean | undefined; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: RemoteObject | undefined; + } + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + } + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId | undefined; + } + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: object | undefined; + } + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId | undefined; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string | undefined; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace | undefined; + /** + * Exception object if available. + */ + exception?: RemoteObject | undefined; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId | undefined; + } + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string | undefined; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace | undefined; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId | undefined; + } + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + /** + * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId | undefined; + } + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + } + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should be specified. + */ + objectId?: RemoteObjectId | undefined; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[] | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + /** + * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string | undefined; + } + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean | undefined; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean | undefined; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean | undefined; + } + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + } + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionThrown. + */ + exceptionId: number; + } + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace | undefined; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string | undefined; + } + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: object; + } + } + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + /** + * Call frame identifier. + */ + type CallFrameId = string; + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + } + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location | undefined; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject | undefined; + } + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string | undefined; + /** + * Location in the source code where scope starts + */ + startLocation?: Location | undefined; + /** + * Location in the source code where scope ends + */ + endLocation?: Location | undefined; + } + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + type?: string | undefined; + } + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string | undefined; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. + */ + urlRegex?: string | undefined; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string | undefined; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number | undefined; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Location | undefined; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean | undefined; + } + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string | undefined; + } + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean | undefined; + } + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean | undefined; + } + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean | undefined; + } + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + */ + objectGroup?: string | undefined; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean | undefined; + } + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[] | undefined; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + } + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: object | undefined; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: object | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: object | undefined; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[] | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId | undefined; + } + } + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string | undefined; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number | undefined; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number | undefined; + } + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number | undefined; + /** + * Child node ids. + */ + children?: number[] | undefined; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string | undefined; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[] | undefined; + } + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[] | undefined; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[] | undefined; + } + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean | undefined; + /** + * Collect block-based coverage. + */ + detailed?: boolean | undefined; + } + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + } + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean | undefined; + } + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean | undefined; + } + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean | undefined; + } + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + } + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number | undefined; + } + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean | undefined; + } + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string | undefined; + /** + * Included category filters. + */ + includedCategories: string[]; + } + interface StartParameterType { + traceConfig: TraceConfig; + } + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + interface DataCollectedEventDataType { + value: object[]; + } + } + namespace NodeWorker { + type WorkerID = string; + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + interface DetachParameterType { + sessionId: SessionID; + } + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + namespace Network { + /** + * Resource type as it was perceived by the rendering engine. + */ + type ResourceType = string; + /** + * Unique request identifier. + */ + type RequestId = string; + /** + * UTC time in seconds, counted from January 1, 1970. + */ + type TimeSinceEpoch = number; + /** + * Monotonically increasing time in seconds since an arbitrary point in the past. + */ + type MonotonicTime = number; + /** + * Information about the request initiator. + */ + interface Initiator { + /** + * Type of this initiator. + */ + type: string; + /** + * Initiator JavaScript stack trace, set for Script only. + * Requires the Debugger domain to be enabled. + */ + stack?: Runtime.StackTrace | undefined; + /** + * Initiator URL, set for Parser type or for Script type (when script is importing module) or for SignedExchange type. + */ + url?: string | undefined; + /** + * Initiator line number, set for Parser type or for Script type (when script is importing + * module) (0-based). + */ + lineNumber?: number | undefined; + /** + * Initiator column number, set for Parser type or for Script type (when script is importing + * module) (0-based). + */ + columnNumber?: number | undefined; + /** + * Set if another request triggered this request (e.g. preflight). + */ + requestId?: RequestId | undefined; + } + /** + * HTTP request data. + */ + interface Request { + url: string; + method: string; + headers: Headers; + hasPostData: boolean; + } + /** + * HTTP response data. + */ + interface Response { + url: string; + status: number; + statusText: string; + headers: Headers; + mimeType: string; + charset: string; + } + /** + * Request / response headers as keys / values of JSON object. + */ + interface Headers { + } + interface GetRequestPostDataParameterType { + /** + * Identifier of the network request to get content for. + */ + requestId: RequestId; + } + interface GetResponseBodyParameterType { + /** + * Identifier of the network request to get content for. + */ + requestId: RequestId; + } + interface StreamResourceContentParameterType { + /** + * Identifier of the request to stream. + */ + requestId: RequestId; + } + interface GetRequestPostDataReturnType { + /** + * Request body string, omitting files from multipart requests + */ + postData: string; + } + interface GetResponseBodyReturnType { + /** + * Response body. + */ + body: string; + /** + * True, if content was sent as base64. + */ + base64Encoded: boolean; + } + interface StreamResourceContentReturnType { + /** + * Data that has been buffered until streaming is enabled. + */ + bufferedData: string; + } + interface RequestWillBeSentEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Request data. + */ + request: Request; + /** + * Request initiator. + */ + initiator: Initiator; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Timestamp. + */ + wallTime: TimeSinceEpoch; + } + interface ResponseReceivedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Resource type. + */ + type: ResourceType; + /** + * Response data. + */ + response: Response; + } + interface LoadingFailedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Resource type. + */ + type: ResourceType; + /** + * Error message. + */ + errorText: string; + } + interface LoadingFinishedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + } + interface DataReceivedEventDataType { + /** + * Request identifier. + */ + requestId: RequestId; + /** + * Timestamp. + */ + timestamp: MonotonicTime; + /** + * Data chunk length. + */ + dataLength: number; + /** + * Actual bytes received (might be less than dataLength for compressed encodings). + */ + encodedDataLength: number; + /** + * Data that was received. + * @experimental + */ + data?: string | undefined; + } + } + namespace NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: boolean; + } + } + namespace Target { + type SessionID = string; + type TargetID = string; + interface TargetInfo { + targetId: TargetID; + type: string; + title: string; + url: string; + attached: boolean; + canAccessOpener: boolean; + } + interface SetAutoAttachParameterType { + autoAttach: boolean; + waitForDebuggerOnStart: boolean; + } + interface TargetCreatedEventDataType { + targetInfo: TargetInfo; + } + interface AttachedToTargetEventDataType { + sessionId: SessionID; + targetInfo: TargetInfo; + waitingForDebugger: boolean; + } + } + + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend. + */ + constructor(); + + /** + * Connects a session to the inspector back-end. + */ + connect(): void; + + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. + * @since v12.11.0 + */ + connectToMainThread(): void; + + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * `session.connect()` will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + + /** + * Posts a message to the inspector back-end. `callback` will be notified when + * a response is received. `callback` is a function that accepts two optional + * arguments: error and message-specific result. + * + * ```js + * session.post('Runtime.evaluate', { expression: '2 + 2' }, + * (error, { result }) => console.log(result)); + * // Output: { type: 'number', value: 4, description: '4' } + * ``` + * + * The latest version of the V8 inspector protocol is published on the + * [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + */ + post(method: string, callback?: (err: Error | null, params?: object) => void): void; + post(method: string, params?: object, callback?: (err: Error | null, params?: object) => void): void; + /** + * Returns supported domains. + */ + post(method: 'Schema.getDomains', callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Evaluates expression on global object. + */ + post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: 'Runtime.evaluate', callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + /** + * Add handler to promise with given promise object id. + */ + post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: 'Runtime.awaitPromise', callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.callFunctionOn', params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: 'Runtime.callFunctionOn', callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: 'Runtime.getProperties', callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + /** + * Releases remote object with given id. + */ + post(method: 'Runtime.releaseObject', params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObject', callback?: (err: Error | null) => void): void; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObjectGroup', callback?: (err: Error | null) => void): void; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: 'Runtime.runIfWaitingForDebugger', callback?: (err: Error | null) => void): void; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: 'Runtime.enable', callback?: (err: Error | null) => void): void; + /** + * Disables reporting of execution contexts creation. + */ + post(method: 'Runtime.disable', callback?: (err: Error | null) => void): void; + /** + * Discards collected exceptions and console API calls. + */ + post(method: 'Runtime.discardConsoleEntries', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.setCustomObjectFormatterEnabled', callback?: (err: Error | null) => void): void; + /** + * Compiles expression. + */ + post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: 'Runtime.compileScript', callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + /** + * Runs script with given id in a given context. + */ + post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.runScript', callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: 'Runtime.queryObjects', callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: 'Runtime.globalLexicalScopeNames', + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: 'Runtime.globalLexicalScopeNames', callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: 'Debugger.enable', callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + /** + * Disables debugger for given page. + */ + post(method: 'Debugger.disable', callback?: (err: Error | null) => void): void; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBreakpointsActive', callback?: (err: Error | null) => void): void; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setSkipAllPauses', callback?: (err: Error | null) => void): void; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: 'Debugger.setBreakpointByUrl', params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: 'Debugger.setBreakpointByUrl', callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: 'Debugger.setBreakpoint', callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + /** + * Removes JavaScript breakpoint. + */ + post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.removeBreakpoint', callback?: (err: Error | null) => void): void; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post( + method: 'Debugger.getPossibleBreakpoints', + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: 'Debugger.getPossibleBreakpoints', callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + /** + * Continues execution until specific location is reached. + */ + post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.continueToLocation', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.pauseOnAsyncCall', callback?: (err: Error | null) => void): void; + /** + * Steps over the statement. + */ + post(method: 'Debugger.stepOver', callback?: (err: Error | null) => void): void; + /** + * Steps into the function call. + */ + post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.stepInto', callback?: (err: Error | null) => void): void; + /** + * Steps out of the function call. + */ + post(method: 'Debugger.stepOut', callback?: (err: Error | null) => void): void; + /** + * Stops on the next JavaScript statement. + */ + post(method: 'Debugger.pause', callback?: (err: Error | null) => void): void; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: 'Debugger.scheduleStepIntoAsync', callback?: (err: Error | null) => void): void; + /** + * Resumes JavaScript execution. + */ + post(method: 'Debugger.resume', callback?: (err: Error | null) => void): void; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: 'Debugger.getStackTrace', callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + /** + * Searches for given string in script content. + */ + post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: 'Debugger.searchInContent', callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + /** + * Edits JavaScript source live. + */ + post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: 'Debugger.setScriptSource', callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + /** + * Restarts particular call frame from the beginning. + */ + post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: 'Debugger.restartFrame', callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + /** + * Returns source for the script with given id. + */ + post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: 'Debugger.getScriptSource', callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: 'Debugger.setPauseOnExceptions', params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setPauseOnExceptions', callback?: (err: Error | null) => void): void; + /** + * Evaluates expression on a given call frame. + */ + post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: 'Debugger.evaluateOnCallFrame', callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: 'Debugger.setVariableValue', params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setVariableValue', callback?: (err: Error | null) => void): void; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: 'Debugger.setReturnValue', params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setReturnValue', callback?: (err: Error | null) => void): void; + /** + * Enables or disables async call stacks tracking. + */ + post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setAsyncCallStackDepth', callback?: (err: Error | null) => void): void; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: 'Debugger.setBlackboxPatterns', params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxPatterns', callback?: (err: Error | null) => void): void; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: 'Debugger.setBlackboxedRanges', params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxedRanges', callback?: (err: Error | null) => void): void; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: 'Console.enable', callback?: (err: Error | null) => void): void; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: 'Console.disable', callback?: (err: Error | null) => void): void; + /** + * Does nothing. + */ + post(method: 'Console.clearMessages', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.disable', callback?: (err: Error | null) => void): void; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.setSamplingInterval', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.start', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.stop', callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: 'Profiler.startPreciseCoverage', params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.startPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: 'Profiler.stopPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: 'Profiler.takePreciseCoverage', callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: 'Profiler.getBestEffortCoverage', callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + post(method: 'HeapProfiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.disable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.collectGarbage', callback?: (err: Error | null) => void): void; + post( + method: 'HeapProfiler.getObjectByHeapObjectId', + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: 'HeapProfiler.getObjectByHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: 'HeapProfiler.addInspectedHeapObject', params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.addInspectedHeapObject', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startSampling', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopSampling', callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + post(method: 'HeapProfiler.getSamplingProfile', callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: 'NodeTracing.getCategories', callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + /** + * Start trace events collection. + */ + post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeTracing.start', callback?: (err: Error | null) => void): void; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: 'NodeTracing.stop', callback?: (err: Error | null) => void): void; + /** + * Sends protocol message over session with given id. + */ + post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.sendMessageToWorker', callback?: (err: Error | null) => void): void; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.enable', callback?: (err: Error | null) => void): void; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: 'NodeWorker.disable', callback?: (err: Error | null) => void): void; + /** + * Detached from the worker with given sessionId. + */ + post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.detach', callback?: (err: Error | null) => void): void; + /** + * Disables network tracking, prevents network events from being sent to the client. + */ + post(method: 'Network.disable', callback?: (err: Error | null) => void): void; + /** + * Enables network tracking, network events will now be delivered to the client. + */ + post(method: 'Network.enable', callback?: (err: Error | null) => void): void; + /** + * Returns post data sent with the request. Returns an error when no data was sent with the request. + */ + post(method: 'Network.getRequestPostData', params?: Network.GetRequestPostDataParameterType, callback?: (err: Error | null, params: Network.GetRequestPostDataReturnType) => void): void; + post(method: 'Network.getRequestPostData', callback?: (err: Error | null, params: Network.GetRequestPostDataReturnType) => void): void; + /** + * Returns content served for the given request. + */ + post(method: 'Network.getResponseBody', params?: Network.GetResponseBodyParameterType, callback?: (err: Error | null, params: Network.GetResponseBodyReturnType) => void): void; + post(method: 'Network.getResponseBody', callback?: (err: Error | null, params: Network.GetResponseBodyReturnType) => void): void; + /** + * Enables streaming of the response for the given requestId. + * If enabled, the dataReceived event contains the data that was received during streaming. + * @experimental + */ + post( + method: 'Network.streamResourceContent', + params?: Network.StreamResourceContentParameterType, + callback?: (err: Error | null, params: Network.StreamResourceContentReturnType) => void + ): void; + post(method: 'Network.streamResourceContent', callback?: (err: Error | null, params: Network.StreamResourceContentReturnType) => void): void; + /** + * Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.enable', callback?: (err: Error | null) => void): void; + /** + * Disable NodeRuntime events + */ + post(method: 'NodeRuntime.disable', callback?: (err: Error | null) => void): void; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', callback?: (err: Error | null) => void): void; + post(method: 'Target.setAutoAttach', params?: Target.SetAutoAttachParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Target.setAutoAttach', callback?: (err: Error | null) => void): void; + + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + addListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + addListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + addListener(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + addListener(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + addListener(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'inspectorNotification', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextCreated', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextDestroyed', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextsCleared'): boolean; + emit(event: 'Runtime.exceptionThrown', message: InspectorNotification): boolean; + emit(event: 'Runtime.exceptionRevoked', message: InspectorNotification): boolean; + emit(event: 'Runtime.consoleAPICalled', message: InspectorNotification): boolean; + emit(event: 'Runtime.inspectRequested', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptParsed', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptFailedToParse', message: InspectorNotification): boolean; + emit(event: 'Debugger.breakpointResolved', message: InspectorNotification): boolean; + emit(event: 'Debugger.paused', message: InspectorNotification): boolean; + emit(event: 'Debugger.resumed'): boolean; + emit(event: 'Console.messageAdded', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileStarted', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileFinished', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.addHeapSnapshotChunk', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.resetProfiles'): boolean; + emit(event: 'HeapProfiler.reportHeapSnapshotProgress', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.lastSeenObjectId', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.heapStatsUpdate', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.dataCollected', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.tracingComplete'): boolean; + emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification): boolean; + emit(event: 'Network.requestWillBeSent', message: InspectorNotification): boolean; + emit(event: 'Network.responseReceived', message: InspectorNotification): boolean; + emit(event: 'Network.loadingFailed', message: InspectorNotification): boolean; + emit(event: 'Network.loadingFinished', message: InspectorNotification): boolean; + emit(event: 'Network.dataReceived', message: InspectorNotification): boolean; + emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; + emit(event: 'NodeRuntime.waitingForDebugger'): boolean; + emit(event: 'Target.targetCreated', message: InspectorNotification): boolean; + emit(event: 'Target.attachedToTarget', message: InspectorNotification): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + on(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + on(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + on(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + on(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + on(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + on(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + on(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + on(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + on(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + once(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + once(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + once(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + once(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + once(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + once(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + once(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + once(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + once(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependListener(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependListener(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + prependListener(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependOnceListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependOnceListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependOnceListener(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependOnceListener(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + prependOnceListener(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + } + + /** + * Activate inspector on host and port. Equivalent to `node --inspect=[[host:]port]`, but can be done programmatically after node has + * started. + * + * If wait is `true`, will block until a client has connected to the inspect port + * and flow control has been passed to the debugger client. + * + * See the [security warning](https://nodejs.org/docs/latest-v24.x/api/cli.html#warning-binding-inspector-to-a-public-ipport-combination-is-insecure) + * regarding the `host` parameter usage. + * @param port Port to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param host Host to listen on for inspector connections. Defaults to what was specified on the CLI. + * @param wait Block until a client has connected. Defaults to what was specified on the CLI. + * @returns Disposable that calls `inspector.close()`. + */ + function open(port?: number, host?: string, wait?: boolean): Disposable; + + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + + /** + * Return the URL of the active inspector, or `undefined` if there is none. + * + * ```console + * $ node --inspect -p 'inspector.url()' + * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * For help, see: https://nodejs.org/en/docs/inspector + * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * + * $ node --inspect=localhost:3000 -p 'inspector.url()' + * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * For help, see: https://nodejs.org/en/docs/inspector + * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * + * $ node -p 'inspector.url()' + * undefined + * ``` + */ + function url(): string | undefined; + + /** + * Blocks until a client (existing or connected later) has sent `Runtime.runIfWaitingForDebugger` command. + * + * An exception will be thrown if there is no active inspector. + * @since v12.7.0 + */ + function waitForDebugger(): void; + + // These methods are exposed by the V8 inspector console API (inspector/v8-console.h). + // The method signatures differ from those of the Node.js console, and are deliberately + // typed permissively. + interface InspectorConsole { + debug(...data: any[]): void; + error(...data: any[]): void; + info(...data: any[]): void; + log(...data: any[]): void; + warn(...data: any[]): void; + dir(...data: any[]): void; + dirxml(...data: any[]): void; + table(...data: any[]): void; + trace(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(...data: any[]): void; + clear(...data: any[]): void; + count(label?: any): void; + countReset(label?: any): void; + assert(value?: any, ...data: any[]): void; + profile(label?: any): void; + profileEnd(label?: any): void; + time(label?: any): void; + timeLog(label?: any): void; + timeStamp(label?: any): void; + } + + /** + * An object to send messages to the remote inspector console. + * @since v11.0.0 + */ + const console: InspectorConsole; + + // DevTools protocol event broadcast methods + namespace Network { + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.requestWillBeSent` event to connected frontends. This event indicates that + * the application is about to send an HTTP request. + * @since v22.6.0 + */ + function requestWillBeSent(params: RequestWillBeSentEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.dataReceived` event to connected frontends, or buffers the data if + * `Network.streamResourceContent` command was not invoked for the given request yet. + * + * Also enables `Network.getResponseBody` command to retrieve the response data. + * @since v24.2.0 + */ + function dataReceived(params: DataReceivedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Enables `Network.getRequestPostData` command to retrieve the request data. + * @since v24.3.0 + */ + function dataSent(params: unknown): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.responseReceived` event to connected frontends. This event indicates that + * HTTP response is available. + * @since v22.6.0 + */ + function responseReceived(params: ResponseReceivedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.loadingFinished` event to connected frontends. This event indicates that + * HTTP request has finished loading. + * @since v22.6.0 + */ + function loadingFinished(params: LoadingFinishedEventDataType): void; + /** + * This feature is only available with the `--experimental-network-inspection` flag enabled. + * + * Broadcasts the `Network.loadingFailed` event to connected frontends. This event indicates that + * HTTP request has failed to load. + * @since v22.7.0 + */ + function loadingFailed(params: LoadingFailedEventDataType): void; + } +} + +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + */ +declare module 'node:inspector' { + export * from 'inspector'; +} + +/** + * The `node:inspector/promises` module provides an API for interacting with the V8 + * inspector. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/inspector/promises.js) + * @since v19.0.0 + */ +declare module 'inspector/promises' { + import EventEmitter = require('node:events'); + import { + open, + close, + url, + waitForDebugger, + console, + InspectorNotification, + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + NodeTracing, + NodeWorker, + Network, + NodeRuntime, + Target, + } from 'inspector'; + + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + * @since v19.0.0 + */ + class Session extends EventEmitter { + /** + * Create a new instance of the `inspector.Session` class. + * The inspector session needs to be connected through `session.connect()` before the messages can be dispatched to the inspector backend. + */ + constructor(); + + /** + * Connects a session to the inspector back-end. + */ + connect(): void; + + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if this API was not called on a Worker thread. + */ + connectToMainThread(): void; + + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * `session.connect()` will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + + /** + * Posts a message to the inspector back-end. + * + * ```js + * import { Session } from 'node:inspector/promises'; + * try { + * const session = new Session(); + * session.connect(); + * const result = await session.post('Runtime.evaluate', { expression: '2 + 2' }); + * console.log(result); + * } catch (error) { + * console.error(error); + * } + * // Output: { result: { type: 'number', value: 4, description: '4' } } + * ``` + * + * The latest version of the V8 inspector protocol is published on the + * [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + */ + post(method: string, params?: object): Promise; + /** + * Returns supported domains. + */ + post(method: 'Schema.getDomains'): Promise; + /** + * Evaluates expression on global object. + */ + post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType): Promise; + /** + * Add handler to promise with given promise object id. + */ + post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType): Promise; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.callFunctionOn', params?: Runtime.CallFunctionOnParameterType): Promise; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType): Promise; + /** + * Releases remote object with given id. + */ + post(method: 'Runtime.releaseObject', params?: Runtime.ReleaseObjectParameterType): Promise; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType): Promise; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: 'Runtime.runIfWaitingForDebugger'): Promise; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: 'Runtime.enable'): Promise; + /** + * Disables reporting of execution contexts creation. + */ + post(method: 'Runtime.disable'): Promise; + /** + * Discards collected exceptions and console API calls. + */ + post(method: 'Runtime.discardConsoleEntries'): Promise; + /** + * @experimental + */ + post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType): Promise; + /** + * Compiles expression. + */ + post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType): Promise; + /** + * Runs script with given id in a given context. + */ + post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType): Promise; + post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType): Promise; + /** + * Returns all let, const and class variables from global scope. + */ + post(method: 'Runtime.globalLexicalScopeNames', params?: Runtime.GlobalLexicalScopeNamesParameterType): Promise; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: 'Debugger.enable'): Promise; + /** + * Disables debugger for given page. + */ + post(method: 'Debugger.disable'): Promise; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType): Promise; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType): Promise; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: 'Debugger.setBreakpointByUrl', params?: Debugger.SetBreakpointByUrlParameterType): Promise; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType): Promise; + /** + * Removes JavaScript breakpoint. + */ + post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType): Promise; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post(method: 'Debugger.getPossibleBreakpoints', params?: Debugger.GetPossibleBreakpointsParameterType): Promise; + /** + * Continues execution until specific location is reached. + */ + post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType): Promise; + /** + * @experimental + */ + post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType): Promise; + /** + * Steps over the statement. + */ + post(method: 'Debugger.stepOver'): Promise; + /** + * Steps into the function call. + */ + post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType): Promise; + /** + * Steps out of the function call. + */ + post(method: 'Debugger.stepOut'): Promise; + /** + * Stops on the next JavaScript statement. + */ + post(method: 'Debugger.pause'): Promise; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: 'Debugger.scheduleStepIntoAsync'): Promise; + /** + * Resumes JavaScript execution. + */ + post(method: 'Debugger.resume'): Promise; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType): Promise; + /** + * Searches for given string in script content. + */ + post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType): Promise; + /** + * Edits JavaScript source live. + */ + post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType): Promise; + /** + * Restarts particular call frame from the beginning. + */ + post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType): Promise; + /** + * Returns source for the script with given id. + */ + post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType): Promise; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: 'Debugger.setPauseOnExceptions', params?: Debugger.SetPauseOnExceptionsParameterType): Promise; + /** + * Evaluates expression on a given call frame. + */ + post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType): Promise; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: 'Debugger.setVariableValue', params?: Debugger.SetVariableValueParameterType): Promise; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: 'Debugger.setReturnValue', params?: Debugger.SetReturnValueParameterType): Promise; + /** + * Enables or disables async call stacks tracking. + */ + post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType): Promise; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: 'Debugger.setBlackboxPatterns', params?: Debugger.SetBlackboxPatternsParameterType): Promise; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: 'Debugger.setBlackboxedRanges', params?: Debugger.SetBlackboxedRangesParameterType): Promise; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: 'Console.enable'): Promise; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: 'Console.disable'): Promise; + /** + * Does nothing. + */ + post(method: 'Console.clearMessages'): Promise; + post(method: 'Profiler.enable'): Promise; + post(method: 'Profiler.disable'): Promise; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType): Promise; + post(method: 'Profiler.start'): Promise; + post(method: 'Profiler.stop'): Promise; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: 'Profiler.startPreciseCoverage', params?: Profiler.StartPreciseCoverageParameterType): Promise; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: 'Profiler.stopPreciseCoverage'): Promise; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: 'Profiler.takePreciseCoverage'): Promise; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: 'Profiler.getBestEffortCoverage'): Promise; + post(method: 'HeapProfiler.enable'): Promise; + post(method: 'HeapProfiler.disable'): Promise; + post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType): Promise; + post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType): Promise; + post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType): Promise; + post(method: 'HeapProfiler.collectGarbage'): Promise; + post(method: 'HeapProfiler.getObjectByHeapObjectId', params?: HeapProfiler.GetObjectByHeapObjectIdParameterType): Promise; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: 'HeapProfiler.addInspectedHeapObject', params?: HeapProfiler.AddInspectedHeapObjectParameterType): Promise; + post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType): Promise; + post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType): Promise; + post(method: 'HeapProfiler.stopSampling'): Promise; + post(method: 'HeapProfiler.getSamplingProfile'): Promise; + /** + * Gets supported tracing categories. + */ + post(method: 'NodeTracing.getCategories'): Promise; + /** + * Start trace events collection. + */ + post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType): Promise; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: 'NodeTracing.stop'): Promise; + /** + * Sends protocol message over session with given id. + */ + post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType): Promise; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType): Promise; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: 'NodeWorker.disable'): Promise; + /** + * Detached from the worker with given sessionId. + */ + post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType): Promise; + /** + * Disables network tracking, prevents network events from being sent to the client. + */ + post(method: 'Network.disable'): Promise; + /** + * Enables network tracking, network events will now be delivered to the client. + */ + post(method: 'Network.enable'): Promise; + /** + * Returns post data sent with the request. Returns an error when no data was sent with the request. + */ + post(method: 'Network.getRequestPostData', params?: Network.GetRequestPostDataParameterType): Promise; + /** + * Returns content served for the given request. + */ + post(method: 'Network.getResponseBody', params?: Network.GetResponseBodyParameterType): Promise; + /** + * Enables streaming of the response for the given requestId. + * If enabled, the dataReceived event contains the data that was received during streaming. + * @experimental + */ + post(method: 'Network.streamResourceContent', params?: Network.StreamResourceContentParameterType): Promise; + /** + * Enable the NodeRuntime events except by `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.enable'): Promise; + /** + * Disable NodeRuntime events + */ + post(method: 'NodeRuntime.disable'): Promise; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType): Promise; + post(method: 'Target.setAutoAttach', params?: Target.SetAutoAttachParameterType): Promise; + + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + addListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + addListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + addListener(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + addListener(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + addListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + addListener(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'inspectorNotification', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextCreated', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextDestroyed', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextsCleared'): boolean; + emit(event: 'Runtime.exceptionThrown', message: InspectorNotification): boolean; + emit(event: 'Runtime.exceptionRevoked', message: InspectorNotification): boolean; + emit(event: 'Runtime.consoleAPICalled', message: InspectorNotification): boolean; + emit(event: 'Runtime.inspectRequested', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptParsed', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptFailedToParse', message: InspectorNotification): boolean; + emit(event: 'Debugger.breakpointResolved', message: InspectorNotification): boolean; + emit(event: 'Debugger.paused', message: InspectorNotification): boolean; + emit(event: 'Debugger.resumed'): boolean; + emit(event: 'Console.messageAdded', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileStarted', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileFinished', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.addHeapSnapshotChunk', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.resetProfiles'): boolean; + emit(event: 'HeapProfiler.reportHeapSnapshotProgress', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.lastSeenObjectId', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.heapStatsUpdate', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.dataCollected', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.tracingComplete'): boolean; + emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification): boolean; + emit(event: 'Network.requestWillBeSent', message: InspectorNotification): boolean; + emit(event: 'Network.responseReceived', message: InspectorNotification): boolean; + emit(event: 'Network.loadingFailed', message: InspectorNotification): boolean; + emit(event: 'Network.loadingFinished', message: InspectorNotification): boolean; + emit(event: 'Network.dataReceived', message: InspectorNotification): boolean; + emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; + emit(event: 'NodeRuntime.waitingForDebugger'): boolean; + emit(event: 'Target.targetCreated', message: InspectorNotification): boolean; + emit(event: 'Target.attachedToTarget', message: InspectorNotification): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + on(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + on(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + on(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + on(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + on(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + on(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + on(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + on(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + on(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + on(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + once(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + once(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + once(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + once(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + once(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + once(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + once(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + once(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + once(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + once(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependListener(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependListener(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + prependListener(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependOnceListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Fired when page is about to send HTTP request. + */ + prependOnceListener(event: 'Network.requestWillBeSent', listener: (message: InspectorNotification) => void): this; + /** + * Fired when HTTP response is available. + */ + prependOnceListener(event: 'Network.responseReceived', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Network.loadingFailed', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Network.loadingFinished', listener: (message: InspectorNotification) => void): this; + /** + * Fired when data chunk was received over the network. + */ + prependOnceListener(event: 'Network.dataReceived', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + /** + * This event is fired when the runtime is waiting for the debugger. For + * example, when inspector.waitingForDebugger is called + */ + prependOnceListener(event: 'NodeRuntime.waitingForDebugger', listener: () => void): this; + prependOnceListener(event: 'Target.targetCreated', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Target.attachedToTarget', listener: (message: InspectorNotification) => void): this; + } + + export { + Session, + open, + close, + url, + waitForDebugger, + console, + InspectorNotification, + Schema, + Runtime, + Debugger, + Console, + Profiler, + HeapProfiler, + NodeTracing, + NodeWorker, + Network, + NodeRuntime, + Target, + }; +} + +/** + * The `node:inspector/promises` module provides an API for interacting with the V8 + * inspector. + * @since v19.0.0 + */ +declare module 'node:inspector/promises' { + export * from 'inspector/promises'; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/module.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/module.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c0c85f9671941f7ae94fbd37b000f885f04130ea --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/module.d.ts @@ -0,0 +1,893 @@ +/** + * @since v0.3.7 + */ +declare module "module" { + import { URL } from "node:url"; + class Module { + constructor(id: string, parent?: Module); + } + interface Module extends NodeJS.Module {} + namespace Module { + export { Module }; + } + namespace Module { + /** + * A list of the names of all modules provided by Node.js. Can be used to verify + * if a module is maintained by a third party or not. + * + * Note: the list doesn't contain prefix-only modules like `node:test`. + * @since v9.3.0, v8.10.0, v6.13.0 + */ + const builtinModules: readonly string[]; + /** + * @since v12.2.0 + * @param path Filename to be used to construct the require + * function. Must be a file URL object, file URL string, or absolute path + * string. + */ + function createRequire(path: string | URL): NodeJS.Require; + namespace constants { + /** + * The following constants are returned as the `status` field in the object returned by + * {@link enableCompileCache} to indicate the result of the attempt to enable the + * [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache). + * @since v22.8.0 + */ + namespace compileCacheStatus { + /** + * Node.js has enabled the compile cache successfully. The directory used to store the + * compile cache will be returned in the `directory` field in the + * returned object. + */ + const ENABLED: number; + /** + * The compile cache has already been enabled before, either by a previous call to + * {@link enableCompileCache}, or by the `NODE_COMPILE_CACHE=dir` + * environment variable. The directory used to store the + * compile cache will be returned in the `directory` field in the + * returned object. + */ + const ALREADY_ENABLED: number; + /** + * Node.js fails to enable the compile cache. This can be caused by the lack of + * permission to use the specified directory, or various kinds of file system errors. + * The detail of the failure will be returned in the `message` field in the + * returned object. + */ + const FAILED: number; + /** + * Node.js cannot enable the compile cache because the environment variable + * `NODE_DISABLE_COMPILE_CACHE=1` has been set. + */ + const DISABLED: number; + } + } + interface EnableCompileCacheResult { + /** + * One of the {@link constants.compileCacheStatus} + */ + status: number; + /** + * If Node.js cannot enable the compile cache, this contains + * the error message. Only set if `status` is `module.constants.compileCacheStatus.FAILED`. + */ + message?: string; + /** + * If the compile cache is enabled, this contains the directory + * where the compile cache is stored. Only set if `status` is + * `module.constants.compileCacheStatus.ENABLED` or + * `module.constants.compileCacheStatus.ALREADY_ENABLED`. + */ + directory?: string; + } + /** + * Enable [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache) + * in the current Node.js instance. + * + * If `cacheDir` is not specified, Node.js will either use the directory specified by the + * `NODE_COMPILE_CACHE=dir` environment variable if it's set, or use + * `path.join(os.tmpdir(), 'node-compile-cache')` otherwise. For general use cases, it's + * recommended to call `module.enableCompileCache()` without specifying the `cacheDir`, + * so that the directory can be overridden by the `NODE_COMPILE_CACHE` environment + * variable when necessary. + * + * Since compile cache is supposed to be a quiet optimization that is not required for the + * application to be functional, this method is designed to not throw any exception when the + * compile cache cannot be enabled. Instead, it will return an object containing an error + * message in the `message` field to aid debugging. + * If compile cache is enabled successfully, the `directory` field in the returned object + * contains the path to the directory where the compile cache is stored. The `status` + * field in the returned object would be one of the `module.constants.compileCacheStatus` + * values to indicate the result of the attempt to enable the + * [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache). + * + * This method only affects the current Node.js instance. To enable it in child worker threads, + * either call this method in child worker threads too, or set the + * `process.env.NODE_COMPILE_CACHE` value to compile cache directory so the behavior can + * be inherited into the child workers. The directory can be obtained either from the + * `directory` field returned by this method, or with {@link getCompileCacheDir}. + * @since v22.8.0 + * @param cacheDir Optional path to specify the directory where the compile cache + * will be stored/retrieved. + */ + function enableCompileCache(cacheDir?: string): EnableCompileCacheResult; + /** + * Flush the [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache) + * accumulated from modules already loaded + * in the current Node.js instance to disk. This returns after all the flushing + * file system operations come to an end, no matter they succeed or not. If there + * are any errors, this will fail silently, since compile cache misses should not + * interfere with the actual operation of the application. + * @since v22.10.0 + */ + function flushCompileCache(): void; + /** + * @since v22.8.0 + * @return Path to the [module compile cache](https://nodejs.org/docs/latest-v24.x/api/module.html#module-compile-cache) + * directory if it is enabled, or `undefined` otherwise. + */ + function getCompileCacheDir(): string | undefined; + /** + * ```text + * /path/to/project + * ├ packages/ + * ├ bar/ + * ├ bar.js + * └ package.json // name = '@foo/bar' + * └ qux/ + * ├ node_modules/ + * └ some-package/ + * └ package.json // name = 'some-package' + * ├ qux.js + * └ package.json // name = '@foo/qux' + * ├ main.js + * └ package.json // name = '@foo' + * ``` + * ```js + * // /path/to/project/packages/bar/bar.js + * import { findPackageJSON } from 'node:module'; + * + * findPackageJSON('..', import.meta.url); + * // '/path/to/project/package.json' + * // Same result when passing an absolute specifier instead: + * findPackageJSON(new URL('../', import.meta.url)); + * findPackageJSON(import.meta.resolve('../')); + * + * findPackageJSON('some-package', import.meta.url); + * // '/path/to/project/packages/bar/node_modules/some-package/package.json' + * // When passing an absolute specifier, you might get a different result if the + * // resolved module is inside a subfolder that has nested `package.json`. + * findPackageJSON(import.meta.resolve('some-package')); + * // '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json' + * + * findPackageJSON('@foo/qux', import.meta.url); + * // '/path/to/project/packages/qux/package.json' + * ``` + * @since v22.14.0 + * @param specifier The specifier for the module whose `package.json` to + * retrieve. When passing a _bare specifier_, the `package.json` at the root of + * the package is returned. When passing a _relative specifier_ or an _absolute specifier_, + * the closest parent `package.json` is returned. + * @param base The absolute location (`file:` URL string or FS path) of the + * containing module. For CJS, use `__filename` (not `__dirname`!); for ESM, use + * `import.meta.url`. You do not need to pass it if `specifier` is an _absolute specifier_. + * @returns A path if the `package.json` is found. When `startLocation` + * is a package, the package's root `package.json`; when a relative or unresolved, the closest + * `package.json` to the `startLocation`. + */ + function findPackageJSON(specifier: string | URL, base?: string | URL): string | undefined; + /** + * @since v18.6.0, v16.17.0 + */ + function isBuiltin(moduleName: string): boolean; + interface RegisterOptions { + /** + * If you want to resolve `specifier` relative to a + * base URL, such as `import.meta.url`, you can pass that URL here. This + * property is ignored if the `parentURL` is supplied as the second argument. + * @default 'data:' + */ + parentURL?: string | URL | undefined; + /** + * Any arbitrary, cloneable JavaScript value to pass into the + * {@link initialize} hook. + */ + data?: Data | undefined; + /** + * [Transferable objects](https://nodejs.org/docs/latest-v24.x/api/worker_threads.html#portpostmessagevalue-transferlist) + * to be passed into the `initialize` hook. + */ + transferList?: any[] | undefined; + } + /* eslint-disable @definitelytyped/no-unnecessary-generics */ + /** + * Register a module that exports hooks that customize Node.js module + * resolution and loading behavior. See + * [Customization hooks](https://nodejs.org/docs/latest-v24.x/api/module.html#customization-hooks). + * + * This feature requires `--allow-worker` if used with the + * [Permission Model](https://nodejs.org/docs/latest-v24.x/api/permissions.html#permission-model). + * @since v20.6.0, v18.19.0 + * @param specifier Customization hooks to be registered; this should be + * the same string that would be passed to `import()`, except that if it is + * relative, it is resolved relative to `parentURL`. + * @param parentURL f you want to resolve `specifier` relative to a base + * URL, such as `import.meta.url`, you can pass that URL here. + */ + function register( + specifier: string | URL, + parentURL?: string | URL, + options?: RegisterOptions, + ): void; + function register(specifier: string | URL, options?: RegisterOptions): void; + interface RegisterHooksOptions { + /** + * See [load hook](https://nodejs.org/docs/latest-v24.x/api/module.html#loadurl-context-nextload). + * @default undefined + */ + load?: LoadHookSync | undefined; + /** + * See [resolve hook](https://nodejs.org/docs/latest-v24.x/api/module.html#resolvespecifier-context-nextresolve). + * @default undefined + */ + resolve?: ResolveHookSync | undefined; + } + interface ModuleHooks { + /** + * Deregister the hook instance. + */ + deregister(): void; + } + /** + * Register [hooks](https://nodejs.org/docs/latest-v24.x/api/module.html#customization-hooks) + * that customize Node.js module resolution and loading behavior. + * @since v22.15.0 + * @experimental + */ + function registerHooks(options: RegisterHooksOptions): ModuleHooks; + interface StripTypeScriptTypesOptions { + /** + * Possible values are: + * * `'strip'` Only strip type annotations without performing the transformation of TypeScript features. + * * `'transform'` Strip type annotations and transform TypeScript features to JavaScript. + * @default 'strip' + */ + mode?: "strip" | "transform" | undefined; + /** + * Only when `mode` is `'transform'`, if `true`, a source map + * will be generated for the transformed code. + * @default false + */ + sourceMap?: boolean | undefined; + /** + * Specifies the source url used in the source map. + */ + sourceUrl?: string | undefined; + } + /** + * `module.stripTypeScriptTypes()` removes type annotations from TypeScript code. It + * can be used to strip type annotations from TypeScript code before running it + * with `vm.runInContext()` or `vm.compileFunction()`. + * By default, it will throw an error if the code contains TypeScript features + * that require transformation such as `Enums`, + * see [type-stripping](https://nodejs.org/docs/latest-v24.x/api/typescript.md#type-stripping) for more information. + * When mode is `'transform'`, it also transforms TypeScript features to JavaScript, + * see [transform TypeScript features](https://nodejs.org/docs/latest-v24.x/api/typescript.md#typescript-features) for more information. + * When mode is `'strip'`, source maps are not generated, because locations are preserved. + * If `sourceMap` is provided, when mode is `'strip'`, an error will be thrown. + * + * _WARNING_: The output of this function should not be considered stable across Node.js versions, + * due to changes in the TypeScript parser. + * + * ```js + * import { stripTypeScriptTypes } from 'node:module'; + * const code = 'const a: number = 1;'; + * const strippedCode = stripTypeScriptTypes(code); + * console.log(strippedCode); + * // Prints: const a = 1; + * ``` + * + * If `sourceUrl` is provided, it will be used appended as a comment at the end of the output: + * + * ```js + * import { stripTypeScriptTypes } from 'node:module'; + * const code = 'const a: number = 1;'; + * const strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' }); + * console.log(strippedCode); + * // Prints: const a = 1\n\n//# sourceURL=source.ts; + * ``` + * + * When `mode` is `'transform'`, the code is transformed to JavaScript: + * + * ```js + * import { stripTypeScriptTypes } from 'node:module'; + * const code = ` + * namespace MathUtil { + * export const add = (a: number, b: number) => a + b; + * }`; + * const strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true }); + * console.log(strippedCode); + * // Prints: + * // var MathUtil; + * // (function(MathUtil) { + * // MathUtil.add = (a, b)=>a + b; + * // })(MathUtil || (MathUtil = {})); + * // # sourceMappingURL=data:application/json;base64, ... + * ``` + * @since v22.13.0 + * @param code The code to strip type annotations from. + * @returns The code with type annotations stripped. + */ + function stripTypeScriptTypes(code: string, options?: StripTypeScriptTypesOptions): string; + /* eslint-enable @definitelytyped/no-unnecessary-generics */ + /** + * The `module.syncBuiltinESMExports()` method updates all the live bindings for + * builtin `ES Modules` to match the properties of the `CommonJS` exports. It + * does not add or remove exported names from the `ES Modules`. + * + * ```js + * import fs from 'node:fs'; + * import assert from 'node:assert'; + * import { syncBuiltinESMExports } from 'node:module'; + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('node:fs').then((esmFS) => { + * // It syncs the existing readFile property with the new value + * assert.strictEqual(esmFS.readFile, newAPI); + * // readFileSync has been deleted from the required fs + * assert.strictEqual('readFileSync' in fs, false); + * // syncBuiltinESMExports() does not remove readFileSync from esmFS + * assert.strictEqual('readFileSync' in esmFS, true); + * // syncBuiltinESMExports() does not add names + * assert.strictEqual(esmFS.newAPI, undefined); + * }); + * ``` + * @since v12.12.0 + */ + function syncBuiltinESMExports(): void; + interface ImportAttributes extends NodeJS.Dict { + type?: string | undefined; + } + type ModuleFormat = + | "addon" + | "builtin" + | "commonjs" + | "commonjs-typescript" + | "json" + | "module" + | "module-typescript" + | "wasm"; + type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray; + /** + * The `initialize` hook provides a way to define a custom function that runs in + * the hooks thread when the hooks module is initialized. Initialization happens + * when the hooks module is registered via {@link register}. + * + * This hook can receive data from a {@link register} invocation, including + * ports and other transferable objects. The return value of `initialize` can be a + * `Promise`, in which case it will be awaited before the main application thread + * execution resumes. + */ + type InitializeHook = (data: Data) => void | Promise; + interface ResolveHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + /** + * The module importing this one, or undefined if this is the Node.js entry point + */ + parentURL: string | undefined; + } + interface ResolveFnOutput { + /** + * A hint to the load hook (it might be ignored); can be an intermediary value. + */ + format?: string | null | undefined; + /** + * The import attributes to use when caching the module (optional; if excluded the input will be used) + */ + importAttributes?: ImportAttributes | undefined; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The absolute URL to which this input resolves + */ + url: string; + } + /** + * The `resolve` hook chain is responsible for telling Node.js where to find and + * how to cache a given `import` statement or expression, or `require` call. It can + * optionally return a format (such as `'module'`) as a hint to the `load` hook. If + * a format is specified, the `load` hook is ultimately responsible for providing + * the final `format` value (and it is free to ignore the hint provided by + * `resolve`); if `resolve` provides a `format`, a custom `load` hook is required + * even if only to pass the value to the Node.js default `load` hook. + */ + type ResolveHook = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: Partial, + ) => ResolveFnOutput | Promise, + ) => ResolveFnOutput | Promise; + type ResolveHookSync = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: Partial, + ) => ResolveFnOutput, + ) => ResolveFnOutput; + interface LoadHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * The format optionally supplied by the `resolve` hook chain (can be an intermediary value). + */ + format: string | null | undefined; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + } + interface LoadFnOutput { + format: string | null | undefined; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The source for Node.js to evaluate + */ + source?: ModuleSource | undefined; + } + /** + * The `load` hook provides a way to define a custom method of determining how a + * URL should be interpreted, retrieved, and parsed. It is also in charge of + * validating the import attributes. + */ + type LoadHook = ( + url: string, + context: LoadHookContext, + nextLoad: ( + url: string, + context?: Partial, + ) => LoadFnOutput | Promise, + ) => LoadFnOutput | Promise; + type LoadHookSync = ( + url: string, + context: LoadHookContext, + nextLoad: ( + url: string, + context?: Partial, + ) => LoadFnOutput, + ) => LoadFnOutput; + interface SourceMapsSupport { + /** + * If the source maps support is enabled + */ + enabled: boolean; + /** + * If the support is enabled for files in `node_modules`. + */ + nodeModules: boolean; + /** + * If the support is enabled for generated code from `eval` or `new Function`. + */ + generatedCode: boolean; + } + /** + * This method returns whether the [Source Map v3](https://tc39.es/ecma426/) support for stack + * traces is enabled. + * @since v23.7.0, v22.14.0 + */ + function getSourceMapsSupport(): SourceMapsSupport; + /** + * `path` is the resolved path for the file for which a corresponding source map + * should be fetched. + * @since v13.7.0, v12.17.0 + * @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise. + */ + function findSourceMap(path: string): SourceMap | undefined; + interface SetSourceMapsSupportOptions { + /** + * If enabling the support for files in `node_modules`. + * @default false + */ + nodeModules?: boolean | undefined; + /** + * If enabling the support for generated code from `eval` or `new Function`. + * @default false + */ + generatedCode?: boolean | undefined; + } + /** + * This function enables or disables the [Source Map v3](https://tc39.es/ecma426/) support for + * stack traces. + * + * It provides same features as launching Node.js process with commandline options + * `--enable-source-maps`, with additional options to alter the support for files + * in `node_modules` or generated codes. + * + * Only source maps in JavaScript files that are loaded after source maps has been + * enabled will be parsed and loaded. Preferably, use the commandline options + * `--enable-source-maps` to avoid losing track of source maps of modules loaded + * before this API call. + * @since v23.7.0, v22.14.0 + */ + function setSourceMapsSupport(enabled: boolean, options?: SetSourceMapsSupportOptions): void; + interface SourceMapConstructorOptions { + /** + * @since v21.0.0, v20.5.0 + */ + lineLengths?: readonly number[] | undefined; + } + interface SourceMapPayload { + file: string; + version: number; + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: string; + sourceRoot: string; + } + interface SourceMapping { + generatedLine: number; + generatedColumn: number; + originalSource: string; + originalLine: number; + originalColumn: number; + } + interface SourceOrigin { + /** + * The name of the range in the source map, if one was provided + */ + name: string | undefined; + /** + * The file name of the original source, as reported in the SourceMap + */ + fileName: string; + /** + * The 1-indexed lineNumber of the corresponding call site in the original source + */ + lineNumber: number; + /** + * The 1-indexed columnNumber of the corresponding call site in the original source + */ + columnNumber: number; + } + /** + * @since v13.7.0, v12.17.0 + */ + class SourceMap { + constructor(payload: SourceMapPayload, options?: SourceMapConstructorOptions); + /** + * Getter for the payload used to construct the `SourceMap` instance. + */ + readonly payload: SourceMapPayload; + /** + * Given a line offset and column offset in the generated source + * file, returns an object representing the SourceMap range in the + * original file if found, or an empty object if not. + * + * The object returned contains the following keys: + * + * The returned value represents the raw range as it appears in the + * SourceMap, based on zero-indexed offsets, _not_ 1-indexed line and + * column numbers as they appear in Error messages and CallSite + * objects. + * + * To get the corresponding 1-indexed line and column numbers from a + * lineNumber and columnNumber as they are reported by Error stacks + * and CallSite objects, use `sourceMap.findOrigin(lineNumber, columnNumber)` + * @param lineOffset The zero-indexed line number offset in the generated source + * @param columnOffset The zero-indexed column number offset in the generated source + */ + findEntry(lineOffset: number, columnOffset: number): SourceMapping | {}; + /** + * Given a 1-indexed `lineNumber` and `columnNumber` from a call site in the generated source, + * find the corresponding call site location in the original source. + * + * If the `lineNumber` and `columnNumber` provided are not found in any source map, + * then an empty object is returned. + * @param lineNumber The 1-indexed line number of the call site in the generated source + * @param columnNumber The 1-indexed column number of the call site in the generated source + */ + findOrigin(lineNumber: number, columnNumber: number): SourceOrigin | {}; + } + function runMain(main?: string): void; + function wrap(script: string): string; + } + global { + interface ImportMeta { + /** + * The directory name of the current module. + * + * This is the same as the `path.dirname()` of the `import.meta.filename`. + * + * > **Caveat**: only present on `file:` modules. + * @since v21.2.0, v20.11.0 + */ + dirname: string; + /** + * The full absolute path and filename of the current module, with + * symlinks resolved. + * + * This is the same as the `url.fileURLToPath()` of the `import.meta.url`. + * + * > **Caveat** only local modules support this property. Modules not using the + * > `file:` protocol will not provide it. + * @since v21.2.0, v20.11.0 + */ + filename: string; + /** + * The absolute `file:` URL of the module. + * + * This is defined exactly the same as it is in browsers providing the URL of the + * current module file. + * + * This enables useful patterns such as relative file loading: + * + * ```js + * import { readFileSync } from 'node:fs'; + * const buffer = readFileSync(new URL('./data.proto', import.meta.url)); + * ``` + */ + url: string; + /** + * `import.meta.resolve` is a module-relative resolution function scoped to + * each module, returning the URL string. + * + * ```js + * const dependencyAsset = import.meta.resolve('component-lib/asset.css'); + * // file:///app/node_modules/component-lib/asset.css + * import.meta.resolve('./dep.js'); + * // file:///app/dep.js + * ``` + * + * All features of the Node.js module resolution are supported. Dependency + * resolutions are subject to the permitted exports resolutions within the package. + * + * **Caveats**: + * + * * This can result in synchronous file-system operations, which + * can impact performance similarly to `require.resolve`. + * * This feature is not available within custom loaders (it would + * create a deadlock). + * @since v13.9.0, v12.16.0 + * @param specifier The module specifier to resolve relative to the + * current module. + * @param parent An optional absolute parent module URL to resolve from. + * **Default:** `import.meta.url` + * @returns The absolute URL string that the specifier would resolve to. + */ + resolve(specifier: string, parent?: string | URL): string; + /** + * `true` when the current module is the entry point of the current process; `false` otherwise. + * + * Equivalent to `require.main === module` in CommonJS. + * + * Analogous to Python's `__name__ == "__main__"`. + * + * ```js + * export function foo() { + * return 'Hello, world'; + * } + * + * function main() { + * const message = foo(); + * console.log(message); + * } + * + * if (import.meta.main) main(); + * // `foo` can be imported from another module without possible side-effects from `main` + * ``` + * @since v24.2.0 + * @experimental + */ + main: boolean; + } + namespace NodeJS { + interface Module { + /** + * The module objects required for the first time by this one. + * @since v0.1.16 + */ + children: Module[]; + /** + * The `module.exports` object is created by the `Module` system. Sometimes this is + * not acceptable; many want their module to be an instance of some class. To do + * this, assign the desired export object to `module.exports`. + * @since v0.1.16 + */ + exports: any; + /** + * The fully resolved filename of the module. + * @since v0.1.16 + */ + filename: string; + /** + * The identifier for the module. Typically this is the fully resolved + * filename. + * @since v0.1.16 + */ + id: string; + /** + * `true` if the module is running during the Node.js preload + * phase. + * @since v15.4.0, v14.17.0 + */ + isPreloading: boolean; + /** + * Whether or not the module is done loading, or is in the process of + * loading. + * @since v0.1.16 + */ + loaded: boolean; + /** + * The module that first required this one, or `null` if the current module is the + * entry point of the current process, or `undefined` if the module was loaded by + * something that is not a CommonJS module (e.g. REPL or `import`). + * @since v0.1.16 + * @deprecated Please use `require.main` and `module.children` instead. + */ + parent: Module | null | undefined; + /** + * The directory name of the module. This is usually the same as the + * `path.dirname()` of the `module.id`. + * @since v11.14.0 + */ + path: string; + /** + * The search paths for the module. + * @since v0.4.0 + */ + paths: string[]; + /** + * The `module.require()` method provides a way to load a module as if + * `require()` was called from the original module. + * @since v0.5.1 + */ + require(id: string): any; + } + interface Require { + /** + * Used to import modules, `JSON`, and local files. + * @since v0.1.13 + */ + (id: string): any; + /** + * Modules are cached in this object when they are required. By deleting a key + * value from this object, the next `require` will reload the module. + * This does not apply to + * [native addons](https://nodejs.org/docs/latest-v24.x/api/addons.html), + * for which reloading will result in an error. + * @since v0.3.0 + */ + cache: Dict; + /** + * Instruct `require` on how to handle certain file extensions. + * @since v0.3.0 + * @deprecated + */ + extensions: RequireExtensions; + /** + * The `Module` object representing the entry script loaded when the Node.js + * process launched, or `undefined` if the entry point of the program is not a + * CommonJS module. + * @since v0.1.17 + */ + main: Module | undefined; + /** + * @since v0.3.0 + */ + resolve: RequireResolve; + } + /** @deprecated */ + interface RequireExtensions extends Dict<(module: Module, filename: string) => any> { + ".js": (module: Module, filename: string) => any; + ".json": (module: Module, filename: string) => any; + ".node": (module: Module, filename: string) => any; + } + interface RequireResolveOptions { + /** + * Paths to resolve module location from. If present, these + * paths are used instead of the default resolution paths, with the exception + * of + * [GLOBAL\_FOLDERS](https://nodejs.org/docs/latest-v24.x/api/modules.html#loading-from-the-global-folders) + * like `$HOME/.node_modules`, which are + * always included. Each of these paths is used as a starting point for + * the module resolution algorithm, meaning that the `node_modules` hierarchy + * is checked from this location. + * @since v8.9.0 + */ + paths?: string[] | undefined; + } + interface RequireResolve { + /** + * Use the internal `require()` machinery to look up the location of a module, + * but rather than loading the module, just return the resolved filename. + * + * If the module can not be found, a `MODULE_NOT_FOUND` error is thrown. + * @since v0.3.0 + * @param request The module path to resolve. + */ + (request: string, options?: RequireResolveOptions): string; + /** + * Returns an array containing the paths searched during resolution of `request` or + * `null` if the `request` string references a core module, for example `http` or + * `fs`. + * @since v8.9.0 + * @param request The module path whose lookup paths are being retrieved. + */ + paths(request: string): string[] | null; + } + } + /** + * The directory name of the current module. This is the same as the + * `path.dirname()` of the `__filename`. + * @since v0.1.27 + */ + var __dirname: string; + /** + * The file name of the current module. This is the current module file's absolute + * path with symlinks resolved. + * + * For a main program this is not necessarily the same as the file name used in the + * command line. + * @since v0.0.1 + */ + var __filename: string; + /** + * The `exports` variable is available within a module's file-level scope, and is + * assigned the value of `module.exports` before the module is evaluated. + * @since v0.1.16 + */ + var exports: NodeJS.Module["exports"]; + /** + * A reference to the current module. + * @since v0.1.16 + */ + var module: NodeJS.Module; + /** + * @since v0.1.13 + */ + var require: NodeJS.Require; + // Global-scope aliases for backwards compatibility with @types/node <13.0.x + // TODO: consider removing in a future major version update + /** @deprecated Use `NodeJS.Module` instead. */ + interface NodeModule extends NodeJS.Module {} + /** @deprecated Use `NodeJS.Require` instead. */ + interface NodeRequire extends NodeJS.Require {} + /** @deprecated Use `NodeJS.RequireResolve` instead. */ + interface RequireResolve extends NodeJS.RequireResolve {} + } + export = Module; +} +declare module "node:module" { + import module = require("module"); + export = module; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/net.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/net.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7a4c5cb7c043d5ed34b30cb2270b524b46d6e408 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/net.d.ts @@ -0,0 +1,1032 @@ +/** + * > Stability: 2 - Stable + * + * The `node:net` module provides an asynchronous network API for creating stream-based + * TCP or `IPC` servers ({@link createServer}) and clients + * ({@link createConnection}). + * + * It can be accessed using: + * + * ```js + * import net from 'node:net'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/net.js) + */ +declare module "net" { + import * as stream from "node:stream"; + import { Abortable, EventEmitter } from "node:events"; + import * as dns from "node:dns"; + type LookupFunction = ( + hostname: string, + options: dns.LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | dns.LookupAddress[], family?: number) => void, + ) => void; + interface AddressInfo { + address: string; + family: string; + port: number; + } + interface SocketConstructorOpts { + fd?: number | undefined; + allowHalfOpen?: boolean | undefined; + onread?: OnReadOpts | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + signal?: AbortSignal; + } + interface OnReadOpts { + buffer: Uint8Array | (() => Uint8Array); + /** + * This function is called for every chunk of incoming data. + * Two arguments are passed to it: the number of bytes written to `buffer` and a reference to `buffer`. + * Return `false` from this function to implicitly `pause()` the socket. + */ + callback(bytesWritten: number, buffer: Uint8Array): boolean; + } + interface TcpSocketConnectOpts { + port: number; + host?: string | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + hints?: number | undefined; + family?: number | undefined; + lookup?: LookupFunction | undefined; + noDelay?: boolean | undefined; + keepAlive?: boolean | undefined; + keepAliveInitialDelay?: number | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamily?: boolean | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamilyAttemptTimeout?: number | undefined; + blockList?: BlockList | undefined; + } + interface IpcSocketConnectOpts { + path: string; + } + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + type SocketReadyState = "opening" | "open" | "readOnly" | "writeOnly" | "closed"; + /** + * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint + * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also + * an `EventEmitter`. + * + * A `net.Socket` can be created by the user and used directly to interact with + * a server. For example, it is returned by {@link createConnection}, + * so the user can use it to talk to the server. + * + * It can also be created by Node.js and passed to the user when a connection + * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use + * it to interact with the client. + * @since v0.3.4 + */ + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + /** + * Destroys the socket after all data is written. If the `finish` event was already emitted the socket is destroyed immediately. + * If the socket is still writable it implicitly calls `socket.end()`. + * @since v0.3.4 + */ + destroySoon(): void; + /** + * Sends data on the socket. The second parameter specifies the encoding in the + * case of a string. It defaults to UTF8 encoding. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. + * + * The optional `callback` parameter will be executed when the data is finally + * written out, which may not be immediately. + * + * See `Writable` stream `write()` method for more + * information. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + */ + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + /** + * Initiate a connection on a given socket. + * + * Possible signatures: + * + * * `socket.connect(options[, connectListener])` + * * `socket.connect(path[, connectListener])` for `IPC` connections. + * * `socket.connect(port[, host][, connectListener])` for TCP connections. + * * Returns: `net.Socket` The socket itself. + * + * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, + * instead of a `'connect'` event, an `'error'` event will be emitted with + * the error passed to the `'error'` listener. + * The last parameter `connectListener`, if supplied, will be added as a listener + * for the `'connect'` event **once**. + * + * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined + * behavior. + */ + connect(options: SocketConnectOpts, connectionListener?: () => void): this; + connect(port: number, host: string, connectionListener?: () => void): this; + connect(port: number, connectionListener?: () => void): this; + connect(path: string, connectionListener?: () => void): this; + /** + * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information. + * @since v0.1.90 + * @return The socket itself. + */ + setEncoding(encoding?: BufferEncoding): this; + /** + * Pauses the reading of data. That is, `'data'` events will not be emitted. + * Useful to throttle back an upload. + * @return The socket itself. + */ + pause(): this; + /** + * Close the TCP connection by sending an RST packet and destroy the stream. + * If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected. + * Otherwise, it will call `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. + * If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an `ERR_INVALID_HANDLE_TYPE` Error. + * @since v18.3.0, v16.17.0 + */ + resetAndDestroy(): this; + /** + * Resumes reading after a call to `socket.pause()`. + * @return The socket itself. + */ + resume(): this; + /** + * Sets the socket to timeout after `timeout` milliseconds of inactivity on + * the socket. By default `net.Socket` do not have a timeout. + * + * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to + * end the connection. + * + * ```js + * socket.setTimeout(3000); + * socket.on('timeout', () => { + * console.log('socket timeout'); + * socket.end(); + * }); + * ``` + * + * If `timeout` is 0, then the existing idle timeout is disabled. + * + * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. + * @since v0.1.90 + * @return The socket itself. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Enable/disable the use of Nagle's algorithm. + * + * When a TCP connection is created, it will have Nagle's algorithm enabled. + * + * Nagle's algorithm delays data before it is sent via the network. It attempts + * to optimize throughput at the expense of latency. + * + * Passing `true` for `noDelay` or not passing an argument will disable Nagle's + * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's + * algorithm. + * @since v0.1.90 + * @param [noDelay=true] + * @return The socket itself. + */ + setNoDelay(noDelay?: boolean): this; + /** + * Enable/disable keep-alive functionality, and optionally set the initial + * delay before the first keepalive probe is sent on an idle socket. + * + * Set `initialDelay` (in milliseconds) to set the delay between the last + * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default + * (or previous) setting. + * + * Enabling the keep-alive functionality will set the following socket options: + * + * * `SO_KEEPALIVE=1` + * * `TCP_KEEPIDLE=initialDelay` + * * `TCP_KEEPCNT=10` + * * `TCP_KEEPINTVL=1` + * @since v0.1.92 + * @param [enable=false] + * @param [initialDelay=0] + * @return The socket itself. + */ + setKeepAlive(enable?: boolean, initialDelay?: number): this; + /** + * Returns the bound `address`, the address `family` name and `port` of the + * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + * @since v0.1.90 + */ + address(): AddressInfo | {}; + /** + * Calling `unref()` on a socket will allow the program to exit if this is the only + * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + unref(): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will _not_ let the program exit if it's the only socket left (the default behavior). + * If the socket is `ref`ed calling `ref` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + ref(): this; + /** + * This property is only present if the family autoselection algorithm is enabled in `socket.connect(options)` + * and it is an array of the addresses that have been attempted. + * + * Each address is a string in the form of `$IP:$PORT`. + * If the connection was successful, then the last address is the one that the socket is currently connected to. + * @since v19.4.0 + */ + readonly autoSelectFamilyAttemptedAddresses: string[]; + /** + * This property shows the number of characters buffered for writing. The buffer + * may contain strings whose length after encoding is not yet known. So this number + * is only an approximation of the number of bytes in the buffer. + * + * `net.Socket` has the property that `socket.write()` always works. This is to + * help users get up and running quickly. The computer cannot always keep up + * with the amount of data that is written to a socket. The network connection + * simply might be too slow. Node.js will internally queue up the data written to a + * socket and send it out over the wire when it is possible. + * + * The consequence of this internal buffering is that memory may grow. + * Users who experience large or growing `bufferSize` should attempt to + * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`. + * @since v0.3.8 + * @deprecated Since v14.6.0 - Use `writableLength` instead. + */ + readonly bufferSize: number; + /** + * The amount of received bytes. + * @since v0.5.3 + */ + readonly bytesRead: number; + /** + * The amount of bytes sent. + * @since v0.5.3 + */ + readonly bytesWritten: number; + /** + * If `true`, `socket.connect(options[, connectListener])` was + * called and has not yet finished. It will stay `true` until the socket becomes + * connected, then it is set to `false` and the `'connect'` event is emitted. Note + * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. + * @since v6.1.0 + */ + readonly connecting: boolean; + /** + * This is `true` if the socket is not connected yet, either because `.connect()`has not yet been called or because it is still in the process of connecting + * (see `socket.connecting`). + * @since v11.2.0, v10.16.0 + */ + readonly pending: boolean; + /** + * See `writable.destroyed` for further details. + */ + readonly destroyed: boolean; + /** + * The string representation of the local IP address the remote client is + * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client + * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`. + * @since v0.9.6 + */ + readonly localAddress?: string; + /** + * The numeric representation of the local port. For example, `80` or `21`. + * @since v0.9.6 + */ + readonly localPort?: number; + /** + * The string representation of the local IP family. `'IPv4'` or `'IPv6'`. + * @since v18.8.0, v16.18.0 + */ + readonly localFamily?: string; + /** + * This property represents the state of the connection as a string. + * + * * If the stream is connecting `socket.readyState` is `opening`. + * * If the stream is readable and writable, it is `open`. + * * If the stream is readable and not writable, it is `readOnly`. + * * If the stream is not readable and writable, it is `writeOnly`. + * @since v0.5.0 + */ + readonly readyState: SocketReadyState; + /** + * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remoteAddress?: string | undefined; + /** + * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.11.14 + */ + readonly remoteFamily?: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remotePort?: number | undefined; + /** + * The socket timeout in milliseconds as set by `socket.setTimeout()`. + * It is `undefined` if a timeout has not been set. + * @since v10.7.0 + */ + readonly timeout?: number | undefined; + /** + * Half-closes the socket. i.e., it sends a FIN packet. It is possible the + * server will still send some data. + * + * See `writable.end()` for further details. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(callback?: () => void): this; + end(buffer: Uint8Array | string, callback?: () => void): this; + end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. connectionAttempt + * 4. connectionAttemptFailed + * 5. connectionAttemptTimeout + * 6. data + * 7. drain + * 8. end + * 9. error + * 10. lookup + * 11. ready + * 12. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (hadError: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + addListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + addListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + addListener(event: "data", listener: (data: Buffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "timeout", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", hadError: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "connectionAttempt", ip: string, port: number, family: number): boolean; + emit(event: "connectionAttemptFailed", ip: string, port: number, family: number, error: Error): boolean; + emit(event: "connectionAttemptTimeout", ip: string, port: number, family: number): boolean; + emit(event: "data", data: Buffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "ready"): boolean; + emit(event: "timeout"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (hadError: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + on( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + on(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this; + on(event: "data", listener: (data: Buffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + on(event: "ready", listener: () => void): this; + on(event: "timeout", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (hadError: boolean) => void): this; + once(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + once( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + once(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: Buffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + once(event: "ready", listener: () => void): this; + once(event: "timeout", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (hadError: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + prependListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + prependListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependListener(event: "data", listener: (data: Buffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (hadError: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener( + event: "connectionAttempt", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number, error: Error) => void, + ): this; + prependOnceListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener(event: "data", listener: (data: Buffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + interface ListenOptions extends Abortable { + backlog?: number | undefined; + exclusive?: boolean | undefined; + host?: string | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + reusePort?: boolean | undefined; + path?: string | undefined; + port?: number | undefined; + readableAll?: boolean | undefined; + writableAll?: boolean | undefined; + } + interface ServerOpts { + /** + * Indicates whether half-opened TCP connections are allowed. + * @default false + */ + allowHalfOpen?: boolean | undefined; + /** + * Indicates whether the socket should be paused on incoming connections. + * @default false + */ + pauseOnConnect?: boolean | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default false + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + /** + * Optionally overrides all `net.Socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * @default See [stream.getDefaultHighWaterMark()](https://nodejs.org/docs/latest-v24.x/api/stream.html#streamgetdefaulthighwatermarkobjectmode). + * @since v18.17.0, v20.1.0 + */ + highWaterMark?: number | undefined; + /** + * `blockList` can be used for disabling inbound + * access to specific IP addresses, IP ranges, or IP subnets. This does not + * work if the server is behind a reverse proxy, NAT, etc. because the address + * checked against the block list is the address of the proxy, or the one + * specified by the NAT. + * @since v22.13.0 + */ + blockList?: BlockList | undefined; + } + interface DropArgument { + localAddress?: string; + localPort?: number; + localFamily?: string; + remoteAddress?: string; + remotePort?: number; + remoteFamily?: string; + } + /** + * This class is used to create a TCP or `IPC` server. + * @since v0.1.90 + */ + class Server extends EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); + /** + * Start a server listening for connections. A `net.Server` can be a TCP or + * an `IPC` server depending on what it listens to. + * + * Possible signatures: + * + * * `server.listen(handle[, backlog][, callback])` + * * `server.listen(options[, callback])` + * * `server.listen(path[, backlog][, callback])` for `IPC` servers + * * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + * + * This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` + * event. + * + * All `listen()` methods can take a `backlog` parameter to specify the maximum + * length of the queue of pending connections. The actual length will be determined + * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn` on Linux. The default value of this parameter is 511 (not 512). + * + * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for + * details). + * + * The `server.listen()` method can be called again if and only if there was an + * error during the first `server.listen()` call or `server.close()` has been + * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + * + * One of the most common errors raised when listening is `EADDRINUSE`. + * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry + * after a certain amount of time: + * + * ```js + * server.on('error', (e) => { + * if (e.code === 'EADDRINUSE') { + * console.error('Address in use, retrying...'); + * setTimeout(() => { + * server.close(); + * server.listen(PORT, HOST); + * }, 1000); + * } + * }); + * ``` + */ + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, hostname?: string, listeningListener?: () => void): this; + listen(port?: number, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, listeningListener?: () => void): this; + listen(path: string, backlog?: number, listeningListener?: () => void): this; + listen(path: string, listeningListener?: () => void): this; + listen(options: ListenOptions, listeningListener?: () => void): this; + listen(handle: any, backlog?: number, listeningListener?: () => void): this; + listen(handle: any, listeningListener?: () => void): this; + /** + * Stops the server from accepting new connections and keeps existing + * connections. This function is asynchronous, the server is finally closed + * when all connections are ended and the server emits a `'close'` event. + * The optional `callback` will be called once the `'close'` event occurs. Unlike + * that event, it will be called with an `Error` as its only argument if the server + * was not open when it was closed. + * @since v0.1.90 + * @param callback Called when the server is closed. + */ + close(callback?: (err?: Error) => void): this; + /** + * Returns the bound `address`, the address `family` name, and `port` of the server + * as reported by the operating system if listening on an IP socket + * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. + * + * For a server listening on a pipe or Unix domain socket, the name is returned + * as a string. + * + * ```js + * const server = net.createServer((socket) => { + * socket.end('goodbye\n'); + * }).on('error', (err) => { + * // Handle errors here. + * throw err; + * }); + * + * // Grab an arbitrary unused port. + * server.listen(() => { + * console.log('opened server on', server.address()); + * }); + * ``` + * + * `server.address()` returns `null` before the `'listening'` event has been + * emitted or after calling `server.close()`. + * @since v0.1.90 + */ + address(): AddressInfo | string | null; + /** + * Asynchronously get the number of concurrent connections on the server. Works + * when sockets were sent to forks. + * + * Callback should take two arguments `err` and `count`. + * @since v0.9.7 + */ + getConnections(cb: (error: Error | null, count: number) => void): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will _not_ let the program exit if it's the only server left (the default behavior). + * If the server is `ref`ed calling `ref()` again will have no effect. + * @since v0.9.1 + */ + ref(): this; + /** + * Calling `unref()` on a server will allow the program to exit if this is the only + * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + */ + unref(): this; + /** + * Set this property to reject connections when the server's connection count gets + * high. + * + * It is not recommended to use this option once a socket has been sent to a child + * with `child_process.fork()`. + * @since v0.2.0 + */ + maxConnections: number; + connections: number; + /** + * Indicates whether or not the server is listening for connections. + * @since v5.7.0 + */ + readonly listening: boolean; + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + * 5. drop + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "drop", listener: (data?: DropArgument) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "drop", data?: DropArgument): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "drop", listener: (data?: DropArgument) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "drop", listener: (data?: DropArgument) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "drop", listener: (data?: DropArgument) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "drop", listener: (data?: DropArgument) => void): this; + /** + * Calls {@link Server.close()} and returns a promise that fulfills when the server has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } + type IPVersion = "ipv4" | "ipv6"; + /** + * The `BlockList` object can be used with some network APIs to specify rules for + * disabling inbound or outbound access to specific IP addresses, IP ranges, or + * IP subnets. + * @since v15.0.0, v14.18.0 + */ + class BlockList { + /** + * Adds a rule to block the given IP address. + * @since v15.0.0, v14.18.0 + * @param address An IPv4 or IPv6 address. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addAddress(address: string, type?: IPVersion): void; + addAddress(address: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). + * @since v15.0.0, v14.18.0 + * @param start The starting IPv4 or IPv6 address in the range. + * @param end The ending IPv4 or IPv6 address in the range. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addRange(start: string, end: string, type?: IPVersion): void; + addRange(start: SocketAddress, end: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses specified as a subnet mask. + * @since v15.0.0, v14.18.0 + * @param net The network IPv4 or IPv6 address. + * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addSubnet(net: SocketAddress, prefix: number): void; + addSubnet(net: string, prefix: number, type?: IPVersion): void; + /** + * Returns `true` if the given IP address matches any of the rules added to the`BlockList`. + * + * ```js + * const blockList = new net.BlockList(); + * blockList.addAddress('123.123.123.123'); + * blockList.addRange('10.0.0.1', '10.0.0.10'); + * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); + * + * console.log(blockList.check('123.123.123.123')); // Prints: true + * console.log(blockList.check('10.0.0.3')); // Prints: true + * console.log(blockList.check('222.111.111.222')); // Prints: false + * + * // IPv6 notation for IPv4 addresses works: + * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true + * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true + * ``` + * @since v15.0.0, v14.18.0 + * @param address The IP address to check + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + check(address: SocketAddress): boolean; + check(address: string, type?: IPVersion): boolean; + /** + * The list of rules added to the blocklist. + * @since v15.0.0, v14.18.0 + */ + rules: readonly string[]; + /** + * Returns `true` if the `value` is a `net.BlockList`. + * @since v22.13.0 + * @param value Any JS value + */ + static isBlockList(value: unknown): value is BlockList; + } + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + /** + * Creates a new TCP or `IPC` server. + * + * If `allowHalfOpen` is set to `true`, when the other end of the socket + * signals the end of transmission, the server will only send back the end of + * transmission when `socket.end()` is explicitly called. For example, in the + * context of TCP, when a FIN packed is received, a FIN packed is sent + * back only when `socket.end()` is explicitly called. Until then the + * connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information. + * + * If `pauseOnConnect` is set to `true`, then the socket associated with each + * incoming connection will be paused, and no data will be read from its handle. + * This allows connections to be passed between processes without any data being + * read by the original process. To begin reading data from a paused socket, call `socket.resume()`. + * + * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. + * + * Here is an example of a TCP echo server which listens for connections + * on port 8124: + * + * ```js + * import net from 'node:net'; + * const server = net.createServer((c) => { + * // 'connection' listener. + * console.log('client connected'); + * c.on('end', () => { + * console.log('client disconnected'); + * }); + * c.write('hello\r\n'); + * c.pipe(c); + * }); + * server.on('error', (err) => { + * throw err; + * }); + * server.listen(8124, () => { + * console.log('server bound'); + * }); + * ``` + * + * Test this by using `telnet`: + * + * ```bash + * telnet localhost 8124 + * ``` + * + * To listen on the socket `/tmp/echo.sock`: + * + * ```js + * server.listen('/tmp/echo.sock', () => { + * console.log('server bound'); + * }); + * ``` + * + * Use `nc` to connect to a Unix domain socket server: + * + * ```bash + * nc -U /tmp/echo.sock + * ``` + * @since v0.5.0 + * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. + */ + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; + /** + * Aliases to {@link createConnection}. + * + * Possible signatures: + * + * * {@link connect} + * * {@link connect} for `IPC` connections. + * * {@link connect} for TCP connections. + */ + function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; + function connect(port: number, host?: string, connectionListener?: () => void): Socket; + function connect(path: string, connectionListener?: () => void): Socket; + /** + * A factory function, which creates a new {@link Socket}, + * immediately initiates connection with `socket.connect()`, + * then returns the `net.Socket` that starts the connection. + * + * When the connection is established, a `'connect'` event will be emitted + * on the returned socket. The last parameter `connectListener`, if supplied, + * will be added as a listener for the `'connect'` event **once**. + * + * Possible signatures: + * + * * {@link createConnection} + * * {@link createConnection} for `IPC` connections. + * * {@link createConnection} for TCP connections. + * + * The {@link connect} function is an alias to this function. + */ + function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; + function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; + function createConnection(path: string, connectionListener?: () => void): Socket; + /** + * Gets the current default value of the `autoSelectFamily` option of `socket.connect(options)`. + * The initial default value is `true`, unless the command line option`--no-network-family-autoselection` is provided. + * @since v19.4.0 + */ + function getDefaultAutoSelectFamily(): boolean; + /** + * Sets the default value of the `autoSelectFamily` option of `socket.connect(options)`. + * @param value The new default value. + * The initial default value is `true`, unless the command line option + * `--no-network-family-autoselection` is provided. + * @since v19.4.0 + */ + function setDefaultAutoSelectFamily(value: boolean): void; + /** + * Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * The initial default value is `250` or the value specified via the command line option `--network-family-autoselection-attempt-timeout`. + * @returns The current default value of the `autoSelectFamilyAttemptTimeout` option. + * @since v19.8.0, v18.8.0 + */ + function getDefaultAutoSelectFamilyAttemptTimeout(): number; + /** + * Sets the default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * @param value The new default value, which must be a positive number. If the number is less than `10`, the value `10` is used instead. The initial default value is `250` or the value specified via the command line + * option `--network-family-autoselection-attempt-timeout`. + * @since v19.8.0, v18.8.0 + */ + function setDefaultAutoSelectFamilyAttemptTimeout(value: number): void; + /** + * Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4 + * address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`. + * + * ```js + * net.isIP('::1'); // returns 6 + * net.isIP('127.0.0.1'); // returns 4 + * net.isIP('127.000.000.001'); // returns 0 + * net.isIP('127.0.0.1/24'); // returns 0 + * net.isIP('fhqwhgads'); // returns 0 + * ``` + * @since v0.3.0 + */ + function isIP(input: string): number; + /** + * Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no + * leading zeroes. Otherwise, returns `false`. + * + * ```js + * net.isIPv4('127.0.0.1'); // returns true + * net.isIPv4('127.000.000.001'); // returns false + * net.isIPv4('127.0.0.1/24'); // returns false + * net.isIPv4('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv4(input: string): boolean; + /** + * Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`. + * + * ```js + * net.isIPv6('::1'); // returns true + * net.isIPv6('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv6(input: string): boolean; + interface SocketAddressInitOptions { + /** + * The network address as either an IPv4 or IPv6 string. + * @default 127.0.0.1 + */ + address?: string | undefined; + /** + * @default `'ipv4'` + */ + family?: IPVersion | undefined; + /** + * An IPv6 flow-label used only if `family` is `'ipv6'`. + * @default 0 + */ + flowlabel?: number | undefined; + /** + * An IP port. + * @default 0 + */ + port?: number | undefined; + } + /** + * @since v15.14.0, v14.18.0 + */ + class SocketAddress { + constructor(options: SocketAddressInitOptions); + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly address: string; + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly family: IPVersion; + /** + * @since v15.14.0, v14.18.0 + */ + readonly port: number; + /** + * @since v15.14.0, v14.18.0 + */ + readonly flowlabel: number; + /** + * @since v22.13.0 + * @param input An input string containing an IP address and optional port, + * e.g. `123.1.2.3:1234` or `[1::1]:1234`. + * @returns Returns a `SocketAddress` if parsing was successful. + * Otherwise returns `undefined`. + */ + static parse(input: string): SocketAddress | undefined; + } +} +declare module "node:net" { + export * from "net"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/os.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/os.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..77a633609068d6cb92534397d44bd1a81adeb7ff --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/os.d.ts @@ -0,0 +1,496 @@ +/** + * The `node:os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * import os from 'node:os'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/os.js) + */ +declare module "os" { + interface CpuInfo { + model: string; + speed: number; + times: { + /** The number of milliseconds the CPU has spent in user mode. */ + user: number; + /** The number of milliseconds the CPU has spent in nice mode. */ + nice: number; + /** The number of milliseconds the CPU has spent in sys mode. */ + sys: number; + /** The number of milliseconds the CPU has spent in idle mode. */ + idle: number; + /** The number of milliseconds the CPU has spent in irq mode. */ + irq: number; + }; + } + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: "IPv4"; + scopeid?: undefined; + } + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: "IPv6"; + scopeid: number; + } + interface UserInfo { + username: T; + uid: number; + gid: number; + shell: T | null; + homedir: T; + } + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + /** + * Returns the host name of the operating system as a string. + * @since v0.3.3 + */ + function hostname(): string; + /** + * Returns an array containing the 1, 5, and 15 minute load averages. + * + * The load average is a measure of system activity calculated by the operating + * system and expressed as a fractional number. + * + * The load average is a Unix-specific concept. On Windows, the return value is + * always `[0, 0, 0]`. + * @since v0.3.3 + */ + function loadavg(): number[]; + /** + * Returns the system uptime in number of seconds. + * @since v0.3.3 + */ + function uptime(): number; + /** + * Returns the amount of free system memory in bytes as an integer. + * @since v0.3.3 + */ + function freemem(): number; + /** + * Returns the total amount of system memory in bytes as an integer. + * @since v0.3.3 + */ + function totalmem(): number; + /** + * Returns an array of objects containing information about each logical CPU core. + * The array will be empty if no CPU information is available, such as if the `/proc` file system is unavailable. + * + * The properties included on each object include: + * + * ```js + * [ + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 252020, + * nice: 0, + * sys: 30340, + * idle: 1070356870, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 306960, + * nice: 0, + * sys: 26980, + * idle: 1071569080, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 248450, + * nice: 0, + * sys: 21750, + * idle: 1070919370, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 256880, + * nice: 0, + * sys: 19430, + * idle: 1070905480, + * irq: 20, + * }, + * }, + * ] + * ``` + * + * `nice` values are POSIX-only. On Windows, the `nice` values of all processors + * are always 0. + * + * `os.cpus().length` should not be used to calculate the amount of parallelism + * available to an application. Use {@link availableParallelism} for this purpose. + * @since v0.3.3 + */ + function cpus(): CpuInfo[]; + /** + * Returns an estimate of the default amount of parallelism a program should use. + * Always returns a value greater than zero. + * + * This function is a small wrapper about libuv's [`uv_available_parallelism()`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism). + * @since v19.4.0, v18.14.0 + */ + function availableParallelism(): number; + /** + * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it + * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. + * + * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information + * about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems. + * @since v0.3.3 + */ + function type(): string; + /** + * Returns the operating system as a string. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See + * [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v0.3.3 + */ + function release(): string; + /** + * Returns an object containing network interfaces that have been assigned a + * network address. + * + * Each key on the returned object identifies a network interface. The associated + * value is an array of objects that each describe an assigned network address. + * + * The properties available on the assigned network address object include: + * + * ```js + * { + * lo: [ + * { + * address: '127.0.0.1', + * netmask: '255.0.0.0', + * family: 'IPv4', + * mac: '00:00:00:00:00:00', + * internal: true, + * cidr: '127.0.0.1/8' + * }, + * { + * address: '::1', + * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', + * family: 'IPv6', + * mac: '00:00:00:00:00:00', + * scopeid: 0, + * internal: true, + * cidr: '::1/128' + * } + * ], + * eth0: [ + * { + * address: '192.168.1.108', + * netmask: '255.255.255.0', + * family: 'IPv4', + * mac: '01:02:03:0a:0b:0c', + * internal: false, + * cidr: '192.168.1.108/24' + * }, + * { + * address: 'fe80::a00:27ff:fe4e:66a1', + * netmask: 'ffff:ffff:ffff:ffff::', + * family: 'IPv6', + * mac: '01:02:03:0a:0b:0c', + * scopeid: 1, + * internal: false, + * cidr: 'fe80::a00:27ff:fe4e:66a1/64' + * } + * ] + * } + * ``` + * @since v0.6.0 + */ + function networkInterfaces(): NodeJS.Dict; + /** + * Returns the string path of the current user's home directory. + * + * On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it + * uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory. + * + * On Windows, it uses the `USERPROFILE` environment variable if defined. + * Otherwise it uses the path to the profile directory of the current user. + * @since v2.3.0 + */ + function homedir(): string; + /** + * Returns information about the currently effective user. On POSIX platforms, + * this is typically a subset of the password file. The returned object includes + * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and `gid` fields are `-1`, and `shell` is `null`. + * + * The value of `homedir` returned by `os.userInfo()` is provided by the operating + * system. This differs from the result of `os.homedir()`, which queries + * environment variables for the home directory before falling back to the + * operating system response. + * + * Throws a [`SystemError`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-systemerror) if a user has no `username` or `homedir`. + * @since v6.0.0 + */ + function userInfo(options: { encoding: "buffer" }): UserInfo; + function userInfo(options?: { encoding: BufferEncoding }): UserInfo; + type SignalConstants = { + [key in NodeJS.Signals]: number; + }; + namespace constants { + const UV_UDP_REUSEADDR: number; + namespace signals {} + const signals: SignalConstants; + namespace errno { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EDQUOT: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const EMULTIHOP: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ESTALE: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + } + namespace dlopen { + const RTLD_LAZY: number; + const RTLD_NOW: number; + const RTLD_GLOBAL: number; + const RTLD_LOCAL: number; + const RTLD_DEEPBIND: number; + } + namespace priority { + const PRIORITY_LOW: number; + const PRIORITY_BELOW_NORMAL: number; + const PRIORITY_NORMAL: number; + const PRIORITY_ABOVE_NORMAL: number; + const PRIORITY_HIGH: number; + const PRIORITY_HIGHEST: number; + } + } + const devNull: string; + /** + * The operating system-specific end-of-line marker. + * * `\n` on POSIX + * * `\r\n` on Windows + */ + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, + * `'mips'`, `'mipsel'`, `'ppc64'`, `'riscv64'`, `'s390x'`, and `'x64'`. + * + * The return value is equivalent to [process.arch](https://nodejs.org/docs/latest-v24.x/api/process.html#processarch). + * @since v0.5.0 + */ + function arch(): NodeJS.Architecture; + /** + * Returns a string identifying the kernel version. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v13.11.0, v12.17.0 + */ + function version(): string; + /** + * Returns a string identifying the operating system platform for which + * the Node.js binary was compiled. The value is set at compile time. + * Possible values are `'aix'`, `'darwin'`, `'freebsd'`, `'linux'`, `'openbsd'`, `'sunos'`, and `'win32'`. + * + * The return value is equivalent to `process.platform`. + * + * The value `'android'` may also be returned if Node.js is built on the Android + * operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.5.0 + */ + function platform(): NodeJS.Platform; + /** + * Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`, + * `mips`, `mips64`, `ppc64`, `ppc64le`, `s390x`, `i386`, `i686`, `x86_64`. + * + * On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v18.9.0, v16.18.0 + */ + function machine(): string; + /** + * Returns the operating system's default directory for temporary files as a + * string. + * @since v0.9.9 + */ + function tmpdir(): string; + /** + * Returns a string identifying the endianness of the CPU for which the Node.js + * binary was compiled. + * + * Possible values are `'BE'` for big endian and `'LE'` for little endian. + * @since v0.9.4 + */ + function endianness(): "BE" | "LE"; + /** + * Returns the scheduling priority for the process specified by `pid`. If `pid` is + * not provided or is `0`, the priority of the current process is returned. + * @since v10.10.0 + * @param [pid=0] The process ID to retrieve scheduling priority for. + */ + function getPriority(pid?: number): number; + /** + * Attempts to set the scheduling priority for the process specified by `pid`. If `pid` is not provided or is `0`, the process ID of the current process is used. + * + * The `priority` input must be an integer between `-20` (high priority) and `19` (low priority). Due to differences between Unix priority levels and Windows + * priority classes, `priority` is mapped to one of six priority constants in `os.constants.priority`. When retrieving a process priority level, this range + * mapping may cause the return value to be slightly different on Windows. To avoid + * confusion, set `priority` to one of the priority constants. + * + * On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user + * privileges. Otherwise the set priority will be silently reduced to `PRIORITY_HIGH`. + * @since v10.10.0 + * @param [pid=0] The process ID to set scheduling priority for. + * @param priority The scheduling priority to assign to the process. + */ + function setPriority(priority: number): void; + function setPriority(pid: number, priority: number): void; +} +declare module "node:os" { + export * from "os"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/package.json b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7d4a99d189c4626e4785011aff2af09ff98a01f6 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/package.json @@ -0,0 +1,155 @@ +{ + "name": "@types/node", + "version": "24.3.0", + "description": "TypeScript definitions for node", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "license": "MIT", + "contributors": [ + { + "name": "Microsoft TypeScript", + "githubUsername": "Microsoft", + "url": "https://github.com/Microsoft" + }, + { + "name": "Alberto Schiabel", + "githubUsername": "jkomyno", + "url": "https://github.com/jkomyno" + }, + { + "name": "Andrew Makarov", + "githubUsername": "r3nya", + "url": "https://github.com/r3nya" + }, + { + "name": "Benjamin Toueg", + "githubUsername": "btoueg", + "url": "https://github.com/btoueg" + }, + { + "name": "David Junger", + "githubUsername": "touffy", + "url": "https://github.com/touffy" + }, + { + "name": "Mohsen Azimi", + "githubUsername": "mohsen1", + "url": "https://github.com/mohsen1" + }, + { + "name": "Nikita Galkin", + "githubUsername": "galkin", + "url": "https://github.com/galkin" + }, + { + "name": "Sebastian Silbermann", + "githubUsername": "eps1lon", + "url": "https://github.com/eps1lon" + }, + { + "name": "Wilco Bakker", + "githubUsername": "WilcoBakker", + "url": "https://github.com/WilcoBakker" + }, + { + "name": "Marcin Kopacz", + "githubUsername": "chyzwar", + "url": "https://github.com/chyzwar" + }, + { + "name": "Trivikram Kamat", + "githubUsername": "trivikr", + "url": "https://github.com/trivikr" + }, + { + "name": "Junxiao Shi", + "githubUsername": "yoursunny", + "url": "https://github.com/yoursunny" + }, + { + "name": "Ilia Baryshnikov", + "githubUsername": "qwelias", + "url": "https://github.com/qwelias" + }, + { + "name": "ExE Boss", + "githubUsername": "ExE-Boss", + "url": "https://github.com/ExE-Boss" + }, + { + "name": "Piotr Błażejewicz", + "githubUsername": "peterblazejewicz", + "url": "https://github.com/peterblazejewicz" + }, + { + "name": "Anna Henningsen", + "githubUsername": "addaleax", + "url": "https://github.com/addaleax" + }, + { + "name": "Victor Perin", + "githubUsername": "victorperin", + "url": "https://github.com/victorperin" + }, + { + "name": "NodeJS Contributors", + "githubUsername": "NodeJS", + "url": "https://github.com/NodeJS" + }, + { + "name": "Linus Unnebäck", + "githubUsername": "LinusU", + "url": "https://github.com/LinusU" + }, + { + "name": "wafuwafu13", + "githubUsername": "wafuwafu13", + "url": "https://github.com/wafuwafu13" + }, + { + "name": "Matteo Collina", + "githubUsername": "mcollina", + "url": "https://github.com/mcollina" + }, + { + "name": "Dmitry Semigradsky", + "githubUsername": "Semigradsky", + "url": "https://github.com/Semigradsky" + }, + { + "name": "René", + "githubUsername": "Renegade334", + "url": "https://github.com/Renegade334" + }, + { + "name": "Yagiz Nizipli", + "githubUsername": "anonrig", + "url": "https://github.com/anonrig" + } + ], + "main": "", + "types": "index.d.ts", + "typesVersions": { + "<=5.6": { + "*": [ + "ts5.6/*" + ] + }, + "<=5.7": { + "*": [ + "ts5.7/*" + ] + } + }, + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "dependencies": { + "undici-types": "~7.10.0" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "1db0510763ba3afd8e54c0591e60a100a7b90926f5d7da28ae32d8f845d725da", + "typeScriptVersion": "5.2" +} \ No newline at end of file diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/path.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/path.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d363397ffe8228c766f465384832acb535679f20 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/path.d.ts @@ -0,0 +1,200 @@ +declare module "path/posix" { + import path = require("path"); + export = path; +} +declare module "path/win32" { + import path = require("path"); + export = path; +} +/** + * The `node:path` module provides utilities for working with file and directory + * paths. It can be accessed using: + * + * ```js + * import path from 'node:path'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/path.js) + */ +declare module "path" { + namespace path { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string | undefined; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string | undefined; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string | undefined; + /** + * The file extension (if any) such as '.html' + */ + ext?: string | undefined; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string | undefined; + } + interface PlatformPath { + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param path string path to normalize. + * @throws {TypeError} if `path` is not a string. + */ + normalize(path: string): string; + /** + * Join all arguments together and normalize the resulting path. + * + * @param paths paths to join. + * @throws {TypeError} if any of the path segments is not a string. + */ + join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param paths A sequence of paths or path segments. + * @throws {TypeError} if any of the arguments is not a string. + */ + resolve(...paths: string[]): string; + /** + * The `path.matchesGlob()` method determines if `path` matches the `pattern`. + * @param path The path to glob-match against. + * @param pattern The glob to check the path against. + * @returns Whether or not the `path` matched the `pattern`. + * @throws {TypeError} if `path` or `pattern` are not strings. + * @since v22.5.0 + */ + matchesGlob(path: string, pattern: string): boolean; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * If the given {path} is a zero-length string, `false` will be returned. + * + * @param path path to test. + * @throws {TypeError} if `path` is not a string. + */ + isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to} based on the current working directory. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @throws {TypeError} if either `from` or `to` is not a string. + */ + relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + dirname(path: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param path the path to evaluate. + * @param suffix optionally, an extension to remove from the result. + * @throws {TypeError} if `path` is not a string or if `ext` is given and is not a string. + */ + basename(path: string, suffix?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + extname(path: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + readonly sep: "\\" | "/"; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + readonly delimiter: ";" | ":"; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param path path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + parse(path: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathObject path to evaluate. + */ + format(pathObject: FormatInputPathObject): string; + /** + * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. + * If path is not a string, path will be returned without modifications. + * This method is meaningful only on Windows system. + * On POSIX systems, the method is non-operational and always returns path without modifications. + */ + toNamespacedPath(path: string): string; + /** + * Posix specific pathing. + * Same as parent object on posix. + */ + readonly posix: PlatformPath; + /** + * Windows specific pathing. + * Same as parent object on windows + */ + readonly win32: PlatformPath; + } + } + const path: path.PlatformPath; + export = path; +} +declare module "node:path" { + import path = require("path"); + export = path; +} +declare module "node:path/posix" { + import path = require("path/posix"); + export = path; +} +declare module "node:path/win32" { + import path = require("path/win32"); + export = path; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/perf_hooks.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/perf_hooks.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..51d78d0b1230d4d7936eda198c46f1a36d21c833 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,984 @@ +/** + * This module provides an implementation of a subset of the W3C [Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for + * Node.js-specific performance measurements. + * + * Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): + * + * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) + * * [Performance Timeline](https://w3c.github.io/performance-timeline/) + * * [User Timing](https://www.w3.org/TR/user-timing/) + * * [Resource Timing](https://www.w3.org/TR/resource-timing-2/) + * + * ```js + * import { PerformanceObserver, performance } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((items) => { + * console.log(items.getEntries()[0].duration); + * performance.clearMarks(); + * }); + * obs.observe({ type: 'measure' }); + * performance.measure('Start to Now'); + * + * performance.mark('A'); + * doSomeLongRunningProcess(() => { + * performance.measure('A to Now', 'A'); + * + * performance.mark('B'); + * performance.measure('A to B', 'A', 'B'); + * }); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/perf_hooks.js) + */ +declare module "perf_hooks" { + import { AsyncResource } from "node:async_hooks"; + type EntryType = + | "dns" // Node.js only + | "function" // Node.js only + | "gc" // Node.js only + | "http2" // Node.js only + | "http" // Node.js only + | "mark" // available on the Web + | "measure" // available on the Web + | "net" // Node.js only + | "node" // Node.js only + | "resource"; // available on the Web + interface NodeGCPerformanceDetail { + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.kind` property identifies + * the type of garbage collection operation that occurred. + * See perf_hooks.constants for valid values. + */ + readonly kind?: number | undefined; + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` + * property contains additional information about garbage collection operation. + * See perf_hooks.constants for valid values. + */ + readonly flags?: number | undefined; + } + /** + * The constructor of this class is not exposed to users directly. + * @since v8.5.0 + */ + class PerformanceEntry { + protected constructor(); + /** + * The total number of milliseconds elapsed for this entry. This value will not + * be meaningful for all Performance Entry types. + * @since v8.5.0 + */ + readonly duration: number; + /** + * The name of the performance entry. + * @since v8.5.0 + */ + readonly name: string; + /** + * The high resolution millisecond timestamp marking the starting time of the + * Performance Entry. + * @since v8.5.0 + */ + readonly startTime: number; + /** + * The type of the performance entry. It may be one of: + * + * * `'node'` (Node.js only) + * * `'mark'` (available on the Web) + * * `'measure'` (available on the Web) + * * `'gc'` (Node.js only) + * * `'function'` (Node.js only) + * * `'http2'` (Node.js only) + * * `'http'` (Node.js only) + * @since v8.5.0 + */ + readonly entryType: EntryType; + /** + * Additional detail specific to the `entryType`. + * @since v16.0.0 + */ + readonly detail?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type. + toJSON(): any; + } + /** + * Exposes marks created via the `Performance.mark()` method. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMark extends PerformanceEntry { + readonly duration: 0; + readonly entryType: "mark"; + } + /** + * Exposes measures created via the `Performance.measure()` method. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMeasure extends PerformanceEntry { + readonly entryType: "measure"; + } + interface UVMetrics { + /** + * Number of event loop iterations. + */ + readonly loopCount: number; + /** + * Number of events that have been processed by the event handler. + */ + readonly events: number; + /** + * Number of events that were waiting to be processed when the event provider was called. + */ + readonly eventsWaiting: number; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Provides timing details for Node.js itself. The constructor of this class + * is not exposed to users. + * @since v8.5.0 + */ + class PerformanceNodeTiming extends PerformanceEntry { + readonly entryType: "node"; + /** + * The high resolution millisecond timestamp at which the Node.js process + * completed bootstrapping. If bootstrapping has not yet finished, the property + * has the value of -1. + * @since v8.5.0 + */ + readonly bootstrapComplete: number; + /** + * The high resolution millisecond timestamp at which the Node.js environment was + * initialized. + * @since v8.5.0 + */ + readonly environment: number; + /** + * The high resolution millisecond timestamp of the amount of time the event loop + * has been idle within the event loop's event provider (e.g. `epoll_wait`). This + * does not take CPU usage into consideration. If the event loop has not yet + * started (e.g., in the first tick of the main script), the property has the + * value of 0. + * @since v14.10.0, v12.19.0 + */ + readonly idleTime: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * exited. If the event loop has not yet exited, the property has the value of -1\. + * It can only have a value of not -1 in a handler of the `'exit'` event. + * @since v8.5.0 + */ + readonly loopExit: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * started. If the event loop has not yet started (e.g., in the first tick of the + * main script), the property has the value of -1. + * @since v8.5.0 + */ + readonly loopStart: number; + /** + * The high resolution millisecond timestamp at which the Node.js process was initialized. + * @since v8.5.0 + */ + readonly nodeStart: number; + /** + * This is a wrapper to the `uv_metrics_info` function. + * It returns the current set of event loop metrics. + * + * It is recommended to use this property inside a function whose execution was + * scheduled using `setImmediate` to avoid collecting metrics before finishing all + * operations scheduled during the current loop iteration. + * @since v22.8.0, v20.18.0 + */ + readonly uvMetricsInfo: UVMetrics; + /** + * The high resolution millisecond timestamp at which the V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + /** + * @param utilization1 The result of a previous call to `eventLoopUtilization()`. + * @param utilization2 The result of a previous call to `eventLoopUtilization()` prior to `utilization1`. + */ + type EventLoopUtilityFunction = ( + utilization1?: EventLoopUtilization, + utilization2?: EventLoopUtilization, + ) => EventLoopUtilization; + interface MarkOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * An optional timestamp to be used as the mark time. + * @default `performance.now()` + */ + startTime?: number | undefined; + } + interface MeasureOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * Duration between start and end times. + */ + duration?: number | undefined; + /** + * Timestamp to be used as the end time, or a string identifying a previously recorded mark. + */ + end?: number | string | undefined; + /** + * Timestamp to be used as the start time, or a string identifying a previously recorded mark. + */ + start?: number | string | undefined; + } + interface TimerifyOptions { + /** + * A histogram object created using `perf_hooks.createHistogram()` that will record runtime + * durations in nanoseconds. + */ + histogram?: RecordableHistogram | undefined; + } + interface Performance { + /** + * If `name` is not provided, removes all `PerformanceMark` objects from the Performance Timeline. + * If `name` is provided, removes only the named mark. + * @since v8.5.0 + */ + clearMarks(name?: string): void; + /** + * If `name` is not provided, removes all `PerformanceMeasure` objects from the Performance Timeline. + * If `name` is provided, removes only the named measure. + * @since v16.7.0 + */ + clearMeasures(name?: string): void; + /** + * If `name` is not provided, removes all `PerformanceResourceTiming` objects from the Resource Timeline. + * If `name` is provided, removes only the named resource. + * @since v18.2.0, v16.17.0 + */ + clearResourceTimings(name?: string): void; + /** + * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. + * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). + * No other CPU idle time is taken into consideration. + */ + eventLoopUtilization: EventLoopUtilityFunction; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`. + * If you are only interested in performance entries of certain types or that have certain names, see + * `performance.getEntriesByType()` and `performance.getEntriesByName()`. + * @since v16.7.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.name` is equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to `type`. + * @param name + * @param type + * @since v16.7.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.entryType` is equal to `type`. + * @param type + * @since v16.7.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + /** + * Creates a new `PerformanceMark` entry in the Performance Timeline. + * A `PerformanceMark` is a subclass of `PerformanceEntry` whose `performanceEntry.entryType` is always `'mark'`, + * and whose `performanceEntry.duration` is always `0`. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * + * The created `PerformanceMark` entry is put in the global Performance Timeline and can be queried with + * `performance.getEntries`, `performance.getEntriesByName`, and `performance.getEntriesByType`. When the observation is + * performed, the entries should be cleared from the global Performance Timeline manually with `performance.clearMarks`. + * @param name + */ + mark(name: string, options?: MarkOptions): PerformanceMark; + /** + * Creates a new `PerformanceResourceTiming` entry in the Resource Timeline. + * A `PerformanceResourceTiming` is a subclass of `PerformanceEntry` whose `performanceEntry.entryType` is always `'resource'`. + * Performance resources are used to mark moments in the Resource Timeline. + * @param timingInfo [Fetch Timing Info](https://fetch.spec.whatwg.org/#fetch-timing-info) + * @param requestedUrl The resource url + * @param initiatorType The initiator name, e.g: 'fetch' + * @param global + * @param cacheMode The cache mode must be an empty string ('') or 'local' + * @param bodyInfo [Fetch Response Body Info](https://fetch.spec.whatwg.org/#response-body-info) + * @param responseStatus The response's status code + * @param deliveryType The delivery type. Default: ''. + * @since v18.2.0, v16.17.0 + */ + markResourceTiming( + timingInfo: object, + requestedUrl: string, + initiatorType: string, + global: object, + cacheMode: "" | "local", + bodyInfo: object, + responseStatus: number, + deliveryType?: string, + ): PerformanceResourceTiming; + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + * @return The PerformanceMeasure entry that was created + */ + measure(name: string, startMark?: string, endMark?: string): PerformanceMeasure; + measure(name: string, options: MeasureOptions): PerformanceMeasure; + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * An instance of the `PerformanceNodeTiming` class that provides performance metrics for specific Node.js operational milestones. + * @since v8.5.0 + */ + readonly nodeTiming: PerformanceNodeTiming; + /** + * Returns the current high resolution millisecond timestamp, where 0 represents the start of the current `node` process. + * @since v8.5.0 + */ + now(): number; + /** + * Sets the global performance resource timing buffer size to the specified number of "resource" type performance entry objects. + * + * By default the max buffer size is set to 250. + * @since v18.8.0 + */ + setResourceTimingBufferSize(maxSize: number): void; + /** + * The [`timeOrigin`](https://w3c.github.io/hr-time/#dom-performance-timeorigin) specifies the high resolution millisecond timestamp + * at which the current `node` process began, measured in Unix time. + * @since v8.5.0 + */ + readonly timeOrigin: number; + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Wraps a function within a new function that measures the running time of the wrapped function. + * A `PerformanceObserver` must be subscribed to the `'function'` event type in order for the timing details to be accessed. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * function someFunction() { + * console.log('hello world'); + * } + * + * const wrapped = performance.timerify(someFunction); + * + * const obs = new PerformanceObserver((list) => { + * console.log(list.getEntries()[0].duration); + * + * performance.clearMarks(); + * performance.clearMeasures(); + * obs.disconnect(); + * }); + * obs.observe({ entryTypes: ['function'] }); + * + * // A performance timeline entry will be created + * wrapped(); + * ``` + * + * If the wrapped function returns a promise, a finally handler will be attached to the promise and the duration will be reported + * once the finally handler is invoked. + * @param fn + */ + timerify any>(fn: T, options?: TimerifyOptions): T; + /** + * An object which is JSON representation of the performance object. It is similar to + * [`window.performance.toJSON`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/toJSON) in browsers. + * @since v16.1.0 + */ + toJSON(): any; + } + class PerformanceObserverEntryList { + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime`. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntries()); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 81.465639, + * * duration: 0, + * * detail: null + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 81.860064, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.name` is + * equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByName('meow')); + * + * * [ + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 98.545991, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('nope')); // [] + * + * console.log(perfObserverList.getEntriesByName('test', 'mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 63.518931, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ entryTypes: ['mark', 'measure'] }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType` is equal to `type`. + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByType('mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 55.897834, + * * duration: 0, + * * detail: null + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 56.350146, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + } + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + /** + * @since v8.5.0 + */ + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + /** + * Disconnects the `PerformanceObserver` instance from all notifications. + * @since v8.5.0 + */ + disconnect(): void; + /** + * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes` or `options.type`: + * + * ```js + * import { + * performance, + * PerformanceObserver, + * } from 'node:perf_hooks'; + * + * const obs = new PerformanceObserver((list, observer) => { + * // Called once asynchronously. `list` contains three items. + * }); + * obs.observe({ type: 'mark' }); + * + * for (let n = 0; n < 3; n++) + * performance.mark(`test${n}`); + * ``` + * @since v8.5.0 + */ + observe( + options: + | { + entryTypes: readonly EntryType[]; + buffered?: boolean | undefined; + } + | { + type: EntryType; + buffered?: boolean | undefined; + }, + ): void; + /** + * @since v16.0.0 + * @returns Current list of entries stored in the performance observer, emptying it out. + */ + takeRecords(): PerformanceEntry[]; + } + /** + * Provides detailed network timing data regarding the loading of an application's resources. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceResourceTiming extends PerformanceEntry { + readonly entryType: "resource"; + protected constructor(); + /** + * The high resolution millisecond timestamp at immediately before dispatching the `fetch` + * request. If the resource is not intercepted by a worker the property will always return 0. + * @since v18.2.0, v16.17.0 + */ + readonly workerStart: number; + /** + * The high resolution millisecond timestamp that represents the start time of the fetch which + * initiates the redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectStart: number; + /** + * The high resolution millisecond timestamp that will be created immediately after receiving + * the last byte of the response of the last redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectEnd: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts to fetch the resource. + * @since v18.2.0, v16.17.0 + */ + readonly fetchStart: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts the domain name lookup + * for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after the Node.js finished + * the domain name lookup for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts to + * establish the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js finishes + * establishing the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts the + * handshake process to secure the current connection. + * @since v18.2.0, v16.17.0 + */ + readonly secureConnectionStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js receives the + * first byte of the response from the server. + * @since v18.2.0, v16.17.0 + */ + readonly requestStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js receives the + * last byte of the resource or immediately before the transport connection is closed, whichever comes first. + * @since v18.2.0, v16.17.0 + */ + readonly responseEnd: number; + /** + * A number representing the size (in octets) of the fetched resource. The size includes the response header + * fields plus the response payload body. + * @since v18.2.0, v16.17.0 + */ + readonly transferSize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the payload body, before + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly encodedBodySize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the message body, after + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly decodedBodySize: number; + /** + * Returns a `object` that is the JSON representation of the `PerformanceResourceTiming` object + * @since v18.2.0, v16.17.0 + */ + toJSON(): any; + } + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + const NODE_PERFORMANCE_GC_FLAGS_NO: number; + const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; + const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; + const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; + const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; + } + const performance: Performance; + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number | undefined; + } + interface Histogram { + /** + * The number of samples recorded by the histogram. + * @since v17.4.0, v16.14.0 + */ + readonly count: number; + /** + * The number of samples recorded by the histogram. + * v17.4.0, v16.14.0 + */ + readonly countBigInt: bigint; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event + * loop delay threshold. + * @since v11.10.0 + */ + readonly exceeds: number; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold. + * @since v17.4.0, v16.14.0 + */ + readonly exceedsBigInt: bigint; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The maximum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly maxBigInt: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The minimum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly minBigInt: bigint; + /** + * Returns the value at the given percentile. + * @since v11.10.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentile(percentile: number): number; + /** + * Returns the value at the given percentile. + * @since v17.4.0, v16.14.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentileBigInt(percentile: number): bigint; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v17.4.0, v16.14.0 + */ + readonly percentilesBigInt: Map; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + } + interface IntervalHistogram extends Histogram { + /** + * Enables the update interval timer. Returns `true` if the timer was + * started, `false` if it was already started. + * @since v11.10.0 + */ + enable(): boolean; + /** + * Disables the update interval timer. Returns `true` if the timer was + * stopped, `false` if it was already stopped. + * @since v11.10.0 + */ + disable(): boolean; + /** + * Disables the update interval timer when the histogram is disposed. + * + * ```js + * const { monitorEventLoopDelay } = require('node:perf_hooks'); + * { + * using hist = monitorEventLoopDelay({ resolution: 20 }); + * hist.enable(); + * // The histogram will be disabled when the block is exited. + * } + * ``` + * @since v24.2.0 + */ + [Symbol.dispose](): void; + } + interface RecordableHistogram extends Histogram { + /** + * @since v15.9.0, v14.18.0 + * @param val The amount to record in the histogram. + */ + record(val: number | bigint): void; + /** + * Calculates the amount of time (in nanoseconds) that has passed since the + * previous call to `recordDelta()` and records that amount in the histogram. + * @since v15.9.0, v14.18.0 + */ + recordDelta(): void; + /** + * Adds the values from `other` to this histogram. + * @since v17.4.0, v16.14.0 + */ + add(other: RecordableHistogram): void; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Creates an `IntervalHistogram` object that samples and reports the event loop + * delay over time. The delays will be reported in nanoseconds. + * + * Using a timer to detect approximate event loop delay works because the + * execution of timers is tied specifically to the lifecycle of the libuv + * event loop. That is, a delay in the loop will cause a delay in the execution + * of the timer, and those delays are specifically what this API is intended to + * detect. + * + * ```js + * import { monitorEventLoopDelay } from 'node:perf_hooks'; + * const h = monitorEventLoopDelay({ resolution: 20 }); + * h.enable(); + * // Do something. + * h.disable(); + * console.log(h.min); + * console.log(h.max); + * console.log(h.mean); + * console.log(h.stddev); + * console.log(h.percentiles); + * console.log(h.percentile(50)); + * console.log(h.percentile(99)); + * ``` + * @since v11.10.0 + */ + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; + interface CreateHistogramOptions { + /** + * The minimum recordable value. Must be an integer value greater than 0. + * @default 1 + */ + lowest?: number | bigint | undefined; + /** + * The maximum recordable value. Must be an integer value greater than min. + * @default Number.MAX_SAFE_INTEGER + */ + highest?: number | bigint | undefined; + /** + * The number of accuracy digits. Must be a number between 1 and 5. + * @default 3 + */ + figures?: number | undefined; + } + /** + * Returns a `RecordableHistogram`. + * @since v15.9.0, v14.18.0 + */ + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; + import { + performance as _performance, + PerformanceEntry as _PerformanceEntry, + PerformanceMark as _PerformanceMark, + PerformanceMeasure as _PerformanceMeasure, + PerformanceObserver as _PerformanceObserver, + PerformanceObserverEntryList as _PerformanceObserverEntryList, + PerformanceResourceTiming as _PerformanceResourceTiming, + } from "perf_hooks"; + global { + /** + * `PerformanceEntry` is a global reference for `import { PerformanceEntry } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performanceentry + * @since v19.0.0 + */ + var PerformanceEntry: typeof globalThis extends { + onmessage: any; + PerformanceEntry: infer T; + } ? T + : typeof _PerformanceEntry; + /** + * `PerformanceMark` is a global reference for `import { PerformanceMark } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performancemark + * @since v19.0.0 + */ + var PerformanceMark: typeof globalThis extends { + onmessage: any; + PerformanceMark: infer T; + } ? T + : typeof _PerformanceMark; + /** + * `PerformanceMeasure` is a global reference for `import { PerformanceMeasure } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performancemeasure + * @since v19.0.0 + */ + var PerformanceMeasure: typeof globalThis extends { + onmessage: any; + PerformanceMeasure: infer T; + } ? T + : typeof _PerformanceMeasure; + /** + * `PerformanceObserver` is a global reference for `import { PerformanceObserver } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performanceobserver + * @since v19.0.0 + */ + var PerformanceObserver: typeof globalThis extends { + onmessage: any; + PerformanceObserver: infer T; + } ? T + : typeof _PerformanceObserver; + /** + * `PerformanceObserverEntryList` is a global reference for `import { PerformanceObserverEntryList } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performanceobserverentrylist + * @since v19.0.0 + */ + var PerformanceObserverEntryList: typeof globalThis extends { + onmessage: any; + PerformanceObserverEntryList: infer T; + } ? T + : typeof _PerformanceObserverEntryList; + /** + * `PerformanceResourceTiming` is a global reference for `import { PerformanceResourceTiming } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performanceresourcetiming + * @since v19.0.0 + */ + var PerformanceResourceTiming: typeof globalThis extends { + onmessage: any; + PerformanceResourceTiming: infer T; + } ? T + : typeof _PerformanceResourceTiming; + /** + * `performance` is a global reference for `import { performance } from 'node:perf_hooks'` + * @see https://nodejs.org/docs/latest-v24.x/api/globals.html#performance + * @since v16.0.0 + */ + var performance: typeof globalThis extends { + onmessage: any; + performance: infer T; + } ? T + : typeof _performance; + } +} +declare module "node:perf_hooks" { + export * from "perf_hooks"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/process.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/process.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7428b36a4fa520fdedcb6dabb2a1a1482908974d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/process.d.ts @@ -0,0 +1,2073 @@ +declare module "process" { + import * as tty from "node:tty"; + import { Worker } from "node:worker_threads"; + + interface BuiltInModule { + "assert": typeof import("assert"); + "node:assert": typeof import("node:assert"); + "assert/strict": typeof import("assert/strict"); + "node:assert/strict": typeof import("node:assert/strict"); + "async_hooks": typeof import("async_hooks"); + "node:async_hooks": typeof import("node:async_hooks"); + "buffer": typeof import("buffer"); + "node:buffer": typeof import("node:buffer"); + "child_process": typeof import("child_process"); + "node:child_process": typeof import("node:child_process"); + "cluster": typeof import("cluster"); + "node:cluster": typeof import("node:cluster"); + "console": typeof import("console"); + "node:console": typeof import("node:console"); + "constants": typeof import("constants"); + "node:constants": typeof import("node:constants"); + "crypto": typeof import("crypto"); + "node:crypto": typeof import("node:crypto"); + "dgram": typeof import("dgram"); + "node:dgram": typeof import("node:dgram"); + "diagnostics_channel": typeof import("diagnostics_channel"); + "node:diagnostics_channel": typeof import("node:diagnostics_channel"); + "dns": typeof import("dns"); + "node:dns": typeof import("node:dns"); + "dns/promises": typeof import("dns/promises"); + "node:dns/promises": typeof import("node:dns/promises"); + "domain": typeof import("domain"); + "node:domain": typeof import("node:domain"); + "events": typeof import("events"); + "node:events": typeof import("node:events"); + "fs": typeof import("fs"); + "node:fs": typeof import("node:fs"); + "fs/promises": typeof import("fs/promises"); + "node:fs/promises": typeof import("node:fs/promises"); + "http": typeof import("http"); + "node:http": typeof import("node:http"); + "http2": typeof import("http2"); + "node:http2": typeof import("node:http2"); + "https": typeof import("https"); + "node:https": typeof import("node:https"); + "inspector": typeof import("inspector"); + "node:inspector": typeof import("node:inspector"); + "inspector/promises": typeof import("inspector/promises"); + "node:inspector/promises": typeof import("node:inspector/promises"); + "module": typeof import("module"); + "node:module": typeof import("node:module"); + "net": typeof import("net"); + "node:net": typeof import("node:net"); + "os": typeof import("os"); + "node:os": typeof import("node:os"); + "path": typeof import("path"); + "node:path": typeof import("node:path"); + "path/posix": typeof import("path/posix"); + "node:path/posix": typeof import("node:path/posix"); + "path/win32": typeof import("path/win32"); + "node:path/win32": typeof import("node:path/win32"); + "perf_hooks": typeof import("perf_hooks"); + "node:perf_hooks": typeof import("node:perf_hooks"); + "process": typeof import("process"); + "node:process": typeof import("node:process"); + "punycode": typeof import("punycode"); + "node:punycode": typeof import("node:punycode"); + "querystring": typeof import("querystring"); + "node:querystring": typeof import("node:querystring"); + "readline": typeof import("readline"); + "node:readline": typeof import("node:readline"); + "readline/promises": typeof import("readline/promises"); + "node:readline/promises": typeof import("node:readline/promises"); + "repl": typeof import("repl"); + "node:repl": typeof import("node:repl"); + "node:sea": typeof import("node:sea"); + "node:sqlite": typeof import("node:sqlite"); + "stream": typeof import("stream"); + "node:stream": typeof import("node:stream"); + "stream/consumers": typeof import("stream/consumers"); + "node:stream/consumers": typeof import("node:stream/consumers"); + "stream/promises": typeof import("stream/promises"); + "node:stream/promises": typeof import("node:stream/promises"); + "stream/web": typeof import("stream/web"); + "node:stream/web": typeof import("node:stream/web"); + "string_decoder": typeof import("string_decoder"); + "node:string_decoder": typeof import("node:string_decoder"); + "node:test": typeof import("node:test"); + "node:test/reporters": typeof import("node:test/reporters"); + "timers": typeof import("timers"); + "node:timers": typeof import("node:timers"); + "timers/promises": typeof import("timers/promises"); + "node:timers/promises": typeof import("node:timers/promises"); + "tls": typeof import("tls"); + "node:tls": typeof import("node:tls"); + "trace_events": typeof import("trace_events"); + "node:trace_events": typeof import("node:trace_events"); + "tty": typeof import("tty"); + "node:tty": typeof import("node:tty"); + "url": typeof import("url"); + "node:url": typeof import("node:url"); + "util": typeof import("util"); + "node:util": typeof import("node:util"); + "sys": typeof import("util"); + "node:sys": typeof import("node:util"); + "util/types": typeof import("util/types"); + "node:util/types": typeof import("node:util/types"); + "v8": typeof import("v8"); + "node:v8": typeof import("node:v8"); + "vm": typeof import("vm"); + "node:vm": typeof import("node:vm"); + "wasi": typeof import("wasi"); + "node:wasi": typeof import("node:wasi"); + "worker_threads": typeof import("worker_threads"); + "node:worker_threads": typeof import("node:worker_threads"); + "zlib": typeof import("zlib"); + "node:zlib": typeof import("node:zlib"); + } + global { + var process: NodeJS.Process; + namespace NodeJS { + // this namespace merge is here because these are specifically used + // as the type for process.stdin, process.stdout, and process.stderr. + // they can't live in tty.d.ts because we need to disambiguate the imported name. + interface ReadStream extends tty.ReadStream {} + interface WriteStream extends tty.WriteStream {} + interface MemoryUsageFn { + /** + * The `process.memoryUsage()` method iterate over each page to gather informations about memory + * usage which can be slow depending on the program memory allocations. + */ + (): MemoryUsage; + /** + * method returns an integer representing the Resident Set Size (RSS) in bytes. + */ + rss(): number; + } + interface MemoryUsage { + /** + * Resident Set Size, is the amount of space occupied in the main memory device (that is a subset of the total allocated memory) for the + * process, including all C++ and JavaScript objects and code. + */ + rss: number; + /** + * Refers to V8's memory usage. + */ + heapTotal: number; + /** + * Refers to V8's memory usage. + */ + heapUsed: number; + external: number; + /** + * Refers to memory allocated for `ArrayBuffer`s and `SharedArrayBuffer`s, including all Node.js Buffers. This is also included + * in the external value. When Node.js is used as an embedded library, this value may be `0` because allocations for `ArrayBuffer`s + * may not be tracked in that case. + */ + arrayBuffers: number; + } + interface CpuUsage { + user: number; + system: number; + } + interface ProcessRelease { + name: string; + sourceUrl?: string | undefined; + headersUrl?: string | undefined; + libUrl?: string | undefined; + lts?: string | undefined; + } + interface ProcessFeatures { + /** + * A boolean value that is `true` if the current Node.js build is caching builtin modules. + * @since v12.0.0 + */ + readonly cached_builtins: boolean; + /** + * A boolean value that is `true` if the current Node.js build is a debug build. + * @since v0.5.5 + */ + readonly debug: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes the inspector. + * @since v11.10.0 + */ + readonly inspector: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for IPv6. + * + * Since all Node.js builds have IPv6 support, this value is always `true`. + * @since v0.5.3 + * @deprecated This property is always true, and any checks based on it are redundant. + */ + readonly ipv6: boolean; + /** + * A boolean value that is `true` if the current Node.js build supports + * [loading ECMAScript modules using `require()`](https://nodejs.org/docs/latest-v24.x/api/modules.md#loading-ecmascript-modules-using-require). + * @since v22.10.0 + */ + readonly require_module: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for TLS. + * @since v0.5.3 + */ + readonly tls: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for ALPN in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional ALPN support. + * This value is therefore identical to that of `process.features.tls`. + * @since v4.8.0 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_alpn: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for OCSP in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional OCSP support. + * This value is therefore identical to that of `process.features.tls`. + * @since v0.11.13 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_ocsp: boolean; + /** + * A boolean value that is `true` if the current Node.js build includes support for SNI in TLS. + * + * In Node.js 11.0.0 and later versions, the OpenSSL dependencies feature unconditional SNI support. + * This value is therefore identical to that of `process.features.tls`. + * @since v0.5.3 + * @deprecated Use `process.features.tls` instead. + */ + readonly tls_sni: boolean; + /** + * A value that is `"strip"` by default, + * `"transform"` if Node.js is run with `--experimental-transform-types`, and `false` if + * Node.js is run with `--no-experimental-strip-types`. + * @since v22.10.0 + */ + readonly typescript: "strip" | "transform" | false; + /** + * A boolean value that is `true` if the current Node.js build includes support for libuv. + * + * Since it's not possible to build Node.js without libuv, this value is always `true`. + * @since v0.5.3 + * @deprecated This property is always true, and any checks based on it are redundant. + */ + readonly uv: boolean; + } + interface ProcessVersions extends Dict { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + type Platform = + | "aix" + | "android" + | "darwin" + | "freebsd" + | "haiku" + | "linux" + | "openbsd" + | "sunos" + | "win32" + | "cygwin" + | "netbsd"; + type Architecture = + | "arm" + | "arm64" + | "ia32" + | "loong64" + | "mips" + | "mipsel" + | "ppc64" + | "riscv64" + | "s390x" + | "x64"; + type Signals = + | "SIGABRT" + | "SIGALRM" + | "SIGBUS" + | "SIGCHLD" + | "SIGCONT" + | "SIGFPE" + | "SIGHUP" + | "SIGILL" + | "SIGINT" + | "SIGIO" + | "SIGIOT" + | "SIGKILL" + | "SIGPIPE" + | "SIGPOLL" + | "SIGPROF" + | "SIGPWR" + | "SIGQUIT" + | "SIGSEGV" + | "SIGSTKFLT" + | "SIGSTOP" + | "SIGSYS" + | "SIGTERM" + | "SIGTRAP" + | "SIGTSTP" + | "SIGTTIN" + | "SIGTTOU" + | "SIGUNUSED" + | "SIGURG" + | "SIGUSR1" + | "SIGUSR2" + | "SIGVTALRM" + | "SIGWINCH" + | "SIGXCPU" + | "SIGXFSZ" + | "SIGBREAK" + | "SIGLOST" + | "SIGINFO"; + type UncaughtExceptionOrigin = "uncaughtException" | "unhandledRejection"; + type MultipleResolveType = "resolve" | "reject"; + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error, origin: UncaughtExceptionOrigin) => void; + /** + * Most of the time the unhandledRejection will be an Error, but this should not be relied upon + * as *anything* can be thrown/rejected, it is therefore unsafe to assume that the value is an Error. + */ + type UnhandledRejectionListener = (reason: unknown, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: unknown, sendHandle: unknown) => void; + type SignalsListener = (signal: Signals) => void; + type MultipleResolveListener = ( + type: MultipleResolveType, + promise: Promise, + value: unknown, + ) => void; + type WorkerListener = (worker: Worker) => void; + interface Socket extends ReadWriteStream { + isTTY?: true | undefined; + } + // Alias for compatibility + interface ProcessEnv extends Dict { + /** + * Can be used to change the default timezone at runtime + */ + TZ?: string; + } + interface HRTime { + /** + * This is the legacy version of {@link process.hrtime.bigint()} + * before bigint was introduced in JavaScript. + * + * The `process.hrtime()` method returns the current high-resolution real time in a `[seconds, nanoseconds]` tuple `Array`, + * where `nanoseconds` is the remaining part of the real time that can't be represented in second precision. + * + * `time` is an optional parameter that must be the result of a previous `process.hrtime()` call to diff with the current time. + * If the parameter passed in is not a tuple `Array`, a TypeError will be thrown. + * Passing in a user-defined array instead of the result of a previous call to `process.hrtime()` will lead to undefined behavior. + * + * These times are relative to an arbitrary time in the past, + * and not related to the time of day and therefore not subject to clock drift. + * The primary use is for measuring performance between intervals: + * ```js + * const { hrtime } = require('node:process'); + * const NS_PER_SEC = 1e9; + * const time = hrtime(); + * // [ 1800216, 25 ] + * + * setTimeout(() => { + * const diff = hrtime(time); + * // [ 1, 552 ] + * + * console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`); + * // Benchmark took 1000000552 nanoseconds + * }, 1000); + * ``` + * @since 0.7.6 + * @legacy Use {@link process.hrtime.bigint()} instead. + * @param time The result of a previous call to `process.hrtime()` + */ + (time?: [number, number]): [number, number]; + /** + * The `bigint` version of the {@link process.hrtime()} method returning the current high-resolution real time in nanoseconds as a `bigint`. + * + * Unlike {@link process.hrtime()}, it does not support an additional time argument since the difference can just be computed directly by subtraction of the two `bigint`s. + * ```js + * import { hrtime } from 'node:process'; + * + * const start = hrtime.bigint(); + * // 191051479007711n + * + * setTimeout(() => { + * const end = hrtime.bigint(); + * // 191052633396993n + * + * console.log(`Benchmark took ${end - start} nanoseconds`); + * // Benchmark took 1154389282 nanoseconds + * }, 1000); + * ``` + * @since v10.7.0 + */ + bigint(): bigint; + } + interface ProcessPermission { + /** + * Verifies that the process is able to access the given scope and reference. + * If no reference is provided, a global scope is assumed, for instance, `process.permission.has('fs.read')` + * will check if the process has ALL file system read permissions. + * + * The reference has a meaning based on the provided scope. For example, the reference when the scope is File System means files and folders. + * + * The available scopes are: + * + * * `fs` - All File System + * * `fs.read` - File System read operations + * * `fs.write` - File System write operations + * * `child` - Child process spawning operations + * * `worker` - Worker thread spawning operation + * + * ```js + * // Check if the process has permission to read the README file + * process.permission.has('fs.read', './README.md'); + * // Check if the process has read permission operations + * process.permission.has('fs.read'); + * ``` + * @since v20.0.0 + */ + has(scope: string, reference?: string): boolean; + } + interface ProcessReport { + /** + * Write reports in a compact format, single-line JSON, more easily consumable by log processing systems + * than the default multi-line format designed for human consumption. + * @since v13.12.0, v12.17.0 + */ + compact: boolean; + /** + * Directory where the report is written. + * The default value is the empty string, indicating that reports are written to the current + * working directory of the Node.js process. + */ + directory: string; + /** + * Filename where the report is written. If set to the empty string, the output filename will be comprised + * of a timestamp, PID, and sequence number. The default value is the empty string. + */ + filename: string; + /** + * Returns a JavaScript Object representation of a diagnostic report for the running process. + * The report's JavaScript stack trace is taken from `err`, if present. + */ + getReport(err?: Error): object; + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @default false + */ + reportOnSignal: boolean; + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from `err`, if present. + * + * If the value of filename is set to `'stdout'` or `'stderr'`, the report is written + * to the stdout or stderr of the process respectively. + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param err A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string, err?: Error): string; + writeReport(err?: Error): string; + } + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + interface EmitWarningOptions { + /** + * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. + * + * @default 'Warning' + */ + type?: string | undefined; + /** + * A unique identifier for the warning instance being emitted. + */ + code?: string | undefined; + /** + * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. + * + * @default process.emitWarning + */ + ctor?: Function | undefined; + /** + * Additional text to include with the error. + */ + detail?: string | undefined; + } + interface ProcessConfig { + readonly target_defaults: { + readonly cflags: any[]; + readonly default_configuration: string; + readonly defines: string[]; + readonly include_dirs: string[]; + readonly libraries: string[]; + }; + readonly variables: { + readonly clang: number; + readonly host_arch: string; + readonly node_install_npm: boolean; + readonly node_install_waf: boolean; + readonly node_prefix: string; + readonly node_shared_openssl: boolean; + readonly node_shared_v8: boolean; + readonly node_shared_zlib: boolean; + readonly node_use_dtrace: boolean; + readonly node_use_etw: boolean; + readonly node_use_openssl: boolean; + readonly target_arch: string; + readonly v8_no_strict_aliasing: number; + readonly v8_use_snapshot: boolean; + readonly visibility: string; + }; + } + interface Process extends EventEmitter { + /** + * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is + * a `Writable` stream. + * + * For example, to copy `process.stdin` to `process.stdout`: + * + * ```js + * import { stdin, stdout } from 'node:process'; + * + * stdin.pipe(stdout); + * ``` + * + * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stdout: WriteStream & { + fd: 1; + }; + /** + * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is + * a `Writable` stream. + * + * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stderr: WriteStream & { + fd: 2; + }; + /** + * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is + * a `Readable` stream. + * + * For details of how to read from `stdin` see `readable.read()`. + * + * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that + * is compatible with scripts written for Node.js prior to v0.10\. + * For more information see `Stream compatibility`. + * + * In "old" streams mode the `stdin` stream is paused by default, so one + * must call `process.stdin.resume()` to read from it. Note also that calling `process.stdin.resume()` itself would switch stream to "old" mode. + */ + stdin: ReadStream & { + fd: 0; + }; + /** + * The `process.argv` property returns an array containing the command-line + * arguments passed when the Node.js process was launched. The first element will + * be {@link execPath}. See `process.argv0` if access to the original value + * of `argv[0]` is needed. The second element will be the path to the JavaScript + * file being executed. The remaining elements will be any additional command-line + * arguments. + * + * For example, assuming the following script for `process-args.js`: + * + * ```js + * import { argv } from 'node:process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```bash + * node process-args.js one two=three four + * ``` + * + * Would generate the output: + * + * ```text + * 0: /usr/local/bin/node + * 1: /Users/mjr/work/node/process-args.js + * 2: one + * 3: two=three + * 4: four + * ``` + * @since v0.1.27 + */ + argv: string[]; + /** + * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. + * + * ```console + * $ bash -c 'exec -a customArgv0 ./node' + * > process.argv[0] + * '/Volumes/code/external/node/out/Release/node' + * > process.argv0 + * 'customArgv0' + * ``` + * @since v6.4.0 + */ + argv0: string; + /** + * The `process.execArgv` property returns the set of Node.js-specific command-line + * options passed when the Node.js process was launched. These options do not + * appear in the array returned by the {@link argv} property, and do not + * include the Node.js executable, the name of the script, or any options following + * the script name. These options are useful in order to spawn child processes with + * the same execution environment as the parent. + * + * ```bash + * node --icu-data-dir=./foo --require ./bar.js script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ["--icu-data-dir=./foo", "--require", "./bar.js"] + * ``` + * + * And `process.argv`: + * + * ```js + * ['/usr/local/bin/node', 'script.js', '--version'] + * ``` + * + * Refer to `Worker constructor` for the detailed behavior of worker + * threads with this property. + * @since v0.7.7 + */ + execArgv: string[]; + /** + * The `process.execPath` property returns the absolute pathname of the executable + * that started the Node.js process. Symbolic links, if any, are resolved. + * + * ```js + * '/usr/local/bin/node' + * ``` + * @since v0.1.100 + */ + execPath: string; + /** + * The `process.abort()` method causes the Node.js process to exit immediately and + * generate a core file. + * + * This feature is not available in `Worker` threads. + * @since v0.7.0 + */ + abort(): never; + /** + * The `process.chdir()` method changes the current working directory of the + * Node.js process or throws an exception if doing so fails (for instance, if + * the specified `directory` does not exist). + * + * ```js + * import { chdir, cwd } from 'node:process'; + * + * console.log(`Starting directory: ${cwd()}`); + * try { + * chdir('/tmp'); + * console.log(`New directory: ${cwd()}`); + * } catch (err) { + * console.error(`chdir: ${err}`); + * } + * ``` + * + * This feature is not available in `Worker` threads. + * @since v0.1.17 + */ + chdir(directory: string): void; + /** + * The `process.cwd()` method returns the current working directory of the Node.js + * process. + * + * ```js + * import { cwd } from 'node:process'; + * + * console.log(`Current directory: ${cwd()}`); + * ``` + * @since v0.1.8 + */ + cwd(): string; + /** + * The port used by the Node.js debugger when enabled. + * + * ```js + * import process from 'node:process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * The `process.dlopen()` method allows dynamically loading shared objects. It is primarily used by `require()` to load C++ Addons, and + * should not be used directly, except in special cases. In other words, `require()` should be preferred over `process.dlopen()` + * unless there are specific reasons such as custom dlopen flags or loading from ES modules. + * + * The `flags` argument is an integer that allows to specify dlopen behavior. See the `[os.constants.dlopen](https://nodejs.org/docs/latest-v24.x/api/os.html#dlopen-constants)` + * documentation for details. + * + * An important requirement when calling `process.dlopen()` is that the `module` instance must be passed. Functions exported by the C++ Addon + * are then accessible via `module.exports`. + * + * The example below shows how to load a C++ Addon, named `local.node`, that exports a `foo` function. All the symbols are loaded before the call returns, by passing the `RTLD_NOW` constant. + * In this example the constant is assumed to be available. + * + * ```js + * import { dlopen } from 'node:process'; + * import { constants } from 'node:os'; + * import { fileURLToPath } from 'node:url'; + * + * const module = { exports: {} }; + * dlopen(module, fileURLToPath(new URL('local.node', import.meta.url)), + * constants.dlopen.RTLD_NOW); + * module.exports.foo(); + * ``` + */ + dlopen(module: object, filename: string, flags?: number): void; + /** + * The `process.emitWarning()` method can be used to emit custom or application + * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string. + * emitWarning('Something happened!'); + * // Emits: (node: 56338) Warning: Something happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string and a type. + * emitWarning('Something Happened!', 'CustomWarning'); + * // Emits: (node:56338) CustomWarning: Something Happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * emitWarning('Something happened!', 'CustomWarning', 'WARN001'); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ```js + * + * In each of the previous examples, an `Error` object is generated internally by `process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from 'node:process'; + * + * process.on('warning', (warning) => { + * console.warn(warning.name); // 'Warning' + * console.warn(warning.message); // 'Something happened!' + * console.warn(warning.code); // 'MY_WARNING' + * console.warn(warning.stack); // Stack trace + * console.warn(warning.detail); // 'This is some additional information' + * }); + * ``` + * + * If `warning` is passed as an `Error` object, it will be passed through to the `'warning'` event handler + * unmodified (and the optional `type`, `code` and `ctor` arguments will be ignored): + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using an Error object. + * const myWarning = new Error('Something happened!'); + * // Use the Error name property to specify the type name + * myWarning.name = 'CustomWarning'; + * myWarning.code = 'WARN001'; + * + * emitWarning(myWarning); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ``` + * + * A `TypeError` is thrown if `warning` is anything other than a string or `Error` object. + * + * While process warnings use `Error` objects, the process warning mechanism is not a replacement for normal error handling mechanisms. + * + * The following additional handling is implemented if the warning `type` is `'DeprecationWarning'`: + * * If the `--throw-deprecation` command-line flag is used, the deprecation warning is thrown as an exception rather than being emitted as an event. + * * If the `--no-deprecation` command-line flag is used, the deprecation warning is suppressed. + * * If the `--trace-deprecation` command-line flag is used, the deprecation warning is printed to `stderr` along with the full stack trace. + * @since v8.0.0 + * @param warning The warning to emit. + */ + emitWarning(warning: string | Error, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; + emitWarning(warning: string | Error, options?: EmitWarningOptions): void; + /** + * The `process.env` property returns an object containing the user environment. + * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). + * + * An example of this object looks like: + * + * ```js + * { + * TERM: 'xterm-256color', + * SHELL: '/usr/local/bin/bash', + * USER: 'maciej', + * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', + * PWD: '/Users/maciej', + * EDITOR: 'vim', + * SHLVL: '1', + * HOME: '/Users/maciej', + * LOGNAME: 'maciej', + * _: '/usr/local/bin/node' + * } + * ``` + * + * It is possible to modify this object, but such modifications will not be + * reflected outside the Node.js process, or (unless explicitly requested) + * to other `Worker` threads. + * In other words, the following example would not work: + * + * ```bash + * node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from 'node:process'; + * + * env.foo = 'bar'; + * console.log(env.foo); + * ``` + * + * Assigning a property on `process.env` will implicitly convert the value + * to a string. **This behavior is deprecated.** Future versions of Node.js may + * throw an error when the value is not a string, number, or boolean. + * + * ```js + * import { env } from 'node:process'; + * + * env.test = null; + * console.log(env.test); + * // => 'null' + * env.test = undefined; + * console.log(env.test); + * // => 'undefined' + * ``` + * + * Use `delete` to delete a property from `process.env`. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * delete env.TEST; + * console.log(env.TEST); + * // => undefined + * ``` + * + * On Windows operating systems, environment variables are case-insensitive. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * console.log(env.test); + * // => 1 + * ``` + * + * Unless explicitly specified when creating a `Worker` instance, + * each `Worker` thread has its own copy of `process.env`, based on its + * parent thread's `process.env`, or whatever was specified as the `env` option + * to the `Worker` constructor. Changes to `process.env` will not be visible + * across `Worker` threads, and only the main thread can make changes that + * are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner + * unlike the main thread. + * @since v0.1.27 + */ + env: ProcessEnv; + /** + * The `process.exit()` method instructs Node.js to terminate the process + * synchronously with an exit status of `code`. If `code` is omitted, exit uses + * either the 'success' code `0` or the value of `process.exitCode` if it has been + * set. Node.js will not terminate until all the `'exit'` event listeners are + * called. + * + * To exit with a 'failure' code: + * + * ```js + * import { exit } from 'node:process'; + * + * exit(1); + * ``` + * + * The shell that executed Node.js should see the exit code as `1`. + * + * Calling `process.exit()` will force the process to exit as quickly as possible + * even if there are still asynchronous operations pending that have not yet + * completed fully, including I/O operations to `process.stdout` and `process.stderr`. + * + * In most situations, it is not actually necessary to call `process.exit()` explicitly. The Node.js process will exit on its own _if there is no additional_ + * _work pending_ in the event loop. The `process.exitCode` property can be set to + * tell the process which exit code to use when the process exits gracefully. + * + * For instance, the following example illustrates a _misuse_ of the `process.exit()` method that could lead to data printed to stdout being + * truncated and lost: + * + * ```js + * import { exit } from 'node:process'; + * + * // This is an example of what *not* to do: + * if (someConditionNotMet()) { + * printUsageToStdout(); + * exit(1); + * } + * ``` + * + * The reason this is problematic is because writes to `process.stdout` in Node.js + * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js + * event loop. Calling `process.exit()`, however, forces the process to exit _before_ those additional writes to `stdout` can be performed. + * + * Rather than calling `process.exit()` directly, the code _should_ set the `process.exitCode` and allow the process to exit naturally by avoiding + * scheduling any additional work for the event loop: + * + * ```js + * import process from 'node:process'; + * + * // How to properly set the exit code while letting + * // the process exit gracefully. + * if (someConditionNotMet()) { + * printUsageToStdout(); + * process.exitCode = 1; + * } + * ``` + * + * If it is necessary to terminate the Node.js process due to an error condition, + * throwing an _uncaught_ error and allowing the process to terminate accordingly + * is safer than calling `process.exit()`. + * + * In `Worker` threads, this function stops the current thread rather + * than the current process. + * @since v0.1.13 + * @param [code=0] The exit code. For string type, only integer strings (e.g.,'1') are allowed. + */ + exit(code?: number | string | null | undefined): never; + /** + * A number which will be the process exit code, when the process either + * exits gracefully, or is exited via {@link exit} without specifying + * a code. + * + * Specifying a code to {@link exit} will override any + * previous setting of `process.exitCode`. + * @default undefined + * @since v0.11.8 + */ + exitCode?: number | string | number | undefined; + finalization: { + /** + * This function registers a callback to be called when the process emits the `exit` event if the `ref` object was not garbage collected. + * If the object `ref` was garbage collected before the `exit` event is emitted, the callback will be removed from the finalization registry, and it will not be called on process exit. + * + * Inside the callback you can release the resources allocated by the `ref` object. + * Be aware that all limitations applied to the `beforeExit` event are also applied to the callback function, + * this means that there is a possibility that the callback will not be called under special circumstances. + * + * The idea of ​​this function is to help you free up resources when the starts process exiting, but also let the object be garbage collected if it is no longer being used. + * @param ref The reference to the resource that is being tracked. + * @param callback The callback function to be called when the resource is finalized. + * @since v22.5.0 + * @experimental + */ + register(ref: T, callback: (ref: T, event: "exit") => void): void; + /** + * This function behaves exactly like the `register`, except that the callback will be called when the process emits the `beforeExit` event if `ref` object was not garbage collected. + * + * Be aware that all limitations applied to the `beforeExit` event are also applied to the callback function, this means that there is a possibility that the callback will not be called under special circumstances. + * @param ref The reference to the resource that is being tracked. + * @param callback The callback function to be called when the resource is finalized. + * @since v22.5.0 + * @experimental + */ + registerBeforeExit(ref: T, callback: (ref: T, event: "beforeExit") => void): void; + /** + * This function remove the register of the object from the finalization registry, so the callback will not be called anymore. + * @param ref The reference to the resource that was registered previously. + * @since v22.5.0 + * @experimental + */ + unregister(ref: object): void; + }; + /** + * The `process.getActiveResourcesInfo()` method returns an array of strings containing + * the types of the active resources that are currently keeping the event loop alive. + * + * ```js + * import { getActiveResourcesInfo } from 'node:process'; + * import { setTimeout } from 'node:timers'; + + * console.log('Before:', getActiveResourcesInfo()); + * setTimeout(() => {}, 1000); + * console.log('After:', getActiveResourcesInfo()); + * // Prints: + * // Before: [ 'TTYWrap', 'TTYWrap', 'TTYWrap' ] + * // After: [ 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ] + * ``` + * @since v17.3.0, v16.14.0 + */ + getActiveResourcesInfo(): string[]; + /** + * Provides a way to load built-in modules in a globally available function. + * @param id ID of the built-in module being requested. + */ + getBuiltinModule(id: ID): BuiltInModule[ID]; + getBuiltinModule(id: string): object | undefined; + /** + * The `process.getgid()` method returns the numerical group identity of the + * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid) { + * console.log(`Current gid: ${process.getgid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.31 + */ + getgid?: () => number; + /** + * The `process.setgid()` method sets the group identity of the process. (See [`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a + * numeric ID or a group name + * string. If a group name is specified, this method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid && process.setgid) { + * console.log(`Current gid: ${process.getgid()}`); + * try { + * process.setgid(501); + * console.log(`New gid: ${process.getgid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.31 + * @param id The group name or ID + */ + setgid?: (id: number | string) => void; + /** + * The `process.getuid()` method returns the numeric user identity of the process. + * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid) { + * console.log(`Current uid: ${process.getuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.28 + */ + getuid?: () => number; + /** + * The `process.setuid(id)` method sets the user identity of the process. (See [`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a + * numeric ID or a username string. + * If a username is specified, the method blocks while resolving the associated + * numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid && process.setuid) { + * console.log(`Current uid: ${process.getuid()}`); + * try { + * process.setuid(501); + * console.log(`New uid: ${process.getuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.28 + */ + setuid?: (id: number | string) => void; + /** + * The `process.geteuid()` method returns the numerical effective user identity of + * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + geteuid?: () => number; + /** + * The `process.seteuid()` method sets the effective user identity of the process. + * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username + * string. If a username is specified, the method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid && process.seteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * try { + * process.seteuid(501); + * console.log(`New uid: ${process.geteuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A user name or ID + */ + seteuid?: (id: number | string) => void; + /** + * The `process.getegid()` method returns the numerical effective group identity + * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid) { + * console.log(`Current gid: ${process.getegid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + getegid?: () => number; + /** + * The `process.setegid()` method sets the effective group identity of the process. + * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group + * name string. If a group name is specified, this method blocks while resolving + * the associated a numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid && process.setegid) { + * console.log(`Current gid: ${process.getegid()}`); + * try { + * process.setegid(501); + * console.log(`New gid: ${process.getegid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A group name or ID + */ + setegid?: (id: number | string) => void; + /** + * The `process.getgroups()` method returns an array with the supplementary group + * IDs. POSIX leaves it unspecified if the effective group ID is included but + * Node.js ensures it always is. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups) { + * console.log(process.getgroups()); // [ 16, 21, 297 ] + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.9.4 + */ + getgroups?: () => number[]; + /** + * The `process.setgroups()` method sets the supplementary group IDs for the + * Node.js process. This is a privileged operation that requires the Node.js + * process to have `root` or the `CAP_SETGID` capability. + * + * The `groups` array can contain numeric group IDs, group names, or both. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups && process.setgroups) { + * try { + * process.setgroups([501]); + * console.log(process.getgroups()); // new groups + * } catch (err) { + * console.log(`Failed to set groups: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.9.4 + */ + setgroups?: (groups: ReadonlyArray) => void; + /** + * The `process.setUncaughtExceptionCaptureCallback()` function sets a function + * that will be invoked when an uncaught exception occurs, which will receive the + * exception value itself as its first argument. + * + * If such a function is set, the `'uncaughtException'` event will + * not be emitted. If `--abort-on-uncaught-exception` was passed from the + * command line or set through `v8.setFlagsFromString()`, the process will + * not abort. Actions configured to take place on exceptions such as report + * generations will be affected too + * + * To unset the capture function, `process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this + * method with a non-`null` argument while another capture function is set will + * throw an error. + * + * Using this function is mutually exclusive with using the deprecated `domain` built-in module. + * @since v9.3.0 + */ + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + /** + * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. + * @since v9.3.0 + */ + hasUncaughtExceptionCaptureCallback(): boolean; + /** + * The `process.sourceMapsEnabled` property returns whether the [Source Map v3](https://sourcemaps.info/spec.html) support for stack traces is enabled. + * @since v20.7.0 + * @experimental + */ + readonly sourceMapsEnabled: boolean; + /** + * This function enables or disables the [Source Map v3](https://sourcemaps.info/spec.html) support for + * stack traces. + * + * It provides same features as launching Node.js process with commandline options `--enable-source-maps`. + * + * Only source maps in JavaScript files that are loaded after source maps has been + * enabled will be parsed and loaded. + * @since v16.6.0, v14.18.0 + * @experimental + */ + setSourceMapsEnabled(value: boolean): void; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from 'node:process'; + * + * console.log(`Version: ${version}`); + * // Version: v14.8.0 + * ``` + * + * To get the version string without the prepended _v_, use`process.versions.node`. + * @since v0.1.3 + */ + readonly version: string; + /** + * The `process.versions` property returns an object listing the version strings of + * Node.js and its dependencies. `process.versions.modules` indicates the current + * ABI version, which is increased whenever a C++ API changes. Node.js will refuse + * to load modules that were compiled against a different module ABI version. + * + * ```js + * import { versions } from 'node:process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '20.2.0', + * acorn: '8.8.2', + * ada: '2.4.0', + * ares: '1.19.0', + * base64: '0.5.0', + * brotli: '1.0.9', + * cjs_module_lexer: '1.2.2', + * cldr: '43.0', + * icu: '73.1', + * llhttp: '8.1.0', + * modules: '115', + * napi: '8', + * nghttp2: '1.52.0', + * nghttp3: '0.7.0', + * ngtcp2: '0.8.1', + * openssl: '3.0.8+quic', + * simdutf: '3.2.9', + * tz: '2023c', + * undici: '5.22.0', + * unicode: '15.0', + * uv: '1.44.2', + * uvwasi: '0.0.16', + * v8: '11.3.244.8-node.9', + * zlib: '1.2.13' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns a frozen `Object` containing the + * JavaScript representation of the configure options used to compile the current + * Node.js executable. This is the same as the `config.gypi` file that was produced + * when running the `./configure` script. + * + * An example of the possible output looks like: + * + * ```js + * { + * target_defaults: + * { cflags: [], + * default_configuration: 'Release', + * defines: [], + * include_dirs: [], + * libraries: [] }, + * variables: + * { + * host_arch: 'x64', + * napi_build_version: 5, + * node_install_npm: 'true', + * node_prefix: '', + * node_shared_cares: 'false', + * node_shared_http_parser: 'false', + * node_shared_libuv: 'false', + * node_shared_zlib: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * @since v0.7.7 + */ + readonly config: ProcessConfig; + /** + * The `process.kill()` method sends the `signal` to the process identified by`pid`. + * + * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. + * + * This method will throw an error if the target `pid` does not exist. As a special + * case, a signal of `0` can be used to test for the existence of a process. + * Windows platforms will throw an error if the `pid` is used to kill a process + * group. + * + * Even though the name of this function is `process.kill()`, it is really just a + * signal sender, like the `kill` system call. The signal sent may do something + * other than kill the target process. + * + * ```js + * import process, { kill } from 'node:process'; + * + * process.on('SIGHUP', () => { + * console.log('Got SIGHUP signal.'); + * }); + * + * setTimeout(() => { + * console.log('Exiting.'); + * process.exit(0); + * }, 100); + * + * kill(process.pid, 'SIGHUP'); + * ``` + * + * When `SIGUSR1` is received by a Node.js process, Node.js will start the + * debugger. See `Signal Events`. + * @since v0.0.6 + * @param pid A process ID + * @param [signal='SIGTERM'] The signal to send, either as a string or number. + */ + kill(pid: number, signal?: string | number): true; + /** + * Loads the environment configuration from a `.env` file into `process.env`. If + * the file is not found, error will be thrown. + * + * To load a specific .env file by specifying its path, use the following code: + * + * ```js + * import { loadEnvFile } from 'node:process'; + * + * loadEnvFile('./development.env') + * ``` + * @since v20.12.0 + * @param path The path to the .env file + */ + loadEnvFile(path?: string | URL | Buffer): void; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from 'node:process'; + * + * console.log(`This process is pid ${pid}`); + * ``` + * @since v0.1.15 + */ + readonly pid: number; + /** + * The `process.ppid` property returns the PID of the parent of the + * current process. + * + * ```js + * import { ppid } from 'node:process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * The `process.threadCpuUsage()` method returns the user and system CPU time usage of + * the current worker thread, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). + * + * The result of a previous call to `process.threadCpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * @since v23.9.0 + * @param previousValue A previous return value from calling + * `process.threadCpuUsage()` + */ + threadCpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * The `process.title` property returns the current process title (i.e. returns + * the current value of `ps`). Assigning a new value to `process.title` modifies + * the current value of `ps`. + * + * When a new value is assigned, different platforms will impose different maximum + * length restrictions on the title. Usually such restrictions are quite limited. + * For instance, on Linux and macOS, `process.title` is limited to the size of the + * binary name plus the length of the command-line arguments because setting the `process.title` overwrites the `argv` memory of the process. Node.js v0.8 + * allowed for longer process title strings by also overwriting the `environ` memory but that was potentially insecure and confusing in some (rather obscure) + * cases. + * + * Assigning a value to `process.title` might not result in an accurate label + * within process manager applications such as macOS Activity Monitor or Windows + * Services Manager. + * @since v0.1.104 + */ + title: string; + /** + * The operating system CPU architecture for which the Node.js binary was compiled. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, + * `'mipsel'`, `'ppc64'`, `'riscv64'`, `'s390x'`, and `'x64'`. + * + * ```js + * import { arch } from 'node:process'; + * + * console.log(`This processor architecture is ${arch}`); + * ``` + * @since v0.5.0 + */ + readonly arch: Architecture; + /** + * The `process.platform` property returns a string identifying the operating + * system platform for which the Node.js binary was compiled. + * + * Currently possible values are: + * + * * `'aix'` + * * `'darwin'` + * * `'freebsd'` + * * `'linux'` + * * `'openbsd'` + * * `'sunos'` + * * `'win32'` + * + * ```js + * import { platform } from 'node:process'; + * + * console.log(`This platform is ${platform}`); + * ``` + * + * The value `'android'` may also be returned if the Node.js is built on the + * Android operating system. However, Android support in Node.js [is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.1.16 + */ + readonly platform: Platform; + /** + * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at + * runtime, `require.main` may still refer to the original main module in + * modules that were required before the change occurred. Generally, it's + * safe to assume that the two refer to the same module. + * + * As with `require.main`, `process.mainModule` will be `undefined` if there + * is no entry script. + * @since v0.1.17 + * @deprecated Since v14.0.0 - Use `main` instead. + */ + mainModule?: Module | undefined; + memoryUsage: MemoryUsageFn; + /** + * Gets the amount of memory available to the process (in bytes) based on + * limits imposed by the OS. If there is no such constraint, or the constraint + * is unknown, `0` is returned. + * + * See [`uv_get_constrained_memory`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory) for more + * information. + * @since v19.6.0, v18.15.0 + */ + constrainedMemory(): number; + /** + * Gets the amount of free memory that is still available to the process (in bytes). + * See [`uv_get_available_memory`](https://nodejs.org/docs/latest-v24.x/api/process.html#processavailablememory) for more information. + * @since v20.13.0 + */ + availableMemory(): number; + /** + * The `process.cpuUsage()` method returns the user and system CPU time usage of + * the current process, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). These values measure time + * spent in user and system code respectively, and may end up being greater than + * actual elapsed time if multiple CPU cores are performing work for this process. + * + * The result of a previous call to `process.cpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * + * ```js + * import { cpuUsage } from 'node:process'; + * + * const startUsage = cpuUsage(); + * // { user: 38579, system: 6986 } + * + * // spin the CPU for 500 milliseconds + * const now = Date.now(); + * while (Date.now() - now < 500); + * + * console.log(cpuUsage(startUsage)); + * // { user: 514883, system: 11226 } + * ``` + * @since v6.1.0 + * @param previousValue A previous return value from calling `process.cpuUsage()` + */ + cpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * `process.nextTick()` adds `callback` to the "next tick queue". This queue is + * fully drained after the current operation on the JavaScript stack runs to + * completion and before the event loop is allowed to continue. It's possible to + * create an infinite loop if one were to recursively call `process.nextTick()`. + * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. + * + * ```js + * import { nextTick } from 'node:process'; + * + * console.log('start'); + * nextTick(() => { + * console.log('nextTick callback'); + * }); + * console.log('scheduled'); + * // Output: + * // start + * // scheduled + * // nextTick callback + * ``` + * + * This is important when developing APIs in order to give users the opportunity + * to assign event handlers _after_ an object has been constructed but before any + * I/O has occurred: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function MyThing(options) { + * this.setupOptions(options); + * + * nextTick(() => { + * this.startDoingStuff(); + * }); + * } + * + * const thing = new MyThing(); + * thing.getReadyForStuff(); + * + * // thing.startDoingStuff() gets called now, not before. + * ``` + * + * It is very important for APIs to be either 100% synchronous or 100% + * asynchronous. Consider this example: + * + * ```js + * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! + * function maybeSync(arg, cb) { + * if (arg) { + * cb(); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * + * This API is hazardous because in the following case: + * + * ```js + * const maybeTrue = Math.random() > 0.5; + * + * maybeSync(maybeTrue, () => { + * foo(); + * }); + * + * bar(); + * ``` + * + * It is not clear whether `foo()` or `bar()` will be called first. + * + * The following approach is much better: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function definitelyAsync(arg, cb) { + * if (arg) { + * nextTick(cb); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * @since v0.1.26 + * @param args Additional arguments to pass when invoking the `callback` + */ + nextTick(callback: Function, ...args: any[]): void; + /** + * This API is available through the [--permission](https://nodejs.org/api/cli.html#--permission) flag. + * + * `process.permission` is an object whose methods are used to manage permissions for the current process. + * Additional documentation is available in the [Permission Model](https://nodejs.org/api/permissions.html#permission-model). + * @since v20.0.0 + */ + permission: ProcessPermission; + /** + * The `process.release` property returns an `Object` containing metadata related + * to the current release, including URLs for the source tarball and headers-only + * tarball. + * + * `process.release` contains the following properties: + * + * ```js + * { + * name: 'node', + * lts: 'Hydrogen', + * sourceUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib' + * } + * ``` + * + * In custom builds from non-release versions of the source tree, only the `name` property may be present. The additional properties should not be + * relied upon to exist. + * @since v3.0.0 + */ + readonly release: ProcessRelease; + readonly features: ProcessFeatures; + /** + * `process.umask()` returns the Node.js process's file mode creation mask. Child + * processes inherit the mask from the parent process. + * @since v0.1.19 + * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential + * security vulnerability. There is no safe, cross-platform alternative API. + */ + umask(): number; + /** + * Can only be set if not in worker thread. + */ + umask(mask: string | number): number; + /** + * The `process.uptime()` method returns the number of seconds the current Node.js + * process has been running. + * + * The return value includes fractions of a second. Use `Math.floor()` to get whole + * seconds. + * @since v0.5.0 + */ + uptime(): number; + hrtime: HRTime; + /** + * If the Node.js process was spawned with an IPC channel, the process.channel property is a reference to the IPC channel. + * If no IPC channel exists, this property is undefined. + * @since v7.1.0 + */ + channel?: { + /** + * This method makes the IPC channel keep the event loop of the process running if .unref() has been called before. + * @since v7.1.0 + */ + ref(): void; + /** + * This method makes the IPC channel not keep the event loop of the process running, and lets it finish even while the channel is open. + * @since v7.1.0 + */ + unref(): void; + }; + /** + * If Node.js is spawned with an IPC channel, the `process.send()` method can be + * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. + * + * If Node.js was not spawned with an IPC channel, `process.send` will be `undefined`. + * + * The message goes through serialization and parsing. The resulting message might + * not be the same as what is originally sent. + * @since v0.5.9 + * @param options used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send?( + message: any, + sendHandle?: any, + options?: { + keepOpen?: boolean | undefined; + }, + callback?: (error: Error | null) => void, + ): boolean; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the + * IPC channel to the parent process, allowing the child process to exit gracefully + * once there are no other connections keeping it alive. + * + * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. + * + * If the Node.js process was not spawned with an IPC channel, `process.disconnect()` will be `undefined`. + * @since v0.7.2 + */ + disconnect(): void; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return `true` so long as the IPC + * channel is connected and will return `false` after `process.disconnect()` is called. + * + * Once `process.connected` is `false`, it is no longer possible to send messages + * over the IPC channel using `process.send()`. + * @since v0.7.2 + */ + connected: boolean; + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. + * + * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides `Set.prototype.has` to recognize several different possible flag + * representations. `process.allowedNodeEnvironmentFlags.has()` will + * return `true` in the following cases: + * + * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g., `inspect-brk` for `--inspect-brk`, or `r` for `-r`. + * * Flags passed through to V8 (as listed in `--v8-options`) may replace + * one or more _non-leading_ dashes for an underscore, or vice-versa; + * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, + * etc. + * * Flags may contain one or more equals (`=`) characters; all + * characters after and including the first equals will be ignored; + * e.g., `--stack-trace-limit=100`. + * * Flags _must_ be allowable within `NODE_OPTIONS`. + * + * When iterating over `process.allowedNodeEnvironmentFlags`, flags will + * appear only _once_; each will begin with one or more dashes. Flags + * passed through to V8 will contain underscores instead of non-leading + * dashes: + * + * ```js + * import { allowedNodeEnvironmentFlags } from 'node:process'; + * + * allowedNodeEnvironmentFlags.forEach((flag) => { + * // -r + * // --inspect-brk + * // --abort_on_uncaught_exception + * // ... + * }); + * ``` + * + * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail + * silently. + * + * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will + * contain what _would have_ been allowable. + * @since v10.10.0 + */ + allowedNodeEnvironmentFlags: ReadonlySet; + /** + * `process.report` is an object whose methods are used to generate diagnostic reports for the current process. + * Additional documentation is available in the [report documentation](https://nodejs.org/docs/latest-v24.x/api/report.html). + * @since v11.8.0 + */ + report: ProcessReport; + /** + * ```js + * import { resourceUsage } from 'node:process'; + * + * console.log(resourceUsage()); + * /* + * Will output: + * { + * userCPUTime: 82872, + * systemCPUTime: 4143, + * maxRSS: 33164, + * sharedMemorySize: 0, + * unsharedDataSize: 0, + * unsharedStackSize: 0, + * minorPageFault: 2469, + * majorPageFault: 0, + * swappedOut: 0, + * fsRead: 0, + * fsWrite: 8, + * ipcSent: 0, + * ipcReceived: 0, + * signalsCount: 0, + * voluntaryContextSwitches: 79, + * involuntaryContextSwitches: 1 + * } + * + * ``` + * @since v12.6.0 + * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. + */ + resourceUsage(): ResourceUsage; + /** + * The initial value of `process.throwDeprecation` indicates whether the `--throw-deprecation` flag is set on the current Node.js process. `process.throwDeprecation` + * is mutable, so whether or not deprecation warnings result in errors may be altered at runtime. See the documentation for the 'warning' event and the emitWarning() + * method for more information. + * + * ```bash + * $ node --throw-deprecation -p "process.throwDeprecation" + * true + * $ node -p "process.throwDeprecation" + * undefined + * $ node + * > process.emitWarning('test', 'DeprecationWarning'); + * undefined + * > (node:26598) DeprecationWarning: test + * > process.throwDeprecation = true; + * true + * > process.emitWarning('test', 'DeprecationWarning'); + * Thrown: + * [DeprecationWarning: test] { name: 'DeprecationWarning' } + * ``` + * @since v0.9.12 + */ + throwDeprecation: boolean; + /** + * The `process.traceDeprecation` property indicates whether the `--trace-deprecation` flag is set on the current Node.js process. See the + * documentation for the `'warning' event` and the `emitWarning() method` for more information about this + * flag's behavior. + * @since v0.8.0 + */ + traceDeprecation: boolean; + /** + * An object is "refable" if it implements the Node.js "Refable protocol". + * Specifically, this means that the object implements the `Symbol.for('nodejs.ref')` + * and `Symbol.for('nodejs.unref')` methods. "Ref'd" objects will keep the Node.js + * event loop alive, while "unref'd" objects will not. Historically, this was + * implemented by using `ref()` and `unref()` methods directly on the objects. + * This pattern, however, is being deprecated in favor of the "Refable protocol" + * in order to better support Web Platform API types whose APIs cannot be modified + * to add `ref()` and `unref()` methods but still need to support that behavior. + * @since v22.14.0 + * @experimental + * @param maybeRefable An object that may be "refable". + */ + ref(maybeRefable: any): void; + /** + * An object is "unrefable" if it implements the Node.js "Refable protocol". + * Specifically, this means that the object implements the `Symbol.for('nodejs.ref')` + * and `Symbol.for('nodejs.unref')` methods. "Ref'd" objects will keep the Node.js + * event loop alive, while "unref'd" objects will not. Historically, this was + * implemented by using `ref()` and `unref()` methods directly on the objects. + * This pattern, however, is being deprecated in favor of the "Refable protocol" + * in order to better support Web Platform API types whose APIs cannot be modified + * to add `ref()` and `unref()` methods but still need to support that behavior. + * @since v22.14.0 + * @experimental + * @param maybeRefable An object that may be "unref'd". + */ + unref(maybeRefable: any): void; + /** + * Replaces the current process with a new process. + * + * This is achieved by using the `execve` POSIX function and therefore no memory or other + * resources from the current process are preserved, except for the standard input, + * standard output and standard error file descriptor. + * + * All other resources are discarded by the system when the processes are swapped, without triggering + * any exit or close events and without running any cleanup handler. + * + * This function will never return, unless an error occurred. + * + * This function is not available on Windows or IBM i. + * @since v22.15.0 + * @experimental + * @param file The name or path of the executable file to run. + * @param args List of string arguments. No argument can contain a null-byte (`\u0000`). + * @param env Environment key-value pairs. + * No key or value can contain a null-byte (`\u0000`). + * **Default:** `process.env`. + */ + execve?(file: string, args?: readonly string[], env?: ProcessEnv): never; + /* EventEmitter */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + addListener(event: "worker", listener: WorkerListener): this; + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "uncaughtExceptionMonitor", error: Error): boolean; + emit(event: "unhandledRejection", reason: unknown, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: unknown, sendHandle: unknown): this; + emit(event: Signals, signal?: Signals): boolean; + emit( + event: "multipleResolves", + type: MultipleResolveType, + promise: Promise, + value: unknown, + ): this; + emit(event: "worker", listener: WorkerListener): this; + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + on(event: "worker", listener: WorkerListener): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + once(event: "worker", listener: WorkerListener): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependListener(event: "worker", listener: WorkerListener): this; + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependOnceListener(event: "worker", listener: WorkerListener): this; + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + listeners(event: "worker"): WorkerListener[]; + } + } + } + export = process; +} +declare module "node:process" { + import process = require("process"); + export = process; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/punycode.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/punycode.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7ac26c8261b1903fbe7bf88e9209a14ef0138fe9 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/punycode.d.ts @@ -0,0 +1,117 @@ +/** + * **The version of the punycode module bundled in Node.js is being deprecated. **In a future major version of Node.js this module will be removed. Users + * currently depending on the `punycode` module should switch to using the + * userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL + * encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. + * + * The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It + * can be accessed using: + * + * ```js + * import punycode from 'node:punycode'; + * ``` + * + * [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is + * primarily intended for use in Internationalized Domain Names. Because host + * names in URLs are limited to ASCII characters only, Domain Names that contain + * non-ASCII characters must be converted into ASCII using the Punycode scheme. + * For instance, the Japanese character that translates into the English word, `'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent + * to `'example.com'`) is represented by Punycode as the ASCII string `'xn--fsq.com'`. + * + * The `punycode` module provides a simple implementation of the Punycode standard. + * + * The `punycode` module is a third-party dependency used by Node.js and + * made available to developers as a convenience. Fixes or other modifications to + * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. + * @deprecated Since v7.0.0 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/punycode.js) + */ +declare module "punycode" { + /** + * The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only + * characters to the equivalent string of Unicode codepoints. + * + * ```js + * punycode.decode('maana-pta'); // 'mañana' + * punycode.decode('--dqo34k'); // '☃-⌘' + * ``` + * @since v0.5.1 + */ + function decode(string: string): string; + /** + * The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. + * + * ```js + * punycode.encode('mañana'); // 'maana-pta' + * punycode.encode('☃-⌘'); // '--dqo34k' + * ``` + * @since v0.5.1 + */ + function encode(string: string): string; + /** + * The `punycode.toUnicode()` method converts a string representing a domain name + * containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be + * converted. + * + * ```js + * // decode domain names + * punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' + * punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' + * punycode.toUnicode('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toUnicode(domain: string): string; + /** + * The `punycode.toASCII()` method converts a Unicode string representing an + * Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the + * domain name will be converted. Calling `punycode.toASCII()` on a string that + * already only contains ASCII characters will have no effect. + * + * ```js + * // encode domain names + * punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' + * punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' + * punycode.toASCII('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toASCII(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const ucs2: ucs2; + interface ucs2 { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + decode(string: string): number[]; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + encode(codePoints: readonly number[]): string; + } + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const version: string; +} +declare module "node:punycode" { + export * from "punycode"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/querystring.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/querystring.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..aaeefe8d3d38c80055964d56a9a3d5fc27e64c22 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,152 @@ +/** + * The `node:querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * import querystring from 'node:querystring'; + * ``` + * + * `querystring` is more performant than `URLSearchParams` but is not a + * standardized API. Use `URLSearchParams` when performance is not critical or + * when compatibility with browser code is desirable. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/querystring.js) + */ +declare module "querystring" { + interface StringifyOptions { + /** + * The function to use when converting URL-unsafe characters to percent-encoding in the query string. + * @default `querystring.escape()` + */ + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + /** + * Specifies the maximum number of keys to parse. Specify `0` to remove key counting limitations. + * @default 1000 + */ + maxKeys?: number | undefined; + /** + * The function to use when decoding percent-encoded characters in the query string. + * @default `querystring.unescape()` + */ + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends + NodeJS.Dict< + | string + | number + | boolean + | bigint + | ReadonlyArray + | null + > + {} + /** + * The `querystring.stringify()` method produces a URL query string from a + * given `obj` by iterating through the object's "own properties". + * + * It serializes the following types of values passed in `obj`: [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | + * [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to + * empty strings. + * + * ```js + * querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); + * // Returns 'foo=bar&baz=qux&baz=quux&corge=' + * + * querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); + * // Returns 'foo:bar;baz:qux' + * ``` + * + * By default, characters requiring percent-encoding within the query string will + * be encoded as UTF-8\. If an alternative encoding is required, then an alternative `encodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkEncodeURIComponent function already exists, + * + * querystring.stringify({ w: '中文', foo: 'bar' }, null, null, + * { encodeURIComponent: gbkEncodeURIComponent }); + * ``` + * @since v0.1.25 + * @param obj The object to serialize into a URL query string + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; + /** + * The `querystring.parse()` method parses a URL query string (`str`) into a + * collection of key and value pairs. + * + * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: + * + * ```json + * { + * "foo": "bar", + * "abc": ["xyz", "123"] + * } + * ``` + * + * The object returned by the `querystring.parse()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * By default, percent-encoded characters within the query string will be assumed + * to use UTF-8 encoding. If an alternative character encoding is used, then an + * alternative `decodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkDecodeURIComponent function already exists... + * + * querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, + * { decodeURIComponent: gbkDecodeURIComponent }); + * ``` + * @since v0.1.25 + * @param str The URL query string to parse + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] The substring used to delimit keys and values in the query string. + */ + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + /** + * The `querystring.escape()` method performs URL percent-encoding on the given `str` in a manner that is optimized for the specific requirements of URL + * query strings. + * + * The `querystring.escape()` method is used by `querystring.stringify()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement percent-encoding implementation if + * necessary by assigning `querystring.escape` to an alternative function. + * @since v0.1.25 + */ + function escape(str: string): string; + /** + * The `querystring.unescape()` method performs decoding of URL percent-encoded + * characters on the given `str`. + * + * The `querystring.unescape()` method is used by `querystring.parse()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement decoding implementation if + * necessary by assigning `querystring.unescape` to an alternative function. + * + * By default, the `querystring.unescape()` method will attempt to use the + * JavaScript built-in `decodeURIComponent()` method to decode. If that fails, + * a safer equivalent that does not throw on malformed URLs will be used. + * @since v0.1.25 + */ + function unescape(str: string): string; +} +declare module "node:querystring" { + export * from "querystring"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/readline.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/readline.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..519b4a46be1fa2047e26a8b13fd711bab720ce13 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/readline.d.ts @@ -0,0 +1,594 @@ +/** + * The `node:readline` module provides an interface for reading data from a [Readable](https://nodejs.org/docs/latest-v24.x/api/stream.html#readable-streams) stream + * (such as [`process.stdin`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdin)) one line at a time. + * + * To use the promise-based APIs: + * + * ```js + * import * as readline from 'node:readline/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as readline from 'node:readline'; + * ``` + * + * The following simple example illustrates the basic use of the `node:readline` module. + * + * ```js + * import * as readline from 'node:readline/promises'; + * import { stdin as input, stdout as output } from 'node:process'; + * + * const rl = readline.createInterface({ input, output }); + * + * const answer = await rl.question('What do you think of Node.js? '); + * + * console.log(`Thank you for your valuable feedback: ${answer}`); + * + * rl.close(); + * ``` + * + * Once this code is invoked, the Node.js application will not terminate until the `readline.Interface` is closed because the interface waits for data to be + * received on the `input` stream. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/readline.js) + */ +declare module "readline" { + import { Abortable, EventEmitter } from "node:events"; + import * as promises from "node:readline/promises"; + export { promises }; + export interface Key { + sequence?: string | undefined; + name?: string | undefined; + ctrl?: boolean | undefined; + meta?: boolean | undefined; + shift?: boolean | undefined; + } + /** + * Instances of the `readline.Interface` class are constructed using the `readline.createInterface()` method. Every instance is associated with a + * single `input` [Readable](https://nodejs.org/docs/latest-v24.x/api/stream.html#readable-streams) stream and a single `output` [Writable](https://nodejs.org/docs/latest-v24.x/api/stream.html#writable-streams) stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v0.1.104 + */ + export class Interface extends EventEmitter implements Disposable { + readonly terminal: boolean; + /** + * The current input data being processed by node. + * + * This can be used when collecting input from a TTY stream to retrieve the + * current value that has been processed thus far, prior to the `line` event + * being emitted. Once the `line` event has been emitted, this property will + * be an empty string. + * + * Be aware that modifying the value during the instance runtime may have + * unintended consequences if `rl.cursor` is not also controlled. + * + * **If not using a TTY stream for input, use the `'line'` event.** + * + * One possible use case would be as follows: + * + * ```js + * const values = ['lorem ipsum', 'dolor sit amet']; + * const rl = readline.createInterface(process.stdin); + * const showResults = debounce(() => { + * console.log( + * '\n', + * values.filter((val) => val.startsWith(rl.line)).join(' '), + * ); + * }, 300); + * process.stdin.on('keypress', (c, k) => { + * showResults(); + * }); + * ``` + * @since v0.1.98 + */ + readonly line: string; + /** + * The cursor position relative to `rl.line`. + * + * This will track where the current cursor lands in the input string, when + * reading input from a TTY stream. The position of cursor determines the + * portion of the input string that will be modified as input is processed, + * as well as the column where the terminal caret will be rendered. + * @since v0.1.98 + */ + readonly cursor: number; + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor(options: ReadLineOptions); + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.0, v14.17.0 + * @return the current prompt string + */ + getPrompt(): string; + /** + * The `rl.setPrompt()` method sets the prompt that will be written to `output` whenever `rl.prompt()` is called. + * @since v0.1.98 + */ + setPrompt(prompt: string): void; + /** + * The `rl.prompt()` method writes the `Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new + * location at which to provide input. + * + * When called, `rl.prompt()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the prompt is not written. + * @since v0.1.98 + * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. + */ + prompt(preserveCursor?: boolean): void; + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. + * + * The `callback` function passed to `rl.question()` does not follow the typical + * pattern of accepting an `Error` object or `null` as the first argument. + * The `callback` is called with the provided answer as the only argument. + * + * An error will be thrown if calling `rl.question()` after `rl.close()`. + * + * Example usage: + * + * ```js + * rl.question('What is your favorite food? ', (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * ``` + * + * Using an `AbortController` to cancel a question. + * + * ```js + * const ac = new AbortController(); + * const signal = ac.signal; + * + * rl.question('What is your favorite food? ', { signal }, (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * setTimeout(() => ac.abort(), 10000); + * ``` + * @since v0.3.3 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @param callback A callback function that is invoked with the user's input in response to the `query`. + */ + question(query: string, callback: (answer: string) => void): void; + question(query: string, options: Abortable, callback: (answer: string) => void): void; + /** + * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed + * later if necessary. + * + * Calling `rl.pause()` does not immediately pause other events (including `'line'`) from being emitted by the `Interface` instance. + * @since v0.3.4 + */ + pause(): this; + /** + * The `rl.resume()` method resumes the `input` stream if it has been paused. + * @since v0.3.4 + */ + resume(): this; + /** + * The `rl.close()` method closes the `Interface` instance and + * relinquishes control over the `input` and `output` streams. When called, + * the `'close'` event will be emitted. + * + * Calling `rl.close()` does not immediately stop other events (including `'line'`) + * from being emitted by the `Interface` instance. + * @since v0.1.98 + */ + close(): void; + /** + * Alias for `rl.close()`. + * @since v22.15.0 + */ + [Symbol.dispose](): void; + /** + * The `rl.write()` method will write either `data` or a key sequence identified + * by `key` to the `output`. The `key` argument is supported only if `output` is + * a `TTY` text terminal. See `TTY keybindings` for a list of key + * combinations. + * + * If `key` is specified, `data` is ignored. + * + * When called, `rl.write()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `data` and `key` are not written. + * + * ```js + * rl.write('Delete this!'); + * // Simulate Ctrl+U to delete the line written previously + * rl.write(null, { ctrl: true, name: 'u' }); + * ``` + * + * The `rl.write()` method will write the data to the `readline` `Interface`'s `input` _as if it were provided by the user_. + * @since v0.1.98 + */ + write(data: string | Buffer, key?: Key): void; + write(data: undefined | null | string | Buffer, key: Key): void; + /** + * Returns the real position of the cursor in relation to the input + * prompt + string. Long input (wrapping) strings, as well as multiple + * line prompts are included in the calculations. + * @since v13.5.0, v12.16.0 + */ + getCursorPos(): CursorPos; + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + * 8. history + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "history", listener: (history: string[]) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "history", history: string[]): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "history", listener: (history: string[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "history", listener: (history: string[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "history", listener: (history: string[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "history", listener: (history: string[]) => void): this; + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + } + export type ReadLine = Interface; // type forwarded for backwards compatibility + export type Completer = (line: string) => CompleterResult; + export type AsyncCompleter = ( + line: string, + callback: (err?: null | Error, result?: CompleterResult) => void, + ) => void; + export type CompleterResult = [string[], string]; + export interface ReadLineOptions { + /** + * The [`Readable`](https://nodejs.org/docs/latest-v24.x/api/stream.html#readable-streams) stream to listen to + */ + input: NodeJS.ReadableStream; + /** + * The [`Writable`](https://nodejs.org/docs/latest-v24.x/api/stream.html#writable-streams) stream to write readline data to. + */ + output?: NodeJS.WritableStream | undefined; + /** + * An optional function used for Tab autocompletion. + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * `true` if the `input` and `output` streams should be treated like a TTY, + * and have ANSI/VT100 escape codes written to it. + * Default: checking `isTTY` on the `output` stream upon instantiation. + */ + terminal?: boolean | undefined; + /** + * Initial list of history lines. + * This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, + * otherwise the history caching mechanism is not initialized at all. + * @default [] + */ + history?: string[] | undefined; + /** + * Maximum number of history lines retained. + * To disable the history set this value to `0`. + * This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, + * otherwise the history caching mechanism is not initialized at all. + * @default 30 + */ + historySize?: number | undefined; + /** + * If `true`, when a new input line added to the history list duplicates an older one, + * this removes the older line from the list. + * @default false + */ + removeHistoryDuplicates?: boolean | undefined; + /** + * The prompt string to use. + * @default "> " + */ + prompt?: string | undefined; + /** + * If the delay between `\r` and `\n` exceeds `crlfDelay` milliseconds, + * both `\r` and `\n` will be treated as separate end-of-line input. + * `crlfDelay` will be coerced to a number no less than `100`. + * It can be set to `Infinity`, in which case + * `\r` followed by `\n` will always be considered a single newline + * (which may be reasonable for [reading files](https://nodejs.org/docs/latest-v24.x/api/readline.html#example-read-file-stream-line-by-line) with `\r\n` line delimiter). + * @default 100 + */ + crlfDelay?: number | undefined; + /** + * The duration `readline` will wait for a character + * (when reading an ambiguous key sequence in milliseconds + * one that can both form a complete key sequence using the input read so far + * and can take additional input to complete a longer key sequence). + * @default 500 + */ + escapeCodeTimeout?: number | undefined; + /** + * The number of spaces a tab is equal to (minimum 1). + * @default 8 + */ + tabSize?: number | undefined; + /** + * Allows closing the interface using an AbortSignal. + * Aborting the signal will internally call `close` on the interface. + */ + signal?: AbortSignal | undefined; + } + /** + * The `readline.createInterface()` method creates a new `readline.Interface` instance. + * + * ```js + * import readline from 'node:readline'; + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readline.Interface` instance is created, the most common case is to + * listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * + * When creating a `readline.Interface` using `stdin` as input, the program + * will not terminate until it receives an [EOF character](https://en.wikipedia.org/wiki/End-of-file#EOF_character). To exit without + * waiting for user input, call `process.stdin.unref()`. + * @since v0.1.98 + */ + export function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + export function createInterface(options: ReadLineOptions): Interface; + /** + * The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input. + * + * Optionally, `interface` specifies a `readline.Interface` instance for which + * autocompletion is disabled when copy-pasted input is detected. + * + * If the `stream` is a `TTY`, then it must be in raw mode. + * + * This is automatically called by any readline instance on its `input` if the `input` is a terminal. Closing the `readline` instance does not stop + * the `input` from emitting `'keypress'` events. + * + * ```js + * readline.emitKeypressEvents(process.stdin); + * if (process.stdin.isTTY) + * process.stdin.setRawMode(true); + * ``` + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * import readline from 'node:readline'; + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ', + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * import fs from 'node:fs'; + * import readline from 'node:readline'; + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity, + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * import fs from 'node:fs'; + * import readline from 'node:readline'; + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await` flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * import { once } from 'node:events'; + * import { createReadStream } from 'node:fs'; + * import { createInterface } from 'node:readline'; + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + */ + export function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + export type Direction = -1 | 0 | 1; + export interface CursorPos { + rows: number; + cols: number; + } + /** + * The `readline.clearLine()` method clears current line of given [TTY](https://nodejs.org/docs/latest-v24.x/api/tty.html) stream + * in a specified direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; + /** + * The `readline.clearScreenDown()` method clears the given [TTY](https://nodejs.org/docs/latest-v24.x/api/tty.html) stream from + * the current position of the cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; + /** + * The `readline.cursorTo()` method moves cursor to the specified position in a + * given [TTY](https://nodejs.org/docs/latest-v24.x/api/tty.html) `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; + /** + * The `readline.moveCursor()` method moves the cursor _relative_ to its current + * position in a given [TTY](https://nodejs.org/docs/latest-v24.x/api/tty.html) `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} +declare module "node:readline" { + export * from "readline"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/readline/promises.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/readline/promises.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c0ebf4ba58ff122abdac2447259ccc0d0afcb59f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/readline/promises.d.ts @@ -0,0 +1,161 @@ +/** + * @since v17.0.0 + */ +declare module "readline/promises" { + import { Abortable } from "node:events"; + import { + CompleterResult, + Direction, + Interface as _Interface, + ReadLineOptions as _ReadLineOptions, + } from "node:readline"; + /** + * Instances of the `readlinePromises.Interface` class are constructed using the `readlinePromises.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v17.0.0 + */ + class Interface extends _Interface { + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. + * + * If the question is called after `rl.close()`, it returns a rejected promise. + * + * Example usage: + * + * ```js + * const answer = await rl.question('What is your favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * + * Using an `AbortSignal` to cancel a question. + * + * ```js + * const signal = AbortSignal.timeout(10_000); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * const answer = await rl.question('What is your favorite food? ', { signal }); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * @since v17.0.0 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @return A promise that is fulfilled with the user's input in response to the `query`. + */ + question(query: string): Promise; + question(query: string, options: Abortable): Promise; + } + /** + * @since v17.0.0 + */ + class Readline { + /** + * @param stream A TTY stream. + */ + constructor( + stream: NodeJS.WritableStream, + options?: { + autoCommit?: boolean; + }, + ); + /** + * The `rl.clearLine()` method adds to the internal list of pending action an + * action that clears current line of the associated `stream` in a specified + * direction identified by `dir`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearLine(dir: Direction): this; + /** + * The `rl.clearScreenDown()` method adds to the internal list of pending action an + * action that clears the associated stream from the current position of the + * cursor down. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearScreenDown(): this; + /** + * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. + * @since v17.0.0 + */ + commit(): Promise; + /** + * The `rl.cursorTo()` method adds to the internal list of pending action an action + * that moves cursor to the specified position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + cursorTo(x: number, y?: number): this; + /** + * The `rl.moveCursor()` method adds to the internal list of pending action an + * action that moves the cursor _relative_ to its current position in the + * associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + moveCursor(dx: number, dy: number): this; + /** + * The `rl.rollback` methods clears the internal list of pending actions without + * sending it to the associated `stream`. + * @since v17.0.0 + * @return this + */ + rollback(): this; + } + type Completer = (line: string) => CompleterResult | Promise; + interface ReadLineOptions extends Omit<_ReadLineOptions, "completer"> { + /** + * An optional function used for Tab autocompletion. + */ + completer?: Completer | undefined; + } + /** + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. + * + * ```js + * import readlinePromises from 'node:readline/promises'; + * const rl = readlinePromises.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readlinePromises.Interface` instance is created, the most common case + * is to listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * @since v17.0.0 + */ + function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer, + terminal?: boolean, + ): Interface; + function createInterface(options: ReadLineOptions): Interface; +} +declare module "node:readline/promises" { + export * from "readline/promises"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/repl.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/repl.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..60dc94ad78afa2da51edbbaa3b55a98567100b82 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/repl.d.ts @@ -0,0 +1,438 @@ +/** + * The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation + * that is available both as a standalone program or includible in other + * applications. It can be accessed using: + * + * ```js + * import repl from 'node:repl'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/repl.js) + */ +declare module "repl" { + import { AsyncCompleter, Completer, Interface } from "node:readline"; + import { Context } from "node:vm"; + import { InspectOptions } from "node:util"; + interface ReplOptions { + /** + * The input prompt to display. + * @default "> " + */ + prompt?: string | undefined; + /** + * The `Readable` stream from which REPL input will be read. + * @default process.stdin + */ + input?: NodeJS.ReadableStream | undefined; + /** + * The `Writable` stream to which REPL output will be written. + * @default process.stdout + */ + output?: NodeJS.WritableStream | undefined; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean | undefined; + /** + * The function to be used when evaluating each given line of input. + * **Default:** an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. See the [custom evaluation functions](https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#custom-evaluation-functions) + * section for more details. + */ + eval?: REPLEval | undefined; + /** + * Defines if the repl prints output previews or not. + * @default `true` Always `false` in case `terminal` is falsy. + */ + preview?: boolean | undefined; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * @default the REPL instance's `terminal` value + */ + useColors?: boolean | undefined; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * @default false + */ + useGlobal?: boolean | undefined; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * @default false + */ + ignoreUndefined?: boolean | undefined; + /** + * The function to invoke to format the output of each command before writing to `output`. + * @default a wrapper for `util.inspect` + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter | undefined; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * @default false + */ + breakEvalOnSigint?: boolean | undefined; + } + type REPLEval = ( + this: REPLServer, + evalCmd: string, + context: Context, + file: string, + cb: (err: Error | null, result: any) => void, + ) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { + options: InspectOptions; + }; + type REPLCommandAction = (this: REPLServer, text: string) => void; + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string | undefined; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + interface REPLServerSetupHistoryOptions { + filePath?: string | undefined; + size?: number | undefined; + removeHistoryDuplicates?: boolean | undefined; + onHistoryFileLoaded?: ((err: Error | null, repl: REPLServer) => void) | undefined; + } + /** + * Instances of `repl.REPLServer` are created using the {@link start} method + * or directly using the JavaScript `new` keyword. + * + * ```js + * import repl from 'node:repl'; + * + * const options = { useColors: true }; + * + * const firstInstance = repl.start(options); + * const secondInstance = new repl.REPLServer(options); + * ``` + * @since v0.1.91 + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * @deprecated since v14.3.0 - Use `input` instead. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * @deprecated since v14.3.0 - Use `output` instead. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly input: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly output: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: NodeJS.ReadOnlyDict; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + /** + * The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands + * to the REPL instance. Such commands are invoked by typing a `.` followed by the `keyword`. The `cmd` is either a `Function` or an `Object` with the following + * properties: + * + * The following example shows two new commands added to the REPL instance: + * + * ```js + * import repl from 'node:repl'; + * + * const replServer = repl.start({ prompt: '> ' }); + * replServer.defineCommand('sayhello', { + * help: 'Say hello', + * action(name) { + * this.clearBufferedCommand(); + * console.log(`Hello, ${name}!`); + * this.displayPrompt(); + * }, + * }); + * replServer.defineCommand('saybye', function saybye() { + * console.log('Goodbye!'); + * this.close(); + * }); + * ``` + * + * The new commands can then be used from within the REPL instance: + * + * ```console + * > .sayhello Node.js User + * Hello, Node.js User! + * > .saybye + * Goodbye! + * ``` + * @since v0.3.0 + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * The `replServer.displayPrompt()` method readies the REPL instance for input + * from the user, printing the configured `prompt` to a new line in the `output` and resuming the `input` to accept new input. + * + * When multi-line input is being entered, a pipe `'|'` is printed rather than the + * 'prompt'. + * + * When `preserveCursor` is `true`, the cursor placement will not be reset to `0`. + * + * The `replServer.displayPrompt` method is primarily intended to be called from + * within the action function for commands registered using the `replServer.defineCommand()` method. + * @since v0.1.91 + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * The `replServer.clearBufferedCommand()` method clears any command that has been + * buffered but not yet executed. This method is primarily intended to be + * called from within the action function for commands registered using the `replServer.defineCommand()` method. + * @since v9.0.0 + */ + clearBufferedCommand(): void; + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command-line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @since v11.10.0 + * @param historyPath the path to the history file + * @param callback called when history writes are ready or upon error + */ + setupHistory(historyPath: string, callback: (err: Error | null, repl: this) => void): void; + setupHistory( + historyConfig?: REPLServerSetupHistoryOptions, + callback?: (err: Error | null, repl: this) => void, + ): void; + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: (context: Context) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: Context): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: (context: Context) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: (context: Context) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: (context: Context) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: (context: Context) => void): this; + } + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + const REPL_MODE_SLOPPY: unique symbol; + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + const REPL_MODE_STRICT: unique symbol; + /** + * The `repl.start()` method creates and starts a {@link REPLServer} instance. + * + * If `options` is a string, then it specifies the input prompt: + * + * ```js + * import repl from 'node:repl'; + * + * // a Unix style prompt + * repl.start('$ '); + * ``` + * @since v0.1.91 + */ + function start(options?: string | ReplOptions): REPLServer; + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v24.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + constructor(err: Error); + } +} +declare module "node:repl" { + export * from "repl"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/sea.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/sea.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5119ede087d0b60b0733438fa885e906534b4169 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/sea.d.ts @@ -0,0 +1,153 @@ +/** + * This feature allows the distribution of a Node.js application conveniently to a + * system that does not have Node.js installed. + * + * Node.js supports the creation of [single executable applications](https://github.com/nodejs/single-executable) by allowing + * the injection of a blob prepared by Node.js, which can contain a bundled script, + * into the `node` binary. During start up, the program checks if anything has been + * injected. If the blob is found, it executes the script in the blob. Otherwise + * Node.js operates as it normally does. + * + * The single executable application feature currently only supports running a + * single embedded script using the `CommonJS` module system. + * + * Users can create a single executable application from their bundled script + * with the `node` binary itself and any tool which can inject resources into the + * binary. + * + * Here are the steps for creating a single executable application using one such + * tool, [postject](https://github.com/nodejs/postject): + * + * 1. Create a JavaScript file: + * ```bash + * echo 'console.log(`Hello, ${process.argv[2]}!`);' > hello.js + * ``` + * 2. Create a configuration file building a blob that can be injected into the + * single executable application (see `Generating single executable preparation blobs` for details): + * ```bash + * echo '{ "main": "hello.js", "output": "sea-prep.blob" }' > sea-config.json + * ``` + * 3. Generate the blob to be injected: + * ```bash + * node --experimental-sea-config sea-config.json + * ``` + * 4. Create a copy of the `node` executable and name it according to your needs: + * * On systems other than Windows: + * ```bash + * cp $(command -v node) hello + * ``` + * * On Windows: + * ```text + * node -e "require('fs').copyFileSync(process.execPath, 'hello.exe')" + * ``` + * The `.exe` extension is necessary. + * 5. Remove the signature of the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --remove-signature hello + * ``` + * * On Windows (optional): + * [signtool](https://learn.microsoft.com/en-us/windows/win32/seccrypto/signtool) can be used from the installed [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/). + * If this step is + * skipped, ignore any signature-related warning from postject. + * ```powershell + * signtool remove /s hello.exe + * ``` + * 6. Inject the blob into the copied binary by running `postject` with + * the following options: + * * `hello` / `hello.exe` \- The name of the copy of the `node` executable + * created in step 4. + * * `NODE_SEA_BLOB` \- The name of the resource / note / section in the binary + * where the contents of the blob will be stored. + * * `sea-prep.blob` \- The name of the blob created in step 1. + * * `--sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2` \- The [fuse](https://www.electronjs.org/docs/latest/tutorial/fuses) used by the Node.js project to detect if a file has been + * injected. + * * `--macho-segment-name NODE_SEA` (only needed on macOS) - The name of the + * segment in the binary where the contents of the blob will be + * stored. + * To summarize, here is the required command for each platform: + * * On Linux: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - PowerShell: + * ```powershell + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ` + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - Command Prompt: + * ```text + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ^ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On macOS: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 \ + * --macho-segment-name NODE_SEA + * ``` + * 7. Sign the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --sign - hello + * ``` + * * On Windows (optional): + * A certificate needs to be present for this to work. However, the unsigned + * binary would still be runnable. + * ```powershell + * signtool sign /fd SHA256 hello.exe + * ``` + * 8. Run the binary: + * * On systems other than Windows + * ```console + * $ ./hello world + * Hello, world! + * ``` + * * On Windows + * ```console + * $ .\hello.exe world + * Hello, world! + * ``` + * @since v19.7.0, v18.16.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v24.x/src/node_sea.cc) + */ +declare module "node:sea" { + type AssetKey = string; + /** + * @since v20.12.0 + * @return Whether this script is running inside a single-executable application. + */ + function isSea(): boolean; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAsset(key: AssetKey): ArrayBuffer; + function getAsset(key: AssetKey, encoding: string): string; + /** + * Similar to `sea.getAsset()`, but returns the result in a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob). + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAssetAsBlob(key: AssetKey, options?: { + type: string; + }): Blob; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * + * Unlike `sea.getRawAsset()` or `sea.getAssetAsBlob()`, this method does not + * return a copy. Instead, it returns the raw asset bundled inside the executable. + * + * For now, users should avoid writing to the returned array buffer. If the + * injected section is not marked as writable or not aligned properly, + * writes to the returned array buffer is likely to result in a crash. + * @since v20.12.0 + */ + function getRawAsset(key: AssetKey): ArrayBuffer; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/sqlite.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/sqlite.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9019832f5866f6745bf784dacf1dfbfb360c3794 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/sqlite.d.ts @@ -0,0 +1,687 @@ +/** + * The `node:sqlite` module facilitates working with SQLite databases. + * To access it: + * + * ```js + * import sqlite from 'node:sqlite'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import sqlite from 'sqlite'; + * ``` + * + * The following example shows the basic usage of the `node:sqlite` module to open + * an in-memory database, write data to the database, and then read the data back. + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * const database = new DatabaseSync(':memory:'); + * + * // Execute SQL statements from strings. + * database.exec(` + * CREATE TABLE data( + * key INTEGER PRIMARY KEY, + * value TEXT + * ) STRICT + * `); + * // Create a prepared statement to insert data into the database. + * const insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)'); + * // Execute the prepared statement with bound values. + * insert.run(1, 'hello'); + * insert.run(2, 'world'); + * // Create a prepared statement to read data from the database. + * const query = database.prepare('SELECT * FROM data ORDER BY key'); + * // Execute the prepared statement and log the result set. + * console.log(query.all()); + * // Prints: [ { key: 1, value: 'hello' }, { key: 2, value: 'world' } ] + * ``` + * @since v22.5.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/sqlite.js) + */ +declare module "node:sqlite" { + type SQLInputValue = null | number | bigint | string | NodeJS.ArrayBufferView; + type SQLOutputValue = null | number | bigint | string | Uint8Array; + /** @deprecated Use `SQLInputValue` or `SQLOutputValue` instead. */ + type SupportedValueType = SQLOutputValue; + interface DatabaseSyncOptions { + /** + * If `true`, the database is opened by the constructor. When + * this value is `false`, the database must be opened via the `open()` method. + * @since v22.5.0 + * @default true + */ + open?: boolean | undefined; + /** + * If `true`, foreign key constraints + * are enabled. This is recommended but can be disabled for compatibility with + * legacy database schemas. The enforcement of foreign key constraints can be + * enabled and disabled after opening the database using + * [`PRAGMA foreign_keys`](https://www.sqlite.org/pragma.html#pragma_foreign_keys). + * @since v22.10.0 + * @default true + */ + enableForeignKeyConstraints?: boolean | undefined; + /** + * If `true`, SQLite will accept + * [double-quoted string literals](https://www.sqlite.org/quirks.html#dblquote). + * This is not recommended but can be + * enabled for compatibility with legacy database schemas. + * @since v22.10.0 + * @default false + */ + enableDoubleQuotedStringLiterals?: boolean | undefined; + /** + * If `true`, the database is opened in read-only mode. + * If the database does not exist, opening it will fail. + * @since v22.12.0 + * @default false + */ + readOnly?: boolean | undefined; + /** + * If `true`, the `loadExtension` SQL function + * and the `loadExtension()` method are enabled. + * You can call `enableLoadExtension(false)` later to disable this feature. + * @since v22.13.0 + * @default false + */ + allowExtension?: boolean | undefined; + /** + * The [busy timeout](https://sqlite.org/c3ref/busy_timeout.html) in milliseconds. This is the maximum amount of + * time that SQLite will wait for a database lock to be released before + * returning an error. + * @since v24.0.0 + * @default 0 + */ + timeout?: number | undefined; + } + interface CreateSessionOptions { + /** + * A specific table to track changes for. By default, changes to all tables are tracked. + * @since v22.12.0 + */ + table?: string | undefined; + /** + * Name of the database to track. This is useful when multiple databases have been added using + * [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html). + * @since v22.12.0 + * @default 'main' + */ + db?: string | undefined; + } + interface ApplyChangesetOptions { + /** + * Skip changes that, when targeted table name is supplied to this function, return a truthy value. + * By default, all changes are attempted. + * @since v22.12.0 + */ + filter?: ((tableName: string) => boolean) | undefined; + /** + * A function that determines how to handle conflicts. The function receives one argument, + * which can be one of the following values: + * + * * `SQLITE_CHANGESET_DATA`: A `DELETE` or `UPDATE` change does not contain the expected "before" values. + * * `SQLITE_CHANGESET_NOTFOUND`: A row matching the primary key of the `DELETE` or `UPDATE` change does not exist. + * * `SQLITE_CHANGESET_CONFLICT`: An `INSERT` change results in a duplicate primary key. + * * `SQLITE_CHANGESET_FOREIGN_KEY`: Applying a change would result in a foreign key violation. + * * `SQLITE_CHANGESET_CONSTRAINT`: Applying a change results in a `UNIQUE`, `CHECK`, or `NOT NULL` constraint + * violation. + * + * The function should return one of the following values: + * + * * `SQLITE_CHANGESET_OMIT`: Omit conflicting changes. + * * `SQLITE_CHANGESET_REPLACE`: Replace existing values with conflicting changes (only valid with + `SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT` conflicts). + * * `SQLITE_CHANGESET_ABORT`: Abort on conflict and roll back the database. + * + * When an error is thrown in the conflict handler or when any other value is returned from the handler, + * applying the changeset is aborted and the database is rolled back. + * + * **Default**: A function that returns `SQLITE_CHANGESET_ABORT`. + * @since v22.12.0 + */ + onConflict?: ((conflictType: number) => number) | undefined; + } + interface FunctionOptions { + /** + * If `true`, the [`SQLITE_DETERMINISTIC`](https://www.sqlite.org/c3ref/c_deterministic.html) flag is + * set on the created function. + * @default false + */ + deterministic?: boolean | undefined; + /** + * If `true`, the [`SQLITE_DIRECTONLY`](https://www.sqlite.org/c3ref/c_directonly.html) flag is set on + * the created function. + * @default false + */ + directOnly?: boolean | undefined; + /** + * If `true`, integer arguments to `function` + * are converted to `BigInt`s. If `false`, integer arguments are passed as + * JavaScript numbers. + * @default false + */ + useBigIntArguments?: boolean | undefined; + /** + * If `true`, `function` may be invoked with any number of + * arguments (between zero and + * [`SQLITE_MAX_FUNCTION_ARG`](https://www.sqlite.org/limits.html#max_function_arg)). If `false`, + * `function` must be invoked with exactly `function.length` arguments. + * @default false + */ + varargs?: boolean | undefined; + } + interface AggregateOptions extends FunctionOptions { + /** + * The identity value for the aggregation function. This value is used when the aggregation + * function is initialized. When a `Function` is passed the identity will be its return value. + */ + start: T | (() => T); + /** + * The function to call for each row in the aggregation. The + * function receives the current state and the row value. The return value of + * this function should be the new state. + */ + step: (accumulator: T, ...args: SQLOutputValue[]) => T; + /** + * The function to call to get the result of the + * aggregation. The function receives the final state and should return the + * result of the aggregation. + */ + result?: ((accumulator: T) => SQLInputValue) | undefined; + /** + * When this function is provided, the `aggregate` method will work as a window function. + * The function receives the current state and the dropped row value. The return value of this function should be the + * new state. + */ + inverse?: ((accumulator: T, ...args: SQLOutputValue[]) => T) | undefined; + } + /** + * This class represents a single [connection](https://www.sqlite.org/c3ref/sqlite3.html) to a SQLite database. All APIs + * exposed by this class execute synchronously. + * @since v22.5.0 + */ + class DatabaseSync implements Disposable { + /** + * Constructs a new `DatabaseSync` instance. + * @param path The path of the database. + * A SQLite database can be stored in a file or completely [in memory](https://www.sqlite.org/inmemorydb.html). + * To use a file-backed database, the path should be a file path. + * To use an in-memory database, the path should be the special name `':memory:'`. + * @param options Configuration options for the database connection. + */ + constructor(path: string | Buffer | URL, options?: DatabaseSyncOptions); + /** + * Registers a new aggregate function with the SQLite database. This method is a wrapper around + * [`sqlite3_create_window_function()`](https://www.sqlite.org/c3ref/create_function.html). + * + * When used as a window function, the `result` function will be called multiple times. + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * + * const db = new DatabaseSync(':memory:'); + * db.exec(` + * CREATE TABLE t3(x, y); + * INSERT INTO t3 VALUES ('a', 4), + * ('b', 5), + * ('c', 3), + * ('d', 8), + * ('e', 1); + * `); + * + * db.aggregate('sumint', { + * start: 0, + * step: (acc, value) => acc + value, + * }); + * + * db.prepare('SELECT sumint(y) as total FROM t3').get(); // { total: 21 } + * ``` + * @since v24.0.0 + * @param name The name of the SQLite function to create. + * @param options Function configuration settings. + */ + aggregate(name: string, options: AggregateOptions): void; + aggregate(name: string, options: AggregateOptions): void; + /** + * Closes the database connection. An exception is thrown if the database is not + * open. This method is a wrapper around [`sqlite3_close_v2()`](https://www.sqlite.org/c3ref/close.html). + * @since v22.5.0 + */ + close(): void; + /** + * Loads a shared library into the database connection. This method is a wrapper + * around [`sqlite3_load_extension()`](https://www.sqlite.org/c3ref/load_extension.html). It is required to enable the + * `allowExtension` option when constructing the `DatabaseSync` instance. + * @since v22.13.0 + * @param path The path to the shared library to load. + */ + loadExtension(path: string): void; + /** + * Enables or disables the `loadExtension` SQL function, and the `loadExtension()` + * method. When `allowExtension` is `false` when constructing, you cannot enable + * loading extensions for security reasons. + * @since v22.13.0 + * @param allow Whether to allow loading extensions. + */ + enableLoadExtension(allow: boolean): void; + /** + * This method is a wrapper around [`sqlite3_db_filename()`](https://sqlite.org/c3ref/db_filename.html) + * @since v24.0.0 + * @param dbName Name of the database. This can be `'main'` (the default primary database) or any other + * database that has been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) **Default:** `'main'`. + * @returns The location of the database file. When using an in-memory database, + * this method returns null. + */ + location(dbName?: string): string | null; + /** + * This method allows one or more SQL statements to be executed without returning + * any results. This method is useful when executing SQL statements read from a + * file. This method is a wrapper around [`sqlite3_exec()`](https://www.sqlite.org/c3ref/exec.html). + * @since v22.5.0 + * @param sql A SQL string to execute. + */ + exec(sql: string): void; + /** + * This method is used to create SQLite user-defined functions. This method is a + * wrapper around [`sqlite3_create_function_v2()`](https://www.sqlite.org/c3ref/create_function.html). + * @since v22.13.0 + * @param name The name of the SQLite function to create. + * @param options Optional configuration settings for the function. + * @param func The JavaScript function to call when the SQLite + * function is invoked. The return value of this function should be a valid + * SQLite data type: see + * [Type conversion between JavaScript and SQLite](https://nodejs.org/docs/latest-v24.x/api/sqlite.html#type-conversion-between-javascript-and-sqlite). + * The result defaults to `NULL` if the return value is `undefined`. + */ + function( + name: string, + options: FunctionOptions, + func: (...args: SQLOutputValue[]) => SQLInputValue, + ): void; + function(name: string, func: (...args: SQLOutputValue[]) => SQLInputValue): void; + /** + * Whether the database is currently open or not. + * @since v22.15.0 + */ + readonly isOpen: boolean; + /** + * Whether the database is currently within a transaction. This method + * is a wrapper around [`sqlite3_get_autocommit()`](https://sqlite.org/c3ref/get_autocommit.html). + * @since v24.0.0 + */ + readonly isTransaction: boolean; + /** + * Opens the database specified in the `path` argument of the `DatabaseSync`constructor. This method should only be used when the database is not opened via + * the constructor. An exception is thrown if the database is already open. + * @since v22.5.0 + */ + open(): void; + /** + * Compiles a SQL statement into a [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This method is a wrapper + * around [`sqlite3_prepare_v2()`](https://www.sqlite.org/c3ref/prepare.html). + * @since v22.5.0 + * @param sql A SQL string to compile to a prepared statement. + * @return The prepared statement. + */ + prepare(sql: string): StatementSync; + /** + * Creates and attaches a session to the database. This method is a wrapper around + * [`sqlite3session_create()`](https://www.sqlite.org/session/sqlite3session_create.html) and + * [`sqlite3session_attach()`](https://www.sqlite.org/session/sqlite3session_attach.html). + * @param options The configuration options for the session. + * @returns A session handle. + * @since v22.12.0 + */ + createSession(options?: CreateSessionOptions): Session; + /** + * An exception is thrown if the database is not + * open. This method is a wrapper around + * [`sqlite3changeset_apply()`](https://www.sqlite.org/session/sqlite3changeset_apply.html). + * + * ```js + * const sourceDb = new DatabaseSync(':memory:'); + * const targetDb = new DatabaseSync(':memory:'); + * + * sourceDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)'); + * targetDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)'); + * + * const session = sourceDb.createSession(); + * + * const insert = sourceDb.prepare('INSERT INTO data (key, value) VALUES (?, ?)'); + * insert.run(1, 'hello'); + * insert.run(2, 'world'); + * + * const changeset = session.changeset(); + * targetDb.applyChangeset(changeset); + * // Now that the changeset has been applied, targetDb contains the same data as sourceDb. + * ``` + * @param changeset A binary changeset or patchset. + * @param options The configuration options for how the changes will be applied. + * @returns Whether the changeset was applied successfully without being aborted. + * @since v22.12.0 + */ + applyChangeset(changeset: Uint8Array, options?: ApplyChangesetOptions): boolean; + /** + * Closes the database connection. If the database connection is already closed + * then this is a no-op. + * @since v22.15.0 + */ + [Symbol.dispose](): void; + } + /** + * @since v22.12.0 + */ + interface Session { + /** + * Retrieves a changeset containing all changes since the changeset was created. Can be called multiple times. + * An exception is thrown if the database or the session is not open. This method is a wrapper around + * [`sqlite3session_changeset()`](https://www.sqlite.org/session/sqlite3session_changeset.html). + * @returns Binary changeset that can be applied to other databases. + * @since v22.12.0 + */ + changeset(): Uint8Array; + /** + * Similar to the method above, but generates a more compact patchset. See + * [Changesets and Patchsets](https://www.sqlite.org/sessionintro.html#changesets_and_patchsets) + * in the documentation of SQLite. An exception is thrown if the database or the session is not open. This method is a + * wrapper around + * [`sqlite3session_patchset()`](https://www.sqlite.org/session/sqlite3session_patchset.html). + * @returns Binary patchset that can be applied to other databases. + * @since v22.12.0 + */ + patchset(): Uint8Array; + /** + * Closes the session. An exception is thrown if the database or the session is not open. This method is a + * wrapper around + * [`sqlite3session_delete()`](https://www.sqlite.org/session/sqlite3session_delete.html). + */ + close(): void; + } + interface StatementColumnMetadata { + /** + * The unaliased name of the column in the origin + * table, or `null` if the column is the result of an expression or subquery. + * This property is the result of [`sqlite3_column_origin_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + column: string | null; + /** + * The unaliased name of the origin database, or + * `null` if the column is the result of an expression or subquery. This + * property is the result of [`sqlite3_column_database_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + database: string | null; + /** + * The name assigned to the column in the result set of a + * `SELECT` statement. This property is the result of + * [`sqlite3_column_name()`](https://www.sqlite.org/c3ref/column_name.html). + */ + name: string; + /** + * The unaliased name of the origin table, or `null` if + * the column is the result of an expression or subquery. This property is the + * result of [`sqlite3_column_table_name()`](https://www.sqlite.org/c3ref/column_database_name.html). + */ + table: string | null; + /** + * The declared data type of the column, or `null` if the + * column is the result of an expression or subquery. This property is the + * result of [`sqlite3_column_decltype()`](https://www.sqlite.org/c3ref/column_decltype.html). + */ + type: string | null; + } + interface StatementResultingChanges { + /** + * The number of rows modified, inserted, or deleted by the most recently completed `INSERT`, `UPDATE`, or `DELETE` statement. + * This field is either a number or a `BigInt` depending on the prepared statement's configuration. + * This property is the result of [`sqlite3_changes64()`](https://www.sqlite.org/c3ref/changes.html). + */ + changes: number | bigint; + /** + * The most recently inserted rowid. + * This field is either a number or a `BigInt` depending on the prepared statement's configuration. + * This property is the result of [`sqlite3_last_insert_rowid()`](https://www.sqlite.org/c3ref/last_insert_rowid.html). + */ + lastInsertRowid: number | bigint; + } + /** + * This class represents a single [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This class cannot be + * instantiated via its constructor. Instead, instances are created via the`database.prepare()` method. All APIs exposed by this class execute + * synchronously. + * + * A prepared statement is an efficient binary representation of the SQL used to + * create it. Prepared statements are parameterizable, and can be invoked multiple + * times with different bound values. Parameters also offer protection against [SQL injection](https://en.wikipedia.org/wiki/SQL_injection) attacks. For these reasons, prepared statements are + * preferred + * over hand-crafted SQL strings when handling user input. + * @since v22.5.0 + */ + class StatementSync { + private constructor(); + /** + * This method executes a prepared statement and returns all results as an array of + * objects. If the prepared statement does not return any results, this method + * returns an empty array. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using + * the values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @return An array of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of + * the row. + */ + all(...anonymousParameters: SQLInputValue[]): Record[]; + all( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): Record[]; + /** + * This method is used to retrieve information about the columns returned by the + * prepared statement. + * @since v23.11.0 + * @returns An array of objects. Each object corresponds to a column + * in the prepared statement, and contains the following properties: + */ + columns(): StatementColumnMetadata[]; + /** + * The source SQL text of the prepared statement with parameter + * placeholders replaced by the values that were used during the most recent + * execution of this prepared statement. This property is a wrapper around + * [`sqlite3_expanded_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html). + * @since v22.5.0 + */ + readonly expandedSQL: string; + /** + * This method executes a prepared statement and returns the first result as an + * object. If the prepared statement does not return any results, this method + * returns `undefined`. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the + * values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @return An object corresponding to the first row returned by executing the prepared statement. The keys and values of the object correspond to the column names and values of the row. If no + * rows were returned from the database then this method returns `undefined`. + */ + get(...anonymousParameters: SQLInputValue[]): Record | undefined; + get( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): Record | undefined; + /** + * This method executes a prepared statement and returns an iterator of + * objects. If the prepared statement does not return any results, this method + * returns an empty iterator. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using + * the values in `namedParameters` and `anonymousParameters`. + * @since v22.13.0 + * @param namedParameters An optional object used to bind named parameters. + * The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + * @returns An iterable iterator of objects. Each object corresponds to a row + * returned by executing the prepared statement. The keys and values of each + * object correspond to the column names and values of the row. + */ + iterate(...anonymousParameters: SQLInputValue[]): NodeJS.Iterator>; + iterate( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): NodeJS.Iterator>; + /** + * This method executes a prepared statement and returns an object summarizing the + * resulting changes. The prepared statement [parameters are bound](https://www.sqlite.org/c3ref/bind_blob.html) using the + * values in `namedParameters` and `anonymousParameters`. + * @since v22.5.0 + * @param namedParameters An optional object used to bind named parameters. The keys of this object are used to configure the mapping. + * @param anonymousParameters Zero or more values to bind to anonymous parameters. + */ + run(...anonymousParameters: SQLInputValue[]): StatementResultingChanges; + run( + namedParameters: Record, + ...anonymousParameters: SQLInputValue[] + ): StatementResultingChanges; + /** + * The names of SQLite parameters begin with a prefix character. By default,`node:sqlite` requires that this prefix character is present when binding + * parameters. However, with the exception of dollar sign character, these + * prefix characters also require extra quoting when used in object keys. + * + * To improve ergonomics, this method can be used to also allow bare named + * parameters, which do not require the prefix character in JavaScript code. There + * are several caveats to be aware of when enabling bare named parameters: + * + * * The prefix character is still required in SQL. + * * The prefix character is still allowed in JavaScript. In fact, prefixed names + * will have slightly better binding performance. + * * Using ambiguous named parameters, such as `$k` and `@k`, in the same prepared + * statement will result in an exception as it cannot be determined how to bind + * a bare name. + * @since v22.5.0 + * @param enabled Enables or disables support for binding named parameters without the prefix character. + */ + setAllowBareNamedParameters(enabled: boolean): void; + /** + * By default, if an unknown name is encountered while binding parameters, an + * exception is thrown. This method allows unknown named parameters to be ignored. + * @since v22.15.0 + * @param enabled Enables or disables support for unknown named parameters. + */ + setAllowUnknownNamedParameters(enabled: boolean): void; + /** + * When reading from the database, SQLite `INTEGER`s are mapped to JavaScript + * numbers by default. However, SQLite `INTEGER`s can store values larger than + * JavaScript numbers are capable of representing. In such cases, this method can + * be used to read `INTEGER` data using JavaScript `BigInt`s. This method has no + * impact on database write operations where numbers and `BigInt`s are both + * supported at all times. + * @since v22.5.0 + * @param enabled Enables or disables the use of `BigInt`s when reading `INTEGER` fields from the database. + */ + setReadBigInts(enabled: boolean): void; + /** + * The source SQL text of the prepared statement. This property is a + * wrapper around [`sqlite3_sql()`](https://www.sqlite.org/c3ref/expanded_sql.html). + * @since v22.5.0 + */ + readonly sourceSQL: string; + } + interface BackupOptions { + /** + * Name of the source database. This can be `'main'` (the default primary database) or any other + * database that have been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) + * @default 'main' + */ + source?: string | undefined; + /** + * Name of the target database. This can be `'main'` (the default primary database) or any other + * database that have been added with [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html) + * @default 'main' + */ + target?: string | undefined; + /** + * Number of pages to be transmitted in each batch of the backup. + * @default 100 + */ + rate?: number | undefined; + /** + * Callback function that will be called with the number of pages copied and the total number of + * pages. + */ + progress?: ((progressInfo: BackupProgressInfo) => void) | undefined; + } + interface BackupProgressInfo { + totalPages: number; + remainingPages: number; + } + /** + * This method makes a database backup. This method abstracts the + * [`sqlite3_backup_init()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupinit), + * [`sqlite3_backup_step()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupstep) + * and [`sqlite3_backup_finish()`](https://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupfinish) functions. + * + * The backed-up database can be used normally during the backup process. Mutations coming from the same connection - same + * `DatabaseSync` - object will be reflected in the backup right away. However, mutations from other connections will cause + * the backup process to restart. + * + * ```js + * import { backup, DatabaseSync } from 'node:sqlite'; + * + * const sourceDb = new DatabaseSync('source.db'); + * const totalPagesTransferred = await backup(sourceDb, 'backup.db', { + * rate: 1, // Copy one page at a time. + * progress: ({ totalPages, remainingPages }) => { + * console.log('Backup in progress', { totalPages, remainingPages }); + * }, + * }); + * + * console.log('Backup completed', totalPagesTransferred); + * ``` + * @since v23.8.0 + * @param sourceDb The database to backup. The source database must be open. + * @param path The path where the backup will be created. If the file already exists, + * the contents will be overwritten. + * @param options Optional configuration for the backup. The + * following properties are supported: + * @returns A promise that resolves when the backup is completed and rejects if an error occurs. + */ + function backup(sourceDb: DatabaseSync, path: string | Buffer | URL, options?: BackupOptions): Promise; + /** + * @since v22.13.0 + */ + namespace constants { + /** + * The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is present in the database, but one or more other (non primary-key) fields modified by the update do not contain the expected "before" values. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_DATA: number; + /** + * The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is not present in the database. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_NOTFOUND: number; + /** + * This constant is passed to the conflict handler while processing an INSERT change if the operation would result in duplicate primary key values. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_CONFLICT: number; + /** + * If foreign key handling is enabled, and applying a changeset leaves the database in a state containing foreign key violations, the conflict handler is invoked with this constant exactly once before the changeset is committed. If the conflict handler returns `SQLITE_CHANGESET_OMIT`, the changes, including those that caused the foreign key constraint violation, are committed. Or, if it returns `SQLITE_CHANGESET_ABORT`, the changeset is rolled back. + * @since v22.14.0 + */ + const SQLITE_CHANGESET_FOREIGN_KEY: number; + /** + * Conflicting changes are omitted. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_OMIT: number; + /** + * Conflicting changes replace existing values. Note that this value can only be returned when the type of conflict is either `SQLITE_CHANGESET_DATA` or `SQLITE_CHANGESET_CONFLICT`. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_REPLACE: number; + /** + * Abort when a change encounters a conflict and roll back database. + * @since v22.12.0 + */ + const SQLITE_CHANGESET_ABORT: number; + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/stream.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/stream.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b586dd237fd7c58bcc33dbee7b0666faf0e2e8ae --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1668 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `node:stream` module provides an API for implementing the stream interface. + * + * There are many stream objects provided by Node.js. For instance, a [request to an HTTP server](https://nodejs.org/docs/latest-v24.x/api/http.html#class-httpincomingmessage) + * and [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of [`EventEmitter`](https://nodejs.org/docs/latest-v24.x/api/events.html#class-eventemitter). + * + * To access the `node:stream` module: + * + * ```js + * import stream from 'node:stream'; + * ``` + * + * The `node:stream` module is useful for creating new types of stream instances. + * It is usually not necessary to use the `node:stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/stream.js) + */ +declare module "stream" { + import { Abortable, EventEmitter } from "node:events"; + import { Blob as NodeBlob } from "node:buffer"; + import * as streamPromises from "node:stream/promises"; + import * as streamWeb from "node:stream/web"; + + type ComposeFnParam = (source: any) => void; + + class Stream extends EventEmitter { + pipe( + destination: T, + options?: { + end?: boolean | undefined; + }, + ): T; + compose( + stream: T | ComposeFnParam | Iterable | AsyncIterable, + options?: { signal: AbortSignal }, + ): T; + } + namespace Stream { + export { Stream, streamPromises as promises }; + } + namespace Stream { + interface StreamOptions extends Abortable { + emitClose?: boolean | undefined; + highWaterMark?: number | undefined; + objectMode?: boolean | undefined; + construct?(this: T, callback: (error?: Error | null) => void): void; + destroy?(this: T, error: Error | null, callback: (error?: Error | null) => void): void; + autoDestroy?: boolean | undefined; + } + interface ReadableOptions extends StreamOptions { + encoding?: BufferEncoding | undefined; + read?(this: T, size: number): void; + } + interface ArrayOptions { + /** + * The maximum concurrent invocations of `fn` to call on the stream at once. + * @default 1 + */ + concurrency?: number; + /** Allows destroying the stream if the signal is aborted. */ + signal?: AbortSignal; + } + /** + * @since v0.9.4 + */ + class Readable extends Stream implements NodeJS.ReadableStream { + /** + * A utility method for creating Readable Streams out of iterators. + * @since v12.3.0, v10.17.0 + * @param iterable Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed. + * @param options Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * A utility method for creating a `Readable` from a web `ReadableStream`. + * @since v17.0.0 + */ + static fromWeb( + readableStream: streamWeb.ReadableStream, + options?: Pick, + ): Readable; + /** + * A utility method for creating a web `ReadableStream` from a `Readable`. + * @since v17.0.0 + */ + static toWeb( + streamReadable: Readable, + options?: { + strategy?: streamWeb.QueuingStrategy | undefined; + }, + ): streamWeb.ReadableStream; + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @since v16.8.0 + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call {@link read}, which means + * the stream has not been destroyed or emitted `'error'` or `'end'`. + * @since v11.4.0 + */ + readable: boolean; + /** + * Returns whether `'data'` has been emitted. + * @since v16.7.0, v14.18.0 + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding` property can be set using the {@link setEncoding} method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when [`'end'`](https://nodejs.org/docs/latest-v24.x/api/stream.html#event-end) event is emitted. + * @since v12.9.0 + */ + readonly readableEnded: boolean; + /** + * This property reflects the current state of a `Readable` stream as described + * in the [Three states](https://nodejs.org/docs/latest-v24.x/api/stream.html#three-states) section. + * @since v9.4.0 + */ + readonly readableFlowing: boolean | null; + /** + * Returns the value of `highWaterMark` passed when creating this `Readable`. + * @since v9.3.0 + */ + readonly readableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be read. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly readableLength: number; + /** + * Getter for the property `objectMode` of a given `Readable` stream. + * @since v12.3.0 + */ + readonly readableObjectMode: boolean; + /** + * Is `true` after `readable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + constructor(opts?: ReadableOptions); + _construct?(callback: (error?: Error | null) => void): void; + _read(size: number): void; + /** + * The `readable.read()` method reads data out of the internal buffer and + * returns it. If no data is available to be read, `null` is returned. By default, + * the data is returned as a `Buffer` object unless an encoding has been + * specified using the `readable.setEncoding()` method or the stream is operating + * in object mode. + * + * The optional `size` argument specifies a specific number of bytes to read. If + * `size` bytes are not available to be read, `null` will be returned _unless_ the + * stream has ended, in which case all of the data remaining in the internal buffer + * will be returned. + * + * If the `size` argument is not specified, all of the data contained in the + * internal buffer will be returned. + * + * The `size` argument must be less than or equal to 1 GiB. + * + * The `readable.read()` method should only be called on `Readable` streams + * operating in paused mode. In flowing mode, `readable.read()` is called + * automatically until the internal buffer is fully drained. + * + * ```js + * const readable = getReadableStreamSomehow(); + * + * // 'readable' may be triggered multiple times as data is buffered in + * readable.on('readable', () => { + * let chunk; + * console.log('Stream is readable (new data received in buffer)'); + * // Use a loop to make sure we read all currently available data + * while (null !== (chunk = readable.read())) { + * console.log(`Read ${chunk.length} bytes of data...`); + * } + * }); + * + * // 'end' will be triggered once when there is no more data available + * readable.on('end', () => { + * console.log('Reached end of stream.'); + * }); + * ``` + * + * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks + * are not concatenated. A `while` loop is necessary to consume all data + * currently in the buffer. When reading a large file `.read()` may return `null`, + * having consumed all buffered content so far, but there is still more data to + * come not yet buffered. In this case a new `'readable'` event will be emitted + * when there is more data in the buffer. Finally the `'end'` event will be + * emitted when there is no more data to come. + * + * Therefore to read a file's whole contents from a `readable`, it is necessary + * to collect chunks across multiple `'readable'` events: + * + * ```js + * const chunks = []; + * + * readable.on('readable', () => { + * let chunk; + * while (null !== (chunk = readable.read())) { + * chunks.push(chunk); + * } + * }); + * + * readable.on('end', () => { + * const content = chunks.join(''); + * }); + * ``` + * + * A `Readable` stream in object mode will always return a single item from + * a call to `readable.read(size)`, regardless of the value of the `size` argument. + * + * If the `readable.read()` method returns a chunk of data, a `'data'` event will + * also be emitted. + * + * Calling {@link read} after the `'end'` event has + * been emitted will return `null`. No runtime error will be raised. + * @since v0.9.4 + * @param size Optional argument to specify how much data to read. + */ + read(size?: number): any; + /** + * The `readable.setEncoding()` method sets the character encoding for + * data read from the `Readable` stream. + * + * By default, no encoding is assigned and stream data will be returned as `Buffer` objects. Setting an encoding causes the stream data + * to be returned as strings of the specified encoding rather than as `Buffer` objects. For instance, calling `readable.setEncoding('utf8')` will cause the + * output data to be interpreted as UTF-8 data, and passed as strings. Calling `readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal + * string format. + * + * The `Readable` stream will properly handle multi-byte characters delivered + * through the stream that would otherwise become improperly decoded if simply + * pulled from the stream as `Buffer` objects. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.setEncoding('utf8'); + * readable.on('data', (chunk) => { + * assert.equal(typeof chunk, 'string'); + * console.log('Got %d characters of string data:', chunk.length); + * }); + * ``` + * @since v0.9.4 + * @param encoding The encoding to use. + */ + setEncoding(encoding: BufferEncoding): this; + /** + * The `readable.pause()` method will cause a stream in flowing mode to stop + * emitting `'data'` events, switching out of flowing mode. Any data that + * becomes available will remain in the internal buffer. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.on('data', (chunk) => { + * console.log(`Received ${chunk.length} bytes of data.`); + * readable.pause(); + * console.log('There will be no additional data for 1 second.'); + * setTimeout(() => { + * console.log('Now data will start flowing again.'); + * readable.resume(); + * }, 1000); + * }); + * ``` + * + * The `readable.pause()` method has no effect if there is a `'readable'` event listener. + * @since v0.9.4 + */ + pause(): this; + /** + * The `readable.resume()` method causes an explicitly paused `Readable` stream to + * resume emitting `'data'` events, switching the stream into flowing mode. + * + * The `readable.resume()` method can be used to fully consume the data from a + * stream without actually processing any of that data: + * + * ```js + * getReadableStreamSomehow() + * .resume() + * .on('end', () => { + * console.log('Reached the end, but did not read anything.'); + * }); + * ``` + * + * The `readable.resume()` method has no effect if there is a `'readable'` event listener. + * @since v0.9.4 + */ + resume(): this; + /** + * The `readable.isPaused()` method returns the current operating state of the `Readable`. + * This is used primarily by the mechanism that underlies the `readable.pipe()` method. + * In most typical cases, there will be no reason to use this method directly. + * + * ```js + * const readable = new stream.Readable(); + * + * readable.isPaused(); // === false + * readable.pause(); + * readable.isPaused(); // === true + * readable.resume(); + * readable.isPaused(); // === false + * ``` + * @since v0.11.14 + */ + isPaused(): boolean; + /** + * The `readable.unpipe()` method detaches a `Writable` stream previously attached + * using the {@link pipe} method. + * + * If the `destination` is not specified, then _all_ pipes are detached. + * + * If the `destination` is specified, but no pipe is set up for it, then + * the method does nothing. + * + * ```js + * import fs from 'node:fs'; + * const readable = getReadableStreamSomehow(); + * const writable = fs.createWriteStream('file.txt'); + * // All the data from readable goes into 'file.txt', + * // but only for the first second. + * readable.pipe(writable); + * setTimeout(() => { + * console.log('Stop writing to file.txt.'); + * readable.unpipe(writable); + * console.log('Manually close the file stream.'); + * writable.end(); + * }, 1000); + * ``` + * @since v0.9.4 + * @param destination Optional specific stream to unpipe + */ + unpipe(destination?: NodeJS.WritableStream): this; + /** + * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the + * same as `readable.push(null)`, after which no more data can be written. The EOF + * signal is put at the end of the buffer and any buffered data will still be + * flushed. + * + * The `readable.unshift()` method pushes a chunk of data back into the internal + * buffer. This is useful in certain situations where a stream is being consumed by + * code that needs to "un-consume" some amount of data that it has optimistically + * pulled out of the source, so that the data can be passed on to some other party. + * + * The `stream.unshift(chunk)` method cannot be called after the `'end'` event + * has been emitted or a runtime error will be thrown. + * + * Developers using `stream.unshift()` often should consider switching to + * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + * + * ```js + * // Pull off a header delimited by \n\n. + * // Use unshift() if we get too much. + * // Call the callback with (error, header, stream). + * import { StringDecoder } from 'node:string_decoder'; + * function parseHeader(stream, callback) { + * stream.on('error', callback); + * stream.on('readable', onReadable); + * const decoder = new StringDecoder('utf8'); + * let header = ''; + * function onReadable() { + * let chunk; + * while (null !== (chunk = stream.read())) { + * const str = decoder.write(chunk); + * if (str.includes('\n\n')) { + * // Found the header boundary. + * const split = str.split(/\n\n/); + * header += split.shift(); + * const remaining = split.join('\n\n'); + * const buf = Buffer.from(remaining, 'utf8'); + * stream.removeListener('error', callback); + * // Remove the 'readable' listener before unshifting. + * stream.removeListener('readable', onReadable); + * if (buf.length) + * stream.unshift(buf); + * // Now the body of the message can be read from the stream. + * callback(null, header, stream); + * return; + * } + * // Still reading the header. + * header += str; + * } + * } + * } + * ``` + * + * Unlike {@link push}, `stream.unshift(chunk)` will not + * end the reading process by resetting the internal reading state of the stream. + * This can cause unexpected results if `readable.unshift()` is called during a + * read (i.e. from within a {@link _read} implementation on a + * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, + * however it is best to simply avoid calling `readable.unshift()` while in the + * process of performing a read. + * @since v0.9.11 + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must + * be a {string}, {Buffer}, {TypedArray}, {DataView} or `null`. For object mode streams, `chunk` may be any JavaScript value. + * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. + */ + unshift(chunk: any, encoding?: BufferEncoding): void; + /** + * Prior to Node.js 0.10, streams did not implement the entire `node:stream` module API as it is currently defined. (See `Compatibility` for more + * information.) + * + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the `readable.wrap()` method can be used to create a `Readable` + * stream that uses + * the old stream as its data source. + * + * It will rarely be necessary to use `readable.wrap()` but the method has been + * provided as a convenience for interacting with older Node.js applications and + * libraries. + * + * ```js + * import { OldReader } from './old-api-module.js'; + * import { Readable } from 'node:stream'; + * const oreader = new OldReader(); + * const myReader = new Readable().wrap(oreader); + * + * myReader.on('readable', () => { + * myReader.read(); // etc. + * }); + * ``` + * @since v0.9.4 + * @param stream An "old style" readable stream + */ + wrap(stream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: BufferEncoding): boolean; + /** + * The iterator created by this method gives users the option to cancel the destruction + * of the stream if the `for await...of` loop is exited by `return`, `break`, or `throw`, + * or if the iterator should destroy the stream if the stream emitted an error during iteration. + * @since v16.3.0 + * @param options.destroyOnReturn When set to `false`, calling `return` on the async iterator, + * or exiting a `for await...of` iteration using a `break`, `return`, or `throw` will not destroy the stream. + * **Default: `true`**. + */ + iterator(options?: { destroyOnReturn?: boolean }): NodeJS.AsyncIterator; + /** + * This method allows mapping over the stream. The *fn* function will be called for every chunk in the stream. + * If the *fn* function returns a promise - that promise will be `await`ed before being passed to the result stream. + * @since v17.4.0, v16.14.0 + * @param fn a function to map over every chunk in the stream. Async or not. + * @returns a stream mapped with the function *fn*. + */ + map(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method allows filtering the stream. For each chunk in the stream the *fn* function will be called + * and if it returns a truthy value, the chunk will be passed to the result stream. + * If the *fn* function returns a promise - that promise will be `await`ed. + * @since v17.4.0, v16.14.0 + * @param fn a function to filter chunks from the stream. Async or not. + * @returns a stream filtered with the predicate *fn*. + */ + filter( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Readable; + /** + * This method allows iterating a stream. For each chunk in the stream the *fn* function will be called. + * If the *fn* function returns a promise - that promise will be `await`ed. + * + * This method is different from `for await...of` loops in that it can optionally process chunks concurrently. + * In addition, a `forEach` iteration can only be stopped by having passed a `signal` option + * and aborting the related AbortController while `for await...of` can be stopped with `break` or `return`. + * In either case the stream will be destroyed. + * + * This method is different from listening to the `'data'` event in that it uses the `readable` event + * in the underlying machinary and can limit the number of concurrent *fn* calls. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise for when the stream has finished. + */ + forEach( + fn: (data: any, options?: Pick) => void | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method allows easily obtaining the contents of a stream. + * + * As this method reads the entire stream into memory, it negates the benefits of streams. It's intended + * for interoperability and convenience, not as the primary way to consume streams. + * @since v17.5.0 + * @returns a promise containing an array with the contents of the stream. + */ + toArray(options?: Pick): Promise; + /** + * This method is similar to `Array.prototype.some` and calls *fn* on each chunk in the stream + * until the awaited return value is `true` (or any truthy value). Once an *fn* call on a chunk + * `await`ed return value is truthy, the stream is destroyed and the promise is fulfilled with `true`. + * If none of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `false`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for at least one of the chunks. + */ + some( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.find` and calls *fn* on each chunk in the stream + * to find a chunk with a truthy value for *fn*. Once an *fn* call's awaited return value is truthy, + * the stream is destroyed and the promise is fulfilled with value for which *fn* returned a truthy value. + * If all of the *fn* calls on the chunks return a falsy value, the promise is fulfilled with `undefined`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to the first chunk for which *fn* evaluated with a truthy value, + * or `undefined` if no element was found. + */ + find( + fn: (data: any, options?: Pick) => data is T, + options?: ArrayOptions, + ): Promise; + find( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.every` and calls *fn* on each chunk in the stream + * to check if all awaited return values are truthy value for *fn*. Once an *fn* call on a chunk + * `await`ed return value is falsy, the stream is destroyed and the promise is fulfilled with `false`. + * If all of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `true`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for every one of the chunks. + */ + every( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method returns a new stream by applying the given callback to each chunk of the stream + * and then flattening the result. + * + * It is possible to return a stream or another iterable or async iterable from *fn* and the result streams + * will be merged (flattened) into the returned stream. + * @since v17.5.0 + * @param fn a function to map over every chunk in the stream. May be async. May be a stream or generator. + * @returns a stream flat-mapped with the function *fn*. + */ + flatMap(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method returns a new stream with the first *limit* chunks dropped from the start. + * @since v17.5.0 + * @param limit the number of chunks to drop from the readable. + * @returns a stream with *limit* chunks dropped from the start. + */ + drop(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with the first *limit* chunks. + * @since v17.5.0 + * @param limit the number of chunks to take from the readable. + * @returns a stream with *limit* chunks taken. + */ + take(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with chunks of the underlying stream paired with a counter + * in the form `[index, chunk]`. The first index value is `0` and it increases by 1 for each chunk produced. + * @since v17.5.0 + * @returns a stream of indexed pairs. + */ + asIndexedPairs(options?: Pick): Readable; + /** + * This method calls *fn* on each chunk of the stream in order, passing it the result from the calculation + * on the previous element. It returns a promise for the final value of the reduction. + * + * If no *initial* value is supplied the first chunk of the stream is used as the initial value. + * If the stream is empty, the promise is rejected with a `TypeError` with the `ERR_INVALID_ARGS` code property. + * + * The reducer function iterates the stream element-by-element which means that there is no *concurrency* parameter + * or parallelism. To perform a reduce concurrently, you can extract the async function to `readable.map` method. + * @since v17.5.0 + * @param fn a reducer function to call over every chunk in the stream. Async or not. + * @param initial the initial value to use in the reduction. + * @returns a promise for the final value of the reduction. + */ + reduce( + fn: (previous: any, data: any, options?: Pick) => T, + initial?: undefined, + options?: Pick, + ): Promise; + reduce( + fn: (previous: T, data: any, options?: Pick) => T, + initial: T, + options?: Pick, + ): Promise; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the readable + * stream will release any internal resources and subsequent calls to `push()` will be ignored. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, but instead implement `readable._destroy()`. + * @since v8.0.0 + * @param error Error which will be passed as payload in `'error'` event + */ + destroy(error?: Error): this; + /** + * @returns `AsyncIterator` to fully consume the stream. + * @since v10.0.0 + */ + [Symbol.asyncIterator](): NodeJS.AsyncIterator; + /** + * Calls `readable.destroy()` with an `AbortError` and returns + * a promise that fulfills when the stream is finished. + * @since v20.4.0 + */ + [Symbol.asyncDispose](): Promise; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. error + * 5. pause + * 6. readable + * 7. resume + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "pause"): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + interface WritableOptions extends StreamOptions { + decodeStrings?: boolean | undefined; + defaultEncoding?: BufferEncoding | undefined; + write?( + this: T, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void; + writev?( + this: T, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: T, callback: (error?: Error | null) => void): void; + } + /** + * @since v0.9.4 + */ + class Writable extends Stream implements NodeJS.WritableStream { + /** + * A utility method for creating a `Writable` from a web `WritableStream`. + * @since v17.0.0 + */ + static fromWeb( + writableStream: streamWeb.WritableStream, + options?: Pick, + ): Writable; + /** + * A utility method for creating a web `WritableStream` from a `Writable`. + * @since v17.0.0 + */ + static toWeb(streamWritable: Writable): streamWeb.WritableStream; + /** + * Is `true` if it is safe to call `writable.write()`, which means + * the stream has not been destroyed, errored, or ended. + * @since v11.4.0 + */ + readonly writable: boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'finish'`. + * @since v18.0.0, v16.17.0 + */ + readonly writableAborted: boolean; + /** + * Is `true` after `writable.end()` has been called. This property + * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. + * @since v12.9.0 + */ + readonly writableEnded: boolean; + /** + * Is set to `true` immediately before the `'finish'` event is emitted. + * @since v12.6.0 + */ + readonly writableFinished: boolean; + /** + * Return the value of `highWaterMark` passed when creating this `Writable`. + * @since v9.3.0 + */ + readonly writableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be written. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly writableLength: number; + /** + * Getter for the property `objectMode` of a given `Writable` stream. + * @since v12.3.0 + */ + readonly writableObjectMode: boolean; + /** + * Number of times `writable.uncork()` needs to be + * called in order to fully uncork the stream. + * @since v13.2.0, v12.16.0 + */ + readonly writableCorked: number; + /** + * Is `true` after `writable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + /** + * Is `true` if the stream's buffer has been full and stream will emit `'drain'`. + * @since v15.2.0, v14.17.0 + */ + readonly writableNeedDrain: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + _construct?(callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + /** + * The `writable.write()` method writes some data to the stream, and calls the + * supplied `callback` once the data has been fully handled. If an error + * occurs, the `callback` will be called with the error as its + * first argument. The `callback` is called asynchronously and before `'error'` is + * emitted. + * + * The return value is `true` if the internal buffer is less than the `highWaterMark` configured when the stream was created after admitting `chunk`. + * If `false` is returned, further attempts to write data to the stream should + * stop until the `'drain'` event is emitted. + * + * While a stream is not draining, calls to `write()` will buffer `chunk`, and + * return false. Once all currently buffered chunks are drained (accepted for + * delivery by the operating system), the `'drain'` event will be emitted. + * Once `write()` returns false, do not write more chunks + * until the `'drain'` event is emitted. While calling `write()` on a stream that + * is not draining is allowed, Node.js will buffer all written chunks until + * maximum memory usage occurs, at which point it will abort unconditionally. + * Even before it aborts, high memory usage will cause poor garbage collector + * performance and high RSS (which is not typically released back to the system, + * even after the memory is no longer required). Since TCP sockets may never + * drain if the remote peer does not read the data, writing a socket that is + * not draining may lead to a remotely exploitable vulnerability. + * + * Writing data while the stream is not draining is particularly + * problematic for a `Transform`, because the `Transform` streams are paused + * by default until they are piped or a `'data'` or `'readable'` event handler + * is added. + * + * If the data to be written can be generated or fetched on demand, it is + * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is + * possible to respect backpressure and avoid memory issues using the `'drain'` event: + * + * ```js + * function write(data, cb) { + * if (!stream.write(data)) { + * stream.once('drain', cb); + * } else { + * process.nextTick(cb); + * } + * } + * + * // Wait for cb to be called before doing any other write. + * write('hello', () => { + * console.log('Write completed, do more writes now.'); + * }); + * ``` + * + * A `Writable` stream in object mode will always ignore the `encoding` argument. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param [encoding='utf8'] The encoding, if `chunk` is a string. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; + /** + * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. + * @since v0.11.15 + * @param encoding The new default encoding + */ + setDefaultEncoding(encoding: BufferEncoding): this; + /** + * Calling the `writable.end()` method signals that no more data will be written + * to the `Writable`. The optional `chunk` and `encoding` arguments allow one + * final additional chunk of data to be written immediately before closing the + * stream. + * + * Calling the {@link write} method after calling {@link end} will raise an error. + * + * ```js + * // Write 'hello, ' and then end with 'world!'. + * import fs from 'node:fs'; + * const file = fs.createWriteStream('example.txt'); + * file.write('hello, '); + * file.end('world!'); + * // Writing more now is not allowed! + * ``` + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param encoding The encoding if `chunk` is a string + * @param callback Callback for when the stream is finished. + */ + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; + /** + * The `writable.cork()` method forces all written data to be buffered in memory. + * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. + * + * The primary intent of `writable.cork()` is to accommodate a situation in which + * several small chunks are written to the stream in rapid succession. Instead of + * immediately forwarding them to the underlying destination, `writable.cork()` buffers all the chunks until `writable.uncork()` is called, which will pass them + * all to `writable._writev()`, if present. This prevents a head-of-line blocking + * situation where data is being buffered while waiting for the first small chunk + * to be processed. However, use of `writable.cork()` without implementing `writable._writev()` may have an adverse effect on throughput. + * + * See also: `writable.uncork()`, `writable._writev()`. + * @since v0.11.2 + */ + cork(): void; + /** + * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. + * + * When using `writable.cork()` and `writable.uncork()` to manage the buffering + * of writes to a stream, defer calls to `writable.uncork()` using `process.nextTick()`. Doing so allows batching of all `writable.write()` calls that occur within a given Node.js event + * loop phase. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.write('data '); + * process.nextTick(() => stream.uncork()); + * ``` + * + * If the `writable.cork()` method is called multiple times on a stream, the + * same number of calls to `writable.uncork()` must be called to flush the buffered + * data. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.cork(); + * stream.write('data '); + * process.nextTick(() => { + * stream.uncork(); + * // The data will not be flushed until uncork() is called a second time. + * stream.uncork(); + * }); + * ``` + * + * See also: `writable.cork()`. + * @since v0.11.2 + */ + uncork(): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the writable + * stream has ended and subsequent calls to `write()` or `end()` will result in + * an `ERR_STREAM_DESTROYED` error. + * This is a destructive and immediate way to destroy a stream. Previous calls to `write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. + * Use `end()` instead of destroy if data should flush before close, or wait for + * the `'drain'` event before destroying the stream. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, + * but instead implement `writable._destroy()`. + * @since v8.0.0 + * @param error Optional, an error to emit with `'error'` event. + */ + destroy(error?: Error): this; + /** + * Calls `writable.destroy()` with an `AbortError` and returns + * a promise that fulfills when the stream is finished. + * @since v22.4.0, v20.16.0 + */ + [Symbol.asyncDispose](): Promise; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean | undefined; + readableObjectMode?: boolean | undefined; + writableObjectMode?: boolean | undefined; + readableHighWaterMark?: number | undefined; + writableHighWaterMark?: number | undefined; + writableCorked?: number | undefined; + } + /** + * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Duplex` streams include: + * + * * `TCP sockets` + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Duplex extends Stream implements NodeJS.ReadWriteStream { + /** + * If `false` then the stream will automatically end the writable side when the + * readable side ends. Set initially by the `allowHalfOpen` constructor option, + * which defaults to `true`. + * + * This can be changed manually to change the half-open behavior of an existing + * `Duplex` stream instance, but must be changed before the `'end'` event is emitted. + * @since v0.9.4 + */ + allowHalfOpen: boolean; + constructor(opts?: DuplexOptions); + /** + * A utility method for creating duplex streams. + * + * - `Stream` converts writable stream into writable `Duplex` and readable stream + * to `Duplex`. + * - `Blob` converts into readable `Duplex`. + * - `string` converts into readable `Duplex`. + * - `ArrayBuffer` converts into readable `Duplex`. + * - `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. + * - `AsyncGeneratorFunction` converts into a readable/writable transform + * `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + * `null`. + * - `AsyncFunction` converts into a writable `Duplex`. Must return + * either `null` or `undefined` + * - `Object ({ writable, readable })` converts `readable` and + * `writable` into `Stream` and then combines them into `Duplex` where the + * `Duplex` will write to the `writable` and read from the `readable`. + * - `Promise` converts into readable `Duplex`. Value `null` is ignored. + * + * @since v16.8.0 + */ + static from( + src: + | Stream + | NodeBlob + | ArrayBuffer + | string + | Iterable + | AsyncIterable + | AsyncGeneratorFunction + | Promise + | Object, + ): Duplex; + /** + * A utility method for creating a web `ReadableStream` and `WritableStream` from a `Duplex`. + * @since v17.0.0 + */ + static toWeb(streamDuplex: Duplex): { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }; + /** + * A utility method for creating a `Duplex` from a web `ReadableStream` and `WritableStream`. + * @since v17.0.0 + */ + static fromWeb( + duplexStream: { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }, + options?: Pick< + DuplexOptions, + "allowHalfOpen" | "decodeStrings" | "encoding" | "highWaterMark" | "objectMode" | "signal" + >, + ): Duplex; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. drain + * 4. end + * 5. error + * 6. finish + * 7. pause + * 8. pipe + * 9. readable + * 10. resume + * 11. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pause"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pause", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pause", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + interface Duplex extends Readable, Writable {} + /** + * The utility function `duplexPair` returns an Array with two items, + * each being a `Duplex` stream connected to the other side: + * + * ```js + * const [ sideA, sideB ] = duplexPair(); + * ``` + * + * Whatever is written to one stream is made readable on the other. It provides + * behavior analogous to a network connection, where the data written by the client + * becomes readable by the server, and vice-versa. + * + * The Duplex streams are symmetrical; one or the other may be used without any + * difference in behavior. + * @param options A value to pass to both {@link Duplex} constructors, + * to set options such as buffering. + * @since v22.6.0 + */ + function duplexPair(options?: DuplexOptions): [Duplex, Duplex]; + type TransformCallback = (error?: Error | null, data?: any) => void; + interface TransformOptions extends DuplexOptions { + transform?(this: T, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + flush?(this: T, callback: TransformCallback): void; + } + /** + * Transform streams are `Duplex` streams where the output is in some way + * related to the input. Like all `Duplex` streams, `Transform` streams + * implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Transform` streams include: + * + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + /** + * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is + * primarily for examples and testing, but there are some use cases where `stream.PassThrough` is useful as a building block for novel sorts of streams. + */ + class PassThrough extends Transform {} + /** + * A stream to attach a signal to. + * + * Attaches an AbortSignal to a readable or writeable stream. This lets code + * control stream destruction using an `AbortController`. + * + * Calling `abort` on the `AbortController` corresponding to the passed `AbortSignal` will behave the same way as calling `.destroy(new AbortError())` on the + * stream, and `controller.error(new AbortError())` for webstreams. + * + * ```js + * import fs from 'node:fs'; + * + * const controller = new AbortController(); + * const read = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * // Later, abort the operation closing the stream + * controller.abort(); + * ``` + * + * Or using an `AbortSignal` with a readable stream as an async iterable: + * + * ```js + * const controller = new AbortController(); + * setTimeout(() => controller.abort(), 10_000); // set a timeout + * const stream = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * (async () => { + * try { + * for await (const chunk of stream) { + * await process(chunk); + * } + * } catch (e) { + * if (e.name === 'AbortError') { + * // The operation was cancelled + * } else { + * throw e; + * } + * } + * })(); + * ``` + * + * Or using an `AbortSignal` with a ReadableStream: + * + * ```js + * const controller = new AbortController(); + * const rs = new ReadableStream({ + * start(controller) { + * controller.enqueue('hello'); + * controller.enqueue('world'); + * controller.close(); + * }, + * }); + * + * addAbortSignal(controller.signal, rs); + * + * finished(rs, (err) => { + * if (err) { + * if (err.name === 'AbortError') { + * // The operation was cancelled + * } + * } + * }); + * + * const reader = rs.getReader(); + * + * reader.read().then(({ value, done }) => { + * console.log(value); // hello + * console.log(done); // false + * controller.abort(); + * }); + * ``` + * @since v15.4.0 + * @param signal A signal representing possible cancellation + * @param stream A stream to attach a signal to. + */ + function addAbortSignal(signal: AbortSignal, stream: T): T; + /** + * Returns the default highWaterMark used by streams. + * Defaults to `65536` (64 KiB), or `16` for `objectMode`. + * @since v19.9.0 + */ + function getDefaultHighWaterMark(objectMode: boolean): number; + /** + * Sets the default highWaterMark used by streams. + * @since v19.9.0 + * @param value highWaterMark value + */ + function setDefaultHighWaterMark(objectMode: boolean, value: number): void; + interface FinishedOptions extends Abortable { + error?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + /** + * A readable and/or writable stream/webstream. + * + * A function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * import { finished } from 'node:stream'; + * import fs from 'node:fs'; + * + * const rs = fs.createReadStream('archive.tar'); + * + * finished(rs, (err) => { + * if (err) { + * console.error('Stream failed.', err); + * } else { + * console.log('Stream is done reading.'); + * } + * }); + * + * rs.resume(); // Drain the stream. + * ``` + * + * Especially useful in error handling scenarios where a stream is destroyed + * prematurely (like an aborted HTTP request), and will not emit `'end'` or `'finish'`. + * + * The `finished` API provides [`promise version`](https://nodejs.org/docs/latest-v24.x/api/stream.html#streamfinishedstream-options). + * + * `stream.finished()` leaves dangling event listeners (in particular `'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been + * invoked. The reason for this is so that unexpected `'error'` events (due to + * incorrect stream implementations) do not cause unexpected crashes. + * If this is unwanted behavior then the returned cleanup function needs to be + * invoked in the callback: + * + * ```js + * const cleanup = finished(rs, (err) => { + * cleanup(); + * // ... + * }); + * ``` + * @since v10.0.0 + * @param stream A readable and/or writable stream. + * @param callback A callback function that takes an optional error argument. + * @returns A cleanup function which removes all registered listeners. + */ + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options: FinishedOptions, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + namespace finished { + function __promisify__( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + } + type PipelineSourceFunction = () => Iterable | AsyncIterable; + type PipelineSource = Iterable | AsyncIterable | NodeJS.ReadableStream | PipelineSourceFunction; + type PipelineTransform, U> = + | NodeJS.ReadWriteStream + | (( + source: S extends (...args: any[]) => Iterable | AsyncIterable ? AsyncIterable + : S, + ) => AsyncIterable); + type PipelineTransformSource = PipelineSource | PipelineTransform; + type PipelineDestinationIterableFunction = (source: AsyncIterable) => AsyncIterable; + type PipelineDestinationPromiseFunction = (source: AsyncIterable) => Promise

; + type PipelineDestination, P> = S extends + PipelineTransformSource ? + | NodeJS.WritableStream + | PipelineDestinationIterableFunction + | PipelineDestinationPromiseFunction + : never; + type PipelineCallback> = S extends + PipelineDestinationPromiseFunction ? (err: NodeJS.ErrnoException | null, value: P) => void + : (err: NodeJS.ErrnoException | null) => void; + type PipelinePromise> = S extends + PipelineDestinationPromiseFunction ? Promise

: Promise; + interface PipelineOptions { + signal?: AbortSignal | undefined; + end?: boolean | undefined; + } + /** + * A module method to pipe between streams and generators forwarding errors and + * properly cleaning up and provide a callback when the pipeline is complete. + * + * ```js + * import { pipeline } from 'node:stream'; + * import fs from 'node:fs'; + * import zlib from 'node:zlib'; + * + * // Use the pipeline API to easily pipe a series of streams + * // together and get notified when the pipeline is fully done. + * + * // A pipeline to gzip a potentially huge tar file efficiently: + * + * pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * (err) => { + * if (err) { + * console.error('Pipeline failed.', err); + * } else { + * console.log('Pipeline succeeded.'); + * } + * }, + * ); + * ``` + * + * The `pipeline` API provides a [`promise version`](https://nodejs.org/docs/latest-v24.x/api/stream.html#streampipelinesource-transforms-destination-options). + * + * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * + * * `Readable` streams which have emitted `'end'` or `'close'`. + * * `Writable` streams which have emitted `'finish'` or `'close'`. + * + * `stream.pipeline()` leaves dangling event listeners on the streams + * after the `callback` has been invoked. In the case of reuse of streams after + * failure, this can cause event listener leaks and swallowed errors. If the last + * stream is readable, dangling event listeners will be removed so that the last + * stream can be consumed later. + * + * `stream.pipeline()` closes all the streams when an error is raised. + * The `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior + * once it would destroy the socket without sending the expected response. + * See the example below: + * + * ```js + * import fs from 'node:fs'; + * import http from 'node:http'; + * import { pipeline } from 'node:stream'; + * + * const server = http.createServer((req, res) => { + * const fileStream = fs.createReadStream('./fileNotExist.txt'); + * pipeline(fileStream, res, (err) => { + * if (err) { + * console.log(err); // No such file + * // this message can't be sent once `pipeline` already destroyed the socket + * return res.end('error!!!'); + * } + * }); + * }); + * ``` + * @since v10.0.0 + * @param callback Called when the pipeline is fully done. + */ + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline( + streams: ReadonlyArray, + callback: (err: NodeJS.ErrnoException | null) => void, + ): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array< + NodeJS.ReadWriteStream | NodeJS.WritableStream | ((err: NodeJS.ErrnoException | null) => void) + > + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; + } + interface Pipe { + close(): void; + hasRef(): boolean; + ref(): void; + unref(): void; + } + /** + * Returns whether the stream has encountered an error. + * @since v17.3.0, v16.14.0 + */ + function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean; + /** + * Returns whether the stream is readable. + * @since v17.4.0, v16.14.0 + */ + function isReadable(stream: Readable | NodeJS.ReadableStream): boolean; + } + export = Stream; +} +declare module "node:stream" { + import stream = require("stream"); + export = stream; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/stream/consumers.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/stream/consumers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..746d6e508266ac6fa68ee26d852d8d63ab3a15ca --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/stream/consumers.d.ts @@ -0,0 +1,38 @@ +/** + * The utility consumer functions provide common options for consuming + * streams. + * @since v16.7.0 + */ +declare module "stream/consumers" { + import { Blob as NodeBlob } from "node:buffer"; + import { ReadableStream as WebReadableStream } from "node:stream/web"; + /** + * @since v16.7.0 + * @returns Fulfills with an `ArrayBuffer` containing the full contents of the stream. + */ + function arrayBuffer(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with a `Blob` containing the full contents of the stream. + */ + function blob(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with a `Buffer` containing the full contents of the stream. + */ + function buffer(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with the contents of the stream parsed as a + * UTF-8 encoded string that is then passed through `JSON.parse()`. + */ + function json(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v16.7.0 + * @returns Fulfills with the contents of the stream parsed as a UTF-8 encoded string. + */ + function text(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; +} +declare module "node:stream/consumers" { + export * from "stream/consumers"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/stream/promises.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/stream/promises.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d54c14c60fa3590259439e2d02b995710966a664 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/stream/promises.d.ts @@ -0,0 +1,90 @@ +declare module "stream/promises" { + import { + FinishedOptions as _FinishedOptions, + PipelineDestination, + PipelineOptions, + PipelinePromise, + PipelineSource, + PipelineTransform, + } from "node:stream"; + interface FinishedOptions extends _FinishedOptions { + /** + * If true, removes the listeners registered by this function before the promise is fulfilled. + * @default false + */ + cleanup?: boolean | undefined; + } + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; +} +declare module "node:stream/promises" { + export * from "stream/promises"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/stream/web.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/stream/web.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..881e29c089fdb1819971fa2eba808344268b94a6 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,622 @@ +type _ByteLengthQueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ByteLengthQueuingStrategy; +type _CompressionStream = typeof globalThis extends { onmessage: any; ReportingObserver: any } ? {} + : import("stream/web").CompressionStream; +type _CountQueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").CountQueuingStrategy; +type _DecompressionStream = typeof globalThis extends { onmessage: any; ReportingObserver: any } ? {} + : import("stream/web").DecompressionStream; +type _QueuingStrategy = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").QueuingStrategy; +type _ReadableByteStreamController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableByteStreamController; +type _ReadableStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStream; +type _ReadableStreamBYOBReader = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamBYOBReader; +type _ReadableStreamBYOBRequest = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamBYOBRequest; +type _ReadableStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamDefaultController; +type _ReadableStreamDefaultReader = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").ReadableStreamDefaultReader; +type _TextDecoderStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TextDecoderStream; +type _TextEncoderStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TextEncoderStream; +type _TransformStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TransformStream; +type _TransformStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").TransformStreamDefaultController; +type _WritableStream = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStream; +type _WritableStreamDefaultController = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStreamDefaultController; +type _WritableStreamDefaultWriter = typeof globalThis extends { onmessage: any } ? {} + : import("stream/web").WritableStreamDefaultWriter; + +declare module "stream/web" { + // stub module, pending copy&paste from .d.ts or manual impl + // copy from lib.dom.d.ts + interface ReadableWritablePair { + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream + * through a transform stream (or any other { writable, readable } + * pair). It simply pipes the stream into the writable side of the + * supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + */ + writable: WritableStream; + } + interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. + * The way in which the piping process behaves under various error + * conditions can be customized with a number of passed options. It + * returns a promise that fulfills when the piping process completes + * successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate + * as follows: + * + * An error in this source readable stream will abort destination, + * unless preventAbort is truthy. The returned promise will be rejected + * with the source's error, or with any error that occurs during + * aborting the destination. + * + * An error in destination will cancel this source readable stream, + * unless preventCancel is truthy. The returned promise will be rejected + * with the destination's error, or with any error that occurs during + * canceling the source. + * + * When this source readable stream closes, destination will be closed, + * unless preventClose is truthy. The returned promise will be fulfilled + * once this process completes, unless an error is encountered while + * closing the destination, in which case it will be rejected with that + * error. + * + * If destination starts out closed or closing, this source readable + * stream will be canceled, unless preventCancel is true. The returned + * promise will be rejected with an error indicating piping to a closed + * stream failed, or with any error that occurs during canceling the + * source. + * + * The signal option can be set to an AbortSignal to allow aborting an + * ongoing pipe operation via the corresponding AbortController. In this + * case, this source readable stream will be canceled, and destination + * aborted, unless the respective options preventCancel or preventAbort + * are set. + */ + preventClose?: boolean; + signal?: AbortSignal; + } + interface ReadableStreamGenericReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + } + type ReadableStreamController = ReadableStreamDefaultController; + interface ReadableStreamReadValueResult { + done: false; + value: T; + } + interface ReadableStreamReadDoneResult { + done: true; + value?: T; + } + type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; + interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; + } + interface UnderlyingSinkAbortCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSinkCloseCallback { + (): void | PromiseLike; + } + interface UnderlyingSinkStartCallback { + (controller: WritableStreamDefaultController): any; + } + interface UnderlyingSinkWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; + } + interface UnderlyingSourceCancelCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSourcePullCallback { + (controller: ReadableStreamController): void | PromiseLike; + } + interface UnderlyingSourceStartCallback { + (controller: ReadableStreamController): any; + } + interface TransformerFlushCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerStartCallback { + (controller: TransformStreamDefaultController): any; + } + interface TransformerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerCancelCallback { + (reason: any): void | PromiseLike; + } + interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: "bytes"; + } + interface UnderlyingSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: UnderlyingSourcePullCallback; + start?: UnderlyingSourceStartCallback; + type?: undefined; + } + interface UnderlyingSink { + abort?: UnderlyingSinkAbortCallback; + close?: UnderlyingSinkCloseCallback; + start?: UnderlyingSinkStartCallback; + type?: undefined; + write?: UnderlyingSinkWriteCallback; + } + interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; + } + interface ReadableStreamAsyncIterator extends NodeJS.AsyncIterator { + [Symbol.asyncIterator](): ReadableStreamAsyncIterator; + } + /** This Streams API interface represents a readable stream of byte data. */ + interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; + getReader(): ReadableStreamDefaultReader; + getReader(options?: ReadableStreamGetReaderOptions): ReadableStreamReader; + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; + values(options?: { preventCancel?: boolean }): ReadableStreamAsyncIterator; + [Symbol.asyncIterator](): ReadableStreamAsyncIterator; + } + const ReadableStream: { + prototype: ReadableStream; + from(iterable: Iterable | AsyncIterable): ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + }; + type ReadableStreamReaderMode = "byob"; + interface ReadableStreamGetReaderOptions { + /** + * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode?: ReadableStreamReaderMode; + } + type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader; + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */ + interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read( + view: T, + options?: { + min?: number; + }, + ): Promise>; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + } + const ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new(stream: ReadableStream): ReadableStreamDefaultReader; + }; + const ReadableStreamBYOBReader: { + prototype: ReadableStreamBYOBReader; + new(stream: ReadableStream): ReadableStreamBYOBReader; + }; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ + interface ReadableStreamBYOBRequest { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + readonly view: ArrayBufferView | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBufferView): void; + } + const ReadableStreamBYOBRequest: { + prototype: ReadableStreamBYOBRequest; + new(): ReadableStreamBYOBRequest; + }; + interface ReadableByteStreamController { + readonly byobRequest: undefined; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; + } + const ReadableByteStreamController: { + prototype: ReadableByteStreamController; + new(): ReadableByteStreamController; + }; + interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(e?: any): void; + } + const ReadableStreamDefaultController: { + prototype: ReadableStreamDefaultController; + new(): ReadableStreamDefaultController; + }; + interface Transformer { + flush?: TransformerFlushCallback; + readableType?: undefined; + start?: TransformerStartCallback; + transform?: TransformerTransformCallback; + cancel?: TransformerCancelCallback; + writableType?: undefined; + } + interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const TransformStream: { + prototype: TransformStream; + new( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ): TransformStream; + }; + interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk?: O): void; + error(reason?: any): void; + terminate(): void; + } + const TransformStreamDefaultController: { + prototype: TransformStreamDefaultController; + new(): TransformStreamDefaultController; + }; + /** + * This Streams API interface provides a standard abstraction for writing + * streaming data to a destination, known as a sink. This object comes with + * built-in back pressure and queuing. + */ + interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + close(): Promise; + getWriter(): WritableStreamDefaultWriter; + } + const WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; + }; + /** + * This Streams API interface is the object returned by + * WritableStream.getWriter() and once created locks the < writer to the + * WritableStream ensuring that no other streams can write to the underlying + * sink. + */ + interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: W): Promise; + } + const WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new(stream: WritableStream): WritableStreamDefaultWriter; + }; + /** + * This Streams API interface represents a controller allowing control of a + * WritableStream's state. When constructing a WritableStream, the + * underlying sink is given a corresponding WritableStreamDefaultController + * instance to manipulate. + */ + interface WritableStreamDefaultController { + error(e?: any): void; + } + const WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new(): WritableStreamDefaultController; + }; + interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySize; + } + interface QueuingStrategySize { + (chunk?: T): number; + } + interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water + * mark. + * + * Note that the provided high water mark will not be validated ahead of + * time. Instead, if it is negative, NaN, or not a number, the resulting + * ByteLengthQueuingStrategy will cause the corresponding stream + * constructor to throw. + */ + highWaterMark: number; + } + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface ByteLengthQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(init: QueuingStrategyInit): ByteLengthQueuingStrategy; + }; + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface CountQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(init: QueuingStrategyInit): CountQueuingStrategy; + }; + interface TextEncoderStream { + /** Returns "utf-8". */ + readonly encoding: "utf-8"; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextEncoderStream: { + prototype: TextEncoderStream; + new(): TextEncoderStream; + }; + interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; + } + type BufferSource = ArrayBufferView | ArrayBuffer; + interface TextDecoderStream { + /** Returns encoding's name, lower cased. */ + readonly encoding: string; + /** Returns `true` if error mode is "fatal", and `false` otherwise. */ + readonly fatal: boolean; + /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */ + readonly ignoreBOM: boolean; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextDecoderStream: { + prototype: TextDecoderStream; + new(encoding?: string, options?: TextDecoderOptions): TextDecoderStream; + }; + interface CompressionStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const CompressionStream: { + prototype: CompressionStream; + new(format: "deflate" | "deflate-raw" | "gzip"): CompressionStream; + }; + interface DecompressionStream { + readonly writable: WritableStream; + readonly readable: ReadableStream; + } + const DecompressionStream: { + prototype: DecompressionStream; + new(format: "deflate" | "deflate-raw" | "gzip"): DecompressionStream; + }; + + global { + interface ByteLengthQueuingStrategy extends _ByteLengthQueuingStrategy {} + /** + * `ByteLengthQueuingStrategy` class is a global reference for `import { ByteLengthQueuingStrategy } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-bytelengthqueuingstrategy + * @since v18.0.0 + */ + var ByteLengthQueuingStrategy: typeof globalThis extends { onmessage: any; ByteLengthQueuingStrategy: infer T } + ? T + : typeof import("stream/web").ByteLengthQueuingStrategy; + + interface CompressionStream extends _CompressionStream {} + /** + * `CompressionStream` class is a global reference for `import { CompressionStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-compressionstream + * @since v18.0.0 + */ + var CompressionStream: typeof globalThis extends { + onmessage: any; + // CompressionStream, DecompressionStream and ReportingObserver was introduced in the same commit. + // If ReportingObserver check is removed, the type here will form a circular reference in TS5.0+lib.dom.d.ts + ReportingObserver: any; + CompressionStream: infer T; + } ? T + // TS 4.8, 4.9, 5.0 + : typeof globalThis extends { onmessage: any; TransformStream: { prototype: infer T } } ? { + prototype: T; + new(format: "deflate" | "deflate-raw" | "gzip"): T; + } + : typeof import("stream/web").CompressionStream; + + interface CountQueuingStrategy extends _CountQueuingStrategy {} + /** + * `CountQueuingStrategy` class is a global reference for `import { CountQueuingStrategy } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-countqueuingstrategy + * @since v18.0.0 + */ + var CountQueuingStrategy: typeof globalThis extends { onmessage: any; CountQueuingStrategy: infer T } ? T + : typeof import("stream/web").CountQueuingStrategy; + + interface DecompressionStream extends _DecompressionStream {} + /** + * `DecompressionStream` class is a global reference for `import { DecompressionStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-decompressionstream + * @since v18.0.0 + */ + var DecompressionStream: typeof globalThis extends { + onmessage: any; + // CompressionStream, DecompressionStream and ReportingObserver was introduced in the same commit. + // If ReportingObserver check is removed, the type here will form a circular reference in TS5.0+lib.dom.d.ts + ReportingObserver: any; + DecompressionStream: infer T extends object; + } ? T + // TS 4.8, 4.9, 5.0 + : typeof globalThis extends { onmessage: any; TransformStream: { prototype: infer T } } ? { + prototype: T; + new(format: "deflate" | "deflate-raw" | "gzip"): T; + } + : typeof import("stream/web").DecompressionStream; + + interface QueuingStrategy extends _QueuingStrategy {} + + interface ReadableByteStreamController extends _ReadableByteStreamController {} + /** + * `ReadableByteStreamController` class is a global reference for `import { ReadableByteStreamController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablebytestreamcontroller + * @since v18.0.0 + */ + var ReadableByteStreamController: typeof globalThis extends + { onmessage: any; ReadableByteStreamController: infer T } ? T + : typeof import("stream/web").ReadableByteStreamController; + + interface ReadableStream extends _ReadableStream {} + /** + * `ReadableStream` class is a global reference for `import { ReadableStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestream + * @since v18.0.0 + */ + var ReadableStream: typeof globalThis extends { onmessage: any; ReadableStream: infer T } ? T + : typeof import("stream/web").ReadableStream; + + interface ReadableStreamBYOBReader extends _ReadableStreamBYOBReader {} + /** + * `ReadableStreamBYOBReader` class is a global reference for `import { ReadableStreamBYOBReader } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreambyobreader + * @since v18.0.0 + */ + var ReadableStreamBYOBReader: typeof globalThis extends { onmessage: any; ReadableStreamBYOBReader: infer T } + ? T + : typeof import("stream/web").ReadableStreamBYOBReader; + + interface ReadableStreamBYOBRequest extends _ReadableStreamBYOBRequest {} + /** + * `ReadableStreamBYOBRequest` class is a global reference for `import { ReadableStreamBYOBRequest } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreambyobrequest + * @since v18.0.0 + */ + var ReadableStreamBYOBRequest: typeof globalThis extends { onmessage: any; ReadableStreamBYOBRequest: infer T } + ? T + : typeof import("stream/web").ReadableStreamBYOBRequest; + + interface ReadableStreamDefaultController extends _ReadableStreamDefaultController {} + /** + * `ReadableStreamDefaultController` class is a global reference for `import { ReadableStreamDefaultController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreamdefaultcontroller + * @since v18.0.0 + */ + var ReadableStreamDefaultController: typeof globalThis extends + { onmessage: any; ReadableStreamDefaultController: infer T } ? T + : typeof import("stream/web").ReadableStreamDefaultController; + + interface ReadableStreamDefaultReader extends _ReadableStreamDefaultReader {} + /** + * `ReadableStreamDefaultReader` class is a global reference for `import { ReadableStreamDefaultReader } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-readablestreamdefaultreader + * @since v18.0.0 + */ + var ReadableStreamDefaultReader: typeof globalThis extends + { onmessage: any; ReadableStreamDefaultReader: infer T } ? T + : typeof import("stream/web").ReadableStreamDefaultReader; + + interface TextDecoderStream extends _TextDecoderStream {} + /** + * `TextDecoderStream` class is a global reference for `import { TextDecoderStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-textdecoderstream + * @since v18.0.0 + */ + var TextDecoderStream: typeof globalThis extends { onmessage: any; TextDecoderStream: infer T } ? T + : typeof import("stream/web").TextDecoderStream; + + interface TextEncoderStream extends _TextEncoderStream {} + /** + * `TextEncoderStream` class is a global reference for `import { TextEncoderStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-textencoderstream + * @since v18.0.0 + */ + var TextEncoderStream: typeof globalThis extends { onmessage: any; TextEncoderStream: infer T } ? T + : typeof import("stream/web").TextEncoderStream; + + interface TransformStream extends _TransformStream {} + /** + * `TransformStream` class is a global reference for `import { TransformStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-transformstream + * @since v18.0.0 + */ + var TransformStream: typeof globalThis extends { onmessage: any; TransformStream: infer T } ? T + : typeof import("stream/web").TransformStream; + + interface TransformStreamDefaultController extends _TransformStreamDefaultController {} + /** + * `TransformStreamDefaultController` class is a global reference for `import { TransformStreamDefaultController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-transformstreamdefaultcontroller + * @since v18.0.0 + */ + var TransformStreamDefaultController: typeof globalThis extends + { onmessage: any; TransformStreamDefaultController: infer T } ? T + : typeof import("stream/web").TransformStreamDefaultController; + + interface WritableStream extends _WritableStream {} + /** + * `WritableStream` class is a global reference for `import { WritableStream } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-writablestream + * @since v18.0.0 + */ + var WritableStream: typeof globalThis extends { onmessage: any; WritableStream: infer T } ? T + : typeof import("stream/web").WritableStream; + + interface WritableStreamDefaultController extends _WritableStreamDefaultController {} + /** + * `WritableStreamDefaultController` class is a global reference for `import { WritableStreamDefaultController } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-writablestreamdefaultcontroller + * @since v18.0.0 + */ + var WritableStreamDefaultController: typeof globalThis extends + { onmessage: any; WritableStreamDefaultController: infer T } ? T + : typeof import("stream/web").WritableStreamDefaultController; + + interface WritableStreamDefaultWriter extends _WritableStreamDefaultWriter {} + /** + * `WritableStreamDefaultWriter` class is a global reference for `import { WritableStreamDefaultWriter } from 'node:stream/web'`. + * https://nodejs.org/api/globals.html#class-writablestreamdefaultwriter + * @since v18.0.0 + */ + var WritableStreamDefaultWriter: typeof globalThis extends + { onmessage: any; WritableStreamDefaultWriter: infer T } ? T + : typeof import("stream/web").WritableStreamDefaultWriter; + } +} +declare module "node:stream/web" { + export * from "stream/web"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/string_decoder.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/string_decoder.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3632c163006ba2e31880cfcf61f4e9944265d309 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,67 @@ +/** + * The `node:string_decoder` module provides an API for decoding `Buffer` objects + * into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 + * characters. It can be accessed using: + * + * ```js + * import { StringDecoder } from 'node:string_decoder'; + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * import { StringDecoder } from 'node:string_decoder'; + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); // Prints: ¢ + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); // Prints: € + * ``` + * + * When a `Buffer` instance is written to the `StringDecoder` instance, an + * internal buffer is used to ensure that the decoded string does not contain + * any incomplete multibyte characters. These are held in the buffer until the + * next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. + * + * In the following example, the three UTF-8 encoded bytes of the European Euro + * symbol (`€`) are written over three separate operations: + * + * ```js + * import { StringDecoder } from 'node:string_decoder'; + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); // Prints: € + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/string_decoder.js) + */ +declare module "string_decoder" { + class StringDecoder { + constructor(encoding?: BufferEncoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at + * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the + * returned string and stored in an internal buffer for the next call to `stringDecoder.write()` or `stringDecoder.end()`. + * @since v0.1.99 + * @param buffer The bytes to decode. + */ + write(buffer: string | Buffer | NodeJS.ArrayBufferView): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes + * representing incomplete UTF-8 and UTF-16 characters will be replaced with + * substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()` is performed before returning the remaining input. + * After `end()` is called, the `stringDecoder` object can be reused for new input. + * @since v0.9.3 + * @param buffer The bytes to decode. + */ + end(buffer?: string | Buffer | NodeJS.ArrayBufferView): string; + } +} +declare module "node:string_decoder" { + export * from "string_decoder"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/test.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/test.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d397dbaabf074affaedd63b26c0259dcfd482dd3 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/test.d.ts @@ -0,0 +1,2334 @@ +/** + * The `node:test` module facilitates the creation of JavaScript tests. + * To access it: + * + * ```js + * import test from 'node:test'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'node:test'; + * ``` + * + * Tests created via the `test` module consist of a single function that is + * processed in one of three ways: + * + * 1. A synchronous function that is considered failing if it throws an exception, + * and is considered passing otherwise. + * 2. A function that returns a `Promise` that is considered failing if the `Promise` rejects, and is considered passing if the `Promise` fulfills. + * 3. A function that receives a callback function. If the callback receives any + * truthy value as its first argument, the test is considered failing. If a + * falsy value is passed as the first argument to the callback, the test is + * considered passing. If the test function receives a callback function and + * also returns a `Promise`, the test will fail. + * + * The following example illustrates how tests are written using the `test` module. + * + * ```js + * test('synchronous passing test', (t) => { + * // This test passes because it does not throw an exception. + * assert.strictEqual(1, 1); + * }); + * + * test('synchronous failing test', (t) => { + * // This test fails because it throws an exception. + * assert.strictEqual(1, 2); + * }); + * + * test('asynchronous passing test', async (t) => { + * // This test passes because the Promise returned by the async + * // function is settled and not rejected. + * assert.strictEqual(1, 1); + * }); + * + * test('asynchronous failing test', async (t) => { + * // This test fails because the Promise returned by the async + * // function is rejected. + * assert.strictEqual(1, 2); + * }); + * + * test('failing test using Promises', (t) => { + * // Promises can be used directly as well. + * return new Promise((resolve, reject) => { + * setImmediate(() => { + * reject(new Error('this will cause the test to fail')); + * }); + * }); + * }); + * + * test('callback passing test', (t, done) => { + * // done() is the callback function. When the setImmediate() runs, it invokes + * // done() with no arguments. + * setImmediate(done); + * }); + * + * test('callback failing test', (t, done) => { + * // When the setImmediate() runs, done() is invoked with an Error object and + * // the test fails. + * setImmediate(() => { + * done(new Error('callback failure')); + * }); + * }); + * ``` + * + * If any tests fail, the process exit code is set to `1`. + * @since v18.0.0, v16.17.0 + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/test.js) + */ +declare module "node:test" { + import { Readable } from "node:stream"; + import TestFn = test.TestFn; + import TestOptions = test.TestOptions; + /** + * The `test()` function is the value imported from the `test` module. Each + * invocation of this function results in reporting the test to the `TestsStream`. + * + * The `TestContext` object passed to the `fn` argument can be used to perform + * actions related to the current test. Examples include skipping the test, adding + * additional diagnostic information, or creating subtests. + * + * `test()` returns a `Promise` that fulfills once the test completes. + * if `test()` is called within a suite, it fulfills immediately. + * The return value can usually be discarded for top level tests. + * However, the return value from subtests should be used to prevent the parent + * test from finishing first and cancelling the subtest + * as shown in the following example. + * + * ```js + * test('top level test', async (t) => { + * // The setTimeout() in the following subtest would cause it to outlive its + * // parent test if 'await' is removed on the next line. Once the parent test + * // completes, it will cancel any outstanding subtests. + * await t.test('longer running subtest', async (t) => { + * return new Promise((resolve, reject) => { + * setTimeout(resolve, 1000); + * }); + * }); + * }); + * ``` + * + * The `timeout` option can be used to fail the test if it takes longer than `timeout` milliseconds to complete. However, it is not a reliable mechanism for + * canceling tests because a running test might block the application thread and + * thus prevent the scheduled cancellation. + * @since v18.0.0, v16.17.0 + * @param name The name of the test, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the test. + * @param fn The function under test. The first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + * @return Fulfilled with `undefined` once the test completes, or immediately if the test runs within a suite. + */ + function test(name?: string, fn?: TestFn): Promise; + function test(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function test(options?: TestOptions, fn?: TestFn): Promise; + function test(fn?: TestFn): Promise; + namespace test { + export { test }; + export { suite as describe, test as it }; + } + namespace test { + /** + * **Note:** `shard` is used to horizontally parallelize test running across + * machines or processes, ideal for large-scale executions across varied + * environments. It's incompatible with `watch` mode, tailored for rapid + * code iteration by automatically rerunning tests on file changes. + * + * ```js + * import { tap } from 'node:test/reporters'; + * import { run } from 'node:test'; + * import process from 'node:process'; + * import path from 'node:path'; + * + * run({ files: [path.resolve('./tests/test.js')] }) + * .compose(tap) + * .pipe(process.stdout); + * ``` + * @since v18.9.0, v16.19.0 + * @param options Configuration options for running tests. + */ + function run(options?: RunOptions): TestsStream; + /** + * The `suite()` function is imported from the `node:test` module. + * @param name The name of the suite, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the suite. This supports the same options as {@link test}. + * @param fn The suite function declaring nested tests and suites. The first argument to this function is a {@link SuiteContext} object. + * @return Immediately fulfilled with `undefined`. + * @since v20.13.0 + */ + function suite(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function suite(name?: string, fn?: SuiteFn): Promise; + function suite(options?: TestOptions, fn?: SuiteFn): Promise; + function suite(fn?: SuiteFn): Promise; + namespace suite { + /** + * Shorthand for skipping a suite. This is the same as calling {@link suite} with `options.skip` set to `true`. + * @since v20.13.0 + */ + function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function skip(name?: string, fn?: SuiteFn): Promise; + function skip(options?: TestOptions, fn?: SuiteFn): Promise; + function skip(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `TODO`. This is the same as calling {@link suite} with `options.todo` set to `true`. + * @since v20.13.0 + */ + function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function todo(name?: string, fn?: SuiteFn): Promise; + function todo(options?: TestOptions, fn?: SuiteFn): Promise; + function todo(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `only`. This is the same as calling {@link suite} with `options.only` set to `true`. + * @since v20.13.0 + */ + function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function only(name?: string, fn?: SuiteFn): Promise; + function only(options?: TestOptions, fn?: SuiteFn): Promise; + function only(fn?: SuiteFn): Promise; + } + /** + * Shorthand for skipping a test. This is the same as calling {@link test} with `options.skip` set to `true`. + * @since v20.2.0 + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function skip(name?: string, fn?: TestFn): Promise; + function skip(options?: TestOptions, fn?: TestFn): Promise; + function skip(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `TODO`. This is the same as calling {@link test} with `options.todo` set to `true`. + * @since v20.2.0 + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function todo(name?: string, fn?: TestFn): Promise; + function todo(options?: TestOptions, fn?: TestFn): Promise; + function todo(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `only`. This is the same as calling {@link test} with `options.only` set to `true`. + * @since v20.2.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function only(name?: string, fn?: TestFn): Promise; + function only(options?: TestOptions, fn?: TestFn): Promise; + function only(fn?: TestFn): Promise; + /** + * The type of a function passed to {@link test}. The first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + */ + type TestFn = (t: TestContext, done: (result?: any) => void) => void | Promise; + /** + * The type of a suite test function. The argument to this function is a {@link SuiteContext} object. + */ + type SuiteFn = (s: SuiteContext) => void | Promise; + interface TestShard { + /** + * A positive integer between 1 and `total` that specifies the index of the shard to run. + */ + index: number; + /** + * A positive integer that specifies the total number of shards to split the test files to. + */ + total: number; + } + interface RunOptions { + /** + * If a number is provided, then that many test processes would run in parallel, where each process corresponds to one test file. + * If `true`, it would run `os.availableParallelism() - 1` test files in parallel. If `false`, it would only run one test file at a time. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * Specifies the current working directory to be used by the test runner. + * Serves as the base path for resolving files according to the + * [test runner execution model](https://nodejs.org/docs/latest-v24.x/api/test.html#test-runner-execution-model). + * @since v23.0.0 + * @default process.cwd() + */ + cwd?: string | undefined; + /** + * An array containing the list of files to run. If omitted, files are run according to the + * [test runner execution model](https://nodejs.org/docs/latest-v24.x/api/test.html#test-runner-execution-model). + */ + files?: readonly string[] | undefined; + /** + * Configures the test runner to exit the process once all known + * tests have finished executing even if the event loop would + * otherwise remain active. + * @default false + */ + forceExit?: boolean | undefined; + /** + * An array containing the list of glob patterns to match test files. + * This option cannot be used together with `files`. If omitted, files are run according to the + * [test runner execution model](https://nodejs.org/docs/latest-v24.x/api/test.html#test-runner-execution-model). + * @since v22.6.0 + */ + globPatterns?: readonly string[] | undefined; + /** + * Sets inspector port of test child process. + * This can be a number, or a function that takes no arguments and returns a + * number. If a nullish value is provided, each process gets its own port, + * incremented from the primary's `process.debugPort`. This option is ignored + * if the `isolation` option is set to `'none'` as no child processes are + * spawned. + * @default undefined + */ + inspectPort?: number | (() => number) | undefined; + /** + * Configures the type of test isolation. If set to + * `'process'`, each test file is run in a separate child process. If set to + * `'none'`, all test files run in the current process. + * @default 'process' + * @since v22.8.0 + */ + isolation?: "process" | "none" | undefined; + /** + * If truthy, the test context will only run tests that have the `only` option set + */ + only?: boolean | undefined; + /** + * A function that accepts the `TestsStream` instance and can be used to setup listeners before any tests are run. + * @default undefined + */ + setup?: ((reporter: TestsStream) => void | Promise) | undefined; + /** + * An array of CLI flags to pass to the `node` executable when + * spawning the subprocesses. This option has no effect when `isolation` is `'none`'. + * @since v22.10.0 + * @default [] + */ + execArgv?: readonly string[] | undefined; + /** + * An array of CLI flags to pass to each test file when spawning the + * subprocesses. This option has no effect when `isolation` is `'none'`. + * @since v22.10.0 + * @default [] + */ + argv?: readonly string[] | undefined; + /** + * Allows aborting an in-progress test execution. + */ + signal?: AbortSignal | undefined; + /** + * If provided, only run tests whose name matches the provided pattern. + * Strings are interpreted as JavaScript regular expressions. + * @default undefined + */ + testNamePatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * A String, RegExp or a RegExp Array, that can be used to exclude running tests whose + * name matches the provided pattern. Test name patterns are interpreted as JavaScript + * regular expressions. For each test that is executed, any corresponding test hooks, + * such as `beforeEach()`, are also run. + * @default undefined + * @since v22.1.0 + */ + testSkipPatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * The number of milliseconds after which the test execution will fail. + * If unspecified, subtests inherit this value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + /** + * Whether to run in watch mode or not. + * @default false + */ + watch?: boolean | undefined; + /** + * Running tests in a specific shard. + * @default undefined + */ + shard?: TestShard | undefined; + /** + * enable [code coverage](https://nodejs.org/docs/latest-v24.x/api/test.html#collecting-code-coverage) collection. + * @since v22.10.0 + * @default false + */ + coverage?: boolean | undefined; + /** + * Excludes specific files from code coverage + * using a glob pattern, which can match both absolute and relative file paths. + * This property is only applicable when `coverage` was set to `true`. + * If both `coverageExcludeGlobs` and `coverageIncludeGlobs` are provided, + * files must meet **both** criteria to be included in the coverage report. + * @since v22.10.0 + * @default undefined + */ + coverageExcludeGlobs?: string | readonly string[] | undefined; + /** + * Includes specific files in code coverage + * using a glob pattern, which can match both absolute and relative file paths. + * This property is only applicable when `coverage` was set to `true`. + * If both `coverageExcludeGlobs` and `coverageIncludeGlobs` are provided, + * files must meet **both** criteria to be included in the coverage report. + * @since v22.10.0 + * @default undefined + */ + coverageIncludeGlobs?: string | readonly string[] | undefined; + /** + * Require a minimum percent of covered lines. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + lineCoverage?: number | undefined; + /** + * Require a minimum percent of covered branches. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + branchCoverage?: number | undefined; + /** + * Require a minimum percent of covered functions. If code + * coverage does not reach the threshold specified, the process will exit with code `1`. + * @since v22.10.0 + * @default 0 + */ + functionCoverage?: number | undefined; + } + /** + * A successful call to `run()` will return a new `TestsStream` object, streaming a series of events representing the execution of the tests. + * + * Some of the events are guaranteed to be emitted in the same order as the tests are defined, while others are emitted in the order that the tests execute. + * @since v18.9.0, v16.19.0 + */ + interface TestsStream extends Readable { + addListener(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + addListener(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + addListener(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + addListener(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + addListener(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + addListener(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + addListener(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + addListener(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + addListener(event: "test:start", listener: (data: EventData.TestStart) => void): this; + addListener(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + addListener(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + addListener(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + addListener(event: "test:watch:drained", listener: () => void): this; + addListener(event: "test:watch:restarted", listener: () => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + emit(event: "test:coverage", data: EventData.TestCoverage): boolean; + emit(event: "test:complete", data: EventData.TestComplete): boolean; + emit(event: "test:dequeue", data: EventData.TestDequeue): boolean; + emit(event: "test:diagnostic", data: EventData.TestDiagnostic): boolean; + emit(event: "test:enqueue", data: EventData.TestEnqueue): boolean; + emit(event: "test:fail", data: EventData.TestFail): boolean; + emit(event: "test:pass", data: EventData.TestPass): boolean; + emit(event: "test:plan", data: EventData.TestPlan): boolean; + emit(event: "test:start", data: EventData.TestStart): boolean; + emit(event: "test:stderr", data: EventData.TestStderr): boolean; + emit(event: "test:stdout", data: EventData.TestStdout): boolean; + emit(event: "test:summary", data: EventData.TestSummary): boolean; + emit(event: "test:watch:drained"): boolean; + emit(event: "test:watch:restarted"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + on(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + on(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + on(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + on(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + on(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + on(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + on(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + on(event: "test:start", listener: (data: EventData.TestStart) => void): this; + on(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + on(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + on(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + on(event: "test:watch:drained", listener: () => void): this; + on(event: "test:watch:restarted", listener: () => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + once(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + once(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + once(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + once(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + once(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + once(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + once(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + once(event: "test:start", listener: (data: EventData.TestStart) => void): this; + once(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + once(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + once(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + once(event: "test:watch:drained", listener: () => void): this; + once(event: "test:watch:restarted", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + prependListener(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + prependListener(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + prependListener(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + prependListener(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + prependListener(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + prependListener(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + prependListener(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + prependListener(event: "test:start", listener: (data: EventData.TestStart) => void): this; + prependListener(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + prependListener(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + prependListener(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + prependListener(event: "test:watch:drained", listener: () => void): this; + prependListener(event: "test:watch:restarted", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "test:coverage", listener: (data: EventData.TestCoverage) => void): this; + prependOnceListener(event: "test:complete", listener: (data: EventData.TestComplete) => void): this; + prependOnceListener(event: "test:dequeue", listener: (data: EventData.TestDequeue) => void): this; + prependOnceListener(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; + prependOnceListener(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; + prependOnceListener(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + prependOnceListener(event: "test:pass", listener: (data: EventData.TestPass) => void): this; + prependOnceListener(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; + prependOnceListener(event: "test:start", listener: (data: EventData.TestStart) => void): this; + prependOnceListener(event: "test:stderr", listener: (data: EventData.TestStderr) => void): this; + prependOnceListener(event: "test:stdout", listener: (data: EventData.TestStdout) => void): this; + prependOnceListener(event: "test:summary", listener: (data: EventData.TestSummary) => void): this; + prependOnceListener(event: "test:watch:drained", listener: () => void): this; + prependOnceListener(event: "test:watch:restarted", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + } + namespace EventData { + interface Error extends globalThis.Error { + cause: globalThis.Error; + } + interface LocationInfo { + /** + * The column number where the test is defined, or + * `undefined` if the test was run through the REPL. + */ + column?: number; + /** + * The path of the test file, `undefined` if test was run through the REPL. + */ + file?: string; + /** + * The line number where the test is defined, or `undefined` if the test was run through the REPL. + */ + line?: number; + } + interface TestDiagnostic extends LocationInfo { + /** + * The diagnostic message. + */ + message: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The severity level of the diagnostic message. + * Possible values are: + * * `'info'`: Informational messages. + * * `'warn'`: Warnings. + * * `'error'`: Errors. + */ + level: "info" | "warn" | "error"; + } + interface TestCoverage { + /** + * An object containing the coverage report. + */ + summary: { + /** + * An array of coverage reports for individual files. + */ + files: Array<{ + /** + * The absolute path of the file. + */ + path: string; + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + /** + * An array of functions representing function coverage. + */ + functions: Array<{ + /** + * The name of the function. + */ + name: string; + /** + * The line number where the function is defined. + */ + line: number; + /** + * The number of times the function was called. + */ + count: number; + }>; + /** + * An array of branches representing branch coverage. + */ + branches: Array<{ + /** + * The line number where the branch is defined. + */ + line: number; + /** + * The number of times the branch was taken. + */ + count: number; + }>; + /** + * An array of lines representing line numbers and the number of times they were covered. + */ + lines: Array<{ + /** + * The line number. + */ + line: number; + /** + * The number of times the line was covered. + */ + count: number; + }>; + }>; + /** + * An object containing whether or not the coverage for + * each coverage type. + * @since v22.9.0 + */ + thresholds: { + /** + * The function coverage threshold. + */ + function: number; + /** + * The branch coverage threshold. + */ + branch: number; + /** + * The line coverage threshold. + */ + line: number; + }; + /** + * An object containing a summary of coverage for all files. + */ + totals: { + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + }; + /** + * The working directory when code coverage began. This + * is useful for displaying relative path names in case + * the tests changed the working directory of the Node.js process. + */ + workingDirectory: string; + }; + /** + * The nesting level of the test. + */ + nesting: number; + } + interface TestComplete extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * Whether the test passed or not. + */ + passed: boolean; + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test if it did not pass. + */ + error?: Error; + /** + * The type of the test, used to denote whether this is a suite. + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestDequeue extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The test type. Either `'suite'` or `'test'`. + * @since v22.15.0 + */ + type: "suite" | "test"; + } + interface TestEnqueue extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The test type. Either `'suite'` or `'test'`. + * @since v22.15.0 + */ + type: "suite" | "test"; + } + interface TestFail extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test. + */ + error: Error; + /** + * The type of the test, used to denote whether this is a suite. + * @since v20.0.0, v19.9.0, v18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestPass extends LocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * The type of the test, used to denote whether this is a suite. + * @since 20.0.0, 19.9.0, 18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; + } + interface TestPlan extends LocationInfo { + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The number of subtests that have ran. + */ + count: number; + } + interface TestStart extends LocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + } + interface TestStderr { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stderr`. + */ + message: string; + } + interface TestStdout { + /** + * The path of the test file. + */ + file: string; + /** + * The message written to `stdout`. + */ + message: string; + } + interface TestSummary { + /** + * An object containing the counts of various test results. + */ + counts: { + /** + * The total number of cancelled tests. + */ + cancelled: number; + /** + * The total number of passed tests. + */ + passed: number; + /** + * The total number of skipped tests. + */ + skipped: number; + /** + * The total number of suites run. + */ + suites: number; + /** + * The total number of tests run, excluding suites. + */ + tests: number; + /** + * The total number of TODO tests. + */ + todo: number; + /** + * The total number of top level tests and suites. + */ + topLevel: number; + }; + /** + * The duration of the test run in milliseconds. + */ + duration_ms: number; + /** + * The path of the test file that generated the + * summary. If the summary corresponds to multiple files, this value is + * `undefined`. + */ + file: string | undefined; + /** + * Indicates whether or not the test run is considered + * successful or not. If any error condition occurs, such as a failing test or + * unmet coverage threshold, this value will be set to `false`. + */ + success: boolean; + } + } + /** + * An instance of `TestContext` is passed to each test function in order to + * interact with the test runner. However, the `TestContext` constructor is not + * exposed as part of the API. + * @since v18.0.0, v16.17.0 + */ + interface TestContext { + /** + * An object containing assertion methods bound to the test context. + * The top-level functions from the `node:assert` module are exposed here for the purpose of creating test plans. + * + * **Note:** Some of the functions from `node:assert` contain type assertions. If these are called via the + * TestContext `assert` object, then the context parameter in the test's function signature **must be explicitly typed** + * (ie. the parameter must have a type annotation), otherwise an error will be raised by the TypeScript compiler: + * ```ts + * import { test, type TestContext } from 'node:test'; + * + * // The test function's context parameter must have a type annotation. + * test('example', (t: TestContext) => { + * t.assert.deepStrictEqual(actual, expected); + * }); + * + * // Omitting the type annotation will result in a compilation error. + * test('example', t => { + * t.assert.deepStrictEqual(actual, expected); // Error: 't' needs an explicit type annotation. + * }); + * ``` + * @since v22.2.0, v20.15.0 + */ + readonly assert: TestContextAssert; + /** + * This function is used to create a hook running before subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v20.1.0, v18.17.0 + */ + before(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running before each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + beforeEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook that runs after the current test finishes. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.13.0 + */ + after(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. The first argument to this function is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + afterEach(fn?: TestContextHookFn, options?: HookOptions): void; + /** + * This function is used to write diagnostics to the output. Any diagnostic + * information is included at the end of the test's results. This function does + * not return a value. + * + * ```js + * test('top level test', (t) => { + * t.diagnostic('A diagnostic message'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Message to be reported. + */ + diagnostic(message: string): void; + /** + * The absolute path of the test file that created the current test. If a test file imports + * additional modules that generate tests, the imported tests will return the path of the root test file. + * @since v22.6.0 + */ + readonly filePath: string | undefined; + /** + * The name of the test and each of its ancestors, separated by `>`. + * @since v22.3.0 + */ + readonly fullName: string; + /** + * The name of the test. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * This function is used to set the number of assertions and subtests that are expected to run + * within the test. If the number of assertions and subtests that run does not match the + * expected count, the test will fail. + * + * > Note: To make sure assertions are tracked, `t.assert` must be used instead of `assert` directly. + * + * ```js + * test('top level test', (t) => { + * t.plan(2); + * t.assert.ok('some relevant assertion here'); + * t.test('subtest', () => {}); + * }); + * ``` + * + * When working with asynchronous code, the `plan` function can be used to ensure that the + * correct number of assertions are run: + * + * ```js + * test('planning with streams', (t, done) => { + * function* generate() { + * yield 'a'; + * yield 'b'; + * yield 'c'; + * } + * const expected = ['a', 'b', 'c']; + * t.plan(expected.length); + * const stream = Readable.from(generate()); + * stream.on('data', (chunk) => { + * t.assert.strictEqual(chunk, expected.shift()); + * }); + * + * stream.on('end', () => { + * done(); + * }); + * }); + * ``` + * + * When using the `wait` option, you can control how long the test will wait for the expected assertions. + * For example, setting a maximum wait time ensures that the test will wait for asynchronous assertions + * to complete within the specified timeframe: + * + * ```js + * test('plan with wait: 2000 waits for async assertions', (t) => { + * t.plan(1, { wait: 2000 }); // Waits for up to 2 seconds for the assertion to complete. + * + * const asyncActivity = () => { + * setTimeout(() => { + * * t.assert.ok(true, 'Async assertion completed within the wait time'); + * }, 1000); // Completes after 1 second, within the 2-second wait time. + * }; + * + * asyncActivity(); // The test will pass because the assertion is completed in time. + * }); + * ``` + * + * Note: If a `wait` timeout is specified, it begins counting down only after the test function finishes executing. + * @since v22.2.0 + */ + plan(count: number, options?: TestContextPlanOptions): void; + /** + * If `shouldRunOnlyTests` is truthy, the test context will only run tests that + * have the `only` option set. Otherwise, all tests are run. If Node.js was not + * started with the `--test-only` command-line option, this function is a + * no-op. + * + * ```js + * test('top level test', (t) => { + * // The test context can be set to run subtests with the 'only' option. + * t.runOnly(true); + * return Promise.all([ + * t.test('this subtest is now skipped'), + * t.test('this subtest is run', { only: true }), + * ]); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param shouldRunOnlyTests Whether or not to run `only` tests. + */ + runOnly(shouldRunOnlyTests: boolean): void; + /** + * ```js + * test('top level test', async (t) => { + * await fetch('some/uri', { signal: t.signal }); + * }); + * ``` + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + /** + * This function causes the test's output to indicate the test as skipped. If `message` is provided, it is included in the output. Calling `skip()` does + * not terminate execution of the test function. This function does not return a + * value. + * + * ```js + * test('top level test', (t) => { + * // Make sure to return here as well if the test contains additional logic. + * t.skip('this is skipped'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional skip message. + */ + skip(message?: string): void; + /** + * This function adds a `TODO` directive to the test's output. If `message` is + * provided, it is included in the output. Calling `todo()` does not terminate + * execution of the test function. This function does not return a value. + * + * ```js + * test('top level test', (t) => { + * // This test is marked as `TODO` + * t.todo('this is a todo'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional `TODO` message. + */ + todo(message?: string): void; + /** + * This function is used to create subtests under the current test. This function behaves in + * the same fashion as the top level {@link test} function. + * @since v18.0.0 + * @param name The name of the test, which is displayed when reporting test results. + * Defaults to the `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Configuration options for the test. + * @param fn The function under test. This first argument to this function is a {@link TestContext} object. + * If the test uses callbacks, the callback function is passed as the second argument. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + test: typeof test; + /** + * This method polls a `condition` function until that function either returns + * successfully or the operation times out. + * @since v22.14.0 + * @param condition An assertion function that is invoked + * periodically until it completes successfully or the defined polling timeout + * elapses. Successful completion is defined as not throwing or rejecting. This + * function does not accept any arguments, and is allowed to return any value. + * @param options An optional configuration object for the polling operation. + * @returns Fulfilled with the value returned by `condition`. + */ + waitFor(condition: () => T, options?: TestContextWaitForOptions): Promise>; + /** + * Each test provides its own MockTracker instance. + */ + readonly mock: MockTracker; + } + interface TestContextAssert extends + Pick< + typeof import("assert"), + | "deepEqual" + | "deepStrictEqual" + | "doesNotMatch" + | "doesNotReject" + | "doesNotThrow" + | "equal" + | "fail" + | "ifError" + | "match" + | "notDeepEqual" + | "notDeepStrictEqual" + | "notEqual" + | "notStrictEqual" + | "ok" + | "partialDeepStrictEqual" + | "rejects" + | "strictEqual" + | "throws" + > + { + /** + * This function serializes `value` and writes it to the file specified by `path`. + * + * ```js + * test('snapshot test with default serialization', (t) => { + * t.assert.fileSnapshot({ value1: 1, value2: 2 }, './snapshots/snapshot.json'); + * }); + * ``` + * + * This function differs from `context.assert.snapshot()` in the following ways: + * + * * The snapshot file path is explicitly provided by the user. + * * Each snapshot file is limited to a single snapshot value. + * * No additional escaping is performed by the test runner. + * + * These differences allow snapshot files to better support features such as syntax + * highlighting. + * @since v22.14.0 + * @param value A value to serialize to a string. If Node.js was started with + * the [`--test-update-snapshots`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--test-update-snapshots) + * flag, the serialized value is written to + * `path`. Otherwise, the serialized value is compared to the contents of the + * existing snapshot file. + * @param path The file where the serialized `value` is written. + * @param options Optional configuration options. + */ + fileSnapshot(value: any, path: string, options?: AssertSnapshotOptions): void; + /** + * This function implements assertions for snapshot testing. + * ```js + * test('snapshot test with default serialization', (t) => { + * t.assert.snapshot({ value1: 1, value2: 2 }); + * }); + * + * test('snapshot test with custom serialization', (t) => { + * t.assert.snapshot({ value3: 3, value4: 4 }, { + * serializers: [(value) => JSON.stringify(value)] + * }); + * }); + * ``` + * @since v22.3.0 + * @param value A value to serialize to a string. If Node.js was started with + * the [`--test-update-snapshots`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--test-update-snapshots) + * flag, the serialized value is written to + * the snapshot file. Otherwise, the serialized value is compared to the + * corresponding value in the existing snapshot file. + */ + snapshot(value: any, options?: AssertSnapshotOptions): void; + /** + * A custom assertion function registered with `assert.register()`. + */ + [name: string]: (...args: any[]) => void; + } + interface AssertSnapshotOptions { + /** + * An array of synchronous functions used to serialize `value` into a string. + * `value` is passed as the only argument to the first serializer function. + * The return value of each serializer is passed as input to the next serializer. + * Once all serializers have run, the resulting value is coerced to a string. + * + * If no serializers are provided, the test runner's default serializers are used. + */ + serializers?: ReadonlyArray<(value: any) => any> | undefined; + } + interface TestContextPlanOptions { + /** + * The wait time for the plan: + * * If `true`, the plan waits indefinitely for all assertions and subtests to run. + * * If `false`, the plan performs an immediate check after the test function completes, + * without waiting for any pending assertions or subtests. + * Any assertions or subtests that complete after this check will not be counted towards the plan. + * * If a number, it specifies the maximum wait time in milliseconds + * before timing out while waiting for expected assertions and subtests to be matched. + * If the timeout is reached, the test will fail. + * @default false + */ + wait?: boolean | number | undefined; + } + interface TestContextWaitForOptions { + /** + * The number of milliseconds to wait after an unsuccessful + * invocation of `condition` before trying again. + * @default 50 + */ + interval?: number | undefined; + /** + * The poll timeout in milliseconds. If `condition` has not + * succeeded by the time this elapses, an error occurs. + * @default 1000 + */ + timeout?: number | undefined; + } + /** + * An instance of `SuiteContext` is passed to each suite function in order to + * interact with the test runner. However, the `SuiteContext` constructor is not + * exposed as part of the API. + * @since v18.7.0, v16.17.0 + */ + interface SuiteContext { + /** + * The absolute path of the test file that created the current suite. If a test file imports + * additional modules that generate suites, the imported suites will return the path of the root test file. + * @since v22.6.0 + */ + readonly filePath: string | undefined; + /** + * The name of the suite. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * Can be used to abort test subtasks when the test has been aborted. + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + } + interface TestOptions { + /** + * If a number is provided, then that many tests would run in parallel. + * If truthy, it would run (number of cpu cores - 1) tests in parallel. + * For subtests, it will be `Infinity` tests in parallel. + * If falsy, it would only run one test at a time. + * If unspecified, subtests inherit this value from their parent. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * If truthy, and the test context is configured to run `only` tests, then this test will be + * run. Otherwise, the test is skipped. + * @default false + */ + only?: boolean | undefined; + /** + * Allows aborting an in-progress test. + * @since v18.8.0 + */ + signal?: AbortSignal | undefined; + /** + * If truthy, the test is skipped. If a string is provided, that string is displayed in the + * test results as the reason for skipping the test. + * @default false + */ + skip?: boolean | string | undefined; + /** + * A number of milliseconds the test will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + * @since v18.7.0 + */ + timeout?: number | undefined; + /** + * If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in + * the test results as the reason why the test is `TODO`. + * @default false + */ + todo?: boolean | string | undefined; + /** + * The number of assertions and subtests expected to be run in the test. + * If the number of assertions run in the test does not match the number + * specified in the plan, the test will fail. + * @default undefined + * @since v22.2.0 + */ + plan?: number | undefined; + } + /** + * This function creates a hook that runs before executing a suite. + * + * ```js + * describe('tests', async () => { + * before(() => console.log('about to run some test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function before(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after executing a suite. + * + * ```js + * describe('tests', async () => { + * after(() => console.log('finished running tests')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function after(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs before each test in the current suite. + * + * ```js + * describe('tests', async () => { + * beforeEach(() => console.log('about to run a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function beforeEach(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after each test in the current suite. + * The `afterEach()` hook is run even if the test fails. + * + * ```js + * describe('tests', async () => { + * afterEach(() => console.log('finished running a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. + */ + function afterEach(fn?: HookFn, options?: HookOptions): void; + /** + * The hook function. The first argument is the context in which the hook is called. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type HookFn = (c: TestContext | SuiteContext, done: (result?: any) => void) => any; + /** + * The hook function. The first argument is a `TestContext` object. + * If the hook uses callbacks, the callback function is passed as the second argument. + */ + type TestContextHookFn = (t: TestContext, done: (result?: any) => void) => any; + /** + * Configuration options for hooks. + * @since v18.8.0 + */ + interface HookOptions { + /** + * Allows aborting an in-progress hook. + */ + signal?: AbortSignal | undefined; + /** + * A number of milliseconds the hook will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + } + interface MockFunctionOptions { + /** + * The number of times that the mock will use the behavior of `implementation`. + * Once the mock function has been called `times` times, + * it will automatically restore the behavior of `original`. + * This value must be an integer greater than zero. + * @default Infinity + */ + times?: number | undefined; + } + interface MockMethodOptions extends MockFunctionOptions { + /** + * If `true`, `object[methodName]` is treated as a getter. + * This option cannot be used with the `setter` option. + */ + getter?: boolean | undefined; + /** + * If `true`, `object[methodName]` is treated as a setter. + * This option cannot be used with the `getter` option. + */ + setter?: boolean | undefined; + } + type Mock = F & { + mock: MockFunctionContext; + }; + interface MockModuleOptions { + /** + * If false, each call to `require()` or `import()` generates a new mock module. + * If true, subsequent calls will return the same module mock, and the mock module is inserted into the CommonJS cache. + * @default false + */ + cache?: boolean | undefined; + /** + * The value to use as the mocked module's default export. + * + * If this value is not provided, ESM mocks do not include a default export. + * If the mock is a CommonJS or builtin module, this setting is used as the value of `module.exports`. + * If this value is not provided, CJS and builtin mocks use an empty object as the value of `module.exports`. + */ + defaultExport?: any; + /** + * An object whose keys and values are used to create the named exports of the mock module. + * + * If the mock is a CommonJS or builtin module, these values are copied onto `module.exports`. + * Therefore, if a mock is created with both named exports and a non-object default export, + * the mock will throw an exception when used as a CJS or builtin module. + */ + namedExports?: object | undefined; + } + /** + * The `MockTracker` class is used to manage mocking functionality. The test runner + * module provides a top level `mock` export which is a `MockTracker` instance. + * Each test also provides its own `MockTracker` instance via the test context's `mock` property. + * @since v19.1.0, v18.13.0 + */ + interface MockTracker { + /** + * This function is used to create a mock function. + * + * The following example creates a mock function that increments a counter by one + * on each invocation. The `times` option is used to modify the mock behavior such + * that the first two invocations add two to the counter instead of one. + * + * ```js + * test('mocks a counting function', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne, addTwo, { times: 2 }); + * + * assert.strictEqual(fn(), 2); + * assert.strictEqual(fn(), 4); + * assert.strictEqual(fn(), 5); + * assert.strictEqual(fn(), 6); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param original An optional function to create a mock on. + * @param implementation An optional function used as the mock implementation for `original`. This is useful for creating mocks that exhibit one behavior for a specified number of calls and + * then restore the behavior of `original`. + * @param options Optional configuration options for the mock function. + * @return The mocked function. The mocked function contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked function. + */ + fn undefined>( + original?: F, + options?: MockFunctionOptions, + ): Mock; + fn undefined, Implementation extends Function = F>( + original?: F, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock; + /** + * This function is used to create a mock on an existing object method. The + * following example demonstrates how a mock is created on an existing object + * method. + * + * ```js + * test('spies on an object method', (t) => { + * const number = { + * value: 5, + * subtract(a) { + * return this.value - a; + * }, + * }; + * + * t.mock.method(number, 'subtract'); + * assert.strictEqual(number.subtract.mock.calls.length, 0); + * assert.strictEqual(number.subtract(3), 2); + * assert.strictEqual(number.subtract.mock.calls.length, 1); + * + * const call = number.subtract.mock.calls[0]; + * + * assert.deepStrictEqual(call.arguments, [3]); + * assert.strictEqual(call.result, 2); + * assert.strictEqual(call.error, undefined); + * assert.strictEqual(call.target, undefined); + * assert.strictEqual(call.this, number); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param object The object whose method is being mocked. + * @param methodName The identifier of the method on `object` to mock. If `object[methodName]` is not a function, an error is thrown. + * @param implementation An optional function used as the mock implementation for `object[methodName]`. + * @param options Optional configuration options for the mock method. + * @return The mocked method. The mocked method contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked method. + */ + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation: Implementation, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method( + object: MockedObject, + methodName: keyof MockedObject, + options: MockMethodOptions, + ): Mock; + method( + object: MockedObject, + methodName: keyof MockedObject, + implementation: Function, + options: MockMethodOptions, + ): Mock; + /** + * This function is syntax sugar for `MockTracker.method` with `options.getter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<() => MockedObject[MethodName]>; + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<(() => MockedObject[MethodName]) | Implementation>; + /** + * This function is syntax sugar for `MockTracker.method` with `options.setter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<(value: MockedObject[MethodName]) => void>; + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<((value: MockedObject[MethodName]) => void) | Implementation>; + /** + * This function is used to mock the exports of ECMAScript modules, CommonJS modules, JSON modules, and + * Node.js builtin modules. Any references to the original module prior to mocking are not impacted. In + * order to enable module mocking, Node.js must be started with the + * [`--experimental-test-module-mocks`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--experimental-test-module-mocks) + * command-line flag. + * + * The following example demonstrates how a mock is created for a module. + * + * ```js + * test('mocks a builtin module in both module systems', async (t) => { + * // Create a mock of 'node:readline' with a named export named 'fn', which + * // does not exist in the original 'node:readline' module. + * const mock = t.mock.module('node:readline', { + * namedExports: { fn() { return 42; } }, + * }); + * + * let esmImpl = await import('node:readline'); + * let cjsImpl = require('node:readline'); + * + * // cursorTo() is an export of the original 'node:readline' module. + * assert.strictEqual(esmImpl.cursorTo, undefined); + * assert.strictEqual(cjsImpl.cursorTo, undefined); + * assert.strictEqual(esmImpl.fn(), 42); + * assert.strictEqual(cjsImpl.fn(), 42); + * + * mock.restore(); + * + * // The mock is restored, so the original builtin module is returned. + * esmImpl = await import('node:readline'); + * cjsImpl = require('node:readline'); + * + * assert.strictEqual(typeof esmImpl.cursorTo, 'function'); + * assert.strictEqual(typeof cjsImpl.cursorTo, 'function'); + * assert.strictEqual(esmImpl.fn, undefined); + * assert.strictEqual(cjsImpl.fn, undefined); + * }); + * ``` + * @since v22.3.0 + * @experimental + * @param specifier A string identifying the module to mock. + * @param options Optional configuration options for the mock module. + */ + module(specifier: string, options?: MockModuleOptions): MockModuleContext; + /** + * Creates a mock for a property value on an object. This allows you to track and control access to a specific property, + * including how many times it is read (getter) or written (setter), and to restore the original value after mocking. + * + * ```js + * test('mocks a property value', (t) => { + * const obj = { foo: 42 }; + * const prop = t.mock.property(obj, 'foo', 100); + * + * assert.strictEqual(obj.foo, 100); + * assert.strictEqual(prop.mock.accessCount(), 1); + * assert.strictEqual(prop.mock.accesses[0].type, 'get'); + * assert.strictEqual(prop.mock.accesses[0].value, 100); + * + * obj.foo = 200; + * assert.strictEqual(prop.mock.accessCount(), 2); + * assert.strictEqual(prop.mock.accesses[1].type, 'set'); + * assert.strictEqual(prop.mock.accesses[1].value, 200); + * + * prop.mock.restore(); + * assert.strictEqual(obj.foo, 42); + * }); + * ``` + * @since v24.3.0 + * @param object The object whose value is being mocked. + * @param propertyName The identifier of the property on `object` to mock. + * @param value An optional value used as the mock value + * for `object[propertyName]`. **Default:** The original property value. + * @returns A proxy to the mocked object. The mocked object contains a + * special `mock` property, which is an instance of [`MockPropertyContext`][], and + * can be used for inspecting and changing the behavior of the mocked property. + */ + property< + MockedObject extends object, + PropertyName extends keyof MockedObject, + >( + object: MockedObject, + property: PropertyName, + value?: MockedObject[PropertyName], + ): MockedObject & { mock: MockPropertyContext }; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker` and disassociates the mocks from the `MockTracker` instance. Once disassociated, the mocks can still be used, but the `MockTracker` instance can no longer be + * used to reset their behavior or + * otherwise interact with them. + * + * After each test completes, this function is called on the test context's `MockTracker`. If the global `MockTracker` is used extensively, calling this + * function manually is recommended. + * @since v19.1.0, v18.13.0 + */ + reset(): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker`. Unlike `mock.reset()`, `mock.restoreAll()` does + * not disassociate the mocks from the `MockTracker` instance. + * @since v19.1.0, v18.13.0 + */ + restoreAll(): void; + readonly timers: MockTimers; + } + const mock: MockTracker; + interface MockFunctionCall< + F extends Function, + ReturnType = F extends (...args: any) => infer T ? T + : F extends abstract new(...args: any) => infer T ? T + : unknown, + Args = F extends (...args: infer Y) => any ? Y + : F extends abstract new(...args: infer Y) => any ? Y + : unknown[], + > { + /** + * An array of the arguments passed to the mock function. + */ + arguments: Args; + /** + * If the mocked function threw then this property contains the thrown value. + */ + error: unknown | undefined; + /** + * The value returned by the mocked function. + * + * If the mocked function threw, it will be `undefined`. + */ + result: ReturnType | undefined; + /** + * An `Error` object whose stack can be used to determine the callsite of the mocked function invocation. + */ + stack: Error; + /** + * If the mocked function is a constructor, this field contains the class being constructed. + * Otherwise this will be `undefined`. + */ + target: F extends abstract new(...args: any) => any ? F : undefined; + /** + * The mocked function's `this` value. + */ + this: unknown; + } + /** + * The `MockFunctionContext` class is used to inspect or manipulate the behavior of + * mocks created via the `MockTracker` APIs. + * @since v19.1.0, v18.13.0 + */ + interface MockFunctionContext { + /** + * A getter that returns a copy of the internal array used to track calls to the + * mock. Each entry in the array is an object with the following properties. + * @since v19.1.0, v18.13.0 + */ + readonly calls: MockFunctionCall[]; + /** + * This function returns the number of times that this mock has been invoked. This + * function is more efficient than checking `ctx.calls.length` because `ctx.calls` is a getter that creates a copy of the internal call tracking array. + * @since v19.1.0, v18.13.0 + * @return The number of times that this mock has been invoked. + */ + callCount(): number; + /** + * This function is used to change the behavior of an existing mock. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, and then changes the mock implementation to a different function. + * + * ```js + * test('changes a mock behavior', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementation(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 5); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's new implementation. + */ + mockImplementation(implementation: F): void; + /** + * This function is used to change the behavior of an existing mock for a single + * invocation. Once invocation `onCall` has occurred, the mock will revert to + * whatever behavior it would have used had `mockImplementationOnce()` not been + * called. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, changes the mock implementation to a different function for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementationOnce(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 4); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's implementation for the invocation number specified by `onCall`. + * @param onCall The invocation number that will use `implementation`. If the specified invocation has already occurred then an exception is thrown. + */ + mockImplementationOnce(implementation: F, onCall?: number): void; + /** + * Resets the call history of the mock function. + * @since v19.3.0, v18.13.0 + */ + resetCalls(): void; + /** + * Resets the implementation of the mock function to its original behavior. The + * mock can still be used after calling this function. + * @since v19.1.0, v18.13.0 + */ + restore(): void; + } + /** + * @since v22.3.0 + * @experimental + */ + interface MockModuleContext { + /** + * Resets the implementation of the mock module. + * @since v22.3.0 + */ + restore(): void; + } + /** + * @since v24.3.0 + */ + class MockPropertyContext { + /** + * A getter that returns a copy of the internal array used to track accesses (get/set) to + * the mocked property. Each entry in the array is an object with the following properties: + */ + readonly accesses: Array<{ + type: "get" | "set"; + value: PropertyType; + stack: Error; + }>; + /** + * This function returns the number of times that the property was accessed. + * This function is more efficient than checking `ctx.accesses.length` because + * `ctx.accesses` is a getter that creates a copy of the internal access tracking array. + * @returns The number of times that the property was accessed (read or written). + */ + accessCount(): number; + /** + * This function is used to change the value returned by the mocked property getter. + * @param value The new value to be set as the mocked property value. + */ + mockImplementation(value: PropertyType): void; + /** + * This function is used to change the behavior of an existing mock for a single + * invocation. Once invocation `onAccess` has occurred, the mock will revert to + * whatever behavior it would have used had `mockImplementationOnce()` not been + * called. + * + * The following example creates a mock function using `t.mock.property()`, calls the + * mock property, changes the mock implementation to a different value for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * const obj = { foo: 1 }; + * + * const prop = t.mock.property(obj, 'foo', 5); + * + * assert.strictEqual(obj.foo, 5); + * prop.mock.mockImplementationOnce(25); + * assert.strictEqual(obj.foo, 25); + * assert.strictEqual(obj.foo, 5); + * }); + * ``` + * @param value The value to be used as the mock's + * implementation for the invocation number specified by `onAccess`. + * @param onAccess The invocation number that will use `value`. If + * the specified invocation has already occurred then an exception is thrown. + * **Default:** The number of the next invocation. + */ + mockImplementationOnce(value: PropertyType, onAccess?: number): void; + /** + * Resets the access history of the mocked property. + */ + resetAccesses(): void; + /** + * Resets the implementation of the mock property to its original behavior. The + * mock can still be used after calling this function. + */ + restore(): void; + } + interface MockTimersOptions { + apis: ReadonlyArray<"setInterval" | "setTimeout" | "setImmediate" | "Date">; + now?: number | Date | undefined; + } + /** + * Mocking timers is a technique commonly used in software testing to simulate and + * control the behavior of timers, such as `setInterval` and `setTimeout`, + * without actually waiting for the specified time intervals. + * + * The MockTimers API also allows for mocking of the `Date` constructor and + * `setImmediate`/`clearImmediate` functions. + * + * The `MockTracker` provides a top-level `timers` export + * which is a `MockTimers` instance. + * @since v20.4.0 + */ + interface MockTimers { + /** + * Enables timer mocking for the specified timers. + * + * **Note:** When you enable mocking for a specific timer, its associated + * clear function will also be implicitly mocked. + * + * **Note:** Mocking `Date` will affect the behavior of the mocked timers + * as they use the same internal clock. + * + * Example usage without setting initial time: + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['setInterval', 'Date'], now: 1234 }); + * ``` + * + * The above example enables mocking for the `Date` constructor, `setInterval` timer and + * implicitly mocks the `clearInterval` function. Only the `Date` constructor from `globalThis`, + * `setInterval` and `clearInterval` functions from `node:timers`, `node:timers/promises`, and `globalThis` will be mocked. + * + * Example usage with initial time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: 1000 }); + * ``` + * + * Example usage with initial Date object as time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: new Date() }); + * ``` + * + * Alternatively, if you call `mock.timers.enable()` without any parameters: + * + * All timers (`'setInterval'`, `'clearInterval'`, `'Date'`, `'setImmediate'`, `'clearImmediate'`, `'setTimeout'`, and `'clearTimeout'`) + * will be mocked. + * + * The `setInterval`, `clearInterval`, `setTimeout`, and `clearTimeout` functions from `node:timers`, `node:timers/promises`, + * and `globalThis` will be mocked. + * The `Date` constructor from `globalThis` will be mocked. + * + * If there is no initial epoch set, the initial date will be based on 0 in the Unix epoch. This is `January 1st, 1970, 00:00:00 UTC`. You can + * set an initial date by passing a now property to the `.enable()` method. This value will be used as the initial date for the mocked Date + * object. It can either be a positive integer, or another Date object. + * @since v20.4.0 + */ + enable(options?: MockTimersOptions): void; + /** + * You can use the `.setTime()` method to manually move the mocked date to another time. This method only accepts a positive integer. + * Note: This method will execute any mocked timers that are in the past from the new time. + * In the below example we are setting a new time for the mocked date. + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * test('sets the time of a date object', (context) => { + * // Optionally choose what to mock + * context.mock.timers.enable({ apis: ['Date'], now: 100 }); + * assert.strictEqual(Date.now(), 100); + * // Advance in time will also advance the date + * context.mock.timers.setTime(1000); + * context.mock.timers.tick(200); + * assert.strictEqual(Date.now(), 1200); + * }); + * ``` + */ + setTime(time: number): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTimers` instance and disassociates the mocks + * from the `MockTracker` instance. + * + * **Note:** After each test completes, this function is called on + * the test context's `MockTracker`. + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.reset(); + * ``` + * @since v20.4.0 + */ + reset(): void; + /** + * Advances time for all mocked timers. + * + * **Note:** This diverges from how `setTimeout` in Node.js behaves and accepts + * only positive numbers. In Node.js, `setTimeout` with negative numbers is + * only supported for web compatibility reasons. + * + * The following example mocks a `setTimeout` function and + * by using `.tick` advances in + * time triggering all pending timers. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Alternativelly, the `.tick` function can be called many times + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * const nineSecs = 9000; + * setTimeout(fn, nineSecs); + * + * const twoSeconds = 3000; + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Advancing time using `.tick` will also advance the time for any `Date` object + * created after the mock was enabled (if `Date` was also set to be mocked). + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * assert.strictEqual(Date.now(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * assert.strictEqual(fn.mock.callCount(), 1); + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * @since v20.4.0 + */ + tick(milliseconds: number): void; + /** + * Triggers all pending mocked timers immediately. If the `Date` object is also + * mocked, it will also advance the `Date` object to the furthest timer's time. + * + * The example below triggers all pending timers immediately, + * causing them to execute without any delay. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('runAll functions following the given order', (context) => { + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * const results = []; + * setTimeout(() => results.push(1), 9999); + * + * // Notice that if both timers have the same timeout, + * // the order of execution is guaranteed + * setTimeout(() => results.push(3), 8888); + * setTimeout(() => results.push(2), 8888); + * + * assert.deepStrictEqual(results, []); + * + * context.mock.timers.runAll(); + * assert.deepStrictEqual(results, [3, 2, 1]); + * // The Date object is also advanced to the furthest timer's time + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * + * **Note:** The `runAll()` function is specifically designed for + * triggering timers in the context of timer mocking. + * It does not have any effect on real-time system + * clocks or actual timers outside of the mocking environment. + * @since v20.4.0 + */ + runAll(): void; + /** + * Calls {@link MockTimers.reset()}. + */ + [Symbol.dispose](): void; + } + /** + * An object whose methods are used to configure available assertions on the + * `TestContext` objects in the current process. The methods from `node:assert` + * and snapshot testing functions are available by default. + * + * It is possible to apply the same configuration to all files by placing common + * configuration code in a module + * preloaded with `--require` or `--import`. + * @since v22.14.0 + */ + namespace assert { + /** + * Defines a new assertion function with the provided name and function. If an + * assertion already exists with the same name, it is overwritten. + * @since v22.14.0 + */ + function register(name: string, fn: (this: TestContext, ...args: any[]) => void): void; + } + /** + * @since v22.3.0 + */ + namespace snapshot { + /** + * This function is used to customize the default serialization mechanism used by the test runner. + * + * By default, the test runner performs serialization by calling `JSON.stringify(value, null, 2)` on the provided value. + * `JSON.stringify()` does have limitations regarding circular structures and supported data types. + * If a more robust serialization mechanism is required, this function should be used to specify a list of custom serializers. + * + * Serializers are called in order, with the output of the previous serializer passed as input to the next. + * The final result must be a string value. + * @since v22.3.0 + * @param serializers An array of synchronous functions used as the default serializers for snapshot tests. + */ + function setDefaultSnapshotSerializers(serializers: ReadonlyArray<(value: any) => any>): void; + /** + * This function is used to set a custom resolver for the location of the snapshot file used for snapshot testing. + * By default, the snapshot filename is the same as the entry point filename with `.snapshot` appended. + * @since v22.3.0 + * @param fn A function used to compute the location of the snapshot file. + * The function receives the path of the test file as its only argument. If the + * test is not associated with a file (for example in the REPL), the input is + * undefined. `fn()` must return a string specifying the location of the snapshot file. + */ + function setResolveSnapshotPath(fn: (path: string | undefined) => string): void; + } + } + type FunctionPropertyNames = { + [K in keyof T]: T[K] extends Function ? K : never; + }[keyof T]; + export = test; +} + +/** + * The `node:test/reporters` module exposes the builtin-reporters for `node:test`. + * To access it: + * + * ```js + * import test from 'node:test/reporters'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'node:test/reporters'; + * ``` + * @since v19.9.0 + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/test/reporters.js) + */ +declare module "node:test/reporters" { + import { Transform, TransformOptions } from "node:stream"; + import { EventData } from "node:test"; + + type TestEvent = + | { type: "test:coverage"; data: EventData.TestCoverage } + | { type: "test:complete"; data: EventData.TestComplete } + | { type: "test:dequeue"; data: EventData.TestDequeue } + | { type: "test:diagnostic"; data: EventData.TestDiagnostic } + | { type: "test:enqueue"; data: EventData.TestEnqueue } + | { type: "test:fail"; data: EventData.TestFail } + | { type: "test:pass"; data: EventData.TestPass } + | { type: "test:plan"; data: EventData.TestPlan } + | { type: "test:start"; data: EventData.TestStart } + | { type: "test:stderr"; data: EventData.TestStderr } + | { type: "test:stdout"; data: EventData.TestStdout } + | { type: "test:summary"; data: EventData.TestSummary } + | { type: "test:watch:drained"; data: undefined } + | { type: "test:watch:restarted"; data: undefined }; + type TestEventGenerator = AsyncGenerator; + + interface ReporterConstructorWrapper Transform> { + new(...args: ConstructorParameters): InstanceType; + (...args: ConstructorParameters): InstanceType; + } + + /** + * The `dot` reporter outputs the test results in a compact format, + * where each passing test is represented by a `.`, + * and each failing test is represented by a `X`. + * @since v20.0.0 + */ + function dot(source: TestEventGenerator): AsyncGenerator<"\n" | "." | "X", void>; + /** + * The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format. + * @since v20.0.0 + */ + function tap(source: TestEventGenerator): AsyncGenerator; + class SpecReporter extends Transform { + constructor(); + } + /** + * The `spec` reporter outputs the test results in a human-readable format. + * @since v20.0.0 + */ + const spec: ReporterConstructorWrapper; + /** + * The `junit` reporter outputs test results in a jUnit XML format. + * @since v21.0.0 + */ + function junit(source: TestEventGenerator): AsyncGenerator; + class LcovReporter extends Transform { + constructor(opts?: Omit); + } + /** + * The `lcov` reporter outputs test coverage when used with the + * [`--experimental-test-coverage`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--experimental-test-coverage) flag. + * @since v22.0.0 + */ + const lcov: ReporterConstructorWrapper; + + export { dot, junit, lcov, spec, tap, TestEvent }; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/timers.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/timers.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..30a91c0644e9b8992ba8aaa16efd24d8ef61668b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/timers.d.ts @@ -0,0 +1,285 @@ +/** + * The `timer` module exposes a global API for scheduling functions to + * be called at some future period of time. Because the timer functions are + * globals, there is no need to import `node:timers` to use the API. + * + * The timer functions within Node.js implement a similar API as the timers API + * provided by Web Browsers but use a different internal implementation that is + * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/timers.js) + */ +declare module "timers" { + import { Abortable } from "node:events"; + import * as promises from "node:timers/promises"; + export interface TimerOptions extends Abortable { + /** + * Set to `false` to indicate that the scheduled `Timeout` + * should not require the Node.js event loop to remain active. + * @default true + */ + ref?: boolean | undefined; + } + global { + namespace NodeJS { + /** + * This object is created internally and is returned from `setImmediate()`. It + * can be passed to `clearImmediate()` in order to cancel the scheduled + * actions. + * + * By default, when an immediate is scheduled, the Node.js event loop will continue + * running as long as the immediate is active. The `Immediate` object returned by + * `setImmediate()` exports both `immediate.ref()` and `immediate.unref()` + * functions that can be used to control this default behavior. + */ + interface Immediate extends RefCounted, Disposable { + /** + * If true, the `Immediate` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the + * `Immediate` is active. Calling `immediate.ref()` multiple times will have no + * effect. + * + * By default, all `Immediate` objects are "ref'ed", making it normally unnecessary + * to call `immediate.ref()` unless `immediate.unref()` had been called previously. + * @since v9.7.0 + * @returns a reference to `immediate` + */ + ref(): this; + /** + * When called, the active `Immediate` object will not require the Node.js event + * loop to remain active. If there is no other activity keeping the event loop + * running, the process may exit before the `Immediate` object's callback is + * invoked. Calling `immediate.unref()` multiple times will have no effect. + * @since v9.7.0 + * @returns a reference to `immediate` + */ + unref(): this; + /** + * Cancels the immediate. This is similar to calling `clearImmediate()`. + * @since v20.5.0, v18.18.0 + */ + [Symbol.dispose](): void; + _onImmediate(...args: any[]): void; + } + // Legacy interface used in Node.js v9 and prior + // TODO: remove in a future major version bump + /** @deprecated Use `NodeJS.Timeout` instead. */ + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + /** + * This object is created internally and is returned from `setTimeout()` and + * `setInterval()`. It can be passed to either `clearTimeout()` or + * `clearInterval()` in order to cancel the scheduled actions. + * + * By default, when a timer is scheduled using either `setTimeout()` or + * `setInterval()`, the Node.js event loop will continue running as long as the + * timer is active. Each of the `Timeout` objects returned by these functions + * export both `timeout.ref()` and `timeout.unref()` functions that can be used to + * control this default behavior. + */ + interface Timeout extends RefCounted, Disposable, Timer { + /** + * Cancels the timeout. + * @since v0.9.1 + * @legacy Use `clearTimeout()` instead. + * @returns a reference to `timeout` + */ + close(): this; + /** + * If true, the `Timeout` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the + * `Timeout` is active. Calling `timeout.ref()` multiple times will have no effect. + * + * By default, all `Timeout` objects are "ref'ed", making it normally unnecessary + * to call `timeout.ref()` unless `timeout.unref()` had been called previously. + * @since v0.9.1 + * @returns a reference to `timeout` + */ + ref(): this; + /** + * Sets the timer's start time to the current time, and reschedules the timer to + * call its callback at the previously specified duration adjusted to the current + * time. This is useful for refreshing a timer without allocating a new + * JavaScript object. + * + * Using this on a timer that has already called its callback will reactivate the + * timer. + * @since v10.2.0 + * @returns a reference to `timeout` + */ + refresh(): this; + /** + * When called, the active `Timeout` object will not require the Node.js event loop + * to remain active. If there is no other activity keeping the event loop running, + * the process may exit before the `Timeout` object's callback is invoked. Calling + * `timeout.unref()` multiple times will have no effect. + * @since v0.9.1 + * @returns a reference to `timeout` + */ + unref(): this; + /** + * Coerce a `Timeout` to a primitive. The primitive can be used to + * clear the `Timeout`. The primitive can only be used in the + * same thread where the timeout was created. Therefore, to use it + * across `worker_threads` it must first be passed to the correct + * thread. This allows enhanced compatibility with browser + * `setTimeout()` and `setInterval()` implementations. + * @since v14.9.0, v12.19.0 + */ + [Symbol.toPrimitive](): number; + /** + * Cancels the timeout. + * @since v20.5.0, v18.18.0 + */ + [Symbol.dispose](): void; + _onTimeout(...args: any[]): void; + } + } + /** + * Schedules the "immediate" execution of the `callback` after I/O events' + * callbacks. + * + * When multiple calls to `setImmediate()` are made, the `callback` functions are + * queued for execution in the order in which they are created. The entire callback + * queue is processed every event loop iteration. If an immediate timer is queued + * from inside an executing callback, that timer will not be triggered until the + * next event loop iteration. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using + * `timersPromises.setImmediate()`. + * @since v0.9.1 + * @param callback The function to call at the end of this turn of + * the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout) + * @param args Optional arguments to pass when the `callback` is called. + * @returns for use with `clearImmediate()` + */ + function setImmediate( + callback: (...args: TArgs) => void, + ...args: TArgs + ): NodeJS.Immediate; + // Allow a single void-accepting argument to be optional in arguments lists. + // Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258) + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setImmediate(callback: (_: void) => void): NodeJS.Immediate; + namespace setImmediate { + import __promisify__ = promises.setImmediate; + export { __promisify__ }; + } + /** + * Schedules repeated execution of `callback` every `delay` milliseconds. + * + * When `delay` is larger than `2147483647` or less than `1` or `NaN`, the `delay` + * will be set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using + * `timersPromises.setInterval()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param delay The number of milliseconds to wait before calling the + * `callback`. **Default:** `1`. + * @param args Optional arguments to pass when the `callback` is called. + * @returns for use with `clearInterval()` + */ + function setInterval( + callback: (...args: TArgs) => void, + delay?: number, + ...args: TArgs + ): NodeJS.Timeout; + // Allow a single void-accepting argument to be optional in arguments lists. + // Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258) + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setInterval(callback: (_: void) => void, delay?: number): NodeJS.Timeout; + /** + * Schedules execution of a one-time `callback` after `delay` milliseconds. + * + * The `callback` will likely not be invoked in precisely `delay` milliseconds. + * Node.js makes no guarantees about the exact timing of when callbacks will fire, + * nor of their ordering. The callback will be called as close as possible to the + * time specified. + * + * When `delay` is larger than `2147483647` or less than `1` or `NaN`, the `delay` + * will be set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using + * `timersPromises.setTimeout()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param delay The number of milliseconds to wait before calling the + * `callback`. **Default:** `1`. + * @param args Optional arguments to pass when the `callback` is called. + * @returns for use with `clearTimeout()` + */ + function setTimeout( + callback: (...args: TArgs) => void, + delay?: number, + ...args: TArgs + ): NodeJS.Timeout; + // Allow a single void-accepting argument to be optional in arguments lists. + // Allows usage such as `new Promise(resolve => setTimeout(resolve, ms))` (#54258) + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setTimeout(callback: (_: void) => void, delay?: number): NodeJS.Timeout; + namespace setTimeout { + import __promisify__ = promises.setTimeout; + export { __promisify__ }; + } + /** + * Cancels an `Immediate` object created by `setImmediate()`. + * @since v0.9.1 + * @param immediate An `Immediate` object as returned by `setImmediate()`. + */ + function clearImmediate(immediate: NodeJS.Immediate | undefined): void; + /** + * Cancels a `Timeout` object created by `setInterval()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by `setInterval()` + * or the primitive of the `Timeout` object as a string or a number. + */ + function clearInterval(timeout: NodeJS.Timeout | string | number | undefined): void; + /** + * Cancels a `Timeout` object created by `setTimeout()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by `setTimeout()` + * or the primitive of the `Timeout` object as a string or a number. + */ + function clearTimeout(timeout: NodeJS.Timeout | string | number | undefined): void; + /** + * The `queueMicrotask()` method queues a microtask to invoke `callback`. If + * `callback` throws an exception, the `process` object `'uncaughtException'` + * event will be emitted. + * + * The microtask queue is managed by V8 and may be used in a similar manner to + * the `process.nextTick()` queue, which is managed by Node.js. The + * `process.nextTick()` queue is always processed before the microtask queue + * within each turn of the Node.js event loop. + * @since v11.0.0 + * @param callback Function to be queued. + */ + function queueMicrotask(callback: () => void): void; + } + import clearImmediate = globalThis.clearImmediate; + import clearInterval = globalThis.clearInterval; + import clearTimeout = globalThis.clearTimeout; + import setImmediate = globalThis.setImmediate; + import setInterval = globalThis.setInterval; + import setTimeout = globalThis.setTimeout; + export { clearImmediate, clearInterval, clearTimeout, promises, setImmediate, setInterval, setTimeout }; +} +declare module "node:timers" { + export * from "timers"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/timers/promises.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/timers/promises.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7ad2b297badc85c50997b6bb926423510b5e7780 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,108 @@ +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via + * `require('node:timers/promises')`. + * + * ```js + * import { + * setTimeout, + * setImmediate, + * setInterval, + * } from 'node:timers/promises'; + * ``` + * @since v15.0.0 + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/timers/promises.js) + */ +declare module "timers/promises" { + import { TimerOptions } from "node:timers"; + /** + * ```js + * import { + * setTimeout, + * } from 'node:timers/promises'; + * + * const res = await setTimeout(100, 'result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param delay The number of milliseconds to wait before fulfilling the + * promise. **Default:** `1`. + * @param value A value with which the promise is fulfilled. + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + /** + * ```js + * import { + * setImmediate, + * } from 'node:timers/promises'; + * + * const res = await setImmediate('result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param value A value with which the promise is fulfilled. + */ + function setImmediate(value?: T, options?: TimerOptions): Promise; + /** + * Returns an async iterator that generates values in an interval of `delay` ms. + * If `ref` is `true`, you need to call `next()` of async iterator explicitly + * or implicitly to keep the event loop alive. + * + * ```js + * import { + * setInterval, + * } from 'node:timers/promises'; + * + * const interval = 100; + * for await (const startTime of setInterval(interval, Date.now())) { + * const now = Date.now(); + * console.log(now); + * if ((now - startTime) > 1000) + * break; + * } + * console.log(Date.now()); + * ``` + * @since v15.9.0 + * @param delay The number of milliseconds to wait between iterations. + * **Default:** `1`. + * @param value A value with which the iterator returns. + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): NodeJS.AsyncIterator; + interface Scheduler { + /** + * An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification + * being developed as a standard Web Platform API. + * + * Calling `timersPromises.scheduler.wait(delay, options)` is roughly equivalent + * to calling `timersPromises.setTimeout(delay, undefined, options)` except that + * the `ref` option is not supported. + * + * ```js + * import { scheduler } from 'node:timers/promises'; + * + * await scheduler.wait(1000); // Wait one second before continuing + * ``` + * @since v17.3.0, v16.14.0 + * @experimental + * @param delay The number of milliseconds to wait before resolving the + * promise. + */ + wait(delay: number, options?: { signal?: AbortSignal }): Promise; + /** + * An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification + * being developed as a standard Web Platform API. + * + * Calling `timersPromises.scheduler.yield()` is equivalent to calling + * `timersPromises.setImmediate()` with no arguments. + * @since v17.3.0, v16.14.0 + * @experimental + */ + yield(): Promise; + } + const scheduler: Scheduler; +} +declare module "node:timers/promises" { + export * from "timers/promises"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/tls.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/tls.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b9c4f244bf4f5a1d5585c992dc6da28d3a66aebd --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1213 @@ +/** + * The `node:tls` module provides an implementation of the Transport Layer Security + * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. + * The module can be accessed using: + * + * ```js + * import tls from 'node:tls'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/tls.js) + */ +declare module "tls" { + import { X509Certificate } from "node:crypto"; + import * as net from "node:net"; + import * as stream from "stream"; + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + interface PeerCertificate { + /** + * `true` if a Certificate Authority (CA), `false` otherwise. + * @since v18.13.0 + */ + ca: boolean; + /** + * The DER encoded X.509 certificate data. + */ + raw: Buffer; + /** + * The certificate subject. + */ + subject: Certificate; + /** + * The certificate issuer, described in the same terms as the `subject`. + */ + issuer: Certificate; + /** + * The date-time the certificate is valid from. + */ + valid_from: string; + /** + * The date-time the certificate is valid to. + */ + valid_to: string; + /** + * The certificate serial number, as a hex string. + */ + serialNumber: string; + /** + * The SHA-1 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint: string; + /** + * The SHA-256 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint256: string; + /** + * The SHA-512 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint512: string; + /** + * The extended key usage, a set of OIDs. + */ + ext_key_usage?: string[]; + /** + * A string containing concatenated names for the subject, + * an alternative to the `subject` names. + */ + subjectaltname?: string; + /** + * An array describing the AuthorityInfoAccess, used with OCSP. + */ + infoAccess?: NodeJS.Dict; + /** + * For RSA keys: The RSA bit size. + * + * For EC keys: The key size in bits. + */ + bits?: number; + /** + * The RSA exponent, as a string in hexadecimal number notation. + */ + exponent?: string; + /** + * The RSA modulus, as a hexadecimal string. + */ + modulus?: string; + /** + * The public key. + */ + pubkey?: Buffer; + /** + * The ASN.1 name of the OID of the elliptic curve. + * Well-known curves are identified by an OID. + * While it is unusual, it is possible that the curve + * is identified by its mathematical properties, + * in which case it will not have an OID. + */ + asn1Curve?: string; + /** + * The NIST name for the elliptic curve, if it has one + * (not all well-known curves have been assigned names by NIST). + */ + nistCurve?: string; + } + interface DetailedPeerCertificate extends PeerCertificate { + /** + * The issuer certificate object. + * For self-signed certificates, this may be a circular reference. + */ + issuerCertificate: DetailedPeerCertificate; + } + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + /** + * IETF name for the cipher suite. + */ + standardName: string; + } + interface EphemeralKeyInfo { + /** + * The supported types are 'DH' and 'ECDH'. + */ + type: string; + /** + * The name property is available only when type is 'ECDH'. + */ + name?: string | undefined; + /** + * The size of parameter of an ephemeral key exchange. + */ + size: number; + } + interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean | undefined; + /** + * An optional net.Server instance. + */ + server?: net.Server | undefined; + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer | undefined; + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean | undefined; + } + /** + * Performs transparent encryption of written data and all required TLS + * negotiation. + * + * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. + * + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate}) will only return data while the + * connection is open. + * @since v0.11.4 + */ + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket | stream.Duplex, options?: TLSSocketOptions); + /** + * This property is `true` if the peer certificate was signed by one of the CAs + * specified when creating the `tls.TLSSocket` instance, otherwise `false`. + * @since v0.11.4 + */ + authorized: boolean; + /** + * Returns the reason why the peer's certificate was not been verified. This + * property is set only when `tlsSocket.authorized === false`. + * @since v0.11.4 + */ + authorizationError: Error; + /** + * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. + * @since v0.11.4 + */ + encrypted: true; + /** + * String containing the selected ALPN protocol. + * Before a handshake has completed, this value is always null. + * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol: string | false | null; + /** + * Returns an object representing the local certificate. The returned object has + * some properties corresponding to the fields of the certificate. + * + * See {@link TLSSocket.getPeerCertificate} for an example of the certificate + * structure. + * + * If there is no local certificate, an empty object will be returned. If the + * socket has been destroyed, `null` will be returned. + * @since v11.2.0 + */ + getCertificate(): PeerCertificate | object | null; + /** + * Returns an object containing information on the negotiated cipher suite. + * + * For example, a TLSv1.2 protocol with AES256-SHA cipher: + * + * ```json + * { + * "name": "AES256-SHA", + * "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA", + * "version": "SSLv3" + * } + * ``` + * + * See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. + * @since v0.11.4 + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the type, name, and size of parameter of + * an ephemeral key exchange in `perfect forward secrecy` on a client + * connection. It returns an empty object when the key exchange is not + * ephemeral. As this is only supported on a client socket; `null` is returned + * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The `name` property is available only when type is `'ECDH'`. + * + * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. + * @since v5.0.0 + */ + getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. + */ + getFinished(): Buffer | undefined; + /** + * Returns an object representing the peer's certificate. If the peer does not + * provide a certificate, an empty object will be returned. If the socket has been + * destroyed, `null` will be returned. + * + * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's + * certificate. + * @since v0.11.4 + * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. + * @return A certificate object. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so + * far. + */ + getPeerFinished(): Buffer | undefined; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the + * current connection. The value `'unknown'` will be returned for connected + * sockets that have not completed the handshaking process. The value `null` will + * be returned for server sockets or disconnected client sockets. + * + * Protocol versions are: + * + * * `'SSLv3'` + * * `'TLSv1'` + * * `'TLSv1.1'` + * * `'TLSv1.2'` + * * `'TLSv1.3'` + * + * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. + * @since v5.7.0 + */ + getProtocol(): string | null; + /** + * Returns the TLS session data or `undefined` if no session was + * negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful + * for debugging. + * + * See `Session Resumption` for more information. + * + * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications + * must use the `'session'` event (it also works for TLSv1.2 and below). + * @since v0.11.4 + */ + getSession(): Buffer | undefined; + /** + * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. + * @since v12.11.0 + * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. + */ + getSharedSigalgs(): string[]; + /** + * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. + * + * It may be useful for debugging. + * + * See `Session Resumption` for more information. + * @since v0.11.4 + */ + getTLSTicket(): Buffer | undefined; + /** + * See `Session Resumption` for more information. + * @since v0.5.6 + * @return `true` if the session was reused, `false` otherwise. + */ + isSessionReused(): boolean; + /** + * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. + * Upon completion, the `callback` function will be passed a single argument + * that is either an `Error` (if the request failed) or `null`. + * + * This method can be used to request a peer's certificate after the secure + * connection has been established. + * + * When running as the server, the socket will be destroyed with an error after `handshakeTimeout` timeout. + * + * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the + * protocol. + * @since v0.11.8 + * @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with + * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. + * @return `true` if renegotiation was initiated, `false` otherwise. + */ + renegotiate( + options: { + rejectUnauthorized?: boolean | undefined; + requestCert?: boolean | undefined; + }, + callback: (err: Error | null) => void, + ): undefined | boolean; + /** + * The `tlsSocket.setKeyCert()` method sets the private key and certificate to use for the socket. + * This is mainly useful if you wish to select a server certificate from a TLS server's `ALPNCallback`. + * @since v22.5.0, v20.17.0 + * @param context An object containing at least `key` and `cert` properties from the {@link createSecureContext()} `options`, + * or a TLS context object created with {@link createSecureContext()} itself. + */ + setKeyCert(context: SecureContextOptions | SecureContext): void; + /** + * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. + * Returns `true` if setting the limit succeeded; `false` otherwise. + * + * Smaller fragment sizes decrease the buffering latency on the client: larger + * fragments are buffered by the TLS layer until the entire fragment is received + * and its integrity is verified; large fragments can span multiple roundtrips + * and their processing can be delayed due to packet loss or reordering. However, + * smaller fragments add extra TLS framing bytes and CPU overhead, which may + * decrease overall server throughput. + * @since v0.11.11 + * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. + */ + setMaxSendFragment(size: number): boolean; + /** + * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts + * to renegotiate will trigger an `'error'` event on the `TLSSocket`. + * @since v8.4.0 + */ + disableRenegotiation(): void; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * + * The format of the output is identical to the output of`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by + * OpenSSL's `SSL_trace()` function, the format is undocumented, can change + * without notice, and should not be relied on. + * @since v12.2.0 + */ + enableTrace(): void; + /** + * Returns the peer certificate as an `X509Certificate` object. + * + * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getPeerX509Certificate(): X509Certificate | undefined; + /** + * Returns the local certificate as an `X509Certificate` object. + * + * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getX509Certificate(): X509Certificate | undefined; + /** + * Keying material is used for validations to prevent different kind of attacks in + * network protocols, for example in the specifications of IEEE 802.1X. + * + * Example + * + * ```js + * const keyingMaterial = tlsSocket.exportKeyingMaterial( + * 128, + * 'client finished'); + * + * /* + * Example return value of keyingMaterial: + * + * + * ``` + * + * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more + * information. + * @since v13.10.0, v12.17.0 + * @param length number of bytes to retrieve from keying material + * @param label an application specific label, typically this will be a value from the [IANA Exporter Label + * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * @param context Optionally provide a context. + * @return requested bytes of the keying material + */ + exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + addListener(event: "session", listener: (session: Buffer) => void): this; + addListener(event: "keylog", listener: (line: Buffer) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; + emit(event: "session", session: Buffer): boolean; + emit(event: "keylog", line: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + on(event: "session", listener: (session: Buffer) => void): this; + on(event: "keylog", listener: (line: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + once(event: "session", listener: (session: Buffer) => void): this; + once(event: "keylog", listener: (line: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + prependListener(event: "session", listener: (session: Buffer) => void): this; + prependListener(event: "keylog", listener: (line: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + prependOnceListener(event: "session", listener: (session: Buffer) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer) => void): this; + } + interface CommonConnectionOptions { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext | undefined; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * @default false + */ + enableTrace?: boolean | undefined; + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean | undefined; + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) + */ + ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined; + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. + * @default true + */ + rejectUnauthorized?: boolean | undefined; + } + interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { + /** + * Abort the connection if the SSL/TLS handshake does not finish in the + * specified number of milliseconds. A 'tlsClientError' is emitted on + * the tls.Server object whenever a handshake times out. Default: + * 120000 (120 seconds). + */ + handshakeTimeout?: number | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + */ + ticketKeys?: Buffer | undefined; + /** + * @param socket + * @param identity identity parameter sent from the client. + * @return pre-shared key that must either be + * a buffer or `null` to stop the negotiation process. Returned PSK must be + * compatible with the selected cipher's digest. + * + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with the identity provided by the client. + * If the return value is `null` the negotiation process will stop and an + * "unknown_psk_identity" alert message will be sent to the other party. + * If the server wishes to hide the fact that the PSK identity was not known, + * the callback must provide some random data as `psk` to make the connection + * fail with "decrypt_error" before negotiation is finished. + * PSK ciphers are disabled by default, and using TLS-PSK thus + * requires explicitly specifying a cipher suite with the `ciphers` option. + * More information can be found in the RFC 4279. + */ + pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; + /** + * hint to send to a client to help + * with selecting the identity during TLS-PSK negotiation. Will be ignored + * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be + * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. + */ + pskIdentityHint?: string | undefined; + } + interface PSKCallbackNegotation { + psk: DataView | NodeJS.TypedArray; + identity: string; + } + interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { + host?: string | undefined; + port?: number | undefined; + path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket + checkServerIdentity?: typeof checkServerIdentity | undefined; + servername?: string | undefined; // SNI TLS Extension + session?: Buffer | undefined; + minDHSize?: number | undefined; + lookup?: net.LookupFunction | undefined; + timeout?: number | undefined; + /** + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with optional identity `hint` provided by the server or `null` + * in case of TLS 1.3 where `hint` was removed. + * It will be necessary to provide a custom `tls.checkServerIdentity()` + * for the connection as the default one will try to check hostname/IP + * of the server against the certificate but that's not applicable for PSK + * because there won't be a certificate present. + * More information can be found in the RFC 4279. + * + * @param hint message sent from the server to help client + * decide which identity to use during negotiation. + * Always `null` if TLS 1.3 is used. + * @returns Return `null` to stop the negotiation process. `psk` must be + * compatible with the selected cipher's digest. + * `identity` must use UTF-8 encoding. + */ + pskCallback?(hint: string | null): PSKCallbackNegotation | null; + } + /** + * Accepts encrypted connections using TLS or SSL. + * @since v0.3.2 + */ + class Server extends net.Server { + constructor(secureConnectionListener?: (socket: TLSSocket) => void); + constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); + /** + * The `server.addContext()` method adds a secure context that will be used if + * the client request's SNI name matches the supplied `hostname` (or wildcard). + * + * When there are multiple matching contexts, the most recently added one is + * used. + * @since v0.5.3 + * @param hostname A SNI host name or wildcard (e.g. `'*'`) + * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc), or a TLS context object created + * with {@link createSecureContext} itself. + */ + addContext(hostname: string, context: SecureContextOptions | SecureContext): void; + /** + * Returns the session ticket keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @return A 48-byte buffer containing the session ticket keys. + */ + getTicketKeys(): Buffer; + /** + * The `server.setSecureContext()` method replaces the secure context of an + * existing server. Existing connections to the server are not interrupted. + * @since v11.0.0 + * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + setSecureContext(options: SecureContextOptions): void; + /** + * Sets the session ticket keys. + * + * Changes to the ticket keys are effective only for future server connections. + * Existing or currently pending server connections will use the previous keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @param keys A 48-byte buffer containing the session ticket keys. + */ + setTicketKeys(keys: Buffer): void; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + * 6. keylog + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + addListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: () => void): boolean; + emit( + event: "OCSPRequest", + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ): boolean; + emit( + event: "resumeSession", + sessionId: Buffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + emit(event: "keylog", line: Buffer, tlsSocket: TLSSocket): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void): this; + on( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + on(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + once(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + } + type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1"; + interface SecureContextOptions { + /** + * If set, this will be called when a client opens a connection using the ALPN extension. + * One argument will be passed to the callback: an object containing `servername` and `protocols` fields, + * respectively containing the server name from the SNI extension (if any) and an array of + * ALPN protocol name strings. The callback must return either one of the strings listed in `protocols`, + * which will be returned to the client as the selected ALPN protocol, or `undefined`, + * to reject the connection with a fatal alert. If a string is returned that does not match one of + * the client's ALPN protocols, an error will be thrown. + * This option cannot be used with the `ALPNProtocols` option, and setting both options will throw an error. + */ + ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | undefined; + /** + * Treat intermediate (non-self-signed) + * certificates in the trust CA certificate list as trusted. + * @since v22.9.0, v20.18.0 + */ + allowPartialTrustChain?: boolean | undefined; + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array | undefined; + /** + * Colon-separated list of supported signature algorithms. The list + * can contain digest algorithms (SHA256, MD5 etc.), public key + * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g + * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). + */ + sigalgs?: string | undefined; + /** + * Cipher suite specification, replacing the default. For more + * information, see modifying the default cipher suite. Permitted + * ciphers can be obtained via tls.getCiphers(). Cipher names must be + * uppercased in order for OpenSSL to accept them. + */ + ciphers?: string | undefined; + /** + * Name of an OpenSSL engine which can provide the client certificate. + * @deprecated + */ + clientCertEngine?: string | undefined; + /** + * PEM formatted CRLs (Certificate Revocation Lists). + */ + crl?: string | Buffer | Array | undefined; + /** + * `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. + * If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. + * ECDHE-based perfect forward secrecy will still be available. + */ + dhparam?: string | Buffer | undefined; + /** + * A string describing a named curve or a colon separated list of curve + * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key + * agreement. Set to auto to select the curve automatically. Use + * crypto.getCurves() to obtain a list of available curve names. On + * recent releases, openssl ecparam -list_curves will also display the + * name and description of each available elliptic curve. Default: + * tls.DEFAULT_ECDH_CURVE. + */ + ecdhCurve?: string | undefined; + /** + * Attempt to use the server's cipher suite preferences instead of the + * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be + * set in secureOptions + */ + honorCipherOrder?: boolean | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form {pem: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted keys will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array | undefined; + /** + * Name of an OpenSSL engine to get private key from. Should be used + * together with privateKeyIdentifier. + * @deprecated + */ + privateKeyEngine?: string | undefined; + /** + * Identifier of a private key managed by an OpenSSL engine. Should be + * used together with privateKeyEngine. Should not be set together with + * key, because both options define a private key in different ways. + * @deprecated + */ + privateKeyIdentifier?: string | undefined; + /** + * Optionally set the maximum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. + * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using + * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to + * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. + */ + maxVersion?: SecureVersion | undefined; + /** + * Optionally set the minimum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to + * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. + */ + minVersion?: SecureVersion | undefined; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string | undefined; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form {buf: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted PFX will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array | undefined; + /** + * Optionally affect the OpenSSL protocol behavior, which is not + * usually necessary. This should be used carefully if at all! Value is + * a numeric bitmask of the SSL_OP_* options from OpenSSL Options + */ + secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options + /** + * Legacy mechanism to select the TLS protocol version to use, it does + * not support independent control of the minimum and maximum version, + * and does not support limiting the protocol to TLSv1.3. Use + * minVersion and maxVersion instead. The possible values are listed as + * SSL_METHODS, use the function names as strings. For example, use + * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow + * any TLS protocol version up to TLSv1.3. It is not recommended to use + * TLS versions less than 1.2, but it may be required for + * interoperability. Default: none, see minVersion. + */ + secureProtocol?: string | undefined; + /** + * Opaque identifier used by servers to ensure session state is not + * shared between applications. Unused by clients. + */ + sessionIdContext?: string | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + * See Session Resumption for more information. + */ + ticketKeys?: Buffer | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + } + interface SecureContext { + context: any; + } + /** + * Verifies the certificate `cert` is issued to `hostname`. + * + * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on + * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). + * + * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as + * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead. + * + * This function can be overwritten by providing an alternative function as the `options.checkServerIdentity` option that is passed to `tls.connect()`. The + * overwriting function can call `tls.checkServerIdentity()` of course, to augment + * the checks done with additional verification. + * + * This function is only called if the certificate passed all other checks, such as + * being issued by trusted CA (`options.ca`). + * + * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name + * was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use + * a custom `options.checkServerIdentity` function that implements the desired behavior. + * @since v0.8.4 + * @param hostname The host name or IP address to verify the certificate against. + * @param cert A `certificate object` representing the peer's certificate. + */ + function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; + /** + * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is + * automatically set as a listener for the `'secureConnection'` event. + * + * The `ticketKeys` options is automatically shared between `node:cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * import tls from 'node:tls'; + * import fs from 'node:fs'; + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * + * // This is necessary only if using client certificate authentication. + * requestCert: true, + * + * // This is necessary only if the client uses a self-signed certificate. + * ca: [ fs.readFileSync('client-cert.pem') ], + * }; + * + * const server = tls.createServer(options, (socket) => { + * console.log('server connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * socket.write('welcome!\n'); + * socket.setEncoding('utf8'); + * socket.pipe(socket); + * }); + * server.listen(8000, () => { + * console.log('server bound'); + * }); + * ``` + * + * The server can be tested by connecting to it using the example client from {@link connect}. + * @since v0.3.2 + */ + function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + /** + * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. + * + * `tls.connect()` returns a {@link TLSSocket} object. + * + * Unlike the `https` API, `tls.connect()` does not enable the + * SNI (Server Name Indication) extension by default, which may cause some + * servers to return an incorrect certificate or reject the connection + * altogether. To enable SNI, set the `servername` option in addition + * to `host`. + * + * The following illustrates a client for the echo server example from {@link createServer}: + * + * ```js + * // Assumes an echo server that is listening on port 8000. + * import tls from 'node:tls'; + * import fs from 'node:fs'; + * + * const options = { + * // Necessary only if the server requires client certificate authentication. + * key: fs.readFileSync('client-key.pem'), + * cert: fs.readFileSync('client-cert.pem'), + * + * // Necessary only if the server uses a self-signed certificate. + * ca: [ fs.readFileSync('server-cert.pem') ], + * + * // Necessary only if the server's cert isn't for "localhost". + * checkServerIdentity: () => { return null; }, + * }; + * + * const socket = tls.connect(8000, options, () => { + * console.log('client connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * process.stdin.pipe(socket); + * process.stdin.resume(); + * }); + * socket.setEncoding('utf8'); + * socket.on('data', (data) => { + * console.log(data); + * }); + * socket.on('end', () => { + * console.log('server ends connection'); + * }); + * ``` + * @since v0.11.3 + */ + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect( + port: number, + host?: string, + options?: ConnectionOptions, + secureConnectListener?: () => void, + ): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + /** + * `{@link createServer}` sets the default value of the `honorCipherOrder` option + * to `true`, other APIs that create secure contexts leave it unset. + * + * `{@link createServer}` uses a 128 bit truncated SHA1 hash value generated + * from `process.argv` as the default value of the `sessionIdContext` option, other + * APIs that create secure contexts have no default value. + * + * The `tls.createSecureContext()` method creates a `SecureContext` object. It is + * usable as an argument to several `tls` APIs, such as `server.addContext()`, + * but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option. + * + * A key is _required_ for ciphers that use certificates. Either `key` or `pfx` can be used to provide it. + * + * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of + * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). + * + * Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto' `option. When set to `'auto'`, well-known DHE parameters of sufficient strength + * will be selected automatically. Otherwise, if necessary, `openssl dhparam` can + * be used to create custom parameters. The key length must be greater than or + * equal to 1024 bits or else an error will be thrown. Although 1024 bits is + * permissible, use 2048 bits or larger for stronger security. + * @since v0.11.13 + */ + function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * Returns an array containing the CA certificates from various sources, depending on `type`: + * + * * `"default"`: return the CA certificates that will be used by the Node.js TLS clients by default. + * * When `--use-bundled-ca` is enabled (default), or `--use-openssl-ca` is not enabled, + * this would include CA certificates from the bundled Mozilla CA store. + * * When `--use-system-ca` is enabled, this would also include certificates from the system's + * trusted store. + * * When `NODE_EXTRA_CA_CERTS` is used, this would also include certificates loaded from the specified + * file. + * * `"system"`: return the CA certificates that are loaded from the system's trusted store, according + * to rules set by `--use-system-ca`. This can be used to get the certificates from the system + * when `--use-system-ca` is not enabled. + * * `"bundled"`: return the CA certificates from the bundled Mozilla CA store. This would be the same + * as `tls.rootCertificates`. + * * `"extra"`: return the CA certificates loaded from `NODE_EXTRA_CA_CERTS`. It's an empty array if + * `NODE_EXTRA_CA_CERTS` is not set. + * @since v22.15.0 + * @param type The type of CA certificates that will be returned. Valid values + * are `"default"`, `"system"`, `"bundled"` and `"extra"`. + * **Default:** `"default"`. + * @returns An array of PEM-encoded certificates. The array may contain duplicates + * if the same certificate is repeatedly stored in multiple sources. + */ + function getCACertificates(type?: "default" | "system" | "bundled" | "extra"): string[]; + /** + * Returns an array with the names of the supported TLS ciphers. The names are + * lower-case for historical reasons, but must be uppercased to be used in + * the `ciphers` option of `{@link createSecureContext}`. + * + * Not all supported ciphers are enabled by default. See + * [Modifying the default TLS cipher suite](https://nodejs.org/docs/latest-v24.x/api/tls.html#modifying-the-default-tls-cipher-suite). + * + * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for + * TLSv1.2 and below. + * + * ```js + * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] + * ``` + * @since v0.10.2 + */ + function getCiphers(): string[]; + /** + * The default curve name to use for ECDH key agreement in a tls server. + * The default value is `'auto'`. See `{@link createSecureContext()}` for further + * information. + * @since v0.11.13 + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the `maxVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.3'`, unless + * changed using CLI options. Using `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using + * `--tls-max-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the highest maximum is used. + * @since v11.4.0 + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the `minVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.2'`, unless + * changed using CLI options. Using `--tls-min-v1.0` sets the default to + * `'TLSv1'`. Using `--tls-min-v1.1` sets the default to `'TLSv1.1'`. Using + * `--tls-min-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the lowest minimum is used. + * @since v11.4.0 + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * The default value of the `ciphers` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported OpenSSL ciphers. + * Defaults to the content of `crypto.constants.defaultCoreCipherList`, unless + * changed using CLI options using `--tls-default-ciphers`. + * @since v19.8.0 + */ + let DEFAULT_CIPHERS: string; + /** + * An immutable array of strings representing the root certificates (in PEM format) + * from the bundled Mozilla CA store as supplied by the current Node.js version. + * + * The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store + * that is fixed at release time. It is identical on all supported platforms. + * @since v12.3.0 + */ + const rootCertificates: readonly string[]; +} +declare module "node:tls" { + export * from "tls"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/trace_events.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/trace_events.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..56e46209657d33396b88e836b4e3d2cb5a28d77f --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,197 @@ +/** + * The `node:trace_events` module provides a mechanism to centralize tracing information + * generated by V8, Node.js core, and userspace code. + * + * Tracing can be enabled with the `--trace-event-categories` command-line flag + * or by using the `trace_events` module. The `--trace-event-categories` flag + * accepts a list of comma-separated category names. + * + * The available categories are: + * + * * `node`: An empty placeholder. + * * `node.async_hooks`: Enables capture of detailed [`async_hooks`](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html) trace data. + * The [`async_hooks`](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html) events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. + * * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. + * * `node.console`: Enables capture of `console.time()` and `console.count()` output. + * * `node.threadpoolwork.sync`: Enables capture of trace data for threadpool synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.threadpoolwork.async`: Enables capture of trace data for threadpool asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.dns.native`: Enables capture of trace data for DNS queries. + * * `node.net.native`: Enables capture of trace data for network. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.fs_dir.sync`: Enables capture of trace data for file system sync directory methods. + * * `node.fs.async`: Enables capture of trace data for file system async methods. + * * `node.fs_dir.async`: Enables capture of trace data for file system async directory methods. + * * `node.perf`: Enables capture of [Performance API](https://nodejs.org/docs/latest-v24.x/api/perf_hooks.html) measurements. + * * `node.perf.usertiming`: Enables capture of only Performance API User Timing + * measures and marks. + * * `node.perf.timerify`: Enables capture of only Performance API timerify + * measurements. + * * `node.promises.rejections`: Enables capture of trace data tracking the number + * of unhandled Promise rejections and handled-after-rejections. + * * `node.vm.script`: Enables capture of trace data for the `node:vm` module's `runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The [V8](https://nodejs.org/docs/latest-v24.x/api/v8.html) events are GC, compiling, and execution related. + * * `node.http`: Enables capture of trace data for http request / response. + * + * By default the `node`, `node.async_hooks`, and `v8` categories are enabled. + * + * ```bash + * node --trace-event-categories v8,node,node.async_hooks server.js + * ``` + * + * Prior versions of Node.js required the use of the `--trace-events-enabled` flag to enable trace events. This requirement has been removed. However, the `--trace-events-enabled` flag _may_ still be + * used and will enable the `node`, `node.async_hooks`, and `v8` trace event categories by default. + * + * ```bash + * node --trace-events-enabled + * + * # is equivalent to + * + * node --trace-event-categories v8,node,node.async_hooks + * ``` + * + * Alternatively, trace events may be enabled using the `node:trace_events` module: + * + * ```js + * import trace_events from 'node:trace_events'; + * const tracing = trace_events.createTracing({ categories: ['node.perf'] }); + * tracing.enable(); // Enable trace event capture for the 'node.perf' category + * + * // do work + * + * tracing.disable(); // Disable trace event capture for the 'node.perf' category + * ``` + * + * Running Node.js with tracing enabled will produce log files that can be opened + * in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome. + * + * The logging file is by default called `node_trace.${rotation}.log`, where `${rotation}` is an incrementing log-rotation id. The filepath pattern can + * be specified with `--trace-event-file-pattern` that accepts a template + * string that supports `${rotation}` and `${pid}`: + * + * ```bash + * node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js + * ``` + * + * To guarantee that the log file is properly generated after signal events like `SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers + * in your code, such as: + * + * ```js + * process.on('SIGINT', function onSigint() { + * console.info('Received SIGINT.'); + * process.exit(130); // Or applicable exit code depending on OS and signal + * }); + * ``` + * + * The tracing system uses the same time source + * as the one used by `process.hrtime()`. + * However the trace-event timestamps are expressed in microseconds, + * unlike `process.hrtime()` which returns nanoseconds. + * + * The features from this module are not available in [`Worker`](https://nodejs.org/docs/latest-v24.x/api/worker_threads.html#class-worker) threads. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/trace_events.js) + */ +declare module "trace_events" { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + * @since v10.0.0 + */ + readonly categories: string; + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + * + * ```js + * import trace_events from 'node:trace_events'; + * const t1 = trace_events.createTracing({ categories: ['node', 'v8'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] }); + * t1.enable(); + * t2.enable(); + * + * // Prints 'node,node.perf,v8' + * console.log(trace_events.getEnabledCategories()); + * + * t2.disable(); // Will only disable emission of the 'node.perf' category + * + * // Prints 'node,v8' + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + * @since v10.0.0 + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + * @since v10.0.0 + */ + readonly enabled: boolean; + } + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + /** + * Creates and returns a `Tracing` object for the given set of `categories`. + * + * ```js + * import trace_events from 'node:trace_events'; + * const categories = ['node.perf', 'node.async_hooks']; + * const tracing = trace_events.createTracing({ categories }); + * tracing.enable(); + * // do stuff + * tracing.disable(); + * ``` + * @since v10.0.0 + */ + function createTracing(options: CreateTracingOptions): Tracing; + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is determined + * by the _union_ of all currently-enabled `Tracing` objects and any categories + * enabled using the `--trace-event-categories` flag. + * + * Given the file `test.js` below, the command `node --trace-event-categories node.perf test.js` will print `'node.async_hooks,node.perf'` to the console. + * + * ```js + * import trace_events from 'node:trace_events'; + * const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf'] }); + * const t3 = trace_events.createTracing({ categories: ['v8'] }); + * + * t1.enable(); + * t2.enable(); + * + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + function getEnabledCategories(): string | undefined; +} +declare module "node:trace_events" { + export * from "trace_events"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/ts5.6/buffer.buffer.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/ts5.6/buffer.buffer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d19026dc2ff99c5a865defba1953ec7588278345 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/ts5.6/buffer.buffer.d.ts @@ -0,0 +1,460 @@ +declare module "buffer" { + global { + interface BufferConstructor { + // see ../buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: ArrayLike): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * If `array` is an `Array`-like object (that is, one with a `length` property of + * type `number`), it is treated as if it is an array, unless it is a `Buffer` or + * a `Uint8Array`. This means all other `TypedArray` variants get treated as an + * `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use + * `Buffer.copyBytesFrom()`. + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal + * `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from(array: WithImplicitCoercion>): Buffer; + /** + * This creates a view of the `ArrayBuffer` without copying the underlying + * memory. For example, when passed a reference to the `.buffer` property of a + * `TypedArray` instance, the newly created `Buffer` will share the same + * allocated memory as the `TypedArray`'s underlying `ArrayBuffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arr = new Uint16Array(2); + * + * arr[0] = 5000; + * arr[1] = 4000; + * + * // Shares memory with `arr`. + * const buf = Buffer.from(arr.buffer); + * + * console.log(buf); + * // Prints: + * + * // Changing the original Uint16Array changes the Buffer also. + * arr[1] = 6000; + * + * console.log(buf); + * // Prints: + * ``` + * + * The optional `byteOffset` and `length` arguments specify a memory range within + * the `arrayBuffer` that will be shared by the `Buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const ab = new ArrayBuffer(10); + * const buf = Buffer.from(ab, 0, 2); + * + * console.log(buf.length); + * // Prints: 2 + * ``` + * + * A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer` or a + * `SharedArrayBuffer` or another type appropriate for `Buffer.from()` + * variants. + * + * It is important to remember that a backing `ArrayBuffer` can cover a range + * of memory that extends beyond the bounds of a `TypedArray` view. A new + * `Buffer` created using the `buffer` property of a `TypedArray` may extend + * beyond the range of the `TypedArray`: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements + * const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements + * console.log(arrA.buffer === arrB.buffer); // true + * + * const buf = Buffer.from(arrB.buffer); + * console.log(buf); + * // Prints: + * ``` + * @since v5.10.0 + * @param arrayBuffer An `ArrayBuffer`, `SharedArrayBuffer`, for example the + * `.buffer` property of a `TypedArray`. + * @param byteOffset Index of first byte to expose. **Default:** `0`. + * @param length Number of bytes to expose. **Default:** + * `arrayBuffer.byteLength - byteOffset`. + */ + from( + arrayBuffer: WithImplicitCoercion, + byteOffset?: number, + length?: number, + ): Buffer; + /** + * Creates a new `Buffer` containing `string`. The `encoding` parameter identifies + * the character encoding to be used when converting `string` into bytes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('this is a tést'); + * const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); + * + * console.log(buf1.toString()); + * // Prints: this is a tést + * console.log(buf2.toString()); + * // Prints: this is a tést + * console.log(buf1.toString('latin1')); + * // Prints: this is a tést + * ``` + * + * A `TypeError` will be thrown if `string` is not a string or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(string)` may also use the internal `Buffer` pool like + * `Buffer.allocUnsafe()` does. + * @since v5.10.0 + * @param string A string to encode. + * @param encoding The encoding of `string`. **Default:** `'utf8'`. + */ + from(string: WithImplicitCoercion, encoding?: BufferEncoding): Buffer; + from(arrayOrString: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: readonly Uint8Array[], totalLength?: number): Buffer; + /** + * Copies the underlying memory of `view` into a new `Buffer`. + * + * ```js + * const u16 = new Uint16Array([0, 0xffff]); + * const buf = Buffer.copyBytesFrom(u16, 1, 1); + * u16[1] = 0; + * console.log(buf.length); // 2 + * console.log(buf[0]); // 255 + * console.log(buf[1]); // 255 + * ``` + * @since v19.8.0 + * @param view The {TypedArray} to copy. + * @param [offset=0] The starting offset within `view`. + * @param [length=view.length - offset] The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, + * and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if + * `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + } + interface Buffer extends Uint8Array { + // see ../buffer.d.ts for implementation shared with all TypeScript versions + + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @since v0.3.0 + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + } + type NonSharedBuffer = Buffer; + type AllowSharedBuffer = Buffer; + } + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + var SlowBuffer: { + /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ + new(size: number): Buffer; + prototype: Buffer; + }; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/ts5.6/compatibility/float16array.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/ts5.6/compatibility/float16array.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f148cc4f85b83107f8e8bc4fe3fcf6b642b294fe --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/ts5.6/compatibility/float16array.d.ts @@ -0,0 +1,71 @@ +// Interface declaration for Float16Array, required in @types/node v24+. +// These definitions are specific to TS <=5.6. + +// This needs all of the "common" properties/methods of the TypedArrays, +// otherwise the type unions `TypedArray` and `ArrayBufferView` will be +// empty objects. +interface Float16Array extends Pick { + readonly BYTES_PER_ELEMENT: number; + readonly buffer: ArrayBufferLike; + readonly byteLength: number; + readonly byteOffset: number; + readonly length: number; + readonly [Symbol.toStringTag]: "Float16Array"; + at(index: number): number | undefined; + copyWithin(target: number, start: number, end?: number): this; + every(predicate: (value: number, index: number, array: Float16Array) => unknown, thisArg?: any): boolean; + fill(value: number, start?: number, end?: number): this; + filter(predicate: (value: number, index: number, array: Float16Array) => any, thisArg?: any): Float16Array; + find(predicate: (value: number, index: number, obj: Float16Array) => boolean, thisArg?: any): number | undefined; + findIndex(predicate: (value: number, index: number, obj: Float16Array) => boolean, thisArg?: any): number; + findLast( + predicate: (value: number, index: number, array: Float16Array) => value is S, + thisArg?: any, + ): S | undefined; + findLast( + predicate: (value: number, index: number, array: Float16Array) => unknown, + thisArg?: any, + ): number | undefined; + findLastIndex(predicate: (value: number, index: number, array: Float16Array) => unknown, thisArg?: any): number; + forEach(callbackfn: (value: number, index: number, array: Float16Array) => void, thisArg?: any): void; + includes(searchElement: number, fromIndex?: number): boolean; + indexOf(searchElement: number, fromIndex?: number): number; + join(separator?: string): string; + lastIndexOf(searchElement: number, fromIndex?: number): number; + map(callbackfn: (value: number, index: number, array: Float16Array) => number, thisArg?: any): Float16Array; + reduce( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number, + ): number; + reduce( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number, + initialValue: number, + ): number; + reduce( + callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float16Array) => U, + initialValue: U, + ): U; + reduceRight( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number, + ): number; + reduceRight( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float16Array) => number, + initialValue: number, + ): number; + reduceRight( + callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float16Array) => U, + initialValue: U, + ): U; + reverse(): Float16Array; + set(array: ArrayLike, offset?: number): void; + slice(start?: number, end?: number): Float16Array; + some(predicate: (value: number, index: number, array: Float16Array) => unknown, thisArg?: any): boolean; + sort(compareFn?: (a: number, b: number) => number): this; + subarray(begin?: number, end?: number): Float16Array; + toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string; + toReversed(): Float16Array; + toSorted(compareFn?: (a: number, b: number) => number): Float16Array; + toString(): string; + valueOf(): Float16Array; + with(index: number, value: number): Float16Array; + [index: number]: number; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/ts5.6/globals.typedarray.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/ts5.6/globals.typedarray.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..255e204813d2bb15c6849889b0de395f8ef5a83b --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/ts5.6/globals.typedarray.d.ts @@ -0,0 +1,20 @@ +export {}; // Make this a module + +declare global { + namespace NodeJS { + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float16Array + | Float32Array + | Float64Array; + type ArrayBufferView = TypedArray | DataView; + } +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/ts5.6/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/ts5.6/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b98cc67db600b43e0e21b4e1dda713be9aa3a282 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/ts5.6/index.d.ts @@ -0,0 +1,96 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +// NOTE: These definitions support Node.js and TypeScript 5.2 through 5.6. + +// Reference required TypeScript libraries: +/// +/// + +// TypeScript library polyfills required for TypeScript <=5.6: +/// + +// Iterator definitions required for compatibility with TypeScript <5.6: +/// + +// Definitions for Node.js modules specific to TypeScript <=5.6: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/ts5.7/compatibility/float16array.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/ts5.7/compatibility/float16array.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..110b1ebb19cb26cfac04deff6f9280ce796089d5 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/ts5.7/compatibility/float16array.d.ts @@ -0,0 +1,72 @@ +// Interface declaration for Float16Array, required in @types/node v24+. +// These definitions are specific to TS 5.7. + +// This needs all of the "common" properties/methods of the TypedArrays, +// otherwise the type unions `TypedArray` and `ArrayBufferView` will be +// empty objects. +interface Float16Array { + readonly BYTES_PER_ELEMENT: number; + readonly buffer: TArrayBuffer; + readonly byteLength: number; + readonly byteOffset: number; + readonly length: number; + readonly [Symbol.toStringTag]: "Float16Array"; + at(index: number): number | undefined; + copyWithin(target: number, start: number, end?: number): this; + entries(): ArrayIterator<[number, number]>; + every(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; + fill(value: number, start?: number, end?: number): this; + filter(predicate: (value: number, index: number, array: this) => any, thisArg?: any): Float16Array; + find(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number | undefined; + findIndex(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number; + findLast( + predicate: (value: number, index: number, array: this) => value is S, + thisArg?: any, + ): S | undefined; + findLast(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number | undefined; + findLastIndex(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number; + forEach(callbackfn: (value: number, index: number, array: this) => void, thisArg?: any): void; + includes(searchElement: number, fromIndex?: number): boolean; + indexOf(searchElement: number, fromIndex?: number): number; + join(separator?: string): string; + keys(): ArrayIterator; + lastIndexOf(searchElement: number, fromIndex?: number): number; + map(callbackfn: (value: number, index: number, array: this) => number, thisArg?: any): Float16Array; + reduce( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, + ): number; + reduce( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, + initialValue: number, + ): number; + reduce( + callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, + initialValue: U, + ): U; + reduceRight( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, + ): number; + reduceRight( + callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, + initialValue: number, + ): number; + reduceRight( + callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, + initialValue: U, + ): U; + reverse(): this; + set(array: ArrayLike, offset?: number): void; + slice(start?: number, end?: number): Float16Array; + some(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; + sort(compareFn?: (a: number, b: number) => number): this; + subarray(begin?: number, end?: number): Float16Array; + toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string; + toReversed(): Float16Array; + toSorted(compareFn?: (a: number, b: number) => number): Float16Array; + toString(): string; + valueOf(): this; + values(): ArrayIterator; + with(index: number, value: number): Float16Array; + [Symbol.iterator](): ArrayIterator; + [index: number]: number; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/ts5.7/index.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/ts5.7/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9793c72ea8a0ae51e9b5839ab11c4575a70c7a9a --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/ts5.7/index.d.ts @@ -0,0 +1,96 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +// NOTE: These definitions support Node.js and TypeScript 5.7. + +// Reference required TypeScript libraries: +/// +/// + +// TypeScript library polyfills required for TypeScript 5.7: +/// + +// Iterator definitions required for compatibility with TypeScript <5.6: +/// + +// Definitions for Node.js modules specific to TypeScript 5.7+: +/// +/// + +// Definitions for Node.js modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/tty.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/tty.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..602324ab905f2d1d4fc00bcdc52f23105261b693 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/tty.d.ts @@ -0,0 +1,208 @@ +/** + * The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes. In most cases, it will not be necessary or possible to use this module + * directly. However, it can be accessed using: + * + * ```js + * import tty from 'node:tty'; + * ``` + * + * When Node.js detects that it is being run with a text terminal ("TTY") + * attached, `process.stdin` will, by default, be initialized as an instance of `tty.ReadStream` and both `process.stdout` and `process.stderr` will, by + * default, be instances of `tty.WriteStream`. The preferred method of determining + * whether Node.js is being run within a TTY context is to check that the value of + * the `process.stdout.isTTY` property is `true`: + * + * ```console + * $ node -p -e "Boolean(process.stdout.isTTY)" + * true + * $ node -p -e "Boolean(process.stdout.isTTY)" | cat + * false + * ``` + * + * In most cases, there should be little to no reason for an application to + * manually create instances of the `tty.ReadStream` and `tty.WriteStream` classes. + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/tty.js) + */ +declare module "tty" { + import * as net from "node:net"; + /** + * The `tty.isatty()` method returns `true` if the given `fd` is associated with + * a TTY and `false` if it is not, including whenever `fd` is not a non-negative + * integer. + * @since v0.5.8 + * @param fd A numeric file descriptor + */ + function isatty(fd: number): boolean; + /** + * Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js + * process and there should be no reason to create additional instances. + * @since v0.5.8 + */ + class ReadStream extends net.Socket { + constructor(fd: number, options?: net.SocketConstructorOpts); + /** + * A `boolean` that is `true` if the TTY is currently configured to operate as a + * raw device. + * + * This flag is always `false` when a process starts, even if the terminal is + * operating in raw mode. Its value will change with subsequent calls to `setRawMode`. + * @since v0.7.7 + */ + isRaw: boolean; + /** + * Allows configuration of `tty.ReadStream` so that it operates as a raw device. + * + * When in raw mode, input is always available character-by-character, not + * including modifiers. Additionally, all special processing of characters by the + * terminal is disabled, including echoing input + * characters. Ctrl+C will no longer cause a `SIGINT` when + * in this mode. + * @since v0.7.7 + * @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` + * property will be set to the resulting mode. + * @return The read stream instance. + */ + setRawMode(mode: boolean): this; + /** + * A `boolean` that is always `true` for `tty.ReadStream` instances. + * @since v0.5.8 + */ + isTTY: boolean; + } + /** + * -1 - to the left from cursor + * 0 - the entire line + * 1 - to the right from cursor + */ + type Direction = -1 | 0 | 1; + /** + * Represents the writable side of a TTY. In normal circumstances, `process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there + * should be no reason to create additional instances. + * @since v0.5.8 + */ + class WriteStream extends net.Socket { + constructor(fd: number); + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "resize", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "resize"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "resize", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "resize", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "resize", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "resize", listener: () => void): this; + /** + * `writeStream.clearLine()` clears the current line of this `WriteStream` in a + * direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearLine(dir: Direction, callback?: () => void): boolean; + /** + * `writeStream.clearScreenDown()` clears this `WriteStream` from the current + * cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearScreenDown(callback?: () => void): boolean; + /** + * `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified + * position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + cursorTo(x: number, y?: number, callback?: () => void): boolean; + cursorTo(x: number, callback: () => void): boolean; + /** + * `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its + * current position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + moveCursor(dx: number, dy: number, callback?: () => void): boolean; + /** + * Returns: + * + * * `1` for 2, + * * `4` for 16, + * * `8` for 256, + * * `24` for 16,777,216 colors supported. + * + * Use this to determine what colors the terminal supports. Due to the nature of + * colors in terminals it is possible to either have false positives or false + * negatives. It depends on process information and the environment variables that + * may lie about what terminal is used. + * It is possible to pass in an `env` object to simulate the usage of a specific + * terminal. This can be useful to check how specific environment settings behave. + * + * To enforce a specific color support, use one of the below environment settings. + * + * * 2 colors: `FORCE_COLOR = 0` (Disables colors) + * * 16 colors: `FORCE_COLOR = 1` + * * 256 colors: `FORCE_COLOR = 2` + * * 16,777,216 colors: `FORCE_COLOR = 3` + * + * Disabling color support is also possible by using the `NO_COLOR` and `NODE_DISABLE_COLORS` environment variables. + * @since v9.9.0 + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + getColorDepth(env?: object): number; + /** + * Returns `true` if the `writeStream` supports at least as many colors as provided + * in `count`. Minimum support is 2 (black and white). + * + * This has the same false positives and negatives as described in `writeStream.getColorDepth()`. + * + * ```js + * process.stdout.hasColors(); + * // Returns true or false depending on if `stdout` supports at least 16 colors. + * process.stdout.hasColors(256); + * // Returns true or false depending on if `stdout` supports at least 256 colors. + * process.stdout.hasColors({ TMUX: '1' }); + * // Returns true. + * process.stdout.hasColors(2 ** 24, { TMUX: '1' }); + * // Returns false (the environment setting pretends to support 2 ** 8 colors). + * ``` + * @since v11.13.0, v10.16.0 + * @param [count=16] The number of colors that are requested (minimum 2). + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + hasColors(count?: number): boolean; + hasColors(env?: object): boolean; + hasColors(count: number, env?: object): boolean; + /** + * `writeStream.getWindowSize()` returns the size of the TTY + * corresponding to this `WriteStream`. The array is of the type `[numColumns, numRows]` where `numColumns` and `numRows` represent the number + * of columns and rows in the corresponding TTY. + * @since v0.7.7 + */ + getWindowSize(): [number, number]; + /** + * A `number` specifying the number of columns the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + columns: number; + /** + * A `number` specifying the number of rows the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + rows: number; + /** + * A `boolean` that is always `true`. + * @since v0.5.8 + */ + isTTY: boolean; + } +} +declare module "node:tty" { + export * from "tty"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/url.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/url.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..83e3872e4837109fee29eb4030a2084814ffde9d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/url.d.ts @@ -0,0 +1,1025 @@ +/** + * The `node:url` module provides utilities for URL resolution and parsing. It can + * be accessed using: + * + * ```js + * import url from 'node:url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/url.js) + */ +declare module "url" { + import { Blob as NodeBlob } from "node:buffer"; + import { ClientRequestArgs } from "node:http"; + import { ParsedUrlQuery, ParsedUrlQueryInput } from "node:querystring"; + // Input to `url.format` + interface UrlObject { + auth?: string | null | undefined; + hash?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + href?: string | null | undefined; + pathname?: string | null | undefined; + protocol?: string | null | undefined; + search?: string | null | undefined; + slashes?: boolean | null | undefined; + port?: string | number | null | undefined; + query?: string | null | ParsedUrlQueryInput | undefined; + } + // Output of `url.parse` + interface Url { + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + path: string | null; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | null | ParsedUrlQuery; + } + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + interface UrlWithStringQuery extends Url { + query: string | null; + } + interface FileUrlToPathOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + * @since v22.1.0 + */ + windows?: boolean | undefined; + } + interface PathToFileUrlOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + * @since v22.1.0 + */ + windows?: boolean | undefined; + } + /** + * The `url.parse()` method takes a URL string, parses it, and returns a URL + * object. + * + * A `TypeError` is thrown if `urlString` is not a string. + * + * A `URIError` is thrown if the `auth` property is present but cannot be decoded. + * + * `url.parse()` uses a lenient, non-standard algorithm for parsing URL + * strings. It is prone to security issues such as [host name spoofing](https://hackerone.com/reports/678487) and incorrect handling of usernames and passwords. Do not use with untrusted + * input. CVEs are not issued for `url.parse()` vulnerabilities. Use the `WHATWG URL` API instead. + * @since v0.1.25 + * @deprecated Use the WHATWG URL API instead. + * @param urlString The URL string to parse. + * @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property + * on the returned URL object will be an unparsed, undecoded string. + * @param [slashesDenoteHost=false] If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the + * result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. + */ + function parse(urlString: string): UrlWithStringQuery; + function parse( + urlString: string, + parseQueryString: false | undefined, + slashesDenoteHost?: boolean, + ): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlString: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * import url from 'node:url'; + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: URL, options?: URLFormatOptions): string; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * import url from 'node:url'; + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: UrlObject | string): string; + /** + * The `url.resolve()` method resolves a target URL relative to a base URL in a + * manner similar to that of a web browser resolving an anchor tag. + * + * ```js + * import url from 'node:url'; + * url.resolve('/one/two/three', 'four'); // '/one/two/four' + * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' + * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * + * To achieve the same result using the WHATWG URL API: + * + * ```js + * function resolve(from, to) { + * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); + * if (resolvedUrl.protocol === 'resolve:') { + * // `from` is a relative URL. + * const { pathname, search, hash } = resolvedUrl; + * return pathname + search + hash; + * } + * return resolvedUrl.toString(); + * } + * + * resolve('/one/two/three', 'four'); // '/one/two/four' + * resolve('http://example.com/', '/one'); // 'http://example.com/one' + * resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param from The base URL to use if `to` is a relative URL. + * @param to The target URL to resolve. + */ + function resolve(from: string, to: string): string; + /** + * Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an + * invalid domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToUnicode}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToASCII('español.com')); + * // Prints xn--espaol-zwa.com + * console.log(url.domainToASCII('中文.com')); + * // Prints xn--fiq228c.com + * console.log(url.domainToASCII('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToASCII(domain: string): string; + /** + * Returns the Unicode serialization of the `domain`. If `domain` is an invalid + * domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToASCII}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToUnicode('xn--espaol-zwa.com')); + * // Prints español.com + * console.log(url.domainToUnicode('xn--fiq228c.com')); + * // Prints 中文.com + * console.log(url.domainToUnicode('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToUnicode(domain: string): string; + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * + * ```js + * import { fileURLToPath } from 'node:url'; + * + * const __filename = fileURLToPath(import.meta.url); + * + * new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ + * fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) + * + * new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt + * fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) + * + * new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt + * fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) + * + * new URL('file:///hello world').pathname; // Incorrect: /hello%20world + * fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) + * ``` + * @since v10.12.0 + * @param url The file URL string or URL object to convert to a path. + * @return The fully-resolved platform-specific Node.js file path. + */ + function fileURLToPath(url: string | URL, options?: FileUrlToPathOptions): string; + /** + * Like `url.fileURLToPath(...)` except that instead of returning a string + * representation of the path, a `Buffer` is returned. This conversion is + * helpful when the input URL contains percent-encoded segments that are + * not valid UTF-8 / Unicode sequences. + * @since v24.3.0 + * @param url The file URL string or URL object to convert to a path. + * @returns The fully-resolved platform-specific Node.js file path + * as a `Buffer`. + */ + function fileURLToPathBuffer(url: string | URL, options?: FileUrlToPathOptions): Buffer; + /** + * This function ensures that `path` is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * + * ```js + * import { pathToFileURL } from 'node:url'; + * + * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 + * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) + * + * new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c + * pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) + * ``` + * @since v10.12.0 + * @param path The path to convert to a File URL. + * @return The file URL object. + */ + function pathToFileURL(path: string, options?: PathToFileUrlOptions): URL; + /** + * This utility function converts a URL object into an ordinary options object as + * expected by the `http.request()` and `https.request()` APIs. + * + * ```js + * import { urlToHttpOptions } from 'node:url'; + * const myURL = new URL('https://a:b@測試?abc#foo'); + * + * console.log(urlToHttpOptions(myURL)); + * /* + * { + * protocol: 'https:', + * hostname: 'xn--g6w251d', + * hash: '#foo', + * search: '?abc', + * pathname: '/', + * path: '/?abc', + * href: 'https://a:b@xn--g6w251d/?abc#foo', + * auth: 'a:b' + * } + * + * ``` + * @since v15.7.0, v14.18.0 + * @param url The `WHATWG URL` object to convert to an options object. + * @return Options object + */ + function urlToHttpOptions(url: URL): ClientRequestArgs; + interface URLFormatOptions { + /** + * `true` if the serialized URL string should include the username and password, `false` otherwise. + * @default true + */ + auth?: boolean | undefined; + /** + * `true` if the serialized URL string should include the fragment, `false` otherwise. + * @default true + */ + fragment?: boolean | undefined; + /** + * `true` if the serialized URL string should include the search query, `false` otherwise. + * @default true + */ + search?: boolean | undefined; + /** + * `true` if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to + * being Punycode encoded. + * @default false + */ + unicode?: boolean | undefined; + } + /** + * Browser-compatible `URL` class, implemented by following the WHATWG URL + * Standard. [Examples of parsed URLs](https://url.spec.whatwg.org/#example-url-parsing) may be found in the Standard itself. + * The `URL` class is also available on the global object. + * + * In accordance with browser conventions, all properties of `URL` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. Thus, unlike `legacy urlObject`s, + * using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still + * return `true`. + * @since v7.0.0, v6.13.0 + */ + class URL { + /** + * Creates a `'blob:nodedata:...'` URL string that represents the given `Blob` object and can be used to retrieve the `Blob` later. + * + * ```js + * import { + * Blob, + * resolveObjectURL, + * } from 'node:buffer'; + * + * const blob = new Blob(['hello']); + * const id = URL.createObjectURL(blob); + * + * // later... + * + * const otherBlob = resolveObjectURL(id); + * console.log(otherBlob.size); + * ``` + * + * The data stored by the registered `Blob` will be retained in memory until `URL.revokeObjectURL()` is called to remove it. + * + * `Blob` objects are registered within the current thread. If using Worker + * Threads, `Blob` objects registered within one Worker will not be available + * to other workers or the main thread. + * @since v16.7.0 + */ + static createObjectURL(blob: NodeBlob): string; + /** + * Removes the stored `Blob` identified by the given ID. Attempting to revoke a + * ID that isn't registered will silently fail. + * @since v16.7.0 + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + static revokeObjectURL(id: string): void; + /** + * Checks if an `input` relative to the `base` can be parsed to a `URL`. + * + * ```js + * const isValid = URL.canParse('/foo', 'https://example.org/'); // true + * + * const isNotValid = URL.canParse('/foo'); // false + * ``` + * @since v19.9.0 + * @param input The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored. If `input` is not a string, it is + * `converted to a string` first. + * @param base The base URL to resolve against if the `input` is not absolute. If `base` is not a string, it is `converted to a string` first. + */ + static canParse(input: string, base?: string): boolean; + /** + * Parses a string as a URL. If `base` is provided, it will be used as the base URL for the purpose of resolving non-absolute `input` URLs. + * Returns `null` if `input` is not a valid. + * @param input The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored. If `input` is not a string, it is + * `converted to a string` first. + * @param base The base URL to resolve against if the `input` is not absolute. If `base` is not a string, it is `converted to a string` first. + * @since v22.1.0 + */ + static parse(input: string, base?: string): URL | null; + constructor(input: string | { toString: () => string }, base?: string | URL); + /** + * Gets and sets the fragment portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/foo#bar'); + * console.log(myURL.hash); + * // Prints #bar + * + * myURL.hash = 'baz'; + * console.log(myURL.href); + * // Prints https://example.org/foo#baz + * ``` + * + * Invalid URL characters included in the value assigned to the `hash` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + hash: string; + /** + * Gets and sets the host portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.host); + * // Prints example.org:81 + * + * myURL.host = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:82/foo + * ``` + * + * Invalid host values assigned to the `host` property are ignored. + */ + host: string; + /** + * Gets and sets the host name portion of the URL. The key difference between`url.host` and `url.hostname` is that `url.hostname` does _not_ include the + * port. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.hostname); + * // Prints example.org + * + * // Setting the hostname does not change the port + * myURL.hostname = 'example.com'; + * console.log(myURL.href); + * // Prints https://example.com:81/foo + * + * // Use myURL.host to change the hostname and port + * myURL.host = 'example.org:82'; + * console.log(myURL.href); + * // Prints https://example.org:82/foo + * ``` + * + * Invalid host name values assigned to the `hostname` property are ignored. + */ + hostname: string; + /** + * Gets and sets the serialized URL. + * + * ```js + * const myURL = new URL('https://example.org/foo'); + * console.log(myURL.href); + * // Prints https://example.org/foo + * + * myURL.href = 'https://example.com/bar'; + * console.log(myURL.href); + * // Prints https://example.com/bar + * ``` + * + * Getting the value of the `href` property is equivalent to calling {@link toString}. + * + * Setting the value of this property to a new value is equivalent to creating a + * new `URL` object using `new URL(value)`. Each of the `URL` object's properties will be modified. + * + * If the value assigned to the `href` property is not a valid URL, a `TypeError` will be thrown. + */ + href: string; + /** + * Gets the read-only serialization of the URL's origin. + * + * ```js + * const myURL = new URL('https://example.org/foo/bar?baz'); + * console.log(myURL.origin); + * // Prints https://example.org + * ``` + * + * ```js + * const idnURL = new URL('https://測試'); + * console.log(idnURL.origin); + * // Prints https://xn--g6w251d + * + * console.log(idnURL.hostname); + * // Prints xn--g6w251d + * ``` + */ + readonly origin: string; + /** + * Gets and sets the password portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.password); + * // Prints xyz + * + * myURL.password = '123'; + * console.log(myURL.href); + * // Prints https://abc:123@example.com/ + * ``` + * + * Invalid URL characters included in the value assigned to the `password` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + password: string; + /** + * Gets and sets the path portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc/xyz?123'); + * console.log(myURL.pathname); + * // Prints /abc/xyz + * + * myURL.pathname = '/abcdef'; + * console.log(myURL.href); + * // Prints https://example.org/abcdef?123 + * ``` + * + * Invalid URL characters included in the value assigned to the `pathname` property are `percent-encoded`. The selection of which characters + * to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + pathname: string; + /** + * Gets and sets the port portion of the URL. + * + * The port value may be a number or a string containing a number in the range `0` to `65535` (inclusive). Setting the value to the default port of the `URL` objects given `protocol` will + * result in the `port` value becoming + * the empty string (`''`). + * + * The port value can be an empty string in which case the port depends on + * the protocol/scheme: + * + * + * + * Upon assigning a value to the port, the value will first be converted to a + * string using `.toString()`. + * + * If that string is invalid but it begins with a number, the leading number is + * assigned to `port`. + * If the number lies outside the range denoted above, it is ignored. + * + * ```js + * const myURL = new URL('https://example.org:8888'); + * console.log(myURL.port); + * // Prints 8888 + * + * // Default ports are automatically transformed to the empty string + * // (HTTPS protocol's default port is 443) + * myURL.port = '443'; + * console.log(myURL.port); + * // Prints the empty string + * console.log(myURL.href); + * // Prints https://example.org/ + * + * myURL.port = 1234; + * console.log(myURL.port); + * // Prints 1234 + * console.log(myURL.href); + * // Prints https://example.org:1234/ + * + * // Completely invalid port strings are ignored + * myURL.port = 'abcd'; + * console.log(myURL.port); + * // Prints 1234 + * + * // Leading numbers are treated as a port number + * myURL.port = '5678abcd'; + * console.log(myURL.port); + * // Prints 5678 + * + * // Non-integers are truncated + * myURL.port = 1234.5678; + * console.log(myURL.port); + * // Prints 1234 + * + * // Out-of-range numbers which are not represented in scientific notation + * // will be ignored. + * myURL.port = 1e10; // 10000000000, will be range-checked as described below + * console.log(myURL.port); + * // Prints 1234 + * ``` + * + * Numbers which contain a decimal point, + * such as floating-point numbers or numbers in scientific notation, + * are not an exception to this rule. + * Leading numbers up to the decimal point will be set as the URL's port, + * assuming they are valid: + * + * ```js + * myURL.port = 4.567e21; + * console.log(myURL.port); + * // Prints 4 (because it is the leading number in the string '4.567e21') + * ``` + */ + port: string; + /** + * Gets and sets the protocol portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org'); + * console.log(myURL.protocol); + * // Prints https: + * + * myURL.protocol = 'ftp'; + * console.log(myURL.href); + * // Prints ftp://example.org/ + * ``` + * + * Invalid URL protocol values assigned to the `protocol` property are ignored. + */ + protocol: string; + /** + * Gets and sets the serialized query portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc?123'); + * console.log(myURL.search); + * // Prints ?123 + * + * myURL.search = 'abc=xyz'; + * console.log(myURL.href); + * // Prints https://example.org/abc?abc=xyz + * ``` + * + * Any invalid URL characters appearing in the value assigned the `search` property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + search: string; + /** + * Gets the `URLSearchParams` object representing the query parameters of the + * URL. This property is read-only but the `URLSearchParams` object it provides + * can be used to mutate the URL instance; to replace the entirety of query + * parameters of the URL, use the {@link search} setter. See `URLSearchParams` documentation for details. + * + * Use care when using `.searchParams` to modify the `URL` because, + * per the WHATWG specification, the `URLSearchParams` object uses + * different rules to determine which characters to percent-encode. For + * instance, the `URL` object will not percent encode the ASCII tilde (`~`) + * character, while `URLSearchParams` will always encode it: + * + * ```js + * const myURL = new URL('https://example.org/abc?foo=~bar'); + * + * console.log(myURL.search); // prints ?foo=~bar + * + * // Modify the URL via searchParams... + * myURL.searchParams.sort(); + * + * console.log(myURL.search); // prints ?foo=%7Ebar + * ``` + */ + readonly searchParams: URLSearchParams; + /** + * Gets and sets the username portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.username); + * // Prints abc + * + * myURL.username = '123'; + * console.log(myURL.href); + * // Prints https://123:xyz@example.com/ + * ``` + * + * Any invalid URL characters appearing in the value assigned the `username` property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + username: string; + /** + * The `toString()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toJSON}. + */ + toString(): string; + /** + * The `toJSON()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toString}. + * + * This method is automatically called when an `URL` object is serialized + * with [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). + * + * ```js + * const myURLs = [ + * new URL('https://www.example.com'), + * new URL('https://test.example.org'), + * ]; + * console.log(JSON.stringify(myURLs)); + * // Prints ["https://www.example.com/","https://test.example.org/"] + * ``` + */ + toJSON(): string; + } + interface URLPatternComponentResult { + input: string; + groups: Record; + } + interface URLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; + } + interface URLPatternOptions { + ignoreCase?: boolean; + } + interface URLPatternResult { + inputs: (string | URLPatternInit)[]; + protocol: URLPatternComponentResult; + username: URLPatternComponentResult; + password: URLPatternComponentResult; + hostname: URLPatternComponentResult; + port: URLPatternComponentResult; + pathname: URLPatternComponentResult; + search: URLPatternComponentResult; + hash: URLPatternComponentResult; + } + /** + * @since v23.8.0 + * @experimental + */ + class URLPattern { + constructor(input: string | URLPatternInit, baseURL: string, options?: URLPatternOptions); + constructor(input?: string | URLPatternInit, options?: URLPatternOptions); + exec(input?: string | URLPatternInit, baseURL?: string): URLPatternResult | null; + readonly hasRegExpGroups: boolean; + readonly hash: string; + readonly hostname: string; + readonly password: string; + readonly pathname: string; + readonly port: string; + readonly protocol: string; + readonly search: string; + test(input?: string | URLPatternInit, baseURL?: string): boolean; + readonly username: string; + } + interface URLSearchParamsIterator extends NodeJS.Iterator { + [Symbol.iterator](): URLSearchParamsIterator; + } + /** + * The `URLSearchParams` API provides read and write access to the query of a `URL`. The `URLSearchParams` class can also be used standalone with one of the + * four following constructors. + * The `URLSearchParams` class is also available on the global object. + * + * The WHATWG `URLSearchParams` interface and the `querystring` module have + * similar purpose, but the purpose of the `querystring` module is more + * general, as it allows the customization of delimiter characters (`&` and `=`). + * On the other hand, this API is designed purely for URL query strings. + * + * ```js + * const myURL = new URL('https://example.org/?abc=123'); + * console.log(myURL.searchParams.get('abc')); + * // Prints 123 + * + * myURL.searchParams.append('abc', 'xyz'); + * console.log(myURL.href); + * // Prints https://example.org/?abc=123&abc=xyz + * + * myURL.searchParams.delete('abc'); + * myURL.searchParams.set('a', 'b'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * + * const newSearchParams = new URLSearchParams(myURL.searchParams); + * // The above is equivalent to + * // const newSearchParams = new URLSearchParams(myURL.search); + * + * newSearchParams.append('a', 'c'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * console.log(newSearchParams.toString()); + * // Prints a=b&a=c + * + * // newSearchParams.toString() is implicitly called + * myURL.search = newSearchParams; + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * newSearchParams.delete('a'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * ``` + * @since v7.5.0, v6.13.0 + */ + class URLSearchParams implements Iterable<[string, string]> { + constructor( + init?: + | URLSearchParams + | string + | Record + | Iterable<[string, string]> + | ReadonlyArray<[string, string]>, + ); + /** + * Append a new name-value pair to the query string. + */ + append(name: string, value: string): void; + /** + * If `value` is provided, removes all name-value pairs + * where name is `name` and value is `value`. + * + * If `value` is not provided, removes all name-value pairs whose name is `name`. + */ + delete(name: string, value?: string): void; + /** + * Returns an ES6 `Iterator` over each of the name-value pairs in the query. + * Each item of the iterator is a JavaScript `Array`. The first item of the `Array` is the `name`, the second item of the `Array` is the `value`. + * + * Alias for `urlSearchParams[Symbol.iterator]()`. + */ + entries(): URLSearchParamsIterator<[string, string]>; + /** + * Iterates over each name-value pair in the query and invokes the given function. + * + * ```js + * const myURL = new URL('https://example.org/?a=b&c=d'); + * myURL.searchParams.forEach((value, name, searchParams) => { + * console.log(name, value, myURL.searchParams === searchParams); + * }); + * // Prints: + * // a b true + * // c d true + * ``` + * @param fn Invoked for each name-value pair in the query + * @param thisArg To be used as `this` value for when `fn` is called + */ + forEach( + fn: (this: TThis, value: string, name: string, searchParams: URLSearchParams) => void, + thisArg?: TThis, + ): void; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns the values of all name-value pairs whose name is `name`. If there are + * no such pairs, an empty array is returned. + */ + getAll(name: string): string[]; + /** + * Checks if the `URLSearchParams` object contains key-value pair(s) based on `name` and an optional `value` argument. + * + * If `value` is provided, returns `true` when name-value pair with + * same `name` and `value` exists. + * + * If `value` is not provided, returns `true` if there is at least one name-value + * pair whose name is `name`. + */ + has(name: string, value?: string): boolean; + /** + * Returns an ES6 `Iterator` over the names of each name-value pair. + * + * ```js + * const params = new URLSearchParams('foo=bar&foo=baz'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // foo + * ``` + */ + keys(): URLSearchParamsIterator; + /** + * Sets the value in the `URLSearchParams` object associated with `name` to `value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value` and remove all others. If not, + * append the name-value pair to the query string. + * + * ```js + * const params = new URLSearchParams(); + * params.append('foo', 'bar'); + * params.append('foo', 'baz'); + * params.append('abc', 'def'); + * console.log(params.toString()); + * // Prints foo=bar&foo=baz&abc=def + * + * params.set('foo', 'def'); + * params.set('xyz', 'opq'); + * console.log(params.toString()); + * // Prints foo=def&abc=def&xyz=opq + * ``` + */ + set(name: string, value: string): void; + /** + * The total number of parameter entries. + * @since v19.8.0 + */ + readonly size: number; + /** + * Sort all existing name-value pairs in-place by their names. Sorting is done + * with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability), so relative order between name-value pairs + * with the same name is preserved. + * + * This method can be used, in particular, to increase cache hits. + * + * ```js + * const params = new URLSearchParams('query[]=abc&type=search&query[]=123'); + * params.sort(); + * console.log(params.toString()); + * // Prints query%5B%5D=abc&query%5B%5D=123&type=search + * ``` + * @since v7.7.0, v6.13.0 + */ + sort(): void; + /** + * Returns the search parameters serialized as a string, with characters + * percent-encoded where necessary. + */ + toString(): string; + /** + * Returns an ES6 `Iterator` over the values of each name-value pair. + */ + values(): URLSearchParamsIterator; + [Symbol.iterator](): URLSearchParamsIterator<[string, string]>; + } + import { + URL as _URL, + URLPattern as _URLPattern, + URLPatternInit as _URLPatternInit, + URLPatternResult as _URLPatternResult, + URLSearchParams as _URLSearchParams, + } from "url"; + global { + interface URL extends _URL {} + var URL: typeof globalThis extends { + onmessage: any; + URL: infer T; + } ? T + : typeof _URL; + interface URLSearchParams extends _URLSearchParams {} + var URLSearchParams: typeof globalThis extends { + onmessage: any; + URLSearchParams: infer T; + } ? T + : typeof _URLSearchParams; + interface URLPatternInit extends _URLPatternInit {} + interface URLPatternResult extends _URLPatternResult {} + interface URLPattern extends _URLPattern {} + var URLPattern: typeof _URLPattern; + } +} +declare module "node:url" { + export * from "url"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/util.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/util.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..142e78b2f849052618e0dc93cac3a5a149d49113 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/util.d.ts @@ -0,0 +1,2309 @@ +/** + * The `node:util` module supports the needs of Node.js internal APIs. Many of the + * utilities are useful for application and module developers as well. To access + * it: + * + * ```js + * import util from 'node:util'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/util.js) + */ +declare module "util" { + import * as types from "node:util/types"; + export interface InspectOptions { + /** + * If `true`, object's non-enumerable symbols and properties are included in the formatted result. + * `WeakMap` and `WeakSet` entries are also included as well as user defined prototype properties (excluding method properties). + * @default false + */ + showHidden?: boolean | undefined; + /** + * Specifies the number of times to recurse while formatting object. + * This is useful for inspecting large objects. + * To recurse up to the maximum call stack size pass `Infinity` or `null`. + * @default 2 + */ + depth?: number | null | undefined; + /** + * If `true`, the output is styled with ANSI color codes. Colors are customizable. + */ + colors?: boolean | undefined; + /** + * If `false`, `[util.inspect.custom](depth, opts, inspect)` functions are not invoked. + * @default true + */ + customInspect?: boolean | undefined; + /** + * If `true`, `Proxy` inspection includes the target and handler objects. + * @default false + */ + showProxy?: boolean | undefined; + /** + * Specifies the maximum number of `Array`, `TypedArray`, `WeakMap`, and `WeakSet` elements + * to include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no elements. + * @default 100 + */ + maxArrayLength?: number | null | undefined; + /** + * Specifies the maximum number of characters to + * include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no characters. + * @default 10000 + */ + maxStringLength?: number | null | undefined; + /** + * The length at which input values are split across multiple lines. + * Set to `Infinity` to format the input as a single line + * (in combination with `compact` set to `true` or any number >= `1`). + * @default 80 + */ + breakLength?: number | undefined; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default true + */ + compact?: boolean | number | undefined; + /** + * If set to `true` or a function, all properties of an object, and `Set` and `Map` + * entries are sorted in the resulting string. + * If set to `true` the default sort is used. + * If set to a function, it is used as a compare function. + */ + sorted?: boolean | ((a: string, b: string) => number) | undefined; + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default false + */ + getters?: "get" | "set" | boolean | undefined; + /** + * If set to `true`, an underscore is used to separate every three digits in all bigints and numbers. + * @default false + */ + numericSeparator?: boolean | undefined; + } + export type Style = + | "special" + | "number" + | "bigint" + | "boolean" + | "undefined" + | "null" + | "string" + | "symbol" + | "date" + | "regexp" + | "module"; + export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => any; // TODO: , inspect: inspect + export interface InspectOptionsStylized extends InspectOptions { + stylize(text: string, styleType: Style): string; + } + export interface CallSiteObject { + /** + * Returns the name of the function associated with this call site. + */ + functionName: string; + /** + * Returns the name of the resource that contains the script for the + * function for this call site. + */ + scriptName: string; + /** + * Returns the unique id of the script, as in Chrome DevTools protocol + * [`Runtime.ScriptId`](https://chromedevtools.github.io/devtools-protocol/1-3/Runtime/#type-ScriptId). + * @since v22.14.0 + */ + scriptId: string; + /** + * Returns the number, 1-based, of the line for the associate function call. + */ + lineNumber: number; + /** + * Returns the 1-based column offset on the line for the associated function call. + */ + columnNumber: number; + } + export type DiffEntry = [operation: -1 | 0 | 1, value: string]; + /** + * `util.diff()` compares two string or array values and returns an array of difference entries. + * It uses the Myers diff algorithm to compute minimal differences, which is the same algorithm + * used internally by assertion error messages. + * + * If the values are equal, an empty array is returned. + * + * ```js + * const { diff } = require('node:util'); + * + * // Comparing strings + * const actualString = '12345678'; + * const expectedString = '12!!5!7!'; + * console.log(diff(actualString, expectedString)); + * // [ + * // [0, '1'], + * // [0, '2'], + * // [1, '3'], + * // [1, '4'], + * // [-1, '!'], + * // [-1, '!'], + * // [0, '5'], + * // [1, '6'], + * // [-1, '!'], + * // [0, '7'], + * // [1, '8'], + * // [-1, '!'], + * // ] + * // Comparing arrays + * const actualArray = ['1', '2', '3']; + * const expectedArray = ['1', '3', '4']; + * console.log(diff(actualArray, expectedArray)); + * // [ + * // [0, '1'], + * // [1, '2'], + * // [0, '3'], + * // [-1, '4'], + * // ] + * // Equal values return empty array + * console.log(diff('same', 'same')); + * // [] + * ``` + * @since v22.15.0 + * @experimental + * @param actual The first value to compare + * @param expected The second value to compare + * @returns An array of difference entries. Each entry is an array with two elements: + * * Index 0: `number` Operation code: `-1` for delete, `0` for no-op/unchanged, `1` for insert + * * Index 1: `string` The value associated with the operation + */ + export function diff(actual: string | readonly string[], expected: string | readonly string[]): DiffEntry[]; + /** + * The `util.format()` method returns a formatted string using the first argument + * as a `printf`-like format string which can contain zero or more format + * specifiers. Each specifier is replaced with the converted value from the + * corresponding argument. Supported specifiers are: + * + * If a specifier does not have a corresponding argument, it is not replaced: + * + * ```js + * util.format('%s:%s', 'foo'); + * // Returns: 'foo:%s' + * ``` + * + * Values that are not part of the format string are formatted using `util.inspect()` if their type is not `string`. + * + * If there are more arguments passed to the `util.format()` method than the + * number of specifiers, the extra arguments are concatenated to the returned + * string, separated by spaces: + * + * ```js + * util.format('%s:%s', 'foo', 'bar', 'baz'); + * // Returns: 'foo:bar baz' + * ``` + * + * If the first argument does not contain a valid format specifier, `util.format()` returns a string that is the concatenation of all arguments separated by spaces: + * + * ```js + * util.format(1, 2, 3); + * // Returns: '1 2 3' + * ``` + * + * If only one argument is passed to `util.format()`, it is returned as it is + * without any formatting: + * + * ```js + * util.format('%% %s'); + * // Returns: '%% %s' + * ``` + * + * `util.format()` is a synchronous method that is intended as a debugging tool. + * Some input values can have a significant performance overhead that can block the + * event loop. Use this function with care and never in a hot code path. + * @since v0.5.3 + * @param format A `printf`-like format string. + */ + export function format(format?: any, ...param: any[]): string; + /** + * This function is identical to {@link format}, except in that it takes + * an `inspectOptions` argument which specifies options that are passed along to {@link inspect}. + * + * ```js + * util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); + * // Returns 'See object { foo: 42 }', where `42` is colored as a number + * // when printed to a terminal. + * ``` + * @since v10.0.0 + */ + export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; + interface GetCallSitesOptions { + /** + * Reconstruct the original location in the stacktrace from the source-map. + * Enabled by default with the flag `--enable-source-maps`. + */ + sourceMap?: boolean | undefined; + } + /** + * Returns an array of call site objects containing the stack of + * the caller function. + * + * ```js + * import { getCallSites } from 'node:util'; + * + * function exampleFunction() { + * const callSites = getCallSites(); + * + * console.log('Call Sites:'); + * callSites.forEach((callSite, index) => { + * console.log(`CallSite ${index + 1}:`); + * console.log(`Function Name: ${callSite.functionName}`); + * console.log(`Script Name: ${callSite.scriptName}`); + * console.log(`Line Number: ${callSite.lineNumber}`); + * console.log(`Column Number: ${callSite.column}`); + * }); + * // CallSite 1: + * // Function Name: exampleFunction + * // Script Name: /home/example.js + * // Line Number: 5 + * // Column Number: 26 + * + * // CallSite 2: + * // Function Name: anotherFunction + * // Script Name: /home/example.js + * // Line Number: 22 + * // Column Number: 3 + * + * // ... + * } + * + * // A function to simulate another stack layer + * function anotherFunction() { + * exampleFunction(); + * } + * + * anotherFunction(); + * ``` + * + * It is possible to reconstruct the original locations by setting the option `sourceMap` to `true`. + * If the source map is not available, the original location will be the same as the current location. + * When the `--enable-source-maps` flag is enabled, for example when using `--experimental-transform-types`, + * `sourceMap` will be true by default. + * + * ```ts + * import { getCallSites } from 'node:util'; + * + * interface Foo { + * foo: string; + * } + * + * const callSites = getCallSites({ sourceMap: true }); + * + * // With sourceMap: + * // Function Name: '' + * // Script Name: example.js + * // Line Number: 7 + * // Column Number: 26 + * + * // Without sourceMap: + * // Function Name: '' + * // Script Name: example.js + * // Line Number: 2 + * // Column Number: 26 + * ``` + * @param frameCount Number of frames to capture as call site objects. + * **Default:** `10`. Allowable range is between 1 and 200. + * @return An array of call site objects + * @since v22.9.0 + */ + export function getCallSites(frameCount?: number, options?: GetCallSitesOptions): CallSiteObject[]; + export function getCallSites(options: GetCallSitesOptions): CallSiteObject[]; + /** + * Returns the string name for a numeric error code that comes from a Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const name = util.getSystemErrorName(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v9.7.0 + */ + export function getSystemErrorName(err: number): string; + /** + * Returns a Map of all system error codes available from the Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const errorMap = util.getSystemErrorMap(); + * const name = errorMap.get(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v16.0.0, v14.17.0 + */ + export function getSystemErrorMap(): Map; + /** + * Returns the string message for a numeric error code that comes from a Node.js + * API. + * The mapping between error codes and string messages is platform-dependent. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const message = util.getSystemErrorMessage(err.errno); + * console.error(message); // no such file or directory + * }); + * ``` + * @since v22.12.0 + */ + export function getSystemErrorMessage(err: number): string; + /** + * Returns the `string` after replacing any surrogate code points + * (or equivalently, any unpaired surrogate code units) with the + * Unicode "replacement character" U+FFFD. + * @since v16.8.0, v14.18.0 + */ + export function toUSVString(string: string): string; + /** + * Creates and returns an `AbortController` instance whose `AbortSignal` is marked + * as transferable and can be used with `structuredClone()` or `postMessage()`. + * @since v18.11.0 + * @returns A transferable AbortController + */ + export function transferableAbortController(): AbortController; + /** + * Marks the given `AbortSignal` as transferable so that it can be used with`structuredClone()` and `postMessage()`. + * + * ```js + * const signal = transferableAbortSignal(AbortSignal.timeout(100)); + * const channel = new MessageChannel(); + * channel.port2.postMessage(signal, [signal]); + * ``` + * @since v18.11.0 + * @param signal The AbortSignal + * @returns The same AbortSignal + */ + export function transferableAbortSignal(signal: AbortSignal): AbortSignal; + /** + * Listens to abort event on the provided `signal` and returns a promise that resolves when the `signal` is aborted. + * If `resource` is provided, it weakly references the operation's associated object, + * so if `resource` is garbage collected before the `signal` aborts, + * then returned promise shall remain pending. + * This prevents memory leaks in long-running or non-cancelable operations. + * + * ```js + * import { aborted } from 'node:util'; + * + * // Obtain an object with an abortable signal, like a custom resource or operation. + * const dependent = obtainSomethingAbortable(); + * + * // Pass `dependent` as the resource, indicating the promise should only resolve + * // if `dependent` is still in memory when the signal is aborted. + * aborted(dependent.signal, dependent).then(() => { + * // This code runs when `dependent` is aborted. + * console.log('Dependent resource was aborted.'); + * }); + * + * // Simulate an event that triggers the abort. + * dependent.on('event', () => { + * dependent.abort(); // This will cause the `aborted` promise to resolve. + * }); + * ``` + * @since v19.7.0 + * @param resource Any non-null object tied to the abortable operation and held weakly. + * If `resource` is garbage collected before the `signal` aborts, the promise remains pending, + * allowing Node.js to stop tracking it. + * This helps prevent memory leaks in long-running or non-cancelable operations. + */ + export function aborted(signal: AbortSignal, resource: any): Promise; + /** + * The `util.inspect()` method returns a string representation of `object` that is + * intended for debugging. The output of `util.inspect` may change at any time + * and should not be depended upon programmatically. Additional `options` may be + * passed that alter the result. + * `util.inspect()` will use the constructor's name and/or `Symbol.toStringTag` + * property to make an identifiable tag for an inspected value. + * + * ```js + * class Foo { + * get [Symbol.toStringTag]() { + * return 'bar'; + * } + * } + * + * class Bar {} + * + * const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); + * + * util.inspect(new Foo()); // 'Foo [bar] {}' + * util.inspect(new Bar()); // 'Bar {}' + * util.inspect(baz); // '[foo] {}' + * ``` + * + * Circular references point to their anchor by using a reference index: + * + * ```js + * import { inspect } from 'node:util'; + * + * const obj = {}; + * obj.a = [obj]; + * obj.b = {}; + * obj.b.inner = obj.b; + * obj.b.obj = obj; + * + * console.log(inspect(obj)); + * // { + * // a: [ [Circular *1] ], + * // b: { inner: [Circular *2], obj: [Circular *1] } + * // } + * ``` + * + * The following example inspects all properties of the `util` object: + * + * ```js + * import util from 'node:util'; + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * import { inspect } from 'node:util'; + * + * const o = { + * a: [1, 2, [[ + * 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + + * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', + * 'test', + * 'foo']], 4], + * b: new Map([['za', 1], ['zb', 'test']]), + * }; + * console.log(inspect(o, { compact: true, depth: 5, breakLength: 80 })); + * + * // { a: + * // [ 1, + * // 2, + * // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line + * // 'test', + * // 'foo' ] ], + * // 4 ], + * // b: Map(2) { 'za' => 1, 'zb' => 'test' } } + * + * // Setting `compact` to false or an integer creates more reader friendly output. + * console.log(inspect(o, { compact: false, depth: 5, breakLength: 80 })); + * + * // { + * // a: [ + * // 1, + * // 2, + * // [ + * // [ + * // 'Lorem ipsum dolor sit amet,\n' + + * // 'consectetur adipiscing elit, sed do eiusmod \n' + + * // 'tempor incididunt ut labore et dolore magna aliqua.', + * // 'test', + * // 'foo' + * // ] + * // ], + * // 4 + * // ], + * // b: Map(2) { + * // 'za' => 1, + * // 'zb' => 'test' + * // } + * // } + * + * // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a + * // single line. + * ``` + * + * The `showHidden` option allows `WeakMap` and `WeakSet` entries to be + * inspected. If there are more entries than `maxArrayLength`, there is no + * guarantee which entries are displayed. That means retrieving the same + * `WeakSet` entries twice may result in different output. Furthermore, entries + * with no remaining strong references may be garbage collected at any time. + * + * ```js + * import { inspect } from 'node:util'; + * + * const obj = { a: 1 }; + * const obj2 = { b: 2 }; + * const weakSet = new WeakSet([obj, obj2]); + * + * console.log(inspect(weakSet, { showHidden: true })); + * // WeakSet { { a: 1 }, { b: 2 } } + * ``` + * + * The `sorted` option ensures that an object's property insertion order does not + * impact the result of `util.inspect()`. + * + * ```js + * import { inspect } from 'node:util'; + * import assert from 'node:assert'; + * + * const o1 = { + * b: [2, 3, 1], + * a: '`a` comes before `b`', + * c: new Set([2, 3, 1]), + * }; + * console.log(inspect(o1, { sorted: true })); + * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } + * console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); + * // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } + * + * const o2 = { + * c: new Set([2, 1, 3]), + * a: '`a` comes before `b`', + * b: [2, 3, 1], + * }; + * assert.strict.equal( + * inspect(o1, { sorted: true }), + * inspect(o2, { sorted: true }), + * ); + * ``` + * + * The `numericSeparator` option adds an underscore every three digits to all + * numbers. + * + * ```js + * import { inspect } from 'node:util'; + * + * const thousand = 1000; + * const million = 1000000; + * const bigNumber = 123456789n; + * const bigDecimal = 1234.12345; + * + * console.log(inspect(thousand, { numericSeparator: true })); + * // 1_000 + * console.log(inspect(million, { numericSeparator: true })); + * // 1_000_000 + * console.log(inspect(bigNumber, { numericSeparator: true })); + * // 123_456_789n + * console.log(inspect(bigDecimal, { numericSeparator: true })); + * // 1_234.123_45 + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MiB. Inputs that result in longer output will + * be truncated. + * @since v0.3.0 + * @param object Any JavaScript primitive or `Object`. + * @return The representation of `object`. + */ + export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + export function inspect(object: any, options?: InspectOptions): string; + export namespace inspect { + let colors: NodeJS.Dict<[number, number]>; + let styles: { + [K in Style]: string; + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; + /** + * That can be used to declare custom inspect functions. + */ + const custom: unique symbol; + } + /** + * Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). + * + * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. + * + * ```js + * import util from 'node:util'; + * + * util.isArray([]); + * // Returns: true + * util.isArray(new Array()); + * // Returns: true + * util.isArray({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use `isArray` instead. + */ + export function isArray(object: unknown): object is unknown[]; + /** + * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and + * `extends` keywords to get language level inheritance support. Also note + * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179). + * + * Inherit the prototype methods from one + * [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The + * prototype of `constructor` will be set to a new object created from + * `superConstructor`. + * + * This mainly adds some input validation on top of + * `Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. + * As an additional convenience, `superConstructor` will be accessible + * through the `constructor.super_` property. + * + * ```js + * const util = require('node:util'); + * const EventEmitter = require('node:events'); + * + * function MyStream() { + * EventEmitter.call(this); + * } + * + * util.inherits(MyStream, EventEmitter); + * + * MyStream.prototype.write = function(data) { + * this.emit('data', data); + * }; + * + * const stream = new MyStream(); + * + * console.log(stream instanceof EventEmitter); // true + * console.log(MyStream.super_ === EventEmitter); // true + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('It works!'); // Received data: "It works!" + * ``` + * + * ES6 example using `class` and `extends`: + * + * ```js + * import EventEmitter from 'node:events'; + * + * class MyStream extends EventEmitter { + * write(data) { + * this.emit('data', data); + * } + * } + * + * const stream = new MyStream(); + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('With ES6'); + * ``` + * @since v0.3.0 + * @legacy Use ES2015 class syntax and `extends` keyword instead. + */ + export function inherits(constructor: unknown, superConstructor: unknown): void; + export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; + export interface DebugLogger extends DebugLoggerFunction { + /** + * The `util.debuglog().enabled` getter is used to create a test that can be used + * in conditionals based on the existence of the `NODE_DEBUG` environment variable. + * If the `section` name appears within the value of that environment variable, + * then the returned value will be `true`. If not, then the returned value will be + * `false`. + * + * ```js + * import { debuglog } from 'node:util'; + * const enabled = debuglog('foo').enabled; + * if (enabled) { + * console.log('hello from foo [%d]', 123); + * } + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then it will + * output something like: + * + * ```console + * hello from foo [123] + * ``` + */ + enabled: boolean; + } + /** + * The `util.debuglog()` method is used to create a function that conditionally + * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG` + * environment variable. If the `section` name appears within the value of that + * environment variable, then the returned function operates similar to + * `console.error()`. If not, then the returned function is a no-op. + * + * ```js + * import { debuglog } from 'node:util'; + * const log = debuglog('foo'); + * + * log('hello from foo [%d]', 123); + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then + * it will output something like: + * + * ```console + * FOO 3245: hello from foo [123] + * ``` + * + * where `3245` is the process id. If it is not run with that + * environment variable set, then it will not print anything. + * + * The `section` supports wildcard also: + * + * ```js + * import { debuglog } from 'node:util'; + * const log = debuglog('foo'); + * + * log('hi there, it\'s foo-bar [%d]', 2333); + * ``` + * + * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output + * something like: + * + * ```console + * FOO-BAR 3257: hi there, it's foo-bar [2333] + * ``` + * + * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG` + * environment variable: `NODE_DEBUG=fs,net,tls`. + * + * The optional `callback` argument can be used to replace the logging function + * with a different function that doesn't have any initialization or + * unnecessary wrapping. + * + * ```js + * import { debuglog } from 'node:util'; + * let log = debuglog('internals', (debug) => { + * // Replace with a logging function that optimizes out + * // testing if the section is enabled + * log = debug; + * }); + * ``` + * @since v0.11.3 + * @param section A string identifying the portion of the application for which the `debuglog` function is being created. + * @param callback A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function. + * @return The logging function + */ + export function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger; + export { debuglog as debug }; + /** + * The `util.deprecate()` method wraps `fn` (which may be a function or class) in + * such a way that it is marked as deprecated. + * + * ```js + * import { deprecate } from 'node:util'; + * + * export const obsoleteFunction = deprecate(() => { + * // Do something here. + * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); + * ``` + * + * When called, `util.deprecate()` will return a function that will emit a + * `DeprecationWarning` using the `'warning'` event. The warning will + * be emitted and printed to `stderr` the first time the returned function is + * called. After the warning is emitted, the wrapped function is called without + * emitting a warning. + * + * If the same optional `code` is supplied in multiple calls to `util.deprecate()`, + * the warning will be emitted only once for that `code`. + * + * ```js + * import { deprecate } from 'node:util'; + * + * const fn1 = deprecate( + * () => 'a value', + * 'deprecation message', + * 'DEP0001', + * ); + * const fn2 = deprecate( + * () => 'a different value', + * 'other dep message', + * 'DEP0001', + * ); + * fn1(); // Emits a deprecation warning with code DEP0001 + * fn2(); // Does not emit a deprecation warning because it has the same code + * ``` + * + * If either the `--no-deprecation` or `--no-warnings` command-line flags are + * used, or if the `process.noDeprecation` property is set to `true` _prior_ to + * the first deprecation warning, the `util.deprecate()` method does nothing. + * + * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set, + * or the `process.traceDeprecation` property is set to `true`, a warning and a + * stack trace are printed to `stderr` the first time the deprecated function is + * called. + * + * If the `--throw-deprecation` command-line flag is set, or the + * `process.throwDeprecation` property is set to `true`, then an exception will be + * thrown when the deprecated function is called. + * + * The `--throw-deprecation` command-line flag and `process.throwDeprecation` + * property take precedence over `--trace-deprecation` and + * `process.traceDeprecation`. + * @since v0.8.0 + * @param fn The function that is being deprecated. + * @param msg A warning message to display when the deprecated function is invoked. + * @param code A deprecation code. See the `list of deprecated APIs` for a list of codes. + * @return The deprecated function wrapped to emit a warning. + */ + export function deprecate(fn: T, msg: string, code?: string): T; + /** + * Returns `true` if there is deep strict equality between `val1` and `val2`. + * Otherwise, returns `false`. + * + * See `assert.deepStrictEqual()` for more information about deep strict + * equality. + * @since v9.0.0 + */ + export function isDeepStrictEqual(val1: unknown, val2: unknown): boolean; + /** + * Returns `str` with any ANSI escape codes removed. + * + * ```js + * console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); + * // Prints "value" + * ``` + * @since v16.11.0 + */ + export function stripVTControlCharacters(str: string): string; + /** + * Takes an `async` function (or a function that returns a `Promise`) and returns a + * function following the error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument. In the callback, the + * first argument will be the rejection reason (or `null` if the `Promise` + * resolved), and the second argument will be the resolved value. + * + * ```js + * import { callbackify } from 'node:util'; + * + * async function fn() { + * return 'hello world'; + * } + * const callbackFunction = callbackify(fn); + * + * callbackFunction((err, ret) => { + * if (err) throw err; + * console.log(ret); + * }); + * ``` + * + * Will print: + * + * ```text + * hello world + * ``` + * + * The callback is executed asynchronously, and will have a limited stack trace. + * If the callback throws, the process will emit an `'uncaughtException'` + * event, and if not handled will exit. + * + * Since `null` has a special meaning as the first argument to a callback, if a + * wrapped function rejects a `Promise` with a falsy value as a reason, the value + * is wrapped in an `Error` with the original value stored in a field named + * `reason`. + * + * ```js + * function fn() { + * return Promise.reject(null); + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * // When the Promise was rejected with `null` it is wrapped with an Error and + * // the original value is stored in `reason`. + * err && Object.hasOwn(err, 'reason') && err.reason === null; // true + * }); + * ``` + * @since v8.2.0 + * @param fn An `async` function + * @return a callback style function + */ + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: () => Promise, + ): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export interface CustomPromisifyLegacy extends Function { + __promisify__: TCustom; + } + export interface CustomPromisifySymbol extends Function { + [promisify.custom]: TCustom; + } + export type CustomPromisify = + | CustomPromisifySymbol + | CustomPromisifyLegacy; + /** + * Takes a function following the common error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument, and returns a version + * that returns promises. + * + * ```js + * import { promisify } from 'node:util'; + * import { stat } from 'node:fs'; + * + * const promisifiedStat = promisify(stat); + * promisifiedStat('.').then((stats) => { + * // Do something with `stats` + * }).catch((error) => { + * // Handle the error. + * }); + * ``` + * + * Or, equivalently using `async function`s: + * + * ```js + * import { promisify } from 'node:util'; + * import { stat } from 'node:fs'; + * + * const promisifiedStat = promisify(stat); + * + * async function callStat() { + * const stats = await promisifiedStat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * + * callStat(); + * ``` + * + * If there is an `original[util.promisify.custom]` property present, `promisify` + * will return its value, see [Custom promisified functions](https://nodejs.org/docs/latest-v24.x/api/util.html#custom-promisified-functions). + * + * `promisify()` assumes that `original` is a function taking a callback as its + * final argument in all cases. If `original` is not a function, `promisify()` + * will throw an error. If `original` is a function but its last argument is not + * an error-first callback, it will still be passed an error-first + * callback as its last argument. + * + * Using `promisify()` on class methods or other methods that use `this` may not + * work as expected unless handled specially: + * + * ```js + * import { promisify } from 'node:util'; + * + * class Foo { + * constructor() { + * this.a = 42; + * } + * + * bar(callback) { + * callback(null, this.a); + * } + * } + * + * const foo = new Foo(); + * + * const naiveBar = promisify(foo.bar); + * // TypeError: Cannot read properties of undefined (reading 'a') + * // naiveBar().then(a => console.log(a)); + * + * naiveBar.call(foo).then((a) => console.log(a)); // '42' + * + * const bindBar = naiveBar.bind(foo); + * bindBar().then((a) => console.log(a)); // '42' + * ``` + * @since v8.0.0 + */ + export function promisify(fn: CustomPromisify): TCustom; + export function promisify( + fn: (callback: (err: any, result: TResult) => void) => void, + ): () => Promise; + export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + export function promisify( + fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: Function): Function; + export namespace promisify { + /** + * That can be used to declare custom promisified variants of functions. + */ + const custom: unique symbol; + } + /** + * Stability: 1.1 - Active development + * Given an example `.env` file: + * + * ```js + * import { parseEnv } from 'node:util'; + * + * parseEnv('HELLO=world\nHELLO=oh my\n'); + * // Returns: { HELLO: 'oh my' } + * ``` + * @param content The raw contents of a `.env` file. + * @since v20.12.0 + */ + export function parseEnv(content: string): NodeJS.Dict; + // https://nodejs.org/docs/latest/api/util.html#foreground-colors + type ForegroundColors = + | "black" + | "blackBright" + | "blue" + | "blueBright" + | "cyan" + | "cyanBright" + | "gray" + | "green" + | "greenBright" + | "grey" + | "magenta" + | "magentaBright" + | "red" + | "redBright" + | "white" + | "whiteBright" + | "yellow" + | "yellowBright"; + // https://nodejs.org/docs/latest/api/util.html#background-colors + type BackgroundColors = + | "bgBlack" + | "bgBlackBright" + | "bgBlue" + | "bgBlueBright" + | "bgCyan" + | "bgCyanBright" + | "bgGray" + | "bgGreen" + | "bgGreenBright" + | "bgGrey" + | "bgMagenta" + | "bgMagentaBright" + | "bgRed" + | "bgRedBright" + | "bgWhite" + | "bgWhiteBright" + | "bgYellow" + | "bgYellowBright"; + // https://nodejs.org/docs/latest/api/util.html#modifiers + type Modifiers = + | "blink" + | "bold" + | "dim" + | "doubleunderline" + | "framed" + | "hidden" + | "inverse" + | "italic" + | "none" + | "overlined" + | "reset" + | "strikethrough" + | "underline"; + export interface StyleTextOptions { + /** + * When true, `stream` is checked to see if it can handle colors. + * @default true + */ + validateStream?: boolean | undefined; + /** + * A stream that will be validated if it can be colored. + * @default process.stdout + */ + stream?: NodeJS.WritableStream | undefined; + } + /** + * This function returns a formatted text considering the `format` passed + * for printing in a terminal. It is aware of the terminal's capabilities + * and acts according to the configuration set via `NO_COLOR`, + * `NODE_DISABLE_COLORS` and `FORCE_COLOR` environment variables. + * + * ```js + * import { styleText } from 'node:util'; + * import { stderr } from 'node:process'; + * + * const successMessage = styleText('green', 'Success!'); + * console.log(successMessage); + * + * const errorMessage = styleText( + * 'red', + * 'Error! Error!', + * // Validate if process.stderr has TTY + * { stream: stderr }, + * ); + * console.error(errorMessage); + * ``` + * + * `util.inspect.colors` also provides text formats such as `italic`, and + * `underline` and you can combine both: + * + * ```js + * console.log( + * util.styleText(['underline', 'italic'], 'My italic underlined message'), + * ); + * ``` + * + * When passing an array of formats, the order of the format applied + * is left to right so the following style might overwrite the previous one. + * + * ```js + * console.log( + * util.styleText(['red', 'green'], 'text'), // green + * ); + * ``` + * + * The special format value `none` applies no additional styling to the text. + * + * The full list of formats can be found in [modifiers](https://nodejs.org/docs/latest-v24.x/api/util.html#modifiers). + * @param format A text format or an Array of text formats defined in `util.inspect.colors`. + * @param text The text to to be formatted. + * @since v20.12.0 + */ + export function styleText( + format: + | ForegroundColors + | BackgroundColors + | Modifiers + | Array, + text: string, + options?: StyleTextOptions, + ): string; + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API. + * + * ```js + * const decoder = new TextDecoder(); + * const u8arr = new Uint8Array([72, 101, 108, 108, 111]); + * console.log(decoder.decode(u8arr)); // Hello + * ``` + * @since v8.3.0 + */ + export class TextDecoder { + /** + * The encoding supported by the `TextDecoder` instance. + */ + readonly encoding: string; + /** + * The value will be `true` if decoding errors result in a `TypeError` being + * thrown. + */ + readonly fatal: boolean; + /** + * The value will be `true` if the decoding result will include the byte order + * mark. + */ + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { + fatal?: boolean | undefined; + ignoreBOM?: boolean | undefined; + }, + ); + /** + * Decodes the `input` and returns a string. If `options.stream` is `true`, any + * incomplete byte sequences occurring at the end of the `input` are buffered + * internally and emitted after the next call to `textDecoder.decode()`. + * + * If `textDecoder.fatal` is `true`, decoding errors that occur will result in a `TypeError` being thrown. + * @param input An `ArrayBuffer`, `DataView`, or `TypedArray` instance containing the encoded data. + */ + decode( + input?: NodeJS.ArrayBufferView | ArrayBuffer | null, + options?: { + stream?: boolean | undefined; + }, + ): string; + } + export interface EncodeIntoResult { + /** + * The read Unicode code units of input. + */ + read: number; + /** + * The written UTF-8 bytes of output. + */ + written: number; + } + export { types }; + + //// TextEncoder/Decoder + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All + * instances of `TextEncoder` only support UTF-8 encoding. + * + * ```js + * const encoder = new TextEncoder(); + * const uint8array = encoder.encode('this is some data'); + * ``` + * + * The `TextEncoder` class is also available on the global object. + * @since v8.3.0 + */ + export class TextEncoder { + /** + * The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. + */ + readonly encoding: string; + /** + * UTF-8 encodes the `input` string and returns a `Uint8Array` containing the + * encoded bytes. + * @param [input='an empty string'] The text to encode. + */ + encode(input?: string): Uint8Array; + /** + * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object + * containing the read Unicode code units and written UTF-8 bytes. + * + * ```js + * const encoder = new TextEncoder(); + * const src = 'this is some data'; + * const dest = new Uint8Array(10); + * const { read, written } = encoder.encodeInto(src, dest); + * ``` + * @param src The text to encode. + * @param dest The array to hold the encode result. + */ + encodeInto(src: string, dest: Uint8Array): EncodeIntoResult; + } + import { TextDecoder as _TextDecoder, TextEncoder as _TextEncoder } from "util"; + global { + /** + * `TextDecoder` class is a global reference for `import { TextDecoder } from 'node:util'` + * https://nodejs.org/api/globals.html#textdecoder + * @since v11.0.0 + */ + var TextDecoder: typeof globalThis extends { + onmessage: any; + TextDecoder: infer TextDecoder; + } ? TextDecoder + : typeof _TextDecoder; + /** + * `TextEncoder` class is a global reference for `import { TextEncoder } from 'node:util'` + * https://nodejs.org/api/globals.html#textencoder + * @since v11.0.0 + */ + var TextEncoder: typeof globalThis extends { + onmessage: any; + TextEncoder: infer TextEncoder; + } ? TextEncoder + : typeof _TextEncoder; + } + + //// parseArgs + /** + * Provides a higher level API for command-line argument parsing than interacting + * with `process.argv` directly. Takes a specification for the expected arguments + * and returns a structured object with the parsed options and positionals. + * + * ```js + * import { parseArgs } from 'node:util'; + * const args = ['-f', '--bar', 'b']; + * const options = { + * foo: { + * type: 'boolean', + * short: 'f', + * }, + * bar: { + * type: 'string', + * }, + * }; + * const { + * values, + * positionals, + * } = parseArgs({ args, options }); + * console.log(values, positionals); + * // Prints: [Object: null prototype] { foo: true, bar: 'b' } [] + * ``` + * @since v18.3.0, v16.17.0 + * @param config Used to provide arguments for parsing and to configure the parser. `config` supports the following properties: + * @return The parsed command line arguments: + */ + export function parseArgs(config?: T): ParsedResults; + + /** + * Type of argument used in {@link parseArgs}. + */ + export type ParseArgsOptionsType = "boolean" | "string"; + + export interface ParseArgsOptionDescriptor { + /** + * Type of argument. + */ + type: ParseArgsOptionsType; + /** + * Whether this option can be provided multiple times. + * If `true`, all values will be collected in an array. + * If `false`, values for the option are last-wins. + * @default false. + */ + multiple?: boolean | undefined; + /** + * A single character alias for the option. + */ + short?: string | undefined; + /** + * The default value to + * be used if (and only if) the option does not appear in the arguments to be + * parsed. It must be of the same type as the `type` property. When `multiple` + * is `true`, it must be an array. + * @since v18.11.0 + */ + default?: string | boolean | string[] | boolean[] | undefined; + } + export interface ParseArgsOptionsConfig { + [longOption: string]: ParseArgsOptionDescriptor; + } + export interface ParseArgsConfig { + /** + * Array of argument strings. + */ + args?: string[] | undefined; + /** + * Used to describe arguments known to the parser. + */ + options?: ParseArgsOptionsConfig | undefined; + /** + * Should an error be thrown when unknown arguments are encountered, + * or when arguments are passed that do not match the `type` configured in `options`. + * @default true + */ + strict?: boolean | undefined; + /** + * Whether this command accepts positional arguments. + */ + allowPositionals?: boolean | undefined; + /** + * If `true`, allows explicitly setting boolean options to `false` by prefixing the option name with `--no-`. + * @default false + * @since v22.4.0 + */ + allowNegative?: boolean | undefined; + /** + * Return the parsed tokens. This is useful for extending the built-in behavior, + * from adding additional checks through to reprocessing the tokens in different ways. + * @default false + */ + tokens?: boolean | undefined; + } + /* + IfDefaultsTrue and IfDefaultsFalse are helpers to handle default values for missing boolean properties. + TypeScript does not have exact types for objects: https://github.com/microsoft/TypeScript/issues/12936 + This means it is impossible to distinguish between "field X is definitely not present" and "field X may or may not be present". + But we expect users to generally provide their config inline or `as const`, which means TS will always know whether a given field is present. + So this helper treats "not definitely present" (i.e., not `extends boolean`) as being "definitely not present", i.e. it should have its default value. + This is technically incorrect but is a much nicer UX for the common case. + The IfDefaultsTrue version is for things which default to true; the IfDefaultsFalse version is for things which default to false. + */ + type IfDefaultsTrue = T extends true ? IfTrue + : T extends false ? IfFalse + : IfTrue; + + // we put the `extends false` condition first here because `undefined` compares like `any` when `strictNullChecks: false` + type IfDefaultsFalse = T extends false ? IfFalse + : T extends true ? IfTrue + : IfFalse; + + type ExtractOptionValue = IfDefaultsTrue< + T["strict"], + O["type"] extends "string" ? string : O["type"] extends "boolean" ? boolean : string | boolean, + string | boolean + >; + + type ApplyOptionalModifiers> = ( + & { -readonly [LongOption in keyof O]?: V[LongOption] } + & { [LongOption in keyof O as O[LongOption]["default"] extends {} ? LongOption : never]: V[LongOption] } + ) extends infer P ? { [K in keyof P]: P[K] } : never; // resolve intersection to object + + type ParsedValues = + & IfDefaultsTrue + & (T["options"] extends ParseArgsOptionsConfig ? ApplyOptionalModifiers< + T["options"], + { + [LongOption in keyof T["options"]]: IfDefaultsFalse< + T["options"][LongOption]["multiple"], + Array>, + ExtractOptionValue + >; + } + > + : {}); + + type ParsedPositionals = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type PreciseTokenForOptions< + K extends string, + O extends ParseArgsOptionDescriptor, + > = O["type"] extends "string" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: string; + inlineValue: boolean; + } + : O["type"] extends "boolean" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: undefined; + inlineValue: undefined; + } + : OptionToken & { name: K }; + + type TokenForOptions< + T extends ParseArgsConfig, + K extends keyof T["options"] = keyof T["options"], + > = K extends unknown + ? T["options"] extends ParseArgsOptionsConfig ? PreciseTokenForOptions + : OptionToken + : never; + + type ParsedOptionToken = IfDefaultsTrue, OptionToken>; + + type ParsedPositionalToken = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type ParsedTokens = Array< + ParsedOptionToken | ParsedPositionalToken | { kind: "option-terminator"; index: number } + >; + + type PreciseParsedResults = IfDefaultsFalse< + T["tokens"], + { + values: ParsedValues; + positionals: ParsedPositionals; + tokens: ParsedTokens; + }, + { + values: ParsedValues; + positionals: ParsedPositionals; + } + >; + + type OptionToken = + | { kind: "option"; index: number; name: string; rawName: string; value: string; inlineValue: boolean } + | { + kind: "option"; + index: number; + name: string; + rawName: string; + value: undefined; + inlineValue: undefined; + }; + + type Token = + | OptionToken + | { kind: "positional"; index: number; value: string } + | { kind: "option-terminator"; index: number }; + + // If ParseArgsConfig extends T, then the user passed config constructed elsewhere. + // So we can't rely on the `"not definitely present" implies "definitely not present"` assumption mentioned above. + type ParsedResults = ParseArgsConfig extends T ? { + values: { + [longOption: string]: undefined | string | boolean | Array; + }; + positionals: string[]; + tokens?: Token[]; + } + : PreciseParsedResults; + + /** + * An implementation of [the MIMEType class](https://bmeck.github.io/node-proposal-mime-api/). + * + * In accordance with browser conventions, all properties of `MIMEType` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. + * + * A MIME string is a structured string containing multiple meaningful + * components. When parsed, a `MIMEType` object is returned containing + * properties for each of these components. + * @since v19.1.0, v18.13.0 + */ + export class MIMEType { + /** + * Creates a new MIMEType object by parsing the input. + * + * A `TypeError` will be thrown if the `input` is not a valid MIME. + * Note that an effort will be made to coerce the given values into strings. + * @param input The input MIME to parse. + */ + constructor(input: string | { toString: () => string }); + + /** + * Gets and sets the type portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript'); + * console.log(myMIME.type); + * // Prints: text + * myMIME.type = 'application'; + * console.log(myMIME.type); + * // Prints: application + * console.log(String(myMIME)); + * // Prints: application/javascript + * ``` + */ + type: string; + /** + * Gets and sets the subtype portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/ecmascript'); + * console.log(myMIME.subtype); + * // Prints: ecmascript + * myMIME.subtype = 'javascript'; + * console.log(myMIME.subtype); + * // Prints: javascript + * console.log(String(myMIME)); + * // Prints: text/javascript + * ``` + */ + subtype: string; + /** + * Gets the essence of the MIME. This property is read only. + * Use `mime.type` or `mime.subtype` to alter the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript;key=value'); + * console.log(myMIME.essence); + * // Prints: text/javascript + * myMIME.type = 'application'; + * console.log(myMIME.essence); + * // Prints: application/javascript + * console.log(String(myMIME)); + * // Prints: application/javascript;key=value + * ``` + */ + readonly essence: string; + /** + * Gets the `MIMEParams` object representing the + * parameters of the MIME. This property is read-only. See `MIMEParams` documentation for details. + */ + readonly params: MIMEParams; + /** + * The `toString()` method on the `MIMEType` object returns the serialized MIME. + * + * Because of the need for standard compliance, this method does not allow users + * to customize the serialization process of the MIME. + */ + toString(): string; + } + /** + * The `MIMEParams` API provides read and write access to the parameters of a `MIMEType`. + * @since v19.1.0, v18.13.0 + */ + export class MIMEParams { + /** + * Remove all name-value pairs whose name is `name`. + */ + delete(name: string): void; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + * Each item of the iterator is a JavaScript `Array`. The first item of the array + * is the `name`, the second item of the array is the `value`. + */ + entries(): NodeJS.Iterator<[name: string, value: string]>; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ + has(name: string): boolean; + /** + * Returns an iterator over the names of each name-value pair. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // bar + * ``` + */ + keys(): NodeJS.Iterator; + /** + * Sets the value in the `MIMEParams` object associated with `name` to `value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value`. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * params.set('foo', 'def'); + * params.set('baz', 'xyz'); + * console.log(params.toString()); + * // Prints: foo=def;bar=1;baz=xyz + * ``` + */ + set(name: string, value: string): void; + /** + * Returns an iterator over the values of each name-value pair. + */ + values(): NodeJS.Iterator; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + */ + [Symbol.iterator](): NodeJS.Iterator<[name: string, value: string]>; + } +} +declare module "util/types" { + import { KeyObject, webcrypto } from "node:crypto"; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or + * [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * + * See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`. + * + * ```js + * util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isAnyArrayBuffer(object: unknown): object is ArrayBufferLike; + /** + * Returns `true` if the value is an `arguments` object. + * + * ```js + * function foo() { + * util.types.isArgumentsObject(arguments); // Returns true + * } + * ``` + * @since v10.0.0 + */ + function isArgumentsObject(object: unknown): object is IArguments; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance. + * This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false + * ``` + * @since v10.0.0 + */ + function isArrayBuffer(object: unknown): object is ArrayBuffer; + /** + * Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) views, such as typed + * array objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent to + * [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * + * ```js + * util.types.isArrayBufferView(new Int8Array()); // true + * util.types.isArrayBufferView(Buffer.from('hello world')); // true + * util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true + * util.types.isArrayBufferView(new ArrayBuffer()); // false + * ``` + * @since v10.0.0 + */ + function isArrayBufferView(object: unknown): object is NodeJS.ArrayBufferView; + /** + * Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isAsyncFunction(function foo() {}); // Returns false + * util.types.isAsyncFunction(async function foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isAsyncFunction(object: unknown): boolean; + /** + * Returns `true` if the value is a `BigInt64Array` instance. + * + * ```js + * util.types.isBigInt64Array(new BigInt64Array()); // Returns true + * util.types.isBigInt64Array(new BigUint64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isBigInt64Array(value: unknown): value is BigInt64Array; + /** + * Returns `true` if the value is a BigInt object, e.g. created + * by `Object(BigInt(123))`. + * + * ```js + * util.types.isBigIntObject(Object(BigInt(123))); // Returns true + * util.types.isBigIntObject(BigInt(123)); // Returns false + * util.types.isBigIntObject(123); // Returns false + * ``` + * @since v10.4.0 + */ + function isBigIntObject(object: unknown): object is BigInt; + /** + * Returns `true` if the value is a `BigUint64Array` instance. + * + * ```js + * util.types.isBigUint64Array(new BigInt64Array()); // Returns false + * util.types.isBigUint64Array(new BigUint64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isBigUint64Array(value: unknown): value is BigUint64Array; + /** + * Returns `true` if the value is a boolean object, e.g. created + * by `new Boolean()`. + * + * ```js + * util.types.isBooleanObject(false); // Returns false + * util.types.isBooleanObject(true); // Returns false + * util.types.isBooleanObject(new Boolean(false)); // Returns true + * util.types.isBooleanObject(new Boolean(true)); // Returns true + * util.types.isBooleanObject(Boolean(false)); // Returns false + * util.types.isBooleanObject(Boolean(true)); // Returns false + * ``` + * @since v10.0.0 + */ + function isBooleanObject(object: unknown): object is Boolean; + /** + * Returns `true` if the value is any boxed primitive object, e.g. created + * by `new Boolean()`, `new String()` or `Object(Symbol())`. + * + * For example: + * + * ```js + * util.types.isBoxedPrimitive(false); // Returns false + * util.types.isBoxedPrimitive(new Boolean(false)); // Returns true + * util.types.isBoxedPrimitive(Symbol('foo')); // Returns false + * util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true + * util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true + * ``` + * @since v10.11.0 + */ + function isBoxedPrimitive(object: unknown): object is String | Number | BigInt | Boolean | Symbol; + /** + * Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance. + * + * ```js + * const ab = new ArrayBuffer(20); + * util.types.isDataView(new DataView(ab)); // Returns true + * util.types.isDataView(new Float64Array()); // Returns false + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isDataView(object: unknown): object is DataView; + /** + * Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance. + * + * ```js + * util.types.isDate(new Date()); // Returns true + * ``` + * @since v10.0.0 + */ + function isDate(object: unknown): object is Date; + /** + * Returns `true` if the value is a native `External` value. + * + * A native `External` value is a special type of object that contains a + * raw C++ pointer (`void*`) for access from native code, and has no other + * properties. Such objects are created either by Node.js internals or native + * addons. In JavaScript, they are + * [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a + * `null` prototype. + * + * ```c + * #include + * #include + * napi_value result; + * static napi_value MyNapi(napi_env env, napi_callback_info info) { + * int* raw = (int*) malloc(1024); + * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); + * if (status != napi_ok) { + * napi_throw_error(env, NULL, "napi_create_external failed"); + * return NULL; + * } + * return result; + * } + * ... + * DECLARE_NAPI_PROPERTY("myNapi", MyNapi) + * ... + * ``` + * + * ```js + * import native from 'napi_addon.node'; + * import { types } from 'node:util'; + * + * const data = native.myNapi(); + * types.isExternal(data); // returns true + * types.isExternal(0); // returns false + * types.isExternal(new String('foo')); // returns false + * ``` + * + * For further information on `napi_create_external`, refer to + * [`napi_create_external()`](https://nodejs.org/docs/latest-v24.x/api/n-api.html#napi_create_external). + * @since v10.0.0 + */ + function isExternal(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`Float16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float16Array) instance. + * + * ```js + * util.types.isFloat16Array(new ArrayBuffer()); // Returns false + * util.types.isFloat16Array(new Float16Array()); // Returns true + * util.types.isFloat16Array(new Float32Array()); // Returns false + * ``` + * @since v24.0.0 + */ + function isFloat16Array(object: unknown): object is Float16Array; + /** + * Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance. + * + * ```js + * util.types.isFloat32Array(new ArrayBuffer()); // Returns false + * util.types.isFloat32Array(new Float32Array()); // Returns true + * util.types.isFloat32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isFloat32Array(object: unknown): object is Float32Array; + /** + * Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance. + * + * ```js + * util.types.isFloat64Array(new ArrayBuffer()); // Returns false + * util.types.isFloat64Array(new Uint8Array()); // Returns false + * util.types.isFloat64Array(new Float64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isFloat64Array(object: unknown): object is Float64Array; + /** + * Returns `true` if the value is a generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isGeneratorFunction(function foo() {}); // Returns false + * util.types.isGeneratorFunction(function* foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorFunction(object: unknown): object is GeneratorFunction; + /** + * Returns `true` if the value is a generator object as returned from a + * built-in generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * function* foo() {} + * const generator = foo(); + * util.types.isGeneratorObject(generator); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorObject(object: unknown): object is Generator; + /** + * Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance. + * + * ```js + * util.types.isInt8Array(new ArrayBuffer()); // Returns false + * util.types.isInt8Array(new Int8Array()); // Returns true + * util.types.isInt8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt8Array(object: unknown): object is Int8Array; + /** + * Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance. + * + * ```js + * util.types.isInt16Array(new ArrayBuffer()); // Returns false + * util.types.isInt16Array(new Int16Array()); // Returns true + * util.types.isInt16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt16Array(object: unknown): object is Int16Array; + /** + * Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance. + * + * ```js + * util.types.isInt32Array(new ArrayBuffer()); // Returns false + * util.types.isInt32Array(new Int32Array()); // Returns true + * util.types.isInt32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt32Array(object: unknown): object is Int32Array; + /** + * Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * util.types.isMap(new Map()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMap( + object: T | {}, + ): object is T extends ReadonlyMap ? (unknown extends T ? never : ReadonlyMap) + : Map; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * const map = new Map(); + * util.types.isMapIterator(map.keys()); // Returns true + * util.types.isMapIterator(map.values()); // Returns true + * util.types.isMapIterator(map.entries()); // Returns true + * util.types.isMapIterator(map[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMapIterator(object: unknown): boolean; + /** + * Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects). + * + * ```js + * import * as ns from './a.js'; + * + * util.types.isModuleNamespaceObject(ns); // Returns true + * ``` + * @since v10.0.0 + */ + function isModuleNamespaceObject(value: unknown): boolean; + /** + * Returns `true` if the value was returned by the constructor of a + * [built-in `Error` type](https://tc39.es/ecma262/#sec-error-objects). + * + * ```js + * console.log(util.types.isNativeError(new Error())); // true + * console.log(util.types.isNativeError(new TypeError())); // true + * console.log(util.types.isNativeError(new RangeError())); // true + * ``` + * + * Subclasses of the native error types are also native errors: + * + * ```js + * class MyError extends Error {} + * console.log(util.types.isNativeError(new MyError())); // true + * ``` + * + * A value being `instanceof` a native error class is not equivalent to `isNativeError()` + * returning `true` for that value. `isNativeError()` returns `true` for errors + * which come from a different [realm](https://tc39.es/ecma262/#realm) while `instanceof Error` returns `false` + * for these errors: + * + * ```js + * import { createContext, runInContext } from 'node:vm'; + * import { types } from 'node:util'; + * + * const context = createContext({}); + * const myError = runInContext('new Error()', context); + * console.log(types.isNativeError(myError)); // true + * console.log(myError instanceof Error); // false + * ``` + * + * Conversely, `isNativeError()` returns `false` for all objects which were not + * returned by the constructor of a native error. That includes values + * which are `instanceof` native errors: + * + * ```js + * const myError = { __proto__: Error.prototype }; + * console.log(util.types.isNativeError(myError)); // false + * console.log(myError instanceof Error); // true + * ``` + * @since v10.0.0 + * @deprecated The `util.types.isNativeError` API is deprecated. Please use `Error.isError` instead. + */ + function isNativeError(object: unknown): object is Error; + /** + * Returns `true` if the value is a number object, e.g. created + * by `new Number()`. + * + * ```js + * util.types.isNumberObject(0); // Returns false + * util.types.isNumberObject(new Number(0)); // Returns true + * ``` + * @since v10.0.0 + */ + function isNumberObject(object: unknown): object is Number; + /** + * Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + * + * ```js + * util.types.isPromise(Promise.resolve(42)); // Returns true + * ``` + * @since v10.0.0 + */ + function isPromise(object: unknown): object is Promise; + /** + * Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance. + * + * ```js + * const target = {}; + * const proxy = new Proxy(target, {}); + * util.types.isProxy(target); // Returns false + * util.types.isProxy(proxy); // Returns true + * ``` + * @since v10.0.0 + */ + function isProxy(object: unknown): boolean; + /** + * Returns `true` if the value is a regular expression object. + * + * ```js + * util.types.isRegExp(/abc/); // Returns true + * util.types.isRegExp(new RegExp('abc')); // Returns true + * ``` + * @since v10.0.0 + */ + function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * util.types.isSet(new Set()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSet( + object: T | {}, + ): object is T extends ReadonlySet ? (unknown extends T ? never : ReadonlySet) : Set; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * const set = new Set(); + * util.types.isSetIterator(set.keys()); // Returns true + * util.types.isSetIterator(set.values()); // Returns true + * util.types.isSetIterator(set.entries()); // Returns true + * util.types.isSetIterator(set[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSetIterator(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * This does _not_ include [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false + * util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSharedArrayBuffer(object: unknown): object is SharedArrayBuffer; + /** + * Returns `true` if the value is a string object, e.g. created + * by `new String()`. + * + * ```js + * util.types.isStringObject('foo'); // Returns false + * util.types.isStringObject(new String('foo')); // Returns true + * ``` + * @since v10.0.0 + */ + function isStringObject(object: unknown): object is String; + /** + * Returns `true` if the value is a symbol object, created + * by calling `Object()` on a `Symbol` primitive. + * + * ```js + * const symbol = Symbol('foo'); + * util.types.isSymbolObject(symbol); // Returns false + * util.types.isSymbolObject(Object(symbol)); // Returns true + * ``` + * @since v10.0.0 + */ + function isSymbolObject(object: unknown): object is Symbol; + /** + * Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance. + * + * ```js + * util.types.isTypedArray(new ArrayBuffer()); // Returns false + * util.types.isTypedArray(new Uint8Array()); // Returns true + * util.types.isTypedArray(new Float64Array()); // Returns true + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isTypedArray(object: unknown): object is NodeJS.TypedArray; + /** + * Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance. + * + * ```js + * util.types.isUint8Array(new ArrayBuffer()); // Returns false + * util.types.isUint8Array(new Uint8Array()); // Returns true + * util.types.isUint8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8Array(object: unknown): object is Uint8Array; + /** + * Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance. + * + * ```js + * util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false + * util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true + * util.types.isUint8ClampedArray(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8ClampedArray(object: unknown): object is Uint8ClampedArray; + /** + * Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance. + * + * ```js + * util.types.isUint16Array(new ArrayBuffer()); // Returns false + * util.types.isUint16Array(new Uint16Array()); // Returns true + * util.types.isUint16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint16Array(object: unknown): object is Uint16Array; + /** + * Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance. + * + * ```js + * util.types.isUint32Array(new ArrayBuffer()); // Returns false + * util.types.isUint32Array(new Uint32Array()); // Returns true + * util.types.isUint32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint32Array(object: unknown): object is Uint32Array; + /** + * Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance. + * + * ```js + * util.types.isWeakMap(new WeakMap()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakMap(object: unknown): object is WeakMap; + /** + * Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance. + * + * ```js + * util.types.isWeakSet(new WeakSet()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakSet(object: unknown): object is WeakSet; + /** + * Returns `true` if `value` is a `KeyObject`, `false` otherwise. + * @since v16.2.0 + */ + function isKeyObject(object: unknown): object is KeyObject; + /** + * Returns `true` if `value` is a `CryptoKey`, `false` otherwise. + * @since v16.2.0 + */ + function isCryptoKey(object: unknown): object is webcrypto.CryptoKey; +} +declare module "node:util" { + export * from "util"; +} +declare module "node:util/types" { + export * from "util/types"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/v8.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/v8.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d9af4e2b7cb90c7e0cc4f70a841a608366f6eb9 --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/v8.d.ts @@ -0,0 +1,919 @@ +/** + * The `node:v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using: + * + * ```js + * import v8 from 'node:v8'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/v8.js) + */ +declare module "v8" { + import { Readable } from "node:stream"; + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + number_of_native_contexts: number; + number_of_detached_contexts: number; + total_global_handles_size: number; + used_global_handles_size: number; + external_memory: number; + } + interface HeapCodeStatistics { + code_and_metadata_size: number; + bytecode_and_metadata_size: number; + external_script_source_size: number; + } + interface HeapSnapshotOptions { + /** + * If true, expose internals in the heap snapshot. + * @default false + */ + exposeInternals?: boolean; + /** + * If true, expose numeric values in artificial fields. + * @default false + */ + exposeNumericValues?: boolean; + } + /** + * Returns an integer representing a version tag derived from the V8 version, + * command-line flags, and detected CPU features. This is useful for determining + * whether a `vm.Script` `cachedData` buffer is compatible with this instance + * of V8. + * + * ```js + * console.log(v8.cachedDataVersionTag()); // 3947234607 + * // The value returned by v8.cachedDataVersionTag() is derived from the V8 + * // version, command-line flags, and detected CPU features. Test that the value + * // does indeed update when flags are toggled. + * v8.setFlagsFromString('--allow_natives_syntax'); + * console.log(v8.cachedDataVersionTag()); // 183726201 + * ``` + * @since v8.0.0 + */ + function cachedDataVersionTag(): number; + /** + * Returns an object with the following properties: + * + * `does_zap_garbage` is a 0/1 boolean, which signifies whether the `--zap_code_space` option is enabled or not. This makes V8 overwrite heap + * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger + * because it continuously touches all heap pages and that makes them less likely + * to get swapped out by the operating system. + * + * `number_of_native_contexts` The value of native\_context is the number of the + * top-level contexts currently active. Increase of this number over time indicates + * a memory leak. + * + * `number_of_detached_contexts` The value of detached\_context is the number + * of contexts that were detached and not yet garbage collected. This number + * being non-zero indicates a potential memory leak. + * + * `total_global_handles_size` The value of total\_global\_handles\_size is the + * total memory size of V8 global handles. + * + * `used_global_handles_size` The value of used\_global\_handles\_size is the + * used memory size of V8 global handles. + * + * `external_memory` The value of external\_memory is the memory size of array + * buffers and external strings. + * + * ```js + * { + * total_heap_size: 7326976, + * total_heap_size_executable: 4194304, + * total_physical_size: 7326976, + * total_available_size: 1152656, + * used_heap_size: 3476208, + * heap_size_limit: 1535115264, + * malloced_memory: 16384, + * peak_malloced_memory: 1127496, + * does_zap_garbage: 0, + * number_of_native_contexts: 1, + * number_of_detached_contexts: 0, + * total_global_handles_size: 8192, + * used_global_handles_size: 3296, + * external_memory: 318824 + * } + * ``` + * @since v1.0.0 + */ + function getHeapStatistics(): HeapInfo; + /** + * It returns an object with a structure similar to the + * [`cppgc::HeapStatistics`](https://v8docs.nodesource.com/node-22.4/d7/d51/heap-statistics_8h_source.html) + * object. See the [V8 documentation](https://v8docs.nodesource.com/node-22.4/df/d2f/structcppgc_1_1_heap_statistics.html) + * for more information about the properties of the object. + * + * ```js + * // Detailed + * ({ + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 152, + * space_statistics: [ + * { + * name: 'NormalPageSpace0', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace1', + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 152, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace2', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace3', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'LargePageSpace', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * ], + * type_names: [], + * detail_level: 'detailed', + * }); + * ``` + * + * ```js + * // Brief + * ({ + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 128864, + * space_statistics: [], + * type_names: [], + * detail_level: 'brief', + * }); + * ``` + * @since v22.15.0 + * @param detailLevel **Default:** `'detailed'`. Specifies the level of detail in the returned statistics. + * Accepted values are: + * * `'brief'`: Brief statistics contain only the top-level + * allocated and used + * memory statistics for the entire heap. + * * `'detailed'`: Detailed statistics also contain a break + * down per space and page, as well as freelist statistics + * and object type histograms. + */ + function getCppHeapStatistics(detailLevel?: "brief" | "detailed"): object; + /** + * Returns statistics about the V8 heap spaces, i.e. the segments which make up + * the V8 heap. Neither the ordering of heap spaces, nor the availability of a + * heap space can be guaranteed as the statistics are provided via the + * V8 [`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the + * next. + * + * The value returned is an array of objects containing the following properties: + * + * ```json + * [ + * { + * "space_name": "new_space", + * "space_size": 2063872, + * "space_used_size": 951112, + * "space_available_size": 80824, + * "physical_space_size": 2063872 + * }, + * { + * "space_name": "old_space", + * "space_size": 3090560, + * "space_used_size": 2493792, + * "space_available_size": 0, + * "physical_space_size": 3090560 + * }, + * { + * "space_name": "code_space", + * "space_size": 1260160, + * "space_used_size": 644256, + * "space_available_size": 960, + * "physical_space_size": 1260160 + * }, + * { + * "space_name": "map_space", + * "space_size": 1094160, + * "space_used_size": 201608, + * "space_available_size": 0, + * "physical_space_size": 1094160 + * }, + * { + * "space_name": "large_object_space", + * "space_size": 0, + * "space_used_size": 0, + * "space_available_size": 1490980608, + * "physical_space_size": 0 + * } + * ] + * ``` + * @since v6.0.0 + */ + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + /** + * The `v8.setFlagsFromString()` method can be used to programmatically set + * V8 command-line flags. This method should be used with care. Changing settings + * after the VM has started may result in unpredictable behavior, including + * crashes and data loss; or it may simply do nothing. + * + * The V8 options available for a version of Node.js may be determined by running `node --v8-options`. + * + * Usage: + * + * ```js + * // Print GC events to stdout for one minute. + * import v8 from 'node:v8'; + * v8.setFlagsFromString('--trace_gc'); + * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); + * ``` + * @since v1.0.0 + */ + function setFlagsFromString(flags: string): void; + /** + * This is similar to the [`queryObjects()` console API](https://developer.chrome.com/docs/devtools/console/utilities#queryObjects-function) + * provided by the Chromium DevTools console. It can be used to search for objects that have the matching constructor on its prototype chain + * in the heap after a full garbage collection, which can be useful for memory leak regression tests. To avoid surprising results, users should + * avoid using this API on constructors whose implementation they don't control, or on constructors that can be invoked by other parties in the + * application. + * + * To avoid accidental leaks, this API does not return raw references to the objects found. By default, it returns the count of the objects + * found. If `options.format` is `'summary'`, it returns an array containing brief string representations for each object. The visibility provided + * in this API is similar to what the heap snapshot provides, while users can save the cost of serialization and parsing and directly filter the + * target objects during the search. + * + * Only objects created in the current execution context are included in the results. + * + * ```js + * import { queryObjects } from 'node:v8'; + * class A { foo = 'bar'; } + * console.log(queryObjects(A)); // 0 + * const a = new A(); + * console.log(queryObjects(A)); // 1 + * // [ "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * + * class B extends A { bar = 'qux'; } + * const b = new B(); + * console.log(queryObjects(B)); // 1 + * // [ "B { foo: 'bar', bar: 'qux' }" ] + * console.log(queryObjects(B, { format: 'summary' })); + * + * // Note that, when there are child classes inheriting from a constructor, + * // the constructor also shows up in the prototype chain of the child + * // classes's prototoype, so the child classes's prototoype would also be + * // included in the result. + * console.log(queryObjects(A)); // 3 + * // [ "B { foo: 'bar', bar: 'qux' }", 'A {}', "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * ``` + * @param ctor The constructor that can be used to search on the prototype chain in order to filter target objects in the heap. + * @since v20.13.0 + * @experimental + */ + function queryObjects(ctor: Function): number | string[]; + function queryObjects(ctor: Function, options: { format: "count" }): number; + function queryObjects(ctor: Function, options: { format: "summary" }): string[]; + /** + * Generates a snapshot of the current V8 heap and returns a Readable + * Stream that may be used to read the JSON serialized representation. + * This JSON stream format is intended to be used with tools such as + * Chrome DevTools. The JSON schema is undocumented and specific to the + * V8 engine. Therefore, the schema may change from one version of V8 to the next. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * // Print heap snapshot to the console + * import v8 from 'node:v8'; + * const stream = v8.getHeapSnapshot(); + * stream.pipe(process.stdout); + * ``` + * @since v11.13.0 + * @return A Readable containing the V8 heap snapshot. + */ + function getHeapSnapshot(options?: HeapSnapshotOptions): Readable; + /** + * Generates a snapshot of the current V8 heap and writes it to a JSON + * file. This file is intended to be used with tools such as Chrome + * DevTools. The JSON schema is undocumented and specific to the V8 + * engine, and may change from one version of V8 to the next. + * + * A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will + * not contain any information about the workers, and vice versa. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * import { writeHeapSnapshot } from 'node:v8'; + * import { + * Worker, + * isMainThread, + * parentPort, + * } from 'node:worker_threads'; + * + * if (isMainThread) { + * const worker = new Worker(__filename); + * + * worker.once('message', (filename) => { + * console.log(`worker heapdump: ${filename}`); + * // Now get a heapdump for the main thread. + * console.log(`main thread heapdump: ${writeHeapSnapshot()}`); + * }); + * + * // Tell the worker to create a heapdump. + * worker.postMessage('heapdump'); + * } else { + * parentPort.once('message', (message) => { + * if (message === 'heapdump') { + * // Generate a heapdump for the worker + * // and return the filename to the parent. + * parentPort.postMessage(writeHeapSnapshot()); + * } + * }); + * } + * ``` + * @since v11.13.0 + * @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be + * generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a + * worker thread. + * @return The filename where the snapshot was saved. + */ + function writeHeapSnapshot(filename?: string, options?: HeapSnapshotOptions): string; + /** + * Get statistics about code and its metadata in the heap, see + * V8 [`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the + * following properties: + * + * ```js + * { + * code_and_metadata_size: 212208, + * bytecode_and_metadata_size: 161368, + * external_script_source_size: 1410794, + * cpu_profiler_metadata_size: 0, + * } + * ``` + * @since v12.8.0 + */ + function getHeapCodeStatistics(): HeapCodeStatistics; + /** + * V8 only supports `Latin-1/ISO-8859-1` and `UTF16` as the underlying representation of a string. + * If the `content` uses `Latin-1/ISO-8859-1` as the underlying representation, this function will return true; + * otherwise, it returns false. + * + * If this method returns false, that does not mean that the string contains some characters not in `Latin-1/ISO-8859-1`. + * Sometimes a `Latin-1` string may also be represented as `UTF16`. + * + * ```js + * const { isStringOneByteRepresentation } = require('node:v8'); + * + * const Encoding = { + * latin1: 1, + * utf16le: 2, + * }; + * const buffer = Buffer.alloc(100); + * function writeString(input) { + * if (isStringOneByteRepresentation(input)) { + * buffer.writeUint8(Encoding.latin1); + * buffer.writeUint32LE(input.length, 1); + * buffer.write(input, 5, 'latin1'); + * } else { + * buffer.writeUint8(Encoding.utf16le); + * buffer.writeUint32LE(input.length * 2, 1); + * buffer.write(input, 5, 'utf16le'); + * } + * } + * writeString('hello'); + * writeString('你好'); + * ``` + * @since v23.10.0, v22.15.0 + */ + function isStringOneByteRepresentation(content: string): boolean; + /** + * @since v8.0.0 + */ + class Serializer { + /** + * Writes out a header, which includes the serialization format version. + */ + writeHeader(): void; + /** + * Serializes a JavaScript value and adds the serialized representation to the + * internal buffer. + * + * This throws an error if `value` cannot be serialized. + */ + writeValue(val: any): boolean; + /** + * Returns the stored internal buffer. This serializer should not be used once + * the buffer is released. Calling this method results in undefined behavior + * if a previous write has failed. + */ + releaseBuffer(): Buffer; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`. + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Write a raw 32-bit unsigned integer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint32(value: number): void; + /** + * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint64(hi: number, lo: number): void; + /** + * Write a JS `number` value. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeDouble(value: number): void; + /** + * Write raw bytes into the serializer's internal buffer. The deserializer + * will require a way to compute the length of the buffer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeRawBytes(buffer: NodeJS.TypedArray): void; + } + /** + * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only + * stores the part of their underlying `ArrayBuffer`s that they are referring to. + * @since v8.0.0 + */ + class DefaultSerializer extends Serializer {} + /** + * @since v8.0.0 + */ + class Deserializer { + constructor(data: NodeJS.TypedArray); + /** + * Reads and validates a header (including the format version). + * May, for example, reject an invalid or unsupported wire format. In that case, + * an `Error` is thrown. + */ + readHeader(): boolean; + /** + * Deserializes a JavaScript value from the buffer and returns it. + */ + readValue(): any; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of + * `SharedArrayBuffer`s). + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Reads the underlying wire format version. Likely mostly to be useful to + * legacy code reading old wire format versions. May not be called before `.readHeader()`. + */ + getWireFormatVersion(): number; + /** + * Read a raw 32-bit unsigned integer and return it. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint32(): number; + /** + * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]` with two 32-bit unsigned integer entries. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint64(): [number, number]; + /** + * Read a JS `number` value. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readDouble(): number; + /** + * Read raw bytes from the deserializer's internal buffer. The `length` parameter + * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readRawBytes(length: number): Buffer; + } + /** + * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`. + * @since v8.0.0 + */ + class DefaultDeserializer extends Deserializer {} + /** + * Uses a `DefaultSerializer` to serialize `value` into a buffer. + * + * `ERR_BUFFER_TOO_LARGE` will be thrown when trying to + * serialize a huge object which requires buffer + * larger than `buffer.constants.MAX_LENGTH`. + * @since v8.0.0 + */ + function serialize(value: any): Buffer; + /** + * Uses a `DefaultDeserializer` with default options to read a JS value + * from a buffer. + * @since v8.0.0 + * @param buffer A buffer returned by {@link serialize}. + */ + function deserialize(buffer: NodeJS.ArrayBufferView): any; + /** + * The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple + * times during the lifetime of the process. Each time the execution counter will + * be reset and a new coverage report will be written to the directory specified + * by `NODE_V8_COVERAGE`. + * + * When the process is about to exit, one last coverage will still be written to + * disk unless {@link stopCoverage} is invoked before the process exits. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function takeCoverage(): void; + /** + * The `v8.stopCoverage()` method allows the user to stop the coverage collection + * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count + * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function stopCoverage(): void; + /** + * The API is a no-op if `--heapsnapshot-near-heap-limit` is already set from the command line or the API is called more than once. + * `limit` must be a positive integer. See [`--heapsnapshot-near-heap-limit`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--heapsnapshot-near-heap-limitmax_count) for more information. + * @since v18.10.0, v16.18.0 + */ + function setHeapSnapshotNearHeapLimit(limit: number): void; + /** + * This API collects GC data in current thread. + * @since v19.6.0, v18.15.0 + */ + class GCProfiler { + /** + * Start collecting GC data. + * @since v19.6.0, v18.15.0 + */ + start(): void; + /** + * Stop collecting GC data and return an object. The content of object + * is as follows. + * + * ```json + * { + * "version": 1, + * "startTime": 1674059033862, + * "statistics": [ + * { + * "gcType": "Scavenge", + * "beforeGC": { + * "heapStatistics": { + * "totalHeapSize": 5005312, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5226496, + * "totalAvailableSize": 4341325216, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4883840, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * }, + * "cost": 1574.14, + * "afterGC": { + * "heapStatistics": { + * "totalHeapSize": 6053888, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5500928, + * "totalAvailableSize": 4341101384, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4059096, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * } + * } + * ], + * "endTime": 1674059036865 + * } + * ``` + * + * Here's an example. + * + * ```js + * import { GCProfiler } from 'node:v8'; + * const profiler = new GCProfiler(); + * profiler.start(); + * setTimeout(() => { + * console.log(profiler.stop()); + * }, 1000); + * ``` + * @since v19.6.0, v18.15.0 + */ + stop(): GCProfilerResult; + } + interface GCProfilerResult { + version: number; + startTime: number; + endTime: number; + statistics: Array<{ + gcType: string; + cost: number; + beforeGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + afterGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + }>; + } + interface HeapStatistics { + totalHeapSize: number; + totalHeapSizeExecutable: number; + totalPhysicalSize: number; + totalAvailableSize: number; + totalGlobalHandlesSize: number; + usedGlobalHandlesSize: number; + usedHeapSize: number; + heapSizeLimit: number; + mallocedMemory: number; + externalMemory: number; + peakMallocedMemory: number; + } + interface HeapSpaceStatistics { + spaceName: string; + spaceSize: number; + spaceUsedSize: number; + spaceAvailableSize: number; + physicalSpaceSize: number; + } + /** + * Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will + * happen if a promise is created without ever getting a continuation. + * @since v17.1.0, v16.14.0 + * @param promise The promise being created. + * @param parent The promise continued from, if applicable. + */ + interface Init { + (promise: Promise, parent: Promise): void; + } + /** + * Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming. + * + * The before callback will be called 0 to N times. The before callback will typically be called 0 times if no continuation was ever made for the promise. + * The before callback may be called many times in the case where many continuations have been made from the same promise. + * @since v17.1.0, v16.14.0 + */ + interface Before { + (promise: Promise): void; + } + /** + * Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await. + * @since v17.1.0, v16.14.0 + */ + interface After { + (promise: Promise): void; + } + /** + * Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of {@link Promise.resolve()} or + * {@link Promise.reject()}. + * @since v17.1.0, v16.14.0 + */ + interface Settled { + (promise: Promise): void; + } + /** + * Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or + * around an await, and when the promise resolves or rejects. + * + * Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and + * `settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop. + * @since v17.1.0, v16.14.0 + */ + interface HookCallbacks { + init?: Init; + before?: Before; + after?: After; + settled?: Settled; + } + interface PromiseHooks { + /** + * The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param init The {@link Init | `init` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onInit: (init: Init) => Function; + /** + * The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param settled The {@link Settled | `settled` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onSettled: (settled: Settled) => Function; + /** + * The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param before The {@link Before | `before` callback} to call before a promise continuation executes. + * @return Call to stop the hook. + */ + onBefore: (before: Before) => Function; + /** + * The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param after The {@link After | `after` callback} to call after a promise continuation executes. + * @return Call to stop the hook. + */ + onAfter: (after: After) => Function; + /** + * Registers functions to be called for different lifetime events of each promise. + * The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime. + * All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed. + * The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param callbacks The {@link HookCallbacks | Hook Callbacks} to register + * @return Used for disabling hooks + */ + createHook: (callbacks: HookCallbacks) => Function; + } + /** + * The `promiseHooks` interface can be used to track promise lifecycle events. + * @since v17.1.0, v16.14.0 + */ + const promiseHooks: PromiseHooks; + type StartupSnapshotCallbackFn = (args: any) => any; + /** + * The `v8.startupSnapshot` interface can be used to add serialization and deserialization hooks for custom startup snapshots. + * + * ```bash + * $ node --snapshot-blob snapshot.blob --build-snapshot entry.js + * # This launches a process with the snapshot + * $ node --snapshot-blob snapshot.blob + * ``` + * + * In the example above, `entry.js` can use methods from the `v8.startupSnapshot` interface to specify how to save information for custom objects + * in the snapshot during serialization and how the information can be used to synchronize these objects during deserialization of the snapshot. + * For example, if the `entry.js` contains the following script: + * + * ```js + * 'use strict'; + * + * import fs from 'node:fs'; + * import zlib from 'node:zlib'; + * import path from 'node:path'; + * import assert from 'node:assert'; + * + * import v8 from 'node:v8'; + * + * class BookShelf { + * storage = new Map(); + * + * // Reading a series of files from directory and store them into storage. + * constructor(directory, books) { + * for (const book of books) { + * this.storage.set(book, fs.readFileSync(path.join(directory, book))); + * } + * } + * + * static compressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gzipSync(content)); + * } + * } + * + * static decompressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gunzipSync(content)); + * } + * } + * } + * + * // __dirname here is where the snapshot script is placed + * // during snapshot building time. + * const shelf = new BookShelf(__dirname, [ + * 'book1.en_US.txt', + * 'book1.es_ES.txt', + * 'book2.zh_CN.txt', + * ]); + * + * assert(v8.startupSnapshot.isBuildingSnapshot()); + * // On snapshot serialization, compress the books to reduce size. + * v8.startupSnapshot.addSerializeCallback(BookShelf.compressAll, shelf); + * // On snapshot deserialization, decompress the books. + * v8.startupSnapshot.addDeserializeCallback(BookShelf.decompressAll, shelf); + * v8.startupSnapshot.setDeserializeMainFunction((shelf) => { + * // process.env and process.argv are refreshed during snapshot + * // deserialization. + * const lang = process.env.BOOK_LANG || 'en_US'; + * const book = process.argv[1]; + * const name = `${book}.${lang}.txt`; + * console.log(shelf.storage.get(name)); + * }, shelf); + * ``` + * + * The resulted binary will get print the data deserialized from the snapshot during start up, using the refreshed `process.env` and `process.argv` of the launched process: + * + * ```bash + * $ BOOK_LANG=es_ES node --snapshot-blob snapshot.blob book1 + * # Prints content of book1.es_ES.txt deserialized from the snapshot. + * ``` + * + * Currently the application deserialized from a user-land snapshot cannot be snapshotted again, so these APIs are only available to applications that are not deserialized from a user-land snapshot. + * + * @since v18.6.0, v16.17.0 + */ + namespace startupSnapshot { + /** + * Add a callback that will be called when the Node.js instance is about to get serialized into a snapshot and exit. + * This can be used to release resources that should not or cannot be serialized or to convert user data into a form more suitable for serialization. + * @since v18.6.0, v16.17.0 + */ + function addSerializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Add a callback that will be called when the Node.js instance is deserialized from a snapshot. + * The `callback` and the `data` (if provided) will be serialized into the snapshot, they can be used to re-initialize the state of the application or + * to re-acquire resources that the application needs when the application is restarted from the snapshot. + * @since v18.6.0, v16.17.0 + */ + function addDeserializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * This sets the entry point of the Node.js application when it is deserialized from a snapshot. This can be called only once in the snapshot building script. + * If called, the deserialized application no longer needs an additional entry point script to start up and will simply invoke the callback along with the deserialized + * data (if provided), otherwise an entry point script still needs to be provided to the deserialized application. + * @since v18.6.0, v16.17.0 + */ + function setDeserializeMainFunction(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Returns true if the Node.js instance is run to build a snapshot. + * @since v18.6.0, v16.17.0 + */ + function isBuildingSnapshot(): boolean; + } +} +declare module "node:v8" { + export * from "v8"; +} diff --git a/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/vm.d.ts b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/vm.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bba2e0ba49cc7c8f17bf6a4ef692dacc4fe5ff9d --- /dev/null +++ b/platform/aiml/elizabeth/e-1-first_session/claude-code-router/node_modules/@types/node/vm.d.ts @@ -0,0 +1,1036 @@ +/** + * The `node:vm` module enables compiling and running code within V8 Virtual + * Machine contexts. + * + * **The `node:vm` module is not a security** + * **mechanism. Do not use it to run untrusted code.** + * + * JavaScript code can be compiled and run immediately or + * compiled, saved, and run later. + * + * A common use case is to run the code in a different V8 Context. This means + * invoked code has a different global object than the invoking code. + * + * One can provide the context by `contextifying` an + * object. The invoked code treats any property in the context like a + * global variable. Any changes to global variables caused by the invoked + * code are reflected in the context object. + * + * ```js + * import vm from 'node:vm'; + * + * const x = 1; + * + * const context = { x: 2 }; + * vm.createContext(context); // Contextify the object. + * + * const code = 'x += 40; var y = 17;'; + * // `x` and `y` are global variables in the context. + * // Initially, x has the value 2 because that is the value of context.x. + * vm.runInContext(code, context); + * + * console.log(context.x); // 42 + * console.log(context.y); // 17 + * + * console.log(x); // 1; y is not defined. + * ``` + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/vm.js) + */ +declare module "vm" { + import { ImportAttributes } from "node:module"; + interface Context extends NodeJS.Dict {} + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * @default '' + */ + filename?: string | undefined; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + lineOffset?: number | undefined; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + columnOffset?: number | undefined; + } + type DynamicModuleLoader = ( + specifier: string, + referrer: T, + importAttributes: ImportAttributes, + phase: "source" | "evaluation", + ) => Module | Promise; + interface ScriptOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer | NodeJS.ArrayBufferView | undefined; + /** @deprecated in favor of `script.createCachedData()` */ + produceCachedData?: boolean | undefined; + /** + * Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is + * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see + * [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v24.x/api/vm.html#support-of-dynamic-import-in-compilation-apis). + * @experimental + */ + importModuleDynamically?: + | DynamicModuleLoader